@plitzi/sdk-server 0.38.21 → 0.38.23

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 (31) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/dist/core/auth/createAuth.d.ts +1 -1
  3. package/dist/core/auth/tokens.d.ts +1 -1
  4. package/dist/core/configSeam.js +12 -2
  5. package/dist/functions-api.d.ts +21 -3
  6. package/dist/hosts/project/serveProject.d.ts +7 -0
  7. package/dist/hosts/project/serveProject.js +19 -1
  8. package/dist/modules/actions/index.js +1 -1
  9. package/dist/modules/actions/runtime/errors.d.ts +9 -1
  10. package/dist/modules/actions/runtime/errors.js +12 -2
  11. package/dist/modules/actions/runtime/taskContext.js +2 -0
  12. package/dist/modules/actions/types.d.ts +4 -2
  13. package/dist/modules/functions/capabilities.js +65 -12
  14. package/dist/modules/functions/config.d.ts +11 -0
  15. package/dist/modules/functions/context.js +2 -2
  16. package/dist/modules/functions/contract.d.ts +13 -2
  17. package/dist/modules/functions/driver.js +42 -7
  18. package/dist/modules/functions/manifest.d.ts +2 -0
  19. package/dist/modules/functions/manifest.js +1 -1
  20. package/dist/modules/functions/oauth.d.ts +1 -1
  21. package/dist/modules/functions/oauth.js +39 -18
  22. package/dist/modules/functions/protocol.d.ts +27 -3
  23. package/dist/modules/functions/protocol.js +14 -1
  24. package/dist/modules/functions/routes.js +2 -2
  25. package/dist/modules/functions/runner/messages.js +6 -3
  26. package/dist/modules/functions/runner/remote.js +2 -5
  27. package/dist/modules/functions/runner/service.js +2 -2
  28. package/dist/modules/functions/sandbox/guest.js +5 -3
  29. package/dist/modules/functions/sandbox/isolate.js +2 -5
  30. package/dist/modules/functions/space.js +1 -1
  31. package/package.json +3 -3
package/CHANGELOG.md CHANGED
@@ -1,5 +1,46 @@
1
1
  # @plitzi/sdk-server
2
2
 
3
+ ## 0.38.23
4
+
5
+ ### Patch Changes
6
+
7
+ - 1e93ac7: ## Server
8
+
9
+ - **The project's server sends OAuth providers back to its loopback** (`@plitzi/sdk-server`) — PZ-160. 0.38.22 chose
10
+ `publicUrl`, which without `PUBLIC_URL` is the machine's address on the network: a private IP the router may change and
11
+ providers refuse, so a project opened to the network could no longer connect a new account. The callback origin is now
12
+ `127.0.0.1` unless `PUBLIC_URL` is HTTPS, and `serverOptions.functions.oauth.callbackOrigin` names another without
13
+ touching `PUBLIC_URL`. Open to the network with a loopback callback, the server says that a sign-in another device
14
+ starts needs a name of its own.
15
+
16
+ - Updated dependencies [1e93ac7]
17
+ - @plitzi/plitzi-sdk@0.38.23
18
+ - @plitzi/sdk-shared@0.38.23
19
+
20
+ ## 0.38.22
21
+
22
+ ### Patch Changes
23
+
24
+ - 19fbc45: ## Server
25
+
26
+ - **`ctx.oauth`, after a project moved onto it** (`@plitzi/sdk-server`, `@plitzi/sdk-shared`) — PZ-155..158.
27
+ `functions.oauth.callbackOrigin` fixes the one address providers send a visitor back to, on a server of one space
28
+ reached on several: `serveProject` sets it to the address people reach it on, or its loopback `127.0.0.1` when that is
29
+ plain HTTP (providers refuse `http` past loopback, and `localhost`), and prints it as it starts; the callback then sends
30
+ the visitor on to `returnTo` on the address they started from — its `location` is absolute now. `connect(name,
31
+ { returnTo, authorizeParams })` adds to the connection's parameters for one consent (`prompt: 'select_account'`), and
32
+ refuses one the platform writes. `ctx.fetch` and `ctx.oauth.fetch` take `init.signal`: in the sandbox and a runtime the
33
+ request is numbered and the code's `abort` cuts it on the platform. `ActionRefusal` takes `{ code }`; `ctx.oauth`
34
+ refuses with `oauth-not-connected` and `oauth-no-owner`.
35
+ - **A refusal of the platform's stays one across the sandbox** (`@plitzi/sdk-server`). A call answered with an
36
+ `ActionRefusal` crossed the isolate, the runner service and a runtime as a plain error: caught, the code could not tell
37
+ it apart; uncaught, a route answered 500 `This route failed` instead of 400 and the reason. The answer carries
38
+ `refused` and `code` now, and the code catches the refusal it was thrown.
39
+
40
+ - Updated dependencies [19fbc45]
41
+ - @plitzi/plitzi-sdk@0.38.22
42
+ - @plitzi/sdk-shared@0.38.22
43
+
3
44
  ## 0.38.21
4
45
 
5
46
  ### Patch Changes
@@ -69,7 +69,7 @@ export interface AuthConfig {
69
69
  */
70
70
  export declare const createAuth: (config: AuthConfig) => {
71
71
  tokens: {
72
- lifetimes: Record<"refresh" | "access" | "session" | "widget" | "agent" | "mfaChallenge", number>;
72
+ lifetimes: Record<"session" | "refresh" | "access" | "widget" | "agent" | "mfaChallenge", number>;
73
73
  issuer: string;
74
74
  generateUserToken: (userId: number | string, { actingAs, ttlSeconds }?: import('./tokens').UserTokenOptions) => string;
75
75
  generateRefreshToken: (userId: number | string) => string;
@@ -174,7 +174,7 @@ export interface SpaceTokenOptions {
174
174
  * server issues under their own and nothing they mint is worth anything here, or the other way round.
175
175
  */
176
176
  export declare const createTokens: (config: TokenConfig) => {
177
- lifetimes: Record<"refresh" | "access" | "session" | "widget" | "agent" | "mfaChallenge", number>;
177
+ lifetimes: Record<"session" | "refresh" | "access" | "widget" | "agent" | "mfaChallenge", number>;
178
178
  /** What this deployment mints under. Read by anything that has to name the deployment — an enrolment URI, say. */
179
179
  issuer: string;
180
180
  generateUserToken: (userId: number | string, { actingAs, ttlSeconds }?: UserTokenOptions) => string;
@@ -112,7 +112,15 @@ var isFunction = (value) => typeof value === "function";
112
112
  /** A driver as `createDbDrivers` builds one: the engine a credential names, and how to query it. */
113
113
  var isDbDriver = (value) => isRecord(value) && typeof value.engine === "string" && isFunction(value.query);
114
114
  /** The functions config as `@plitzi/sdk-server/functions` builds it: native and plugin definitions, a runner, ceilings. */
115
- var isFunctionsConfig = (value) => isRecord(value) && (value.native === void 0 || Array.isArray(value.native) && value.native.every(isRecord)) && (value.plugins === void 0 || isRecord(value.plugins) && Object.values(value.plugins).every(isRecord)) && (value.runner === void 0 || isRecord(value.runner) && isFunction(value.runner.describe) && isFunction(value.runner.invoke)) && (value.limits === void 0 || isRecord(value.limits)) && (value.jobs === void 0 || isRecord(value.jobs) && (value.jobs.limitsFor === void 0 || isFunction(value.jobs.limitsFor)));
115
+ var isFunctionsConfig = (value) => isRecord(value) && (value.native === void 0 || Array.isArray(value.native) && value.native.every(isRecord)) && (value.plugins === void 0 || isRecord(value.plugins) && Object.values(value.plugins).every(isRecord)) && (value.runner === void 0 || isRecord(value.runner) && isFunction(value.runner.describe) && isFunction(value.runner.invoke)) && (value.limits === void 0 || isRecord(value.limits)) && (value.jobs === void 0 || isRecord(value.jobs) && (value.jobs.limitsFor === void 0 || isFunction(value.jobs.limitsFor))) && (value.oauth === void 0 || isRecord(value.oauth) && (value.oauth.callbackOrigin === void 0 || typeof value.oauth.callbackOrigin === "string"));
116
+ /** Whether a value is an origin as a browser writes it — `https://example.com`, no path or trailing slash. */
117
+ var isOrigin = (value) => {
118
+ try {
119
+ return new URL(value).origin === value;
120
+ } catch {
121
+ return false;
122
+ }
123
+ };
116
124
  /** The deployment's database drivers, each held to what a `db` task calls — or why one is not, as the server starts. */
117
125
  var dbDriversOf = (drivers) => {
118
126
  if (drivers === void 0) return;
@@ -123,7 +131,9 @@ var dbDriversOf = (drivers) => {
123
131
  /** The deployment's functions config, held to what runs a space's code — or why it is not, as the server starts. */
124
132
  var functionsConfigOf = (config) => {
125
133
  if (config === void 0) return;
126
- if (!isFunctionsConfig(config)) throw new Error("`functions` is not what @plitzi/sdk-server/functions configures: `native` definitions, `plugins` by type, a `runner` with `describe` and `invoke`, `limits`, `jobs` with a `limitsFor` function.");
134
+ if (!isFunctionsConfig(config)) throw new Error("`functions` is not what @plitzi/sdk-server/functions configures: `native` definitions, `plugins` by type, a `runner` with `describe` and `invoke`, `limits`, `jobs` with a `limitsFor` function, `oauth` with a `callbackOrigin`.");
135
+ const callbackOrigin = config.oauth?.callbackOrigin;
136
+ if (callbackOrigin !== void 0 && !isOrigin(callbackOrigin)) throw new Error(`\`functions.oauth.callbackOrigin\` is an origin, as a browser writes it — \`https://example.com\`, no path or slash — not "${callbackOrigin}"`);
127
137
  return config;
128
138
  };
129
139
  //#endregion
@@ -65,9 +65,15 @@ declare type ActionKvStore = {
65
65
  * URL, a credential's name, and a page is shown to anybody. This one says, by its type, that its message was written
66
66
  * to be read. A run that ends on it answers `status: 'failed'` with the message as `error`, which a page's flow reads
67
67
  * as `{{ step.error }}` — the same place a refusal before the run began puts its own.
68
+ *
69
+ * `code` names the refusal for code that catches it (`oauth-not-connected`): what to tell apart by, never the message,
70
+ * which is written for a person and may change.
68
71
  */
69
72
  export declare class ActionRefusal extends Error {
70
- constructor(message: string);
73
+ code?: string;
74
+ constructor(message: string, options?: {
75
+ code?: string;
76
+ });
71
77
  }
72
78
 
73
79
  /**
@@ -158,6 +164,8 @@ export declare type FunctionFetchInit = {
158
164
  headers?: Record<string, string>;
159
165
  body?: string;
160
166
  credential?: string;
167
+ /** Cuts the request short when it aborts (`AbortSignal.timeout(12_000)`); the run's own end cuts it regardless. */
168
+ signal?: AbortSignal;
161
169
  };
162
170
 
163
171
  /** A job of the space's: work longer than a request, run on the server slice by slice until it answers. */
@@ -261,17 +269,21 @@ export declare type FunctionOAuth = {
261
269
  /**
262
270
  * Where to send the visitor to consent (authorization code, PKCE). They come back to `/fn/oauth/callback` — the
263
271
  * address to register with the provider, on the space's host — and from there to `returnTo`, a path of the space,
264
- * with `?oauth=<connection>&oauth_result=connected` or `&oauth_error=<what>`.
272
+ * with `?oauth=<connection>&oauth_result=connected` or `&oauth_error=<what>`. `authorizeParams` adds to the
273
+ * connection's for this consent alone — `{ prompt: 'select_account' }` to choose another account — never one the
274
+ * platform writes (`state`, `redirect_uri`, `scope`, PKCE's).
265
275
  */
266
276
  connect: (connection: string, options: {
267
277
  returnTo: string;
278
+ authorizeParams?: Record<string, string>;
268
279
  } & FunctionOAuthOwner) => Promise<{
269
280
  url: string;
270
281
  }>;
271
282
  status: (connection: string, options?: FunctionOAuthOwner) => Promise<FunctionOAuthStatus>;
272
283
  /**
273
284
  * A request to the provider's API with the token written in (`Authorization: Bearer`), renewed when it is about to
274
- * lapse and once more if the answer is 401. Only to the hosts the space declared (`allow.hosts`).
285
+ * lapse and once more if the answer is 401. Only to the hosts the space declared (`allow.hosts`). With nobody
286
+ * connected it refuses, `code: 'oauth-not-connected'` ({@link FunctionOAuthRefusal}).
275
287
  */
276
288
  fetch: (connection: string, url: string | URL, init?: Omit<FunctionFetchInit, 'credential'> & FunctionOAuthOwner) => Promise<Response>;
277
289
  /** Forgets the connection — revoked at the provider when it says where — and answers whether there was one. */
@@ -323,6 +335,12 @@ export declare type FunctionOAuthOwner = {
323
335
  owner?: string;
324
336
  };
325
337
 
338
+ /**
339
+ * The `code` of a refusal `ctx.oauth` throws (an `ActionRefusal`), to tell it apart by: `oauth-not-connected` — no
340
+ * account connected for that owner yet, so `connect` first; `oauth-no-owner` — nobody signed in and no `owner` named.
341
+ */
342
+ export declare type FunctionOAuthRefusal = 'oauth-not-connected' | 'oauth-no-owner';
343
+
326
344
  /** What `ctx.oauth.status` says of a connection — never its token. */
327
345
  export declare type FunctionOAuthStatus = {
328
346
  connected: boolean;
@@ -1,6 +1,7 @@
1
1
  import { AuthoredDocuments } from './watchSpace';
2
2
  import { ServerConfig } from '../../core/createServer';
3
3
  import { ConnectorManifest } from '../../modules/connectors';
4
+ import { FunctionsConfig } from '../../modules/functions/config';
4
5
  import { ActionEntry, SSRServer } from '@plitzi/sdk-shared';
5
6
  /** What `serveProject` sets itself, from the project's layout — so never the project's options'. */
6
7
  type SetByProject = 'port' | 'health' | 'adapters' | 'plugins' | 'publicDir' | 'dataDir' | 'functions' | 'action';
@@ -14,6 +15,12 @@ type SetByProject = 'port' | 'health' | 'adapters' | 'plugins' | 'publicDir' | '
14
15
  */
15
16
  export type ProjectServerOptions = Partial<Omit<ServerConfig, SetByProject>> & {
16
17
  action?: Omit<NonNullable<ServerConfig['action']>, 'lookups'>;
18
+ /**
19
+ * Of the functions, what is the project's to say: `oauth.callbackOrigin`, the one address OAuth providers send a
20
+ * visitor back to — this machine's loopback unless `PUBLIC_URL` says where people reach it. A name of its own for a
21
+ * sign-in another device starts (`https://aiko.example.com:8080`, `process.env.OAUTH_CALLBACK_ORIGIN`).
22
+ */
23
+ functions?: Pick<FunctionsConfig, 'oauth'>;
17
24
  };
18
25
  /** A space authored in the project — `authorProjectSpace` of `@plitzi/sdk-authoring/node` — and what it warned of. */
19
26
  export type ProjectSpace = AuthoredDocuments & {
@@ -1,5 +1,6 @@
1
1
  import { consoleLogger } from "../../helpers/serverLog.js";
2
2
  import { isFleetWorker } from "../../core/server/fleet/role.js";
3
+ import { OAUTH_CALLBACK_PATH } from "../../modules/functions/oauth.js";
3
4
  import { loadFunctions } from "../../modules/functions/load.js";
4
5
  import { createServer as createServer$1 } from "../../core/createServer.js";
5
6
  import { closeOnSignals } from "../../core/server/closeOnSignals.js";
@@ -15,6 +16,7 @@ import { projectPlugins, watchProjectPlugins } from "./plugins.js";
15
16
  import { createSpaceFailure } from "./spaceFailure.js";
16
17
  import { watchSpace } from "./watchSpace.js";
17
18
  import { fleetKv } from "../../core/server/fleet/stores.js";
19
+ import { FUNCTION_ROUTES_PREFIX } from "@plitzi/sdk-shared/actions";
18
20
  import { X509Certificate } from "node:crypto";
19
21
  import { hostname, networkInterfaces } from "node:os";
20
22
  import { isIP } from "node:net";
@@ -70,6 +72,16 @@ var LOOPBACK = /* @__PURE__ */ new Set([
70
72
  "localhost"
71
73
  ]);
72
74
  var ANY_ADDRESS = /* @__PURE__ */ new Set(["0.0.0.0", "::"]);
75
+ /**
76
+ * Where OAuth providers send a visitor back (`ctx.oauth`) when the project does not say: the one address to register,
77
+ * whichever this server was opened on. `PUBLIC_URL`, the address people reach it at, when it is HTTPS; this machine's
78
+ * loopback otherwise — the one address every provider takes. Never its address on the network, which the router may
79
+ * change and providers refuse (a private IP, a `.local` name), nor `localhost`, refused too (RFC 8252).
80
+ */
81
+ var oauthCallbackOrigin = (publicUrl, localUrl) => {
82
+ const reached = publicUrl === void 0 ? void 0 : new URL(publicUrl);
83
+ return reached?.protocol === "https:" ? reached.origin : new URL(localUrl).origin;
84
+ };
73
85
  /** An address as a URL writes it: an IPv6 one in brackets. */
74
86
  var urlHost = (address) => address.includes(":") ? `[${address}]` : address;
75
87
  /** Where this machine reaches a server listening on `host`: its loopback, unless it listens on one address only. */
@@ -205,6 +217,7 @@ var startProject = async (options) => {
205
217
  }) : cloudAdapters(plugins.names);
206
218
  const functionsDir = path.join(root, FUNCTIONS_DIR);
207
219
  const functions = existsSync(functionsDir) ? await loadFunctions(functionsDir) : [];
220
+ const callbackOrigin = serverOptions.functions?.oauth?.callbackOrigin ?? oauthCallbackOrigin(process.env.PUBLIC_URL, localUrl);
208
221
  const runtimeBundle = path.join(root, RUNTIME_BUNDLE);
209
222
  const spaceRuntime = await loadRuntimeModule(projectModule(root, RUNTIME_ENTRY, process.argv[1])) ?? (existsSync(runtimeBundle) ? await loadRuntime(readFileSync(runtimeBundle), path.join(root, PROJECT_TMP, "runtime")) : void 0);
210
223
  const runtime = spaceRuntime && await serveRuntime(spaceRuntime, {
@@ -234,7 +247,8 @@ var startProject = async (options) => {
234
247
  dataDir: path.join(root, DATA_DIR),
235
248
  functions: {
236
249
  native: [...functions, ...runtime?.native ?? []],
237
- plugins: plugins.functions
250
+ plugins: plugins.functions,
251
+ oauth: { callbackOrigin }
238
252
  },
239
253
  action: {
240
254
  signingSecret: process.env.PLITZI_SIGNING_SECRET,
@@ -259,6 +273,10 @@ var startProject = async (options) => {
259
273
  console.log(`pages on ${localUrl}/`);
260
274
  if (network.length > 0) console.log(`also on ${network.map((address) => `${address}/`).join(", ")} — anyone on this network can open it (HOST=${host})`);
261
275
  else if (developing && LOOPBACK.has(host)) console.log("only this machine opens it: HOST=0.0.0.0 in .env opens it to your network (a phone on the Wi-Fi)");
276
+ if ([...functions, ...runtime?.native ?? []].some((definition) => Object.keys(definition.oauth ?? {}).length > 0)) {
277
+ console.log(`OAuth providers send visitors back to ${callbackOrigin}${FUNCTION_ROUTES_PREFIX}${OAUTH_CALLBACK_PATH} — the address to register with each`);
278
+ if (network.length > 0 && new URL(callbackOrigin).origin === new URL(localUrl).origin) console.log(" a sign-in started on another device (a tablet) comes back to its own loopback: for one, give this server a name providers accept — functions.oauth.callbackOrigin in src/config/serverOptions.ts, or PUBLIC_URL");
279
+ }
262
280
  if (reached.unnamed.length > 0) console.warn(`[tls] the certificate does not name ${reached.unnamed.join(", ")}: a device that opens it there is refused — \`plitzi cert\` makes one for this machine as it is now`);
263
281
  }
264
282
  const watching = developing ? [...held ? [watchSpace(root, (authored) => {
@@ -12,10 +12,10 @@ import { KV_METHODS, createMemoryKv } from "./runtime/memoryKv.js";
12
12
  import { namespaceKv, spaceKvPatterns } from "./runtime/namespaceKv.js";
13
13
  import "./runtime/precheck.js";
14
14
  import { createActionRunner } from "./runtime/runAction.js";
15
+ import { readManifest } from "../functions/manifest.js";
15
16
  import { functionCeilings } from "../functions/config.js";
16
17
  import { createFunctionJobs } from "../functions/jobs.js";
17
18
  import { createTaskRegistry } from "./tasks/registry.js";
18
- import { readManifest } from "../functions/manifest.js";
19
19
  import { createRoutes } from "../functions/routes.js";
20
20
  import { createSpaceRegistries, prepareFunctions } from "../functions/space.js";
21
21
  import "./runtime/check.js";
@@ -22,9 +22,15 @@ export declare class ActionRunError extends Error {
22
22
  * URL, a credential's name, and a page is shown to anybody. This one says, by its type, that its message was written
23
23
  * to be read. A run that ends on it answers `status: 'failed'` with the message as `error`, which a page's flow reads
24
24
  * as `{{ step.error }}` — the same place a refusal before the run began puts its own.
25
+ *
26
+ * `code` names the refusal for code that catches it (`oauth-not-connected`): what to tell apart by, never the message,
27
+ * which is written for a person and may change.
25
28
  */
26
29
  export declare class ActionRefusal extends Error {
27
- constructor(message: string);
30
+ code?: string;
31
+ constructor(message: string, options?: {
32
+ code?: string;
33
+ });
28
34
  }
29
35
  /**
30
36
  * Whether an error is a refusal — told apart by its NAME, never by `instanceof`: a functions bundle carries its own copy
@@ -32,3 +38,5 @@ export declare class ActionRefusal extends Error {
32
38
  * its reason was dropped on the way to the page.
33
39
  */
34
40
  export declare const isActionRefusal: (error: unknown) => error is Error;
41
+ /** A refusal's code, when it has one that is a string — read off a refusal made by any copy of the class. */
42
+ export declare const refusalCodeOf: (error: unknown) => string | undefined;
@@ -26,11 +26,16 @@ var ActionRunError = class extends Error {
26
26
  * URL, a credential's name, and a page is shown to anybody. This one says, by its type, that its message was written
27
27
  * to be read. A run that ends on it answers `status: 'failed'` with the message as `error`, which a page's flow reads
28
28
  * as `{{ step.error }}` — the same place a refusal before the run began puts its own.
29
+ *
30
+ * `code` names the refusal for code that catches it (`oauth-not-connected`): what to tell apart by, never the message,
31
+ * which is written for a person and may change.
29
32
  */
30
33
  var ActionRefusal = class extends Error {
31
- constructor(message) {
34
+ code;
35
+ constructor(message, options) {
32
36
  super(message);
33
37
  this.name = "ActionRefusal";
38
+ if (options?.code !== void 0) this.code = options.code;
34
39
  }
35
40
  };
36
41
  /**
@@ -39,5 +44,10 @@ var ActionRefusal = class extends Error {
39
44
  * its reason was dropped on the way to the page.
40
45
  */
41
46
  var isActionRefusal = (error) => error instanceof Error && error.name === "ActionRefusal";
47
+ /** A refusal's code, when it has one that is a string — read off a refusal made by any copy of the class. */
48
+ var refusalCodeOf = (error) => {
49
+ const code = isActionRefusal(error) && "code" in error ? error.code : void 0;
50
+ return typeof code === "string" ? code : void 0;
51
+ };
42
52
  //#endregion
43
- export { ActionRefusal, ActionRunError, isActionRefusal };
53
+ export { ActionRefusal, ActionRunError, isActionRefusal, refusalCodeOf };
@@ -69,10 +69,12 @@ var createRunFetch = (base, signal, limits, lineage, onBudgetSpent) => {
69
69
  */
70
70
  var taskContextFor = (config, { kv, email, redactor, signing, later, jobs }, request, signal, runFetch) => {
71
71
  const { realtime } = config;
72
+ const oauthCallbackOrigin = config.functions?.oauth?.callbackOrigin;
72
73
  const readData = projectDataReader(config.lookups.getData, request.spaceId, request.at);
73
74
  return (scope) => ({
74
75
  runId: request.runId,
75
76
  ...request.origin ? { origin: request.origin } : {},
77
+ ...oauthCallbackOrigin ? { oauthCallbackOrigin } : {},
76
78
  spaceId: request.spaceId,
77
79
  environment: request.environment,
78
80
  trigger: request.trigger,
@@ -219,10 +219,12 @@ export type ActionTaskContext = {
219
219
  open?: SpaceSigning['open'];
220
220
  /**
221
221
  * The public origin of the request that started the run (`https://shop.example.com`), as the server resolved it —
222
- * what an address back to the space is made of (an OAuth `redirect_uri`). `undefined` for a run no request started:
223
- * a schedule, a job.
222
+ * where a visitor is sent back to (after an OAuth consent). `undefined` for a run no request started: a schedule, a
223
+ * job.
224
224
  */
225
225
  origin?: string;
226
+ /** Where OAuth providers send a visitor back, when the deployment fixed it (`functions.oauth.callbackOrigin`). */
227
+ oauthCallbackOrigin?: string;
226
228
  /**
227
229
  * One file of the space's data (`products.json`), parsed, as of the run's revision — read-only, and refused when
228
230
  * the deployment keeps no data (`lookups.getData`, or `dataDir`). One lookup per run, whichever step reads it.
@@ -129,6 +129,12 @@ var fetchInitOf = (value) => {
129
129
  };
130
130
  };
131
131
  var optionalString = (value, what) => value === void 0 || value === null ? void 0 : stringArg(value, what);
132
+ /** The code's number for a request it may cut short — see {@link FunctionCall}. */
133
+ var requestArg = (value) => {
134
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new CallError("A request is named by a whole number");
135
+ return value;
136
+ };
137
+ var cutShort = (value) => value === void 0 || value === null ? {} : { request: requestArg(value) };
132
138
  /** A call to `ctx.jobs`, read into the one method it names: a name and an object for `start`, an id for the rest. */
133
139
  var jobsCallOf = (call) => {
134
140
  switch (call.method) {
@@ -179,13 +185,17 @@ var oauthCallOf = (call) => {
179
185
  const owner = optionalString(call.owner, "An OAuth owner");
180
186
  const own = owner === void 0 ? {} : { owner };
181
187
  switch (call.method) {
182
- case "connect": return {
183
- op: "oauth",
184
- method: "connect",
185
- connection,
186
- returnTo: stringArg(call.returnTo, "returnTo"),
187
- ...own
188
- };
188
+ case "connect": {
189
+ const params = call.authorizeParams === void 0 ? void 0 : recordArg(call.authorizeParams, "authorizeParams");
190
+ return {
191
+ op: "oauth",
192
+ method: "connect",
193
+ connection,
194
+ returnTo: stringArg(call.returnTo, "returnTo"),
195
+ ...params === void 0 ? {} : { authorizeParams: Object.fromEntries(Object.entries(params).map(([key, value]) => [key, stringArg(value, `authorizeParams.${key}`)])) },
196
+ ...own
197
+ };
198
+ }
189
199
  case "status":
190
200
  case "disconnect":
191
201
  case "token": return {
@@ -202,7 +212,8 @@ var oauthCallOf = (call) => {
202
212
  connection,
203
213
  url: stringArg(call.url, "A URL"),
204
214
  init,
205
- ...own
215
+ ...own,
216
+ ...cutShort(call.request)
206
217
  };
207
218
  }
208
219
  default: throw new CallError("Not an OAuth method the platform answers");
@@ -243,7 +254,12 @@ var readCall = (value) => {
243
254
  case "fetch": return {
244
255
  op: "fetch",
245
256
  url: stringArg(call.url, "A URL"),
246
- init: fetchInitOf(call.init ?? {})
257
+ init: fetchInitOf(call.init ?? {}),
258
+ ...cutShort(call.request)
259
+ };
260
+ case "abort": return {
261
+ op: "abort",
262
+ request: requestArg(call.request)
247
263
  };
248
264
  case "publish": return {
249
265
  op: "publish",
@@ -307,6 +323,31 @@ var readCall = (value) => {
307
323
  default: throw new CallError("Not a call the platform answers");
308
324
  }
309
325
  };
326
+ /** Keyed by the invocation's context: every call of one invocation is answered with the same one. */
327
+ var cutsByRun = /* @__PURE__ */ new WeakMap();
328
+ var cutsOf = (ctx) => {
329
+ const known = cutsByRun.get(ctx);
330
+ if (known) return known;
331
+ const made = {
332
+ live: /* @__PURE__ */ new Map(),
333
+ early: /* @__PURE__ */ new Set()
334
+ };
335
+ cutsByRun.set(ctx, made);
336
+ return made;
337
+ };
338
+ /** The work of a request the code numbered, handed the signal its `abort` fires — even one that arrived first. */
339
+ var cuttable = async (ctx, request, work) => {
340
+ if (request === void 0) return work({});
341
+ const cuts = cutsOf(ctx);
342
+ const controller = new AbortController();
343
+ if (cuts.early.delete(request)) controller.abort();
344
+ cuts.live.set(request, controller);
345
+ try {
346
+ return await work({ signal: controller.signal });
347
+ } finally {
348
+ cuts.live.delete(request);
349
+ }
350
+ };
310
351
  /**
311
352
  * Answers one call from a space's code with the run's own {@link FunctionContext} — the same object a self-hosted
312
353
  * server hands its functions, so the sandbox can do exactly what native code can and not one thing more.
@@ -314,7 +355,17 @@ var readCall = (value) => {
314
355
  var answerCall = async (ctx, call) => {
315
356
  switch (call.op) {
316
357
  case "kv": return kvCall(ctx.kv, call.method, call.args);
317
- case "fetch": return wireResponseOf(await ctx.fetch(call.url, call.init));
358
+ case "fetch": return cuttable(ctx, call.request, async (cut) => wireResponseOf(await ctx.fetch(call.url, {
359
+ ...call.init,
360
+ ...cut
361
+ })));
362
+ case "abort": {
363
+ const cuts = cutsOf(ctx);
364
+ const live = cuts.live.get(call.request);
365
+ if (live) live.abort();
366
+ else cuts.early.add(call.request);
367
+ return null;
368
+ }
318
369
  case "publish": return ctx.publish(call.topic, call.type, call.data);
319
370
  case "grant": return ctx.grant(call.topic, call.ttlSeconds);
320
371
  case "revoke": return ctx.revoke(call.topic, call.grant);
@@ -328,15 +379,17 @@ var answerCall = async (ctx, call) => {
328
379
  switch (call.method) {
329
380
  case "connect": return ctx.oauth.connect(call.connection, {
330
381
  returnTo: call.returnTo,
382
+ ...call.authorizeParams === void 0 ? {} : { authorizeParams: call.authorizeParams },
331
383
  ...call.owner === void 0 ? {} : { owner: call.owner }
332
384
  });
333
385
  case "status": return ctx.oauth.status(call.connection, call.owner === void 0 ? {} : { owner: call.owner });
334
386
  case "disconnect": return ctx.oauth.disconnect(call.connection, call.owner === void 0 ? {} : { owner: call.owner });
335
387
  case "token": return ctx.oauth.token(call.connection, call.owner === void 0 ? {} : { owner: call.owner });
336
- case "fetch": return wireResponseOf(await ctx.oauth.fetch(call.connection, call.url, {
388
+ case "fetch": return cuttable(ctx, call.request, async (cut) => wireResponseOf(await ctx.oauth.fetch(call.connection, call.url, {
337
389
  ...call.init,
390
+ ...cut,
338
391
  ...call.owner === void 0 ? {} : { owner: call.owner }
339
- }));
392
+ })));
340
393
  }
341
394
  break;
342
395
  case "jobs":
@@ -48,6 +48,17 @@ export type FunctionsConfig = {
48
48
  */
49
49
  limitsFor?: (spaceId: number) => Promise<Partial<FunctionJobLimits> | undefined>;
50
50
  };
51
+ /** The spaces' OAuth connections (`ctx.oauth`). */
52
+ oauth?: {
53
+ /**
54
+ * The origin every provider sends a visitor back to (`<origin>/fn/oauth/callback`), whichever address they opened
55
+ * the space on — the one address to register, which a server reached on several (`localhost`, its loopback, its
56
+ * address on the network) needs. The visitor is then sent on to the address they started from. Only for a server
57
+ * of one space, such as a project's (`serveProject` sets its `publicUrl`): one of many spaces tells them apart by
58
+ * host, and answers each callback on the space's own. Left out, the address the visitor started on.
59
+ */
60
+ callbackOrigin?: string;
61
+ };
51
62
  };
52
63
  /** What an invocation gets unless its task asks for more CPU or time. */
53
64
  export declare const DEFAULT_FUNCTION_LIMITS: FunctionLimits;
@@ -1,8 +1,8 @@
1
1
  import { prefixKv } from "../actions/runtime/namespaceKv.js";
2
2
  import { fetchOutbound } from "../../helpers/outboundGuard.js";
3
3
  import { countRate, refusedOver } from "../actions/runtime/rateLimit.js";
4
- import { noOAuth, oauthFor } from "./oauth.js";
5
4
  import { pluginKvPrefix, pluginSigned } from "./scope.js";
5
+ import { noOAuth, oauthFor } from "./oauth.js";
6
6
  import { processTwigParam } from "@plitzi/sdk-shared/helpers/twigWrapper";
7
7
  //#region src/modules/functions/context.ts
8
8
  /**
@@ -46,7 +46,7 @@ var functionFetch = (ctx, hosts, scope) => async (input, init = {}) => {
46
46
  method: init.method ?? "GET",
47
47
  headers,
48
48
  body: init.body === void 0 ? void 0 : render(init.body),
49
- signal: ctx.signal
49
+ signal: init.signal ? AbortSignal.any([ctx.signal, init.signal]) : ctx.signal
50
50
  });
51
51
  };
52
52
  /**
@@ -24,6 +24,8 @@ export type FunctionFetchInit = {
24
24
  headers?: Record<string, string>;
25
25
  body?: string;
26
26
  credential?: string;
27
+ /** Cuts the request short when it aborts (`AbortSignal.timeout(12_000)`); the run's own end cuts it regardless. */
28
+ signal?: AbortSignal;
27
29
  };
28
30
  /** What a function's `fetch` answers: a web `Response`, whichever runner it is in. */
29
31
  export type FunctionFetch = (url: string | URL, init?: FunctionFetchInit) => Promise<Response>;
@@ -34,6 +36,11 @@ export type FunctionFetch = (url: string | URL, init?: FunctionFetchInit) => Pro
34
36
  export type FunctionOAuthOwner = {
35
37
  owner?: string;
36
38
  };
39
+ /**
40
+ * The `code` of a refusal `ctx.oauth` throws (an `ActionRefusal`), to tell it apart by: `oauth-not-connected` — no
41
+ * account connected for that owner yet, so `connect` first; `oauth-no-owner` — nobody signed in and no `owner` named.
42
+ */
43
+ export type FunctionOAuthRefusal = 'oauth-not-connected' | 'oauth-no-owner';
37
44
  /** What `ctx.oauth.status` says of a connection — never its token. */
38
45
  export type FunctionOAuthStatus = {
39
46
  connected: boolean;
@@ -56,17 +63,21 @@ export type FunctionOAuth = {
56
63
  /**
57
64
  * Where to send the visitor to consent (authorization code, PKCE). They come back to `/fn/oauth/callback` — the
58
65
  * address to register with the provider, on the space's host — and from there to `returnTo`, a path of the space,
59
- * with `?oauth=<connection>&oauth_result=connected` or `&oauth_error=<what>`.
66
+ * with `?oauth=<connection>&oauth_result=connected` or `&oauth_error=<what>`. `authorizeParams` adds to the
67
+ * connection's for this consent alone — `{ prompt: 'select_account' }` to choose another account — never one the
68
+ * platform writes (`state`, `redirect_uri`, `scope`, PKCE's).
60
69
  */
61
70
  connect: (connection: string, options: {
62
71
  returnTo: string;
72
+ authorizeParams?: Record<string, string>;
63
73
  } & FunctionOAuthOwner) => Promise<{
64
74
  url: string;
65
75
  }>;
66
76
  status: (connection: string, options?: FunctionOAuthOwner) => Promise<FunctionOAuthStatus>;
67
77
  /**
68
78
  * A request to the provider's API with the token written in (`Authorization: Bearer`), renewed when it is about to
69
- * lapse and once more if the answer is 401. Only to the hosts the space declared (`allow.hosts`).
79
+ * lapse and once more if the answer is 401. Only to the hosts the space declared (`allow.hosts`). With nobody
80
+ * connected it refuses, `code: 'oauth-not-connected'` ({@link FunctionOAuthRefusal}).
70
81
  */
71
82
  fetch: (connection: string, url: string | URL, init?: Omit<FunctionFetchInit, 'credential'> & FunctionOAuthOwner) => Promise<Response>;
72
83
  /** Forgets the connection — revoked at the provider when it says where — and answers whether there was one. */
@@ -39,6 +39,42 @@ var createFunctionsDriver = (environment) => {
39
39
  const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
40
40
  const isCallable = (value) => typeof value === "function";
41
41
  const listOf = (value) => Array.isArray(value) ? value : [];
42
+ const isSignal = (value) => isRecord(value) && typeof value.aborted === "boolean" && typeof value.addEventListener === "function" && typeof value.removeEventListener === "function";
43
+ /** Why a request was cut: the signal's reason, as a web `fetch` rejects with it — an `AbortError` when it gave none. */
44
+ const abortedWith = (signal) => signal.reason instanceof Error ? signal.reason : Object.assign(/* @__PURE__ */ new Error("This operation was aborted"), { name: "AbortError" });
45
+ let requests = 0;
46
+ /**
47
+ * A request the code may cut short with its init's `signal`: the signal stays here — it does not cross — and the
48
+ * call is numbered, so that its firing tells the platform which request to cut (`abort`). The code stops waiting at
49
+ * once, with the signal's reason, as a web `fetch` does.
50
+ */
51
+ const cuttable = (message, init) => {
52
+ const { signal: given, ...rest } = init;
53
+ if (given === void 0 || given === null) return call({
54
+ ...message,
55
+ init: rest
56
+ });
57
+ if (!isSignal(given)) return Promise.reject(/* @__PURE__ */ new TypeError("The signal of a request is an AbortSignal"));
58
+ if (given.aborted) return Promise.reject(abortedWith(given));
59
+ const request = ++requests;
60
+ return new Promise((resolve, reject) => {
61
+ const cut = () => {
62
+ call({
63
+ op: "abort",
64
+ request
65
+ }).catch(() => void 0);
66
+ reject(abortedWith(given));
67
+ };
68
+ given.addEventListener("abort", cut, { once: true });
69
+ call({
70
+ ...message,
71
+ init: rest,
72
+ request
73
+ }).then(resolve, reject).finally(() => {
74
+ given.removeEventListener("abort", cut);
75
+ });
76
+ });
77
+ };
42
78
  /** A value as the wire can carry it; how a line reads is the platform's (`lineOf`), not the driver's. */
43
79
  const wireValue = (value) => {
44
80
  if (value instanceof Error) return `${value.name}: ${value.message}`;
@@ -77,11 +113,10 @@ var createFunctionsDriver = (environment) => {
77
113
  ...facts,
78
114
  kv,
79
115
  fetch: async (url, init = {}) => {
80
- const answer = await call({
116
+ const answer = await cuttable({
81
117
  op: "fetch",
82
- url: String(url),
83
- init
84
- });
118
+ url: String(url)
119
+ }, init);
85
120
  return responseOf(isRecord(answer) ? answer : {});
86
121
  },
87
122
  publish: async (topic, type, data) => {
@@ -169,6 +204,7 @@ var createFunctionsDriver = (environment) => {
169
204
  method: "connect",
170
205
  connection,
171
206
  returnTo: options.returnTo,
207
+ authorizeParams: options.authorizeParams,
172
208
  owner: options.owner
173
209
  }),
174
210
  status: (connection, options = {}) => call({
@@ -191,14 +227,13 @@ var createFunctionsDriver = (environment) => {
191
227
  }),
192
228
  fetch: async (connection, url, init = {}) => {
193
229
  const { owner, ...rest } = init;
194
- const answer = await call({
230
+ const answer = await cuttable({
195
231
  op: "oauth",
196
232
  method: "fetch",
197
233
  connection,
198
234
  url: String(url),
199
- init: rest,
200
235
  owner
201
- });
236
+ }, rest);
202
237
  return responseOf(isRecord(answer) ? answer : {});
203
238
  }
204
239
  },
@@ -14,6 +14,8 @@ export declare const reservedRouteProblem: (route: string) => string;
14
14
  * wildcard, `..` — is not a key, so what a space may answer is only ever a path it spelled out.
15
15
  */
16
16
  export declare const parseRouteKey: (key: string) => RouteKey | undefined;
17
+ /** What the platform writes into the consent URL itself: `authorizeParams` may add to it, never change it. */
18
+ export declare const OWN_AUTHORIZE_PARAMS: ReadonlySet<string>;
17
19
  export type ManifestReading = {
18
20
  manifest: FunctionsManifest;
19
21
  problems: string[];
@@ -328,4 +328,4 @@ var readManifest = (value, reserved, ceilings, scope) => {
328
328
  };
329
329
  };
330
330
  //#endregion
331
- export { ROUTE_METHODS, parseRouteKey, readManifest, reservedRouteProblem };
331
+ export { OWN_AUTHORIZE_PARAMS, ROUTE_METHODS, parseRouteKey, readManifest, reservedRouteProblem };
@@ -15,7 +15,7 @@ import { FunctionOAuthConnection } from '@plitzi/sdk-shared';
15
15
  /** Where the provider sends the visitor back, under `/fn` — the one address to register with every provider. */
16
16
  export declare const OAUTH_CALLBACK_PATH = "/oauth/callback";
17
17
  /** What the parts of a run `ctx.oauth` uses are: its fetch, its kv, its credentials, its sealing, who and where. */
18
- export type OAuthRun = Pick<ActionTaskContext, 'fetch' | 'kv' | 'credential' | 'seal' | 'open' | 'origin' | 'user' | 'signal'>;
18
+ export type OAuthRun = Pick<ActionTaskContext, 'fetch' | 'kv' | 'credential' | 'seal' | 'open' | 'origin' | 'oauthCallbackOrigin' | 'user' | 'signal'>;
19
19
  /**
20
20
  * `ctx.oauth` for one run, over the connections its code declared. `hosts` are where `fetch` may write the token — the
21
21
  * same `allow.hosts` every request of the code is held to.
@@ -1,5 +1,6 @@
1
1
  import { ActionRefusal } from "../actions/runtime/errors.js";
2
2
  import { fetchOutbound } from "../../helpers/outboundGuard.js";
3
+ import { OWN_AUTHORIZE_PARAMS } from "./manifest.js";
3
4
  import { FUNCTION_ROUTES_PREFIX } from "@plitzi/sdk-shared/actions";
4
5
  import { isRecord } from "@plitzi/sdk-shared/helpers";
5
6
  import { createHash, randomBytes } from "node:crypto";
@@ -26,6 +27,8 @@ var OWNER = /^[\w:.@-]{1,128}$/;
26
27
  var KEY_PREFIX = "plitzi:oauth";
27
28
  var stateKey = (state) => `${KEY_PREFIX}:state:${state}`;
28
29
  var tokenKey = (connection, owner) => `${KEY_PREFIX}:token:${connection}:${owner}`;
30
+ var refused = (message, code) => new ActionRefusal(message, { code });
31
+ var notConnected = (connection) => refused(`Not connected to "${connection}": ctx.oauth.connect first`, "oauth-not-connected");
29
32
  var discovered = /* @__PURE__ */ new Map();
30
33
  var stringField = (record, key) => typeof record[key] === "string" ? record[key] : void 0;
31
34
  /** The connection's endpoints: written out, or read from its issuer's OpenID metadata — what is written wins. */
@@ -89,7 +92,7 @@ var clientOf = async (run, connection, spec) => {
89
92
  };
90
93
  };
91
94
  /** 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) => {
95
+ var tokenRequest = async (run, connection, spec, url, grant, signal = run.signal) => {
93
96
  const client = await clientOf(run, connection, spec);
94
97
  const form = new URLSearchParams(grant);
95
98
  const headers = {
@@ -105,7 +108,7 @@ var tokenRequest = async (run, connection, spec, url, grant) => {
105
108
  method: "POST",
106
109
  headers,
107
110
  body: form.toString(),
108
- signal: run.signal
111
+ signal
109
112
  });
110
113
  const body = await answer.json().catch(() => void 0);
111
114
  const said = isRecord(body) ? body : {};
@@ -140,11 +143,11 @@ var readSealed = async (run, key, check) => {
140
143
  return check(parsed) ? parsed : void 0;
141
144
  };
142
145
  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";
146
+ var isPending = (value) => isRecord(value) && typeof value.connection === "string" && isRecord(value.spec) && typeof value.owner === "string" && typeof value.origin === "string" && typeof value.returnTo === "string" && typeof value.verifier === "string" && typeof value.redirectUri === "string";
144
147
  /** Whose the connection is: the code's own key, or the signed-in visitor — and none is refused, saying which to name. */
145
148
  var ownerOf = (run, connection, options) => {
146
149
  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)`);
150
+ if (!owner) throw refused(`OAuth connection "${connection}" is somebody's: sign the visitor in, or name its owner ({ owner: 'space' }, a key of your own)`, "oauth-no-owner");
148
151
  if (!OWNER.test(owner)) throw new Error(`An OAuth owner is letters, digits and ":._@-", up to 128 — not "${owner}"`);
149
152
  return owner;
150
153
  };
@@ -153,10 +156,21 @@ var pathOf = (returnTo) => {
153
156
  if (!returnTo.startsWith("/") || returnTo.startsWith("//") || returnTo.includes("\\")) throw new Error(`returnTo is a path of the space ("/settings"), not "${returnTo}"`);
154
157
  return returnTo;
155
158
  };
156
- var withQuery = (path, params) => {
157
- const url = new URL(path, "http://space");
159
+ /** `returnTo` on the origin the visitor started from, told how the consent went. */
160
+ var backTo = (origin, path, params) => {
161
+ const url = new URL(path, origin);
158
162
  Object.entries(params).forEach(([key, value]) => url.searchParams.set(key, value));
159
- return `${url.pathname}${url.search}${url.hash}`;
163
+ return url.href;
164
+ };
165
+ /** What one consent adds to the connection's `authorizeParams` (`prompt: 'select_account'`): strings, none the platform's. */
166
+ var authorizeParamsOf = (connection, params) => {
167
+ if (params === void 0) return {};
168
+ if (!isRecord(params)) throw new Error(`OAuth connection "${connection}": authorizeParams is an object of strings`);
169
+ return Object.fromEntries(Object.entries(params).map(([key, value]) => {
170
+ if (OWN_AUTHORIZE_PARAMS.has(key)) throw new Error(`OAuth connection "${connection}": authorizeParams.${key} is the platform's to write`);
171
+ if (typeof value !== "string") throw new Error(`OAuth connection "${connection}": authorizeParams.${key} is a string`);
172
+ return [key, value];
173
+ }));
160
174
  };
161
175
  /**
162
176
  * `ctx.oauth` for one run, over the connections its code declared. `hosts` are where `fetch` may write the token — the
@@ -173,7 +187,7 @@ var oauthFor = (run, connections, allowed) => {
173
187
  };
174
188
  const save = (connection, owner, tokens) => run.kv.set(tokenKey(connection, owner), sealed(run).seal(JSON.stringify(tokens)));
175
189
  /** 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) => {
190
+ const tokensOf = async (connection, owner, { force = false, signal = run.signal } = {}) => {
177
191
  const tokens = await readSealed(run, tokenKey(connection, owner), isTokens);
178
192
  if (!tokens) return;
179
193
  if (!(tokens.expiresAt !== void 0 && tokens.expiresAt - RENEW_BEFORE_MS <= Date.now() || force) || !tokens.refresh) return tokens;
@@ -182,7 +196,7 @@ var oauthFor = (run, connections, allowed) => {
182
196
  const renewed = tokensFrom(await tokenRequest(run, connection, spec, token, {
183
197
  grant_type: "refresh_token",
184
198
  refresh_token: tokens.refresh
185
- }), tokens);
199
+ }, signal), tokens);
186
200
  await save(connection, owner, renewed);
187
201
  return renewed;
188
202
  };
@@ -192,15 +206,17 @@ var oauthFor = (run, connections, allowed) => {
192
206
  const owner = ownerOf(run, connection, options);
193
207
  const returnTo = pathOf(options.returnTo);
194
208
  if (!run.origin) throw new Error(`OAuth connection "${connection}" is made from a visitor's request: this run has none to return to`);
209
+ const once = authorizeParamsOf(connection, options.authorizeParams);
195
210
  const { authorize } = await endpointsOf(run, connection, spec);
196
211
  const client = await clientOf(run, connection, spec);
197
212
  const verifier = randomBytes(32).toString("base64url");
198
213
  const state = randomBytes(24).toString("base64url");
199
- const redirectUri = `${run.origin}${FUNCTION_ROUTES_PREFIX}${OAUTH_CALLBACK_PATH}`;
214
+ const redirectUri = `${run.oauthCallbackOrigin ?? run.origin}${FUNCTION_ROUTES_PREFIX}${OAUTH_CALLBACK_PATH}`;
200
215
  const pending = {
201
216
  connection,
202
217
  spec,
203
218
  owner,
219
+ origin: run.origin,
204
220
  returnTo,
205
221
  verifier,
206
222
  redirectUri
@@ -209,6 +225,7 @@ var oauthFor = (run, connections, allowed) => {
209
225
  const url = new URL(authorize);
210
226
  const params = {
211
227
  ...spec.authorizeParams,
228
+ ...once,
212
229
  response_type: "code",
213
230
  client_id: client.id,
214
231
  redirect_uri: redirectUri,
@@ -234,6 +251,7 @@ var oauthFor = (run, connections, allowed) => {
234
251
  const owner = ownerOf(run, connection, init);
235
252
  const url = new URL(typeof input === "string" ? input : input.href);
236
253
  allowed(url);
254
+ const signal = init.signal ? AbortSignal.any([run.signal, init.signal]) : run.signal;
237
255
  const send = (tokens) => fetchOutbound(run.fetch, url, {
238
256
  method: init.method ?? "GET",
239
257
  headers: {
@@ -241,13 +259,16 @@ var oauthFor = (run, connections, allowed) => {
241
259
  authorization: `${/^bearer$/i.test(tokens.type) ? "Bearer" : tokens.type} ${tokens.access}`
242
260
  },
243
261
  body: init.body,
244
- signal: run.signal
262
+ signal
245
263
  });
246
- const tokens = await tokensOf(connection, owner);
247
- if (!tokens) throw new ActionRefusal(`Not connected to "${connection}": ctx.oauth.connect first`);
264
+ const tokens = await tokensOf(connection, owner, { signal });
265
+ if (!tokens) throw notConnected(connection);
248
266
  const answer = await send(tokens);
249
267
  if (answer.status !== 401 || !tokens.refresh) return answer;
250
- const renewed = await tokensOf(connection, owner, true);
268
+ const renewed = await tokensOf(connection, owner, {
269
+ force: true,
270
+ signal
271
+ });
251
272
  return renewed ? send(renewed) : answer;
252
273
  },
253
274
  disconnect: async (connection, options) => {
@@ -263,7 +284,7 @@ var oauthFor = (run, connections, allowed) => {
263
284
  token: async (connection, options) => {
264
285
  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
286
  const tokens = await tokensOf(connection, ownerOf(run, connection, options));
266
- if (!tokens) throw new ActionRefusal(`Not connected to "${connection}": ctx.oauth.connect first`);
287
+ if (!tokens) throw notConnected(connection);
267
288
  return {
268
289
  token: tokens.access,
269
290
  type: tokens.type,
@@ -299,13 +320,13 @@ var oauthCallback = async (run, query) => {
299
320
  });
300
321
  const back = (params) => new Response(null, {
301
322
  status: 303,
302
- headers: { location: withQuery(pending.returnTo, {
323
+ headers: { location: backTo(pending.origin, pending.returnTo, {
303
324
  oauth: pending.connection,
304
325
  ...params
305
326
  }) }
306
327
  });
307
- const refused = query.get("error");
308
- if (refused) return back({ oauth_error: refused });
328
+ const denied = query.get("error");
329
+ if (denied) return back({ oauth_error: denied });
309
330
  const code = query.get("code");
310
331
  if (!code) return back({ oauth_error: "no_code" });
311
332
  try {
@@ -99,9 +99,14 @@ export type FunctionInvocation = {
99
99
  request: WireRequest;
100
100
  context: FunctionInvocationContext;
101
101
  };
102
+ /** A request's init as the wire carries it: what the code wrote but its `signal`, which never crosses (`request`). */
103
+ export type WireFetchInit = Omit<FunctionFetchInit, 'signal'>;
102
104
  /**
103
105
  * One call back from the code to the platform: a {@link FunctionContext} method, by name, with its arguments. The
104
106
  * platform answers it with the run's own context — scoped to the space and the run before anything is done.
107
+ *
108
+ * A request the code may cut short (its init had a `signal`) carries `request`, the code's own number for it, and the
109
+ * code's `abort` names that number when the signal fires: a signal is the code's object, and does not cross.
105
110
  */
106
111
  export type FunctionCall = {
107
112
  op: 'kv';
@@ -110,7 +115,11 @@ export type FunctionCall = {
110
115
  } | {
111
116
  op: 'fetch';
112
117
  url: string;
113
- init: FunctionFetchInit;
118
+ init: WireFetchInit;
119
+ request?: number;
120
+ } | {
121
+ op: 'abort';
122
+ request: number;
114
123
  } | {
115
124
  op: 'publish';
116
125
  topic: string;
@@ -149,6 +158,7 @@ export type FunctionCall = {
149
158
  method: 'connect';
150
159
  connection: string;
151
160
  returnTo: string;
161
+ authorizeParams?: Record<string, string>;
152
162
  owner?: string;
153
163
  } | {
154
164
  op: 'oauth';
@@ -160,8 +170,9 @@ export type FunctionCall = {
160
170
  method: 'fetch';
161
171
  connection: string;
162
172
  url: string;
163
- init: Omit<FunctionFetchInit, 'credential'>;
173
+ init: Omit<WireFetchInit, 'credential'>;
164
174
  owner?: string;
175
+ request?: number;
165
176
  }
166
177
  /** `ctx.jobs`: the space's jobs, started and stopped by its code. */
167
178
  | {
@@ -194,14 +205,27 @@ export type FunctionCall = {
194
205
  op: 'emit';
195
206
  chunk: unknown;
196
207
  };
197
- /** How a call or an invocation ended: its value, or why not — never a thrown object crossing the boundary. */
208
+ /**
209
+ * How a call or an invocation ended: its value, or why not — never a thrown object crossing the boundary. A refusal
210
+ * (`refused`, with its `code`) stays one on the other side: the code that made the call catches what the platform threw.
211
+ */
198
212
  export type FunctionAnswer = {
199
213
  ok: true;
200
214
  value: unknown;
201
215
  } | {
202
216
  ok: false;
203
217
  error: string;
218
+ refused?: true;
219
+ code?: string;
204
220
  };
221
+ /** What a call that threw answers across a boundary: its message, and whether — and as what — it was a refusal. */
222
+ export declare const failedAnswerOf: (error: unknown) => Extract<FunctionAnswer, {
223
+ ok: false;
224
+ }>;
225
+ /** …and that answer thrown again on the side that made the call: a refusal as a refusal, anything else as an error. */
226
+ export declare const errorOfAnswer: ({ error, refused, code }: Extract<FunctionAnswer, {
227
+ ok: false;
228
+ }>) => Error;
205
229
  /** Why the runner stopped an invocation, when it was not the code's own error. */
206
230
  export type FunctionStopReason = 'cpu' | 'wall' | 'memory' | 'output' | 'calls' | 'aborted';
207
231
  /** What the platform asks a runner for: every runner implements this, and nothing else of it is assumed. */
@@ -1,3 +1,4 @@
1
+ import { ActionRefusal, isActionRefusal, refusalCodeOf } from "../actions/runtime/errors.js";
1
2
  //#region src/modules/functions/protocol.ts
2
3
  /**
3
4
  * The messages between the platform and whatever runs a space's code — the one protocol every runner speaks, whether
@@ -6,6 +7,18 @@
6
7
  */
7
8
  var FUNCTIONS_PROTOCOL = 1;
8
9
  var isStreamedRouteAnswer = (value) => typeof value === "object" && value !== null && "streamed" in value && value.streamed === true && "body" in value && value.body instanceof ReadableStream;
10
+ /** What a call that threw answers across a boundary: its message, and whether — and as what — it was a refusal. */
11
+ var failedAnswerOf = (error) => {
12
+ const code = refusalCodeOf(error);
13
+ return {
14
+ ok: false,
15
+ error: error instanceof Error ? error.message : String(error),
16
+ ...isActionRefusal(error) ? { refused: true } : {},
17
+ ...code === void 0 ? {} : { code }
18
+ };
19
+ };
20
+ /** …and that answer thrown again on the side that made the call: a refusal as a refusal, anything else as an error. */
21
+ var errorOfAnswer = ({ error, refused, code }) => refused ? new ActionRefusal(error, code === void 0 ? {} : { code }) : new Error(error);
9
22
  /** An invocation that did not answer, and why ({@link FunctionFailureReason}). */
10
23
  var FunctionFailure = class extends Error {
11
24
  reason;
@@ -16,4 +29,4 @@ var FunctionFailure = class extends Error {
16
29
  }
17
30
  };
18
31
  //#endregion
19
- export { FUNCTIONS_PROTOCOL, FunctionFailure, isStreamedRouteAnswer };
32
+ export { FUNCTIONS_PROTOCOL, FunctionFailure, errorOfAnswer, failedAnswerOf, isStreamedRouteAnswer };
@@ -1,13 +1,13 @@
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";
4
3
  import { pluginOfPath } from "./scope.js";
4
+ import { parseRouteKey, reservedRouteProblem } from "./manifest.js";
5
+ import { OAUTH_CALLBACK_PATH, oauthCallback } from "./oauth.js";
5
6
  import { functionContextFor } from "./context.js";
6
7
  import { answerCall, readCall, responseOf, wireRequestOf, wireResponseFrom } from "./capabilities.js";
7
8
  import { functionLimitsFor } from "./config.js";
8
9
  import { FunctionFailure, isStreamedRouteAnswer } from "./protocol.js";
9
10
  import { jobsManifestOf } from "./jobs.js";
10
- import { parseRouteKey, reservedRouteProblem } from "./manifest.js";
11
11
  import { PLUGIN_ROUTES_SEGMENT } from "@plitzi/sdk-shared/actions";
12
12
  import { randomUUID } from "node:crypto";
13
13
  //#region src/modules/functions/routes.ts
@@ -107,10 +107,13 @@ var answerOf = (value) => {
107
107
  ok: true,
108
108
  value: value.value
109
109
  };
110
- return value.ok === false && typeof value.error === "string" ? {
110
+ if (value.ok !== false || typeof value.error !== "string") return;
111
+ return {
111
112
  ok: false,
112
- error: value.error
113
- } : void 0;
113
+ error: value.error,
114
+ ...value.refused === true ? { refused: true } : {},
115
+ ...typeof value.code === "string" ? { code: value.code } : {}
116
+ };
114
117
  };
115
118
  /** What the platform sent the runner, or nothing when it is not one of the protocol's messages. */
116
119
  var readRequestMessage = (data) => {
@@ -1,4 +1,4 @@
1
- import { FunctionFailure } from "../protocol.js";
1
+ import { FunctionFailure, failedAnswerOf } from "../protocol.js";
2
2
  import { frameText } from "../../../helpers/wsFrame.js";
3
3
  import { readResponseMessage } from "./messages.js";
4
4
  import { WebSocket } from "ws";
@@ -78,10 +78,7 @@ var createRemoteRunner = ({ url, secret, connectTimeoutMs = 5e3, graceMs = 5e3 }
78
78
  }), (error) => send({
79
79
  type: "answer",
80
80
  id: message.id,
81
- answer: {
82
- ok: false,
83
- error: error instanceof Error ? error.message : String(error)
84
- }
81
+ answer: failedAnswerOf(error)
85
82
  }));
86
83
  return;
87
84
  case "head": {
@@ -1,5 +1,5 @@
1
1
  import { serverLog } from "../../../helpers/serverLog.js";
2
- import { FunctionFailure, isStreamedRouteAnswer } from "../protocol.js";
2
+ import { FunctionFailure, errorOfAnswer, isStreamedRouteAnswer } from "../protocol.js";
3
3
  import { frameText } from "../../../helpers/wsFrame.js";
4
4
  import { watchConnections } from "../../../core/server/drain.js";
5
5
  import { readRequestMessage } from "./messages.js";
@@ -96,7 +96,7 @@ var serveConnection = (socket, runner) => {
96
96
  };
97
97
  const answer = (call) => new Promise((resolve, reject) => {
98
98
  const id = nextCall++;
99
- pending.set(id, (reply) => reply.ok ? resolve(reply.value) : reject(new Error(reply.error)));
99
+ pending.set(id, (reply) => reply.ok ? resolve(reply.value) : reject(errorOfAnswer(reply)));
100
100
  send({
101
101
  type: "call",
102
102
  id,
@@ -17,7 +17,7 @@ var installGuest = (scope, host, shared) => {
17
17
  */
18
18
  const REFUSAL = "ActionRefusal";
19
19
  const isRefusal = (error) => error instanceof Error && error.name === REFUSAL;
20
- const refusal = (message) => Object.assign(new Error(message), { name: REFUSAL });
20
+ const refusal = (message, code) => Object.assign(new Error(message), { name: REFUSAL }, code === void 0 ? {} : { code });
21
21
  const encodeUtf8 = (text) => {
22
22
  const out = [];
23
23
  for (const char of text) {
@@ -561,8 +561,10 @@ var installGuest = (scope, host, shared) => {
561
561
  };
562
562
  const call = async (message) => {
563
563
  const answer = JSON.parse(await host.call(JSON.stringify(message)));
564
- if (!isRecord(answer) || answer.ok !== true) throw new Error(isRecord(answer) && typeof answer.error === "string" ? answer.error : "The platform refused the call");
565
- return answer.value;
564
+ if (isRecord(answer) && answer.ok === true) return answer.value;
565
+ const said = isRecord(answer) && typeof answer.error === "string" ? answer.error : "The platform refused the call";
566
+ if (isRecord(answer) && answer.refused === true) throw refusal(said, typeof answer.code === "string" ? answer.code : void 0);
567
+ throw new Error(said);
566
568
  };
567
569
  const run = new GuestAbortController();
568
570
  const driver = shared.createFunctionsDriver({
@@ -1,5 +1,5 @@
1
1
  import { changeKv } from "../../actions/runtime/kvChange.js";
2
- import { FunctionFailure } from "../protocol.js";
2
+ import { FunctionFailure, failedAnswerOf } from "../protocol.js";
3
3
  import { installGuest } from "./guest.js";
4
4
  import { guestPrelude } from "./prelude.js";
5
5
  import { createFunctionsDriver, describeFunctions } from "../driver.js";
@@ -245,10 +245,7 @@ var createIsolateRunner = ({ concurrency = 8, cacheBytes = 67108864 } = {}) => {
245
245
  value: value ?? null
246
246
  });
247
247
  } catch (error) {
248
- return JSON.stringify({
249
- ok: false,
250
- error: messageOf(error)
251
- });
248
+ return JSON.stringify(failedAnswerOf(error));
252
249
  }
253
250
  }));
254
251
  global.setSync("__plitziSleep", new ivm.Reference((ms) => new Promise((resolve) => later(Math.min(Math.max(0, ms), limits.wallMs), resolve))));
@@ -1,10 +1,10 @@
1
1
  import { ActionRefusal } from "../actions/runtime/errors.js";
2
+ import { readManifest } from "./manifest.js";
2
3
  import { functionContextFor } from "./context.js";
3
4
  import { answerCall, readCall } from "./capabilities.js";
4
5
  import { functionLimitsFor } from "./config.js";
5
6
  import { FunctionFailure } from "./protocol.js";
6
7
  import { taskName } from "../actions/tasks/registry.js";
7
- import { readManifest } from "./manifest.js";
8
8
  import { FunctionsBuildError, buildFunctions } from "./build.js";
9
9
  import { createHash } from "node:crypto";
10
10
  //#region src/modules/functions/space.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@plitzi/sdk-server",
3
- "version": "0.38.21",
3
+ "version": "0.38.23",
4
4
  "license": "AGPL-3.0",
5
5
  "files": [
6
6
  "dist",
@@ -114,8 +114,8 @@
114
114
  "./dist/env.js"
115
115
  ],
116
116
  "dependencies": {
117
- "@plitzi/plitzi-sdk": "0.38.21",
118
- "@plitzi/sdk-shared": "0.38.21",
117
+ "@plitzi/plitzi-sdk": "0.38.23",
118
+ "@plitzi/sdk-shared": "0.38.23",
119
119
  "ejs": "^7.0.2",
120
120
  "esbuild": "^0.28.2",
121
121
  "jsonwebtoken": "^9.0.3",