javascript-solid-server 0.0.172 → 0.0.173

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.
@@ -405,7 +405,12 @@
405
405
  "Bash(ANDROID_HOME=/home/melvin/Android/Sdk ANDROID_SDK_ROOT=/home/melvin/Android/Sdk ./gradlew :app:compileDebugKotlin --no-daemon)",
406
406
  "Bash(./scripts/fetch-libnode.sh v18.20.4)",
407
407
  "Bash(ANDROID_HOME=/home/melvin/Android/Sdk ANDROID_SDK_ROOT=/home/melvin/Android/Sdk ./gradlew :app:assembleDebug --no-daemon)",
408
- "Bash(/home/melvin/Android/Sdk/platform-tools/adb devices *)"
408
+ "Bash(/home/melvin/Android/Sdk/platform-tools/adb devices *)",
409
+ "Bash(command -v chromium chromium-browser google-chrome firefox playwright)",
410
+ "Bash(/usr/bin/chromium-browser --headless --no-sandbox --disable-gpu --hide-scrollbars --window-size=480,800 --screenshot=/tmp/consent-preview.png file:///tmp/consent-preview.html)",
411
+ "Bash(cp /tmp/consent-preview.html ~/consent-preview.html)",
412
+ "Read(//home/melvin/**)",
413
+ "Bash(/usr/bin/chromium-browser --headless --no-sandbox --disable-gpu --hide-scrollbars --window-size=520,900 --screenshot=consent.png file:///home/melvin/consent-preview.html)"
409
414
  ]
410
415
  }
411
416
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "javascript-solid-server",
3
- "version": "0.0.172",
3
+ "version": "0.0.173",
4
4
  "description": "A minimal, fast Solid server",
5
5
  "main": "src/index.js",
6
6
  "type": "module",
package/src/idp/index.js CHANGED
@@ -11,6 +11,7 @@ import {
11
11
  handleLogin,
12
12
  handleConsent,
13
13
  handleAbort,
14
+ handleSwitchAccount,
14
15
  handleRegisterGet,
15
16
  handleRegisterPost,
16
17
  handlePasskeyComplete,
@@ -324,6 +325,13 @@ export async function idpPlugin(fastify, options) {
324
325
  return handleAbort(request, reply, provider);
325
326
  });
326
327
 
328
+ // POST "Sign in as a different user" (#384) — destroys the OIDC
329
+ // session and bounces back to the login prompt while preserving the
330
+ // in-flight authz request.
331
+ fastify.post('/idp/interaction/:uid/switch', async (request, reply) => {
332
+ return handleSwitchAccount(request, reply, provider);
333
+ });
334
+
327
335
  // Registration routes (disabled in single-user mode)
328
336
  if (singleUser) {
329
337
  // Single-user mode: registration disabled
@@ -297,6 +297,89 @@ export async function handleConsent(request, reply, provider) {
297
297
  }
298
298
  }
299
299
 
300
+ /**
301
+ * Handle POST /idp/interaction/:uid/switch
302
+ *
303
+ * "Sign in as a different user" from the consent page (#384). Destroys
304
+ * the current OIDC session, mutates the in-flight interaction back to
305
+ * the login prompt, and redirects the user to the same /idp/interaction
306
+ * URL — which `handleInteractionGet` will render as the login page.
307
+ *
308
+ * Re-using the same interaction uid (rather than starting a fresh
309
+ * /idp/auth flow) preserves the original authz request params so the
310
+ * caller's redirect_uri / state / nonce all flow through unchanged.
311
+ */
312
+ export async function handleSwitchAccount(request, reply, provider) {
313
+ const { uid } = request.params;
314
+
315
+ try {
316
+ const interaction = await provider.Interaction.find(uid);
317
+ if (!interaction) {
318
+ return reply.code(404).type('text/html').send(errorPage('Interaction not found', 'This interaction may have expired. Try signing in again from your app.'));
319
+ }
320
+
321
+ // The UI entrypoint is the consent page only. Refusing on other
322
+ // prompt states (login, passkey, etc.) prevents a crafted request
323
+ // from corrupting an in-flight non-consent interaction.
324
+ if (interaction.prompt?.name !== 'consent') {
325
+ return reply.code(400).type('text/html').send(errorPage('Cannot switch account here', 'Account switching is only available from the consent page.'));
326
+ }
327
+
328
+ // Destroy the bound session so the new login starts cold. The cookie
329
+ // becomes a stale reference; oidc-provider's Session.get treats a
330
+ // missing session blob as "new browser", which is the shape we want.
331
+ if (interaction.session?.uid) {
332
+ const sess = await provider.Session.findByUid(interaction.session.uid);
333
+ if (sess) await sess.destroy();
334
+ }
335
+
336
+ // Reset the interaction back to the login prompt, dropping the
337
+ // session reference and any prior `result` snapshot. `prompt`,
338
+ // `session`, and `result` are all in the oidc-provider Interaction
339
+ // IN_PAYLOAD allowlist, so the mutations persist through the
340
+ // adapter. Original `params` (client_id, redirect_uri, state, etc.)
341
+ // are untouched, so resume picks them up after login. Clearing
342
+ // `result` prevents a stale `result.login` from a previous identity
343
+ // influencing the next resume.
344
+ interaction.session = undefined;
345
+ interaction.result = undefined;
346
+ interaction.prompt = { name: 'login', reasons: ['no_session'], details: {} };
347
+ interaction.lastError = undefined;
348
+ const ttl = Math.max(1, interaction.exp - Math.floor(Date.now() / 1000));
349
+ await interaction.save(ttl);
350
+
351
+ // Clear the user-agent's session cookie too. The IdP runs with
352
+ // signed cookies (provider.js cookies.long.signed = true), so each
353
+ // session cookie has a paired `.sig`. The `.legacy` variant is
354
+ // created during identifier rotation and likewise has its own
355
+ // `.sig`. Clearing all four keeps the browser fully tidy. JSS
356
+ // doesn't register @fastify/cookie, so we emit Set-Cookie headers
357
+ // directly with an expired Expires + Max-Age=0. Server-side state
358
+ // is already gone via session.destroy() above — these expirations
359
+ // are belt-and-suspenders.
360
+ const expired = 'Path=/; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; HttpOnly';
361
+ reply.header('Set-Cookie', [
362
+ `_session=; ${expired}`,
363
+ `_session.sig=; ${expired}`,
364
+ `_session.legacy=; ${expired}`,
365
+ `_session.legacy.sig=; ${expired}`,
366
+ ]);
367
+
368
+ // 303 See Other — explicitly forces the UA to issue GET on the
369
+ // Location target. 302 leaves it ambiguous (and some legacy UAs
370
+ // repeat the POST), which would re-trigger this handler in a loop.
371
+ // Status-then-URL arg order matches the rest of the codebase
372
+ // (src/server.js:637, src/tunnel/index.js:222).
373
+ return reply.redirect(303, `/idp/interaction/${uid}`);
374
+ } catch (err) {
375
+ request.log.error(err, 'Switch-account error');
376
+ // Don't surface raw err.message — adapter errors and stack-leaking
377
+ // strings on an auth endpoint are a soft info-leak. Full error is
378
+ // already in the server log via request.log.error above.
379
+ return reply.code(500).type('text/html').send(errorPage('Error', 'Something went wrong. Please try signing in again.'));
380
+ }
381
+ }
382
+
300
383
  /**
301
384
  * Handle POST /idp/interaction/:uid/abort
302
385
  * User cancelled the flow
package/src/idp/views.js CHANGED
@@ -503,7 +503,15 @@ export function consentPage(uid, client, params, account) {
503
503
  ${clientUri ? `<div class="client-uri">${escapeHtml(clientUri)}</div>` : ''}
504
504
  </div>
505
505
 
506
- ${account ? `<p>Signed in as <strong>${escapeHtml(account.email)}</strong></p>` : ''}
506
+ ${account ? `
507
+ <div style="display: flex; align-items: center; justify-content: center; gap: 8px; flex-wrap: wrap; margin: 12px 0;">
508
+ <span>Signed in as <strong>${escapeHtml(account.email)}</strong></span>
509
+ <span style="color: #94a3b8;">·</span>
510
+ <form method="POST" action="/idp/interaction/${uid}/switch" style="display: inline; margin: 0;">
511
+ <button type="submit" style="background: none; border: 0; padding: 0; color: #2563eb; font: inherit; cursor: pointer; text-decoration: underline;">Sign in as a different user</button>
512
+ </form>
513
+ </div>
514
+ ` : ''}
507
515
 
508
516
  <div class="scopes">
509
517
  <label>This app is requesting access to:</label>
package/test/idp.test.js CHANGED
@@ -4,6 +4,7 @@
4
4
 
5
5
  import { describe, it, before, after, beforeEach } from 'node:test';
6
6
  import assert from 'node:assert';
7
+ import http from 'node:http';
7
8
  import { createServer } from '../src/server.js';
8
9
  import fs from 'fs-extra';
9
10
  import path from 'path';
@@ -182,6 +183,122 @@ describe('Identity Provider', () => {
182
183
  });
183
184
  });
184
185
 
186
+ // Regression coverage for #384 — "Sign in as a different user" on consent
187
+ describe('Switch account on consent (#384)', () => {
188
+ // The IDP's filesystem adapter stores Interaction records as JSON at
189
+ // <DATA_ROOT>/.idp/interaction/<uid>.json (model name "Interaction"
190
+ // → dir "interaction" via the adapter's modelToDir camelCase split).
191
+ // Tests write a synthetic interaction directly so we don't have to
192
+ // walk a full OIDC client flow to set up state.
193
+ const interactionDir = `${DATA_DIR}/.idp/interaction`;
194
+
195
+ function writeInteraction(uid, payload) {
196
+ const ttlSec = 3600;
197
+ const data = {
198
+ ...payload,
199
+ kind: 'Interaction',
200
+ jti: uid,
201
+ exp: Math.floor(Date.now() / 1000) + ttlSec,
202
+ iat: Math.floor(Date.now() / 1000),
203
+ _id: uid,
204
+ _expiresAt: Date.now() + ttlSec * 1000,
205
+ };
206
+ return fs.outputJson(`${interactionDir}/${uid}.json`, data, { spaces: 2 });
207
+ }
208
+
209
+ // Use node:http directly for the cookie-clearing assertion. fetch's
210
+ // Headers.getSetCookie() is only available on Node 19.7+, but the
211
+ // package declares engines.node >= 18. http.request gives us
212
+ // res.headers['set-cookie'] as a real array on every supported
213
+ // Node version, no version-gated branches needed.
214
+ function rawPost(urlString) {
215
+ return new Promise((resolve, reject) => {
216
+ const u = new URL(urlString);
217
+ const req = http.request({
218
+ method: 'POST',
219
+ hostname: u.hostname,
220
+ port: u.port,
221
+ path: u.pathname + u.search,
222
+ }, (res) => {
223
+ let body = '';
224
+ res.on('data', (c) => body += c);
225
+ res.on('end', () => resolve({
226
+ statusCode: res.statusCode,
227
+ headers: res.headers,
228
+ body,
229
+ }));
230
+ });
231
+ req.on('error', reject);
232
+ req.end();
233
+ });
234
+ }
235
+
236
+ it('redirects back to /idp/interaction/:uid and resets the prompt to login', async () => {
237
+ const uid = 'test-switch-' + Math.random().toString(36).slice(2);
238
+ await writeInteraction(uid, {
239
+ prompt: { name: 'consent', reasons: [], details: {} },
240
+ session: { uid: 'fake-session-uid', accountId: 'acct-foo' },
241
+ params: { client_id: 'test-client', redirect_uri: 'http://localhost', state: 'xyz' },
242
+ });
243
+
244
+ const res = await rawPost(`${baseUrl}/idp/interaction/${uid}/switch`);
245
+
246
+ // 303 See Other — forces UA to GET the Location target so a
247
+ // (broken) UA can't loop by re-POSTing to /switch.
248
+ assert.strictEqual(res.statusCode, 303);
249
+ assert.strictEqual(res.headers.location, `/idp/interaction/${uid}`);
250
+
251
+ // Verify the interaction was mutated as expected.
252
+ const saved = await fs.readJson(`${interactionDir}/${uid}.json`);
253
+ assert.strictEqual(saved.prompt.name, 'login');
254
+ assert.ok(saved.session === undefined || saved.session === null,
255
+ 'session should be cleared');
256
+ // Original params survive so resume can continue the authz request.
257
+ assert.strictEqual(saved.params.client_id, 'test-client');
258
+ assert.strictEqual(saved.params.state, 'xyz');
259
+
260
+ // Cookies should be cleared so the user's UA forgets the prior
261
+ // session. Node's http module gives Set-Cookie as an array on
262
+ // every supported version, so no Node 19.7+ gating needed.
263
+ const setCookies = Array.isArray(res.headers['set-cookie']) ? res.headers['set-cookie'] : [];
264
+ assert.ok(setCookies.length >= 4, `expected at least 4 Set-Cookie headers, got ${setCookies.length}`);
265
+ // All four signed-cookie names should be cleared:
266
+ // _session + _session.sig + _session.legacy + _session.legacy.sig.
267
+ for (const name of ['_session=', '_session.sig=', '_session.legacy=', '_session.legacy.sig=']) {
268
+ assert.ok(setCookies.some(c => c.startsWith(name)),
269
+ `should clear ${name.slice(0, -1)}`);
270
+ }
271
+ assert.ok(setCookies.every(c => /Max-Age=0|Expires=Thu, 01 Jan 1970/.test(c)),
272
+ 'all Set-Cookies should be expirations');
273
+ });
274
+
275
+ it('returns 400 when the interaction is not on the consent prompt', async () => {
276
+ const uid = 'test-switch-bad-' + Math.random().toString(36).slice(2);
277
+ await writeInteraction(uid, {
278
+ prompt: { name: 'login', reasons: ['no_session'], details: {} },
279
+ params: { client_id: 'test-client' },
280
+ });
281
+
282
+ const res = await fetch(`${baseUrl}/idp/interaction/${uid}/switch`, {
283
+ method: 'POST',
284
+ redirect: 'manual',
285
+ });
286
+
287
+ assert.strictEqual(res.status, 400);
288
+ // Original interaction should be untouched.
289
+ const saved = await fs.readJson(`${interactionDir}/${uid}.json`);
290
+ assert.strictEqual(saved.prompt.name, 'login');
291
+ });
292
+
293
+ it('returns 404 for an unknown interaction uid', async () => {
294
+ const res = await fetch(`${baseUrl}/idp/interaction/does-not-exist-${Date.now()}/switch`, {
295
+ method: 'POST',
296
+ redirect: 'manual',
297
+ });
298
+ assert.strictEqual(res.status, 404);
299
+ });
300
+ });
301
+
185
302
  // Regression coverage for #286 — friendly /idp landing + /idp/auth guard.
186
303
  describe('Landing page', () => {
187
304
  it('GET /idp returns the landing HTML', async () => {