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