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