@selvajs/selva 4.21.0-beta.6 → 4.21.0-beta.8
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/build/adapter-node.js +1 -1
- package/build/client/_app/immutable/assets/0.CqqJCiiV.css +2 -0
- package/build/client/_app/immutable/assets/0.CqqJCiiV.css.br +0 -0
- package/build/client/_app/immutable/assets/0.CqqJCiiV.css.gz +0 -0
- package/build/client/_app/immutable/chunks/{BepzH9eI.js → DptnDNFA.js} +60 -55
- package/build/client/_app/immutable/chunks/DptnDNFA.js.br +0 -0
- package/build/client/_app/immutable/chunks/{BepzH9eI.js.gz → DptnDNFA.js.gz} +0 -0
- package/build/client/_app/immutable/chunks/DvJo0Zn0.js +1 -0
- package/build/client/_app/immutable/chunks/DvJo0Zn0.js.br +1 -0
- package/build/client/_app/immutable/chunks/DvJo0Zn0.js.gz +0 -0
- package/build/client/_app/immutable/entry/{app.DblLep9O.js → app.DPVyoSCt.js} +2 -2
- package/build/client/_app/immutable/entry/app.DPVyoSCt.js.br +0 -0
- package/build/client/_app/immutable/entry/app.DPVyoSCt.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{15.BXIV1QfS.js → 15.0NRg5Hm0.js} +1 -1
- package/build/client/_app/immutable/nodes/15.0NRg5Hm0.js.br +0 -0
- package/build/client/_app/immutable/nodes/15.0NRg5Hm0.js.gz +0 -0
- package/build/client/_app/immutable/nodes/21.DpKe0-GH.js +1 -0
- package/build/client/_app/immutable/nodes/21.DpKe0-GH.js.br +0 -0
- package/build/client/_app/immutable/nodes/21.DpKe0-GH.js.gz +0 -0
- package/build/client/_app/immutable/nodes/24.DkL5kHzA.js +3 -0
- package/build/client/_app/immutable/nodes/24.DkL5kHzA.js.br +0 -0
- package/build/client/_app/immutable/nodes/24.DkL5kHzA.js.gz +0 -0
- package/build/client/_app/version.json +1 -1
- package/build/client/_app/version.json.br +0 -0
- package/build/client/_app/version.json.gz +0 -0
- package/build/server/.vite/manifest.json +20 -34
- package/build/server/_app/immutable/assets/_layout.CqqJCiiV.css +2 -0
- package/build/server/chunks/api-errors.js +18 -3
- package/build/server/chunks/api-errors.js.map +1 -1
- package/build/server/chunks/boot.server.js +1 -1
- package/build/server/chunks/computeRateLimit.server.js +1 -1
- package/build/server/chunks/delete-with-blobs.js +1 -1
- package/build/server/chunks/engine.server.js +50 -3
- package/build/server/chunks/engine.server.js.map +1 -1
- package/build/server/chunks/grasshopper.js +1 -1
- package/build/server/chunks/handlers.js +24 -20
- package/build/server/chunks/handlers.js.map +1 -1
- package/build/server/chunks/http2.js +1 -1
- package/build/server/chunks/instance.js +3 -3
- package/build/server/chunks/internal.js +1 -1
- package/build/server/chunks/{abort-Bfrdupaj.js → keepalive-vtcjhAV3.js} +6 -3
- package/build/server/chunks/keepalive-vtcjhAV3.js.map +1 -0
- package/build/server/chunks/oauth.js +70 -24
- package/build/server/chunks/oauth.js.map +1 -1
- package/build/server/chunks/package.js +1 -1
- package/build/server/chunks/package.js.map +1 -1
- package/build/server/chunks/permissions.server.js +1 -1
- package/build/server/chunks/providers.server.js +72 -3
- package/build/server/chunks/providers.server.js.map +1 -1
- package/build/server/chunks/resolve-server.js +1 -1
- package/build/server/chunks/schema-extraction.js +75 -8
- package/build/server/chunks/schema-extraction.js.map +1 -1
- package/build/server/chunks/server-config-write.js +1 -1
- package/build/server/chunks/server2.js +2 -2
- package/build/server/chunks/server2.js.map +1 -1
- package/build/server/chunks/serverStats.server.js +1 -1
- package/build/server/chunks/solve.server.js +4 -5
- package/build/server/chunks/solve.server.js.map +1 -1
- package/build/server/chunks/sveltekit.js +3 -4
- package/build/server/chunks/sveltekit.js.map +1 -1
- package/build/server/entries/endpoints/.well-known/oauth-authorization-server/_server.ts.js +6 -3
- package/build/server/entries/endpoints/.well-known/oauth-authorization-server/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/.well-known/oauth-protected-resource/_server.ts.js +6 -3
- package/build/server/entries/endpoints/.well-known/oauth-protected-resource/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/.well-known/oauth-protected-resource/mcp/_server.ts.js +6 -3
- package/build/server/entries/endpoints/.well-known/oauth-protected-resource/mcp/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/api/admin/compute/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/compute/actions/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/compute/status/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/system/health/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/system/update/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/users/_id_/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/users/_id_/disable/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/admin/users/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/files/_...path_/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/compute/_server.ts.js +10 -5
- package/build/server/entries/endpoints/api/v1/compute/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/api/v1/compute/schema/_server.ts.js +2 -2
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/solve/_server.ts.js +3 -3
- package/build/server/entries/endpoints/mcp/_server.ts.js +43 -13
- package/build/server/entries/endpoints/mcp/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/oauth/register/_server.ts.js +1 -1
- package/build/server/entries/endpoints/oauth/token/_server.ts.js +1 -1
- package/build/server/entries/hooks.server.js +1 -1
- package/build/server/entries/pages/admin/compute/_page.server.ts.js +1 -2
- package/build/server/entries/pages/admin/compute/_page.server.ts.js.map +1 -1
- package/build/server/entries/pages/admin/system/_page.server.ts.js +3 -3
- package/build/server/entries/pages/admin/system/_page.server.ts.js.map +1 -1
- package/build/server/entries/pages/admin/system/_page.svelte.js +1 -1
- package/build/server/entries/pages/admin/system/_page.svelte.js.map +1 -1
- package/build/server/entries/pages/library/_guid_/_page.server.ts.js +198 -99
- package/build/server/entries/pages/library/_guid_/_page.server.ts.js.map +1 -1
- package/build/server/entries/pages/library/_guid_/_page.svelte.js +462 -30
- package/build/server/entries/pages/library/_guid_/_page.svelte.js.map +1 -1
- package/build/server/entries/pages/oauth/authorize/_page.server.ts.js +3 -2
- package/build/server/entries/pages/oauth/authorize/_page.server.ts.js.map +1 -1
- package/build/server/entries/pages/oauth/authorize/_page.svelte.js +8 -1
- package/build/server/entries/pages/oauth/authorize/_page.svelte.js.map +1 -1
- package/build/server/manifest-full.js +1 -1
- package/build/server/manifest.js +1 -1
- package/build/server/nodes/0.js +2 -2
- package/build/server/nodes/15.js +1 -1
- package/build/server/nodes/21.js +1 -1
- package/build/server/nodes/24.js +1 -1
- package/build/server/server.js +1 -1
- package/package.json +7 -7
- package/templates/.env.example +5 -3
- package/build/client/_app/immutable/assets/0.2jDm0bqh.css +0 -2
- package/build/client/_app/immutable/assets/0.2jDm0bqh.css.br +0 -0
- package/build/client/_app/immutable/assets/0.2jDm0bqh.css.gz +0 -0
- package/build/client/_app/immutable/chunks/BepzH9eI.js.br +0 -0
- package/build/client/_app/immutable/chunks/BmoT9ksD.js +0 -1
- package/build/client/_app/immutable/chunks/BmoT9ksD.js.br +0 -1
- package/build/client/_app/immutable/chunks/BmoT9ksD.js.gz +0 -0
- package/build/client/_app/immutable/entry/app.DblLep9O.js.br +0 -0
- package/build/client/_app/immutable/entry/app.DblLep9O.js.gz +0 -0
- package/build/client/_app/immutable/nodes/15.BXIV1QfS.js.br +0 -0
- package/build/client/_app/immutable/nodes/15.BXIV1QfS.js.gz +0 -0
- package/build/client/_app/immutable/nodes/21.DvC40Ypm.js +0 -1
- package/build/client/_app/immutable/nodes/21.DvC40Ypm.js.br +0 -0
- package/build/client/_app/immutable/nodes/21.DvC40Ypm.js.gz +0 -0
- package/build/client/_app/immutable/nodes/24.CPSunfJJ.js +0 -3
- package/build/client/_app/immutable/nodes/24.CPSunfJJ.js.br +0 -0
- package/build/client/_app/immutable/nodes/24.CPSunfJJ.js.gz +0 -0
- package/build/server/_app/immutable/assets/_layout.2jDm0bqh.css +0 -2
- package/build/server/chunks/abort-Bfrdupaj.js.map +0 -1
- package/build/server/chunks/computeLimits.js +0 -33
- package/build/server/chunks/computeLimits.js.map +0 -1
- /package/build/client/_app/immutable/nodes/{0.CYdyv5To.js → 0.Ds0zeDAg.js} +0 -0
- /package/build/client/_app/immutable/nodes/{0.CYdyv5To.js.br → 0.Ds0zeDAg.js.br} +0 -0
- /package/build/client/_app/immutable/nodes/{0.CYdyv5To.js.gz → 0.Ds0zeDAg.js.gz} +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { k as ApiErrorCode } from "./access.js";
|
|
2
2
|
import "./api.js";
|
|
3
|
-
import {
|
|
3
|
+
import { r as handleApiError, t as apiError } from "./api-errors.js";
|
|
4
4
|
import { json } from "@sveltejs/kit";
|
|
5
5
|
// src/lib/server/api/http.ts
|
|
6
6
|
/**
|
|
@@ -213,7 +213,7 @@ function server_data_serializer(event, state) {
|
|
|
213
213
|
let promise_id = 1;
|
|
214
214
|
let max_nodes = -1;
|
|
215
215
|
const iterator = create_async_iterator();
|
|
216
|
-
const global = "
|
|
216
|
+
const global = "__sveltekit_cjj2z9";
|
|
217
217
|
/** @param {number} index */
|
|
218
218
|
function get_replacer(index) {
|
|
219
219
|
/** @param {any} thing */
|
|
@@ -1443,7 +1443,7 @@ async function render_response({ branch, fetched, page_config, status, error = n
|
|
|
1443
1443
|
"crossorigin"
|
|
1444
1444
|
]);
|
|
1445
1445
|
}
|
|
1446
|
-
const global = "
|
|
1446
|
+
const global = "__sveltekit_cjj2z9";
|
|
1447
1447
|
const { data, chunks } = data_serializer.get_data(csp);
|
|
1448
1448
|
if (page_config.ssr && page_config.csr) body += `\n\t\t\t${fetched.map((item) => serialize_data(item, resolve_opts.filterSerializedResponseHeaders, !!(state.prerendering || state.prerender_default === true))).join("\n ")}`;
|
|
1449
1449
|
if (page_config.csr && client) {
|
|
@@ -1467,7 +1467,7 @@ async function render_response({ branch, fetched, page_config, status, error = n
|
|
|
1467
1467
|
}
|
|
1468
1468
|
}
|
|
1469
1469
|
const blocks = [];
|
|
1470
|
-
const properties = [`base: ${base_expression}`, `version: ${s("
|
|
1470
|
+
const properties = [`base: ${base_expression}`, `version: ${s("1794483560744")}`];
|
|
1471
1471
|
if (assets) properties.push(`assets: ${s(assets)}`);
|
|
1472
1472
|
if (client.uses_env_dynamic_public) properties.push(`env: ${load_env_eagerly ? "null" : uneval$1(rendered_env)}`);
|
|
1473
1473
|
if (chunks) {
|
|
@@ -2363,7 +2363,7 @@ function redirect_response(status, location) {
|
|
|
2363
2363
|
* @param {Response} response
|
|
2364
2364
|
*/
|
|
2365
2365
|
function with_version_header(response) {
|
|
2366
|
-
response.headers.set("x-sveltekit-version", "
|
|
2366
|
+
response.headers.set("x-sveltekit-version", "1794483560744");
|
|
2367
2367
|
return response;
|
|
2368
2368
|
}
|
|
2369
2369
|
/**
|
|
@@ -18,7 +18,7 @@ function getLayoutItems(schema) {
|
|
|
18
18
|
function getInputItems(schema) {
|
|
19
19
|
return getLayoutItems(schema).filter((i) => i.type === "input");
|
|
20
20
|
}
|
|
21
|
-
// ../solve/dist/
|
|
21
|
+
// ../solve/dist/keepalive-vtcjhAV3.js
|
|
22
22
|
/**
|
|
23
23
|
* Inputs the schema marks `source.kind === 'server'`. No resolver fills them, so they solve with
|
|
24
24
|
* their schema default: the client sends no value for them, and the server refuses one.
|
|
@@ -35,6 +35,9 @@ function raceAbort(promise, signal) {
|
|
|
35
35
|
promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
|
|
36
36
|
});
|
|
37
37
|
}
|
|
38
|
-
|
|
38
|
+
var KEEPALIVE_PREFERENCE = "selva-keepalive";
|
|
39
|
+
/** Under the 30 s many load balancers allow an idle upstream. */
|
|
40
|
+
var KEEPALIVE_INTERVAL_MS = 15e3;
|
|
41
|
+
export { getGroups as a, serverSourcedInputIds as i, KEEPALIVE_PREFERENCE as n, getInputItems as o, raceAbort as r, getLayoutItems as s, KEEPALIVE_INTERVAL_MS as t };
|
|
39
42
|
|
|
40
|
-
//# sourceMappingURL=
|
|
43
|
+
//# sourceMappingURL=keepalive-vtcjhAV3.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"keepalive-vtcjhAV3.js","names":[],"sources":["../../../../schemas/src/traversal.ts","../../../../solve/dist/keepalive-vtcjhAV3.js"],"sourcesContent":["// Schema layout traversal — the single place that knows how to walk a UISchema's\n// layout. The layout is a discriminated union ('tabbed' | 'flat'); without this module\n// every caller re-derives the `layout.type === 'tabbed' ? tabs.flatMap(...) : groups`\n// branch by hand. Add a new layout kind and you change this file, not a dozen others.\n//\n// Lives in @selvajs/schemas (next to the types it walks) so any package that depends on\n// the schema can traverse it without pulling in @selvajs/ui. Readers are defensive: a\n// missing layout or missing groups/items yields an empty result rather than throwing.\n\nimport type { UISchema, GroupConfig, LayoutItem, InputLayoutItem } from './generated/index.js';\n\n/**\n * Every group across the schema, in tab order, with tab boundaries flattened away.\n * Callers that need the tab structure (e.g. position-based panels) must walk `layout`\n * directly — this is intentionally a group-level view.\n */\nexport function getGroups(schema: UISchema): GroupConfig[] {\n\tif (!schema?.layout) return [];\n\tif (schema.layout.type === 'tabbed') {\n\t\treturn schema.layout.tabs?.flatMap((t) => t.groups ?? []) ?? [];\n\t}\n\tif (schema.layout.type === 'flat') {\n\t\treturn schema.layout.groups ?? [];\n\t}\n\treturn [];\n}\n\n/** Every layout item across every group — inputs, outputs, and linebreaks. */\nexport function getLayoutItems(schema: UISchema): LayoutItem[] {\n\treturn getGroups(schema).flatMap((g) => g.items ?? []);\n}\n\n/** Only the input items. `getExternalInputs` and preset save build on this. */\nexport function getInputItems(schema: UISchema): InputLayoutItem[] {\n\treturn getLayoutItems(schema).filter((i): i is InputLayoutItem => i.type === 'input');\n}\n","import { getInputItems } from \"@selvajs/schemas\";\n// src/shared/server-sourced.ts\n/**\n* Inputs the schema marks `source.kind === 'server'`. No resolver fills them, so they solve with\n* their schema default: the client sends no value for them, and the server refuses one.\n*/\nfunction serverSourcedInputIds(schema) {\n\treturn new Set(getInputItems(schema).filter((item) => item.source?.kind === \"server\").map((item) => item.paramId));\n}\n// src/shared/abort.ts\n/** `promise`'s outcome, or a rejection with `signal`'s reason if that fires first. */\nfunction raceAbort(promise, signal) {\n\treturn new Promise((resolve, reject) => {\n\t\tconst onAbort = () => reject(signal.reason);\n\t\tif (signal.aborted) onAbort();\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\tpromise.then(resolve, reject).finally(() => signal.removeEventListener(\"abort\", onAbort));\n\t});\n}\n// src/shared/keepalive.ts\nconst KEEPALIVE_PREFERENCE = \"selva-keepalive\";\n/** Under the 30 s many load balancers allow an idle upstream. */\nconst KEEPALIVE_INTERVAL_MS = 15e3;\nexport { serverSourcedInputIds as i, KEEPALIVE_PREFERENCE as n, raceAbort as r, KEEPALIVE_INTERVAL_MS as t };\n\n//# sourceMappingURL=keepalive-vtcjhAV3.js.map"],"mappings":";;;;;;AAgBA,SAAgB,UAAU,QAAiC;CAC1D,IAAI,CAAC,QAAQ,QAAQ,OAAO,CAAC;CAC7B,IAAI,OAAO,OAAO,SAAS,UAC1B,OAAO,OAAO,OAAO,MAAM,SAAS,MAAM,EAAE,UAAU,CAAC,CAAC,KAAK,CAAC;CAE/D,IAAI,OAAO,OAAO,SAAS,QAC1B,OAAO,OAAO,OAAO,UAAU,CAAC;CAEjC,OAAO,CAAC;AACT;;AAGA,SAAgB,eAAe,QAAgC;CAC9D,OAAO,UAAU,MAAM,CAAC,CAAC,SAAS,MAAM,EAAE,SAAS,CAAC,CAAC;AACtD;;AAGA,SAAgB,cAAc,QAAqC;CAClE,OAAO,eAAe,MAAM,CAAC,CAAC,QAAQ,MAA4B,EAAE,SAAS,OAAO;AACrF;;;;;;AC7BA,SAAS,sBAAsB,QAAQ;CACtC,OAAO,IAAI,IAAI,cAAc,MAAM,CAAC,CAAC,QAAQ,SAAS,KAAK,QAAQ,SAAS,QAAQ,CAAC,CAAC,KAAK,SAAS,KAAK,OAAO,CAAC;AAClH;;AAGA,SAAS,UAAU,SAAS,QAAQ;CACnC,OAAO,IAAI,SAAS,SAAS,WAAW;EACvC,MAAM,gBAAgB,OAAO,OAAO,MAAM;EAC1C,IAAI,OAAO,SAAS,QAAQ;EAC5B,OAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;EACxD,QAAQ,KAAK,SAAS,MAAM,CAAC,CAAC,cAAc,OAAO,oBAAoB,SAAS,OAAO,CAAC;CACzF,CAAC;AACF;AAEA,IAAM,uBAAuB;;AAE7B,IAAM,wBAAwB"}
|
|
@@ -19,15 +19,24 @@ import { createCipheriv, createDecipheriv, createHash, createHmac, hkdfSync, ran
|
|
|
19
19
|
var OAUTH_SCOPES = [
|
|
20
20
|
"read",
|
|
21
21
|
"solve",
|
|
22
|
+
"write",
|
|
22
23
|
"upload",
|
|
23
24
|
"create_projects"
|
|
24
25
|
];
|
|
25
26
|
/**
|
|
26
|
-
* All a registered (DCR or CIMD)
|
|
27
|
+
* All a host may hand registered (DCR or CIMD) clients. Their name and redirects
|
|
27
28
|
* are whatever the registrant chose, so `upload`, which puts code on the org's
|
|
28
|
-
* Compute server, and `create_projects`
|
|
29
|
-
*
|
|
29
|
+
* Compute server, and `create_projects` aren't here. `write` is, but `write:all`
|
|
30
|
+
* covers both at `/api/v1` and can delete projects and definitions, so it is
|
|
31
|
+
* off by default. An allowlist: a new scope reaches registered clients only
|
|
32
|
+
* once it is added here.
|
|
30
33
|
*/
|
|
34
|
+
var REGISTERABLE_SCOPES = [
|
|
35
|
+
"read",
|
|
36
|
+
"solve",
|
|
37
|
+
"write"
|
|
38
|
+
];
|
|
39
|
+
/** The default `registeredClientScopes`. */
|
|
31
40
|
var REGISTERED_CLIENT_SCOPES = ["read", "solve"];
|
|
32
41
|
var GRASSHOPPER_CLIENT = {
|
|
33
42
|
clientId: "selva-grasshopper",
|
|
@@ -74,20 +83,26 @@ function mcpResourceUrl(origin) {
|
|
|
74
83
|
function resourceMetadataUrl(origin) {
|
|
75
84
|
return `${origin}/.well-known/oauth-protected-resource${MCP_PATH}`;
|
|
76
85
|
}
|
|
77
|
-
/**
|
|
78
|
-
|
|
86
|
+
/**
|
|
87
|
+
* RFC 9728. Claude uses only the first authorization server. `scopes` is what a
|
|
88
|
+
* registered client may be granted; prefer the server's own method, which
|
|
89
|
+
* passes its `registeredClientScopes`.
|
|
90
|
+
*/
|
|
91
|
+
function protectedResourceMetadata(origin, scopes = REGISTERED_CLIENT_SCOPES) {
|
|
79
92
|
return {
|
|
80
93
|
resource: mcpResourceUrl(origin),
|
|
81
94
|
authorization_servers: [origin],
|
|
82
|
-
scopes_supported: [...
|
|
95
|
+
scopes_supported: [...scopes],
|
|
83
96
|
bearer_methods_supported: ["header"]
|
|
84
97
|
};
|
|
85
98
|
}
|
|
86
99
|
/**
|
|
87
100
|
* RFC 8414. Claude picks Client ID Metadata Documents only when both
|
|
88
101
|
* `client_id_metadata_document_supported` and the `none` auth method appear.
|
|
102
|
+
* Advertises only scopes some client can be granted: a client that asks for one
|
|
103
|
+
* it can never get re-authorizes in a loop. Prefer the server's own method.
|
|
89
104
|
*/
|
|
90
|
-
function authorizationServerMetadata(origin) {
|
|
105
|
+
function authorizationServerMetadata(origin, registeredScopes = REGISTERED_CLIENT_SCOPES) {
|
|
91
106
|
return {
|
|
92
107
|
issuer: origin,
|
|
93
108
|
authorization_endpoint: `${origin}/oauth/authorize`,
|
|
@@ -97,11 +112,21 @@ function authorizationServerMetadata(origin) {
|
|
|
97
112
|
grant_types_supported: ["authorization_code"],
|
|
98
113
|
code_challenge_methods_supported: ["S256"],
|
|
99
114
|
token_endpoint_auth_methods_supported: ["none"],
|
|
100
|
-
scopes_supported:
|
|
115
|
+
scopes_supported: OAUTH_SCOPES.filter((s) => GRASSHOPPER_CLIENT.scopes.includes(s) || registeredScopes.includes(s)),
|
|
101
116
|
client_id_metadata_document_supported: true,
|
|
102
117
|
authorization_response_iss_parameter_supported: true
|
|
103
118
|
};
|
|
104
119
|
}
|
|
120
|
+
/**
|
|
121
|
+
* The host's list, checked: a JS host or a cast gets past the type, and a list
|
|
122
|
+
* without `read` would leave every consent page empty with a message blaming
|
|
123
|
+
* the user's account.
|
|
124
|
+
*/
|
|
125
|
+
function checkRegisteredScopes(scopes) {
|
|
126
|
+
for (const s of scopes) if (!REGISTERABLE_SCOPES.includes(s)) throw new TypeError(`registeredClientScopes: "${s}" can't be granted to a registered client.`);
|
|
127
|
+
if (!scopes.includes("read")) throw new TypeError("registeredClientScopes must include \"read\".");
|
|
128
|
+
return REGISTERABLE_SCOPES.filter((s) => scopes.includes(s));
|
|
129
|
+
}
|
|
105
130
|
function createOAuthServer(options) {
|
|
106
131
|
const { origin } = options;
|
|
107
132
|
const now = options.now ?? Date.now;
|
|
@@ -111,6 +136,7 @@ function createOAuthServer(options) {
|
|
|
111
136
|
const previousSignKey = previous ? derive(previous, "selva-oauth-client") : void 0;
|
|
112
137
|
const previousCodeKey = previous ? derive(previous, `selva-oauth-code:${origin}`) : void 0;
|
|
113
138
|
const redeemed = options.redeemedCodes ?? /* @__PURE__ */ new Map();
|
|
139
|
+
const registeredScopes = checkRegisteredScopes(options.registeredClientScopes ?? REGISTERED_CLIENT_SCOPES);
|
|
114
140
|
const metadataCache = /* @__PURE__ */ new Map();
|
|
115
141
|
/** RFC 7591. The client id carries the metadata, signed, so nothing is stored. */
|
|
116
142
|
function register(input) {
|
|
@@ -159,7 +185,7 @@ function createOAuthServer(options) {
|
|
|
159
185
|
name: meta.n || "An MCP client",
|
|
160
186
|
redirectUris: meta.r,
|
|
161
187
|
builtIn: false,
|
|
162
|
-
scopes:
|
|
188
|
+
scopes: registeredScopes
|
|
163
189
|
};
|
|
164
190
|
}
|
|
165
191
|
async function metadataClient(url) {
|
|
@@ -170,7 +196,7 @@ function createOAuthServer(options) {
|
|
|
170
196
|
}
|
|
171
197
|
if (!options.fetchClientMetadata) throw new OAuthError("invalid_client", "This server does not accept URL client ids.");
|
|
172
198
|
try {
|
|
173
|
-
const client = await readMetadata(url, options.fetchClientMetadata);
|
|
199
|
+
const client = await readMetadata(url, options.fetchClientMetadata, registeredScopes);
|
|
174
200
|
remember(url, {
|
|
175
201
|
at: now(),
|
|
176
202
|
client
|
|
@@ -284,15 +310,17 @@ function createOAuthServer(options) {
|
|
|
284
310
|
approve,
|
|
285
311
|
deny,
|
|
286
312
|
exchange,
|
|
287
|
-
|
|
288
|
-
|
|
313
|
+
/** All a registered client can be granted: the MCP 401 challenge's scopes. */
|
|
314
|
+
registeredScopes,
|
|
315
|
+
protectedResourceMetadata: () => protectedResourceMetadata(origin, registeredScopes),
|
|
316
|
+
authorizationServerMetadata: () => authorizationServerMetadata(origin, registeredScopes)
|
|
289
317
|
};
|
|
290
318
|
}
|
|
291
319
|
/** OAuth scopes to the API scopes a minted token gets. */
|
|
292
320
|
function apiScopesFor(scopes) {
|
|
293
321
|
return scopes.map((s) => `${s}:all`);
|
|
294
322
|
}
|
|
295
|
-
async function readMetadata(url, fetchClientMetadata) {
|
|
323
|
+
async function readMetadata(url, fetchClientMetadata, scopes) {
|
|
296
324
|
let doc;
|
|
297
325
|
try {
|
|
298
326
|
doc = await fetchClientMetadata(url);
|
|
@@ -305,7 +333,7 @@ async function readMetadata(url, fetchClientMetadata) {
|
|
|
305
333
|
name: typeof doc.client_name === "string" && doc.client_name.trim() ? doc.client_name.trim().slice(0, CLIENT_NAME_MAX) : new URL(url).host,
|
|
306
334
|
redirectUris: checkRedirectUris(doc.redirect_uris),
|
|
307
335
|
builtIn: false,
|
|
308
|
-
scopes
|
|
336
|
+
scopes
|
|
309
337
|
};
|
|
310
338
|
}
|
|
311
339
|
/**
|
|
@@ -313,34 +341,52 @@ async function readMetadata(url, fetchClientMetadata) {
|
|
|
313
341
|
* that is dropped, not refused, so a client that asks for every advertised
|
|
314
342
|
* scope still signs in with what it may have. No `scope` at all means all of
|
|
315
343
|
* them. Asking only for scopes it may not have gets `read`, never more than it
|
|
316
|
-
* asked for. `read` rides along with `solve`, which the consent
|
|
317
|
-
* "read and run solves".
|
|
344
|
+
* asked for. `read` rides along with `solve` and `write`, which the consent
|
|
345
|
+
* page offers as "read and run solves" and "read and change".
|
|
318
346
|
*/
|
|
319
347
|
function parseScopes(raw, allowed) {
|
|
320
348
|
const requested = (raw ?? "").split(" ").filter(Boolean);
|
|
321
349
|
if (!requested.length) return [...allowed];
|
|
322
350
|
const asked = requested.filter((s) => allowed.includes(s));
|
|
323
351
|
if (!asked.length) return allowed.includes("read") ? ["read"] : [];
|
|
324
|
-
|
|
352
|
+
const impliesRead = asked.includes("solve") || asked.includes("write");
|
|
353
|
+
return allowed.filter((s) => asked.includes(s) || s === "read" && impliesRead);
|
|
325
354
|
}
|
|
326
355
|
/**
|
|
327
|
-
* The access levels a consent page offers for a request
|
|
328
|
-
* user may narrow what the client asked for, never widen
|
|
329
|
-
* is offered
|
|
330
|
-
*
|
|
356
|
+
* The access levels a consent page offers for a request: `read` first, all it
|
|
357
|
+
* asked for last. The user may narrow what the client asked for, never widen
|
|
358
|
+
* it. `write` is offered with and without `solve`, so change access needn't
|
|
359
|
+
* spend compute budget, and a host policy that allows one can still grant it.
|
|
360
|
+
* An upload request is offered as asked: narrowing it to read would leave the
|
|
361
|
+
* client unable to do the one thing it signed in for.
|
|
331
362
|
*/
|
|
332
363
|
function consentChoices(scopes) {
|
|
364
|
+
if (!scopes.length) return [];
|
|
333
365
|
if (scopes.includes("upload")) return [{
|
|
334
366
|
access: "upload",
|
|
335
367
|
scopes: [...scopes]
|
|
336
368
|
}];
|
|
369
|
+
const solve = scopes.includes("solve");
|
|
370
|
+
const write = scopes.includes("write");
|
|
337
371
|
const choices = [{
|
|
338
372
|
access: "read",
|
|
339
373
|
scopes: ["read"]
|
|
340
374
|
}];
|
|
341
|
-
if (
|
|
375
|
+
if (solve) choices.push({
|
|
342
376
|
access: "solve",
|
|
343
|
-
scopes: [
|
|
377
|
+
scopes: ["read", "solve"]
|
|
378
|
+
});
|
|
379
|
+
if (write) choices.push({
|
|
380
|
+
access: "write",
|
|
381
|
+
scopes: ["read", "write"]
|
|
382
|
+
});
|
|
383
|
+
if (solve && write) choices.push({
|
|
384
|
+
access: "write_and_solve",
|
|
385
|
+
scopes: [
|
|
386
|
+
"read",
|
|
387
|
+
"solve",
|
|
388
|
+
"write"
|
|
389
|
+
]
|
|
344
390
|
});
|
|
345
391
|
return choices;
|
|
346
392
|
}
|
|
@@ -422,6 +468,6 @@ function safeEqual(a, b) {
|
|
|
422
468
|
const y = Buffer.from(b);
|
|
423
469
|
return x.length === y.length && timingSafeEqual(x, y);
|
|
424
470
|
}
|
|
425
|
-
export {
|
|
471
|
+
export { createOAuthServer as a, consentChoices as i, OAuthError as n, isLoopbackRedirect as o, apiScopesFor as r, resourceMetadataUrl as s, CODE_TTL_MS as t };
|
|
426
472
|
|
|
427
473
|
//# sourceMappingURL=oauth.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oauth.js","names":["sign"],"sources":["../../../../server/src/oauth/index.ts"],"sourcesContent":["/**\n * OAuth 2.1 for MCP clients and the Grasshopper plugin, with this instance as\n * its own authorization server.\n *\n * The access token is an ordinary API token. The host mints it while the user is\n * signed in, at consent, through the same path as Team → API tokens; this\n * module seals the raw key into the authorization code and hands it over at the\n * token endpoint. So `/mcp` and `/api/v1` keep one credential type.\n *\n * Nothing here is stored. A registered client's id is its own signed metadata,\n * and a code is its own encrypted grant, bound to the issuing origin. The only\n * state is the set of redeemed codes, in the host's memory, so on several\n * replicas a code could be redeemed once per replica within its minute, and only\n * by whoever holds the PKCE verifier.\n */\n\nimport {\n\tcreateCipheriv,\n\tcreateDecipheriv,\n\tcreateHash,\n\tcreateHmac,\n\thkdfSync,\n\trandomBytes,\n\ttimingSafeEqual\n} from 'node:crypto';\n\n/** The scopes a grant can carry. Each maps to one org-wide API scope. */\nexport const OAUTH_SCOPES = ['read', 'solve', 'upload', 'create_projects'] as const;\nexport type OAuthScope = (typeof OAUTH_SCOPES)[number];\n\n/**\n * All a registered (DCR or CIMD) client can be granted. Its name and redirects\n * are whatever the registrant chose, so `upload`, which puts code on the org's\n * Compute server, and `create_projects` stay with the built-in client and a\n * look-alike can't phish for them.\n */\nexport const REGISTERED_CLIENT_SCOPES = ['read', 'solve'] as const satisfies readonly OAuthScope[];\n\n/** The Grasshopper plugin's client id. Built in, so it needs no registration and works air-gapped. */\nexport const GRASSHOPPER_CLIENT_ID = 'selva-grasshopper';\n\n// Loopback on any port (RFC 8252 §7.3), but only this host and path: the code\n// can only ever reach a program on the user's own machine.\nconst GRASSHOPPER_CLIENT: OAuthClient = {\n\tclientId: GRASSHOPPER_CLIENT_ID,\n\tname: 'Selva for Grasshopper',\n\tredirectUris: ['http://127.0.0.1/callback'],\n\tbuiltIn: true,\n\tscopes: ['read', 'upload', 'create_projects']\n};\n\nexport const MCP_PATH = '/mcp';\n\nexport const CODE_TTL_MS = 60_000;\nconst CLIENT_NAME_MAX = 100;\nconst REDIRECT_URIS_MAX = 10;\nconst CIMD_TTL_MS = 60 * 60_000;\n// A failing metadata URL is not refetched for this long: each fetch is outbound\n// work an anonymous caller could otherwise trigger at will.\nconst CIMD_FAILURE_TTL_MS = 60_000;\nconst CIMD_CACHE_MAX = 500;\nconst LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);\n\nexport class OAuthError extends Error {\n\tconstructor(\n\t\t/** RFC 6749 / 7591 error code. */\n\t\treadonly error: string,\n\t\tdescription: string,\n\t\treadonly status = 400\n\t) {\n\t\tsuper(description);\n\t\tthis.name = 'OAuthError';\n\t}\n\n\ttoBody(): { error: string; error_description: string } {\n\t\treturn { error: this.error, error_description: this.message };\n\t}\n}\n\nexport interface OAuthClient {\n\tclientId: string;\n\t/** Shown on the consent page. Unverified for a registered client: whatever it claimed. */\n\tname: string;\n\tredirectUris: string[];\n\t/** Shipped with this server, so its name can be trusted. */\n\tbuiltIn: boolean;\n\t/** All this client can be granted, whatever it asks for. */\n\tscopes: readonly OAuthScope[];\n}\n\n/** A validated `/oauth/authorize` request, ready for the consent page. */\nexport interface AuthorizeRequest {\n\tclient: OAuthClient;\n\tredirectUri: string;\n\tstate?: string;\n\tcodeChallenge: string;\n\tscopes: OAuthScope[];\n\tresource: string;\n}\n\n/** What the host minted at consent. `secret` is the raw API key. */\nexport interface Grant {\n\ttokenId: string;\n\tsecret: string;\n\tscopes: OAuthScope[];\n\texpiresAt: string;\n}\n\nexport interface OAuthServerOptions {\n\t/** This instance's origin, e.g. `https://selva.example.com`. */\n\torigin: string;\n\t/** `SELVA_HMAC_KEY`. Signs client ids and seals codes. */\n\tsecret: string;\n\t/** The key before the last rotation: client ids and codes it made still verify. */\n\tpreviousSecret?: string;\n\t/**\n\t * Fetches a Client ID Metadata Document. The URL comes from an unknown client,\n\t * so the host must guard it against SSRF. Without it, URL client ids are refused.\n\t */\n\tfetchClientMetadata?: (url: string) => Promise<unknown>;\n\t/**\n\t * Redeemed code hashes and their expiry. Pass one map for the process so a\n\t * rebuilt server (a new origin, a rotated secret) still refuses a replay.\n\t */\n\tredeemedCodes?: Map<string, number>;\n\t/** Called once a code is exchanged, with the token its grant carries. */\n\tonRedeemed?: (tokenId: string) => void;\n\tnow?: () => number;\n}\n\ninterface HttpResult {\n\tstatus: number;\n\tbody: Record<string, unknown>;\n}\n\n// ============================================================================\n// Discovery documents\n// ============================================================================\n\nexport function mcpResourceUrl(origin: string): string {\n\treturn origin + MCP_PATH;\n}\n\nexport function resourceMetadataUrl(origin: string): string {\n\treturn `${origin}/.well-known/oauth-protected-resource${MCP_PATH}`;\n}\n\n/** RFC 9728. Claude uses only the first authorization server. */\nexport function protectedResourceMetadata(origin: string) {\n\treturn {\n\t\tresource: mcpResourceUrl(origin),\n\t\tauthorization_servers: [origin],\n\t\tscopes_supported: [...REGISTERED_CLIENT_SCOPES],\n\t\tbearer_methods_supported: ['header']\n\t};\n}\n\n/**\n * RFC 8414. Claude picks Client ID Metadata Documents only when both\n * `client_id_metadata_document_supported` and the `none` auth method appear.\n */\nexport function authorizationServerMetadata(origin: string) {\n\treturn {\n\t\tissuer: origin,\n\t\tauthorization_endpoint: `${origin}/oauth/authorize`,\n\t\ttoken_endpoint: `${origin}/oauth/token`,\n\t\tregistration_endpoint: `${origin}/oauth/register`,\n\t\tresponse_types_supported: ['code'],\n\t\tgrant_types_supported: ['authorization_code'],\n\t\tcode_challenge_methods_supported: ['S256'],\n\t\ttoken_endpoint_auth_methods_supported: ['none'],\n\t\tscopes_supported: [...OAUTH_SCOPES],\n\t\tclient_id_metadata_document_supported: true,\n\t\tauthorization_response_iss_parameter_supported: true\n\t};\n}\n\n// ============================================================================\n// Server\n// ============================================================================\n\nexport function createOAuthServer(options: OAuthServerOptions) {\n\tconst { origin } = options;\n\tconst now = options.now ?? Date.now;\n\tconst signKey = derive(options.secret, 'selva-oauth-client');\n\tconst codeKey = derive(options.secret, `selva-oauth-code:${origin}`);\n\tconst previous = options.previousSecret;\n\tconst previousSignKey = previous ? derive(previous, 'selva-oauth-client') : undefined;\n\tconst previousCodeKey = previous ? derive(previous, `selva-oauth-code:${origin}`) : undefined;\n\tconst redeemed = options.redeemedCodes ?? new Map<string, number>();\n\tconst metadataCache = new Map<\n\t\tstring,\n\t\t{ at: number; client: OAuthClient } | { at: number; failure: OAuthError }\n\t>();\n\n\t// ==========================================================================\n\t// Clients\n\t// ==========================================================================\n\n\t/** RFC 7591. The client id carries the metadata, signed, so nothing is stored. */\n\tfunction register(input: unknown): HttpResult {\n\t\ttry {\n\t\t\tconst meta = (input ?? {}) as { client_name?: unknown; redirect_uris?: unknown };\n\t\t\tconst redirectUris = checkRedirectUris(meta.redirect_uris);\n\t\t\tconst name = typeof meta.client_name === 'string' ? meta.client_name.trim() : '';\n\t\t\tconst payload = b64(\n\t\t\t\tJSON.stringify({ n: name.slice(0, CLIENT_NAME_MAX), r: redirectUris, t: now() })\n\t\t\t);\n\t\t\tconst clientId = `dcr_${payload}.${sign(signKey, payload)}`;\n\t\t\treturn {\n\t\t\t\tstatus: 201,\n\t\t\t\tbody: {\n\t\t\t\t\tclient_id: clientId,\n\t\t\t\t\tclient_id_issued_at: Math.floor(now() / 1000),\n\t\t\t\t\tclient_name: name || undefined,\n\t\t\t\t\tredirect_uris: redirectUris,\n\t\t\t\t\tgrant_types: ['authorization_code'],\n\t\t\t\t\tresponse_types: ['code'],\n\t\t\t\t\ttoken_endpoint_auth_method: 'none'\n\t\t\t\t}\n\t\t\t};\n\t\t} catch (err) {\n\t\t\tif (err instanceof OAuthError) return { status: err.status, body: err.toBody() };\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tasync function resolveClient(clientId: string): Promise<OAuthClient> {\n\t\tif (clientId === GRASSHOPPER_CLIENT_ID) return GRASSHOPPER_CLIENT;\n\t\tif (clientId.startsWith('dcr_')) return registeredClient(clientId);\n\t\tif (clientId.startsWith('https://')) return metadataClient(clientId);\n\t\tthrow new OAuthError('invalid_client', 'Unknown client.');\n\t}\n\n\tfunction registeredClient(clientId: string): OAuthClient {\n\t\tconst [payload, signature] = clientId.slice('dcr_'.length).split('.');\n\t\tconst signedBy = (key: Buffer | undefined) =>\n\t\t\tkey !== undefined && safeEqual(signature, sign(key, payload));\n\t\tif (!payload || !signature || !(signedBy(signKey) || signedBy(previousSignKey))) {\n\t\t\tthrow new OAuthError('invalid_client', 'Unknown client.');\n\t\t}\n\t\tconst meta = JSON.parse(unb64(payload)) as { n: string; r: string[] };\n\t\treturn {\n\t\t\tclientId,\n\t\t\tname: meta.n || 'An MCP client',\n\t\t\tredirectUris: meta.r,\n\t\t\tbuiltIn: false,\n\t\t\tscopes: REGISTERED_CLIENT_SCOPES\n\t\t};\n\t}\n\n\tasync function metadataClient(url: string): Promise<OAuthClient> {\n\t\tconst cached = metadataCache.get(url);\n\t\tif (cached) {\n\t\t\tif ('client' in cached && now() - cached.at < CIMD_TTL_MS) return cached.client;\n\t\t\tif ('failure' in cached && now() - cached.at < CIMD_FAILURE_TTL_MS) throw cached.failure;\n\t\t}\n\t\tif (!options.fetchClientMetadata) {\n\t\t\tthrow new OAuthError('invalid_client', 'This server does not accept URL client ids.');\n\t\t}\n\t\ttry {\n\t\t\tconst client = await readMetadata(url, options.fetchClientMetadata);\n\t\t\tremember(url, { at: now(), client });\n\t\t\treturn client;\n\t\t} catch (err) {\n\t\t\tif (!(err instanceof OAuthError)) throw err;\n\t\t\tremember(url, { at: now(), failure: err });\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tfunction remember(url: string, entry: Parameters<typeof metadataCache.set>[1]) {\n\t\tif (metadataCache.size >= CIMD_CACHE_MAX) {\n\t\t\tmetadataCache.delete(metadataCache.keys().next().value!);\n\t\t}\n\t\tmetadataCache.set(url, entry);\n\t}\n\n\t// ==========================================================================\n\t// Authorization\n\t// ==========================================================================\n\n\t/**\n\t * Validates the query `/oauth/authorize` arrives with. An `OAuthError` from a\n\t * bad client or redirect URI must be shown, not redirected: the redirect target\n\t * is exactly what can't be trusted.\n\t */\n\tasync function parseAuthorizeRequest(query: URLSearchParams): Promise<AuthorizeRequest> {\n\t\tconst client = await resolveClient(query.get('client_id') ?? '');\n\t\tconst redirectUri = query.get('redirect_uri') ?? '';\n\t\tif (!client.redirectUris.some((r) => redirectMatches(r, redirectUri))) {\n\t\t\tthrow new OAuthError(\n\t\t\t\t'invalid_request',\n\t\t\t\t'The redirect URI is not registered for this client.'\n\t\t\t);\n\t\t}\n\t\tif (query.get('response_type') !== 'code') {\n\t\t\tthrow new OAuthError('unsupported_response_type', 'Only response_type=code is supported.');\n\t\t}\n\t\tconst codeChallenge = query.get('code_challenge') ?? '';\n\t\tif (!codeChallenge || query.get('code_challenge_method') !== 'S256') {\n\t\t\tthrow new OAuthError('invalid_request', 'PKCE with code_challenge_method=S256 is required.');\n\t\t}\n\t\tconst resource = query.get('resource') ?? mcpResourceUrl(origin);\n\t\tif (!isThisResource(resource)) {\n\t\t\tthrow new OAuthError('invalid_target', 'The resource is not this server.');\n\t\t}\n\t\treturn {\n\t\t\tclient,\n\t\t\tredirectUri,\n\t\t\tstate: query.get('state') ?? undefined,\n\t\t\tcodeChallenge,\n\t\t\tscopes: parseScopes(query.get('scope'), client.scopes),\n\t\t\tresource\n\t\t};\n\t}\n\n\t/** Where to send the browser after consent: the client's redirect URI with a code. */\n\tfunction approve(request: AuthorizeRequest, grant: Grant): string {\n\t\tconst code = seal(codeKey, {\n\t\t\tc: request.client.clientId,\n\t\t\tr: request.redirectUri,\n\t\t\tp: request.codeChallenge,\n\t\t\tx: now() + CODE_TTL_MS,\n\t\t\tg: grant\n\t\t});\n\t\treturn withParams(request.redirectUri, { code, state: request.state, iss: origin });\n\t}\n\n\tfunction deny(request: AuthorizeRequest): string {\n\t\treturn withParams(request.redirectUri, {\n\t\t\terror: 'access_denied',\n\t\t\tstate: request.state,\n\t\t\tiss: origin\n\t\t});\n\t}\n\n\t// ==========================================================================\n\t// Token endpoint\n\t// ==========================================================================\n\n\tfunction exchange(form: URLSearchParams): HttpResult {\n\t\ttry {\n\t\t\tif (form.get('grant_type') !== 'authorization_code') {\n\t\t\t\tthrow new OAuthError('unsupported_grant_type', 'Only authorization_code is supported.');\n\t\t\t}\n\t\t\tconst code = form.get('code') ?? '';\n\t\t\tconst sealed = (open(codeKey, code) ??\n\t\t\t\t(previousCodeKey ? open(previousCodeKey, code) : null)) as {\n\t\t\t\tc: string;\n\t\t\t\tr: string;\n\t\t\t\tp: string;\n\t\t\t\tx: number;\n\t\t\t\tg: Grant;\n\t\t\t} | null;\n\t\t\tif (!sealed || sealed.x < now()) {\n\t\t\t\tthrow new OAuthError('invalid_grant', 'The code is invalid or expired.');\n\t\t\t}\n\t\t\tif (sealed.c !== form.get('client_id') || sealed.r !== form.get('redirect_uri')) {\n\t\t\t\tthrow new OAuthError('invalid_grant', 'The code was issued to another client.');\n\t\t\t}\n\t\t\tconst verifier = form.get('code_verifier') ?? '';\n\t\t\tif (!safeEqual(createHash('sha256').update(verifier).digest('base64url'), sealed.p)) {\n\t\t\t\tthrow new OAuthError('invalid_grant', 'The code_verifier does not match.');\n\t\t\t}\n\t\t\tconst resource = form.get('resource');\n\t\t\tif (resource !== null && !isThisResource(resource)) {\n\t\t\t\tthrow new OAuthError('invalid_target', 'The resource is not this server.');\n\t\t\t}\n\t\t\tif (!markRedeemed(code, sealed.x)) {\n\t\t\t\tthrow new OAuthError('invalid_grant', 'The code was already used.');\n\t\t\t}\n\t\t\tconst { g } = sealed;\n\t\t\toptions.onRedeemed?.(g.tokenId);\n\t\t\treturn {\n\t\t\t\tstatus: 200,\n\t\t\t\tbody: {\n\t\t\t\t\taccess_token: g.secret,\n\t\t\t\t\ttoken_type: 'Bearer',\n\t\t\t\t\texpires_in: Math.max(0, Math.floor((Date.parse(g.expiresAt) - now()) / 1000)),\n\t\t\t\t\tscope: g.scopes.join(' ')\n\t\t\t\t}\n\t\t\t};\n\t\t} catch (err) {\n\t\t\tif (err instanceof OAuthError) return { status: err.status, body: err.toBody() };\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tfunction markRedeemed(code: string, expiresAt: number): boolean {\n\t\tconst t = now();\n\t\tfor (const [k, x] of redeemed) if (x < t) redeemed.delete(k);\n\t\tconst id = createHash('sha256').update(code).digest('base64url');\n\t\tif (redeemed.has(id)) return false;\n\t\tredeemed.set(id, expiresAt);\n\t\treturn true;\n\t}\n\n\tfunction isThisResource(resource: string): boolean {\n\t\tconst r = resource.replace(/\\/$/, '');\n\t\treturn r === origin || r === mcpResourceUrl(origin);\n\t}\n\n\treturn {\n\t\tregister,\n\t\tresolveClient,\n\t\tparseAuthorizeRequest,\n\t\tapprove,\n\t\tdeny,\n\t\texchange,\n\t\tprotectedResourceMetadata: () => protectedResourceMetadata(origin),\n\t\tauthorizationServerMetadata: () => authorizationServerMetadata(origin)\n\t};\n}\n\nexport type OAuthServer = ReturnType<typeof createOAuthServer>;\n\n/** OAuth scopes to the API scopes a minted token gets. */\nexport function apiScopesFor(scopes: readonly OAuthScope[]): string[] {\n\treturn scopes.map((s) => `${s}:all`);\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nasync function readMetadata(\n\turl: string,\n\tfetchClientMetadata: (url: string) => Promise<unknown>\n): Promise<OAuthClient> {\n\tlet doc: { client_id?: unknown; client_name?: unknown; redirect_uris?: unknown };\n\ttry {\n\t\tdoc = (await fetchClientMetadata(url)) as typeof doc;\n\t} catch {\n\t\tthrow new OAuthError('invalid_client', 'The client metadata document could not be read.');\n\t}\n\tif (doc?.client_id !== url) {\n\t\tthrow new OAuthError('invalid_client', 'The metadata document names a different client_id.');\n\t}\n\treturn {\n\t\tclientId: url,\n\t\tname:\n\t\t\ttypeof doc.client_name === 'string' && doc.client_name.trim()\n\t\t\t\t? doc.client_name.trim().slice(0, CLIENT_NAME_MAX)\n\t\t\t\t: new URL(url).host,\n\t\tredirectUris: checkRedirectUris(doc.redirect_uris),\n\t\tbuiltIn: false,\n\t\tscopes: REGISTERED_CLIENT_SCOPES\n\t};\n}\n\n/**\n * What the request asks for, within what its client may have. A scope outside\n * that is dropped, not refused, so a client that asks for every advertised\n * scope still signs in with what it may have. No `scope` at all means all of\n * them. Asking only for scopes it may not have gets `read`, never more than it\n * asked for. `read` rides along with `solve`, which the consent page offers as\n * \"read and run solves\".\n */\nfunction parseScopes(raw: string | null, allowed: readonly OAuthScope[]): OAuthScope[] {\n\tconst requested = (raw ?? '').split(' ').filter(Boolean);\n\tif (!requested.length) return [...allowed];\n\tconst asked = requested.filter((s): s is OAuthScope =>\n\t\t(allowed as readonly string[]).includes(s)\n\t);\n\tif (!asked.length) return allowed.includes('read') ? ['read'] : [];\n\treturn allowed.filter((s) => asked.includes(s) || (s === 'read' && asked.includes('solve')));\n}\n\n/** One access level a consent page offers, and the scopes approving it grants. */\nexport interface ConsentChoice {\n\taccess: 'read' | 'solve' | 'upload';\n\tscopes: OAuthScope[];\n}\n\n/**\n * The access levels a consent page offers for a request, narrowest first. The\n * user may narrow what the client asked for, never widen it. An upload request\n * is offered as asked: narrowing it to read would leave the client unable to\n * do the one thing it signed in for.\n */\nexport function consentChoices(scopes: readonly OAuthScope[]): ConsentChoice[] {\n\tif (scopes.includes('upload')) return [{ access: 'upload', scopes: [...scopes] }];\n\tconst choices: ConsentChoice[] = [{ access: 'read', scopes: ['read'] }];\n\tif (scopes.includes('solve')) choices.push({ access: 'solve', scopes: [...scopes] });\n\treturn choices;\n}\n\nfunction checkRedirectUris(value: unknown): string[] {\n\tif (!Array.isArray(value) || !value.length || value.length > REDIRECT_URIS_MAX) {\n\t\tthrow new OAuthError('invalid_redirect_uri', 'Give between 1 and 10 redirect_uris.');\n\t}\n\tfor (const uri of value) {\n\t\tif (typeof uri !== 'string' || !isAllowedRedirect(uri)) {\n\t\t\tthrow new OAuthError(\n\t\t\t\t'invalid_redirect_uri',\n\t\t\t\t'Redirect URIs must be https, or http on a loopback address.'\n\t\t\t);\n\t\t}\n\t}\n\treturn value as string[];\n}\n\nfunction isAllowedRedirect(uri: string): boolean {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(uri);\n\t} catch {\n\t\treturn false;\n\t}\n\tif (url.hash) return false;\n\treturn (\n\t\turl.protocol === 'https:' || (url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname))\n\t);\n}\n\n/** A redirect to a program on the user's own machine, which any local process can claim. */\nexport function isLoopbackRedirect(uri: string): boolean {\n\ttry {\n\t\treturn LOOPBACK_HOSTS.has(new URL(uri).hostname);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/** Exact, except a loopback redirect matches on any port (RFC 8252 §7.3). */\nexport function redirectMatches(registered: string, requested: string): boolean {\n\tif (registered === requested) return true;\n\tlet a: URL, b: URL;\n\ttry {\n\t\ta = new URL(registered);\n\t\tb = new URL(requested);\n\t} catch {\n\t\treturn false;\n\t}\n\treturn (\n\t\ta.protocol === 'http:' &&\n\t\tb.protocol === 'http:' &&\n\t\tLOOPBACK_HOSTS.has(a.hostname) &&\n\t\ta.hostname === b.hostname &&\n\t\ta.pathname === b.pathname &&\n\t\ta.search === b.search &&\n\t\t!b.hash &&\n\t\t!b.username &&\n\t\t!b.password\n\t);\n}\n\nfunction withParams(uri: string, params: Record<string, string | undefined>): string {\n\tconst url = new URL(uri);\n\tfor (const [k, v] of Object.entries(params)) if (v !== undefined) url.searchParams.set(k, v);\n\treturn url.toString();\n}\n\nfunction derive(secret: string, info: string): Buffer {\n\treturn Buffer.from(hkdfSync('sha256', secret, '', info, 32));\n}\n\nfunction sign(key: Buffer, data: string): string {\n\treturn createHmac('sha256', key).update(data).digest('base64url');\n}\n\nfunction seal(key: Buffer, value: unknown): string {\n\tconst iv = randomBytes(12);\n\tconst cipher = createCipheriv('aes-256-gcm', key, iv);\n\tconst body = Buffer.concat([cipher.update(JSON.stringify(value)), cipher.final()]);\n\treturn Buffer.concat([iv, cipher.getAuthTag(), body]).toString('base64url');\n}\n\nfunction open(key: Buffer, sealed: string): unknown {\n\ttry {\n\t\tconst raw = Buffer.from(sealed, 'base64url');\n\t\t// Without the length, a short code is checked against however many tag bytes it has.\n\t\tconst decipher = createDecipheriv('aes-256-gcm', key, raw.subarray(0, 12), {\n\t\t\tauthTagLength: 16\n\t\t});\n\t\tdecipher.setAuthTag(raw.subarray(12, 28));\n\t\tconst body = Buffer.concat([decipher.update(raw.subarray(28)), decipher.final()]);\n\t\treturn JSON.parse(body.toString('utf8'));\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction b64(text: string): string {\n\treturn Buffer.from(text).toString('base64url');\n}\n\nfunction unb64(text: string): string {\n\treturn Buffer.from(text, 'base64url').toString('utf8');\n}\n\nfunction safeEqual(a: string, b: string): boolean {\n\tconst x = Buffer.from(a);\n\tconst y = Buffer.from(b);\n\treturn x.length === y.length && timingSafeEqual(x, y);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2BA,IAAa,eAAe;CAAC;CAAQ;CAAS;CAAU;AAAiB;;;;;;;AASzE,IAAa,2BAA2B,CAAC,QAAQ,OAAO;AAOxD,IAAM,q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AAO,KAAK,MAAM,KAAK,SAAS,MAAM,CAAC;CACxC,QAAQ;EACP,OAAO;CACR;AACD;AAEA,SAAS,IAAI,MAAsB;CAClC,OAAO,OAAO,KAAK,IAAI,CAAC,CAAC,SAAS,WAAW;AAC9C;AAEA,SAAS,MAAM,MAAsB;CACpC,OAAO,OAAO,KAAK,MAAM,WAAW,CAAC,CAAC,SAAS,MAAM;AACtD;AAEA,SAAS,UAAU,GAAW,GAAoB;CACjD,MAAM,IAAI,OAAO,KAAK,CAAC;CACvB,MAAM,IAAI,OAAO,KAAK,CAAC;CACvB,OAAO,EAAE,WAAW,EAAE,UAAU,gBAAgB,GAAG,CAAC;AACrD"}
|
|
1
|
+
{"version":3,"file":"oauth.js","names":["sign"],"sources":["../../../../server/src/oauth/index.ts"],"sourcesContent":["/**\n * OAuth 2.1 for MCP clients and the Grasshopper plugin, with this instance as\n * its own authorization server.\n *\n * The access token is an ordinary API token. The host mints it while the user is\n * signed in, at consent, through the same path as Team → API tokens; this\n * module seals the raw key into the authorization code and hands it over at the\n * token endpoint. So `/mcp` and `/api/v1` keep one credential type.\n *\n * Nothing here is stored. A registered client's id is its own signed metadata,\n * and a code is its own encrypted grant, bound to the issuing origin. The only\n * state is the set of redeemed codes, in the host's memory, so on several\n * replicas a code could be redeemed once per replica within its minute, and only\n * by whoever holds the PKCE verifier.\n */\n\nimport {\n\tcreateCipheriv,\n\tcreateDecipheriv,\n\tcreateHash,\n\tcreateHmac,\n\thkdfSync,\n\trandomBytes,\n\ttimingSafeEqual\n} from 'node:crypto';\n\n/** The scopes a grant can carry. Each maps to one org-wide API scope. */\nexport const OAUTH_SCOPES = ['read', 'solve', 'write', 'upload', 'create_projects'] as const;\nexport type OAuthScope = (typeof OAUTH_SCOPES)[number];\n\n/**\n * All a host may hand registered (DCR or CIMD) clients. Their name and redirects\n * are whatever the registrant chose, so `upload`, which puts code on the org's\n * Compute server, and `create_projects` aren't here. `write` is, but `write:all`\n * covers both at `/api/v1` and can delete projects and definitions, so it is\n * off by default. An allowlist: a new scope reaches registered clients only\n * once it is added here.\n */\nexport const REGISTERABLE_SCOPES = [\n\t'read',\n\t'solve',\n\t'write'\n] as const satisfies readonly OAuthScope[];\nexport type RegisteredClientScope = (typeof REGISTERABLE_SCOPES)[number];\n\n/** The default `registeredClientScopes`. */\nexport const REGISTERED_CLIENT_SCOPES = [\n\t'read',\n\t'solve'\n] as const satisfies readonly RegisteredClientScope[];\n\n/** The Grasshopper plugin's client id. Built in, so it needs no registration and works air-gapped. */\nexport const GRASSHOPPER_CLIENT_ID = 'selva-grasshopper';\n\n// Loopback on any port (RFC 8252 §7.3), but only this host and path: the code\n// can only ever reach a program on the user's own machine.\nconst GRASSHOPPER_CLIENT: OAuthClient = {\n\tclientId: GRASSHOPPER_CLIENT_ID,\n\tname: 'Selva for Grasshopper',\n\tredirectUris: ['http://127.0.0.1/callback'],\n\tbuiltIn: true,\n\tscopes: ['read', 'upload', 'create_projects']\n};\n\nexport const MCP_PATH = '/mcp';\n\nexport const CODE_TTL_MS = 60_000;\nconst CLIENT_NAME_MAX = 100;\nconst REDIRECT_URIS_MAX = 10;\nconst CIMD_TTL_MS = 60 * 60_000;\n// A failing metadata URL is not refetched for this long: each fetch is outbound\n// work an anonymous caller could otherwise trigger at will.\nconst CIMD_FAILURE_TTL_MS = 60_000;\nconst CIMD_CACHE_MAX = 500;\nconst LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);\n\nexport class OAuthError extends Error {\n\tconstructor(\n\t\t/** RFC 6749 / 7591 error code. */\n\t\treadonly error: string,\n\t\tdescription: string,\n\t\treadonly status = 400\n\t) {\n\t\tsuper(description);\n\t\tthis.name = 'OAuthError';\n\t}\n\n\ttoBody(): { error: string; error_description: string } {\n\t\treturn { error: this.error, error_description: this.message };\n\t}\n}\n\nexport interface OAuthClient {\n\tclientId: string;\n\t/** Shown on the consent page. Unverified for a registered client: whatever it claimed. */\n\tname: string;\n\tredirectUris: string[];\n\t/** Shipped with this server, so its name can be trusted. */\n\tbuiltIn: boolean;\n\t/** All this client can be granted, whatever it asks for. */\n\tscopes: readonly OAuthScope[];\n}\n\n/** A validated `/oauth/authorize` request, ready for the consent page. */\nexport interface AuthorizeRequest {\n\tclient: OAuthClient;\n\tredirectUri: string;\n\tstate?: string;\n\tcodeChallenge: string;\n\tscopes: OAuthScope[];\n\tresource: string;\n}\n\n/** What the host minted at consent. `secret` is the raw API key. */\nexport interface Grant {\n\ttokenId: string;\n\tsecret: string;\n\tscopes: OAuthScope[];\n\texpiresAt: string;\n}\n\nexport interface OAuthServerOptions {\n\t/** This instance's origin, e.g. `https://selva.example.com`. */\n\torigin: string;\n\t/** `SELVA_HMAC_KEY`. Signs client ids and seals codes. */\n\tsecret: string;\n\t/** The key before the last rotation: client ids and codes it made still verify. */\n\tpreviousSecret?: string;\n\t/**\n\t * All a DCR or CIMD client can be granted, from {@link REGISTERABLE_SCOPES}\n\t * and including `read`. Default {@link REGISTERED_CLIENT_SCOPES}. Serve the\n\t * server's discovery documents and pass its `registeredScopes` as the MCP\n\t * 401 challenge's scopes, so clients ask for this same list.\n\t */\n\tregisteredClientScopes?: readonly RegisteredClientScope[];\n\t/**\n\t * Fetches a Client ID Metadata Document. The URL comes from an unknown client,\n\t * so the host must guard it against SSRF. Without it, URL client ids are refused.\n\t */\n\tfetchClientMetadata?: (url: string) => Promise<unknown>;\n\t/**\n\t * Redeemed code hashes and their expiry. Pass one map for the process so a\n\t * rebuilt server (a new origin, a rotated secret) still refuses a replay.\n\t */\n\tredeemedCodes?: Map<string, number>;\n\t/** Called once a code is exchanged, with the token its grant carries. */\n\tonRedeemed?: (tokenId: string) => void;\n\tnow?: () => number;\n}\n\ninterface HttpResult {\n\tstatus: number;\n\tbody: Record<string, unknown>;\n}\n\n// ============================================================================\n// Discovery documents\n// ============================================================================\n\nexport function mcpResourceUrl(origin: string): string {\n\treturn origin + MCP_PATH;\n}\n\nexport function resourceMetadataUrl(origin: string): string {\n\treturn `${origin}/.well-known/oauth-protected-resource${MCP_PATH}`;\n}\n\n/**\n * RFC 9728. Claude uses only the first authorization server. `scopes` is what a\n * registered client may be granted; prefer the server's own method, which\n * passes its `registeredClientScopes`.\n */\nexport function protectedResourceMetadata(\n\torigin: string,\n\tscopes: readonly RegisteredClientScope[] = REGISTERED_CLIENT_SCOPES\n) {\n\treturn {\n\t\tresource: mcpResourceUrl(origin),\n\t\tauthorization_servers: [origin],\n\t\tscopes_supported: [...scopes],\n\t\tbearer_methods_supported: ['header']\n\t};\n}\n\n/**\n * RFC 8414. Claude picks Client ID Metadata Documents only when both\n * `client_id_metadata_document_supported` and the `none` auth method appear.\n * Advertises only scopes some client can be granted: a client that asks for one\n * it can never get re-authorizes in a loop. Prefer the server's own method.\n */\nexport function authorizationServerMetadata(\n\torigin: string,\n\tregisteredScopes: readonly RegisteredClientScope[] = REGISTERED_CLIENT_SCOPES\n) {\n\treturn {\n\t\tissuer: origin,\n\t\tauthorization_endpoint: `${origin}/oauth/authorize`,\n\t\ttoken_endpoint: `${origin}/oauth/token`,\n\t\tregistration_endpoint: `${origin}/oauth/register`,\n\t\tresponse_types_supported: ['code'],\n\t\tgrant_types_supported: ['authorization_code'],\n\t\tcode_challenge_methods_supported: ['S256'],\n\t\ttoken_endpoint_auth_methods_supported: ['none'],\n\t\tscopes_supported: OAUTH_SCOPES.filter(\n\t\t\t(s) =>\n\t\t\t\tGRASSHOPPER_CLIENT.scopes.includes(s) ||\n\t\t\t\t(registeredScopes as readonly OAuthScope[]).includes(s)\n\t\t),\n\t\tclient_id_metadata_document_supported: true,\n\t\tauthorization_response_iss_parameter_supported: true\n\t};\n}\n\n/**\n * The host's list, checked: a JS host or a cast gets past the type, and a list\n * without `read` would leave every consent page empty with a message blaming\n * the user's account.\n */\nfunction checkRegisteredScopes(scopes: readonly string[]): RegisteredClientScope[] {\n\tfor (const s of scopes) {\n\t\tif (!(REGISTERABLE_SCOPES as readonly string[]).includes(s)) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`registeredClientScopes: \"${s}\" can't be granted to a registered client.`\n\t\t\t);\n\t\t}\n\t}\n\tif (!scopes.includes('read')) throw new TypeError('registeredClientScopes must include \"read\".');\n\treturn REGISTERABLE_SCOPES.filter((s) => scopes.includes(s));\n}\n\n// ============================================================================\n// Server\n// ============================================================================\n\nexport function createOAuthServer(options: OAuthServerOptions) {\n\tconst { origin } = options;\n\tconst now = options.now ?? Date.now;\n\tconst signKey = derive(options.secret, 'selva-oauth-client');\n\tconst codeKey = derive(options.secret, `selva-oauth-code:${origin}`);\n\tconst previous = options.previousSecret;\n\tconst previousSignKey = previous ? derive(previous, 'selva-oauth-client') : undefined;\n\tconst previousCodeKey = previous ? derive(previous, `selva-oauth-code:${origin}`) : undefined;\n\tconst redeemed = options.redeemedCodes ?? new Map<string, number>();\n\tconst registeredScopes = checkRegisteredScopes(\n\t\toptions.registeredClientScopes ?? REGISTERED_CLIENT_SCOPES\n\t);\n\tconst metadataCache = new Map<\n\t\tstring,\n\t\t{ at: number; client: OAuthClient } | { at: number; failure: OAuthError }\n\t>();\n\n\t// ==========================================================================\n\t// Clients\n\t// ==========================================================================\n\n\t/** RFC 7591. The client id carries the metadata, signed, so nothing is stored. */\n\tfunction register(input: unknown): HttpResult {\n\t\ttry {\n\t\t\tconst meta = (input ?? {}) as { client_name?: unknown; redirect_uris?: unknown };\n\t\t\tconst redirectUris = checkRedirectUris(meta.redirect_uris);\n\t\t\tconst name = typeof meta.client_name === 'string' ? meta.client_name.trim() : '';\n\t\t\tconst payload = b64(\n\t\t\t\tJSON.stringify({ n: name.slice(0, CLIENT_NAME_MAX), r: redirectUris, t: now() })\n\t\t\t);\n\t\t\tconst clientId = `dcr_${payload}.${sign(signKey, payload)}`;\n\t\t\treturn {\n\t\t\t\tstatus: 201,\n\t\t\t\tbody: {\n\t\t\t\t\tclient_id: clientId,\n\t\t\t\t\tclient_id_issued_at: Math.floor(now() / 1000),\n\t\t\t\t\tclient_name: name || undefined,\n\t\t\t\t\tredirect_uris: redirectUris,\n\t\t\t\t\tgrant_types: ['authorization_code'],\n\t\t\t\t\tresponse_types: ['code'],\n\t\t\t\t\ttoken_endpoint_auth_method: 'none'\n\t\t\t\t}\n\t\t\t};\n\t\t} catch (err) {\n\t\t\tif (err instanceof OAuthError) return { status: err.status, body: err.toBody() };\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tasync function resolveClient(clientId: string): Promise<OAuthClient> {\n\t\tif (clientId === GRASSHOPPER_CLIENT_ID) return GRASSHOPPER_CLIENT;\n\t\tif (clientId.startsWith('dcr_')) return registeredClient(clientId);\n\t\tif (clientId.startsWith('https://')) return metadataClient(clientId);\n\t\tthrow new OAuthError('invalid_client', 'Unknown client.');\n\t}\n\n\tfunction registeredClient(clientId: string): OAuthClient {\n\t\tconst [payload, signature] = clientId.slice('dcr_'.length).split('.');\n\t\tconst signedBy = (key: Buffer | undefined) =>\n\t\t\tkey !== undefined && safeEqual(signature, sign(key, payload));\n\t\tif (!payload || !signature || !(signedBy(signKey) || signedBy(previousSignKey))) {\n\t\t\tthrow new OAuthError('invalid_client', 'Unknown client.');\n\t\t}\n\t\tconst meta = JSON.parse(unb64(payload)) as { n: string; r: string[] };\n\t\treturn {\n\t\t\tclientId,\n\t\t\tname: meta.n || 'An MCP client',\n\t\t\tredirectUris: meta.r,\n\t\t\tbuiltIn: false,\n\t\t\tscopes: registeredScopes\n\t\t};\n\t}\n\n\tasync function metadataClient(url: string): Promise<OAuthClient> {\n\t\tconst cached = metadataCache.get(url);\n\t\tif (cached) {\n\t\t\tif ('client' in cached && now() - cached.at < CIMD_TTL_MS) return cached.client;\n\t\t\tif ('failure' in cached && now() - cached.at < CIMD_FAILURE_TTL_MS) throw cached.failure;\n\t\t}\n\t\tif (!options.fetchClientMetadata) {\n\t\t\tthrow new OAuthError('invalid_client', 'This server does not accept URL client ids.');\n\t\t}\n\t\ttry {\n\t\t\tconst client = await readMetadata(url, options.fetchClientMetadata, registeredScopes);\n\t\t\tremember(url, { at: now(), client });\n\t\t\treturn client;\n\t\t} catch (err) {\n\t\t\tif (!(err instanceof OAuthError)) throw err;\n\t\t\tremember(url, { at: now(), failure: err });\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tfunction remember(url: string, entry: Parameters<typeof metadataCache.set>[1]) {\n\t\tif (metadataCache.size >= CIMD_CACHE_MAX) {\n\t\t\tmetadataCache.delete(metadataCache.keys().next().value!);\n\t\t}\n\t\tmetadataCache.set(url, entry);\n\t}\n\n\t// ==========================================================================\n\t// Authorization\n\t// ==========================================================================\n\n\t/**\n\t * Validates the query `/oauth/authorize` arrives with. An `OAuthError` from a\n\t * bad client or redirect URI must be shown, not redirected: the redirect target\n\t * is exactly what can't be trusted.\n\t */\n\tasync function parseAuthorizeRequest(query: URLSearchParams): Promise<AuthorizeRequest> {\n\t\tconst client = await resolveClient(query.get('client_id') ?? '');\n\t\tconst redirectUri = query.get('redirect_uri') ?? '';\n\t\tif (!client.redirectUris.some((r) => redirectMatches(r, redirectUri))) {\n\t\t\tthrow new OAuthError(\n\t\t\t\t'invalid_request',\n\t\t\t\t'The redirect URI is not registered for this client.'\n\t\t\t);\n\t\t}\n\t\tif (query.get('response_type') !== 'code') {\n\t\t\tthrow new OAuthError('unsupported_response_type', 'Only response_type=code is supported.');\n\t\t}\n\t\tconst codeChallenge = query.get('code_challenge') ?? '';\n\t\tif (!codeChallenge || query.get('code_challenge_method') !== 'S256') {\n\t\t\tthrow new OAuthError('invalid_request', 'PKCE with code_challenge_method=S256 is required.');\n\t\t}\n\t\tconst resource = query.get('resource') ?? mcpResourceUrl(origin);\n\t\tif (!isThisResource(resource)) {\n\t\t\tthrow new OAuthError('invalid_target', 'The resource is not this server.');\n\t\t}\n\t\treturn {\n\t\t\tclient,\n\t\t\tredirectUri,\n\t\t\tstate: query.get('state') ?? undefined,\n\t\t\tcodeChallenge,\n\t\t\tscopes: parseScopes(query.get('scope'), client.scopes),\n\t\t\tresource\n\t\t};\n\t}\n\n\t/** Where to send the browser after consent: the client's redirect URI with a code. */\n\tfunction approve(request: AuthorizeRequest, grant: Grant): string {\n\t\tconst code = seal(codeKey, {\n\t\t\tc: request.client.clientId,\n\t\t\tr: request.redirectUri,\n\t\t\tp: request.codeChallenge,\n\t\t\tx: now() + CODE_TTL_MS,\n\t\t\tg: grant\n\t\t});\n\t\treturn withParams(request.redirectUri, { code, state: request.state, iss: origin });\n\t}\n\n\tfunction deny(request: AuthorizeRequest): string {\n\t\treturn withParams(request.redirectUri, {\n\t\t\terror: 'access_denied',\n\t\t\tstate: request.state,\n\t\t\tiss: origin\n\t\t});\n\t}\n\n\t// ==========================================================================\n\t// Token endpoint\n\t// ==========================================================================\n\n\tfunction exchange(form: URLSearchParams): HttpResult {\n\t\ttry {\n\t\t\tif (form.get('grant_type') !== 'authorization_code') {\n\t\t\t\tthrow new OAuthError('unsupported_grant_type', 'Only authorization_code is supported.');\n\t\t\t}\n\t\t\tconst code = form.get('code') ?? '';\n\t\t\tconst sealed = (open(codeKey, code) ??\n\t\t\t\t(previousCodeKey ? open(previousCodeKey, code) : null)) as {\n\t\t\t\tc: string;\n\t\t\t\tr: string;\n\t\t\t\tp: string;\n\t\t\t\tx: number;\n\t\t\t\tg: Grant;\n\t\t\t} | null;\n\t\t\tif (!sealed || sealed.x < now()) {\n\t\t\t\tthrow new OAuthError('invalid_grant', 'The code is invalid or expired.');\n\t\t\t}\n\t\t\tif (sealed.c !== form.get('client_id') || sealed.r !== form.get('redirect_uri')) {\n\t\t\t\tthrow new OAuthError('invalid_grant', 'The code was issued to another client.');\n\t\t\t}\n\t\t\tconst verifier = form.get('code_verifier') ?? '';\n\t\t\tif (!safeEqual(createHash('sha256').update(verifier).digest('base64url'), sealed.p)) {\n\t\t\t\tthrow new OAuthError('invalid_grant', 'The code_verifier does not match.');\n\t\t\t}\n\t\t\tconst resource = form.get('resource');\n\t\t\tif (resource !== null && !isThisResource(resource)) {\n\t\t\t\tthrow new OAuthError('invalid_target', 'The resource is not this server.');\n\t\t\t}\n\t\t\tif (!markRedeemed(code, sealed.x)) {\n\t\t\t\tthrow new OAuthError('invalid_grant', 'The code was already used.');\n\t\t\t}\n\t\t\tconst { g } = sealed;\n\t\t\toptions.onRedeemed?.(g.tokenId);\n\t\t\treturn {\n\t\t\t\tstatus: 200,\n\t\t\t\tbody: {\n\t\t\t\t\taccess_token: g.secret,\n\t\t\t\t\ttoken_type: 'Bearer',\n\t\t\t\t\texpires_in: Math.max(0, Math.floor((Date.parse(g.expiresAt) - now()) / 1000)),\n\t\t\t\t\tscope: g.scopes.join(' ')\n\t\t\t\t}\n\t\t\t};\n\t\t} catch (err) {\n\t\t\tif (err instanceof OAuthError) return { status: err.status, body: err.toBody() };\n\t\t\tthrow err;\n\t\t}\n\t}\n\n\tfunction markRedeemed(code: string, expiresAt: number): boolean {\n\t\tconst t = now();\n\t\tfor (const [k, x] of redeemed) if (x < t) redeemed.delete(k);\n\t\tconst id = createHash('sha256').update(code).digest('base64url');\n\t\tif (redeemed.has(id)) return false;\n\t\tredeemed.set(id, expiresAt);\n\t\treturn true;\n\t}\n\n\tfunction isThisResource(resource: string): boolean {\n\t\tconst r = resource.replace(/\\/$/, '');\n\t\treturn r === origin || r === mcpResourceUrl(origin);\n\t}\n\n\treturn {\n\t\tregister,\n\t\tresolveClient,\n\t\tparseAuthorizeRequest,\n\t\tapprove,\n\t\tdeny,\n\t\texchange,\n\t\t/** All a registered client can be granted: the MCP 401 challenge's scopes. */\n\t\tregisteredScopes: registeredScopes as readonly RegisteredClientScope[],\n\t\tprotectedResourceMetadata: () => protectedResourceMetadata(origin, registeredScopes),\n\t\tauthorizationServerMetadata: () => authorizationServerMetadata(origin, registeredScopes)\n\t};\n}\n\nexport type OAuthServer = ReturnType<typeof createOAuthServer>;\n\n/** OAuth scopes to the API scopes a minted token gets. */\nexport function apiScopesFor(scopes: readonly OAuthScope[]): string[] {\n\treturn scopes.map((s) => `${s}:all`);\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nasync function readMetadata(\n\turl: string,\n\tfetchClientMetadata: (url: string) => Promise<unknown>,\n\tscopes: readonly OAuthScope[]\n): Promise<OAuthClient> {\n\tlet doc: { client_id?: unknown; client_name?: unknown; redirect_uris?: unknown };\n\ttry {\n\t\tdoc = (await fetchClientMetadata(url)) as typeof doc;\n\t} catch {\n\t\tthrow new OAuthError('invalid_client', 'The client metadata document could not be read.');\n\t}\n\tif (doc?.client_id !== url) {\n\t\tthrow new OAuthError('invalid_client', 'The metadata document names a different client_id.');\n\t}\n\treturn {\n\t\tclientId: url,\n\t\tname:\n\t\t\ttypeof doc.client_name === 'string' && doc.client_name.trim()\n\t\t\t\t? doc.client_name.trim().slice(0, CLIENT_NAME_MAX)\n\t\t\t\t: new URL(url).host,\n\t\tredirectUris: checkRedirectUris(doc.redirect_uris),\n\t\tbuiltIn: false,\n\t\tscopes\n\t};\n}\n\n/**\n * What the request asks for, within what its client may have. A scope outside\n * that is dropped, not refused, so a client that asks for every advertised\n * scope still signs in with what it may have. No `scope` at all means all of\n * them. Asking only for scopes it may not have gets `read`, never more than it\n * asked for. `read` rides along with `solve` and `write`, which the consent\n * page offers as \"read and run solves\" and \"read and change\".\n */\nfunction parseScopes(raw: string | null, allowed: readonly OAuthScope[]): OAuthScope[] {\n\tconst requested = (raw ?? '').split(' ').filter(Boolean);\n\tif (!requested.length) return [...allowed];\n\tconst asked = requested.filter((s): s is OAuthScope =>\n\t\t(allowed as readonly string[]).includes(s)\n\t);\n\tif (!asked.length) return allowed.includes('read') ? ['read'] : [];\n\tconst impliesRead = asked.includes('solve') || asked.includes('write');\n\treturn allowed.filter((s) => asked.includes(s) || (s === 'read' && impliesRead));\n}\n\n/** One access level a consent page offers, and the scopes approving it grants. */\nexport interface ConsentChoice {\n\taccess: 'read' | 'solve' | 'write' | 'write_and_solve' | 'upload';\n\tscopes: OAuthScope[];\n}\n\n/**\n * The access levels a consent page offers for a request: `read` first, all it\n * asked for last. The user may narrow what the client asked for, never widen\n * it. `write` is offered with and without `solve`, so change access needn't\n * spend compute budget, and a host policy that allows one can still grant it.\n * An upload request is offered as asked: narrowing it to read would leave the\n * client unable to do the one thing it signed in for.\n */\nexport function consentChoices(scopes: readonly OAuthScope[]): ConsentChoice[] {\n\tif (!scopes.length) return [];\n\tif (scopes.includes('upload')) return [{ access: 'upload', scopes: [...scopes] }];\n\tconst solve = scopes.includes('solve');\n\tconst write = scopes.includes('write');\n\tconst choices: ConsentChoice[] = [{ access: 'read', scopes: ['read'] }];\n\tif (solve) choices.push({ access: 'solve', scopes: ['read', 'solve'] });\n\tif (write) choices.push({ access: 'write', scopes: ['read', 'write'] });\n\tif (solve && write) {\n\t\tchoices.push({ access: 'write_and_solve', scopes: ['read', 'solve', 'write'] });\n\t}\n\treturn choices;\n}\n\nfunction checkRedirectUris(value: unknown): string[] {\n\tif (!Array.isArray(value) || !value.length || value.length > REDIRECT_URIS_MAX) {\n\t\tthrow new OAuthError('invalid_redirect_uri', 'Give between 1 and 10 redirect_uris.');\n\t}\n\tfor (const uri of value) {\n\t\tif (typeof uri !== 'string' || !isAllowedRedirect(uri)) {\n\t\t\tthrow new OAuthError(\n\t\t\t\t'invalid_redirect_uri',\n\t\t\t\t'Redirect URIs must be https, or http on a loopback address.'\n\t\t\t);\n\t\t}\n\t}\n\treturn value as string[];\n}\n\nfunction isAllowedRedirect(uri: string): boolean {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(uri);\n\t} catch {\n\t\treturn false;\n\t}\n\tif (url.hash) return false;\n\treturn (\n\t\turl.protocol === 'https:' || (url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname))\n\t);\n}\n\n/** A redirect to a program on the user's own machine, which any local process can claim. */\nexport function isLoopbackRedirect(uri: string): boolean {\n\ttry {\n\t\treturn LOOPBACK_HOSTS.has(new URL(uri).hostname);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/** Exact, except a loopback redirect matches on any port (RFC 8252 §7.3). */\nexport function redirectMatches(registered: string, requested: string): boolean {\n\tif (registered === requested) return true;\n\tlet a: URL, b: URL;\n\ttry {\n\t\ta = new URL(registered);\n\t\tb = new URL(requested);\n\t} catch {\n\t\treturn false;\n\t}\n\treturn (\n\t\ta.protocol === 'http:' &&\n\t\tb.protocol === 'http:' &&\n\t\tLOOPBACK_HOSTS.has(a.hostname) &&\n\t\ta.hostname === b.hostname &&\n\t\ta.pathname === b.pathname &&\n\t\ta.search === b.search &&\n\t\t!b.hash &&\n\t\t!b.username &&\n\t\t!b.password\n\t);\n}\n\nfunction withParams(uri: string, params: Record<string, string | undefined>): string {\n\tconst url = new URL(uri);\n\tfor (const [k, v] of Object.entries(params)) if (v !== undefined) url.searchParams.set(k, v);\n\treturn url.toString();\n}\n\nfunction derive(secret: string, info: string): Buffer {\n\treturn Buffer.from(hkdfSync('sha256', secret, '', info, 32));\n}\n\nfunction sign(key: Buffer, data: string): string {\n\treturn createHmac('sha256', key).update(data).digest('base64url');\n}\n\nfunction seal(key: Buffer, value: unknown): string {\n\tconst iv = randomBytes(12);\n\tconst cipher = createCipheriv('aes-256-gcm', key, iv);\n\tconst body = Buffer.concat([cipher.update(JSON.stringify(value)), cipher.final()]);\n\treturn Buffer.concat([iv, cipher.getAuthTag(), body]).toString('base64url');\n}\n\nfunction open(key: Buffer, sealed: string): unknown {\n\ttry {\n\t\tconst raw = Buffer.from(sealed, 'base64url');\n\t\t// Without the length, a short code is checked against however many tag bytes it has.\n\t\tconst decipher = createDecipheriv('aes-256-gcm', key, raw.subarray(0, 12), {\n\t\t\tauthTagLength: 16\n\t\t});\n\t\tdecipher.setAuthTag(raw.subarray(12, 28));\n\t\tconst body = Buffer.concat([decipher.update(raw.subarray(28)), decipher.final()]);\n\t\treturn JSON.parse(body.toString('utf8'));\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction b64(text: string): string {\n\treturn Buffer.from(text).toString('base64url');\n}\n\nfunction unb64(text: string): string {\n\treturn Buffer.from(text, 'base64url').toString('utf8');\n}\n\nfunction safeEqual(a: string, b: string): boolean {\n\t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ACpC,OAAO,OAAO,KAAK,MAAM,WAAW,CAAC,CAAC,SAAS,MAAM;AACtD;AAEA,SAAS,UAAU,GAAW,GAAoB;CACjD,MAAM,IAAI,OAAO,KAAK,CAAC;CACvB,MAAM,IAAI,OAAO,KAAK,CAAC;CACvB,OAAO,EAAE,WAAW,EAAE,UAAU,gBAAgB,GAAG,CAAC;AACrD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"package.js","names":[],"sources":["../../../package.json"],"sourcesContent":["{\n\t\"name\": \"@selvajs/selva\",\n\t\"version\": \"4.21.0-beta.
|
|
1
|
+
{"version":3,"file":"package.js","names":[],"sources":["../../../package.json"],"sourcesContent":["{\n\t\"name\": \"@selvajs/selva\",\n\t\"version\": \"4.21.0-beta.8\",\n\t\"description\": \"Selva — self-contained Grasshopper-driven web app. Install, configure via .env, deploy.\",\n\t\"license\": \"MIT\",\n\t\"author\": \"VektorNode\",\n\t\"homepage\": \"https://selva.dev\",\n\t\"bugs\": \"https://github.com/VektorNode/selva/issues\",\n\t\"keywords\": [\n\t\t\"grasshopper\",\n\t\t\"rhino\",\n\t\t\"rhino-compute\",\n\t\t\"parametric-design\",\n\t\t\"web-app\",\n\t\t\"sveltekit\"\n\t],\n\t\"publishConfig\": {\n\t\t\"access\": \"public\"\n\t},\n\t\"repository\": {\n\t\t\"type\": \"git\",\n\t\t\"url\": \"git+https://github.com/VektorNode/selva.git\",\n\t\t\"directory\": \"packages/selva\"\n\t},\n\t\"type\": \"module\",\n\t\"main\": \"./build/index.js\",\n\t\"files\": [\n\t\t\"build\",\n\t\t\"templates\"\n\t],\n\t\"engines\": {\n\t\t\"node\": \">=24.0.0\"\n\t},\n\t\"scripts\": {\n\t\t\"dev\": \"vite dev\",\n\t\t\"dev:lan\": \"vite dev --host\",\n\t\t\"build\": \"rimraf build && vite build && node ./scripts/generate-templates.js && node ./scripts/write-runtime-meta.js\",\n\t\t\"preview\": \"vite preview\",\n\t\t\"start\": \"node build/index.js\",\n\t\t\"clean\": \"rimraf build templates\",\n\t\t\"prepare\": \"svelte-kit sync || echo ''\",\n\t\t\"check\": \"svelte-kit sync && svelte-check --tsconfig ./tsconfig.json\",\n\t\t\"test\": \"vitest run\",\n\t\t\"test:watch\": \"vitest\",\n\t\t\"openapi:generate\": \"node scripts/generate-openapi.js\",\n\t\t\"test:e2e\": \"playwright test\",\n\t\t\"lint\": \"eslint .\",\n\t\t\"lint:types\": \"eslint . --config eslint.typed.config.js\",\n\t\t\"generate:cli-config\": \"node scripts/generate-cli-config.js\"\n\t},\n\t\"dependencies\": {\n\t\t\"@lucide/svelte\": \"catalog:\",\n\t\t\"@supabase/supabase-js\": \"catalog:\",\n\t\t\"@sveltejs/kit\": \"catalog:\",\n\t\t\"bits-ui\": \"catalog:\",\n\t\t\"clsx\": \"catalog:\",\n\t\t\"mode-watcher\": \"catalog:\",\n\t\t\"nodemailer\": \"catalog:\",\n\t\t\"pino\": \"^10.4.0\",\n\t\t\"rhino3dm\": \"catalog:\",\n\t\t\"sharp\": \"catalog:\",\n\t\t\"tailwind-merge\": \"catalog:\",\n\t\t\"tailwind-variants\": \"catalog:\",\n\t\t\"three\": \"catalog:\",\n\t\t\"zod\": \"catalog:\"\n\t},\n\t\"optionalDependencies\": {\n\t\t\"@sentry/node\": \"^11.10.0\"\n\t},\n\t\"devDependencies\": {\n\t\t\"@playwright/test\": \"catalog:\",\n\t\t\"@selvajs/compute\": \"workspace:*\",\n\t\t\"@selvajs/config\": \"workspace:*\",\n\t\t\"@selvajs/header-auth-provider\": \"workspace:*\",\n\t\t\"@selvajs/local-provider\": \"workspace:*\",\n\t\t\"@selvajs/mcp\": \"workspace:*\",\n\t\t\"@selvajs/notifications\": \"workspace:*\",\n\t\t\"@selvajs/platform\": \"workspace:*\",\n\t\t\"@selvajs/schemas\": \"workspace:*\",\n\t\t\"@selvajs/server\": \"workspace:*\",\n\t\t\"@selvajs/solve\": \"workspace:*\",\n\t\t\"@selvajs/supabase-provider\": \"workspace:*\",\n\t\t\"@selvajs/ui\": \"workspace:*\",\n\t\t\"@selvajs/visualization\": \"workspace:*\",\n\t\t\"@sveltejs/adapter-node\": \"catalog:\",\n\t\t\"@types/nodemailer\": \"catalog:\",\n\t\t\"@types/three\": \"catalog:\",\n\t\t\"rimraf\": \"catalog:\",\n\t\t\"tw-animate-css\": \"catalog:\",\n\t\t\"vitest\": \"catalog:\"\n\t},\n\t\"imports\": {\n\t\t\"#lib/*\": \"./src/lib/*\"\n\t}\n}\n"],"mappings":""}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { K as actorFrom, g as getPermissionStore, u as getEventSink } from "./providers.server.js";
|
|
2
2
|
// src/lib/server/permissions.server.ts
|
|
3
3
|
/**
|
|
4
4
|
* Permission read/write seam over `IPlatformPermissionStore`. Reads happen
|
|
@@ -8,8 +8,8 @@ import { t as ALL_PLATFORM_PERMISSIONS } from "./types3.js";
|
|
|
8
8
|
import { d as encodeOffsetCursor, l as clampPageLimit, u as decodeOffsetCursor } from "./visibility.js";
|
|
9
9
|
import { n as readBool } from "./limits.js";
|
|
10
10
|
import { a as createLogger, i as ConsoleLogger, n as renderThrown } from "./definitions.js";
|
|
11
|
-
import { c as
|
|
12
|
-
import { i as
|
|
11
|
+
import { c as stableStringify, d as ErrorCodes, g as isDefinitionRef, h as enableDebugLogging, i as TreeBuilder, l as withSolveMode, n as GrasshopperClient, u as ComputeError } from "./grasshopper.js";
|
|
12
|
+
import { i as serverSourcedInputIds, n as KEEPALIVE_PREFERENCE, o as getInputItems, r as raceAbort, t as KEEPALIVE_INTERVAL_MS } from "./keepalive-vtcjhAV3.js";
|
|
13
13
|
import { createRequire } from "node:module";
|
|
14
14
|
import * as crypto from "node:crypto";
|
|
15
15
|
import { createCipheriv, createDecipheriv, createHash, createHmac, createPrivateKey, randomBytes, randomUUID, sign, timingSafeEqual } from "node:crypto";
|
|
@@ -34193,6 +34193,14 @@ function createClientCache(config) {
|
|
|
34193
34193
|
evictEntry(id);
|
|
34194
34194
|
}
|
|
34195
34195
|
},
|
|
34196
|
+
largestReportedRequestBytes() {
|
|
34197
|
+
let largest = null;
|
|
34198
|
+
for (const { limits } of cache.values()) {
|
|
34199
|
+
const reported = limits.maxRequestBytes;
|
|
34200
|
+
if (reported !== null && (largest === null || reported > largest)) largest = reported;
|
|
34201
|
+
}
|
|
34202
|
+
return largest;
|
|
34203
|
+
},
|
|
34196
34204
|
solveCacheStats() {
|
|
34197
34205
|
const total = {
|
|
34198
34206
|
warmClients: cache.size,
|
|
@@ -34707,6 +34715,13 @@ var SolveEngine = class {
|
|
|
34707
34715
|
this.clientCache.clearSolveCaches();
|
|
34708
34716
|
}
|
|
34709
34717
|
/**
|
|
34718
|
+
* The largest request body a warm client's server reports accepting
|
|
34719
|
+
* (`RHINO_COMPUTE_MAX_REQUEST_SIZE`). Null until a server that reports one has been reached.
|
|
34720
|
+
*/
|
|
34721
|
+
largestReportedRequestBytes() {
|
|
34722
|
+
return this.clientCache.largestReportedRequestBytes();
|
|
34723
|
+
}
|
|
34724
|
+
/**
|
|
34710
34725
|
* Drop every retained `.gh` byte entry. Safe at any time: entries key on an
|
|
34711
34726
|
* immutable version id, so clearing costs a storage re-read and nothing else.
|
|
34712
34727
|
*/
|
|
@@ -34870,6 +34885,60 @@ var SolveEngine = class {
|
|
|
34870
34885
|
};
|
|
34871
34886
|
}
|
|
34872
34887
|
};
|
|
34888
|
+
var SPACE = new Uint8Array([32]);
|
|
34889
|
+
/** True when the request asked for a keep-alive response (`Prefer: selva-keepalive`). */
|
|
34890
|
+
function wantsKeepalive(request) {
|
|
34891
|
+
const prefer = request.headers.get("Prefer");
|
|
34892
|
+
if (!prefer) return false;
|
|
34893
|
+
return prefer.split(",").some((token) => token.split(";")[0].trim().toLowerCase() === KEEPALIVE_PREFERENCE);
|
|
34894
|
+
}
|
|
34895
|
+
/**
|
|
34896
|
+
* Answers 200 at once and holds the connection with a space every `intervalMs` until `work`
|
|
34897
|
+
* settles, then sends its status, headers and body (wire format in `shared/keepalive.ts`).
|
|
34898
|
+
*
|
|
34899
|
+
* `work` must resolve to every outcome, errors included: once the 200 is out, a rejection can
|
|
34900
|
+
* only drop the connection.
|
|
34901
|
+
*/
|
|
34902
|
+
function respondWithKeepalive(work, intervalMs = KEEPALIVE_INTERVAL_MS) {
|
|
34903
|
+
let timer;
|
|
34904
|
+
const body = new ReadableStream({
|
|
34905
|
+
start(controller) {
|
|
34906
|
+
controller.enqueue(SPACE);
|
|
34907
|
+
timer = setInterval(() => controller.enqueue(SPACE), intervalMs);
|
|
34908
|
+
work.then(async (response) => {
|
|
34909
|
+
clearInterval(timer);
|
|
34910
|
+
const meta = {
|
|
34911
|
+
status: response.status,
|
|
34912
|
+
headers: [...response.headers]
|
|
34913
|
+
};
|
|
34914
|
+
controller.enqueue(new TextEncoder().encode(`${JSON.stringify(meta)}\n`));
|
|
34915
|
+
if (response.body) {
|
|
34916
|
+
const reader = response.body.getReader();
|
|
34917
|
+
for (;;) {
|
|
34918
|
+
const { done, value } = await reader.read();
|
|
34919
|
+
if (done) break;
|
|
34920
|
+
controller.enqueue(value);
|
|
34921
|
+
}
|
|
34922
|
+
}
|
|
34923
|
+
controller.close();
|
|
34924
|
+
}).catch((err) => {
|
|
34925
|
+
clearInterval(timer);
|
|
34926
|
+
controller.error(err);
|
|
34927
|
+
});
|
|
34928
|
+
},
|
|
34929
|
+
cancel() {
|
|
34930
|
+
clearInterval(timer);
|
|
34931
|
+
}
|
|
34932
|
+
});
|
|
34933
|
+
return new Response(body, {
|
|
34934
|
+
status: 200,
|
|
34935
|
+
headers: {
|
|
34936
|
+
"Content-Type": "application/octet-stream",
|
|
34937
|
+
"Cache-Control": "no-store",
|
|
34938
|
+
"Preference-Applied": KEEPALIVE_PREFERENCE
|
|
34939
|
+
}
|
|
34940
|
+
});
|
|
34941
|
+
}
|
|
34873
34942
|
// ../server/src/organizations/org-asset-service.ts
|
|
34874
34943
|
/**
|
|
34875
34944
|
* Orchestrates org-asset writes that span IStorageProvider + IOrgStore — one
|
|
@@ -35641,6 +35710,6 @@ if (!globalThis[ERROR_HOOKS_FLAG]) {
|
|
|
35641
35710
|
getErrorReporter().capture(error, { tags: { origin: "uncaughtException" } });
|
|
35642
35711
|
});
|
|
35643
35712
|
}
|
|
35644
|
-
export { deploymentSnapshot as A,
|
|
35713
|
+
export { deploymentSnapshot as A, LocalComputeServerStore as B, getUserProfileStore as C, computeDebugMode as D, RETIRED_KEYS as E, acceptsGzip as F, NoopEventSink as G, emptyProfile as H, postedServerSourcedIds as I, definitionPaths as J, actorFrom as K, respondWithKeepalive as L, DEFAULT_SOLVE_DEADLINE_MS as M, MAX_SOLVE_DEADLINE_MS as N, deploymentManifest as O, SolveEngine as P, solveInputsFromSchema as R, getTenancy as S, providers as T, classifyAssetPath as U, isEncryptedSecret as V, orgPaths as W, diffSnapshots as Y, getPlatformProjectGrantStore as _, getComputeServerConfigStore as a, getSolveMetricSink as b, getDefinitionService as c, getInviteStore as d, getLogger as f, getPermissionStore as g, getOrganizationProvider as h, getBranding as i, keyRotationStatus as j, deploymentReport as k, getErrorReporter as l, getOrgAssetService as m, getAuditQuery as n, getDataProvider as o, getNotificationProvider as p, actorOf as q, getAuthProvider as r, getDefinitionMeta as s, flag as t, getEventSink as u, getProjectProvider as v, lazyLogger as w, getStorageProvider as x, getShareLinkStore as y, wantsKeepalive as z };
|
|
35645
35714
|
|
|
35646
35715
|
//# sourceMappingURL=providers.server.js.map
|