Skip to content

feat: GET /idp/account/export — self-service pod data download (#353) - #449

Merged
melvincarvalho merged 10 commits into
gh-pagesfrom
issue-353-pod-data-export
May 14, 2026
Merged

melvincarvalho merged 10 commits into
gh-pagesfrom
issue-353-pod-data-export

Conversation

@melvincarvalho

@melvincarvalho melvincarvalho commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

GET /idp/account/export — authenticated owner downloads their pod tree as a streamed tar.gz. The L0-3 backup MVP from the Credible Exit ladder (#448), and the third leg of the user-rights trio (#351 password change, #352 account delete, this).

Archive shape

jss-export/
├── manifest.json   — webId, username, email, podName, mode,
│                     createdAt, exportedAt, jssVersion
├── account.json    — allowlisted fields only (id, webId,
│                     username, email, podName, createdAt, etc.)
│                     Never carries passwordHash, passkey
│                     credentials, OIDC client secrets, or any
│                     non-allowlisted field — adding a new
│                     allowlisted field requires security review.
└── pod/...         — entire pod tree, including /private/

In single-user root pod mode (podDir = dataRoot), ROOT_POD_EXCLUDE keeps server-internal directories out of the archive: .idp/ (IDP accounts incl. passwordHash for every user, IDP signing keys, OIDC adapter state) and .private/ (pay handler's Bitcoin keypair + UTXO state — drainable). Adding a new server-managed dotfile dir at the data root WITHOUT updating this set is a security bug; the regression test pins the property "no IdP secrets in the export" against on-disk seeded files.

Authorization

  • Multi-user: caller's WebID must resolve to a local account record (findByWebId); else 403.
  • Single-user: same — caller's WebID must match the seeded single-user account; an authenticated third-party WebID (external Solid-OIDC, LWS-CID JWT, etc.) gets 403, not the operator's /private/privkey.jsonld.

Design call: include /private/privkey.jsonld?

Yes. Per the Credible Exit framing in #448, the user's secret IS theirs and must leave with them. Refusing to export it would make L4+ identity migration impossible. The endpoint is owner-authenticated; the secret never leaves the WAC perimeter to anyone but the owner.

Streaming

tar.pack → zlib.createGzip → reply. Memory stays constant regardless of pod size — a multi-GB pod doesn't OOM. Stream-error handler destroys the pipeline on mid-pack failures (so clients see an aborted transfer rather than a silently-truncated archive). Client-disconnect handler on reply.raw.on('close') short-circuits the walk so we don't keep reading every file in a multi-GB pod into a dead socket.

Rate limiting

3/min, keyed by source IP, consistent with the other /idp/ endpoints. Per-WebID keying isn't possible in the current code path: the global auth hook in src/server.js skips /idp/* (so request.webId is unset at the rate-limit phase) and @fastify/rate-limit's keyGenerator is sync, so we can't await token verification inline. Per-user keying is a follow-up that needs a preParsing hook resolving auth before the limiter runs. Operators behind a NAT: the limit is shared across all users on the source IP.

Tests

test/idp-export.test.js — 6/6 passing locally, full suite green.

  • 401 unauthenticated
  • 200 for the authenticated owner — valid tar.gz with manifest + account + pod tree
  • account.json allowlist (no passwordHash)
  • Cross-account: alice plants a uniquely-named canary file; bob's archive contains neither the canary name nor the canary body bytes
  • Single-user-root-pod denylist: .idp/accounts/*.json and .private/keypair.json synthesized on disk pre-export, asserted absent from archive
  • Single-user + --provision-keys: archive contains the on-disk /private/privkey.jsonld (Credible Exit), manifest carries username/email/createdAt parity with multi-user
  • Single-user 403: third-party HMAC token with attacker.example.com WebID gets 403, not the operator's pod

process.env.DATA_ROOT is snapshotted/restored in startServer/stopServer to prevent cross-test leakage to subsequent test files in the same run.

New dep

tar-stream@^3.2.0. Pure JS, no native bindings. Functional install footprint on Node is just tar-stream (~60K) — but the npm install also drops streamx, b4a, and the bare-* family (bare-fs, bare-os, bare-path, bare-stream, bare-url, bare-events) totaling ~4.4 MB on disk. Those bare-* packages exist for the Bare runtime and are lazy-loaded only when running outside Node — on Node they sit on disk but never load, contributing zero runtime weight. Verified install + tests run cleanly on the Termux/mobile target.

The disk footprint matters more for our mobile/embedded targets than I'd want — tracked as #450 (replace tar-stream with a leaner producer, e.g. ~200 lines of hand-rolled POSIX ustar). Out of scope here; ship the working endpoint, optimize the dep tree as a focused follow-up.

Out of scope (per #353)

  • Re-import / cross-server pod migration (separate spec problem)
  • Periodic / scheduled backups (operator concern, not per-user right)
  • Partial / per-resource selection (defer until someone asks)
  • UI button on /idp/account (endpoint first, UI follow-up)
  • Per-WebID rate-limit keying (follow-up: needs preParsing-hook auth resolution)

Closes #353. First slice of #448.

The export side of the user-rights trio (#351 password change,
#352 account delete, this). MVP slice of the Credible Exit ladder
(#448) — the L0-3 'take your stuff with you' deliverable.

Authenticated owner gets a streamed tar.gz containing:
  jss-export/
    manifest.json   — webId, username, email, podName, mode,
                      createdAt, exportedAt, jssVersion
    account.json    — full account record minus passwordHash
                      (single-user without an IDP account: omitted)
    pod/...         — entire pod tree, including /private/

Per the Credible Exit framing in #448, /private/privkey.jsonld
IS included in the archive when the pod was provisioned with
--provision-keys. The user's secret is theirs; refusing to export
would make L4+ identity migration impossible. The endpoint is
owner-authenticated; the secret never leaves the WAC perimeter
to anyone but the owner.

Streaming pipeline: tar.pack → zlib.createGzip → reply. Memory
stays constant regardless of pod size; multi-GB pods don't OOM.
Per-IP rate limit at 3/min — heavy read, but a legitimate
operator pulling a backup shouldn't hit it.

Failure modes:
  401 — unauthenticated
  403 — multi-user: no account for the caller's WebID
  404 — pod directory unexpectedly missing

Out of scope (per the issue): re-import, cross-server pod
migration, periodic scheduled backups, partial / per-resource
selection, UI button on /idp/account.

New dep: tar-stream@^3.2.0. Pure JS, ~20KB, no native bindings —
runs cleanly on Termux / mobile per the deployment target.

Tests:
  - 401 unauthenticated
  - 200 owner export → valid tar.gz with manifest + account +
    pod tree
  - account.json never carries passwordHash
  - cross-account: each authenticated caller can only get their
    own data (the endpoint takes no target parameter)
  - single-user + --provision-keys: archive contains the on-disk
    /private/privkey.jsonld

864/864 tests pass.

Closes #353. First slice of #448.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds a self-service GET /idp/account/export endpoint that lets an authenticated owner stream their pod tree as a tar.gz, plus a manifest.json and a passwordHash-stripped account.json. This is the "L0-3 backup MVP" from the Credible Exit ladder (#448) and the third entry in the user-rights trio with #351 and #352. The archive intentionally includes /private/privkey.jsonld when present so users can take their identity with them.

Changes:

  • New src/idp/export.js handler that walks the pod directory and pipes tar.pack → zlib.createGzip → reply.
  • Wire-up in src/idp/index.js (route + 3/min/IP rate limit) and src/server.js (threads singleUserName and jssVersion into the IdP plugin).
  • Adds tar-stream@^3.2.0 (and its transitive deps) and a new test suite covering multi-user happy path, manifest shape, passwordHash exclusion, cross-account property, and single-user --provision-keys privkey inclusion.

Reviewed changes

Copilot reviewed 5 out of 6 changed files in this pull request and generated 10 comments.

Show a summary per file
File Description
src/idp/export.js New tar.gz pod-export handler with manifest + account stripping.
src/idp/index.js Mounts GET /idp/account/export, threads new options, adds rate limit.
src/server.js Reads package.json synchronously to thread jssVersion (and singleUserName) into the IdP plugin.
package.json / package-lock.json Adds tar-stream@^3.2.0 and its transitive b4a/bare-*/streamx deps; reorders @noble/* entries.
test/idp-export.test.js New test suite for the export endpoint (multi-user + single-user + provision-keys).

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread src/idp/export.js Outdated
Comment on lines +72 to +80
podDir = isRootPod
? dataRoot
: path.join(dataRoot, options.singleUserName);

accountRecord = await findByWebId(webId); // may be null in --no-idp mode
manifest = {
webId,
mode: 'single-user',
podName: isRootPod ? null : options.singleUserName,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CRITICAL — addressed. Added a first-level denylist (currently {.idp}) applied only in single-user root-pod mode where podDir is the data root. Named-pod / multi-user paths don't hit this since the tree is already isolated by the filesystem layout. New regression test in test/idp-export.test.js provisions a root pod, asserts .idp/ exists on disk pre-export, and confirms nothing from it lands in the archive. Pre-condition assert means the test is meaningful (would fail if the IdP somehow stopped writing to .idp/).

Comment thread src/idp/index.js Outdated
Comment on lines 27 to 32
} from './credentials.js';
import { handleExportAccount } from './export.js';
import {
handleAccountDeleteForm,
setNoCacheClickjackHeaders,
} from './credentials.js';

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed: merged the two from ./'credentials.js' blocks into one statement.

Comment thread src/idp/export.js Outdated
Comment on lines +171 to +203
// Pod tree. Walk the directory, stream each file in turn. Symlinks
// are followed (we want the file content, not the link metadata).
await walkAndPack(pack, podDir, 'jss-export/pod');

pack.finalize();
}

/**
* Recursively pack `dir` into `pack` under the tar prefix `tarBase`.
*/
async function walkAndPack(pack, dir, tarBase) {
const entries = await fsp.readdir(dir, { withFileTypes: true });
for (const dirent of entries) {
const fullPath = path.join(dir, dirent.name);
const tarPath = `${tarBase}/${dirent.name}`;
if (dirent.isDirectory()) {
await walkAndPack(pack, fullPath, tarPath);
} else if (dirent.isFile()) {
const stat = await fsp.stat(fullPath);
// Stream the file into the entry — keeps memory constant
// even for large media files in a pod.
await new Promise((resolve, reject) => {
const entry = pack.entry(
{ name: tarPath, size: stat.size, mode: stat.mode & 0o777 },
(err) => err ? reject(err) : resolve(),
);
fs.createReadStream(fullPath).pipe(entry);
});
}
// Symlinks, sockets, etc. are intentionally skipped — they're
// out of scope for "downloadable pod data" and would complicate
// restore semantics without serving a real use case.
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed: removed the misleading symlink-following comment. The implementation uses dirent.isFile() and intentionally skips non-regular entries; the older comment was wrong about behaviour. The remaining comment correctly documents the skip.

Comment thread src/idp/export.js Outdated
Comment on lines +189 to +198
const stat = await fsp.stat(fullPath);
// Stream the file into the entry — keeps memory constant
// even for large media files in a pod.
await new Promise((resolve, reject) => {
const entry = pack.entry(
{ name: tarPath, size: stat.size, mode: stat.mode & 0o777 },
(err) => err ? reject(err) : resolve(),
);
fs.createReadStream(fullPath).pipe(entry);
});

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed: open the fd once via fsp.open, fstat off the same fd, stream via createReadStream({autoClose:false}) on that fd, close in a finally. A concurrent truncate/grow can't desync the declared tar size from the bytes actually piped now.

Comment thread test/idp-export.test.js Outdated
Comment on lines +145 to +165
it("returns 403 for an authenticated caller exporting somebody else's account", async () => {
// bob is authenticated, but the export endpoint scopes to the
// caller's WebID — bob can only get bob's data, never alice's.
// The endpoint doesn't take a target parameter; cross-account is
// already prevented by design. This test pins that property by
// confirming bob's export contains bob, never alice.
const res = await fetch(`${baseUrl}/idp/account/export`, {
headers: { Authorization: `Bearer ${bobToken}` }
});
assert.strictEqual(res.status, 200);
const buf = Buffer.from(await res.arrayBuffer());
const files = await unpackTarGz(buf);
const manifest = JSON.parse(files['jss-export/manifest.json'].toString('utf8'));
assert.strictEqual(manifest.username, 'bob');
assert.strictEqual(manifest.podName, 'bob');
// No alice/* in bob's export.
const podKeys = Object.keys(files).filter(k => k.startsWith('jss-export/pod/'));
for (const k of podKeys) {
assert.doesNotMatch(k, /\/alice\//, `bob's export must not contain alice's data: ${k}`);
}
});

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed: renamed test to 'scopes the export to the authenticated caller — no cross-account exposure' to reflect what it actually proves (cross-account is structurally impossible since the endpoint takes no target parameter). Updated the export.js header comment + PR description to drop the inaccurate 403 cross-account claim.

Comment thread src/server.js
Comment on lines +331 to +338
let jssVersion = 'unknown';
try {
// Synchronous read — createServer isn't async, and the file is
// tiny + on local disk. Same approach the existing config code
// uses for package.json metadata.
const pkgRaw = readFileSync(join(__dirname, '..', 'package.json'), 'utf8');
jssVersion = JSON.parse(pkgRaw).version;
} catch { /* keep 'unknown' */ }

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Acknowledged but not addressing in this PR — two callsites, two lines each. Hoisting into a single helper would be ~15 lines of import/export plumbing for what is currently sync-vs-async incompatibility (createServer can't await readFile easily). Worth doing in a small refactor pass when there's a third call site.

Comment thread src/idp/export.js
Comment on lines +132 to +154
const pack = tar.pack();
const gzip = zlib.createGzip();
pack.pipe(gzip);

// Pump in the background; entries are added asynchronously below.
const streamingPromise = packExport({
pack,
podDir,
manifest,
accountRecord,
}).catch((err) => {
// Once headers + body bytes are out, the only thing we can do is
// destroy the stream and let Fastify surface the connection drop.
request.log?.error({ err }, 'pod export failed mid-stream');
pack.destroy(err);
});

// Don't await streamingPromise here — Fastify will close the
// response when `gzip` ends. We do attach the catch above so an
// error during traversal is logged instead of being swallowed.
void streamingPromise;

return reply.send(gzip);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed: pack.on('error') and gzip.on('error') handlers added. On stream failure the pipeline is destroyed (severs the response) and the error is logged server-side. Better to truncate-and-fail than 200-and-silently-corrupt.

Comment thread src/idp/export.js Outdated
Comment on lines +181 to +204
async function walkAndPack(pack, dir, tarBase) {
const entries = await fsp.readdir(dir, { withFileTypes: true });
for (const dirent of entries) {
const fullPath = path.join(dir, dirent.name);
const tarPath = `${tarBase}/${dirent.name}`;
if (dirent.isDirectory()) {
await walkAndPack(pack, fullPath, tarPath);
} else if (dirent.isFile()) {
const stat = await fsp.stat(fullPath);
// Stream the file into the entry — keeps memory constant
// even for large media files in a pod.
await new Promise((resolve, reject) => {
const entry = pack.entry(
{ name: tarPath, size: stat.size, mode: stat.mode & 0o777 },
(err) => err ? reject(err) : resolve(),
);
fs.createReadStream(fullPath).pipe(entry);
});
}
// Symlinks, sockets, etc. are intentionally skipped — they're
// out of scope for "downloadable pod data" and would complicate
// restore semantics without serving a real use case.
}
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed: walkAndPack now emits an explicit pack.entry({type:'directory'}) for each visited directory before recursing. Empty LDP containers survive round-trip restore.

Comment thread src/idp/index.js
Comment on lines +308 to +315
fastify.get('/idp/account/export', {
config: {
rateLimit: {
max: 3,
timeWindow: '1 minute',
keyGenerator: (request) => request.ip
}
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed: rate limit now keyed by request.webId with IP fallback. One user's heavy backup pull no longer locks out everyone behind a shared NAT / proxy egress.

Comment thread src/idp/export.js
Comment on lines +123 to +130
const slug = sanitizeSlug(webId);
const isoDate = manifest.exportedAt.replace(/[:.]/g, '-');
const filename = `jss-export-${slug}-${isoDate}.tar.gz`;

reply
.type('application/x-tar+gzip')
.header('Content-Disposition', `attachment; filename="${filename}"`)
.header('Cache-Control', 'no-store');

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed: added an RFC 5987 filename*=UTF-8''… form alongside the legacy filename= value. sanitizeSlug already restricts to [A-Za-z0-9._-] so today the two forms produce identical text, but a future change that lets non-ASCII through would now degrade to valid percent-encoding rather than a malformed header.

#449)

Ten batched pickups from Copilot. The first is security-critical;
the rest are real cleanup.

CRITICAL — single-user root-pod data leak. In root-pod single-user
mode (the default since #348), podDir IS dataRoot — and dataRoot
contains .idp/accounts/*.json (every IdP account incl.
passwordHash) and .idp/keys/ (the IdP signing keys that mint
tokens for any user). The previous handler walked the directory
naively and would have shipped all of that to the caller, then
shrugged off responsibility because account.json had passwordHash
stripped — the same hashes (and worse) re-leaked via the raw walk.
Add a first-level denylist (currently {.idp}) applied only when
podDir is the data root. Named-pod / multi-user paths don't hit
this code path because the pod tree is already isolated by the
filesystem layout. New regression test pins the property by
provisioning a root pod, asserting the .idp/ tree exists on disk,
and confirming nothing from it lands in the archive.

Other fixes batched into the same commit:

- Stream-level error handler. pack.on('error') + gzip.on('error')
  now log + destroy the pipeline so an EACCES / mid-pack failure
  doesn't silently produce a 200 + truncated gzip.
- Empty-directory tar entries via pack.entry({ type: 'directory' }).
  Preserves LDP container shape on round-trip restore — without
  this, an empty container provisioned by the operator vanishes.
- TOCTOU on stat→read fix. Open the fd once, fstat off the same
  fd, stream through createReadStream({ autoClose: false }). A
  concurrent truncate/grow can no longer desync the declared tar
  size from the bytes piped, which would otherwise produce a
  corrupt tar that fails extraction.
- Rate limit keyed by request.webId with IP fallback. One user's
  heavy backup pull no longer locks out everyone behind a shared
  NAT / proxy egress.
- Merged the duplicate `import from './credentials.js'` blocks in
  src/idp/index.js — the split was a diff artifact.
- Removed the contradictory symlink comment. The implementation
  uses dirent.isFile() and intentionally skips non-regular
  entries; the older "follows symlinks" comment was wrong.
- Renamed the cross-account test ('scopes the export to the
  authenticated caller — no cross-account exposure') to reflect
  what it actually proves. The endpoint takes no target parameter
  so cross-account is structurally impossible; the docstring +
  PR description claim of 403 was inaccurate. Removed the 403
  claim from the export.js header.
- Content-Disposition: added the RFC 5987 `filename*=UTF-8''…`
  fallback so a future non-ASCII slip through sanitizeSlug
  degrades to valid percent-encoding rather than a malformed
  header.

Out of scope here: hoisting the duplicate package.json read into
a single helper (#449 review #9). Two callsites, two lines each;
not worth the refactor right now.

865/865 tests pass.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 6 changed files in this pull request and generated 7 comments.

Comment thread src/idp/export.js Outdated
Comment on lines +47 to +55
* naively would ship the IdP accounts (incl. passwordHash for every
* user), the IdP signing keys (mint tokens for any user), and OIDC
* adapter state (sessions, refresh tokens) to the caller. Skip them.
*
* Named-pod single-user (podDir = <dataRoot>/<name>/) and multi-user
* (podDir = <dataRoot>/<podName>/) don't hit this code path — the
* pod tree is already isolated by the path layout.
*/
const ROOT_POD_EXCLUDE = new Set(['.idp']);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caught — and you're right that this is the same class of catastrophic leak as .idp. Confirmed two paths at <dataRoot>/:

  • .private/keypair.json + .private/utxos.json — pay handler's Bitcoin keypair + UTXO state. Recipient could drain pay balance / spend UTXOs.
  • .well-known/webledgers/* — these are public-by-spec (any HTTP client can curl them under .well-known/), so they're part of the pod's public surface and stay in the export. Including them is consistent with the pod's existing public reachability.

Fix in 9ce7403:

  • ROOT_POD_EXCLUDE expanded to new Set(['.idp', '.private']).
  • Denylist regression test now synthesizes .private/keypair.json on disk pre-export and asserts no jss-export/pod/.private/* entries appear in the archive — same shape as the .idp/ assertion so a future regression can't slip through.

The "deny by name only the things we can think of today" concern you raised in the account.json comment also applied here at the directory level — addressed by the test now exercising both real on-disk entries and asserting on the leak shape, not the implementation. New entries to the denylist still need a corresponding regression test.

Comment thread src/idp/index.js
Comment on lines +311 to +318
fastify.get('/idp/account/export', {
config: {
rateLimit: {
max: 3,
timeWindow: '1 minute',
keyGenerator: (request) => request.webId || request.ip
}
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right — request.webId is unset at the rate-limit phase because the global onRequest auth hook in src/server.js explicitly skips /idp/*, and @fastify/rate-limit's keyGenerator runs sync before any preHandler. So the WebID branch was always dead and only the IP fallback ran. The comment overpromised.

Honest fix in 9ce7403:

  • Dropped request.webId from the keyGenerator. Now keyed by IP, consistent with every other /idp/ rate-limit in the file.
  • Updated the comment to explain why per-user keying needs a preParsing hook resolving auth before the limiter, and flagged it as a follow-up.

Verifying inside keyGenerator was tempting but it's sync — we can't await token verification cleanly there, and an unverified header-based key would let a caller rotate keys to bypass the limit. Better to defer to the proper preParsing-hook fix than ship something that looks per-user but isn't.

Comment thread src/idp/export.js
Comment on lines +159 to +191
const pack = tar.pack();
const gzip = zlib.createGzip();
pack.pipe(gzip);

// Surface stream-level errors. Once response headers are out an
// EACCES / mid-pack failure can otherwise present as a silently
// truncated download — the client gets 200 + partial gzip + no
// error signal. We log on the server side and destroy the
// pipeline so the client at least sees an aborted transfer rather
// than a corrupt but seemingly-complete archive.
const onStreamError = (err) => {
request.log?.error({ err }, 'pod export stream error');
pack.destroy(err);
gzip.destroy(err);
};
pack.on('error', onStreamError);
gzip.on('error', onStreamError);

// Pump in the background; entries are added asynchronously below.
// The root-pod denylist is wired in so single-user-root-pod mode
// doesn't ship .idp/ (accounts + signing keys + OIDC state).
const streamingPromise = packExport({
pack,
podDir,
manifest,
accountRecord,
excludeAtRoot: (options.singleUser && isRootPod) ? ROOT_POD_EXCLUDE : null,
}).catch(onStreamError);

void streamingPromise;

return reply.send(gzip);
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed — without the close handler, walkAndPack keeps reading every file in a multi-GB pod into a gzip whose downstream socket is gone, burning fds and IO until the walk finishes naturally.

Fix in 9ce7403: reply.raw.on('close', ...) checks !reply.raw.writableEnded (so a normal end doesn't trigger), logs the abort via request.log.warn, and destroys both pack and gzip. The destroy propagates an error up walkAndPack which short-circuits the next fsp.readdir / fsp.open and the open file descriptor closes via the existing finally { await fh.close() } block.

Comment thread test/idp-export.test.js Outdated
Comment on lines +160 to +164
// No alice/* in bob's export.
const podKeys = Object.keys(files).filter(k => k.startsWith('jss-export/pod/'));
for (const k of podKeys) {
assert.doesNotMatch(k, /\/alice\//, `bob's export must not contain alice's data: ${k}`);
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair catch — the /alice/ regex was tautological because the pod-tree prefix is jss-export/pod/... with no username segment embedded. It would have passed even if bob's archive contained alice's actual files.

Fix in 9ce7403:

  • Alice plants a uniquely-named canary file (alice-canary-do-not-leak.txt with body ALICE_SECRET_CANARY_a7f3e9d1c4b2) at <DATA_ROOT>/alice/ in before().
  • Bob's export must contain neither the canary filename (in any entry name) nor the canary body bytes (in any entry contents). Both conditions checked across all archive entries.
  • Added account.username === 'bob' and account.email === '[email protected]' checks against account.json — guards a different bug class where the wrong account record is looked up but the manifest is built from the request webId.

The combined assertions now anchor on actual files-on-disk identity rather than the archive's prefix layout.

Comment thread test/idp-export.test.js Outdated
Comment on lines +202 to +205
if (!ownerToken) {
t.skip('IDP credentials handshake unavailable');
return;
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right — silent t.skip defeats the entire point of the test. A credentials regression would turn the denylist assertion (the most security-critical test in the file) into a no-op while the suite still reports green.

Fix in 9ce7403: replaced both t.skip calls with assert.ok(ownerToken, ...) in the root-pod denylist test and the --provision-keys test. Now a credentials shape change fails loudly with a pre-condition assertion identifying the regression, instead of masquerading as coverage.

Comment thread src/idp/export.js Outdated
Comment on lines +201 to +205
if (accountRecord) {
const { passwordHash: _omit, ...safeAccount } = accountRecord;
await addEntry(pack, 'jss-export/account.json',
Buffer.from(JSON.stringify(safeAccount, null, 2), 'utf8'));
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed — denylist-by-field-name is fragile across account-schema growth. Anything new added to the account record (passkey credential records, OIDC client secrets, recovery tokens) would silently land in exports without a security review.

Fix in 9ce7403: introduced ACCOUNT_EXPORT_FIELDS allowlist:

const ACCOUNT_EXPORT_FIELDS = [
  'id', 'webId', 'username', 'email', 'podName', 'createdAt', 'updatedAt',
  'passwordChangedAt', 'lastLoginAt',
];

Construction switched from { passwordHash: _omit, ...rest } to a loop that copies only allowlisted keys with !== undefined. Adding a new export field now requires an explicit code change with a security-review comment in the JSDoc. Passkey credentials are intentionally not on the list — device-bound, not portable to a fresh server.

Comment thread src/idp/export.js Outdated
// pipeline so the client at least sees an aborted transfer rather
// than a corrupt but seemingly-complete archive.
const onStreamError = (err) => {
request.log?.error({ err }, 'pod export stream error');

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tiny but right — Fastify always decorates request with log, so the optional chain hides a typo and is inconsistent with the rest of the codebase. Fixed in 9ce7403 — request.log.error(...) directly. Same convention used for the new request.log.warn in the disconnect handler.

…it (#449)

- ROOT_POD_EXCLUDE: add `.private` (pay handler's Bitcoin keypair +
  UTXO state). Without this, single-user root-pod export ships a
  drainable Bitcoin keypair to the recipient. Same class of leak
  as `.idp/`, missed in the first pass.
- account.json: switch from denylist (`{ passwordHash: _omit, ...rest }`)
  to allowlist (`ACCOUNT_EXPORT_FIELDS`). Future secret-bearing
  fields (passkey credentials, OIDC client secrets, recovery
  tokens) won't silently land in exports without a security review.
- Client-disconnect handler on `reply.raw.on('close')`: destroy
  pack + gzip when the socket goes away so walkAndPack stops
  reading every file in a multi-GB pod into a dead pipeline.
- Stop misleading rate-limit-by-WebID: /idp/* skips the global auth
  hook so `request.webId` is always undefined here, meaning the
  fallback to IP was the only thing actually running. Documented
  honestly; per-user keying is a follow-up needing pre-rate-limit
  auth resolution.
- Tests: hard-assert ownerToken instead of `t.skip()` (a creds
  regression must not silently turn the denylist + Credible-Exit
  assertions into no-ops). Cross-account test seeds an alice-only
  canary file + asserts bob's archive contains neither the name
  nor the bytes (prior `/alice/` regex was tautological — the
  archive prefix never embeds a username segment). Denylist test
  also synthesizes `.private/keypair.json` so it asserts a real
  on-disk entry isn't packed.
- Tiny: drop `request.log?.` optional chaining; Fastify always
  decorates the request with `log`.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 6 changed files in this pull request and generated 7 comments.

Comment thread src/idp/export.js Outdated
Comment on lines +126 to +127
mode: 'single-user',
podName: isRootPod ? null : options.singleUserName,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch — the multi-user branch built the manifest from accountRecord (username, email, createdAt) but the single-user branch only emitted { webId, mode, podName, exportedAt, jssVersion }. A downstream importer would see two different shapes for no documented reason.

Fix in fefe1ad: when an account record is resolved in single-user mode, populate the same fields from it. Combined with the 403 fix in the next thread (single-user now requires a matching local account), the single-user manifest is now always a strict superset of the documented shape — never a subset. The --provision-keys test asserts username, webId, and createdAt are present so a future regression breaks loudly.

Comment thread src/idp/export.js
Comment on lines +114 to +130
if (options.singleUser) {
// Single-user: pod is at `/` (root pod) or `/<name>/` based on
// singleUserName. There's at most one IDP account; if it exists
// include it, else emit a single-user manifest with no account.
isRootPod = !options.singleUserName;
podDir = isRootPod
? dataRoot
: path.join(dataRoot, options.singleUserName);

accountRecord = await findByWebId(webId); // may be null in --no-idp mode
manifest = {
webId,
mode: 'single-user',
podName: isRootPod ? null : options.singleUserName,
exportedAt: new Date().toISOString(),
jssVersion: options.jssVersion ?? 'unknown',
};

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Critical catch — this is the most important comment in the review. You're right: in single-user mode the previous code accepted ANY successfully-authenticated WebID and shipped the entire pod, including /private/privkey.jsonld. With external Solid-OIDC issuers / LWS-CID JWTs in scope, a third-party bearer would suffice to download the operator's owner key.

Fix in fefe1ad:

accountRecord = await findByWebId(webId);
if (!accountRecord) {
  return reply.code(403).send({
    error: 'forbidden',
    error_description:
      'Authenticated WebID does not match the single-user account',
  });
}

Same shape as the multi-user 403. The route is only mounted when idpEnabled, and seedSingleUserIdpAccount runs at startup, so a missing account record can only mean "caller is not the seeded owner".

Test in fefe1ad: mint a third-party HMAC token via createToken('http://attacker.example.com/profile/card.jsonld#me', 3600) (same SECRET as the server, so verifyToken accepts the signature and getWebIdFromRequestAsync resolves to the foreign WebID), call /idp/account/export with that bearer, assert 403 + error: 'forbidden'. Passes.

Comment thread src/idp/export.js
* (podDir = <dataRoot>/<podName>/) don't hit this code path — the
* pod tree is already isolated by the path layout.
*/
const ROOT_POD_EXCLUDE = new Set(['.idp', '.private']);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Considered the allowlist flip and decided against it. Pod content is open-ended — operators and apps create arbitrary top-level containers, and an allowlist would silently drop legitimate user data, breaking Credible Exit (the whole point of the endpoint). The trade-off you're flagging is real, though, so fefe1ad pays it down with two reinforcements:

  1. Inline security-critical guidance in ROOT_POD_EXCLUDE that adding a new server-managed dotfile dir at the data root without updating this set + adding a regression test is a security bug that re-leaks. Adding it in the same PR as the new dir is now an explicit code-review requirement.

  2. Strengthened the denylist test to assert the property ("no IdP secrets in the export") rather than the implementation ("no entries under one specific dotted prefix"). The pre-condition now reads .idp/accounts/*.json from disk and asserts at least one secret-bearing file is present pre-export — so a future refactor that moves IdP secrets out of .idp/accounts/ fails the pre-condition loudly and forces the denylist + assertion to be re-pinned to wherever the secrets moved.

Net effect: a future feature dropping a secret-bearing dir at the data root would still need to go through code review with a security-review gate at ROOT_POD_EXCLUDE, and the test pattern is now reusable for any new secret-bearing dir.

Comment thread src/idp/index.js
Comment on lines +307 to +320
// Keyed by IP, consistent with the other /idp/ endpoints. We can't
// honestly key by WebID here: the global auth hook in src/server.js
// skips /idp/* (so request.webId is unset at this phase) and the
// rate-limit keyGenerator is sync, so we can't await token
// verification inline. Per-user keying is a follow-up that needs
// a preParsing hook resolving auth before the limiter runs.
fastify.get('/idp/account/export', {
config: {
rateLimit: {
max: 3,
timeWindow: '1 minute',
keyGenerator: (request) => request.ip
}
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reconciled in fefe1ad and the previous commit (9ce7403):

  • keyGenerator (src/idp/index.js): request.ip only. The earlier request.webId || request.ip was dead code (/idp/* skips the global auth hook, and the rate-limit keyGenerator runs sync before any preHandler) — the IP fallback was the only thing actually firing.
  • Inline comment: now states explicitly that we can't honestly key by WebID here without a preParsing hook resolving auth before the limiter, and flags it as a follow-up.
  • PR description: updated to drop the per-WebID claim, document the IP-only quota semantics, and link the follow-up.

Operators behind a NAT now have an accurate model: the limit is 3/min per source IP, shared across all users on that IP. Heavier per-user keying needs the preParsing-hook follow-up.

Comment thread src/idp/export.js Outdated
? dataRoot
: path.join(dataRoot, options.singleUserName);

accountRecord = await findByWebId(webId); // may be null in --no-idp mode

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right — the comment was misleading. The route is mounted by idpPlugin which is only registered when idpEnabled (src/server.js:324), so accountRecord can never be null because IdP is disabled.

In fefe1ad the comment is replaced (and the underlying code is no longer permissive on null): single-user mode now refuses with 403 when accountRecord is null, which can only happen if the caller's WebID doesn't match the seeded local account. The new comment explains exactly that — "third-party identity, NOT the pod owner, must not get the operator's /private/privkey.jsonld" — pointing at seedSingleUserIdpAccount for the seeded-owner contract.

Comment thread test/idp-export.test.js
Comment on lines +263 to +294
);
assert.ok(
await fs.pathExists(path.join(DATA_DIR, '.idp')),
'pre-condition: .idp/ must exist on disk for the test to be meaningful'
);
assert.ok(
await fs.pathExists(path.join(DATA_DIR, '.private')),
'pre-condition: .private/ must exist on disk for the test to be meaningful'
);
const res = await fetch(`${baseUrl}/idp/account/export`, {
headers: { Authorization: `Bearer ${ownerToken}` }
});
assert.strictEqual(res.status, 200);
const buf = Buffer.from(await res.arrayBuffer());
const files = await unpackTarGz(buf);

// Critical: NOTHING under jss-export/pod/.idp/ or jss-export/pod/.private/.
const leakedEntries = Object.keys(files).filter(k =>
k.startsWith('jss-export/pod/.idp/') || k === 'jss-export/pod/.idp' ||
k.startsWith('jss-export/pod/.private/') || k === 'jss-export/pod/.private'
);
assert.strictEqual(leakedEntries.length, 0,
`Server-internal dirs must not be packed in root-pod export. ` +
`Found: ${leakedEntries.join(', ')}`);

// Sanity: actual pod content IS in the archive.
const podKeys = Object.keys(files).filter(k => k.startsWith('jss-export/pod/'));
assert.ok(podKeys.some(k => k.endsWith('profile/card.jsonld')),
'pod content must still be exported');
assert.ok(podKeys.some(k => k.endsWith('private/privkey.jsonld')),
'pod /private/ must still be exported (this is pod data, not server-internal)');
});

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good — "the test asserts the implementation, not the property" is exactly the right framing. Fixed in fefe1ad:

const idpAccounts = await fs.readdir(path.join(DATA_DIR, '.idp', 'accounts'))
  .catch(() => []);
const accountFiles = idpAccounts.filter(f => f.endsWith('.json'));
assert.ok(accountFiles.length > 0,
  'pre-condition: .idp/accounts/*.json must exist (the actual ' +
  'secret-bearing material that the denylist must keep out of the export)');

Pre-condition now reads the actual secret-bearing files from disk. If a future refactor moves IdP secrets out of .idp/accounts/, this fails loudly and the test forces an update to the denylist + assertion — pinning the property "no IdP secrets in the export", not the path .idp/.

Comment thread test/idp-export.test.js
Comment on lines +28 to +47
async function startServer(dataDir, options = {}) {
await fs.remove(dataDir);
await fs.ensureDir(dataDir);
const server = createServer({
logger: false,
forceCloseConnections: true,
root: dataDir,
idp: true,
idpIssuer: 'http://127.0.0.1/',
...options,
});
await server.listen({ port: 0, host: '127.0.0.1' });
const baseUrl = `http://127.0.0.1:${server.server.address().port}`;
return { server, baseUrl };
}

async function stopServer(server, dataDir) {
await server.close();
await fs.remove(dataDir);
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed: createServer writes process.env.DATA_ROOT = options.root (src/server.js:175), and the test file's three describe blocks each spin one up + tear it down without restoring the env var. Any unrelated test running after this file in the same process would see a path pointing at a now-removed directory.

Fix in fefe1ad: startServer snapshots process.env.DATA_ROOT and stashes it on the returned server (server.__prevDataRoot); stopServer restores or deletes accordingly. Since both helpers are used by every before/after pair in the file, the fix covers all three describe blocks at once and any future ones in the same file.

#449)

CRITICAL FIX:
- Single-user mode previously trusted ANY successfully-authenticated
  WebID and shipped the entire pod (incl. /private/privkey.jsonld)
  to the caller. With LWS-CID JWTs / external Solid-OIDC issuers
  in scope, a third-party bearer was sufficient to download the
  operator's secret. Handler now refuses with 403 when the
  authenticated WebID does NOT match the seeded single-user
  account — same shape as the multi-user "no local account" 403.
  New test mints a third-party HMAC token and asserts 403.

Other:
- Single-user manifest now populates `username`, `email`, `createdAt`
  from the resolved account record so manifest shape matches the
  multi-user branch — downstream importers see one shape, not two.
- ROOT_POD_EXCLUDE: stronger inline guidance that adding a new
  server-internal top-level dir without updating this set + a
  regression test is a security bug. Allowlist alternative would
  break Credible Exit (drops legit user content) — denylist + test
  is the deliberate trade-off.
- Removed misleading "may be null in --no-idp mode" comment;
  idpPlugin doesn't mount when idp is disabled, so the only path
  to a null accountRecord here is the third-party-WebID case
  handled by the new 403.
- Tests: snapshot/restore process.env.DATA_ROOT around start/stop
  so cross-test leakage doesn't leave a stale path for any
  unrelated test that reads DATA_ROOT after this file runs.
- Denylist test now asserts presence of an actual secret-bearing
  file (`.idp/accounts/*.json`), not just `.idp/` existence — pins
  the property "no IdP secrets in the export", not the implementation.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 6 changed files in this pull request and generated 5 comments.

Comment thread src/idp/export.js
Comment on lines +152 to +161
manifest = {
webId: accountRecord.webId,
username: accountRecord.username,
email: accountRecord.email,
podName: isRootPod ? null : options.singleUserName,
mode: 'single-user',
createdAt: accountRecord.createdAt,
exportedAt: new Date().toISOString(),
jssVersion: options.jssVersion ?? 'unknown',
};

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Real disagreement — caught it. seedSingleUserIdpAccount writes podName: isRootPod ? 'me' : singleUserName (src/server.js:965), so root-pod accounts have account.podName === 'me' while manifest.podName was independently derived as isRootPod ? null : singleUserName. Two values for the same concept in the same archive — exactly the importer-keys-on-the-wrong-field hazard.

Fix in ec7cc46: manifest.podName = accountRecord.podName in single-user, mirroring the multi-user branch which already does manifest.podName = podName where podName = accountRecord.podName || accountRecord.username. Both branches now read podName from accountRecord — single source of truth.

Filesystem layout (root-pod vs /<name>/ pod) is conveyed by mode === 'single-user' plus the seeded podName ('me' for root-pod, singleUserName otherwise). The new root-pod manifest test asserts manifest.podName === account.podName === 'me' so the parity property is pinned and a regression to the old null-vs-'me' shape fails loudly.

Comment thread src/idp/export.js Outdated
Comment on lines +272 to +281
// Account record — allowlisted fields only. Single-user without
// an IDP account skips this (no record to include).
if (accountRecord) {
const safeAccount = {};
for (const key of ACCOUNT_EXPORT_FIELDS) {
if (accountRecord[key] !== undefined) safeAccount[key] = accountRecord[key];
}
await addEntry(pack, 'jss-export/account.json',
Buffer.from(JSON.stringify(safeAccount, null, 2), 'utf8'));
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right — both branches now 403 on null accountRecord, so packExport is unreachable with a null record. The guard was already dead.

Fix in ec7cc46: removed the if (accountRecord) conditional — account.json is now unconditionally emitted. Updated comment to "Both branches in handleExportAccount now refuse with 403 when accountRecord is null, so by the time we get here the record is always defined". A future reader reasoning about the call graph won't have to wonder whether there's a path that ships a manifest without an account record.

Comment thread src/idp/export.js
Comment on lines +228 to +248
const onStreamError = (err) => {
request.log.error({ err }, 'pod export stream error');
pack.destroy(err);
gzip.destroy(err);
};
pack.on('error', onStreamError);
gzip.on('error', onStreamError);

// Client disconnect handler. Without this, walkAndPack keeps
// reading every file in the pod, opening file descriptors, and
// pushing into a gzip whose downstream socket is gone. For a
// multi-GB pod that's wasted IO + fds until the walk finishes.
// Destroying both ends short-circuits the walk via stream error
// propagation; the request.log captures the abort for diagnostics.
reply.raw.on('close', () => {
if (!reply.raw.writableEnded) {
request.log.warn('pod export client disconnected mid-stream');
pack.destroy(new Error('client disconnected'));
gzip.destroy(new Error('client disconnected'));
}
});

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Subtle but real — pack/gzip .destroy(err) re-emits 'error' which re-enters onStreamError, and with three call sites (pack.on('error'), gzip.on('error'), streamingPromise.catch) one underlying failure produces multiple log lines.

Fix in ec7cc46:

const onStreamError = (err) => {
  if (gzip.destroyed || pack.destroyed) return;
  request.log.error({ err }, 'pod export stream error');
  pack.destroy(err);
  gzip.destroy(err);
};

First call logs + destroys; subsequent re-entries from the destroy chain see destroyed === true and short-circuit. One failure → one log line.

Comment thread src/idp/index.js
@@ -38,7 +39,7 @@ import { landingPage, accountDeletePage } from './views.js';
* @param {string} options.issuer - The issuer URL

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct — the JSDoc was stale. After singleUserName and jssVersion were threaded through for the export endpoint (and inviteOnly was added previously), only issuer was still documented.

Fix in ec7cc46: JSDoc now describes inviteOnly, singleUser, singleUserName, and jssVersion in the existing one-line-per-option style. A caller reading just the function header can now discover the export endpoint's plumbing requirements without grepping the body.

Comment thread test/idp-export.test.js
Comment on lines +293 to +312
assert.strictEqual(res.status, 200);
const buf = Buffer.from(await res.arrayBuffer());
const files = await unpackTarGz(buf);

// Critical: NOTHING under jss-export/pod/.idp/ or jss-export/pod/.private/.
const leakedEntries = Object.keys(files).filter(k =>
k.startsWith('jss-export/pod/.idp/') || k === 'jss-export/pod/.idp' ||
k.startsWith('jss-export/pod/.private/') || k === 'jss-export/pod/.private'
);
assert.strictEqual(leakedEntries.length, 0,
`Server-internal dirs must not be packed in root-pod export. ` +
`Found: ${leakedEntries.join(', ')}`);

// Sanity: actual pod content IS in the archive.
const podKeys = Object.keys(files).filter(k => k.startsWith('jss-export/pod/'));
assert.ok(podKeys.some(k => k.endsWith('profile/card.jsonld')),
'pod content must still be exported');
assert.ok(podKeys.some(k => k.endsWith('private/privkey.jsonld')),
'pod /private/ must still be exported (this is pod data, not server-internal)');
});

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good observation — combined with the podName: null vs 'me' mismatch you flagged on lines 152-161, root-pod manifest shape was completely untested. A regression there could silently change the on-disk-vs-OIDC-name semantics with no test failure.

Fix in ec7cc46 (root-pod denylist test now also asserts manifest shape):

const manifest = JSON.parse(files['jss-export/manifest.json'].toString('utf8'));
const account = JSON.parse(files['jss-export/account.json'].toString('utf8'));
assert.strictEqual(manifest.mode, 'single-user');
assert.strictEqual(manifest.username, 'me');
assert.strictEqual(manifest.podName, account.podName,
  'manifest.podName must match account.json.podName — single source of truth');
assert.strictEqual(account.podName, 'me',
  'seeded root-pod account.podName is "me" (the OIDC short name)');

Pins the parity property + the seeded root-pod podName value. The old null-vs-'me' shape would fail this loudly.

…tent error handler (#449)

- manifest.podName in single-user now reads from accountRecord (same
  source as the multi-user branch), so manifest.podName ===
  account.json.podName in every archive shape. Previously root-pod
  emitted manifest.podName=null while accountRecord.podName='me' —
  silent disagreement in the same archive that a downstream importer
  would see depending on which field it read.
- packExport: dropped the now-dead `if (accountRecord)` guard.
  Both branches in handleExportAccount return 403 on null
  accountRecord, so by the time control reaches packExport the
  record is always defined and account.json is always emitted.
- onStreamError: idempotent via `if (gzip.destroyed || pack.destroyed)
  return;`. Destroying a stream re-emits 'error' which would re-enter
  this handler from three sources (pack.error, gzip.error,
  streamingPromise.catch) and produce duplicate "pod export stream
  error" log lines for one underlying failure.
- idpPlugin JSDoc: added `inviteOnly`, `singleUser`, `singleUserName`,
  `jssVersion` (previously only `issuer` was documented). A future
  caller reading the function header now discovers the export
  endpoint's plumbing requirements without grepping the body.
- Test: added root-pod manifest shape + parity assertions
  (manifest.podName === account.podName === 'me'). Pins the
  consistency property — a regression to the previous
  `null`-vs-`'me'` disagreement now fails loudly.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 6 changed files in this pull request and generated 5 comments.

Comment thread src/idp/export.js
Comment on lines +255 to +261
reply.raw.on('close', () => {
if (!reply.raw.writableEnded) {
request.log.warn('pod export client disconnected mid-stream');
pack.destroy(new Error('client disconnected'));
gzip.destroy(new Error('client disconnected'));
}
});

ghost May 14, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Subtle race — caught it. The window is real: socket 'close' can fire before writableEnded flips on a completely normal completion (slow/congested writes), so the !writableEnded guard alone would log a spurious client disconnected warn line on a successful export. Then the resulting pack.destroy(...) would re-enter onStreamError (now silent thanks to the destroyed-flag short-circuit, but still a stray destroy on a finished stream).

Fix in 7ed0476: added a packFinished flag set synchronously after pack.finalize() resolves:

let packFinished = false;
reply.raw.on('close', () => {
  if (packFinished || reply.raw.writableEnded) return;
  request.log.warn('pod export client disconnected mid-stream');
  pack.destroy(...);
  gzip.destroy(...);
});
const streamingPromise = packExport({ ... })
  .then(() => { packFinished = true; })
  .catch(onStreamError);

Now the close handler can distinguish "real disconnect mid-walk" (packFinished still false) from "natural end of stream" (packFinished true) and only logs/destroys in the former case.

Comment thread src/idp/export.js
Comment on lines +94 to +97
const ACCOUNT_EXPORT_FIELDS = [
'id', 'webId', 'username', 'email', 'podName', 'createdAt', 'updatedAt',
'passwordChangedAt', 'lastLoginAt',
];

ghost May 14, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right — top-level allowlist, but the nested structure of any allowlisted field flows through unchecked. A future oidcClientConfig: { secret } or metadata: { recoveryAnswers } would export the entire object including secrets just because the top-level key is on the allowlist.

Fix in 7ed0476: explicit warning in the JSDoc above ACCOUNT_EXPORT_FIELDS:

!!! TOP-LEVEL ONLY. The allowlist gates only at the first level of the account record. If a future field is itself an object/array (e.g. oidcClientConfig: { secret: ... }, metadata: { recoveryAnswers: [...] }, etc.), allowlisting the top-level key alone exports the entire nested structure including any secrets. Nested structures need their own scrubbing before being added here, OR they should be projected into a flat shape that excludes the secret-bearing fields.

Maintainer adding a new nested field hits the warning at the only place it matters.

Comment thread src/idp/export.js Outdated
Comment on lines +266 to +272
const streamingPromise = packExport({
pack,
podDir,
manifest,
accountRecord,
excludeAtRoot: (options.singleUser && isRootPod) ? ROOT_POD_EXCLUDE : null,
}).catch(onStreamError);

ghost May 14, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good defense-in-depth catch — ROOT_POD_EXCLUDE only fires when excludeAtRoot is set (single-user-root-pod), so multi-user mode silently relies on account-creation rejecting reserved names. That's a real coupling hidden across two layers.

Fix in 7ed0476: defensive check before opening the pod:

if (
  !(options.singleUser && isRootPod) &&
  ROOT_POD_EXCLUDE.has(path.basename(podDir))
) {
  request.log.error({ podDir, basename: path.basename(podDir) },
    'export refused — podDir resolved to a server-internal name; ' +
    'account-creation validation regression?');
  return reply.code(500).send({
    error: 'server_error',
    error_description: 'Pod resolution conflicts with server-internal layout',
  });
}

Account-creation validation stays the primary defense; this is the second line that fires + logs loudly if the invariant ever breaks. 500 (not 403) because a podDir resolving here means server state is in a state that shouldn't be reachable, not a caller authorization issue.

Comment thread src/server.js
Comment on lines +331 to +338
let jssVersion = 'unknown';
try {
// Synchronous read — createServer isn't async, and the file is
// tiny + on local disk. Same approach the existing config code
// uses for package.json metadata.
const pkgRaw = readFileSync(join(__dirname, '..', 'package.json'), 'utf8');
jssVersion = JSON.parse(pkgRaw).version;
} catch { /* keep 'unknown' */ }

ghost May 14, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Acknowledged the duplication is real (sync read at idpPlugin registration + async read in onReady for seedServerRoot). Pushed back on the broader refactor for scope reasons but updated the misleading comment in 7ed0476:

Sync read because createServer isn't async and we need the version to thread into idpPlugin registration below. The file is tiny + on local disk. There is a second async read of package.json in the onReady hook for seedServerRoot — both are read-once at startup so drift is bounded to "package.json changed between two ~ms-apart reads", which doesn't happen in practice. Hoisting both into a memoized module-level helper is a worthwhile follow-up but out of scope for #353.

The earlier "same approach the existing config code uses" claim was false (no shared helper exists) — that's gone. The follow-up is now flagged in-place so a future maintainer touching either site can pick it up.

Comment thread src/idp/export.js
Comment on lines +114 to +205
if (!webId) {
return reply.code(401).send({
error: 'invalid_token',
error_description: authError || 'Authentication required',
});
}

// 2. Resolve the pod tree on disk + the manifest data.
const dataRoot = process.env.DATA_ROOT || './data';
let podDir;
let accountRecord = null;
let manifest;
let isRootPod = false;

if (options.singleUser) {
// Single-user: pod is at `/` (root pod) or `/<name>/` based on
// singleUserName. The seeded IDP account (per
// seedSingleUserIdpAccount in src/server.js) is the sole owner —
// an authenticated WebID without a matching local account is
// some third-party identity (external Solid-OIDC, LWS-CID JWT,
// etc.), NOT the pod owner, and must not get the operator's
// /private/privkey.jsonld. The route is only mounted when
// idpEnabled, so a missing account record means "caller is not
// the seeded owner" — refuse with the same 403 shape as
// multi-user.
isRootPod = !options.singleUserName;
podDir = isRootPod
? dataRoot
: path.join(dataRoot, options.singleUserName);

accountRecord = await findByWebId(webId);
if (!accountRecord) {
return reply.code(403).send({
error: 'forbidden',
error_description:
'Authenticated WebID does not match the single-user account',
});
}
// manifest.podName mirrors the IDP account's podName (the OIDC
// short name) for parity with the multi-user branch — both
// branches now read podName from accountRecord, so a downstream
// importer keying on manifest.podName or account.json.podName
// gets the same answer regardless of server mode. Filesystem
// layout (root-pod vs /<name>/ pod) is conveyed by `mode` +
// the seeded podName ('me' for root-pod, singleUserName otherwise).
manifest = {
webId: accountRecord.webId,
username: accountRecord.username,
email: accountRecord.email,
podName: accountRecord.podName,
mode: 'single-user',
createdAt: accountRecord.createdAt,
exportedAt: new Date().toISOString(),
jssVersion: options.jssVersion ?? 'unknown',
};
} else {
// Multi-user: caller's WebID must resolve to an account record
// on this server. Same 403 shape as DELETE /idp/account uses
// when an authenticated WebID has no local account.
accountRecord = await findByWebId(webId);
if (!accountRecord) {
return reply.code(403).send({
error: 'forbidden',
error_description: 'No account found for authenticated WebID',
});
}
const podName = accountRecord.podName || accountRecord.username;
podDir = path.join(dataRoot, podName);
manifest = {
webId: accountRecord.webId,
username: accountRecord.username,
email: accountRecord.email,
podName,
mode: 'multi-user',
createdAt: accountRecord.createdAt,
exportedAt: new Date().toISOString(),
jssVersion: options.jssVersion ?? 'unknown',
};
}

// Defensive: the pod dir should exist for any legitimate caller.
// 404 lets the client distinguish "auth was fine, but there's
// nothing on disk" from a true server error.
try {
const st = await fsp.stat(podDir);
if (!st.isDirectory()) throw new Error('not a directory');
} catch {
return reply.code(404).send({
error: 'not_found',
error_description: `No pod directory at ${podDir}`,
});
}

ghost May 14, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed by checking the existing IdP endpoints. The mixed convention is the established codebase pattern, not a new inconsistency in this PR:

  • credentials.js: 401 → invalid_token / invalid_grant (OAuth Bearer, RFC 6750), 403 → forbidden (plain), 400 → invalid_request (OAuth)
  • passkey.js: 401/403/404 → plain English ('Must provide accountId', 'Account mismatch', etc.)
  • idp/index.js: 403 → 'Registration disabled in single-user mode' (plain)

So the export endpoint matches credentials.js exactly: 401 borrows the OAuth Bearer error vocabulary (because that's what verifies the token), 403/404 use HTTP-semantic tokens (because they describe HTTP-level outcomes, not OAuth ones).

Fix in 7ed0476: added a JSDoc comment to handleExportAccount documenting this convention explicitly + noting that aligning the whole IdP surface to one vocabulary is its own refactor. The export endpoint now signals the deliberate choice rather than appearing to be drift.

…llowlist + comments (#449)

- Close-handler race: `reply.raw.on('close')` could briefly observe
  `writableEnded === false` on a normal completion (window between
  socket close and writableEnded flip), producing spurious "client
  disconnected" warn lines for successful exports on slow writes.
  Added `packFinished` flag set after pack.finalize() resolves; the
  close handler short-circuits when set, distinguishing "real
  disconnect mid-walk" from "natural end of stream".
- Defense-in-depth check on podDir basename: refuse with 500 if a
  multi-user export resolves podDir to a server-internal name in
  ROOT_POD_EXCLUDE. Account-creation validation rejects these names
  today; this is a second-line guard against an upstream regression
  silently letting `<dataRoot>/.idp` be walked as a "user pod".
- ACCOUNT_EXPORT_FIELDS: documented top-level-only behavior. A
  future field that's itself an object (e.g. `oidcClientConfig:
  { secret }`) would export the entire nested structure including
  secrets. Comment now warns maintainers and points at projection
  as the right pattern for nested data.
- Error vocabulary: added comment explaining the deliberate mixed
  convention (401 → OAuth-defined `invalid_token`, 403/404 → plain
  HTTP semantic), matching credentials.js and the rest of src/idp/.
- src/server.js: dropped misleading "same approach the existing
  config code uses" comment. Updated to honestly note the duplicate
  package.json read (sync at idpPlugin registration vs async in
  onReady) and flag a memoized helper as a follow-up out of scope
  for #353.

ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 6 changed files in this pull request and generated 3 comments.

Comment thread src/idp/export.js Outdated
*/

import path from 'path';
import fs from 'fs';

ghost May 14, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed unused — fs had no remaining references after the TOCTOU fix switched all I/O to fsp.open() + fh.createReadStream(). Removed in 75ced8e.

Comment thread src/idp/export.js Outdated
Comment on lines +23 to +25
* 403 — multi-user: no account for the caller's WebID
* 404 — pod directory unexpectedly missing (shouldn't happen for
* an account with a valid WebID, but caught defensively)

ghost May 14, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right — the docblock missed two failure modes added in later review rounds. Updated in 75ced8e:

 * Failure modes:
 *   401 — unauthenticated
 *   403 — caller's WebID has no matching local account record;
 *         applies to multi-user (no account for the WebID) and
 *         single-user (authenticated WebID is not the seeded owner —
 *         e.g. an external Solid-OIDC / LWS-CID identity)
 *   404 — pod directory unexpectedly missing (shouldn't happen for
 *         an account with a valid WebID, but caught defensively)
 *   500 — defense-in-depth: podDir resolved to a server-internal
 *         name (.idp / .private / etc.) in non-root-pod mode,
 *         meaning account-creation validation has regressed and
 *         allowed a reserved username through

A reader mapping status codes back to causes now finds all four.

Comment thread src/idp/export.js Outdated
} catch {
return reply.code(404).send({
error: 'not_found',
error_description: `No pod directory at ${podDir}`,

ghost May 14, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Real info disclosure — fair catch. No pod directory at /var/lib/jss/data/alice would tell any authenticated owner whose pod went missing exactly where on disk the operator stores pod data, which is server-internal layout the client has no business with.

Fix in 75ced8e:

} catch {
  request.log.warn({ podDir }, 'pod export: podDir missing or not a directory');
  return reply.code(404).send({
    error: 'not_found',
    error_description: 'Pod data not found',
  });
}

Generic message on the wire; the resolved path stays in the server log via request.log.warn so an operator debugging a missing-pod incident still has the diagnostic without exposing it to the caller.

…o podDir in 404 (#449)

- Drop unused `import fs from 'fs'` (all I/O goes through fsp).
- Failure-modes JSDoc was stale: now lists the single-user 403
  (third-party WebID, the security-critical fix from round 3) and
  the new 500 defense-in-depth code (podDir resolved to a server-
  internal name).
- 404 error_description no longer echoes the resolved podDir back
  to the caller. Leaking the operator's filesystem layout to an
  authenticated owner whose pod is missing was needless info
  disclosure. Path stays in the server log for debugging.

ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 6 changed files in this pull request and generated 3 comments.

Comment thread src/idp/export.js Outdated
Comment on lines +162 to +191
isRootPod = !options.singleUserName;
podDir = isRootPod
? dataRoot
: path.join(dataRoot, options.singleUserName);

accountRecord = await findByWebId(webId);
if (!accountRecord) {
return reply.code(403).send({
error: 'forbidden',
error_description:
'Authenticated WebID does not match the single-user account',
});
}
// manifest.podName mirrors the IDP account's podName (the OIDC
// short name) for parity with the multi-user branch — both
// branches now read podName from accountRecord, so a downstream
// importer keying on manifest.podName or account.json.podName
// gets the same answer regardless of server mode. Filesystem
// layout (root-pod vs /<name>/ pod) is conveyed by `mode` +
// the seeded podName ('me' for root-pod, singleUserName otherwise).
manifest = {
webId: accountRecord.webId,
username: accountRecord.username,
email: accountRecord.email,
podName: accountRecord.podName,
mode: 'single-user',
createdAt: accountRecord.createdAt,
exportedAt: new Date().toISOString(),
jssVersion: options.jssVersion ?? 'unknown',
};

ghost May 14, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Real two-source-of-truth coupling — podDir flows from options.singleUserName (CLI) while manifest.podName flows from accountRecord.podName (seeded by seedSingleUserIdpAccount). Today they're always equal in named-pod mode (the seed uses podName: isRootPod ? 'me' : singleUserName), but a future change could silently drift them and produce a manifest advertising X over a tree from <dataRoot>/Y.

Fix in 443b633:

if (!isRootPod && accountRecord.podName !== options.singleUserName) {
  request.log.error(
    { seededPodName: accountRecord.podName,
      cliSingleUserName: options.singleUserName },
    'pod export refused — accountRecord.podName disagrees with ' +
    'singleUserName; seedSingleUserIdpAccount regression?',
  );
  return reply.code(500).send({
    error: 'server_error',
    error_description: 'Pod identity inconsistent with on-disk layout',
  });
}

Skipped in root-pod where the disagreement is intentional (accountRecord.podName === 'me' is the OIDC short name, while podDir === dataRoot has no path component for it). 500 (not 4xx) because a divergence here means server state is in a shape that shouldn't be reachable, not a caller authorization issue.

Comment thread src/idp/export.js Outdated
Comment on lines +326 to +334
const streamingPromise = packExport({
pack,
podDir,
manifest,
accountRecord,
excludeAtRoot: (options.singleUser && isRootPod) ? ROOT_POD_EXCLUDE : null,
}).then(() => { packFinished = true; }).catch(onStreamError);

void streamingPromise;

ghost May 14, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right — the chained .then().catch(onStreamError) already attaches a rejection handler, so there's no unhandled-rejection risk and the void suppresses nothing. The local was just a leftover from an earlier iteration that didn't use the chained .then.

Fix in 443b633: dropped both the local and the void line. Chain runs directly:

packExport({ ... })
  .then(() => { packFinished = true; })
  .catch(onStreamError);

return reply.send(gzip);

Same behavior, less noise.

Comment thread src/idp/export.js
Comment on lines +271 to +336
reply
.type('application/x-tar+gzip')
.header('Content-Disposition', cdValue)
.header('Cache-Control', 'no-store');

const pack = tar.pack();
const gzip = zlib.createGzip();
pack.pipe(gzip);

// Surface stream-level errors. Once response headers are out an
// EACCES / mid-pack failure can otherwise present as a silently
// truncated download — the client gets 200 + partial gzip + no
// error signal. We log on the server side and destroy the
// pipeline so the client at least sees an aborted transfer rather
// than a corrupt but seemingly-complete archive.
// Idempotent: invoked from pack.error, gzip.error, AND
// streamingPromise.catch. Destroying a stream re-emits 'error',
// which would re-enter this handler and produce duplicate log
// lines for one underlying failure. The destroyed-flag short-
// circuits all subsequent calls so a single failure logs once.
const onStreamError = (err) => {
if (gzip.destroyed || pack.destroyed) return;
request.log.error({ err }, 'pod export stream error');
pack.destroy(err);
gzip.destroy(err);
};
pack.on('error', onStreamError);
gzip.on('error', onStreamError);

// Client disconnect handler. Without this, walkAndPack keeps
// reading every file in the pod, opening file descriptors, and
// pushing into a gzip whose downstream socket is gone. For a
// multi-GB pod that's wasted IO + fds until the walk finishes.
// Destroying both ends short-circuits the walk via stream error
// propagation; the request.log captures the abort for diagnostics.
//
// The `packFinished` flag closes a race window: socket 'close'
// can briefly observe `writableEnded === false` on a perfectly
// normal completion (between socket close and writableEnded
// flipping), which would log a spurious "client disconnected"
// warn line for successful exports on slow/congested writes.
// We set the flag synchronously after pack.finalize() resolves
// so the close handler can distinguish "real disconnect mid-walk"
// from "natural end of stream".
let packFinished = false;
reply.raw.on('close', () => {
if (packFinished || reply.raw.writableEnded) return;
request.log.warn('pod export client disconnected mid-stream');
pack.destroy(new Error('client disconnected'));
gzip.destroy(new Error('client disconnected'));
});

// Pump in the background; entries are added asynchronously below.
// The root-pod denylist is wired in so single-user-root-pod mode
// doesn't ship .idp/ (accounts + signing keys + OIDC state).
const streamingPromise = packExport({
pack,
podDir,
manifest,
accountRecord,
excludeAtRoot: (options.singleUser && isRootPod) ? ROOT_POD_EXCLUDE : null,
}).then(() => { packFinished = true; }).catch(onStreamError);

void streamingPromise;

return reply.send(gzip);

ghost May 14, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Genuine race — caught it. The first FS-touching op in packExport is walkAndPack -> fsp.readdir(podDir), and that's the most likely first-byte failure mode (EACCES from a misconfigured pod permission). When it threw mid-stream, onStreamError would destroy gzip after reply.send(gzip) had already returned — the client sees a 200 with truncated/empty body, not a parseable 5xx.

Fix in 443b633: pre-flight readdir BEFORE flushing headers. The existing fsp.stat check stays for ENOENT/ENOTDIR (404), and now an fsp.readdir(podDir) follows it to surface readability errors as a clean 500 before any reply.send:

try {
  const st = await fsp.stat(podDir);
  if (!st.isDirectory()) { ... ENOTDIR ... }
  await fsp.readdir(podDir);   // pre-flight readability
} catch (err) {
  if (err.code === 'ENOENT' || err.code === 'ENOTDIR') {
    return reply.code(404).send({ error: 'not_found', ... });
  }
  request.log.error({ err, podDir }, 'pod export: pre-flight failed');
  return reply.code(500).send({ error: 'server_error', ... });
}

Cost: one extra readdir of the top-level pod dir, then walkAndPack does its own. Cheap relative to the streamed walk. Mid-stream EACCES on subdirectories still surfaces via onStreamError (which can't be made clean once headers are out — that's a fundamental property of streaming response), but the entry-point case Copilot flagged is now handled cleanly.

… void no-op (#449)

- Pre-flight readability via fsp.readdir(podDir) BEFORE flushing
  response headers. A first-byte EACCES on the top-level readdir
  was previously surfacing inside the streaming pipeline AFTER
  reply.send(gzip) had flushed headers — client got 200 +
  truncated/empty body instead of clean 5xx JSON. Pre-flight
  catches this and routes to a clean 404 (ENOENT/ENOTDIR) or 500
  (anything else) before headers go out. Both error_descriptions
  stay generic; resolved podDir stays in server log only.
- Named-pod single-user consistency: assert
  accountRecord.podName === options.singleUserName before walking.
  If seedSingleUserIdpAccount ever drifts so the seeded podName
  diverges from the CLI option that derives podDir, the manifest
  would advertise X while the export's tree comes from
  <dataRoot>/Y. Refuse with 500 + log so the seeding regression
  fails loudly. Skipped in root-pod (where podDir is dataRoot
  regardless of the seeded podName).
- Drop `void streamingPromise` no-op + the local. `.catch()` is
  already attached so no unhandled-rejection risk; the void was
  suppressing nothing. Chain `.then().catch()` directly.
@melvincarvalho
melvincarvalho requested a review from Copilot May 14, 2026 14:51

ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 6 changed files in this pull request and generated 3 comments.

Comment thread src/idp/export.js Outdated
Comment on lines +336 to +340
// Idempotent: invoked from pack.error, gzip.error, AND
// streamingPromise.catch. Destroying a stream re-emits 'error',
// which would re-enter this handler and produce duplicate log
// lines for one underlying failure. The destroyed-flag short-
// circuits all subsequent calls so a single failure logs once.

ghost May 14, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caught — streamingPromise was removed two rounds ago when the chain was inlined, but the comment kept referring to it. Updated in c09ebd2:

Idempotent: invoked from pack.error, gzip.error, AND the .catch(onStreamError) chained on packExport(...) below.

Now matches the actual call sites in the file.

Comment thread test/idp-export.test.js
Comment on lines +100 to +115
const aliceRes = await fetch(`${baseUrl}/.pods`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: 'alice', email: '[email protected]', password: 'pw-alice-123'
})
});
aliceToken = (await aliceRes.json()).token;
const bobRes = await fetch(`${baseUrl}/.pods`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: 'bob', email: '[email protected]', password: 'pw-bob-456'
})
});
bobToken = (await bobRes.json()).token;

ghost May 14, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right — silent token destructuring would mask a /.pods shape regression as cryptic 401s downstream instead of "pod creation failed" up front. Hard-fail pattern was used for the single-user before hooks but the multi-user one was still permissive.

Fix in c09ebd2:

const aliceRes = await fetch(`${baseUrl}/.pods`, { ... });
assert.ok(aliceRes.ok, `alice pod creation failed: ${aliceRes.status}`);
aliceToken = (await aliceRes.json()).token;
assert.ok(aliceToken, 'alice pod creation must return a token');

Same for bob. A /.pods endpoint shape change now fails the test with a clear pre-condition error pointing at the real culprit, not at the export endpoint.

Comment thread src/idp/export.js Outdated
Comment on lines +365 to +387
let packFinished = false;
reply.raw.on('close', () => {
if (packFinished || reply.raw.writableEnded) return;
request.log.warn('pod export client disconnected mid-stream');
pack.destroy(new Error('client disconnected'));
gzip.destroy(new Error('client disconnected'));
});

// Pump in the background; entries are added asynchronously below.
// The root-pod denylist is wired in so single-user-root-pod mode
// doesn't ship .idp/ (accounts + signing keys + OIDC state).
// No `void` / no local — `.then().catch(onStreamError)` already
// attaches a rejection handler, so there's no unhandled-rejection
// risk and the pipeline runs detached.
packExport({
pack,
podDir,
manifest,
accountRecord,
excludeAtRoot: (options.singleUser && isRootPod) ? ROOT_POD_EXCLUDE : null,
})
.then(() => { packFinished = true; })
.catch(onStreamError);

ghost May 14, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Subtle but real — packExport resolves on pack.finalize(), which is "we're done writing into the pipeline", NOT "the client received the bytes". For a multi-GB gzipped response over a slow link, the gap between those events is substantial, and during that window a real client disconnect would be silently swallowed because the close handler short-circuits on a flag set too early.

Fix in c09ebd2: gate on the right signal. Renamed flag responseFinished and tied it to reply.raw.on('finish'):

let responseFinished = false;
reply.raw.on('finish', () => { responseFinished = true; });
reply.raw.on('close', () => {
  if (responseFinished || reply.raw.writableEnded) return;
  request.log.warn('pod export client disconnected mid-stream');
  pack.destroy(...);
  gzip.destroy(...);
});

Node emits 'finish' when the last byte hits the OS socket buffer. After that a 'close' is "client disconnected after we were done" — correctly ignored. Before 'finish', a 'close' is a genuine mid-stream disconnect — correctly logged + cleaned up. The packExport chain no longer needs to set the flag, so it just .catch(onStreamError) now.

… + comment refresh (#449)

- packFinished was set when packExport (i.e. pack.finalize()) resolved
  — that's "we're done writing into the pipeline", not "the client
  has received the bytes". For a multi-GB gzipped response over a
  slow link the gap can be substantial, and a real client disconnect
  during the final flush would be silently swallowed (close handler
  short-circuits on a flag set too early). Renamed to responseFinished
  and gated on `reply.raw.on('finish')` instead — Node emits 'finish'
  when the last byte hits the OS socket buffer, after which a 'close'
  is "client gone after we were done" (correctly ignored). Before
  'finish', a 'close' is a genuine mid-stream disconnect.
- Multi-user before hook: hard-assert `aliceRes.ok` + `aliceToken`
  (and bob) so a /.pods shape regression surfaces as "pod creation
  failed: <status>" rather than as cryptic 401s in every downstream
  test. Same hard-fail pattern as the single-user before hooks.
- onStreamError comment refreshed to mention the inline
  `.catch(onStreamError)` chained on packExport instead of the
  no-longer-existing streamingPromise local.

ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 6 changed files in this pull request and generated 4 comments.

Comment thread src/idp/export.js Outdated
// idpEnabled, so a missing account record means "caller is not
// the seeded owner" — refuse with the same 403 shape as
// multi-user.
isRootPod = !options.singleUserName;

ghost May 14, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Worse than you flagged actually — caught a security implication while fixing it.

The previous isRootPod = !options.singleUserName mapped both null and '' to root-pod, and the root-pod branch applies ROOT_POD_EXCLUDE. So '' accidentally got the right denylist.

But just switching to a strict null check (isRootPod = options.singleUserName == null) would have been catastrophic: '' then takes the NAMED-POD branch with podDir = path.join(dataRoot, '') = dataRoot AND excludeAtRoot = null (because isRootPod is now false). Result: ships the entire <dataRoot> including .idp/ accounts, signing keys, and .private/ Bitcoin keypair.

Fix in 2d23ce2: refuse empty-string / non-string singleUserName explicitly BEFORE deciding isRootPod:

if (
  options.singleUserName !== null &&
  options.singleUserName !== undefined &&
  (typeof options.singleUserName !== 'string' || options.singleUserName.length === 0)
) {
  request.log.error({ singleUserName: options.singleUserName },
    'pod export refused — singleUserName must be null/undefined or a non-empty string');
  return reply.code(500).send({ error: 'server_error', ... });
}
isRootPod = options.singleUserName == null;

'' / 0 / false / {} all fail loudly with 500 + log. Only legitimate inputs (null/undefined for root-pod, non-empty string for named-pod) pass through to the existing logic.

Comment thread src/idp/export.js Outdated
Comment on lines +288 to +292
// Pre-flight readability via the same call walkAndPack will use
// for its first iteration. Discard the result; walkAndPack will
// redo this — readdir on a top-level pod dir is O(top-level
// entries) and cheap relative to the streamed walk.
await fsp.readdir(podDir);

ghost May 14, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Worth doing — fsp.readdir reads + discards the entire top-level entry list, then walkAndPack re-reads it. fsp.access(podDir, R_OK | X_OK) gives the same EACCES guard with one syscall instead of one + a discarded listing.

Fix in 2d23ce2:

import { promises as fsp, constants as fsConstants } from 'fs';
...
await fsp.access(podDir, fsConstants.R_OK | fsConstants.X_OK);

R_OK gates listing, X_OK gates traversal into subdirectories — both required by the recursive walk. Same first-byte-EACCES protection, half the work.

Comment thread package.json
Comment on lines +41 to +42
"sql.js": "^1.13.0",
"tar-stream": "^3.2.0"

ghost May 14, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified and you're right — the PR description undersold this. Confirmed on disk after npm install:

  • tar-stream itself: 60K
  • bare-fs: 1.4M, bare-os: 1.0M, bare-url: 1.6M, bare-events: 64K, bare-path: 68K, bare-stream: 80K
  • streamx: 64K, b4a: 80K
  • Total: ~4.4 MB on disk

Functional impact on Node is zero — the bare-* packages exist for the Bare runtime (a Node-alternative for embedded / RN) and are lazy-loaded only when running outside Node. On Node, streamx falls back to readable-stream and the bare-* deps sit on disk but never load, so the runtime weight is the 60K of tar-stream itself.

Updated the PR description in 2d23ce2 to be honest about the disk footprint while clarifying the runtime weight is unchanged. Verified install + tests still run cleanly on the Termux/mobile target.

Comment thread src/idp/export.js Outdated
Comment on lines +309 to +311
const slug = sanitizeSlug(webId);
const isoDate = manifest.exportedAt.replace(/[:.]/g, '-');
const filename = `jss-export-${slug}-${isoDate}.tar.gz`;

ghost May 14, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Real even if low-probability — a script polling the endpoint in a tight loop or a parallel-batch UI could land two exports in the same ms and overwrite each other on the client side.

Fix in 2d23ce2: 6-hex-char crypto.randomBytes(3) suffix appended:

const rand = crypto.randomBytes(3).toString('hex');  // 6 hex chars
const filename = `jss-export-${slug}-${isoDate}-${rand}.tar.gz`;

Format becomes jss-export-127-0-0-1_42_alice_profile_card-2026-05-14T15-00-34-118Z-a7f3e9.tar.gz. The filename test asserts only on the prefix (/^attachment; filename="jss-export-/) so no test churn. 24 bits of entropy is plenty for collision avoidance within a single ms.

…llision suffix (#449)

- singleUserName='' would have silently switched the handler into
  root-pod mode under the previous `!singleUserName` falsy-check.
  Worse, naively switching to a strict null check would route ''
  through the named-pod branch with podDir = path.join(dataRoot, '')
  = dataRoot AND excludeAtRoot = null, silently exporting
  server-internal `.idp/` and `.private/`. Now refuse empty-string /
  non-string singleUserName explicitly with 500 + log before
  deciding isRootPod, then `isRootPod = singleUserName == null` for
  the legitimate cases.
- Pre-flight readability switched from `fsp.readdir(podDir)` (which
  reads + discards the entire top-level entry list before
  walkAndPack re-reads it) to `fsp.access(podDir, R_OK | X_OK)` —
  same semantic guard against EACCES, half the syscalls.
- Filename: 6-hex-char crypto.randomBytes(3) suffix appended to
  `jss-export-<slug>-<isoDate>-<rand>.tar.gz`. ISO timestamps have
  ms resolution; consecutive exports in the same ms would otherwise
  produce identical Content-Disposition filenames that overwrite
  each other on the client side.

ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 6 changed files in this pull request and generated no new comments.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add self-service data export — download all my pod data

2 participants