@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
@@ -0,0 +1,62 @@
1
+ import { CredentialCarrier } from '../credentials';
2
+ import { Actor } from '../identity';
3
+ import { AuthContext } from './context';
4
+ import { AuthOutcome } from './types';
5
+ /** Signing in and out: the session, a password or a provider's token, the second factor, refreshing and revoking. */
6
+ export declare const sessionFlows: ({ tokens, adapters, verifyPassword, csrf, record, digestRecoveryCode, throttleSucceeded, throttled, capabilities, issue, grantBody, exchangeAccount }: AuthContext) => {
7
+ capabilities: {
8
+ passwordLogin: boolean;
9
+ refresh: boolean;
10
+ signup: boolean;
11
+ passwordReset: boolean;
12
+ emailVerification: boolean;
13
+ exchange: boolean;
14
+ mfa: boolean;
15
+ passwordless: boolean;
16
+ profile: boolean;
17
+ passwordChange: boolean;
18
+ accountDeletion: boolean;
19
+ sessionList: boolean;
20
+ administration: boolean;
21
+ emailChange: boolean;
22
+ impersonation: boolean;
23
+ };
24
+ /** What a client reads to know which of the flows below actually exist here. */
25
+ describe: () => AuthOutcome;
26
+ /**
27
+ * Who the caller is, and until when. Reaching a resolved actor at all is the answer to "is the session alive" —
28
+ * the guard refuses with a `reason` when it could not, so a client learns whether to renew or to drop to
29
+ * signed-out from the refusal itself. It costs no query: the actor was resolved before routing.
30
+ */
31
+ session: (actor?: Actor) => AuthOutcome;
32
+ login: (credentials: Record<string, unknown>, carrier?: CredentialCarrier) => Promise<AuthOutcome>;
33
+ /**
34
+ * The second half of a sign-in that owed a factor.
35
+ *
36
+ * Takes a TOTP code or a recovery code. A recovery code is SPENT — removed from the stored list — because one
37
+ * that survives being used is a password with extra steps.
38
+ */
39
+ completeMfa: (mfaToken: string, code: string, carrier?: CredentialCarrier) => Promise<AuthOutcome>;
40
+ refresh: (refreshToken?: string, carrier?: CredentialCarrier) => Promise<AuthOutcome>;
41
+ /** Reachable with an expired access token on purpose, or a live refresh token could never be revoked. */
42
+ logout: (credentials: {
43
+ accessToken?: string;
44
+ refreshToken?: string;
45
+ }) => Promise<AuthOutcome>;
46
+ /**
47
+ * Ends this account's session everywhere, for the case where one leaked. Unlike logout it is authenticated and
48
+ * works by account id, so it can be used from a device that still has a good session while the stolen copy is
49
+ * somewhere else entirely.
50
+ */
51
+ /**
52
+ * Signing out everywhere: every session of the account (`scope` `all`, or none said) — or, `site`, those signed in on
53
+ * `host`, the one asking: a space's visitor ending theirs there and nowhere else.
54
+ */
55
+ revokeSessions: (userId: number | undefined, scope: unknown, host: string) => Promise<AuthOutcome>;
56
+ exchange: (provider: string, token: string, carrier: CredentialCarrier) => Promise<AuthOutcome>;
57
+ /**
58
+ * A CSRF token for whoever is asking, bound to their session when they have one. Answered as a body AND as the
59
+ * cookie the binding writes, so a page can take whichever it finds easier to read.
60
+ */
61
+ issueCsrf: (sessionToken?: string) => AuthOutcome;
62
+ };
@@ -0,0 +1,312 @@
1
+ import { NOT_OFFERED, asString, asText, clientOf, deniedReason, now, refuse } from "./values.js";
2
+ import { totpStep } from "../totp.js";
3
+ import { authFailureMessage, userIdOf } from "../tokens.js";
4
+ //#region src/core/auth/api/session.ts
5
+ /** Signing in and out: the session, a password or a provider's token, the second factor, refreshing and revoking. */
6
+ var sessionFlows = ({ tokens, adapters, verifyPassword, csrf, record, digestRecoveryCode, throttleSucceeded, throttled, capabilities, issue, grantBody, exchangeAccount }) => ({
7
+ capabilities,
8
+ /** What a client reads to know which of the flows below actually exist here. */
9
+ describe: () => ({
10
+ ok: true,
11
+ body: { features: capabilities }
12
+ }),
13
+ /**
14
+ * Who the caller is, and until when. Reaching a resolved actor at all is the answer to "is the session alive" —
15
+ * the guard refuses with a `reason` when it could not, so a client learns whether to renew or to drop to
16
+ * signed-out from the refusal itself. It costs no query: the actor was resolved before routing.
17
+ */
18
+ session: (actor) => {
19
+ if (!actor) return refuse(401, "Not authenticated", "missing");
20
+ const now = Math.floor(Date.now() / 1e3);
21
+ return {
22
+ ok: true,
23
+ body: {
24
+ success: true,
25
+ details: {
26
+ id: actor.id,
27
+ username: actor.username,
28
+ email: actor.email,
29
+ verified: actor.verified,
30
+ roles: actor.roles,
31
+ permissions: actor.permissions,
32
+ ...actor.impersonatedBy === void 0 ? {} : { impersonatedBy: actor.impersonatedBy }
33
+ },
34
+ access_token: actor.token,
35
+ expire_in: Math.max(0, actor.expiresAt - now),
36
+ expire_at: actor.expiresAt
37
+ }
38
+ };
39
+ },
40
+ login: async (credentials, carrier) => {
41
+ if (!capabilities.passwordLogin) return NOT_OFFERED;
42
+ const username = asString(credentials.username);
43
+ const password = asText(credentials.password);
44
+ if (!username || !password) return refuse(400, "A username and a password are required");
45
+ const limited = await throttled({
46
+ action: "login",
47
+ key: username,
48
+ carrier
49
+ });
50
+ if (limited) return limited;
51
+ /**
52
+ * The username, or the email — in that order.
53
+ *
54
+ * Every sign-in screen worth using offers both, because the one thing a person reliably remembers about an
55
+ * account is the address it was created with. Username first so an account whose name happens to be somebody
56
+ * else's address cannot shadow the owner of that address; the email lookup only runs when the first misses,
57
+ * so this costs a second query on a failed sign-in and nothing on a successful one.
58
+ *
59
+ * `findByEmail` is optional like everything else here: a deployment that supplies no email store keeps exactly
60
+ * the behaviour it had.
61
+ */
62
+ const account = await adapters.findByUsername?.(username) ?? (username.includes("@") ? await adapters.findByEmail?.(username) : void 0);
63
+ if (!account) return refuse(401, "Invalid credentials");
64
+ if (!account.passwordHash || !await verifyPassword(password, account.passwordHash)) {
65
+ record({
66
+ type: "login.failed",
67
+ userId: account.id,
68
+ carrier,
69
+ detail: { username }
70
+ });
71
+ return refuse(401, "Invalid credentials");
72
+ }
73
+ /**
74
+ * Whether this account may hold a session — asked AFTER the password, and that order is the point.
75
+ *
76
+ * Anything said about an account before its password is checked is said to anybody who types an address. The
77
+ * other way round, "that address has not been confirmed" once cost nothing to establish: two attempts with a
78
+ * made-up password told a stranger which of a list of addresses have accounts here and which do not. It is
79
+ * only a refusal somebody has earned the right to understand once they have proved the account is theirs.
80
+ */
81
+ if (!account.active) {
82
+ const reason = deniedReason(account);
83
+ return refuse(401, authFailureMessage[reason], reason);
84
+ }
85
+ const ssoOnly = await adapters.passwordSignInRefused?.(account);
86
+ if (ssoOnly) {
87
+ throttleSucceeded({
88
+ action: "login",
89
+ key: username,
90
+ carrier
91
+ });
92
+ record({
93
+ type: "login.failed",
94
+ userId: account.id,
95
+ carrier,
96
+ detail: {
97
+ username,
98
+ reason: "sso-required"
99
+ }
100
+ });
101
+ return refuse(401, ssoOnly, "sso-required");
102
+ }
103
+ if ((capabilities.mfa ? await adapters.loadMfa?.(account.id) : void 0)?.confirmedAt) {
104
+ throttleSucceeded({
105
+ action: "login",
106
+ key: username,
107
+ carrier
108
+ });
109
+ record({
110
+ type: "login.mfa-required",
111
+ userId: account.id,
112
+ carrier
113
+ });
114
+ return {
115
+ ok: true,
116
+ body: {
117
+ success: false,
118
+ mfaRequired: true,
119
+ mfaToken: tokens.generateMfaChallenge(account.id)
120
+ }
121
+ };
122
+ }
123
+ const session = await issue(account.id, { client: clientOf(carrier) });
124
+ throttleSucceeded({
125
+ action: "login",
126
+ key: username,
127
+ carrier
128
+ });
129
+ record({
130
+ type: "login",
131
+ userId: account.id,
132
+ carrier
133
+ });
134
+ return {
135
+ ok: true,
136
+ body: await grantBody(account, session),
137
+ session
138
+ };
139
+ },
140
+ /**
141
+ * The second half of a sign-in that owed a factor.
142
+ *
143
+ * Takes a TOTP code or a recovery code. A recovery code is SPENT — removed from the stored list — because one
144
+ * that survives being used is a password with extra steps.
145
+ */
146
+ completeMfa: async (mfaToken, code, carrier) => {
147
+ if (!capabilities.mfa) return NOT_OFFERED;
148
+ const verified = tokens.verifyMfaChallenge(mfaToken);
149
+ if (!verified.ok) return refuse(401, authFailureMessage[verified.reason], verified.reason);
150
+ const userId = Number(verified.payload.sub);
151
+ const limited = await throttled({
152
+ action: "mfa",
153
+ key: String(userId),
154
+ carrier
155
+ });
156
+ if (limited) return limited;
157
+ const account = await adapters.findById?.(userId);
158
+ const mfa = await adapters.loadMfa?.(userId);
159
+ if (!account || !mfa?.confirmedAt) return refuse(401, "Invalid credentials");
160
+ if (!account.active) {
161
+ const reason = deniedReason(account);
162
+ return refuse(401, authFailureMessage[reason], reason);
163
+ }
164
+ const stored = mfa.recoveryCodes ?? [];
165
+ const supplied = digestRecoveryCode(code);
166
+ const usedRecovery = stored.includes(supplied);
167
+ const step = usedRecovery ? void 0 : totpStep(mfa.secret, code);
168
+ const replayed = step !== void 0 && mfa.lastUsedStep !== void 0 && step <= mfa.lastUsedStep;
169
+ if (!usedRecovery && (step === void 0 || replayed)) {
170
+ record({
171
+ type: "mfa.failed",
172
+ userId,
173
+ carrier,
174
+ ...replayed ? { detail: { replayed: true } } : {}
175
+ });
176
+ return refuse(401, "Invalid code");
177
+ }
178
+ await adapters.saveMfa?.(userId, usedRecovery ? {
179
+ ...mfa,
180
+ recoveryCodes: stored.filter((entry) => entry !== supplied)
181
+ } : {
182
+ ...mfa,
183
+ lastUsedStep: step
184
+ });
185
+ const session = await issue(userId, { client: clientOf(carrier) });
186
+ throttleSucceeded({
187
+ action: "mfa",
188
+ key: String(userId),
189
+ carrier
190
+ });
191
+ record({
192
+ type: "login",
193
+ userId,
194
+ carrier,
195
+ detail: { recoveryCode: usedRecovery }
196
+ });
197
+ return {
198
+ ok: true,
199
+ body: {
200
+ ...await grantBody(account, session),
201
+ ...usedRecovery ? { recoveryCodeUsed: true } : {}
202
+ },
203
+ session
204
+ };
205
+ },
206
+ refresh: async (refreshToken, carrier) => {
207
+ if (!capabilities.refresh) return NOT_OFFERED;
208
+ if (!refreshToken) return refuse(400, "Refresh token is required");
209
+ /**
210
+ * Every refusal below ends the session in this browser, because each of them means the credential it just
211
+ * presented can never work again: not one this deployment signed, no such row, past its deadline, or an
212
+ * account that may not hold one. What is being cleared is not authority — the row is already gone — it is the
213
+ * browser's reason to keep asking.
214
+ *
215
+ * The token carries its own deadline, so the store is asked only whether it still holds the row — the switch
216
+ * that revokes it. A `refreshExpiresAt` it reports overrides that deadline, and a store that keeps none needs
217
+ * to report nothing.
218
+ */
219
+ const lapsed = {
220
+ ...refuse(401, "Invalid or expired refresh token", "expired"),
221
+ endSession: true
222
+ };
223
+ const verified = tokens.verifyRefreshToken(refreshToken);
224
+ if (!verified.ok) return lapsed;
225
+ const account = await adapters.findByRefreshToken?.(refreshToken);
226
+ const deadline = account?.refreshExpiresAt ?? verified.payload.exp;
227
+ if (!account || account.id !== userIdOf(verified.payload) || deadline === void 0 || deadline < now()) return lapsed;
228
+ if (!account.active) {
229
+ const reason = deniedReason(account);
230
+ return {
231
+ ...refuse(401, authFailureMessage[reason], reason),
232
+ endSession: true
233
+ };
234
+ }
235
+ const cap = tokens.lifetimes.session;
236
+ if (cap > 0 && account.sessionStartedAt !== void 0 && account.sessionStartedAt + cap < now()) {
237
+ await adapters.clearSession({ refreshToken });
238
+ return {
239
+ ...refuse(401, "This session has reached its maximum lifetime", "expired"),
240
+ endSession: true
241
+ };
242
+ }
243
+ const session = await issue(account.id, {
244
+ replaces: { refreshToken },
245
+ client: clientOf(carrier)
246
+ });
247
+ return {
248
+ ok: true,
249
+ body: await grantBody(account, session),
250
+ session
251
+ };
252
+ },
253
+ /** Reachable with an expired access token on purpose, or a live refresh token could never be revoked. */
254
+ logout: async (credentials) => {
255
+ if (credentials.accessToken || credentials.refreshToken) await adapters.clearSession(credentials);
256
+ return {
257
+ ok: true,
258
+ body: { message: "Logged out successfully" },
259
+ endSession: true
260
+ };
261
+ },
262
+ /**
263
+ * Ends this account's session everywhere, for the case where one leaked. Unlike logout it is authenticated and
264
+ * works by account id, so it can be used from a device that still has a good session while the stolen copy is
265
+ * somewhere else entirely.
266
+ */
267
+ /**
268
+ * Signing out everywhere: every session of the account (`scope` `all`, or none said) — or, `site`, those signed in on
269
+ * `host`, the one asking: a space's visitor ending theirs there and nowhere else.
270
+ */
271
+ revokeSessions: async (userId, scope, host) => {
272
+ if (!userId) return refuse(401, "Not authenticated", "missing");
273
+ if (scope !== void 0 && scope !== "" && scope !== "site" && scope !== "all") return refuse(400, "A scope is \"site\" — this site's sessions — or \"all\", every one of the account");
274
+ await adapters.clearSession(scope === "site" ? {
275
+ userId,
276
+ host: host.toLowerCase()
277
+ } : { userId });
278
+ return {
279
+ ok: true,
280
+ body: { message: "All sessions revoked" },
281
+ endSession: true
282
+ };
283
+ },
284
+ exchange: async (provider, token, carrier) => {
285
+ const result = await exchangeAccount(provider, token, carrier);
286
+ if (!result.ok) return result.offered ? refuse(result.status, result.error, result.reason) : NOT_OFFERED;
287
+ const { account, access, session } = result;
288
+ return {
289
+ ok: true,
290
+ body: await grantBody(account, session, access),
291
+ session
292
+ };
293
+ },
294
+ /**
295
+ * A CSRF token for whoever is asking, bound to their session when they have one. Answered as a body AND as the
296
+ * cookie the binding writes, so a page can take whichever it finds easier to read.
297
+ */
298
+ issueCsrf: (sessionToken) => {
299
+ if (!csrf) return NOT_OFFERED;
300
+ const token = csrf.issue(sessionToken);
301
+ return {
302
+ ok: true,
303
+ body: {
304
+ token,
305
+ headerName: csrf.headerName
306
+ },
307
+ csrf: token
308
+ };
309
+ }
310
+ });
311
+ //#endregion
312
+ export { sessionFlows };
@@ -1,7 +1,6 @@
1
- import { CredentialCarrier } from './credentials';
2
- import { Csrf } from './csrf';
3
- import { Actor, Identity } from './identity';
4
- import { AuthFailure, Tokens } from './tokens';
1
+ import { CredentialCarrier } from '../credentials';
2
+ import { Csrf } from '../csrf';
3
+ import { AuthFailure } from '../tokens';
5
4
  import { SSRSession } from '@plitzi/sdk-shared';
6
5
  /**
7
6
  * An account, as whatever stores accounts reports one. Deliberately not a user model: these are the only fields any
@@ -39,9 +38,15 @@ export interface AccountAccess {
39
38
  export interface SessionClient {
40
39
  userAgent?: string;
41
40
  ip?: string;
41
+ /**
42
+ * The host it was signed in on: a space's own (`acme.plitzi.app`), where its visitors sign in through the platform,
43
+ * or the platform's. What "sign out of this site everywhere" ends — a host's cookies are its own, so its sessions
44
+ * are what a visitor holds there, on every device.
45
+ */
46
+ host?: string;
42
47
  /**
43
48
  * The application holding it, when it is not a browser: a native client names itself when it registers
44
- * (`Plitzi CLI on carlos-mbp`, software `plitzi-cli`). A user agent says which browser; this says which app.
49
+ * (`Plitzi CLI on dev-laptop`, software `plitzi-cli`). A user agent says which browser; this says which app.
45
50
  */
46
51
  app?: SessionApp;
47
52
  }
@@ -61,6 +66,8 @@ export interface SessionSummary {
61
66
  userAgent?: string;
62
67
  ip?: string;
63
68
  app?: SessionApp;
69
+ /** Where it was signed in (`SessionClient.host`): a space's own host, or the platform's. */
70
+ host?: string;
64
71
  createdAt: number;
65
72
  /** When it was last used, where the store keeps it; a session never seen since it was made has none. */
66
73
  lastActiveAt?: number;
@@ -117,10 +124,9 @@ export interface SessionContext {
117
124
  client?: SessionClient;
118
125
  }
119
126
  /**
120
- * The account store, as auth needs to see it. Every method is optional except the three the session cycle cannot do
121
- * without, and **what is absent decides what this server offers**: a deployment with no `createAccount` has no
122
- * signup, and its route answers 404 rather than failing at runtime. That rule is what lets one server serve a
123
- * deployment with its own user table and one that signs everybody in through an external provider.
127
+ * The user agent and the address, off whatever carried the request — what lets somebody tell their devices apart.
128
+ * Nothing else here reads headers, so it is done once. The address is the host's when it resolved one, the proxies'
129
+ * otherwise; it names a session in a list and decides nothing.
124
130
  */
125
131
  export interface AccountAdapters {
126
132
  /**
@@ -131,11 +137,15 @@ export interface AccountAdapters {
131
137
  * renewal leaves a row behind.
132
138
  */
133
139
  saveSession: (userId: number, session: SSRSession, context?: SessionContext) => Promise<void>;
134
- /** Clear the pair, by whichever half the caller holds, or by account. */
140
+ /**
141
+ * Clear the pair, by whichever half the caller holds, or by account — and with `host` beside `userId`, only that
142
+ * account's sessions signed in on that host (`SessionClient.host`): a site's sign-out everywhere, not the account's.
143
+ */
135
144
  clearSession: (target: {
136
145
  accessToken?: string;
137
146
  refreshToken?: string;
138
147
  userId?: number;
148
+ host?: string;
139
149
  }) => Promise<void>;
140
150
  /** Global roles and permissions, for the body a grant answers with. */
141
151
  loadAccess: (userId: number) => Promise<AccountAccess>;
@@ -188,8 +198,20 @@ export interface AccountAdapters {
188
198
  username: string;
189
199
  email: string;
190
200
  passwordHash: string;
201
+ /** The terms the person accepted as they signed up, when the deployment asks for them (`terms`). */
202
+ termsAccepted?: {
203
+ version: string;
204
+ at: Date;
205
+ };
191
206
  }) => Promise<AccountRecord>;
192
207
  findByEmail?: (email: string) => Promise<AccountRecord | undefined>;
208
+ /**
209
+ * Why `account` may not sign in with a password, if it may not: its organization requires its own single sign-on.
210
+ * Asked only once the password is proved right — what is said of an account before that is said to anybody who
211
+ * types its address. The refusal is a 401 with the reason `sso-required` and these words — a 401 like `unverified`,
212
+ * the other refusal of a right password: it is what a browser's sign-in reads a reason from.
213
+ */
214
+ passwordSignInRefused?: (account: AccountRecord) => Promise<string | undefined>;
193
215
  setPassword?: (userId: number, passwordHash: string) => Promise<void>;
194
216
  setResetToken?: (userId: number, token: string) => Promise<void>;
195
217
  findByResetToken?: (token: string) => Promise<AccountRecord | undefined>;
@@ -299,6 +321,15 @@ export interface AuthApiConfig {
299
321
  generateToken?: () => string;
300
322
  /** Whether a new account may sign in immediately or has to confirm its address first. */
301
323
  verifyOnSignup?: boolean;
324
+ /**
325
+ * The terms an account is opened under. Set, `/auth/signup` refuses a sign-up that does not say `acceptedTerms: true`
326
+ * (400, `field: 'acceptedTerms'`), and `createAccount` is told which version was accepted and when — the record a
327
+ * deployment keeps of what each person agreed to. `version` is the deployment's own name for the text in force (a
328
+ * date, a number); change it when the terms change.
329
+ */
330
+ terms?: {
331
+ version: string;
332
+ };
302
333
  /**
303
334
  * The global capability an administrator must hold to act on somebody else's account. Named rather than fixed,
304
335
  * because what a deployment calls its permissions is its own vocabulary. Default `userManage`.
@@ -381,188 +412,3 @@ export type AuthOutcome = {
381
412
  body: object;
382
413
  endSession?: boolean;
383
414
  };
384
- /**
385
- * The HTTP surface of authentication, as functions rather than routes.
386
- *
387
- * Nothing here knows about Express, or about this server's own pipeline: a handler is given what the request
388
- * carried and answers what should be sent, including whether the session cookies should be written or cleared. The
389
- * binding does the rest, which is what lets the same login live behind an API endpoint and behind a rendered page's
390
- * form without either owning it.
391
- */
392
- export declare const createAuthApi: ({ tokens, identity, adapters, config }: {
393
- tokens: Tokens;
394
- identity: Identity;
395
- adapters: AccountAdapters;
396
- config?: AuthApiConfig;
397
- }) => {
398
- capabilities: {
399
- passwordLogin: boolean;
400
- refresh: boolean;
401
- signup: boolean;
402
- passwordReset: boolean;
403
- emailVerification: boolean;
404
- exchange: boolean;
405
- mfa: boolean;
406
- passwordless: boolean;
407
- profile: boolean;
408
- passwordChange: boolean;
409
- accountDeletion: boolean;
410
- sessionList: boolean;
411
- administration: boolean;
412
- /** Changing an address by confirming it, rather than on the spot. Needs somewhere to park it and a way to write. */
413
- emailChange: boolean;
414
- /** Off unless the deployment named the capability it takes — see `impersonationPermission`. */
415
- impersonation: boolean;
416
- };
417
- /** What a client reads to know which of the flows below actually exist here. */
418
- describe: () => AuthOutcome;
419
- /**
420
- * Who the caller is, and until when. Reaching a resolved actor at all is the answer to "is the session alive" —
421
- * the guard refuses with a `reason` when it could not, so a client learns whether to renew or to drop to
422
- * signed-out from the refusal itself. It costs no query: the actor was resolved before routing.
423
- */
424
- session: (actor?: Actor) => AuthOutcome;
425
- login: (credentials: Record<string, unknown>, carrier?: CredentialCarrier) => Promise<AuthOutcome>;
426
- /**
427
- * The second half of a sign-in that owed a factor.
428
- *
429
- * Takes a TOTP code or a recovery code. A recovery code is SPENT — removed from the stored list — because one
430
- * that survives being used is a password with extra steps.
431
- */
432
- completeMfa: (mfaToken: string, code: string, carrier?: CredentialCarrier) => Promise<AuthOutcome>;
433
- /**
434
- * Signing in with a code sent to an email address, and no password at all.
435
- *
436
- * Two decisions worth stating. **The request answers the same whether the address exists or not** — anything
437
- * else turns this endpoint into a way to ask which addresses have accounts. And **it never creates an
438
- * account**: a sign-in flow that silently registers whoever asks is a different feature, and one a deployment
439
- * should choose deliberately rather than inherit.
440
- */
441
- passwordless: {
442
- request: (email: string, carrier?: CredentialCarrier) => Promise<AuthOutcome>;
443
- complete: (email: string, code: string, carrier?: CredentialCarrier) => Promise<AuthOutcome>;
444
- };
445
- /**
446
- * Everything about this account's second factor. `begin` hands back a secret and the URI an app scans; nothing
447
- * is in force until `confirm` proves a code from it.
448
- */
449
- mfa: {
450
- status: (actor: Actor | undefined) => Promise<AuthOutcome>;
451
- begin: (actor: Actor | undefined) => Promise<AuthOutcome>;
452
- /** Proves the app was actually set up, and only then does the factor start being required. */
453
- confirm: (actor: Actor | undefined, code: string) => Promise<AuthOutcome>;
454
- /** Removing a factor is a security downgrade, so it asks for the password the way deleting an account does. */
455
- disable: (actor: Actor | undefined, password?: string) => Promise<AuthOutcome>;
456
- };
457
- refresh: (refreshToken?: string, carrier?: CredentialCarrier) => Promise<AuthOutcome>;
458
- /** Reachable with an expired access token on purpose, or a live refresh token could never be revoked. */
459
- logout: (credentials: {
460
- accessToken?: string;
461
- refreshToken?: string;
462
- }) => Promise<AuthOutcome>;
463
- /**
464
- * Ends this account's session everywhere, for the case where one leaked. Unlike logout it is authenticated and
465
- * works by account id, so it can be used from a device that still has a good session while the stolen copy is
466
- * somewhere else entirely.
467
- */
468
- revokeSessions: (userId?: number) => Promise<AuthOutcome>;
469
- exchange: (provider: string, token: string, carrier: CredentialCarrier) => Promise<AuthOutcome>;
470
- /**
471
- * The same exchange, answering in accounts rather than in HTTP.
472
- *
473
- * A page server needs who came back and the session they got; the flow above needs a body and a status. They
474
- * are the same act, and the translation between them has one correct answer — so it is made once, here, rather
475
- * than by every deployment that wires an external identity provider into a rendered page.
476
- */
477
- exchangeAccount: (provider: string, token: string, carrier: CredentialCarrier) => Promise<ExchangeResult>;
478
- signup: (fields: Record<string, unknown>) => Promise<AuthOutcome>;
479
- /** Answers the same either way: whether an address has an account here is not something a stranger may probe. */
480
- forgotPassword: (email: string) => Promise<AuthOutcome>;
481
- resetPassword: (token: string, password: string) => Promise<AuthOutcome>;
482
- validateAccount: (token: string) => Promise<AuthOutcome>;
483
- resendVerification: (email: string, redirect?: string) => Promise<AuthOutcome>;
484
- /**
485
- * Change what an account says about itself.
486
- *
487
- * Both fields are sign-in identifiers, so both are checked for collision first — a store that only has a unique
488
- * index reports the clash as a driver error five hundred lines away.
489
- */
490
- updateProfile: (actor: Actor | undefined, fields: Record<string, unknown>) => Promise<AuthOutcome>;
491
- /**
492
- * Takes the parked address, having proved somebody reads it.
493
- *
494
- * Public, and it has to be: the link is opened from a mail client, in whatever browser that happens to be, with
495
- * no session. The token is the whole credential — which is why it is single-use and why confirming also marks
496
- * the account verified: an address that answered a link is an address that was proven.
497
- */
498
- confirmEmailChange: (token: string) => Promise<AuthOutcome>;
499
- /**
500
- * Change a password, having proved you know the current one.
501
- *
502
- * Then **every other session ends**. Changing a password is what somebody does when they think a credential
503
- * escaped, and one that leaves the other sessions signed in has not done the thing they asked for. The session
504
- * making the change survives, or the act of securing the account would sign them out of it.
505
- */
506
- changePassword: (actor: Actor | undefined, currentPassword: string, newPassword: string) => Promise<AuthOutcome>;
507
- /**
508
- * Close the account.
509
- *
510
- * Confirmed with the password when there is one — this is irreversible, and a borrowed session should not be
511
- * able to do it. An account with no password (one that signs in through a provider) cannot be asked, so the
512
- * session alone has to be enough.
513
- */
514
- deleteSelf: (actor: Actor | undefined, password?: string) => Promise<AuthOutcome>;
515
- /** The devices this account is signed in on, with the one asking marked. */
516
- listSessions: (actor: Actor | undefined) => Promise<AuthOutcome>;
517
- /** End one of them. Scoped to the caller's own account, or a session id would be an IDOR. */
518
- revokeSession: (actor: Actor | undefined, sessionId: number) => Promise<AuthOutcome>;
519
- /** "Sign out everywhere else" — the thing to do from a device you still hold after losing one you do not. */
520
- revokeOtherSessions: (actor: Actor | undefined) => Promise<AuthOutcome>;
521
- admin: {
522
- list: (actor: Actor | undefined, query: AccountQuery) => Promise<AuthOutcome>;
523
- get: (actor: Actor | undefined, userId: number) => Promise<AuthOutcome>;
524
- /**
525
- * Suspend, block or restore an account — and **end its sessions when it stops being active**.
526
- *
527
- * That second half is the whole point. A ban that leaves the credential working is not a ban, it is a note
528
- * in a database; the person stays signed in until their token happens to lapse.
529
- */
530
- setStatus: (actor: Actor | undefined, userId: number, status: AccountStatus) => Promise<AuthOutcome>;
531
- setRoles: (actor: Actor | undefined, userId: number, roles: unknown) => Promise<AuthOutcome>;
532
- remove: (actor: Actor | undefined, userId: number) => Promise<AuthOutcome>;
533
- /**
534
- * A session AS somebody else, for support that has to see what they see.
535
- *
536
- * Three properties make it something a deployment can live with, and all three are deliberate:
537
- *
538
- * - **It says so.** The credential carries `act` (RFC 8693), so every request made with it can be told from
539
- * one the account holder made — `Actor.impersonatedBy` is that claim, read back. A borrowed session that
540
- * is indistinguishable from a real one turns an audit log into fiction.
541
- * - **It is short and cannot renew.** Fifteen minutes by default and no refresh token, so it expires rather
542
- * than becoming a permanent second key to somebody's account.
543
- * - **It is off unless asked for**, behind its own permission — see `impersonationPermission`.
544
- *
545
- * The session is answered in the BODY and no cookie is written. Swapping the administrator's own session
546
- * cookie for this one would sign them out of the account they administer from, and getting back would mean
547
- * signing in again; whoever asked decides where to put a credential they were handed.
548
- *
549
- * One caveat a deployment has to know: a store that keeps a single session per account — no `session` table —
550
- * will overwrite the subject's own session with this one, signing them out. Anything with per-session rows,
551
- * which is what `createMysqlStore` builds, does not.
552
- */
553
- impersonate: (actor: Actor | undefined, userId: number, carrier?: CredentialCarrier) => Promise<AuthOutcome>;
554
- };
555
- /**
556
- * A CSRF token for whoever is asking, bound to their session when they have one. Answered as a body AND as the
557
- * cookie the binding writes, so a page can take whichever it finds easier to read.
558
- */
559
- issueCsrf: (sessionToken?: string) => AuthOutcome;
560
- /** Exposed so a deployment can mint a session outside the flows above — a rendered page's login form. */
561
- issueSession: (userId: number, context?: SessionContext, options?: {
562
- actingAs?: number;
563
- ttlSeconds?: number;
564
- renewable?: boolean;
565
- }) => Promise<SSRSession>;
566
- resolveActor: (carrier: CredentialCarrier) => Promise<import('./identity').ActorResult>;
567
- };
568
- export type AuthApi = ReturnType<typeof createAuthApi>;