@pithy-sh/auth 0.4.0 → 0.5.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: {
@@ -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.5.0";
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.5.0";
8
8
  //#endregion
9
9
  export { PACKAGE_NAME, PACKAGE_VERSION };
@@ -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.5.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
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
  }
@@ -2,17 +2,22 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  /**
5
- * **What pays for `allowDifferentEmails`.**
5
+ * **Changing which providers can sign you in requires a recent authentication.** Both directions.
6
6
  *
7
- * A signed-in user may attach a provider whose email differs from their own. That is the right behavior
8
- * and it widens something: before it, a provider could only be linked to an account holding the same
9
- * address, so a link was self-limiting. After it, a link is a decision the session alone authorizes.
7
+ * Attaching one grants permanent access — after it a sign-in resolves by account id and the email stops
8
+ * mattering — and it is what `allowDifferentEmails: true` widened: before that, a provider could only be
9
+ * linked to an account holding the same address, so a link was self-limiting. Detaching one is the
10
+ * smaller decision, but `allowUnlinkingAll: true` means an attacker inside the window can strip *every*
11
+ * provider from an account. Neither belongs behind a credential whose age nobody checked.
10
12
  *
11
- * And Better Auth guards that decision **less** than it guards undoing it. Read the two endpoints beside
12
- * each other in `better-auth/dist/api/routes/account.mjs`: `/link-social` takes `use: [sessionMiddleware]`
13
- * — any session, any age — while `/unlink-account` takes `use: [freshSessionMiddleware]`. Attaching an
14
- * identity grants *permanent* access, because once linked a sign-in resolves by account id and the email
15
- * stops mattering; detaching one does not. The cheaper-guarded operation is the more powerful one.
13
+ * **Better Auth guards the two unevenly, and neither guard is one the kit can use.** In
14
+ * `better-auth/dist/api/routes/account.mjs`, `/link-social` takes `use: [sessionMiddleware]` — any
15
+ * session, any age — while `/unlink-account` takes `use: [freshSessionMiddleware]`, which reads
16
+ * `session.createdAt` against a `freshAge` defaulting to 24 hours. So the more powerful operation was
17
+ * the cheaper-guarded one, and the guarded one was checked against a value `/token/rotate` resets:
18
+ * `internal-adapter.mjs:275` stamps `createdAt` after the caller's override, so a row's `created_at` is
19
+ * the moment of its most recent rotation. Ordinary refreshing resets it; so does anyone holding a stolen
20
+ * refresh token.
16
21
  *
17
22
  * **It reads `authenticatedAt`, not the session's `createdAt`, and that distinction is the whole of #558.**
18
23
  * The first version of this gate read session age. `/token/rotate` stamps a successor's `createdAt` with
@@ -35,10 +40,11 @@
35
40
  import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
36
41
  import { PithyError, UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
37
42
  import type { MiddlewareHandler } from "hono";
38
- import { emitLinkSessionNotFresh } from "../audit/emit";
43
+ import type { ProviderChange } from "../audit/emit";
44
+ import { emitProviderChangeNotFresh } from "../audit/emit";
39
45
 
40
46
  /**
41
- * How recently the caller must have authenticated to attach a provider: **fifteen minutes.**
47
+ * How recently the caller must have authenticated to change which providers sign them in: **fifteen minutes.**
42
48
  *
43
49
  * Stated rather than inherited. Better Auth's `freshAge` default is 24 hours, which is the wrong order of
44
50
  * magnitude here — a day-old authentication is not evidence that the person at the keyboard holds the
@@ -46,10 +52,12 @@ import { emitLinkSessionNotFresh } from "../audit/emit";
46
52
  * trip that involves signing in to the provider first, and is short enough that a stolen credential is
47
53
  * unlikely to still be inside the window.
48
54
  *
49
- * The cost of being wrong is one re-authentication — exactly what `/unlink-account` already charges for
50
- * the smaller decision.
55
+ * **One number for both operations.** Asymmetry is arguable — linking grants access and unlinking
56
+ * removes it — but the argument cuts both ways once `allowUnlinkingAll` is on, and a second constant
57
+ * would be a second thing to keep true. The cost of being wrong in either direction is one
58
+ * re-authentication.
51
59
  */
52
- export const LINK_FRESH_AGE_SECONDS = 15 * 60;
60
+ export const PROVIDER_CHANGE_FRESH_AGE_SECONDS = 15 * 60;
53
61
 
54
62
  /**
55
63
  * Whether an authentication is recent enough to authorize attaching a provider.
@@ -66,7 +74,7 @@ export function authenticationIsFresh(authenticatedAt: Date | string | null | un
66
74
  if (Number.isNaN(millis)) return false;
67
75
  const age = (now.getTime() - millis) / 1000;
68
76
  if (age < 0) return false;
69
- return age <= LINK_FRESH_AGE_SECONDS;
77
+ return age <= PROVIDER_CHANGE_FRESH_AGE_SECONDS;
70
78
  }
71
79
 
72
80
  /**
@@ -101,14 +109,21 @@ export function sessionNotFresh(): PithyError {
101
109
  return new PithyError({
102
110
  code: "auth/session_not_fresh",
103
111
  status: 403,
104
- message: "Sign in again to connect an account. Nothing was changed.",
112
+ message: "Sign in again to change your connected accounts. Nothing was changed.",
105
113
  action:
106
- "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`.",
107
- detail: "session authenticatedAt is older than LINK_FRESH_AGE_SECONDS, absent, or unreadable",
114
+ "A deliberate gate: changing which providers can sign somebody in requires a recent authentication, in both directions. See `http/providerFreshness.ts`.",
115
+ detail: "session authenticatedAt is older than PROVIDER_CHANGE_FRESH_AGE_SECONDS, absent, or unreadable",
108
116
  });
109
117
  }
110
118
 
111
- export function requireFreshAuthenticationToLink(now: () => Date = () => new Date()): MiddlewareHandler<PithyHonoEnv> {
119
+ /**
120
+ * Which direction is being refused. Carried into the audit row, because "somebody tried to attach an
121
+ * identity on a stale credential" and "somebody tried to strip one" are different things to read later.
122
+ */
123
+ export function requireFreshAuthentication(
124
+ change: ProviderChange,
125
+ now: () => Date = () => new Date(),
126
+ ): MiddlewareHandler<PithyHonoEnv> {
112
127
  return async (c, next) => {
113
128
  const auth = c.var.auth;
114
129
  if (!auth) {
@@ -118,7 +133,8 @@ export function requireFreshAuthenticationToLink(now: () => Date = () => new Dat
118
133
  });
119
134
  }
120
135
  if (!authenticationIsFresh(auth.authenticatedAt, now())) {
121
- await emitLinkSessionNotFresh(c.var.emit, {
136
+ await emitProviderChangeNotFresh(c.var.emit, {
137
+ change,
122
138
  userId: auth.userId,
123
139
  sessionId: auth.sessionId,
124
140
  headers: c.req.raw.headers,
@@ -22,8 +22,8 @@ import {
22
22
  } from "../token/rotation";
23
23
  import { registerAuthAdminRoutes } from "./adminRoutes";
24
24
  import { apiErrorToPithy } from "./errors";
25
- import { requireFreshAuthenticationToLink } from "./linkFreshness";
26
25
  import { requireAuth } from "./middleware";
26
+ import { requireFreshAuthentication } from "./providerFreshness";
27
27
  import { getAuthInstance, resolveDb } from "./resolve";
28
28
  import { RevokeDeviceBody } from "./schemas";
29
29
 
@@ -88,12 +88,13 @@ export function createAuthRoutes(wiring: AuthWiring): (app: Hono<PithyHonoEnv>)
88
88
  revokeMyDevice(c, wiring, c.req.valid("json")),
89
89
  );
90
90
 
91
- // **Attaching a provider requires a recent authentication.** Mounted explicitly ahead of the
92
- // catch-all, or the gate never runs. `http/linkFreshness.ts` carries the argument: Better Auth guards
93
- // `/link-social` with a plain session and `/unlink-account` with a fresh one, so the operation that
94
- // grants permanent access is the cheaper-guarded one. No kit validator — the body is Better Auth's,
95
- // and `handleBetterAuth` hands it `c.req.raw`, which is the catch-all's own reason for taking none.
96
- app.post(`${base}/link-social`, requireFreshAuthenticationToLink(), (c) => handleBetterAuth(c, wiring));
91
+ // **Changing which providers can sign you in requires a recent authentication — both directions.**
92
+ // Mounted explicitly ahead of the catch-all, or neither gate runs. `http/providerFreshness.ts`
93
+ // carries the argument: Better Auth guards the two unevenly, and its guard on the unlink side reads
94
+ // `session.createdAt`, which `/token/rotate` resets. Neither takes a kit validator — the body is
95
+ // Better Auth's, and `handleBetterAuth` hands it `c.req.raw`, which is the catch-all's own reason.
96
+ app.post(`${base}/link-social`, requireFreshAuthentication("link"), (c) => handleBetterAuth(c, wiring));
97
+ app.post(`${base}/unlink-account`, requireFreshAuthentication("unlink"), (c) => handleBetterAuth(c, wiring));
97
98
 
98
99
  // The control-plane management surface. Registered here, before the catch-all below, or it is dead.
99
100
  registerAuthAdminRoutes(wiring)(app);
@@ -8,6 +8,7 @@ import { emitAfterRequest, emitProviderUnavailable } from "../audit/emit";
8
8
  import { KIT_SESSION_FIELDS, KIT_USER_FIELDS } from "../data/kitFields";
9
9
  import type { AuthDatabase } from "../data/tables";
10
10
  import { parseDeviceMeta, registerDevice } from "../device/registry";
11
+ import { PROVIDER_CHANGE_FRESH_AGE_SECONDS } from "../http/providerFreshness";
11
12
  import { defaultGithubUserInfo, type GithubUserInfoResolver } from "./githubUserInfo";
12
13
  import { kitPlugins } from "./plugins";
13
14
  import {
@@ -357,6 +358,20 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
357
358
  modelName: "pithyAuthSessions",
358
359
  expiresIn: deps.sessionExpiresIn,
359
360
  updateAge: deps.sessionUpdateAge,
361
+ /**
362
+ * Better Auth's own re-authentication window, stated rather than inherited.
363
+ *
364
+ * Its default is 24 hours, which nobody here chose, and it is the number `freshSessionMiddleware`
365
+ * holds `/unlink-account` to. Bringing it to the kit's own window means the two checks on that
366
+ * endpoint agree instead of one silently permitting a day.
367
+ *
368
+ * **It is defense in depth, not the control.** `freshSessionMiddleware` measures
369
+ * `session.createdAt`, which `/token/rotate` restamps — so narrowing it narrows a window that is
370
+ * still resettable. The control is `http/providerFreshness.ts`, which reads the authentication
371
+ * instant a rotation carries forward, and it is strictly the stricter of the two: `createdAt` is
372
+ * never older than `authenticatedAt`, so anything our gate admits this one admits too.
373
+ */
374
+ freshAge: PROVIDER_CHANGE_FRESH_AGE_SECONDS,
360
375
  // Server-set session fields clients never supply: the bound device, and the refresh-token family
361
376
  // (carried across rotations via createSession override, like deviceId — see `token/rotation.ts`).
362
377
  additionalFields: KIT_SESSION_FIELDS,
@@ -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.4.0";
16
+ export const PACKAGE_VERSION = "0.5.0";
@@ -1 +0,0 @@
1
- {"version":3,"file":"linkFreshness.d.ts","sourceRoot":"","sources":["../../src/http/linkFreshness.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;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;AAG9C;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,sBAAsB,QAAU,CAAC;AAE9C;;;;;;;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,wBAAgB,gCAAgC,CAAC,GAAG,GAAE,MAAM,IAAuB,GAAG,iBAAiB,CAAC,YAAY,CAAC,CAmBpH"}