javascript-solid-server 0.0.191 → 0.0.193

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.
package/src/idp/index.js CHANGED
@@ -27,6 +27,7 @@ import {
27
27
  handleAccountDeleteForm,
28
28
  setNoCacheClickjackHeaders,
29
29
  } from './credentials.js';
30
+ import { handleExportAccount } from './export.js';
30
31
  import * as passkey from './passkey.js';
31
32
  import { addTrustedIssuer } from '../auth/solid-oidc.js';
32
33
  import { landingPage, accountDeletePage } from './views.js';
@@ -36,9 +37,21 @@ import { landingPage, accountDeletePage } from './views.js';
36
37
  * @param {FastifyInstance} fastify
37
38
  * @param {object} options
38
39
  * @param {string} options.issuer - The issuer URL
40
+ * @param {boolean} [options.inviteOnly=false] - If true, /idp/register
41
+ * requires a valid invite code; public registration is disabled.
42
+ * @param {boolean} [options.singleUser=false] - Single-user mode.
43
+ * Disables /idp/register and /idp/account DELETE; gates the
44
+ * single-user branch in /idp/account/export.
45
+ * @param {string|null} [options.singleUserName=null] - Single-user
46
+ * pod name. null → root pod (podDir = dataRoot); string → pod
47
+ * lives at <dataRoot>/<name>/. Threaded into /idp/account/export
48
+ * so the handler can resolve podDir + apply ROOT_POD_EXCLUDE.
49
+ * @param {string} [options.jssVersion] - Server version, written
50
+ * into the export manifest for forensic / "what server made this"
51
+ * purposes. Defaults to 'unknown' inside the export handler.
39
52
  */
40
53
  export async function idpPlugin(fastify, options) {
41
- const { issuer, inviteOnly = false, singleUser = false } = options;
54
+ const { issuer, inviteOnly = false, singleUser = false, singleUserName = null, jssVersion } = options;
42
55
 
43
56
  if (!issuer) {
44
57
  throw new Error('IdP requires issuer URL');
@@ -297,6 +310,34 @@ export async function idpPlugin(fastify, options) {
297
310
  return handleDeleteAccount(request, reply, { singleUser });
298
311
  });
299
312
 
313
+ // GET account export — authenticated owner downloads their pod tree as
314
+ // a streamed tar.gz (#353). MVP slice of the Credible Exit ladder
315
+ // (#448). Lighter rate-limit than the destructive endpoints — this is
316
+ // a read, but a heavy one (entire pod), so cap at 3/min to deter
317
+ // abuse without blocking a legitimate operator pulling a backup.
318
+ //
319
+ // Keyed by IP, consistent with the other /idp/ endpoints. We can't
320
+ // honestly key by WebID here: the global auth hook in src/server.js
321
+ // skips /idp/* (so request.webId is unset at this phase) and the
322
+ // rate-limit keyGenerator is sync, so we can't await token
323
+ // verification inline. Per-user keying is a follow-up that needs
324
+ // a preParsing hook resolving auth before the limiter runs.
325
+ fastify.get('/idp/account/export', {
326
+ config: {
327
+ rateLimit: {
328
+ max: 3,
329
+ timeWindow: '1 minute',
330
+ keyGenerator: (request) => request.ip
331
+ }
332
+ }
333
+ }, async (request, reply) => {
334
+ return handleExportAccount(request, reply, {
335
+ singleUser,
336
+ singleUserName,
337
+ jssVersion,
338
+ });
339
+ });
340
+
300
341
  // GET account-delete form (#392) - human-friendly UI for #352. Public
301
342
  // unauthenticated page; auth happens at form submission via password.
302
343
  // Single-user mode returns 403 to stay consistent with /idp/register's
@@ -9,6 +9,7 @@ import * as storage from '../storage/filesystem.js';
9
9
  import { createPodStructure } from '../handlers/container.js';
10
10
  import { validateInvite } from './invites.js';
11
11
  import { verifyNostrAuth, getNostrPubkey, verifyNostrPubkeyAgainstWebId } from '../auth/nostr.js';
12
+ import { expireSessionCookies } from './cookies.js';
12
13
 
13
14
  // Security: Maximum body size for IdP form submissions (1MB)
14
15
  const MAX_BODY_SIZE = 1024 * 1024;
@@ -348,22 +349,10 @@ export async function handleSwitchAccount(request, reply, provider) {
348
349
  const ttl = Math.max(1, interaction.exp - Math.floor(Date.now() / 1000));
349
350
  await interaction.save(ttl);
350
351
 
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
352
+ // Clear the user-agent's session cookies. Server-side state is
353
+ // already gone via session.destroy() above — these expirations
359
354
  // 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
- ]);
355
+ expireSessionCookies(reply, request);
367
356
 
368
357
  // 303 See Other — explicitly forces the UA to issue GET on the
369
358
  // Location target. 302 leaves it ambiguous (and some legacy UAs
@@ -543,7 +532,8 @@ export async function handleRegisterPost(request, reply, issuer, inviteOnly = fa
543
532
  }
544
533
 
545
534
  // Create pod structure
546
- await createPodStructure(username, webId, podUri, issuer);
535
+ await createPodStructure(username, webId, podUri, issuer, 0,
536
+ { provisionKeys: request.provisionKeys === true });
547
537
 
548
538
  // Create account
549
539
  await createAccount({
@@ -8,6 +8,7 @@ import { createAdapter } from './adapter.js';
8
8
  import { getJwks, getCookieKeys } from './keys.js';
9
9
  import { getAccountForProvider } from './accounts.js';
10
10
  import { validateExternalUrl } from '../utils/ssrf.js';
11
+ import { expireSessionCookiesKoa } from './cookies.js';
11
12
 
12
13
  // Cache for fetched client documents
13
14
  const clientDocumentCache = new Map();
@@ -264,8 +265,16 @@ export async function createProvider(issuer) {
264
265
  // Auto-approve consent by loading/creating grants automatically
265
266
  // This skips the consent prompt for all clients (appropriate for test/dev servers)
266
267
  loadExistingGrant: async (ctx) => {
267
- // Check if there's an existing grant for this client/account pair
268
- const grantId = ctx.oidc.session?.grantIdFor(ctx.oidc.client?.clientId);
268
+ // Guard: if session or client is missing (e.g. stale cookies after
269
+ // account deletion), bail out early so oidc-provider doesn't crash
270
+ // calling getOIDCScopeEncountered() on an undefined grant (#452).
271
+ if (!ctx.oidc.session || !ctx.oidc.client) {
272
+ return undefined;
273
+ }
274
+
275
+ // Check if there's an existing grant for this client/account pair.
276
+ // Optional chain: grantIdFor may be absent on a stale session stub.
277
+ const grantId = ctx.oidc.session.grantIdFor?.(ctx.oidc.client.clientId);
269
278
 
270
279
  if (grantId) {
271
280
  const existingGrant = await ctx.oidc.provider.Grant.find(grantId);
@@ -275,7 +284,7 @@ export async function createProvider(issuer) {
275
284
  }
276
285
 
277
286
  // Auto-approve: create a new grant with all requested scopes
278
- if (ctx.oidc.session?.accountId && ctx.oidc.client?.clientId) {
287
+ if (ctx.oidc.session.accountId) {
279
288
  const grant = new ctx.oidc.provider.Grant({
280
289
  accountId: ctx.oidc.session.accountId,
281
290
  clientId: ctx.oidc.client.clientId,
@@ -393,6 +402,27 @@ export async function createProvider(issuer) {
393
402
 
394
403
  // Render errors
395
404
  renderError: async (ctx, out, error) => {
405
+ // Stale session recovery (#452): when oidc-provider crashes because
406
+ // a deleted account's session/grant is still in the browser cookies,
407
+ // expire those cookies and redirect back to the same URL. The retry
408
+ // starts with a clean session and succeeds. The `_stale_retry` param
409
+ // prevents infinite redirect loops — only try once.
410
+ const isStaleSessionCrash = out.error === 'server_error' &&
411
+ error instanceof TypeError &&
412
+ /Cannot read properties of undefined/.test(error?.message);
413
+ const reqUrl = ctx.req?.originalUrl || ctx.request?.url || ctx.url || '';
414
+ const alreadyRetried = reqUrl.includes('_stale_retry=1');
415
+
416
+ // Only redirect browser GETs (authorization endpoint). POST/token/
417
+ // userinfo are programmatic — clients won't follow redirects or
418
+ // honor Set-Cookie, so just fall through to the error page.
419
+ if (isStaleSessionCrash && !alreadyRetried && ctx.method === 'GET') {
420
+ expireSessionCookiesKoa(ctx);
421
+ const separator = reqUrl.includes('?') ? '&' : '?';
422
+ ctx.redirect(`${reqUrl}${separator}_stale_retry=1`);
423
+ return;
424
+ }
425
+
396
426
  ctx.type = 'html';
397
427
  ctx.body = `
398
428
  <!DOCTYPE html>
package/src/server.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import Fastify from 'fastify';
2
2
  import rateLimit from '@fastify/rate-limit';
3
3
  import { readFile } from 'fs/promises';
4
+ import { readFileSync } from 'fs';
4
5
  import { STATUS_CODES } from 'node:http';
5
6
  import { join, dirname } from 'path';
6
7
  import { fileURLToPath } from 'url';
@@ -264,6 +265,7 @@ export function createServer(options = {}) {
264
265
  fastify.decorateRequest('mashlibVersion', null);
265
266
  fastify.decorateRequest('mashlibModule', null);
266
267
  fastify.decorateRequest('defaultQuota', null);
268
+ fastify.decorateRequest('provisionKeys', null);
267
269
  fastify.decorateRequest('config', null);
268
270
  fastify.decorateRequest('liveReloadEnabled', null);
269
271
  fastify.decorateRequest('singleUser', null);
@@ -279,6 +281,7 @@ export function createServer(options = {}) {
279
281
  request.mashlibVersion = mashlibVersion;
280
282
  request.mashlibModule = mashlibModule;
281
283
  request.defaultQuota = defaultQuota;
284
+ request.provisionKeys = provisionKeysEnabled;
282
285
  request.config = { public: options.public, readOnly: options.readOnly };
283
286
  request.liveReloadEnabled = liveReloadEnabled;
284
287
  request.singleUser = singleUser;
@@ -321,7 +324,28 @@ export function createServer(options = {}) {
321
324
 
322
325
  // Register Identity Provider plugin if enabled
323
326
  if (idpEnabled) {
324
- fastify.register(idpPlugin, { issuer: idpIssuer, inviteOnly, singleUser });
327
+ // singleUserName + jssVersion are threaded through for the
328
+ // pod-data export endpoint (#353), which uses singleUserName to
329
+ // resolve the pod's on-disk path and writes the version into
330
+ // the export manifest for forensic / "what server made this"
331
+ // purposes. Reading the package.json lazily here keeps the
332
+ // export endpoint independent of any seedServerRoot work.
333
+ let jssVersion = 'unknown';
334
+ try {
335
+ // Sync read because createServer isn't async and we need the
336
+ // version to thread into idpPlugin registration below. The file
337
+ // is tiny + on local disk. There is a second async read of
338
+ // package.json in the onReady hook for seedServerRoot — both
339
+ // are read-once at startup so drift is bounded to "package.json
340
+ // changed between two ~ms-apart reads", which doesn't happen
341
+ // in practice. Hoisting both into a memoized module-level
342
+ // helper is a worthwhile follow-up but out of scope for #353.
343
+ const pkgRaw = readFileSync(join(__dirname, '..', 'package.json'), 'utf8');
344
+ jssVersion = JSON.parse(pkgRaw).version;
345
+ } catch { /* keep 'unknown' */ }
346
+ fastify.register(idpPlugin, {
347
+ issuer: idpIssuer, inviteOnly, singleUser, singleUserName, jssVersion,
348
+ });
325
349
  }
326
350
 
327
351
  // Register Nostr relay if enabled
@@ -0,0 +1,429 @@
1
+ /**
2
+ * GET /idp/account/export — pod data export endpoint (#353).
3
+ *
4
+ * MVP slice of the Credible Exit ladder (#448). The end user takes
5
+ * their pod data with them, no operator help required.
6
+ *
7
+ * Coverage:
8
+ * - 401 unauthenticated
9
+ * - 403 cross-account (multi-user: caller authed as B can't pull A)
10
+ * - 200 owner export → valid tar.gz containing manifest + account
11
+ * + pod tree
12
+ * - account.json never carries passwordHash
13
+ * - manifest shape (webId, podName, mode, exportedAt, jssVersion)
14
+ * - Single-user mode + --provision-keys: archive contains
15
+ * /private/privkey.jsonld (per Credible Exit framing — the
16
+ * user's secret IS theirs and must leave with them)
17
+ */
18
+
19
+ import { describe, it, before, after } from 'node:test';
20
+ import assert from 'node:assert';
21
+ import fs from 'fs-extra';
22
+ import path from 'path';
23
+ import zlib from 'zlib';
24
+ import tar from 'tar-stream';
25
+ import { Readable } from 'stream';
26
+ import { createServer } from '../src/server.js';
27
+ import { createToken } from '../src/auth/token.js';
28
+
29
+ // startServer/stopServer manage process.env.DATA_ROOT via a snapshot
30
+ // stored on the returned server. createServer mutates DATA_ROOT
31
+ // (src/server.js:175); without restore, subsequent unrelated tests
32
+ // reading DATA_ROOT in this run see a stale path pointing at a
33
+ // now-removed directory.
34
+ async function startServer(dataDir, options = {}) {
35
+ const prevDataRoot = process.env.DATA_ROOT;
36
+ await fs.remove(dataDir);
37
+ await fs.ensureDir(dataDir);
38
+ const server = createServer({
39
+ logger: false,
40
+ forceCloseConnections: true,
41
+ root: dataDir,
42
+ idp: true,
43
+ idpIssuer: 'http://127.0.0.1/',
44
+ ...options,
45
+ });
46
+ await server.listen({ port: 0, host: '127.0.0.1' });
47
+ const baseUrl = `http://127.0.0.1:${server.server.address().port}`;
48
+ server.__prevDataRoot = prevDataRoot;
49
+ return { server, baseUrl };
50
+ }
51
+
52
+ async function stopServer(server, dataDir) {
53
+ await server.close();
54
+ await fs.remove(dataDir);
55
+ if (server.__prevDataRoot === undefined) delete process.env.DATA_ROOT;
56
+ else process.env.DATA_ROOT = server.__prevDataRoot;
57
+ }
58
+
59
+ /**
60
+ * Read a tar.gz archive from a Buffer or Response into a map of
61
+ * `{ filename: Buffer-content }`. Tests can then assert on filenames
62
+ * + content shapes without touching disk.
63
+ */
64
+ async function unpackTarGz(buf) {
65
+ const out = {};
66
+ const extract = tar.extract();
67
+ await new Promise((resolve, reject) => {
68
+ extract.on('entry', (header, stream, next) => {
69
+ const chunks = [];
70
+ stream.on('data', (c) => chunks.push(c));
71
+ stream.on('end', () => {
72
+ out[header.name] = Buffer.concat(chunks);
73
+ next();
74
+ });
75
+ stream.on('error', reject);
76
+ stream.resume();
77
+ });
78
+ extract.on('finish', resolve);
79
+ extract.on('error', reject);
80
+ Readable.from(buf).pipe(zlib.createGunzip()).pipe(extract);
81
+ });
82
+ return out;
83
+ }
84
+
85
+ describe('GET /idp/account/export — multi-user', () => {
86
+ const DATA_DIR = './test-data-export-mu';
87
+ // Alice plants a uniquely-named marker resource in her pod. Bob's
88
+ // export must not contain anything matching this name OR contents.
89
+ // Anchors the cross-account test against the actual files-on-disk
90
+ // shape rather than the archive's prefix layout (which never embeds
91
+ // a username segment, so a plain `/alice/` regex would tautologically
92
+ // pass even if Bob's archive somehow contained Alice's bytes).
93
+ const ALICE_CANARY_NAME = 'alice-canary-do-not-leak.txt';
94
+ const ALICE_CANARY_BODY = 'ALICE_SECRET_CANARY_a7f3e9d1c4b2';
95
+ let server, baseUrl, aliceToken, bobToken;
96
+
97
+ before(async () => {
98
+ ({ server, baseUrl } = await startServer(DATA_DIR));
99
+ // Create two pods so the cross-account property is real.
100
+ // Hard-fail on pod creation so a /.pods shape regression surfaces
101
+ // as "pod creation failed" rather than as cryptic 401s in every
102
+ // downstream test. Same pattern as the single-user before hooks.
103
+ const aliceRes = await fetch(`${baseUrl}/.pods`, {
104
+ method: 'POST',
105
+ headers: { 'Content-Type': 'application/json' },
106
+ body: JSON.stringify({
107
+ name: 'alice', email: 'alice@example.com', password: 'pw-alice-123'
108
+ })
109
+ });
110
+ assert.ok(aliceRes.ok, `alice pod creation failed: ${aliceRes.status}`);
111
+ aliceToken = (await aliceRes.json()).token;
112
+ assert.ok(aliceToken, 'alice pod creation must return a token');
113
+ const bobRes = await fetch(`${baseUrl}/.pods`, {
114
+ method: 'POST',
115
+ headers: { 'Content-Type': 'application/json' },
116
+ body: JSON.stringify({
117
+ name: 'bob', email: 'bob@example.com', password: 'pw-bob-456'
118
+ })
119
+ });
120
+ assert.ok(bobRes.ok, `bob pod creation failed: ${bobRes.status}`);
121
+ bobToken = (await bobRes.json()).token;
122
+ assert.ok(bobToken, 'bob pod creation must return a token');
123
+
124
+ // Plant the alice-only canary file directly on disk under
125
+ // <DATA_ROOT>/alice/. PUT through the LDP layer would also work
126
+ // but adds an auth round-trip we don't need for this assertion.
127
+ await fs.outputFile(
128
+ path.join(DATA_DIR, 'alice', ALICE_CANARY_NAME),
129
+ ALICE_CANARY_BODY,
130
+ );
131
+ });
132
+
133
+ after(async () => {
134
+ await stopServer(server, DATA_DIR);
135
+ });
136
+
137
+ it('returns 401 unauthenticated', async () => {
138
+ const res = await fetch(`${baseUrl}/idp/account/export`);
139
+ assert.strictEqual(res.status, 401);
140
+ });
141
+
142
+ it('returns 200 with a tar.gz for the authenticated owner', async () => {
143
+ const res = await fetch(`${baseUrl}/idp/account/export`, {
144
+ headers: { Authorization: `Bearer ${aliceToken}` }
145
+ });
146
+ assert.strictEqual(res.status, 200);
147
+ assert.strictEqual(res.headers.get('content-type'), 'application/x-tar+gzip');
148
+ assert.match(res.headers.get('content-disposition') || '', /^attachment; filename="jss-export-/);
149
+ const buf = Buffer.from(await res.arrayBuffer());
150
+ const files = await unpackTarGz(buf);
151
+
152
+ // Manifest first.
153
+ assert.ok(files['jss-export/manifest.json'], 'manifest must be present');
154
+ const manifest = JSON.parse(files['jss-export/manifest.json'].toString('utf8'));
155
+ assert.strictEqual(manifest.username, 'alice');
156
+ assert.strictEqual(manifest.podName, 'alice');
157
+ assert.strictEqual(manifest.mode, 'multi-user');
158
+ assert.match(manifest.exportedAt, /^\d{4}-\d{2}-\d{2}T/);
159
+ assert.match(manifest.webId, /alice\/profile\/card\.jsonld#me$/);
160
+
161
+ // Account record present, sans passwordHash.
162
+ assert.ok(files['jss-export/account.json'], 'account.json must be present');
163
+ const account = JSON.parse(files['jss-export/account.json'].toString('utf8'));
164
+ assert.strictEqual(account.username, 'alice');
165
+ assert.strictEqual(account.email, 'alice@example.com');
166
+ assert.strictEqual(account.passwordHash, undefined,
167
+ 'account.json must NEVER include the password hash');
168
+
169
+ // Pod tree contents — at minimum the seeded files.
170
+ const podKeys = Object.keys(files).filter(k => k.startsWith('jss-export/pod/'));
171
+ assert.ok(podKeys.length > 0, 'pod tree must be packed');
172
+ assert.ok(podKeys.some(k => k.endsWith('profile/card.jsonld')),
173
+ 'WebID profile must be in the export');
174
+ assert.ok(podKeys.some(k => k.endsWith('.acl')),
175
+ 'ACL files must be in the export');
176
+ });
177
+
178
+ it("scopes the export to the authenticated caller — no cross-account exposure", async () => {
179
+ // The endpoint takes no target parameter; the WebID is taken
180
+ // from the auth context. Cross-account access is structurally
181
+ // impossible to attempt (so there's no 403 case). This test
182
+ // pins the *property* by confirming bob's authenticated call
183
+ // returns bob's data and never anything from alice's pod.
184
+ const res = await fetch(`${baseUrl}/idp/account/export`, {
185
+ headers: { Authorization: `Bearer ${bobToken}` }
186
+ });
187
+ assert.strictEqual(res.status, 200);
188
+ const buf = Buffer.from(await res.arrayBuffer());
189
+ const files = await unpackTarGz(buf);
190
+
191
+ // Manifest identifies bob.
192
+ const manifest = JSON.parse(files['jss-export/manifest.json'].toString('utf8'));
193
+ assert.strictEqual(manifest.username, 'bob');
194
+ assert.strictEqual(manifest.podName, 'bob');
195
+
196
+ // Account record (the actual server-side record, not the manifest)
197
+ // identifies bob — guards against a bug where the wrong account
198
+ // is looked up but the manifest is built from the request webId.
199
+ assert.ok(files['jss-export/account.json'],
200
+ 'account.json must be present in bob\'s export');
201
+ const account = JSON.parse(files['jss-export/account.json'].toString('utf8'));
202
+ assert.strictEqual(account.username, 'bob',
203
+ 'account.json.username must be bob, not alice');
204
+ assert.strictEqual(account.email, 'bob@example.com');
205
+
206
+ // The alice-only canary file must NOT appear in bob's archive,
207
+ // by entry name or by entry contents. This is the substantive
208
+ // cross-account assertion — the previous `/alice/` regex check
209
+ // was tautological because pod-tree entries are namespaced by
210
+ // archive prefix (`jss-export/pod/...`), not by username segment.
211
+ const allKeys = Object.keys(files);
212
+ for (const k of allKeys) {
213
+ assert.ok(
214
+ !k.endsWith(ALICE_CANARY_NAME),
215
+ `bob's export must not contain alice's canary file: ${k}`,
216
+ );
217
+ // Body check: even if the entry name was reshaped, the canary
218
+ // body bytes must never appear in any of bob's archive entries.
219
+ assert.ok(
220
+ !files[k].includes(ALICE_CANARY_BODY),
221
+ `bob's export entry ${k} contains alice's canary body bytes`,
222
+ );
223
+ }
224
+ });
225
+ });
226
+
227
+ describe('GET /idp/account/export — single-user ROOT pod (denylist check)', () => {
228
+ // Critical: in single-user root-pod mode (the default since #348),
229
+ // podDir IS dataRoot. Without an explicit denylist, the export would
230
+ // ship server-internal directories that live next to pod data:
231
+ //
232
+ // .idp/ — every account record (incl. passwordHash) and the
233
+ // IdP signing keys that mint tokens for any user
234
+ // .private/ — pay handler's Bitcoin keypair + UTXO state
235
+ // (recipient could drain pay balance / spend UTXOs)
236
+ //
237
+ // The handler must refuse to include either at the top level.
238
+ const DATA_DIR = './test-data-export-root-pod';
239
+ let server, baseUrl, ownerToken;
240
+
241
+ before(async () => {
242
+ ({ server, baseUrl } = await startServer(DATA_DIR, {
243
+ singleUser: true,
244
+ // No singleUserName → root pod (#348 default)
245
+ singleUserName: null,
246
+ singleUserPassword: 'pw-root-321',
247
+ provisionKeys: true,
248
+ }));
249
+ const credRes = await fetch(`${baseUrl}/idp/credentials`, {
250
+ method: 'POST',
251
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
252
+ body: new URLSearchParams({ username: 'me', password: 'pw-root-321' }).toString(),
253
+ });
254
+ if (credRes.status === 200) {
255
+ const body = await credRes.json();
256
+ ownerToken = body.access_token || body.token;
257
+ }
258
+ });
259
+
260
+ after(async () => {
261
+ await stopServer(server, DATA_DIR);
262
+ });
263
+
264
+ it('does NOT pack server-internal dirs (.idp/, .private/) at root', async () => {
265
+ // Hard-fail rather than t.skip — a credentials regression must
266
+ // not silently disable this denylist test, which is the only
267
+ // assertion guarding against the catastrophic root-pod leak.
268
+ assert.ok(ownerToken,
269
+ 'pre-condition: IDP credentials handshake must return a token; ' +
270
+ 'a regression here would silently skip the denylist assertion');
271
+
272
+ // Sanity: confirm the server actually wrote these dirs to disk so
273
+ // the denylist assertion below is exercising real entries. We
274
+ // synthesize .private/ ourselves (pay handler only writes it on
275
+ // first /pay use) so the test doesn't depend on side-channel
276
+ // activity to be meaningful. We also pin the IdP secret-bearing
277
+ // file specifically — the property under test is "no IdP secrets
278
+ // appear in the export", not just "no entries under one specific
279
+ // dotted prefix". A future refactor moving secrets out of
280
+ // `.idp/accounts/*.json` would fail this pre-condition loudly
281
+ // and force the denylist + assertion to be re-pinned to wherever
282
+ // the secrets moved.
283
+ await fs.outputFile(
284
+ path.join(DATA_DIR, '.private', 'keypair.json'),
285
+ JSON.stringify({ canary: 'must-not-leak' }),
286
+ );
287
+ const idpAccounts = await fs.readdir(path.join(DATA_DIR, '.idp', 'accounts'))
288
+ .catch(() => []);
289
+ const accountFiles = idpAccounts.filter(f => f.endsWith('.json'));
290
+ assert.ok(accountFiles.length > 0,
291
+ 'pre-condition: .idp/accounts/*.json must exist (the actual ' +
292
+ 'secret-bearing material that the denylist must keep out of the export)');
293
+ assert.ok(
294
+ await fs.pathExists(path.join(DATA_DIR, '.private', 'keypair.json')),
295
+ 'pre-condition: .private/keypair.json must exist'
296
+ );
297
+ const res = await fetch(`${baseUrl}/idp/account/export`, {
298
+ headers: { Authorization: `Bearer ${ownerToken}` }
299
+ });
300
+ assert.strictEqual(res.status, 200);
301
+ const buf = Buffer.from(await res.arrayBuffer());
302
+ const files = await unpackTarGz(buf);
303
+
304
+ // Critical: NOTHING under jss-export/pod/.idp/ or jss-export/pod/.private/.
305
+ const leakedEntries = Object.keys(files).filter(k =>
306
+ k.startsWith('jss-export/pod/.idp/') || k === 'jss-export/pod/.idp' ||
307
+ k.startsWith('jss-export/pod/.private/') || k === 'jss-export/pod/.private'
308
+ );
309
+ assert.strictEqual(leakedEntries.length, 0,
310
+ `Server-internal dirs must not be packed in root-pod export. ` +
311
+ `Found: ${leakedEntries.join(', ')}`);
312
+
313
+ // Sanity: actual pod content IS in the archive.
314
+ const podKeys = Object.keys(files).filter(k => k.startsWith('jss-export/pod/'));
315
+ assert.ok(podKeys.some(k => k.endsWith('profile/card.jsonld')),
316
+ 'pod content must still be exported');
317
+ assert.ok(podKeys.some(k => k.endsWith('private/privkey.jsonld')),
318
+ 'pod /private/ must still be exported (this is pod data, not server-internal)');
319
+
320
+ // Manifest shape in root-pod mode. Pins the parity property:
321
+ // manifest.podName MUST equal account.json.podName so a downstream
322
+ // importer keying on either field gets the same answer. Without
323
+ // this, root-pod previously emitted manifest.podName=null while
324
+ // accountRecord.podName='me' — silent disagreement in the same
325
+ // archive.
326
+ assert.ok(files['jss-export/manifest.json'], 'manifest.json must be present');
327
+ assert.ok(files['jss-export/account.json'], 'account.json must be present');
328
+ const manifest = JSON.parse(files['jss-export/manifest.json'].toString('utf8'));
329
+ const account = JSON.parse(files['jss-export/account.json'].toString('utf8'));
330
+ assert.strictEqual(manifest.mode, 'single-user');
331
+ assert.strictEqual(manifest.username, 'me',
332
+ 'root-pod manifest carries the seeded username');
333
+ assert.strictEqual(manifest.podName, account.podName,
334
+ 'manifest.podName must match account.json.podName — single source of truth');
335
+ assert.strictEqual(account.podName, 'me',
336
+ 'seeded root-pod account.podName is "me" (the OIDC short name)');
337
+ });
338
+ });
339
+
340
+ describe('GET /idp/account/export — single-user with --provision-keys', () => {
341
+ const DATA_DIR = './test-data-export-su-keys';
342
+ let server, baseUrl, ownerToken;
343
+
344
+ before(async () => {
345
+ ({ server, baseUrl } = await startServer(DATA_DIR, {
346
+ singleUser: true,
347
+ singleUserName: 'me',
348
+ singleUserPassword: 'pw-me-789',
349
+ provisionKeys: true,
350
+ }));
351
+ // Auth via the seeded IDP account password.
352
+ const credRes = await fetch(`${baseUrl}/idp/credentials`, {
353
+ method: 'POST',
354
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
355
+ body: new URLSearchParams({ username: 'me', password: 'pw-me-789' }).toString(),
356
+ });
357
+ if (credRes.status === 200) {
358
+ const body = await credRes.json();
359
+ ownerToken = body.access_token || body.token;
360
+ }
361
+ });
362
+
363
+ after(async () => {
364
+ await stopServer(server, DATA_DIR);
365
+ });
366
+
367
+ it('exports the pod tree including the on-disk owner secret', async () => {
368
+ // Hard-fail rather than t.skip — a credentials regression must
369
+ // not silently turn this Credible Exit assertion into a no-op.
370
+ assert.ok(ownerToken,
371
+ 'pre-condition: IDP credentials must return a token; a silent ' +
372
+ 'skip here would mask a regression in single-user authentication');
373
+ const res = await fetch(`${baseUrl}/idp/account/export`, {
374
+ headers: { Authorization: `Bearer ${ownerToken}` }
375
+ });
376
+ assert.strictEqual(res.status, 200);
377
+ const buf = Buffer.from(await res.arrayBuffer());
378
+ const files = await unpackTarGz(buf);
379
+
380
+ const manifest = JSON.parse(files['jss-export/manifest.json'].toString('utf8'));
381
+ assert.strictEqual(manifest.mode, 'single-user',
382
+ 'manifest.mode reflects the server mode, not the existence of an account record');
383
+ assert.strictEqual(manifest.podName, 'me',
384
+ 'singleUserName="me" → pod is at <DATA_ROOT>/me/ → podName is "me"');
385
+ // Single-user manifest now includes account-derived fields when an
386
+ // account record exists, matching the multi-user manifest shape so
387
+ // a downstream importer doesn't see different shapes per server mode.
388
+ assert.strictEqual(manifest.username, 'me');
389
+ assert.match(manifest.webId, /me\/profile\/card\.jsonld#me$/);
390
+ assert.ok(manifest.createdAt, 'manifest.createdAt must be populated from the seeded account');
391
+
392
+ // The on-disk secret must be in the archive — Credible Exit
393
+ // requires the user can leave with their identity, not just
394
+ // their bytes. Refusing to include the secret would make L4+
395
+ // identity migration impossible.
396
+ const podKeys = Object.keys(files).filter(k => k.startsWith('jss-export/pod/'));
397
+ assert.ok(
398
+ podKeys.some(k => k.endsWith('private/privkey.jsonld')),
399
+ `/private/privkey.jsonld must be in the archive (Credible Exit). Pod entries: ${podKeys.join(', ')}`
400
+ );
401
+ // And the WebID profile carrying the public side.
402
+ assert.ok(podKeys.some(k => k.endsWith('profile/card.jsonld')));
403
+ });
404
+
405
+ it('rejects an authenticated third-party WebID with 403', async () => {
406
+ // Single-user mode previously trusted ANY successfully-authenticated
407
+ // WebID and shipped the entire pod (incl. /private/privkey.jsonld)
408
+ // to the caller. If the server accepts external Solid-OIDC issuers,
409
+ // LWS-CID JWTs, or any non-local WebID, that meant a third party's
410
+ // bearer token was sufficient to download the operator's secret.
411
+ //
412
+ // The handler now refuses with 403 when the authenticated WebID
413
+ // does NOT match the seeded single-user account — same shape as
414
+ // the multi-user "no local account record" 403.
415
+ //
416
+ // We mint the third-party token with createToken (same HMAC
417
+ // SECRET the server uses) so verifyToken accepts the signature
418
+ // and getWebIdFromRequestAsync resolves to the foreign WebID.
419
+ const intruderWebId = 'http://attacker.example.com/profile/card.jsonld#me';
420
+ const intruderToken = createToken(intruderWebId, 3600);
421
+ const res = await fetch(`${baseUrl}/idp/account/export`, {
422
+ headers: { Authorization: `Bearer ${intruderToken}` }
423
+ });
424
+ assert.strictEqual(res.status, 403,
425
+ 'authenticated-but-not-owner WebID must NOT receive the pod export');
426
+ const body = await res.json();
427
+ assert.strictEqual(body.error, 'forbidden');
428
+ });
429
+ });