@pithy-sh/auth 0.9.0 → 0.10.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/audit/actions.d.ts +21 -0
- package/dist/audit/actions.d.ts.map +1 -1
- package/dist/audit/actions.js +22 -1
- package/dist/audit/emit.js +1 -1
- package/dist/capability.d.ts +26 -1
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +23 -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 +28 -2
- package/dist/data/tables.d.ts.map +1 -1
- package/dist/data/tables.js +5 -3
- package/dist/data/userLifecycle.d.ts +61 -0
- package/dist/data/userLifecycle.d.ts.map +1 -0
- package/dist/data/userLifecycle.js +50 -0
- package/dist/http/guards.d.ts +23 -1
- package/dist/http/guards.d.ts.map +1 -1
- package/dist/http/guards.js +28 -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 +5 -0
- package/dist/http/middleware.d.ts.map +1 -1
- package/dist/http/middleware.js +47 -6
- 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/routes.d.ts.map +1 -1
- package/dist/http/routes.js +20 -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/enforce.d.ts +40 -0
- package/dist/lifecycle/enforce.d.ts.map +1 -0
- package/dist/lifecycle/enforce.js +70 -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/request.d.ts +15 -0
- package/dist/lifecycle/request.d.ts.map +1 -0
- package/dist/lifecycle/request.js +27 -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 +132 -0
- package/dist/lifecycle/transitions.d.ts.map +1 -0
- package/dist/lifecycle/transitions.js +349 -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/set.d.ts +2 -1
- package/dist/migrations/set.d.ts.map +1 -1
- package/dist/migrations/set.js +4 -2
- package/dist/peer.d.ts +4 -0
- package/dist/peer.d.ts.map +1 -1
- 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 +105 -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 +23 -0
- package/src/audit/emit.ts +1 -1
- package/src/capability.ts +125 -54
- 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 +80 -0
- package/src/http/guards.ts +29 -1
- package/src/http/lifecycleGate.ts +78 -0
- package/src/http/middleware.ts +61 -2
- package/src/http/providerRefusal.ts +10 -0
- package/src/http/resolve.ts +8 -3
- package/src/http/routes.ts +38 -1
- package/src/instance/auth.ts +69 -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/enforce.ts +89 -0
- package/src/lifecycle/hooks.ts +54 -0
- package/src/lifecycle/request.ts +31 -0
- package/src/lifecycle/state.ts +101 -0
- package/src/lifecycle/transitions.ts +483 -0
- package/src/migrations/0004_user_lifecycle.ts +68 -0
- package/src/migrations/set.ts +3 -1
- 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/capability.ts
CHANGED
|
@@ -22,6 +22,7 @@ import { createAuthRoutes } from "./http/routes";
|
|
|
22
22
|
import type { GithubUserInfoResolver } from "./instance/githubUserInfo";
|
|
23
23
|
import { AuthPlugin, assertAdditivePlugins } from "./instance/plugins";
|
|
24
24
|
import { authSecretsRegistryFor, inapplicableProviderSecrets } from "./instance/secrets";
|
|
25
|
+
import type { UserLifecycleHooks } from "./lifecycle/hooks";
|
|
25
26
|
import { AUTH_MIGRATION_ORDER } from "./migrations/0001_init";
|
|
26
27
|
import { authPluginPlan } from "./migrations/pluginTables";
|
|
27
28
|
import { AUTH_MIGRATIONS } from "./migrations/set";
|
|
@@ -97,6 +98,9 @@ export const AuthConfig = z
|
|
|
97
98
|
github: ProviderToggle.prefault({}).describe(
|
|
98
99
|
"GitHub OAuth. Enable it, then store credentials as the `auth-github-credentials` secret. See docs/github-oauth.md.",
|
|
99
100
|
),
|
|
101
|
+
microsoft: ProviderToggle.prefault({}).describe(
|
|
102
|
+
"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.",
|
|
103
|
+
),
|
|
100
104
|
sessionExpiresIn: z
|
|
101
105
|
.number()
|
|
102
106
|
.int()
|
|
@@ -127,6 +131,41 @@ export const AuthConfig = z
|
|
|
127
131
|
.describe(
|
|
128
132
|
"When true, sign-in never provisions a new user — existing accounts only. Unknown emails get no email (anti-enumeration).",
|
|
129
133
|
),
|
|
134
|
+
retention: z
|
|
135
|
+
.object({
|
|
136
|
+
purgeAfterDays: z
|
|
137
|
+
.number()
|
|
138
|
+
.int()
|
|
139
|
+
.positive()
|
|
140
|
+
.default(30)
|
|
141
|
+
.describe(
|
|
142
|
+
"How many days a deleted account waits before its data is erased. Inside the window it cannot sign in and can be restored; after it, the purge erases its rows from every capability that holds them. Defaults to 30.",
|
|
143
|
+
),
|
|
144
|
+
})
|
|
145
|
+
.prefault({})
|
|
146
|
+
.describe(
|
|
147
|
+
"How long a deleted account is kept before it is purged. Self-service deletion and an operator's soft deletion both use this window.",
|
|
148
|
+
),
|
|
149
|
+
lifecycleEmails: z
|
|
150
|
+
.object({
|
|
151
|
+
accountSuspended: z
|
|
152
|
+
.boolean()
|
|
153
|
+
.default(true)
|
|
154
|
+
.describe("Email the person when their account is suspended, with the reason and any end date."),
|
|
155
|
+
accountReinstated: z.boolean().default(true).describe("Email the person when a suspension is lifted."),
|
|
156
|
+
deletionScheduled: z
|
|
157
|
+
.boolean()
|
|
158
|
+
.default(true)
|
|
159
|
+
.describe("Email the person when their account is deleted, with the date its data will be erased."),
|
|
160
|
+
deletionComplete: z
|
|
161
|
+
.boolean()
|
|
162
|
+
.default(true)
|
|
163
|
+
.describe("Email the person once their data has been erased. Sent before the address is."),
|
|
164
|
+
})
|
|
165
|
+
.prefault({})
|
|
166
|
+
.describe(
|
|
167
|
+
"Which account-lifecycle emails are sent. All four send by default, through `@pithy-sh/email`; switch one off by setting it to false.",
|
|
168
|
+
),
|
|
130
169
|
plugins: z
|
|
131
170
|
.array(AuthPlugin)
|
|
132
171
|
.default([])
|
|
@@ -164,6 +203,12 @@ export interface AuthWiring {
|
|
|
164
203
|
* Optional on the wiring for the reason `onSessionRevoked` is: no resolver is the ordinary composition.
|
|
165
204
|
*/
|
|
166
205
|
resolveScopes?: ScopeResolver | undefined;
|
|
206
|
+
/**
|
|
207
|
+
* The adopter's lifecycle hooks, or absent. See {@link UserLifecycleHooks}.
|
|
208
|
+
*
|
|
209
|
+
* Optional on the wiring for the reason `onSessionRevoked` is: no hook is the ordinary composition.
|
|
210
|
+
*/
|
|
211
|
+
lifecycleHooks?: UserLifecycleHooks | undefined;
|
|
167
212
|
}
|
|
168
213
|
|
|
169
214
|
/** The session a {@link ScopeResolver} is asked about — the one Better Auth just resolved for this request. */
|
|
@@ -205,62 +250,68 @@ export type SessionRevokedListener = (session: { id: string; userId: string }, d
|
|
|
205
250
|
* `PaymentsOptions`: everything describable stays in {@link AuthConfig}, and a resolver is a sibling key
|
|
206
251
|
* destructured off before the parse.
|
|
207
252
|
*/
|
|
208
|
-
export type AuthOptions = AuthConfigInput &
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
253
|
+
export type AuthOptions = AuthConfigInput &
|
|
254
|
+
UserLifecycleHooks & {
|
|
255
|
+
/**
|
|
256
|
+
* Resolve a GitHub identity yourself, replacing the kit's primary-only rule.
|
|
257
|
+
*
|
|
258
|
+
* The kit's default is deliberately conservative: it links on the **primary** address and nothing else,
|
|
259
|
+
* because GitHub never re-verifies and a verified secondary can only speak to the past. An adopter who
|
|
260
|
+
* wants a richer ladder — match a verified secondary, present a chooser on multiple matches — builds it
|
|
261
|
+
* here. `getUserInfo` is the only hook in this flow running before both fetches and before
|
|
262
|
+
* `mapProfileToUser`, and the only one holding the OAuth token.
|
|
263
|
+
*
|
|
264
|
+
* **Better Auth trusts what you return, verbatim.** It performs no independent check, so an
|
|
265
|
+
* `emailVerified: true` you did not read from GitHub is an account takeover: an attacker adds a
|
|
266
|
+
* victim's address to their own GitHub *unverified* and links to the victim's user. Return GitHub's
|
|
267
|
+
* real per-address flag, always.
|
|
268
|
+
*/
|
|
269
|
+
resolveGithubUserInfo?: GithubUserInfoResolver;
|
|
270
|
+
/**
|
|
271
|
+
* Told when a session is revoked, so state another capability keyed on it can go with it.
|
|
272
|
+
*
|
|
273
|
+
* **On the row, not on the sign-out route.** A sign-out, a revoke and an admin ending somebody's
|
|
274
|
+
* devices all delete the same row, so a listener hung off one endpoint would miss the others.
|
|
275
|
+
*
|
|
276
|
+
* The case this exists for is `@pithy-sh/organization`: its acting selection is keyed by session id
|
|
277
|
+
* and its schema says signing out must take it with it. Tenancy depends on auth and not the reverse,
|
|
278
|
+
* so the composition holding both is what joins them, and this is the join.
|
|
279
|
+
*
|
|
280
|
+
* **Non-fatal by contract.** The session is already gone when this runs; a failure here must not turn
|
|
281
|
+
* a completed sign-out into an error the caller retries, so the instance swallows what it throws.
|
|
282
|
+
*
|
|
283
|
+
* A function, so it is destructured off before `AuthConfig.parse` for the reason above.
|
|
284
|
+
*/
|
|
285
|
+
onSessionRevoked?: SessionRevokedListener;
|
|
286
|
+
/**
|
|
287
|
+
* Decide, per request, what this request's caller is — and so which scope gates it opens (#560).
|
|
288
|
+
*
|
|
289
|
+
* `leaderboard:submit`, `rating:record`, `leaderboard:admin` and `ledger:admin` are **attestations about
|
|
290
|
+
* the caller, not permissions granted to the user**: each says *this write came from the adopter's own
|
|
291
|
+
* trusted backend, not from a device*. This is where that is decided, and the seam does not dictate how.
|
|
292
|
+
* A backend calling over a service binding, one presenting a client certificate, and one presenting a
|
|
293
|
+
* short-lived token all answer the same question here. `verifyCallerToken` and `readClientCertificate`
|
|
294
|
+
* are the kit's helpers for the last two; `docs/server-authoritative.md` ranks the three.
|
|
295
|
+
*
|
|
296
|
+
* **Resolved per request, never cached** — a cached scope is a revocation that has not taken effect.
|
|
297
|
+
* **Failure is closed and never fatal**: a resolver that throws, or answers anything but a list of
|
|
298
|
+
* strings, leaves the request with no scopes and logs at warn, and the request goes on to whatever gate
|
|
299
|
+
* it was headed for. **No default**: without one the array is empty and nothing extra runs, so composing
|
|
300
|
+
* this changes nothing until an adopter opts in.
|
|
301
|
+
*
|
|
302
|
+
* A function, so it is destructured off before `AuthConfig.parse` for the reason above.
|
|
303
|
+
*/
|
|
304
|
+
resolveScopes?: ScopeResolver;
|
|
305
|
+
};
|
|
260
306
|
|
|
261
307
|
/** The auth capability, with its resolved config attached for inspection. */
|
|
262
308
|
export interface AuthCapability extends Capability {
|
|
263
309
|
authConfig: AuthConfig;
|
|
310
|
+
/**
|
|
311
|
+
* The adopter's account-lifecycle hooks, as `auth()` was handed them. Read by whatever runs a transition
|
|
312
|
+
* outside a request this capability serves — the purge Workflow (#622) fires `onUserPurged` through it.
|
|
313
|
+
*/
|
|
314
|
+
lifecycleHooks: UserLifecycleHooks;
|
|
264
315
|
/**
|
|
265
316
|
* What a capability composed beside this one reads an account through — `matchmaking`, `support`,
|
|
266
317
|
* `testers`. Found in their `compose` hooks, so none of them imports this package and a project without
|
|
@@ -311,8 +362,25 @@ export function auth(options: AuthOptions): AuthCapability {
|
|
|
311
362
|
// Zod 4 objects strip unknown keys silently, so a `resolveGithubUserInfo` handed to `AuthConfig.parse`
|
|
312
363
|
// would vanish with no error and the adopter's override would simply never run. `payments()` splits
|
|
313
364
|
// its `resolveSubject` out for the same reason.
|
|
314
|
-
const {
|
|
365
|
+
const {
|
|
366
|
+
resolveGithubUserInfo,
|
|
367
|
+
onSessionRevoked,
|
|
368
|
+
resolveScopes,
|
|
369
|
+
onUserSuspended,
|
|
370
|
+
onUserReinstated,
|
|
371
|
+
onUserDeleted,
|
|
372
|
+
onUserPurged,
|
|
373
|
+
...config
|
|
374
|
+
} = options;
|
|
315
375
|
const resolved = AuthConfig.parse(config);
|
|
376
|
+
// The lifecycle hooks, kept only where one was given, so an absent hook is an absent key rather than an
|
|
377
|
+
// `undefined` every reader has to tell apart from a hook.
|
|
378
|
+
const lifecycleHooks: UserLifecycleHooks = {
|
|
379
|
+
...(onUserSuspended ? { onUserSuspended } : {}),
|
|
380
|
+
...(onUserReinstated ? { onUserReinstated } : {}),
|
|
381
|
+
...(onUserDeleted ? { onUserDeleted } : {}),
|
|
382
|
+
...(onUserPurged ? { onUserPurged } : {}),
|
|
383
|
+
};
|
|
316
384
|
// What may be composed, before anything is built from the list. The four the kit composes are the
|
|
317
385
|
// sign-in this product promises and what the control-plane seam verifies against, so a list naming one
|
|
318
386
|
// of them is refused here by name rather than silently redefining a route at request time — and so is a
|
|
@@ -329,6 +397,7 @@ export function auth(options: AuthOptions): AuthCapability {
|
|
|
329
397
|
turnstile: undefined,
|
|
330
398
|
onSessionRevoked,
|
|
331
399
|
resolveScopes,
|
|
400
|
+
lifecycleHooks,
|
|
332
401
|
};
|
|
333
402
|
|
|
334
403
|
// Tier-1 edge rate limiter, contributed as middleware so it runs before session resolution.
|
|
@@ -436,6 +505,7 @@ export function auth(options: AuthOptions): AuthCapability {
|
|
|
436
505
|
apple: resolved.apple.enabled,
|
|
437
506
|
facebook: resolved.facebook.enabled,
|
|
438
507
|
github: resolved.github.enabled,
|
|
508
|
+
microsoft: resolved.microsoft.enabled,
|
|
439
509
|
},
|
|
440
510
|
// Per provider, beside the global one. A project may let email create accounts while a provider
|
|
441
511
|
// may not, and a screen with only `signUpEnabled` promises what that provider will refuse (#559).
|
|
@@ -444,6 +514,7 @@ export function auth(options: AuthOptions): AuthCapability {
|
|
|
444
514
|
apple: resolved.apple.allowSignUp,
|
|
445
515
|
facebook: resolved.facebook.allowSignUp,
|
|
446
516
|
github: resolved.github.allowSignUp,
|
|
517
|
+
microsoft: resolved.microsoft.allowSignUp,
|
|
447
518
|
},
|
|
448
519
|
otpLength: resolved.otpLength,
|
|
449
520
|
signUpEnabled: !resolved.disableSignUp,
|
|
@@ -470,7 +541,7 @@ export function auth(options: AuthOptions): AuthCapability {
|
|
|
470
541
|
seeds: [authExampleSeed, authDevSessionSeed],
|
|
471
542
|
});
|
|
472
543
|
|
|
473
|
-
return Object.assign(capability, { authConfig: resolved, authPeer });
|
|
544
|
+
return Object.assign(capability, { authConfig: resolved, authPeer, lifecycleHooks });
|
|
474
545
|
}
|
|
475
546
|
|
|
476
547
|
/** 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,80 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import { 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
|
+
createdAt: SQLiteDate.describe("When the transition happened. Ms-epoch in SQLite; a `Date` in app code."),
|
|
76
|
+
})
|
|
77
|
+
.describe(
|
|
78
|
+
"One transition in `pithy_auth_user_lifecycle`: an account suspended, reinstated, deleted, restored or purged, with who did it and why.",
|
|
79
|
+
);
|
|
80
|
+
export type UserLifecycleEvent = z.output<typeof UserLifecycleEvent>;
|
package/src/http/guards.ts
CHANGED
|
@@ -29,7 +29,7 @@ import type { ControlPlaneScope } from "@pithy-sh/core/src/controlPlane/scope/sc
|
|
|
29
29
|
* every legitimate management call, permanently, and **no credential could fix it** — there is no user
|
|
30
30
|
* to sign in as. `controlPlaneIsolation.workers.test.ts` pins both directions of that separation.
|
|
31
31
|
*
|
|
32
|
-
* ##
|
|
32
|
+
* ## Eight scopes, because these are eight different blast radii
|
|
33
33
|
*
|
|
34
34
|
* The temptation is one `auth:admin` flag, and on this capability it is the most dangerous version of
|
|
35
35
|
* that mistake. **Reading a user is a privacy operation; revoking their sessions is an availability
|
|
@@ -92,9 +92,34 @@ export const AUTH_USERS_LOGOUT_SCOPE: ControlPlaneScope = "auth:users:logout";
|
|
|
92
92
|
*/
|
|
93
93
|
export const AUTH_DEVICES_REVOKE_SCOPE: ControlPlaneScope = "auth:devices:revoke";
|
|
94
94
|
|
|
95
|
+
/**
|
|
96
|
+
* Suspend an account and reinstate it (#620, the routes in #621). Ending somebody's access is an availability
|
|
97
|
+
* operation on one person, and reversible — which is what separates it from deleting them, and why it is
|
|
98
|
+
* granted apart from both reading them and erasing them.
|
|
99
|
+
*/
|
|
100
|
+
export const AUTH_USERS_SUSPEND_SCOPE: ControlPlaneScope = "auth:users:suspend";
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Delete an account, restore one inside its purge window, and start a purge (#620, the routes in #622). The
|
|
104
|
+
* one scope on this surface whose worst case cannot be undone: once the window closes, the person's rows are
|
|
105
|
+
* gone from every capability that held them.
|
|
106
|
+
*/
|
|
107
|
+
export const AUTH_USERS_DELETE_SCOPE: ControlPlaneScope = "auth:users:delete";
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Export everything the kit holds about one account — the answer to an access request (#620, the route in
|
|
111
|
+
* #622). A disclosure, and a far larger one than reading the user: it carries every capability's rows about
|
|
112
|
+
* them, so it is granted on its own and audited as one.
|
|
113
|
+
*/
|
|
114
|
+
export const AUTH_USERS_EXPORT_SCOPE: ControlPlaneScope = "auth:users:export";
|
|
115
|
+
|
|
95
116
|
/**
|
|
96
117
|
* Every control-plane scope auth defines — what `pithy dashboard connect` offers for this capability,
|
|
97
118
|
* and the list a manifest or a doc quotes rather than re-typing.
|
|
119
|
+
*
|
|
120
|
+
* **The three lifecycle scopes are declared before the routes that require them.** The suspend, delete and
|
|
121
|
+
* export routes land in #621 and #622; declaring the vocabulary here, once, is what lets those issues build on
|
|
122
|
+
* one name each rather than three issues each choosing their own.
|
|
98
123
|
*/
|
|
99
124
|
export const AUTH_CONTROL_PLANE_SCOPES: readonly ControlPlaneScope[] = [
|
|
100
125
|
AUTH_USERS_READ_SCOPE,
|
|
@@ -102,6 +127,9 @@ export const AUTH_CONTROL_PLANE_SCOPES: readonly ControlPlaneScope[] = [
|
|
|
102
127
|
AUTH_SESSIONS_REVOKE_SCOPE,
|
|
103
128
|
AUTH_USERS_LOGOUT_SCOPE,
|
|
104
129
|
AUTH_DEVICES_REVOKE_SCOPE,
|
|
130
|
+
AUTH_USERS_SUSPEND_SCOPE,
|
|
131
|
+
AUTH_USERS_DELETE_SCOPE,
|
|
132
|
+
AUTH_USERS_EXPORT_SCOPE,
|
|
105
133
|
];
|
|
106
134
|
|
|
107
135
|
/**
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import type { PithyError } from "@pithy-sh/core/src/error/pithyError";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Where a suspended or deleted account meets Better Auth's own endpoints (#620).
|
|
8
|
+
*
|
|
9
|
+
* The session middleware refuses such an account an `AuthContext`, which closes every kit route. Better Auth's
|
|
10
|
+
* catch-all is the one place that does not ask: it resolves the session itself, so `/token` would mint a fresh
|
|
11
|
+
* access token for an account the rest of the Worker refuses. `handleBetterAuth` therefore refuses the
|
|
12
|
+
* middleware's verdict here too — everywhere except the endpoints below.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* The endpoints that never act as the account the presented credential names, relative to `basePath`.
|
|
17
|
+
*
|
|
18
|
+
* Signing out must always work. And each of the rest *starts* a session rather than using one, so a stale
|
|
19
|
+
* cookie a suspended person left on a shared machine must not stop somebody else signing in — the session
|
|
20
|
+
* that results is checked where it is created, in `session.create.before`. Everything else is refused by
|
|
21
|
+
* default: an endpoint nobody listed may be one a plugin added, and an account that may not act may not act
|
|
22
|
+
* there either.
|
|
23
|
+
*/
|
|
24
|
+
const ADMITTED_PREFIXES = [
|
|
25
|
+
"/sign-out",
|
|
26
|
+
"/sign-in/",
|
|
27
|
+
"/magic-link/verify",
|
|
28
|
+
"/email-otp/",
|
|
29
|
+
"/callback/",
|
|
30
|
+
"/oauth2/callback/",
|
|
31
|
+
] as const;
|
|
32
|
+
const ADMITTED_EXACT = new Set(["/jwks", "/ok", "/error"]);
|
|
33
|
+
|
|
34
|
+
/** Whether a refused account's credential may still reach this Better Auth endpoint (path relative to `basePath`). */
|
|
35
|
+
export function admitsRefusedAccount(path: string): boolean {
|
|
36
|
+
if (ADMITTED_EXACT.has(path)) return true;
|
|
37
|
+
return ADMITTED_PREFIXES.some((prefix) => path === prefix || path.startsWith(prefix));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* The redirect a refused magic link answers with: back to the screen the link named, carrying the code as
|
|
42
|
+
* `?error=`, exactly as Better Auth's own `redirectWithError` does for the refusals it raises itself
|
|
43
|
+
* (`plugins/magic-link/index.mjs`). `null` when the target is not one this Worker trusts, and the caller
|
|
44
|
+
* answers the refusal as JSON instead.
|
|
45
|
+
*
|
|
46
|
+
* A browser following a magic link is mid-navigation, so a 403 body would strand it on the API's origin
|
|
47
|
+
* with nothing to read; the adopter's screen is where the copy for this state lives. Better Auth has already
|
|
48
|
+
* checked the URLs by the time a session is refused, so the trust check is defense in depth — a refusal must
|
|
49
|
+
* not become an open redirect.
|
|
50
|
+
*/
|
|
51
|
+
export function lifecycleRedirect(
|
|
52
|
+
requestUrl: URL,
|
|
53
|
+
baseURL: string,
|
|
54
|
+
trustedOrigins: readonly string[],
|
|
55
|
+
refusal: PithyError,
|
|
56
|
+
): Response | null {
|
|
57
|
+
const named = requestUrl.searchParams.get("errorCallbackURL") || requestUrl.searchParams.get("callbackURL") || "/";
|
|
58
|
+
let target: URL;
|
|
59
|
+
try {
|
|
60
|
+
target = new URL(named, baseURL);
|
|
61
|
+
} catch {
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
const trusted = new Set([new URL(baseURL).origin, ...trustedOrigins.flatMap((origin) => originOf(origin))]);
|
|
65
|
+
if (!trusted.has(target.origin)) return null;
|
|
66
|
+
target.searchParams.set("error", refusal.payload.code);
|
|
67
|
+
return new Response(null, { status: 302, headers: { location: target.toString() } });
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** An origin's canonical form, or nothing for an entry that is not a URL (a bare deep-link scheme). */
|
|
71
|
+
function originOf(value: string): string[] {
|
|
72
|
+
try {
|
|
73
|
+
const origin = new URL(value).origin;
|
|
74
|
+
return origin === "null" ? [] : [origin];
|
|
75
|
+
} catch {
|
|
76
|
+
return [];
|
|
77
|
+
}
|
|
78
|
+
}
|