javascript-solid-server 0.0.11 → 0.0.12

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,204 @@
1
+ /**
2
+ * Filesystem adapter for oidc-provider
3
+ * Stores OIDC data (tokens, sessions, clients, etc.) as JSON files
4
+ */
5
+
6
+ import fs from 'fs-extra';
7
+ import path from 'path';
8
+
9
+ /**
10
+ * Get IDP root directory (dynamic to support changing DATA_ROOT)
11
+ */
12
+ function getIdpRoot() {
13
+ const dataRoot = process.env.DATA_ROOT || './data';
14
+ return path.join(dataRoot, '.idp');
15
+ }
16
+
17
+ /**
18
+ * Convert model name to directory name
19
+ * e.g., 'AccessToken' -> 'access_token'
20
+ */
21
+ function modelToDir(model) {
22
+ return model.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase();
23
+ }
24
+
25
+ /**
26
+ * Filesystem adapter for oidc-provider
27
+ * Implements the adapter interface required by oidc-provider
28
+ */
29
+ class FilesystemAdapter {
30
+ constructor(model) {
31
+ this.model = model;
32
+ }
33
+
34
+ /**
35
+ * Get directory for this model (computed dynamically)
36
+ */
37
+ get dir() {
38
+ return path.join(getIdpRoot(), modelToDir(this.model));
39
+ }
40
+
41
+ /**
42
+ * Get file path for an ID
43
+ */
44
+ _path(id) {
45
+ // Sanitize ID to prevent path traversal
46
+ const safeId = id.replace(/[^a-zA-Z0-9_-]/g, '_');
47
+ return path.join(this.dir, `${safeId}.json`);
48
+ }
49
+
50
+ /**
51
+ * Create or update a stored item
52
+ * @param {string} id - Unique identifier
53
+ * @param {object} payload - Data to store
54
+ * @param {number} expiresIn - TTL in seconds
55
+ */
56
+ async upsert(id, payload, expiresIn) {
57
+ await fs.ensureDir(this.dir);
58
+
59
+ const data = {
60
+ ...payload,
61
+ _id: id,
62
+ };
63
+
64
+ // Set expiration if provided
65
+ if (expiresIn) {
66
+ data._expiresAt = Date.now() + (expiresIn * 1000);
67
+ }
68
+
69
+ await fs.writeJson(this._path(id), data, { spaces: 2 });
70
+ }
71
+
72
+ /**
73
+ * Find an item by ID
74
+ * @param {string} id - Unique identifier
75
+ * @returns {object|undefined} - The payload or undefined if not found/expired
76
+ */
77
+ async find(id) {
78
+ try {
79
+ const data = await fs.readJson(this._path(id));
80
+
81
+ // Check if expired
82
+ if (data._expiresAt && data._expiresAt < Date.now()) {
83
+ await this.destroy(id);
84
+ return undefined;
85
+ }
86
+
87
+ return data;
88
+ } catch (err) {
89
+ if (err.code === 'ENOENT') {
90
+ return undefined;
91
+ }
92
+ throw err;
93
+ }
94
+ }
95
+
96
+ /**
97
+ * Find by user code (for device flow)
98
+ * @param {string} userCode - Device flow user code
99
+ */
100
+ async findByUserCode(userCode) {
101
+ try {
102
+ const files = await fs.readdir(this.dir);
103
+ for (const file of files) {
104
+ if (file.startsWith('_')) continue; // Skip index files
105
+ const data = await fs.readJson(path.join(this.dir, file));
106
+ if (data.userCode === userCode) {
107
+ // Check expiry
108
+ if (data._expiresAt && data._expiresAt < Date.now()) {
109
+ await this.destroy(data._id);
110
+ continue;
111
+ }
112
+ return data;
113
+ }
114
+ }
115
+ } catch (err) {
116
+ if (err.code !== 'ENOENT') throw err;
117
+ }
118
+ return undefined;
119
+ }
120
+
121
+ /**
122
+ * Find by UID (for sessions/interactions)
123
+ * @param {string} uid - Session/interaction UID
124
+ */
125
+ async findByUid(uid) {
126
+ try {
127
+ const files = await fs.readdir(this.dir);
128
+ for (const file of files) {
129
+ if (file.startsWith('_')) continue; // Skip index files
130
+ const data = await fs.readJson(path.join(this.dir, file));
131
+ if (data.uid === uid) {
132
+ // Check expiry
133
+ if (data._expiresAt && data._expiresAt < Date.now()) {
134
+ await this.destroy(data._id);
135
+ continue;
136
+ }
137
+ return data;
138
+ }
139
+ }
140
+ } catch (err) {
141
+ if (err.code !== 'ENOENT') throw err;
142
+ }
143
+ return undefined;
144
+ }
145
+
146
+ /**
147
+ * Delete an item
148
+ * @param {string} id - Unique identifier
149
+ */
150
+ async destroy(id) {
151
+ try {
152
+ await fs.remove(this._path(id));
153
+ } catch (err) {
154
+ if (err.code !== 'ENOENT') throw err;
155
+ }
156
+ }
157
+
158
+ /**
159
+ * Mark a token as consumed (one-time use)
160
+ * @param {string} id - Token identifier
161
+ */
162
+ async consume(id) {
163
+ const data = await this.find(id);
164
+ if (data) {
165
+ data.consumed = Date.now() / 1000; // oidc-provider expects seconds
166
+ await this.upsert(id, data);
167
+ }
168
+ }
169
+
170
+ /**
171
+ * Revoke all tokens for a grant
172
+ * Used when user revokes consent or logs out
173
+ * @param {string} grantId - Grant identifier
174
+ */
175
+ async revokeByGrantId(grantId) {
176
+ try {
177
+ const files = await fs.readdir(this.dir);
178
+ for (const file of files) {
179
+ if (file.startsWith('_')) continue; // Skip index files
180
+ try {
181
+ const data = await fs.readJson(path.join(this.dir, file));
182
+ if (data.grantId === grantId) {
183
+ await fs.remove(path.join(this.dir, file));
184
+ }
185
+ } catch (err) {
186
+ // Skip files that can't be read
187
+ }
188
+ }
189
+ } catch (err) {
190
+ if (err.code !== 'ENOENT') throw err;
191
+ }
192
+ }
193
+ }
194
+
195
+ /**
196
+ * Adapter factory for oidc-provider
197
+ * @param {string} model - Model name (e.g., 'AccessToken', 'Client')
198
+ * @returns {FilesystemAdapter} - Adapter instance
199
+ */
200
+ export function createAdapter(model) {
201
+ return new FilesystemAdapter(model);
202
+ }
203
+
204
+ export default FilesystemAdapter;
@@ -0,0 +1,118 @@
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
+
16
+ /**
17
+ * IdP Fastify Plugin
18
+ * @param {FastifyInstance} fastify
19
+ * @param {object} options
20
+ * @param {string} options.issuer - The issuer URL
21
+ */
22
+ export async function idpPlugin(fastify, options) {
23
+ const { issuer } = options;
24
+
25
+ if (!issuer) {
26
+ throw new Error('IdP requires issuer URL');
27
+ }
28
+
29
+ // Initialize signing keys
30
+ await initializeKeys();
31
+
32
+ // Create the OIDC provider
33
+ const provider = await createProvider(issuer);
34
+
35
+ // Store provider reference on fastify for handlers
36
+ fastify.decorate('oidcProvider', provider);
37
+
38
+ // Register middleware support for oidc-provider (Koa app)
39
+ await fastify.register(middie, {
40
+ hook: 'preHandler',
41
+ });
42
+
43
+ // Mount oidc-provider on /idp path
44
+ // oidc-provider is a Koa app, middie handles the bridge
45
+ fastify.use('/idp', (req, res, next) => {
46
+ // Skip our custom interaction routes
47
+ if (req.url.startsWith('/interaction/')) {
48
+ return next();
49
+ }
50
+ // Let oidc-provider handle everything else
51
+ provider.callback()(req, res);
52
+ });
53
+
54
+ // /.well-known/openid-configuration
55
+ fastify.get('/.well-known/openid-configuration', async (request, reply) => {
56
+ // Build discovery document
57
+ const config = {
58
+ issuer,
59
+ authorization_endpoint: `${issuer}/idp/auth`,
60
+ token_endpoint: `${issuer}/idp/token`,
61
+ userinfo_endpoint: `${issuer}/idp/me`,
62
+ jwks_uri: `${issuer}/.well-known/jwks.json`,
63
+ registration_endpoint: `${issuer}/idp/reg`,
64
+ introspection_endpoint: `${issuer}/idp/token/introspection`,
65
+ revocation_endpoint: `${issuer}/idp/token/revocation`,
66
+ end_session_endpoint: `${issuer}/idp/session/end`,
67
+ scopes_supported: ['openid', 'webid', 'profile', 'email', 'offline_access'],
68
+ response_types_supported: ['code'],
69
+ response_modes_supported: ['query', 'fragment', 'form_post'],
70
+ grant_types_supported: ['authorization_code', 'refresh_token', 'client_credentials'],
71
+ subject_types_supported: ['public'],
72
+ id_token_signing_alg_values_supported: ['ES256'],
73
+ token_endpoint_auth_methods_supported: ['none', 'client_secret_basic', 'client_secret_post'],
74
+ claims_supported: ['sub', 'webid', 'name', 'email', 'email_verified'],
75
+ code_challenge_methods_supported: ['S256'],
76
+ dpop_signing_alg_values_supported: ['ES256', 'RS256'],
77
+ // Solid-OIDC specific
78
+ solid_oidc_supported: 'https://solidproject.org/TR/solid-oidc',
79
+ };
80
+
81
+ reply.header('Cache-Control', 'public, max-age=3600');
82
+ return config;
83
+ });
84
+
85
+ // /.well-known/jwks.json
86
+ fastify.get('/.well-known/jwks.json', async (request, reply) => {
87
+ const jwks = await getPublicJwks();
88
+ reply.header('Cache-Control', 'public, max-age=3600');
89
+ return jwks;
90
+ });
91
+
92
+ // Interaction routes (our custom login/consent UI)
93
+ // These bypass oidc-provider and use our handlers
94
+
95
+ // GET interaction - show login or consent page
96
+ fastify.get('/idp/interaction/:uid', async (request, reply) => {
97
+ return handleInteractionGet(request, reply, provider);
98
+ });
99
+
100
+ // POST login
101
+ fastify.post('/idp/interaction/:uid/login', async (request, reply) => {
102
+ return handleLogin(request, reply, provider);
103
+ });
104
+
105
+ // POST consent
106
+ fastify.post('/idp/interaction/:uid/confirm', async (request, reply) => {
107
+ return handleConsent(request, reply, provider);
108
+ });
109
+
110
+ // POST abort
111
+ fastify.post('/idp/interaction/:uid/abort', async (request, reply) => {
112
+ return handleAbort(request, reply, provider);
113
+ });
114
+
115
+ fastify.log.info(`IdP initialized with issuer: ${issuer}`);
116
+ }
117
+
118
+ 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
+ }