@pithy-sh/auth 0.10.0 → 0.12.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 (283) hide show
  1. package/README.md +30 -2
  2. package/dist/admin/users.js +1 -1
  3. package/dist/audit/actions.d.ts +58 -0
  4. package/dist/audit/actions.d.ts.map +1 -1
  5. package/dist/audit/actions.js +59 -1
  6. package/dist/audit/emit.d.ts +36 -0
  7. package/dist/audit/emit.d.ts.map +1 -1
  8. package/dist/audit/emit.js +48 -2
  9. package/dist/audit/evidence.d.ts +8 -2
  10. package/dist/audit/evidence.d.ts.map +1 -1
  11. package/dist/capability.d.ts +47 -8
  12. package/dist/capability.d.ts.map +1 -1
  13. package/dist/capability.js +56 -6
  14. package/dist/client/api.d.ts +55 -12
  15. package/dist/client/api.d.ts.map +1 -1
  16. package/dist/client/api.js +57 -18
  17. package/dist/client/bearer.d.ts +110 -0
  18. package/dist/client/bearer.d.ts.map +1 -0
  19. package/dist/client/bearer.js +265 -0
  20. package/dist/client/handoff.d.ts +77 -0
  21. package/dist/client/handoff.d.ts.map +1 -0
  22. package/dist/client/handoff.js +119 -0
  23. package/dist/client/mcp.d.ts +70 -0
  24. package/dist/client/mcp.d.ts.map +1 -0
  25. package/dist/client/mcp.js +65 -0
  26. package/dist/data/betterAuth.d.ts +3 -2
  27. package/dist/data/betterAuth.d.ts.map +1 -1
  28. package/dist/data/betterAuth.js +5 -3
  29. package/dist/data/kitFields.d.ts +5 -0
  30. package/dist/data/kitFields.d.ts.map +1 -1
  31. package/dist/data/kitFields.js +5 -0
  32. package/dist/data/tables.d.ts +26 -4
  33. package/dist/data/tables.d.ts.map +1 -1
  34. package/dist/data/tables.js +5 -3
  35. package/dist/data/userLifecycle.d.ts +10 -0
  36. package/dist/data/userLifecycle.d.ts.map +1 -1
  37. package/dist/data/userLifecycle.js +8 -3
  38. package/dist/data/verificationOutcome.d.ts +53 -0
  39. package/dist/data/verificationOutcome.d.ts.map +1 -0
  40. package/dist/data/verificationOutcome.js +50 -0
  41. package/dist/email/send.js +6 -2
  42. package/dist/http/adminRoutes.d.ts.map +1 -1
  43. package/dist/http/adminRoutes.js +319 -8
  44. package/dist/http/csrf.d.ts.map +1 -1
  45. package/dist/http/csrf.js +2 -1
  46. package/dist/http/guards.d.ts +15 -10
  47. package/dist/http/guards.d.ts.map +1 -1
  48. package/dist/http/guards.js +76 -10
  49. package/dist/http/handoff.d.ts +76 -0
  50. package/dist/http/handoff.d.ts.map +1 -0
  51. package/dist/http/handoff.js +316 -0
  52. package/dist/http/middleware.d.ts +37 -1
  53. package/dist/http/middleware.d.ts.map +1 -1
  54. package/dist/http/middleware.js +68 -6
  55. package/dist/http/resolve.d.ts.map +1 -1
  56. package/dist/http/resolve.js +9 -3
  57. package/dist/http/responses.d.ts +322 -0
  58. package/dist/http/responses.d.ts.map +1 -1
  59. package/dist/http/responses.js +202 -5
  60. package/dist/http/routes.d.ts +3 -0
  61. package/dist/http/routes.d.ts.map +1 -1
  62. package/dist/http/routes.js +78 -5
  63. package/dist/http/schemas.d.ts +114 -0
  64. package/dist/http/schemas.d.ts.map +1 -1
  65. package/dist/http/schemas.js +94 -1
  66. package/dist/http/views.d.ts +60 -3
  67. package/dist/http/views.d.ts.map +1 -1
  68. package/dist/http/views.js +143 -3
  69. package/dist/index.d.ts +2 -0
  70. package/dist/index.d.ts.map +1 -1
  71. package/dist/index.js +4 -2
  72. package/dist/instance/auth.d.ts +148 -10
  73. package/dist/instance/auth.d.ts.map +1 -1
  74. package/dist/instance/auth.js +87 -42
  75. package/dist/instance/plugins.d.ts +6 -0
  76. package/dist/instance/plugins.d.ts.map +1 -1
  77. package/dist/instance/plugins.js +14 -1
  78. package/dist/ledger/read.d.ts +53 -0
  79. package/dist/ledger/read.d.ts.map +1 -0
  80. package/dist/ledger/read.js +85 -0
  81. package/dist/ledger/record.d.ts +35 -0
  82. package/dist/ledger/record.d.ts.map +1 -0
  83. package/dist/ledger/record.js +98 -0
  84. package/dist/lifecycle/audited.d.ts +48 -0
  85. package/dist/lifecycle/audited.d.ts.map +1 -0
  86. package/dist/lifecycle/audited.js +65 -0
  87. package/dist/lifecycle/enforce.d.ts +37 -2
  88. package/dist/lifecycle/enforce.d.ts.map +1 -1
  89. package/dist/lifecycle/enforce.js +46 -5
  90. package/dist/lifecycle/erasure.d.ts +9 -0
  91. package/dist/lifecycle/erasure.d.ts.map +1 -0
  92. package/dist/lifecycle/erasure.js +96 -0
  93. package/dist/lifecycle/inactivity.d.ts +19 -0
  94. package/dist/lifecycle/inactivity.d.ts.map +1 -0
  95. package/dist/lifecycle/inactivity.js +28 -0
  96. package/dist/lifecycle/reason.d.ts +11 -0
  97. package/dist/lifecycle/reason.d.ts.map +1 -0
  98. package/dist/lifecycle/reason.js +13 -0
  99. package/dist/lifecycle/request.d.ts +5 -2
  100. package/dist/lifecycle/request.d.ts.map +1 -1
  101. package/dist/lifecycle/request.js +6 -2
  102. package/dist/lifecycle/transitions.d.ts +179 -18
  103. package/dist/lifecycle/transitions.d.ts.map +1 -1
  104. package/dist/lifecycle/transitions.js +391 -70
  105. package/dist/mcp/argumentClass.d.ts +51 -0
  106. package/dist/mcp/argumentClass.d.ts.map +1 -0
  107. package/dist/mcp/argumentClass.js +69 -0
  108. package/dist/mcp/capability.d.ts +50 -0
  109. package/dist/mcp/capability.d.ts.map +1 -0
  110. package/dist/mcp/capability.js +140 -0
  111. package/dist/mcp/clientMetadata.d.ts +40 -0
  112. package/dist/mcp/clientMetadata.d.ts.map +1 -0
  113. package/dist/mcp/clientMetadata.js +68 -0
  114. package/dist/mcp/consent.d.ts +49 -0
  115. package/dist/mcp/consent.d.ts.map +1 -0
  116. package/dist/mcp/consent.js +69 -0
  117. package/dist/mcp/dispatch.d.ts +35 -0
  118. package/dist/mcp/dispatch.d.ts.map +1 -0
  119. package/dist/mcp/dispatch.js +135 -0
  120. package/dist/mcp/floor.d.ts +37 -0
  121. package/dist/mcp/floor.d.ts.map +1 -0
  122. package/dist/mcp/floor.js +41 -0
  123. package/dist/mcp/host.d.ts +34 -0
  124. package/dist/mcp/host.d.ts.map +1 -0
  125. package/dist/mcp/host.js +2 -0
  126. package/dist/mcp/http/redirectList.d.ts +9 -0
  127. package/dist/mcp/http/redirectList.d.ts.map +1 -0
  128. package/dist/mcp/http/redirectList.js +24 -0
  129. package/dist/mcp/http/responses.d.ts +143 -0
  130. package/dist/mcp/http/responses.d.ts.map +1 -0
  131. package/dist/mcp/http/responses.js +83 -0
  132. package/dist/mcp/http/routes.d.ts +28 -0
  133. package/dist/mcp/http/routes.d.ts.map +1 -0
  134. package/dist/mcp/http/routes.js +517 -0
  135. package/dist/mcp/http/schemas.d.ts +24 -0
  136. package/dist/mcp/http/schemas.d.ts.map +1 -0
  137. package/dist/mcp/http/schemas.js +18 -0
  138. package/dist/mcp/marker.d.ts +15 -0
  139. package/dist/mcp/marker.d.ts.map +1 -0
  140. package/dist/mcp/marker.js +15 -0
  141. package/dist/mcp/provider.d.ts +78 -0
  142. package/dist/mcp/provider.d.ts.map +1 -0
  143. package/dist/mcp/provider.js +108 -0
  144. package/dist/mcp/purge.d.ts +15 -0
  145. package/dist/mcp/purge.d.ts.map +1 -0
  146. package/dist/mcp/purge.js +31 -0
  147. package/dist/mcp/rpc.d.ts +79 -0
  148. package/dist/mcp/rpc.d.ts.map +1 -0
  149. package/dist/mcp/rpc.js +103 -0
  150. package/dist/mcp/toolAudit.d.ts +76 -0
  151. package/dist/mcp/toolAudit.d.ts.map +1 -0
  152. package/dist/mcp/toolAudit.js +86 -0
  153. package/dist/migrations/0005_purge_once.d.ts +22 -0
  154. package/dist/migrations/0005_purge_once.d.ts.map +1 -0
  155. package/dist/migrations/0005_purge_once.js +35 -0
  156. package/dist/migrations/0006_verification_outcomes.d.ts +15 -0
  157. package/dist/migrations/0006_verification_outcomes.d.ts.map +1 -0
  158. package/dist/migrations/0006_verification_outcomes.js +35 -0
  159. package/dist/migrations/0007_erasure_record.d.ts +17 -0
  160. package/dist/migrations/0007_erasure_record.d.ts.map +1 -0
  161. package/dist/migrations/0007_erasure_record.js +36 -0
  162. package/dist/migrations/0008_last_active.d.ts +15 -0
  163. package/dist/migrations/0008_last_active.d.ts.map +1 -0
  164. package/dist/migrations/0008_last_active.js +29 -0
  165. package/dist/migrations/pluginTables.d.ts +8 -0
  166. package/dist/migrations/pluginTables.d.ts.map +1 -1
  167. package/dist/migrations/pluginTables.js +8 -1
  168. package/dist/migrations/set.d.ts +5 -1
  169. package/dist/migrations/set.d.ts.map +1 -1
  170. package/dist/migrations/set.js +10 -2
  171. package/dist/peer.d.ts +3 -2
  172. package/dist/peer.d.ts.map +1 -1
  173. package/dist/processing/activities.d.ts +6 -0
  174. package/dist/processing/activities.d.ts.map +1 -0
  175. package/dist/processing/activities.js +12 -0
  176. package/dist/purge/contribution.d.ts +62 -0
  177. package/dist/purge/contribution.d.ts.map +1 -0
  178. package/dist/purge/contribution.js +155 -0
  179. package/dist/purge/retryPolicy.d.ts +22 -0
  180. package/dist/purge/retryPolicy.d.ts.map +1 -0
  181. package/dist/purge/retryPolicy.js +26 -0
  182. package/dist/purge/run.d.ts +158 -0
  183. package/dist/purge/run.d.ts.map +1 -0
  184. package/dist/purge/run.js +205 -0
  185. package/dist/purge/specs.d.ts +71 -0
  186. package/dist/purge/specs.d.ts.map +1 -0
  187. package/dist/purge/specs.js +72 -0
  188. package/dist/purge/start.d.ts +42 -0
  189. package/dist/purge/start.d.ts.map +1 -0
  190. package/dist/purge/start.js +37 -0
  191. package/dist/purge/workflow.d.ts +71 -0
  192. package/dist/purge/workflow.d.ts.map +1 -0
  193. package/dist/purge/workflow.js +140 -0
  194. package/dist/test-utils/accountFootprint.d.ts +13 -0
  195. package/dist/test-utils/accountFootprint.d.ts.map +1 -0
  196. package/dist/test-utils/accountFootprint.js +49 -0
  197. package/dist/test-utils/liveApp.d.ts +6 -0
  198. package/dist/test-utils/liveApp.d.ts.map +1 -1
  199. package/dist/test-utils/liveApp.js +7 -2
  200. package/dist/token/handoff.d.ts +80 -0
  201. package/dist/token/handoff.d.ts.map +1 -0
  202. package/dist/token/handoff.js +136 -0
  203. package/dist/version.generated.d.ts +1 -1
  204. package/dist/version.generated.js +1 -1
  205. package/docs/account-lifecycle.md +176 -12
  206. package/docs/apple-signin.md +32 -4
  207. package/docs/facebook-oauth.md +2 -2
  208. package/docs/github-oauth.md +2 -2
  209. package/docs/google-oauth.md +9 -7
  210. package/docs/microsoft-oauth.md +2 -2
  211. package/package.json +11 -5
  212. package/pithy.manifest.json +2 -2
  213. package/pithy.mcp.manifest.json +36 -0
  214. package/src/audit/actions.ts +58 -0
  215. package/src/audit/emit.ts +66 -1
  216. package/src/audit/evidence.ts +8 -4
  217. package/src/capability.ts +122 -18
  218. package/src/client/api.ts +69 -19
  219. package/src/client/bearer.ts +388 -0
  220. package/src/client/handoff.ts +172 -0
  221. package/src/client/mcp.ts +140 -0
  222. package/src/data/betterAuth.ts +8 -4
  223. package/src/data/kitFields.ts +2 -0
  224. package/src/data/tables.ts +4 -2
  225. package/src/data/userLifecycle.ts +19 -4
  226. package/src/data/verificationOutcome.ts +86 -0
  227. package/src/email/send.ts +2 -2
  228. package/src/http/adminRoutes.ts +465 -4
  229. package/src/http/csrf.ts +4 -1
  230. package/src/http/guards.ts +79 -10
  231. package/src/http/handoff.ts +350 -0
  232. package/src/http/middleware.ts +74 -5
  233. package/src/http/resolve.ts +25 -25
  234. package/src/http/responses.ts +374 -3
  235. package/src/http/routes.ts +116 -5
  236. package/src/http/schemas.ts +195 -0
  237. package/src/http/views.ts +192 -3
  238. package/src/index.ts +2 -0
  239. package/src/instance/auth.ts +58 -3
  240. package/src/instance/plugins.ts +20 -2
  241. package/src/ledger/read.ts +133 -0
  242. package/src/ledger/record.ts +198 -0
  243. package/src/lifecycle/audited.ts +104 -0
  244. package/src/lifecycle/enforce.ts +55 -5
  245. package/src/lifecycle/erasure.ts +118 -0
  246. package/src/lifecycle/inactivity.ts +56 -0
  247. package/src/lifecycle/reason.ts +11 -0
  248. package/src/lifecycle/request.ts +10 -2
  249. package/src/lifecycle/transitions.ts +552 -93
  250. package/src/mcp/argumentClass.ts +112 -0
  251. package/src/mcp/capability.ts +194 -0
  252. package/src/mcp/clientMetadata.ts +81 -0
  253. package/src/mcp/consent.ts +95 -0
  254. package/src/mcp/dispatch.ts +154 -0
  255. package/src/mcp/floor.ts +62 -0
  256. package/src/mcp/host.ts +36 -0
  257. package/src/mcp/http/redirectList.ts +26 -0
  258. package/src/mcp/http/responses.ts +157 -0
  259. package/src/mcp/http/routes.ts +635 -0
  260. package/src/mcp/http/schemas.ts +37 -0
  261. package/src/mcp/marker.ts +18 -0
  262. package/src/mcp/provider.ts +151 -0
  263. package/src/mcp/purge.ts +39 -0
  264. package/src/mcp/rpc.ts +135 -0
  265. package/src/mcp/toolAudit.ts +132 -0
  266. package/src/migrations/0005_purge_once.ts +42 -0
  267. package/src/migrations/0006_verification_outcomes.ts +51 -0
  268. package/src/migrations/0007_erasure_record.ts +43 -0
  269. package/src/migrations/0008_last_active.ts +30 -0
  270. package/src/migrations/pluginTables.ts +19 -1
  271. package/src/migrations/set.ts +9 -1
  272. package/src/processing/activities.ts +14 -0
  273. package/src/purge/contribution.ts +218 -0
  274. package/src/purge/retryPolicy.ts +26 -0
  275. package/src/purge/run.ts +348 -0
  276. package/src/purge/specs.ts +95 -0
  277. package/src/purge/start.ts +79 -0
  278. package/src/purge/workflow.ts +202 -0
  279. package/src/seeds/example.ts +2 -2
  280. package/src/test-utils/accountFootprint.ts +104 -0
  281. package/src/test-utils/liveApp.ts +10 -1
  282. package/src/token/handoff.ts +180 -0
  283. package/src/version.generated.ts +1 -1
@@ -1,22 +1,32 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
+ import { AuthAuditActions } from "./audit/actions.js";
3
4
  import { authTables } from "./data/tables.js";
5
+ import { baseURLResolver } from "./http/baseUrl.js";
4
6
  import { publishSameOrigin } from "./http/csrf.js";
5
7
  import { authSecretsRegistryFor, inapplicableProviderSecrets } from "./instance/secrets.js";
6
8
  import { authDevSessionSeed } from "./seeds/devSession.js";
7
9
  import { AuthPlugin, assertAdditivePlugins } from "./instance/plugins.js";
10
+ import { getAuthInstance } from "./http/resolve.js";
8
11
  import { registerDevLoginRoute } from "./http/devLoginRoute.js";
9
12
  import { authAdminRoutes } from "./http/guards.js";
10
13
  import { createSessionMiddleware } from "./http/middleware.js";
11
14
  import { createRateLimitMiddleware } from "./http/rateLimit.js";
15
+ import { authWorkflows } from "./purge/specs.js";
12
16
  import { createAuthRoutes } from "./http/routes.js";
17
+ import { authErasureRecords } from "./lifecycle/erasure.js";
18
+ import { isMcpCapability } from "./mcp/marker.js";
13
19
  import "./migrations/0001_init.js";
14
20
  import { authPluginPlan } from "./migrations/pluginTables.js";
15
21
  import { AUTH_MIGRATIONS } from "./migrations/set.js";
16
22
  import { authPeer } from "./peer.js";
23
+ import { AUTH_PROCESSING } from "./processing/activities.js";
24
+ import { authAddressOf, authPurgeContribution } from "./purge/contribution.js";
17
25
  import { authExampleSeed } from "./seeds/example.js";
18
26
  import { PACKAGE_NAME, PACKAGE_VERSION } from "./version.generated.js";
27
+ import { composedAuditEmit } from "@pithy-sh/core/src/audit/composed";
19
28
  import { defineCapability } from "@pithy-sh/core/src/capability/capability";
29
+ import { purgeSteps } from "@pithy-sh/core/src/capability/purge";
20
30
  import { ValidationError } from "@pithy-sh/core/src/error/pithyError";
21
31
  import { isEmailCapability } from "@pithy-sh/email/src/capability";
22
32
  import { isTurnstileCapability } from "@pithy-sh/turnstile/src/capability";
@@ -55,7 +65,10 @@ const AuthConfig = z.object({
55
65
  verificationExpiresIn: z.number().int().default(300).describe("Magic-link and OTP lifetime in seconds. Defaults to 5 minutes. Single-use regardless."),
56
66
  otpLength: z.number().int().default(6).describe("The number of digits in an email OTP. Defaults to 6."),
57
67
  disableSignUp: z.boolean().default(false).describe("When true, sign-in never provisions a new user — existing accounts only. Unknown emails get no email (anti-enumeration)."),
58
- retention: z.object({ purgeAfterDays: z.number().int().positive().default(30).describe("How many days a deleted account waits before its data is erased. Inside the window it cannot sign in and can be restored; after it, the purge erases its rows from every capability that holds them. Defaults to 30.") }).prefault({}).describe("How long a deleted account is kept before it is purged. Self-service deletion and an operator's soft deletion both use this window."),
68
+ retention: z.object({
69
+ purgeAfterDays: z.number().int().positive().default(30).describe("How many days a deleted account waits before its data is erased. Inside the window it cannot sign in and can be restored; after it, the purge erases its rows from every capability that holds them. Defaults to 30."),
70
+ restoreUrl: z.url({ protocol: /^https?$/ }).optional().describe("Where a person whose account is deleted asks for it back inside the window: an http(s) page of yours. Carried in the deletion-scheduled mail as its restore button, so it must be a web address — a tracked click redirects only to one. Absent, the mail still tells them to reply before the purge date.")
71
+ }).prefault({}).describe("How long a deleted account is kept before it is purged. Self-service deletion and an operator's soft deletion both use this window."),
59
72
  lifecycleEmails: z.object({
60
73
  accountSuspended: z.boolean().default(true).describe("Email the person when their account is suspended, with the reason and any end date."),
61
74
  accountReinstated: z.boolean().default(true).describe("Email the person when a suspension is lifted."),
@@ -64,6 +77,14 @@ const AuthConfig = z.object({
64
77
  }).prefault({}).describe("Which account-lifecycle emails are sent. All four send by default, through `@pithy-sh/email`; switch one off by setting it to false."),
65
78
  plugins: z.array(AuthPlugin).default([]).describe("Additional Better Auth plugins to compose — `organization()`, `passkey()`, `twoFactor()`, `apiKey()`, a generic OAuth provider. Additive: they join the set the kit composes (i18n, bearer, jwt, magic-link, email-otp) and cannot replace one. Tables a plugin declares are created by `pithy migrate`; add the matching client plugin to `createAuthClient` for its typed client surface.")
66
79
  }).describe("Configuration for the auth capability.");
80
+ /** The sign-in gate a composed turnstile asks for, or `undefined` when none is composed or sign-in is unprotected. */
81
+ function turnstileLoginGate(capability) {
82
+ const mode = capability?.turnstileConfig.protect[TURNSTILE_LOGIN_ACTION];
83
+ return mode ? {
84
+ mode,
85
+ token: capability.turnstileConfig.token
86
+ } : void 0;
87
+ }
67
88
  /**
68
89
  * Refuse a composition where a Better Auth plugin's table is one another capability already declares in
69
90
  * the same database. `capabilities` is every capability composed into this backend, so this is the first
@@ -112,8 +133,12 @@ function auth(options) {
112
133
  turnstile: void 0,
113
134
  onSessionRevoked,
114
135
  resolveScopes,
115
- lifecycleHooks
136
+ lifecycleHooks,
137
+ purgeSteps: []
116
138
  };
139
+ const steps = [];
140
+ wiring.purgeSteps = steps;
141
+ let composition = [];
117
142
  const rateLimitMiddleware = (app) => {
118
143
  app.use(`${resolved.basePath}/*`, createRateLimitMiddleware(resolved.rateLimiterBinding));
119
144
  };
@@ -147,6 +172,20 @@ function auth(options) {
147
172
  ...pluginPlan.migrations
148
173
  }
149
174
  } },
175
+ purge: [authPurgeContribution(resolved.database, pluginPlan.userTables)],
176
+ processing: AUTH_PROCESSING,
177
+ erasureRecords: authErasureRecords(resolved.database),
178
+ purgeWindow: {
179
+ subject: "user",
180
+ days: resolved.retention.purgeAfterDays
181
+ },
182
+ lifecycleAuditActions: [
183
+ AuthAuditActions.adminUserSuspended,
184
+ AuthAuditActions.adminUserReinstated,
185
+ AuthAuditActions.adminUserRestored
186
+ ],
187
+ addressOf: authAddressOf(resolved.database),
188
+ workflows: authWorkflows,
150
189
  compose: ({ capabilities }) => {
151
190
  const email = capabilities.find(isEmailCapability);
152
191
  if (!email) throw new ValidationError({
@@ -154,9 +193,12 @@ function auth(options) {
154
193
  action: "Add `email(...)` to your capabilities — magic-link and OTP delivery enqueue email jobs."
155
194
  });
156
195
  wiring.enqueueEmail = email.enqueue;
157
- const loginMode = capabilities.find(isTurnstileCapability)?.turnstileConfig.protect[TURNSTILE_LOGIN_ACTION];
158
- wiring.turnstile = loginMode ? { mode: loginMode } : void 0;
196
+ wiring.turnstile = turnstileLoginGate(capabilities.find(isTurnstileCapability));
159
197
  assertPluginTablesUnclaimed(capabilities, resolved.database, pluginPlan.extensions);
198
+ steps.splice(0, steps.length, ...purgeSteps(capabilities, "user"));
199
+ wiring.mcp = capabilities.find(isMcpCapability)?.mcpWiring;
200
+ composition = capabilities;
201
+ wiring.composed = capabilities;
160
202
  },
161
203
  /**
162
204
  * The client-safe projection — what a sign-in screen needs and nothing more: where to call
@@ -209,7 +251,15 @@ function auth(options) {
209
251
  return Object.assign(capability, {
210
252
  authConfig: resolved,
211
253
  authPeer,
212
- lifecycleHooks
254
+ lifecycleHooks,
255
+ purgeSteps: steps,
256
+ auditFor: (env) => composedAuditEmit(composition, env),
257
+ mcpHost: {
258
+ instance: (c) => getAuthInstance(c, wiring),
259
+ baseURL: (request) => baseURLResolver(resolved.baseURL)(request),
260
+ basePath: resolved.basePath,
261
+ database: resolved.database
262
+ }
213
263
  });
214
264
  }
215
265
  /** Type guard: is this capability the auth capability? */
@@ -217,4 +267,4 @@ function isAuthCapability(capability) {
217
267
  return capability.name === "auth" && "authConfig" in capability;
218
268
  }
219
269
  //#endregion
220
- export { AuthConfig, auth, isAuthCapability };
270
+ export { AuthConfig, auth, isAuthCapability, turnstileLoginGate };
@@ -13,11 +13,12 @@
13
13
  * `/sign-out`, the two OTP routes, the magic link, and the social handoff — each spelling out the same
14
14
  * transport by hand. They call this now, and this upgrades with a minor release (#370).
15
15
  *
16
- * **Cookie/session, same origin, and that is enforced rather than assumed.** Every request carries
17
- * `credentials: "include"` and nothing else: no token in `localStorage` or `sessionStorage`, no
18
- * `Authorization` header, no refresh rotation. The SPA and its Worker share an origin, so the session
19
- * rides an httpOnly cookie JavaScript cannot read. Bearer is the mobile path — the same routes serve
20
- * it, documented rather than scaffolded.
16
+ * **Two transports, chosen by one option.** With no `origin`, every request is a rooted path on the
17
+ * page's own origin carrying `credentials: "include"` and nothing else: no token in `localStorage` or
18
+ * `sessionStorage`, no `Authorization` header, no refresh rotation. The SPA and its Worker share an
19
+ * origin, so the session rides an httpOnly cookie JavaScript cannot read. With an `origin` — a native
20
+ * app, which no Worker serves — the request goes to that origin with `credentials: "omit"`, and the
21
+ * credential is the `Authorization` header the handed-in `fetch` adds. `./bearer` builds that fetch.
21
22
  *
22
23
  * **CSRF travels with the cookie mode, and half of it is on this side of the wire.** The server's
23
24
  * `requireSameOrigin()` refuses a cookie-authenticated mutating request whose `Origin` does not match;
@@ -34,7 +35,7 @@
34
35
  * on this side of the wire protects anything, it only decides what a screen shows.
35
36
  *
36
37
  * **No absolute URL literals, and no schema library.** Paths are relative, so the calls follow whatever
37
- * origin the bundle is served from. Answers are narrowed by hand-written `is…(value: unknown): value is
38
+ * origin the bundle is served from, or the one `origin` names. Answers are narrowed by hand-written `is…(value: unknown): value is
38
39
  * T` guards rather than Zod: this file compiles into an adopter's browser bundle, and it must not drag
39
40
  * the Worker's schema graph in behind it. `sameOrigin.test.ts` holds the import list to empty, so the
40
41
  * property is structural rather than a habit.
@@ -55,7 +56,10 @@ export interface AuthRequestInit {
55
56
  headers?: Record<string, string>;
56
57
  /** The JSON body, already serialized. */
57
58
  body?: string;
58
- /** Cookie policy. Always `include` here — same-origin, httpOnly session cookie. */
59
+ /**
60
+ * Cookie policy. `include` on the page's own origin, where the session is an httpOnly cookie; `omit`
61
+ * once an {@link AuthClientOptions.origin} is set, where the credential is a bearer the fetch adds.
62
+ */
59
63
  credentials?: "include" | "same-origin" | "omit";
60
64
  }
61
65
  /** The slice of `Response` this module reads. */
@@ -94,6 +98,13 @@ export type AuthGate = (body: Record<string, unknown>) => {
94
98
  };
95
99
  /** What every call takes: where the routes are, and the seams a test replaces. */
96
100
  export interface AuthClientOptions {
101
+ /**
102
+ * The Worker's absolute origin, for a program it does not serve: a native app. `scheme://host[:port]`
103
+ * over http or https and nothing else — no path, no trailing slash. Absent, every request is a rooted
104
+ * path on the page's own origin carrying its cookie. Present, the request goes to this origin with no
105
+ * cookie, and the credential is whatever the `fetch` handed in adds.
106
+ */
107
+ origin?: string;
97
108
  /** Where the auth routes mount. Defaults to {@link AUTH_BASE_PATH}. */
98
109
  basePath?: string;
99
110
  /** The fetch to use. Defaults to the one on {@link AuthClientOptions.global}. */
@@ -127,14 +138,46 @@ export declare const AUTH_UNREADABLE: AuthFailure;
127
138
  /**
128
139
  * The request would have left this origin, so it was never sent.
129
140
  *
130
- * The only way to reach it is a `basePath` or a path that is not a rooted same-origin path — an
131
- * absolute URL, a protocol-relative `//host`, a backslash form a URL parser reads as one. Sending it
132
- * would attach an ambient session to a request this page is not entitled to make, which is the thing
133
- * the cookie mode exists to keep from happening.
141
+ * Reached through a `basePath` that is not a rooted path — an absolute URL, a protocol-relative
142
+ * `//host`, a backslash form a URL parser reads as one — or an `origin` that is not a bare http(s)
143
+ * origin. Sending it would attach a session to a request this program is not entitled to make.
134
144
  */
135
145
  export declare const AUTH_CROSS_ORIGIN: AuthFailure;
136
146
  /**
137
- * One call: same-origin, cookie-carrying, never throwing. **The only producer of that request.**
147
+ * Whether a composed path stays on this origin.
148
+ *
149
+ * A rooted path and nothing that resolves elsewhere. `//host` and `/\host` are the two forms a URL
150
+ * parser reads as an authority rather than as a path, and a browser follows both — which is why the
151
+ * check is on the second character rather than on a scheme it would never find after a leading `/`.
152
+ */
153
+ export declare function isSameOriginPath(path: string): boolean;
154
+ /**
155
+ * Whether a configured origin is a bare http(s) origin: a scheme, a host, an optional port, nothing else.
156
+ *
157
+ * A regular expression rather than `new URL`, because React Native's `URL` does not implement the
158
+ * getters a parsed check would read. Userinfo, a path, a query, a fragment, a backslash and whitespace
159
+ * are all refused, so the composed URL can only ever name this host.
160
+ */
161
+ export declare function isBareOrigin(origin: string): boolean;
162
+ /**
163
+ * The fetch a call goes through: the one passed, else the one on the injected global, else none.
164
+ *
165
+ * Exported so `./bearer` reaches the global the same way every call here does, rather than keeping a
166
+ * second copy of where a fetch comes from.
167
+ */
168
+ export declare function resolveFetch(options: Pick<AuthClientOptions, "fetch" | "global"> | undefined): AuthFetch | undefined;
169
+ /**
170
+ * The same request with no cookie on it — the bearer transport's policy.
171
+ *
172
+ * Written here because this module is the one place a cookie mode is written. `./bearer` puts it on
173
+ * every request its session sends, which is what keeps a cookie a native `fetch` stored from a sign-in
174
+ * answer from riding alongside the bearer: Better Auth refuses a cookie-carrying request with no
175
+ * `Origin`.
176
+ */
177
+ export declare function withoutCookies(init: AuthRequestInit | undefined): AuthRequestInit;
178
+ /**
179
+ * One call: same-origin and cookie-carrying, or to an absolute origin with no cookie; never throwing.
180
+ * **The only producer of either request.**
138
181
  *
139
182
  * The body is read before the status is judged, because a refusal's body is the failure a screen
140
183
  * renders. A body that will not parse is the generic failure rather than a crash — a corporate proxy's
@@ -1 +1 @@
1
- {"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../../src/client/api.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AAEH,iGAAiG;AACjG,eAAO,MAAM,cAAc,UAAU,CAAC;AAEtC;;;;;;GAMG;AACH,MAAM,WAAW,eAAe;IAC9B,yCAAyC;IACzC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,uBAAuB;IACvB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,yCAAyC;IACzC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,mFAAmF;IACnF,WAAW,CAAC,EAAE,SAAS,GAAG,aAAa,GAAG,MAAM,CAAC;CAClD;AAED,iDAAiD;AACjD,MAAM,WAAW,YAAY;IAC3B,kCAAkC;IAClC,EAAE,EAAE,OAAO,CAAC;IACZ,uBAAuB;IACvB,MAAM,EAAE,MAAM,CAAC;IACf,4DAA4D;IAC5D,IAAI,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;CAC1B;AAED,oCAAoC;AACpC,MAAM,MAAM,SAAS,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,eAAe,KAAK,OAAO,CAAC,YAAY,CAAC,CAAC;AAEzF;;;;;;GAMG;AACH,MAAM,WAAW,UAAU;IACzB,2BAA2B;IAC3B,KAAK,CAAC,EAAE,SAAS,CAAC;CACnB;AAED;;;;;GAKG;AACH,MAAM,MAAM,QAAQ,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B,GAC1B,OAAO,CAAC,UAAU,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,CAE9C;AAED;;;;;GAKG;AACH,wBAAgB,aAAa,CAC3B,KAAK,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAA;CAAE,EAC7C,OAAO,CAAC,EAAE,iBAAiB,GAC1B,OAAO,CAAC,UAAU,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,CAE9C;AAED;;;;;;;GAOG;AACH,MAAM,MAAM,YAAY,GACpB;IAAE,IAAI,EAAE,WAAW,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GAClC;IAAE,IAAI,EAAE,cAAc,CAAA;CAAE,GACxB;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,OAAO,EAAE,WAAW,CAAA;CAAE,CAAC;AA0B9C;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAsB,iBAAiB,CACrC,KAAK,EAAE;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC;IAAC,gBAAgB,CAAC,EAAE,MAAM,CAAA;CAAE,EAC3E,OAAO,CAAC,EAAE,iBAAiB,GAC1B,OAAO,CAAC,YAAY,CAAC,CAOvB"}
@@ -14,11 +14,12 @@
14
14
  * `/sign-out`, the two OTP routes, the magic link, and the social handoff — each spelling out the same
15
15
  * transport by hand. They call this now, and this upgrades with a minor release (#370).
16
16
  *
17
- * **Cookie/session, same origin, and that is enforced rather than assumed.** Every request carries
18
- * `credentials: "include"` and nothing else: no token in `localStorage` or `sessionStorage`, no
19
- * `Authorization` header, no refresh rotation. The SPA and its Worker share an origin, so the session
20
- * rides an httpOnly cookie JavaScript cannot read. Bearer is the mobile path — the same routes serve
21
- * it, documented rather than scaffolded.
17
+ * **Two transports, chosen by one option.** With no `origin`, every request is a rooted path on the
18
+ * page's own origin carrying `credentials: "include"` and nothing else: no token in `localStorage` or
19
+ * `sessionStorage`, no `Authorization` header, no refresh rotation. The SPA and its Worker share an
20
+ * origin, so the session rides an httpOnly cookie JavaScript cannot read. With an `origin` — a native
21
+ * app, which no Worker serves — the request goes to that origin with `credentials: "omit"`, and the
22
+ * credential is the `Authorization` header the handed-in `fetch` adds. `./bearer` builds that fetch.
22
23
  *
23
24
  * **CSRF travels with the cookie mode, and half of it is on this side of the wire.** The server's
24
25
  * `requireSameOrigin()` refuses a cookie-authenticated mutating request whose `Origin` does not match;
@@ -35,7 +36,7 @@
35
36
  * on this side of the wire protects anything, it only decides what a screen shows.
36
37
  *
37
38
  * **No absolute URL literals, and no schema library.** Paths are relative, so the calls follow whatever
38
- * origin the bundle is served from. Answers are narrowed by hand-written `is…(value: unknown): value is
39
+ * origin the bundle is served from, or the one `origin` names. Answers are narrowed by hand-written `is…(value: unknown): value is
39
40
  * T` guards rather than Zod: this file compiles into an adopter's browser bundle, and it must not drag
40
41
  * the Worker's schema graph in behind it. `sameOrigin.test.ts` holds the import list to empty, so the
41
42
  * property is structural rather than a habit.
@@ -57,15 +58,14 @@ const AUTH_UNREADABLE = {
57
58
  /**
58
59
  * The request would have left this origin, so it was never sent.
59
60
  *
60
- * The only way to reach it is a `basePath` or a path that is not a rooted same-origin path — an
61
- * absolute URL, a protocol-relative `//host`, a backslash form a URL parser reads as one. Sending it
62
- * would attach an ambient session to a request this page is not entitled to make, which is the thing
63
- * the cookie mode exists to keep from happening.
61
+ * Reached through a `basePath` that is not a rooted path — an absolute URL, a protocol-relative
62
+ * `//host`, a backslash form a URL parser reads as one — or an `origin` that is not a bare http(s)
63
+ * origin. Sending it would attach a session to a request this program is not entitled to make.
64
64
  */
65
65
  const AUTH_CROSS_ORIGIN = {
66
66
  code: "client/cross_origin",
67
67
  message: "That request would have left this site, so it wasn't sent.",
68
- action: "Check the auth `basePath` in pithy.config.ts — it is a path on this worker, not a URL."
68
+ action: "Check the auth `basePath` in pithy.config.ts, which is a path on the worker and not a URL, and the client's `origin`, which is a scheme and host with no path."
69
69
  };
70
70
  /** Whether a value is a plain record — the first step of every guard below. */
71
71
  function isRecord(value) {
@@ -84,6 +84,39 @@ function isSameOriginPath(path) {
84
84
  return second !== "/" && second !== "\\";
85
85
  }
86
86
  /**
87
+ * Whether a configured origin is a bare http(s) origin: a scheme, a host, an optional port, nothing else.
88
+ *
89
+ * A regular expression rather than `new URL`, because React Native's `URL` does not implement the
90
+ * getters a parsed check would read. Userinfo, a path, a query, a fragment, a backslash and whitespace
91
+ * are all refused, so the composed URL can only ever name this host.
92
+ */
93
+ function isBareOrigin(origin) {
94
+ return /^https?:\/\/[A-Za-z0-9.-]+(?::[0-9]{1,5})?$|^https?:\/\/\[[0-9A-Fa-f:.]+\](?::[0-9]{1,5})?$/.test(origin);
95
+ }
96
+ /**
97
+ * The fetch a call goes through: the one passed, else the one on the injected global, else none.
98
+ *
99
+ * Exported so `./bearer` reaches the global the same way every call here does, rather than keeping a
100
+ * second copy of where a fetch comes from.
101
+ */
102
+ function resolveFetch(options) {
103
+ return options?.fetch ?? (options?.global ?? globalThis).fetch;
104
+ }
105
+ /**
106
+ * The same request with no cookie on it — the bearer transport's policy.
107
+ *
108
+ * Written here because this module is the one place a cookie mode is written. `./bearer` puts it on
109
+ * every request its session sends, which is what keeps a cookie a native `fetch` stored from a sign-in
110
+ * answer from riding alongside the bearer: Better Auth refuses a cookie-carrying request with no
111
+ * `Origin`.
112
+ */
113
+ function withoutCookies(init) {
114
+ return {
115
+ ...init,
116
+ credentials: "omit"
117
+ };
118
+ }
119
+ /**
87
120
  * A failure read off either shape this Worker answers with, or the generic one when the body is neither.
88
121
  *
89
122
  * **Two shapes, because two packages own routes here and only one of them is ours.** Everything this
@@ -127,7 +160,8 @@ function readFailure(body) {
127
160
  };
128
161
  }
129
162
  /**
130
- * One call: same-origin, cookie-carrying, never throwing. **The only producer of that request.**
163
+ * One call: same-origin and cookie-carrying, or to an absolute origin with no cookie; never throwing.
164
+ * **The only producer of either request.**
131
165
  *
132
166
  * The body is read before the status is judged, because a refusal's body is the failure a screen
133
167
  * renders. A body that will not parse is the generic failure rather than a crash — a corporate proxy's
@@ -144,22 +178,27 @@ function readFailure(body) {
144
178
  * dragging the Worker's schema graph in behind it would break their build rather than ours.
145
179
  */
146
180
  async function callAuth(path, init, options, guard) {
147
- const url = `${options?.basePath ?? "/auth"}${path}`;
148
- if (!isSameOriginPath(url)) return {
181
+ const rooted = `${options?.basePath ?? "/auth"}${path}`;
182
+ if (!isSameOriginPath(rooted)) return {
183
+ ok: false,
184
+ failure: AUTH_CROSS_ORIGIN
185
+ };
186
+ const origin = options?.origin;
187
+ if (origin !== void 0 && !isBareOrigin(origin)) return {
149
188
  ok: false,
150
189
  failure: AUTH_CROSS_ORIGIN
151
190
  };
152
- const fetcher = options?.fetch ?? (options?.global ?? globalThis).fetch;
191
+ const fetcher = resolveFetch(options);
153
192
  if (!fetcher) return {
154
193
  ok: false,
155
194
  failure: AUTH_UNREACHABLE
156
195
  };
157
196
  let response;
158
197
  try {
159
- response = await fetcher(url, {
198
+ response = origin === void 0 ? await fetcher(rooted, {
160
199
  ...init,
161
200
  credentials: "include"
162
- });
201
+ }) : await fetcher(`${origin}${rooted}`, withoutCookies(init));
163
202
  } catch {
164
203
  return {
165
204
  ok: false,
@@ -399,4 +438,4 @@ async function startSocialSignIn(input, options) {
399
438
  } : { kind: "unconfigured" };
400
439
  }
401
440
  //#endregion
402
- export { AUTH_BASE_PATH, AUTH_CROSS_ORIGIN, AUTH_UNREACHABLE, AUTH_UNREADABLE, callAuth, getSession, sendMagicLink, sendOtp, signInWithOtp, signOut, startSocialSignIn, updateUser };
441
+ export { AUTH_BASE_PATH, AUTH_CROSS_ORIGIN, AUTH_UNREACHABLE, AUTH_UNREADABLE, callAuth, getSession, isBareOrigin, isSameOriginPath, resolveFetch, sendMagicLink, sendOtp, signInWithOtp, signOut, startSocialSignIn, updateUser, withoutCookies };
@@ -0,0 +1,110 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { type AuthClientOptions, type AuthFetch, type AuthResult } from "./api";
4
+ /**
5
+ * The bearer half of `@pithy-sh/auth`'s client: how a program this Worker does not serve — a native app —
6
+ * holds a session and presents it.
7
+ *
8
+ * **The credential is the raw session token**, the `token` a sign-in answers with and the `refreshToken`
9
+ * `/token/rotate` answers with. Never the JWT `accessToken` beside it, which the kit's own routes do not
10
+ * accept, and never the signed `set-auth-token` header, which the Worker cannot match against a spent
11
+ * credential. Only the raw token lets a replay be recognized as one.
12
+ *
13
+ * **It lives in memory and persists through a {@link SecureStore}**, the Keychain or the Keystore on a
14
+ * phone (`expo-secure-store`). Nothing here writes to `AsyncStorage` or `localStorage`.
15
+ *
16
+ * **Rotation is single-flight, and the successor is stored before anything uses it.** `/token/rotate`
17
+ * spends the credential it is shown. A second rotation of the same credential is refused, and one more
18
+ * than thirty seconds late is read as theft: every session descended from that sign-in is revoked. So
19
+ * one rotation is ever in flight, every request that arrives during it waits for it, and none proceeds
20
+ * until the successor is in the store — a launch that read the spent one back would present it.
21
+ *
22
+ * Nothing here throws. A store that fails costs persistence, never a crash, and every failure on the
23
+ * wire is an {@link AuthResult}.
24
+ */
25
+ /** Where a credential is persisted between launches. `expo-secure-store`'s three calls have this shape. */
26
+ export interface SecureStore {
27
+ /** The value stored under `key`, or `null`. */
28
+ getItem(key: string): Promise<string | null>;
29
+ /** Store `value` under `key`. */
30
+ setItem(key: string, value: string): Promise<void>;
31
+ /** Remove whatever is stored under `key`. */
32
+ deleteItem(key: string): Promise<void>;
33
+ }
34
+ /** The device a sign-in registers. The Worker lists it, and revoking it signs out its sessions. */
35
+ export interface DeviceInfo {
36
+ /** A stable id the app mints once per install, at most 128 characters. */
37
+ id: string;
38
+ /** The platform the app runs on. */
39
+ platform: "ios" | "android" | "web";
40
+ /** A human label for the device, when the platform gives one. */
41
+ name?: string;
42
+ /** The hardware model, when the platform gives one. */
43
+ model?: string;
44
+ }
45
+ /** A bearer session: the transport every client call takes, and the credential behind it. */
46
+ export interface BearerSession {
47
+ /** `{ origin, basePath, fetch }`. Pass it to every auth call. */
48
+ readonly options: AuthClientOptions;
49
+ /**
50
+ * A fetch that adds `Authorization` when a credential is held, sends no cookie, and rotates first when
51
+ * the credential is due. Another capability's client takes it as its own `fetch`.
52
+ */
53
+ readonly fetch: AuthFetch;
54
+ /** Load the credential an earlier launch stored. `true` when one was found. */
55
+ restore(): Promise<boolean>;
56
+ /** Hold the raw session token a sign-in answered with. Resolves once it is stored. */
57
+ adopt(token: string): Promise<void>;
58
+ /** Trade the credential for its successor. Concurrent calls share one request. */
59
+ rotate(): Promise<AuthResult<{
60
+ expiresAt: string;
61
+ }>>;
62
+ /** Forget the credential here and in the store. Sign-out calls this after the server call. */
63
+ clear(): Promise<void>;
64
+ /** Whether a credential is held. */
65
+ signedIn(): boolean;
66
+ /**
67
+ * The `Authorization` value a request to `url` would carry now, rotating first when due, for a request the
68
+ * platform sends itself rather than through {@link BearerSession.fetch}: an image the app draws. `null` when
69
+ * nothing is held, and for any URL off the Worker's origin, so the credential is still only ever presented there.
70
+ */
71
+ authorization(url: string): Promise<string | null>;
72
+ }
73
+ /** The key a credential is stored under by default. */
74
+ export declare const BEARER_STORAGE_KEY = "pithy.auth.session";
75
+ /**
76
+ * How long before its expiry a credential is rotated.
77
+ *
78
+ * Wide enough to absorb a phone's clock running a few minutes off the Worker's, narrow enough that a
79
+ * short configured session lifetime does not rotate on every request.
80
+ */
81
+ export declare const ROTATION_MARGIN_MS: number;
82
+ /** The request headers the Worker reads a device from at sign-in. */
83
+ export declare const BEARER_DEVICE_HEADERS: {
84
+ readonly id: "x-pithy-device-id";
85
+ readonly platform: "x-pithy-platform";
86
+ readonly name: "x-pithy-device-name";
87
+ readonly model: "x-pithy-device-model";
88
+ };
89
+ /**
90
+ * Start a bearer session against the Worker at `origin`.
91
+ *
92
+ * Nothing is held until {@link BearerSession.restore} or {@link BearerSession.adopt}. Device headers
93
+ * ride on every request to the auth routes, so whichever route creates the session registers the
94
+ * device; requests to another capability's routes carry the credential alone.
95
+ * A URL off `origin` is refused before it is sent, so the credential is only ever presented to this Worker.
96
+ *
97
+ * The expiry is learnt from what the Worker says: each rotation's `expiresAt`, and the session a
98
+ * `get-session` describes. Until one of those has been seen, nothing rotates on its own. A `get-session`
99
+ * that answers nobody means the credential is dead, and it is forgotten.
100
+ */
101
+ export declare function createBearerSession(input: {
102
+ origin: string;
103
+ basePath?: string;
104
+ store: SecureStore;
105
+ device: DeviceInfo;
106
+ fetch?: AuthFetch;
107
+ now?: () => number;
108
+ storageKey?: string;
109
+ }): BearerSession;
110
+ //# sourceMappingURL=bearer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bearer.d.ts","sourceRoot":"","sources":["../../src/client/bearer.ts"],"names":[],"mappings":"AAGA,OAAO,EAEL,KAAK,iBAAiB,EACtB,KAAK,SAAS,EAGd,KAAK,UAAU,EAKhB,MAAM,OAAO,CAAC;AAEf;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,2GAA2G;AAC3G,MAAM,WAAW,WAAW;IAC1B,+CAA+C;IAC/C,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IAC7C,iCAAiC;IACjC,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACnD,6CAA6C;IAC7C,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACxC;AAED,mGAAmG;AACnG,MAAM,WAAW,UAAU;IACzB,0EAA0E;IAC1E,EAAE,EAAE,MAAM,CAAC;IACX,oCAAoC;IACpC,QAAQ,EAAE,KAAK,GAAG,SAAS,GAAG,KAAK,CAAC;IACpC,iEAAiE;IACjE,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,uDAAuD;IACvD,KAAK,CAAC,EAAE,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