@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,164 @@
1
+ // Password reset by token. A request counts its buckets and answers the same for every email;
2
+ // `deliverPasswordReset` then issues the token and calls the app's sender (the Next adapter runs it
3
+ // after the response, so neither its timing nor its failures reveal an account). A reset link
4
+ // carries 32 random bytes; only their sha256 is stored, one pending link per account, and the reset
5
+ // deletes the row in the transaction that sets the new password and ends every session.
6
+ import { err, ok, type Err, type Ok, type SoftureConfig } from "@softure-ai/core";
7
+ import type { RateLimitRejection } from "@softure-ai/security";
8
+ import { consumeRateLimit } from "@softure-ai/security/server";
9
+ import { and, eq, gt, lte } from "drizzle-orm";
10
+ import type { AuthUser } from "../contract.js";
11
+ import { passwordResets, sessions, users } from "../schema.js";
12
+ import { getAuthOptions, getAuthRoutes } from "./options.js";
13
+ import { hashPassword } from "./password.js";
14
+ import { assertAuthBuckets, BUCKETS, emailSubjectKey } from "./rate-limits.js";
15
+ import type { AuthContext } from "./sessions.js";
16
+ // Reset tokens have the shape of session tokens: the same generator, hash and shape check.
17
+ import { createSessionToken, hashSessionToken, isSessionTokenShape } from "./session-token.js";
18
+ import { checkNewPassword, parseEmail } from "./validation.js";
19
+
20
+ const MINUTE_MS = 60 * 1000;
21
+ /** The query parameter of the reset link that carries the token. */
22
+ export const RESET_TOKEN_PARAM = "token";
23
+
24
+ /** Whether the app passed a sender, i.e. whether password reset is offered at all. */
25
+ export function isPasswordResetEnabled(config: SoftureConfig): boolean {
26
+ return getAuthOptions(config).passwordReset.send !== undefined;
27
+ }
28
+
29
+ export interface PasswordResetRequestInput {
30
+ readonly email: string;
31
+ /** The client's rate limit key (`identifyClient`). */
32
+ readonly clientKey: string;
33
+ }
34
+
35
+ export type PasswordResetRequestResult =
36
+ | Ok<{ readonly email: string }>
37
+ | Err<"auth.password_reset_unavailable" | "auth.email_invalid">
38
+ | RateLimitRejection;
39
+
40
+ /**
41
+ * Accepts a reset request: counts `password-reset` per client, checks the email's shape and counts
42
+ * `password-reset-account` per email. It never looks the account up, so its answer is the same for
43
+ * every email; pass the returned email to `deliverPasswordReset`. Database errors propagate.
44
+ */
45
+ export async function requestPasswordReset(ctx: AuthContext, input: PasswordResetRequestInput): Promise<PasswordResetRequestResult> {
46
+ assertAuthBuckets(ctx.config);
47
+ if (!isPasswordResetEnabled(ctx.config)) return err("auth.password_reset_unavailable");
48
+ const byClient = await consumeRateLimit(ctx, { bucket: BUCKETS.passwordReset, key: input.clientKey });
49
+ if (!byClient.ok) return byClient;
50
+
51
+ const email = parseEmail(input.email);
52
+ if (!email.ok) return email;
53
+ const byAccount = await consumeRateLimit(ctx, { bucket: BUCKETS.passwordResetAccount, key: emailSubjectKey(email.value) });
54
+ if (!byAccount.ok) return byAccount;
55
+ return ok({ email: email.value });
56
+ }
57
+
58
+ /**
59
+ * Issues a reset link for the account with `email` (replacing a pending one) and hands it to the
60
+ * app's sender. `no_account` when no account has that email. Sender and database errors propagate.
61
+ */
62
+ export async function deliverPasswordReset(ctx: AuthContext, email: string): Promise<"sent" | "no_account"> {
63
+ const send = getAuthOptions(ctx.config).passwordReset.send;
64
+ if (send === undefined) {
65
+ throw new Error("@softure-ai/auth: deliverPasswordReset needs auth({ passwordReset: { send } })");
66
+ }
67
+ const [user] = await ctx.db
68
+ .select({ id: users.id, email: users.email, createdAt: users.createdAt })
69
+ .from(users)
70
+ .where(eq(users.email, email))
71
+ .limit(1);
72
+ if (user === undefined) return "no_account";
73
+
74
+ const { token, expiresAt } = await issuePasswordReset(ctx, user.id);
75
+ await send(getPasswordResetLink(ctx.config, token), user, { expiresAt, locale: ctx.config.locale });
76
+ return "sent";
77
+ }
78
+
79
+ /** Stores a new reset token for `userId`, replacing a pending one, and returns the token. */
80
+ export async function issuePasswordReset(ctx: AuthContext, userId: string): Promise<{ readonly token: string; readonly expiresAt: Date }> {
81
+ const now = ctx.clock.now();
82
+ const expiresAt = new Date(now.getTime() + getAuthOptions(ctx.config).passwordReset.ttlMinutes * MINUTE_MS);
83
+ const { token, tokenHash } = createSessionToken();
84
+ await ctx.db
85
+ .insert(passwordResets)
86
+ .values({ userId, tokenHash, createdAt: now, expiresAt })
87
+ .onConflictDoUpdate({ target: passwordResets.userId, set: { tokenHash, createdAt: now, expiresAt } });
88
+ return { token, expiresAt };
89
+ }
90
+
91
+ /** The link the sender delivers: the reset route on `appOrigin`, with the token in the query. */
92
+ export function getPasswordResetLink(config: SoftureConfig, token: string): string {
93
+ const link = new URL(getAuthRoutes(config).resetPassword, config.appOrigin);
94
+ link.searchParams.set(RESET_TOKEN_PARAM, token);
95
+ return link.href;
96
+ }
97
+
98
+ /** The account a live reset token belongs to, or null for an unknown, malformed, used or expired one. Reads only. */
99
+ export async function findPasswordResetUser(ctx: AuthContext, token: string): Promise<AuthUser | null> {
100
+ if (!isSessionTokenShape(token)) return null;
101
+ const [row] = await ctx.db
102
+ .select({ id: users.id, email: users.email, createdAt: users.createdAt })
103
+ .from(passwordResets)
104
+ .innerJoin(users, eq(users.id, passwordResets.userId))
105
+ .where(and(eq(passwordResets.tokenHash, hashSessionToken(token)), gt(passwordResets.expiresAt, ctx.clock.now())))
106
+ .limit(1);
107
+ return row ?? null;
108
+ }
109
+
110
+ export interface ResetPasswordInput {
111
+ readonly token: string;
112
+ readonly newPassword: string;
113
+ /** The client's rate limit key (`identifyClient`). */
114
+ readonly clientKey: string;
115
+ }
116
+
117
+ export type ResetPasswordErrorCode =
118
+ | "auth.password_reset_unavailable"
119
+ | "auth.reset_token_invalid"
120
+ | "auth.password_too_short"
121
+ | "auth.password_too_long";
122
+
123
+ export type ResetPasswordResult = Ok<undefined> | Err<ResetPasswordErrorCode> | RateLimitRejection;
124
+
125
+ /**
126
+ * Sets a new password with a reset token. Counts `password-reset-confirm` per client first. The
127
+ * token is consumed by a conditional delete in the transaction that stores the new hash and ends
128
+ * every session of the account, so it works once even when two submissions race. Database errors
129
+ * propagate.
130
+ */
131
+ export async function resetPassword(ctx: AuthContext, input: ResetPasswordInput): Promise<ResetPasswordResult> {
132
+ const options = getAuthOptions(ctx.config);
133
+ assertAuthBuckets(ctx.config);
134
+ if (!isPasswordResetEnabled(ctx.config)) return err("auth.password_reset_unavailable");
135
+ const limit = await consumeRateLimit(ctx, { bucket: BUCKETS.passwordResetConfirm, key: input.clientKey });
136
+ if (!limit.ok) return limit;
137
+
138
+ const user = await findPasswordResetUser(ctx, input.token);
139
+ if (user === null) return err("auth.reset_token_invalid");
140
+ const policy = checkNewPassword(input.newPassword, options.password.minLength);
141
+ // A fresh error, not the check's own result: CodeQL treats that result as password data
142
+ // (js/insufficient-password-hash), as in registerUser.
143
+ if (!policy.ok) return err(policy.error);
144
+
145
+ const passwordHash = await hashPassword(input.newPassword, options.password.scrypt);
146
+ const tokenHash = hashSessionToken(input.token);
147
+ return ctx.db.transaction(async (tx): Promise<ResetPasswordResult> => {
148
+ const now = ctx.clock.now();
149
+ const [consumed] = await tx
150
+ .delete(passwordResets)
151
+ .where(and(eq(passwordResets.tokenHash, tokenHash), gt(passwordResets.expiresAt, now)))
152
+ .returning();
153
+ if (consumed === undefined) return err("auth.reset_token_invalid");
154
+ await tx.update(users).set({ passwordHash, passwordChangedAt: now }).where(eq(users.id, consumed.userId));
155
+ await tx.delete(sessions).where(eq(sessions.userId, consumed.userId));
156
+ return ok();
157
+ });
158
+ }
159
+
160
+ /** Deletes every expired reset; for a scheduled job. Returns how many were deleted. */
161
+ export async function prunePasswordResets(ctx: AuthContext): Promise<number> {
162
+ const deleted = await ctx.db.delete(passwordResets).where(lte(passwordResets.expiresAt, ctx.clock.now())).returning();
163
+ return deleted.length;
164
+ }
@@ -0,0 +1,108 @@
1
+ // Password hashing with scrypt from node:crypto. A hash describes its own parameters
2
+ // (`scrypt$<N>$<r>$<p>$<salt>$<key>`, base64url), so the cost can be raised later: a login with an
3
+ // older cost rehashes (`needsRehash`). Keys are compared with `timingSafeEqual`.
4
+ import { randomBytes, scrypt, timingSafeEqual, type ScryptOptions } from "node:crypto";
5
+ import type { ScryptParams } from "../options.js";
6
+
7
+ const SALT_BYTES = 16;
8
+ const KEY_BYTES = 64;
9
+ /** Longest password accepted anywhere, so a request cannot make the server hash megabytes. */
10
+ export const MAX_PASSWORD_LENGTH = 1024;
11
+
12
+ interface ParsedHash {
13
+ readonly params: ScryptParams;
14
+ readonly salt: Buffer;
15
+ readonly key: Buffer;
16
+ }
17
+
18
+ /** A new salted hash of `password`. */
19
+ export async function hashPassword(password: string, params: ScryptParams): Promise<string> {
20
+ const salt = randomBytes(SALT_BYTES);
21
+ const key = await deriveKey(password.normalize("NFC"), salt, params);
22
+ return ["scrypt", params.cost, params.blockSize, params.parallelization, salt.toString("base64url"), key.toString("base64url")].join("$");
23
+ }
24
+
25
+ /**
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.
31
+ */
32
+ export async function matchPassword(password: string, storedHash: string): Promise<PasswordMatch> {
33
+ const parsed = parseHash(storedHash);
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);
49
+ }
50
+
51
+ /** Whether `storedHash` was made with other parameters than `params`. */
52
+ export function needsRehash(storedHash: string, params: ScryptParams): boolean {
53
+ const current = parseHash(storedHash).params;
54
+ return current.cost !== params.cost || current.blockSize !== params.blockSize || current.parallelization !== params.parallelization;
55
+ }
56
+
57
+ const dummyHashes = new Map<string, Promise<string>>();
58
+
59
+ /**
60
+ * Spends the time of one verification without an account, so a login for an unknown email takes
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.
63
+ */
64
+ export async function verifyDummyPassword(password: string, params: ScryptParams): Promise<void> {
65
+ const cacheKey = `${String(params.cost)}:${String(params.blockSize)}:${String(params.parallelization)}`;
66
+ let dummy = dummyHashes.get(cacheKey);
67
+ if (dummy === undefined) {
68
+ dummy = hashPassword(randomBytes(SALT_BYTES).toString("base64url"), params);
69
+ dummyHashes.set(cacheKey, dummy);
70
+ dummy.catch(() => dummyHashes.delete(cacheKey));
71
+ }
72
+ await verifyPassword(password, await dummy);
73
+ }
74
+
75
+ /** The key of `password` exactly as given; callers normalise. */
76
+ function deriveKey(password: string, salt: Buffer, params: ScryptParams): Promise<Buffer> {
77
+ const options: ScryptOptions = {
78
+ N: params.cost,
79
+ r: params.blockSize,
80
+ p: params.parallelization,
81
+ // Node refuses above 32 MiB by default; scrypt needs 128 * N * r bytes, so leave room for it.
82
+ maxmem: 256 * params.cost * params.blockSize,
83
+ };
84
+ return new Promise((resolve, reject) => {
85
+ scrypt(password, salt, KEY_BYTES, options, (error, key) => {
86
+ if (error === null) resolve(key);
87
+ else reject(error);
88
+ });
89
+ });
90
+ }
91
+
92
+ function parseHash(storedHash: string): ParsedHash {
93
+ const [scheme, cost, blockSize, parallelization, salt, key, ...rest] = storedHash.split("$");
94
+ const params = { cost: Number(cost), blockSize: Number(blockSize), parallelization: Number(parallelization) };
95
+ const isValid =
96
+ scheme === "scrypt" &&
97
+ rest.length === 0 &&
98
+ Object.values(params).every((value) => Number.isSafeInteger(value) && value > 0) &&
99
+ salt !== undefined &&
100
+ salt !== "" &&
101
+ key !== undefined &&
102
+ key !== "";
103
+ if (!isValid) {
104
+ // The hash itself stays out of the message: it is secret-derived data.
105
+ throw new Error("@softure-ai/auth: a stored password hash is not in the scrypt$N$r$p$salt$key format");
106
+ }
107
+ return { params, salt: Buffer.from(salt, "base64url"), key: Buffer.from(key, "base64url") };
108
+ }
@@ -0,0 +1,70 @@
1
+ // The auth part of a GDPR export and deletion (`@softure-ai/privacy`): the account, its roles, its
2
+ // sessions and a pending reset link. Secrets never leave: no password hash and no token hash.
3
+ import { ok, type ModuleContext, type Ok, type PrivacyContributor } from "@softure-ai/core";
4
+ import type { Queryable } from "@softure-ai/db";
5
+ import { asc, eq } from "drizzle-orm";
6
+ import { passwordResets, sessions, userRoles, users } from "../schema.js";
7
+
8
+ /** What auth holds about one user, as it appears in their export. */
9
+ export interface AuthUserData {
10
+ /** Null when no account has this id. */
11
+ readonly account: {
12
+ readonly id: string;
13
+ readonly email: string;
14
+ readonly createdAt: Date;
15
+ readonly passwordChangedAt: Date;
16
+ } | null;
17
+ /** Stored roles; a role held through `adminEmails` is configuration, not stored data. */
18
+ readonly roles: readonly { readonly role: string; readonly grantedAt: Date }[];
19
+ readonly sessions: readonly { readonly createdAt: Date; readonly expiresAt: Date }[];
20
+ readonly passwordReset: { readonly createdAt: Date; readonly expiresAt: Date } | null;
21
+ }
22
+
23
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
24
+
25
+ const NO_DATA: AuthUserData = { account: null, roles: [], sessions: [], passwordReset: null };
26
+
27
+ /** The user's auth data. An id that is not a UUID cannot be an account, so it has none. */
28
+ export async function exportAuthUserData(context: ModuleContext, userId: string): Promise<Ok<AuthUserData>> {
29
+ if (!UUID.test(userId)) return ok(NO_DATA);
30
+ // Core types `db` as unknown; privacy passes the @softure-ai/db handle or its transaction.
31
+ const db = context.db as Queryable;
32
+ const [account] = await db
33
+ .select({ id: users.id, email: users.email, createdAt: users.createdAt, passwordChangedAt: users.passwordChangedAt })
34
+ .from(users)
35
+ .where(eq(users.id, userId));
36
+ const roles = await db
37
+ .select({ role: userRoles.role, grantedAt: userRoles.grantedAt })
38
+ .from(userRoles)
39
+ .where(eq(userRoles.userId, userId))
40
+ .orderBy(asc(userRoles.role));
41
+ const userSessions = await db
42
+ .select({ createdAt: sessions.createdAt, expiresAt: sessions.expiresAt })
43
+ .from(sessions)
44
+ .where(eq(sessions.userId, userId))
45
+ .orderBy(asc(sessions.createdAt));
46
+ const [passwordReset] = await db
47
+ .select({ createdAt: passwordResets.createdAt, expiresAt: passwordResets.expiresAt })
48
+ .from(passwordResets)
49
+ .where(eq(passwordResets.userId, userId));
50
+ return ok({ account: account ?? null, roles, sessions: userSessions, passwordReset: passwordReset ?? null });
51
+ }
52
+
53
+ /**
54
+ * Deletes the account and everything auth keeps for it. The child rows go first, by name, so the
55
+ * deletion does not depend on the cascades alone; every session ends with them.
56
+ */
57
+ export async function deleteAuthUserData(context: ModuleContext, userId: string): Promise<Ok<undefined>> {
58
+ if (!UUID.test(userId)) return ok();
59
+ const db = context.db as Queryable;
60
+ await db.delete(sessions).where(eq(sessions.userId, userId));
61
+ await db.delete(passwordResets).where(eq(passwordResets.userId, userId));
62
+ await db.delete(userRoles).where(eq(userRoles.userId, userId));
63
+ await db.delete(users).where(eq(users.id, userId));
64
+ return ok();
65
+ }
66
+
67
+ export const authPrivacyContributor: PrivacyContributor = {
68
+ exportUserData: exportAuthUserData,
69
+ deleteUserData: deleteAuthUserData,
70
+ };
@@ -0,0 +1,51 @@
1
+ // The rate limit buckets auth consumes (AUTH_RATE_LIMIT_BUCKETS). Each attempt is counted before the
2
+ // work it guards, hashing included, so a flood is stopped before it costs anything.
3
+ import { getModule, type SoftureConfig } from "@softure-ai/core";
4
+ import { subjectKey } from "@softure-ai/security/server";
5
+ import { getAuthOptions } from "./options.js";
6
+
7
+ export const BUCKETS = {
8
+ register: "register",
9
+ login: "login",
10
+ loginAccount: "login-account",
11
+ changePassword: "change-password",
12
+ passwordReset: "password-reset",
13
+ passwordResetAccount: "password-reset-account",
14
+ passwordResetConfirm: "password-reset-confirm",
15
+ } as const;
16
+
17
+ /** The subject key of an account's email for `login-account` and `password-reset-account`. */
18
+ export function emailSubjectKey(normalizedEmail: string): string {
19
+ return subjectKey(`email:${normalizedEmail}`);
20
+ }
21
+
22
+ /** The subject key of a user for `change-password`. */
23
+ export function userSubjectKey(userId: string): string {
24
+ return subjectKey(`user:${userId}`);
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
+
30
+ const checkedConfigs = new WeakSet<SoftureConfig>();
31
+
32
+ /**
33
+ * Throws, naming every missing bucket, when the app's `security({ buckets })` lacks one auth
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.
37
+ */
38
+ export function assertAuthBuckets(config: SoftureConfig): void {
39
+ if (checkedConfigs.has(config)) return;
40
+ const options = getModule(config, "security")?.options as { buckets?: Readonly<Record<string, unknown>> } | undefined;
41
+ const configured = options?.buckets ?? {};
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));
45
+ if (missing.length > 0) {
46
+ throw new Error(
47
+ `@softure-ai/auth: security({ buckets }) lacks ${missing.map((name) => `"${name}"`).join(", ")}; spread AUTH_RATE_LIMIT_BUCKETS into it`,
48
+ );
49
+ }
50
+ checkedConfigs.add(config);
51
+ }
@@ -0,0 +1,16 @@
1
+ // Re-authentication before an action that cannot be undone, such as deleting the account: the
2
+ // signed-in user types their password again, so a session cookie alone is not enough.
3
+ import { eq } from "drizzle-orm";
4
+ import { users } from "../schema.js";
5
+ import { verifyPassword } from "./password.js";
6
+ import type { AuthContext } from "./sessions.js";
7
+
8
+ /**
9
+ * Whether `password` is the current password of the account. False for an unknown account. The
10
+ * caller counts the attempt in a rate limit bucket first: this is a password check like a login.
11
+ */
12
+ export async function isCurrentPassword(ctx: AuthContext, userId: string, password: string): Promise<boolean> {
13
+ const [stored] = await ctx.db.select({ passwordHash: users.passwordHash }).from(users).where(eq(users.id, userId)).limit(1);
14
+ if (stored === undefined) return false;
15
+ return verifyPassword(password, stored.passwordHash);
16
+ }
@@ -0,0 +1,87 @@
1
+ // Registration: a new account with its first session, in one transaction with the app's
2
+ // `onRegistered` hook, so a consent the hook could not store never leaves an account behind.
3
+ import { err, ok, type Err, type Ok } from "@softure-ai/core";
4
+ import type { RateLimitRejection } from "@softure-ai/security";
5
+ import { consumeRateLimit } from "@softure-ai/security/server";
6
+ import type { SignedIn } from "../contract.js";
7
+ import { users } from "../schema.js";
8
+ import { getAuthOptions } from "./options.js";
9
+ import { hashPassword } from "./password.js";
10
+ import { assertAuthBuckets, BUCKETS } from "./rate-limits.js";
11
+ import { createSession, type AuthContext } from "./sessions.js";
12
+ import { isRegistrationClosed } from "./switches.js";
13
+ import { checkNewPassword, parseEmail } from "./validation.js";
14
+
15
+ export interface RegisterInput {
16
+ readonly email: string;
17
+ readonly password: string;
18
+ /** Whether the consent checkbox was ticked. */
19
+ readonly hasConsented: boolean;
20
+ /** The client's rate limit key (`identifyClient`). */
21
+ readonly clientKey: string;
22
+ /** Values of the app's `registrationFields`; other names are dropped. */
23
+ readonly fields?: Readonly<Record<string, string>>;
24
+ }
25
+
26
+ /** Longest registration field value handed to the hook; longer ones are cut. */
27
+ const MAX_FIELD_LENGTH = 512;
28
+
29
+ export type RegisterErrorCode =
30
+ | "auth.registration_closed"
31
+ | "auth.email_invalid"
32
+ | "auth.email_taken"
33
+ | "auth.password_too_short"
34
+ | "auth.password_too_long"
35
+ | "auth.consent_required";
36
+
37
+ export type RegisterResult = Ok<SignedIn> | Err<RegisterErrorCode> | RateLimitRejection;
38
+
39
+ /**
40
+ * Creates an account and signs it in. The input is checked first (cheap, and a typo should not
41
+ * spend the client's attempts), then the `register` bucket is counted, then the password is hashed.
42
+ * Database errors and errors thrown by the hook propagate after the rollback.
43
+ */
44
+ export async function registerUser(ctx: AuthContext, input: RegisterInput): Promise<RegisterResult> {
45
+ const options = getAuthOptions(ctx.config);
46
+ assertAuthBuckets(ctx.config);
47
+ if (await isRegistrationClosed(ctx)) return err("auth.registration_closed");
48
+
49
+ const email = parseEmail(input.email);
50
+ if (!email.ok) return email;
51
+ const passwordPolicy = checkNewPassword(input.password, options.password.minLength);
52
+ // A fresh error, not the check's own result: CodeQL treats that result as password data and
53
+ // would follow it through the returned union to the session token (js/insufficient-password-hash).
54
+ if (!passwordPolicy.ok) return err(passwordPolicy.error);
55
+ if (options.requireConsent && !input.hasConsented) return err("auth.consent_required");
56
+
57
+ const limit = await consumeRateLimit(ctx, { bucket: BUCKETS.register, key: input.clientKey });
58
+ if (!limit.ok) return limit;
59
+
60
+ const passwordHash = await hashPassword(input.password, options.password.scrypt);
61
+ const now = ctx.clock.now();
62
+
63
+ return ctx.db.transaction(async (tx): Promise<Ok<SignedIn> | Err<"auth.email_taken">> => {
64
+ const txCtx: AuthContext = { ...ctx, db: tx };
65
+ const [row] = await tx
66
+ .insert(users)
67
+ .values({ email: email.value, passwordHash, createdAt: now, passwordChangedAt: now })
68
+ .onConflictDoNothing({ target: users.email })
69
+ .returning();
70
+ if (row === undefined) return err("auth.email_taken");
71
+ const user = { id: row.id, email: row.email, createdAt: row.createdAt };
72
+
73
+ const fields = pickRegistrationFields(options.registrationFields, input.fields);
74
+ await options.onRegistered?.({ user, consent: options.requireConsent ? { acceptedAt: now } : null, fields }, txCtx);
75
+ const session = await createSession(txCtx, user.id);
76
+ return ok({ user, session });
77
+ });
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
+ }
@@ -0,0 +1,72 @@
1
+ // Roles: rows of auth.user_roles, plus `admin` for the accounts listed in `adminEmails`. Nothing is
2
+ // granted by default, so with no admin configured every admin-only surface stays closed.
3
+ import { err, ok, type Err, type Ok, type SoftureConfig } from "@softure-ai/core";
4
+ import { and, eq } from "drizzle-orm";
5
+ import type { AuthUser } from "../contract.js";
6
+ import { ADMIN_ROLE } from "../roles.js";
7
+ import { userRoles } from "../schema.js";
8
+ import { getAuthOptions } from "./options.js";
9
+ import type { AuthContext } from "./sessions.js";
10
+
11
+ export type RoleErrorCode = "auth.role_undeclared" | "auth.role_already_granted" | "auth.role_not_granted";
12
+
13
+ export interface RoleChange {
14
+ readonly userId: string;
15
+ readonly role: string;
16
+ }
17
+
18
+ /** `admin` and the roles the app declared in `auth({ roles })`. */
19
+ export function getDeclaredRoles(config: SoftureConfig): ReadonlySet<string> {
20
+ return new Set([ADMIN_ROLE, ...getAuthOptions(config).roles]);
21
+ }
22
+
23
+ export function isDeclaredRole(config: SoftureConfig, role: string): boolean {
24
+ return getDeclaredRoles(config).has(role);
25
+ }
26
+
27
+ /**
28
+ * Throws for a role the app never declared: a check for a mistyped role is a bug, and it must
29
+ * fail loudly instead of quietly denying (or, worse, allowing) everyone.
30
+ */
31
+ export function assertDeclaredRole(config: SoftureConfig, role: string): void {
32
+ if (!isDeclaredRole(config, role)) {
33
+ const declared = [...getDeclaredRoles(config)].join(", ");
34
+ throw new Error(`@softure-ai/auth: role "${role}" is not declared (declared: ${declared}); add it to auth({ roles }) in softure.config.ts`);
35
+ }
36
+ }
37
+
38
+ /** Whether `adminEmails` makes this account an admin. */
39
+ export function isConfiguredAdmin(config: SoftureConfig, user: Pick<AuthUser, "email">): boolean {
40
+ return getAuthOptions(config).adminEmails.includes(user.email);
41
+ }
42
+
43
+ /** Every role the user holds: its rows, and `admin` when its email is in `adminEmails`. */
44
+ export async function findUserRoles(ctx: AuthContext, user: Pick<AuthUser, "id" | "email">): Promise<ReadonlySet<string>> {
45
+ const rows = await ctx.db.select({ role: userRoles.role }).from(userRoles).where(eq(userRoles.userId, user.id));
46
+ const roles = new Set(rows.map((row) => row.role));
47
+ if (isConfiguredAdmin(ctx.config, user)) roles.add(ADMIN_ROLE);
48
+ return roles;
49
+ }
50
+
51
+ /** Stores a declared role for a user. An unknown user id is a foreign key error and propagates. */
52
+ export async function grantRole(
53
+ ctx: AuthContext,
54
+ change: RoleChange,
55
+ ): Promise<Ok<undefined> | Err<"auth.role_undeclared" | "auth.role_already_granted">> {
56
+ if (!isDeclaredRole(ctx.config, change.role)) return err("auth.role_undeclared");
57
+ const inserted = await ctx.db
58
+ .insert(userRoles)
59
+ .values({ userId: change.userId, role: change.role, grantedAt: ctx.clock.now() })
60
+ .onConflictDoNothing()
61
+ .returning();
62
+ return inserted.length === 0 ? err("auth.role_already_granted") : ok();
63
+ }
64
+
65
+ /** Deletes a stored role. It cannot take away an `admin` that comes from `adminEmails`. */
66
+ export async function revokeRole(ctx: AuthContext, change: RoleChange): Promise<Ok<undefined> | Err<"auth.role_not_granted">> {
67
+ const deleted = await ctx.db
68
+ .delete(userRoles)
69
+ .where(and(eq(userRoles.userId, change.userId), eq(userRoles.role, change.role)))
70
+ .returning();
71
+ return deleted.length === 0 ? err("auth.role_not_granted") : ok();
72
+ }
@@ -0,0 +1,25 @@
1
+ // Session tokens: 32 random bytes in the cookie, only their sha256 in the database. A stolen
2
+ // database row cannot be replayed as a cookie.
3
+ import { createHash, randomBytes } from "node:crypto";
4
+
5
+ const TOKEN_BYTES = 32;
6
+ /** base64url of 32 bytes. */
7
+ const TOKEN_SHAPE = /^[A-Za-z0-9_-]{43}$/;
8
+
9
+ export function createSessionToken(): { readonly token: string; readonly tokenHash: string } {
10
+ const token = randomBytes(TOKEN_BYTES).toString("base64url");
11
+ return { token, tokenHash: hashSessionToken(token) };
12
+ }
13
+
14
+ export function hashSessionToken(token: string): string {
15
+ return createHash("sha256").update(token, "utf8").digest("hex");
16
+ }
17
+
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);
25
+ }
@@ -0,0 +1,65 @@
1
+ // Database sessions: one row per login, keyed by the sha256 of the cookie token, with a fixed expiry.
2
+ import type { ModuleContext } from "@softure-ai/core";
3
+ import type { Queryable } from "@softure-ai/db";
4
+ import { and, eq, gt, lte, ne } from "drizzle-orm";
5
+ import type { AuthUser, NewSession } from "../contract.js";
6
+ import { sessions, users } from "../schema.js";
7
+ import { getAuthOptions, getLegacyTokenPattern } from "./options.js";
8
+ import { createSessionToken, hashSessionToken, isSessionTokenShape } from "./session-token.js";
9
+
10
+ export type AuthContext = ModuleContext<Queryable>;
11
+
12
+ const DAY_MS = 24 * 60 * 60 * 1000;
13
+
14
+ /** Opens a session for `userId`; the returned token goes into the cookie. */
15
+ export async function createSession(ctx: AuthContext, userId: string): Promise<NewSession> {
16
+ const now = ctx.clock.now();
17
+ const expiresAt = new Date(now.getTime() + getAuthOptions(ctx.config).session.ttlDays * DAY_MS);
18
+ const { token, tokenHash } = createSessionToken();
19
+ await ctx.db.insert(sessions).values({ tokenHash, userId, createdAt: now, expiresAt });
20
+ return { token, expiresAt };
21
+ }
22
+
23
+ /** The user of a live session, or null for an unknown, malformed or expired token. */
24
+ export async function findSessionUser(ctx: AuthContext, token: string): Promise<AuthUser | null> {
25
+ if (!isSessionTokenShape(token, getLegacyTokenPattern(ctx.config))) return null;
26
+ const [row] = await ctx.db
27
+ .select({ id: users.id, email: users.email, createdAt: users.createdAt })
28
+ .from(sessions)
29
+ .innerJoin(users, eq(users.id, sessions.userId))
30
+ .where(and(eq(sessions.tokenHash, hashSessionToken(token)), gt(sessions.expiresAt, ctx.clock.now())))
31
+ .limit(1);
32
+ return row ?? null;
33
+ }
34
+
35
+ /** Ends one session. An unknown token is already logged out, so it is not an error. */
36
+ export async function logoutSession(ctx: AuthContext, token: string): Promise<void> {
37
+ if (!isSessionTokenShape(token, getLegacyTokenPattern(ctx.config))) return;
38
+ await ctx.db.delete(sessions).where(eq(sessions.tokenHash, hashSessionToken(token)));
39
+ }
40
+
41
+ /** Deletes every expired session; for a scheduled job. Returns how many were deleted. */
42
+ export async function pruneSessions(ctx: AuthContext): Promise<number> {
43
+ const deleted = await ctx.db.delete(sessions).where(lte(sessions.expiresAt, ctx.clock.now())).returning();
44
+ return deleted.length;
45
+ }
46
+
47
+ /** Deletes the expired sessions of one user (at their login, so rows do not pile up without a job). */
48
+ export async function deleteExpiredSessions(ctx: AuthContext, userId: string): Promise<void> {
49
+ await ctx.db.delete(sessions).where(and(eq(sessions.userId, userId), lte(sessions.expiresAt, ctx.clock.now())));
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
+ }