@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
package/src/index.ts ADDED
@@ -0,0 +1,100 @@
1
+ // Public API of @softure-ai/auth: the module factory for softure.config.ts, its types, messages and
2
+ // tables, and the development reset sender. Database work is in `@softure-ai/auth/server`, the Next.js adapter in `/next`, the route
3
+ // guard in `/proxy`, the forms in `/ui` and the role scripts in `/scripts`.
4
+ import { defineModule, resolveMigrationsDir } from "@softure-ai/core";
5
+ import { authMessages } from "./messages/index.js";
6
+ import { authOptionsSchema } from "./options.js";
7
+ import { checkAuthTables } from "./server/health.js";
8
+ import { authPrivacyContributor } from "./server/privacy.js";
9
+
10
+ export const MODULE_ID = "auth";
11
+
12
+ /** Name of the runtime switch that closes registration. */
13
+ export const REGISTRATION_CLOSED_SWITCH = "auth.registration_closed";
14
+
15
+ /**
16
+ * The env override of that switch: `true`/`1` or `false`/`0` while auth reads it itself. When the app
17
+ * defines the switch in `@softure-ai/feature-switches`, that module reads the same variable.
18
+ */
19
+ export const REGISTRATION_CLOSED_ENV = "SOFTURE_SWITCH_AUTH_REGISTRATION_CLOSED";
20
+
21
+ /**
22
+ * Rate limit buckets auth consumes, with defaults to spread into `security({ buckets })`:
23
+ * `register` and `login` per client address, `login-account` per email, `change-password` per user,
24
+ * `password-reset` (link requests) and `password-reset-confirm` (new passwords) per client address,
25
+ * and `password-reset-account` per email, which bounds the mails one address can receive.
26
+ */
27
+ export const AUTH_RATE_LIMIT_BUCKETS = {
28
+ register: { limit: 5, windowMinutes: 15 },
29
+ login: { limit: 50, windowMinutes: 15 },
30
+ "login-account": { limit: 10, windowMinutes: 15 },
31
+ "change-password": { limit: 10, windowMinutes: 15 },
32
+ "password-reset": { limit: 10, windowMinutes: 15 },
33
+ "password-reset-account": { limit: 3, windowMinutes: 15 },
34
+ "password-reset-confirm": { limit: 10, windowMinutes: 15 },
35
+ } as const;
36
+
37
+ /**
38
+ * Enables accounts in `softure.config.ts` (next to `security({ ... })`):
39
+ * `auth({ routes: { afterLogin: "/dashboard" }, password: { minLength: 12 } })`.
40
+ */
41
+ export const auth = defineModule({
42
+ manifest: {
43
+ id: MODULE_ID,
44
+ version: "0.1.7",
45
+ dependsOn: { security: "^0.1.0", mailing: "^0.1.0?", ops: "^0.1.0?" },
46
+ dbSchema: "auth",
47
+ tables: ["users", "sessions", "user_roles", "password_resets"],
48
+ env: [
49
+ {
50
+ name: REGISTRATION_CLOSED_ENV,
51
+ required: false,
52
+ description: "Overrides the auth.registration_closed switch: true or 1 closes registration, false or 0 opens it.",
53
+ },
54
+ ],
55
+ switches: [REGISTRATION_CLOSED_SWITCH],
56
+ routes: {
57
+ login: "/login",
58
+ register: "/register",
59
+ changePassword: "/account/password",
60
+ forgotPassword: "/forgot-password",
61
+ resetPassword: "/reset-password",
62
+ afterLogin: "/",
63
+ afterLogout: "/login",
64
+ },
65
+ mount: [
66
+ { kind: "page", path: "app/login/page.tsx", export: "LoginPage" },
67
+ { kind: "page", path: "app/register/page.tsx", export: "RegisterPage" },
68
+ { kind: "page", path: "app/account/password/page.tsx", export: "ChangePasswordPage" },
69
+ { kind: "page", path: "app/forgot-password/page.tsx", export: "ForgotPasswordPage" },
70
+ { kind: "page", path: "app/reset-password/page.tsx", export: "ResetPasswordPage" },
71
+ { kind: "route-handler", path: "app/api/auth/session/route.ts", export: "getSessionRoute" },
72
+ { kind: "middleware", path: "proxy.ts", export: "createAuthGuard" },
73
+ ],
74
+ privacy: { exports: true, deletes: true },
75
+ },
76
+ messages: authMessages,
77
+ options: authOptionsSchema,
78
+ migrations: { dir: resolveMigrationsDir(import.meta.url, "../migrations/") },
79
+ privacy: authPrivacyContributor,
80
+ health: checkAuthTables,
81
+ });
82
+
83
+ export { INITIAL_AUTH_FORM_STATE } from "./contract.js";
84
+ export type {
85
+ AuthErrorCode,
86
+ AuthFormErrorCode,
87
+ AuthFormField,
88
+ AuthFormState,
89
+ AuthUser,
90
+ NewSession,
91
+ RegisteredEvent,
92
+ SignedIn,
93
+ } from "./contract.js";
94
+ export { authMessages, getAuthErrorMessage, type AuthMessages } from "./messages/index.js";
95
+ export type { AuthOptions, AuthOptionsInput, OnRegisteredHook, RewriteRedirect, RewriteRedirectContext, ScryptParams } from "./options.js";
96
+ export { consolePasswordResetSender, type PasswordResetDetails, type PasswordResetSender } from "./password-reset-sender.js";
97
+ export { getSessionCookie, type SessionCookie } from "./session-cookie.js";
98
+ export { toSafeNextPath } from "./safe-next-path.js";
99
+ export { ADMIN_ROLE, ROLE_NAME_PATTERN } from "./roles.js";
100
+ export { passwordResets, sessions, userRoles, users } from "./schema.js";
@@ -0,0 +1,3 @@
1
+ // The mailing adapter of @softure-ai/auth: password reset mails through `@softure-ai/mailing`
2
+ // (an optional peer dependency; only apps that import this entry need it).
3
+ export { mailingResetSender, renderPasswordResetMail, type PasswordResetMail, type PasswordResetMailInput } from "./reset-mail.js";
@@ -0,0 +1,73 @@
1
+ // The password reset mail: rendered from auth's dictionaries in the app's locale and sent through
2
+ // `@softure-ai/mailing`. A transactional mail: no unsubscribe link, never suppressed. The link is
3
+ // placed by the code, never by a translatable string, so a copy override cannot drop it.
4
+ import { formatMessage, selectPlural, type Locale, type SoftureConfig } from "@softure-ai/core";
5
+ import { getSoftureConfig } from "@softure-ai/core/next";
6
+ import type { OutgoingMail } from "@softure-ai/mailing";
7
+ import { sendMail } from "@softure-ai/mailing/server";
8
+ import type { AuthMessages } from "../messages/index.js";
9
+ import type { PasswordResetSender } from "../password-reset-sender.js";
10
+ import { getAuthModule, getAuthOptions } from "../server/options.js";
11
+
12
+ export interface PasswordResetMailInput {
13
+ /** The reset link auth hands to the sender. */
14
+ readonly link: string;
15
+ /** How long the link works (`passwordReset.ttlMinutes`). */
16
+ readonly ttlMinutes: number;
17
+ }
18
+
19
+ /** The subject and bodies of a reset mail, without the recipient. */
20
+ export type PasswordResetMail = Pick<OutgoingMail, "subject" | "text"> & { readonly html: string };
21
+
22
+ const HTML_ESCAPES: Readonly<Record<string, string>> = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
23
+
24
+ function escapeHtml(value: string): string {
25
+ return value.replace(/[&<>"']/g, (character) => HTML_ESCAPES[character] ?? character);
26
+ }
27
+
28
+ /**
29
+ * Renders the reset mail from `messages` (one locale's dictionary, overrides applied): a plain-text
30
+ * body with the bare link and an HTML body with the same paragraphs and the link as an anchor.
31
+ */
32
+ export function renderPasswordResetMail(messages: AuthMessages, locale: Locale, input: PasswordResetMailInput): PasswordResetMail {
33
+ const copy = messages.resetMail;
34
+ const duration = formatMessage(selectPlural(locale, input.ttlMinutes, copy.minutes), { count: input.ttlMinutes });
35
+ const expiry = formatMessage(copy.expiry, { duration });
36
+
37
+ const text = [copy.greeting, copy.intro, input.link, expiry, copy.ignore].join("\n\n");
38
+ const paragraphs = [
39
+ escapeHtml(copy.greeting),
40
+ escapeHtml(copy.intro),
41
+ `<a href="${escapeHtml(input.link)}">${escapeHtml(copy.action)}</a>`,
42
+ escapeHtml(expiry),
43
+ escapeHtml(copy.ignore),
44
+ ];
45
+ const html = paragraphs.map((paragraph) => `<p>${paragraph}</p>`).join("\n");
46
+ return { subject: copy.subject, text, html };
47
+ }
48
+
49
+ /** The app's auth dictionary for `locale`, with its overrides applied. */
50
+ function getMessages(config: SoftureConfig, locale: Locale): AuthMessages {
51
+ // The module factory merged the dictionaries; their shape is the module's own.
52
+ return getAuthModule(config).messages[locale] as AuthMessages;
53
+ }
54
+
55
+ /**
56
+ * A `passwordReset.send` that mails the link through `@softure-ai/mailing`:
57
+ * `auth({ passwordReset: { send: mailingResetSender() } })` next to `mailing({ ... })`. It reads the
58
+ * registered config (`registerSoftureConfig`) when it runs. A failed send throws an error naming
59
+ * the `mailing.*` code (never the address or the link), which auth logs.
60
+ */
61
+ export function mailingResetSender(): PasswordResetSender {
62
+ return async (link, user, details) => {
63
+ const config = getSoftureConfig();
64
+ const mail = renderPasswordResetMail(getMessages(config, details.locale), details.locale, {
65
+ link,
66
+ ttlMinutes: getAuthOptions(config).passwordReset.ttlMinutes,
67
+ });
68
+ const result = await sendMail({ config }, { to: user.email, ...mail });
69
+ if (!result.ok) {
70
+ throw new Error(`@softure-ai/auth: the password reset mail was not sent (${result.error})`);
71
+ }
72
+ };
73
+ }
@@ -0,0 +1,92 @@
1
+ export const en = {
2
+ fields: {
3
+ email: "Email",
4
+ password: "Password",
5
+ currentPassword: "Current password",
6
+ newPassword: "New password",
7
+ newPasswordHint: "At least {minLength} characters.",
8
+ consent: "I accept the terms of service and the privacy policy.",
9
+ },
10
+ login: {
11
+ title: "Log in",
12
+ lead: "Welcome back.",
13
+ submit: "Log in",
14
+ pending: "Logging in…",
15
+ noAccount: "No account yet?",
16
+ registerLink: "Create one",
17
+ forgotPassword: "Forgot your password?",
18
+ },
19
+ register: {
20
+ title: "Create an account",
21
+ lead: "It takes a minute.",
22
+ submit: "Create account",
23
+ pending: "Creating…",
24
+ hasAccount: "Already have an account?",
25
+ loginLink: "Log in",
26
+ closedTitle: "Registration is closed",
27
+ closedBody: "New accounts cannot be created right now. Try again later.",
28
+ },
29
+ changePassword: {
30
+ title: "Change password",
31
+ lead: "Every other device you are logged in on will be logged out.",
32
+ submit: "Change password",
33
+ pending: "Saving…",
34
+ success: "Your password has been changed.",
35
+ },
36
+ forgotPassword: {
37
+ title: "Reset your password",
38
+ lead: "Enter the email of your account and we will send you a link to set a new password.",
39
+ submit: "Send the link",
40
+ pending: "Sending…",
41
+ sent: "If an account uses this email, a link to reset its password is on its way. It works for {ttlMinutes} minutes.",
42
+ backToLogin: "Back to login",
43
+ },
44
+ resetPassword: {
45
+ title: "Set a new password",
46
+ lead: "You will be logged out on every device.",
47
+ submit: "Set password",
48
+ pending: "Saving…",
49
+ success: "Your password has been changed. Log in with the new one.",
50
+ invalidTitle: "This link does not work",
51
+ invalidBody: "The link has expired or has already been used. Ask for a new one.",
52
+ requestNew: "Get a new link",
53
+ },
54
+ resetMail: {
55
+ subject: "Reset your password",
56
+ greeting: "Hello,",
57
+ intro: "We got a request to reset the password of your account. Open this link to set a new one:",
58
+ action: "Set a new password",
59
+ expiry: "The link works for {duration} and only once.",
60
+ /** `{count}` minutes, by the locale's plural rules (Intl.PluralRules categories). */
61
+ minutes: { one: "{count} minute", few: "{count} minutes", many: "{count} minutes", other: "{count} minutes" },
62
+ ignore: "If you did not ask for this, ignore this mail: your password stays as it is.",
63
+ },
64
+ logout: {
65
+ submit: "Log out",
66
+ },
67
+ errors: {
68
+ auth: {
69
+ invalid_credentials: "The email or password is incorrect.",
70
+ email_invalid: "Enter a valid email address.",
71
+ email_taken: "An account with this email already exists.",
72
+ password_too_short: "The password is too short.",
73
+ password_too_long: "The password is too long.",
74
+ consent_required: "You need to accept the terms to create an account.",
75
+ registration_closed: "Registration is closed.",
76
+ current_password_invalid: "The current password is incorrect.",
77
+ password_unchanged: "The new password must differ from the current one.",
78
+ unauthenticated: "Your session has ended. Log in again.",
79
+ forbidden: "You do not have access to this.",
80
+ reset_token_invalid: "This link has expired or has already been used. Ask for a new one.",
81
+ password_reset_unavailable: "Password reset is not available.",
82
+ },
83
+ security: {
84
+ rate_limited: "Too many attempts. Wait a few minutes and try again.",
85
+ client_unidentified: "We could not verify where this request came from. Try again later.",
86
+ },
87
+ core: {
88
+ database_failed: "Something went wrong on our side. Try again in a moment.",
89
+ unexpected: "Something went wrong on our side. Try again in a moment.",
90
+ },
91
+ },
92
+ };
@@ -0,0 +1,15 @@
1
+ import type { AuthFormErrorCode } from "../contract.js";
2
+ import { en } from "./en.js";
3
+ import { pl } from "./pl.js";
4
+
5
+ /** Complete default dictionaries; apps pass partial overrides per locale. */
6
+ export const authMessages = { en, pl };
7
+
8
+ export type AuthMessages = typeof en;
9
+
10
+ /** The copy for an error code; an unknown code gets the generic failure. */
11
+ export function getAuthErrorMessage(messages: AuthMessages, code: AuthFormErrorCode): string {
12
+ const [namespace, name] = code.split(".", 2) as [string, string];
13
+ const group: Readonly<Record<string, string>> | undefined = (messages.errors as Readonly<Record<string, Readonly<Record<string, string>>>>)[namespace];
14
+ return (group !== undefined && Object.hasOwn(group, name) ? group[name] : undefined) ?? messages.errors.core.unexpected;
15
+ }
@@ -0,0 +1,93 @@
1
+ import type { en } from "./en.js";
2
+
3
+ export const pl: typeof en = {
4
+ fields: {
5
+ email: "E-mail",
6
+ password: "Hasło",
7
+ currentPassword: "Obecne hasło",
8
+ newPassword: "Nowe hasło",
9
+ newPasswordHint: "Co najmniej {minLength} znaków.",
10
+ consent: "Akceptuję regulamin i politykę prywatności.",
11
+ },
12
+ login: {
13
+ title: "Zaloguj się",
14
+ lead: "Witaj ponownie.",
15
+ submit: "Zaloguj się",
16
+ pending: "Logowanie…",
17
+ noAccount: "Nie masz jeszcze konta?",
18
+ registerLink: "Załóż je",
19
+ forgotPassword: "Nie pamiętasz hasła?",
20
+ },
21
+ register: {
22
+ title: "Załóż konto",
23
+ lead: "To zajmie chwilę.",
24
+ submit: "Załóż konto",
25
+ pending: "Zakładanie…",
26
+ hasAccount: "Masz już konto?",
27
+ loginLink: "Zaloguj się",
28
+ closedTitle: "Rejestracja jest zamknięta",
29
+ closedBody: "Nie można teraz założyć nowego konta. Spróbuj ponownie później.",
30
+ },
31
+ changePassword: {
32
+ title: "Zmień hasło",
33
+ lead: "Wszystkie inne urządzenia, na których jesteś zalogowany, zostaną wylogowane.",
34
+ submit: "Zmień hasło",
35
+ pending: "Zapisywanie…",
36
+ success: "Hasło zostało zmienione.",
37
+ },
38
+ forgotPassword: {
39
+ title: "Zresetuj hasło",
40
+ lead: "Podaj e-mail swojego konta, a wyślemy Ci link do ustawienia nowego hasła.",
41
+ submit: "Wyślij link",
42
+ pending: "Wysyłanie…",
43
+ sent: "Jeśli istnieje konto z tym adresem, wysłaliśmy na niego link do zmiany hasła. Link działa przez {ttlMinutes} minut.",
44
+ backToLogin: "Wróć do logowania",
45
+ },
46
+ resetPassword: {
47
+ title: "Ustaw nowe hasło",
48
+ lead: "Zostaniesz wylogowany na wszystkich urządzeniach.",
49
+ submit: "Ustaw hasło",
50
+ pending: "Zapisywanie…",
51
+ success: "Hasło zostało zmienione. Zaloguj się nowym hasłem.",
52
+ invalidTitle: "Ten link nie działa",
53
+ invalidBody: "Link wygasł albo został już użyty. Poproś o nowy.",
54
+ requestNew: "Wyślij nowy link",
55
+ },
56
+ resetMail: {
57
+ subject: "Zresetuj hasło",
58
+ greeting: "Dzień dobry,",
59
+ intro: "Otrzymaliśmy prośbę o zresetowanie hasła do Twojego konta. Otwórz ten link, aby ustawić nowe:",
60
+ action: "Ustaw nowe hasło",
61
+ expiry: "Link działa przez {duration} i tylko raz.",
62
+ minutes: { one: "{count} minutę", few: "{count} minuty", many: "{count} minut", other: "{count} minuty" },
63
+ ignore: "Jeśli to nie Ty, zignoruj tę wiadomość: Twoje hasło się nie zmieni.",
64
+ },
65
+ logout: {
66
+ submit: "Wyloguj się",
67
+ },
68
+ errors: {
69
+ auth: {
70
+ invalid_credentials: "Nieprawidłowy e-mail lub hasło.",
71
+ email_invalid: "Podaj prawidłowy adres e-mail.",
72
+ email_taken: "Konto z tym adresem e-mail już istnieje.",
73
+ password_too_short: "Hasło jest za krótkie.",
74
+ password_too_long: "Hasło jest za długie.",
75
+ consent_required: "Aby założyć konto, zaakceptuj regulamin.",
76
+ registration_closed: "Rejestracja jest zamknięta.",
77
+ current_password_invalid: "Obecne hasło jest nieprawidłowe.",
78
+ password_unchanged: "Nowe hasło musi różnić się od obecnego.",
79
+ unauthenticated: "Sesja wygasła. Zaloguj się ponownie.",
80
+ forbidden: "Nie masz dostępu do tej funkcji.",
81
+ reset_token_invalid: "Ten link wygasł albo został już użyty. Poproś o nowy.",
82
+ password_reset_unavailable: "Reset hasła jest niedostępny.",
83
+ },
84
+ security: {
85
+ rate_limited: "Zbyt wiele prób. Odczekaj kilka minut i spróbuj ponownie.",
86
+ client_unidentified: "Nie udało się ustalić, skąd przyszło to żądanie. Spróbuj ponownie później.",
87
+ },
88
+ core: {
89
+ database_failed: "Coś poszło nie tak po naszej stronie. Spróbuj ponownie za chwilę.",
90
+ unexpected: "Coś poszło nie tak po naszej stronie. Spróbuj ponownie za chwilę.",
91
+ },
92
+ },
93
+ };
@@ -0,0 +1,240 @@
1
+ "use server";
2
+
3
+ // The auth server actions. Each one identifies the client and counts its attempt (inside the
4
+ // server functions) before any work, reads the user from the session cookie (never from a bound
5
+ // argument, which the client controls, docs/02 §8), and turns unexpected failures into
6
+ // `safeError` codes. Next refuses an action whose Origin does not match the host. Every redirect
7
+ // goes through the app's `rewriteRedirect` (`resolveRedirectTarget`).
8
+ import { errorLogLabel, safeError, type SoftureConfig } from "@softure-ai/core";
9
+ import { getSoftureConfig } from "@softure-ai/core/next";
10
+ import { identifyClient } from "@softure-ai/security/server";
11
+ import { headers } from "next/headers";
12
+ import { redirect } from "next/navigation";
13
+ import { after } from "next/server";
14
+ import { z } from "zod";
15
+ import type { AuthFormErrorCode, AuthFormField, AuthFormState } from "../contract.js";
16
+ import { resolveRedirectTarget } from "../redirect-target.js";
17
+ import { MAX_NEXT_PATH_LENGTH, toSafeNextPath } from "../safe-next-path.js";
18
+ import { changePassword } from "../server/change-password.js";
19
+ import { getAuthOptions } from "../server/options.js";
20
+ import { loginUser } from "../server/login.js";
21
+ import { getAuthRoutes } from "../server/options.js";
22
+ import { deliverPasswordReset, requestPasswordReset, resetPassword } from "../server/password-reset.js";
23
+ import { registerUser } from "../server/register.js";
24
+ import { logoutSession } from "../server/sessions.js";
25
+ import { getAuthContext } from "./context.js";
26
+ import { PASSWORD_RESET_DONE_PARAM } from "./params.js";
27
+ import { clearSessionCookie, readLegacySessionToken, readSessionToken, writeSessionCookie } from "./session-cookie.js";
28
+
29
+ /** Longer values are cut: the server functions refuse them anyway, and nothing huge is echoed back. */
30
+ const MAX_FIELD_LENGTH = 4096;
31
+ const text = z
32
+ .string()
33
+ .catch("")
34
+ .transform((value) => value.slice(0, MAX_FIELD_LENGTH));
35
+
36
+ // One character over the cap, so `toSafeNextPath` still sees an overlong path as overlong, not cut.
37
+ const nextPath = z
38
+ .string()
39
+ .catch("")
40
+ .transform((value) => value.slice(0, MAX_NEXT_PATH_LENGTH + 1));
41
+
42
+ const loginInput = z.object({ email: text, password: text, next: nextPath });
43
+ const registerInput = z.object({ email: text, password: text, next: nextPath, consent: z.string().nullable().catch(null) });
44
+ const changePasswordInput = z.object({ currentPassword: text, newPassword: text });
45
+ const forgotPasswordInput = z.object({ email: text });
46
+ const resetPasswordInput = z.object({ token: text, newPassword: text });
47
+
48
+ const FIELD_OF: Partial<Record<AuthFormErrorCode, AuthFormField>> = {
49
+ "auth.email_invalid": "email",
50
+ "auth.email_taken": "email",
51
+ "auth.password_too_short": "password",
52
+ "auth.password_too_long": "password",
53
+ "auth.consent_required": "consent",
54
+ };
55
+
56
+ const CHANGE_FIELD_OF: Partial<Record<AuthFormErrorCode, AuthFormField>> = {
57
+ "auth.current_password_invalid": "currentPassword",
58
+ "auth.password_unchanged": "newPassword",
59
+ "auth.password_too_short": "newPassword",
60
+ "auth.password_too_long": "newPassword",
61
+ };
62
+
63
+ const RESET_FIELD_OF: Partial<Record<AuthFormErrorCode, AuthFormField>> = {
64
+ "auth.password_too_short": "newPassword",
65
+ "auth.password_too_long": "newPassword",
66
+ };
67
+
68
+ function failure(error: AuthFormErrorCode, options: { field?: AuthFormField; email?: string } = {}): AuthFormState {
69
+ return { status: "error", error, ...options };
70
+ }
71
+
72
+ function readForm<T extends z.ZodType>(schema: T, formData: FormData): z.output<T> {
73
+ const raw = Object.fromEntries([...formData.keys()].map((key) => [key, formData.get(key)]));
74
+ // Every field has a `catch`, so parsing cannot fail.
75
+ return schema.parse(raw);
76
+ }
77
+
78
+ /** The app's declared registration fields the form sent as text; files and other names are ignored (the server cuts them to 512). */
79
+ function readRegistrationFields(config: SoftureConfig, formData: FormData): Record<string, string> {
80
+ const fields: Record<string, string> = {};
81
+ for (const name of getAuthOptions(config).registrationFields) {
82
+ const value = formData.get(name);
83
+ if (typeof value === "string") fields[name] = value.slice(0, MAX_FIELD_LENGTH);
84
+ }
85
+ return fields;
86
+ }
87
+
88
+ function reportFailure(operation: string, error: unknown): AuthFormErrorCode {
89
+ console.error(`@softure-ai/auth: ${operation} failed: ${errorLogLabel(error)}`);
90
+ return safeError(error).error;
91
+ }
92
+
93
+ export async function loginAction(_previous: AuthFormState, formData: FormData): Promise<AuthFormState> {
94
+ const config = getSoftureConfig();
95
+ const input = readForm(loginInput, formData);
96
+ const client = identifyClient({ config }, await headers());
97
+ if (!client.ok) return failure(client.error, { email: input.email });
98
+
99
+ let result;
100
+ try {
101
+ result = await loginUser(await getAuthContext(config), { email: input.email, password: input.password, clientKey: client.value });
102
+ } catch (error) {
103
+ return failure(reportFailure("login", error), { email: input.email });
104
+ }
105
+ if (!result.ok) return failure(result.error, { email: input.email });
106
+
107
+ await endPreviousSession(config);
108
+ await writeSessionCookie(config, result.value.session);
109
+ redirect(await resolveRedirectTarget(config, toSafeNextPath(input.next, getAuthRoutes(config).afterLogin)));
110
+ }
111
+
112
+ export async function registerAction(_previous: AuthFormState, formData: FormData): Promise<AuthFormState> {
113
+ const config = getSoftureConfig();
114
+ const input = readForm(registerInput, formData);
115
+ const client = identifyClient({ config }, await headers());
116
+ if (!client.ok) return failure(client.error, { email: input.email });
117
+
118
+ let result;
119
+ try {
120
+ result = await registerUser(await getAuthContext(config), {
121
+ email: input.email,
122
+ password: input.password,
123
+ // A checked HTML checkbox sends "on" (or its value); an unchecked one sends nothing.
124
+ hasConsented: input.consent !== null,
125
+ clientKey: client.value,
126
+ fields: readRegistrationFields(config, formData),
127
+ });
128
+ } catch (error) {
129
+ return failure(reportFailure("registration", error), { email: input.email });
130
+ }
131
+ if (!result.ok) return failure(result.error, { field: FIELD_OF[result.error], email: input.email });
132
+
133
+ await endPreviousSession(config);
134
+ await writeSessionCookie(config, result.value.session);
135
+ redirect(await resolveRedirectTarget(config, toSafeNextPath(input.next, getAuthRoutes(config).afterLogin)));
136
+ }
137
+
138
+ export async function changePasswordAction(_previous: AuthFormState, formData: FormData): Promise<AuthFormState> {
139
+ const config = getSoftureConfig();
140
+ const input = readForm(changePasswordInput, formData);
141
+ const token = await readSessionToken(config);
142
+ if (token === null) return failure("auth.unauthenticated");
143
+
144
+ try {
145
+ const result = await changePassword(await getAuthContext(config), {
146
+ sessionToken: token,
147
+ currentPassword: input.currentPassword,
148
+ newPassword: input.newPassword,
149
+ });
150
+ return result.ok ? { status: "ok" } : failure(result.error, { field: CHANGE_FIELD_OF[result.error] });
151
+ } catch (error) {
152
+ return failure(reportFailure("password change", error));
153
+ }
154
+ }
155
+
156
+ /**
157
+ * Asks for a reset link. The answer depends only on the buckets and the email's shape, never on
158
+ * whether the account exists: the link is issued and handed to the app's sender after the
159
+ * response, so neither the sender's time nor its failure shows here.
160
+ */
161
+ export async function forgotPasswordAction(_previous: AuthFormState, formData: FormData): Promise<AuthFormState> {
162
+ const config = getSoftureConfig();
163
+ const input = readForm(forgotPasswordInput, formData);
164
+ const client = identifyClient({ config }, await headers());
165
+ if (!client.ok) return failure(client.error, { email: input.email });
166
+
167
+ let result;
168
+ try {
169
+ result = await requestPasswordReset(await getAuthContext(config), { email: input.email, clientKey: client.value });
170
+ } catch (error) {
171
+ return failure(reportFailure("password reset request", error), { email: input.email });
172
+ }
173
+ if (!result.ok) return failure(result.error, { field: FIELD_OF[result.error], email: input.email });
174
+
175
+ const { email } = result.value;
176
+ after(async () => {
177
+ try {
178
+ await deliverPasswordReset(await getAuthContext(config), email);
179
+ } catch (error) {
180
+ reportFailure("password reset delivery", error);
181
+ }
182
+ });
183
+ return { status: "ok" };
184
+ }
185
+
186
+ /**
187
+ * Sets a new password with the token from a reset link, then goes to the login page, which says so.
188
+ * A redirect, not an `ok` state: without JavaScript the reset page renders again after the action,
189
+ * and its token is used by then.
190
+ */
191
+ export async function resetPasswordAction(_previous: AuthFormState, formData: FormData): Promise<AuthFormState> {
192
+ const config = getSoftureConfig();
193
+ const input = readForm(resetPasswordInput, formData);
194
+ const client = identifyClient({ config }, await headers());
195
+ if (!client.ok) return failure(client.error);
196
+
197
+ let result;
198
+ try {
199
+ result = await resetPassword(await getAuthContext(config), {
200
+ token: input.token,
201
+ newPassword: input.newPassword,
202
+ clientKey: client.value,
203
+ });
204
+ } catch (error) {
205
+ return failure(reportFailure("password reset", error));
206
+ }
207
+ if (!result.ok) return failure(result.error, { field: RESET_FIELD_OF[result.error] });
208
+ redirect(await resolveRedirectTarget(config, `${getAuthRoutes(config).login}?${PASSWORD_RESET_DONE_PARAM}=1`));
209
+ }
210
+
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
+ /** 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
+ }
225
+ }
226
+ }
227
+
228
+ /** Ends the request's sessions and goes to `afterLogout`. The cookies are cleared even if the delete fails. */
229
+ export async function logoutAction(): Promise<void> {
230
+ const config = getSoftureConfig();
231
+ for (const token of await readHeldTokens(config)) {
232
+ try {
233
+ await logoutSession(await getAuthContext(config), token);
234
+ } catch (error) {
235
+ reportFailure("logout", error);
236
+ }
237
+ }
238
+ await clearSessionCookie(config);
239
+ redirect(await resolveRedirectTarget(config, getAuthRoutes(config).afterLogout));
240
+ }
@@ -0,0 +1,14 @@
1
+ // What the adapter hands the server functions: the registered config, the process-wide database
2
+ // handle and the wall clock. Request scope (cookies, headers) stays in this folder.
3
+ import { systemClock, type SoftureConfig } from "@softure-ai/core";
4
+ import { getSoftureConfig } from "@softure-ai/core/next";
5
+ import { getConfiguredDatabase } from "@softure-ai/db";
6
+ import type { AuthContext } from "../server/sessions.js";
7
+
8
+ export async function getAuthContext(config: SoftureConfig = getSoftureConfig()): Promise<AuthContext> {
9
+ if (config.database === null) {
10
+ throw new Error("@softure-ai/auth: softure.config.ts has no database; auth needs one");
11
+ }
12
+ const { db } = await getConfiguredDatabase(config.database);
13
+ return { db, clock: systemClock, config };
14
+ }