@softure-ai/auth 0.1.5 → 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 (130) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +130 -21
  3. package/dist/contract.d.ts +3 -1
  4. package/dist/contract.d.ts.map +1 -1
  5. package/dist/contract.js.map +1 -1
  6. package/dist/index.d.ts +6 -0
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +2 -2
  9. package/dist/index.js.map +1 -1
  10. package/dist/messages/en.d.ts +1 -0
  11. package/dist/messages/en.d.ts.map +1 -1
  12. package/dist/messages/en.js +1 -0
  13. package/dist/messages/en.js.map +1 -1
  14. package/dist/messages/index.d.ts +2 -0
  15. package/dist/messages/index.d.ts.map +1 -1
  16. package/dist/messages/pl.d.ts.map +1 -1
  17. package/dist/messages/pl.js +1 -0
  18. package/dist/messages/pl.js.map +1 -1
  19. package/dist/next/actions.d.ts +1 -1
  20. package/dist/next/actions.d.ts.map +1 -1
  21. package/dist/next/actions.js +37 -16
  22. package/dist/next/actions.js.map +1 -1
  23. package/dist/next/context.js +2 -2
  24. package/dist/next/context.js.map +1 -1
  25. package/dist/next/index.d.ts +1 -1
  26. package/dist/next/index.d.ts.map +1 -1
  27. package/dist/next/index.js +1 -1
  28. package/dist/next/index.js.map +1 -1
  29. package/dist/next/pages.d.ts +13 -0
  30. package/dist/next/pages.d.ts.map +1 -1
  31. package/dist/next/pages.js +28 -2
  32. package/dist/next/pages.js.map +1 -1
  33. package/dist/next/session-cookie.d.ts +3 -0
  34. package/dist/next/session-cookie.d.ts.map +1 -1
  35. package/dist/next/session-cookie.js +39 -2
  36. package/dist/next/session-cookie.js.map +1 -1
  37. package/dist/options.d.ts +10 -1
  38. package/dist/options.d.ts.map +1 -1
  39. package/dist/options.js +44 -3
  40. package/dist/options.js.map +1 -1
  41. package/dist/proxy/index.d.ts +5 -0
  42. package/dist/proxy/index.d.ts.map +1 -1
  43. package/dist/proxy/index.js +25 -7
  44. package/dist/proxy/index.js.map +1 -1
  45. package/dist/safe-next-path.d.ts +3 -1
  46. package/dist/safe-next-path.d.ts.map +1 -1
  47. package/dist/safe-next-path.js +9 -3
  48. package/dist/safe-next-path.js.map +1 -1
  49. package/dist/scripts/index.d.ts +1 -0
  50. package/dist/scripts/index.d.ts.map +1 -1
  51. package/dist/scripts/index.js +3 -1
  52. package/dist/scripts/index.js.map +1 -1
  53. package/dist/scripts/temporary-password.d.ts +12 -0
  54. package/dist/scripts/temporary-password.d.ts.map +1 -0
  55. package/dist/scripts/temporary-password.js +47 -0
  56. package/dist/scripts/temporary-password.js.map +1 -0
  57. package/dist/server/change-password.d.ts +1 -1
  58. package/dist/server/change-password.d.ts.map +1 -1
  59. package/dist/server/change-password.js +4 -1
  60. package/dist/server/change-password.js.map +1 -1
  61. package/dist/server/index.d.ts +2 -2
  62. package/dist/server/index.d.ts.map +1 -1
  63. package/dist/server/index.js +2 -2
  64. package/dist/server/index.js.map +1 -1
  65. package/dist/server/login.js +5 -4
  66. package/dist/server/login.js.map +1 -1
  67. package/dist/server/options.d.ts +2 -0
  68. package/dist/server/options.d.ts.map +1 -1
  69. package/dist/server/options.js +14 -0
  70. package/dist/server/options.js.map +1 -1
  71. package/dist/server/password.d.ts +10 -3
  72. package/dist/server/password.d.ts.map +1 -1
  73. package/dist/server/password.js +24 -8
  74. package/dist/server/password.js.map +1 -1
  75. package/dist/server/rate-limits.d.ts +3 -2
  76. package/dist/server/rate-limits.d.ts.map +1 -1
  77. package/dist/server/rate-limits.js +9 -3
  78. package/dist/server/rate-limits.js.map +1 -1
  79. package/dist/server/register.d.ts +2 -0
  80. package/dist/server/register.d.ts.map +1 -1
  81. package/dist/server/register.js +13 -1
  82. package/dist/server/register.js.map +1 -1
  83. package/dist/server/session-token.d.ts +6 -2
  84. package/dist/server/session-token.d.ts.map +1 -1
  85. package/dist/server/session-token.js +7 -3
  86. package/dist/server/session-token.js.map +1 -1
  87. package/dist/server/sessions.d.ts +9 -0
  88. package/dist/server/sessions.d.ts.map +1 -1
  89. package/dist/server/sessions.js +13 -4
  90. package/dist/server/sessions.js.map +1 -1
  91. package/dist/testing/account.d.ts +17 -0
  92. package/dist/testing/account.d.ts.map +1 -0
  93. package/dist/testing/account.js +31 -0
  94. package/dist/testing/account.js.map +1 -0
  95. package/dist/testing/index.d.ts +2 -0
  96. package/dist/testing/index.d.ts.map +1 -0
  97. package/dist/testing/index.js +4 -0
  98. package/dist/testing/index.js.map +1 -0
  99. package/dist/ui/auth-forms.d.ts +14 -7
  100. package/dist/ui/auth-forms.d.ts.map +1 -1
  101. package/dist/ui/auth-forms.js +14 -12
  102. package/dist/ui/auth-forms.js.map +1 -1
  103. package/module.json +2 -2
  104. package/package.json +15 -3
  105. package/src/contract.ts +3 -0
  106. package/src/index.ts +2 -2
  107. package/src/messages/en.ts +1 -0
  108. package/src/messages/pl.ts +1 -0
  109. package/src/next/actions.ts +38 -14
  110. package/src/next/context.ts +2 -2
  111. package/src/next/index.ts +10 -1
  112. package/src/next/pages.tsx +44 -0
  113. package/src/next/session-cookie.ts +42 -2
  114. package/src/options.ts +49 -3
  115. package/src/proxy/index.ts +35 -8
  116. package/src/safe-next-path.ts +9 -3
  117. package/src/scripts/index.ts +7 -1
  118. package/src/scripts/temporary-password.ts +62 -0
  119. package/src/server/change-password.ts +4 -1
  120. package/src/server/index.ts +10 -2
  121. package/src/server/login.ts +5 -5
  122. package/src/server/options.ts +15 -0
  123. package/src/server/password.ts +26 -8
  124. package/src/server/rate-limits.ts +10 -3
  125. package/src/server/register.ts +16 -1
  126. package/src/server/session-token.ts +7 -3
  127. package/src/server/sessions.ts +19 -4
  128. package/src/testing/account.ts +43 -0
  129. package/src/testing/index.ts +3 -0
  130. package/src/ui/auth-forms.tsx +26 -7
package/src/next/index.ts CHANGED
@@ -19,6 +19,15 @@ export {
19
19
  } from "./current-user.js";
20
20
  export { LogoutButton, type LogoutButtonProps } from "./logout-button.js";
21
21
  export { getAuthMessages } from "./messages.js";
22
- export { type AuthPageProps, ChangePasswordPage, ForgotPasswordPage, LoginPage, RegisterPage, ResetPasswordPage } from "./pages.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";
23
32
  export { getSessionRoute } from "./route.js";
24
33
  export type { PageSearchParams } from "./search-params.js";
@@ -27,6 +27,8 @@ export interface AuthPageProps {
27
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
28
  const FOOTER_CLASS = "sft:m-0 sft:text-sm sft:text-muted";
29
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;
30
32
 
31
33
  function AuthLayout({ title, lead, children }: { title: string; lead: string; children: ReactNode }) {
32
34
  return (
@@ -74,7 +76,29 @@ export async function LoginPage({ searchParams }: AuthPageProps) {
74
76
  );
75
77
  }
76
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
+
77
97
  export async function RegisterPage({ searchParams }: AuthPageProps) {
98
+ return renderRegisterPage(searchParams, {});
99
+ }
100
+
101
+ async function renderRegisterPage(searchParams: SearchParams | undefined, pageOptions: RegisterPageOptions) {
78
102
  const config = getSoftureConfig();
79
103
  const routes = getAuthRoutes(config);
80
104
  const next = await readNext(searchParams, routes.afterLogin);
@@ -88,6 +112,7 @@ export async function RegisterPage({ searchParams }: AuthPageProps) {
88
112
  );
89
113
  }
90
114
  const options = getAuthOptions(config);
115
+ const carried = await readCarriedFields(searchParams, options.registrationFields);
91
116
  return (
92
117
  <AuthLayout title={messages.register.title} lead={messages.register.lead}>
93
118
  <RegisterForm
@@ -98,11 +123,30 @@ export async function RegisterPage({ searchParams }: AuthPageProps) {
98
123
  loginHref={routes.login}
99
124
  requireConsent={options.requireConsent}
100
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
+ }
101
135
  />
102
136
  </AuthLayout>
103
137
  );
104
138
  }
105
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
+
106
150
  export async function ChangePasswordPage() {
107
151
  const config = getSoftureConfig();
108
152
  const routes = getAuthRoutes(config);
@@ -2,12 +2,49 @@
2
2
  import type { SoftureConfig } from "@softure-ai/core";
3
3
  import { cookies } from "next/headers";
4
4
  import type { NewSession } from "../contract.js";
5
+ import { getAuthOptions } from "../server/options.js";
5
6
  import { getSessionCookie } from "../session-cookie.js";
6
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`). */
7
16
  export async function readSessionToken(config: SoftureConfig): Promise<string | null> {
8
17
  const store = await cookies();
9
- const value = store.get(getSessionCookie(config).name)?.value;
10
- return value === undefined || value === "" ? null : value;
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
+ });
11
48
  }
12
49
 
13
50
  /** Only in a server action or a route handler: pages cannot set cookies. */
@@ -22,6 +59,8 @@ export async function writeSessionCookie(config: SoftureConfig, session: NewSess
22
59
  domain: cookie.domain,
23
60
  maxAge: cookie.maxAgeSeconds,
24
61
  });
62
+ // A new session replaces the legacy one: the browser keeps one cookie from here on.
63
+ await clearLegacySessionCookie(config);
25
64
  }
26
65
 
27
66
  /** Removes the cookie with the attributes it was set with, so the browser drops that one. */
@@ -36,4 +75,5 @@ export async function clearSessionCookie(config: SoftureConfig): Promise<void> {
36
75
  domain: cookie.domain,
37
76
  maxAge: 0,
38
77
  });
78
+ await clearLegacySessionCookie(config);
39
79
  }
package/src/options.ts CHANGED
@@ -6,11 +6,21 @@ import type { RegisteredEvent } from "./contract.js";
6
6
  import type { PasswordResetSender } from "./password-reset-sender.js";
7
7
  import { ROLE_NAME_PATTERN } from "./roles.js";
8
8
 
9
- /** OWASP's scrypt cost for passwords: N = 2^17, r = 8, p = 1 (about 128 MiB per hash). */
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
+ */
10
14
  export const DEFAULT_SCRYPT_COST = 2 ** 17;
11
15
 
12
16
  const MAX_EMAIL_LENGTH = 254;
13
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"]);
14
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])?)+$/;
15
25
 
16
26
  /** Runs inside the registration transaction; a thrown error rolls the registration back. */
@@ -58,7 +68,7 @@ export const authOptionsSchema = z.strictObject({
58
68
  .strictObject({
59
69
  /** Shortest password a user may set (characters). */
60
70
  minLength: z.number().int().min(8).max(128).default(10),
61
- /** Hash cost. Raising it rehashes each password at its owner's next login. */
71
+ /** Hash cost; memory per hash is 128 * cost * blockSize bytes. Raising it rehashes each password at its owner's next login. */
62
72
  scrypt: scryptSchema.prefault({}),
63
73
  })
64
74
  .prefault({}),
@@ -71,13 +81,43 @@ export const authOptionsSchema = z.strictObject({
71
81
  cookie: z
72
82
  .strictObject({
73
83
  /** Base name; `__Host-` or `__Secure-` is added when the cookie is secure. */
74
- name: z.string().regex(COOKIE_NAME, "must be 1-64 letters, digits, _ or -").default("softure_session"),
84
+ name: z.string().regex(COOKIE_NAME, "must be 1-64 letters, digits, _ or -").default(DEFAULT_COOKIE_NAME),
75
85
  /** Share the session with subdomains, e.g. `example.com` for the apex and `app.example.com`. */
76
86
  domain: z.string().regex(DOMAIN, "must be a lowercase host name such as example.com").optional(),
77
87
  /** Defaults to whether `appOrigin` is https. */
78
88
  secure: z.boolean().optional(),
79
89
  })
80
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([]),
81
121
  /** Registration needs a ticked consent checkbox. */
82
122
  requireConsent: z.boolean().default(true),
83
123
  /** Declared default of the `auth.registration_closed` switch. */
@@ -101,6 +141,12 @@ export const authOptionsSchema = z.strictObject({
101
141
  onRegistered: z.custom<OnRegisteredHook>((value) => typeof value === "function", "must be a function").optional(),
102
142
  /** Rewrites the path of every auth redirect (e.g. `tagRedirect` from `@softure-ai/analytics/next`). */
103
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
+ }
104
150
  });
105
151
 
106
152
  export type AuthOptionsInput = z.input<typeof authOptionsSchema>;
@@ -5,31 +5,53 @@
5
5
  //
6
6
  // It checks that the session cookie is present, nothing more: an optimistic check that keeps
7
7
  // anonymous visitors off private pages without a database round trip in the proxy. Pages and
8
- // actions still call `requireUser`, which reads the session row.
8
+ // actions still call `requireUser`, which reads the session row. An app that is private by default
9
+ // protects "/" and lists its public paths in `exclude`; auth's own public pages are never guarded.
9
10
  import type { SoftureConfig } from "@softure-ai/core";
10
- import { getAuthRoutes } from "../server/options.js";
11
+ import { getAuthOptions, getAuthRoutes } from "../server/options.js";
11
12
  import { getSessionCookie, readSessionToken } from "../session-cookie.js";
12
13
 
13
14
  export interface AuthGuardOptions {
14
15
  /** Path prefixes that need a session; each matches whole segments (`/account` → `/account/…`). */
15
16
  readonly protect: readonly string[];
17
+ /**
18
+ * Path prefixes that never need one, checked before `protect` (e.g. `protect: ["/"]` with the
19
+ * public pages here). `"/"` here is the home page only. The change-password route stays guarded.
20
+ */
21
+ readonly exclude?: readonly string[];
16
22
  }
17
23
 
24
+ /** Mounted at a fixed path by the module (manifest `mount`); it answers `{ user: null }` without a session. */
25
+ const SESSION_ROUTE = "/api/auth/session";
26
+
18
27
  export type AuthGuard = (request: Request) => Response | null;
19
28
 
20
29
  /** A guard that redirects to the login page (with `?next=`) for protected paths without a session cookie. */
21
30
  export function createAuthGuard(config: SoftureConfig, options: AuthGuardOptions): AuthGuard {
22
31
  const routes = getAuthRoutes(config);
23
- const cookieName = getSessionCookie(config).name;
24
- const prefixes = [...options.protect, routes.changePassword].map(normalizePrefix);
32
+ const cookieNames = [getSessionCookie(config).name, getAuthOptions(config).legacySession?.cookieName].filter((name) => name !== undefined);
33
+ const prefixes = options.protect.map((prefix) => normalizePrefix(prefix, "protected"));
34
+ const changePassword = normalizePrefix(routes.changePassword, "protected");
35
+ // Auth's own public pages: guarding them would send a visitor from the login page to itself.
36
+ const publicPaths = [routes.login, routes.register, routes.forgotPassword, routes.resetPassword, SESSION_ROUTE].map((path) =>
37
+ normalizePrefix(path, "excluded"),
38
+ );
39
+ const excluded = (options.exclude ?? []).map((prefix) => normalizePrefix(prefix, "excluded"));
40
+
41
+ const isGuarded = (path: string): boolean => {
42
+ if (isUnder(path, changePassword)) return true;
43
+ if ([...publicPaths, ...excluded].some((prefix) => isExcludedBy(path, prefix))) return false;
44
+ return prefixes.some((prefix) => isUnder(path, prefix));
45
+ };
25
46
 
26
47
  return (request) => {
27
48
  const url = new URL(request.url);
28
49
  // Compared decoded and lowercased, so `/%61ccount` or `/ACCOUNT` (which a case-insensitive
29
50
  // front proxy may route to /account) is guarded too. Undecodable paths are guarded.
30
51
  const path = decodePath(url.pathname);
31
- if (path !== null && !prefixes.some((prefix) => isUnder(path, prefix))) return null;
32
- if (readSessionToken(request.headers.get("cookie"), cookieName) !== null) return null;
52
+ if (path !== null && !isGuarded(path)) return null;
53
+ const cookieHeader = request.headers.get("cookie");
54
+ if (cookieNames.some((name) => readSessionToken(cookieHeader, name) !== null)) return null;
33
55
  // Built on appOrigin: behind a proxy the request URL may carry an internal host.
34
56
  const login = new URL(routes.login, config.appOrigin);
35
57
  login.searchParams.set("next", `${url.pathname}${url.search}`);
@@ -37,9 +59,9 @@ export function createAuthGuard(config: SoftureConfig, options: AuthGuardOptions
37
59
  };
38
60
  }
39
61
 
40
- function normalizePrefix(prefix: string): string {
62
+ function normalizePrefix(prefix: string, kind: "protected" | "excluded"): string {
41
63
  if (!prefix.startsWith("/")) {
42
- throw new Error(`createAuthGuard: protected path "${prefix}" must start with /`);
64
+ throw new Error(`createAuthGuard: ${kind} path "${prefix}" must start with /`);
43
65
  }
44
66
  const trimmed = prefix.length > 1 && prefix.endsWith("/") ? prefix.slice(0, -1) : prefix;
45
67
  return trimmed.toLowerCase();
@@ -53,6 +75,11 @@ function decodePath(pathname: string): string | null {
53
75
  }
54
76
  }
55
77
 
78
+ /** An exclusion of "/" is the home page: excluding every path would switch the guard off. */
79
+ function isExcludedBy(pathname: string, prefix: string): boolean {
80
+ return prefix === "/" ? pathname === "/" : isUnder(pathname, prefix);
81
+ }
82
+
56
83
  function isUnder(pathname: string, prefix: string): boolean {
57
84
  return prefix === "/" || pathname === prefix || pathname.startsWith(`${prefix}/`);
58
85
  }
@@ -1,11 +1,17 @@
1
1
  // Where to go after login. `next` comes from the query string, so anyone can craft it: only a path
2
2
  // on this app is accepted, never another origin (`//evil.example`, `/\evil.example`, `https://…`).
3
3
  const BASE = "http://softure.invalid";
4
- const MAX_LENGTH = 2048;
4
+ /** Room for an OAuth authorize URL (state, PKCE challenge, resource, scope) under common URL limits. */
5
+ export const MAX_NEXT_PATH_LENGTH = 8192;
5
6
 
6
- /** `candidate` when it is a same-origin path, else `fallback`. */
7
+ /** `candidate` when it is a same-origin path, else `fallback`. A path over the cap is logged by length. */
7
8
  export function toSafeNextPath(candidate: unknown, fallback: string): string {
8
- if (typeof candidate !== "string" || candidate.length > MAX_LENGTH) return fallback;
9
+ if (typeof candidate !== "string") return fallback;
10
+ if (candidate.length > MAX_NEXT_PATH_LENGTH) {
11
+ // The length only: the path may carry tokens.
12
+ console.warn(`@softure-ai/auth: a next path of ${String(candidate.length)} characters is over the ${String(MAX_NEXT_PATH_LENGTH)} limit; using the fallback`);
13
+ return fallback;
14
+ }
9
15
  if (!candidate.startsWith("/") || candidate.startsWith("//") || candidate.startsWith("/\\")) return fallback;
10
16
  // eslint-disable-next-line no-control-regex -- control characters are exactly what is refused
11
17
  if (/[\u0000-\u001f\u007f\\]/.test(candidate)) return fallback;
@@ -1,2 +1,8 @@
1
- // `@softure-ai/auth/scripts`: ops scripts that grant and revoke roles (see the README, "Roles").
1
+ // `@softure-ai/auth/scripts`: ops scripts that grant and revoke roles and set a temporary password
2
+ // (see the README, "Roles" and "Account recovery").
2
3
  export { createGrantRoleScript, createRevokeRoleScript, type RoleScriptArgs, type RoleScriptOptions } from "./role-scripts.js";
4
+ export {
5
+ createSetTemporaryPasswordScript,
6
+ type TemporaryPasswordScriptArgs,
7
+ type TemporaryPasswordScriptOptions,
8
+ } from "./temporary-password.js";
@@ -0,0 +1,62 @@
1
+ // The operator's account recovery: a safe ops script (`@softure-ai/ops/scripts`), dry run by
2
+ // default, `--commit` writes. It sets a random password, ends every session of the account and its
3
+ // pending reset link, and prints the password once for the operator to hand over through a channel
4
+ // that proves the owner (a reply to the account's own address). Reports carry the user id, never the email.
5
+ import { randomBytes } from "node:crypto";
6
+ import { ok, systemClock, type Clock, type SoftureConfig } from "@softure-ai/core";
7
+ import { defineOpsScript, refuseOpsScript, type OpsScript } from "@softure-ai/ops/scripts";
8
+ import { eq } from "drizzle-orm";
9
+ import { z } from "zod";
10
+ import { passwordResets, sessions, users } from "../schema.js";
11
+ import { getAuthOptions } from "../server/options.js";
12
+ import { hashPassword } from "../server/password.js";
13
+ import { revokeUserSessions, type AuthContext } from "../server/sessions.js";
14
+ import { normalizeEmail } from "../server/validation.js";
15
+
16
+ /** Long enough to be out of guessing range in any rate limit window. */
17
+ const MIN_TEMPORARY_LENGTH = 20;
18
+
19
+ export interface TemporaryPasswordScriptArgs {
20
+ readonly email: string;
21
+ }
22
+
23
+ export interface TemporaryPasswordScriptOptions {
24
+ /** The time stored as `password_changed_at`; the system clock by default. */
25
+ readonly clock?: Clock;
26
+ }
27
+
28
+ const scriptArgs = z.strictObject({ email: z.string().min(1, "--email=<account email> is required") });
29
+
30
+ /** A random password of `length` base64url characters. */
31
+ function createTemporaryPassword(length: number): string {
32
+ return randomBytes(Math.ceil((length * 3) / 4)).toString("base64url").slice(0, length);
33
+ }
34
+
35
+ /** `set-temporary-password --email=…`: a new random password, every session and reset link ended. */
36
+ export function createSetTemporaryPasswordScript(
37
+ config: SoftureConfig,
38
+ options: TemporaryPasswordScriptOptions = {},
39
+ ): OpsScript<TemporaryPasswordScriptArgs> {
40
+ const clock = options.clock ?? systemClock;
41
+ return defineOpsScript({
42
+ name: "set-temporary-password",
43
+ description: "Sets a random password for the account with the given email and ends its sessions and reset link.",
44
+ usage: ["--email=<account email>"],
45
+ args: scriptArgs,
46
+ run: async (tx, args) => {
47
+ const ctx: AuthContext = { db: tx, clock, config };
48
+ const [account] = await tx.select({ id: users.id }).from(users).where(eq(users.email, normalizeEmail(args.email))).limit(1);
49
+ if (account === undefined) return refuseOpsScript("no account has this email");
50
+ const before = { userId: account.id, sessions: (await tx.select().from(sessions).where(eq(sessions.userId, account.id))).length };
51
+
52
+ const authOptions = getAuthOptions(config);
53
+ const temporaryPassword = createTemporaryPassword(Math.max(authOptions.password.minLength, MIN_TEMPORARY_LENGTH));
54
+ const passwordHash = await hashPassword(temporaryPassword, authOptions.password.scrypt);
55
+ await tx.update(users).set({ passwordHash, passwordChangedAt: clock.now() }).where(eq(users.id, account.id));
56
+ await revokeUserSessions(ctx, account.id);
57
+ await tx.delete(passwordResets).where(eq(passwordResets.userId, account.id));
58
+ const remaining = (await tx.select().from(sessions).where(eq(sessions.userId, account.id))).length;
59
+ return ok({ before, after: { userId: account.id, sessions: remaining, temporaryPassword } });
60
+ },
61
+ });
62
+ }
@@ -1,4 +1,4 @@
1
- // Password change for a signed-in user. The new hash, the end of every other session of the user
1
+ // Password change for a signed-in user. The new password must differ from the current one. The new hash, the end of every other session of the user
2
2
  // and of a pending reset link happen in one transaction; the session that made the change stays signed in.
3
3
  import { err, ok, type Err, type Ok } from "@softure-ai/core";
4
4
  import type { RateLimitRejection } from "@softure-ai/security";
@@ -22,6 +22,7 @@ export interface ChangePasswordInput {
22
22
  export type ChangePasswordErrorCode =
23
23
  | "auth.unauthenticated"
24
24
  | "auth.current_password_invalid"
25
+ | "auth.password_unchanged"
25
26
  | "auth.password_too_short"
26
27
  | "auth.password_too_long";
27
28
 
@@ -43,6 +44,8 @@ export async function changePassword(ctx: AuthContext, input: ChangePasswordInpu
43
44
  const [stored] = await ctx.db.select({ passwordHash: users.passwordHash }).from(users).where(eq(users.id, user.id)).limit(1);
44
45
  if (stored === undefined) return err("auth.unauthenticated");
45
46
  if (!(await verifyPassword(input.currentPassword, stored.passwordHash))) return err("auth.current_password_invalid");
47
+ // Compared in NFC, as the hash is: another Unicode form of the same password is the same password.
48
+ if (input.newPassword.normalize("NFC") === input.currentPassword.normalize("NFC")) return err("auth.password_unchanged");
46
49
 
47
50
  const passwordHash = await hashPassword(input.newPassword, options.password.scrypt);
48
51
  return ctx.db.transaction(async (tx): Promise<ChangePasswordResult> => {
@@ -3,7 +3,7 @@
3
3
  export { changePassword, type ChangePasswordErrorCode, type ChangePasswordInput, type ChangePasswordResult } from "./change-password.js";
4
4
  export { loginUser, type LoginInput, type LoginResult } from "./login.js";
5
5
  export { getAuthOptions, getAuthRoutes, type AuthRoutes } from "./options.js";
6
- export { hashPassword, MAX_PASSWORD_LENGTH, needsRehash, verifyPassword } from "./password.js";
6
+ export { hashPassword, matchPassword, MAX_PASSWORD_LENGTH, needsRehash, verifyPassword, type PasswordMatch } from "./password.js";
7
7
  export {
8
8
  deliverPasswordReset,
9
9
  findPasswordResetUser,
@@ -34,5 +34,13 @@ export {
34
34
  export { authPrivacyContributor, deleteAuthUserData, exportAuthUserData, type AuthUserData } from "./privacy.js";
35
35
  export { isCurrentPassword } from "./reauthenticate.js";
36
36
  export { registerUser, type RegisterErrorCode, type RegisterInput, type RegisterResult } from "./register.js";
37
- export { createSession, findSessionUser, logoutSession, pruneSessions, type AuthContext } from "./sessions.js";
37
+ export {
38
+ createSession,
39
+ findSessionUser,
40
+ logoutSession,
41
+ pruneSessions,
42
+ revokeUserSessions,
43
+ type AuthContext,
44
+ type RevokeUserSessionsOptions,
45
+ } from "./sessions.js";
38
46
  export { isRegistrationClosed } from "./switches.js";
@@ -8,7 +8,7 @@ import { and, eq } from "drizzle-orm";
8
8
  import type { SignedIn } from "../contract.js";
9
9
  import { users } from "../schema.js";
10
10
  import { getAuthOptions } from "./options.js";
11
- import { hashPassword, MAX_PASSWORD_LENGTH, needsRehash, verifyDummyPassword, verifyPassword } from "./password.js";
11
+ import { hashPassword, matchPassword, MAX_PASSWORD_LENGTH, needsRehash, verifyDummyPassword } from "./password.js";
12
12
  import { assertAuthBuckets, BUCKETS, emailSubjectKey } from "./rate-limits.js";
13
13
  import { createSession, deleteExpiredSessions, type AuthContext } from "./sessions.js";
14
14
  import { getPasswordLength, normalizeEmail } from "./validation.js";
@@ -42,13 +42,13 @@ export async function loginUser(ctx: AuthContext, input: LoginInput): Promise<Lo
42
42
  await verifyDummyPassword(input.password, options.password.scrypt);
43
43
  return err("auth.invalid_credentials");
44
44
  }
45
- if (!(await verifyPassword(input.password, user.passwordHash))) {
46
- return err("auth.invalid_credentials");
47
- }
45
+ const match = await matchPassword(input.password, user.passwordHash);
46
+ if (match === "mismatch") return err("auth.invalid_credentials");
48
47
 
49
48
  await resetRateLimit(ctx, { bucket: BUCKETS.loginAccount, key: accountKey });
50
49
  await deleteExpiredSessions(ctx, user.id);
51
- if (needsRehash(user.passwordHash, options.password.scrypt)) {
50
+ // A legacy match (raw, non-NFC input) is rehashed too, so the stored hash is of the NFC form.
51
+ if (match === "legacy" || needsRehash(user.passwordHash, options.password.scrypt)) {
52
52
  const passwordHash = await hashPassword(input.password, options.password.scrypt);
53
53
  // Conditional: a password changed meanwhile is not overwritten with the old one.
54
54
  await ctx.db
@@ -18,6 +18,21 @@ export function getAuthOptions(config: SoftureConfig): AuthOptions {
18
18
  return getAuthModule(config).options as AuthOptions;
19
19
  }
20
20
 
21
+ const anchoredPatterns = new WeakMap<RegExp, RegExp>();
22
+
23
+ /** `legacySession.tokenPattern` anchored to the whole token, or undefined without a legacy session. */
24
+ export function getLegacyTokenPattern(config: SoftureConfig): RegExp | undefined {
25
+ const pattern = getAuthOptions(config).legacySession?.tokenPattern;
26
+ if (pattern === undefined) return undefined;
27
+ let anchored = anchoredPatterns.get(pattern);
28
+ if (anchored === undefined) {
29
+ // The schema refused the g and y flags, so `test` keeps no state between calls.
30
+ anchored = new RegExp(`^(?:${pattern.source})$`, pattern.flags);
31
+ anchoredPatterns.set(pattern, anchored);
32
+ }
33
+ return anchored;
34
+ }
35
+
21
36
  /** The module's routes with the app's overrides applied. */
22
37
  export function getAuthRoutes(config: SoftureConfig): AuthRoutes {
23
38
  const routes = getAuthModule(config).routes;
@@ -18,18 +18,34 @@ interface ParsedHash {
18
18
  /** A new salted hash of `password`. */
19
19
  export async function hashPassword(password: string, params: ScryptParams): Promise<string> {
20
20
  const salt = randomBytes(SALT_BYTES);
21
- const key = await deriveKey(password, salt, params);
21
+ const key = await deriveKey(password.normalize("NFC"), salt, params);
22
22
  return ["scrypt", params.cost, params.blockSize, params.parallelization, salt.toString("base64url"), key.toString("base64url")].join("$");
23
23
  }
24
24
 
25
25
  /**
26
- * Whether `password` matches `storedHash`. Throws on a hash this module did not write: that is
27
- * damaged data, not a wrong password.
26
+ * How `password` matched `storedHash`: `match`, `mismatch`, or `legacy` when only the raw input
27
+ * matched. This module hashes the NFC form; a system it took over may have hashed what the browser
28
+ * sent, so a password typed in another Unicode form (NFD from some keyboards) is tried as given
29
+ * when the NFC form fails. A `legacy` match is rehashed at login. Throws on a hash this module did
30
+ * not write: that is damaged data, not a wrong password.
28
31
  */
29
- export async function verifyPassword(password: string, storedHash: string): Promise<boolean> {
32
+ export async function matchPassword(password: string, storedHash: string): Promise<PasswordMatch> {
30
33
  const parsed = parseHash(storedHash);
31
- const key = await deriveKey(password, parsed.salt, parsed.params);
32
- return key.length === parsed.key.length && timingSafeEqual(key, parsed.key);
34
+ const normalized = password.normalize("NFC");
35
+ if (isSameKey(await deriveKey(normalized, parsed.salt, parsed.params), parsed.key)) return "match";
36
+ if (normalized === password) return "mismatch";
37
+ return isSameKey(await deriveKey(password, parsed.salt, parsed.params), parsed.key) ? "legacy" : "mismatch";
38
+ }
39
+
40
+ export type PasswordMatch = "match" | "legacy" | "mismatch";
41
+
42
+ /** Whether `password` matches `storedHash` (`matchPassword` as a yes or no). */
43
+ export async function verifyPassword(password: string, storedHash: string): Promise<boolean> {
44
+ return (await matchPassword(password, storedHash)) !== "mismatch";
45
+ }
46
+
47
+ function isSameKey(key: Buffer, stored: Buffer): boolean {
48
+ return key.length === stored.length && timingSafeEqual(key, stored);
33
49
  }
34
50
 
35
51
  /** Whether `storedHash` was made with other parameters than `params`. */
@@ -42,7 +58,8 @@ const dummyHashes = new Map<string, Promise<string>>();
42
58
 
43
59
  /**
44
60
  * Spends the time of one verification without an account, so a login for an unknown email takes
45
- * as long as one with a wrong password. The dummy hash is made once per parameter set.
61
+ * as long as one with a wrong password (the NFC retry included: it goes through `verifyPassword`).
62
+ * The dummy hash is made once per parameter set.
46
63
  */
47
64
  export async function verifyDummyPassword(password: string, params: ScryptParams): Promise<void> {
48
65
  const cacheKey = `${String(params.cost)}:${String(params.blockSize)}:${String(params.parallelization)}`;
@@ -55,6 +72,7 @@ export async function verifyDummyPassword(password: string, params: ScryptParams
55
72
  await verifyPassword(password, await dummy);
56
73
  }
57
74
 
75
+ /** The key of `password` exactly as given; callers normalise. */
58
76
  function deriveKey(password: string, salt: Buffer, params: ScryptParams): Promise<Buffer> {
59
77
  const options: ScryptOptions = {
60
78
  N: params.cost,
@@ -64,7 +82,7 @@ function deriveKey(password: string, salt: Buffer, params: ScryptParams): Promis
64
82
  maxmem: 256 * params.cost * params.blockSize,
65
83
  };
66
84
  return new Promise((resolve, reject) => {
67
- scrypt(password.normalize("NFC"), salt, KEY_BYTES, options, (error, key) => {
85
+ scrypt(password, salt, KEY_BYTES, options, (error, key) => {
68
86
  if (error === null) resolve(key);
69
87
  else reject(error);
70
88
  });
@@ -2,6 +2,7 @@
2
2
  // work it guards, hashing included, so a flood is stopped before it costs anything.
3
3
  import { getModule, type SoftureConfig } from "@softure-ai/core";
4
4
  import { subjectKey } from "@softure-ai/security/server";
5
+ import { getAuthOptions } from "./options.js";
5
6
 
6
7
  export const BUCKETS = {
7
8
  register: "register",
@@ -23,18 +24,24 @@ export function userSubjectKey(userId: string): string {
23
24
  return subjectKey(`user:${userId}`);
24
25
  }
25
26
 
27
+ /** The buckets only password reset counts in; not needed while it is off. */
28
+ const RESET_BUCKETS: ReadonlySet<string> = new Set([BUCKETS.passwordReset, BUCKETS.passwordResetAccount, BUCKETS.passwordResetConfirm]);
29
+
26
30
  const checkedConfigs = new WeakSet<SoftureConfig>();
27
31
 
28
32
  /**
29
33
  * Throws, naming every missing bucket, when the app's `security({ buckets })` lacks one auth
30
- * counts in. Checked once per config, before the first attempt is counted, so a setup mistake is
31
- * one clear error instead of a generic failure on every login.
34
+ * counts in: the reset buckets only when password reset is on (`passwordReset.send`). Checked once
35
+ * per config, before the first attempt is counted, so a setup mistake is one clear error instead of
36
+ * a generic failure on every login.
32
37
  */
33
38
  export function assertAuthBuckets(config: SoftureConfig): void {
34
39
  if (checkedConfigs.has(config)) return;
35
40
  const options = getModule(config, "security")?.options as { buckets?: Readonly<Record<string, unknown>> } | undefined;
36
41
  const configured = options?.buckets ?? {};
37
- const missing = Object.values(BUCKETS).filter((name) => !Object.hasOwn(configured, name));
42
+ const isResetOn = getAuthOptions(config).passwordReset.send !== undefined;
43
+ const required = Object.values(BUCKETS).filter((name) => isResetOn || !RESET_BUCKETS.has(name));
44
+ const missing = required.filter((name) => !Object.hasOwn(configured, name));
38
45
  if (missing.length > 0) {
39
46
  throw new Error(
40
47
  `@softure-ai/auth: security({ buckets }) lacks ${missing.map((name) => `"${name}"`).join(", ")}; spread AUTH_RATE_LIMIT_BUCKETS into it`,