@swirepay-developer/sparo-embed-sdk 1.0.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/CHANGELOG.md ADDED
@@ -0,0 +1,9 @@
1
+ # Changelog
2
+
3
+ ## 1.0.0
4
+
5
+ - Introduced `embed(options)` SDK API aligned with SPARO guest-token backend flow.
6
+ - Added iframe lifecycle handling, origin-pinned `postMessage` auth, and token auto-refresh.
7
+ - Added `SPARO-EMBEDDING.md` integration guide for consumer applications.
8
+ - Prepared package for distribution with `dist` outputs (CJS, ESM, browser global).
9
+
package/LICENSE ADDED
@@ -0,0 +1,9 @@
1
+ UNLICENSED
2
+
3
+ Copyright (c) Swirepay.
4
+ All rights reserved.
5
+
6
+ This package is proprietary and confidential.
7
+ No part of this package may be used, copied, modified, merged, published,
8
+ distributed, sublicensed, and/or sold without explicit prior written permission.
9
+
package/README.md ADDED
@@ -0,0 +1,86 @@
1
+ # SPARO Embed SDK
2
+
3
+ `@swirepay/sparo-embed-sdk` embeds SPARO in any web application using:
4
+
5
+ - iframe render (`/embed.html?embed=true&account=...`)
6
+ - guest-token auth via `postMessage`
7
+ - automatic token refresh before expiry
8
+
9
+ For full backend + integration flow, see `SPARO-EMBEDDING.md`.
10
+ For Maven/WebJar distribution, see `MAVEN-PUBLISH.md`.
11
+
12
+ ## Install
13
+
14
+ ```bash
15
+ npm install @swirepay/sparo-embed-sdk
16
+ ```
17
+
18
+ ## Quick Start
19
+
20
+ ```js
21
+ import { embed } from '@swirepay/sparo-embed-sdk';
22
+
23
+ const handle = embed({
24
+ id: 'sparo-chat',
25
+ sparoDomain: 'https://sparo.swirepay.com',
26
+ mountPoint: document.getElementById('sparo'),
27
+ fetchGuestToken: async () => {
28
+ const res = await fetch('/sparo/token', { credentials: 'include' });
29
+ if (!res.ok) throw new Error('token fetch failed');
30
+ return await res.json(); // { token, expiresIn, account }
31
+ },
32
+ uiConfig: { theme: 'light' },
33
+ onReady: () => console.log('SPARO ready'),
34
+ onError: (err) => console.error('SPARO error', err),
35
+ });
36
+
37
+ // handle.unmount();
38
+ ```
39
+
40
+ ## API
41
+
42
+ ### `embed(options)`
43
+
44
+ Required:
45
+
46
+ - `sparoDomain: string`
47
+ - `mountPoint: HTMLElement`
48
+ - `fetchGuestToken: () => Promise<{ token: string, expiresIn: number, account: string }>`
49
+
50
+ Optional:
51
+
52
+ - `id: string` (default `sparo-embed`)
53
+ - `uiConfig: object`
54
+ - `onReady: () => void`
55
+ - `onError: (error) => void`
56
+
57
+ Returns:
58
+
59
+ - `refresh(): Promise<void>`
60
+ - `unmount(): void`
61
+
62
+ ## Development
63
+
64
+ ```bash
65
+ npm install
66
+ npm run lint
67
+ npm test
68
+ npm run build
69
+ npm pack --dry-run
70
+ ```
71
+
72
+ ## Package Outputs
73
+
74
+ `npm run build` generates:
75
+
76
+ - `dist/index.js` (CommonJS)
77
+ - `dist/index.mjs` (ES module)
78
+ - `dist/sparo-embed-sdk.global.js` (browser global: `window.SparoEmbedSDK`)
79
+
80
+ ## Publish Checklist
81
+
82
+ ```bash
83
+ npm run verify
84
+ npm pack --dry-run
85
+ # npm publish --access restricted
86
+ ```
package/SECURITY.md ADDED
@@ -0,0 +1,28 @@
1
+ # Security
2
+
3
+ ## Trust Boundary
4
+
5
+ This SDK runs in the browser and must never hold long-lived secrets.
6
+
7
+ ### Browser may hold:
8
+ - short-lived guest JWT (per user + merchant)
9
+
10
+ ### Browser must never hold:
11
+ - `SPARO_ADMIN_KEY`
12
+ - signing secrets
13
+
14
+ ## Token Flow
15
+
16
+ 1. Consumer app calls its backend (`/sparo/token`).
17
+ 2. Backend authenticates user and calls SPARO `/api/guest-token`.
18
+ 3. SDK receives `{ token, expiresIn, account }`.
19
+ 4. SDK sends JWT to iframe with origin-pinned `postMessage`.
20
+
21
+ ## Required Controls
22
+
23
+ - Mint tokens on backend only.
24
+ - Short TTL (recommended 900s).
25
+ - Per-user, per-merchant token scope.
26
+ - No token in URL params.
27
+ - Restrict CORS on `/sparo/token`.
28
+ - Rotate `SPARO_ADMIN_KEY` immediately if leaked.
@@ -0,0 +1,115 @@
1
+ # Embedding SPARO
2
+
3
+ Embed the SPARO assistant into your application with short-lived guest JWTs, no SPARO login screen, and automatic token refresh.
4
+
5
+ - SDK: `@swirepay/sparo-embed-sdk`
6
+ - SPARO backend: `v1.10.1+`
7
+
8
+ ## Architecture
9
+
10
+ 1. User opens your page.
11
+ 2. SDK calls `fetchGuestToken()` in your app.
12
+ 3. Your backend calls SPARO mint endpoint with `SPARO_ADMIN_KEY`.
13
+ 4. SPARO returns guest JWT (`token`, `expiresIn`).
14
+ 5. SDK creates iframe and posts auth via `postMessage` (never URL token).
15
+ 6. SDK refreshes token automatically before expiry.
16
+
17
+ ## Prerequisites
18
+
19
+ - SPARO deployed (`https://sparo.swirepay.com` or self-hosted).
20
+ - `SPARO_ADMIN_KEY` stored in your backend secrets manager.
21
+ - Merchant allowlisted in SPARO.
22
+ - Your backend endpoint that authenticates end users and returns guest token.
23
+
24
+ ## Backend Token Mint Endpoint
25
+
26
+ `POST https://sparo.swirepay.com/api/guest-token`
27
+
28
+ Headers:
29
+ - `Authorization: Bearer <SPARO_ADMIN_KEY>`
30
+ - `Content-Type: application/json`
31
+
32
+ Body:
33
+
34
+ ```json
35
+ {
36
+ "user": "user-abc",
37
+ "account": "account-72ec92...",
38
+ "scope": ["chat:read", "chat:write"],
39
+ "ttl": 900
40
+ }
41
+ ```
42
+
43
+ Response:
44
+
45
+ ```json
46
+ {
47
+ "token": "eyJhbGciOi...",
48
+ "expiresIn": 900
49
+ }
50
+ ```
51
+
52
+ ## Frontend Integration
53
+
54
+ ```html
55
+ <div id="sparo" style="width: 100%; height: 720px;"></div>
56
+ ```
57
+
58
+ ```js
59
+ import { embed } from '@swirepay/sparo-embed-sdk';
60
+
61
+ const handle = embed({
62
+ id: 'sparo-chat',
63
+ sparoDomain: 'https://sparo.swirepay.com',
64
+ mountPoint: document.getElementById('sparo'),
65
+ fetchGuestToken: async () => {
66
+ const res = await fetch('/sparo/token', { credentials: 'include' });
67
+ if (!res.ok) throw new Error('token fetch failed');
68
+ return await res.json(); // { token, expiresIn, account }
69
+ },
70
+ uiConfig: { theme: 'light' },
71
+ onReady: () => console.log('[Sparo] ready'),
72
+ onError: (err) => {
73
+ console.error('[Sparo]', err.code, err.message);
74
+ },
75
+ });
76
+
77
+ // handle.unmount();
78
+ ```
79
+
80
+ ## Error Semantics
81
+
82
+ Expected backend/SDK error codes:
83
+
84
+ - `invalid_admin_key` (401)
85
+ - `merchant_not_enabled` (403)
86
+ - `invalid_request` (400)
87
+ - `rate_limited` (429)
88
+ - `fetch_failed` (SDK token fetch failure)
89
+ - `invalid_token` (SDK token payload shape)
90
+ - `iframe_load_failed` / `iframe_error` (iframe runtime issues)
91
+
92
+ ## Security Rules
93
+
94
+ Do:
95
+ - Mint tokens only on your trusted backend.
96
+ - Keep `SPARO_ADMIN_KEY` server-side only.
97
+ - Use short token TTL (default 15 min).
98
+ - Pin `postMessage` target origin (SDK does this).
99
+
100
+ Don't:
101
+ - Never expose `SPARO_ADMIN_KEY` to browser code.
102
+ - Never return tokens from unauthenticated endpoints.
103
+ - Never pass guest JWT as URL params.
104
+ - Never reuse one guest token across users.
105
+
106
+ ## Refresh Behavior
107
+
108
+ The SDK refreshes automatically at `expiresIn - 30s`:
109
+
110
+ - calls `fetchGuestToken()`
111
+ - receives new guest JWT
112
+ - sends `sparo:auth` to iframe again
113
+
114
+ No manual timers required in consuming apps.
115
+
package/dist/index.cjs ADDED
@@ -0,0 +1 @@
1
+ var E=Object.defineProperty;var L=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var A=Object.prototype.hasOwnProperty;var I=(e,t)=>{for(var i in t)E(e,i,{get:t[i],enumerable:!0})},F=(e,t,i,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let c of M(t))!A.call(e,c)&&c!==i&&E(e,c,{get:()=>t[c],enumerable:!(s=L(t,c))||s.enumerable});return e};var G=e=>F(E({},"__esModule",{value:!0}),e);var P={};I(P,{default:()=>x,embed:()=>g});module.exports=G(P);function C(e){try{return new URL(e).origin}catch{throw new Error("Invalid sparoDomain. Expected absolute URL, e.g. https://sparo.swirepay.com")}}function a(e,t,i){let s=new Error(t||e);return s.code=e,typeof i=="number"&&(s.status=i),s}function H(e){if(!e||typeof e!="object")throw a("fetch_failed","fetchGuestToken must return an object");if(!e.token||typeof e.token!="string")throw a("invalid_token","Missing token in fetchGuestToken response");if(!e.account||typeof e.account!="string")throw a("invalid_token","Missing account in fetchGuestToken response");let t=Number(e.expiresIn||900);if(!Number.isFinite(t)||t<=0)throw a("invalid_token","Invalid expiresIn in fetchGuestToken response");return{token:e.token,account:e.account,expiresIn:t}}function N(e,t){let i=new URLSearchParams({embed:"true",account:t});return`${e}/embed.html?${i.toString()}`}function g(e){let{id:t="sparo-embed",sparoDomain:i,mountPoint:s,fetchGuestToken:c,uiConfig:v={},onReady:k,onError:b}=e||{};if(!s||!(s instanceof HTMLElement))throw new Error("mountPoint must be a valid HTMLElement");if(typeof c!="function")throw new Error("fetchGuestToken must be a function");let d=C(i),o=document.createElement("iframe");o.id=t,o.title="SPARO Assistant",o.style.width="100%",o.style.height="100%",o.style.border="0",o.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-modals"),o.setAttribute("referrerpolicy","no-referrer");let l=!0,T=!1,m=null,p=null,y=()=>{p&&(window.clearTimeout(p),p=null)},h=n=>{b&&b(n)},S=()=>{if(!l||!T||!m)return;let n=o.contentWindow;!n||typeof n.postMessage!="function"||n.postMessage({type:"sparo:auth",token:m.token,account:m.account,uiConfig:v},d)},D=n=>{y();let r=Math.max(5,n-30);p=window.setTimeout(()=>{w().catch(()=>{})},r*1e3)},w=async()=>{if(!l)return;let n;try{n=await c()}catch(f){let R=a("fetch_failed",(f==null?void 0:f.message)||"Failed to fetch guest token");throw h(R),R}let r=H(n);m=r,D(r.expiresIn);let u=N(d,r.account);!o.src||o.src!==u?o.src=u:S()},_=n=>{if(!l||n.origin!==d)return;let r=n.data;if(!(!r||typeof r!="object"||typeof r.type!="string")){if(r.type==="sparo:ready"||r.type==="SPARO_EMBED_READY"){T=!0,S(),k&&k();return}if(r.type==="sparo:error"){let u=r.code||"iframe_error",f=a(u,r.message||u,r.status);h(f)}}};return window.addEventListener("message",_),s.innerHTML="",s.appendChild(o),w().catch(n=>{h(n)}),{refresh:()=>w(),unmount:()=>{l=!1,y(),window.removeEventListener("message",_),o.parentNode===s&&s.removeChild(o)}}}var x=g;0&&(module.exports={embed});
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ function v(e){try{return new URL(e).origin}catch{throw new Error("Invalid sparoDomain. Expected absolute URL, e.g. https://sparo.swirepay.com")}}function c(e,o,i){let s=new Error(o||e);return s.code=e,typeof i=="number"&&(s.status=i),s}function D(e){if(!e||typeof e!="object")throw c("fetch_failed","fetchGuestToken must return an object");if(!e.token||typeof e.token!="string")throw c("invalid_token","Missing token in fetchGuestToken response");if(!e.account||typeof e.account!="string")throw c("invalid_token","Missing account in fetchGuestToken response");let o=Number(e.expiresIn||900);if(!Number.isFinite(o)||o<=0)throw c("invalid_token","Invalid expiresIn in fetchGuestToken response");return{token:e.token,account:e.account,expiresIn:o}}function L(e,o){let i=new URLSearchParams({embed:"true",account:o});return`${e}/embed.html?${i.toString()}`}function _(e){let{id:o="sparo-embed",sparoDomain:i,mountPoint:s,fetchGuestToken:w,uiConfig:R={},onReady:E,onError:g}=e||{};if(!s||!(s instanceof HTMLElement))throw new Error("mountPoint must be a valid HTMLElement");if(typeof w!="function")throw new Error("fetchGuestToken must be a function");let p=v(i),r=document.createElement("iframe");r.id=o,r.title="SPARO Assistant",r.style.width="100%",r.style.height="100%",r.style.border="0",r.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-modals"),r.setAttribute("referrerpolicy","no-referrer");let f=!0,k=!1,l=null,m=null,b=()=>{m&&(window.clearTimeout(m),m=null)},d=t=>{g&&g(t)},T=()=>{if(!f||!k||!l)return;let t=r.contentWindow;!t||typeof t.postMessage!="function"||t.postMessage({type:"sparo:auth",token:l.token,account:l.account,uiConfig:R},p)},x=t=>{b();let n=Math.max(5,t-30);m=window.setTimeout(()=>{h().catch(()=>{})},n*1e3)},h=async()=>{if(!f)return;let t;try{t=await w()}catch(u){let S=c("fetch_failed",(u==null?void 0:u.message)||"Failed to fetch guest token");throw d(S),S}let n=D(t);l=n,x(n.expiresIn);let a=L(p,n.account);!r.src||r.src!==a?r.src=a:T()},y=t=>{if(!f||t.origin!==p)return;let n=t.data;if(!(!n||typeof n!="object"||typeof n.type!="string")){if(n.type==="sparo:ready"||n.type==="SPARO_EMBED_READY"){k=!0,T(),E&&E();return}if(n.type==="sparo:error"){let a=n.code||"iframe_error",u=c(a,n.message||a,n.status);d(u)}}};return window.addEventListener("message",y),s.innerHTML="",s.appendChild(r),h().catch(t=>{d(t)}),{refresh:()=>h(),unmount:()=>{f=!1,b(),window.removeEventListener("message",y),r.parentNode===s&&s.removeChild(r)}}}var M=_;export{M as default,_ as embed};
@@ -0,0 +1 @@
1
+ var SparoEmbedSDK=(()=>{var E=Object.defineProperty;var L=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var A=Object.prototype.hasOwnProperty;var I=(e,t)=>{for(var i in t)E(e,i,{get:t[i],enumerable:!0})},F=(e,t,i,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let c of M(t))!A.call(e,c)&&c!==i&&E(e,c,{get:()=>t[c],enumerable:!(s=L(t,c))||s.enumerable});return e};var G=e=>F(E({},"__esModule",{value:!0}),e);var P={};I(P,{default:()=>x,embed:()=>g});function C(e){try{return new URL(e).origin}catch{throw new Error("Invalid sparoDomain. Expected absolute URL, e.g. https://sparo.swirepay.com")}}function a(e,t,i){let s=new Error(t||e);return s.code=e,typeof i=="number"&&(s.status=i),s}function H(e){if(!e||typeof e!="object")throw a("fetch_failed","fetchGuestToken must return an object");if(!e.token||typeof e.token!="string")throw a("invalid_token","Missing token in fetchGuestToken response");if(!e.account||typeof e.account!="string")throw a("invalid_token","Missing account in fetchGuestToken response");let t=Number(e.expiresIn||900);if(!Number.isFinite(t)||t<=0)throw a("invalid_token","Invalid expiresIn in fetchGuestToken response");return{token:e.token,account:e.account,expiresIn:t}}function N(e,t){let i=new URLSearchParams({embed:"true",account:t});return`${e}/embed.html?${i.toString()}`}function g(e){let{id:t="sparo-embed",sparoDomain:i,mountPoint:s,fetchGuestToken:c,uiConfig:v={},onReady:k,onError:b}=e||{};if(!s||!(s instanceof HTMLElement))throw new Error("mountPoint must be a valid HTMLElement");if(typeof c!="function")throw new Error("fetchGuestToken must be a function");let p=C(i),o=document.createElement("iframe");o.id=t,o.title="SPARO Assistant",o.style.width="100%",o.style.height="100%",o.style.border="0",o.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-modals"),o.setAttribute("referrerpolicy","no-referrer");let f=!0,T=!1,l=null,m=null,y=()=>{m&&(window.clearTimeout(m),m=null)},d=n=>{b&&b(n)},S=()=>{if(!f||!T||!l)return;let n=o.contentWindow;!n||typeof n.postMessage!="function"||n.postMessage({type:"sparo:auth",token:l.token,account:l.account,uiConfig:v},p)},D=n=>{y();let r=Math.max(5,n-30);m=window.setTimeout(()=>{h().catch(()=>{})},r*1e3)},h=async()=>{if(!f)return;let n;try{n=await c()}catch(w){let R=a("fetch_failed",w?.message||"Failed to fetch guest token");throw d(R),R}let r=H(n);l=r,D(r.expiresIn);let u=N(p,r.account);!o.src||o.src!==u?o.src=u:S()},_=n=>{if(!f||n.origin!==p)return;let r=n.data;if(!(!r||typeof r!="object"||typeof r.type!="string")){if(r.type==="sparo:ready"||r.type==="SPARO_EMBED_READY"){T=!0,S(),k&&k();return}if(r.type==="sparo:error"){let u=r.code||"iframe_error",w=a(u,r.message||u,r.status);d(w)}}};return window.addEventListener("message",_),s.innerHTML="",s.appendChild(o),h().catch(n=>{d(n)}),{refresh:()=>h(),unmount:()=>{f=!1,y(),window.removeEventListener("message",_),o.parentNode===s&&s.removeChild(o)}}}var x=g;return G(P);})();
package/package.json ADDED
@@ -0,0 +1,78 @@
1
+ {
2
+ "name": "@swirepay-developer/sparo-embed-sdk",
3
+ "version": "1.0.0",
4
+ "description": "SPARO embedding SDK for guest-token based iframe integration",
5
+ "private": false,
6
+ "license": "UNLICENSED",
7
+ "author": "Swirepay",
8
+ "sideEffects": false,
9
+ "type": "module",
10
+ "main": "./dist/index.js",
11
+ "module": "./dist/index.mjs",
12
+ "types": "./types/index.d.ts",
13
+ "unpkg": "./dist/sparo-embed-sdk.global.js",
14
+ "jsdelivr": "./dist/sparo-embed-sdk.global.js",
15
+ "exports": {
16
+ ".": {
17
+ "types": "./types/index.d.ts",
18
+ "import": "./dist/index.mjs",
19
+ "require": "./dist/index.js",
20
+ "default": "./dist/index.mjs"
21
+ },
22
+ "./package.json": "./package.json"
23
+ },
24
+ "files": [
25
+ "dist",
26
+ "types",
27
+ "README.md",
28
+ "CHANGELOG.md",
29
+ "SPARO-EMBEDDING.md",
30
+ "SECURITY.md",
31
+ "LICENSE"
32
+ ],
33
+ "keywords": [
34
+ "sparo",
35
+ "embed",
36
+ "sdk",
37
+ "iframe",
38
+ "guest-token"
39
+ ],
40
+ "repository": {
41
+ "type": "git",
42
+ "url": "git+https://github.com/swirepay/sparo-embed-sdk.git"
43
+ },
44
+ "bugs": {
45
+ "url": "https://github.com/swirepay/sparo-embed-sdk/issues"
46
+ },
47
+ "homepage": "https://github.com/swirepay/sparo-embed-sdk#readme",
48
+ "scripts": {
49
+ "clean": "rimraf dist",
50
+ "build": "npm run clean && tsup src/sdk/index.js --format cjs,esm --out-dir dist --minify --clean && esbuild src/sdk/index.js --bundle --format=iife --global-name=SparoEmbedSDK --platform=browser --outfile=dist/sparo-embed-sdk.global.js --minify",
51
+ "test": "vitest run",
52
+ "test:watch": "vitest",
53
+ "lint": "eslint src",
54
+ "verify": "npm run lint && npm run test && npm run build",
55
+ "prepublishOnly": "npm run verify",
56
+ "prepare": "husky"
57
+ },
58
+ "devDependencies": {
59
+ "@eslint/js": "^9.28.0",
60
+ "@testing-library/dom": "^10.4.0",
61
+ "esbuild": "^0.25.5",
62
+ "eslint": "^9.28.0",
63
+ "globals": "^16.2.0",
64
+ "husky": "^9.0.11",
65
+ "jsdom": "^26.1.0",
66
+ "lint-staged": "^15.2.2",
67
+ "prettier": "^3.2.5",
68
+ "rimraf": "^6.0.1",
69
+ "tsup": "^8.1.0",
70
+ "vitest": "^3.2.3"
71
+ },
72
+ "lint-staged": {
73
+ "src/**/*.js": [
74
+ "eslint --fix",
75
+ "prettier --write"
76
+ ]
77
+ }
78
+ }
@@ -0,0 +1,48 @@
1
+ export type UiConfig = {
2
+ theme?: 'light' | 'dark';
3
+ showWelcome?: boolean;
4
+ showSuggestions?: boolean;
5
+ hideSidebar?: boolean;
6
+ [key: string]: unknown;
7
+ };
8
+
9
+ export type GuestTokenResponse = {
10
+ token: string;
11
+ expiresIn: number;
12
+ account: string;
13
+ };
14
+
15
+ export type SparoEmbedErrorCode =
16
+ | 'merchant_not_enabled'
17
+ | 'invalid_token'
18
+ | 'expired_token'
19
+ | 'fetch_failed'
20
+ | 'iframe_load_failed'
21
+ | 'iframe_error'
22
+ | 'invalid_admin_key'
23
+ | 'invalid_request'
24
+ | 'rate_limited';
25
+
26
+ export type SparoEmbedError = Error & {
27
+ code?: SparoEmbedErrorCode | string;
28
+ status?: number;
29
+ };
30
+
31
+ export type EmbedOptions = {
32
+ id?: string;
33
+ sparoDomain: string;
34
+ mountPoint: HTMLElement;
35
+ fetchGuestToken: () => Promise<GuestTokenResponse>;
36
+ uiConfig?: UiConfig;
37
+ onReady?: () => void;
38
+ onError?: (error: SparoEmbedError) => void;
39
+ };
40
+
41
+ export type EmbedHandle = {
42
+ refresh: () => Promise<void>;
43
+ unmount: () => void;
44
+ };
45
+
46
+ export declare function embed(options: EmbedOptions): EmbedHandle;
47
+ export default embed;
48
+