@pithy-sh/auth 0.9.0 → 0.10.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/README.md +8 -2
- package/dist/audit/actions.d.ts +21 -0
- package/dist/audit/actions.d.ts.map +1 -1
- package/dist/audit/actions.js +22 -1
- package/dist/audit/emit.js +1 -1
- package/dist/capability.d.ts +26 -1
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +23 -5
- package/dist/client/lifecycle.d.ts +19 -0
- package/dist/client/lifecycle.d.ts.map +1 -0
- package/dist/client/lifecycle.js +25 -0
- package/dist/client/projection.d.ts +4 -0
- package/dist/client/projection.d.ts.map +1 -1
- package/dist/data/betterAuth.d.ts +4 -0
- package/dist/data/betterAuth.d.ts.map +1 -1
- package/dist/data/betterAuth.js +6 -2
- package/dist/data/kitFields.d.ts +20 -25
- package/dist/data/kitFields.d.ts.map +1 -1
- package/dist/data/kitFields.js +28 -32
- package/dist/data/tables.d.ts +28 -2
- package/dist/data/tables.d.ts.map +1 -1
- package/dist/data/tables.js +5 -3
- package/dist/data/userLifecycle.d.ts +61 -0
- package/dist/data/userLifecycle.d.ts.map +1 -0
- package/dist/data/userLifecycle.js +50 -0
- package/dist/http/guards.d.ts +23 -1
- package/dist/http/guards.d.ts.map +1 -1
- package/dist/http/guards.js +28 -3
- package/dist/http/lifecycleGate.d.ts +18 -0
- package/dist/http/lifecycleGate.d.ts.map +1 -0
- package/dist/http/lifecycleGate.js +75 -0
- package/dist/http/middleware.d.ts +5 -0
- package/dist/http/middleware.d.ts.map +1 -1
- package/dist/http/middleware.js +47 -6
- package/dist/http/providerRefusal.d.ts.map +1 -1
- package/dist/http/providerRefusal.js +8 -0
- package/dist/http/resolve.d.ts.map +1 -1
- package/dist/http/resolve.js +7 -4
- package/dist/http/routes.d.ts.map +1 -1
- package/dist/http/routes.js +20 -1
- package/dist/instance/auth.d.ts +55 -3
- package/dist/instance/auth.d.ts.map +1 -1
- package/dist/instance/auth.js +53 -2
- package/dist/instance/microsoftEmail.d.ts +70 -0
- package/dist/instance/microsoftEmail.d.ts.map +1 -0
- package/dist/instance/microsoftEmail.js +96 -0
- package/dist/instance/providerSignInGate.d.ts +7 -6
- package/dist/instance/providerSignInGate.d.ts.map +1 -1
- package/dist/instance/providerSignInGate.js +7 -6
- package/dist/instance/providers.d.ts +7 -5
- package/dist/instance/providers.d.ts.map +1 -1
- package/dist/instance/providers.js +5 -3
- package/dist/instance/secrets.d.ts +64 -3
- package/dist/instance/secrets.d.ts.map +1 -1
- package/dist/instance/secrets.js +44 -5
- package/dist/lifecycle/enforce.d.ts +40 -0
- package/dist/lifecycle/enforce.d.ts.map +1 -0
- package/dist/lifecycle/enforce.js +70 -0
- package/dist/lifecycle/hooks.d.ts +53 -0
- package/dist/lifecycle/hooks.d.ts.map +1 -0
- package/dist/lifecycle/hooks.js +2 -0
- package/dist/lifecycle/request.d.ts +15 -0
- package/dist/lifecycle/request.d.ts.map +1 -0
- package/dist/lifecycle/request.js +27 -0
- package/dist/lifecycle/state.d.ts +64 -0
- package/dist/lifecycle/state.d.ts.map +1 -0
- package/dist/lifecycle/state.js +90 -0
- package/dist/lifecycle/transitions.d.ts +132 -0
- package/dist/lifecycle/transitions.d.ts.map +1 -0
- package/dist/lifecycle/transitions.js +349 -0
- package/dist/migrations/0004_user_lifecycle.d.ts +28 -0
- package/dist/migrations/0004_user_lifecycle.d.ts.map +1 -0
- package/dist/migrations/0004_user_lifecycle.js +47 -0
- package/dist/migrations/set.d.ts +2 -1
- package/dist/migrations/set.d.ts.map +1 -1
- package/dist/migrations/set.js +4 -2
- package/dist/peer.d.ts +4 -0
- package/dist/peer.d.ts.map +1 -1
- package/dist/test-utils/liveApp.d.ts +21 -0
- package/dist/test-utils/liveApp.d.ts.map +1 -1
- package/dist/test-utils/liveApp.js +1 -0
- package/dist/test-utils/scopedBackend.d.ts +21 -0
- package/dist/test-utils/scopedBackend.d.ts.map +1 -1
- package/dist/test-utils/scopedBackend.js +7 -1
- package/dist/version.generated.d.ts +1 -1
- package/dist/version.generated.d.ts.map +1 -1
- package/dist/version.generated.js +1 -1
- package/docs/account-lifecycle.md +105 -0
- package/docs/apple-signin.md +7 -1
- package/docs/facebook-oauth.md +7 -1
- package/docs/github-oauth.md +7 -1
- package/docs/google-oauth.md +7 -1
- package/docs/microsoft-oauth.md +177 -0
- package/package.json +5 -5
- package/pithy.manifest.json +17 -3
- package/src/audit/actions.ts +23 -0
- package/src/audit/emit.ts +1 -1
- package/src/capability.ts +125 -54
- package/src/client/lifecycle.ts +27 -0
- package/src/client/projection.ts +4 -0
- package/src/data/betterAuth.ts +21 -1
- package/src/data/kitFields.ts +27 -0
- package/src/data/tables.ts +4 -2
- package/src/data/userLifecycle.ts +80 -0
- package/src/http/guards.ts +29 -1
- package/src/http/lifecycleGate.ts +78 -0
- package/src/http/middleware.ts +61 -2
- package/src/http/providerRefusal.ts +10 -0
- package/src/http/resolve.ts +8 -3
- package/src/http/routes.ts +38 -1
- package/src/instance/auth.ts +69 -2
- package/src/instance/microsoftEmail.ts +111 -0
- package/src/instance/providerSignInGate.ts +7 -6
- package/src/instance/providers.ts +8 -4
- package/src/instance/secrets.ts +59 -5
- package/src/lifecycle/enforce.ts +89 -0
- package/src/lifecycle/hooks.ts +54 -0
- package/src/lifecycle/request.ts +31 -0
- package/src/lifecycle/state.ts +101 -0
- package/src/lifecycle/transitions.ts +483 -0
- package/src/migrations/0004_user_lifecycle.ts +68 -0
- package/src/migrations/set.ts +3 -1
- package/src/test-utils/liveApp.ts +2 -1
- package/src/test-utils/scopedBackend.ts +2 -1
- package/src/version.generated.ts +1 -1
package/src/http/middleware.ts
CHANGED
|
@@ -2,14 +2,17 @@
|
|
|
2
2
|
// SPDX-License-Identifier: MIT
|
|
3
3
|
|
|
4
4
|
import type { PithyHonoEnv, PithyMiddleware } from "@pithy-sh/core/src/capability/capability";
|
|
5
|
-
import { UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
|
|
5
|
+
import { InternalError, type PithyError, UnauthorizedError } from "@pithy-sh/core/src/error/pithyError";
|
|
6
6
|
import { AuthContext } from "@pithy-sh/core/src/http/authContext";
|
|
7
7
|
import { isLocale } from "@pithy-sh/core/src/i18n/locale";
|
|
8
8
|
import type { Context, MiddlewareHandler } from "hono";
|
|
9
9
|
import type { AuthWiring, ScopeResolver, ScopeResolverSession } from "../capability";
|
|
10
|
+
import { authDatabase } from "../data/tables";
|
|
10
11
|
import type { AuthInstance } from "../instance/auth";
|
|
12
|
+
import { lifecycleRefusalFor, noteRefusal, noticedRefusal } from "../lifecycle/enforce";
|
|
13
|
+
import { LifecycleColumns } from "../lifecycle/state";
|
|
11
14
|
import { withResignedCredentials } from "./credentialResign";
|
|
12
|
-
import { getAuthInstance } from "./resolve";
|
|
15
|
+
import { getAuthInstance, resolveDb } from "./resolve";
|
|
13
16
|
|
|
14
17
|
/**
|
|
15
18
|
* The session-resolution middleware: it fills core's `AuthContext` seam (`c.var.auth`) for every
|
|
@@ -93,6 +96,16 @@ async function resolveSession(c: Context<PithyHonoEnv>, wiring: AuthWiring, inst
|
|
|
93
96
|
try {
|
|
94
97
|
const session = await instance.api.getSession({ headers });
|
|
95
98
|
if (session) {
|
|
99
|
+
// **A suspended or deleted account gets no `AuthContext` at all** (#620). Read off the user Better
|
|
100
|
+
// Auth just loaded, which carries the four columns, so an account in good standing costs nothing
|
|
101
|
+
// here. Leaving `auth` null is what makes every `requireAuth()` in the kit refuse it — the copies
|
|
102
|
+
// other capabilities carry included, since each one only asks whether `auth` was filled. This
|
|
103
|
+
// capability's own guard raises the refusal itself, with its code; see `requireAuth` below.
|
|
104
|
+
const refusal = await standingRefusal(c, wiring, session.user);
|
|
105
|
+
if (refusal) {
|
|
106
|
+
noteRefusal(c, refusal);
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
96
109
|
// Before the context is built, so a resolver sees the request exactly as it arrived and the
|
|
97
110
|
// context is published once, whole. Per request and never cached: the answer is about this
|
|
98
111
|
// request's caller, and a cached one is a revocation that has not taken effect (#560).
|
|
@@ -128,13 +141,59 @@ async function resolveSession(c: Context<PithyHonoEnv>, wiring: AuthWiring, inst
|
|
|
128
141
|
}
|
|
129
142
|
}
|
|
130
143
|
|
|
144
|
+
/**
|
|
145
|
+
* The refusal for the session's account, or `null` when it may act.
|
|
146
|
+
*
|
|
147
|
+
* **A check that cannot be made refuses**, rather than throwing into `resolveSession`'s catch. That catch
|
|
148
|
+
* leaves `auth` null and notes nothing, and `handleBetterAuth` only refuses on a noted verdict — so a failed
|
|
149
|
+
* read of a suspension's reason, or a column that will not decode, would let Better Auth's own `/token` mint a
|
|
150
|
+
* JWT for the suspended account it resolved on its own. So the failure is logged and becomes the verdict: a
|
|
151
|
+
* 500, since the fault is this Worker's, and every door that honors a lifecycle refusal honors this one.
|
|
152
|
+
*/
|
|
153
|
+
async function standingRefusal(
|
|
154
|
+
c: Context<PithyHonoEnv>,
|
|
155
|
+
wiring: AuthWiring,
|
|
156
|
+
user: { id: string },
|
|
157
|
+
): Promise<PithyError | null> {
|
|
158
|
+
try {
|
|
159
|
+
return await lifecycleRefusalFor(
|
|
160
|
+
authDatabase(resolveDb(c.env, wiring.config.database)),
|
|
161
|
+
user.id,
|
|
162
|
+
LifecycleColumns.parse(user),
|
|
163
|
+
new Date(),
|
|
164
|
+
);
|
|
165
|
+
} catch (cause) {
|
|
166
|
+
// Optional, unlike the logger elsewhere here: this branch is the refusal, and a missing logger must not
|
|
167
|
+
// turn it back into the throw it exists to replace.
|
|
168
|
+
c.var.log?.child("auth").warn("the account's standing could not be checked; the request is refused", {
|
|
169
|
+
userId: user.id,
|
|
170
|
+
reason: cause instanceof Error ? cause.message : String(cause),
|
|
171
|
+
});
|
|
172
|
+
return new InternalError(
|
|
173
|
+
{
|
|
174
|
+
message: "This account could not be checked. Try again shortly.",
|
|
175
|
+
action: "Check the auth database binding and that the auth migrations have run.",
|
|
176
|
+
detail: `lifecycle check for user ${user.id} failed`,
|
|
177
|
+
},
|
|
178
|
+
{ cause },
|
|
179
|
+
);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
131
183
|
/**
|
|
132
184
|
* The gate other capabilities stack on a protected route. Rejects a request whose `AuthContext` was
|
|
133
185
|
* not filled (no valid credential) with a `PithyError` `auth/invalid_token` (401).
|
|
186
|
+
*
|
|
187
|
+
* **A genuine credential for an account that may not act is refused with what happened to it** —
|
|
188
|
+
* `auth/account_suspended` or `auth/account_deleted`, 403 — rather than the 401, because signing in again
|
|
189
|
+
* cannot help and a client that read it as an expired token would loop. The verdict is the session
|
|
190
|
+
* middleware's, remembered for this request; this guard only raises it.
|
|
134
191
|
*/
|
|
135
192
|
export function requireAuth(): MiddlewareHandler<PithyHonoEnv> {
|
|
136
193
|
return async (c, next) => {
|
|
137
194
|
if (!c.var.auth) {
|
|
195
|
+
const refusal = noticedRefusal(c);
|
|
196
|
+
if (refusal) throw refusal;
|
|
138
197
|
throw new UnauthorizedError({
|
|
139
198
|
message: "Authentication required.",
|
|
140
199
|
action: "Sign in and retry with a valid session or bearer token.",
|
|
@@ -169,6 +169,16 @@ const PROVIDER_REFUSAL_VERDICTS: Readonly<Record<string, RefusalVerdict>> = {
|
|
|
169
169
|
why: "Two producers, and the verdict follows the one that reads our rows. `linkOAuthAccount` (link-account.mjs:45/68) answers it on `/link-social`, where the caller is signed in as the user being changed. But `handleOAuthUserInfo` answers it too, inside `if (dbUser)` when the account write fails (:171/:184), so on the social callback it says a row matched, and `unable_to_create_user` is its other half. Collapsing costs the signed-in linker a specific code for a fault. Letting it travel would cost the oracle. Corrected in #787; the earlier verdict read only the link flow.",
|
|
170
170
|
},
|
|
171
171
|
|
|
172
|
+
// ── The account's own standing, told to the person who just proved they hold it. ──────────────
|
|
173
|
+
"auth/account_suspended": {
|
|
174
|
+
collapse: false,
|
|
175
|
+
why: "The kit's own `session.create.before` hook (instance/auth.ts, #620). A session is only ever created for a user the callback has already resolved and linked — the caller has just proved control of a provider identity bound to this account — so the code is told to its holder, never to somebody probing an address. Collapsing it would leave a suspended person with a screen that says nothing happened.",
|
|
176
|
+
},
|
|
177
|
+
"auth/account_deleted": {
|
|
178
|
+
collapse: false,
|
|
179
|
+
why: "The same hook, for an account inside its purge window, and the same reasoning: it is reached only after the caller authenticated as the account, so it names the state of their own account to them.",
|
|
180
|
+
},
|
|
181
|
+
|
|
172
182
|
// ── The caller's own request, or the provider's. Nothing to do with our rows. ──────────────────
|
|
173
183
|
no_code: {
|
|
174
184
|
collapse: false,
|
package/src/http/resolve.ts
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// SPDX-License-Identifier: MIT
|
|
3
3
|
|
|
4
4
|
import type { D1Database } from "@cloudflare/workers-types";
|
|
5
|
+
import type { AuditEventInput } from "@pithy-sh/core/src/audit/auditEvent";
|
|
5
6
|
import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
|
|
6
7
|
import { InternalError } from "@pithy-sh/core/src/error/pithyError";
|
|
7
8
|
import { createWorkerLogger } from "@pithy-sh/core/src/logger/worker";
|
|
@@ -19,6 +20,7 @@ import {
|
|
|
19
20
|
resolveFacebookCredentials,
|
|
20
21
|
resolveGithubCredentials,
|
|
21
22
|
resolveGoogleCredentials,
|
|
23
|
+
resolveMicrosoftCredentials,
|
|
22
24
|
resolveSessionSecrets,
|
|
23
25
|
} from "../instance/secrets";
|
|
24
26
|
import { baseURLResolver } from "./baseUrl";
|
|
@@ -87,7 +89,7 @@ async function buildAuthInstance(c: Context<PithyHonoEnv>, wiring: AuthWiring):
|
|
|
87
89
|
});
|
|
88
90
|
}
|
|
89
91
|
const env = c.env as unknown as AuthEnv;
|
|
90
|
-
// Secret resolutions hit the same per-invocation cache; run them concurrently.
|
|
92
|
+
// Secret resolutions hit the same per-invocation cache; run them concurrently. Six reads, and they
|
|
91
93
|
// are not alike — which is the whole of #381.
|
|
92
94
|
//
|
|
93
95
|
// `resolveSessionSecret` is what an auth instance *is*: nothing signs a session without it, so its
|
|
@@ -105,12 +107,13 @@ async function buildAuthInstance(c: Context<PithyHonoEnv>, wiring: AuthWiring):
|
|
|
105
107
|
//
|
|
106
108
|
// A held failure belongs to its own secret (#170), so an unreadable provider credential does not
|
|
107
109
|
// disturb the session secret's own read, and a *disabled* provider never calls `.get()` at all.
|
|
108
|
-
const [sessionSecrets, google, apple, facebook, github] = await Promise.all([
|
|
110
|
+
const [sessionSecrets, google, apple, facebook, github, microsoft] = await Promise.all([
|
|
109
111
|
resolveSessionSecrets(env),
|
|
110
112
|
resolveProvider(cfg.google.enabled, () => resolveGoogleCredentials(env)),
|
|
111
113
|
resolveProvider(cfg.apple.enabled, () => resolveAppleCredentials(env)),
|
|
112
114
|
resolveProvider(cfg.facebook.enabled, () => resolveFacebookCredentials(env)),
|
|
113
115
|
resolveProvider(cfg.github.enabled, () => resolveGithubCredentials(env)),
|
|
116
|
+
resolveProvider(cfg.microsoft.enabled, () => resolveMicrosoftCredentials(env)),
|
|
114
117
|
]);
|
|
115
118
|
const expiresMinutes = Math.max(1, Math.round(cfg.verificationExpiresIn / 60));
|
|
116
119
|
const d1 = resolveDb(c.env, cfg.database);
|
|
@@ -161,6 +164,7 @@ async function buildAuthInstance(c: Context<PithyHonoEnv>, wiring: AuthWiring):
|
|
|
161
164
|
apple,
|
|
162
165
|
facebook,
|
|
163
166
|
github,
|
|
167
|
+
microsoft,
|
|
164
168
|
sendEmail: makeSendAuthEmail(
|
|
165
169
|
(input) => enqueueEmail(env, input),
|
|
166
170
|
expiresMinutes,
|
|
@@ -179,11 +183,12 @@ async function buildAuthInstance(c: Context<PithyHonoEnv>, wiring: AuthWiring):
|
|
|
179
183
|
apple: cfg.apple.allowSignUp,
|
|
180
184
|
facebook: cfg.facebook.allowSignUp,
|
|
181
185
|
github: cfg.github.allowSignUp,
|
|
186
|
+
microsoft: cfg.microsoft.allowSignUp,
|
|
182
187
|
},
|
|
183
188
|
...(wiring.resolveGithubUserInfo ? { resolveGithubUserInfo: wiring.resolveGithubUserInfo } : {}),
|
|
184
189
|
// Read the emit seam lazily so a later-composed audit capability is honored regardless of the
|
|
185
190
|
// capability order (the instance may be built before audit's middleware runs).
|
|
186
|
-
emit: (event) => c.var.emit(event),
|
|
191
|
+
emit: (event: AuditEventInput) => c.var.emit(event),
|
|
187
192
|
// This request's own headers, for the refusal rows `../instance/providerSignInGate` writes from
|
|
188
193
|
// inside `getUserInfo`, where no request is in scope to read them from.
|
|
189
194
|
requestHeaders: c.req.raw.headers,
|
package/src/http/routes.ts
CHANGED
|
@@ -14,6 +14,8 @@ import { correlation, emitDenied, emitDeviceRevoked, emitTokenRefresh, emitToken
|
|
|
14
14
|
import type { AuthWiring } from "../capability";
|
|
15
15
|
import { authDatabase } from "../data/tables";
|
|
16
16
|
import { deleteDevice, deviceSessionTokens, listDevices } from "../device/registry";
|
|
17
|
+
import { noticedRefusal } from "../lifecycle/enforce";
|
|
18
|
+
import { isLifecycleRefusal } from "../lifecycle/state";
|
|
17
19
|
import { PROFILE_IMAGE_PATH } from "../profile/profile";
|
|
18
20
|
import {
|
|
19
21
|
consumeSession,
|
|
@@ -25,6 +27,7 @@ import {
|
|
|
25
27
|
import { registerAuthAdminRoutes } from "./adminRoutes";
|
|
26
28
|
import { guardErrorCallbackURL } from "./errorCallbackUrl";
|
|
27
29
|
import { apiErrorToPithy } from "./errors";
|
|
30
|
+
import { admitsRefusedAccount, lifecycleRedirect } from "./lifecycleGate";
|
|
28
31
|
import { requireAuth } from "./middleware";
|
|
29
32
|
import { requireFreshAuthentication } from "./providerFreshness";
|
|
30
33
|
import { collapseProviderRefusal } from "./providerRefusal";
|
|
@@ -279,6 +282,15 @@ async function auditRefusal(c: Ctx, response: Response): Promise<void> {
|
|
|
279
282
|
async function handleBetterAuth(c: Ctx, wiring: AuthWiring): Promise<Response> {
|
|
280
283
|
const instance = await getAuthInstance(c, wiring);
|
|
281
284
|
|
|
285
|
+
// **A suspended or deleted account does not reach Better Auth as itself (#620).** The session middleware
|
|
286
|
+
// has already refused it an `AuthContext`, but Better Auth resolves its own session on these endpoints and
|
|
287
|
+
// would happily mint a `/token` for it. So its verdict is applied here too, on every endpoint that acts as
|
|
288
|
+
// the credential's holder — and not on the ones that end a session or start a new one. `./lifecycleGate`
|
|
289
|
+
// says which, and why a stale cookie must not stop somebody else signing in.
|
|
290
|
+
const pathname = new URL(c.req.raw.url).pathname;
|
|
291
|
+
const refusal = noticedRefusal(c);
|
|
292
|
+
if (refusal && !admitsRefusedAccount(pathname.slice(wiring.config.basePath.length))) throw refusal;
|
|
293
|
+
|
|
282
294
|
// **The first of the two guards on the refusal redirect (#625).** `errorCallbackURL` is the caller's
|
|
283
295
|
// string and `redirectOnError` builds the redirect on it, so the shape handed *in* decides
|
|
284
296
|
// whether the collapse below is reading a query at all. `./errorCallbackUrl` normalizes it to something
|
|
@@ -290,7 +302,26 @@ async function handleBetterAuth(c: Ctx, wiring: AuthWiring): Promise<Response> {
|
|
|
290
302
|
try {
|
|
291
303
|
response = await instance.handler(request);
|
|
292
304
|
} catch (error) {
|
|
293
|
-
|
|
305
|
+
const pithy = apiErrorToPithy(error);
|
|
306
|
+
// A sign-in refused because the account is suspended or deleted: the session hook threw it, so it
|
|
307
|
+
// arrives here rather than as a Better Auth response, and is recorded here for the same reason.
|
|
308
|
+
if (isLifecycleRefusal(pithy)) {
|
|
309
|
+
if (isSignInAttempt(pathname)) {
|
|
310
|
+
await emitDenied(c.var.emit, { ...correlation(c.req.raw.headers), detail: pithy.payload.code });
|
|
311
|
+
}
|
|
312
|
+
// A magic link is a browser navigation, so the refusal goes back to the screen the link named rather
|
|
313
|
+
// than stranding the reader on this origin's 403. OTP and every JSON caller get the envelope.
|
|
314
|
+
if (c.req.method === "GET" && pathname === `${wiring.config.basePath}/magic-link/verify`) {
|
|
315
|
+
const redirect = lifecycleRedirect(
|
|
316
|
+
new URL(request.url),
|
|
317
|
+
wiring.config.baseURL,
|
|
318
|
+
wiring.config.trustedOrigins,
|
|
319
|
+
pithy,
|
|
320
|
+
);
|
|
321
|
+
if (redirect) return redirect;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
throw pithy;
|
|
294
325
|
}
|
|
295
326
|
|
|
296
327
|
// **The enumeration oracle on the social callback, closed here because here is the only place both
|
|
@@ -390,6 +421,12 @@ async function rotateToken(c: Ctx, wiring: AuthWiring): Promise<Response> {
|
|
|
390
421
|
});
|
|
391
422
|
}
|
|
392
423
|
|
|
424
|
+
// An account that may not act gets no successor (#620). `session.create.before` would refuse the mint below
|
|
425
|
+
// anyway; refusing here, from the middleware's verdict, is what keeps the presented token unspent and the
|
|
426
|
+
// successor never written, so a reinstated account's device still holds a credential that works.
|
|
427
|
+
const refusal = noticedRefusal(c);
|
|
428
|
+
if (refusal) throw refusal;
|
|
429
|
+
|
|
393
430
|
const ip = headers.get("cf-connecting-ip") ?? undefined;
|
|
394
431
|
const userAgent = headers.get("user-agent") ?? undefined;
|
|
395
432
|
const session = current.session as {
|
package/src/instance/auth.ts
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// SPDX-License-Identifier: MIT
|
|
3
3
|
|
|
4
4
|
import type { AuditEmit } from "@pithy-sh/core/src/audit/recorder";
|
|
5
|
+
import type { PithyError } from "@pithy-sh/core/src/error/pithyError";
|
|
5
6
|
import { type BetterAuthPlugin, betterAuth } from "better-auth";
|
|
6
7
|
import { APIError, createAuthMiddleware } from "better-auth/api";
|
|
7
8
|
import { emitAfterRequest, emitProviderAccountChanged, emitProviderUnavailable } from "../audit/emit";
|
|
@@ -16,8 +17,10 @@ import { KIT_SESSION_FIELDS, KIT_USER_FIELDS } from "../data/kitFields";
|
|
|
16
17
|
import type { AuthDatabase } from "../data/tables";
|
|
17
18
|
import { parseDeviceMeta, registerDevice } from "../device/registry";
|
|
18
19
|
import { PROVIDER_CHANGE_FRESH_AGE_SECONDS } from "../http/providerFreshness";
|
|
20
|
+
import { lifecycleRefusalFor } from "../lifecycle/enforce";
|
|
19
21
|
import { refuseUnsafeProfile, sanitizeProfile } from "../profile/profile";
|
|
20
22
|
import { defaultGithubUserInfo, type GithubUserInfoResolver } from "./githubUserInfo";
|
|
23
|
+
import { microsoftProfileToUser } from "./microsoftEmail";
|
|
21
24
|
import { kitPlugins } from "./plugins";
|
|
22
25
|
import {
|
|
23
26
|
providerUnavailable,
|
|
@@ -105,9 +108,39 @@ export function socialProviders(deps: AuthInstanceDeps): Record<string, unknown>
|
|
|
105
108
|
...signUpOption(deps.providerSignUp.github),
|
|
106
109
|
};
|
|
107
110
|
}
|
|
111
|
+
if (deps.microsoft.state === "ready") {
|
|
112
|
+
// Entra ID cannot vouch for an email it did not verify: work and school tokens carry no
|
|
113
|
+
// `email_verified`, and `email` is a directory attribute a tenant admin sets to anything. So
|
|
114
|
+
// Microsoft stays out of `trustedProviders`, and `mapProfileToUser` decides the flag from the two
|
|
115
|
+
// claims Microsoft computes and a tenant cannot write — `./microsoftEmail.ts` has the rule. It is
|
|
116
|
+
// spread over Better Auth's own default, which reads claims a tenant can influence.
|
|
117
|
+
const microsoft = deps.microsoft.credentials;
|
|
118
|
+
providers.microsoft = {
|
|
119
|
+
clientId: microsoft.clientId,
|
|
120
|
+
clientSecret: microsoft.clientSecret,
|
|
121
|
+
tenantId: microsoft.tenantId,
|
|
122
|
+
// The stock resolver fetches a Graph photo and stores it as `data:image/jpeg;base64, …` — a space
|
|
123
|
+
// after the comma, which `../profile/profile.ts` refuses, so the create hook would drop every one.
|
|
124
|
+
// A third-party fetch per sign-in for a value that is always discarded is not worth making.
|
|
125
|
+
disableProfilePhoto: true,
|
|
126
|
+
mapProfileToUser: microsoftProfileToUser,
|
|
127
|
+
...signUpOption(deps.providerSignUp.microsoft),
|
|
128
|
+
};
|
|
129
|
+
}
|
|
108
130
|
return Object.keys(providers).length > 0 ? providers : undefined;
|
|
109
131
|
}
|
|
110
132
|
|
|
133
|
+
/**
|
|
134
|
+
* The providers whose email links into an existing account on the strength of their name alone.
|
|
135
|
+
*
|
|
136
|
+
* Google and Apple, and nobody else, permanently. Facebook's verified flag is asserted in its block with
|
|
137
|
+
* a reason; GitHub's comes from its emails API; Microsoft's is decided per sign-in by
|
|
138
|
+
* `./microsoftEmail.ts`, because Entra ID cannot vouch for an email it did not verify. Adding a provider
|
|
139
|
+
* here would skip the verified half of the linking gate for it — `./providerSignInGate.ts` reads the same
|
|
140
|
+
* list off the context.
|
|
141
|
+
*/
|
|
142
|
+
export const TRUSTED_PROVIDERS: readonly string[] = ["google", "apple"];
|
|
143
|
+
|
|
111
144
|
/**
|
|
112
145
|
* The seeding guard: a new account may be created only for an email a provider has **verified**.
|
|
113
146
|
*
|
|
@@ -137,10 +170,37 @@ function refuseUnsafeProfileFields(user: { name?: unknown; image?: unknown }): v
|
|
|
137
170
|
throw new APIError("BAD_REQUEST", { code: "INVALID_PROFILE_FIELD", message: refusal.message });
|
|
138
171
|
}
|
|
139
172
|
|
|
140
|
-
/** The endpoint context a database hook is handed, narrowed to
|
|
173
|
+
/** The endpoint context a database hook is handed, narrowed to what attribution and refusal need. */
|
|
141
174
|
interface HookContext {
|
|
142
175
|
headers?: Headers;
|
|
143
176
|
context?: { session?: { user?: { id?: string } } | null };
|
|
177
|
+
/** The endpoint path this write was reached from, e.g. `/callback/google`. Absent outside an endpoint. */
|
|
178
|
+
path?: string;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Refuse a session for an account that may not act, in the shape the endpoint creating it can answer.
|
|
183
|
+
*
|
|
184
|
+
* **On the social callback, an `APIError` carrying the kit's code**, because that endpoint answers a refusal
|
|
185
|
+
* by redirecting to the caller's `errorCallbackURL` with `?error=<code>` — but only for an `APIError`
|
|
186
|
+
* (`callback.mjs:192`). A `PithyError` would escape it and leave a browser mid-OAuth on a bare 403 body
|
|
187
|
+
* instead of back on the adopter's screen. The code is the same string either way, and the reason travels as
|
|
188
|
+
* `error_description`, which is where Better Auth puts a refusal's message.
|
|
189
|
+
*
|
|
190
|
+
* **Everywhere else, the `PithyError` itself**, which `handleBetterAuth` renders through the one error
|
|
191
|
+
* envelope — or, on the magic-link verify redirect, turns into the same `?error=` redirect.
|
|
192
|
+
*/
|
|
193
|
+
function refuseSession(refusal: PithyError, ctx: HookContext | null | undefined): never {
|
|
194
|
+
if (ctx?.path?.startsWith("/callback/")) {
|
|
195
|
+
// Spelled out per code rather than copied off the payload, so `providerRefusal.test.ts` — which reads
|
|
196
|
+
// every `APIError` code in this package off the source — sees both and holds each to a verdict.
|
|
197
|
+
const message = refusal.payload.message;
|
|
198
|
+
if (refusal.payload.code === "auth/account_deleted") {
|
|
199
|
+
throw new APIError("FORBIDDEN", { code: "auth/account_deleted", message });
|
|
200
|
+
}
|
|
201
|
+
throw new APIError("FORBIDDEN", { code: "auth/account_suspended", message });
|
|
202
|
+
}
|
|
203
|
+
throw refusal;
|
|
144
204
|
}
|
|
145
205
|
|
|
146
206
|
/**
|
|
@@ -457,6 +517,13 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
|
|
|
457
517
|
* `deviceId` by override for the same reason.
|
|
458
518
|
*/
|
|
459
519
|
before: async (session, ctx) => {
|
|
520
|
+
// **No session for an account that may not act (#620).** Every sign-in and every token
|
|
521
|
+
// refresh creates its session here — magic link, OTP, each social callback, `/token/rotate` —
|
|
522
|
+
// so this one check is what makes a suspension hold at every door, and the reason it is not
|
|
523
|
+
// written once per endpoint. The row is read rather than trusted from the caller: nothing
|
|
524
|
+
// that arrives with a sign-in may say whether its own account is suspended.
|
|
525
|
+
const refusal = await lifecycleRefusalFor(deps.db, session.userId, null, new Date());
|
|
526
|
+
if (refusal) refuseSession(refusal, ctx);
|
|
460
527
|
// **`undefined` and `null` are different answers here, and collapsing them is a hole.**
|
|
461
528
|
// Absent means nobody supplied one, which is a sign-in: stamp it. Present-and-null is a
|
|
462
529
|
// rotation of a session written before the column existed, and it must stay null so the gate
|
|
@@ -614,7 +681,7 @@ export function makeAuth<const Plugins extends readonly BetterAuthPlugin[]>(deps
|
|
|
614
681
|
accountLinking: {
|
|
615
682
|
enabled: true,
|
|
616
683
|
// Link a social sign-in to an existing magic-link user when the verified emails match.
|
|
617
|
-
trustedProviders: [
|
|
684
|
+
trustedProviders: [...TRUSTED_PROVIDERS],
|
|
618
685
|
/**
|
|
619
686
|
* **A signed-in user may attach a provider whose email differs from their account's.**
|
|
620
687
|
*
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import { getOAuthState } from "better-auth/api";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Whether a Microsoft sign-in's email is the signer's own — the one decision the Microsoft provider adds (#262).
|
|
8
|
+
*
|
|
9
|
+
* ## Why Microsoft needs a rule of its own
|
|
10
|
+
*
|
|
11
|
+
* Every other provider the kit serves can say which address it verified. Entra ID cannot. A work or
|
|
12
|
+
* school ID token carries no `email_verified` claim, and its `email` is read from the directory's `mail`
|
|
13
|
+
* attribute — which a tenant admin sets to any string, a stranger's address at a domain they do not own
|
|
14
|
+
* included. Sign in, and the token asserts you are somebody else. That is the nOAuth takeover class, and
|
|
15
|
+
* it is a property of Entra ID, not of an app's configuration. Microsoft's own claims reference says of
|
|
16
|
+
* `email`: "This value isn't guaranteed to be correct, and is mutable over time - never use it for
|
|
17
|
+
* authorization." So Microsoft stays out of `trustedProviders` permanently, and this decides the flag.
|
|
18
|
+
*
|
|
19
|
+
* ## The three ways an address is verified, and nothing else
|
|
20
|
+
*
|
|
21
|
+
* - **`xms_edov === true`** — "email domain owner verified", the optional claim Microsoft published as
|
|
22
|
+
* the nOAuth remediation. The tenant provably owns the address's domain, so it cannot be a stranger's.
|
|
23
|
+
* Off unless the app registration asks for it; `docs/microsoft-oauth.md` walks that step.
|
|
24
|
+
* - **`tid` is the personal-accounts tenant.** A personal Microsoft account is in no directory, has no
|
|
25
|
+
* admin, and its address is the account itself, confirmed by Microsoft at sign-up. It never carries
|
|
26
|
+
* `xms_edov`, so it needs its own clause.
|
|
27
|
+
* - **Linking from inside the account, to the account's own address.** The verify-to-link challenge's
|
|
28
|
+
* second half. Somebody refused above signs in by magic link — which proves the address — and connects
|
|
29
|
+
* Microsoft from inside. That Microsoft identity naming the very address the session holds is verified
|
|
30
|
+
* by the kit, not by Microsoft. A different address is not, and Better Auth's link branch refuses it.
|
|
31
|
+
*
|
|
32
|
+
* Anything else — the claim absent, `false`, `"true"`, `1` — is unverified. **Absence is never read as
|
|
33
|
+
* verification**, and only the boolean `true` is. `email_verified` and `verified_primary_email` are read
|
|
34
|
+
* by Better Auth's own default and deliberately not here: Entra does not issue the first for work
|
|
35
|
+
* accounts, and the second is sourced from directory attributes this rule does not get to vouch for.
|
|
36
|
+
*
|
|
37
|
+
* `oid` and `tid` are immutable, so once an identity is linked it signs in on `oid` forever
|
|
38
|
+
* (`./providerSignInGate.ts`, row 1) and none of this runs again for it.
|
|
39
|
+
*/
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The tenant id every personal Microsoft account signs in under.
|
|
43
|
+
*
|
|
44
|
+
* Source: https://learn.microsoft.com/en-us/entra/identity-platform/id-token-claims-reference — the `tid`
|
|
45
|
+
* row: "For sign-ins to the personal Microsoft account tenant (services like Xbox, Teams for Life, or
|
|
46
|
+
* Outlook), the value is `9188040d-6c67-4c5b-b112-36a304b66dad`." The `iss` row names the same GUID.
|
|
47
|
+
* Compared exactly: Microsoft issues it lowercase, and a token that spells it otherwise is not one of its.
|
|
48
|
+
*/
|
|
49
|
+
export const MICROSOFT_PERSONAL_ACCOUNTS_TENANT_ID = "9188040d-6c67-4c5b-b112-36a304b66dad";
|
|
50
|
+
|
|
51
|
+
/** The part of a link-in-progress this rule reads: the signed-in account's own address. */
|
|
52
|
+
export interface LinkInProgress {
|
|
53
|
+
/** The address on the account the session belongs to, as Better Auth's `/link-social` stored it. */
|
|
54
|
+
readonly email: unknown;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Decide the flag from the decoded ID token and, on a link, the account it is being linked to.
|
|
59
|
+
*
|
|
60
|
+
* Pure, so every hostile shape can be driven without a request. `profile` is the whole decoded ID token —
|
|
61
|
+
* Better Auth hands `mapProfileToUser` the `decodeJwt` result itself (`@better-auth/core`
|
|
62
|
+
* `social-providers/microsoft-entra-id.mjs`), so `xms_edov` and `tid` are in reach as claims, not as
|
|
63
|
+
* fields somebody copied.
|
|
64
|
+
*/
|
|
65
|
+
export function microsoftEmailVerified(
|
|
66
|
+
profile: Readonly<Record<string, unknown>>,
|
|
67
|
+
link: LinkInProgress | null,
|
|
68
|
+
): boolean {
|
|
69
|
+
if (profile.xms_edov === true) return true;
|
|
70
|
+
if (profile.tid === MICROSOFT_PERSONAL_ACCOUNTS_TENANT_ID) return true;
|
|
71
|
+
if (link === null) return false;
|
|
72
|
+
const { email } = profile;
|
|
73
|
+
if (typeof email !== "string" || email.length === 0) return false;
|
|
74
|
+
if (typeof link.email !== "string" || link.email.length === 0) return false;
|
|
75
|
+
return email.toLowerCase() === link.email.toLowerCase();
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* The link this callback completes, or `null` when it is a sign-in.
|
|
80
|
+
*
|
|
81
|
+
* `link` is written by Better Auth's `/link-social` alone: `generateState` spreads the caller's
|
|
82
|
+
* `additionalData` first and assigns `link` last, so a sign-in overwrites any injected one
|
|
83
|
+
* (`./providerSignInGate.ts` records it, and plants against it).
|
|
84
|
+
*
|
|
85
|
+
* **`getOAuthState()` throws where no request state was established**, and here the throw is caught on
|
|
86
|
+
* purpose, unlike the gate's. The gate's safe direction is a loud failure; this one's is *unverified*,
|
|
87
|
+
* and that is exactly what a missing link means.
|
|
88
|
+
*/
|
|
89
|
+
async function linkInProgress(): Promise<LinkInProgress | null> {
|
|
90
|
+
try {
|
|
91
|
+
const state = await getOAuthState();
|
|
92
|
+
const link: unknown = state?.link;
|
|
93
|
+
if (typeof link !== "object" || link === null || !("email" in link)) return null;
|
|
94
|
+
return { email: link.email };
|
|
95
|
+
} catch {
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* The Microsoft block's `mapProfileToUser`: the rule, applied to this callback.
|
|
102
|
+
*
|
|
103
|
+
* **It always states the flag.** Better Auth computes its own default first and spreads this over it, so
|
|
104
|
+
* a mapper that omitted the key on the unverified path would leave that default — read off claims a
|
|
105
|
+
* tenant can influence — standing.
|
|
106
|
+
*/
|
|
107
|
+
export async function microsoftProfileToUser(
|
|
108
|
+
profile: Readonly<Record<string, unknown>>,
|
|
109
|
+
): Promise<{ emailVerified: boolean }> {
|
|
110
|
+
return { emailVerified: microsoftEmailVerified(profile, await linkInProgress()) };
|
|
111
|
+
}
|
|
@@ -65,14 +65,15 @@ import { NEUTRAL_PROVIDER_REFUSAL } from "../http/providerRefusal";
|
|
|
65
65
|
* ## Why a wrapper, and not a `getUserInfo` supplied in the config block
|
|
66
66
|
*
|
|
67
67
|
* `options.getUserInfo` short-circuits each provider's own resolver on its first line
|
|
68
|
-
* (`social-providers/google.mjs:118`, `facebook.mjs:93`, `apple.mjs:62`, `github.mjs:65
|
|
69
|
-
* one means reimplementing the profile fetch it replaced —
|
|
70
|
-
* access-token-owner check. `./githubUserInfo.ts` already records
|
|
71
|
-
* resolver silently dropped `name` and `image`, which had to be
|
|
72
|
-
* dependency's own resolver and reads its result, so nothing is
|
|
68
|
+
* (`social-providers/google.mjs:118`, `facebook.mjs:93`, `apple.mjs:62`, `github.mjs:65`,
|
|
69
|
+
* `microsoft-entra-id.mjs:99`), so supplying one means reimplementing the profile fetch it replaced —
|
|
70
|
+
* Google's id-token decode, Facebook's access-token-owner check. `./githubUserInfo.ts` already records
|
|
71
|
+
* what that costs: replacing GitHub's resolver silently dropped `name` and `image`, which had to be
|
|
72
|
+
* re-derived. Wrapping calls the dependency's own resolver and reads its result, so nothing is
|
|
73
|
+
* reimplemented and nothing reconstructed.
|
|
73
74
|
*
|
|
74
75
|
* **And it is the wrapping that makes the predicate read the right flag.** `mapProfileToUser` is applied
|
|
75
|
-
* *inside* each provider's own `getUserInfo` — every one of the
|
|
76
|
+
* *inside* each provider's own `getUserInfo` — every one of the five spreads `...userMap` over the
|
|
76
77
|
* `emailVerified` it computed — so the value this module reads is by construction the **effective** flag.
|
|
77
78
|
* Facebook is the trap that makes this load-bearing: it sits outside `trustedProviders` like GitHub, but
|
|
78
79
|
* `./auth.ts` asserts its address as verified with a documented reason, and its OAuth response carries no
|
|
@@ -9,6 +9,7 @@ import type {
|
|
|
9
9
|
FacebookOAuthCredentials,
|
|
10
10
|
GithubOAuthCredentials,
|
|
11
11
|
GoogleOAuthCredentials,
|
|
12
|
+
MicrosoftOAuthCredentials,
|
|
12
13
|
} from "./secrets";
|
|
13
14
|
|
|
14
15
|
/**
|
|
@@ -56,7 +57,7 @@ export type ResolvedProvider<Credentials> =
|
|
|
56
57
|
export const PROVIDER_DISABLED: { readonly state: "disabled" } = { state: "disabled" };
|
|
57
58
|
|
|
58
59
|
/** The social providers the kit composes. Ordered as they are declared in config. */
|
|
59
|
-
export const SOCIAL_PROVIDER_IDS = ["google", "apple", "facebook", "github"] as const;
|
|
60
|
+
export const SOCIAL_PROVIDER_IDS = ["google", "apple", "facebook", "github", "microsoft"] as const;
|
|
60
61
|
|
|
61
62
|
/** One of the kit's social providers. */
|
|
62
63
|
export type SocialProviderId = (typeof SOCIAL_PROVIDER_IDS)[number];
|
|
@@ -64,9 +65,9 @@ export type SocialProviderId = (typeof SOCIAL_PROVIDER_IDS)[number];
|
|
|
64
65
|
/**
|
|
65
66
|
* Every provider's state for one instance.
|
|
66
67
|
*
|
|
67
|
-
* A record rather than
|
|
68
|
+
* A record rather than five loose fields, because two things read it — the `socialProviders` block the
|
|
68
69
|
* instance is built from, and the refusal that answers a caller who asked for one that is not there —
|
|
69
|
-
* and they must be reading the same
|
|
70
|
+
* and they must be reading the same five values or they will disagree about what is available.
|
|
70
71
|
*/
|
|
71
72
|
export interface ResolvedProviders {
|
|
72
73
|
/** Google OAuth: disabled, ready with its credential pair, or declared and unreadable. */
|
|
@@ -77,17 +78,20 @@ export interface ResolvedProviders {
|
|
|
77
78
|
facebook: ResolvedProvider<FacebookOAuthCredentials>;
|
|
78
79
|
/** GitHub OAuth: disabled, ready with its credential pair, or declared and unreadable. */
|
|
79
80
|
github: ResolvedProvider<GithubOAuthCredentials>;
|
|
81
|
+
/** Microsoft Entra ID: disabled, ready with its credential set and tenant, or declared and unreadable. */
|
|
82
|
+
microsoft: ResolvedProvider<MicrosoftOAuthCredentials>;
|
|
80
83
|
}
|
|
81
84
|
|
|
82
85
|
/**
|
|
83
86
|
* Every provider disabled — what a composition that enables no social sign-in resolves to, and the
|
|
84
|
-
* base a construction site spreads over rather than spelling
|
|
87
|
+
* base a construction site spreads over rather than spelling five times.
|
|
85
88
|
*/
|
|
86
89
|
export const NO_SOCIAL_PROVIDERS: Readonly<ResolvedProviders> = {
|
|
87
90
|
google: PROVIDER_DISABLED,
|
|
88
91
|
apple: PROVIDER_DISABLED,
|
|
89
92
|
facebook: PROVIDER_DISABLED,
|
|
90
93
|
github: PROVIDER_DISABLED,
|
|
94
|
+
microsoft: PROVIDER_DISABLED,
|
|
91
95
|
};
|
|
92
96
|
|
|
93
97
|
/**
|