@pithy-sh/auth 0.10.0 → 0.11.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 (116) hide show
  1. package/README.md +1 -1
  2. package/dist/admin/users.js +1 -1
  3. package/dist/audit/actions.d.ts +19 -0
  4. package/dist/audit/actions.d.ts.map +1 -1
  5. package/dist/audit/actions.js +20 -1
  6. package/dist/audit/emit.d.ts +2 -0
  7. package/dist/audit/emit.d.ts.map +1 -1
  8. package/dist/audit/emit.js +1 -1
  9. package/dist/capability.d.ts +19 -0
  10. package/dist/capability.d.ts.map +1 -1
  11. package/dist/capability.js +20 -3
  12. package/dist/data/tables.d.ts +1 -0
  13. package/dist/data/tables.d.ts.map +1 -1
  14. package/dist/data/userLifecycle.d.ts +1 -0
  15. package/dist/data/userLifecycle.d.ts.map +1 -1
  16. package/dist/data/userLifecycle.js +2 -1
  17. package/dist/http/adminRoutes.d.ts.map +1 -1
  18. package/dist/http/adminRoutes.js +270 -5
  19. package/dist/http/guards.d.ts +8 -7
  20. package/dist/http/guards.d.ts.map +1 -1
  21. package/dist/http/guards.js +38 -7
  22. package/dist/http/middleware.d.ts +25 -1
  23. package/dist/http/middleware.d.ts.map +1 -1
  24. package/dist/http/middleware.js +44 -3
  25. package/dist/http/responses.d.ts +180 -0
  26. package/dist/http/responses.d.ts.map +1 -1
  27. package/dist/http/responses.js +142 -1
  28. package/dist/http/routes.d.ts +1 -0
  29. package/dist/http/routes.d.ts.map +1 -1
  30. package/dist/http/routes.js +45 -3
  31. package/dist/http/schemas.d.ts +57 -0
  32. package/dist/http/schemas.d.ts.map +1 -1
  33. package/dist/http/schemas.js +51 -1
  34. package/dist/http/views.d.ts +39 -2
  35. package/dist/http/views.d.ts.map +1 -1
  36. package/dist/http/views.js +105 -1
  37. package/dist/instance/auth.d.ts.map +1 -1
  38. package/dist/instance/auth.js +2 -2
  39. package/dist/lifecycle/audited.d.ts +48 -0
  40. package/dist/lifecycle/audited.d.ts.map +1 -0
  41. package/dist/lifecycle/audited.js +65 -0
  42. package/dist/lifecycle/enforce.d.ts +37 -2
  43. package/dist/lifecycle/enforce.d.ts.map +1 -1
  44. package/dist/lifecycle/enforce.js +46 -5
  45. package/dist/lifecycle/reason.d.ts +11 -0
  46. package/dist/lifecycle/reason.d.ts.map +1 -0
  47. package/dist/lifecycle/reason.js +13 -0
  48. package/dist/lifecycle/request.d.ts +5 -2
  49. package/dist/lifecycle/request.d.ts.map +1 -1
  50. package/dist/lifecycle/request.js +6 -2
  51. package/dist/lifecycle/transitions.d.ts +158 -18
  52. package/dist/lifecycle/transitions.d.ts.map +1 -1
  53. package/dist/lifecycle/transitions.js +344 -70
  54. package/dist/migrations/0005_purge_once.d.ts +22 -0
  55. package/dist/migrations/0005_purge_once.d.ts.map +1 -0
  56. package/dist/migrations/0005_purge_once.js +35 -0
  57. package/dist/migrations/pluginTables.d.ts +8 -0
  58. package/dist/migrations/pluginTables.d.ts.map +1 -1
  59. package/dist/migrations/pluginTables.js +8 -1
  60. package/dist/migrations/set.d.ts +2 -1
  61. package/dist/migrations/set.d.ts.map +1 -1
  62. package/dist/migrations/set.js +4 -2
  63. package/dist/purge/contribution.d.ts +47 -0
  64. package/dist/purge/contribution.d.ts.map +1 -0
  65. package/dist/purge/contribution.js +141 -0
  66. package/dist/purge/retryPolicy.d.ts +22 -0
  67. package/dist/purge/retryPolicy.d.ts.map +1 -0
  68. package/dist/purge/retryPolicy.js +26 -0
  69. package/dist/purge/run.d.ts +88 -0
  70. package/dist/purge/run.d.ts.map +1 -0
  71. package/dist/purge/run.js +102 -0
  72. package/dist/purge/specs.d.ts +71 -0
  73. package/dist/purge/specs.d.ts.map +1 -0
  74. package/dist/purge/specs.js +72 -0
  75. package/dist/purge/start.d.ts +42 -0
  76. package/dist/purge/start.d.ts.map +1 -0
  77. package/dist/purge/start.js +37 -0
  78. package/dist/purge/workflow.d.ts +58 -0
  79. package/dist/purge/workflow.d.ts.map +1 -0
  80. package/dist/purge/workflow.js +96 -0
  81. package/dist/test-utils/accountFootprint.d.ts +10 -0
  82. package/dist/test-utils/accountFootprint.d.ts.map +1 -0
  83. package/dist/test-utils/accountFootprint.js +44 -0
  84. package/dist/version.generated.d.ts +1 -1
  85. package/dist/version.generated.js +1 -1
  86. package/docs/account-lifecycle.md +123 -11
  87. package/package.json +5 -5
  88. package/pithy.manifest.json +1 -1
  89. package/src/audit/actions.ts +19 -0
  90. package/src/audit/emit.ts +3 -1
  91. package/src/capability.ts +48 -1
  92. package/src/data/userLifecycle.ts +4 -1
  93. package/src/http/adminRoutes.ts +398 -2
  94. package/src/http/guards.ts +39 -7
  95. package/src/http/middleware.ts +45 -2
  96. package/src/http/responses.ts +245 -0
  97. package/src/http/routes.ts +55 -3
  98. package/src/http/schemas.ts +110 -0
  99. package/src/http/views.ts +147 -2
  100. package/src/instance/auth.ts +7 -2
  101. package/src/lifecycle/audited.ts +104 -0
  102. package/src/lifecycle/enforce.ts +55 -5
  103. package/src/lifecycle/reason.ts +11 -0
  104. package/src/lifecycle/request.ts +10 -2
  105. package/src/lifecycle/transitions.ts +482 -93
  106. package/src/migrations/0005_purge_once.ts +42 -0
  107. package/src/migrations/pluginTables.ts +19 -1
  108. package/src/migrations/set.ts +3 -1
  109. package/src/purge/contribution.ts +191 -0
  110. package/src/purge/retryPolicy.ts +26 -0
  111. package/src/purge/run.ts +185 -0
  112. package/src/purge/specs.ts +95 -0
  113. package/src/purge/start.ts +79 -0
  114. package/src/purge/workflow.ts +144 -0
  115. package/src/test-utils/accountFootprint.ts +95 -0
  116. package/src/version.generated.ts +1 -1
@@ -2,13 +2,16 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
5
+ import { purgeExports } from "@pithy-sh/core/src/capability/purge";
5
6
  import type { ControlPlaneContext } from "@pithy-sh/core/src/controlPlane/context";
6
7
  import { requireControlPlane } from "@pithy-sh/core/src/controlPlane/http/guard";
7
8
  import { MAX_PAGE_SIZE } from "@pithy-sh/core/src/data/cursor";
8
9
  import { InternalError, NotFoundError } from "@pithy-sh/core/src/error/pithyError";
9
10
  import { describeRoute } from "@pithy-sh/core/src/http/routeSpec";
10
11
  import { validate } from "@pithy-sh/core/src/http/validation";
12
+ import { workflowBindingFor } from "@pithy-sh/core/src/workflow/dispatch";
11
13
  import type { Context, Hono } from "hono";
14
+ import type { z } from "zod";
12
15
  import {
13
16
  type AdminSubList,
14
17
  findSessionById,
@@ -25,23 +28,66 @@ import { correlation, emitControlPlaneAction } from "../audit/emit";
25
28
  import type { AuthWiring } from "../capability";
26
29
  import { authDatabase } from "../data/tables";
27
30
  import { deleteDevice, deviceSessionTokens } from "../device/registry";
31
+ import { auditedLifecycleCall, recordLifecycleRefusal } from "../lifecycle/audited";
32
+ import { MAX_REASON } from "../lifecycle/reason";
33
+ import { lifecycleDeps } from "../lifecycle/request";
34
+ import {
35
+ type DeleteTransition,
36
+ deleteUser,
37
+ type LifecycleActor,
38
+ reinstateUser,
39
+ requirePresent,
40
+ restoreUser,
41
+ suspendUser,
42
+ } from "../lifecycle/transitions";
43
+ import { AUTH_PURGE_BINDING } from "../purge/specs";
44
+ import { startPurgeInstance } from "../purge/start";
28
45
  import {
29
46
  AUTH_DEVICES_READ_SCOPE,
30
47
  AUTH_DEVICES_REVOKE_SCOPE,
31
48
  AUTH_SESSIONS_REVOKE_SCOPE,
49
+ AUTH_USERS_DELETE_SCOPE,
50
+ AUTH_USERS_EXPORT_SCOPE,
32
51
  AUTH_USERS_LOGOUT_SCOPE,
33
52
  AUTH_USERS_READ_SCOPE,
53
+ AUTH_USERS_SUSPEND_SCOPE,
34
54
  } from "./guards";
35
55
  import { getAuthInstance, resolveDb } from "./resolve";
36
56
  import {
37
57
  AdminDeviceRevokeResponse,
38
58
  AdminDevicesResponse,
39
59
  AdminRevokeResponse,
60
+ AdminUserDeleteResponse,
61
+ AdminUserExportResponse,
62
+ AdminUserReinstateResponse,
40
63
  AdminUserResponse,
64
+ AdminUserRestoreResponse,
65
+ AdminUserSuspendResponse,
41
66
  AdminUsersResponse,
42
67
  } from "./responses";
43
- import { ListDevicesQuery, ListUsersQuery, RevokeDeviceBody, RevokeSessionBody, UserIdParam } from "./schemas";
44
- import { deviceView, sessionView, userView } from "./views";
68
+ import {
69
+ DeleteUserBody,
70
+ ExportUserQuery,
71
+ ListDevicesQuery,
72
+ ListUsersQuery,
73
+ ReinstateUserBody,
74
+ RestoreUserBody,
75
+ RevokeDeviceBody,
76
+ RevokeSessionBody,
77
+ SuspendUserBody,
78
+ UserIdParam,
79
+ } from "./schemas";
80
+ import {
81
+ deletionView,
82
+ deviceView,
83
+ exportView,
84
+ type PurgeDisposition,
85
+ reinstatementView,
86
+ restorationView,
87
+ sessionView,
88
+ suspensionView,
89
+ userView,
90
+ } from "./views";
45
91
 
46
92
  type Ctx = Context<PithyHonoEnv>;
47
93
 
@@ -55,6 +101,11 @@ type Ctx = Context<PithyHonoEnv>;
55
101
  * POST {base}/admin/sessions/revoke auth:sessions:revoke json: RevokeSessionBody
56
102
  * POST {base}/admin/users/:userId/sessions/revoke auth:users:logout param: UserIdParam
57
103
  * POST {base}/admin/users/:userId/devices/revoke auth:devices:revoke param + json
104
+ * POST {base}/admin/users/:userId/suspend auth:users:suspend param + json: SuspendUserBody
105
+ * POST {base}/admin/users/:userId/reinstate auth:users:suspend param + json: ReinstateUserBody
106
+ * DELETE {base}/admin/users/:userId auth:users:delete param + json: DeleteUserBody
107
+ * POST {base}/admin/users/:userId/restore auth:users:delete param + json: RestoreUserBody
108
+ * GET {base}/admin/users/:userId/export auth:users:export param + query: ExportUserQuery
58
109
  *
59
110
  * ## Registered before the catch-all, or dead
60
111
  *
@@ -169,6 +220,122 @@ async function revokeTokens(c: Ctx, wiring: AuthWiring, tokens: readonly string[
169
220
  return tokens.length;
170
221
  }
171
222
 
223
+ /**
224
+ * What a lifecycle route hands `../lifecycle/`: the transitions' dependencies, with the request's correlation
225
+ * and the connection on every audit event they write, and the operator as the actor.
226
+ *
227
+ * The actor is the token's verified `sub` — which person at the dashboard — the same id every other admin
228
+ * event records, so the trail and the history table name the same somebody.
229
+ */
230
+ function lifecycleCall(c: Ctx, wiring: AuthWiring, caller: ControlPlaneContext, userId: string, reason: string) {
231
+ const correlated = context(c);
232
+ return {
233
+ deps: lifecycleDeps(c, wiring, { ...correlated, metadata: { connectionId: caller.connectionId } }),
234
+ actor: { type: "control-plane", id: caller.subject } satisfies LifecycleActor,
235
+ // Named so the refusal for a deleted account says which route comes first.
236
+ restoreRoute: `POST ${wiring.config.basePath}/admin/users/${userId}/restore`,
237
+ audit: { subject: caller.subject, connectionId: caller.connectionId, userId, reason, ...correlated },
238
+ };
239
+ }
240
+
241
+ /**
242
+ * A lifecycle route's body validator, which audits the bodies it refuses (#621). Every call is on the trail,
243
+ * a refusal included, and a body the validator turns away never reaches `auditedLifecycleCall`. So it is
244
+ * recorded here, as `denied` under the route's own action, with whatever reason the body carried — cut to the
245
+ * reason's own limit, so a refused essay is not stored whole — and the 400 is thrown as before.
246
+ */
247
+ function lifecycleBody<Schema extends z.ZodType>(schema: Schema, action: string | ((body: unknown) => string)) {
248
+ return validate("json", schema, async (raw, error, body) => {
249
+ // The route validated its `:userId` before its body, so it is readable here.
250
+ const c = raw as Context<PithyHonoEnv, string, { out: { param: z.output<typeof UserIdParam> } }>;
251
+ const caller = controlPlaneCaller(c);
252
+ const reason = body && typeof body === "object" ? (body as { reason?: unknown }).reason : undefined;
253
+ await recordLifecycleRefusal(
254
+ c.var.emit,
255
+ {
256
+ action: typeof action === "string" ? action : action(body),
257
+ subject: caller.subject,
258
+ connectionId: caller.connectionId,
259
+ userId: c.req.valid("param").userId,
260
+ reason: typeof reason === "string" ? reason.slice(0, MAX_REASON) : null,
261
+ ...context(c),
262
+ },
263
+ error,
264
+ // Hono's own refusal of a body that is not JSON carries no code; the client sees this one.
265
+ { code: "validation/invalid_input", outcome: "denied" },
266
+ );
267
+ });
268
+ }
269
+
270
+ /**
271
+ * End every session an account holds, after its columns are written — never before, for the reason the suspend
272
+ * route gives: enforcement refuses the account the moment the columns land, and revoking first would leave a
273
+ * window for a sign-in the revocation never saw. Through Better Auth's adapter, so `onSessionRevoked` hears
274
+ * each, and recorded under `auth/admin_user_sessions_revoked` with the cause.
275
+ */
276
+ async function endSessions(
277
+ c: Ctx,
278
+ wiring: AuthWiring,
279
+ caller: ControlPlaneContext,
280
+ userId: string,
281
+ cause: string,
282
+ ): Promise<number> {
283
+ const revoked = await revokeTokens(c, wiring, await userSessionTokens(db(c, wiring), userId));
284
+ await emitControlPlaneAction(c.var.emit, {
285
+ action: AuthAuditActions.adminUserSessionsRevoked,
286
+ subject: caller.subject,
287
+ connectionId: caller.connectionId,
288
+ resourceType: "user",
289
+ resourceId: userId,
290
+ ...context(c),
291
+ metadata: { revoked, cause },
292
+ });
293
+ return revoked;
294
+ }
295
+
296
+ /**
297
+ * Start the purge of one account now (#622): `started` when this Worker binds the purge Workflow and it took the
298
+ * instance — or already held it — and `pending` when it binds none or the start failed; the account is due
299
+ * either way, and the daily pass starts it. A failed start is not this call's failure: the deletion is already
300
+ * written, and a 500 over it would invite a retry that finds the account deleted and says nothing new.
301
+ *
302
+ * Under the instance id the deletion names (`../purge/start.ts`), so a hard deletion repeated, or one the daily
303
+ * pass also finds due, is the one purge and never a second.
304
+ */
305
+ async function startPurge(
306
+ c: Ctx,
307
+ result: DeleteTransition,
308
+ userId: string,
309
+ notify: boolean | undefined,
310
+ ): Promise<PurgeDisposition> {
311
+ const log = c.var.log.child("auth");
312
+ const binding = workflowBindingFor(c.env as Record<string, unknown>, AUTH_PURGE_BINDING);
313
+ if (!binding) {
314
+ log.warn("a deletion found no purge Workflow bound; the purge is pending", { userId });
315
+ return "pending";
316
+ }
317
+ try {
318
+ await startPurgeInstance(binding, {
319
+ userId,
320
+ deletedAt: result.deletedAt.getTime(),
321
+ ...(notify === undefined ? {} : { notify }),
322
+ at: new Date(),
323
+ });
324
+ return "started";
325
+ } catch (error) {
326
+ log.warn("the purge could not be started; the daily pass will start it", {
327
+ userId,
328
+ reason: error instanceof Error ? error.message : String(error),
329
+ });
330
+ return "pending";
331
+ }
332
+ }
333
+
334
+ /** What becomes of a soft deletion's purge: due later, or — when its window has already closed — due now. */
335
+ function scheduledOrDue(result: DeleteTransition): PurgeDisposition | "due" {
336
+ return result.purgeAfter.getTime() > Date.now() ? "scheduled" : "due";
337
+ }
338
+
172
339
  /**
173
340
  * Register the control-plane admin routes. Called by `createAuthRoutes` **before** the Better Auth
174
341
  * catch-all; see the file header for why that ordering is load-bearing.
@@ -400,5 +567,234 @@ export function registerAuthAdminRoutes(wiring: AuthWiring): (app: Hono<PithyHon
400
567
  return c.json({ revoked, removed } satisfies AdminDeviceRevokeResponse);
401
568
  },
402
569
  );
570
+
571
+ app.post(
572
+ `${base}/admin/users/:userId/suspend`,
573
+ describeRoute({
574
+ summary: "Suspend one user, with a reason: their sessions end and every sign-in is refused.",
575
+ verification: "control-plane",
576
+ scopes: [AUTH_USERS_SUSPEND_SCOPE],
577
+ responses: { 200: AdminUserSuspendResponse },
578
+ }),
579
+ requireControlPlane(AUTH_USERS_SUSPEND_SCOPE),
580
+ validate("param", UserIdParam),
581
+ lifecycleBody(SuspendUserBody, AuthAuditActions.adminUserSuspended),
582
+ async (c) => {
583
+ const { userId } = c.req.valid("param");
584
+ const { reason, until, notify } = c.req.valid("json");
585
+ const caller = controlPlaneCaller(c);
586
+ const call = lifecycleCall(c, wiring, caller, userId, reason);
587
+
588
+ // Every call is audited: the transition audits a suspension it writes, and this records the refusals.
589
+ // A suspension always writes — a fresh one or a restatement — so there is no no-op to record.
590
+ const result = await auditedLifecycleCall(
591
+ c.var.emit,
592
+ { action: AuthAuditActions.adminUserSuspended, ...call.audit },
593
+ () =>
594
+ suspendUser(call.deps, {
595
+ userId,
596
+ actor: call.actor,
597
+ reason,
598
+ until: until ?? null,
599
+ ...(notify === undefined ? {} : { notify }),
600
+ restoreRoute: call.restoreRoute,
601
+ }),
602
+ () => false,
603
+ );
604
+
605
+ // After the columns, never before. Enforcement refuses the account the moment they are written, so a
606
+ // session alive in between meets `auth/account_suspended`; revoking first would leave a window where a
607
+ // sign-in could mint one the revocation never saw. Every call revokes, a restatement included, so a
608
+ // credential that slipped past an earlier one does not outlive this one. Through Better Auth's adapter,
609
+ // so `onSessionRevoked` hears each. A refresh token is a session token here, so this ends both.
610
+ const revoked = await revokeTokens(c, wiring, await userSessionTokens(db(c, wiring), userId));
611
+ await emitControlPlaneAction(c.var.emit, {
612
+ action: AuthAuditActions.adminUserSessionsRevoked,
613
+ subject: caller.subject,
614
+ connectionId: caller.connectionId,
615
+ resourceType: "user",
616
+ resourceId: userId,
617
+ ...context(c),
618
+ metadata: { revoked, cause: "suspended" },
619
+ });
620
+
621
+ return c.json(suspensionView(userId, result, revoked) satisfies AdminUserSuspendResponse);
622
+ },
623
+ );
624
+
625
+ app.post(
626
+ `${base}/admin/users/:userId/reinstate`,
627
+ describeRoute({
628
+ summary: "Lift one user's suspension, with a reason. They sign in again; no session is restored.",
629
+ verification: "control-plane",
630
+ scopes: [AUTH_USERS_SUSPEND_SCOPE],
631
+ responses: { 200: AdminUserReinstateResponse },
632
+ }),
633
+ requireControlPlane(AUTH_USERS_SUSPEND_SCOPE),
634
+ validate("param", UserIdParam),
635
+ lifecycleBody(ReinstateUserBody, AuthAuditActions.adminUserReinstated),
636
+ async (c) => {
637
+ const { userId } = c.req.valid("param");
638
+ const { reason, notify } = c.req.valid("json");
639
+ const caller = controlPlaneCaller(c);
640
+ const call = lifecycleCall(c, wiring, caller, userId, reason);
641
+
642
+ // An account with no suspension in force is a 200 that changed nothing — the state the caller asked
643
+ // for already holds — and is audited as exactly that.
644
+ const result = await auditedLifecycleCall(
645
+ c.var.emit,
646
+ { action: AuthAuditActions.adminUserReinstated, ...call.audit },
647
+ () =>
648
+ reinstateUser(call.deps, {
649
+ userId,
650
+ actor: call.actor,
651
+ reason,
652
+ ...(notify === undefined ? {} : { notify }),
653
+ restoreRoute: call.restoreRoute,
654
+ }),
655
+ (outcome) => !outcome.changed,
656
+ );
657
+
658
+ return c.json(reinstatementView(userId, result) satisfies AdminUserReinstateResponse);
659
+ },
660
+ );
661
+
662
+ app.delete(
663
+ `${base}/admin/users/:userId`,
664
+ describeRoute({
665
+ summary:
666
+ "Delete one user, with a reason: soft by default, restorable until the purge window closes; hard when named, purged now.",
667
+ verification: "control-plane",
668
+ scopes: [AUTH_USERS_DELETE_SCOPE],
669
+ responses: { 200: AdminUserDeleteResponse },
670
+ }),
671
+ requireControlPlane(AUTH_USERS_DELETE_SCOPE),
672
+ validate("param", UserIdParam),
673
+ // A refused body is recorded under the mode it asked for, so a malformed hard deletion is on the trail as
674
+ // an attempt at one. Only the exact `"hard"` reads as hard, as only it parses as hard.
675
+ lifecycleBody(DeleteUserBody, (body) =>
676
+ (body as { mode?: unknown } | null)?.mode === "hard"
677
+ ? AuthAuditActions.adminUserHardDeleted
678
+ : AuthAuditActions.adminUserSoftDeleted,
679
+ ),
680
+ async (c) => {
681
+ const { userId } = c.req.valid("param");
682
+ const { mode, reason, notify } = c.req.valid("json");
683
+ const caller = controlPlaneCaller(c);
684
+ const call = lifecycleCall(c, wiring, caller, userId, reason);
685
+ const action = mode === "hard" ? AuthAuditActions.adminUserHardDeleted : AuthAuditActions.adminUserSoftDeleted;
686
+
687
+ // Every call is audited: the transition audits a deletion it writes, this records the refusals and the
688
+ // call that found the account already deleted.
689
+ const result = await auditedLifecycleCall(
690
+ c.var.emit,
691
+ { action, ...call.audit },
692
+ () =>
693
+ deleteUser(call.deps, {
694
+ userId,
695
+ actor: call.actor,
696
+ reason,
697
+ mode,
698
+ ...(notify === undefined ? {} : { notify }),
699
+ }),
700
+ (outcome) => outcome.outcome === "unchanged",
701
+ );
702
+
703
+ const sessionsRevoked = await endSessions(c, wiring, caller, userId, "deleted");
704
+ // A hard deletion starts its purge here. A soft one waits for the daily pass — unless its window has
705
+ // already closed, in which case it is due now and is started like a hard one.
706
+ const disposition = mode === "hard" ? "due" : scheduledOrDue(result);
707
+ const purge =
708
+ disposition === "due"
709
+ ? await startPurge(c, result, userId, mode === "hard" ? notify : undefined)
710
+ : disposition;
711
+ return c.json(deletionView(userId, mode, result, purge, sessionsRevoked) satisfies AdminUserDeleteResponse);
712
+ },
713
+ );
714
+
715
+ app.post(
716
+ `${base}/admin/users/:userId/restore`,
717
+ describeRoute({
718
+ summary:
719
+ "Restore one deleted user inside the purge window, with a reason. They sign in again; no session is restored.",
720
+ verification: "control-plane",
721
+ scopes: [AUTH_USERS_DELETE_SCOPE],
722
+ responses: { 200: AdminUserRestoreResponse },
723
+ }),
724
+ requireControlPlane(AUTH_USERS_DELETE_SCOPE),
725
+ validate("param", UserIdParam),
726
+ lifecycleBody(RestoreUserBody, AuthAuditActions.adminUserRestored),
727
+ async (c) => {
728
+ const { userId } = c.req.valid("param");
729
+ const { reason } = c.req.valid("json");
730
+ const caller = controlPlaneCaller(c);
731
+ const call = lifecycleCall(c, wiring, caller, userId, reason);
732
+
733
+ // After the purge there is no account, and the transition's 404 says the data is gone. A window that has
734
+ // closed is a conflict naming when. Both are refusals, and both are on the trail.
735
+ const result = await auditedLifecycleCall(
736
+ c.var.emit,
737
+ { action: AuthAuditActions.adminUserRestored, ...call.audit },
738
+ () => restoreUser(call.deps, { userId, actor: call.actor, reason }),
739
+ (outcome) => !outcome.changed,
740
+ );
741
+
742
+ return c.json(restorationView(userId, result) satisfies AdminUserRestoreResponse);
743
+ },
744
+ );
745
+
746
+ app.get(
747
+ `${base}/admin/users/:userId/export`,
748
+ describeRoute({
749
+ summary: "Export everything the kit holds about one user, from every composed capability, as one document.",
750
+ description:
751
+ "The answer to an access request. One entry per composed capability that declares a purge contribution, in the order the purge erases them. Audited as a disclosure, with the reason.",
752
+ verification: "control-plane",
753
+ scopes: [AUTH_USERS_EXPORT_SCOPE],
754
+ responses: { 200: AdminUserExportResponse },
755
+ }),
756
+ requireControlPlane(AUTH_USERS_EXPORT_SCOPE),
757
+ validate("param", UserIdParam),
758
+ validate("query", ExportUserQuery),
759
+ async (c) => {
760
+ const { userId } = c.req.valid("param");
761
+ const { reason } = c.req.valid("query");
762
+ const caller = controlPlaneCaller(c);
763
+ const call = lifecycleCall(c, wiring, caller, userId, reason);
764
+ const exportedAt = new Date();
765
+
766
+ // The account first, so an unknown or purged one is a 404 — the purged one saying its data is gone —
767
+ // and never a document of empty parts. Then every composed capability's part, each guarded on its own.
768
+ const entries = await auditedLifecycleCall(
769
+ c.var.emit,
770
+ { action: AuthAuditActions.adminUserExported, ...call.audit },
771
+ async () => {
772
+ await requirePresent(db(c, wiring), userId);
773
+ return purgeExports(wiring.purgeSteps ?? [], {
774
+ subject: { type: "user", id: userId },
775
+ env: c.env as Record<string, unknown>,
776
+ });
777
+ },
778
+ () => false,
779
+ );
780
+
781
+ // A disclosure, recorded with who asked, why, and which parts answered — never with any of the data.
782
+ await emitControlPlaneAction(c.var.emit, {
783
+ action: AuthAuditActions.adminUserExported,
784
+ subject: caller.subject,
785
+ connectionId: caller.connectionId,
786
+ resourceType: "user",
787
+ resourceId: userId,
788
+ ...context(c),
789
+ metadata: {
790
+ reason,
791
+ disclosure: true,
792
+ capabilities: entries.map((entry) => `${entry.capability}:${entry.state}`),
793
+ },
794
+ });
795
+
796
+ return c.json(exportView(userId, exportedAt, entries) satisfies AdminUserExportResponse);
797
+ },
798
+ );
403
799
  };
404
800
  }
@@ -93,22 +93,23 @@ export const AUTH_USERS_LOGOUT_SCOPE: ControlPlaneScope = "auth:users:logout";
93
93
  export const AUTH_DEVICES_REVOKE_SCOPE: ControlPlaneScope = "auth:devices:revoke";
94
94
 
95
95
  /**
96
- * Suspend an account and reinstate it (#620, the routes in #621). Ending somebody's access is an availability
96
+ * Suspend an account and reinstate it (#620): `POST {base}/admin/users/:userId/suspend` and `/reinstate` (#621). Ending somebody's access is an availability
97
97
  * operation on one person, and reversible — which is what separates it from deleting them, and why it is
98
98
  * granted apart from both reading them and erasing them.
99
99
  */
100
100
  export const AUTH_USERS_SUSPEND_SCOPE: ControlPlaneScope = "auth:users:suspend";
101
101
 
102
102
  /**
103
- * Delete an account, restore one inside its purge window, and start a purge (#620, the routes in #622). The
103
+ * Delete an account, restore one inside its purge window, and start a purge (#620):
104
+ * `DELETE {base}/admin/users/:userId` and `POST …/restore` (#622). The
104
105
  * one scope on this surface whose worst case cannot be undone: once the window closes, the person's rows are
105
106
  * gone from every capability that held them.
106
107
  */
107
108
  export const AUTH_USERS_DELETE_SCOPE: ControlPlaneScope = "auth:users:delete";
108
109
 
109
110
  /**
110
- * Export everything the kit holds about one account — the answer to an access request (#620, the route in
111
- * #622). A disclosure, and a far larger one than reading the user: it carries every capability's rows about
111
+ * Export everything the kit holds about one account — the answer to an access request (#620):
112
+ * `GET {base}/admin/users/:userId/export` (#622). A disclosure, and a far larger one than reading the user: it carries every capability's rows about
112
113
  * them, so it is granted on its own and audited as one.
113
114
  */
114
115
  export const AUTH_USERS_EXPORT_SCOPE: ControlPlaneScope = "auth:users:export";
@@ -117,9 +118,9 @@ export const AUTH_USERS_EXPORT_SCOPE: ControlPlaneScope = "auth:users:export";
117
118
  * Every control-plane scope auth defines — what `pithy dashboard connect` offers for this capability,
118
119
  * and the list a manifest or a doc quotes rather than re-typing.
119
120
  *
120
- * **The three lifecycle scopes are declared before the routes that require them.** The suspend, delete and
121
- * export routes land in #621 and #622; declaring the vocabulary here, once, is what lets those issues build on
122
- * one name each rather than three issues each choosing their own.
121
+ * **The lifecycle scopes were declared before the routes that require them** (#620): suspend and reinstate
122
+ * landed in #621, delete, restore and export in #622. Declaring the vocabulary here, once, is what let those
123
+ * issues build on one name each rather than each choosing its own.
123
124
  */
124
125
  export const AUTH_CONTROL_PLANE_SCOPES: readonly ControlPlaneScope[] = [
125
126
  AUTH_USERS_READ_SCOPE,
@@ -182,5 +183,36 @@ export function authAdminRoutes(basePath: string): AdminRoute[] {
182
183
  scope: AUTH_DEVICES_REVOKE_SCOPE,
183
184
  summary: "Sign one device out and forget it — for a phone reported lost.",
184
185
  },
186
+ {
187
+ method: "POST",
188
+ path: `${basePath}/admin/users/:userId/suspend`,
189
+ scope: AUTH_USERS_SUSPEND_SCOPE,
190
+ summary: "Suspend a user, with a reason. Their sessions end and every sign-in is refused.",
191
+ },
192
+ {
193
+ method: "POST",
194
+ path: `${basePath}/admin/users/:userId/reinstate`,
195
+ scope: AUTH_USERS_SUSPEND_SCOPE,
196
+ summary: "Lift a suspension, with a reason. They sign in again; no session comes back.",
197
+ },
198
+ {
199
+ method: "DELETE",
200
+ path: `${basePath}/admin/users/:userId`,
201
+ scope: AUTH_USERS_DELETE_SCOPE,
202
+ summary:
203
+ "Delete a user, with a reason. Soft by default: restorable until the purge window closes. Hard, when named: erased now.",
204
+ },
205
+ {
206
+ method: "POST",
207
+ path: `${basePath}/admin/users/:userId/restore`,
208
+ scope: AUTH_USERS_DELETE_SCOPE,
209
+ summary: "Restore a deleted user inside the purge window, with a reason. They sign in again.",
210
+ },
211
+ {
212
+ method: "GET",
213
+ path: `${basePath}/admin/users/:userId/export`,
214
+ scope: AUTH_USERS_EXPORT_SCOPE,
215
+ summary: "Everything the kit holds about one user, from every capability — the answer to an access request.",
216
+ },
185
217
  ];
186
218
  }
@@ -9,7 +9,7 @@ import type { Context, MiddlewareHandler } from "hono";
9
9
  import type { AuthWiring, ScopeResolver, ScopeResolverSession } from "../capability";
10
10
  import { authDatabase } from "../data/tables";
11
11
  import type { AuthInstance } from "../instance/auth";
12
- import { lifecycleRefusalFor, noteRefusal, noticedRefusal } from "../lifecycle/enforce";
12
+ import { lifecycleRefusalFor, noteRefusal, noticedRefusal, suspendedHolder } from "../lifecycle/enforce";
13
13
  import { LifecycleColumns } from "../lifecycle/state";
14
14
  import { withResignedCredentials } from "./credentialResign";
15
15
  import { getAuthInstance, resolveDb } from "./resolve";
@@ -103,7 +103,7 @@ async function resolveSession(c: Context<PithyHonoEnv>, wiring: AuthWiring, inst
103
103
  // capability's own guard raises the refusal itself, with its code; see `requireAuth` below.
104
104
  const refusal = await standingRefusal(c, wiring, session.user);
105
105
  if (refusal) {
106
- noteRefusal(c, refusal);
106
+ noteRefusal(c, refusal, { userId: session.user.id, sessionId: session.session.id });
107
107
  return;
108
108
  }
109
109
  // Before the context is built, so a resolver sees the request exactly as it arrived and the
@@ -202,3 +202,46 @@ export function requireAuth(): MiddlewareHandler<PithyHonoEnv> {
202
202
  await next();
203
203
  };
204
204
  }
205
+
206
+ /** Whose account a request may act on as its own holder: the signed-in account, or a suspended one's. */
207
+ export interface AccountHolder {
208
+ /** The account. */
209
+ readonly userId: string;
210
+ /** The session the request presented. */
211
+ readonly sessionId: string;
212
+ /** Whether the account is suspended — every other route refuses it. */
213
+ readonly suspended: boolean;
214
+ }
215
+
216
+ /**
217
+ * The account this request's credential opens, for a route a **suspended** account may still use — and there is
218
+ * exactly one, deleting it (#622). The App Store and Google Play require that a person can delete their account
219
+ * from inside the app, and a suspension is no reason to keep somebody who wants to leave.
220
+ *
221
+ * A deleted account is not admitted: there is nothing left to delete. Neither is a request whose standing could
222
+ * not be checked.
223
+ */
224
+ export function accountHolder(c: Context<PithyHonoEnv>): AccountHolder | null {
225
+ if (c.var.auth) return { userId: c.var.auth.userId, sessionId: c.var.auth.sessionId, suspended: false };
226
+ const held = suspendedHolder(c);
227
+ return held ? { ...held, suspended: true } : null;
228
+ }
229
+
230
+ /**
231
+ * The gate for that route: `requireAuth()`, with a suspended account's genuine credential admitted. Everything
232
+ * `requireAuth()` refuses otherwise, it refuses the same way — a deleted account with its code, anything else
233
+ * with `auth/invalid_token`.
234
+ */
235
+ export function requireAccountHolder(): MiddlewareHandler<PithyHonoEnv> {
236
+ return async (c, next) => {
237
+ if (!accountHolder(c)) {
238
+ const refusal = noticedRefusal(c);
239
+ if (refusal) throw refusal;
240
+ throw new UnauthorizedError({
241
+ message: "Authentication required.",
242
+ action: "Sign in and retry with a valid session or bearer token.",
243
+ });
244
+ }
245
+ await next();
246
+ };
247
+ }