UNPKG

@civic/mcp-bridge-commander

Version:

Stdio <-> HTTP/SSE MCP bridge with Civic auth handling

44 lines 2.16 kB
/** * encryption.ts * * Utilities for encrypting and decrypting sensitive data like tokens * when passing them between services. */ import * as jose from 'jose'; /** * Encrypts a token using JOSE JWE format (which handles hybrid encryption internally) * This handles tokens of any size by using RSA to encrypt a symmetric key * and using that symmetric key to encrypt the actual token. * * @param token The token to encrypt * @returns Compact JWE format encrypted token */ export async function encryptToken(token) { try { // Get public key from environment const publicKeyString = process.env.TOKEN_ENCRYPTION_PUBLIC_KEY || '-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsu+oMpl/yT5oiqLMvfuQ\ne43S8S0eu59Qbax4M7DfWjimw3gVmK5KcR7TB4v4vlZsvF91vCT6ArYs8Ke9gGsB\nDNgVS20WE6GB5biEUIiYDKlremBGlYxzHoVIrOvTH7WS8KpogpNJpqFV735aTVoy\nHOetl4Ap6tXkznLeBllirMpntJS3vVUW/+L5YGiY7aSuRwfoXphLItfamWos3/Ff\nz33FjrQY6bb6g+vdTtq8JLkiOXKynEcaGYXGibnkDc5C+jKx2JS63TOpp1LbvEmh\njEXpaee94YTs99H3LdqsporedAwEXKFrmX76eXrlIYei+ZUubrCToFkCXRzjwGMU\n9wIDAQAB\n-----END PUBLIC KEY-----\n'; if (!publicKeyString) { throw new Error('No public key found in environment'); } // Format key correctly (replace \n with actual newlines) const formattedKey = publicKeyString.replace(/\\n/g, '\n'); // Import the public key const publicKey = await jose.importSPKI(formattedKey, 'RSA-OAEP-256'); // Encode the token as Uint8Array (required by JOSE) const tokenBytes = new TextEncoder().encode(token); // Encrypt using JOSE's JWE format, which handles the hybrid encryption process const jwe = await new jose.CompactEncrypt(tokenBytes) .setProtectedHeader({ alg: 'RSA-OAEP-256', // Key encryption algorithm enc: 'A256GCM' // Content encryption algorithm }) .encrypt(publicKey); return jwe; } catch (error) { console.error('Error encrypting token:', error); throw new Error('Failed to encrypt token'); } } //# sourceMappingURL=encryption.js.map