@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,5 +1,6 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
+ import type { D1Database } from "@cloudflare/workers-types";
3
4
  import type { Capability } from "@pithy-sh/core/src/capability/capability";
4
5
  import type { EmailCapability } from "@pithy-sh/email/src/capability";
5
6
  import { type TurnstileMode } from "@pithy-sh/turnstile/src/config/config";
@@ -52,7 +53,26 @@ export interface AuthWiring {
52
53
  turnstile: {
53
54
  mode: TurnstileMode;
54
55
  } | undefined;
56
+ /**
57
+ * The adopter's session-revoked listener, or absent. See {@link AuthOptions.onSessionRevoked}.
58
+ *
59
+ * Optional on the wiring rather than required-and-undefined, because a composition without a listener
60
+ * is the ordinary case and every harness that builds this shape by hand would otherwise have to say so.
61
+ */
62
+ onSessionRevoked?: SessionRevokedListener | undefined;
55
63
  }
64
+ /**
65
+ * Called when a session row is deleted — a sign-out, a revoke, an admin ending somebody's devices.
66
+ *
67
+ * **Handed this request's D1 binding**, because the auth instance is built per request and the listener
68
+ * almost certainly wants to write to the same database under a different capability's view of it. Taking
69
+ * the binding rather than a typed database keeps this seam out of the business of knowing whose tables
70
+ * the listener is about to touch.
71
+ */
72
+ export type SessionRevokedListener = (session: {
73
+ id: string;
74
+ userId: string;
75
+ }, d1: D1Database) => Promise<void>;
56
76
  /**
57
77
  * What `auth()` takes: the config, plus the seams that are **behavior rather than data**.
58
78
  *
@@ -77,6 +97,22 @@ export type AuthOptions = AuthConfigInput & {
77
97
  * real per-address flag, always.
78
98
  */
79
99
  resolveGithubUserInfo?: GithubUserInfoResolver;
100
+ /**
101
+ * Told when a session is revoked, so state another capability keyed on it can go with it.
102
+ *
103
+ * **On the row, not on the sign-out route.** A sign-out, a revoke and an admin ending somebody's
104
+ * devices all delete the same row, so a listener hung off one endpoint would miss the others.
105
+ *
106
+ * The case this exists for is `@pithy-sh/organization`: its acting selection is keyed by session id
107
+ * and its schema says signing out must take it with it. Tenancy depends on auth and not the reverse,
108
+ * so the composition holding both is what joins them, and this is the join.
109
+ *
110
+ * **Non-fatal by contract.** The session is already gone when this runs; a failure here must not turn
111
+ * a completed sign-out into an error the caller retries, so the instance swallows what it throws.
112
+ *
113
+ * A function, so it is destructured off before `AuthConfig.parse` for the reason above.
114
+ */
115
+ onSessionRevoked?: SessionRevokedListener;
80
116
  };
81
117
  /** The auth capability, with its resolved config attached for inspection. */
82
118
  export interface AuthCapability extends Capability {
@@ -1 +1 @@
1
- {"version":3,"file":"capability.d.ts","sourceRoot":"","sources":["../src/capability.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAmB,MAAM,0CAA0C,CAAC;AAG5F,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AAGtE,OAAO,EAA0B,KAAK,aAAa,EAAE,MAAM,uCAAuC,CAAC;AACnG,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AASxB,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AAmCxE,mGAAmG;AACnG,eAAO,MAAM,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAsE8B,CAAC;AACtD,MAAM,MAAM,UAAU,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AACrD,MAAM,MAAM,eAAe,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,UAAU,CAAC,CAAC;AAEzD;;;;GAIG;AACH,MAAM,WAAW,UAAU;IACzB,MAAM,EAAE,UAAU,CAAC;IACnB,8GAA8G;IAC9G,qBAAqB,EAAE,sBAAsB,GAAG,SAAS,CAAC;IAC1D,sGAAsG;IACtG,YAAY,EAAE,eAAe,CAAC,SAAS,CAAC,GAAG,SAAS,CAAC;IACrD,6FAA6F;IAC7F,SAAS,EAAE;QAAE,IAA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CAAC;IAC1D,sGAAsG;IACtG,YAAY,EAAE,eAAe,CAAC,SAAS,CAAC,GAAG,SAAS,CAAC;IACrD,6FAA6F;IAC7F,SAAS,EAAE;QAAE,IAAI,EAAE,aAAa,CAAA;KAAE,GAAG,SAAS,CAAC;IAC/C;;;;;OAKG;IACH,gBAAgB,CAAC,EAAE,sBAAsB,GAAG,SAAS,CAAC;CACvD;AAED;;;;;;;GAOG;AACH,MAAM,MAAM,sBAAsB,GAAG,CAAC,OAAO,EAAE;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,EAAE,EAAE,EAAE,UAAU,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;AAEhH;;;;;;;GAOG;AACH,MAAM,MAAM,WAAW,GAAG,eAAe,GAAG;IAC1C;;;;;;;;;;;;;OAaG;IACH,qBAAqB,CAAC,EAAE,sBAAsB,CAAC;IAC/C;;;;;;;;;;;;;;OAcG;IACH,gBAAgB,CAAC,EAAE,sBAAsB,CAAC;CAC3C,CAAC;AAEF,6EAA6E;AAC7E,MAAM,WAAW,cAAe,SAAQ,UAAU;IAChD,UAAU,EAAE,UAAU,CAAC;CACxB;AAiCD;;;;;GAKG;AACH,wBAAgB,IAAI,CAAC,OAAO,EAAE,WAAW,GAAG,cAAc,CA0JzD;AAED,0DAA0D;AAC1D,wBAAgB,gBAAgB,CAAC,UAAU,EAAE,UAAU,GAAG,UAAU,IAAI,cAAc,CAErF"}
@@ -85,7 +85,7 @@ function assertPluginTablesUnclaimed(capabilities, binding, extensions) {
85
85
  * and emits `auth/*` through `audit` when those are composed.
86
86
  */
87
87
  function auth(options) {
88
- const { resolveGithubUserInfo, ...config } = options;
88
+ const { resolveGithubUserInfo, onSessionRevoked, ...config } = options;
89
89
  const resolved = AuthConfig.parse(config);
90
90
  assertAdditivePlugins(resolved.plugins);
91
91
  const pluginPlan = authPluginPlan(resolved.plugins);
@@ -93,7 +93,8 @@ function auth(options) {
93
93
  config: resolved,
94
94
  resolveGithubUserInfo,
95
95
  enqueueEmail: void 0,
96
- turnstile: void 0
96
+ turnstile: void 0,
97
+ onSessionRevoked
97
98
  };
98
99
  const rateLimitMiddleware = (app) => {
99
100
  app.use(`${resolved.basePath}/*`, createRateLimitMiddleware(resolved.rateLimiterBinding));
@@ -1 +1 @@
1
- {"version":3,"file":"betterAuth.d.ts","sourceRoot":"","sources":["../../src/data/betterAuth.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAuBxB,2FAA2F;AAC3F,eAAO,MAAM,IAAI;;;;;;;;;iBAqBwF,CAAC;AAC1G,MAAM,MAAM,IAAI,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,IAAI,CAAC,CAAC;AAEzC,6FAA6F;AAC7F,eAAO,MAAM,OAAO;;;;;;;;;;;;iBAqCqF,CAAC;AAC1G,MAAM,MAAM,OAAO,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,OAAO,CAAC,CAAC;AAE/C,mGAAmG;AACnG,eAAO,MAAM,OAAO;;;;;;;;;;;;;;;iBAyCqF,CAAC;AAC1G,MAAM,MAAM,OAAO,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,OAAO,CAAC,CAAC;AAE/C,8FAA8F;AAC9F,eAAO,MAAM,YAAY;;;;;;;iBAmBtB,CAAC;AACJ,MAAM,MAAM,YAAY,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,YAAY,CAAC,CAAC;AAEzD,gGAAgG;AAChG,eAAO,MAAM,IAAI;;;;;;;;iBA8Bd,CAAC;AACJ,MAAM,MAAM,IAAI,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,IAAI,CAAC,CAAC;AAEzC,sHAAsH;AACtH,eAAO,MAAM,SAAS;;;;;iBAcnB,CAAC;AACJ,MAAM,MAAM,SAAS,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,SAAS,CAAC,CAAC"}
1
+ {"version":3,"file":"betterAuth.d.ts","sourceRoot":"","sources":["../../src/data/betterAuth.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAuBxB,2FAA2F;AAC3F,eAAO,MAAM,IAAI;;;;;;;;;iBA0BwF,CAAC;AAC1G,MAAM,MAAM,IAAI,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,IAAI,CAAC,CAAC;AAEzC,6FAA6F;AAC7F,eAAO,MAAM,OAAO;;;;;;;;;;;;iBAqCqF,CAAC;AAC1G,MAAM,MAAM,OAAO,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,OAAO,CAAC,CAAC;AAE/C,mGAAmG;AACnG,eAAO,MAAM,OAAO;;;;;;;;;;;;;;;iBAyCqF,CAAC;AAC1G,MAAM,MAAM,OAAO,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,OAAO,CAAC,CAAC;AAE/C,8FAA8F;AAC9F,eAAO,MAAM,YAAY;;;;;;;iBAmBtB,CAAC;AACJ,MAAM,MAAM,YAAY,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,YAAY,CAAC,CAAC;AAEzD,gGAAgG;AAChG,eAAO,MAAM,IAAI;;;;;;;;iBA8Bd,CAAC;AACJ,MAAM,MAAM,IAAI,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,IAAI,CAAC,CAAC;AAEzC,sHAAsH;AACtH,eAAO,MAAM,SAAS;;;;;iBAcnB,CAAC;AACJ,MAAM,MAAM,SAAS,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,SAAS,CAAC,CAAC"}
@@ -29,7 +29,7 @@ const User = z.object({
29
29
  name: z.string().describe("The user's display name, supplied by the provider profile or at sign-up."),
30
30
  email: z.string().describe("The user's email address. Unique across all users; the identity key for passwordless sign-in."),
31
31
  emailVerified: SQLiteBoolean.describe("Whether the email has been verified. Stored as `0|1`; magic-link/OTP sign-in sets it true."),
32
- image: z.string().nullable().describe("URL of the user's avatar from a social profile, or null."),
32
+ image: z.string().nullable().describe("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."),
33
33
  locale: Locale.nullable().describe("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."),
34
34
  createdAt: BetterAuthDate.describe("When the user record was created. ISO-8601 text in SQLite; a `Date` in app code."),
35
35
  updatedAt: BetterAuthDate.describe("When the user record was last updated. ISO-8601 text in SQLite; a `Date` in app code.")
@@ -1 +1 @@
1
- {"version":3,"file":"devLoginRoute.d.ts","sourceRoot":"","sources":["../../src/http/devLoginRoute.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAE7E,OAAO,EAAE,KAAK,UAAU,EAAsC,MAAM,gCAAgC,CAAC;AAKrG,OAAO,KAAK,EAAW,IAAI,EAAE,MAAM,MAAM,CAAC;AAE1C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAWhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,UAAU,EAClB,GAAG,GAAE,UAAyB,GAC7B,CAAC,GAAG,EAAE,IAAI,CAAC,YAAY,CAAC,KAAK,IAAI,CAQnC"}
1
+ {"version":3,"file":"devLoginRoute.d.ts","sourceRoot":"","sources":["../../src/http/devLoginRoute.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAC7E,OAAO,EAAE,KAAK,UAAU,EAAsC,MAAM,gCAAgC,CAAC;AAMrG,OAAO,KAAK,EAAW,IAAI,EAAE,MAAM,MAAM,CAAC;AAE1C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAOhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,UAAU,EAClB,GAAG,GAAE,UAAyB,GAC7B,CAAC,GAAG,EAAE,IAAI,CAAC,YAAY,CAAC,KAAK,IAAI,CAYnC"}
@@ -1,15 +1,17 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
+ import { Session } from "../data/betterAuth.js";
3
4
  import { authDatabase } from "../data/tables.js";
4
5
  import { resolveSessionSecret } from "../instance/secrets.js";
5
- import { DEV_SESSION_COOKIE_NAME, DEV_SESSION_TOKEN_PREFIX, secretFingerprint, signCookieValue } from "../seeds/devSession.js";
6
+ import { DEV_SESSION_COOKIE_NAME, signCookieValue, verifyDevLoginClaim } from "../seeds/devSession.js";
6
7
  import { resolveDb } from "./resolve.js";
7
- import { NotFoundError, fromZodError } from "@pithy-sh/core/src/error/pithyError";
8
+ import { NotFoundError } from "@pithy-sh/core/src/error/pithyError";
8
9
  import { z } from "zod";
9
- import { JsonDate } from "@pithy-sh/core/src/data/codecs";
10
10
  import { ambientEnv, compositionEnvironment } from "@pithy-sh/core/src/env/ambient";
11
+ import { zValidator } from "@hono/zod-validator";
11
12
  import { isContinuousIntegration } from "@pithy-sh/core/src/env/ci";
12
- import { DEV_LOGIN_ROUTE } from "@pithy-sh/core/src/seed/devLogin";
13
+ import { validationHook } from "@pithy-sh/core/src/http/validation";
14
+ import { DEV_LOGIN_CLAIM_PARAM, DEV_LOGIN_ROUTE } from "@pithy-sh/core/src/seed/devLogin";
13
15
  //#region src/http/devLoginRoute.ts
14
16
  /**
15
17
  * `GET /__pithy/dev-login` — the seeded session, as a redirect that signs the browser in.
@@ -51,22 +53,10 @@ function registerDevLoginRoute(wiring, env = ambientEnv()) {
51
53
  return (app) => {
52
54
  if (compositionEnvironment(env) !== "dev") return;
53
55
  if (isContinuousIntegration(env)) return;
54
- app.get(DEV_LOGIN_ROUTE, (c) => serveDevLogin(c, wiring));
56
+ app.get(DEV_LOGIN_ROUTE, zValidator("query", DevLoginQuery, validationHook), (c) => serveDevLogin(c, wiring, c.req.valid("query")[DEV_LOGIN_CLAIM_PARAM]));
55
57
  };
56
58
  }
57
59
  /**
58
- * The seeded session row, narrowed to what handing it to a browser needs — and validated, because a D1
59
- * row is a boundary like any other. `z.input` is the stored row (ISO-8601 text); `z.output` the app shape.
60
- */
61
- const DevSessionRow = z.object({
62
- token: z.string().min(1).describe("The seeded session's opaque token — signed with this environment's secret to make the cookie."),
63
- expiresAt: JsonDate.describe("When the seeded session expires. ISO-8601 text in SQLite; a `Date` here.")
64
- }).describe("A seeded dev session, narrowed to the two columns the dev-login redirect needs.");
65
- /** How long the browser is told to keep the cookie: whatever is left of the seeded session, never longer. */
66
- function maxAgeSeconds(expiresAt, now) {
67
- return Math.floor((expiresAt.getTime() - now.getTime()) / 1e3);
68
- }
69
- /**
70
60
  * The refusal when there is nothing to sign in as. A 404, because the honest answer is that this
71
61
  * composition has no seeded session — not that the caller got something wrong.
72
62
  *
@@ -83,27 +73,50 @@ function noSeededSession() {
83
73
  return new NotFoundError({ message: "No dev login has been seeded for this environment. Run pithy seed, then open this URL again." });
84
74
  }
85
75
  /**
86
- * Serve the seeded session as a `Set-Cookie` and a redirect to `/`.
76
+ * What the route takes: the claim, in the query.
87
77
  *
88
- * The row is found by the prefix every seeded session carries and **verified against the current
89
- * signing secret's fingerprint**, which the seed puts in the token for this exact purpose. A session
90
- * minted before a rotation is a cookie Better Auth will reject, so handing it over would sign nobody in
91
- * and send the developer hunting through auth for a bug that is a stale seed. Unfound is unfound.
78
+ * **Optional, and that is deliberate.** A required field would make a missing claim a 400 and a wrong one
79
+ * a 404, and the difference between those two answers is exactly what this route must not tell anybody.
80
+ * Declaring it optional puts every refusal in the handler, where there is one of them.
81
+ *
82
+ * Bounded because an unbounded query parameter is an unbounded read. The ceiling is far above any claim
83
+ * this seed mints; a value past it is refused for its length, which tells the sender only about the
84
+ * request they just made.
85
+ */
86
+ const DevLoginQuery = z.object({ [DEV_LOGIN_CLAIM_PARAM]: z.string().max(4096).optional().describe("The signed claim naming the user to sign in as, as `pithy seed` wrote it into the URL.") }).describe("The dev-login route's query: a claim, or nothing and the same refusal as a wrong one.");
87
+ /**
88
+ * Exchange a claim for a session, as a `Set-Cookie` and a redirect to `/`.
92
89
  *
93
90
  * Nothing about the cookie is logged, and nothing is written to a response body: the value exists in
94
- * this handler and in the browser, and in no third place.
91
+ * this handler and in the browser, and in no third place. The claim that bought it is in the URL, which
92
+ * is the one place it has to be — `dev/devLogin.ts` in the CLI carries why, and keeps it out of every
93
+ * printed line it can.
95
94
  */
96
- async function serveDevLogin(c, wiring) {
95
+ async function serveDevLogin(c, wiring, presented) {
96
+ if (!presented) throw noSeededSession();
97
97
  const secret = await resolveSessionSecret(c.env);
98
- const fingerprint = await secretFingerprint(secret);
99
- const found = await authDatabase(resolveDb(c.env, wiring.config.database)).selectFrom("pithyAuthSessions").select(["token", "expiresAt"]).where("token", "like", `${DEV_SESSION_TOKEN_PREFIX}%-${fingerprint}`).orderBy("createdAt", "desc").limit(1).executeTakeFirst();
100
- if (!found) throw noSeededSession();
101
- const parsed = DevSessionRow.safeParse(found);
102
- if (!parsed.success) throw fromZodError(parsed.error, { message: "The seeded dev session is not readable. Run pithy seed to mint a fresh one." });
103
- const row = parsed.data;
104
- const maxAge = maxAgeSeconds(row.expiresAt, /* @__PURE__ */ new Date());
105
- if (maxAge <= 0) throw noSeededSession();
106
- const value = await signCookieValue(row.token, secret);
98
+ const now = /* @__PURE__ */ new Date();
99
+ const claim = await verifyDevLoginClaim(presented, secret, now);
100
+ if (!claim) throw noSeededSession();
101
+ const db = authDatabase(resolveDb(c.env, wiring.config.database));
102
+ if (!await db.selectFrom("pithyAuthUsers").select("id").where("id", "=", claim.userId).executeTakeFirst()) throw noSeededSession();
103
+ const token = crypto.randomUUID();
104
+ const expiresAt = new Date(now.getTime() + wiring.config.sessionExpiresIn * 1e3);
105
+ await db.insertInto("pithyAuthSessions").values(Session.encode({
106
+ id: crypto.randomUUID(),
107
+ token,
108
+ userId: claim.userId,
109
+ expiresAt,
110
+ createdAt: now,
111
+ updatedAt: now,
112
+ ipAddress: "127.0.0.1",
113
+ userAgent: "pithy dev login",
114
+ deviceId: null,
115
+ familyId: null,
116
+ authenticatedAt: now
117
+ })).execute();
118
+ const value = await signCookieValue(token, secret);
119
+ const maxAge = Math.floor((expiresAt.getTime() - now.getTime()) / 1e3);
107
120
  const cookie = `${DEV_SESSION_COOKIE_NAME}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}`;
108
121
  return c.body(null, 302, {
109
122
  "Set-Cookie": cookie,
@@ -69,8 +69,11 @@ async function buildAuthInstance(c, wiring) {
69
69
  resolveProvider(cfg.github.enabled, () => resolveGithubCredentials(env))
70
70
  ]);
71
71
  const expiresMinutes = Math.max(1, Math.round(cfg.verificationExpiresIn / 60));
72
+ const d1 = resolveDb(c.env, cfg.database);
73
+ const listener = wiring.onSessionRevoked;
72
74
  return makeAuth({
73
- db: authDatabase(resolveDb(c.env, cfg.database)),
75
+ db: authDatabase(d1),
76
+ ...listener ? { onSessionRevoked: (session) => listener(session, d1) } : {},
74
77
  secret,
75
78
  baseURL: baseURLResolver(cfg.baseURL)(c.req.raw),
76
79
  locale: c.var.locale?.catalogLocale ?? null,
@@ -1 +1 @@
1
- {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../src/http/routes.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAM7E,OAAO,KAAK,EAAW,IAAI,EAAE,MAAM,MAAM,CAAC;AAE1C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAuBhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,UAAU,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,YAAY,CAAC,KAAK,IAAI,CAwCtF"}
1
+ {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../src/http/routes.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAO7E,OAAO,KAAK,EAAW,IAAI,EAAE,MAAM,MAAM,CAAC;AAE1C,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAwBhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,UAAU,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,YAAY,CAAC,KAAK,IAAI,CA4CtF"}
@@ -4,17 +4,19 @@ import { authDatabase } from "../data/tables.js";
4
4
  import { correlation, emitDenied, emitDeviceRevoked, emitTokenRefresh, emitTokenReuseDetected } from "../audit/emit.js";
5
5
  import { deleteDevice, deviceSessionTokens, listDevices } from "../device/registry.js";
6
6
  import { requireFreshAuthentication } from "./providerFreshness.js";
7
+ import { PROFILE_IMAGE_PATH } from "../profile/profile.js";
7
8
  import { getAuthInstance, resolveDb } from "./resolve.js";
8
9
  import { requireAuth } from "./middleware.js";
9
10
  import { consumeSession, findConsumedToken, pruneConsumedTokens, recordConsumedToken, revokeFamily } from "../token/rotation.js";
10
11
  import { RevokeDeviceBody } from "./schemas.js";
11
12
  import { registerAuthAdminRoutes } from "./adminRoutes.js";
12
13
  import { apiErrorToPithy } from "./errors.js";
13
- import { UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
14
+ import { NotFoundError, UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
14
15
  import { TURNSTILE_LOGIN_ACTION } from "@pithy-sh/turnstile/src/config/config";
15
16
  import { zValidator } from "@hono/zod-validator";
16
- import { requireSameOrigin } from "@pithy-sh/core/src/http/sameOrigin";
17
17
  import { validationHook } from "@pithy-sh/core/src/http/validation";
18
+ import { STORED_IMAGE_HEADERS, storedImageBytes } from "@pithy-sh/core/src/image/storedImage";
19
+ import { requireSameOrigin } from "@pithy-sh/core/src/http/sameOrigin";
18
20
  import { turnstile } from "@pithy-sh/turnstile/src/http/middleware";
19
21
  //#region src/http/routes.ts
20
22
  function db(c, wiring) {
@@ -66,6 +68,7 @@ function createAuthRoutes(wiring) {
66
68
  app.post(`${base}/devices/revoke`, requireAuth(), csrf, zValidator("json", RevokeDeviceBody, validationHook), (c) => revokeMyDevice(c, wiring, c.req.valid("json")));
67
69
  app.post(`${base}/link-social`, requireFreshAuthentication("link"), (c) => handleBetterAuth(c, wiring));
68
70
  app.post(`${base}/unlink-account`, requireFreshAuthentication("unlink"), (c) => handleBetterAuth(c, wiring));
71
+ app.get(`${base}${PROFILE_IMAGE_PATH}`, requireAuth(), (c) => serveMyImage(c, wiring));
69
72
  registerAuthAdminRoutes(wiring)(app);
70
73
  app.all(`${base}/*`, (c) => handleBetterAuth(c, wiring));
71
74
  };
@@ -271,5 +274,40 @@ async function revokeMyDevice(c, wiring, body) {
271
274
  });
272
275
  return c.json({ revoked: tokens.length });
273
276
  }
277
+ /**
278
+ * Serve the signed-in caller's own stored picture.
279
+ *
280
+ * **There is no id in the path, and that is the security design rather than a simplification.** A
281
+ * serving route addressed by user id has to answer *is this caller entitled to see this person*, and
282
+ * this capability has no such notion — everyone signed in is a peer, so any answer it invented would be
283
+ * either an enumeration oracle or a guess. The subject here is the session, so there is nothing to
284
+ * enumerate. A roster of *other* people's faces is a tenancy question, and `@pithy-sh/organization`
285
+ * answers it with membership, through the same core helpers.
286
+ *
287
+ * **A vector is refused rather than served with headers.** `storedImageBytes` answers null for one and
288
+ * this 404s on null — so there is no arrangement of parameters that makes this origin return an SVG by
289
+ * navigation, which would run script in it. `@pithy-sh/core/src/image/storedImage` carries the full
290
+ * argument.
291
+ *
292
+ * A provider link 404s too, for the same reason it is not this origin's to serve: it is already a URL
293
+ * somewhere else, and `userImageSource` hands the client that URL directly rather than this path.
294
+ *
295
+ * The response is `immutable` because `userImageSource` puts the row's `updatedAt` in the query, and
296
+ * `private` because it was authorized against a session.
297
+ */
298
+ async function serveMyImage(c, wiring) {
299
+ const auth = c.var.auth;
300
+ if (!auth) throw new UnauthorizedError({ message: "Sign in to see this." });
301
+ const row = await db(c, wiring).selectFrom("pithyAuthUsers").select(["image"]).where("id", "=", auth.userId).executeTakeFirst();
302
+ const bytes = storedImageBytes(row?.image ?? null);
303
+ if (!bytes) throw new NotFoundError({
304
+ message: "No picture to show.",
305
+ detail: `user ${auth.userId}: ${row === void 0 || row.image === null ? "no stored picture" : "picture is linked or a vector, neither served by URL"}`
306
+ });
307
+ return new Response(bytes.body, { headers: {
308
+ "content-type": bytes.type,
309
+ ...STORED_IMAGE_HEADERS
310
+ } });
311
+ }
274
312
  //#endregion
275
313
  export { createAuthRoutes };
@@ -91,6 +91,24 @@ export interface AuthInstanceDeps<Plugins extends readonly BetterAuthPlugin[] =
91
91
  resolveGithubUserInfo?: GithubUserInfoResolver;
92
92
  /** Audit seam — emits `auth/*` events. A no-op when the audit capability is absent. */
93
93
  emit: AuditEmit;
94
+ /**
95
+ * Called when a session row is deleted — a sign-out, a revoke, an admin ending somebody's devices.
96
+ *
97
+ * **The seam exists because a session id is a key other capabilities hang state on**, and nothing
98
+ * else tells them it has gone. `@pithy-sh/organization` keys its acting selection by session id and
99
+ * states that signing out must take it with it; without this there was no moment at which it could,
100
+ * so every sign-in/sign-out cycle left an orphan row in a table with no TTL and no sweep.
101
+ *
102
+ * Wired by the project that composes both — a capability does not reach into another, and the
103
+ * direction is wrong anyway: tenancy depends on auth, not the reverse.
104
+ *
105
+ * **Non-fatal by contract.** By the time this runs the session is already gone; a failure here must
106
+ * not turn a completed sign-out into an error the caller retries. Implementations swallow their own.
107
+ */
108
+ onSessionRevoked?: (session: {
109
+ id: string;
110
+ userId: string;
111
+ }) => Promise<void>;
94
112
  /**
95
113
  * The adopter's additional Better Auth plugins, from `auth({ plugins: [...] })`. Composed **after**
96
114
  * the kit's own, never in place of one — `assertAdditivePlugins` has already refused a list that
@@ -149,7 +167,28 @@ export declare function makeAuth<const Plugins extends readonly BetterAuthPlugin
149
167
  emailVerified: boolean;
150
168
  name: string;
151
169
  image?: string | null | undefined;
152
- } & Record<string, unknown>) => Promise<void>;
170
+ } & Record<string, unknown>) => Promise<{
171
+ data: {
172
+ id: string;
173
+ createdAt: Date;
174
+ updatedAt: Date;
175
+ email: string;
176
+ emailVerified: boolean;
177
+ name: string;
178
+ image?: string | null | undefined;
179
+ };
180
+ } | undefined>;
181
+ };
182
+ update: {
183
+ before: (user: Partial<{
184
+ id: string;
185
+ createdAt: Date;
186
+ updatedAt: Date;
187
+ email: string;
188
+ emailVerified: boolean;
189
+ name: string;
190
+ image?: string | null | undefined;
191
+ }> & Record<string, unknown>) => Promise<void>;
153
192
  };
154
193
  };
155
194
  session: {
@@ -211,6 +250,29 @@ export declare function makeAuth<const Plugins extends readonly BetterAuthPlugin
211
250
  };
212
251
  }>;
213
252
  };
253
+ delete: {
254
+ /**
255
+ * Tell whoever keyed state on this session that it has gone.
256
+ *
257
+ * A sign-out, a revoke, an admin ending somebody's devices — all of them land here, which is
258
+ * why the seam is on the row rather than on the sign-out endpoint. A handler wired to one
259
+ * endpoint would miss the other three, and the row is what the state was keyed by.
260
+ *
261
+ * **After, not before.** The session is already gone when this runs, so a slow or failing
262
+ * listener cannot hold up or refuse a sign-out — and it swallows its own failure for the same
263
+ * reason the audit emit does: the thing it reports has already happened.
264
+ */
265
+ after: (session: {
266
+ id: string;
267
+ createdAt: Date;
268
+ updatedAt: Date;
269
+ userId: string;
270
+ expiresAt: Date;
271
+ token: string;
272
+ ipAddress?: string | null | undefined;
273
+ userAgent?: string | null | undefined;
274
+ } & Record<string, unknown>) => Promise<void>;
275
+ };
214
276
  };
215
277
  };
216
278
  hooks: {
@@ -1 +1 @@
1
- {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../src/instance/auth.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mCAAmC,CAAC;AACnE,OAAO,EAAE,KAAK,gBAAgB,EAAc,MAAM,aAAa,CAAC;AAIhE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAGnD,OAAO,EAAyB,KAAK,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAEtF,OAAO,EAEL,KAAK,iBAAiB,EACtB,KAAK,gBAAgB,EAEtB,MAAM,aAAa,CAAC;AA6BrB,wBAAgB,eAAe,CAAC,IAAI,EAAE,gBAAgB,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,CAoD3F;AAED;;;;;;;;;GASG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE;IAAE,aAAa,CAAC,EAAE,OAAO,GAAG,IAAI,CAAA;CAAE,GAAG,OAAO,CAEpF;AAED;;;GAGG;AACH,MAAM,MAAM,gBAAgB,GACxB;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,WAAW,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GACjE;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,KAAK,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC;AAElD,yGAAyG;AACzG,MAAM,MAAM,aAAa,GAAG,CAAC,OAAO,EAAE,gBAAgB,KAAK,OAA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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAUtD"}
@@ -4,6 +4,7 @@ import { emitAfterRequest, emitProviderUnavailable } from "../audit/emit.js";
4
4
  import { KIT_SESSION_FIELDS, KIT_USER_FIELDS } from "../data/kitFields.js";
5
5
  import { parseDeviceMeta, registerDevice } from "../device/registry.js";
6
6
  import "../http/providerFreshness.js";
7
+ import { refuseUnsafeProfile, sanitizeProfile } from "../profile/profile.js";
7
8
  import { defaultGithubUserInfo } from "./githubUserInfo.js";
8
9
  import { kitPlugins } from "./plugins.js";
9
10
  import { providerUnavailable, unavailableProviderFor } from "./providers.js";
@@ -84,6 +85,23 @@ function isUnverifiedSignup(user) {
84
85
  return user.emailVerified !== true;
85
86
  }
86
87
  /**
88
+ * Refuse a write whose `name` or `image` is not a shape this kit will render, with a 400 naming the
89
+ * field.
90
+ *
91
+ * The decision is `../profile/profile.ts`'s and is pure; this is the half that needs `APIError`, which
92
+ * is what turns a refusal into a 400 instead of a row that throws on every later read. That failure
93
+ * mode is the one `../data/kitFields.ts` already documents for `locale`: a bad value written once makes
94
+ * the *listing* fail for every operator rather than only for its author.
95
+ */
96
+ function refuseUnsafeProfileFields(user) {
97
+ const refusal = refuseUnsafeProfile(user);
98
+ if (!refusal) return;
99
+ throw new APIError("BAD_REQUEST", {
100
+ code: "INVALID_PROFILE_FIELD",
101
+ message: refusal.message
102
+ });
103
+ }
104
+ /**
87
105
  * Build the Better-Auth instance for one request.
88
106
  *
89
107
  * Passwordless only — `emailAndPassword` is never enabled. The Kysely adapter wraps our shared
@@ -107,53 +125,86 @@ function makeAuth(deps) {
107
125
  advanced: { database: { generateId: () => crypto.randomUUID() } },
108
126
  onAPIError: { throw: true },
109
127
  databaseHooks: {
110
- user: { create: { before: async (user) => {
111
- if (isUnverifiedSignup(user)) throw new APIError("FORBIDDEN", {
112
- code: "EMAIL_NOT_VERIFIED",
113
- message: "This email isn't verified by the provider. Sign in with a magic link to verify it, then connect the provider."
114
- });
115
- } } },
116
- session: { create: {
117
- /**
118
- * Stamp when this session's holder authenticated, and bind the session to its device.
119
- *
120
- * **`authenticatedAt` is stamped here and nowhere else.** A sign-in is the only event that is
121
- * an authentication; `/token/rotate` carries the value forward through `createSession`'s
122
- * override instead, which is why a rotated session keeps the original instant. A field
123
- * `defaultValue` would have looked equivalent and is not: `getSessionDefaultFields` is spread
124
- * into the row *after* the caller's override, so it would overwrite the carried value and
125
- * silently restore the defect the column exists to fix (#558).
126
- *
127
- * A value already on the row is left alone — that is the rotation, passing its own.
128
- *
129
- * **Every other `createSession` is treated as an authentication, which is right for all of
130
- * them the kit composes.** `better-auth/plugins/admin`'s `impersonateUser` would be the
131
- * exception — an admin impersonating somebody would get a freshly-stamped session and could
132
- * attach a provider to that account — but the kit composes no admin plugin, so it is a note
133
- * for whoever does rather than a live path.
134
- *
135
- * Device binding only fires when the request carried device headers; a rotation passes
136
- * `deviceId` by override for the same reason.
137
- */
128
+ user: {
129
+ create: { before: async (user) => {
130
+ if (isUnverifiedSignup(user)) throw new APIError("FORBIDDEN", {
131
+ code: "EMAIL_NOT_VERIFIED",
132
+ message: "This email isn't verified by the provider. Sign in with a magic link to verify it, then connect the provider."
133
+ });
134
+ const safe = sanitizeProfile(user);
135
+ if (Object.keys(safe).length > 0) return { data: {
136
+ ...user,
137
+ ...safe
138
+ } };
139
+ } },
140
+ update: { before: async (user) => {
141
+ refuseUnsafeProfileFields(user);
142
+ } }
143
+ },
144
+ session: {
145
+ create: {
146
+ /**
147
+ * Stamp when this session's holder authenticated, and bind the session to its device.
148
+ *
149
+ * **`authenticatedAt` is stamped here and nowhere else.** A sign-in is the only event that is
150
+ * an authentication; `/token/rotate` carries the value forward through `createSession`'s
151
+ * override instead, which is why a rotated session keeps the original instant. A field
152
+ * `defaultValue` would have looked equivalent and is not: `getSessionDefaultFields` is spread
153
+ * into the row *after* the caller's override, so it would overwrite the carried value and
154
+ * silently restore the defect the column exists to fix (#558).
155
+ *
156
+ * A value already on the row is left alone — that is the rotation, passing its own.
157
+ *
158
+ * **Every other `createSession` is treated as an authentication, which is right for all of
159
+ * them the kit composes.** `better-auth/plugins/admin`'s `impersonateUser` would be the
160
+ * exception — an admin impersonating somebody would get a freshly-stamped session and could
161
+ * attach a provider to that account — but the kit composes no admin plugin, so it is a note
162
+ * for whoever does rather than a live path.
163
+ *
164
+ * Device binding only fires when the request carried device headers; a rotation passes
165
+ * `deviceId` by override for the same reason.
166
+ */
138
167
  before: async (session, ctx) => {
139
- const carried = session.authenticatedAt;
140
- const authenticatedAt = carried !== void 0 ? carried : /* @__PURE__ */ new Date();
141
- const meta = ctx?.headers ? parseDeviceMeta(ctx.headers) : void 0;
142
- if (!meta) return { data: {
143
- ...session,
144
- authenticatedAt
145
- } };
146
- await registerDevice(deps.db, meta, {
147
- userId: session.userId,
148
- lastIp: session.ipAddress ?? null,
149
- now: /* @__PURE__ */ new Date()
150
- });
151
- return { data: {
152
- ...session,
153
- deviceId: meta.id,
154
- authenticatedAt
155
- } };
156
- } } }
168
+ const carried = session.authenticatedAt;
169
+ const authenticatedAt = carried !== void 0 ? carried : /* @__PURE__ */ new Date();
170
+ const meta = ctx?.headers ? parseDeviceMeta(ctx.headers) : void 0;
171
+ if (!meta) return { data: {
172
+ ...session,
173
+ authenticatedAt
174
+ } };
175
+ await registerDevice(deps.db, meta, {
176
+ userId: session.userId,
177
+ lastIp: session.ipAddress ?? null,
178
+ now: /* @__PURE__ */ new Date()
179
+ });
180
+ return { data: {
181
+ ...session,
182
+ deviceId: meta.id,
183
+ authenticatedAt
184
+ } };
185
+ } },
186
+ delete: {
187
+ /**
188
+ * Tell whoever keyed state on this session that it has gone.
189
+ *
190
+ * A sign-out, a revoke, an admin ending somebody's devices — all of them land here, which is
191
+ * why the seam is on the row rather than on the sign-out endpoint. A handler wired to one
192
+ * endpoint would miss the other three, and the row is what the state was keyed by.
193
+ *
194
+ * **After, not before.** The session is already gone when this runs, so a slow or failing
195
+ * listener cannot hold up or refuse a sign-out — and it swallows its own failure for the same
196
+ * reason the audit emit does: the thing it reports has already happened.
197
+ */
198
+ after: async (session) => {
199
+ if (!deps.onSessionRevoked) return;
200
+ try {
201
+ await deps.onSessionRevoked({
202
+ id: String(session.id),
203
+ userId: String(session.userId)
204
+ });
205
+ } catch {}
206
+ } }
207
+ }
157
208
  },
158
209
  hooks: {
159
210
  /**
@@ -11,8 +11,16 @@ import type { Migration } from "kysely/migration";
11
11
  * every identifier in the emitted DDL (CLAUDE.md §Data layer) — and the same plugin lets Better
12
12
  * Auth's camelCase queries land on these snake_case columns. Better-Auth `date` columns are **text**
13
13
  * (it stores ISO-8601 strings on SQLite; ISO sorts chronologically); Pithy's own device timestamps
14
- * are **integer** ms-epoch. Foreign keys are omitted to match the repo convention (D1 does not enforce
15
- * them without a per-connection PRAGMA); linkage is by indexed id columns.
14
+ * are **integer** ms-epoch. Linkage is by indexed id columns.
15
+ *
16
+ * **No foreign keys across a capability boundary — a choice, not a limitation.** D1 *does* enforce
17
+ * them: `PRAGMA foreign_keys` is on, a cascade fires, and an orphan insert is refused with
18
+ * `FOREIGN KEY constraint failed`. `packages/core/src/data/foreignKeys.workers.test.ts` measures both
19
+ * directions, because this is the kind of claim that rots quietly. What is traded away is real, and the
20
+ * reason is the boundary rather than the platform: a constraint from one capability's table to another's
21
+ * binds two release cadences together and breaks the day either moves to its own database. Within a
22
+ * single capability's own tables a foreign key is available and is simply not used here — worth
23
+ * revisiting per table rather than as a rule.
16
24
  *
17
25
  * `down` is the tested inverse — indexes then tables, in reverse creation order (D1 has no
18
26
  * transactional DDL, so order matters).
@@ -1 +1 @@
1
- {"version":3,"file":"0001_init.d.ts","sourceRoot":"","sources":["../../src/migrations/0001_init.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAElD;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,eAAO,MAAM,cAAc,EAAE,SA+L5B,CAAC;AAEF,oHAAoH;AACpH,eAAO,MAAM,oBAAoB,MAAM,CAAC"}
1
+ {"version":3,"file":"0001_init.d.ts","sourceRoot":"","sources":["../../src/migrations/0001_init.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAElD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,eAAO,MAAM,cAAc,EAAE,SA+L5B,CAAC;AAEF,oHAAoH;AACpH,eAAO,MAAM,oBAAoB,MAAM,CAAC"}