@pithy-sh/auth 0.9.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 (188) hide show
  1. package/README.md +8 -2
  2. package/dist/admin/users.js +1 -1
  3. package/dist/audit/actions.d.ts +40 -0
  4. package/dist/audit/actions.d.ts.map +1 -1
  5. package/dist/audit/actions.js +41 -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 +2 -2
  9. package/dist/capability.d.ts +45 -1
  10. package/dist/capability.d.ts.map +1 -1
  11. package/dist/capability.js +40 -5
  12. package/dist/client/lifecycle.d.ts +19 -0
  13. package/dist/client/lifecycle.d.ts.map +1 -0
  14. package/dist/client/lifecycle.js +25 -0
  15. package/dist/client/projection.d.ts +4 -0
  16. package/dist/client/projection.d.ts.map +1 -1
  17. package/dist/data/betterAuth.d.ts +4 -0
  18. package/dist/data/betterAuth.d.ts.map +1 -1
  19. package/dist/data/betterAuth.js +6 -2
  20. package/dist/data/kitFields.d.ts +20 -25
  21. package/dist/data/kitFields.d.ts.map +1 -1
  22. package/dist/data/kitFields.js +28 -32
  23. package/dist/data/tables.d.ts +29 -2
  24. package/dist/data/tables.d.ts.map +1 -1
  25. package/dist/data/tables.js +5 -3
  26. package/dist/data/userLifecycle.d.ts +62 -0
  27. package/dist/data/userLifecycle.d.ts.map +1 -0
  28. package/dist/data/userLifecycle.js +51 -0
  29. package/dist/http/adminRoutes.d.ts.map +1 -1
  30. package/dist/http/adminRoutes.js +270 -5
  31. package/dist/http/guards.d.ts +24 -1
  32. package/dist/http/guards.d.ts.map +1 -1
  33. package/dist/http/guards.js +59 -3
  34. package/dist/http/lifecycleGate.d.ts +18 -0
  35. package/dist/http/lifecycleGate.d.ts.map +1 -0
  36. package/dist/http/lifecycleGate.js +75 -0
  37. package/dist/http/middleware.d.ts +30 -1
  38. package/dist/http/middleware.d.ts.map +1 -1
  39. package/dist/http/middleware.js +89 -7
  40. package/dist/http/providerRefusal.d.ts.map +1 -1
  41. package/dist/http/providerRefusal.js +8 -0
  42. package/dist/http/resolve.d.ts.map +1 -1
  43. package/dist/http/resolve.js +7 -4
  44. package/dist/http/responses.d.ts +180 -0
  45. package/dist/http/responses.d.ts.map +1 -1
  46. package/dist/http/responses.js +142 -1
  47. package/dist/http/routes.d.ts +1 -0
  48. package/dist/http/routes.d.ts.map +1 -1
  49. package/dist/http/routes.js +65 -4
  50. package/dist/http/schemas.d.ts +57 -0
  51. package/dist/http/schemas.d.ts.map +1 -1
  52. package/dist/http/schemas.js +51 -1
  53. package/dist/http/views.d.ts +39 -2
  54. package/dist/http/views.d.ts.map +1 -1
  55. package/dist/http/views.js +105 -1
  56. package/dist/instance/auth.d.ts +55 -3
  57. package/dist/instance/auth.d.ts.map +1 -1
  58. package/dist/instance/auth.js +53 -2
  59. package/dist/instance/microsoftEmail.d.ts +70 -0
  60. package/dist/instance/microsoftEmail.d.ts.map +1 -0
  61. package/dist/instance/microsoftEmail.js +96 -0
  62. package/dist/instance/providerSignInGate.d.ts +7 -6
  63. package/dist/instance/providerSignInGate.d.ts.map +1 -1
  64. package/dist/instance/providerSignInGate.js +7 -6
  65. package/dist/instance/providers.d.ts +7 -5
  66. package/dist/instance/providers.d.ts.map +1 -1
  67. package/dist/instance/providers.js +5 -3
  68. package/dist/instance/secrets.d.ts +64 -3
  69. package/dist/instance/secrets.d.ts.map +1 -1
  70. package/dist/instance/secrets.js +44 -5
  71. package/dist/lifecycle/audited.d.ts +48 -0
  72. package/dist/lifecycle/audited.d.ts.map +1 -0
  73. package/dist/lifecycle/audited.js +65 -0
  74. package/dist/lifecycle/enforce.d.ts +75 -0
  75. package/dist/lifecycle/enforce.d.ts.map +1 -0
  76. package/dist/lifecycle/enforce.js +111 -0
  77. package/dist/lifecycle/hooks.d.ts +53 -0
  78. package/dist/lifecycle/hooks.d.ts.map +1 -0
  79. package/dist/lifecycle/hooks.js +2 -0
  80. package/dist/lifecycle/reason.d.ts +11 -0
  81. package/dist/lifecycle/reason.d.ts.map +1 -0
  82. package/dist/lifecycle/reason.js +13 -0
  83. package/dist/lifecycle/request.d.ts +18 -0
  84. package/dist/lifecycle/request.d.ts.map +1 -0
  85. package/dist/lifecycle/request.js +31 -0
  86. package/dist/lifecycle/state.d.ts +64 -0
  87. package/dist/lifecycle/state.d.ts.map +1 -0
  88. package/dist/lifecycle/state.js +90 -0
  89. package/dist/lifecycle/transitions.d.ts +272 -0
  90. package/dist/lifecycle/transitions.d.ts.map +1 -0
  91. package/dist/lifecycle/transitions.js +623 -0
  92. package/dist/migrations/0004_user_lifecycle.d.ts +28 -0
  93. package/dist/migrations/0004_user_lifecycle.d.ts.map +1 -0
  94. package/dist/migrations/0004_user_lifecycle.js +47 -0
  95. package/dist/migrations/0005_purge_once.d.ts +22 -0
  96. package/dist/migrations/0005_purge_once.d.ts.map +1 -0
  97. package/dist/migrations/0005_purge_once.js +35 -0
  98. package/dist/migrations/pluginTables.d.ts +8 -0
  99. package/dist/migrations/pluginTables.d.ts.map +1 -1
  100. package/dist/migrations/pluginTables.js +8 -1
  101. package/dist/migrations/set.d.ts +3 -1
  102. package/dist/migrations/set.d.ts.map +1 -1
  103. package/dist/migrations/set.js +6 -2
  104. package/dist/peer.d.ts +4 -0
  105. package/dist/peer.d.ts.map +1 -1
  106. package/dist/purge/contribution.d.ts +47 -0
  107. package/dist/purge/contribution.d.ts.map +1 -0
  108. package/dist/purge/contribution.js +141 -0
  109. package/dist/purge/retryPolicy.d.ts +22 -0
  110. package/dist/purge/retryPolicy.d.ts.map +1 -0
  111. package/dist/purge/retryPolicy.js +26 -0
  112. package/dist/purge/run.d.ts +88 -0
  113. package/dist/purge/run.d.ts.map +1 -0
  114. package/dist/purge/run.js +102 -0
  115. package/dist/purge/specs.d.ts +71 -0
  116. package/dist/purge/specs.d.ts.map +1 -0
  117. package/dist/purge/specs.js +72 -0
  118. package/dist/purge/start.d.ts +42 -0
  119. package/dist/purge/start.d.ts.map +1 -0
  120. package/dist/purge/start.js +37 -0
  121. package/dist/purge/workflow.d.ts +58 -0
  122. package/dist/purge/workflow.d.ts.map +1 -0
  123. package/dist/purge/workflow.js +96 -0
  124. package/dist/test-utils/accountFootprint.d.ts +10 -0
  125. package/dist/test-utils/accountFootprint.d.ts.map +1 -0
  126. package/dist/test-utils/accountFootprint.js +44 -0
  127. package/dist/test-utils/liveApp.d.ts +21 -0
  128. package/dist/test-utils/liveApp.d.ts.map +1 -1
  129. package/dist/test-utils/liveApp.js +1 -0
  130. package/dist/test-utils/scopedBackend.d.ts +21 -0
  131. package/dist/test-utils/scopedBackend.d.ts.map +1 -1
  132. package/dist/test-utils/scopedBackend.js +7 -1
  133. package/dist/version.generated.d.ts +1 -1
  134. package/dist/version.generated.d.ts.map +1 -1
  135. package/dist/version.generated.js +1 -1
  136. package/docs/account-lifecycle.md +217 -0
  137. package/docs/apple-signin.md +7 -1
  138. package/docs/facebook-oauth.md +7 -1
  139. package/docs/github-oauth.md +7 -1
  140. package/docs/google-oauth.md +7 -1
  141. package/docs/microsoft-oauth.md +177 -0
  142. package/package.json +5 -5
  143. package/pithy.manifest.json +17 -3
  144. package/src/audit/actions.ts +42 -0
  145. package/src/audit/emit.ts +4 -2
  146. package/src/capability.ts +170 -52
  147. package/src/client/lifecycle.ts +27 -0
  148. package/src/client/projection.ts +4 -0
  149. package/src/data/betterAuth.ts +21 -1
  150. package/src/data/kitFields.ts +27 -0
  151. package/src/data/tables.ts +4 -2
  152. package/src/data/userLifecycle.ts +83 -0
  153. package/src/http/adminRoutes.ts +398 -2
  154. package/src/http/guards.ts +61 -1
  155. package/src/http/lifecycleGate.ts +78 -0
  156. package/src/http/middleware.ts +104 -2
  157. package/src/http/providerRefusal.ts +10 -0
  158. package/src/http/resolve.ts +8 -3
  159. package/src/http/responses.ts +245 -0
  160. package/src/http/routes.ts +93 -4
  161. package/src/http/schemas.ts +110 -0
  162. package/src/http/views.ts +147 -2
  163. package/src/instance/auth.ts +74 -2
  164. package/src/instance/microsoftEmail.ts +111 -0
  165. package/src/instance/providerSignInGate.ts +7 -6
  166. package/src/instance/providers.ts +8 -4
  167. package/src/instance/secrets.ts +59 -5
  168. package/src/lifecycle/audited.ts +104 -0
  169. package/src/lifecycle/enforce.ts +139 -0
  170. package/src/lifecycle/hooks.ts +54 -0
  171. package/src/lifecycle/reason.ts +11 -0
  172. package/src/lifecycle/request.ts +39 -0
  173. package/src/lifecycle/state.ts +101 -0
  174. package/src/lifecycle/transitions.ts +872 -0
  175. package/src/migrations/0004_user_lifecycle.ts +68 -0
  176. package/src/migrations/0005_purge_once.ts +42 -0
  177. package/src/migrations/pluginTables.ts +19 -1
  178. package/src/migrations/set.ts +5 -1
  179. package/src/purge/contribution.ts +191 -0
  180. package/src/purge/retryPolicy.ts +26 -0
  181. package/src/purge/run.ts +185 -0
  182. package/src/purge/specs.ts +95 -0
  183. package/src/purge/start.ts +79 -0
  184. package/src/purge/workflow.ts +144 -0
  185. package/src/test-utils/accountFootprint.ts +95 -0
  186. package/src/test-utils/liveApp.ts +2 -1
  187. package/src/test-utils/scopedBackend.ts +2 -1
  188. package/src/version.generated.ts +1 -1
@@ -119,6 +119,138 @@ const AdminDeviceRevokeResponse = z.object({
119
119
  revoked: RevokedCount,
120
120
  removed: z.boolean().describe("Whether a device row was deleted. False when the user had no such device.")
121
121
  }).describe("How many sessions the device revocation ended, and whether the registry row went with them.");
122
+ /**
123
+ * `POST {base}/admin/users/:userId/suspend` (#621).
124
+ *
125
+ * The suspension the account is now under, how many sessions ended with it, and whether the person was told.
126
+ * Not the reason: the caller wrote it, the trail keeps it, and echoing it back would put it in one more place
127
+ * a dashboard logs.
128
+ */
129
+ const AdminUserSuspendResponse = z.object({
130
+ userId: z.string().describe("The account suspended, as `pithy_auth_users.id` stores it."),
131
+ state: z.literal("suspended").describe("Where the account stands now. Every sign-in and refresh is refused."),
132
+ outcome: z.enum(["suspended", "updated"]).describe("`suspended` when this call suspended an account in good standing; `updated` when it was already suspended and this call restated the reason and the end."),
133
+ suspendedAt: z.iso.datetime().describe("When the suspension in force began, ISO-8601. A restatement keeps the original start."),
134
+ suspendedUntil: z.iso.datetime().nullable().describe("When it ends by itself, ISO-8601, with nothing written to end it. Null lasts until a reinstatement."),
135
+ sessionsRevoked: RevokedCount,
136
+ mailed: z.boolean().describe("Whether the account-suspended mail was enqueued. False for `notify: false`, when the config turns it off, or when no email capability is composed.")
137
+ }).describe("A suspended account: since when, until when, how many sessions it cost, and whether the person was told.");
138
+ /**
139
+ * `POST {base}/admin/users/:userId/reinstate` (#621).
140
+ *
141
+ * No session count: a reinstatement restores none. The person signs in again.
142
+ */
143
+ const AdminUserReinstateResponse = z.object({
144
+ userId: z.string().describe("The account reinstated, as `pithy_auth_users.id` stores it."),
145
+ state: z.literal("active").describe("Where the account stands now. It can sign in again."),
146
+ outcome: z.enum(["reinstated", "unchanged"]).describe("`reinstated` when this call lifted a suspension; `unchanged` when there was none in force — never suspended, or past its end — and nothing was written."),
147
+ mailed: z.boolean().describe("Whether the account-reinstated mail was enqueued. Always false for `unchanged`, and on the same rule as a suspension's otherwise.")
148
+ }).describe("A reinstated account, and whether the person was told. Its revoked sessions stay revoked.");
149
+ /** When the purge may erase a deleted account, ISO-8601. */
150
+ const PurgeAfter = z.iso.datetime().describe("When the purge may erase the account, ISO-8601. It can be restored until then; a hard deletion's is the moment it was deleted.");
151
+ /**
152
+ * `DELETE {base}/admin/users/:userId` (#622).
153
+ *
154
+ * What the deletion left in force, how many sessions ended with it, whether the person was told, and what
155
+ * became of the purge. Not the reason: the caller wrote it and the trail keeps it.
156
+ */
157
+ const AdminUserDeleteResponse = z.object({
158
+ userId: z.string().describe("The account deleted, as `pithy_auth_users.id` stores it."),
159
+ state: z.literal("deleted").describe("Where the account stands now. Every sign-in and refresh is refused."),
160
+ mode: z.enum(["soft", "hard"]).describe("The mode this call ran in — `soft` unless the caller named `hard`."),
161
+ outcome: z.enum([
162
+ "deleted",
163
+ "brought_forward",
164
+ "unchanged"
165
+ ]).describe("`deleted` when this call deleted an account in good standing; `brought_forward` when a hard deletion moved an already-deleted account's purge to now; `unchanged` when it was already deleted and there was nothing to move."),
166
+ deletedAt: z.iso.datetime().describe("When the account was deleted, ISO-8601. Kept by a deletion brought forward."),
167
+ purgeAfter: PurgeAfter,
168
+ purge: z.enum([
169
+ "scheduled",
170
+ "started",
171
+ "pending"
172
+ ]).describe("`scheduled`: the daily purge erases it once `purgeAfter` passes. `started`: the purge Workflow was started by this call. `pending`: the purge is due and this Worker binds no purge Workflow to start, so it runs once one is bound."),
173
+ sessionsRevoked: RevokedCount,
174
+ mailed: z.boolean().describe("Whether the deletion-scheduled mail was enqueued. Always false for `hard`, whose mail the purge sends, for `notify: false`, and when the config turns it off.")
175
+ }).describe("A deleted account: when, until when it can be restored, what became of the purge, and its sessions.");
176
+ /**
177
+ * `POST {base}/admin/users/:userId/restore` (#622). No session count: a restoration restores none.
178
+ */
179
+ const AdminUserRestoreResponse = z.object({
180
+ userId: z.string().describe("The account restored, as `pithy_auth_users.id` stores it."),
181
+ state: z.enum(["active", "suspended"]).describe("Where the account stands now: `active`, or `suspended` when a suspension it was under before the deletion is still in force."),
182
+ outcome: z.enum(["restored", "unchanged"]).describe("`restored` when this call restored a deleted account; `unchanged` when it was not deleted.")
183
+ }).describe("A restored account, inside its purge window. Its revoked sessions stay revoked.");
184
+ /** One provider link an account holds, as an export carries it — no provider token. */
185
+ const AuthExportProvider = z.object({
186
+ providerId: z.string().describe("The sign-in provider's slug — `google`, `apple`, `github`."),
187
+ createdAt: z.iso.datetime().describe("When the provider was linked, ISO-8601.")
188
+ }).describe("One sign-in provider linked to the account. The provider's tokens are credentials and are not here.");
189
+ /** One transition in an account's history, as an export carries it — not who made it. */
190
+ const AuthExportTransition = z.object({
191
+ action: z.string().describe("What happened: `suspended`, `reinstated`, `deleted`, `restored`, `purge_step`, `purged`."),
192
+ actorType: z.string().describe("Who made it: `control-plane`, `user` (the account's holder), or `system`."),
193
+ reason: z.string().nullable().describe("The reason given, in the words of whoever made the transition, or null."),
194
+ suspendedUntil: z.iso.datetime().nullable().describe("For a suspension, when it ends by itself, ISO-8601."),
195
+ createdAt: z.iso.datetime().describe("When it happened, ISO-8601.")
196
+ }).describe("One transition in the account's history. The operator's identity is theirs, not the person's, so it is not here.");
197
+ /**
198
+ * What `@pithy-sh/auth` holds about one account, as its purge contribution exports it (#622) — the `data` of
199
+ * the `auth` entry in an export.
200
+ *
201
+ * The person's own data and none of their credentials: no session token, no provider token, no push token.
202
+ * Every list is whole, because an export that stopped at a bound would answer an access request with part of
203
+ * an answer.
204
+ */
205
+ const AuthUserExport = z.object({
206
+ user: AdminUserView.extend({
207
+ suspendedAt: z.iso.datetime().nullable().describe("When a suspension in force began, ISO-8601, or null."),
208
+ suspendedUntil: z.iso.datetime().nullable().describe("When that suspension ends by itself, ISO-8601, or null."),
209
+ deletedAt: z.iso.datetime().nullable().describe("When the account was deleted, ISO-8601, or null."),
210
+ purgeAfter: z.iso.datetime().nullable().describe("When the purge may erase it, ISO-8601, or null.")
211
+ }).describe("The account itself, with where it stands."),
212
+ sessions: z.array(AdminSessionView).describe("Every live session, newest first. Without the tokens."),
213
+ providers: z.array(AuthExportProvider).describe("Every linked sign-in provider."),
214
+ devices: z.array(AdminDeviceView).describe("Every registered device, most recently seen first. Without push tokens."),
215
+ history: z.array(AuthExportTransition).describe("Every lifecycle transition, oldest first."),
216
+ plugins: z.record(z.string(), z.array(z.record(z.string(), z.unknown()))).describe("The account's rows in each table a composed Better Auth plugin created keyed by `userId` — two-factor, passkeys, API keys — keyed by table. Without a column that holds a credential. Empty when no such plugin is composed.")
217
+ }).describe("Everything `@pithy-sh/auth` holds about one account, without a credential.");
218
+ /** Fields every capability's export entry carries. */
219
+ const exportEntry = {
220
+ capability: z.string().describe("The capability whose rows these are — the purge step that erases them."),
221
+ summary: z.string().describe("What that capability's purge erases or anonymizes, in its own sentence.")
222
+ };
223
+ /** One capability's part of an export. */
224
+ const AdminUserExportEntry = z.discriminatedUnion("state", [
225
+ z.object({
226
+ ...exportEntry,
227
+ state: z.literal("exported").describe("The capability answered."),
228
+ data: z.record(z.string(), z.unknown()).describe("What it holds about the account, in the shape that capability exports. `auth`'s is `AuthUserExport`.")
229
+ }).describe("A capability's rows about the account."),
230
+ z.object({
231
+ ...exportEntry,
232
+ state: z.literal("not_exported").describe("The capability erases rows about the account and does not say how to export them.")
233
+ }).describe("A capability that holds rows it does not export. Ask its owner."),
234
+ z.object({
235
+ ...exportEntry,
236
+ state: z.literal("unavailable").describe("The capability's rows could not be read on this request.")
237
+ }).describe("Nothing was established about this capability's rows. Deliberately empty — it is not 'none'.")
238
+ ]).describe("One capability's part of an export, behind a state, so an unread part cannot be taken for an empty one.");
239
+ /**
240
+ * `GET {base}/admin/users/:userId/export` (#622).
241
+ *
242
+ * Everything the kit holds about one account — the answer to an access request. One entry per composed
243
+ * capability that declares a purge contribution, in the order the purge runs them, each read on its own so
244
+ * one that will not read costs its own entry and not the document.
245
+ */
246
+ const AdminUserExportResponse = z.object({
247
+ subject: z.object({
248
+ type: z.literal("user").describe("The kind of subject: one person's account."),
249
+ id: z.string().describe("The account's id, as `pithy_auth_users.id` stores it.")
250
+ }).describe("Who this export is about."),
251
+ exportedAt: z.iso.datetime().describe("When the export was read, ISO-8601."),
252
+ capabilities: z.array(AdminUserExportEntry).describe("Every composed capability's part, in the order the purge erases them.")
253
+ }).describe("Everything the kit holds about one account, from every composed capability, as one document.");
122
254
  /** `POST {base}/token/rotate`. */
123
255
  const TokenRotateResponse = z.object({
124
256
  accessToken: z.string().describe("A fresh short-lived access token (a JWT) for the `Authorization: Bearer` header."),
@@ -143,5 +275,14 @@ const MyDeviceView = z.object({
143
275
  const MyDevicesResponse = z.object({ devices: z.array(MyDeviceView).describe("Every device registered to the caller, most recently seen first.") }).describe("The caller's own registered devices.");
144
276
  /** `POST {base}/devices/revoke`. */
145
277
  const MyDeviceRevokeResponse = z.object({ revoked: RevokedCount }).describe("How many of the device's sessions the revocation signed out. The device's row goes with them.");
278
+ /**
279
+ * `DELETE {base}/account` (#622) — the signed-in person deleted their own account. Always soft, on the
280
+ * configured window. Their sessions end with it, this one included.
281
+ */
282
+ const AccountDeleteResponse = z.object({
283
+ state: z.literal("deleted").describe("The account is deleted. This session and every other one has ended."),
284
+ purgeAfter: PurgeAfter,
285
+ mailed: z.boolean().describe("Whether the deletion-scheduled mail, with the purge date and how to ask for the account back, was sent.")
286
+ }).describe("The caller's own account, deleted: when its data will be erased, and whether they were mailed.");
146
287
  //#endregion
147
- export { AdminDeviceRevokeResponse, AdminDeviceView, AdminDevicesResponse, AdminRevokeResponse, AdminSessionView, AdminUserResponse, AdminUserView, AdminUsersResponse, MyDeviceRevokeResponse, MyDeviceView, MyDevicesResponse, TokenRotateResponse };
288
+ export { AccountDeleteResponse, AdminDeviceRevokeResponse, AdminDeviceView, AdminDevicesResponse, AdminRevokeResponse, AdminSessionView, AdminUserDeleteResponse, AdminUserExportResponse, AdminUserReinstateResponse, AdminUserResponse, AdminUserRestoreResponse, AdminUserSuspendResponse, AdminUserView, AdminUsersResponse, AuthUserExport, MyDeviceRevokeResponse, MyDeviceView, MyDevicesResponse, TokenRotateResponse };
@@ -19,6 +19,7 @@ import type { AuthWiring } from "../capability";
19
19
  * | `POST /token/rotate` | bearer/session | none — the credential only |
20
20
  * | `GET /devices` | bearer/session | none |
21
21
  * | `POST /devices/revoke` | bearer/session | json `RevokeDeviceBody` |
22
+ * | `DELETE /account` | bearer/session | json `DeleteAccountBody` |
22
23
  * | `* /admin/*` | control-plane | see `./adminRoutes` |
23
24
  *
24
25
  * The catch-all takes NO validator, deliberately: `handleBetterAuth` hands Better Auth `c.req.raw`,
@@ -1 +1 @@
1
- {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../src/http/routes.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAQ7E,OAAO,KAAK,EAAW,IAAI,EAAE,MAAM,MAAM,CAAC;AAE1C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAqChD;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,UAAU,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,YAAY,CAAC,KAAK,IAAI,CAuHtF"}
1
+ {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../src/http/routes.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAQ7E,OAAO,KAAK,EAAW,IAAI,EAAE,MAAM,MAAM,CAAC;AAG1C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AA2ChD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,UAAU,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,YAAY,CAAC,KAAK,IAAI,CA0ItF"}
@@ -4,16 +4,23 @@ import { authDatabase } from "../data/tables.js";
4
4
  import { correlation, emitDenied, emitDeviceRevoked, emitTokenRefresh, emitTokenReuseDetected } from "../audit/emit.js";
5
5
  import { deleteDevice, deviceSessionTokens, listDevices } from "../device/registry.js";
6
6
  import { requireFreshAuthentication } from "./providerFreshness.js";
7
+ import { isLifecycleRefusal } from "../lifecycle/state.js";
8
+ import { noticedRefusal } from "../lifecycle/enforce.js";
7
9
  import { PROFILE_IMAGE_PATH } from "../profile/profile.js";
8
10
  import { collapseProviderRefusal } from "./providerRefusal.js";
9
11
  import { getAuthInstance, resolveDb } from "./resolve.js";
10
- import { requireAuth } from "./middleware.js";
12
+ import { accountHolder, requireAccountHolder, requireAuth } from "./middleware.js";
13
+ import { userSessionTokens } from "../admin/users.js";
14
+ import { lifecycleDeps } from "../lifecycle/request.js";
15
+ import { deleteUser } from "../lifecycle/transitions.js";
11
16
  import { consumeSession, findConsumedToken, pruneConsumedTokens, recordConsumedToken, revokeFamily } from "../token/rotation.js";
12
- import { MyDeviceRevokeResponse, MyDevicesResponse, TokenRotateResponse } from "./responses.js";
13
- import { RevokeDeviceBody } from "./schemas.js";
17
+ import { AccountDeleteResponse, MyDeviceRevokeResponse, MyDevicesResponse, TokenRotateResponse } from "./responses.js";
18
+ import { DeleteAccountBody, RevokeDeviceBody } from "./schemas.js";
19
+ import { accountDeletionView } from "./views.js";
14
20
  import { registerAuthAdminRoutes } from "./adminRoutes.js";
15
21
  import { guardErrorCallbackURL } from "./errorCallbackUrl.js";
16
22
  import { apiErrorToPithy } from "./errors.js";
23
+ import { admitsRefusedAccount, lifecycleRedirect } from "./lifecycleGate.js";
17
24
  import { NotFoundError, UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
18
25
  import { TURNSTILE_LOGIN_ACTION } from "@pithy-sh/turnstile/src/config/config";
19
26
  import { describeRoute } from "@pithy-sh/core/src/http/routeSpec";
@@ -50,6 +57,7 @@ function db(c, wiring) {
50
57
  * | `POST /token/rotate` | bearer/session | none — the credential only |
51
58
  * | `GET /devices` | bearer/session | none |
52
59
  * | `POST /devices/revoke` | bearer/session | json `RevokeDeviceBody` |
60
+ * | `DELETE /account` | bearer/session | json `DeleteAccountBody` |
53
61
  * | `* /admin/*` | control-plane | see `./adminRoutes` |
54
62
  *
55
63
  * The catch-all takes NO validator, deliberately: `handleBetterAuth` hands Better Auth `c.req.raw`,
@@ -91,6 +99,12 @@ function createAuthRoutes(wiring) {
91
99
  verification: ["bearer", "session"],
92
100
  responses: { 200: MyDeviceRevokeResponse }
93
101
  }), requireAuth(), csrf, validate("json", RevokeDeviceBody), (c) => revokeMyDevice(c, wiring, c.req.valid("json")));
102
+ app.delete(`${base}/account`, describeRoute({
103
+ summary: "Delete the caller's own account. Always soft: restorable until the purge window closes.",
104
+ description: "What the App Store and Google Play require of an app with accounts. A suspended account may still delete itself, with the session a sign-in carrying `x-pithy-intent: delete-account` gets it; a deleted one is refused with `auth/account_deleted`. Every session ends, this one included. The body must carry `confirm: true`.",
105
+ verification: ["bearer", "session"],
106
+ responses: { 200: AccountDeleteResponse }
107
+ }), requireAccountHolder(), csrf, validate("json", DeleteAccountBody), (c) => deleteMyAccount(c, wiring));
94
108
  app.post(`${base}/link-social`, describeRoute({
95
109
  summary: "Connect another sign-in provider to the caller's account.",
96
110
  description: "Better Auth's endpoint, behind a kit gate: the caller must have signed in within the last fifteen minutes, or it is refused with `auth/session_not_fresh`.",
@@ -197,12 +211,26 @@ async function auditRefusal(c, response) {
197
211
  */
198
212
  async function handleBetterAuth(c, wiring) {
199
213
  const instance = await getAuthInstance(c, wiring);
214
+ const pathname = new URL(c.req.raw.url).pathname;
215
+ const refusal = noticedRefusal(c);
216
+ if (refusal && !admitsRefusedAccount(pathname.slice(wiring.config.basePath.length))) throw refusal;
200
217
  const request = await guardErrorCallbackURL(c.req.raw, c.req.raw.url);
201
218
  let response;
202
219
  try {
203
220
  response = await instance.handler(request);
204
221
  } catch (error) {
205
- throw apiErrorToPithy(error);
222
+ const pithy = apiErrorToPithy(error);
223
+ if (isLifecycleRefusal(pithy)) {
224
+ if (isSignInAttempt(pathname)) await emitDenied(c.var.emit, {
225
+ ...correlation(c.req.raw.headers),
226
+ detail: pithy.payload.code
227
+ });
228
+ if (c.req.method === "GET" && pathname === `${wiring.config.basePath}/magic-link/verify`) {
229
+ const redirect = lifecycleRedirect(new URL(request.url), wiring.config.baseURL, wiring.config.trustedOrigins, pithy);
230
+ if (redirect) return redirect;
231
+ }
232
+ }
233
+ throw pithy;
206
234
  }
207
235
  const collapsed = collapseProviderRefusal(c.req.raw.url, response);
208
236
  if (collapsed) {
@@ -272,6 +300,8 @@ async function rotateToken(c, wiring) {
272
300
  action: "Present a valid session or bearer token to rotate."
273
301
  });
274
302
  }
303
+ const refusal = noticedRefusal(c);
304
+ if (refusal) throw refusal;
275
305
  const ip = headers.get("cf-connecting-ip") ?? void 0;
276
306
  const userAgent = headers.get("user-agent") ?? void 0;
277
307
  const session = current.session;
@@ -320,6 +350,37 @@ async function listMyDevices(c, wiring) {
320
350
  if (!userId) throw new UnauthorizedError({ message: "Authentication required." });
321
351
  return c.json({ devices: await listDevices(db(c, wiring), userId) });
322
352
  }
353
+ /**
354
+ * Delete the caller's own account (#622): soft, on the configured window, audited as `auth/user_self_deleted`
355
+ * with them as the actor, and every session they hold ended after the columns are written — through Better
356
+ * Auth's adapter, so `onSessionRevoked` hears each. No reason: a person leaving owes nobody one.
357
+ */
358
+ async function deleteMyAccount(c, wiring) {
359
+ const holder = accountHolder(c);
360
+ if (!holder) throw new UnauthorizedError({ message: "Authentication required." });
361
+ const { ip, userAgent } = correlation(c.req.raw.headers);
362
+ const deps = lifecycleDeps(c, wiring, {
363
+ ip,
364
+ userAgent,
365
+ requestId: c.req.header("cf-ray"),
366
+ metadata: {
367
+ sessionId: holder.sessionId,
368
+ suspended: holder.suspended
369
+ }
370
+ });
371
+ const result = await deleteUser(deps, {
372
+ userId: holder.userId,
373
+ actor: {
374
+ type: "user",
375
+ id: holder.userId
376
+ },
377
+ reason: null
378
+ });
379
+ const tokens = await userSessionTokens(db(c, wiring), holder.userId);
380
+ const ctx = await (await getAuthInstance(c, wiring)).$context;
381
+ for (const token of tokens) await ctx.internalAdapter.deleteSession(token);
382
+ return c.json(accountDeletionView(result));
383
+ }
323
384
  /** Revoke one of the authenticated user's devices: sign out its sessions, then drop the device row. */
324
385
  async function revokeMyDevice(c, wiring, body) {
325
386
  const userId = c.var.auth?.userId;
@@ -65,4 +65,61 @@ export declare const RevokeSessionBody: z.ZodObject<{
65
65
  sessionId: z.ZodString;
66
66
  }, z.core.$strip>;
67
67
  export type RevokeSessionBody = z.output<typeof RevokeSessionBody>;
68
+ /** The body of `POST /admin/users/:userId/suspend`. */
69
+ export declare const SuspendUserBody: z.ZodObject<{
70
+ reason: z.ZodString;
71
+ until: z.ZodOptional<z.ZodCodec<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodDate]>, z.ZodDate>>;
72
+ notify: z.ZodOptional<z.ZodBoolean>;
73
+ }, z.core.$strip>;
74
+ export type SuspendUserBody = z.output<typeof SuspendUserBody>;
75
+ /** The body of `POST /admin/users/:userId/reinstate`. */
76
+ export declare const ReinstateUserBody: z.ZodObject<{
77
+ reason: z.ZodString;
78
+ notify: z.ZodOptional<z.ZodBoolean>;
79
+ }, z.core.$strip>;
80
+ export type ReinstateUserBody = z.output<typeof ReinstateUserBody>;
81
+ /**
82
+ * How a deletion runs (#622). `soft` is the default and the only thing an omission reaches: the account is shut
83
+ * now and erased once the window closes, restorable until then. `hard` starts the purge at once, with no
84
+ * window, and is reached only by naming it — a typo is a 400, never either mode.
85
+ */
86
+ export declare const DeletionMode: z.ZodEnum<{
87
+ hard: "hard";
88
+ soft: "soft";
89
+ }>;
90
+ export type DeletionMode = z.output<typeof DeletionMode>;
91
+ /** The body of `DELETE /admin/users/:userId`. */
92
+ export declare const DeleteUserBody: z.ZodObject<{
93
+ mode: z.ZodDefault<z.ZodEnum<{
94
+ hard: "hard";
95
+ soft: "soft";
96
+ }>>;
97
+ reason: z.ZodString;
98
+ notify: z.ZodOptional<z.ZodBoolean>;
99
+ }, z.core.$strip>;
100
+ export type DeleteUserBody = z.output<typeof DeleteUserBody>;
101
+ /** The body of `POST /admin/users/:userId/restore`. */
102
+ export declare const RestoreUserBody: z.ZodObject<{
103
+ reason: z.ZodString;
104
+ }, z.core.$strip>;
105
+ export type RestoreUserBody = z.output<typeof RestoreUserBody>;
106
+ /**
107
+ * The query of `GET /admin/users/:userId/export`. A disclosure of everything the kit holds about one person
108
+ * says why, like every lifecycle call: the reason goes on the trail beside who asked.
109
+ */
110
+ export declare const ExportUserQuery: z.ZodObject<{
111
+ reason: z.ZodString;
112
+ }, z.core.$strip>;
113
+ export type ExportUserQuery = z.output<typeof ExportUserQuery>;
114
+ /**
115
+ * The body of `DELETE /account`, the signed-in person deleting their own account (#622).
116
+ *
117
+ * The confirmation is the literal `true`, so a client must say it on purpose: a stray `DELETE` with an empty
118
+ * body, or a form posting `"false"`, deletes nothing. There is no field naming an account — the subject is the
119
+ * session's own, always — and a key that tries is dropped.
120
+ */
121
+ export declare const DeleteAccountBody: z.ZodObject<{
122
+ confirm: z.ZodLiteral<true>;
123
+ }, z.core.$strip>;
124
+ export type DeleteAccountBody = z.output<typeof DeleteAccountBody>;
68
125
  //# sourceMappingURL=schemas.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"schemas.d.ts","sourceRoot":"","sources":["../../src/http/schemas.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB;;;;;;;;;;;GAWG;AAEH;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB;;iBAQ2E,CAAC;AACzG,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,gBAAgB,CAAC,CAAC;AAEjE;;;;;;GAMG;AACH,eAAO,MAAM,WAAW;;iBAIoD,CAAC;AAC7E,MAAM,MAAM,WAAW,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,WAAW,CAAC,CAAC;AAkBvD,8BAA8B;AAC9B,eAAO,MAAM,cAAc;;;;iBAawE,CAAC;AACpG,MAAM,MAAM,cAAc,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,cAAc,CAAC,CAAC;AAE7D,yCAAyC;AACzC,eAAO,MAAM,gBAAgB;;;;;;;;;iBAYwE,CAAC;AACtG,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,gBAAgB,CAAC,CAAC;AAEjE;;;;;;;GAOG;AACH,eAAO,MAAM,iBAAiB;;iBAQqC,CAAC;AACpE,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,iBAAiB,CAAC,CAAC"}
1
+ {"version":3,"file":"schemas.d.ts","sourceRoot":"","sources":["../../src/http/schemas.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAIxB;;;;;;;;;;;GAWG;AAEH;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB;;iBAQ2E,CAAC;AACzG,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,gBAAgB,CAAC,CAAC;AAEjE;;;;;;GAMG;AACH,eAAO,MAAM,WAAW;;iBAIoD,CAAC;AAC7E,MAAM,MAAM,WAAW,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,WAAW,CAAC,CAAC;AAkBvD,8BAA8B;AAC9B,eAAO,MAAM,cAAc;;;;iBAawE,CAAC;AACpG,MAAM,MAAM,cAAc,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,cAAc,CAAC,CAAC;AAE7D,yCAAyC;AACzC,eAAO,MAAM,gBAAgB;;;;;;;;;iBAYwE,CAAC;AACtG,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,gBAAgB,CAAC,CAAC;AAEjE;;;;;;;GAOG;AACH,eAAO,MAAM,iBAAiB;;iBAQqC,CAAC;AACpE,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,iBAAiB,CAAC,CAAC;AA0BnE,uDAAuD;AACvD,eAAO,MAAM,eAAe;;;;iBAUzB,CAAC;AACJ,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,eAAe,CAAC,CAAC;AAE/D,yDAAyD;AACzD,eAAO,MAAM,iBAAiB;;;iBAE8D,CAAC;AAC7F,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,iBAAiB,CAAC,CAAC;AAEnE;;;;GAIG;AACH,eAAO,MAAM,YAAY;;;EAItB,CAAC;AACJ,MAAM,MAAM,YAAY,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,YAAY,CAAC,CAAC;AAEzD,iDAAiD;AACjD,eAAO,MAAM,cAAc;;;;;;;iBAakD,CAAC;AAC9E,MAAM,MAAM,cAAc,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,cAAc,CAAC,CAAC;AAE7D,uDAAuD;AACvD,eAAO,MAAM,eAAe;;iBAEiF,CAAC;AAC9G,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,eAAe,CAAC,CAAC;AAE/D;;;GAGG;AACH,eAAO,MAAM,eAAe;;iBAMmB,CAAC;AAChD,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,eAAe,CAAC,CAAC;AAE/D;;;;;;GAMG;AACH,eAAO,MAAM,iBAAiB;;iBAM+E,CAAC;AAC9G,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,iBAAiB,CAAC,CAAC"}
@@ -1,7 +1,9 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
  import { DevicePlatform } from "../data/device.js";
4
+ import "../lifecycle/reason.js";
4
5
  import { z } from "zod";
6
+ import { JsonDate } from "@pithy-sh/core/src/data/codecs";
5
7
  import { MAX_PAGE_SIZE } from "@pithy-sh/core/src/data/cursor";
6
8
  //#region src/http/schemas.ts
7
9
  /**
@@ -57,5 +59,53 @@ const ListDevicesQuery = z.object({
57
59
  * the read routes project.
58
60
  */
59
61
  const RevokeSessionBody = z.object({ sessionId: z.string().min(1).max(255).describe("The session's id, as the admin read routes report it. Not the session token.") }).describe("The body identifying which single session to revoke.");
62
+ /**
63
+ * Why an account's access is changing — required on both lifecycle routes (#621).
64
+ *
65
+ * Trimmed, then bounded by the same constant the transition enforces, so a reason the transition would refuse
66
+ * is a 400 here rather than a conflict later. Required rather than defaulted: a suspension nobody explained is
67
+ * a lockout the person cannot answer, and the trail would record nothing about why.
68
+ */
69
+ const LifecycleReason = z.string().trim().min(1).max(500).describe("Why, in a sentence written for the person. A suspension's reason is what every refused sign-in shows them.");
70
+ /** Whether the person is mailed. */
71
+ const Notify = z.boolean().optional().describe("Whether to mail the person. Absent is true. The config can turn a lifecycle mail off for every call; this turns it off for one.");
72
+ /** The body of `POST /admin/users/:userId/suspend`. */
73
+ const SuspendUserBody = z.object({
74
+ reason: LifecycleReason,
75
+ until: JsonDate.optional().describe("When the suspension ends by itself, as an ISO-8601 timestamp. Must be in the future. Absent lasts until a reinstatement. Nothing is written when it passes."),
76
+ notify: Notify
77
+ }).describe("A suspension: why, until when, and whether to tell the person. Suspending a suspended account restates the reason and the end.");
78
+ /** The body of `POST /admin/users/:userId/reinstate`. */
79
+ const ReinstateUserBody = z.object({
80
+ reason: LifecycleReason,
81
+ notify: Notify
82
+ }).describe("A reinstatement: why, and whether to tell the person. It restores no session.");
83
+ /**
84
+ * How a deletion runs (#622). `soft` is the default and the only thing an omission reaches: the account is shut
85
+ * now and erased once the window closes, restorable until then. `hard` starts the purge at once, with no
86
+ * window, and is reached only by naming it — a typo is a 400, never either mode.
87
+ */
88
+ const DeletionMode = z.enum(["soft", "hard"]).describe("`soft` (the default): the account is shut now and its data erased once `retention.purgeAfterDays` have passed; it can be restored until then. `hard`: the purge starts now, with no window and nothing to restore.");
89
+ /** The body of `DELETE /admin/users/:userId`. */
90
+ const DeleteUserBody = z.object({
91
+ mode: DeletionMode.default("soft").describe("`soft` unless named: the window, then the purge. `hard` purges now. Anything else is refused."),
92
+ reason: LifecycleReason,
93
+ notify: z.boolean().optional().describe("Whether to mail the person. Absent is true. It silences the mail this call sends: the deletion-scheduled notice for `soft`, the deletion-complete notice for `hard`.")
94
+ }).describe("A deletion: soft or hard, why, and whether to tell the person.");
95
+ /** The body of `POST /admin/users/:userId/restore`. */
96
+ const RestoreUserBody = z.object({ reason: LifecycleReason }).describe("A restoration inside the purge window: why. It restores no session; the person signs in again.");
97
+ /**
98
+ * The query of `GET /admin/users/:userId/export`. A disclosure of everything the kit holds about one person
99
+ * says why, like every lifecycle call: the reason goes on the trail beside who asked.
100
+ */
101
+ const ExportUserQuery = z.object({ reason: LifecycleReason.describe("Why this person's data is being exported — the access request it answers. Recorded on the audit trail.") }).describe("An export: why it is being made.");
102
+ /**
103
+ * The body of `DELETE /account`, the signed-in person deleting their own account (#622).
104
+ *
105
+ * The confirmation is the literal `true`, so a client must say it on purpose: a stray `DELETE` with an empty
106
+ * body, or a form posting `"false"`, deletes nothing. There is no field naming an account — the subject is the
107
+ * session's own, always — and a key that tries is dropped.
108
+ */
109
+ const DeleteAccountBody = z.object({ confirm: z.literal(true).describe("Must be `true`. The person confirmed, in your app, that they want their account deleted.") }).describe("A self-service deletion: the person's own confirmation. Always soft, on the configured window.");
60
110
  //#endregion
61
- export { ListDevicesQuery, ListUsersQuery, RevokeDeviceBody, RevokeSessionBody, UserIdParam };
111
+ export { DeleteAccountBody, DeleteUserBody, DeletionMode, ExportUserQuery, ListDevicesQuery, ListUsersQuery, ReinstateUserBody, RestoreUserBody, RevokeDeviceBody, RevokeSessionBody, SuspendUserBody, UserIdParam };
@@ -1,8 +1,11 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
- import type { Session, User } from "../data/betterAuth";
3
+ import type { PurgeExportEntry } from "@pithy-sh/core/src/capability/purge";
4
+ import type { Account, Session, User } from "../data/betterAuth";
4
5
  import type { Device } from "../data/device";
5
- import type { AdminDeviceView, AdminSessionView, AdminUserView } from "./responses";
6
+ import type { UserLifecycleEvent } from "../data/userLifecycle";
7
+ import type { DeleteTransition, DeletionMode, LifecycleTransition, RestoreTransition, SuspendTransition } from "../lifecycle/transitions";
8
+ import type { AccountDeleteResponse, AdminDeviceView, AdminSessionView, AdminUserDeleteResponse, AdminUserExportResponse, AdminUserReinstateResponse, AdminUserRestoreResponse, AdminUserSuspendResponse, AdminUserView, AuthUserExport } from "./responses";
6
9
  /**
7
10
  * The admin projections — what a management client is shown of a user, a session, and a device.
8
11
  *
@@ -52,4 +55,38 @@ export declare function sessionView(session: Session): AdminSessionView;
52
55
  * adopter's users under the adopter's own app identity. It never leaves the Worker.
53
56
  */
54
57
  export declare function deviceView(device: Device): AdminDeviceView;
58
+ /**
59
+ * The suspension projection (#621): the suspension the transition left in force, and the sessions the route
60
+ * revoked after it. Dates cross as ISO-8601, like every other response here.
61
+ */
62
+ export declare function suspensionView(userId: string, result: SuspendTransition, sessionsRevoked: number): AdminUserSuspendResponse;
63
+ /** The reinstatement projection (#621). A call that found no suspension in force is `unchanged`. */
64
+ export declare function reinstatementView(userId: string, result: LifecycleTransition): AdminUserReinstateResponse;
65
+ /** What became of a deletion's purge: due later, started by the call, or due with nothing bound to start it. */
66
+ export type PurgeDisposition = AdminUserDeleteResponse["purge"];
67
+ /**
68
+ * The deletion projection (#622): the deletion the transition left in force, the sessions the route revoked
69
+ * after it, and what became of the purge.
70
+ */
71
+ export declare function deletionView(userId: string, mode: DeletionMode, result: DeleteTransition, purge: PurgeDisposition, sessionsRevoked: number): AdminUserDeleteResponse;
72
+ /** The restoration projection (#622). A call that found the account not deleted is `unchanged`. */
73
+ export declare function restorationView(userId: string, result: RestoreTransition): AdminUserRestoreResponse;
74
+ /** The self-service deletion projection (#622). */
75
+ export declare function accountDeletionView(result: DeleteTransition): AccountDeleteResponse;
76
+ /**
77
+ * What auth holds about one account, as its export carries it (#622) — the person's own data, projected through
78
+ * the same views a support pane sees, so a session token, a provider token and a push token are absent here by
79
+ * the same construction that keeps them out of every other response. The operator who made a transition is
80
+ * theirs to disclose, not the person's, so the history carries the kind of actor and not its id.
81
+ */
82
+ export declare function authUserExportView(input: {
83
+ user: User;
84
+ sessions: readonly Session[];
85
+ accounts: readonly Pick<Account, "providerId" | "createdAt">[];
86
+ devices: readonly Device[];
87
+ history: readonly UserLifecycleEvent[];
88
+ plugins?: Record<string, Record<string, unknown>[]>;
89
+ }): AuthUserExport;
90
+ /** The export document (#622): who it is about, when it was read, and every capability's part. */
91
+ export declare function exportView(userId: string, exportedAt: Date, entries: readonly PurgeExportEntry[]): AdminUserExportResponse;
55
92
  //# sourceMappingURL=views.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"views.d.ts","sourceRoot":"","sources":["../../src/http/views.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAEpF;;;;;;;;;;;;GAYG;AAEH;;;;;;;;;;;GAWG;AACH,wBAAgB,QAAQ,CAAC,IAAI,EAAE,IAAI,GAAG,aAAa,CAWlD;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,OAAO,GAAG,gBAAgB,CAU9D;AAED;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,eAAe,CAa1D"}
1
+ {"version":3,"file":"views.d.ts","sourceRoot":"","sources":["../../src/http/views.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qCAAqC,CAAC;AAC5E,OAAO,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AACjE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAChE,OAAO,KAAK,EACV,gBAAgB,EAChB,YAAY,EACZ,mBAAmB,EACnB,iBAAiB,EACjB,iBAAiB,EAClB,MAAM,0BAA0B,CAAC;AAClC,OAAO,KAAK,EACV,qBAAqB,EACrB,eAAe,EACf,gBAAgB,EAChB,uBAAuB,EACvB,uBAAuB,EACvB,0BAA0B,EAC1B,wBAAwB,EACxB,wBAAwB,EACxB,aAAa,EACb,cAAc,EACf,MAAM,aAAa,CAAC;AAErB;;;;;;;;;;;;GAYG;AAEH;;;;;;;;;;;GAWG;AACH,wBAAgB,QAAQ,CAAC,IAAI,EAAE,IAAI,GAAG,aAAa,CAWlD;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,OAAO,GAAG,gBAAgB,CAU9D;AAED;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,eAAe,CAa1D;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAC5B,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,iBAAiB,EACzB,eAAe,EAAE,MAAM,GACtB,wBAAwB,CAU1B;AAED,oGAAoG;AACpG,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,mBAAmB,GAAG,0BAA0B,CAOzG;AAED,gHAAgH;AAChH,MAAM,MAAM,gBAAgB,GAAG,uBAAuB,CAAC,OAAO,CAAC,CAAC;AAEhE;;;GAGG;AACH,wBAAgB,YAAY,CAC1B,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,YAAY,EAClB,MAAM,EAAE,gBAAgB,EACxB,KAAK,EAAE,gBAAgB,EACvB,eAAe,EAAE,MAAM,GACtB,uBAAuB,CAYzB;AAED,mGAAmG;AACnG,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,iBAAiB,GAAG,wBAAwB,CAEnG;AAED,mDAAmD;AACnD,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,gBAAgB,GAAG,qBAAqB,CAEnF;AAOD;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE;IACxC,IAAI,EAAE,IAAI,CAAC;IACX,QAAQ,EAAE,SAAS,OAAO,EAAE,CAAC;IAC7B,QAAQ,EAAE,SAAS,IAAI,CAAC,OAAO,EAAE,YAAY,GAAG,WAAW,CAAC,EAAE,CAAC;IAC/D,OAAO,EAAE,SAAS,MAAM,EAAE,CAAC;IAC3B,OAAO,EAAE,SAAS,kBAAkB,EAAE,CAAC;IACvC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC,CAAC;CACrD,GAAG,cAAc,CAyBjB;AAED,kGAAkG;AAClG,wBAAgB,UAAU,CACxB,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,IAAI,EAChB,OAAO,EAAE,SAAS,gBAAgB,EAAE,GACnC,uBAAuB,CAMzB"}
@@ -84,5 +84,109 @@ function deviceView(device) {
84
84
  createdAt: device.createdAt.toISOString()
85
85
  };
86
86
  }
87
+ /**
88
+ * The suspension projection (#621): the suspension the transition left in force, and the sessions the route
89
+ * revoked after it. Dates cross as ISO-8601, like every other response here.
90
+ */
91
+ function suspensionView(userId, result, sessionsRevoked) {
92
+ return {
93
+ userId,
94
+ state: "suspended",
95
+ outcome: result.updated ? "updated" : "suspended",
96
+ suspendedAt: result.suspendedAt.toISOString(),
97
+ suspendedUntil: result.suspendedUntil?.toISOString() ?? null,
98
+ sessionsRevoked,
99
+ mailed: result.mailed
100
+ };
101
+ }
102
+ /** The reinstatement projection (#621). A call that found no suspension in force is `unchanged`. */
103
+ function reinstatementView(userId, result) {
104
+ return {
105
+ userId,
106
+ state: "active",
107
+ outcome: result.changed ? "reinstated" : "unchanged",
108
+ mailed: result.mailed
109
+ };
110
+ }
111
+ /**
112
+ * The deletion projection (#622): the deletion the transition left in force, the sessions the route revoked
113
+ * after it, and what became of the purge.
114
+ */
115
+ function deletionView(userId, mode, result, purge, sessionsRevoked) {
116
+ return {
117
+ userId,
118
+ state: "deleted",
119
+ mode,
120
+ outcome: result.outcome,
121
+ deletedAt: result.deletedAt.toISOString(),
122
+ purgeAfter: result.purgeAfter.toISOString(),
123
+ purge,
124
+ sessionsRevoked,
125
+ mailed: result.mailed
126
+ };
127
+ }
128
+ /** The restoration projection (#622). A call that found the account not deleted is `unchanged`. */
129
+ function restorationView(userId, result) {
130
+ return {
131
+ userId,
132
+ state: result.state,
133
+ outcome: result.changed ? "restored" : "unchanged"
134
+ };
135
+ }
136
+ /** The self-service deletion projection (#622). */
137
+ function accountDeletionView(result) {
138
+ return {
139
+ state: "deleted",
140
+ purgeAfter: result.purgeAfter.toISOString(),
141
+ mailed: result.mailed
142
+ };
143
+ }
144
+ /** A date as the wire carries it, or null. */
145
+ function iso(date) {
146
+ return date ? date.toISOString() : null;
147
+ }
148
+ /**
149
+ * What auth holds about one account, as its export carries it (#622) — the person's own data, projected through
150
+ * the same views a support pane sees, so a session token, a provider token and a push token are absent here by
151
+ * the same construction that keeps them out of every other response. The operator who made a transition is
152
+ * theirs to disclose, not the person's, so the history carries the kind of actor and not its id.
153
+ */
154
+ function authUserExportView(input) {
155
+ const { user } = input;
156
+ return {
157
+ user: {
158
+ ...userView(user),
159
+ suspendedAt: iso(user.suspendedAt),
160
+ suspendedUntil: iso(user.suspendedUntil),
161
+ deletedAt: iso(user.deletedAt),
162
+ purgeAfter: iso(user.purgeAfter)
163
+ },
164
+ sessions: input.sessions.map(sessionView),
165
+ providers: input.accounts.map((account) => ({
166
+ providerId: account.providerId,
167
+ createdAt: account.createdAt.toISOString()
168
+ })),
169
+ devices: input.devices.map(deviceView),
170
+ history: input.history.map((event) => ({
171
+ action: event.action,
172
+ actorType: event.actorType,
173
+ reason: event.reason,
174
+ suspendedUntil: iso(event.suspendedUntil),
175
+ createdAt: event.createdAt.toISOString()
176
+ })),
177
+ plugins: input.plugins ?? {}
178
+ };
179
+ }
180
+ /** The export document (#622): who it is about, when it was read, and every capability's part. */
181
+ function exportView(userId, exportedAt, entries) {
182
+ return {
183
+ subject: {
184
+ type: "user",
185
+ id: userId
186
+ },
187
+ exportedAt: exportedAt.toISOString(),
188
+ capabilities: entries.map((entry) => ({ ...entry }))
189
+ };
190
+ }
87
191
  //#endregion
88
- export { deviceView, sessionView, userView };
192
+ export { accountDeletionView, authUserExportView, deletionView, deviceView, exportView, reinstatementView, restorationView, sessionView, suspensionView, userView };