@softure-ai/auth 0.0.0-stage → 0.1.7

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 (255) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/LICENSE +21 -0
  3. package/README.md +490 -2
  4. package/dist/contract.d.ts +46 -0
  5. package/dist/contract.d.ts.map +1 -0
  6. package/dist/contract.js +2 -0
  7. package/dist/contract.js.map +1 -0
  8. package/dist/index.d.ts +194 -0
  9. package/dist/index.d.ts.map +1 -0
  10. package/dist/index.js +84 -0
  11. package/dist/index.js.map +1 -0
  12. package/dist/mailing/index.d.ts +2 -0
  13. package/dist/mailing/index.d.ts.map +1 -0
  14. package/dist/mailing/index.js +4 -0
  15. package/dist/mailing/index.js.map +1 -0
  16. package/dist/mailing/reset-mail.d.ts +27 -0
  17. package/dist/mailing/reset-mail.d.ts.map +1 -0
  18. package/dist/mailing/reset-mail.js +55 -0
  19. package/dist/mailing/reset-mail.js.map +1 -0
  20. package/dist/messages/en.d.ts +98 -0
  21. package/dist/messages/en.d.ts.map +1 -0
  22. package/dist/messages/en.js +93 -0
  23. package/dist/messages/en.js.map +1 -0
  24. package/dist/messages/index.d.ts +201 -0
  25. package/dist/messages/index.d.ts.map +1 -0
  26. package/dist/messages/index.js +11 -0
  27. package/dist/messages/index.js.map +1 -0
  28. package/dist/messages/pl.d.ts +3 -0
  29. package/dist/messages/pl.d.ts.map +1 -0
  30. package/dist/messages/pl.js +92 -0
  31. package/dist/messages/pl.js.map +1 -0
  32. package/dist/next/actions.d.ts +19 -0
  33. package/dist/next/actions.d.ts.map +1 -0
  34. package/dist/next/actions.js +231 -0
  35. package/dist/next/actions.js.map +1 -0
  36. package/dist/next/context.d.ts +4 -0
  37. package/dist/next/context.d.ts.map +1 -0
  38. package/dist/next/context.js +13 -0
  39. package/dist/next/context.js.map +1 -0
  40. package/dist/next/current-user.d.ts +34 -0
  41. package/dist/next/current-user.d.ts.map +1 -0
  42. package/dist/next/current-user.js +77 -0
  43. package/dist/next/current-user.js.map +1 -0
  44. package/dist/next/index.d.ts +8 -0
  45. package/dist/next/index.d.ts.map +1 -0
  46. package/dist/next/index.js +9 -0
  47. package/dist/next/index.js.map +1 -0
  48. package/dist/next/logout-button.d.ts +7 -0
  49. package/dist/next/logout-button.d.ts.map +1 -0
  50. package/dist/next/logout-button.js +12 -0
  51. package/dist/next/logout-button.js.map +1 -0
  52. package/dist/next/messages.d.ts +5 -0
  53. package/dist/next/messages.d.ts.map +1 -0
  54. package/dist/next/messages.js +7 -0
  55. package/dist/next/messages.js.map +1 -0
  56. package/dist/next/pages.d.ts +31 -0
  57. package/dist/next/pages.d.ts.map +1 -0
  58. package/dist/next/pages.js +118 -0
  59. package/dist/next/pages.js.map +1 -0
  60. package/dist/next/params.d.ts +3 -0
  61. package/dist/next/params.d.ts.map +1 -0
  62. package/dist/next/params.js +4 -0
  63. package/dist/next/params.js.map +1 -0
  64. package/dist/next/route.d.ts +3 -0
  65. package/dist/next/route.d.ts.map +1 -0
  66. package/dist/next/route.js +17 -0
  67. package/dist/next/route.js.map +1 -0
  68. package/dist/next/search-params.d.ts +5 -0
  69. package/dist/next/search-params.d.ts.map +1 -0
  70. package/dist/next/search-params.js +13 -0
  71. package/dist/next/search-params.js.map +1 -0
  72. package/dist/next/session-cookie.d.ts +11 -0
  73. package/dist/next/session-cookie.d.ts.map +1 -0
  74. package/dist/next/session-cookie.js +71 -0
  75. package/dist/next/session-cookie.js.map +1 -0
  76. package/dist/options.d.ts +72 -0
  77. package/dist/options.d.ts.map +1 -0
  78. package/dist/options.js +115 -0
  79. package/dist/options.js.map +1 -0
  80. package/dist/password-reset-sender.d.ts +21 -0
  81. package/dist/password-reset-sender.d.ts.map +1 -0
  82. package/dist/password-reset-sender.js +12 -0
  83. package/dist/password-reset-sender.js.map +1 -0
  84. package/dist/proxy/index.d.ts +14 -0
  85. package/dist/proxy/index.d.ts.map +1 -0
  86. package/dist/proxy/index.js +59 -0
  87. package/dist/proxy/index.js.map +1 -0
  88. package/dist/redirect-target.d.ts +7 -0
  89. package/dist/redirect-target.d.ts.map +1 -0
  90. package/dist/redirect-target.js +25 -0
  91. package/dist/redirect-target.js.map +1 -0
  92. package/dist/roles.d.ts +5 -0
  93. package/dist/roles.d.ts.map +1 -0
  94. package/dist/roles.js +6 -0
  95. package/dist/roles.js.map +1 -0
  96. package/dist/safe-next-path.d.ts +5 -0
  97. package/dist/safe-next-path.d.ts.map +1 -0
  98. package/dist/safe-next-path.js +25 -0
  99. package/dist/safe-next-path.js.map +1 -0
  100. package/dist/schema.d.ts +302 -0
  101. package/dist/schema.d.ts.map +1 -0
  102. package/dist/schema.js +37 -0
  103. package/dist/schema.js.map +1 -0
  104. package/dist/scripts/index.d.ts +3 -0
  105. package/dist/scripts/index.d.ts.map +1 -0
  106. package/dist/scripts/index.js +5 -0
  107. package/dist/scripts/index.js.map +1 -0
  108. package/dist/scripts/role-scripts.d.ts +15 -0
  109. package/dist/scripts/role-scripts.d.ts.map +1 -0
  110. package/dist/scripts/role-scripts.js +76 -0
  111. package/dist/scripts/role-scripts.js.map +1 -0
  112. package/dist/scripts/temporary-password.d.ts +12 -0
  113. package/dist/scripts/temporary-password.d.ts.map +1 -0
  114. package/dist/scripts/temporary-password.js +47 -0
  115. package/dist/scripts/temporary-password.js.map +1 -0
  116. package/dist/server/change-password.d.ts +14 -0
  117. package/dist/server/change-password.d.ts.map +1 -0
  118. package/dist/server/change-password.js +50 -0
  119. package/dist/server/change-password.js.map +1 -0
  120. package/dist/server/health.d.ts +3 -0
  121. package/dist/server/health.d.ts.map +1 -0
  122. package/dist/server/health.js +15 -0
  123. package/dist/server/health.js.map +1 -0
  124. package/dist/server/index.d.ts +12 -0
  125. package/dist/server/index.d.ts.map +1 -0
  126. package/dist/server/index.js +14 -0
  127. package/dist/server/index.js.map +1 -0
  128. package/dist/server/login.d.ts +14 -0
  129. package/dist/server/login.d.ts.map +1 -0
  130. package/dist/server/login.js +50 -0
  131. package/dist/server/login.js.map +1 -0
  132. package/dist/server/options.d.ts +19 -0
  133. package/dist/server/options.d.ts.map +1 -0
  134. package/dist/server/options.js +50 -0
  135. package/dist/server/options.js.map +1 -0
  136. package/dist/server/password-reset.d.ts +54 -0
  137. package/dist/server/password-reset.d.ts.map +1 -0
  138. package/dist/server/password-reset.js +134 -0
  139. package/dist/server/password-reset.js.map +1 -0
  140. package/dist/server/password.d.ts +25 -0
  141. package/dist/server/password.d.ts.map +1 -0
  142. package/dist/server/password.js +93 -0
  143. package/dist/server/password.js.map +1 -0
  144. package/dist/server/privacy.d.ts +33 -0
  145. package/dist/server/privacy.d.ts.map +1 -0
  146. package/dist/server/privacy.js +52 -0
  147. package/dist/server/privacy.js.map +1 -0
  148. package/dist/server/rate-limits.d.ts +22 -0
  149. package/dist/server/rate-limits.d.ts.map +1 -0
  150. package/dist/server/rate-limits.js +45 -0
  151. package/dist/server/rate-limits.js.map +1 -0
  152. package/dist/server/reauthenticate.d.ts +7 -0
  153. package/dist/server/reauthenticate.d.ts.map +1 -0
  154. package/dist/server/reauthenticate.js +16 -0
  155. package/dist/server/reauthenticate.js.map +1 -0
  156. package/dist/server/register.d.ts +23 -0
  157. package/dist/server/register.d.ts.map +1 -0
  158. package/dist/server/register.js +64 -0
  159. package/dist/server/register.js.map +1 -0
  160. package/dist/server/roles.d.ts +25 -0
  161. package/dist/server/roles.d.ts.map +1 -0
  162. package/dist/server/roles.js +56 -0
  163. package/dist/server/roles.js.map +1 -0
  164. package/dist/server/session-token.d.ts +12 -0
  165. package/dist/server/session-token.d.ts.map +1 -0
  166. package/dist/server/session-token.js +22 -0
  167. package/dist/server/session-token.js.map +1 -0
  168. package/dist/server/sessions.d.ts +24 -0
  169. package/dist/server/sessions.d.ts.map +1 -0
  170. package/dist/server/sessions.js +50 -0
  171. package/dist/server/sessions.js.map +1 -0
  172. package/dist/server/switches.d.ts +9 -0
  173. package/dist/server/switches.d.ts.map +1 -0
  174. package/dist/server/switches.js +34 -0
  175. package/dist/server/switches.js.map +1 -0
  176. package/dist/server/validation.d.ts +10 -0
  177. package/dist/server/validation.d.ts.map +1 -0
  178. package/dist/server/validation.js +32 -0
  179. package/dist/server/validation.js.map +1 -0
  180. package/dist/session-cookie.d.ts +14 -0
  181. package/dist/session-cookie.d.ts.map +1 -0
  182. package/dist/session-cookie.js +31 -0
  183. package/dist/session-cookie.js.map +1 -0
  184. package/dist/testing/account.d.ts +17 -0
  185. package/dist/testing/account.d.ts.map +1 -0
  186. package/dist/testing/account.js +31 -0
  187. package/dist/testing/account.js.map +1 -0
  188. package/dist/testing/index.d.ts +2 -0
  189. package/dist/testing/index.d.ts.map +1 -0
  190. package/dist/testing/index.js +4 -0
  191. package/dist/testing/index.js.map +1 -0
  192. package/dist/ui/auth-forms.d.ts +64 -0
  193. package/dist/ui/auth-forms.d.ts.map +1 -0
  194. package/dist/ui/auth-forms.js +67 -0
  195. package/dist/ui/auth-forms.js.map +1 -0
  196. package/dist/ui/index.d.ts +2 -0
  197. package/dist/ui/index.d.ts.map +1 -0
  198. package/dist/ui/index.js +4 -0
  199. package/dist/ui/index.js.map +1 -0
  200. package/migrations/0001_create_users_and_sessions.sql +25 -0
  201. package/migrations/0002_create_user_roles.sql +10 -0
  202. package/migrations/0003_create_password_resets.sql +15 -0
  203. package/migrations/0004_index_users_created_at.sql +5 -0
  204. package/module.json +34 -0
  205. package/package.json +97 -4
  206. package/src/contract.ts +67 -0
  207. package/src/index.ts +100 -0
  208. package/src/mailing/index.ts +3 -0
  209. package/src/mailing/reset-mail.ts +73 -0
  210. package/src/messages/en.ts +92 -0
  211. package/src/messages/index.ts +15 -0
  212. package/src/messages/pl.ts +93 -0
  213. package/src/next/actions.ts +240 -0
  214. package/src/next/context.ts +14 -0
  215. package/src/next/current-user.ts +90 -0
  216. package/src/next/index.ts +33 -0
  217. package/src/next/logout-button.tsx +22 -0
  218. package/src/next/messages.ts +9 -0
  219. package/src/next/next-modules.d.ts +16 -0
  220. package/src/next/pages.tsx +223 -0
  221. package/src/next/params.ts +4 -0
  222. package/src/next/route.ts +17 -0
  223. package/src/next/search-params.ts +14 -0
  224. package/src/next/session-cookie.ts +79 -0
  225. package/src/options.ts +154 -0
  226. package/src/password-reset-sender.ts +33 -0
  227. package/src/proxy/index.ts +85 -0
  228. package/src/redirect-target.ts +24 -0
  229. package/src/roles.ts +7 -0
  230. package/src/safe-next-path.ts +21 -0
  231. package/src/schema.ts +45 -0
  232. package/src/scripts/index.ts +8 -0
  233. package/src/scripts/role-scripts.ts +98 -0
  234. package/src/scripts/temporary-password.ts +62 -0
  235. package/src/server/change-password.ts +64 -0
  236. package/src/server/health.ts +16 -0
  237. package/src/server/index.ts +46 -0
  238. package/src/server/login.ts +61 -0
  239. package/src/server/options.ts +64 -0
  240. package/src/server/password-reset.ts +164 -0
  241. package/src/server/password.ts +108 -0
  242. package/src/server/privacy.ts +70 -0
  243. package/src/server/rate-limits.ts +51 -0
  244. package/src/server/reauthenticate.ts +16 -0
  245. package/src/server/register.ts +87 -0
  246. package/src/server/roles.ts +72 -0
  247. package/src/server/session-token.ts +25 -0
  248. package/src/server/sessions.ts +65 -0
  249. package/src/server/switches.ts +31 -0
  250. package/src/server/validation.ts +37 -0
  251. package/src/session-cookie.ts +47 -0
  252. package/src/testing/account.ts +43 -0
  253. package/src/testing/index.ts +3 -0
  254. package/src/ui/auth-forms.tsx +383 -0
  255. package/src/ui/index.ts +16 -0
@@ -0,0 +1,31 @@
1
+ // Runtime switches of the module. `auth.registration_closed` is read through the switch-reader
2
+ // contract of `@softure-ai/core`: when the app defines it in `@softure-ai/feature-switches`, the
3
+ // value stored in the switches panel applies. Otherwise auth falls back to its declared default (an
4
+ // option) with an env override, so an app without feature-switches keeps working.
5
+ import { readSwitch, type ModuleContext } from "@softure-ai/core";
6
+ import { REGISTRATION_CLOSED_ENV, REGISTRATION_CLOSED_SWITCH } from "../index.js";
7
+ import { getAuthOptions } from "./options.js";
8
+
9
+ const ON = new Set(["true", "1"]);
10
+ let hasReportedBadValue = false;
11
+ const OFF = new Set(["false", "0"]);
12
+
13
+ /**
14
+ * Whether registration is closed. The app's switch provider answers first (env override, stored
15
+ * value, default and fail mode as it defines them). Without one, the env override wins over the
16
+ * declared default; a value it cannot read closes registration (fail closed) and is logged once, by
17
+ * name, never by value.
18
+ */
19
+ export async function isRegistrationClosed(ctx: ModuleContext, env: Readonly<Record<string, string | undefined>> = process.env): Promise<boolean> {
20
+ const reading = await readSwitch(ctx, REGISTRATION_CLOSED_SWITCH);
21
+ if (reading.kind === "value") return reading.isEnabled;
22
+ const override = env[REGISTRATION_CLOSED_ENV]?.trim().toLowerCase();
23
+ if (override === undefined || override === "") return getAuthOptions(ctx.config).registrationClosed;
24
+ if (ON.has(override)) return true;
25
+ if (OFF.has(override)) return false;
26
+ if (!hasReportedBadValue) {
27
+ hasReportedBadValue = true;
28
+ console.error(`@softure-ai/auth: ${REGISTRATION_CLOSED_ENV} must be true, false, 1 or 0; registration stays closed`);
29
+ }
30
+ return true;
31
+ }
@@ -0,0 +1,37 @@
1
+ // Input rules for emails and new passwords. Expected failures are codes the form shows next to the field.
2
+ import { err, ok, type Err, type Ok } from "@softure-ai/core";
3
+ import { z } from "zod";
4
+ import { MAX_PASSWORD_LENGTH } from "./password.js";
5
+
6
+ const MAX_EMAIL_LENGTH = 254;
7
+ const emailSchema = z.email();
8
+
9
+ /** Trims and lowercases an email, so two spellings are one account. */
10
+ export function normalizeEmail(email: string): string {
11
+ return email.trim().toLowerCase();
12
+ }
13
+
14
+ /** The normalized email, or `auth.email_invalid`. */
15
+ export function parseEmail(email: string): Ok<string> | Err<"auth.email_invalid"> {
16
+ const normalized = normalizeEmail(email);
17
+ if (normalized.length > MAX_EMAIL_LENGTH || !emailSchema.safeParse(normalized).success) {
18
+ return err("auth.email_invalid");
19
+ }
20
+ return ok(normalized);
21
+ }
22
+
23
+ /** A password's length as the policy counts it: characters after NFC, not UTF-16 units. */
24
+ export function getPasswordLength(password: string): number {
25
+ return [...password.normalize("NFC")].length;
26
+ }
27
+
28
+ /** Whether a new password fits the policy. */
29
+ export function checkNewPassword(
30
+ password: string,
31
+ minLength: number,
32
+ ): Ok<undefined> | Err<"auth.password_too_short" | "auth.password_too_long"> {
33
+ const length = getPasswordLength(password);
34
+ if (length < minLength) return err("auth.password_too_short");
35
+ if (length > MAX_PASSWORD_LENGTH) return err("auth.password_too_long");
36
+ return ok();
37
+ }
@@ -0,0 +1,47 @@
1
+ // The session cookie (roadmap ID-3, unknown 2). A secure cookie gets the prefix browsers enforce:
2
+ // `__Host-` when it is host-only (no Domain, Path=/), `__Secure-` when it is shared with subdomains
3
+ // through `cookie.domain`. On plain HTTP (local development) it keeps the bare name, because
4
+ // browsers refuse prefixed cookies without Secure.
5
+ import type { SoftureConfig } from "@softure-ai/core";
6
+ import { getAuthOptions } from "./server/options.js";
7
+
8
+ const DAY_SECONDS = 24 * 60 * 60;
9
+
10
+ export interface SessionCookie {
11
+ readonly name: string;
12
+ readonly domain: string | undefined;
13
+ readonly secure: boolean;
14
+ readonly httpOnly: true;
15
+ readonly sameSite: "lax";
16
+ readonly path: "/";
17
+ readonly maxAgeSeconds: number;
18
+ }
19
+
20
+ export function getSessionCookie(config: SoftureConfig): SessionCookie {
21
+ const options = getAuthOptions(config);
22
+ const secure = options.cookie.secure ?? config.appOrigin.startsWith("https:");
23
+ const domain = options.cookie.domain;
24
+ const prefix = !secure ? "" : domain === undefined ? "__Host-" : "__Secure-";
25
+ return {
26
+ name: `${prefix}${options.cookie.name}`,
27
+ domain,
28
+ secure,
29
+ httpOnly: true,
30
+ sameSite: "lax",
31
+ path: "/",
32
+ maxAgeSeconds: options.session.ttlDays * DAY_SECONDS,
33
+ };
34
+ }
35
+
36
+ /** The session token in a `Cookie` header, or null. */
37
+ export function readSessionToken(cookieHeader: string | null, cookieName: string): string | null {
38
+ if (cookieHeader === null) return null;
39
+ for (const part of cookieHeader.split(";")) {
40
+ const separator = part.indexOf("=");
41
+ if (separator !== -1 && part.slice(0, separator).trim() === cookieName) {
42
+ const value = part.slice(separator + 1).trim();
43
+ return value === "" ? null : value;
44
+ }
45
+ }
46
+ return null;
47
+ }
@@ -0,0 +1,43 @@
1
+ // An account written straight to auth's tables, hashed the way registration hashes it. No
2
+ // `onRegistered` hook runs and no session is opened: the test signs in through the login form.
3
+ import type { Queryable } from "@softure-ai/db";
4
+ import type { AuthUser } from "../contract.js";
5
+ import { DEFAULT_SCRYPT_COST, type ScryptParams } from "../options.js";
6
+ import { userRoles, users } from "../schema.js";
7
+ import { hashPassword } from "../server/password.js";
8
+ import { parseEmail } from "../server/validation.js";
9
+
10
+ /** Auth's own hash parameters when the app sets none (`password.scrypt` in `auth({ ... })`). */
11
+ const DEFAULT_SCRYPT: ScryptParams = { cost: DEFAULT_SCRYPT_COST, blockSize: 8, parallelization: 1 };
12
+
13
+ export interface TestAccountInput {
14
+ readonly email: string;
15
+ readonly password: string;
16
+ /** Rows of `auth.user_roles`, e.g. `["admin"]`. */
17
+ readonly roles?: readonly string[];
18
+ /** The app's hash parameters (`getAuthOptions(config).password.scrypt`), so its login does not rehash. */
19
+ readonly scrypt?: ScryptParams;
20
+ }
21
+
22
+ /**
23
+ * Creates an account and its roles in one transaction and returns it. The email is normalized as
24
+ * registration normalizes it. An invalid or taken email throws: in test setup it is a bug of the test.
25
+ */
26
+ export async function createTestAccount(db: Queryable, input: TestAccountInput): Promise<AuthUser> {
27
+ const email = parseEmail(input.email);
28
+ if (!email.ok) throw new Error(`createTestAccount: "${input.email}" is not a valid email`);
29
+ const passwordHash = await hashPassword(input.password, input.scrypt ?? DEFAULT_SCRYPT);
30
+ const now = new Date();
31
+
32
+ return db.transaction(async (tx) => {
33
+ const [row] = await tx
34
+ .insert(users)
35
+ .values({ email: email.value, passwordHash, createdAt: now, passwordChangedAt: now })
36
+ .onConflictDoNothing({ target: users.email })
37
+ .returning();
38
+ if (row === undefined) throw new Error(`createTestAccount: an account with the email "${email.value}" already exists`);
39
+ const roles = input.roles ?? [];
40
+ if (roles.length > 0) await tx.insert(userRoles).values(roles.map((role) => ({ userId: row.id, role, grantedAt: now })));
41
+ return { id: row.id, email: row.email, createdAt: row.createdAt };
42
+ });
43
+ }
@@ -0,0 +1,3 @@
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.
3
+ export { createTestAccount, type TestAccountInput } from "./account.js";
@@ -0,0 +1,383 @@
1
+ "use client";
2
+
3
+ import { formatMessage, type Locale } from "@softure-ai/core";
4
+ import { Button, type ButtonVariant, Checkbox, type ClassNames, createSlotClassGetter, FormError, PasswordField, TextField } from "@softure-ai/ui";
5
+ import { type ReactNode, useActionState } from "react";
6
+ import { type AuthFormField, type AuthFormState, INITIAL_AUTH_FORM_STATE } from "../contract.js";
7
+ import { type AuthMessages, getAuthErrorMessage } from "../messages/index.js";
8
+
9
+ // The auth forms. Each submits straight to its server action through `useActionState`, so it
10
+ // works before (and without) JavaScript, and a server-side redirect after login is followed.
11
+ // Copy comes from the module's messages; styling only from @softure-ai/ui classes and tokens.
12
+
13
+ export type AuthFormAction = (previous: AuthFormState, formData: FormData) => Promise<AuthFormState>;
14
+
15
+ export type AuthFormSlot = "root" | "form" | "footer" | "link" | "notice" | "submit";
16
+
17
+ interface AuthFormBaseProps {
18
+ readonly action: AuthFormAction;
19
+ readonly messages: AuthMessages;
20
+ /** Locale of the built-in copy of the ui primitives. */
21
+ readonly locale?: Locale;
22
+ readonly classNames?: ClassNames<AuthFormSlot>;
23
+ readonly unstyled?: boolean;
24
+ /** The submit button's look; `primary` by default. Its class goes in `classNames.submit`. */
25
+ readonly submitVariant?: ButtonVariant;
26
+ }
27
+
28
+ const DEFAULT_CLASSES: Readonly<Record<AuthFormSlot, string>> = {
29
+ root: "sft:flex sft:flex-col sft:gap-3 sft:font-sans",
30
+ form: "sft:flex sft:flex-col sft:gap-3",
31
+ footer: "sft:m-0 sft:text-sm sft:text-muted",
32
+ link: "sft:font-medium sft:text-accent",
33
+ notice: "sft:m-0 sft:text-sm sft:text-success",
34
+ // The button styles itself; the slot only carries the app's class.
35
+ submit: "",
36
+ };
37
+
38
+ /** The error of one field, or of the form when no field owns it. */
39
+ function useErrors(state: AuthFormState, messages: AuthMessages) {
40
+ const message = state.error === undefined ? undefined : getAuthErrorMessage(messages, state.error);
41
+ return {
42
+ at: (field: AuthFormField) => (state.field === field ? message : undefined),
43
+ form: state.field === undefined ? message : undefined,
44
+ };
45
+ }
46
+
47
+ function FormShell({
48
+ formAction,
49
+ isPending,
50
+ submitLabel,
51
+ pendingLabel,
52
+ formError,
53
+ footer,
54
+ slot,
55
+ unstyled,
56
+ submitVariant = "primary",
57
+ children,
58
+ }: {
59
+ formAction: (formData: FormData) => void;
60
+ isPending: boolean;
61
+ submitLabel: string;
62
+ pendingLabel: string;
63
+ formError: string | undefined;
64
+ footer?: ReactNode;
65
+ slot: (part: AuthFormSlot) => string | undefined;
66
+ unstyled: boolean | undefined;
67
+ submitVariant: ButtonVariant | undefined;
68
+ children: ReactNode;
69
+ }) {
70
+ return (
71
+ <div className={slot("root")}>
72
+ <form action={formAction} className={slot("form")}>
73
+ {children}
74
+ <FormError message={formError} unstyled={unstyled} />
75
+ <Button type="submit" variant={submitVariant} fullWidth pending={isPending} classNames={{ root: slot("submit") }} unstyled={unstyled}>
76
+ {isPending ? pendingLabel : submitLabel}
77
+ </Button>
78
+ </form>
79
+ {footer}
80
+ </div>
81
+ );
82
+ }
83
+
84
+ export interface LoginFormProps extends AuthFormBaseProps {
85
+ /** Where to go after login; checked again on the server. */
86
+ readonly next?: string;
87
+ /** Link to the register page; omitted when registration is not offered. */
88
+ readonly registerHref?: string;
89
+ /** Link to the password reset request page; omitted when reset is not offered. */
90
+ readonly forgotPasswordHref?: string;
91
+ /** A confirmation shown under the form, e.g. after a password reset. */
92
+ readonly notice?: string;
93
+ }
94
+
95
+ export function LoginForm({ action, messages, locale, next, registerHref, forgotPasswordHref, notice, classNames, unstyled, submitVariant }: LoginFormProps) {
96
+ const [state, formAction, isPending] = useActionState(action, INITIAL_AUTH_FORM_STATE);
97
+ const errors = useErrors(state, messages);
98
+ const slot = createSlotClassGetter({ defaults: DEFAULT_CLASSES, classNames, unstyled });
99
+ const footer =
100
+ registerHref === undefined && forgotPasswordHref === undefined && notice === undefined ? undefined : (
101
+ <>
102
+ {notice === undefined ? null : (
103
+ <p role="status" className={slot("notice")}>
104
+ {notice}
105
+ </p>
106
+ )}
107
+ {forgotPasswordHref === undefined ? null : (
108
+ <p className={slot("footer")}>
109
+ <a href={forgotPasswordHref} className={slot("link")}>
110
+ {messages.login.forgotPassword}
111
+ </a>
112
+ </p>
113
+ )}
114
+ {registerHref === undefined ? null : (
115
+ <p className={slot("footer")}>
116
+ {messages.login.noAccount}{" "}
117
+ <a href={registerHref} className={slot("link")}>
118
+ {messages.login.registerLink}
119
+ </a>
120
+ </p>
121
+ )}
122
+ </>
123
+ );
124
+ return (
125
+ <FormShell
126
+ formAction={formAction}
127
+ isPending={isPending}
128
+ submitLabel={messages.login.submit}
129
+ pendingLabel={messages.login.pending}
130
+ formError={errors.form}
131
+ footer={footer}
132
+ slot={slot}
133
+ unstyled={unstyled}
134
+ submitVariant={submitVariant}
135
+ >
136
+ {next === undefined ? null : <input type="hidden" name="next" value={next} />}
137
+ <TextField
138
+ name="email"
139
+ type="email"
140
+ label={messages.fields.email}
141
+ autoComplete="email"
142
+ required
143
+ defaultValue={state.email ?? ""}
144
+ error={errors.at("email")}
145
+ unstyled={unstyled}
146
+ locale={locale}
147
+ />
148
+ <PasswordField
149
+ name="password"
150
+ label={messages.fields.password}
151
+ autoComplete="current-password"
152
+ error={errors.at("password")}
153
+ unstyled={unstyled}
154
+ locale={locale}
155
+ />
156
+ </FormShell>
157
+ );
158
+ }
159
+
160
+ export interface RegisterFormProps extends AuthFormBaseProps {
161
+ readonly next?: string;
162
+ readonly loginHref?: string;
163
+ /** Show the consent checkbox (the module's `requireConsent`). */
164
+ readonly requireConsent: boolean;
165
+ /** The password policy's minimum, for the hint and the browser check. */
166
+ readonly minPasswordLength: number;
167
+ /** The consent statement; may contain links to the terms. Defaults to `messages.fields.consent`. */
168
+ readonly consentLabel?: ReactNode;
169
+ /**
170
+ * The app's own inputs, before the consent checkbox. Their values reach `onRegistered` as
171
+ * `event.fields` when their names are declared in `auth({ registrationFields })`.
172
+ */
173
+ readonly extraFields?: ReactNode;
174
+ }
175
+
176
+ export function RegisterForm({
177
+ action,
178
+ messages,
179
+ locale,
180
+ next,
181
+ loginHref,
182
+ requireConsent,
183
+ minPasswordLength,
184
+ consentLabel,
185
+ extraFields,
186
+ classNames,
187
+ unstyled,
188
+ submitVariant,
189
+ }: RegisterFormProps) {
190
+ const [state, formAction, isPending] = useActionState(action, INITIAL_AUTH_FORM_STATE);
191
+ const errors = useErrors(state, messages);
192
+ const slot = createSlotClassGetter({ defaults: DEFAULT_CLASSES, classNames, unstyled });
193
+ const footer =
194
+ loginHref === undefined ? undefined : (
195
+ <p className={slot("footer")}>
196
+ {messages.register.hasAccount}{" "}
197
+ <a href={loginHref} className={slot("link")}>
198
+ {messages.register.loginLink}
199
+ </a>
200
+ </p>
201
+ );
202
+ return (
203
+ <FormShell
204
+ formAction={formAction}
205
+ isPending={isPending}
206
+ submitLabel={messages.register.submit}
207
+ pendingLabel={messages.register.pending}
208
+ formError={errors.form}
209
+ footer={footer}
210
+ slot={slot}
211
+ unstyled={unstyled}
212
+ submitVariant={submitVariant}
213
+ >
214
+ {next === undefined ? null : <input type="hidden" name="next" value={next} />}
215
+ <TextField
216
+ name="email"
217
+ type="email"
218
+ label={messages.fields.email}
219
+ autoComplete="email"
220
+ required
221
+ defaultValue={state.email ?? ""}
222
+ error={errors.at("email")}
223
+ unstyled={unstyled}
224
+ locale={locale}
225
+ />
226
+ <PasswordField
227
+ name="password"
228
+ label={messages.fields.password}
229
+ hint={formatMessage(messages.fields.newPasswordHint, { minLength: minPasswordLength })}
230
+ autoComplete="new-password"
231
+ minLength={minPasswordLength}
232
+ error={errors.at("password")}
233
+ unstyled={unstyled}
234
+ locale={locale}
235
+ />
236
+ {extraFields}
237
+ {requireConsent ? (
238
+ <Checkbox name="consent" label={consentLabel ?? messages.fields.consent} required error={errors.at("consent")} unstyled={unstyled} />
239
+ ) : null}
240
+ </FormShell>
241
+ );
242
+ }
243
+
244
+ export interface ChangePasswordFormProps extends AuthFormBaseProps {
245
+ readonly minPasswordLength: number;
246
+ }
247
+
248
+ export function ChangePasswordForm({ action, messages, locale, minPasswordLength, classNames, unstyled, submitVariant }: ChangePasswordFormProps) {
249
+ const [state, formAction, isPending] = useActionState(action, INITIAL_AUTH_FORM_STATE);
250
+ const errors = useErrors(state, messages);
251
+ const slot = createSlotClassGetter({ defaults: DEFAULT_CLASSES, classNames, unstyled });
252
+ const notice =
253
+ state.status === "ok" ? (
254
+ <p role="status" className={slot("notice")}>
255
+ {messages.changePassword.success}
256
+ </p>
257
+ ) : undefined;
258
+ return (
259
+ <FormShell
260
+ formAction={formAction}
261
+ isPending={isPending}
262
+ submitLabel={messages.changePassword.submit}
263
+ pendingLabel={messages.changePassword.pending}
264
+ formError={errors.form}
265
+ footer={notice}
266
+ slot={slot}
267
+ unstyled={unstyled}
268
+ submitVariant={submitVariant}
269
+ >
270
+ <PasswordField
271
+ name="currentPassword"
272
+ label={messages.fields.currentPassword}
273
+ autoComplete="current-password"
274
+ error={errors.at("currentPassword")}
275
+ unstyled={unstyled}
276
+ locale={locale}
277
+ />
278
+ <PasswordField
279
+ name="newPassword"
280
+ label={messages.fields.newPassword}
281
+ hint={formatMessage(messages.fields.newPasswordHint, { minLength: minPasswordLength })}
282
+ autoComplete="new-password"
283
+ minLength={minPasswordLength}
284
+ error={errors.at("newPassword")}
285
+ unstyled={unstyled}
286
+ locale={locale}
287
+ />
288
+ </FormShell>
289
+ );
290
+ }
291
+
292
+ export interface ForgotPasswordFormProps extends AuthFormBaseProps {
293
+ /** How long a link works, for the confirmation. */
294
+ readonly ttlMinutes: number;
295
+ readonly loginHref?: string;
296
+ }
297
+
298
+ /** Asks for a reset link. Its confirmation is the same whether or not the email has an account. */
299
+ export function ForgotPasswordForm({ action, messages, locale, ttlMinutes, loginHref, classNames, unstyled, submitVariant }: ForgotPasswordFormProps) {
300
+ const [state, formAction, isPending] = useActionState(action, INITIAL_AUTH_FORM_STATE);
301
+ const errors = useErrors(state, messages);
302
+ const slot = createSlotClassGetter({ defaults: DEFAULT_CLASSES, classNames, unstyled });
303
+ const backToLogin =
304
+ loginHref === undefined ? undefined : (
305
+ <p className={slot("footer")}>
306
+ <a href={loginHref} className={slot("link")}>
307
+ {messages.forgotPassword.backToLogin}
308
+ </a>
309
+ </p>
310
+ );
311
+ if (state.status === "ok") {
312
+ return (
313
+ <div className={slot("root")}>
314
+ <p role="status" className={slot("notice")}>
315
+ {formatMessage(messages.forgotPassword.sent, { ttlMinutes })}
316
+ </p>
317
+ {backToLogin}
318
+ </div>
319
+ );
320
+ }
321
+ return (
322
+ <FormShell
323
+ formAction={formAction}
324
+ isPending={isPending}
325
+ submitLabel={messages.forgotPassword.submit}
326
+ pendingLabel={messages.forgotPassword.pending}
327
+ formError={errors.form}
328
+ footer={backToLogin}
329
+ slot={slot}
330
+ unstyled={unstyled}
331
+ submitVariant={submitVariant}
332
+ >
333
+ <TextField
334
+ name="email"
335
+ type="email"
336
+ label={messages.fields.email}
337
+ autoComplete="email"
338
+ required
339
+ defaultValue={state.email ?? ""}
340
+ error={errors.at("email")}
341
+ unstyled={unstyled}
342
+ locale={locale}
343
+ />
344
+ </FormShell>
345
+ );
346
+ }
347
+
348
+ export interface ResetPasswordFormProps extends AuthFormBaseProps {
349
+ /** The token from the reset link; checked again on the server. */
350
+ readonly token: string;
351
+ readonly minPasswordLength: number;
352
+ }
353
+
354
+ /** Sets a new password from a reset link; its action goes to the login page on success. */
355
+ export function ResetPasswordForm({ action, messages, locale, token, minPasswordLength, classNames, unstyled, submitVariant }: ResetPasswordFormProps) {
356
+ const [state, formAction, isPending] = useActionState(action, INITIAL_AUTH_FORM_STATE);
357
+ const errors = useErrors(state, messages);
358
+ const slot = createSlotClassGetter({ defaults: DEFAULT_CLASSES, classNames, unstyled });
359
+ return (
360
+ <FormShell
361
+ formAction={formAction}
362
+ isPending={isPending}
363
+ submitLabel={messages.resetPassword.submit}
364
+ pendingLabel={messages.resetPassword.pending}
365
+ formError={errors.form}
366
+ slot={slot}
367
+ unstyled={unstyled}
368
+ submitVariant={submitVariant}
369
+ >
370
+ <input type="hidden" name="token" value={token} />
371
+ <PasswordField
372
+ name="newPassword"
373
+ label={messages.fields.newPassword}
374
+ hint={formatMessage(messages.fields.newPasswordHint, { minLength: minPasswordLength })}
375
+ autoComplete="new-password"
376
+ minLength={minPasswordLength}
377
+ error={errors.at("newPassword")}
378
+ unstyled={unstyled}
379
+ locale={locale}
380
+ />
381
+ </FormShell>
382
+ );
383
+ }
@@ -0,0 +1,16 @@
1
+ // The auth forms, to compose into the app's own pages. They take the server actions from
2
+ // `@softure-ai/auth/next` as props: no `next/*` import here (docs/02-module-standard.md §5).
3
+ export {
4
+ type AuthFormAction,
5
+ type AuthFormSlot,
6
+ ChangePasswordForm,
7
+ type ChangePasswordFormProps,
8
+ ForgotPasswordForm,
9
+ type ForgotPasswordFormProps,
10
+ LoginForm,
11
+ type LoginFormProps,
12
+ RegisterForm,
13
+ type RegisterFormProps,
14
+ ResetPasswordForm,
15
+ type ResetPasswordFormProps,
16
+ } from "./auth-forms.js";