javascript-solid-server 0.0.11 → 0.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Identity Provider Fastify Plugin
3
+ * Mounts oidc-provider and interaction routes
4
+ */
5
+
6
+ import middie from '@fastify/middie';
7
+ import { createProvider } from './provider.js';
8
+ import { initializeKeys, getPublicJwks } from './keys.js';
9
+ import {
10
+ handleInteractionGet,
11
+ handleLogin,
12
+ handleConsent,
13
+ handleAbort,
14
+ } from './interactions.js';
15
+ import {
16
+ handleCredentials,
17
+ handleCredentialsInfo,
18
+ } from './credentials.js';
19
+
20
+ /**
21
+ * IdP Fastify Plugin
22
+ * @param {FastifyInstance} fastify
23
+ * @param {object} options
24
+ * @param {string} options.issuer - The issuer URL
25
+ */
26
+ export async function idpPlugin(fastify, options) {
27
+ const { issuer } = options;
28
+
29
+ if (!issuer) {
30
+ throw new Error('IdP requires issuer URL');
31
+ }
32
+
33
+ // Initialize signing keys
34
+ await initializeKeys();
35
+
36
+ // Create the OIDC provider
37
+ const provider = await createProvider(issuer);
38
+
39
+ // Store provider reference on fastify for handlers
40
+ fastify.decorate('oidcProvider', provider);
41
+
42
+ // Register middleware support for oidc-provider (Koa app)
43
+ await fastify.register(middie, {
44
+ hook: 'preHandler',
45
+ });
46
+
47
+ // Mount oidc-provider on /idp path
48
+ // oidc-provider is a Koa app, middie handles the bridge
49
+ fastify.use('/idp', (req, res, next) => {
50
+ // Skip our custom routes (handled by Fastify)
51
+ if (req.url.startsWith('/interaction/') || req.url.startsWith('/credentials')) {
52
+ return next();
53
+ }
54
+ // Let oidc-provider handle everything else
55
+ provider.callback()(req, res);
56
+ });
57
+
58
+ // /.well-known/openid-configuration
59
+ fastify.get('/.well-known/openid-configuration', async (request, reply) => {
60
+ // Build discovery document
61
+ const config = {
62
+ issuer,
63
+ authorization_endpoint: `${issuer}/idp/auth`,
64
+ token_endpoint: `${issuer}/idp/token`,
65
+ userinfo_endpoint: `${issuer}/idp/me`,
66
+ jwks_uri: `${issuer}/.well-known/jwks.json`,
67
+ registration_endpoint: `${issuer}/idp/reg`,
68
+ introspection_endpoint: `${issuer}/idp/token/introspection`,
69
+ revocation_endpoint: `${issuer}/idp/token/revocation`,
70
+ end_session_endpoint: `${issuer}/idp/session/end`,
71
+ scopes_supported: ['openid', 'webid', 'profile', 'email', 'offline_access'],
72
+ response_types_supported: ['code'],
73
+ response_modes_supported: ['query', 'fragment', 'form_post'],
74
+ grant_types_supported: ['authorization_code', 'refresh_token', 'client_credentials'],
75
+ subject_types_supported: ['public'],
76
+ id_token_signing_alg_values_supported: ['ES256'],
77
+ token_endpoint_auth_methods_supported: ['none', 'client_secret_basic', 'client_secret_post'],
78
+ claims_supported: ['sub', 'webid', 'name', 'email', 'email_verified'],
79
+ code_challenge_methods_supported: ['S256'],
80
+ dpop_signing_alg_values_supported: ['ES256', 'RS256'],
81
+ // Solid-OIDC specific
82
+ solid_oidc_supported: 'https://solidproject.org/TR/solid-oidc',
83
+ };
84
+
85
+ reply.header('Cache-Control', 'public, max-age=3600');
86
+ return config;
87
+ });
88
+
89
+ // /.well-known/jwks.json
90
+ fastify.get('/.well-known/jwks.json', async (request, reply) => {
91
+ const jwks = await getPublicJwks();
92
+ reply.header('Cache-Control', 'public, max-age=3600');
93
+ return jwks;
94
+ });
95
+
96
+ // Programmatic credentials endpoint for CTH compatibility
97
+ // Allows obtaining tokens via email/password without browser interaction
98
+
99
+ // GET credentials info
100
+ fastify.get('/idp/credentials', async (request, reply) => {
101
+ return handleCredentialsInfo(request, reply, issuer);
102
+ });
103
+
104
+ // POST credentials - obtain tokens
105
+ fastify.post('/idp/credentials', async (request, reply) => {
106
+ return handleCredentials(request, reply, issuer);
107
+ });
108
+
109
+ // Interaction routes (our custom login/consent UI)
110
+ // These bypass oidc-provider and use our handlers
111
+
112
+ // GET interaction - show login or consent page
113
+ fastify.get('/idp/interaction/:uid', async (request, reply) => {
114
+ return handleInteractionGet(request, reply, provider);
115
+ });
116
+
117
+ // POST login
118
+ fastify.post('/idp/interaction/:uid/login', async (request, reply) => {
119
+ return handleLogin(request, reply, provider);
120
+ });
121
+
122
+ // POST consent
123
+ fastify.post('/idp/interaction/:uid/confirm', async (request, reply) => {
124
+ return handleConsent(request, reply, provider);
125
+ });
126
+
127
+ // POST abort
128
+ fastify.post('/idp/interaction/:uid/abort', async (request, reply) => {
129
+ return handleAbort(request, reply, provider);
130
+ });
131
+
132
+ fastify.log.info(`IdP initialized with issuer: ${issuer}`);
133
+ }
134
+
135
+ export default idpPlugin;
@@ -0,0 +1,180 @@
1
+ /**
2
+ * Interaction handlers for login and consent flows
3
+ * Handles the user-facing parts of the authentication flow
4
+ */
5
+
6
+ import { authenticate, findById } from './accounts.js';
7
+ import { loginPage, consentPage, errorPage } from './views.js';
8
+
9
+ /**
10
+ * Handle GET /idp/interaction/:uid
11
+ * Shows login or consent page based on interaction state
12
+ */
13
+ export async function handleInteractionGet(request, reply, provider) {
14
+ const { uid } = request.params;
15
+
16
+ try {
17
+ const interaction = await provider.Interaction.find(uid);
18
+ if (!interaction) {
19
+ return reply.code(404).type('text/html').send(errorPage('Interaction not found', 'This login session has expired. Please try again.'));
20
+ }
21
+
22
+ const { prompt, params, session } = interaction;
23
+
24
+ // If we need login
25
+ if (prompt.name === 'login') {
26
+ return reply.type('text/html').send(loginPage(uid, params.client_id, interaction.lastError));
27
+ }
28
+
29
+ // If we need consent
30
+ if (prompt.name === 'consent') {
31
+ const client = await provider.Client.find(params.client_id);
32
+ const account = session?.accountId ? await findById(session.accountId) : null;
33
+
34
+ return reply.type('text/html').send(consentPage(uid, client, params, account));
35
+ }
36
+
37
+ // Unknown prompt
38
+ return reply.code(400).type('text/html').send(errorPage('Unknown prompt', `Unexpected prompt: ${prompt.name}`));
39
+ } catch (err) {
40
+ request.log.error(err, 'Interaction error');
41
+ return reply.code(500).type('text/html').send(errorPage('Server Error', err.message));
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Handle POST /idp/interaction/:uid/login
47
+ * Processes login form submission
48
+ */
49
+ export async function handleLogin(request, reply, provider) {
50
+ const { uid } = request.params;
51
+ const { email, password } = request.body || {};
52
+
53
+ try {
54
+ const interaction = await provider.Interaction.find(uid);
55
+ if (!interaction) {
56
+ return reply.code(404).type('text/html').send(errorPage('Session expired', 'Please try logging in again.'));
57
+ }
58
+
59
+ // Validate input
60
+ if (!email || !password) {
61
+ interaction.lastError = 'Email and password are required';
62
+ await interaction.save(interaction.exp - Math.floor(Date.now() / 1000));
63
+ return reply.redirect(`/idp/interaction/${uid}`);
64
+ }
65
+
66
+ // Authenticate
67
+ const account = await authenticate(email, password);
68
+ if (!account) {
69
+ interaction.lastError = 'Invalid email or password';
70
+ await interaction.save(interaction.exp - Math.floor(Date.now() / 1000));
71
+ return reply.redirect(`/idp/interaction/${uid}`);
72
+ }
73
+
74
+ // Login successful - complete the interaction
75
+ const result = {
76
+ login: {
77
+ accountId: account.id,
78
+ remember: true,
79
+ },
80
+ };
81
+
82
+ const redirectTo = await provider.interactionResult(
83
+ request.raw,
84
+ reply.raw,
85
+ result,
86
+ { mergeWithLastSubmission: false }
87
+ );
88
+
89
+ return reply.redirect(redirectTo);
90
+ } catch (err) {
91
+ request.log.error(err, 'Login error');
92
+ return reply.code(500).type('text/html').send(errorPage('Login failed', err.message));
93
+ }
94
+ }
95
+
96
+ /**
97
+ * Handle POST /idp/interaction/:uid/confirm
98
+ * Processes consent confirmation
99
+ */
100
+ export async function handleConsent(request, reply, provider) {
101
+ const { uid } = request.params;
102
+
103
+ try {
104
+ const interaction = await provider.Interaction.find(uid);
105
+ if (!interaction) {
106
+ return reply.code(404).type('text/html').send(errorPage('Session expired', 'Please try again.'));
107
+ }
108
+
109
+ const { prompt, params, session } = interaction;
110
+ if (prompt.name !== 'consent') {
111
+ return reply.code(400).type('text/html').send(errorPage('Invalid state', 'Not in consent stage.'));
112
+ }
113
+
114
+ // Grant consent
115
+ const grant = new provider.Grant({
116
+ accountId: session.accountId,
117
+ clientId: params.client_id,
118
+ });
119
+
120
+ // Grant requested scopes
121
+ if (params.scope) {
122
+ grant.addOIDCScope(params.scope);
123
+ }
124
+
125
+ // Grant resource-specific scopes if present
126
+ if (params.resource) {
127
+ const resources = Array.isArray(params.resource) ? params.resource : [params.resource];
128
+ for (const resource of resources) {
129
+ grant.addResourceScope(resource, params.scope);
130
+ }
131
+ }
132
+
133
+ const grantId = await grant.save();
134
+
135
+ const result = {
136
+ consent: {
137
+ grantId,
138
+ },
139
+ };
140
+
141
+ const redirectTo = await provider.interactionResult(
142
+ request.raw,
143
+ reply.raw,
144
+ result,
145
+ { mergeWithLastSubmission: true }
146
+ );
147
+
148
+ return reply.redirect(redirectTo);
149
+ } catch (err) {
150
+ request.log.error(err, 'Consent error');
151
+ return reply.code(500).type('text/html').send(errorPage('Consent failed', err.message));
152
+ }
153
+ }
154
+
155
+ /**
156
+ * Handle POST /idp/interaction/:uid/abort
157
+ * User cancelled the flow
158
+ */
159
+ export async function handleAbort(request, reply, provider) {
160
+ const { uid } = request.params;
161
+
162
+ try {
163
+ const result = {
164
+ error: 'access_denied',
165
+ error_description: 'User cancelled the authorization request',
166
+ };
167
+
168
+ const redirectTo = await provider.interactionResult(
169
+ request.raw,
170
+ reply.raw,
171
+ result,
172
+ { mergeWithLastSubmission: false }
173
+ );
174
+
175
+ return reply.redirect(redirectTo);
176
+ } catch (err) {
177
+ request.log.error(err, 'Abort error');
178
+ return reply.code(500).type('text/html').send(errorPage('Error', err.message));
179
+ }
180
+ }
@@ -0,0 +1,157 @@
1
+ /**
2
+ * JWKS key management for the Identity Provider
3
+ * Generates and stores signing keys for tokens
4
+ */
5
+
6
+ import * as jose from 'jose';
7
+ import fs from 'fs-extra';
8
+ import path from 'path';
9
+ import crypto from 'crypto';
10
+
11
+ /**
12
+ * Get keys directory (dynamic to support changing DATA_ROOT)
13
+ */
14
+ function getKeysDir() {
15
+ const dataRoot = process.env.DATA_ROOT || './data';
16
+ return path.join(dataRoot, '.idp', 'keys');
17
+ }
18
+
19
+ function getJwksPath() {
20
+ return path.join(getKeysDir(), 'jwks.json');
21
+ }
22
+
23
+ /**
24
+ * Generate a new EC P-256 key pair for signing
25
+ * @returns {Promise<object>} - JWK key pair with private key
26
+ */
27
+ async function generateSigningKey() {
28
+ const { publicKey, privateKey } = await jose.generateKeyPair('ES256', {
29
+ extractable: true,
30
+ });
31
+
32
+ const privateJwk = await jose.exportJWK(privateKey);
33
+ const publicJwk = await jose.exportJWK(publicKey);
34
+
35
+ // Add metadata
36
+ const kid = crypto.randomUUID();
37
+ const now = Math.floor(Date.now() / 1000);
38
+
39
+ return {
40
+ ...privateJwk,
41
+ kid,
42
+ use: 'sig',
43
+ alg: 'ES256',
44
+ iat: now,
45
+ };
46
+ }
47
+
48
+ /**
49
+ * Generate cookie signing keys
50
+ * @returns {string[]} - Array of random secret strings
51
+ */
52
+ function generateCookieKeys() {
53
+ return [
54
+ crypto.randomBytes(32).toString('base64url'),
55
+ crypto.randomBytes(32).toString('base64url'),
56
+ ];
57
+ }
58
+
59
+ /**
60
+ * Initialize JWKS - generate keys if they don't exist
61
+ * @returns {Promise<object>} - { jwks, cookieKeys }
62
+ */
63
+ export async function initializeKeys() {
64
+ await fs.ensureDir(getKeysDir());
65
+
66
+ try {
67
+ // Try to load existing keys
68
+ const data = await fs.readJson(getJwksPath());
69
+ return data;
70
+ } catch (err) {
71
+ if (err.code !== 'ENOENT') throw err;
72
+
73
+ // Generate new keys
74
+ console.log('Generating new IdP signing keys...');
75
+ const signingKey = await generateSigningKey();
76
+ const cookieKeys = generateCookieKeys();
77
+
78
+ const data = {
79
+ jwks: {
80
+ keys: [signingKey],
81
+ },
82
+ cookieKeys,
83
+ createdAt: new Date().toISOString(),
84
+ };
85
+
86
+ await fs.writeJson(getJwksPath(), data, { spaces: 2 });
87
+ console.log('IdP signing keys generated and saved.');
88
+
89
+ return data;
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Get the JWKS (public keys only) for /.well-known/jwks.json
95
+ * @returns {Promise<object>} - JWKS with public keys only
96
+ */
97
+ export async function getPublicJwks() {
98
+ const { jwks } = await initializeKeys();
99
+
100
+ // Return only public key components
101
+ const publicKeys = jwks.keys.map((key) => {
102
+ // For EC keys, remove 'd' (private key component)
103
+ const { d, ...publicKey } = key;
104
+ return publicKey;
105
+ });
106
+
107
+ return { keys: publicKeys };
108
+ }
109
+
110
+ /**
111
+ * Get the full JWKS (including private keys) for oidc-provider
112
+ * @returns {Promise<object>} - Full JWKS
113
+ */
114
+ export async function getJwks() {
115
+ const { jwks } = await initializeKeys();
116
+ return jwks;
117
+ }
118
+
119
+ /**
120
+ * Get cookie signing keys
121
+ * @returns {Promise<string[]>} - Cookie keys
122
+ */
123
+ export async function getCookieKeys() {
124
+ const { cookieKeys } = await initializeKeys();
125
+ return cookieKeys;
126
+ }
127
+
128
+ /**
129
+ * Rotate signing keys (add new key, keep old for verification)
130
+ * @returns {Promise<void>}
131
+ */
132
+ export async function rotateKeys() {
133
+ const data = await fs.readJson(getJwksPath());
134
+
135
+ // Mark old keys
136
+ data.jwks.keys.forEach((key) => {
137
+ if (!key.rotatedAt) {
138
+ key.rotatedAt = new Date().toISOString();
139
+ }
140
+ });
141
+
142
+ // Generate new signing key
143
+ const newKey = await generateSigningKey();
144
+ data.jwks.keys.unshift(newKey); // New key first (primary)
145
+
146
+ // Keep only last 3 keys for verification
147
+ if (data.jwks.keys.length > 3) {
148
+ data.jwks.keys = data.jwks.keys.slice(0, 3);
149
+ }
150
+
151
+ // Rotate cookie keys too
152
+ data.cookieKeys = generateCookieKeys();
153
+ data.rotatedAt = new Date().toISOString();
154
+
155
+ await fs.writeJson(getJwksPath(), data, { spaces: 2 });
156
+ console.log('IdP keys rotated.');
157
+ }