@first-to-fly/crm-sdk 1.0.1 → 1.1.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/README.md CHANGED
@@ -1,6 +1,13 @@
1
1
  # @first-to-fly/crm-sdk
2
2
 
3
- CRM Embeddable App SDK — enables communication between third-party iframes and the CRM host.
3
+ The CRM SDK supports **two integration directions**:
4
+
5
+ | You want to… | Import | Runs in |
6
+ |---|---|---|
7
+ | **Embed an app _inside_ the CRM** (guest app in the CRM's iframe) | `@first-to-fly/crm-sdk` | browser |
8
+ | **Embed _the CRM_ inside your SaaS** (host the CRM's iframe) | `@first-to-fly/crm-sdk/embed-host` + `@first-to-fly/crm-sdk/embed-server` | browser + server |
9
+
10
+ The first is documented under [Quick Start](#quick-start). The second — the proxy-free, cookie-less embed — is under [Embedding the CRM in your SaaS](#embedding-the-crm-in-your-saas).
4
11
 
5
12
  ## Installation
6
13
 
@@ -121,6 +128,113 @@ Messages include `{ source: 'crm-host', type, ... }`:
121
128
  | `context_update` | Sent when context changes, contains updated `context` |
122
129
  | `response` | Response to an `invoke`, contains `invoke_id` and `result` or `error` |
123
130
 
131
+ ## Embedding the CRM in your SaaS
132
+
133
+ Render the CRM as a cross-origin iframe in your app, authenticated **without cookies**
134
+ and **without a reverse proxy**. You mint a short-lived signed assertion server-side,
135
+ exchange it for a CRM bearer, and hand that bearer to the iframe over a secure
136
+ `MessageChannel`. Two modules do the heavy lifting: `embed-server` (Node/Bun) and
137
+ `embed-host` (browser).
138
+
139
+ ### How it works
140
+
141
+ ```
142
+ [your server] [browser] [CRM]
143
+ createEmbedSession(user) ─mint+exchange─▶ CRM bearer
144
+ │
145
+ createCrmEmbedHost({ iframe, getBearer })
146
+ │ ready → channel-init → ack
147
+ └──────── auth-tokens ─────────▶ CRM iframe loads
148
+ ```
149
+
150
+ ### One-time setup (with the CRM team)
151
+
152
+ 1. Generate an RS256 (or ES256) key pair. Keep the private key on your server.
153
+ 2. Serve your **public JWKS** at a public `https` URL (see `getCrmEmbedJwks` below).
154
+ 3. Give the CRM team your **`client_id`** (issuer) and **JWKS URL**. They register your
155
+ app and enable it. An admin in the CRM binds your **`org_id`** to a CRM workspace.
156
+ 4. Ask the CRM team for their **exchange base URL** and **embed origin**.
157
+
158
+ ### Server: mint + exchange
159
+
160
+ ```typescript
161
+ import { createEmbedSession, getCrmEmbedJwks } from '@first-to-fly/crm-sdk/embed-server';
162
+
163
+ const config = {
164
+ iss: process.env.CRM_CLIENT_ID!, // == the client_id the CRM registered
165
+ privateKeyPem: process.env.CRM_PRIVATE_KEY_PEM!,
166
+ publicKeyPem: process.env.CRM_PUBLIC_KEY_PEM!,
167
+ // alg: 'RS256' (default) or 'ES256'
168
+ };
169
+
170
+ // Endpoint your frontend calls to (re)obtain a CRM bearer:
171
+ app.post('/api/crm/session', async (req, res) => {
172
+ const user = req.user; // your authenticated user
173
+ const session = await createEmbedSession(
174
+ {
175
+ sub: user.id, // stable id in YOUR system
176
+ email: user.email,
177
+ requestedRole: 'admin', // CRM clamps to the install's max_role
178
+ orgId: user.orgId, // CRM resolves the workspace from this
179
+ fullName: user.name, // optional
180
+ avatarUrl: user.avatar, // optional
181
+ },
182
+ config,
183
+ { crmBaseUrl: process.env.CRM_BASE_URL! }, // e.g. https://api.crm.example.com
184
+ );
185
+ // { accessToken, expiresIn, workspaceId, user, role }
186
+ res.json(session);
187
+ });
188
+
189
+ // Publish your public JWKS so the CRM can verify your assertions:
190
+ app.get('/crm-embed/jwks', async (_req, res) => res.json(await getCrmEmbedJwks(config)));
191
+ ```
192
+
193
+ Prefer to split minting and exchange? Use `mintCrmAssertion(input, config)` and
194
+ `exchangeAssertion(assertion, { crmBaseUrl })` directly. A rejected exchange throws
195
+ `CrmExchangeError` with `.status` and `.code` (e.g. `IDENTITY_CONFLICT`,
196
+ `WORKSPACE_NOT_OWNED`).
197
+
198
+ ### Browser: host the iframe
199
+
200
+ ```typescript
201
+ import { createCrmEmbedHost, buildCrmEmbedUrl } from '@first-to-fly/crm-sdk/embed-host';
202
+
203
+ const CRM_ORIGIN = 'https://app.crm.example.com';
204
+
205
+ async function getSession() {
206
+ const res = await fetch('/api/crm/session', { method: 'POST' });
207
+ return res.json(); // { accessToken, workspaceId, ... }
208
+ }
209
+
210
+ const { workspaceId } = await getSession();
211
+ const iframe = document.querySelector('#crm') as HTMLIFrameElement;
212
+ iframe.src = buildCrmEmbedUrl(CRM_ORIGIN, workspaceId);
213
+
214
+ const host = createCrmEmbedHost({
215
+ iframe,
216
+ crmOrigin: CRM_ORIGIN,
217
+ getBearer: async () => ({ accessToken: (await getSession()).accessToken }),
218
+ onRouteChange: (path) => console.log('CRM navigated to', path),
219
+ onError: (err) => console.error(err),
220
+ });
221
+
222
+ // Drive the CRM from your own nav:
223
+ host.navigate('/contacts');
224
+
225
+ // On unmount:
226
+ host.dispose();
227
+ ```
228
+
229
+ ### Requirements & gotchas
230
+
231
+ - `getBearer` is called on connect **and** whenever the CRM's session expires — always
232
+ return a fresh bearer (call your `/session` endpoint again).
233
+ - `crmOrigin` must exactly match the iframe's origin, and the CRM must allow your origin
234
+ in its `frame-ancestors` (the CRM team configures this).
235
+ - Assertions are single-use and live ≤120s — always mint fresh; never cache one.
236
+ - `jose` is a peer dependency, required only by `embed-server`: `npm i jose`.
237
+
124
238
  ## License
125
239
 
126
240
  MIT
@@ -0,0 +1,2 @@
1
+ "use strict";var d=Object.defineProperty;var u=Object.getOwnPropertyDescriptor;var p=Object.getOwnPropertyNames;var f=Object.prototype.hasOwnProperty;var y=(e,t)=>{for(var i in t)d(e,i,{get:t[i],enumerable:!0})},v=(e,t,i,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of p(t))!f.call(e,n)&&n!==i&&d(e,n,{get:()=>t[n],enumerable:!(o=u(t,n))||o.enumerable});return e};var C=e=>v(d({},"__esModule",{value:!0}),e);var b={};y(b,{buildCrmEmbedUrl:()=>w,createCrmEmbedHost:()=>E});module.exports=C(b);function M(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function w(e,t){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(t)}`}function E(e){let t=e.windowTarget??window,i=e.createChannel??(()=>new MessageChannel),o=e.devAllowAnyOrigin?"*":e.crmOrigin,n=null,a="",c=!1;async function g(){try{let r=await e.getBearer();n?.postMessage({type:"auth-tokens",accessToken:r.accessToken,refreshToken:r.refreshToken??""})}catch(r){e.onError?.(r)}}function l(r){let s=r.data;if(s)if(s.type==="channel-ack"){if(s.nonce!==a)return;g()}else s.type==="route-change"?e.onRouteChange?.(s.path):s.type==="resize"?e.onResize?.(s.height):s.type==="session-expired"&&(g(),n?.postMessage({type:"session-refreshed"}))}function h(){n?.close();let r=i();n=r.port1,a=globalThis.crypto?.randomUUID?.()??`n-${String(Math.random()).slice(2)}`,n.onmessage=l,n.start?.(),e.iframe.contentWindow?.postMessage({type:"channel-init",nonce:a},o,[r.port2])}function m(r){c||r.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&r.origin!==e.crmOrigin||M(r.data)&&h())}return t.addEventListener("message",m),{navigate(r){n?.postMessage({type:"navigate",path:r})},dispose(){c=!0,t.removeEventListener("message",m),n?.close(),n=null}}}0&&(module.exports={buildCrmEmbedUrl,createCrmEmbedHost});
2
+ //# sourceMappingURL=embed-host.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/embed-host.ts"],"sourcesContent":["/**\n * CRM Embed Host SDK (browser side).\n *\n * Use this in YOUR SaaS to embed the First To Fly CRM as a cross-origin iframe,\n * authenticated WITHOUT cookies. You render an <iframe> pointing at the CRM's\n * embed URL, and this helper runs the MessageChannel handshake that hands the\n * CRM a short-lived bearer token you mint server-side (see ./embed-server).\n *\n * Handshake (this side is the HOST/parent):\n * 1. CRM iframe posts { source: 'crm-embed', type: 'ready' }\n * 2. host replies { type: 'channel-init', nonce } + a MessagePort\n * 3. CRM iframe replies { type: 'channel-ack', nonce } on that port\n * 4. host sends { type: 'auth-tokens', accessToken } (your CRM bearer)\n * 5. CRM iframe streams { type: 'route-change' | 'resize' | 'session-expired' }\n * - on 'session-expired' the host re-fetches a bearer and re-sends it.\n *\n * @packageDocumentation\n */\n\n/** A CRM bearer (from the assertion exchange). refreshToken is unused today. */\nexport interface CrmBearer {\n accessToken: string;\n refreshToken?: string;\n}\n\nexport interface CrmEmbedHostOptions {\n /** The <iframe> element that loads the CRM embed URL. */\n iframe: HTMLIFrameElement;\n /**\n * Origin the CRM is served from — the postMessage targetOrigin, e.g.\n * \"https://app.crm.example.com\". Must match the iframe's origin exactly.\n */\n crmOrigin: string;\n /**\n * Returns a fresh CRM bearer. Called once on connect and again whenever the\n * CRM reports its session expired. Typically calls your own backend endpoint\n * that runs createEmbedSession() (see ./embed-server).\n */\n getBearer: () => Promise<CrmBearer>;\n /** Called when the CRM navigates internally (e.g. \"/contacts\"). */\n onRouteChange?: (path: string) => void;\n /** Called when the CRM reports its content height (for iframe auto-resize). */\n onResize?: (height: number) => void;\n /** Called on any handshake/bearer error. */\n onError?: (err: unknown) => void;\n /**\n * DEV ONLY: accept the CRM's `ready` from any origin (cross-port localhost).\n * NEVER enable in production — it disables the origin check.\n */\n devAllowAnyOrigin?: boolean;\n /** Test seam — defaults to the global MessageChannel. */\n createChannel?: () => MessageChannel;\n /** Test seam — defaults to `window` as the message-event target. */\n windowTarget?: Pick<Window, 'addEventListener' | 'removeEventListener'>;\n}\n\nexport interface CrmEmbedHost {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n /** Tear down the channel and listeners. Call on unmount. */\n dispose: () => void;\n}\n\ninterface CrmReadyMessage { source: 'crm-embed'; type: 'ready' }\ntype ChildMessage =\n | { type: 'channel-ack'; nonce: string }\n | { type: 'route-change'; path: string }\n | { type: 'resize'; height: number }\n | { type: 'session-expired' };\n\nfunction isReady(data: unknown): data is CrmReadyMessage {\n return !!data && typeof data === 'object'\n && (data as CrmReadyMessage).source === 'crm-embed'\n && (data as CrmReadyMessage).type === 'ready';\n}\n\n/**\n * Build the CRM embed iframe URL. The CRM resolves the tenant from the bearer,\n * so the workspaceId segment is only a routing hint.\n *\n * buildCrmEmbedUrl('https://app.crm.example.com', 'ws_123')\n * => 'https://app.crm.example.com/embed/ws_123'\n */\nexport function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): string {\n return `${crmOrigin.replace(/\\/$/, '')}/embed/${encodeURIComponent(workspaceId)}`;\n}\n\n/**\n * Wire the host side of the CRM embed. Attach this once the iframe is in the DOM.\n * Returns a handle with `navigate()` and `dispose()`.\n */\nexport function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost {\n const target = opts.windowTarget ?? window;\n const makeChannel = opts.createChannel ?? (() => new MessageChannel());\n const targetOrigin = opts.devAllowAnyOrigin ? '*' : opts.crmOrigin;\n\n let port: MessagePort | null = null;\n let nonce = '';\n let disposed = false;\n\n async function deliverBearer(): Promise<void> {\n try {\n const bearer = await opts.getBearer();\n port?.postMessage({\n type: 'auth-tokens',\n accessToken: bearer.accessToken,\n refreshToken: bearer.refreshToken ?? '',\n });\n } catch (err) {\n opts.onError?.(err);\n }\n }\n\n function onPortMessage(e: MessageEvent<ChildMessage>): void {\n const data = e.data;\n if (!data) return;\n if (data.type === 'channel-ack') {\n if (data.nonce !== nonce) return; // stale/forged ack\n void deliverBearer();\n } else if (data.type === 'route-change') {\n opts.onRouteChange?.(data.path);\n } else if (data.type === 'resize') {\n opts.onResize?.(data.height);\n } else if (data.type === 'session-expired') {\n // Embed sessions renew by re-minting (no refresh-token flow).\n void deliverBearer();\n port?.postMessage({ type: 'session-refreshed' });\n }\n }\n\n function startHandshake(): void {\n port?.close();\n const channel = makeChannel();\n port = channel.port1;\n nonce = globalThis.crypto?.randomUUID?.() ?? `n-${String(Math.random()).slice(2)}`;\n port.onmessage = onPortMessage;\n port.start?.();\n opts.iframe.contentWindow?.postMessage(\n { type: 'channel-init', nonce },\n targetOrigin,\n [channel.port2],\n );\n }\n\n function onWindowMessage(event: MessageEvent): void {\n if (disposed) return;\n if (event.source !== opts.iframe.contentWindow) return;\n if (!opts.devAllowAnyOrigin && event.origin !== opts.crmOrigin) return;\n if (isReady(event.data)) startHandshake();\n }\n\n target.addEventListener('message', onWindowMessage as EventListener);\n\n return {\n navigate(path: string): void {\n port?.postMessage({ type: 'navigate', path });\n },\n dispose(): void {\n disposed = true;\n target.removeEventListener('message', onWindowMessage as EventListener);\n port?.close();\n port = null;\n },\n };\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,sBAAAE,EAAA,uBAAAC,IAAA,eAAAC,EAAAJ,GAsEA,SAASK,EAAQC,EAAwC,CACvD,MAAO,CAAC,CAACA,GAAQ,OAAOA,GAAS,UAC3BA,EAAyB,SAAW,aACpCA,EAAyB,OAAS,OAC1C,CASO,SAASJ,EAAiBK,EAAmBC,EAA6B,CAC/E,MAAO,GAAGD,EAAU,QAAQ,MAAO,EAAE,CAAC,UAAU,mBAAmBC,CAAW,CAAC,EACjF,CAMO,SAASL,EAAmBM,EAAyC,CAC1E,IAAMC,EAASD,EAAK,cAAgB,OAC9BE,EAAcF,EAAK,gBAAkB,IAAM,IAAI,gBAC/CG,EAAeH,EAAK,kBAAoB,IAAMA,EAAK,UAErDI,EAA2B,KAC3BC,EAAQ,GACRC,EAAW,GAEf,eAAeC,GAA+B,CAC5C,GAAI,CACF,IAAMC,EAAS,MAAMR,EAAK,UAAU,EACpCI,GAAM,YAAY,CAChB,KAAM,cACN,YAAaI,EAAO,YACpB,aAAcA,EAAO,cAAgB,EACvC,CAAC,CACH,OAASC,EAAK,CACZT,EAAK,UAAUS,CAAG,CACpB,CACF,CAEA,SAASC,EAAcC,EAAqC,CAC1D,IAAMd,EAAOc,EAAE,KACf,GAAKd,EACL,GAAIA,EAAK,OAAS,cAAe,CAC/B,GAAIA,EAAK,QAAUQ,EAAO,OACrBE,EAAc,CACrB,MAAWV,EAAK,OAAS,eACvBG,EAAK,gBAAgBH,EAAK,IAAI,EACrBA,EAAK,OAAS,SACvBG,EAAK,WAAWH,EAAK,MAAM,EAClBA,EAAK,OAAS,oBAElBU,EAAc,EACnBH,GAAM,YAAY,CAAE,KAAM,mBAAoB,CAAC,EAEnD,CAEA,SAASQ,GAAuB,CAC9BR,GAAM,MAAM,EACZ,IAAMS,EAAUX,EAAY,EAC5BE,EAAOS,EAAQ,MACfR,EAAQ,WAAW,QAAQ,aAAa,GAAK,KAAK,OAAO,KAAK,OAAO,CAAC,EAAE,MAAM,CAAC,CAAC,GAChFD,EAAK,UAAYM,EACjBN,EAAK,QAAQ,EACbJ,EAAK,OAAO,eAAe,YACzB,CAAE,KAAM,eAAgB,MAAAK,CAAM,EAC9BF,EACA,CAACU,EAAQ,KAAK,CAChB,CACF,CAEA,SAASC,EAAgBC,EAA2B,CAC9CT,GACAS,EAAM,SAAWf,EAAK,OAAO,gBAC7B,CAACA,EAAK,mBAAqBe,EAAM,SAAWf,EAAK,WACjDJ,EAAQmB,EAAM,IAAI,GAAGH,EAAe,EAC1C,CAEA,OAAAX,EAAO,iBAAiB,UAAWa,CAAgC,EAE5D,CACL,SAASE,EAAoB,CAC3BZ,GAAM,YAAY,CAAE,KAAM,WAAY,KAAAY,CAAK,CAAC,CAC9C,EACA,SAAgB,CACdV,EAAW,GACXL,EAAO,oBAAoB,UAAWa,CAAgC,EACtEV,GAAM,MAAM,EACZA,EAAO,IACT,CACF,CACF","names":["embed_host_exports","__export","buildCrmEmbedUrl","createCrmEmbedHost","__toCommonJS","isReady","data","crmOrigin","workspaceId","opts","target","makeChannel","targetOrigin","port","nonce","disposed","deliverBearer","bearer","err","onPortMessage","e","startHandshake","channel","onWindowMessage","event","path"]}
@@ -0,0 +1,74 @@
1
+ /**
2
+ * CRM Embed Host SDK (browser side).
3
+ *
4
+ * Use this in YOUR SaaS to embed the First To Fly CRM as a cross-origin iframe,
5
+ * authenticated WITHOUT cookies. You render an <iframe> pointing at the CRM's
6
+ * embed URL, and this helper runs the MessageChannel handshake that hands the
7
+ * CRM a short-lived bearer token you mint server-side (see ./embed-server).
8
+ *
9
+ * Handshake (this side is the HOST/parent):
10
+ * 1. CRM iframe posts { source: 'crm-embed', type: 'ready' }
11
+ * 2. host replies { type: 'channel-init', nonce } + a MessagePort
12
+ * 3. CRM iframe replies { type: 'channel-ack', nonce } on that port
13
+ * 4. host sends { type: 'auth-tokens', accessToken } (your CRM bearer)
14
+ * 5. CRM iframe streams { type: 'route-change' | 'resize' | 'session-expired' }
15
+ * - on 'session-expired' the host re-fetches a bearer and re-sends it.
16
+ *
17
+ * @packageDocumentation
18
+ */
19
+ /** A CRM bearer (from the assertion exchange). refreshToken is unused today. */
20
+ interface CrmBearer {
21
+ accessToken: string;
22
+ refreshToken?: string;
23
+ }
24
+ interface CrmEmbedHostOptions {
25
+ /** The <iframe> element that loads the CRM embed URL. */
26
+ iframe: HTMLIFrameElement;
27
+ /**
28
+ * Origin the CRM is served from — the postMessage targetOrigin, e.g.
29
+ * "https://app.crm.example.com". Must match the iframe's origin exactly.
30
+ */
31
+ crmOrigin: string;
32
+ /**
33
+ * Returns a fresh CRM bearer. Called once on connect and again whenever the
34
+ * CRM reports its session expired. Typically calls your own backend endpoint
35
+ * that runs createEmbedSession() (see ./embed-server).
36
+ */
37
+ getBearer: () => Promise<CrmBearer>;
38
+ /** Called when the CRM navigates internally (e.g. "/contacts"). */
39
+ onRouteChange?: (path: string) => void;
40
+ /** Called when the CRM reports its content height (for iframe auto-resize). */
41
+ onResize?: (height: number) => void;
42
+ /** Called on any handshake/bearer error. */
43
+ onError?: (err: unknown) => void;
44
+ /**
45
+ * DEV ONLY: accept the CRM's `ready` from any origin (cross-port localhost).
46
+ * NEVER enable in production — it disables the origin check.
47
+ */
48
+ devAllowAnyOrigin?: boolean;
49
+ /** Test seam — defaults to the global MessageChannel. */
50
+ createChannel?: () => MessageChannel;
51
+ /** Test seam — defaults to `window` as the message-event target. */
52
+ windowTarget?: Pick<Window, 'addEventListener' | 'removeEventListener'>;
53
+ }
54
+ interface CrmEmbedHost {
55
+ /** Tell the CRM to navigate to a sub-path, e.g. "/contacts" or "/leads/123". */
56
+ navigate: (path: string) => void;
57
+ /** Tear down the channel and listeners. Call on unmount. */
58
+ dispose: () => void;
59
+ }
60
+ /**
61
+ * Build the CRM embed iframe URL. The CRM resolves the tenant from the bearer,
62
+ * so the workspaceId segment is only a routing hint.
63
+ *
64
+ * buildCrmEmbedUrl('https://app.crm.example.com', 'ws_123')
65
+ * => 'https://app.crm.example.com/embed/ws_123'
66
+ */
67
+ declare function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): string;
68
+ /**
69
+ * Wire the host side of the CRM embed. Attach this once the iframe is in the DOM.
70
+ * Returns a handle with `navigate()` and `dispose()`.
71
+ */
72
+ declare function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost;
73
+
74
+ export { type CrmBearer, type CrmEmbedHost, type CrmEmbedHostOptions, buildCrmEmbedUrl, createCrmEmbedHost };
@@ -0,0 +1,74 @@
1
+ /**
2
+ * CRM Embed Host SDK (browser side).
3
+ *
4
+ * Use this in YOUR SaaS to embed the First To Fly CRM as a cross-origin iframe,
5
+ * authenticated WITHOUT cookies. You render an <iframe> pointing at the CRM's
6
+ * embed URL, and this helper runs the MessageChannel handshake that hands the
7
+ * CRM a short-lived bearer token you mint server-side (see ./embed-server).
8
+ *
9
+ * Handshake (this side is the HOST/parent):
10
+ * 1. CRM iframe posts { source: 'crm-embed', type: 'ready' }
11
+ * 2. host replies { type: 'channel-init', nonce } + a MessagePort
12
+ * 3. CRM iframe replies { type: 'channel-ack', nonce } on that port
13
+ * 4. host sends { type: 'auth-tokens', accessToken } (your CRM bearer)
14
+ * 5. CRM iframe streams { type: 'route-change' | 'resize' | 'session-expired' }
15
+ * - on 'session-expired' the host re-fetches a bearer and re-sends it.
16
+ *
17
+ * @packageDocumentation
18
+ */
19
+ /** A CRM bearer (from the assertion exchange). refreshToken is unused today. */
20
+ interface CrmBearer {
21
+ accessToken: string;
22
+ refreshToken?: string;
23
+ }
24
+ interface CrmEmbedHostOptions {
25
+ /** The <iframe> element that loads the CRM embed URL. */
26
+ iframe: HTMLIFrameElement;
27
+ /**
28
+ * Origin the CRM is served from — the postMessage targetOrigin, e.g.
29
+ * "https://app.crm.example.com". Must match the iframe's origin exactly.
30
+ */
31
+ crmOrigin: string;
32
+ /**
33
+ * Returns a fresh CRM bearer. Called once on connect and again whenever the
34
+ * CRM reports its session expired. Typically calls your own backend endpoint
35
+ * that runs createEmbedSession() (see ./embed-server).
36
+ */
37
+ getBearer: () => Promise<CrmBearer>;
38
+ /** Called when the CRM navigates internally (e.g. "/contacts"). */
39
+ onRouteChange?: (path: string) => void;
40
+ /** Called when the CRM reports its content height (for iframe auto-resize). */
41
+ onResize?: (height: number) => void;
42
+ /** Called on any handshake/bearer error. */
43
+ onError?: (err: unknown) => void;
44
+ /**
45
+ * DEV ONLY: accept the CRM's `ready` from any origin (cross-port localhost).
46
+ * NEVER enable in production — it disables the origin check.
47
+ */
48
+ devAllowAnyOrigin?: boolean;
49
+ /** Test seam — defaults to the global MessageChannel. */
50
+ createChannel?: () => MessageChannel;
51
+ /** Test seam — defaults to `window` as the message-event target. */
52
+ windowTarget?: Pick<Window, 'addEventListener' | 'removeEventListener'>;
53
+ }
54
+ interface CrmEmbedHost {
55
+ /** Tell the CRM to navigate to a sub-path, e.g. "/contacts" or "/leads/123". */
56
+ navigate: (path: string) => void;
57
+ /** Tear down the channel and listeners. Call on unmount. */
58
+ dispose: () => void;
59
+ }
60
+ /**
61
+ * Build the CRM embed iframe URL. The CRM resolves the tenant from the bearer,
62
+ * so the workspaceId segment is only a routing hint.
63
+ *
64
+ * buildCrmEmbedUrl('https://app.crm.example.com', 'ws_123')
65
+ * => 'https://app.crm.example.com/embed/ws_123'
66
+ */
67
+ declare function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): string;
68
+ /**
69
+ * Wire the host side of the CRM embed. Attach this once the iframe is in the DOM.
70
+ * Returns a handle with `navigate()` and `dispose()`.
71
+ */
72
+ declare function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost;
73
+
74
+ export { type CrmBearer, type CrmEmbedHost, type CrmEmbedHostOptions, buildCrmEmbedUrl, createCrmEmbedHost };
@@ -0,0 +1,2 @@
1
+ function h(e){return!!e&&typeof e=="object"&&e.source==="crm-embed"&&e.type==="ready"}function u(e,s){return`${e.replace(/\/$/,"")}/embed/${encodeURIComponent(s)}`}function p(e){let s=e.windowTarget??window,c=e.createChannel??(()=>new MessageChannel),g=e.devAllowAnyOrigin?"*":e.crmOrigin,r=null,i="",o=!1;async function a(){try{let n=await e.getBearer();r?.postMessage({type:"auth-tokens",accessToken:n.accessToken,refreshToken:n.refreshToken??""})}catch(n){e.onError?.(n)}}function m(n){let t=n.data;if(t)if(t.type==="channel-ack"){if(t.nonce!==i)return;a()}else t.type==="route-change"?e.onRouteChange?.(t.path):t.type==="resize"?e.onResize?.(t.height):t.type==="session-expired"&&(a(),r?.postMessage({type:"session-refreshed"}))}function l(){r?.close();let n=c();r=n.port1,i=globalThis.crypto?.randomUUID?.()??`n-${String(Math.random()).slice(2)}`,r.onmessage=m,r.start?.(),e.iframe.contentWindow?.postMessage({type:"channel-init",nonce:i},g,[n.port2])}function d(n){o||n.source===e.iframe.contentWindow&&(!e.devAllowAnyOrigin&&n.origin!==e.crmOrigin||h(n.data)&&l())}return s.addEventListener("message",d),{navigate(n){r?.postMessage({type:"navigate",path:n})},dispose(){o=!0,s.removeEventListener("message",d),r?.close(),r=null}}}export{u as buildCrmEmbedUrl,p as createCrmEmbedHost};
2
+ //# sourceMappingURL=embed-host.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/embed-host.ts"],"sourcesContent":["/**\n * CRM Embed Host SDK (browser side).\n *\n * Use this in YOUR SaaS to embed the First To Fly CRM as a cross-origin iframe,\n * authenticated WITHOUT cookies. You render an <iframe> pointing at the CRM's\n * embed URL, and this helper runs the MessageChannel handshake that hands the\n * CRM a short-lived bearer token you mint server-side (see ./embed-server).\n *\n * Handshake (this side is the HOST/parent):\n * 1. CRM iframe posts { source: 'crm-embed', type: 'ready' }\n * 2. host replies { type: 'channel-init', nonce } + a MessagePort\n * 3. CRM iframe replies { type: 'channel-ack', nonce } on that port\n * 4. host sends { type: 'auth-tokens', accessToken } (your CRM bearer)\n * 5. CRM iframe streams { type: 'route-change' | 'resize' | 'session-expired' }\n * - on 'session-expired' the host re-fetches a bearer and re-sends it.\n *\n * @packageDocumentation\n */\n\n/** A CRM bearer (from the assertion exchange). refreshToken is unused today. */\nexport interface CrmBearer {\n accessToken: string;\n refreshToken?: string;\n}\n\nexport interface CrmEmbedHostOptions {\n /** The <iframe> element that loads the CRM embed URL. */\n iframe: HTMLIFrameElement;\n /**\n * Origin the CRM is served from — the postMessage targetOrigin, e.g.\n * \"https://app.crm.example.com\". Must match the iframe's origin exactly.\n */\n crmOrigin: string;\n /**\n * Returns a fresh CRM bearer. Called once on connect and again whenever the\n * CRM reports its session expired. Typically calls your own backend endpoint\n * that runs createEmbedSession() (see ./embed-server).\n */\n getBearer: () => Promise<CrmBearer>;\n /** Called when the CRM navigates internally (e.g. \"/contacts\"). */\n onRouteChange?: (path: string) => void;\n /** Called when the CRM reports its content height (for iframe auto-resize). */\n onResize?: (height: number) => void;\n /** Called on any handshake/bearer error. */\n onError?: (err: unknown) => void;\n /**\n * DEV ONLY: accept the CRM's `ready` from any origin (cross-port localhost).\n * NEVER enable in production — it disables the origin check.\n */\n devAllowAnyOrigin?: boolean;\n /** Test seam — defaults to the global MessageChannel. */\n createChannel?: () => MessageChannel;\n /** Test seam — defaults to `window` as the message-event target. */\n windowTarget?: Pick<Window, 'addEventListener' | 'removeEventListener'>;\n}\n\nexport interface CrmEmbedHost {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n /** Tear down the channel and listeners. Call on unmount. */\n dispose: () => void;\n}\n\ninterface CrmReadyMessage { source: 'crm-embed'; type: 'ready' }\ntype ChildMessage =\n | { type: 'channel-ack'; nonce: string }\n | { type: 'route-change'; path: string }\n | { type: 'resize'; height: number }\n | { type: 'session-expired' };\n\nfunction isReady(data: unknown): data is CrmReadyMessage {\n return !!data && typeof data === 'object'\n && (data as CrmReadyMessage).source === 'crm-embed'\n && (data as CrmReadyMessage).type === 'ready';\n}\n\n/**\n * Build the CRM embed iframe URL. The CRM resolves the tenant from the bearer,\n * so the workspaceId segment is only a routing hint.\n *\n * buildCrmEmbedUrl('https://app.crm.example.com', 'ws_123')\n * => 'https://app.crm.example.com/embed/ws_123'\n */\nexport function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): string {\n return `${crmOrigin.replace(/\\/$/, '')}/embed/${encodeURIComponent(workspaceId)}`;\n}\n\n/**\n * Wire the host side of the CRM embed. Attach this once the iframe is in the DOM.\n * Returns a handle with `navigate()` and `dispose()`.\n */\nexport function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost {\n const target = opts.windowTarget ?? window;\n const makeChannel = opts.createChannel ?? (() => new MessageChannel());\n const targetOrigin = opts.devAllowAnyOrigin ? '*' : opts.crmOrigin;\n\n let port: MessagePort | null = null;\n let nonce = '';\n let disposed = false;\n\n async function deliverBearer(): Promise<void> {\n try {\n const bearer = await opts.getBearer();\n port?.postMessage({\n type: 'auth-tokens',\n accessToken: bearer.accessToken,\n refreshToken: bearer.refreshToken ?? '',\n });\n } catch (err) {\n opts.onError?.(err);\n }\n }\n\n function onPortMessage(e: MessageEvent<ChildMessage>): void {\n const data = e.data;\n if (!data) return;\n if (data.type === 'channel-ack') {\n if (data.nonce !== nonce) return; // stale/forged ack\n void deliverBearer();\n } else if (data.type === 'route-change') {\n opts.onRouteChange?.(data.path);\n } else if (data.type === 'resize') {\n opts.onResize?.(data.height);\n } else if (data.type === 'session-expired') {\n // Embed sessions renew by re-minting (no refresh-token flow).\n void deliverBearer();\n port?.postMessage({ type: 'session-refreshed' });\n }\n }\n\n function startHandshake(): void {\n port?.close();\n const channel = makeChannel();\n port = channel.port1;\n nonce = globalThis.crypto?.randomUUID?.() ?? `n-${String(Math.random()).slice(2)}`;\n port.onmessage = onPortMessage;\n port.start?.();\n opts.iframe.contentWindow?.postMessage(\n { type: 'channel-init', nonce },\n targetOrigin,\n [channel.port2],\n );\n }\n\n function onWindowMessage(event: MessageEvent): void {\n if (disposed) return;\n if (event.source !== opts.iframe.contentWindow) return;\n if (!opts.devAllowAnyOrigin && event.origin !== opts.crmOrigin) return;\n if (isReady(event.data)) startHandshake();\n }\n\n target.addEventListener('message', onWindowMessage as EventListener);\n\n return {\n navigate(path: string): void {\n port?.postMessage({ type: 'navigate', path });\n },\n dispose(): void {\n disposed = true;\n target.removeEventListener('message', onWindowMessage as EventListener);\n port?.close();\n port = null;\n },\n };\n}\n"],"mappings":"AAsEA,SAASA,EAAQC,EAAwC,CACvD,MAAO,CAAC,CAACA,GAAQ,OAAOA,GAAS,UAC3BA,EAAyB,SAAW,aACpCA,EAAyB,OAAS,OAC1C,CASO,SAASC,EAAiBC,EAAmBC,EAA6B,CAC/E,MAAO,GAAGD,EAAU,QAAQ,MAAO,EAAE,CAAC,UAAU,mBAAmBC,CAAW,CAAC,EACjF,CAMO,SAASC,EAAmBC,EAAyC,CAC1E,IAAMC,EAASD,EAAK,cAAgB,OAC9BE,EAAcF,EAAK,gBAAkB,IAAM,IAAI,gBAC/CG,EAAeH,EAAK,kBAAoB,IAAMA,EAAK,UAErDI,EAA2B,KAC3BC,EAAQ,GACRC,EAAW,GAEf,eAAeC,GAA+B,CAC5C,GAAI,CACF,IAAMC,EAAS,MAAMR,EAAK,UAAU,EACpCI,GAAM,YAAY,CAChB,KAAM,cACN,YAAaI,EAAO,YACpB,aAAcA,EAAO,cAAgB,EACvC,CAAC,CACH,OAASC,EAAK,CACZT,EAAK,UAAUS,CAAG,CACpB,CACF,CAEA,SAASC,EAAcC,EAAqC,CAC1D,IAAMhB,EAAOgB,EAAE,KACf,GAAKhB,EACL,GAAIA,EAAK,OAAS,cAAe,CAC/B,GAAIA,EAAK,QAAUU,EAAO,OACrBE,EAAc,CACrB,MAAWZ,EAAK,OAAS,eACvBK,EAAK,gBAAgBL,EAAK,IAAI,EACrBA,EAAK,OAAS,SACvBK,EAAK,WAAWL,EAAK,MAAM,EAClBA,EAAK,OAAS,oBAElBY,EAAc,EACnBH,GAAM,YAAY,CAAE,KAAM,mBAAoB,CAAC,EAEnD,CAEA,SAASQ,GAAuB,CAC9BR,GAAM,MAAM,EACZ,IAAMS,EAAUX,EAAY,EAC5BE,EAAOS,EAAQ,MACfR,EAAQ,WAAW,QAAQ,aAAa,GAAK,KAAK,OAAO,KAAK,OAAO,CAAC,EAAE,MAAM,CAAC,CAAC,GAChFD,EAAK,UAAYM,EACjBN,EAAK,QAAQ,EACbJ,EAAK,OAAO,eAAe,YACzB,CAAE,KAAM,eAAgB,MAAAK,CAAM,EAC9BF,EACA,CAACU,EAAQ,KAAK,CAChB,CACF,CAEA,SAASC,EAAgBC,EAA2B,CAC9CT,GACAS,EAAM,SAAWf,EAAK,OAAO,gBAC7B,CAACA,EAAK,mBAAqBe,EAAM,SAAWf,EAAK,WACjDN,EAAQqB,EAAM,IAAI,GAAGH,EAAe,EAC1C,CAEA,OAAAX,EAAO,iBAAiB,UAAWa,CAAgC,EAE5D,CACL,SAASE,EAAoB,CAC3BZ,GAAM,YAAY,CAAE,KAAM,WAAY,KAAAY,CAAK,CAAC,CAC9C,EACA,SAAgB,CACdV,EAAW,GACXL,EAAO,oBAAoB,UAAWa,CAAgC,EACtEV,GAAM,MAAM,EACZA,EAAO,IACT,CACF,CACF","names":["isReady","data","buildCrmEmbedUrl","crmOrigin","workspaceId","createCrmEmbedHost","opts","target","makeChannel","targetOrigin","port","nonce","disposed","deliverBearer","bearer","err","onPortMessage","e","startHandshake","channel","onWindowMessage","event","path"]}
@@ -0,0 +1,2 @@
1
+ "use strict";var d=Object.defineProperty;var f=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var C=Object.prototype.hasOwnProperty;var S=(t,e)=>{for(var r in e)d(t,r,{get:e[r],enumerable:!0})},w=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of x(e))!C.call(t,s)&&s!==r&&d(t,s,{get:()=>e[s],enumerable:!(n=f(e,s))||n.enumerable});return t};var h=t=>w(d({},"__esModule",{value:!0}),t);var U={};S(U,{CrmExchangeError:()=>l,createEmbedSession:()=>P,exchangeAssertion:()=>b,getCrmEmbedJwks:()=>I,mintCrmAssertion:()=>y,resetCrmEmbedKeys:()=>k});module.exports=h(U);var i=require("jose"),E="crm",u=120,g=new Map;function K(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=new Uint8Array(16);t?.getRandomValues?.(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let r=Array.from(e,n=>n.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}async function p(t){let e=t.alg??"RS256",r=`${t.iss}:${e}`,n=g.get(r);if(n)return n;let s=(async()=>{let o=await(0,i.importPKCS8)(t.privateKeyPem,e),a=await(0,i.importSPKI)(t.publicKeyPem,e),c=await(0,i.exportJWK)(a),m=await(0,i.calculateJwkThumbprint)(c);return{privateKey:o,publicJwk:{...c,kid:m,alg:e,use:"sig"},kid:m}})();return g.set(r,s),s}function k(){g.clear()}async function I(t){let{publicJwk:e}=await p(t);return{keys:[e]}}async function y(t,e,r){let n=e.alg??"RS256",{privateKey:s,kid:o}=await p(e),a=Math.min(r?.ttlSeconds??u,u);return new i.SignJWT({email:t.email,requested_role:t.requestedRole,org_id:t.orgId,...t.fullName?{full_name:t.fullName}:{},...t.avatarUrl?{avatar_url:t.avatarUrl}:{}}).setProtectedHeader({alg:n,kid:o}).setSubject(t.sub).setIssuer(e.iss).setAudience(E).setIssuedAt().setExpirationTime(`${a}s`).setJti(K()).sign(s)}async function b(t,e){let r=e.fetch??fetch,n=`${e.crmBaseUrl.replace(/\/$/,"")}/api/auth/exchange`,s=await r(n,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({assertion:t})}),o=await s.json().catch(()=>({}));if(!s.ok){let c=o?.error?.code??`HTTP_${s.status}`,m=o?.error?.message??"CRM exchange failed";throw new l(m,s.status,c,o)}let a=o?.data??{};return{accessToken:a.access_token,expiresIn:a.expires_in,workspaceId:a.workspace?.id,user:a.user,role:a.role}}async function P(t,e,r){let n=await y(t,e);return b(n,r)}var l=class extends Error{constructor(r,n,s,o){super(r);this.status=n;this.code=s;this.detail=o;this.name="CrmExchangeError"}};0&&(module.exports={CrmExchangeError,createEmbedSession,exchangeAssertion,getCrmEmbedJwks,mintCrmAssertion,resetCrmEmbedKeys});
2
+ //# sourceMappingURL=embed-server.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/embed-server.ts"],"sourcesContent":["/**\n * CRM Embed Server SDK (server side).\n *\n * Use this in YOUR SaaS backend to authenticate the embedded CRM without a\n * shared secret. You mint a short-lived ASYMMETRIC (RS256/ES256) assertion for\n * the logged-in user and exchange it at the CRM for a CRM bearer, which your\n * frontend hands to the CRM iframe (see ./embed-host).\n *\n * The CRM verifies the assertion against your PUBLIC JWKS — you never share a\n * private key with the CRM. Expose getCrmEmbedJwks() at a public https URL and\n * give that URL to the CRM team (they register it as your app's `jwks_url`).\n *\n * Claim contract the CRM expects:\n * iss = your client_id (registered with the CRM; == this config.iss)\n * aud = 'crm'\n * sub = stable user id in YOUR system (becomes the CRM external_subject)\n * email = user email\n * requested_role = 'member' | 'admin' (the CRM clamps to the install's max_role)\n * org_id = your organization id; the CRM resolves the target workspace\n * from the install an admin bound to this org\n * exp - iat <= 120s, plus a unique jti (single-use, replay-protected)\n *\n * Requires `jose` (peer of this subpath). Works in Node and Bun.\n *\n * @packageDocumentation\n */\nimport {\n SignJWT,\n exportJWK,\n importPKCS8,\n importSPKI,\n calculateJwkThumbprint,\n type JWK,\n type KeyLike,\n} from 'jose';\n\nexport type CrmEmbedAlg = 'RS256' | 'ES256';\n\nconst AUDIENCE = 'crm';\nconst DEFAULT_TTL_SECONDS = 120;\n\nexport interface CrmEmbedSigningConfig {\n /** Issuer — MUST equal the client_id the CRM registered for your app. */\n iss: string;\n /** PKCS8 PEM private key used to sign assertions. */\n privateKeyPem: string;\n /** SPKI PEM public key — required so getCrmEmbedJwks() can publish it. */\n publicKeyPem: string;\n /** Signature algorithm. Default 'RS256'. The CRM accepts RS256 or ES256. */\n alg?: CrmEmbedAlg;\n}\n\nexport interface CrmAssertionInput {\n /** Stable user id in your system (becomes the CRM external_subject). */\n sub: string;\n /** User email. */\n email: string;\n /** Requested role; the CRM clamps it to the install's configured max_role. */\n requestedRole: 'member' | 'admin';\n /** Your organization id; the CRM resolves the workspace from the org binding. */\n orgId: string;\n /** Optional display name for first-time provisioning. */\n fullName?: string;\n /** Optional avatar URL for first-time provisioning. */\n avatarUrl?: string;\n}\n\n/** The CRM session returned by the exchange. */\nexport interface CrmEmbedSession {\n accessToken: string;\n expiresIn?: number;\n /** The CRM workspace the user was provisioned into (resolved from org_id). */\n workspaceId?: string;\n user?: { id: string; email: string; full_name?: string };\n role?: string;\n}\n\ninterface LoadedKeys { privateKey: KeyLike; publicJwk: JWK; kid: string }\n\n// Memoize per config.iss so repeated calls don't re-import keys.\nconst keyCache = new Map<string, Promise<LoadedKeys>>();\n\nfunction randomUUID(): string {\n const c = (globalThis as { crypto?: Crypto }).crypto;\n if (c?.randomUUID) return c.randomUUID();\n // Fallback (should not happen on Node 16+/Bun): RFC4122-ish from getRandomValues.\n const b = new Uint8Array(16);\n c?.getRandomValues?.(b);\n b[6] = (b[6] & 0x0f) | 0x40;\n b[8] = (b[8] & 0x3f) | 0x80;\n const h = Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');\n return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;\n}\n\nasync function loadKeys(config: CrmEmbedSigningConfig): Promise<LoadedKeys> {\n const alg = config.alg ?? 'RS256';\n const cacheKey = `${config.iss}:${alg}`;\n const existing = keyCache.get(cacheKey);\n if (existing) return existing;\n\n const created = (async (): Promise<LoadedKeys> => {\n const privateKey = await importPKCS8(config.privateKeyPem, alg);\n const publicKey = await importSPKI(config.publicKeyPem, alg);\n const publicJwk = await exportJWK(publicKey);\n // Stable kid = RFC 7638 thumbprint so the signed header kid matches JWKS.\n const kid = await calculateJwkThumbprint(publicJwk);\n return { privateKey, publicJwk: { ...publicJwk, kid, alg, use: 'sig' }, kid };\n })();\n keyCache.set(cacheKey, created);\n return created;\n}\n\n/** Test/dev only: clear the memoized keys. */\nexport function resetCrmEmbedKeys(): void {\n keyCache.clear();\n}\n\n/**\n * The public JWKS document to serve at a public https URL. Give that URL to the\n * CRM team so they can verify your assertions. Example (Express):\n *\n * app.get('/crm-embed/jwks', async (_req, res) =>\n * res.json(await getCrmEmbedJwks(config)));\n */\nexport async function getCrmEmbedJwks(\n config: CrmEmbedSigningConfig,\n): Promise<{ keys: JWK[] }> {\n const { publicJwk } = await loadKeys(config);\n return { keys: [publicJwk] };\n}\n\n/** Mint a short-lived signed assertion the CRM will exchange for a bearer. */\nexport async function mintCrmAssertion(\n input: CrmAssertionInput,\n config: CrmEmbedSigningConfig,\n options?: { ttlSeconds?: number },\n): Promise<string> {\n const alg = config.alg ?? 'RS256';\n const { privateKey, kid } = await loadKeys(config);\n const ttl = Math.min(options?.ttlSeconds ?? DEFAULT_TTL_SECONDS, DEFAULT_TTL_SECONDS);\n\n return new SignJWT({\n email: input.email,\n requested_role: input.requestedRole,\n org_id: input.orgId,\n ...(input.fullName ? { full_name: input.fullName } : {}),\n ...(input.avatarUrl ? { avatar_url: input.avatarUrl } : {}),\n })\n .setProtectedHeader({ alg, kid })\n .setSubject(input.sub)\n .setIssuer(config.iss)\n .setAudience(AUDIENCE)\n .setIssuedAt()\n .setExpirationTime(`${ttl}s`)\n .setJti(randomUUID())\n .sign(privateKey);\n}\n\nexport interface ExchangeOptions {\n /** CRM exchange base URL, e.g. \"https://api.crm.example.com\". */\n crmBaseUrl: string;\n /** Override fetch (tests / custom agents). Defaults to global fetch. */\n fetch?: typeof fetch;\n}\n\n/**\n * Exchange a minted assertion at the CRM for a CRM bearer. Do this server-side\n * so the browser never calls the CRM's exchange endpoint cross-origin.\n */\nexport async function exchangeAssertion(\n assertion: string,\n options: ExchangeOptions,\n): Promise<CrmEmbedSession> {\n const doFetch = options.fetch ?? fetch;\n const url = `${options.crmBaseUrl.replace(/\\/$/, '')}/api/auth/exchange`;\n const res = await doFetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ assertion }),\n });\n const body = await res.json().catch(() => ({}));\n if (!res.ok) {\n const code = body?.error?.code ?? `HTTP_${res.status}`;\n const msg = body?.error?.message ?? 'CRM exchange failed';\n throw new CrmExchangeError(msg, res.status, code, body);\n }\n const data = body?.data ?? {};\n return {\n accessToken: data.access_token,\n expiresIn: data.expires_in,\n workspaceId: data.workspace?.id,\n user: data.user,\n role: data.role,\n };\n}\n\n/** Mint + exchange in one call — the typical \"give me a CRM session\" helper. */\nexport async function createEmbedSession(\n input: CrmAssertionInput,\n config: CrmEmbedSigningConfig,\n options: ExchangeOptions,\n): Promise<CrmEmbedSession> {\n const assertion = await mintCrmAssertion(input, config);\n return exchangeAssertion(assertion, options);\n}\n\n/** Thrown when the CRM rejects the exchange. `code` is the CRM's error code. */\nexport class CrmExchangeError extends Error {\n constructor(\n message: string,\n public readonly status: number,\n public readonly code: string,\n public readonly detail?: unknown,\n ) {\n super(message);\n this.name = 'CrmExchangeError';\n }\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,sBAAAE,EAAA,uBAAAC,EAAA,sBAAAC,EAAA,oBAAAC,EAAA,qBAAAC,EAAA,sBAAAC,IAAA,eAAAC,EAAAR,GA0BA,IAAAS,E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,IAAIjC,EAAiBmC,EAAKH,EAAI,OAAQE,EAAMD,CAAI,CACxD,CACA,IAAMG,EAAOH,GAAM,MAAQ,CAAC,EAC5B,MAAO,CACL,YAAaG,EAAK,aAClB,UAAWA,EAAK,WAChB,YAAaA,EAAK,WAAW,GAC7B,KAAMA,EAAK,KACX,KAAMA,EAAK,IACb,CACF,CAGA,eAAsBnC,EACpByB,EACAT,EACAU,EAC0B,CAC1B,IAAME,EAAY,MAAMzB,EAAiBsB,EAAOT,CAAM,EACtD,OAAOf,EAAkB2B,EAAWF,CAAO,CAC7C,CAGO,IAAM3B,EAAN,cAA+B,KAAM,CAC1C,YACEqC,EACgBC,EACAJ,EACAK,EAChB,CACA,MAAMF,CAAO,EAJG,YAAAC,EACA,UAAAJ,EACA,YAAAK,EAGhB,KAAK,KAAO,kBACd,CACF","names":["embed_server_exports","__export","CrmExchangeError","createEmbedSession","exchangeAssertion","getCrmEmbedJwks","mintCrmAssertion","resetCrmEmbedKeys","__toCommonJS","import_jose","AUDIENCE","DEFAULT_TTL_SECONDS","keyCache","randomUUID","c","b","h","x","loadKeys","config","alg","cacheKey","existing","created","privateKey","publicKey","publicJwk","kid","input","options","ttl","assertion","doFetch","url","res","body","code","msg","data","message","status","detail"]}
@@ -0,0 +1,105 @@
1
+ import { JWK } from 'jose';
2
+
3
+ /**
4
+ * CRM Embed Server SDK (server side).
5
+ *
6
+ * Use this in YOUR SaaS backend to authenticate the embedded CRM without a
7
+ * shared secret. You mint a short-lived ASYMMETRIC (RS256/ES256) assertion for
8
+ * the logged-in user and exchange it at the CRM for a CRM bearer, which your
9
+ * frontend hands to the CRM iframe (see ./embed-host).
10
+ *
11
+ * The CRM verifies the assertion against your PUBLIC JWKS — you never share a
12
+ * private key with the CRM. Expose getCrmEmbedJwks() at a public https URL and
13
+ * give that URL to the CRM team (they register it as your app's `jwks_url`).
14
+ *
15
+ * Claim contract the CRM expects:
16
+ * iss = your client_id (registered with the CRM; == this config.iss)
17
+ * aud = 'crm'
18
+ * sub = stable user id in YOUR system (becomes the CRM external_subject)
19
+ * email = user email
20
+ * requested_role = 'member' | 'admin' (the CRM clamps to the install's max_role)
21
+ * org_id = your organization id; the CRM resolves the target workspace
22
+ * from the install an admin bound to this org
23
+ * exp - iat <= 120s, plus a unique jti (single-use, replay-protected)
24
+ *
25
+ * Requires `jose` (peer of this subpath). Works in Node and Bun.
26
+ *
27
+ * @packageDocumentation
28
+ */
29
+
30
+ type CrmEmbedAlg = 'RS256' | 'ES256';
31
+ interface CrmEmbedSigningConfig {
32
+ /** Issuer — MUST equal the client_id the CRM registered for your app. */
33
+ iss: string;
34
+ /** PKCS8 PEM private key used to sign assertions. */
35
+ privateKeyPem: string;
36
+ /** SPKI PEM public key — required so getCrmEmbedJwks() can publish it. */
37
+ publicKeyPem: string;
38
+ /** Signature algorithm. Default 'RS256'. The CRM accepts RS256 or ES256. */
39
+ alg?: CrmEmbedAlg;
40
+ }
41
+ interface CrmAssertionInput {
42
+ /** Stable user id in your system (becomes the CRM external_subject). */
43
+ sub: string;
44
+ /** User email. */
45
+ email: string;
46
+ /** Requested role; the CRM clamps it to the install's configured max_role. */
47
+ requestedRole: 'member' | 'admin';
48
+ /** Your organization id; the CRM resolves the workspace from the org binding. */
49
+ orgId: string;
50
+ /** Optional display name for first-time provisioning. */
51
+ fullName?: string;
52
+ /** Optional avatar URL for first-time provisioning. */
53
+ avatarUrl?: string;
54
+ }
55
+ /** The CRM session returned by the exchange. */
56
+ interface CrmEmbedSession {
57
+ accessToken: string;
58
+ expiresIn?: number;
59
+ /** The CRM workspace the user was provisioned into (resolved from org_id). */
60
+ workspaceId?: string;
61
+ user?: {
62
+ id: string;
63
+ email: string;
64
+ full_name?: string;
65
+ };
66
+ role?: string;
67
+ }
68
+ /** Test/dev only: clear the memoized keys. */
69
+ declare function resetCrmEmbedKeys(): void;
70
+ /**
71
+ * The public JWKS document to serve at a public https URL. Give that URL to the
72
+ * CRM team so they can verify your assertions. Example (Express):
73
+ *
74
+ * app.get('/crm-embed/jwks', async (_req, res) =>
75
+ * res.json(await getCrmEmbedJwks(config)));
76
+ */
77
+ declare function getCrmEmbedJwks(config: CrmEmbedSigningConfig): Promise<{
78
+ keys: JWK[];
79
+ }>;
80
+ /** Mint a short-lived signed assertion the CRM will exchange for a bearer. */
81
+ declare function mintCrmAssertion(input: CrmAssertionInput, config: CrmEmbedSigningConfig, options?: {
82
+ ttlSeconds?: number;
83
+ }): Promise<string>;
84
+ interface ExchangeOptions {
85
+ /** CRM exchange base URL, e.g. "https://api.crm.example.com". */
86
+ crmBaseUrl: string;
87
+ /** Override fetch (tests / custom agents). Defaults to global fetch. */
88
+ fetch?: typeof fetch;
89
+ }
90
+ /**
91
+ * Exchange a minted assertion at the CRM for a CRM bearer. Do this server-side
92
+ * so the browser never calls the CRM's exchange endpoint cross-origin.
93
+ */
94
+ declare function exchangeAssertion(assertion: string, options: ExchangeOptions): Promise<CrmEmbedSession>;
95
+ /** Mint + exchange in one call — the typical "give me a CRM session" helper. */
96
+ declare function createEmbedSession(input: CrmAssertionInput, config: CrmEmbedSigningConfig, options: ExchangeOptions): Promise<CrmEmbedSession>;
97
+ /** Thrown when the CRM rejects the exchange. `code` is the CRM's error code. */
98
+ declare class CrmExchangeError extends Error {
99
+ readonly status: number;
100
+ readonly code: string;
101
+ readonly detail?: unknown | undefined;
102
+ constructor(message: string, status: number, code: string, detail?: unknown | undefined);
103
+ }
104
+
105
+ export { type CrmAssertionInput, type CrmEmbedAlg, type CrmEmbedSession, type CrmEmbedSigningConfig, CrmExchangeError, type ExchangeOptions, createEmbedSession, exchangeAssertion, getCrmEmbedJwks, mintCrmAssertion, resetCrmEmbedKeys };
@@ -0,0 +1,105 @@
1
+ import { JWK } from 'jose';
2
+
3
+ /**
4
+ * CRM Embed Server SDK (server side).
5
+ *
6
+ * Use this in YOUR SaaS backend to authenticate the embedded CRM without a
7
+ * shared secret. You mint a short-lived ASYMMETRIC (RS256/ES256) assertion for
8
+ * the logged-in user and exchange it at the CRM for a CRM bearer, which your
9
+ * frontend hands to the CRM iframe (see ./embed-host).
10
+ *
11
+ * The CRM verifies the assertion against your PUBLIC JWKS — you never share a
12
+ * private key with the CRM. Expose getCrmEmbedJwks() at a public https URL and
13
+ * give that URL to the CRM team (they register it as your app's `jwks_url`).
14
+ *
15
+ * Claim contract the CRM expects:
16
+ * iss = your client_id (registered with the CRM; == this config.iss)
17
+ * aud = 'crm'
18
+ * sub = stable user id in YOUR system (becomes the CRM external_subject)
19
+ * email = user email
20
+ * requested_role = 'member' | 'admin' (the CRM clamps to the install's max_role)
21
+ * org_id = your organization id; the CRM resolves the target workspace
22
+ * from the install an admin bound to this org
23
+ * exp - iat <= 120s, plus a unique jti (single-use, replay-protected)
24
+ *
25
+ * Requires `jose` (peer of this subpath). Works in Node and Bun.
26
+ *
27
+ * @packageDocumentation
28
+ */
29
+
30
+ type CrmEmbedAlg = 'RS256' | 'ES256';
31
+ interface CrmEmbedSigningConfig {
32
+ /** Issuer — MUST equal the client_id the CRM registered for your app. */
33
+ iss: string;
34
+ /** PKCS8 PEM private key used to sign assertions. */
35
+ privateKeyPem: string;
36
+ /** SPKI PEM public key — required so getCrmEmbedJwks() can publish it. */
37
+ publicKeyPem: string;
38
+ /** Signature algorithm. Default 'RS256'. The CRM accepts RS256 or ES256. */
39
+ alg?: CrmEmbedAlg;
40
+ }
41
+ interface CrmAssertionInput {
42
+ /** Stable user id in your system (becomes the CRM external_subject). */
43
+ sub: string;
44
+ /** User email. */
45
+ email: string;
46
+ /** Requested role; the CRM clamps it to the install's configured max_role. */
47
+ requestedRole: 'member' | 'admin';
48
+ /** Your organization id; the CRM resolves the workspace from the org binding. */
49
+ orgId: string;
50
+ /** Optional display name for first-time provisioning. */
51
+ fullName?: string;
52
+ /** Optional avatar URL for first-time provisioning. */
53
+ avatarUrl?: string;
54
+ }
55
+ /** The CRM session returned by the exchange. */
56
+ interface CrmEmbedSession {
57
+ accessToken: string;
58
+ expiresIn?: number;
59
+ /** The CRM workspace the user was provisioned into (resolved from org_id). */
60
+ workspaceId?: string;
61
+ user?: {
62
+ id: string;
63
+ email: string;
64
+ full_name?: string;
65
+ };
66
+ role?: string;
67
+ }
68
+ /** Test/dev only: clear the memoized keys. */
69
+ declare function resetCrmEmbedKeys(): void;
70
+ /**
71
+ * The public JWKS document to serve at a public https URL. Give that URL to the
72
+ * CRM team so they can verify your assertions. Example (Express):
73
+ *
74
+ * app.get('/crm-embed/jwks', async (_req, res) =>
75
+ * res.json(await getCrmEmbedJwks(config)));
76
+ */
77
+ declare function getCrmEmbedJwks(config: CrmEmbedSigningConfig): Promise<{
78
+ keys: JWK[];
79
+ }>;
80
+ /** Mint a short-lived signed assertion the CRM will exchange for a bearer. */
81
+ declare function mintCrmAssertion(input: CrmAssertionInput, config: CrmEmbedSigningConfig, options?: {
82
+ ttlSeconds?: number;
83
+ }): Promise<string>;
84
+ interface ExchangeOptions {
85
+ /** CRM exchange base URL, e.g. "https://api.crm.example.com". */
86
+ crmBaseUrl: string;
87
+ /** Override fetch (tests / custom agents). Defaults to global fetch. */
88
+ fetch?: typeof fetch;
89
+ }
90
+ /**
91
+ * Exchange a minted assertion at the CRM for a CRM bearer. Do this server-side
92
+ * so the browser never calls the CRM's exchange endpoint cross-origin.
93
+ */
94
+ declare function exchangeAssertion(assertion: string, options: ExchangeOptions): Promise<CrmEmbedSession>;
95
+ /** Mint + exchange in one call — the typical "give me a CRM session" helper. */
96
+ declare function createEmbedSession(input: CrmAssertionInput, config: CrmEmbedSigningConfig, options: ExchangeOptions): Promise<CrmEmbedSession>;
97
+ /** Thrown when the CRM rejects the exchange. `code` is the CRM's error code. */
98
+ declare class CrmExchangeError extends Error {
99
+ readonly status: number;
100
+ readonly code: string;
101
+ readonly detail?: unknown | undefined;
102
+ constructor(message: string, status: number, code: string, detail?: unknown | undefined);
103
+ }
104
+
105
+ export { type CrmAssertionInput, type CrmEmbedAlg, type CrmEmbedSession, type CrmEmbedSigningConfig, CrmExchangeError, type ExchangeOptions, createEmbedSession, exchangeAssertion, getCrmEmbedJwks, mintCrmAssertion, resetCrmEmbedKeys };
@@ -0,0 +1,2 @@
1
+ import{SignJWT as u,exportJWK as p,importPKCS8 as y,importSPKI as b,calculateJwkThumbprint as f}from"jose";var x="crm",d=120,m=new Map;function C(){let e=globalThis.crypto;if(e?.randomUUID)return e.randomUUID();let t=new Uint8Array(16);e?.getRandomValues?.(t),t[6]=t[6]&15|64,t[8]=t[8]&63|128;let r=Array.from(t,s=>s.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}async function g(e){let t=e.alg??"RS256",r=`${e.iss}:${t}`,s=m.get(r);if(s)return s;let n=(async()=>{let i=await y(e.privateKeyPem,t),o=await b(e.publicKeyPem,t),a=await p(o),c=await f(a);return{privateKey:i,publicJwk:{...a,kid:c,alg:t,use:"sig"},kid:c}})();return m.set(r,n),n}function E(){m.clear()}async function K(e){let{publicJwk:t}=await g(e);return{keys:[t]}}async function S(e,t,r){let s=t.alg??"RS256",{privateKey:n,kid:i}=await g(t),o=Math.min(r?.ttlSeconds??d,d);return new u({email:e.email,requested_role:e.requestedRole,org_id:e.orgId,...e.fullName?{full_name:e.fullName}:{},...e.avatarUrl?{avatar_url:e.avatarUrl}:{}}).setProtectedHeader({alg:s,kid:i}).setSubject(e.sub).setIssuer(t.iss).setAudience(x).setIssuedAt().setExpirationTime(`${o}s`).setJti(C()).sign(n)}async function w(e,t){let r=t.fetch??fetch,s=`${t.crmBaseUrl.replace(/\/$/,"")}/api/auth/exchange`,n=await r(s,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({assertion:e})}),i=await n.json().catch(()=>({}));if(!n.ok){let a=i?.error?.code??`HTTP_${n.status}`,c=i?.error?.message??"CRM exchange failed";throw new l(c,n.status,a,i)}let o=i?.data??{};return{accessToken:o.access_token,expiresIn:o.expires_in,workspaceId:o.workspace?.id,user:o.user,role:o.role}}async function k(e,t,r){let s=await S(e,t);return w(s,r)}var l=class extends Error{constructor(r,s,n,i){super(r);this.status=s;this.code=n;this.detail=i;this.name="CrmExchangeError"}};export{l as CrmExchangeError,k as createEmbedSession,w as exchangeAssertion,K as getCrmEmbedJwks,S as mintCrmAssertion,E as resetCrmEmbedKeys};
2
+ //# sourceMappingURL=embed-server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/embed-server.ts"],"sourcesContent":["/**\n * CRM Embed Server SDK (server side).\n *\n * Use this in YOUR SaaS backend to authenticate the embedded CRM without a\n * shared secret. You mint a short-lived ASYMMETRIC (RS256/ES256) assertion for\n * the logged-in user and exchange it at the CRM for a CRM bearer, which your\n * frontend hands to the CRM iframe (see ./embed-host).\n *\n * The CRM verifies the assertion against your PUBLIC JWKS — you never share a\n * private key with the CRM. Expose getCrmEmbedJwks() at a public https URL and\n * give that URL to the CRM team (they register it as your app's `jwks_url`).\n *\n * Claim contract the CRM expects:\n * iss = your client_id (registered with the CRM; == this config.iss)\n * aud = 'crm'\n * sub = stable user id in YOUR system (becomes the CRM external_subject)\n * email = user email\n * requested_role = 'member' | 'admin' (the CRM clamps to the install's max_role)\n * org_id = your organization id; the CRM resolves the target workspace\n * from the install an admin bound to this org\n * exp - iat <= 120s, plus a unique jti (single-use, replay-protected)\n *\n * Requires `jose` (peer of this subpath). Works in Node and Bun.\n *\n * @packageDocumentation\n */\nimport {\n SignJWT,\n exportJWK,\n importPKCS8,\n importSPKI,\n calculateJwkThumbprint,\n type JWK,\n type KeyLike,\n} from 'jose';\n\nexport type CrmEmbedAlg = 'RS256' | 'ES256';\n\nconst AUDIENCE = 'crm';\nconst DEFAULT_TTL_SECONDS = 120;\n\nexport interface CrmEmbedSigningConfig {\n /** Issuer — MUST equal the client_id the CRM registered for your app. */\n iss: string;\n /** PKCS8 PEM private key used to sign assertions. */\n privateKeyPem: string;\n /** SPKI PEM public key — required so getCrmEmbedJwks() can publish it. */\n publicKeyPem: string;\n /** Signature algorithm. Default 'RS256'. The CRM accepts RS256 or ES256. */\n alg?: CrmEmbedAlg;\n}\n\nexport interface CrmAssertionInput {\n /** Stable user id in your system (becomes the CRM external_subject). */\n sub: string;\n /** User email. */\n email: string;\n /** Requested role; the CRM clamps it to the install's configured max_role. */\n requestedRole: 'member' | 'admin';\n /** Your organization id; the CRM resolves the workspace from the org binding. */\n orgId: string;\n /** Optional display name for first-time provisioning. */\n fullName?: string;\n /** Optional avatar URL for first-time provisioning. */\n avatarUrl?: string;\n}\n\n/** The CRM session returned by the exchange. */\nexport interface CrmEmbedSession {\n accessToken: string;\n expiresIn?: number;\n /** The CRM workspace the user was provisioned into (resolved from org_id). */\n workspaceId?: string;\n user?: { id: string; email: string; full_name?: string };\n role?: string;\n}\n\ninterface LoadedKeys { privateKey: KeyLike; publicJwk: JWK; kid: string }\n\n// Memoize per config.iss so repeated calls don't re-import keys.\nconst keyCache = new Map<string, Promise<LoadedKeys>>();\n\nfunction randomUUID(): string {\n const c = (globalThis as { crypto?: Crypto }).crypto;\n if (c?.randomUUID) return c.randomUUID();\n // Fallback (should not happen on Node 16+/Bun): RFC4122-ish from getRandomValues.\n const b = new Uint8Array(16);\n c?.getRandomValues?.(b);\n b[6] = (b[6] & 0x0f) | 0x40;\n b[8] = (b[8] & 0x3f) | 0x80;\n const h = Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');\n return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;\n}\n\nasync function loadKeys(config: CrmEmbedSigningConfig): Promise<LoadedKeys> {\n const alg = config.alg ?? 'RS256';\n const cacheKey = `${config.iss}:${alg}`;\n const existing = keyCache.get(cacheKey);\n if (existing) return existing;\n\n const created = (async (): Promise<LoadedKeys> => {\n const privateKey = await importPKCS8(config.privateKeyPem, alg);\n const publicKey = await importSPKI(config.publicKeyPem, alg);\n const publicJwk = await exportJWK(publicKey);\n // Stable kid = RFC 7638 thumbprint so the signed header kid matches JWKS.\n const kid = await calculateJwkThumbprint(publicJwk);\n return { privateKey, publicJwk: { ...publicJwk, kid, alg, use: 'sig' }, kid };\n })();\n keyCache.set(cacheKey, created);\n return created;\n}\n\n/** Test/dev only: clear the memoized keys. */\nexport function resetCrmEmbedKeys(): void {\n keyCache.clear();\n}\n\n/**\n * The public JWKS document to serve at a public https URL. Give that URL to the\n * CRM team so they can verify your assertions. Example (Express):\n *\n * app.get('/crm-embed/jwks', async (_req, res) =>\n * res.json(await getCrmEmbedJwks(config)));\n */\nexport async function getCrmEmbedJwks(\n config: CrmEmbedSigningConfig,\n): Promise<{ keys: JWK[] }> {\n const { publicJwk } = await loadKeys(config);\n return { keys: [publicJwk] };\n}\n\n/** Mint a short-lived signed assertion the CRM will exchange for a bearer. */\nexport async function mintCrmAssertion(\n input: CrmAssertionInput,\n config: CrmEmbedSigningConfig,\n options?: { ttlSeconds?: number },\n): Promise<string> {\n const alg = config.alg ?? 'RS256';\n const { privateKey, kid } = await loadKeys(config);\n const ttl = Math.min(options?.ttlSeconds ?? DEFAULT_TTL_SECONDS, DEFAULT_TTL_SECONDS);\n\n return new SignJWT({\n email: input.email,\n requested_role: input.requestedRole,\n org_id: input.orgId,\n ...(input.fullName ? { full_name: input.fullName } : {}),\n ...(input.avatarUrl ? { avatar_url: input.avatarUrl } : {}),\n })\n .setProtectedHeader({ alg, kid })\n .setSubject(input.sub)\n .setIssuer(config.iss)\n .setAudience(AUDIENCE)\n .setIssuedAt()\n .setExpirationTime(`${ttl}s`)\n .setJti(randomUUID())\n .sign(privateKey);\n}\n\nexport interface ExchangeOptions {\n /** CRM exchange base URL, e.g. \"https://api.crm.example.com\". */\n crmBaseUrl: string;\n /** Override fetch (tests / custom agents). Defaults to global fetch. */\n fetch?: typeof fetch;\n}\n\n/**\n * Exchange a minted assertion at the CRM for a CRM bearer. Do this server-side\n * so the browser never calls the CRM's exchange endpoint cross-origin.\n */\nexport async function exchangeAssertion(\n assertion: string,\n options: ExchangeOptions,\n): Promise<CrmEmbedSession> {\n const doFetch = options.fetch ?? fetch;\n const url = `${options.crmBaseUrl.replace(/\\/$/, '')}/api/auth/exchange`;\n const res = await doFetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ assertion }),\n });\n const body = await res.json().catch(() => ({}));\n if (!res.ok) {\n const code = body?.error?.code ?? `HTTP_${res.status}`;\n const msg = body?.error?.message ?? 'CRM exchange failed';\n throw new CrmExchangeError(msg, res.status, code, body);\n }\n const data = body?.data ?? {};\n return {\n accessToken: data.access_token,\n expiresIn: data.expires_in,\n workspaceId: data.workspace?.id,\n user: data.user,\n role: data.role,\n };\n}\n\n/** Mint + exchange in one call — the typical \"give me a CRM session\" helper. */\nexport async function createEmbedSession(\n input: CrmAssertionInput,\n config: CrmEmbedSigningConfig,\n options: ExchangeOptions,\n): Promise<CrmEmbedSession> {\n const assertion = await mintCrmAssertion(input, config);\n return exchangeAssertion(assertion, options);\n}\n\n/** Thrown when the CRM rejects the exchange. `code` is the CRM's error code. */\nexport class CrmExchangeError extends Error {\n constructor(\n message: string,\n public readonly status: number,\n public readonly code: string,\n public readonly detail?: unknown,\n ) {\n super(message);\n this.name = 'CrmExchangeError';\n }\n}\n"],"mappings":"AA0BA,OACE,WAAAA,EACA,aAAAC,EACA,eAAAC,EACA,cAAAC,EACA,0BAAAC,MAGK,OAIP,IAAMC,EAAW,MACXC,EAAsB,IAyCtBC,EAAW,IAAI,IAErB,SAASC,GAAqB,CAC5B,IAAMC,EAAK,WAAmC,OAC9C,GAAIA,GAAG,WAAY,OAAOA,EAAE,WAAW,EAEvC,IAAMC,EAAI,IAAI,WAAW,EAAE,EAC3BD,GAAG,kBAAkBC,CAAC,EACtBA,EAAE,CAAC,EAAKA,EAAE,CAAC,EAAI,GAAQ,GACvBA,EAAE,CAAC,EAAKA,EAAE,CAAC,EAAI,GAAQ,IACvB,IAAMC,EAAI,MAAM,KAAKD,EAAIE,GAAMA,EAAE,SAAS,EAAE,EAAE,SAAS,E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M,CAC1C,YACEG,EACgBC,EACAN,EACAO,EAChB,CACA,MAAMF,CAAO,EAJG,YAAAC,EACA,UAAAN,EACA,YAAAO,EAGhB,KAAK,KAAO,kBACd,CACF","names":["SignJWT","exportJWK","importPKCS8","importSPKI","calculateJwkThumbprint","AUDIENCE","DEFAULT_TTL_SECONDS","keyCache","randomUUID","c","b","h","x","loadKeys","config","alg","cacheKey","existing","created","privateKey","publicKey","publicJwk","kid","resetCrmEmbedKeys","getCrmEmbedJwks","mintCrmAssertion","input","options","ttl","exchangeAssertion","assertion","doFetch","url","res","body","code","msg","CrmExchangeError","data","createEmbedSession","message","status","detail"]}
package/dist/index.cjs ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";var c=Object.defineProperty;var v=Object.getOwnPropertyDescriptor;var f=Object.getOwnPropertyNames;var m=Object.prototype.hasOwnProperty;var C=(n,e)=>{for(var t in e)c(n,t,{get:e[t],enumerable:!0})},w=(n,e,t,d)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of f(e))!m.call(n,r)&&r!==t&&c(n,r,{get:()=>e[r],enumerable:!(d=v(e,r))||d.enumerable});return n};var g=n=>w(c({},"__esModule",{value:!0}),n);var E={};C(E,{CrmApp:()=>p,default:()=>y});module.exports=g(E);var i=null,s={},o={},k=0,a=null;function u(n,e){let t=s[n]||[];for(let d of t)try{d(e)}catch(r){console.error("[CrmApp] Listener error:",r)}}function l(n){if(typeof window<"u"&&window.parent&&window.parent!==window){let e=a||"*";window.parent.postMessage({source:"crm-app",...n},e)}}function x(n){let{data:e}=n;if(!(!e||e.source!=="crm-host")&&(!a&&n.origin&&(a=n.origin),!(a&&n.origin!==a)))switch(e.type){case"init":i=e.context??null,i&&u("ready",i);break;case"context_update":i=e.context??null,i&&u("context_update",i);break;case"response":{let t=e.invoke_id;t!=null&&o[t]&&(e.error?o[t].reject(new Error(e.error)):o[t].resolve(e.result),delete o[t]);break}}}typeof window<"u"&&window.addEventListener("message",x,!1);var p={init(){l({type:"app_ready"})},on(n,e){s[n]||(s[n]=[]),s[n].push(e)},off(n,e){s[n]&&(s[n]=s[n].filter(t=>t!==e))},getContext(){return i},invoke(n,e){let t=++k;return l({type:"invoke",invoke_id:t,action:n,data:e||{}}),new Promise((d,r)=>{o[t]={resolve:d,reject:r},setTimeout(()=>{o[t]&&(o[t].reject(new Error("Invoke timeout")),delete o[t])},3e4)})}},y=p;0&&(module.exports={CrmApp});
2
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * CRM Embeddable App SDK\n * Enables communication between third-party iframes and the CRM host.\n *\n * @packageDocumentation\n */\n\n/** Context provided by the CRM host after initialization */\nexport interface CrmContext {\n token: string | null;\n workspace_id: string;\n conversation_id: string | null;\n contact_id: string | null;\n conversation_metadata?: Record<string, unknown>;\n}\n\n/** Supported SDK event types */\nexport type CrmEventType = 'ready' | 'context_update';\n\n/** Event listener callback */\nexport type CrmEventListener = (data: CrmContext) => void;\n\n/** Public SDK interface */\nexport interface CrmAppSDK {\n /** Signal readiness to the CRM host and start the handshake */\n init(): void;\n /** Register an event listener */\n on(event: CrmEventType, fn: CrmEventListener): void;\n /** Remove an event listener */\n off(event: CrmEventType, fn: CrmEventListener): void;\n /** Get the current context (null before initialization) */\n getContext(): CrmContext | null;\n /** Request an action from the CRM host. Returns a Promise that resolves with the result. */\n invoke<T = unknown>(action: string, data?: Record<string, unknown>): Promise<T>;\n}\n\n// ---------------------------------------------------------------------------\n// Internal state\n// ---------------------------------------------------------------------------\n\nlet context: CrmContext | null = null;\nconst listeners: Record<string, CrmEventListener[]> = {};\nconst pendingInvokes: Record<\n number,\n { resolve: (value: unknown) => void; reject: (reason: Error) => void }\n> = {};\nlet invokeCounter = 0;\n/** Captured origin of the CRM host — used as postMessage targetOrigin */\nlet hostOrigin: string | null = null;\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction emit(event: string, data: CrmContext): void {\n const fns = listeners[event] || [];\n for (const fn of fns) {\n try {\n fn(data);\n } catch (e) {\n console.error('[CrmApp] Listener error:', e);\n }\n }\n}\n\nfunction postToHost(msg: Record<string, unknown>): void {\n if (\n typeof window !== 'undefined' &&\n window.parent &&\n window.parent !== window\n ) {\n // Use the captured host origin for security; fall back to '*' only during\n // the initial handshake before the host origin is known.\n const target = hostOrigin || '*';\n window.parent.postMessage({ source: 'crm-app', ...msg }, target);\n }\n}\n\nfunction handleMessage(event: MessageEvent): void {\n const { data } = event;\n if (!data || data.source !== 'crm-host') return;\n\n // Capture the host origin from the first trusted message\n if (!hostOrigin && event.origin) {\n hostOrigin = event.origin;\n }\n\n // After host origin is established, reject messages from other origins\n if (hostOrigin && event.origin !== hostOrigin) return;\n\n switch (data.type) {\n case 'init':\n context = data.context ?? null;\n if (context) emit('ready', context);\n break;\n\n case 'context_update':\n context = data.context ?? null;\n if (context) emit('context_update', context);\n break;\n\n case 'response': {\n const id: number | undefined = data.invoke_id;\n if (id != null && pendingInvokes[id]) {\n if (data.error) {\n pendingInvokes[id].reject(new Error(data.error));\n } else {\n pendingInvokes[id].resolve(data.result);\n }\n delete pendingInvokes[id];\n }\n break;\n }\n }\n}\n\n// Auto-register message listener in browser environments\nif (typeof window !== 'undefined') {\n window.addEventListener('message', handleMessage, false);\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\nexport const CrmApp: CrmAppSDK = {\n init(): void {\n postToHost({ type: 'app_ready' });\n },\n\n on(event: CrmEventType, fn: CrmEventListener): void {\n if (!listeners[event]) listeners[event] = [];\n listeners[event].push(fn);\n },\n\n off(event: CrmEventType, fn: CrmEventListener): void {\n if (!listeners[event]) return;\n listeners[event] = listeners[event].filter((f) => f !== fn);\n },\n\n getContext(): CrmContext | null {\n return context;\n },\n\n invoke<T = unknown>(\n action: string,\n data?: Record<string, unknown>,\n ): Promise<T> {\n const id = ++invokeCounter;\n postToHost({\n type: 'invoke',\n invoke_id: id,\n action,\n data: data || {},\n });\n\n return new Promise<T>((resolve, reject) => {\n pendingInvokes[id] = {\n resolve: resolve as (value: unknown) => void,\n reject,\n };\n setTimeout(() => {\n if (pendingInvokes[id]) {\n pendingInvokes[id].reject(new Error('Invoke timeout'));\n delete pendingInvokes[id];\n }\n }, 30000);\n });\n },\n};\n\n// Default export for convenience\nexport default CrmApp;\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,YAAAE,EAAA,YAAAC,IAAA,eAAAC,EAAAJ,GAwCA,IAAIK,EAA6B,KAC3BC,EAAgD,CAAC,EACjDC,EAGF,CAAC,EACDC,EAAgB,EAEhBC,EAA4B,KAMhC,SAASC,EAAKC,EAAeC,EAAwB,CACnD,IAAMC,EAAMP,EAAUK,CAAK,GAAK,CAAC,EACjC,QAAWG,KAAMD,EACf,GAAI,CACFC,EAAGF,CAAI,CACT,OAASG,EAAG,CACV,QAAQ,MAAM,2BAA4BA,CAAC,CAC7C,CAEJ,CAEA,SAASC,EAAWC,EAAoC,CACtD,GACE,OAAO,OAAW,KAClB,OAAO,QACP,OAAO,SAAW,OAClB,CAGA,IAAMC,EAAST,GAAc,IAC7B,OAAO,OAAO,YAAY,CAAE,OAAQ,UAAW,GAAGQ,CAAI,EAAGC,CAAM,CACjE,CACF,CAEA,SAASC,EAAcR,EAA2B,CAChD,GAAM,CAAE,KAAAC,CAAK,EAAID,EACjB,GAAI,GAACC,GAAQA,EAAK,SAAW,cAGzB,CAACH,GAAcE,EAAM,SACvBF,EAAaE,EAAM,QAIjB,EAAAF,GAAcE,EAAM,SAAWF,IAEnC,OAAQG,EAAK,KAAM,CACjB,IAAK,OACHP,EAAUO,EAAK,SAAW,KACtBP,GAASK,EAAK,QAASL,CAAO,EAClC,MAEF,IAAK,iBACHA,EAAUO,EAAK,SAAW,KACtBP,GAASK,EAAK,iBAAkBL,CAAO,EAC3C,MAEF,IAAK,WAAY,CACf,IAAMe,EAAyBR,EAAK,UAChCQ,GAAM,MAAQb,EAAea,CAAE,IAC7BR,EAAK,MACPL,EAAea,CAAE,EAAE,OAAO,IAAI,MAAMR,EAAK,KAAK,CAAC,EAE/CL,EAAea,CAAE,EAAE,QAAQR,EAAK,MAAM,EAExC,OAAOL,EAAea,CAAE,GAE1B,KACF,CACF,CACF,CAGI,OAAO,OAAW,KACpB,OAAO,iBAAiB,UAAWD,EAAe,EAAK,EAOlD,IAAMjB,EAAoB,CAC/B,MAAa,CACXc,EAAW,CAAE,KAAM,WAAY,CAAC,CAClC,EAEA,GAAGL,EAAqBG,EAA4B,CAC7CR,EAAUK,CAAK,IAAGL,EAAUK,CAAK,EAAI,CAAC,GAC3CL,EAAUK,CAAK,EAAE,KAAKG,CAAE,CAC1B,EAEA,IAAIH,EAAqBG,EAA4B,CAC9CR,EAAUK,CAAK,IACpBL,EAAUK,CAAK,EAAIL,EAAUK,CAAK,EAAE,OAAQU,GAAMA,IAAMP,CAAE,EAC5D,EAEA,YAAgC,CAC9B,OAAOT,CACT,EAEA,OACEiB,EACAV,EACY,CACZ,IAAMQ,EAAK,EAAEZ,EACb,OAAAQ,EAAW,CACT,KAAM,SACN,UAAWI,EACX,OAAAE,EACA,KAAMV,GAAQ,CAAC,CACjB,CAAC,EAEM,IAAI,QAAW,CAACW,EAASC,IAAW,CACzCjB,EAAea,CAAE,EAAI,CACnB,QAASG,EACT,OAAAC,CACF,EACA,WAAW,IAAM,CACXjB,EAAea,CAAE,IACnBb,EAAea,CAAE,EAAE,OAAO,IAAI,MAAM,gBAAgB,CAAC,EACrD,OAAOb,EAAea,CAAE,EAE5B,EAAG,GAAK,CACV,CAAC,CACH,CACF,EAGOjB,EAAQD","names":["index_exports","__export","CrmApp","index_default","__toCommonJS","context","listeners","pendingInvokes","invokeCounter","hostOrigin","emit","event","data","fns","fn","e","postToHost","msg","target","handleMessage","id","f","action","resolve","reject"]}
@@ -1,3 +1,3 @@
1
- "use strict";var CrmAppSDK=(()=>{var a=Object.defineProperty;var v=Object.getOwnPropertyDescriptor;var l=Object.getOwnPropertyNames;var f=Object.prototype.hasOwnProperty;var m=(n,e)=>{for(var t in e)a(n,t,{get:e[t],enumerable:!0})},C=(n,e,t,d)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of l(e))!f.call(n,r)&&r!==t&&a(n,r,{get:()=>e[r],enumerable:!(d=v(e,r))||d.enumerable});return n};var w=n=>C(a({},"__esModule",{value:!0}),n);var y={};m(y,{CrmApp:()=>p,default:()=>g});var i=null,s={},o={},k=0;function c(n,e){let t=s[n]||[];for(let d of t)try{d(e)}catch(r){console.error("[CrmApp] Listener error:",r)}}function u(n){typeof window<"u"&&window.parent&&window.parent!==window&&window.parent.postMessage({source:"crm-app",...n},"*")}function x(n){let{data:e}=n;if(!(!e||e.source!=="crm-host"))switch(e.type){case"init":i=e.context??null,i&&c("ready",i);break;case"context_update":i=e.context??null,i&&c("context_update",i);break;case"response":{let t=e.invoke_id;t!=null&&o[t]&&(e.error?o[t].reject(new Error(e.error)):o[t].resolve(e.result),delete o[t]);break}}}typeof window<"u"&&window.addEventListener("message",x,!1);var p={init(){u({type:"app_ready"})},on(n,e){s[n]||(s[n]=[]),s[n].push(e)},off(n,e){s[n]&&(s[n]=s[n].filter(t=>t!==e))},getContext(){return i},invoke(n,e){let t=++k;return u({type:"invoke",invoke_id:t,action:n,data:e||{}}),new Promise((d,r)=>{o[t]={resolve:d,reject:r},setTimeout(()=>{o[t]&&(o[t].reject(new Error("Invoke timeout")),delete o[t])},3e4)})}},g=p;return w(y);})();
1
+ "use strict";var CrmAppSDK=(()=>{var c=Object.defineProperty;var v=Object.getOwnPropertyDescriptor;var f=Object.getOwnPropertyNames;var m=Object.prototype.hasOwnProperty;var C=(n,e)=>{for(var t in e)c(n,t,{get:e[t],enumerable:!0})},w=(n,e,t,d)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of f(e))!m.call(n,r)&&r!==t&&c(n,r,{get:()=>e[r],enumerable:!(d=v(e,r))||d.enumerable});return n};var g=n=>w(c({},"__esModule",{value:!0}),n);var E={};C(E,{CrmApp:()=>p,default:()=>y});var i=null,s={},o={},k=0,a=null;function u(n,e){let t=s[n]||[];for(let d of t)try{d(e)}catch(r){console.error("[CrmApp] Listener error:",r)}}function l(n){if(typeof window<"u"&&window.parent&&window.parent!==window){let e=a||"*";window.parent.postMessage({source:"crm-app",...n},e)}}function x(n){let{data:e}=n;if(!(!e||e.source!=="crm-host")&&(!a&&n.origin&&(a=n.origin),!(a&&n.origin!==a)))switch(e.type){case"init":i=e.context??null,i&&u("ready",i);break;case"context_update":i=e.context??null,i&&u("context_update",i);break;case"response":{let t=e.invoke_id;t!=null&&o[t]&&(e.error?o[t].reject(new Error(e.error)):o[t].resolve(e.result),delete o[t]);break}}}typeof window<"u"&&window.addEventListener("message",x,!1);var p={init(){l({type:"app_ready"})},on(n,e){s[n]||(s[n]=[]),s[n].push(e)},off(n,e){s[n]&&(s[n]=s[n].filter(t=>t!==e))},getContext(){return i},invoke(n,e){let t=++k;return l({type:"invoke",invoke_id:t,action:n,data:e||{}}),new Promise((d,r)=>{o[t]={resolve:d,reject:r},setTimeout(()=>{o[t]&&(o[t].reject(new Error("Invoke timeout")),delete o[t])},3e4)})}},y=p;return g(E);})();
2
2
  if(typeof window!=="undefined"&&CrmAppSDK&&CrmAppSDK.CrmApp){window.CrmApp=CrmAppSDK.CrmApp;}
3
3
  //# sourceMappingURL=index.global.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * CRM Embeddable App SDK\n * Enables communication between third-party iframes and the CRM host.\n *\n * @packageDocumentation\n */\n\n/** Context provided by the CRM host after initialization */\nexport interface CrmContext {\n token: string | null;\n workspace_id: string;\n conversation_id: string | null;\n contact_id: string | null;\n conversation_metadata?: Record<string, unknown>;\n}\n\n/** Supported SDK event types */\nexport type CrmEventType = 'ready' | 'context_update';\n\n/** Event listener callback */\nexport type CrmEventListener = (data: CrmContext) => void;\n\n/** Public SDK interface */\nexport interface CrmAppSDK {\n /** Signal readiness to the CRM host and start the handshake */\n init(): void;\n /** Register an event listener */\n on(event: CrmEventType, fn: CrmEventListener): void;\n /** Remove an event listener */\n off(event: CrmEventType, fn: CrmEventListener): void;\n /** Get the current context (null before initialization) */\n getContext(): CrmContext | null;\n /** Request an action from the CRM host. Returns a Promise that resolves with the result. */\n invoke<T = unknown>(action: string, data?: Record<string, unknown>): Promise<T>;\n}\n\n// ---------------------------------------------------------------------------\n// Internal state\n// ---------------------------------------------------------------------------\n\nlet context: CrmContext | null = null;\nconst listeners: Record<string, CrmEventListener[]> = {};\nconst pendingInvokes: Record<\n number,\n { resolve: (value: unknown) => void; reject: (reason: Error) => void }\n> = {};\nlet invokeCounter = 0;\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction emit(event: string, data: CrmContext): void {\n const fns = listeners[event] || [];\n for (const fn of fns) {\n try {\n fn(data);\n } catch (e) {\n console.error('[CrmApp] Listener error:', e);\n }\n }\n}\n\nfunction postToHost(msg: Record<string, unknown>): void {\n if (\n typeof window !== 'undefined' &&\n window.parent &&\n window.parent !== window\n ) {\n window.parent.postMessage({ source: 'crm-app', ...msg }, '*');\n }\n}\n\nfunction handleMessage(event: MessageEvent): void {\n const { data } = event;\n if (!data || data.source !== 'crm-host') return;\n\n switch (data.type) {\n case 'init':\n context = data.context ?? null;\n if (context) emit('ready', context);\n break;\n\n case 'context_update':\n context = data.context ?? null;\n if (context) emit('context_update', context);\n break;\n\n case 'response': {\n const id: number | undefined = data.invoke_id;\n if (id != null && pendingInvokes[id]) {\n if (data.error) {\n pendingInvokes[id].reject(new Error(data.error));\n } else {\n pendingInvokes[id].resolve(data.result);\n }\n delete pendingInvokes[id];\n }\n break;\n }\n }\n}\n\n// Auto-register message listener in browser environments\nif (typeof window !== 'undefined') {\n window.addEventListener('message', handleMessage, false);\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\nexport const CrmApp: CrmAppSDK = {\n init(): void {\n postToHost({ type: 'app_ready' });\n },\n\n on(event: CrmEventType, fn: CrmEventListener): void {\n if (!listeners[event]) listeners[event] = [];\n listeners[event].push(fn);\n },\n\n off(event: CrmEventType, fn: CrmEventListener): void {\n if (!listeners[event]) return;\n listeners[event] = listeners[event].filter((f) => f !== fn);\n },\n\n getContext(): CrmContext | null {\n return context;\n },\n\n invoke<T = unknown>(\n action: string,\n data?: Record<string, unknown>,\n ): Promise<T> {\n const id = ++invokeCounter;\n postToHost({\n type: 'invoke',\n invoke_id: id,\n action,\n data: data || {},\n });\n\n return new Promise<T>((resolve, reject) => {\n pendingInvokes[id] = {\n resolve: resolve as (value: unknown) => void,\n reject,\n };\n setTimeout(() => {\n if (pendingInvokes[id]) {\n pendingInvokes[id].reject(new Error('Invoke timeout'));\n delete pendingInvokes[id];\n }\n }, 30000);\n });\n },\n};\n\n// Default export for convenience\nexport default CrmApp;\n"],"mappings":"6bAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,YAAAE,EAAA,YAAAC,IAwCA,IAAIC,EAA6B,KAC3BC,EAAgD,CAAC,EACjDC,EAGF,CAAC,EACDC,EAAgB,EAMpB,SAASC,EAAKC,EAAeC,EAAwB,CACnD,IAAMC,EAAMN,EAAUI,CAAK,GAAK,CAAC,EACjC,QAAWG,KAAMD,EACf,GAAI,CACFC,EAAGF,CAAI,CACT,OAASG,EAAG,CACV,QAAQ,MAAM,2BAA4BA,CAAC,CAC7C,CAEJ,CAEA,SAASC,EAAWC,EAAoC,CAEpD,OAAO,OAAW,KAClB,OAAO,QACP,OAAO,SAAW,QAElB,OAAO,OAAO,YAAY,CAAE,OAAQ,UAAW,GAAGA,CAAI,EAAG,GAAG,CAEhE,CAEA,SAASC,EAAcP,EAA2B,CAChD,GAAM,CAAE,KAAAC,CAAK,EAAID,EACjB,GAAI,GAACC,GAAQA,EAAK,SAAW,YAE7B,OAAQA,EAAK,KAAM,CACjB,IAAK,OACHN,EAAUM,EAAK,SAAW,KACtBN,GAASI,E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ners","pendingInvokes","invokeCounter","emit","event","data","fns","fn","e","postToHost","msg","handleMessage","id","f","action","resolve","reject"]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * CRM Embeddable App SDK\n * Enables communication between third-party iframes and the CRM host.\n *\n * @packageDocumentation\n */\n\n/** Context provided by the CRM host after initialization */\nexport interface CrmContext {\n token: string | null;\n workspace_id: string;\n conversation_id: string | null;\n contact_id: string | null;\n conversation_metadata?: Record<string, unknown>;\n}\n\n/** Supported SDK event types */\nexport type CrmEventType = 'ready' | 'context_update';\n\n/** Event listener callback */\nexport type CrmEventListener = (data: CrmContext) => void;\n\n/** Public SDK interface */\nexport interface CrmAppSDK {\n /** Signal readiness to the CRM host and start the handshake */\n init(): void;\n /** Register an event listener */\n on(event: CrmEventType, fn: CrmEventListener): void;\n /** Remove an event listener */\n off(event: CrmEventType, fn: CrmEventListener): void;\n /** Get the current context (null before initialization) */\n getContext(): CrmContext | null;\n /** Request an action from the CRM host. Returns a Promise that resolves with the result. */\n invoke<T = unknown>(action: string, data?: Record<string, unknown>): Promise<T>;\n}\n\n// ---------------------------------------------------------------------------\n// Internal state\n// ---------------------------------------------------------------------------\n\nlet context: CrmContext | null = null;\nconst listeners: Record<string, CrmEventListener[]> = {};\nconst pendingInvokes: Record<\n number,\n { resolve: (value: unknown) => void; reject: (reason: Error) => void }\n> = {};\nlet invokeCounter = 0;\n/** Captured origin of the CRM host — used as postMessage targetOrigin */\nlet hostOrigin: string | null = null;\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction emit(event: string, data: CrmContext): void {\n const fns = listeners[event] || [];\n for (const fn of fns) {\n try {\n fn(data);\n } catch (e) {\n console.error('[CrmApp] Listener error:', e);\n }\n }\n}\n\nfunction postToHost(msg: Record<string, unknown>): void {\n if (\n typeof window !== 'undefined' &&\n window.parent &&\n window.parent !== window\n ) {\n // Use the captured host origin for security; fall back to '*' only during\n // the initial handshake before the host origin is known.\n const target = hostOrigin || '*';\n window.parent.postMessage({ source: 'crm-app', ...msg }, target);\n }\n}\n\nfunction handleMessage(event: MessageEvent): void {\n const { data } = event;\n if (!data || data.source !== 'crm-host') return;\n\n // Capture the host origin from the first trusted message\n if (!hostOrigin && event.origin) {\n hostOrigin = event.origin;\n }\n\n // After host origin is established, reject messages from other origins\n if (hostOrigin && event.origin !== hostOrigin) return;\n\n switch (data.type) {\n case 'init':\n context = data.context ?? null;\n if (context) emit('ready', context);\n break;\n\n case 'context_update':\n context = data.context ?? null;\n if (context) emit('context_update', context);\n break;\n\n case 'response': {\n const id: number | undefined = data.invoke_id;\n if (id != null && pendingInvokes[id]) {\n if (data.error) {\n pendingInvokes[id].reject(new Error(data.error));\n } else {\n pendingInvokes[id].resolve(data.result);\n }\n delete pendingInvokes[id];\n }\n break;\n }\n }\n}\n\n// Auto-register message listener in browser environments\nif (typeof window !== 'undefined') {\n window.addEventListener('message', handleMessage, false);\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\nexport const CrmApp: CrmAppSDK = {\n init(): void {\n postToHost({ type: 'app_ready' });\n },\n\n on(event: CrmEventType, fn: CrmEventListener): void {\n if (!listeners[event]) listeners[event] = [];\n listeners[event].push(fn);\n },\n\n off(event: CrmEventType, fn: CrmEventListener): void {\n if (!listeners[event]) return;\n listeners[event] = listeners[event].filter((f) => f !== fn);\n },\n\n getContext(): CrmContext | null {\n return context;\n },\n\n invoke<T = unknown>(\n action: string,\n data?: Record<string, unknown>,\n ): Promise<T> {\n const id = ++invokeCounter;\n postToHost({\n type: 'invoke',\n invoke_id: id,\n action,\n data: data || {},\n });\n\n return new Promise<T>((resolve, reject) => {\n pendingInvokes[id] = {\n resolve: resolve as (value: unknown) => void,\n reject,\n };\n setTimeout(() => {\n if (pendingInvokes[id]) {\n pendingInvokes[id].reject(new Error('Invoke timeout'));\n delete pendingInvokes[id];\n }\n }, 30000);\n });\n },\n};\n\n// Default export for convenience\nexport default CrmApp;\n"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B,EAAoB,CAC/B,MAAa,CACXa,EAAW,CAAE,KAAM,WAAY,CAAC,CAClC,EAEA,GAAGL,EAAqBG,EAA4B,CAC7CR,EAAUK,CAAK,IAAGL,EAAUK,CAAK,EAAI,CAAC,GAC3CL,EAAUK,CAAK,EAAE,KAAKG,CAAE,CAC1B,EAEA,IAAIH,EAAqBG,EAA4B,CAC9CR,EAAUK,CAAK,IACpBL,EAAUK,CAAK,EAAIL,EAAUK,CAAK,EAAE,OAAQU,GAAMA,IAAMP,CAAE,EAC5D,EAEA,YAAgC,CAC9B,OAAOT,CACT,EAEA,OACEiB,EACAV,EACY,CACZ,IAAMQ,EAAK,EAAEZ,EACb,OAAAQ,EAAW,CACT,KAAM,SACN,UAAWI,EACX,OAAAE,EACA,KAAMV,GAAQ,CAAC,CACjB,CAAC,EAEM,IAAI,QAAW,CAACW,EAASC,IAAW,CACzCjB,EAAea,CAAE,EAAI,CACnB,QAASG,EACT,OAAAC,CACF,EACA,WAAW,IAAM,CACXjB,EAAea,CAAE,IACnBb,EAAea,CAAE,EAAE,OAAO,IAAI,MAAM,gBAAgB,CAAC,EACrD,OAAOb,EAAea,CAAE,EAE5B,EAAG,GAAK,CACV,CAAC,CACH,CACF,EAGOhB,EAAQD","names":["index_exports","__export","CrmApp","index_default","context","listeners","pendingInvokes","invokeCounter","hostOrigin","emit","event","data","fns","fn","e","postToHost","msg","target","handleMessage","id","f","action","resolve","reject"]}
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var a=Object.defineProperty;var v=Object.getOwnPropertyDescriptor;var l=Object.getOwnPropertyNames;var f=Object.prototype.hasOwnProperty;var m=(n,e)=>{for(var t in e)a(n,t,{get:e[t],enumerable:!0})},C=(n,e,t,d)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of l(e))!f.call(n,r)&&r!==t&&a(n,r,{get:()=>e[r],enumerable:!(d=v(e,r))||d.enumerable});return n};var w=n=>C(a({},"__esModule",{value:!0}),n);var y={};m(y,{CrmApp:()=>p,default:()=>g});module.exports=w(y);var i=null,s={},o={},k=0;function c(n,e){let t=s[n]||[];for(let d of t)try{d(e)}catch(r){console.error("[CrmApp] Listener error:",r)}}function u(n){typeof window<"u"&&window.parent&&window.parent!==window&&window.parent.postMessage({source:"crm-app",...n},"*")}function x(n){let{data:e}=n;if(!(!e||e.source!=="crm-host"))switch(e.type){case"init":i=e.context??null,i&&c("ready",i);break;case"context_update":i=e.context??null,i&&c("context_update",i);break;case"response":{let t=e.invoke_id;t!=null&&o[t]&&(e.error?o[t].reject(new Error(e.error)):o[t].resolve(e.result),delete o[t]);break}}}typeof window<"u"&&window.addEventListener("message",x,!1);var p={init(){u({type:"app_ready"})},on(n,e){s[n]||(s[n]=[]),s[n].push(e)},off(n,e){s[n]&&(s[n]=s[n].filter(t=>t!==e))},getContext(){return i},invoke(n,e){let t=++k;return u({type:"invoke",invoke_id:t,action:n,data:e||{}}),new Promise((d,r)=>{o[t]={resolve:d,reject:r},setTimeout(()=>{o[t]&&(o[t].reject(new Error("Invoke timeout")),delete o[t])},3e4)})}},g=p;0&&(module.exports={CrmApp});
1
+ var o=null,i={},r={},l=0,s=null;function c(n,e){let t=i[n]||[];for(let d of t)try{d(e)}catch(a){console.error("[CrmApp] Listener error:",a)}}function u(n){if(typeof window<"u"&&window.parent&&window.parent!==window){let e=s||"*";window.parent.postMessage({source:"crm-app",...n},e)}}function p(n){let{data:e}=n;if(!(!e||e.source!=="crm-host")&&(!s&&n.origin&&(s=n.origin),!(s&&n.origin!==s)))switch(e.type){case"init":o=e.context??null,o&&c("ready",o);break;case"context_update":o=e.context??null,o&&c("context_update",o);break;case"response":{let t=e.invoke_id;t!=null&&r[t]&&(e.error?r[t].reject(new Error(e.error)):r[t].resolve(e.result),delete r[t]);break}}}typeof window<"u"&&window.addEventListener("message",p,!1);var v={init(){u({type:"app_ready"})},on(n,e){i[n]||(i[n]=[]),i[n].push(e)},off(n,e){i[n]&&(i[n]=i[n].filter(t=>t!==e))},getContext(){return o},invoke(n,e){let t=++l;return u({type:"invoke",invoke_id:t,action:n,data:e||{}}),new Promise((d,a)=>{r[t]={resolve:d,reject:a},setTimeout(()=>{r[t]&&(r[t].reject(new Error("Invoke timeout")),delete r[t])},3e4)})}},f=v;export{v as CrmApp,f as default};
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * CRM Embeddable App SDK\n * Enables communication between third-party iframes and the CRM host.\n *\n * @packageDocumentation\n */\n\n/** Context provided by the CRM host after initialization */\nexport interface CrmContext {\n token: string | null;\n workspace_id: string;\n conversation_id: string | null;\n contact_id: string | null;\n conversation_metadata?: Record<string, unknown>;\n}\n\n/** Supported SDK event types */\nexport type CrmEventType = 'ready' | 'context_update';\n\n/** Event listener callback */\nexport type CrmEventListener = (data: CrmContext) => void;\n\n/** Public SDK interface */\nexport interface CrmAppSDK {\n /** Signal readiness to the CRM host and start the handshake */\n init(): void;\n /** Register an event listener */\n on(event: CrmEventType, fn: CrmEventListener): void;\n /** Remove an event listener */\n off(event: CrmEventType, fn: CrmEventListener): void;\n /** Get the current context (null before initialization) */\n getContext(): CrmContext | null;\n /** Request an action from the CRM host. Returns a Promise that resolves with the result. */\n invoke<T = unknown>(action: string, data?: Record<string, unknown>): Promise<T>;\n}\n\n// ---------------------------------------------------------------------------\n// Internal state\n// ---------------------------------------------------------------------------\n\nlet context: CrmContext | null = null;\nconst listeners: Record<string, CrmEventListener[]> = {};\nconst pendingInvokes: Record<\n number,\n { resolve: (value: unknown) => void; reject: (reason: Error) => void }\n> = {};\nlet invokeCounter = 0;\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction emit(event: string, data: CrmContext): void {\n const fns = listeners[event] || [];\n for (const fn of fns) {\n try {\n fn(data);\n } catch (e) {\n console.error('[CrmApp] Listener error:', e);\n }\n }\n}\n\nfunction postToHost(msg: Record<string, unknown>): void {\n if (\n typeof window !== 'undefined' &&\n window.parent &&\n window.parent !== window\n ) {\n window.parent.postMessage({ source: 'crm-app', ...msg }, '*');\n }\n}\n\nfunction handleMessage(event: MessageEvent): void {\n const { data } = event;\n if (!data || data.source !== 'crm-host') return;\n\n switch (data.type) {\n case 'init':\n context = data.context ?? null;\n if (context) emit('ready', context);\n break;\n\n case 'context_update':\n context = data.context ?? null;\n if (context) emit('context_update', context);\n break;\n\n case 'response': {\n const id: number | undefined = data.invoke_id;\n if (id != null && pendingInvokes[id]) {\n if (data.error) {\n pendingInvokes[id].reject(new Error(data.error));\n } else {\n pendingInvokes[id].resolve(data.result);\n }\n delete pendingInvokes[id];\n }\n break;\n }\n }\n}\n\n// Auto-register message listener in browser environments\nif (typeof window !== 'undefined') {\n window.addEventListener('message', handleMessage, false);\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\nexport const CrmApp: CrmAppSDK = {\n init(): void {\n postToHost({ type: 'app_ready' });\n },\n\n on(event: CrmEventType, fn: CrmEventListener): void {\n if (!listeners[event]) listeners[event] = [];\n listeners[event].push(fn);\n },\n\n off(event: CrmEventType, fn: CrmEventListener): void {\n if (!listeners[event]) return;\n listeners[event] = listeners[event].filter((f) => f !== fn);\n },\n\n getContext(): CrmContext | null {\n return context;\n },\n\n invoke<T = unknown>(\n action: string,\n data?: Record<string, unknown>,\n ): Promise<T> {\n const id = ++invokeCounter;\n postToHost({\n type: 'invoke',\n invoke_id: id,\n action,\n data: data || {},\n });\n\n return new Promise<T>((resolve, reject) => {\n pendingInvokes[id] = {\n resolve: resolve as (value: unknown) => void,\n reject,\n };\n setTimeout(() => {\n if (pendingInvokes[id]) {\n pendingInvokes[id].reject(new Error('Invoke timeout'));\n delete pendingInvokes[id];\n }\n }, 30000);\n });\n },\n};\n\n// Default export for convenience\nexport default CrmApp;\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,YAAAE,EAAA,YAAAC,IAAA,eAAAC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CAC1B,EAEA,IAAIH,EAAqBG,EAA4B,CAC9CP,EAAUI,CAAK,IACpBJ,EAAUI,CAAK,EAAIJ,EAAUI,CAAK,EAAE,OAAQS,GAAMA,IAAMN,CAAE,EAC5D,EAEA,YAAgC,CAC9B,OAAOR,CACT,EAEA,OACEe,EACAT,EACY,CACZ,IAAMO,EAAK,EAAEV,EACb,OAAAO,EAAW,CACT,KAAM,SACN,UAAWG,EACX,OAAAE,EACA,KAAMT,GAAQ,CAAC,CACjB,CAAC,EAEM,IAAI,QAAW,CAACU,EAASC,IAAW,CACzCf,EAAeW,CAAE,EAAI,CACnB,QAASG,EACT,OAAAC,CACF,EACA,WAAW,IAAM,CACXf,EAAeW,CAAE,IACnBX,EAAeW,CAAE,EAAE,OAAO,IAAI,MAAM,gBAAgB,CAAC,EACrD,OAAOX,EAAeW,CAAE,EAE5B,EAAG,GAAK,CACV,CAAC,CACH,CACF,EAGOf,EAAQD","names":["index_exports","__export","CrmApp","index_default","__toCommonJS","context","listeners","pendingInvokes","invokeCounter","emit","event","data","fns","fn","e","postToHost","msg","handleMessage","id","f","action","resolve","reject"]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * CRM Embeddable App SDK\n * Enables communication between third-party iframes and the CRM host.\n *\n * @packageDocumentation\n */\n\n/** Context provided by the CRM host after initialization */\nexport interface CrmContext {\n token: string | null;\n workspace_id: string;\n conversation_id: string | null;\n contact_id: string | null;\n conversation_metadata?: Record<string, unknown>;\n}\n\n/** Supported SDK event types */\nexport type CrmEventType = 'ready' | 'context_update';\n\n/** Event listener callback */\nexport type CrmEventListener = (data: CrmContext) => void;\n\n/** Public SDK interface */\nexport interface CrmAppSDK {\n /** Signal readiness to the CRM host and start the handshake */\n init(): void;\n /** Register an event listener */\n on(event: CrmEventType, fn: CrmEventListener): void;\n /** Remove an event listener */\n off(event: CrmEventType, fn: CrmEventListener): void;\n /** Get the current context (null before initialization) */\n getContext(): CrmContext | null;\n /** Request an action from the CRM host. Returns a Promise that resolves with the result. */\n invoke<T = unknown>(action: string, data?: Record<string, unknown>): Promise<T>;\n}\n\n// ---------------------------------------------------------------------------\n// Internal state\n// ---------------------------------------------------------------------------\n\nlet context: CrmContext | null = null;\nconst listeners: Record<string, CrmEventListener[]> = {};\nconst pendingInvokes: Record<\n number,\n { resolve: (value: unknown) => void; reject: (reason: Error) => void }\n> = {};\nlet invokeCounter = 0;\n/** Captured origin of the CRM host — used as postMessage targetOrigin */\nlet hostOrigin: string | null = null;\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction emit(event: string, data: CrmContext): void {\n const fns = listeners[event] || [];\n for (const fn of fns) {\n try {\n fn(data);\n } catch (e) {\n console.error('[CrmApp] Listener error:', e);\n }\n }\n}\n\nfunction postToHost(msg: Record<string, unknown>): void {\n if (\n typeof window !== 'undefined' &&\n window.parent &&\n window.parent !== window\n ) {\n // Use the captured host origin for security; fall back to '*' only during\n // the initial handshake before the host origin is known.\n const target = hostOrigin || '*';\n window.parent.postMessage({ source: 'crm-app', ...msg }, target);\n }\n}\n\nfunction handleMessage(event: MessageEvent): void {\n const { data } = event;\n if (!data || data.source !== 'crm-host') return;\n\n // Capture the host origin from the first trusted message\n if (!hostOrigin && event.origin) {\n hostOrigin = event.origin;\n }\n\n // After host origin is established, reject messages from other origins\n if (hostOrigin && event.origin !== hostOrigin) return;\n\n switch (data.type) {\n case 'init':\n context = data.context ?? null;\n if (context) emit('ready', context);\n break;\n\n case 'context_update':\n context = data.context ?? null;\n if (context) emit('context_update', context);\n break;\n\n case 'response': {\n const id: number | undefined = data.invoke_id;\n if (id != null && pendingInvokes[id]) {\n if (data.error) {\n pendingInvokes[id].reject(new Error(data.error));\n } else {\n pendingInvokes[id].resolve(data.result);\n }\n delete pendingInvokes[id];\n }\n break;\n }\n }\n}\n\n// Auto-register message listener in browser environments\nif (typeof window !== 'undefined') {\n window.addEventListener('message', handleMessage, false);\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\nexport const CrmApp: CrmAppSDK = {\n init(): void {\n postToHost({ type: 'app_ready' });\n },\n\n on(event: CrmEventType, fn: CrmEventListener): void {\n if (!listeners[event]) listeners[event] = [];\n listeners[event].push(fn);\n },\n\n off(event: CrmEventType, fn: CrmEventListener): void {\n if (!listeners[event]) return;\n listeners[event] = listeners[event].filter((f) => f !== fn);\n },\n\n getContext(): CrmContext | null {\n return context;\n },\n\n invoke<T = unknown>(\n action: string,\n data?: Record<string, unknown>,\n ): Promise<T> {\n const id = ++invokeCounter;\n postToHost({\n type: 'invoke',\n invoke_id: id,\n action,\n data: data || {},\n });\n\n return new Promise<T>((resolve, reject) => {\n pendingInvokes[id] = {\n resolve: resolve as (value: unknown) => void,\n reject,\n };\n setTimeout(() => {\n if (pendingInvokes[id]) {\n pendingInvokes[id].reject(new Error('Invoke timeout'));\n delete pendingInvokes[id];\n }\n }, 30000);\n });\n },\n};\n\n// Default export for convenience\nexport default CrmApp;\n"],"mappings":"AAwCA,IAAIA,EAA6B,KAC3BC,EAAgD,CAAC,EACjDC,EAGF,CAAC,EACDC,EAAgB,EAEhBC,EAA4B,KAMhC,SAASC,EAAKC,EAAeC,EAAwB,CACnD,IAAMC,EAAMP,EAAUK,CAAK,GAAK,CAAC,EACjC,QAAWG,KAAMD,EACf,GAAI,CACFC,EAAGF,CAAI,CACT,OAASG,EAAG,CACV,QAAQ,MAAM,2BAA4BA,CAAC,CAC7C,CAEJ,CAEA,SAASC,EAAWC,EAAoC,CACtD,GACE,OAAO,OAAW,KAClB,OAAO,QACP,OAAO,SAAW,OAClB,CAGA,IAAMC,EAAST,GAAc,IAC7B,OAAO,OAAO,YAAY,CAAE,OAAQ,UAAW,GAAGQ,CAAI,EAAGC,CAAM,CACjE,CACF,CAEA,SAASC,EAAcR,EAA2B,CAChD,GAAM,CAAE,KAAAC,CAAK,EAAID,EACjB,GAAI,GAACC,GAAQA,EAAK,SAAW,cAGzB,CAACH,GAAcE,E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gBAAgB,CAAC,EACrD,OAAOb,EAAea,CAAE,EAE5B,EAAG,GAAK,CACV,CAAC,CACH,CACF,EAGOM,EAAQL","names":["context","listeners","pendingInvokes","invokeCounter","hostOrigin","emit","event","data","fns","fn","e","postToHost","msg","target","handleMessage","id","CrmApp","f","action","resolve","reject","index_default"]}
package/package.json CHANGED
@@ -1,7 +1,8 @@
1
1
  {
2
2
  "name": "@first-to-fly/crm-sdk",
3
- "version": "1.0.1",
4
- "description": "CRM Embeddable App SDK — enables communication between third-party iframes and the CRM host",
3
+ "version": "1.1.0",
4
+ "description": "CRM SDK — embed third-party apps inside the CRM, or embed the CRM inside your own SaaS (proxy-free, signed-assertion auth)",
5
+ "type": "module",
5
6
  "main": "dist/index.cjs",
6
7
  "module": "dist/index.js",
7
8
  "browser": "dist/index.global.js",
@@ -17,7 +18,27 @@
17
18
  "default": "./dist/index.cjs"
18
19
  }
19
20
  },
20
- "./umd": "./dist/index.global.js"
21
+ "./umd": "./dist/index.global.js",
22
+ "./embed-host": {
23
+ "import": {
24
+ "types": "./dist/embed-host.d.ts",
25
+ "default": "./dist/embed-host.js"
26
+ },
27
+ "require": {
28
+ "types": "./dist/embed-host.d.cts",
29
+ "default": "./dist/embed-host.cjs"
30
+ }
31
+ },
32
+ "./embed-server": {
33
+ "import": {
34
+ "types": "./dist/embed-server.d.ts",
35
+ "default": "./dist/embed-server.js"
36
+ },
37
+ "require": {
38
+ "types": "./dist/embed-server.d.cts",
39
+ "default": "./dist/embed-server.cjs"
40
+ }
41
+ }
21
42
  },
22
43
  "files": [
23
44
  "dist",
@@ -36,11 +57,23 @@
36
57
  "sdk",
37
58
  "iframe",
38
59
  "embeddable",
39
- "postmessage"
60
+ "postmessage",
61
+ "embed",
62
+ "jwt",
63
+ "assertion"
40
64
  ],
41
65
  "author": "First to Fly",
42
66
  "license": "MIT",
67
+ "peerDependencies": {
68
+ "jose": ">=5"
69
+ },
70
+ "peerDependenciesMeta": {
71
+ "jose": {
72
+ "optional": true
73
+ }
74
+ },
43
75
  "devDependencies": {
76
+ "jose": "^5.9.6",
44
77
  "@types/jsdom": "^28.0.0",
45
78
  "jsdom": "^28.1.0",
46
79
  "tsup": "^8.5.1",
package/dist/index.mjs DELETED
@@ -1,2 +0,0 @@
1
- var o=null,i={},r={},u=0;function a(n,e){let t=i[n]||[];for(let s of t)try{s(e)}catch(d){console.error("[CrmApp] Listener error:",d)}}function c(n){typeof window<"u"&&window.parent&&window.parent!==window&&window.parent.postMessage({source:"crm-app",...n},"*")}function p(n){let{data:e}=n;if(!(!e||e.source!=="crm-host"))switch(e.type){case"init":o=e.context??null,o&&a("ready",o);break;case"context_update":o=e.context??null,o&&a("context_update",o);break;case"response":{let t=e.invoke_id;t!=null&&r[t]&&(e.error?r[t].reject(new Error(e.error)):r[t].resolve(e.result),delete r[t]);break}}}typeof window<"u"&&window.addEventListener("message",p,!1);var v={init(){c({type:"app_ready"})},on(n,e){i[n]||(i[n]=[]),i[n].push(e)},off(n,e){i[n]&&(i[n]=i[n].filter(t=>t!==e))},getContext(){return o},invoke(n,e){let t=++u;return c({type:"invoke",invoke_id:t,action:n,data:e||{}}),new Promise((s,d)=>{r[t]={resolve:s,reject:d},setTimeout(()=>{r[t]&&(r[t].reject(new Error("Invoke timeout")),delete r[t])},3e4)})}},l=v;export{v as CrmApp,l as default};
2
- //# sourceMappingURL=index.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * CRM Embeddable App SDK\n * Enables communication between third-party iframes and the CRM host.\n *\n * @packageDocumentation\n */\n\n/** Context provided by the CRM host after initialization */\nexport interface CrmContext {\n token: string | null;\n workspace_id: string;\n conversation_id: string | null;\n contact_id: string | null;\n conversation_metadata?: Record<string, unknown>;\n}\n\n/** Supported SDK event types */\nexport type CrmEventType = 'ready' | 'context_update';\n\n/** Event listener callback */\nexport type CrmEventListener = (data: CrmContext) => void;\n\n/** Public SDK interface */\nexport interface CrmAppSDK {\n /** Signal readiness to the CRM host and start the handshake */\n init(): void;\n /** Register an event listener */\n on(event: CrmEventType, fn: CrmEventListener): void;\n /** Remove an event listener */\n off(event: CrmEventType, fn: CrmEventListener): void;\n /** Get the current context (null before initialization) */\n getContext(): CrmContext | null;\n /** Request an action from the CRM host. Returns a Promise that resolves with the result. */\n invoke<T = unknown>(action: string, data?: Record<string, unknown>): Promise<T>;\n}\n\n// ---------------------------------------------------------------------------\n// Internal state\n// ---------------------------------------------------------------------------\n\nlet context: CrmContext | null = null;\nconst listeners: Record<string, CrmEventListener[]> = {};\nconst pendingInvokes: Record<\n number,\n { resolve: (value: unknown) => void; reject: (reason: Error) => void }\n> = {};\nlet invokeCounter = 0;\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction emit(event: string, data: CrmContext): void {\n const fns = listeners[event] || [];\n for (const fn of fns) {\n try {\n fn(data);\n } catch (e) {\n console.error('[CrmApp] Listener error:', e);\n }\n }\n}\n\nfunction postToHost(msg: Record<string, unknown>): void {\n if (\n typeof window !== 'undefined' &&\n window.parent &&\n window.parent !== window\n ) {\n window.parent.postMessage({ source: 'crm-app', ...msg }, '*');\n }\n}\n\nfunction handleMessage(event: MessageEvent): void {\n const { data } = event;\n if (!data || data.source !== 'crm-host') return;\n\n switch (data.type) {\n case 'init':\n context = data.context ?? null;\n if (context) emit('ready', context);\n break;\n\n case 'context_update':\n context = data.context ?? null;\n if (context) emit('context_update', context);\n break;\n\n case 'response': {\n const id: number | undefined = data.invoke_id;\n if (id != null && pendingInvokes[id]) {\n if (data.error) {\n pendingInvokes[id].reject(new Error(data.error));\n } else {\n pendingInvokes[id].resolve(data.result);\n }\n delete pendingInvokes[id];\n }\n break;\n }\n }\n}\n\n// Auto-register message listener in browser environments\nif (typeof window !== 'undefined') {\n window.addEventListener('message', handleMessage, false);\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\nexport const CrmApp: CrmAppSDK = {\n init(): void {\n postToHost({ type: 'app_ready' });\n },\n\n on(event: CrmEventType, fn: CrmEventListener): void {\n if (!listeners[event]) listeners[event] = [];\n listeners[event].push(fn);\n },\n\n off(event: CrmEventType, fn: CrmEventListener): void {\n if (!listeners[event]) return;\n listeners[event] = listeners[event].filter((f) => f !== fn);\n },\n\n getContext(): CrmContext | null {\n return context;\n },\n\n invoke<T = unknown>(\n action: string,\n data?: Record<string, unknown>,\n ): Promise<T> {\n const id = ++invokeCounter;\n postToHost({\n type: 'invoke',\n invoke_id: id,\n action,\n data: data || {},\n });\n\n return new Promise<T>((resolve, reject) => {\n pendingInvokes[id] = {\n resolve: resolve as (value: unknown) => void,\n reject,\n };\n setTimeout(() => {\n if (pendingInvokes[id]) {\n pendingInvokes[id].reject(new Error('Invoke timeout'));\n delete pendingInvokes[id];\n }\n }, 30000);\n });\n },\n};\n\n// Default export for convenience\nexport default CrmApp;\n"],"mappings":"AAwCA,IAAIA,EAA6B,KAC3BC,EAAgD,CAAC,EACjDC,EAGF,CAAC,EACDC,EAAgB,EAMpB,SAASC,EAAKC,EAAeC,EAAwB,CACnD,IAAMC,EAAMN,EAAUI,CAAK,GAAK,CAAC,EACjC,QAAWG,KAAMD,EACf,GAAI,CACFC,EAAGF,CAAI,CACT,OAASG,EAAG,CACV,QAAQ,MAAM,2BAA4BA,CAAC,CAC7C,CAEJ,CAEA,SAASC,EAAWC,EAAoC,CAEpD,OAAO,OAAW,KAClB,OAAO,QACP,OAAO,SAAW,QAElB,OAAO,OAAO,YAAY,CAAE,OAAQ,UAAW,GAAGA,CAAI,EAAG,GAAG,CAEhE,CAEA,SAASC,EAAcP,EAA2B,CAChD,GAAM,CAAE,KAAAC,CAAK,EAAID,EACjB,GAAI,GAACC,GAAQA,EAAK,SAAW,YAE7B,OAAQA,EAAK,KAAM,CACjB,IAAK,OACHN,EAAUM,EAAK,SAAW,KACtBN,GAASI,EAAK,QAASJ,CAAO,EAClC,MAEF,IAAK,iBACHA,EAAUM,EAAK,SAAW,KACtBN,GAASI,EAAK,iBAAkBJ,CAAO,EAC3C,MAEF,IAAK,WAAY,CACf,IAAMa,EAAyBP,EAAK,UAChCO,GAAM,MAAQX,EAAeW,CAAE,IAC7BP,EAAK,MACPJ,EAAeW,CAAE,EAAE,OAAO,IAAI,MAAMP,EAAK,KAAK,CAAC,EAE/CJ,EAAeW,CAAE,EAAE,QAAQP,EAAK,MAAM,EAExC,OAAOJ,EAAeW,CAAE,GAE1B,KACF,CACF,CACF,CAGI,OAAO,OAAW,KACpB,OAAO,iBAAiB,UAAWD,EAAe,EAAK,EAOlD,IAAME,EAAoB,CAC/B,MAAa,CACXJ,EAAW,CAAE,KAAM,WAAY,CAAC,CAClC,EAEA,GAAGL,EAAqBG,EAA4B,CAC7CP,EAAUI,CAAK,IAAGJ,EAAUI,CAAK,EAAI,CAAC,GAC3CJ,EAAUI,CAAK,EAAE,KAAKG,CAAE,CAC1B,EAEA,IAAIH,EAAqBG,EAA4B,CAC9CP,EAAUI,CAAK,IACpBJ,EAAUI,CAAK,EAAIJ,EAAUI,CAAK,EAAE,OAAQU,GAAMA,IAAMP,CAAE,EAC5D,EAEA,YAAgC,CAC9B,OAAOR,CACT,EAEA,OACEgB,EACAV,EACY,CACZ,IAAMO,EAAK,EAAEV,EACb,OAAAO,EAAW,CACT,KAAM,SACN,UAAWG,EACX,OAAAG,EACA,KAAMV,GAAQ,CAAC,CACjB,CAAC,EAEM,IAAI,QAAW,CAACW,EAASC,IAAW,CACzChB,EAAeW,CAAE,EAAI,CACnB,QAASI,EACT,OAAAC,CACF,EACA,WAAW,IAAM,CACXhB,EAAeW,CAAE,IACnBX,EAAeW,CAAE,EAAE,OAAO,IAAI,MAAM,gBAAgB,CAAC,EACrD,OAAOX,EAAeW,CAAE,EAE5B,EAAG,GAAK,CACV,CAAC,CACH,CACF,EAGOM,EAAQL","names":["context","listeners","pendingInvokes","invokeCounter","emit","event","data","fns","fn","e","postToHost","msg","handleMessage","id","CrmApp","f","action","resolve","reject","index_default"]}
File without changes