@plitzi/sdk-server 0.38.19 → 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 +61 -0
- package/dist/core/auth/createAuth.d.ts +1 -1
- package/dist/core/auth/csrf.js +13 -8
- package/dist/core/auth/tokens.d.ts +1 -1
- package/dist/core/createServer.oauth.test.d.ts +1 -0
- package/dist/core/services/functionRoutes.js +1 -0
- package/dist/functions-api.d.ts +73 -0
- package/dist/functions.d.ts +2 -2
- package/dist/modules/actions/runtime/signing.d.ts +7 -0
- package/dist/modules/actions/runtime/signing.js +23 -1
- package/dist/modules/actions/runtime/taskContext.d.ts +1 -1
- package/dist/modules/actions/runtime/taskContext.js +1 -0
- package/dist/modules/actions/transport/callHandler.js +3 -0
- package/dist/modules/actions/types.d.ts +11 -0
- package/dist/modules/functions/capabilities.js +49 -0
- package/dist/modules/functions/context.d.ts +2 -1
- package/dist/modules/functions/context.js +8 -3
- package/dist/modules/functions/contract.d.ts +46 -1
- package/dist/modules/functions/driver.js +35 -1
- package/dist/modules/functions/manifest.js +83 -1
- package/dist/modules/functions/native.js +1 -1
- package/dist/modules/functions/oauth.d.ts +30 -0
- package/dist/modules/functions/oauth.js +313 -0
- package/dist/modules/functions/oauth.test.d.ts +1 -0
- package/dist/modules/functions/protocol.d.ts +18 -0
- package/dist/modules/functions/routes.d.ts +2 -0
- package/dist/modules/functions/routes.js +30 -14
- package/dist/modules/functions/space.js +1 -1
- package/package.json +6 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,66 @@
|
|
|
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
|
+
|
|
3
64
|
## 0.38.19
|
|
4
65
|
|
|
5
66
|
### 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<"
|
|
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;
|
package/dist/core/auth/csrf.js
CHANGED
|
@@ -76,12 +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 request was addressed
|
|
80
|
-
*
|
|
81
|
-
*
|
|
82
|
-
*
|
|
83
|
-
*
|
|
84
|
-
*
|
|
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.
|
|
85
90
|
*/
|
|
86
91
|
var isOwnOrigin = (origin, carrier) => {
|
|
87
92
|
let url;
|
|
@@ -92,9 +97,9 @@ var isOwnOrigin = (origin, carrier) => {
|
|
|
92
97
|
}
|
|
93
98
|
const forwarded = header(carrier, "x-forwarded-host")?.split(",")[0]?.trim();
|
|
94
99
|
for (const authority of [
|
|
95
|
-
forwarded,
|
|
96
100
|
header(carrier, ":authority"),
|
|
97
|
-
header(carrier, "host")
|
|
101
|
+
header(carrier, "host"),
|
|
102
|
+
forwarded
|
|
98
103
|
]) {
|
|
99
104
|
if (!authority) continue;
|
|
100
105
|
let own;
|
|
@@ -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<"
|
|
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;
|
package/dist/functions-api.d.ts
CHANGED
|
@@ -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
|
/**
|
package/dist/functions.d.ts
CHANGED
|
@@ -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
|
|
@@ -18,7 +18,8 @@ var describeFunctions = (definition) => {
|
|
|
18
18
|
limits: task.limits
|
|
19
19
|
} : {}),
|
|
20
20
|
routes: isRecord(found.routes) ? Object.keys(found.routes) : [],
|
|
21
|
-
limits: found.limits
|
|
21
|
+
limits: found.limits,
|
|
22
|
+
oauth: found.oauth
|
|
22
23
|
};
|
|
23
24
|
};
|
|
24
25
|
/**
|
|
@@ -129,6 +130,39 @@ var createFunctionsDriver = (environment) => {
|
|
|
129
130
|
op: "data",
|
|
130
131
|
file
|
|
131
132
|
}),
|
|
133
|
+
oauth: {
|
|
134
|
+
connect: (connection, options = {}) => call({
|
|
135
|
+
op: "oauth",
|
|
136
|
+
method: "connect",
|
|
137
|
+
connection,
|
|
138
|
+
returnTo: options.returnTo,
|
|
139
|
+
owner: options.owner
|
|
140
|
+
}),
|
|
141
|
+
status: (connection, options = {}) => call({
|
|
142
|
+
op: "oauth",
|
|
143
|
+
method: "status",
|
|
144
|
+
connection,
|
|
145
|
+
owner: options.owner
|
|
146
|
+
}),
|
|
147
|
+
disconnect: (connection, options = {}) => call({
|
|
148
|
+
op: "oauth",
|
|
149
|
+
method: "disconnect",
|
|
150
|
+
connection,
|
|
151
|
+
owner: options.owner
|
|
152
|
+
}),
|
|
153
|
+
fetch: async (connection, url, init = {}) => {
|
|
154
|
+
const { owner, ...rest } = init;
|
|
155
|
+
const answer = await call({
|
|
156
|
+
op: "oauth",
|
|
157
|
+
method: "fetch",
|
|
158
|
+
connection,
|
|
159
|
+
url: String(url),
|
|
160
|
+
init: rest,
|
|
161
|
+
owner
|
|
162
|
+
});
|
|
163
|
+
return responseOf(isRecord(answer) ? answer : {});
|
|
164
|
+
}
|
|
165
|
+
},
|
|
132
166
|
log,
|
|
133
167
|
emit: (chunk) => {
|
|
134
168
|
call({
|
|
@@ -29,6 +29,82 @@ var parseRouteKey = (key) => {
|
|
|
29
29
|
};
|
|
30
30
|
};
|
|
31
31
|
var HOST = /^(\*\.)?([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/;
|
|
32
|
+
/** Where the platform answers the visitor back from an OAuth provider: no route of a space's may be it. */
|
|
33
|
+
var OAUTH_CALLBACK_SEGMENTS = ["oauth", "callback"];
|
|
34
|
+
var CONNECTION_NAME = /^[A-Za-z][A-Za-z0-9-]{0,63}$/;
|
|
35
|
+
/** What the platform writes into the consent URL itself: `authorizeParams` may add to it, never change it. */
|
|
36
|
+
var OWN_AUTHORIZE_PARAMS = /* @__PURE__ */ new Set([
|
|
37
|
+
"response_type",
|
|
38
|
+
"client_id",
|
|
39
|
+
"redirect_uri",
|
|
40
|
+
"state",
|
|
41
|
+
"code_challenge",
|
|
42
|
+
"code_challenge_method",
|
|
43
|
+
"scope"
|
|
44
|
+
]);
|
|
45
|
+
var httpsUrl = (value) => {
|
|
46
|
+
if (typeof value !== "string") return;
|
|
47
|
+
try {
|
|
48
|
+
return new URL(value).protocol === "https:" ? value : void 0;
|
|
49
|
+
} catch {
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
/**
|
|
54
|
+
* The OAuth connections a definition declared, rebuilt field by field: each a provider's issuer or its endpoints (https),
|
|
55
|
+
* the credential with the app's id and secret, the scopes. What is wrong is said by connection, and that one left out.
|
|
56
|
+
*/
|
|
57
|
+
var oauthOf = (value, problems, scope) => {
|
|
58
|
+
if (value === void 0 || value === null) return;
|
|
59
|
+
if (scope) {
|
|
60
|
+
problems.push("The functions of a plugin declare no OAuth connections: only its space does (oauth)");
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
if (!isRecord(value)) {
|
|
64
|
+
problems.push("oauth is an object of connections, by the name the code calls them");
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
const connections = {};
|
|
68
|
+
for (const [name, entry] of Object.entries(value)) {
|
|
69
|
+
const where = `OAuth connection "${name}"`;
|
|
70
|
+
const said = problems.length;
|
|
71
|
+
if (!CONNECTION_NAME.test(name)) problems.push(`${where}: a name is a letter, then letters, digits and "-", up to 64`);
|
|
72
|
+
const spec = isRecord(entry) ? entry : {};
|
|
73
|
+
const credential = stringOf(spec.credential);
|
|
74
|
+
if (!credential) problems.push(`${where} names no credential: the space's credential with the app's clientId and clientSecret`);
|
|
75
|
+
const urls = {};
|
|
76
|
+
for (const field of [
|
|
77
|
+
"issuer",
|
|
78
|
+
"authorizeUrl",
|
|
79
|
+
"tokenUrl",
|
|
80
|
+
"revokeUrl"
|
|
81
|
+
]) {
|
|
82
|
+
if (spec[field] === void 0) continue;
|
|
83
|
+
const url = httpsUrl(spec[field]);
|
|
84
|
+
if (url) urls[field] = url;
|
|
85
|
+
else problems.push(`${where}: ${field} is an https URL`);
|
|
86
|
+
}
|
|
87
|
+
if (!urls.issuer && !(urls.authorizeUrl && urls.tokenUrl)) problems.push(`${where}: an issuer (OpenID), or its authorizeUrl and tokenUrl`);
|
|
88
|
+
const scopes = Array.isArray(spec.scopes) ? spec.scopes : [];
|
|
89
|
+
if (spec.scopes !== void 0 && (!Array.isArray(spec.scopes) || !scopes.every((each) => typeof each === "string"))) problems.push(`${where}: scopes are strings`);
|
|
90
|
+
const params = isRecord(spec.authorizeParams) ? spec.authorizeParams : {};
|
|
91
|
+
if (spec.authorizeParams !== void 0 && !isRecord(spec.authorizeParams)) problems.push(`${where}: authorizeParams is an object of strings`);
|
|
92
|
+
const authorizeParams = {};
|
|
93
|
+
for (const [key, param] of Object.entries(params)) if (OWN_AUTHORIZE_PARAMS.has(key)) problems.push(`${where}: authorizeParams.${key} is the platform's to write`);
|
|
94
|
+
else if (typeof param === "string") authorizeParams[key] = param;
|
|
95
|
+
else problems.push(`${where}: authorizeParams.${key} is a string`);
|
|
96
|
+
if (spec.clientAuth !== void 0 && spec.clientAuth !== "body" && spec.clientAuth !== "basic") problems.push(`${where}: clientAuth is "body" or "basic"`);
|
|
97
|
+
if (problems.length > said || !credential) continue;
|
|
98
|
+
connections[name] = {
|
|
99
|
+
...urls,
|
|
100
|
+
credential,
|
|
101
|
+
...scopes.length ? { scopes: scopes.filter((each) => typeof each === "string") } : {},
|
|
102
|
+
...Object.keys(authorizeParams).length ? { authorizeParams } : {},
|
|
103
|
+
...spec.clientAuth === "basic" || spec.clientAuth === "body" ? { clientAuth: spec.clientAuth } : {}
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
return Object.keys(connections).length ? connections : void 0;
|
|
107
|
+
};
|
|
32
108
|
var stringOf = (value) => typeof value === "string" ? value : void 0;
|
|
33
109
|
var optionsOf = (value) => Array.isArray(value) ? value.flatMap((option) => {
|
|
34
110
|
const label = isRecord(option) ? stringOf(option.label) : void 0;
|
|
@@ -197,17 +273,23 @@ var readManifest = (value, reserved, ceilings, scope) => {
|
|
|
197
273
|
problems.push(reservedRouteProblem(route));
|
|
198
274
|
return;
|
|
199
275
|
}
|
|
276
|
+
if (key.segments.join("/") === OAUTH_CALLBACK_SEGMENTS.join("/")) {
|
|
277
|
+
problems.push(`Route "${route}" is /oauth/callback, where the platform answers the visitor back from an OAuth provider`);
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
200
280
|
const shape = `${key.method} /${key.segments.map((segment) => segment.startsWith(":") ? ":" : segment).join("/")}`;
|
|
201
281
|
if (routed.has(shape)) problems.push(`Route "${route}" answers the same requests as another one`);
|
|
202
282
|
routed.add(shape);
|
|
203
283
|
});
|
|
204
284
|
const limits = limitsOf(raw.limits, "The functions", ceilings, problems);
|
|
285
|
+
const oauth = oauthOf(raw.oauth, problems, scope);
|
|
205
286
|
return {
|
|
206
287
|
manifest: {
|
|
207
288
|
hosts,
|
|
208
289
|
tasks,
|
|
209
290
|
routes,
|
|
210
|
-
...limits ? { limits } : {}
|
|
291
|
+
...limits ? { limits } : {},
|
|
292
|
+
...oauth ? { oauth } : {}
|
|
211
293
|
},
|
|
212
294
|
problems
|
|
213
295
|
};
|
|
@@ -6,7 +6,7 @@ import { functionContextFor } from "./context.js";
|
|
|
6
6
|
* space runs in the sandbox, loaded without one.
|
|
7
7
|
*/
|
|
8
8
|
var nativeTasks = (definitions = [], scope) => definitions.flatMap((definition) => (definition.tasks ?? []).map((task) => {
|
|
9
|
-
const contextFor = (ctx) => functionContextFor(ctx, definition.allow?.hosts ?? [], scope);
|
|
9
|
+
const contextFor = (ctx) => functionContextFor(ctx, definition.allow?.hosts ?? [], scope, definition.oauth);
|
|
10
10
|
const { run, params } = task;
|
|
11
11
|
return {
|
|
12
12
|
namespace: task.namespace,
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { FunctionOAuth } from './contract';
|
|
2
|
+
import { ActionTaskContext } from '../actions/types';
|
|
3
|
+
import { FunctionOAuthConnection } from '@plitzi/sdk-shared';
|
|
4
|
+
/**
|
|
5
|
+
* OAuth 2.0 for a space's code (`ctx.oauth`): any provider, declared as data — none is known here by name.
|
|
6
|
+
*
|
|
7
|
+
* The authorization code flow with PKCE: `connect` makes the consent URL and remembers, sealed in the space's `kv` for
|
|
8
|
+
* ten minutes, who asked and where they go back; the provider sends the visitor to `/fn/oauth/callback`, which
|
|
9
|
+
* exchanges the code with the app's id and secret (a credential of the space's, resolved here) and keeps the tokens
|
|
10
|
+
* sealed under the connection and its owner; `fetch` writes the access token into a request, renewing it first when it
|
|
11
|
+
* is about to lapse and once more on a 401. Sealed with the space's own key, which no signature of `ctx.sign` reaches:
|
|
12
|
+
* the code reads only ciphertext, even with `ctx.kv`.
|
|
13
|
+
*/
|
|
14
|
+
/** Where the provider sends the visitor back, under `/fn` — the one address to register with every provider. */
|
|
15
|
+
export declare const OAUTH_CALLBACK_PATH = "/oauth/callback";
|
|
16
|
+
/** What the parts of a run `ctx.oauth` uses are: its fetch, its kv, its credentials, its sealing, who and where. */
|
|
17
|
+
export type OAuthRun = Pick<ActionTaskContext, 'fetch' | 'kv' | 'credential' | 'seal' | 'open' | 'origin' | 'user' | 'signal'>;
|
|
18
|
+
/**
|
|
19
|
+
* `ctx.oauth` for one run, over the connections its code declared. `hosts` are where `fetch` may write the token — the
|
|
20
|
+
* same `allow.hosts` every request of the code is held to.
|
|
21
|
+
*/
|
|
22
|
+
export declare const oauthFor: (run: OAuthRun, connections: Readonly<Record<string, FunctionOAuthConnection>>, allowed: (url: URL) => void) => FunctionOAuth;
|
|
23
|
+
/** `ctx.oauth` where there is none to give — a plugin's code: the space's connections are the space's. */
|
|
24
|
+
export declare const noOAuth: (why: string) => FunctionOAuth;
|
|
25
|
+
/**
|
|
26
|
+
* The visitor back from the provider (`/fn/oauth/callback`): the consent it remembered taken (once), the code
|
|
27
|
+
* exchanged, the tokens kept — and the visitor sent where the code said, told how it went. A visit with no consent
|
|
28
|
+
* under way is answered, not redirected: there is nowhere of the space's to send it.
|
|
29
|
+
*/
|
|
30
|
+
export declare const oauthCallback: (run: OAuthRun, query: URLSearchParams) => Promise<Response>;
|
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
import { ActionRefusal } from "../actions/runtime/errors.js";
|
|
2
|
+
import { fetchOutbound } from "../../helpers/outboundGuard.js";
|
|
3
|
+
import { FUNCTION_ROUTES_PREFIX } from "@plitzi/sdk-shared/actions";
|
|
4
|
+
import { isRecord } from "@plitzi/sdk-shared/helpers";
|
|
5
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
6
|
+
//#region src/modules/functions/oauth.ts
|
|
7
|
+
/**
|
|
8
|
+
* OAuth 2.0 for a space's code (`ctx.oauth`): any provider, declared as data — none is known here by name.
|
|
9
|
+
*
|
|
10
|
+
* The authorization code flow with PKCE: `connect` makes the consent URL and remembers, sealed in the space's `kv` for
|
|
11
|
+
* ten minutes, who asked and where they go back; the provider sends the visitor to `/fn/oauth/callback`, which
|
|
12
|
+
* exchanges the code with the app's id and secret (a credential of the space's, resolved here) and keeps the tokens
|
|
13
|
+
* sealed under the connection and its owner; `fetch` writes the access token into a request, renewing it first when it
|
|
14
|
+
* is about to lapse and once more on a 401. Sealed with the space's own key, which no signature of `ctx.sign` reaches:
|
|
15
|
+
* the code reads only ciphertext, even with `ctx.kv`.
|
|
16
|
+
*/
|
|
17
|
+
/** Where the provider sends the visitor back, under `/fn` — the one address to register with every provider. */
|
|
18
|
+
var OAUTH_CALLBACK_PATH = "/oauth/callback";
|
|
19
|
+
var STATE_SECONDS = 600;
|
|
20
|
+
/** A token this close to lapsing is renewed before it is used. */
|
|
21
|
+
var RENEW_BEFORE_MS = 6e4;
|
|
22
|
+
/** How long an issuer's endpoints are kept once read. */
|
|
23
|
+
var DISCOVERY_MS = 36e5;
|
|
24
|
+
var OWNER = /^[\w:.@-]{1,128}$/;
|
|
25
|
+
var KEY_PREFIX = "plitzi:oauth";
|
|
26
|
+
var stateKey = (state) => `${KEY_PREFIX}:state:${state}`;
|
|
27
|
+
var tokenKey = (connection, owner) => `${KEY_PREFIX}:token:${connection}:${owner}`;
|
|
28
|
+
var discovered = /* @__PURE__ */ new Map();
|
|
29
|
+
var stringField = (record, key) => typeof record[key] === "string" ? record[key] : void 0;
|
|
30
|
+
/** The connection's endpoints: written out, or read from its issuer's OpenID metadata — what is written wins. */
|
|
31
|
+
var endpointsOf = async (run, connection, spec) => {
|
|
32
|
+
let published = {};
|
|
33
|
+
if (spec.issuer && (!spec.authorizeUrl || !spec.tokenUrl)) {
|
|
34
|
+
const kept = discovered.get(spec.issuer);
|
|
35
|
+
if (kept && Date.now() - kept.at < DISCOVERY_MS) published = kept.endpoints;
|
|
36
|
+
else {
|
|
37
|
+
const url = new URL(`${spec.issuer.replace(/\/+$/, "")}/.well-known/openid-configuration`);
|
|
38
|
+
const answer = await fetchOutbound(run.fetch, url, {
|
|
39
|
+
method: "GET",
|
|
40
|
+
signal: run.signal
|
|
41
|
+
});
|
|
42
|
+
const metadata = answer.ok ? await answer.json().catch(() => void 0) : void 0;
|
|
43
|
+
const authorize = isRecord(metadata) ? stringField(metadata, "authorization_endpoint") : void 0;
|
|
44
|
+
const token = isRecord(metadata) ? stringField(metadata, "token_endpoint") : void 0;
|
|
45
|
+
if (!authorize || !token) throw new Error(`OAuth connection "${connection}": ${url.href} answered ${String(answer.status)} without authorization_endpoint and token_endpoint — write authorizeUrl and tokenUrl instead`);
|
|
46
|
+
const revoke = isRecord(metadata) ? stringField(metadata, "revocation_endpoint") : void 0;
|
|
47
|
+
published = {
|
|
48
|
+
authorize,
|
|
49
|
+
token,
|
|
50
|
+
...revoke ? { revoke } : {}
|
|
51
|
+
};
|
|
52
|
+
discovered.set(spec.issuer, {
|
|
53
|
+
at: Date.now(),
|
|
54
|
+
endpoints: {
|
|
55
|
+
authorize,
|
|
56
|
+
token,
|
|
57
|
+
...revoke ? { revoke } : {}
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
const authorize = spec.authorizeUrl ?? published.authorize;
|
|
63
|
+
const token = spec.tokenUrl ?? published.token;
|
|
64
|
+
if (!authorize || !token) throw new Error(`OAuth connection "${connection}" names no issuer, nor its authorizeUrl and tokenUrl`);
|
|
65
|
+
const revoke = spec.revokeUrl ?? published.revoke;
|
|
66
|
+
return {
|
|
67
|
+
authorize,
|
|
68
|
+
token,
|
|
69
|
+
...revoke ? { revoke } : {}
|
|
70
|
+
};
|
|
71
|
+
};
|
|
72
|
+
var sealed = (run) => {
|
|
73
|
+
const { seal, open } = run;
|
|
74
|
+
if (!seal || !open) throw new Error("This server keeps no OAuth tokens: its actions were given no signingSecret to seal them with");
|
|
75
|
+
return {
|
|
76
|
+
seal,
|
|
77
|
+
open
|
|
78
|
+
};
|
|
79
|
+
};
|
|
80
|
+
/** The app's id and secret, from the credential the connection names — resolved here, never handed to the code. */
|
|
81
|
+
var clientOf = async (run, connection, spec) => {
|
|
82
|
+
const credential = await run.credential(spec.credential);
|
|
83
|
+
const id = credential?.clientId;
|
|
84
|
+
if (!id) throw new Error(`OAuth connection "${connection}": the credential "${spec.credential}" ${credential ? "has no clientId" : "is not available for this space"} — it holds the app's clientId and clientSecret`);
|
|
85
|
+
return {
|
|
86
|
+
id,
|
|
87
|
+
...credential.clientSecret ? { secret: credential.clientSecret } : {}
|
|
88
|
+
};
|
|
89
|
+
};
|
|
90
|
+
/** A request to the token endpoint: the grant, and the app's proof of who it is where the provider wants it. */
|
|
91
|
+
var tokenRequest = async (run, connection, spec, url, grant) => {
|
|
92
|
+
const client = await clientOf(run, connection, spec);
|
|
93
|
+
const form = new URLSearchParams(grant);
|
|
94
|
+
const headers = {
|
|
95
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
96
|
+
accept: "application/json"
|
|
97
|
+
};
|
|
98
|
+
if (spec.clientAuth === "basic") headers.authorization = `Basic ${Buffer.from(`${encodeURIComponent(client.id)}:${encodeURIComponent(client.secret ?? "")}`).toString("base64")}`;
|
|
99
|
+
else {
|
|
100
|
+
form.set("client_id", client.id);
|
|
101
|
+
if (client.secret) form.set("client_secret", client.secret);
|
|
102
|
+
}
|
|
103
|
+
const answer = await fetchOutbound(run.fetch, new URL(url), {
|
|
104
|
+
method: "POST",
|
|
105
|
+
headers,
|
|
106
|
+
body: form.toString(),
|
|
107
|
+
signal: run.signal
|
|
108
|
+
});
|
|
109
|
+
const body = await answer.json().catch(() => void 0);
|
|
110
|
+
const said = isRecord(body) ? body : {};
|
|
111
|
+
if (!answer.ok || typeof said.access_token !== "string") {
|
|
112
|
+
const error = stringField(said, "error_description") ?? stringField(said, "error") ?? `status ${String(answer.status)}`;
|
|
113
|
+
throw new Error(`OAuth connection "${connection}": the provider refused the token (${error})`);
|
|
114
|
+
}
|
|
115
|
+
return said;
|
|
116
|
+
};
|
|
117
|
+
var tokensFrom = (said, earlier) => {
|
|
118
|
+
const expiresIn = typeof said.expires_in === "number" ? said.expires_in : Number(said.expires_in);
|
|
119
|
+
const refresh = stringField(said, "refresh_token") ?? earlier?.refresh;
|
|
120
|
+
const scope = stringField(said, "scope");
|
|
121
|
+
return {
|
|
122
|
+
access: said.access_token,
|
|
123
|
+
type: stringField(said, "token_type") ?? "Bearer",
|
|
124
|
+
...refresh ? { refresh } : {},
|
|
125
|
+
...Number.isFinite(expiresIn) && expiresIn > 0 ? { expiresAt: Date.now() + expiresIn * 1e3 } : {},
|
|
126
|
+
...scope ? { scopes: scope.split(/[\s,]+/).filter(Boolean) } : earlier?.scopes ? { scopes: earlier.scopes } : {}
|
|
127
|
+
};
|
|
128
|
+
};
|
|
129
|
+
var readSealed = async (run, key, check) => {
|
|
130
|
+
const stored = await run.kv.get(key);
|
|
131
|
+
if (typeof stored !== "string") return;
|
|
132
|
+
const opened = sealed(run).open(stored);
|
|
133
|
+
let parsed;
|
|
134
|
+
try {
|
|
135
|
+
parsed = opened === void 0 ? void 0 : JSON.parse(opened);
|
|
136
|
+
} catch {
|
|
137
|
+
parsed = void 0;
|
|
138
|
+
}
|
|
139
|
+
return check(parsed) ? parsed : void 0;
|
|
140
|
+
};
|
|
141
|
+
var isTokens = (value) => isRecord(value) && typeof value.access === "string" && typeof value.type === "string";
|
|
142
|
+
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";
|
|
143
|
+
/** Whose the connection is: the code's own key, or the signed-in visitor — and none is refused, saying which to name. */
|
|
144
|
+
var ownerOf = (run, connection, options) => {
|
|
145
|
+
const owner = options?.owner ?? (run.user ? `user:${String(run.user.id)}` : void 0);
|
|
146
|
+
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)`);
|
|
147
|
+
if (!OWNER.test(owner)) throw new Error(`An OAuth owner is letters, digits and ":._@-", up to 128 — not "${owner}"`);
|
|
148
|
+
return owner;
|
|
149
|
+
};
|
|
150
|
+
/** A path of the space to come back to: never another site (`//evil.example`, `https://…`). */
|
|
151
|
+
var pathOf = (returnTo) => {
|
|
152
|
+
if (!returnTo.startsWith("/") || returnTo.startsWith("//") || returnTo.includes("\\")) throw new Error(`returnTo is a path of the space ("/settings"), not "${returnTo}"`);
|
|
153
|
+
return returnTo;
|
|
154
|
+
};
|
|
155
|
+
var withQuery = (path, params) => {
|
|
156
|
+
const url = new URL(path, "http://space");
|
|
157
|
+
Object.entries(params).forEach(([key, value]) => url.searchParams.set(key, value));
|
|
158
|
+
return `${url.pathname}${url.search}${url.hash}`;
|
|
159
|
+
};
|
|
160
|
+
/**
|
|
161
|
+
* `ctx.oauth` for one run, over the connections its code declared. `hosts` are where `fetch` may write the token — the
|
|
162
|
+
* same `allow.hosts` every request of the code is held to.
|
|
163
|
+
*/
|
|
164
|
+
var oauthFor = (run, connections, allowed) => {
|
|
165
|
+
const specOf = (connection) => {
|
|
166
|
+
const spec = Object.hasOwn(connections, connection) ? connections[connection] : void 0;
|
|
167
|
+
if (!spec) {
|
|
168
|
+
const names = Object.keys(connections);
|
|
169
|
+
throw new Error(`No OAuth connection "${connection}": ${names.length ? `this space declares ${names.join(", ")}` : "declare it in oauth of defineFunctions"}`);
|
|
170
|
+
}
|
|
171
|
+
return spec;
|
|
172
|
+
};
|
|
173
|
+
const save = (connection, owner, tokens) => run.kv.set(tokenKey(connection, owner), sealed(run).seal(JSON.stringify(tokens)));
|
|
174
|
+
/** The connection's tokens, renewed first when they are about to lapse (or `force`d, after a 401). */
|
|
175
|
+
const tokensOf = async (connection, owner, force = false) => {
|
|
176
|
+
const tokens = await readSealed(run, tokenKey(connection, owner), isTokens);
|
|
177
|
+
if (!tokens) return;
|
|
178
|
+
if (!(tokens.expiresAt !== void 0 && tokens.expiresAt - RENEW_BEFORE_MS <= Date.now() || force) || !tokens.refresh) return tokens;
|
|
179
|
+
const spec = specOf(connection);
|
|
180
|
+
const { token } = await endpointsOf(run, connection, spec);
|
|
181
|
+
const renewed = tokensFrom(await tokenRequest(run, connection, spec, token, {
|
|
182
|
+
grant_type: "refresh_token",
|
|
183
|
+
refresh_token: tokens.refresh
|
|
184
|
+
}), tokens);
|
|
185
|
+
await save(connection, owner, renewed);
|
|
186
|
+
return renewed;
|
|
187
|
+
};
|
|
188
|
+
return {
|
|
189
|
+
connect: async (connection, options) => {
|
|
190
|
+
const spec = specOf(connection);
|
|
191
|
+
const owner = ownerOf(run, connection, options);
|
|
192
|
+
const returnTo = pathOf(options.returnTo);
|
|
193
|
+
if (!run.origin) throw new Error(`OAuth connection "${connection}" is made from a visitor's request: this run has none to return to`);
|
|
194
|
+
const { authorize } = await endpointsOf(run, connection, spec);
|
|
195
|
+
const client = await clientOf(run, connection, spec);
|
|
196
|
+
const verifier = randomBytes(32).toString("base64url");
|
|
197
|
+
const state = randomBytes(24).toString("base64url");
|
|
198
|
+
const redirectUri = `${run.origin}${FUNCTION_ROUTES_PREFIX}${OAUTH_CALLBACK_PATH}`;
|
|
199
|
+
const pending = {
|
|
200
|
+
connection,
|
|
201
|
+
spec,
|
|
202
|
+
owner,
|
|
203
|
+
returnTo,
|
|
204
|
+
verifier,
|
|
205
|
+
redirectUri
|
|
206
|
+
};
|
|
207
|
+
await run.kv.set(stateKey(state), sealed(run).seal(JSON.stringify(pending)), STATE_SECONDS);
|
|
208
|
+
const url = new URL(authorize);
|
|
209
|
+
const params = {
|
|
210
|
+
...spec.authorizeParams,
|
|
211
|
+
response_type: "code",
|
|
212
|
+
client_id: client.id,
|
|
213
|
+
redirect_uri: redirectUri,
|
|
214
|
+
state,
|
|
215
|
+
code_challenge: createHash("sha256").update(verifier).digest("base64url"),
|
|
216
|
+
code_challenge_method: "S256",
|
|
217
|
+
...spec.scopes?.length ? { scope: spec.scopes.join(" ") } : {}
|
|
218
|
+
};
|
|
219
|
+
Object.entries(params).forEach(([key, value]) => url.searchParams.set(key, value));
|
|
220
|
+
return { url: url.href };
|
|
221
|
+
},
|
|
222
|
+
status: async (connection, options) => {
|
|
223
|
+
specOf(connection);
|
|
224
|
+
const tokens = await readSealed(run, tokenKey(connection, ownerOf(run, connection, options)), isTokens);
|
|
225
|
+
return tokens ? {
|
|
226
|
+
connected: true,
|
|
227
|
+
...tokens.scopes ? { scopes: tokens.scopes } : {},
|
|
228
|
+
...tokens.expiresAt ? { expiresAt: tokens.expiresAt } : {}
|
|
229
|
+
} : { connected: false };
|
|
230
|
+
},
|
|
231
|
+
fetch: async (connection, input, init = {}) => {
|
|
232
|
+
specOf(connection);
|
|
233
|
+
const owner = ownerOf(run, connection, init);
|
|
234
|
+
const url = new URL(typeof input === "string" ? input : input.href);
|
|
235
|
+
allowed(url);
|
|
236
|
+
const send = (tokens) => fetchOutbound(run.fetch, url, {
|
|
237
|
+
method: init.method ?? "GET",
|
|
238
|
+
headers: {
|
|
239
|
+
...init.headers,
|
|
240
|
+
authorization: `${/^bearer$/i.test(tokens.type) ? "Bearer" : tokens.type} ${tokens.access}`
|
|
241
|
+
},
|
|
242
|
+
body: init.body,
|
|
243
|
+
signal: run.signal
|
|
244
|
+
});
|
|
245
|
+
const tokens = await tokensOf(connection, owner);
|
|
246
|
+
if (!tokens) throw new ActionRefusal(`Not connected to "${connection}": ctx.oauth.connect first`);
|
|
247
|
+
const answer = await send(tokens);
|
|
248
|
+
if (answer.status !== 401 || !tokens.refresh) return answer;
|
|
249
|
+
const renewed = await tokensOf(connection, owner, true);
|
|
250
|
+
return renewed ? send(renewed) : answer;
|
|
251
|
+
},
|
|
252
|
+
disconnect: async (connection, options) => {
|
|
253
|
+
const spec = specOf(connection);
|
|
254
|
+
const owner = ownerOf(run, connection, options);
|
|
255
|
+
const tokens = await readSealed(run, tokenKey(connection, owner), isTokens);
|
|
256
|
+
if (!tokens) return false;
|
|
257
|
+
const { revoke } = await endpointsOf(run, connection, spec);
|
|
258
|
+
if (revoke) await tokenRequest(run, connection, spec, revoke, { token: tokens.refresh ?? tokens.access }).catch(() => void 0);
|
|
259
|
+
await run.kv.delete(tokenKey(connection, owner));
|
|
260
|
+
return true;
|
|
261
|
+
}
|
|
262
|
+
};
|
|
263
|
+
};
|
|
264
|
+
/** `ctx.oauth` where there is none to give — a plugin's code: the space's connections are the space's. */
|
|
265
|
+
var noOAuth = (why) => {
|
|
266
|
+
const refused = () => Promise.reject(new Error(why));
|
|
267
|
+
return {
|
|
268
|
+
connect: refused,
|
|
269
|
+
status: refused,
|
|
270
|
+
fetch: refused,
|
|
271
|
+
disconnect: refused
|
|
272
|
+
};
|
|
273
|
+
};
|
|
274
|
+
/**
|
|
275
|
+
* The visitor back from the provider (`/fn/oauth/callback`): the consent it remembered taken (once), the code
|
|
276
|
+
* exchanged, the tokens kept — and the visitor sent where the code said, told how it went. A visit with no consent
|
|
277
|
+
* under way is answered, not redirected: there is nowhere of the space's to send it.
|
|
278
|
+
*/
|
|
279
|
+
var oauthCallback = async (run, query) => {
|
|
280
|
+
const state = query.get("state") ?? "";
|
|
281
|
+
const pending = state ? await readSealed(run, stateKey(state), isPending) : void 0;
|
|
282
|
+
if (state) await run.kv.delete(stateKey(state));
|
|
283
|
+
if (!pending) return new Response("This sign-in expired or was already used: start it again from the page.", {
|
|
284
|
+
status: 400,
|
|
285
|
+
headers: { "content-type": "text/plain; charset=utf-8" }
|
|
286
|
+
});
|
|
287
|
+
const back = (params) => new Response(null, {
|
|
288
|
+
status: 303,
|
|
289
|
+
headers: { location: withQuery(pending.returnTo, {
|
|
290
|
+
oauth: pending.connection,
|
|
291
|
+
...params
|
|
292
|
+
}) }
|
|
293
|
+
});
|
|
294
|
+
const refused = query.get("error");
|
|
295
|
+
if (refused) return back({ oauth_error: refused });
|
|
296
|
+
const code = query.get("code");
|
|
297
|
+
if (!code) return back({ oauth_error: "no_code" });
|
|
298
|
+
try {
|
|
299
|
+
const { token } = await endpointsOf(run, pending.connection, pending.spec);
|
|
300
|
+
const said = await tokenRequest(run, pending.connection, pending.spec, token, {
|
|
301
|
+
grant_type: "authorization_code",
|
|
302
|
+
code,
|
|
303
|
+
redirect_uri: pending.redirectUri,
|
|
304
|
+
code_verifier: pending.verifier
|
|
305
|
+
});
|
|
306
|
+
await run.kv.set(tokenKey(pending.connection, pending.owner), sealed(run).seal(JSON.stringify(tokensFrom(said))));
|
|
307
|
+
} catch (error) {
|
|
308
|
+
return back({ oauth_error: error instanceof Error ? error.message.slice(0, 200) : "exchange_failed" });
|
|
309
|
+
}
|
|
310
|
+
return back({ oauth_result: "connected" });
|
|
311
|
+
};
|
|
312
|
+
//#endregion
|
|
313
|
+
export { OAUTH_CALLBACK_PATH, noOAuth, oauthCallback, oauthFor };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -114,6 +114,24 @@ export type FunctionCall = {
|
|
|
114
114
|
} | {
|
|
115
115
|
op: 'data';
|
|
116
116
|
file: string;
|
|
117
|
+
} | {
|
|
118
|
+
op: 'oauth';
|
|
119
|
+
method: 'connect';
|
|
120
|
+
connection: string;
|
|
121
|
+
returnTo: string;
|
|
122
|
+
owner?: string;
|
|
123
|
+
} | {
|
|
124
|
+
op: 'oauth';
|
|
125
|
+
method: 'status' | 'disconnect';
|
|
126
|
+
connection: string;
|
|
127
|
+
owner?: string;
|
|
128
|
+
} | {
|
|
129
|
+
op: 'oauth';
|
|
130
|
+
method: 'fetch';
|
|
131
|
+
connection: string;
|
|
132
|
+
url: string;
|
|
133
|
+
init: Omit<FunctionFetchInit, 'credential'>;
|
|
134
|
+
owner?: string;
|
|
117
135
|
}
|
|
118
136
|
/** Each value as the guest could send it: JSON, with what JSON cannot say already said as text. */
|
|
119
137
|
| {
|
|
@@ -11,6 +11,8 @@ export type RouteVisit = {
|
|
|
11
11
|
user?: SSRUser;
|
|
12
12
|
/** `user:<id>` or `ip:<address>`, as for an action call. */
|
|
13
13
|
callerId: string;
|
|
14
|
+
/** The public origin the request reached (`https://shop.example.com`), as the server resolved it. */
|
|
15
|
+
origin?: string;
|
|
14
16
|
signal: AbortSignal;
|
|
15
17
|
};
|
|
16
18
|
export type RouteHandler = {
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { serverLog } from "../../helpers/serverLog.js";
|
|
2
2
|
import { isActionRefusal } from "../actions/runtime/errors.js";
|
|
3
|
+
import { OAUTH_CALLBACK_PATH, oauthCallback } from "./oauth.js";
|
|
3
4
|
import { pluginOfPath } from "./scope.js";
|
|
4
5
|
import { functionContextFor } from "./context.js";
|
|
5
6
|
import { functionLimitsFor } from "./config.js";
|
|
@@ -78,7 +79,8 @@ var failed = (visit, key, error) => {
|
|
|
78
79
|
var routesOf = (definition) => Object.entries(definition.routes ?? {}).map(([key, handler]) => ({
|
|
79
80
|
key,
|
|
80
81
|
handler,
|
|
81
|
-
hosts: definition.allow?.hosts ?? []
|
|
82
|
+
hosts: definition.allow?.hosts ?? [],
|
|
83
|
+
...definition.oauth ? { oauth: definition.oauth } : {}
|
|
82
84
|
}));
|
|
83
85
|
/**
|
|
84
86
|
* The route a request reaches, if one does: under `/plugins/<type>/`, that plugin's — this server's own, then the one
|
|
@@ -89,23 +91,26 @@ var createRoutes = ({ config, plugins = () => new Map(Object.entries(config.plug
|
|
|
89
91
|
const native = (config.native ?? []).flatMap(routesOf);
|
|
90
92
|
const reserved = native.find((route) => parseRouteKey(route.key)?.segments[0] === PLUGIN_ROUTES_SEGMENT);
|
|
91
93
|
if (reserved) throw new Error(`[Functions] ${reservedRouteProblem(reserved.key)}`);
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
94
|
+
/** The run's own context for a request of this visit: the space's kv, its credentials, its key. */
|
|
95
|
+
const runOf = (visit, key) => taskContext({
|
|
96
|
+
runId: randomUUID(),
|
|
97
|
+
spaceId: visit.spaceId,
|
|
98
|
+
environment: visit.environment,
|
|
99
|
+
trigger: "call",
|
|
100
|
+
callerId: visit.callerId,
|
|
101
|
+
...visit.user ? { user: visit.user } : {},
|
|
102
|
+
...visit.at ? { at: visit.at } : {},
|
|
103
|
+
...visit.origin ? { origin: visit.origin } : {}
|
|
104
|
+
}, visit.signal, [`route:${key}`]);
|
|
105
|
+
const contextOf = (visit, key, hosts, scope, oauth) => {
|
|
106
|
+
const ctx = runOf(visit, key);
|
|
102
107
|
return {
|
|
103
108
|
...functionContextFor({
|
|
104
109
|
...ctx,
|
|
105
110
|
log: (line) => {
|
|
106
111
|
serverLog.info("Functions", `route ${key} of space ${String(visit.spaceId)}: ${line}`);
|
|
107
112
|
}
|
|
108
|
-
}, hosts, scope),
|
|
113
|
+
}, hosts, scope, oauth),
|
|
109
114
|
trigger: "route"
|
|
110
115
|
};
|
|
111
116
|
};
|
|
@@ -120,7 +125,7 @@ var createRoutes = ({ config, plugins = () => new Map(Object.entries(config.plug
|
|
|
120
125
|
handle: async (request) => {
|
|
121
126
|
try {
|
|
122
127
|
return withoutCookies(await handler(withoutCredentials(request), {
|
|
123
|
-
...contextOf(visit, match.key, route.hosts, scope),
|
|
128
|
+
...contextOf(visit, match.key, route.hosts, scope, route.oauth),
|
|
124
129
|
params: match.params
|
|
125
130
|
}));
|
|
126
131
|
} catch (error) {
|
|
@@ -140,7 +145,7 @@ var createRoutes = ({ config, plugins = () => new Map(Object.entries(config.plug
|
|
|
140
145
|
handle: async (request) => {
|
|
141
146
|
const refusal = await config.admit?.(visit.spaceId);
|
|
142
147
|
if (refusal) return Response.json({ error: refusal }, { status: 429 });
|
|
143
|
-
const fnCtx = contextOf(visit, match.key, functions.manifest.hosts, scope);
|
|
148
|
+
const fnCtx = contextOf(visit, match.key, functions.manifest.hosts, scope, functions.manifest.oauth);
|
|
144
149
|
let ok = false;
|
|
145
150
|
let spent;
|
|
146
151
|
try {
|
|
@@ -192,6 +197,17 @@ var createRoutes = ({ config, plugins = () => new Map(Object.entries(config.plug
|
|
|
192
197
|
return {
|
|
193
198
|
/** The route that answers `method path` (the path after `/fn`), for this visit — or none. */
|
|
194
199
|
routeFor: async (visit, method, path) => {
|
|
200
|
+
if (method === "GET" && path === "/oauth/callback") return {
|
|
201
|
+
key: `GET ${OAUTH_CALLBACK_PATH}`,
|
|
202
|
+
handle: async (request) => {
|
|
203
|
+
const run = runOf(visit, `GET ${OAUTH_CALLBACK_PATH}`);
|
|
204
|
+
try {
|
|
205
|
+
return await oauthCallback(run, new URL(request.url).searchParams);
|
|
206
|
+
} catch (error) {
|
|
207
|
+
return failed(visit, `GET ${OAUTH_CALLBACK_PATH}`, error);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
};
|
|
195
211
|
const addressed = pluginOfPath(path);
|
|
196
212
|
if (addressed) return pluginRoute(visit, method, addressed);
|
|
197
213
|
return loadedRoute(native, visit, method, path) ?? runnerRoute(await getFunctions?.(visit.spaceId, visit.at), visit, method, path);
|
|
@@ -36,7 +36,7 @@ var spaceTasks = (functions, runner, limitsFor, { admit, onUsage } = {}, scope)
|
|
|
36
36
|
run: async (params, ctx) => {
|
|
37
37
|
const refusal = await admit?.(ctx.spaceId);
|
|
38
38
|
if (refusal) throw new Error(refusal);
|
|
39
|
-
const fnCtx = functionContextFor(ctx, functions.manifest.hosts, scope);
|
|
39
|
+
const fnCtx = functionContextFor(ctx, functions.manifest.hosts, scope, functions.manifest.oauth);
|
|
40
40
|
let ok = false;
|
|
41
41
|
let spent;
|
|
42
42
|
try {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@plitzi/sdk-server",
|
|
3
|
-
"version": "0.38.
|
|
3
|
+
"version": "0.38.20",
|
|
4
4
|
"license": "AGPL-3.0",
|
|
5
5
|
"files": [
|
|
6
6
|
"dist",
|
|
@@ -107,12 +107,15 @@
|
|
|
107
107
|
"url": "https://github.com/plitzi/plitzi-workspace.git"
|
|
108
108
|
},
|
|
109
109
|
"type": "module",
|
|
110
|
+
"engines": {
|
|
111
|
+
"node": ">=22.18"
|
|
112
|
+
},
|
|
110
113
|
"sideEffects": [
|
|
111
114
|
"./dist/env.js"
|
|
112
115
|
],
|
|
113
116
|
"dependencies": {
|
|
114
|
-
"@plitzi/plitzi-sdk": "0.38.
|
|
115
|
-
"@plitzi/sdk-shared": "0.38.
|
|
117
|
+
"@plitzi/plitzi-sdk": "0.38.20",
|
|
118
|
+
"@plitzi/sdk-shared": "0.38.20",
|
|
116
119
|
"ejs": "^7.0.2",
|
|
117
120
|
"esbuild": "^0.28.2",
|
|
118
121
|
"jsonwebtoken": "^9.0.3",
|