@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.
- package/README.md +8 -2
- package/dist/admin/users.js +1 -1
- package/dist/audit/actions.d.ts +40 -0
- package/dist/audit/actions.d.ts.map +1 -1
- package/dist/audit/actions.js +41 -1
- package/dist/audit/emit.d.ts +2 -0
- package/dist/audit/emit.d.ts.map +1 -1
- package/dist/audit/emit.js +2 -2
- package/dist/capability.d.ts +45 -1
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +40 -5
- package/dist/client/lifecycle.d.ts +19 -0
- package/dist/client/lifecycle.d.ts.map +1 -0
- package/dist/client/lifecycle.js +25 -0
- package/dist/client/projection.d.ts +4 -0
- package/dist/client/projection.d.ts.map +1 -1
- package/dist/data/betterAuth.d.ts +4 -0
- package/dist/data/betterAuth.d.ts.map +1 -1
- package/dist/data/betterAuth.js +6 -2
- package/dist/data/kitFields.d.ts +20 -25
- package/dist/data/kitFields.d.ts.map +1 -1
- package/dist/data/kitFields.js +28 -32
- package/dist/data/tables.d.ts +29 -2
- package/dist/data/tables.d.ts.map +1 -1
- package/dist/data/tables.js +5 -3
- package/dist/data/userLifecycle.d.ts +62 -0
- package/dist/data/userLifecycle.d.ts.map +1 -0
- package/dist/data/userLifecycle.js +51 -0
- package/dist/http/adminRoutes.d.ts.map +1 -1
- package/dist/http/adminRoutes.js +270 -5
- package/dist/http/guards.d.ts +24 -1
- package/dist/http/guards.d.ts.map +1 -1
- package/dist/http/guards.js +59 -3
- package/dist/http/lifecycleGate.d.ts +18 -0
- package/dist/http/lifecycleGate.d.ts.map +1 -0
- package/dist/http/lifecycleGate.js +75 -0
- package/dist/http/middleware.d.ts +30 -1
- package/dist/http/middleware.d.ts.map +1 -1
- package/dist/http/middleware.js +89 -7
- package/dist/http/providerRefusal.d.ts.map +1 -1
- package/dist/http/providerRefusal.js +8 -0
- package/dist/http/resolve.d.ts.map +1 -1
- package/dist/http/resolve.js +7 -4
- package/dist/http/responses.d.ts +180 -0
- package/dist/http/responses.d.ts.map +1 -1
- package/dist/http/responses.js +142 -1
- package/dist/http/routes.d.ts +1 -0
- package/dist/http/routes.d.ts.map +1 -1
- package/dist/http/routes.js +65 -4
- package/dist/http/schemas.d.ts +57 -0
- package/dist/http/schemas.d.ts.map +1 -1
- package/dist/http/schemas.js +51 -1
- package/dist/http/views.d.ts +39 -2
- package/dist/http/views.d.ts.map +1 -1
- package/dist/http/views.js +105 -1
- package/dist/instance/auth.d.ts +55 -3
- package/dist/instance/auth.d.ts.map +1 -1
- package/dist/instance/auth.js +53 -2
- package/dist/instance/microsoftEmail.d.ts +70 -0
- package/dist/instance/microsoftEmail.d.ts.map +1 -0
- package/dist/instance/microsoftEmail.js +96 -0
- package/dist/instance/providerSignInGate.d.ts +7 -6
- package/dist/instance/providerSignInGate.d.ts.map +1 -1
- package/dist/instance/providerSignInGate.js +7 -6
- package/dist/instance/providers.d.ts +7 -5
- package/dist/instance/providers.d.ts.map +1 -1
- package/dist/instance/providers.js +5 -3
- package/dist/instance/secrets.d.ts +64 -3
- package/dist/instance/secrets.d.ts.map +1 -1
- package/dist/instance/secrets.js +44 -5
- package/dist/lifecycle/audited.d.ts +48 -0
- package/dist/lifecycle/audited.d.ts.map +1 -0
- package/dist/lifecycle/audited.js +65 -0
- package/dist/lifecycle/enforce.d.ts +75 -0
- package/dist/lifecycle/enforce.d.ts.map +1 -0
- package/dist/lifecycle/enforce.js +111 -0
- package/dist/lifecycle/hooks.d.ts +53 -0
- package/dist/lifecycle/hooks.d.ts.map +1 -0
- package/dist/lifecycle/hooks.js +2 -0
- package/dist/lifecycle/reason.d.ts +11 -0
- package/dist/lifecycle/reason.d.ts.map +1 -0
- package/dist/lifecycle/reason.js +13 -0
- package/dist/lifecycle/request.d.ts +18 -0
- package/dist/lifecycle/request.d.ts.map +1 -0
- package/dist/lifecycle/request.js +31 -0
- package/dist/lifecycle/state.d.ts +64 -0
- package/dist/lifecycle/state.d.ts.map +1 -0
- package/dist/lifecycle/state.js +90 -0
- package/dist/lifecycle/transitions.d.ts +272 -0
- package/dist/lifecycle/transitions.d.ts.map +1 -0
- package/dist/lifecycle/transitions.js +623 -0
- package/dist/migrations/0004_user_lifecycle.d.ts +28 -0
- package/dist/migrations/0004_user_lifecycle.d.ts.map +1 -0
- package/dist/migrations/0004_user_lifecycle.js +47 -0
- package/dist/migrations/0005_purge_once.d.ts +22 -0
- package/dist/migrations/0005_purge_once.d.ts.map +1 -0
- package/dist/migrations/0005_purge_once.js +35 -0
- package/dist/migrations/pluginTables.d.ts +8 -0
- package/dist/migrations/pluginTables.d.ts.map +1 -1
- package/dist/migrations/pluginTables.js +8 -1
- package/dist/migrations/set.d.ts +3 -1
- package/dist/migrations/set.d.ts.map +1 -1
- package/dist/migrations/set.js +6 -2
- package/dist/peer.d.ts +4 -0
- package/dist/peer.d.ts.map +1 -1
- package/dist/purge/contribution.d.ts +47 -0
- package/dist/purge/contribution.d.ts.map +1 -0
- package/dist/purge/contribution.js +141 -0
- package/dist/purge/retryPolicy.d.ts +22 -0
- package/dist/purge/retryPolicy.d.ts.map +1 -0
- package/dist/purge/retryPolicy.js +26 -0
- package/dist/purge/run.d.ts +88 -0
- package/dist/purge/run.d.ts.map +1 -0
- package/dist/purge/run.js +102 -0
- package/dist/purge/specs.d.ts +71 -0
- package/dist/purge/specs.d.ts.map +1 -0
- package/dist/purge/specs.js +72 -0
- package/dist/purge/start.d.ts +42 -0
- package/dist/purge/start.d.ts.map +1 -0
- package/dist/purge/start.js +37 -0
- package/dist/purge/workflow.d.ts +58 -0
- package/dist/purge/workflow.d.ts.map +1 -0
- package/dist/purge/workflow.js +96 -0
- package/dist/test-utils/accountFootprint.d.ts +10 -0
- package/dist/test-utils/accountFootprint.d.ts.map +1 -0
- package/dist/test-utils/accountFootprint.js +44 -0
- package/dist/test-utils/liveApp.d.ts +21 -0
- package/dist/test-utils/liveApp.d.ts.map +1 -1
- package/dist/test-utils/liveApp.js +1 -0
- package/dist/test-utils/scopedBackend.d.ts +21 -0
- package/dist/test-utils/scopedBackend.d.ts.map +1 -1
- package/dist/test-utils/scopedBackend.js +7 -1
- package/dist/version.generated.d.ts +1 -1
- package/dist/version.generated.d.ts.map +1 -1
- package/dist/version.generated.js +1 -1
- package/docs/account-lifecycle.md +217 -0
- package/docs/apple-signin.md +7 -1
- package/docs/facebook-oauth.md +7 -1
- package/docs/github-oauth.md +7 -1
- package/docs/google-oauth.md +7 -1
- package/docs/microsoft-oauth.md +177 -0
- package/package.json +5 -5
- package/pithy.manifest.json +17 -3
- package/src/audit/actions.ts +42 -0
- package/src/audit/emit.ts +4 -2
- package/src/capability.ts +170 -52
- package/src/client/lifecycle.ts +27 -0
- package/src/client/projection.ts +4 -0
- package/src/data/betterAuth.ts +21 -1
- package/src/data/kitFields.ts +27 -0
- package/src/data/tables.ts +4 -2
- package/src/data/userLifecycle.ts +83 -0
- package/src/http/adminRoutes.ts +398 -2
- package/src/http/guards.ts +61 -1
- package/src/http/lifecycleGate.ts +78 -0
- package/src/http/middleware.ts +104 -2
- package/src/http/providerRefusal.ts +10 -0
- package/src/http/resolve.ts +8 -3
- package/src/http/responses.ts +245 -0
- package/src/http/routes.ts +93 -4
- package/src/http/schemas.ts +110 -0
- package/src/http/views.ts +147 -2
- package/src/instance/auth.ts +74 -2
- package/src/instance/microsoftEmail.ts +111 -0
- package/src/instance/providerSignInGate.ts +7 -6
- package/src/instance/providers.ts +8 -4
- package/src/instance/secrets.ts +59 -5
- package/src/lifecycle/audited.ts +104 -0
- package/src/lifecycle/enforce.ts +139 -0
- package/src/lifecycle/hooks.ts +54 -0
- package/src/lifecycle/reason.ts +11 -0
- package/src/lifecycle/request.ts +39 -0
- package/src/lifecycle/state.ts +101 -0
- package/src/lifecycle/transitions.ts +872 -0
- package/src/migrations/0004_user_lifecycle.ts +68 -0
- package/src/migrations/0005_purge_once.ts +42 -0
- package/src/migrations/pluginTables.ts +19 -1
- package/src/migrations/set.ts +5 -1
- package/src/purge/contribution.ts +191 -0
- package/src/purge/retryPolicy.ts +26 -0
- package/src/purge/run.ts +185 -0
- package/src/purge/specs.ts +95 -0
- package/src/purge/start.ts +79 -0
- package/src/purge/workflow.ts +144 -0
- package/src/test-utils/accountFootprint.ts +95 -0
- package/src/test-utils/liveApp.ts +2 -1
- package/src/test-utils/scopedBackend.ts +2 -1
- package/src/version.generated.ts +1 -1
package/src/audit/actions.ts
CHANGED
|
@@ -150,6 +150,48 @@ export const AuthAuditActions = {
|
|
|
150
150
|
adminUserSessionsRevoked: "auth/admin_user_sessions_revoked",
|
|
151
151
|
/** One of a user's devices was signed out and its registration dropped, from the management surface. */
|
|
152
152
|
adminDeviceRevoked: "auth/admin_device_revoked",
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* The account lifecycle (#620). Each is written by the transition in `../lifecycle/transitions.ts`, beside
|
|
156
|
+
* the `pithy_auth_user_lifecycle` row that records the same fact — the trail answers "who, from where", the
|
|
157
|
+
* table answers "what happened to this account". The admin ones carry `actorType: "control-plane"`; the
|
|
158
|
+
* self-service deletion carries the account's own holder, and the purge `system`.
|
|
159
|
+
*
|
|
160
|
+
* The dashboard's own `customer/user_suspended` and `customer/user_restored` are the client side of the
|
|
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.
|
|
168
|
+
*/
|
|
169
|
+
|
|
170
|
+
/** An account was suspended from the management surface. Carries the reason and any end date. */
|
|
171
|
+
adminUserSuspended: "auth/admin_user_suspended",
|
|
172
|
+
/** A suspended account was reinstated from the management surface. */
|
|
173
|
+
adminUserReinstated: "auth/admin_user_reinstated",
|
|
174
|
+
/** An account was deleted from the management surface, with its purge window starting now. */
|
|
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",
|
|
182
|
+
/** A deleted account was restored inside its purge window, from the management surface. */
|
|
183
|
+
adminUserRestored: "auth/admin_user_restored",
|
|
184
|
+
/** A deleted account's data was erased. Recorded once, when the last purge step has run. */
|
|
185
|
+
adminUserPurged: "auth/admin_user_purged",
|
|
186
|
+
/** The account's own holder deleted their account. Always a soft deletion, on the configured window. */
|
|
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",
|
|
153
195
|
} as const;
|
|
154
196
|
|
|
155
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,
|
|
@@ -431,7 +433,7 @@ export const ProviderAccount = z
|
|
|
431
433
|
.object({
|
|
432
434
|
id: z.string().describe("The account row's primary key — which link was made or broken."),
|
|
433
435
|
userId: z.string().describe("The user this provider can, or could, sign in as."),
|
|
434
|
-
providerId: z.string().describe("The provider slug (`google`, `apple`, `facebook`, `github`)."),
|
|
436
|
+
providerId: z.string().describe("The provider slug (`google`, `apple`, `facebook`, `github`, `microsoft`)."),
|
|
435
437
|
})
|
|
436
438
|
.describe("The account-row columns `auth/oauth_linked` and `auth/oauth_unlinked` are built from.");
|
|
437
439
|
export type ProviderAccount = z.output<typeof ProviderAccount>;
|
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";
|
|
@@ -22,10 +25,13 @@ import { createAuthRoutes } from "./http/routes";
|
|
|
22
25
|
import type { GithubUserInfoResolver } from "./instance/githubUserInfo";
|
|
23
26
|
import { AuthPlugin, assertAdditivePlugins } from "./instance/plugins";
|
|
24
27
|
import { authSecretsRegistryFor, inapplicableProviderSecrets } from "./instance/secrets";
|
|
28
|
+
import type { UserLifecycleHooks } from "./lifecycle/hooks";
|
|
25
29
|
import { AUTH_MIGRATION_ORDER } from "./migrations/0001_init";
|
|
26
30
|
import { authPluginPlan } from "./migrations/pluginTables";
|
|
27
31
|
import { AUTH_MIGRATIONS } from "./migrations/set";
|
|
28
32
|
import { type AuthPeer, authPeer } from "./peer";
|
|
33
|
+
import { authPurgeContribution } from "./purge/contribution";
|
|
34
|
+
import { authWorkflows } from "./purge/specs";
|
|
29
35
|
import { authDevSessionSeed } from "./seeds/devSession";
|
|
30
36
|
import { authExampleSeed } from "./seeds/example";
|
|
31
37
|
import { PACKAGE_NAME, PACKAGE_VERSION } from "./version.generated";
|
|
@@ -97,6 +103,9 @@ export const AuthConfig = z
|
|
|
97
103
|
github: ProviderToggle.prefault({}).describe(
|
|
98
104
|
"GitHub OAuth. Enable it, then store credentials as the `auth-github-credentials` secret. See docs/github-oauth.md.",
|
|
99
105
|
),
|
|
106
|
+
microsoft: ProviderToggle.prefault({}).describe(
|
|
107
|
+
"Microsoft sign-in — work, school, or personal accounts through Entra ID. Enable it, then store credentials and the tenant as the `auth-microsoft-credentials` secret. Entra ID cannot vouch for an email it did not verify, so an unverified one is verified by magic link before it links. See docs/microsoft-oauth.md.",
|
|
108
|
+
),
|
|
100
109
|
sessionExpiresIn: z
|
|
101
110
|
.number()
|
|
102
111
|
.int()
|
|
@@ -127,6 +136,47 @@ export const AuthConfig = z
|
|
|
127
136
|
.describe(
|
|
128
137
|
"When true, sign-in never provisions a new user — existing accounts only. Unknown emails get no email (anti-enumeration).",
|
|
129
138
|
),
|
|
139
|
+
retention: z
|
|
140
|
+
.object({
|
|
141
|
+
purgeAfterDays: z
|
|
142
|
+
.number()
|
|
143
|
+
.int()
|
|
144
|
+
.positive()
|
|
145
|
+
.default(30)
|
|
146
|
+
.describe(
|
|
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.",
|
|
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
|
+
),
|
|
155
|
+
})
|
|
156
|
+
.prefault({})
|
|
157
|
+
.describe(
|
|
158
|
+
"How long a deleted account is kept before it is purged. Self-service deletion and an operator's soft deletion both use this window.",
|
|
159
|
+
),
|
|
160
|
+
lifecycleEmails: z
|
|
161
|
+
.object({
|
|
162
|
+
accountSuspended: z
|
|
163
|
+
.boolean()
|
|
164
|
+
.default(true)
|
|
165
|
+
.describe("Email the person when their account is suspended, with the reason and any end date."),
|
|
166
|
+
accountReinstated: z.boolean().default(true).describe("Email the person when a suspension is lifted."),
|
|
167
|
+
deletionScheduled: z
|
|
168
|
+
.boolean()
|
|
169
|
+
.default(true)
|
|
170
|
+
.describe("Email the person when their account is deleted, with the date its data will be erased."),
|
|
171
|
+
deletionComplete: z
|
|
172
|
+
.boolean()
|
|
173
|
+
.default(true)
|
|
174
|
+
.describe("Email the person once their data has been erased. Sent before the address is."),
|
|
175
|
+
})
|
|
176
|
+
.prefault({})
|
|
177
|
+
.describe(
|
|
178
|
+
"Which account-lifecycle emails are sent. All four send by default, through `@pithy-sh/email`; switch one off by setting it to false.",
|
|
179
|
+
),
|
|
130
180
|
plugins: z
|
|
131
181
|
.array(AuthPlugin)
|
|
132
182
|
.default([])
|
|
@@ -164,6 +214,18 @@ export interface AuthWiring {
|
|
|
164
214
|
* Optional on the wiring for the reason `onSessionRevoked` is: no resolver is the ordinary composition.
|
|
165
215
|
*/
|
|
166
216
|
resolveScopes?: ScopeResolver | undefined;
|
|
217
|
+
/**
|
|
218
|
+
* The adopter's lifecycle hooks, or absent. See {@link UserLifecycleHooks}.
|
|
219
|
+
*
|
|
220
|
+
* Optional on the wiring for the reason `onSessionRevoked` is: no hook is the ordinary composition.
|
|
221
|
+
*/
|
|
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;
|
|
167
229
|
}
|
|
168
230
|
|
|
169
231
|
/** The session a {@link ScopeResolver} is asked about — the one Better Auth just resolved for this request. */
|
|
@@ -205,62 +267,78 @@ export type SessionRevokedListener = (session: { id: string; userId: string }, d
|
|
|
205
267
|
* `PaymentsOptions`: everything describable stays in {@link AuthConfig}, and a resolver is a sibling key
|
|
206
268
|
* destructured off before the parse.
|
|
207
269
|
*/
|
|
208
|
-
export type AuthOptions = AuthConfigInput &
|
|
270
|
+
export type AuthOptions = AuthConfigInput &
|
|
271
|
+
UserLifecycleHooks & {
|
|
272
|
+
/**
|
|
273
|
+
* Resolve a GitHub identity yourself, replacing the kit's primary-only rule.
|
|
274
|
+
*
|
|
275
|
+
* The kit's default is deliberately conservative: it links on the **primary** address and nothing else,
|
|
276
|
+
* because GitHub never re-verifies and a verified secondary can only speak to the past. An adopter who
|
|
277
|
+
* wants a richer ladder — match a verified secondary, present a chooser on multiple matches — builds it
|
|
278
|
+
* here. `getUserInfo` is the only hook in this flow running before both fetches and before
|
|
279
|
+
* `mapProfileToUser`, and the only one holding the OAuth token.
|
|
280
|
+
*
|
|
281
|
+
* **Better Auth trusts what you return, verbatim.** It performs no independent check, so an
|
|
282
|
+
* `emailVerified: true` you did not read from GitHub is an account takeover: an attacker adds a
|
|
283
|
+
* victim's address to their own GitHub *unverified* and links to the victim's user. Return GitHub's
|
|
284
|
+
* real per-address flag, always.
|
|
285
|
+
*/
|
|
286
|
+
resolveGithubUserInfo?: GithubUserInfoResolver;
|
|
287
|
+
/**
|
|
288
|
+
* Told when a session is revoked, so state another capability keyed on it can go with it.
|
|
289
|
+
*
|
|
290
|
+
* **On the row, not on the sign-out route.** A sign-out, a revoke and an admin ending somebody's
|
|
291
|
+
* devices all delete the same row, so a listener hung off one endpoint would miss the others.
|
|
292
|
+
*
|
|
293
|
+
* The case this exists for is `@pithy-sh/organization`: its acting selection is keyed by session id
|
|
294
|
+
* and its schema says signing out must take it with it. Tenancy depends on auth and not the reverse,
|
|
295
|
+
* so the composition holding both is what joins them, and this is the join.
|
|
296
|
+
*
|
|
297
|
+
* **Non-fatal by contract.** The session is already gone when this runs; a failure here must not turn
|
|
298
|
+
* a completed sign-out into an error the caller retries, so the instance swallows what it throws.
|
|
299
|
+
*
|
|
300
|
+
* A function, so it is destructured off before `AuthConfig.parse` for the reason above.
|
|
301
|
+
*/
|
|
302
|
+
onSessionRevoked?: SessionRevokedListener;
|
|
303
|
+
/**
|
|
304
|
+
* Decide, per request, what this request's caller is — and so which scope gates it opens (#560).
|
|
305
|
+
*
|
|
306
|
+
* `leaderboard:submit`, `rating:record`, `leaderboard:admin` and `ledger:admin` are **attestations about
|
|
307
|
+
* the caller, not permissions granted to the user**: each says *this write came from the adopter's own
|
|
308
|
+
* trusted backend, not from a device*. This is where that is decided, and the seam does not dictate how.
|
|
309
|
+
* A backend calling over a service binding, one presenting a client certificate, and one presenting a
|
|
310
|
+
* short-lived token all answer the same question here. `verifyCallerToken` and `readClientCertificate`
|
|
311
|
+
* are the kit's helpers for the last two; `docs/server-authoritative.md` ranks the three.
|
|
312
|
+
*
|
|
313
|
+
* **Resolved per request, never cached** — a cached scope is a revocation that has not taken effect.
|
|
314
|
+
* **Failure is closed and never fatal**: a resolver that throws, or answers anything but a list of
|
|
315
|
+
* strings, leaves the request with no scopes and logs at warn, and the request goes on to whatever gate
|
|
316
|
+
* it was headed for. **No default**: without one the array is empty and nothing extra runs, so composing
|
|
317
|
+
* this changes nothing until an adopter opts in.
|
|
318
|
+
*
|
|
319
|
+
* A function, so it is destructured off before `AuthConfig.parse` for the reason above.
|
|
320
|
+
*/
|
|
321
|
+
resolveScopes?: ScopeResolver;
|
|
322
|
+
};
|
|
323
|
+
|
|
324
|
+
/** The auth capability, with its resolved config attached for inspection. */
|
|
325
|
+
export interface AuthCapability extends Capability {
|
|
326
|
+
authConfig: AuthConfig;
|
|
209
327
|
/**
|
|
210
|
-
*
|
|
211
|
-
*
|
|
212
|
-
* The kit's default is deliberately conservative: it links on the **primary** address and nothing else,
|
|
213
|
-
* because GitHub never re-verifies and a verified secondary can only speak to the past. An adopter who
|
|
214
|
-
* wants a richer ladder — match a verified secondary, present a chooser on multiple matches — builds it
|
|
215
|
-
* here. `getUserInfo` is the only hook in this flow running before both fetches and before
|
|
216
|
-
* `mapProfileToUser`, and the only one holding the OAuth token.
|
|
217
|
-
*
|
|
218
|
-
* **Better Auth trusts what you return, verbatim.** It performs no independent check, so an
|
|
219
|
-
* `emailVerified: true` you did not read from GitHub is an account takeover: an attacker adds a
|
|
220
|
-
* victim's address to their own GitHub *unverified* and links to the victim's user. Return GitHub's
|
|
221
|
-
* real per-address flag, always.
|
|
328
|
+
* The adopter's account-lifecycle hooks, as `auth()` was handed them. Read by whatever runs a transition
|
|
329
|
+
* outside a request this capability serves — the purge Workflow (#622) fires `onUserPurged` through it.
|
|
222
330
|
*/
|
|
223
|
-
|
|
331
|
+
lifecycleHooks: UserLifecycleHooks;
|
|
224
332
|
/**
|
|
225
|
-
*
|
|
226
|
-
*
|
|
227
|
-
* **On the row, not on the sign-out route.** A sign-out, a revoke and an admin ending somebody's
|
|
228
|
-
* devices all delete the same row, so a listener hung off one endpoint would miss the others.
|
|
229
|
-
*
|
|
230
|
-
* The case this exists for is `@pithy-sh/organization`: its acting selection is keyed by session id
|
|
231
|
-
* and its schema says signing out must take it with it. Tenancy depends on auth and not the reverse,
|
|
232
|
-
* so the composition holding both is what joins them, and this is the join.
|
|
233
|
-
*
|
|
234
|
-
* **Non-fatal by contract.** The session is already gone when this runs; a failure here must not turn
|
|
235
|
-
* a completed sign-out into an error the caller retries, so the instance swallows what it throws.
|
|
236
|
-
*
|
|
237
|
-
* A function, so it is destructured off before `AuthConfig.parse` for the reason above.
|
|
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.
|
|
238
335
|
*/
|
|
239
|
-
|
|
336
|
+
purgeSteps: readonly PurgeStep[];
|
|
240
337
|
/**
|
|
241
|
-
*
|
|
242
|
-
*
|
|
243
|
-
* `leaderboard:submit`, `rating:record`, `leaderboard:admin` and `ledger:admin` are **attestations about
|
|
244
|
-
* the caller, not permissions granted to the user**: each says *this write came from the adopter's own
|
|
245
|
-
* trusted backend, not from a device*. This is where that is decided, and the seam does not dictate how.
|
|
246
|
-
* A backend calling over a service binding, one presenting a client certificate, and one presenting a
|
|
247
|
-
* short-lived token all answer the same question here. `verifyCallerToken` and `readClientCertificate`
|
|
248
|
-
* are the kit's helpers for the last two; `docs/server-authoritative.md` ranks the three.
|
|
249
|
-
*
|
|
250
|
-
* **Resolved per request, never cached** — a cached scope is a revocation that has not taken effect.
|
|
251
|
-
* **Failure is closed and never fatal**: a resolver that throws, or answers anything but a list of
|
|
252
|
-
* strings, leaves the request with no scopes and logs at warn, and the request goes on to whatever gate
|
|
253
|
-
* it was headed for. **No default**: without one the array is empty and nothing extra runs, so composing
|
|
254
|
-
* this changes nothing until an adopter opts in.
|
|
255
|
-
*
|
|
256
|
-
* A function, so it is destructured off before `AuthConfig.parse` for the reason above.
|
|
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`.
|
|
257
340
|
*/
|
|
258
|
-
|
|
259
|
-
};
|
|
260
|
-
|
|
261
|
-
/** The auth capability, with its resolved config attached for inspection. */
|
|
262
|
-
export interface AuthCapability extends Capability {
|
|
263
|
-
authConfig: AuthConfig;
|
|
341
|
+
auditFor: (env: Record<string, unknown>) => AuditEmit;
|
|
264
342
|
/**
|
|
265
343
|
* What a capability composed beside this one reads an account through — `matchmaking`, `support`,
|
|
266
344
|
* `testers`. Found in their `compose` hooks, so none of them imports this package and a project without
|
|
@@ -311,8 +389,25 @@ export function auth(options: AuthOptions): AuthCapability {
|
|
|
311
389
|
// Zod 4 objects strip unknown keys silently, so a `resolveGithubUserInfo` handed to `AuthConfig.parse`
|
|
312
390
|
// would vanish with no error and the adopter's override would simply never run. `payments()` splits
|
|
313
391
|
// its `resolveSubject` out for the same reason.
|
|
314
|
-
const {
|
|
392
|
+
const {
|
|
393
|
+
resolveGithubUserInfo,
|
|
394
|
+
onSessionRevoked,
|
|
395
|
+
resolveScopes,
|
|
396
|
+
onUserSuspended,
|
|
397
|
+
onUserReinstated,
|
|
398
|
+
onUserDeleted,
|
|
399
|
+
onUserPurged,
|
|
400
|
+
...config
|
|
401
|
+
} = options;
|
|
315
402
|
const resolved = AuthConfig.parse(config);
|
|
403
|
+
// The lifecycle hooks, kept only where one was given, so an absent hook is an absent key rather than an
|
|
404
|
+
// `undefined` every reader has to tell apart from a hook.
|
|
405
|
+
const lifecycleHooks: UserLifecycleHooks = {
|
|
406
|
+
...(onUserSuspended ? { onUserSuspended } : {}),
|
|
407
|
+
...(onUserReinstated ? { onUserReinstated } : {}),
|
|
408
|
+
...(onUserDeleted ? { onUserDeleted } : {}),
|
|
409
|
+
...(onUserPurged ? { onUserPurged } : {}),
|
|
410
|
+
};
|
|
316
411
|
// What may be composed, before anything is built from the list. The four the kit composes are the
|
|
317
412
|
// sign-in this product promises and what the control-plane seam verifies against, so a list naming one
|
|
318
413
|
// of them is refused here by name rather than silently redefining a route at request time — and so is a
|
|
@@ -329,7 +424,14 @@ export function auth(options: AuthOptions): AuthCapability {
|
|
|
329
424
|
turnstile: undefined,
|
|
330
425
|
onSessionRevoked,
|
|
331
426
|
resolveScopes,
|
|
427
|
+
lifecycleHooks,
|
|
428
|
+
purgeSteps: [],
|
|
332
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[] = [];
|
|
333
435
|
|
|
334
436
|
// Tier-1 edge rate limiter, contributed as middleware so it runs before session resolution.
|
|
335
437
|
const rateLimitMiddleware: PithyMiddleware = (app) => {
|
|
@@ -388,6 +490,11 @@ export function auth(options: AuthOptions): AuthCapability {
|
|
|
388
490
|
migrations: { ...AUTH_MIGRATIONS, ...pluginPlan.migrations },
|
|
389
491
|
},
|
|
390
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,
|
|
391
498
|
compose: ({ capabilities }) => {
|
|
392
499
|
const email = capabilities.find(isEmailCapability);
|
|
393
500
|
if (!email) {
|
|
@@ -409,6 +516,9 @@ export function auth(options: AuthOptions): AuthCapability {
|
|
|
409
516
|
// Refused at boot, naming both sides: the alternative is a `create table` that fails halfway
|
|
410
517
|
// through `pithy migrate`, or two capabilities quietly reading and writing one table.
|
|
411
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;
|
|
412
522
|
},
|
|
413
523
|
/**
|
|
414
524
|
* The client-safe projection — what a sign-in screen needs and nothing more: where to call
|
|
@@ -436,6 +546,7 @@ export function auth(options: AuthOptions): AuthCapability {
|
|
|
436
546
|
apple: resolved.apple.enabled,
|
|
437
547
|
facebook: resolved.facebook.enabled,
|
|
438
548
|
github: resolved.github.enabled,
|
|
549
|
+
microsoft: resolved.microsoft.enabled,
|
|
439
550
|
},
|
|
440
551
|
// Per provider, beside the global one. A project may let email create accounts while a provider
|
|
441
552
|
// may not, and a screen with only `signUpEnabled` promises what that provider will refuse (#559).
|
|
@@ -444,6 +555,7 @@ export function auth(options: AuthOptions): AuthCapability {
|
|
|
444
555
|
apple: resolved.apple.allowSignUp,
|
|
445
556
|
facebook: resolved.facebook.allowSignUp,
|
|
446
557
|
github: resolved.github.allowSignUp,
|
|
558
|
+
microsoft: resolved.microsoft.allowSignUp,
|
|
447
559
|
},
|
|
448
560
|
otpLength: resolved.otpLength,
|
|
449
561
|
signUpEnabled: !resolved.disableSignUp,
|
|
@@ -470,7 +582,13 @@ export function auth(options: AuthOptions): AuthCapability {
|
|
|
470
582
|
seeds: [authExampleSeed, authDevSessionSeed],
|
|
471
583
|
});
|
|
472
584
|
|
|
473
|
-
return Object.assign(capability, {
|
|
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
|
+
});
|
|
474
592
|
}
|
|
475
593
|
|
|
476
594
|
/** Type guard: is this capability the auth capability? */
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import type { KitErrorCode } from "@pithy-sh/core/src/error/payload";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The two codes a refused account comes back with, for a screen to branch on (#620).
|
|
8
|
+
*
|
|
9
|
+
* **Imported rather than spelled**, for the reason the sign-in screen imports `NEUTRAL_PROVIDER_REFUSAL`: a
|
|
10
|
+
* literal in a copied screen and a literal in the Worker are a pair that can drift, and the drift shows as a
|
|
11
|
+
* locked-out person landing on a sign-in form that says nothing. The type ties each to the kit's taxonomy, so
|
|
12
|
+
* a rename there is a compile error here.
|
|
13
|
+
*
|
|
14
|
+
* Either arrives as a `PithyError` body's `code` from a JSON call, or as `?error=` on the screen a magic link
|
|
15
|
+
* or a social sign-in returned to.
|
|
16
|
+
*/
|
|
17
|
+
export const ACCOUNT_SUSPENDED = "auth/account_suspended" satisfies KitErrorCode;
|
|
18
|
+
|
|
19
|
+
/** The code for an account inside its purge window. See {@link ACCOUNT_SUSPENDED}. */
|
|
20
|
+
export const ACCOUNT_DELETED = "auth/account_deleted" satisfies KitErrorCode;
|
|
21
|
+
|
|
22
|
+
/** Which of the two a code is, or `null` for anything else — a refusal a screen should not reroute. */
|
|
23
|
+
export function accountRefusal(code: string | null | undefined): "suspended" | "deleted" | null {
|
|
24
|
+
if (code === ACCOUNT_SUSPENDED) return "suspended";
|
|
25
|
+
if (code === ACCOUNT_DELETED) return "deleted";
|
|
26
|
+
return null;
|
|
27
|
+
}
|
package/src/client/projection.ts
CHANGED
|
@@ -47,6 +47,8 @@ export type AuthClientProjection =
|
|
|
47
47
|
facebook: boolean;
|
|
48
48
|
/** Whether Sign in with GitHub is offered. */
|
|
49
49
|
github: boolean;
|
|
50
|
+
/** Whether Sign in with Microsoft is offered. */
|
|
51
|
+
microsoft: boolean;
|
|
50
52
|
};
|
|
51
53
|
/**
|
|
52
54
|
* Whether each offered provider may create an account, from its `allowSignUp` toggle.
|
|
@@ -69,6 +71,8 @@ export type AuthClientProjection =
|
|
|
69
71
|
facebook: boolean;
|
|
70
72
|
/** Whether a GitHub sign-in may create an account. */
|
|
71
73
|
github: boolean;
|
|
74
|
+
/** Whether a Microsoft sign-in may create an account. */
|
|
75
|
+
microsoft: boolean;
|
|
72
76
|
};
|
|
73
77
|
/** How many digits an email OTP carries. */
|
|
74
78
|
otpLength: number;
|
package/src/data/betterAuth.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
2
|
// SPDX-License-Identifier: MIT
|
|
3
3
|
|
|
4
|
-
import { JsonDate, SQLiteBoolean } from "@pithy-sh/core/src/data/codecs";
|
|
4
|
+
import { JsonDate, SQLiteBoolean, SQLiteDate } from "@pithy-sh/core/src/data/codecs";
|
|
5
5
|
import { Locale } from "@pithy-sh/core/src/i18n/locale";
|
|
6
6
|
import { z } from "zod";
|
|
7
7
|
|
|
@@ -52,6 +52,26 @@ export const User = z
|
|
|
52
52
|
updatedAt: BetterAuthDate.describe(
|
|
53
53
|
"When the user record was last updated. ISO-8601 text in SQLite; a `Date` in app code.",
|
|
54
54
|
),
|
|
55
|
+
// The four lifecycle columns (#620). **Ms-epoch through `SQLiteDate`, not ISO text like their
|
|
56
|
+
// neighbors**, and the difference is who writes them: Better Auth writes every other date on this
|
|
57
|
+
// table, and never these — they are `input: false` and only the kit's lifecycle transitions set
|
|
58
|
+
// them, through the kit's own Kysely. So they take the house convention, and `../data/kitFields.ts`
|
|
59
|
+
// declares them `type: "number"` so Better Auth hands back exactly what is stored.
|
|
60
|
+
//
|
|
61
|
+
// `nullish` rather than `nullable`: a row read before `0004_user_lifecycle` ran has no such key at
|
|
62
|
+
// all, and an absent state is the same fact as a null one — nothing has happened to this account.
|
|
63
|
+
suspendedAt: SQLiteDate.nullish().describe(
|
|
64
|
+
"When this account was suspended, or null when it is not. A suspended account cannot sign in, refresh a token, or act on any route. Ms-epoch in SQLite; a `Date` in app code.",
|
|
65
|
+
),
|
|
66
|
+
suspendedUntil: SQLiteDate.nullish().describe(
|
|
67
|
+
"When the current suspension ends by itself, or null for one that lasts until an operator reinstates the account. A suspension past this instant is treated as absent, with no write needed to expire it. Ms-epoch in SQLite.",
|
|
68
|
+
),
|
|
69
|
+
deletedAt: SQLiteDate.nullish().describe(
|
|
70
|
+
"When this account was deleted, or null when it is not. A deleted account cannot sign in or act, and can be restored until `purgeAfter`. Ms-epoch in SQLite.",
|
|
71
|
+
),
|
|
72
|
+
purgeAfter: SQLiteDate.nullish().describe(
|
|
73
|
+
"When a deleted account's data may be erased — the deletion instant plus `retention.purgeAfterDays`. Null unless the account is deleted. Ms-epoch in SQLite.",
|
|
74
|
+
),
|
|
55
75
|
})
|
|
56
76
|
.describe("A user in `pithy_auth_users` — the canonical identity every session and account hangs off.");
|
|
57
77
|
export type User = z.output<typeof User>;
|
package/src/data/kitFields.ts
CHANGED
|
@@ -29,6 +29,32 @@ import { Locale } from "@pithy-sh/core/src/i18n/locale";
|
|
|
29
29
|
* because it has no transactional DDL.
|
|
30
30
|
*/
|
|
31
31
|
|
|
32
|
+
/**
|
|
33
|
+
* The account-lifecycle columns on `pithy_auth_users` (#620): whether this account is suspended or
|
|
34
|
+
* deleted, and until when.
|
|
35
|
+
*
|
|
36
|
+
* **Declared here so a session read already carries them.** Better Auth returns every declared field on
|
|
37
|
+
* the user it resolves for a session, so the middleware that fills `AuthContext` reads the account's state
|
|
38
|
+
* off the row it has already loaded — enforcement costs no query and no join. Left out of this object, the
|
|
39
|
+
* columns would exist and every session would read as unrestricted.
|
|
40
|
+
*
|
|
41
|
+
* **`input: false` on all four, and that is the security property.** An account's state is something done
|
|
42
|
+
* *to* it — by an operator, or by its owner through the kit's own deletion route — never a field its
|
|
43
|
+
* holder may write. With `input: true`, one `updateUser({ suspendedAt: null })` would lift a suspension.
|
|
44
|
+
*
|
|
45
|
+
* **`type: "number"`, not `"date"`.** Only the kit writes these, through its own Kysely, in the house
|
|
46
|
+
* ms-epoch convention (`../data/betterAuth.ts` says why they differ from their neighbors). `"date"` would
|
|
47
|
+
* have Better Auth convert what it hands back, and a `"date"` that the adapter believes is ISO text while
|
|
48
|
+
* the column holds an integer is a column that reads back as the wrong thing. As a number it arrives
|
|
49
|
+
* exactly as stored, and `SQLiteDate` decodes it.
|
|
50
|
+
*/
|
|
51
|
+
const LIFECYCLE_FIELDS = {
|
|
52
|
+
suspendedAt: { type: "number", required: false, input: false },
|
|
53
|
+
suspendedUntil: { type: "number", required: false, input: false },
|
|
54
|
+
deletedAt: { type: "number", required: false, input: false },
|
|
55
|
+
purgeAfter: { type: "number", required: false, input: false },
|
|
56
|
+
} as const;
|
|
57
|
+
|
|
32
58
|
/**
|
|
33
59
|
* The extra `pithy_auth_users` columns.
|
|
34
60
|
*
|
|
@@ -54,6 +80,7 @@ import { Locale } from "@pithy-sh/core/src/i18n/locale";
|
|
|
54
80
|
*/
|
|
55
81
|
export const KIT_USER_FIELDS = {
|
|
56
82
|
locale: { type: "string", required: false, input: true, validator: { input: Locale.nullable() } },
|
|
83
|
+
...LIFECYCLE_FIELDS,
|
|
57
84
|
} as const;
|
|
58
85
|
|
|
59
86
|
/**
|
package/src/data/tables.ts
CHANGED
|
@@ -7,14 +7,15 @@ import type { Kysely } from "kysely";
|
|
|
7
7
|
import { Account, Jwks, RateLimit, Session, User, Verification } from "./betterAuth";
|
|
8
8
|
import { Device } from "./device";
|
|
9
9
|
import { RotatedToken } from "./rotatedToken";
|
|
10
|
+
import { UserLifecycleEvent } from "./userLifecycle";
|
|
10
11
|
|
|
11
12
|
/**
|
|
12
13
|
* The auth capability's table map: camelCase keys, so `CamelCasePlugin` emits the snake_case
|
|
13
14
|
* `pithy_auth_*` SQL. One source of truth shared by the capability wiring, the Better-Auth instance
|
|
14
15
|
* (whose Kysely adapter wraps this same Kysely), the device registry, and the migration.
|
|
15
16
|
*
|
|
16
|
-
* The first six tables are Better-Auth-managed; `pithyAuthDevices
|
|
17
|
-
* ours. Setting Better Auth's `modelName` to these exact camelCase keys lets the one `CamelCasePlugin`
|
|
17
|
+
* The first six tables are Better-Auth-managed; `pithyAuthDevices`, `pithyAuthRotatedTokens` and
|
|
18
|
+
* `pithyAuthUserLifecycle` are ours. Setting Better Auth's `modelName` to these exact camelCase keys lets the one `CamelCasePlugin`
|
|
18
19
|
* own the camelCase ↔ snake_case boundary uniformly for both Better Auth's queries and our migration DDL.
|
|
19
20
|
*/
|
|
20
21
|
export const authTables = {
|
|
@@ -26,6 +27,7 @@ export const authTables = {
|
|
|
26
27
|
pithyAuthRateLimit: RateLimit,
|
|
27
28
|
pithyAuthDevices: Device,
|
|
28
29
|
pithyAuthRotatedTokens: RotatedToken,
|
|
30
|
+
pithyAuthUserLifecycle: UserLifecycleEvent,
|
|
29
31
|
};
|
|
30
32
|
export type AuthTables = typeof authTables;
|
|
31
33
|
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import { SQLiteBoolean, SQLiteDate } from "@pithy-sh/core/src/data/codecs";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* `pithy_auth_user_lifecycle` — every transition an account went through, who made it, and why.
|
|
9
|
+
*
|
|
10
|
+
* **The columns on `pithy_auth_users` answer "what is true now"; this table answers "what happened, and who
|
|
11
|
+
* did it".** The two are written together by `../lifecycle/transitions.ts` and never apart. The columns are
|
|
12
|
+
* what enforcement reads on every request, so they hold only the current state; the reason an operator gave
|
|
13
|
+
* for a suspension, and the history of every reinstatement before it, live here.
|
|
14
|
+
*
|
|
15
|
+
* **No foreign key to the user, deliberately.** A purge erases the user row and every row hanging off it, and
|
|
16
|
+
* this table is the one record that must survive it: the trail that the account existed, was deleted, and
|
|
17
|
+
* was erased, by whom and when. A cascade would take the evidence with the subject. So the row names the user
|
|
18
|
+
* by id and holds nothing else about them — no address, no name — and is the only `pithy_auth_*` row a purge
|
|
19
|
+
* leaves behind.
|
|
20
|
+
*
|
|
21
|
+
* Written by the kit through its own Kysely, so its dates take the house ms-epoch `SQLiteDate`.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
/** What happened to the account. */
|
|
25
|
+
export const UserLifecycleAction = z
|
|
26
|
+
.enum(["suspended", "reinstated", "deleted", "restored", "purge_step", "purged"])
|
|
27
|
+
.describe(
|
|
28
|
+
"The transition: `suspended` and `reinstated`; `deleted` (by an operator, or by the account's owner) and `restored` inside the purge window; `purge_step`, one capability's rows erased during a purge, named in `step`; and `purged`, the erasure finished.",
|
|
29
|
+
);
|
|
30
|
+
export type UserLifecycleAction = z.output<typeof UserLifecycleAction>;
|
|
31
|
+
|
|
32
|
+
/** Who made the transition. */
|
|
33
|
+
export const UserLifecycleActorType = z
|
|
34
|
+
.enum(["control-plane", "user", "system"])
|
|
35
|
+
.describe(
|
|
36
|
+
"Who made the transition: `control-plane` (a management client, under a scoped grant), `user` (the account's own holder, deleting their own account), or `system` (the scheduled purge, with nobody calling).",
|
|
37
|
+
);
|
|
38
|
+
export type UserLifecycleActorType = z.output<typeof UserLifecycleActorType>;
|
|
39
|
+
|
|
40
|
+
/** One transition, as stored. */
|
|
41
|
+
export const UserLifecycleEvent = z
|
|
42
|
+
.object({
|
|
43
|
+
id: z
|
|
44
|
+
.number()
|
|
45
|
+
.int()
|
|
46
|
+
.describe("Primary key. Auto-incrementing, so a user's history reads in the order it was written."),
|
|
47
|
+
userId: z
|
|
48
|
+
.string()
|
|
49
|
+
.describe(
|
|
50
|
+
"The account this happened to. Not a foreign key: the row outlives the user it names, because a purge must leave its own record behind. Indexed.",
|
|
51
|
+
),
|
|
52
|
+
action: UserLifecycleAction.describe("What happened to the account."),
|
|
53
|
+
actorType: UserLifecycleActorType.describe("Who made the transition."),
|
|
54
|
+
actorId: z
|
|
55
|
+
.string()
|
|
56
|
+
.nullable()
|
|
57
|
+
.describe(
|
|
58
|
+
"The acting principal's id — the user's own id for a self-service deletion, the connection's for a management client. Null for `system`, and for a management client that named none.",
|
|
59
|
+
),
|
|
60
|
+
reason: z
|
|
61
|
+
.string()
|
|
62
|
+
.nullable()
|
|
63
|
+
.describe(
|
|
64
|
+
"Why, in the words of whoever made the transition. For a suspension this is the sentence the locked-out person is shown, so it is written for them. Null for a transition nobody had to justify — a purge, a self-service deletion.",
|
|
65
|
+
),
|
|
66
|
+
suspendedUntil: SQLiteDate.nullable().describe(
|
|
67
|
+
"For a `suspended` row, when that suspension ends by itself; null for one that lasts until a reinstatement, and for every other action. Ms-epoch in SQLite.",
|
|
68
|
+
),
|
|
69
|
+
step: z
|
|
70
|
+
.string()
|
|
71
|
+
.nullable()
|
|
72
|
+
.describe(
|
|
73
|
+
"For a `purge_step` row, the capability whose rows that step erased — the purge's step name. Null for every other action.",
|
|
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
|
+
),
|
|
78
|
+
createdAt: SQLiteDate.describe("When the transition happened. Ms-epoch in SQLite; a `Date` in app code."),
|
|
79
|
+
})
|
|
80
|
+
.describe(
|
|
81
|
+
"One transition in `pithy_auth_user_lifecycle`: an account suspended, reinstated, deleted, restored or purged, with who did it and why.",
|
|
82
|
+
);
|
|
83
|
+
export type UserLifecycleEvent = z.output<typeof UserLifecycleEvent>;
|