@pithy-sh/auth 0.1.1 → 0.1.3

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 (122) hide show
  1. package/dist/admin/users.d.ts +155 -0
  2. package/dist/admin/users.d.ts.map +1 -0
  3. package/dist/admin/users.js +205 -0
  4. package/dist/audit/actions.d.ts +66 -0
  5. package/dist/audit/actions.d.ts.map +1 -0
  6. package/dist/audit/actions.js +66 -0
  7. package/dist/audit/emit.d.ts +101 -0
  8. package/dist/audit/emit.d.ts.map +1 -0
  9. package/dist/audit/emit.js +170 -0
  10. package/dist/capability.d.ts +60 -0
  11. package/dist/capability.d.ts.map +1 -0
  12. package/dist/capability.js +169 -0
  13. package/dist/client/api.d.ts +299 -0
  14. package/dist/client/api.d.ts.map +1 -0
  15. package/dist/client/api.js +385 -0
  16. package/dist/client/projection.d.ts +51 -0
  17. package/dist/client/projection.d.ts.map +1 -0
  18. package/dist/client/projection.js +0 -0
  19. package/dist/data/betterAuth.d.ts +75 -0
  20. package/dist/data/betterAuth.d.ts.map +1 -0
  21. package/dist/data/betterAuth.js +92 -0
  22. package/dist/data/device.d.ts +36 -0
  23. package/dist/data/device.d.ts.map +1 -0
  24. package/dist/data/device.js +33 -0
  25. package/dist/data/kitFields.d.ts +78 -0
  26. package/dist/data/kitFields.d.ts.map +1 -0
  27. package/dist/data/kitFields.js +77 -0
  28. package/dist/data/rotatedToken.d.ts +20 -0
  29. package/dist/data/rotatedToken.d.ts.map +1 -0
  30. package/dist/data/rotatedToken.js +22 -0
  31. package/dist/data/tables.d.ts +104 -0
  32. package/dist/data/tables.d.ts.map +1 -0
  33. package/dist/data/tables.js +30 -0
  34. package/dist/device/registry.d.ts +54 -0
  35. package/dist/device/registry.d.ts.map +1 -0
  36. package/dist/device/registry.js +85 -0
  37. package/dist/email/send.d.ts +38 -0
  38. package/dist/email/send.d.ts.map +1 -0
  39. package/dist/email/send.js +48 -0
  40. package/dist/http/adminRoutes.d.ts +9 -0
  41. package/dist/http/adminRoutes.d.ts.map +1 -0
  42. package/dist/http/adminRoutes.js +274 -0
  43. package/dist/http/baseUrl.d.ts +41 -0
  44. package/dist/http/baseUrl.d.ts.map +1 -0
  45. package/dist/http/baseUrl.js +96 -0
  46. package/dist/http/csrf.d.ts +18 -0
  47. package/dist/http/csrf.d.ts.map +1 -0
  48. package/dist/http/csrf.js +81 -0
  49. package/dist/http/devLoginRoute.d.ts +42 -0
  50. package/dist/http/devLoginRoute.d.ts.map +1 -0
  51. package/dist/http/devLoginRoute.js +112 -0
  52. package/dist/http/errors.d.ts +24 -0
  53. package/dist/http/errors.d.ts.map +1 -0
  54. package/dist/http/errors.js +67 -0
  55. package/dist/http/guards.d.ts +103 -0
  56. package/dist/http/guards.d.ts.map +1 -0
  57. package/dist/http/guards.js +148 -0
  58. package/dist/http/middleware.d.ts +17 -0
  59. package/dist/http/middleware.d.ts.map +1 -0
  60. package/dist/http/middleware.js +47 -0
  61. package/dist/http/rateLimit.d.ts +17 -0
  62. package/dist/http/rateLimit.d.ts.map +1 -0
  63. package/dist/http/rateLimit.js +31 -0
  64. package/dist/http/resolve.d.ts +9 -0
  65. package/dist/http/resolve.d.ts.map +1 -0
  66. package/dist/http/resolve.js +92 -0
  67. package/dist/http/responses.d.ts +152 -0
  68. package/dist/http/responses.d.ts.map +1 -0
  69. package/dist/http/responses.js +121 -0
  70. package/dist/http/routes.d.ts +34 -0
  71. package/dist/http/routes.d.ts.map +1 -0
  72. package/dist/http/routes.js +268 -0
  73. package/dist/http/schemas.d.ts +66 -0
  74. package/dist/http/schemas.d.ts.map +1 -0
  75. package/dist/http/schemas.js +59 -0
  76. package/dist/http/views.d.ts +53 -0
  77. package/dist/http/views.d.ts.map +1 -0
  78. package/dist/http/views.js +86 -0
  79. package/dist/i18n/errorCopy.d.ts +24 -0
  80. package/dist/i18n/errorCopy.d.ts.map +1 -0
  81. package/dist/i18n/errorCopy.es.d.ts +31 -0
  82. package/dist/i18n/errorCopy.es.d.ts.map +1 -0
  83. package/dist/i18n/errorCopy.es.js +33 -0
  84. package/dist/i18n/errorCopy.js +91 -0
  85. package/dist/index.d.ts +14 -0
  86. package/dist/index.d.ts.map +1 -0
  87. package/dist/index.js +8 -0
  88. package/dist/instance/auth.d.ts +1122 -0
  89. package/dist/instance/auth.d.ts.map +1 -0
  90. package/dist/instance/auth.js +176 -0
  91. package/dist/instance/plugins.d.ts +87 -0
  92. package/dist/instance/plugins.d.ts.map +1 -0
  93. package/dist/instance/plugins.js +116 -0
  94. package/dist/instance/providers.d.ts +117 -0
  95. package/dist/instance/providers.d.ts.map +1 -0
  96. package/dist/instance/providers.js +111 -0
  97. package/dist/instance/secrets.d.ts +163 -0
  98. package/dist/instance/secrets.d.ts.map +1 -0
  99. package/dist/instance/secrets.js +169 -0
  100. package/dist/migrations/0001_init.d.ts +33 -0
  101. package/dist/migrations/0001_init.d.ts.map +1 -0
  102. package/dist/migrations/0001_init.js +77 -0
  103. package/dist/migrations/pluginTables.d.ts +126 -0
  104. package/dist/migrations/pluginTables.d.ts.map +1 -0
  105. package/dist/migrations/pluginTables.js +233 -0
  106. package/dist/seeds/devSession.d.ts +124 -0
  107. package/dist/seeds/devSession.d.ts.map +1 -0
  108. package/dist/seeds/devSession.js +211 -0
  109. package/dist/seeds/example.d.ts +12 -0
  110. package/dist/seeds/example.d.ts.map +1 -0
  111. package/dist/seeds/example.js +30 -0
  112. package/dist/test-utils/liveApp.d.ts +227 -0
  113. package/dist/test-utils/liveApp.d.ts.map +1 -0
  114. package/dist/test-utils/liveApp.js +240 -0
  115. package/dist/token/rotation.d.ts +56 -0
  116. package/dist/token/rotation.d.ts.map +1 -0
  117. package/dist/token/rotation.js +68 -0
  118. package/dist/version.generated.d.ts +5 -0
  119. package/dist/version.generated.d.ts.map +1 -0
  120. package/dist/version.generated.js +7 -0
  121. package/package.json +24 -13
  122. package/src/version.generated.ts +1 -1
@@ -0,0 +1,385 @@
1
+ //#region src/client/api.ts
2
+ /**
3
+ * The browser half of `@pithy-sh/auth`: the one place that knows how a browser program makes a
4
+ * same-origin, cookie-bearing request to this Worker, and the calls made through it — the six a
5
+ * scaffolded screen makes, and {@link updateUser}, which an adopter's own screen calls.
6
+ *
7
+ * **This module lives in the package for the reason `@pithy-sh/payments`'s counterpart does, only more
8
+ * so.** `pithy ui add` writes the auth screens once and may never rewrite them: they are copied into
9
+ * the adopter's repository and become the adopter's files. Every request written into one of those
10
+ * files is frozen there at the moment `pithy init` ran, and a later fix to the base path, the cookie
11
+ * mode or the failure directions reaches none of them. Six such requests existed — `/get-session`,
12
+ * `/sign-out`, the two OTP routes, the magic link, and the social handoff — each spelling out the same
13
+ * transport by hand. They call this now, and this upgrades with a minor release (#370).
14
+ *
15
+ * **Cookie/session, same origin, and that is enforced rather than assumed.** Every request carries
16
+ * `credentials: "include"` and nothing else: no token in `localStorage` or `sessionStorage`, no
17
+ * `Authorization` header, no refresh rotation. The SPA and its Worker share an origin, so the session
18
+ * rides an httpOnly cookie JavaScript cannot read. Bearer is the mobile path — the same routes serve
19
+ * it, documented rather than scaffolded.
20
+ *
21
+ * **CSRF travels with the cookie mode, and half of it is on this side of the wire.** The server's
22
+ * `requireSameOrigin()` refuses a cookie-authenticated mutating request whose `Origin` does not match;
23
+ * the browser only attaches that header to a request it considers this page's own. So the client half
24
+ * of the rule is that the request never leaves the origin — {@link callAuth} builds its URL from a base
25
+ * path and a relative path and **refuses anything that is not a rooted same-origin path**, rather than
26
+ * handing an ambient session to whatever a mis-set `basePath` names. A caller cannot forget the check,
27
+ * because a caller no longer writes the request.
28
+ *
29
+ * **Nothing here throws.** Not a stylistic choice: this module imports nothing, so `PithyError` is not
30
+ * in reach, and a bare `throw new Error` is exactly what this kit forbids. An unreachable Worker, a
31
+ * proxy's HTML error page, a 500 — each becomes a renderable {@link AuthFailure} on an
32
+ * {@link AuthResult}, and every caller answers one. The Worker is still the security boundary; nothing
33
+ * on this side of the wire protects anything, it only decides what a screen shows.
34
+ *
35
+ * **No absolute URL literals, and no schema library.** Paths are relative, so the calls follow whatever
36
+ * origin the bundle is served from. Answers are narrowed by hand-written `is…(value: unknown): value is
37
+ * T` guards rather than Zod: this file compiles into an adopter's browser bundle, and it must not drag
38
+ * the Worker's schema graph in behind it. `sameOrigin.test.ts` holds the import list to empty, so the
39
+ * property is structural rather than a habit.
40
+ */
41
+ /** Where the auth handler mounts by default — the same default `AuthConfig.basePath` carries. */
42
+ const AUTH_BASE_PATH = "/auth";
43
+ /** The worker could not be reached at all. Offline, or a DNS failure, or no fetch in this program. */
44
+ const AUTH_UNREACHABLE = {
45
+ code: "client/unreachable",
46
+ message: "We couldn't reach the server.",
47
+ action: "Check your connection, then try again."
48
+ };
49
+ /** The worker answered with something this client cannot read. A proxy's HTML page, or a shape change. */
50
+ const AUTH_UNREADABLE = {
51
+ code: "client/unreadable",
52
+ message: "The server answered with something we couldn't read.",
53
+ action: "Try again. If it keeps happening, the app and the backend are out of step."
54
+ };
55
+ /**
56
+ * The request would have left this origin, so it was never sent.
57
+ *
58
+ * The only way to reach it is a `basePath` or a path that is not a rooted same-origin path — an
59
+ * absolute URL, a protocol-relative `//host`, a backslash form a URL parser reads as one. Sending it
60
+ * would attach an ambient session to a request this page is not entitled to make, which is the thing
61
+ * the cookie mode exists to keep from happening.
62
+ */
63
+ const AUTH_CROSS_ORIGIN = {
64
+ code: "client/cross_origin",
65
+ message: "That request would have left this site, so it wasn't sent.",
66
+ action: "Check the auth `basePath` in pithy.config.ts — it is a path on this worker, not a URL."
67
+ };
68
+ /** Whether a value is a plain record — the first step of every guard below. */
69
+ function isRecord(value) {
70
+ return typeof value === "object" && value !== null && !Array.isArray(value);
71
+ }
72
+ /**
73
+ * Whether a composed path stays on this origin.
74
+ *
75
+ * A rooted path and nothing that resolves elsewhere. `//host` and `/\host` are the two forms a URL
76
+ * parser reads as an authority rather than as a path, and a browser follows both — which is why the
77
+ * check is on the second character rather than on a scheme it would never find after a leading `/`.
78
+ */
79
+ function isSameOriginPath(path) {
80
+ if (!path.startsWith("/")) return false;
81
+ const second = path.charAt(1);
82
+ return second !== "/" && second !== "\\";
83
+ }
84
+ /**
85
+ * A failure read off either shape this Worker answers with, or the generic one when the body is neither.
86
+ *
87
+ * **Two shapes, because two packages own routes here and only one of them is ours.** Everything this
88
+ * capability writes answers `{ error: { code, message, action } }` through `pithyErrorHandler`. Every
89
+ * route Better Auth owns — the one-time code, the magic link, sign-out, `get-session`, the social
90
+ * handoff, `update-user` — answers its own flat `{ message, code }`, because better-call renders an
91
+ * endpoint's `APIError` into a Response inside `instance.handler` and nothing on our side of that ever
92
+ * sees it (#449).
93
+ *
94
+ * Reading only the envelope meant every one of those refusals arrived as {@link AUTH_UNREADABLE}, so a
95
+ * reader who mistyped their one-time code was told the app was broken rather than that the code was
96
+ * wrong — in a screen `pithy ui add` copies into an adopter's repository, where it can never be fixed.
97
+ *
98
+ * **The flat shape is read rather than rewritten on the server, deliberately.** `packages/auth/README.md`
99
+ * documents `createAuthClient` from `better-auth/client` as a first-class client surface (#271), and
100
+ * `@better-fetch/fetch` builds its error as `{ ...parsedBody, status }` — so an adopter on that path
101
+ * reads `error.code === "INVALID_OTP"` today. Re-homing the body into our envelope would make that
102
+ * `undefined` for every one of them. The wire is Better Auth's contract; this side learns to read it.
103
+ *
104
+ * So `code` arrives in whichever vocabulary produced it, and the two are told apart by their shape:
105
+ * `auth/invalid_token` is ours, `INVALID_OTP` is Better Auth's. A screen matching on a code should
106
+ * expect the one belonging to the route it called.
107
+ */
108
+ function readFailure(body) {
109
+ if (!isRecord(body)) return AUTH_UNREADABLE;
110
+ if (isRecord(body.error)) {
111
+ const { code, message, action } = body.error;
112
+ if (typeof code !== "string" || typeof message !== "string") return AUTH_UNREADABLE;
113
+ return {
114
+ code,
115
+ message,
116
+ action: typeof action === "string" ? action : null
117
+ };
118
+ }
119
+ const { code, message } = body;
120
+ if (typeof code !== "string" || typeof message !== "string") return AUTH_UNREADABLE;
121
+ return {
122
+ code,
123
+ message,
124
+ action: null
125
+ };
126
+ }
127
+ /**
128
+ * One call: same-origin, cookie-carrying, never throwing. **The only producer of that request.**
129
+ *
130
+ * The body is read before the status is judged, because a refusal's body is the failure a screen
131
+ * renders. A body that will not parse is the generic failure rather than a crash — a corporate proxy's
132
+ * HTML page reaches a browser far more often than anyone expects.
133
+ *
134
+ * **Exported, and that is the point of it.** `@pithy-sh/auth` shipped no browser primitive at all, so
135
+ * six scaffolded screens each wrote the transport out by hand — and those screens are copied into an
136
+ * adopter's repository, where Pithy can never fix them. Every browser program that asks this Worker an
137
+ * auth question calls this, and `sameOrigin.test.ts` fails the build on any module that grows its own
138
+ * (#370).
139
+ *
140
+ * **Zod-free, like everything on this side of the wire.** The answer is narrowed by the hand-written
141
+ * `guard` a caller passes, never by a schema: this compiles into an adopter's browser bundle, and
142
+ * dragging the Worker's schema graph in behind it would break their build rather than ours.
143
+ */
144
+ async function callAuth(path, init, options, guard) {
145
+ const url = `${options?.basePath ?? "/auth"}${path}`;
146
+ if (!isSameOriginPath(url)) return {
147
+ ok: false,
148
+ failure: AUTH_CROSS_ORIGIN
149
+ };
150
+ const fetcher = options?.fetch ?? (options?.global ?? globalThis).fetch;
151
+ if (!fetcher) return {
152
+ ok: false,
153
+ failure: AUTH_UNREACHABLE
154
+ };
155
+ let response;
156
+ try {
157
+ response = await fetcher(url, {
158
+ ...init,
159
+ credentials: "include"
160
+ });
161
+ } catch {
162
+ return {
163
+ ok: false,
164
+ failure: AUTH_UNREACHABLE
165
+ };
166
+ }
167
+ let body;
168
+ try {
169
+ body = await response.json();
170
+ } catch {
171
+ return {
172
+ ok: false,
173
+ failure: AUTH_UNREADABLE
174
+ };
175
+ }
176
+ if (!response.ok) return {
177
+ ok: false,
178
+ failure: readFailure(body)
179
+ };
180
+ return guard(body) ? {
181
+ ok: true,
182
+ value: body
183
+ } : {
184
+ ok: false,
185
+ failure: AUTH_UNREADABLE
186
+ };
187
+ }
188
+ /**
189
+ * A JSON POST, with the humanity check's contribution already folded in.
190
+ *
191
+ * The gate is applied here rather than at each call site for the reason the cookie mode is: a screen
192
+ * that forgets it sends an ungated request to a gated route and gets a 403 it cannot explain.
193
+ */
194
+ function jsonPost(body, options) {
195
+ const gated = options?.gate ? options.gate(body) : {
196
+ body,
197
+ headers: {}
198
+ };
199
+ return {
200
+ method: "POST",
201
+ headers: {
202
+ "content-type": "application/json",
203
+ ...gated.headers
204
+ },
205
+ body: JSON.stringify(gated.body)
206
+ };
207
+ }
208
+ /**
209
+ * Whether a value is a session envelope, or the explicit "nobody" the route answers with.
210
+ *
211
+ * `null` is a valid answer and a distinct one from a failure — signed out is not the same as unread —
212
+ * so it is narrowed here rather than collapsed into one by a caller.
213
+ */
214
+ function isSession(value) {
215
+ if (value === null) return true;
216
+ if (!isRecord(value)) return false;
217
+ const user = value.user;
218
+ return isRecord(user) && typeof user.id === "string" && typeof user.email === "string";
219
+ }
220
+ /** Whether a value is any JSON object. The floor for a route whose success body a screen does not read. */
221
+ function isObject(value) {
222
+ return isRecord(value);
223
+ }
224
+ /**
225
+ * Who is signed in, or `null`.
226
+ *
227
+ * **A failure is not a signed-out session**, and the return type is what keeps the two apart. A screen
228
+ * that renders "signed out" from an unreachable Worker offers a sign-in form to somebody who is
229
+ * already signed in, and the sign-in it starts replaces a live session with a new one. A caller that
230
+ * wants to treat them alike writes `result.ok ? result.value : null` — one line, reading as the
231
+ * decision it is.
232
+ */
233
+ function getSession(options) {
234
+ return callAuth("/get-session", {}, options, isSession);
235
+ }
236
+ /**
237
+ * End the session server-side.
238
+ *
239
+ * **The content type is not decoration, and the scaffolded screen was missing it.** The route refuses a
240
+ * POST without `application/json` with a 415 — so every app scaffolded so far has been signing nobody
241
+ * out. It went unnoticed because the screen ignored the answer and navigated to `/sign-in` regardless,
242
+ * which looks exactly like a successful sign-out until the back button restores a live session.
243
+ * `clientRoundTrip.test.ts` is what found it, and is what would find it again: a request written into a
244
+ * file Pithy may never rewrite is a request nobody ever tested against the route it names (#370).
245
+ *
246
+ * The body is an empty object rather than nothing, because a declared JSON content type with no body is
247
+ * the other half of the same 415.
248
+ */
249
+ function signOut(options) {
250
+ return callAuth("/sign-out", {
251
+ method: "POST",
252
+ headers: { "content-type": "application/json" },
253
+ body: "{}"
254
+ }, options, isObject);
255
+ }
256
+ /**
257
+ * Store something on the signed-in reader's own account. Today that is their language, and only that.
258
+ *
259
+ * **The rule it exists to serve is `docs/I18N.md`'s: `pithy_auth_users.locale` is the one home for a
260
+ * person's language — do not put language in your own preferences table.** A preferences table is the
261
+ * right home for time zone, date format, a 24-hour clock; none of those is language. Two homes for one
262
+ * fact is not a duplicate row, it is a magic-link email in the wrong language with nothing anywhere
263
+ * failing to say so, because the send Workflow reads the auth column and the settings pane reads the
264
+ * other one. This is the write that keeps the home single, and `useNegotiatedLocale`'s `persist` seam
265
+ * (`@pithy-sh/i18n`) is the caller it was written for: `persist: (next) => { void updateUser({ locale: next }); }`.
266
+ * The discard is deliberate: `persist` returns `void | Promise<void>` and this resolves to an
267
+ * `AuthResult`, so returning the call straight does not typecheck — and nothing is lost by dropping
268
+ * it, because nothing here throws.
269
+ *
270
+ * **`locale` is the only field it takes, because it is the only kit user field declared `input: true`**
271
+ * (`../data/kitFields`). Every other column Pithy adds is server-set — a client that could name its own
272
+ * device or token family could name somebody else's — while a language is the reader's own preference
273
+ * and no admin route is a thing a reader has. What makes taking it from a client safe is the `Locale`
274
+ * validator on the field rather than this signature: Better Auth runs it before the write, so the same
275
+ * schema that guards every read guards the write one hop earlier, and a megabyte of junk is a 400 here
276
+ * instead of a row that throws for every operator who later lists users.
277
+ *
278
+ * **`null` is accepted deliberately, and it is not the empty string.** Null means *this reader has not
279
+ * chosen*, which is what makes the server fall back to `Accept-Language`; taking a language choice back
280
+ * is an ordinary thing a reader does, and a call that refused it would answer 400 for the one state the
281
+ * schema calls ordinary.
282
+ *
283
+ * **Not `jsonPost`, for the reason {@link signOut} is not.** That folds in the humanity check, and this
284
+ * is not a gated route: `createAuthRoutes` stacks the Turnstile gate on `/sign-in/magic-link` and
285
+ * `/email-otp/send-verification-otp` and on nothing else, so a token folded in here would be an
286
+ * unexpected field on a request Better Auth validates itself. The content type and the `{}` body are
287
+ * the same 415 story as sign-out — a declared JSON type with no body is refused just as an undeclared
288
+ * one is.
289
+ *
290
+ * **And it is kit code rather than an adopter's, because both alternatives are worse than this
291
+ * function.** Standing up a second Better Auth client with `inferAdditionalFields` duplicates
292
+ * configuration `@pithy-sh/auth` already owns. Reaching for {@link callAuth} instead means an adopter
293
+ * spelling out the path, the content type and the guard themselves, one deep import below the surface
294
+ * every other auth call in their app goes through — written into a file Pithy can never fix (#446).
295
+ *
296
+ * **The answer carries no user, whatever the route's own OpenAPI block advertises.** Better Auth's
297
+ * `/update-user` ends `ctx.json({ status: true })`, so `value` is `{ status: true }` and
298
+ * `value.locale` is `undefined`. Nothing is lost by that — a screen already has the value it just
299
+ * wrote — but do not reach into it for the row.
300
+ *
301
+ * **A refusal is a failure to render and never a throw, and it is `client/unreadable` more often than
302
+ * it looks.** This is Better Auth's own route, and Better Auth turns its own `APIError`s into
303
+ * Responses inside `instance.handler`, so they never reach the `apiErrorToPithy` re-homing in
304
+ * `../http/routes`. The body stays Better Auth's flat `{ message, code }` rather than the kit's error
305
+ * envelope, and {@link AUTH_UNREADABLE} is what `readFailure` makes of anything that is not that
306
+ * envelope: a signed-out reader's 401 reads as `client/unreadable`, and so does a tag the `Locale`
307
+ * validator rejected. Which is enough for the caller this exists for — `useNegotiatedLocale` drops a
308
+ * failed preference write either way, because the reader already has the language they picked.
309
+ */
310
+ function updateUser(fields, options) {
311
+ return callAuth("/update-user", {
312
+ method: "POST",
313
+ headers: { "content-type": "application/json" },
314
+ body: JSON.stringify({ ...fields })
315
+ }, options, isObject);
316
+ }
317
+ /** Sign in with a one-time code the user typed. The answer is the session it created. */
318
+ function signInWithOtp(input, options) {
319
+ return callAuth("/sign-in/email-otp", jsonPost({ ...input }, options), options, isObject);
320
+ }
321
+ /**
322
+ * Mail a one-time code.
323
+ *
324
+ * Gated by the humanity check when one is composed — `options.gate` puts the token where the middleware
325
+ * reads it, and a screen cannot forget to.
326
+ */
327
+ function sendOtp(input, options) {
328
+ return callAuth("/email-otp/send-verification-otp", jsonPost({ ...input }, options), options, isObject);
329
+ }
330
+ /**
331
+ * Mail a magic link.
332
+ *
333
+ * `callbackURL` is the adopter's own screen, so it is theirs to name. Gated the same way as
334
+ * {@link sendOtp}.
335
+ */
336
+ function sendMagicLink(input, options) {
337
+ return callAuth("/sign-in/magic-link", jsonPost({ ...input }, options), options, isObject);
338
+ }
339
+ /**
340
+ * Whether an answer is an authorization URL a browser may be sent to, and the two reasons it might not be.
341
+ *
342
+ * **The scheme check.** `window.location.href = url` with a `javascript:` URL executes that script in
343
+ * this page, so a response body is not something to hand straight to a navigator however trusted its
344
+ * origin.
345
+ *
346
+ * **The `client_id` check.** An OAuth 2.0 authorization request must carry one, so an authorization URL
347
+ * naming no client is a provider with a blank credential behind it. The client projection carries
348
+ * booleans and never credentials, so a browser cannot know that in advance — refusing the *response* is
349
+ * what turns a blank credential into a sentence on the screen rather than a bounce to Google's own
350
+ * error page.
351
+ */
352
+ function isAuthorization(value) {
353
+ if (!isRecord(value) || typeof value.url !== "string") return false;
354
+ try {
355
+ const parsed = new URL(value.url);
356
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return false;
357
+ return (parsed.searchParams.get("client_id") ?? "") !== "";
358
+ } catch {
359
+ return false;
360
+ }
361
+ }
362
+ /**
363
+ * Ask for a provider's authorization URL.
364
+ *
365
+ * **No humanity check, deliberately**: the redirect carries no token to check and the provider runs its
366
+ * own bot defense, which is what `@pithy-sh/auth` already assumes when it stacks the check on the
367
+ * magic-link route alone. Gating it would only stop people signing in.
368
+ */
369
+ async function startSocialSignIn(input, options) {
370
+ const ungated = options && {
371
+ ...options,
372
+ gate: void 0
373
+ };
374
+ const result = await callAuth("/sign-in/social", jsonPost({ ...input }, void 0), ungated, isObject);
375
+ if (!result.ok) return {
376
+ kind: "refused",
377
+ failure: result.failure
378
+ };
379
+ return isAuthorization(result.value) ? {
380
+ kind: "authorize",
381
+ url: result.value.url
382
+ } : { kind: "unconfigured" };
383
+ }
384
+ //#endregion
385
+ export { AUTH_BASE_PATH, AUTH_CROSS_ORIGIN, AUTH_UNREACHABLE, AUTH_UNREADABLE, callAuth, getSession, sendMagicLink, sendOtp, signInWithOtp, signOut, startSocialSignIn, updateUser };
@@ -0,0 +1,51 @@
1
+ /**
2
+ * What a browser may know about this project's auth — the shape of `virtual:pithy/auth`.
3
+ *
4
+ * **This declaration is the contract, and the projection is checked against it.** It is written here
5
+ * rather than inferred from the closure that builds it, and that is the whole point: an inferred type
6
+ * follows whatever the producer last happened to say, so a projection that dropped `otpLength`, or that
7
+ * started projecting `baseURL` because one screen wanted it, would take the type with it and nothing
8
+ * would go red. Declared, both are a compile error at the `client:` that wrote them, and widening what
9
+ * every adopter's bundle carries becomes a decision made here, on purpose.
10
+ *
11
+ * The `enabled: false` branch is not this capability's to produce. `resolveClientProjection` answers it
12
+ * for a capability nobody composed, and a front end is written against the capabilities it *may* have.
13
+ * It is declared here because it is what a browser reads, and the browser cannot tell the two apart.
14
+ *
15
+ * **This is the only statement of the shape.** `@pithy-sh/ui-react`'s `templates/client-env.d.ts` — the
16
+ * ambient declaration `pithy ui add react` copies into an adopter's Worker — is generated from this type
17
+ * by `@pithy-sh/vite`'s `clientEnvDeclaration.ts` (#398). The unions and the per-field doc comments below
18
+ * are emitted verbatim, so what is written here is what a screen author reads.
19
+ */
20
+ export type AuthClientProjection = {
21
+ /** Auth is not composed on this worker. A screen branches rather than rendering a sign-in form. */
22
+ enabled: false;
23
+ } | {
24
+ /** Auth is composed on this worker. */
25
+ enabled: true;
26
+ /** The path the auth handler mounts under, e.g. `/auth`. */
27
+ basePath: string;
28
+ /**
29
+ * Which social providers are switched on in pithy.config.ts. Credentials never reach the client —
30
+ * they are not in the config this projection can see, they are in the secrets store.
31
+ *
32
+ * Nested, so a screen iterates the set rather than naming four booleans. A fifth provider is one
33
+ * key here — and until it is written here, projecting it is a compile error, not a surprise in
34
+ * somebody's bundle.
35
+ */
36
+ providers: {
37
+ /** Whether Sign in with Google is offered. */
38
+ google: boolean;
39
+ /** Whether Sign in with Apple is offered. */
40
+ apple: boolean;
41
+ /** Whether Sign in with Facebook is offered. */
42
+ facebook: boolean;
43
+ /** Whether Sign in with GitHub is offered. */
44
+ github: boolean;
45
+ };
46
+ /** How many digits an email OTP carries. */
47
+ otpLength: number;
48
+ /** Whether signing in may provision a new user. Drives the sign-up copy. */
49
+ signUpEnabled: boolean;
50
+ };
51
+ //# sourceMappingURL=projection.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"projection.d.ts","sourceRoot":"","sources":["../../src/client/projection.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,MAAM,oBAAoB,GAC5B;IACE,mGAAmG;IACnG,OAAO,EAAE,KAAK,CAAC;CAChB,GACD;IACE,uCAAuC;IACvC,OAAO,EAAE,IAAI,CAAC;IACd,4DAA4D;IAC5D,QAAQ,EAAE,MAAM,CAAC;IACjB;;;;;;;OAOG;IACH,SAAS,EAAE;QACT,8CAA8C;QAC9C,MAAM,EAAE,OAAO,CAAC;QAChB,6CAA6C;QAC7C,KAAK,EAAE,OAAO,CAAC;QACf,gDAAgD;QAChD,QAAQ,EAAE,OAAO,CAAC;QAClB,8CAA8C;QAC9C,MAAM,EAAE,OAAO,CAAC;KACjB,CAAC;IACF,4CAA4C;IAC5C,SAAS,EAAE,MAAM,CAAC;IAClB,4EAA4E;IAC5E,aAAa,EAAE,OAAO,CAAC;CACxB,CAAC"}
File without changes
@@ -0,0 +1,75 @@
1
+ import { z } from "zod";
2
+ /** `pithy_auth_users` — one end user. Text/UUID id (anti-enumeration); email is unique. */
3
+ export declare const User: z.ZodObject<{
4
+ id: z.ZodString;
5
+ name: z.ZodString;
6
+ email: z.ZodString;
7
+ emailVerified: z.ZodCodec<z.ZodUnion<readonly [z.ZodLiteral<0>, z.ZodLiteral<1>, z.ZodBoolean, z.ZodString]>, z.ZodBoolean>;
8
+ image: z.ZodNullable<z.ZodString>;
9
+ locale: z.ZodNullable<z.ZodString>;
10
+ createdAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodDate]>, z.ZodDate>;
11
+ updatedAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodDate]>, z.ZodDate>;
12
+ }, z.core.$strip>;
13
+ export type User = z.output<typeof User>;
14
+ /** `pithy_auth_sessions` — one active session (the long-lived, bearer/cookie credential). */
15
+ export declare const Session: z.ZodObject<{
16
+ id: z.ZodString;
17
+ expiresAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodDate]>, z.ZodDate>;
18
+ token: z.ZodString;
19
+ createdAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodDate]>, z.ZodDate>;
20
+ updatedAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodDate]>, z.ZodDate>;
21
+ ipAddress: z.ZodNullable<z.ZodString>;
22
+ userAgent: z.ZodNullable<z.ZodString>;
23
+ userId: z.ZodString;
24
+ deviceId: z.ZodNullable<z.ZodString>;
25
+ familyId: z.ZodNullable<z.ZodString>;
26
+ }, z.core.$strip>;
27
+ export type Session = z.output<typeof Session>;
28
+ /** `pithy_auth_accounts` — a credential/identity link for a user (one row per social provider). */
29
+ export declare const Account: z.ZodObject<{
30
+ id: z.ZodString;
31
+ issuer: z.ZodString;
32
+ accountId: z.ZodString;
33
+ providerId: z.ZodString;
34
+ userId: z.ZodString;
35
+ accessToken: z.ZodNullable<z.ZodString>;
36
+ refreshToken: z.ZodNullable<z.ZodString>;
37
+ idToken: z.ZodNullable<z.ZodString>;
38
+ accessTokenExpiresAt: z.ZodNullable<z.ZodCodec<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodDate]>, z.ZodDate>>;
39
+ refreshTokenExpiresAt: z.ZodNullable<z.ZodCodec<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodDate]>, z.ZodDate>>;
40
+ scope: z.ZodNullable<z.ZodString>;
41
+ password: z.ZodNullable<z.ZodString>;
42
+ createdAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodDate]>, z.ZodDate>;
43
+ updatedAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodDate]>, z.ZodDate>;
44
+ }, z.core.$strip>;
45
+ export type Account = z.output<typeof Account>;
46
+ /** `pithy_auth_verifications` — short-lived tokens: magic-link, OTP, and OAuth PKCE/state. */
47
+ export declare const Verification: z.ZodObject<{
48
+ id: z.ZodString;
49
+ identifier: z.ZodString;
50
+ value: z.ZodString;
51
+ expiresAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodDate]>, z.ZodDate>;
52
+ createdAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodDate]>, z.ZodDate>;
53
+ updatedAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodDate]>, z.ZodDate>;
54
+ }, z.core.$strip>;
55
+ export type Verification = z.output<typeof Verification>;
56
+ /** `pithy_auth_jwks` — the JWKS keypairs that sign and verify short-lived JWT access tokens. */
57
+ export declare const Jwks: z.ZodObject<{
58
+ id: z.ZodString;
59
+ publicKey: z.ZodString;
60
+ privateKey: z.ZodString;
61
+ createdAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodDate]>, z.ZodDate>;
62
+ expiresAt: z.ZodNullable<z.ZodCodec<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodDate]>, z.ZodDate>>;
63
+ alg: z.ZodNullable<z.ZodString>;
64
+ crv: z.ZodNullable<z.ZodString>;
65
+ }, z.core.$strip>;
66
+ export type Jwks = z.output<typeof Jwks>;
67
+ /** `pithy_auth_rate_limit` — Better Auth's database-backed rate-limit counters (per key, durable across isolates). */
68
+ export declare const RateLimit: z.ZodObject<{
69
+ id: z.ZodString;
70
+ key: z.ZodString;
71
+ count: z.ZodNumber;
72
+ lastRequest: z.ZodNumber;
73
+ }, z.core.$strip>;
74
+ export type RateLimit = z.output<typeof RateLimit>;
75
+ //# sourceMappingURL=betterAuth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"betterAuth.d.ts","sourceRoot":"","sources":["../../src/data/betterAuth.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAuBxB,2FAA2F;AAC3F,eAAO,MAAM,IAAI;;;;;;;;;iBAqBwF,CAAC;AAC1G,MAAM,MAAM,IAAI,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,IAAI,CAAC,CAAC;AAEzC,6FAA6F;AAC7F,eAAO,MAAM,OAAO;;;;;;;;;;;iBAkCqF,CAAC;AAC1G,MAAM,MAAM,OAAO,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,OAAO,CAAC,CAAC;AAE/C,mGAAmG;AACnG,eAAO,MAAM,OAAO;;;;;;;;;;;;;;;iBAyCqF,CAAC;AAC1G,MAAM,MAAM,OAAO,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,OAAO,CAAC,CAAC;AAE/C,8FAA8F;AAC9F,eAAO,MAAM,YAAY;;;;;;;iBAmBtB,CAAC;AACJ,MAAM,MAAM,YAAY,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,YAAY,CAAC,CAAC;AAEzD,gGAAgG;AAChG,eAAO,MAAM,IAAI;;;;;;;;iBA8Bd,CAAC;AACJ,MAAM,MAAM,IAAI,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,IAAI,CAAC,CAAC;AAEzC,sHAAsH;AACtH,eAAO,MAAM,SAAS;;;;;iBAcnB,CAAC;AACJ,MAAM,MAAM,SAAS,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,SAAS,CAAC,CAAC"}
@@ -0,0 +1,92 @@
1
+ import { z } from "zod";
2
+ import { JsonDate, SQLiteBoolean } from "@pithy-sh/core/src/data/codecs";
3
+ import { Locale } from "@pithy-sh/core/src/i18n/locale";
4
+ //#region src/data/betterAuth.ts
5
+ /**
6
+ * The Better-Auth-managed tables, one Zod object per table.
7
+ *
8
+ * Better Auth owns the reads and writes to these via its Kysely adapter (which wraps our shared
9
+ * Kysely + `CamelCasePlugin`, so it issues camelCase identifiers that map to the snake_case
10
+ * `pithy_auth_*` columns our migration creates). These schemas are the table definitions of record:
11
+ * they back the migration, document the model, and decode any direct read Pithy does. Columns are
12
+ * column-exact to Better Auth 1.6.19's generated SQLite schema. Dates are ISO-8601 text
13
+ * (`BetterAuthDate`), booleans are `0|1` (`SQLiteBoolean`) — matching Better Auth's on-disk
14
+ * representation, not Pithy's ms-epoch house default. `z.input` is the SQLite row; `z.output` the
15
+ * app shape.
16
+ */
17
+ /**
18
+ * Date codec for Better-Auth columns. On SQLite/D1 Better Auth's adapter serializes `date` fields with
19
+ * `Date#toISOString()` — ISO-8601 **text**, not the ms-epoch number Pithy's house `SQLiteDate` assumes.
20
+ * That on-disk shape is exactly core's `JsonDate` (Date ↔ ISO-8601 string), so this is an alias, named
21
+ * for its use so the right codec is obvious at each Better-Auth column (`SQLiteDate` would mis-decode).
22
+ */
23
+ const BetterAuthDate = JsonDate;
24
+ /** `pithy_auth_users` — one end user. Text/UUID id (anti-enumeration); email is unique. */
25
+ const User = z.object({
26
+ id: z.string().describe("Primary key. A random/UUID text id (not auto-increment) so users cannot be enumerated."),
27
+ name: z.string().describe("The user's display name, supplied by the provider profile or at sign-up."),
28
+ email: z.string().describe("The user's email address. Unique across all users; the identity key for passwordless sign-in."),
29
+ emailVerified: SQLiteBoolean.describe("Whether the email has been verified. Stored as `0|1`; magic-link/OTP sign-in sets it true."),
30
+ image: z.string().nullable().describe("URL of the user's avatar from a social profile, or null."),
31
+ locale: Locale.nullable().describe("The reader's chosen language as a BCP-47 tag, or null when they have never chosen. Null is not the default locale: it means negotiate from `Accept-Language`, so an unchosen reader follows their device. A stored tag outranks the header."),
32
+ createdAt: BetterAuthDate.describe("When the user record was created. ISO-8601 text in SQLite; a `Date` in app code."),
33
+ updatedAt: BetterAuthDate.describe("When the user record was last updated. ISO-8601 text in SQLite; a `Date` in app code.")
34
+ }).describe("A user in `pithy_auth_users` — the canonical identity every session and account hangs off.");
35
+ /** `pithy_auth_sessions` — one active session (the long-lived, bearer/cookie credential). */
36
+ const Session = z.object({
37
+ id: z.string().describe("Primary key. A random/UUID text id."),
38
+ expiresAt: BetterAuthDate.describe("When the session expires. Slides forward on use within `updateAge`. ISO-8601 text in SQLite."),
39
+ token: z.string().describe("The opaque session token. Unique; presented as the cookie value or `Authorization: Bearer`. The refresh credential."),
40
+ createdAt: BetterAuthDate.describe("When the session was created. ISO-8601 text in SQLite."),
41
+ updatedAt: BetterAuthDate.describe("When the session was last refreshed. ISO-8601 text in SQLite."),
42
+ ipAddress: z.string().nullable().describe("The client IP at sign-in, for the device registry and `new sign-in from…` security signals. Nullable."),
43
+ userAgent: z.string().nullable().describe("The client user-agent at sign-in. Nullable."),
44
+ userId: z.string().describe("The owning user's id. Foreign key to `pithy_auth_users(id)`, ON DELETE CASCADE."),
45
+ deviceId: z.string().nullable().describe("The id of the `pithy_auth_devices` row this session is bound to (per-device sessions), or null for a device-less web login."),
46
+ familyId: z.string().nullable().describe("The refresh-token family this session belongs to, carried across rotations so a replayed refresh token can revoke the whole chain. Server-set; null for a session created before rotation or one never rotated.")
47
+ }).describe("A session in `pithy_auth_sessions` — a signed-in credential, optionally bound to a device.");
48
+ /** `pithy_auth_accounts` — a credential/identity link for a user (one row per social provider). */
49
+ const Account = z.object({
50
+ id: z.string().describe("Primary key. A random/UUID text id."),
51
+ issuer: z.string().describe("Who asserted this identity, as the identity provider names itself: an OIDC issuer URL (`https://accounts.google.com`), `local:oauth:<id>` for an OAuth provider that publishes none, or `local:credential` for a password. With `accountId` it is the account's identity and carries a unique index — a provider slug is a name this project chose, so two providers pointed at one directory could assert the same `accountId` and land on two rows."),
52
+ accountId: z.string().describe("The provider's stable id for this user (e.g. the Google `sub` claim)."),
53
+ providerId: z.string().describe("The provider slug, e.g. `google`. Identifies which OAuth/credential provider this row links."),
54
+ userId: z.string().describe("The owning user's id. Foreign key to `pithy_auth_users(id)`, ON DELETE CASCADE."),
55
+ accessToken: z.string().nullable().describe("The provider OAuth access token, if granted. Never returned to clients. Nullable."),
56
+ refreshToken: z.string().nullable().describe("The provider OAuth refresh token, if granted (`accessType: offline`). Never returned to clients. Nullable."),
57
+ idToken: z.string().nullable().describe("The provider OIDC id token from the last sign-in. Never returned to clients. Nullable."),
58
+ accessTokenExpiresAt: BetterAuthDate.nullable().describe("When the provider access token expires. ISO-8601 text in SQLite. Nullable."),
59
+ refreshTokenExpiresAt: BetterAuthDate.nullable().describe("When the provider refresh token expires. ISO-8601 text in SQLite. Nullable."),
60
+ scope: z.string().nullable().describe("The OAuth scopes granted, space-delimited. Nullable."),
61
+ password: z.string().nullable().describe("Unused — Pithy is passwordless-only, so this Better-Auth column is always null."),
62
+ createdAt: BetterAuthDate.describe("When the account link was created. ISO-8601 text in SQLite."),
63
+ updatedAt: BetterAuthDate.describe("When the account link was last updated. ISO-8601 text in SQLite.")
64
+ }).describe("An account link in `pithy_auth_accounts` — a user's connection to a social/OAuth provider.");
65
+ /** `pithy_auth_verifications` — short-lived tokens: magic-link, OTP, and OAuth PKCE/state. */
66
+ const Verification = z.object({
67
+ id: z.string().describe("Primary key. A random/UUID text id."),
68
+ identifier: z.string().describe("What the value verifies — a namespaced email for OTP/magic-link, or the OAuth `state` for PKCE. Indexed."),
69
+ value: z.string().describe("The token, code, or serialized PKCE/state payload. Consumed atomically on first verify (single-use)."),
70
+ expiresAt: BetterAuthDate.describe("When the verification expires (5 min for magic-link/OTP, ~10 min for OAuth state). ISO-8601 text in SQLite."),
71
+ createdAt: BetterAuthDate.describe("When the verification was created. ISO-8601 text in SQLite."),
72
+ updatedAt: BetterAuthDate.describe("When the verification was last updated. ISO-8601 text in SQLite.")
73
+ }).describe("A verification record in `pithy_auth_verifications` — the store behind magic-link, OTP, and OAuth PKCE state.");
74
+ /** `pithy_auth_jwks` — the JWKS keypairs that sign and verify short-lived JWT access tokens. */
75
+ const Jwks = z.object({
76
+ id: z.string().describe("Primary key. A random/UUID text id, used as the JWT `kid`."),
77
+ publicKey: z.string().describe("The public key (JWK), published at `/jwks` so resource servers verify access tokens locally."),
78
+ privateKey: z.string().describe("The private signing key, encrypted at rest with the Better-Auth secret (sourced from `@pithy-sh/secrets`). Never published."),
79
+ createdAt: BetterAuthDate.describe("When the keypair was created. ISO-8601 text in SQLite."),
80
+ expiresAt: BetterAuthDate.nullable().describe("When the keypair is retired. Retired keys stay published through their grace window so in-flight tokens still verify. Nullable."),
81
+ alg: z.string().nullable().describe("The signing algorithm this keypair is for (`EdDSA`, `RS256`), published in the key's JWKS entry so a verifier picks the right one without guessing. Nullable because Better Auth declares it optional and a key minted before 1.7 has none — the plugin falls back to `EdDSA`, which is what those keys are."),
82
+ crv: z.string().nullable().describe("The elliptic curve for an EC or OKP key (`Ed25519`, `P-256`), and null for RSA, which has no curve. Published beside `alg` for the same reason.")
83
+ }).describe("A signing keypair in `pithy_auth_jwks` — rotation keeps prior public keys published so issued tokens keep verifying.");
84
+ /** `pithy_auth_rate_limit` — Better Auth's database-backed rate-limit counters (per key, durable across isolates). */
85
+ const RateLimit = z.object({
86
+ id: z.string().describe("Primary key. A random/UUID text id."),
87
+ key: z.string().describe("The rate-limit bucket key (path + client IP). Unique."),
88
+ count: z.number().int().describe("The number of requests counted in the current window."),
89
+ lastRequest: z.number().int().describe("The ms-epoch timestamp of the most recent request in the window. A raw number, written by Better Auth's limiter.")
90
+ }).describe("A rate-limit counter in `pithy_auth_rate_limit` — durable per-isolate-safe throttling for the auth send/sign-in routes.");
91
+ //#endregion
92
+ export { Account, Jwks, RateLimit, Session, User, Verification };
@@ -0,0 +1,36 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * `pithy_auth_devices` — the device registry, a Pithy-specific table with no Better-Auth equivalent.
4
+ *
5
+ * One row per user-device, keyed on a client-generated stable id so the same physical device maps to
6
+ * one row across re-logins. Sessions link back via `pithy_auth_sessions.device_id`. This table is
7
+ * written by Pithy code (the `session.create` hook and the device routes) through our shared Kysely,
8
+ * so it keeps Pithy's house ms-epoch `SQLiteDate` — unlike the Better-Auth tables.
9
+ */
10
+ /** The platform a device runs. `web` covers any browser; mobile carries richer metadata. */
11
+ export declare const DevicePlatform: z.ZodEnum<{
12
+ android: "android";
13
+ ios: "ios";
14
+ web: "web";
15
+ }>;
16
+ export type DevicePlatform = z.output<typeof DevicePlatform>;
17
+ /** One registered device. */
18
+ export declare const Device: z.ZodObject<{
19
+ id: z.ZodString;
20
+ userId: z.ZodString;
21
+ platform: z.ZodEnum<{
22
+ android: "android";
23
+ ios: "ios";
24
+ web: "web";
25
+ }>;
26
+ name: z.ZodNullable<z.ZodString>;
27
+ model: z.ZodNullable<z.ZodString>;
28
+ osVersion: z.ZodNullable<z.ZodString>;
29
+ appVersion: z.ZodNullable<z.ZodString>;
30
+ pushToken: z.ZodNullable<z.ZodString>;
31
+ lastIp: z.ZodNullable<z.ZodString>;
32
+ lastSeenAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>;
33
+ createdAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>;
34
+ }, z.core.$strip>;
35
+ export type Device = z.output<typeof Device>;
36
+ //# sourceMappingURL=device.d.ts.map