@pithy-sh/auth 0.4.0 → 0.6.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.
@@ -94,14 +94,18 @@ export declare function emitProviderUnavailable(emit: AuditEmit, context: {
94
94
  provider: string;
95
95
  headers: Headers | undefined;
96
96
  }): Promise<void>;
97
+ /** Which direction of provider change was refused — the two read very differently in a trail. */
98
+ export type ProviderChange = "link" | "unlink";
97
99
  /**
98
- * Emit a `session_not_fresh` event — an attempt to attach a provider on an authentic but stale session.
100
+ * Emit a `session_not_fresh` event — an attempt to change connected accounts on an authentic but stale
101
+ * credential.
99
102
  *
100
103
  * `actorType: "user"` rather than `anonymous`, unlike `emitProviderUnavailable`: this caller is
101
104
  * authenticated, and the user id is the whole value of the row. Counting these per user is how a stolen
102
- * credential being walked toward a link becomes visible.
105
+ * credential being walked toward an account change becomes visible.
103
106
  */
104
- export declare function emitLinkSessionNotFresh(emit: AuditEmit, context: {
107
+ export declare function emitProviderChangeNotFresh(emit: AuditEmit, context: {
108
+ change: ProviderChange;
105
109
  userId: string;
106
110
  sessionId: string;
107
111
  headers: Headers | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"emit.d.ts","sourceRoot":"","sources":["../../src/audit/emit.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mCAAmC,CAAC;AAGnE;;;;;;;GAOG;AAEH,gFAAgF;AAChF,wBAAgB,WAAW,CAAC,OAAO,EAAE,OAAO,GAAG,SAAS,GAAG;IAAE,EAAE,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,CAK7F;AAUD,uGAAuG;AACvG,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,OAAO,GAAG,SAAS,CAAC;IAC7B,UAAU,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAA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IACf,OAAO,EAAE,MAAM,CAAC;IAChB,YAAY,EAAE,MAAM,CAAC;IACrB,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACpC,GACA,OAAO,CAAC,IAAI,CAAC,CAaf;AAED;;;;;;;;;;;;GAYG;AACH,wBAAsB,uBAAuB,CAC3C,IAAI,EAAE,SAAS,EACf,OAAO,EAAE;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,OAAO,GAAG,SAAS,CAAA;CAAE,GAC1D,OAAO,CAAC,IAAI,CAAC,CASf;AAED,iGAAiG;AACjG,MAAM,MAAM,cAAc,GAAG,MAAM,GAAG,QAAQ,CAAC;AAE/C;;;;;;;GAOG;AACH,wBAAsB,0BAA0B,CAC9C,IAAI,EAAE,SAAS,EACf,OAAO,EAAE;IAAE,MAAM,EAAE,cAAc,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,OAAO,GAAG,SAAS,CAAA;CAAE,GACnG,OAAO,CAAC,IAAI,CAAC,CAcf;AAED,0EAA0E;AAC1E,wBAAsB,UAAU,CAC9B,IAAI,EAAE,SAAS,EACf,OAAO,EAAE;IAAE,EAAE,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,GAC5D,OAAO,CAAC,IAAI,CAAC,CASf"}
@@ -158,13 +158,14 @@ async function emitProviderUnavailable(emit, context) {
158
158
  });
159
159
  }
160
160
  /**
161
- * Emit a `session_not_fresh` event — an attempt to attach a provider on an authentic but stale session.
161
+ * Emit a `session_not_fresh` event — an attempt to change connected accounts on an authentic but stale
162
+ * credential.
162
163
  *
163
164
  * `actorType: "user"` rather than `anonymous`, unlike `emitProviderUnavailable`: this caller is
164
165
  * authenticated, and the user id is the whole value of the row. Counting these per user is how a stolen
165
- * credential being walked toward a link becomes visible.
166
+ * credential being walked toward an account change becomes visible.
166
167
  */
167
- async function emitLinkSessionNotFresh(emit, context) {
168
+ async function emitProviderChangeNotFresh(emit, context) {
168
169
  await safeEmit(emit, {
169
170
  action: AuthAuditActions.sessionNotFresh,
170
171
  outcome: "denied",
@@ -172,6 +173,7 @@ async function emitLinkSessionNotFresh(emit, context) {
172
173
  actorType: "user",
173
174
  actorId: context.userId,
174
175
  sessionId: context.sessionId,
176
+ metadata: { change: context.change },
175
177
  ...correlation(context.headers)
176
178
  });
177
179
  }
@@ -187,4 +189,4 @@ async function emitDenied(emit, context) {
187
189
  });
188
190
  }
189
191
  //#endregion
190
- export { correlation, emitAfterRequest, emitControlPlaneAction, emitDenied, emitDeviceRevoked, emitLinkSessionNotFresh, emitProviderUnavailable, emitTokenRefresh, emitTokenReuseDetected };
192
+ export { correlation, emitAfterRequest, emitControlPlaneAction, emitDenied, emitDeviceRevoked, emitProviderChangeNotFresh, emitProviderUnavailable, emitTokenRefresh, emitTokenReuseDetected };
@@ -1,17 +1,22 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
  /**
4
- * **What pays for `allowDifferentEmails`.**
4
+ * **Changing which providers can sign you in requires a recent authentication.** Both directions.
5
5
  *
6
- * A signed-in user may attach a provider whose email differs from their own. That is the right behavior
7
- * and it widens something: before it, a provider could only be linked to an account holding the same
8
- * address, so a link was self-limiting. After it, a link is a decision the session alone authorizes.
6
+ * Attaching one grants permanent access — after it a sign-in resolves by account id and the email stops
7
+ * mattering — and it is what `allowDifferentEmails: true` widened: before that, a provider could only be
8
+ * linked to an account holding the same address, so a link was self-limiting. Detaching one is the
9
+ * smaller decision, but `allowUnlinkingAll: true` means an attacker inside the window can strip *every*
10
+ * provider from an account. Neither belongs behind a credential whose age nobody checked.
9
11
  *
10
- * And Better Auth guards that decision **less** than it guards undoing it. Read the two endpoints beside
11
- * each other in `better-auth/dist/api/routes/account.mjs`: `/link-social` takes `use: [sessionMiddleware]`
12
- * — any session, any age — while `/unlink-account` takes `use: [freshSessionMiddleware]`. Attaching an
13
- * identity grants *permanent* access, because once linked a sign-in resolves by account id and the email
14
- * stops mattering; detaching one does not. The cheaper-guarded operation is the more powerful one.
12
+ * **Better Auth guards the two unevenly, and neither guard is one the kit can use.** In
13
+ * `better-auth/dist/api/routes/account.mjs`, `/link-social` takes `use: [sessionMiddleware]` — any
14
+ * session, any age — while `/unlink-account` takes `use: [freshSessionMiddleware]`, which reads
15
+ * `session.createdAt` against a `freshAge` defaulting to 24 hours. So the more powerful operation was
16
+ * the cheaper-guarded one, and the guarded one was checked against a value `/token/rotate` resets:
17
+ * `internal-adapter.mjs:275` stamps `createdAt` after the caller's override, so a row's `created_at` is
18
+ * the moment of its most recent rotation. Ordinary refreshing resets it; so does anyone holding a stolen
19
+ * refresh token.
15
20
  *
16
21
  * **It reads `authenticatedAt`, not the session's `createdAt`, and that distinction is the whole of #558.**
17
22
  * The first version of this gate read session age. `/token/rotate` stamps a successor's `createdAt` with
@@ -33,8 +38,9 @@
33
38
  import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
34
39
  import { PithyError } from "@pithy-sh/core/src/error/pithyError";
35
40
  import type { MiddlewareHandler } from "hono";
41
+ import type { ProviderChange } from "../audit/emit";
36
42
  /**
37
- * How recently the caller must have authenticated to attach a provider: **fifteen minutes.**
43
+ * How recently the caller must have authenticated to change which providers sign them in: **fifteen minutes.**
38
44
  *
39
45
  * Stated rather than inherited. Better Auth's `freshAge` default is 24 hours, which is the wrong order of
40
46
  * magnitude here — a day-old authentication is not evidence that the person at the keyboard holds the
@@ -42,10 +48,12 @@ import type { MiddlewareHandler } from "hono";
42
48
  * trip that involves signing in to the provider first, and is short enough that a stolen credential is
43
49
  * unlikely to still be inside the window.
44
50
  *
45
- * The cost of being wrong is one re-authentication — exactly what `/unlink-account` already charges for
46
- * the smaller decision.
51
+ * **One number for both operations.** Asymmetry is arguable — linking grants access and unlinking
52
+ * removes it — but the argument cuts both ways once `allowUnlinkingAll` is on, and a second constant
53
+ * would be a second thing to keep true. The cost of being wrong in either direction is one
54
+ * re-authentication.
47
55
  */
48
- export declare const LINK_FRESH_AGE_SECONDS: number;
56
+ export declare const PROVIDER_CHANGE_FRESH_AGE_SECONDS: number;
49
57
  /**
50
58
  * Whether an authentication is recent enough to authorize attaching a provider.
51
59
  *
@@ -84,5 +92,9 @@ export declare function authenticationIsFresh(authenticatedAt: Date | string | n
84
92
  * the link half-happened.
85
93
  */
86
94
  export declare function sessionNotFresh(): PithyError;
87
- export declare function requireFreshAuthenticationToLink(now?: () => Date): MiddlewareHandler<PithyHonoEnv>;
88
- //# sourceMappingURL=linkFreshness.d.ts.map
95
+ /**
96
+ * Which direction is being refused. Carried into the audit row, because "somebody tried to attach an
97
+ * identity on a stale credential" and "somebody tried to strip one" are different things to read later.
98
+ */
99
+ export declare function requireFreshAuthentication(change: ProviderChange, now?: () => Date): MiddlewareHandler<PithyHonoEnv>;
100
+ //# sourceMappingURL=providerFreshness.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"providerFreshness.d.ts","sourceRoot":"","sources":["../../src/http/providerFreshness.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0CAA0C,CAAC;AAC7E,OAAO,EAAE,UAAU,EAAqB,MAAM,qCAAqC,CAAC;AACpF,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAC9C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAGpD;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,iCAAiC,QAAU,CAAC;AAEzD;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,eAAe,EAAE,IAAI,GAAG,MAAM,GAAG,IAAI,GAAG,SAAS,EAAE,GAAG,EAAE,IAAI,GAAG,OAAO,CAQ3G;AAED;;;;;;;;;;;;;;;;GAgBG;AACH;;;;;;;;;;GAUG;AACH,wBAAgB,eAAe,IAAI,UAAU,CAS5C;AAED;;;GAGG;AACH,wBAAgB,0BAA0B,CACxC,MAAM,EAAE,cAAc,EACtB,GAAG,GAAE,MAAM,IAAuB,GACjC,iBAAiB,CAAC,YAAY,CAAC,CAoBjC"}
@@ -1,10 +1,10 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
- import { emitLinkSessionNotFresh } from "../audit/emit.js";
3
+ import { emitProviderChangeNotFresh } from "../audit/emit.js";
4
4
  import { PithyError, UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
5
- //#region src/http/linkFreshness.ts
5
+ //#region src/http/providerFreshness.ts
6
6
  /**
7
- * How recently the caller must have authenticated to attach a provider: **fifteen minutes.**
7
+ * How recently the caller must have authenticated to change which providers sign them in: **fifteen minutes.**
8
8
  *
9
9
  * Stated rather than inherited. Better Auth's `freshAge` default is 24 hours, which is the wrong order of
10
10
  * magnitude here — a day-old authentication is not evidence that the person at the keyboard holds the
@@ -12,10 +12,12 @@ import { PithyError, UnauthorizedError } from "@pithy-sh/core/src/error/pithyErr
12
12
  * trip that involves signing in to the provider first, and is short enough that a stolen credential is
13
13
  * unlikely to still be inside the window.
14
14
  *
15
- * The cost of being wrong is one re-authentication — exactly what `/unlink-account` already charges for
16
- * the smaller decision.
15
+ * **One number for both operations.** Asymmetry is arguable — linking grants access and unlinking
16
+ * removes it — but the argument cuts both ways once `allowUnlinkingAll` is on, and a second constant
17
+ * would be a second thing to keep true. The cost of being wrong in either direction is one
18
+ * re-authentication.
17
19
  */
18
- const LINK_FRESH_AGE_SECONDS = 900;
20
+ const PROVIDER_CHANGE_FRESH_AGE_SECONDS = 900;
19
21
  /**
20
22
  * Whether an authentication is recent enough to authorize attaching a provider.
21
23
  *
@@ -64,12 +66,16 @@ function sessionNotFresh() {
64
66
  return new PithyError({
65
67
  code: "auth/session_not_fresh",
66
68
  status: 403,
67
- message: "Sign in again to connect an account. Nothing was changed.",
68
- action: "A deliberate gate: connecting a provider grants permanent access, so it requires a recent sign-in the way disconnecting one already does. See `http/linkFreshness.ts`.",
69
- detail: "session authenticatedAt is older than LINK_FRESH_AGE_SECONDS, absent, or unreadable"
69
+ message: "Sign in again to change your connected accounts. Nothing was changed.",
70
+ action: "A deliberate gate: changing which providers can sign somebody in requires a recent authentication, in both directions. See `http/providerFreshness.ts`.",
71
+ detail: "session authenticatedAt is older than PROVIDER_CHANGE_FRESH_AGE_SECONDS, absent, or unreadable"
70
72
  });
71
73
  }
72
- function requireFreshAuthenticationToLink(now = () => /* @__PURE__ */ new Date()) {
74
+ /**
75
+ * Which direction is being refused. Carried into the audit row, because "somebody tried to attach an
76
+ * identity on a stale credential" and "somebody tried to strip one" are different things to read later.
77
+ */
78
+ function requireFreshAuthentication(change, now = () => /* @__PURE__ */ new Date()) {
73
79
  return async (c, next) => {
74
80
  const auth = c.var.auth;
75
81
  if (!auth) throw new UnauthorizedError({
@@ -77,7 +83,8 @@ function requireFreshAuthenticationToLink(now = () => /* @__PURE__ */ new Date()
77
83
  action: "Sign in and retry with a valid session or bearer token."
78
84
  });
79
85
  if (!authenticationIsFresh(auth.authenticatedAt, now())) {
80
- await emitLinkSessionNotFresh(c.var.emit, {
86
+ await emitProviderChangeNotFresh(c.var.emit, {
87
+ change,
81
88
  userId: auth.userId,
82
89
  sessionId: auth.sessionId,
83
90
  headers: c.req.raw.headers
@@ -88,4 +95,4 @@ function requireFreshAuthenticationToLink(now = () => /* @__PURE__ */ new Date()
88
95
  };
89
96
  }
90
97
  //#endregion
91
- export { LINK_FRESH_AGE_SECONDS, authenticationIsFresh, requireFreshAuthenticationToLink, sessionNotFresh };
98
+ export { PROVIDER_CHANGE_FRESH_AGE_SECONDS, authenticationIsFresh, requireFreshAuthentication, sessionNotFresh };
@@ -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,CAuCtF"}
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"}
@@ -3,13 +3,13 @@
3
3
  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
+ import { requireFreshAuthentication } from "./providerFreshness.js";
6
7
  import { getAuthInstance, resolveDb } from "./resolve.js";
7
8
  import { requireAuth } from "./middleware.js";
8
9
  import { consumeSession, findConsumedToken, pruneConsumedTokens, recordConsumedToken, revokeFamily } from "../token/rotation.js";
9
10
  import { RevokeDeviceBody } from "./schemas.js";
10
11
  import { registerAuthAdminRoutes } from "./adminRoutes.js";
11
12
  import { apiErrorToPithy } from "./errors.js";
12
- import { requireFreshAuthenticationToLink } from "./linkFreshness.js";
13
13
  import { UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
14
14
  import { TURNSTILE_LOGIN_ACTION } from "@pithy-sh/turnstile/src/config/config";
15
15
  import { zValidator } from "@hono/zod-validator";
@@ -64,7 +64,8 @@ function createAuthRoutes(wiring) {
64
64
  app.post(`${base}/token/rotate`, csrf, (c) => rotateToken(c, wiring));
65
65
  app.get(`${base}/devices`, requireAuth(), (c) => listMyDevices(c, wiring));
66
66
  app.post(`${base}/devices/revoke`, requireAuth(), csrf, zValidator("json", RevokeDeviceBody, validationHook), (c) => revokeMyDevice(c, wiring, c.req.valid("json")));
67
- app.post(`${base}/link-social`, requireFreshAuthenticationToLink(), (c) => handleBetterAuth(c, wiring));
67
+ app.post(`${base}/link-social`, requireFreshAuthentication("link"), (c) => handleBetterAuth(c, wiring));
68
+ app.post(`${base}/unlink-account`, requireFreshAuthentication("unlink"), (c) => handleBetterAuth(c, wiring));
68
69
  registerAuthAdminRoutes(wiring)(app);
69
70
  app.all(`${base}/*`, (c) => handleBetterAuth(c, wiring));
70
71
  };
@@ -255,6 +255,20 @@ export declare function makeAuth<const Plugins extends readonly BetterAuthPlugin
255
255
  modelName: "pithyAuthSessions";
256
256
  expiresIn: number;
257
257
  updateAge: number;
258
+ /**
259
+ * Better Auth's own re-authentication window, stated rather than inherited.
260
+ *
261
+ * Its default is 24 hours, which nobody here chose, and it is the number `freshSessionMiddleware`
262
+ * holds `/unlink-account` to. Bringing it to the kit's own window means the two checks on that
263
+ * endpoint agree instead of one silently permitting a day.
264
+ *
265
+ * **It is defense in depth, not the control.** `freshSessionMiddleware` measures
266
+ * `session.createdAt`, which `/token/rotate` restamps — so narrowing it narrows a window that is
267
+ * still resettable. The control is `http/providerFreshness.ts`, which reads the authentication
268
+ * instant a rotation carries forward, and it is strictly the stricter of the two: `createdAt` is
269
+ * never older than `authenticatedAt`, so anything our gate admits this one admits too.
270
+ */
271
+ freshAge: number;
258
272
  additionalFields: {
259
273
  readonly deviceId: {
260
274
  readonly type: "string";
@@ -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;AAEnD,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,OAAO,CAAC,IAAI,CAAC,CAAC;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAUtD"}
@@ -3,6 +3,7 @@
3
3
  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
+ import "../http/providerFreshness.js";
6
7
  import { defaultGithubUserInfo } from "./githubUserInfo.js";
7
8
  import { kitPlugins } from "./plugins.js";
8
9
  import { providerUnavailable, unavailableProviderFor } from "./providers.js";
@@ -207,6 +208,20 @@ before: async (session, ctx) => {
207
208
  modelName: "pithyAuthSessions",
208
209
  expiresIn: deps.sessionExpiresIn,
209
210
  updateAge: deps.sessionUpdateAge,
211
+ /**
212
+ * Better Auth's own re-authentication window, stated rather than inherited.
213
+ *
214
+ * Its default is 24 hours, which nobody here chose, and it is the number `freshSessionMiddleware`
215
+ * holds `/unlink-account` to. Bringing it to the kit's own window means the two checks on that
216
+ * endpoint agree instead of one silently permitting a day.
217
+ *
218
+ * **It is defense in depth, not the control.** `freshSessionMiddleware` measures
219
+ * `session.createdAt`, which `/token/rotate` restamps — so narrowing it narrows a window that is
220
+ * still resettable. The control is `http/providerFreshness.ts`, which reads the authentication
221
+ * instant a rotation carries forward, and it is strictly the stricter of the two: `createdAt` is
222
+ * never older than `authenticatedAt`, so anything our gate admits this one admits too.
223
+ */
224
+ freshAge: 900,
210
225
  additionalFields: KIT_SESSION_FIELDS
211
226
  },
212
227
  account: {
@@ -103,7 +103,7 @@ Better Auth trusts what a resolver returns **verbatim**. Return GitHub's real pe
103
103
 
104
104
  Signed in, you can connect a GitHub whose primary differs from the address you signed in as. Both sides are proven at that moment — you authenticated as the account, and you just authenticated with GitHub — and the address still has to be one GitHub has verified.
105
105
 
106
- **Connecting requires a recent sign-in, not merely a valid session.** Attaching a provider grants permanent access: once linked, sign-in resolves by account id and your primary stops mattering. So it is gated the way disconnecting one already is. Sign in more than fifteen minutes ago and the connect answers `auth/session_not_fresh` and asks you to sign in again. Nothing is changed when it refuses, and the attempt is recorded in the audit trail.
106
+ **Changing your connected accounts requires a recent sign-in, not merely a valid session — in both directions.** Attaching a provider grants permanent access: once linked, sign-in resolves by account id and your primary stops mattering. Detaching one is smaller, but a provider is never the last way in here, so somebody with a stolen session could otherwise strip all of them. Sign in more than fifteen minutes ago and either answers `auth/session_not_fresh` and asks you to sign in again. Nothing is changed when it refuses, and the attempt is recorded in the audit trail.
107
107
 
108
108
  That window measures time since you **authenticated**, not the age of your session row. A `/token/rotate` continues the same authentication and carries the instant forward, so ordinary refreshing does not reset the gate — and neither does anyone holding a stolen refresh token.
109
109
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pithy-sh/auth",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -42,10 +42,10 @@
42
42
  "better-auth": "^1.7.1"
43
43
  },
44
44
  "peerDependencies": {
45
- "@pithy-sh/core": "^0.5.0",
46
- "@pithy-sh/email": "^0.3.1",
47
- "@pithy-sh/secrets": "^0.2.1",
48
- "@pithy-sh/turnstile": "^0.2.1",
45
+ "@pithy-sh/core": "^0.6.0",
46
+ "@pithy-sh/email": "^0.3.2",
47
+ "@pithy-sh/secrets": "^0.2.2",
48
+ "@pithy-sh/turnstile": "^0.2.2",
49
49
  "hono": "^4.13.2",
50
50
  "kysely": "^0.29.0",
51
51
  "zod": "^4.4.0"
package/src/audit/emit.ts CHANGED
@@ -207,16 +207,20 @@ export async function emitProviderUnavailable(
207
207
  });
208
208
  }
209
209
 
210
+ /** Which direction of provider change was refused — the two read very differently in a trail. */
211
+ export type ProviderChange = "link" | "unlink";
212
+
210
213
  /**
211
- * Emit a `session_not_fresh` event — an attempt to attach a provider on an authentic but stale session.
214
+ * Emit a `session_not_fresh` event — an attempt to change connected accounts on an authentic but stale
215
+ * credential.
212
216
  *
213
217
  * `actorType: "user"` rather than `anonymous`, unlike `emitProviderUnavailable`: this caller is
214
218
  * authenticated, and the user id is the whole value of the row. Counting these per user is how a stolen
215
- * credential being walked toward a link becomes visible.
219
+ * credential being walked toward an account change becomes visible.
216
220
  */
217
- export async function emitLinkSessionNotFresh(
221
+ export async function emitProviderChangeNotFresh(
218
222
  emit: AuditEmit,
219
- context: { userId: string; sessionId: string; headers: Headers | undefined },
223
+ context: { change: ProviderChange; userId: string; sessionId: string; headers: Headers | undefined },
220
224
  ): Promise<void> {
221
225
  await safeEmit(emit, {
222
226
  action: AuthAuditActions.sessionNotFresh,
@@ -227,6 +231,8 @@ export async function emitLinkSessionNotFresh(
227
231
  // The first-class column, not `metadata`. Counting these per user is the whole value of the row, and
228
232
  // an id buried in a JSON blob is one this action alone cannot be correlated by.
229
233
  sessionId: context.sessionId,
234
+ // Attaching an identity and stripping one are the same refusal and very different intentions.
235
+ metadata: { change: context.change },
230
236
  ...correlation(context.headers),
231
237
  });
232
238
  }
package/src/capability.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
+ import type { D1Database } from "@cloudflare/workers-types";
4
5
  import type { Capability, PithyMiddleware } from "@pithy-sh/core/src/capability/capability";
5
6
  import { defineCapability } from "@pithy-sh/core/src/capability/capability";
6
7
  import { ValidationError } from "@pithy-sh/core/src/error/pithyError";
@@ -140,8 +141,25 @@ export interface AuthWiring {
140
141
  enqueueEmail: EmailCapability["enqueue"] | undefined;
141
142
  /** The turnstile login gate, when the turnstile capability is composed. Set by `compose`. */
142
143
  turnstile: { mode: TurnstileMode } | undefined;
144
+ /**
145
+ * The adopter's session-revoked listener, or absent. See {@link AuthOptions.onSessionRevoked}.
146
+ *
147
+ * Optional on the wiring rather than required-and-undefined, because a composition without a listener
148
+ * is the ordinary case and every harness that builds this shape by hand would otherwise have to say so.
149
+ */
150
+ onSessionRevoked?: SessionRevokedListener | undefined;
143
151
  }
144
152
 
153
+ /**
154
+ * Called when a session row is deleted — a sign-out, a revoke, an admin ending somebody's devices.
155
+ *
156
+ * **Handed this request's D1 binding**, because the auth instance is built per request and the listener
157
+ * almost certainly wants to write to the same database under a different capability's view of it. Taking
158
+ * the binding rather than a typed database keeps this seam out of the business of knowing whose tables
159
+ * the listener is about to touch.
160
+ */
161
+ export type SessionRevokedListener = (session: { id: string; userId: string }, d1: D1Database) => Promise<void>;
162
+
145
163
  /**
146
164
  * What `auth()` takes: the config, plus the seams that are **behavior rather than data**.
147
165
  *
@@ -166,6 +184,22 @@ export type AuthOptions = AuthConfigInput & {
166
184
  * real per-address flag, always.
167
185
  */
168
186
  resolveGithubUserInfo?: GithubUserInfoResolver;
187
+ /**
188
+ * Told when a session is revoked, so state another capability keyed on it can go with it.
189
+ *
190
+ * **On the row, not on the sign-out route.** A sign-out, a revoke and an admin ending somebody's
191
+ * devices all delete the same row, so a listener hung off one endpoint would miss the others.
192
+ *
193
+ * The case this exists for is `@pithy-sh/organization`: its acting selection is keyed by session id
194
+ * and its schema says signing out must take it with it. Tenancy depends on auth and not the reverse,
195
+ * so the composition holding both is what joins them, and this is the join.
196
+ *
197
+ * **Non-fatal by contract.** The session is already gone when this runs; a failure here must not turn
198
+ * a completed sign-out into an error the caller retries, so the instance swallows what it throws.
199
+ *
200
+ * A function, so it is destructured off before `AuthConfig.parse` for the reason above.
201
+ */
202
+ onSessionRevoked?: SessionRevokedListener;
169
203
  };
170
204
 
171
205
  /** The auth capability, with its resolved config attached for inspection. */
@@ -215,7 +249,7 @@ export function auth(options: AuthOptions): AuthCapability {
215
249
  // Zod 4 objects strip unknown keys silently, so a `resolveGithubUserInfo` handed to `AuthConfig.parse`
216
250
  // would vanish with no error and the adopter's override would simply never run. `payments()` splits
217
251
  // its `resolveSubject` out for the same reason.
218
- const { resolveGithubUserInfo, ...config } = options;
252
+ const { resolveGithubUserInfo, onSessionRevoked, ...config } = options;
219
253
  const resolved = AuthConfig.parse(config);
220
254
  // Additivity, before anything is built from the list. The four the kit composes are the sign-in this
221
255
  // product promises and what the control-plane seam verifies against, so a list naming one of them is
@@ -229,6 +263,7 @@ export function auth(options: AuthOptions): AuthCapability {
229
263
  resolveGithubUserInfo,
230
264
  enqueueEmail: undefined,
231
265
  turnstile: undefined,
266
+ onSessionRevoked,
232
267
  };
233
268
 
234
269
  // Tier-1 edge rate limiter, contributed as middleware so it runs before session resolution.
@@ -37,7 +37,12 @@ export const User = z
37
37
  emailVerified: SQLiteBoolean.describe(
38
38
  "Whether the email has been verified. Stored as `0|1`; magic-link/OTP sign-in sets it true.",
39
39
  ),
40
- image: z.string().nullable().describe("URL of the user's avatar from a social profile, or null."),
40
+ image: z
41
+ .string()
42
+ .nullable()
43
+ .describe(
44
+ "The user's picture: a URL on the provider that signed them in, or bytes this application stores as a bounded `data:` URL — see `../profile/profile.ts` for why the column takes two shapes. Null when nobody has set one, and then a caller draws initials, which is a real answer and not a placeholder.\n\n**Permissive here and strict on the write, exactly as `name` is, and the asymmetry is the point.** `UserImage` runs at the database hook, so nothing this kit writes can put an unacceptable value in the column. What this schema decodes is what is *already there* — a row a provider wrote before the rule existed, a repair script, a restored backup. A strict column turns one such row into a `ZodError` on every read that touches it, and `getUsers` parses a page of rows at once: one poisoned row would take down the whole roster for every operator rather than drawing one gap. That is the failure mode `./kitFields.ts` records for `locale`, and it is worse here, because a roster is read by people who did not write the row.\n\nThe value is made safe on the way **out** instead. `userImageSource` answers null for anything the rule does not recognize, so an unrecognized value renders as initials; and the serving route refuses to hand out bytes it cannot type.",
45
+ ),
41
46
  locale: Locale.nullable().describe(
42
47
  "The reader's chosen language as a BCP-47 tag, or null when they have never chosen. Null is not the default locale: it means negotiate from `Accept-Language`, so an unchosen reader follows their device. A stored tag outranks the header.",
43
48
  ),