@softure-ai/auth 0.2.4 → 0.2.6
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/CHANGELOG.md +46 -0
- package/README.md +98 -10
- package/dist/contract.d.ts +5 -1
- package/dist/contract.d.ts.map +1 -1
- package/dist/contract.js.map +1 -1
- package/dist/index.d.ts +72 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9 -4
- package/dist/index.js.map +1 -1
- package/dist/messages/en.d.ts +10 -0
- package/dist/messages/en.d.ts.map +1 -1
- package/dist/messages/en.js +10 -0
- package/dist/messages/en.js.map +1 -1
- package/dist/messages/index.d.ts +8 -0
- package/dist/messages/index.d.ts.map +1 -1
- package/dist/next/actions.d.ts +5 -0
- package/dist/next/actions.d.ts.map +1 -1
- package/dist/next/actions.js +26 -15
- package/dist/next/actions.js.map +1 -1
- package/dist/next/index.d.ts +2 -1
- package/dist/next/index.d.ts.map +1 -1
- package/dist/next/index.js +2 -1
- package/dist/next/index.js.map +1 -1
- package/dist/next/oidc-cookie.d.ts +7 -0
- package/dist/next/oidc-cookie.d.ts.map +1 -0
- package/dist/next/oidc-cookie.js +25 -0
- package/dist/next/oidc-cookie.js.map +1 -0
- package/dist/next/oidc-login-url.d.ts +4 -0
- package/dist/next/oidc-login-url.d.ts.map +1 -0
- package/dist/next/oidc-login-url.js +13 -0
- package/dist/next/oidc-login-url.js.map +1 -0
- package/dist/next/oidc-route.d.ts +7 -0
- package/dist/next/oidc-route.d.ts.map +1 -0
- package/dist/next/oidc-route.js +48 -0
- package/dist/next/oidc-route.js.map +1 -0
- package/dist/next/pages.d.ts +5 -0
- package/dist/next/pages.d.ts.map +1 -1
- package/dist/next/pages.js +19 -4
- package/dist/next/pages.js.map +1 -1
- package/dist/next/params.d.ts +2 -0
- package/dist/next/params.d.ts.map +1 -1
- package/dist/next/params.js +2 -0
- package/dist/next/params.js.map +1 -1
- package/dist/next/previous-session.d.ts +6 -0
- package/dist/next/previous-session.d.ts.map +1 -0
- package/dist/next/previous-session.js +23 -0
- package/dist/next/previous-session.js.map +1 -0
- package/dist/options.d.ts +99 -1
- package/dist/options.d.ts.map +1 -1
- package/dist/options.js +80 -0
- package/dist/options.js.map +1 -1
- package/dist/proxy/index.d.ts.map +1 -1
- package/dist/proxy/index.js +3 -1
- package/dist/proxy/index.js.map +1 -1
- package/dist/schema.d.ts +235 -0
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +22 -3
- package/dist/schema.js.map +1 -1
- package/dist/server/change-password.d.ts +1 -1
- package/dist/server/change-password.d.ts.map +1 -1
- package/dist/server/change-password.js +3 -0
- package/dist/server/change-password.js.map +1 -1
- package/dist/server/health.d.ts.map +1 -1
- package/dist/server/health.js +2 -0
- package/dist/server/health.js.map +1 -1
- package/dist/server/index.d.ts +1 -0
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +1 -0
- package/dist/server/index.js.map +1 -1
- package/dist/server/login.d.ts +1 -1
- package/dist/server/login.d.ts.map +1 -1
- package/dist/server/login.js +3 -1
- package/dist/server/login.js.map +1 -1
- package/dist/server/oidc/accounts.d.ts +12 -0
- package/dist/server/oidc/accounts.d.ts.map +1 -0
- package/dist/server/oidc/accounts.js +71 -0
- package/dist/server/oidc/accounts.js.map +1 -0
- package/dist/server/oidc/context.d.ts +37 -0
- package/dist/server/oidc/context.d.ts.map +1 -0
- package/dist/server/oidc/context.js +34 -0
- package/dist/server/oidc/context.js.map +1 -0
- package/dist/server/oidc/discovery.d.ts +24 -0
- package/dist/server/oidc/discovery.d.ts.map +1 -0
- package/dist/server/oidc/discovery.js +109 -0
- package/dist/server/oidc/discovery.js.map +1 -0
- package/dist/server/oidc/flow.d.ts +49 -0
- package/dist/server/oidc/flow.d.ts.map +1 -0
- package/dist/server/oidc/flow.js +168 -0
- package/dist/server/oidc/flow.js.map +1 -0
- package/dist/server/oidc/id-token.d.ts +36 -0
- package/dist/server/oidc/id-token.d.ts.map +1 -0
- package/dist/server/oidc/id-token.js +105 -0
- package/dist/server/oidc/id-token.js.map +1 -0
- package/dist/server/oidc/index.d.ts +4 -0
- package/dist/server/oidc/index.d.ts.map +1 -0
- package/dist/server/oidc/index.js +4 -0
- package/dist/server/oidc/index.js.map +1 -0
- package/dist/server/oidc/token-request.d.ts +13 -0
- package/dist/server/oidc/token-request.d.ts.map +1 -0
- package/dist/server/oidc/token-request.js +49 -0
- package/dist/server/oidc/token-request.js.map +1 -0
- package/dist/server/password-reset.d.ts +1 -1
- package/dist/server/password-reset.d.ts.map +1 -1
- package/dist/server/password-reset.js +3 -2
- package/dist/server/password-reset.js.map +1 -1
- package/dist/server/privacy.d.ts +8 -0
- package/dist/server/privacy.d.ts.map +1 -1
- package/dist/server/privacy.js +16 -4
- package/dist/server/privacy.js.map +1 -1
- package/dist/server/rate-limits.d.ts +4 -1
- package/dist/server/rate-limits.d.ts.map +1 -1
- package/dist/server/rate-limits.js +10 -3
- package/dist/server/rate-limits.js.map +1 -1
- package/dist/server/register.js +1 -1
- package/dist/server/register.js.map +1 -1
- package/dist/server/switches.d.ts +1 -1
- package/dist/server/switches.d.ts.map +1 -1
- package/dist/server/switches.js +3 -1
- package/dist/server/switches.js.map +1 -1
- package/dist/testing/account.js +1 -1
- package/dist/testing/account.js.map +1 -1
- package/dist/testing/index.d.ts +1 -0
- package/dist/testing/index.d.ts.map +1 -1
- package/dist/testing/index.js +3 -1
- package/dist/testing/index.js.map +1 -1
- package/dist/testing/oidc-provider.d.ts +64 -0
- package/dist/testing/oidc-provider.d.ts.map +1 -0
- package/dist/testing/oidc-provider.js +181 -0
- package/dist/testing/oidc-provider.js.map +1 -0
- package/dist/ui/auth-forms.d.ts.map +1 -1
- package/dist/ui/auth-forms.js +1 -1
- package/dist/ui/auth-forms.js.map +1 -1
- package/dist/ui/index.d.ts +1 -0
- package/dist/ui/index.d.ts.map +1 -1
- package/dist/ui/index.js +1 -0
- package/dist/ui/index.js.map +1 -1
- package/dist/ui/oidc-sign-in.d.ts +25 -0
- package/dist/ui/oidc-sign-in.d.ts.map +1 -0
- package/dist/ui/oidc-sign-in.js +17 -0
- package/dist/ui/oidc-sign-in.js.map +1 -0
- package/migrations/0005_create_identities_and_oidc_states.sql +34 -0
- package/module.json +3 -2
- package/package.json +2 -2
- package/src/contract.ts +10 -1
- package/src/index.ts +20 -5
- package/src/messages/en.ts +10 -0
- package/src/next/actions.ts +23 -14
- package/src/next/index.ts +2 -0
- package/src/next/oidc-cookie.ts +31 -0
- package/src/next/oidc-login-url.ts +14 -0
- package/src/next/oidc-route.ts +48 -0
- package/src/next/pages.tsx +38 -11
- package/src/next/params.ts +3 -0
- package/src/next/previous-session.ts +23 -0
- package/src/options.ts +86 -1
- package/src/proxy/index.ts +3 -1
- package/src/schema.ts +28 -3
- package/src/server/change-password.ts +3 -0
- package/src/server/health.ts +2 -0
- package/src/server/index.ts +17 -0
- package/src/server/login.ts +2 -1
- package/src/server/oidc/accounts.ts +82 -0
- package/src/server/oidc/context.ts +56 -0
- package/src/server/oidc/discovery.ts +133 -0
- package/src/server/oidc/flow.ts +196 -0
- package/src/server/oidc/id-token.ts +124 -0
- package/src/server/oidc/index.ts +14 -0
- package/src/server/oidc/token-request.ts +59 -0
- package/src/server/password-reset.ts +3 -2
- package/src/server/privacy.ts +24 -4
- package/src/server/rate-limits.ts +11 -3
- package/src/server/register.ts +1 -1
- package/src/server/switches.ts +2 -1
- package/src/testing/account.ts +1 -1
- package/src/testing/index.ts +10 -1
- package/src/testing/oidc-provider.ts +248 -0
- package/src/ui/auth-forms.tsx +10 -2
- package/src/ui/index.ts +1 -0
- package/src/ui/oidc-sign-in.tsx +60 -0
package/src/schema.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// Drizzle view of the module's tables (migrations/0001_create_users_and_sessions.sql,
|
|
2
|
-
// 0002_create_user_roles.sql, 0003_create_password_resets.sql
|
|
3
|
-
// 0004_index_users_created_at.sql). The migrations are the source of truth; this file only types
|
|
2
|
+
// 0002_create_user_roles.sql, 0003_create_password_resets.sql, the users.created_at index of
|
|
3
|
+
// 0004_index_users_created_at.sql and 0005_create_identities_and_oidc_states.sql). The migrations are the source of truth; this file only types
|
|
4
4
|
// the queries. App tables may reference `users.id`.
|
|
5
|
-
import { pgSchema, primaryKey, text, timestamp, uuid } from "drizzle-orm/pg-core";
|
|
5
|
+
import { pgSchema, primaryKey, text, timestamp, unique, uuid } from "drizzle-orm/pg-core";
|
|
6
6
|
|
|
7
7
|
export const authSchema = pgSchema("auth");
|
|
8
8
|
|
|
@@ -43,3 +43,28 @@ export const passwordResets = authSchema.table("password_resets", {
|
|
|
43
43
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
|
|
44
44
|
expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
|
|
45
45
|
});
|
|
46
|
+
|
|
47
|
+
export const identities = authSchema.table(
|
|
48
|
+
"identities",
|
|
49
|
+
{
|
|
50
|
+
provider: text("provider").notNull(),
|
|
51
|
+
subject: text("subject").notNull(),
|
|
52
|
+
userId: uuid("user_id")
|
|
53
|
+
.notNull()
|
|
54
|
+
.references(() => users.id, { onDelete: "cascade" }),
|
|
55
|
+
email: text("email").notNull(),
|
|
56
|
+
createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
|
|
57
|
+
lastLoginAt: timestamp("last_login_at", { withTimezone: true }).notNull(),
|
|
58
|
+
},
|
|
59
|
+
(table) => [primaryKey({ columns: [table.provider, table.subject] }), unique("identities_user_provider_key").on(table.userId, table.provider)],
|
|
60
|
+
);
|
|
61
|
+
|
|
62
|
+
export const oidcStates = authSchema.table("oidc_states", {
|
|
63
|
+
stateHash: text("state_hash").primaryKey(),
|
|
64
|
+
provider: text("provider").notNull(),
|
|
65
|
+
nonce: text("nonce").notNull(),
|
|
66
|
+
codeVerifier: text("code_verifier").notNull(),
|
|
67
|
+
nextPath: text("next_path").notNull(),
|
|
68
|
+
createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
|
|
69
|
+
expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
|
|
70
|
+
});
|
|
@@ -21,6 +21,7 @@ export interface ChangePasswordInput {
|
|
|
21
21
|
|
|
22
22
|
export type ChangePasswordErrorCode =
|
|
23
23
|
| "auth.unauthenticated"
|
|
24
|
+
| "auth.forbidden"
|
|
24
25
|
| "auth.current_password_invalid"
|
|
25
26
|
| "auth.password_unchanged"
|
|
26
27
|
| "auth.password_too_short"
|
|
@@ -32,6 +33,8 @@ export type ChangePasswordResult = Ok<undefined> | Err<ChangePasswordErrorCode>
|
|
|
32
33
|
export async function changePassword(ctx: AuthContext, input: ChangePasswordInput): Promise<ChangePasswordResult> {
|
|
33
34
|
const options = getAuthOptions(ctx.config);
|
|
34
35
|
assertAuthBuckets(ctx.config);
|
|
36
|
+
// Passwords are off: there is none to change.
|
|
37
|
+
if (!options.password.enabled) return err("auth.forbidden");
|
|
35
38
|
const user = await findSessionUser(ctx, input.sessionToken);
|
|
36
39
|
if (user === null) return err("auth.unauthenticated");
|
|
37
40
|
|
package/src/server/health.ts
CHANGED
|
@@ -12,5 +12,7 @@ export const checkAuthTables: HealthCheck = async (context) => {
|
|
|
12
12
|
await db.execute(sql`select 1 from auth.sessions limit 0`);
|
|
13
13
|
await db.execute(sql`select 1 from auth.user_roles limit 0`);
|
|
14
14
|
await db.execute(sql`select 1 from auth.password_resets limit 0`);
|
|
15
|
+
await db.execute(sql`select 1 from auth.identities limit 0`);
|
|
16
|
+
await db.execute(sql`select 1 from auth.oidc_states limit 0`);
|
|
15
17
|
return ok();
|
|
16
18
|
};
|
package/src/server/index.ts
CHANGED
|
@@ -9,6 +9,23 @@ export {
|
|
|
9
9
|
type OnlyAccountResult,
|
|
10
10
|
type ResolveOnlyAccountOptions,
|
|
11
11
|
} from "./only-account.js";
|
|
12
|
+
export {
|
|
13
|
+
completeOidcSignIn,
|
|
14
|
+
findOidcProvider,
|
|
15
|
+
getAllowedEmail,
|
|
16
|
+
getOidcCallbackPath,
|
|
17
|
+
getOidcProviders,
|
|
18
|
+
getOidcRedirectUri,
|
|
19
|
+
startOidcSignIn,
|
|
20
|
+
type CompleteOidcSignInInput,
|
|
21
|
+
type CompleteOidcSignInResult,
|
|
22
|
+
type IdentityClaims,
|
|
23
|
+
type OidcCallbackParams,
|
|
24
|
+
type OidcContext,
|
|
25
|
+
type StartedOidcSignIn,
|
|
26
|
+
type StartOidcSignInInput,
|
|
27
|
+
type StartOidcSignInResult,
|
|
28
|
+
} from "./oidc/index.js";
|
|
12
29
|
export { getAuthOptions, getAuthRoutes, type AuthRoutes } from "./options.js";
|
|
13
30
|
export { hashPassword, isPasswordHash, matchPassword, MAX_PASSWORD_LENGTH, needsRehash, verifyPassword, type PasswordMatch } from "./password.js";
|
|
14
31
|
export {
|
package/src/server/login.ts
CHANGED
|
@@ -22,10 +22,11 @@ export interface LoginInput {
|
|
|
22
22
|
|
|
23
23
|
export type LoginResult = Ok<SignedIn> | Err<"auth.invalid_credentials"> | RateLimitRejection;
|
|
24
24
|
|
|
25
|
-
/** Checks the credentials and opens a session. Database errors propagate. */
|
|
25
|
+
/** Checks the credentials and opens a session; with `password.enabled: false` no password opens one. Database errors propagate. */
|
|
26
26
|
export async function loginUser(ctx: AuthContext, input: LoginInput): Promise<LoginResult> {
|
|
27
27
|
const options = getAuthOptions(ctx.config);
|
|
28
28
|
assertAuthBuckets(ctx.config);
|
|
29
|
+
if (!options.password.enabled) return err("auth.invalid_credentials");
|
|
29
30
|
const byClient = await consumeRateLimit(ctx, { bucket: BUCKETS.login, key: input.clientKey });
|
|
30
31
|
if (!byClient.ok) return byClient;
|
|
31
32
|
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// The account an OpenID Connect identity signs in to. The provider's subject finds it (`auth.identities`), so an
|
|
2
|
+
// email change at the provider keeps it; a first sign-in links the account with the same verified email, or creates
|
|
3
|
+
// one with an unusable password when the provider may create accounts. One transaction, so two first sign-ins at
|
|
4
|
+
// once end with one account and one identity.
|
|
5
|
+
import { randomBytes } from "node:crypto";
|
|
6
|
+
import { err, ok, type Err, type Ok } from "@softure-ai/core";
|
|
7
|
+
import { and, eq } from "drizzle-orm";
|
|
8
|
+
import type { AuthUser } from "../../contract.js";
|
|
9
|
+
import type { OidcProvider } from "../../options.js";
|
|
10
|
+
import { identities, users } from "../../schema.js";
|
|
11
|
+
import { getAuthOptions } from "../options.js";
|
|
12
|
+
import { hashPassword } from "../password.js";
|
|
13
|
+
import type { AuthContext } from "../sessions.js";
|
|
14
|
+
|
|
15
|
+
export interface OidcIdentity {
|
|
16
|
+
readonly subject: string;
|
|
17
|
+
/** Verified, trimmed and lowercased. */
|
|
18
|
+
readonly email: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export type OidcAccountResult = Ok<AuthUser> | Err<"auth.oidc_no_account">;
|
|
22
|
+
|
|
23
|
+
export async function resolveOidcAccount(ctx: AuthContext, provider: OidcProvider, identity: OidcIdentity): Promise<OidcAccountResult> {
|
|
24
|
+
const options = getAuthOptions(ctx.config);
|
|
25
|
+
const now = ctx.clock.now();
|
|
26
|
+
|
|
27
|
+
return ctx.db.transaction(async (tx): Promise<OidcAccountResult> => {
|
|
28
|
+
const txCtx: AuthContext = { ...ctx, db: tx };
|
|
29
|
+
const findLinked = async (): Promise<AuthUser | undefined> => {
|
|
30
|
+
const [row] = await tx
|
|
31
|
+
.select({ id: users.id, email: users.email, createdAt: users.createdAt })
|
|
32
|
+
.from(identities)
|
|
33
|
+
.innerJoin(users, eq(users.id, identities.userId))
|
|
34
|
+
.where(and(eq(identities.provider, provider.id), eq(identities.subject, identity.subject)))
|
|
35
|
+
.limit(1);
|
|
36
|
+
return row;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const linked = await findLinked();
|
|
40
|
+
if (linked !== undefined) {
|
|
41
|
+
await tx
|
|
42
|
+
.update(identities)
|
|
43
|
+
.set({ email: identity.email, lastLoginAt: now })
|
|
44
|
+
.where(and(eq(identities.provider, provider.id), eq(identities.subject, identity.subject)));
|
|
45
|
+
return ok(linked);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
let [user] = await tx
|
|
49
|
+
.select({ id: users.id, email: users.email, createdAt: users.createdAt })
|
|
50
|
+
.from(users)
|
|
51
|
+
.where(eq(users.email, identity.email))
|
|
52
|
+
.limit(1);
|
|
53
|
+
let isCreated = false;
|
|
54
|
+
if (user === undefined) {
|
|
55
|
+
if (!provider.createAccounts) return err("auth.oidc_no_account");
|
|
56
|
+
// Nobody knows this password: the account signs in through its identity (or a reset link, when passwords are on).
|
|
57
|
+
const unusablePassword = await hashPassword(randomBytes(32).toString("base64url"), options.password.scrypt);
|
|
58
|
+
const [created] = await tx
|
|
59
|
+
.insert(users)
|
|
60
|
+
.values({ email: identity.email, passwordHash: unusablePassword, createdAt: now, passwordChangedAt: now })
|
|
61
|
+
.onConflictDoNothing({ target: users.email })
|
|
62
|
+
.returning({ id: users.id, email: users.email, createdAt: users.createdAt });
|
|
63
|
+
isCreated = created !== undefined;
|
|
64
|
+
// Taken meanwhile by another sign-in or a registration: that account is the one to link.
|
|
65
|
+
[user] =
|
|
66
|
+
created === undefined
|
|
67
|
+
? await tx.select({ id: users.id, email: users.email, createdAt: users.createdAt }).from(users).where(eq(users.email, identity.email)).limit(1)
|
|
68
|
+
: [created];
|
|
69
|
+
if (user === undefined) return err("auth.oidc_no_account");
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
await tx
|
|
73
|
+
.insert(identities)
|
|
74
|
+
.values({ provider: provider.id, subject: identity.subject, userId: user.id, email: identity.email, createdAt: now, lastLoginAt: now })
|
|
75
|
+
.onConflictDoNothing();
|
|
76
|
+
// The pair may have been linked meanwhile; an account that already has another subject of this provider is refused.
|
|
77
|
+
const nowLinked = await findLinked();
|
|
78
|
+
if (nowLinked?.id !== user.id) return err("auth.oidc_no_account");
|
|
79
|
+
if (isCreated) await options.onRegistered?.({ user, consent: null, fields: {}, oidcProvider: provider.id }, txCtx);
|
|
80
|
+
return ok(user);
|
|
81
|
+
});
|
|
82
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// What the OpenID Connect functions receive besides the auth context, and the lookups they share.
|
|
2
|
+
import type { SoftureConfig } from "@softure-ai/core";
|
|
3
|
+
import type { OidcProvider } from "../../options.js";
|
|
4
|
+
import { getAuthOptions } from "../options.js";
|
|
5
|
+
import type { AuthContext } from "../sessions.js";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* A step's outcome inside the flow: its value, or the reason it failed. The reason is this module's own wording for
|
|
9
|
+
* the log, never shown to the user (who gets `auth.oidc_failed`) and never a value from the provider.
|
|
10
|
+
*/
|
|
11
|
+
export type Checked<T> = { readonly ok: true; readonly value: T } | { readonly ok: false; readonly reason: string };
|
|
12
|
+
|
|
13
|
+
export function passed<T>(value: T): Checked<T> {
|
|
14
|
+
return { ok: true, value };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function refused(reason: string): { readonly ok: false; readonly reason: string } {
|
|
18
|
+
return { ok: false, reason };
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** The auth context, plus the environment the client id and secret are read from (default `process.env`). */
|
|
22
|
+
export type OidcContext = AuthContext & { readonly env?: Readonly<Record<string, string | undefined>> };
|
|
23
|
+
|
|
24
|
+
/** The path a provider sends the browser back to, mounted at `app/api/auth/oidc/[provider]/callback/route.ts`. */
|
|
25
|
+
export function getOidcCallbackPath(providerId: string): string {
|
|
26
|
+
return `/api/auth/oidc/${providerId}/callback`;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The callback as an absolute URL on `appOrigin`: the `redirect_uri` registered at the provider. */
|
|
30
|
+
export function getOidcRedirectUri(config: SoftureConfig, providerId: string): string {
|
|
31
|
+
return new URL(getOidcCallbackPath(providerId), config.appOrigin).toString();
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The configured providers, in their order; empty when OpenID Connect sign-in is off. */
|
|
35
|
+
export function getOidcProviders(config: SoftureConfig): readonly OidcProvider[] {
|
|
36
|
+
return getAuthOptions(config).oidc.providers;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function findOidcProvider(config: SoftureConfig, providerId: string): OidcProvider | undefined {
|
|
40
|
+
return getOidcProviders(config).find((provider) => provider.id === providerId);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface OidcClient {
|
|
44
|
+
readonly clientId: string;
|
|
45
|
+
readonly clientSecret: string | null;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The client id and secret from the environment; a missing one is named (never its value) in the error. */
|
|
49
|
+
export function readOidcClient(ctx: OidcContext, provider: OidcProvider): Checked<OidcClient> {
|
|
50
|
+
const env = ctx.env ?? process.env;
|
|
51
|
+
const clientId = env[provider.clientIdEnv]?.trim() ?? "";
|
|
52
|
+
if (clientId === "") return refused(`${provider.clientIdEnv} is not set`);
|
|
53
|
+
if (provider.clientSecretEnv === undefined) return passed({ clientId, clientSecret: null });
|
|
54
|
+
const clientSecret = env[provider.clientSecretEnv]?.trim() ?? "";
|
|
55
|
+
return clientSecret === "" ? refused(`${provider.clientSecretEnv} is not set`) : passed({ clientId, clientSecret });
|
|
56
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
// A provider's discovery document (OpenID Connect Discovery 1.0) and its signing keys (JWKS), fetched through
|
|
2
|
+
// core's `requestJson` (timeout, no redirect followed) and cached per app configuration. The document must name the
|
|
3
|
+
// configured issuer (§4.3) and https endpoints, so a document cannot send the client secret to another scheme.
|
|
4
|
+
import { createPublicKey, type JsonWebKey, type KeyObject } from "node:crypto";
|
|
5
|
+
import { requestJson, type SoftureConfig } from "@softure-ai/core";
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
import { isSecureEndpoint, type OidcProvider } from "../../options.js";
|
|
8
|
+
import { getAuthOptions } from "../options.js";
|
|
9
|
+
import { passed, refused, type Checked, type OidcContext } from "./context.js";
|
|
10
|
+
|
|
11
|
+
/** How long a discovery document is reused. */
|
|
12
|
+
const METADATA_TTL_MS = 60 * 60 * 1000;
|
|
13
|
+
/** How long a key set is reused, and the shortest gap between two fetches for an unknown key id. */
|
|
14
|
+
const JWKS_TTL_MS = 60 * 60 * 1000;
|
|
15
|
+
const JWKS_REFETCH_FLOOR_MS = 60 * 1000;
|
|
16
|
+
|
|
17
|
+
const endpoint = z.string().max(2048).refine(isSecureEndpoint);
|
|
18
|
+
|
|
19
|
+
const metadataSchema = z.object({
|
|
20
|
+
issuer: z.string().max(2048),
|
|
21
|
+
authorization_endpoint: endpoint,
|
|
22
|
+
token_endpoint: endpoint,
|
|
23
|
+
jwks_uri: endpoint,
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
const jwkSchema = z.looseObject({
|
|
27
|
+
kty: z.string(),
|
|
28
|
+
kid: z.string().max(256).optional(),
|
|
29
|
+
use: z.string().optional(),
|
|
30
|
+
alg: z.string().optional(),
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
const jwksSchema = z.object({ keys: z.array(jwkSchema).max(100) });
|
|
34
|
+
|
|
35
|
+
export interface ProviderMetadata {
|
|
36
|
+
readonly issuer: string;
|
|
37
|
+
readonly authorizationEndpoint: string;
|
|
38
|
+
readonly tokenEndpoint: string;
|
|
39
|
+
readonly jwksUri: string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface SigningKey {
|
|
43
|
+
readonly kid: string | undefined;
|
|
44
|
+
readonly key: KeyObject;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
interface Cached<T> {
|
|
48
|
+
readonly value: T;
|
|
49
|
+
readonly fetchedAt: number;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const metadataCache = new WeakMap<SoftureConfig, Map<string, Cached<ProviderMetadata>>>();
|
|
53
|
+
const jwksCache = new WeakMap<SoftureConfig, Map<string, Cached<readonly SigningKey[]>>>();
|
|
54
|
+
|
|
55
|
+
function getCache<T>(caches: WeakMap<SoftureConfig, Map<string, Cached<T>>>, config: SoftureConfig): Map<string, Cached<T>> {
|
|
56
|
+
let cache = caches.get(config);
|
|
57
|
+
if (cache === undefined) {
|
|
58
|
+
cache = new Map();
|
|
59
|
+
caches.set(config, cache);
|
|
60
|
+
}
|
|
61
|
+
return cache;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function requestOptions(ctx: OidcContext) {
|
|
65
|
+
const options = getAuthOptions(ctx.config).oidc;
|
|
66
|
+
return { fetch: options.fetch, timeoutMs: options.httpTimeoutMs, clock: ctx.clock };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The provider's endpoints, or the reason (for the log) they could not be read. */
|
|
70
|
+
export async function getProviderMetadata(ctx: OidcContext, provider: OidcProvider): Promise<Checked<ProviderMetadata>> {
|
|
71
|
+
const cache = getCache(metadataCache, ctx.config);
|
|
72
|
+
const now = ctx.clock.now().getTime();
|
|
73
|
+
const cached = cache.get(provider.issuer);
|
|
74
|
+
if (cached !== undefined && now - cached.fetchedAt < METADATA_TTL_MS) return passed(cached.value);
|
|
75
|
+
|
|
76
|
+
const answer = await requestJson({
|
|
77
|
+
url: `${provider.issuer}/.well-known/openid-configuration`,
|
|
78
|
+
schema: metadataSchema,
|
|
79
|
+
...requestOptions(ctx),
|
|
80
|
+
});
|
|
81
|
+
if (!answer.ok) return refused(`discovery ${answer.error}`);
|
|
82
|
+
if (answer.value.issuer.replace(/\/+$/, "") !== provider.issuer) return refused("discovery issuer_mismatch");
|
|
83
|
+
const metadata: ProviderMetadata = {
|
|
84
|
+
issuer: answer.value.issuer,
|
|
85
|
+
authorizationEndpoint: answer.value.authorization_endpoint,
|
|
86
|
+
tokenEndpoint: answer.value.token_endpoint,
|
|
87
|
+
jwksUri: answer.value.jwks_uri,
|
|
88
|
+
};
|
|
89
|
+
cache.set(provider.issuer, { value: metadata, fetchedAt: now });
|
|
90
|
+
return passed(metadata);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* The key that signed a token: by `kid`, or the only signing key of the type when the token names none. An unknown
|
|
95
|
+
* `kid` (the provider rotated its keys) refetches the set, at most once a minute.
|
|
96
|
+
*/
|
|
97
|
+
export async function findSigningKey(
|
|
98
|
+
ctx: OidcContext,
|
|
99
|
+
metadata: ProviderMetadata,
|
|
100
|
+
match: { readonly kid: string | undefined; readonly keyType: "RSA" | "EC" },
|
|
101
|
+
): Promise<Checked<KeyObject>> {
|
|
102
|
+
const cache = getCache(jwksCache, ctx.config);
|
|
103
|
+
const now = ctx.clock.now().getTime();
|
|
104
|
+
const cached = cache.get(metadata.jwksUri);
|
|
105
|
+
if (cached !== undefined && now - cached.fetchedAt < JWKS_TTL_MS) {
|
|
106
|
+
const key = pickKey(cached.value, match);
|
|
107
|
+
if (key !== undefined) return passed(key);
|
|
108
|
+
if (now - cached.fetchedAt < JWKS_REFETCH_FLOOR_MS) return refused("jwks unknown_key");
|
|
109
|
+
}
|
|
110
|
+
const answer = await requestJson({ url: metadata.jwksUri, schema: jwksSchema, ...requestOptions(ctx) });
|
|
111
|
+
if (!answer.ok) return refused(`jwks ${answer.error}`);
|
|
112
|
+
const keys = answer.value.keys.flatMap((jwk) => toSigningKey(jwk));
|
|
113
|
+
cache.set(metadata.jwksUri, { value: keys, fetchedAt: now });
|
|
114
|
+
const key = pickKey(keys, match);
|
|
115
|
+
return key === undefined ? refused("jwks unknown_key") : passed(key);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function toSigningKey(jwk: z.output<typeof jwkSchema>): SigningKey[] {
|
|
119
|
+
if (jwk.use !== undefined && jwk.use !== "sig") return [];
|
|
120
|
+
try {
|
|
121
|
+
return [{ kid: jwk.kid, key: createPublicKey({ key: jwk as JsonWebKey, format: "jwk" }) }];
|
|
122
|
+
} catch {
|
|
123
|
+
// A key node cannot read (another curve, a broken entry) cannot have signed a token we accept.
|
|
124
|
+
return [];
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function pickKey(keys: readonly SigningKey[], match: { readonly kid: string | undefined; readonly keyType: "RSA" | "EC" }): KeyObject | undefined {
|
|
129
|
+
const nodeType = match.keyType === "RSA" ? "rsa" : "ec";
|
|
130
|
+
const ofType = keys.filter((entry) => entry.key.asymmetricKeyType === nodeType);
|
|
131
|
+
if (match.kid !== undefined) return ofType.find((entry) => entry.kid === match.kid)?.key;
|
|
132
|
+
return ofType.length === 1 ? ofType[0]?.key : undefined;
|
|
133
|
+
}
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
// OpenID Connect sign-in: the authorization code flow with PKCE S256 (RFC 7636), a one-time state and a nonce.
|
|
2
|
+
// `startOidcSignIn` stores the sign-in (the state's sha256, the nonce, the verifier, the return path) and answers
|
|
3
|
+
// the provider's authorize URL and the state, which the adapter keeps in a short-lived cookie: the callback must come
|
|
4
|
+
// back to the browser that started it (no login CSRF). `completeOidcSignIn` consumes the row, exchanges the code,
|
|
5
|
+
// verifies the ID token, checks the allowlist and opens a session. Nothing the provider says is echoed: failures
|
|
6
|
+
// are codes, and the reason behind `auth.oidc_failed` goes to the log only.
|
|
7
|
+
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
8
|
+
import { err, ok, type Err, type Ok } from "@softure-ai/core";
|
|
9
|
+
import type { RateLimitRejection } from "@softure-ai/security";
|
|
10
|
+
import { consumeRateLimit } from "@softure-ai/security/server";
|
|
11
|
+
import { and, eq, gt, lte } from "drizzle-orm";
|
|
12
|
+
import type { OidcSignInErrorCode, SignedIn } from "../../contract.js";
|
|
13
|
+
import type { OidcProvider } from "../../options.js";
|
|
14
|
+
import { toSafeNextPath } from "../../safe-next-path.js";
|
|
15
|
+
import { oidcStates } from "../../schema.js";
|
|
16
|
+
import { getAuthOptions, getAuthRoutes } from "../options.js";
|
|
17
|
+
import { assertAuthBuckets, BUCKETS } from "../rate-limits.js";
|
|
18
|
+
import { createSession, deleteExpiredSessions } from "../sessions.js";
|
|
19
|
+
import { resolveOidcAccount } from "./accounts.js";
|
|
20
|
+
import { findOidcProvider, getOidcRedirectUri, readOidcClient, type OidcContext } from "./context.js";
|
|
21
|
+
import { findSigningKey, getProviderMetadata } from "./discovery.js";
|
|
22
|
+
import { checkIdTokenClaims, decodeIdToken, isSignedBy, type IdentityClaims } from "./id-token.js";
|
|
23
|
+
import { exchangeCode } from "./token-request.js";
|
|
24
|
+
|
|
25
|
+
const RANDOM_BYTES = 32;
|
|
26
|
+
const MAX_STATE_LENGTH = 512;
|
|
27
|
+
const MAX_CODE_LENGTH = 4096;
|
|
28
|
+
const REQUIRED_SCOPES = ["openid", "email"];
|
|
29
|
+
|
|
30
|
+
export interface StartOidcSignInInput {
|
|
31
|
+
readonly provider: string;
|
|
32
|
+
/** Where to go after the sign-in; checked like login's `next`. */
|
|
33
|
+
readonly next?: string;
|
|
34
|
+
/** The client's rate limit key (`identifyClient`). */
|
|
35
|
+
readonly clientKey: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface StartedOidcSignIn {
|
|
39
|
+
/** The provider's authorize URL to send the browser to. */
|
|
40
|
+
readonly url: string;
|
|
41
|
+
/** The state, for the browser's cookie; the callback must bring the same one back. */
|
|
42
|
+
readonly state: string;
|
|
43
|
+
/** How long the sign-in may take, for the cookie's `Max-Age`. */
|
|
44
|
+
readonly maxAgeSeconds: number;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export type StartOidcSignInResult = Ok<StartedOidcSignIn> | Err<"auth.oidc_failed"> | RateLimitRejection;
|
|
48
|
+
|
|
49
|
+
/** Starts a sign-in with `provider`. Database errors propagate. */
|
|
50
|
+
export async function startOidcSignIn(ctx: OidcContext, input: StartOidcSignInInput): Promise<StartOidcSignInResult> {
|
|
51
|
+
assertAuthBuckets(ctx.config);
|
|
52
|
+
const limit = await consumeRateLimit(ctx, { bucket: BUCKETS.oidcStart, key: input.clientKey });
|
|
53
|
+
if (!limit.ok) return limit;
|
|
54
|
+
const provider = findOidcProvider(ctx.config, input.provider);
|
|
55
|
+
if (provider === undefined) return err("auth.oidc_failed");
|
|
56
|
+
const client = readOidcClient(ctx, provider);
|
|
57
|
+
if (!client.ok) return fail(provider, client.reason);
|
|
58
|
+
const metadata = await getProviderMetadata(ctx, provider);
|
|
59
|
+
if (!metadata.ok) return fail(provider, metadata.reason);
|
|
60
|
+
|
|
61
|
+
const now = ctx.clock.now();
|
|
62
|
+
const ttlMinutes = getAuthOptions(ctx.config).oidc.stateTtlMinutes;
|
|
63
|
+
const state = createRandomValue();
|
|
64
|
+
const nonce = createRandomValue();
|
|
65
|
+
const codeVerifier = createRandomValue();
|
|
66
|
+
await ctx.db.delete(oidcStates).where(lte(oidcStates.expiresAt, now));
|
|
67
|
+
await ctx.db.insert(oidcStates).values({
|
|
68
|
+
stateHash: hashState(state),
|
|
69
|
+
provider: provider.id,
|
|
70
|
+
nonce,
|
|
71
|
+
codeVerifier,
|
|
72
|
+
nextPath: toSafeNextPath(input.next, getAuthRoutes(ctx.config).afterLogin),
|
|
73
|
+
createdAt: now,
|
|
74
|
+
expiresAt: new Date(now.getTime() + ttlMinutes * 60_000),
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
const url = new URL(metadata.value.authorizationEndpoint);
|
|
78
|
+
for (const [name, value] of Object.entries(provider.authorizeParams)) url.searchParams.set(name, value);
|
|
79
|
+
url.searchParams.set("response_type", "code");
|
|
80
|
+
url.searchParams.set("client_id", client.value.clientId);
|
|
81
|
+
url.searchParams.set("redirect_uri", getOidcRedirectUri(ctx.config, provider.id));
|
|
82
|
+
url.searchParams.set("scope", [...new Set([...REQUIRED_SCOPES, ...provider.scopes])].join(" "));
|
|
83
|
+
url.searchParams.set("state", state);
|
|
84
|
+
url.searchParams.set("nonce", nonce);
|
|
85
|
+
url.searchParams.set("code_challenge", createHash("sha256").update(codeVerifier, "ascii").digest("base64url"));
|
|
86
|
+
url.searchParams.set("code_challenge_method", "S256");
|
|
87
|
+
return ok({ url: url.toString(), state, maxAgeSeconds: ttlMinutes * 60 });
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** The callback's query: `code` and `state`, or `error` and `state`. */
|
|
91
|
+
export interface OidcCallbackParams {
|
|
92
|
+
readonly state: string | null;
|
|
93
|
+
readonly code: string | null;
|
|
94
|
+
readonly error: string | null;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export interface CompleteOidcSignInInput {
|
|
98
|
+
/** The provider in the callback's path. */
|
|
99
|
+
readonly provider: string;
|
|
100
|
+
readonly params: OidcCallbackParams;
|
|
101
|
+
/** The state from the browser's cookie; null without the cookie. */
|
|
102
|
+
readonly browserState: string | null;
|
|
103
|
+
readonly clientKey: string;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export type CompleteOidcSignInResult = Ok<SignedIn & { readonly next: string }> | Err<OidcSignInErrorCode> | RateLimitRejection;
|
|
107
|
+
|
|
108
|
+
/** Completes the sign-in the callback names and opens a session. Database errors and a failing hook propagate. */
|
|
109
|
+
export async function completeOidcSignIn(ctx: OidcContext, input: CompleteOidcSignInInput): Promise<CompleteOidcSignInResult> {
|
|
110
|
+
assertAuthBuckets(ctx.config);
|
|
111
|
+
const limit = await consumeRateLimit(ctx, { bucket: BUCKETS.oidcCallback, key: input.clientKey });
|
|
112
|
+
if (!limit.ok) return limit;
|
|
113
|
+
const provider = findOidcProvider(ctx.config, input.provider);
|
|
114
|
+
if (provider === undefined) return err("auth.oidc_failed");
|
|
115
|
+
|
|
116
|
+
const { state, code, error } = input.params;
|
|
117
|
+
if (state === null || state.length > MAX_STATE_LENGTH) return fail(provider, "state missing");
|
|
118
|
+
if (input.browserState === null || !isSameText(state, input.browserState)) return fail(provider, "state not from this browser");
|
|
119
|
+
const now = ctx.clock.now();
|
|
120
|
+
// One-time: the row is gone whatever happens next.
|
|
121
|
+
const [pending] = await ctx.db
|
|
122
|
+
.delete(oidcStates)
|
|
123
|
+
.where(and(eq(oidcStates.stateHash, hashState(state)), eq(oidcStates.provider, provider.id), gt(oidcStates.expiresAt, now)))
|
|
124
|
+
.returning();
|
|
125
|
+
if (pending === undefined) return fail(provider, "state unknown, used or expired");
|
|
126
|
+
if (error !== null) return error === "access_denied" ? err("auth.oidc_cancelled") : fail(provider, "provider answered an error");
|
|
127
|
+
if (code === null || code === "" || code.length > MAX_CODE_LENGTH) return fail(provider, "code missing");
|
|
128
|
+
|
|
129
|
+
const client = readOidcClient(ctx, provider);
|
|
130
|
+
if (!client.ok) return fail(provider, client.reason);
|
|
131
|
+
const metadata = await getProviderMetadata(ctx, provider);
|
|
132
|
+
if (!metadata.ok) return fail(provider, metadata.reason);
|
|
133
|
+
const exchanged = await exchangeCode(ctx, {
|
|
134
|
+
provider,
|
|
135
|
+
client: client.value,
|
|
136
|
+
tokenEndpoint: metadata.value.tokenEndpoint,
|
|
137
|
+
code,
|
|
138
|
+
codeVerifier: pending.codeVerifier,
|
|
139
|
+
redirectUri: getOidcRedirectUri(ctx.config, provider.id),
|
|
140
|
+
});
|
|
141
|
+
if (!exchanged.ok) return fail(provider, exchanged.reason);
|
|
142
|
+
|
|
143
|
+
const token = decodeIdToken(exchanged.value);
|
|
144
|
+
if (!token.ok) return fail(provider, token.reason);
|
|
145
|
+
const key = await findSigningKey(ctx, metadata.value, { kid: token.value.kid, keyType: token.value.keyType });
|
|
146
|
+
if (!key.ok) return fail(provider, key.reason);
|
|
147
|
+
if (!isSignedBy(token.value, key.value)) return fail(provider, "id_token signature");
|
|
148
|
+
const claims = checkIdTokenClaims(token.value.payload, { issuer: provider.issuer, clientId: client.value.clientId, nonce: pending.nonce, now });
|
|
149
|
+
if (!claims.ok) return fail(provider, claims.reason);
|
|
150
|
+
|
|
151
|
+
const email = getAllowedEmail(provider, claims.value);
|
|
152
|
+
if (email === null) return err("auth.oidc_not_allowed");
|
|
153
|
+
const account = await resolveOidcAccount(ctx, provider, { subject: claims.value.subject, email });
|
|
154
|
+
if (!account.ok) return account;
|
|
155
|
+
|
|
156
|
+
await deleteExpiredSessions(ctx, account.value.id);
|
|
157
|
+
const session = await createSession(ctx, account.value.id);
|
|
158
|
+
return ok({ user: account.value, session, next: toSafeNextPath(pending.nextPath, getAuthRoutes(ctx.config).afterLogin) });
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* The identity's email when it may sign in: verified, and listed in `allowedEmails` or of a domain in
|
|
163
|
+
* `allowedDomains` (with `requireHostedDomain`, the `hd` claim must name that domain too); null otherwise.
|
|
164
|
+
*/
|
|
165
|
+
export function getAllowedEmail(provider: OidcProvider, claims: IdentityClaims): string | null {
|
|
166
|
+
const { email } = claims;
|
|
167
|
+
if (email === null || !claims.isEmailVerified) return null;
|
|
168
|
+
if (provider.allowedEmails.includes(email)) return email;
|
|
169
|
+
const at = email.lastIndexOf("@");
|
|
170
|
+
if (at <= 0) return null;
|
|
171
|
+
const domain = email.slice(at + 1);
|
|
172
|
+
if (!provider.allowedDomains.includes(domain)) return null;
|
|
173
|
+
if (provider.requireHostedDomain && claims.hostedDomain !== domain) return null;
|
|
174
|
+
return email;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function fail(provider: OidcProvider, reason: string): Err<"auth.oidc_failed"> {
|
|
178
|
+
// The reason is this module's own wording: never a value from the provider or the browser.
|
|
179
|
+
console.warn(`@softure-ai/auth: OpenID Connect sign-in with ${provider.id} failed: ${reason}`);
|
|
180
|
+
return err("auth.oidc_failed");
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function createRandomValue(): string {
|
|
184
|
+
return randomBytes(RANDOM_BYTES).toString("base64url");
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** The stored form of a state: sha256 hex. */
|
|
188
|
+
function hashState(state: string): string {
|
|
189
|
+
return createHash("sha256").update(state, "utf8").digest("hex");
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function isSameText(a: string, b: string): boolean {
|
|
193
|
+
const left = Buffer.from(a, "utf8");
|
|
194
|
+
const right = Buffer.from(b, "utf8");
|
|
195
|
+
return left.length === right.length && timingSafeEqual(left, right);
|
|
196
|
+
}
|