@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
package/src/contract.ts CHANGED
@@ -16,7 +16,14 @@ export type AuthErrorCode =
16
16
  | "auth.unauthenticated"
17
17
  | "auth.forbidden"
18
18
  | "auth.reset_token_invalid"
19
- | "auth.password_reset_unavailable";
19
+ | "auth.password_reset_unavailable"
20
+ | "auth.oidc_failed"
21
+ | "auth.oidc_cancelled"
22
+ | "auth.oidc_not_allowed"
23
+ | "auth.oidc_no_account";
24
+
25
+ /** Why an OpenID Connect sign-in did not open a session; the login page shows it (`?oidc_error=`). */
26
+ export type OidcSignInErrorCode = Extract<AuthErrorCode, `auth.oidc_${string}`>;
20
27
 
21
28
  /** Every code an auth form can show: its own, the rate limiter's and the generic ones. */
22
29
  export type AuthFormErrorCode = AuthErrorCode | Extract<SecurityErrorCode, "security.rate_limited" | "security.client_unidentified"> | CoreErrorCode;
@@ -46,6 +53,8 @@ export interface RegisteredEvent {
46
53
  readonly consent: { readonly acceptedAt: Date } | null;
47
54
  /** The declared `registrationFields` the form sent, by name; client input, so validate it. */
48
55
  readonly fields: Readonly<Record<string, string>>;
56
+ /** The OpenID Connect provider of a sign-in that created the account; null for the register form. */
57
+ readonly oidcProvider: string | null;
49
58
  }
50
59
 
51
60
  /** The fields of the auth forms that can carry their own error. */
package/src/index.ts CHANGED
@@ -23,7 +23,8 @@ export const REGISTRATION_CLOSED_ENV = "SOFTURE_SWITCH_AUTH_REGISTRATION_CLOSED"
23
23
  * Rate limit buckets auth consumes, with defaults to spread into `security({ buckets })`:
24
24
  * `register` and `login` per client address, `login-account` per email, `change-password` per user,
25
25
  * `password-reset` (link requests) and `password-reset-confirm` (new passwords) per client address,
26
- * and `password-reset-account` per email, which bounds the mails one address can receive.
26
+ * `password-reset-account` per email, which bounds the mails one address can receive, and `oidc-start` and
27
+ * `oidc-callback` (OpenID Connect sign-ins started and completed) per client address.
27
28
  */
28
29
  export const AUTH_RATE_LIMIT_BUCKETS = {
29
30
  register: { limit: 5, windowMinutes: 15, key: "ip" },
@@ -33,6 +34,8 @@ export const AUTH_RATE_LIMIT_BUCKETS = {
33
34
  "password-reset": { limit: 10, windowMinutes: 15, key: "ip" },
34
35
  "password-reset-account": { limit: 3, windowMinutes: 15, key: "account" },
35
36
  "password-reset-confirm": { limit: 10, windowMinutes: 15, key: "ip" },
37
+ "oidc-start": { limit: 20, windowMinutes: 15, key: "ip" },
38
+ "oidc-callback": { limit: 20, windowMinutes: 15, key: "ip" },
36
39
  } as const satisfies Readonly<Record<string, RateLimitBucketInput>>;
37
40
 
38
41
  /**
@@ -42,10 +45,10 @@ export const AUTH_RATE_LIMIT_BUCKETS = {
42
45
  export const auth = defineModule({
43
46
  manifest: {
44
47
  id: MODULE_ID,
45
- version: "0.2.5",
48
+ version: "0.2.6",
46
49
  dependsOn: { security: "^0.2.0", mailing: "^0.2.0?", ops: "^0.2.0?", jobs: "^0.1.1?" },
47
50
  dbSchema: "auth",
48
- tables: ["users", "sessions", "user_roles", "password_resets"],
51
+ tables: ["users", "sessions", "user_roles", "password_resets", "identities", "oidc_states"],
49
52
  env: [
50
53
  {
51
54
  name: REGISTRATION_CLOSED_ENV,
@@ -70,6 +73,7 @@ export const auth = defineModule({
70
73
  { kind: "page", path: "app/forgot-password/page.tsx", export: "ForgotPasswordPage" },
71
74
  { kind: "page", path: "app/reset-password/page.tsx", export: "ResetPasswordPage" },
72
75
  { kind: "route-handler", path: "app/api/auth/session/route.ts", export: "getSessionRoute" },
76
+ { kind: "route-handler", path: "app/api/auth/oidc/[provider]/callback/route.ts", export: "oidcCallbackRoute" },
73
77
  { kind: "middleware", path: "proxy.ts", export: "createAuthGuard" },
74
78
  ],
75
79
  privacy: { exports: true, deletes: true },
@@ -89,11 +93,22 @@ export type {
89
93
  AuthFormState,
90
94
  AuthUser,
91
95
  NewSession,
96
+ OidcSignInErrorCode,
92
97
  RegisteredEvent,
93
98
  SignedIn,
94
99
  } from "./contract.js";
95
100
  export { authMessages, getAuthErrorMessage, type AuthMessages } from "./messages/index.js";
96
- export type { AuthOptions, AuthOptionsInput, OnRegisteredHook, RewriteRedirect, RewriteRedirectContext, ScryptParams } from "./options.js";
101
+ export {
102
+ OIDC_PROVIDER_ID_PATTERN,
103
+ type AuthOptions,
104
+ type AuthOptionsInput,
105
+ type OidcProvider,
106
+ type OidcProviderInput,
107
+ type OnRegisteredHook,
108
+ type RewriteRedirect,
109
+ type RewriteRedirectContext,
110
+ type ScryptParams,
111
+ } from "./options.js";
97
112
  export {
98
113
  consolePasswordResetSender,
99
114
  type PasswordResetDetails,
@@ -103,4 +118,4 @@ export {
103
118
  export { getSessionCookie, type SessionCookie } from "./session-cookie.js";
104
119
  export { toSafeNextPath } from "./safe-next-path.js";
105
120
  export { ADMIN_ROLE, ROLE_NAME_PATTERN } from "./roles.js";
106
- export { passwordResets, sessions, userRoles, users } from "./schema.js";
121
+ export { identities, oidcStates, passwordResets, sessions, userRoles, users } from "./schema.js";
@@ -64,6 +64,12 @@ export const en = {
64
64
  logout: {
65
65
  submit: "Log out",
66
66
  },
67
+ oidc: {
68
+ /** The button of an OpenID Connect provider; `{provider}` is its `name` (e.g. Google). */
69
+ signInWith: "Sign in with {provider}",
70
+ /** Between the provider buttons and the password form. */
71
+ divider: "or",
72
+ },
67
73
  errors: {
68
74
  auth: {
69
75
  invalid_credentials: "The email or password is incorrect.",
@@ -79,6 +85,10 @@ export const en = {
79
85
  forbidden: "You do not have access to this.",
80
86
  reset_token_invalid: "This link has expired or has already been used. Ask for a new one.",
81
87
  password_reset_unavailable: "Password reset is not available.",
88
+ oidc_failed: "Signing in did not work. Try again.",
89
+ oidc_cancelled: "Signing in was cancelled.",
90
+ oidc_not_allowed: "This account may not sign in here.",
91
+ oidc_no_account: "There is no account for this sign-in. Ask for access.",
82
92
  },
83
93
  security: {
84
94
  rate_limited: "Too many attempts. Wait a few minutes and try again.",
@@ -21,10 +21,14 @@ import { loginUser } from "../server/login.js";
21
21
  import { getAuthRoutes } from "../server/options.js";
22
22
  import { deliverPasswordReset, requestPasswordReset, resetPassword } from "../server/password-reset.js";
23
23
  import { registerUser } from "../server/register.js";
24
+ import { startOidcSignIn } from "../server/oidc/flow.js";
24
25
  import { logoutSession } from "../server/sessions.js";
25
26
  import { getAuthContext } from "./context.js";
27
+ import { writeOidcStateCookie } from "./oidc-cookie.js";
28
+ import { getOidcErrorLoginPath } from "./oidc-login-url.js";
26
29
  import { PASSWORD_RESET_DONE_PARAM } from "./params.js";
27
- import { clearSessionCookie, readLegacySessionToken, readSessionToken, writeSessionCookie } from "./session-cookie.js";
30
+ import { endPreviousSession, readHeldTokens } from "./previous-session.js";
31
+ import { clearSessionCookie, readSessionToken, writeSessionCookie } from "./session-cookie.js";
28
32
 
29
33
  /** Longer values are cut: the server functions refuse them anyway, and nothing huge is echoed back. */
30
34
  const MAX_FIELD_LENGTH = 4096;
@@ -44,6 +48,7 @@ const registerInput = z.object({ email: text, password: text, next: nextPath, co
44
48
  const changePasswordInput = z.object({ currentPassword: text, newPassword: text });
45
49
  const forgotPasswordInput = z.object({ email: text });
46
50
  const resetPasswordInput = z.object({ token: text, newPassword: text });
51
+ const oidcSignInInput = z.object({ provider: text, next: nextPath });
47
52
 
48
53
  const FIELD_OF: Partial<Record<AuthFormErrorCode, AuthFormField>> = {
49
54
  "auth.email_invalid": "email",
@@ -208,21 +213,25 @@ export async function resetPasswordAction(_previous: AuthFormState, formData: Fo
208
213
  redirect(await resolveRedirectTarget(config, `${getAuthRoutes(config).login}?${PASSWORD_RESET_DONE_PARAM}=1`));
209
214
  }
210
215
 
211
- /** Every session token the browser holds: the current cookie's and a legacy session's. */
212
- async function readHeldTokens(config: SoftureConfig): Promise<string[]> {
213
- const tokens = [await readSessionToken(config), await readLegacySessionToken(config)];
214
- return [...new Set(tokens.filter((token) => token !== null))];
215
- }
216
+ /**
217
+ * Starts an OpenID Connect sign-in: the provider button's form posts `provider` and `next`. The state goes into a
218
+ * short-lived cookie and the browser to the provider; a failure goes back to the login page, which shows its code.
219
+ */
220
+ export async function oidcSignInAction(formData: FormData): Promise<void> {
221
+ const config = getSoftureConfig();
222
+ const input = readForm(oidcSignInInput, formData);
223
+ const client = identifyClient({ config }, await headers());
224
+ if (!client.ok) redirect(getOidcErrorLoginPath(config, client.error, input.next));
216
225
 
217
- /** Ends the sessions the browser held before a login or register, so they cannot be reused. */
218
- async function endPreviousSession(config: SoftureConfig): Promise<void> {
219
- for (const previous of await readHeldTokens(config)) {
220
- try {
221
- await logoutSession(await getAuthContext(config), previous);
222
- } catch (error) {
223
- reportFailure("ending the previous session", error);
224
- }
226
+ let result;
227
+ try {
228
+ result = await startOidcSignIn(await getAuthContext(config), { provider: input.provider, next: input.next, clientKey: client.value });
229
+ } catch (error) {
230
+ result = { ok: false as const, error: reportFailure("starting an OpenID Connect sign-in", error) };
225
231
  }
232
+ if (!result.ok) redirect(getOidcErrorLoginPath(config, result.error, input.next));
233
+ await writeOidcStateCookie(config, result.value.state, result.value.maxAgeSeconds);
234
+ redirect(result.value.url);
226
235
  }
227
236
 
228
237
  /** Where to go after logout: a path on this app, checked like login's `next`. */
package/src/next/index.ts CHANGED
@@ -6,6 +6,7 @@ export {
6
6
  loginAction,
7
7
  logoutAction,
8
8
  type LogoutInput,
9
+ oidcSignInAction,
9
10
  registerAction,
10
11
  resetPasswordAction,
11
12
  } from "./actions.js";
@@ -30,5 +31,6 @@ export {
30
31
  type RegisterPageOptions,
31
32
  ResetPasswordPage,
32
33
  } from "./pages.js";
34
+ export { oidcCallbackRoute } from "./oidc-route.js";
33
35
  export { getSessionRoute } from "./route.js";
34
36
  export type { PageSearchParams } from "./search-params.js";
@@ -0,0 +1,31 @@
1
+ // The cookie that ties an OpenID Connect sign-in to the browser that started it: it holds the state until the
2
+ // provider sends the browser back. Host-only, httpOnly, `SameSite=Lax` (the callback is a top-level GET from the
3
+ // provider's site, which Lax lets through) and as short-lived as the sign-in itself.
4
+ import type { SoftureConfig } from "@softure-ai/core";
5
+ import { cookies } from "next/headers";
6
+ import { getSessionCookie } from "../session-cookie.js";
7
+ import { getAuthOptions } from "../server/options.js";
8
+
9
+ function getOidcCookie(config: SoftureConfig) {
10
+ const { secure } = getSessionCookie(config);
11
+ const name = `${secure ? "__Host-" : ""}${getAuthOptions(config).cookie.name}_oidc`;
12
+ return { name, secure, httpOnly: true, sameSite: "lax" as const, path: "/" };
13
+ }
14
+
15
+ export async function writeOidcStateCookie(config: SoftureConfig, state: string, maxAgeSeconds: number): Promise<void> {
16
+ const { name, ...attributes } = getOidcCookie(config);
17
+ (await cookies()).set(name, state, { ...attributes, maxAge: maxAgeSeconds });
18
+ }
19
+
20
+ /** The state of the sign-in this browser started, or null. */
21
+ export async function readOidcStateCookie(config: SoftureConfig): Promise<string | null> {
22
+ const value = (await cookies()).get(getOidcCookie(config).name)?.value;
23
+ return value === undefined || value === "" ? null : value;
24
+ }
25
+
26
+ /** Removes the cookie: a state is used once, whatever the callback came to. */
27
+ export async function clearOidcStateCookie(config: SoftureConfig): Promise<void> {
28
+ const { name, ...attributes } = getOidcCookie(config);
29
+ const store = await cookies();
30
+ if (store.get(name) !== undefined) store.set(name, "", { ...attributes, maxAge: 0 });
31
+ }
@@ -0,0 +1,14 @@
1
+ // The login page a failed OpenID Connect sign-in goes back to, with the error code it shows.
2
+ import type { SoftureConfig } from "@softure-ai/core";
3
+ import { toSafeNextPath } from "../safe-next-path.js";
4
+ import { getAuthRoutes } from "../server/options.js";
5
+ import { OIDC_ERROR_PARAM } from "./params.js";
6
+
7
+ /** `<login>?oidc_error=<code>[&next=…]`, a path on this app. */
8
+ export function getOidcErrorLoginPath(config: SoftureConfig, code: string, next?: string): string {
9
+ const routes = getAuthRoutes(config);
10
+ const query = new URLSearchParams({ [OIDC_ERROR_PARAM]: code });
11
+ const target = toSafeNextPath(next, routes.afterLogin);
12
+ if (target !== routes.afterLogin) query.set("next", target);
13
+ return `${routes.login}?${query.toString()}`;
14
+ }
@@ -0,0 +1,48 @@
1
+ // The OpenID Connect callback, mounted with one line:
2
+ // `app/api/auth/oidc/[provider]/callback/route.ts → export { oidcCallbackRoute as GET } from "@softure-ai/auth/next";`
3
+ // The provider sends the browser here with `code` and `state` (or `error`). The answer is always a `303`: to the
4
+ // sign-in's `next` with a new session cookie, or to the login page with `?oidc_error=<code>`. The state cookie is
5
+ // cleared either way, and the URL (it carries the code) is never sent on as a referrer.
6
+ import { errorLogLabel, safeError, type SoftureConfig } from "@softure-ai/core";
7
+ import { getSoftureConfig } from "@softure-ai/core/next";
8
+ import { identifyClient } from "@softure-ai/security/server";
9
+ import { resolveRedirectTarget } from "../redirect-target.js";
10
+ import { completeOidcSignIn } from "../server/oidc/flow.js";
11
+ import { getAuthContext } from "./context.js";
12
+ import { clearOidcStateCookie, readOidcStateCookie } from "./oidc-cookie.js";
13
+ import { getOidcErrorLoginPath } from "./oidc-login-url.js";
14
+ import { endPreviousSession } from "./previous-session.js";
15
+ import { writeSessionCookie } from "./session-cookie.js";
16
+
17
+ const NO_STORE = { "cache-control": "no-store", "referrer-policy": "no-referrer" };
18
+
19
+ function seeOther(config: SoftureConfig, path: string): Response {
20
+ return new Response(null, { status: 303, headers: { ...NO_STORE, location: new URL(path, config.appOrigin).toString() } });
21
+ }
22
+
23
+ /** `GET /api/auth/oidc/<provider>/callback`. */
24
+ export async function oidcCallbackRoute(request: Request, route: { readonly params: Promise<{ readonly provider: string }> }): Promise<Response> {
25
+ const config = getSoftureConfig();
26
+ const { provider } = await route.params;
27
+ const query = new URL(request.url).searchParams;
28
+ const browserState = await readOidcStateCookie(config);
29
+ await clearOidcStateCookie(config);
30
+ const client = identifyClient({ config }, request.headers);
31
+ if (!client.ok) return seeOther(config, getOidcErrorLoginPath(config, client.error));
32
+
33
+ try {
34
+ const result = await completeOidcSignIn(await getAuthContext(config), {
35
+ provider,
36
+ params: { state: query.get("state"), code: query.get("code"), error: query.get("error") },
37
+ browserState,
38
+ clientKey: client.value,
39
+ });
40
+ if (!result.ok) return seeOther(config, getOidcErrorLoginPath(config, result.error));
41
+ await endPreviousSession(config);
42
+ await writeSessionCookie(config, result.value.session);
43
+ return seeOther(config, await resolveRedirectTarget(config, result.value.next));
44
+ } catch (error) {
45
+ console.error(`@softure-ai/auth: completing an OpenID Connect sign-in failed: ${errorLogLabel(error)}`);
46
+ return seeOther(config, getOidcErrorLoginPath(config, safeError(error).error));
47
+ }
48
+ }
@@ -1,6 +1,7 @@
1
1
  // Pages ready to mount with one line: `export { LoginPage as default } from "@softure-ai/auth/next"`.
2
2
  // Server components: they read the config and the session, and render the forms from `../ui`.
3
3
  import type { SoftureConfig } from "@softure-ai/core";
4
+ import type { AuthFormErrorCode } from "../contract.js";
4
5
  import { getSoftureConfig } from "@softure-ai/core/next";
5
6
  import { Card } from "@softure-ai/ui";
6
7
  import { notFound, redirect } from "next/navigation";
@@ -10,12 +11,15 @@ import { toSafeNextPath } from "../safe-next-path.js";
10
11
  import { getAuthOptions, getAuthRoutes } from "../server/options.js";
11
12
  import { findPasswordResetUser, isPasswordResetEnabled, RESET_TOKEN_PARAM } from "../server/password-reset.js";
12
13
  import { isRegistrationClosed } from "../server/switches.js";
14
+ import { getAuthErrorMessage } from "../messages/index.js";
15
+ import { getOidcProviders } from "../server/oidc/context.js";
13
16
  import { ChangePasswordForm, ForgotPasswordForm, LoginForm, RegisterForm, ResetPasswordForm } from "../ui/auth-forms.js";
14
- import { changePasswordAction, forgotPasswordAction, loginAction, registerAction, resetPasswordAction } from "./actions.js";
17
+ import { OidcSignIn } from "../ui/oidc-sign-in.js";
18
+ import { changePasswordAction, forgotPasswordAction, loginAction, oidcSignInAction, registerAction, resetPasswordAction } from "./actions.js";
15
19
  import { getAuthContext } from "./context.js";
16
20
  import { getCurrentUser, requireUser } from "./current-user.js";
17
21
  import { getAuthMessages } from "./messages.js";
18
- import { PASSWORD_RESET_DONE_PARAM } from "./params.js";
22
+ import { OIDC_ERROR_PARAM, PASSWORD_RESET_DONE_PARAM } from "./params.js";
19
23
  import { toUrlSearchParams } from "./search-params.js";
20
24
 
21
25
  type SearchParams = Promise<Record<string, string | string[] | undefined>>;
@@ -27,6 +31,8 @@ export interface AuthPageProps {
27
31
  const LAYOUT_CLASS = "sft:mx-auto sft:box-border sft:w-full sft:sm:max-w-md sft:px-4 sft:py-4";
28
32
  const FOOTER_CLASS = "sft:m-0 sft:text-sm sft:text-muted";
29
33
  const LINK_CLASS = "sft:font-medium sft:text-accent";
34
+ /** An error code as auth writes it into `?oidc_error=`; anything else in the URL is not shown. */
35
+ const ERROR_CODE = /^[a-z]+\.[a-z_]{1,64}$/;
30
36
  /** The server keeps 512 characters of a registration field; nothing longer is echoed into the page. */
31
37
  const MAX_CARRIED_LENGTH = 512;
32
38
 
@@ -54,24 +60,43 @@ async function redirectSignedIn(config: SoftureConfig, next: string, searchParam
54
60
  redirect(await resolveRedirectTarget(config, next, toUrlSearchParams(await searchParams)));
55
61
  }
56
62
 
63
+ /**
64
+ * The login page: the OpenID Connect buttons when the app configured providers, then the password form unless
65
+ * `password.enabled` is false. A failed provider sign-in comes back here with `?oidc_error=`, shown above the buttons.
66
+ */
57
67
  export async function LoginPage({ searchParams }: AuthPageProps) {
58
68
  const config = getSoftureConfig();
59
69
  const routes = getAuthRoutes(config);
60
70
  const next = await readNext(searchParams, routes.afterLogin);
61
71
  if ((await getCurrentUser()) !== null) await redirectSignedIn(config, next, searchParams);
62
72
  const messages = getAuthMessages(config);
73
+ const isPasswordOn = getAuthOptions(config).password.enabled;
74
+ const providers = getOidcProviders(config).map((provider) => ({ id: provider.id, name: provider.name }));
75
+ const oidcError = await readParam(searchParams, OIDC_ERROR_PARAM);
63
76
  const isClosed = await isRegistrationClosed(await getAuthContext(config));
64
77
  return (
65
78
  <AuthLayout title={messages.login.title} lead={messages.login.lead}>
66
- <LoginForm
67
- action={loginAction}
68
- messages={messages}
69
- locale={config.locale}
70
- next={next}
71
- registerHref={isClosed ? undefined : routes.register}
72
- forgotPasswordHref={isPasswordResetEnabled(config) ? routes.forgotPassword : undefined}
73
- notice={(await readParam(searchParams, PASSWORD_RESET_DONE_PARAM)) === "1" ? messages.resetPassword.success : undefined}
74
- />
79
+ {providers.length === 0 ? null : (
80
+ <OidcSignIn
81
+ action={oidcSignInAction}
82
+ providers={providers}
83
+ messages={messages}
84
+ next={next}
85
+ error={oidcError !== undefined && ERROR_CODE.test(oidcError) ? getAuthErrorMessage(messages, oidcError as AuthFormErrorCode) : undefined}
86
+ hasDivider={isPasswordOn}
87
+ />
88
+ )}
89
+ {!isPasswordOn ? null : (
90
+ <LoginForm
91
+ action={loginAction}
92
+ messages={messages}
93
+ locale={config.locale}
94
+ next={next}
95
+ registerHref={isClosed ? undefined : routes.register}
96
+ forgotPasswordHref={isPasswordResetEnabled(config) ? routes.forgotPassword : undefined}
97
+ notice={(await readParam(searchParams, PASSWORD_RESET_DONE_PARAM)) === "1" ? messages.resetPassword.success : undefined}
98
+ />
99
+ )}
75
100
  </AuthLayout>
76
101
  );
77
102
  }
@@ -147,8 +172,10 @@ async function readCarriedFields(searchParams: SearchParams | undefined, declare
147
172
  return carried;
148
173
  }
149
174
 
175
+ /** Not found when `password.enabled` is false: there is no password to change. */
150
176
  export async function ChangePasswordPage() {
151
177
  const config = getSoftureConfig();
178
+ if (!getAuthOptions(config).password.enabled) notFound();
152
179
  const routes = getAuthRoutes(config);
153
180
  await requireUser({ next: routes.changePassword });
154
181
  const messages = getAuthMessages(config);
@@ -2,3 +2,6 @@
2
2
 
3
3
  /** Set on the login page after a password reset, so it confirms the change. */
4
4
  export const PASSWORD_RESET_DONE_PARAM = "reset";
5
+
6
+ /** Set on the login page after a failed OpenID Connect sign-in: the error code it shows. */
7
+ export const OIDC_ERROR_PARAM = "oidc_error";
@@ -0,0 +1,23 @@
1
+ // The sessions a browser already holds when it signs in again, ended before the new cookie is written, so they
2
+ // cannot be reused. Shared by the login and register actions and the OpenID Connect callback.
3
+ import { errorLogLabel, type SoftureConfig } from "@softure-ai/core";
4
+ import { logoutSession } from "../server/sessions.js";
5
+ import { getAuthContext } from "./context.js";
6
+ import { readLegacySessionToken, readSessionToken } from "./session-cookie.js";
7
+
8
+ /** Every session token the browser holds: the current cookie's and a legacy session's. */
9
+ export async function readHeldTokens(config: SoftureConfig): Promise<string[]> {
10
+ const tokens = [await readSessionToken(config), await readLegacySessionToken(config)];
11
+ return [...new Set(tokens.filter((token) => token !== null))];
12
+ }
13
+
14
+ /** Ends the sessions the browser held before a sign-in. A failure is logged: the new session still opens. */
15
+ export async function endPreviousSession(config: SoftureConfig): Promise<void> {
16
+ for (const previous of await readHeldTokens(config)) {
17
+ try {
18
+ await logoutSession(await getAuthContext(config), previous);
19
+ } catch (error) {
20
+ console.error(`@softure-ai/auth: ending the previous session failed: ${errorLogLabel(error)}`);
21
+ }
22
+ }
23
+ }
package/src/options.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  // The options an app passes to `auth({ ... })` in softure.config.ts, parsed at startup.
2
- import type { ModuleContext, SoftureConfig } from "@softure-ai/core";
2
+ import type { FetchFunction, ModuleContext, SoftureConfig } from "@softure-ai/core";
3
3
  import type { Queryable } from "@softure-ai/db";
4
4
  import { z } from "zod";
5
5
  import type { RegisteredEvent } from "./contract.js";
@@ -86,9 +86,76 @@ function parseAdminEmailList(raw: string): string[] {
86
86
  return emails;
87
87
  }
88
88
 
89
+ /** A provider id: the path segment of its callback (`/api/auth/oidc/<id>/callback`) and the key of its identities. */
90
+ export const OIDC_PROVIDER_ID_PATTERN = /^[a-z][a-z0-9-]{0,31}$/;
91
+ const GOOGLE_ISSUER = "https://accounts.google.com";
92
+ const ENV_NAME = /^[A-Z][A-Z0-9_]{0,127}$/;
93
+ const LOCAL_HOSTS: ReadonlySet<string> = new Set(["localhost", "127.0.0.1", "[::1]"]);
94
+
95
+ /** An https URL, or http on the local machine (a development identity provider). */
96
+ export function isSecureEndpoint(value: string): boolean {
97
+ let url: URL;
98
+ try {
99
+ url = new URL(value);
100
+ } catch {
101
+ return false;
102
+ }
103
+ if (url.username !== "" || url.password !== "" || url.hash !== "") return false;
104
+ return url.protocol === "https:" || (url.protocol === "http:" && LOCAL_HOSTS.has(url.hostname));
105
+ }
106
+
107
+ const domainSchema = z.string().trim().toLowerCase().regex(DOMAIN, "must be a lowercase host name such as example.com");
108
+
109
+ 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 }))
143
+ .refine((provider) => provider.allowedDomains.length + provider.allowedEmails.length > 0, {
144
+ message: "needs allowedDomains or allowedEmails: an OpenID Connect sign-in is limited to them",
145
+ path: ["allowedDomains"],
146
+ });
147
+
148
+ export type OidcProviderInput = z.input<typeof oidcProviderSchema>;
149
+ export type OidcProvider = z.output<typeof oidcProviderSchema>;
150
+
89
151
  export const authOptionsSchema = z.strictObject({
90
152
  password: z
91
153
  .strictObject({
154
+ /**
155
+ * The password form and routes (login, register, change, reset). False leaves OpenID Connect as the only way in:
156
+ * the pages are not found and the server functions refuse.
157
+ */
158
+ enabled: z.boolean().default(true),
92
159
  /** Shortest password a user may set (characters). */
93
160
  minLength: z.number().int().min(8).max(128).default(10),
94
161
  /** Hash cost; memory per hash is 128 * cost * blockSize bytes. Raising it rehashes each password at its owner's next login. */
@@ -167,6 +234,21 @@ export const authOptionsSchema = z.strictObject({
167
234
  ttlMinutes: z.number().int().min(5).max(1440).default(60),
168
235
  })
169
236
  .prefault({}),
237
+ /** Sign-in with OpenID Connect providers (e.g. Google), limited to allowed domains or emails. Off without providers. */
238
+ oidc: z
239
+ .strictObject({
240
+ providers: z
241
+ .array(oidcProviderSchema)
242
+ .refine((providers) => new Set(providers.map((provider) => provider.id)).size === providers.length, "must not repeat a provider id")
243
+ .default([]),
244
+ /** How long a started sign-in may take at the provider. */
245
+ stateTtlMinutes: z.number().int().min(1).max(60).default(10),
246
+ /** Timeout of each call to a provider (discovery, keys, token). */
247
+ httpTimeoutMs: z.number().int().min(1000).max(60_000).default(10_000),
248
+ /** The `fetch` the provider calls go through; tests pass a fake provider's. */
249
+ fetch: z.custom<FetchFunction>((value) => typeof value === "function", "must be a function").optional(),
250
+ })
251
+ .prefault({}),
170
252
  /** Called after an account is created, in the same transaction (e.g. to store the consent). */
171
253
  onRegistered: z.custom<OnRegisteredHook>((value) => typeof value === "function", "must be a function").optional(),
172
254
  /** Rewrites the path of every auth redirect (e.g. `tagRedirect` from `@softure-ai/analytics/next`). */
@@ -175,6 +257,9 @@ export const authOptionsSchema = z.strictObject({
175
257
  if (options.passwordReset.enqueue !== undefined && options.passwordReset.send === undefined) {
176
258
  context.addIssue({ code: "custom", path: ["passwordReset", "enqueue"], message: "needs passwordReset.send, which the job calls" });
177
259
  }
260
+ if (!options.password.enabled && options.oidc.providers.length === 0) {
261
+ context.addIssue({ code: "custom", path: ["password", "enabled"], message: "needs an oidc provider: without passwords nobody could sign in" });
262
+ }
178
263
  const legacy = options.legacySession?.cookieName;
179
264
  const base = options.cookie.name;
180
265
  if (legacy !== undefined && [base, `__Host-${base}`, `__Secure-${base}`].includes(legacy)) {
@@ -43,6 +43,8 @@ export interface AuthGuardOptions {
43
43
 
44
44
  /** Mounted at a fixed path by the module (manifest `mount`); it answers `{ user: null }` without a session. */
45
45
  const SESSION_ROUTE = "/api/auth/session";
46
+ /** The OpenID Connect callbacks (`/api/auth/oidc/<provider>/callback`): a visitor arrives there without a session. */
47
+ const OIDC_ROUTES = "/api/auth/oidc";
46
48
 
47
49
  export type AuthGuard = (request: Request) => Response | null;
48
50
 
@@ -53,7 +55,7 @@ export function createAuthGuard(config: SoftureConfig, options: AuthGuardOptions
53
55
  const prefixes = options.protect.map((prefix) => normalizePrefix(prefix, "protected"));
54
56
  const changePassword = normalizePrefix(routes.changePassword, "protected");
55
57
  // Auth's own public pages: guarding them would send a visitor from the login page to itself.
56
- const publicPaths = [routes.login, routes.register, routes.forgotPassword, routes.resetPassword, SESSION_ROUTE].map((path) =>
58
+ const publicPaths = [routes.login, routes.register, routes.forgotPassword, routes.resetPassword, SESSION_ROUTE, OIDC_ROUTES].map((path) =>
57
59
  normalizePrefix(path, "excluded"),
58
60
  );
59
61
  const excluded = (options.exclude ?? []).map((prefix) => normalizePrefix(prefix, "excluded"));
package/src/schema.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  // Drizzle view of the module's tables (migrations/0001_create_users_and_sessions.sql,
2
- // 0002_create_user_roles.sql, 0003_create_password_resets.sql and the users.created_at index of
3
- // 0004_index_users_created_at.sql). The migrations are the source of truth; this file only types
2
+ // 0002_create_user_roles.sql, 0003_create_password_resets.sql, the users.created_at index of
3
+ // 0004_index_users_created_at.sql and 0005_create_identities_and_oidc_states.sql). The migrations are the source of truth; this file only types
4
4
  // the queries. App tables may reference `users.id`.
5
- import { pgSchema, primaryKey, text, timestamp, uuid } from "drizzle-orm/pg-core";
5
+ import { pgSchema, primaryKey, text, timestamp, unique, uuid } from "drizzle-orm/pg-core";
6
6
 
7
7
  export const authSchema = pgSchema("auth");
8
8
 
@@ -43,3 +43,28 @@ export const passwordResets = authSchema.table("password_resets", {
43
43
  createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
44
44
  expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
45
45
  });
46
+
47
+ export const identities = authSchema.table(
48
+ "identities",
49
+ {
50
+ provider: text("provider").notNull(),
51
+ subject: text("subject").notNull(),
52
+ userId: uuid("user_id")
53
+ .notNull()
54
+ .references(() => users.id, { onDelete: "cascade" }),
55
+ email: text("email").notNull(),
56
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
57
+ lastLoginAt: timestamp("last_login_at", { withTimezone: true }).notNull(),
58
+ },
59
+ (table) => [primaryKey({ columns: [table.provider, table.subject] }), unique("identities_user_provider_key").on(table.userId, table.provider)],
60
+ );
61
+
62
+ export const oidcStates = authSchema.table("oidc_states", {
63
+ stateHash: text("state_hash").primaryKey(),
64
+ provider: text("provider").notNull(),
65
+ nonce: text("nonce").notNull(),
66
+ codeVerifier: text("code_verifier").notNull(),
67
+ nextPath: text("next_path").notNull(),
68
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
69
+ expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
70
+ });
@@ -21,6 +21,7 @@ export interface ChangePasswordInput {
21
21
 
22
22
  export type ChangePasswordErrorCode =
23
23
  | "auth.unauthenticated"
24
+ | "auth.forbidden"
24
25
  | "auth.current_password_invalid"
25
26
  | "auth.password_unchanged"
26
27
  | "auth.password_too_short"
@@ -32,6 +33,8 @@ export type ChangePasswordResult = Ok<undefined> | Err<ChangePasswordErrorCode>
32
33
  export async function changePassword(ctx: AuthContext, input: ChangePasswordInput): Promise<ChangePasswordResult> {
33
34
  const options = getAuthOptions(ctx.config);
34
35
  assertAuthBuckets(ctx.config);
36
+ // Passwords are off: there is none to change.
37
+ if (!options.password.enabled) return err("auth.forbidden");
35
38
  const user = await findSessionUser(ctx, input.sessionToken);
36
39
  if (user === null) return err("auth.unauthenticated");
37
40
 
@@ -12,5 +12,7 @@ export const checkAuthTables: HealthCheck = async (context) => {
12
12
  await db.execute(sql`select 1 from auth.sessions limit 0`);
13
13
  await db.execute(sql`select 1 from auth.user_roles limit 0`);
14
14
  await db.execute(sql`select 1 from auth.password_resets limit 0`);
15
+ await db.execute(sql`select 1 from auth.identities limit 0`);
16
+ await db.execute(sql`select 1 from auth.oidc_states limit 0`);
15
17
  return ok();
16
18
  };