@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,197 @@
1
+ import { OAuthFailure } from "../types.js";
2
+ import { createPublicKey } from "node:crypto";
3
+ import jwt from "jsonwebtoken";
4
+ //#region src/core/auth/oauth/providers/oidc.ts
5
+ /** How long a discovery document and a key set are trusted before they are read again. */
6
+ var CACHE_MS = 36e5;
7
+ /** The least time between two reads of a key set forced by a key it did not have: a stranger's token cannot flood it. */
8
+ var KEY_REFRESH_MS = 6e4;
9
+ var FETCH_TIMEOUT_MS = 1e4;
10
+ /** Asymmetric signatures only: an HMAC would be keyed by the client secret, and `none` by nothing. */
11
+ var SIGNING_ALGORITHMS = [
12
+ "RS256",
13
+ "RS384",
14
+ "RS512",
15
+ "PS256",
16
+ "PS384",
17
+ "PS512",
18
+ "ES256",
19
+ "ES384",
20
+ "ES512"
21
+ ];
22
+ var isSigningAlgorithm = (value) => typeof value === "string" && SIGNING_ALGORITHMS.includes(value);
23
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
24
+ /**
25
+ * An endpoint an issuer may name: HTTPS, or plain HTTP on this machine's loopback — a development identity provider,
26
+ * never one across a network, where the code and the tokens would travel readable.
27
+ */
28
+ var isSafeEndpoint = (value) => {
29
+ if (typeof value !== "string") return false;
30
+ try {
31
+ const url = new URL(value);
32
+ return url.protocol === "https:" || url.protocol === "http:" && [
33
+ "localhost",
34
+ "127.0.0.1",
35
+ "[::1]"
36
+ ].includes(url.hostname);
37
+ } catch {
38
+ return false;
39
+ }
40
+ };
41
+ var fetchJson = async (url, what) => {
42
+ let response;
43
+ try {
44
+ response = await fetch(url, {
45
+ headers: { Accept: "application/json" },
46
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
47
+ });
48
+ } catch (error) {
49
+ throw new Error(`Could not reach ${what} at ${url}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
50
+ }
51
+ if (!response.ok) throw new Error(`${what} at ${url} answered ${String(response.status)}`);
52
+ try {
53
+ return await response.json();
54
+ } catch {
55
+ throw new Error(`${what} at ${url} is not JSON`);
56
+ }
57
+ };
58
+ var discoveries = /* @__PURE__ */ new Map();
59
+ /**
60
+ * Reads an issuer's discovery document, and checks it is the issuer's: its `issuer` is the one asked for, exactly
61
+ * (OpenID Connect Discovery §4.3 — a document that names another issuer is somebody else's), and every endpoint it
62
+ * names is one a sign-in may use. Kept an hour. Throws, saying what is wrong, for whoever set the issuer to read.
63
+ */
64
+ var discoverOidc = async (issuer) => {
65
+ const cached = discoveries.get(issuer);
66
+ if (cached && Date.now() - cached.at < CACHE_MS) return cached.discovery;
67
+ if (!isSafeEndpoint(issuer)) throw new Error(`The issuer must be an https:// address (${issuer})`);
68
+ const url = `${issuer.replace(/\/+$/, "")}/.well-known/openid-configuration`;
69
+ const document = await fetchJson(url, "The discovery document");
70
+ if (!isRecord(document)) throw new Error(`The discovery document at ${url} is not an object`);
71
+ if (document.issuer !== issuer) throw new Error(`The discovery document at ${url} is for "${String(document.issuer)}", not "${issuer}": use the issuer it names`);
72
+ const missing = [
73
+ "authorization_endpoint",
74
+ "token_endpoint",
75
+ "jwks_uri"
76
+ ].filter((key) => !isSafeEndpoint(document[key]));
77
+ if (missing.length > 0) throw new Error(`The discovery document at ${url} has no https:// ${missing.join(", ")}`);
78
+ const discovery = {
79
+ issuer,
80
+ authorizationEndpoint: String(document.authorization_endpoint),
81
+ tokenEndpoint: String(document.token_endpoint),
82
+ jwksUri: String(document.jwks_uri)
83
+ };
84
+ discoveries.set(issuer, {
85
+ at: Date.now(),
86
+ discovery
87
+ });
88
+ return discovery;
89
+ };
90
+ var keySets = /* @__PURE__ */ new Map();
91
+ /** The public parts of a published key that a signature is checked with, read field by field from what was fetched. */
92
+ var publicKeyOf = (key) => {
93
+ const jwk = {};
94
+ for (const field of [
95
+ "kty",
96
+ "crv",
97
+ "n",
98
+ "e",
99
+ "x",
100
+ "y",
101
+ "alg"
102
+ ]) {
103
+ const value = key[field];
104
+ if (typeof value === "string") jwk[field] = value;
105
+ }
106
+ return jwk;
107
+ };
108
+ var readKeys = async (jwksUri) => {
109
+ const document = await fetchJson(jwksUri, "The key set");
110
+ const keys = /* @__PURE__ */ new Map();
111
+ const listed = isRecord(document) && Array.isArray(document.keys) ? document.keys : [];
112
+ for (const key of listed) if (isRecord(key) && typeof key.kid === "string" && key.use !== "enc") keys.set(key.kid, publicKeyOf(key));
113
+ keySets.set(jwksUri, {
114
+ at: Date.now(),
115
+ keys
116
+ });
117
+ return keys;
118
+ };
119
+ /** The issuer's key named `kid`: from the kept set, or the set read again when it is old or lacks it (a rotation). */
120
+ var signingKey = async (jwksUri, kid) => {
121
+ const kept = keySets.get(jwksUri);
122
+ let key = kept && Date.now() - kept.at < CACHE_MS ? kept.keys.get(kid) : void 0;
123
+ if (!key && (!kept || Date.now() - kept.at >= KEY_REFRESH_MS)) key = (await readKeys(jwksUri)).get(kid);
124
+ if (!key) throw new OAuthFailure("profile_failed", `The ID token is signed with a key the issuer does not publish (${kid})`);
125
+ return createPublicKey({
126
+ key,
127
+ format: "jwk"
128
+ });
129
+ };
130
+ var claimString = (claims, name) => {
131
+ const value = claims[name];
132
+ return typeof value === "string" ? value : "";
133
+ };
134
+ /**
135
+ * Who an ID token says signed in, once it is proved to be this sign-in's: signed by the issuer's published key with an
136
+ * asymmetric algorithm, from this issuer, for this client — and, when it names several audiences, authorized for this
137
+ * one (`azp`) — unexpired, and carrying this flow's nonce, so a token from another sign-in cannot be replayed into it.
138
+ */
139
+ var verifyIdToken = async (idToken, discovery, clientId, nonce) => {
140
+ const decoded = jwt.decode(idToken, { complete: true });
141
+ if (!decoded || typeof decoded.header.kid !== "string" || !isSigningAlgorithm(decoded.header.alg)) throw new OAuthFailure("profile_failed", "The ID token is not signed with a published asymmetric key");
142
+ const key = await signingKey(discovery.jwksUri, decoded.header.kid);
143
+ let claims;
144
+ try {
145
+ claims = jwt.verify(idToken, key, {
146
+ algorithms: [decoded.header.alg],
147
+ issuer: discovery.issuer,
148
+ audience: clientId,
149
+ clockTolerance: 60
150
+ });
151
+ } catch (error) {
152
+ throw new OAuthFailure("profile_failed", `The ID token did not verify: ${error instanceof Error ? error.message : String(error)}`);
153
+ }
154
+ if (!isRecord(claims)) throw new OAuthFailure("profile_failed", "The ID token carries no claims");
155
+ if (Array.isArray(claims.aud) && claims.aud.length > 1 && claims.azp !== clientId) throw new OAuthFailure("profile_failed", "The ID token was issued for several clients and authorized for another");
156
+ if (claims.nonce !== nonce) throw new OAuthFailure("profile_failed", "The ID token is not this sign-in’s (its nonce differs)");
157
+ return claims;
158
+ };
159
+ /**
160
+ * A provider for any OpenID Connect issuer — a company's own identity provider (Okta, Microsoft Entra ID, Google
161
+ * Workspace, Keycloak…) — from its issuer, its client and its secret. The authorization-code grant with PKCE, as every
162
+ * provider here; what makes it OpenID Connect is the profile: read from the ID token the token endpoint returns,
163
+ * verified against the issuer's published keys, never from an endpoint the access token would reach.
164
+ *
165
+ * `email_verified` is reported as the issuer states it — many corporate issuers omit it for addresses they own. What a
166
+ * deployment trusts an issuer to vouch for is the deployment's to decide in `linkAccount`.
167
+ */
168
+ var createOidcProvider = async (options) => {
169
+ const discovery = await discoverOidc(options.issuer);
170
+ return {
171
+ id: options.id,
172
+ label: options.label,
173
+ config: {
174
+ clientId: options.clientId,
175
+ clientSecret: options.clientSecret,
176
+ redirectUri: options.redirectUri
177
+ },
178
+ authorizationUrl: discovery.authorizationEndpoint,
179
+ tokenUrl: discovery.tokenEndpoint,
180
+ scope: "openid email profile",
181
+ usePkce: true,
182
+ sendsNonce: true,
183
+ async fetchProfile({ idToken, nonce }) {
184
+ if (!idToken) throw new OAuthFailure("profile_failed", `${options.label} returned no ID token: is it an OpenID Connect issuer?`);
185
+ const claims = await verifyIdToken(idToken, discovery, options.clientId, nonce);
186
+ const verified = claims.email_verified;
187
+ return {
188
+ id: claimString(claims, "sub"),
189
+ email: claimString(claims, "email").toLowerCase(),
190
+ emailVerified: verified === true || verified === "true",
191
+ username: claimString(claims, "name") || claimString(claims, "preferred_username")
192
+ };
193
+ }
194
+ };
195
+ };
196
+ //#endregion
197
+ export { createOidcProvider, discoverOidc, verifyIdToken };
@@ -1,6 +1,8 @@
1
1
  export interface OAuthFlowState {
2
2
  provider: string;
3
3
  nonce: string;
4
+ /** OpenID Connect's `nonce`, apart from `nonce` (the `state` the provider echoes): an ID token must carry this one. */
5
+ idNonce: string;
4
6
  verifier: string;
5
7
  redirect: string;
6
8
  }
@@ -20,6 +20,7 @@ var startFlow = (provider, redirect, secret, ttlSeconds) => {
20
20
  const state = {
21
21
  provider,
22
22
  nonce: base64Url(randomBytes(16)),
23
+ idNonce: base64Url(randomBytes(16)),
23
24
  verifier: createCodeVerifier(),
24
25
  redirect
25
26
  };
@@ -47,6 +48,7 @@ var consumeFlow = (cookie, provider, nonce, secret) => {
47
48
  return {
48
49
  provider: claims.provider,
49
50
  nonce: claims.nonce,
51
+ idNonce: claims.idNonce,
50
52
  verifier: claims.verifier,
51
53
  redirect: claims.redirect
52
54
  };
@@ -7,6 +7,15 @@ export interface OAuthProviderConfig {
7
7
  * The identity a provider reports back. `emailVerified` is what makes linking safe: an incoming account may only be
8
8
  * matched onto an existing one by an address the provider itself checked.
9
9
  */
10
+ /**
11
+ * What the token endpoint answered. `idToken` is OpenID Connect's — a signed statement of who signed in — and `nonce` is
12
+ * the value this flow sent with the authorization request, which an ID token must carry back to be this flow's.
13
+ */
14
+ export interface OAuthTokens {
15
+ accessToken: string;
16
+ idToken?: string;
17
+ nonce: string;
18
+ }
10
19
  export interface OAuthProfile {
11
20
  id: string;
12
21
  email: string;
@@ -32,7 +41,9 @@ export interface OAuthProvider {
32
41
  authorizationParams?: Record<string, string>;
33
42
  /** Extra headers on the token request. GitHub returns form-encoded bodies unless asked for JSON. */
34
43
  tokenHeaders?: Record<string, string>;
35
- fetchProfile: (accessToken: string) => Promise<OAuthProfile>;
44
+ /** OpenID Connect: send the flow's `nonce` with the authorization request, for the ID token to carry back. */
45
+ sendsNonce?: boolean;
46
+ fetchProfile: (tokens: OAuthTokens) => Promise<OAuthProfile>;
36
47
  /**
37
48
  * Proves a token was issued **for this application**, and not merely that it is a valid token belonging to
38
49
  * somebody. Only the credential exchange needs it, where the token arrives from a browser rather than from a code
@@ -42,10 +53,17 @@ export interface OAuthProvider {
42
53
  */
43
54
  verifyAudience?: (accessToken: string) => Promise<boolean>;
44
55
  }
45
- export type OAuthFailureReason = 'access_denied' | 'invalid_state' | 'exchange_failed' | 'profile_failed' | 'email_unverified' | 'email_missing' | 'account_inactive' | 'server_error';
56
+ export type OAuthFailureReason = 'access_denied' | 'invalid_state' | 'exchange_failed' | 'profile_failed' | 'email_unverified' | 'email_missing' | 'account_inactive'
57
+ /**
58
+ * The provider proved who this is, and the deployment does not let them in — an address outside what the provider
59
+ * may vouch for, a place with no room. `OAuthFailure.detail` says which, in the deployment's own words.
60
+ */
61
+ | 'not_permitted' | 'server_error';
46
62
  /** Carried all the way to the browser as `?error=<reason>` on the redirect target, so a front-end can tell "you
47
63
  * cancelled" from "that account is disabled" without parsing prose. */
48
64
  export declare class OAuthFailure extends Error {
49
65
  readonly reason: OAuthFailureReason;
50
- constructor(reason: OAuthFailureReason, message: string);
66
+ /** A short code of the deployment's, carried as `&detail=<code>` beside the reason, for a screen to say more by. */
67
+ readonly detail?: string;
68
+ constructor(reason: OAuthFailureReason, message: string, detail?: string);
51
69
  }
@@ -3,10 +3,13 @@
3
3
  * cancelled" from "that account is disabled" without parsing prose. */
4
4
  var OAuthFailure = class extends Error {
5
5
  reason;
6
- constructor(reason, message) {
6
+ /** A short code of the deployment's, carried as `&detail=<code>` beside the reason, for a screen to say more by. */
7
+ detail;
8
+ constructor(reason, message, detail) {
7
9
  super(message);
8
10
  this.name = "OAuthFailure";
9
11
  this.reason = reason;
12
+ if (detail !== void 0) this.detail = detail;
10
13
  }
11
14
  };
12
15
  //#endregion
@@ -101,7 +101,7 @@ var FLOWS = [
101
101
  method: "POST",
102
102
  path: "/sessions/revoke",
103
103
  requirement: "actor",
104
- run: (api, _cookies, req) => api.revokeSessions(req.actor?.id)
104
+ run: (api, _cookies, req) => api.revokeSessions(req.actor?.id, field(req, "scope"), req.hostname)
105
105
  },
106
106
  {
107
107
  method: "POST",
@@ -51,7 +51,9 @@ export type AuthFailure = 'missing' | 'malformed' | 'expired' | 'outdated' | 're
51
51
  * The password was right and the address has never answered. Separate from `inactive` because it is the one
52
52
  * refusal whose owner can clear it themselves, and a screen that cannot tell them apart has to guess.
53
53
  */
54
- | 'unverified';
54
+ | 'unverified'
55
+ /** The password was right, and the account's organization signs it in through its own single sign-on instead. */
56
+ | 'sso-required';
55
57
  export declare const authFailureMessage: Record<AuthFailure, string>;
56
58
  /**
57
59
  * How long each credential lives. One rule, applied by how much damage the credential can do and whether something
@@ -42,7 +42,8 @@ var authFailureMessage = {
42
42
  "origin-not-allowed": "Access Not Authorized",
43
43
  "domain-not-allowed": "This token is not allowed on this domain",
44
44
  inactive: "Account is not active",
45
- unverified: "Account is not verified"
45
+ unverified: "Account is not verified",
46
+ "sso-required": "Sign in with your organization’s single sign-on"
46
47
  };
47
48
  var DAY = 86400;
48
49
  /**
@@ -3,10 +3,6 @@ import { ConnectorLookups } from '../modules/connectors/resolver';
3
3
  import { ActionLookupsConfig, ConnectorLookupsConfig } from '@plitzi/sdk-shared';
4
4
  /** The connector lookups a deployment configured, each manifest checked as it is read. One per config object. */
5
5
  export declare const connectorLookupsOf: (config: ConnectorLookupsConfig) => ConnectorLookups;
6
- /**
7
- * The action lookups a deployment configured, each document checked as it is read. Asked for one, a document that is
8
- * not one is refused; listed, it is left out and said, so one broken action does not take its space's schedule down.
9
- */
10
6
  export declare const actionLookupsOf: (config: ActionLookupsConfig) => ActionLookups;
11
7
  /** The deployment's database drivers, each held to what a `db` task calls — or why one is not, as the server starts. */
12
8
  export declare const dbDriversOf: (drivers: readonly unknown[] | undefined) => ActionDbDriver[] | undefined;
@@ -66,9 +66,20 @@ var connectorLookupsOf = (config) => {
66
66
  * The action lookups a deployment configured, each document checked as it is read. Asked for one, a document that is
67
67
  * not one is refused; listed, it is left out and said, so one broken action does not take its space's schedule down.
68
68
  */
69
+ /** What a deployment answered for a visitor, as a function may read it: the public fields alone, the rest dropped. */
70
+ var visitorOf = (found) => {
71
+ if (!isRecord(found) || typeof found.id !== "number" || typeof found.username !== "string") return;
72
+ return {
73
+ id: found.id,
74
+ username: found.username,
75
+ ...typeof found.name === "string" && found.name ? { name: found.name } : {},
76
+ ...typeof found.avatar === "string" && found.avatar ? { avatar: found.avatar } : {}
77
+ };
78
+ };
69
79
  var actionLookupsOf = (config) => {
70
- const { getConnector, getData, getFunctions, getPluginFunctions, listActions } = config;
80
+ const { getConnector, getData, getFunctions, getPluginFunctions, getVisitor, listActions } = config;
71
81
  return {
82
+ ...getVisitor ? { getVisitor: async (spaceId, environment, who) => visitorOf(await getVisitor(spaceId, environment, who)) } : {},
72
83
  getAction: async (spaceId, actionId, at) => {
73
84
  const found = await config.getAction(spaceId, actionId, at);
74
85
  if (found === void 0 || found === null) return;
@@ -1,4 +1,5 @@
1
1
  import { actionLookupsOf, connectorLookupsOf } from "./configSeam.js";
2
+ import { privateOriginsOf } from "../helpers/outboundGuard.js";
2
3
  import { dataDirLookup } from "../modules/actions/runtime/projectData.js";
3
4
  import { actionsModuleFor } from "../modules/actions/moduleFor.js";
4
5
  import { connectorRscData } from "../modules/rsc/connectorRscData.js";
@@ -34,7 +35,9 @@ var withDataLookup = (config) => {
34
35
  * caches or plugin manager this one does. */
35
36
  /**
36
37
  * Fills in `getRscData` from whatever can produce a server element's data — `connectors`, `action.lookups`, the
37
- * files of `dataDir` and `publicDir` — when the deployment did not write one.
38
+ * files of `dataDir` and `publicDir`, another site's address — when the deployment did not write one. Always, then:
39
+ * a provider that asks another site needs nothing configured, and with none of the rest it drew empty until the
40
+ * browser asked.
38
41
  *
39
42
  * The lookups are already here and the assembly is entirely this package's — a resolver over `resolveRscData`.
40
43
  * Leaving it out meant every deployment passed the same lookups twice: once as config, for the write endpoint,
@@ -45,7 +48,7 @@ var withDataLookup = (config) => {
45
48
  * with no configuration missing anywhere.
46
49
  */
47
50
  var withConnectorRsc = (config) => {
48
- if (config.adapters.getRscData || !config.connectors && !config.action?.lookups && !config.publicDir && !config.dataDir) return config;
51
+ if (config.adapters.getRscData) return config;
49
52
  const resolved = {
50
53
  ...config,
51
54
  adapters: { ...config.adapters }
@@ -60,7 +63,9 @@ var withConnectorRsc = (config) => {
60
63
  actions,
61
64
  publicDir: config.publicDir,
62
65
  data: actions?.lookups.getData ?? (config.dataDir ? dataDirLookup(config.dataDir) : void 0),
63
- elementTimeoutMs: config.rsc?.elementTimeoutMs
66
+ elementTimeoutMs: config.rsc?.elementTimeoutMs,
67
+ sayFailures: config.devMode === true,
68
+ outbound: { privateOrigins: privateOriginsOf(config.outbound?.privateOrigins) }
64
69
  });
65
70
  return resolved;
66
71
  };
@@ -90,7 +95,14 @@ var createServer = ({ auth, sessionRenewal, ...config }, extensions) => {
90
95
  adapters: {
91
96
  ...auth.ssrAdapters,
92
97
  ...supplied
93
- }
98
+ },
99
+ ...config.action?.lookups && !config.action.lookups.getVisitor ? { action: {
100
+ ...config.action,
101
+ lookups: {
102
+ ...config.action.lookups,
103
+ getVisitor: (_space, _environment, who) => auth.publicAccount(who)
104
+ }
105
+ } } : {}
94
106
  }));
95
107
  const withAuthRoutes = {
96
108
  ...extensions,
@@ -12,3 +12,13 @@ export declare const portBindable: (port: number, host: string) => Promise<boole
12
12
  * this: a fixed port that is taken is an error worth stopping for.
13
13
  */
14
14
  export declare const freePort: (preferred: number, host?: string, attempts?: number) => Promise<number>;
15
+ /**
16
+ * A free port as {@link freePort} finds it, held from the other servers starting on this machine until `release`: two
17
+ * development servers started at once both found 8080 free and both bound it — one failed (a run's copies, started by
18
+ * their agents together). Each port taken is a file created only if absent (`wx`), in the system's temporary folder;
19
+ * one left by a process that died is taken again once it is older than a minute.
20
+ */
21
+ export declare const reservePort: (preferred: number, host?: string, attempts?: number) => Promise<{
22
+ port: number;
23
+ release: () => void;
24
+ }>;
@@ -1,4 +1,7 @@
1
1
  import { connect, createServer } from "node:net";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { mkdirSync, rmSync, statSync, writeFileSync } from "node:fs";
2
5
  //#region src/core/freePort.ts
3
6
  /** Whether something already answers at `port` — the one test that sees a listener on every address, not just `host`. */
4
7
  var portAnswers = (port, host) => new Promise((resolve) => {
@@ -32,5 +35,40 @@ var freePort = async (preferred, host = "127.0.0.1", attempts = 20) => {
32
35
  for (let port = preferred; port < preferred + attempts; port += 1) if (!await portAnswers(port, host) && await portBindable(port, host)) return port;
33
36
  throw new Error(`No free port between ${preferred} and ${preferred + attempts - 1} on ${host}. Set PORT to one.`);
34
37
  };
38
+ /** How long a port reserved by a server starting is held from the others: past it, the one that reserved it died. */
39
+ var RESERVED_MS = 6e4;
40
+ /**
41
+ * A free port as {@link freePort} finds it, held from the other servers starting on this machine until `release`: two
42
+ * development servers started at once both found 8080 free and both bound it — one failed (a run's copies, started by
43
+ * their agents together). Each port taken is a file created only if absent (`wx`), in the system's temporary folder;
44
+ * one left by a process that died is taken again once it is older than a minute.
45
+ */
46
+ var reservePort = async (preferred, host = "127.0.0.1", attempts = 20) => {
47
+ const folder = path.join(os.tmpdir(), "plitzi-ports");
48
+ mkdirSync(folder, { recursive: true });
49
+ for (let port = preferred; port < preferred + attempts; port += 1) {
50
+ const file = path.join(folder, `${String(port)}.lock`);
51
+ if ((() => {
52
+ try {
53
+ return Date.now() - statSync(file).mtimeMs > RESERVED_MS;
54
+ } catch {
55
+ return false;
56
+ }
57
+ })()) rmSync(file, { force: true });
58
+ let reserved = false;
59
+ try {
60
+ writeFileSync(file, String(process.pid), { flag: "wx" });
61
+ reserved = true;
62
+ } catch {}
63
+ if (reserved) {
64
+ if (!await portAnswers(port, host) && await portBindable(port, host)) return {
65
+ port,
66
+ release: () => rmSync(file, { force: true })
67
+ };
68
+ rmSync(file, { force: true });
69
+ }
70
+ }
71
+ throw new Error(`No free port between ${preferred} and ${preferred + attempts - 1} on ${host}. Set PORT to one.`);
72
+ };
35
73
  //#endregion
36
- export { freePort, portAnswers, portBindable };
74
+ export { freePort, portAnswers, portBindable, reservePort };
@@ -1,4 +1,5 @@
1
1
  import { HttpRoute, RouterLike, SocialRouteHandler } from './types';
2
+ import { Actor } from '../auth/identity';
2
3
  import { SocialAuth } from '../auth/oauth';
3
4
  import { SessionCookies } from '../auth/session';
4
5
  import { SSRSession } from '@plitzi/sdk-shared';
@@ -17,6 +18,13 @@ export interface SocialRouteHandlersOptions {
17
18
  method: string;
18
19
  path: string;
19
20
  }) => void;
21
+ /**
22
+ * A step of the deployment's own before the destination, for a signed-in person leaving through `/continue` — the
23
+ * first-sign-in questions, terms to accept: where to send them first (vetted like the destination, which it should
24
+ * carry on to), or none to go straight on. Asked of the server, so every way out of every sign-in passes it and no
25
+ * screen can skip it. One that throws is reported and the person goes straight on: a sign-in never dead-ends on it.
26
+ */
27
+ beforeContinue?: (user: Actor, destination: string) => Promise<string | undefined>;
20
28
  }
21
29
  /**
22
30
  * Social sign-in as request handlers: the provider listing, and the two legs of the authorization-code flow.
@@ -35,6 +43,6 @@ export interface SocialRouteHandlersOptions {
35
43
  * A list, so nothing has to be a router — {@link mountSocialAuthRoutes} is the loop that hangs it on one. Mount it
36
44
  * on the same base as the `/auth` flows: the paths are `/providers` and `/<provider>/{login,callback}`.
37
45
  */
38
- export declare const createSocialAuthRouteHandlers: ({ social, cookies, issueSession, onError }: SocialRouteHandlersOptions) => HttpRoute<SocialRouteHandler>[];
46
+ export declare const createSocialAuthRouteHandlers: ({ social, cookies, issueSession, onError, beforeContinue }: SocialRouteHandlersOptions) => HttpRoute<SocialRouteHandler>[];
39
47
  /** {@link createSocialAuthRouteHandlers}, hung on a router. Mount it wherever the `/auth` flows are mounted. */
40
48
  export declare const mountSocialAuthRoutes: (router: RouterLike<SocialRouteHandler>, options: SocialRouteHandlersOptions) => void;
@@ -30,7 +30,7 @@ var providerOf = (req) => {
30
30
  * A list, so nothing has to be a router — {@link mountSocialAuthRoutes} is the loop that hangs it on one. Mount it
31
31
  * on the same base as the `/auth` flows: the paths are `/providers` and `/<provider>/{login,callback}`.
32
32
  */
33
- var createSocialAuthRouteHandlers = ({ social, cookies, issueSession, onError }) => {
33
+ var createSocialAuthRouteHandlers = ({ social, cookies, issueSession, onError, beforeContinue }) => {
34
34
  const report = (error, context) => {
35
35
  if (onError) {
36
36
  onError(error, context);
@@ -63,28 +63,62 @@ var createSocialAuthRouteHandlers = ({ social, cookies, issueSession, onError })
63
63
  *
64
64
  * `?fallback=` is where to go instead when `redirect` is refused, vetted by the same judgement — a way BACK
65
65
  * from the screen, whose default ("you are signed in") is the wrong place for somebody who never signed in.
66
+ *
67
+ * A signed-in person may be sent somewhere first — `beforeContinue`, the deployment's own step — and that too is
68
+ * vetted: it is a deployment's answer, but it may carry the caller's destination on.
66
69
  */
67
70
  method: "GET",
68
71
  path: "/continue",
69
- handle: (req, res) => {
72
+ handle: async (req, res) => {
70
73
  const redirect = req.query?.redirect;
71
74
  const vetted = social.sanitizeRedirect(redirect);
72
- res.redirect(vetted === redirect ? vetted : social.sanitizeRedirect(req.query?.fallback));
73
- return Promise.resolve();
75
+ const destination = vetted === redirect ? vetted : social.sanitizeRedirect(req.query?.fallback);
76
+ let first;
77
+ if (req.user && beforeContinue) try {
78
+ first = await beforeContinue(req.user, destination);
79
+ } catch (error) {
80
+ report(error, {
81
+ method: "GET",
82
+ path: "/continue"
83
+ });
84
+ }
85
+ res.redirect(first ? social.sanitizeRedirect(first) : destination);
86
+ }
87
+ },
88
+ {
89
+ /**
90
+ * `?email=` — the single sign-on that signs that address in, by its domain: `{ provider: { id, label, url } }`,
91
+ * or a 404 that says there is none. Asked before the browser is sent anywhere, so a screen can say "no single
92
+ * sign-on for that domain" in place rather than send somebody to a dead end.
93
+ */
94
+ method: "GET",
95
+ path: "/sso",
96
+ handle: async (req, res) => {
97
+ const email = req.query?.email;
98
+ const found = await social.sso(typeof email === "string" ? email : "");
99
+ res.status("provider" in found ? 200 : 404).json(found);
74
100
  }
75
101
  },
76
102
  {
77
103
  method: "GET",
78
104
  path: "/:provider/login",
79
- handle: (req, res) => {
80
- const started = social.start(providerOf(req), req.query?.redirect);
81
- if (!started) {
82
- res.status(404).json({ error: "Unknown provider" });
83
- return Promise.resolve();
105
+ handle: async (req, res) => {
106
+ const providerId = providerOf(req);
107
+ try {
108
+ const started = await social.start(providerId, req.query?.redirect);
109
+ if (!started) {
110
+ res.status(404).json({ error: "Unknown provider" });
111
+ return;
112
+ }
113
+ cookies.writeFlow(req, res, started.stateCookie, started.ttl);
114
+ res.redirect(started.redirectTo);
115
+ } catch (error) {
116
+ report(error, {
117
+ method: "GET",
118
+ path: `/${providerId}/login`
119
+ });
120
+ res.status(502).json({ error: `${providerId} cannot be reached to sign in right now` });
84
121
  }
85
- cookies.writeFlow(req, res, started.stateCookie, started.ttl);
86
- res.redirect(started.redirectTo);
87
- return Promise.resolve();
88
122
  }
89
123
  },
90
124
  {
@@ -5,6 +5,7 @@ export interface HealthIdentity {
5
5
  role: string;
6
6
  name?: string;
7
7
  version?: string;
8
+ instance?: string;
8
9
  }
9
10
  export declare const buildHealthPayload: (identity?: Partial<HealthIdentity>) => Record<string, unknown>;
10
11
  /**
@@ -2,7 +2,8 @@
2
2
  var buildHealthPayload = (identity = {}) => ({
3
3
  Server: identity.name ?? "SDK Server",
4
4
  Version: identity.version ? `v${identity.version}` : "unknown",
5
- role: identity.role
5
+ role: identity.role,
6
+ ...identity.instance === void 0 ? {} : { Instance: identity.instance }
6
7
  });
7
8
  /**
8
9
  * Attach the generic /health endpoint to an Express-style app — a deployment whose roles are not all on the sdk-server
@@ -1,4 +1,10 @@
1
1
  import { Stage } from '../types';
2
2
  export declare const loginStage: Stage;
3
3
  export declare const logoutStage: Stage;
4
+ /**
5
+ * Signing the person out on every device (`endSessions`): `{ scope: 'site' }`, this host's sessions — a space's visitor
6
+ * ending it on their phone too; `{ scope: 'all' }`, every session of the account. Said, never assumed: a sign-out the
7
+ * page did not mean is one the person did not ask for. Guarded as a sign-out is — a page of another origin is refused.
8
+ */
9
+ export declare const logoutEverywhereStage: Stage;
4
10
  export declare const authRoutesStages: Stage[];