@softure-ai/auth 0.2.5 → 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.
Files changed (175) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +98 -10
  3. package/dist/contract.d.ts +5 -1
  4. package/dist/contract.d.ts.map +1 -1
  5. package/dist/contract.js.map +1 -1
  6. package/dist/index.d.ts +72 -4
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +9 -4
  9. package/dist/index.js.map +1 -1
  10. package/dist/messages/en.d.ts +10 -0
  11. package/dist/messages/en.d.ts.map +1 -1
  12. package/dist/messages/en.js +10 -0
  13. package/dist/messages/en.js.map +1 -1
  14. package/dist/messages/index.d.ts +8 -0
  15. package/dist/messages/index.d.ts.map +1 -1
  16. package/dist/next/actions.d.ts +5 -0
  17. package/dist/next/actions.d.ts.map +1 -1
  18. package/dist/next/actions.js +26 -15
  19. package/dist/next/actions.js.map +1 -1
  20. package/dist/next/index.d.ts +2 -1
  21. package/dist/next/index.d.ts.map +1 -1
  22. package/dist/next/index.js +2 -1
  23. package/dist/next/index.js.map +1 -1
  24. package/dist/next/oidc-cookie.d.ts +7 -0
  25. package/dist/next/oidc-cookie.d.ts.map +1 -0
  26. package/dist/next/oidc-cookie.js +25 -0
  27. package/dist/next/oidc-cookie.js.map +1 -0
  28. package/dist/next/oidc-login-url.d.ts +4 -0
  29. package/dist/next/oidc-login-url.d.ts.map +1 -0
  30. package/dist/next/oidc-login-url.js +13 -0
  31. package/dist/next/oidc-login-url.js.map +1 -0
  32. package/dist/next/oidc-route.d.ts +7 -0
  33. package/dist/next/oidc-route.d.ts.map +1 -0
  34. package/dist/next/oidc-route.js +48 -0
  35. package/dist/next/oidc-route.js.map +1 -0
  36. package/dist/next/pages.d.ts +5 -0
  37. package/dist/next/pages.d.ts.map +1 -1
  38. package/dist/next/pages.js +19 -4
  39. package/dist/next/pages.js.map +1 -1
  40. package/dist/next/params.d.ts +2 -0
  41. package/dist/next/params.d.ts.map +1 -1
  42. package/dist/next/params.js +2 -0
  43. package/dist/next/params.js.map +1 -1
  44. package/dist/next/previous-session.d.ts +6 -0
  45. package/dist/next/previous-session.d.ts.map +1 -0
  46. package/dist/next/previous-session.js +23 -0
  47. package/dist/next/previous-session.js.map +1 -0
  48. package/dist/options.d.ts +99 -1
  49. package/dist/options.d.ts.map +1 -1
  50. package/dist/options.js +80 -0
  51. package/dist/options.js.map +1 -1
  52. package/dist/proxy/index.d.ts.map +1 -1
  53. package/dist/proxy/index.js +3 -1
  54. package/dist/proxy/index.js.map +1 -1
  55. package/dist/schema.d.ts +235 -0
  56. package/dist/schema.d.ts.map +1 -1
  57. package/dist/schema.js +22 -3
  58. package/dist/schema.js.map +1 -1
  59. package/dist/server/change-password.d.ts +1 -1
  60. package/dist/server/change-password.d.ts.map +1 -1
  61. package/dist/server/change-password.js +3 -0
  62. package/dist/server/change-password.js.map +1 -1
  63. package/dist/server/health.d.ts.map +1 -1
  64. package/dist/server/health.js +2 -0
  65. package/dist/server/health.js.map +1 -1
  66. package/dist/server/index.d.ts +1 -0
  67. package/dist/server/index.d.ts.map +1 -1
  68. package/dist/server/index.js +1 -0
  69. package/dist/server/index.js.map +1 -1
  70. package/dist/server/login.d.ts +1 -1
  71. package/dist/server/login.d.ts.map +1 -1
  72. package/dist/server/login.js +3 -1
  73. package/dist/server/login.js.map +1 -1
  74. package/dist/server/oidc/accounts.d.ts +12 -0
  75. package/dist/server/oidc/accounts.d.ts.map +1 -0
  76. package/dist/server/oidc/accounts.js +71 -0
  77. package/dist/server/oidc/accounts.js.map +1 -0
  78. package/dist/server/oidc/context.d.ts +37 -0
  79. package/dist/server/oidc/context.d.ts.map +1 -0
  80. package/dist/server/oidc/context.js +34 -0
  81. package/dist/server/oidc/context.js.map +1 -0
  82. package/dist/server/oidc/discovery.d.ts +24 -0
  83. package/dist/server/oidc/discovery.d.ts.map +1 -0
  84. package/dist/server/oidc/discovery.js +109 -0
  85. package/dist/server/oidc/discovery.js.map +1 -0
  86. package/dist/server/oidc/flow.d.ts +49 -0
  87. package/dist/server/oidc/flow.d.ts.map +1 -0
  88. package/dist/server/oidc/flow.js +168 -0
  89. package/dist/server/oidc/flow.js.map +1 -0
  90. package/dist/server/oidc/id-token.d.ts +36 -0
  91. package/dist/server/oidc/id-token.d.ts.map +1 -0
  92. package/dist/server/oidc/id-token.js +105 -0
  93. package/dist/server/oidc/id-token.js.map +1 -0
  94. package/dist/server/oidc/index.d.ts +4 -0
  95. package/dist/server/oidc/index.d.ts.map +1 -0
  96. package/dist/server/oidc/index.js +4 -0
  97. package/dist/server/oidc/index.js.map +1 -0
  98. package/dist/server/oidc/token-request.d.ts +13 -0
  99. package/dist/server/oidc/token-request.d.ts.map +1 -0
  100. package/dist/server/oidc/token-request.js +49 -0
  101. package/dist/server/oidc/token-request.js.map +1 -0
  102. package/dist/server/password-reset.d.ts +1 -1
  103. package/dist/server/password-reset.d.ts.map +1 -1
  104. package/dist/server/password-reset.js +3 -2
  105. package/dist/server/password-reset.js.map +1 -1
  106. package/dist/server/privacy.d.ts +8 -0
  107. package/dist/server/privacy.d.ts.map +1 -1
  108. package/dist/server/privacy.js +16 -4
  109. package/dist/server/privacy.js.map +1 -1
  110. package/dist/server/rate-limits.d.ts +4 -1
  111. package/dist/server/rate-limits.d.ts.map +1 -1
  112. package/dist/server/rate-limits.js +10 -3
  113. package/dist/server/rate-limits.js.map +1 -1
  114. package/dist/server/register.js +1 -1
  115. package/dist/server/register.js.map +1 -1
  116. package/dist/server/switches.d.ts +1 -1
  117. package/dist/server/switches.d.ts.map +1 -1
  118. package/dist/server/switches.js +3 -1
  119. package/dist/server/switches.js.map +1 -1
  120. package/dist/testing/account.js +1 -1
  121. package/dist/testing/account.js.map +1 -1
  122. package/dist/testing/index.d.ts +1 -0
  123. package/dist/testing/index.d.ts.map +1 -1
  124. package/dist/testing/index.js +3 -1
  125. package/dist/testing/index.js.map +1 -1
  126. package/dist/testing/oidc-provider.d.ts +64 -0
  127. package/dist/testing/oidc-provider.d.ts.map +1 -0
  128. package/dist/testing/oidc-provider.js +181 -0
  129. package/dist/testing/oidc-provider.js.map +1 -0
  130. package/dist/ui/index.d.ts +1 -0
  131. package/dist/ui/index.d.ts.map +1 -1
  132. package/dist/ui/index.js +1 -0
  133. package/dist/ui/index.js.map +1 -1
  134. package/dist/ui/oidc-sign-in.d.ts +25 -0
  135. package/dist/ui/oidc-sign-in.d.ts.map +1 -0
  136. package/dist/ui/oidc-sign-in.js +17 -0
  137. package/dist/ui/oidc-sign-in.js.map +1 -0
  138. package/migrations/0005_create_identities_and_oidc_states.sql +34 -0
  139. package/module.json +3 -2
  140. package/package.json +2 -2
  141. package/src/contract.ts +10 -1
  142. package/src/index.ts +20 -5
  143. package/src/messages/en.ts +10 -0
  144. package/src/next/actions.ts +23 -14
  145. package/src/next/index.ts +2 -0
  146. package/src/next/oidc-cookie.ts +31 -0
  147. package/src/next/oidc-login-url.ts +14 -0
  148. package/src/next/oidc-route.ts +48 -0
  149. package/src/next/pages.tsx +38 -11
  150. package/src/next/params.ts +3 -0
  151. package/src/next/previous-session.ts +23 -0
  152. package/src/options.ts +86 -1
  153. package/src/proxy/index.ts +3 -1
  154. package/src/schema.ts +28 -3
  155. package/src/server/change-password.ts +3 -0
  156. package/src/server/health.ts +2 -0
  157. package/src/server/index.ts +17 -0
  158. package/src/server/login.ts +2 -1
  159. package/src/server/oidc/accounts.ts +82 -0
  160. package/src/server/oidc/context.ts +56 -0
  161. package/src/server/oidc/discovery.ts +133 -0
  162. package/src/server/oidc/flow.ts +196 -0
  163. package/src/server/oidc/id-token.ts +124 -0
  164. package/src/server/oidc/index.ts +14 -0
  165. package/src/server/oidc/token-request.ts +59 -0
  166. package/src/server/password-reset.ts +3 -2
  167. package/src/server/privacy.ts +24 -4
  168. package/src/server/rate-limits.ts +11 -3
  169. package/src/server/register.ts +1 -1
  170. package/src/server/switches.ts +2 -1
  171. package/src/testing/account.ts +1 -1
  172. package/src/testing/index.ts +10 -1
  173. package/src/testing/oidc-provider.ts +248 -0
  174. package/src/ui/index.ts +1 -0
  175. package/src/ui/oidc-sign-in.tsx +60 -0
@@ -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 the app passed a sender, i.e. whether password reset is offered at all. */
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
- return getAuthOptions(config).passwordReset.send !== undefined;
27
+ const options = getAuthOptions(config);
28
+ return options.password.enabled && options.passwordReset.send !== undefined;
28
29
  }
29
30
 
30
31
  export interface PasswordResetRequestInput {
@@ -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 and a pending reset link. Secrets never leave: no password hash and no token hash.
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
- return ok({ account: account ?? null, roles, sessions: userSessions, passwordReset: passwordReset ?? null });
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`). Checked once
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 isResetOn = getAuthOptions(config).passwordReset.send !== undefined;
43
- const required = Object.values(BUCKETS).filter((name) => isResetOn || !RESET_BUCKETS.has(name));
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(
@@ -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
  });
@@ -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();
@@ -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
  });
@@ -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. Server-only; never imported by the module's runtime code.
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/index.ts CHANGED
@@ -15,3 +15,4 @@ export {
15
15
  ResetPasswordForm,
16
16
  type ResetPasswordFormProps,
17
17
  } from "./auth-forms.js";
18
+ export { OidcSignIn, type OidcSignInProps, type OidcSignInProvider, type OidcSignInSlot } from "./oidc-sign-in.js";
@@ -0,0 +1,60 @@
1
+ "use client";
2
+
3
+ import { formatMessage } from "@softure-ai/core";
4
+ import { Button, type ButtonVariant, type ClassNames, createSlotClassGetter, FormError } from "@softure-ai/ui";
5
+ import type { AuthMessages } from "../messages/index.js";
6
+
7
+ // The OpenID Connect buttons: one small form per provider, posting `provider` and `next` to the start action
8
+ // (`oidcSignInAction` of `@softure-ai/auth/next`), so it works without JavaScript. Copy comes from messages.
9
+
10
+ export type OidcSignInSlot = "root" | "form" | "submit" | "divider";
11
+
12
+ export interface OidcSignInProvider {
13
+ readonly id: string;
14
+ /** Shown in `messages.oidc.signInWith`, e.g. Google. */
15
+ readonly name: string;
16
+ }
17
+
18
+ export interface OidcSignInProps {
19
+ readonly action: (formData: FormData) => void | Promise<void>;
20
+ readonly providers: readonly OidcSignInProvider[];
21
+ readonly messages: AuthMessages;
22
+ /** Where to go after the sign-in; checked again on the server. */
23
+ readonly next?: string;
24
+ /** A failed sign-in's message, e.g. from the login page's `?oidc_error=`. */
25
+ readonly error?: string;
26
+ /** Shows `messages.oidc.divider` under the buttons, before a password form. */
27
+ readonly hasDivider?: boolean;
28
+ readonly classNames?: ClassNames<OidcSignInSlot>;
29
+ readonly unstyled?: boolean;
30
+ /** The buttons' look; `secondary` by default. */
31
+ readonly submitVariant?: ButtonVariant;
32
+ }
33
+
34
+ const DEFAULT_CLASSES: Readonly<Record<OidcSignInSlot, string>> = {
35
+ root: "sft:flex sft:flex-col sft:gap-3 sft:font-sans",
36
+ form: "sft:flex sft:flex-col",
37
+ // The button styles itself; the slot only carries the app's class.
38
+ submit: "",
39
+ divider: "sft:m-0 sft:text-center sft:text-sm sft:text-muted",
40
+ };
41
+
42
+ export function OidcSignIn(props: OidcSignInProps) {
43
+ const { action, providers, messages, next, error, hasDivider = false, classNames, unstyled, submitVariant = "secondary" } = props;
44
+ const slot = createSlotClassGetter({ defaults: DEFAULT_CLASSES, classNames, unstyled });
45
+ return (
46
+ <div className={slot("root")}>
47
+ <FormError message={error} unstyled={unstyled} />
48
+ {providers.map((provider) => (
49
+ <form key={provider.id} action={action} className={slot("form")}>
50
+ <input type="hidden" name="provider" value={provider.id} />
51
+ {next === undefined ? null : <input type="hidden" name="next" value={next} />}
52
+ <Button type="submit" variant={submitVariant} fullWidth classNames={{ root: slot("submit") }} unstyled={unstyled}>
53
+ {formatMessage(messages.oidc.signInWith, { provider: provider.name })}
54
+ </Button>
55
+ </form>
56
+ ))}
57
+ {hasDivider ? <p className={slot("divider")}>{messages.oidc.divider}</p> : null}
58
+ </div>
59
+ );
60
+ }