@first-to-fly/crm-sdk 1.0.1 → 1.2.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,186 @@ 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**. Your server obtains a short-lived CRM bearer (via one
135
+ of the two auth options below) and hands it to the iframe over a secure `MessageChannel`.
136
+ Two modules do the heavy lifting: `embed-server` (Node/Bun) and `embed-host` (browser).
137
+
138
+ ### Choosing a server auth approach
139
+
140
+ | | Option A — API-key | Option B — Signed assertion |
141
+ |---|---|---|
142
+ | **Setup** | CRM team gives you `app_id` + `app_secret` | You generate an RS256/ES256 keypair; CRM team registers your JWKS URL |
143
+ | **Shared secret** | `app_secret` on your server | None — private key stays on your server |
144
+ | **Peer dep** | None | `jose` (`npm i jose`) |
145
+ | **Helper** | `createEmbedSessionWithKey` | `createEmbedSession` (or `mintCrmAssertion` + `exchangeAssertion`) |
146
+
147
+ ### How it works (Option A — API-key)
148
+
149
+ ```
150
+ [your server] [browser] [CRM]
151
+ createEmbedSessionWithKey(user) ─exchange─▶ CRM bearer
152
+ │
153
+ createCrmEmbedHost({ iframe, getBearer })
154
+ │ ready → channel-init → ack
155
+ └──────── auth-tokens ─────────▶ CRM iframe loads
156
+ ```
157
+
158
+ ### How it works (Option B — Signed assertion)
159
+
160
+ ```
161
+ [your server] [browser] [CRM]
162
+ createEmbedSession(user) ─mint+exchange─▶ CRM bearer
163
+ │
164
+ createCrmEmbedHost({ iframe, getBearer })
165
+ │ ready → channel-init → ack
166
+ └──────── auth-tokens ─────────▶ CRM iframe loads
167
+ ```
168
+
169
+ ---
170
+
171
+ ### Option A: API-key auth (simpler, no keypair)
172
+
173
+ #### One-time setup
174
+
175
+ 1. Ask the CRM team to register your app. They give you an **`app_id`** and **`app_secret`**.
176
+ An admin in the CRM binds your app to a CRM workspace.
177
+ 2. Ask the CRM team for their **exchange base URL** and **embed origin**.
178
+
179
+ #### Server: exchange credentials for a bearer
180
+
181
+ ```typescript
182
+ import { createEmbedSessionWithKey } from '@first-to-fly/crm-sdk/embed-server';
183
+
184
+ // Endpoint your frontend calls to (re)obtain a CRM bearer:
185
+ app.post('/api/crm/session', async (req, res) => {
186
+ const user = req.user; // your authenticated user
187
+ const session = await createEmbedSessionWithKey(
188
+ {
189
+ appId: process.env.CRM_APP_ID!,
190
+ appSecret: process.env.CRM_APP_SECRET!,
191
+ user: {
192
+ id: user.id, // stable id in YOUR system
193
+ email: user.email,
194
+ role: 'member', // 'member' | 'admin'
195
+ name: user.name, // optional
196
+ avatar_url: user.avatar, // optional
197
+ },
198
+ },
199
+ { crmBaseUrl: process.env.CRM_BASE_URL! }, // e.g. https://api.crm.example.com
200
+ );
201
+ // { accessToken, expiresIn, workspaceId, user, role }
202
+ res.json(session);
203
+ });
204
+ ```
205
+
206
+ A rejected exchange throws `CrmExchangeError` with `.status` and `.code`
207
+ (e.g. `SUBAPP_DISABLED`, `IDENTITY_CONFLICT`).
208
+
209
+ ---
210
+
211
+ ### Option B: Signed-assertion auth (zero shared-secret)
212
+
213
+ > **Requires an assertion-capable CRM endpoint.** These helpers are retained for
214
+ > partners integrating against a CRM that still exposes the RS256/JWKS assertion
215
+ > exchange. The First-to-Fly hosted CRM now uses **Option A (API-key)** only, so
216
+ > use Option A there. Confirm with the CRM team which flow their deployment supports
217
+ > before choosing Option B.
218
+
219
+ #### One-time setup
220
+
221
+ 1. Generate an RS256 (or ES256) key pair. Keep the private key on your server.
222
+ 2. Serve your **public JWKS** at a public `https` URL (see `getCrmEmbedJwks` below).
223
+ 3. Give the CRM team your **`client_id`** (issuer) and **JWKS URL**. They register your
224
+ app and enable it. An admin in the CRM binds your **`org_id`** to a CRM workspace.
225
+ 4. Ask the CRM team for their **exchange base URL** and **embed origin**.
226
+
227
+ #### Server: mint + exchange
228
+
229
+ ```typescript
230
+ import { createEmbedSession, getCrmEmbedJwks } from '@first-to-fly/crm-sdk/embed-server';
231
+
232
+ const config = {
233
+ iss: process.env.CRM_CLIENT_ID!, // == the client_id the CRM registered
234
+ privateKeyPem: process.env.CRM_PRIVATE_KEY_PEM!,
235
+ publicKeyPem: process.env.CRM_PUBLIC_KEY_PEM!,
236
+ // alg: 'RS256' (default) or 'ES256'
237
+ };
238
+
239
+ // Endpoint your frontend calls to (re)obtain a CRM bearer:
240
+ app.post('/api/crm/session', async (req, res) => {
241
+ const user = req.user; // your authenticated user
242
+ const session = await createEmbedSession(
243
+ {
244
+ sub: user.id, // stable id in YOUR system
245
+ email: user.email,
246
+ requestedRole: 'admin', // CRM clamps to the install's max_role
247
+ orgId: user.orgId, // CRM resolves the workspace from this
248
+ fullName: user.name, // optional
249
+ avatarUrl: user.avatar, // optional
250
+ },
251
+ config,
252
+ { crmBaseUrl: process.env.CRM_BASE_URL! }, // e.g. https://api.crm.example.com
253
+ );
254
+ // { accessToken, expiresIn, workspaceId, user, role }
255
+ res.json(session);
256
+ });
257
+
258
+ // Publish your public JWKS so the CRM can verify your assertions:
259
+ app.get('/crm-embed/jwks', async (_req, res) => res.json(await getCrmEmbedJwks(config)));
260
+ ```
261
+
262
+ Prefer to split minting and exchange? Use `mintCrmAssertion(input, config)` and
263
+ `exchangeAssertion(assertion, { crmBaseUrl })` directly. A rejected exchange throws
264
+ `CrmExchangeError` with `.status` and `.code` (e.g. `IDENTITY_CONFLICT`,
265
+ `WORKSPACE_NOT_OWNED`).
266
+
267
+ Requires `jose` (peer dependency): `npm i jose`.
268
+
269
+ ---
270
+
271
+ ### Browser: host the iframe (same for both options)
272
+
273
+ ```typescript
274
+ import { createCrmEmbedHost, buildCrmEmbedUrl } from '@first-to-fly/crm-sdk/embed-host';
275
+
276
+ const CRM_ORIGIN = 'https://app.crm.example.com';
277
+
278
+ async function getSession() {
279
+ const res = await fetch('/api/crm/session', { method: 'POST' });
280
+ return res.json(); // { accessToken, workspaceId, ... }
281
+ }
282
+
283
+ const { workspaceId } = await getSession();
284
+ const iframe = document.querySelector('#crm') as HTMLIFrameElement;
285
+ iframe.src = buildCrmEmbedUrl(CRM_ORIGIN, workspaceId);
286
+
287
+ const host = createCrmEmbedHost({
288
+ iframe,
289
+ crmOrigin: CRM_ORIGIN,
290
+ getBearer: async () => ({ accessToken: (await getSession()).accessToken }),
291
+ onRouteChange: (path) => console.log('CRM navigated to', path),
292
+ onError: (err) => console.error(err),
293
+ });
294
+
295
+ // Drive the CRM from your own nav:
296
+ host.navigate('/contacts');
297
+
298
+ // On unmount:
299
+ host.dispose();
300
+ ```
301
+
302
+ ### Requirements & gotchas
303
+
304
+ - `getBearer` is called on connect **and** whenever the CRM's session expires — always
305
+ return a fresh bearer (call your `/session` endpoint again).
306
+ - `crmOrigin` must exactly match the iframe's origin, and the CRM must allow your origin
307
+ in its `frame-ancestors` (the CRM team configures this).
308
+ - Assertions (Option B) are single-use and live ≤120s — always mint fresh; never cache one.
309
+ - `jose` is only required for Option B (`embed-server` assertion path): `npm i jose`.
310
+
124
311
  ## License
125
312
 
126
313
  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,EAA2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,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,CAC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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 l=Object.defineProperty;var f=Object.getOwnPropertyDescriptor;var h=Object.getOwnPropertyNames;var x=Object.prototype.hasOwnProperty;var S=(e,t)=>{for(var r in t)l(e,r,{get:t[r],enumerable:!0})},w=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of h(t))!x.call(e,s)&&s!==r&&l(e,s,{get:()=>t[s],enumerable:!(n=f(t,s))||n.enumerable});return e};var k=e=>w(l({},"__esModule",{value:!0}),e);var T={};S(T,{CrmExchangeError:()=>d,createEmbedSession:()=>U,createEmbedSessionWithKey:()=>C,exchangeAssertion:()=>b,getCrmEmbedJwks:()=>P,mintCrmAssertion:()=>y,resetCrmEmbedKeys:()=>I});module.exports=k(T);var o=require("jose"),d=class extends Error{constructor(r,n,s,a){super(r);this.status=n;this.code=s;this.detail=a;this.name="CrmExchangeError"}};async function C(e,t){let r=t.fetch??fetch,n=`${t.crmBaseUrl.replace(/\/$/,"")}/api/auth/exchange`,s=await r(n,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:e.appId,app_secret:e.appSecret,user:e.user})}),a=await s.json().catch(()=>({}));if(!s.ok){let c=a?.error?.code??`HTTP_${s.status}`,m=a?.error?.message??"CRM exchange failed";throw new d(m,s.status,c,a)}let i=a?.data??{};return{accessToken:i.access_token,expiresIn:i.expires_in,workspaceId:i.workspace?.id,user:i.user,role:i.role}}var E="crm",g=120,p=new Map;function K(){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,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 u(e){let t=e.alg??"RS256",r=`${e.iss}:${t}`,n=p.get(r);if(n)return n;let s=(async()=>{let a=await(0,o.importPKCS8)(e.privateKeyPem,t),i=await(0,o.importSPKI)(e.publicKeyPem,t),c=await(0,o.exportJWK)(i),m=await(0,o.calculateJwkThumbprint)(c);return{privateKey:a,publicJwk:{...c,kid:m,alg:t,use:"sig"},kid:m}})();return p.set(r,s),s}function I(){p.clear()}async function P(e){let{publicJwk:t}=await u(e);return{keys:[t]}}async function y(e,t,r){let n=t.alg??"RS256",{privateKey:s,kid:a}=await u(t),i=Math.min(r?.ttlSeconds??g,g);return new o.SignJWT({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:n,kid:a}).setSubject(e.sub).setIssuer(t.iss).setAudience(E).setIssuedAt().setExpirationTime(`${i}s`).setJti(K()).sign(s)}async function b(e,t){let r=t.fetch??fetch,n=`${t.crmBaseUrl.replace(/\/$/,"")}/api/auth/exchange`,s=await r(n,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({assertion:e})}),a=await s.json().catch(()=>({}));if(!s.ok){let c=a?.error?.code??`HTTP_${s.status}`,m=a?.error?.message??"CRM exchange failed";throw new d(m,s.status,c,a)}let i=a?.data??{};return{accessToken:i.access_token,expiresIn:i.expires_in,workspaceId:i.workspace?.id,user:i.user,role:i.role}}async function U(e,t,r){let n=await y(e,t);return b(n,r)}0&&(module.exports={CrmExchangeError,createEmbedSession,createEmbedSessionWithKey,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. Two auth\n * approaches are supported:\n *\n * **Option A — API-key auth (simpler, no keypair):**\n * POST user identity + your registered `app_id`/`app_secret` to the CRM.\n * Use {@link createEmbedSessionWithKey}. No `jose` required.\n *\n * **Option B — Signed-assertion auth (zero shared-secret):**\n * Mint a short-lived asymmetric (RS256/ES256) assertion server-side and\n * exchange it at the CRM for a CRM bearer. Use {@link createEmbedSession} (or\n * {@link mintCrmAssertion} + {@link exchangeAssertion} separately).\n * Requires the `jose` peer dependency.\n *\n * Both paths return a short-lived CRM bearer; hand that bearer to the CRM\n * iframe via `embed-host` (see ./embed-host).\n *\n * Works in Node and Bun (or any environment with a global `fetch`).\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\n// ─── Shared error class ──────────────────────────────────────────────────────\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\n// ─── Option A: API-key auth ──────────────────────────────────────────────────\n\n/** The end-user being embedded into the CRM. */\nexport interface EmbedUser {\n id: string;\n email: string;\n role: 'member' | 'admin';\n name?: string;\n avatar_url?: string;\n}\n\n/** Input for {@link createEmbedSessionWithKey}. */\nexport interface CreateEmbedSessionWithKeyInput {\n appId: string;\n appSecret: string;\n user: EmbedUser;\n}\n\n/** The CRM session returned by {@link createEmbedSessionWithKey}. */\nexport interface EmbedSession {\n accessToken: string;\n expiresIn?: number;\n /** The CRM workspace the user was provisioned into. */\n workspaceId?: string;\n user?: unknown;\n role?: string;\n}\n\n/**\n * Exchange app credentials + user identity for a short-lived CRM bearer.\n *\n * POSTs `{ app_id, app_secret, user }` to `${crmBaseUrl}/api/auth/exchange`\n * and maps the CRM response to an {@link EmbedSession}. On non-2xx, throws\n * {@link CrmExchangeError} with `.status` and `.code`.\n *\n * @example\n * ```typescript\n * const session = await createEmbedSessionWithKey(\n * { appId: process.env.CRM_APP_ID!, appSecret: process.env.CRM_APP_SECRET!, user },\n * { crmBaseUrl: process.env.CRM_BASE_URL! },\n * );\n * // { accessToken, expiresIn, workspaceId, user, role }\n * ```\n */\nexport async function createEmbedSessionWithKey(\n input: CreateEmbedSessionWithKeyInput,\n opts: { crmBaseUrl: string; fetch?: typeof fetch },\n): Promise<EmbedSession> {\n const doFetch = opts.fetch ?? fetch;\n const url = `${opts.crmBaseUrl.replace(/\\/$/, '')}/api/auth/exchange`;\n const res = await doFetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n app_id: input.appId,\n app_secret: input.appSecret,\n user: input.user,\n }),\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// ─── Option B: Signed-assertion auth ────────────────────────────────────────\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 {@link createEmbedSession} / {@link exchangeAssertion}. */\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\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\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\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"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,sBAAAE,EAAA,uBAAAC,EAAA,8BAAAC,EAAA,sBAAAC,EAAA,oBAAAC,EAAA,qBAAAC,EAAA,sBAAAC,IAAA,eAAAC,EAAAT,GAuBA,IAAAU,EAQO,gBAKMR,EAAN,cAA+B,KAAM,CAC1C,YACES,EACgBC,EACAC,EACAC,EAChB,CACA,MAAMH,CAAO,EAJG,YAAAC,EACA,UAAAC,EACA,YAAAC,EAGhB,KAAK,KAAO,kBACd,CACF,EA8CA,eAAsBV,EACpBW,EACAC,EACuB,CACvB,IAAMC,EAAUD,EAAK,OAAS,MACxBE,EAAM,GAAGF,EAAK,WAAW,QAAQ,MAAO,EAAE,CAAC,qBAC3CG,EAAM,MAAMF,EAAQC,EAAK,CAC7B,OAAQ,OACR,QAAS,CAAE,eAAgB,kBAAmB,EAC9C,KAAM,KAAK,UAAU,CACnB,OAAQH,EAAM,MACd,WAAYA,EAAM,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AAsBhC,EACpBsC,EACAF,EAC0B,CAC1B,IAAMxB,EAAUwB,EAAQ,OAAS,MAC3BvB,EAAM,GAAGuB,EAAQ,WAAW,QAAQ,MAAO,EAAE,CAAC,qBAC9CtB,EAAM,MAAMF,EAAQC,EAAK,CAC7B,OAAQ,OACR,QAAS,CAAE,eAAgB,kBAAmB,EAC9C,KAAM,KAAK,UAAU,CAAE,UAAAyB,CAAU,CAAC,CACpC,CAAC,EACKvB,EAAO,MAAMD,EAAI,KAAK,EAAE,MAAM,KAAO,CAAC,EAAE,EAC9C,GAAI,CAACA,EAAI,GAAI,CACX,IAAMN,EAAOO,GAAM,OAAO,MAAQ,QAAQD,EAAI,MAAM,GAC9CE,EAAMD,GAAM,OAAO,SAAW,sBACpC,MAAM,IAAIlB,EAAiBmB,EAAKF,EAAI,OAAQN,EAAMO,CAAI,CACxD,CACA,IAAME,EAAOF,GAAM,MAAQ,CAAC,EAC5B,MAAO,CACL,YAAaE,EAAK,aAClB,UAAWA,EAAK,WAChB,YAAaA,EAAK,WAAW,GAC7B,KAAMA,EAAK,KACX,KAAMA,EAAK,IACb,CACF,CAGA,eAAsBnB,EACpBY,EACAiB,EACAS,EAC0B,CAC1B,IAAME,EAAY,MAAMpC,EAAiBQ,EAAOiB,CAAM,EACtD,OAAO3B,EAAkBsC,EAAWF,CAAO,CAC7C","names":["embed_server_exports","__export","CrmExchangeError","createEmbedSession","createEmbedSessionWithKey","exchangeAssertion","getCrmEmbedJwks","mintCrmAssertion","resetCrmEmbedKeys","__toCommonJS","import_jose","message","status","code","detail","input","opts","doFetch","url","res","body","msg","data","AUDIENCE","DEFAULT_TTL_SECONDS","keyCache","randomUUID","c","b","h","x","loadKeys","config","alg","cacheKey","existing","created","privateKey","publicKey","publicJwk","kid","options","ttl","assertion"]}
@@ -0,0 +1,145 @@
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. Two auth
7
+ * approaches are supported:
8
+ *
9
+ * **Option A — API-key auth (simpler, no keypair):**
10
+ * POST user identity + your registered `app_id`/`app_secret` to the CRM.
11
+ * Use {@link createEmbedSessionWithKey}. No `jose` required.
12
+ *
13
+ * **Option B — Signed-assertion auth (zero shared-secret):**
14
+ * Mint a short-lived asymmetric (RS256/ES256) assertion server-side and
15
+ * exchange it at the CRM for a CRM bearer. Use {@link createEmbedSession} (or
16
+ * {@link mintCrmAssertion} + {@link exchangeAssertion} separately).
17
+ * Requires the `jose` peer dependency.
18
+ *
19
+ * Both paths return a short-lived CRM bearer; hand that bearer to the CRM
20
+ * iframe via `embed-host` (see ./embed-host).
21
+ *
22
+ * Works in Node and Bun (or any environment with a global `fetch`).
23
+ *
24
+ * @packageDocumentation
25
+ */
26
+
27
+ /** Thrown when the CRM rejects the exchange. `code` is the CRM's error code. */
28
+ declare class CrmExchangeError extends Error {
29
+ readonly status: number;
30
+ readonly code: string;
31
+ readonly detail?: unknown | undefined;
32
+ constructor(message: string, status: number, code: string, detail?: unknown | undefined);
33
+ }
34
+ /** The end-user being embedded into the CRM. */
35
+ interface EmbedUser {
36
+ id: string;
37
+ email: string;
38
+ role: 'member' | 'admin';
39
+ name?: string;
40
+ avatar_url?: string;
41
+ }
42
+ /** Input for {@link createEmbedSessionWithKey}. */
43
+ interface CreateEmbedSessionWithKeyInput {
44
+ appId: string;
45
+ appSecret: string;
46
+ user: EmbedUser;
47
+ }
48
+ /** The CRM session returned by {@link createEmbedSessionWithKey}. */
49
+ interface EmbedSession {
50
+ accessToken: string;
51
+ expiresIn?: number;
52
+ /** The CRM workspace the user was provisioned into. */
53
+ workspaceId?: string;
54
+ user?: unknown;
55
+ role?: string;
56
+ }
57
+ /**
58
+ * Exchange app credentials + user identity for a short-lived CRM bearer.
59
+ *
60
+ * POSTs `{ app_id, app_secret, user }` to `${crmBaseUrl}/api/auth/exchange`
61
+ * and maps the CRM response to an {@link EmbedSession}. On non-2xx, throws
62
+ * {@link CrmExchangeError} with `.status` and `.code`.
63
+ *
64
+ * @example
65
+ * ```typescript
66
+ * const session = await createEmbedSessionWithKey(
67
+ * { appId: process.env.CRM_APP_ID!, appSecret: process.env.CRM_APP_SECRET!, user },
68
+ * { crmBaseUrl: process.env.CRM_BASE_URL! },
69
+ * );
70
+ * // { accessToken, expiresIn, workspaceId, user, role }
71
+ * ```
72
+ */
73
+ declare function createEmbedSessionWithKey(input: CreateEmbedSessionWithKeyInput, opts: {
74
+ crmBaseUrl: string;
75
+ fetch?: typeof fetch;
76
+ }): Promise<EmbedSession>;
77
+ type CrmEmbedAlg = 'RS256' | 'ES256';
78
+ interface CrmEmbedSigningConfig {
79
+ /** Issuer — MUST equal the client_id the CRM registered for your app. */
80
+ iss: string;
81
+ /** PKCS8 PEM private key used to sign assertions. */
82
+ privateKeyPem: string;
83
+ /** SPKI PEM public key — required so getCrmEmbedJwks() can publish it. */
84
+ publicKeyPem: string;
85
+ /** Signature algorithm. Default 'RS256'. The CRM accepts RS256 or ES256. */
86
+ alg?: CrmEmbedAlg;
87
+ }
88
+ interface CrmAssertionInput {
89
+ /** Stable user id in your system (becomes the CRM external_subject). */
90
+ sub: string;
91
+ /** User email. */
92
+ email: string;
93
+ /** Requested role; the CRM clamps it to the install's configured max_role. */
94
+ requestedRole: 'member' | 'admin';
95
+ /** Your organization id; the CRM resolves the workspace from the org binding. */
96
+ orgId: string;
97
+ /** Optional display name for first-time provisioning. */
98
+ fullName?: string;
99
+ /** Optional avatar URL for first-time provisioning. */
100
+ avatarUrl?: string;
101
+ }
102
+ /** The CRM session returned by {@link createEmbedSession} / {@link exchangeAssertion}. */
103
+ interface CrmEmbedSession {
104
+ accessToken: string;
105
+ expiresIn?: number;
106
+ /** The CRM workspace the user was provisioned into (resolved from org_id). */
107
+ workspaceId?: string;
108
+ user?: {
109
+ id: string;
110
+ email: string;
111
+ full_name?: string;
112
+ };
113
+ role?: string;
114
+ }
115
+ interface ExchangeOptions {
116
+ /** CRM exchange base URL, e.g. "https://api.crm.example.com". */
117
+ crmBaseUrl: string;
118
+ /** Override fetch (tests / custom agents). Defaults to global fetch. */
119
+ fetch?: typeof fetch;
120
+ }
121
+ /** Test/dev only: clear the memoized keys. */
122
+ declare function resetCrmEmbedKeys(): void;
123
+ /**
124
+ * The public JWKS document to serve at a public https URL. Give that URL to the
125
+ * CRM team so they can verify your assertions. Example (Express):
126
+ *
127
+ * app.get('/crm-embed/jwks', async (_req, res) =>
128
+ * res.json(await getCrmEmbedJwks(config)));
129
+ */
130
+ declare function getCrmEmbedJwks(config: CrmEmbedSigningConfig): Promise<{
131
+ keys: JWK[];
132
+ }>;
133
+ /** Mint a short-lived signed assertion the CRM will exchange for a bearer. */
134
+ declare function mintCrmAssertion(input: CrmAssertionInput, config: CrmEmbedSigningConfig, options?: {
135
+ ttlSeconds?: number;
136
+ }): Promise<string>;
137
+ /**
138
+ * Exchange a minted assertion at the CRM for a CRM bearer. Do this server-side
139
+ * so the browser never calls the CRM's exchange endpoint cross-origin.
140
+ */
141
+ declare function exchangeAssertion(assertion: string, options: ExchangeOptions): Promise<CrmEmbedSession>;
142
+ /** Mint + exchange in one call — the typical "give me a CRM session" helper. */
143
+ declare function createEmbedSession(input: CrmAssertionInput, config: CrmEmbedSigningConfig, options: ExchangeOptions): Promise<CrmEmbedSession>;
144
+
145
+ export { type CreateEmbedSessionWithKeyInput, type CrmAssertionInput, type CrmEmbedAlg, type CrmEmbedSession, type CrmEmbedSigningConfig, CrmExchangeError, type EmbedSession, type EmbedUser, type ExchangeOptions, createEmbedSession, createEmbedSessionWithKey, exchangeAssertion, getCrmEmbedJwks, mintCrmAssertion, resetCrmEmbedKeys };
@@ -0,0 +1,145 @@
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. Two auth
7
+ * approaches are supported:
8
+ *
9
+ * **Option A — API-key auth (simpler, no keypair):**
10
+ * POST user identity + your registered `app_id`/`app_secret` to the CRM.
11
+ * Use {@link createEmbedSessionWithKey}. No `jose` required.
12
+ *
13
+ * **Option B — Signed-assertion auth (zero shared-secret):**
14
+ * Mint a short-lived asymmetric (RS256/ES256) assertion server-side and
15
+ * exchange it at the CRM for a CRM bearer. Use {@link createEmbedSession} (or
16
+ * {@link mintCrmAssertion} + {@link exchangeAssertion} separately).
17
+ * Requires the `jose` peer dependency.
18
+ *
19
+ * Both paths return a short-lived CRM bearer; hand that bearer to the CRM
20
+ * iframe via `embed-host` (see ./embed-host).
21
+ *
22
+ * Works in Node and Bun (or any environment with a global `fetch`).
23
+ *
24
+ * @packageDocumentation
25
+ */
26
+
27
+ /** Thrown when the CRM rejects the exchange. `code` is the CRM's error code. */
28
+ declare class CrmExchangeError extends Error {
29
+ readonly status: number;
30
+ readonly code: string;
31
+ readonly detail?: unknown | undefined;
32
+ constructor(message: string, status: number, code: string, detail?: unknown | undefined);
33
+ }
34
+ /** The end-user being embedded into the CRM. */
35
+ interface EmbedUser {
36
+ id: string;
37
+ email: string;
38
+ role: 'member' | 'admin';
39
+ name?: string;
40
+ avatar_url?: string;
41
+ }
42
+ /** Input for {@link createEmbedSessionWithKey}. */
43
+ interface CreateEmbedSessionWithKeyInput {
44
+ appId: string;
45
+ appSecret: string;
46
+ user: EmbedUser;
47
+ }
48
+ /** The CRM session returned by {@link createEmbedSessionWithKey}. */
49
+ interface EmbedSession {
50
+ accessToken: string;
51
+ expiresIn?: number;
52
+ /** The CRM workspace the user was provisioned into. */
53
+ workspaceId?: string;
54
+ user?: unknown;
55
+ role?: string;
56
+ }
57
+ /**
58
+ * Exchange app credentials + user identity for a short-lived CRM bearer.
59
+ *
60
+ * POSTs `{ app_id, app_secret, user }` to `${crmBaseUrl}/api/auth/exchange`
61
+ * and maps the CRM response to an {@link EmbedSession}. On non-2xx, throws
62
+ * {@link CrmExchangeError} with `.status` and `.code`.
63
+ *
64
+ * @example
65
+ * ```typescript
66
+ * const session = await createEmbedSessionWithKey(
67
+ * { appId: process.env.CRM_APP_ID!, appSecret: process.env.CRM_APP_SECRET!, user },
68
+ * { crmBaseUrl: process.env.CRM_BASE_URL! },
69
+ * );
70
+ * // { accessToken, expiresIn, workspaceId, user, role }
71
+ * ```
72
+ */
73
+ declare function createEmbedSessionWithKey(input: CreateEmbedSessionWithKeyInput, opts: {
74
+ crmBaseUrl: string;
75
+ fetch?: typeof fetch;
76
+ }): Promise<EmbedSession>;
77
+ type CrmEmbedAlg = 'RS256' | 'ES256';
78
+ interface CrmEmbedSigningConfig {
79
+ /** Issuer — MUST equal the client_id the CRM registered for your app. */
80
+ iss: string;
81
+ /** PKCS8 PEM private key used to sign assertions. */
82
+ privateKeyPem: string;
83
+ /** SPKI PEM public key — required so getCrmEmbedJwks() can publish it. */
84
+ publicKeyPem: string;
85
+ /** Signature algorithm. Default 'RS256'. The CRM accepts RS256 or ES256. */
86
+ alg?: CrmEmbedAlg;
87
+ }
88
+ interface CrmAssertionInput {
89
+ /** Stable user id in your system (becomes the CRM external_subject). */
90
+ sub: string;
91
+ /** User email. */
92
+ email: string;
93
+ /** Requested role; the CRM clamps it to the install's configured max_role. */
94
+ requestedRole: 'member' | 'admin';
95
+ /** Your organization id; the CRM resolves the workspace from the org binding. */
96
+ orgId: string;
97
+ /** Optional display name for first-time provisioning. */
98
+ fullName?: string;
99
+ /** Optional avatar URL for first-time provisioning. */
100
+ avatarUrl?: string;
101
+ }
102
+ /** The CRM session returned by {@link createEmbedSession} / {@link exchangeAssertion}. */
103
+ interface CrmEmbedSession {
104
+ accessToken: string;
105
+ expiresIn?: number;
106
+ /** The CRM workspace the user was provisioned into (resolved from org_id). */
107
+ workspaceId?: string;
108
+ user?: {
109
+ id: string;
110
+ email: string;
111
+ full_name?: string;
112
+ };
113
+ role?: string;
114
+ }
115
+ interface ExchangeOptions {
116
+ /** CRM exchange base URL, e.g. "https://api.crm.example.com". */
117
+ crmBaseUrl: string;
118
+ /** Override fetch (tests / custom agents). Defaults to global fetch. */
119
+ fetch?: typeof fetch;
120
+ }
121
+ /** Test/dev only: clear the memoized keys. */
122
+ declare function resetCrmEmbedKeys(): void;
123
+ /**
124
+ * The public JWKS document to serve at a public https URL. Give that URL to the
125
+ * CRM team so they can verify your assertions. Example (Express):
126
+ *
127
+ * app.get('/crm-embed/jwks', async (_req, res) =>
128
+ * res.json(await getCrmEmbedJwks(config)));
129
+ */
130
+ declare function getCrmEmbedJwks(config: CrmEmbedSigningConfig): Promise<{
131
+ keys: JWK[];
132
+ }>;
133
+ /** Mint a short-lived signed assertion the CRM will exchange for a bearer. */
134
+ declare function mintCrmAssertion(input: CrmAssertionInput, config: CrmEmbedSigningConfig, options?: {
135
+ ttlSeconds?: number;
136
+ }): Promise<string>;
137
+ /**
138
+ * Exchange a minted assertion at the CRM for a CRM bearer. Do this server-side
139
+ * so the browser never calls the CRM's exchange endpoint cross-origin.
140
+ */
141
+ declare function exchangeAssertion(assertion: string, options: ExchangeOptions): Promise<CrmEmbedSession>;
142
+ /** Mint + exchange in one call — the typical "give me a CRM session" helper. */
143
+ declare function createEmbedSession(input: CrmAssertionInput, config: CrmEmbedSigningConfig, options: ExchangeOptions): Promise<CrmEmbedSession>;
144
+
145
+ export { type CreateEmbedSessionWithKeyInput, type CrmAssertionInput, type CrmEmbedAlg, type CrmEmbedSession, type CrmEmbedSigningConfig, CrmExchangeError, type EmbedSession, type EmbedUser, type ExchangeOptions, createEmbedSession, createEmbedSessionWithKey, exchangeAssertion, getCrmEmbedJwks, mintCrmAssertion, resetCrmEmbedKeys };
@@ -0,0 +1,2 @@
1
+ import{SignJWT as g,exportJWK as u,importPKCS8 as y,importSPKI as b,calculateJwkThumbprint as f}from"jose";var m=class extends Error{constructor(r,a,s,i){super(r);this.status=a;this.code=s;this.detail=i;this.name="CrmExchangeError"}};async function C(e,t){let r=t.fetch??fetch,a=`${t.crmBaseUrl.replace(/\/$/,"")}/api/auth/exchange`,s=await r(a,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:e.appId,app_secret:e.appSecret,user:e.user})}),i=await s.json().catch(()=>({}));if(!s.ok){let o=i?.error?.code??`HTTP_${s.status}`,c=i?.error?.message??"CRM exchange failed";throw new m(c,s.status,o,i)}let n=i?.data??{};return{accessToken:n.access_token,expiresIn:n.expires_in,workspaceId:n.workspace?.id,user:n.user,role:n.role}}var h="crm",l=120,d=new Map;function x(){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,a=>a.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(e){let t=e.alg??"RS256",r=`${e.iss}:${t}`,a=d.get(r);if(a)return a;let s=(async()=>{let i=await y(e.privateKeyPem,t),n=await b(e.publicKeyPem,t),o=await u(n),c=await f(o);return{privateKey:i,publicJwk:{...o,kid:c,alg:t,use:"sig"},kid:c}})();return d.set(r,s),s}function E(){d.clear()}async function K(e){let{publicJwk:t}=await p(e);return{keys:[t]}}async function S(e,t,r){let a=t.alg??"RS256",{privateKey:s,kid:i}=await p(t),n=Math.min(r?.ttlSeconds??l,l);return new g({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:a,kid:i}).setSubject(e.sub).setIssuer(t.iss).setAudience(h).setIssuedAt().setExpirationTime(`${n}s`).setJti(x()).sign(s)}async function w(e,t){let r=t.fetch??fetch,a=`${t.crmBaseUrl.replace(/\/$/,"")}/api/auth/exchange`,s=await r(a,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({assertion:e})}),i=await s.json().catch(()=>({}));if(!s.ok){let o=i?.error?.code??`HTTP_${s.status}`,c=i?.error?.message??"CRM exchange failed";throw new m(c,s.status,o,i)}let n=i?.data??{};return{accessToken:n.access_token,expiresIn:n.expires_in,workspaceId:n.workspace?.id,user:n.user,role:n.role}}async function I(e,t,r){let a=await S(e,t);return w(a,r)}export{m as CrmExchangeError,I as createEmbedSession,C as createEmbedSessionWithKey,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. Two auth\n * approaches are supported:\n *\n * **Option A — API-key auth (simpler, no keypair):**\n * POST user identity + your registered `app_id`/`app_secret` to the CRM.\n * Use {@link createEmbedSessionWithKey}. No `jose` required.\n *\n * **Option B — Signed-assertion auth (zero shared-secret):**\n * Mint a short-lived asymmetric (RS256/ES256) assertion server-side and\n * exchange it at the CRM for a CRM bearer. Use {@link createEmbedSession} (or\n * {@link mintCrmAssertion} + {@link exchangeAssertion} separately).\n * Requires the `jose` peer dependency.\n *\n * Both paths return a short-lived CRM bearer; hand that bearer to the CRM\n * iframe via `embed-host` (see ./embed-host).\n *\n * Works in Node and Bun (or any environment with a global `fetch`).\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\n// ─── Shared error class ──────────────────────────────────────────────────────\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\n// ─── Option A: API-key auth ──────────────────────────────────────────────────\n\n/** The end-user being embedded into the CRM. */\nexport interface EmbedUser {\n id: string;\n email: string;\n role: 'member' | 'admin';\n name?: string;\n avatar_url?: string;\n}\n\n/** Input for {@link createEmbedSessionWithKey}. */\nexport interface CreateEmbedSessionWithKeyInput {\n appId: string;\n appSecret: string;\n user: EmbedUser;\n}\n\n/** The CRM session returned by {@link createEmbedSessionWithKey}. */\nexport interface EmbedSession {\n accessToken: string;\n expiresIn?: number;\n /** The CRM workspace the user was provisioned into. */\n workspaceId?: string;\n user?: unknown;\n role?: string;\n}\n\n/**\n * Exchange app credentials + user identity for a short-lived CRM bearer.\n *\n * POSTs `{ app_id, app_secret, user }` to `${crmBaseUrl}/api/auth/exchange`\n * and maps the CRM response to an {@link EmbedSession}. On non-2xx, throws\n * {@link CrmExchangeError} with `.status` and `.code`.\n *\n * @example\n * ```typescript\n * const session = await createEmbedSessionWithKey(\n * { appId: process.env.CRM_APP_ID!, appSecret: process.env.CRM_APP_SECRET!, user },\n * { crmBaseUrl: process.env.CRM_BASE_URL! },\n * );\n * // { accessToken, expiresIn, workspaceId, user, role }\n * ```\n */\nexport async function createEmbedSessionWithKey(\n input: CreateEmbedSessionWithKeyInput,\n opts: { crmBaseUrl: string; fetch?: typeof fetch },\n): Promise<EmbedSession> {\n const doFetch = opts.fetch ?? fetch;\n const url = `${opts.crmBaseUrl.replace(/\\/$/, '')}/api/auth/exchange`;\n const res = await doFetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n app_id: input.appId,\n app_secret: input.appSecret,\n user: input.user,\n }),\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// ─── Option B: Signed-assertion auth ────────────────────────────────────────\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 {@link createEmbedSession} / {@link exchangeAssertion}. */\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\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\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\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"],"mappings":"AAuBA,OACE,WAAAA,EACA,aAAAC,EACA,eAAAC,EACA,cAAAC,EACA,0BAAAC,MAGK,OAKA,IAAMC,EAAN,cAA+B,KAAM,CAC1C,YACEC,EACgBC,EACAC,EACAC,EAChB,CACA,MAAMH,CAAO,EAJG,YAAAC,EACA,UAAAC,EACA,YAAAC,EAGhB,KAAK,KAAO,kBACd,CACF,EA8CA,eAAsBC,EACpBC,EACAC,EACuB,CACvB,IAAMC,EAAUD,EAAK,OAAS,MACxBE,EAAM,GAAGF,EAAK,WAAW,QAAQ,MAAO,EAAE,CAAC,qBAC3CG,EAAM,MAAMF,EAAQC,EAAK,CAC7B,OAAQ,OACR,QAAS,CAAE,eAAgB,kBAAmB,EAC9C,KAAM,KAA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3B,OAAOnB,EAAW,CAAC,EACnB,KAAKW,CAAU,CACpB,CAMA,eAAsBS,EACpBC,EACAH,EAC0B,CAC1B,IAAM3B,EAAU2B,EAAQ,OAAS,MAC3B1B,EAAM,GAAG0B,EAAQ,WAAW,QAAQ,MAAO,EAAE,CAAC,qBAC9CzB,EAAM,MAAMF,EAAQC,EAAK,CAC7B,OAAQ,OACR,QAAS,CAAE,eAAgB,kBAAmB,EAC9C,KAAM,KAAK,UAAU,CAAE,UAAA6B,CAAU,CAAC,CACpC,CAAC,EACK3B,EAAO,MAAMD,EAAI,KAAK,EAAE,MAAM,KAAO,CAAC,EAAE,EAC9C,GAAI,CAACA,EAAI,GAAI,CACX,IAAMP,EAAOQ,GAAM,OAAO,MAAQ,QAAQD,EAAI,MAAM,GAC9CE,EAAMD,GAAM,OAAO,SAAW,sBACpC,MAAM,IAAIX,EAAiBY,EAAKF,EAAI,OAAQP,EAAMQ,CAAI,CACxD,CACA,IAAME,EAAOF,GAAM,MAAQ,CAAC,EAC5B,MAAO,CACL,YAAaE,EAAK,aAClB,UAAWA,EAAK,WAChB,YAAaA,EAAK,WAAW,GAC7B,KAAMA,EAAK,KACX,KAAMA,EAAK,IACb,CACF,CAGA,eAAsB0B,EACpBjC,EACAiB,EACAY,EAC0B,CAC1B,IAAMG,EAAY,MAAMJ,EAAiB5B,EAAOiB,CAAM,EACtD,OAAOc,EAAkBC,EAAWH,CAAO,CAC7C","names":["SignJWT","exportJWK","importPKCS8","importSPKI","calculateJwkThumbprint","CrmExchangeError","message","status","code","detail","createEmbedSessionWithKey","input","opts","doFetch","url","res","body","msg","data","AUDIENCE","DEFAULT_TTL_SECONDS","keyCache","randomUUID","c","b","h","x","loadKeys","config","alg","cacheKey","existing","created","privateKey","publicKey","publicJwk","kid","resetCrmEmbedKeys","getCrmEmbedJwks","mintCrmAssertion","options","ttl","exchangeAssertion","assertion","createEmbedSession"]}
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,CACn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A,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,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,IAAMd,EAAoB,CAC/B,MAAa,CACXY,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,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,EAGOd,EAAQD","names":["index_exports","__export","CrmApp","index_default","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":"6bAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,YAAAE,EAAA,YAAAC,IAwCA,IAAIC,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,IA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AAWI,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,EAAAJ,GAwCA,IAAIK,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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AAeW,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,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,IAAME,EAAoB,CAC/B,MAAa,CACXL,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,OAAQW,GAAMA,IAAMR,CAAE,EAC5D,EAEA,YAAgC,CAC9B,OAAOT,CACT,EAEA,OACEkB,EACAX,EACY,CACZ,IAAMQ,EAAK,EAAEZ,EACb,OAAAQ,EAAW,CACT,KAAM,SACN,UAAWI,EACX,OAAAG,EACA,KAAMX,GAAQ,CAAC,CACjB,CAAC,EAEM,IAAI,QAAW,CAACY,EAASC,IAAW,CACzClB,EAAea,CAAE,EAAI,CACnB,QAASI,EACT,OAAAC,CACF,EACA,WAAW,IAAM,CACXlB,EAAea,CAAE,IACnBb,EAAea,CAAE,EAAE,OAAO,IAAI,MAAM,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.2.0",
4
+ "description": "CRM SDK — embed third-party apps inside the CRM, or embed the CRM inside your own SaaS (proxy-free, signed-assertion or API-key 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