@first-to-fly/crm-sdk 1.1.0 → 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 +83 -10
- package/dist/embed-server.cjs +1 -1
- package/dist/embed-server.cjs.map +1 -1
- package/dist/embed-server.d.cts +72 -32
- package/dist/embed-server.d.ts +72 -32
- package/dist/embed-server.js +1 -1
- package/dist/embed-server.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -131,12 +131,31 @@ Messages include `{ source: 'crm-host', type, ... }`:
|
|
|
131
131
|
## Embedding the CRM in your SaaS
|
|
132
132
|
|
|
133
133
|
Render the CRM as a cross-origin iframe in your app, authenticated **without cookies**
|
|
134
|
-
and **without a reverse proxy**.
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
`embed-host` (browser).
|
|
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).
|
|
138
137
|
|
|
139
|
-
###
|
|
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)
|
|
140
159
|
|
|
141
160
|
```
|
|
142
161
|
[your server] [browser] [CRM]
|
|
@@ -147,7 +166,57 @@ createEmbedSession(user) ─mint+exchange─▶ CRM bearer
|
|
|
147
166
|
└──────── auth-tokens ─────────▶ CRM iframe loads
|
|
148
167
|
```
|
|
149
168
|
|
|
150
|
-
|
|
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
|
|
151
220
|
|
|
152
221
|
1. Generate an RS256 (or ES256) key pair. Keep the private key on your server.
|
|
153
222
|
2. Serve your **public JWKS** at a public `https` URL (see `getCrmEmbedJwks` below).
|
|
@@ -155,7 +224,7 @@ createEmbedSession(user) ─mint+exchange─▶ CRM bearer
|
|
|
155
224
|
app and enable it. An admin in the CRM binds your **`org_id`** to a CRM workspace.
|
|
156
225
|
4. Ask the CRM team for their **exchange base URL** and **embed origin**.
|
|
157
226
|
|
|
158
|
-
|
|
227
|
+
#### Server: mint + exchange
|
|
159
228
|
|
|
160
229
|
```typescript
|
|
161
230
|
import { createEmbedSession, getCrmEmbedJwks } from '@first-to-fly/crm-sdk/embed-server';
|
|
@@ -195,7 +264,11 @@ Prefer to split minting and exchange? Use `mintCrmAssertion(input, config)` and
|
|
|
195
264
|
`CrmExchangeError` with `.status` and `.code` (e.g. `IDENTITY_CONFLICT`,
|
|
196
265
|
`WORKSPACE_NOT_OWNED`).
|
|
197
266
|
|
|
198
|
-
|
|
267
|
+
Requires `jose` (peer dependency): `npm i jose`.
|
|
268
|
+
|
|
269
|
+
---
|
|
270
|
+
|
|
271
|
+
### Browser: host the iframe (same for both options)
|
|
199
272
|
|
|
200
273
|
```typescript
|
|
201
274
|
import { createCrmEmbedHost, buildCrmEmbedUrl } from '@first-to-fly/crm-sdk/embed-host';
|
|
@@ -232,8 +305,8 @@ host.dispose();
|
|
|
232
305
|
return a fresh bearer (call your `/session` endpoint again).
|
|
233
306
|
- `crmOrigin` must exactly match the iframe's origin, and the CRM must allow your origin
|
|
234
307
|
in its `frame-ancestors` (the CRM team configures this).
|
|
235
|
-
- Assertions are single-use and live ≤120s — always mint fresh; never cache one.
|
|
236
|
-
- `jose` is
|
|
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`.
|
|
237
310
|
|
|
238
311
|
## License
|
|
239
312
|
|
package/dist/embed-server.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
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
2
|
//# sourceMappingURL=embed-server.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/embed-server.ts"],"sourcesContent":["/**\n * CRM Embed Server SDK (server side).\n *\n * Use this in YOUR SaaS backend to authenticate the embedded CRM without a\n * shared secret. You mint a short-lived ASYMMETRIC (RS256/ES256) assertion for\n * the logged-in user and exchange it at the CRM for a CRM bearer, which your\n * frontend hands to the CRM iframe (see ./embed-host).\n *\n * The CRM verifies the assertion against your PUBLIC JWKS — you never share a\n * private key with the CRM. Expose getCrmEmbedJwks() at a public https URL and\n * give that URL to the CRM team (they register it as your app's `jwks_url`).\n *\n * Claim contract the CRM expects:\n * iss = your client_id (registered with the CRM; == this config.iss)\n * aud = 'crm'\n * sub = stable user id in YOUR system (becomes the CRM external_subject)\n * email = user email\n * requested_role = 'member' | 'admin' (the CRM clamps to the install's max_role)\n * org_id = your organization id; the CRM resolves the target workspace\n * from the install an admin bound to this org\n * exp - iat <= 120s, plus a unique jti (single-use, replay-protected)\n *\n * Requires `jose` (peer of this subpath). Works in Node and Bun.\n *\n * @packageDocumentation\n */\nimport {\n SignJWT,\n exportJWK,\n importPKCS8,\n importSPKI,\n calculateJwkThumbprint,\n type JWK,\n type KeyLike,\n} from 'jose';\n\nexport type CrmEmbedAlg = 'RS256' | 'ES256';\n\nconst AUDIENCE = 'crm';\nconst DEFAULT_TTL_SECONDS = 120;\n\nexport interface CrmEmbedSigningConfig {\n /** Issuer — MUST equal the client_id the CRM registered for your app. */\n iss: string;\n /** PKCS8 PEM private key used to sign assertions. */\n privateKeyPem: string;\n /** SPKI PEM public key — required so getCrmEmbedJwks() can publish it. */\n publicKeyPem: string;\n /** Signature algorithm. Default 'RS256'. The CRM accepts RS256 or ES256. */\n alg?: CrmEmbedAlg;\n}\n\nexport interface CrmAssertionInput {\n /** Stable user id in your system (becomes the CRM external_subject). */\n sub: string;\n /** User email. */\n email: string;\n /** Requested role; the CRM clamps it to the install's configured max_role. */\n requestedRole: 'member' | 'admin';\n /** Your organization id; the CRM resolves the workspace from the org binding. */\n orgId: string;\n /** Optional display name for first-time provisioning. */\n fullName?: string;\n /** Optional avatar URL for first-time provisioning. */\n avatarUrl?: string;\n}\n\n/** The CRM session returned by the exchange. */\nexport interface CrmEmbedSession {\n accessToken: string;\n expiresIn?: number;\n /** The CRM workspace the user was provisioned into (resolved from org_id). */\n workspaceId?: string;\n user?: { id: string; email: string; full_name?: string };\n role?: string;\n}\n\ninterface LoadedKeys { privateKey: KeyLike; publicJwk: JWK; kid: string }\n\n// Memoize per config.iss so repeated calls don't re-import keys.\nconst keyCache = new Map<string, Promise<LoadedKeys>>();\n\nfunction randomUUID(): string {\n const c = (globalThis as { crypto?: Crypto }).crypto;\n if (c?.randomUUID) return c.randomUUID();\n // Fallback (should not happen on Node 16+/Bun): RFC4122-ish from getRandomValues.\n const b = new Uint8Array(16);\n c?.getRandomValues?.(b);\n b[6] = (b[6] & 0x0f) | 0x40;\n b[8] = (b[8] & 0x3f) | 0x80;\n const h = Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');\n return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;\n}\n\nasync function loadKeys(config: CrmEmbedSigningConfig): Promise<LoadedKeys> {\n const alg = config.alg ?? 'RS256';\n const cacheKey = `${config.iss}:${alg}`;\n const existing = keyCache.get(cacheKey);\n if (existing) return existing;\n\n const created = (async (): Promise<LoadedKeys> => {\n const privateKey = await importPKCS8(config.privateKeyPem, alg);\n const publicKey = await importSPKI(config.publicKeyPem, alg);\n const publicJwk = await exportJWK(publicKey);\n // Stable kid = RFC 7638 thumbprint so the signed header kid matches JWKS.\n const kid = await calculateJwkThumbprint(publicJwk);\n return { privateKey, publicJwk: { ...publicJwk, kid, alg, use: 'sig' }, kid };\n })();\n keyCache.set(cacheKey, created);\n return created;\n}\n\n/** Test/dev only: clear the memoized keys. */\nexport function resetCrmEmbedKeys(): void {\n keyCache.clear();\n}\n\n/**\n * The public JWKS document to serve at a public https URL. Give that URL to the\n * CRM team so they can verify your assertions. Example (Express):\n *\n * app.get('/crm-embed/jwks', async (_req, res) =>\n * res.json(await getCrmEmbedJwks(config)));\n */\nexport async function getCrmEmbedJwks(\n config: CrmEmbedSigningConfig,\n): Promise<{ keys: JWK[] }> {\n const { publicJwk } = await loadKeys(config);\n return { keys: [publicJwk] };\n}\n\n/** Mint a short-lived signed assertion the CRM will exchange for a bearer. */\nexport async function mintCrmAssertion(\n input: CrmAssertionInput,\n config: CrmEmbedSigningConfig,\n options?: { ttlSeconds?: number },\n): Promise<string> {\n const alg = config.alg ?? 'RS256';\n const { privateKey, kid } = await loadKeys(config);\n const ttl = Math.min(options?.ttlSeconds ?? DEFAULT_TTL_SECONDS, DEFAULT_TTL_SECONDS);\n\n return new SignJWT({\n email: input.email,\n requested_role: input.requestedRole,\n org_id: input.orgId,\n ...(input.fullName ? { full_name: input.fullName } : {}),\n ...(input.avatarUrl ? { avatar_url: input.avatarUrl } : {}),\n })\n .setProtectedHeader({ alg, kid })\n .setSubject(input.sub)\n .setIssuer(config.iss)\n .setAudience(AUDIENCE)\n .setIssuedAt()\n .setExpirationTime(`${ttl}s`)\n .setJti(randomUUID())\n .sign(privateKey);\n}\n\nexport interface ExchangeOptions {\n /** CRM exchange base URL, e.g. \"https://api.crm.example.com\". */\n crmBaseUrl: string;\n /** Override fetch (tests / custom agents). Defaults to global fetch. */\n fetch?: typeof fetch;\n}\n\n/**\n * Exchange a minted assertion at the CRM for a CRM bearer. Do this server-side\n * so the browser never calls the CRM's exchange endpoint cross-origin.\n */\nexport async function exchangeAssertion(\n assertion: string,\n options: ExchangeOptions,\n): Promise<CrmEmbedSession> {\n const doFetch = options.fetch ?? fetch;\n const url = `${options.crmBaseUrl.replace(/\\/$/, '')}/api/auth/exchange`;\n const res = await doFetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ assertion }),\n });\n const body = await res.json().catch(() => ({}));\n if (!res.ok) {\n const code = body?.error?.code ?? `HTTP_${res.status}`;\n const msg = body?.error?.message ?? 'CRM exchange failed';\n throw new CrmExchangeError(msg, res.status, code, body);\n }\n const data = body?.data ?? {};\n return {\n accessToken: data.access_token,\n expiresIn: data.expires_in,\n workspaceId: data.workspace?.id,\n user: data.user,\n role: data.role,\n };\n}\n\n/** Mint + exchange in one call — the typical \"give me a CRM session\" helper. */\nexport async function createEmbedSession(\n input: CrmAssertionInput,\n config: CrmEmbedSigningConfig,\n options: ExchangeOptions,\n): Promise<CrmEmbedSession> {\n const assertion = await mintCrmAssertion(input, config);\n return exchangeAssertion(assertion, options);\n}\n\n/** Thrown when the CRM rejects the exchange. `code` is the CRM's error code. */\nexport class CrmExchangeError extends Error {\n constructor(\n message: string,\n public readonly status: number,\n public readonly code: string,\n public readonly detail?: unknown,\n ) {\n super(message);\n this.name = 'CrmExchangeError';\n }\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,sBAAAE,EAAA,uBAAAC,EAAA,sBAAAC,EAAA,oBAAAC,EAAA,qBAAAC,EAAA,sBAAAC,IAAA,eAAAC,EAAAR,GA0BA,IAAAS,EAQO,gBAIDC,EAAW,MACXC,EAAsB,IAyCtBC,EAAW,IAAI,IAErB,SAASC,GAAqB,CAC5B,IAAMC,EAAK,WAAmC,OAC9C,GAAIA,GAAG,WAAY,OAAOA,EAAE,WAAW,EAEvC,IAAMC,EAAI,IAAI,WAAW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B,KAAMA,EAAK,KACX,KAAMA,EAAK,IACb,CACF,CAGA,eAAsBnC,EACpByB,EACAT,EACAU,EAC0B,CAC1B,IAAME,EAAY,MAAMzB,EAAiBsB,EAAOT,CAAM,EACtD,OAAOf,EAAkB2B,EAAWF,CAAO,CAC7C,CAGO,IAAM3B,EAAN,cAA+B,KAAM,CAC1C,YACEqC,EACgBC,EACAJ,EACAK,EAChB,CACA,MAAMF,CAAO,EAJG,YAAAC,EACA,UAAAJ,EACA,YAAAK,EAGhB,KAAK,KAAO,kBACd,CACF","names":["embed_server_exports","__export","CrmExchangeError","createEmbedSession","exchangeAssertion","getCrmEmbedJwks","mintCrmAssertion","resetCrmEmbedKeys","__toCommonJS","import_jose","AUDIENCE","DEFAULT_TTL_SECONDS","keyCache","randomUUID","c","b","h","x","loadKeys","config","alg","cacheKey","existing","created","privateKey","publicKey","publicJwk","kid","input","options","ttl","assertion","doFetch","url","res","body","code","msg","data","message","status","detail"]}
|
|
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,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ACAS,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"]}
|
package/dist/embed-server.d.cts
CHANGED
|
@@ -3,30 +3,77 @@ import { JWK } from 'jose';
|
|
|
3
3
|
/**
|
|
4
4
|
* CRM Embed Server SDK (server side).
|
|
5
5
|
*
|
|
6
|
-
* Use this in YOUR SaaS backend to authenticate the embedded CRM
|
|
7
|
-
*
|
|
8
|
-
* the logged-in user and exchange it at the CRM for a CRM bearer, which your
|
|
9
|
-
* frontend hands to the CRM iframe (see ./embed-host).
|
|
6
|
+
* Use this in YOUR SaaS backend to authenticate the embedded CRM. Two auth
|
|
7
|
+
* approaches are supported:
|
|
10
8
|
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
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.
|
|
14
12
|
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
* requested_role = 'member' | 'admin' (the CRM clamps to the install's max_role)
|
|
21
|
-
* org_id = your organization id; the CRM resolves the target workspace
|
|
22
|
-
* from the install an admin bound to this org
|
|
23
|
-
* exp - iat <= 120s, plus a unique jti (single-use, replay-protected)
|
|
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.
|
|
24
18
|
*
|
|
25
|
-
*
|
|
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`).
|
|
26
23
|
*
|
|
27
24
|
* @packageDocumentation
|
|
28
25
|
*/
|
|
29
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>;
|
|
30
77
|
type CrmEmbedAlg = 'RS256' | 'ES256';
|
|
31
78
|
interface CrmEmbedSigningConfig {
|
|
32
79
|
/** Issuer — MUST equal the client_id the CRM registered for your app. */
|
|
@@ -52,7 +99,7 @@ interface CrmAssertionInput {
|
|
|
52
99
|
/** Optional avatar URL for first-time provisioning. */
|
|
53
100
|
avatarUrl?: string;
|
|
54
101
|
}
|
|
55
|
-
/** The CRM session returned by
|
|
102
|
+
/** The CRM session returned by {@link createEmbedSession} / {@link exchangeAssertion}. */
|
|
56
103
|
interface CrmEmbedSession {
|
|
57
104
|
accessToken: string;
|
|
58
105
|
expiresIn?: number;
|
|
@@ -65,6 +112,12 @@ interface CrmEmbedSession {
|
|
|
65
112
|
};
|
|
66
113
|
role?: string;
|
|
67
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
|
+
}
|
|
68
121
|
/** Test/dev only: clear the memoized keys. */
|
|
69
122
|
declare function resetCrmEmbedKeys(): void;
|
|
70
123
|
/**
|
|
@@ -81,12 +134,6 @@ declare function getCrmEmbedJwks(config: CrmEmbedSigningConfig): Promise<{
|
|
|
81
134
|
declare function mintCrmAssertion(input: CrmAssertionInput, config: CrmEmbedSigningConfig, options?: {
|
|
82
135
|
ttlSeconds?: number;
|
|
83
136
|
}): Promise<string>;
|
|
84
|
-
interface ExchangeOptions {
|
|
85
|
-
/** CRM exchange base URL, e.g. "https://api.crm.example.com". */
|
|
86
|
-
crmBaseUrl: string;
|
|
87
|
-
/** Override fetch (tests / custom agents). Defaults to global fetch. */
|
|
88
|
-
fetch?: typeof fetch;
|
|
89
|
-
}
|
|
90
137
|
/**
|
|
91
138
|
* Exchange a minted assertion at the CRM for a CRM bearer. Do this server-side
|
|
92
139
|
* so the browser never calls the CRM's exchange endpoint cross-origin.
|
|
@@ -94,12 +141,5 @@ interface ExchangeOptions {
|
|
|
94
141
|
declare function exchangeAssertion(assertion: string, options: ExchangeOptions): Promise<CrmEmbedSession>;
|
|
95
142
|
/** Mint + exchange in one call — the typical "give me a CRM session" helper. */
|
|
96
143
|
declare function createEmbedSession(input: CrmAssertionInput, config: CrmEmbedSigningConfig, options: ExchangeOptions): Promise<CrmEmbedSession>;
|
|
97
|
-
/** Thrown when the CRM rejects the exchange. `code` is the CRM's error code. */
|
|
98
|
-
declare class CrmExchangeError extends Error {
|
|
99
|
-
readonly status: number;
|
|
100
|
-
readonly code: string;
|
|
101
|
-
readonly detail?: unknown | undefined;
|
|
102
|
-
constructor(message: string, status: number, code: string, detail?: unknown | undefined);
|
|
103
|
-
}
|
|
104
144
|
|
|
105
|
-
export { type CrmAssertionInput, type CrmEmbedAlg, type CrmEmbedSession, type CrmEmbedSigningConfig, CrmExchangeError, type ExchangeOptions, createEmbedSession, exchangeAssertion, getCrmEmbedJwks, mintCrmAssertion, resetCrmEmbedKeys };
|
|
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 };
|
package/dist/embed-server.d.ts
CHANGED
|
@@ -3,30 +3,77 @@ import { JWK } from 'jose';
|
|
|
3
3
|
/**
|
|
4
4
|
* CRM Embed Server SDK (server side).
|
|
5
5
|
*
|
|
6
|
-
* Use this in YOUR SaaS backend to authenticate the embedded CRM
|
|
7
|
-
*
|
|
8
|
-
* the logged-in user and exchange it at the CRM for a CRM bearer, which your
|
|
9
|
-
* frontend hands to the CRM iframe (see ./embed-host).
|
|
6
|
+
* Use this in YOUR SaaS backend to authenticate the embedded CRM. Two auth
|
|
7
|
+
* approaches are supported:
|
|
10
8
|
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
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.
|
|
14
12
|
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
* requested_role = 'member' | 'admin' (the CRM clamps to the install's max_role)
|
|
21
|
-
* org_id = your organization id; the CRM resolves the target workspace
|
|
22
|
-
* from the install an admin bound to this org
|
|
23
|
-
* exp - iat <= 120s, plus a unique jti (single-use, replay-protected)
|
|
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.
|
|
24
18
|
*
|
|
25
|
-
*
|
|
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`).
|
|
26
23
|
*
|
|
27
24
|
* @packageDocumentation
|
|
28
25
|
*/
|
|
29
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>;
|
|
30
77
|
type CrmEmbedAlg = 'RS256' | 'ES256';
|
|
31
78
|
interface CrmEmbedSigningConfig {
|
|
32
79
|
/** Issuer — MUST equal the client_id the CRM registered for your app. */
|
|
@@ -52,7 +99,7 @@ interface CrmAssertionInput {
|
|
|
52
99
|
/** Optional avatar URL for first-time provisioning. */
|
|
53
100
|
avatarUrl?: string;
|
|
54
101
|
}
|
|
55
|
-
/** The CRM session returned by
|
|
102
|
+
/** The CRM session returned by {@link createEmbedSession} / {@link exchangeAssertion}. */
|
|
56
103
|
interface CrmEmbedSession {
|
|
57
104
|
accessToken: string;
|
|
58
105
|
expiresIn?: number;
|
|
@@ -65,6 +112,12 @@ interface CrmEmbedSession {
|
|
|
65
112
|
};
|
|
66
113
|
role?: string;
|
|
67
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
|
+
}
|
|
68
121
|
/** Test/dev only: clear the memoized keys. */
|
|
69
122
|
declare function resetCrmEmbedKeys(): void;
|
|
70
123
|
/**
|
|
@@ -81,12 +134,6 @@ declare function getCrmEmbedJwks(config: CrmEmbedSigningConfig): Promise<{
|
|
|
81
134
|
declare function mintCrmAssertion(input: CrmAssertionInput, config: CrmEmbedSigningConfig, options?: {
|
|
82
135
|
ttlSeconds?: number;
|
|
83
136
|
}): Promise<string>;
|
|
84
|
-
interface ExchangeOptions {
|
|
85
|
-
/** CRM exchange base URL, e.g. "https://api.crm.example.com". */
|
|
86
|
-
crmBaseUrl: string;
|
|
87
|
-
/** Override fetch (tests / custom agents). Defaults to global fetch. */
|
|
88
|
-
fetch?: typeof fetch;
|
|
89
|
-
}
|
|
90
137
|
/**
|
|
91
138
|
* Exchange a minted assertion at the CRM for a CRM bearer. Do this server-side
|
|
92
139
|
* so the browser never calls the CRM's exchange endpoint cross-origin.
|
|
@@ -94,12 +141,5 @@ interface ExchangeOptions {
|
|
|
94
141
|
declare function exchangeAssertion(assertion: string, options: ExchangeOptions): Promise<CrmEmbedSession>;
|
|
95
142
|
/** Mint + exchange in one call — the typical "give me a CRM session" helper. */
|
|
96
143
|
declare function createEmbedSession(input: CrmAssertionInput, config: CrmEmbedSigningConfig, options: ExchangeOptions): Promise<CrmEmbedSession>;
|
|
97
|
-
/** Thrown when the CRM rejects the exchange. `code` is the CRM's error code. */
|
|
98
|
-
declare class CrmExchangeError extends Error {
|
|
99
|
-
readonly status: number;
|
|
100
|
-
readonly code: string;
|
|
101
|
-
readonly detail?: unknown | undefined;
|
|
102
|
-
constructor(message: string, status: number, code: string, detail?: unknown | undefined);
|
|
103
|
-
}
|
|
104
144
|
|
|
105
|
-
export { type CrmAssertionInput, type CrmEmbedAlg, type CrmEmbedSession, type CrmEmbedSigningConfig, CrmExchangeError, type ExchangeOptions, createEmbedSession, exchangeAssertion, getCrmEmbedJwks, mintCrmAssertion, resetCrmEmbedKeys };
|
|
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 };
|
package/dist/embed-server.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{SignJWT as
|
|
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
2
|
//# sourceMappingURL=embed-server.js.map
|
package/dist/embed-server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/embed-server.ts"],"sourcesContent":["/**\n * CRM Embed Server SDK (server side).\n *\n * Use this in YOUR SaaS backend to authenticate the embedded CRM without a\n * shared secret. You mint a short-lived ASYMMETRIC (RS256/ES256) assertion for\n * the logged-in user and exchange it at the CRM for a CRM bearer, which your\n * frontend hands to the CRM iframe (see ./embed-host).\n *\n * The CRM verifies the assertion against your PUBLIC JWKS — you never share a\n * private key with the CRM. Expose getCrmEmbedJwks() at a public https URL and\n * give that URL to the CRM team (they register it as your app's `jwks_url`).\n *\n * Claim contract the CRM expects:\n * iss = your client_id (registered with the CRM; == this config.iss)\n * aud = 'crm'\n * sub = stable user id in YOUR system (becomes the CRM external_subject)\n * email = user email\n * requested_role = 'member' | 'admin' (the CRM clamps to the install's max_role)\n * org_id = your organization id; the CRM resolves the target workspace\n * from the install an admin bound to this org\n * exp - iat <= 120s, plus a unique jti (single-use, replay-protected)\n *\n * Requires `jose` (peer of this subpath). Works in Node and Bun.\n *\n * @packageDocumentation\n */\nimport {\n SignJWT,\n exportJWK,\n importPKCS8,\n importSPKI,\n calculateJwkThumbprint,\n type JWK,\n type KeyLike,\n} from 'jose';\n\nexport type CrmEmbedAlg = 'RS256' | 'ES256';\n\nconst AUDIENCE = 'crm';\nconst DEFAULT_TTL_SECONDS = 120;\n\nexport interface CrmEmbedSigningConfig {\n /** Issuer — MUST equal the client_id the CRM registered for your app. */\n iss: string;\n /** PKCS8 PEM private key used to sign assertions. */\n privateKeyPem: string;\n /** SPKI PEM public key — required so getCrmEmbedJwks() can publish it. */\n publicKeyPem: string;\n /** Signature algorithm. Default 'RS256'. The CRM accepts RS256 or ES256. */\n alg?: CrmEmbedAlg;\n}\n\nexport interface CrmAssertionInput {\n /** Stable user id in your system (becomes the CRM external_subject). */\n sub: string;\n /** User email. */\n email: string;\n /** Requested role; the CRM clamps it to the install's configured max_role. */\n requestedRole: 'member' | 'admin';\n /** Your organization id; the CRM resolves the workspace from the org binding. */\n orgId: string;\n /** Optional display name for first-time provisioning. */\n fullName?: string;\n /** Optional avatar URL for first-time provisioning. */\n avatarUrl?: string;\n}\n\n/** The CRM session returned by the exchange. */\nexport interface CrmEmbedSession {\n accessToken: string;\n expiresIn?: number;\n /** The CRM workspace the user was provisioned into (resolved from org_id). */\n workspaceId?: string;\n user?: { id: string; email: string; full_name?: string };\n role?: string;\n}\n\ninterface LoadedKeys { privateKey: KeyLike; publicJwk: JWK; kid: string }\n\n// Memoize per config.iss so repeated calls don't re-import keys.\nconst keyCache = new Map<string, Promise<LoadedKeys>>();\n\nfunction randomUUID(): string {\n const c = (globalThis as { crypto?: Crypto }).crypto;\n if (c?.randomUUID) return c.randomUUID();\n // Fallback (should not happen on Node 16+/Bun): RFC4122-ish from getRandomValues.\n const b = new Uint8Array(16);\n c?.getRandomValues?.(b);\n b[6] = (b[6] & 0x0f) | 0x40;\n b[8] = (b[8] & 0x3f) | 0x80;\n const h = Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');\n return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;\n}\n\nasync function loadKeys(config: CrmEmbedSigningConfig): Promise<LoadedKeys> {\n const alg = config.alg ?? 'RS256';\n const cacheKey = `${config.iss}:${alg}`;\n const existing = keyCache.get(cacheKey);\n if (existing) return existing;\n\n const created = (async (): Promise<LoadedKeys> => {\n const privateKey = await importPKCS8(config.privateKeyPem, alg);\n const publicKey = await importSPKI(config.publicKeyPem, alg);\n const publicJwk = await exportJWK(publicKey);\n // Stable kid = RFC 7638 thumbprint so the signed header kid matches JWKS.\n const kid = await calculateJwkThumbprint(publicJwk);\n return { privateKey, publicJwk: { ...publicJwk, kid, alg, use: 'sig' }, kid };\n })();\n keyCache.set(cacheKey, created);\n return created;\n}\n\n/** Test/dev only: clear the memoized keys. */\nexport function resetCrmEmbedKeys(): void {\n keyCache.clear();\n}\n\n/**\n * The public JWKS document to serve at a public https URL. Give that URL to the\n * CRM team so they can verify your assertions. Example (Express):\n *\n * app.get('/crm-embed/jwks', async (_req, res) =>\n * res.json(await getCrmEmbedJwks(config)));\n */\nexport async function getCrmEmbedJwks(\n config: CrmEmbedSigningConfig,\n): Promise<{ keys: JWK[] }> {\n const { publicJwk } = await loadKeys(config);\n return { keys: [publicJwk] };\n}\n\n/** Mint a short-lived signed assertion the CRM will exchange for a bearer. */\nexport async function mintCrmAssertion(\n input: CrmAssertionInput,\n config: CrmEmbedSigningConfig,\n options?: { ttlSeconds?: number },\n): Promise<string> {\n const alg = config.alg ?? 'RS256';\n const { privateKey, kid } = await loadKeys(config);\n const ttl = Math.min(options?.ttlSeconds ?? DEFAULT_TTL_SECONDS, DEFAULT_TTL_SECONDS);\n\n return new SignJWT({\n email: input.email,\n requested_role: input.requestedRole,\n org_id: input.orgId,\n ...(input.fullName ? { full_name: input.fullName } : {}),\n ...(input.avatarUrl ? { avatar_url: input.avatarUrl } : {}),\n })\n .setProtectedHeader({ alg, kid })\n .setSubject(input.sub)\n .setIssuer(config.iss)\n .setAudience(AUDIENCE)\n .setIssuedAt()\n .setExpirationTime(`${ttl}s`)\n .setJti(randomUUID())\n .sign(privateKey);\n}\n\nexport interface ExchangeOptions {\n /** CRM exchange base URL, e.g. \"https://api.crm.example.com\". */\n crmBaseUrl: string;\n /** Override fetch (tests / custom agents). Defaults to global fetch. */\n fetch?: typeof fetch;\n}\n\n/**\n * Exchange a minted assertion at the CRM for a CRM bearer. Do this server-side\n * so the browser never calls the CRM's exchange endpoint cross-origin.\n */\nexport async function exchangeAssertion(\n assertion: string,\n options: ExchangeOptions,\n): Promise<CrmEmbedSession> {\n const doFetch = options.fetch ?? fetch;\n const url = `${options.crmBaseUrl.replace(/\\/$/, '')}/api/auth/exchange`;\n const res = await doFetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ assertion }),\n });\n const body = await res.json().catch(() => ({}));\n if (!res.ok) {\n const code = body?.error?.code ?? `HTTP_${res.status}`;\n const msg = body?.error?.message ?? 'CRM exchange failed';\n throw new CrmExchangeError(msg, res.status, code, body);\n }\n const data = body?.data ?? {};\n return {\n accessToken: data.access_token,\n expiresIn: data.expires_in,\n workspaceId: data.workspace?.id,\n user: data.user,\n role: data.role,\n };\n}\n\n/** Mint + exchange in one call — the typical \"give me a CRM session\" helper. */\nexport async function createEmbedSession(\n input: CrmAssertionInput,\n config: CrmEmbedSigningConfig,\n options: ExchangeOptions,\n): Promise<CrmEmbedSession> {\n const assertion = await mintCrmAssertion(input, config);\n return exchangeAssertion(assertion, options);\n}\n\n/** Thrown when the CRM rejects the exchange. `code` is the CRM's error code. */\nexport class CrmExchangeError extends Error {\n constructor(\n message: string,\n public readonly status: number,\n public readonly code: string,\n public readonly detail?: unknown,\n ) {\n super(message);\n this.name = 'CrmExchangeError';\n }\n}\n"],"mappings":"AA0BA,OACE,WAAAA,EACA,aAAAC,EACA,eAAAC,EACA,cAAAC,EACA,0BAAAC,MAGK,OAIP,IAAMC,EAAW,MACXC,EAAsB,IAyCtBC,EAAW,IAAI,IAErB,SAASC,GAAqB,CAC5B,IAAMC,EAAK,WAAmC,OAC9C,GAAIA,GAAG,WAAY,OAAOA,EAAE,WAAW,EAEvC,IAAMC,EAAI,IAAI,WAAW,EAAE,EAC3BD,GAAG,kBAAkBC,CAAC,EACtBA,EAAE,CAAC,EAAKA,EAAE,CAAC,EAAI,GAAQ,GACvBA,EAAE,CAAC,EAAKA,EAAE,CAAC,EAAI,GAAQ,IACvB,IAAMC,EAAI,MAAM,KAAKD,EAAIE,GAAMA,EAAE,SAAS,EAAE,EAAE,SAAS,EAAG,GAAG,CAAC,EAAE,KAAK,EAAE,EACvE,MAAO,GAAGD,EAAE,MAAM,EAAG,CAAC,CAAC,IAAIA,EAAE,MAAM,EAAG,EAAE,CAAC,IAAIA,EAAE,MAAM,GAAI,EAAE,CAAC,IAAIA,EAAE,MAAM,GAAI,EAAE,CAAC,IAAIA,EAAE,MAAM,EAAE,CAAC,EAChG,CAEA,eAAeE,EAASC,EAAoD,CAC1E,IAAMC,EAAMD,EAAO,KAAO,QACpBE,EAAW,GAAGF,EAAO,GAAG,IAAIC,CAAG,GAC/BE,EAAWV,EAAS,IAAIS,CAAQ,EACtC,GAAIC,EAAU,OAAOA,EAErB,IAAMC,GAAW,SAAiC,CAChD,IAAMC,EAAa,MAAMjB,EAAYY,EAAO,cAAeC,CAAG,EACxDK,EAAY,MAAMjB,EAAWW,EAAO,aAAcC,CAAG,EACrDM,EAAY,MAAMpB,EAAUmB,CAAS,EAErCE,EAAM,MAAMlB,EAAuBiB,CAAS,EAClD,MAAO,CAAE,WAAAF,EAAY,UAAW,CAAE,GAAGE,EAAW,IAAAC,E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MD,EAAI,KAAK,EAAE,MAAM,KAAO,CAAC,EAAE,EAC9C,GAAI,CAACA,EAAI,GAAI,CACX,IAAME,EAAOD,GAAM,OAAO,MAAQ,QAAQD,EAAI,MAAM,GAC9CG,EAAMF,GAAM,OAAO,SAAW,sBACpC,MAAM,IAAIG,EAAiBD,EAAKH,EAAI,OAAQE,EAAMD,CAAI,CACxD,CACA,IAAMI,EAAOJ,GAAM,MAAQ,CAAC,EAC5B,MAAO,CACL,YAAaI,EAAK,aAClB,UAAWA,EAAK,WAChB,YAAaA,EAAK,WAAW,GAC7B,KAAMA,EAAK,KACX,KAAMA,EAAK,IACb,CACF,CAGA,eAAsBC,EACpBb,EACAZ,EACAa,EAC0B,CAC1B,IAAMG,EAAY,MAAML,EAAiBC,EAAOZ,CAAM,EACtD,OAAOe,EAAkBC,EAAWH,CAAO,CAC7C,CAGO,IAAMU,EAAN,cAA+B,KAAM,CAC1C,YACEG,EACgBC,EACAN,EACAO,EAChB,CACA,MAAMF,CAAO,EAJG,YAAAC,EACA,UAAAN,EACA,YAAAO,EAGhB,KAAK,KAAO,kBACd,CACF","names":["SignJWT","exportJWK","importPKCS8","importSPKI","calculateJwkThumbprint","AUDIENCE","DEFAULT_TTL_SECONDS","keyCache","randomUUID","c","b","h","x","loadKeys","config","alg","cacheKey","existing","created","privateKey","publicKey","publicJwk","kid","resetCrmEmbedKeys","getCrmEmbedJwks","mintCrmAssertion","input","options","ttl","exchangeAssertion","assertion","doFetch","url","res","body","code","msg","CrmExchangeError","data","createEmbedSession","message","status","detail"]}
|
|
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,KAAK,UAAU,CACnB,OAAQH,EAAM,MACd,WAAYA,EAAM,UAClB,KAAMA,EAAM,IACd,CAAC,CACH,CAAC,EACKK,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,C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M,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/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@first-to-fly/crm-sdk",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "CRM SDK — embed third-party apps inside the CRM, or embed the CRM inside your own SaaS (proxy-free, signed-assertion auth)",
|
|
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
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.cjs",
|
|
7
7
|
"module": "dist/index.js",
|