@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,90 @@
1
+ // The signed-in user and their roles for server components, actions and route handlers. React's
2
+ // `cache` makes each one lookup per request, however many components ask; nothing is cached
3
+ // across requests, so a revoked role is gone on the next one.
4
+ import { err, ok, type Err, type Ok } from "@softure-ai/core";
5
+ import { getSoftureConfig } from "@softure-ai/core/next";
6
+ import { notFound, redirect } from "next/navigation";
7
+ import { cache } from "react";
8
+ import type { AuthUser } from "../contract.js";
9
+ import { resolveRedirectTarget } from "../redirect-target.js";
10
+ import { toSafeNextPath } from "../safe-next-path.js";
11
+ import { getAuthRoutes } from "../server/options.js";
12
+ import { assertDeclaredRole, findUserRoles } from "../server/roles.js";
13
+ import { findSessionUser } from "../server/sessions.js";
14
+ import { getAuthContext } from "./context.js";
15
+ import { toUrlSearchParams, type PageSearchParams } from "./search-params.js";
16
+ import { readSessionToken } from "./session-cookie.js";
17
+
18
+ /** The user of the request's session, or null. Database failures propagate to the error page. */
19
+ export const getCurrentUser = cache(async (): Promise<AuthUser | null> => {
20
+ const config = getSoftureConfig();
21
+ const token = await readSessionToken(config);
22
+ if (token === null) return null;
23
+ return findSessionUser(await getAuthContext(config), token);
24
+ });
25
+
26
+ export interface RequireUserOptions {
27
+ /** Where to come back after login; a same-origin path. */
28
+ readonly next?: string;
29
+ /**
30
+ * A page's own search params (awaited), handed to the app's `rewriteRedirect` so the login URL
31
+ * can keep the page's channel tag. Without them the rewrite reads as for an action.
32
+ */
33
+ readonly searchParams?: PageSearchParams | undefined;
34
+ }
35
+
36
+ /**
37
+ * The signed-in user; without one, a redirect to the login page (with `next` when given), through
38
+ * the app's `rewriteRedirect`.
39
+ */
40
+ export async function requireUser(options: RequireUserOptions = {}): Promise<AuthUser> {
41
+ const user = await getCurrentUser();
42
+ if (user !== null) return user;
43
+ const config = getSoftureConfig();
44
+ const login = getAuthRoutes(config).login;
45
+ const next = options.next === undefined ? null : toSafeNextPath(options.next, "");
46
+ const path = next === null || next === "" ? login : `${login}?next=${encodeURIComponent(next)}`;
47
+ const searchParams = options.searchParams === undefined ? undefined : toUrlSearchParams(options.searchParams);
48
+ redirect(await resolveRedirectTarget(config, path, searchParams));
49
+ }
50
+
51
+ const NO_ROLES: ReadonlySet<string> = new Set();
52
+
53
+ /** The roles of the request's user; none without a session. */
54
+ export const getCurrentUserRoles = cache(async (): Promise<ReadonlySet<string>> => {
55
+ const user = await getCurrentUser();
56
+ if (user === null) return NO_ROLES;
57
+ return findUserRoles(await getAuthContext(), user);
58
+ });
59
+
60
+ /** The signed-in user when they hold `role`, else null. Throws for an undeclared role. */
61
+ async function findUserWithRole(role: string): Promise<AuthUser | null> {
62
+ assertDeclaredRole(getSoftureConfig(), role);
63
+ const user = await getCurrentUser();
64
+ if (user === null) return null;
65
+ return (await getCurrentUserRoles()).has(role) ? user : null;
66
+ }
67
+
68
+ /**
69
+ * For pages, layouts and route handlers: the signed-in user when they hold `role`; for anyone
70
+ * else, signed in or not, Next's "not found", so the surface does not reveal that it exists.
71
+ */
72
+ export async function requireRole(role: string): Promise<AuthUser> {
73
+ const user = await findUserWithRole(role);
74
+ if (user === null) notFound();
75
+ return user;
76
+ }
77
+
78
+ /**
79
+ * For server actions: the signed-in user when they hold `role`, else `auth.forbidden` (also
80
+ * without a session), for the action to return to its form. Call it before reading any input.
81
+ */
82
+ export async function authorizeRole(role: string): Promise<Ok<AuthUser> | Err<"auth.forbidden">> {
83
+ const user = await findUserWithRole(role);
84
+ return user === null ? err("auth.forbidden") : ok(user);
85
+ }
86
+
87
+ /** For UI decisions such as showing a link; never the access check itself. */
88
+ export async function hasRole(role: string): Promise<boolean> {
89
+ return (await findUserWithRole(role)) !== null;
90
+ }
@@ -0,0 +1,33 @@
1
+ // The Next.js adapter of @softure-ai/auth: pages, server actions, the session route and the
2
+ // current-user and role helpers (docs/02-module-standard.md §8). The route guard is `@softure-ai/auth/proxy`.
3
+ export {
4
+ changePasswordAction,
5
+ forgotPasswordAction,
6
+ loginAction,
7
+ logoutAction,
8
+ registerAction,
9
+ resetPasswordAction,
10
+ } from "./actions.js";
11
+ export {
12
+ authorizeRole,
13
+ getCurrentUser,
14
+ getCurrentUserRoles,
15
+ hasRole,
16
+ requireRole,
17
+ requireUser,
18
+ type RequireUserOptions,
19
+ } from "./current-user.js";
20
+ export { LogoutButton, type LogoutButtonProps } from "./logout-button.js";
21
+ export { getAuthMessages } from "./messages.js";
22
+ export {
23
+ type AuthPageProps,
24
+ ChangePasswordPage,
25
+ createRegisterPage,
26
+ ForgotPasswordPage,
27
+ LoginPage,
28
+ RegisterPage,
29
+ type RegisterPageOptions,
30
+ ResetPasswordPage,
31
+ } from "./pages.js";
32
+ export { getSessionRoute } from "./route.js";
33
+ export type { PageSearchParams } from "./search-params.js";
@@ -0,0 +1,22 @@
1
+ // A logout button for the app's own pages: a plain form posting to `logoutAction`, so it works
2
+ // without JavaScript. Server component.
3
+ import { getSoftureConfig } from "@softure-ai/core/next";
4
+ import { Button, type ButtonVariant } from "@softure-ai/ui";
5
+ import { logoutAction } from "./actions.js";
6
+ import { getAuthMessages } from "./messages.js";
7
+
8
+ export interface LogoutButtonProps {
9
+ readonly variant?: ButtonVariant;
10
+ readonly className?: string;
11
+ }
12
+
13
+ export function LogoutButton({ variant = "secondary", className }: LogoutButtonProps) {
14
+ const messages = getAuthMessages(getSoftureConfig());
15
+ return (
16
+ <form action={logoutAction} className={className}>
17
+ <Button type="submit" variant={variant}>
18
+ {messages.logout.submit}
19
+ </Button>
20
+ </form>
21
+ );
22
+ }
@@ -0,0 +1,9 @@
1
+ import type { SoftureConfig } from "@softure-ai/core";
2
+ import type { AuthMessages } from "../messages/index.js";
3
+ import { getAuthModule } from "../server/options.js";
4
+
5
+ /** The module's copy in the app's locale, with the app's overrides applied. */
6
+ export function getAuthMessages(config: SoftureConfig): AuthMessages {
7
+ // The module factory merged the dictionaries; their shape is the module's own.
8
+ return getAuthModule(config).messages[config.locale] as AuthMessages;
9
+ }
@@ -0,0 +1,16 @@
1
+ // Next.js has no `exports` map, so NodeNext resolution (tsconfig.base.json) only finds
2
+ // `next/navigation.js` and `next/headers.js`. The code must still import the bare specifiers:
3
+ // Next's bundler aliases them per runtime, and the `.js` form bypasses the alias (measured:
4
+ // `next build` failed to collect a route handler importing `next/navigation.js`, MODULE_UNPARSABLE
5
+ // on the vendored app-router context). These declarations give the bare specifiers their types.
6
+ declare module "next/navigation" {
7
+ export * from "next/navigation.js";
8
+ }
9
+
10
+ declare module "next/headers" {
11
+ export * from "next/headers.js";
12
+ }
13
+
14
+ declare module "next/server" {
15
+ export * from "next/server.js";
16
+ }
@@ -0,0 +1,223 @@
1
+ // Pages ready to mount with one line: `export { LoginPage as default } from "@softure-ai/auth/next"`.
2
+ // Server components: they read the config and the session, and render the forms from `../ui`.
3
+ import type { SoftureConfig } from "@softure-ai/core";
4
+ import { getSoftureConfig } from "@softure-ai/core/next";
5
+ import { Card } from "@softure-ai/ui";
6
+ import { notFound, redirect } from "next/navigation";
7
+ import type { ReactNode } from "react";
8
+ import { resolveRedirectTarget } from "../redirect-target.js";
9
+ import { toSafeNextPath } from "../safe-next-path.js";
10
+ import { getAuthOptions, getAuthRoutes } from "../server/options.js";
11
+ import { findPasswordResetUser, isPasswordResetEnabled, RESET_TOKEN_PARAM } from "../server/password-reset.js";
12
+ import { isRegistrationClosed } from "../server/switches.js";
13
+ import { ChangePasswordForm, ForgotPasswordForm, LoginForm, RegisterForm, ResetPasswordForm } from "../ui/auth-forms.js";
14
+ import { changePasswordAction, forgotPasswordAction, loginAction, registerAction, resetPasswordAction } from "./actions.js";
15
+ import { getAuthContext } from "./context.js";
16
+ import { getCurrentUser, requireUser } from "./current-user.js";
17
+ import { getAuthMessages } from "./messages.js";
18
+ import { PASSWORD_RESET_DONE_PARAM } from "./params.js";
19
+ import { toUrlSearchParams } from "./search-params.js";
20
+
21
+ type SearchParams = Promise<Record<string, string | string[] | undefined>>;
22
+
23
+ export interface AuthPageProps {
24
+ readonly searchParams?: SearchParams;
25
+ }
26
+
27
+ const LAYOUT_CLASS = "sft:mx-auto sft:box-border sft:w-full sft:sm:max-w-md sft:px-4 sft:py-4";
28
+ const FOOTER_CLASS = "sft:m-0 sft:text-sm sft:text-muted";
29
+ const LINK_CLASS = "sft:font-medium sft:text-accent";
30
+ /** The server keeps 512 characters of a registration field; nothing longer is echoed into the page. */
31
+ const MAX_CARRIED_LENGTH = 512;
32
+
33
+ function AuthLayout({ title, lead, children }: { title: string; lead: string; children: ReactNode }) {
34
+ return (
35
+ <main className={LAYOUT_CLASS}>
36
+ <Card title={title} subtitle={lead}>
37
+ {children}
38
+ </Card>
39
+ </main>
40
+ );
41
+ }
42
+
43
+ async function readParam(searchParams: SearchParams | undefined, name: string): Promise<string | undefined> {
44
+ const value = (await searchParams)?.[name];
45
+ return Array.isArray(value) ? value[0] : value;
46
+ }
47
+
48
+ async function readNext(searchParams: SearchParams | undefined, fallback: string): Promise<string> {
49
+ return toSafeNextPath(await readParam(searchParams, "next"), fallback);
50
+ }
51
+
52
+ /** Sends a signed-in visitor on from the login or register page, through the app's redirect rewrite. */
53
+ async function redirectSignedIn(config: SoftureConfig, next: string, searchParams: SearchParams | undefined): Promise<never> {
54
+ redirect(await resolveRedirectTarget(config, next, toUrlSearchParams(await searchParams)));
55
+ }
56
+
57
+ export async function LoginPage({ searchParams }: AuthPageProps) {
58
+ const config = getSoftureConfig();
59
+ const routes = getAuthRoutes(config);
60
+ const next = await readNext(searchParams, routes.afterLogin);
61
+ if ((await getCurrentUser()) !== null) await redirectSignedIn(config, next, searchParams);
62
+ const messages = getAuthMessages(config);
63
+ const isClosed = await isRegistrationClosed(await getAuthContext(config));
64
+ return (
65
+ <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
+ />
75
+ </AuthLayout>
76
+ );
77
+ }
78
+
79
+ export interface RegisterPageOptions {
80
+ /** The consent statement, e.g. with links to the terms and the privacy policy. */
81
+ readonly consentLabel?: ReactNode;
82
+ /** The app's own inputs, before the consent checkbox (`auth({ registrationFields })` declares their names). */
83
+ readonly extraFields?: ReactNode;
84
+ }
85
+
86
+ /**
87
+ * A register page with the app's consent label and extra inputs:
88
+ * `export default createRegisterPage({ consentLabel: <>I accept the <a href="/terms">terms</a></> })`.
89
+ * A declared registration field present in the page's URL (`?z=…`) is carried as a hidden input.
90
+ */
91
+ export function createRegisterPage(pageOptions: RegisterPageOptions = {}) {
92
+ return async function RegisterPageWithOptions({ searchParams }: AuthPageProps) {
93
+ return renderRegisterPage(searchParams, pageOptions);
94
+ };
95
+ }
96
+
97
+ export async function RegisterPage({ searchParams }: AuthPageProps) {
98
+ return renderRegisterPage(searchParams, {});
99
+ }
100
+
101
+ async function renderRegisterPage(searchParams: SearchParams | undefined, pageOptions: RegisterPageOptions) {
102
+ const config = getSoftureConfig();
103
+ const routes = getAuthRoutes(config);
104
+ const next = await readNext(searchParams, routes.afterLogin);
105
+ if ((await getCurrentUser()) !== null) await redirectSignedIn(config, next, searchParams);
106
+ const messages = getAuthMessages(config);
107
+ if (await isRegistrationClosed(await getAuthContext(config))) {
108
+ return (
109
+ <AuthLayout title={messages.register.closedTitle} lead={messages.register.closedBody}>
110
+ {null}
111
+ </AuthLayout>
112
+ );
113
+ }
114
+ const options = getAuthOptions(config);
115
+ const carried = await readCarriedFields(searchParams, options.registrationFields);
116
+ return (
117
+ <AuthLayout title={messages.register.title} lead={messages.register.lead}>
118
+ <RegisterForm
119
+ action={registerAction}
120
+ messages={messages}
121
+ locale={config.locale}
122
+ next={next}
123
+ loginHref={routes.login}
124
+ requireConsent={options.requireConsent}
125
+ minPasswordLength={options.password.minLength}
126
+ consentLabel={pageOptions.consentLabel}
127
+ extraFields={
128
+ <>
129
+ {carried.map(([name, value]) => (
130
+ <input key={name} type="hidden" name={name} value={value} />
131
+ ))}
132
+ {pageOptions.extraFields}
133
+ </>
134
+ }
135
+ />
136
+ </AuthLayout>
137
+ );
138
+ }
139
+
140
+ /** The declared registration fields present in the page's URL, carried into the form as hidden inputs. */
141
+ async function readCarriedFields(searchParams: SearchParams | undefined, declared: readonly string[]): Promise<[string, string][]> {
142
+ const carried: [string, string][] = [];
143
+ for (const name of declared) {
144
+ const value = await readParam(searchParams, name);
145
+ if (value !== undefined && value !== "") carried.push([name, value.slice(0, MAX_CARRIED_LENGTH)]);
146
+ }
147
+ return carried;
148
+ }
149
+
150
+ export async function ChangePasswordPage() {
151
+ const config = getSoftureConfig();
152
+ const routes = getAuthRoutes(config);
153
+ await requireUser({ next: routes.changePassword });
154
+ const messages = getAuthMessages(config);
155
+ return (
156
+ <AuthLayout title={messages.changePassword.title} lead={messages.changePassword.lead}>
157
+ <ChangePasswordForm
158
+ action={changePasswordAction}
159
+ messages={messages}
160
+ locale={config.locale}
161
+ minPasswordLength={getAuthOptions(config).password.minLength}
162
+ />
163
+ </AuthLayout>
164
+ );
165
+ }
166
+
167
+ /** Asks for a reset link. Not found when the app configured no sender. */
168
+ export function ForgotPasswordPage() {
169
+ const config = getSoftureConfig();
170
+ if (!isPasswordResetEnabled(config)) notFound();
171
+ const messages = getAuthMessages(config);
172
+ return (
173
+ <AuthLayout title={messages.forgotPassword.title} lead={messages.forgotPassword.lead}>
174
+ <ForgotPasswordForm
175
+ action={forgotPasswordAction}
176
+ messages={messages}
177
+ locale={config.locale}
178
+ ttlMinutes={getAuthOptions(config).passwordReset.ttlMinutes}
179
+ loginHref={getAuthRoutes(config).login}
180
+ />
181
+ </AuthLayout>
182
+ );
183
+ }
184
+
185
+ /**
186
+ * The page a reset link opens. It only checks the token (mail scanners open links too); the form
187
+ * submission consumes it. Its referrer policy is `same-origin`: the token in its URL never goes to
188
+ * another site, and the form still sends the Origin header Next checks on server actions
189
+ * (`no-referrer` would turn it into `null`, and Next would refuse the plain HTML form).
190
+ */
191
+ export async function ResetPasswordPage({ searchParams }: AuthPageProps) {
192
+ const config = getSoftureConfig();
193
+ if (!isPasswordResetEnabled(config)) notFound();
194
+ const routes = getAuthRoutes(config);
195
+ const messages = getAuthMessages(config);
196
+ const token = (await readParam(searchParams, RESET_TOKEN_PARAM)) ?? "";
197
+ const user = token === "" ? null : await findPasswordResetUser(await getAuthContext(config), token);
198
+ const referrerPolicy = <meta name="referrer" content="same-origin" />;
199
+ if (user === null) {
200
+ return (
201
+ <AuthLayout title={messages.resetPassword.invalidTitle} lead={messages.resetPassword.invalidBody}>
202
+ {referrerPolicy}
203
+ <p className={FOOTER_CLASS}>
204
+ <a href={routes.forgotPassword} className={LINK_CLASS}>
205
+ {messages.resetPassword.requestNew}
206
+ </a>
207
+ </p>
208
+ </AuthLayout>
209
+ );
210
+ }
211
+ return (
212
+ <AuthLayout title={messages.resetPassword.title} lead={messages.resetPassword.lead}>
213
+ {referrerPolicy}
214
+ <ResetPasswordForm
215
+ action={resetPasswordAction}
216
+ messages={messages}
217
+ locale={config.locale}
218
+ token={token}
219
+ minPasswordLength={getAuthOptions(config).password.minLength}
220
+ />
221
+ </AuthLayout>
222
+ );
223
+ }
@@ -0,0 +1,4 @@
1
+ // Query parameters the adapter's pages and actions pass between each other.
2
+
3
+ /** Set on the login page after a password reset, so it confirms the change. */
4
+ export const PASSWORD_RESET_DONE_PARAM = "reset";
@@ -0,0 +1,17 @@
1
+ // Route handlers. Mount with a rename, so later handlers of the module fit next to it:
2
+ // `export { getSessionRoute as GET } from "@softure-ai/auth/next"` in app/api/auth/session/route.ts.
3
+ import { errorLogLabel, safeError } from "@softure-ai/core";
4
+ import { getCurrentUser } from "./current-user.js";
5
+
6
+ const NO_STORE = { "cache-control": "no-store" };
7
+
8
+ /** `{ user: { id, email } | null }` for the request's session. Never cached. */
9
+ export async function getSessionRoute(): Promise<Response> {
10
+ try {
11
+ const user = await getCurrentUser();
12
+ return Response.json({ user: user === null ? null : { id: user.id, email: user.email } }, { headers: NO_STORE });
13
+ } catch (error) {
14
+ console.error(`@softure-ai/auth: session lookup failed: ${errorLogLabel(error)}`);
15
+ return Response.json({ error: safeError(error).error }, { status: 500, headers: NO_STORE });
16
+ }
17
+ }
@@ -0,0 +1,14 @@
1
+ // A page's search params in the one shape auth's redirect rewrite takes.
2
+
3
+ /** A page's awaited `searchParams`, or any `URLSearchParams`. */
4
+ export type PageSearchParams = URLSearchParams | Readonly<Record<string, string | readonly string[] | undefined>>;
5
+
6
+ /** `searchParams` as `URLSearchParams`, every value of a repeated name kept. */
7
+ export function toUrlSearchParams(searchParams: PageSearchParams | undefined): URLSearchParams {
8
+ if (searchParams instanceof URLSearchParams) return searchParams;
9
+ const query = new URLSearchParams();
10
+ for (const [name, value] of Object.entries(searchParams ?? {})) {
11
+ for (const item of typeof value === "string" ? [value] : (value ?? [])) query.append(name, item);
12
+ }
13
+ return query;
14
+ }
@@ -0,0 +1,79 @@
1
+ // Reading and writing the session cookie through Next's request scope.
2
+ import type { SoftureConfig } from "@softure-ai/core";
3
+ import { cookies } from "next/headers";
4
+ import type { NewSession } from "../contract.js";
5
+ import { getAuthOptions } from "../server/options.js";
6
+ import { getSessionCookie } from "../session-cookie.js";
7
+
8
+ type CookieStore = Awaited<ReturnType<typeof cookies>>;
9
+
10
+ function readCookie(store: CookieStore, name: string): string | null {
11
+ const value = store.get(name)?.value;
12
+ return value === undefined || value === "" ? null : value;
13
+ }
14
+
15
+ /** The request's session token: the current cookie's, else the legacy session's (`legacySession`). */
16
+ export async function readSessionToken(config: SoftureConfig): Promise<string | null> {
17
+ const store = await cookies();
18
+ return readCookie(store, getSessionCookie(config).name) ?? (await readLegacySessionToken(config));
19
+ }
20
+
21
+ /** The legacy session cookie's token, or null (also without `legacySession`). */
22
+ export async function readLegacySessionToken(config: SoftureConfig): Promise<string | null> {
23
+ const name = getAuthOptions(config).legacySession?.cookieName;
24
+ return name === undefined ? null : readCookie(await cookies(), name);
25
+ }
26
+
27
+ /**
28
+ * Removes the legacy cookie, if the app declared one: with `Path=/` and the configured domain, the
29
+ * only attributes the module knows. A legacy cookie set on another path or domain stays until it
30
+ * expires; its session row is ended anyway.
31
+ */
32
+ async function clearLegacySessionCookie(config: SoftureConfig): Promise<void> {
33
+ const name = getAuthOptions(config).legacySession?.cookieName;
34
+ if (name === undefined) return;
35
+ const store = await cookies();
36
+ if (store.get(name) === undefined) return;
37
+ const cookie = getSessionCookie(config);
38
+ // Browsers refuse a `__Host-` cookie with a Domain or without Secure, the removal included.
39
+ const isHostOnly = name.startsWith("__Host-");
40
+ store.set(name, "", {
41
+ httpOnly: true,
42
+ secure: isHostOnly || cookie.secure,
43
+ sameSite: cookie.sameSite,
44
+ path: "/",
45
+ domain: isHostOnly ? undefined : cookie.domain,
46
+ maxAge: 0,
47
+ });
48
+ }
49
+
50
+ /** Only in a server action or a route handler: pages cannot set cookies. */
51
+ export async function writeSessionCookie(config: SoftureConfig, session: NewSession): Promise<void> {
52
+ const cookie = getSessionCookie(config);
53
+ const store = await cookies();
54
+ store.set(cookie.name, session.token, {
55
+ httpOnly: cookie.httpOnly,
56
+ secure: cookie.secure,
57
+ sameSite: cookie.sameSite,
58
+ path: cookie.path,
59
+ domain: cookie.domain,
60
+ maxAge: cookie.maxAgeSeconds,
61
+ });
62
+ // A new session replaces the legacy one: the browser keeps one cookie from here on.
63
+ await clearLegacySessionCookie(config);
64
+ }
65
+
66
+ /** Removes the cookie with the attributes it was set with, so the browser drops that one. */
67
+ export async function clearSessionCookie(config: SoftureConfig): Promise<void> {
68
+ const cookie = getSessionCookie(config);
69
+ const store = await cookies();
70
+ store.set(cookie.name, "", {
71
+ httpOnly: cookie.httpOnly,
72
+ secure: cookie.secure,
73
+ sameSite: cookie.sameSite,
74
+ path: cookie.path,
75
+ domain: cookie.domain,
76
+ maxAge: 0,
77
+ });
78
+ await clearLegacySessionCookie(config);
79
+ }
package/src/options.ts ADDED
@@ -0,0 +1,154 @@
1
+ // The options an app passes to `auth({ ... })` in softure.config.ts, parsed at startup.
2
+ import type { ModuleContext, SoftureConfig } from "@softure-ai/core";
3
+ import type { Queryable } from "@softure-ai/db";
4
+ import { z } from "zod";
5
+ import type { RegisteredEvent } from "./contract.js";
6
+ import type { PasswordResetSender } from "./password-reset-sender.js";
7
+ import { ROLE_NAME_PATTERN } from "./roles.js";
8
+
9
+ /**
10
+ * OWASP's scrypt cost for passwords: N = 2^17, r = 8, p = 1. One hash takes 128 * N * r bytes
11
+ * (128 MiB) and about 0.4 s of a core; Node runs up to four at once on its libuv pool, so a burst of
12
+ * logins can take 512 MiB. A small server lowers `password.scrypt.cost` (README §3).
13
+ */
14
+ export const DEFAULT_SCRYPT_COST = 2 ** 17;
15
+
16
+ const MAX_EMAIL_LENGTH = 254;
17
+ const COOKIE_NAME = /^[A-Za-z0-9_-]{1,64}$/;
18
+ /** A legacy cookie may carry its own prefix (`__Host-session`) or a dot. */
19
+ const LEGACY_COOKIE_NAME = /^[A-Za-z0-9_.-]{1,128}$/;
20
+ const DEFAULT_COOKIE_NAME = "softure_session";
21
+ const REGISTRATION_FIELD_NAME = /^[a-z][a-zA-Z0-9_]{0,31}$/;
22
+ /** The register form's own fields, which an app field must not shadow. */
23
+ const REGISTER_FORM_FIELDS: ReadonlySet<string> = new Set(["email", "password", "next", "consent"]);
24
+ const DOMAIN = /^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/;
25
+
26
+ /** Runs inside the registration transaction; a thrown error rolls the registration back. */
27
+ export type OnRegisteredHook = (event: RegisteredEvent, ctx: ModuleContext<Queryable>) => Promise<void>;
28
+
29
+ /** What a redirect rewrite gets besides the path. */
30
+ export interface RewriteRedirectContext {
31
+ readonly config: SoftureConfig;
32
+ /**
33
+ * The page's own search params, when a page redirects while it renders (the login and register
34
+ * pages send a signed-in visitor on); absent for an action's redirect. A render's `Referer` is the
35
+ * page before, not this one.
36
+ */
37
+ readonly searchParams?: URLSearchParams;
38
+ }
39
+
40
+ /**
41
+ * Rewrites the path auth redirects to (after login, sign-up, a password reset and logout, and the
42
+ * login and register pages' redirect of a signed-in visitor), e.g. analytics' `tagRedirect`, which
43
+ * keeps the channel tag. A result that is not a path on this app, or a failure, leaves auth's own path.
44
+ */
45
+ export type RewriteRedirect = (path: string, ctx: RewriteRedirectContext) => Promise<string> | string;
46
+
47
+ function isPowerOfTwo(value: number): boolean {
48
+ return Number.isInteger(Math.log2(value));
49
+ }
50
+
51
+ const scryptSchema = z.strictObject({
52
+ /** N: CPU and memory cost, a power of two. */
53
+ cost: z
54
+ .number()
55
+ .int()
56
+ .min(2 ** 10)
57
+ .max(2 ** 20)
58
+ .refine(isPowerOfTwo, "must be a power of two")
59
+ .default(DEFAULT_SCRYPT_COST),
60
+ /** r: block size. */
61
+ blockSize: z.number().int().min(1).max(32).default(8),
62
+ /** p: parallelization. */
63
+ parallelization: z.number().int().min(1).max(16).default(1),
64
+ });
65
+
66
+ export const authOptionsSchema = z.strictObject({
67
+ password: z
68
+ .strictObject({
69
+ /** Shortest password a user may set (characters). */
70
+ minLength: z.number().int().min(8).max(128).default(10),
71
+ /** Hash cost; memory per hash is 128 * cost * blockSize bytes. Raising it rehashes each password at its owner's next login. */
72
+ scrypt: scryptSchema.prefault({}),
73
+ })
74
+ .prefault({}),
75
+ session: z
76
+ .strictObject({
77
+ /** How long a session lasts from login; it is not extended by use. */
78
+ ttlDays: z.number().int().min(1).max(365).default(30),
79
+ })
80
+ .prefault({}),
81
+ cookie: z
82
+ .strictObject({
83
+ /** Base name; `__Host-` or `__Secure-` is added when the cookie is secure. */
84
+ name: z.string().regex(COOKIE_NAME, "must be 1-64 letters, digits, _ or -").default(DEFAULT_COOKIE_NAME),
85
+ /** Share the session with subdomains, e.g. `example.com` for the apex and `app.example.com`. */
86
+ domain: z.string().regex(DOMAIN, "must be a lowercase host name such as example.com").optional(),
87
+ /** Defaults to whether `appOrigin` is https. */
88
+ secure: z.boolean().optional(),
89
+ })
90
+ .prefault({}),
91
+ /**
92
+ * Sessions of the system the app took over, so adopting the module does not log everyone out:
93
+ * the cookie it set and the shape of its tokens, stored as the sha256 hex of the token like here.
94
+ * Read when the current cookie is absent; ended and cleared at the next login, register or logout.
95
+ */
96
+ legacySession: z
97
+ .strictObject({
98
+ /** The old cookie's full name, prefix included. */
99
+ cookieName: z.string().regex(LEGACY_COOKIE_NAME, "must be 1-128 letters, digits, _ . or -"),
100
+ /** The whole token's shape, e.g. /[0-9a-f]{64}/; anchored by the module. */
101
+ tokenPattern: z.custom<RegExp>(
102
+ (value) => value instanceof RegExp && !value.global && !value.sticky,
103
+ "must be a RegExp without the g or y flag",
104
+ ),
105
+ })
106
+ .optional(),
107
+ /**
108
+ * Extra register form fields handed to `onRegistered` as `event.fields` (strings, at most 512
109
+ * characters; empty ones are left out). `RegisterPage` carries a declared field from its URL as a
110
+ * hidden input (e.g. `?z=` for a channel tag). Values come from the client: validate them in the hook.
111
+ */
112
+ registrationFields: z
113
+ .array(
114
+ z
115
+ .string()
116
+ .regex(REGISTRATION_FIELD_NAME, "must be a field name such as channel (a-z first, then letters, digits or _, at most 32)")
117
+ .refine((name) => !REGISTER_FORM_FIELDS.has(name), "is a field of the register form itself"),
118
+ )
119
+ .refine((names) => new Set(names).size === names.length, "must not repeat a name")
120
+ .default([]),
121
+ /** Registration needs a ticked consent checkbox. */
122
+ requireConsent: z.boolean().default(true),
123
+ /** Declared default of the `auth.registration_closed` switch. */
124
+ registrationClosed: z.boolean().default(false),
125
+ /** Role names the app checks besides `admin`, which is always declared. */
126
+ roles: z.array(z.string().regex(ROLE_NAME_PATTERN, "must be a role name such as editor (a-z, 0-9, _ or -, at most 32)")).default([]),
127
+ /**
128
+ * Initial admin list: while an email is listed, the account with that email holds `admin`.
129
+ * Auth does not verify emails, so create these accounts before deploying the list.
130
+ */
131
+ adminEmails: z.array(z.string().trim().toLowerCase().max(MAX_EMAIL_LENGTH).pipe(z.email("must be an email address"))).default([]),
132
+ passwordReset: z
133
+ .strictObject({
134
+ /** Delivers reset links. Without it password reset is off: no link, and its pages are not found. */
135
+ send: z.custom<PasswordResetSender>((value) => typeof value === "function", "must be a function").optional(),
136
+ /** How long a reset link works. */
137
+ ttlMinutes: z.number().int().min(5).max(1440).default(60),
138
+ })
139
+ .prefault({}),
140
+ /** Called after an account is created, in the same transaction (e.g. to store the consent). */
141
+ onRegistered: z.custom<OnRegisteredHook>((value) => typeof value === "function", "must be a function").optional(),
142
+ /** Rewrites the path of every auth redirect (e.g. `tagRedirect` from `@softure-ai/analytics/next`). */
143
+ rewriteRedirect: z.custom<RewriteRedirect>((value) => typeof value === "function", "must be a function").optional(),
144
+ }).superRefine((options, context) => {
145
+ const legacy = options.legacySession?.cookieName;
146
+ const base = options.cookie.name;
147
+ if (legacy !== undefined && [base, `__Host-${base}`, `__Secure-${base}`].includes(legacy)) {
148
+ context.addIssue({ code: "custom", path: ["legacySession", "cookieName"], message: "must differ from the current session cookie's name" });
149
+ }
150
+ });
151
+
152
+ export type AuthOptionsInput = z.input<typeof authOptionsSchema>;
153
+ export type AuthOptions = z.output<typeof authOptionsSchema>;
154
+ export type ScryptParams = z.output<typeof scryptSchema>;