@pithy-sh/auth 0.8.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.
Files changed (164) hide show
  1. package/README.md +12 -2
  2. package/dist/audit/actions.d.ts +21 -0
  3. package/dist/audit/actions.d.ts.map +1 -1
  4. package/dist/audit/actions.js +22 -1
  5. package/dist/audit/emit.js +1 -1
  6. package/dist/caller/certificate.d.ts +83 -0
  7. package/dist/caller/certificate.d.ts.map +1 -0
  8. package/dist/caller/certificate.js +92 -0
  9. package/dist/caller/request.d.ts +66 -0
  10. package/dist/caller/request.d.ts.map +1 -0
  11. package/dist/caller/request.js +71 -0
  12. package/dist/caller/token.d.ts +130 -0
  13. package/dist/caller/token.d.ts.map +1 -0
  14. package/dist/caller/token.js +207 -0
  15. package/dist/capability.d.ts +70 -2
  16. package/dist/capability.d.ts.map +1 -1
  17. package/dist/capability.js +28 -7
  18. package/dist/client/lifecycle.d.ts +19 -0
  19. package/dist/client/lifecycle.d.ts.map +1 -0
  20. package/dist/client/lifecycle.js +25 -0
  21. package/dist/client/projection.d.ts +4 -0
  22. package/dist/client/projection.d.ts.map +1 -1
  23. package/dist/data/betterAuth.d.ts +5 -1
  24. package/dist/data/betterAuth.d.ts.map +1 -1
  25. package/dist/data/betterAuth.js +7 -3
  26. package/dist/data/kitFields.d.ts +20 -25
  27. package/dist/data/kitFields.d.ts.map +1 -1
  28. package/dist/data/kitFields.js +28 -32
  29. package/dist/data/tables.d.ts +29 -3
  30. package/dist/data/tables.d.ts.map +1 -1
  31. package/dist/data/tables.js +5 -3
  32. package/dist/data/userLifecycle.d.ts +61 -0
  33. package/dist/data/userLifecycle.d.ts.map +1 -0
  34. package/dist/data/userLifecycle.js +50 -0
  35. package/dist/http/credentialResign.d.ts +46 -0
  36. package/dist/http/credentialResign.d.ts.map +1 -0
  37. package/dist/http/credentialResign.js +203 -0
  38. package/dist/http/errorCallbackUrl.d.ts.map +1 -1
  39. package/dist/http/errorCallbackUrl.js +15 -9
  40. package/dist/http/guards.d.ts +23 -1
  41. package/dist/http/guards.d.ts.map +1 -1
  42. package/dist/http/guards.js +28 -3
  43. package/dist/http/lifecycleGate.d.ts +18 -0
  44. package/dist/http/lifecycleGate.d.ts.map +1 -0
  45. package/dist/http/lifecycleGate.js +75 -0
  46. package/dist/http/middleware.d.ts +5 -0
  47. package/dist/http/middleware.d.ts.map +1 -1
  48. package/dist/http/middleware.js +113 -21
  49. package/dist/http/providerRefusal.d.ts +8 -7
  50. package/dist/http/providerRefusal.d.ts.map +1 -1
  51. package/dist/http/providerRefusal.js +37 -32
  52. package/dist/http/resolve.d.ts.map +1 -1
  53. package/dist/http/resolve.js +23 -5
  54. package/dist/http/routes.d.ts.map +1 -1
  55. package/dist/http/routes.js +20 -1
  56. package/dist/instance/auth.d.ts +1280 -5
  57. package/dist/instance/auth.d.ts.map +1 -1
  58. package/dist/instance/auth.js +59 -4
  59. package/dist/instance/jwksReencryption.d.ts +75 -0
  60. package/dist/instance/jwksReencryption.d.ts.map +1 -0
  61. package/dist/instance/jwksReencryption.js +160 -0
  62. package/dist/instance/microsoftEmail.d.ts +70 -0
  63. package/dist/instance/microsoftEmail.d.ts.map +1 -0
  64. package/dist/instance/microsoftEmail.js +96 -0
  65. package/dist/instance/providerSignInGate.d.ts +14 -12
  66. package/dist/instance/providerSignInGate.d.ts.map +1 -1
  67. package/dist/instance/providerSignInGate.js +23 -20
  68. package/dist/instance/providers.d.ts +7 -5
  69. package/dist/instance/providers.d.ts.map +1 -1
  70. package/dist/instance/providers.js +5 -3
  71. package/dist/instance/secrets.d.ts +232 -4
  72. package/dist/instance/secrets.d.ts.map +1 -1
  73. package/dist/instance/secrets.js +129 -7
  74. package/dist/instance/sessionSecrets.d.ts +45 -0
  75. package/dist/instance/sessionSecrets.d.ts.map +1 -0
  76. package/dist/instance/sessionSecrets.js +29 -0
  77. package/dist/lifecycle/enforce.d.ts +40 -0
  78. package/dist/lifecycle/enforce.d.ts.map +1 -0
  79. package/dist/lifecycle/enforce.js +70 -0
  80. package/dist/lifecycle/hooks.d.ts +53 -0
  81. package/dist/lifecycle/hooks.d.ts.map +1 -0
  82. package/dist/lifecycle/hooks.js +2 -0
  83. package/dist/lifecycle/request.d.ts +15 -0
  84. package/dist/lifecycle/request.d.ts.map +1 -0
  85. package/dist/lifecycle/request.js +27 -0
  86. package/dist/lifecycle/state.d.ts +64 -0
  87. package/dist/lifecycle/state.d.ts.map +1 -0
  88. package/dist/lifecycle/state.js +90 -0
  89. package/dist/lifecycle/transitions.d.ts +132 -0
  90. package/dist/lifecycle/transitions.d.ts.map +1 -0
  91. package/dist/lifecycle/transitions.js +349 -0
  92. package/dist/migrations/0001_init.d.ts.map +1 -1
  93. package/dist/migrations/0003_account_issuer_nullable.d.ts +5 -0
  94. package/dist/migrations/0003_account_issuer_nullable.d.ts.map +1 -0
  95. package/dist/migrations/0003_account_issuer_nullable.js +131 -0
  96. package/dist/migrations/0004_user_lifecycle.d.ts +28 -0
  97. package/dist/migrations/0004_user_lifecycle.d.ts.map +1 -0
  98. package/dist/migrations/0004_user_lifecycle.js +47 -0
  99. package/dist/migrations/set.d.ts +3 -1
  100. package/dist/migrations/set.d.ts.map +1 -1
  101. package/dist/migrations/set.js +6 -2
  102. package/dist/peer.d.ts +4 -0
  103. package/dist/peer.d.ts.map +1 -1
  104. package/dist/test-utils/liveApp.d.ts +26 -0
  105. package/dist/test-utils/liveApp.d.ts.map +1 -1
  106. package/dist/test-utils/liveApp.js +1 -0
  107. package/dist/test-utils/schemaDrift.d.ts +49 -0
  108. package/dist/test-utils/schemaDrift.d.ts.map +1 -0
  109. package/dist/test-utils/schemaDrift.js +35 -0
  110. package/dist/test-utils/scopedBackend.d.ts +204 -0
  111. package/dist/test-utils/scopedBackend.d.ts.map +1 -0
  112. package/dist/test-utils/scopedBackend.js +166 -0
  113. package/dist/version.generated.d.ts +1 -1
  114. package/dist/version.generated.d.ts.map +1 -1
  115. package/dist/version.generated.js +1 -1
  116. package/docs/account-lifecycle.md +105 -0
  117. package/docs/apple-signin.md +7 -1
  118. package/docs/facebook-oauth.md +7 -1
  119. package/docs/github-oauth.md +7 -1
  120. package/docs/google-oauth.md +7 -1
  121. package/docs/microsoft-oauth.md +177 -0
  122. package/docs/server-authoritative.md +182 -0
  123. package/package.json +11 -8
  124. package/pithy.manifest.json +17 -3
  125. package/src/audit/actions.ts +23 -0
  126. package/src/audit/emit.ts +1 -1
  127. package/src/caller/certificate.ts +133 -0
  128. package/src/caller/request.ts +84 -0
  129. package/src/caller/token.ts +276 -0
  130. package/src/capability.ts +170 -38
  131. package/src/client/lifecycle.ts +27 -0
  132. package/src/client/projection.ts +4 -0
  133. package/src/data/betterAuth.ts +23 -2
  134. package/src/data/kitFields.ts +27 -0
  135. package/src/data/tables.ts +4 -2
  136. package/src/data/userLifecycle.ts +80 -0
  137. package/src/http/credentialResign.ts +268 -0
  138. package/src/http/errorCallbackUrl.ts +21 -13
  139. package/src/http/guards.ts +29 -1
  140. package/src/http/lifecycleGate.ts +78 -0
  141. package/src/http/middleware.ts +161 -37
  142. package/src/http/providerRefusal.ts +40 -32
  143. package/src/http/resolve.ts +34 -5
  144. package/src/http/routes.ts +39 -2
  145. package/src/instance/auth.ts +91 -6
  146. package/src/instance/jwksReencryption.ts +206 -0
  147. package/src/instance/microsoftEmail.ts +111 -0
  148. package/src/instance/providerSignInGate.ts +30 -27
  149. package/src/instance/providers.ts +8 -4
  150. package/src/instance/secrets.ts +153 -6
  151. package/src/instance/sessionSecrets.ts +64 -0
  152. package/src/lifecycle/enforce.ts +89 -0
  153. package/src/lifecycle/hooks.ts +54 -0
  154. package/src/lifecycle/request.ts +31 -0
  155. package/src/lifecycle/state.ts +101 -0
  156. package/src/lifecycle/transitions.ts +483 -0
  157. package/src/migrations/0001_init.ts +8 -10
  158. package/src/migrations/0003_account_issuer_nullable.ts +199 -0
  159. package/src/migrations/0004_user_lifecycle.ts +68 -0
  160. package/src/migrations/set.ts +5 -1
  161. package/src/test-utils/liveApp.ts +2 -1
  162. package/src/test-utils/schemaDrift.ts +82 -0
  163. package/src/test-utils/scopedBackend.ts +137 -0
  164. package/src/version.generated.ts +1 -1
@@ -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
+ }
@@ -2,12 +2,17 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import type { PithyHonoEnv, PithyMiddleware } from "@pithy-sh/core/src/capability/capability";
5
- import { UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
5
+ import { InternalError, type PithyError, UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
6
6
  import { AuthContext } from "@pithy-sh/core/src/http/authContext";
7
7
  import { isLocale } from "@pithy-sh/core/src/i18n/locale";
8
- import type { MiddlewareHandler } from "hono";
9
- import type { AuthWiring } from "../capability";
10
- import { getAuthInstance } from "./resolve";
8
+ import type { Context, MiddlewareHandler } from "hono";
9
+ import type { AuthWiring, ScopeResolver, ScopeResolverSession } from "../capability";
10
+ import { authDatabase } from "../data/tables";
11
+ import type { AuthInstance } from "../instance/auth";
12
+ import { lifecycleRefusalFor, noteRefusal, noticedRefusal } from "../lifecycle/enforce";
13
+ import { LifecycleColumns } from "../lifecycle/state";
14
+ import { withResignedCredentials } from "./credentialResign";
15
+ import { getAuthInstance, resolveDb } from "./resolve";
11
16
 
12
17
  /**
13
18
  * The session-resolution middleware: it fills core's `AuthContext` seam (`c.var.auth`) for every
@@ -22,54 +27,173 @@ function authenticatedDate(session: unknown): Date | null {
22
27
  return value instanceof Date ? value : null;
23
28
  }
24
29
 
30
+ /**
31
+ * The scopes this request's caller resolves to — what the adopter's resolver answered, or `[]`.
32
+ *
33
+ * **Closed on every failure, and never fatal** (#560). A resolver that throws or rejects, and one that answers
34
+ * something other than a list of strings, both leave the request with no scopes and a warning: a gate then
35
+ * refuses it as it would any untrusted caller, rather than the request becoming a 500 or — worse — a
36
+ * malformed answer reaching a guard that would read `includes` off a string. Validated through
37
+ * `AuthContext`'s own field, so this and the context the middleware publishes cannot disagree on the shape.
38
+ *
39
+ * The warning names the session and never the answer: whatever the resolver handed back is the adopter's,
40
+ * and a log is not where to learn what a caller was trusted with.
41
+ */
42
+ async function resolvedScopes(
43
+ c: Context<PithyHonoEnv>,
44
+ resolve: ScopeResolver | undefined,
45
+ session: ScopeResolverSession,
46
+ ): Promise<string[]> {
47
+ if (resolve === undefined) return [];
48
+ let answer: unknown;
49
+ try {
50
+ answer = await resolve(c, session);
51
+ } catch (error) {
52
+ c.var.log.child("auth").warn("resolveScopes failed; this request carries no scopes", {
53
+ sessionId: session.sessionId,
54
+ reason: error instanceof Error ? error.message : String(error),
55
+ });
56
+ return [];
57
+ }
58
+ const parsed = AuthContext.shape.scopes.safeParse(answer);
59
+ if (!parsed.success || answer === undefined) {
60
+ c.var.log
61
+ .child("auth")
62
+ .warn("resolveScopes answered something that is not a list of strings; this request carries no scopes", {
63
+ sessionId: session.sessionId,
64
+ });
65
+ return [];
66
+ }
67
+ return parsed.data;
68
+ }
69
+
25
70
  export function createSessionMiddleware(wiring: AuthWiring): PithyMiddleware {
26
71
  return (app) => {
27
72
  app.use("*", async (c, next) => {
28
- const headers = c.req.raw.headers;
29
- if (headers.has("authorization") || headers.has("cookie")) {
30
- try {
31
- const instance = await getAuthInstance(c, wiring);
32
- const session = await instance.api.getSession({ headers });
33
- if (session) {
34
- // `locale` comes off the user row the session lookup already loaded, so publishing it
35
- // costs nothing — and it is the `user` link of `@pithy-sh/i18n`'s server chain, the one
36
- // that makes a reader's stored choice outrank their device's `Accept-Language`. Read
37
- // through `AuthContext.parse`, so a column holding something that is not a tag lands as
38
- // `undefined` rather than reaching `Intl`.
39
- const stored = (session.user as { locale?: unknown }).locale;
40
- c.set(
41
- "auth",
42
- AuthContext.parse({
43
- userId: session.user.id,
44
- sessionId: session.session.id,
45
- scopes: [],
46
- locale: typeof stored === "string" && isLocale(stored) ? stored : null,
47
- // Published for the same reason `locale` is: the session lookup has already loaded the
48
- // row, so a gate that needs it should not pay for a second read. The adapter hands back
49
- // a `Date`; a session predating the column hands back null, which reads as "cannot say".
50
- // Guarded like `locale` beside it, and for a worse failure: `z.date()` throws on a
51
- // string, the catch below swallows it, and every authenticated request in the Worker
52
- // becomes anonymous — a total outage presenting as "everyone is logged out".
53
- authenticatedAt: authenticatedDate(session.session),
54
- }),
55
- );
56
- }
57
- } catch {
58
- // Leave `auth` null; the credential was missing/invalid.
59
- }
73
+ if (!c.req.raw.headers.has("authorization") && !c.req.raw.headers.has("cookie")) return await next();
74
+ // A credential signed under a session secret this deployment has since rotated is re-signed under the
75
+ // current one before anything reads it (#602), and the re-signed one rides back on the response. A
76
+ // failure building the instance is not this middleware's to raise, so it is left to the routes.
77
+ let instance: AuthInstance | undefined;
78
+ try {
79
+ instance = await getAuthInstance(c, wiring);
80
+ } catch {
81
+ instance = undefined;
60
82
  }
61
- await next();
83
+ if (instance === undefined) return await next();
84
+ const built = instance;
85
+ await withResignedCredentials(c, built, async () => {
86
+ await resolveSession(c, wiring, built);
87
+ await next();
88
+ });
62
89
  });
63
90
  };
64
91
  }
65
92
 
93
+ /** Fill `c.var.auth` from the request's credential, or leave it null. Never throws. */
94
+ async function resolveSession(c: Context<PithyHonoEnv>, wiring: AuthWiring, instance: AuthInstance): Promise<void> {
95
+ const headers = c.req.raw.headers;
96
+ try {
97
+ const session = await instance.api.getSession({ headers });
98
+ if (session) {
99
+ // **A suspended or deleted account gets no `AuthContext` at all** (#620). Read off the user Better
100
+ // Auth just loaded, which carries the four columns, so an account in good standing costs nothing
101
+ // here. Leaving `auth` null is what makes every `requireAuth()` in the kit refuse it — the copies
102
+ // other capabilities carry included, since each one only asks whether `auth` was filled. This
103
+ // capability's own guard raises the refusal itself, with its code; see `requireAuth` below.
104
+ const refusal = await standingRefusal(c, wiring, session.user);
105
+ if (refusal) {
106
+ noteRefusal(c, refusal);
107
+ return;
108
+ }
109
+ // Before the context is built, so a resolver sees the request exactly as it arrived and the
110
+ // context is published once, whole. Per request and never cached: the answer is about this
111
+ // request's caller, and a cached one is a revocation that has not taken effect (#560).
112
+ const scopes = await resolvedScopes(c, wiring.resolveScopes, {
113
+ userId: session.user.id,
114
+ sessionId: session.session.id,
115
+ });
116
+ // `locale` comes off the user row the session lookup already loaded, so publishing it
117
+ // costs nothing — and it is the `user` link of `@pithy-sh/i18n`'s server chain, the one
118
+ // that makes a reader's stored choice outrank their device's `Accept-Language`. Read
119
+ // through `AuthContext.parse`, so a column holding something that is not a tag lands as
120
+ // `undefined` rather than reaching `Intl`.
121
+ const stored = (session.user as { locale?: unknown }).locale;
122
+ c.set(
123
+ "auth",
124
+ AuthContext.parse({
125
+ userId: session.user.id,
126
+ sessionId: session.session.id,
127
+ scopes,
128
+ locale: typeof stored === "string" && isLocale(stored) ? stored : null,
129
+ // Published for the same reason `locale` is: the session lookup has already loaded the
130
+ // row, so a gate that needs it should not pay for a second read. The adapter hands back
131
+ // a `Date`; a session predating the column hands back null, which reads as "cannot say".
132
+ // Guarded like `locale` beside it, and for a worse failure: `z.date()` throws on a
133
+ // string, the catch below swallows it, and every authenticated request in the Worker
134
+ // becomes anonymous — a total outage presenting as "everyone is logged out".
135
+ authenticatedAt: authenticatedDate(session.session),
136
+ }),
137
+ );
138
+ }
139
+ } catch {
140
+ // Leave `auth` null; the credential was missing/invalid.
141
+ }
142
+ }
143
+
144
+ /**
145
+ * The refusal for the session's account, or `null` when it may act.
146
+ *
147
+ * **A check that cannot be made refuses**, rather than throwing into `resolveSession`'s catch. That catch
148
+ * leaves `auth` null and notes nothing, and `handleBetterAuth` only refuses on a noted verdict — so a failed
149
+ * read of a suspension's reason, or a column that will not decode, would let Better Auth's own `/token` mint a
150
+ * JWT for the suspended account it resolved on its own. So the failure is logged and becomes the verdict: a
151
+ * 500, since the fault is this Worker's, and every door that honors a lifecycle refusal honors this one.
152
+ */
153
+ async function standingRefusal(
154
+ c: Context<PithyHonoEnv>,
155
+ wiring: AuthWiring,
156
+ user: { id: string },
157
+ ): Promise<PithyError | null> {
158
+ try {
159
+ return await lifecycleRefusalFor(
160
+ authDatabase(resolveDb(c.env, wiring.config.database)),
161
+ user.id,
162
+ LifecycleColumns.parse(user),
163
+ new Date(),
164
+ );
165
+ } catch (cause) {
166
+ // Optional, unlike the logger elsewhere here: this branch is the refusal, and a missing logger must not
167
+ // turn it back into the throw it exists to replace.
168
+ c.var.log?.child("auth").warn("the account's standing could not be checked; the request is refused", {
169
+ userId: user.id,
170
+ reason: cause instanceof Error ? cause.message : String(cause),
171
+ });
172
+ return new InternalError(
173
+ {
174
+ message: "This account could not be checked. Try again shortly.",
175
+ action: "Check the auth database binding and that the auth migrations have run.",
176
+ detail: `lifecycle check for user ${user.id} failed`,
177
+ },
178
+ { cause },
179
+ );
180
+ }
181
+ }
182
+
66
183
  /**
67
184
  * The gate other capabilities stack on a protected route. Rejects a request whose `AuthContext` was
68
185
  * not filled (no valid credential) with a `PithyError` `auth/invalid_token` (401).
186
+ *
187
+ * **A genuine credential for an account that may not act is refused with what happened to it** —
188
+ * `auth/account_suspended` or `auth/account_deleted`, 403 — rather than the 401, because signing in again
189
+ * cannot help and a client that read it as an expired token would loop. The verdict is the session
190
+ * middleware's, remembered for this request; this guard only raises it.
69
191
  */
70
192
  export function requireAuth(): MiddlewareHandler<PithyHonoEnv> {
71
193
  return async (c, next) => {
72
194
  if (!c.var.auth) {
195
+ const refusal = noticedRefusal(c);
196
+ if (refusal) throw refusal;
73
197
  throw new UnauthorizedError({
74
198
  message: "Authentication required.",
75
199
  action: "Sign in and retry with a valid session or bearer token.",
@@ -40,11 +40,11 @@
40
40
  *
41
41
  * | Code | Emitted only when |
42
42
  * | --- | --- |
43
- * | `account_not_linked` | a user row **did** match (`better-auth/dist/oauth2/link-account.mjs:86`) |
44
- * | `signup_disabled` | **no** row matched (`:202`) |
43
+ * | `account_not_linked` | a user row **did** match (`better-auth/dist/oauth2/link-account.mjs:142`) |
44
+ * | `signup_disabled` | **no** row matched (`:257`) |
45
45
  *
46
46
  * Both leave through one line — `redirectOnError(result.error.split(" ").join("_"))`,
47
- * `dist/api/routes/callback.mjs:245` — so from outside the Worker they are one question with two
47
+ * `dist/api/routes/callback.mjs:197` — so from outside the Worker they are one question with two
48
48
  * answers. Press the provider button, read the `Location` header, repeat: an account-enumeration oracle
49
49
  * needing one GitHub account, no account on the target, and no page render. It works against the
50
50
  * configuration the kit's own security guidance recommends (`allowSignUp: false`, #554), so the
@@ -75,9 +75,10 @@
75
75
  * ## This module is the second line of defense, not the only one
76
76
  *
77
77
  * It reads the `Location` a refused callback answered with — which is the output of
78
- * `redirectOnError`'s raw string concatenation (`callback.mjs:78`), performed on a value the caller
79
- * supplied. It was walked around twice that way, and the second bypass was the diagnosis: **every input
80
- * shape where that concatenation and this parsing disagree is another one**, so patching the parsing
78
+ * `redirectOnError` (`callback.mjs:78`), built on a value the caller supplied. 1.7.1 concatenated it raw;
79
+ * 1.7.11 parses it with `new URL` in `@better-auth/core`'s `appendQueryParams`, which sets the query
80
+ * before any fragment and throws on a `//` or `/\` input. It was walked around twice on 1.7.1, and the second bypass
81
+ * was the diagnosis: **every input shape where that construction and this parsing disagree is another one**, so patching the parsing
81
82
  * again only moves the report later. `./errorCallbackUrl` therefore guards the value on the way *in*,
82
83
  * and by the time this module runs the string being parsed is one the kit produced.
83
84
  *
@@ -123,7 +124,7 @@ interface RefusalVerdict {
123
124
  * `providerRefusal.test.ts` reads Better Auth's own `OAUTH_CALLBACK_ERROR_CODES`, scans the
124
125
  * `result.error` literals out of `link-account.mjs`, and scans the `new APIError(…, { code })` sites in
125
126
  * both codebases — `better-auth`'s on the callback's path and the kit's across this whole package,
126
- * because `callback.mjs:239` re-emits *anything* thrown inside `handleOAuthUserInfo` as `?error=`. Every
127
+ * because `callback.mjs:192` re-emits *anything* thrown inside `handleOAuthUserInfo` as `?error=`. Every
127
128
  * code any of them can produce must appear here. A dependency bump that adds one turns that red, and
128
129
  * somebody writes a verdict for it. So the roster records a *review*, and the review cannot silently fall
129
130
  * behind the thing it reviews.
@@ -140,11 +141,11 @@ const PROVIDER_REFUSAL_VERDICTS: Readonly<Record<string, RefusalVerdict>> = {
140
141
  // ── Decided by the user table. These are the defect. ───────────────────────────────────────────
141
142
  account_not_linked: {
142
143
  collapse: true,
143
- why: "link-account.mjs:86 — returned only inside `if (dbUser)`, so it is literally the statement that a row matched.",
144
+ why: "link-account.mjs:142 — returned only inside `if (dbUser)`, so it is literally the statement that a row matched.",
144
145
  },
145
146
  signup_disabled: {
146
147
  collapse: true,
147
- why: "link-account.mjs:202 — the `else` of that same branch, so it is literally the statement that none did.",
148
+ why: "link-account.mjs:257 — the `else` of that same branch, so it is literally the statement that none did.",
148
149
  },
149
150
  EMAIL_NOT_VERIFIED: {
150
151
  collapse: true,
@@ -152,15 +153,30 @@ const PROVIDER_REFUSAL_VERDICTS: Readonly<Record<string, RefusalVerdict>> = {
152
153
  },
153
154
  unable_to_create_user: {
154
155
  collapse: true,
155
- why: "link-account.mjs:254 — the create path only, so it sits on the no-row side exactly as `signup_disabled` does. A fault rather than a refusal, and still an answer to the question being asked.",
156
+ why: "link-account.mjs:301/308 — the create path only, so it sits on the no-row side exactly as `signup_disabled` does. A fault rather than a refusal, and still an answer to the question being asked.",
156
157
  },
157
158
  INVALID_PROFILE_FIELD: {
158
159
  collapse: true,
159
- why: "The kit's `user.update.before` hook, and **the branch it sits on was read wrong the first time.** `if (dbUser) {` opens at link-account.mjs:77 and the `if (!linkedAccount) {…} else {…}` pair sits *inside* it, so the ownership argument that carries `unable_to_update_account` does not reach here: the `updateUser` that can carry a provider's `name`/`image` is the `overrideUserInfo` write at :185, which runs after **either** sub-branch — including the one that has just linked an account that did not exist a line earlier. What every path to it does share is `if (dbUser)`: a matched row. The other side of that branch calls `createUser`, where the kit's `user.create.before` **sanitizes** the same two fields instead of refusing them. So a hostile provider display name answers `?error=INVALID_PROFILE_FIELD` against an address that has a row and a completed sign-in against one that does not, which is the oracle with a different name on it.",
160
+ why: "The kit's `user.update.before` hook, and **the branch it sits on was read wrong the first time.** `if (dbUser) {` opens at link-account.mjs:133 and the `if (!linkedAccount) {…} else {…}` pair sits *inside* it, so the ownership argument that carries `unable_to_update_account` does not reach here: the `updateUser` writes that can carry a provider's `name`/`image` are the `overrideUserInfo` write at :238, which runs after **either** sub-branch, and since 1.7.3 the `updateUserInfoOnLink` write at :189 on the branch that has just linked an account that did not exist a line earlier. What every path to it does share is `if (dbUser)`: a matched row. The other side of that branch calls `createUser`, where the kit's `user.create.before` **sanitizes** the same two fields instead of refusing them. So a hostile provider display name answers `?error=INVALID_PROFILE_FIELD` against an address that has a row and a completed sign-in against one that does not, which is the oracle with a different name on it.",
160
161
  },
161
162
  validation_context_missing: {
162
163
  collapse: true,
163
- why: "internal-adapter.mjs:160 — raised when `getCurrentAuthContext()` fails inside `createUser`, and `createUser` is the no-row side. `updateUser` runs no such check (internal-adapter.mjs:599), so this code cannot be observed against an address that has a row: it is `signup_disabled`'s shape reached through the adopter's `validateUserInfo` option rather than through the sign-up policy.",
164
+ why: "internal-adapter.mjs:160 — raised when `getCurrentAuthContext()` fails inside `createUser`, and `createUser` is the no-row side. `updateUser` runs no such check (internal-adapter.mjs:616), so this code cannot be observed against an address that has a row: it is `signup_disabled`'s shape reached through the adopter's `validateUserInfo` option rather than through the sign-up policy.",
165
+ },
166
+
167
+ unable_to_link_account: {
168
+ collapse: true,
169
+ why: "Two producers, and the verdict follows the one that reads our rows. `linkOAuthAccount` (link-account.mjs:45/68) answers it on `/link-social`, where the caller is signed in as the user being changed. But `handleOAuthUserInfo` answers it too, inside `if (dbUser)` when the account write fails (:171/:184), so on the social callback it says a row matched, and `unable_to_create_user` is its other half. Collapsing costs the signed-in linker a specific code for a fault. Letting it travel would cost the oracle. Corrected in #787; the earlier verdict read only the link flow.",
170
+ },
171
+
172
+ // ── The account's own standing, told to the person who just proved they hold it. ──────────────
173
+ "auth/account_suspended": {
174
+ collapse: false,
175
+ why: "The kit's own `session.create.before` hook (instance/auth.ts, #620). A session is only ever created for a user the callback has already resolved and linked — the caller has just proved control of a provider identity bound to this account — so the code is told to its holder, never to somebody probing an address. Collapsing it would leave a suspended person with a screen that says nothing happened.",
176
+ },
177
+ "auth/account_deleted": {
178
+ collapse: false,
179
+ why: "The same hook, for an account inside its purge window, and the same reasoning: it is reached only after the caller authenticated as the account, so it names the state of their own account to them.",
164
180
  },
165
181
 
166
182
  // ── The caller's own request, or the provider's. Nothing to do with our rows. ──────────────────
@@ -174,7 +190,7 @@ const PROVIDER_REFUSAL_VERDICTS: Readonly<Record<string, RefusalVerdict>> = {
174
190
  },
175
191
  invalid_callback_request: {
176
192
  collapse: false,
177
- why: "callback.mjs:55 — the callback's own query or body would not parse. Raised before `parseState`, so nothing had been read from anywhere yet.",
193
+ why: "callback.mjs:54 — the callback's own query or body would not parse. Raised before `parseState`, so nothing had been read from anywhere yet.",
178
194
  },
179
195
  oauth_provider_not_found: {
180
196
  collapse: false,
@@ -206,15 +222,15 @@ const PROVIDER_REFUSAL_VERDICTS: Readonly<Record<string, RefusalVerdict>> = {
206
222
  },
207
223
  email_not_verified: {
208
224
  collapse: false,
209
- why: "Better Auth's lower-case code, from `requireEmailVerification` (link-account.mjs:263) — which the kit does not set. Reachable for a registering and a returning user alike, so it names no row either way. Not to be confused with the kit's upper-case `EMAIL_NOT_VERIFIED` above; the two are different strings from different places and only one of them is the oracle.",
225
+ why: "Better Auth's lower-case code, from `requireEmailVerification` (link-account.mjs:317) — which the kit does not set. Reachable for a registering and a returning user alike, so it names no row either way. Not to be confused with the kit's upper-case `EMAIL_NOT_VERIFIED` above; the two are different strings from different places and only one of them is the oracle.",
210
226
  },
211
227
  unable_to_create_session: {
212
228
  collapse: false,
213
- why: "link-account.mjs:269 — after the user is resolved, so it is reached from both sides of the branch equally.",
229
+ why: "link-account.mjs:324 — after the user is resolved, so it is reached from both sides of the branch equally.",
214
230
  },
215
231
  state_not_found: {
216
232
  collapse: false,
217
- why: "The request carried no state to parse. Raised at state.mjs:90, before any lookup.",
233
+ why: "The request carried no state to parse. Raised at state.mjs:93, before any lookup.",
218
234
  },
219
235
  state_mismatch: {
220
236
  collapse: false,
@@ -238,7 +254,7 @@ const PROVIDER_REFUSAL_VERDICTS: Readonly<Record<string, RefusalVerdict>> = {
238
254
  },
239
255
  account_hook_binding_conflict: {
240
256
  collapse: false,
241
- why: "link-account.mjs:120/176/237 — a hook moved the account binding out from under the write that had just been made. Raised on the link path, the sign-in path *and* the create path, so it is reached from both sides of `if (dbUser)` equally and names neither.",
257
+ why: "link-account.mjs:175/231/291 — a hook moved the account binding out from under the write that had just been made. Raised on the link path, the sign-in path *and* the create path, so it is reached from both sides of `if (dbUser)` equally and names neither.",
242
258
  },
243
259
  validation_source_missing: {
244
260
  collapse: false,
@@ -246,14 +262,10 @@ const PROVIDER_REFUSAL_VERDICTS: Readonly<Record<string, RefusalVerdict>> = {
246
262
  },
247
263
  validation_failed: {
248
264
  collapse: false,
249
- why: "validate-user-info.mjs:34 — the adopter's own `validateUserInfo` callback threw, and Better Auth fails closed. Called on the link path (link-account.mjs:92), the sign-in path (:137) and the create path (internal-adapter.mjs:164), so it is reachable whether or not a row matched. What that callback *returns* is the adopter's own code and travels off-roster, which is the same decision as for the provider's own `error` values.",
265
+ why: "validate-user-info.mjs:34 — the adopter's own `validateUserInfo` callback threw, and Better Auth fails closed. Called on the link path (link-account.mjs:24 and :148), the sign-in path (:192) and the create path (internal-adapter.mjs:164), so it is reachable whether or not a row matched. What that callback *returns* is the adopter's own code and travels off-roster, which is the same decision as for the provider's own `error` values.",
250
266
  },
251
267
 
252
268
  // ── The link flow. The caller already holds a session for the account in question. ─────────────
253
- unable_to_link_account: {
254
- collapse: false,
255
- why: "callback.mjs:173/198, inside `if (link)` — reachable only on `/link-social`, where the caller is signed in as the user being changed. Telling somebody about their own account is not enumeration.",
256
- },
257
269
  email_does_not_match: {
258
270
  collapse: false,
259
271
  why: "The link flow, and the address compared against is the signed-in caller's own. The caller's account, as above.",
@@ -264,7 +276,7 @@ const PROVIDER_REFUSAL_VERDICTS: Readonly<Record<string, RefusalVerdict>> = {
264
276
  },
265
277
  unable_to_update_account: {
266
278
  collapse: false,
267
- why: "link-account.mjs:172, inside `if (linkedAccount)` — reaching it requires an account row already binding this provider identity to this user, and the caller proved control of that identity at the provider to get here. Ownership, not a matched row. (This is the argument `INVALID_PROFILE_FIELD` was wrongly given: that code's write sits outside this branch.)",
279
+ why: "link-account.mjs:227, inside `if (linkedAccount)` — reaching it requires an account row already binding this provider identity to this user, and the caller proved control of that identity at the provider to get here. Ownership, not a matched row. (This is the argument `INVALID_PROFILE_FIELD` was wrongly given: that code's write sits outside this branch.)",
268
280
  },
269
281
 
270
282
  // ── The account-selection flow, which the social callback never enters. ────────────────────────
@@ -274,23 +286,19 @@ const PROVIDER_REFUSAL_VERDICTS: Readonly<Record<string, RefusalVerdict>> = {
274
286
  // verdict a reader can check, where silence is not.
275
287
  account_ownership_conflict: {
276
288
  collapse: false,
277
- why: "link-account.mjs:38, inside `if (opts.selectedUser && …)`. The lookup it reports on is keyed by the *provider* identity the caller has just proved control of, not by an address handed over — and the social callback passes no `selectedUser`, so this never reaches that redirect at all.",
278
- },
279
- account_provider_conflict: {
280
- collapse: false,
281
- why: "link-account.mjs:42, guarded by `requireExactAccountBinding`, which is `opts.selectedUser || opts.requireExactAccountBinding` — neither of which `callback.mjs` passes. Keyed by the caller's own provider identity, as above.",
289
+ why: "link-account.mjs:97, inside `if (opts.selectedUser && …)`. The lookup it reports on is keyed by the *provider* identity the caller has just proved control of, not by an address handed over — and the social callback passes no `selectedUser`, so this never reaches that redirect at all.",
282
290
  },
283
291
  user_not_found: {
284
292
  collapse: false,
285
- why: "link-account.mjs:54 — `findUserById(opts.selectedUser.userId)`, so it answers about a user id the caller was already handed, on a flow the social callback does not enter. It reads a row by id, never by a provider-resolved address.",
293
+ why: "link-account.mjs:109 — `findUserById(opts.selectedUser.userId)`, so it answers about a user id the caller was already handed, on a flow the social callback does not enter. It reads a row by id, never by a provider-resolved address.",
286
294
  },
287
295
  user_hook_selection_conflict: {
288
296
  collapse: false,
289
- why: "link-account.mjs:195, inside `if (opts.selectedUser …)`. A hook returned a different user than the one the caller picked from a list they had already been shown, and the social callback never picks one.",
297
+ why: "link-account.mjs:249, inside `if (opts.selectedUser …)`. A hook returned a different user than the one the caller picked from a list they had already been shown, and the social callback never picks one.",
290
298
  },
291
299
  session_hook_user_conflict: {
292
300
  collapse: false,
293
- why: "link-account.mjs:275 — after the user is resolved and the session minted, under the same `requireExactAccountBinding` gate. Reached from both sides of `if (dbUser)` when it is reached at all, which on the social callback is never.",
301
+ why: "link-account.mjs:328 — after the user is resolved and the session minted, under the same `requireExactAccountBinding` gate. Reached from both sides of `if (dbUser)` when it is reached at all, which on the social callback is never.",
294
302
  },
295
303
  };
296
304
 
@@ -344,7 +352,7 @@ export interface CollapsedRefusal {
344
352
  *
345
353
  * - **It need not be absolute.** `api/middlewares/origin-check.mjs` passes `allowRelativePaths: true`,
346
354
  * `matchesOriginPattern` admits `/path?query`, `oauth2/state.mjs` stores the value as a bare
347
- * `z.string().optional()`, and `redirectOnError` concatenates it raw. So a relative `Location` is a
355
+ * `z.string().optional()`, and `redirectOnError` keeps it root-relative. So a relative `Location` is a
348
356
  * supported answer, and returning `undefined` to one sent the true code to the browser and wrote no
349
357
  * audit row.
350
358
  * - **`error` need not be the only one.** `redirectOnError` *appends* `&error=<code>`. An
@@ -2,8 +2,10 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import type { D1Database } from "@cloudflare/workers-types";
5
+ import type { AuditEventInput } from "@pithy-sh/core/src/audit/auditEvent";
5
6
  import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
6
7
  import { InternalError } from "@pithy-sh/core/src/error/pithyError";
8
+ import { createWorkerLogger } from "@pithy-sh/core/src/logger/worker";
7
9
  import type { EmailEnqueueEnv } from "@pithy-sh/email/src/capability";
8
10
  import type { SecretsStoreEnv } from "@pithy-sh/secrets/src/env/bindings";
9
11
  import type { Context } from "hono";
@@ -11,13 +13,15 @@ import type { AuthWiring } from "../capability";
11
13
  import { authDatabase } from "../data/tables";
12
14
  import { makeSendAuthEmail, type ResolveRecipientLocale } from "../email/send";
13
15
  import { type AuthInstance, makeAuth } from "../instance/auth";
16
+ import { ensureJwksSealedUnderCurrent } from "../instance/jwksReencryption";
14
17
  import { resolveProvider } from "../instance/providers";
15
18
  import {
16
19
  resolveAppleCredentials,
17
20
  resolveFacebookCredentials,
18
21
  resolveGithubCredentials,
19
22
  resolveGoogleCredentials,
20
- resolveSessionSecret,
23
+ resolveMicrosoftCredentials,
24
+ resolveSessionSecrets,
21
25
  } from "../instance/secrets";
22
26
  import { baseURLResolver } from "./baseUrl";
23
27
 
@@ -85,7 +89,7 @@ async function buildAuthInstance(c: Context<PithyHonoEnv>, wiring: AuthWiring):
85
89
  });
86
90
  }
87
91
  const env = c.env as unknown as AuthEnv;
88
- // Secret resolutions hit the same per-invocation cache; run them concurrently. Five reads, and they
92
+ // Secret resolutions hit the same per-invocation cache; run them concurrently. Six reads, and they
89
93
  // are not alike — which is the whole of #381.
90
94
  //
91
95
  // `resolveSessionSecret` is what an auth instance *is*: nothing signs a session without it, so its
@@ -103,15 +107,37 @@ async function buildAuthInstance(c: Context<PithyHonoEnv>, wiring: AuthWiring):
103
107
  //
104
108
  // A held failure belongs to its own secret (#170), so an unreadable provider credential does not
105
109
  // disturb the session secret's own read, and a *disabled* provider never calls `.get()` at all.
106
- const [secret, google, apple, facebook, github] = await Promise.all([
107
- resolveSessionSecret(env),
110
+ const [sessionSecrets, google, apple, facebook, github, microsoft] = await Promise.all([
111
+ resolveSessionSecrets(env),
108
112
  resolveProvider(cfg.google.enabled, () => resolveGoogleCredentials(env)),
109
113
  resolveProvider(cfg.apple.enabled, () => resolveAppleCredentials(env)),
110
114
  resolveProvider(cfg.facebook.enabled, () => resolveFacebookCredentials(env)),
111
115
  resolveProvider(cfg.github.enabled, () => resolveGithubCredentials(env)),
116
+ resolveProvider(cfg.microsoft.enabled, () => resolveMicrosoftCredentials(env)),
112
117
  ]);
113
118
  const expiresMinutes = Math.max(1, Math.round(cfg.verificationExpiresIn / 60));
114
119
  const d1 = resolveDb(c.env, cfg.database);
120
+ // The current version signs; every retained one opens (#602). A version set with no current entry is a
121
+ // corrupt envelope, and the store's own reader has already refused that — this narrows it for the type.
122
+ const secret = sessionSecrets.versions[sessionSecrets.currentVersion];
123
+ if (secret === undefined) {
124
+ throw new InternalError({
125
+ message: "Authentication is misconfigured.",
126
+ detail: "auth-session-secret resolved with no value at its current version",
127
+ });
128
+ }
129
+ // Mid-rotation, move the JWKS keys under the current version before the old one is retired, and record this
130
+ // database as a holder either way. Once per version per isolate, never fatal — see
131
+ // `../instance/jwksReencryption.ts`.
132
+ await ensureJwksSealedUnderCurrent({
133
+ db: authDatabase(d1),
134
+ holder: cfg.database,
135
+ secrets: env.SECRETS,
136
+ versions: sessionSecrets,
137
+ // Read off the context when a backend seeded one, as `createBackend` always does; a hand-built app in a
138
+ // test may not have, and a re-encryption that cannot say what it did must not break the request.
139
+ log: (c.get("log") ?? createWorkerLogger({ name: "auth" })).child("auth"),
140
+ });
115
141
  const listener = wiring.onSessionRevoked;
116
142
  return makeAuth({
117
143
  db: authDatabase(d1),
@@ -120,6 +146,7 @@ async function buildAuthInstance(c: Context<PithyHonoEnv>, wiring: AuthWiring):
120
146
  // has none.
121
147
  ...(listener ? { onSessionRevoked: (session: { id: string; userId: string }) => listener(session, d1) } : {}),
122
148
  secret,
149
+ sessionSecrets,
123
150
  // Never `cfg.baseURL` directly. The instance derives the session cookie's name, the OAuth callback
124
151
  // URLs, and the magic-link URL from whatever base URL it is handed, so in a `dev` composition every
125
152
  // one of those has to name the address this run is actually serving on — not the production origin
@@ -137,6 +164,7 @@ async function buildAuthInstance(c: Context<PithyHonoEnv>, wiring: AuthWiring):
137
164
  apple,
138
165
  facebook,
139
166
  github,
167
+ microsoft,
140
168
  sendEmail: makeSendAuthEmail(
141
169
  (input) => enqueueEmail(env, input),
142
170
  expiresMinutes,
@@ -155,11 +183,12 @@ async function buildAuthInstance(c: Context<PithyHonoEnv>, wiring: AuthWiring):
155
183
  apple: cfg.apple.allowSignUp,
156
184
  facebook: cfg.facebook.allowSignUp,
157
185
  github: cfg.github.allowSignUp,
186
+ microsoft: cfg.microsoft.allowSignUp,
158
187
  },
159
188
  ...(wiring.resolveGithubUserInfo ? { resolveGithubUserInfo: wiring.resolveGithubUserInfo } : {}),
160
189
  // Read the emit seam lazily so a later-composed audit capability is honored regardless of the
161
190
  // capability order (the instance may be built before audit's middleware runs).
162
- emit: (event) => c.var.emit(event),
191
+ emit: (event: AuditEventInput) => c.var.emit(event),
163
192
  // This request's own headers, for the refusal rows `../instance/providerSignInGate` writes from
164
193
  // inside `getUserInfo`, where no request is in scope to read them from.
165
194
  requestHeaders: c.req.raw.headers,