@pithy-sh/auth 0.2.1 → 0.4.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.
- package/dist/audit/actions.d.ts +12 -0
- package/dist/audit/actions.d.ts.map +1 -1
- package/dist/audit/actions.js +12 -0
- package/dist/audit/emit.d.ts +12 -0
- package/dist/audit/emit.d.ts.map +1 -1
- package/dist/audit/emit.js +19 -1
- package/dist/capability.d.ts +37 -5
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +30 -9
- package/dist/client/api.d.ts +8 -0
- package/dist/client/api.d.ts.map +1 -1
- package/dist/client/api.js +7 -0
- package/dist/client/projection.d.ts +22 -0
- package/dist/client/projection.d.ts.map +1 -1
- package/dist/data/betterAuth.d.ts +1 -0
- package/dist/data/betterAuth.d.ts.map +1 -1
- package/dist/data/betterAuth.js +2 -1
- package/dist/data/kitFields.d.ts +23 -1
- package/dist/data/kitFields.d.ts.map +1 -1
- package/dist/data/kitFields.js +23 -1
- package/dist/data/tables.d.ts +1 -0
- package/dist/data/tables.d.ts.map +1 -1
- package/dist/http/linkFreshness.d.ts +88 -0
- package/dist/http/linkFreshness.d.ts.map +1 -0
- package/dist/http/linkFreshness.js +91 -0
- package/dist/http/middleware.d.ts +0 -7
- package/dist/http/middleware.d.ts.map +1 -1
- package/dist/http/middleware.js +7 -1
- package/dist/http/resolve.js +7 -0
- package/dist/http/routes.d.ts.map +1 -1
- package/dist/http/routes.js +4 -0
- package/dist/instance/auth.d.ts +93 -13
- package/dist/instance/auth.d.ts.map +1 -1
- package/dist/instance/auth.js +90 -8
- package/dist/instance/githubUserInfo.d.ts +129 -0
- package/dist/instance/githubUserInfo.d.ts.map +1 -0
- package/dist/instance/githubUserInfo.js +153 -0
- package/dist/migrations/0002_session_authenticated_at.d.ts +39 -0
- package/dist/migrations/0002_session_authenticated_at.d.ts.map +1 -0
- package/dist/migrations/0002_session_authenticated_at.js +47 -0
- package/dist/migrations/set.d.ts +20 -0
- package/dist/migrations/set.d.ts.map +1 -0
- package/dist/migrations/set.js +24 -0
- package/dist/seeds/devSession.d.ts.map +1 -1
- package/dist/seeds/devSession.js +2 -1
- package/dist/test-utils/liveApp.d.ts.map +1 -1
- package/dist/test-utils/liveApp.js +4 -2
- package/dist/version.generated.d.ts +1 -1
- package/dist/version.generated.js +1 -1
- package/docs/github-oauth.md +55 -0
- package/package.json +5 -5
- package/src/audit/actions.ts +12 -0
- package/src/audit/emit.ts +24 -0
- package/src/capability.ts +76 -10
- package/src/client/api.ts +8 -1
- package/src/client/projection.ts +22 -0
- package/src/data/betterAuth.ts +3 -0
- package/src/data/kitFields.ts +19 -1
- package/src/http/linkFreshness.ts +130 -0
- package/src/http/middleware.ts +13 -0
- package/src/http/resolve.ts +10 -0
- package/src/http/routes.ts +28 -1
- package/src/instance/auth.ts +113 -7
- package/src/instance/githubUserInfo.ts +212 -0
- package/src/migrations/0002_session_authenticated_at.ts +50 -0
- package/src/migrations/set.ts +23 -0
- package/src/seeds/devSession.ts +2 -0
- package/src/test-utils/liveApp.ts +4 -2
- package/src/version.generated.ts +1 -1
package/src/capability.ts
CHANGED
|
@@ -17,23 +17,40 @@ import { authAdminRoutes } from "./http/guards";
|
|
|
17
17
|
import { createSessionMiddleware } from "./http/middleware";
|
|
18
18
|
import { createRateLimitMiddleware } from "./http/rateLimit";
|
|
19
19
|
import { createAuthRoutes } from "./http/routes";
|
|
20
|
+
import type { GithubUserInfoResolver } from "./instance/githubUserInfo";
|
|
20
21
|
import { AuthPlugin, assertAdditivePlugins } from "./instance/plugins";
|
|
21
22
|
import { authSecretsRegistry, inapplicableProviderSecrets } from "./instance/secrets";
|
|
22
|
-
import { AUTH_MIGRATION_ORDER
|
|
23
|
+
import { AUTH_MIGRATION_ORDER } from "./migrations/0001_init";
|
|
23
24
|
import { authPluginPlan } from "./migrations/pluginTables";
|
|
25
|
+
import { AUTH_MIGRATIONS } from "./migrations/set";
|
|
24
26
|
import { authDevSessionSeed } from "./seeds/devSession";
|
|
25
27
|
import { authExampleSeed } from "./seeds/example";
|
|
26
28
|
import { PACKAGE_VERSION } from "./version.generated";
|
|
27
29
|
|
|
28
|
-
/**
|
|
30
|
+
/**
|
|
31
|
+
* A social provider toggle. Credentials live in the secrets store, never config.
|
|
32
|
+
*
|
|
33
|
+
* **Defaulted with `.prefault({})` rather than `.default({ enabled: false })`, and the difference is not
|
|
34
|
+
* cosmetic.** Zod 4 hands a `.default` value back verbatim without parsing it, so a literal supplied the
|
|
35
|
+
* object's *shape* while silently skipping every inner field default — `allowSignUp` was `undefined` on
|
|
36
|
+
* all four providers until a caller wrote one out by hand, which is precisely the field whose absence
|
|
37
|
+
* must not read as "false". `.prefault` runs the value through the schema, so one place states the
|
|
38
|
+
* defaults and nothing has to restate them.
|
|
39
|
+
*/
|
|
29
40
|
const ProviderToggle = z
|
|
30
41
|
.object({
|
|
31
42
|
enabled: z
|
|
32
43
|
.boolean()
|
|
33
44
|
.default(false)
|
|
34
45
|
.describe("Whether this social provider is enabled. Credentials are read from the secrets store, never config."),
|
|
46
|
+
allowSignUp: z
|
|
47
|
+
.boolean()
|
|
48
|
+
.default(true)
|
|
49
|
+
.describe(
|
|
50
|
+
"Whether signing in with this provider may create a new account. When false, a sign-in whose email matches no existing user is refused and nothing is minted — the caller signs in by email first, then connects this provider from their profile. Separate from the top-level `disableSignUp`, which governs magic link and OTP.",
|
|
51
|
+
),
|
|
35
52
|
})
|
|
36
|
-
.describe("A social provider's on/off toggle.");
|
|
53
|
+
.describe("A social provider's on/off toggle and its sign-up policy.");
|
|
37
54
|
|
|
38
55
|
/** The auth capability's configuration — the thin surface an adopter owns in `pithy.config.ts`. */
|
|
39
56
|
export const AuthConfig = z
|
|
@@ -65,16 +82,16 @@ export const AuthConfig = z
|
|
|
65
82
|
.describe(
|
|
66
83
|
"The Workers Rate Limiting binding for the coarse per-IP edge guard on the auth routes (tier 1). Its limit and window are set on the binding in wrangler.jsonc. Complements Better Auth's per-action limiter (tier 2).",
|
|
67
84
|
),
|
|
68
|
-
google: ProviderToggle.
|
|
85
|
+
google: ProviderToggle.prefault({}).describe(
|
|
69
86
|
"Google OAuth. Enable it, then store credentials as the `auth-google-credentials` secret. See docs/google-oauth.md.",
|
|
70
87
|
),
|
|
71
|
-
apple: ProviderToggle.
|
|
88
|
+
apple: ProviderToggle.prefault({}).describe(
|
|
72
89
|
"Apple Sign-In. Enable it, then store credentials as the `auth-apple-credentials` secret. See docs/apple-signin.md.",
|
|
73
90
|
),
|
|
74
|
-
facebook: ProviderToggle.
|
|
91
|
+
facebook: ProviderToggle.prefault({}).describe(
|
|
75
92
|
"Facebook Login. Enable it, then store credentials as the `auth-facebook-credentials` secret. See docs/facebook-oauth.md.",
|
|
76
93
|
),
|
|
77
|
-
github: ProviderToggle.
|
|
94
|
+
github: ProviderToggle.prefault({}).describe(
|
|
78
95
|
"GitHub OAuth. Enable it, then store credentials as the `auth-github-credentials` secret. See docs/github-oauth.md.",
|
|
79
96
|
),
|
|
80
97
|
sessionExpiresIn: z
|
|
@@ -117,12 +134,40 @@ export type AuthConfigInput = z.input<typeof AuthConfig>;
|
|
|
117
134
|
*/
|
|
118
135
|
export interface AuthWiring {
|
|
119
136
|
config: AuthConfig;
|
|
137
|
+
/** The adopter's GitHub identity resolver, or `undefined` for the kit's own rule. See {@link AuthOptions}. */
|
|
138
|
+
resolveGithubUserInfo: GithubUserInfoResolver | undefined;
|
|
120
139
|
/** The email capability's bound enqueue seam — how magic-link/OTP are delivered. Set by `compose`. */
|
|
121
140
|
enqueueEmail: EmailCapability["enqueue"] | undefined;
|
|
122
141
|
/** The turnstile login gate, when the turnstile capability is composed. Set by `compose`. */
|
|
123
142
|
turnstile: { mode: TurnstileMode } | undefined;
|
|
124
143
|
}
|
|
125
144
|
|
|
145
|
+
/**
|
|
146
|
+
* What `auth()` takes: the config, plus the seams that are **behavior rather than data**.
|
|
147
|
+
*
|
|
148
|
+
* A function cannot live in the Zod schema — the schema is the self-documenting surface `pithy` renders
|
|
149
|
+
* and the config projection serializes, and neither can carry a closure. So the split follows
|
|
150
|
+
* `PaymentsOptions`: everything describable stays in {@link AuthConfig}, and a resolver is a sibling key
|
|
151
|
+
* destructured off before the parse.
|
|
152
|
+
*/
|
|
153
|
+
export type AuthOptions = AuthConfigInput & {
|
|
154
|
+
/**
|
|
155
|
+
* Resolve a GitHub identity yourself, replacing the kit's primary-only rule.
|
|
156
|
+
*
|
|
157
|
+
* The kit's default is deliberately conservative: it links on the **primary** address and nothing else,
|
|
158
|
+
* because GitHub never re-verifies and a verified secondary can only speak to the past. An adopter who
|
|
159
|
+
* wants a richer ladder — match a verified secondary, present a chooser on multiple matches — builds it
|
|
160
|
+
* here. `getUserInfo` is the only hook in this flow running before both fetches and before
|
|
161
|
+
* `mapProfileToUser`, and the only one holding the OAuth token.
|
|
162
|
+
*
|
|
163
|
+
* **Better Auth trusts what you return, verbatim.** It performs no independent check, so an
|
|
164
|
+
* `emailVerified: true` you did not read from GitHub is an account takeover: an attacker adds a
|
|
165
|
+
* victim's address to their own GitHub *unverified* and links to the victim's user. Return GitHub's
|
|
166
|
+
* real per-address flag, always.
|
|
167
|
+
*/
|
|
168
|
+
resolveGithubUserInfo?: GithubUserInfoResolver;
|
|
169
|
+
};
|
|
170
|
+
|
|
126
171
|
/** The auth capability, with its resolved config attached for inspection. */
|
|
127
172
|
export interface AuthCapability extends Capability {
|
|
128
173
|
authConfig: AuthConfig;
|
|
@@ -165,7 +210,12 @@ function assertPluginTablesUnclaimed(
|
|
|
165
210
|
* `AuthContext` seam. Depends on `secrets` and `email`; auto-gates its send routes with `turnstile`
|
|
166
211
|
* and emits `auth/*` through `audit` when those are composed.
|
|
167
212
|
*/
|
|
168
|
-
export function auth(
|
|
213
|
+
export function auth(options: AuthOptions): AuthCapability {
|
|
214
|
+
// **Destructured before the parse, and that ordering is the whole reason this is not a config field.**
|
|
215
|
+
// Zod 4 objects strip unknown keys silently, so a `resolveGithubUserInfo` handed to `AuthConfig.parse`
|
|
216
|
+
// would vanish with no error and the adopter's override would simply never run. `payments()` splits
|
|
217
|
+
// its `resolveSubject` out for the same reason.
|
|
218
|
+
const { resolveGithubUserInfo, ...config } = options;
|
|
169
219
|
const resolved = AuthConfig.parse(config);
|
|
170
220
|
// Additivity, before anything is built from the list. The four the kit composes are the sign-in this
|
|
171
221
|
// product promises and what the control-plane seam verifies against, so a list naming one of them is
|
|
@@ -174,7 +224,12 @@ export function auth(config: AuthConfigInput): AuthCapability {
|
|
|
174
224
|
// And the tables those plugins imply, derived now so a collision is a config error at `auth()` rather
|
|
175
225
|
// than a half-applied migration against a database with no transactional DDL.
|
|
176
226
|
const pluginPlan = authPluginPlan(resolved.plugins);
|
|
177
|
-
const wiring: AuthWiring = {
|
|
227
|
+
const wiring: AuthWiring = {
|
|
228
|
+
config: resolved,
|
|
229
|
+
resolveGithubUserInfo,
|
|
230
|
+
enqueueEmail: undefined,
|
|
231
|
+
turnstile: undefined,
|
|
232
|
+
};
|
|
178
233
|
|
|
179
234
|
// Tier-1 edge rate limiter, contributed as middleware so it runs before session resolution.
|
|
180
235
|
const rateLimitMiddleware: PithyMiddleware = (app) => {
|
|
@@ -219,7 +274,10 @@ export function auth(config: AuthConfigInput): AuthCapability {
|
|
|
219
274
|
// is in `pithy.config.ts`, which is the file `pithy migrate` already imports to collect
|
|
220
275
|
// capabilities, so the tables ride the migration model that exists rather than needing a new
|
|
221
276
|
// one. A project that composes no plugins contributes exactly what it did before.
|
|
222
|
-
|
|
277
|
+
// Every kit migration, from one definition — see `migrations/set.ts` for why it is not written
|
|
278
|
+
// out here. Appended, never folded into `0001`: this capability has shipped, so that migration is
|
|
279
|
+
// history and re-shaping it would re-shape a database somebody is already running (#558).
|
|
280
|
+
migrations: { ...AUTH_MIGRATIONS, ...pluginPlan.migrations },
|
|
223
281
|
},
|
|
224
282
|
},
|
|
225
283
|
compose: ({ capabilities }) => {
|
|
@@ -271,6 +329,14 @@ export function auth(config: AuthConfigInput): AuthCapability {
|
|
|
271
329
|
facebook: resolved.facebook.enabled,
|
|
272
330
|
github: resolved.github.enabled,
|
|
273
331
|
},
|
|
332
|
+
// Per provider, beside the global one. A project may let email create accounts while a provider
|
|
333
|
+
// may not, and a screen with only `signUpEnabled` promises what that provider will refuse (#559).
|
|
334
|
+
providerSignUp: {
|
|
335
|
+
google: resolved.google.allowSignUp,
|
|
336
|
+
apple: resolved.apple.allowSignUp,
|
|
337
|
+
facebook: resolved.facebook.allowSignUp,
|
|
338
|
+
github: resolved.github.allowSignUp,
|
|
339
|
+
},
|
|
274
340
|
otpLength: resolved.otpLength,
|
|
275
341
|
signUpEnabled: !resolved.disableSignUp,
|
|
276
342
|
}),
|
package/src/client/api.ts
CHANGED
|
@@ -487,9 +487,16 @@ function isAuthorization(value: unknown): value is { url: string } {
|
|
|
487
487
|
* **No humanity check, deliberately**: the redirect carries no token to check and the provider runs its
|
|
488
488
|
* own bot defense, which is what `@pithy-sh/auth` already assumes when it stacks the check on the
|
|
489
489
|
* magic-link route alone. Gating it would only stop people signing in.
|
|
490
|
+
*
|
|
491
|
+
* **`errorCallbackURL` is how a refusal gets back to a screen at all.** Absent it, Better Auth sends a
|
|
492
|
+
* refused callback to `${baseURL}${basePath}/error`, which in production redirects on to the adopter's
|
|
493
|
+
* home route carrying a query string no template reads — so the user lands on a page that says nothing
|
|
494
|
+
* about what just happened. Pass the sign-in screen's own path and the refusal returns to the control
|
|
495
|
+
* that started it, as `?error=<code>`. That is the transport the whole GitHub rejection copy depends on
|
|
496
|
+
* (pithy-sh/pithy#554); without it the sentence exists and is unreachable.
|
|
490
497
|
*/
|
|
491
498
|
export async function startSocialSignIn(
|
|
492
|
-
input: { provider: string; callbackURL: string },
|
|
499
|
+
input: { provider: string; callbackURL: string; errorCallbackURL?: string },
|
|
493
500
|
options?: AuthClientOptions,
|
|
494
501
|
): Promise<SocialSignIn> {
|
|
495
502
|
// The gate is dropped rather than passed through, so a screen holding one client options object for
|
package/src/client/projection.ts
CHANGED
|
@@ -48,6 +48,28 @@ export type AuthClientProjection =
|
|
|
48
48
|
/** Whether Sign in with GitHub is offered. */
|
|
49
49
|
github: boolean;
|
|
50
50
|
};
|
|
51
|
+
/**
|
|
52
|
+
* Whether each offered provider may create an account, from its `allowSignUp` toggle.
|
|
53
|
+
*
|
|
54
|
+
* **A second fact from {@link signUpEnabled}, and the screen needs both.** That one answers for
|
|
55
|
+
* magic link and OTP; this answers per provider. A project can let email create accounts while
|
|
56
|
+
* GitHub only signs existing ones in — which is the configuration #554 exists for — and with only
|
|
57
|
+
* the global flag a screen renders "Signing in creates one." directly beneath a button that will
|
|
58
|
+
* refuse (#559).
|
|
59
|
+
*
|
|
60
|
+
* Optional, so a screen copied before this landed keeps compiling and reads `undefined` as "no
|
|
61
|
+
* provider objects" — the state every project was in until now.
|
|
62
|
+
*/
|
|
63
|
+
providerSignUp?: {
|
|
64
|
+
/** Whether a Google sign-in may create an account. */
|
|
65
|
+
google: boolean;
|
|
66
|
+
/** Whether an Apple sign-in may create an account. */
|
|
67
|
+
apple: boolean;
|
|
68
|
+
/** Whether a Facebook sign-in may create an account. */
|
|
69
|
+
facebook: boolean;
|
|
70
|
+
/** Whether a GitHub sign-in may create an account. */
|
|
71
|
+
github: boolean;
|
|
72
|
+
};
|
|
51
73
|
/** How many digits an email OTP carries. */
|
|
52
74
|
otpLength: number;
|
|
53
75
|
/** Whether signing in may provision a new user. Drives the sign-up copy. */
|
package/src/data/betterAuth.ts
CHANGED
|
@@ -85,6 +85,9 @@ export const Session = z
|
|
|
85
85
|
.describe(
|
|
86
86
|
"The refresh-token family this session belongs to, carried across rotations so a replayed refresh token can revoke the whole chain. Server-set; null for a session created before rotation or one never rotated.",
|
|
87
87
|
),
|
|
88
|
+
authenticatedAt: BetterAuthDate.nullable().describe(
|
|
89
|
+
"When the holder of this session last actually authenticated — a sign-in, never a rotation, which carries the value forward unchanged. This is what the provider-linking freshness gate reads; the session's own `createdAt` cannot be, because `/token/rotate` stamps a fresh one on every successor and is therefore resettable by anyone holding a stolen refresh token (#558). ISO-8601 text in SQLite. Null only for a session written before the column existed.",
|
|
90
|
+
),
|
|
88
91
|
})
|
|
89
92
|
.describe("A session in `pithy_auth_sessions` — a signed-in credential, optionally bound to a device.");
|
|
90
93
|
export type Session = z.output<typeof Session>;
|
package/src/data/kitFields.ts
CHANGED
|
@@ -57,13 +57,31 @@ export const KIT_USER_FIELDS = {
|
|
|
57
57
|
} as const;
|
|
58
58
|
|
|
59
59
|
/**
|
|
60
|
+
* **`authenticatedAt` carries three decisions a future author must not undo.**
|
|
61
|
+
*
|
|
62
|
+
* `type: "date"` rather than `"string"`: the adapter's `Date` ↔ ISO-8601 conversion is keyed on that
|
|
63
|
+
* literal (`@better-auth/core`'s `factory.mjs`, on write and on read), and the kysely adapter reports
|
|
64
|
+
* `supportsDates: false` for SQLite. `deviceId`/`familyId` are `"string"` because they are opaque ids; a
|
|
65
|
+
* timestamp is not.
|
|
66
|
+
*
|
|
67
|
+
* **No `defaultValue`, and this is the one that bites.** A function default would stamp every sign-in
|
|
68
|
+
* with no hook at all — but `getSessionDefaultFields` is spread into the row *after* the caller's
|
|
69
|
+
* override in `createSession`, so a fresh default would overwrite the value `rotateToken` carries
|
|
70
|
+
* forward, silently restoring the exact defect this column exists to fix (#558). It is stamped by the
|
|
71
|
+
* `session.create.before` hook instead.
|
|
72
|
+
*
|
|
73
|
+
* `input: false`, like its siblings: a client able to name its own authentication time would defeat the
|
|
74
|
+
* link-freshness gate outright. `required: false` because the column is nullable for rows written before
|
|
75
|
+
* it existed.
|
|
76
|
+
*
|
|
60
77
|
* The extra `pithy_auth_sessions` columns — the bound device, and the refresh-token family carried
|
|
61
78
|
* across rotations.
|
|
62
79
|
*
|
|
63
|
-
* `input: false` on
|
|
80
|
+
* `input: false` on all three: these are server-set facts about a session, and a client able to name its own
|
|
64
81
|
* device id or token family could name somebody else's.
|
|
65
82
|
*/
|
|
66
83
|
export const KIT_SESSION_FIELDS = {
|
|
67
84
|
deviceId: { type: "string", required: false, input: false },
|
|
68
85
|
familyId: { type: "string", required: false, input: false },
|
|
86
|
+
authenticatedAt: { type: "date", required: false, input: false },
|
|
69
87
|
} as const;
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* **What pays for `allowDifferentEmails`.**
|
|
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.
|
|
10
|
+
*
|
|
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.
|
|
16
|
+
*
|
|
17
|
+
* **It reads `authenticatedAt`, not the session's `createdAt`, and that distinction is the whole of #558.**
|
|
18
|
+
* The first version of this gate read session age. `/token/rotate` stamps a successor's `createdAt` with
|
|
19
|
+
* the moment of the call, so session age is reset by every rotation — ordinary on the bearer path, and
|
|
20
|
+
* available on demand to anyone holding a stolen refresh token. Two requests and the gate was open. The
|
|
21
|
+
* question it means to ask is how recently the *person* authenticated, which is a different fact, stamped
|
|
22
|
+
* once at sign-in and carried across rotations verbatim.
|
|
23
|
+
*
|
|
24
|
+
* **Not a Better Auth hook, and that is a framework constraint rather than a preference.** A `before` hook
|
|
25
|
+
* runs ahead of the endpoint's own `sessionMiddleware`, so `ctx.context.session` is null at hook time; and
|
|
26
|
+
* `runBeforeHooks` accumulates each hook's context changes and applies them only after *every* hook, so
|
|
27
|
+
* `bearer()`'s rewrite of `Authorization` into the session cookie never reaches a sibling hook either. A
|
|
28
|
+
* hook therefore cannot resolve a mobile caller's session at all, and a gate that cannot read a session
|
|
29
|
+
* refuses everyone — indistinguishable from the feature being broken, which invites deleting the gate.
|
|
30
|
+
*
|
|
31
|
+
* Provider-agnostic on purpose. Google and Apple are trusted providers, which makes them *more* exposed
|
|
32
|
+
* to this, not less: the question is how recently the caller proved they hold the account.
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
|
|
36
|
+
import { PithyError, UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
|
|
37
|
+
import type { MiddlewareHandler } from "hono";
|
|
38
|
+
import { emitLinkSessionNotFresh } from "../audit/emit";
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* How recently the caller must have authenticated to attach a provider: **fifteen minutes.**
|
|
42
|
+
*
|
|
43
|
+
* Stated rather than inherited. Better Auth's `freshAge` default is 24 hours, which is the wrong order of
|
|
44
|
+
* magnitude here — a day-old authentication is not evidence that the person at the keyboard holds the
|
|
45
|
+
* account, and the whole exposure is a credential valid for days. Fifteen minutes covers an OAuth round
|
|
46
|
+
* trip that involves signing in to the provider first, and is short enough that a stolen credential is
|
|
47
|
+
* unlikely to still be inside the window.
|
|
48
|
+
*
|
|
49
|
+
* The cost of being wrong is one re-authentication — exactly what `/unlink-account` already charges for
|
|
50
|
+
* the smaller decision.
|
|
51
|
+
*/
|
|
52
|
+
export const LINK_FRESH_AGE_SECONDS = 15 * 60;
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Whether an authentication is recent enough to authorize attaching a provider.
|
|
56
|
+
*
|
|
57
|
+
* **Fails closed on anything it cannot read.** An absent, unparseable or future timestamp is not evidence
|
|
58
|
+
* of a recent authentication — it is the absence of evidence — and a gate that reads "I cannot tell" as
|
|
59
|
+
* "fresh" is one a row written before the column walks straight through. The future case matters as much
|
|
60
|
+
* as the past: a window checked on one side only would pass any future value forever.
|
|
61
|
+
*/
|
|
62
|
+
export function authenticationIsFresh(authenticatedAt: Date | string | null | undefined, now: Date): boolean {
|
|
63
|
+
if (authenticatedAt === null || authenticatedAt === undefined) return false;
|
|
64
|
+
const at = authenticatedAt instanceof Date ? authenticatedAt : new Date(authenticatedAt);
|
|
65
|
+
const millis = at.getTime();
|
|
66
|
+
if (Number.isNaN(millis)) return false;
|
|
67
|
+
const age = (now.getTime() - millis) / 1000;
|
|
68
|
+
if (age < 0) return false;
|
|
69
|
+
return age <= LINK_FRESH_AGE_SECONDS;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* The gate, as Hono middleware on the kit's own route tree.
|
|
74
|
+
*
|
|
75
|
+
* **A pure read of `c.var.auth`.** `createSessionMiddleware` has already resolved this request's
|
|
76
|
+
* credential — core registers every capability's middleware before any capability's routes — so resolving
|
|
77
|
+
* it again would be a second D1 round trip for a fact the seam is holding. That is the argument
|
|
78
|
+
* `AuthContext` already makes for `locale`.
|
|
79
|
+
*
|
|
80
|
+
* **No credential at all is 401, not this 403.** `auth/session_not_fresh` means "signed in, but not
|
|
81
|
+
* recently enough"; a caller holding nothing cannot tell that from "not signed in" and will not know
|
|
82
|
+
* whether to re-authenticate or to retry. The refusal is `requireAuth()`'s, word for word, so the two
|
|
83
|
+
* surfaces answer an absent credential identically.
|
|
84
|
+
*
|
|
85
|
+
* **Recorded before the throw**, like `emitProviderUnavailable`: one refusal is somebody who left a tab
|
|
86
|
+
* open, and a run of them against one user id is the incident. The trail has to hold it whether or not
|
|
87
|
+
* anything logs the refusal.
|
|
88
|
+
*/
|
|
89
|
+
/**
|
|
90
|
+
* The refusal for attaching a provider without having authenticated recently.
|
|
91
|
+
*
|
|
92
|
+
* **Not `auth/forbidden`.** A client has to render this differently from every other 403, because the
|
|
93
|
+
* remedy is specific and cheap — sign in again, then retry — and a generic "you are not allowed" sends
|
|
94
|
+
* somebody to ask for a permission they already hold. `http/linkFreshness.ts` carries the argument for
|
|
95
|
+
* the gate itself.
|
|
96
|
+
*
|
|
97
|
+
* `message` says nothing was changed, because the caller is mid-flow and cannot otherwise tell whether
|
|
98
|
+
* the link half-happened.
|
|
99
|
+
*/
|
|
100
|
+
export function sessionNotFresh(): PithyError {
|
|
101
|
+
return new PithyError({
|
|
102
|
+
code: "auth/session_not_fresh",
|
|
103
|
+
status: 403,
|
|
104
|
+
message: "Sign in again to connect an account. Nothing was changed.",
|
|
105
|
+
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",
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function requireFreshAuthenticationToLink(now: () => Date = () => new Date()): MiddlewareHandler<PithyHonoEnv> {
|
|
112
|
+
return async (c, next) => {
|
|
113
|
+
const auth = c.var.auth;
|
|
114
|
+
if (!auth) {
|
|
115
|
+
throw new UnauthorizedError({
|
|
116
|
+
message: "Authentication required.",
|
|
117
|
+
action: "Sign in and retry with a valid session or bearer token.",
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
if (!authenticationIsFresh(auth.authenticatedAt, now())) {
|
|
121
|
+
await emitLinkSessionNotFresh(c.var.emit, {
|
|
122
|
+
userId: auth.userId,
|
|
123
|
+
sessionId: auth.sessionId,
|
|
124
|
+
headers: c.req.raw.headers,
|
|
125
|
+
});
|
|
126
|
+
throw sessionNotFresh();
|
|
127
|
+
}
|
|
128
|
+
await next();
|
|
129
|
+
};
|
|
130
|
+
}
|
package/src/http/middleware.ts
CHANGED
|
@@ -16,6 +16,12 @@ import { getAuthInstance } from "./resolve";
|
|
|
16
16
|
* call covers mobile and web. A credential-less request stays anonymous (no instance build, no D1 hit).
|
|
17
17
|
* Resolution never throws — an invalid credential simply leaves `auth` null for `requireAuth` to reject.
|
|
18
18
|
*/
|
|
19
|
+
/** The session's authentication instant when it is a real `Date`, else `null`. Never anything else. */
|
|
20
|
+
function authenticatedDate(session: unknown): Date | null {
|
|
21
|
+
const value = (session as { authenticatedAt?: unknown }).authenticatedAt;
|
|
22
|
+
return value instanceof Date ? value : null;
|
|
23
|
+
}
|
|
24
|
+
|
|
19
25
|
export function createSessionMiddleware(wiring: AuthWiring): PithyMiddleware {
|
|
20
26
|
return (app) => {
|
|
21
27
|
app.use("*", async (c, next) => {
|
|
@@ -38,6 +44,13 @@ export function createSessionMiddleware(wiring: AuthWiring): PithyMiddleware {
|
|
|
38
44
|
sessionId: session.session.id,
|
|
39
45
|
scopes: [],
|
|
40
46
|
locale: typeof stored === "string" && isLocale(stored) ? stored : null,
|
|
47
|
+
// Published for the same reason `locale` is: the session lookup has already loaded the
|
|
48
|
+
// row, so a gate that needs it should not pay for a second read. The adapter hands back
|
|
49
|
+
// a `Date`; a session predating the column hands back null, which reads as "cannot say".
|
|
50
|
+
// Guarded like `locale` beside it, and for a worse failure: `z.date()` throws on a
|
|
51
|
+
// string, the catch below swallows it, and every authenticated request in the Worker
|
|
52
|
+
// becomes anonymous — a total outage presenting as "everyone is logged out".
|
|
53
|
+
authenticatedAt: authenticatedDate(session.session),
|
|
41
54
|
}),
|
|
42
55
|
);
|
|
43
56
|
}
|
package/src/http/resolve.ts
CHANGED
|
@@ -141,6 +141,16 @@ async function buildAuthInstance(c: Context<PithyHonoEnv>, wiring: AuthWiring):
|
|
|
141
141
|
verificationExpiresIn: cfg.verificationExpiresIn,
|
|
142
142
|
otpLength: cfg.otpLength,
|
|
143
143
|
disableSignUp: cfg.disableSignUp,
|
|
144
|
+
// Per provider, and separate from the line above on purpose: `disableSignUp` governs magic link and
|
|
145
|
+
// OTP, this governs one OAuth provider. A project wanting email sign-up and no GitHub sign-up could
|
|
146
|
+
// not say so before, which is how an orphan user appeared (#554).
|
|
147
|
+
providerSignUp: {
|
|
148
|
+
google: cfg.google.allowSignUp,
|
|
149
|
+
apple: cfg.apple.allowSignUp,
|
|
150
|
+
facebook: cfg.facebook.allowSignUp,
|
|
151
|
+
github: cfg.github.allowSignUp,
|
|
152
|
+
},
|
|
153
|
+
...(wiring.resolveGithubUserInfo ? { resolveGithubUserInfo: wiring.resolveGithubUserInfo } : {}),
|
|
144
154
|
// Read the emit seam lazily so a later-composed audit capability is honored regardless of the
|
|
145
155
|
// capability order (the instance may be built before audit's middleware runs).
|
|
146
156
|
emit: (event) => c.var.emit(event),
|
package/src/http/routes.ts
CHANGED
|
@@ -22,6 +22,7 @@ import {
|
|
|
22
22
|
} from "../token/rotation";
|
|
23
23
|
import { registerAuthAdminRoutes } from "./adminRoutes";
|
|
24
24
|
import { apiErrorToPithy } from "./errors";
|
|
25
|
+
import { requireFreshAuthenticationToLink } from "./linkFreshness";
|
|
25
26
|
import { requireAuth } from "./middleware";
|
|
26
27
|
import { getAuthInstance, resolveDb } from "./resolve";
|
|
27
28
|
import { RevokeDeviceBody } from "./schemas";
|
|
@@ -87,6 +88,13 @@ export function createAuthRoutes(wiring: AuthWiring): (app: Hono<PithyHonoEnv>)
|
|
|
87
88
|
revokeMyDevice(c, wiring, c.req.valid("json")),
|
|
88
89
|
);
|
|
89
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));
|
|
97
|
+
|
|
90
98
|
// The control-plane management surface. Registered here, before the catch-all below, or it is dead.
|
|
91
99
|
registerAuthAdminRoutes(wiring)(app);
|
|
92
100
|
|
|
@@ -254,10 +262,28 @@ async function rotateToken(c: Ctx, wiring: AuthWiring): Promise<Response> {
|
|
|
254
262
|
|
|
255
263
|
const ip = headers.get("cf-connecting-ip") ?? undefined;
|
|
256
264
|
const userAgent = headers.get("user-agent") ?? undefined;
|
|
257
|
-
const session = current.session as {
|
|
265
|
+
const session = current.session as {
|
|
266
|
+
token: string;
|
|
267
|
+
deviceId?: string | null;
|
|
268
|
+
familyId?: string | null;
|
|
269
|
+
authenticatedAt?: Date | null;
|
|
270
|
+
};
|
|
258
271
|
const deviceId = session.deviceId ?? undefined;
|
|
259
272
|
// Carry the family forward across the rotation; a session that never had one starts a family now.
|
|
260
273
|
const familyId = session.familyId ?? crypto.randomUUID();
|
|
274
|
+
// **And carry the authentication instant, which is the whole point of the column.** A rotation is the
|
|
275
|
+
// same authentication continuing, not a new one — `createSession` would otherwise stamp `createdAt`
|
|
276
|
+
// afresh and leave the freshness gate measuring nothing, resettable by anyone holding a stolen refresh
|
|
277
|
+
// token (#558).
|
|
278
|
+
//
|
|
279
|
+
// **A session predating the column carries `null` forward, and must not fall back to `createdAt`.**
|
|
280
|
+
// That looked like a reasonable lower bound and is the opposite: `internal-adapter.mjs:275` stamps
|
|
281
|
+
// `createdAt` *after* the caller's override, so a row's `created_at` is the moment of its most recent
|
|
282
|
+
// rotation. Substituting it would hand every legacy session an authentication instant minutes old —
|
|
283
|
+
// freshest for exactly the actor rotating a stolen token — turning the one control that fails closed
|
|
284
|
+
// into one that fails open, on upgrade day, for the whole pre-migration population. `null` travels
|
|
285
|
+
// instead, the gate keeps refusing, and one real sign-in fixes it permanently.
|
|
286
|
+
const authenticatedAt = session.authenticatedAt ?? null;
|
|
261
287
|
|
|
262
288
|
// Mint the successor session and its access token BEFORE consuming the old one, so a transient signing
|
|
263
289
|
// failure leaves the presented refresh token still valid (the successor simply expires unused) rather
|
|
@@ -266,6 +292,7 @@ async function rotateToken(c: Ctx, wiring: AuthWiring): Promise<Response> {
|
|
|
266
292
|
ipAddress: ip,
|
|
267
293
|
userAgent,
|
|
268
294
|
familyId,
|
|
295
|
+
authenticatedAt,
|
|
269
296
|
...(deviceId ? { deviceId } : {}),
|
|
270
297
|
});
|
|
271
298
|
const access = await instance.api.getToken({ headers: new Headers({ authorization: `Bearer ${next.token}` }) });
|