@pithy-sh/auth 0.1.2 → 0.1.4

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 +157 -0
  2. package/dist/admin/users.d.ts.map +1 -0
  3. package/dist/admin/users.js +207 -0
  4. package/dist/audit/actions.d.ts +68 -0
  5. package/dist/audit/actions.d.ts.map +1 -0
  6. package/dist/audit/actions.js +68 -0
  7. package/dist/audit/emit.d.ts +103 -0
  8. package/dist/audit/emit.d.ts.map +1 -0
  9. package/dist/audit/emit.js +172 -0
  10. package/dist/capability.d.ts +62 -0
  11. package/dist/capability.d.ts.map +1 -0
  12. package/dist/capability.js +171 -0
  13. package/dist/client/api.d.ts +301 -0
  14. package/dist/client/api.d.ts.map +1 -0
  15. package/dist/client/api.js +387 -0
  16. package/dist/client/projection.d.ts +53 -0
  17. package/dist/client/projection.d.ts.map +1 -0
  18. package/dist/client/projection.js +2 -0
  19. package/dist/data/betterAuth.d.ts +77 -0
  20. package/dist/data/betterAuth.d.ts.map +1 -0
  21. package/dist/data/betterAuth.js +94 -0
  22. package/dist/data/device.d.ts +38 -0
  23. package/dist/data/device.d.ts.map +1 -0
  24. package/dist/data/device.js +35 -0
  25. package/dist/data/kitFields.d.ts +80 -0
  26. package/dist/data/kitFields.d.ts.map +1 -0
  27. package/dist/data/kitFields.js +79 -0
  28. package/dist/data/rotatedToken.d.ts +22 -0
  29. package/dist/data/rotatedToken.d.ts.map +1 -0
  30. package/dist/data/rotatedToken.js +24 -0
  31. package/dist/data/tables.d.ts +106 -0
  32. package/dist/data/tables.d.ts.map +1 -0
  33. package/dist/data/tables.js +32 -0
  34. package/dist/device/registry.d.ts +56 -0
  35. package/dist/device/registry.d.ts.map +1 -0
  36. package/dist/device/registry.js +87 -0
  37. package/dist/email/send.d.ts +40 -0
  38. package/dist/email/send.d.ts.map +1 -0
  39. package/dist/email/send.js +50 -0
  40. package/dist/http/adminRoutes.d.ts +11 -0
  41. package/dist/http/adminRoutes.d.ts.map +1 -0
  42. package/dist/http/adminRoutes.js +276 -0
  43. package/dist/http/baseUrl.d.ts +43 -0
  44. package/dist/http/baseUrl.d.ts.map +1 -0
  45. package/dist/http/baseUrl.js +98 -0
  46. package/dist/http/csrf.d.ts +20 -0
  47. package/dist/http/csrf.d.ts.map +1 -0
  48. package/dist/http/csrf.js +83 -0
  49. package/dist/http/devLoginRoute.d.ts +44 -0
  50. package/dist/http/devLoginRoute.d.ts.map +1 -0
  51. package/dist/http/devLoginRoute.js +114 -0
  52. package/dist/http/errors.d.ts +26 -0
  53. package/dist/http/errors.d.ts.map +1 -0
  54. package/dist/http/errors.js +69 -0
  55. package/dist/http/guards.d.ts +105 -0
  56. package/dist/http/guards.d.ts.map +1 -0
  57. package/dist/http/guards.js +150 -0
  58. package/dist/http/middleware.d.ts +19 -0
  59. package/dist/http/middleware.d.ts.map +1 -0
  60. package/dist/http/middleware.js +49 -0
  61. package/dist/http/rateLimit.d.ts +19 -0
  62. package/dist/http/rateLimit.d.ts.map +1 -0
  63. package/dist/http/rateLimit.js +33 -0
  64. package/dist/http/resolve.d.ts +11 -0
  65. package/dist/http/resolve.d.ts.map +1 -0
  66. package/dist/http/resolve.js +94 -0
  67. package/dist/http/responses.d.ts +154 -0
  68. package/dist/http/responses.d.ts.map +1 -0
  69. package/dist/http/responses.js +123 -0
  70. package/dist/http/routes.d.ts +36 -0
  71. package/dist/http/routes.d.ts.map +1 -0
  72. package/dist/http/routes.js +270 -0
  73. package/dist/http/schemas.d.ts +68 -0
  74. package/dist/http/schemas.d.ts.map +1 -0
  75. package/dist/http/schemas.js +61 -0
  76. package/dist/http/views.d.ts +55 -0
  77. package/dist/http/views.d.ts.map +1 -0
  78. package/dist/http/views.js +88 -0
  79. package/dist/i18n/errorCopy.d.ts +26 -0
  80. package/dist/i18n/errorCopy.d.ts.map +1 -0
  81. package/dist/i18n/errorCopy.es.d.ts +33 -0
  82. package/dist/i18n/errorCopy.es.d.ts.map +1 -0
  83. package/dist/i18n/errorCopy.es.js +35 -0
  84. package/dist/i18n/errorCopy.js +93 -0
  85. package/dist/index.d.ts +16 -0
  86. package/dist/index.d.ts.map +1 -0
  87. package/dist/index.js +10 -0
  88. package/dist/instance/auth.d.ts +1124 -0
  89. package/dist/instance/auth.d.ts.map +1 -0
  90. package/dist/instance/auth.js +178 -0
  91. package/dist/instance/plugins.d.ts +89 -0
  92. package/dist/instance/plugins.d.ts.map +1 -0
  93. package/dist/instance/plugins.js +118 -0
  94. package/dist/instance/providers.d.ts +119 -0
  95. package/dist/instance/providers.d.ts.map +1 -0
  96. package/dist/instance/providers.js +113 -0
  97. package/dist/instance/secrets.d.ts +165 -0
  98. package/dist/instance/secrets.d.ts.map +1 -0
  99. package/dist/instance/secrets.js +171 -0
  100. package/dist/migrations/0001_init.d.ts +35 -0
  101. package/dist/migrations/0001_init.d.ts.map +1 -0
  102. package/dist/migrations/0001_init.js +79 -0
  103. package/dist/migrations/pluginTables.d.ts +128 -0
  104. package/dist/migrations/pluginTables.d.ts.map +1 -0
  105. package/dist/migrations/pluginTables.js +235 -0
  106. package/dist/seeds/devSession.d.ts +126 -0
  107. package/dist/seeds/devSession.d.ts.map +1 -0
  108. package/dist/seeds/devSession.js +213 -0
  109. package/dist/seeds/example.d.ts +14 -0
  110. package/dist/seeds/example.d.ts.map +1 -0
  111. package/dist/seeds/example.js +32 -0
  112. package/dist/test-utils/liveApp.d.ts +229 -0
  113. package/dist/test-utils/liveApp.d.ts.map +1 -0
  114. package/dist/test-utils/liveApp.js +242 -0
  115. package/dist/token/rotation.d.ts +58 -0
  116. package/dist/token/rotation.d.ts.map +1 -0
  117. package/dist/token/rotation.js +70 -0
  118. package/dist/version.generated.d.ts +7 -0
  119. package/dist/version.generated.d.ts.map +1 -0
  120. package/dist/version.generated.js +9 -0
  121. package/package.json +24 -13
  122. package/src/version.generated.ts +1 -1
@@ -0,0 +1,50 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ //#region src/email/send.ts
4
+ /**
5
+ * Build the `sendEmail` the auth instance calls from its magic-link / OTP hooks.
6
+ *
7
+ * ## The locale
8
+ *
9
+ * A sign-in email is the first thing a project sends and the one it cannot afford to send in a
10
+ * language the reader does not have, because there is no password to fall back to: somebody who cannot
11
+ * find the button in an unfamiliar alphabet cannot get in at all. So `localeFor` is asked per message
12
+ * and the answer rides onto the job, where the send Workflow reads it back hours later.
13
+ *
14
+ * It resolves in two steps and the order matters. **A stored `pithy_auth_users.locale` wins**, because
15
+ * a person who has chosen a language has said something durable about themselves, and the device they
16
+ * happen to be signing in from tonight has not. Where there is no row — a first-time sign-up, which is
17
+ * exactly when a magic link matters most — the resolver falls back to the language this request
18
+ * negotiated, which is the only thing anyone knows about the reader yet. Null means neither answered,
19
+ * and null renders the kit's English rather than asserting English was chosen.
20
+ *
21
+ * Optional so that a composition without it (and every existing test harness) behaves as it did.
22
+ */
23
+ function makeSendAuthEmail(enqueue, expiresMinutes, localeFor) {
24
+ return async (message) => {
25
+ const locale = await localeFor?.(message.to) ?? void 0;
26
+ if (message.template === "magicLink") {
27
+ await enqueue({
28
+ to: message.to,
29
+ template: "magicLink",
30
+ payload: {
31
+ url: message.url,
32
+ expiresMinutes
33
+ },
34
+ ...locale ? { locale } : {}
35
+ });
36
+ return;
37
+ }
38
+ await enqueue({
39
+ to: message.to,
40
+ template: "otp",
41
+ payload: {
42
+ code: message.code,
43
+ expiresMinutes
44
+ },
45
+ ...locale ? { locale } : {}
46
+ });
47
+ };
48
+ }
49
+ //#endregion
50
+ export { makeSendAuthEmail };
@@ -0,0 +1,11 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
4
+ import type { Hono } from "hono";
5
+ import type { AuthWiring } from "../capability";
6
+ /**
7
+ * Register the control-plane admin routes. Called by `createAuthRoutes` **before** the Better Auth
8
+ * catch-all; see the file header for why that ordering is load-bearing.
9
+ */
10
+ export declare function registerAuthAdminRoutes(wiring: AuthWiring): (app: Hono<PithyHonoEnv>) => void;
11
+ //# sourceMappingURL=adminRoutes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adminRoutes.d.ts","sourceRoot":"","sources":["../../src/http/adminRoutes.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAM7E,OAAO,KAAK,EAAW,IAAI,EAAE,MAAM,MAAM,CAAC;AAc1C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAmJhD;;;GAGG;AACH,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,UAAU,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,YAAY,CAAC,KAAK,IAAI,CAgM7F"}
@@ -0,0 +1,276 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { authDatabase } from "../data/tables.js";
4
+ import { AuthAuditActions } from "../audit/actions.js";
5
+ import { correlation, emitControlPlaneAction } from "../audit/emit.js";
6
+ import { deleteDevice, deviceSessionTokens } from "../device/registry.js";
7
+ import { getAuthInstance, resolveDb } from "./resolve.js";
8
+ import { AUTH_DEVICES_READ_SCOPE, AUTH_DEVICES_REVOKE_SCOPE, AUTH_SESSIONS_REVOKE_SCOPE, AUTH_USERS_LOGOUT_SCOPE, AUTH_USERS_READ_SCOPE } from "./guards.js";
9
+ import { findSessionById, getUser, listDeviceRegistry, listUserDevices, listUserSessions, listUsers, userProviders, userSessionTokens } from "../admin/users.js";
10
+ import { ListDevicesQuery, ListUsersQuery, RevokeDeviceBody, RevokeSessionBody, UserIdParam } from "./schemas.js";
11
+ import { deviceView, sessionView, userView } from "./views.js";
12
+ import { InternalError, NotFoundError } from "@pithy-sh/core/src/error/pithyError";
13
+ import { zValidator } from "@hono/zod-validator";
14
+ import { validationHook } from "@pithy-sh/core/src/http/validation";
15
+ import { requireControlPlane } from "@pithy-sh/core/src/controlPlane/http/guard";
16
+ import { MAX_PAGE_SIZE } from "@pithy-sh/core/src/data/cursor";
17
+ //#region src/http/adminRoutes.ts
18
+ /**
19
+ * The control-plane admin surface: the reads a management dashboard's user panes resolve to, and the
20
+ * revocations an incident costs.
21
+ *
22
+ * GET {base}/admin/users auth:users:read query: ListUsersQuery
23
+ * GET {base}/admin/users/:userId auth:users:read param: UserIdParam
24
+ * GET {base}/admin/devices auth:devices:read query: ListDevicesQuery
25
+ * POST {base}/admin/sessions/revoke auth:sessions:revoke json: RevokeSessionBody
26
+ * POST {base}/admin/users/:userId/sessions/revoke auth:users:logout param: UserIdParam
27
+ * POST {base}/admin/users/:userId/devices/revoke auth:devices:revoke param + json
28
+ *
29
+ * ## Registered before the catch-all, or dead
30
+ *
31
+ * `createAuthRoutes` ends with `app.all(`${base}/*`, handleBetterAuth)`, and `handleBetterAuth` returns
32
+ * a Response — which ends the chain. **Anything registered after that line is silently unreachable**,
33
+ * and a route-inspection test would still pass because the route is genuinely mounted; it just never
34
+ * runs. So these are registered from inside `createAuthRoutes` before the catch-all, and
35
+ * `routeContract.test.ts` proves it with a real request rather than by reading `app.routes`.
36
+ *
37
+ * ## `requireControlPlane` only, never `requireAuth`
38
+ *
39
+ * See `guards.ts` for the whole argument. The short version: the seam deliberately leaves `c.var.auth`
40
+ * null, so an auth gate here would deny every legitimate management call forever, and there is no user
41
+ * to sign in as that would fix it.
42
+ *
43
+ * ## Validators after the gate, on every line
44
+ *
45
+ * A validator ahead of the gate turns a 403 into a 400 and tells an unverified caller which requests
46
+ * were well-formed. On this surface that is a live oracle for an adopter's identity model, so the
47
+ * ordering is asserted in `routeContract.test.ts` rather than trusted to the order somebody typed the
48
+ * arguments in.
49
+ *
50
+ * ## Every response is a deliberate projection, and every projection has a schema
51
+ *
52
+ * No handler returns a row. The projections live in `views.ts` and the objects a client validates
53
+ * against live in `responses.ts`, each view typed as `z.output` of its own schema — so what this
54
+ * Worker sends and what a management client is told to expect are one declaration rather than two
55
+ * that drift. `sessionView` drops the session **token**; `deviceView` drops the **push token**; and
56
+ * the account link is read as a list of provider slugs by a query that selects only `providerId`, so
57
+ * the OAuth `accessToken`, `refreshToken` and `idToken` are never loaded at all.
58
+ *
59
+ * Each `c.json` below is `satisfies`-checked against its envelope. The check belongs at compile time:
60
+ * parsing every response would spend a validation pass on data this Worker just built from its own
61
+ * rows, and it would turn a shape mistake into a 500 in production rather than a red build.
62
+ */
63
+ /** The auth Kysely for this request. */
64
+ function db(c, wiring) {
65
+ return authDatabase(resolveDb(c.env, wiring.config.database));
66
+ }
67
+ /**
68
+ * One of the user pane's sub-reads, guarded and projected in one step (#380).
69
+ *
70
+ * **`try`/`catch` inside an `async` function, never `.catch()`.** The read is *called* inside the `try`,
71
+ * so a seam that throws before it returns a promise is caught too — a rejected promise is not the only
72
+ * way a D1 read fails, and a `.catch()` guard has been escaped by exactly that before (#371).
73
+ *
74
+ * **The guard takes no binding.** The state is the whole of what travels; what the read threw names a
75
+ * query and a table, and this response goes to a management client across a trust boundary.
76
+ *
77
+ * It projects while it is here, because the alternative is a second helper mapping a union it just
78
+ * built, and a projection that runs outside the guard is a second place a row can throw.
79
+ */
80
+ async function readBounded(read, project) {
81
+ try {
82
+ const list = await read();
83
+ return {
84
+ state: "read",
85
+ items: list.items.map(project),
86
+ truncated: list.truncated
87
+ };
88
+ } catch {
89
+ return { state: "unavailable" };
90
+ }
91
+ }
92
+ /** The same guard for a read with no bound to exceed — the provider slugs, which carry no truncation. */
93
+ async function readWhole(read) {
94
+ try {
95
+ return {
96
+ state: "read",
97
+ items: await read()
98
+ };
99
+ } catch {
100
+ return { state: "unavailable" };
101
+ }
102
+ }
103
+ /**
104
+ * The verified management client behind a control-plane call.
105
+ *
106
+ * `requireControlPlane()` has run on every route below, so a null context is a wiring mistake rather
107
+ * than an unverified request — hence `InternalError`, not a 401. Deliberately not read off `c.var.auth`:
108
+ * a management client has no user row and no session, and keeping the two accessors apart is what stops
109
+ * a control-plane caller from being recorded as, or mistaken for, a user of this app.
110
+ */
111
+ function controlPlaneCaller(c) {
112
+ const caller = c.var.controlPlane;
113
+ if (!caller) throw new InternalError({
114
+ message: "Authentication is misconfigured.",
115
+ detail: "requireControlPlane() must run before an auth admin handler reads the management caller."
116
+ });
117
+ return caller;
118
+ }
119
+ /** The request correlation every admin audit event carries. */
120
+ function context(c) {
121
+ return {
122
+ ...correlation(c.req.raw.headers),
123
+ requestId: c.req.header("cf-ray")
124
+ };
125
+ }
126
+ /** Delete sessions through Better Auth's own adapter, so its bookkeeping stays consistent. */
127
+ async function revokeTokens(c, wiring, tokens) {
128
+ if (tokens.length === 0) return 0;
129
+ const ctx = await (await getAuthInstance(c, wiring)).$context;
130
+ for (const token of tokens) await ctx.internalAdapter.deleteSession(token);
131
+ return tokens.length;
132
+ }
133
+ /**
134
+ * Register the control-plane admin routes. Called by `createAuthRoutes` **before** the Better Auth
135
+ * catch-all; see the file header for why that ordering is load-bearing.
136
+ */
137
+ function registerAuthAdminRoutes(wiring) {
138
+ return (app) => {
139
+ const base = wiring.config.basePath;
140
+ app.get(`${base}/admin/users`, requireControlPlane(AUTH_USERS_READ_SCOPE), zValidator("query", ListUsersQuery, validationHook), async (c) => {
141
+ const query = c.req.valid("query");
142
+ const caller = controlPlaneCaller(c);
143
+ const page = await listUsers(db(c, wiring), query);
144
+ await emitControlPlaneAction(c.var.emit, {
145
+ action: AuthAuditActions.adminUsersListed,
146
+ subject: caller.subject,
147
+ connectionId: caller.connectionId,
148
+ resourceType: "user",
149
+ ...context(c),
150
+ metadata: {
151
+ searched: query.search !== void 0,
152
+ returned: page.items.length
153
+ }
154
+ });
155
+ return c.json({
156
+ users: page.items.map(userView),
157
+ nextCursor: page.nextCursor
158
+ });
159
+ });
160
+ app.get(`${base}/admin/users/:userId`, requireControlPlane(AUTH_USERS_READ_SCOPE), zValidator("param", UserIdParam, validationHook), async (c) => {
161
+ const { userId } = c.req.valid("param");
162
+ const caller = controlPlaneCaller(c);
163
+ const database = db(c, wiring);
164
+ const user = await getUser(database, userId);
165
+ if (!user) throw new NotFoundError({
166
+ message: "No such user.",
167
+ detail: `no pithy_auth_users row for ${userId}`
168
+ });
169
+ const [sessions, devices, providers] = await Promise.all([
170
+ readBounded(() => listUserSessions(database, userId, MAX_PAGE_SIZE), sessionView),
171
+ readBounded(() => listUserDevices(database, userId, MAX_PAGE_SIZE), deviceView),
172
+ readWhole(() => userProviders(database, userId))
173
+ ]);
174
+ await emitControlPlaneAction(c.var.emit, {
175
+ action: AuthAuditActions.adminUserRead,
176
+ subject: caller.subject,
177
+ connectionId: caller.connectionId,
178
+ resourceType: "user",
179
+ resourceId: userId,
180
+ ...context(c),
181
+ metadata: {
182
+ sessions: sessions.state === "read" ? sessions.items.length : null,
183
+ devices: devices.state === "read" ? devices.items.length : null
184
+ }
185
+ });
186
+ return c.json({
187
+ user: userView(user),
188
+ providers,
189
+ sessions,
190
+ devices
191
+ });
192
+ });
193
+ app.get(`${base}/admin/devices`, requireControlPlane(AUTH_DEVICES_READ_SCOPE), zValidator("query", ListDevicesQuery, validationHook), async (c) => {
194
+ const query = c.req.valid("query");
195
+ const caller = controlPlaneCaller(c);
196
+ const page = await listDeviceRegistry(db(c, wiring), query);
197
+ await emitControlPlaneAction(c.var.emit, {
198
+ action: AuthAuditActions.adminDevicesListed,
199
+ subject: caller.subject,
200
+ connectionId: caller.connectionId,
201
+ resourceType: "device",
202
+ resourceId: query.userId ?? null,
203
+ ...context(c),
204
+ metadata: {
205
+ returned: page.items.length,
206
+ filteredByUser: query.userId !== void 0
207
+ }
208
+ });
209
+ return c.json({
210
+ devices: page.items.map(deviceView),
211
+ nextCursor: page.nextCursor
212
+ });
213
+ });
214
+ app.post(`${base}/admin/sessions/revoke`, requireControlPlane(AUTH_SESSIONS_REVOKE_SCOPE), zValidator("json", RevokeSessionBody, validationHook), async (c) => {
215
+ const { sessionId } = c.req.valid("json");
216
+ const caller = controlPlaneCaller(c);
217
+ const session = await findSessionById(db(c, wiring), sessionId);
218
+ const revoked = session ? await revokeTokens(c, wiring, [session.token]) : 0;
219
+ await emitControlPlaneAction(c.var.emit, {
220
+ action: AuthAuditActions.adminSessionRevoked,
221
+ subject: caller.subject,
222
+ connectionId: caller.connectionId,
223
+ resourceType: "session",
224
+ resourceId: sessionId,
225
+ ...context(c),
226
+ metadata: {
227
+ revoked,
228
+ userId: session?.userId ?? null
229
+ }
230
+ });
231
+ return c.json({ revoked });
232
+ });
233
+ app.post(`${base}/admin/users/:userId/sessions/revoke`, requireControlPlane(AUTH_USERS_LOGOUT_SCOPE), zValidator("param", UserIdParam, validationHook), async (c) => {
234
+ const { userId } = c.req.valid("param");
235
+ const caller = controlPlaneCaller(c);
236
+ const revoked = await revokeTokens(c, wiring, await userSessionTokens(db(c, wiring), userId));
237
+ await emitControlPlaneAction(c.var.emit, {
238
+ action: AuthAuditActions.adminUserSessionsRevoked,
239
+ subject: caller.subject,
240
+ connectionId: caller.connectionId,
241
+ resourceType: "user",
242
+ resourceId: userId,
243
+ ...context(c),
244
+ metadata: { revoked }
245
+ });
246
+ return c.json({ revoked });
247
+ });
248
+ app.post(`${base}/admin/users/:userId/devices/revoke`, requireControlPlane(AUTH_DEVICES_REVOKE_SCOPE), zValidator("param", UserIdParam, validationHook), zValidator("json", RevokeDeviceBody, validationHook), async (c) => {
249
+ const { userId } = c.req.valid("param");
250
+ const { deviceId } = c.req.valid("json");
251
+ const caller = controlPlaneCaller(c);
252
+ const database = db(c, wiring);
253
+ const revoked = await revokeTokens(c, wiring, await deviceSessionTokens(database, userId, deviceId));
254
+ const removed = await deleteDevice(database, userId, deviceId);
255
+ await emitControlPlaneAction(c.var.emit, {
256
+ action: AuthAuditActions.adminDeviceRevoked,
257
+ subject: caller.subject,
258
+ connectionId: caller.connectionId,
259
+ resourceType: "device",
260
+ resourceId: deviceId,
261
+ ...context(c),
262
+ metadata: {
263
+ userId,
264
+ revoked,
265
+ removed
266
+ }
267
+ });
268
+ return c.json({
269
+ revoked,
270
+ removed
271
+ });
272
+ });
273
+ };
274
+ }
275
+ //#endregion
276
+ export { registerAuthAdminRoutes };
@@ -0,0 +1,43 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { type AmbientEnv } from "@pithy-sh/core/src/env/ambient";
4
+ /**
5
+ * The scheme every `dev` composition serves on.
6
+ *
7
+ * Not a default and not a guess: Pithy runs no TLS locally, so there is no second possibility to choose
8
+ * between. It is exported because the dev-session seed needs it to name the cookie it writes, and that
9
+ * agreement is the whole invariant.
10
+ */
11
+ export declare const DEV_PROTOCOL = "http:";
12
+ /**
13
+ * The base URL a `dev` composition resolves for a request that arrived at `host`.
14
+ *
15
+ * `host`, not `hostname`: the port is the whole point, and it is the part of a dev address that nobody
16
+ * can know before the run allocates it.
17
+ */
18
+ export declare function devBaseURL(host: string): string;
19
+ /**
20
+ * A base URL's scheme, or `""` for a string that is not a URL at all.
21
+ *
22
+ * Tolerant rather than throwing, for the same reason the CSRF gate's `originOf` is: `baseURL` is a
23
+ * `z.string()` an adopter writes by hand, and a malformed one must fail as "no `__Secure-` prefix" —
24
+ * matching what Better Auth itself does with it — not as a 500 on every request.
25
+ */
26
+ export declare function baseURLProtocol(baseURL: string): string;
27
+ /**
28
+ * Better Auth's session cookie name for a base URL served over `protocol`.
29
+ *
30
+ * Our mirror of a rule that lives in Better Auth: it adds the `__Secure-` prefix when the base URL is
31
+ * HTTPS. Mirrored because the seed has to name the cookie before any instance exists, and pinned to the
32
+ * running version by a test that reads the name off a live instance — so an upgrade that changed the
33
+ * rule fails there rather than in a browser.
34
+ */
35
+ export declare function sessionCookieName(protocol: string): string;
36
+ /** Resolve the base URL this composition serves under, for one request. */
37
+ export type ResolveBaseURL = (request: Request) => string;
38
+ /**
39
+ * Build this composition's base-URL resolver. The environment is read once, here, and nowhere else in
40
+ * this seam.
41
+ */
42
+ export declare function baseURLResolver(configured: string, env?: AmbientEnv): ResolveBaseURL;
43
+ //# sourceMappingURL=baseUrl.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"baseUrl.d.ts","sourceRoot":"","sources":["../../src/http/baseUrl.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,UAAU,EAAsC,MAAM,gCAAgC,CAAC;AA4CrG;;;;;;GAMG;AACH,eAAO,MAAM,YAAY,UAAU,CAAC;AAKpC;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE/C;AAED;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAMvD;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAE1D;AAED,2EAA2E;AAC3E,MAAM,MAAM,cAAc,GAAG,CAAC,OAAO,EAAE,OAAO,KAAK,MAAM,CAAC;AAE1D;;;GAGG;AACH,wBAAgB,eAAe,CAAC,UAAU,EAAE,MAAM,EAAE,GAAG,GAAE,UAAyB,GAAG,cAAc,CAKlG"}
@@ -0,0 +1,98 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { ambientEnv, compositionEnvironment } from "@pithy-sh/core/src/env/ambient";
4
+ //#region src/http/baseUrl.ts
5
+ /**
6
+ * Where a composition's base URL comes from — and therefore what its session cookie is called, and
7
+ * which origin its CSRF gate calls its own.
8
+ *
9
+ * ## The shape, and the two that lost
10
+ *
11
+ * `baseURL` stays **one string, and it means the deployed origin**. A `dev` composition does not read
12
+ * it: it resolves its base URL from the host the request actually arrived on, over `http`.
13
+ *
14
+ * A per-environment record (`{ prod, staging, dev }`, the way a Worker's `domains` block reads) was the
15
+ * obvious shape and it fails on the one value it exists to hold. The dev port is assigned per Worker per
16
+ * run from the feature's reserved block, so `dev: "http://localhost:8787"` is wrong the moment a second
17
+ * Worker starts or that port is taken — and a record whose `dev` key must be left empty to be correct is
18
+ * a field that only ever holds a mistake.
19
+ *
20
+ * Resolving from the request is what survives that, because the request is the only thing that knows the
21
+ * port. It cannot be stale, it needs no cooperation from `pithy dev`, and nothing has to be written down.
22
+ *
23
+ * ## We run no TLS locally, so the scheme is a constant
24
+ *
25
+ * That is settled policy, and it is what makes the rest hold **by construction** rather than by comment.
26
+ * `devBaseURL` fixes the scheme and takes only the host; {@link sessionCookieName} reads only the scheme.
27
+ * So the part nobody can know ahead of time — the port — cannot reach the cookie name, and the part that
28
+ * decides the cookie name is a constant. The dev seed and the running composition agree because they are
29
+ * reading the same two lines, not because they were written on the same day.
30
+ *
31
+ * ## One gate, on the environment alone
32
+ *
33
+ * {@link baseURLResolver} contains the only environment test in this seam: one `if`, on
34
+ * `compositionEnvironment` and nothing else, and-ed and or-ed with nothing. Outside `dev` it returns the
35
+ * configured value verbatim for every request, so a staging or production Worker resolves exactly what it
36
+ * resolved before this module existed — and the same-origin set it builds is byte-identical, because the
37
+ * origin the gate adds is the origin the configured base URL already contributed.
38
+ *
39
+ * `undefined` — nothing stamped `ENVIRONMENT` — is not `dev`, which is `compositionEnvironment`'s own
40
+ * rule and the right one here too: a deployment whose `wrangler.jsonc` lost the var must not start
41
+ * trusting whatever host a request claims to have arrived at.
42
+ */
43
+ /** The one environment whose base URL is derived from the request rather than read from config. */
44
+ const DERIVED_ENVIRONMENT = "dev";
45
+ /**
46
+ * The scheme every `dev` composition serves on.
47
+ *
48
+ * Not a default and not a guess: Pithy runs no TLS locally, so there is no second possibility to choose
49
+ * between. It is exported because the dev-session seed needs it to name the cookie it writes, and that
50
+ * agreement is the whole invariant.
51
+ */
52
+ const DEV_PROTOCOL = "http:";
53
+ /** Better Auth's session cookie, before any prefix — `<cookiePrefix>.session_token`, prefix unchanged. */
54
+ const SESSION_COOKIE = "better-auth.session_token";
55
+ /**
56
+ * The base URL a `dev` composition resolves for a request that arrived at `host`.
57
+ *
58
+ * `host`, not `hostname`: the port is the whole point, and it is the part of a dev address that nobody
59
+ * can know before the run allocates it.
60
+ */
61
+ function devBaseURL(host) {
62
+ return `${DEV_PROTOCOL}//${host}`;
63
+ }
64
+ /**
65
+ * A base URL's scheme, or `""` for a string that is not a URL at all.
66
+ *
67
+ * Tolerant rather than throwing, for the same reason the CSRF gate's `originOf` is: `baseURL` is a
68
+ * `z.string()` an adopter writes by hand, and a malformed one must fail as "no `__Secure-` prefix" —
69
+ * matching what Better Auth itself does with it — not as a 500 on every request.
70
+ */
71
+ function baseURLProtocol(baseURL) {
72
+ try {
73
+ return new URL(baseURL).protocol;
74
+ } catch {
75
+ return "";
76
+ }
77
+ }
78
+ /**
79
+ * Better Auth's session cookie name for a base URL served over `protocol`.
80
+ *
81
+ * Our mirror of a rule that lives in Better Auth: it adds the `__Secure-` prefix when the base URL is
82
+ * HTTPS. Mirrored because the seed has to name the cookie before any instance exists, and pinned to the
83
+ * running version by a test that reads the name off a live instance — so an upgrade that changed the
84
+ * rule fails there rather than in a browser.
85
+ */
86
+ function sessionCookieName(protocol) {
87
+ return protocol === "https:" ? `__Secure-${SESSION_COOKIE}` : SESSION_COOKIE;
88
+ }
89
+ /**
90
+ * Build this composition's base-URL resolver. The environment is read once, here, and nowhere else in
91
+ * this seam.
92
+ */
93
+ function baseURLResolver(configured, env = ambientEnv()) {
94
+ if (compositionEnvironment(env) !== DERIVED_ENVIRONMENT) return () => configured;
95
+ return (request) => devBaseURL(new URL(request.url).host);
96
+ }
97
+ //#endregion
98
+ export { DEV_PROTOCOL, baseURLProtocol, baseURLResolver, devBaseURL, sessionCookieName };
@@ -0,0 +1,20 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { PithyMiddleware } from "@pithy-sh/core/src/capability/capability";
4
+ import { type AmbientEnv } from "@pithy-sh/core/src/env/ambient";
5
+ import type { AuthWiring } from "../capability";
6
+ /**
7
+ * Publish the bound gate on every request, as capability middleware.
8
+ *
9
+ * The configured origin set is built once at composition: it is resolved config, and re-deriving it on
10
+ * the hot path is work that can only ever produce the same answer — or a different one, which is the
11
+ * bug. The composition's *own* origin is the one part that is not config, and only in `dev`: it is the
12
+ * address this run was assigned, which no config file can hold. So the resolver is built here, at
13
+ * composition, with the environment gate inside it ({@link baseURLResolver}), and the gate it hands
14
+ * back is a constant everywhere but `dev`.
15
+ *
16
+ * Registered on `*` rather than under `basePath`, because the routes that most need it are the
17
+ * adopter's, and those are anywhere.
18
+ */
19
+ export declare function publishSameOrigin(wiring: AuthWiring, env?: AmbientEnv): PithyMiddleware;
20
+ //# sourceMappingURL=csrf.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"csrf.d.ts","sourceRoot":"","sources":["../../src/http/csrf.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,0CAA0C,CAAC;AAChF,OAAO,EAAE,KAAK,UAAU,EAAc,MAAM,gCAAgC,CAAC;AAG7E,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAkEhD;;;;;;;;;;;;GAYG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,UAAU,EAAE,GAAG,GAAE,UAAyB,GAAG,eAAe,CAWrG"}
@@ -0,0 +1,83 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { baseURLResolver } from "./baseUrl.js";
4
+ import { ForbiddenError } from "@pithy-sh/core/src/error/pithyError";
5
+ import { ambientEnv } from "@pithy-sh/core/src/env/ambient";
6
+ //#region src/http/csrf.ts
7
+ /**
8
+ * CSRF origin guard for every state-changing route in the Worker — Pithy's own (token rotation, device
9
+ * revoke) and the adopter's alike.
10
+ *
11
+ * Better Auth applies this check to its own endpoints; routes in front of the catch-all must enforce
12
+ * it themselves to honor principle 2 ("cookie/session mode ⇒ CSRF on"). Bearer requests carry no
13
+ * ambient credential, so they are CSRF-exempt and pass through. A cookie-authenticated request must
14
+ * present an `Origin` (or `Referer`) matching an allowed origin.
15
+ *
16
+ * ## Nothing here takes an origin list
17
+ *
18
+ * The gate used to be built by whoever needed it, from origins they passed in. Auth's own routes had
19
+ * the resolved ones; an adopter's routes did not — the `routes` hook receives only the Hono app — so
20
+ * the adopter wrote the check again from the request and hoped the two agreed. One Worker, two
21
+ * same-origin implementations, free to drift, and the weaker one is the real policy.
22
+ *
23
+ * Now the capability publishes the gate **already bound** to the origins it resolved, and core's
24
+ * `requireSameOrigin()` takes no argument. There is no list to pass, so there is no wrong list to
25
+ * pass — and no second implementation to keep in step.
26
+ */
27
+ function originOf(value) {
28
+ if (!value) return null;
29
+ try {
30
+ return new URL(value).origin;
31
+ } catch {
32
+ return null;
33
+ }
34
+ }
35
+ /** The origins a cookie-authenticated mutating request may come from: the base URL plus trustedOrigins. */
36
+ function allowedOrigins(baseURL, trustedOrigins) {
37
+ const origins = new Set(trustedOrigins);
38
+ const base = originOf(baseURL);
39
+ if (base) origins.add(base);
40
+ return [...origins];
41
+ }
42
+ /** The decision itself, closed over the one resolved origin set. Never exported: see the module doc. */
43
+ function sameOriginGate(allowedOrigins, resolveBaseURL) {
44
+ const allowed = new Set(allowedOrigins);
45
+ return async (c, next) => {
46
+ if (c.req.raw.headers.has("authorization")) {
47
+ await next();
48
+ return;
49
+ }
50
+ const origin = c.req.raw.headers.get("origin") ?? originOf(c.req.raw.headers.get("referer"));
51
+ const own = originOf(resolveBaseURL(c.req.raw));
52
+ if (!origin || origin !== own && !allowed.has(origin)) throw new ForbiddenError({
53
+ message: "Cross-origin request rejected.",
54
+ action: "Send the request from an allowed origin, or use a bearer token.",
55
+ detail: `origin ${origin ?? "(none)"} is not in trustedOrigins`
56
+ });
57
+ await next();
58
+ };
59
+ }
60
+ /**
61
+ * Publish the bound gate on every request, as capability middleware.
62
+ *
63
+ * The configured origin set is built once at composition: it is resolved config, and re-deriving it on
64
+ * the hot path is work that can only ever produce the same answer — or a different one, which is the
65
+ * bug. The composition's *own* origin is the one part that is not config, and only in `dev`: it is the
66
+ * address this run was assigned, which no config file can hold. So the resolver is built here, at
67
+ * composition, with the environment gate inside it ({@link baseURLResolver}), and the gate it hands
68
+ * back is a constant everywhere but `dev`.
69
+ *
70
+ * Registered on `*` rather than under `basePath`, because the routes that most need it are the
71
+ * adopter's, and those are anywhere.
72
+ */
73
+ function publishSameOrigin(wiring, env = ambientEnv()) {
74
+ const gate = sameOriginGate(allowedOrigins(wiring.config.baseURL, wiring.config.trustedOrigins), baseURLResolver(wiring.config.baseURL, env));
75
+ return (app) => {
76
+ app.use("*", async (c, next) => {
77
+ c.set("sameOrigin", gate);
78
+ await next();
79
+ });
80
+ };
81
+ }
82
+ //#endregion
83
+ export { publishSameOrigin };
@@ -0,0 +1,44 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
4
+ import { type AmbientEnv } from "@pithy-sh/core/src/env/ambient";
5
+ import type { Hono } from "hono";
6
+ import type { AuthWiring } from "../capability";
7
+ /**
8
+ * `GET /__pithy/dev-login` — the seeded session, as a redirect that signs the browser in.
9
+ *
10
+ * The seed already mints a real session row and a real signed cookie. What was missing was a way to
11
+ * *hand it to a browser*: the artifact is a file, and the only route to a browser from a file was the
12
+ * terminal — `document.cookie = "…"`, printed on the ready banner, pasted into a console. That line put
13
+ * a live session token in the one place a credential must never be, which is a place people read, copy,
14
+ * screenshot, and tee into a log. A URL carries the same credential to the same browser without it ever
15
+ * being rendered as text.
16
+ *
17
+ * ## The two gates, and why they are two statements
18
+ *
19
+ * This route mints an authenticated session with **no credential presented**. That is the entire risk of
20
+ * the feature, so it is refused twice, independently:
21
+ *
22
+ * 1. The composition's environment is not `dev`.
23
+ * 2. `CI` is set to any non-blank value — even in a `dev` composition.
24
+ *
25
+ * Neither implies the other. CI runs `dev` compositions constantly (integration suites, packaging
26
+ * checks, `pithy dev` itself), and a developer's laptop is not CI, so "not `dev`" does not cover CI and
27
+ * "not CI" does not cover production. Written as one `||` the pair reads like a single condition, and a
28
+ * single condition is one edit from an `&&` — with a session-minting endpoint answering as the failure
29
+ * mode, silently. Two `if`s, two comments, two tests.
30
+ *
31
+ * ## And the gates are at registration
32
+ *
33
+ * Not inside the handler. A route that exists and refuses is one refactor away from a route that exists
34
+ * and does not, and it is visible in the route table of a production Worker, where its presence alone is
35
+ * a finding. The assertion the tests make is therefore about what a composition *mounts*.
36
+ *
37
+ * **What the CI gate can and cannot see.** In a Worker, `process.env` is the script's bindings and
38
+ * nothing else — the shell's `CI` does not cross into workerd. `pithy dev` forwards it as a var for
39
+ * exactly this reason, so the read is truthful for every Worker Pithy starts; a Worker started some
40
+ * other way in CI is covered only by the environment gate. That is why there are two, and why the
41
+ * second is the one that needs no cooperation.
42
+ */
43
+ export declare function registerDevLoginRoute(wiring: AuthWiring, env?: AmbientEnv): (app: Hono<PithyHonoEnv>) => void;
44
+ //# sourceMappingURL=devLoginRoute.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"devLoginRoute.d.ts","sourceRoot":"","sources":["../../src/http/devLoginRoute.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAE7E,OAAO,EAAE,KAAK,UAAU,EAAsC,MAAM,gCAAgC,CAAC;AAKrG,OAAO,KAAK,EAAW,IAAI,EAAE,MAAM,MAAM,CAAC;AAE1C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAWhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,UAAU,EAClB,GAAG,GAAE,UAAyB,GAC7B,CAAC,GAAG,EAAE,IAAI,CAAC,YAAY,CAAC,KAAK,IAAI,CAQnC"}