@fuzdev/fuz_app 0.164.0 → 0.166.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.
Files changed (112) hide show
  1. package/dist/actions/CLAUDE.md +2 -2
  2. package/dist/actions/action_event_data.d.ts +1 -1
  3. package/dist/actions/action_rpc.d.ts.map +1 -1
  4. package/dist/actions/action_rpc.js +24 -15
  5. package/dist/actions/action_spec.d.ts +2 -2
  6. package/dist/actions/perform_action.d.ts +2 -1
  7. package/dist/actions/perform_action.d.ts.map +1 -1
  8. package/dist/auth/account_action_specs.d.ts +8 -8
  9. package/dist/auth/account_route_schema.d.ts +197 -164
  10. package/dist/auth/account_route_schema.d.ts.map +1 -1
  11. package/dist/auth/account_route_schema.js +19 -17
  12. package/dist/auth/account_routes.d.ts.map +1 -1
  13. package/dist/auth/account_routes.js +285 -294
  14. package/dist/auth/admin_action_specs.d.ts +64 -64
  15. package/dist/auth/audit_log_route_schema.d.ts +16 -8
  16. package/dist/auth/audit_log_route_schema.d.ts.map +1 -1
  17. package/dist/auth/audit_log_route_schema.js +4 -3
  18. package/dist/auth/audit_log_routes.d.ts +1 -1
  19. package/dist/auth/audit_log_routes.d.ts.map +1 -1
  20. package/dist/auth/audit_log_routes.js +112 -111
  21. package/dist/auth/audit_log_schema.d.ts +22 -22
  22. package/dist/auth/bootstrap_route_schema.d.ts +46 -69
  23. package/dist/auth/bootstrap_route_schema.d.ts.map +1 -1
  24. package/dist/auth/bootstrap_route_schema.js +8 -7
  25. package/dist/auth/bootstrap_routes.d.ts.map +1 -1
  26. package/dist/auth/bootstrap_routes.js +100 -98
  27. package/dist/auth/role_grant_offer_action_specs.d.ts +4 -4
  28. package/dist/auth/signup_route_schema.d.ts +9 -4
  29. package/dist/auth/signup_route_schema.d.ts.map +1 -1
  30. package/dist/auth/signup_route_schema.js +5 -3
  31. package/dist/auth/signup_routes.d.ts.map +1 -1
  32. package/dist/auth/signup_routes.js +170 -170
  33. package/dist/http/CLAUDE.md +50 -4
  34. package/dist/http/common_routes.d.ts +1 -1
  35. package/dist/http/common_routes.d.ts.map +1 -1
  36. package/dist/http/common_routes.js +13 -11
  37. package/dist/http/db_routes.d.ts.map +1 -1
  38. package/dist/http/db_routes.js +25 -28
  39. package/dist/http/error_schemas.d.ts +5 -1
  40. package/dist/http/error_schemas.d.ts.map +1 -1
  41. package/dist/http/error_schemas.js +5 -1
  42. package/dist/http/route_error_check.d.ts +21 -0
  43. package/dist/http/route_error_check.d.ts.map +1 -1
  44. package/dist/http/route_error_check.js +37 -1
  45. package/dist/http/route_result.d.ts +101 -0
  46. package/dist/http/route_result.d.ts.map +1 -0
  47. package/dist/http/route_result.js +56 -0
  48. package/dist/http/route_spec.d.ts +110 -6
  49. package/dist/http/route_spec.d.ts.map +1 -1
  50. package/dist/http/route_spec.js +82 -14
  51. package/dist/http/schema_helpers.d.ts +15 -1
  52. package/dist/http/schema_helpers.d.ts.map +1 -1
  53. package/dist/http/schema_helpers.js +12 -3
  54. package/dist/rate_limiter.d.ts +0 -9
  55. package/dist/rate_limiter.d.ts.map +1 -1
  56. package/dist/rate_limiter.js +0 -15
  57. package/dist/server/serve_fact_route.d.ts.map +1 -1
  58. package/dist/server/serve_fact_route.js +23 -21
  59. package/dist/server/surface_route.d.ts +1 -1
  60. package/dist/server/surface_route.d.ts.map +1 -1
  61. package/dist/server/surface_route.js +4 -2
  62. package/dist/testing/CLAUDE.md +80 -28
  63. package/dist/testing/admin_integration.js +1 -1
  64. package/dist/testing/adversarial_404.d.ts.map +1 -1
  65. package/dist/testing/adversarial_404.js +13 -8
  66. package/dist/testing/adversarial_input.js +2 -2
  67. package/dist/testing/assertions.d.ts +13 -3
  68. package/dist/testing/assertions.d.ts.map +1 -1
  69. package/dist/testing/assertions.js +21 -4
  70. package/dist/testing/attack_surface.d.ts +12 -0
  71. package/dist/testing/attack_surface.d.ts.map +1 -1
  72. package/dist/testing/attack_surface.js +8 -5
  73. package/dist/testing/cross_backend/in_process_setup.d.ts +7 -3
  74. package/dist/testing/cross_backend/in_process_setup.d.ts.map +1 -1
  75. package/dist/testing/cross_backend/in_process_setup.js +11 -4
  76. package/dist/testing/cross_backend/login_security.d.ts.map +1 -1
  77. package/dist/testing/cross_backend/login_security.js +3 -2
  78. package/dist/testing/cross_backend/rust_spine_consumer_surface.d.ts.map +1 -1
  79. package/dist/testing/cross_backend/rust_spine_consumer_surface.js +2 -6
  80. package/dist/testing/cross_backend/spine_suites.d.ts +3 -2
  81. package/dist/testing/cross_backend/spine_suites.d.ts.map +1 -1
  82. package/dist/testing/cross_backend/spine_suites.js +5 -2
  83. package/dist/testing/cross_backend/standard.d.ts +31 -0
  84. package/dist/testing/cross_backend/standard.d.ts.map +1 -1
  85. package/dist/testing/cross_backend/standard.js +9 -3
  86. package/dist/testing/data_exposure.d.ts +7 -0
  87. package/dist/testing/data_exposure.d.ts.map +1 -1
  88. package/dist/testing/data_exposure.js +3 -3
  89. package/dist/testing/error_coverage.d.ts +35 -33
  90. package/dist/testing/error_coverage.d.ts.map +1 -1
  91. package/dist/testing/error_coverage.js +53 -43
  92. package/dist/testing/integration.d.ts +28 -1
  93. package/dist/testing/integration.d.ts.map +1 -1
  94. package/dist/testing/integration.js +51 -18
  95. package/dist/testing/integration_helpers.d.ts.map +1 -1
  96. package/dist/testing/integration_helpers.js +4 -15
  97. package/dist/testing/middleware_gate_probes.d.ts +90 -0
  98. package/dist/testing/middleware_gate_probes.d.ts.map +1 -0
  99. package/dist/testing/middleware_gate_probes.js +179 -0
  100. package/dist/testing/round_trip.d.ts +7 -0
  101. package/dist/testing/round_trip.d.ts.map +1 -1
  102. package/dist/testing/round_trip.js +3 -2
  103. package/dist/testing/schema_generators.d.ts +31 -9
  104. package/dist/testing/schema_generators.d.ts.map +1 -1
  105. package/dist/testing/schema_generators.js +53 -11
  106. package/dist/testing/stubs.d.ts +14 -3
  107. package/dist/testing/stubs.d.ts.map +1 -1
  108. package/dist/testing/stubs.js +21 -6
  109. package/dist/testing/transports/raw_http.d.ts +10 -2
  110. package/dist/testing/transports/raw_http.d.ts.map +1 -1
  111. package/dist/testing/transports/raw_http.js +10 -4
  112. package/package.json +1 -1
@@ -29,14 +29,15 @@ import { query_account_by_username_or_email, query_update_account_password } fro
29
29
  import { query_revoke_all_api_tokens_for_account } from './api_token_queries.js';
30
30
  import { build_account_context, build_request_context, get_public_account_id, get_request_context, require_request_context, resolve_acting_actor } from './request_context.js';
31
31
  import { get_resolved_auth, resolved_auth_session_hash } from './resolved_auth.js';
32
- import { get_route_input } from '../http/route_spec.js';
32
+ import { attach_route_handler, get_route_input } from '../http/route_spec.js';
33
+ import { route_fail, route_ok, route_raw } from '../http/route_result.js';
33
34
  import { get_client_ip } from '../http/client_ip.js';
34
35
  import { rate_limit_ip_key } from '../http/ip_canonical.js';
35
36
  import { parse_acting } from '../http/auth_shape.js';
36
- import { rate_limit_exceeded_response, reserve_optional } from '../rate_limiter.js';
37
+ import { reserve_optional } from '../rate_limiter.js';
37
38
  import { start_fail_floor, warn_if_fail_floor_disabled } from './fail_floor.js';
38
39
  import { close_connections_after_commit, queue_connection_close } from '../actions/connection_closer.js';
39
- import { ERROR_AUTHENTICATION_REQUIRED, ERROR_INVALID_CREDENTIALS } from '../http/error_schemas.js';
40
+ import { REST_AUTHENTICATION_REQUIRED_BOOTSTRAP, REST_INVALID_CREDENTIALS, REST_RATE_LIMIT_EXCEEDED } from '../http/error_schemas.js';
40
41
  /**
41
42
  * Create the account status route spec.
42
43
  *
@@ -58,18 +59,19 @@ import { ERROR_AUTHENTICATION_REQUIRED, ERROR_INVALID_CREDENTIALS } from '../htt
58
59
  * @param options - optional configuration (bootstrap_status for bootstrap detection)
59
60
  * @returns a single account status route spec
60
61
  */
61
- export const create_account_status_route_spec = (options) => ({
62
- ...account_status_route_shape,
63
- path: options?.path ?? account_status_route_shape.path,
64
- handler: async (c, route) => {
62
+ export const create_account_status_route_spec = (options) => {
63
+ // the anonymous caller's 401, with the bootstrap status when one is open
64
+ const fail_anonymous = () => options?.bootstrap_status?.available
65
+ ? route_fail(REST_AUTHENTICATION_REQUIRED_BOOTSTRAP, { bootstrap_available: true })
66
+ : route_fail(REST_AUTHENTICATION_REQUIRED_BOOTSTRAP);
67
+ return attach_route_handler({
68
+ ...account_status_route_shape,
69
+ path: options?.path ?? account_status_route_shape.path
70
+ }, async (c, route) => {
65
71
  // a narrowed token is the anonymous caller here, never a refusal
66
72
  const account_id = get_public_account_id(c);
67
- if (!account_id) {
68
- return c.json({
69
- error: ERROR_AUTHENTICATION_REQUIRED,
70
- ...(options?.bootstrap_status?.available ? { bootstrap_available: true } : {})
71
- }, 401);
72
- }
73
+ if (!account_id)
74
+ return fail_anonymous();
73
75
  // Honor a pre-populated request context. The dispatcher's authorization
74
76
  // phase doesn't run for `auth: 'none'` routes, but a caller (test
75
77
  // harness, or future middleware) may still populate the context — use
@@ -85,7 +87,7 @@ export const create_account_status_route_spec = (options) => ({
85
87
  expires_at: p.expires_at,
86
88
  granted_by: p.granted_by
87
89
  }));
88
- return c.json({
90
+ return route_ok({
89
91
  account: to_session_account(existing.account),
90
92
  actor: existing.actor ? { id: existing.actor.id, name: existing.actor.name } : null,
91
93
  role_grants
@@ -114,7 +116,7 @@ export const create_account_status_route_spec = (options) => ({
114
116
  expires_at: p.expires_at,
115
117
  granted_by: p.granted_by
116
118
  }));
117
- return c.json({
119
+ return route_ok({
118
120
  account: to_session_account(ctx.account),
119
121
  actor: { id: ctx.actor.id, name: ctx.actor.name },
120
122
  role_grants
@@ -122,19 +124,15 @@ export const create_account_status_route_spec = (options) => ({
122
124
  }
123
125
  }
124
126
  const account_ctx = await build_account_context(route, account_id);
125
- if (!account_ctx) {
126
- return c.json({
127
- error: ERROR_AUTHENTICATION_REQUIRED,
128
- ...(options?.bootstrap_status?.available ? { bootstrap_available: true } : {})
129
- }, 401);
130
- }
131
- return c.json({
127
+ if (!account_ctx)
128
+ return fail_anonymous();
129
+ return route_ok({
132
130
  account: to_session_account(account_ctx.account),
133
131
  actor: null,
134
132
  role_grants: []
135
133
  });
136
- }
137
- });
134
+ });
135
+ };
138
136
  /**
139
137
  * Default minimum wall-clock time (ms) for a login failure (401) response.
140
138
  *
@@ -154,8 +152,8 @@ export const DEFAULT_LOGIN_FAIL_FLOOR_MS = 250;
154
152
  * unpredictability of the exact delay, not cryptographic guarantees.
155
153
  */
156
154
  export const DEFAULT_LOGIN_FAIL_JITTER_MS = 25;
157
- // `create_account_route_specs` spreads each shape and attaches the live
158
- // handler below.
155
+ // `create_account_route_specs` attaches the live handler to each shape
156
+ // below.
159
157
  /**
160
158
  * Create account route specs for session-based auth.
161
159
  *
@@ -192,295 +190,288 @@ export const create_account_route_specs = (deps, options) => {
192
190
  // it — matching the Rust `account_router`. The standalone
193
191
  // `create_account_status_route_spec` stays the building block.
194
192
  create_account_status_route_spec({ bootstrap_status }),
195
- {
196
- ...verify_shape,
197
- handler: (c) => {
198
- require_request_context(c);
199
- return c.body(null, 200);
193
+ attach_route_handler(verify_shape, (c) => {
194
+ require_request_context(c);
195
+ // the probe's answer is its status alone, an empty body
196
+ return route_raw(c.body(null, 200));
197
+ }),
198
+ attach_route_handler(login_shape, async (c, route) => {
199
+ // Per-IP rate limit (before any DB/password work). Reserved, not
200
+ // checked: the attempt counts against the cap from here until it
201
+ // settles, so a concurrent burst can't all pass before any of it
202
+ // records. A key at its cap only because of attempts in flight
203
+ // waits briefly for a slot (`RESERVATION_WAIT_MAX_MS`) rather than
204
+ // refusing a burst of correct logins outright. Order: IP, then the
205
+ // lookup, then the account (its key is the looked-up id). A wait on
206
+ // the account bucket keeps the IP slot: it belongs to the same
207
+ // address, the wait is bounded, and giving it up would let that
208
+ // address exceed its cap meanwhile. The `finally` releases whatever
209
+ // no branch recorded.
210
+ // keyed by the address's rate-limit key (an IPv6 client's /64)
211
+ const ip_key = login_ip_rate_limiter ? rate_limit_ip_key(get_client_ip(c)) : null;
212
+ const ip_reserved = await reserve_optional(login_ip_rate_limiter, ip_key, {
213
+ signal: c.req.raw.signal
214
+ });
215
+ if (!ip_reserved.ok) {
216
+ return route_fail(REST_RATE_LIMIT_EXCEEDED, { retry_after: ip_reserved.retry_after });
200
217
  }
201
- },
202
- {
203
- ...login_shape,
204
- handler: async (c, route) => {
205
- // Per-IP rate limit (before any DB/password work). Reserved, not
206
- // checked: the attempt counts against the cap from here until it
207
- // settles, so a concurrent burst can't all pass before any of it
208
- // records. A key at its cap only because of attempts in flight
209
- // waits briefly for a slot (`RESERVATION_WAIT_MAX_MS`) rather than
210
- // refusing a burst of correct logins outright. Order: IP, then the
211
- // lookup, then the account (its key is the looked-up id). A wait on
212
- // the account bucket keeps the IP slot: it belongs to the same
213
- // address, the wait is bounded, and giving it up would let that
214
- // address exceed its cap meanwhile. The `finally` releases whatever
215
- // no branch recorded.
216
- // keyed by the address's rate-limit key (an IPv6 client's /64)
217
- const ip_key = login_ip_rate_limiter ? rate_limit_ip_key(get_client_ip(c)) : null;
218
- const ip_reserved = await reserve_optional(login_ip_rate_limiter, ip_key, {
219
- signal: c.req.raw.signal
220
- });
221
- if (!ip_reserved.ok) {
222
- return rate_limit_exceeded_response(c, ip_reserved.retry_after);
218
+ let account_reservation = null;
219
+ try {
220
+ // `UsernameProvided` canonicalizes via `.trim().toLowerCase()` at
221
+ // parse time — the validated value lands canonical in
222
+ // `c.var.validated_input`, so the per-account rate-limit key,
223
+ // DB lookup, and audit metadata see one form. See
224
+ // `primitive_schemas_fuz.ts` for the schema-layer canonicalization.
225
+ const { username, password: pw } = get_route_input(c);
226
+ // DB lookup first so we can key the per-account rate limit by a canonical value
227
+ // (account.id) rather than the submitted identifier. Otherwise an attacker could
228
+ // alternate between username and email to double the per-account bucket.
229
+ const account = await query_account_by_username_or_email(route, username);
230
+ const account_rate_key = account ? account.id : username;
231
+ // Per-account rate limit (after DB lookup so the key is canonical)
232
+ const account_reserved = await reserve_optional(login_account_rate_limiter, account_rate_key, { signal: c.req.raw.signal });
233
+ if (!account_reserved.ok) {
234
+ return route_fail(REST_RATE_LIMIT_EXCEEDED, {
235
+ retry_after: account_reserved.retry_after
236
+ });
223
237
  }
224
- let account_reservation = null;
225
- try {
226
- // `UsernameProvided` canonicalizes via `.trim().toLowerCase()` at
227
- // parse time — the validated value lands canonical in
228
- // `c.var.validated_input`, so the per-account rate-limit key,
229
- // DB lookup, and audit metadata see one form. See
230
- // `primitive_schemas_fuz.ts` for the schema-layer canonicalization.
231
- const { username, password: pw } = get_route_input(c);
232
- // DB lookup first so we can key the per-account rate limit by a canonical value
233
- // (account.id) rather than the submitted identifier. Otherwise an attacker could
234
- // alternate between username and email to double the per-account bucket.
235
- const account = await query_account_by_username_or_email(route, username);
236
- const account_rate_key = account ? account.id : username;
237
- // Per-account rate limit (after DB lookup so the key is canonical)
238
- const account_reserved = await reserve_optional(login_account_rate_limiter, account_rate_key, { signal: c.req.raw.signal });
239
- if (!account_reserved.ok) {
240
- return rate_limit_exceeded_response(c, account_reserved.retry_after);
241
- }
242
- account_reservation = account_reserved.reservation;
243
- // Start the minimum-delay timer concurrently with failure work.
244
- // Observed response time is max(work, delay) so all 401 paths
245
- // (found-wrong-pw, not-found) return in similar time.
246
- const delay = start_fail_floor(login_fail_floor_ms, login_fail_jitter_ms);
247
- if (!account) {
248
- // enumeration prevention: verify_dummy equalizes Argon2id timing;
249
- // the fail floor equalizes every other path difference.
250
- await password.verify_dummy(pw);
251
- ip_reserved.reservation.record();
252
- account_reservation?.record();
253
- await deps.audit.emit(route, {
254
- event_type: 'login',
255
- outcome: 'failure',
256
- ip: get_client_ip(c),
257
- metadata: { username }
258
- });
259
- await delay;
260
- return c.json({ error: ERROR_INVALID_CREDENTIALS }, 401);
261
- }
262
- const valid = await password.verify_password(pw, account.password_hash);
263
- if (!valid) {
264
- ip_reserved.reservation.record();
265
- account_reservation?.record();
266
- await deps.audit.emit(route, {
267
- event_type: 'login',
268
- outcome: 'failure',
269
- account_id: account.id,
270
- ip: get_client_ip(c),
271
- metadata: { username }
272
- });
273
- await delay;
274
- return c.json({ error: ERROR_INVALID_CREDENTIALS }, 401);
275
- }
276
- // Successful login — clear the account-grain failure history only.
277
- // The IP aggregate is deliberately left standing: it is the
278
- // distributed-spray backstop, so a success on one account must not
279
- // refund the budget shared by every other account reachable from
280
- // that address. See `RateLimiter.reset`. A success records nothing:
281
- // both reservations are released.
282
- ip_reserved.reservation.release();
283
- account_reservation?.release();
284
- if (login_account_rate_limiter)
285
- login_account_rate_limiter.reset(account_rate_key);
286
- // The session INSERT and the cap eviction are the route's only
287
- // writes, and only atomic together: one transaction around just
288
- // them (the route is `transaction: false`, so the reservation
289
- // waits above and the Argon2 verify held no connection). Twin of
290
- // the Rust login's transaction around `create_capped_session`.
291
- const evicted = await route.db.transaction((tx) => create_session_and_set_cookie({
292
- keyring,
293
- deps: { db: tx },
294
- c,
295
- account_id: account.id,
296
- session_options,
297
- max_sessions
298
- }));
299
- // The sessions the cap evicted are gone from the table, but not
300
- // from the connections they opened — a WebSocket keeps the
301
- // authority it resolved at upgrade, and an SSE stream never
302
- // rechecks. Close them now the eviction has committed — inline, not
303
- // queued: with no route transaction, a throw later in the handler
304
- // would drop a queued close while the eviction stands. No audit
305
- // row: there is no eviction event, and the `login` row records
306
- // the cause.
307
- for (const session_hash of evicted) {
308
- close_connections_after_commit(connection_closer, { kind: 'session', session_hash }, deps.log);
309
- }
238
+ account_reservation = account_reserved.reservation;
239
+ // Start the minimum-delay timer concurrently with failure work.
240
+ // Observed response time is max(work, delay) so all 401 paths
241
+ // (found-wrong-pw, not-found) return in similar time.
242
+ const delay = start_fail_floor(login_fail_floor_ms, login_fail_jitter_ms);
243
+ if (!account) {
244
+ // enumeration prevention: verify_dummy equalizes Argon2id timing;
245
+ // the fail floor equalizes every other path difference.
246
+ await password.verify_dummy(pw);
247
+ ip_reserved.reservation.record();
248
+ account_reservation?.record();
310
249
  await deps.audit.emit(route, {
311
250
  event_type: 'login',
312
- account_id: account.id,
313
- ip: get_client_ip(c)
251
+ outcome: 'failure',
252
+ ip: get_client_ip(c),
253
+ metadata: { username }
314
254
  });
315
- return c.json({ ok: true });
316
- }
317
- finally {
318
- ip_reserved.reservation.release();
319
- account_reservation?.release();
255
+ await delay;
256
+ return route_fail(REST_INVALID_CREDENTIALS);
320
257
  }
321
- }
322
- },
323
- {
324
- ...logout_shape,
325
- handler: async (c, route) => {
326
- const ctx = require_request_context(c);
327
- // the shape admits only a session credential, so this is its hash
328
- // (the Rust `account_logout` reads the same value)
329
- const session_hash = resolved_auth_session_hash(get_resolved_auth(c));
330
- if (session_hash !== null) {
331
- await query_session_revoke_by_hash_unscoped(route, session_hash);
332
- // Close this account's live connections once the revoke has
333
- // committed — queued, so it never runs before the commit or on
334
- // rollback, and it does not depend on the audit row below (written
335
- // in the route transaction, so it commits with the revoke). Account-wide (not session-targeted) to match the Rust
336
- // `account_logout` handler and the sibling `/password` handler
337
- // — logout is a self-initiated account-grain operation. The
338
- // audit listeners repeat the same close on the announced
339
- // `logout` row; closing is idempotent.
340
- queue_connection_close(route, connection_closer, {
341
- kind: 'account',
342
- account_id: ctx.account.id
258
+ const valid = await password.verify_password(pw, account.password_hash);
259
+ if (!valid) {
260
+ ip_reserved.reservation.record();
261
+ account_reservation?.record();
262
+ await deps.audit.emit(route, {
263
+ event_type: 'login',
264
+ outcome: 'failure',
265
+ account_id: account.id,
266
+ ip: get_client_ip(c),
267
+ metadata: { username }
343
268
  });
269
+ await delay;
270
+ return route_fail(REST_INVALID_CREDENTIALS);
271
+ }
272
+ // Successful login — clear the account-grain failure history only.
273
+ // The IP aggregate is deliberately left standing: it is the
274
+ // distributed-spray backstop, so a success on one account must not
275
+ // refund the budget shared by every other account reachable from
276
+ // that address. See `RateLimiter.reset`. A success records nothing:
277
+ // both reservations are released.
278
+ ip_reserved.reservation.release();
279
+ account_reservation?.release();
280
+ if (login_account_rate_limiter)
281
+ login_account_rate_limiter.reset(account_rate_key);
282
+ // The session INSERT and the cap eviction are the route's only
283
+ // writes, and only atomic together: one transaction around just
284
+ // them (the route is `transaction: false`, so the reservation
285
+ // waits above and the Argon2 verify held no connection). Twin of
286
+ // the Rust login's transaction around `create_capped_session`.
287
+ const evicted = await route.db.transaction((tx) => create_session_and_set_cookie({
288
+ keyring,
289
+ deps: { db: tx },
290
+ c,
291
+ account_id: account.id,
292
+ session_options,
293
+ max_sessions
294
+ }));
295
+ // The sessions the cap evicted are gone from the table, but not
296
+ // from the connections they opened — a WebSocket keeps the
297
+ // authority it resolved at upgrade, and an SSE stream never
298
+ // rechecks. Close them now the eviction has committed — inline, not
299
+ // queued: with no route transaction, a throw later in the handler
300
+ // would drop a queued close while the eviction stands. No audit
301
+ // row: there is no eviction event, and the `login` row records
302
+ // the cause.
303
+ for (const session_hash of evicted) {
304
+ close_connections_after_commit(connection_closer, { kind: 'session', session_hash }, deps.log);
344
305
  }
345
- clear_session_cookie(c, session_options);
346
- // Account-grain operation — no `actor_id` (which actor was
347
- // resolved per-request is incidental to "this account ended
348
- // its session"). Mirrors `login`.
349
306
  await deps.audit.emit(route, {
350
- event_type: 'logout',
351
- account_id: ctx.account.id,
307
+ event_type: 'login',
308
+ account_id: account.id,
352
309
  ip: get_client_ip(c)
353
310
  });
354
- return c.json({ ok: true, username: ctx.account.username });
311
+ return route_ok({ ok: true });
355
312
  }
356
- },
357
- {
358
- ...password_shape,
359
- handler: async (c, route) => {
360
- // Per-IP rate limit (before argon2 work). Reserved, not checked:
361
- // the attempt counts against the shared login limiters from here
362
- // until it settles, so a concurrent burst of guesses at
363
- // `current_password` can't all pass before any of it records. The
364
- // `finally` releases whatever no branch recorded.
365
- // keyed by the address's rate-limit key (an IPv6 client's /64)
366
- const ip_key = login_ip_rate_limiter ? rate_limit_ip_key(get_client_ip(c)) : null;
367
- const ip_reserved = await reserve_optional(login_ip_rate_limiter, ip_key, {
368
- signal: c.req.raw.signal
313
+ finally {
314
+ ip_reserved.reservation.release();
315
+ account_reservation?.release();
316
+ }
317
+ }),
318
+ attach_route_handler(logout_shape, async (c, route) => {
319
+ const ctx = require_request_context(c);
320
+ // the shape admits only a session credential, so this is its hash
321
+ // (the Rust `account_logout` reads the same value)
322
+ const session_hash = resolved_auth_session_hash(get_resolved_auth(c));
323
+ if (session_hash !== null) {
324
+ await query_session_revoke_by_hash_unscoped(route, session_hash);
325
+ // Close this account's live connections once the revoke has
326
+ // committed — queued, so it never runs before the commit or on
327
+ // rollback, and it does not depend on the audit row below (written
328
+ // in the route transaction, so it commits with the revoke). Account-wide (not session-targeted) to match the Rust
329
+ // `account_logout` handler and the sibling `/password` handler
330
+ // — logout is a self-initiated account-grain operation. The
331
+ // audit listeners repeat the same close on the announced
332
+ // `logout` row; closing is idempotent.
333
+ queue_connection_close(route, connection_closer, {
334
+ kind: 'account',
335
+ account_id: ctx.account.id
369
336
  });
370
- if (!ip_reserved.ok) {
371
- return rate_limit_exceeded_response(c, ip_reserved.retry_after);
372
- }
373
- let account_reservation = null;
374
- try {
375
- const ctx = require_request_context(c);
376
- const { current_password, new_password } = get_route_input(c);
377
- // Defense in depth — see `docs/security.md` §Credential-channel gating.
378
- const credential_type = get_resolved_auth(c)?.credential_type;
379
- // per-account rate limit (after context resolution, before argon2 work)
380
- const account_reserved = await reserve_optional(login_account_rate_limiter, ctx.account.id, { signal: c.req.raw.signal });
381
- if (!account_reserved.ok) {
382
- return rate_limit_exceeded_response(c, account_reserved.retry_after);
383
- }
384
- account_reservation = account_reserved.reservation;
385
- const valid = await password.verify_password(current_password, ctx.account.password_hash);
386
- if (!valid) {
387
- ip_reserved.reservation.record();
388
- account_reservation?.record();
389
- await deps.audit.emit(route, {
390
- event_type: 'password_change',
391
- outcome: 'failure',
392
- account_id: ctx.account.id,
393
- ip: get_client_ip(c),
394
- metadata: { credential_type }
395
- });
396
- return c.json({ error: ERROR_INVALID_CREDENTIALS }, 401);
397
- }
398
- // Verify succeeded — do the throw-y operations FIRST so a fault
399
- // (Argon2 OOM, native binding error, DB outage on the UPDATE)
400
- // can't wipe the rate-limit history of a caller observing 500s.
401
- // Resets happen below, after both calls have settled.
402
- const new_hash = await password.hash_password(new_password);
403
- // Conditional UPDATE keyed on the verified hash: closes the
404
- // verify-write race with a concurrent password change that
405
- // already committed against the same starting hash. Account-grain
406
- // operation — `updated_by` stays null (the per-request actor is
407
- // incidental; password is account-level state).
408
- //
409
- // The UPDATE and the two revocations are the route's writes, and
410
- // commit together or not at all: one transaction around just them
411
- // (the route is `transaction: false`, so the reservation waits
412
- // above and the Argon2 verify and hash held no connection). Twin of
413
- // the Rust spine's `change_password`. `null` when the UPDATE matched
414
- // nothing — a concurrent change committed first.
415
- const change = await route.db.transaction(async (tx) => {
416
- const tx_deps = { db: tx };
417
- const updated = await query_update_account_password(tx_deps, ctx.account.id, new_hash, null, ctx.account.password_hash);
418
- if (!updated)
419
- return null;
420
- // revoke all sessions and API tokens (force re-auth everywhere)
421
- const sessions_revoked = await query_session_revoke_all_for_account(tx_deps, ctx.account.id);
422
- const tokens_revoked = await query_revoke_all_api_tokens_for_account(tx_deps, ctx.account.id);
423
- return { sessions_revoked, tokens_revoked };
337
+ }
338
+ clear_session_cookie(c, session_options);
339
+ // Account-grain operation — no `actor_id` (which actor was
340
+ // resolved per-request is incidental to "this account ended
341
+ // its session"). Mirrors `login`.
342
+ await deps.audit.emit(route, {
343
+ event_type: 'logout',
344
+ account_id: ctx.account.id,
345
+ ip: get_client_ip(c)
346
+ });
347
+ return route_ok({ ok: true, username: ctx.account.username });
348
+ }),
349
+ attach_route_handler(password_shape, async (c, route) => {
350
+ // Per-IP rate limit (before argon2 work). Reserved, not checked:
351
+ // the attempt counts against the shared login limiters from here
352
+ // until it settles, so a concurrent burst of guesses at
353
+ // `current_password` can't all pass before any of it records. The
354
+ // `finally` releases whatever no branch recorded.
355
+ // keyed by the address's rate-limit key (an IPv6 client's /64)
356
+ const ip_key = login_ip_rate_limiter ? rate_limit_ip_key(get_client_ip(c)) : null;
357
+ const ip_reserved = await reserve_optional(login_ip_rate_limiter, ip_key, {
358
+ signal: c.req.raw.signal
359
+ });
360
+ if (!ip_reserved.ok) {
361
+ return route_fail(REST_RATE_LIMIT_EXCEEDED, { retry_after: ip_reserved.retry_after });
362
+ }
363
+ let account_reservation = null;
364
+ try {
365
+ const ctx = require_request_context(c);
366
+ const { current_password, new_password } = get_route_input(c);
367
+ // Defense in depth — see `docs/security.md` §Credential-channel gating.
368
+ const credential_type = get_resolved_auth(c)?.credential_type;
369
+ // per-account rate limit (after context resolution, before argon2 work)
370
+ const account_reserved = await reserve_optional(login_account_rate_limiter, ctx.account.id, { signal: c.req.raw.signal });
371
+ if (!account_reserved.ok) {
372
+ return route_fail(REST_RATE_LIMIT_EXCEEDED, {
373
+ retry_after: account_reserved.retry_after
424
374
  });
425
- // Verify-success contract — the caller proved knowledge, so wipe
426
- // their account-grain failure history. The race-loser branch below
427
- // re-records one on top of the wiped slate so net cost stays 1 on
428
- // that bucket. Deferring from "after verify" to "after UPDATE
429
- // settled" is what closes the S1 bypass — a throw between reset
430
- // and the UPDATE could have wiped an attacker's budget.
431
- //
432
- // The IP aggregate is deliberately not cleared: it is the same
433
- // instance login uses, so refunding it here reopens the spray path
434
- // through a route that only needs the caller's *own* password. Its
435
- // record on the race-loser branch below therefore accumulates
436
- // rather than netting out, which is the intent.
437
- if (login_account_rate_limiter)
438
- login_account_rate_limiter.reset(ctx.account.id);
439
- if (!change) {
440
- // A concurrent password change committed first — our
441
- // `current_password` was correct at read-time but the row's
442
- // `password_hash` no longer matches. Mirrors the wrong-password
443
- // 401 shape; tag the failure metadata so admins reading the
444
- // audit log can distinguish "user typoed" from "two clients
445
- // raced." Sessions/tokens were already revoked by the winner;
446
- // no cookie clear here either.
447
- ip_reserved.reservation.record();
448
- account_reservation?.record();
449
- await deps.audit.emit(route, {
450
- event_type: 'password_change',
451
- outcome: 'failure',
452
- account_id: ctx.account.id,
453
- ip: get_client_ip(c),
454
- metadata: { reason: 'concurrent_change', credential_type }
455
- });
456
- return c.json({ error: ERROR_INVALID_CREDENTIALS }, 401);
457
- }
458
- const { sessions_revoked, tokens_revoked } = change;
459
- // Close every live connection of this account now the password
460
- // update and the revoke-all cascade have committed — inline, not
461
- // queued: with no route transaction, a throw later in the handler
462
- // would drop a queued close while the revocation stands. It does
463
- // not depend on the fail-open audit write below; the audit
464
- // listeners repeat it on the announced `password_change` row.
465
- close_connections_after_commit(connection_closer, { kind: 'account', account_id: ctx.account.id }, deps.log);
466
- clear_session_cookie(c, session_options);
467
- // Account-grain operation — no `actor_id`. The password is
468
- // account-level state; which per-request actor was resolved
469
- // has no semantic bearing on "this account changed its
470
- // password". Mirrors `login`/`logout`.
375
+ }
376
+ account_reservation = account_reserved.reservation;
377
+ const valid = await password.verify_password(current_password, ctx.account.password_hash);
378
+ if (!valid) {
379
+ ip_reserved.reservation.record();
380
+ account_reservation?.record();
471
381
  await deps.audit.emit(route, {
472
382
  event_type: 'password_change',
383
+ outcome: 'failure',
473
384
  account_id: ctx.account.id,
474
385
  ip: get_client_ip(c),
475
- metadata: { sessions_revoked, tokens_revoked, credential_type }
386
+ metadata: { credential_type }
476
387
  });
477
- return c.json({ ok: true, sessions_revoked, tokens_revoked });
388
+ return route_fail(REST_INVALID_CREDENTIALS);
478
389
  }
479
- finally {
480
- ip_reserved.reservation.release();
481
- account_reservation?.release();
390
+ // Verify succeeded — do the throw-y operations FIRST so a fault
391
+ // (Argon2 OOM, native binding error, DB outage on the UPDATE)
392
+ // can't wipe the rate-limit history of a caller observing 500s.
393
+ // Resets happen below, after both calls have settled.
394
+ const new_hash = await password.hash_password(new_password);
395
+ // Conditional UPDATE keyed on the verified hash: closes the
396
+ // verify-write race with a concurrent password change that
397
+ // already committed against the same starting hash. Account-grain
398
+ // operation — `updated_by` stays null (the per-request actor is
399
+ // incidental; password is account-level state).
400
+ //
401
+ // The UPDATE and the two revocations are the route's writes, and
402
+ // commit together or not at all: one transaction around just them
403
+ // (the route is `transaction: false`, so the reservation waits
404
+ // above and the Argon2 verify and hash held no connection). Twin of
405
+ // the Rust spine's `change_password`. `null` when the UPDATE matched
406
+ // nothing — a concurrent change committed first.
407
+ const change = await route.db.transaction(async (tx) => {
408
+ const tx_deps = { db: tx };
409
+ const updated = await query_update_account_password(tx_deps, ctx.account.id, new_hash, null, ctx.account.password_hash);
410
+ if (!updated)
411
+ return null;
412
+ // revoke all sessions and API tokens (force re-auth everywhere)
413
+ const sessions_revoked = await query_session_revoke_all_for_account(tx_deps, ctx.account.id);
414
+ const tokens_revoked = await query_revoke_all_api_tokens_for_account(tx_deps, ctx.account.id);
415
+ return { sessions_revoked, tokens_revoked };
416
+ });
417
+ // Verify-success contract — the caller proved knowledge, so wipe
418
+ // their account-grain failure history. The race-loser branch below
419
+ // re-records one on top of the wiped slate so net cost stays 1 on
420
+ // that bucket. Deferring from "after verify" to "after UPDATE
421
+ // settled" is what closes the S1 bypass — a throw between reset
422
+ // and the UPDATE could have wiped an attacker's budget.
423
+ //
424
+ // The IP aggregate is deliberately not cleared: it is the same
425
+ // instance login uses, so refunding it here reopens the spray path
426
+ // through a route that only needs the caller's *own* password. Its
427
+ // record on the race-loser branch below therefore accumulates
428
+ // rather than netting out, which is the intent.
429
+ if (login_account_rate_limiter)
430
+ login_account_rate_limiter.reset(ctx.account.id);
431
+ if (!change) {
432
+ // A concurrent password change committed first — our
433
+ // `current_password` was correct at read-time but the row's
434
+ // `password_hash` no longer matches. Mirrors the wrong-password
435
+ // 401 shape; tag the failure metadata so admins reading the
436
+ // audit log can distinguish "user typoed" from "two clients
437
+ // raced." Sessions/tokens were already revoked by the winner;
438
+ // no cookie clear here either.
439
+ ip_reserved.reservation.record();
440
+ account_reservation?.record();
441
+ await deps.audit.emit(route, {
442
+ event_type: 'password_change',
443
+ outcome: 'failure',
444
+ account_id: ctx.account.id,
445
+ ip: get_client_ip(c),
446
+ metadata: { reason: 'concurrent_change', credential_type }
447
+ });
448
+ return route_fail(REST_INVALID_CREDENTIALS);
482
449
  }
450
+ const { sessions_revoked, tokens_revoked } = change;
451
+ // Close every live connection of this account now the password
452
+ // update and the revoke-all cascade have committed — inline, not
453
+ // queued: with no route transaction, a throw later in the handler
454
+ // would drop a queued close while the revocation stands. It does
455
+ // not depend on the fail-open audit write below; the audit
456
+ // listeners repeat it on the announced `password_change` row.
457
+ close_connections_after_commit(connection_closer, { kind: 'account', account_id: ctx.account.id }, deps.log);
458
+ clear_session_cookie(c, session_options);
459
+ // Account-grain operation — no `actor_id`. The password is
460
+ // account-level state; which per-request actor was resolved
461
+ // has no semantic bearing on "this account changed its
462
+ // password". Mirrors `login`/`logout`.
463
+ await deps.audit.emit(route, {
464
+ event_type: 'password_change',
465
+ account_id: ctx.account.id,
466
+ ip: get_client_ip(c),
467
+ metadata: { sessions_revoked, tokens_revoked, credential_type }
468
+ });
469
+ return route_ok({ ok: true, sessions_revoked, tokens_revoked });
483
470
  }
484
- }
471
+ finally {
472
+ ip_reserved.reservation.release();
473
+ account_reservation?.release();
474
+ }
475
+ })
485
476
  ];
486
477
  };