@pithy-sh/auth 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) 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/src/audit/actions.ts +32 -28
  34. package/src/audit/emit.ts +50 -34
  35. package/src/http/providerFreshness.ts +40 -42
  36. package/src/http/recentSignIn.ts +114 -0
  37. package/src/index.ts +4 -2
  38. package/src/test-utils/dropOrder.ts +139 -0
  39. package/src/test-utils/scopedBackend.ts +51 -13
  40. package/src/version.generated.ts +1 -1
@@ -28,21 +28,16 @@ async function safeEmit(emit, event) {
28
28
  * The endpoints whose *path* names an audit action, what "success" means for each, and what a completed
29
29
  * response without it means instead.
30
30
  *
31
- * **A table rather than a chain of `if`s so the rule can be asserted over all of it.** #627's second
32
- * half was that every entry here wrote `outcome: "success"` for a request the endpoint had refused:
33
- * Better Auth catches an endpoint's `APIError` into a result and runs the `after` hooks over it anyway
34
- * (`better-auth/dist/api/dispatch.mjs`), so a 401 `/token` and a 400 `/email-otp/send-verification-otp`
35
- * both looked, from here, exactly like a request that worked. Naming the two paths somebody happened to
36
- * probe would have fixed those two; the exposure was every entry, including ones added later. So the
37
- * rule is `emitAfterRequest` reading the outcome, and the gate walks this table.
31
+ * **A table rather than a chain of `if`s so the rule can be asserted over all of it.** Better Auth
32
+ * catches an endpoint's `APIError` into a result and runs the `after` hooks over it anyway
33
+ * (`better-auth/dist/api/dispatch.mjs`), so a refused `/token` reaches the hook looking like one that
34
+ * worked. `emitAfterRequest` reads the outcome for every entry, and the gate walks this table.
38
35
  *
39
- * **Its third half was that a refusal can answer 200**, which the first fix could not see, and the
40
- * correction is the same shape: not a fifth branch for the endpoint somebody probed, but a column every
41
- * entry must fill. `evidence` has no "the response says so" member, so an entry that claims an outcome
42
- * it cannot evidence does not compile, and `emit.test.ts` walks the table asserting that an entry whose
43
- * evidence is absent never writes `success`.
36
+ * **A refusal can also answer 200**, so every entry fills `evidence`, which has no "the response says so"
37
+ * member: an entry that claims an outcome it cannot evidence does not compile, and `emit.test.ts` walks
38
+ * the table asserting that an entry whose evidence is absent never writes `success`.
44
39
  *
45
- * **No path maps to `oauth_linked`, and that is the correction #627 made first.** `/link-social` mints
40
+ * **No path maps to `oauth_linked`.** `/link-social` mints
46
41
  * a redirect, which is a request rather than an outcome; `/callback/:id` completes a sign-in *or* a link
47
42
  * and cannot be told apart by its path. The event that means "this provider can sign in as this user" is
48
43
  * the account row, so it is emitted from the row — see `emitProviderAccountChanged`.
@@ -277,8 +272,8 @@ async function emitControlPlaneAction(emit, event) {
277
272
  *
278
273
  * `anonymous`, because the caller has no session yet by definition. `denied` rather than `failure`: the
279
274
  * request was refused deliberately by a rule this Worker holds, not lost to a fault. `warning` rather
280
- * than `critical` — the other sign-in methods are working, which is the entire point of #381, so this is
281
- * notable rather than alert-worthy.
275
+ * than `critical` — the other sign-in methods are still working, so this is notable rather than
276
+ * alert-worthy.
282
277
  *
283
278
  * `metadata.provider` is the provider id and nothing else. The secret name is derivable from it and is
284
279
  * still not written: an audit row is long-lived and queryable, and naming a store entry in one is a map
@@ -302,7 +297,7 @@ async function emitProviderUnavailable(emit, context) {
302
297
  * three. Parsing it into a named shape means the emitter below is holding a value that never contained
303
298
  * a provider token, so no later edit spreading "the account" into `metadata` can leak one — the guard
304
299
  * is structural instead of a rule somebody has to remember. The provider-asserted email is not here
305
- * either, and is not stored on this row to begin with: #627 does not widen what is retained.
300
+ * either, and is not stored on this row to begin with.
306
301
  */
307
302
  const ProviderAccount = z.object({
308
303
  id: z.string().describe("The account row's primary key — which link was made or broken."),
@@ -324,9 +319,8 @@ const PROVIDER_CHANGE_ACTIONS = {
324
319
  *
325
320
  * **Called from the `account` database hooks, and the row is the point.** An operator's question is
326
321
  * "which providers can sign in as this account today, and when did that change"; the account table is
327
- * the answer to the first half, so the second half has to be recorded where that table changes. Wiring
328
- * this to an endpoint instead is what #627 was: `/link-social` recorded an intention as an outcome, and
329
- * `/unlink-account` recorded nothing. From the row, an abandoned consent screen emits nothing because
322
+ * the answer to the first half, so the second half has to be recorded where that table changes. An
323
+ * endpoint records an intention, not an outcome. From the row, an abandoned consent screen emits nothing because
330
324
  * nothing happened, and every path that ends a link — the unlink endpoint, and the cascade when a user
331
325
  * is deleted — is covered without naming any of them.
332
326
  *
@@ -335,11 +329,11 @@ const PROVIDER_CHANGE_ACTIONS = {
335
329
  * filter on.
336
330
  *
337
331
  * **The actor is whoever caused the change, never the account it concerns.** The row's `userId` says
338
- * *whose* link it was, which is not the same question and is carried in `metadata.userId` instead. The
339
- * first cut of #627 conflated them: `delete.after` fires on every removal, the user-deletion cascade
340
- * included, so an operator deleting somebody's account wrote rows saying that person had detached their
341
- * own providers — from the operator's IP. A trail that misattributes an actor is worse than one that is
342
- * silent, because it reads as evidence. Three cases, and only three:
332
+ * *whose* link it was, which is not the same question and is carried in `metadata.userId` instead.
333
+ * `delete.after` fires on every removal, the user-deletion cascade included, so an operator deleting
334
+ * somebody's account must not write rows saying that person detached their own providers. A trail that
335
+ * misattributes an actor is worse than one that is silent, because it reads as evidence. Three cases,
336
+ * and only three:
343
337
  *
344
338
  * - An authenticated caller — `/unlink-account`, a link from a signed-in session, an operator's console
345
339
  * endpoint — is `user`, named.
@@ -348,13 +342,12 @@ const PROVIDER_CHANGE_ACTIONS = {
348
342
  * - No request at all is `system`, with no actor id and no ip: there is no caller to name and nothing to
349
343
  * borrow one from.
350
344
  *
351
- * **A cascade is not a fourth case, and an earlier revision of this list said it was.** `deleteWithHooks`
352
- * resolves its context from `getCurrentAuthContext()`, which is async-scoped to the dispatch, so the
353
- * cascade `internalAdapter.deleteUser` runs carries whatever context reached it: an operator deleting
354
- * somebody through an endpoint is named as the actor of every row it writes, with their address, because
355
- * they caused every one of them. `system` is what *no request* looks like — a queue consumer, a script,
356
- * a migration — not what a cascade looks like, and the two were written down here as the same thing. The
357
- * rule that does hold everywhere is the one above it: the account's owner is never the actor merely for
345
+ * **A cascade is not a fourth case.** `deleteWithHooks` resolves its context from
346
+ * `getCurrentAuthContext()`, which is async-scoped to the dispatch, so the cascade
347
+ * `internalAdapter.deleteUser` runs carries whatever context reached it: an operator deleting somebody
348
+ * through an endpoint is named as the actor of every row it writes, with their address, because they
349
+ * caused every one of them. `system` is what *no request* looks like — a queue consumer, a script, a
350
+ * 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
358
351
  * owning the row. Both shapes are driven in `emit.workers.test.ts` rather than asserted here.
359
352
  *
360
353
  * Unparseable input is dropped rather than thrown. The write it describes has already happened, and an
@@ -409,6 +402,26 @@ async function emitProviderChangeNotFresh(emit, context) {
409
402
  });
410
403
  }
411
404
  /**
405
+ * Emit a `recent_sign_in_refused` event — a signed-in caller reached an app route gated by
406
+ * `requireRecentSignIn` without a sign-in inside that route's window.
407
+ *
408
+ * `actorType: "user"`, for the same reason as {@link emitProviderChangeNotFresh}: the caller is
409
+ * authenticated and the user id is the whole value of the row. `metadata.purpose` is the app's own
410
+ * `domain/reason` for the route, which says what was being reached for.
411
+ */
412
+ async function emitRecentSignInRefused(emit, context) {
413
+ await safeEmit(emit, {
414
+ action: AuthAuditActions.recentSignInRefused,
415
+ outcome: "denied",
416
+ severity: "warning",
417
+ actorType: "user",
418
+ actorId: context.userId,
419
+ sessionId: context.sessionId,
420
+ metadata: { purpose: context.purpose },
421
+ ...correlation(context.headers)
422
+ });
423
+ }
424
+ /**
412
425
  * Emit a `handoff_issued` event: a redirect sign-in's session left on a deep link as a one-time code, or, denied,
413
426
  * a sign-in whose deep link carried no challenge, or a magic link to a custom scheme, so no code was issued.
414
427
  */
@@ -466,4 +479,4 @@ async function emitDenied(emit, context) {
466
479
  });
467
480
  }
468
481
  //#endregion
469
- export { EVIDENCE_OBSERVERS, PATH_EVENTS, ProviderAccount, correlation, emitAfterRequest, emitControlPlaneAction, emitDenied, emitDeviceRevoked, emitHandoffExchanged, emitHandoffIssued, emitProviderAccountChanged, emitProviderChangeNotFresh, emitProviderUnavailable, emitTokenRefresh, emitTokenReuseDetected, wasRefused };
482
+ export { EVIDENCE_OBSERVERS, PATH_EVENTS, ProviderAccount, correlation, emitAfterRequest, emitControlPlaneAction, emitDenied, emitDeviceRevoked, emitHandoffExchanged, emitHandoffIssued, emitProviderAccountChanged, emitProviderChangeNotFresh, emitProviderUnavailable, emitRecentSignInRefused, emitTokenRefresh, emitTokenReuseDetected, wasRefused };
@@ -6,11 +6,11 @@ import { baseURLResolver } from "./http/baseUrl.js";
6
6
  import { publishSameOrigin } from "./http/csrf.js";
7
7
  import { authSecretsRegistryFor, inapplicableProviderSecrets } from "./instance/secrets.js";
8
8
  import { authDevSessionSeed } from "./seeds/devSession.js";
9
+ import { createSessionMiddleware } from "./http/middleware.js";
9
10
  import { AuthPlugin, assertAdditivePlugins } from "./instance/plugins.js";
10
11
  import { getAuthInstance } from "./http/resolve.js";
11
12
  import { registerDevLoginRoute } from "./http/devLoginRoute.js";
12
13
  import { authAdminRoutes } from "./http/guards.js";
13
- import { createSessionMiddleware } from "./http/middleware.js";
14
14
  import { createRateLimitMiddleware } from "./http/rateLimit.js";
15
15
  import { authWorkflows } from "./purge/specs.js";
16
16
  import { createAuthRoutes } from "./http/routes.js";
@@ -4,8 +4,8 @@ import { authDatabase } from "../data/tables.js";
4
4
  import { dispatchedAuth } from "../mcp/dispatch.js";
5
5
  import { LifecycleColumns } from "../lifecycle/state.js";
6
6
  import { lifecycleRefusalFor, noteRefusal, noticedRefusal, suspendedHolder } from "../lifecycle/enforce.js";
7
- import { getAuthInstance, resolveDb } from "./resolve.js";
8
7
  import { withResignedCredentials } from "./credentialResign.js";
8
+ import { getAuthInstance, resolveDb } from "./resolve.js";
9
9
  import { InternalError, UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
10
10
  import { isLocale } from "@pithy-sh/core/src/i18n/locale";
11
11
  import { AuthContext } from "@pithy-sh/core/src/http/authContext";
@@ -4,26 +4,26 @@
4
4
  * **Changing which providers can sign you in requires a recent authentication.** Both directions.
5
5
  *
6
6
  * Attaching one grants permanent access — after it a sign-in resolves by account id and the email stops
7
- * mattering — and it is what `allowDifferentEmails: true` widened: before that, a provider could only be
8
- * linked to an account holding the same address, so a link was self-limiting. Detaching one is the
7
+ * mattering — and under `allowDifferentEmails: true` a provider can be linked to an account holding a
8
+ * different address, so a link is not self-limiting. Detaching one is the
9
9
  * smaller decision, but `allowUnlinkingAll: true` means an attacker inside the window can strip *every*
10
10
  * provider from an account. Neither belongs behind a credential whose age nobody checked.
11
11
  *
12
12
  * **Better Auth guards the two unevenly, and neither guard is one the kit can use.** In
13
13
  * `better-auth/dist/api/routes/account.mjs`, `/link-social` takes `use: [sessionMiddleware]` — any
14
14
  * session, any age — while `/unlink-account` takes `use: [freshSessionMiddleware]`, which reads
15
- * `session.createdAt` against a `freshAge` defaulting to 24 hours. So the more powerful operation was
16
- * the cheaper-guarded one, and the guarded one was checked against a value `/token/rotate` resets:
15
+ * `session.createdAt` against a `freshAge` defaulting to 24 hours. So the more powerful operation is the
16
+ * cheaper-guarded one, and the guarded one is checked against a value `/token/rotate` resets:
17
17
  * `internal-adapter.mjs:275` stamps `createdAt` after the caller's override, so a row's `created_at` is
18
18
  * the moment of its most recent rotation. Ordinary refreshing resets it; so does anyone holding a stolen
19
19
  * refresh token.
20
20
  *
21
- * **It reads `authenticatedAt`, not the session's `createdAt`, and that distinction is the whole of #558.**
22
- * The first version of this gate read session age. `/token/rotate` stamps a successor's `createdAt` with
23
- * the moment of the call, so session age is reset by every rotation — ordinary on the bearer path, and
24
- * available on demand to anyone holding a stolen refresh token. Two requests and the gate was open. The
25
- * question it means to ask is how recently the *person* authenticated, which is a different fact, stamped
26
- * once at sign-in and carried across rotations verbatim.
21
+ * **It reads `authenticatedAt`, not the session's `createdAt`.** `/token/rotate` stamps a successor's
22
+ * `createdAt` with the moment of the call, so session age is reset by every rotation — ordinary on the
23
+ * bearer path, and available on demand to anyone holding a stolen refresh token. The question is how
24
+ * recently the *person* authenticated, which is stamped once at sign-in and carried across rotations
25
+ * verbatim. The check itself is `authenticatedWithin` in `./recentSignIn`, which app routes share through
26
+ * `requireRecentSignIn`; this gate keeps its own window, code and audit event.
27
27
  *
28
28
  * **Not a Better Auth hook, and that is a framework constraint rather than a preference.** A `before` hook
29
29
  * runs ahead of the endpoint's own `sessionMiddleware`, so `ctx.context.session` is null at hook time; and
@@ -55,43 +55,42 @@ import type { ProviderChange } from "../audit/emit";
55
55
  */
56
56
  export declare const PROVIDER_CHANGE_FRESH_AGE_SECONDS: number;
57
57
  /**
58
- * Whether an authentication is recent enough to authorize attaching a provider.
58
+ * Whether an authentication is recent enough: within `maxAgeSeconds`, which defaults to
59
+ * {@link PROVIDER_CHANGE_FRESH_AGE_SECONDS}.
59
60
  *
60
61
  * **Fails closed on anything it cannot read.** An absent, unparseable or future timestamp is not evidence
61
62
  * of a recent authentication — it is the absence of evidence — and a gate that reads "I cannot tell" as
62
- * "fresh" is one a row written before the column walks straight through. The future case matters as much
63
- * as the past: a window checked on one side only would pass any future value forever.
63
+ * "fresh" is one a row written before the column walks straight through.
64
64
  */
65
- export declare function authenticationIsFresh(authenticatedAt: Date | string | null | undefined, now: Date): boolean;
65
+ export declare function authenticationIsFresh(authenticatedAt: Date | string | null | undefined, now: Date, maxAgeSeconds?: number): boolean;
66
66
  /**
67
- * The gate, as Hono middleware on the kit's own route tree.
67
+ * The refusal for changing a connected account without having authenticated recently.
68
+ *
69
+ * **Not `auth/forbidden`.** A client has to render this differently from every other 403, because the
70
+ * remedy is specific and cheap — sign in again, then retry — and a generic "you are not allowed" sends
71
+ * somebody to ask for a permission they already hold.
72
+ *
73
+ * `message` says nothing was changed, because the caller is mid-flow and cannot otherwise tell whether
74
+ * the link half-happened.
75
+ */
76
+ export declare function sessionNotFresh(): PithyError;
77
+ /**
78
+ * The gate, as Hono middleware on the kit's own route tree. `change` is which direction is being refused,
79
+ * carried into the audit row, because "somebody tried to attach an identity on a stale credential" and
80
+ * "somebody tried to strip one" are different things to read later.
68
81
  *
69
82
  * **A pure read of `c.var.auth`.** `createSessionMiddleware` has already resolved this request's
70
83
  * credential — core registers every capability's middleware before any capability's routes — so resolving
71
- * it again would be a second D1 round trip for a fact the seam is holding. That is the argument
72
- * `AuthContext` already makes for `locale`.
84
+ * it again would be a second D1 round trip for a fact the seam is holding.
73
85
  *
74
86
  * **No credential at all is 401, not this 403.** `auth/session_not_fresh` means "signed in, but not
75
87
  * recently enough"; a caller holding nothing cannot tell that from "not signed in" and will not know
76
- * whether to re-authenticate or to retry. The refusal is `requireAuth()`'s, word for word, so the two
77
- * surfaces answer an absent credential identically.
88
+ * whether to re-authenticate or to retry.
78
89
  *
79
90
  * **Recorded before the throw**, like `emitProviderUnavailable`: one refusal is somebody who left a tab
80
91
  * open, and a run of them against one user id is the incident. The trail has to hold it whether or not
81
92
  * anything logs the refusal.
82
93
  */
83
- /**
84
- * The refusal for attaching a provider without having authenticated recently.
85
- *
86
- * **Not `auth/forbidden`.** A client has to render this differently from every other 403, because the
87
- * remedy is specific and cheap — sign in again, then retry — and a generic "you are not allowed" sends
88
- * somebody to ask for a permission they already hold. `http/linkFreshness.ts` carries the argument for
89
- * the gate itself.
90
- *
91
- * `message` says nothing was changed, because the caller is mid-flow and cannot otherwise tell whether
92
- * the link half-happened.
93
- */
94
- export declare function sessionNotFresh(): PithyError;
95
94
  /**
96
95
  * Which direction is being refused. Carried into the audit row, because "somebody tried to attach an
97
96
  * identity on a stale credential" and "somebody tried to strip one" are different things to read later.
@@ -1 +1 @@
1
- {"version":3,"file":"providerFreshness.d.ts","sourceRoot":"","sources":["../../src/http/providerFreshness.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAC7E,OAAO,EAAE,UAAU,EAAqB,MAAM,qCAAqC,CAAC;AACpF,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAC9C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAGpD;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,iCAAiC,QAAU,CAAC;AAEzD;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,eAAe,EAAE,IAAI,GAAG,MAAM,GAAG,IAAI,GAAG,SAAS,EAAE,GAAG,EAAE,IAAI,GAAG,OAAO,CAQ3G;AAED;;;;;;;;;;;;;;;;GAgBG;AACH;;;;;;;;;;GAUG;AACH,wBAAgB,eAAe,IAAI,UAAU,CAS5C;AAED;;;GAGG;AACH,wBAAgB,0BAA0B,CACxC,MAAM,EAAE,cAAc,EACtB,GAAG,GAAE,MAAM,IAAuB,GACjC,iBAAiB,CAAC,YAAY,CAAC,CAoBjC"}
1
+ {"version":3,"file":"providerFreshness.d.ts","sourceRoot":"","sources":["../../src/http/providerFreshness.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAC7E,OAAO,EAAE,UAAU,EAAqB,MAAM,qCAAqC,CAAC;AACpF,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAC9C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAIpD;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,iCAAiC,QAAU,CAAC;AAEzD;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CACnC,eAAe,EAAE,IAAI,GAAG,MAAM,GAAG,IAAI,GAAG,SAAS,EACjD,GAAG,EAAE,IAAI,EACT,aAAa,GAAE,MAA0C,GACxD,OAAO,CAET;AAED;;;;;;;;;GASG;AACH,wBAAgB,eAAe,IAAI,UAAU,CAS5C;AAED;;;;;;;;;;;;;;;;GAgBG;AACH;;;GAGG;AACH,wBAAgB,0BAA0B,CACxC,MAAM,EAAE,cAAc,EACtB,GAAG,GAAE,MAAM,IAAuB,GACjC,iBAAiB,CAAC,YAAY,CAAC,CAoBjC"}
@@ -1,6 +1,7 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
  import { emitProviderChangeNotFresh } from "../audit/emit.js";
4
+ import { authenticatedWithin } from "./recentSignIn.js";
4
5
  import { PithyError, UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
5
6
  //#region src/http/providerFreshness.ts
6
7
  /**
@@ -19,45 +20,22 @@ import { PithyError, UnauthorizedError } from "@pithy-sh/core/src/error/pithyErr
19
20
  */
20
21
  const PROVIDER_CHANGE_FRESH_AGE_SECONDS = 900;
21
22
  /**
22
- * Whether an authentication is recent enough to authorize attaching a provider.
23
+ * Whether an authentication is recent enough: within `maxAgeSeconds`, which defaults to
24
+ * {@link PROVIDER_CHANGE_FRESH_AGE_SECONDS}.
23
25
  *
24
26
  * **Fails closed on anything it cannot read.** An absent, unparseable or future timestamp is not evidence
25
27
  * of a recent authentication — it is the absence of evidence — and a gate that reads "I cannot tell" as
26
- * "fresh" is one a row written before the column walks straight through. The future case matters as much
27
- * as the past: a window checked on one side only would pass any future value forever.
28
+ * "fresh" is one a row written before the column walks straight through.
28
29
  */
29
- function authenticationIsFresh(authenticatedAt, now) {
30
- if (authenticatedAt === null || authenticatedAt === void 0) return false;
31
- const millis = (authenticatedAt instanceof Date ? authenticatedAt : new Date(authenticatedAt)).getTime();
32
- if (Number.isNaN(millis)) return false;
33
- const age = (now.getTime() - millis) / 1e3;
34
- if (age < 0) return false;
35
- return age <= 900;
30
+ function authenticationIsFresh(authenticatedAt, now, maxAgeSeconds = 900) {
31
+ return authenticatedWithin(authenticatedAt, now, maxAgeSeconds);
36
32
  }
37
33
  /**
38
- * The gate, as Hono middleware on the kit's own route tree.
39
- *
40
- * **A pure read of `c.var.auth`.** `createSessionMiddleware` has already resolved this request's
41
- * credential — core registers every capability's middleware before any capability's routes — so resolving
42
- * it again would be a second D1 round trip for a fact the seam is holding. That is the argument
43
- * `AuthContext` already makes for `locale`.
44
- *
45
- * **No credential at all is 401, not this 403.** `auth/session_not_fresh` means "signed in, but not
46
- * recently enough"; a caller holding nothing cannot tell that from "not signed in" and will not know
47
- * whether to re-authenticate or to retry. The refusal is `requireAuth()`'s, word for word, so the two
48
- * surfaces answer an absent credential identically.
49
- *
50
- * **Recorded before the throw**, like `emitProviderUnavailable`: one refusal is somebody who left a tab
51
- * open, and a run of them against one user id is the incident. The trail has to hold it whether or not
52
- * anything logs the refusal.
53
- */
54
- /**
55
- * The refusal for attaching a provider without having authenticated recently.
34
+ * The refusal for changing a connected account without having authenticated recently.
56
35
  *
57
36
  * **Not `auth/forbidden`.** A client has to render this differently from every other 403, because the
58
37
  * remedy is specific and cheap — sign in again, then retry — and a generic "you are not allowed" sends
59
- * somebody to ask for a permission they already hold. `http/linkFreshness.ts` carries the argument for
60
- * the gate itself.
38
+ * somebody to ask for a permission they already hold.
61
39
  *
62
40
  * `message` says nothing was changed, because the caller is mid-flow and cannot otherwise tell whether
63
41
  * the link half-happened.
@@ -72,6 +50,23 @@ function sessionNotFresh() {
72
50
  });
73
51
  }
74
52
  /**
53
+ * The gate, as Hono middleware on the kit's own route tree. `change` is which direction is being refused,
54
+ * carried into the audit row, because "somebody tried to attach an identity on a stale credential" and
55
+ * "somebody tried to strip one" are different things to read later.
56
+ *
57
+ * **A pure read of `c.var.auth`.** `createSessionMiddleware` has already resolved this request's
58
+ * credential — core registers every capability's middleware before any capability's routes — so resolving
59
+ * it again would be a second D1 round trip for a fact the seam is holding.
60
+ *
61
+ * **No credential at all is 401, not this 403.** `auth/session_not_fresh` means "signed in, but not
62
+ * recently enough"; a caller holding nothing cannot tell that from "not signed in" and will not know
63
+ * whether to re-authenticate or to retry.
64
+ *
65
+ * **Recorded before the throw**, like `emitProviderUnavailable`: one refusal is somebody who left a tab
66
+ * open, and a run of them against one user id is the incident. The trail has to hold it whether or not
67
+ * anything logs the refusal.
68
+ */
69
+ /**
75
70
  * Which direction is being refused. Carried into the audit row, because "somebody tried to attach an
76
71
  * identity on a stale credential" and "somebody tried to strip one" are different things to read later.
77
72
  */
@@ -82,7 +77,7 @@ function requireFreshAuthentication(change, now = () => /* @__PURE__ */ new Date
82
77
  message: "Authentication required.",
83
78
  action: "Sign in and retry with a valid session or bearer token."
84
79
  });
85
- if (!authenticationIsFresh(auth.authenticatedAt, now())) {
80
+ if (!authenticationIsFresh(auth.authenticatedAt, now(), 900)) {
86
81
  await emitProviderChangeNotFresh(c.var.emit, {
87
82
  change,
88
83
  userId: auth.userId,
@@ -0,0 +1,57 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
4
+ import { PithyError } from "@pithy-sh/core/src/error/pithyError";
5
+ import type { MiddlewareHandler } from "hono";
6
+ import { z } from "zod";
7
+ /**
8
+ * Whether `authenticatedAt` falls within the last `maxAgeSeconds` of `now`, boundary included.
9
+ *
10
+ * `authenticatedAt` is the session's sign-in instant: stamped once at sign-in and carried across every
11
+ * rotation, unlike the session's `createdAt`, which a rotation restamps. So a rotation never passes a
12
+ * window that the sign-in did not.
13
+ *
14
+ * **Fails closed on anything it cannot read.** An absent, unparseable or future timestamp is not evidence
15
+ * of a recent sign-in. The future case matters as much as the past: a window checked on one side only
16
+ * would pass any future value forever.
17
+ */
18
+ export declare function authenticatedWithin(authenticatedAt: Date | string | null | undefined, now: Date, maxAgeSeconds: number): boolean;
19
+ /** What an app route's recent-sign-in gate is built from. Checked once, when the gate is built. */
20
+ export declare const RecentSignInOptions: z.ZodObject<{
21
+ maxAgeSeconds: z.ZodNumber;
22
+ purpose: z.ZodString;
23
+ }, z.core.$strip>;
24
+ export type RecentSignInOptions = z.infer<typeof RecentSignInOptions>;
25
+ /**
26
+ * The refusal for an app route reached without a recent enough sign-in: 403 `auth/recent_sign_in_required`.
27
+ *
28
+ * One code for every gated route, so a client renders one remedy — sign in again, then retry — wherever it
29
+ * meets it. `message` says nothing was changed, because the caller cannot otherwise tell whether the
30
+ * request half-happened.
31
+ */
32
+ export declare function recentSignInRequired(): PithyError;
33
+ /**
34
+ * Gate an app route on a recent sign-in, with the window the route names.
35
+ *
36
+ * ```ts
37
+ * app.post(
38
+ * "/things/:id/secret",
39
+ * describeRoute({ … }),
40
+ * requireRecentSignIn({ maxAgeSeconds: 300, purpose: "things/secret_revealed" }),
41
+ * validate("param", ThingParams),
42
+ * handler,
43
+ * );
44
+ * ```
45
+ *
46
+ * - No credential answers exactly as `requireAuth()` does.
47
+ * - A session whose `authenticatedAt` is older than `maxAgeSeconds`, absent, unreadable or in the future is
48
+ * refused with {@link recentSignInRequired}, after an `auth/recent_sign_in_refused` audit row naming the
49
+ * user, the session and `purpose`.
50
+ * - A bearer session and a cookie session are judged by the same rule. A phone passes by signing in again,
51
+ * which starts a session with a new `authenticatedAt`; a rotation does not.
52
+ *
53
+ * `options` is checked here, so a `maxAgeSeconds` that is not a positive whole number or a `purpose` that is
54
+ * not `domain/reason` throws when the route is declared rather than on a request.
55
+ */
56
+ export declare function requireRecentSignIn(options: RecentSignInOptions, now?: () => Date): MiddlewareHandler<PithyHonoEnv>;
57
+ //# sourceMappingURL=recentSignIn.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"recentSignIn.d.ts","sourceRoot":"","sources":["../../src/http/recentSignIn.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAC7E,OAAO,EAAE,UAAU,EAAE,MAAM,qCAAqC,CAAC;AACjE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAC9C,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAIxB;;;;;;;;;;GAUG;AACH,wBAAgB,mBAAmB,CACjC,eAAe,EAAE,IAAI,GAAG,MAAM,GAAG,IAAI,GAAG,SAAS,EACjD,GAAG,EAAE,IAAI,EACT,aAAa,EAAE,MAAM,GACpB,OAAO,CAQT;AAED,mGAAmG;AACnG,eAAO,MAAM,mBAAmB;;;iBAWkD,CAAC;AACnF,MAAM,MAAM,mBAAmB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAEtE;;;;;;GAMG;AACH,wBAAgB,oBAAoB,IAAI,UAAU,CASjD;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,EAAE,mBAAmB,EAC5B,GAAG,GAAE,MAAM,IAAuB,GACjC,iBAAiB,CAAC,YAAY,CAAC,CAkBjC"}
@@ -0,0 +1,88 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { emitRecentSignInRefused } from "../audit/emit.js";
4
+ import { requireAuth } from "./middleware.js";
5
+ import { PithyError } from "@pithy-sh/core/src/error/pithyError";
6
+ import { z } from "zod";
7
+ import { AuditAction } from "@pithy-sh/core/src/audit/auditEvent";
8
+ //#region src/http/recentSignIn.ts
9
+ /**
10
+ * Whether `authenticatedAt` falls within the last `maxAgeSeconds` of `now`, boundary included.
11
+ *
12
+ * `authenticatedAt` is the session's sign-in instant: stamped once at sign-in and carried across every
13
+ * rotation, unlike the session's `createdAt`, which a rotation restamps. So a rotation never passes a
14
+ * window that the sign-in did not.
15
+ *
16
+ * **Fails closed on anything it cannot read.** An absent, unparseable or future timestamp is not evidence
17
+ * of a recent sign-in. The future case matters as much as the past: a window checked on one side only
18
+ * would pass any future value forever.
19
+ */
20
+ function authenticatedWithin(authenticatedAt, now, maxAgeSeconds) {
21
+ if (authenticatedAt === null || authenticatedAt === void 0) return false;
22
+ const millis = (authenticatedAt instanceof Date ? authenticatedAt : new Date(authenticatedAt)).getTime();
23
+ if (Number.isNaN(millis)) return false;
24
+ const age = (now.getTime() - millis) / 1e3;
25
+ if (age < 0) return false;
26
+ return age <= maxAgeSeconds;
27
+ }
28
+ /** What an app route's recent-sign-in gate is built from. Checked once, when the gate is built. */
29
+ const RecentSignInOptions = z.object({
30
+ maxAgeSeconds: z.number().int().positive().describe("How recently the caller must have signed in, in seconds, for this route. A whole number above zero."),
31
+ purpose: AuditAction.describe("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.")
32
+ }).describe("The window and the audit purpose of one `requireRecentSignIn` gate.");
33
+ /**
34
+ * The refusal for an app route reached without a recent enough sign-in: 403 `auth/recent_sign_in_required`.
35
+ *
36
+ * One code for every gated route, so a client renders one remedy — sign in again, then retry — wherever it
37
+ * meets it. `message` says nothing was changed, because the caller cannot otherwise tell whether the
38
+ * request half-happened.
39
+ */
40
+ function recentSignInRequired() {
41
+ return new PithyError({
42
+ code: "auth/recent_sign_in_required",
43
+ status: 403,
44
+ message: "Sign in again to continue. Nothing was changed.",
45
+ action: "A deliberate gate: this route requires a sign-in within the window its `requireRecentSignIn` names. Sign in again, then retry.",
46
+ detail: "session authenticatedAt is outside the route's window, absent, or unreadable"
47
+ });
48
+ }
49
+ /**
50
+ * Gate an app route on a recent sign-in, with the window the route names.
51
+ *
52
+ * ```ts
53
+ * app.post(
54
+ * "/things/:id/secret",
55
+ * describeRoute({ … }),
56
+ * requireRecentSignIn({ maxAgeSeconds: 300, purpose: "things/secret_revealed" }),
57
+ * validate("param", ThingParams),
58
+ * handler,
59
+ * );
60
+ * ```
61
+ *
62
+ * - No credential answers exactly as `requireAuth()` does.
63
+ * - A session whose `authenticatedAt` is older than `maxAgeSeconds`, absent, unreadable or in the future is
64
+ * refused with {@link recentSignInRequired}, after an `auth/recent_sign_in_refused` audit row naming the
65
+ * user, the session and `purpose`.
66
+ * - A bearer session and a cookie session are judged by the same rule. A phone passes by signing in again,
67
+ * which starts a session with a new `authenticatedAt`; a rotation does not.
68
+ *
69
+ * `options` is checked here, so a `maxAgeSeconds` that is not a positive whole number or a `purpose` that is
70
+ * not `domain/reason` throws when the route is declared rather than on a request.
71
+ */
72
+ function requireRecentSignIn(options, now = () => /* @__PURE__ */ new Date()) {
73
+ const { maxAgeSeconds, purpose } = RecentSignInOptions.parse(options);
74
+ const authenticated = requireAuth();
75
+ return (c, next) => authenticated(c, async () => {
76
+ const auth = c.var.auth;
77
+ if (auth && authenticatedWithin(auth.authenticatedAt, now(), maxAgeSeconds)) return next();
78
+ if (auth) await emitRecentSignInRefused(c.var.emit, {
79
+ purpose,
80
+ userId: auth.userId,
81
+ sessionId: auth.sessionId,
82
+ headers: c.req.raw.headers
83
+ });
84
+ throw recentSignInRequired();
85
+ });
86
+ }
87
+ //#endregion
88
+ export { RecentSignInOptions, authenticatedWithin, recentSignInRequired, requireRecentSignIn };
@@ -3,13 +3,13 @@
3
3
  import { authDatabase } from "../data/tables.js";
4
4
  import { correlation, emitDenied, emitDeviceRevoked, emitTokenRefresh, emitTokenReuseDetected } from "../audit/emit.js";
5
5
  import { deleteDevice, deviceSessionTokens, listDevices } from "../device/registry.js";
6
- import { requireFreshAuthentication } from "./providerFreshness.js";
7
6
  import { isLifecycleRefusal } from "../lifecycle/state.js";
8
7
  import { noticedRefusal } from "../lifecycle/enforce.js";
8
+ import { accountHolder, requireAccountHolder, requireAuth } from "./middleware.js";
9
+ import { requireFreshAuthentication } from "./providerFreshness.js";
9
10
  import { PROFILE_IMAGE_PATH } from "../profile/profile.js";
10
11
  import { collapseProviderRefusal } from "./providerRefusal.js";
11
12
  import { getAuthInstance, resolveDb } from "./resolve.js";
12
- import { accountHolder, requireAccountHolder, requireAuth } from "./middleware.js";
13
13
  import { userSessionTokens } from "../admin/users.js";
14
14
  import { lifecycleDeps } from "../lifecycle/request.js";
15
15
  import { deleteUser } from "../lifecycle/transitions.js";
package/dist/index.d.ts CHANGED
@@ -2,8 +2,9 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
  /**
4
4
  * The package entrypoint — the surface `pithy add auth` wires into `pithy.config.ts`. Deliberately
5
- * narrow: the capability factory, the `requireAuth()` gate other capabilities stack, and the data /
6
- * secret types an app or tool needs. Every other module is imported by deep path
5
+ * narrow: the capability factory, the `requireAuth()` gate other capabilities stack, the
6
+ * `requireRecentSignIn()` gate an app route stacks, and the data / secret types an app or tool needs.
7
+ * Every other module is imported by deep path
7
8
  * (`@pithy-sh/auth/src/...`) — this is the documented contract, not a barrel over the package.
8
9
  */
9
10
  export { AuthAuditActions } from "./audit/actions";
@@ -12,6 +13,7 @@ export { type Device, DevicePlatform } from "./data/device";
12
13
  export { type AuthDatabase, authDatabase } from "./data/tables";
13
14
  export { DEVICE_HEADERS, type DeviceMeta } from "./device/registry";
14
15
  export { requireAuth } from "./http/middleware";
16
+ export { RecentSignInOptions, requireRecentSignIn } from "./http/recentSignIn";
15
17
  export { AppleOAuthCredentials, AUTH_APPLE_CREDENTIALS, AUTH_GOOGLE_CREDENTIALS, AUTH_SESSION_SECRET, authSecretsRegistry, GoogleOAuthCredentials, } from "./instance/secrets";
16
18
  export { type McpCapability, McpConfig, type McpConfigInput, mcp } from "./mcp/capability";
17
19
  export { McpFloor } from "./mcp/floor";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA;;;;;GAKG;AAEH,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACnD,OAAO,EAAE,KAAK,cAAc,EAAE,UAAU,EAAE,KAAK,eAAe,EAAE,IAAI,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAC7G,OAAO,EAAE,KAAK,MAAM,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC5D,OAAO,EAAE,KAAK,YAAY,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,KAAK,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACpE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EACL,qBAAqB,EACrB,sBAAsB,EACtB,uBAAuB,EACvB,mBAAmB,EACnB,mBAAmB,EACnB,sBAAsB,GACvB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,KAAK,aAAa,EAAE,SAAS,EAAE,KAAK,cAAc,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAC;AAC3F,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA;;;;;;GAMG;AAEH,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACnD,OAAO,EAAE,KAAK,cAAc,EAAE,UAAU,EAAE,KAAK,eAAe,EAAE,IAAI,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAC7G,OAAO,EAAE,KAAK,MAAM,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC5D,OAAO,EAAE,KAAK,YAAY,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,KAAK,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACpE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC/E,OAAO,EACL,qBAAqB,EACrB,sBAAsB,EACtB,uBAAuB,EACvB,mBAAmB,EACnB,mBAAmB,EACnB,sBAAsB,GACvB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,KAAK,aAAa,EAAE,SAAS,EAAE,KAAK,cAAc,EAAE,GAAG,EAAE,MAAM,kBAAkB,CAAC;AAC3F,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC"}
package/dist/index.js CHANGED
@@ -6,7 +6,8 @@ import { authDatabase } from "./data/tables.js";
6
6
  import { AUTH_APPLE_CREDENTIALS, AUTH_GOOGLE_CREDENTIALS, AUTH_SESSION_SECRET, AppleOAuthCredentials, GoogleOAuthCredentials, authSecretsRegistry } from "./instance/secrets.js";
7
7
  import { DEVICE_HEADERS } from "./device/registry.js";
8
8
  import { requireAuth } from "./http/middleware.js";
9
+ import { RecentSignInOptions, requireRecentSignIn } from "./http/recentSignIn.js";
9
10
  import { AuthConfig, auth, isAuthCapability } from "./capability.js";
10
11
  import { McpFloor } from "./mcp/floor.js";
11
12
  import { McpConfig, mcp } from "./mcp/capability.js";
12
- export { AUTH_APPLE_CREDENTIALS, AUTH_GOOGLE_CREDENTIALS, AUTH_SESSION_SECRET, AppleOAuthCredentials, AuthAuditActions, AuthConfig, DEVICE_HEADERS, DevicePlatform, GoogleOAuthCredentials, McpConfig, McpFloor, auth, authDatabase, authSecretsRegistry, isAuthCapability, mcp, requireAuth };
13
+ export { AUTH_APPLE_CREDENTIALS, AUTH_GOOGLE_CREDENTIALS, AUTH_SESSION_SECRET, AppleOAuthCredentials, AuthAuditActions, AuthConfig, DEVICE_HEADERS, DevicePlatform, GoogleOAuthCredentials, McpConfig, McpFloor, RecentSignInOptions, auth, authDatabase, authSecretsRegistry, isAuthCapability, mcp, requireAuth, requireRecentSignIn };
@@ -4,16 +4,16 @@ import { emitAfterRequest, emitProviderAccountChanged, emitProviderUnavailable }
4
4
  import { claimedDelete, markSessionEnded, messageDeliveryDuring, sessionEndedDuring } from "../audit/evidence.js";
5
5
  import { KIT_SESSION_FIELDS, KIT_USER_FIELDS } from "../data/kitFields.js";
6
6
  import { parseDeviceMeta, registerDevice } from "../device/registry.js";
7
+ import { admitsDeletionSignIn, lifecycleRefusalFor } from "../lifecycle/enforce.js";
8
+ import { betterAuthSecrets } from "./sessionSecrets.js";
7
9
  import "../http/providerFreshness.js";
8
10
  import { verificationLedger } from "../ledger/record.js";
9
- import { admitsDeletionSignIn, lifecycleRefusalFor } from "../lifecycle/enforce.js";
10
11
  import { recordActivity } from "../lifecycle/inactivity.js";
11
12
  import { refuseUnsafeProfile, sanitizeProfile } from "../profile/profile.js";
12
13
  import { defaultGithubUserInfo } from "./githubUserInfo.js";
13
14
  import { microsoftProfileToUser } from "./microsoftEmail.js";
14
15
  import { kitPlugins } from "./plugins.js";
15
16
  import { providerUnavailable, unavailableProviderFor } from "./providers.js";
16
- import { betterAuthSecrets } from "./sessionSecrets.js";
17
17
  import { betterAuth } from "better-auth";
18
18
  import { APIError, createAuthMiddleware } from "better-auth/api";
19
19
  //#region src/instance/auth.ts
@@ -4,9 +4,9 @@ import { AuthAuditActions } from "../../audit/actions.js";
4
4
  import { authDatabase } from "../../data/tables.js";
5
5
  import { dispatchRequest, dispatchedOutcome, toolArguments } from "../dispatch.js";
6
6
  import { lifecycleRefusalFor } from "../../lifecycle/enforce.js";
7
+ import { requireAuth } from "../../http/middleware.js";
7
8
  import { MCP_SCOPES } from "../provider.js";
8
9
  import { resolveDb } from "../../http/resolve.js";
9
- import { requireAuth } from "../../http/middleware.js";
10
10
  import { PACKAGE_VERSION } from "../../version.generated.js";
11
11
  import { verifiedHost } from "../clientMetadata.js";
12
12
  import { floorAdmits } from "../floor.js";
@@ -20,8 +20,8 @@ import { ConnectionParam, ConsentBody, ConsentQuery, McpRequestBody } from "./sc
20
20
  import { ForbiddenError, NotFoundError, PithyError, UnauthorizedError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
21
21
  import { describeRoute } from "@pithy-sh/core/src/http/routeSpec";
22
22
  import { validate } from "@pithy-sh/core/src/http/validation";
23
- import { verifyOAuthQueryParams } from "@better-auth/oauth-provider";
24
23
  import { AuthContext } from "@pithy-sh/core/src/http/authContext";
24
+ import { verifyOAuthQueryParams } from "@better-auth/oauth-provider";
25
25
  import { requireSameOrigin } from "@pithy-sh/core/src/http/sameOrigin";
26
26
  import { offeredTools } from "@pithy-sh/core/src/mcp/tools";
27
27
  import { grantedEntitlementKeys } from "@pithy-sh/core/src/entitlement/entitlement";