@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 +89 -0
- package/dist/core/auth/createAuth.d.ts +1 -1
- package/dist/core/auth/csrf.d.ts +2 -2
- package/dist/core/auth/csrf.js +28 -12
- 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 +8 -5
|
@@ -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 {
|