@noodleseed/one 0.141.1 → 0.142.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.
Files changed (57) hide show
  1. package/dist/bin.js +0 -0
  2. package/dist/commands/assistant-appearance-ops.d.ts +3 -0
  3. package/dist/commands/assistant-appearance-ops.d.ts.map +1 -0
  4. package/dist/commands/assistant-appearance-ops.js +148 -0
  5. package/dist/commands/assistant-appearance-ops.js.map +1 -0
  6. package/dist/commands/assistant-ops.d.ts.map +1 -1
  7. package/dist/commands/assistant-ops.js +4 -1
  8. package/dist/commands/assistant-ops.js.map +1 -1
  9. package/node_modules/@noodle-borg/agent-kit/dist/generated/example-files.js +3 -3
  10. package/node_modules/@noodle-borg/agent-kit/dist/skill-embedded-assistant-ref.js +25 -18
  11. package/node_modules/@noodle-borg/assistant-gateway/dist/assistant-appearance-store.d.ts +34 -0
  12. package/node_modules/@noodle-borg/assistant-gateway/dist/assistant-appearance-store.js +12 -0
  13. package/node_modules/@noodle-borg/assistant-gateway/dist/assistant-appearance.d.ts +18 -0
  14. package/node_modules/@noodle-borg/assistant-gateway/dist/assistant-appearance.js +228 -0
  15. package/node_modules/@noodle-borg/assistant-gateway/dist/assistant-configuration.d.ts +31 -0
  16. package/node_modules/@noodle-borg/{service/dist/routes → assistant-gateway/dist}/assistant-configuration.js +12 -1
  17. package/node_modules/@noodle-borg/assistant-gateway/dist/assistant-delegated-projection.d.ts +12 -0
  18. package/node_modules/@noodle-borg/assistant-gateway/dist/assistant-store.d.ts +1 -1
  19. package/node_modules/@noodle-borg/assistant-gateway/dist/assistant-store.js +1 -0
  20. package/node_modules/@noodle-borg/assistant-gateway/dist/assistant-view-availability.d.ts +38 -0
  21. package/node_modules/@noodle-borg/assistant-gateway/dist/embed-store.d.ts +3 -0
  22. package/node_modules/@noodle-borg/assistant-gateway/dist/embed-store.js +4 -0
  23. package/node_modules/@noodle-borg/assistant-gateway/dist/in-memory-assistant-appearance-store.d.ts +8 -0
  24. package/node_modules/@noodle-borg/assistant-gateway/dist/in-memory-assistant-appearance-store.js +26 -0
  25. package/node_modules/@noodle-borg/assistant-gateway/dist/portable.d.ts +7 -1
  26. package/node_modules/@noodle-borg/assistant-gateway/dist/portable.js +7 -1
  27. package/node_modules/@noodle-borg/assistant-gateway/dist/public-configuration.d.ts +22 -0
  28. package/node_modules/@noodle-borg/assistant-gateway/dist/public-configuration.js +25 -0
  29. package/node_modules/@noodle-borg/assistant-gateway/package.json +3 -1
  30. package/node_modules/@noodle-borg/authoring/dist/assistant.d.ts +6 -2
  31. package/node_modules/@noodle-borg/authoring/dist/react/components.d.ts +3 -3
  32. package/node_modules/@noodle-borg/authoring/dist/react/native-components.d.ts +2 -2
  33. package/node_modules/@noodle-borg/cli-catalog/dist/catalog-data-assistant.js +38 -0
  34. package/node_modules/@noodle-borg/compiler/dist/manifest/schema.d.ts +56 -4
  35. package/node_modules/@noodle-borg/compiler/dist/manifest/schema.js +25 -47
  36. package/node_modules/@noodle-borg/service/dist/credential-broker.js +1 -1
  37. package/node_modules/@noodle-borg/service/dist/invocation-context.js +1 -2
  38. package/node_modules/@noodle-borg/service/dist/local-options.d.ts +1 -0
  39. package/node_modules/@noodle-borg/service/dist/registry-compile.js +1 -1
  40. package/node_modules/@noodle-borg/service/dist/routes/assistant-agent.js +1 -3
  41. package/node_modules/@noodle-borg/service/dist/routes/assistant-appearance.js +104 -0
  42. package/node_modules/@noodle-borg/service/dist/routes/assistant-dispatch.js +24 -4
  43. package/node_modules/@noodle-borg/service/dist/routes/assistant-interaction-replay.js +1 -2
  44. package/node_modules/@noodle-borg/service/dist/routes/assistant-interactions.js +1 -2
  45. package/node_modules/@noodle-borg/service/dist/routes/assistant-public-configuration.js +41 -0
  46. package/node_modules/@noodle-borg/service/dist/routes/assistant-public-session.js +7 -12
  47. package/node_modules/@noodle-borg/service/dist/routes/assistant-route-http.js +2 -2
  48. package/node_modules/@noodle-borg/service/dist/routes/assistant-sandbox.js +47 -12
  49. package/node_modules/@noodle-borg/service/dist/routes/assistant.js +4 -5
  50. package/node_modules/@noodle-borg/service/dist/service.js +3 -15
  51. package/node_modules/@noodleseed/assistant/README.md +63 -24
  52. package/node_modules/@noodleseed/assistant/package.json +1 -1
  53. package/package.json +1 -1
  54. package/node_modules/@noodle-borg/assistant-gateway/dist/assistant-app-sandbox.d.ts +0 -13
  55. package/node_modules/@noodle-borg/assistant-gateway/dist/assistant-app-sandbox.js +0 -204
  56. /package/node_modules/@noodle-borg/{service → assistant-gateway}/dist/assistant-delegated-projection.js +0 -0
  57. /package/node_modules/@noodle-borg/{service → assistant-gateway}/dist/assistant-view-availability.js +0 -0
@@ -6,10 +6,10 @@ The package exports the canonical `<noodle-assistant>` managed Web Component, th
6
6
  `<noodle-app-view>` MCP App host from `@noodleseed/assistant/app-view`, a managed React wrapper and
7
7
  `NoodleAppView` adapter from `@noodleseed/assistant/react`, a renderer-free React hook from
8
8
  `@noodleseed/assistant/react/client`, a DOM-free client from `@noodleseed/assistant/client`, and the
9
- backend-only `createAssistantSession` helper from `@noodleseed/assistant/server`. Light, dark, and automatic
10
- themes work without configuration; the component inherits the deployed MCP server's brand kit while slots,
11
- methods, events, and semantic CSS variables let a SaaS developer integrate it without depending on internal
12
- DOM selectors.
9
+ backend-only `createAssistantSession` helper from `@noodleseed/assistant/server`. The component inherits the
10
+ deployed MCP server's brand kit while slots, methods, events, and semantic CSS variables let a SaaS developer
11
+ integrate it without depending on internal DOM selectors. Light, dark, automatic host-page matching, and
12
+ host-page inversion work without replacing conversation or App DOM.
13
13
 
14
14
  Never pass an embed client secret, model key, MCP token, or raw application session into the browser
15
15
  component. Exchange the already-authenticated user from the customer backend and return only the short-lived
@@ -22,7 +22,7 @@ The model configuration and SaaS integration credentials have different owners:
22
22
  | Noodle deployment | `ASSISTANT_MODEL_BASE_URL`, `ASSISTANT_MODEL`, `ASSISTANT_MODEL_API_KEY` | Managed with `noodle variables set` / `noodle secrets set` |
23
23
  | Customer backend | `NOODLE_SERVICE_URL`, `NOODLE_ASSISTANT_CLIENT_ID`, `NOODLE_ASSISTANT_CLIENT_SECRET` | Backend environment or secret manager only |
24
24
 
25
- `allowedOrigins` accepts exact origins. Production origins must be HTTPS; plain HTTP is accepted only for
25
+ `access.origins` accepts exact origins. Production origins must be HTTPS; plain HTTP is accepted only for
26
26
  loopback development origins such as `http://localhost:3000`. Local MCP authoring remains available without
27
27
  login, but an external browser embed needs an active deployment before its deployment-bound client can be
28
28
  created.
@@ -35,8 +35,8 @@ troubleshooting) lives at <https://docs.noodleseed.dev/guides/embedded-assistant
35
35
  the server itself is `@noodleseed/one` (`npm install -g @noodleseed/one`).
36
36
 
37
37
  If your page sends a `Content-Security-Policy`, allow the Noodle service origin in `connect-src` (turns and
38
- event streams) and the exact session-advertised `endpoints.sandbox` origin in `frame-src` (it may be a
39
- dedicated sandbox origin, so your `script-src` can stay strict). Details are in the guide's
38
+ event streams) **and** `frame-src` (app widgets render inside a hosted sandbox document served from the
39
+ service origin, `endpoints.sandbox`, so your `script-src` can stay strict). Details are in the guide's
40
40
  "Content-Security-Policy on your page" section.
41
41
 
42
42
  ## Quick start
@@ -55,6 +55,7 @@ structure and treatment in `embeddedAssistant({ presentation })`:
55
55
 
56
56
  ```ts
57
57
  import {
58
+ authenticatedWebsite,
58
59
  embeddedAssistant,
59
60
  openAICompatible,
60
61
  secret,
@@ -83,19 +84,23 @@ export default server(
83
84
  model: variable("ASSISTANT_MODEL"),
84
85
  apiKey: secret("ASSISTANT_MODEL_API_KEY"),
85
86
  }),
86
- allowedOrigins: ["http://localhost:3000", "https://app.acme.example"],
87
+ access: authenticatedWebsite({
88
+ origins: ["http://localhost:3000", "https://app.acme.example"],
89
+ }),
87
90
  layout: {
88
91
  mode: "floating",
89
- position: "bottom-right",
90
- panelWidth: 520,
92
+ position: "bottom-center",
93
+ panelWidth: 970,
91
94
  panelMinHeight: 540,
92
- panelMaxHeight: 740,
93
- edgeOffset: 24,
95
+ panelMaxHeight: 1025,
96
+ edgeOffset: 20,
94
97
  },
95
- behavior: { showTimestamps: true },
98
+ theme: "invert",
99
+ behavior: { showTimestamps: true, showPoweredBy: false },
96
100
  labels: {
97
101
  welcomeHeading: "How can Acme help?",
98
102
  welcomeMessage: "Fast answers from the tools your team already uses.",
103
+ launcherPlaceholder: "Ask Acme anything",
99
104
  composerPlaceholder: "Message Acme Support…",
100
105
  sessionReady: "Acme support is online",
101
106
  },
@@ -107,6 +112,7 @@ export default server(
107
112
  radius: 20,
108
113
  },
109
114
  launcher: {
115
+ style: "bubble",
110
116
  icon: "chat",
111
117
  size: "lg",
112
118
  status: "session",
@@ -144,10 +150,15 @@ markup-looking text stays text. `presentation.panel.radius` is a bounded panel-s
144
150
  not a second color or identity source. An HTTPS or packaged SVG referenced by `branding.logo`, `branding.mark`, or
145
151
  `branding.avatar` is a bounded asset, not inline renderer markup.
146
152
 
147
- If `presentation` is omitted, the rounded Halo-inspired baseline remains: a frosted glass panel with a 24px
148
- radius, soft elevation, subtle border/motion, medium brand-mark launcher without status or effect,
149
- undecorated header, pill composer and action controls, and rounded user bubbles with plain assistant messages
150
- at comfortable width. Partial objects merge with those defaults.
153
+ With UI overrides omitted, the complete managed baseline remains: a bottom-center frosted launcher pill that
154
+ morphs into a prompt input before opening; a 970px outer desktop shell with 20px side padding, 85vh height,
155
+ 1025px maximum height, and a 24px panel using the built-in `#F8F8F8` light and `#0C0A09` dark surfaces;
156
+ bottom prompt chips and pill composer; plain assistant messages and 85%-wide user bubbles; a Noodle Seed
157
+ attribution row; and safe-area-aware mobile fullscreen.
158
+ The generic prompt chips ship as defaults, while an authored list—including `[]`—replaces them. Set
159
+ `presentation.launcher.style` to `bubble` for a direct-open 44px launcher. The baseline does not include the
160
+ “Available on ChatGPT” promotion. Partial configuration objects merge with the remaining defaults;
161
+ `presentation.panel.surface: "glass"` remains available when a translucent panel is intentional.
151
162
 
152
163
  ### Configure and deploy
153
164
 
@@ -294,6 +305,22 @@ import "@noodleseed/assistant";
294
305
  ></noodle-assistant>
295
306
  ```
296
307
 
308
+ That single element is the complete managed assistant in React, Vue, Angular, or plain DOM. The
309
+ default pill expands into a prompt first; set `presentation.launcher.style: "bubble"` in `server.ts` when the
310
+ launcher should open the panel directly. Frameworks must treat `noodle-assistant` as a custom element.
311
+
312
+ When the host needs an authenticated fetch wrapper, assign complex values as properties before connecting
313
+ the element so the first session exchange already carries the application's credentials:
314
+
315
+ ```ts
316
+ import type { NoodleAssistantElement } from "@noodleseed/assistant";
317
+
318
+ const assistant = document.createElement("noodle-assistant") as NoodleAssistantElement;
319
+ assistant.fetch = authenticatedFetch;
320
+ assistant.sessionEndpoint = "/api/assistant/session";
321
+ document.body.append(assistant);
322
+ ```
323
+
297
324
  Or use React:
298
325
 
299
326
  ```tsx
@@ -410,8 +437,13 @@ import "@noodleseed/assistant/app-view";
410
437
  </template>
411
438
  ```
412
439
 
413
- Framework setup, lifecycle ownership, sandbox/CSP behavior, and staged diagnostics are owned by the
414
- [Bring your own UI guide](https://docs.noodleseed.dev/docs/guides/bring-your-own-ui).
440
+ Configure Vue's `isCustomElement` for `noodle-app-view`. Angular uses the same element with `[client]`,
441
+ `[view]`, and `[theme]` property bindings. Do not serialize `client` or `view` into attributes.
442
+
443
+ `<noodle-app-view>` is the canonical host; `NoodleAppView` delegates to it. Both use the
444
+ service-advertised sandbox URL, route App calls through the supplied client, publish theme changes without
445
+ replacing the iframe, and request standard teardown on semantic replacement, disconnect, or an App teardown
446
+ request.
415
447
 
416
448
  The App document owns its action intent: it calls standard `tools/call` after connecting and never relies on
417
449
  native form navigation. If that call needs input or confirmation, the same `client` publishes the normal
@@ -636,24 +668,31 @@ noodle-assistant {
636
668
  ```
637
669
 
638
670
  For each matching region or token, precedence is the typed host appearance object, then host-provided slot
639
- content or a public CSS custom property, then compiled server `presentation`/`branding`, then built-in
640
- defaults. The public slots are `launcher-icon`,
671
+ content or a public CSS custom property, then the saved environment operator override, compiled server
672
+ `presentation`/`branding`, and built-in defaults. The public slots are `launcher-icon`,
641
673
  `header-leading`, `header-actions`, `empty-state`, `composer-leading`, `composer-trailing`, and
642
674
  `conversation-footer`; slotted host DOM replaces the renderer fallback for that region. Slots are a trusted
643
675
  embedding-page integration API, not a way to put HTML or callbacks in deployment configuration. Internal
644
676
  shadow-DOM selectors and classes are not public API.
645
677
 
646
- `theme="auto"` follows the browser's operating-system color preference. When the embedding application has
678
+ The Console **Assistant** tab and `noodle assistant appearance show|apply|reset` manage that environment
679
+ override. Existing embed code does not change: public elements load its non-secret configuration before
680
+ first paint without spending a session mint, while authenticated elements receive it from session exchange.
681
+ Each new session pins one resolved revision; an open conversation remains visually stable.
682
+
683
+ `theme="auto"` follows an explicit `light`/`dark` host-page class or data attribute, then the browser's
684
+ operating-system preference; `theme="invert"` selects the opposite host mode. When the embedding application has
647
685
  its own theme toggle, pass its resolved `"light"` or `"dark"` value to `NoodleAssistant` and every
648
686
  `<noodle-app-view>`/`NoodleAppView`. Updates change the assistant in place and notify mounted MCP Apps through standard host
649
687
  context.
650
688
 
651
689
  Server branding controls customer name, themed logo/mark/avatar assets, semantic light/dark colors, density,
652
- radius, typography, and automatic theme. `embeddedAssistant(...)` controls floating/inline/drawer layout,
653
- position and dimensions, mobile and launcher/header/avatar/timestamp behavior, visible labels, suggested
690
+ radius, typography, and automatic theme. `embeddedAssistant(...)` controls theme selection,
691
+ floating/inline/drawer layout, position and dimensions, mobile and launcher/header/avatar/timestamp/attribution behavior, visible labels, suggested
654
692
  prompts, privacy/terms links, locale, and text direction.
655
693
  Named slots cover launcher/header/composer/footer extensions. Public methods include `open`, `close`,
656
694
  `toggle`, `focusComposer`, `sendMessage`, `stop`, `reconnect`, `updateContext`, `updateModelContext`, `respond`, `confirmTool`, and `resetSession`;
695
+ lifecycle properties include `sessionEndpoint`, `embedId`, `serviceUrl`, `fetch`, and `appearance`;
657
696
  lifecycle, message, tool-proposal, interaction-resolution, view-availability, context, and error events
658
697
  support application integration. `confirmTool(id)` remains the compatibility shorthand for
659
698
  `respond(id, { action: 'accept' })`.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noodleseed/assistant",
3
- "version": "1.25.0",
3
+ "version": "1.25.1",
4
4
  "description": "Embed the Noodle Seed customer-branded assistant in your web app with managed or framework-owned UI, a framework-neutral MCP App host, a DOM-free client, and a backend session helper. Authoring and deploying the server is @noodleseed/one.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noodleseed/one",
3
- "version": "0.141.1",
3
+ "version": "0.142.0",
4
4
  "private": false,
5
5
  "description": "Noodle CLI by Noodle Seed — author, run, and deploy declarative MCP servers. Embedding the assistant in your own web app is @noodleseed/assistant.",
6
6
  "license": "Apache-2.0",
@@ -1,13 +0,0 @@
1
- /** Relay body pinned to `contract/v1/assistant-sandbox-document.html` and the browser client. */
2
- export declare const ASSISTANT_SANDBOX_DOCUMENT = "<!doctype html><meta charset=\"utf-8\"><style>html,body,iframe{border:0;margin:0;width:100%;height:100%;overflow:hidden}body{background:transparent}</style><body><script>\nlet inner,loaded=false;\nif(self===top)throw new Error('The assistant sandbox relay must be embedded');\nconst standardSandbox='allow-scripts allow-same-origin allow-forms';\nconst rawParentOrigin=new URLSearchParams(location.hash.slice(1)).get('parentOrigin');\nlet expectedParentOrigin;\ntry{const parsed=new URL(rawParentOrigin||'');if(parsed.origin===rawParentOrigin&&/^https?:$/.test(parsed.protocol))expectedParentOrigin=parsed.origin}catch{}\nconst parentTarget=expectedParentOrigin||'*';\nconst ownOrigin=self.origin;\nconst ready={jsonrpc:'2.0',method:'ui/notifications/sandbox-proxy-ready',params:{}};\n// Re-announce until the host acknowledges with the resource: when this document is hosted\n// cross-origin, the first announcement can arrive before the host's load handler is listening.\nconst announce=setInterval(()=>parent.postMessage(ready,parentTarget),120);\nsetTimeout(()=>clearInterval(announce),15000);\naddEventListener('message',(event)=>{\n if(event.source===parent){\n if(expectedParentOrigin&&event.origin!==expectedParentOrigin)return;\n const message=event.data;\n if(message?.method==='ui/notifications/sandbox-resource-ready'){\n clearInterval(announce);\n if(loaded)return;\n loaded=true;\n const requestedSandbox=message.params?.sandbox;\n inner=document.createElement('iframe');\n inner.setAttribute('sandbox',requestedSandbox===standardSandbox?standardSandbox:'allow-scripts');\n inner.setAttribute('referrerpolicy','no-referrer');\n const permissions=message.params?.permissions;\n const allow=[];\n if(permissions?.camera)allow.push('camera');\n if(permissions?.microphone)allow.push('microphone');\n if(permissions?.geolocation)allow.push('geolocation');\n if(permissions?.clipboardWrite)allow.push('clipboard-write');\n if(allow.length)inner.setAttribute('allow',allow.join('; '));\n document.body.append(inner);\n let html=String(message.params?.html||'');\n const csp=message.params?.csp;\n if(csp&&typeof csp==='object'){\n const list=(value,fallback)=>Array.isArray(value)&&value.length?value.join(' '):fallback;\n const resources=Array.isArray(csp.resourceDomains)?csp.resourceDomains:[];\n const suffix=resources.length?' '+resources.join(' '):'';\n const policy=[\"default-src 'none'\",\"script-src 'unsafe-inline'\"+suffix,\"style-src 'unsafe-inline'\"+suffix,'img-src data: blob:'+suffix,'font-src data: blob:'+suffix,'media-src data: blob:'+suffix,'worker-src blob:'+suffix,'connect-src '+list(csp.connectDomains,\"'none'\"),'frame-src '+list(csp.frameDomains,\"'none'\"),\"object-src 'none'\",\"form-action 'none'\",'base-uri '+list(csp.baseUriDomains,\"'none'\")].join('; ');\n const meta='<meta http-equiv=\"Content-Security-Policy\" content=\"'+policy.replace(/&/g,'&amp;').replace(/\"/g,'&quot;')+'\">';\n const doctype=html.match(/^\\s*<!doctype[^>]*>/i);\n html=doctype?html.slice(0,doctype[0].length)+meta+html.slice(doctype[0].length):meta+html;\n }\n try{\n const doc=inner.contentDocument||inner.contentWindow?.document;\n if(!doc)throw new Error('document unavailable');\n doc.open();doc.write(html);doc.close();\n }catch{inner.srcdoc=html}\n return;\n }\n inner?.contentWindow?.postMessage(message,'*');\n } else if(inner && event.source===inner.contentWindow) {\n if(event.origin!==ownOrigin)return;\n parent.postMessage(event.data,parentTarget);\n }\n});\nparent.postMessage(ready,parentTarget);\n</script></body>";
3
- export interface AssistantSandboxResponsePolicy {
4
- readonly ok: boolean;
5
- readonly contentSecurityPolicy: string;
6
- }
7
- /** Match a request authority to the configured sandbox origin, normalizing default ports. */
8
- export declare function isAssistantSandboxHost(requestHost: string | undefined, sandboxBaseUrl: string | undefined): boolean;
9
- /** Validate an untrusted query and return the CSP response header to apply before navigation. */
10
- export declare function resolveAssistantSandboxResponsePolicy(requestUrl: string, isolatedOrigin?: boolean): AssistantSandboxResponsePolicy;
11
- /** Normalize the operator-provided dedicated sandbox origin and keep it off the service origin. */
12
- export declare function validateAssistantSandboxBaseUrl(value: string, serviceBase: string | undefined): string;
13
- //# sourceMappingURL=assistant-app-sandbox.d.ts.map
@@ -1,204 +0,0 @@
1
- /** Relay body pinned to `contract/v1/assistant-sandbox-document.html` and the browser client. */
2
- export const ASSISTANT_SANDBOX_DOCUMENT = `<!doctype html><meta charset="utf-8"><style>html,body,iframe{border:0;margin:0;width:100%;height:100%;overflow:hidden}body{background:transparent}</style><body><script>
3
- let inner,loaded=false;
4
- if(self===top)throw new Error('The assistant sandbox relay must be embedded');
5
- const standardSandbox='allow-scripts allow-same-origin allow-forms';
6
- const rawParentOrigin=new URLSearchParams(location.hash.slice(1)).get('parentOrigin');
7
- let expectedParentOrigin;
8
- try{const parsed=new URL(rawParentOrigin||'');if(parsed.origin===rawParentOrigin&&/^https?:$/.test(parsed.protocol))expectedParentOrigin=parsed.origin}catch{}
9
- const parentTarget=expectedParentOrigin||'*';
10
- const ownOrigin=self.origin;
11
- const ready={jsonrpc:'2.0',method:'ui/notifications/sandbox-proxy-ready',params:{}};
12
- // Re-announce until the host acknowledges with the resource: when this document is hosted
13
- // cross-origin, the first announcement can arrive before the host's load handler is listening.
14
- const announce=setInterval(()=>parent.postMessage(ready,parentTarget),120);
15
- setTimeout(()=>clearInterval(announce),15000);
16
- addEventListener('message',(event)=>{
17
- if(event.source===parent){
18
- if(expectedParentOrigin&&event.origin!==expectedParentOrigin)return;
19
- const message=event.data;
20
- if(message?.method==='ui/notifications/sandbox-resource-ready'){
21
- clearInterval(announce);
22
- if(loaded)return;
23
- loaded=true;
24
- const requestedSandbox=message.params?.sandbox;
25
- inner=document.createElement('iframe');
26
- inner.setAttribute('sandbox',requestedSandbox===standardSandbox?standardSandbox:'allow-scripts');
27
- inner.setAttribute('referrerpolicy','no-referrer');
28
- const permissions=message.params?.permissions;
29
- const allow=[];
30
- if(permissions?.camera)allow.push('camera');
31
- if(permissions?.microphone)allow.push('microphone');
32
- if(permissions?.geolocation)allow.push('geolocation');
33
- if(permissions?.clipboardWrite)allow.push('clipboard-write');
34
- if(allow.length)inner.setAttribute('allow',allow.join('; '));
35
- document.body.append(inner);
36
- let html=String(message.params?.html||'');
37
- const csp=message.params?.csp;
38
- if(csp&&typeof csp==='object'){
39
- const list=(value,fallback)=>Array.isArray(value)&&value.length?value.join(' '):fallback;
40
- const resources=Array.isArray(csp.resourceDomains)?csp.resourceDomains:[];
41
- const suffix=resources.length?' '+resources.join(' '):'';
42
- const policy=["default-src 'none'","script-src 'unsafe-inline'"+suffix,"style-src 'unsafe-inline'"+suffix,'img-src data: blob:'+suffix,'font-src data: blob:'+suffix,'media-src data: blob:'+suffix,'worker-src blob:'+suffix,'connect-src '+list(csp.connectDomains,"'none'"),'frame-src '+list(csp.frameDomains,"'none'"),"object-src 'none'","form-action 'none'",'base-uri '+list(csp.baseUriDomains,"'none'")].join('; ');
43
- const meta='<meta http-equiv="Content-Security-Policy" content="'+policy.replace(/&/g,'&amp;').replace(/"/g,'&quot;')+'">';
44
- const doctype=html.match(/^\\s*<!doctype[^>]*>/i);
45
- html=doctype?html.slice(0,doctype[0].length)+meta+html.slice(doctype[0].length):meta+html;
46
- }
47
- try{
48
- const doc=inner.contentDocument||inner.contentWindow?.document;
49
- if(!doc)throw new Error('document unavailable');
50
- doc.open();doc.write(html);doc.close();
51
- }catch{inner.srcdoc=html}
52
- return;
53
- }
54
- inner?.contentWindow?.postMessage(message,'*');
55
- } else if(inner && event.source===inner.contentWindow) {
56
- if(event.origin!==ownOrigin)return;
57
- parent.postMessage(event.data,parentTarget);
58
- }
59
- });
60
- parent.postMessage(ready,parentTarget);
61
- </script></body>`;
62
- const COMPATIBILITY_CSP = "sandbox allow-scripts; default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src https: data: blob:; font-src https: data:; frame-src about:; form-action 'none'; base-uri 'none'; frame-ancestors *";
63
- const MAX_CSP_QUERY_LENGTH = 8_192;
64
- const MAX_DOMAINS_PER_DIRECTIVE = 32;
65
- const CSP_KEYS = ['connectDomains', 'resourceDomains', 'frameDomains', 'baseUriDomains'];
66
- const CSP_KEY_SET = new Set(CSP_KEYS);
67
- /** Match a request authority to the configured sandbox origin, normalizing default ports. */
68
- export function isAssistantSandboxHost(requestHost, sandboxBaseUrl) {
69
- if (requestHost === undefined || sandboxBaseUrl === undefined)
70
- return false;
71
- try {
72
- const sandboxUrl = new URL(sandboxBaseUrl);
73
- const requestUrl = new URL(`${sandboxUrl.protocol}//${requestHost}`);
74
- return requestUrl.href === `${sandboxUrl.origin}/`;
75
- }
76
- catch {
77
- return false;
78
- }
79
- }
80
- function isRecord(value) {
81
- return typeof value === 'object' && value !== null && !Array.isArray(value);
82
- }
83
- function isLoopback(hostname) {
84
- return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '[::1]';
85
- }
86
- function normalizeCspDomain(value, connect) {
87
- if (value.length > 512 || /[;\r\n'"\s]/u.test(value))
88
- return undefined;
89
- try {
90
- const parsed = new URL(value);
91
- const secure = parsed.protocol === 'https:' || (connect && parsed.protocol === 'wss:');
92
- const local = isLoopback(parsed.hostname) &&
93
- (parsed.protocol === 'http:' || (connect && parsed.protocol === 'ws:'));
94
- if (!secure && !local)
95
- return undefined;
96
- if (parsed.username ||
97
- parsed.password ||
98
- parsed.pathname !== '/' ||
99
- parsed.search ||
100
- parsed.hash) {
101
- return undefined;
102
- }
103
- return parsed.origin;
104
- }
105
- catch {
106
- return undefined;
107
- }
108
- }
109
- function parseSandboxCsp(requestUrl) {
110
- const url = new URL(requestUrl, 'http://sandbox.invalid');
111
- const values = url.searchParams.getAll('csp');
112
- if (values.length === 0)
113
- return { ok: true };
114
- const serialized = values[0];
115
- if (values.length !== 1 || serialized === undefined || serialized.length > MAX_CSP_QUERY_LENGTH) {
116
- return { ok: false };
117
- }
118
- let parsed;
119
- try {
120
- parsed = JSON.parse(serialized);
121
- }
122
- catch {
123
- return { ok: false };
124
- }
125
- if (!isRecord(parsed) || Object.keys(parsed).some((key) => !CSP_KEY_SET.has(key))) {
126
- return { ok: false };
127
- }
128
- const csp = {};
129
- for (const key of CSP_KEYS) {
130
- const raw = parsed[key];
131
- if (raw === undefined)
132
- continue;
133
- if (!Array.isArray(raw) || raw.length > MAX_DOMAINS_PER_DIRECTIVE)
134
- return { ok: false };
135
- const normalized = [];
136
- for (const entry of raw) {
137
- if (typeof entry !== 'string')
138
- return { ok: false };
139
- const domain = normalizeCspDomain(entry, key === 'connectDomains');
140
- if (!domain)
141
- return { ok: false };
142
- normalized.push(domain);
143
- }
144
- csp[key] = [...new Set(normalized)];
145
- }
146
- return { ok: true, value: csp };
147
- }
148
- function sources(values, fallback) {
149
- return values && values.length > 0 ? values.join(' ') : fallback;
150
- }
151
- function sandboxCsp(csp, isolatedOrigin) {
152
- const resources = csp.resourceDomains ?? [];
153
- const resourceSuffix = resources.length > 0 ? ` ${resources.join(' ')}` : '';
154
- return [
155
- isolatedOrigin
156
- ? 'sandbox allow-scripts allow-same-origin allow-forms'
157
- : 'sandbox allow-scripts',
158
- "default-src 'none'",
159
- `script-src 'self' 'unsafe-inline'${resourceSuffix}`,
160
- `style-src 'self' 'unsafe-inline'${resourceSuffix}`,
161
- `img-src 'self' data: blob:${resourceSuffix}`,
162
- `font-src 'self' data: blob:${resourceSuffix}`,
163
- `media-src 'self' data: blob:${resourceSuffix}`,
164
- `worker-src 'self' blob:${resourceSuffix}`,
165
- `connect-src 'self'${csp.connectDomains && csp.connectDomains.length > 0 ? ` ${csp.connectDomains.join(' ')}` : ''}`,
166
- `frame-src ${sources(csp.frameDomains, "'none'")}`,
167
- "object-src 'none'",
168
- "form-action 'none'",
169
- `base-uri ${sources(csp.baseUriDomains, "'none'")}`,
170
- 'frame-ancestors *',
171
- ].join('; ');
172
- }
173
- /** Validate an untrusted query and return the CSP response header to apply before navigation. */
174
- export function resolveAssistantSandboxResponsePolicy(requestUrl, isolatedOrigin = false) {
175
- const parsed = parseSandboxCsp(requestUrl);
176
- if (!parsed.ok)
177
- return { ok: false, contentSecurityPolicy: COMPATIBILITY_CSP };
178
- return {
179
- ok: true,
180
- contentSecurityPolicy: parsed.value !== undefined || isolatedOrigin
181
- ? sandboxCsp(parsed.value ?? {}, isolatedOrigin)
182
- : COMPATIBILITY_CSP,
183
- };
184
- }
185
- /** Normalize the operator-provided dedicated sandbox origin and keep it off the service origin. */
186
- export function validateAssistantSandboxBaseUrl(value, serviceBase) {
187
- let parsed;
188
- try {
189
- parsed = new URL(value);
190
- }
191
- catch {
192
- throw new Error('assistantSandboxBaseUrl must be an exact HTTPS or HTTP loopback origin');
193
- }
194
- const loopback = isLoopback(parsed.hostname);
195
- if (parsed.origin !== value ||
196
- (parsed.protocol !== 'https:' && !(parsed.protocol === 'http:' && loopback))) {
197
- throw new Error('assistantSandboxBaseUrl must be an exact HTTPS or HTTP loopback origin');
198
- }
199
- if (serviceBase !== undefined && new URL(serviceBase).origin === parsed.origin) {
200
- throw new Error('assistantSandboxBaseUrl must use an origin separate from publicBaseUrl');
201
- }
202
- return parsed.origin;
203
- }
204
- //# sourceMappingURL=assistant-app-sandbox.js.map