@pithy-sh/auth 0.6.0 → 0.6.2

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.4.0";
6
+ export declare const PACKAGE_VERSION = "0.6.2";
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.4.0";
7
+ const PACKAGE_VERSION = "0.6.2";
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.6.0",
3
+ "version": "0.6.2",
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.6.0",
46
- "@pithy-sh/email": "^0.3.2",
47
- "@pithy-sh/secrets": "^0.2.2",
48
- "@pithy-sh/turnstile": "^0.2.2",
45
+ "@pithy-sh/core": "^0.7.0",
46
+ "@pithy-sh/email": "^0.3.4",
47
+ "@pithy-sh/secrets": "^0.2.4",
48
+ "@pithy-sh/turnstile": "^0.3.0",
49
49
  "hono": "^4.13.2",
50
50
  "kysely": "^0.29.0",
51
51
  "zod": "^4.4.0"
@@ -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.6.0";
16
+ export const PACKAGE_VERSION = "0.6.2";