@stigmer/embed 3.1.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +190 -0
- package/define.d.ts +8 -0
- package/define.d.ts.map +1 -0
- package/define.js +9 -0
- package/define.js.map +1 -0
- package/element.d.ts +30 -0
- package/element.d.ts.map +1 -0
- package/element.js +147 -0
- package/element.js.map +1 -0
- package/embed.global.js +1 -0
- package/frame.d.ts +45 -0
- package/frame.d.ts.map +1 -0
- package/frame.js +118 -0
- package/frame.js.map +1 -0
- package/global.d.ts +18 -0
- package/global.d.ts.map +1 -0
- package/global.js +23 -0
- package/global.js.map +1 -0
- package/host.d.ts +26 -0
- package/host.d.ts.map +1 -0
- package/host.js +49 -0
- package/host.js.map +1 -0
- package/index.d.ts +15 -0
- package/index.d.ts.map +1 -0
- package/index.js +15 -0
- package/index.js.map +1 -0
- package/package.json +41 -0
- package/protocol.d.ts +48 -0
- package/protocol.d.ts.map +1 -0
- package/protocol.js +61 -0
- package/protocol.js.map +1 -0
- package/src/__tests__/element.test.ts +177 -0
- package/src/__tests__/frame.test.ts +141 -0
- package/src/__tests__/host.test.ts +103 -0
- package/src/__tests__/protocol.test.ts +55 -0
- package/src/define.ts +10 -0
- package/src/element.ts +180 -0
- package/src/frame.ts +129 -0
- package/src/global.ts +30 -0
- package/src/host.ts +67 -0
- package/src/index.ts +39 -0
- package/src/protocol.ts +76 -0
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
2
|
+
|
|
3
|
+
import { createEmbedHost } from "../host.js";
|
|
4
|
+
import { toWire } from "../protocol.js";
|
|
5
|
+
|
|
6
|
+
const FRAME_ORIGIN = "https://app.stigmer.example";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* happy-dom does not model cross-frame messaging, so the tests drive the
|
|
10
|
+
* host's window listener directly with synthetic MessageEvents whose
|
|
11
|
+
* source/origin we control — exactly the fields the pinning rules check.
|
|
12
|
+
*/
|
|
13
|
+
function makeIframe(): HTMLIFrameElement {
|
|
14
|
+
const iframe = document.createElement("iframe");
|
|
15
|
+
document.body.appendChild(iframe);
|
|
16
|
+
return iframe;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function dispatchMessage(
|
|
20
|
+
data: unknown,
|
|
21
|
+
origin: string,
|
|
22
|
+
source: MessageEventSource | null,
|
|
23
|
+
): void {
|
|
24
|
+
window.dispatchEvent(
|
|
25
|
+
new MessageEvent("message", { data, origin, source }),
|
|
26
|
+
);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
afterEach(() => {
|
|
30
|
+
document.body.innerHTML = "";
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
describe("createEmbedHost", () => {
|
|
34
|
+
it("invokes onReady / onRefused for pinned messages from the frame", () => {
|
|
35
|
+
const iframe = makeIframe();
|
|
36
|
+
const onReady = vi.fn();
|
|
37
|
+
const onRefused = vi.fn();
|
|
38
|
+
const host = createEmbedHost(iframe, FRAME_ORIGIN, { onReady, onRefused });
|
|
39
|
+
|
|
40
|
+
dispatchMessage(toWire({ type: "ready" }), FRAME_ORIGIN, iframe.contentWindow);
|
|
41
|
+
dispatchMessage(toWire({ type: "refused" }), FRAME_ORIGIN, iframe.contentWindow);
|
|
42
|
+
|
|
43
|
+
expect(onReady).toHaveBeenCalledTimes(1);
|
|
44
|
+
expect(onRefused).toHaveBeenCalledTimes(1);
|
|
45
|
+
host.destroy();
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it("ignores messages from the right origin but the wrong window", () => {
|
|
49
|
+
const iframe = makeIframe();
|
|
50
|
+
const other = makeIframe();
|
|
51
|
+
const onReady = vi.fn();
|
|
52
|
+
const host = createEmbedHost(iframe, FRAME_ORIGIN, { onReady });
|
|
53
|
+
|
|
54
|
+
dispatchMessage(toWire({ type: "ready" }), FRAME_ORIGIN, other.contentWindow);
|
|
55
|
+
|
|
56
|
+
expect(onReady).not.toHaveBeenCalled();
|
|
57
|
+
host.destroy();
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it("ignores messages from the right window but the wrong origin", () => {
|
|
61
|
+
const iframe = makeIframe();
|
|
62
|
+
const onReady = vi.fn();
|
|
63
|
+
const host = createEmbedHost(iframe, FRAME_ORIGIN, { onReady });
|
|
64
|
+
|
|
65
|
+
dispatchMessage(
|
|
66
|
+
toWire({ type: "ready" }),
|
|
67
|
+
"https://evil.example",
|
|
68
|
+
iframe.contentWindow,
|
|
69
|
+
);
|
|
70
|
+
|
|
71
|
+
expect(onReady).not.toHaveBeenCalled();
|
|
72
|
+
host.destroy();
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it("answers hello with init posted to the pinned frame origin", () => {
|
|
76
|
+
const iframe = makeIframe();
|
|
77
|
+
const host = createEmbedHost(iframe, FRAME_ORIGIN);
|
|
78
|
+
// Stubbed (not called through): happy-dom's about:blank frame would
|
|
79
|
+
// reject the cross-origin target that a real chat frame accepts.
|
|
80
|
+
const postMessage = vi
|
|
81
|
+
.spyOn(iframe.contentWindow!, "postMessage")
|
|
82
|
+
.mockImplementation(() => undefined);
|
|
83
|
+
|
|
84
|
+
dispatchMessage(toWire({ type: "hello" }), FRAME_ORIGIN, iframe.contentWindow);
|
|
85
|
+
|
|
86
|
+
expect(postMessage).toHaveBeenCalledWith(
|
|
87
|
+
toWire({ type: "init" }),
|
|
88
|
+
FRAME_ORIGIN,
|
|
89
|
+
);
|
|
90
|
+
host.destroy();
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it("stops reacting after destroy", () => {
|
|
94
|
+
const iframe = makeIframe();
|
|
95
|
+
const onReady = vi.fn();
|
|
96
|
+
const host = createEmbedHost(iframe, FRAME_ORIGIN, { onReady });
|
|
97
|
+
|
|
98
|
+
host.destroy();
|
|
99
|
+
dispatchMessage(toWire({ type: "ready" }), FRAME_ORIGIN, iframe.contentWindow);
|
|
100
|
+
|
|
101
|
+
expect(onReady).not.toHaveBeenCalled();
|
|
102
|
+
});
|
|
103
|
+
});
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
EMBED_PROTOCOL_VERSION,
|
|
5
|
+
EMBED_SOURCE,
|
|
6
|
+
parseFrameMessage,
|
|
7
|
+
parseHostMessage,
|
|
8
|
+
toWire,
|
|
9
|
+
} from "../protocol.js";
|
|
10
|
+
|
|
11
|
+
describe("embed protocol", () => {
|
|
12
|
+
it("stamps every outbound message with source and version", () => {
|
|
13
|
+
expect(toWire({ type: "ready" })).toEqual({
|
|
14
|
+
source: EMBED_SOURCE,
|
|
15
|
+
v: EMBED_PROTOCOL_VERSION,
|
|
16
|
+
type: "ready",
|
|
17
|
+
});
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
it("round-trips every frame->host message type", () => {
|
|
21
|
+
for (const type of ["hello", "ready", "refused"] as const) {
|
|
22
|
+
expect(parseFrameMessage(toWire({ type }))).toEqual({ type });
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
it("round-trips the host->frame init message", () => {
|
|
27
|
+
expect(parseHostMessage(toWire({ type: "init" }))).toEqual({ type: "init" });
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
it("rejects foreign messages on the shared channel", () => {
|
|
31
|
+
// The message channel is page-global: analytics scripts, React DevTools,
|
|
32
|
+
// and other embeds all post here. Anything unstamped must parse to null.
|
|
33
|
+
const foreign: unknown[] = [
|
|
34
|
+
null,
|
|
35
|
+
undefined,
|
|
36
|
+
"string-message",
|
|
37
|
+
42,
|
|
38
|
+
{},
|
|
39
|
+
{ type: "ready" },
|
|
40
|
+
{ source: "other-widget", v: 1, type: "ready" },
|
|
41
|
+
{ source: EMBED_SOURCE, v: 999, type: "ready" },
|
|
42
|
+
{ source: EMBED_SOURCE, v: EMBED_PROTOCOL_VERSION, type: "unknown" },
|
|
43
|
+
{ source: EMBED_SOURCE, v: EMBED_PROTOCOL_VERSION },
|
|
44
|
+
];
|
|
45
|
+
for (const data of foreign) {
|
|
46
|
+
expect(parseFrameMessage(data)).toBeNull();
|
|
47
|
+
expect(parseHostMessage(data)).toBeNull();
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it("does not cross-parse directions", () => {
|
|
52
|
+
expect(parseFrameMessage(toWire({ type: "init" }))).toBeNull();
|
|
53
|
+
expect(parseHostMessage(toWire({ type: "ready" }))).toBeNull();
|
|
54
|
+
});
|
|
55
|
+
});
|
package/src/define.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Side-effect entry for bundler consumers: `import "@stigmer/embed/define"`
|
|
3
|
+
* registers `<stigmer-agent>` on load. Elements still need an app origin —
|
|
4
|
+
* via the `app-origin` attribute or {@link setDefaultAppOrigin} — because a
|
|
5
|
+
* bundled import has no script URL to derive it from.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { defineStigmerAgent } from "./element.js";
|
|
9
|
+
|
|
10
|
+
defineStigmerAgent();
|
package/src/element.ts
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `<stigmer-agent>` custom element — the widget a site owner pastes next
|
|
3
|
+
* to the one-line loader script:
|
|
4
|
+
*
|
|
5
|
+
* ```html
|
|
6
|
+
* <script src="https://app.stigmer.ai/embed.js" async></script>
|
|
7
|
+
* <stigmer-agent org="acme" agent="support-bot"></stigmer-agent>
|
|
8
|
+
* ```
|
|
9
|
+
*
|
|
10
|
+
* The element renders a cross-origin iframe onto the hosted chat page — the
|
|
11
|
+
* iframe is the isolation boundary; no Stigmer UI code runs in the host page.
|
|
12
|
+
* It hides itself when the platform refuses the embed context (origin not in
|
|
13
|
+
* the agent's allowed list), re-dispatching lifecycle signals as
|
|
14
|
+
* `stigmer:ready` / `stigmer:refused` CustomEvents for host-page scripting.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { createEmbedHost, type EmbedHost } from "./host.js";
|
|
18
|
+
|
|
19
|
+
/** Attribute-driven configuration of `<stigmer-agent>`. */
|
|
20
|
+
const OBSERVED_ATTRIBUTES = [
|
|
21
|
+
"org",
|
|
22
|
+
"agent",
|
|
23
|
+
"token",
|
|
24
|
+
"theme",
|
|
25
|
+
"width",
|
|
26
|
+
"height",
|
|
27
|
+
"app-origin",
|
|
28
|
+
] as const;
|
|
29
|
+
|
|
30
|
+
/** Matches the T03 iframe snippet's default footprint. */
|
|
31
|
+
const DEFAULT_WIDTH = "400px";
|
|
32
|
+
const DEFAULT_HEIGHT = "600px";
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* App origin the IIFE loader derives from its own `<script src>` (see
|
|
36
|
+
* `global.ts`). ESM consumers either call {@link setDefaultAppOrigin} or set
|
|
37
|
+
* the `app-origin` attribute per element.
|
|
38
|
+
*/
|
|
39
|
+
let defaultAppOrigin: string | null = null;
|
|
40
|
+
|
|
41
|
+
/** Sets the fallback origin used when an element has no `app-origin` attribute. */
|
|
42
|
+
export function setDefaultAppOrigin(origin: string): void {
|
|
43
|
+
defaultAppOrigin = origin;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export class StigmerAgentElement extends HTMLElement {
|
|
47
|
+
static get observedAttributes(): readonly string[] {
|
|
48
|
+
return OBSERVED_ATTRIBUTES;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
private iframe: HTMLIFrameElement | null = null;
|
|
52
|
+
private host: EmbedHost | null = null;
|
|
53
|
+
|
|
54
|
+
connectedCallback(): void {
|
|
55
|
+
this.attach();
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
disconnectedCallback(): void {
|
|
59
|
+
this.detach();
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
attributeChangedCallback(): void {
|
|
63
|
+
// Identity/config changes rebuild the frame; a chat conversation cannot
|
|
64
|
+
// survive a change of agent, theme, or origin anyway.
|
|
65
|
+
if (this.isConnected) {
|
|
66
|
+
this.attach();
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
private attach(): void {
|
|
71
|
+
this.detach();
|
|
72
|
+
|
|
73
|
+
const org = this.getAttribute("org");
|
|
74
|
+
const agent = this.getAttribute("agent");
|
|
75
|
+
const appOrigin = this.getAttribute("app-origin") ?? defaultAppOrigin;
|
|
76
|
+
if (!org || !agent) {
|
|
77
|
+
console.error("[stigmer-agent] the org and agent attributes are required");
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
if (!appOrigin) {
|
|
81
|
+
console.error(
|
|
82
|
+
"[stigmer-agent] no app origin: load embed.js from your Stigmer app " +
|
|
83
|
+
'origin, or set the app-origin attribute (e.g. app-origin="https://app.stigmer.ai")',
|
|
84
|
+
);
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
this.style.display = "inline-block";
|
|
89
|
+
this.style.width = cssLength(this.getAttribute("width"), DEFAULT_WIDTH);
|
|
90
|
+
this.style.height = cssLength(this.getAttribute("height"), DEFAULT_HEIGHT);
|
|
91
|
+
|
|
92
|
+
const iframe = document.createElement("iframe");
|
|
93
|
+
iframe.src = buildChatUrl(
|
|
94
|
+
appOrigin,
|
|
95
|
+
org,
|
|
96
|
+
agent,
|
|
97
|
+
this.getAttribute("token"),
|
|
98
|
+
this.getAttribute("theme"),
|
|
99
|
+
);
|
|
100
|
+
iframe.title = `Chat with ${agent}`;
|
|
101
|
+
iframe.setAttribute("loading", "lazy");
|
|
102
|
+
iframe.style.cssText =
|
|
103
|
+
"width:100%;height:100%;border:0;border-radius:12px";
|
|
104
|
+
this.appendChild(iframe);
|
|
105
|
+
|
|
106
|
+
this.iframe = iframe;
|
|
107
|
+
this.host = createEmbedHost(iframe, appOrigin, {
|
|
108
|
+
onReady: () => {
|
|
109
|
+
this.dispatchEvent(new CustomEvent("stigmer:ready"));
|
|
110
|
+
},
|
|
111
|
+
onRefused: () => {
|
|
112
|
+
// Hide gracefully rather than erroring — the requirement for embeds
|
|
113
|
+
// on sites the agent owner has not allowed.
|
|
114
|
+
this.style.display = "none";
|
|
115
|
+
this.dispatchEvent(new CustomEvent("stigmer:refused"));
|
|
116
|
+
},
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
private detach(): void {
|
|
121
|
+
this.host?.destroy();
|
|
122
|
+
this.host = null;
|
|
123
|
+
this.iframe?.remove();
|
|
124
|
+
this.iframe = null;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function buildChatUrl(
|
|
129
|
+
appOrigin: string,
|
|
130
|
+
org: string,
|
|
131
|
+
agent: string,
|
|
132
|
+
token: string | null,
|
|
133
|
+
theme: string | null,
|
|
134
|
+
): string {
|
|
135
|
+
const url = new URL(
|
|
136
|
+
`/chat/${encodeURIComponent(org)}/${encodeURIComponent(agent)}`,
|
|
137
|
+
appOrigin,
|
|
138
|
+
);
|
|
139
|
+
// `k` is the platform's link-token parameter (see @stigmer/sdk's
|
|
140
|
+
// LINK_TOKEN_PARAM — not imported: this loader stays dependency-free).
|
|
141
|
+
// Required when the share link is locked; the hosted page forwards it
|
|
142
|
+
// on its guest mint, where the server validates it.
|
|
143
|
+
if (token) {
|
|
144
|
+
url.searchParams.set("k", token);
|
|
145
|
+
}
|
|
146
|
+
const resolved = resolveTheme(theme);
|
|
147
|
+
if (resolved) {
|
|
148
|
+
url.searchParams.set("theme", resolved);
|
|
149
|
+
}
|
|
150
|
+
return url.toString();
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Resolves the theme attribute once, at mount. Deliberately not live-tracked:
|
|
155
|
+
* a theme flip mid-conversation would reload the iframe and destroy the
|
|
156
|
+
* visitor's chat, which is worse than a stale theme.
|
|
157
|
+
*/
|
|
158
|
+
function resolveTheme(theme: string | null): "light" | "dark" | null {
|
|
159
|
+
if (theme === "light" || theme === "dark") return theme;
|
|
160
|
+
if (theme === "auto") {
|
|
161
|
+
return window.matchMedia?.("(prefers-color-scheme: dark)").matches
|
|
162
|
+
? "dark"
|
|
163
|
+
: "light";
|
|
164
|
+
}
|
|
165
|
+
// No attribute: let the hosted page use its own default.
|
|
166
|
+
return null;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function cssLength(value: string | null, fallback: string): string {
|
|
170
|
+
if (!value) return fallback;
|
|
171
|
+
return /^\d+$/.test(value) ? `${value}px` : value;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Registers `<stigmer-agent>`; safe to call more than once. */
|
|
175
|
+
export function defineStigmerAgent(): void {
|
|
176
|
+
if (typeof customElements === "undefined") return;
|
|
177
|
+
if (!customElements.get("stigmer-agent")) {
|
|
178
|
+
customElements.define("stigmer-agent", StigmerAgentElement);
|
|
179
|
+
}
|
|
180
|
+
}
|
package/src/frame.ts
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Frame-side helpers — the half of the embed protocol that runs inside the
|
|
3
|
+
* hosted chat page (`/chat/<org>/<slug>` in `client-apps/web`).
|
|
4
|
+
*
|
|
5
|
+
* The embedding site cannot alter this code (it is served from the Stigmer app
|
|
6
|
+
* origin), so the parent origin discovered here is honest by construction.
|
|
7
|
+
* Every source in the discovery ladder is browser-controlled:
|
|
8
|
+
*
|
|
9
|
+
* 1. `location.ancestorOrigins[0]` — the direct parent's origin (Chromium and
|
|
10
|
+
* WebKit; not implemented in Firefox).
|
|
11
|
+
* 2. `document.referrer` — the parent page URL at iframe load (all browsers,
|
|
12
|
+
* but suppressible via the embedder's Referrer-Policy).
|
|
13
|
+
* 3. The `hello`/`init` postMessage handshake with the loader — the browser
|
|
14
|
+
* stamps `event.origin` on the parent's reply, which no page can forge.
|
|
15
|
+
*
|
|
16
|
+
* When all three fail (a plain iframe with suppressed referrer and no loader),
|
|
17
|
+
* the ladder resolves to {@link OPAQUE_ORIGIN} — the WHATWG serialization of
|
|
18
|
+
* an opaque origin — which the platform refuses whenever the agent's
|
|
19
|
+
* `allowed_origins` list is non-empty (fail closed in strict mode).
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import {
|
|
23
|
+
parseHostMessage,
|
|
24
|
+
toWire,
|
|
25
|
+
type FrameToHostMessage,
|
|
26
|
+
} from "./protocol.js";
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Serialization of an opaque/undiscoverable origin (WHATWG HTML spec).
|
|
30
|
+
* Mirrors `SharingOriginPolicy.OPAQUE_ORIGIN` on the server.
|
|
31
|
+
*/
|
|
32
|
+
export const OPAQUE_ORIGIN = "null";
|
|
33
|
+
|
|
34
|
+
/** How long to wait for the loader's `init` reply before giving up. */
|
|
35
|
+
const HANDSHAKE_TIMEOUT_MS = 1_500;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Whether the page is running inside an iframe. `false` during SSR/prerender
|
|
39
|
+
* (no `window`), so static export never takes the embed path.
|
|
40
|
+
*/
|
|
41
|
+
export function isEmbedded(): boolean {
|
|
42
|
+
if (typeof window === "undefined") return false;
|
|
43
|
+
try {
|
|
44
|
+
return window.self !== window.top;
|
|
45
|
+
} catch {
|
|
46
|
+
// Cross-origin access to window.top throws in some engines — which
|
|
47
|
+
// itself proves the page is framed by a foreign origin.
|
|
48
|
+
return true;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Resolves the embedding page's origin via the discovery ladder above.
|
|
54
|
+
* Only meaningful when {@link isEmbedded} is `true`. Never rejects — an
|
|
55
|
+
* undiscoverable parent resolves to {@link OPAQUE_ORIGIN}.
|
|
56
|
+
*/
|
|
57
|
+
export function resolveParentOrigin(
|
|
58
|
+
timeoutMs: number = HANDSHAKE_TIMEOUT_MS,
|
|
59
|
+
): Promise<string> {
|
|
60
|
+
const ancestor = ancestorOrigin();
|
|
61
|
+
if (ancestor) return Promise.resolve(ancestor);
|
|
62
|
+
|
|
63
|
+
const referrer = referrerOrigin();
|
|
64
|
+
if (referrer) return Promise.resolve(referrer);
|
|
65
|
+
|
|
66
|
+
return handshakeOrigin(timeoutMs);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function ancestorOrigin(): string | null {
|
|
70
|
+
const origins = window.location.ancestorOrigins;
|
|
71
|
+
const direct = origins && origins.length > 0 ? origins[0] : null;
|
|
72
|
+
// An opaque ancestor serializes as "null"; treat it as undiscovered so the
|
|
73
|
+
// remaining rungs get a chance before the opaque fallback.
|
|
74
|
+
return direct && direct !== OPAQUE_ORIGIN ? direct : null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function referrerOrigin(): string | null {
|
|
78
|
+
const referrer = document.referrer;
|
|
79
|
+
if (!referrer) return null;
|
|
80
|
+
try {
|
|
81
|
+
return new URL(referrer).origin;
|
|
82
|
+
} catch {
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Asks the loader for `init` and reads the browser-authentic `event.origin`
|
|
89
|
+
* off the reply. The `hello` is posted to `"*"` because the parent origin is
|
|
90
|
+
* exactly what we do not know yet — it carries no payload, so broadcasting
|
|
91
|
+
* it is safe.
|
|
92
|
+
*/
|
|
93
|
+
function handshakeOrigin(timeoutMs: number): Promise<string> {
|
|
94
|
+
return new Promise((resolveOrigin) => {
|
|
95
|
+
let settled = false;
|
|
96
|
+
const settle = (origin: string) => {
|
|
97
|
+
if (settled) return;
|
|
98
|
+
settled = true;
|
|
99
|
+
window.removeEventListener("message", onMessage);
|
|
100
|
+
clearTimeout(timer);
|
|
101
|
+
resolveOrigin(origin);
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
const onMessage = (event: MessageEvent) => {
|
|
105
|
+
if (event.source !== window.parent) return;
|
|
106
|
+
if (!parseHostMessage(event.data)) return;
|
|
107
|
+
settle(event.origin === "" ? OPAQUE_ORIGIN : event.origin);
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
const timer = setTimeout(() => settle(OPAQUE_ORIGIN), timeoutMs);
|
|
111
|
+
window.addEventListener("message", onMessage);
|
|
112
|
+
window.parent.postMessage(toWire({ type: "hello" }), "*");
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Posts a lifecycle signal to the embedding page's loader.
|
|
118
|
+
*
|
|
119
|
+
* Targets the discovered parent origin when known; `ready`/`refused` carry no
|
|
120
|
+
* payload, so the `"*"` fallback for an opaque parent leaks nothing.
|
|
121
|
+
*/
|
|
122
|
+
export function notifyParent(
|
|
123
|
+
message: FrameToHostMessage,
|
|
124
|
+
parentOrigin: string,
|
|
125
|
+
): void {
|
|
126
|
+
if (!isEmbedded()) return;
|
|
127
|
+
const target = parentOrigin === OPAQUE_ORIGIN ? "*" : parentOrigin;
|
|
128
|
+
window.parent.postMessage(toWire(message), target);
|
|
129
|
+
}
|
package/src/global.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* IIFE entry for the one-line `<script>` loader (`dist/embed.global.js`,
|
|
3
|
+
* served as `embed.js` from the Stigmer app origin).
|
|
4
|
+
*
|
|
5
|
+
* Derives the app origin from its own script URL — the loader is served from
|
|
6
|
+
* the same origin as the hosted chat page, so the snippet needs zero
|
|
7
|
+
* configuration and self-hosted OSS installs work unchanged. If the loader is
|
|
8
|
+
* ever served from a dedicated CDN host instead, embedders set the
|
|
9
|
+
* `app-origin` attribute on `<stigmer-agent>` (or the CDN build bakes in
|
|
10
|
+
* {@link setDefaultAppOrigin}).
|
|
11
|
+
*
|
|
12
|
+
* Must stay a classic script (not `type="module"`): `document.currentScript`
|
|
13
|
+
* is `null` inside module scripts, and it is the only zero-config way to know
|
|
14
|
+
* where the loader came from.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import {
|
|
18
|
+
StigmerAgentElement,
|
|
19
|
+
defineStigmerAgent,
|
|
20
|
+
setDefaultAppOrigin,
|
|
21
|
+
} from "./element.js";
|
|
22
|
+
|
|
23
|
+
const script = document.currentScript;
|
|
24
|
+
if (script instanceof HTMLScriptElement && script.src) {
|
|
25
|
+
setDefaultAppOrigin(new URL(script.src).origin);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
defineStigmerAgent();
|
|
29
|
+
|
|
30
|
+
export { StigmerAgentElement, defineStigmerAgent, setDefaultAppOrigin };
|
package/src/host.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host-side embed controller — the loader half of the protocol, shared by the
|
|
3
|
+
* `<stigmer-agent>` element (and any future framework adapters) so the
|
|
4
|
+
* message-pinning rules live in exactly one place.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { parseFrameMessage, toWire } from "./protocol.js";
|
|
8
|
+
|
|
9
|
+
export interface EmbedHostHandlers {
|
|
10
|
+
/** The widget rendered inside the iframe and may be shown. */
|
|
11
|
+
readonly onReady?: () => void;
|
|
12
|
+
/** The platform refused this embed context; the caller should hide the widget. */
|
|
13
|
+
readonly onRefused?: () => void;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface EmbedHost {
|
|
17
|
+
/** Detaches listeners. Call when the iframe is removed. */
|
|
18
|
+
destroy(): void;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Wires the host side of the embed bridge onto an iframe.
|
|
23
|
+
*
|
|
24
|
+
* Security posture: every inbound message is pinned to both the iframe's
|
|
25
|
+
* `contentWindow` (source) and the expected frame origin, and `init` is only
|
|
26
|
+
* ever posted to that origin. `init` is sent once the iframe loads and again
|
|
27
|
+
* on every `hello` — the frame's script may attach its listener after the
|
|
28
|
+
* load-time send, so the handshake must be answerable at any time.
|
|
29
|
+
*/
|
|
30
|
+
export function createEmbedHost(
|
|
31
|
+
iframe: HTMLIFrameElement,
|
|
32
|
+
frameOrigin: string,
|
|
33
|
+
handlers: EmbedHostHandlers = {},
|
|
34
|
+
): EmbedHost {
|
|
35
|
+
const sendInit = (): void => {
|
|
36
|
+
iframe.contentWindow?.postMessage(toWire({ type: "init" }), frameOrigin);
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const onMessage = (event: MessageEvent): void => {
|
|
40
|
+
if (event.source !== iframe.contentWindow) return;
|
|
41
|
+
if (event.origin !== frameOrigin) return;
|
|
42
|
+
const message = parseFrameMessage(event.data);
|
|
43
|
+
if (!message) return;
|
|
44
|
+
|
|
45
|
+
switch (message.type) {
|
|
46
|
+
case "hello":
|
|
47
|
+
sendInit();
|
|
48
|
+
break;
|
|
49
|
+
case "ready":
|
|
50
|
+
handlers.onReady?.();
|
|
51
|
+
break;
|
|
52
|
+
case "refused":
|
|
53
|
+
handlers.onRefused?.();
|
|
54
|
+
break;
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
window.addEventListener("message", onMessage);
|
|
59
|
+
iframe.addEventListener("load", sendInit);
|
|
60
|
+
|
|
61
|
+
return {
|
|
62
|
+
destroy(): void {
|
|
63
|
+
window.removeEventListener("message", onMessage);
|
|
64
|
+
iframe.removeEventListener("load", sendInit);
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @stigmer/embed — the one-line script embed for shared Stigmer agents.
|
|
3
|
+
*
|
|
4
|
+
* Three consumption forms:
|
|
5
|
+
* - `<script src=".../embed.js">` — the IIFE loader (`./loader` export),
|
|
6
|
+
* auto-registers `<stigmer-agent>` and derives the app origin from its URL.
|
|
7
|
+
* - `import "@stigmer/embed/define"` — bundler-side auto-registration.
|
|
8
|
+
* - `import { ... } from "@stigmer/embed"` — this side-effect-free API, also
|
|
9
|
+
* used by the hosted chat page itself for the frame half of the protocol.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
export {
|
|
13
|
+
EMBED_SOURCE,
|
|
14
|
+
EMBED_PROTOCOL_VERSION,
|
|
15
|
+
parseFrameMessage,
|
|
16
|
+
parseHostMessage,
|
|
17
|
+
toWire,
|
|
18
|
+
type FrameToHostMessage,
|
|
19
|
+
type HostToFrameMessage,
|
|
20
|
+
} from "./protocol.js";
|
|
21
|
+
|
|
22
|
+
export {
|
|
23
|
+
OPAQUE_ORIGIN,
|
|
24
|
+
isEmbedded,
|
|
25
|
+
notifyParent,
|
|
26
|
+
resolveParentOrigin,
|
|
27
|
+
} from "./frame.js";
|
|
28
|
+
|
|
29
|
+
export {
|
|
30
|
+
createEmbedHost,
|
|
31
|
+
type EmbedHost,
|
|
32
|
+
type EmbedHostHandlers,
|
|
33
|
+
} from "./host.js";
|
|
34
|
+
|
|
35
|
+
export {
|
|
36
|
+
StigmerAgentElement,
|
|
37
|
+
defineStigmerAgent,
|
|
38
|
+
setDefaultAppOrigin,
|
|
39
|
+
} from "./element.js";
|
package/src/protocol.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The postMessage wire contract between the embed loader (host page) and the
|
|
3
|
+
* hosted chat page (inside the iframe).
|
|
4
|
+
*
|
|
5
|
+
* This module is the single source of truth for the protocol: the loader
|
|
6
|
+
* (`element.ts` / `host.ts`) and the chat page (`frame.ts`, consumed by
|
|
7
|
+
* `client-apps/web`) both import these constants and parsers — nothing is
|
|
8
|
+
* redeclared elsewhere. Every message is stamped with {@link EMBED_SOURCE}
|
|
9
|
+
* and {@link EMBED_PROTOCOL_VERSION}; receivers must ignore anything that
|
|
10
|
+
* does not match, because the browser `message` channel is shared with the
|
|
11
|
+
* whole page.
|
|
12
|
+
*
|
|
13
|
+
* v1 messages:
|
|
14
|
+
* - host -> frame `init` — carries no payload; its value is the browser-set
|
|
15
|
+
* `event.origin`, which tells the framed page who embeds it (unforgeable).
|
|
16
|
+
* - frame -> host `hello` — asks the host to (re)send `init`, for the case
|
|
17
|
+
* where the frame's listener attaches after the host's load-time `init`.
|
|
18
|
+
* - frame -> host `ready` — the widget rendered and may be shown.
|
|
19
|
+
* - frame -> host `refused` — the platform refused this embed context (origin
|
|
20
|
+
* not allowed); the loader hides the element gracefully.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
export const EMBED_SOURCE = "stigmer-embed";
|
|
24
|
+
export const EMBED_PROTOCOL_VERSION = 1;
|
|
25
|
+
|
|
26
|
+
/** Messages sent by the hosted chat page (frame) to the embedding page (host). */
|
|
27
|
+
export type FrameToHostMessage =
|
|
28
|
+
| { readonly type: "hello" }
|
|
29
|
+
| { readonly type: "ready" }
|
|
30
|
+
| { readonly type: "refused" };
|
|
31
|
+
|
|
32
|
+
/** Messages sent by the embedding page (host) to the hosted chat page (frame). */
|
|
33
|
+
export type HostToFrameMessage = { readonly type: "init" };
|
|
34
|
+
|
|
35
|
+
interface Envelope {
|
|
36
|
+
readonly source: typeof EMBED_SOURCE;
|
|
37
|
+
readonly v: typeof EMBED_PROTOCOL_VERSION;
|
|
38
|
+
readonly type: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Wraps a message in the versioned envelope for `postMessage`. */
|
|
42
|
+
export function toWire(
|
|
43
|
+
message: FrameToHostMessage | HostToFrameMessage,
|
|
44
|
+
): Envelope {
|
|
45
|
+
return { source: EMBED_SOURCE, v: EMBED_PROTOCOL_VERSION, ...message };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function parseEnvelope(data: unknown): Envelope | null {
|
|
49
|
+
if (typeof data !== "object" || data === null) return null;
|
|
50
|
+
const candidate = data as Record<string, unknown>;
|
|
51
|
+
if (candidate.source !== EMBED_SOURCE) return null;
|
|
52
|
+
if (candidate.v !== EMBED_PROTOCOL_VERSION) return null;
|
|
53
|
+
if (typeof candidate.type !== "string") return null;
|
|
54
|
+
return candidate as unknown as Envelope;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Parses an inbound message on the host side; `null` for foreign messages. */
|
|
58
|
+
export function parseFrameMessage(data: unknown): FrameToHostMessage | null {
|
|
59
|
+
const envelope = parseEnvelope(data);
|
|
60
|
+
if (!envelope) return null;
|
|
61
|
+
switch (envelope.type) {
|
|
62
|
+
case "hello":
|
|
63
|
+
case "ready":
|
|
64
|
+
case "refused":
|
|
65
|
+
return { type: envelope.type };
|
|
66
|
+
default:
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Parses an inbound message on the frame side; `null` for foreign messages. */
|
|
72
|
+
export function parseHostMessage(data: unknown): HostToFrameMessage | null {
|
|
73
|
+
const envelope = parseEnvelope(data);
|
|
74
|
+
if (!envelope) return null;
|
|
75
|
+
return envelope.type === "init" ? { type: "init" } : null;
|
|
76
|
+
}
|