UNPKG

canvas-lti

Version:

A Canvas LTI 1.3 integration tool.

77 lines (67 loc) 2.69 kB
const jose = require('node-jose'); const fs = require('fs'); require('dotenv').config(); const PRIVATE_KEY_PATH = 'private.key'; const PUBLIC_KEY_PATH = 'public.key'; const PUBLIC_JWK_PATH = 'public.jwk'; let keystore = jose.JWK.createKeyStore(); async function initializeKeyStore() { try { // Check if keys already exist if (!fs.existsSync(PRIVATE_KEY_PATH) || !fs.existsSync(PUBLIC_KEY_PATH)) { // Generate new key pair with properties const props = { alg: 'RS256', use: 'sig', kid: 'M9db5159sdPyfFMO-YXDYH_PCmgvcLvwCmumuQqEe7M' // You should generate a unique key ID }; const keyPair = await keystore.generate('RSA', 2048, props); // Save private key const privatePem = await keyPair.toPEM(true); fs.writeFileSync(PRIVATE_KEY_PATH, privatePem); // Save public key const publicPem = await keyPair.toPEM(); fs.writeFileSync(PUBLIC_KEY_PATH, publicPem); // Save public JWK with 'alg' and 'use' included const publicJwk = keyPair.toJSON(); // Manually add 'alg' and 'use' to the JWK publicJwk.alg = props.alg ? props.alg : 'RS256'; publicJwk.use = props.use ? props.use : 'sig'; fs.writeFileSync(PUBLIC_JWK_PATH, JSON.stringify(publicJwk, null, 2)); } else { // Load existing private key const privatePem = fs.readFileSync(PRIVATE_KEY_PATH, 'utf8'); await keystore.add(privatePem, 'pem'); } } catch (error) { console.error('Error initializing key store:', error); throw error; } } async function getJwks() { try { if (keystore.all().length === 0) { await initializeKeyStore(); } // Map each key to its JSON representation, ensuring 'alg' and 'use' are included return { keys: keystore.all().map(key => { let keyJson = key.toJSON(); // Explicitly add 'alg' and 'use' fields from the key properties if not present if (!keyJson.alg) { keyJson.alg = 'RS256'; } if (!keyJson.use) { keyJson.use = 'sig'; } return keyJson; }) }; } catch (error) { console.error('Error getting JWKS:', error); throw error; } } // Initialize keys when the module loads initializeKeyStore().catch(console.error); module.exports = { getJwks };