@fuzdev/fuz_app 0.75.0 → 0.76.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -400,6 +400,10 @@ are excluded.
400
400
  declare `credential_types: ['session']`. `account_session_revoke` is
401
401
  gated alongside `_revoke_all` because a leaked bearer can otherwise
402
402
  compose `account_session_list` + N×revoke to reach the same lockout.
403
+ REST `POST /logout` also declares `credential_types: ['session']`, but
404
+ for forensic fidelity rather than a threat — a bearer / daemon token
405
+ holds no session to end, so the gate refuses it instead of returning a
406
+ misleading 200 + a phantom `logout` audit row.
403
407
  Admin token/session revoke specs deliberately stay unrestricted (admin
404
408
  scripting from CLI/bearer is legitimate operator workflow). See
405
409
  ../../../docs/security.md §Credential-channel gating.
@@ -1 +1 @@
1
- {"version":3,"file":"account_routes.d.ts","sourceRoot":"../src/lib/","sources":["../../src/lib/auth/account_routes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,EAAC,CAAC,EAAC,MAAM,KAAK,CAAC;AAEtB,OAAO,KAAK,EAAC,cAAc,EAAC,MAAM,qBAAqB,CAAC;AA2BxD,OAAO,EAAkB,KAAK,SAAS,EAAC,MAAM,uBAAuB,CAAC;AAEtE,OAAO,EAA+B,KAAK,WAAW,EAAC,MAAM,oBAAoB,CAAC;AAElF,OAAO,KAAK,EAAC,gBAAgB,EAAC,MAAM,WAAW,CAAC;AAChD,OAAO,KAAK,EAAC,gBAAgB,EAAC,MAAM,iCAAiC,CAAC;AAQtE,kFAAkF;AAClF,eAAO,MAAM,kBAAkB,WAAW,CAAC;AAC3C,MAAM,MAAM,kBAAkB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,kBAAkB,CAAC,CAAC;AAEpE;;;;;;;;GAQG;AACH,eAAO,MAAM,mBAAmB;;;;;;;;;;;;;;;;;;;;;kBAI9B,CAAC;AACH,MAAM,MAAM,mBAAmB,GAAG,CAAC,CAA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C,MAAM,gBAAgB,EACtB,SAAS,mBAAmB,KAC1B,KAAK,CAAC,SAAS,CAoTjB,CAAC"}
@@ -333,7 +333,11 @@ export const create_account_route_specs = (deps, options) => {
333
333
  {
334
334
  method: 'POST',
335
335
  path: '/logout',
336
- auth: { account: 'required', actor: 'none' },
336
+ // `credential_types: ['session']` see `docs/security.md` §Credential-channel gating.
337
+ // Logout is a session-bound operation; a bearer / daemon token holds no session
338
+ // to end, so the dispatcher rejects it (403 `credential_type_required`) rather than
339
+ // returning a misleading 200 + a phantom `logout` audit row for a no-op.
340
+ auth: { account: 'required', actor: 'none', credential_types: ['session'] },
337
341
  description: 'Revoke current session and clear cookie',
338
342
  input: LogoutInput,
339
343
  output: LogoutOutput,
@@ -343,20 +347,21 @@ export const create_account_route_specs = (deps, options) => {
343
347
  if (session_token) {
344
348
  const token_hash = hash_session_token(session_token);
345
349
  await query_session_revoke_by_hash_unscoped(route, token_hash);
346
- // Handler-side belt+suspenders: close the live WS bound to
347
- // this session BEFORE the audit emit so revocation lands
348
- // even if the audit INSERT fails. Same transaction-commit
349
- // trade as `password` / RPC `session_revoke` below — a
350
- // throw between this close and the response rolls back the
351
- // DB revoke while leaving the socket severed; benign
352
- // (client reconnects, session still valid) but don't
353
- // introduce a throw here without acknowledging the trade.
354
- // The audit listener (`create_ws_logout_closer`) runs an
355
- // account-wide close on the logout event afterward
356
- // broader than this targeted close, but both layers are
357
- // idempotent. Mirrors `zzz_server::account::logout_inner`.
350
+ // Handler-side belt+suspenders: eagerly close this account's
351
+ // live WS connections BEFORE the audit emit so revocation
352
+ // lands even if the audit INSERT fails. Account-wide (not
353
+ // session-targeted) to match the Rust `account_logout` handler
354
+ // and the sibling `/password` handler logout is a
355
+ // self-initiated account-grain operation, and the audit
356
+ // listener (`create_ws_logout_closer`) runs the same
357
+ // account-wide close on the logout event afterward, so both
358
+ // layers converge (idempotent). Same transaction-commit trade
359
+ // as `password` / RPC `session_revoke`: a throw between this
360
+ // close and the response rolls back the DB revoke while
361
+ // leaving sockets severed; benign (client reconnects), but
362
+ // don't introduce a throw here without acknowledging the trade.
358
363
  if (connection_closer) {
359
- connection_closer.close_sockets_for_session(token_hash);
364
+ connection_closer.close_sockets_for_account(ctx.account.id);
360
365
  }
361
366
  }
362
367
  clear_session_cookie(c, session_options);
package/dist/db/CLAUDE.md CHANGED
@@ -49,10 +49,11 @@ The wire schemas + RPC handlers + authz predicates for this layer live in
49
49
  (`CELL_HISTORY_MIGRATION_NS`, namespace `fuz_cell_history`), FK → `cell.id`.
50
50
  Ships present-but-unwritten; no snapshot lifecycle yet.
51
51
  - **`cell_queries.ts`** — `query_cell_create / get / get_by_path / update /
52
- delete`, `_list_by_data_kind / _list_by_creator / _list_by_ref`, the
52
+ delete`, `_list_by_data_kind / _list_by_creator`, the
53
53
  generic `query_cell_list` (filter + SQL-side visibility predicate mirroring
54
- `can_view_cell`), and `query_cell_load_many` (bulk id load, no visibility
55
- filter feeds the strict relation-read filter). `cell.refs` derived from
54
+ `can_view_cell`; the `ref` filter narrows by `cell.refs`), and
55
+ `query_cell_load_many` (bulk id load, no visibility filter feeds the
56
+ strict relation-read filter). `cell.refs` derived from
56
57
  `data` via `extract_refs` on create/update. `CellRow.grant_count` is a
57
58
  derived projection (correlated subquery on `idx_cell_grant_cell`).
58
59
  - **`cell_grant_queries.ts`** — resource-side ACL: `query_cell_grant_create`
@@ -301,27 +301,4 @@ export interface CellListParams {
301
301
  /** Include soft-deleted rows. Default `false`. */
302
302
  include_deleted?: boolean;
303
303
  }
304
- /**
305
- * List active cells whose `refs` array contains the given fact hash,
306
- * newest first. Backed by the `idx_cell_refs` GIN index.
307
- *
308
- * Used by the fact-serving route's authz walk: a fact is viewable iff
309
- * **at least one** referencing active cell admits the caller via
310
- * `can_view_cell`. Unreferenced facts (no row returned here) are
311
- * unreachable through the public surface — orphan-fact GC handles them.
312
- *
313
- * `include_grant_count` defaults to true so the row hydrates uniformly
314
- * with the rest of the cell query surface. The fact-serving route is
315
- * the one hot path where the count is wasted work — pass `false`
316
- * there to skip the per-row correlated subquery; the field falls back
317
- * to a constant 0 so `CellRow` stays type-stable.
318
- *
319
- * @param deps - query deps
320
- * @param hash - fact hash to search for
321
- * @param options - pagination + grant-count toggle
322
- * @returns matching active rows
323
- */
324
- export declare const query_cell_list_by_ref: (deps: QueryDeps, hash: FactHash, options?: Pick<CellListOptions, "limit" | "offset"> & {
325
- include_grant_count?: boolean;
326
- }) => Promise<Array<CellRow>>;
327
304
  //# sourceMappingURL=cell_queries.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"cell_queries.d.ts","sourceRoot":"../src/lib/","sources":["../../src/lib/db/cell_queries.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,KAAK,EAAC,SAAS,EAAC,MAAM,iBAAiB,CAAC;AAC/C,OAAO,KAAK,EAAC,IAAI,EAAC,MAAM,0BAA0B,CAAC;AACnD,OAAO,KAAK,EAAC,IAAI,EAAC,MAAM,wBAAwB,CAAC;AACjD,OAAO,EAAyB,KAAK,QAAQ,EAAC,MAAM,+BAA+B,CAAC;AAGpF,OAAO,KAAK,EAAC,QAAQ,EAAC,MAAM,6BAA6B,CAAC;AAC1D,OAAO,KAAK,EAAC,cAAc,EAAC,MAAM,8BAA8B,CAAC;AAEjE;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,OAAO;IACvB,EAAE,EAAE,IAAI,CAAC;IACT,IAAI,EAAE,QAAQ,CAAC;IACf,UAAU,EAAE,cAAc,CAAC;IAC3B,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,IAAI,EAAE,KAAK,CAAC,QAAQ,CAAC,GAAG,IAAI,CAAC;IAC7B,UAAU,EAAE,IAAI,CAAC;IACjB,UAAU,EAAE,IAAI,GAAG,IAAI,CAAC;IACxB,UAAU,EAAE,IAAI,GAAG,IAAI,CAAC;IACxB,UAAU,EAAE,IAAI,GAAG,IAAI,CAAC;IACxB,UAAU,EAAE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AC,EAAE,MAAM,CAAC;IACf,mBAAmB;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,kDAAkD;IAClD,eAAe,CAAC,EAAE,OAAO,CAAC;CAC1B"}
@@ -388,36 +388,6 @@ const build_shared_with_sql = (order_column, order_direction) => `${CALLER_ROLE_
388
388
  AND $6::bool IS NOT NULL
389
389
  ORDER BY c.${order_column} ${order_direction} NULLS LAST
390
390
  LIMIT $8 OFFSET $9`;
391
- /**
392
- * List active cells whose `refs` array contains the given fact hash,
393
- * newest first. Backed by the `idx_cell_refs` GIN index.
394
- *
395
- * Used by the fact-serving route's authz walk: a fact is viewable iff
396
- * **at least one** referencing active cell admits the caller via
397
- * `can_view_cell`. Unreferenced facts (no row returned here) are
398
- * unreachable through the public surface — orphan-fact GC handles them.
399
- *
400
- * `include_grant_count` defaults to true so the row hydrates uniformly
401
- * with the rest of the cell query surface. The fact-serving route is
402
- * the one hot path where the count is wasted work — pass `false`
403
- * there to skip the per-row correlated subquery; the field falls back
404
- * to a constant 0 so `CellRow` stays type-stable.
405
- *
406
- * @param deps - query deps
407
- * @param hash - fact hash to search for
408
- * @param options - pagination + grant-count toggle
409
- * @returns matching active rows
410
- */
411
- export const query_cell_list_by_ref = async (deps, hash, options) => {
412
- const include_grant_count = options?.include_grant_count !== false;
413
- const projection = include_grant_count ? grant_count_projection('cell') : '0::int AS grant_count';
414
- return deps.db.query(`SELECT *, ${projection}
415
- FROM cell
416
- WHERE refs @> ARRAY[$1]::text[]
417
- AND deleted_at IS NULL
418
- ORDER BY created_at DESC
419
- LIMIT $2 OFFSET $3`, [hash, options?.limit ?? null, options?.offset ?? 0]);
420
- };
421
391
  /**
422
392
  * Derive the `refs` array column value from a cell's `data`.
423
393
  *
@@ -1,38 +1,67 @@
1
1
  /**
2
- * `GET /api/facts/:hash`content-addressed fact serving.
2
+ * Content-addressed fact serving cell-scoped, per-reference reads.
3
3
  *
4
- * Resolves a fact hash to the bytes referenced by at least one viewable
5
- * cell. Embedded facts stream from the `facts.bytes` PG column;
6
- * external facts (filesystem-backed `file:<shard>/<rest>` URLs) either
7
- * return an `X-Accel-Redirect` header pointing into nginx's internal
8
- * facts location (production) or stream from disk via the filesystem
9
- * `FactExternalFetcher` (dev / tests). The runtime mode is selected by
10
- * the optional `x_accel_redirect_prefix` factory option — set in prod,
11
- * unset in dev.
4
+ * Two routes serve fact bytes from the PG-backed fact store:
5
+ *
6
+ * - `GET /api/cells/:cell_id/facts/:hash` the **per-reference read**.
7
+ * The request names the referencing cell. Authz is scoped to that one
8
+ * reference: `can_view_cell(caller, cell) AND cell.refs includes hash`.
9
+ * This is the path non-admin callers use, and the only path for
10
+ * confidential content.
11
+ * - `GET /api/facts/:hash` — the **bare-hash read**, restricted to admins.
12
+ *
13
+ * Embedded facts stream from the `fact.bytes` PG column; external facts
14
+ * (filesystem-backed `file:<shard>/<rest>` URLs) either return an
15
+ * `X-Accel-Redirect` header pointing into nginx's internal facts location
16
+ * (production) or stream from disk via the filesystem `FactExternalFetcher`
17
+ * (dev / tests). The runtime mode is selected by the optional
18
+ * `x_accel_redirect_prefix` factory option — set in prod, unset in dev.
12
19
  *
13
20
  * REST, not RPC: binary responses don't fit the JSON-RPC envelope.
14
21
  *
15
- * ## Authorization
16
- *
17
- * Auth is `{account: 'none', actor: 'none'}` — the dispatcher's
18
- * authorization phase is skipped for pure-public routes, so this handler
19
- * builds the `RequestContext` itself from `c.var.account_id` (populated
20
- * by the `/api/*` session middleware) by resolving the caller's single
21
- * actor and loading their role_grants. Unauthed callers pass through
22
- * with `req_ctx: null`. Viewers are admitted via `can_view_cell` over
23
- * **every** active cell that references the hash. Multi-actor accounts
24
- * fall through with `req_ctx: null`there's no `acting?` slot on a
25
- * pure-public route, so multi-actor callers are treated as anonymous
26
- * (admitted only by the public-visibility branch). A fact is viewable iff
27
- * at least one referencing cell admits the caller; unauthenticated callers
28
- * are admitted only via a referencing cell with `cell.visibility ===
29
- * 'public'`. Facts with no referencing active cell are unreachable here
30
- * orphan-fact GC reaps them separately.
31
- *
32
- * 404 is the universal "not viewable" response: missing fact, missing
33
- * referencing cell, all referencing cells private to other actors. We
34
- * deliberately don't distinguish 403 from 404 the existence of a
35
- * private hash should not leak through the public surface.
22
+ * ## Authorization — authz lives on the cell→fact edge, not the hash
23
+ *
24
+ * Facts are global, content-addressed, owner-less bytes: identical bytes
25
+ * from different owners dedup to **one** `fact` row. Keying access control
26
+ * on the bare hash therefore unions visibility across every owner that
27
+ * references it A's private bytes leak the instant B references identical
28
+ * bytes from a public cell. The fix is to scope authz to the
29
+ * `(cell, hash)` edge: a caller reads a fact *through a specific cell it
30
+ * can view that references the hash*. Dedup becomes a pure storage
31
+ * optimization with zero authz consequence whether two owners' bytes
32
+ * share a `fact` row is invisible to the read check.
33
+ *
34
+ * The cell-scoped route resolves the named cell, requires
35
+ * `can_view_cell(caller, cell)`, and requires `cell.refs` to include the
36
+ * hash. B publishing identical bytes from B's public cell makes them
37
+ * readable *via B's cell* — it never touches A's private reference.
38
+ *
39
+ * The bare-hash route is **admin-only**: an admin's reach already spans
40
+ * every cell, so serving by bare hash grants no escalation. Non-admin
41
+ * callers are rejected at the auth phase and never reach the handler.
42
+ * (Explicitly-public facts a producer opting bytes into world-readable
43
+ * status — are a future refinement; there is no such concept today, so
44
+ * the bare-hash route stays strictly admin-gated.)
45
+ *
46
+ * Auth shape on the cell-scoped route is `{account: 'none', actor: 'none'}`
47
+ * — the dispatcher's authorization phase is skipped for pure-public routes,
48
+ * so the handler builds the `RequestContext` itself from `c.var.account_id`
49
+ * (populated by the `/api/*` session middleware) by resolving the caller's
50
+ * single actor and loading their role_grants. Unauthed callers pass through
51
+ * with `req_ctx: null` and are admitted only by a `cell.visibility ===
52
+ * 'public'` cell. Multi-actor accounts fall through with `req_ctx: null`
53
+ * — there's no `acting?` slot on a pure-public route, so multi-actor
54
+ * callers are treated as anonymous.
55
+ *
56
+ * 404 is the universal "not viewable" response: missing fact, missing or
57
+ * unviewable cell, or the cell doesn't reference the hash. We deliberately
58
+ * don't distinguish 403 from 404 — neither the existence of a fact nor the
59
+ * existence of a cell→fact edge should leak through the public surface.
60
+ *
61
+ * Content-addressed serving of inline `blake3:` images (a markdown doc cell
62
+ * with embedded image refs) works through this model: the referencing cell
63
+ * is the doc cell, so serving goes view-doc-cell → doc-cell-refs-include-hash
64
+ * → serve.
36
65
  *
37
66
  * ## Defense-in-depth
38
67
  *
@@ -68,11 +97,33 @@ export interface CreateServeFactRouteSpecOptions {
68
97
  log: Logger;
69
98
  }
70
99
  /**
71
- * Build the `GET /api/facts/:hash` `RouteSpec`.
100
+ * Build the cell-scoped `GET /api/cells/:cell_id/facts/:hash` `RouteSpec`
101
+ * — the per-reference read.
102
+ *
103
+ * Resolves the named cell (404 if missing / soft-deleted), requires
104
+ * `can_view_cell(caller, cell)` AND `cell.refs` to include the hash
105
+ * (else 404, masked), then serves the bytes. Authz is scoped to this one
106
+ * `(cell, hash)` edge — never unioned across the fact's other referrers.
72
107
  *
73
108
  * Pure-public auth — the handler builds the per-request `RequestContext`
74
- * from `c.var.account_id` and enforces visibility per-fact via the
75
- * cell-walk above.
109
+ * from `c.var.account_id` and enforces visibility per-reference.
110
+ */
111
+ export declare const create_serve_cell_fact_route_spec: (options: CreateServeFactRouteSpecOptions) => RouteSpec;
112
+ /**
113
+ * Build the admin-only bare-hash `GET /api/facts/:hash` `RouteSpec`.
114
+ *
115
+ * An admin's reach already spans every cell, so serving by bare hash grants
116
+ * no escalation — the union concern that made this route a cross-owner leak
117
+ * for non-admins is vacuous for an admin. Non-admin callers are rejected at
118
+ * the auth phase (403) and never reach the handler. Confidential non-admin
119
+ * reads always go through the cell-scoped route above.
120
+ *
121
+ * Auth is `{account: 'required', actor: 'required', roles: ['admin']}` —
122
+ * the dispatcher's authorization phase resolves the acting actor and the
123
+ * post-authorization guard enforces the admin role before the handler runs.
124
+ * The handler re-checks `has_role(_, admin)` as defense-in-depth so a future
125
+ * mounting/auth-shape regression fails closed rather than serving by bare
126
+ * hash to a non-admin.
76
127
  */
77
128
  export declare const create_serve_fact_route_spec: (options: CreateServeFactRouteSpecOptions) => RouteSpec;
78
129
  //# sourceMappingURL=serve_fact_route.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"serve_fact_route.d.ts","sourceRoot":"../src/lib/","sources":["../../src/lib/server/serve_fact_route.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4CG;AAKH,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,yBAAyB,CAAC;AAOpD,OAAO,EAAmB,KAAK,SAAS,EAAC,MAAM,uBAAuB,CAAC;AAEvE,OAAO,KAAK,EAAC,OAAO,EAAC,MAAM,iBAAiB,CAAC;AAoB7C,MAAM,WAAW,+BAA+B;IAC/C;;;;;;OAMG;IACH,IAAI,EAAE,OAAO,CAAC;IACd,kFAAkF;IAClF,SAAS,EAAE,MAAM,CAAC;IAClB;;;;;;OAMG;IACH,uBAAuB,CAAC,EAAE,MAAM,CAAC;IACjC,GAAG,EAAE,MAAM,CAAC;CACZ;AAED;;;;;;GAMG;AACH,eAAO,MAAM,4BAA4B,GACxC,SAAS,+BAA+B,KACtC,SAgIF,CAAC"}
1
+ {"version":3,"file":"serve_fact_route.d.ts","sourceRoot":"../src/lib/","sources":["../../src/lib/server/serve_fact_route.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyEG;AAMH,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,yBAAyB,CAAC;AAepD,OAAO,EAAsC,KAAK,SAAS,EAAC,MAAM,uBAAuB,CAAC;AAE1F,OAAO,KAAK,EAAC,OAAO,EAAC,MAAM,iBAAiB,CAAC;AAsC7C,MAAM,WAAW,+BAA+B;IAC/C;;;;;;OAMG;IACH,IAAI,EAAE,OAAO,CAAC;IACd,kFAAkF;IAClF,SAAS,EAAE,MAAM,CAAC;IAClB;;;;;;OAMG;IACH,uBAAuB,CAAC,EAAE,MAAM,CAAC;IACjC,GAAG,EAAE,MAAM,CAAC;CACZ;AAwGD;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,iCAAiC,GAC7C,SAAS,+BAA+B,KACtC,SA8CF,CAAC;AAEF;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,4BAA4B,GACxC,SAAS,+BAA+B,KACtC,SAgCF,CAAC"}
@@ -1,38 +1,67 @@
1
1
  /**
2
- * `GET /api/facts/:hash`content-addressed fact serving.
2
+ * Content-addressed fact serving cell-scoped, per-reference reads.
3
3
  *
4
- * Resolves a fact hash to the bytes referenced by at least one viewable
5
- * cell. Embedded facts stream from the `facts.bytes` PG column;
6
- * external facts (filesystem-backed `file:<shard>/<rest>` URLs) either
7
- * return an `X-Accel-Redirect` header pointing into nginx's internal
8
- * facts location (production) or stream from disk via the filesystem
9
- * `FactExternalFetcher` (dev / tests). The runtime mode is selected by
10
- * the optional `x_accel_redirect_prefix` factory option — set in prod,
11
- * unset in dev.
4
+ * Two routes serve fact bytes from the PG-backed fact store:
5
+ *
6
+ * - `GET /api/cells/:cell_id/facts/:hash` the **per-reference read**.
7
+ * The request names the referencing cell. Authz is scoped to that one
8
+ * reference: `can_view_cell(caller, cell) AND cell.refs includes hash`.
9
+ * This is the path non-admin callers use, and the only path for
10
+ * confidential content.
11
+ * - `GET /api/facts/:hash` — the **bare-hash read**, restricted to admins.
12
+ *
13
+ * Embedded facts stream from the `fact.bytes` PG column; external facts
14
+ * (filesystem-backed `file:<shard>/<rest>` URLs) either return an
15
+ * `X-Accel-Redirect` header pointing into nginx's internal facts location
16
+ * (production) or stream from disk via the filesystem `FactExternalFetcher`
17
+ * (dev / tests). The runtime mode is selected by the optional
18
+ * `x_accel_redirect_prefix` factory option — set in prod, unset in dev.
12
19
  *
13
20
  * REST, not RPC: binary responses don't fit the JSON-RPC envelope.
14
21
  *
15
- * ## Authorization
16
- *
17
- * Auth is `{account: 'none', actor: 'none'}` — the dispatcher's
18
- * authorization phase is skipped for pure-public routes, so this handler
19
- * builds the `RequestContext` itself from `c.var.account_id` (populated
20
- * by the `/api/*` session middleware) by resolving the caller's single
21
- * actor and loading their role_grants. Unauthed callers pass through
22
- * with `req_ctx: null`. Viewers are admitted via `can_view_cell` over
23
- * **every** active cell that references the hash. Multi-actor accounts
24
- * fall through with `req_ctx: null`there's no `acting?` slot on a
25
- * pure-public route, so multi-actor callers are treated as anonymous
26
- * (admitted only by the public-visibility branch). A fact is viewable iff
27
- * at least one referencing cell admits the caller; unauthenticated callers
28
- * are admitted only via a referencing cell with `cell.visibility ===
29
- * 'public'`. Facts with no referencing active cell are unreachable here
30
- * orphan-fact GC reaps them separately.
31
- *
32
- * 404 is the universal "not viewable" response: missing fact, missing
33
- * referencing cell, all referencing cells private to other actors. We
34
- * deliberately don't distinguish 403 from 404 the existence of a
35
- * private hash should not leak through the public surface.
22
+ * ## Authorization — authz lives on the cell→fact edge, not the hash
23
+ *
24
+ * Facts are global, content-addressed, owner-less bytes: identical bytes
25
+ * from different owners dedup to **one** `fact` row. Keying access control
26
+ * on the bare hash therefore unions visibility across every owner that
27
+ * references it A's private bytes leak the instant B references identical
28
+ * bytes from a public cell. The fix is to scope authz to the
29
+ * `(cell, hash)` edge: a caller reads a fact *through a specific cell it
30
+ * can view that references the hash*. Dedup becomes a pure storage
31
+ * optimization with zero authz consequence whether two owners' bytes
32
+ * share a `fact` row is invisible to the read check.
33
+ *
34
+ * The cell-scoped route resolves the named cell, requires
35
+ * `can_view_cell(caller, cell)`, and requires `cell.refs` to include the
36
+ * hash. B publishing identical bytes from B's public cell makes them
37
+ * readable *via B's cell* — it never touches A's private reference.
38
+ *
39
+ * The bare-hash route is **admin-only**: an admin's reach already spans
40
+ * every cell, so serving by bare hash grants no escalation. Non-admin
41
+ * callers are rejected at the auth phase and never reach the handler.
42
+ * (Explicitly-public facts a producer opting bytes into world-readable
43
+ * status — are a future refinement; there is no such concept today, so
44
+ * the bare-hash route stays strictly admin-gated.)
45
+ *
46
+ * Auth shape on the cell-scoped route is `{account: 'none', actor: 'none'}`
47
+ * — the dispatcher's authorization phase is skipped for pure-public routes,
48
+ * so the handler builds the `RequestContext` itself from `c.var.account_id`
49
+ * (populated by the `/api/*` session middleware) by resolving the caller's
50
+ * single actor and loading their role_grants. Unauthed callers pass through
51
+ * with `req_ctx: null` and are admitted only by a `cell.visibility ===
52
+ * 'public'` cell. Multi-actor accounts fall through with `req_ctx: null`
53
+ * — there's no `acting?` slot on a pure-public route, so multi-actor
54
+ * callers are treated as anonymous.
55
+ *
56
+ * 404 is the universal "not viewable" response: missing fact, missing or
57
+ * unviewable cell, or the cell doesn't reference the hash. We deliberately
58
+ * don't distinguish 403 from 404 — neither the existence of a fact nor the
59
+ * existence of a cell→fact edge should leak through the public surface.
60
+ *
61
+ * Content-addressed serving of inline `blake3:` images (a markdown doc cell
62
+ * with embedded image refs) works through this model: the referencing cell
63
+ * is the doc cell, so serving goes view-doc-cell → doc-cell-refs-include-hash
64
+ * → serve.
36
65
  *
37
66
  * ## Defense-in-depth
38
67
  *
@@ -47,151 +76,223 @@ import { createReadStream } from 'node:fs';
47
76
  import { Readable } from 'node:stream';
48
77
  import { join } from 'node:path';
49
78
  import { FactHashSchema } from '@fuzdev/fuz_util/fact_hash.js';
79
+ import { Uuid } from '@fuzdev/fuz_util/id.js';
50
80
  import { z } from 'zod';
51
- import { build_request_context } from '../auth/request_context.js';
81
+ import { build_request_context, get_request_context, has_role, } from '../auth/request_context.js';
82
+ import { ROLE_ADMIN } from '../auth/role_schema.js';
83
+ import { ActingActor } from '../http/auth_shape.js';
52
84
  import { ACCOUNT_ID_KEY } from '../hono_context.js';
53
85
  import { query_actors_by_account } from '../auth/account_queries.js';
54
86
  import { get_route_params } from '../http/route_spec.js';
55
87
  import { ERROR_INVALID_ROUTE_PARAMS } from '../http/error_schemas.js';
56
88
  import { query_get_fact, query_get_fact_meta } from '../db/fact_queries.js';
57
- import { query_cell_list_by_ref } from '../db/cell_queries.js';
89
+ import { query_cell_get } from '../db/cell_queries.js';
58
90
  import { query_cell_grant_list_for_cell } from '../db/cell_grant_queries.js';
59
91
  import { can_view_cell } from '../auth/cell_authorize.js';
60
92
  import { parse_file_fact_url } from './file_fact_url.js';
61
93
  /** `Cache-Control` for fact responses — 5 min revocation window. */
62
94
  const CACHE_CONTROL = 'private, max-age=300';
63
95
  /**
64
- * Path-param schema. Matching the canonical fact-hash form here pushes
65
- * malformed-hash 400s through the framework's standard params-validation
66
- * error shape (`ERROR_INVALID_ROUTE_PARAMS`), which the round-trip
67
- * validator expects.
96
+ * Path-param schema for the bare-hash route. Matching the canonical
97
+ * fact-hash form here pushes malformed-hash 400s through the framework's
98
+ * standard params-validation error shape (`ERROR_INVALID_ROUTE_PARAMS`),
99
+ * which the round-trip validator expects.
100
+ */
101
+ const bare_hash_params_schema = z.strictObject({
102
+ hash: FactHashSchema,
103
+ });
104
+ /**
105
+ * Path-param schema for the cell-scoped route. `cell_id` validates as a
106
+ * `Uuid`; `hash` as the canonical fact-hash form. Malformed values 400 via
107
+ * the standard params-validation shape.
68
108
  */
69
- const params_schema = z.strictObject({
109
+ const cell_fact_params_schema = z.strictObject({
110
+ cell_id: Uuid,
70
111
  hash: FactHashSchema,
71
112
  });
113
+ /** Shared error-schema entry: tighten the auto-derived 400 to the literal emitted by params validation. */
114
+ const params_400_error = {
115
+ 400: z.looseObject({
116
+ error: z.literal(ERROR_INVALID_ROUTE_PARAMS),
117
+ issues: z.array(z.unknown()),
118
+ }),
119
+ };
120
+ /**
121
+ * Serve a fact's bytes by hash, after the caller has been authorized for it.
122
+ *
123
+ * This is the shared tail of both routes — it never re-checks authz, so it
124
+ * MUST only be called once the caller has been admitted (admin on the
125
+ * bare-hash route, viewable referencing cell on the cell-scoped route).
126
+ * Reuses the embedded-stream / `X-Accel-Redirect` / disk-stream logic.
127
+ *
128
+ * Returns 404 when the fact's metadata is missing or its embedded bytes
129
+ * have vanished (a race), so the response shape is identical whether the
130
+ * fact is genuinely absent or merely unviewable.
131
+ */
132
+ const serve_fact_bytes = async (c, route, hash, config) => {
133
+ const { facts_dir, x_accel_redirect_prefix, log } = config;
134
+ const meta = await query_get_fact_meta({ db: route.db }, hash);
135
+ if (!meta) {
136
+ return c.body(null, 404);
137
+ }
138
+ const content_type = meta.content_type ?? 'application/octet-stream';
139
+ const size = String(meta.size);
140
+ if (meta.external_url === null) {
141
+ // Embedded — bytes live in the PG row.
142
+ const row = await query_get_fact({ db: route.db }, hash);
143
+ if (!row || row.bytes === null) {
144
+ // Race: meta said embedded but bytes vanished. Treat as not-found.
145
+ log.warn(`serve_fact: embedded bytes missing for ${hash} (meta said embedded, row=${row ? 'present' : 'null'})`);
146
+ return c.body(null, 404);
147
+ }
148
+ const bytes = to_uint8(row.bytes);
149
+ return c.body(bytes, 200, {
150
+ 'Content-Type': content_type,
151
+ 'Content-Length': size,
152
+ 'Cache-Control': CACHE_CONTROL,
153
+ });
154
+ }
155
+ // External — defense-in-depth re-validate the URL before trusting it
156
+ // to address the filesystem.
157
+ const parsed = parse_file_fact_url(meta.external_url);
158
+ if (!parsed) {
159
+ log.error(`serve_fact: rejecting malformed external_url for ${hash}: ${meta.external_url}`);
160
+ return c.body(null, 404);
161
+ }
162
+ const { shard, rest } = parsed;
163
+ if (x_accel_redirect_prefix !== undefined) {
164
+ // Production: hand off to nginx via the internal facts location.
165
+ return c.body(null, 200, {
166
+ 'Content-Type': content_type,
167
+ 'Content-Length': size,
168
+ 'Cache-Control': CACHE_CONTROL,
169
+ 'X-Accel-Redirect': `${x_accel_redirect_prefix}${shard}/${rest}`,
170
+ });
171
+ }
172
+ // Dev / tests: stream from disk. `createReadStream` errors land on the
173
+ // returned ReadableStream, which Hono surfaces as a 500 to the client.
174
+ const file_path = join(facts_dir, shard, rest);
175
+ const node_stream = createReadStream(file_path);
176
+ const web_stream = Readable.toWeb(node_stream);
177
+ return c.body(web_stream, 200, {
178
+ 'Content-Type': content_type,
179
+ 'Content-Length': size,
180
+ 'Cache-Control': CACHE_CONTROL,
181
+ });
182
+ };
72
183
  /**
73
- * Build the `GET /api/facts/:hash` `RouteSpec`.
184
+ * Resolve the caller's `RequestContext` on a pure-public route from the
185
+ * session-middleware-set account id. Multi-actor accounts return `null`
186
+ * (no `acting?` slot on a public route to disambiguate); single-actor
187
+ * accounts resolve their actor and role_grants for owner / grant / admin
188
+ * admission paths. Unauthenticated callers return `null`.
189
+ */
190
+ const build_public_request_context = async (c, route) => {
191
+ const account_id = c.get(ACCOUNT_ID_KEY);
192
+ if (!account_id)
193
+ return null;
194
+ const actors = await query_actors_by_account({ db: route.db }, account_id);
195
+ if (actors.length !== 1)
196
+ return null;
197
+ return build_request_context({ db: route.db }, account_id, actors[0].id);
198
+ };
199
+ /**
200
+ * Build the cell-scoped `GET /api/cells/:cell_id/facts/:hash` `RouteSpec`
201
+ * — the per-reference read.
202
+ *
203
+ * Resolves the named cell (404 if missing / soft-deleted), requires
204
+ * `can_view_cell(caller, cell)` AND `cell.refs` to include the hash
205
+ * (else 404, masked), then serves the bytes. Authz is scoped to this one
206
+ * `(cell, hash)` edge — never unioned across the fact's other referrers.
74
207
  *
75
208
  * Pure-public auth — the handler builds the per-request `RequestContext`
76
- * from `c.var.account_id` and enforces visibility per-fact via the
77
- * cell-walk above.
209
+ * from `c.var.account_id` and enforces visibility per-reference.
78
210
  */
79
- export const create_serve_fact_route_spec = (options) => {
211
+ export const create_serve_cell_fact_route_spec = (options) => {
80
212
  const { facts_dir, x_accel_redirect_prefix, log } = options;
213
+ const config = { facts_dir, x_accel_redirect_prefix, log };
81
214
  return {
82
215
  method: 'GET',
83
- path: '/api/facts/:hash',
216
+ path: '/api/cells/:cell_id/facts/:hash',
84
217
  auth: { account: 'none', actor: 'none' },
85
- description: 'Serve content-addressed fact bytes. 404 unless at least one referencing cell admits the caller via can_view_cell.',
86
- params: params_schema,
218
+ description: 'Serve content-addressed fact bytes through a named referencing cell. 404 unless the cell admits the caller via can_view_cell AND references the hash (per-reference, never union-of-referrers).',
219
+ params: cell_fact_params_schema,
87
220
  input: z.null(),
88
221
  // The body is a binary stream; no JSON output schema applies.
89
222
  output: z.null(),
90
- errors: {
91
- // Tighten the auto-derived 400 from `ApiError` (`error: string`) to
92
- // the actual literal emitted by `create_params_validation`, so
93
- // `assert_error_schema_tightness` reads the surface as specific
94
- // rather than generic.
95
- 400: z.looseObject({
96
- error: z.literal(ERROR_INVALID_ROUTE_PARAMS),
97
- issues: z.array(z.unknown()),
98
- }),
99
- },
223
+ errors: params_400_error,
100
224
  handler: async (c, route) => {
101
- const { hash } = get_route_params(c);
102
- const meta = await query_get_fact_meta({ db: route.db }, hash);
103
- if (!meta) {
225
+ const { cell_id, hash } = get_route_params(c);
226
+ // Resolve the named cell. Missing / soft-deleted → 404 (masked).
227
+ const cell = await query_cell_get({ db: route.db }, cell_id);
228
+ if (!cell) {
104
229
  return c.body(null, 404);
105
230
  }
106
- // Pure-public route dispatcher skips the authorization phase, so
107
- // build the `RequestContext` here from the session-middleware-set
108
- // account id. Multi-actor accounts fall through with `null` (no
109
- // `acting?` slot on a public route to disambiguate); single-actor
110
- // accounts resolve their actor and role_grants for owner / grant /
111
- // admin admission paths.
112
- const account_id = c.get(ACCOUNT_ID_KEY);
113
- let req_ctx = null;
114
- if (account_id) {
115
- const actors = await query_actors_by_account({ db: route.db }, account_id);
116
- if (actors.length === 1) {
117
- req_ctx = await build_request_context({ db: route.db }, account_id, actors[0].id);
118
- }
119
- }
120
- // `include_grant_count: false` — the authz walk only reads
121
- // `can_view_cell`-relevant fields, so skip the per-row grant
122
- // COUNT subquery. Cheap to begin with; even cheaper now.
123
- const referencing_cells = await query_cell_list_by_ref({ db: route.db }, hash, {
124
- include_grant_count: false,
125
- });
126
- // Sequential walk with early break on first admit — preserves
127
- // the original `.some()` short-circuit. Unauthenticated callers
128
- // skip the grant fetch entirely since no grant can admit a null
129
- // req_ctx (the only admit path is the public-visibility branch
130
- // in `can_view_cell`, which doesn't need grants). Authenticated
131
- // callers eat one `cell_grant` lookup per referencing cell up
132
- // to the first admit; acceptable at MVP fact-serve scale.
133
- // TODO: if profiling shows this hot, batch grants in one query
134
- // across all referencing cells, or push the predicate into SQL.
135
- let viewable = false;
136
- for (const cell of referencing_cells) {
137
- const grants = req_ctx
138
- ? await query_cell_grant_list_for_cell({ db: route.db }, cell.id)
139
- : null;
140
- if (can_view_cell(req_ctx, cell, grants)) {
141
- viewable = true;
142
- break;
143
- }
144
- }
145
- if (!viewable) {
146
- // 404 (not 403) so existence of private hashes doesn't leak
147
- // through the public surface. Same response shape as a
148
- // genuinely missing fact.
231
+ // The cell→fact edge: the cell must actually reference the hash.
232
+ // `cell.refs` is auto-derived from `data` on every write, so this is
233
+ // the authoritative "does this cell reference these bytes" check.
234
+ // Missing edge 404 (masked), never "exists elsewhere".
235
+ if (!cell.refs?.includes(hash)) {
149
236
  return c.body(null, 404);
150
237
  }
151
- const content_type = meta.content_type ?? 'application/octet-stream';
152
- const size = String(meta.size);
153
- if (meta.external_url === null) {
154
- // Embedded bytes live in the PG row.
155
- const row = await query_get_fact({ db: route.db }, hash);
156
- if (!row || row.bytes === null) {
157
- // Race: meta said embedded but bytes vanished. Treat as not-found.
158
- log.warn(`serve_fact: embedded bytes missing for ${hash} (meta said embedded, row=${row ? 'present' : 'null'})`);
159
- return c.body(null, 404);
160
- }
161
- const bytes = to_uint8(row.bytes);
162
- return c.body(bytes, 200, {
163
- 'Content-Type': content_type,
164
- 'Content-Length': size,
165
- 'Cache-Control': CACHE_CONTROL,
166
- });
167
- }
168
- // External — defense-in-depth re-validate the URL before trusting it
169
- // to address the filesystem.
170
- const parsed = parse_file_fact_url(meta.external_url);
171
- if (!parsed) {
172
- log.error(`serve_fact: rejecting malformed external_url for ${hash}: ${meta.external_url}`);
238
+ // Per-reference view check scoped to *this* cell only.
239
+ const req_ctx = await build_public_request_context(c, route);
240
+ // Unauthenticated callers skip the grant fetch entirely — no grant
241
+ // can admit a null req_ctx (the only admit path is the
242
+ // public-visibility branch in `can_view_cell`, which doesn't read
243
+ // grants).
244
+ const grants = req_ctx ? await query_cell_grant_list_for_cell({ db: route.db }, cell.id) : null;
245
+ if (!can_view_cell(req_ctx, cell, grants)) {
246
+ // 404 (not 403) so an unviewable cell→fact edge doesn't leak.
173
247
  return c.body(null, 404);
174
248
  }
175
- const { shard, rest } = parsed;
176
- if (x_accel_redirect_prefix !== undefined) {
177
- // Production: hand off to nginx via the internal facts location.
178
- return c.body(null, 200, {
179
- 'Content-Type': content_type,
180
- 'Content-Length': size,
181
- 'Cache-Control': CACHE_CONTROL,
182
- 'X-Accel-Redirect': `${x_accel_redirect_prefix}${shard}/${rest}`,
183
- });
249
+ return serve_fact_bytes(c, route, hash, config);
250
+ },
251
+ };
252
+ };
253
+ /**
254
+ * Build the admin-only bare-hash `GET /api/facts/:hash` `RouteSpec`.
255
+ *
256
+ * An admin's reach already spans every cell, so serving by bare hash grants
257
+ * no escalation — the union concern that made this route a cross-owner leak
258
+ * for non-admins is vacuous for an admin. Non-admin callers are rejected at
259
+ * the auth phase (403) and never reach the handler. Confidential non-admin
260
+ * reads always go through the cell-scoped route above.
261
+ *
262
+ * Auth is `{account: 'required', actor: 'required', roles: ['admin']}` —
263
+ * the dispatcher's authorization phase resolves the acting actor and the
264
+ * post-authorization guard enforces the admin role before the handler runs.
265
+ * The handler re-checks `has_role(_, admin)` as defense-in-depth so a future
266
+ * mounting/auth-shape regression fails closed rather than serving by bare
267
+ * hash to a non-admin.
268
+ */
269
+ export const create_serve_fact_route_spec = (options) => {
270
+ const { facts_dir, x_accel_redirect_prefix, log } = options;
271
+ const config = { facts_dir, x_accel_redirect_prefix, log };
272
+ return {
273
+ method: 'GET',
274
+ path: '/api/facts/:hash',
275
+ auth: { account: 'required', actor: 'required', roles: [ROLE_ADMIN] },
276
+ description: 'Serve content-addressed fact bytes by bare hash — admin only. Non-admin reads go through GET /api/cells/:cell_id/facts/:hash (per-reference).',
277
+ params: bare_hash_params_schema,
278
+ // `actor: 'required'` (implied by the admin role gate) needs the
279
+ // authorization phase to resolve an acting actor — registry-time
280
+ // invariant 2 requires the `acting?` slot. On a GET it lives on
281
+ // `query` (a multi-actor admin disambiguates via `?acting=<actor>`).
282
+ query: z.strictObject({ acting: ActingActor }),
283
+ input: z.null(),
284
+ // The body is a binary stream; no JSON output schema applies.
285
+ output: z.null(),
286
+ errors: params_400_error,
287
+ handler: async (c, route) => {
288
+ const { hash } = get_route_params(c);
289
+ // Defense-in-depth: the auth phase already gated this on the admin
290
+ // role, but re-check the resolved context so a mounting/auth-shape
291
+ // regression fails closed instead of serving by bare hash.
292
+ if (!has_role(get_request_context(c), ROLE_ADMIN)) {
293
+ return c.body(null, 404);
184
294
  }
185
- // Dev / tests: stream from disk. `createReadStream` errors land on the
186
- // returned ReadableStream, which Hono surfaces as a 500 to the client.
187
- const file_path = join(facts_dir, shard, rest);
188
- const node_stream = createReadStream(file_path);
189
- const web_stream = Readable.toWeb(node_stream);
190
- return c.body(web_stream, 200, {
191
- 'Content-Type': content_type,
192
- 'Content-Length': size,
193
- 'Cache-Control': CACHE_CONTROL,
194
- });
295
+ return serve_fact_bytes(c, route, hash, config);
195
296
  },
196
297
  };
197
298
  };
@@ -574,7 +574,11 @@ auth-related routes (login/logout/verify/sessions/tokens/password/signup)
574
574
  and asserts `DEFAULT_INTEGRATION_ERROR_COVERAGE` (20%). Bootstrap is
575
575
  excluded because no describe block in this suite drives it — its declared
576
576
  codes would always be uncovered. Consumer-specific routes aren't exercised
577
- here either — they don't count against the baseline. Override with
577
+ here either — they don't count against the baseline. 403 authorization
578
+ denials (the credential-channel gate on `/logout` + `/password`, the invite
579
+ gate on `/signup`) are likewise excluded via `ignore_statuses: [403]` — they're
580
+ exercised by the conformance + attack-surface suites, not this lifecycle suite.
581
+ Override with
578
582
  `error_coverage_min?: number` (set to `0` to skip the assertion — useful for
579
583
  minimal route sets whose declared error codes outpace the suite's
580
584
  denial-path drivers).
@@ -1 +1 @@
1
- {"version":3,"file":"integration.d.ts","sourceRoot":"../src/lib/","sources":["../../src/lib/testing/integration.ts"],"names":[],"mappings":"AAAA,OAAO,qBAAqB,CAAC;AAsB7B,OAAO,KAAK,EAAC,cAAc,EAAC,MAAM,2BAA2B,CAAC;AAM9D,OAAO,EAKN,KAAK,uBAAuB,EAC5B,MAAM,kBAAkB,CAAC;AAiB1B,OAAO,KAAK,EAAC,cAAc,EAAC,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAC,KAAK,mBAAmB,EAAC,MAAM,iCAAiC,CAAC;AACzE,OAAO,KAAK,EAAC,SAAS,EAAC,MAAM,0BAA0B,CAAC;AAGxD;;GAEG;AACH,MAAM,WAAW,8BAA8B;IAC9C;;;;OAIG;IACH,UAAU,EAAE,SAAS,CAAC;IACtB;;;;;;;;;OASG;IACH,cAAc,EAAE,cAAc,CAAC;IAC/B,kEAAkE;IAClE,YAAY,EAAE,mBAAmB,CAAC;IAClC;;;;OAIG;IACH,eAAe,EAAE,cAAc,CAAC,MAAM,CAAC,CAAC;IACxC;;;;;;;;;;;;OAYG;IACH,aAAa,EAAE,uBAAuB,CAAC;IACvC;;;;;;;OAOG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,eAAO,MAAM,mCAAmC,GAC/C,SAAS,8BAA8B,KACrC,IA60CF,CAAC"}
1
+ {"version":3,"file":"integration.d.ts","sourceRoot":"../src/lib/","sources":["../../src/lib/testing/integration.ts"],"names":[],"mappings":"AAAA,OAAO,qBAAqB,CAAC;AAsB7B,OAAO,KAAK,EAAC,cAAc,EAAC,MAAM,2BAA2B,CAAC;AAM9D,OAAO,EAKN,KAAK,uBAAuB,EAC5B,MAAM,kBAAkB,CAAC;AAkB1B,OAAO,KAAK,EAAC,cAAc,EAAC,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAC,KAAK,mBAAmB,EAAC,MAAM,iCAAiC,CAAC;AACzE,OAAO,KAAK,EAAC,SAAS,EAAC,MAAM,0BAA0B,CAAC;AAGxD;;GAEG;AACH,MAAM,WAAW,8BAA8B;IAC9C;;;;OAIG;IACH,UAAU,EAAE,SAAS,CAAC;IACtB;;;;;;;;;OASG;IACH,cAAc,EAAE,cAAc,CAAC;IAC/B,kEAAkE;IAClE,YAAY,EAAE,mBAAmB,CAAC;IAClC;;;;OAIG;IACH,eAAe,EAAE,cAAc,CAAC,MAAM,CAAC,CAAC;IACxC;;;;;;;;;;;;OAYG;IACH,aAAa,EAAE,uBAAuB,CAAC;IACvC;;;;;;;OAOG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,eAAO,MAAM,mCAAmC,GAC/C,SAAS,8BAA8B,KACrC,IAw6CF,CAAC"}
@@ -23,6 +23,7 @@ import { ErrorCoverageCollector, assert_error_coverage, DEFAULT_INTEGRATION_ERRO
23
23
  import { is_public_auth } from '../http/auth_shape.js';
24
24
  import { account_verify_action_spec, account_session_list_action_spec, account_session_revoke_action_spec, account_session_revoke_all_action_spec, account_token_create_action_spec, account_token_list_action_spec, account_token_revoke_action_spec, } from '../auth/account_action_specs.js';
25
25
  import { invite_create_action_spec } from '../auth/admin_action_specs.js';
26
+ import { LoginOutput, AccountStatusOutput } from '../auth/account_routes.js';
26
27
  import {} from './cross_backend/capabilities.js';
27
28
  import { DEFAULT_TEST_PASSWORD } from './app_server.js';
28
29
  /**
@@ -91,6 +92,14 @@ export const describe_standard_integration_tests = (options) => {
91
92
  });
92
93
  assert_error_coverage(error_collector, auth_routes.length > 0 ? auth_routes : route_specs, {
93
94
  min_coverage: options.error_coverage_min ?? DEFAULT_INTEGRATION_ERROR_COVERAGE,
95
+ // Authorization denials (403) on these scoped auth routes — the
96
+ // credential-channel gate on /logout + /password, the invite gate on
97
+ // /signup — are exercised by the conformance + attack-surface suites,
98
+ // not this lifecycle suite. Drop 403 from this collector's denominator
99
+ // (same spirit as the [401, 403, 429] ignore in the attack-surface
100
+ // tightness defaults); otherwise #10 adding /logout's 403 to the spine
101
+ // surface tips the ratio under threshold here though the gate is tested.
102
+ ignore_statuses: [403],
94
103
  });
95
104
  });
96
105
  // --- 1. Login/logout lifecycle ---
@@ -269,6 +278,75 @@ export const describe_standard_integration_tests = (options) => {
269
278
  assert.deepStrictEqual(wrong_pw_keys, no_user_keys, 'Response keys must be identical to prevent account enumeration');
270
279
  assert.strictEqual(wrong_pw_body.error, no_user_body.error, 'Error codes must be identical');
271
280
  });
281
+ // Wire-shape gate: the successful `POST /login` body must strict-parse
282
+ // against `LoginOutput` (`{ok: true}`). `.strictObject` rejects any
283
+ // extra field, so a backend leaking `username` / `account_id` (the
284
+ // Rust spine's old shape) fails here on either impl.
285
+ test('successful login body strict-parses against LoginOutput', async () => {
286
+ const fixture = await options.setup_test();
287
+ const login_route = find_auth_route(route_specs, '/login', 'POST');
288
+ assert.ok(login_route, 'Expected POST /login route — ensure create_route_specs includes account routes');
289
+ const res = await fixture.transport(login_route.path, {
290
+ method: 'POST',
291
+ headers: {
292
+ host: 'localhost',
293
+ origin: 'http://localhost:5173',
294
+ 'content-type': 'application/json',
295
+ },
296
+ body: JSON.stringify({
297
+ username: fixture.account.username,
298
+ password: DEFAULT_TEST_PASSWORD,
299
+ }),
300
+ });
301
+ assert.strictEqual(res.status, 200);
302
+ const body = await res.json();
303
+ // Throws on any extra or missing field — drift on either backend fails.
304
+ LoginOutput.parse(body);
305
+ });
306
+ });
307
+ // --- 1b. Account status body (strict schema) ---
308
+ describe('account status response body', () => {
309
+ // Wire-shape gate: the authenticated `GET /api/account/status` body
310
+ // must strict-parse against `AccountStatusOutput` — the full shape
311
+ // `{account: SessionAccountJson, actor: ActorSummaryJson | null,
312
+ // role_grants: RoleGrantSummaryJson[]}`. `.strictObject` rejects any
313
+ // extra or missing field on `account` / `actor` / each role_grant, so
314
+ // a backend returning the old narrow shape (Rust's `{account:{id,
315
+ // username}, role_grants:[{role}]}`) fails here on either impl. The
316
+ // fixture keeper is single-actor, so `actor` must be non-null and
317
+ // `role_grants` populated (keeper holds keeper + admin globally).
318
+ //
319
+ // `/status` is mounted at `create_app_server` time (it needs the
320
+ // `bootstrap_available` runtime state), not by `create_account_route_specs`
321
+ // and not listed in the declared surface, so we can't gate on `route_specs`.
322
+ // A backend that mounts only the account-route factory (e.g. a minimal
323
+ // in-process route set) doesn't serve it — probe at runtime and skip on
324
+ // 404. The full spine surfaces (in-process + cross-process) serve it, so
325
+ // the gate runs there. `find_auth_route` can't be used: `/status` isn't a
326
+ // `RestAuthRouteSuffix`.
327
+ test('authenticated status body strict-parses against AccountStatusOutput', async (ctx) => {
328
+ const fixture = await options.setup_test();
329
+ const login_route = find_auth_route(route_specs, '/login', 'POST');
330
+ assert.ok(login_route, 'Expected POST /login route — ensure create_route_specs includes account routes');
331
+ // `/status` is the sibling of `/login` under the same account prefix.
332
+ const status_path = login_route.path.replace(/\/login$/, '/status');
333
+ const res = await fixture.transport(status_path, {
334
+ method: 'GET',
335
+ headers: fixture.create_session_headers({ host: 'localhost' }),
336
+ });
337
+ if (res.status === 404) {
338
+ // Backend doesn't mount /status (minimal route set) — nothing to gate.
339
+ ctx.skip();
340
+ return;
341
+ }
342
+ assert.strictEqual(res.status, 200);
343
+ const body = await res.json();
344
+ // Throws on any extra/missing field across account/actor/role_grants.
345
+ const parsed = AccountStatusOutput.parse(body);
346
+ // Single-actor keeper: actor resolved, role_grants populated.
347
+ assert.ok(parsed.actor, 'single-actor keeper must resolve a non-null actor');
348
+ assert.ok(parsed.role_grants.length > 0, 'single-actor keeper must have populated role_grants');
349
+ });
272
350
  });
273
351
  // --- 2. Cookie attributes ---
274
352
  describe('cookie attributes', () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fuzdev/fuz_app",
3
- "version": "0.75.0",
3
+ "version": "0.76.0",
4
4
  "description": "fullstack app library",
5
5
  "glyph": "🗝",
6
6
  "logo": "logo.svg",
@@ -63,10 +63,10 @@
63
63
  },
64
64
  "devDependencies": {
65
65
  "@electric-sql/pglite": "^0.4.5",
66
- "@fuzdev/blake3_wasm": "^0.1.0",
66
+ "@fuzdev/blake3_wasm": "^0.1.1",
67
67
  "@fuzdev/fuz_code": "^0.45.1",
68
- "@fuzdev/fuz_css": "^0.60.0",
69
- "@fuzdev/fuz_ui": "^0.195.1",
68
+ "@fuzdev/fuz_css": "^0.61.1",
69
+ "@fuzdev/fuz_ui": "^0.197.0",
70
70
  "@fuzdev/fuz_util": "^0.63.0",
71
71
  "@fuzdev/gro": "^0.200.0",
72
72
  "@hono/node-server": "^1.19.14",
@@ -94,7 +94,7 @@
94
94
  "prettier-plugin-svelte": "^3.5.1",
95
95
  "svelte": "^5.56.0",
96
96
  "svelte-check": "^4.4.5",
97
- "svelte-docinfo": "^0.2.0",
97
+ "svelte-docinfo": "^0.2.1",
98
98
  "svelte2tsx": "^0.7.52",
99
99
  "tslib": "^2.8.1",
100
100
  "typescript": "^5.9.3",