@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
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// The ID token (OpenID Connect Core §3.1.3.7): a JWS in compact form, signed with RS256 or ES256 (no `none`, no
|
|
2
|
+
// HMAC), checked against the issuer's key and the claims the sign-in expects. Nothing in the token is trusted before
|
|
3
|
+
// its signature is.
|
|
4
|
+
import { timingSafeEqual, verify, type KeyObject } from "node:crypto";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import { passed, refused, type Checked } from "./context.js";
|
|
7
|
+
|
|
8
|
+
/** Clock skew tolerated between this server and the provider. */
|
|
9
|
+
const SKEW_SECONDS = 60;
|
|
10
|
+
const MAX_TOKEN_LENGTH = 16_384;
|
|
11
|
+
const SEGMENT = /^[A-Za-z0-9_-]+$/;
|
|
12
|
+
|
|
13
|
+
const ALGORITHMS = { RS256: "RSA", ES256: "EC" } as const;
|
|
14
|
+
export type IdTokenAlgorithm = keyof typeof ALGORITHMS;
|
|
15
|
+
|
|
16
|
+
const headerSchema = z.object({ alg: z.string(), kid: z.string().max(256).optional() });
|
|
17
|
+
|
|
18
|
+
const claimsSchema = z.object({
|
|
19
|
+
iss: z.string(),
|
|
20
|
+
sub: z.string().min(1).max(255),
|
|
21
|
+
aud: z.union([z.string(), z.array(z.string()).min(1).max(20)]),
|
|
22
|
+
azp: z.string().optional(),
|
|
23
|
+
exp: z.number(),
|
|
24
|
+
iat: z.number(),
|
|
25
|
+
nonce: z.string().optional(),
|
|
26
|
+
email: z.string().max(254).optional(),
|
|
27
|
+
// Most providers send a boolean; some send the string.
|
|
28
|
+
email_verified: z.union([z.boolean(), z.enum(["true", "false"]).transform((value) => value === "true")]).optional(),
|
|
29
|
+
hd: z.string().max(253).optional(),
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
export interface DecodedIdToken {
|
|
33
|
+
readonly algorithm: IdTokenAlgorithm;
|
|
34
|
+
readonly keyType: "RSA" | "EC";
|
|
35
|
+
readonly kid: string | undefined;
|
|
36
|
+
readonly signingInput: string;
|
|
37
|
+
readonly signature: Buffer;
|
|
38
|
+
readonly payload: unknown;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The token's parts, or the reason (for the log) it is not a JWS this module accepts. */
|
|
42
|
+
export function decodeIdToken(token: string): Checked<DecodedIdToken> {
|
|
43
|
+
if (token.length > MAX_TOKEN_LENGTH) return refused("id_token too_long");
|
|
44
|
+
const parts = token.split(".");
|
|
45
|
+
if (parts.length !== 3 || !parts.every((part) => SEGMENT.test(part))) return refused("id_token malformed");
|
|
46
|
+
const [encodedHeader = "", encodedPayload = "", encodedSignature = ""] = parts;
|
|
47
|
+
const header = headerSchema.safeParse(parseJson(encodedHeader));
|
|
48
|
+
if (!header.success) return refused("id_token malformed");
|
|
49
|
+
const algorithm = header.data.alg;
|
|
50
|
+
if (!Object.hasOwn(ALGORITHMS, algorithm)) return refused("id_token algorithm");
|
|
51
|
+
const payload = parseJson(encodedPayload);
|
|
52
|
+
if (payload === undefined) return refused("id_token malformed");
|
|
53
|
+
return passed({
|
|
54
|
+
algorithm: algorithm as IdTokenAlgorithm,
|
|
55
|
+
keyType: ALGORITHMS[algorithm as IdTokenAlgorithm],
|
|
56
|
+
kid: header.data.kid,
|
|
57
|
+
signingInput: `${encodedHeader}.${encodedPayload}`,
|
|
58
|
+
signature: Buffer.from(encodedSignature, "base64url"),
|
|
59
|
+
payload,
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function parseJson(segment: string): unknown {
|
|
64
|
+
try {
|
|
65
|
+
return JSON.parse(Buffer.from(segment, "base64url").toString("utf8")) as unknown;
|
|
66
|
+
} catch {
|
|
67
|
+
return undefined;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Whether `key` signed the token. An ES256 signature is the JWS form (r || s), not DER. */
|
|
72
|
+
export function isSignedBy(token: DecodedIdToken, key: KeyObject): boolean {
|
|
73
|
+
const data = Buffer.from(token.signingInput, "ascii");
|
|
74
|
+
try {
|
|
75
|
+
if (token.algorithm === "ES256") {
|
|
76
|
+
return key.asymmetricKeyDetails?.namedCurve === "prime256v1" && verify("sha256", data, { key, dsaEncoding: "ieee-p1363" }, token.signature);
|
|
77
|
+
}
|
|
78
|
+
return verify("sha256", data, key, token.signature);
|
|
79
|
+
} catch {
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export interface ExpectedClaims {
|
|
85
|
+
readonly issuer: string;
|
|
86
|
+
readonly clientId: string;
|
|
87
|
+
readonly nonce: string;
|
|
88
|
+
readonly now: Date;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** What a valid token says about the person. */
|
|
92
|
+
export interface IdentityClaims {
|
|
93
|
+
readonly subject: string;
|
|
94
|
+
readonly email: string | null;
|
|
95
|
+
readonly isEmailVerified: boolean;
|
|
96
|
+
readonly hostedDomain: string | null;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The identity, or the reason (for the log) the claims do not fit this sign-in. */
|
|
100
|
+
export function checkIdTokenClaims(payload: unknown, expected: ExpectedClaims): Checked<IdentityClaims> {
|
|
101
|
+
const parsed = claimsSchema.safeParse(payload);
|
|
102
|
+
if (!parsed.success) return refused("id_token claims");
|
|
103
|
+
const claims = parsed.data;
|
|
104
|
+
const nowSeconds = expected.now.getTime() / 1000;
|
|
105
|
+
if (claims.iss.replace(/\/+$/, "") !== expected.issuer) return refused("id_token issuer");
|
|
106
|
+
const audiences = typeof claims.aud === "string" ? [claims.aud] : claims.aud;
|
|
107
|
+
if (!audiences.includes(expected.clientId)) return refused("id_token audience");
|
|
108
|
+
if ((audiences.length > 1 || claims.azp !== undefined) && claims.azp !== expected.clientId) return refused("id_token azp");
|
|
109
|
+
if (claims.exp <= nowSeconds - SKEW_SECONDS) return refused("id_token expired");
|
|
110
|
+
if (claims.iat > nowSeconds + SKEW_SECONDS) return refused("id_token issued_in_future");
|
|
111
|
+
if (claims.nonce === undefined || !isSameText(claims.nonce, expected.nonce)) return refused("id_token nonce");
|
|
112
|
+
return passed({
|
|
113
|
+
subject: claims.sub,
|
|
114
|
+
email: claims.email === undefined ? null : claims.email.trim().toLowerCase(),
|
|
115
|
+
isEmailVerified: claims.email_verified === true,
|
|
116
|
+
hostedDomain: claims.hd === undefined ? null : claims.hd.trim().toLowerCase(),
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function isSameText(a: string, b: string): boolean {
|
|
121
|
+
const left = Buffer.from(a, "utf8");
|
|
122
|
+
const right = Buffer.from(b, "utf8");
|
|
123
|
+
return left.length === right.length && timingSafeEqual(left, right);
|
|
124
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// OpenID Connect sign-in (`auth({ oidc })`): the flow, its context and the allowlist check.
|
|
2
|
+
export { findOidcProvider, getOidcCallbackPath, getOidcProviders, getOidcRedirectUri, type OidcContext } from "./context.js";
|
|
3
|
+
export {
|
|
4
|
+
completeOidcSignIn,
|
|
5
|
+
getAllowedEmail,
|
|
6
|
+
startOidcSignIn,
|
|
7
|
+
type CompleteOidcSignInInput,
|
|
8
|
+
type CompleteOidcSignInResult,
|
|
9
|
+
type OidcCallbackParams,
|
|
10
|
+
type StartedOidcSignIn,
|
|
11
|
+
type StartOidcSignInInput,
|
|
12
|
+
type StartOidcSignInResult,
|
|
13
|
+
} from "./flow.js";
|
|
14
|
+
export type { IdentityClaims } from "./id-token.js";
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// The authorization code exchange at the provider's token endpoint (RFC 6749 §4.1.3, with the PKCE verifier of
|
|
2
|
+
// RFC 7636): a form POST through core's `requestJson`, which follows no redirect, so the client secret never reaches
|
|
3
|
+
// another host. Only the ID token is read; the access token is not kept.
|
|
4
|
+
import { requestJson } from "@softure-ai/core";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import type { OidcProvider } from "../../options.js";
|
|
7
|
+
import { getAuthOptions } from "../options.js";
|
|
8
|
+
import { passed, refused, type Checked, type OidcClient, type OidcContext } from "./context.js";
|
|
9
|
+
|
|
10
|
+
const tokenBodySchema = z.object({ id_token: z.string().min(1).max(16_384) });
|
|
11
|
+
// Only an RFC 6749 error code shape is read (it goes to the log); any other body is just a failed call.
|
|
12
|
+
const errorBodySchema = z.object({ error: z.string().regex(/^[a-z_]{1,64}$/) });
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
export interface TokenExchangeInput {
|
|
16
|
+
readonly provider: OidcProvider;
|
|
17
|
+
readonly client: OidcClient;
|
|
18
|
+
readonly tokenEndpoint: string;
|
|
19
|
+
readonly code: string;
|
|
20
|
+
readonly codeVerifier: string;
|
|
21
|
+
readonly redirectUri: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** The ID token for `code`, or the reason (for the log): the OAuth error code or core's failure code. */
|
|
25
|
+
export async function exchangeCode(ctx: OidcContext, input: TokenExchangeInput): Promise<Checked<string>> {
|
|
26
|
+
const form = new URLSearchParams({
|
|
27
|
+
grant_type: "authorization_code",
|
|
28
|
+
code: input.code,
|
|
29
|
+
redirect_uri: input.redirectUri,
|
|
30
|
+
code_verifier: input.codeVerifier,
|
|
31
|
+
});
|
|
32
|
+
const headers = new Headers();
|
|
33
|
+
if (input.provider.clientAuth === "basic" && input.client.clientSecret !== null) {
|
|
34
|
+
// RFC 6749 §2.3.1: both parts form-encoded before the Basic encoding.
|
|
35
|
+
const user = encodeURIComponent(input.client.clientId);
|
|
36
|
+
const password = encodeURIComponent(input.client.clientSecret);
|
|
37
|
+
headers.set("authorization", `Basic ${Buffer.from(`${user}:${password}`).toString("base64")}`);
|
|
38
|
+
} else {
|
|
39
|
+
form.set("client_id", input.client.clientId);
|
|
40
|
+
if (input.client.clientSecret !== null) form.set("client_secret", input.client.clientSecret);
|
|
41
|
+
}
|
|
42
|
+
const options = getAuthOptions(ctx.config).oidc;
|
|
43
|
+
const answer = await requestJson({
|
|
44
|
+
url: input.tokenEndpoint,
|
|
45
|
+
method: "POST",
|
|
46
|
+
form,
|
|
47
|
+
headers,
|
|
48
|
+
schema: tokenBodySchema,
|
|
49
|
+
errorSchema: errorBodySchema,
|
|
50
|
+
fetch: options.fetch,
|
|
51
|
+
timeoutMs: options.httpTimeoutMs,
|
|
52
|
+
clock: ctx.clock,
|
|
53
|
+
});
|
|
54
|
+
if (answer.ok) {
|
|
55
|
+
// A write answered with no body is `ok(undefined)`; a token endpoint must answer one.
|
|
56
|
+
return answer.value === undefined ? refused("token empty_answer") : passed(answer.value.id_token);
|
|
57
|
+
}
|
|
58
|
+
return refused(`token ${answer.errorBody?.error ?? answer.error}`);
|
|
59
|
+
}
|
|
@@ -22,9 +22,10 @@ const MINUTE_MS = 60 * 1000;
|
|
|
22
22
|
/** The query parameter of the reset link that carries the token. */
|
|
23
23
|
export const RESET_TOKEN_PARAM = "token";
|
|
24
24
|
|
|
25
|
-
/** Whether
|
|
25
|
+
/** Whether password reset is offered at all: passwords are on and the app passed a sender. */
|
|
26
26
|
export function isPasswordResetEnabled(config: SoftureConfig): boolean {
|
|
27
|
-
|
|
27
|
+
const options = getAuthOptions(config);
|
|
28
|
+
return options.password.enabled && options.passwordReset.send !== undefined;
|
|
28
29
|
}
|
|
29
30
|
|
|
30
31
|
export interface PasswordResetRequestInput {
|
package/src/server/privacy.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
// The auth part of a GDPR export and deletion (`@softure-ai/privacy`): the account, its roles, its
|
|
2
|
-
// sessions
|
|
2
|
+
// sessions, a pending reset link and its OpenID Connect identities. Secrets never leave: no password hash and no token hash.
|
|
3
3
|
import { ok, type ModuleContext, type Ok, type PrivacyContributor } from "@softure-ai/core";
|
|
4
4
|
import type { Queryable } from "@softure-ai/db";
|
|
5
5
|
import { asc, eq } from "drizzle-orm";
|
|
6
|
-
import { passwordResets, sessions, userRoles, users } from "../schema.js";
|
|
6
|
+
import { identities, passwordResets, sessions, userRoles, users } from "../schema.js";
|
|
7
7
|
|
|
8
8
|
/** What auth holds about one user, as it appears in their export. */
|
|
9
9
|
export interface AuthUserData {
|
|
@@ -18,11 +18,19 @@ export interface AuthUserData {
|
|
|
18
18
|
readonly roles: readonly { readonly role: string; readonly grantedAt: Date }[];
|
|
19
19
|
readonly sessions: readonly { readonly createdAt: Date; readonly expiresAt: Date }[];
|
|
20
20
|
readonly passwordReset: { readonly createdAt: Date; readonly expiresAt: Date } | null;
|
|
21
|
+
/** The provider identities that sign in to the account. */
|
|
22
|
+
readonly identities: readonly {
|
|
23
|
+
readonly provider: string;
|
|
24
|
+
readonly subject: string;
|
|
25
|
+
readonly email: string;
|
|
26
|
+
readonly createdAt: Date;
|
|
27
|
+
readonly lastLoginAt: Date;
|
|
28
|
+
}[];
|
|
21
29
|
}
|
|
22
30
|
|
|
23
31
|
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
24
32
|
|
|
25
|
-
const NO_DATA: AuthUserData = { account: null, roles: [], sessions: [], passwordReset: null };
|
|
33
|
+
const NO_DATA: AuthUserData = { account: null, roles: [], sessions: [], passwordReset: null, identities: [] };
|
|
26
34
|
|
|
27
35
|
/** The user's auth data. An id that is not a UUID cannot be an account, so it has none. */
|
|
28
36
|
export async function exportAuthUserData(context: ModuleContext, userId: string): Promise<Ok<AuthUserData>> {
|
|
@@ -47,7 +55,18 @@ export async function exportAuthUserData(context: ModuleContext, userId: string)
|
|
|
47
55
|
.select({ createdAt: passwordResets.createdAt, expiresAt: passwordResets.expiresAt })
|
|
48
56
|
.from(passwordResets)
|
|
49
57
|
.where(eq(passwordResets.userId, userId));
|
|
50
|
-
|
|
58
|
+
const userIdentities = await db
|
|
59
|
+
.select({
|
|
60
|
+
provider: identities.provider,
|
|
61
|
+
subject: identities.subject,
|
|
62
|
+
email: identities.email,
|
|
63
|
+
createdAt: identities.createdAt,
|
|
64
|
+
lastLoginAt: identities.lastLoginAt,
|
|
65
|
+
})
|
|
66
|
+
.from(identities)
|
|
67
|
+
.where(eq(identities.userId, userId))
|
|
68
|
+
.orderBy(asc(identities.provider));
|
|
69
|
+
return ok({ account: account ?? null, roles, sessions: userSessions, passwordReset: passwordReset ?? null, identities: userIdentities });
|
|
51
70
|
}
|
|
52
71
|
|
|
53
72
|
/**
|
|
@@ -60,6 +79,7 @@ export async function deleteAuthUserData(context: ModuleContext, userId: string)
|
|
|
60
79
|
await db.delete(sessions).where(eq(sessions.userId, userId));
|
|
61
80
|
await db.delete(passwordResets).where(eq(passwordResets.userId, userId));
|
|
62
81
|
await db.delete(userRoles).where(eq(userRoles.userId, userId));
|
|
82
|
+
await db.delete(identities).where(eq(identities.userId, userId));
|
|
63
83
|
await db.delete(users).where(eq(users.id, userId));
|
|
64
84
|
return ok();
|
|
65
85
|
}
|
|
@@ -12,6 +12,8 @@ export const BUCKETS = {
|
|
|
12
12
|
passwordReset: "password-reset",
|
|
13
13
|
passwordResetAccount: "password-reset-account",
|
|
14
14
|
passwordResetConfirm: "password-reset-confirm",
|
|
15
|
+
oidcStart: "oidc-start",
|
|
16
|
+
oidcCallback: "oidc-callback",
|
|
15
17
|
} as const;
|
|
16
18
|
|
|
17
19
|
/** The subject key of an account's email for `login-account` and `password-reset-account`. */
|
|
@@ -27,11 +29,15 @@ export function userSubjectKey(userId: string): string {
|
|
|
27
29
|
/** The buckets only password reset counts in; not needed while it is off. */
|
|
28
30
|
const RESET_BUCKETS: ReadonlySet<string> = new Set([BUCKETS.passwordReset, BUCKETS.passwordResetAccount, BUCKETS.passwordResetConfirm]);
|
|
29
31
|
|
|
32
|
+
/** The buckets only OpenID Connect sign-in counts in; not needed without providers. */
|
|
33
|
+
const OIDC_BUCKETS: ReadonlySet<string> = new Set([BUCKETS.oidcStart, BUCKETS.oidcCallback]);
|
|
34
|
+
|
|
30
35
|
const checkedConfigs = new WeakSet<SoftureConfig>();
|
|
31
36
|
|
|
32
37
|
/**
|
|
33
38
|
* Throws, naming every missing bucket, when the app's `security({ buckets })` lacks one auth
|
|
34
|
-
* counts in: the reset buckets only when password reset is on (`passwordReset.send`)
|
|
39
|
+
* counts in: the reset buckets only when password reset is on (`passwordReset.send`), the OpenID Connect ones only
|
|
40
|
+
* with a provider. Checked once
|
|
35
41
|
* per config, before the first attempt is counted, so a setup mistake is one clear error instead of
|
|
36
42
|
* a generic failure on every login.
|
|
37
43
|
*/
|
|
@@ -39,8 +45,10 @@ export function assertAuthBuckets(config: SoftureConfig): void {
|
|
|
39
45
|
if (checkedConfigs.has(config)) return;
|
|
40
46
|
const options = getModule(config, "security")?.options as { buckets?: Readonly<Record<string, unknown>> } | undefined;
|
|
41
47
|
const configured = options?.buckets ?? {};
|
|
42
|
-
const
|
|
43
|
-
const
|
|
48
|
+
const authOptions = getAuthOptions(config);
|
|
49
|
+
const isResetOn = authOptions.passwordReset.send !== undefined;
|
|
50
|
+
const isOidcOn = authOptions.oidc.providers.length > 0;
|
|
51
|
+
const required = Object.values(BUCKETS).filter((name) => (isResetOn || !RESET_BUCKETS.has(name)) && (isOidcOn || !OIDC_BUCKETS.has(name)));
|
|
44
52
|
const missing = required.filter((name) => !Object.hasOwn(configured, name));
|
|
45
53
|
if (missing.length > 0) {
|
|
46
54
|
throw new Error(
|
package/src/server/register.ts
CHANGED
|
@@ -71,7 +71,7 @@ export async function registerUser(ctx: AuthContext, input: RegisterInput): Prom
|
|
|
71
71
|
const user = { id: row.id, email: row.email, createdAt: row.createdAt };
|
|
72
72
|
|
|
73
73
|
const fields = pickRegistrationFields(options.registrationFields, input.fields);
|
|
74
|
-
await options.onRegistered?.({ user, consent: options.requireConsent ? { acceptedAt: now } : null, fields }, txCtx);
|
|
74
|
+
await options.onRegistered?.({ user, consent: options.requireConsent ? { acceptedAt: now } : null, fields, oidcProvider: null }, txCtx);
|
|
75
75
|
const session = await createSession(txCtx, user.id);
|
|
76
76
|
return ok({ user, session });
|
|
77
77
|
});
|
package/src/server/switches.ts
CHANGED
|
@@ -14,9 +14,10 @@ const OFF = new Set(["false", "0"]);
|
|
|
14
14
|
* Whether registration is closed. The app's switch provider answers first (env override, stored
|
|
15
15
|
* value, default and fail mode as it defines them). Without one, the env override wins over the
|
|
16
16
|
* declared default; a value it cannot read closes registration (fail closed) and is logged once, by
|
|
17
|
-
* name, never by value.
|
|
17
|
+
* name, never by value. With `password.enabled: false` the register form is gone, so it is always closed.
|
|
18
18
|
*/
|
|
19
19
|
export async function isRegistrationClosed(ctx: ModuleContext, env: Readonly<Record<string, string | undefined>> = process.env): Promise<boolean> {
|
|
20
|
+
if (!getAuthOptions(ctx.config).password.enabled) return true;
|
|
20
21
|
const reading = await readSwitch(ctx, REGISTRATION_CLOSED_SWITCH);
|
|
21
22
|
if (reading.kind === "value") return reading.isEnabled;
|
|
22
23
|
const override = env[REGISTRATION_CLOSED_ENV]?.trim().toLowerCase();
|
package/src/testing/account.ts
CHANGED
|
@@ -75,7 +75,7 @@ export async function createTestAccount(target: Queryable | AuthContext, input:
|
|
|
75
75
|
if (input.runHooks === true && ctx !== null) {
|
|
76
76
|
const options = getAuthOptions(ctx.config);
|
|
77
77
|
const consent = options.requireConsent ? { acceptedAt: now } : null;
|
|
78
|
-
await options.onRegistered?.({ user, consent, fields: input.fields ?? {} }, { ...ctx, db: tx });
|
|
78
|
+
await options.onRegistered?.({ user, consent, fields: input.fields ?? {}, oidcProvider: null }, { ...ctx, db: tx });
|
|
79
79
|
}
|
|
80
80
|
return user;
|
|
81
81
|
});
|
package/src/testing/index.ts
CHANGED
|
@@ -1,3 +1,12 @@
|
|
|
1
1
|
// Test helpers of @softure-ai/auth: accounts created directly in the database, for tests that need
|
|
2
|
-
// a user but are not about registration
|
|
2
|
+
// a user but are not about registration, and a fake OpenID Connect provider for tests of the sign-in.
|
|
3
|
+
// Server-only; never imported by the module's runtime code.
|
|
3
4
|
export { createTestAccount, type TestAccountHashInput, type TestAccountInput } from "./account.js";
|
|
5
|
+
export {
|
|
6
|
+
createFakeOidcProvider,
|
|
7
|
+
type FakeOidcFailure,
|
|
8
|
+
type FakeOidcProvider,
|
|
9
|
+
type FakeOidcProviderOptions,
|
|
10
|
+
type FakeOidcUser,
|
|
11
|
+
type FakeSignInOptions,
|
|
12
|
+
} from "./oidc-provider.js";
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
// An in-memory OpenID Connect provider for tests: discovery, JWKS, authorize (`signIn`) and the token endpoint, reached
|
|
2
|
+
// through a `fetch` the app's `auth({ oidc: { fetch } })` takes. It checks what a real provider checks (client
|
|
3
|
+
// credentials, redirect URI, PKCE verifier, one-time codes) and signs real ID tokens (RS256 or ES256), so the module's
|
|
4
|
+
// verification runs for real. A test breaks it on purpose: other claims, another key, `alg: none`, key rotation, an
|
|
5
|
+
// outage, an endpoint on plain http.
|
|
6
|
+
import { createHash, generateKeyPairSync, randomBytes, sign, type KeyObject } from "node:crypto";
|
|
7
|
+
import { systemClock, type Clock, type FetchFunction } from "@softure-ai/core";
|
|
8
|
+
import type { OidcProviderInput } from "../options.js";
|
|
9
|
+
|
|
10
|
+
export interface FakeOidcProviderOptions {
|
|
11
|
+
/** The provider id. Default `fake`. */
|
|
12
|
+
readonly id?: string;
|
|
13
|
+
/** Default `https://fake-oidc.test`. */
|
|
14
|
+
readonly issuer?: string;
|
|
15
|
+
readonly clientId?: string;
|
|
16
|
+
readonly clientSecret?: string;
|
|
17
|
+
readonly clientAuth?: "body" | "basic";
|
|
18
|
+
/** Default RS256. */
|
|
19
|
+
readonly algorithm?: "RS256" | "ES256";
|
|
20
|
+
/** The clock the tokens' `iat` and `exp` come from; pass the module context's test clock. */
|
|
21
|
+
readonly clock?: Clock;
|
|
22
|
+
/** The allowlist of the definition. Default `allowedDomains: ["example.com"]`. */
|
|
23
|
+
readonly allowedDomains?: readonly string[];
|
|
24
|
+
readonly allowedEmails?: readonly string[];
|
|
25
|
+
readonly requireHostedDomain?: boolean;
|
|
26
|
+
readonly createAccounts?: boolean;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The person at the provider's sign-in screen. */
|
|
30
|
+
export interface FakeOidcUser {
|
|
31
|
+
readonly subject: string;
|
|
32
|
+
readonly email: string;
|
|
33
|
+
/** Default true. */
|
|
34
|
+
readonly emailVerified?: boolean;
|
|
35
|
+
/** Google's Workspace domain claim. */
|
|
36
|
+
readonly hostedDomain?: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface FakeSignInOptions {
|
|
40
|
+
/** The person refuses consent: the callback carries `error=access_denied`. */
|
|
41
|
+
readonly deny?: boolean;
|
|
42
|
+
/** Claims that replace or add to the ID token's own (`aud`, `nonce`, `exp`, …); `undefined` removes one. */
|
|
43
|
+
readonly claims?: Readonly<Record<string, unknown>>;
|
|
44
|
+
/** Signs with a key outside the JWKS, or sends an unsigned token (`alg: none`). */
|
|
45
|
+
readonly signWith?: "unknown-key" | "none";
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** A failure the next calls to the provider answer with, in order. */
|
|
49
|
+
export type FakeOidcFailure = "unavailable" | "invalid_grant" | "no_id_token";
|
|
50
|
+
|
|
51
|
+
export interface FakeOidcProvider {
|
|
52
|
+
/** The provider entry for `auth({ oidc: { providers: [fake.definition] } })`. */
|
|
53
|
+
readonly definition: OidcProviderInput;
|
|
54
|
+
/** The environment the definition reads its client id and secret from. */
|
|
55
|
+
readonly env: Readonly<Record<string, string>>;
|
|
56
|
+
/** The `fetch` for `auth({ oidc: { fetch } })`. */
|
|
57
|
+
readonly fetch: FetchFunction;
|
|
58
|
+
/** Checks the authorize URL as a provider does and answers the callback URL it redirects the browser to. */
|
|
59
|
+
signIn(authorizeUrl: string, user: FakeOidcUser, options?: FakeSignInOptions): URL;
|
|
60
|
+
/** A new signing key replaces the current one in the JWKS (the provider rotated its keys). */
|
|
61
|
+
rotateKeys(): void;
|
|
62
|
+
/** The next calls to the token endpoint fail like this, one per entry. */
|
|
63
|
+
failNext(...failures: FakeOidcFailure[]): void;
|
|
64
|
+
/** Overrides fields of the discovery document (`{ token_endpoint: "http://…" }`). */
|
|
65
|
+
setDiscovery(overrides: Readonly<Record<string, unknown>>): void;
|
|
66
|
+
/** What the provider saw. */
|
|
67
|
+
readonly calls: { readonly discovery: number; readonly jwks: number; readonly token: number; readonly lastForm: URLSearchParams | null };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
interface PendingCode {
|
|
71
|
+
readonly redirectUri: string;
|
|
72
|
+
readonly challenge: string;
|
|
73
|
+
readonly nonce: string | null;
|
|
74
|
+
readonly user: FakeOidcUser;
|
|
75
|
+
readonly options: FakeSignInOptions;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
interface SigningKeyPair {
|
|
79
|
+
readonly kid: string;
|
|
80
|
+
readonly privateKey: KeyObject;
|
|
81
|
+
readonly publicKey: KeyObject;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const random = () => randomBytes(24).toString("base64url");
|
|
85
|
+
const encode = (value: unknown) => Buffer.from(JSON.stringify(value), "utf8").toString("base64url");
|
|
86
|
+
|
|
87
|
+
export function createFakeOidcProvider(options: FakeOidcProviderOptions = {}): FakeOidcProvider {
|
|
88
|
+
const id = options.id ?? "fake";
|
|
89
|
+
const issuer = options.issuer ?? "https://fake-oidc.test";
|
|
90
|
+
const clientId = options.clientId ?? "fake-client";
|
|
91
|
+
const clientSecret = options.clientSecret ?? "fake-client-secret";
|
|
92
|
+
const algorithm = options.algorithm ?? "RS256";
|
|
93
|
+
const clock = options.clock ?? systemClock;
|
|
94
|
+
const envPrefix = `${id.toUpperCase().replaceAll("-", "_")}_OIDC`;
|
|
95
|
+
const urls = { discovery: `${issuer}/.well-known/openid-configuration`, jwks: `${issuer}/jwks`, token: `${issuer}/token`, authorize: `${issuer}/authorize` };
|
|
96
|
+
|
|
97
|
+
const createKey = (): SigningKeyPair => {
|
|
98
|
+
const pair = algorithm === "RS256" ? generateKeyPairSync("rsa", { modulusLength: 2048 }) : generateKeyPairSync("ec", { namedCurve: "P-256" });
|
|
99
|
+
return { kid: random(), ...pair };
|
|
100
|
+
};
|
|
101
|
+
let key = createKey();
|
|
102
|
+
const strangerKey = createKey();
|
|
103
|
+
const codes = new Map<string, PendingCode>();
|
|
104
|
+
const failures: FakeOidcFailure[] = [];
|
|
105
|
+
let discoveryOverrides: Readonly<Record<string, unknown>> = {};
|
|
106
|
+
const calls = { discovery: 0, jwks: 0, token: 0, lastForm: null as URLSearchParams | null };
|
|
107
|
+
|
|
108
|
+
const json = (status: number, body: unknown) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
109
|
+
|
|
110
|
+
function signToken(claims: Record<string, unknown>, signWith: FakeSignInOptions["signWith"]): string {
|
|
111
|
+
if (signWith === "none") return `${encode({ alg: "none", typ: "JWT" })}.${encode(claims)}.`;
|
|
112
|
+
const signer = signWith === "unknown-key" ? strangerKey : key;
|
|
113
|
+
const input = `${encode({ alg: algorithm, typ: "JWT", kid: signer.kid })}.${encode(claims)}`;
|
|
114
|
+
const signature =
|
|
115
|
+
algorithm === "RS256"
|
|
116
|
+
? sign("sha256", Buffer.from(input), signer.privateKey)
|
|
117
|
+
: sign("sha256", Buffer.from(input), { key: signer.privateKey, dsaEncoding: "ieee-p1363" });
|
|
118
|
+
return `${input}.${signature.toString("base64url")}`;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function buildClaims(pending: PendingCode): Record<string, unknown> {
|
|
122
|
+
const now = Math.floor(clock.now().getTime() / 1000);
|
|
123
|
+
const claims: Record<string, unknown> = {
|
|
124
|
+
iss: issuer,
|
|
125
|
+
sub: pending.user.subject,
|
|
126
|
+
aud: clientId,
|
|
127
|
+
iat: now,
|
|
128
|
+
exp: now + 3600,
|
|
129
|
+
email: pending.user.email,
|
|
130
|
+
email_verified: pending.user.emailVerified ?? true,
|
|
131
|
+
};
|
|
132
|
+
if (pending.nonce !== null) claims.nonce = pending.nonce;
|
|
133
|
+
if (pending.user.hostedDomain !== undefined) claims.hd = pending.user.hostedDomain;
|
|
134
|
+
for (const [name, value] of Object.entries(pending.options.claims ?? {})) {
|
|
135
|
+
if (value === undefined) delete claims[name];
|
|
136
|
+
else claims[name] = value;
|
|
137
|
+
}
|
|
138
|
+
return claims;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function readClient(form: URLSearchParams, authorization: string | null): { id: string | null; secret: string | null } {
|
|
142
|
+
if (authorization?.startsWith("Basic ") === true) {
|
|
143
|
+
const [user, password] = Buffer.from(authorization.slice(6), "base64").toString("utf8").split(":");
|
|
144
|
+
return { id: user === undefined ? null : decodeURIComponent(user), secret: password === undefined ? null : decodeURIComponent(password) };
|
|
145
|
+
}
|
|
146
|
+
return { id: form.get("client_id"), secret: form.get("client_secret") };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function answerToken(init: RequestInit): Response {
|
|
150
|
+
calls.token += 1;
|
|
151
|
+
const form = new URLSearchParams(init.body instanceof URLSearchParams ? init.body : typeof init.body === "string" ? init.body : "");
|
|
152
|
+
calls.lastForm = form;
|
|
153
|
+
const failure = failures.shift();
|
|
154
|
+
if (failure === "unavailable") return json(503, { error: "temporarily_unavailable" });
|
|
155
|
+
if (failure === "invalid_grant") return json(400, { error: "invalid_grant" });
|
|
156
|
+
const client = readClient(form, new Headers(init.headers).get("authorization"));
|
|
157
|
+
if (client.id !== clientId || client.secret !== clientSecret) return json(401, { error: "invalid_client" });
|
|
158
|
+
if (form.get("grant_type") !== "authorization_code") return json(400, { error: "unsupported_grant_type" });
|
|
159
|
+
const code = form.get("code") ?? "";
|
|
160
|
+
const pending = codes.get(code);
|
|
161
|
+
codes.delete(code);
|
|
162
|
+
if (pending === undefined || form.get("redirect_uri") !== pending.redirectUri) return json(400, { error: "invalid_grant" });
|
|
163
|
+
const verifier = form.get("code_verifier") ?? "";
|
|
164
|
+
if (createHash("sha256").update(verifier, "ascii").digest("base64url") !== pending.challenge) return json(400, { error: "invalid_grant" });
|
|
165
|
+
if (failure === "no_id_token") return json(200, { access_token: random(), token_type: "Bearer" });
|
|
166
|
+
return json(200, {
|
|
167
|
+
access_token: random(),
|
|
168
|
+
token_type: "Bearer",
|
|
169
|
+
expires_in: 3600,
|
|
170
|
+
id_token: signToken(buildClaims(pending), pending.options.signWith),
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const fetchFake: FetchFunction = (input, init) => Promise.resolve(route(input, init));
|
|
175
|
+
|
|
176
|
+
function route(input: string | URL, init: RequestInit): Response {
|
|
177
|
+
const url = new URL(typeof input === "string" ? input : input.toString());
|
|
178
|
+
const target = `${url.origin}${url.pathname}`;
|
|
179
|
+
if (target === urls.discovery) {
|
|
180
|
+
calls.discovery += 1;
|
|
181
|
+
return json(200, {
|
|
182
|
+
issuer,
|
|
183
|
+
authorization_endpoint: urls.authorize,
|
|
184
|
+
token_endpoint: urls.token,
|
|
185
|
+
jwks_uri: urls.jwks,
|
|
186
|
+
response_types_supported: ["code"],
|
|
187
|
+
id_token_signing_alg_values_supported: [algorithm],
|
|
188
|
+
...discoveryOverrides,
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
if (target === urls.jwks) {
|
|
192
|
+
calls.jwks += 1;
|
|
193
|
+
return json(200, { keys: [{ ...key.publicKey.export({ format: "jwk" }), kid: key.kid, use: "sig", alg: algorithm }] });
|
|
194
|
+
}
|
|
195
|
+
if (target === urls.token && init.method === "POST") return answerToken(init);
|
|
196
|
+
return json(404, { error: "not_found" });
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
return {
|
|
200
|
+
definition: {
|
|
201
|
+
id,
|
|
202
|
+
name: "Fake",
|
|
203
|
+
issuer,
|
|
204
|
+
clientIdEnv: `${envPrefix}_CLIENT_ID`,
|
|
205
|
+
clientSecretEnv: `${envPrefix}_CLIENT_SECRET`,
|
|
206
|
+
clientAuth: options.clientAuth ?? "body",
|
|
207
|
+
allowedDomains: [...(options.allowedDomains ?? (options.allowedEmails === undefined ? ["example.com"] : []))],
|
|
208
|
+
allowedEmails: [...(options.allowedEmails ?? [])],
|
|
209
|
+
requireHostedDomain: options.requireHostedDomain,
|
|
210
|
+
createAccounts: options.createAccounts,
|
|
211
|
+
},
|
|
212
|
+
env: { [`${envPrefix}_CLIENT_ID`]: clientId, [`${envPrefix}_CLIENT_SECRET`]: clientSecret },
|
|
213
|
+
fetch: fetchFake,
|
|
214
|
+
signIn(authorizeUrl, user, signInOptions = {}) {
|
|
215
|
+
const url = new URL(authorizeUrl);
|
|
216
|
+
const query = url.searchParams;
|
|
217
|
+
if (`${url.origin}${url.pathname}` !== urls.authorize) throw new Error(`fake OIDC provider: authorize URL ${url.origin}${url.pathname} is not ${urls.authorize}`);
|
|
218
|
+
if (query.get("client_id") !== clientId) throw new Error("fake OIDC provider: unknown client_id");
|
|
219
|
+
if (query.get("response_type") !== "code") throw new Error("fake OIDC provider: response_type must be code");
|
|
220
|
+
if (!(query.get("scope") ?? "").split(" ").includes("openid")) throw new Error("fake OIDC provider: scope lacks openid");
|
|
221
|
+
if (query.get("code_challenge_method") !== "S256") throw new Error("fake OIDC provider: PKCE S256 is required");
|
|
222
|
+
const redirectUri = query.get("redirect_uri");
|
|
223
|
+
const state = query.get("state");
|
|
224
|
+
const challenge = query.get("code_challenge");
|
|
225
|
+
if (redirectUri === null || state === null || challenge === null) throw new Error("fake OIDC provider: redirect_uri, state and code_challenge are required");
|
|
226
|
+
const callback = new URL(redirectUri);
|
|
227
|
+
callback.searchParams.set("state", state);
|
|
228
|
+
if (signInOptions.deny === true) {
|
|
229
|
+
callback.searchParams.set("error", "access_denied");
|
|
230
|
+
return callback;
|
|
231
|
+
}
|
|
232
|
+
const code = random();
|
|
233
|
+
codes.set(code, { redirectUri, challenge, nonce: query.get("nonce"), user, options: signInOptions });
|
|
234
|
+
callback.searchParams.set("code", code);
|
|
235
|
+
return callback;
|
|
236
|
+
},
|
|
237
|
+
rotateKeys() {
|
|
238
|
+
key = createKey();
|
|
239
|
+
},
|
|
240
|
+
failNext(...next) {
|
|
241
|
+
failures.push(...next);
|
|
242
|
+
},
|
|
243
|
+
setDiscovery(overrides) {
|
|
244
|
+
discoveryOverrides = overrides;
|
|
245
|
+
},
|
|
246
|
+
calls,
|
|
247
|
+
};
|
|
248
|
+
}
|
package/src/ui/auth-forms.tsx
CHANGED
|
@@ -158,8 +158,16 @@ function FormShell({
|
|
|
158
158
|
<form action={formAction} className={slot("form")}>
|
|
159
159
|
{children}
|
|
160
160
|
<FormError message={formError} unstyled={unstyled} />
|
|
161
|
-
<Button
|
|
162
|
-
|
|
161
|
+
<Button
|
|
162
|
+
type="submit"
|
|
163
|
+
variant={submitVariant}
|
|
164
|
+
fullWidth
|
|
165
|
+
pending={isPending}
|
|
166
|
+
pendingLabel={pendingLabel}
|
|
167
|
+
classNames={{ root: slot("submit") }}
|
|
168
|
+
unstyled={unstyled}
|
|
169
|
+
>
|
|
170
|
+
{submitLabel}
|
|
163
171
|
</Button>
|
|
164
172
|
</form>
|
|
165
173
|
{footer}
|
package/src/ui/index.ts
CHANGED