@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
@@ -1,13 +1,13 @@
1
1
  # Account lifecycle
2
2
 
3
- An account can be suspended or deleted. The kit holds the state, enforces it at every door, records every transition, and sends the mail. The routes that suspend, delete, restore and export arrive with their own issues, and so does the purge that erases a deleted account's data: the suspend routes with #621, the delete, restore and export routes and the purge Workflow with #622. This page is the seam they are built on.
3
+ An account can be suspended or deleted. The kit holds the state, enforces it at every door, records every transition, and sends the mail. An operator suspends, reinstates, deletes, restores and exports an account through control-plane routes, below. A person deletes their own account from inside your app. A purge erases a deleted account's data from every capability that holds it, once its window closes.
4
4
 
5
5
  ## Two states
6
6
 
7
7
  | State | Columns | What it means | Ends |
8
8
  |---|---|---|---|
9
9
  | Suspended | `suspended_at`, `suspended_until` | The account cannot sign in, refresh a token, or act on any route. | At `suspended_until`, by itself, or when an operator reinstates it. |
10
- | Deleted | `deleted_at`, `purge_after` | The same, and its data is due for erasure once the purge window closes. Restorable until then. | When it is restored, or when the purge erases it. The purge arrives with #622; until then a deleted account stays deleted and its rows stay where they are. |
10
+ | Deleted | `deleted_at`, `purge_after` | The same, and its data is due for erasure once the purge window closes. Restorable until then. | When it is restored inside the window, or when the purge erases it. |
11
11
 
12
12
  Both live on `pithy_auth_users`, so a session read already carries them. An account in good standing costs no extra read, and neither does refusing a deleted one. Refusing a suspended account costs one: the operator's reason is read from `pithy_auth_user_lifecycle`, on every refused request. A deleted account outranks a suspension it was already under. A suspension past its `suspended_until` is not a suspension, and nothing has to be written to end it.
13
13
 
@@ -34,11 +34,13 @@ A magic link for a refused account returns to the screen it named, with the code
34
34
 
35
35
  ## The record
36
36
 
37
- `pithy_auth_user_lifecycle` holds every transition: the action, the actor, the reason, the time. The columns say what is true now; the table says what happened and who did it. The two are written in one transaction, so neither is ever there without the other. It has no foreign key to the user, because a purge erases the user row and this record must outlive it. It is the one `pithy_auth_*` row the purge will leave behind.
37
+ `pithy_auth_user_lifecycle` holds every transition: the action, the actor, the reason, the time. The columns say what is true now; the table says what happened and who did it. The two are written in one transaction, so neither is ever there without the other. It has no foreign key to the user, because a purge erases the user row and this record must outlive it. It is the one `pithy_auth_*` row the purge leaves behind.
38
38
 
39
- A transition that finds the account already where it was asked to put it does nothing: no row, no event, no mail, no hook. A suspension past its end counts as no suspension, so reinstating it is nothing too. A deleted account cannot be suspended or reinstated; restore it first, and its suspension is still there to lift.
39
+ A transition that finds the account already where it was asked to put it does nothing: no row, no event, no mail, no hook. The control-plane routes still record the call on the trail, as below. A suspension past its end counts as no suspension, so reinstating it is nothing too. A deleted account cannot be suspended or reinstated; restore it first, and its suspension is still there to lift.
40
40
 
41
- Each transition also writes an audit event: `auth/admin_user_suspended`, `auth/admin_user_reinstated`, `auth/admin_user_soft_deleted`, `auth/admin_user_restored`, `auth/admin_user_purged`, and `auth/user_self_deleted` when the account's holder deletes it.
41
+ Suspending an account that is already suspended is the one exception. It restates the suspension: the new reason and end replace the old, a row records them, and the mail and the audit event go out. The start stays, and no hook fires, because the account was suspended and still is.
42
+
43
+ Each transition also writes an audit event: `auth/admin_user_suspended`, `auth/admin_user_reinstated`, `auth/admin_user_soft_deleted`, `auth/admin_user_hard_deleted`, `auth/admin_user_restored`, `auth/admin_user_purged`, and `auth/user_self_deleted` when the account's holder deletes it. An export writes `auth/admin_user_exported`.
42
44
 
43
45
  ## Scopes
44
46
 
@@ -50,13 +52,119 @@ Reading a user, ending their access, and erasing them are three grants, beside `
50
52
 
51
53
  None of them is implied by another. See [CONTROL-PLANE.md](../../../docs/CONTROL-PLANE.md) for how a connection is granted one.
52
54
 
55
+ ## Suspend and reinstate
56
+
57
+ Two routes, each gated by `auth:users:suspend`. A connection holding only `auth:users:read` is refused 403, and the scope is checked before the body is read.
58
+
59
+ ```
60
+ POST /auth/admin/users/:userId/suspend { reason, until?, notify? }
61
+ POST /auth/admin/users/:userId/reinstate { reason, notify? }
62
+ ```
63
+
64
+ The paths are under auth's `basePath` (`/auth` by default), which the manifest reports — not under `/control-plane`, which holds only the seam's own routes. `reason` is required on both: one sentence, at most 500 characters, written for the person, because a suspension's reason is what every refused sign-in shows them. A request without one is `validation/invalid_input`.
65
+
66
+ **Suspend** stamps the columns, writes the row, and then revokes every session the account holds. A refresh token is a session token, so it goes with them. Revoked after the columns, never before: a session alive in between meets `auth/account_suspended`. The person's held credential stops working, a refresh is refused, and signing in again answers `auth/account_suspended` with the reason. `until` is an ISO-8601 time in the future; one in the past is refused. The suspension ends by itself when it passes, with nothing written. Suspending a suspended account restates it, and the response says `outcome: "updated"`. The response carries the suspension in force, `sessionsRevoked`, and `mailed`.
67
+
68
+ **Reinstate** lifts the suspension. It restores no session: the person signs in again. An account with no suspension in force answers 200 with `outcome: "unchanged"`, and nothing is written.
69
+
70
+ Neither touches a deleted account. Both answer `core/conflict`, naming the restore route, because a deleted account is restored, not reinstated. An unknown `:userId` is a 404.
71
+
72
+ `notify` is true when absent. It sends the account-suspended mail, or the account-reinstated mail, through `@pithy-sh/email`. `notify: false` sends none. The config can turn a mail off for every call; `notify` turns it off for one.
73
+
74
+ Every call is audited, as `auth/admin_user_suspended` or `auth/admin_user_reinstated`, with the operator, the connection, the reason and the user id. A refusal is recorded as `denied` with its code — a body the validator turns away included, with whatever reason it carried — and a reinstatement that changed nothing as a success with `changed: false`. The sessions a suspension ends are recorded as `auth/admin_user_sessions_revoked`, `cause: "suspended"`.
75
+
76
+ ## Delete, restore and export
77
+
78
+ Three routes. Deleting and restoring are gated by `auth:users:delete`, exporting by `auth:users:export`. Neither grants the other, and `auth:users:read` grants neither. The scope is checked before the body is read.
79
+
80
+ ```
81
+ DELETE /auth/admin/users/:userId { mode?, reason, notify? }
82
+ POST /auth/admin/users/:userId/restore { reason }
83
+ GET /auth/admin/users/:userId/export?reason=…
84
+ ```
85
+
86
+ `reason` is required on all three, on the same terms as a suspension's. A request without one is `validation/invalid_input`.
87
+
88
+ **Two modes, and soft is the default.** `mode: "soft"`, or no mode at all, stamps `deleted_at` and `purge_after` — now plus `retention.purgeAfterDays`, 30 unless you set it — and revokes every session the account holds. Signing in again answers `auth/account_deleted`. The deletion-scheduled mail goes out with the purge date and, when you configure one, the restore path. `onUserDeleted` fires. The account can be restored until `purge_after`. `mode: "hard"` closes the window now: `purge_after` is the moment of the deletion, nothing can restore it, and the purge starts in the same call. You name it on purpose. A typo — `"Hard"`, `"hrad"` — is a 400, never either mode. A hard deletion of an account already deleted softly brings its purge forward to now.
89
+
90
+ The response says what happened: `outcome` is `deleted`, `brought_forward`, or `unchanged` for an account already deleted. `purge` is `scheduled` for a soft deletion, `started` when this call started the purge, and `pending` when the account is due and this Worker binds no purge Workflow to start. `notify: false` silences the mail this call sends: the deletion-scheduled notice for soft, the deletion-complete notice for hard.
91
+
92
+ **Restore** clears both columns inside the window and records it. The person signs in again; no session comes back. A suspension the account was under before the deletion is still there, and the response says `state: "suspended"`. Once `purge_after` has passed the purge is due, so a restore is a 409 naming the date. The window is checked against the database's clock as the restore's write runs, the same clock the purge checks it against, so a restore and a purge that race always agree on which one won. A window that closes while a restore is in flight, or that a hard deletion brings forward, is the same 409. After the purge there is no account: a 404, whose action says the data is gone.
93
+
94
+ **Export** answers an access request. It returns one JSON document, validated by `AdminUserExportResponse` from `@pithy-sh/auth/src/http/responses`: the subject, when it was read, and one entry per composed capability that declares a purge contribution, in the order the purge erases them. An entry is `exported` with that capability's data, `not_exported` when it erases rows it does not say how to export, or `unavailable` when its rows would not read. Auth's own part is `AuthUserExport`: the account, its sessions, linked providers, devices, history and its rows in the user-keyed tables its Better Auth plugins created, and no credential — no session token, no provider token, no push token, no two-factor secret or backup code, no key. It is audited as a disclosure, `auth/admin_user_exported`, with the operator, the reason, and which parts answered, never the data. An unknown or purged account is a 404.
95
+
96
+ Every call is audited, as for suspend and reinstate: a deletion under `auth/admin_user_soft_deleted` or `auth/admin_user_hard_deleted`, a restore under `auth/admin_user_restored`, with the operator, the connection, the reason and the user id. A refusal is `denied` with its code, and a call that changed nothing is a success with `changed: false`.
97
+
98
+ ## Deleting your own account
99
+
100
+ ```
101
+ DELETE /auth/account { confirm: true }
102
+ ```
103
+
104
+ The signed-in person deletes their own account. **This is the route the App Store and Google Play require**: an app that lets people create an account must let them delete it from inside the app. Put a button behind it in your settings screen, and send `confirm: true` once the person has confirmed. Without the confirmation it is a 400 and nothing moves.
105
+
106
+ It is always soft, on the configured window, and the subject is always the session's own: no field names an account, and a key that tries is dropped. Every session ends, this one included. It is audited as `auth/user_self_deleted`, with the person as the actor. A suspended account can still delete itself — a suspension is no reason to keep somebody who wants to leave. A deleted one is refused with `auth/account_deleted`.
107
+
108
+ **Signing in to leave.** A suspension ends every session and refuses every sign-in, so a suspended person holds no credential to call this route with. A sign-in that sends `x-pithy-intent: delete-account` is the way back in: the person signs in as usual, by code, link or provider, and the suspended account gets a session anyway. That session opens nothing else. Every other route, a token and a refresh included, still answers `auth/account_suspended`, and `DELETE /auth/account` is the one that admits it. When a sign-in answers `auth/account_suspended`, offer the person a delete button that signs in again with the header and then calls this route. A deleted account is refused with or without the header. The header only works on a sign-in request your app sends itself, such as the OTP or an ID-token sign-in. A browser redirect, such as a magic link or a web social callback, cannot carry it. CSRF-guarded in cookie mode, like every mutating route.
109
+
110
+ **The restore path.** A person who changes their mind inside the window cannot sign in to undo it, so the deletion-scheduled mail tells them how: its restore button links to `retention.restoreUrl` when you set one — an http(s) page of yours — and the mail always says to reply before the purge date. An operator restores the account from the management surface.
111
+
112
+ ## The purge
113
+
114
+ A purge erases one deleted account from every capability that holds rows about it. It runs as a Workflow, **one step per composed purge contribution**, named for its capability, so a capability that fails retries alone and the steps that finished are not run again. Each step records that it ran in `pithy_auth_user_lifecycle`, with the contribution's summary. The order:
115
+
116
+ 1. Is the account due — deleted, with its window closed? A restored account, one inside its window, and one already erased end the run here, having erased nothing. Re-running a purge for the same subject exits without error.
117
+ 2. Every composed contribution but auth's, in composition order, your `app` last.
118
+ 3. The deletion-complete mail, **before the address is erased**: auth's rows, which hold it, are still there.
119
+ 4. Auth's own: the user row, its sessions, linked providers, devices, refresh-token ledger and pending sign-in codes, and its rows in every table a composed Better Auth plugin created with a `userId` column — a two-factor secret and its backup codes, a passkey, an API key. Its history stays — the one `pithy_auth_*` row left. `organization()`'s tables are not erased yet; a membership is the organization's as much as the person's.
120
+ 5. The `purged` record, `auth/admin_user_purged`, and `onUserPurged`, once — even when two purges of one account overlap.
121
+
122
+ A daily cron at 02:00 UTC starts the purge for every account past its `purge_after`, and for none before it. A hard deletion starts its own. Either way the instance is named for the deletion and the UTC day, so a hard deletion repeated, or one the daily pass also finds due, is one purge, and a purge that failed is started again by the next day's pass. A hard deletion's `notify: false` is saved with the deletion, so it holds when the daily pass is the one that starts its purge.
123
+
124
+ The `scheduled` handler starts only the jobs whose `schedule` is the cron that fired, so the daily pass runs once a day even in a Worker whose other jobs run hourly.
125
+
126
+ **The Workflows are yours to export.** A purge runs every composed capability's contribution, your own among them, and only the Worker that composes auth has them. So the two classes are five lines each in that Worker's entry, beside `createEntrypoint`, and their bodies are the kit's:
127
+
128
+ ```ts
129
+ // apps/api/src/index.ts
130
+ import { WorkflowEntrypoint, type WorkflowEvent, type WorkflowStep } from "cloudflare:workers";
131
+ import { NonRetryableError } from "cloudflare:workflows";
132
+ import { runAuthPurge, runAuthPurgeDue } from "@pithy-sh/auth/src/purge/workflow";
133
+
134
+ export class AuthPurgeWorkflow extends WorkflowEntrypoint<Record<string, unknown>> {
135
+ override run(event: WorkflowEvent<unknown>, step: WorkflowStep) {
136
+ return runAuthPurge(this.env, event, step, NonRetryableError);
137
+ }
138
+ }
139
+
140
+ export class AuthPurgeDueWorkflow extends WorkflowEntrypoint<Record<string, unknown>> {
141
+ override run(event: WorkflowEvent<unknown>, step: WorkflowStep) {
142
+ return runAuthPurgeDue(this.env, event, step, NonRetryableError);
143
+ }
144
+ }
145
+ ```
146
+
147
+ ```jsonc
148
+ // apps/api/wrangler.jsonc, in each environment's stanza
149
+ "workflows": [
150
+ { "binding": "AUTH_PURGE", "name": "acme-prod-auth-purge", "class_name": "AuthPurgeWorkflow" },
151
+ { "binding": "AUTH_PURGE_DUE", "name": "acme-prod-auth-purge-due", "class_name": "AuthPurgeDueWorkflow" }
152
+ ],
153
+ "triggers": { "crons": ["0 2 * * *"] }
154
+ ```
155
+
156
+ `pithy worker sync` leaves these entries and the cron where you wrote them, and `pithy deploy` does not count them against your app's own Workflows. Until they are bound, deletions still shut the account, a hard deletion reports its purge as `pending`, and nothing is erased. `c.var.workflows.trigger("auth/purge-due", {})` runs the daily pass on demand.
157
+
158
+ The purge audits from the Workflow through the composed audit capability, which provides a recorder for code with no request. With no audit capability composed, nothing is recorded, as for every other event.
159
+
53
160
  ## Config
54
161
 
55
162
  ```ts
56
163
  auth({
57
164
  baseURL: "https://api.example.com",
58
- // How long a deleted account waits before the purge erases its data (the purge lands in #622). 30 when nothing says otherwise.
59
- retention: { purgeAfterDays: 30 },
165
+ // How long a deleted account waits before the purge erases its data. 30 when nothing says otherwise. `restoreUrl`
166
+ // is where the deletion-scheduled mail sends somebody who wants their account back: an http(s) page of yours.
167
+ retention: { purgeAfterDays: 30, restoreUrl: "https://example.com/account/restore" },
60
168
  // All four send by default. Turn one off by setting it to false.
61
169
  lifecycleEmails: { accountSuspended: true, accountReinstated: true, deletionScheduled: true, deletionComplete: true },
62
170
  });
@@ -64,7 +172,7 @@ auth({
64
172
 
65
173
  ## Mail
66
174
 
67
- Four templates in `@pithy-sh/email`, all transactional, so an unsubscribe never silences them: account suspended, account reinstated, deletion scheduled, deletion complete. Each says what happened and what it means. Account suspended and deletion scheduled also say who to answer: a reply, which reaches your sending address. Account reinstated and deletion complete say nothing about who to answer; add that to your own copy if your people need it. Deletion scheduled carries the date the purge is due. Deletion complete carries the date it ran. Each is written in the account's own language, dates included.
175
+ Four templates in `@pithy-sh/email`, all transactional, so an unsubscribe never silences them: account suspended, account reinstated, deletion scheduled, deletion complete. Each says what happened and what it means. Account suspended and deletion scheduled also say who to answer: a reply, which reaches your sending address. Account reinstated and deletion complete say nothing about who to answer; add that to your own copy if your people need it. Deletion scheduled carries the date the purge is due, and the restore button when `retention.restoreUrl` is set. Deletion complete carries the date it ran, and is sent before the address is erased. Each is written in the account's own language, dates included.
68
176
 
69
177
  ## Hooks
70
178
 
@@ -78,7 +186,7 @@ auth({
78
186
  });
79
187
  ```
80
188
 
81
- Each fires once per transition. A call that finds the account already where it asked to put it fires nothing. A hook that throws is logged and changes nothing: the transition is already written.
189
+ Each fires once per transition. A call that finds the account already where it asked to put it fires nothing, and neither does restating a suspension. A hook that throws is logged and changes nothing: the transition is already written.
82
190
 
83
191
  ## Screens
84
192
 
@@ -86,7 +194,7 @@ Three screens ship with auth and are yours after `pithy ui add react`: account s
86
194
 
87
195
  ## The purge contribution
88
196
 
89
- A hard delete has to reach rows other capabilities hold, and no foreign key crosses a capability. So each capability declares how one subject's rows are erased or anonymized, on the `Capability` contract:
197
+ A purge has to reach rows other capabilities hold, and no foreign key crosses a capability. So each capability declares how one subject's rows are erased or anonymized, and what an export hands back, on the `Capability` contract:
90
198
 
91
199
  ```ts
92
200
  import type { PurgeContribution } from "@pithy-sh/core/src/capability/purge";
@@ -97,9 +205,13 @@ const purge: PurgeContribution = {
97
205
  erase: async ({ subject, env }) => {
98
206
  // Remove or anonymize this user's rows. Succeed when there is nothing left to remove.
99
207
  },
208
+ export: async ({ subject, env }) => {
209
+ // What you hold about this user, as one JSON object. No credentials.
210
+ return { drafts: [] };
211
+ },
100
212
  };
101
213
 
102
214
  defineCapability({ name: "app", requiredBindings: [], purge: [purge] });
103
215
  ```
104
216
 
105
- Today the kit declares the contract and the window, and nothing calls `erase` yet. The purge Workflow arrives with #622. It will run every composed contribution as its own step, named for its capability, so a failure retries that capability alone. That is why there is at most one per subject per capability, and why `erase` must succeed when the rows are already gone. `defineCapability` refuses a contribution for a subject the kit does not know. Declare one on your own `app` capability for your own tables.
217
+ The purge runs every composed contribution as its own step, named for its capability, so a failure retries that capability alone. That is why there is at most one per subject per capability, and why `erase` must succeed when the rows are already gone: a step is retried after a failure that may have come once they were. Any fault in `erase` is retried with the platform's backoff, because the contract makes it safe to. `export` is optional; without one, the export lists the capability as `not_exported`. A throw from it costs its own entry, never the document. The kit knows two subjects, `user` and `organization` — the second for rows scoped to a tenant, which `@pithy-sh/organization`'s purge runs ([`organization-lifecycle.md`](../../organization/docs/organization-lifecycle.md#the-purge)) — and `defineCapability` refuses a contribution for any other. Declare one on your own `app` capability for your own tables.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pithy-sh/auth",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -42,10 +42,10 @@
42
42
  "better-auth": "^1.7.11"
43
43
  },
44
44
  "peerDependencies": {
45
- "@pithy-sh/core": "^0.12.0",
46
- "@pithy-sh/email": "^0.6.0",
47
- "@pithy-sh/secrets": "^0.6.0",
48
- "@pithy-sh/turnstile": "^0.6.0",
45
+ "@pithy-sh/core": "^0.13.0",
46
+ "@pithy-sh/email": "^0.7.0",
47
+ "@pithy-sh/secrets": "^0.6.1",
48
+ "@pithy-sh/turnstile": "^0.6.1",
49
49
  "hono": "^4.13.2",
50
50
  "kysely": "^0.29.0",
51
51
  "zod": "^4.4.0"
@@ -99,7 +99,7 @@
99
99
  "Facebook (optional): set `facebook: { enabled: true }`, then `pithy secrets create auth-facebook-credentials` with the typed JSON `{ clientId, clientSecret }`. See the package's docs/facebook-oauth.md.",
100
100
  "GitHub (optional): set `github: { enabled: true }`, then `pithy secrets create auth-github-credentials` with the typed JSON `{ clientId, clientSecret }`. See the package's docs/github-oauth.md.",
101
101
  "Microsoft (optional): set `microsoft: { enabled: true }`, then `pithy secrets create auth-microsoft-credentials` with the typed JSON `{ clientId, clientSecret, tenantId }`. Add the `xms_edov` optional claim to the ID token in the app registration, or every work and school address is verified by magic link before it links. See the package's docs/microsoft-oauth.md.",
102
- "Looking a user up and signing them out from a dashboard is a `control-plane` surface, not an admin user, so the routes under /auth/admin are reached with a signed management credential rather than a session. Add `controlplane()` to this Worker and run `pithy dashboard connect`, then grant the connection only what its tooling needs: `auth:users:read` to find people, `auth:devices:read` to walk the device registry, `auth:sessions:revoke` to kill one stolen session, `auth:users:logout` to sign somebody out everywhere, `auth:devices:revoke` for a phone reported lost, and the account lifecycle's three: `auth:users:suspend`, `auth:users:delete`, `auth:users:export`. Eight scopes and not one admin flag — a support tool that looks people up must not also be able to sign the customer base out, and an incident-response tool that kills a session has no business reading every address in the user table. With the seam not composed every /auth/admin route answers `controlplane/not_connected`, and no app session opens any of them whatever it carries. There is deliberately no impersonation: signing in as a user produces a credential indistinguishable from theirs, so it is excluded until it has its own design and security review."
102
+ "Looking a user up and signing them out from a dashboard is a `control-plane` surface, not an admin user, so the routes under /auth/admin are reached with a signed management credential rather than a session. Add `controlplane()` to this Worker and run `pithy dashboard connect`, then grant the connection only what its tooling needs: `auth:users:read` to find people, `auth:devices:read` to walk the device registry, `auth:sessions:revoke` to kill one stolen session, `auth:users:logout` to sign somebody out everywhere, `auth:devices:revoke` for a phone reported lost, and the account lifecycle's three: `auth:users:suspend` to suspend somebody and reinstate them, `auth:users:delete`, `auth:users:export`. Eight scopes and not one admin flag — a support tool that looks people up must not also be able to sign the customer base out, and an incident-response tool that kills a session has no business reading every address in the user table. With the seam not composed every /auth/admin route answers `controlplane/not_connected`, and no app session opens any of them whatever it carries. There is deliberately no impersonation: signing in as a user produces a credential indistinguishable from theirs, so it is excluded until it has its own design and security review."
103
103
  ],
104
104
  "configOptions": [
105
105
  {
@@ -159,6 +159,12 @@ export const AuthAuditActions = {
159
159
  *
160
160
  * The dashboard's own `customer/user_suspended` and `customer/user_restored` are the client side of the
161
161
  * same events, recorded where the operator pressed the button.
162
+ *
163
+ * **The suspend and reinstate routes record every call under the same action (#621)**, the ones the
164
+ * transition did not write included: a refusal as `denied` with its code in `metadata.code`, and a
165
+ * reinstatement that found nothing to lift as a `success` with `metadata.changed: false`. A restated
166
+ * suspension is the transition's own event, with `metadata.updated: true`. So one filter on the action
167
+ * finds every attempt on one account. `../lifecycle/audited.ts` writes the route's half.
162
168
  */
163
169
 
164
170
  /** An account was suspended from the management surface. Carries the reason and any end date. */
@@ -167,12 +173,25 @@ export const AuthAuditActions = {
167
173
  adminUserReinstated: "auth/admin_user_reinstated",
168
174
  /** An account was deleted from the management surface, with its purge window starting now. */
169
175
  adminUserSoftDeleted: "auth/admin_user_soft_deleted",
176
+ /**
177
+ * An account was deleted from the management surface with no window — its purge starts now (#622). Also
178
+ * written when a hard deletion brings an already-deleted account's purge forward, with
179
+ * `metadata.broughtForward: true`. Never written by omission: the route reaches it only for `mode: "hard"`.
180
+ */
181
+ adminUserHardDeleted: "auth/admin_user_hard_deleted",
170
182
  /** A deleted account was restored inside its purge window, from the management surface. */
171
183
  adminUserRestored: "auth/admin_user_restored",
172
184
  /** A deleted account's data was erased. Recorded once, when the last purge step has run. */
173
185
  adminUserPurged: "auth/admin_user_purged",
174
186
  /** The account's own holder deleted their account. Always a soft deletion, on the configured window. */
175
187
  userSelfDeleted: "auth/user_self_deleted",
188
+ /**
189
+ * Everything the kit holds about one account was exported from the management surface — an access request
190
+ * answered (#622). A **disclosure**, and the largest one on this surface: it carries every composed
191
+ * capability's rows about the person. Recorded with the caller, the reason they gave, and which capabilities
192
+ * answered; never with any of the data.
193
+ */
194
+ adminUserExported: "auth/admin_user_exported",
176
195
  } as const;
177
196
 
178
197
  /** One of the auth audit action codes. */
package/src/audit/emit.ts CHANGED
@@ -371,11 +371,13 @@ export async function emitControlPlaneAction(
371
371
  userAgent?: string;
372
372
  requestId?: string;
373
373
  metadata?: Record<string, unknown>;
374
+ /** `success` unless the call was refused (`denied`) or broke (`failure`) — #621 records both. */
375
+ outcome?: "success" | "denied" | "failure";
374
376
  },
375
377
  ): Promise<void> {
376
378
  await safeEmit(emit, {
377
379
  action: event.action,
378
- outcome: "success",
380
+ outcome: event.outcome ?? "success",
379
381
  actorType: "control-plane",
380
382
  actorId: event.subject,
381
383
  resourceType: event.resourceType,
package/src/capability.ts CHANGED
@@ -2,8 +2,11 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import type { D1Database } from "@cloudflare/workers-types";
5
+ import { composedAuditEmit } from "@pithy-sh/core/src/audit/composed";
6
+ import type { AuditEmit } from "@pithy-sh/core/src/audit/recorder";
5
7
  import type { Capability, PithyHonoEnv, PithyMiddleware } from "@pithy-sh/core/src/capability/capability";
6
8
  import { defineCapability } from "@pithy-sh/core/src/capability/capability";
9
+ import { type PurgeStep, purgeSteps } from "@pithy-sh/core/src/capability/purge";
7
10
  import { ValidationError } from "@pithy-sh/core/src/error/pithyError";
8
11
  import type { EmailCapability } from "@pithy-sh/email/src/capability";
9
12
  import { isEmailCapability } from "@pithy-sh/email/src/capability";
@@ -27,6 +30,8 @@ import { AUTH_MIGRATION_ORDER } from "./migrations/0001_init";
27
30
  import { authPluginPlan } from "./migrations/pluginTables";
28
31
  import { AUTH_MIGRATIONS } from "./migrations/set";
29
32
  import { type AuthPeer, authPeer } from "./peer";
33
+ import { authPurgeContribution } from "./purge/contribution";
34
+ import { authWorkflows } from "./purge/specs";
30
35
  import { authDevSessionSeed } from "./seeds/devSession";
31
36
  import { authExampleSeed } from "./seeds/example";
32
37
  import { PACKAGE_NAME, PACKAGE_VERSION } from "./version.generated";
@@ -141,6 +146,12 @@ export const AuthConfig = z
141
146
  .describe(
142
147
  "How many days a deleted account waits before its data is erased. Inside the window it cannot sign in and can be restored; after it, the purge erases its rows from every capability that holds them. Defaults to 30.",
143
148
  ),
149
+ restoreUrl: z
150
+ .url({ protocol: /^https?$/ })
151
+ .optional()
152
+ .describe(
153
+ "Where a person whose account is deleted asks for it back inside the window: an http(s) page of yours. Carried in the deletion-scheduled mail as its restore button, so it must be a web address — a tracked click redirects only to one. Absent, the mail still tells them to reply before the purge date.",
154
+ ),
144
155
  })
145
156
  .prefault({})
146
157
  .describe(
@@ -209,6 +220,12 @@ export interface AuthWiring {
209
220
  * Optional on the wiring for the reason `onSessionRevoked` is: no hook is the ordinary composition.
210
221
  */
211
222
  lifecycleHooks?: UserLifecycleHooks | undefined;
223
+ /**
224
+ * Every composed capability's purge step for a user, auth's own among them, in composition order (#622). Filled
225
+ * by `compose`; the export route reads every capability's contribution from it, and the purge runs it.
226
+ * Optional on the wiring for the reason `onSessionRevoked` is: a harness that builds this by hand composes none.
227
+ */
228
+ purgeSteps?: readonly PurgeStep[] | undefined;
212
229
  }
213
230
 
214
231
  /** The session a {@link ScopeResolver} is asked about — the one Better Auth just resolved for this request. */
@@ -312,6 +329,16 @@ export interface AuthCapability extends Capability {
312
329
  * outside a request this capability serves — the purge Workflow (#622) fires `onUserPurged` through it.
313
330
  */
314
331
  lifecycleHooks: UserLifecycleHooks;
332
+ /**
333
+ * Every composed capability's purge step for a user, auth's own among them, in composition order (#622). Empty
334
+ * until `compose` has run. Read by the purge Workflow, which runs in the Worker that composed it.
335
+ */
336
+ purgeSteps: readonly PurgeStep[];
337
+ /**
338
+ * The audit recorder for code with no request, over one run's env — the composed audit capability's, or the
339
+ * no-op (#622). Read by the purge Workflow, which owes the trail its `auth/admin_user_purged`.
340
+ */
341
+ auditFor: (env: Record<string, unknown>) => AuditEmit;
315
342
  /**
316
343
  * What a capability composed beside this one reads an account through — `matchmaking`, `support`,
317
344
  * `testers`. Found in their `compose` hooks, so none of them imports this package and a project without
@@ -398,7 +425,13 @@ export function auth(options: AuthOptions): AuthCapability {
398
425
  onSessionRevoked,
399
426
  resolveScopes,
400
427
  lifecycleHooks,
428
+ purgeSteps: [],
401
429
  };
430
+ // Filled by `compose`, read by the purge Workflow through the capability and by the export route through the
431
+ // wiring. One array, so both read the same steps.
432
+ const steps: PurgeStep[] = [];
433
+ wiring.purgeSteps = steps;
434
+ let composition: readonly Capability[] = [];
402
435
 
403
436
  // Tier-1 edge rate limiter, contributed as middleware so it runs before session resolution.
404
437
  const rateLimitMiddleware: PithyMiddleware = (app) => {
@@ -457,6 +490,11 @@ export function auth(options: AuthOptions): AuthCapability {
457
490
  migrations: { ...AUTH_MIGRATIONS, ...pluginPlan.migrations },
458
491
  },
459
492
  },
493
+ // What erasing a person means for the `pithy_auth_*` tables, and what exporting them hands back (#622).
494
+ purge: [authPurgeContribution(resolved.database, pluginPlan.userTables)],
495
+ // The purge of one account, and the daily pass that starts every due one. Both hosted by the adopter's own
496
+ // Worker, because a purge runs every composed capability's contribution — see `purge/specs.ts`.
497
+ workflows: authWorkflows,
460
498
  compose: ({ capabilities }) => {
461
499
  const email = capabilities.find(isEmailCapability);
462
500
  if (!email) {
@@ -478,6 +516,9 @@ export function auth(options: AuthOptions): AuthCapability {
478
516
  // Refused at boot, naming both sides: the alternative is a `create table` that fails halfway
479
517
  // through `pithy migrate`, or two capabilities quietly reading and writing one table.
480
518
  assertPluginTablesUnclaimed(capabilities, resolved.database, pluginPlan.extensions);
519
+ // Every composed capability's purge step, auth's own among them, for the export route and the purge (#622).
520
+ steps.splice(0, steps.length, ...purgeSteps(capabilities, "user"));
521
+ composition = capabilities;
481
522
  },
482
523
  /**
483
524
  * The client-safe projection — what a sign-in screen needs and nothing more: where to call
@@ -541,7 +582,13 @@ export function auth(options: AuthOptions): AuthCapability {
541
582
  seeds: [authExampleSeed, authDevSessionSeed],
542
583
  });
543
584
 
544
- return Object.assign(capability, { authConfig: resolved, authPeer, lifecycleHooks });
585
+ return Object.assign(capability, {
586
+ authConfig: resolved,
587
+ authPeer,
588
+ lifecycleHooks,
589
+ purgeSteps: steps,
590
+ auditFor: (env: Record<string, unknown>) => composedAuditEmit(composition, env),
591
+ });
545
592
  }
546
593
 
547
594
  /** Type guard: is this capability the auth capability? */
@@ -1,7 +1,7 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
- import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
4
+ import { SQLiteBoolean, SQLiteDate } from "@pithy-sh/core/src/data/codecs";
5
5
  import { z } from "zod";
6
6
 
7
7
  /**
@@ -72,6 +72,9 @@ export const UserLifecycleEvent = z
72
72
  .describe(
73
73
  "For a `purge_step` row, the capability whose rows that step erased — the purge's step name. Null for every other action.",
74
74
  ),
75
+ notify: SQLiteBoolean.nullable().describe(
76
+ "For a hard deletion's `deleted` row, whether the purge sends the deletion-complete mail — false when the deletion asked for none. Null for every other row, and for a hard deletion that did not say. The purge reads it, so a purge the daily pass starts keeps the choice (#622).",
77
+ ),
75
78
  createdAt: SQLiteDate.describe("When the transition happened. Ms-epoch in SQLite; a `Date` in app code."),
76
79
  })
77
80
  .describe(