@pithy-sh/auth 0.6.7 → 0.8.0

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.
@@ -2,9 +2,10 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import { normalizeAddress } from "@pithy-sh/core/src/address/address";
5
+ import { commandName } from "@pithy-sh/core/src/cli/command";
5
6
  import { fromZodError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
6
7
  import { MAX_SEED_ORDER } from "@pithy-sh/core/src/seed/compose";
7
- import { DEV_LOGIN_FILE, DEV_LOGIN_PATH, DevLogin } from "@pithy-sh/core/src/seed/devLogin";
8
+ import { DEV_LOGIN_FILE, DEV_LOGIN_PATH, type DevLogin, DevLogins } from "@pithy-sh/core/src/seed/devLogin";
8
9
  import { defineSeed, type SeedPreparation, type SeedPrepareContext, type SeedSet } from "@pithy-sh/core/src/seed/seed";
9
10
  import { z } from "zod";
10
11
  import { DEV_PROTOCOL, sessionCookieName } from "../http/baseUrl";
@@ -76,8 +77,9 @@ export const DevPreferences = z
76
77
  .object({
77
78
  user: z
78
79
  .string()
80
+ .optional()
79
81
  .describe(
80
- "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.",
82
+ "The email of the seeded user to sign in as first. **This key is the dev-login opt-in**: without it no claim is minted at all, because `dev.json` has other tenants and its mere existence is not consent. With it, every seeded user gets a claim and this one is offered first. Must be a user this seed run creates, or the seed fails rather than naming nobody.",
81
83
  ),
82
84
  })
83
85
  .describe(
@@ -266,6 +268,29 @@ export async function mintDevLogin(input: MintDevLoginInput): Promise<MintedDevL
266
268
  };
267
269
  }
268
270
 
271
+ /**
272
+ * Mint a claim for **every** user this run seeds, keyed by user id — `#667`.
273
+ *
274
+ * Cheap by construction: a claim is a signature over a user id and an expiry, so N of them add no seeded
275
+ * rows and a few hundred bytes each.
276
+ *
277
+ * **The record keeps the order it is handed, except for integer-like ids — and that is JS, not us.** Keys
278
+ * that are canonical array indices are enumerated first and in ascending numeric order, by the language and
279
+ * again by `JSON.parse`, so an adopter whose users carry stringified integer PKs gets a numerically ordered
280
+ * picker and `dev.json`'s "offered first" does not survive for them. Keying the artifact by user id is the
281
+ * design; holding the order for every possible id would mean a different artifact shape.
282
+ */
283
+ export async function mintDevLogins(input: {
284
+ users: readonly SeededUser[];
285
+ secret: string;
286
+ now?: Date;
287
+ }): Promise<DevLogins> {
288
+ const minted = await Promise.all(
289
+ input.users.map((user) => mintDevLogin({ user, secret: input.secret, ...(input.now ? { now: input.now } : {}) })),
290
+ );
291
+ return Object.fromEntries(minted.map(({ login }) => [login.userId, login]));
292
+ }
293
+
269
294
  /**
270
295
  * The users this run creates, whichever set contributes them.
271
296
  *
@@ -287,22 +312,32 @@ function nameOneOf(users: readonly SeededUser[]): string {
287
312
  return `Name one of the users this run seeds instead: ${users.map((user) => user.email).join(", ")}.`;
288
313
  }
289
314
 
290
- /** Resolve the preference file into the user to sign in as, or fail saying who this run does seed. */
291
- function requireUser(preferences: unknown, users: readonly SeededUser[]): SeededUser {
315
+ /**
316
+ * The email `dev.json` names, or `undefined` when it names none. A file that does not parse is a failure.
317
+ *
318
+ * Split from resolving it because the two answers differ: naming nobody is a valid file that wants no dev
319
+ * login, and naming somebody this run does not create is a typo worth failing over.
320
+ */
321
+ function namedUser(preferences: unknown, users: readonly SeededUser[]): string | undefined {
292
322
  const parsed = DevPreferences.safeParse(preferences);
293
323
  if (!parsed.success) {
294
324
  throw fromZodError(parsed.error, {
295
- message: "The dev.json preference file does not name a user.",
325
+ message: "The dev.json preference file does not parse.",
296
326
  action: `Set { "user": "<email>" } in it. ${nameOneOf(users)}`,
297
327
  });
298
328
  }
299
- // Both sides normalized: `dev.json` is hand-typed, and refusing to sign in over the capital in
300
- // `Ada@example.com` would be a puzzle rather than an error.
301
- const wanted = normalizeAddress(parsed.data.user);
329
+ return parsed.data.user;
330
+ }
331
+
332
+ /** Resolve the named email to a user this run seeds, or fail saying who it does seed. */
333
+ function requireNamedUser(named: string, users: readonly SeededUser[]): SeededUser {
334
+ // Both sides normalized: `dev.json` is hand-typed, and refusing over the capital in `Ada@example.com`
335
+ // would be a puzzle rather than an error.
336
+ const wanted = normalizeAddress(named);
302
337
  const user = users.find((candidate) => normalizeAddress(candidate.email) === wanted);
303
338
  if (!user) {
304
339
  throw new ValidationError({
305
- message: `dev.json asks to sign in as ${parsed.data.user}, which this seed run does not create.`,
340
+ message: `dev.json asks to sign in as ${named}, which this seed run does not create.`,
306
341
  action: nameOneOf(users),
307
342
  });
308
343
  }
@@ -322,7 +357,17 @@ export const authDevSessionSeed: SeedSet = defineSeed({
322
357
  // a magic link" true for everyone who never asked for anything else.
323
358
  if (context.preferences === undefined || context.preferences === null) return {};
324
359
 
325
- const user = requireUser(context.preferences, seededUsers(context.seeded));
360
+ const users = seededUsers(context.seeded);
361
+ const named = namedUser(context.preferences, users);
362
+ // **No user named, no dev login — and `dev.json` is why the *key* has to be the opt-in rather than the
363
+ // file (`#154`, `#667`).** That file has other tenants: `writeBootstrapVars` creates it for bootstrap
364
+ // `.dev.vars` alone, with no `user` in it and no interest in signing anybody in. Treating its mere
365
+ // existence as consent would mint a live claim for every seeded user on a machine where nobody ever
366
+ // asked for one. `doctor/devPreferences.ts` holds the same contract, and this is the half that enforces
367
+ // it: naming a user is the opt-in, and it is also which identity `pithy dev` offers first.
368
+ if (named === undefined) return {};
369
+
370
+ const preferred = requireNamedUser(named, users);
326
371
  const secret = await context.secret(AUTH_SESSION_SECRET);
327
372
  if (!secret) {
328
373
  throw new ValidationError({
@@ -332,16 +377,18 @@ export const authDevSessionSeed: SeedSet = defineSeed({
332
377
  // fail again with the same sentence. The path is deliberately unnamed rather than guessed: this
333
378
  // set runs inside a Worker with no filesystem and no config directory to resolve, and `pithy
334
379
  // doctor` prints the resolved path on every run precisely so a message like this does not have to.
335
- action: `Add ${AUTH_SESSION_SECRET} to this project's dev secrets file — pithy doctor prints its path — then seed again.`,
380
+ action: `Add ${AUTH_SESSION_SECRET} to this project's dev secrets file — ${commandName("doctor")} prints its path — then seed again.`,
336
381
  });
337
382
  }
338
383
 
339
- const minted = await mintDevLogin({ user, secret });
384
+ // The named user first, then everyone else in the order the run seeded them.
385
+ const ordered = [preferred, ...users.filter((user) => user.id !== preferred.id)];
386
+ const minted = await mintDevLogins({ users: ordered, secret });
340
387
  // **No `d1` — `#572`.** This set writes a file and nothing else now. Nothing reaches
341
388
  // `pithy_auth_sessions` until somebody opens the link and the route mints a session for them, which
342
389
  // is what makes signing out of the app harmless to the way back in.
343
390
  return {
344
- artifacts: [{ file: DEV_LOGIN_FILE, contents: `${JSON.stringify(DevLogin.encode(minted.login), null, 2)}\n` }],
391
+ artifacts: [{ file: DEV_LOGIN_FILE, contents: `${JSON.stringify(DevLogins.encode(minted), null, 2)}\n` }],
345
392
  };
346
393
  },
347
394
  });
@@ -17,7 +17,7 @@ import { devEncryptionKeys } from "@pithy-sh/secrets/src/test-utils/devEncryptio
17
17
  import { type SecretFixture, seedSecrets } from "@pithy-sh/secrets/src/test-utils/secretFixtures";
18
18
  import { turnstileSecretsRegistry } from "@pithy-sh/turnstile/src/secret/registry";
19
19
  import { Hono } from "hono";
20
- import { Miniflare } from "miniflare";
20
+ import { convertV4MiniflareOptions, Miniflare } from "miniflare";
21
21
  import { AuthConfig, type AuthWiring } from "../capability";
22
22
  import { publishSameOrigin } from "../http/csrf";
23
23
  import { createSessionMiddleware } from "../http/middleware";
@@ -150,11 +150,13 @@ export interface LiveApp {
150
150
  * forgets leaves a workerd process behind.
151
151
  */
152
152
  export async function startLiveApp(options: LiveAppOptions): Promise<LiveApp> {
153
- const miniflare = new Miniflare({
154
- modules: true,
155
- script: "export default {};",
156
- d1Databases: { DB: "DB", SECRETS: "SECRETS" },
157
- });
153
+ const miniflare = new Miniflare(
154
+ convertV4MiniflareOptions({
155
+ modules: true,
156
+ script: "export default {};",
157
+ d1Databases: { DB: "DB", SECRETS: "SECRETS" },
158
+ }),
159
+ );
158
160
  const db = (await miniflare.getD1Database("DB")) as unknown as D1Database;
159
161
  const secretsDb = (await miniflare.getD1Database("SECRETS")) as unknown as D1Database;
160
162
 
@@ -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.7";
16
+ export const PACKAGE_VERSION = "0.8.0";