@armdesk/connect-sdk 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/LICENSE.txt +15 -0
  3. package/README.md +525 -3
  4. package/dist/armdesk-connect.js +41 -0
  5. package/dist/esm/browser.d.ts +3 -0
  6. package/dist/esm/browser.js +18 -0
  7. package/dist/esm/client.d.ts +46 -0
  8. package/dist/esm/client.js +307 -0
  9. package/dist/esm/defaults.d.ts +8 -0
  10. package/dist/esm/defaults.js +22 -0
  11. package/dist/esm/elements.d.ts +3 -0
  12. package/dist/esm/elements.js +368 -0
  13. package/dist/esm/errors.d.ts +12 -0
  14. package/dist/esm/errors.js +34 -0
  15. package/dist/esm/handler.d.ts +40 -0
  16. package/dist/esm/handler.js +106 -0
  17. package/dist/esm/http.d.ts +22 -0
  18. package/dist/esm/http.js +66 -0
  19. package/dist/esm/index.d.ts +30 -0
  20. package/dist/esm/index.js +30 -0
  21. package/dist/esm/messenger.d.ts +8 -0
  22. package/dist/esm/messenger.js +269 -0
  23. package/dist/esm/mount.d.ts +8 -0
  24. package/dist/esm/mount.js +213 -0
  25. package/dist/esm/protocol.d.ts +37 -0
  26. package/dist/esm/protocol.js +57 -0
  27. package/dist/esm/react.d.ts +89 -0
  28. package/dist/esm/react.js +311 -0
  29. package/dist/esm/register.d.ts +1 -0
  30. package/dist/esm/register.js +5 -0
  31. package/dist/esm/sanitize.d.ts +8 -0
  32. package/dist/esm/sanitize.js +57 -0
  33. package/dist/esm/server.d.ts +17 -0
  34. package/dist/esm/server.js +93 -0
  35. package/dist/esm/sign.d.ts +54 -0
  36. package/dist/esm/sign.js +77 -0
  37. package/dist/esm/theme.d.ts +8 -0
  38. package/dist/esm/theme.js +46 -0
  39. package/dist/esm/types.d.ts +375 -0
  40. package/dist/esm/types.js +1 -0
  41. package/examples/express-server/package.json +10 -0
  42. package/examples/express-server/server.mjs +35 -0
  43. package/examples/mock-idp.mjs +30 -0
  44. package/examples/react-vite/index.html +11 -0
  45. package/examples/react-vite/package.json +15 -0
  46. package/examples/react-vite/src/main.jsx +25 -0
  47. package/examples/react-vite/vite.config.js +4 -0
  48. package/examples/wso2-browser.html +86 -0
  49. package/package.json +59 -4
@@ -0,0 +1,77 @@
1
+ import { createHmac, createPrivateKey, randomBytes, sign } from "node:crypto";
2
+ import { ASSERTION_AUDIENCE } from "./protocol.js";
3
+ export const MAX_EXPIRES_IN = 600;
4
+ export const DEFAULT_EXPIRES_IN = 300;
5
+ const MAX_ATTRIBUTES_BYTES = 4096;
6
+ const KEY_CONTEXT = "armdesk-connect-assertion-v1";
7
+ const b64 = (b) => Buffer.from(b).toString("base64url");
8
+ /** HMAC-SHA256(orgSecret, "armdesk-connect-assertion-v1"): the signing key, so the raw secret is never the JWT key. */
9
+ export function deriveAssertionKey(orgSecret) {
10
+ return createHmac("sha256", orgSecret).update(KEY_CONTEXT).digest();
11
+ }
12
+ /**
13
+ * Mints the signed user token (OAuth 2.0 JWT bearer assertion, RFC 7523) your page hands to the browser library as
14
+ * `auth: { userToken }`. Local: no network call, no endpoint of yours. HS256 with the key derived from the org
15
+ * secret, or RS256 / ES256 with your own registered private key.
16
+ */
17
+ export function signUserToken(options) {
18
+ var _a, _b, _c, _d, _e;
19
+ const { orgKey, user } = options;
20
+ if (!orgKey)
21
+ throw new Error("signUserToken: orgKey is required");
22
+ const sub = (_a = user === null || user === void 0 ? void 0 : user.id) !== null && _a !== void 0 ? _a : user === null || user === void 0 ? void 0 : user.uid;
23
+ if (!sub || typeof sub !== "string")
24
+ throw new Error("signUserToken: user.id is required");
25
+ const expiresIn = (_b = options.expiresIn) !== null && _b !== void 0 ? _b : DEFAULT_EXPIRES_IN;
26
+ if (!Number.isFinite(expiresIn) || expiresIn <= 0 || expiresIn > MAX_EXPIRES_IN)
27
+ throw new Error(`signUserToken: expiresIn must be 1 to ${MAX_EXPIRES_IN} seconds`);
28
+ if (user.attributes && Buffer.byteLength(JSON.stringify(user.attributes)) > MAX_ATTRIBUTES_BYTES)
29
+ throw new Error("signUserToken: attributes are limited to 4 KB");
30
+ const iat = Math.floor(((_c = options.now) !== null && _c !== void 0 ? _c : Date.now()) / 1000);
31
+ const claims = {
32
+ iss: orgKey,
33
+ sub,
34
+ aud: ASSERTION_AUDIENCE,
35
+ iat,
36
+ nbf: iat,
37
+ exp: iat + Math.floor(expiresIn),
38
+ jti: randomBytes(16).toString("hex"),
39
+ };
40
+ const optional = [
41
+ ["email", user.email],
42
+ ["email_verified", user.emailVerified],
43
+ ["name", user.name],
44
+ ["given_name", user.firstName],
45
+ ["family_name", user.lastName],
46
+ ["phone_number", user.phone],
47
+ ["role", user.role],
48
+ ["department", user.department],
49
+ ["attributes", user.attributes],
50
+ ];
51
+ for (const [k, v] of optional)
52
+ if (v !== undefined && v !== null && v !== "")
53
+ claims[k] = v;
54
+ let alg;
55
+ let kid;
56
+ let signer;
57
+ if (options.privateKey !== undefined) {
58
+ if (!options.kid)
59
+ throw new Error("signUserToken: kid is required with privateKey");
60
+ const key = typeof options.privateKey === "string" ? createPrivateKey(options.privateKey) : options.privateKey;
61
+ alg = (_d = options.alg) !== null && _d !== void 0 ? _d : (key.asymmetricKeyType === "ec" ? "ES256" : "RS256");
62
+ if ((alg === "ES256") !== (key.asymmetricKeyType === "ec"))
63
+ throw new Error(`signUserToken: ${alg} does not match the key type`);
64
+ kid = options.kid;
65
+ signer = (data) => (alg === "ES256" ? sign("sha256", Buffer.from(data), { key, dsaEncoding: "ieee-p1363" }) : sign("sha256", Buffer.from(data), key));
66
+ }
67
+ else {
68
+ if (!options.orgSecret)
69
+ throw new Error("signUserToken: orgSecret (or privateKey + kid) is required");
70
+ alg = "HS256";
71
+ kid = `${orgKey}:${(_e = options.secretVersion) !== null && _e !== void 0 ? _e : 1}`;
72
+ const key = deriveAssertionKey(options.orgSecret);
73
+ signer = (data) => createHmac("sha256", key).update(data).digest();
74
+ }
75
+ const input = `${b64(JSON.stringify({ alg, typ: "JWT", kid }))}.${b64(JSON.stringify(claims))}`;
76
+ return `${input}.${b64(signer(input))}`;
77
+ }
@@ -0,0 +1,8 @@
1
+ import type { ConnectTheme } from "./types.js";
2
+ /** The validated, explicit overrides of a theme as CSS custom properties (unknown or invalid keys are dropped). */
3
+ export declare function themeVars(theme: ConnectTheme | undefined): Record<string, string>;
4
+ /**
5
+ * CSS for a shadow root's `:host`: the light or dark palette (mode `auto` follows the visitor's system), then the
6
+ * theme's own colours on top.
7
+ */
8
+ export declare function themeCss(theme: ConnectTheme | undefined): string;
@@ -0,0 +1,46 @@
1
+ const HEX = /^#[0-9a-fA-F]{6}$/;
2
+ const FONTS = {
3
+ system: 'system-ui, -apple-system, "Segoe UI", Roboto, sans-serif',
4
+ inter: 'Inter, system-ui, -apple-system, "Segoe UI", sans-serif',
5
+ roboto: 'Roboto, system-ui, "Segoe UI", sans-serif',
6
+ "open-sans": '"Open Sans", system-ui, "Segoe UI", sans-serif',
7
+ lato: 'Lato, system-ui, "Segoe UI", sans-serif',
8
+ };
9
+ const LIGHT = { "--ad-bg": "#ffffff", "--ad-surface": "#f8f9fb", "--ad-text": "#1a1d23", "--ad-muted": "#6b7280", "--ad-border": "#e5e7eb", "--ad-primary": "#2563eb" };
10
+ const DARK = { "--ad-bg": "#0f1115", "--ad-surface": "#181b21", "--ad-text": "#f3f4f6", "--ad-muted": "#9ca3af", "--ad-border": "#2a2f38", "--ad-primary": "#60a5fa" };
11
+ const KEYS = [
12
+ ["backgroundColor", "--ad-bg"],
13
+ ["surfaceColor", "--ad-surface"],
14
+ ["textColor", "--ad-text"],
15
+ ["mutedColor", "--ad-muted"],
16
+ ["borderColor", "--ad-border"],
17
+ ["primaryColor", "--ad-primary"],
18
+ ];
19
+ const decl = (vars) => Object.entries(vars).map(([k, v]) => `${k}:${v};`).join("");
20
+ /** The validated, explicit overrides of a theme as CSS custom properties (unknown or invalid keys are dropped). */
21
+ export function themeVars(theme) {
22
+ const out = {};
23
+ const t = theme !== null && theme !== void 0 ? theme : {};
24
+ for (const [key, cssVar] of KEYS) {
25
+ const v = t[key];
26
+ if (typeof v === "string" && HEX.test(v))
27
+ out[cssVar] = v.toLowerCase();
28
+ }
29
+ if (typeof t.fontFamily === "string" && FONTS[t.fontFamily])
30
+ out["--ad-font"] = FONTS[t.fontFamily];
31
+ if (typeof t.radius === "number" && Number.isFinite(t.radius))
32
+ out["--ad-radius"] = `${Math.min(24, Math.max(0, Math.round(t.radius)))}px`;
33
+ out["--ad-pad"] = t.density === "compact" ? "6px 10px" : "10px 14px";
34
+ return out;
35
+ }
36
+ /**
37
+ * CSS for a shadow root's `:host`: the light or dark palette (mode `auto` follows the visitor's system), then the
38
+ * theme's own colours on top.
39
+ */
40
+ export function themeCss(theme) {
41
+ var _a;
42
+ const mode = (_a = theme === null || theme === void 0 ? void 0 : theme.mode) !== null && _a !== void 0 ? _a : "auto";
43
+ const base = `:host{display:block;--ad-font:${FONTS.system};--ad-radius:8px;--ad-pad:10px 14px;${decl(mode === "dark" ? DARK : LIGHT)}}`;
44
+ const auto = mode === "auto" ? `@media (prefers-color-scheme:dark){:host{${decl(DARK)}}}` : "";
45
+ return `${base}${auto}:host{${decl(themeVars(theme))}}`;
46
+ }
@@ -0,0 +1,375 @@
1
+ /** The embed's colours, shape and header. Every key is optional; the desk validates again. */
2
+ export interface ConnectTheme {
3
+ primaryColor?: string;
4
+ backgroundColor?: string;
5
+ surfaceColor?: string;
6
+ textColor?: string;
7
+ mutedColor?: string;
8
+ borderColor?: string;
9
+ fontFamily?: "system" | "inter" | "roboto" | "open-sans" | "lato";
10
+ /** 0-24 px. */
11
+ radius?: number;
12
+ density?: "comfortable" | "compact";
13
+ /** https URL of a logo shown in the header. */
14
+ logoUrl?: string;
15
+ showHeader?: boolean;
16
+ headerTitle?: string;
17
+ mode?: "light" | "dark" | "auto";
18
+ }
19
+ /** Features can only be narrowed: a feature the organisation has switched off stays off. */
20
+ export interface ConnectFeatures {
21
+ newTicket?: boolean;
22
+ attachments?: boolean;
23
+ catalog?: boolean;
24
+ orgTickets?: boolean;
25
+ replies?: boolean;
26
+ closeTicket?: boolean;
27
+ /** 1.1: live chat in the messenger. */
28
+ chat?: boolean;
29
+ /** 1.1: the Help tab (article search). */
30
+ helpCenter?: boolean;
31
+ /** 1.1: AI answers in Help, grounded in your docs and the shared knowledge base. */
32
+ aiAnswers?: boolean;
33
+ }
34
+ export type ConnectLocale = "en" | "es" | "ar";
35
+ /**
36
+ * `tickets` (the list), `new` (the form), `ticket:<id>` (one ticket); 1.1 messenger views: `home`, `messages`,
37
+ * `help`, `chat:<conversationId>`, `article:<id>`.
38
+ */
39
+ export type ConnectView = "tickets" | "new" | "home" | "messages" | "help" | `ticket:${string}` | `chat:${string}` | `article:${string}`;
40
+ export interface ConnectEvent {
41
+ name: "ticket.created" | "ticket.replied" | "navigate" | (string & {});
42
+ data?: unknown;
43
+ }
44
+ export interface ConnectError {
45
+ code: string;
46
+ message: string;
47
+ }
48
+ export interface MountOptions {
49
+ /** The desk, e.g. https://desk.example.com (https; http only for localhost). */
50
+ baseUrl: string;
51
+ /** The organisation's public key (org_...). */
52
+ orgKey: string;
53
+ /** Ask YOUR backend for a connect token (it calls createConnectSession). Called on load and when the token expires. */
54
+ getToken: () => Promise<string>;
55
+ view?: ConnectView;
56
+ theme?: ConnectTheme;
57
+ features?: ConnectFeatures;
58
+ locale?: ConnectLocale;
59
+ /** "auto" (default) follows the embed's content; a number is a fixed height in px. */
60
+ height?: "auto" | number;
61
+ onEvent?: (event: ConnectEvent) => void;
62
+ onError?: (error: ConnectError) => void;
63
+ /** 1.1: the frame reports how many messages are unread (launcher badge). */
64
+ onUnread?: (count: number) => void;
65
+ /** 1.1: the user closed the messenger from inside the frame. */
66
+ onClose?: () => void;
67
+ /** 1.1: tells the frame it is hosted in a messenger panel (it then shows its own close control). */
68
+ host?: "messenger";
69
+ /** 1.1: iframe title (accessibility). Default "Support tickets". */
70
+ title?: string;
71
+ }
72
+ export interface ConnectHandle {
73
+ navigate(view: ConnectView): void;
74
+ /** 1.1: the panel became visible; optionally switch view. Queued until the frame is ready. */
75
+ open(view?: ConnectView): void;
76
+ setTheme(theme: ConnectTheme): void;
77
+ /** Fetch a fresh token through getToken and hand it to the embed. */
78
+ refreshToken(): Promise<void>;
79
+ destroy(): void;
80
+ }
81
+ export interface ConnectUser {
82
+ /** The user's id in your system (WSO2 `sub`). Required unless idToken is used. */
83
+ uid: string;
84
+ email?: string;
85
+ name?: string;
86
+ firstName?: string;
87
+ lastName?: string;
88
+ phone?: string;
89
+ /** Your role name; the organisation's role mappings turn it into a CRM contact role. */
90
+ role?: string;
91
+ department?: string;
92
+ attributes?: Record<string, unknown>;
93
+ /**
94
+ * Whether `email` is verified by your sign-in (default true: your backend vouches for it).
95
+ * false = ARM Desk never links an existing account by this address.
96
+ */
97
+ emailVerified?: boolean;
98
+ }
99
+ export interface CreateConnectSessionOptions {
100
+ /** The desk, e.g. https://desk.example.com (its host also selects the tenant). */
101
+ baseUrl: string;
102
+ /** The API's own base (e.g. http://api:3000/api). Default: `<baseUrl>/api/proxy`. */
103
+ apiUrl?: string;
104
+ /** Name the tenant when you do not call the tenant's own host (sent as X-Tenant-Slug). */
105
+ tenantSlug?: string;
106
+ orgKey: string;
107
+ orgSecret: string;
108
+ user?: ConnectUser;
109
+ /** An OIDC ID token (WSO2 ...), verified by ARM Desk against the organisation's trusted issuers. */
110
+ idToken?: string;
111
+ /** Switch features OFF for this session (e.g. { closeTicket: false }). Can only narrow what the organisation allows. */
112
+ features?: ConnectFeatures;
113
+ /** Abort after this many ms (default 10000). */
114
+ timeoutMs?: number;
115
+ /** A fetch implementation (default: the global one, Node 18+). */
116
+ fetch?: typeof fetch;
117
+ }
118
+ export interface ConnectSession {
119
+ token: string;
120
+ /** Seconds until the token expires. */
121
+ expiresIn: number;
122
+ user: {
123
+ id: string;
124
+ email?: string;
125
+ name?: string;
126
+ emailVerified?: boolean;
127
+ };
128
+ contactId: string | null;
129
+ }
130
+ export type TicketStatus = "NEW" | "OPEN" | "IN_PROGRESS" | "PENDING" | "PENDING_APPROVAL" | "PENDING_PROCUREMENT" | "ON_HOLD" | "RESOLVED" | "CLOSED" | "CANCELED";
131
+ export type TicketPriority = "LOW" | "NORMAL" | "HIGH" | "URGENT";
132
+ export interface TicketSummary {
133
+ id: string;
134
+ number: string;
135
+ subject: string;
136
+ status: TicketStatus | (string & {});
137
+ priority: TicketPriority | (string & {});
138
+ createdAt: string;
139
+ updatedAt: string;
140
+ lastReplyAt: string | null;
141
+ }
142
+ export interface Attachment {
143
+ id: string;
144
+ name: string;
145
+ mimeType?: string;
146
+ size?: number;
147
+ /** A signed 15-minute download link. */
148
+ url?: string;
149
+ }
150
+ export interface Thread {
151
+ id: string;
152
+ author: {
153
+ name: string;
154
+ isAgent: boolean;
155
+ };
156
+ /** Sanitised HTML. */
157
+ body: string;
158
+ createdAt: string;
159
+ attachments?: Attachment[];
160
+ }
161
+ export interface TicketDetail extends TicketSummary {
162
+ category: {
163
+ id: string;
164
+ name: string;
165
+ } | null;
166
+ requester: {
167
+ name: string;
168
+ isMe: boolean;
169
+ };
170
+ canReply: boolean;
171
+ canClose: boolean;
172
+ threads: Thread[];
173
+ }
174
+ export interface TicketList {
175
+ items: TicketSummary[];
176
+ total: number;
177
+ }
178
+ export interface ListTicketsParams {
179
+ /** One status or several (sent as CSV). */
180
+ status?: string | string[];
181
+ search?: string;
182
+ page?: number;
183
+ /** Up to 100. */
184
+ limit?: number;
185
+ }
186
+ export interface CreateTicketInput {
187
+ /** 5 to 255 characters. */
188
+ subject: string;
189
+ /** 10 to 20000 characters of PLAIN TEXT. */
190
+ description: string;
191
+ priority?: TicketPriority;
192
+ categoryId?: string;
193
+ files?: Array<File | Blob>;
194
+ }
195
+ export interface CreatedTicket {
196
+ id: string;
197
+ number: string;
198
+ subject: string;
199
+ status: string;
200
+ createdAt: string;
201
+ attachments: Array<{
202
+ id: string;
203
+ name: string;
204
+ }>;
205
+ }
206
+ export interface ReplyInput {
207
+ /** Plain text. */
208
+ body: string;
209
+ files?: Array<File | Blob>;
210
+ }
211
+ export interface Reply {
212
+ id: string;
213
+ author: string;
214
+ body: string;
215
+ createdAt: string;
216
+ attachments: Array<{
217
+ id: string;
218
+ name: string;
219
+ }>;
220
+ }
221
+ export interface Me {
222
+ id: string;
223
+ email: string;
224
+ name: string;
225
+ firstName: string | null;
226
+ lastName: string | null;
227
+ phone: string | null;
228
+ uid: string | null;
229
+ role: string | null;
230
+ contactId: string | null;
231
+ organization: {
232
+ id: string;
233
+ name: string;
234
+ };
235
+ }
236
+ export interface Category {
237
+ id: string;
238
+ name: string;
239
+ parentId: string | null;
240
+ }
241
+ export interface DeskConfig {
242
+ organization: {
243
+ name: string;
244
+ };
245
+ theme?: ConnectTheme;
246
+ features?: ConnectFeatures;
247
+ locale?: string;
248
+ }
249
+ export interface CatalogRequestOptions {
250
+ quantity?: number;
251
+ requestedForId?: string;
252
+ /** Files by catalog variable name. */
253
+ files?: Record<string, File | Blob>;
254
+ }
255
+ export interface Unsubscribe {
256
+ (): void;
257
+ }
258
+ export type ClientEventMap = {
259
+ "ticket.created": CreatedTicket;
260
+ "ticket.replied": {
261
+ ticketId: string;
262
+ reply: Reply;
263
+ };
264
+ "session.expired": ArmDeskErrorLike;
265
+ error: ArmDeskErrorLike;
266
+ };
267
+ export type ArmDeskErrorLike = {
268
+ code: string;
269
+ message: string;
270
+ status?: number;
271
+ };
272
+ /**
273
+ * How the browser signs in. ONE of:
274
+ * - `userToken`: PRIMARY. A short-lived signed user token minted by YOUR server with signUserToken() (no network call
275
+ * on your side, no endpoint of yours). The library exchanges it for an ARM Desk token (OAuth 2.0 JWT bearer grant).
276
+ * - `idToken`: browser OIDC (WSO2 ...). The organisation must allow browser sessions.
277
+ * - `sessionUrl`: a route on YOUR server mounted with createConnectHandler (default `/armdesk/session`).
278
+ * - `getToken`: you obtain the ARM Desk connect token yourself (legacy; `mount` compatible).
279
+ */
280
+ export type AuthOption = {
281
+ userToken: () => string | Promise<string>;
282
+ } | {
283
+ idToken: () => string | Promise<string>;
284
+ nonce?: string;
285
+ } | {
286
+ sessionUrl?: string;
287
+ } | {
288
+ getToken: () => string | Promise<string>;
289
+ };
290
+ export interface ClientOptions {
291
+ /** The organisation's public key (org_...). */
292
+ orgKey: string;
293
+ /** The desk, e.g. https://desk.example.com. Default: the origin the script tag was loaded from. */
294
+ desk?: string;
295
+ /** Override the API base (default: announced by the desk's bootstrap, else `<desk>/api/proxy`). */
296
+ apiBase?: string;
297
+ auth: AuthOption;
298
+ locale?: ConnectLocale;
299
+ theme?: ConnectTheme;
300
+ features?: ConnectFeatures;
301
+ /** Retries on 429 / 5xx (default 2). */
302
+ retries?: number;
303
+ /** First backoff delay in ms (default 400; doubles each retry). */
304
+ retryDelayMs?: number;
305
+ /** Per-request timeout in ms (default 20000). */
306
+ timeoutMs?: number;
307
+ fetch?: typeof fetch;
308
+ }
309
+ export interface ClientMountOptions {
310
+ view?: ConnectView;
311
+ theme?: ConnectTheme;
312
+ features?: ConnectFeatures;
313
+ locale?: ConnectLocale;
314
+ height?: "auto" | number;
315
+ onEvent?: (event: ConnectEvent) => void;
316
+ onError?: (error: ConnectError) => void;
317
+ onUnread?: (count: number) => void;
318
+ onClose?: () => void;
319
+ host?: "messenger";
320
+ title?: string;
321
+ }
322
+ export type MessengerPosition = "bottom-right" | "bottom-left";
323
+ export interface MessengerOptions {
324
+ /** Corner of the bubble and panel. Default "bottom-right" ("right" / "left" are accepted too). */
325
+ position?: MessengerPosition | "right" | "left";
326
+ /** Distance from the viewport edges in px: one number, or { x, y }. Default 20. */
327
+ offset?: number | {
328
+ x?: number;
329
+ y?: number;
330
+ };
331
+ /** Text shown next to the icon (the bubble becomes a pill). Without it the bubble is round. */
332
+ label?: string;
333
+ /** Accessible name of the bubble and panel. Default "Support". */
334
+ ariaLabel?: string;
335
+ /** An https URL of a custom bubble icon (an image ~28 px). Default: a chat glyph. */
336
+ iconUrl?: string;
337
+ /** The view the panel opens at. Default "home". */
338
+ view?: ConnectView;
339
+ /** Open as soon as it is created. */
340
+ open?: boolean;
341
+ /** Load the iframe only on first open (no unread badge until then). Default false: preloads so the badge works. */
342
+ lazy?: boolean;
343
+ /** Overrides the organisation's theme; `primaryColor` colours the bubble. */
344
+ theme?: ConnectTheme;
345
+ features?: ConnectFeatures;
346
+ locale?: ConnectLocale;
347
+ /** CSS z-index of the bubble and panel. Default 2147483000. */
348
+ zIndex?: number;
349
+ /** Where to attach the messenger. Default document.body. */
350
+ container?: HTMLElement | ShadowRoot;
351
+ onEvent?: (event: ConnectEvent) => void;
352
+ onError?: (error: ConnectError) => void;
353
+ }
354
+ export type MessengerEventMap = {
355
+ unread: number;
356
+ open: {
357
+ view: ConnectView | null;
358
+ };
359
+ close: void;
360
+ };
361
+ export interface MessengerController {
362
+ /** Opens the panel (optionally at a view). */
363
+ open(view?: ConnectView): void;
364
+ close(): void;
365
+ toggle(): void;
366
+ /** Switch the panel's view without opening it. */
367
+ navigate(view: ConnectView): void;
368
+ setTheme(theme: ConnectTheme): void;
369
+ isOpen(): boolean;
370
+ /** The last unread count reported by the frame. */
371
+ unread(): number;
372
+ on<K extends keyof MessengerEventMap>(event: K, cb: (payload: MessengerEventMap[K]) => void): Unsubscribe;
373
+ /** Removes the bubble, the panel and every listener. Idempotent. */
374
+ destroy(): void;
375
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,10 @@
1
+ {
2
+ "name": "armdesk-connect-example-express",
3
+ "private": true,
4
+ "type": "module",
5
+ "scripts": { "start": "node server.mjs" },
6
+ "dependencies": {
7
+ "@armdesk/connect-sdk": "file:../..",
8
+ "express": "^4.19.2"
9
+ }
10
+ }
@@ -0,0 +1,35 @@
1
+ // Server mode with Express. Run:
2
+ // cd examples/express-server && npm install && DESK_URL=http://localhost:3001 ORG_KEY=org_... ORG_SECRET=cos_... npm start
3
+ // then open http://localhost:4000 (add that origin to the organisation's allowed origins first).
4
+ import express from "express";
5
+ import { createConnectHandler, signUserToken } from "@armdesk/connect-sdk/server";
6
+
7
+ const { DESK_URL = "http://localhost:3001", ORG_KEY, ORG_SECRET, PORT = "4000" } = process.env;
8
+ if (!ORG_KEY || !ORG_SECRET) {
9
+ console.error("Set ORG_KEY and ORG_SECRET (shown once when the organisation is registered).");
10
+ process.exit(1);
11
+ }
12
+
13
+ // Your own sign-in would set req.user. This demo signs everybody in as one fixed user.
14
+ const DEMO_USER = { id: "demo-user-1", email: "demo.user@example.com", name: "Demo User", role: "manager", department: "Finance" };
15
+ const app = express();
16
+ app.use((req, _res, next) => ((req.user = DEMO_USER), next()));
17
+
18
+ // Mode A (server mode): the route the browser library calls by default.
19
+ const armdesk = createConnectHandler({ orgKey: ORG_KEY, orgSecret: ORG_SECRET, desk: DESK_URL, getUser: (req) => req.user });
20
+ app.post("/armdesk/session", armdesk.express());
21
+
22
+ // Mode B (signed user token): render a token into the page, no route needed.
23
+ app.get("/", (req, res) => {
24
+ const userToken = signUserToken({ orgKey: ORG_KEY, orgSecret: ORG_SECRET, user: req.user });
25
+ res.type("html").send(`<!doctype html><meta charset="utf-8"><title>Express host</title>
26
+ <h1>Express host product</h1><div id="support"></div>
27
+ <script src="${DESK_URL}/connect/armdesk-connect.js"></script>
28
+ <script>
29
+ const client = ArmDeskConnect.init({ orgKey: ${JSON.stringify(ORG_KEY)}, auth: { userToken: () => ${JSON.stringify(userToken)} } });
30
+ client.mount("#support");
31
+ // server mode instead: ArmDeskConnect.init({ orgKey: ..., auth: {} }).mount("#support");
32
+ </script>`);
33
+ });
34
+
35
+ app.listen(Number(PORT), () => console.log(`Express host on http://localhost:${PORT} (desk: ${DESK_URL})`));
@@ -0,0 +1,30 @@
1
+ // A local stand-in for WSO2, for trying browser mode against a real ARM Desk. Not for production.
2
+ // node examples/mock-idp.mjs
3
+ // Serves JWKS at /.well-known/jwks.json, discovery at /.well-known/openid-configuration and mints an RS256 ID token
4
+ // at POST /issue (CORS open). In ARM Desk (Admin > Connect > Identity) trust issuer http://localhost:4010, audience
5
+ // "demo-product", jwksUri http://localhost:4010/.well-known/jwks.json (plain http is a local-testing exception only).
6
+ import { createServer } from "node:http";
7
+ import { createSign, generateKeyPairSync } from "node:crypto";
8
+
9
+ const PORT = Number(process.env.PORT ?? 4010);
10
+ const ISSUER = `http://localhost:${PORT}`;
11
+ const { privateKey, publicKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
12
+ const jwk = { ...publicKey.export({ format: "jwk" }), kid: "mock-1", use: "sig", alg: "RS256" };
13
+ const b64u = (v) => Buffer.from(typeof v === "string" ? v : JSON.stringify(v)).toString("base64url");
14
+
15
+ function issue() {
16
+ const now = Math.floor(Date.now() / 1000);
17
+ const input = `${b64u({ alg: "RS256", typ: "JWT", kid: "mock-1" })}.${b64u({ iss: ISSUER, aud: "demo-product", sub: "demo-user-1", email: "ana@example.com", email_verified: true, given_name: "Ana", family_name: "Silva", roles: "manager", iat: now, exp: now + 300 })}`;
18
+ return `${input}.${createSign("RSA-SHA256").update(input).sign(privateKey).toString("base64url")}`;
19
+ }
20
+
21
+ createServer((req, res) => {
22
+ res.setHeader("Access-Control-Allow-Origin", "*");
23
+ res.setHeader("Access-Control-Allow-Headers", "*");
24
+ if (req.method === "OPTIONS") return res.writeHead(204).end();
25
+ const json = (b) => res.writeHead(200, { "Content-Type": "application/json" }).end(JSON.stringify(b));
26
+ if (req.url === "/.well-known/jwks.json") return json({ keys: [jwk] });
27
+ if (req.url === "/.well-known/openid-configuration") return json({ issuer: ISSUER, jwks_uri: `${ISSUER}/.well-known/jwks.json` });
28
+ if (req.url === "/issue" && req.method === "POST") return json({ idToken: issue() });
29
+ res.writeHead(404).end();
30
+ }).listen(PORT, () => console.log(`Mock IdP on ${ISSUER}`));
@@ -0,0 +1,11 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <title>ARM Desk Connect - React + Vite</title>
6
+ </head>
7
+ <body>
8
+ <div id="root"></div>
9
+ <script type="module" src="/src/main.jsx"></script>
10
+ </body>
11
+ </html>
@@ -0,0 +1,15 @@
1
+ {
2
+ "name": "armdesk-connect-example-react-vite",
3
+ "private": true,
4
+ "type": "module",
5
+ "scripts": { "dev": "vite", "build": "vite build" },
6
+ "dependencies": {
7
+ "@armdesk/connect-sdk": "file:../..",
8
+ "react": "^18.3.1",
9
+ "react-dom": "^18.3.1"
10
+ },
11
+ "devDependencies": {
12
+ "@vitejs/plugin-react": "^4.3.1",
13
+ "vite": "^5.4.0"
14
+ }
15
+ }
@@ -0,0 +1,25 @@
1
+ // React + WSO2 (OIDC) in the browser: no backend of your own. Run:
2
+ // cd examples/react-vite && npm install && VITE_DESK_URL=http://localhost:3001 VITE_ORG_KEY=org_... npm run dev
3
+ // Replace getIdToken with your real OIDC client (oidc-client-ts, WSO2 SDK ...). Add http://localhost:5173 to the
4
+ // organisation's allowed origins, switch on Browser sessions and trust your issuer.
5
+ import React, { useState } from "react";
6
+ import { createRoot } from "react-dom/client";
7
+ import { ArmDeskEmbed, ArmDeskNewTicket, ArmDeskProvider, ArmDeskTicket, ArmDeskTickets } from "@dhrp-ticket/connect-sdk/react";
8
+
9
+ const getIdToken = async () => window.sessionStorage.getItem("id_token"); // your OIDC client's ID token
10
+
11
+ function App() {
12
+ const [open, setOpen] = useState(null);
13
+ return (
14
+ <ArmDeskProvider orgKey={import.meta.env.VITE_ORG_KEY} desk={import.meta.env.VITE_DESK_URL} auth={{ idToken: getIdToken }}>
15
+ <h1>Acme product</h1>
16
+ <h2>Your own layout with the headless components</h2>
17
+ {open ? <><button onClick={() => setOpen(null)}>Back</button><ArmDeskTicket ticketId={open} /></> : <ArmDeskTickets onSelect={setOpen} />}
18
+ <ArmDeskNewTicket />
19
+ <h2>Or the complete portal</h2>
20
+ <ArmDeskEmbed view="tickets" theme={{ primaryColor: "#0f766e" }} />
21
+ </ArmDeskProvider>
22
+ );
23
+ }
24
+
25
+ createRoot(document.getElementById("root")).render(<App />);
@@ -0,0 +1,4 @@
1
+ import react from "@vitejs/plugin-react";
2
+ import { defineConfig } from "vite";
3
+
4
+ export default defineConfig({ plugins: [react()], server: { port: 5173 } });