@plitzi/sdk-server 0.38.23 → 0.39.0

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 (233) hide show
  1. package/CHANGELOG.md +172 -1
  2. package/README.md +55 -9
  3. package/dist/actions.d.ts +4 -1
  4. package/dist/actions.js +3 -2
  5. package/dist/auth.d.ts +2 -2
  6. package/dist/auth.js +5 -4
  7. package/dist/core/auth/api/accounts.d.ts +11 -0
  8. package/dist/core/auth/api/accounts.js +175 -0
  9. package/dist/core/auth/api/admin.d.ts +41 -0
  10. package/dist/core/auth/api/admin.js +146 -0
  11. package/dist/core/auth/api/context.d.ts +119 -0
  12. package/dist/core/auth/api/context.js +262 -0
  13. package/dist/core/auth/api/factors.d.ts +31 -0
  14. package/dist/core/auth/api/factors.js +209 -0
  15. package/dist/core/auth/api/index.d.ts +94 -0
  16. package/dist/core/auth/api/index.js +43 -0
  17. package/dist/core/auth/api/profile.d.ts +43 -0
  18. package/dist/core/auth/api/profile.js +243 -0
  19. package/dist/core/auth/api/session.d.ts +62 -0
  20. package/dist/core/auth/api/session.js +312 -0
  21. package/dist/core/auth/{api.d.ts → api/types.d.ts} +41 -195
  22. package/dist/core/auth/api/values.d.ts +67 -0
  23. package/dist/core/auth/api/values.js +90 -0
  24. package/dist/core/auth/createAuth.d.ts +49 -39
  25. package/dist/core/auth/createAuth.js +21 -1
  26. package/dist/core/auth/oauth/client.d.ts +2 -2
  27. package/dist/core/auth/oauth/client.js +6 -1
  28. package/dist/core/auth/oauth/index.d.ts +30 -7
  29. package/dist/core/auth/oauth/index.js +33 -14
  30. package/dist/core/auth/oauth/providers/github.js +1 -1
  31. package/dist/core/auth/oauth/providers/google.js +1 -1
  32. package/dist/core/auth/oauth/providers/oidc.d.ts +40 -0
  33. package/dist/core/auth/oauth/providers/oidc.js +197 -0
  34. package/dist/core/auth/oauth/state.d.ts +2 -0
  35. package/dist/core/auth/oauth/state.js +2 -0
  36. package/dist/core/auth/oauth/types.d.ts +21 -3
  37. package/dist/core/auth/oauth/types.js +4 -1
  38. package/dist/core/auth/routes.js +1 -1
  39. package/dist/core/auth/tokens.d.ts +3 -1
  40. package/dist/core/auth/tokens.js +2 -1
  41. package/dist/core/configSeam.d.ts +0 -4
  42. package/dist/core/configSeam.js +12 -1
  43. package/dist/core/createServer.js +16 -4
  44. package/dist/core/freePort.d.ts +10 -0
  45. package/dist/core/freePort.js +39 -1
  46. package/dist/core/handlers/socialRouteHandlers.d.ts +9 -1
  47. package/dist/core/handlers/socialRouteHandlers.js +46 -12
  48. package/dist/core/health.d.ts +1 -0
  49. package/dist/core/health.js +2 -1
  50. package/dist/core/http/stages/authRoutes.d.ts +6 -0
  51. package/dist/core/http/stages/authRoutes.js +42 -1
  52. package/dist/core/http/stages/images.js +5 -3
  53. package/dist/core/http/stages/livePages.js +1 -1
  54. package/dist/core/server/fleet/relay.js +9 -1
  55. package/dist/core/server/fleet/stores.d.ts +7 -0
  56. package/dist/core/server/fleet/stores.js +15 -2
  57. package/dist/core/server/pageServer.js +5 -1
  58. package/dist/core/services/realtime.js +4 -2
  59. package/dist/core/services/registry.js +7 -1
  60. package/dist/core/services/robotsTxt.d.ts +16 -0
  61. package/dist/core/services/robotsTxt.js +50 -0
  62. package/dist/core/services/servedSpace.d.ts +8 -0
  63. package/dist/core/services/servedSpace.js +16 -0
  64. package/dist/core/services/sitemapXml.d.ts +7 -0
  65. package/dist/core/services/sitemapXml.js +37 -0
  66. package/dist/functions-api.d.ts +75 -2
  67. package/dist/helpers/fileStore.d.ts +60 -0
  68. package/dist/helpers/fileStore.js +127 -0
  69. package/dist/helpers/outboundGuard.d.ts +32 -3
  70. package/dist/helpers/outboundGuard.js +50 -5
  71. package/dist/hosts/project/agentRuns.d.ts +24 -0
  72. package/dist/hosts/project/agentRuns.js +107 -0
  73. package/dist/hosts/project/laterAsks.d.ts +41 -0
  74. package/dist/hosts/project/laterAsks.js +117 -0
  75. package/dist/hosts/project/plugins.js +11 -4
  76. package/dist/hosts/project/serveProject.d.ts +11 -3
  77. package/dist/hosts/project/serveProject.js +94 -36
  78. package/dist/hosts/project/spaceFailure.d.ts +4 -0
  79. package/dist/hosts/project/spaceFailure.js +10 -0
  80. package/dist/hosts/project/watchSpace.d.ts +5 -5
  81. package/dist/hosts/project/watchSpace.js +15 -6
  82. package/dist/index.js +2 -2
  83. package/dist/kernel.js +1 -1
  84. package/dist/modules/actions/connectorWrite.js +3 -1
  85. package/dist/modules/actions/index.js +1 -1
  86. package/dist/modules/actions/jobs/fileQueue.d.ts +34 -0
  87. package/dist/modules/actions/jobs/fileQueue.js +72 -0
  88. package/dist/modules/actions/jobs/index.js +3 -3
  89. package/dist/modules/actions/jobs/memoryQueue.js +6 -215
  90. package/dist/modules/actions/jobs/queueDocument.d.ts +14 -0
  91. package/dist/modules/actions/jobs/queueDocument.js +22 -0
  92. package/dist/modules/actions/jobs/queueRules.d.ts +39 -0
  93. package/dist/modules/actions/jobs/queueRules.js +270 -0
  94. package/dist/modules/actions/moduleFor.js +2 -0
  95. package/dist/modules/actions/runtime/fileKv.d.ts +3 -1
  96. package/dist/modules/actions/runtime/fileKv.js +12 -98
  97. package/dist/modules/actions/runtime/guards.d.ts +19 -1
  98. package/dist/modules/actions/runtime/guards.js +10 -1
  99. package/dist/modules/actions/runtime/kvChange.d.ts +40 -0
  100. package/dist/modules/actions/runtime/kvChange.js +23 -1
  101. package/dist/modules/actions/runtime/kvList.d.ts +4 -0
  102. package/dist/modules/actions/runtime/kvList.js +5 -1
  103. package/dist/modules/actions/runtime/kvStore.js +15 -1
  104. package/dist/modules/actions/runtime/namespaceKv.js +2 -0
  105. package/dist/modules/actions/runtime/renderResolver.js +31 -5
  106. package/dist/modules/actions/runtime/runAction.js +16 -6
  107. package/dist/modules/actions/runtime/scope.js +11 -0
  108. package/dist/modules/actions/runtime/taskContext.js +11 -32
  109. package/dist/modules/actions/tasks/auth.js +2 -0
  110. package/dist/modules/actions/tasks/connector.js +6 -2
  111. package/dist/modules/actions/tasks/flow.js +5 -0
  112. package/dist/modules/actions/tasks/http.js +2 -1
  113. package/dist/modules/actions/tasks/kv.js +5 -0
  114. package/dist/modules/actions/tasks/list.js +11 -2
  115. package/dist/modules/actions/tasks/transform.js +2 -0
  116. package/dist/modules/actions/transport/callHandler.js +25 -4
  117. package/dist/modules/actions/types.d.ts +46 -1
  118. package/dist/modules/connectors/engine.d.ts +7 -2
  119. package/dist/modules/connectors/engine.js +4 -4
  120. package/dist/modules/connectors/resolver.d.ts +2 -1
  121. package/dist/modules/connectors/resolver.js +3 -2
  122. package/dist/modules/functions/build.d.ts +7 -2
  123. package/dist/modules/functions/build.js +90 -6
  124. package/dist/modules/functions/capabilities.js +21 -0
  125. package/dist/modules/functions/context.js +6 -2
  126. package/dist/modules/functions/contract.d.ts +45 -1
  127. package/dist/modules/functions/driver.d.ts +2 -1
  128. package/dist/modules/functions/driver.js +39 -0
  129. package/dist/modules/functions/load.d.ts +1 -1
  130. package/dist/modules/functions/load.js +2 -2
  131. package/dist/modules/functions/manifest.js +7 -1
  132. package/dist/modules/functions/oauth.d.ts +3 -1
  133. package/dist/modules/functions/oauth.js +20 -7
  134. package/dist/modules/functions/protocol.d.ts +9 -0
  135. package/dist/modules/functions/sandbox/guest/bytes.d.ts +27 -0
  136. package/dist/modules/functions/sandbox/guest/bytes.js +108 -0
  137. package/dist/modules/functions/sandbox/guest/crypto.d.ts +47 -0
  138. package/dist/modules/functions/sandbox/guest/crypto.js +144 -0
  139. package/dist/modules/functions/sandbox/guest/events.d.ts +152 -0
  140. package/dist/modules/functions/sandbox/guest/events.js +143 -0
  141. package/dist/modules/functions/sandbox/guest/fetch.d.ts +305 -0
  142. package/dist/modules/functions/sandbox/guest/fetch.js +237 -0
  143. package/dist/modules/functions/sandbox/guest/index.d.ts +28 -0
  144. package/dist/modules/functions/sandbox/guest/index.js +130 -0
  145. package/dist/modules/functions/sandbox/{guest.d.ts → guest/types.d.ts} +5 -12
  146. package/dist/modules/functions/sandbox/isolate.js +20 -6
  147. package/dist/modules/functions/space.js +2 -8
  148. package/dist/modules/images/imageProxy.d.ts +3 -2
  149. package/dist/modules/images/imageProxy.js +2 -2
  150. package/dist/modules/mongo/jobQueue.js +0 -19
  151. package/dist/modules/mysql/accounts.js +12 -5
  152. package/dist/modules/mysql/jobs/index.d.ts +1 -1
  153. package/dist/modules/mysql/jobs/schema.d.ts +0 -6
  154. package/dist/modules/mysql/jobs/schema.js +2 -46
  155. package/dist/modules/mysql/schema.js +26 -1
  156. package/dist/modules/mysql/sessions.js +2 -1
  157. package/dist/modules/realtime/handlers.d.ts +9 -4
  158. package/dist/modules/realtime/handlers.js +20 -3
  159. package/dist/modules/realtime/hub.d.ts +4 -2
  160. package/dist/modules/realtime/hub.js +36 -4
  161. package/dist/modules/realtime/index.d.ts +14 -0
  162. package/dist/modules/realtime/index.js +14 -1
  163. package/dist/modules/realtime/presence.d.ts +33 -0
  164. package/dist/modules/realtime/presence.js +56 -0
  165. package/dist/modules/realtime/socket.d.ts +3 -1
  166. package/dist/modules/realtime/socket.js +2 -2
  167. package/dist/modules/rsc/connectorRscData.d.ts +6 -1
  168. package/dist/modules/rsc/connectorRscData.js +27 -6
  169. package/dist/modules/rsc/externalQueryReader.d.ts +28 -0
  170. package/dist/modules/rsc/externalQueryReader.js +43 -0
  171. package/dist/modules/rsc/handler.js +1 -1
  172. package/dist/modules/rsc/resolveRscData.d.ts +11 -1
  173. package/dist/modules/rsc/resolveRscData.js +86 -16
  174. package/dist/modules/runtime/inside.js +1 -1
  175. package/dist/modules/runtime/runner.js +2 -1
  176. package/dist/modules/sqlite/jobQueue.d.ts +35 -0
  177. package/dist/modules/sqlite/jobQueue.js +56 -0
  178. package/dist/modules/sqlite/kv.d.ts +1 -1
  179. package/dist/modules/sqlite/kv.js +2 -10
  180. package/dist/modules/sqlite/open.d.ts +3 -0
  181. package/dist/modules/sqlite/open.js +13 -0
  182. package/dist/modules/ssr/Component.d.ts +5 -1
  183. package/dist/modules/ssr/Component.js +3 -1
  184. package/dist/modules/ssr/applySSRResult.d.ts +8 -1
  185. package/dist/modules/ssr/applySSRResult.js +23 -3
  186. package/dist/modules/ssr/handler.js +30 -5
  187. package/dist/modules/ssr/prepareRender.js +27 -5
  188. package/dist/modules/ssr/preview.d.ts +2 -0
  189. package/dist/modules/ssr/preview.js +6 -3
  190. package/dist/modules/ssr/registerExternalPlugins.d.ts +2 -6
  191. package/dist/modules/ssr/registerExternalPlugins.js +2 -2
  192. package/dist/modules/ssr/resolvePageSeo.d.ts +11 -0
  193. package/dist/modules/ssr/resolvePageSeo.js +13 -2
  194. package/dist/modules/ssr/streamBody.js +2 -2
  195. package/dist/modules/ssr/views/template.ejs +21 -17
  196. package/dist/mysql.d.ts +1 -1
  197. package/dist/mysql.js +2 -2
  198. package/dist/plugins/manager.d.ts +5 -0
  199. package/dist/plugins/manager.js +9 -0
  200. package/dist/sqlite.d.ts +8 -1
  201. package/dist/sqlite.js +3 -1
  202. package/package.json +5 -5
  203. package/skills/plitzi-authoring/CHEATSHEET.md +6 -6
  204. package/skills/plitzi-authoring/SKILL.md +4 -2
  205. package/skills/plitzi-authoring/recipes/accordion.ts +2 -1
  206. package/skills/plitzi-authoring/recipes/carousel.ts +24 -3
  207. package/skills/plitzi-authoring/recipes/detail-page.ts +0 -1
  208. package/skills/plitzi-authoring/recipes/embed-and-svg.ts +3 -1
  209. package/skills/plitzi-authoring/recipes/filter-a-list.ts +0 -1
  210. package/skills/plitzi-authoring/recipes/show-data.ts +0 -1
  211. package/skills/plitzi-authoring/recipes/typed-data.ts +0 -1
  212. package/skills/plitzi-authoring/reference/accessibility.md +7 -2
  213. package/skills/plitzi-authoring/reference/auth.md +15 -4
  214. package/skills/plitzi-authoring/reference/authoring-errors.md +51 -10
  215. package/skills/plitzi-authoring/reference/colours-and-motion.md +7 -1
  216. package/skills/plitzi-authoring/reference/components.md +4 -1
  217. package/skills/plitzi-authoring/reference/data-and-visibility.md +31 -22
  218. package/skills/plitzi-authoring/reference/efficiency.md +2 -1
  219. package/skills/plitzi-authoring/reference/elements-and-styles.md +16 -15
  220. package/skills/plitzi-authoring/reference/flows.md +20 -8
  221. package/skills/plitzi-authoring/reference/kept-state.md +8 -0
  222. package/skills/plitzi-authoring/reference/layouts.md +18 -2
  223. package/skills/plitzi-authoring/reference/lists.md +20 -4
  224. package/skills/plitzi-authoring/reference/plugin-reach.md +12 -0
  225. package/skills/plitzi-authoring/reference/plugins.md +13 -2
  226. package/skills/plitzi-authoring/reference/realtime.md +8 -5
  227. package/skills/plitzi-authoring/reference/structure.md +17 -1
  228. package/skills/plitzi-authoring/reference/templates.md +11 -3
  229. package/skills/plitzi-authoring/reference/testing.md +82 -5
  230. package/skills/plitzi-authoring/reference/typed-sources.md +6 -0
  231. package/skills/plitzi-authoring/reference/validation.md +1 -1
  232. package/dist/core/auth/api.js +0 -1323
  233. package/dist/modules/functions/sandbox/guest.js +0 -662
@@ -1,1323 +0,0 @@
1
- import { serverLog } from "../../helpers/serverLog.js";
2
- import { forwardedIp } from "../requestParser.js";
3
- import { checkPermission } from "./authorize.js";
4
- import { generateToken, hashPassword, verifyPassword } from "./passwords.js";
5
- import { createMemoryRateLimit, fleetRateLimit } from "./throttle.js";
6
- import { authFailureMessage, userIdOf } from "./tokens.js";
7
- import { generateRecoveryCodes, generateTotpSecret, normalizeRecoveryCode, randomCode, totpStep, totpUri } from "./totp.js";
8
- import { createHash } from "node:crypto";
9
- //#region src/core/auth/api.ts
10
- /**
11
- * The user agent and the address, off whatever carried the request — what lets somebody tell their devices apart.
12
- * Nothing else here reads headers, so it is done once. The address is the host's when it resolved one, the proxies'
13
- * otherwise; it names a session in a list and decides nothing.
14
- */
15
- var clientOf = (carrier) => {
16
- if (!carrier) return;
17
- const userAgent = carrier.headers["user-agent"];
18
- const ip = carrier.ip || forwardedIp(carrier.headers);
19
- const client = {
20
- ...typeof userAgent === "string" && userAgent ? { userAgent } : {},
21
- ...ip ? { ip } : {}
22
- };
23
- return client.userAgent || client.ip ? client : void 0;
24
- };
25
- var refuse = (status, error, reason) => ({
26
- ok: false,
27
- status,
28
- body: reason ? {
29
- error,
30
- reason
31
- } : { error }
32
- });
33
- var NOT_OFFERED = refuse(404, "Not found");
34
- /**
35
- * A field from a request body, as a string. Numbers count: JSON carries an all-digits password as a number, and a
36
- * client that sends one has supplied a password — refusing it as "credentials are required" is a lie about what
37
- * arrived. Objects and arrays do not, since `[object Object]` is not a value anybody sent.
38
- */
39
- var asText = (value) => {
40
- if (typeof value === "string") return value;
41
- return typeof value === "number" && Number.isFinite(value) ? String(value) : "";
42
- };
43
- var asString = (value) => asText(value).trim();
44
- /**
45
- * The destination a caller named, for a mail to carry — or nothing at all.
46
- *
47
- * Carried, not judged: the kernel has no redirect policy, and the link it ends up in is composed by the deployment,
48
- * which vets it there (`createRedirectPolicy`). Absent rather than empty when there is none, so a mail template never
49
- * has to know that `''` means "nowhere".
50
- */
51
- var destinationOf = (value) => {
52
- const redirect = asString(value);
53
- return redirect ? { redirect } : {};
54
- };
55
- var now = () => Math.floor(Date.now() / 1e3);
56
- var HOUR = 3600;
57
- /**
58
- * How long the things this server mails or hands out stay good for. Constants rather than configuration: each is a
59
- * security answer with one sensible value, and an option here is a question every deployment has to work out an
60
- * answer to before it can start.
61
- */
62
- var LIFETIME = {
63
- /** A code from an email. Long enough to go and find it, short enough that a stolen one is worthless. */
64
- signInCode: 600,
65
- /** A reset link IS a password, and it sits in an inbox, a mail archive, a forwarded ticket. */
66
- resetLink: HOUR,
67
- /** Confirming an address is not a credential in the same way, and people read their mail tomorrow. */
68
- confirmLink: 24 * HOUR,
69
- /** A borrowed session — see `admin.impersonate`. Short, and it cannot renew. */
70
- impersonation: 900
71
- };
72
- var STATUSES = [
73
- "active",
74
- "inactive",
75
- "blocked"
76
- ];
77
- /**
78
- * Why an account may not hold a session, when it may not.
79
- *
80
- * `active` answers whether it may sign in at all; `verified` answers whether its owner can do anything about that.
81
- * A deployment where confirming an address is what makes an account active — Plitzi is one — refuses both through
82
- * the same flag, so a screen told only `inactive` has to tell somebody whose address has simply never answered that
83
- * their password was wrong. It was, in fact, right.
84
- */
85
- var deniedReason = (account) => account && !account.verified ? "unverified" : "inactive";
86
- /** An account as it may be shown. Never the password hash, and never the credentials — not even to an admin. */
87
- var profileOf = (account) => ({
88
- id: account.id,
89
- username: account.username,
90
- email: account.email,
91
- active: account.active,
92
- verified: account.verified
93
- });
94
- /**
95
- * The HTTP surface of authentication, as functions rather than routes.
96
- *
97
- * Nothing here knows about Express, or about this server's own pipeline: a handler is given what the request
98
- * carried and answers what should be sent, including whether the session cookies should be written or cleared. The
99
- * binding does the rest, which is what lets the same login live behind an API endpoint and behind a rendered page's
100
- * form without either owning it.
101
- */
102
- var createAuthApi = ({ tokens, identity, adapters, config = {} }) => {
103
- const { verifyPassword: verifyPassword$1 = verifyPassword, hashPassword: hashPassword$1 = hashPassword, generateToken: generateToken$1 = generateToken, verifyOnSignup = false, adminPermission = "userManage", impersonationPermission, password: policy = {}, rateLimit = fleetRateLimit() ?? createMemoryRateLimit(), onMailError, onEvent, mfaIssuer, csrf } = config;
104
- /** Never awaited, never able to throw: a logging outage must not become an authentication outage. */
105
- const record = (event) => {
106
- if (!onEvent) return;
107
- try {
108
- onEvent({
109
- ...event,
110
- at: Math.floor(Date.now() / 1e3)
111
- });
112
- } catch (error) {
113
- serverLog.error("auth", "security event handler threw", error);
114
- }
115
- };
116
- /**
117
- * A single-use link token that stops working.
118
- *
119
- * The deadline is carried **inside the token**, after a `~`, and that is what makes this cost nothing: no column,
120
- * no adapter argument, and nothing a deployment with its own store has to remember to enforce — which is the
121
- * failure mode of putting the check in the adapters, where forgetting it is silent and looks like everything
122
- * working. It is not a secret and does not need to be: the token is compared against the stored copy, so editing
123
- * the deadline just produces a string that matches no row.
124
- *
125
- * A token issued before this existed has no `~`, reads as no deadline, and keeps working — the links already in
126
- * people's inboxes when a deployment upgrades.
127
- */
128
- const mintLink = (random, lifetime) => `${random}~${now() + lifetime}`;
129
- const linkExpired = (token) => {
130
- const deadline = Number(token.slice(token.lastIndexOf("~") + 1));
131
- return Number.isFinite(deadline) && token.includes("~") && deadline < now();
132
- };
133
- /** Recovery codes are high-entropy, so a fast digest is right — scrypt ten times per sign-in would not be. */
134
- const digestRecoveryCode = (code) => createHash("sha256").update(normalizeRecoveryCode(code)).digest("hex");
135
- /**
136
- * Sends, and never fails the flow if it cannot.
137
- *
138
- * Every one of these goes out AFTER something has already been committed — an account created, an address
139
- * changed, a reset token stored. Letting the mail provider decide whether that request succeeded turns an
140
- * outage at Brevo into a 500 on a change that did happen, which is the worst of both: the caller is told it
141
- * failed and retries against the new state. Reported instead, and the person can ask for another.
142
- */
143
- const deliver = async (message) => {
144
- try {
145
- await adapters.sendMail?.(message);
146
- } catch (error) {
147
- (onMailError ?? ((cause) => serverLog.error("auth", "could not send mail", cause)))(error, {
148
- to: message.to,
149
- template: message.template
150
- });
151
- }
152
- };
153
- /**
154
- * Checked before the password is, so a throttled attempt costs no hash — which is the difference between a rate
155
- * limit and a slightly slower way to be brute-forced.
156
- */
157
- /** Whatever was counted against this key is forgiven: the attempt it was guarding against succeeded. */
158
- const throttleSucceeded = (attempt) => {
159
- Promise.resolve(rateLimit({
160
- ...attempt,
161
- succeeded: true
162
- })).catch(() => void 0);
163
- };
164
- const throttled = async (attempt) => {
165
- const verdict = await rateLimit(attempt);
166
- if (typeof verdict === "boolean" ? verdict : verdict.allowed) return;
167
- const retryAfter = typeof verdict === "boolean" ? void 0 : verdict.retryAfter;
168
- return {
169
- ok: false,
170
- status: 429,
171
- body: {
172
- error: "Too many attempts",
173
- ...retryAfter !== void 0 ? { retryAfter } : {}
174
- }
175
- };
176
- };
177
- /** The one place a new password is judged, so signing up, resetting and changing cannot disagree about it. */
178
- const rejectPassword = async (value, context = {}) => {
179
- const minLength = policy.minLength ?? 8;
180
- if (value.length < minLength) return refuse(400, `The password must be at least ${minLength} characters`);
181
- const reason = await policy.validate?.(value, context);
182
- return reason ? refuse(400, reason) : void 0;
183
- };
184
- /**
185
- * What this deployment offers, decided by what it supplied and nothing else.
186
- *
187
- * There used to be a parallel set of `features` switches. They were redundant in every case — each flow reads
188
- * adapters that no other flow reads, so leaving one out is already how you decline it — and two ways of saying
189
- * the same thing invite the state where they disagree: an adapter wired up, the flag forgotten, and an endpoint
190
- * that answers 404 for no reason anyone can see. Declining a flow is now one act: do not implement it.
191
- */
192
- const capabilities = {
193
- passwordLogin: !!adapters.findByUsername,
194
- refresh: !!adapters.findByRefreshToken,
195
- signup: !!adapters.createAccount,
196
- passwordReset: !!adapters.findByEmail && !!adapters.setResetToken,
197
- emailVerification: !!adapters.findByValidationToken && !!adapters.setVerified,
198
- exchange: !!adapters.exchangeCredential,
199
- mfa: !!adapters.loadMfa && !!adapters.saveMfa,
200
- passwordless: !!adapters.saveOtp && !!adapters.findOtp && !!adapters.findByEmail && !!adapters.sendMail,
201
- profile: !!adapters.updateAccount,
202
- passwordChange: !!adapters.findById && !!adapters.setPassword,
203
- accountDeletion: !!adapters.deleteAccount,
204
- sessionList: !!adapters.listSessions,
205
- administration: !!adapters.listAccounts && !!adapters.findById,
206
- /** Changing an address by confirming it, rather than on the spot. Needs somewhere to park it and a way to write. */
207
- emailChange: !!adapters.setPendingEmail && !!adapters.findByPendingEmail && !!adapters.clearPendingEmail && !!adapters.updateAccount && !!adapters.sendMail,
208
- /** Off unless the deployment named the capability it takes — see `impersonationPermission`. */
209
- impersonation: !!impersonationPermission && !!adapters.findById
210
- };
211
- /**
212
- * An administrator acting on somebody else.
213
- *
214
- * `subject` refuses the case where that somebody is themselves. Banning or deleting your own account through the
215
- * admin surface is how a deployment loses its last administrator, and it is never what was meant: closing your
216
- * own account is the self-service flow, which asks for a password precisely because it is irreversible.
217
- */
218
- const requireAdmin = (actor, subject) => {
219
- const check = checkPermission(actor, adminPermission);
220
- if (!check.ok) return refuse(check.status, check.error, check.status === 401 ? "missing" : void 0);
221
- if (subject !== void 0 && subject === actor?.id) return refuse(400, "Use the self-service route to act on your own account");
222
- };
223
- /**
224
- * A session for this account. `options` is only for the one that is not an ordinary sign-in: a borrowed session
225
- * carries who borrowed it and cannot renew itself, so it dies at its deadline instead of quietly living for a
226
- * month behind a refresh token.
227
- */
228
- const issue = async (userId, context, options = {}) => {
229
- const { actingAs, ttlSeconds, renewable = true } = options;
230
- const now = Math.floor(Date.now() / 1e3);
231
- const session = {
232
- token: tokens.generateUserToken(userId, {
233
- actingAs,
234
- ttlSeconds
235
- }),
236
- expiresAt: now + (ttlSeconds ?? tokens.lifetimes.access),
237
- ...renewable ? {
238
- refreshToken: tokens.generateRefreshToken(userId),
239
- refreshExpiresAt: now + tokens.lifetimes.refresh
240
- } : {}
241
- };
242
- await adapters.saveSession(userId, session, context);
243
- return session;
244
- };
245
- /**
246
- * The body a grant answers with. `details` is the same object the session endpoint returns, deliberately: it makes
247
- * a grant an identity, so a client that has just signed in or renewed knows who it is without a second request.
248
- */
249
- const grantBody = async (account, session, loaded) => {
250
- const access = loaded ?? await adapters.loadAccess(account.id);
251
- const now = Math.floor(Date.now() / 1e3);
252
- return {
253
- success: true,
254
- details: {
255
- id: account.id,
256
- username: account.username,
257
- email: account.email,
258
- verified: account.verified,
259
- roles: access.roles,
260
- permissions: access.permissions
261
- },
262
- access_token: session.token,
263
- expire_in: Math.max(0, session.expiresAt - now),
264
- expire_at: session.expiresAt,
265
- refresh_token: session.refreshToken,
266
- refresh_expire_in: Math.max(0, (session.refreshExpiresAt ?? 0) - now),
267
- refresh_expire_at: session.refreshExpiresAt
268
- };
269
- };
270
- /**
271
- * Turning a credential from an external identity provider into a session here, answered in accounts.
272
- *
273
- * `offered` separates "this deployment does not do exchanges" from "that credential was refused" — a 404 and a
274
- * 401 respectively, and a caller that cannot tell them apart reports a misconfiguration as a bad password.
275
- */
276
- const exchangeAccount = async (provider, token, carrier) => {
277
- if (!capabilities.exchange) return {
278
- ok: false,
279
- offered: false,
280
- status: 404,
281
- error: "Not found"
282
- };
283
- if (!provider || !token) return {
284
- ok: false,
285
- offered: true,
286
- status: 400,
287
- error: "A provider and a token are required"
288
- };
289
- if (await throttled({
290
- action: "exchange",
291
- key: provider,
292
- carrier
293
- })) return {
294
- ok: false,
295
- offered: true,
296
- status: 429,
297
- error: "Too many attempts"
298
- };
299
- const result = await adapters.exchangeCredential?.(provider, token, carrier);
300
- if (!result) return {
301
- ok: false,
302
- offered: true,
303
- status: 401,
304
- error: "Token Invalid",
305
- reason: "revoked"
306
- };
307
- if ("error" in result) return {
308
- ok: false,
309
- offered: true,
310
- status: result.status ?? 400,
311
- error: result.error,
312
- reason: "revoked"
313
- };
314
- return {
315
- ok: true,
316
- account: result,
317
- access: await adapters.loadAccess(result.id),
318
- session: await issue(result.id, { client: clientOf(carrier) })
319
- };
320
- };
321
- return {
322
- capabilities,
323
- /** What a client reads to know which of the flows below actually exist here. */
324
- describe: () => ({
325
- ok: true,
326
- body: { features: capabilities }
327
- }),
328
- /**
329
- * Who the caller is, and until when. Reaching a resolved actor at all is the answer to "is the session alive" —
330
- * the guard refuses with a `reason` when it could not, so a client learns whether to renew or to drop to
331
- * signed-out from the refusal itself. It costs no query: the actor was resolved before routing.
332
- */
333
- session: (actor) => {
334
- if (!actor) return refuse(401, "Not authenticated", "missing");
335
- const now = Math.floor(Date.now() / 1e3);
336
- return {
337
- ok: true,
338
- body: {
339
- success: true,
340
- details: {
341
- id: actor.id,
342
- username: actor.username,
343
- email: actor.email,
344
- verified: actor.verified,
345
- roles: actor.roles,
346
- permissions: actor.permissions,
347
- ...actor.impersonatedBy === void 0 ? {} : { impersonatedBy: actor.impersonatedBy }
348
- },
349
- access_token: actor.token,
350
- expire_in: Math.max(0, actor.expiresAt - now),
351
- expire_at: actor.expiresAt
352
- }
353
- };
354
- },
355
- login: async (credentials, carrier) => {
356
- if (!capabilities.passwordLogin) return NOT_OFFERED;
357
- const username = asString(credentials.username);
358
- const password = asText(credentials.password);
359
- if (!username || !password) return refuse(400, "A username and a password are required");
360
- const limited = await throttled({
361
- action: "login",
362
- key: username,
363
- carrier
364
- });
365
- if (limited) return limited;
366
- /**
367
- * The username, or the email — in that order.
368
- *
369
- * Every sign-in screen worth using offers both, because the one thing a person reliably remembers about an
370
- * account is the address it was created with. Username first so an account whose name happens to be somebody
371
- * else's address cannot shadow the owner of that address; the email lookup only runs when the first misses,
372
- * so this costs a second query on a failed sign-in and nothing on a successful one.
373
- *
374
- * `findByEmail` is optional like everything else here: a deployment that supplies no email store keeps exactly
375
- * the behaviour it had.
376
- */
377
- const account = await adapters.findByUsername?.(username) ?? (username.includes("@") ? await adapters.findByEmail?.(username) : void 0);
378
- if (!account) return refuse(401, "Invalid credentials");
379
- if (!account.passwordHash || !await verifyPassword$1(password, account.passwordHash)) {
380
- record({
381
- type: "login.failed",
382
- userId: account.id,
383
- carrier,
384
- detail: { username }
385
- });
386
- return refuse(401, "Invalid credentials");
387
- }
388
- /**
389
- * Whether this account may hold a session — asked AFTER the password, and that order is the point.
390
- *
391
- * Anything said about an account before its password is checked is said to anybody who types an address. The
392
- * other way round, "that address has not been confirmed" once cost nothing to establish: two attempts with a
393
- * made-up password told a stranger which of a list of addresses have accounts here and which do not. It is
394
- * only a refusal somebody has earned the right to understand once they have proved the account is theirs.
395
- */
396
- if (!account.active) {
397
- const reason = deniedReason(account);
398
- return refuse(401, authFailureMessage[reason], reason);
399
- }
400
- if ((capabilities.mfa ? await adapters.loadMfa?.(account.id) : void 0)?.confirmedAt) {
401
- throttleSucceeded({
402
- action: "login",
403
- key: username,
404
- carrier
405
- });
406
- record({
407
- type: "login.mfa-required",
408
- userId: account.id,
409
- carrier
410
- });
411
- return {
412
- ok: true,
413
- body: {
414
- success: false,
415
- mfaRequired: true,
416
- mfaToken: tokens.generateMfaChallenge(account.id)
417
- }
418
- };
419
- }
420
- const session = await issue(account.id, { client: clientOf(carrier) });
421
- throttleSucceeded({
422
- action: "login",
423
- key: username,
424
- carrier
425
- });
426
- record({
427
- type: "login",
428
- userId: account.id,
429
- carrier
430
- });
431
- return {
432
- ok: true,
433
- body: await grantBody(account, session),
434
- session
435
- };
436
- },
437
- /**
438
- * The second half of a sign-in that owed a factor.
439
- *
440
- * Takes a TOTP code or a recovery code. A recovery code is SPENT — removed from the stored list — because one
441
- * that survives being used is a password with extra steps.
442
- */
443
- completeMfa: async (mfaToken, code, carrier) => {
444
- if (!capabilities.mfa) return NOT_OFFERED;
445
- const verified = tokens.verifyMfaChallenge(mfaToken);
446
- if (!verified.ok) return refuse(401, authFailureMessage[verified.reason], verified.reason);
447
- const userId = Number(verified.payload.sub);
448
- const limited = await throttled({
449
- action: "mfa",
450
- key: String(userId),
451
- carrier
452
- });
453
- if (limited) return limited;
454
- const account = await adapters.findById?.(userId);
455
- const mfa = await adapters.loadMfa?.(userId);
456
- if (!account || !mfa?.confirmedAt) return refuse(401, "Invalid credentials");
457
- if (!account.active) {
458
- const reason = deniedReason(account);
459
- return refuse(401, authFailureMessage[reason], reason);
460
- }
461
- const stored = mfa.recoveryCodes ?? [];
462
- const supplied = digestRecoveryCode(code);
463
- const usedRecovery = stored.includes(supplied);
464
- const step = usedRecovery ? void 0 : totpStep(mfa.secret, code);
465
- const replayed = step !== void 0 && mfa.lastUsedStep !== void 0 && step <= mfa.lastUsedStep;
466
- if (!usedRecovery && (step === void 0 || replayed)) {
467
- record({
468
- type: "mfa.failed",
469
- userId,
470
- carrier,
471
- ...replayed ? { detail: { replayed: true } } : {}
472
- });
473
- return refuse(401, "Invalid code");
474
- }
475
- await adapters.saveMfa?.(userId, usedRecovery ? {
476
- ...mfa,
477
- recoveryCodes: stored.filter((entry) => entry !== supplied)
478
- } : {
479
- ...mfa,
480
- lastUsedStep: step
481
- });
482
- const session = await issue(userId, { client: clientOf(carrier) });
483
- throttleSucceeded({
484
- action: "mfa",
485
- key: String(userId),
486
- carrier
487
- });
488
- record({
489
- type: "login",
490
- userId,
491
- carrier,
492
- detail: { recoveryCode: usedRecovery }
493
- });
494
- return {
495
- ok: true,
496
- body: {
497
- ...await grantBody(account, session),
498
- ...usedRecovery ? { recoveryCodeUsed: true } : {}
499
- },
500
- session
501
- };
502
- },
503
- /**
504
- * Signing in with a code sent to an email address, and no password at all.
505
- *
506
- * Two decisions worth stating. **The request answers the same whether the address exists or not** — anything
507
- * else turns this endpoint into a way to ask which addresses have accounts. And **it never creates an
508
- * account**: a sign-in flow that silently registers whoever asks is a different feature, and one a deployment
509
- * should choose deliberately rather than inherit.
510
- */
511
- passwordless: {
512
- request: async (email, carrier) => {
513
- if (!capabilities.passwordless) return NOT_OFFERED;
514
- const address = asString(email).toLowerCase();
515
- if (!address) return refuse(400, "An email is required");
516
- const limited = await throttled({
517
- action: "passwordless",
518
- key: address,
519
- carrier
520
- });
521
- if (limited) return limited;
522
- const account = await adapters.findByEmail?.(address);
523
- if (account?.active) {
524
- /**
525
- * Six characters somebody reads out of an email and types, not a link token — `generateToken` mints 128
526
- * random bits, which is right for something clicked and hostile for something retyped. Two different jobs
527
- * that were sharing one function, and the deployment that fixed the code for typing quietly weakened
528
- * every reset link it mailed.
529
- */
530
- const code = randomCode(6);
531
- await adapters.saveOtp?.({
532
- purpose: "signin",
533
- identifier: address,
534
- codeHash: digestRecoveryCode(code),
535
- expiresAt: now() + LIFETIME.signInCode,
536
- userId: account.id
537
- });
538
- await deliver({
539
- to: account.email,
540
- template: "signin-code",
541
- data: {
542
- username: account.username,
543
- code
544
- }
545
- });
546
- }
547
- return {
548
- ok: true,
549
- body: { message: "If that address has an account, a sign-in link is on its way" }
550
- };
551
- },
552
- complete: async (email, code, carrier) => {
553
- if (!capabilities.passwordless) return NOT_OFFERED;
554
- const address = asString(email).toLowerCase();
555
- if (!address || !code) return refuse(400, "An email and a code are required");
556
- const limited = await throttled({
557
- action: "passwordless",
558
- key: address,
559
- carrier
560
- });
561
- if (limited) return limited;
562
- const stored = await adapters.findOtp?.("signin", address);
563
- if (!stored || stored.expiresAt < now() || stored.codeHash !== digestRecoveryCode(code)) {
564
- record({
565
- type: "login.failed",
566
- carrier,
567
- detail: {
568
- method: "passwordless",
569
- email: address
570
- }
571
- });
572
- return refuse(401, "Invalid or expired code");
573
- }
574
- await adapters.consumeOtp?.(stored.id);
575
- const account = stored.userId === void 0 ? void 0 : await adapters.findById?.(stored.userId);
576
- if (!account?.active) {
577
- const reason = deniedReason(account);
578
- return refuse(401, authFailureMessage[reason], reason);
579
- }
580
- if ((capabilities.mfa ? await adapters.loadMfa?.(account.id) : void 0)?.confirmedAt) {
581
- record({
582
- type: "login.mfa-required",
583
- userId: account.id,
584
- carrier
585
- });
586
- return {
587
- ok: true,
588
- body: {
589
- success: false,
590
- mfaRequired: true,
591
- mfaToken: tokens.generateMfaChallenge(account.id)
592
- }
593
- };
594
- }
595
- const session = await issue(account.id, { client: clientOf(carrier) });
596
- throttleSucceeded({
597
- action: "passwordless",
598
- key: address,
599
- carrier
600
- });
601
- record({
602
- type: "login",
603
- userId: account.id,
604
- carrier,
605
- detail: { method: "passwordless" }
606
- });
607
- return {
608
- ok: true,
609
- body: await grantBody(account, session),
610
- session
611
- };
612
- }
613
- },
614
- /**
615
- * Everything about this account's second factor. `begin` hands back a secret and the URI an app scans; nothing
616
- * is in force until `confirm` proves a code from it.
617
- */
618
- mfa: {
619
- status: async (actor) => {
620
- if (!capabilities.mfa) return NOT_OFFERED;
621
- if (!actor) return refuse(401, "Not authenticated", "missing");
622
- const mfa = await adapters.loadMfa?.(actor.id);
623
- return {
624
- ok: true,
625
- body: {
626
- enabled: Boolean(mfa?.confirmedAt),
627
- pending: Boolean(mfa && !mfa.confirmedAt),
628
- recoveryCodesRemaining: mfa?.recoveryCodes?.length ?? 0
629
- }
630
- };
631
- },
632
- begin: async (actor) => {
633
- if (!capabilities.mfa) return NOT_OFFERED;
634
- if (!actor) return refuse(401, "Not authenticated", "missing");
635
- if ((await adapters.loadMfa?.(actor.id))?.confirmedAt) return refuse(409, "A second factor is already set up. Remove it before enrolling another.");
636
- const secret = generateTotpSecret();
637
- await adapters.saveMfa?.(actor.id, { secret });
638
- return {
639
- ok: true,
640
- body: {
641
- secret,
642
- uri: totpUri({
643
- secret,
644
- account: actor.email || actor.username,
645
- issuer: mfaIssuer ?? tokens.issuer
646
- })
647
- }
648
- };
649
- },
650
- /** Proves the app was actually set up, and only then does the factor start being required. */
651
- confirm: async (actor, code) => {
652
- if (!capabilities.mfa) return NOT_OFFERED;
653
- if (!actor) return refuse(401, "Not authenticated", "missing");
654
- const mfa = await adapters.loadMfa?.(actor.id);
655
- if (!mfa) return refuse(400, "Start the enrolment first");
656
- if (mfa.confirmedAt) return refuse(409, "A second factor is already set up");
657
- const step = totpStep(mfa.secret, code);
658
- if (step === void 0) {
659
- record({
660
- type: "mfa.failed",
661
- userId: actor.id
662
- });
663
- return refuse(401, "Invalid code");
664
- }
665
- const plain = generateRecoveryCodes();
666
- await adapters.saveMfa?.(actor.id, {
667
- ...mfa,
668
- confirmedAt: Math.floor(Date.now() / 1e3),
669
- recoveryCodes: plain.map(digestRecoveryCode),
670
- lastUsedStep: step
671
- });
672
- record({
673
- type: "mfa.enabled",
674
- userId: actor.id
675
- });
676
- return {
677
- ok: true,
678
- body: {
679
- success: true,
680
- recoveryCodes: plain
681
- }
682
- };
683
- },
684
- /** Removing a factor is a security downgrade, so it asks for the password the way deleting an account does. */
685
- disable: async (actor, password) => {
686
- if (!capabilities.mfa || !adapters.deleteMfa) return NOT_OFFERED;
687
- if (!actor) return refuse(401, "Not authenticated", "missing");
688
- const account = await adapters.findById?.(actor.id);
689
- if (account?.passwordHash) {
690
- if (!password || !await verifyPassword$1(password, account.passwordHash)) return refuse(401, "Invalid credentials");
691
- }
692
- await adapters.deleteMfa(actor.id);
693
- record({
694
- type: "mfa.disabled",
695
- userId: actor.id
696
- });
697
- return {
698
- ok: true,
699
- body: { success: true }
700
- };
701
- }
702
- },
703
- refresh: async (refreshToken, carrier) => {
704
- if (!capabilities.refresh) return NOT_OFFERED;
705
- if (!refreshToken) return refuse(400, "Refresh token is required");
706
- /**
707
- * Every refusal below ends the session in this browser, because each of them means the credential it just
708
- * presented can never work again: not one this deployment signed, no such row, past its deadline, or an
709
- * account that may not hold one. What is being cleared is not authority — the row is already gone — it is the
710
- * browser's reason to keep asking.
711
- *
712
- * The token carries its own deadline, so the store is asked only whether it still holds the row — the switch
713
- * that revokes it. A `refreshExpiresAt` it reports overrides that deadline, and a store that keeps none needs
714
- * to report nothing.
715
- */
716
- const lapsed = {
717
- ...refuse(401, "Invalid or expired refresh token", "expired"),
718
- endSession: true
719
- };
720
- const verified = tokens.verifyRefreshToken(refreshToken);
721
- if (!verified.ok) return lapsed;
722
- const account = await adapters.findByRefreshToken?.(refreshToken);
723
- const deadline = account?.refreshExpiresAt ?? verified.payload.exp;
724
- if (!account || account.id !== userIdOf(verified.payload) || deadline === void 0 || deadline < now()) return lapsed;
725
- if (!account.active) {
726
- const reason = deniedReason(account);
727
- return {
728
- ...refuse(401, authFailureMessage[reason], reason),
729
- endSession: true
730
- };
731
- }
732
- const cap = tokens.lifetimes.session;
733
- if (cap > 0 && account.sessionStartedAt !== void 0 && account.sessionStartedAt + cap < now()) {
734
- await adapters.clearSession({ refreshToken });
735
- return {
736
- ...refuse(401, "This session has reached its maximum lifetime", "expired"),
737
- endSession: true
738
- };
739
- }
740
- const session = await issue(account.id, {
741
- replaces: { refreshToken },
742
- client: clientOf(carrier)
743
- });
744
- return {
745
- ok: true,
746
- body: await grantBody(account, session),
747
- session
748
- };
749
- },
750
- /** Reachable with an expired access token on purpose, or a live refresh token could never be revoked. */
751
- logout: async (credentials) => {
752
- if (credentials.accessToken || credentials.refreshToken) await adapters.clearSession(credentials);
753
- return {
754
- ok: true,
755
- body: { message: "Logged out successfully" },
756
- endSession: true
757
- };
758
- },
759
- /**
760
- * Ends this account's session everywhere, for the case where one leaked. Unlike logout it is authenticated and
761
- * works by account id, so it can be used from a device that still has a good session while the stolen copy is
762
- * somewhere else entirely.
763
- */
764
- revokeSessions: async (userId) => {
765
- if (!userId) return refuse(401, "Not authenticated", "missing");
766
- await adapters.clearSession({ userId });
767
- return {
768
- ok: true,
769
- body: { message: "All sessions revoked" },
770
- endSession: true
771
- };
772
- },
773
- exchange: async (provider, token, carrier) => {
774
- const result = await exchangeAccount(provider, token, carrier);
775
- if (!result.ok) return result.offered ? refuse(result.status, result.error, result.reason) : NOT_OFFERED;
776
- const { account, access, session } = result;
777
- return {
778
- ok: true,
779
- body: await grantBody(account, session, access),
780
- session
781
- };
782
- },
783
- /**
784
- * The same exchange, answering in accounts rather than in HTTP.
785
- *
786
- * A page server needs who came back and the session they got; the flow above needs a body and a status. They
787
- * are the same act, and the translation between them has one correct answer — so it is made once, here, rather
788
- * than by every deployment that wires an external identity provider into a rendered page.
789
- */
790
- exchangeAccount,
791
- signup: async (fields) => {
792
- if (!capabilities.signup) return NOT_OFFERED;
793
- const username = asString(fields.username);
794
- const email = asString(fields.email);
795
- const password = asText(fields.password);
796
- if (!username || !email || !password) return refuse(400, "A username, an email and a password are required");
797
- const weak = await rejectPassword(password, {
798
- username,
799
- email
800
- });
801
- if (weak) return weak;
802
- const limited = await throttled({
803
- action: "signup",
804
- key: email
805
- });
806
- if (limited) return limited;
807
- if (await adapters.findByUsername?.(username) ?? await adapters.findByEmail?.(email)) return refuse(400, "User already exists");
808
- if (!adapters.createAccount) return NOT_OFFERED;
809
- const account = await adapters.createAccount({
810
- username,
811
- email,
812
- passwordHash: await hashPassword$1(password)
813
- });
814
- if (!verifyOnSignup && capabilities.emailVerification && adapters.setValidationToken) {
815
- const validationToken = mintLink(generateToken$1(), LIFETIME.confirmLink);
816
- await adapters.setValidationToken(account.id, validationToken);
817
- await deliver({
818
- to: email,
819
- template: "validation",
820
- data: {
821
- username,
822
- validationToken,
823
- ...destinationOf(fields.redirect)
824
- }
825
- });
826
- }
827
- record({
828
- type: "signup",
829
- userId: account.id
830
- });
831
- return {
832
- ok: true,
833
- status: 201,
834
- body: {
835
- message: "User created successfully",
836
- userId: account.id
837
- }
838
- };
839
- },
840
- /** Answers the same either way: whether an address has an account here is not something a stranger may probe. */
841
- forgotPassword: async (email) => {
842
- if (!capabilities.passwordReset) return NOT_OFFERED;
843
- const limited = await throttled({
844
- action: "forgotPassword",
845
- key: asString(email)
846
- });
847
- if (limited) return limited;
848
- const account = await adapters.findByEmail?.(asString(email));
849
- if (account) {
850
- const resetToken = mintLink(generateToken$1(), LIFETIME.resetLink);
851
- await adapters.setResetToken?.(account.id, resetToken);
852
- await deliver({
853
- to: account.email,
854
- template: "password-reset",
855
- data: {
856
- username: account.username,
857
- resetToken
858
- }
859
- });
860
- }
861
- return {
862
- ok: true,
863
- body: { message: "Password reset email sent" }
864
- };
865
- },
866
- resetPassword: async (token, password) => {
867
- if (!capabilities.passwordReset) return NOT_OFFERED;
868
- if (!token || !password) return refuse(400, "A token and a password are required");
869
- const limited = await throttled({
870
- action: "resetPassword",
871
- key: token
872
- });
873
- if (limited) return limited;
874
- const account = linkExpired(token) ? void 0 : await adapters.findByResetToken?.(token);
875
- if (!account) return refuse(400, "Invalid or expired token");
876
- const weak = await rejectPassword(password, {
877
- username: account.username,
878
- email: account.email
879
- });
880
- if (weak) return weak;
881
- await adapters.setPassword?.(account.id, await hashPassword$1(password));
882
- await adapters.setResetToken?.(account.id, "");
883
- await adapters.clearSession({ userId: account.id });
884
- record({
885
- type: "password.reset",
886
- userId: account.id
887
- });
888
- return {
889
- ok: true,
890
- body: { message: "Password reset successfully" },
891
- endSession: true
892
- };
893
- },
894
- validateAccount: async (token) => {
895
- if (!capabilities.emailVerification) return NOT_OFFERED;
896
- const account = linkExpired(token) ? void 0 : await adapters.findByValidationToken?.(token);
897
- if (!account) return refuse(400, "Invalid or expired token");
898
- await adapters.setVerified?.(account.id, true);
899
- return {
900
- ok: true,
901
- body: { message: "Account validated successfully" }
902
- };
903
- },
904
- resendVerification: async (email, redirect) => {
905
- if (!capabilities.emailVerification) return NOT_OFFERED;
906
- const account = await adapters.findByEmail?.(asString(email));
907
- if (account && !account.verified) {
908
- const validationToken = mintLink(generateToken$1(), LIFETIME.confirmLink);
909
- await adapters.setValidationToken?.(account.id, validationToken);
910
- await deliver({
911
- to: account.email,
912
- template: "validation",
913
- data: {
914
- username: account.username,
915
- validationToken,
916
- ...destinationOf(redirect)
917
- }
918
- });
919
- }
920
- return {
921
- ok: true,
922
- body: { message: "Verification email resent" }
923
- };
924
- },
925
- /**
926
- * Change what an account says about itself.
927
- *
928
- * Both fields are sign-in identifiers, so both are checked for collision first — a store that only has a unique
929
- * index reports the clash as a driver error five hundred lines away.
930
- */
931
- updateProfile: async (actor, fields) => {
932
- if (!capabilities.profile || !adapters.updateAccount) return NOT_OFFERED;
933
- if (!actor) return refuse(401, "Not authenticated", "missing");
934
- const username = asString(fields.username);
935
- const email = asString(fields.email);
936
- if (!username && !email) return refuse(400, "Nothing to change");
937
- if (username && username !== actor.username) {
938
- const taken = await adapters.findByUsername?.(username);
939
- if (taken && taken.id !== actor.id) return refuse(409, "That username is taken");
940
- }
941
- if (email && email !== actor.email) {
942
- const taken = await adapters.findByEmail?.(email);
943
- if (taken && taken.id !== actor.id) return refuse(409, "That email is taken");
944
- }
945
- const changingEmail = Boolean(email) && email !== actor.email;
946
- /**
947
- * A new address is PARKED, not applied: the account keeps the one it has until the new one answers a
948
- * confirmation. That is what makes a typo survivable — `n@exmaple.com` costs a resend, not the account.
949
- *
950
- * The alternative, applying it and taking `verified` away, was tried and reverted: `verified` in this server
951
- * gates ACCESS (`createAuthorizer` refuses to present an unverified account as an actor at all), so it locked
952
- * people out of the account they were sitting in. And the attack it guarded against needs a live session,
953
- * from which the same person could simply change the password.
954
- *
955
- * A deployment that supplies nowhere to park it changes the address on the spot, as it always did.
956
- */
957
- const parking = changingEmail && capabilities.emailChange;
958
- const account = await adapters.updateAccount(actor.id, {
959
- ...username ? { username } : {},
960
- ...email && !parking ? { email } : {}
961
- });
962
- if (parking && adapters.setPendingEmail) {
963
- const confirmationToken = mintLink(generateToken$1(), LIFETIME.confirmLink);
964
- await adapters.setPendingEmail(actor.id, email, confirmationToken);
965
- await deliver({
966
- to: email,
967
- template: "email-change",
968
- data: {
969
- username: account.username,
970
- email,
971
- confirmationToken
972
- }
973
- });
974
- return {
975
- ok: true,
976
- body: {
977
- success: true,
978
- details: profileOf(account),
979
- pendingEmail: email,
980
- message: "A confirmation was sent to the new address. It takes effect once confirmed."
981
- }
982
- };
983
- }
984
- if (changingEmail && capabilities.emailVerification && adapters.setValidationToken) {
985
- const validationToken = mintLink(generateToken$1(), LIFETIME.confirmLink);
986
- await adapters.setValidationToken(actor.id, validationToken);
987
- await deliver({
988
- to: account.email,
989
- template: "validation",
990
- data: {
991
- username: account.username,
992
- validationToken
993
- }
994
- });
995
- return {
996
- ok: true,
997
- body: {
998
- success: true,
999
- details: profileOf(account),
1000
- message: "A confirmation was sent to the new address"
1001
- }
1002
- };
1003
- }
1004
- return {
1005
- ok: true,
1006
- body: {
1007
- success: true,
1008
- details: profileOf(account)
1009
- }
1010
- };
1011
- },
1012
- /**
1013
- * Takes the parked address, having proved somebody reads it.
1014
- *
1015
- * Public, and it has to be: the link is opened from a mail client, in whatever browser that happens to be, with
1016
- * no session. The token is the whole credential — which is why it is single-use and why confirming also marks
1017
- * the account verified: an address that answered a link is an address that was proven.
1018
- */
1019
- confirmEmailChange: async (token) => {
1020
- if (!capabilities.emailChange || !adapters.findByPendingEmail || !adapters.clearPendingEmail) return NOT_OFFERED;
1021
- const confirmation = asString(token);
1022
- const pending = linkExpired(confirmation) ? void 0 : await adapters.findByPendingEmail(confirmation);
1023
- if (!pending) return refuse(400, "Invalid or expired token");
1024
- const taken = await adapters.findByEmail?.(pending.email);
1025
- if (taken && taken.id !== pending.account.id) {
1026
- await adapters.clearPendingEmail(pending.account.id);
1027
- return refuse(409, "That email is taken");
1028
- }
1029
- const account = await adapters.updateAccount?.(pending.account.id, { email: pending.email });
1030
- await adapters.clearPendingEmail(pending.account.id);
1031
- if (adapters.setVerified) await adapters.setVerified(pending.account.id, true);
1032
- record({
1033
- type: "email.changed",
1034
- userId: pending.account.id,
1035
- detail: { email: pending.email }
1036
- });
1037
- const confirmed = {
1038
- ...account ?? pending.account,
1039
- email: pending.email
1040
- };
1041
- return {
1042
- ok: true,
1043
- body: {
1044
- success: true,
1045
- details: profileOf(adapters.setVerified ? {
1046
- ...confirmed,
1047
- verified: true
1048
- } : confirmed)
1049
- }
1050
- };
1051
- },
1052
- /**
1053
- * Change a password, having proved you know the current one.
1054
- *
1055
- * Then **every other session ends**. Changing a password is what somebody does when they think a credential
1056
- * escaped, and one that leaves the other sessions signed in has not done the thing they asked for. The session
1057
- * making the change survives, or the act of securing the account would sign them out of it.
1058
- */
1059
- changePassword: async (actor, currentPassword, newPassword) => {
1060
- if (!capabilities.passwordChange || !adapters.findById) return NOT_OFFERED;
1061
- if (!actor) return refuse(401, "Not authenticated", "missing");
1062
- if (!currentPassword || !newPassword) return refuse(400, "The current and the new password are required");
1063
- const weak = await rejectPassword(newPassword, {
1064
- username: actor.username,
1065
- email: actor.email
1066
- });
1067
- if (weak) return weak;
1068
- const limited = await throttled({
1069
- action: "changePassword",
1070
- key: String(actor.id)
1071
- });
1072
- if (limited) return limited;
1073
- const account = await adapters.findById(actor.id);
1074
- if (!account?.passwordHash || !await verifyPassword$1(currentPassword, account.passwordHash)) return refuse(401, "Invalid credentials");
1075
- await adapters.setPassword?.(actor.id, await hashPassword$1(newPassword));
1076
- await adapters.revokeOtherSessions?.(actor.id, actor.token);
1077
- throttleSucceeded({
1078
- action: "changePassword",
1079
- key: String(actor.id)
1080
- });
1081
- record({
1082
- type: "password.changed",
1083
- userId: actor.id
1084
- });
1085
- return {
1086
- ok: true,
1087
- body: {
1088
- success: true,
1089
- message: "Password changed. Other sessions were signed out."
1090
- }
1091
- };
1092
- },
1093
- /**
1094
- * Close the account.
1095
- *
1096
- * Confirmed with the password when there is one — this is irreversible, and a borrowed session should not be
1097
- * able to do it. An account with no password (one that signs in through a provider) cannot be asked, so the
1098
- * session alone has to be enough.
1099
- */
1100
- deleteSelf: async (actor, password) => {
1101
- if (!capabilities.accountDeletion || !adapters.deleteAccount) return NOT_OFFERED;
1102
- if (!actor) return refuse(401, "Not authenticated", "missing");
1103
- const account = await adapters.findById?.(actor.id);
1104
- if (account?.passwordHash) {
1105
- if (!password || !await verifyPassword$1(password, account.passwordHash)) return refuse(401, "Invalid credentials");
1106
- }
1107
- const blockers = await adapters.deletionBlockers?.(actor.id) ?? [];
1108
- if (blockers.length > 0) return {
1109
- ok: false,
1110
- status: 409,
1111
- body: {
1112
- error: "This account still owns things that would be lost with it",
1113
- blockers
1114
- }
1115
- };
1116
- await adapters.deleteAccount(actor.id);
1117
- record({
1118
- type: "account.deleted",
1119
- userId: actor.id
1120
- });
1121
- return {
1122
- ok: true,
1123
- body: {
1124
- success: true,
1125
- message: "Account deleted"
1126
- },
1127
- endSession: true
1128
- };
1129
- },
1130
- /** The devices this account is signed in on, with the one asking marked. */
1131
- listSessions: async (actor) => {
1132
- if (!capabilities.sessionList || !adapters.listSessions) return NOT_OFFERED;
1133
- if (!actor) return refuse(401, "Not authenticated", "missing");
1134
- return {
1135
- ok: true,
1136
- body: { sessions: await adapters.listSessions(actor.id, actor.token) }
1137
- };
1138
- },
1139
- /** End one of them. Scoped to the caller's own account, or a session id would be an IDOR. */
1140
- revokeSession: async (actor, sessionId) => {
1141
- if (!adapters.revokeSession) return NOT_OFFERED;
1142
- if (!actor) return refuse(401, "Not authenticated", "missing");
1143
- if (!Number.isInteger(sessionId)) return refuse(400, "A session id is required");
1144
- return await adapters.revokeSession(actor.id, sessionId) ? {
1145
- ok: true,
1146
- body: { success: true }
1147
- } : refuse(404, "No such session");
1148
- },
1149
- /** "Sign out everywhere else" — the thing to do from a device you still hold after losing one you do not. */
1150
- revokeOtherSessions: async (actor) => {
1151
- if (!adapters.revokeOtherSessions) return NOT_OFFERED;
1152
- if (!actor) return refuse(401, "Not authenticated", "missing");
1153
- return {
1154
- ok: true,
1155
- body: {
1156
- success: true,
1157
- revoked: await adapters.revokeOtherSessions(actor.id, actor.token)
1158
- }
1159
- };
1160
- },
1161
- admin: {
1162
- list: async (actor, query) => {
1163
- const denial = requireAdmin(actor);
1164
- if (denial) return denial;
1165
- if (!adapters.listAccounts) return NOT_OFFERED;
1166
- const { accounts, total } = await adapters.listAccounts(query);
1167
- return {
1168
- ok: true,
1169
- body: {
1170
- accounts: accounts.map(profileOf),
1171
- total
1172
- }
1173
- };
1174
- },
1175
- get: async (actor, userId) => {
1176
- const denial = requireAdmin(actor);
1177
- if (denial) return denial;
1178
- const account = await adapters.findById?.(userId);
1179
- if (!account) return refuse(404, "No such account");
1180
- return {
1181
- ok: true,
1182
- body: {
1183
- account: profileOf(account),
1184
- access: await adapters.loadAccess(userId)
1185
- }
1186
- };
1187
- },
1188
- /**
1189
- * Suspend, block or restore an account — and **end its sessions when it stops being active**.
1190
- *
1191
- * That second half is the whole point. A ban that leaves the credential working is not a ban, it is a note
1192
- * in a database; the person stays signed in until their token happens to lapse.
1193
- */
1194
- setStatus: async (actor, userId, status) => {
1195
- const denial = requireAdmin(actor, userId);
1196
- if (denial) return denial;
1197
- if (!adapters.setStatus) return NOT_OFFERED;
1198
- if (!STATUSES.includes(status)) return refuse(400, `Status must be one of ${STATUSES.join(", ")}`);
1199
- if (!await adapters.findById?.(userId)) return refuse(404, "No such account");
1200
- await adapters.setStatus(userId, status);
1201
- if (status !== "active") await adapters.clearSession({ userId });
1202
- record({
1203
- type: "admin.status-changed",
1204
- userId,
1205
- actorId: actor?.id,
1206
- detail: { status }
1207
- });
1208
- return {
1209
- ok: true,
1210
- body: {
1211
- success: true,
1212
- status
1213
- }
1214
- };
1215
- },
1216
- setRoles: async (actor, userId, roles) => {
1217
- const denial = requireAdmin(actor);
1218
- if (denial) return denial;
1219
- if (!adapters.setRoles) return NOT_OFFERED;
1220
- if (!Array.isArray(roles) || roles.some((role) => typeof role !== "string")) return refuse(400, "Roles must be a list of names");
1221
- const names = roles;
1222
- if (!await adapters.findById?.(userId)) return refuse(404, "No such account");
1223
- await adapters.setRoles(userId, names);
1224
- record({
1225
- type: "admin.roles-changed",
1226
- userId,
1227
- actorId: actor?.id,
1228
- detail: { roles: names }
1229
- });
1230
- return {
1231
- ok: true,
1232
- body: {
1233
- success: true,
1234
- roles: names
1235
- }
1236
- };
1237
- },
1238
- remove: async (actor, userId) => {
1239
- const denial = requireAdmin(actor, userId);
1240
- if (denial) return denial;
1241
- if (!adapters.deleteAccount) return NOT_OFFERED;
1242
- if (!await adapters.findById?.(userId)) return refuse(404, "No such account");
1243
- await adapters.deleteAccount(userId);
1244
- record({
1245
- type: "admin.account-deleted",
1246
- userId,
1247
- actorId: actor?.id
1248
- });
1249
- return {
1250
- ok: true,
1251
- body: { success: true }
1252
- };
1253
- },
1254
- /**
1255
- * A session AS somebody else, for support that has to see what they see.
1256
- *
1257
- * Three properties make it something a deployment can live with, and all three are deliberate:
1258
- *
1259
- * - **It says so.** The credential carries `act` (RFC 8693), so every request made with it can be told from
1260
- * one the account holder made — `Actor.impersonatedBy` is that claim, read back. A borrowed session that
1261
- * is indistinguishable from a real one turns an audit log into fiction.
1262
- * - **It is short and cannot renew.** Fifteen minutes by default and no refresh token, so it expires rather
1263
- * than becoming a permanent second key to somebody's account.
1264
- * - **It is off unless asked for**, behind its own permission — see `impersonationPermission`.
1265
- *
1266
- * The session is answered in the BODY and no cookie is written. Swapping the administrator's own session
1267
- * cookie for this one would sign them out of the account they administer from, and getting back would mean
1268
- * signing in again; whoever asked decides where to put a credential they were handed.
1269
- *
1270
- * One caveat a deployment has to know: a store that keeps a single session per account — no `session` table —
1271
- * will overwrite the subject's own session with this one, signing them out. Anything with per-session rows,
1272
- * which is what `createMysqlStore` builds, does not.
1273
- */
1274
- impersonate: async (actor, userId, carrier) => {
1275
- if (!capabilities.impersonation || !impersonationPermission || !adapters.findById) return NOT_OFFERED;
1276
- const check = checkPermission(actor, impersonationPermission);
1277
- if (!check.ok) return refuse(check.status, check.error, check.status === 401 ? "missing" : void 0);
1278
- if (!actor || userId === actor.id) return refuse(400, "You are already signed in as yourself");
1279
- const account = await adapters.findById(userId);
1280
- if (!account) return refuse(404, "No such account");
1281
- if (!account.active) return refuse(403, "That account is not active");
1282
- const session = await issue(userId, { client: clientOf(carrier) }, {
1283
- actingAs: actor.id,
1284
- ttlSeconds: LIFETIME.impersonation,
1285
- renewable: false
1286
- });
1287
- record({
1288
- type: "admin.impersonated",
1289
- userId,
1290
- actorId: actor.id
1291
- });
1292
- return {
1293
- ok: true,
1294
- body: {
1295
- ...await grantBody(account, session),
1296
- impersonatedBy: actor.id
1297
- }
1298
- };
1299
- }
1300
- },
1301
- /**
1302
- * A CSRF token for whoever is asking, bound to their session when they have one. Answered as a body AND as the
1303
- * cookie the binding writes, so a page can take whichever it finds easier to read.
1304
- */
1305
- issueCsrf: (sessionToken) => {
1306
- if (!csrf) return NOT_OFFERED;
1307
- const token = csrf.issue(sessionToken);
1308
- return {
1309
- ok: true,
1310
- body: {
1311
- token,
1312
- headerName: csrf.headerName
1313
- },
1314
- csrf: token
1315
- };
1316
- },
1317
- /** Exposed so a deployment can mint a session outside the flows above — a rendered page's login form. */
1318
- issueSession: issue,
1319
- resolveActor: identity.resolveActor
1320
- };
1321
- };
1322
- //#endregion
1323
- export { createAuthApi };