@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
@@ -1 +1 @@
1
- {"version":3,"file":"guards.d.ts","sourceRoot":"","sources":["../../src/http/guards.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sDAAsD,CAAC;AACvF,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,6CAA6C,CAAC;AAErF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmDG;AAEH;;;;GAIG;AACH,eAAO,MAAM,qBAAqB,EAAE,iBAAqC,CAAC;AAE1E;;;;GAIG;AACH,eAAO,MAAM,uBAAuB,EAAE,iBAAuC,CAAC;AAE9E;;;GAGG;AACH,eAAO,MAAM,0BAA0B,EAAE,iBAA0C,CAAC;AAEpF;;;;GAIG;AACH,eAAO,MAAM,uBAAuB,EAAE,iBAAuC,CAAC;AAE9E;;;;;GAKG;AACH,eAAO,MAAM,yBAAyB,EAAE,iBAAyC,CAAC;AAElF;;;GAGG;AACH,eAAO,MAAM,yBAAyB,EAAE,SAAS,iBAAiB,EAMjE,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,MAAM,GAAG,UAAU,EAAE,CAuC9D"}
1
+ {"version":3,"file":"guards.d.ts","sourceRoot":"","sources":["../../src/http/guards.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sDAAsD,CAAC;AACvF,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,6CAA6C,CAAC;AAErF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmDG;AAEH;;;;GAIG;AACH,eAAO,MAAM,qBAAqB,EAAE,iBAAqC,CAAC;AAE1E;;;;GAIG;AACH,eAAO,MAAM,uBAAuB,EAAE,iBAAuC,CAAC;AAE9E;;;GAGG;AACH,eAAO,MAAM,0BAA0B,EAAE,iBAA0C,CAAC;AAEpF;;;;GAIG;AACH,eAAO,MAAM,uBAAuB,EAAE,iBAAuC,CAAC;AAE9E;;;;;GAKG;AACH,eAAO,MAAM,yBAAyB,EAAE,iBAAyC,CAAC;AAElF;;;;GAIG;AACH,eAAO,MAAM,wBAAwB,EAAE,iBAAwC,CAAC;AAEhF;;;;GAIG;AACH,eAAO,MAAM,uBAAuB,EAAE,iBAAuC,CAAC;AAE9E;;;;GAIG;AACH,eAAO,MAAM,uBAAuB,EAAE,iBAAuC,CAAC;AAE9E;;;;;;;GAOG;AACH,eAAO,MAAM,yBAAyB,EAAE,SAAS,iBAAiB,EASjE,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,MAAM,GAAG,UAAU,EAAE,CAuC9D"}
@@ -26,7 +26,7 @@
26
26
  * every legitimate management call, permanently, and **no credential could fix it** — there is no user
27
27
  * to sign in as. `controlPlaneIsolation.workers.test.ts` pins both directions of that separation.
28
28
  *
29
- * ## Five scopes, because these are five different blast radii
29
+ * ## Eight scopes, because these are eight different blast radii
30
30
  *
31
31
  * The temptation is one `auth:admin` flag, and on this capability it is the most dangerous version of
32
32
  * that mistake. **Reading a user is a privacy operation; revoking their sessions is an availability
@@ -84,15 +84,40 @@ const AUTH_USERS_LOGOUT_SCOPE = "auth:users:logout";
84
84
  */
85
85
  const AUTH_DEVICES_REVOKE_SCOPE = "auth:devices:revoke";
86
86
  /**
87
+ * Suspend an account and reinstate it (#620, the routes in #621). Ending somebody's access is an availability
88
+ * operation on one person, and reversible — which is what separates it from deleting them, and why it is
89
+ * granted apart from both reading them and erasing them.
90
+ */
91
+ const AUTH_USERS_SUSPEND_SCOPE = "auth:users:suspend";
92
+ /**
93
+ * Delete an account, restore one inside its purge window, and start a purge (#620, the routes in #622). The
94
+ * one scope on this surface whose worst case cannot be undone: once the window closes, the person's rows are
95
+ * gone from every capability that held them.
96
+ */
97
+ const AUTH_USERS_DELETE_SCOPE = "auth:users:delete";
98
+ /**
99
+ * Export everything the kit holds about one account — the answer to an access request (#620, the route in
100
+ * #622). A disclosure, and a far larger one than reading the user: it carries every capability's rows about
101
+ * them, so it is granted on its own and audited as one.
102
+ */
103
+ const AUTH_USERS_EXPORT_SCOPE = "auth:users:export";
104
+ /**
87
105
  * Every control-plane scope auth defines — what `pithy dashboard connect` offers for this capability,
88
106
  * and the list a manifest or a doc quotes rather than re-typing.
107
+ *
108
+ * **The three lifecycle scopes are declared before the routes that require them.** The suspend, delete and
109
+ * export routes land in #621 and #622; declaring the vocabulary here, once, is what lets those issues build on
110
+ * one name each rather than three issues each choosing their own.
89
111
  */
90
112
  const AUTH_CONTROL_PLANE_SCOPES = [
91
113
  AUTH_USERS_READ_SCOPE,
92
114
  AUTH_DEVICES_READ_SCOPE,
93
115
  AUTH_SESSIONS_REVOKE_SCOPE,
94
116
  AUTH_USERS_LOGOUT_SCOPE,
95
- AUTH_DEVICES_REVOKE_SCOPE
117
+ AUTH_DEVICES_REVOKE_SCOPE,
118
+ AUTH_USERS_SUSPEND_SCOPE,
119
+ AUTH_USERS_DELETE_SCOPE,
120
+ AUTH_USERS_EXPORT_SCOPE
96
121
  ];
97
122
  /**
98
123
  * Auth's management surface, as `GET /control-plane/manifest` reports it.
@@ -147,4 +172,4 @@ function authAdminRoutes(basePath) {
147
172
  ];
148
173
  }
149
174
  //#endregion
150
- export { AUTH_CONTROL_PLANE_SCOPES, AUTH_DEVICES_READ_SCOPE, AUTH_DEVICES_REVOKE_SCOPE, AUTH_SESSIONS_REVOKE_SCOPE, AUTH_USERS_LOGOUT_SCOPE, AUTH_USERS_READ_SCOPE, authAdminRoutes };
175
+ export { AUTH_CONTROL_PLANE_SCOPES, AUTH_DEVICES_READ_SCOPE, AUTH_DEVICES_REVOKE_SCOPE, AUTH_SESSIONS_REVOKE_SCOPE, AUTH_USERS_DELETE_SCOPE, AUTH_USERS_EXPORT_SCOPE, AUTH_USERS_LOGOUT_SCOPE, AUTH_USERS_READ_SCOPE, AUTH_USERS_SUSPEND_SCOPE, authAdminRoutes };
@@ -0,0 +1,18 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { PithyError } from "@pithy-sh/core/src/error/pithyError";
4
+ /** Whether a refused account's credential may still reach this Better Auth endpoint (path relative to `basePath`). */
5
+ export declare function admitsRefusedAccount(path: string): boolean;
6
+ /**
7
+ * The redirect a refused magic link answers with: back to the screen the link named, carrying the code as
8
+ * `?error=`, exactly as Better Auth's own `redirectWithError` does for the refusals it raises itself
9
+ * (`plugins/magic-link/index.mjs`). `null` when the target is not one this Worker trusts, and the caller
10
+ * answers the refusal as JSON instead.
11
+ *
12
+ * A browser following a magic link is mid-navigation, so a 403 body would strand it on the API's origin
13
+ * with nothing to read; the adopter's screen is where the copy for this state lives. Better Auth has already
14
+ * checked the URLs by the time a session is refused, so the trust check is defense in depth — a refusal must
15
+ * not become an open redirect.
16
+ */
17
+ export declare function lifecycleRedirect(requestUrl: URL, baseURL: string, trustedOrigins: readonly string[], refusal: PithyError): Response | null;
18
+ //# sourceMappingURL=lifecycleGate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lifecycleGate.d.ts","sourceRoot":"","sources":["../../src/http/lifecycleGate.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qCAAqC,CAAC;AA8BtE,sHAAsH;AACtH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAG1D;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,iBAAiB,CAC/B,UAAU,EAAE,GAAG,EACf,OAAO,EAAE,MAAM,EACf,cAAc,EAAE,SAAS,MAAM,EAAE,EACjC,OAAO,EAAE,UAAU,GAClB,QAAQ,GAAG,IAAI,CAYjB"}
@@ -0,0 +1,75 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ //#region src/http/lifecycleGate.ts
4
+ /**
5
+ * Where a suspended or deleted account meets Better Auth's own endpoints (#620).
6
+ *
7
+ * The session middleware refuses such an account an `AuthContext`, which closes every kit route. Better Auth's
8
+ * catch-all is the one place that does not ask: it resolves the session itself, so `/token` would mint a fresh
9
+ * access token for an account the rest of the Worker refuses. `handleBetterAuth` therefore refuses the
10
+ * middleware's verdict here too — everywhere except the endpoints below.
11
+ */
12
+ /**
13
+ * The endpoints that never act as the account the presented credential names, relative to `basePath`.
14
+ *
15
+ * Signing out must always work. And each of the rest *starts* a session rather than using one, so a stale
16
+ * cookie a suspended person left on a shared machine must not stop somebody else signing in — the session
17
+ * that results is checked where it is created, in `session.create.before`. Everything else is refused by
18
+ * default: an endpoint nobody listed may be one a plugin added, and an account that may not act may not act
19
+ * there either.
20
+ */
21
+ const ADMITTED_PREFIXES = [
22
+ "/sign-out",
23
+ "/sign-in/",
24
+ "/magic-link/verify",
25
+ "/email-otp/",
26
+ "/callback/",
27
+ "/oauth2/callback/"
28
+ ];
29
+ const ADMITTED_EXACT = /* @__PURE__ */ new Set([
30
+ "/jwks",
31
+ "/ok",
32
+ "/error"
33
+ ]);
34
+ /** Whether a refused account's credential may still reach this Better Auth endpoint (path relative to `basePath`). */
35
+ function admitsRefusedAccount(path) {
36
+ if (ADMITTED_EXACT.has(path)) return true;
37
+ return ADMITTED_PREFIXES.some((prefix) => path === prefix || path.startsWith(prefix));
38
+ }
39
+ /**
40
+ * The redirect a refused magic link answers with: back to the screen the link named, carrying the code as
41
+ * `?error=`, exactly as Better Auth's own `redirectWithError` does for the refusals it raises itself
42
+ * (`plugins/magic-link/index.mjs`). `null` when the target is not one this Worker trusts, and the caller
43
+ * answers the refusal as JSON instead.
44
+ *
45
+ * A browser following a magic link is mid-navigation, so a 403 body would strand it on the API's origin
46
+ * with nothing to read; the adopter's screen is where the copy for this state lives. Better Auth has already
47
+ * checked the URLs by the time a session is refused, so the trust check is defense in depth — a refusal must
48
+ * not become an open redirect.
49
+ */
50
+ function lifecycleRedirect(requestUrl, baseURL, trustedOrigins, refusal) {
51
+ const named = requestUrl.searchParams.get("errorCallbackURL") || requestUrl.searchParams.get("callbackURL") || "/";
52
+ let target;
53
+ try {
54
+ target = new URL(named, baseURL);
55
+ } catch {
56
+ return null;
57
+ }
58
+ if (!(/* @__PURE__ */ new Set([new URL(baseURL).origin, ...trustedOrigins.flatMap((origin) => originOf(origin))])).has(target.origin)) return null;
59
+ target.searchParams.set("error", refusal.payload.code);
60
+ return new Response(null, {
61
+ status: 302,
62
+ headers: { location: target.toString() }
63
+ });
64
+ }
65
+ /** An origin's canonical form, or nothing for an entry that is not a URL (a bare deep-link scheme). */
66
+ function originOf(value) {
67
+ try {
68
+ const origin = new URL(value).origin;
69
+ return origin === "null" ? [] : [origin];
70
+ } catch {
71
+ return [];
72
+ }
73
+ }
74
+ //#endregion
75
+ export { admitsRefusedAccount, lifecycleRedirect };
@@ -7,6 +7,11 @@ export declare function createSessionMiddleware(wiring: AuthWiring): PithyMiddle
7
7
  /**
8
8
  * The gate other capabilities stack on a protected route. Rejects a request whose `AuthContext` was
9
9
  * not filled (no valid credential) with a `PithyError` `auth/invalid_token` (401).
10
+ *
11
+ * **A genuine credential for an account that may not act is refused with what happened to it** —
12
+ * `auth/account_suspended` or `auth/account_deleted`, 403 — rather than the 401, because signing in again
13
+ * cannot help and a client that read it as an expired token would loop. The verdict is the session
14
+ * middleware's, remembered for this request; this guard only raises it.
10
15
  */
11
16
  export declare function requireAuth(): MiddlewareHandler<PithyHonoEnv>;
12
17
  //# sourceMappingURL=middleware.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../../src/http/middleware.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,0CAA0C,CAAC;AAI9F,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAC9C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAgBhD,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,UAAU,GAAG,eAAe,CAuC3E;AAED;;;GAGG;AACH,wBAAgB,WAAW,IAAI,iBAAiB,CAAC,YAAY,CAAC,CAU7D"}
1
+ {"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../../src/http/middleware.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,0CAA0C,CAAC;AAI9F,OAAO,KAAK,EAAW,iBAAiB,EAAE,MAAM,MAAM,CAAC;AACvD,OAAO,KAAK,EAAE,UAAU,EAAuC,MAAM,eAAe,CAAC;AA6DrF,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,UAAU,GAAG,eAAe,CAqB3E;AA4FD;;;;;;;;GAQG;AACH,wBAAgB,WAAW,IAAI,iBAAiB,CAAC,YAAY,CAAC,CAY7D"}
@@ -1,7 +1,11 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
- import { getAuthInstance } from "./resolve.js";
4
- import { UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
3
+ import { authDatabase } from "../data/tables.js";
4
+ import { LifecycleColumns } from "../lifecycle/state.js";
5
+ import { lifecycleRefusalFor, noteRefusal, noticedRefusal } from "../lifecycle/enforce.js";
6
+ import { getAuthInstance, resolveDb } from "./resolve.js";
7
+ import { withResignedCredentials } from "./credentialResign.js";
8
+ import { InternalError, UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
5
9
  import { isLocale } from "@pithy-sh/core/src/i18n/locale";
6
10
  import { AuthContext } from "@pithy-sh/core/src/http/authContext";
7
11
  //#region src/http/middleware.ts
@@ -17,37 +21,125 @@ function authenticatedDate(session) {
17
21
  const value = session.authenticatedAt;
18
22
  return value instanceof Date ? value : null;
19
23
  }
24
+ /**
25
+ * The scopes this request's caller resolves to — what the adopter's resolver answered, or `[]`.
26
+ *
27
+ * **Closed on every failure, and never fatal** (#560). A resolver that throws or rejects, and one that answers
28
+ * something other than a list of strings, both leave the request with no scopes and a warning: a gate then
29
+ * refuses it as it would any untrusted caller, rather than the request becoming a 500 or — worse — a
30
+ * malformed answer reaching a guard that would read `includes` off a string. Validated through
31
+ * `AuthContext`'s own field, so this and the context the middleware publishes cannot disagree on the shape.
32
+ *
33
+ * The warning names the session and never the answer: whatever the resolver handed back is the adopter's,
34
+ * and a log is not where to learn what a caller was trusted with.
35
+ */
36
+ async function resolvedScopes(c, resolve, session) {
37
+ if (resolve === void 0) return [];
38
+ let answer;
39
+ try {
40
+ answer = await resolve(c, session);
41
+ } catch (error) {
42
+ c.var.log.child("auth").warn("resolveScopes failed; this request carries no scopes", {
43
+ sessionId: session.sessionId,
44
+ reason: error instanceof Error ? error.message : String(error)
45
+ });
46
+ return [];
47
+ }
48
+ const parsed = AuthContext.shape.scopes.safeParse(answer);
49
+ if (!parsed.success || answer === void 0) {
50
+ c.var.log.child("auth").warn("resolveScopes answered something that is not a list of strings; this request carries no scopes", { sessionId: session.sessionId });
51
+ return [];
52
+ }
53
+ return parsed.data;
54
+ }
20
55
  function createSessionMiddleware(wiring) {
21
56
  return (app) => {
22
57
  app.use("*", async (c, next) => {
23
- const headers = c.req.raw.headers;
24
- if (headers.has("authorization") || headers.has("cookie")) try {
25
- const session = await (await getAuthInstance(c, wiring)).api.getSession({ headers });
26
- if (session) {
27
- const stored = session.user.locale;
28
- c.set("auth", AuthContext.parse({
29
- userId: session.user.id,
30
- sessionId: session.session.id,
31
- scopes: [],
32
- locale: typeof stored === "string" && isLocale(stored) ? stored : null,
33
- authenticatedAt: authenticatedDate(session.session)
34
- }));
35
- }
36
- } catch {}
37
- await next();
58
+ if (!c.req.raw.headers.has("authorization") && !c.req.raw.headers.has("cookie")) return await next();
59
+ let instance;
60
+ try {
61
+ instance = await getAuthInstance(c, wiring);
62
+ } catch {
63
+ instance = void 0;
64
+ }
65
+ if (instance === void 0) return await next();
66
+ const built = instance;
67
+ await withResignedCredentials(c, built, async () => {
68
+ await resolveSession(c, wiring, built);
69
+ await next();
70
+ });
38
71
  });
39
72
  };
40
73
  }
74
+ /** Fill `c.var.auth` from the request's credential, or leave it null. Never throws. */
75
+ async function resolveSession(c, wiring, instance) {
76
+ const headers = c.req.raw.headers;
77
+ try {
78
+ const session = await instance.api.getSession({ headers });
79
+ if (session) {
80
+ const refusal = await standingRefusal(c, wiring, session.user);
81
+ if (refusal) {
82
+ noteRefusal(c, refusal);
83
+ return;
84
+ }
85
+ const scopes = await resolvedScopes(c, wiring.resolveScopes, {
86
+ userId: session.user.id,
87
+ sessionId: session.session.id
88
+ });
89
+ const stored = session.user.locale;
90
+ c.set("auth", AuthContext.parse({
91
+ userId: session.user.id,
92
+ sessionId: session.session.id,
93
+ scopes,
94
+ locale: typeof stored === "string" && isLocale(stored) ? stored : null,
95
+ authenticatedAt: authenticatedDate(session.session)
96
+ }));
97
+ }
98
+ } catch {}
99
+ }
100
+ /**
101
+ * The refusal for the session's account, or `null` when it may act.
102
+ *
103
+ * **A check that cannot be made refuses**, rather than throwing into `resolveSession`'s catch. That catch
104
+ * leaves `auth` null and notes nothing, and `handleBetterAuth` only refuses on a noted verdict — so a failed
105
+ * read of a suspension's reason, or a column that will not decode, would let Better Auth's own `/token` mint a
106
+ * JWT for the suspended account it resolved on its own. So the failure is logged and becomes the verdict: a
107
+ * 500, since the fault is this Worker's, and every door that honors a lifecycle refusal honors this one.
108
+ */
109
+ async function standingRefusal(c, wiring, user) {
110
+ try {
111
+ return await lifecycleRefusalFor(authDatabase(resolveDb(c.env, wiring.config.database)), user.id, LifecycleColumns.parse(user), /* @__PURE__ */ new Date());
112
+ } catch (cause) {
113
+ c.var.log?.child("auth").warn("the account's standing could not be checked; the request is refused", {
114
+ userId: user.id,
115
+ reason: cause instanceof Error ? cause.message : String(cause)
116
+ });
117
+ return new InternalError({
118
+ message: "This account could not be checked. Try again shortly.",
119
+ action: "Check the auth database binding and that the auth migrations have run.",
120
+ detail: `lifecycle check for user ${user.id} failed`
121
+ }, { cause });
122
+ }
123
+ }
41
124
  /**
42
125
  * The gate other capabilities stack on a protected route. Rejects a request whose `AuthContext` was
43
126
  * not filled (no valid credential) with a `PithyError` `auth/invalid_token` (401).
127
+ *
128
+ * **A genuine credential for an account that may not act is refused with what happened to it** —
129
+ * `auth/account_suspended` or `auth/account_deleted`, 403 — rather than the 401, because signing in again
130
+ * cannot help and a client that read it as an expired token would loop. The verdict is the session
131
+ * middleware's, remembered for this request; this guard only raises it.
44
132
  */
45
133
  function requireAuth() {
46
134
  return async (c, next) => {
47
- if (!c.var.auth) throw new UnauthorizedError({
48
- message: "Authentication required.",
49
- action: "Sign in and retry with a valid session or bearer token."
50
- });
135
+ if (!c.var.auth) {
136
+ const refusal = noticedRefusal(c);
137
+ if (refusal) throw refusal;
138
+ throw new UnauthorizedError({
139
+ message: "Authentication required.",
140
+ action: "Sign in and retry with a valid session or bearer token."
141
+ });
142
+ }
51
143
  await next();
52
144
  };
53
145
  }
@@ -39,11 +39,11 @@
39
39
  *
40
40
  * | Code | Emitted only when |
41
41
  * | --- | --- |
42
- * | `account_not_linked` | a user row **did** match (`better-auth/dist/oauth2/link-account.mjs:86`) |
43
- * | `signup_disabled` | **no** row matched (`:202`) |
42
+ * | `account_not_linked` | a user row **did** match (`better-auth/dist/oauth2/link-account.mjs:142`) |
43
+ * | `signup_disabled` | **no** row matched (`:257`) |
44
44
  *
45
45
  * Both leave through one line — `redirectOnError(result.error.split(" ").join("_"))`,
46
- * `dist/api/routes/callback.mjs:245` — so from outside the Worker they are one question with two
46
+ * `dist/api/routes/callback.mjs:197` — so from outside the Worker they are one question with two
47
47
  * answers. Press the provider button, read the `Location` header, repeat: an account-enumeration oracle
48
48
  * needing one GitHub account, no account on the target, and no page render. It works against the
49
49
  * configuration the kit's own security guidance recommends (`allowSignUp: false`, #554), so the
@@ -74,9 +74,10 @@
74
74
  * ## This module is the second line of defense, not the only one
75
75
  *
76
76
  * It reads the `Location` a refused callback answered with — which is the output of
77
- * `redirectOnError`'s raw string concatenation (`callback.mjs:78`), performed on a value the caller
78
- * supplied. It was walked around twice that way, and the second bypass was the diagnosis: **every input
79
- * shape where that concatenation and this parsing disagree is another one**, so patching the parsing
77
+ * `redirectOnError` (`callback.mjs:78`), built on a value the caller supplied. 1.7.1 concatenated it raw;
78
+ * 1.7.11 parses it with `new URL` in `@better-auth/core`'s `appendQueryParams`, which sets the query
79
+ * before any fragment and throws on a `//` or `/\` input. It was walked around twice on 1.7.1, and the second bypass
80
+ * was the diagnosis: **every input shape where that construction and this parsing disagree is another one**, so patching the parsing
80
81
  * again only moves the report later. `./errorCallbackUrl` therefore guards the value on the way *in*,
81
82
  * and by the time this module runs the string being parsed is one the kit produced.
82
83
  *
@@ -157,7 +158,7 @@ export interface CollapsedRefusal {
157
158
  *
158
159
  * - **It need not be absolute.** `api/middlewares/origin-check.mjs` passes `allowRelativePaths: true`,
159
160
  * `matchesOriginPattern` admits `/path?query`, `oauth2/state.mjs` stores the value as a bare
160
- * `z.string().optional()`, and `redirectOnError` concatenates it raw. So a relative `Location` is a
161
+ * `z.string().optional()`, and `redirectOnError` keeps it root-relative. So a relative `Location` is a
161
162
  * supported answer, and returning `undefined` to one sent the true code to the browser and wrote no
162
163
  * audit row.
163
164
  * - **`error` need not be the only one.** `redirectOnError` *appends* `&error=<code>`. An
@@ -1 +1 @@
1
- {"version":3,"file":"providerRefusal.d.ts","sourceRoot":"","sources":["../../src/http/providerRefusal.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4FG;AAEH;;;;;;;GAOG;AACH,eAAO,MAAM,wBAAwB,6BAA6B,CAAC;AAEnE,yFAAyF;AACzF,UAAU,cAAc;IACtB;;;OAGG;IACH,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;IAC3B,yFAAyF;IACzF,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;CACtB;AAoLD,qGAAqG;AACrG,eAAO,MAAM,sBAAsB,EAAE,SAAS,MAAM,EAE5B,CAAC;AAEzB,gFAAgF;AAChF,eAAO,MAAM,uBAAuB,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAA6B,CAAC;AAE3G,yFAAyF;AACzF,MAAM,WAAW,gBAAgB;IAC/B,wEAAwE;IACxE,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC;IAC5B;;;;;;OAMG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;CACzB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AACH,wBAAgB,uBAAuB,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,GAAG,gBAAgB,GAAG,SAAS,CA0D5G"}
1
+ {"version":3,"file":"providerRefusal.d.ts","sourceRoot":"","sources":["../../src/http/providerRefusal.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6FG;AAEH;;;;;;;GAOG;AACH,eAAO,MAAM,wBAAwB,6BAA6B,CAAC;AAEnE,yFAAyF;AACzF,UAAU,cAAc;IACtB;;;OAGG;IACH,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;IAC3B,yFAAyF;IACzF,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;CACtB;AA2LD,qGAAqG;AACrG,eAAO,MAAM,sBAAsB,EAAE,SAAS,MAAM,EAE5B,CAAC;AAEzB,gFAAgF;AAChF,eAAO,MAAM,uBAAuB,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAA6B,CAAC;AAE3G,yFAAyF;AACzF,MAAM,WAAW,gBAAgB;IAC/B,wEAAwE;IACxE,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC;IAC5B;;;;;;OAMG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;CACzB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AACH,wBAAgB,uBAAuB,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,GAAG,gBAAgB,GAAG,SAAS,CA0D5G"}
@@ -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
  *
@@ -110,7 +111,7 @@ const NEUTRAL_PROVIDER_REFUSAL = "provider_sign_in_refused";
110
111
  * `providerRefusal.test.ts` reads Better Auth's own `OAUTH_CALLBACK_ERROR_CODES`, scans the
111
112
  * `result.error` literals out of `link-account.mjs`, and scans the `new APIError(…, { code })` sites in
112
113
  * both codebases — `better-auth`'s on the callback's path and the kit's across this whole package,
113
- * because `callback.mjs:239` re-emits *anything* thrown inside `handleOAuthUserInfo` as `?error=`. Every
114
+ * because `callback.mjs:192` re-emits *anything* thrown inside `handleOAuthUserInfo` as `?error=`. Every
114
115
  * code any of them can produce must appear here. A dependency bump that adds one turns that red, and
115
116
  * somebody writes a verdict for it. So the roster records a *review*, and the review cannot silently fall
116
117
  * behind the thing it reviews.
@@ -126,11 +127,11 @@ const NEUTRAL_PROVIDER_REFUSAL = "provider_sign_in_refused";
126
127
  const PROVIDER_REFUSAL_VERDICTS = {
127
128
  account_not_linked: {
128
129
  collapse: true,
129
- why: "link-account.mjs:86 — returned only inside `if (dbUser)`, so it is literally the statement that a row matched."
130
+ why: "link-account.mjs:142 — returned only inside `if (dbUser)`, so it is literally the statement that a row matched."
130
131
  },
131
132
  signup_disabled: {
132
133
  collapse: true,
133
- why: "link-account.mjs:202 — the `else` of that same branch, so it is literally the statement that none did."
134
+ why: "link-account.mjs:257 — the `else` of that same branch, so it is literally the statement that none did."
134
135
  },
135
136
  EMAIL_NOT_VERIFIED: {
136
137
  collapse: true,
@@ -138,15 +139,27 @@ const PROVIDER_REFUSAL_VERDICTS = {
138
139
  },
139
140
  unable_to_create_user: {
140
141
  collapse: true,
141
- 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."
142
+ 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."
142
143
  },
143
144
  INVALID_PROFILE_FIELD: {
144
145
  collapse: true,
145
- 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."
146
+ 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."
146
147
  },
147
148
  validation_context_missing: {
148
149
  collapse: true,
149
- 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."
150
+ 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."
151
+ },
152
+ unable_to_link_account: {
153
+ collapse: true,
154
+ 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."
155
+ },
156
+ "auth/account_suspended": {
157
+ collapse: false,
158
+ 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."
159
+ },
160
+ "auth/account_deleted": {
161
+ collapse: false,
162
+ 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."
150
163
  },
151
164
  no_code: {
152
165
  collapse: false,
@@ -158,7 +171,7 @@ const PROVIDER_REFUSAL_VERDICTS = {
158
171
  },
159
172
  invalid_callback_request: {
160
173
  collapse: false,
161
- 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."
174
+ 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."
162
175
  },
163
176
  oauth_provider_not_found: {
164
177
  collapse: false,
@@ -190,15 +203,15 @@ const PROVIDER_REFUSAL_VERDICTS = {
190
203
  },
191
204
  email_not_verified: {
192
205
  collapse: false,
193
- 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."
206
+ 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."
194
207
  },
195
208
  unable_to_create_session: {
196
209
  collapse: false,
197
- why: "link-account.mjs:269 — after the user is resolved, so it is reached from both sides of the branch equally."
210
+ why: "link-account.mjs:324 — after the user is resolved, so it is reached from both sides of the branch equally."
198
211
  },
199
212
  state_not_found: {
200
213
  collapse: false,
201
- why: "The request carried no state to parse. Raised at state.mjs:90, before any lookup."
214
+ why: "The request carried no state to parse. Raised at state.mjs:93, before any lookup."
202
215
  },
203
216
  state_mismatch: {
204
217
  collapse: false,
@@ -222,7 +235,7 @@ const PROVIDER_REFUSAL_VERDICTS = {
222
235
  },
223
236
  account_hook_binding_conflict: {
224
237
  collapse: false,
225
- 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."
238
+ 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."
226
239
  },
227
240
  validation_source_missing: {
228
241
  collapse: false,
@@ -230,11 +243,7 @@ const PROVIDER_REFUSAL_VERDICTS = {
230
243
  },
231
244
  validation_failed: {
232
245
  collapse: false,
233
- 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."
234
- },
235
- unable_to_link_account: {
236
- collapse: false,
237
- 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."
246
+ 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."
238
247
  },
239
248
  email_does_not_match: {
240
249
  collapse: false,
@@ -246,27 +255,23 @@ const PROVIDER_REFUSAL_VERDICTS = {
246
255
  },
247
256
  unable_to_update_account: {
248
257
  collapse: false,
249
- 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.)"
258
+ 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.)"
250
259
  },
251
260
  account_ownership_conflict: {
252
261
  collapse: false,
253
- 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."
254
- },
255
- account_provider_conflict: {
256
- collapse: false,
257
- 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."
262
+ 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."
258
263
  },
259
264
  user_not_found: {
260
265
  collapse: false,
261
- 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."
266
+ 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."
262
267
  },
263
268
  user_hook_selection_conflict: {
264
269
  collapse: false,
265
- 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."
270
+ 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."
266
271
  },
267
272
  session_hook_user_conflict: {
268
273
  collapse: false,
269
- 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."
274
+ 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."
270
275
  }
271
276
  };
272
277
  /** The codes this module refuses to let out. Derived from the roster, so the two cannot disagree. */
@@ -301,7 +306,7 @@ const PROVIDER_REFUSAL_ROSTER = PROVIDER_REFUSAL_VERDICTS;
301
306
  *
302
307
  * - **It need not be absolute.** `api/middlewares/origin-check.mjs` passes `allowRelativePaths: true`,
303
308
  * `matchesOriginPattern` admits `/path?query`, `oauth2/state.mjs` stores the value as a bare
304
- * `z.string().optional()`, and `redirectOnError` concatenates it raw. So a relative `Location` is a
309
+ * `z.string().optional()`, and `redirectOnError` keeps it root-relative. So a relative `Location` is a
305
310
  * supported answer, and returning `undefined` to one sent the true code to the browser and wrote no
306
311
  * audit row.
307
312
  * - **`error` need not be the only one.** `redirectOnError` *appends* `&error=<code>`. An
@@ -1 +1 @@
1
- {"version":3,"file":"resolve.d.ts","sourceRoot":"","sources":["../../src/http/resolve.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAI7E,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAGhD,OAAO,EAAE,KAAK,YAAY,EAAY,MAAM,kBAAkB,CAAC;AAqB/D,2GAA2G;AAC3G,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,WAAW,EAAE,MAAM,GAAG,UAAU,CASvF;AA0BD,wBAAgB,eAAe,CAAC,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,EAAE,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,YAAY,CAAC,CAMnG"}
1
+ {"version":3,"file":"resolve.d.ts","sourceRoot":"","sources":["../../src/http/resolve.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAE5D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAK7E,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAGhD,OAAO,EAAE,KAAK,YAAY,EAAY,MAAM,kBAAkB,CAAC;AAuB/D,2GAA2G;AAC3G,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,WAAW,EAAE,MAAM,GAAG,UAAU,CASvF;AA0BD,wBAAgB,eAAe,CAAC,CAAC,EAAE,OAAO,CAAC,YAAY,CAAC,EAAE,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,YAAY,CAAC,CAMnG"}