@warlock.js/devtools 5.57.0 → 5.59.0
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 +23 -0
- package/README.md +3 -0
- package/cjs/{ai-source-DTpxumMA.cjs → ai-source-BdvMfyKw.cjs} +84 -17
- package/cjs/ai-source-BdvMfyKw.cjs.map +1 -0
- package/cjs/app-versions-DfpPZOI2.cjs +253 -0
- package/cjs/app-versions-DfpPZOI2.cjs.map +1 -0
- package/cjs/{auth-DzU0gHDG.cjs → auth-B3wyjJnQ.cjs} +43 -406
- package/cjs/auth-B3wyjJnQ.cjs.map +1 -0
- package/cjs/{boot-Dy5OqgTM.cjs → boot-nczSvJ_F.cjs} +15 -12
- package/cjs/boot-nczSvJ_F.cjs.map +1 -0
- package/cjs/{capture-CqIiaznN.cjs → capture-CuyT8Vab.cjs} +4 -4
- package/cjs/{capture-CqIiaznN.cjs.map → capture-CuyT8Vab.cjs.map} +1 -1
- package/cjs/{cascade-store-pHjKeSFm.cjs → cascade-store-CuRRYzt_.cjs} +141 -4
- package/cjs/cascade-store-CuRRYzt_.cjs.map +1 -0
- package/cjs/{current-request-id-BoJJb3y7.cjs → current-request-id-CeQhRz9Q.cjs} +3 -3
- package/cjs/{current-request-id-BoJJb3y7.cjs.map → current-request-id-CeQhRz9Q.cjs.map} +1 -1
- package/cjs/{errors-CyZp5yS-.cjs → errors-BadbSDX8.cjs} +6 -4
- package/cjs/errors-BadbSDX8.cjs.map +1 -0
- package/cjs/helpers-BcMBFy9v.cjs +439 -0
- package/cjs/helpers-BcMBFy9v.cjs.map +1 -0
- package/cjs/{histogram-BaI-PnCv.cjs → histogram-DTOGnNBW.cjs} +6 -6
- package/cjs/{histogram-BaI-PnCv.cjs.map → histogram-DTOGnNBW.cjs.map} +1 -1
- package/cjs/{http-DCfXQvw-.cjs → http-Biauhqi0.cjs} +517 -28
- package/cjs/http-Biauhqi0.cjs.map +1 -0
- package/cjs/index.cjs +1 -1
- package/cjs/{insights-BKtqxdnP.cjs → insights-BjJA6Ret.cjs} +8 -7
- package/cjs/{insights-BKtqxdnP.cjs.map → insights-BjJA6Ret.cjs.map} +1 -1
- package/cjs/{migrations-w7GMsrQw.cjs → migrations-BP4cYTGo.cjs} +40 -5
- package/cjs/migrations-BP4cYTGo.cjs.map +1 -0
- package/cjs/{options-CWqFC5__.cjs → options-B9FHbRAJ.cjs} +29 -5
- package/cjs/options-B9FHbRAJ.cjs.map +1 -0
- package/cjs/{panels-Rcmeitu3.cjs → panels-D1ITm-jc.cjs} +77 -11
- package/cjs/panels-D1ITm-jc.cjs.map +1 -0
- package/cjs/{process-panel-DEOnLxoT.cjs → process-panel-DskSA7Cm.cjs} +4 -4
- package/cjs/{process-panel-DEOnLxoT.cjs.map → process-panel-DskSA7Cm.cjs.map} +1 -1
- package/cjs/production/index.cjs +4 -4
- package/cjs/{server-ykxsOwob.cjs → server-D3XRbSSb.cjs} +8 -5
- package/cjs/server-D3XRbSSb.cjs.map +1 -0
- package/cjs/{src-UPtTCI2j.cjs → src-QcNghoYN.cjs} +52 -15
- package/cjs/src-QcNghoYN.cjs.map +1 -0
- package/cjs/{store-aq207T8v.cjs → store-CNFv3wVp.cjs} +2 -2
- package/cjs/{stream-route-CJTABkUy.cjs → stream-route-BqyAlfxQ.cjs} +92 -17
- package/cjs/stream-route-BqyAlfxQ.cjs.map +1 -0
- package/esm/app-versions.mjs +74 -0
- package/esm/app-versions.mjs.map +1 -0
- package/esm/devtools-connector.d.mts.map +1 -1
- package/esm/devtools-connector.mjs +10 -3
- package/esm/devtools-connector.mjs.map +1 -1
- package/esm/index.d.mts +3 -3
- package/esm/panel-errors.mjs +33 -0
- package/esm/panel-errors.mjs.map +1 -0
- package/esm/panels.mjs +73 -6
- package/esm/panels.mjs.map +1 -1
- package/esm/production/auth/helpers.mjs +8 -5
- package/esm/production/auth/helpers.mjs.map +1 -1
- package/esm/production/auth/service.mjs +15 -5
- package/esm/production/auth/service.mjs.map +1 -1
- package/esm/production/boot.mjs +5 -2
- package/esm/production/boot.mjs.map +1 -1
- package/esm/production/contracts.d.mts +75 -2
- package/esm/production/contracts.d.mts.map +1 -1
- package/esm/production/contracts.mjs +5 -1
- package/esm/production/contracts.mjs.map +1 -1
- package/esm/production/errors.d.mts +1 -1
- package/esm/production/errors.mjs +5 -3
- package/esm/production/errors.mjs.map +1 -1
- package/esm/production/http/access.mjs +6 -2
- package/esm/production/http/access.mjs.map +1 -1
- package/esm/production/http/constants.mjs +7 -1
- package/esm/production/http/constants.mjs.map +1 -1
- package/esm/production/http/context.mjs.map +1 -1
- package/esm/production/http/cookie.mjs +23 -2
- package/esm/production/http/cookie.mjs.map +1 -1
- package/esm/production/http/mount.mjs +25 -3
- package/esm/production/http/mount.mjs.map +1 -1
- package/esm/production/http/share-session.mjs +114 -0
- package/esm/production/http/share-session.mjs.map +1 -0
- package/esm/production/http/share.mjs +339 -0
- package/esm/production/http/share.mjs.map +1 -0
- package/esm/production/index.d.mts +2 -2
- package/esm/production/insights/writer.mjs +2 -1
- package/esm/production/insights/writer.mjs.map +1 -1
- package/esm/production/options.d.mts +10 -1
- package/esm/production/options.d.mts.map +1 -1
- package/esm/production/options.mjs +27 -3
- package/esm/production/options.mjs.map +1 -1
- package/esm/production/store/cascade-store.mjs +49 -2
- package/esm/production/store/cascade-store.mjs.map +1 -1
- package/esm/production/store/mapping.mjs +29 -1
- package/esm/production/store/mapping.mjs.map +1 -1
- package/esm/production/store/memory-store.mjs +62 -0
- package/esm/production/store/memory-store.mjs.map +1 -1
- package/esm/production/store/migrations.d.mts +2 -1
- package/esm/production/store/migrations.d.mts.map +1 -1
- package/esm/production/store/migrations.mjs +5 -2
- package/esm/production/store/migrations.mjs.map +1 -1
- package/esm/production/store/models/index.mjs +3 -1
- package/esm/production/store/models/share.migration.mjs +27 -0
- package/esm/production/store/models/share.migration.mjs.map +1 -0
- package/esm/production/store/models/share.model.mjs +13 -0
- package/esm/production/store/models/share.model.mjs.map +1 -0
- package/esm/server/ai-routes.mjs +20 -6
- package/esm/server/ai-routes.mjs.map +1 -1
- package/esm/server/panel-files.mjs +35 -0
- package/esm/server/panel-files.mjs.map +1 -0
- package/esm/server/panel-routes.mjs +27 -7
- package/esm/server/panel-routes.mjs.map +1 -1
- package/esm/server/session-routes.mjs +4 -1
- package/esm/server/session-routes.mjs.map +1 -1
- package/esm/sources/ai-source.d.mts.map +1 -1
- package/esm/sources/ai-source.mjs +75 -7
- package/esm/sources/ai-source.mjs.map +1 -1
- package/esm/types.d.mts +91 -3
- package/esm/types.d.mts.map +1 -1
- package/llms-full.txt +57 -19
- package/package.json +8 -8
- package/skills/SKILL.md +57 -19
- package/ui/dashboard/assets/app.css +1 -1
- package/ui/dashboard/assets/app.js +16 -16
- package/ui/dashboard/build-info.json +7 -7
- package/cjs/ai-source-DTpxumMA.cjs.map +0 -1
- package/cjs/auth-DzU0gHDG.cjs.map +0 -1
- package/cjs/boot-Dy5OqgTM.cjs.map +0 -1
- package/cjs/cascade-store-pHjKeSFm.cjs.map +0 -1
- package/cjs/contracts-CVmplkNb.cjs +0 -112
- package/cjs/contracts-CVmplkNb.cjs.map +0 -1
- package/cjs/errors-CyZp5yS-.cjs.map +0 -1
- package/cjs/http-DCfXQvw-.cjs.map +0 -1
- package/cjs/migrations-w7GMsrQw.cjs.map +0 -1
- package/cjs/options-CWqFC5__.cjs.map +0 -1
- package/cjs/panels-Rcmeitu3.cjs.map +0 -1
- package/cjs/rolldown-runtime-Zuuoy_Rh.cjs +0 -52
- package/cjs/server-ykxsOwob.cjs.map +0 -1
- package/cjs/src-UPtTCI2j.cjs.map +0 -1
- package/cjs/stream-route-CJTABkUy.cjs.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { DEVTOOLS_SESSION_COOKIE, DEVTOOLS_SESSION_COOKIE_INSECURE } from "./constants.mjs";
|
|
1
|
+
import { DEVTOOLS_SESSION_COOKIE, DEVTOOLS_SESSION_COOKIE_INSECURE, DEVTOOLS_SHARE_COOKIE, DEVTOOLS_SHARE_COOKIE_INSECURE } from "./constants.mjs";
|
|
2
2
|
|
|
3
3
|
//#region ../../packages/devtools/src/production/http/cookie.ts
|
|
4
4
|
/** The cookie name for the HTTPS mode. */
|
|
@@ -33,7 +33,28 @@ function readCookie(header, name) {
|
|
|
33
33
|
}
|
|
34
34
|
}
|
|
35
35
|
}
|
|
36
|
+
/** The share cookie name for the HTTPS mode. */
|
|
37
|
+
function shareCookieName(secure) {
|
|
38
|
+
return secure ? DEVTOOLS_SHARE_COOKIE : DEVTOOLS_SHARE_COOKIE_INSECURE;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* `Set-Cookie` value for a share grant (or a clearing cookie when `value` is
|
|
42
|
+
* `null`). Scoped to the dashboard path, `HttpOnly`, `SameSite=Strict`, no
|
|
43
|
+
* `Domain`, and it ends after `maxAgeSeconds`.
|
|
44
|
+
*/
|
|
45
|
+
function shareCookie(value, options) {
|
|
46
|
+
const parts = [
|
|
47
|
+
`${shareCookieName(options.secure)}=${value ?? ""}`,
|
|
48
|
+
`Path=${options.path}`,
|
|
49
|
+
"HttpOnly",
|
|
50
|
+
"SameSite=Strict"
|
|
51
|
+
];
|
|
52
|
+
if (options.secure) parts.push("Secure");
|
|
53
|
+
if (value === null) parts.push("Max-Age=0", "Expires=Thu, 01 Jan 1970 00:00:00 GMT");
|
|
54
|
+
else parts.push(`Max-Age=${Math.max(1, Math.floor(options.maxAgeSeconds ?? 0))}`);
|
|
55
|
+
return parts.join("; ");
|
|
56
|
+
}
|
|
36
57
|
|
|
37
58
|
//#endregion
|
|
38
|
-
export { readCookie, sessionCookie, sessionCookieName };
|
|
59
|
+
export { readCookie, sessionCookie, sessionCookieName, shareCookie, shareCookieName };
|
|
39
60
|
//# sourceMappingURL=cookie.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cookie.mjs","names":[],"sources":["../../../../../../../../../packages/devtools/src/production/http/cookie.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"file":"cookie.mjs","names":[],"sources":["../../../../../../../../../packages/devtools/src/production/http/cookie.ts"],"sourcesContent":["import {\n DEVTOOLS_SESSION_COOKIE,\n DEVTOOLS_SESSION_COOKIE_INSECURE,\n DEVTOOLS_SHARE_COOKIE,\n DEVTOOLS_SHARE_COOKIE_INSECURE,\n} from \"./constants\";\n\n/** The cookie name for the HTTPS mode. */\nexport function sessionCookieName(secure: boolean): string {\n return secure ? DEVTOOLS_SESSION_COOKIE : DEVTOOLS_SESSION_COOKIE_INSECURE;\n}\n\n/**\n * `Set-Cookie` value for a session token (or a clearing cookie when `token`\n * is `null`). The cookie is a browser-session cookie scoped to the dashboard\n * path, `HttpOnly` and `SameSite=Strict`, with no `Domain`.\n */\nexport function sessionCookie(\n token: string | null,\n options: { path: string; secure: boolean },\n): string {\n const parts = [\n `${sessionCookieName(options.secure)}=${token ?? \"\"}`,\n `Path=${options.path}`,\n \"HttpOnly\",\n \"SameSite=Strict\",\n ];\n\n if (options.secure) parts.push(\"Secure\");\n\n if (token === null) parts.push(\"Max-Age=0\", \"Expires=Thu, 01 Jan 1970 00:00:00 GMT\");\n\n return parts.join(\"; \");\n}\n\n/** The value of cookie `name` in a `Cookie` header, or `undefined`. */\nexport function readCookie(header: string | undefined, name: string): string | undefined {\n if (!header) return undefined;\n\n for (const pair of header.split(\";\")) {\n const equals = pair.indexOf(\"=\");\n\n if (equals === -1) continue;\n\n if (pair.slice(0, equals).trim() === name) {\n const value = pair.slice(equals + 1).trim();\n\n return value === \"\" ? undefined : value;\n }\n }\n\n return undefined;\n}\n\n/** The share cookie name for the HTTPS mode. */\nexport function shareCookieName(secure: boolean): string {\n return secure ? DEVTOOLS_SHARE_COOKIE : DEVTOOLS_SHARE_COOKIE_INSECURE;\n}\n\n/**\n * `Set-Cookie` value for a share grant (or a clearing cookie when `value` is\n * `null`). Scoped to the dashboard path, `HttpOnly`, `SameSite=Strict`, no\n * `Domain`, and it ends after `maxAgeSeconds`.\n */\nexport function shareCookie(\n value: string | null,\n options: { path: string; secure: boolean; maxAgeSeconds?: number },\n): string {\n const parts = [\n `${shareCookieName(options.secure)}=${value ?? \"\"}`,\n `Path=${options.path}`,\n \"HttpOnly\",\n \"SameSite=Strict\",\n ];\n\n if (options.secure) parts.push(\"Secure\");\n\n if (value === null) parts.push(\"Max-Age=0\", \"Expires=Thu, 01 Jan 1970 00:00:00 GMT\");\n else parts.push(`Max-Age=${Math.max(1, Math.floor(options.maxAgeSeconds ?? 0))}`);\n\n return parts.join(\"; \");\n}\n"],"mappings":";;;;AAQA,SAAgB,kBAAkB,QAAyB;CACzD,OAAO,SAAS,0BAA0B;AAC5C;;;;;;AAOA,SAAgB,cACd,OACA,SACQ;CACR,MAAM,QAAQ;EACZ,GAAG,kBAAkB,QAAQ,MAAM,EAAE,GAAG,SAAS;EACjD,QAAQ,QAAQ;EAChB;EACA;CACF;CAEA,IAAI,QAAQ,QAAQ,MAAM,KAAK,QAAQ;CAEvC,IAAI,UAAU,MAAM,MAAM,KAAK,aAAa,uCAAuC;CAEnF,OAAO,MAAM,KAAK,IAAI;AACxB;;AAGA,SAAgB,WAAW,QAA4B,MAAkC;CACvF,IAAI,CAAC,QAAQ,OAAO;CAEpB,KAAK,MAAM,QAAQ,OAAO,MAAM,GAAG,GAAG;EACpC,MAAM,SAAS,KAAK,QAAQ,GAAG;EAE/B,IAAI,WAAW,IAAI;EAEnB,IAAI,KAAK,MAAM,GAAG,MAAM,CAAC,CAAC,KAAK,MAAM,MAAM;GACzC,MAAM,QAAQ,KAAK,MAAM,SAAS,CAAC,CAAC,CAAC,KAAK;GAE1C,OAAO,UAAU,KAAK,SAAY;EACpC;CACF;AAGF;;AAGA,SAAgB,gBAAgB,QAAyB;CACvD,OAAO,SAAS,wBAAwB;AAC1C;;;;;;AAOA,SAAgB,YACd,OACA,SACQ;CACR,MAAM,QAAQ;EACZ,GAAG,gBAAgB,QAAQ,MAAM,EAAE,GAAG,SAAS;EAC/C,QAAQ,QAAQ;EAChB;EACA;CACF;CAEA,IAAI,QAAQ,QAAQ,MAAM,KAAK,QAAQ;CAEvC,IAAI,UAAU,MAAM,MAAM,KAAK,aAAa,uCAAuC;MAC9E,MAAM,KAAK,WAAW,KAAK,IAAI,GAAG,KAAK,MAAM,QAAQ,iBAAiB,CAAC,CAAC,GAAG;CAEhF,OAAO,MAAM,KAAK,IAAI;AACxB"}
|
|
@@ -19,6 +19,7 @@ import { registerRouteRoutes } from "../../server/route-routes.mjs";
|
|
|
19
19
|
import { registerStreamRoute } from "../../server/stream-route.mjs";
|
|
20
20
|
import { registerAuthRoutes } from "./auth-routes.mjs";
|
|
21
21
|
import { DASHBOARD_CSP, DASHBOARD_HEADERS, DOCS_CSP } from "./headers.mjs";
|
|
22
|
+
import { createDevtoolsShare } from "./share.mjs";
|
|
22
23
|
import { createHash } from "node:crypto";
|
|
23
24
|
|
|
24
25
|
//#region ../../packages/devtools/src/production/http/mount.ts
|
|
@@ -34,6 +35,8 @@ const SAFE_METHODS = /* @__PURE__ */ new Set([
|
|
|
34
35
|
]);
|
|
35
36
|
/** The routes of the opt-in API documentation pages (they keep a CSP of their own). */
|
|
36
37
|
const DOCS_PATTERNS = /* @__PURE__ */ new Set(["/docs", "/docs/swagger"]);
|
|
38
|
+
/** The grant exchange of a share link: every failure of it answers the uniform 404. */
|
|
39
|
+
const SHARE_OPEN_PATTERN = "/api/share/open";
|
|
37
40
|
/** The mail preview's HTML: framed by the dashboard, with a policy of its own. */
|
|
38
41
|
const MAIL_HTML_PATTERN = "/api/mails/:id/html";
|
|
39
42
|
/** Which tab a route belongs to: a route of a tab that is off answers the uniform 404. */
|
|
@@ -96,7 +99,8 @@ function mountProductionDevtools(server, deps) {
|
|
|
96
99
|
const prefix = production.path;
|
|
97
100
|
const cookieName = sessionCookieName(production.requireHttps);
|
|
98
101
|
const enabledTabs = new Set(deps.builtInPanels);
|
|
99
|
-
const
|
|
102
|
+
const share = production.share.enabled ? createDevtoolsShare(deps) : null;
|
|
103
|
+
const lookup = createAccessLookup(productionRouteAccess(deps.panels.map((panel) => panel.id), { share: share !== null }));
|
|
100
104
|
const streamsPerSession = /* @__PURE__ */ new Map();
|
|
101
105
|
let streamsInstance = 0;
|
|
102
106
|
let lastWarningAt = 0;
|
|
@@ -197,6 +201,19 @@ function mountProductionDevtools(server, deps) {
|
|
|
197
201
|
const rule = lookup(method, pattern);
|
|
198
202
|
const access = rule?.access ?? { type: "admin" };
|
|
199
203
|
let authenticated = null;
|
|
204
|
+
if (access.type === "share") {
|
|
205
|
+
const grant = share ? await share.authorize(request, meta) : null;
|
|
206
|
+
if (grant === null) return notFound(request, reply);
|
|
207
|
+
setDevtoolsRequestContext(request, {
|
|
208
|
+
client,
|
|
209
|
+
meta,
|
|
210
|
+
rule,
|
|
211
|
+
pattern,
|
|
212
|
+
authenticated: null,
|
|
213
|
+
share: grant
|
|
214
|
+
});
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
200
217
|
if (access.type !== "public") {
|
|
201
218
|
try {
|
|
202
219
|
authenticated = await auth.authenticate(readCookie(request.headers.cookie, cookieName));
|
|
@@ -228,7 +245,10 @@ function mountProductionDevtools(server, deps) {
|
|
|
228
245
|
if (authenticated === null) return notFound(request, reply);
|
|
229
246
|
throw new DevtoolsApiError("csrf.invalid");
|
|
230
247
|
}
|
|
231
|
-
if (hasBody(request) && !isJson(request))
|
|
248
|
+
if (hasBody(request) && !isJson(request)) {
|
|
249
|
+
if (pattern === SHARE_OPEN_PATTERN) return notFound(request, reply);
|
|
250
|
+
throw new DevtoolsApiError("input.invalid");
|
|
251
|
+
}
|
|
232
252
|
if (authenticated !== null) {
|
|
233
253
|
const header = request.headers[DEVTOOLS_CSRF_HEADER];
|
|
234
254
|
if (!auth.verifyCsrf(authenticated, Array.isArray(header) ? header[0] : header)) throw new DevtoolsApiError("csrf.invalid");
|
|
@@ -264,6 +284,7 @@ function mountProductionDevtools(server, deps) {
|
|
|
264
284
|
});
|
|
265
285
|
});
|
|
266
286
|
instance.setErrorHandler((error, request, reply) => {
|
|
287
|
+
if (devtoolsRequestContext(request)?.pattern === SHARE_OPEN_PATTERN) return notFound(request, reply);
|
|
267
288
|
if (error instanceof DevtoolsApiError) return reply.code(error.statusCode).send(error.toBody());
|
|
268
289
|
const status = error.statusCode;
|
|
269
290
|
if (status !== void 0 && status >= 400 && status < 500) return reply.code(status).send(error.code?.startsWith("FST_ERR_") ? new DevtoolsApiError("input.invalid").toBody() : { error: error.message });
|
|
@@ -287,7 +308,8 @@ function mountProductionDevtools(server, deps) {
|
|
|
287
308
|
registerInsightsRoutes(instance, routes);
|
|
288
309
|
registerLogRoutes(instance, routes);
|
|
289
310
|
registerShapeExplainRoute(instance, routes);
|
|
290
|
-
registerPanelRoutes(instance, deps.panels);
|
|
311
|
+
registerPanelRoutes(instance, deps.panels, { notFound });
|
|
312
|
+
share?.register(instance, notFound);
|
|
291
313
|
if (enabledTabs.has("mail")) registerMailRoutes(instance, routes);
|
|
292
314
|
if (enabledTabs.has("ai") || enabledTabs.has("agents")) registerAiRoutes(instance, routes);
|
|
293
315
|
if (enabledTabs.has("api")) registerOpenApiRoutes(instance, routes);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mount.mjs","names":[],"sources":["../../../../../../../../../packages/devtools/src/production/http/mount.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport { listPanelInfos } from \"../../panels\";\nimport { registerAiRoutes } from \"../../server/ai-routes\";\nimport { registerShapeExplainRoute } from \"../../server/explain-route\";\nimport { registerInsightsRoutes } from \"../../server/insights-routes\";\nimport { registerLogRoutes } from \"../../server/log-routes\";\nimport { registerMailRoutes } from \"../../server/mail-routes\";\nimport { registerOpenApiRoutes } from \"../../server/openapi-routes\";\nimport { registerPanelRoutes } from \"../../server/panel-routes\";\nimport { registerRequestsRoutes } from \"../../server/requests-routes\";\nimport { registerRouteRoutes } from \"../../server/route-routes\";\nimport { registerStreamRoute } from \"../../server/stream-route\";\nimport type { DevtoolsStreamSession, MountDevtoolsRoutesDeps } from \"../../server/types\";\nimport { registerUiAssets } from \"../../server/ui-assets\";\nimport type { DevtoolsAuthenticated, DevtoolsRequestMeta } from \"../auth/types\";\nimport { DevtoolsApiError, createErrorRef, DEVTOOLS_ERROR_MESSAGES } from \"../errors\";\nimport { createAccessLookup, productionRouteAccess } from \"./access\";\nimport { registerAuthRoutes } from \"./auth-routes\";\nimport { resolveClient } from \"./client\";\nimport { setDevtoolsRequestContext, devtoolsRequestContext } from \"./context\";\nimport { readCookie, sessionCookieName } from \"./cookie\";\nimport { DASHBOARD_CSP, DASHBOARD_HEADERS, DOCS_CSP } from \"./headers\";\nimport { DEVTOOLS_CSRF_HEADER } from \"./constants\";\nimport { ipMatches } from \"./ip\";\nimport type { DevtoolsRouteAccess, MountProductionDevtoolsDeps } from \"./types\";\n\n/** Open live streams a session may hold, and an instance may serve. */\nconst MAX_STREAMS_PER_SESSION = 3;\nconst MAX_STREAMS_PER_INSTANCE = 50;\n\nconst MAX_USER_AGENT = 200;\n\n/** Methods that never change state. */\nconst SAFE_METHODS = new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\n\n/** The routes of the opt-in API documentation pages (they keep a CSP of their own). */\nconst DOCS_PATTERNS = new Set([\"/docs\", \"/docs/swagger\"]);\n\n/** The mail preview's HTML: framed by the dashboard, with a policy of its own. */\nconst MAIL_HTML_PATTERN = \"/api/mails/:id/html\";\n\n/** Which tab a route belongs to: a route of a tab that is off answers the uniform 404. */\nconst TAB_OF_ROUTE: readonly (readonly [prefix: string, tab: string])[] = [\n [\"/api/resources\", \"resources\"],\n [\"/api/queries\", \"queries\"],\n [\"/api/routes/stats\", \"routes\"],\n [\"/api/routes\", \"routes\"],\n [\"/api/health\", \"health\"],\n [\"/api/errors\", \"errors\"],\n [\"/api/jobs\", \"jobs\"],\n [\"/api/logs\", \"logs\"],\n [\"/api/requests\", \"requests\"],\n [\"/api/mails\", \"mail\"],\n [\"/api/ai/agent-runs\", \"agents\"],\n [\"/api/ai\", \"ai\"],\n [\"/api/openapi.json\", \"api\"],\n [\"/api/postman.json\", \"api\"],\n [\"/docs\", \"api\"],\n];\n\nfunction tabOf(pattern: string): string | undefined {\n return TAB_OF_ROUTE.find(\n ([prefix]) => pattern === prefix || pattern.startsWith(`${prefix}/`),\n )?.[1];\n}\n\nfunction tokenHash(token: string): string {\n return createHash(\"sha256\").update(token).digest(\"hex\");\n}\n\n/** Requests that were answered with the uniform 404: they get none of the dashboard's headers. */\nconst uniformNotFound = new WeakSet<FastifyRequest>();\n\n/**\n * The origin the browser must send for an unsafe request: `production.origin`,\n * else the scheme and host the request was addressed to.\n */\nfunction originAllowed(request: FastifyRequest, expected: string): boolean {\n const origin = request.headers.origin;\n const site = request.headers[\"sec-fetch-site\"];\n\n if (site !== undefined && site !== \"same-origin\") return false;\n\n if (origin !== undefined) return origin.toLowerCase() === expected.toLowerCase();\n\n // No Origin header: a same-origin fetch from an older browser. Accept it only with the fetch metadata that proves it.\n return site === \"same-origin\";\n}\n\nfunction hasBody(request: FastifyRequest): boolean {\n const length = request.headers[\"content-length\"];\n\n return (\n (length !== undefined && length !== \"0\") || request.headers[\"transfer-encoding\"] !== undefined\n );\n}\n\nfunction isJson(request: FastifyRequest): boolean {\n return /^application\\/json\\s*(;|$)/i.test(request.headers[\"content-type\"] ?? \"\");\n}\n\nfunction sessionAccessOk(\n access: Exclude<DevtoolsRouteAccess, { type: \"public\" }>,\n stage: string,\n): boolean {\n if (stage === \"active\") return true;\n\n return access.type === \"pending\" && (access.stages as readonly string[]).includes(stage);\n}\n\n/**\n * Mounts the production monitor under `production.path` in one encapsulated\n * Fastify context: the gate (uniform 404, HTTPS, allowed IPs, open state),\n * session and role checks from the access table, CSRF and origin checks,\n * security headers and CORS stripping, the auth/account/admin routes, and\n * the shared data routes of the enabled tabs.\n */\nexport function mountProductionDevtools(\n server: FastifyInstance,\n deps: MountProductionDevtoolsDeps,\n): void {\n const { production, auth, state, store } = deps;\n const prefix = production.path;\n const cookieName = sessionCookieName(production.requireHttps);\n const enabledTabs = new Set(deps.builtInPanels);\n const lookup = createAccessLookup(productionRouteAccess(deps.panels.map((panel) => panel.id)));\n const streamsPerSession = new Map<string, number>();\n let streamsInstance = 0;\n let lastWarningAt = 0;\n\n const warn = (message: string): void => {\n // At most one line a minute: a database outage must not flood the log.\n const now = Date.now();\n\n if (now - lastWarningAt < 60_000) return;\n\n lastWarningAt = now;\n deps.warn?.(message);\n };\n\n const notFound = (request: FastifyRequest, reply: FastifyReply): FastifyReply => {\n uniformNotFound.add(request);\n\n // The app's own not-found handler answers, so the reply is the one any unknown URL gets.\n reply.callNotFound();\n\n // Returning the reply is what stops an async hook's lifecycle.\n return reply;\n };\n\n const streamSession = async (request: FastifyRequest): Promise<DevtoolsStreamSession> => {\n const authenticated = devtoolsRequestContext(request)?.authenticated;\n\n if (!authenticated) throw new Error(\"A dashboard stream was opened without a session.\");\n\n const sessionId = authenticated.session.id;\n const token = readCookie(request.headers.cookie, cookieName);\n const open = streamsPerSession.get(sessionId) ?? 0;\n\n if (open >= MAX_STREAMS_PER_SESSION || streamsInstance >= MAX_STREAMS_PER_INSTANCE) {\n throw new DevtoolsApiError(\"stream.too-many\");\n }\n\n streamsPerSession.set(sessionId, open + 1);\n streamsInstance += 1;\n\n let released = false;\n\n return {\n role: authenticated.account.role,\n logLevels: production.logLevels,\n headers: DASHBOARD_HEADERS,\n // Reads the session without touching `lastSeenAt`: a stream left open must not keep the session alive.\n async revalidate() {\n if (token === undefined || !(await state.isOpen())) return false;\n\n const session = await store.sessions.findByTokenHash(tokenHash(token));\n const now = Date.now();\n\n if (\n session === null ||\n session.stage !== \"active\" ||\n now >= session.expiresAt ||\n now - session.lastSeenAt >= production.session.idleMinutes * 60_000\n ) {\n return false;\n }\n\n return (await store.accounts.findById(session.accountId)) !== null;\n },\n release() {\n if (released) return;\n\n released = true;\n streamsInstance -= 1;\n\n const left = (streamsPerSession.get(sessionId) ?? 1) - 1;\n\n if (left <= 0) streamsPerSession.delete(sessionId);\n else streamsPerSession.set(sessionId, left);\n },\n };\n };\n\n // The route deps the shared route files read: the development deps, completed.\n const routes: MountDevtoolsRoutesDeps = {\n ...deps.routes,\n mode: \"production\",\n isDevelopment: () => false,\n instance: deps.instance,\n insights: deps.insights,\n collector: deps.routes.collector ?? deps.capture.collector,\n requests: deps.routes.requests ?? deps.capture.requests,\n explainShape: deps.routes.explainShape ?? ((shapeId) => deps.capture.explain(shapeId)),\n builtInPanels: deps.builtInPanels,\n streamSession,\n };\n\n server.register(\n async (instance) => {\n // ---- The gate -------------------------------------------------------\n instance.addHook(\"onRequest\", async (request, reply) => {\n let open: boolean;\n\n try {\n open = await state.isOpen();\n } catch (error) {\n // Fail closed: when the state cannot be read the dashboard does not answer.\n warn(\n `The devtools dashboard state could not be read and the dashboard is closed: ${error instanceof Error ? error.message : String(error)}`,\n );\n open = false;\n }\n\n if (!open) return notFound(request, reply);\n\n const client = resolveClient(request, production.trustedProxies);\n\n if (production.requireHttps && client.proto !== \"https\") return notFound(request, reply);\n\n if (production.allowedIps.length > 0 && !ipMatches(client.ip, production.allowedIps)) {\n return notFound(request, reply);\n }\n\n const userAgent = request.headers[\"user-agent\"];\n const expectedOrigin = production.origin ?? `${client.proto}://${client.host}`;\n const meta: DevtoolsRequestMeta = {\n ip: client.ip,\n userAgent: typeof userAgent === \"string\" ? userAgent.slice(0, MAX_USER_AGENT) : null,\n origin: expectedOrigin,\n hostname: client.hostname,\n };\n\n const routeUrl = request.routeOptions.url ?? \"\";\n const relative = routeUrl.startsWith(prefix) ? routeUrl.slice(prefix.length) : routeUrl;\n // The shell is registered once for both `<path>` and `<path>/`.\n const pattern = relative === \"\" ? \"/\" : relative;\n const method = request.method;\n\n // The bare path (no trailing slash) redirects to the shell's address. The\n // address as sent: core's server drops a trailing slash before routing,\n // so the rewritten URL of `<path>/` is the bare path too.\n const sent = request.originalUrl ?? request.raw.url ?? \"\";\n\n if (sent.split(\"?\")[0] === prefix) {\n setDevtoolsRequestContext(request, {\n client,\n meta,\n rule: undefined,\n pattern,\n authenticated: null,\n });\n\n if (method !== \"GET\" && method !== \"HEAD\") return notFound(request, reply);\n\n const search = sent.includes(\"?\") ? `?${sent.split(\"?\").slice(1).join(\"?\")}` : \"\";\n\n return reply.redirect(`${prefix}/${search}`, 308);\n }\n\n const tab = tabOf(pattern);\n\n if (tab !== undefined && !enabledTabs.has(tab)) return notFound(request, reply);\n\n const rule = lookup(method, pattern);\n const access: DevtoolsRouteAccess = rule?.access ?? { type: \"admin\" };\n let authenticated: DevtoolsAuthenticated | null = null;\n\n if (access.type !== \"public\") {\n try {\n authenticated = await auth.authenticate(readCookie(request.headers.cookie, cookieName));\n } catch (error) {\n warn(\n `The devtools session could not be checked and the request was refused: ${error instanceof Error ? error.message : String(error)}`,\n );\n\n return notFound(request, reply);\n }\n\n if (authenticated === null || !sessionAccessOk(access, authenticated.stage)) {\n return notFound(request, reply);\n }\n\n if (access.type === \"admin\" && authenticated.account.role !== \"admin\") {\n setDevtoolsRequestContext(request, { client, meta, rule, pattern, authenticated });\n throw new DevtoolsApiError(\"role.forbidden\");\n }\n }\n\n setDevtoolsRequestContext(request, { client, meta, rule, pattern, authenticated });\n\n if (SAFE_METHODS.has(method)) return;\n\n if (!originAllowed(request, expectedOrigin)) {\n if (authenticated === null) return notFound(request, reply);\n\n throw new DevtoolsApiError(\"csrf.invalid\");\n }\n\n if (hasBody(request) && !isJson(request)) throw new DevtoolsApiError(\"input.invalid\");\n\n if (authenticated !== null) {\n const header = request.headers[DEVTOOLS_CSRF_HEADER];\n\n if (!auth.verifyCsrf(authenticated, Array.isArray(header) ? header[0] : header)) {\n throw new DevtoolsApiError(\"csrf.invalid\");\n }\n }\n });\n\n // ---- Headers --------------------------------------------------------\n instance.addHook(\"onSend\", async (request, reply, payload) => {\n // The uniform 404 must look like any other 404 of the app.\n if (uniformNotFound.has(request)) return payload;\n\n for (const name of Object.keys(reply.getHeaders())) {\n if (name.startsWith(\"access-control-\")) reply.removeHeader(name);\n }\n\n reply.headers(DASHBOARD_HEADERS);\n\n const pattern = devtoolsRequestContext(request)?.pattern ?? \"\";\n\n // The mail preview is the one page the dashboard frames, from its own origin, and it sends its own policy.\n if (pattern === MAIL_HTML_PATTERN) {\n reply.header(\"X-Frame-Options\", \"SAMEORIGIN\");\n\n return payload;\n }\n\n // The API docs pages are shown in a frame by the dashboard's API tab.\n if (DOCS_PATTERNS.has(pattern)) reply.header(\"X-Frame-Options\", \"SAMEORIGIN\");\n\n // Always the dashboard's policy: the app's own (core's security headers set one on every response) is not\n // written for this page and must not replace it.\n if (String(reply.getHeader(\"content-type\") ?? \"\").startsWith(\"text/html\")) {\n reply.header(\n \"Content-Security-Policy\",\n DOCS_PATTERNS.has(pattern) ? DOCS_CSP : DASHBOARD_CSP,\n );\n }\n\n return payload;\n });\n\n // ---- Audit ----------------------------------------------------------\n instance.addHook(\"onResponse\", async (request, reply) => {\n const context = devtoolsRequestContext(request);\n const type = context?.rule?.audit;\n\n if (!context || !type || reply.statusCode < 200 || reply.statusCode > 299) return;\n\n const params = (request.params ?? {}) as Record<string, string | undefined>;\n const detail: Record<string, string | number | boolean | null> =\n type === \"explain.run\"\n ? { shapeId: params.shapeId ?? null }\n : type === \"panel.action\"\n ? {\n panel: context.pattern.split(\"/\")[2] ?? null,\n method: request.method,\n route: context.pattern,\n }\n : {};\n\n await auth.audit(type, { auth: context.authenticated, meta: context.meta, detail });\n });\n\n // ---- Errors ---------------------------------------------------------\n instance.setErrorHandler(\n (error: Error & { statusCode?: number; code?: string }, request, reply) => {\n if (error instanceof DevtoolsApiError) {\n return reply.code(error.statusCode).send(error.toBody());\n }\n\n const status = error.statusCode;\n\n // The request itself was wrong (bad JSON, too large): say so in the dashboard's own shape.\n if (status !== undefined && status >= 400 && status < 500) {\n return reply\n .code(status)\n .send(\n error.code?.startsWith(\"FST_ERR_\")\n ? new DevtoolsApiError(\"input.invalid\").toBody()\n : { error: error.message },\n );\n }\n\n const ref = createErrorRef();\n\n // Never rate limited: the reference the browser shows must always be findable in the log. The route is\n // written relative to the dashboard path, which never reaches the log.\n deps.warn?.(\n `Devtools dashboard error ${ref} on ${request.method} ${devtoolsRequestContext(request)?.pattern ?? \"(dashboard route)\"}: ${error.message}`,\n );\n request.log.error({ ref, err: error }, \"devtools dashboard error\");\n\n return reply.code(500).send({\n error: DEVTOOLS_ERROR_MESSAGES[\"server.error\"],\n code: \"server.error\",\n ref,\n });\n },\n );\n\n // ---- Routes ---------------------------------------------------------\n registerUiAssets(instance, { notFound });\n registerAuthRoutes(instance, deps);\n\n instance.get(\"/api/panels\", async () => listPanelInfos(deps.panels, deps.builtInPanels));\n\n registerRequestsRoutes(instance, routes);\n registerRouteRoutes(instance, routes);\n registerInsightsRoutes(instance, routes);\n registerLogRoutes(instance, routes);\n registerShapeExplainRoute(instance, routes);\n registerPanelRoutes(instance, deps.panels);\n\n if (enabledTabs.has(\"mail\")) registerMailRoutes(instance, routes);\n if (enabledTabs.has(\"ai\") || enabledTabs.has(\"agents\")) registerAiRoutes(instance, routes);\n if (enabledTabs.has(\"api\")) registerOpenApiRoutes(instance, routes);\n\n registerStreamRoute(instance, routes);\n },\n { prefix },\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,MAAM,0BAA0B;AAChC,MAAM,2BAA2B;AAEjC,MAAM,iBAAiB;;AAGvB,MAAM,+BAAe,IAAI,IAAI;CAAC;CAAO;CAAQ;AAAS,CAAC;;AAGvD,MAAM,gCAAgB,IAAI,IAAI,CAAC,SAAS,eAAe,CAAC;;AAGxD,MAAM,oBAAoB;;AAG1B,MAAM,eAAoE;CACxE,CAAC,kBAAkB,WAAW;CAC9B,CAAC,gBAAgB,SAAS;CAC1B,CAAC,qBAAqB,QAAQ;CAC9B,CAAC,eAAe,QAAQ;CACxB,CAAC,eAAe,QAAQ;CACxB,CAAC,eAAe,QAAQ;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EAEvF,uBAAuB,UAAU,MAAM;EACvC,oBAAoB,UAAU,MAAM;EACpC,uBAAuB,UAAU,MAAM;EACvC,kBAAkB,UAAU,MAAM;EAClC,0BAA0B,UAAU,MAAM;EAC1C,oBAAoB,UAAU,KAAK,MAAM;EAEzC,IAAI,YAAY,IAAI,MAAM,GAAG,mBAAmB,UAAU,MAAM;EAChE,IAAI,YAAY,IAAI,IAAI,KAAK,YAAY,IAAI,QAAQ,GAAG,iBAAiB,UAAU,MAAM;EACzF,IAAI,YAAY,IAAI,KAAK,GAAG,sBAAsB,UAAU,MAAM;EAElE,oBAAoB,UAAU,MAAM;CACtC,GACA,EAAE,OAAO,CACX;AACF"}
|
|
1
|
+
{"version":3,"file":"mount.mjs","names":[],"sources":["../../../../../../../../../packages/devtools/src/production/http/mount.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport { listPanelInfos } from \"../../panels\";\nimport { registerAiRoutes } from \"../../server/ai-routes\";\nimport { registerShapeExplainRoute } from \"../../server/explain-route\";\nimport { registerInsightsRoutes } from \"../../server/insights-routes\";\nimport { registerLogRoutes } from \"../../server/log-routes\";\nimport { registerMailRoutes } from \"../../server/mail-routes\";\nimport { registerOpenApiRoutes } from \"../../server/openapi-routes\";\nimport { registerPanelRoutes } from \"../../server/panel-routes\";\nimport { registerRequestsRoutes } from \"../../server/requests-routes\";\nimport { registerRouteRoutes } from \"../../server/route-routes\";\nimport { registerStreamRoute } from \"../../server/stream-route\";\nimport type { DevtoolsStreamSession, MountDevtoolsRoutesDeps } from \"../../server/types\";\nimport { registerUiAssets } from \"../../server/ui-assets\";\nimport type { DevtoolsAuthenticated, DevtoolsRequestMeta } from \"../auth/types\";\nimport { DevtoolsApiError, createErrorRef, DEVTOOLS_ERROR_MESSAGES } from \"../errors\";\nimport { createAccessLookup, productionRouteAccess } from \"./access\";\nimport { registerAuthRoutes } from \"./auth-routes\";\nimport { resolveClient } from \"./client\";\nimport { setDevtoolsRequestContext, devtoolsRequestContext } from \"./context\";\nimport { readCookie, sessionCookieName } from \"./cookie\";\nimport { DASHBOARD_CSP, DASHBOARD_HEADERS, DOCS_CSP } from \"./headers\";\nimport { DEVTOOLS_CSRF_HEADER } from \"./constants\";\nimport { createDevtoolsShare } from \"./share\";\nimport { ipMatches } from \"./ip\";\nimport type { DevtoolsRouteAccess, MountProductionDevtoolsDeps } from \"./types\";\n\n/** Open live streams a session may hold, and an instance may serve. */\nconst MAX_STREAMS_PER_SESSION = 3;\nconst MAX_STREAMS_PER_INSTANCE = 50;\n\nconst MAX_USER_AGENT = 200;\n\n/** Methods that never change state. */\nconst SAFE_METHODS = new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\n\n/** The routes of the opt-in API documentation pages (they keep a CSP of their own). */\nconst DOCS_PATTERNS = new Set([\"/docs\", \"/docs/swagger\"]);\n\n/** The grant exchange of a share link: every failure of it answers the uniform 404. */\nconst SHARE_OPEN_PATTERN = \"/api/share/open\";\n\n/** The mail preview's HTML: framed by the dashboard, with a policy of its own. */\nconst MAIL_HTML_PATTERN = \"/api/mails/:id/html\";\n\n/** Which tab a route belongs to: a route of a tab that is off answers the uniform 404. */\nconst TAB_OF_ROUTE: readonly (readonly [prefix: string, tab: string])[] = [\n [\"/api/resources\", \"resources\"],\n [\"/api/queries\", \"queries\"],\n [\"/api/routes/stats\", \"routes\"],\n [\"/api/routes\", \"routes\"],\n [\"/api/health\", \"health\"],\n [\"/api/errors\", \"errors\"],\n [\"/api/jobs\", \"jobs\"],\n [\"/api/logs\", \"logs\"],\n [\"/api/requests\", \"requests\"],\n [\"/api/mails\", \"mail\"],\n [\"/api/ai/agent-runs\", \"agents\"],\n [\"/api/ai\", \"ai\"],\n [\"/api/openapi.json\", \"api\"],\n [\"/api/postman.json\", \"api\"],\n [\"/docs\", \"api\"],\n];\n\nfunction tabOf(pattern: string): string | undefined {\n return TAB_OF_ROUTE.find(\n ([prefix]) => pattern === prefix || pattern.startsWith(`${prefix}/`),\n )?.[1];\n}\n\nfunction tokenHash(token: string): string {\n return createHash(\"sha256\").update(token).digest(\"hex\");\n}\n\n/** Requests that were answered with the uniform 404: they get none of the dashboard's headers. */\nconst uniformNotFound = new WeakSet<FastifyRequest>();\n\n/**\n * The origin the browser must send for an unsafe request: `production.origin`,\n * else the scheme and host the request was addressed to.\n */\nfunction originAllowed(request: FastifyRequest, expected: string): boolean {\n const origin = request.headers.origin;\n const site = request.headers[\"sec-fetch-site\"];\n\n if (site !== undefined && site !== \"same-origin\") return false;\n\n if (origin !== undefined) return origin.toLowerCase() === expected.toLowerCase();\n\n // No Origin header: a same-origin fetch from an older browser. Accept it only with the fetch metadata that proves it.\n return site === \"same-origin\";\n}\n\nfunction hasBody(request: FastifyRequest): boolean {\n const length = request.headers[\"content-length\"];\n\n return (\n (length !== undefined && length !== \"0\") || request.headers[\"transfer-encoding\"] !== undefined\n );\n}\n\nfunction isJson(request: FastifyRequest): boolean {\n return /^application\\/json\\s*(;|$)/i.test(request.headers[\"content-type\"] ?? \"\");\n}\n\nfunction sessionAccessOk(\n access: Exclude<DevtoolsRouteAccess, { type: \"public\" }>,\n stage: string,\n): boolean {\n if (stage === \"active\") return true;\n\n return access.type === \"pending\" && (access.stages as readonly string[]).includes(stage);\n}\n\n/**\n * Mounts the production monitor under `production.path` in one encapsulated\n * Fastify context: the gate (uniform 404, HTTPS, allowed IPs, open state),\n * session and role checks from the access table, CSRF and origin checks,\n * security headers and CORS stripping, the auth/account/admin routes, and\n * the shared data routes of the enabled tabs.\n */\nexport function mountProductionDevtools(\n server: FastifyInstance,\n deps: MountProductionDevtoolsDeps,\n): void {\n const { production, auth, state, store } = deps;\n const prefix = production.path;\n const cookieName = sessionCookieName(production.requireHttps);\n const enabledTabs = new Set(deps.builtInPanels);\n const share = production.share.enabled ? createDevtoolsShare(deps) : null;\n const lookup = createAccessLookup(\n productionRouteAccess(\n deps.panels.map((panel) => panel.id),\n { share: share !== null },\n ),\n );\n const streamsPerSession = new Map<string, number>();\n let streamsInstance = 0;\n let lastWarningAt = 0;\n\n const warn = (message: string): void => {\n // At most one line a minute: a database outage must not flood the log.\n const now = Date.now();\n\n if (now - lastWarningAt < 60_000) return;\n\n lastWarningAt = now;\n deps.warn?.(message);\n };\n\n const notFound = (request: FastifyRequest, reply: FastifyReply): FastifyReply => {\n uniformNotFound.add(request);\n\n // The app's own not-found handler answers, so the reply is the one any unknown URL gets.\n reply.callNotFound();\n\n // Returning the reply is what stops an async hook's lifecycle.\n return reply;\n };\n\n const streamSession = async (request: FastifyRequest): Promise<DevtoolsStreamSession> => {\n const authenticated = devtoolsRequestContext(request)?.authenticated;\n\n if (!authenticated) throw new Error(\"A dashboard stream was opened without a session.\");\n\n const sessionId = authenticated.session.id;\n const token = readCookie(request.headers.cookie, cookieName);\n const open = streamsPerSession.get(sessionId) ?? 0;\n\n if (open >= MAX_STREAMS_PER_SESSION || streamsInstance >= MAX_STREAMS_PER_INSTANCE) {\n throw new DevtoolsApiError(\"stream.too-many\");\n }\n\n streamsPerSession.set(sessionId, open + 1);\n streamsInstance += 1;\n\n let released = false;\n\n return {\n role: authenticated.account.role,\n logLevels: production.logLevels,\n headers: DASHBOARD_HEADERS,\n // Reads the session without touching `lastSeenAt`: a stream left open must not keep the session alive.\n async revalidate() {\n if (token === undefined || !(await state.isOpen())) return false;\n\n const session = await store.sessions.findByTokenHash(tokenHash(token));\n const now = Date.now();\n\n if (\n session === null ||\n session.stage !== \"active\" ||\n now >= session.expiresAt ||\n now - session.lastSeenAt >= production.session.idleMinutes * 60_000\n ) {\n return false;\n }\n\n return (await store.accounts.findById(session.accountId)) !== null;\n },\n release() {\n if (released) return;\n\n released = true;\n streamsInstance -= 1;\n\n const left = (streamsPerSession.get(sessionId) ?? 1) - 1;\n\n if (left <= 0) streamsPerSession.delete(sessionId);\n else streamsPerSession.set(sessionId, left);\n },\n };\n };\n\n // The route deps the shared route files read: the development deps, completed.\n const routes: MountDevtoolsRoutesDeps = {\n ...deps.routes,\n mode: \"production\",\n isDevelopment: () => false,\n instance: deps.instance,\n insights: deps.insights,\n collector: deps.routes.collector ?? deps.capture.collector,\n requests: deps.routes.requests ?? deps.capture.requests,\n explainShape: deps.routes.explainShape ?? ((shapeId) => deps.capture.explain(shapeId)),\n builtInPanels: deps.builtInPanels,\n streamSession,\n };\n\n server.register(\n async (instance) => {\n // ---- The gate -------------------------------------------------------\n instance.addHook(\"onRequest\", async (request, reply) => {\n let open: boolean;\n\n try {\n open = await state.isOpen();\n } catch (error) {\n // Fail closed: when the state cannot be read the dashboard does not answer.\n warn(\n `The devtools dashboard state could not be read and the dashboard is closed: ${error instanceof Error ? error.message : String(error)}`,\n );\n open = false;\n }\n\n if (!open) return notFound(request, reply);\n\n const client = resolveClient(request, production.trustedProxies);\n\n if (production.requireHttps && client.proto !== \"https\") return notFound(request, reply);\n\n if (production.allowedIps.length > 0 && !ipMatches(client.ip, production.allowedIps)) {\n return notFound(request, reply);\n }\n\n const userAgent = request.headers[\"user-agent\"];\n const expectedOrigin = production.origin ?? `${client.proto}://${client.host}`;\n const meta: DevtoolsRequestMeta = {\n ip: client.ip,\n userAgent: typeof userAgent === \"string\" ? userAgent.slice(0, MAX_USER_AGENT) : null,\n origin: expectedOrigin,\n hostname: client.hostname,\n };\n\n const routeUrl = request.routeOptions.url ?? \"\";\n const relative = routeUrl.startsWith(prefix) ? routeUrl.slice(prefix.length) : routeUrl;\n // The shell is registered once for both `<path>` and `<path>/`.\n const pattern = relative === \"\" ? \"/\" : relative;\n const method = request.method;\n\n // The bare path (no trailing slash) redirects to the shell's address. The\n // address as sent: core's server drops a trailing slash before routing,\n // so the rewritten URL of `<path>/` is the bare path too.\n const sent = request.originalUrl ?? request.raw.url ?? \"\";\n\n if (sent.split(\"?\")[0] === prefix) {\n setDevtoolsRequestContext(request, {\n client,\n meta,\n rule: undefined,\n pattern,\n authenticated: null,\n });\n\n if (method !== \"GET\" && method !== \"HEAD\") return notFound(request, reply);\n\n const search = sent.includes(\"?\") ? `?${sent.split(\"?\").slice(1).join(\"?\")}` : \"\";\n\n return reply.redirect(`${prefix}/${search}`, 308);\n }\n\n const tab = tabOf(pattern);\n\n if (tab !== undefined && !enabledTabs.has(tab)) return notFound(request, reply);\n\n const rule = lookup(method, pattern);\n const access: DevtoolsRouteAccess = rule?.access ?? { type: \"admin\" };\n let authenticated: DevtoolsAuthenticated | null = null;\n\n // A share link has no account: its cookie grants one panel's shared view and nothing else.\n if (access.type === \"share\") {\n const grant = share ? await share.authorize(request, meta) : null;\n\n if (grant === null) return notFound(request, reply);\n\n setDevtoolsRequestContext(request, {\n client,\n meta,\n rule,\n pattern,\n authenticated: null,\n share: grant,\n });\n\n return;\n }\n\n if (access.type !== \"public\") {\n try {\n authenticated = await auth.authenticate(readCookie(request.headers.cookie, cookieName));\n } catch (error) {\n warn(\n `The devtools session could not be checked and the request was refused: ${error instanceof Error ? error.message : String(error)}`,\n );\n\n return notFound(request, reply);\n }\n\n if (authenticated === null || !sessionAccessOk(access, authenticated.stage)) {\n return notFound(request, reply);\n }\n\n if (access.type === \"admin\" && authenticated.account.role !== \"admin\") {\n setDevtoolsRequestContext(request, { client, meta, rule, pattern, authenticated });\n throw new DevtoolsApiError(\"role.forbidden\");\n }\n }\n\n setDevtoolsRequestContext(request, { client, meta, rule, pattern, authenticated });\n\n if (SAFE_METHODS.has(method)) return;\n\n if (!originAllowed(request, expectedOrigin)) {\n if (authenticated === null) return notFound(request, reply);\n\n throw new DevtoolsApiError(\"csrf.invalid\");\n }\n\n if (hasBody(request) && !isJson(request)) {\n if (pattern === SHARE_OPEN_PATTERN) return notFound(request, reply);\n\n throw new DevtoolsApiError(\"input.invalid\");\n }\n\n if (authenticated !== null) {\n const header = request.headers[DEVTOOLS_CSRF_HEADER];\n\n if (!auth.verifyCsrf(authenticated, Array.isArray(header) ? header[0] : header)) {\n throw new DevtoolsApiError(\"csrf.invalid\");\n }\n }\n });\n\n // ---- Headers --------------------------------------------------------\n instance.addHook(\"onSend\", async (request, reply, payload) => {\n // The uniform 404 must look like any other 404 of the app.\n if (uniformNotFound.has(request)) return payload;\n\n for (const name of Object.keys(reply.getHeaders())) {\n if (name.startsWith(\"access-control-\")) reply.removeHeader(name);\n }\n\n reply.headers(DASHBOARD_HEADERS);\n\n const pattern = devtoolsRequestContext(request)?.pattern ?? \"\";\n\n // The mail preview is the one page the dashboard frames, from its own origin, and it sends its own policy.\n if (pattern === MAIL_HTML_PATTERN) {\n reply.header(\"X-Frame-Options\", \"SAMEORIGIN\");\n\n return payload;\n }\n\n // The API docs pages are shown in a frame by the dashboard's API tab.\n if (DOCS_PATTERNS.has(pattern)) reply.header(\"X-Frame-Options\", \"SAMEORIGIN\");\n\n // Always the dashboard's policy: the app's own (core's security headers set one on every response) is not\n // written for this page and must not replace it.\n if (String(reply.getHeader(\"content-type\") ?? \"\").startsWith(\"text/html\")) {\n reply.header(\n \"Content-Security-Policy\",\n DOCS_PATTERNS.has(pattern) ? DOCS_CSP : DASHBOARD_CSP,\n );\n }\n\n return payload;\n });\n\n // ---- Audit ----------------------------------------------------------\n instance.addHook(\"onResponse\", async (request, reply) => {\n const context = devtoolsRequestContext(request);\n const type = context?.rule?.audit;\n\n if (!context || !type || reply.statusCode < 200 || reply.statusCode > 299) return;\n\n const params = (request.params ?? {}) as Record<string, string | undefined>;\n const detail: Record<string, string | number | boolean | null> =\n type === \"explain.run\"\n ? { shapeId: params.shapeId ?? null }\n : type === \"panel.action\"\n ? {\n panel: context.pattern.split(\"/\")[2] ?? null,\n method: request.method,\n route: context.pattern,\n }\n : {};\n\n await auth.audit(type, { auth: context.authenticated, meta: context.meta, detail });\n });\n\n // ---- Errors ---------------------------------------------------------\n instance.setErrorHandler(\n (error: Error & { statusCode?: number; code?: string }, request, reply) => {\n // A malformed grant exchange (bad JSON, too large) answers like any unknown URL.\n if (devtoolsRequestContext(request)?.pattern === SHARE_OPEN_PATTERN) {\n return notFound(request, reply);\n }\n\n if (error instanceof DevtoolsApiError) {\n return reply.code(error.statusCode).send(error.toBody());\n }\n\n const status = error.statusCode;\n\n // The request itself was wrong (bad JSON, too large): say so in the dashboard's own shape.\n if (status !== undefined && status >= 400 && status < 500) {\n return reply\n .code(status)\n .send(\n error.code?.startsWith(\"FST_ERR_\")\n ? new DevtoolsApiError(\"input.invalid\").toBody()\n : { error: error.message },\n );\n }\n\n const ref = createErrorRef();\n\n // Never rate limited: the reference the browser shows must always be findable in the log. The route is\n // written relative to the dashboard path, which never reaches the log.\n deps.warn?.(\n `Devtools dashboard error ${ref} on ${request.method} ${devtoolsRequestContext(request)?.pattern ?? \"(dashboard route)\"}: ${error.message}`,\n );\n request.log.error({ ref, err: error }, \"devtools dashboard error\");\n\n return reply.code(500).send({\n error: DEVTOOLS_ERROR_MESSAGES[\"server.error\"],\n code: \"server.error\",\n ref,\n });\n },\n );\n\n // ---- Routes ---------------------------------------------------------\n registerUiAssets(instance, { notFound });\n registerAuthRoutes(instance, deps);\n\n instance.get(\"/api/panels\", async () => listPanelInfos(deps.panels, deps.builtInPanels));\n\n registerRequestsRoutes(instance, routes);\n registerRouteRoutes(instance, routes);\n registerInsightsRoutes(instance, routes);\n registerLogRoutes(instance, routes);\n registerShapeExplainRoute(instance, routes);\n registerPanelRoutes(instance, deps.panels, { notFound });\n\n share?.register(instance, notFound);\n\n if (enabledTabs.has(\"mail\")) registerMailRoutes(instance, routes);\n if (enabledTabs.has(\"ai\") || enabledTabs.has(\"agents\")) registerAiRoutes(instance, routes);\n if (enabledTabs.has(\"api\")) registerOpenApiRoutes(instance, routes);\n\n registerStreamRoute(instance, routes);\n },\n { prefix },\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,MAAM,0BAA0B;AAChC,MAAM,2BAA2B;AAEjC,MAAM,iBAAiB;;AAGvB,MAAM,+BAAe,IAAI,IAAI;CAAC;CAAO;CAAQ;AAAS,CAAC;;AAGvD,MAAM,gCAAgB,IAAI,IAAI,CAAC,SAAS,eAAe,CAAC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import { DEVTOOLS_SHARE_COOKIE_MAX_SECONDS } from "./constants.mjs";
|
|
3
|
+
|
|
4
|
+
//#region ../../packages/devtools/src/production/http/share-session.ts
|
|
5
|
+
/** How long a read of a share record is reused. A revoke reaches every instance within this time. */
|
|
6
|
+
const SHARE_CACHE_MS = 5e3;
|
|
7
|
+
/** Records kept in the cache of one process (oldest evicted). */
|
|
8
|
+
const SHARE_CACHE_SIZE = 500;
|
|
9
|
+
/** A link's use is written at most this often per link and process. */
|
|
10
|
+
const TOUCH_INTERVAL_MS = 6e4;
|
|
11
|
+
/**
|
|
12
|
+
* The share grant: a cookie carrying `<shareId>.<exp>.<HMAC-SHA256(key,
|
|
13
|
+
* "share:<id>:<exp>")>`. The signature proves this server issued it; the
|
|
14
|
+
* link's record, read through a 5-second cache, proves it is still alive, so
|
|
15
|
+
* a revoke takes effect everywhere within that time without a session table.
|
|
16
|
+
*/
|
|
17
|
+
function createShareSessions(input) {
|
|
18
|
+
const { store, hmac } = input;
|
|
19
|
+
const now = input.now ?? (() => Date.now());
|
|
20
|
+
const panels = new Map(input.panels.filter((panel) => panel.share !== null).map((panel) => [panel.id, panel]));
|
|
21
|
+
const cache = /* @__PURE__ */ new Map();
|
|
22
|
+
const touched = /* @__PURE__ */ new Map();
|
|
23
|
+
const sign = (id, exp) => hmac(`share:${id}:${exp}`);
|
|
24
|
+
async function record(id) {
|
|
25
|
+
const cached = cache.get(id);
|
|
26
|
+
if (cached && now() - cached.at < 5e3) return cached.record;
|
|
27
|
+
const found = await store.shares.get(id);
|
|
28
|
+
cache.delete(id);
|
|
29
|
+
if (cache.size >= SHARE_CACHE_SIZE) {
|
|
30
|
+
const oldest = cache.keys().next();
|
|
31
|
+
if (!oldest.done) cache.delete(oldest.value);
|
|
32
|
+
}
|
|
33
|
+
cache.set(id, {
|
|
34
|
+
record: found,
|
|
35
|
+
at: now()
|
|
36
|
+
});
|
|
37
|
+
return found;
|
|
38
|
+
}
|
|
39
|
+
function grantFor(share) {
|
|
40
|
+
if (share.revokedAt !== null) return {
|
|
41
|
+
refused: "revoked",
|
|
42
|
+
shareId: share.id
|
|
43
|
+
};
|
|
44
|
+
if (share.expiresAt <= now()) return {
|
|
45
|
+
refused: "expired",
|
|
46
|
+
shareId: share.id
|
|
47
|
+
};
|
|
48
|
+
const panel = panels.get(share.panel);
|
|
49
|
+
return panel ? { grant: {
|
|
50
|
+
share,
|
|
51
|
+
panel
|
|
52
|
+
} } : {
|
|
53
|
+
refused: "panel",
|
|
54
|
+
shareId: share.id
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
return {
|
|
58
|
+
issue(share) {
|
|
59
|
+
const remaining = Math.floor((share.expiresAt - now()) / 1e3);
|
|
60
|
+
const maxAgeSeconds = Math.max(1, Math.min(remaining, DEVTOOLS_SHARE_COOKIE_MAX_SECONDS));
|
|
61
|
+
const exp = now() + maxAgeSeconds * 1e3;
|
|
62
|
+
return {
|
|
63
|
+
value: `${share.id}.${exp}.${sign(share.id, exp)}`,
|
|
64
|
+
maxAgeSeconds
|
|
65
|
+
};
|
|
66
|
+
},
|
|
67
|
+
async verify(value) {
|
|
68
|
+
const parts = (value ?? "").split(".");
|
|
69
|
+
const [id, expText, signature] = parts;
|
|
70
|
+
if (parts.length !== 3 || !id || !expText || !signature || !/^\d{1,16}$/.test(expText)) return {
|
|
71
|
+
refused: "cookie",
|
|
72
|
+
shareId: null
|
|
73
|
+
};
|
|
74
|
+
const exp = Number(expText);
|
|
75
|
+
if (!safeEqual(signature, sign(id, exp)) || exp <= now()) return {
|
|
76
|
+
refused: "cookie",
|
|
77
|
+
shareId: null
|
|
78
|
+
};
|
|
79
|
+
const share = await record(id);
|
|
80
|
+
return share ? grantFor(share) : {
|
|
81
|
+
refused: "unknown",
|
|
82
|
+
shareId: id
|
|
83
|
+
};
|
|
84
|
+
},
|
|
85
|
+
async open(tokenHash) {
|
|
86
|
+
const share = await store.shares.findByTokenHash(tokenHash);
|
|
87
|
+
return share ? grantFor(share) : {
|
|
88
|
+
refused: "unknown",
|
|
89
|
+
shareId: null
|
|
90
|
+
};
|
|
91
|
+
},
|
|
92
|
+
touch(shareId) {
|
|
93
|
+
const at = now();
|
|
94
|
+
const last = touched.get(shareId);
|
|
95
|
+
if (last !== void 0 && at - last < TOUCH_INTERVAL_MS) return;
|
|
96
|
+
touched.delete(shareId);
|
|
97
|
+
if (touched.size >= SHARE_CACHE_SIZE) {
|
|
98
|
+
const oldest = touched.keys().next();
|
|
99
|
+
if (!oldest.done) touched.delete(oldest.value);
|
|
100
|
+
}
|
|
101
|
+
touched.set(shareId, at);
|
|
102
|
+
store.shares.touch(shareId, at).catch((error) => {
|
|
103
|
+
input.warn?.(`devtools could not record a share link use: ${error instanceof Error ? error.message : String(error)}`);
|
|
104
|
+
});
|
|
105
|
+
},
|
|
106
|
+
invalidate() {
|
|
107
|
+
cache.clear();
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
//#endregion
|
|
113
|
+
export { SHARE_CACHE_MS, createShareSessions };
|
|
114
|
+
//# sourceMappingURL=share-session.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"share-session.mjs","names":[],"sources":["../../../../../../../../../packages/devtools/src/production/http/share-session.ts"],"sourcesContent":["import type { MountedDevtoolsPanel } from \"../../panels\";\nimport { safeEqual } from \"../auth/helpers\";\nimport type { DevtoolsShareRecord, DevtoolsStore } from \"../store/types\";\nimport { DEVTOOLS_SHARE_COOKIE_MAX_SECONDS } from \"./constants\";\n\n/** How long a read of a share record is reused. A revoke reaches every instance within this time. */\nexport const SHARE_CACHE_MS = 5000;\n\n/** Records kept in the cache of one process (oldest evicted). */\nconst SHARE_CACHE_SIZE = 500;\n\n/** A link's use is written at most this often per link and process. */\nconst TOUCH_INTERVAL_MS = 60_000;\n\n/** What a valid share cookie grants: the link and the panel it opens. */\nexport type DevtoolsShareGrant = {\n share: DevtoolsShareRecord;\n panel: MountedDevtoolsPanel;\n};\n\n/** Why a share cookie or token was refused (written to the audit log; never the value). */\nexport type DevtoolsShareRefusal = \"unknown\" | \"expired\" | \"revoked\" | \"panel\" | \"cookie\";\n\nexport type DevtoolsShareSessions = {\n /** The cookie value for `share`: `<id>.<exp>.<hmac>`, and its life in seconds. */\n issue(share: DevtoolsShareRecord): { value: string; maxAgeSeconds: number };\n /** The grant a `Cookie` value carries, or the reason it was refused. */\n verify(\n value: string | undefined,\n ): Promise<\n { grant: DevtoolsShareGrant } | { refused: DevtoolsShareRefusal; shareId: string | null }\n >;\n /** The record a token hash names, checked for life and panel; or the reason it is refused. */\n open(\n tokenHash: string,\n ): Promise<\n { grant: DevtoolsShareGrant } | { refused: DevtoolsShareRefusal; shareId: string | null }\n >;\n /** Counts one use of `share` (at most once a minute per link). */\n touch(shareId: string): void;\n /** Forgets cached records (after this process revoked or created a link). */\n invalidate(): void;\n};\n\n/**\n * The share grant: a cookie carrying `<shareId>.<exp>.<HMAC-SHA256(key,\n * \"share:<id>:<exp>\")>`. The signature proves this server issued it; the\n * link's record, read through a 5-second cache, proves it is still alive, so\n * a revoke takes effect everywhere within that time without a session table.\n */\nexport function createShareSessions(input: {\n store: DevtoolsStore;\n panels: readonly MountedDevtoolsPanel[];\n hmac: (value: string) => string;\n now?: () => number;\n warn?: (message: string) => void;\n}): DevtoolsShareSessions {\n const { store, hmac } = input;\n const now = input.now ?? (() => Date.now());\n const panels = new Map(\n input.panels.filter((panel) => panel.share !== null).map((panel) => [panel.id, panel]),\n );\n const cache = new Map<string, { record: DevtoolsShareRecord | null; at: number }>();\n const touched = new Map<string, number>();\n\n const sign = (id: string, exp: number): string => hmac(`share:${id}:${exp}`);\n\n async function record(id: string): Promise<DevtoolsShareRecord | null> {\n const cached = cache.get(id);\n\n if (cached && now() - cached.at < SHARE_CACHE_MS) return cached.record;\n\n const found = await store.shares.get(id);\n\n cache.delete(id);\n\n if (cache.size >= SHARE_CACHE_SIZE) {\n const oldest = cache.keys().next();\n\n if (!oldest.done) cache.delete(oldest.value);\n }\n\n cache.set(id, { record: found, at: now() });\n\n return found;\n }\n\n function grantFor(\n share: DevtoolsShareRecord,\n ): { grant: DevtoolsShareGrant } | { refused: DevtoolsShareRefusal; shareId: string } {\n if (share.revokedAt !== null) return { refused: \"revoked\", shareId: share.id };\n\n if (share.expiresAt <= now()) return { refused: \"expired\", shareId: share.id };\n\n const panel = panels.get(share.panel);\n\n return panel ? { grant: { share, panel } } : { refused: \"panel\", shareId: share.id };\n }\n\n return {\n issue(share) {\n const remaining = Math.floor((share.expiresAt - now()) / 1000);\n const maxAgeSeconds = Math.max(1, Math.min(remaining, DEVTOOLS_SHARE_COOKIE_MAX_SECONDS));\n const exp = now() + maxAgeSeconds * 1000;\n\n return { value: `${share.id}.${exp}.${sign(share.id, exp)}`, maxAgeSeconds };\n },\n\n async verify(value) {\n const parts = (value ?? \"\").split(\".\");\n const [id, expText, signature] = parts;\n\n if (parts.length !== 3 || !id || !expText || !signature || !/^\\d{1,16}$/.test(expText)) {\n return { refused: \"cookie\", shareId: null };\n }\n\n const exp = Number(expText);\n\n if (!safeEqual(signature, sign(id, exp)) || exp <= now()) {\n return { refused: \"cookie\", shareId: null };\n }\n\n const share = await record(id);\n\n return share ? grantFor(share) : { refused: \"unknown\", shareId: id };\n },\n\n async open(tokenHash) {\n const share = await store.shares.findByTokenHash(tokenHash);\n\n return share ? grantFor(share) : { refused: \"unknown\", shareId: null };\n },\n\n touch(shareId) {\n const at = now();\n const last = touched.get(shareId);\n\n if (last !== undefined && at - last < TOUCH_INTERVAL_MS) return;\n\n touched.delete(shareId);\n\n if (touched.size >= SHARE_CACHE_SIZE) {\n const oldest = touched.keys().next();\n\n if (!oldest.done) touched.delete(oldest.value);\n }\n\n touched.set(shareId, at);\n // A failed write is not worth failing the request for.\n void store.shares.touch(shareId, at).catch((error: unknown) => {\n input.warn?.(\n `devtools could not record a share link use: ${error instanceof Error ? error.message : String(error)}`,\n );\n });\n },\n\n invalidate() {\n cache.clear();\n },\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