@softure-ai/auth 0.2.8 → 0.2.10

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.
Files changed (54) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +49 -2
  3. package/dist/index.d.ts +42 -8
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +1 -1
  6. package/dist/index.js.map +1 -1
  7. package/dist/options.d.ts +124 -13
  8. package/dist/options.d.ts.map +1 -1
  9. package/dist/options.js +48 -15
  10. package/dist/options.js.map +1 -1
  11. package/dist/server/oidc/allowlist.d.ts +10 -0
  12. package/dist/server/oidc/allowlist.d.ts.map +1 -0
  13. package/dist/server/oidc/allowlist.js +23 -0
  14. package/dist/server/oidc/allowlist.js.map +1 -0
  15. package/dist/server/oidc/discovery.d.ts +2 -2
  16. package/dist/server/oidc/discovery.d.ts.map +1 -1
  17. package/dist/server/oidc/discovery.js.map +1 -1
  18. package/dist/server/oidc/flow.d.ts +0 -7
  19. package/dist/server/oidc/flow.d.ts.map +1 -1
  20. package/dist/server/oidc/flow.js +50 -49
  21. package/dist/server/oidc/flow.js.map +1 -1
  22. package/dist/server/oidc/github.d.ts +33 -0
  23. package/dist/server/oidc/github.d.ts.map +1 -0
  24. package/dist/server/oidc/github.js +92 -0
  25. package/dist/server/oidc/github.js.map +1 -0
  26. package/dist/server/oidc/index.d.ts +2 -1
  27. package/dist/server/oidc/index.d.ts.map +1 -1
  28. package/dist/server/oidc/index.js +3 -2
  29. package/dist/server/oidc/index.js.map +1 -1
  30. package/dist/server/oidc/token-request.d.ts +2 -2
  31. package/dist/server/oidc/token-request.d.ts.map +1 -1
  32. package/dist/testing/github-provider.d.ts +58 -0
  33. package/dist/testing/github-provider.d.ts.map +1 -0
  34. package/dist/testing/github-provider.js +139 -0
  35. package/dist/testing/github-provider.js.map +1 -0
  36. package/dist/testing/index.d.ts +1 -0
  37. package/dist/testing/index.d.ts.map +1 -1
  38. package/dist/testing/index.js +2 -1
  39. package/dist/testing/index.js.map +1 -1
  40. package/dist/testing/oidc-provider.d.ts +2 -2
  41. package/dist/testing/oidc-provider.d.ts.map +1 -1
  42. package/module.json +1 -1
  43. package/package.json +1 -1
  44. package/src/index.ts +5 -1
  45. package/src/options.ts +80 -36
  46. package/src/server/oidc/allowlist.ts +23 -0
  47. package/src/server/oidc/discovery.ts +2 -2
  48. package/src/server/oidc/flow.ts +63 -47
  49. package/src/server/oidc/github.ts +112 -0
  50. package/src/server/oidc/index.ts +2 -2
  51. package/src/server/oidc/token-request.ts +2 -2
  52. package/src/testing/github-provider.ts +202 -0
  53. package/src/testing/index.ts +10 -1
  54. package/src/testing/oidc-provider.ts +2 -2
@@ -0,0 +1,139 @@
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
+ const AUTHORIZE_URL = "https://github.com/login/oauth/authorize";
7
+ const TOKEN_URL = "https://github.com/login/oauth/access_token";
8
+ const USER_URL = "https://api.github.com/user";
9
+ const EMAILS_URL = "https://api.github.com/user/emails";
10
+ const random = () => randomBytes(24).toString("base64url");
11
+ export function createFakeGithubProvider(options = {}) {
12
+ const id = options.id ?? "github";
13
+ const clientId = options.clientId ?? "fake-github-client";
14
+ const clientSecret = options.clientSecret ?? "fake-github-secret";
15
+ const envPrefix = `${id.toUpperCase().replaceAll("-", "_")}_AUTH`;
16
+ const codes = new Map();
17
+ const tokens = new Map();
18
+ const failures = [];
19
+ const calls = { token: 0, user: 0, emails: 0, lastForm: null, issuedTokens: [] };
20
+ const json = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json; charset=utf-8" } });
21
+ const takeFailure = (...kinds) => {
22
+ const next = failures[0];
23
+ if (next === undefined || !kinds.includes(next))
24
+ return undefined;
25
+ return failures.shift();
26
+ };
27
+ function answerToken(init) {
28
+ calls.token += 1;
29
+ const form = new URLSearchParams(init.body instanceof URLSearchParams ? init.body : typeof init.body === "string" ? init.body : "");
30
+ calls.lastForm = form;
31
+ const headers = new Headers(init.headers);
32
+ const wantsJson = headers.get("accept")?.includes("application/json") === true;
33
+ const answer = (body) => wantsJson ? json(200, body) : new Response(new URLSearchParams(body).toString(), { status: 200, headers: { "content-type": "application/x-www-form-urlencoded" } });
34
+ const failure = takeFailure("unavailable", "bad_verification_code");
35
+ if (failure === "unavailable")
36
+ return json(503, { message: "Service unavailable" });
37
+ if (failure === "bad_verification_code")
38
+ return answer({ error: "bad_verification_code", error_description: "The code passed is incorrect or expired." });
39
+ if (form.get("client_id") !== clientId || form.get("client_secret") !== clientSecret)
40
+ return answer({ error: "incorrect_client_credentials" });
41
+ const code = form.get("code") ?? "";
42
+ const pending = codes.get(code);
43
+ codes.delete(code);
44
+ if (pending === undefined)
45
+ return answer({ error: "bad_verification_code" });
46
+ if (form.get("redirect_uri") !== pending.redirectUri)
47
+ return answer({ error: "redirect_uri_mismatch" });
48
+ const verifier = form.get("code_verifier") ?? "";
49
+ if (createHash("sha256").update(verifier, "ascii").digest("base64url") !== pending.challenge)
50
+ return answer({ error: "bad_verification_code" });
51
+ const token = `gho_${random()}`;
52
+ tokens.set(token, pending.user);
53
+ calls.issuedTokens.push(token);
54
+ return answer({ access_token: token, token_type: "bearer", scope: "read:user,user:email" });
55
+ }
56
+ function readBearer(init) {
57
+ const authorization = new Headers(init.headers).get("authorization") ?? "";
58
+ return authorization.startsWith("Bearer ") ? tokens.get(authorization.slice(7)) : undefined;
59
+ }
60
+ function answerUser(init) {
61
+ calls.user += 1;
62
+ if (takeFailure("user_unavailable") !== undefined)
63
+ return json(502, { message: "Server Error" });
64
+ const user = readBearer(init);
65
+ if (user === undefined)
66
+ return json(401, { message: "Bad credentials" });
67
+ return json(200, { login: user.login, id: user.id, type: "User", name: user.name ?? null, email: null });
68
+ }
69
+ function answerEmails(init) {
70
+ calls.emails += 1;
71
+ if (takeFailure("emails_unavailable") !== undefined)
72
+ return json(502, { message: "Server Error" });
73
+ const user = readBearer(init);
74
+ if (user === undefined)
75
+ return json(401, { message: "Bad credentials" });
76
+ return json(200, user.emails.map((entry, index) => ({ email: entry.email, primary: entry.primary ?? index === 0, verified: entry.verified ?? true, visibility: null })));
77
+ }
78
+ const fetchFake = (input, init) => Promise.resolve(route(input, init));
79
+ function route(input, init) {
80
+ const url = new URL(typeof input === "string" ? input : input.toString());
81
+ const target = `${url.origin}${url.pathname}`;
82
+ const method = init.method ?? "GET";
83
+ if (target === TOKEN_URL && method === "POST")
84
+ return answerToken(init);
85
+ if (target === USER_URL && method === "GET")
86
+ return answerUser(init);
87
+ if (target === EMAILS_URL && method === "GET")
88
+ return answerEmails(init);
89
+ return json(404, { message: "Not Found" });
90
+ }
91
+ return {
92
+ definition: {
93
+ type: "github",
94
+ id,
95
+ name: "GitHub",
96
+ clientIdEnv: `${envPrefix}_CLIENT_ID`,
97
+ clientSecretEnv: `${envPrefix}_CLIENT_SECRET`,
98
+ allowedDomains: [...(options.allowedDomains ?? (options.allowedEmails === undefined ? ["example.com"] : []))],
99
+ allowedEmails: [...(options.allowedEmails ?? [])],
100
+ createAccounts: options.createAccounts,
101
+ },
102
+ env: { [`${envPrefix}_CLIENT_ID`]: clientId, [`${envPrefix}_CLIENT_SECRET`]: clientSecret },
103
+ fetch: fetchFake,
104
+ signIn(authorizeUrl, user, signInOptions = {}) {
105
+ const url = new URL(authorizeUrl);
106
+ const query = url.searchParams;
107
+ if (`${url.origin}${url.pathname}` !== AUTHORIZE_URL)
108
+ throw new Error(`fake GitHub: authorize URL ${url.origin}${url.pathname} is not ${AUTHORIZE_URL}`);
109
+ if (query.get("client_id") !== clientId)
110
+ throw new Error("fake GitHub: unknown client_id");
111
+ const scopes = (query.get("scope") ?? "").split(" ");
112
+ if (!scopes.includes("read:user") || !scopes.includes("user:email"))
113
+ throw new Error("fake GitHub: scope needs read:user and user:email");
114
+ if (query.get("code_challenge_method") !== "S256")
115
+ throw new Error("fake GitHub: PKCE S256 is required");
116
+ const redirectUri = query.get("redirect_uri");
117
+ const state = query.get("state");
118
+ const challenge = query.get("code_challenge");
119
+ if (redirectUri === null || state === null || challenge === null)
120
+ throw new Error("fake GitHub: redirect_uri, state and code_challenge are required");
121
+ const callback = new URL(redirectUri);
122
+ callback.searchParams.set("state", state);
123
+ if (signInOptions.deny === true) {
124
+ callback.searchParams.set("error", "access_denied");
125
+ callback.searchParams.set("error_description", "The user has denied your application access.");
126
+ return callback;
127
+ }
128
+ const code = random();
129
+ codes.set(code, { redirectUri, challenge, user });
130
+ callback.searchParams.set("code", code);
131
+ return callback;
132
+ },
133
+ failNext(...next) {
134
+ failures.push(...next);
135
+ },
136
+ calls,
137
+ };
138
+ }
139
+ //# sourceMappingURL=github-provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"github-provider.js","sourceRoot":"","sources":["../../src/testing/github-provider.ts"],"names":[],"mappings":"AAAA,mHAAmH;AACnH,qHAAqH;AACrH,oHAAoH;AACpH,+GAA+G;AAC/G,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAItD,MAAM,aAAa,GAAG,0CAA0C,CAAC;AACjE,MAAM,SAAS,GAAG,6CAA6C,CAAC;AAChE,MAAM,QAAQ,GAAG,6BAA6B,CAAC;AAC/C,MAAM,UAAU,GAAG,oCAAoC,CAAC;AAoExD,MAAM,MAAM,GAAG,GAAG,EAAE,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;AAE3D,MAAM,UAAU,wBAAwB,CAAC,UAAqC,EAAE;IAC9E,MAAM,EAAE,GAAG,OAAO,CAAC,EAAE,IAAI,QAAQ,CAAC;IAClC,MAAM,QAAQ,GA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C,CAAC;YAC9C,MAAM,KAAK,GAAG,KAAK,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;YACjC,MAAM,SAAS,GAAG,KAAK,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;YAC9C,IAAI,WAAW,KAAK,IAAI,IAAI,KAAK,KAAK,IAAI,IAAI,SAAS,KAAK,IAAI;gBAAE,MAAM,IAAI,KAAK,CAAC,kEAAkE,CAAC,CAAC;YACtJ,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,WAAW,CAAC,CAAC;YACtC,QAAQ,CAAC,YAAY,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;YAC1C,IAAI,aAAa,CAAC,IAAI,KAAK,IAAI,EAAE,CAAC;gBAChC,QAAQ,CAAC,YAAY,CAAC,GAAG,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC;gBACpD,QAAQ,CAAC,YAAY,CAAC,GAAG,CAAC,mBAAmB,EAAE,8CAA8C,CAAC,CAAC;gBAC/F,OAAO,QAAQ,CAAC;YAClB,CAAC;YACD,MAAM,IAAI,GAAG,MAAM,EAAE,CAAC;YACtB,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,WAAW,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;YAClD,QAAQ,CAAC,YAAY,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;YACxC,OAAO,QAAQ,CAAC;QAClB,CAAC;QACD,QAAQ,CAAC,GAAG,IAAI;YACd,QAAQ,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC;QACzB,CAAC;QACD,KAAK;KACN,CAAC;AACJ,CAAC"}
@@ -1,3 +1,4 @@
1
1
  export { createTestAccount, type TestAccountHashInput, type TestAccountInput } from "./account.js";
2
+ export { createFakeGithubProvider, type FakeGithubEmail, type FakeGithubFailure, type FakeGithubProvider, type FakeGithubProviderOptions, type FakeGithubSignInOptions, type FakeGithubUser, } from "./github-provider.js";
2
3
  export { createFakeOidcProvider, type FakeOidcFailure, type FakeOidcProvider, type FakeOidcProviderOptions, type FakeOidcUser, type FakeSignInOptions, } from "./oidc-provider.js";
3
4
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/testing/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,iBAAiB,EAAE,KAAK,oBAAoB,EAAE,KAAK,gBAAgB,EAAE,MAAM,cAAc,CAAC;AACnG,OAAO,EACL,sBAAsB,EACtB,KAAK,eAAe,EACpB,KAAK,gBAAgB,EACrB,KAAK,uBAAuB,EAC5B,KAAK,YAAY,EACjB,KAAK,iBAAiB,GACvB,MAAM,oBAAoB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/testing/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,iBAAiB,EAAE,KAAK,oBAAoB,EAAE,KAAK,gBAAgB,EAAE,MAAM,cAAc,CAAC;AACnG,OAAO,EACL,wBAAwB,EACxB,KAAK,eAAe,EACpB,KAAK,iBAAiB,EACtB,KAAK,kBAAkB,EACvB,KAAK,yBAAyB,EAC9B,KAAK,uBAAuB,EAC5B,KAAK,cAAc,GACpB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,sBAAsB,EACtB,KAAK,eAAe,EACpB,KAAK,gBAAgB,EACrB,KAAK,uBAAuB,EAC5B,KAAK,YAAY,EACjB,KAAK,iBAAiB,GACvB,MAAM,oBAAoB,CAAC"}
@@ -1,6 +1,7 @@
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 } from "./account.js";
5
+ export { createFakeGithubProvider, } from "./github-provider.js";
5
6
  export { createFakeOidcProvider, } from "./oidc-provider.js";
6
7
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/testing/index.ts"],"names":[],"mappings":"AAAA,mGAAmG;AACnG,sGAAsG;AACtG,4DAA4D;AAC5D,OAAO,EAAE,iBAAiB,EAAoD,MAAM,cAAc,CAAC;AACnG,OAAO,EACL,sBAAsB,GAMvB,MAAM,oBAAoB,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/testing/index.ts"],"names":[],"mappings":"AAAA,mGAAmG;AACnG,wHAAwH;AACxH,4DAA4D;AAC5D,OAAO,EAAE,iBAAiB,EAAoD,MAAM,cAAc,CAAC;AACnG,OAAO,EACL,wBAAwB,GAOzB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,sBAAsB,GAMvB,MAAM,oBAAoB,CAAC"}
@@ -1,5 +1,5 @@
1
1
  import { type Clock, type FetchFunction } from "@softure-ai/core";
2
- import type { OidcProviderInput } from "../options.js";
2
+ import type { OpenIdConnectProviderInput } from "../options.js";
3
3
  export interface FakeOidcProviderOptions {
4
4
  /** The provider id. Default `fake`. */
5
5
  readonly id?: string;
@@ -43,7 +43,7 @@ export interface FakeSignInOptions {
43
43
  export type FakeOidcFailure = "unavailable" | "invalid_grant" | "no_id_token";
44
44
  export interface FakeOidcProvider {
45
45
  /** The provider entry for `auth({ oidc: { providers: [fake.definition] } })`. */
46
- readonly definition: OidcProviderInput;
46
+ readonly definition: OpenIdConnectProviderInput;
47
47
  /** The environment the definition reads its client id and secret from. */
48
48
  readonly env: Readonly<Record<string, string>>;
49
49
  /** The `fetch` for `auth({ oidc: { fetch } })`. */
@@ -1 +1 @@
1
- {"version":3,"file":"oidc-provider.d.ts","sourceRoot":"","sources":["../../src/testing/oidc-provider.ts"],"names":[],"mappings":"AAMA,OAAO,EAAe,KAAK,KAAK,EAAE,KAAK,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAC/E,OAAO,KAAK,EAAE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,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,QAAQ,EAAE,eAAe,GAAG,IAAI,CAAA;KAAE,CAAC;CAC1I;AAmBD,wBAAgB,sBAAsB,CAAC,OAAO,GAAE,uBAA4B,GAAG,gBAAgB,CAmK9F"}
package/module.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "id": "auth",
3
- "version": "0.2.8",
3
+ "version": "0.2.10",
4
4
  "dependsOn": { "security": "^0.2.0", "mailing": "^0.2.0?", "ops": "^0.2.0?", "jobs": "^0.1.1?" },
5
5
  "dbSchema": "auth",
6
6
  "tables": ["users", "sessions", "user_roles", "password_resets", "identities", "oidc_states"],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@softure-ai/auth",
3
- "version": "0.2.8",
3
+ "version": "0.2.10",
4
4
  "description": "SOFTURE AI auth module: users, scrypt passwords, database sessions, register with consent, login, logout, password change, roles, a proxy route guard, pages and forms for Next.js, and a password reset sender over @softure-ai/mailing, sent in the request or by a background job through @softure-ai/jobs.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/index.ts CHANGED
@@ -46,7 +46,7 @@ export const AUTH_RATE_LIMIT_BUCKETS = {
46
46
  export const auth = defineModule({
47
47
  manifest: {
48
48
  id: MODULE_ID,
49
- version: "0.2.8",
49
+ version: "0.2.10",
50
50
  dependsOn: { security: "^0.2.0", mailing: "^0.2.0?", ops: "^0.2.0?", jobs: "^0.1.1?" },
51
51
  dbSchema: "auth",
52
52
  tables: ["users", "sessions", "user_roles", "password_resets", "identities", "oidc_states"],
@@ -103,9 +103,13 @@ export {
103
103
  OIDC_PROVIDER_ID_PATTERN,
104
104
  type AuthOptions,
105
105
  type AuthOptionsInput,
106
+ type GithubProvider,
107
+ type GithubProviderInput,
106
108
  type OidcProvider,
107
109
  type OidcProviderInput,
108
110
  type OnRegisteredHook,
111
+ type OpenIdConnectProvider,
112
+ type OpenIdConnectProviderInput,
109
113
  type RewriteRedirect,
110
114
  type RewriteRedirectContext,
111
115
  type ScryptParams,
package/src/options.ts CHANGED
@@ -106,47 +106,88 @@ export function isSecureEndpoint(value: string): boolean {
106
106
 
107
107
  const domainSchema = z.string().trim().toLowerCase().regex(DOMAIN, "must be a lowercase host name such as example.com");
108
108
 
109
+ /** Who may sign in through a provider; refined on every provider type. */
110
+ const allowlistShape = {
111
+ /** Who may sign in: a verified email in one of these domains. */
112
+ allowedDomains: z.array(domainSchema).default([]),
113
+ /** Who may sign in: one of these verified emails. */
114
+ allowedEmails: z.array(adminEmailSchema).default([]),
115
+ /** A first sign-in of an allowed identity without an account creates one (no password); false only links. */
116
+ createAccounts: z.boolean().default(true),
117
+ };
118
+
119
+ const providerIdSchema = z.string().regex(OIDC_PROVIDER_ID_PATTERN, "must be an id such as google (a-z first, then a-z, 0-9 or -, at most 32)");
120
+ const authorizeParamsSchema = z.record(z.string().regex(/^[a-z_]{1,64}$/), z.string().max(512)).default({});
121
+
122
+ const openIdConnectProviderSchema = z.strictObject({
123
+ /** Optional: an entry without `type` is an OpenID Connect provider. */
124
+ type: z.literal("oidc").default("oidc"),
125
+ /** The provider's id in URLs and in `auth.identities`, e.g. `google`. */
126
+ id: providerIdSchema,
127
+ /** The provider's name as the button shows it (`messages.oidc.signInWith`), e.g. `Google`. */
128
+ name: z.string().trim().min(1).max(64),
129
+ /** The issuer; its discovery document is `<issuer>/.well-known/openid-configuration`. */
130
+ issuer: z
131
+ .string()
132
+ .refine(isSecureEndpoint, "must be an https URL (http only on localhost)")
133
+ .transform((issuer) => issuer.replace(/\/+$/, "")),
134
+ /** The environment variable that holds the client id. */
135
+ clientIdEnv: z.string().regex(ENV_NAME, "must be an environment variable name such as GOOGLE_AUTH_CLIENT_ID"),
136
+ /** The environment variable that holds the client secret; absent for a public client. */
137
+ clientSecretEnv: z.string().regex(ENV_NAME, "must be an environment variable name such as GOOGLE_AUTH_CLIENT_SECRET").optional(),
138
+ /** How the client authenticates at the token endpoint: form fields (`client_secret_post`) or HTTP Basic. */
139
+ clientAuth: z.enum(["body", "basic"]).default("body"),
140
+ /** Requested scopes; `openid` and `email` are always sent. */
141
+ scopes: z.array(z.string().regex(/^[\x21\x23-\x5b\x5d-\x7e]{1,128}$/, "must be a scope token")).default([]),
142
+ /** Extra parameters of the authorize URL, e.g. `{ prompt: "select_account", hd: "example.com" }`. */
143
+ authorizeParams: authorizeParamsSchema,
144
+ ...allowlistShape,
145
+ /**
146
+ * A domain match also needs the token's `hd` claim to name that domain (a Google Workspace account). Defaults to
147
+ * true for Google, whose consumer accounts can carry a verified address of any domain.
148
+ */
149
+ requireHostedDomain: z.boolean().optional(),
150
+ });
151
+
152
+ /**
153
+ * Sign-in with a GitHub OAuth App: not OpenID Connect (no discovery, ID token or keys), so the endpoints are fixed and
154
+ * the account is read from GitHub's API with the access token, which is not kept. Everything around it (state, PKCE,
155
+ * cookie, rate limits, callback route, allowlist, identities) is the OpenID Connect sign-in's.
156
+ */
157
+ const githubProviderSchema = z.strictObject({
158
+ type: z.literal("github"),
159
+ /** The provider's id in URLs and in `auth.identities`, e.g. `github`. */
160
+ id: providerIdSchema,
161
+ /** The provider's name as the button shows it, e.g. `GitHub`. */
162
+ name: z.string().trim().min(1).max(64),
163
+ /** The environment variable that holds the OAuth App's client id. */
164
+ clientIdEnv: z.string().regex(ENV_NAME, "must be an environment variable name such as GH_AUTH_CLIENT_ID"),
165
+ /** The environment variable that holds the OAuth App's client secret (GitHub's token endpoint always needs it). */
166
+ clientSecretEnv: z.string().regex(ENV_NAME, "must be an environment variable name such as GH_AUTH_CLIENT_SECRET"),
167
+ /** Extra parameters of the authorize URL, e.g. `{ allow_signup: "false", prompt: "select_account" }`. */
168
+ authorizeParams: authorizeParamsSchema,
169
+ ...allowlistShape,
170
+ });
171
+
109
172
  const oidcProviderSchema = z
110
- .strictObject({
111
- /** The provider's id in URLs and in `auth.identities`, e.g. `google`. */
112
- id: z.string().regex(OIDC_PROVIDER_ID_PATTERN, "must be an id such as google (a-z first, then a-z, 0-9 or -, at most 32)"),
113
- /** The provider's name as the button shows it (`messages.oidc.signInWith`), e.g. `Google`. */
114
- name: z.string().trim().min(1).max(64),
115
- /** The issuer; its discovery document is `<issuer>/.well-known/openid-configuration`. */
116
- issuer: z
117
- .string()
118
- .refine(isSecureEndpoint, "must be an https URL (http only on localhost)")
119
- .transform((issuer) => issuer.replace(/\/+$/, "")),
120
- /** The environment variable that holds the client id. */
121
- clientIdEnv: z.string().regex(ENV_NAME, "must be an environment variable name such as GOOGLE_AUTH_CLIENT_ID"),
122
- /** The environment variable that holds the client secret; absent for a public client. */
123
- clientSecretEnv: z.string().regex(ENV_NAME, "must be an environment variable name such as GOOGLE_AUTH_CLIENT_SECRET").optional(),
124
- /** How the client authenticates at the token endpoint: form fields (`client_secret_post`) or HTTP Basic. */
125
- clientAuth: z.enum(["body", "basic"]).default("body"),
126
- /** Requested scopes; `openid` and `email` are always sent. */
127
- scopes: z.array(z.string().regex(/^[\x21\x23-\x5b\x5d-\x7e]{1,128}$/, "must be a scope token")).default([]),
128
- /** Extra parameters of the authorize URL, e.g. `{ prompt: "select_account", hd: "example.com" }`. */
129
- authorizeParams: z.record(z.string().regex(/^[a-z_]{1,64}$/), z.string().max(512)).default({}),
130
- /** Who may sign in: a verified email in one of these domains. */
131
- allowedDomains: z.array(domainSchema).default([]),
132
- /** Who may sign in: one of these verified emails. */
133
- allowedEmails: z.array(adminEmailSchema).default([]),
134
- /**
135
- * A domain match also needs the token's `hd` claim to name that domain (a Google Workspace account). Defaults to
136
- * true for Google, whose consumer accounts can carry a verified address of any domain.
137
- */
138
- requireHostedDomain: z.boolean().optional(),
139
- /** A first sign-in of an allowed identity without an account creates one (no password); false only links. */
140
- createAccounts: z.boolean().default(true),
141
- })
142
- .transform((provider) => ({ ...provider, requireHostedDomain: provider.requireHostedDomain ?? provider.issuer === GOOGLE_ISSUER }))
173
+ .discriminatedUnion("type", [openIdConnectProviderSchema, githubProviderSchema])
174
+ .transform((provider) =>
175
+ provider.type === "github"
176
+ ? { ...provider, requireHostedDomain: false as const }
177
+ : { ...provider, requireHostedDomain: provider.requireHostedDomain ?? provider.issuer === GOOGLE_ISSUER },
178
+ )
143
179
  .refine((provider) => provider.allowedDomains.length + provider.allowedEmails.length > 0, {
144
- message: "needs allowedDomains or allowedEmails: an OpenID Connect sign-in is limited to them",
180
+ message: "needs allowedDomains or allowedEmails: a sign-in through a provider is limited to them",
145
181
  path: ["allowedDomains"],
146
182
  });
147
183
 
148
184
  export type OidcProviderInput = z.input<typeof oidcProviderSchema>;
185
+ export type OpenIdConnectProviderInput = z.input<typeof openIdConnectProviderSchema>;
186
+ export type GithubProviderInput = z.input<typeof githubProviderSchema>;
187
+ /** A configured sign-in provider: OpenID Connect (`type: "oidc"`) or GitHub (`type: "github"`). */
149
188
  export type OidcProvider = z.output<typeof oidcProviderSchema>;
189
+ export type OpenIdConnectProvider = Extract<OidcProvider, { readonly type: "oidc" }>;
190
+ export type GithubProvider = Extract<OidcProvider, { readonly type: "github" }>;
150
191
 
151
192
  export const authOptionsSchema = z.strictObject({
152
193
  password: z
@@ -234,7 +275,10 @@ export const authOptionsSchema = z.strictObject({
234
275
  ttlMinutes: z.number().int().min(5).max(1440).default(60),
235
276
  })
236
277
  .prefault({}),
237
- /** Sign-in with OpenID Connect providers (e.g. Google), limited to allowed domains or emails. Off without providers. */
278
+ /**
279
+ * Sign-in with OpenID Connect providers (e.g. Google) or GitHub (`type: "github"`), limited to allowed domains or
280
+ * emails. Off without providers.
281
+ */
238
282
  oidc: z
239
283
  .strictObject({
240
284
  providers: z
@@ -243,7 +287,7 @@ export const authOptionsSchema = z.strictObject({
243
287
  .default([]),
244
288
  /** How long a started sign-in may take at the provider. */
245
289
  stateTtlMinutes: z.number().int().min(1).max(60).default(10),
246
- /** Timeout of each call to a provider (discovery, keys, token). */
290
+ /** Timeout of each call to a provider (discovery, keys, token, GitHub's API). */
247
291
  httpTimeoutMs: z.number().int().min(1000).max(60_000).default(10_000),
248
292
  /** The `fetch` the provider calls go through; tests pass a fake provider's. */
249
293
  fetch: z.custom<FetchFunction>((value) => typeof value === "function", "must be a function").optional(),
@@ -0,0 +1,23 @@
1
+ // Who may sign in through a provider: a verified email listed in `allowedEmails` or of a domain in `allowedDomains`.
2
+ import type { OidcProvider } from "../../options.js";
3
+ import type { IdentityClaims } from "./id-token.js";
4
+
5
+ /**
6
+ * The identity's email when it may sign in: verified, and listed in `allowedEmails` or of a domain in
7
+ * `allowedDomains` (with `requireHostedDomain`, the `hd` claim must name that domain too); null otherwise.
8
+ */
9
+ export function getAllowedEmail(provider: OidcProvider, claims: IdentityClaims): string | null {
10
+ const { email } = claims;
11
+ if (email === null || !claims.isEmailVerified) return null;
12
+ return isAllowedEmail(provider, email, claims.hostedDomain) ? email : null;
13
+ }
14
+
15
+ /** Whether a verified, lowercased email passes the provider's allowlist. */
16
+ export function isAllowedEmail(provider: OidcProvider, email: string, hostedDomain: string | null): boolean {
17
+ if (provider.allowedEmails.includes(email)) return true;
18
+ const at = email.lastIndexOf("@");
19
+ if (at <= 0) return false;
20
+ const domain = email.slice(at + 1);
21
+ if (!provider.allowedDomains.includes(domain)) return false;
22
+ return !provider.requireHostedDomain || hostedDomain === domain;
23
+ }
@@ -4,7 +4,7 @@
4
4
  import { createPublicKey, type JsonWebKey, type KeyObject } from "node:crypto";
5
5
  import { requestJson, type SoftureConfig } from "@softure-ai/core";
6
6
  import { z } from "zod";
7
- import { isSecureEndpoint, type OidcProvider } from "../../options.js";
7
+ import { isSecureEndpoint, type OpenIdConnectProvider } from "../../options.js";
8
8
  import { getAuthOptions } from "../options.js";
9
9
  import { passed, refused, type Checked, type OidcContext } from "./context.js";
10
10
 
@@ -67,7 +67,7 @@ function requestOptions(ctx: OidcContext) {
67
67
  }
68
68
 
69
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>> {
70
+ export async function getProviderMetadata(ctx: OidcContext, provider: OpenIdConnectProvider): Promise<Checked<ProviderMetadata>> {
71
71
  const cache = getCache(metadataCache, ctx.config);
72
72
  const now = ctx.clock.now().getTime();
73
73
  const cached = cache.get(provider.issuer);
@@ -1,4 +1,5 @@
1
- // OpenID Connect sign-in: the authorization code flow with PKCE S256 (RFC 7636), a one-time state and a nonce.
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 { findOidcProvider, getOidcRedirectUri, readOidcClient, type OidcContext } from "./context.js";
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 { checkIdTokenClaims, decodeIdToken, isSignedBy, type IdentityClaims } from "./id-token.js";
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
- const metadata = await getProviderMetadata(ctx, provider);
59
- if (!metadata.ok) return fail(provider, metadata.reason);
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(metadata.value.authorizationEndpoint);
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 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);
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: claims.value.subject, email, displayName: claims.value.displayName });
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
- * 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;
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
- console.warn(`@softure-ai/auth: OpenID Connect sign-in with ${provider.id} failed: ${reason}`);
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