@softure-ai/auth 0.1.5 → 0.1.8

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 (135) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +172 -24
  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 +9 -2
  20. package/dist/next/actions.d.ts.map +1 -1
  21. package/dist/next/actions.js +51 -18
  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 +2 -2
  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/logout-button.d.ts +3 -1
  30. package/dist/next/logout-button.d.ts.map +1 -1
  31. package/dist/next/logout-button.js +4 -4
  32. package/dist/next/logout-button.js.map +1 -1
  33. package/dist/next/pages.d.ts +13 -0
  34. package/dist/next/pages.d.ts.map +1 -1
  35. package/dist/next/pages.js +28 -2
  36. package/dist/next/pages.js.map +1 -1
  37. package/dist/next/session-cookie.d.ts +3 -0
  38. package/dist/next/session-cookie.d.ts.map +1 -1
  39. package/dist/next/session-cookie.js +39 -2
  40. package/dist/next/session-cookie.js.map +1 -1
  41. package/dist/options.d.ts +10 -1
  42. package/dist/options.d.ts.map +1 -1
  43. package/dist/options.js +44 -3
  44. package/dist/options.js.map +1 -1
  45. package/dist/proxy/index.d.ts +11 -0
  46. package/dist/proxy/index.d.ts.map +1 -1
  47. package/dist/proxy/index.js +60 -9
  48. package/dist/proxy/index.js.map +1 -1
  49. package/dist/safe-next-path.d.ts +3 -1
  50. package/dist/safe-next-path.d.ts.map +1 -1
  51. package/dist/safe-next-path.js +9 -3
  52. package/dist/safe-next-path.js.map +1 -1
  53. package/dist/scripts/index.d.ts +1 -0
  54. package/dist/scripts/index.d.ts.map +1 -1
  55. package/dist/scripts/index.js +3 -1
  56. package/dist/scripts/index.js.map +1 -1
  57. package/dist/scripts/temporary-password.d.ts +12 -0
  58. package/dist/scripts/temporary-password.d.ts.map +1 -0
  59. package/dist/scripts/temporary-password.js +47 -0
  60. package/dist/scripts/temporary-password.js.map +1 -0
  61. package/dist/server/change-password.d.ts +1 -1
  62. package/dist/server/change-password.d.ts.map +1 -1
  63. package/dist/server/change-password.js +4 -1
  64. package/dist/server/change-password.js.map +1 -1
  65. package/dist/server/index.d.ts +2 -2
  66. package/dist/server/index.d.ts.map +1 -1
  67. package/dist/server/index.js +2 -2
  68. package/dist/server/index.js.map +1 -1
  69. package/dist/server/login.js +5 -4
  70. package/dist/server/login.js.map +1 -1
  71. package/dist/server/options.d.ts +2 -0
  72. package/dist/server/options.d.ts.map +1 -1
  73. package/dist/server/options.js +14 -0
  74. package/dist/server/options.js.map +1 -1
  75. package/dist/server/password.d.ts +10 -3
  76. package/dist/server/password.d.ts.map +1 -1
  77. package/dist/server/password.js +24 -8
  78. package/dist/server/password.js.map +1 -1
  79. package/dist/server/rate-limits.d.ts +3 -2
  80. package/dist/server/rate-limits.d.ts.map +1 -1
  81. package/dist/server/rate-limits.js +9 -3
  82. package/dist/server/rate-limits.js.map +1 -1
  83. package/dist/server/register.d.ts +2 -0
  84. package/dist/server/register.d.ts.map +1 -1
  85. package/dist/server/register.js +13 -1
  86. package/dist/server/register.js.map +1 -1
  87. package/dist/server/session-token.d.ts +6 -2
  88. package/dist/server/session-token.d.ts.map +1 -1
  89. package/dist/server/session-token.js +7 -3
  90. package/dist/server/session-token.js.map +1 -1
  91. package/dist/server/sessions.d.ts +9 -0
  92. package/dist/server/sessions.d.ts.map +1 -1
  93. package/dist/server/sessions.js +13 -4
  94. package/dist/server/sessions.js.map +1 -1
  95. package/dist/testing/account.d.ts +17 -0
  96. package/dist/testing/account.d.ts.map +1 -0
  97. package/dist/testing/account.js +31 -0
  98. package/dist/testing/account.js.map +1 -0
  99. package/dist/testing/index.d.ts +2 -0
  100. package/dist/testing/index.d.ts.map +1 -0
  101. package/dist/testing/index.js +4 -0
  102. package/dist/testing/index.js.map +1 -0
  103. package/dist/ui/auth-forms.d.ts +14 -7
  104. package/dist/ui/auth-forms.d.ts.map +1 -1
  105. package/dist/ui/auth-forms.js +14 -12
  106. package/dist/ui/auth-forms.js.map +1 -1
  107. package/module.json +2 -2
  108. package/package.json +15 -3
  109. package/src/contract.ts +3 -0
  110. package/src/index.ts +2 -2
  111. package/src/messages/en.ts +1 -0
  112. package/src/messages/pl.ts +1 -0
  113. package/src/next/actions.ts +58 -16
  114. package/src/next/context.ts +2 -2
  115. package/src/next/index.ts +11 -1
  116. package/src/next/logout-button.tsx +5 -2
  117. package/src/next/pages.tsx +44 -0
  118. package/src/next/session-cookie.ts +42 -2
  119. package/src/options.ts +49 -3
  120. package/src/proxy/index.ts +78 -10
  121. package/src/safe-next-path.ts +9 -3
  122. package/src/scripts/index.ts +7 -1
  123. package/src/scripts/temporary-password.ts +62 -0
  124. package/src/server/change-password.ts +4 -1
  125. package/src/server/index.ts +10 -2
  126. package/src/server/login.ts +5 -5
  127. package/src/server/options.ts +15 -0
  128. package/src/server/password.ts +26 -8
  129. package/src/server/rate-limits.ts +10 -3
  130. package/src/server/register.ts +16 -1
  131. package/src/server/session-token.ts +7 -3
  132. package/src/server/sessions.ts +19 -4
  133. package/src/testing/account.ts +43 -0
  134. package/src/testing/index.ts +3 -0
  135. package/src/ui/auth-forms.tsx +26 -7
@@ -5,46 +5,109 @@
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[];
22
+ /**
23
+ * Origins besides `appOrigin` that the login redirect may stay on (`https://example.com`), for an app
24
+ * served on several hosts. The request's public origin (`X-Forwarded-Proto` / `X-Forwarded-Host`,
25
+ * else `Host` and the URL's scheme) is used only when it is listed; any other goes to `appOrigin`.
26
+ */
27
+ readonly trustedOrigins?: readonly string[];
16
28
  }
17
29
 
30
+ /** Mounted at a fixed path by the module (manifest `mount`); it answers `{ user: null }` without a session. */
31
+ const SESSION_ROUTE = "/api/auth/session";
32
+
18
33
  export type AuthGuard = (request: Request) => Response | null;
19
34
 
20
35
  /** A guard that redirects to the login page (with `?next=`) for protected paths without a session cookie. */
21
36
  export function createAuthGuard(config: SoftureConfig, options: AuthGuardOptions): AuthGuard {
22
37
  const routes = getAuthRoutes(config);
23
- const cookieName = getSessionCookie(config).name;
24
- const prefixes = [...options.protect, routes.changePassword].map(normalizePrefix);
38
+ const cookieNames = [getSessionCookie(config).name, getAuthOptions(config).legacySession?.cookieName].filter((name) => name !== undefined);
39
+ const prefixes = options.protect.map((prefix) => normalizePrefix(prefix, "protected"));
40
+ const changePassword = normalizePrefix(routes.changePassword, "protected");
41
+ // Auth's own public pages: guarding them would send a visitor from the login page to itself.
42
+ const publicPaths = [routes.login, routes.register, routes.forgotPassword, routes.resetPassword, SESSION_ROUTE].map((path) =>
43
+ normalizePrefix(path, "excluded"),
44
+ );
45
+ const excluded = (options.exclude ?? []).map((prefix) => normalizePrefix(prefix, "excluded"));
46
+ const trustedOrigins = new Set((options.trustedOrigins ?? []).map(normalizeOrigin));
47
+
48
+ const isGuarded = (path: string): boolean => {
49
+ if (isUnder(path, changePassword)) return true;
50
+ if ([...publicPaths, ...excluded].some((prefix) => isExcludedBy(path, prefix))) return false;
51
+ return prefixes.some((prefix) => isUnder(path, prefix));
52
+ };
25
53
 
26
54
  return (request) => {
27
55
  const url = new URL(request.url);
28
56
  // Compared decoded and lowercased, so `/%61ccount` or `/ACCOUNT` (which a case-insensitive
29
57
  // front proxy may route to /account) is guarded too. Undecodable paths are guarded.
30
58
  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;
33
- // Built on appOrigin: behind a proxy the request URL may carry an internal host.
34
- const login = new URL(routes.login, config.appOrigin);
59
+ if (path !== null && !isGuarded(path)) return null;
60
+ const cookieHeader = request.headers.get("cookie");
61
+ if (cookieNames.some((name) => readSessionToken(cookieHeader, name) !== null)) return null;
62
+ // Built on appOrigin, or on the request's public origin when the app trusts it: behind a proxy
63
+ // the request URL carries an internal host, and request headers alone are never trusted.
64
+ const origin = findPublicOrigin(request, url);
65
+ const login = new URL(routes.login, origin !== null && trustedOrigins.has(origin) ? origin : config.appOrigin);
35
66
  login.searchParams.set("next", `${url.pathname}${url.search}`);
36
67
  return Response.redirect(login, 307);
37
68
  };
38
69
  }
39
70
 
40
- function normalizePrefix(prefix: string): string {
71
+ function normalizePrefix(prefix: string, kind: "protected" | "excluded"): string {
41
72
  if (!prefix.startsWith("/")) {
42
- throw new Error(`createAuthGuard: protected path "${prefix}" must start with /`);
73
+ throw new Error(`createAuthGuard: ${kind} path "${prefix}" must start with /`);
43
74
  }
44
75
  const trimmed = prefix.length > 1 && prefix.endsWith("/") ? prefix.slice(0, -1) : prefix;
45
76
  return trimmed.toLowerCase();
46
77
  }
47
78
 
79
+ /** `entry` as an origin (`https://example.com`, a trailing `/` dropped); anything else is a config error. */
80
+ function normalizeOrigin(entry: string): string {
81
+ const parsed = parseOrigin(entry.endsWith("/") ? entry.slice(0, -1) : entry);
82
+ if (parsed === null) {
83
+ throw new Error(`createAuthGuard: trusted origin "${entry}" must be an http(s) origin such as https://example.com`);
84
+ }
85
+ return parsed;
86
+ }
87
+
88
+ /** The origin the browser used: the front proxy's forwarded scheme and host, else `Host` and the URL's scheme. */
89
+ function findPublicOrigin(request: Request, url: URL): string | null {
90
+ const host = firstValue(request.headers.get("x-forwarded-host")) ?? firstValue(request.headers.get("host")) ?? url.host;
91
+ const scheme = firstValue(request.headers.get("x-forwarded-proto")) ?? url.protocol.slice(0, -1);
92
+ return parseOrigin(`${scheme}://${host}`);
93
+ }
94
+
95
+ function firstValue(header: string | null): string | null {
96
+ const value = header?.split(",")[0]?.trim();
97
+ return value === undefined || value === "" ? null : value;
98
+ }
99
+
100
+ /** The normalized origin of `candidate` when it is exactly `http(s)://host[:port]`, else null. */
101
+ function parseOrigin(candidate: string): string | null {
102
+ // Checked on the raw text, so a path, query, fragment or credentials make it no origin.
103
+ if (!/^https?:\/\/[^/\\?#@\s]+$/i.test(candidate)) return null;
104
+ try {
105
+ return new URL(candidate).origin;
106
+ } catch {
107
+ return null;
108
+ }
109
+ }
110
+
48
111
  function decodePath(pathname: string): string | null {
49
112
  try {
50
113
  return decodeURIComponent(pathname).toLowerCase();
@@ -53,6 +116,11 @@ function decodePath(pathname: string): string | null {
53
116
  }
54
117
  }
55
118
 
119
+ /** An exclusion of "/" is the home page: excluding every path would switch the guard off. */
120
+ function isExcludedBy(pathname: string, prefix: string): boolean {
121
+ return prefix === "/" ? pathname === "/" : isUnder(pathname, prefix);
122
+ }
123
+
56
124
  function isUnder(pathname: string, prefix: string): boolean {
57
125
  return prefix === "/" || pathname === prefix || pathname.startsWith(`${prefix}/`);
58
126
  }
@@ -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`,
@@ -19,8 +19,13 @@ export interface RegisterInput {
19
19
  readonly hasConsented: boolean;
20
20
  /** The client's rate limit key (`identifyClient`). */
21
21
  readonly clientKey: string;
22
+ /** Values of the app's `registrationFields`; other names are dropped. */
23
+ readonly fields?: Readonly<Record<string, string>>;
22
24
  }
23
25
 
26
+ /** Longest registration field value handed to the hook; longer ones are cut. */
27
+ const MAX_FIELD_LENGTH = 512;
28
+
24
29
  export type RegisterErrorCode =
25
30
  | "auth.registration_closed"
26
31
  | "auth.email_invalid"
@@ -65,8 +70,18 @@ export async function registerUser(ctx: AuthContext, input: RegisterInput): Prom
65
70
  if (row === undefined) return err("auth.email_taken");
66
71
  const user = { id: row.id, email: row.email, createdAt: row.createdAt };
67
72
 
68
- await options.onRegistered?.({ user, consent: options.requireConsent ? { acceptedAt: now } : null }, txCtx);
73
+ const fields = pickRegistrationFields(options.registrationFields, input.fields);
74
+ await options.onRegistered?.({ user, consent: options.requireConsent ? { acceptedAt: now } : null, fields }, txCtx);
69
75
  const session = await createSession(txCtx, user.id);
70
76
  return ok({ user, session });
71
77
  });
72
78
  }
79
+
80
+ function pickRegistrationFields(declared: readonly string[], sent: Readonly<Record<string, string>> | undefined): Record<string, string> {
81
+ const fields: Record<string, string> = {};
82
+ for (const name of declared) {
83
+ const value = sent !== undefined && Object.hasOwn(sent, name) ? sent[name] : undefined;
84
+ if (typeof value === "string" && value !== "") fields[name] = value.slice(0, MAX_FIELD_LENGTH);
85
+ }
86
+ return fields;
87
+ }
@@ -15,7 +15,11 @@ export function hashSessionToken(token: string): string {
15
15
  return createHash("sha256").update(token, "utf8").digest("hex");
16
16
  }
17
17
 
18
- /** Whether a cookie value could be a token at all; anything else is not looked up. */
19
- export function isSessionTokenShape(token: string): boolean {
20
- return TOKEN_SHAPE.test(token);
18
+ /**
19
+ * Whether a cookie value could be a token at all; anything else is not looked up. `legacyPattern`
20
+ * (from `legacySession.tokenPattern`, anchored and without the g or y flag) admits an adopted
21
+ * system's tokens, stored as the same sha256 hex.
22
+ */
23
+ export function isSessionTokenShape(token: string, legacyPattern?: RegExp): boolean {
24
+ return TOKEN_SHAPE.test(token) || (legacyPattern?.test(token) ?? false);
21
25
  }
@@ -1,10 +1,10 @@
1
1
  // Database sessions: one row per login, keyed by the sha256 of the cookie token, with a fixed expiry.
2
2
  import type { ModuleContext } from "@softure-ai/core";
3
3
  import type { Queryable } from "@softure-ai/db";
4
- import { and, eq, gt, lte } from "drizzle-orm";
4
+ import { and, eq, gt, lte, ne } from "drizzle-orm";
5
5
  import type { AuthUser, NewSession } from "../contract.js";
6
6
  import { sessions, users } from "../schema.js";
7
- import { getAuthOptions } from "./options.js";
7
+ import { getAuthOptions, getLegacyTokenPattern } from "./options.js";
8
8
  import { createSessionToken, hashSessionToken, isSessionTokenShape } from "./session-token.js";
9
9
 
10
10
  export type AuthContext = ModuleContext<Queryable>;
@@ -22,7 +22,7 @@ export async function createSession(ctx: AuthContext, userId: string): Promise<N
22
22
 
23
23
  /** The user of a live session, or null for an unknown, malformed or expired token. */
24
24
  export async function findSessionUser(ctx: AuthContext, token: string): Promise<AuthUser | null> {
25
- if (!isSessionTokenShape(token)) return null;
25
+ if (!isSessionTokenShape(token, getLegacyTokenPattern(ctx.config))) return null;
26
26
  const [row] = await ctx.db
27
27
  .select({ id: users.id, email: users.email, createdAt: users.createdAt })
28
28
  .from(sessions)
@@ -34,7 +34,7 @@ export async function findSessionUser(ctx: AuthContext, token: string): Promise<
34
34
 
35
35
  /** Ends one session. An unknown token is already logged out, so it is not an error. */
36
36
  export async function logoutSession(ctx: AuthContext, token: string): Promise<void> {
37
- if (!isSessionTokenShape(token)) return;
37
+ if (!isSessionTokenShape(token, getLegacyTokenPattern(ctx.config))) return;
38
38
  await ctx.db.delete(sessions).where(eq(sessions.tokenHash, hashSessionToken(token)));
39
39
  }
40
40
 
@@ -48,3 +48,18 @@ export async function pruneSessions(ctx: AuthContext): Promise<number> {
48
48
  export async function deleteExpiredSessions(ctx: AuthContext, userId: string): Promise<void> {
49
49
  await ctx.db.delete(sessions).where(and(eq(sessions.userId, userId), lte(sessions.expiresAt, ctx.clock.now())));
50
50
  }
51
+
52
+ export interface RevokeUserSessionsOptions {
53
+ /** A session token to keep, e.g. the one of the admin acting on their own account. */
54
+ readonly except?: string;
55
+ }
56
+
57
+ /**
58
+ * Ends every session of `userId` (all but `except`), e.g. after an account recovery or a suspected
59
+ * leak; each device must log in again. Returns how many sessions were ended.
60
+ */
61
+ export async function revokeUserSessions(ctx: AuthContext, userId: string, options: RevokeUserSessionsOptions = {}): Promise<number> {
62
+ const kept = options.except === undefined ? undefined : ne(sessions.tokenHash, hashSessionToken(options.except));
63
+ const deleted = await ctx.db.delete(sessions).where(and(eq(sessions.userId, userId), kept)).returning();
64
+ return deleted.length;
65
+ }
@@ -0,0 +1,43 @@
1
+ // An account written straight to auth's tables, hashed the way registration hashes it. No
2
+ // `onRegistered` hook runs and no session is opened: the test signs in through the login form.
3
+ import type { Queryable } from "@softure-ai/db";
4
+ import type { AuthUser } from "../contract.js";
5
+ import { DEFAULT_SCRYPT_COST, type ScryptParams } from "../options.js";
6
+ import { userRoles, users } from "../schema.js";
7
+ import { hashPassword } from "../server/password.js";
8
+ import { parseEmail } from "../server/validation.js";
9
+
10
+ /** Auth's own hash parameters when the app sets none (`password.scrypt` in `auth({ ... })`). */
11
+ const DEFAULT_SCRYPT: ScryptParams = { cost: DEFAULT_SCRYPT_COST, blockSize: 8, parallelization: 1 };
12
+
13
+ export interface TestAccountInput {
14
+ readonly email: string;
15
+ readonly password: string;
16
+ /** Rows of `auth.user_roles`, e.g. `["admin"]`. */
17
+ readonly roles?: readonly string[];
18
+ /** The app's hash parameters (`getAuthOptions(config).password.scrypt`), so its login does not rehash. */
19
+ readonly scrypt?: ScryptParams;
20
+ }
21
+
22
+ /**
23
+ * Creates an account and its roles in one transaction and returns it. The email is normalized as
24
+ * registration normalizes it. An invalid or taken email throws: in test setup it is a bug of the test.
25
+ */
26
+ export async function createTestAccount(db: Queryable, input: TestAccountInput): Promise<AuthUser> {
27
+ const email = parseEmail(input.email);
28
+ if (!email.ok) throw new Error(`createTestAccount: "${input.email}" is not a valid email`);
29
+ const passwordHash = await hashPassword(input.password, input.scrypt ?? DEFAULT_SCRYPT);
30
+ const now = new Date();
31
+
32
+ return db.transaction(async (tx) => {
33
+ const [row] = await tx
34
+ .insert(users)
35
+ .values({ email: email.value, passwordHash, createdAt: now, passwordChangedAt: now })
36
+ .onConflictDoNothing({ target: users.email })
37
+ .returning();
38
+ if (row === undefined) throw new Error(`createTestAccount: an account with the email "${email.value}" already exists`);
39
+ const roles = input.roles ?? [];
40
+ if (roles.length > 0) await tx.insert(userRoles).values(roles.map((role) => ({ userId: row.id, role, grantedAt: now })));
41
+ return { id: row.id, email: row.email, createdAt: row.createdAt };
42
+ });
43
+ }
@@ -0,0 +1,3 @@
1
+ // Test helpers of @softure-ai/auth: accounts created directly in the database, for tests that need
2
+ // a user but are not about registration. Server-only; never imported by the module's runtime code.
3
+ export { createTestAccount, type TestAccountInput } from "./account.js";