@plitzi/sdk-server 0.38.19 → 0.38.21

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 (242) hide show
  1. package/CHANGELOG.md +178 -0
  2. package/README.md +2 -2
  3. package/dist/actions.d.ts +6 -0
  4. package/dist/actions.js +2 -1
  5. package/dist/core/auth/createAuth.d.ts +1 -1
  6. package/dist/core/auth/csrf.js +13 -8
  7. package/dist/core/auth/tokens.d.ts +1 -1
  8. package/dist/core/configSeam.js +2 -2
  9. package/dist/core/services/functionRoutes.js +8 -2
  10. package/dist/core/services/realtime.js +5 -2
  11. package/dist/functions-api.d.ts +228 -0
  12. package/dist/functions.d.ts +4 -2
  13. package/dist/functions.js +2 -1
  14. package/dist/helpers/serverLog.d.ts +1 -1
  15. package/dist/helpers/serverLog.js +1 -1
  16. package/dist/hosts/project/plugins.js +20 -3
  17. package/dist/modules/actions/index.js +16 -3
  18. package/dist/modules/actions/jobs/index.d.ts +4 -3
  19. package/dist/modules/actions/jobs/index.js +2 -1
  20. package/dist/modules/actions/jobs/later.d.ts +2 -2
  21. package/dist/modules/actions/jobs/later.js +5 -2
  22. package/dist/modules/actions/jobs/memoryQueue.d.ts +4 -4
  23. package/dist/modules/actions/jobs/memoryQueue.js +69 -25
  24. package/dist/modules/actions/jobs/scheduler.d.ts +2 -2
  25. package/dist/modules/actions/jobs/scheduler.js +5 -2
  26. package/dist/modules/actions/jobs/worker.d.ts +6 -3
  27. package/dist/modules/actions/jobs/worker.js +104 -10
  28. package/dist/modules/actions/runtime/runAction.d.ts +5 -2
  29. package/dist/modules/actions/runtime/runAction.js +5 -3
  30. package/dist/modules/actions/runtime/signing.d.ts +7 -0
  31. package/dist/modules/actions/runtime/signing.js +23 -1
  32. package/dist/modules/actions/runtime/taskContext.d.ts +12 -3
  33. package/dist/modules/actions/runtime/taskContext.js +8 -1
  34. package/dist/modules/actions/transport/callHandler.js +3 -0
  35. package/dist/modules/actions/types.d.ts +29 -4
  36. package/dist/modules/functions/capabilities.js +107 -0
  37. package/dist/modules/functions/config.d.ts +9 -0
  38. package/dist/modules/functions/context.d.ts +2 -1
  39. package/dist/modules/functions/context.js +21 -3
  40. package/dist/modules/functions/contract.d.ts +129 -1
  41. package/dist/modules/functions/driver.js +128 -2
  42. package/dist/modules/functions/jobControl.d.ts +21 -0
  43. package/dist/modules/functions/jobControl.js +43 -0
  44. package/dist/modules/functions/jobs.d.ts +98 -0
  45. package/dist/modules/functions/jobs.js +438 -0
  46. package/dist/modules/functions/manifest.js +117 -2
  47. package/dist/modules/functions/native.js +2 -1
  48. package/dist/modules/functions/oauth.d.ts +31 -0
  49. package/dist/modules/functions/oauth.js +326 -0
  50. package/dist/modules/functions/protocol.d.ts +88 -3
  51. package/dist/modules/functions/protocol.js +2 -1
  52. package/dist/modules/functions/routes.d.ts +11 -1
  53. package/dist/modules/functions/routes.js +71 -30
  54. package/dist/modules/functions/runner/messages.d.ts +0 -1
  55. package/dist/modules/functions/runner/messages.js +40 -2
  56. package/dist/modules/functions/runner/remote.js +58 -3
  57. package/dist/modules/functions/runner/service.js +53 -7
  58. package/dist/modules/functions/sandbox/isolate.js +5 -3
  59. package/dist/modules/functions/space.js +4 -4
  60. package/dist/modules/mongo/jobQueue.d.ts +3 -3
  61. package/dist/modules/mongo/jobQueue.js +137 -26
  62. package/dist/modules/mysql/jobs/jobQueue.d.ts +3 -3
  63. package/dist/modules/mysql/jobs/jobQueue.js +97 -33
  64. package/dist/modules/mysql/jobs/schema.js +38 -11
  65. package/dist/modules/realtime/handlers.d.ts +5 -2
  66. package/dist/modules/realtime/handlers.js +15 -4
  67. package/dist/modules/realtime/index.d.ts +11 -1
  68. package/dist/modules/realtime/index.js +8 -1
  69. package/dist/modules/realtime/jobs.d.ts +20 -0
  70. package/dist/modules/realtime/jobs.js +41 -0
  71. package/dist/modules/realtime/retained.d.ts +3 -2
  72. package/dist/modules/realtime/retained.js +2 -2
  73. package/dist/modules/realtime/socket.d.ts +4 -1
  74. package/dist/modules/realtime/socket.js +2 -2
  75. package/dist/modules/rsc/resolveRscData.js +2 -1
  76. package/dist/modules/runtime/host.js +1 -1
  77. package/dist/modules/runtime/runner.d.ts +1 -1
  78. package/dist/modules/runtime/runner.js +12 -2
  79. package/dist/modules/runtime/stages.js +1 -1
  80. package/dist/modules/ssr/applySSRResult.d.ts +5 -0
  81. package/dist/modules/ssr/applySSRResult.js +8 -1
  82. package/dist/modules/ssr/buildBody.js +2 -1
  83. package/dist/modules/ssr/prepareRender.d.ts +3 -0
  84. package/dist/modules/ssr/prepareRender.js +17 -5
  85. package/dist/modules/ssr/spaceDocument.d.ts +2 -1
  86. package/dist/modules/ssr/spaceDocument.js +14 -5
  87. package/dist/modules/ssr/streamBody.js +2 -1
  88. package/package.json +6 -3
  89. package/skills/plitzi-authoring/reference/auth.md +6 -0
  90. package/skills/plitzi-authoring/reference/authoring-errors.md +1 -0
  91. package/skills/plitzi-authoring/reference/plugin-reach.md +3 -0
  92. package/skills/plitzi-authoring/reference/realtime.md +4 -0
  93. package/dist/adapters/cloudAdapters.test.d.ts +0 -1
  94. package/dist/adapters/jsonAdapters.test.d.ts +0 -1
  95. package/dist/adapters/space/space.test.d.ts +0 -1
  96. package/dist/core/auth/api.test.d.ts +0 -1
  97. package/dist/core/auth/authorize.test.d.ts +0 -1
  98. package/dist/core/auth/createAuth.test.d.ts +0 -1
  99. package/dist/core/auth/csrf.test.d.ts +0 -1
  100. package/dist/core/auth/domains.test.d.ts +0 -1
  101. package/dist/core/auth/identity.test.d.ts +0 -1
  102. package/dist/core/auth/lifecycle.test.d.ts +0 -1
  103. package/dist/core/auth/oauth/oauth.test.d.ts +0 -1
  104. package/dist/core/auth/redirects.test.d.ts +0 -1
  105. package/dist/core/auth/routes.test.d.ts +0 -1
  106. package/dist/core/auth/session.test.d.ts +0 -1
  107. package/dist/core/auth/spaceTokens.test.d.ts +0 -1
  108. package/dist/core/auth/throttle.test.d.ts +0 -1
  109. package/dist/core/auth/tokens.test.d.ts +0 -1
  110. package/dist/core/auth/totp.test.d.ts +0 -1
  111. package/dist/core/configSeam.test.d.ts +0 -1
  112. package/dist/core/createServer.actions.test.d.ts +0 -1
  113. package/dist/core/createServer.functions.test.d.ts +0 -1
  114. package/dist/core/createServer.livePages.test.d.ts +0 -1
  115. package/dist/core/createServer.notFound.test.d.ts +0 -1
  116. package/dist/core/createServer.publicData.test.d.ts +0 -1
  117. package/dist/core/createServer.test.d.ts +0 -1
  118. package/dist/core/fontStore.test.d.ts +0 -1
  119. package/dist/core/freePort.test.d.ts +0 -1
  120. package/dist/core/handlers/csrfMiddleware.test.d.ts +0 -1
  121. package/dist/core/handlers/handlers.test.d.ts +0 -1
  122. package/dist/core/handlers/socialRouteHandlers.test.d.ts +0 -1
  123. package/dist/core/http/dispatcher.test.d.ts +0 -1
  124. package/dist/core/http/stages/crossSiteWrites.test.d.ts +0 -1
  125. package/dist/core/http/stages/exchangeRoute.test.d.ts +0 -1
  126. package/dist/core/http/stages/images.test.d.ts +0 -1
  127. package/dist/core/http/stages/middlewares.test.d.ts +0 -1
  128. package/dist/core/http/stages/sessionRenewal.test.d.ts +0 -1
  129. package/dist/core/http/stages/signInRoute.test.d.ts +0 -1
  130. package/dist/core/oauth/authorize.test.d.ts +0 -1
  131. package/dist/core/oauth/register.test.d.ts +0 -1
  132. package/dist/core/oauth/token.test.d.ts +0 -1
  133. package/dist/core/requestParser.test.d.ts +0 -1
  134. package/dist/core/server/baseServer.test.d.ts +0 -1
  135. package/dist/core/server/closeOnSignals.test.d.ts +0 -1
  136. package/dist/core/server/drain.test.d.ts +0 -1
  137. package/dist/core/server/fleet/channel.test.d.ts +0 -1
  138. package/dist/core/server/fleet/fixtures/fleetServer.d.ts +0 -1
  139. package/dist/core/server/fleet/fleet.integration.test.d.ts +0 -1
  140. package/dist/core/server/fleet/relay.test.d.ts +0 -1
  141. package/dist/core/server/fleet/role.test.d.ts +0 -1
  142. package/dist/core/server/fleet/supervisor.test.d.ts +0 -1
  143. package/dist/core/services/resolve.test.d.ts +0 -1
  144. package/dist/core/staticFiles.test.d.ts +0 -1
  145. package/dist/env.test.d.ts +0 -1
  146. package/dist/helpers/atomicFile.test.d.ts +0 -1
  147. package/dist/helpers/buildResponseHelpers.test.d.ts +0 -1
  148. package/dist/helpers/buildServerInfo.test.d.ts +0 -1
  149. package/dist/helpers/cache/CompressedFileCache.test.d.ts +0 -1
  150. package/dist/helpers/cache/cacheManager.test.d.ts +0 -1
  151. package/dist/helpers/cache/keys.test.d.ts +0 -1
  152. package/dist/helpers/compress.test.d.ts +0 -1
  153. package/dist/helpers/hydrationPayload.test.d.ts +0 -1
  154. package/dist/helpers/offlineDataLoader.test.d.ts +0 -1
  155. package/dist/helpers/onAbort.test.d.ts +0 -1
  156. package/dist/helpers/outboundGuard.test.d.ts +0 -1
  157. package/dist/helpers/reportReactBuild.test.d.ts +0 -1
  158. package/dist/helpers/resolveDebugMode.test.d.ts +0 -1
  159. package/dist/helpers/serverLog.test.d.ts +0 -1
  160. package/dist/hosts/authoringHost/index.test.d.ts +0 -1
  161. package/dist/hosts/project/serveProject.test.d.ts +0 -1
  162. package/dist/layers.test.d.ts +0 -1
  163. package/dist/middlewares/spaceDeployment.test.d.ts +0 -1
  164. package/dist/modules/actions/connectorWrite.test.d.ts +0 -1
  165. package/dist/modules/actions/jobs/failureStreak.test.d.ts +0 -1
  166. package/dist/modules/actions/jobs/later.test.d.ts +0 -1
  167. package/dist/modules/actions/jobs/memoryStores.test.d.ts +0 -1
  168. package/dist/modules/actions/jobs/scheduler.test.d.ts +0 -1
  169. package/dist/modules/actions/jobs/testing/jobQueueContract.d.ts +0 -25
  170. package/dist/modules/actions/jobs/worker.test.d.ts +0 -1
  171. package/dist/modules/actions/moduleFor.test.d.ts +0 -1
  172. package/dist/modules/actions/runtime/check.test.d.ts +0 -1
  173. package/dist/modules/actions/runtime/credentials.test.d.ts +0 -1
  174. package/dist/modules/actions/runtime/email.test.d.ts +0 -1
  175. package/dist/modules/actions/runtime/fileKv.test.d.ts +0 -1
  176. package/dist/modules/actions/runtime/flags.test.d.ts +0 -1
  177. package/dist/modules/actions/runtime/guards.test.d.ts +0 -1
  178. package/dist/modules/actions/runtime/kvStore.test.d.ts +0 -1
  179. package/dist/modules/actions/runtime/namespaceKv.test.d.ts +0 -1
  180. package/dist/modules/actions/runtime/redisKv.integration.test.d.ts +0 -1
  181. package/dist/modules/actions/runtime/renderResolver.test.d.ts +0 -1
  182. package/dist/modules/actions/runtime/renderShare.test.d.ts +0 -1
  183. package/dist/modules/actions/runtime/runAction.test.d.ts +0 -1
  184. package/dist/modules/actions/runtime/runLogger.test.d.ts +0 -1
  185. package/dist/modules/actions/runtime/signing.test.d.ts +0 -1
  186. package/dist/modules/actions/taskCatalog.test.d.ts +0 -1
  187. package/dist/modules/actions/tasks/db.test.d.ts +0 -1
  188. package/dist/modules/actions/tasks/email.test.d.ts +0 -1
  189. package/dist/modules/actions/tasks/http.test.d.ts +0 -1
  190. package/dist/modules/actions/tasks/kv.test.d.ts +0 -1
  191. package/dist/modules/actions/transport/callHandler.test.d.ts +0 -1
  192. package/dist/modules/actions/transport/webhookHandler.test.d.ts +0 -1
  193. package/dist/modules/connectors/engine.test.d.ts +0 -1
  194. package/dist/modules/connectors/projection.test.d.ts +0 -1
  195. package/dist/modules/connectors/resolver.test.d.ts +0 -1
  196. package/dist/modules/functions/build.test.d.ts +0 -1
  197. package/dist/modules/functions/load.test.d.ts +0 -1
  198. package/dist/modules/functions/local.test.d.ts +0 -1
  199. package/dist/modules/functions/manifest.test.d.ts +0 -1
  200. package/dist/modules/functions/native.test.d.ts +0 -1
  201. package/dist/modules/functions/plugins.test.d.ts +0 -1
  202. package/dist/modules/functions/routes.test.d.ts +0 -1
  203. package/dist/modules/functions/runner/remote.test.d.ts +0 -1
  204. package/dist/modules/functions/sandbox/isolate.test.d.ts +0 -1
  205. package/dist/modules/functions/testing/tasksOf.d.ts +0 -4
  206. package/dist/modules/images/imageProxy.test.d.ts +0 -1
  207. package/dist/modules/images/transform.test.d.ts +0 -1
  208. package/dist/modules/mongo/stores.integration.test.d.ts +0 -1
  209. package/dist/modules/mysql/accounts.test.d.ts +0 -1
  210. package/dist/modules/mysql/jobs/stores.integration.test.d.ts +0 -1
  211. package/dist/modules/mysql/schema.test.d.ts +0 -1
  212. package/dist/modules/mysql/store.integration.test.d.ts +0 -1
  213. package/dist/modules/realtime/realtime.test.d.ts +0 -1
  214. package/dist/modules/realtime/redisPubSub.test.d.ts +0 -1
  215. package/dist/modules/realtime/retained.test.d.ts +0 -1
  216. package/dist/modules/realtime/socket.test.d.ts +0 -1
  217. package/dist/modules/rsc/connectorRscData.test.d.ts +0 -1
  218. package/dist/modules/rsc/handler.test.d.ts +0 -1
  219. package/dist/modules/rsc/publicFileResolver.test.d.ts +0 -1
  220. package/dist/modules/rsc/resolveRscData.test.d.ts +0 -1
  221. package/dist/modules/runtime/elsewhere.test.d.ts +0 -1
  222. package/dist/modules/runtime/entry.test.d.ts +0 -1
  223. package/dist/modules/runtime/inside.test.d.ts +0 -1
  224. package/dist/modules/runtime/ownServer.test.d.ts +0 -1
  225. package/dist/modules/runtime/runtime.test.d.ts +0 -1
  226. package/dist/modules/sqlite/kv.test.d.ts +0 -1
  227. package/dist/modules/ssr/draftSession.test.d.ts +0 -1
  228. package/dist/modules/ssr/loadPluginComponents.test.d.ts +0 -1
  229. package/dist/modules/ssr/metering.test.d.ts +0 -1
  230. package/dist/modules/ssr/prepareRender.test.d.ts +0 -1
  231. package/dist/modules/ssr/redirect.test.d.ts +0 -1
  232. package/dist/modules/ssr/registerExternalPlugins.test.d.ts +0 -1
  233. package/dist/modules/ssr/reportMissingPlugins.test.d.ts +0 -1
  234. package/dist/modules/ssr/resolvePageSeo.test.d.ts +0 -1
  235. package/dist/modules/ssr/spaceDocument.test.d.ts +0 -1
  236. package/dist/modules/ssr/template.test.d.ts +0 -1
  237. package/dist/modules/ssr/testing/offlineData.d.ts +0 -5
  238. package/dist/modules/ssr/vendor.test.d.ts +0 -1
  239. package/dist/plugins/compile.test.d.ts +0 -1
  240. package/dist/plugins/copy.test.d.ts +0 -1
  241. package/dist/plugins/manager.test.d.ts +0 -1
  242. package/dist/plugins/validate.test.d.ts +0 -1
@@ -0,0 +1,326 @@
1
+ import { ActionRefusal } from "../actions/runtime/errors.js";
2
+ import { fetchOutbound } from "../../helpers/outboundGuard.js";
3
+ import { FUNCTION_ROUTES_PREFIX } from "@plitzi/sdk-shared/actions";
4
+ import { isRecord } from "@plitzi/sdk-shared/helpers";
5
+ import { createHash, randomBytes } from "node:crypto";
6
+ //#region src/modules/functions/oauth.ts
7
+ /**
8
+ * OAuth 2.0 for a space's code (`ctx.oauth`): any provider, declared as data — none is known here by name.
9
+ *
10
+ * The authorization code flow with PKCE: `connect` makes the consent URL and remembers, sealed in the space's `kv` for
11
+ * ten minutes, who asked and where they go back; the provider sends the visitor to `/fn/oauth/callback`, which
12
+ * exchanges the code with the app's id and secret (a credential of the space's, resolved here) and keeps the tokens
13
+ * sealed under the connection and its owner; `fetch` writes the access token into a request, renewing it first when it
14
+ * is about to lapse and once more on a 401. Sealed with the space's own key, which no signature of `ctx.sign` reaches:
15
+ * the code reads only ciphertext, even with `ctx.kv`. The one way out is `token`, for a connection that declares
16
+ * `exposeToken`: the access token, for an SDK in the page — the refresh token never leaves.
17
+ */
18
+ /** Where the provider sends the visitor back, under `/fn` — the one address to register with every provider. */
19
+ var OAUTH_CALLBACK_PATH = "/oauth/callback";
20
+ var STATE_SECONDS = 600;
21
+ /** A token this close to lapsing is renewed before it is used. */
22
+ var RENEW_BEFORE_MS = 6e4;
23
+ /** How long an issuer's endpoints are kept once read. */
24
+ var DISCOVERY_MS = 36e5;
25
+ var OWNER = /^[\w:.@-]{1,128}$/;
26
+ var KEY_PREFIX = "plitzi:oauth";
27
+ var stateKey = (state) => `${KEY_PREFIX}:state:${state}`;
28
+ var tokenKey = (connection, owner) => `${KEY_PREFIX}:token:${connection}:${owner}`;
29
+ var discovered = /* @__PURE__ */ new Map();
30
+ var stringField = (record, key) => typeof record[key] === "string" ? record[key] : void 0;
31
+ /** The connection's endpoints: written out, or read from its issuer's OpenID metadata — what is written wins. */
32
+ var endpointsOf = async (run, connection, spec) => {
33
+ let published = {};
34
+ if (spec.issuer && (!spec.authorizeUrl || !spec.tokenUrl)) {
35
+ const kept = discovered.get(spec.issuer);
36
+ if (kept && Date.now() - kept.at < DISCOVERY_MS) published = kept.endpoints;
37
+ else {
38
+ const url = new URL(`${spec.issuer.replace(/\/+$/, "")}/.well-known/openid-configuration`);
39
+ const answer = await fetchOutbound(run.fetch, url, {
40
+ method: "GET",
41
+ signal: run.signal
42
+ });
43
+ const metadata = answer.ok ? await answer.json().catch(() => void 0) : void 0;
44
+ const authorize = isRecord(metadata) ? stringField(metadata, "authorization_endpoint") : void 0;
45
+ const token = isRecord(metadata) ? stringField(metadata, "token_endpoint") : void 0;
46
+ if (!authorize || !token) throw new Error(`OAuth connection "${connection}": ${url.href} answered ${String(answer.status)} without authorization_endpoint and token_endpoint — write authorizeUrl and tokenUrl instead`);
47
+ const revoke = isRecord(metadata) ? stringField(metadata, "revocation_endpoint") : void 0;
48
+ published = {
49
+ authorize,
50
+ token,
51
+ ...revoke ? { revoke } : {}
52
+ };
53
+ discovered.set(spec.issuer, {
54
+ at: Date.now(),
55
+ endpoints: {
56
+ authorize,
57
+ token,
58
+ ...revoke ? { revoke } : {}
59
+ }
60
+ });
61
+ }
62
+ }
63
+ const authorize = spec.authorizeUrl ?? published.authorize;
64
+ const token = spec.tokenUrl ?? published.token;
65
+ if (!authorize || !token) throw new Error(`OAuth connection "${connection}" names no issuer, nor its authorizeUrl and tokenUrl`);
66
+ const revoke = spec.revokeUrl ?? published.revoke;
67
+ return {
68
+ authorize,
69
+ token,
70
+ ...revoke ? { revoke } : {}
71
+ };
72
+ };
73
+ var sealed = (run) => {
74
+ const { seal, open } = run;
75
+ if (!seal || !open) throw new Error("This server keeps no OAuth tokens: its actions were given no signingSecret to seal them with");
76
+ return {
77
+ seal,
78
+ open
79
+ };
80
+ };
81
+ /** The app's id and secret, from the credential the connection names — resolved here, never handed to the code. */
82
+ var clientOf = async (run, connection, spec) => {
83
+ const credential = await run.credential(spec.credential);
84
+ const id = credential?.clientId;
85
+ if (!id) throw new Error(`OAuth connection "${connection}": the credential "${spec.credential}" ${credential ? "has no clientId" : "is not available for this space"} — it holds the app's clientId and clientSecret`);
86
+ return {
87
+ id,
88
+ ...credential.clientSecret ? { secret: credential.clientSecret } : {}
89
+ };
90
+ };
91
+ /** A request to the token endpoint: the grant, and the app's proof of who it is where the provider wants it. */
92
+ var tokenRequest = async (run, connection, spec, url, grant) => {
93
+ const client = await clientOf(run, connection, spec);
94
+ const form = new URLSearchParams(grant);
95
+ const headers = {
96
+ "content-type": "application/x-www-form-urlencoded",
97
+ accept: "application/json"
98
+ };
99
+ if (spec.clientAuth === "basic") headers.authorization = `Basic ${Buffer.from(`${encodeURIComponent(client.id)}:${encodeURIComponent(client.secret ?? "")}`).toString("base64")}`;
100
+ else {
101
+ form.set("client_id", client.id);
102
+ if (client.secret) form.set("client_secret", client.secret);
103
+ }
104
+ const answer = await fetchOutbound(run.fetch, new URL(url), {
105
+ method: "POST",
106
+ headers,
107
+ body: form.toString(),
108
+ signal: run.signal
109
+ });
110
+ const body = await answer.json().catch(() => void 0);
111
+ const said = isRecord(body) ? body : {};
112
+ if (!answer.ok || typeof said.access_token !== "string") {
113
+ const error = stringField(said, "error_description") ?? stringField(said, "error") ?? `status ${String(answer.status)}`;
114
+ throw new Error(`OAuth connection "${connection}": the provider refused the token (${error})`);
115
+ }
116
+ return said;
117
+ };
118
+ var tokensFrom = (said, earlier) => {
119
+ const expiresIn = typeof said.expires_in === "number" ? said.expires_in : Number(said.expires_in);
120
+ const refresh = stringField(said, "refresh_token") ?? earlier?.refresh;
121
+ const scope = stringField(said, "scope");
122
+ return {
123
+ access: said.access_token,
124
+ type: stringField(said, "token_type") ?? "Bearer",
125
+ ...refresh ? { refresh } : {},
126
+ ...Number.isFinite(expiresIn) && expiresIn > 0 ? { expiresAt: Date.now() + expiresIn * 1e3 } : {},
127
+ ...scope ? { scopes: scope.split(/[\s,]+/).filter(Boolean) } : earlier?.scopes ? { scopes: earlier.scopes } : {}
128
+ };
129
+ };
130
+ var readSealed = async (run, key, check) => {
131
+ const stored = await run.kv.get(key);
132
+ if (typeof stored !== "string") return;
133
+ const opened = sealed(run).open(stored);
134
+ let parsed;
135
+ try {
136
+ parsed = opened === void 0 ? void 0 : JSON.parse(opened);
137
+ } catch {
138
+ parsed = void 0;
139
+ }
140
+ return check(parsed) ? parsed : void 0;
141
+ };
142
+ var isTokens = (value) => isRecord(value) && typeof value.access === "string" && typeof value.type === "string";
143
+ var isPending = (value) => isRecord(value) && typeof value.connection === "string" && isRecord(value.spec) && typeof value.owner === "string" && typeof value.returnTo === "string" && typeof value.verifier === "string" && typeof value.redirectUri === "string";
144
+ /** Whose the connection is: the code's own key, or the signed-in visitor — and none is refused, saying which to name. */
145
+ var ownerOf = (run, connection, options) => {
146
+ const owner = options?.owner ?? (run.user ? `user:${String(run.user.id)}` : void 0);
147
+ if (!owner) throw new ActionRefusal(`OAuth connection "${connection}" is somebody's: sign the visitor in, or name its owner ({ owner: 'space' }, a key of your own)`);
148
+ if (!OWNER.test(owner)) throw new Error(`An OAuth owner is letters, digits and ":._@-", up to 128 — not "${owner}"`);
149
+ return owner;
150
+ };
151
+ /** A path of the space to come back to: never another site (`//evil.example`, `https://…`). */
152
+ var pathOf = (returnTo) => {
153
+ if (!returnTo.startsWith("/") || returnTo.startsWith("//") || returnTo.includes("\\")) throw new Error(`returnTo is a path of the space ("/settings"), not "${returnTo}"`);
154
+ return returnTo;
155
+ };
156
+ var withQuery = (path, params) => {
157
+ const url = new URL(path, "http://space");
158
+ Object.entries(params).forEach(([key, value]) => url.searchParams.set(key, value));
159
+ return `${url.pathname}${url.search}${url.hash}`;
160
+ };
161
+ /**
162
+ * `ctx.oauth` for one run, over the connections its code declared. `hosts` are where `fetch` may write the token — the
163
+ * same `allow.hosts` every request of the code is held to.
164
+ */
165
+ var oauthFor = (run, connections, allowed) => {
166
+ const specOf = (connection) => {
167
+ const spec = Object.hasOwn(connections, connection) ? connections[connection] : void 0;
168
+ if (!spec) {
169
+ const names = Object.keys(connections);
170
+ throw new Error(`No OAuth connection "${connection}": ${names.length ? `this space declares ${names.join(", ")}` : "declare it in oauth of defineFunctions"}`);
171
+ }
172
+ return spec;
173
+ };
174
+ const save = (connection, owner, tokens) => run.kv.set(tokenKey(connection, owner), sealed(run).seal(JSON.stringify(tokens)));
175
+ /** The connection's tokens, renewed first when they are about to lapse (or `force`d, after a 401). */
176
+ const tokensOf = async (connection, owner, force = false) => {
177
+ const tokens = await readSealed(run, tokenKey(connection, owner), isTokens);
178
+ if (!tokens) return;
179
+ if (!(tokens.expiresAt !== void 0 && tokens.expiresAt - RENEW_BEFORE_MS <= Date.now() || force) || !tokens.refresh) return tokens;
180
+ const spec = specOf(connection);
181
+ const { token } = await endpointsOf(run, connection, spec);
182
+ const renewed = tokensFrom(await tokenRequest(run, connection, spec, token, {
183
+ grant_type: "refresh_token",
184
+ refresh_token: tokens.refresh
185
+ }), tokens);
186
+ await save(connection, owner, renewed);
187
+ return renewed;
188
+ };
189
+ return {
190
+ connect: async (connection, options) => {
191
+ const spec = specOf(connection);
192
+ const owner = ownerOf(run, connection, options);
193
+ const returnTo = pathOf(options.returnTo);
194
+ if (!run.origin) throw new Error(`OAuth connection "${connection}" is made from a visitor's request: this run has none to return to`);
195
+ const { authorize } = await endpointsOf(run, connection, spec);
196
+ const client = await clientOf(run, connection, spec);
197
+ const verifier = randomBytes(32).toString("base64url");
198
+ const state = randomBytes(24).toString("base64url");
199
+ const redirectUri = `${run.origin}${FUNCTION_ROUTES_PREFIX}${OAUTH_CALLBACK_PATH}`;
200
+ const pending = {
201
+ connection,
202
+ spec,
203
+ owner,
204
+ returnTo,
205
+ verifier,
206
+ redirectUri
207
+ };
208
+ await run.kv.set(stateKey(state), sealed(run).seal(JSON.stringify(pending)), STATE_SECONDS);
209
+ const url = new URL(authorize);
210
+ const params = {
211
+ ...spec.authorizeParams,
212
+ response_type: "code",
213
+ client_id: client.id,
214
+ redirect_uri: redirectUri,
215
+ state,
216
+ code_challenge: createHash("sha256").update(verifier).digest("base64url"),
217
+ code_challenge_method: "S256",
218
+ ...spec.scopes?.length ? { scope: spec.scopes.join(" ") } : {}
219
+ };
220
+ Object.entries(params).forEach(([key, value]) => url.searchParams.set(key, value));
221
+ return { url: url.href };
222
+ },
223
+ status: async (connection, options) => {
224
+ specOf(connection);
225
+ const tokens = await readSealed(run, tokenKey(connection, ownerOf(run, connection, options)), isTokens);
226
+ return tokens ? {
227
+ connected: true,
228
+ ...tokens.scopes ? { scopes: tokens.scopes } : {},
229
+ ...tokens.expiresAt ? { expiresAt: tokens.expiresAt } : {}
230
+ } : { connected: false };
231
+ },
232
+ fetch: async (connection, input, init = {}) => {
233
+ specOf(connection);
234
+ const owner = ownerOf(run, connection, init);
235
+ const url = new URL(typeof input === "string" ? input : input.href);
236
+ allowed(url);
237
+ const send = (tokens) => fetchOutbound(run.fetch, url, {
238
+ method: init.method ?? "GET",
239
+ headers: {
240
+ ...init.headers,
241
+ authorization: `${/^bearer$/i.test(tokens.type) ? "Bearer" : tokens.type} ${tokens.access}`
242
+ },
243
+ body: init.body,
244
+ signal: run.signal
245
+ });
246
+ const tokens = await tokensOf(connection, owner);
247
+ if (!tokens) throw new ActionRefusal(`Not connected to "${connection}": ctx.oauth.connect first`);
248
+ const answer = await send(tokens);
249
+ if (answer.status !== 401 || !tokens.refresh) return answer;
250
+ const renewed = await tokensOf(connection, owner, true);
251
+ return renewed ? send(renewed) : answer;
252
+ },
253
+ disconnect: async (connection, options) => {
254
+ const spec = specOf(connection);
255
+ const owner = ownerOf(run, connection, options);
256
+ const tokens = await readSealed(run, tokenKey(connection, owner), isTokens);
257
+ if (!tokens) return false;
258
+ const { revoke } = await endpointsOf(run, connection, spec);
259
+ if (revoke) await tokenRequest(run, connection, spec, revoke, { token: tokens.refresh ?? tokens.access }).catch(() => void 0);
260
+ await run.kv.delete(tokenKey(connection, owner));
261
+ return true;
262
+ },
263
+ token: async (connection, options) => {
264
+ if (!specOf(connection).exposeToken) throw new Error(`OAuth connection "${connection}" keeps its token on the server: declare exposeToken: true on it for the code to read it, or reach its API with ctx.oauth.fetch`);
265
+ const tokens = await tokensOf(connection, ownerOf(run, connection, options));
266
+ if (!tokens) throw new ActionRefusal(`Not connected to "${connection}": ctx.oauth.connect first`);
267
+ return {
268
+ token: tokens.access,
269
+ type: tokens.type,
270
+ ...tokens.expiresAt ? { expiresAt: tokens.expiresAt } : {},
271
+ ...tokens.scopes ? { scopes: tokens.scopes } : {}
272
+ };
273
+ }
274
+ };
275
+ };
276
+ /** `ctx.oauth` where there is none to give — a plugin's code: the space's connections are the space's. */
277
+ var noOAuth = (why) => {
278
+ const refused = () => Promise.reject(new Error(why));
279
+ return {
280
+ connect: refused,
281
+ status: refused,
282
+ fetch: refused,
283
+ disconnect: refused,
284
+ token: refused
285
+ };
286
+ };
287
+ /**
288
+ * The visitor back from the provider (`/fn/oauth/callback`): the consent it remembered taken (once), the code
289
+ * exchanged, the tokens kept — and the visitor sent where the code said, told how it went. A visit with no consent
290
+ * under way is answered, not redirected: there is nowhere of the space's to send it.
291
+ */
292
+ var oauthCallback = async (run, query) => {
293
+ const state = query.get("state") ?? "";
294
+ const pending = state ? await readSealed(run, stateKey(state), isPending) : void 0;
295
+ if (state) await run.kv.delete(stateKey(state));
296
+ if (!pending) return new Response("This sign-in expired or was already used: start it again from the page.", {
297
+ status: 400,
298
+ headers: { "content-type": "text/plain; charset=utf-8" }
299
+ });
300
+ const back = (params) => new Response(null, {
301
+ status: 303,
302
+ headers: { location: withQuery(pending.returnTo, {
303
+ oauth: pending.connection,
304
+ ...params
305
+ }) }
306
+ });
307
+ const refused = query.get("error");
308
+ if (refused) return back({ oauth_error: refused });
309
+ const code = query.get("code");
310
+ if (!code) return back({ oauth_error: "no_code" });
311
+ try {
312
+ const { token } = await endpointsOf(run, pending.connection, pending.spec);
313
+ const said = await tokenRequest(run, pending.connection, pending.spec, token, {
314
+ grant_type: "authorization_code",
315
+ code,
316
+ redirect_uri: pending.redirectUri,
317
+ code_verifier: pending.verifier
318
+ });
319
+ await run.kv.set(tokenKey(pending.connection, pending.owner), sealed(run).seal(JSON.stringify(tokensFrom(said))));
320
+ } catch (error) {
321
+ return back({ oauth_error: error instanceof Error ? error.message.slice(0, 200) : "exchange_failed" });
322
+ }
323
+ return back({ oauth_result: "connected" });
324
+ };
325
+ //#endregion
326
+ export { OAUTH_CALLBACK_PATH, noOAuth, oauthCallback, oauthFor };
@@ -55,13 +55,43 @@ export type WireResponse = {
55
55
  headers: WireHeaders;
56
56
  body: WireBody | null;
57
57
  };
58
+ /**
59
+ * A route's answer as it is written rather than once it is done — what a space's runtime answers, so a route there
60
+ * streams as an endpoint does, with the platform's `ctx` all the same: its head at once, its body as the code writes it.
61
+ * Never JSON: it lives in the process that holds the run, its body fed by the runner's `chunk` messages.
62
+ */
63
+ export type StreamedRouteAnswer = {
64
+ streamed: true;
65
+ status: number;
66
+ statusText: string;
67
+ headers: WireHeaders;
68
+ body: ReadableStream<Uint8Array>;
69
+ };
70
+ export declare const isStreamedRouteAnswer: (value: unknown) => value is StreamedRouteAnswer;
58
71
  /** Who and what an invocation is for: the facts a {@link FunctionContext} carries, sent with it rather than asked for. */
59
72
  export type FunctionInvocationContext = Pick<FunctionContext, 'spaceId' | 'environment' | 'runId' | 'trigger' | 'callerId' | 'user'>;
73
+ /** The slice of a job an invocation runs: which job, what it saved so far, and which attempt this is. */
74
+ export type FunctionJobSlice = {
75
+ id: string;
76
+ state?: unknown;
77
+ attempt: number;
78
+ };
60
79
  export type FunctionInvocation = {
61
80
  kind: 'task';
62
81
  name: string;
63
82
  params: Record<string, unknown>;
64
83
  context: FunctionInvocationContext;
84
+ } | {
85
+ kind: 'job';
86
+ name: string;
87
+ input: Record<string, unknown>;
88
+ job: FunctionJobSlice;
89
+ context: FunctionInvocationContext;
90
+ /**
91
+ * How long the code gets to save and return once the slice is asked to end (`signal` aborting with why: the
92
+ * `FunctionJobStop`), before the runner cuts it.
93
+ */
94
+ graceMs: number;
65
95
  } | {
66
96
  kind: 'route';
67
97
  key: string;
@@ -114,6 +144,47 @@ export type FunctionCall = {
114
144
  } | {
115
145
  op: 'data';
116
146
  file: string;
147
+ } | {
148
+ op: 'oauth';
149
+ method: 'connect';
150
+ connection: string;
151
+ returnTo: string;
152
+ owner?: string;
153
+ } | {
154
+ op: 'oauth';
155
+ method: 'status' | 'disconnect' | 'token';
156
+ connection: string;
157
+ owner?: string;
158
+ } | {
159
+ op: 'oauth';
160
+ method: 'fetch';
161
+ connection: string;
162
+ url: string;
163
+ init: Omit<FunctionFetchInit, 'credential'>;
164
+ owner?: string;
165
+ }
166
+ /** `ctx.jobs`: the space's jobs, started and stopped by its code. */
167
+ | {
168
+ op: 'jobs';
169
+ method: 'start';
170
+ name: string;
171
+ input: Record<string, unknown>;
172
+ key?: string;
173
+ } | {
174
+ op: 'jobs';
175
+ method: 'get' | 'pause' | 'resume' | 'cancel';
176
+ id: string;
177
+ }
178
+ /** A job's `save` and `report`: what its slice keeps, and how far it is. */
179
+ | {
180
+ op: 'job';
181
+ method: 'save';
182
+ state: unknown;
183
+ } | {
184
+ op: 'job';
185
+ method: 'report';
186
+ fraction: number;
187
+ step?: string;
117
188
  }
118
189
  /** Each value as the guest could send it: JSON, with what JSON cannot say already said as text. */
119
190
  | {
@@ -138,8 +209,9 @@ export type FunctionRunner = {
138
209
  /** Loads a bundle and answers what it declares — when the space's functions are saved, never on a run. */
139
210
  describe: (bundle: FunctionsBundle) => Promise<unknown>;
140
211
  /**
141
- * Runs one task or route of a bundle. Each call the code makes is handed to `answer`, whose result goes back to it;
142
- * `signal` aborting ends the invocation. Resolves with what the code returned, and rejects with a
212
+ * Runs one task, route or slice of a job of a bundle. Each call the code makes is handed to `answer`, whose result
213
+ * goes back to it; `signal` aborting ends the invocation — its `reason` handed to the code as the signal's, and a
214
+ * job's slice given its `graceMs` to save before it is cut. Resolves with what the code returned, and rejects with a
143
215
  * {@link FunctionFailure}.
144
216
  */
145
217
  invoke: (request: FunctionInvokeRequest) => Promise<unknown>;
@@ -203,12 +275,25 @@ export type RunnerRequestMessage = {
203
275
  type: 'answer';
204
276
  id: number;
205
277
  answer: FunctionAnswer;
206
- } | {
278
+ }
279
+ /** The invocation is asked to end — for a job's slice, with why (a `FunctionJobStop`). */
280
+ | {
207
281
  type: 'abort';
282
+ reason?: string;
208
283
  };
209
284
  export type RunnerResponseMessage = {
210
285
  type: 'needBundle';
211
286
  }
287
+ /** A route answering as it writes: its head, then each `chunk` of its body, then `done`. */
288
+ | {
289
+ type: 'head';
290
+ status: number;
291
+ statusText: string;
292
+ headers: WireHeaders;
293
+ } | {
294
+ type: 'chunk';
295
+ chunk: WireBody;
296
+ }
212
297
  /** As the code sent it: the platform reads it, trusting no runner to have. */
213
298
  | {
214
299
  type: 'call';
@@ -5,6 +5,7 @@
5
5
  * platform that calls it.
6
6
  */
7
7
  var FUNCTIONS_PROTOCOL = 1;
8
+ var isStreamedRouteAnswer = (value) => typeof value === "object" && value !== null && "streamed" in value && value.streamed === true && "body" in value && value.body instanceof ReadableStream;
8
9
  /** An invocation that did not answer, and why ({@link FunctionFailureReason}). */
9
10
  var FunctionFailure = class extends Error {
10
11
  reason;
@@ -15,4 +16,4 @@ var FunctionFailure = class extends Error {
15
16
  }
16
17
  };
17
18
  //#endregion
18
- export { FUNCTIONS_PROTOCOL, FunctionFailure };
19
+ export { FUNCTIONS_PROTOCOL, FunctionFailure, isStreamedRouteAnswer };
@@ -11,11 +11,21 @@ export type RouteVisit = {
11
11
  user?: SSRUser;
12
12
  /** `user:<id>` or `ip:<address>`, as for an action call. */
13
13
  callerId: string;
14
+ /** The public origin the request reached (`https://shop.example.com`), as the server resolved it. */
15
+ origin?: string;
14
16
  signal: AbortSignal;
15
17
  };
18
+ /**
19
+ * What a route answered, and whether it is written as it comes: a runtime's route and the deployment's own code may
20
+ * stream, and are passed on as they are written; a sandbox's is whole, and sent as one.
21
+ */
22
+ export type RouteAnswer = {
23
+ response: Response;
24
+ streamed: boolean;
25
+ };
16
26
  export type RouteHandler = {
17
27
  key: string;
18
- handle: (request: Request) => Promise<Response>;
28
+ handle: (request: Request) => Promise<RouteAnswer>;
19
29
  };
20
30
  /** The first of `keys` that answers the request, with its params — declared order, as a space reads them. */
21
31
  export declare const matchRoute: (keys: readonly string[], method: string, path: string) => {
@@ -1,14 +1,20 @@
1
1
  import { serverLog } from "../../helpers/serverLog.js";
2
2
  import { isActionRefusal } from "../actions/runtime/errors.js";
3
+ import { OAUTH_CALLBACK_PATH, oauthCallback } from "./oauth.js";
3
4
  import { pluginOfPath } from "./scope.js";
4
5
  import { functionContextFor } from "./context.js";
6
+ import { answerCall, readCall, responseOf, wireRequestOf, wireResponseFrom } from "./capabilities.js";
5
7
  import { functionLimitsFor } from "./config.js";
8
+ import { FunctionFailure, isStreamedRouteAnswer } from "./protocol.js";
9
+ import { jobsManifestOf } from "./jobs.js";
6
10
  import { parseRouteKey, reservedRouteProblem } from "./manifest.js";
7
- import { answerCall, readCall, responseOf, wireRequestOf, wireResponseFrom } from "./capabilities.js";
8
- import { FunctionFailure } from "./protocol.js";
9
11
  import { PLUGIN_ROUTES_SEGMENT } from "@plitzi/sdk-shared/actions";
10
12
  import { randomUUID } from "node:crypto";
11
13
  //#region src/modules/functions/routes.ts
14
+ var whole = (response) => ({
15
+ response,
16
+ streamed: false
17
+ });
12
18
  /** A route key's params from a path it answers, or nothing when it does not answer it. */
13
19
  var matchKey = (key, method, path) => {
14
20
  const segments = path.replace(/^\/+/, "").split("/");
@@ -78,7 +84,9 @@ var failed = (visit, key, error) => {
78
84
  var routesOf = (definition) => Object.entries(definition.routes ?? {}).map(([key, handler]) => ({
79
85
  key,
80
86
  handler,
81
- hosts: definition.allow?.hosts ?? []
87
+ hosts: definition.allow?.hosts ?? [],
88
+ ...definition.oauth ? { oauth: definition.oauth } : {},
89
+ jobs: jobsManifestOf(definition)
82
90
  }));
83
91
  /**
84
92
  * The route a request reaches, if one does: under `/plugins/<type>/`, that plugin's — this server's own, then the one
@@ -89,23 +97,26 @@ var createRoutes = ({ config, plugins = () => new Map(Object.entries(config.plug
89
97
  const native = (config.native ?? []).flatMap(routesOf);
90
98
  const reserved = native.find((route) => parseRouteKey(route.key)?.segments[0] === PLUGIN_ROUTES_SEGMENT);
91
99
  if (reserved) throw new Error(`[Functions] ${reservedRouteProblem(reserved.key)}`);
92
- const contextOf = (visit, key, hosts, scope) => {
93
- const ctx = taskContext({
94
- runId: randomUUID(),
95
- spaceId: visit.spaceId,
96
- environment: visit.environment,
97
- trigger: "call",
98
- callerId: visit.callerId,
99
- ...visit.user ? { user: visit.user } : {},
100
- ...visit.at ? { at: visit.at } : {}
101
- }, visit.signal, [`route:${key}`]);
100
+ /** The run's own context for a request of this visit: the space's kv, its credentials, its key. */
101
+ const runOf = (visit, key) => taskContext({
102
+ runId: randomUUID(),
103
+ spaceId: visit.spaceId,
104
+ environment: visit.environment,
105
+ trigger: "call",
106
+ callerId: visit.callerId,
107
+ ...visit.user ? { user: visit.user } : {},
108
+ ...visit.at ? { at: visit.at } : {},
109
+ ...visit.origin ? { origin: visit.origin } : {}
110
+ }, visit.signal, [`route:${key}`]);
111
+ const contextOf = (visit, key, hosts, scope, oauth, jobs) => {
112
+ const ctx = runOf(visit, key);
102
113
  return {
103
114
  ...functionContextFor({
104
115
  ...ctx,
105
116
  log: (line) => {
106
117
  serverLog.info("Functions", `route ${key} of space ${String(visit.spaceId)}: ${line}`);
107
118
  }
108
- }, hosts, scope),
119
+ }, hosts, scope, oauth, jobs),
109
120
  trigger: "route"
110
121
  };
111
122
  };
@@ -119,12 +130,15 @@ var createRoutes = ({ config, plugins = () => new Map(Object.entries(config.plug
119
130
  key: match.key,
120
131
  handle: async (request) => {
121
132
  try {
122
- return withoutCookies(await handler(withoutCredentials(request), {
123
- ...contextOf(visit, match.key, route.hosts, scope),
124
- params: match.params
125
- }));
133
+ return {
134
+ response: withoutCookies(await handler(withoutCredentials(request), {
135
+ ...contextOf(visit, match.key, route.hosts, scope, route.oauth, route.jobs),
136
+ params: match.params
137
+ })),
138
+ streamed: true
139
+ };
126
140
  } catch (error) {
127
- return failed(visit, match.key, error);
141
+ return whole(failed(visit, match.key, error));
128
142
  }
129
143
  }
130
144
  };
@@ -139,10 +153,19 @@ var createRoutes = ({ config, plugins = () => new Map(Object.entries(config.plug
139
153
  key: match.key,
140
154
  handle: async (request) => {
141
155
  const refusal = await config.admit?.(visit.spaceId);
142
- if (refusal) return Response.json({ error: refusal }, { status: 429 });
143
- const fnCtx = contextOf(visit, match.key, functions.manifest.hosts, scope);
156
+ if (refusal) return whole(Response.json({ error: refusal }, { status: 429 }));
157
+ const fnCtx = contextOf(visit, match.key, functions.manifest.hosts, scope, functions.manifest.oauth, functions.manifest.jobs);
144
158
  let ok = false;
145
159
  let spent;
160
+ let streaming = false;
161
+ const meter = (usage, done) => {
162
+ config.onUsage?.({
163
+ spaceId: visit.spaceId,
164
+ task: usageName,
165
+ ok: done,
166
+ usage
167
+ });
168
+ };
146
169
  try {
147
170
  const value = await runner.invoke({
148
171
  bundle: functions.bundle,
@@ -164,20 +187,27 @@ var createRoutes = ({ config, plugins = () => new Map(Object.entries(config.plug
164
187
  answer: (call) => answerCall(fnCtx, readCall(call)),
165
188
  signal: visit.signal,
166
189
  onUsage: (usage) => {
167
- spent = usage;
190
+ if (streaming) meter(usage, true);
191
+ else spent = usage;
168
192
  }
169
193
  });
170
194
  ok = true;
171
- return withoutCookies(responseOf(wireResponseFrom(value)));
195
+ if (isStreamedRouteAnswer(value)) {
196
+ streaming = true;
197
+ return {
198
+ response: withoutCookies(new Response(value.body, {
199
+ status: value.status,
200
+ statusText: value.statusText,
201
+ headers: value.headers
202
+ })),
203
+ streamed: true
204
+ };
205
+ }
206
+ return whole(withoutCookies(responseOf(wireResponseFrom(value))));
172
207
  } catch (error) {
173
- return failed(visit, match.key, error);
208
+ return whole(failed(visit, match.key, error));
174
209
  } finally {
175
- if (spent) config.onUsage?.({
176
- spaceId: visit.spaceId,
177
- task: usageName,
178
- ok,
179
- usage: spent
180
- });
210
+ if (spent) meter(spent, ok);
181
211
  }
182
212
  }
183
213
  };
@@ -192,6 +222,17 @@ var createRoutes = ({ config, plugins = () => new Map(Object.entries(config.plug
192
222
  return {
193
223
  /** The route that answers `method path` (the path after `/fn`), for this visit — or none. */
194
224
  routeFor: async (visit, method, path) => {
225
+ if (method === "GET" && path === "/oauth/callback") return {
226
+ key: `GET ${OAUTH_CALLBACK_PATH}`,
227
+ handle: async (request) => {
228
+ const run = runOf(visit, `GET ${OAUTH_CALLBACK_PATH}`);
229
+ try {
230
+ return whole(await oauthCallback(run, new URL(request.url).searchParams));
231
+ } catch (error) {
232
+ return whole(failed(visit, `GET ${OAUTH_CALLBACK_PATH}`, error));
233
+ }
234
+ }
235
+ };
195
236
  const addressed = pluginOfPath(path);
196
237
  if (addressed) return pluginRoute(visit, method, addressed);
197
238
  return loadedRoute(native, visit, method, path) ?? runnerRoute(await getFunctions?.(visit.spaceId, visit.at), visit, method, path);
@@ -1,5 +1,4 @@
1
1
  import { RunnerRequestMessage, RunnerResponseMessage } from '../protocol';
2
2
  /** What the platform sent the runner, or nothing when it is not one of the protocol's messages. */
3
3
  export declare const readRequestMessage: (data: string) => RunnerRequestMessage | undefined;
4
- /** What the runner sent the platform, or nothing when it is not one of the protocol's messages. */
5
4
  export declare const readResponseMessage: (data: string) => RunnerResponseMessage | undefined;