@plitzi/sdk-server 0.38.18 → 0.38.20

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,94 @@
1
1
  # @plitzi/sdk-server
2
2
 
3
+ ## 0.38.20
4
+
5
+ ### Patch Changes
6
+
7
+ - c7c241a: ## Security
8
+
9
+ - **The `Origin` fallback reads the request's own authority before a forwarded one** (`@plitzi/sdk-server`): 0.38.19
10
+ took `X-Forwarded-Host` first, and with no proxy in front a client could send one naming this host on another port,
11
+ making that port's `Origin` this server's own. Now `:authority` or `Host` decide whenever they name the host the
12
+ request is answered as; `X-Forwarded-Host` only when they do not — a host that took its hostname from the header
13
+ (Express's `trust proxy`) trusts the proxy that wrote it. No option to set: what the host resolved says which one it
14
+ believes. The write guard (`crossSiteWrites`), the sign-in's login-CSRF check and `createOriginGuardMiddleware`
15
+ share it.
16
+
17
+ ## Server
18
+ - **`ctx.oauth`: OAuth 2.0 for a space's code, any provider** (`@plitzi/sdk-server`, `@plitzi/sdk-shared`): a
19
+ connection is data in `defineFunctions({ oauth: { calendar: { issuer | authorizeUrl + tokenUrl, credential, scopes,
20
+ authorizeParams, clientAuth } } })` — an OpenID provider by its `issuer` (endpoints discovered), any other by its
21
+ endpoints; none is known to the platform by name. `ctx.oauth.connect(name, { returnTo, owner? })` answers the
22
+ consent URL (authorization code with PKCE); the platform answers `/fn/oauth/callback` — the one address to register
23
+ with every provider — exchanges the code with the app's id and secret from the named credential, and sends the
24
+ visitor back to `returnTo` with `?oauth=<name>&oauth_result=connected` (or `&oauth_error=`). `ctx.oauth.fetch(name,
25
+ url)` writes the token in, renewed before it lapses and once more on a 401, only to `allow.hosts`; `status` and
26
+ `disconnect` (revoked where the provider says). A token is a signed-in visitor's own by default, `{ owner: 'space' }`
27
+ the space's, or a key of the code's own; it is kept in the space's `kv` sealed with a key of the space's that no
28
+ `ctx.sign` reaches, so the code never holds one. In the sandbox, natively and in a space's runtime alike; a plugin's
29
+ functions declare and reach none. Needs `signingSecret`. Runs also carry the `origin` of the request that started
30
+ them (`ctx.origin` of a task context), what the callback address is made of.
31
+
32
+ ## Packages
33
+ - **No path a package does not export is written anywhere in the packages** (`@plitzi/plitzi-sdk`,
34
+ `@plitzi/sdk-shared`): two JSDoc comments sent readers to `@plitzi/sdk-authoring/testing`, which is not an entry —
35
+ `inspectRenders` is exported by `@plitzi/sdk-authoring`. `yarn check:specifiers` (in CI after the build) reads every
36
+ `@plitzi/<package>/<path>` the workspace writes — the code, its built declarations, JSDoc, skills and docs — against
37
+ what that package exports, so an import somebody would copy into a project and get `ERR_MODULE_NOT_FOUND` from cannot
38
+ be published again.
39
+
40
+ - **The packages that run in Node say which Node** (`@plitzi/sdk-server`, `@plitzi/cli`, `@plitzi/sdk-mcp`,
41
+ `@plitzi/sdk-authoring`): `"engines": { "node": ">=22.18" }`, the floor every project the CLI makes already declares —
42
+ installed on an older Node they now say so, instead of failing on the first API it lacks (`--env-file-if-exists`,
43
+ `--permission`, `Set#union`). The browser's packages declare none: a bundler reads them.
44
+
45
+ - **A short render guide, and each part of it alone** (`@plitzi/sdk-mcp`): `renderGuideText` stays the whole guide
46
+ (~30k characters); `renderGuideCore` is a third of it for an agent that counts its tokens — a voice assistant, a small
47
+ model — with the model of a render, the element types, the host's theme and what to do on a refusal, and the address
48
+ of every other section; `renderGuideTopics[topic]` and `renderGuideTopicUri(topic)` (`plitzi://render/guide/repeat`,
49
+ `…/data`…) serve each one, cut from the one text. The MCP server answers them as resources and through `plitzi_read`.
50
+
51
+ ## CLI
52
+ - **What Plitzi decided reaches the agent writing a report** (`@plitzi/cli`): `plitzi feedback`'s brief lists what was
53
+ reported and kept as it is — with why, and what to do instead — so a report files it under `changed` as `decided`
54
+ rather than carrying it as open, and the page has that status.
55
+
56
+ - **The CLI skill says what `ERR_MODULE_NOT_FOUND` into a `@plitzi` package's `dist` is** (`@plitzi/cli`): an import of
57
+ a path the package does not export — a file rather than its folder — with `plitzi doctor` to name each one and
58
+ `plitzi upgrade migrations --write` to rewrite it.
59
+
60
+ - Updated dependencies [c7c241a]
61
+ - @plitzi/plitzi-sdk@0.38.20
62
+ - @plitzi/sdk-shared@0.38.20
63
+
64
+ ## 0.38.19
65
+
66
+ ### Patch Changes
67
+
68
+ - 92a9f1b: ## Security
69
+
70
+ - **The `Origin` fallback tells the ports apart over HTTP/2 too** (`@plitzi/sdk-server`): a browser that sends no
71
+ `Sec-Fetch-Site` (Safari before 16.4, older webviews) is judged by its `Origin`, compared with the authority the
72
+ request was addressed to. HTTP/2 carries no `Host` header — the authority is `:authority` — and the comparison then
73
+ fell back to the host's NAME, so every port and scheme of it counted as this server's own: what 0.38.18 closed for
74
+ `same-site` stayed open there, over TLS, where a Plitzi server speaks HTTP/2. The authority is now `:authority`,
75
+ `Host`, or the `X-Forwarded-Host` a proxy in front wrote — whichever names the host the request is answered as — port
76
+ included; when none does, the origin is not taken as its own. The write guard (`crossSiteWrites`), the sign-in's
77
+ login-CSRF check and `createOriginGuardMiddleware` share it.
78
+
79
+ ## Packages
80
+ - **The server evaluates rules without the query editor** (`@plitzi/sdk-shared`, `@plitzi/sdk-auth`,
81
+ `@plitzi/sdk-elements`, `@plitzi/sdk-interactions`, `@plitzi/plitzi-builder`): every evaluation of a `when` rule
82
+ group imports `QueryBuilderEvaluator` from `@plitzi/plitzi-ui/QueryBuilder/evaluator` — the evaluator alone — instead
83
+ of the `QueryBuilder` barrel, which brings the editor's React components, or `QueryBuilder/helpers`, which brings the
84
+ SQL and MongoDB formatters. `@plitzi/sdk-shared/helpers` reads `get` and `omit` from `@plitzi/plitzi-ui/helpers/lodash`.
85
+ Importing `@plitzi/sdk-server` loads 19 modules of `@plitzi/plitzi-ui` (26 before) and neither
86
+ `class-variance-authority` nor `clsx`, and starts in ~125 ms (~150 before). Needs `@plitzi/plitzi-ui` 1.6.34.
87
+
88
+ - Updated dependencies [92a9f1b]
89
+ - @plitzi/plitzi-sdk@0.38.19
90
+ - @plitzi/sdk-shared@0.38.19
91
+
3
92
  ## 0.38.18
4
93
 
5
94
  ### 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<"session" | "refresh" | "widget" | "agent" | "access" | "mfaChallenge", number>;
72
+ lifetimes: Record<"refresh" | "access" | "session" | "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;
@@ -67,8 +67,8 @@ export declare const carrierOf: (req: {
67
67
  * `same-origin`, and `none` (a typed URL, a bookmark), are this server's own; `same-site` and `cross-site` are a
68
68
  * page of another origin, foreign unless its origin was named.
69
69
  * - **`Origin`** is the fallback, for a browser too old to send the above — Safari only did from 16.4. Matched
70
- * **exactly** — host and port; one port does not serve two schemes — against this host or an origin the deployment
71
- * named.
70
+ * **exactly** — host and port, over HTTP/1.1 and HTTP/2 alike; one port does not serve two schemes — against the
71
+ * authority the request was addressed to, or an origin the deployment named.
72
72
  *
73
73
  * **`same-site` is not trusted, and was once.** A site is a registrable domain, with no port in it: another port of
74
74
  * this host, or a sibling sub-domain, is the same site. Both are where somebody else's code is served by design —
@@ -76,8 +76,17 @@ var readCookieHeader = (carrier, name) => {
76
76
  }
77
77
  };
78
78
  /**
79
- * Whether `origin` is the request's own: its host and port, as the `Host` header names them. When a proxy rewrote
80
- * `Host` (it no longer names the hostname the request is answered as), the hostname alone is what is left to compare.
79
+ * Whether `origin` is the request's own: its host AND port, as the request was addressed.
80
+ *
81
+ * The authority is the one that names the hostname the request is answered as, compared port included:
82
+ *
83
+ * - **the request's own** first — HTTP/2's `:authority` (which carries no `Host` header at all), or `Host`;
84
+ * - **`X-Forwarded-Host`** only when that does not: a host that took its hostname from the header trusts the proxy in
85
+ * front of it (Express's `trust proxy`), and that proxy wrote it. Read before the request's own, a client could send
86
+ * one naming this host on another port, and that port would count as this server's.
87
+ *
88
+ * None naming it: nothing says which port the request reached, so the origin is not taken as its own — comparing the
89
+ * name alone made every port and every scheme of this host count.
81
90
  */
82
91
  var isOwnOrigin = (origin, carrier) => {
83
92
  let url;
@@ -86,15 +95,22 @@ var isOwnOrigin = (origin, carrier) => {
86
95
  } catch {
87
96
  return false;
88
97
  }
89
- const host = header(carrier, "host");
90
- if (host === void 0) return url.hostname === carrier.hostname;
91
- let own;
92
- try {
93
- own = new URL(`${url.protocol}//${host}`);
94
- } catch {
95
- return false;
98
+ const forwarded = header(carrier, "x-forwarded-host")?.split(",")[0]?.trim();
99
+ for (const authority of [
100
+ header(carrier, ":authority"),
101
+ header(carrier, "host"),
102
+ forwarded
103
+ ]) {
104
+ if (!authority) continue;
105
+ let own;
106
+ try {
107
+ own = new URL(`${url.protocol}//${authority}`);
108
+ } catch {
109
+ continue;
110
+ }
111
+ if (own.hostname === carrier.hostname) return url.host === own.host;
96
112
  }
97
- return own.hostname === carrier.hostname ? url.host === own.host : url.hostname === carrier.hostname;
113
+ return false;
98
114
  };
99
115
  /**
100
116
  * Did a page of another ORIGIN cause this request — `allowed` naming the origins this deployment counts as its own?
@@ -107,8 +123,8 @@ var isOwnOrigin = (origin, carrier) => {
107
123
  * `same-origin`, and `none` (a typed URL, a bookmark), are this server's own; `same-site` and `cross-site` are a
108
124
  * page of another origin, foreign unless its origin was named.
109
125
  * - **`Origin`** is the fallback, for a browser too old to send the above — Safari only did from 16.4. Matched
110
- * **exactly** — host and port; one port does not serve two schemes — against this host or an origin the deployment
111
- * named.
126
+ * **exactly** — host and port, over HTTP/1.1 and HTTP/2 alike; one port does not serve two schemes — against the
127
+ * authority the request was addressed to, or an origin the deployment named.
112
128
  *
113
129
  * **`same-site` is not trusted, and was once.** A site is a registrable domain, with no port in it: another port of
114
130
  * this host, or a sibling sub-domain, is the same site. Both are where somebody else's code is served by design —
@@ -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<"session" | "refresh" | "widget" | "agent" | "access" | "mfaChallenge", number>;
177
+ lifetimes: Record<"refresh" | "access" | "session" | "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;
@@ -0,0 +1 @@
1
+ export {};
@@ -21,6 +21,7 @@ var functionRoutesStage = async (ctx) => {
21
21
  },
22
22
  ...req.ctx.user ? { user: req.ctx.user } : {},
23
23
  callerId: req.ctx.user ? `user:${String(req.ctx.user.id)}` : `ip:${clientIp(ctx.raw, req)}`,
24
+ ...requestOrigin(req) ? { origin: requestOrigin(req) } : {},
24
25
  signal: ctx.signal
25
26
  }, req.method, req.path.slice(FUNCTION_ROUTES_PREFIX.length));
26
27
  if (!route) return false;
@@ -110,6 +110,8 @@ export declare type FunctionContext = {
110
110
  data: (file: string) => Promise<unknown>;
111
111
  /** A line for whoever reads the run: the builder's Try, and the deployment's logs. */
112
112
  log: (...values: unknown[]) => void;
113
+ /** OAuth 2.0 through the space's declared connections — see {@link FunctionOAuth}. */
114
+ oauth: FunctionOAuth;
113
115
  /** Progress for a caller that asked for a stream — a no-op when nobody did. */
114
116
  emit: (chunk: unknown) => void;
115
117
  /** Aborted when the run is: cancelled, or out of time. Hand it to what can stop early. */
@@ -131,6 +133,72 @@ export declare type FunctionFetchInit = {
131
133
  credential?: string;
132
134
  };
133
135
 
136
+ /**
137
+ * OAuth 2.0 on behalf of whoever the space serves, through the connections it declared (`oauth` in its functions): the
138
+ * consent, the code exchanged, the token kept sealed and renewed by the platform. The code never holds a token, as it
139
+ * never holds a credential — it names the connection.
140
+ */
141
+ export declare type FunctionOAuth = {
142
+ /**
143
+ * Where to send the visitor to consent (authorization code, PKCE). They come back to `/fn/oauth/callback` — the
144
+ * address to register with the provider, on the space's host — and from there to `returnTo`, a path of the space,
145
+ * with `?oauth=<connection>&oauth_result=connected` or `&oauth_error=<what>`.
146
+ */
147
+ connect: (connection: string, options: {
148
+ returnTo: string;
149
+ } & FunctionOAuthOwner) => Promise<{
150
+ url: string;
151
+ }>;
152
+ status: (connection: string, options?: FunctionOAuthOwner) => Promise<FunctionOAuthStatus>;
153
+ /**
154
+ * A request to the provider's API with the token written in (`Authorization: Bearer`), renewed when it is about to
155
+ * lapse and once more if the answer is 401. Only to the hosts the space declared (`allow.hosts`).
156
+ */
157
+ fetch: (connection: string, url: string | URL, init?: Omit<FunctionFetchInit, 'credential'> & FunctionOAuthOwner) => Promise<Response>;
158
+ /** Forgets the connection — revoked at the provider when it says where — and answers whether there was one. */
159
+ disconnect: (connection: string, options?: FunctionOAuthOwner) => Promise<boolean>;
160
+ };
161
+
162
+ /** What a space's functions declare, read from the bundle when it is saved: its tasks, routes and reachable hosts. */
163
+ /**
164
+ * One OAuth 2.0 connection a space's code makes on its visitors' (or its own) behalf, declared as data: any provider,
165
+ * none of them known to the platform by name. `issuer` for one that publishes OpenID metadata — its endpoints are read
166
+ * from `<issuer>/.well-known/openid-configuration` — or the endpoints themselves for one that does not.
167
+ */
168
+ declare type FunctionOAuthConnection = {
169
+ /** An OpenID provider's issuer (`https://accounts.google.com`): the endpoints are discovered from it. */
170
+ issuer?: string;
171
+ /** Where the visitor is sent to consent, when there is no `issuer` (or to override what it publishes). */
172
+ authorizeUrl?: string;
173
+ /** Where the code is exchanged and the token refreshed, when there is no `issuer` (or to override it). */
174
+ tokenUrl?: string;
175
+ /** Where a token is revoked on `disconnect`, when the provider has one. */
176
+ revokeUrl?: string;
177
+ /** The space's credential holding the app's `clientId` and `clientSecret`: the code names it, never holds it. */
178
+ credential: string;
179
+ /** What is asked for, as the provider spells it. */
180
+ scopes?: string[];
181
+ /** More of the consent URL, as the provider needs it: `{ access_type: 'offline', prompt: 'consent' }`. */
182
+ authorizeParams?: Record<string, string>;
183
+ /** How the app proves who it is to `tokenUrl`: in the body (the default) or as HTTP Basic. */
184
+ clientAuth?: 'body' | 'basic';
185
+ };
186
+
187
+ /**
188
+ * Whose an OAuth connection is: a signed-in visitor's own by default (`user:<id>`); `space` for one the whole space
189
+ * shares; or a key the code keeps for whom it serves — a profile, a team (`profile:ana`). Letters, digits and `:._@-`.
190
+ */
191
+ export declare type FunctionOAuthOwner = {
192
+ owner?: string;
193
+ };
194
+
195
+ /** What `ctx.oauth.status` says of a connection — never its token. */
196
+ export declare type FunctionOAuthStatus = {
197
+ connected: boolean;
198
+ scopes?: string[];
199
+ expiresAt?: number;
200
+ };
201
+
134
202
  /**
135
203
  * An HTTP endpoint of the space, under `/fn/`: a web-standard handler, the shape every edge runtime runs. The request
136
204
  * carries no credentials — `ctx.user` says who is asking — and the response sets no cookies: the host's are the
@@ -154,6 +222,11 @@ export declare type FunctionsDefinition = {
154
222
  routes?: Record<string, FunctionRoute>;
155
223
  /** More CPU or time than an invocation gets by default, for every task and route — a task may ask for its own. */
156
224
  limits?: FunctionTimeLimits;
225
+ /**
226
+ * The OAuth connections its code makes (`ctx.oauth`), by the name it calls them — any provider, as data: its `issuer`
227
+ * (OpenID) or its endpoints, the credential with the app's id and secret, the scopes.
228
+ */
229
+ oauth?: Record<string, FunctionOAuthConnection>;
157
230
  };
158
231
 
159
232
  /**
@@ -4,7 +4,7 @@
4
4
  * the contract alone, and nothing that runs it.
5
5
  */
6
6
  export { ActionRefusal, defineFunctions } from './modules/functions/contract';
7
- export type { FunctionContext, FunctionFetch, FunctionFetchInit, FunctionRoute, FunctionRouteContext, FunctionsDefinition, FunctionTask, FunctionUser } from './modules/functions/contract';
7
+ export type { FunctionContext, FunctionFetch, FunctionFetchInit, FunctionOAuth, FunctionOAuthOwner, FunctionOAuthStatus, FunctionRoute, FunctionRouteContext, FunctionsDefinition, FunctionTask, FunctionUser } from './modules/functions/contract';
8
8
  export type { FunctionsConfig, FunctionUsageRecord } from './modules/functions/config';
9
9
  export { DEFAULT_FUNCTION_CEILINGS, DEFAULT_FUNCTION_LIMITS } from './modules/functions/config';
10
10
  /**
@@ -12,7 +12,7 @@ export { DEFAULT_FUNCTION_CEILINGS, DEFAULT_FUNCTION_LIMITS } from './modules/fu
12
12
  * when it was saved (`prepareFunctions` on the actions module is the one way to make one).
13
13
  */
14
14
  export type { FunctionsSource } from './modules/functions/build';
15
- export type { FunctionsManifest, FunctionTaskManifest, FunctionsProblem } from '@plitzi/sdk-shared';
15
+ export type { FunctionOAuthConnection, FunctionsManifest, FunctionTaskManifest, FunctionsProblem } from '@plitzi/sdk-shared';
16
16
  export type { FunctionInvocation, FunctionInvokeRequest, FunctionLimits, FunctionRunner, FunctionsBundle, FunctionStopReason, FunctionUsage, SpaceFunctions } from './modules/functions/protocol';
17
17
  export type { PreparedFunctions } from './modules/functions/space';
18
18
  export type { ManifestReading } from './modules/functions/manifest';
@@ -4,6 +4,13 @@ export type SpaceSigning = {
4
4
  sign: (value: string) => Promise<string>;
5
5
  /** Whether `signature` is what `sign` answers for `value` — compared in constant time. */
6
6
  verify: (value: string, signature: string) => Promise<boolean>;
7
+ /**
8
+ * `value` encrypted (AES-256-GCM) with a key of the space's own that no signature reaches: what the platform keeps for
9
+ * a space and its code must not read — an OAuth token in the space's `kv`. base64url, a fresh IV each time.
10
+ */
11
+ seal: (value: string) => string;
12
+ /** What `seal` encrypted — `undefined` for anything it did not, or that was changed since. */
13
+ open: (sealed: string) => string | undefined;
7
14
  };
8
15
  /** A signing secret is what every link and key a space hands out stands on: as long as a 256-bit key written out. */
9
16
  export declare const MIN_SIGNING_SECRET_LENGTH = 32;
@@ -1,4 +1,4 @@
1
- import { createHmac, timingSafeEqual } from "node:crypto";
1
+ import { createCipheriv, createDecipheriv, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
2
2
  //#region src/modules/actions/runtime/signing.ts
3
3
  /** A signing secret is what every link and key a space hands out stands on: as long as a 256-bit key written out. */
4
4
  var MIN_SIGNING_SECRET_LENGTH = 32;
@@ -14,12 +14,34 @@ var createSigning = (secret) => {
14
14
  return ({ spaceId, environment }) => {
15
15
  const key = createHmac("sha256", secret).update(`space-signing:${String(spaceId)}:${environment}`).digest();
16
16
  const signatureOf = (value) => createHmac("sha256", key).update(value).digest("base64url");
17
+ const sealing = createHmac("sha256", secret).update(`space-sealing:${String(spaceId)}:${environment}`).digest();
17
18
  return {
18
19
  sign: (value) => Promise.resolve(signatureOf(value)),
19
20
  verify: (value, signature) => {
20
21
  const expected = Buffer.from(signatureOf(value));
21
22
  const given = Buffer.from(signature);
22
23
  return Promise.resolve(given.length === expected.length && timingSafeEqual(given, expected));
24
+ },
25
+ seal: (value) => {
26
+ const iv = randomBytes(12);
27
+ const cipher = createCipheriv("aes-256-gcm", sealing, iv);
28
+ const body = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]);
29
+ return Buffer.concat([
30
+ iv,
31
+ cipher.getAuthTag(),
32
+ body
33
+ ]).toString("base64url");
34
+ },
35
+ open: (sealed) => {
36
+ const bytes = Buffer.from(sealed, "base64url");
37
+ if (bytes.length < 28) return;
38
+ try {
39
+ const decipher = createDecipheriv("aes-256-gcm", sealing, bytes.subarray(0, 12));
40
+ decipher.setAuthTag(bytes.subarray(12, 28));
41
+ return Buffer.concat([decipher.update(bytes.subarray(28)), decipher.final()]).toString("utf8");
42
+ } catch {
43
+ return;
44
+ }
23
45
  }
24
46
  };
25
47
  };
@@ -33,7 +33,7 @@ export type TaskContextDeps = {
33
33
  later: LaterDeps;
34
34
  };
35
35
  /** Who and what the context is for — a run's request, or anything shaped like one (a function's route). */
36
- export type TaskContextRequest = Pick<ActionRunRequest, 'runId' | 'spaceId' | 'environment' | 'trigger' | 'user' | 'callerId' | 'at' | 'emit'>;
36
+ export type TaskContextRequest = Pick<ActionRunRequest, 'runId' | 'spaceId' | 'environment' | 'trigger' | 'user' | 'callerId' | 'at' | 'emit' | 'origin'>;
37
37
  /**
38
38
  * What a task runs with — the one place it is made, for a step of a run and for a function answering a route alike:
39
39
  * every secret it resolves registered with the redactor, the space's `kv` namespace, the run's outbound budget, the
@@ -72,6 +72,7 @@ var taskContextFor = (config, { kv, email, redactor, signing, later }, request,
72
72
  const readData = projectDataReader(config.lookups.getData, request.spaceId, request.at);
73
73
  return (scope) => ({
74
74
  runId: request.runId,
75
+ ...request.origin ? { origin: request.origin } : {},
75
76
  spaceId: request.spaceId,
76
77
  environment: request.environment,
77
78
  trigger: request.trigger,
@@ -1,6 +1,7 @@
1
1
  import { serverLog } from "../../../helpers/serverLog.js";
2
2
  import { triggerParams } from "../runtime/triggers.js";
3
3
  import { ActionRunError } from "../runtime/errors.js";
4
+ import { requestOrigin } from "../../../core/requestParser.js";
4
5
  import { forcedFlagsFor } from "../../../helpers/flagOverrides.js";
5
6
  import { precheckRun } from "../runtime/precheck.js";
6
7
  import onAbort from "../../../helpers/onAbort.js";
@@ -108,6 +109,7 @@ var handleActionCall = async (deps) => {
108
109
  return;
109
110
  }
110
111
  const limits = module.limitsFor(entry.document);
112
+ const origin = requestOrigin(req);
111
113
  const input = body.input ?? {};
112
114
  const begin = {
113
115
  spaceId,
@@ -193,6 +195,7 @@ var handleActionCall = async (deps) => {
193
195
  trigger: "call",
194
196
  user: req.ctx.user,
195
197
  callerId,
198
+ ...origin ? { origin } : {},
196
199
  runId: run.runId,
197
200
  lineage,
198
201
  at: {
@@ -207,6 +207,15 @@ export type ActionTaskContext = {
207
207
  /** Signs with the space's own key (`ActionsConfig.signingSecret`) — `undefined` when the deployment gave none. */
208
208
  sign?: SpaceSigning['sign'];
209
209
  verify?: SpaceSigning['verify'];
210
+ /** Encrypts what the platform keeps for the space and its code must not read — `undefined` with no signingSecret. */
211
+ seal?: SpaceSigning['seal'];
212
+ open?: SpaceSigning['open'];
213
+ /**
214
+ * The public origin of the request that started the run (`https://shop.example.com`), as the server resolved it —
215
+ * what an address back to the space is made of (an OAuth `redirect_uri`). `undefined` for a run no request started:
216
+ * a schedule, a job.
217
+ */
218
+ origin?: string;
210
219
  /**
211
220
  * One file of the space's data (`products.json`), parsed, as of the run's revision — read-only, and refused when
212
221
  * the deployment keeps no data (`lookups.getData`, or `dataDir`). One lookup per run, whichever step reads it.
@@ -409,6 +418,8 @@ export type ActionRunRequest = {
409
418
  user?: SSRUser;
410
419
  /** Who is asking. Stated by whatever started the run — see {@link ActionTaskContext.callerId}. */
411
420
  callerId: string;
421
+ /** The public origin of the request that started it — see {@link ActionTaskContext.origin}. */
422
+ origin?: string;
412
423
  runId: string;
413
424
  /** Chain of run ids that caused this one; a run naming its own action is refused before its first node. */
414
425
  lineage?: string[];
@@ -129,6 +129,40 @@ var fetchInitOf = (value) => {
129
129
  };
130
130
  };
131
131
  var optionalString = (value, what) => value === void 0 || value === null ? void 0 : stringArg(value, what);
132
+ /** A call to `ctx.oauth`, read into the one method it names: what each method takes, and an owner only as a string. */
133
+ var oauthCallOf = (call) => {
134
+ const connection = stringArg(call.connection, "An OAuth connection");
135
+ const owner = optionalString(call.owner, "An OAuth owner");
136
+ const own = owner === void 0 ? {} : { owner };
137
+ switch (call.method) {
138
+ case "connect": return {
139
+ op: "oauth",
140
+ method: "connect",
141
+ connection,
142
+ returnTo: stringArg(call.returnTo, "returnTo"),
143
+ ...own
144
+ };
145
+ case "status":
146
+ case "disconnect": return {
147
+ op: "oauth",
148
+ method: call.method,
149
+ connection,
150
+ ...own
151
+ };
152
+ case "fetch": {
153
+ const { credential: _credential, ...init } = fetchInitOf(call.init ?? {});
154
+ return {
155
+ op: "oauth",
156
+ method: "fetch",
157
+ connection,
158
+ url: stringArg(call.url, "A URL"),
159
+ init,
160
+ ...own
161
+ };
162
+ }
163
+ default: throw new CallError("Not an OAuth method the platform answers");
164
+ }
165
+ };
132
166
  /** What a run set for later is checked against where it is queued (`laterFor`); here only that it is what it claims. */
133
167
  var laterOf = (value) => {
134
168
  const request = recordArg(value, "A run set for later");
@@ -214,6 +248,7 @@ var readCall = (value) => {
214
248
  op: "data",
215
249
  file: stringArg(call.file, "A file")
216
250
  };
251
+ case "oauth": return oauthCallOf(call);
217
252
  case "log": return {
218
253
  op: "log",
219
254
  values: Array.isArray(call.values) ? call.values : []
@@ -242,6 +277,20 @@ var answerCall = async (ctx, call) => {
242
277
  case "sign": return ctx.sign(call.value);
243
278
  case "verify": return ctx.verify(call.value, call.signature);
244
279
  case "data": return ctx.data(call.file);
280
+ case "oauth":
281
+ switch (call.method) {
282
+ case "connect": return ctx.oauth.connect(call.connection, {
283
+ returnTo: call.returnTo,
284
+ ...call.owner === void 0 ? {} : { owner: call.owner }
285
+ });
286
+ case "status": return ctx.oauth.status(call.connection, call.owner === void 0 ? {} : { owner: call.owner });
287
+ case "disconnect": return ctx.oauth.disconnect(call.connection, call.owner === void 0 ? {} : { owner: call.owner });
288
+ case "fetch": return wireResponseOf(await ctx.oauth.fetch(call.connection, call.url, {
289
+ ...call.init,
290
+ ...call.owner === void 0 ? {} : { owner: call.owner }
291
+ }));
292
+ }
293
+ break;
245
294
  case "log":
246
295
  ctx.log(...call.values);
247
296
  return;
@@ -1,6 +1,7 @@
1
1
  import { FunctionContext } from './contract';
2
2
  import { FunctionScope } from './scope';
3
3
  import { ActionTaskContext } from '../actions/types';
4
+ import { FunctionOAuthConnection } from '@plitzi/sdk-shared';
4
5
  /**
5
6
  * Whether `hostname` is one the space declared: exactly, or under a `*.` wildcard (`*.example.com` is every subdomain of
6
7
  * it, and not `example.com` itself).
@@ -16,4 +17,4 @@ export declare const lineOf: (values: readonly unknown[]) => string;
16
17
  * A self-hosted server hands it to the code directly; the platform answers the sandbox's calls with it. With a `scope`,
17
18
  * it is a plugin's code, and gets the plugin's corner of the space (`./scope`).
18
19
  */
19
- export declare const functionContextFor: (ctx: ActionTaskContext, hosts: readonly string[], scope?: FunctionScope) => FunctionContext;
20
+ export declare const functionContextFor: (ctx: ActionTaskContext, hosts: readonly string[], scope?: FunctionScope, oauth?: Readonly<Record<string, FunctionOAuthConnection>>) => FunctionContext;
@@ -1,6 +1,7 @@
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";
4
5
  import { pluginKvPrefix, pluginSigned } from "./scope.js";
5
6
  import { processTwigParam } from "@plitzi/sdk-shared/helpers/twigWrapper";
6
7
  //#region src/modules/functions/context.ts
@@ -76,7 +77,7 @@ var noData = (file) => Promise.reject(/* @__PURE__ */ new Error(`The functions o
76
77
  * A self-hosted server hands it to the code directly; the platform answers the sandbox's calls with it. With a `scope`,
77
78
  * it is a plugin's code, and gets the plugin's corner of the space (`./scope`).
78
79
  */
79
- var functionContextFor = (ctx, hosts, scope) => {
80
+ var functionContextFor = (ctx, hosts, scope, oauth = {}) => {
80
81
  const shared = {
81
82
  spaceId: ctx.spaceId,
82
83
  environment: ctx.environment,
@@ -100,7 +101,10 @@ var functionContextFor = (ctx, hosts, scope) => {
100
101
  revoke: ctx.revoke ?? unavailable("revoke"),
101
102
  later: ctx.later ?? noJobs,
102
103
  cancelLater: ctx.cancelLater ?? noJobs,
103
- data: ctx.data
104
+ data: ctx.data,
105
+ oauth: oauthFor(ctx, oauth, (url) => {
106
+ if (!hostAllowed(url.hostname, hosts)) throw new Error(`"${url.hostname}" is not among the hosts this space's functions may reach (allow.hosts)`);
107
+ })
104
108
  };
105
109
  const kv = prefixKv(ctx.kv, pluginKvPrefix(scope.plugin));
106
110
  const { sign, verify } = ctx;
@@ -117,7 +121,8 @@ var functionContextFor = (ctx, hosts, scope) => {
117
121
  revoke: noChannel,
118
122
  later: noLater,
119
123
  cancelLater: noLater,
120
- data: noData
124
+ data: noData,
125
+ oauth: noOAuth("The functions of a plugin make none of the OAuth connections of its space")
121
126
  };
122
127
  };
123
128
  //#endregion
@@ -1,7 +1,7 @@
1
1
  import { LaterAnswer, LaterRequest } from '../actions/jobs/later';
2
2
  import { RateCount, RateLimit } from '../actions/runtime/rateLimit';
3
3
  import { ActionKvStore } from '../actions/types';
4
- import { Environment, FunctionTimeLimits, InteractionCallbackParam } from '@plitzi/sdk-shared';
4
+ import { Environment, FunctionOAuthConnection, FunctionTimeLimits, InteractionCallbackParam } from '@plitzi/sdk-shared';
5
5
  /**
6
6
  * Who started the run, as a space's own code may know them: everything a function decides by — who, their roles and
7
7
  * permissions — and never their session. A token inside the sandbox is a token a function could send anywhere.
@@ -27,6 +27,44 @@ export type FunctionFetchInit = {
27
27
  };
28
28
  /** What a function's `fetch` answers: a web `Response`, whichever runner it is in. */
29
29
  export type FunctionFetch = (url: string | URL, init?: FunctionFetchInit) => Promise<Response>;
30
+ /**
31
+ * Whose an OAuth connection is: a signed-in visitor's own by default (`user:<id>`); `space` for one the whole space
32
+ * shares; or a key the code keeps for whom it serves — a profile, a team (`profile:ana`). Letters, digits and `:._@-`.
33
+ */
34
+ export type FunctionOAuthOwner = {
35
+ owner?: string;
36
+ };
37
+ /** What `ctx.oauth.status` says of a connection — never its token. */
38
+ export type FunctionOAuthStatus = {
39
+ connected: boolean;
40
+ scopes?: string[];
41
+ expiresAt?: number;
42
+ };
43
+ /**
44
+ * OAuth 2.0 on behalf of whoever the space serves, through the connections it declared (`oauth` in its functions): the
45
+ * consent, the code exchanged, the token kept sealed and renewed by the platform. The code never holds a token, as it
46
+ * never holds a credential — it names the connection.
47
+ */
48
+ export type FunctionOAuth = {
49
+ /**
50
+ * Where to send the visitor to consent (authorization code, PKCE). They come back to `/fn/oauth/callback` — the
51
+ * address to register with the provider, on the space's host — and from there to `returnTo`, a path of the space,
52
+ * with `?oauth=<connection>&oauth_result=connected` or `&oauth_error=<what>`.
53
+ */
54
+ connect: (connection: string, options: {
55
+ returnTo: string;
56
+ } & FunctionOAuthOwner) => Promise<{
57
+ url: string;
58
+ }>;
59
+ status: (connection: string, options?: FunctionOAuthOwner) => Promise<FunctionOAuthStatus>;
60
+ /**
61
+ * A request to the provider's API with the token written in (`Authorization: Bearer`), renewed when it is about to
62
+ * lapse and once more if the answer is 401. Only to the hosts the space declared (`allow.hosts`).
63
+ */
64
+ fetch: (connection: string, url: string | URL, init?: Omit<FunctionFetchInit, 'credential'> & FunctionOAuthOwner) => Promise<Response>;
65
+ /** Forgets the connection — revoked at the provider when it says where — and answers whether there was one. */
66
+ disconnect: (connection: string, options?: FunctionOAuthOwner) => Promise<boolean>;
67
+ };
30
68
  /**
31
69
  * Everything a space's code can do besides computing — one object, the same wherever it runs. In a self-hosted server
32
70
  * it is built from the run's own context; in the sandbox each method is a call back to the platform, which scopes it
@@ -84,6 +122,8 @@ export type FunctionContext = {
84
122
  data: (file: string) => Promise<unknown>;
85
123
  /** A line for whoever reads the run: the builder's Try, and the deployment's logs. */
86
124
  log: (...values: unknown[]) => void;
125
+ /** OAuth 2.0 through the space's declared connections — see {@link FunctionOAuth}. */
126
+ oauth: FunctionOAuth;
87
127
  /** Progress for a caller that asked for a stream — a no-op when nobody did. */
88
128
  emit: (chunk: unknown) => void;
89
129
  /** Aborted when the run is: cancelled, or out of time. Hand it to what can stop early. */
@@ -131,6 +171,11 @@ export type FunctionsDefinition = {
131
171
  routes?: Record<string, FunctionRoute>;
132
172
  /** More CPU or time than an invocation gets by default, for every task and route — a task may ask for its own. */
133
173
  limits?: FunctionTimeLimits;
174
+ /**
175
+ * The OAuth connections its code makes (`ctx.oauth`), by the name it calls them — any provider, as data: its `issuer`
176
+ * (OpenID) or its endpoints, the credential with the app's id and secret, the scopes.
177
+ */
178
+ oauth?: Record<string, FunctionOAuthConnection>;
134
179
  };
135
180
  /**
136
181
  * What a function throws to refuse, with a reason written for whoever asked — a wrong password, a board that is