@softure-ai/auth 0.2.7 → 0.2.9
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 +36 -2
- package/README.md +62 -2
- package/dist/index.d.ts +44 -9
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/options.d.ts +124 -13
- package/dist/options.d.ts.map +1 -1
- package/dist/options.js +48 -15
- package/dist/options.js.map +1 -1
- package/dist/server/oidc/allowlist.d.ts +10 -0
- package/dist/server/oidc/allowlist.d.ts.map +1 -0
- package/dist/server/oidc/allowlist.js +23 -0
- package/dist/server/oidc/allowlist.js.map +1 -0
- package/dist/server/oidc/discovery.d.ts +2 -2
- package/dist/server/oidc/discovery.d.ts.map +1 -1
- package/dist/server/oidc/discovery.js.map +1 -1
- package/dist/server/oidc/flow.d.ts +0 -7
- package/dist/server/oidc/flow.d.ts.map +1 -1
- package/dist/server/oidc/flow.js +50 -49
- package/dist/server/oidc/flow.js.map +1 -1
- package/dist/server/oidc/github.d.ts +33 -0
- package/dist/server/oidc/github.d.ts.map +1 -0
- package/dist/server/oidc/github.js +92 -0
- package/dist/server/oidc/github.js.map +1 -0
- package/dist/server/oidc/index.d.ts +2 -1
- package/dist/server/oidc/index.d.ts.map +1 -1
- package/dist/server/oidc/index.js +3 -2
- package/dist/server/oidc/index.js.map +1 -1
- package/dist/server/oidc/token-request.d.ts +2 -2
- package/dist/server/oidc/token-request.d.ts.map +1 -1
- package/dist/testing/github-provider.d.ts +58 -0
- package/dist/testing/github-provider.d.ts.map +1 -0
- package/dist/testing/github-provider.js +139 -0
- package/dist/testing/github-provider.js.map +1 -0
- package/dist/testing/index.d.ts +1 -0
- package/dist/testing/index.d.ts.map +1 -1
- package/dist/testing/index.js +2 -1
- package/dist/testing/index.js.map +1 -1
- package/dist/testing/oidc-provider.d.ts +2 -2
- package/dist/testing/oidc-provider.d.ts.map +1 -1
- package/module.json +1 -1
- package/package.json +1 -1
- package/src/index.ts +7 -2
- package/src/options.ts +80 -36
- package/src/server/oidc/allowlist.ts +23 -0
- package/src/server/oidc/discovery.ts +2 -2
- package/src/server/oidc/flow.ts +63 -47
- package/src/server/oidc/github.ts +112 -0
- package/src/server/oidc/index.ts +2 -2
- package/src/server/oidc/token-request.ts +2 -2
- package/src/testing/github-provider.ts +202 -0
- package/src/testing/index.ts +10 -1
- package/src/testing/oidc-provider.ts +2 -2
package/src/server/oidc/flow.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
//
|
|
1
|
+
// Sign-in through a provider: the authorization code flow with PKCE S256 (RFC 7636), a one-time state and, for
|
|
2
|
+
// OpenID Connect, a nonce. A GitHub provider (an OAuth App) shares everything but the protocol step (`github.ts`).
|
|
2
3
|
// `startOidcSignIn` stores the sign-in (the state's sha256, the nonce, the verifier, the return path) and answers
|
|
3
4
|
// the provider's authorize URL and the state, which the adapter keeps in a short-lived cookie: the callback must come
|
|
4
5
|
// back to the browser that started it (no login CSRF). `completeOidcSignIn` consumes the row, exchanges the code,
|
|
@@ -10,16 +11,18 @@ import type { RateLimitRejection } from "@softure-ai/security";
|
|
|
10
11
|
import { consumeRateLimit } from "@softure-ai/security/server";
|
|
11
12
|
import { and, eq, gt, lte } from "drizzle-orm";
|
|
12
13
|
import type { OidcSignInErrorCode, SignedIn } from "../../contract.js";
|
|
13
|
-
import type { OidcProvider } from "../../options.js";
|
|
14
|
+
import type { OidcProvider, OpenIdConnectProvider } from "../../options.js";
|
|
14
15
|
import { toSafeNextPath } from "../../safe-next-path.js";
|
|
15
16
|
import { oidcStates } from "../../schema.js";
|
|
16
17
|
import { getAuthOptions, getAuthRoutes } from "../options.js";
|
|
17
18
|
import { assertAuthBuckets, BUCKETS } from "../rate-limits.js";
|
|
18
19
|
import { createSession, deleteExpiredSessions } from "../sessions.js";
|
|
19
|
-
import { resolveOidcAccount } from "./accounts.js";
|
|
20
|
-
import {
|
|
20
|
+
import { resolveOidcAccount, type OidcIdentity } from "./accounts.js";
|
|
21
|
+
import { getAllowedEmail } from "./allowlist.js";
|
|
22
|
+
import { findOidcProvider, getOidcRedirectUri, passed, readOidcClient, refused, type Checked, type OidcClient, type OidcContext } from "./context.js";
|
|
21
23
|
import { findSigningKey, getProviderMetadata } from "./discovery.js";
|
|
22
|
-
import {
|
|
24
|
+
import { GITHUB_AUTHORIZE_URL, GITHUB_SCOPES, readGithubIdentity } from "./github.js";
|
|
25
|
+
import { checkIdTokenClaims, decodeIdToken, isSignedBy } from "./id-token.js";
|
|
23
26
|
import { exchangeCode } from "./token-request.js";
|
|
24
27
|
|
|
25
28
|
const RANDOM_BYTES = 32;
|
|
@@ -55,12 +58,17 @@ export async function startOidcSignIn(ctx: OidcContext, input: StartOidcSignInIn
|
|
|
55
58
|
if (provider === undefined) return err("auth.oidc_failed");
|
|
56
59
|
const client = readOidcClient(ctx, provider);
|
|
57
60
|
if (!client.ok) return fail(provider, client.reason);
|
|
58
|
-
|
|
59
|
-
if (
|
|
61
|
+
let authorizationEndpoint = GITHUB_AUTHORIZE_URL;
|
|
62
|
+
if (provider.type === "oidc") {
|
|
63
|
+
const metadata = await getProviderMetadata(ctx, provider);
|
|
64
|
+
if (!metadata.ok) return fail(provider, metadata.reason);
|
|
65
|
+
authorizationEndpoint = metadata.value.authorizationEndpoint;
|
|
66
|
+
}
|
|
60
67
|
|
|
61
68
|
const now = ctx.clock.now();
|
|
62
69
|
const ttlMinutes = getAuthOptions(ctx.config).oidc.stateTtlMinutes;
|
|
63
70
|
const state = createRandomValue();
|
|
71
|
+
// GitHub takes no nonce; the row keeps one anyway (the column is required) and nothing reads it.
|
|
64
72
|
const nonce = createRandomValue();
|
|
65
73
|
const codeVerifier = createRandomValue();
|
|
66
74
|
await ctx.db.delete(oidcStates).where(lte(oidcStates.expiresAt, now));
|
|
@@ -74,14 +82,14 @@ export async function startOidcSignIn(ctx: OidcContext, input: StartOidcSignInIn
|
|
|
74
82
|
expiresAt: new Date(now.getTime() + ttlMinutes * 60_000),
|
|
75
83
|
});
|
|
76
84
|
|
|
77
|
-
const url = new URL(
|
|
85
|
+
const url = new URL(authorizationEndpoint);
|
|
78
86
|
for (const [name, value] of Object.entries(provider.authorizeParams)) url.searchParams.set(name, value);
|
|
79
87
|
url.searchParams.set("response_type", "code");
|
|
80
88
|
url.searchParams.set("client_id", client.value.clientId);
|
|
81
89
|
url.searchParams.set("redirect_uri", getOidcRedirectUri(ctx.config, provider.id));
|
|
82
|
-
url.searchParams.set("scope", [...new Set([...REQUIRED_SCOPES, ...provider.scopes])].join(" "));
|
|
90
|
+
url.searchParams.set("scope", provider.type === "github" ? GITHUB_SCOPES : [...new Set([...REQUIRED_SCOPES, ...provider.scopes])].join(" "));
|
|
83
91
|
url.searchParams.set("state", state);
|
|
84
|
-
url.searchParams.set("nonce", nonce);
|
|
92
|
+
if (provider.type === "oidc") url.searchParams.set("nonce", nonce);
|
|
85
93
|
url.searchParams.set("code_challenge", createHash("sha256").update(codeVerifier, "ascii").digest("base64url"));
|
|
86
94
|
url.searchParams.set("code_challenge_method", "S256");
|
|
87
95
|
return ok({ url: url.toString(), state, maxAgeSeconds: ttlMinutes * 60 });
|
|
@@ -128,29 +136,16 @@ export async function completeOidcSignIn(ctx: OidcContext, input: CompleteOidcSi
|
|
|
128
136
|
|
|
129
137
|
const client = readOidcClient(ctx, provider);
|
|
130
138
|
if (!client.ok) return fail(provider, client.reason);
|
|
131
|
-
const
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
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);
|
|
139
|
+
const exchange = { client: client.value, code, codeVerifier: pending.codeVerifier, redirectUri: getOidcRedirectUri(ctx.config, provider.id) };
|
|
140
|
+
const identity =
|
|
141
|
+
provider.type === "github"
|
|
142
|
+
? await readGithubIdentity(ctx, { ...exchange, provider })
|
|
143
|
+
: await readOpenIdConnectIdentity(ctx, { ...exchange, provider, nonce: pending.nonce, now });
|
|
144
|
+
if (!identity.ok) return fail(provider, identity.reason);
|
|
145
|
+
|
|
146
|
+
const { email } = identity.value;
|
|
152
147
|
if (email === null) return err("auth.oidc_not_allowed");
|
|
153
|
-
const account = await resolveOidcAccount(ctx, provider, { subject:
|
|
148
|
+
const account = await resolveOidcAccount(ctx, provider, { subject: identity.value.subject, email, displayName: identity.value.displayName });
|
|
154
149
|
if (!account.ok) return account;
|
|
155
150
|
|
|
156
151
|
await deleteExpiredSessions(ctx, account.value.id);
|
|
@@ -158,25 +153,46 @@ export async function completeOidcSignIn(ctx: OidcContext, input: CompleteOidcSi
|
|
|
158
153
|
return ok({ user: account.value, session, next: toSafeNextPath(pending.nextPath, getAuthRoutes(ctx.config).afterLogin) });
|
|
159
154
|
}
|
|
160
155
|
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
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;
|
|
156
|
+
interface OpenIdConnectExchange {
|
|
157
|
+
readonly provider: OpenIdConnectProvider;
|
|
158
|
+
readonly client: OidcClient;
|
|
159
|
+
readonly code: string;
|
|
160
|
+
readonly codeVerifier: string;
|
|
161
|
+
readonly redirectUri: string;
|
|
162
|
+
readonly nonce: string;
|
|
163
|
+
readonly now: Date;
|
|
175
164
|
}
|
|
176
165
|
|
|
166
|
+
/** The OpenID Connect step: exchange the code, verify the ID token, apply the allowlist (email null when refused). */
|
|
167
|
+
async function readOpenIdConnectIdentity(ctx: OidcContext, input: OpenIdConnectExchange): Promise<Checked<NullableEmail<OidcIdentity>>> {
|
|
168
|
+
const { provider, client } = input;
|
|
169
|
+
const metadata = await getProviderMetadata(ctx, provider);
|
|
170
|
+
if (!metadata.ok) return metadata;
|
|
171
|
+
const exchanged = await exchangeCode(ctx, {
|
|
172
|
+
provider,
|
|
173
|
+
client,
|
|
174
|
+
tokenEndpoint: metadata.value.tokenEndpoint,
|
|
175
|
+
code: input.code,
|
|
176
|
+
codeVerifier: input.codeVerifier,
|
|
177
|
+
redirectUri: input.redirectUri,
|
|
178
|
+
});
|
|
179
|
+
if (!exchanged.ok) return exchanged;
|
|
180
|
+
const token = decodeIdToken(exchanged.value);
|
|
181
|
+
if (!token.ok) return token;
|
|
182
|
+
const key = await findSigningKey(ctx, metadata.value, { kid: token.value.kid, keyType: token.value.keyType });
|
|
183
|
+
if (!key.ok) return key;
|
|
184
|
+
if (!isSignedBy(token.value, key.value)) return refused("id_token signature");
|
|
185
|
+
const claims = checkIdTokenClaims(token.value.payload, { issuer: provider.issuer, clientId: client.clientId, nonce: input.nonce, now: input.now });
|
|
186
|
+
if (!claims.ok) return claims;
|
|
187
|
+
return passed({ subject: claims.value.subject, email: getAllowedEmail(provider, claims.value), displayName: claims.value.displayName });
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
type NullableEmail<T extends { readonly email: string }> = Omit<T, "email"> & { readonly email: string | null };
|
|
191
|
+
|
|
177
192
|
function fail(provider: OidcProvider, reason: string): Err<"auth.oidc_failed"> {
|
|
178
193
|
// The reason is this module's own wording: never a value from the provider or the browser.
|
|
179
|
-
|
|
194
|
+
const kind = provider.type === "github" ? "GitHub" : "OpenID Connect";
|
|
195
|
+
console.warn(`@softure-ai/auth: ${kind} sign-in with ${provider.id} failed: ${reason}`);
|
|
180
196
|
return err("auth.oidc_failed");
|
|
181
197
|
}
|
|
182
198
|
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// The protocol step of a GitHub sign-in (an OAuth App, not OpenID Connect): the code is exchanged at GitHub's fixed
|
|
2
|
+
// token endpoint, and the account is read from GitHub's API with the access token, which lives only in this call.
|
|
3
|
+
// Every request goes through core's `requestJson`, which follows no redirect, so neither the client secret nor the
|
|
4
|
+
// token reaches another host. Only verified emails count, the primary one first.
|
|
5
|
+
import { requestJson } from "@softure-ai/core";
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
import type { GithubProvider } from "../../options.js";
|
|
8
|
+
import { getAuthOptions } from "../options.js";
|
|
9
|
+
import { isAllowedEmail } from "./allowlist.js";
|
|
10
|
+
import { passed, refused, type Checked, type OidcClient, type OidcContext } from "./context.js";
|
|
11
|
+
import { toDisplayName } from "./id-token.js";
|
|
12
|
+
|
|
13
|
+
export const GITHUB_AUTHORIZE_URL = "https://github.com/login/oauth/authorize";
|
|
14
|
+
export const GITHUB_TOKEN_URL = "https://github.com/login/oauth/access_token";
|
|
15
|
+
export const GITHUB_USER_URL = "https://api.github.com/user";
|
|
16
|
+
export const GITHUB_EMAILS_URL = "https://api.github.com/user/emails";
|
|
17
|
+
/** The profile (id, login, name) and the account's emails, verified flag included; nothing else. */
|
|
18
|
+
export const GITHUB_SCOPES = "read:user user:email";
|
|
19
|
+
|
|
20
|
+
// GitHub answers an OAuth error with status 200, so the error is read from a successful body too.
|
|
21
|
+
const tokenBodySchema = z.object({
|
|
22
|
+
access_token: z.string().min(1).max(4096).optional(),
|
|
23
|
+
error: z.string().regex(/^[a-z_]{1,64}$/).optional(),
|
|
24
|
+
});
|
|
25
|
+
const errorBodySchema = z.object({ error: z.string().regex(/^[a-z_]{1,64}$/) });
|
|
26
|
+
const userSchema = z.object({
|
|
27
|
+
id: z.number().int().positive(),
|
|
28
|
+
login: z.string().max(100),
|
|
29
|
+
name: z.string().nullable().optional(),
|
|
30
|
+
});
|
|
31
|
+
const emailsSchema = z.array(z.object({ email: z.string().max(320), primary: z.boolean(), verified: z.boolean() })).max(100);
|
|
32
|
+
|
|
33
|
+
export interface GithubSignIn {
|
|
34
|
+
readonly provider: GithubProvider;
|
|
35
|
+
readonly client: OidcClient;
|
|
36
|
+
readonly code: string;
|
|
37
|
+
readonly codeVerifier: string;
|
|
38
|
+
readonly redirectUri: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** What a GitHub sign-in says about the person. */
|
|
42
|
+
export interface GithubIdentity {
|
|
43
|
+
/** The account's numeric id, as text: it survives a renamed login. */
|
|
44
|
+
readonly subject: string;
|
|
45
|
+
/** The first verified email the allowlist accepts, primary first; null when none does. */
|
|
46
|
+
readonly email: string | null;
|
|
47
|
+
/** `name`, else `login`, normalized. */
|
|
48
|
+
readonly displayName: string | null;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The identity behind `code`, or the reason (for the log) it could not be read. */
|
|
52
|
+
export async function readGithubIdentity(ctx: OidcContext, input: GithubSignIn): Promise<Checked<GithubIdentity>> {
|
|
53
|
+
const token = await exchangeGithubCode(ctx, input);
|
|
54
|
+
if (!token.ok) return token;
|
|
55
|
+
const headers = {
|
|
56
|
+
authorization: `Bearer ${token.value}`,
|
|
57
|
+
accept: "application/vnd.github+json",
|
|
58
|
+
"x-github-api-version": "2022-11-28",
|
|
59
|
+
"user-agent": "softure-ai-auth",
|
|
60
|
+
};
|
|
61
|
+
const user = await requestJson({ url: GITHUB_USER_URL, headers, schema: userSchema, ...requestOptions(ctx) });
|
|
62
|
+
if (!user.ok) return refused(`user ${user.error}`);
|
|
63
|
+
const emails = await requestJson({ url: GITHUB_EMAILS_URL, headers, schema: emailsSchema, ...requestOptions(ctx) });
|
|
64
|
+
if (!emails.ok) return refused(`emails ${emails.error}`);
|
|
65
|
+
return passed({
|
|
66
|
+
subject: String(user.value.id),
|
|
67
|
+
email: pickGithubEmail(input.provider, emails.value),
|
|
68
|
+
displayName: toDisplayName(user.value.name) ?? toDisplayName(user.value.login),
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The first verified email, primary first, that the provider's allowlist accepts; null when none does. */
|
|
73
|
+
export function pickGithubEmail(
|
|
74
|
+
provider: GithubProvider,
|
|
75
|
+
emails: readonly { readonly email: string; readonly primary: boolean; readonly verified: boolean }[],
|
|
76
|
+
): string | null {
|
|
77
|
+
const verified = emails.filter((entry) => entry.verified).sort((a, b) => Number(b.primary) - Number(a.primary));
|
|
78
|
+
for (const entry of verified) {
|
|
79
|
+
const email = entry.email.trim().toLowerCase();
|
|
80
|
+
if (isAllowedEmail(provider, email, null)) return email;
|
|
81
|
+
}
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async function exchangeGithubCode(ctx: OidcContext, input: GithubSignIn): Promise<Checked<string>> {
|
|
86
|
+
const form = new URLSearchParams({
|
|
87
|
+
client_id: input.client.clientId,
|
|
88
|
+
client_secret: input.client.clientSecret ?? "",
|
|
89
|
+
code: input.code,
|
|
90
|
+
redirect_uri: input.redirectUri,
|
|
91
|
+
code_verifier: input.codeVerifier,
|
|
92
|
+
});
|
|
93
|
+
const answer = await requestJson({
|
|
94
|
+
url: GITHUB_TOKEN_URL,
|
|
95
|
+
method: "POST",
|
|
96
|
+
form,
|
|
97
|
+
// Without it GitHub answers form-encoded.
|
|
98
|
+
headers: { accept: "application/json", "user-agent": "softure-ai-auth" },
|
|
99
|
+
schema: tokenBodySchema,
|
|
100
|
+
errorSchema: errorBodySchema,
|
|
101
|
+
...requestOptions(ctx),
|
|
102
|
+
});
|
|
103
|
+
if (!answer.ok) return refused(`token ${answer.errorBody?.error ?? answer.error}`);
|
|
104
|
+
if (answer.value === undefined) return refused("token empty_answer");
|
|
105
|
+
if (answer.value.error !== undefined) return refused(`token ${answer.value.error}`);
|
|
106
|
+
return answer.value.access_token === undefined ? refused("token no_access_token") : passed(answer.value.access_token);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function requestOptions(ctx: OidcContext) {
|
|
110
|
+
const options = getAuthOptions(ctx.config).oidc;
|
|
111
|
+
return { fetch: options.fetch, timeoutMs: options.httpTimeoutMs, clock: ctx.clock };
|
|
112
|
+
}
|
package/src/server/oidc/index.ts
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
//
|
|
1
|
+
// Sign-in through a provider (`auth({ oidc })`, OpenID Connect or GitHub): the flow, its context and the allowlist.
|
|
2
2
|
export { findOidcProvider, getOidcCallbackPath, getOidcProviders, getOidcRedirectUri, type OidcContext } from "./context.js";
|
|
3
3
|
export {
|
|
4
4
|
completeOidcSignIn,
|
|
5
|
-
getAllowedEmail,
|
|
6
5
|
startOidcSignIn,
|
|
7
6
|
type CompleteOidcSignInInput,
|
|
8
7
|
type CompleteOidcSignInResult,
|
|
@@ -11,4 +10,5 @@ export {
|
|
|
11
10
|
type StartOidcSignInInput,
|
|
12
11
|
type StartOidcSignInResult,
|
|
13
12
|
} from "./flow.js";
|
|
13
|
+
export { getAllowedEmail } from "./allowlist.js";
|
|
14
14
|
export type { IdentityClaims } from "./id-token.js";
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// another host. Only the ID token is read; the access token is not kept.
|
|
4
4
|
import { requestJson } from "@softure-ai/core";
|
|
5
5
|
import { z } from "zod";
|
|
6
|
-
import type {
|
|
6
|
+
import type { OpenIdConnectProvider } from "../../options.js";
|
|
7
7
|
import { getAuthOptions } from "../options.js";
|
|
8
8
|
import { passed, refused, type Checked, type OidcClient, type OidcContext } from "./context.js";
|
|
9
9
|
|
|
@@ -13,7 +13,7 @@ const errorBodySchema = z.object({ error: z.string().regex(/^[a-z_]{1,64}$/) });
|
|
|
13
13
|
|
|
14
14
|
|
|
15
15
|
export interface TokenExchangeInput {
|
|
16
|
-
readonly provider:
|
|
16
|
+
readonly provider: OpenIdConnectProvider;
|
|
17
17
|
readonly client: OidcClient;
|
|
18
18
|
readonly tokenEndpoint: string;
|
|
19
19
|
readonly code: string;
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
// An in-memory GitHub (an OAuth App) for tests: authorize (`signIn`), the token endpoint and the two API reads the
|
|
2
|
+
// sign-in makes (`/user`, `/user/emails`), reached through a `fetch` the app's `auth({ oidc: { fetch } })` takes. It
|
|
3
|
+
// checks what GitHub checks (client credentials, redirect URI, PKCE verifier, one-time codes, the bearer token) and
|
|
4
|
+
// answers like GitHub: an OAuth error with status 200, a form-encoded body without `Accept: application/json`.
|
|
5
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
6
|
+
import type { FetchFunction } from "@softure-ai/core";
|
|
7
|
+
import type { GithubProviderInput } from "../options.js";
|
|
8
|
+
|
|
9
|
+
const AUTHORIZE_URL = "https://github.com/login/oauth/authorize";
|
|
10
|
+
const TOKEN_URL = "https://github.com/login/oauth/access_token";
|
|
11
|
+
const USER_URL = "https://api.github.com/user";
|
|
12
|
+
const EMAILS_URL = "https://api.github.com/user/emails";
|
|
13
|
+
|
|
14
|
+
export interface FakeGithubProviderOptions {
|
|
15
|
+
/** The provider id. Default `github`. */
|
|
16
|
+
readonly id?: string;
|
|
17
|
+
readonly clientId?: string;
|
|
18
|
+
readonly clientSecret?: string;
|
|
19
|
+
/** The allowlist of the definition. Default `allowedDomains: ["example.com"]`. */
|
|
20
|
+
readonly allowedDomains?: readonly string[];
|
|
21
|
+
readonly allowedEmails?: readonly string[];
|
|
22
|
+
readonly createAccounts?: boolean;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** One of the account's emails, as `/user/emails` lists it. */
|
|
26
|
+
export interface FakeGithubEmail {
|
|
27
|
+
readonly email: string;
|
|
28
|
+
/** Default true. */
|
|
29
|
+
readonly verified?: boolean;
|
|
30
|
+
/** Default: true for the first entry only. */
|
|
31
|
+
readonly primary?: boolean;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The person at GitHub's sign-in screen. */
|
|
35
|
+
export interface FakeGithubUser {
|
|
36
|
+
/** The numeric account id: the identity's subject. */
|
|
37
|
+
readonly id: number;
|
|
38
|
+
readonly login: string;
|
|
39
|
+
/** The profile name; null or absent when the profile has none. */
|
|
40
|
+
readonly name?: string | null;
|
|
41
|
+
readonly emails: readonly FakeGithubEmail[];
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface FakeGithubSignInOptions {
|
|
45
|
+
/** The person refuses the authorization: the callback carries `error=access_denied`. */
|
|
46
|
+
readonly deny?: boolean;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** A failure the next calls answer with, in order: the token endpoint for the first two, the API for the others. */
|
|
50
|
+
export type FakeGithubFailure = "unavailable" | "bad_verification_code" | "user_unavailable" | "emails_unavailable";
|
|
51
|
+
|
|
52
|
+
export interface FakeGithubProvider {
|
|
53
|
+
/** The provider entry for `auth({ oidc: { providers: [fake.definition] } })`. */
|
|
54
|
+
readonly definition: GithubProviderInput;
|
|
55
|
+
/** The environment the definition reads its client id and secret from. */
|
|
56
|
+
readonly env: Readonly<Record<string, string>>;
|
|
57
|
+
/** The `fetch` for `auth({ oidc: { fetch } })`. */
|
|
58
|
+
readonly fetch: FetchFunction;
|
|
59
|
+
/** Checks the authorize URL as GitHub does and answers the callback URL it redirects the browser to. */
|
|
60
|
+
signIn(authorizeUrl: string, user: FakeGithubUser, options?: FakeGithubSignInOptions): URL;
|
|
61
|
+
/** The next calls fail like this, one per entry. */
|
|
62
|
+
failNext(...failures: FakeGithubFailure[]): void;
|
|
63
|
+
/** What GitHub saw. */
|
|
64
|
+
readonly calls: {
|
|
65
|
+
readonly token: number;
|
|
66
|
+
readonly user: number;
|
|
67
|
+
readonly emails: number;
|
|
68
|
+
readonly lastForm: URLSearchParams | null;
|
|
69
|
+
/** The access tokens it issued, so a test can check none was stored. */
|
|
70
|
+
readonly issuedTokens: readonly string[];
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
interface PendingCode {
|
|
75
|
+
readonly redirectUri: string;
|
|
76
|
+
readonly challenge: string;
|
|
77
|
+
readonly user: FakeGithubUser;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const random = () => randomBytes(24).toString("base64url");
|
|
81
|
+
|
|
82
|
+
export function createFakeGithubProvider(options: FakeGithubProviderOptions = {}): FakeGithubProvider {
|
|
83
|
+
const id = options.id ?? "github";
|
|
84
|
+
const clientId = options.clientId ?? "fake-github-client";
|
|
85
|
+
const clientSecret = options.clientSecret ?? "fake-github-secret";
|
|
86
|
+
const envPrefix = `${id.toUpperCase().replaceAll("-", "_")}_AUTH`;
|
|
87
|
+
const codes = new Map<string, PendingCode>();
|
|
88
|
+
const tokens = new Map<string, FakeGithubUser>();
|
|
89
|
+
const failures: FakeGithubFailure[] = [];
|
|
90
|
+
const calls = { token: 0, user: 0, emails: 0, lastForm: null as URLSearchParams | null, issuedTokens: [] as string[] };
|
|
91
|
+
|
|
92
|
+
const json = (status: number, body: unknown) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json; charset=utf-8" } });
|
|
93
|
+
const takeFailure = (...kinds: FakeGithubFailure[]): FakeGithubFailure | undefined => {
|
|
94
|
+
const next = failures[0];
|
|
95
|
+
if (next === undefined || !kinds.includes(next)) return undefined;
|
|
96
|
+
return failures.shift();
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
function answerToken(init: RequestInit): Response {
|
|
100
|
+
calls.token += 1;
|
|
101
|
+
const form = new URLSearchParams(init.body instanceof URLSearchParams ? init.body : typeof init.body === "string" ? init.body : "");
|
|
102
|
+
calls.lastForm = form;
|
|
103
|
+
const headers = new Headers(init.headers);
|
|
104
|
+
const wantsJson = headers.get("accept")?.includes("application/json") === true;
|
|
105
|
+
const answer = (body: Record<string, string>) =>
|
|
106
|
+
wantsJson ? json(200, body) : new Response(new URLSearchParams(body).toString(), { status: 200, headers: { "content-type": "application/x-www-form-urlencoded" } });
|
|
107
|
+
const failure = takeFailure("unavailable", "bad_verification_code");
|
|
108
|
+
if (failure === "unavailable") return json(503, { message: "Service unavailable" });
|
|
109
|
+
if (failure === "bad_verification_code") return answer({ error: "bad_verification_code", error_description: "The code passed is incorrect or expired." });
|
|
110
|
+
if (form.get("client_id") !== clientId || form.get("client_secret") !== clientSecret) return answer({ error: "incorrect_client_credentials" });
|
|
111
|
+
const code = form.get("code") ?? "";
|
|
112
|
+
const pending = codes.get(code);
|
|
113
|
+
codes.delete(code);
|
|
114
|
+
if (pending === undefined) return answer({ error: "bad_verification_code" });
|
|
115
|
+
if (form.get("redirect_uri") !== pending.redirectUri) return answer({ error: "redirect_uri_mismatch" });
|
|
116
|
+
const verifier = form.get("code_verifier") ?? "";
|
|
117
|
+
if (createHash("sha256").update(verifier, "ascii").digest("base64url") !== pending.challenge) return answer({ error: "bad_verification_code" });
|
|
118
|
+
const token = `gho_${random()}`;
|
|
119
|
+
tokens.set(token, pending.user);
|
|
120
|
+
calls.issuedTokens.push(token);
|
|
121
|
+
return answer({ access_token: token, token_type: "bearer", scope: "read:user,user:email" });
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function readBearer(init: RequestInit): FakeGithubUser | undefined {
|
|
125
|
+
const authorization = new Headers(init.headers).get("authorization") ?? "";
|
|
126
|
+
return authorization.startsWith("Bearer ") ? tokens.get(authorization.slice(7)) : undefined;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function answerUser(init: RequestInit): Response {
|
|
130
|
+
calls.user += 1;
|
|
131
|
+
if (takeFailure("user_unavailable") !== undefined) return json(502, { message: "Server Error" });
|
|
132
|
+
const user = readBearer(init);
|
|
133
|
+
if (user === undefined) return json(401, { message: "Bad credentials" });
|
|
134
|
+
return json(200, { login: user.login, id: user.id, type: "User", name: user.name ?? null, email: null });
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function answerEmails(init: RequestInit): Response {
|
|
138
|
+
calls.emails += 1;
|
|
139
|
+
if (takeFailure("emails_unavailable") !== undefined) return json(502, { message: "Server Error" });
|
|
140
|
+
const user = readBearer(init);
|
|
141
|
+
if (user === undefined) return json(401, { message: "Bad credentials" });
|
|
142
|
+
return json(
|
|
143
|
+
200,
|
|
144
|
+
user.emails.map((entry, index) => ({ email: entry.email, primary: entry.primary ?? index === 0, verified: entry.verified ?? true, visibility: null })),
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const fetchFake: FetchFunction = (input, init) => Promise.resolve(route(input, init));
|
|
149
|
+
|
|
150
|
+
function route(input: string | URL, init: RequestInit): Response {
|
|
151
|
+
const url = new URL(typeof input === "string" ? input : input.toString());
|
|
152
|
+
const target = `${url.origin}${url.pathname}`;
|
|
153
|
+
const method = init.method ?? "GET";
|
|
154
|
+
if (target === TOKEN_URL && method === "POST") return answerToken(init);
|
|
155
|
+
if (target === USER_URL && method === "GET") return answerUser(init);
|
|
156
|
+
if (target === EMAILS_URL && method === "GET") return answerEmails(init);
|
|
157
|
+
return json(404, { message: "Not Found" });
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
return {
|
|
161
|
+
definition: {
|
|
162
|
+
type: "github",
|
|
163
|
+
id,
|
|
164
|
+
name: "GitHub",
|
|
165
|
+
clientIdEnv: `${envPrefix}_CLIENT_ID`,
|
|
166
|
+
clientSecretEnv: `${envPrefix}_CLIENT_SECRET`,
|
|
167
|
+
allowedDomains: [...(options.allowedDomains ?? (options.allowedEmails === undefined ? ["example.com"] : []))],
|
|
168
|
+
allowedEmails: [...(options.allowedEmails ?? [])],
|
|
169
|
+
createAccounts: options.createAccounts,
|
|
170
|
+
},
|
|
171
|
+
env: { [`${envPrefix}_CLIENT_ID`]: clientId, [`${envPrefix}_CLIENT_SECRET`]: clientSecret },
|
|
172
|
+
fetch: fetchFake,
|
|
173
|
+
signIn(authorizeUrl, user, signInOptions = {}) {
|
|
174
|
+
const url = new URL(authorizeUrl);
|
|
175
|
+
const query = url.searchParams;
|
|
176
|
+
if (`${url.origin}${url.pathname}` !== AUTHORIZE_URL) throw new Error(`fake GitHub: authorize URL ${url.origin}${url.pathname} is not ${AUTHORIZE_URL}`);
|
|
177
|
+
if (query.get("client_id") !== clientId) throw new Error("fake GitHub: unknown client_id");
|
|
178
|
+
const scopes = (query.get("scope") ?? "").split(" ");
|
|
179
|
+
if (!scopes.includes("read:user") || !scopes.includes("user:email")) throw new Error("fake GitHub: scope needs read:user and user:email");
|
|
180
|
+
if (query.get("code_challenge_method") !== "S256") throw new Error("fake GitHub: PKCE S256 is required");
|
|
181
|
+
const redirectUri = query.get("redirect_uri");
|
|
182
|
+
const state = query.get("state");
|
|
183
|
+
const challenge = query.get("code_challenge");
|
|
184
|
+
if (redirectUri === null || state === null || challenge === null) throw new Error("fake GitHub: redirect_uri, state and code_challenge are required");
|
|
185
|
+
const callback = new URL(redirectUri);
|
|
186
|
+
callback.searchParams.set("state", state);
|
|
187
|
+
if (signInOptions.deny === true) {
|
|
188
|
+
callback.searchParams.set("error", "access_denied");
|
|
189
|
+
callback.searchParams.set("error_description", "The user has denied your application access.");
|
|
190
|
+
return callback;
|
|
191
|
+
}
|
|
192
|
+
const code = random();
|
|
193
|
+
codes.set(code, { redirectUri, challenge, user });
|
|
194
|
+
callback.searchParams.set("code", code);
|
|
195
|
+
return callback;
|
|
196
|
+
},
|
|
197
|
+
failNext(...next) {
|
|
198
|
+
failures.push(...next);
|
|
199
|
+
},
|
|
200
|
+
calls,
|
|
201
|
+
};
|
|
202
|
+
}
|
package/src/testing/index.ts
CHANGED
|
@@ -1,7 +1,16 @@
|
|
|
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, and a fake OpenID Connect provider for tests of the sign-in.
|
|
2
|
+
// a user but are not about registration, and a fake OpenID Connect provider and a fake GitHub for tests of the sign-in.
|
|
3
3
|
// Server-only; never imported by the module's runtime code.
|
|
4
4
|
export { createTestAccount, type TestAccountHashInput, type TestAccountInput } from "./account.js";
|
|
5
|
+
export {
|
|
6
|
+
createFakeGithubProvider,
|
|
7
|
+
type FakeGithubEmail,
|
|
8
|
+
type FakeGithubFailure,
|
|
9
|
+
type FakeGithubProvider,
|
|
10
|
+
type FakeGithubProviderOptions,
|
|
11
|
+
type FakeGithubSignInOptions,
|
|
12
|
+
type FakeGithubUser,
|
|
13
|
+
} from "./github-provider.js";
|
|
5
14
|
export {
|
|
6
15
|
createFakeOidcProvider,
|
|
7
16
|
type FakeOidcFailure,
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
// outage, an endpoint on plain http.
|
|
6
6
|
import { createHash, generateKeyPairSync, randomBytes, sign, type KeyObject } from "node:crypto";
|
|
7
7
|
import { systemClock, type Clock, type FetchFunction } from "@softure-ai/core";
|
|
8
|
-
import type {
|
|
8
|
+
import type { OpenIdConnectProviderInput } from "../options.js";
|
|
9
9
|
|
|
10
10
|
export interface FakeOidcProviderOptions {
|
|
11
11
|
/** The provider id. Default `fake`. */
|
|
@@ -54,7 +54,7 @@ export type FakeOidcFailure = "unavailable" | "invalid_grant" | "no_id_token";
|
|
|
54
54
|
|
|
55
55
|
export interface FakeOidcProvider {
|
|
56
56
|
/** The provider entry for `auth({ oidc: { providers: [fake.definition] } })`. */
|
|
57
|
-
readonly definition:
|
|
57
|
+
readonly definition: OpenIdConnectProviderInput;
|
|
58
58
|
/** The environment the definition reads its client id and secret from. */
|
|
59
59
|
readonly env: Readonly<Record<string, string>>;
|
|
60
60
|
/** The `fetch` for `auth({ oidc: { fetch } })`. */
|