@pithy-sh/auth 0.5.0 → 0.6.1

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.
@@ -1,6 +1,5 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
- import { Session } from "../data/betterAuth.js";
4
3
  import { DEV_PROTOCOL, sessionCookieName } from "../http/baseUrl.js";
5
4
  import { AUTH_SESSION_SECRET } from "../instance/secrets.js";
6
5
  import { ValidationError, fromZodError } from "@pithy-sh/core/src/error/pithyError";
@@ -8,7 +7,7 @@ import { z } from "zod";
8
7
  import { DEV_LOGIN_FILE, DevLogin } from "@pithy-sh/core/src/seed/devLogin";
9
8
  import { normalizeAddress } from "@pithy-sh/core/src/address/address";
10
9
  import { MAX_SEED_ORDER } from "@pithy-sh/core/src/seed/compose";
11
- import { d1SeedGroup, defineSeed } from "@pithy-sh/core/src/seed/seed";
10
+ import { defineSeed } from "@pithy-sh/core/src/seed/seed";
12
11
  //#region src/seeds/devSession.ts
13
12
  /**
14
13
  * The dev-login seed set: a real, signed-in session for one seeded user, so local development does not
@@ -60,18 +59,12 @@ const USERS_TABLE = "pithyAuthUsers";
60
59
  */
61
60
  const DEV_SESSION_COOKIE_NAME = sessionCookieName(DEV_PROTOCOL);
62
61
  /**
63
- * The prefix every seeded dev session's id and token carry.
62
+ * How long a dev login stays usable. Long, because reseeding to restore one is the friction this removes.
64
63
  *
65
- * It is what makes a dev session **findable without being told**, which is what the dev-login route
66
- * needs: the route reads the session out of D1 and has no artifact to consult (a Worker has no
67
- * filesystem). And it is what makes one identifiable at all — a `pithy_auth_sessions` row minted by a
68
- * seed is otherwise indistinguishable from one a real sign-in created.
64
+ * It bounds the *claim*, not a session — `#572`. The session the route mints from it lives by the auth
65
+ * config's own `sessionExpiresIn`, exactly as a real sign-in does, because it *is* one.
69
66
  */
70
- const DEV_SESSION_TOKEN_PREFIX = "dev-session-";
71
- /** How long a seeded session lives. Long, because reseeding to restore a dev login is the friction this removes. */
72
- const DEV_SESSION_LIFETIME_MS = 31536e6;
73
- /** Bytes of the secret digest kept as the token's fingerprint — enough to separate secrets, short enough to read. */
74
- const FINGERPRINT_BYTES = 4;
67
+ const DEV_LOGIN_LIFETIME_MS = 31536e6;
75
68
  /** The developer's machine-local preferences for this project, read from `~/.config/pithy/<project>/dev.json`. */
76
69
  const DevPreferences = z.object({ user: z.string().describe("The email of the seeded user to sign in as. Must be a user this seed run creates, or the seed fails rather than signing in as nobody.") }).describe("A developer's machine-local dev preferences, from the Pithy config directory (`~/.config/pithy/<project>/dev.json`, or `%APPDATA%\\pithy\\<project>\\dev.json` on Windows) — outside the repo, so opting in needs no commit.");
77
70
  /**
@@ -104,51 +97,117 @@ async function signCookieValue(value, secret) {
104
97
  return encodeURIComponent(`${value}.${base64}`);
105
98
  }
106
99
  /**
107
- * A short, stable fingerprint of the auth secret.
100
+ * Sign a claim naming the user a dev login signs in as — `#572`.
108
101
  *
109
- * Putting it in the session token makes the token deterministic across reseeds — the same cookie keeps
110
- * working in every worktree once each is seeded, which is the whole point — while rotating the secret
111
- * changes the token *and* invalidates every cookie signed with the old one, for free. A truncated digest,
112
- * never the secret: the token is written to a file and read back by tooling.
102
+ * **The payload is base64 of JSON, not a delimited string.** A user id is an adopter's to choose and may
103
+ * hold any character at all, including whichever one a hand-rolled format picked as its separator. JSON
104
+ * inside base64 has no separator to collide with, and the whole of it is what the signature covers.
105
+ *
106
+ * The same HMAC-SHA-256 construction {@link signCookieValue} uses, deliberately not the same function:
107
+ * that one mirrors better-call's cookie format because Better Auth has to accept its output, and this is
108
+ * ours. Two consumers, two formats, no shared spelling to break one by fixing the other.
113
109
  */
114
- async function secretFingerprint(secret) {
115
- const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(secret));
116
- return Array.from(new Uint8Array(digest).slice(0, FINGERPRINT_BYTES)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
110
+ async function signDevLoginClaim(input) {
111
+ const body = base64Of(new TextEncoder().encode(JSON.stringify({
112
+ u: input.user.id,
113
+ e: input.expiresAt.getTime()
114
+ })));
115
+ const key = await claimKey(input.secret, ["sign"]);
116
+ const signature = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(body));
117
+ return encodeURIComponent(`${body}.${base64Of(signature)}`);
117
118
  }
118
119
  /**
119
- * Mint one deterministic dev session: the `pithy_auth_sessions` row and the signed cookie for it.
120
+ * What a claim says, once it has been proved to say it.
120
121
  *
121
- * The row id carries the fingerprint too, not just the token. Seed writes are `INSERT OR IGNORE`, so an
122
- * id that ignored a rotation would keep the stale token alive under a row the next run refuses to replace.
122
+ * `null` for every failure and never a reason: a malformed claim, one signed by another secret, and one
123
+ * naming a user who has since gone are the same answer to whoever presented it, because distinguishing
124
+ * them is a probe. The route turns all three into the one 404 it already had.
123
125
  */
124
- async function mintDevSession(input) {
125
- const now = input.now ?? /* @__PURE__ */ new Date();
126
- const expiresAt = new Date(now.getTime() + DEV_SESSION_LIFETIME_MS);
127
- const fingerprint = await secretFingerprint(input.secret);
128
- const token = `${DEV_SESSION_TOKEN_PREFIX}${input.user.id}-${fingerprint}`;
126
+ async function verifyDevLoginClaim(claim, secret, now = /* @__PURE__ */ new Date()) {
127
+ const raw = safeDecode(claim);
128
+ if (raw === null) return null;
129
+ const cut = raw.lastIndexOf(".");
130
+ if (cut <= 0) return null;
131
+ const body = raw.slice(0, cut);
132
+ const signature = safeBytes(raw.slice(cut + 1));
133
+ if (signature === null) return null;
134
+ const key = await claimKey(secret, ["verify"]);
135
+ if (!await crypto.subtle.verify("HMAC", key, signature, new TextEncoder().encode(body))) return null;
136
+ const decoded = safeJson(body);
137
+ const parsed = DevLoginClaim.safeParse(decoded);
138
+ if (!parsed.success) return null;
139
+ const expiresAt = new Date(parsed.data.e);
140
+ if (expiresAt.getTime() <= now.getTime()) return null;
129
141
  return {
130
- session: {
131
- id: token,
132
- token,
133
- userId: input.user.id,
134
- expiresAt,
135
- createdAt: now,
136
- updatedAt: now,
137
- ipAddress: "127.0.0.1",
138
- userAgent: "pithy seed (dev login)",
139
- deviceId: null,
140
- familyId: null,
141
- authenticatedAt: now
142
- },
143
- login: {
144
- email: input.user.email,
145
- userId: input.user.id,
146
- cookieName: DEV_SESSION_COOKIE_NAME,
147
- cookieValue: await signCookieValue(token, input.secret),
148
- expiresAt
149
- }
142
+ userId: parsed.data.u,
143
+ expiresAt
150
144
  };
151
145
  }
146
+ /** The claim's payload, as it is signed. Two letters, because it is written into a URL a person may see. */
147
+ const DevLoginClaim = z.object({
148
+ u: z.string().min(1).describe("The user id the route mints a session for."),
149
+ e: z.number().int().positive().describe("When the claim stops being accepted, in ms since the epoch.")
150
+ }).describe("What a dev-login claim asserts: which seeded user, and until when.");
151
+ /** The HMAC key for a claim. Imported per call — a key object is not something to cache across requests. */
152
+ function claimKey(secret, usages) {
153
+ return crypto.subtle.importKey("raw", new TextEncoder().encode(secret), {
154
+ name: "HMAC",
155
+ hash: "SHA-256"
156
+ }, false, [...usages]);
157
+ }
158
+ /** Base64 of bytes — a signature, or a UTF-8 payload. */
159
+ function base64Of(bytes) {
160
+ return btoa(String.fromCharCode(...new Uint8Array(bytes)));
161
+ }
162
+ /** `decodeURIComponent`, or null. A malformed escape throws, and a throw here is just "not a claim". */
163
+ function safeDecode(value) {
164
+ try {
165
+ return decodeURIComponent(value);
166
+ } catch {
167
+ return null;
168
+ }
169
+ }
170
+ /** Base64 to bytes, or null. Same reason: unparseable input is not an error, it is a refusal. */
171
+ function safeBytes(value) {
172
+ try {
173
+ return Uint8Array.from(atob(value), (character) => character.charCodeAt(0));
174
+ } catch {
175
+ return null;
176
+ }
177
+ }
178
+ /** Base64 UTF-8 JSON to a value, or null. Decoded as bytes, to match how {@link base64Of} wrote it. */
179
+ function safeJson(body) {
180
+ try {
181
+ const bytes = Uint8Array.from(atob(body), (character) => character.charCodeAt(0));
182
+ return JSON.parse(new TextDecoder().decode(bytes));
183
+ } catch {
184
+ return null;
185
+ }
186
+ }
187
+ /**
188
+ * Mint one dev login: the signed claim, and the artifact that carries it.
189
+ *
190
+ * **No `pithy_auth_sessions` row — `#572`.** This used to write one and hand it over on every open, which
191
+ * meant the product's own sign-out revoked the dev login along with the session, and the only way back was
192
+ * a reseed. It also meant a row in that table which was, by this module's own admission, indistinguishable
193
+ * from a real sign-in — so it showed up in every surface built over sessions as a device nobody used.
194
+ *
195
+ * What is minted here is a claim about *who*. The route exchanges it for a session at the moment somebody
196
+ * opens the link, so the session is real, is theirs, and is the only thing a sign-out takes away.
197
+ */
198
+ async function mintDevLogin(input) {
199
+ const now = input.now ?? /* @__PURE__ */ new Date();
200
+ const expiresAt = new Date(now.getTime() + DEV_LOGIN_LIFETIME_MS);
201
+ return { login: {
202
+ email: input.user.email,
203
+ userId: input.user.id,
204
+ claim: await signDevLoginClaim({
205
+ ...input,
206
+ expiresAt
207
+ }),
208
+ expiresAt
209
+ } };
210
+ }
152
211
  /**
153
212
  * The users this run creates, whichever set contributes them.
154
213
  *
@@ -197,18 +256,15 @@ const authDevSessionSeed = defineSeed({
197
256
  message: "Cannot mint a dev session without this environment's auth secret.",
198
257
  action: `Add ${AUTH_SESSION_SECRET} to this project's dev secrets file — pithy doctor prints its path — then seed again.`
199
258
  });
200
- const minted = await mintDevSession({
259
+ const minted = await mintDevLogin({
201
260
  user,
202
261
  secret
203
262
  });
204
- return {
205
- d1: [d1SeedGroup("app", "pithyAuthSessions", Session, [minted.session])],
206
- artifacts: [{
207
- file: DEV_LOGIN_FILE,
208
- contents: `${JSON.stringify(DevLogin.encode(minted.login), null, 2)}\n`
209
- }]
210
- };
263
+ return { artifacts: [{
264
+ file: DEV_LOGIN_FILE,
265
+ contents: `${JSON.stringify(DevLogin.encode(minted.login), null, 2)}\n`
266
+ }] };
211
267
  }
212
268
  });
213
269
  //#endregion
214
- export { AUTH_DEV_SESSION_SEED_ORDER, DEV_SESSION_COOKIE_NAME, DEV_SESSION_TOKEN_PREFIX, DevPreferences, SeededUser, authDevSessionSeed, mintDevSession, secretFingerprint, signCookieValue };
270
+ export { AUTH_DEV_SESSION_SEED_ORDER, DEV_SESSION_COOKIE_NAME, DevPreferences, SeededUser, authDevSessionSeed, mintDevLogin, signCookieValue, signDevLoginClaim, verifyDevLoginClaim };
@@ -3,5 +3,5 @@
3
3
  /** This package's npm name — the join key against a release feed. */
4
4
  export declare const PACKAGE_NAME = "@pithy-sh/auth";
5
5
  /** This package's version, stamped from its own package.json at generation time. */
6
- export declare const PACKAGE_VERSION = "0.5.0";
6
+ export declare const PACKAGE_VERSION = "0.6.1";
7
7
  //# sourceMappingURL=version.generated.d.ts.map
@@ -4,6 +4,6 @@
4
4
  /** This package's npm name — the join key against a release feed. */
5
5
  const PACKAGE_NAME = "@pithy-sh/auth";
6
6
  /** This package's version, stamped from its own package.json at generation time. */
7
- const PACKAGE_VERSION = "0.5.0";
7
+ const PACKAGE_VERSION = "0.6.1";
8
8
  //#endregion
9
9
  export { PACKAGE_NAME, PACKAGE_VERSION };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pithy-sh/auth",
3
- "version": "0.5.0",
3
+ "version": "0.6.1",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -42,10 +42,10 @@
42
42
  "better-auth": "^1.7.1"
43
43
  },
44
44
  "peerDependencies": {
45
- "@pithy-sh/core": "^0.5.0",
46
- "@pithy-sh/email": "^0.3.1",
47
- "@pithy-sh/secrets": "^0.2.1",
48
- "@pithy-sh/turnstile": "^0.2.1",
45
+ "@pithy-sh/core": "^0.6.1",
46
+ "@pithy-sh/email": "^0.3.3",
47
+ "@pithy-sh/secrets": "^0.2.3",
48
+ "@pithy-sh/turnstile": "^0.2.3",
49
49
  "hono": "^4.13.2",
50
50
  "kysely": "^0.29.0",
51
51
  "zod": "^4.4.0"
package/src/capability.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
+ import type { D1Database } from "@cloudflare/workers-types";
4
5
  import type { Capability, PithyMiddleware } from "@pithy-sh/core/src/capability/capability";
5
6
  import { defineCapability } from "@pithy-sh/core/src/capability/capability";
6
7
  import { ValidationError } from "@pithy-sh/core/src/error/pithyError";
@@ -140,8 +141,25 @@ export interface AuthWiring {
140
141
  enqueueEmail: EmailCapability["enqueue"] | undefined;
141
142
  /** The turnstile login gate, when the turnstile capability is composed. Set by `compose`. */
142
143
  turnstile: { mode: TurnstileMode } | undefined;
144
+ /**
145
+ * The adopter's session-revoked listener, or absent. See {@link AuthOptions.onSessionRevoked}.
146
+ *
147
+ * Optional on the wiring rather than required-and-undefined, because a composition without a listener
148
+ * is the ordinary case and every harness that builds this shape by hand would otherwise have to say so.
149
+ */
150
+ onSessionRevoked?: SessionRevokedListener | undefined;
143
151
  }
144
152
 
153
+ /**
154
+ * Called when a session row is deleted — a sign-out, a revoke, an admin ending somebody's devices.
155
+ *
156
+ * **Handed this request's D1 binding**, because the auth instance is built per request and the listener
157
+ * almost certainly wants to write to the same database under a different capability's view of it. Taking
158
+ * the binding rather than a typed database keeps this seam out of the business of knowing whose tables
159
+ * the listener is about to touch.
160
+ */
161
+ export type SessionRevokedListener = (session: { id: string; userId: string }, d1: D1Database) => Promise<void>;
162
+
145
163
  /**
146
164
  * What `auth()` takes: the config, plus the seams that are **behavior rather than data**.
147
165
  *
@@ -166,6 +184,22 @@ export type AuthOptions = AuthConfigInput & {
166
184
  * real per-address flag, always.
167
185
  */
168
186
  resolveGithubUserInfo?: GithubUserInfoResolver;
187
+ /**
188
+ * Told when a session is revoked, so state another capability keyed on it can go with it.
189
+ *
190
+ * **On the row, not on the sign-out route.** A sign-out, a revoke and an admin ending somebody's
191
+ * devices all delete the same row, so a listener hung off one endpoint would miss the others.
192
+ *
193
+ * The case this exists for is `@pithy-sh/organization`: its acting selection is keyed by session id
194
+ * and its schema says signing out must take it with it. Tenancy depends on auth and not the reverse,
195
+ * so the composition holding both is what joins them, and this is the join.
196
+ *
197
+ * **Non-fatal by contract.** The session is already gone when this runs; a failure here must not turn
198
+ * a completed sign-out into an error the caller retries, so the instance swallows what it throws.
199
+ *
200
+ * A function, so it is destructured off before `AuthConfig.parse` for the reason above.
201
+ */
202
+ onSessionRevoked?: SessionRevokedListener;
169
203
  };
170
204
 
171
205
  /** The auth capability, with its resolved config attached for inspection. */
@@ -215,7 +249,7 @@ export function auth(options: AuthOptions): AuthCapability {
215
249
  // Zod 4 objects strip unknown keys silently, so a `resolveGithubUserInfo` handed to `AuthConfig.parse`
216
250
  // would vanish with no error and the adopter's override would simply never run. `payments()` splits
217
251
  // its `resolveSubject` out for the same reason.
218
- const { resolveGithubUserInfo, ...config } = options;
252
+ const { resolveGithubUserInfo, onSessionRevoked, ...config } = options;
219
253
  const resolved = AuthConfig.parse(config);
220
254
  // Additivity, before anything is built from the list. The four the kit composes are the sign-in this
221
255
  // product promises and what the control-plane seam verifies against, so a list naming one of them is
@@ -229,6 +263,7 @@ export function auth(options: AuthOptions): AuthCapability {
229
263
  resolveGithubUserInfo,
230
264
  enqueueEmail: undefined,
231
265
  turnstile: undefined,
266
+ onSessionRevoked,
232
267
  };
233
268
 
234
269
  // Tier-1 edge rate limiter, contributed as middleware so it runs before session resolution.
@@ -37,7 +37,12 @@ export const User = z
37
37
  emailVerified: SQLiteBoolean.describe(
38
38
  "Whether the email has been verified. Stored as `0|1`; magic-link/OTP sign-in sets it true.",
39
39
  ),
40
- image: z.string().nullable().describe("URL of the user's avatar from a social profile, or null."),
40
+ image: z
41
+ .string()
42
+ .nullable()
43
+ .describe(
44
+ "The user's picture: a URL on the provider that signed them in, or bytes this application stores as a bounded `data:` URL — see `../profile/profile.ts` for why the column takes two shapes. Null when nobody has set one, and then a caller draws initials, which is a real answer and not a placeholder.\n\n**Permissive here and strict on the write, exactly as `name` is, and the asymmetry is the point.** `UserImage` runs at the database hook, so nothing this kit writes can put an unacceptable value in the column. What this schema decodes is what is *already there* — a row a provider wrote before the rule existed, a repair script, a restored backup. A strict column turns one such row into a `ZodError` on every read that touches it, and `getUsers` parses a page of rows at once: one poisoned row would take down the whole roster for every operator rather than drawing one gap. That is the failure mode `./kitFields.ts` records for `locale`, and it is worse here, because a roster is read by people who did not write the row.\n\nThe value is made safe on the way **out** instead. `userImageSource` answers null for anything the rule does not recognize, so an unrecognized value renders as initials; and the serving route refuses to hand out bytes it cannot type.",
45
+ ),
41
46
  locale: Locale.nullable().describe(
42
47
  "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.",
43
48
  ),
@@ -1,24 +1,21 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
+ import { zValidator } from "@hono/zod-validator";
4
5
  import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
5
- import { JsonDate } from "@pithy-sh/core/src/data/codecs";
6
6
  import { type AmbientEnv, ambientEnv, compositionEnvironment } from "@pithy-sh/core/src/env/ambient";
7
7
  import { isContinuousIntegration } from "@pithy-sh/core/src/env/ci";
8
- import { fromZodError, NotFoundError } from "@pithy-sh/core/src/error/pithyError";
9
- import { DEV_LOGIN_ROUTE } from "@pithy-sh/core/src/seed/devLogin";
8
+ import { NotFoundError } from "@pithy-sh/core/src/error/pithyError";
9
+ import { validationHook } from "@pithy-sh/core/src/http/validation";
10
+ import { DEV_LOGIN_CLAIM_PARAM, DEV_LOGIN_ROUTE } from "@pithy-sh/core/src/seed/devLogin";
10
11
  import type { SecretsStoreEnv } from "@pithy-sh/secrets/src/env/bindings";
11
12
  import type { Context, Hono } from "hono";
12
13
  import { z } from "zod";
13
14
  import type { AuthWiring } from "../capability";
15
+ import { Session } from "../data/betterAuth";
14
16
  import { authDatabase } from "../data/tables";
15
17
  import { resolveSessionSecret } from "../instance/secrets";
16
- import {
17
- DEV_SESSION_COOKIE_NAME,
18
- DEV_SESSION_TOKEN_PREFIX,
19
- secretFingerprint,
20
- signCookieValue,
21
- } from "../seeds/devSession";
18
+ import { DEV_SESSION_COOKIE_NAME, signCookieValue, verifyDevLoginClaim } from "../seeds/devSession";
22
19
  import { resolveDb } from "./resolve";
23
20
 
24
21
  /**
@@ -66,30 +63,14 @@ export function registerDevLoginRoute(
66
63
  if (compositionEnvironment(env) !== "dev") return;
67
64
  // Gate two: continuous integration, independently. A `dev` composition in CI gets no route either.
68
65
  if (isContinuousIntegration(env)) return;
69
- app.get(DEV_LOGIN_ROUTE, (c) => serveDevLogin(c, wiring));
66
+ // The claim is read here rather than inside the handler: `c.req.valid` is typed off the chain it was
67
+ // declared on, and a handler taking a bare `Context` has no validator to read from.
68
+ app.get(DEV_LOGIN_ROUTE, zValidator("query", DevLoginQuery, validationHook), (c) =>
69
+ serveDevLogin(c, wiring, c.req.valid("query")[DEV_LOGIN_CLAIM_PARAM]),
70
+ );
70
71
  };
71
72
  }
72
73
 
73
- /**
74
- * The seeded session row, narrowed to what handing it to a browser needs — and validated, because a D1
75
- * row is a boundary like any other. `z.input` is the stored row (ISO-8601 text); `z.output` the app shape.
76
- */
77
- const DevSessionRow = z
78
- .object({
79
- token: z
80
- .string()
81
- .min(1)
82
- .describe("The seeded session's opaque token — signed with this environment's secret to make the cookie."),
83
- expiresAt: JsonDate.describe("When the seeded session expires. ISO-8601 text in SQLite; a `Date` here."),
84
- })
85
- .describe("A seeded dev session, narrowed to the two columns the dev-login redirect needs.");
86
- type DevSessionRow = z.output<typeof DevSessionRow>;
87
-
88
- /** How long the browser is told to keep the cookie: whatever is left of the seeded session, never longer. */
89
- function maxAgeSeconds(expiresAt: Date, now: Date): number {
90
- return Math.floor((expiresAt.getTime() - now.getTime()) / 1000);
91
- }
92
-
93
74
  /**
94
75
  * The refusal when there is nothing to sign in as. A 404, because the honest answer is that this
95
76
  * composition has no seeded session — not that the caller got something wrong.
@@ -110,48 +91,92 @@ function noSeededSession(): NotFoundError {
110
91
  }
111
92
 
112
93
  /**
113
- * Serve the seeded session as a `Set-Cookie` and a redirect to `/`.
94
+ * What the route takes: the claim, in the query.
95
+ *
96
+ * **Optional, and that is deliberate.** A required field would make a missing claim a 400 and a wrong one
97
+ * a 404, and the difference between those two answers is exactly what this route must not tell anybody.
98
+ * Declaring it optional puts every refusal in the handler, where there is one of them.
114
99
  *
115
- * The row is found by the prefix every seeded session carries and **verified against the current
116
- * signing secret's fingerprint**, which the seed puts in the token for this exact purpose. A session
117
- * minted before a rotation is a cookie Better Auth will reject, so handing it over would sign nobody in
118
- * and send the developer hunting through auth for a bug that is a stale seed. Unfound is unfound.
100
+ * Bounded because an unbounded query parameter is an unbounded read. The ceiling is far above any claim
101
+ * this seed mints; a value past it is refused for its length, which tells the sender only about the
102
+ * request they just made.
103
+ */
104
+ const DevLoginQuery = z
105
+ .object({
106
+ [DEV_LOGIN_CLAIM_PARAM]: z
107
+ .string()
108
+ .max(4096)
109
+ .optional()
110
+ .describe("The signed claim naming the user to sign in as, as `pithy seed` wrote it into the URL."),
111
+ })
112
+ .describe("The dev-login route's query: a claim, or nothing and the same refusal as a wrong one.");
113
+
114
+ /**
115
+ * Exchange a claim for a session, as a `Set-Cookie` and a redirect to `/`.
119
116
  *
120
117
  * Nothing about the cookie is logged, and nothing is written to a response body: the value exists in
121
- * this handler and in the browser, and in no third place.
118
+ * this handler and in the browser, and in no third place. The claim that bought it is in the URL, which
119
+ * is the one place it has to be — `dev/devLogin.ts` in the CLI carries why, and keeps it out of every
120
+ * printed line it can.
122
121
  */
123
- async function serveDevLogin(c: Context<PithyHonoEnv>, wiring: AuthWiring): Promise<Response> {
122
+ async function serveDevLogin(
123
+ c: Context<PithyHonoEnv>,
124
+ wiring: AuthWiring,
125
+ presented: string | undefined,
126
+ ): Promise<Response> {
127
+ if (!presented) throw noSeededSession();
128
+
124
129
  const secret = await resolveSessionSecret(c.env as unknown as SecretsStoreEnv);
125
- const fingerprint = await secretFingerprint(secret);
130
+ const now = new Date();
131
+ // One answer for malformed, for signed-by-another-secret, and for expired. Telling them apart would
132
+ // make this route a probe against the running secret.
133
+ const claim = await verifyDevLoginClaim(presented, secret, now);
134
+ if (!claim) throw noSeededSession();
126
135
 
127
136
  const db = authDatabase(resolveDb(c.env, wiring.config.database));
128
- const found = await db
129
- .selectFrom("pithyAuthSessions")
130
- .select(["token", "expiresAt"])
131
- .where("token", "like", `${DEV_SESSION_TOKEN_PREFIX}%-${fingerprint}`)
132
- .orderBy("createdAt", "desc")
133
- .limit(1)
134
- .executeTakeFirst();
135
- if (!found) throw noSeededSession();
137
+ // The user is proved to exist rather than assumed from the claim. A claim outliving the seed that
138
+ // named it — a reseed with a different `dev.json`, a user removed — must not mint a session pointing
139
+ // at nobody, which `get-session` would answer `null` for while the cookie looked like a way in.
140
+ const user = await db.selectFrom("pithyAuthUsers").select("id").where("id", "=", claim.userId).executeTakeFirst();
141
+ if (!user) throw noSeededSession();
142
+
143
+ /*
144
+ A real session, minted now — `#572`.
136
145
 
137
- const parsed = DevSessionRow.safeParse(found);
138
- if (!parsed.success) {
139
- throw fromZodError(parsed.error, {
140
- // Same reason as `noSeededSession`: this route's caller is the developer who can run the command.
141
- message: "The seeded dev session is not readable. Run pithy seed to mint a fresh one.",
142
- });
143
- }
144
- const row: DevSessionRow = parsed.data;
145
- const maxAge = maxAgeSeconds(row.expiresAt, new Date());
146
- // An expired session is worse than none: the cookie looks like a way in and fails silently in the
147
- // browser. Same answer, same action — reseeding is what fixes both.
148
- if (maxAge <= 0) throw noSeededSession();
146
+ **Random, not derived.** The token this replaced was `dev-session-<userId>-<fingerprint>`, which made
147
+ it reproducible across reseeds and made every dev sign-in the same row. This one is a session like any
148
+ other: its own id, its own token, revoked on its own when somebody signs out, and leaving the claim
149
+ that produced it untouched. Nothing about it says "seeded", because nothing about it is — a person
150
+ opened a link and a session was created, which is what sign-in means.
151
+ */
152
+ const token = crypto.randomUUID();
153
+ const expiresAt = new Date(now.getTime() + wiring.config.sessionExpiresIn * 1000);
154
+ await db
155
+ .insertInto("pithyAuthSessions")
156
+ .values(
157
+ Session.encode({
158
+ id: crypto.randomUUID(),
159
+ token,
160
+ userId: claim.userId,
161
+ expiresAt,
162
+ createdAt: now,
163
+ updatedAt: now,
164
+ ipAddress: "127.0.0.1",
165
+ userAgent: "pithy dev login",
166
+ deviceId: null,
167
+ familyId: null,
168
+ // A dev login is a real sign-in, so it is authenticated now — what the live hook stamps.
169
+ authenticatedAt: now,
170
+ }),
171
+ )
172
+ .execute();
149
173
 
150
- const value = await signCookieValue(row.token, secret);
174
+ const value = await signCookieValue(token, secret);
151
175
  // The attributes Better Auth's own session cookie carries in a `dev` composition: `HttpOnly` (a
152
176
  // session token has no business in `document.cookie`, which is also the habit this route retires),
153
177
  // `SameSite=Lax`, root path. No `Secure` — a `dev` base URL is `http://localhost`, and a `Secure`
154
178
  // cookie there is one the browser accepts and never sends back.
179
+ const maxAge = Math.floor((expiresAt.getTime() - now.getTime()) / 1000);
155
180
  const cookie = `${DEV_SESSION_COOKIE_NAME}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}`;
156
181
  // 302 to the app root rather than 200 with a page: the developer asked to be signed in, not to read a
157
182
  // confirmation, and a redirect leaves the address bar on the app instead of on this route.
@@ -111,8 +111,14 @@ async function buildAuthInstance(c: Context<PithyHonoEnv>, wiring: AuthWiring):
111
111
  resolveProvider(cfg.github.enabled, () => resolveGithubCredentials(env)),
112
112
  ]);
113
113
  const expiresMinutes = Math.max(1, Math.round(cfg.verificationExpiresIn / 60));
114
+ const d1 = resolveDb(c.env, cfg.database);
115
+ const listener = wiring.onSessionRevoked;
114
116
  return makeAuth({
115
- db: authDatabase(resolveDb(c.env, cfg.database)),
117
+ db: authDatabase(d1),
118
+ // The adopter's listener, bound to *this* request's binding. The instance is built per request, so
119
+ // there is a real binding to hand over here and nowhere earlier — `auth()` runs at compose time and
120
+ // has none.
121
+ ...(listener ? { onSessionRevoked: (session: { id: string; userId: string }) => listener(session, d1) } : {}),
116
122
  secret,
117
123
  // Never `cfg.baseURL` directly. The instance derives the session cookie's name, the OAuth callback
118
124
  // URLs, and the magic-link URL from whatever base URL it is handed, so in a `dev` composition every
@@ -3,9 +3,10 @@
3
3
 
4
4
  import { zValidator } from "@hono/zod-validator";
5
5
  import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
6
- import { UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
6
+ import { NotFoundError, UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
7
7
  import { requireSameOrigin } from "@pithy-sh/core/src/http/sameOrigin";
8
8
  import { validationHook } from "@pithy-sh/core/src/http/validation";
9
+ import { STORED_IMAGE_HEADERS, storedImageBytes } from "@pithy-sh/core/src/image/storedImage";
9
10
  import { TURNSTILE_LOGIN_ACTION } from "@pithy-sh/turnstile/src/config/config";
10
11
  import { turnstile } from "@pithy-sh/turnstile/src/http/middleware";
11
12
  import type { Context, Hono } from "hono";
@@ -13,6 +14,7 @@ import { correlation, emitDenied, emitDeviceRevoked, emitTokenRefresh, emitToken
13
14
  import type { AuthWiring } from "../capability";
14
15
  import { authDatabase } from "../data/tables";
15
16
  import { deleteDevice, deviceSessionTokens, listDevices } from "../device/registry";
17
+ import { PROFILE_IMAGE_PATH } from "../profile/profile";
16
18
  import {
17
19
  consumeSession,
18
20
  findConsumedToken,
@@ -96,6 +98,10 @@ export function createAuthRoutes(wiring: AuthWiring): (app: Hono<PithyHonoEnv>)
96
98
  app.post(`${base}/link-social`, requireFreshAuthentication("link"), (c) => handleBetterAuth(c, wiring));
97
99
  app.post(`${base}/unlink-account`, requireFreshAuthentication("unlink"), (c) => handleBetterAuth(c, wiring));
98
100
 
101
+ // The caller's own stored picture, as bytes a browser can cache. No id in the path — see
102
+ // `serveMyImage`, which is where the reason lives.
103
+ app.get(`${base}${PROFILE_IMAGE_PATH}`, requireAuth(), (c) => serveMyImage(c, wiring));
104
+
99
105
  // The control-plane management surface. Registered here, before the catch-all below, or it is dead.
100
106
  registerAuthAdminRoutes(wiring)(app);
101
107
 
@@ -351,3 +357,49 @@ async function revokeMyDevice(c: Ctx, wiring: AuthWiring, body: RevokeDeviceBody
351
357
  await emitDeviceRevoked(c.var.emit, { userId, ...correlation(c.req.raw.headers) });
352
358
  return c.json({ revoked: tokens.length });
353
359
  }
360
+
361
+ /**
362
+ * Serve the signed-in caller's own stored picture.
363
+ *
364
+ * **There is no id in the path, and that is the security design rather than a simplification.** A
365
+ * serving route addressed by user id has to answer *is this caller entitled to see this person*, and
366
+ * this capability has no such notion — everyone signed in is a peer, so any answer it invented would be
367
+ * either an enumeration oracle or a guess. The subject here is the session, so there is nothing to
368
+ * enumerate. A roster of *other* people's faces is a tenancy question, and `@pithy-sh/organization`
369
+ * answers it with membership, through the same core helpers.
370
+ *
371
+ * **A vector is refused rather than served with headers.** `storedImageBytes` answers null for one and
372
+ * this 404s on null — so there is no arrangement of parameters that makes this origin return an SVG by
373
+ * navigation, which would run script in it. `@pithy-sh/core/src/image/storedImage` carries the full
374
+ * argument.
375
+ *
376
+ * A provider link 404s too, for the same reason it is not this origin's to serve: it is already a URL
377
+ * somewhere else, and `userImageSource` hands the client that URL directly rather than this path.
378
+ *
379
+ * The response is `immutable` because `userImageSource` puts the row's `updatedAt` in the query, and
380
+ * `private` because it was authorized against a session.
381
+ */
382
+ async function serveMyImage(c: Ctx, wiring: AuthWiring): Promise<Response> {
383
+ const auth = c.var.auth;
384
+ if (!auth) throw new UnauthorizedError({ message: "Sign in to see this." });
385
+ // Named columns, never `select *`: this table sits beside `pithy_auth_accounts`, and a habit of
386
+ // widening a select on the auth schema is how a provider token reaches a log.
387
+ const row = await db(c, wiring)
388
+ .selectFrom("pithyAuthUsers")
389
+ .select(["image"])
390
+ .where("id", "=", auth.userId)
391
+ .executeTakeFirst();
392
+ const bytes = storedImageBytes(row?.image ?? null);
393
+ if (!bytes) {
394
+ // One answer for four different facts — no row, no picture, a linked one, a vector. The caller is
395
+ // asking about themselves, so none of them is a secret; they are one answer because the route has
396
+ // exactly one thing to say, which is *nothing to serve here*.
397
+ throw new NotFoundError({
398
+ message: "No picture to show.",
399
+ detail: `user ${auth.userId}: ${row === undefined || row.image === null ? "no stored picture" : "picture is linked or a vector, neither served by URL"}`,
400
+ });
401
+ }
402
+ return new Response(bytes.body as unknown as BodyInit, {
403
+ headers: { "content-type": bytes.type, ...STORED_IMAGE_HEADERS },
404
+ });
405
+ }