@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
package/CHANGELOG.md ADDED
@@ -0,0 +1,41 @@
1
+ # Changelog
2
+
3
+ ## 1.1.0
4
+
5
+ The messenger: a chat bubble that opens the support panel (Home, Messages, Help). Backward compatible.
6
+
7
+ - `client.messenger(options)` / `ArmDeskConnect.messenger(...)` returns a controller `{ open(view?), close(), toggle(),
8
+ navigate(view), setTheme(theme), isOpen(), unread(), on("unread" | "open" | "close"), destroy() }`. Bubble position,
9
+ offset, label, custom https icon, unread badge, z-index; 380 x 640 panel, full screen under 480 px; Esc closes and focus
10
+ returns to the bubble; ARIA dialog semantics; no animation under `prefers-reduced-motion`. `theme.primaryColor` (or the
11
+ organisation's theme) colours the bubble.
12
+ - `<armdesk-messenger position view open label icon-url offset>` web component (two-way `open` attribute, events
13
+ `armdesk-messenger-open` / `-close` / `-unread`). `<armdesk-launcher>` is now the messenger (opens at `tickets` by default).
14
+ - React: `<ArmDeskMessenger />` and `useMessenger()`.
15
+ - Embed protocol: views `home`, `messages`, `help`, `chat:<id>`, `article:<id>`; host to frame `open { view? }`; frame to
16
+ host `unread { count }` and `close`; `init` carries `host: "messenger"` inside the panel. `mount()` gains `onUnread`,
17
+ `onClose` and `handle.open(view?)`.
18
+ - Features `chat`, `helpCenter`, `aiAnswers`.
19
+ - README: "Your docs in the AI answers" (the org-backend knowledge sources API).
20
+ - IIFE about 12.5 kB gzipped (budget unchanged at 25 kB).
21
+
22
+ ## 1.0.0
23
+
24
+ The complete library. An integrating product needs only this package; it never calls an ARM Desk endpoint itself.
25
+
26
+ - `ArmDeskConnect.init({ orgKey, auth })` / `createClient`: the desk URL is detected from the script tag's origin.
27
+ Auth modes: `userToken` (signed user token, primary), `idToken` (browser OIDC / WSO2), `sessionUrl` (server route),
28
+ `getToken` (legacy).
29
+ - Headless typed client: `me`, `config`, `categories`, `tickets.{list,get,create,reply,close}`, `catalog.{list,request}`,
30
+ events (`ticket.created`, `ticket.replied`, `session.expired`, `error`), `signOut`, `mount`. Typed `ArmDeskError`.
31
+ Retries with backoff on 429 / 5xx (Retry-After honoured), never on other 4xx; in-memory token cache with early renewal.
32
+ - Web components (Shadow DOM): `<armdesk-tickets>`, `<armdesk-new-ticket>`, `<armdesk-ticket>`, `<armdesk-launcher>`.
33
+ - React: `ArmDeskProvider`, `useArmDesk`, `useTickets`, `useTicket`, `useCreateTicket`, `ArmDeskEmbed`, `ArmDeskTickets`,
34
+ `ArmDeskTicket`, `ArmDeskNewTicket` (React is an optional peer).
35
+ - Server (`/server`): `signUserToken` (HS256 with a key derived from the org secret, or RS256/ES256 with your private key),
36
+ `createConnectHandler` (Express, Next.js, fetch, Node adapters; CSRF-checked), `createConnectSession`.
37
+ - Deprecated: `ArmDeskConnect.mount(el, { baseUrl, orgKey, getToken })` still works; use `init(...).mount(el)`.
38
+
39
+ ## 0.1.0
40
+
41
+ First release: iframe embed (`mount`), `createConnectSession`, `<ArmDeskEmbed>`.
package/LICENSE.txt ADDED
@@ -0,0 +1,15 @@
1
+ ARM Desk SDK licence
2
+
3
+ Copyright (c) 2026 DHRP. All rights reserved.
4
+
5
+ This package is proprietary software. It is made available on the npm registry
6
+ so that customers of ARM Desk can install it, and it may be used only to build
7
+ integrations with an ARM Desk service under the customer's agreement with DHRP.
8
+
9
+ No other right is granted. You may not copy, modify, sublicense, sell or
10
+ redistribute this package, or use it with any service other than ARM Desk,
11
+ except as that agreement allows.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED. IN NO EVENT SHALL DHRP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
15
+ LIABILITY ARISING FROM THE SOFTWARE OR ITS USE, EXCEPT AS THAT AGREEMENT SAYS.
package/README.md CHANGED
@@ -1,3 +1,525 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # @armdesk/connect-sdk
2
+
3
+ ARM Desk Connect: put support tickets (My tickets, New ticket, conversation) inside your own product, with your own
4
+ sign-in and your own look. **This package is everything you need.** You never call an ARM Desk endpoint yourself and
5
+ never read an API reference.
6
+
7
+ ```
8
+ your server your page ARM Desk
9
+ signUserToken({orgKey, orgSecret, ArmDeskConnect.init({ orgKey, verifies the signature, creates/updates
10
+ user}) -> short-lived token --> auth: { userToken: () => token } }) the customer + CRM contact, issues a
11
+ (local, no network call) client.mount(...) / <armdesk-tickets> 15-minute session the library renews
12
+ ```
13
+
14
+ 1. A tenant admin registers your product as a **Connected organization** (Admin > Developer > Connect) and gets an
15
+ `orgKey` (`org_...`, public) and an `orgSecret` (`cos_...`, **shown once**), and lists your site's origins.
16
+ 2. Your **server** signs a short-lived token for the signed-in user (`signUserToken`, no network call) and renders it
17
+ into your page.
18
+ 3. Your **page** gives that token to the library. Done.
19
+
20
+ Contents: [Messenger](#messenger-quick-start) | [Quick starts](#quick-starts) |
21
+ [Signing without Node](#signing-the-user-token-without-node) | [Client API](#client-api) | [UI](#ui) |
22
+ [Your docs in the AI answers](#your-docs-in-the-ai-answers) | [Server helpers](#server-helpers) | [Theme](#theme-keys) |
23
+ [Errors](#errors) | [Security](#security-notes) | [Embed protocol](#embed-protocol)
24
+
25
+ ## Messenger quick start
26
+
27
+ The headline experience (1.1): a chat bubble in the corner of your product. It opens a panel with **Home** (greeting,
28
+ team availability, recent conversations, help search), **Messages** (live chat with your support team plus the user's
29
+ tickets) and **Help** (AI answers from your docs and the knowledge base, with "Talk to a person").
30
+
31
+ ```js
32
+ // your server, while rendering the page the user is signed in to (no network call)
33
+ import { signUserToken } from "@armdesk/connect-sdk/server";
34
+ const userToken = signUserToken({ orgKey: process.env.ARMDESK_ORG_KEY, orgSecret: process.env.ARMDESK_ORG_SECRET, user: { id: user.id, email: user.email, name: user.name } });
35
+ // render it: <meta name="armdesk-user-token" content="...">
36
+ ```
37
+
38
+ ```html
39
+ <script src="https://<your-desk>/connect/armdesk-connect.js"></script>
40
+ <script>
41
+ const messenger = ArmDeskConnect.messenger({
42
+ orgKey: "org_xxxxxxxxxxxxxxxxxxxxxxxx",
43
+ auth: { userToken: () => document.querySelector('meta[name="armdesk-user-token"]').content },
44
+ position: "bottom-right",
45
+ theme: { primaryColor: "#0f766e" }, // optional: defaults to the organisation's theme
46
+ });
47
+ messenger.on("unread", (n) => console.log(n, "unread"));
48
+ document.querySelector("#help-link").onclick = () => messenger.open("help");
49
+ </script>
50
+ ```
51
+
52
+ Or, with no script of your own beyond `init`: `<armdesk-messenger position="bottom-left"></armdesk-messenger>`.
53
+
54
+ React:
55
+
56
+ ```tsx
57
+ import { ArmDeskProvider, ArmDeskMessenger, useMessenger } from "@armdesk/connect-sdk/react";
58
+
59
+ function HelpButton() {
60
+ const { open, unread } = useMessenger();
61
+ return <button onClick={() => open("help")}>Help {unread > 0 ? `(${unread})` : null}</button>;
62
+ }
63
+
64
+ export function App({ userToken }: { userToken: () => string }) {
65
+ return (
66
+ <ArmDeskProvider desk="https://desk.example.com" orgKey="org_xxx" auth={{ userToken }}>
67
+ <HelpButton />
68
+ <ArmDeskMessenger position="bottom-right" onUnread={(n) => (document.title = n ? `(${n}) My app` : "My app")} />
69
+ </ArmDeskProvider>
70
+ );
71
+ }
72
+ ```
73
+
74
+ ### Messenger options
75
+
76
+ `client.messenger(options)`, `ArmDeskConnect.messenger(options)` (also accepts `orgKey` / `auth` / `desk` to sign in
77
+ first, or uses the client from the last `init()`), `<ArmDeskMessenger {...options} />`.
78
+
79
+ | Option | Default | Notes |
80
+ |---|---|---|
81
+ | `position` | `"bottom-right"` | or `"bottom-left"` |
82
+ | `offset` | `20` | px from the edges: a number or `{ x, y }` |
83
+ | `label` | none | text next to the icon (the bubble becomes a pill) |
84
+ | `ariaLabel` | `"Support"` | accessible name of the bubble and the panel |
85
+ | `iconUrl` | chat glyph | an https image URL |
86
+ | `view` | `"home"` | `home`, `messages`, `help`, `chat:<id>`, `article:<id>`, or the ticket views |
87
+ | `open` | `false` | open on creation |
88
+ | `lazy` | `false` | load the panel only on first open (no unread badge until then) |
89
+ | `theme`, `features`, `locale` | the client's | `theme.primaryColor` colours the bubble; features can only narrow (`chat`, `helpCenter`, `aiAnswers`, ...) |
90
+ | `zIndex` | `2147483000` | |
91
+ | `container` | `document.body` | where the bubble is attached |
92
+ | `onEvent`, `onError` | | as for `mount` |
93
+
94
+ The controller: `open(view?)`, `close()`, `toggle()`, `navigate(view)`, `setTheme(theme)`, `isOpen()`, `unread()`,
95
+ `on("unread" | "open" | "close", cb)` (returns an unsubscribe), `destroy()`.
96
+
97
+ `<armdesk-messenger>` attributes: `position`, `view`, `open` (two-way: set it to open; it is present while open), `label`,
98
+ `aria-label`, `icon-url`, `offset`, `theme` (JSON). Events: `armdesk-messenger-open`, `armdesk-messenger-close`,
99
+ `armdesk-messenger-unread` (detail: count). Methods: `open(view?)`, `close()`, `toggle()`.
100
+
101
+ React: `<ArmDeskMessenger />` takes the options plus `open` (controlled), `onOpen`, `onClose`, `onUnread`, `client`.
102
+ `useMessenger()` (anywhere under the provider) returns `{ open, close, toggle, isOpen, unread, ready, controller }` for the
103
+ mounted messenger.
104
+
105
+ Behaviour: a 380 x 640 panel with rounded corners above the bubble, full screen below 480 px wide; Esc (or the panel's
106
+ close button) closes it and returns focus to the bubble; the bubble shows an unread badge (99+); animations are off when
107
+ the visitor prefers reduced motion. The panel is the same origin-checked iframe as `client.mount`.
108
+
109
+ ## Install
110
+
111
+ Script tag (served by your ARM Desk; it detects the desk from its own URL, so only `orgKey` is needed):
112
+
113
+ ```html
114
+ <script src="https://<your-desk>/connect/armdesk-connect.js"></script>
115
+ ```
116
+
117
+ npm: `pnpm add @armdesk/connect-sdk`. Entries: `.` (browser client), `/server` (Node 18+), `/react` (React 17+, optional
118
+ peer), `/elements` (web components). The IIFE has no dependencies (about 12.5 kB gzipped, web components and the
119
+ messenger included).
120
+
121
+ ## Quick starts
122
+
123
+ ### 1. Script tag + signed user token (recommended)
124
+
125
+ Your server signs the token while rendering the page the user is already signed in to (no new endpoint):
126
+
127
+ ```js
128
+ // server (Node). Other languages: see "Signing the user token without Node".
129
+ import { signUserToken } from "@armdesk/connect-sdk/server";
130
+
131
+ const userToken = signUserToken({
132
+ orgKey: process.env.ARMDESK_ORG_KEY,
133
+ orgSecret: process.env.ARMDESK_ORG_SECRET, // server only
134
+ user: { id: user.id, email: user.email, name: user.name, role: user.role, department: user.department, phone: user.phone },
135
+ expiresIn: 300, // seconds, default 300, max 600
136
+ });
137
+ // render it into the page, e.g. <meta name="armdesk-user-token" content="...">
138
+ ```
139
+
140
+ ```html
141
+ <div id="support"></div>
142
+ <script src="https://<your-desk>/connect/armdesk-connect.js"></script>
143
+ <script>
144
+ const client = ArmDeskConnect.init({
145
+ orgKey: "org_xxxxxxxxxxxxxxxxxxxxxxxx",
146
+ auth: { userToken: () => document.querySelector('meta[name="armdesk-user-token"]').content },
147
+ });
148
+ client.mount("#support", { theme: { primaryColor: "#0f766e" } }); // the full portal UI in an iframe
149
+ </script>
150
+ ```
151
+
152
+ The token is short-lived on purpose. When the ARM Desk session (15 minutes) runs out the library calls `userToken()`
153
+ again, so make it return a fresh token (for example by reloading a tiny JSON from your own page, or by minting a token
154
+ per call in a server-rendered app). Prefer the pieces in your own layout? Use the [web components](#ui) instead of
155
+ `client.mount`.
156
+
157
+ ### 2. Script tag + WSO2 / OIDC, no backend at all
158
+
159
+ If your product signs users in with WSO2 (or any OIDC provider) in the browser, hand the library the ID token. Nothing
160
+ of yours runs on a server. The admin must switch on **Browser sessions** and trust your issuer (Admin > Connect > Identity).
161
+
162
+ ```html
163
+ <script src="https://<your-desk>/connect/armdesk-connect.js"></script>
164
+ <script>
165
+ const client = ArmDeskConnect.init({
166
+ orgKey: "org_xxxxxxxxxxxxxxxxxxxxxxxx",
167
+ auth: { idToken: () => myOidcClient.getIdToken() }, // your existing WSO2 sign-in
168
+ });
169
+ client.mount("#support");
170
+ </script>
171
+ ```
172
+
173
+ The library keeps the ARM Desk session in memory and renews it itself; it asks for a new ID token only when it must.
174
+ Try it locally with `examples/wso2-browser.html` (it contains a mock identity provider).
175
+
176
+ ### 3. React
177
+
178
+ ```tsx
179
+ import { ArmDeskProvider, ArmDeskEmbed, ArmDeskTickets, ArmDeskNewTicket, useTickets } from "@armdesk/connect-sdk/react";
180
+
181
+ export function Support({ userToken }: { userToken: string }) {
182
+ return (
183
+ <ArmDeskProvider orgKey="org_xxxxxxxxxxxxxxxxxxxxxxxx" desk="https://desk.example.com" auth={{ userToken: () => userToken }}>
184
+ <ArmDeskEmbed view="tickets" theme={{ primaryColor: "#0f766e" }} />
185
+ {/* or build your own UI: <ArmDeskTickets onSelect={openTicket} /> <ArmDeskNewTicket /> */}
186
+ </ArmDeskProvider>
187
+ );
188
+ }
189
+
190
+ function OpenCount() {
191
+ const { data, loading, error, refetch } = useTickets({ status: "OPEN", limit: 5 });
192
+ return <span>{loading ? "..." : data?.total}</span>;
193
+ }
194
+ ```
195
+
196
+ With WSO2 in the browser use `auth={{ idToken: () => oidc.getIdToken() }}`. Hooks: `useArmDesk()` (the client),
197
+ `useTickets(params)`, `useTicket(id)`, `useCreateTicket()`. They refetch on `ticket.created` / `ticket.replied`.
198
+
199
+ ### 4. Express, server mode
200
+
201
+ When you prefer a route to render-time tokens, the helper mounts the route the browser library calls by default
202
+ (`/armdesk/session`). It reads YOUR signed-in user, talks to ARM Desk with the org secret, and returns only the token.
203
+
204
+ ```js
205
+ import express from "express";
206
+ import { createConnectHandler } from "@armdesk/connect-sdk/server";
207
+
208
+ const armdesk = createConnectHandler({
209
+ orgKey: process.env.ARMDESK_ORG_KEY,
210
+ orgSecret: process.env.ARMDESK_ORG_SECRET,
211
+ desk: "https://desk.example.com",
212
+ getUser: (req) => req.user && { id: req.user.id, email: req.user.email, name: req.user.name, role: req.user.role },
213
+ });
214
+
215
+ const app = express();
216
+ app.post("/armdesk/session", armdesk.express());
217
+ ```
218
+
219
+ ```html
220
+ <script>
221
+ ArmDeskConnect.init({ orgKey: "org_...", auth: {} }).mount("#support"); // sessionUrl defaults to /armdesk/session
222
+ </script>
223
+ ```
224
+
225
+ ### 5. Next.js, server mode
226
+
227
+ ```ts
228
+ // app/armdesk/session/route.ts
229
+ import { createConnectHandler } from "@armdesk/connect-sdk/server";
230
+ import { getSession } from "@/lib/auth"; // yours
231
+
232
+ export const POST = createConnectHandler({
233
+ orgKey: process.env.ARMDESK_ORG_KEY!,
234
+ orgSecret: process.env.ARMDESK_ORG_SECRET!,
235
+ desk: process.env.ARMDESK_URL!,
236
+ getUser: async (req: Request) => {
237
+ const s = await getSession(req);
238
+ return s && { id: s.userId, email: s.email, name: s.name };
239
+ },
240
+ }).next();
241
+ ```
242
+
243
+ Client: `<ArmDeskProvider orgKey="org_..." desk="..." auth={{}}>` (empty auth means `sessionUrl: "/armdesk/session"`).
244
+ Cloudflare Workers, Deno and Bun use `handler.fetch(request)`; plain `http` uses `handler.node(req, res)`.
245
+ CSRF: the route requires the `X-ArmDesk-Csrf: 1` header (sent by the library; a cross-site form cannot add it), refuses
246
+ a foreign `Origin` (add trusted ones with `allowedOrigins`), and never caches.
247
+
248
+ ### 6. Headless (no UI from us)
249
+
250
+ ```ts
251
+ import { createClient, ArmDeskError } from "@armdesk/connect-sdk";
252
+
253
+ const client = createClient({ orgKey: "org_...", desk: "https://desk.example.com", auth: { userToken: () => fetchToken() } });
254
+
255
+ const { items, total } = await client.tickets.list({ status: ["OPEN", "PENDING"], search: "vpn", page: 1, limit: 20 });
256
+ const t = await client.tickets.create({ subject: "Cannot log in", description: "Plain text.", priority: "HIGH", files: [file] });
257
+ await client.tickets.reply(t.id, { body: "Thanks, that worked.", files: [] });
258
+ await client.tickets.close(t.id);
259
+
260
+ client.on("ticket.created", (t) => analytics.track("ticket", t.number));
261
+ client.on("session.expired", () => window.location.assign("/login"));
262
+ try { await client.me(); } catch (e) { if (e instanceof ArmDeskError) console.log(e.code, e.status); }
263
+ ```
264
+
265
+ ## Signing the user token without Node
266
+
267
+ `signUserToken` produces a standard JWT (RFC 7523 assertion), so any JWT library can do it. Rules:
268
+
269
+ - Header: `alg: HS256`, `typ: JWT`, `kid: "<orgKey>:<secretVersion>"` (secret version 1 unless the admin rotated your
270
+ secret; the Connect screen shows the key id to use).
271
+ - HMAC key: `HMAC-SHA256(key = orgSecret, message = "armdesk-connect-assertion-v1")` as raw bytes. The raw secret is never
272
+ the JWT key.
273
+ - Claims: `iss` = orgKey, `sub` = your user id, `aud` = `armdesk-connect`, `iat`, `nbf`, `exp` (at most `iat` + 600 s),
274
+ `jti` (random, single use), and optionally `email`, `email_verified`, `name`, `given_name`, `family_name`,
275
+ `phone_number`, `role`, `department`, `attributes` (object, at most 4 KB).
276
+
277
+ Python (PyJWT):
278
+
279
+ ```python
280
+ import hashlib, hmac, secrets, time, jwt
281
+
282
+ key = hmac.new(ORG_SECRET.encode(), b"armdesk-connect-assertion-v1", hashlib.sha256).digest()
283
+ now = int(time.time())
284
+ token = jwt.encode(
285
+ {"iss": ORG_KEY, "sub": user.id, "aud": "armdesk-connect", "iat": now, "nbf": now, "exp": now + 300,
286
+ "jti": secrets.token_hex(16), "email": user.email, "name": user.name, "role": user.role},
287
+ key, algorithm="HS256", headers={"kid": f"{ORG_KEY}:1"})
288
+ ```
289
+
290
+ Java (com.auth0:java-jwt):
291
+
292
+ ```java
293
+ Mac mac = Mac.getInstance("HmacSHA256");
294
+ mac.init(new SecretKeySpec(ORG_SECRET.getBytes(UTF_8), "HmacSHA256"));
295
+ byte[] key = mac.doFinal("armdesk-connect-assertion-v1".getBytes(UTF_8));
296
+ Instant now = Instant.now();
297
+ String token = JWT.create()
298
+ .withKeyId(ORG_KEY + ":1").withIssuer(ORG_KEY).withSubject(user.getId()).withAudience("armdesk-connect")
299
+ .withIssuedAt(now).withNotBefore(now).withExpiresAt(now.plusSeconds(300)).withJWTId(UUID.randomUUID().toString())
300
+ .withClaim("email", user.getEmail()).withClaim("name", user.getName()).withClaim("role", user.getRole())
301
+ .sign(Algorithm.HMAC256(key));
302
+ ```
303
+
304
+ .NET (System.IdentityModel.Tokens.Jwt):
305
+
306
+ ```csharp
307
+ using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(orgSecret));
308
+ var key = new SymmetricSecurityKey(hmac.ComputeHash(Encoding.UTF8.GetBytes("armdesk-connect-assertion-v1"))) { KeyId = $"{orgKey}:1" };
309
+ var now = DateTime.UtcNow;
310
+ var jwt = new JwtSecurityToken(
311
+ issuer: orgKey, audience: "armdesk-connect", notBefore: now, expires: now.AddMinutes(5),
312
+ signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256),
313
+ claims: new[] { new Claim("sub", user.Id), new Claim("jti", Guid.NewGuid().ToString("N")), new Claim("email", user.Email), new Claim("name", user.Name) });
314
+ jwt.Payload["iat"] = new DateTimeOffset(now).ToUnixTimeSeconds();
315
+ var token = new JwtSecurityTokenHandler().WriteToken(jwt);
316
+ ```
317
+
318
+ PHP (firebase/php-jwt):
319
+
320
+ ```php
321
+ $key = hash_hmac('sha256', 'armdesk-connect-assertion-v1', $orgSecret, true);
322
+ $now = time();
323
+ $token = JWT::encode([
324
+ 'iss' => $orgKey, 'sub' => (string) $user->id, 'aud' => 'armdesk-connect', 'iat' => $now, 'nbf' => $now,
325
+ 'exp' => $now + 300, 'jti' => bin2hex(random_bytes(16)), 'email' => $user->email, 'name' => $user->name,
326
+ ], $key, 'HS256', $orgKey . ':1');
327
+ ```
328
+
329
+ Go (golang-jwt/jwt/v5):
330
+
331
+ ```go
332
+ mac := hmac.New(sha256.New, []byte(orgSecret))
333
+ mac.Write([]byte("armdesk-connect-assertion-v1"))
334
+ key := mac.Sum(nil)
335
+ now := time.Now()
336
+ t := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
337
+ "iss": orgKey, "sub": user.ID, "aud": "armdesk-connect", "iat": now.Unix(), "nbf": now.Unix(),
338
+ "exp": now.Add(5 * time.Minute).Unix(), "jti": uuid.NewString(), "email": user.Email, "name": user.Name,
339
+ })
340
+ t.Header["kid"] = orgKey + ":1"
341
+ token, err := t.SignedString(key)
342
+ ```
343
+
344
+ Prefer asymmetric keys? Register a public key (or JWKS URL) for the organisation and sign RS256 / ES256 with your
345
+ private key; the secret then never exists on your servers: `signUserToken({ orgKey, privateKey, kid, user })`.
346
+
347
+ ## Client API
348
+
349
+ `ArmDeskConnect.init(options)` (script tag) or `createClient(options)` (ESM). `init` also makes the client the one the web
350
+ components use.
351
+
352
+ | Option | Notes |
353
+ |---|---|
354
+ | `orgKey` | Required. |
355
+ | `desk` | The desk URL. Default: the origin the script tag was loaded from. Required with npm. https (http for localhost). |
356
+ | `auth` | One of `{ userToken }`, `{ idToken, nonce? }`, `{ sessionUrl? }`, `{ getToken }` (legacy). |
357
+ | `apiBase` | Override where the API lives (default: announced by the desk, else `<desk>/api/proxy`). |
358
+ | `locale`, `theme`, `features` | Defaults for `mount`. |
359
+ | `retries` / `retryDelayMs` / `timeoutMs` | Default 2 / 400 / 20000. |
360
+ | `fetch` | Custom fetch. |
361
+
362
+ | Method | Returns |
363
+ |---|---|
364
+ | `me()` | the signed-in user and organisation |
365
+ | `config()` | organisation name, theme, features, locale |
366
+ | `tickets.list({ status, search, page, limit })` | `{ items, total }` (status: one value or an array; up to 100 per page) |
367
+ | `tickets.get(id)` | ticket with its public threads (HTML is sanitised) and `canReply` / `canClose` |
368
+ | `tickets.create({ subject, description, priority?, categoryId?, files? })` | the created ticket (description is plain text) |
369
+ | `tickets.reply(id, { body, files? })` | the reply |
370
+ | `tickets.close(id)` | "Mark as solved" |
371
+ | `categories()` | help topics |
372
+ | `catalog.list({ search?, categoryId? })`, `catalog.request(itemId, answers, { quantity?, requestedForId?, files? })` | service catalog |
373
+ | `on(event, cb)` | `ticket.created`, `ticket.replied`, `session.expired`, `error`; returns an unsubscribe function |
374
+ | `mount(el, { view, theme, features, height, onEvent, onError, onUnread, onClose })` | the iframe embed; returns `{ navigate, open, setTheme, refreshToken, destroy }` |
375
+ | `messenger(options)` | the messenger bubble; see [Messenger options](#messenger-options) |
376
+ | `getAccessToken()`, `signOut()` | the cached session token; forget it |
377
+
378
+ Files are `File` or `Blob`. The token lives in memory only, is renewed 30 seconds before it expires, and a rejected token
379
+ triggers one fresh sign-in and a retry. Requests are retried with exponential backoff on 429 and 5xx (a `Retry-After`
380
+ header wins; a POST is retried only on 429 and 503), never on other 4xx.
381
+
382
+ ### Sign-in modes
383
+
384
+ | `auth` | Who proves the user | Your side |
385
+ |---|---|---|
386
+ | `{ userToken }` | Your server, with the org secret (signed token, 5 minutes) | `signUserToken` (any language) |
387
+ | `{ idToken }` | Your IdP (WSO2 / OIDC); needs "Browser sessions" on and the issuer trusted | nothing |
388
+ | `{ sessionUrl }` | Your server route | `createConnectHandler` |
389
+ | `{ getToken }` | You fetch an ARM Desk connect token yourself (legacy) | `createConnectSession` |
390
+
391
+ ## UI
392
+
393
+ Two ways, same data layer:
394
+
395
+ - **`client.mount(el)`**: the complete ARM Desk portal UI in an iframe (origin-checked postMessage, token never in the
396
+ URL, auto-resize). Fastest, always up to date.
397
+ - **Web components** (Shadow DOM, no framework; registered by the script tag or `import "@armdesk/connect-sdk/elements"`):
398
+
399
+ ```html
400
+ <armdesk-tickets limit="10" status="OPEN,PENDING"></armdesk-tickets>
401
+ <armdesk-new-ticket></armdesk-new-ticket>
402
+ <armdesk-ticket ticket-id="..."></armdesk-ticket>
403
+ <armdesk-messenger position="bottom-right"></armdesk-messenger>
404
+ <armdesk-launcher label="Help" view="tickets" position="right"></armdesk-launcher> <!-- 1.0 tag: now the messenger, opening at tickets -->
405
+ ```
406
+
407
+ Why Shadow DOM rather than iframe wrappers: the elements are for hosts that want tickets to be part of their page (their
408
+ layout and scrolling, no frame, no cross-origin resize), and they run on the same headless client, so there is one
409
+ contract. Shadow DOM isolates our CSS from yours. Everything is built from DOM nodes and `textContent`; the only HTML
410
+ (ticket threads) goes through an allow-list sanitiser. `<armdesk-messenger>` / `<armdesk-launcher>` are the exception on
411
+ purpose: they open the full iframe embed in the messenger panel. Elements emit `armdesk-ticket-select`, `armdesk-ticket-created` and
412
+ `armdesk-ticket-replied` events (bubbling, composed), take a `theme` attribute (JSON), and a `client` property when you do
413
+ not want the global one.
414
+
415
+ ## Your docs in the AI answers
416
+
417
+ The messenger's **Help** tab answers questions with AI, citing its sources: the desk's knowledge base and, if you add
418
+ them, **your own documentation**. Pages from your docs are crawled by ARM Desk and used **only for your organisation's
419
+ users**: never for another organisation and never for the desk's own staff answers. An admin can manage them in ARM Desk
420
+ (Admin > Developer > Connect > your organization > Knowledge), or your backend can manage them server to server with
421
+ the organisation's key and secret (HTTP Basic `orgKey:orgSecret`, like `POST /connect/v1/sessions`). Keep this on your
422
+ server: it uses the secret.
423
+
424
+ | Method | Path | Body / notes |
425
+ |---|---|---|
426
+ | `GET` | `/connect/v1/knowledge/sources` | your sources (status, pages, last / next crawl) |
427
+ | `POST` | `/connect/v1/knowledge/sources` | `{ name, startUrls[], allowedDomains[], maxDepth (0-5), maxPages (1-500), refreshHours }`; at most **5** sources |
428
+ | `PATCH` | `/connect/v1/knowledge/sources/:id` | any of the fields above |
429
+ | `DELETE` | `/connect/v1/knowledge/sources/:id` | removes the source and its pages |
430
+ | `POST` | `/connect/v1/knowledge/sources/:id/crawl` | crawl now |
431
+
432
+ ```bash
433
+ curl -u "$ARMDESK_ORG_KEY:$ARMDESK_ORG_SECRET" \
434
+ -H "Content-Type: application/json" \
435
+ -X POST "https://<your-desk>/api/proxy/connect/v1/knowledge/sources" \
436
+ -d '{"name":"Product docs","startUrls":["https://docs.example.com/"],"allowedDomains":["docs.example.com"],"maxDepth":2,"maxPages":200,"refreshHours":24}'
437
+ ```
438
+
439
+ Your docs appear in Help search and AI answers while the desk's AI knowledge assistant is on and the organisation's
440
+ `aiAnswers` feature is on (Help search itself needs `helpCenter`). Only public pages on the allowed domains are fetched
441
+ (robots.txt is honoured). Requests are rate-limited and audited.
442
+ The admin decides whether the AI may also use the workspace's shared sources for your users (Messenger settings).
443
+
444
+ ## Server helpers
445
+
446
+ `@armdesk/connect-sdk/server`: `signUserToken(options)`, `createConnectHandler(options)` (`.express()`, `.next()`,
447
+ `.fetch(req)`, `.node(req, res)`), `createConnectSession(options)` (server-to-server, orgKey + orgSecret, returns a
448
+ connect token), `deriveAssertionKey(secret)`.
449
+
450
+ ## Theme keys
451
+
452
+ All optional; the desk validates them again. Colours are `#rrggbb`. Anything invalid is ignored. They become CSS
453
+ variables (`--ad-primary`, `--ad-bg`, ...) in the web components and style the iframe embed.
454
+
455
+ | Key | Values |
456
+ |---|---|
457
+ | `primaryColor` | Buttons, links, highlights. |
458
+ | `backgroundColor`, `surfaceColor`, `textColor`, `mutedColor`, `borderColor` | Page, cards, text, secondary text, dividers. |
459
+ | `fontFamily` | `system` \| `inter` \| `roboto` \| `open-sans` \| `lato` |
460
+ | `radius` | 0 to 24 (px). |
461
+ | `density` | `comfortable` \| `compact` |
462
+ | `logoUrl`, `showHeader`, `headerTitle` | Header of the embed (https logo, up to 80 characters). |
463
+ | `mode` | `light` \| `dark` \| `auto` (follows the visitor's system) |
464
+
465
+ Features (can only narrow what the organisation allows): `newTicket`, `attachments`, `catalog`, `orgTickets`, `replies`,
466
+ `closeTicket`, and since 1.1 `chat`, `helpCenter`, `aiAnswers`.
467
+
468
+ ## Errors
469
+
470
+ Every failure is an `ArmDeskError` with `code`, `status`, `message`:
471
+
472
+ | code | When |
473
+ |---|---|
474
+ | `unauthorized` | 401: the session could not be established |
475
+ | `forbidden` | 403: feature off, origin not allowed |
476
+ | `not_found`, `conflict`, `validation` | 404, 409, 400 / 422 |
477
+ | `rate_limited`, `server` | 429, 5xx after the retries |
478
+ | `network` | the desk could not be reached |
479
+ | `invalid_grant`, `invalid_request`, `unauthorized_client` | the token exchange refused the signed user token (expired, replayed, wrong key ...) |
480
+ | `config` | wrong library options |
481
+
482
+ ## Security notes
483
+
484
+ - **The secret stays on your server.** It is only used by `signUserToken` / `createConnectHandler` /
485
+ `createConnectSession`. Never put it in a page, an app bundle or a repository. Rotate it in ARM Desk (the previous one
486
+ keeps working for 24 hours).
487
+ - Keep user tokens short-lived (default 5 minutes, hard maximum 10). Each carries a random `jti` and works once.
488
+ - Serve everything over HTTPS. The library refuses a non-https desk except localhost.
489
+ - The ARM Desk session token (15 minutes) is kept in memory, sent as a Bearer header or by postMessage to the desk's exact
490
+ origin, and never put in a URL, cookie or storage.
491
+ - ARM Desk lets only the organisation's **allowed origins** frame the embed and call the API from a browser.
492
+ - Users only see their own tickets (and their organisation's when enabled), never internal notes.
493
+ - Theme values are validated and become CSS variables; no host CSS or HTML is injected. Your Content-Security-Policy must
494
+ allow the desk in `frame-src` and `connect-src` (and `script-src` for the script tag).
495
+
496
+ ## Embed protocol
497
+
498
+ Only for custom hosts of the iframe. The URL is `<desk>/embed/itsm?org=<orgKey>&view=<view>&locale=<locale>`. Messages are
499
+ `{ source: "armdesk-connect", type, payload }`; both sides check `event.origin` and the sender window.
500
+
501
+ | Direction | type | payload |
502
+ |---|---|---|
503
+ | frame to host | `ready` | none (sent first) |
504
+ | host to frame | `init` | `{ token, theme, features, host? }` (`host: "messenger"` inside the messenger panel) |
505
+ | frame to host | `request-token` | none |
506
+ | host to frame | `token` / `navigate` / `theme` | `{ token }` / `{ view }` / `{ theme }` |
507
+ | host to frame | `open` (1.1) | `{ view? }`: the messenger panel became visible |
508
+ | frame to host | `resize` / `event` / `error` | `{ height }` / `{ name, data }` / `{ code, message }` |
509
+ | frame to host | `unread` (1.1) / `close` (1.1) | `{ count }` (badge) / none (the user closed the panel from inside) |
510
+
511
+ Views: `tickets`, `new`, `ticket:<id>`, and since 1.1 `home`, `messages`, `help`, `chat:<conversationId>`,
512
+ `article:<id>` (ids: 1 to 64 of `A-Z a-z 0-9 _ -`).
513
+
514
+ ## Legacy
515
+
516
+ `ArmDeskConnect.mount(el, { baseUrl, orgKey, getToken })` and `<ArmDeskEmbed baseUrl orgKey getToken />` still work
517
+ (deprecated; use `init(...)` and `client.mount(el)`). `getToken` returns an ARM Desk connect token from your own backend
518
+ (`createConnectSession`).
519
+
520
+ ## Examples and release
521
+
522
+ `examples/wso2-browser.html` (script tag + a mock IdP, nothing to install), `examples/express-server/` (server mode),
523
+ `examples/react-vite/` (React). None is wired into Docker. `pnpm --filter @armdesk/connect-sdk build` enforces the size
524
+ budget (IIFE at most 25 kB gzipped) and publishes the script to the web app; `pnpm --filter @armdesk/connect-sdk
525
+ release` writes the npm tarball to `release/` (see CHANGELOG.md).