@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.
@@ -9,6 +9,7 @@ import { KIT_SESSION_FIELDS, KIT_USER_FIELDS } from "../data/kitFields";
9
9
  import type { AuthDatabase } from "../data/tables";
10
10
  import { parseDeviceMeta, registerDevice } from "../device/registry";
11
11
  import { PROVIDER_CHANGE_FRESH_AGE_SECONDS } from "../http/providerFreshness";
12
+ import { refuseUnsafeProfile, sanitizeProfile } from "../profile/profile";
12
13
  import { defaultGithubUserInfo, type GithubUserInfoResolver } from "./githubUserInfo";
13
14
  import { kitPlugins } from "./plugins";
14
15
  import {
@@ -113,6 +114,21 @@ export function isUnverifiedSignup(user: { emailVerified?: boolean | null }): bo
113
114
  return user.emailVerified !== true;
114
115
  }
115
116
 
117
+ /**
118
+ * Refuse a write whose `name` or `image` is not a shape this kit will render, with a 400 naming the
119
+ * field.
120
+ *
121
+ * The decision is `../profile/profile.ts`'s and is pure; this is the half that needs `APIError`, which
122
+ * is what turns a refusal into a 400 instead of a row that throws on every later read. That failure
123
+ * mode is the one `../data/kitFields.ts` already documents for `locale`: a bad value written once makes
124
+ * the *listing* fail for every operator rather than only for its author.
125
+ */
126
+ function refuseUnsafeProfileFields(user: { name?: unknown; image?: unknown }): void {
127
+ const refusal = refuseUnsafeProfile(user);
128
+ if (!refusal) return;
129
+ throw new APIError("BAD_REQUEST", { code: "INVALID_PROFILE_FIELD", message: refusal.message });
130
+ }
131
+
116
132
  /**
117
133
  * What the instance hands to Pithy's email seam to deliver. The route never sends inline — the hook
118
134
  * enqueues an `@pithy-sh/email` job (`magicLink`/`otp` template) which a Workflow delivers.
@@ -184,6 +200,21 @@ export interface AuthInstanceDeps<Plugins extends readonly BetterAuthPlugin[] =
184
200
  resolveGithubUserInfo?: GithubUserInfoResolver;
185
201
  /** Audit seam — emits `auth/*` events. A no-op when the audit capability is absent. */
186
202
  emit: AuditEmit;
203
+ /**
204
+ * Called when a session row is deleted — a sign-out, a revoke, an admin ending somebody's devices.
205
+ *
206
+ * **The seam exists because a session id is a key other capabilities hang state on**, and nothing
207
+ * else tells them it has gone. `@pithy-sh/organization` keys its acting selection by session id and
208
+ * states that signing out must take it with it; without this there was no moment at which it could,
209
+ * so every sign-in/sign-out cycle left an orphan row in a table with no TTL and no sweep.
210
+ *
211
+ * Wired by the project that composes both — a capability does not reach into another, and the
212
+ * direction is wrong anyway: tenancy depends on auth, not the reverse.
213
+ *
214
+ * **Non-fatal by contract.** By the time this runs the session is already gone; a failure here must
215
+ * not turn a completed sign-out into an error the caller retries. Implementations swallow their own.
216
+ */
217
+ onSessionRevoked?: (session: { id: string; userId: string }) => Promise<void>;
187
218
  /**
188
219
  * The adopter's additional Better Auth plugins, from `auth({ plugins: [...] })`. Composed **after**
189
220
  * the kit's own, never in place of one — `assertAdditivePlugins` has already refused a list that
@@ -252,6 +283,21 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
252
283
  "This email isn't verified by the provider. Sign in with a magic link to verify it, then connect the provider.",
253
284
  });
254
285
  }
286
+ // **Sanitized, not refused.** This is a provider's profile arriving mid-sign-in, and the
287
+ // person signing in did not choose it — see `../profile/profile.ts`. A long name is
288
+ // truncated, an avatar this kit will not hold becomes initials, and they get in.
289
+ const safe = sanitizeProfile(user);
290
+ if (Object.keys(safe).length > 0) return { data: { ...user, ...safe } };
291
+ },
292
+ },
293
+ update: {
294
+ // The profile gate. **Every** write to `name` or `image` passes through here — Better Auth's
295
+ // own `/update-user`, an adopter's route, an admin tool — because the hook is at the adapter
296
+ // rather than at any one door. `../profile/profile.ts` records why a validator declared
297
+ // beside the column would not have run: `parseUserInput` reaches the additional fields only,
298
+ // and these two are Better Auth's own.
299
+ before: async (user) => {
300
+ refuseUnsafeProfileFields(user);
255
301
  },
256
302
  },
257
303
  },
@@ -296,6 +342,27 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
296
342
  return { data: { ...session, deviceId: meta.id, authenticatedAt } };
297
343
  },
298
344
  },
345
+ delete: {
346
+ /**
347
+ * Tell whoever keyed state on this session that it has gone.
348
+ *
349
+ * A sign-out, a revoke, an admin ending somebody's devices — all of them land here, which is
350
+ * why the seam is on the row rather than on the sign-out endpoint. A handler wired to one
351
+ * endpoint would miss the other three, and the row is what the state was keyed by.
352
+ *
353
+ * **After, not before.** The session is already gone when this runs, so a slow or failing
354
+ * listener cannot hold up or refuse a sign-out — and it swallows its own failure for the same
355
+ * reason the audit emit does: the thing it reports has already happened.
356
+ */
357
+ after: async (session) => {
358
+ if (!deps.onSessionRevoked) return;
359
+ try {
360
+ await deps.onSessionRevoked({ id: String(session.id), userId: String(session.userId) });
361
+ } catch {
362
+ // Swallowed by contract. The sign-out succeeded; a listener's failure is not the caller's.
363
+ }
364
+ },
365
+ },
299
366
  },
300
367
  },
301
368
  hooks: {
@@ -14,8 +14,16 @@ import type { Migration } from "kysely/migration";
14
14
  * every identifier in the emitted DDL (CLAUDE.md §Data layer) — and the same plugin lets Better
15
15
  * Auth's camelCase queries land on these snake_case columns. Better-Auth `date` columns are **text**
16
16
  * (it stores ISO-8601 strings on SQLite; ISO sorts chronologically); Pithy's own device timestamps
17
- * are **integer** ms-epoch. Foreign keys are omitted to match the repo convention (D1 does not enforce
18
- * them without a per-connection PRAGMA); linkage is by indexed id columns.
17
+ * are **integer** ms-epoch. Linkage is by indexed id columns.
18
+ *
19
+ * **No foreign keys across a capability boundary — a choice, not a limitation.** D1 *does* enforce
20
+ * them: `PRAGMA foreign_keys` is on, a cascade fires, and an orphan insert is refused with
21
+ * `FOREIGN KEY constraint failed`. `packages/core/src/data/foreignKeys.workers.test.ts` measures both
22
+ * directions, because this is the kind of claim that rots quietly. What is traded away is real, and the
23
+ * reason is the boundary rather than the platform: a constraint from one capability's table to another's
24
+ * binds two release cadences together and breaks the day either moves to its own database. Within a
25
+ * single capability's own tables a foreign key is available and is simply not used here — worth
26
+ * revisiting per table rather than as a rule.
19
27
  *
20
28
  * `down` is the tested inverse — indexes then tables, in reverse creation order (D1 has no
21
29
  * transactional DDL, so order matters).
@@ -0,0 +1,230 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import {
5
+ INLINE_IMAGE_TYPES,
6
+ StoredImage,
7
+ storedImageSource,
8
+ typeOfStoredImage,
9
+ } from "@pithy-sh/core/src/image/storedImage";
10
+ import { z } from "zod";
11
+
12
+ /**
13
+ * A person's own display name and face — the two things about themselves they may change.
14
+ *
15
+ * ## Why the column takes two shapes
16
+ *
17
+ * `pithy_auth_users.image` has always held **a link**: a URL on whichever provider signed somebody in,
18
+ * written once and never again. Two things follow, and both are things every adopter hits.
19
+ *
20
+ * **A linked avatar is a third-party fetch per face.** A roster of twenty people is twenty requests to
21
+ * hosts the viewer did not choose, leaking their IP and referrer before they had done anything, and it
22
+ * needs a CSP hole to render at all.
23
+ *
24
+ * **And nothing in the kit could change it.** Somebody who signed in with GitHub was called whatever
25
+ * GitHub calls them, forever.
26
+ *
27
+ * So the column keeps accepting the provider URL it already holds — an existing row is untouched — and
28
+ * gains a second accepted shape: bytes, stored as a bounded `data:` URL under the kit's one image rule
29
+ * (`@pithy-sh/core/src/image/storedImage`). Where the column is settable by its subject, the host is
30
+ * chosen by them.
31
+ *
32
+ * ## Why the rule is core's and not this package's
33
+ *
34
+ * `@pithy-sh/organization` holds an account's mark under the identical rule. It is the same object at a
35
+ * different scale, and two answers to *what may be stored as an image* is one of them being wrong.
36
+ *
37
+ * ## Why this is `auth` and not `organization`
38
+ *
39
+ * Somebody in two accounts is the same person in both, and being asked to upload the same photograph
40
+ * twice would be a product mistaking a membership for an identity. A single-tenant app — a consumer app
41
+ * with no organizations at all — wants a display name and a face just as much, and should not have to
42
+ * compose a tenancy capability to get one.
43
+ *
44
+ * ## What this package does *not* decide: who may see whose face
45
+ *
46
+ * Serving a raster by URL needs an answer to *is this caller entitled to see this person*, and this
47
+ * capability has no such notion — everyone signed in is a peer. So the route here serves exactly one
48
+ * image: **the caller's own**, at a path carrying no id at all, which cannot be an enumeration oracle
49
+ * because there is nothing in it to enumerate. A roster of other people's faces is a tenancy question,
50
+ * and `@pithy-sh/organization` answers it with membership, through the same core helpers.
51
+ */
52
+
53
+ /**
54
+ * The ceiling on a display name, in characters — applied on the **write** and not on the read.
55
+ *
56
+ * Deliberately asymmetric, and the reason is the one `data/kitFields.ts` already records: a bound on
57
+ * the *column* schema turns a row a provider wrote before the bound existed into a row that throws on
58
+ * every later read, and an admin listing reading a page of rows would then fail for every operator
59
+ * rather than only for the author. A bound on the write is a 400 to the one caller who exceeded it.
60
+ *
61
+ * 256, which is longer than any name and short enough that a roster cannot be made expensive with it.
62
+ */
63
+ export const MAX_DISPLAY_NAME_CHARS = 256;
64
+
65
+ /** A display name somebody may set for themselves. Trimmed by the caller; bounded here. */
66
+ export const DisplayName = z
67
+ .string()
68
+ .min(1)
69
+ .max(MAX_DISPLAY_NAME_CHARS)
70
+ .describe(
71
+ "What this application calls somebody, as they typed it. Bounded on the write rather than on the column, so a longer name a provider wrote before the bound existed still reads.",
72
+ );
73
+
74
+ /**
75
+ * A picture linked on a provider's host — the shape the column has always held.
76
+ *
77
+ * Accepted rather than blessed: it is what Google, GitHub and Apple write at sign-in, and refusing it
78
+ * would break every existing row. **Bounded and scheme-pinned**, because the only two things that can
79
+ * be checked about somebody else's URL are how long it is and that it is not a `javascript:` or `data:`
80
+ * payload wearing a URL's clothes.
81
+ */
82
+ export const ProviderImageUrl = z
83
+ .url({ protocol: /^https?$/ })
84
+ .max(2048)
85
+ .describe(
86
+ "An avatar on the provider's own host, written at sign-in. A third-party fetch per face — see the module note for why a stored image is preferred.",
87
+ );
88
+
89
+ /**
90
+ * What `pithy_auth_users.image` may hold: a provider's link, or bytes this application stores.
91
+ *
92
+ * The union is ordered link-first only for readability; the two shapes cannot both match, because a
93
+ * `data:` URL is not `http(s):` and a stored image is pinned to an allowlisted media type inline in the
94
+ * string. `data:text/html` matches neither, which is the whole of what makes this column safe to render.
95
+ */
96
+ export const UserImage = z
97
+ .union([ProviderImageUrl, StoredImage])
98
+ .describe(
99
+ "A person's picture: either a provider URL, as the column has always held, or bytes stored under the kit's image rule. Rendered only through `<img>`.",
100
+ );
101
+ export type UserImage = z.output<typeof UserImage>;
102
+
103
+ /** The path a signed-in caller's own stored raster is served from, relative to the auth base path. */
104
+ export const PROFILE_IMAGE_PATH = "/profile/image";
105
+
106
+ /**
107
+ * What a screen should draw this person's face from.
108
+ *
109
+ * Three answers, and a caller renders every one of them through the same `<img src>`:
110
+ *
111
+ * - **A provider link passes through.** It is already a URL and already cached by somebody else; there
112
+ * is nothing this origin can add to it.
113
+ * - **A stored raster becomes a versioned URL on this origin**, so a browser caches it and a roster
114
+ * costs one request per face once rather than its bytes on every read.
115
+ * - **A stored vector stays inline**, and the serving route refuses to serve one. An `<img src>` is
116
+ * inert by specification; a URL is navigable, and a navigated SVG runs script in the origin that
117
+ * served it. The class of attack is removed rather than managed with headers.
118
+ *
119
+ * `path` is where the owning capability serves bytes from — `basePath + PROFILE_IMAGE_PATH` here, and a
120
+ * membership-scoped path in `@pithy-sh/organization`.
121
+ */
122
+ export function userImageSource(image: string | null, path: string, version: Date | number): string | null {
123
+ if (image === null) return null;
124
+ // A provider link is not a stored image, and `storedImageSource` would answer null for it — which is
125
+ // right for a column value nobody recognizes and wrong for the one shape this column was born
126
+ // holding. Checked here rather than there, because core's rule is about stored bytes and this is the
127
+ // package that also accepts a link.
128
+ if (typeOfStoredImage(image) === null) return ProviderImageUrl.safeParse(image).success ? image : null;
129
+ return storedImageSource(image, path, version);
130
+ }
131
+
132
+ /**
133
+ * Whether this value is drawn inline rather than fetched.
134
+ *
135
+ * Exported for the projection tests and for a caller deciding whether a listing response is carrying
136
+ * bytes — which is what `@pithy-sh/organization`'s roster budget counts.
137
+ */
138
+ export function isInlineImage(image: string | null): boolean {
139
+ if (image === null) return false;
140
+ const type = typeOfStoredImage(image);
141
+ return type !== null && INLINE_IMAGE_TYPES.includes(type);
142
+ }
143
+
144
+ /** A profile field a write supplied, and why it was refused. */
145
+ export interface ProfileRefusal {
146
+ /** Which field failed — `name` or `image`. Named so a caller's message can say which. */
147
+ readonly field: "name" | "image";
148
+ /** Client-safe text. Says what is wrong without echoing the value back. */
149
+ readonly message: string;
150
+ }
151
+
152
+ /**
153
+ * Check the profile fields of a write, or say which one is refused and why.
154
+ *
155
+ * **This is the gate, and it sits at the database hook rather than at a route, deliberately.** Better
156
+ * Auth's own `/update-user` endpoint pulls `name` and `image` out of the body and passes them straight
157
+ * to the adapter — `parseUserInput` runs `validator.input` over the *additional* fields only, so the
158
+ * mechanism `KIT_USER_FIELDS` relies on for `locale` does not reach these two at all. A validator
159
+ * declared next to the column would therefore have been a validator nothing ran.
160
+ *
161
+ * A `databaseHooks.user` hook does reach it, and reaches every other producer with it: `/update-user`,
162
+ * a social sign-in writing a provider's avatar, an admin route, and whatever the adopter composes next.
163
+ * One rule, at the thing being called rather than at each call site.
164
+ *
165
+ * Absent fields pass: a write that does not mention a field is not a write to it.
166
+ */
167
+ export function refuseUnsafeProfile(fields: { name?: unknown; image?: unknown }): ProfileRefusal | null {
168
+ if (fields.name !== undefined && fields.name !== null && !DisplayName.safeParse(fields.name).success) {
169
+ return {
170
+ field: "name",
171
+ message: `A name is between 1 and ${MAX_DISPLAY_NAME_CHARS} characters.`,
172
+ };
173
+ }
174
+ if (fields.image !== undefined && fields.image !== null && !UserImage.safeParse(fields.image).success) {
175
+ return {
176
+ field: "image",
177
+ // Says the shape rather than the reason it matters: a caller learns what to send, and an attacker
178
+ // probing for `data:text/html` learns only that it was refused.
179
+ message: "A picture must be an https URL or an image this application stores, within the size limit.",
180
+ };
181
+ }
182
+ return null;
183
+ }
184
+
185
+ /** What a sign-in's profile fields become after the kit has made them safe to store. */
186
+ export interface SanitizedProfile {
187
+ /** The name, truncated to the bound. Absent when the write did not mention one. */
188
+ readonly name?: string;
189
+ /** The picture, or null when the provider offered one this kit will not hold. */
190
+ readonly image?: string | null;
191
+ }
192
+
193
+ /**
194
+ * Make a **provider's** profile fields storable, rather than refusing them.
195
+ *
196
+ * The asymmetry with {@link refuseUnsafeProfile} is the point, and it is about whose act it is.
197
+ *
198
+ * A person setting their own name and picture is one caller doing one thing: a 400 tells them what to
199
+ * send, and they send it. A provider's profile arrives in the middle of somebody signing in, and they
200
+ * did not choose it — refusing there would mean **a person cannot sign in because Google gave them a
201
+ * long display name.** So an over-long name is truncated and an avatar this kit will not hold becomes
202
+ * no avatar, which draws initials, which is a real answer.
203
+ *
204
+ * Nothing unsafe reaches the column either way. The two paths differ in what they do about it, not in
205
+ * what they accept.
206
+ */
207
+ export function sanitizeProfile(fields: { name?: unknown; image?: unknown }): SanitizedProfile {
208
+ const sanitized: { name?: string; image?: string | null } = {};
209
+ if (fields.name !== undefined && !DisplayName.safeParse(fields.name).success) {
210
+ /*
211
+ **Every value that is not a name, not only the long ones.**
212
+
213
+ The guard was `typeof fields.name === "string" && …`, so a `name` that arrived as a number or an
214
+ object failed the first clause and was neither truncated nor replaced — it fell through untouched
215
+ and was spread into the row by the `create.before` hook. The `image` branch below never had that
216
+ gap, because `UserImage.safeParse` fails for any non-string, and `refuseUnsafeProfile` covers the
217
+ update path. This was the one way in that did not.
218
+
219
+ Truncated rather than dropped where there is something to truncate: Better Auth's user model
220
+ requires a name, and an empty one is a row every roster renders as a blank. A slice of a long name
221
+ is still recognisably them; a value that was never a string has nothing to slice, so it becomes the
222
+ same placeholder an empty slice would.
223
+ */
224
+ sanitized.name = typeof fields.name === "string" ? fields.name.slice(0, MAX_DISPLAY_NAME_CHARS) || "—" : "—";
225
+ }
226
+ if (fields.image !== undefined && fields.image !== null && !UserImage.safeParse(fields.image).success) {
227
+ sanitized.image = null;
228
+ }
229
+ return sanitized;
230
+ }
@@ -5,15 +5,8 @@ import { normalizeAddress } from "@pithy-sh/core/src/address/address";
5
5
  import { fromZodError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
6
6
  import { MAX_SEED_ORDER } from "@pithy-sh/core/src/seed/compose";
7
7
  import { DEV_LOGIN_FILE, DEV_LOGIN_PATH, DevLogin } from "@pithy-sh/core/src/seed/devLogin";
8
- import {
9
- d1SeedGroup,
10
- defineSeed,
11
- type SeedPreparation,
12
- type SeedPrepareContext,
13
- type SeedSet,
14
- } from "@pithy-sh/core/src/seed/seed";
8
+ import { defineSeed, type SeedPreparation, type SeedPrepareContext, type SeedSet } from "@pithy-sh/core/src/seed/seed";
15
9
  import { z } from "zod";
16
- import { Session } from "../data/betterAuth";
17
10
  import { DEV_PROTOCOL, sessionCookieName } from "../http/baseUrl";
18
11
  import { AUTH_SESSION_SECRET } from "../instance/secrets";
19
12
 
@@ -71,20 +64,12 @@ const USERS_TABLE = "pithyAuthUsers";
71
64
  export const DEV_SESSION_COOKIE_NAME = sessionCookieName(DEV_PROTOCOL);
72
65
 
73
66
  /**
74
- * The prefix every seeded dev session's id and token carry.
67
+ * How long a dev login stays usable. Long, because reseeding to restore one is the friction this removes.
75
68
  *
76
- * It is what makes a dev session **findable without being told**, which is what the dev-login route
77
- * needs: the route reads the session out of D1 and has no artifact to consult (a Worker has no
78
- * filesystem). And it is what makes one identifiable at all — a `pithy_auth_sessions` row minted by a
79
- * seed is otherwise indistinguishable from one a real sign-in created.
69
+ * It bounds the *claim*, not a session — `#572`. The session the route mints from it lives by the auth
70
+ * config's own `sessionExpiresIn`, exactly as a real sign-in does, because it *is* one.
80
71
  */
81
- export const DEV_SESSION_TOKEN_PREFIX = "dev-session-";
82
-
83
- /** How long a seeded session lives. Long, because reseeding to restore a dev login is the friction this removes. */
84
- const DEV_SESSION_LIFETIME_MS = 365 * 24 * 60 * 60 * 1000;
85
-
86
- /** Bytes of the secret digest kept as the token's fingerprint — enough to separate secrets, short enough to read. */
87
- const FINGERPRINT_BYTES = 4;
72
+ const DEV_LOGIN_LIFETIME_MS = 365 * 24 * 60 * 60 * 1000;
88
73
 
89
74
  /** The developer's machine-local preferences for this project, read from `~/.config/pithy/<project>/dev.json`. */
90
75
  export const DevPreferences = z
@@ -115,11 +100,9 @@ export const SeededUser = z
115
100
  .describe("A seeded `pithy_auth_users` row, narrowed to what minting a dev session for it requires.");
116
101
  export type SeededUser = z.output<typeof SeededUser>;
117
102
 
118
- /** What {@link mintDevSession} produces: the row to write, and the artifact the browser is handed. */
119
- export interface MintedDevSession {
120
- /** The `pithy_auth_sessions` row, in app shape — re-encoded and validated by the seed writer. */
121
- session: Session;
122
- /** The dev-login artifact, written to `logs/dev-login.json` once the row lands. */
103
+ /** What {@link mintDevLogin} produces. One field, because a dev login is no longer a row — `#572`. */
104
+ export interface MintedDevLogin {
105
+ /** The dev-login artifact, written to `logs/dev-login.json`. */
123
106
  login: DevLogin;
124
107
  }
125
108
 
@@ -145,65 +128,139 @@ export async function signCookieValue(value: string, secret: string): Promise<st
145
128
  return encodeURIComponent(`${value}.${base64}`);
146
129
  }
147
130
 
148
- /**
149
- * A short, stable fingerprint of the auth secret.
150
- *
151
- * Putting it in the session token makes the token deterministic across reseeds — the same cookie keeps
152
- * working in every worktree once each is seeded, which is the whole point — while rotating the secret
153
- * changes the token *and* invalidates every cookie signed with the old one, for free. A truncated digest,
154
- * never the secret: the token is written to a file and read back by tooling.
155
- */
156
- export async function secretFingerprint(secret: string): Promise<string> {
157
- const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(secret));
158
- return Array.from(new Uint8Array(digest).slice(0, FINGERPRINT_BYTES))
159
- .map((byte) => byte.toString(16).padStart(2, "0"))
160
- .join("");
161
- }
162
-
163
- /** Inputs to {@link mintDevSession}. `now` is a seam so the determinism tests do not depend on the clock. */
164
- export interface MintDevSessionInput {
131
+ /** Inputs to {@link mintDevLogin}. `now` is a seam so the tests do not depend on the clock. */
132
+ export interface MintDevLoginInput {
165
133
  /** The seeded user to sign in as. */
166
134
  user: SeededUser;
167
135
  /** The Better Auth signing secret for this environment — never logged, never stored, never in an error. */
168
136
  secret: string;
169
- /** The moment the session is minted. Defaults to now. */
137
+ /** The moment the claim is minted. Defaults to now. */
170
138
  now?: Date;
171
139
  }
172
140
 
173
141
  /**
174
- * Mint one deterministic dev session: the `pithy_auth_sessions` row and the signed cookie for it.
142
+ * Sign a claim naming the user a dev login signs in as — `#572`.
143
+ *
144
+ * **The payload is base64 of JSON, not a delimited string.** A user id is an adopter's to choose and may
145
+ * hold any character at all, including whichever one a hand-rolled format picked as its separator. JSON
146
+ * inside base64 has no separator to collide with, and the whole of it is what the signature covers.
175
147
  *
176
- * The row id carries the fingerprint too, not just the token. Seed writes are `INSERT OR IGNORE`, so an
177
- * id that ignored a rotation would keep the stale token alive under a row the next run refuses to replace.
148
+ * The same HMAC-SHA-256 construction {@link signCookieValue} uses, deliberately not the same function:
149
+ * that one mirrors better-call's cookie format because Better Auth has to accept its output, and this is
150
+ * ours. Two consumers, two formats, no shared spelling to break one by fixing the other.
178
151
  */
179
- export async function mintDevSession(input: MintDevSessionInput): Promise<MintedDevSession> {
180
- const now = input.now ?? new Date();
181
- const expiresAt = new Date(now.getTime() + DEV_SESSION_LIFETIME_MS);
182
- const fingerprint = await secretFingerprint(input.secret);
183
- const token = `${DEV_SESSION_TOKEN_PREFIX}${input.user.id}-${fingerprint}`;
152
+ export async function signDevLoginClaim(input: MintDevLoginInput & { expiresAt: Date }): Promise<string> {
153
+ // **`TextEncoder`, not `btoa` on the string.** `btoa` throws `InvalidCharacterError` for any code
154
+ // point above U+00FF, and a user id is the adopter's to choose — this module already reasons about
155
+ // ids holding a separator, and a non-ASCII one is no stranger. Encoding to UTF-8 bytes first makes
156
+ // the payload total in the id, which is what a seed that must not die on somebody's name requires.
157
+ const body = base64Of(new TextEncoder().encode(JSON.stringify({ u: input.user.id, e: input.expiresAt.getTime() })));
158
+ const key = await claimKey(input.secret, ["sign"]);
159
+ const signature = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(body));
160
+ return encodeURIComponent(`${body}.${base64Of(signature)}`);
161
+ }
184
162
 
185
- const session: Session = {
186
- id: token,
187
- token,
188
- userId: input.user.id,
189
- expiresAt,
190
- createdAt: now,
191
- updatedAt: now,
192
- ipAddress: "127.0.0.1",
193
- userAgent: "pithy seed (dev login)",
194
- deviceId: null,
195
- familyId: null,
196
- // A dev session is a real sign-in, so it is authenticated now — what the live hook stamps.
197
- authenticatedAt: now,
198
- };
163
+ /**
164
+ * What a claim says, once it has been proved to say it.
165
+ *
166
+ * `null` for every failure and never a reason: a malformed claim, one signed by another secret, and one
167
+ * naming a user who has since gone are the same answer to whoever presented it, because distinguishing
168
+ * them is a probe. The route turns all three into the one 404 it already had.
169
+ */
170
+ export async function verifyDevLoginClaim(
171
+ claim: string,
172
+ secret: string,
173
+ now: Date = new Date(),
174
+ ): Promise<{ userId: string; expiresAt: Date } | null> {
175
+ const raw = safeDecode(claim);
176
+ if (raw === null) return null;
177
+ // The last dot, because base64 never contains one and a payload might have been anything.
178
+ const cut = raw.lastIndexOf(".");
179
+ if (cut <= 0) return null;
180
+ const body = raw.slice(0, cut);
181
+ const signature = safeBytes(raw.slice(cut + 1));
182
+ if (signature === null) return null;
183
+
184
+ // `crypto.subtle.verify` rather than comparing strings: the comparison is the part that has to be
185
+ // constant-time, and this is the primitive that already is.
186
+ const key = await claimKey(secret, ["verify"]);
187
+ if (!(await crypto.subtle.verify("HMAC", key, signature, new TextEncoder().encode(body)))) return null;
188
+
189
+ const decoded = safeJson(body);
190
+ const parsed = DevLoginClaim.safeParse(decoded);
191
+ if (!parsed.success) return null;
192
+ const expiresAt = new Date(parsed.data.e);
193
+ if (expiresAt.getTime() <= now.getTime()) return null;
194
+ return { userId: parsed.data.u, expiresAt };
195
+ }
196
+
197
+ /** The claim's payload, as it is signed. Two letters, because it is written into a URL a person may see. */
198
+ const DevLoginClaim = z
199
+ .object({
200
+ u: z.string().min(1).describe("The user id the route mints a session for."),
201
+ e: z.number().int().positive().describe("When the claim stops being accepted, in ms since the epoch."),
202
+ })
203
+ .describe("What a dev-login claim asserts: which seeded user, and until when.");
204
+
205
+ /** The HMAC key for a claim. Imported per call — a key object is not something to cache across requests. */
206
+ function claimKey(secret: string, usages: readonly ("sign" | "verify")[]): Promise<CryptoKey> {
207
+ return crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, [
208
+ ...usages,
209
+ ]);
210
+ }
211
+
212
+ /** Base64 of bytes — a signature, or a UTF-8 payload. */
213
+ function base64Of(bytes: ArrayBuffer | Uint8Array): string {
214
+ return btoa(String.fromCharCode(...new Uint8Array(bytes)));
215
+ }
199
216
 
217
+ /** `decodeURIComponent`, or null. A malformed escape throws, and a throw here is just "not a claim". */
218
+ function safeDecode(value: string): string | null {
219
+ try {
220
+ return decodeURIComponent(value);
221
+ } catch {
222
+ return null;
223
+ }
224
+ }
225
+
226
+ /** Base64 to bytes, or null. Same reason: unparseable input is not an error, it is a refusal. */
227
+ function safeBytes(value: string): Uint8Array | null {
228
+ try {
229
+ return Uint8Array.from(atob(value), (character) => character.charCodeAt(0));
230
+ } catch {
231
+ return null;
232
+ }
233
+ }
234
+
235
+ /** Base64 UTF-8 JSON to a value, or null. Decoded as bytes, to match how {@link base64Of} wrote it. */
236
+ function safeJson(body: string): unknown {
237
+ try {
238
+ const bytes = Uint8Array.from(atob(body), (character) => character.charCodeAt(0));
239
+ return JSON.parse(new TextDecoder().decode(bytes));
240
+ } catch {
241
+ return null;
242
+ }
243
+ }
244
+
245
+ /**
246
+ * Mint one dev login: the signed claim, and the artifact that carries it.
247
+ *
248
+ * **No `pithy_auth_sessions` row — `#572`.** This used to write one and hand it over on every open, which
249
+ * meant the product's own sign-out revoked the dev login along with the session, and the only way back was
250
+ * a reseed. It also meant a row in that table which was, by this module's own admission, indistinguishable
251
+ * from a real sign-in — so it showed up in every surface built over sessions as a device nobody used.
252
+ *
253
+ * What is minted here is a claim about *who*. The route exchanges it for a session at the moment somebody
254
+ * opens the link, so the session is real, is theirs, and is the only thing a sign-out takes away.
255
+ */
256
+ export async function mintDevLogin(input: MintDevLoginInput): Promise<MintedDevLogin> {
257
+ const now = input.now ?? new Date();
258
+ const expiresAt = new Date(now.getTime() + DEV_LOGIN_LIFETIME_MS);
200
259
  return {
201
- session,
202
260
  login: {
203
261
  email: input.user.email,
204
262
  userId: input.user.id,
205
- cookieName: DEV_SESSION_COOKIE_NAME,
206
- cookieValue: await signCookieValue(token, input.secret),
263
+ claim: await signDevLoginClaim({ ...input, expiresAt }),
207
264
  expiresAt,
208
265
  },
209
266
  };
@@ -279,9 +336,11 @@ export const authDevSessionSeed: SeedSet = defineSeed({
279
336
  });
280
337
  }
281
338
 
282
- const minted = await mintDevSession({ user, secret });
339
+ const minted = await mintDevLogin({ user, secret });
340
+ // **No `d1` — `#572`.** This set writes a file and nothing else now. Nothing reaches
341
+ // `pithy_auth_sessions` until somebody opens the link and the route mints a session for them, which
342
+ // is what makes signing out of the app harmless to the way back in.
283
343
  return {
284
- d1: [d1SeedGroup("app", "pithyAuthSessions", Session, [minted.session])],
285
344
  artifacts: [{ file: DEV_LOGIN_FILE, contents: `${JSON.stringify(DevLogin.encode(minted.login), null, 2)}\n` }],
286
345
  };
287
346
  },
@@ -13,4 +13,4 @@
13
13
  export const PACKAGE_NAME = "@pithy-sh/auth";
14
14
 
15
15
  /** This package's version, stamped from its own package.json at generation time. */
16
- export const PACKAGE_VERSION = "0.5.0";
16
+ export const PACKAGE_VERSION = "0.6.1";