@kidecms/core 0.30.1 → 0.31.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/admin/components/PasskeySettings.tsx +121 -0
- package/admin/components/PasskeySignIn.tsx +57 -0
- package/admin/components/SidebarUserMenu.tsx +7 -1
- package/admin/components/TwoFactorSettings.tsx +206 -0
- package/admin/views/EditView.astro +14 -0
- package/core/api.ts +36 -0
- package/core/auth-config.ts +53 -11
- package/core/auth-engine.ts +920 -0
- package/core/auth.ts +46 -152
- package/core/create-admin.ts +9 -5
- package/core/define.ts +75 -35
- package/core/generator.ts +80 -10
- package/core/index.ts +31 -3
- package/core/schema.ts +3 -1
- package/core/seed.ts +12 -2
- package/internals/integration.ts +21 -0
- package/internals/virtual.d.ts +3 -2
- package/middleware/auth.ts +58 -18
- package/package.json +7 -2
- package/routes/admin/account.astro +138 -0
- package/routes/admin/login/verify.astro +90 -0
- package/routes/admin/login.astro +84 -33
- package/routes/api/auth/[...all].ts +153 -0
- package/routes/api/auth/_better-auth.ts +26 -0
- package/routes/api/auth/account.ts +69 -0
- package/routes/api/auth/forgot-password.ts +38 -32
- package/routes/api/auth/invite.ts +66 -98
- package/routes/api/auth/login/verify.ts +50 -0
- package/routes/api/auth/login.ts +68 -118
- package/routes/api/auth/logout.ts +13 -28
- package/routes/api/auth/reset-password.ts +17 -56
- package/routes/api/auth/setup.ts +14 -20
- package/routes/api/auth/sso/[provider]/start.ts +33 -25
|
@@ -0,0 +1,920 @@
|
|
|
1
|
+
import { betterAuth } from "better-auth";
|
|
2
|
+
import type { BetterAuthOptions, BetterAuthPlugin } from "better-auth";
|
|
3
|
+
import { drizzleAdapter } from "better-auth/adapters/drizzle";
|
|
4
|
+
import { APIError } from "better-auth/api";
|
|
5
|
+
import { getSchema as getBetterAuthSchema } from "better-auth/db";
|
|
6
|
+
import { genericOAuth, microsoftEntraId } from "better-auth/plugins/generic-oauth";
|
|
7
|
+
import type { GenericOAuthConfig } from "better-auth/plugins/generic-oauth";
|
|
8
|
+
import { twoFactor } from "better-auth/plugins/two-factor";
|
|
9
|
+
import { passkey } from "@better-auth/passkey";
|
|
10
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
11
|
+
import { and, eq, inArray, isNotNull, sql } from "drizzle-orm";
|
|
12
|
+
import { customType, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
|
|
13
|
+
import { nanoid } from "nanoid";
|
|
14
|
+
|
|
15
|
+
import { hashPassword, verifyPassword, MIN_PASSWORD_LENGTH } from "./auth";
|
|
16
|
+
import { enforcedSsoProviders, mfaRequiredFor, resolveAdminAuth } from "./auth-config";
|
|
17
|
+
import { auditRequestMeta, logAudit } from "./audit";
|
|
18
|
+
import type { AdminAuthSsoProviderConfig, CMSConfig } from "./define";
|
|
19
|
+
import { publicOrigin } from "./http";
|
|
20
|
+
import { getDb, getEmail, readEnv } from "./runtime";
|
|
21
|
+
import { getSchema } from "./schema";
|
|
22
|
+
|
|
23
|
+
export const ADMIN_AUTH_BASE_PATH = "/api/cms/auth";
|
|
24
|
+
export const AUTH_USERS_COLLECTION = "users";
|
|
25
|
+
|
|
26
|
+
// ---------------------------------------------------------------------------
|
|
27
|
+
// Table mapping — shared by the generator (emits the pushed schema) and the
|
|
28
|
+
// runtime (builds the adapter view Better Auth reads and writes through).
|
|
29
|
+
// ---------------------------------------------------------------------------
|
|
30
|
+
|
|
31
|
+
type AuthFieldType = "string" | "number" | "boolean" | "date";
|
|
32
|
+
|
|
33
|
+
export type AuthColumnSpec = {
|
|
34
|
+
/** Better Auth's field name — the key the adapter view uses. */
|
|
35
|
+
field: string;
|
|
36
|
+
/** Key in Kide's generated schema. */
|
|
37
|
+
schemaKey: string;
|
|
38
|
+
column: string;
|
|
39
|
+
type: AuthFieldType;
|
|
40
|
+
required: boolean;
|
|
41
|
+
unique: boolean;
|
|
42
|
+
index: boolean;
|
|
43
|
+
defaultValue?: string | number | boolean;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
export type AuthTableSpec = {
|
|
47
|
+
model: string;
|
|
48
|
+
table: string;
|
|
49
|
+
exportName: string;
|
|
50
|
+
/** The model is stored in the users collection's own table. */
|
|
51
|
+
isUser: boolean;
|
|
52
|
+
columns: AuthColumnSpec[];
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
const KNOWN_TABLES: Record<string, [table: string, exportName: string]> = {
|
|
56
|
+
session: ["cms_auth_sessions", "cmsAuthSessions"],
|
|
57
|
+
account: ["cms_auth_accounts", "cmsAuthAccounts"],
|
|
58
|
+
verification: ["cms_auth_verifications", "cmsAuthVerifications"],
|
|
59
|
+
twoFactor: ["cms_auth_two_factors", "cmsAuthTwoFactors"],
|
|
60
|
+
passkey: ["cms_auth_passkeys", "cmsAuthPasskeys"],
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
// User columns the users collection already owns (Kide naming).
|
|
64
|
+
const USER_OWNED: Record<string, [schemaKey: string, column: string]> = {
|
|
65
|
+
id: ["_id", "_id"],
|
|
66
|
+
name: ["name", "name"],
|
|
67
|
+
email: ["email", "email"],
|
|
68
|
+
createdAt: ["_createdAt", "_created_at"],
|
|
69
|
+
updatedAt: ["_updatedAt", "_updated_at"],
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
const snake = (value: string) => value.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
|
|
73
|
+
const pascal = (value: string) => value.charAt(0).toUpperCase() + value.slice(1);
|
|
74
|
+
|
|
75
|
+
const normalizeType = (type: unknown): AuthFieldType =>
|
|
76
|
+
type === "boolean" || type === "number" || type === "date" ? type : "string";
|
|
77
|
+
|
|
78
|
+
export const authTableSpecs = (options: BetterAuthOptions): AuthTableSpec[] =>
|
|
79
|
+
Object.entries(getBetterAuthSchema(options)).map(([model, definition]) => {
|
|
80
|
+
const isUser = model === "user";
|
|
81
|
+
const [table, exportName] = isUser
|
|
82
|
+
? [`cms_${AUTH_USERS_COLLECTION}`, `cms${pascal(AUTH_USERS_COLLECTION)}`]
|
|
83
|
+
: (KNOWN_TABLES[model] ?? [`cms_auth_${snake(model)}`, `cmsAuth${pascal(model)}`]);
|
|
84
|
+
|
|
85
|
+
const columns: AuthColumnSpec[] = [
|
|
86
|
+
{
|
|
87
|
+
field: "id",
|
|
88
|
+
schemaKey: isUser ? "_id" : "id",
|
|
89
|
+
column: isUser ? "_id" : "id",
|
|
90
|
+
type: "string",
|
|
91
|
+
required: true,
|
|
92
|
+
unique: false,
|
|
93
|
+
index: false,
|
|
94
|
+
},
|
|
95
|
+
];
|
|
96
|
+
for (const [field, attribute] of Object.entries(definition.fields)) {
|
|
97
|
+
const owned = isUser ? USER_OWNED[field] : undefined;
|
|
98
|
+
const defaultValue = ["string", "number", "boolean"].includes(typeof attribute.defaultValue)
|
|
99
|
+
? (attribute.defaultValue as string | number | boolean)
|
|
100
|
+
: undefined;
|
|
101
|
+
columns.push({
|
|
102
|
+
field,
|
|
103
|
+
schemaKey: owned?.[0] ?? (isUser ? `_auth${pascal(field)}` : field),
|
|
104
|
+
column: owned?.[1] ?? (isUser ? `_auth_${snake(field)}` : snake(field)),
|
|
105
|
+
type: normalizeType(attribute.type),
|
|
106
|
+
required: attribute.required === true,
|
|
107
|
+
unique: attribute.unique === true,
|
|
108
|
+
index: attribute.index === true || (!!attribute.references && !isUser),
|
|
109
|
+
defaultValue,
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
return { model, table, exportName, isUser, columns };
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
/** Columns Kide adds to the users table on Better Auth's behalf. */
|
|
116
|
+
export const authUserExtraColumns = (specs: AuthTableSpec[]) =>
|
|
117
|
+
specs.find((spec) => spec.isUser)?.columns.filter((column) => !(column.field in USER_OWNED)) ?? [];
|
|
118
|
+
|
|
119
|
+
/** Drizzle source for a column in Kide's pushed schema (dates stay ISO text, like every Kide timestamp). */
|
|
120
|
+
export const authColumnSource = (column: AuthColumnSpec, options: { userTable?: boolean } = {}) => {
|
|
121
|
+
let source =
|
|
122
|
+
column.type === "boolean"
|
|
123
|
+
? `integer("${column.column}", { mode: "boolean" })`
|
|
124
|
+
: column.type === "number"
|
|
125
|
+
? `integer("${column.column}")`
|
|
126
|
+
: `text("${column.column}")`;
|
|
127
|
+
if (column.field === "id") return `${source}.primaryKey()`;
|
|
128
|
+
// Columns added to an existing users table stay nullable: for a NOT NULL column on a
|
|
129
|
+
// table with rows, drizzle-kit's SQLite push deletes the rows instead of backfilling.
|
|
130
|
+
if (column.required && !options.userTable) source += ".notNull()";
|
|
131
|
+
if (column.unique) source += ".unique()";
|
|
132
|
+
if (column.defaultValue !== undefined) source += `.default(${JSON.stringify(column.defaultValue)})`;
|
|
133
|
+
return source;
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
const isoDate = customType<{ data: Date; driverData: string }>({
|
|
137
|
+
dataType: () => "text",
|
|
138
|
+
toDriver: (value) => (value instanceof Date ? value : new Date(value)).toISOString(),
|
|
139
|
+
fromDriver: (value) => new Date(value),
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
const buildAdapterSchema = (specs: AuthTableSpec[]) =>
|
|
143
|
+
Object.fromEntries(
|
|
144
|
+
specs.map((spec) => {
|
|
145
|
+
const columns = Object.fromEntries(
|
|
146
|
+
spec.columns.map((column) => {
|
|
147
|
+
let builder: any =
|
|
148
|
+
column.type === "boolean"
|
|
149
|
+
? integer(column.column, { mode: "boolean" })
|
|
150
|
+
: column.type === "number"
|
|
151
|
+
? integer(column.column)
|
|
152
|
+
: column.type === "date"
|
|
153
|
+
? isoDate(column.column)
|
|
154
|
+
: text(column.column);
|
|
155
|
+
if (column.field === "id") builder = builder.primaryKey();
|
|
156
|
+
else if (column.required) builder = builder.notNull();
|
|
157
|
+
return [column.field, builder];
|
|
158
|
+
}),
|
|
159
|
+
);
|
|
160
|
+
return [spec.model, sqliteTable(spec.table, columns)];
|
|
161
|
+
}),
|
|
162
|
+
);
|
|
163
|
+
|
|
164
|
+
// ---------------------------------------------------------------------------
|
|
165
|
+
// Options
|
|
166
|
+
// ---------------------------------------------------------------------------
|
|
167
|
+
|
|
168
|
+
const envKey = (providerId: string, suffix: string) =>
|
|
169
|
+
`KIDE_SSO_${providerId.toUpperCase().replace(/-/g, "_")}_${suffix}`;
|
|
170
|
+
|
|
171
|
+
const safeEnv = (key: string) => {
|
|
172
|
+
try {
|
|
173
|
+
return readEnv(key);
|
|
174
|
+
} catch {
|
|
175
|
+
return process.env[key];
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
export const ssoCredentials = (provider: AdminAuthSsoProviderConfig) => ({
|
|
180
|
+
clientId: provider.clientId ?? safeEnv(envKey(provider.id, "CLIENT_ID")),
|
|
181
|
+
clientSecret: provider.clientSecret ?? safeEnv(envKey(provider.id, "CLIENT_SECRET")),
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
const PLACEHOLDER_EMAIL = /@[^@]*\.placeholder\.invalid$/;
|
|
185
|
+
const looksLikeEmail = (value: unknown): value is string =>
|
|
186
|
+
typeof value === "string" && /^[^@\s]+@[^@\s]+$/.test(value);
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Normalizes an identity provider profile into the email Kide links on. Emails at the
|
|
190
|
+
* provider's `allowedDomains` count as verified — the provider is authoritative for them.
|
|
191
|
+
*/
|
|
192
|
+
export const mapSsoProfile = (provider: AdminAuthSsoProviderConfig, profile: Record<string, any>) => {
|
|
193
|
+
let email: string | undefined = looksLikeEmail(profile.email) ? profile.email : undefined;
|
|
194
|
+
if (!email || PLACEHOLDER_EMAIL.test(email)) {
|
|
195
|
+
// Entra puts the sign-in name in preferred_username/upn when the email claim is absent.
|
|
196
|
+
const fallback = [profile.preferred_username, profile.upn].find(looksLikeEmail);
|
|
197
|
+
if (fallback) email = fallback;
|
|
198
|
+
}
|
|
199
|
+
email = email?.toLowerCase();
|
|
200
|
+
const domain = email?.split("@")[1];
|
|
201
|
+
const claimsVerified = profile.email_verified === true || profile.emailVerified === true;
|
|
202
|
+
|
|
203
|
+
let domainTrusted = false;
|
|
204
|
+
if (domain && provider.type !== "google") {
|
|
205
|
+
domainTrusted = (provider.allowedDomains ?? []).some((allowed) => allowed.toLowerCase() === domain);
|
|
206
|
+
} else if (domain && provider.type === "google" && provider.hostedDomain) {
|
|
207
|
+
// Google: only a managed Workspace account (hd claim) is authoritative for its domain.
|
|
208
|
+
domainTrusted = profile.hd === provider.hostedDomain && claimsVerified;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
return { ...(email ? { email } : {}), emailVerified: claimsVerified || domainTrusted };
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
const toGenericOAuth = (provider: AdminAuthSsoProviderConfig): GenericOAuthConfig | null => {
|
|
215
|
+
const { clientId, clientSecret } = ssoCredentials(provider);
|
|
216
|
+
if (!clientId) return null;
|
|
217
|
+
// Refresh tokens are what let Kide re-check a user's standing in the background
|
|
218
|
+
// (offline_access; Google uses access_type=offline instead).
|
|
219
|
+
const defaultScopes =
|
|
220
|
+
provider.type === "google" ? ["openid", "email", "profile"] : ["openid", "email", "profile", "offline_access"];
|
|
221
|
+
const common = {
|
|
222
|
+
clientId,
|
|
223
|
+
clientSecret,
|
|
224
|
+
scopes: provider.scopes ?? defaultScopes,
|
|
225
|
+
pkce: true,
|
|
226
|
+
mapProfileToUser: (profile: Record<string, any>) => mapSsoProfile(provider, profile),
|
|
227
|
+
};
|
|
228
|
+
|
|
229
|
+
if (provider.type === "microsoft") {
|
|
230
|
+
return {
|
|
231
|
+
...microsoftEntraId({ clientId, clientSecret: clientSecret ?? "", tenantId: provider.tenantId }),
|
|
232
|
+
...common,
|
|
233
|
+
providerId: provider.id,
|
|
234
|
+
prompt: "select_account",
|
|
235
|
+
} as GenericOAuthConfig;
|
|
236
|
+
}
|
|
237
|
+
if (provider.type === "google") {
|
|
238
|
+
return {
|
|
239
|
+
...common,
|
|
240
|
+
providerId: provider.id,
|
|
241
|
+
discoveryUrl: "https://accounts.google.com/.well-known/openid-configuration",
|
|
242
|
+
prompt: "select_account",
|
|
243
|
+
accessType: "offline",
|
|
244
|
+
authorizationUrlParams: provider.hostedDomain ? { hd: provider.hostedDomain } : undefined,
|
|
245
|
+
} as GenericOAuthConfig;
|
|
246
|
+
}
|
|
247
|
+
return {
|
|
248
|
+
...common,
|
|
249
|
+
providerId: provider.id,
|
|
250
|
+
discoveryUrl: `${provider.issuer.replace(/\/+$/, "")}/.well-known/openid-configuration`,
|
|
251
|
+
} as GenericOAuthConfig;
|
|
252
|
+
};
|
|
253
|
+
|
|
254
|
+
const DEV_SECRET = "kide-development-secret-do-not-use-in-production";
|
|
255
|
+
let warnedDevSecret = false;
|
|
256
|
+
|
|
257
|
+
export const resolveAuthSecret = () => {
|
|
258
|
+
const secret = safeEnv("KIDE_AUTH_SECRET") ?? safeEnv("BETTER_AUTH_SECRET");
|
|
259
|
+
if (secret) return secret;
|
|
260
|
+
if (process.env.NODE_ENV === "production") {
|
|
261
|
+
throw new Error(
|
|
262
|
+
"[kide] KIDE_AUTH_SECRET is not set. Generate one with `openssl rand -base64 32` and add it to the " +
|
|
263
|
+
"deployment environment — it signs admin session cookies.",
|
|
264
|
+
);
|
|
265
|
+
}
|
|
266
|
+
if (!warnedDevSecret) {
|
|
267
|
+
warnedDevSecret = true;
|
|
268
|
+
console.warn("[kide] KIDE_AUTH_SECRET is not set — using a development secret.");
|
|
269
|
+
}
|
|
270
|
+
return DEV_SECRET;
|
|
271
|
+
};
|
|
272
|
+
|
|
273
|
+
type AuthDeps = {
|
|
274
|
+
baseURL?: string;
|
|
275
|
+
secret?: string;
|
|
276
|
+
};
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* Better Auth options for the admin audience, derived from `admin.auth`. Pure (no DB)
|
|
280
|
+
* so `cms:generate` can read the table layout from the same function the runtime uses.
|
|
281
|
+
*/
|
|
282
|
+
export const buildAdminAuthOptions = (config: CMSConfig, deps: AuthDeps = {}): BetterAuthOptions => {
|
|
283
|
+
const auth = resolveAdminAuth(config);
|
|
284
|
+
const baseURL = deps.baseURL ?? "http://localhost:4321";
|
|
285
|
+
const hostname = new URL(baseURL).hostname;
|
|
286
|
+
const ssoById = new Map(auth.ssoProviders.map((provider) => [provider.id, provider]));
|
|
287
|
+
|
|
288
|
+
const oauthConfigs = auth.ssoProviders.map(toGenericOAuth).filter((entry): entry is GenericOAuthConfig => !!entry);
|
|
289
|
+
|
|
290
|
+
const plugins: BetterAuthPlugin[] = [];
|
|
291
|
+
if (oauthConfigs.length > 0) plugins.push(genericOAuth({ config: oauthConfigs }));
|
|
292
|
+
if (auth.mfa.totp) {
|
|
293
|
+
plugins.push(twoFactor({ issuer: `Kide · ${hostname}`, backupCodeOptions: { amount: 10 } }));
|
|
294
|
+
}
|
|
295
|
+
if (auth.mfa.passkeys) {
|
|
296
|
+
plugins.push(passkey({ rpID: hostname, rpName: "Kide CMS", origin: baseURL }));
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
const options: BetterAuthOptions = {
|
|
300
|
+
appName: "Kide CMS",
|
|
301
|
+
baseURL,
|
|
302
|
+
basePath: ADMIN_AUTH_BASE_PATH,
|
|
303
|
+
secret: deps.secret ?? DEV_SECRET,
|
|
304
|
+
telemetry: { enabled: false },
|
|
305
|
+
// Kide rate-limits its own routes against the shared DB-backed limiter.
|
|
306
|
+
rateLimit: { enabled: false },
|
|
307
|
+
emailAndPassword: {
|
|
308
|
+
enabled: auth.password.enabled,
|
|
309
|
+
disableSignUp: true,
|
|
310
|
+
minPasswordLength: MIN_PASSWORD_LENGTH,
|
|
311
|
+
maxPasswordLength: 4096,
|
|
312
|
+
password: { hash: hashPassword, verify: ({ hash, password }) => verifyPassword(hash, password) },
|
|
313
|
+
resetPasswordTokenExpiresIn: 60 * 60,
|
|
314
|
+
revokeSessionsOnPasswordReset: true,
|
|
315
|
+
onPasswordReset: async ({ user }, request) => {
|
|
316
|
+
const kideUser = await loadAuthUser(user.id);
|
|
317
|
+
logAudit({
|
|
318
|
+
action: "auth.password_reset_completed",
|
|
319
|
+
resourceType: "user",
|
|
320
|
+
resourceCollection: AUTH_USERS_COLLECTION,
|
|
321
|
+
resourceId: user.id,
|
|
322
|
+
actor: auditActor(kideUser),
|
|
323
|
+
...(request ? auditRequestMeta(request) : {}),
|
|
324
|
+
});
|
|
325
|
+
},
|
|
326
|
+
sendResetPassword: async ({ user, token }) => {
|
|
327
|
+
const resetUrl = new URL("/admin/reset-password", baseURL);
|
|
328
|
+
resetUrl.searchParams.set("token", token);
|
|
329
|
+
await getEmail().sendPasswordResetEmail?.(user.email, resetUrl.toString());
|
|
330
|
+
},
|
|
331
|
+
},
|
|
332
|
+
session: {
|
|
333
|
+
expiresIn: auth.sessionDays * 24 * 60 * 60,
|
|
334
|
+
updateAge: 24 * 60 * 60,
|
|
335
|
+
},
|
|
336
|
+
account: {
|
|
337
|
+
accountLinking: { enabled: true, trustedProviders: [], allowDifferentEmails: false },
|
|
338
|
+
// Refresh tokens outlive sessions; keep them unusable to a database reader.
|
|
339
|
+
encryptOAuthTokens: true,
|
|
340
|
+
},
|
|
341
|
+
verification: { storeIdentifier: "hashed" },
|
|
342
|
+
user: {
|
|
343
|
+
changeEmail: { enabled: false },
|
|
344
|
+
deleteUser: { enabled: false },
|
|
345
|
+
},
|
|
346
|
+
advanced: {
|
|
347
|
+
cookiePrefix: "kide",
|
|
348
|
+
database: { generateId: () => nanoid() },
|
|
349
|
+
},
|
|
350
|
+
databaseHooks: {
|
|
351
|
+
user: {
|
|
352
|
+
create: {
|
|
353
|
+
// Kide creates admin users itself (setup, invites, the users collection). The
|
|
354
|
+
// only users Better Auth may create are SSO sign-ins with "jit" provisioning.
|
|
355
|
+
before: async (user, context) => {
|
|
356
|
+
const providerId = (context?.params as { id?: string } | undefined)?.id;
|
|
357
|
+
const provider = providerId ? ssoById.get(providerId) : undefined;
|
|
358
|
+
if (!provider) {
|
|
359
|
+
throw new APIError("FORBIDDEN", { message: "Sign-up is disabled.", code: "SIGNUP_DISABLED" });
|
|
360
|
+
}
|
|
361
|
+
if (provider.provisioning !== "jit") {
|
|
362
|
+
throw new APIError("FORBIDDEN", { message: "No Kide account for this user.", code: "NOT_INVITED" });
|
|
363
|
+
}
|
|
364
|
+
const domain = String(user.email ?? "")
|
|
365
|
+
.split("@")[1]
|
|
366
|
+
?.toLowerCase();
|
|
367
|
+
if (!domain || !(provider.allowedDomains ?? []).some((allowed) => allowed.toLowerCase() === domain)) {
|
|
368
|
+
throw new APIError("FORBIDDEN", { message: "Email domain not allowed.", code: "DOMAIN_NOT_ALLOWED" });
|
|
369
|
+
}
|
|
370
|
+
return { data: user };
|
|
371
|
+
},
|
|
372
|
+
after: async (user, context) => {
|
|
373
|
+
const providerId = (context?.params as { id?: string } | undefined)?.id;
|
|
374
|
+
const provider = providerId ? ssoById.get(providerId) : undefined;
|
|
375
|
+
await setUserRole(user.id, provider?.role ?? "editor");
|
|
376
|
+
},
|
|
377
|
+
},
|
|
378
|
+
},
|
|
379
|
+
},
|
|
380
|
+
plugins,
|
|
381
|
+
};
|
|
382
|
+
|
|
383
|
+
return (config.admin?.auth?.betterAuth?.(options as Record<string, any>) as BetterAuthOptions) ?? options;
|
|
384
|
+
};
|
|
385
|
+
|
|
386
|
+
const KIDE_PLUGIN_IDS = new Set(["generic-oauth", "two-factor", "passkey"]);
|
|
387
|
+
|
|
388
|
+
export type AuthEndpointRule = { methods: string[]; pattern: RegExp };
|
|
389
|
+
|
|
390
|
+
const extensionEndpointCache = new WeakMap<CMSConfig, AuthEndpointRule[]>();
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* HTTP endpoints of plugins a project adds through `admin.auth.betterAuth`. Adding a
|
|
394
|
+
* plugin opts its endpoints in; Better Auth's built-ins stay behind Kide's allowlist.
|
|
395
|
+
*/
|
|
396
|
+
export const extensionAuthEndpoints = (config: CMSConfig): AuthEndpointRule[] => {
|
|
397
|
+
const cached = extensionEndpointCache.get(config);
|
|
398
|
+
if (cached) return cached;
|
|
399
|
+
const rules: AuthEndpointRule[] = [];
|
|
400
|
+
if (config.admin?.auth?.betterAuth) {
|
|
401
|
+
for (const plugin of buildAdminAuthOptions(config).plugins ?? []) {
|
|
402
|
+
if (KIDE_PLUGIN_IDS.has(plugin.id)) continue;
|
|
403
|
+
for (const endpoint of Object.values((plugin.endpoints ?? {}) as Record<string, any>)) {
|
|
404
|
+
if (typeof endpoint?.path !== "string") continue;
|
|
405
|
+
const method = endpoint.options?.method ?? "GET";
|
|
406
|
+
const source = endpoint.path
|
|
407
|
+
.split("/")
|
|
408
|
+
.map((segment: string) =>
|
|
409
|
+
segment.startsWith(":") ? "[^/]+" : segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"),
|
|
410
|
+
)
|
|
411
|
+
.join("/");
|
|
412
|
+
rules.push({
|
|
413
|
+
methods: (Array.isArray(method) ? method : [method]).map((m: string) => m.toUpperCase()),
|
|
414
|
+
pattern: new RegExp(`^${source}$`),
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
extensionEndpointCache.set(config, rules);
|
|
420
|
+
return rules;
|
|
421
|
+
};
|
|
422
|
+
|
|
423
|
+
// ---------------------------------------------------------------------------
|
|
424
|
+
// Runtime instance
|
|
425
|
+
// ---------------------------------------------------------------------------
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* The instance's plugin set depends on config, so Better Auth's inferred `api` type can't
|
|
429
|
+
* follow it; Kide calls the endpoints it enabled by name.
|
|
430
|
+
*/
|
|
431
|
+
export type KideAuth = {
|
|
432
|
+
handler: (request: Request) => Promise<Response>;
|
|
433
|
+
api: Record<string, (input?: any) => Promise<any>>;
|
|
434
|
+
};
|
|
435
|
+
|
|
436
|
+
let registeredConfig: CMSConfig | null = null;
|
|
437
|
+
const instances = new Map<string, Promise<KideAuth>>();
|
|
438
|
+
let legacyMigration: Promise<void> | null = null;
|
|
439
|
+
|
|
440
|
+
/** Called by createCms and the auth middleware so request-time helpers can find the config. */
|
|
441
|
+
export const registerAuthConfig = (config: CMSConfig) => {
|
|
442
|
+
if (registeredConfig !== config) {
|
|
443
|
+
registeredConfig = config;
|
|
444
|
+
instances.clear();
|
|
445
|
+
}
|
|
446
|
+
};
|
|
447
|
+
|
|
448
|
+
export const resetAuthEngine = () => {
|
|
449
|
+
registeredConfig = null;
|
|
450
|
+
instances.clear();
|
|
451
|
+
legacyMigration = null;
|
|
452
|
+
};
|
|
453
|
+
|
|
454
|
+
const requireConfig = () => {
|
|
455
|
+
if (!registeredConfig) throw new Error("[kide] auth config not registered. Call createCms(config) first.");
|
|
456
|
+
return registeredConfig;
|
|
457
|
+
};
|
|
458
|
+
|
|
459
|
+
/** The admin Better Auth instance for a request's public origin (instances are cached per origin). */
|
|
460
|
+
export const getAdminAuth = (originOrRequest: string | Request): Promise<KideAuth> => {
|
|
461
|
+
const config = requireConfig();
|
|
462
|
+
const origin = typeof originOrRequest === "string" ? originOrRequest : publicOrigin(originOrRequest);
|
|
463
|
+
const cached = instances.get(origin);
|
|
464
|
+
if (cached) return cached;
|
|
465
|
+
const instance = (async (): Promise<KideAuth> => {
|
|
466
|
+
const db = await getDb();
|
|
467
|
+
legacyMigration ??= migrateLegacyAuth().catch((error) => {
|
|
468
|
+
legacyMigration = null;
|
|
469
|
+
throw error;
|
|
470
|
+
});
|
|
471
|
+
await legacyMigration;
|
|
472
|
+
const options = buildAdminAuthOptions(config, { baseURL: origin, secret: resolveAuthSecret() });
|
|
473
|
+
const auth = betterAuth({
|
|
474
|
+
...options,
|
|
475
|
+
database: drizzleAdapter(db, { provider: "sqlite", schema: buildAdapterSchema(authTableSpecs(options)) }),
|
|
476
|
+
});
|
|
477
|
+
await captureRefreshErrors(auth);
|
|
478
|
+
return auth as unknown as KideAuth;
|
|
479
|
+
})();
|
|
480
|
+
instance.catch(() => instances.delete(origin));
|
|
481
|
+
instances.set(origin, instance);
|
|
482
|
+
return instance;
|
|
483
|
+
};
|
|
484
|
+
|
|
485
|
+
// Better Auth's /refresh-token reports every failure the same way. Kide needs to tell
|
|
486
|
+
// "the provider refused this user" (end their sessions) from "the provider is unreachable"
|
|
487
|
+
// (try again later), so it records the provider's own error for the duration of a check.
|
|
488
|
+
const refreshErrors = new AsyncLocalStorage<{ error?: unknown }>();
|
|
489
|
+
|
|
490
|
+
const captureRefreshErrors = async (auth: { $context: Promise<unknown> }) => {
|
|
491
|
+
const context = (await auth.$context) as { socialProviders?: Array<Record<string, any>> };
|
|
492
|
+
for (const provider of context.socialProviders ?? []) {
|
|
493
|
+
const refresh = provider.refreshAccessToken;
|
|
494
|
+
if (typeof refresh !== "function") continue;
|
|
495
|
+
provider.refreshAccessToken = async (...args: unknown[]) => {
|
|
496
|
+
try {
|
|
497
|
+
return await refresh.apply(provider, args);
|
|
498
|
+
} catch (error) {
|
|
499
|
+
const store = refreshErrors.getStore();
|
|
500
|
+
if (store) store.error = error;
|
|
501
|
+
throw error;
|
|
502
|
+
}
|
|
503
|
+
};
|
|
504
|
+
}
|
|
505
|
+
};
|
|
506
|
+
|
|
507
|
+
// ---------------------------------------------------------------------------
|
|
508
|
+
// Data helpers (Kide-side writes that bypass Better Auth's HTTP surface)
|
|
509
|
+
// ---------------------------------------------------------------------------
|
|
510
|
+
|
|
511
|
+
const usersTable = () => {
|
|
512
|
+
const tables = getSchema().cmsTables as Record<string, { main: any }>;
|
|
513
|
+
return tables[AUTH_USERS_COLLECTION]?.main ?? null;
|
|
514
|
+
};
|
|
515
|
+
|
|
516
|
+
const authTable = (exportName: string) => (getSchema() as Record<string, any>)[exportName] ?? null;
|
|
517
|
+
|
|
518
|
+
const setUserRole = async (userId: string, role: string) => {
|
|
519
|
+
const users = usersTable();
|
|
520
|
+
if (!users?.role) return;
|
|
521
|
+
const db = await getDb();
|
|
522
|
+
await db.update(users).set({ role }).where(eq(users._id, userId));
|
|
523
|
+
};
|
|
524
|
+
|
|
525
|
+
/** Create or replace a user's password credential. `passwordHash` comes from hashPassword(). */
|
|
526
|
+
export const setCredentialPassword = async (userId: string, passwordHash: string) => {
|
|
527
|
+
const accounts = authTable("cmsAuthAccounts");
|
|
528
|
+
if (!accounts) throw new Error("[kide] cms_auth_accounts is missing — run `pnpm cms:generate && pnpm cms:push`.");
|
|
529
|
+
const db = await getDb();
|
|
530
|
+
const now = new Date().toISOString();
|
|
531
|
+
const updated = await db
|
|
532
|
+
.update(accounts)
|
|
533
|
+
.set({ password: passwordHash, updatedAt: now })
|
|
534
|
+
.where(and(eq(accounts.userId, userId), eq(accounts.providerId, "credential")))
|
|
535
|
+
.returning({ id: accounts.id });
|
|
536
|
+
if (updated.length > 0) return;
|
|
537
|
+
await db.insert(accounts).values({
|
|
538
|
+
id: nanoid(),
|
|
539
|
+
accountId: userId,
|
|
540
|
+
providerId: "credential",
|
|
541
|
+
userId,
|
|
542
|
+
password: passwordHash,
|
|
543
|
+
createdAt: now,
|
|
544
|
+
updatedAt: now,
|
|
545
|
+
});
|
|
546
|
+
};
|
|
547
|
+
|
|
548
|
+
export const hasCredentialPassword = async (userId: string) => {
|
|
549
|
+
const accounts = authTable("cmsAuthAccounts");
|
|
550
|
+
if (!accounts) return false;
|
|
551
|
+
const db = await getDb();
|
|
552
|
+
const rows = await db
|
|
553
|
+
.select({ id: accounts.id })
|
|
554
|
+
.from(accounts)
|
|
555
|
+
.where(and(eq(accounts.userId, userId), eq(accounts.providerId, "credential")))
|
|
556
|
+
.limit(1);
|
|
557
|
+
return rows.length > 0;
|
|
558
|
+
};
|
|
559
|
+
|
|
560
|
+
export const listSignInMethods = async (userId: string): Promise<string[]> => {
|
|
561
|
+
const accounts = authTable("cmsAuthAccounts");
|
|
562
|
+
if (!accounts) return [];
|
|
563
|
+
const db = await getDb();
|
|
564
|
+
const rows = await db.select({ providerId: accounts.providerId }).from(accounts).where(eq(accounts.userId, userId));
|
|
565
|
+
return rows.map((row: { providerId: string }) => row.providerId);
|
|
566
|
+
};
|
|
567
|
+
|
|
568
|
+
export type AccountSecurity = {
|
|
569
|
+
hasPassword: boolean;
|
|
570
|
+
/** SSO provider ids linked to the account. */
|
|
571
|
+
ssoProviders: string[];
|
|
572
|
+
twoFactorEnabled: boolean;
|
|
573
|
+
passkeys: Array<{ id: string; name: string | null; createdAt: string | null }>;
|
|
574
|
+
};
|
|
575
|
+
|
|
576
|
+
export const getAccountSecurity = async (userId: string): Promise<AccountSecurity> => {
|
|
577
|
+
const db = await getDb();
|
|
578
|
+
const methods = await listSignInMethods(userId);
|
|
579
|
+
const users = usersTable();
|
|
580
|
+
let twoFactorEnabled = false;
|
|
581
|
+
if (users?._authTwoFactorEnabled) {
|
|
582
|
+
const rows = await db
|
|
583
|
+
.select({ enabled: users._authTwoFactorEnabled })
|
|
584
|
+
.from(users)
|
|
585
|
+
.where(eq(users._id, userId))
|
|
586
|
+
.limit(1);
|
|
587
|
+
twoFactorEnabled = rows[0]?.enabled === true;
|
|
588
|
+
}
|
|
589
|
+
const passkeyTable = authTable("cmsAuthPasskeys");
|
|
590
|
+
const passkeys = passkeyTable
|
|
591
|
+
? await db
|
|
592
|
+
.select({ id: passkeyTable.id, name: passkeyTable.name, createdAt: passkeyTable.createdAt })
|
|
593
|
+
.from(passkeyTable)
|
|
594
|
+
.where(eq(passkeyTable.userId, userId))
|
|
595
|
+
: [];
|
|
596
|
+
return {
|
|
597
|
+
hasPassword: methods.includes("credential"),
|
|
598
|
+
ssoProviders: methods.filter((method) => method !== "credential"),
|
|
599
|
+
twoFactorEnabled,
|
|
600
|
+
passkeys,
|
|
601
|
+
};
|
|
602
|
+
};
|
|
603
|
+
|
|
604
|
+
/** Sign a user out everywhere. */
|
|
605
|
+
export const revokeUserSessions = async (userId: string) => {
|
|
606
|
+
const sessions = authTable("cmsAuthSessions");
|
|
607
|
+
if (!sessions) return;
|
|
608
|
+
const db = await getDb();
|
|
609
|
+
await db.delete(sessions).where(eq(sessions.userId, userId));
|
|
610
|
+
};
|
|
611
|
+
|
|
612
|
+
/** Remove everything auth-related for a deleted user. */
|
|
613
|
+
export const deleteUserAuthData = async (userId: string) => {
|
|
614
|
+
const db = await getDb();
|
|
615
|
+
for (const exportName of ["cmsAuthSessions", "cmsAuthAccounts", "cmsAuthTwoFactors", "cmsAuthPasskeys"]) {
|
|
616
|
+
const table = authTable(exportName);
|
|
617
|
+
if (table?.userId) await db.delete(table).where(eq(table.userId, userId));
|
|
618
|
+
}
|
|
619
|
+
};
|
|
620
|
+
|
|
621
|
+
/**
|
|
622
|
+
* One-time move of pre-Better-Auth data: `users.password` hashes become credential
|
|
623
|
+
* accounts, and admin-created users are marked email-verified (an admin vouched for
|
|
624
|
+
* the address), so SSO sign-ins can link to them. Idempotent and cheap once done.
|
|
625
|
+
*/
|
|
626
|
+
export const migrateLegacyAuth = async () => {
|
|
627
|
+
const users = usersTable();
|
|
628
|
+
const accounts = authTable("cmsAuthAccounts");
|
|
629
|
+
if (!users || !accounts || !users._authEmailVerified) return;
|
|
630
|
+
const db = await getDb();
|
|
631
|
+
|
|
632
|
+
// Better Auth looks users up by lowercased email; earlier versions stored it as typed.
|
|
633
|
+
// A case-only duplicate keeps its spelling rather than colliding on the unique index.
|
|
634
|
+
try {
|
|
635
|
+
await db.run(sql`
|
|
636
|
+
UPDATE ${users} SET email = lower(email)
|
|
637
|
+
WHERE email != lower(email)
|
|
638
|
+
AND NOT EXISTS (SELECT 1 FROM ${users} other WHERE other.email = lower(${users}.email))
|
|
639
|
+
`);
|
|
640
|
+
} catch (error) {
|
|
641
|
+
// Two case-variants of one address, neither lowercase: leave both for an admin to resolve.
|
|
642
|
+
console.warn("[kide] Could not lowercase all user emails:", error instanceof Error ? error.message : error);
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
if (!users.password) return;
|
|
646
|
+
const pending = await db.select({ id: users._id }).from(users).where(isNotNull(users.password)).limit(1);
|
|
647
|
+
if (pending.length === 0) return;
|
|
648
|
+
|
|
649
|
+
const now = new Date().toISOString();
|
|
650
|
+
await db.update(users).set({ _authEmailVerified: true }).where(isNotNull(users.password));
|
|
651
|
+
try {
|
|
652
|
+
await db.run(sql`
|
|
653
|
+
INSERT INTO cms_auth_accounts (id, account_id, provider_id, user_id, password, created_at, updated_at)
|
|
654
|
+
SELECT 'legacy-' || u._id, u._id, 'credential', u._id, u.password, ${now}, ${now}
|
|
655
|
+
FROM ${users} u
|
|
656
|
+
WHERE u.password IS NOT NULL AND u.password != ''
|
|
657
|
+
AND NOT EXISTS (
|
|
658
|
+
SELECT 1 FROM cms_auth_accounts a WHERE a.user_id = u._id AND a.provider_id = 'credential'
|
|
659
|
+
)
|
|
660
|
+
`);
|
|
661
|
+
} catch (error) {
|
|
662
|
+
// A concurrent cold start already inserted the same rows (deterministic ids).
|
|
663
|
+
if (!/UNIQUE|PRIMARY KEY/i.test(error instanceof Error ? error.message : String(error))) throw error;
|
|
664
|
+
}
|
|
665
|
+
await db.update(users).set({ password: null }).where(isNotNull(users.password));
|
|
666
|
+
};
|
|
667
|
+
|
|
668
|
+
// ---------------------------------------------------------------------------
|
|
669
|
+
// Sessions
|
|
670
|
+
// ---------------------------------------------------------------------------
|
|
671
|
+
|
|
672
|
+
export type SessionUser = {
|
|
673
|
+
id: string;
|
|
674
|
+
email: string;
|
|
675
|
+
name: string;
|
|
676
|
+
role: string;
|
|
677
|
+
[key: string]: unknown;
|
|
678
|
+
};
|
|
679
|
+
|
|
680
|
+
const parseSessionValue = (value: unknown) => {
|
|
681
|
+
if (typeof value !== "string") return value;
|
|
682
|
+
const trimmed = value.trim();
|
|
683
|
+
if (!trimmed.startsWith("[") && !trimmed.startsWith("{")) return value;
|
|
684
|
+
try {
|
|
685
|
+
return JSON.parse(trimmed);
|
|
686
|
+
} catch {
|
|
687
|
+
return value;
|
|
688
|
+
}
|
|
689
|
+
};
|
|
690
|
+
|
|
691
|
+
const loadSessionUser = async (userId: string): Promise<{ user: SessionUser; twoFactorEnabled: boolean } | null> => {
|
|
692
|
+
const users = usersTable();
|
|
693
|
+
if (!users) return null;
|
|
694
|
+
const db = await getDb();
|
|
695
|
+
const rows = await db.select().from(users).where(eq(users._id, userId)).limit(1);
|
|
696
|
+
if (rows.length === 0) return null;
|
|
697
|
+
const row = rows[0] as Record<string, unknown>;
|
|
698
|
+
const publicFields = Object.fromEntries(
|
|
699
|
+
Object.entries(row)
|
|
700
|
+
.filter(([key]) => key !== "_id" && key !== "password" && !key.startsWith("_auth"))
|
|
701
|
+
.map(([key, value]) => [key, parseSessionValue(value)]),
|
|
702
|
+
);
|
|
703
|
+
return {
|
|
704
|
+
user: {
|
|
705
|
+
...publicFields,
|
|
706
|
+
id: String(row._id),
|
|
707
|
+
email: String(row.email),
|
|
708
|
+
name: String(row.name),
|
|
709
|
+
role: String(row.role ?? "editor"),
|
|
710
|
+
},
|
|
711
|
+
twoFactorEnabled: row._authTwoFactorEnabled === true || row._authTwoFactorEnabled === 1,
|
|
712
|
+
};
|
|
713
|
+
};
|
|
714
|
+
|
|
715
|
+
/** A Kide user as the admin sees it (no password, no Better Auth internals). */
|
|
716
|
+
export const loadAuthUser = async (userId: string): Promise<SessionUser | null> =>
|
|
717
|
+
(await loadSessionUser(userId))?.user ?? null;
|
|
718
|
+
|
|
719
|
+
export const auditActor = (user: SessionUser | null) =>
|
|
720
|
+
user ? { id: user.id, email: user.email, role: user.role } : null;
|
|
721
|
+
|
|
722
|
+
// ---------------------------------------------------------------------------
|
|
723
|
+
// SSO standing — offboarding
|
|
724
|
+
// ---------------------------------------------------------------------------
|
|
725
|
+
|
|
726
|
+
export type SsoDenial =
|
|
727
|
+
/** The provider refused the user (disabled, deleted, access revoked): sessions ended. */
|
|
728
|
+
| { kind: "revoked" }
|
|
729
|
+
/** The user must go back through the provider (enforced domain, or nothing to re-check with). */
|
|
730
|
+
| { kind: "reauth"; providerId: string };
|
|
731
|
+
|
|
732
|
+
const ssoDenials = new WeakMap<Request, SsoDenial>();
|
|
733
|
+
|
|
734
|
+
/** Why `resolveAdminSession` refused this request's session, when SSO was the reason. */
|
|
735
|
+
export const getSsoDenial = (request: Request) => ssoDenials.get(request) ?? null;
|
|
736
|
+
|
|
737
|
+
const RETRY_AFTER_TRANSIENT_MS = 5 * 60 * 1000;
|
|
738
|
+
|
|
739
|
+
const isRevocation = (error: unknown) => {
|
|
740
|
+
const body = (error ?? {}) as { status?: number; error?: unknown };
|
|
741
|
+
return (body.status === 400 || body.status === 401) && body.error === "invalid_grant";
|
|
742
|
+
};
|
|
743
|
+
|
|
744
|
+
/** Record that the provider vouched for the user just now (sign-in or a successful re-check). */
|
|
745
|
+
export const markSsoVerified = async (userId: string, providerId: string) => {
|
|
746
|
+
const accounts = authTable("cmsAuthAccounts");
|
|
747
|
+
if (!accounts) return;
|
|
748
|
+
const db = await getDb();
|
|
749
|
+
await db
|
|
750
|
+
.update(accounts)
|
|
751
|
+
.set({ updatedAt: new Date().toISOString() })
|
|
752
|
+
.where(and(eq(accounts.userId, userId), eq(accounts.providerId, providerId)));
|
|
753
|
+
};
|
|
754
|
+
|
|
755
|
+
/**
|
|
756
|
+
* Is this SSO user still in good standing with their identity provider? Checked at most
|
|
757
|
+
* every `sso.verifyEveryMinutes` per user, by refreshing the provider's token; one request
|
|
758
|
+
* claims the check so parallel requests don't race the provider's refresh-token rotation.
|
|
759
|
+
*/
|
|
760
|
+
const checkSsoStanding = async (config: CMSConfig, user: SessionUser, origin: string): Promise<SsoDenial | null> => {
|
|
761
|
+
const resolved = resolveAdminAuth(config);
|
|
762
|
+
if (resolved.ssoProviders.length === 0) return null;
|
|
763
|
+
const accounts = authTable("cmsAuthAccounts");
|
|
764
|
+
if (!accounts) return null;
|
|
765
|
+
|
|
766
|
+
const enforcing = enforcedSsoProviders(resolved, user.email).map((provider) => provider.id);
|
|
767
|
+
const db = await getDb();
|
|
768
|
+
const linked: Array<{ id: string; providerId: string; refreshToken: string | null; updatedAt: string }> = await db
|
|
769
|
+
.select({
|
|
770
|
+
id: accounts.id,
|
|
771
|
+
providerId: accounts.providerId,
|
|
772
|
+
refreshToken: accounts.refreshToken,
|
|
773
|
+
updatedAt: accounts.updatedAt,
|
|
774
|
+
})
|
|
775
|
+
.from(accounts)
|
|
776
|
+
.where(
|
|
777
|
+
and(
|
|
778
|
+
eq(accounts.userId, user.id),
|
|
779
|
+
inArray(
|
|
780
|
+
accounts.providerId,
|
|
781
|
+
resolved.ssoProviders.map((provider) => provider.id),
|
|
782
|
+
),
|
|
783
|
+
),
|
|
784
|
+
);
|
|
785
|
+
|
|
786
|
+
// A domain-bound user must hold a link to one of the providers authoritative for the domain.
|
|
787
|
+
const candidates = enforcing.length ? linked.filter((entry) => enforcing.includes(entry.providerId)) : linked;
|
|
788
|
+
const account = candidates.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))[0];
|
|
789
|
+
if (!account) return enforcing.length ? { kind: "reauth", providerId: enforcing[0] } : null;
|
|
790
|
+
|
|
791
|
+
const intervalMs = resolved.ssoVerifyEveryMinutes * 60 * 1000;
|
|
792
|
+
const lastVerified = Date.parse(account.updatedAt);
|
|
793
|
+
if (Number.isFinite(lastVerified) && Date.now() - lastVerified < intervalMs) return null;
|
|
794
|
+
|
|
795
|
+
// Claim the check: push the timestamp forward so concurrent requests skip it. A failed
|
|
796
|
+
// transient check then retries after RETRY_AFTER_TRANSIENT_MS rather than every request.
|
|
797
|
+
const claimed = await db
|
|
798
|
+
.update(accounts)
|
|
799
|
+
.set({ updatedAt: new Date(Date.now() - intervalMs + RETRY_AFTER_TRANSIENT_MS).toISOString() })
|
|
800
|
+
.where(and(eq(accounts.id, account.id), eq(accounts.updatedAt, account.updatedAt)))
|
|
801
|
+
.returning({ id: accounts.id });
|
|
802
|
+
if (claimed.length === 0) return null;
|
|
803
|
+
|
|
804
|
+
const provider = resolved.ssoProviders.find((entry) => entry.id === account.providerId)!;
|
|
805
|
+
if (!account.refreshToken) {
|
|
806
|
+
// Nothing to re-check with: the user goes back through the provider.
|
|
807
|
+
await revokeUserSessions(user.id);
|
|
808
|
+
return { kind: "reauth", providerId: provider.id };
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
const auth = await getAdminAuth(origin);
|
|
812
|
+
const capture: { error?: unknown } = {};
|
|
813
|
+
try {
|
|
814
|
+
await refreshErrors.run(capture, () => auth.api.refreshToken({ body: { accountId: account.id, userId: user.id } }));
|
|
815
|
+
} catch {
|
|
816
|
+
if (isRevocation(capture.error)) {
|
|
817
|
+
await revokeUserSessions(user.id);
|
|
818
|
+
logAudit({
|
|
819
|
+
action: "auth.sso_access_revoked",
|
|
820
|
+
resourceType: "session",
|
|
821
|
+
resourceCollection: AUTH_USERS_COLLECTION,
|
|
822
|
+
resourceId: user.id,
|
|
823
|
+
actor: auditActor(user),
|
|
824
|
+
});
|
|
825
|
+
return { kind: "revoked" };
|
|
826
|
+
}
|
|
827
|
+
console.warn(
|
|
828
|
+
`[kide] Couldn't re-check ${user.email} with SSO provider "${provider.id}"; retrying in a few minutes.`,
|
|
829
|
+
capture.error ?? "",
|
|
830
|
+
);
|
|
831
|
+
return null;
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
await markSsoVerified(user.id, provider.id);
|
|
835
|
+
await applySsoRoleMapping(provider, user.id);
|
|
836
|
+
return null;
|
|
837
|
+
};
|
|
838
|
+
|
|
839
|
+
export type AdminSession = {
|
|
840
|
+
user: SessionUser;
|
|
841
|
+
/** The user must enroll TOTP before using the admin (`mfa.require`). */
|
|
842
|
+
mfaEnrollmentRequired: boolean;
|
|
843
|
+
/** Set-Cookie headers from a session refresh — forward them on the response. */
|
|
844
|
+
setCookies: string[];
|
|
845
|
+
};
|
|
846
|
+
|
|
847
|
+
const hasSessionCookie = (request: Request) =>
|
|
848
|
+
/(?:^|;\s*)(?:__Secure-)?kide\.session_token=/.test(request.headers.get("cookie") ?? "");
|
|
849
|
+
|
|
850
|
+
export const resolveAdminSession = async (request: Request): Promise<AdminSession | null> => {
|
|
851
|
+
if (!hasSessionCookie(request)) return null;
|
|
852
|
+
const config = requireConfig();
|
|
853
|
+
const auth = await getAdminAuth(request);
|
|
854
|
+
const { headers, response } = await auth.api.getSession({ headers: request.headers, returnHeaders: true });
|
|
855
|
+
if (!response) return null;
|
|
856
|
+
|
|
857
|
+
const loaded = await loadSessionUser(response.user.id);
|
|
858
|
+
if (!loaded) return null;
|
|
859
|
+
|
|
860
|
+
const denial = await checkSsoStanding(config, loaded.user, publicOrigin(request));
|
|
861
|
+
if (denial) {
|
|
862
|
+
ssoDenials.set(request, denial);
|
|
863
|
+
return null;
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
const resolved = resolveAdminAuth(config);
|
|
867
|
+
const mfaEnrollmentRequired =
|
|
868
|
+
mfaRequiredFor(resolved, loaded.user.role) &&
|
|
869
|
+
!loaded.twoFactorEnabled &&
|
|
870
|
+
(await hasCredentialPassword(loaded.user.id));
|
|
871
|
+
|
|
872
|
+
return { user: loaded.user, mfaEnrollmentRequired, setCookies: headers?.getSetCookie?.() ?? [] };
|
|
873
|
+
};
|
|
874
|
+
|
|
875
|
+
export const getSessionUser = async (request: Request): Promise<SessionUser | null> =>
|
|
876
|
+
(await resolveAdminSession(request))?.user ?? null;
|
|
877
|
+
|
|
878
|
+
// ---------------------------------------------------------------------------
|
|
879
|
+
// SSO post-processing
|
|
880
|
+
// ---------------------------------------------------------------------------
|
|
881
|
+
|
|
882
|
+
const decodeJwtPayload = (token: string): Record<string, unknown> | null => {
|
|
883
|
+
const payload = token.split(".")[1];
|
|
884
|
+
if (!payload) return null;
|
|
885
|
+
try {
|
|
886
|
+
const base64 = payload
|
|
887
|
+
.replace(/-/g, "+")
|
|
888
|
+
.replace(/_/g, "/")
|
|
889
|
+
.padEnd(Math.ceil(payload.length / 4) * 4, "=");
|
|
890
|
+
return JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(base64), (char) => char.charCodeAt(0))));
|
|
891
|
+
} catch {
|
|
892
|
+
return null;
|
|
893
|
+
}
|
|
894
|
+
};
|
|
895
|
+
|
|
896
|
+
/**
|
|
897
|
+
* After a successful SSO callback: apply the provider's `mapRole` to the ID token the
|
|
898
|
+
* callback just stored (Better Auth already verified it).
|
|
899
|
+
*/
|
|
900
|
+
export const applySsoRoleMapping = async (provider: AdminAuthSsoProviderConfig, userId: string) => {
|
|
901
|
+
if (!provider.mapRole) return;
|
|
902
|
+
const accounts = authTable("cmsAuthAccounts");
|
|
903
|
+
if (!accounts) return;
|
|
904
|
+
const db = await getDb();
|
|
905
|
+
const rows = await db
|
|
906
|
+
.select({ idToken: accounts.idToken })
|
|
907
|
+
.from(accounts)
|
|
908
|
+
.where(and(eq(accounts.userId, userId), eq(accounts.providerId, provider.id)))
|
|
909
|
+
.limit(1);
|
|
910
|
+
const claims = rows[0]?.idToken ? decodeJwtPayload(rows[0].idToken) : null;
|
|
911
|
+
if (!claims) return;
|
|
912
|
+
const role = provider.mapRole(claims);
|
|
913
|
+
if (typeof role !== "string" || !role) return;
|
|
914
|
+
const roleField = requireConfig().collections.find((c) => c.slug === AUTH_USERS_COLLECTION)?.fields.role;
|
|
915
|
+
if (roleField?.type === "select" && !roleField.options.includes(role)) {
|
|
916
|
+
console.warn(`[kide] SSO provider "${provider.id}" mapped a role ("${role}") the users collection doesn't define.`);
|
|
917
|
+
return;
|
|
918
|
+
}
|
|
919
|
+
await setUserRole(userId, role);
|
|
920
|
+
};
|