@plitzi/sdk-server 0.38.24 → 0.39.1

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 +162 -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 +69 -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 +18 -1
  77. package/dist/hosts/project/serveProject.js +89 -25
  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 +16 -0
  125. package/dist/modules/functions/context.js +6 -2
  126. package/dist/modules/functions/contract.d.ts +39 -1
  127. package/dist/modules/functions/driver.d.ts +2 -1
  128. package/dist/modules/functions/driver.js +35 -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 +1 -1
  133. package/dist/modules/functions/oauth.js +4 -4
  134. package/dist/modules/functions/protocol.d.ts +6 -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 +31 -8
  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 +10 -2
  213. package/skills/plitzi-authoring/reference/auth.md +15 -4
  214. package/skills/plitzi-authoring/reference/authoring-errors.md +55 -12
  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 +29 -17
  221. package/skills/plitzi-authoring/reference/kept-state.md +20 -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 +17 -3
  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
@@ -0,0 +1,209 @@
1
+ import { LIFETIME, NOT_OFFERED, asString, clientOf, deniedReason, now, refuse } from "./values.js";
2
+ import { generateRecoveryCodes, generateTotpSecret, randomCode, totpStep, totpUri } from "../totp.js";
3
+ import { authFailureMessage } from "../tokens.js";
4
+ //#region src/core/auth/api/factors.ts
5
+ /** The ways in besides a password: a code or a link by email (`passwordless`), and the second factor (`mfa`). */
6
+ var factorsFlows = ({ tokens, adapters, verifyPassword, mfaIssuer, record, digestRecoveryCode, deliver, throttleSucceeded, throttled, capabilities, issue, grantBody }) => ({
7
+ /**
8
+ * Signing in with a code sent to an email address, and no password at all.
9
+ *
10
+ * Two decisions worth stating. **The request answers the same whether the address exists or not** — anything
11
+ * else turns this endpoint into a way to ask which addresses have accounts. And **it never creates an
12
+ * account**: a sign-in flow that silently registers whoever asks is a different feature, and one a deployment
13
+ * should choose deliberately rather than inherit.
14
+ */
15
+ passwordless: {
16
+ request: async (email, carrier) => {
17
+ if (!capabilities.passwordless) return NOT_OFFERED;
18
+ const address = asString(email).toLowerCase();
19
+ if (!address) return refuse(400, "An email is required");
20
+ const limited = await throttled({
21
+ action: "passwordless",
22
+ key: address,
23
+ carrier
24
+ });
25
+ if (limited) return limited;
26
+ const account = await adapters.findByEmail?.(address);
27
+ if (account?.active) {
28
+ /**
29
+ * Six characters somebody reads out of an email and types, not a link token — `generateToken` mints 128
30
+ * random bits, which is right for something clicked and hostile for something retyped. Two different jobs
31
+ * that were sharing one function, and the deployment that fixed the code for typing quietly weakened
32
+ * every reset link it mailed.
33
+ */
34
+ const code = randomCode(6);
35
+ await adapters.saveOtp?.({
36
+ purpose: "signin",
37
+ identifier: address,
38
+ codeHash: digestRecoveryCode(code),
39
+ expiresAt: now() + LIFETIME.signInCode,
40
+ userId: account.id
41
+ });
42
+ await deliver({
43
+ to: account.email,
44
+ template: "signin-code",
45
+ data: {
46
+ username: account.username,
47
+ code
48
+ }
49
+ });
50
+ }
51
+ return {
52
+ ok: true,
53
+ body: { message: "If that address has an account, a sign-in link is on its way" }
54
+ };
55
+ },
56
+ complete: async (email, code, carrier) => {
57
+ if (!capabilities.passwordless) return NOT_OFFERED;
58
+ const address = asString(email).toLowerCase();
59
+ if (!address || !code) return refuse(400, "An email and a code are required");
60
+ const limited = await throttled({
61
+ action: "passwordless",
62
+ key: address,
63
+ carrier
64
+ });
65
+ if (limited) return limited;
66
+ const stored = await adapters.findOtp?.("signin", address);
67
+ if (!stored || stored.expiresAt < now() || stored.codeHash !== digestRecoveryCode(code)) {
68
+ record({
69
+ type: "login.failed",
70
+ carrier,
71
+ detail: {
72
+ method: "passwordless",
73
+ email: address
74
+ }
75
+ });
76
+ return refuse(401, "Invalid or expired code");
77
+ }
78
+ await adapters.consumeOtp?.(stored.id);
79
+ const account = stored.userId === void 0 ? void 0 : await adapters.findById?.(stored.userId);
80
+ if (!account?.active) {
81
+ const reason = deniedReason(account);
82
+ return refuse(401, authFailureMessage[reason], reason);
83
+ }
84
+ if ((capabilities.mfa ? await adapters.loadMfa?.(account.id) : void 0)?.confirmedAt) {
85
+ record({
86
+ type: "login.mfa-required",
87
+ userId: account.id,
88
+ carrier
89
+ });
90
+ return {
91
+ ok: true,
92
+ body: {
93
+ success: false,
94
+ mfaRequired: true,
95
+ mfaToken: tokens.generateMfaChallenge(account.id)
96
+ }
97
+ };
98
+ }
99
+ const session = await issue(account.id, { client: clientOf(carrier) });
100
+ throttleSucceeded({
101
+ action: "passwordless",
102
+ key: address,
103
+ carrier
104
+ });
105
+ record({
106
+ type: "login",
107
+ userId: account.id,
108
+ carrier,
109
+ detail: { method: "passwordless" }
110
+ });
111
+ return {
112
+ ok: true,
113
+ body: await grantBody(account, session),
114
+ session
115
+ };
116
+ }
117
+ },
118
+ /**
119
+ * Everything about this account's second factor. `begin` hands back a secret and the URI an app scans; nothing
120
+ * is in force until `confirm` proves a code from it.
121
+ */
122
+ mfa: {
123
+ status: async (actor) => {
124
+ if (!capabilities.mfa) return NOT_OFFERED;
125
+ if (!actor) return refuse(401, "Not authenticated", "missing");
126
+ const mfa = await adapters.loadMfa?.(actor.id);
127
+ return {
128
+ ok: true,
129
+ body: {
130
+ enabled: Boolean(mfa?.confirmedAt),
131
+ pending: Boolean(mfa && !mfa.confirmedAt),
132
+ recoveryCodesRemaining: mfa?.recoveryCodes?.length ?? 0
133
+ }
134
+ };
135
+ },
136
+ begin: async (actor) => {
137
+ if (!capabilities.mfa) return NOT_OFFERED;
138
+ if (!actor) return refuse(401, "Not authenticated", "missing");
139
+ if ((await adapters.loadMfa?.(actor.id))?.confirmedAt) return refuse(409, "A second factor is already set up. Remove it before enrolling another.");
140
+ const secret = generateTotpSecret();
141
+ await adapters.saveMfa?.(actor.id, { secret });
142
+ return {
143
+ ok: true,
144
+ body: {
145
+ secret,
146
+ uri: totpUri({
147
+ secret,
148
+ account: actor.email || actor.username,
149
+ issuer: mfaIssuer ?? tokens.issuer
150
+ })
151
+ }
152
+ };
153
+ },
154
+ /** Proves the app was actually set up, and only then does the factor start being required. */
155
+ confirm: async (actor, code) => {
156
+ if (!capabilities.mfa) return NOT_OFFERED;
157
+ if (!actor) return refuse(401, "Not authenticated", "missing");
158
+ const mfa = await adapters.loadMfa?.(actor.id);
159
+ if (!mfa) return refuse(400, "Start the enrolment first");
160
+ if (mfa.confirmedAt) return refuse(409, "A second factor is already set up");
161
+ const step = totpStep(mfa.secret, code);
162
+ if (step === void 0) {
163
+ record({
164
+ type: "mfa.failed",
165
+ userId: actor.id
166
+ });
167
+ return refuse(401, "Invalid code");
168
+ }
169
+ const plain = generateRecoveryCodes();
170
+ await adapters.saveMfa?.(actor.id, {
171
+ ...mfa,
172
+ confirmedAt: Math.floor(Date.now() / 1e3),
173
+ recoveryCodes: plain.map(digestRecoveryCode),
174
+ lastUsedStep: step
175
+ });
176
+ record({
177
+ type: "mfa.enabled",
178
+ userId: actor.id
179
+ });
180
+ return {
181
+ ok: true,
182
+ body: {
183
+ success: true,
184
+ recoveryCodes: plain
185
+ }
186
+ };
187
+ },
188
+ /** Removing a factor is a security downgrade, so it asks for the password the way deleting an account does. */
189
+ disable: async (actor, password) => {
190
+ if (!capabilities.mfa || !adapters.deleteMfa) return NOT_OFFERED;
191
+ if (!actor) return refuse(401, "Not authenticated", "missing");
192
+ const account = await adapters.findById?.(actor.id);
193
+ if (account?.passwordHash) {
194
+ if (!password || !await verifyPassword(password, account.passwordHash)) return refuse(401, "Invalid credentials");
195
+ }
196
+ await adapters.deleteMfa(actor.id);
197
+ record({
198
+ type: "mfa.disabled",
199
+ userId: actor.id
200
+ });
201
+ return {
202
+ ok: true,
203
+ body: { success: true }
204
+ };
205
+ }
206
+ }
207
+ });
208
+ //#endregion
209
+ export { factorsFlows };
@@ -0,0 +1,94 @@
1
+ import { Identity } from '../identity';
2
+ import { Tokens } from '../tokens';
3
+ import { AccountAdapters, AuthApiConfig } from './types';
4
+ export type * from './types';
5
+ /**
6
+ * The HTTP surface of authentication, as functions rather than routes.
7
+ *
8
+ * Nothing here knows about Express, or about this server's own pipeline: a handler is given what the request
9
+ * carried and answers what should be sent, including whether the session cookies should be written or cleared. The
10
+ * binding does the rest, which is what lets the same login live behind an API endpoint and behind a rendered page's
11
+ * form without either owning it.
12
+ */
13
+ export declare const createAuthApi: ({ tokens, identity, adapters, config }: {
14
+ tokens: Tokens;
15
+ identity: Identity;
16
+ adapters: AccountAdapters;
17
+ config?: AuthApiConfig;
18
+ }) => {
19
+ /**
20
+ * The same exchange, answering in accounts rather than in HTTP.
21
+ *
22
+ * A page server needs who came back and the session they got; the flow above needs a body and a status. They
23
+ * are the same act, and the translation between them has one correct answer — so it is made once, here, rather
24
+ * than by every deployment that wires an external identity provider into a rendered page.
25
+ */
26
+ exchangeAccount: (provider: string, token: string, carrier: import('../credentials').CredentialCarrier) => Promise<import('./types').ExchangeResult>;
27
+ /** Exposed so a deployment can mint a session outside the flows above — a rendered page's login form. */
28
+ issueSession: (userId: number, context?: import('./types').SessionContext, options?: {
29
+ actingAs?: number;
30
+ ttlSeconds?: number;
31
+ renewable?: boolean;
32
+ }) => Promise<import('@plitzi/sdk-shared').SSRSession>;
33
+ resolveActor: (carrier: import('../credentials').CredentialCarrier) => Promise<import('../identity').ActorResult>;
34
+ admin: {
35
+ list: (actor: import('../identity').Actor | undefined, query: import('./types').AccountQuery) => Promise<import('./types').AuthOutcome>;
36
+ get: (actor: import('../identity').Actor | undefined, userId: number) => Promise<import('./types').AuthOutcome>;
37
+ setStatus: (actor: import('../identity').Actor | undefined, userId: number, status: import('./types').AccountStatus) => Promise<import('./types').AuthOutcome>;
38
+ setRoles: (actor: import('../identity').Actor | undefined, userId: number, roles: unknown) => Promise<import('./types').AuthOutcome>;
39
+ remove: (actor: import('../identity').Actor | undefined, userId: number) => Promise<import('./types').AuthOutcome>;
40
+ impersonate: (actor: import('../identity').Actor | undefined, userId: number, carrier?: import('../credentials').CredentialCarrier) => Promise<import('./types').AuthOutcome>;
41
+ };
42
+ updateProfile: (actor: import('../identity').Actor | undefined, fields: Record<string, unknown>) => Promise<import('./types').AuthOutcome>;
43
+ confirmEmailChange: (token: string) => Promise<import('./types').AuthOutcome>;
44
+ changePassword: (actor: import('../identity').Actor | undefined, currentPassword: string, newPassword: string) => Promise<import('./types').AuthOutcome>;
45
+ deleteSelf: (actor: import('../identity').Actor | undefined, password?: string) => Promise<import('./types').AuthOutcome>;
46
+ listSessions: (actor: import('../identity').Actor | undefined) => Promise<import('./types').AuthOutcome>;
47
+ revokeSession: (actor: import('../identity').Actor | undefined, sessionId: number) => Promise<import('./types').AuthOutcome>;
48
+ revokeOtherSessions: (actor: import('../identity').Actor | undefined) => Promise<import('./types').AuthOutcome>;
49
+ signup: (fields: Record<string, unknown>) => Promise<import('./types').AuthOutcome>;
50
+ forgotPassword: (email: string) => Promise<import('./types').AuthOutcome>;
51
+ resetPassword: (token: string, password: string) => Promise<import('./types').AuthOutcome>;
52
+ validateAccount: (token: string) => Promise<import('./types').AuthOutcome>;
53
+ resendVerification: (email: string, redirect?: string) => Promise<import('./types').AuthOutcome>;
54
+ passwordless: {
55
+ request: (email: string, carrier?: import('../credentials').CredentialCarrier) => Promise<import('./types').AuthOutcome>;
56
+ complete: (email: string, code: string, carrier?: import('../credentials').CredentialCarrier) => Promise<import('./types').AuthOutcome>;
57
+ };
58
+ mfa: {
59
+ status: (actor: import('../identity').Actor | undefined) => Promise<import('./types').AuthOutcome>;
60
+ begin: (actor: import('../identity').Actor | undefined) => Promise<import('./types').AuthOutcome>;
61
+ confirm: (actor: import('../identity').Actor | undefined, code: string) => Promise<import('./types').AuthOutcome>;
62
+ disable: (actor: import('../identity').Actor | undefined, password?: string) => Promise<import('./types').AuthOutcome>;
63
+ };
64
+ capabilities: {
65
+ passwordLogin: boolean;
66
+ refresh: boolean;
67
+ signup: boolean;
68
+ passwordReset: boolean;
69
+ emailVerification: boolean;
70
+ exchange: boolean;
71
+ mfa: boolean;
72
+ passwordless: boolean;
73
+ profile: boolean;
74
+ passwordChange: boolean;
75
+ accountDeletion: boolean;
76
+ sessionList: boolean;
77
+ administration: boolean;
78
+ emailChange: boolean;
79
+ impersonation: boolean;
80
+ };
81
+ describe: () => import('./types').AuthOutcome;
82
+ session: (actor?: import('../identity').Actor) => import('./types').AuthOutcome;
83
+ login: (credentials: Record<string, unknown>, carrier?: import('../credentials').CredentialCarrier) => Promise<import('./types').AuthOutcome>;
84
+ completeMfa: (mfaToken: string, code: string, carrier?: import('../credentials').CredentialCarrier) => Promise<import('./types').AuthOutcome>;
85
+ refresh: (refreshToken?: string, carrier?: import('../credentials').CredentialCarrier) => Promise<import('./types').AuthOutcome>;
86
+ logout: (credentials: {
87
+ accessToken?: string;
88
+ refreshToken?: string;
89
+ }) => Promise<import('./types').AuthOutcome>;
90
+ revokeSessions: (userId: number | undefined, scope: unknown, host: string) => Promise<import('./types').AuthOutcome>;
91
+ exchange: (provider: string, token: string, carrier: import('../credentials').CredentialCarrier) => Promise<import('./types').AuthOutcome>;
92
+ issueCsrf: (sessionToken?: string) => import('./types').AuthOutcome;
93
+ };
94
+ export type AuthApi = ReturnType<typeof createAuthApi>;
@@ -0,0 +1,43 @@
1
+ import { accountsFlows } from "./accounts.js";
2
+ import { adminFlows } from "./admin.js";
3
+ import { createAuthContext } from "./context.js";
4
+ import { factorsFlows } from "./factors.js";
5
+ import { profileFlows } from "./profile.js";
6
+ import { sessionFlows } from "./session.js";
7
+ //#region src/core/auth/api/index.ts
8
+ /**
9
+ * The HTTP surface of authentication, as functions rather than routes.
10
+ *
11
+ * Nothing here knows about Express, or about this server's own pipeline: a handler is given what the request
12
+ * carried and answers what should be sent, including whether the session cookies should be written or cleared. The
13
+ * binding does the rest, which is what lets the same login live behind an API endpoint and behind a rendered page's
14
+ * form without either owning it.
15
+ */
16
+ var createAuthApi = ({ tokens, identity, adapters, config = {} }) => {
17
+ const ctx = createAuthContext({
18
+ tokens,
19
+ identity,
20
+ adapters,
21
+ config
22
+ });
23
+ return {
24
+ ...sessionFlows(ctx),
25
+ ...factorsFlows(ctx),
26
+ ...accountsFlows(ctx),
27
+ ...profileFlows(ctx),
28
+ ...adminFlows(ctx),
29
+ /**
30
+ * The same exchange, answering in accounts rather than in HTTP.
31
+ *
32
+ * A page server needs who came back and the session they got; the flow above needs a body and a status. They
33
+ * are the same act, and the translation between them has one correct answer — so it is made once, here, rather
34
+ * than by every deployment that wires an external identity provider into a rendered page.
35
+ */
36
+ exchangeAccount: ctx.exchangeAccount,
37
+ /** Exposed so a deployment can mint a session outside the flows above — a rendered page's login form. */
38
+ issueSession: ctx.issue,
39
+ resolveActor: identity.resolveActor
40
+ };
41
+ };
42
+ //#endregion
43
+ export { createAuthApi };
@@ -0,0 +1,43 @@
1
+ import { Actor } from '../identity';
2
+ import { AuthContext } from './context';
3
+ import { AuthOutcome } from './types';
4
+ /** What a signed-in person does to their own account: the profile, the address, the password, the sessions. */
5
+ export declare const profileFlows: ({ adapters, verifyPassword, hashPassword, generateToken, record, mintLink, linkExpired, deliver, throttleSucceeded, throttled, rejectPassword, capabilities }: AuthContext) => {
6
+ /**
7
+ * Change what an account says about itself.
8
+ *
9
+ * Both fields are sign-in identifiers, so both are checked for collision first — a store that only has a unique
10
+ * index reports the clash as a driver error five hundred lines away.
11
+ */
12
+ updateProfile: (actor: Actor | undefined, fields: Record<string, unknown>) => Promise<AuthOutcome>;
13
+ /**
14
+ * Takes the parked address, having proved somebody reads it.
15
+ *
16
+ * Public, and it has to be: the link is opened from a mail client, in whatever browser that happens to be, with
17
+ * no session. The token is the whole credential — which is why it is single-use and why confirming also marks
18
+ * the account verified: an address that answered a link is an address that was proven.
19
+ */
20
+ confirmEmailChange: (token: string) => Promise<AuthOutcome>;
21
+ /**
22
+ * Change a password, having proved you know the current one.
23
+ *
24
+ * Then **every other session ends**. Changing a password is what somebody does when they think a credential
25
+ * escaped, and one that leaves the other sessions signed in has not done the thing they asked for. The session
26
+ * making the change survives, or the act of securing the account would sign them out of it.
27
+ */
28
+ changePassword: (actor: Actor | undefined, currentPassword: string, newPassword: string) => Promise<AuthOutcome>;
29
+ /**
30
+ * Close the account.
31
+ *
32
+ * Confirmed with the password when there is one — this is irreversible, and a borrowed session should not be
33
+ * able to do it. An account with no password (one that signs in through a provider) cannot be asked, so the
34
+ * session alone has to be enough.
35
+ */
36
+ deleteSelf: (actor: Actor | undefined, password?: string) => Promise<AuthOutcome>;
37
+ /** The devices this account is signed in on, with the one asking marked. */
38
+ listSessions: (actor: Actor | undefined) => Promise<AuthOutcome>;
39
+ /** End one of them. Scoped to the caller's own account, or a session id would be an IDOR. */
40
+ revokeSession: (actor: Actor | undefined, sessionId: number) => Promise<AuthOutcome>;
41
+ /** "Sign out everywhere else" — the thing to do from a device you still hold after losing one you do not. */
42
+ revokeOtherSessions: (actor: Actor | undefined) => Promise<AuthOutcome>;
43
+ };
@@ -0,0 +1,243 @@
1
+ import { LIFETIME, NOT_OFFERED, asString, profileOf, refuse } from "./values.js";
2
+ //#region src/core/auth/api/profile.ts
3
+ /** What a signed-in person does to their own account: the profile, the address, the password, the sessions. */
4
+ var profileFlows = ({ adapters, verifyPassword, hashPassword, generateToken, record, mintLink, linkExpired, deliver, throttleSucceeded, throttled, rejectPassword, capabilities }) => ({
5
+ /**
6
+ * Change what an account says about itself.
7
+ *
8
+ * Both fields are sign-in identifiers, so both are checked for collision first — a store that only has a unique
9
+ * index reports the clash as a driver error five hundred lines away.
10
+ */
11
+ updateProfile: async (actor, fields) => {
12
+ if (!capabilities.profile || !adapters.updateAccount) return NOT_OFFERED;
13
+ if (!actor) return refuse(401, "Not authenticated", "missing");
14
+ const username = asString(fields.username);
15
+ const email = asString(fields.email);
16
+ if (!username && !email) return refuse(400, "Nothing to change");
17
+ if (username && username !== actor.username) {
18
+ const taken = await adapters.findByUsername?.(username);
19
+ if (taken && taken.id !== actor.id) return refuse(409, "That username is taken");
20
+ }
21
+ if (email && email !== actor.email) {
22
+ const taken = await adapters.findByEmail?.(email);
23
+ if (taken && taken.id !== actor.id) return refuse(409, "That email is taken");
24
+ }
25
+ const changingEmail = Boolean(email) && email !== actor.email;
26
+ /**
27
+ * A new address is PARKED, not applied: the account keeps the one it has until the new one answers a
28
+ * confirmation. That is what makes a typo survivable — `n@exmaple.com` costs a resend, not the account.
29
+ *
30
+ * The alternative, applying it and taking `verified` away, was tried and reverted: `verified` in this server
31
+ * gates ACCESS (`createAuthorizer` refuses to present an unverified account as an actor at all), so it locked
32
+ * people out of the account they were sitting in. And the attack it guarded against needs a live session,
33
+ * from which the same person could simply change the password.
34
+ *
35
+ * A deployment that supplies nowhere to park it changes the address on the spot, as it always did.
36
+ */
37
+ const parking = changingEmail && capabilities.emailChange;
38
+ const account = await adapters.updateAccount(actor.id, {
39
+ ...username ? { username } : {},
40
+ ...email && !parking ? { email } : {}
41
+ });
42
+ if (parking && adapters.setPendingEmail) {
43
+ const confirmationToken = mintLink(generateToken(), LIFETIME.confirmLink);
44
+ await adapters.setPendingEmail(actor.id, email, confirmationToken);
45
+ await deliver({
46
+ to: email,
47
+ template: "email-change",
48
+ data: {
49
+ username: account.username,
50
+ email,
51
+ confirmationToken
52
+ }
53
+ });
54
+ return {
55
+ ok: true,
56
+ body: {
57
+ success: true,
58
+ details: profileOf(account),
59
+ pendingEmail: email,
60
+ message: "A confirmation was sent to the new address. It takes effect once confirmed."
61
+ }
62
+ };
63
+ }
64
+ if (changingEmail && capabilities.emailVerification && adapters.setValidationToken) {
65
+ const validationToken = mintLink(generateToken(), LIFETIME.confirmLink);
66
+ await adapters.setValidationToken(actor.id, validationToken);
67
+ await deliver({
68
+ to: account.email,
69
+ template: "validation",
70
+ data: {
71
+ username: account.username,
72
+ validationToken
73
+ }
74
+ });
75
+ return {
76
+ ok: true,
77
+ body: {
78
+ success: true,
79
+ details: profileOf(account),
80
+ message: "A confirmation was sent to the new address"
81
+ }
82
+ };
83
+ }
84
+ return {
85
+ ok: true,
86
+ body: {
87
+ success: true,
88
+ details: profileOf(account)
89
+ }
90
+ };
91
+ },
92
+ /**
93
+ * Takes the parked address, having proved somebody reads it.
94
+ *
95
+ * Public, and it has to be: the link is opened from a mail client, in whatever browser that happens to be, with
96
+ * no session. The token is the whole credential — which is why it is single-use and why confirming also marks
97
+ * the account verified: an address that answered a link is an address that was proven.
98
+ */
99
+ confirmEmailChange: async (token) => {
100
+ if (!capabilities.emailChange || !adapters.findByPendingEmail || !adapters.clearPendingEmail) return NOT_OFFERED;
101
+ const confirmation = asString(token);
102
+ const pending = linkExpired(confirmation) ? void 0 : await adapters.findByPendingEmail(confirmation);
103
+ if (!pending) return refuse(400, "Invalid or expired token");
104
+ const taken = await adapters.findByEmail?.(pending.email);
105
+ if (taken && taken.id !== pending.account.id) {
106
+ await adapters.clearPendingEmail(pending.account.id);
107
+ return refuse(409, "That email is taken");
108
+ }
109
+ const account = await adapters.updateAccount?.(pending.account.id, { email: pending.email });
110
+ await adapters.clearPendingEmail(pending.account.id);
111
+ if (adapters.setVerified) await adapters.setVerified(pending.account.id, true);
112
+ record({
113
+ type: "email.changed",
114
+ userId: pending.account.id,
115
+ detail: { email: pending.email }
116
+ });
117
+ const confirmed = {
118
+ ...account ?? pending.account,
119
+ email: pending.email
120
+ };
121
+ return {
122
+ ok: true,
123
+ body: {
124
+ success: true,
125
+ details: profileOf(adapters.setVerified ? {
126
+ ...confirmed,
127
+ verified: true
128
+ } : confirmed)
129
+ }
130
+ };
131
+ },
132
+ /**
133
+ * Change a password, having proved you know the current one.
134
+ *
135
+ * Then **every other session ends**. Changing a password is what somebody does when they think a credential
136
+ * escaped, and one that leaves the other sessions signed in has not done the thing they asked for. The session
137
+ * making the change survives, or the act of securing the account would sign them out of it.
138
+ */
139
+ changePassword: async (actor, currentPassword, newPassword) => {
140
+ if (!capabilities.passwordChange || !adapters.findById) return NOT_OFFERED;
141
+ if (!actor) return refuse(401, "Not authenticated", "missing");
142
+ if (!currentPassword || !newPassword) return refuse(400, "The current and the new password are required");
143
+ const weak = await rejectPassword(newPassword, {
144
+ username: actor.username,
145
+ email: actor.email
146
+ });
147
+ if (weak) return weak;
148
+ const limited = await throttled({
149
+ action: "changePassword",
150
+ key: String(actor.id)
151
+ });
152
+ if (limited) return limited;
153
+ const account = await adapters.findById(actor.id);
154
+ if (!account?.passwordHash || !await verifyPassword(currentPassword, account.passwordHash)) return refuse(401, "Invalid credentials");
155
+ await adapters.setPassword?.(actor.id, await hashPassword(newPassword));
156
+ await adapters.revokeOtherSessions?.(actor.id, actor.token);
157
+ throttleSucceeded({
158
+ action: "changePassword",
159
+ key: String(actor.id)
160
+ });
161
+ record({
162
+ type: "password.changed",
163
+ userId: actor.id
164
+ });
165
+ return {
166
+ ok: true,
167
+ body: {
168
+ success: true,
169
+ message: "Password changed. Other sessions were signed out."
170
+ }
171
+ };
172
+ },
173
+ /**
174
+ * Close the account.
175
+ *
176
+ * Confirmed with the password when there is one — this is irreversible, and a borrowed session should not be
177
+ * able to do it. An account with no password (one that signs in through a provider) cannot be asked, so the
178
+ * session alone has to be enough.
179
+ */
180
+ deleteSelf: async (actor, password) => {
181
+ if (!capabilities.accountDeletion || !adapters.deleteAccount) return NOT_OFFERED;
182
+ if (!actor) return refuse(401, "Not authenticated", "missing");
183
+ const account = await adapters.findById?.(actor.id);
184
+ if (account?.passwordHash) {
185
+ if (!password || !await verifyPassword(password, account.passwordHash)) return refuse(401, "Invalid credentials");
186
+ }
187
+ const blockers = await adapters.deletionBlockers?.(actor.id) ?? [];
188
+ if (blockers.length > 0) return {
189
+ ok: false,
190
+ status: 409,
191
+ body: {
192
+ error: "This account still owns things that would be lost with it",
193
+ blockers
194
+ }
195
+ };
196
+ await adapters.deleteAccount(actor.id);
197
+ record({
198
+ type: "account.deleted",
199
+ userId: actor.id
200
+ });
201
+ return {
202
+ ok: true,
203
+ body: {
204
+ success: true,
205
+ message: "Account deleted"
206
+ },
207
+ endSession: true
208
+ };
209
+ },
210
+ /** The devices this account is signed in on, with the one asking marked. */
211
+ listSessions: async (actor) => {
212
+ if (!capabilities.sessionList || !adapters.listSessions) return NOT_OFFERED;
213
+ if (!actor) return refuse(401, "Not authenticated", "missing");
214
+ return {
215
+ ok: true,
216
+ body: { sessions: await adapters.listSessions(actor.id, actor.token) }
217
+ };
218
+ },
219
+ /** End one of them. Scoped to the caller's own account, or a session id would be an IDOR. */
220
+ revokeSession: async (actor, sessionId) => {
221
+ if (!adapters.revokeSession) return NOT_OFFERED;
222
+ if (!actor) return refuse(401, "Not authenticated", "missing");
223
+ if (!Number.isInteger(sessionId)) return refuse(400, "A session id is required");
224
+ return await adapters.revokeSession(actor.id, sessionId) ? {
225
+ ok: true,
226
+ body: { success: true }
227
+ } : refuse(404, "No such session");
228
+ },
229
+ /** "Sign out everywhere else" — the thing to do from a device you still hold after losing one you do not. */
230
+ revokeOtherSessions: async (actor) => {
231
+ if (!adapters.revokeOtherSessions) return NOT_OFFERED;
232
+ if (!actor) return refuse(401, "Not authenticated", "missing");
233
+ return {
234
+ ok: true,
235
+ body: {
236
+ success: true,
237
+ revoked: await adapters.revokeOtherSessions(actor.id, actor.token)
238
+ }
239
+ };
240
+ }
241
+ });
242
+ //#endregion
243
+ export { profileFlows };