@pithy-sh/auth 0.14.1 → 0.15.1

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 (42) hide show
  1. package/README.md +4 -0
  2. package/dist/audit/actions.d.ts +32 -28
  3. package/dist/audit/actions.d.ts.map +1 -1
  4. package/dist/audit/actions.js +32 -28
  5. package/dist/audit/emit.d.ts +40 -34
  6. package/dist/audit/emit.d.ts.map +1 -1
  7. package/dist/audit/emit.js +45 -32
  8. package/dist/capability.js +1 -1
  9. package/dist/http/middleware.js +1 -1
  10. package/dist/http/providerFreshness.d.ts +30 -31
  11. package/dist/http/providerFreshness.d.ts.map +1 -1
  12. package/dist/http/providerFreshness.js +26 -31
  13. package/dist/http/recentSignIn.d.ts +57 -0
  14. package/dist/http/recentSignIn.d.ts.map +1 -0
  15. package/dist/http/recentSignIn.js +88 -0
  16. package/dist/http/routes.js +2 -2
  17. package/dist/index.d.ts +4 -2
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +2 -1
  20. package/dist/instance/auth.js +2 -2
  21. package/dist/mcp/http/routes.js +2 -2
  22. package/dist/test-utils/dropOrder.d.ts +26 -0
  23. package/dist/test-utils/dropOrder.d.ts.map +1 -0
  24. package/dist/test-utils/dropOrder.js +120 -0
  25. package/dist/test-utils/scopedBackend.d.ts +10 -6
  26. package/dist/test-utils/scopedBackend.d.ts.map +1 -1
  27. package/dist/test-utils/scopedBackend.js +40 -12
  28. package/dist/version.generated.d.ts +1 -1
  29. package/dist/version.generated.js +1 -1
  30. package/docs/account-lifecycle.md +1 -1
  31. package/docs/recent-sign-in.md +90 -0
  32. package/package.json +5 -5
  33. package/pithy.manifest.json +4 -0
  34. package/pithy.mcp.manifest.json +1 -0
  35. package/src/audit/actions.ts +32 -28
  36. package/src/audit/emit.ts +50 -34
  37. package/src/http/providerFreshness.ts +40 -42
  38. package/src/http/recentSignIn.ts +114 -0
  39. package/src/index.ts +4 -2
  40. package/src/test-utils/dropOrder.ts +139 -0
  41. package/src/test-utils/scopedBackend.ts +51 -13
  42. package/src/version.generated.ts +1 -1
package/src/audit/emit.ts CHANGED
@@ -36,8 +36,7 @@ async function safeEmit(emit: AuditEmit, event: Parameters<AuditEmit>[0]): Promi
36
36
  /**
37
37
  * What an endpoint must have *done* for its path event to be a success.
38
38
  *
39
- * **There is no "the response is its own evidence" member, and its removal is #627's last half.** A
40
- * non-2xx is sufficient evidence of a refusal and is nowhere near necessary: `/sign-out` answers
39
+ * **There is no "the response is its own evidence" member.** A non-2xx is sufficient evidence of a refusal and is nowhere near necessary: `/sign-out` answers
41
40
  * `200 {"success":true}` having deleted nothing, and `/email-otp/send-verification-otp` answers
42
41
  * `200 {"success":true}` having declined to send — Better Auth drops the verification row and returns
43
42
  * success rather than confirm that an address is registered (`plugins/email-otp/routes.mjs`), and the
@@ -85,21 +84,16 @@ export interface PathEvent {
85
84
  * The endpoints whose *path* names an audit action, what "success" means for each, and what a completed
86
85
  * response without it means instead.
87
86
  *
88
- * **A table rather than a chain of `if`s so the rule can be asserted over all of it.** #627's second
89
- * half was that every entry here wrote `outcome: "success"` for a request the endpoint had refused:
90
- * Better Auth catches an endpoint's `APIError` into a result and runs the `after` hooks over it anyway
91
- * (`better-auth/dist/api/dispatch.mjs`), so a 401 `/token` and a 400 `/email-otp/send-verification-otp`
92
- * both looked, from here, exactly like a request that worked. Naming the two paths somebody happened to
93
- * probe would have fixed those two; the exposure was every entry, including ones added later. So the
94
- * rule is `emitAfterRequest` reading the outcome, and the gate walks this table.
87
+ * **A table rather than a chain of `if`s so the rule can be asserted over all of it.** Better Auth
88
+ * catches an endpoint's `APIError` into a result and runs the `after` hooks over it anyway
89
+ * (`better-auth/dist/api/dispatch.mjs`), so a refused `/token` reaches the hook looking like one that
90
+ * worked. `emitAfterRequest` reads the outcome for every entry, and the gate walks this table.
95
91
  *
96
- * **Its third half was that a refusal can answer 200**, which the first fix could not see, and the
97
- * correction is the same shape: not a fifth branch for the endpoint somebody probed, but a column every
98
- * entry must fill. `evidence` has no "the response says so" member, so an entry that claims an outcome
99
- * it cannot evidence does not compile, and `emit.test.ts` walks the table asserting that an entry whose
100
- * evidence is absent never writes `success`.
92
+ * **A refusal can also answer 200**, so every entry fills `evidence`, which has no "the response says so"
93
+ * member: an entry that claims an outcome it cannot evidence does not compile, and `emit.test.ts` walks
94
+ * the table asserting that an entry whose evidence is absent never writes `success`.
101
95
  *
102
- * **No path maps to `oauth_linked`, and that is the correction #627 made first.** `/link-social` mints
96
+ * **No path maps to `oauth_linked`.** `/link-social` mints
103
97
  * a redirect, which is a request rather than an outcome; `/callback/:id` completes a sign-in *or* a link
104
98
  * and cannot be told apart by its path. The event that means "this provider can sign in as this user" is
105
99
  * the account row, so it is emitted from the row — see `emitProviderAccountChanged`.
@@ -372,7 +366,7 @@ export async function emitControlPlaneAction(
372
366
  userAgent?: string;
373
367
  requestId?: string;
374
368
  metadata?: Record<string, unknown>;
375
- /** `success` unless the call was refused (`denied`) or broke (`failure`) — #621 records both. */
369
+ /** `success` unless the call was refused (`denied`) or broke (`failure`). */
376
370
  outcome?: "success" | "denied" | "failure";
377
371
  },
378
372
  ): Promise<void> {
@@ -396,8 +390,8 @@ export async function emitControlPlaneAction(
396
390
  *
397
391
  * `anonymous`, because the caller has no session yet by definition. `denied` rather than `failure`: the
398
392
  * request was refused deliberately by a rule this Worker holds, not lost to a fault. `warning` rather
399
- * than `critical` — the other sign-in methods are working, which is the entire point of #381, so this is
400
- * notable rather than alert-worthy.
393
+ * than `critical` — the other sign-in methods are still working, so this is notable rather than
394
+ * alert-worthy.
401
395
  *
402
396
  * `metadata.provider` is the provider id and nothing else. The secret name is derivable from it and is
403
397
  * still not written: an audit row is long-lived and queryable, and naming a store entry in one is a map
@@ -428,7 +422,7 @@ export type ProviderChange = "link" | "unlink";
428
422
  * three. Parsing it into a named shape means the emitter below is holding a value that never contained
429
423
  * a provider token, so no later edit spreading "the account" into `metadata` can leak one — the guard
430
424
  * is structural instead of a rule somebody has to remember. The provider-asserted email is not here
431
- * either, and is not stored on this row to begin with: #627 does not widen what is retained.
425
+ * either, and is not stored on this row to begin with.
432
426
  */
433
427
  export const ProviderAccount = z
434
428
  .object({
@@ -456,9 +450,8 @@ const PROVIDER_CHANGE_ACTIONS: Record<ProviderChange, AuthAuditAction> = {
456
450
  *
457
451
  * **Called from the `account` database hooks, and the row is the point.** An operator's question is
458
452
  * "which providers can sign in as this account today, and when did that change"; the account table is
459
- * the answer to the first half, so the second half has to be recorded where that table changes. Wiring
460
- * this to an endpoint instead is what #627 was: `/link-social` recorded an intention as an outcome, and
461
- * `/unlink-account` recorded nothing. From the row, an abandoned consent screen emits nothing because
453
+ * the answer to the first half, so the second half has to be recorded where that table changes. An
454
+ * endpoint records an intention, not an outcome. From the row, an abandoned consent screen emits nothing because
462
455
  * nothing happened, and every path that ends a link — the unlink endpoint, and the cascade when a user
463
456
  * is deleted — is covered without naming any of them.
464
457
  *
@@ -467,11 +460,11 @@ const PROVIDER_CHANGE_ACTIONS: Record<ProviderChange, AuthAuditAction> = {
467
460
  * filter on.
468
461
  *
469
462
  * **The actor is whoever caused the change, never the account it concerns.** The row's `userId` says
470
- * *whose* link it was, which is not the same question and is carried in `metadata.userId` instead. The
471
- * first cut of #627 conflated them: `delete.after` fires on every removal, the user-deletion cascade
472
- * included, so an operator deleting somebody's account wrote rows saying that person had detached their
473
- * own providers — from the operator's IP. A trail that misattributes an actor is worse than one that is
474
- * silent, because it reads as evidence. Three cases, and only three:
463
+ * *whose* link it was, which is not the same question and is carried in `metadata.userId` instead.
464
+ * `delete.after` fires on every removal, the user-deletion cascade included, so an operator deleting
465
+ * somebody's account must not write rows saying that person detached their own providers. A trail that
466
+ * misattributes an actor is worse than one that is silent, because it reads as evidence. Three cases,
467
+ * and only three:
475
468
  *
476
469
  * - An authenticated caller — `/unlink-account`, a link from a signed-in session, an operator's console
477
470
  * endpoint — is `user`, named.
@@ -480,13 +473,12 @@ const PROVIDER_CHANGE_ACTIONS: Record<ProviderChange, AuthAuditAction> = {
480
473
  * - No request at all is `system`, with no actor id and no ip: there is no caller to name and nothing to
481
474
  * borrow one from.
482
475
  *
483
- * **A cascade is not a fourth case, and an earlier revision of this list said it was.** `deleteWithHooks`
484
- * resolves its context from `getCurrentAuthContext()`, which is async-scoped to the dispatch, so the
485
- * cascade `internalAdapter.deleteUser` runs carries whatever context reached it: an operator deleting
486
- * somebody through an endpoint is named as the actor of every row it writes, with their address, because
487
- * they caused every one of them. `system` is what *no request* looks like — a queue consumer, a script,
488
- * a migration — not what a cascade looks like, and the two were written down here as the same thing. The
489
- * rule that does hold everywhere is the one above it: the account's owner is never the actor merely for
476
+ * **A cascade is not a fourth case.** `deleteWithHooks` resolves its context from
477
+ * `getCurrentAuthContext()`, which is async-scoped to the dispatch, so the cascade
478
+ * `internalAdapter.deleteUser` runs carries whatever context reached it: an operator deleting somebody
479
+ * through an endpoint is named as the actor of every row it writes, with their address, because they
480
+ * caused every one of them. `system` is what *no request* looks like — a queue consumer, a script, a
481
+ * migration — not what a cascade looks like. The rule that does hold everywhere is the one above it: the account's owner is never the actor merely for
490
482
  * owning the row. Both shapes are driven in `emit.workers.test.ts` rather than asserted here.
491
483
  *
492
484
  * Unparseable input is dropped rather than thrown. The write it describes has already happened, and an
@@ -555,6 +547,30 @@ export async function emitProviderChangeNotFresh(
555
547
  });
556
548
  }
557
549
 
550
+ /**
551
+ * Emit a `recent_sign_in_refused` event — a signed-in caller reached an app route gated by
552
+ * `requireRecentSignIn` without a sign-in inside that route's window.
553
+ *
554
+ * `actorType: "user"`, for the same reason as {@link emitProviderChangeNotFresh}: the caller is
555
+ * authenticated and the user id is the whole value of the row. `metadata.purpose` is the app's own
556
+ * `domain/reason` for the route, which says what was being reached for.
557
+ */
558
+ export async function emitRecentSignInRefused(
559
+ emit: AuditEmit,
560
+ context: { purpose: string; userId: string; sessionId: string; headers: Headers | undefined },
561
+ ): Promise<void> {
562
+ await safeEmit(emit, {
563
+ action: AuthAuditActions.recentSignInRefused,
564
+ outcome: "denied",
565
+ severity: "warning",
566
+ actorType: "user",
567
+ actorId: context.userId,
568
+ sessionId: context.sessionId,
569
+ metadata: { purpose: context.purpose },
570
+ ...correlation(context.headers),
571
+ });
572
+ }
573
+
558
574
  /**
559
575
  * Emit a `handoff_issued` event: a redirect sign-in's session left on a deep link as a one-time code, or, denied,
560
576
  * a sign-in whose deep link carried no challenge, or a magic link to a custom scheme, so no code was issued.
@@ -5,26 +5,26 @@
5
5
  * **Changing which providers can sign you in requires a recent authentication.** Both directions.
6
6
  *
7
7
  * Attaching one grants permanent access — after it a sign-in resolves by account id and the email stops
8
- * mattering — and it is what `allowDifferentEmails: true` widened: before that, a provider could only be
9
- * linked to an account holding the same address, so a link was self-limiting. Detaching one is the
8
+ * mattering — and under `allowDifferentEmails: true` a provider can be linked to an account holding a
9
+ * different address, so a link is not self-limiting. Detaching one is the
10
10
  * smaller decision, but `allowUnlinkingAll: true` means an attacker inside the window can strip *every*
11
11
  * provider from an account. Neither belongs behind a credential whose age nobody checked.
12
12
  *
13
13
  * **Better Auth guards the two unevenly, and neither guard is one the kit can use.** In
14
14
  * `better-auth/dist/api/routes/account.mjs`, `/link-social` takes `use: [sessionMiddleware]` — any
15
15
  * session, any age — while `/unlink-account` takes `use: [freshSessionMiddleware]`, which reads
16
- * `session.createdAt` against a `freshAge` defaulting to 24 hours. So the more powerful operation was
17
- * the cheaper-guarded one, and the guarded one was checked against a value `/token/rotate` resets:
16
+ * `session.createdAt` against a `freshAge` defaulting to 24 hours. So the more powerful operation is the
17
+ * cheaper-guarded one, and the guarded one is checked against a value `/token/rotate` resets:
18
18
  * `internal-adapter.mjs:275` stamps `createdAt` after the caller's override, so a row's `created_at` is
19
19
  * the moment of its most recent rotation. Ordinary refreshing resets it; so does anyone holding a stolen
20
20
  * refresh token.
21
21
  *
22
- * **It reads `authenticatedAt`, not the session's `createdAt`, and that distinction is the whole of #558.**
23
- * The first version of this gate read session age. `/token/rotate` stamps a successor's `createdAt` with
24
- * the moment of the call, so session age is reset by every rotation — ordinary on the bearer path, and
25
- * available on demand to anyone holding a stolen refresh token. Two requests and the gate was open. The
26
- * question it means to ask is how recently the *person* authenticated, which is a different fact, stamped
27
- * once at sign-in and carried across rotations verbatim.
22
+ * **It reads `authenticatedAt`, not the session's `createdAt`.** `/token/rotate` stamps a successor's
23
+ * `createdAt` with the moment of the call, so session age is reset by every rotation — ordinary on the
24
+ * bearer path, and available on demand to anyone holding a stolen refresh token. The question is how
25
+ * recently the *person* authenticated, which is stamped once at sign-in and carried across rotations
26
+ * verbatim. The check itself is `authenticatedWithin` in `./recentSignIn`, which app routes share through
27
+ * `requireRecentSignIn`; this gate keeps its own window, code and audit event.
28
28
  *
29
29
  * **Not a Better Auth hook, and that is a framework constraint rather than a preference.** A `before` hook
30
30
  * runs ahead of the endpoint's own `sessionMiddleware`, so `ctx.context.session` is null at hook time; and
@@ -42,6 +42,7 @@ import { PithyError, UnauthorizedError } from "@pithy-sh/core/src/error/pithyErr
42
42
  import type { MiddlewareHandler } from "hono";
43
43
  import type { ProviderChange } from "../audit/emit";
44
44
  import { emitProviderChangeNotFresh } from "../audit/emit";
45
+ import { authenticatedWithin } from "./recentSignIn";
45
46
 
46
47
  /**
47
48
  * How recently the caller must have authenticated to change which providers sign them in: **fifteen minutes.**
@@ -60,47 +61,27 @@ import { emitProviderChangeNotFresh } from "../audit/emit";
60
61
  export const PROVIDER_CHANGE_FRESH_AGE_SECONDS = 15 * 60;
61
62
 
62
63
  /**
63
- * Whether an authentication is recent enough to authorize attaching a provider.
64
+ * Whether an authentication is recent enough: within `maxAgeSeconds`, which defaults to
65
+ * {@link PROVIDER_CHANGE_FRESH_AGE_SECONDS}.
64
66
  *
65
67
  * **Fails closed on anything it cannot read.** An absent, unparseable or future timestamp is not evidence
66
68
  * of a recent authentication — it is the absence of evidence — and a gate that reads "I cannot tell" as
67
- * "fresh" is one a row written before the column walks straight through. The future case matters as much
68
- * as the past: a window checked on one side only would pass any future value forever.
69
+ * "fresh" is one a row written before the column walks straight through.
69
70
  */
70
- export function authenticationIsFresh(authenticatedAt: Date | string | null | undefined, now: Date): boolean {
71
- if (authenticatedAt === null || authenticatedAt === undefined) return false;
72
- const at = authenticatedAt instanceof Date ? authenticatedAt : new Date(authenticatedAt);
73
- const millis = at.getTime();
74
- if (Number.isNaN(millis)) return false;
75
- const age = (now.getTime() - millis) / 1000;
76
- if (age < 0) return false;
77
- return age <= PROVIDER_CHANGE_FRESH_AGE_SECONDS;
71
+ export function authenticationIsFresh(
72
+ authenticatedAt: Date | string | null | undefined,
73
+ now: Date,
74
+ maxAgeSeconds: number = PROVIDER_CHANGE_FRESH_AGE_SECONDS,
75
+ ): boolean {
76
+ return authenticatedWithin(authenticatedAt, now, maxAgeSeconds);
78
77
  }
79
78
 
80
79
  /**
81
- * The gate, as Hono middleware on the kit's own route tree.
82
- *
83
- * **A pure read of `c.var.auth`.** `createSessionMiddleware` has already resolved this request's
84
- * credential — core registers every capability's middleware before any capability's routes — so resolving
85
- * it again would be a second D1 round trip for a fact the seam is holding. That is the argument
86
- * `AuthContext` already makes for `locale`.
87
- *
88
- * **No credential at all is 401, not this 403.** `auth/session_not_fresh` means "signed in, but not
89
- * recently enough"; a caller holding nothing cannot tell that from "not signed in" and will not know
90
- * whether to re-authenticate or to retry. The refusal is `requireAuth()`'s, word for word, so the two
91
- * surfaces answer an absent credential identically.
92
- *
93
- * **Recorded before the throw**, like `emitProviderUnavailable`: one refusal is somebody who left a tab
94
- * open, and a run of them against one user id is the incident. The trail has to hold it whether or not
95
- * anything logs the refusal.
96
- */
97
- /**
98
- * The refusal for attaching a provider without having authenticated recently.
80
+ * The refusal for changing a connected account without having authenticated recently.
99
81
  *
100
82
  * **Not `auth/forbidden`.** A client has to render this differently from every other 403, because the
101
83
  * remedy is specific and cheap — sign in again, then retry — and a generic "you are not allowed" sends
102
- * somebody to ask for a permission they already hold. `http/linkFreshness.ts` carries the argument for
103
- * the gate itself.
84
+ * somebody to ask for a permission they already hold.
104
85
  *
105
86
  * `message` says nothing was changed, because the caller is mid-flow and cannot otherwise tell whether
106
87
  * the link half-happened.
@@ -116,6 +97,23 @@ export function sessionNotFresh(): PithyError {
116
97
  });
117
98
  }
118
99
 
100
+ /**
101
+ * The gate, as Hono middleware on the kit's own route tree. `change` is which direction is being refused,
102
+ * carried into the audit row, because "somebody tried to attach an identity on a stale credential" and
103
+ * "somebody tried to strip one" are different things to read later.
104
+ *
105
+ * **A pure read of `c.var.auth`.** `createSessionMiddleware` has already resolved this request's
106
+ * credential — core registers every capability's middleware before any capability's routes — so resolving
107
+ * it again would be a second D1 round trip for a fact the seam is holding.
108
+ *
109
+ * **No credential at all is 401, not this 403.** `auth/session_not_fresh` means "signed in, but not
110
+ * recently enough"; a caller holding nothing cannot tell that from "not signed in" and will not know
111
+ * whether to re-authenticate or to retry.
112
+ *
113
+ * **Recorded before the throw**, like `emitProviderUnavailable`: one refusal is somebody who left a tab
114
+ * open, and a run of them against one user id is the incident. The trail has to hold it whether or not
115
+ * anything logs the refusal.
116
+ */
119
117
  /**
120
118
  * Which direction is being refused. Carried into the audit row, because "somebody tried to attach an
121
119
  * identity on a stale credential" and "somebody tried to strip one" are different things to read later.
@@ -132,7 +130,7 @@ export function requireFreshAuthentication(
132
130
  action: "Sign in and retry with a valid session or bearer token.",
133
131
  });
134
132
  }
135
- if (!authenticationIsFresh(auth.authenticatedAt, now())) {
133
+ if (!authenticationIsFresh(auth.authenticatedAt, now(), PROVIDER_CHANGE_FRESH_AGE_SECONDS)) {
136
134
  await emitProviderChangeNotFresh(c.var.emit, {
137
135
  change,
138
136
  userId: auth.userId,
@@ -0,0 +1,114 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { AuditAction } from "@pithy-sh/core/src/audit/auditEvent";
5
+ import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
6
+ import { PithyError } from "@pithy-sh/core/src/error/pithyError";
7
+ import type { MiddlewareHandler } from "hono";
8
+ import { z } from "zod";
9
+ import { emitRecentSignInRefused } from "../audit/emit";
10
+ import { requireAuth } from "./middleware";
11
+
12
+ /**
13
+ * Whether `authenticatedAt` falls within the last `maxAgeSeconds` of `now`, boundary included.
14
+ *
15
+ * `authenticatedAt` is the session's sign-in instant: stamped once at sign-in and carried across every
16
+ * rotation, unlike the session's `createdAt`, which a rotation restamps. So a rotation never passes a
17
+ * window that the sign-in did not.
18
+ *
19
+ * **Fails closed on anything it cannot read.** An absent, unparseable or future timestamp is not evidence
20
+ * of a recent sign-in. The future case matters as much as the past: a window checked on one side only
21
+ * would pass any future value forever.
22
+ */
23
+ export function authenticatedWithin(
24
+ authenticatedAt: Date | string | null | undefined,
25
+ now: Date,
26
+ maxAgeSeconds: number,
27
+ ): boolean {
28
+ if (authenticatedAt === null || authenticatedAt === undefined) return false;
29
+ const at = authenticatedAt instanceof Date ? authenticatedAt : new Date(authenticatedAt);
30
+ const millis = at.getTime();
31
+ if (Number.isNaN(millis)) return false;
32
+ const age = (now.getTime() - millis) / 1000;
33
+ if (age < 0) return false;
34
+ return age <= maxAgeSeconds;
35
+ }
36
+
37
+ /** What an app route's recent-sign-in gate is built from. Checked once, when the gate is built. */
38
+ export const RecentSignInOptions = z
39
+ .object({
40
+ maxAgeSeconds: z
41
+ .number()
42
+ .int()
43
+ .positive()
44
+ .describe("How recently the caller must have signed in, in seconds, for this route. A whole number above zero."),
45
+ purpose: AuditAction.describe(
46
+ "What the route protects, as the app's own `domain/reason` (`things/secret_revealed`). Recorded as `metadata.purpose` on the `auth/recent_sign_in_refused` audit row.",
47
+ ),
48
+ })
49
+ .describe("The window and the audit purpose of one `requireRecentSignIn` gate.");
50
+ export type RecentSignInOptions = z.infer<typeof RecentSignInOptions>;
51
+
52
+ /**
53
+ * The refusal for an app route reached without a recent enough sign-in: 403 `auth/recent_sign_in_required`.
54
+ *
55
+ * One code for every gated route, so a client renders one remedy — sign in again, then retry — wherever it
56
+ * meets it. `message` says nothing was changed, because the caller cannot otherwise tell whether the
57
+ * request half-happened.
58
+ */
59
+ export function recentSignInRequired(): PithyError {
60
+ return new PithyError({
61
+ code: "auth/recent_sign_in_required",
62
+ status: 403,
63
+ message: "Sign in again to continue. Nothing was changed.",
64
+ action:
65
+ "A deliberate gate: this route requires a sign-in within the window its `requireRecentSignIn` names. Sign in again, then retry.",
66
+ detail: "session authenticatedAt is outside the route's window, absent, or unreadable",
67
+ });
68
+ }
69
+
70
+ /**
71
+ * Gate an app route on a recent sign-in, with the window the route names.
72
+ *
73
+ * ```ts
74
+ * app.post(
75
+ * "/things/:id/secret",
76
+ * describeRoute({ … }),
77
+ * requireRecentSignIn({ maxAgeSeconds: 300, purpose: "things/secret_revealed" }),
78
+ * validate("param", ThingParams),
79
+ * handler,
80
+ * );
81
+ * ```
82
+ *
83
+ * - No credential answers exactly as `requireAuth()` does.
84
+ * - A session whose `authenticatedAt` is older than `maxAgeSeconds`, absent, unreadable or in the future is
85
+ * refused with {@link recentSignInRequired}, after an `auth/recent_sign_in_refused` audit row naming the
86
+ * user, the session and `purpose`.
87
+ * - A bearer session and a cookie session are judged by the same rule. A phone passes by signing in again,
88
+ * which starts a session with a new `authenticatedAt`; a rotation does not.
89
+ *
90
+ * `options` is checked here, so a `maxAgeSeconds` that is not a positive whole number or a `purpose` that is
91
+ * not `domain/reason` throws when the route is declared rather than on a request.
92
+ */
93
+ export function requireRecentSignIn(
94
+ options: RecentSignInOptions,
95
+ now: () => Date = () => new Date(),
96
+ ): MiddlewareHandler<PithyHonoEnv> {
97
+ const { maxAgeSeconds, purpose } = RecentSignInOptions.parse(options);
98
+ const authenticated = requireAuth();
99
+ return (c, next) =>
100
+ authenticated(c, async () => {
101
+ // `requireAuth()` has already refused a request with no `AuthContext`.
102
+ const auth = c.var.auth;
103
+ if (auth && authenticatedWithin(auth.authenticatedAt, now(), maxAgeSeconds)) return next();
104
+ if (auth) {
105
+ await emitRecentSignInRefused(c.var.emit, {
106
+ purpose,
107
+ userId: auth.userId,
108
+ sessionId: auth.sessionId,
109
+ headers: c.req.raw.headers,
110
+ });
111
+ }
112
+ throw recentSignInRequired();
113
+ });
114
+ }
package/src/index.ts CHANGED
@@ -3,8 +3,9 @@
3
3
 
4
4
  /**
5
5
  * The package entrypoint — the surface `pithy add auth` wires into `pithy.config.ts`. Deliberately
6
- * narrow: the capability factory, the `requireAuth()` gate other capabilities stack, and the data /
7
- * secret types an app or tool needs. Every other module is imported by deep path
6
+ * narrow: the capability factory, the `requireAuth()` gate other capabilities stack, the
7
+ * `requireRecentSignIn()` gate an app route stacks, and the data / secret types an app or tool needs.
8
+ * Every other module is imported by deep path
8
9
  * (`@pithy-sh/auth/src/...`) — this is the documented contract, not a barrel over the package.
9
10
  */
10
11
 
@@ -14,6 +15,7 @@ export { type Device, DevicePlatform } from "./data/device";
14
15
  export { type AuthDatabase, authDatabase } from "./data/tables";
15
16
  export { DEVICE_HEADERS, type DeviceMeta } from "./device/registry";
16
17
  export { requireAuth } from "./http/middleware";
18
+ export { RecentSignInOptions, requireRecentSignIn } from "./http/recentSignIn";
17
19
  export {
18
20
  AppleOAuthCredentials,
19
21
  AUTH_APPLE_CREDENTIALS,
@@ -0,0 +1,139 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ /** One foreign key, as `PRAGMA foreign_key_list` reports it: `table` holds a column that references `references`. */
5
+ export interface ForeignKey {
6
+ table: string;
7
+ references: string;
8
+ /** What deleting a referenced row does to `table`: `CASCADE`, `SET NULL`, `SET DEFAULT`, `RESTRICT` or `NO ACTION`. */
9
+ onDelete: string;
10
+ }
11
+
12
+ /**
13
+ * The order to drop `tables` in, so that no drop meets a table already gone.
14
+ *
15
+ * With foreign keys on, dropping a table deletes its rows first. A key that cascades deletes the referencing
16
+ * rows with them, which looks up every table the referencing table references and cascades on from there.
17
+ * A set null or set default key only rewrites the referencing column, which looks up the table being dropped
18
+ * and nothing past it. So a table is dropped before every table it references, and a self-reference is no
19
+ * constraint. Tables that reference each other in a cycle have no such order; they are ordered so that no
20
+ * cascade from a drop reaches a table that still names a dropped one, and refused when no order does.
21
+ *
22
+ * Names match as SQLite matches them, ignoring ASCII case, and the order names each table as `tables` does.
23
+ *
24
+ * The caller runs the drops in one batch under `PRAGMA defer_foreign_keys = on`, which is what lets the
25
+ * rows of a cycle go: each table's rows still reference the next table's until both are gone.
26
+ */
27
+ export function dropOrder(tables: readonly string[], foreignKeys: readonly ForeignKey[]): string[] {
28
+ const listed = new Map(tables.map((table) => [foldCase(table), table]));
29
+ const keys = foreignKeys.flatMap((key) => {
30
+ const table = listed.get(foldCase(key.table));
31
+ const references = listed.get(foldCase(key.references));
32
+ return table !== undefined && references !== undefined ? [{ ...key, table, references }] : [];
33
+ });
34
+ const position = new Map(tables.map((table, index) => [table, index]));
35
+ const listedOrder = (a: string, b: string) => (position.get(a) ?? 0) - (position.get(b) ?? 0);
36
+ const pending = components(tables, keys)
37
+ .map((component) => component.sort(listedOrder))
38
+ .sort((a, b) => listedOrder(a[0] ?? "", b[0] ?? ""));
39
+ const dropped = new Set<string>();
40
+ const order: string[] = [];
41
+ while (pending.length > 0) {
42
+ // Components form no cycle among themselves, so one always has no referrer left outside it.
43
+ const ready = pending.findIndex((component) =>
44
+ keys.every(
45
+ (key) => !component.includes(key.references) || component.includes(key.table) || dropped.has(key.table),
46
+ ),
47
+ );
48
+ const [component = []] = pending.splice(ready, 1);
49
+ const members = component.length === 1 ? component : orderCycle(component, keys);
50
+ for (const table of members) dropped.add(table);
51
+ order.push(...members);
52
+ }
53
+ return order;
54
+ }
55
+
56
+ /** The strongly connected components of the reference graph: each cycle together, every other table alone. */
57
+ function components(tables: readonly string[], keys: readonly ForeignKey[]): string[][] {
58
+ const index = new Map<string, number>();
59
+ const low = new Map<string, number>();
60
+ const stack: string[] = [];
61
+ const onStack = new Set<string>();
62
+ const found: string[][] = [];
63
+ const visit = (table: string): void => {
64
+ const own = index.size;
65
+ index.set(table, own);
66
+ low.set(table, own);
67
+ stack.push(table);
68
+ onStack.add(table);
69
+ for (const key of keys) {
70
+ if (key.table !== table) continue;
71
+ const parent = key.references;
72
+ if (!index.has(parent)) visit(parent);
73
+ else if (!onStack.has(parent)) continue;
74
+ low.set(table, Math.min(low.get(table) ?? own, low.get(parent) ?? own));
75
+ }
76
+ if (low.get(table) !== own) return;
77
+ const component: string[] = [];
78
+ for (let member = stack.pop(); member !== undefined; member = stack.pop()) {
79
+ onStack.delete(member);
80
+ component.push(member);
81
+ if (member === table) break;
82
+ }
83
+ found.push(component);
84
+ };
85
+ for (const table of tables) if (!index.has(table)) visit(table);
86
+ return found;
87
+ }
88
+
89
+ /** The members of one cycle in an order no drop fails on, searched in listed order first. */
90
+ function orderCycle(members: readonly string[], allKeys: readonly ForeignKey[]): string[] {
91
+ const keys = allKeys.filter((key) => members.includes(key.table) && members.includes(key.references));
92
+ const dead = new Set<string>();
93
+ const search = (left: readonly string[]): string[] | undefined => {
94
+ if (left.length === 0) return [];
95
+ const state = JSON.stringify(left);
96
+ if (dead.has(state)) return undefined;
97
+ for (const table of left) {
98
+ if (!safeToDrop(table, left, keys)) continue;
99
+ const rest = search(left.filter((other) => other !== table));
100
+ if (rest) return [table, ...rest];
101
+ }
102
+ dead.add(state);
103
+ return undefined;
104
+ };
105
+ const order = search(members);
106
+ if (order) return order;
107
+ const named = members.map((table) => `"${table}"`).join(", ");
108
+ throw new Error(`No drop order clears ${named}: every order cascades into a table that names one already dropped.`);
109
+ }
110
+
111
+ /**
112
+ * Whether `table` can go while `left` remain: every table a cascade from it reaches, itself included when the
113
+ * cascade comes back, still has every table it references.
114
+ */
115
+ function safeToDrop(table: string, left: readonly string[], keys: readonly ForeignKey[]): boolean {
116
+ const present = new Set(left);
117
+ const reached = new Set<string>();
118
+ const frontier = [table];
119
+ for (let current = frontier.pop(); current !== undefined; current = frontier.pop()) {
120
+ for (const key of keys) {
121
+ if (key.references !== current || !cascades(key) || !present.has(key.table) || reached.has(key.table)) continue;
122
+ reached.add(key.table);
123
+ frontier.push(key.table);
124
+ }
125
+ }
126
+ return [...reached].every((reachedTable) =>
127
+ keys.every((key) => key.table !== reachedTable || present.has(key.references)),
128
+ );
129
+ }
130
+
131
+ /** A key that deletes the referencing rows when a referenced row is deleted. */
132
+ function cascades(key: ForeignKey): boolean {
133
+ return key.onDelete.toUpperCase() === "CASCADE";
134
+ }
135
+
136
+ /** A table name as SQLite compares it: ASCII letters fold to lower case, nothing else does. */
137
+ function foldCase(name: string): string {
138
+ return name.replace(/[A-Z]/g, (letter) => letter.toLowerCase());
139
+ }