@armdesk/connect-sdk 0.0.0-stage → 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 +22 -0
- package/LICENSE.txt +15 -0
- package/README.md +403 -3
- package/dist/armdesk-connect.js +23 -0
- package/dist/esm/browser.d.ts +3 -0
- package/dist/esm/browser.js +18 -0
- package/dist/esm/client.d.ts +44 -0
- package/dist/esm/client.js +298 -0
- package/dist/esm/defaults.d.ts +8 -0
- package/dist/esm/defaults.js +22 -0
- package/dist/esm/elements.d.ts +3 -0
- package/dist/esm/elements.js +307 -0
- package/dist/esm/errors.d.ts +12 -0
- package/dist/esm/errors.js +34 -0
- package/dist/esm/handler.d.ts +40 -0
- package/dist/esm/handler.js +106 -0
- package/dist/esm/http.d.ts +22 -0
- package/dist/esm/http.js +66 -0
- package/dist/esm/index.d.ts +18 -0
- package/dist/esm/index.js +15 -0
- package/dist/esm/mount.d.ts +8 -0
- package/dist/esm/mount.js +170 -0
- package/dist/esm/protocol.d.ts +18 -0
- package/dist/esm/protocol.js +31 -0
- package/dist/esm/react.d.ts +61 -0
- package/dist/esm/react.js +199 -0
- package/dist/esm/register.d.ts +1 -0
- package/dist/esm/register.js +5 -0
- package/dist/esm/sanitize.d.ts +8 -0
- package/dist/esm/sanitize.js +57 -0
- package/dist/esm/server.d.ts +17 -0
- package/dist/esm/server.js +93 -0
- package/dist/esm/sign.d.ts +54 -0
- package/dist/esm/sign.js +77 -0
- package/dist/esm/theme.d.ts +8 -0
- package/dist/esm/theme.js +46 -0
- package/dist/esm/types.d.ts +298 -0
- package/dist/esm/types.js +1 -0
- package/examples/express-server/package.json +10 -0
- package/examples/express-server/server.mjs +35 -0
- package/examples/mock-idp.mjs +30 -0
- package/examples/react-vite/index.html +11 -0
- package/examples/react-vite/package.json +15 -0
- package/examples/react-vite/src/main.jsx +25 -0
- package/examples/react-vite/vite.config.js +4 -0
- package/examples/wso2-browser.html +86 -0
- package/package.json +59 -4
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { createContext, createElement, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
|
|
3
|
+
import { createClient } from "./client.js";
|
|
4
|
+
import { setCurrentClient } from "./defaults.js";
|
|
5
|
+
import { mount } from "./mount.js";
|
|
6
|
+
import { sanitizeHtml } from "./sanitize.js";
|
|
7
|
+
import { themeVars } from "./theme.js";
|
|
8
|
+
const Ctx = createContext(null);
|
|
9
|
+
/** `<ArmDeskProvider orgKey auth desk>`: one client for the subtree. `auth` callbacks may change every render. */
|
|
10
|
+
export function ArmDeskProvider({ orgKey, auth, desk, theme, client, children }) {
|
|
11
|
+
const latestAuth = useRef(auth);
|
|
12
|
+
latestAuth.current = auth;
|
|
13
|
+
const kind = Object.keys(auth)[0];
|
|
14
|
+
const sessionUrl = "sessionUrl" in auth ? auth.sessionUrl : undefined;
|
|
15
|
+
const made = useMemo(() => {
|
|
16
|
+
if (client)
|
|
17
|
+
return client;
|
|
18
|
+
// stable wrappers: the latest callback is always used and the client is not rebuilt per render
|
|
19
|
+
const stable = { ...latestAuth.current };
|
|
20
|
+
for (const k of ["userToken", "idToken", "getToken"]) {
|
|
21
|
+
if (typeof stable[k] === "function")
|
|
22
|
+
stable[k] = () => latestAuth.current[k]();
|
|
23
|
+
}
|
|
24
|
+
return createClient({ orgKey, desk, auth: stable, theme });
|
|
25
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
26
|
+
}, [client, orgKey, desk, kind, sessionUrl]);
|
|
27
|
+
useEffect(() => {
|
|
28
|
+
setCurrentClient(made);
|
|
29
|
+
return () => made.signOut();
|
|
30
|
+
}, [made]);
|
|
31
|
+
return createElement(Ctx.Provider, { value: made }, children);
|
|
32
|
+
}
|
|
33
|
+
/** The client of the nearest provider. */
|
|
34
|
+
export function useArmDesk() {
|
|
35
|
+
const c = useContext(Ctx);
|
|
36
|
+
if (!c)
|
|
37
|
+
throw new Error("useArmDesk must be used inside <ArmDeskProvider>");
|
|
38
|
+
return c;
|
|
39
|
+
}
|
|
40
|
+
function useLoad(load, deps, events) {
|
|
41
|
+
const client = useArmDesk();
|
|
42
|
+
const [state, setState] = useState({ data: null, loading: true, error: null });
|
|
43
|
+
const [tick, setTick] = useState(0);
|
|
44
|
+
const refetch = useCallback(() => setTick((t) => t + 1), []);
|
|
45
|
+
useEffect(() => {
|
|
46
|
+
let live = true;
|
|
47
|
+
setState((s) => ({ ...s, loading: true, error: null }));
|
|
48
|
+
load(client).then((data) => live && setState({ data, loading: false, error: null }), (error) => live && setState((s) => ({ ...s, loading: false, error })));
|
|
49
|
+
return () => {
|
|
50
|
+
live = false;
|
|
51
|
+
};
|
|
52
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
53
|
+
}, [client, tick, ...deps]);
|
|
54
|
+
useEffect(() => {
|
|
55
|
+
const offs = events.map((e) => client.on(e, () => refetch()));
|
|
56
|
+
return () => offs.forEach((f) => f());
|
|
57
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
58
|
+
}, [client, refetch]);
|
|
59
|
+
return { ...state, refetch };
|
|
60
|
+
}
|
|
61
|
+
/** `const { data, loading, error, refetch } = useTickets({ status: "OPEN", page: 1 })`; refetches on ticket events. */
|
|
62
|
+
export function useTickets(params = {}) {
|
|
63
|
+
const status = Array.isArray(params.status) ? params.status.join(",") : params.status;
|
|
64
|
+
return useLoad((c) => c.tickets.list(params), [status, params.search, params.page, params.limit], ["ticket.created", "ticket.replied"]);
|
|
65
|
+
}
|
|
66
|
+
export function useTicket(id) {
|
|
67
|
+
return useLoad((c) => (id ? c.tickets.get(id) : Promise.reject(new Error("No ticket id"))), [id], ["ticket.replied"]);
|
|
68
|
+
}
|
|
69
|
+
export function useCreateTicket() {
|
|
70
|
+
const client = useArmDesk();
|
|
71
|
+
const [state, setState] = useState({ loading: false, error: null, ticket: null });
|
|
72
|
+
const create = useCallback(async (input) => {
|
|
73
|
+
setState({ loading: true, error: null, ticket: null });
|
|
74
|
+
try {
|
|
75
|
+
const ticket = await client.tickets.create(input);
|
|
76
|
+
setState({ loading: false, error: null, ticket });
|
|
77
|
+
return ticket;
|
|
78
|
+
}
|
|
79
|
+
catch (e) {
|
|
80
|
+
setState({ loading: false, error: e, ticket: null });
|
|
81
|
+
throw e;
|
|
82
|
+
}
|
|
83
|
+
}, [client]);
|
|
84
|
+
return { create, ...state };
|
|
85
|
+
}
|
|
86
|
+
// ---- components -----------------------------------------------------------
|
|
87
|
+
function useThemeStyle() {
|
|
88
|
+
const client = useArmDesk();
|
|
89
|
+
const [theme, setTheme] = useState();
|
|
90
|
+
useEffect(() => {
|
|
91
|
+
let live = true;
|
|
92
|
+
client.config().then((c) => live && setTheme(c.theme), () => undefined);
|
|
93
|
+
return () => {
|
|
94
|
+
live = false;
|
|
95
|
+
};
|
|
96
|
+
}, [client]);
|
|
97
|
+
return themeVars(theme);
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* `<ArmDeskEmbed view="tickets" />` inside a provider mounts the full portal in an iframe. The legacy form
|
|
101
|
+
* `<ArmDeskEmbed baseUrl orgKey getToken />` (no provider) still works.
|
|
102
|
+
*/
|
|
103
|
+
export function ArmDeskEmbed(props) {
|
|
104
|
+
var _a;
|
|
105
|
+
const provided = useContext(Ctx);
|
|
106
|
+
const ref = useRef(null);
|
|
107
|
+
const handle = useRef(null);
|
|
108
|
+
const latest = useRef(props);
|
|
109
|
+
latest.current = props;
|
|
110
|
+
const legacy = "getToken" in props && typeof props.getToken === "function";
|
|
111
|
+
const key = legacy ? `${props.baseUrl}|${props.orgKey}` : "client";
|
|
112
|
+
useEffect(() => {
|
|
113
|
+
if (!ref.current)
|
|
114
|
+
return;
|
|
115
|
+
const p = latest.current;
|
|
116
|
+
const common = {
|
|
117
|
+
onEvent: (e) => { var _a, _b; return (_b = (_a = latest.current).onEvent) === null || _b === void 0 ? void 0 : _b.call(_a, e); },
|
|
118
|
+
onError: (e) => { var _a, _b; return (_b = (_a = latest.current).onError) === null || _b === void 0 ? void 0 : _b.call(_a, e); },
|
|
119
|
+
};
|
|
120
|
+
if (legacy) {
|
|
121
|
+
handle.current = mount(ref.current, { ...p, ...common, getToken: () => latest.current.getToken() });
|
|
122
|
+
}
|
|
123
|
+
else {
|
|
124
|
+
if (!provided)
|
|
125
|
+
throw new Error("<ArmDeskEmbed> needs <ArmDeskProvider> (or the legacy baseUrl / orgKey / getToken props)");
|
|
126
|
+
handle.current = provided.mount(ref.current, { view: p.view, theme: p.theme, features: p.features, locale: p.locale, height: p.height, ...common });
|
|
127
|
+
}
|
|
128
|
+
return () => {
|
|
129
|
+
var _a;
|
|
130
|
+
(_a = handle.current) === null || _a === void 0 ? void 0 : _a.destroy();
|
|
131
|
+
handle.current = null;
|
|
132
|
+
};
|
|
133
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
134
|
+
}, [key, provided, props.locale, props.height]);
|
|
135
|
+
const themeKey = JSON.stringify((_a = props.theme) !== null && _a !== void 0 ? _a : null);
|
|
136
|
+
useEffect(() => {
|
|
137
|
+
var _a;
|
|
138
|
+
if (props.theme)
|
|
139
|
+
(_a = handle.current) === null || _a === void 0 ? void 0 : _a.setTheme(props.theme);
|
|
140
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
141
|
+
}, [themeKey]);
|
|
142
|
+
useEffect(() => {
|
|
143
|
+
var _a;
|
|
144
|
+
if (props.view)
|
|
145
|
+
(_a = handle.current) === null || _a === void 0 ? void 0 : _a.navigate(props.view);
|
|
146
|
+
}, [props.view]);
|
|
147
|
+
return createElement("div", { ref, className: props.className });
|
|
148
|
+
}
|
|
149
|
+
const cardStyle = { border: "1px solid var(--ad-border, #e5e7eb)", borderRadius: "var(--ad-radius, 8px)", padding: "10px 14px", marginBottom: 8 };
|
|
150
|
+
/** A ticket list. `onSelect` receives the ticket id (open your own route, or render <ArmDeskTicket />). */
|
|
151
|
+
export function ArmDeskTickets({ onSelect, status, limit = 10, className }) {
|
|
152
|
+
const [page, setPage] = useState(1);
|
|
153
|
+
const { data, loading, error, refetch } = useTickets({ status, page, limit });
|
|
154
|
+
const style = useThemeStyle();
|
|
155
|
+
const pages = data ? Math.max(1, Math.ceil(data.total / limit)) : 1;
|
|
156
|
+
return (_jsxs("div", { className: className, style: style, children: [_jsx("h3", { children: "My tickets" }), loading && !data ? _jsx("p", { children: "Loading..." }) : null, error ? _jsxs("p", { role: "alert", children: [error.message, " ", _jsx("button", { onClick: refetch, children: "Try again" })] }) : null, data && data.items.length === 0 ? _jsx("p", { children: "No tickets yet." }) : null, data === null || data === void 0 ? void 0 : data.items.map((t) => (_jsxs("button", { type: "button", style: { ...cardStyle, display: "block", width: "100%", textAlign: "left", cursor: "pointer" }, onClick: () => onSelect === null || onSelect === void 0 ? void 0 : onSelect(t.id), children: [_jsx("strong", { children: t.number }), " ", t.subject, " ", _jsxs("small", { children: ["(", t.status, ")"] })] }, t.id))), _jsxs("div", { children: [_jsx("button", { type: "button", disabled: page <= 1, onClick: () => setPage(page - 1), children: "Previous" }), _jsxs("span", { children: [" ", page, " / ", pages, " "] }), _jsx("button", { type: "button", disabled: page >= pages, onClick: () => setPage(page + 1), children: "Next" })] })] }));
|
|
157
|
+
}
|
|
158
|
+
/** One ticket: conversation (sanitised), reply box, mark as solved. */
|
|
159
|
+
export function ArmDeskTicket({ ticketId, className }) {
|
|
160
|
+
var _a;
|
|
161
|
+
const client = useArmDesk();
|
|
162
|
+
const { data, loading, error, refetch } = useTicket(ticketId);
|
|
163
|
+
const [text, setText] = useState("");
|
|
164
|
+
const [busy, setBusy] = useState(false);
|
|
165
|
+
const style = useThemeStyle();
|
|
166
|
+
const send = async (e) => {
|
|
167
|
+
e.preventDefault();
|
|
168
|
+
setBusy(true);
|
|
169
|
+
try {
|
|
170
|
+
await client.tickets.reply(ticketId, { body: text });
|
|
171
|
+
setText("");
|
|
172
|
+
}
|
|
173
|
+
finally {
|
|
174
|
+
setBusy(false);
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
if (loading && !data)
|
|
178
|
+
return _jsx("p", { children: "Loading..." });
|
|
179
|
+
if (error || !data)
|
|
180
|
+
return _jsx("p", { role: "alert", children: (_a = error === null || error === void 0 ? void 0 : error.message) !== null && _a !== void 0 ? _a : "Not found" });
|
|
181
|
+
return (_jsxs("div", { className: className, style: style, children: [_jsxs("h3", { children: [data.number, " ", data.subject, " ", _jsxs("small", { children: ["(", data.status, ")"] })] }), data.threads.map((t) => (_jsxs("div", { style: cardStyle, children: [_jsxs("small", { children: [t.author.name, " - ", new Date(t.createdAt).toLocaleString()] }), _jsx("div", { dangerouslySetInnerHTML: { __html: sanitizeHtml(t.body) } })] }, t.id))), data.canReply ? (_jsxs("form", { onSubmit: send, children: [_jsx("textarea", { "aria-label": "Reply", value: text, onChange: (e) => setText(e.target.value), required: true, rows: 4, style: { width: "100%" } }), _jsx("button", { type: "submit", disabled: busy || !text.trim(), children: "Send reply" })] })) : null, data.canClose ? _jsx("button", { type: "button", onClick: () => void client.tickets.close(ticketId).then(refetch), children: "Mark as solved" }) : null] }));
|
|
182
|
+
}
|
|
183
|
+
/** The new-ticket form. */
|
|
184
|
+
export function ArmDeskNewTicket({ onCreated, className }) {
|
|
185
|
+
const { create, loading, error } = useCreateTicket();
|
|
186
|
+
const [subject, setSubject] = useState("");
|
|
187
|
+
const [description, setDescription] = useState("");
|
|
188
|
+
const style = useThemeStyle();
|
|
189
|
+
const submit = async (e) => {
|
|
190
|
+
e.preventDefault();
|
|
191
|
+
const t = await create({ subject, description }).catch(() => null);
|
|
192
|
+
if (t) {
|
|
193
|
+
setSubject("");
|
|
194
|
+
setDescription("");
|
|
195
|
+
onCreated === null || onCreated === void 0 ? void 0 : onCreated(t);
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
return (_jsxs("form", { className: className, style: style, onSubmit: submit, children: [_jsx("h3", { children: "New ticket" }), _jsxs("label", { children: ["Subject ", _jsx("input", { value: subject, onChange: (e) => setSubject(e.target.value), required: true, minLength: 5, maxLength: 255, style: { width: "100%" } })] }), _jsxs("label", { children: ["Description ", _jsx("textarea", { value: description, onChange: (e) => setDescription(e.target.value), required: true, minLength: 10, maxLength: 20000, rows: 6, style: { width: "100%" } })] }), _jsx("button", { type: "submit", disabled: loading, children: "Submit ticket" }), error ? _jsx("p", { role: "alert", children: error.message }) : null] }));
|
|
199
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { defineElements, ELEMENT_TAGS } from "./elements.js";
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// `@armdesk/connect-sdk/elements`: importing it registers <armdesk-tickets>, <armdesk-new-ticket>,
|
|
2
|
+
// <armdesk-ticket ticket-id> and <armdesk-launcher>.
|
|
3
|
+
import { defineElements } from "./elements.js";
|
|
4
|
+
defineElements();
|
|
5
|
+
export { defineElements, ELEMENT_TAGS } from "./elements.js";
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Allow-list sanitiser for the (already server-sanitised) thread HTML: a small set of text tags, no attributes
|
|
3
|
+
* except a safe `href`, no scripts, styles, event handlers, images or frames. Returns a DocumentFragment-free
|
|
4
|
+
* HTML string built from DOM nodes, so it never re-parses attacker markup.
|
|
5
|
+
*/
|
|
6
|
+
export declare function sanitizeHtml(html: string): string;
|
|
7
|
+
/** Fills `el` with sanitised HTML using DOM nodes only. */
|
|
8
|
+
export declare function setSafeHtml(el: HTMLElement, html: string): void;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
const ALLOWED = new Set(["p", "br", "b", "strong", "i", "em", "u", "s", "ul", "ol", "li", "a", "code", "pre", "blockquote", "span", "div", "h1", "h2", "h3", "h4", "h5", "h6", "hr"]);
|
|
2
|
+
const DROP_WITH_CONTENT = new Set(["script", "style", "iframe", "object", "embed", "template", "noscript", "svg", "math", "form", "textarea", "select", "head", "title"]);
|
|
3
|
+
function safeHref(value) {
|
|
4
|
+
const v = value.trim();
|
|
5
|
+
if (/^(https?:|mailto:)/i.test(v))
|
|
6
|
+
return v;
|
|
7
|
+
return null;
|
|
8
|
+
}
|
|
9
|
+
function clean(node, out, doc) {
|
|
10
|
+
node.childNodes.forEach((child) => {
|
|
11
|
+
var _a, _b;
|
|
12
|
+
if (child.nodeType === 3) {
|
|
13
|
+
out.appendChild(doc.createTextNode((_a = child.textContent) !== null && _a !== void 0 ? _a : ""));
|
|
14
|
+
return;
|
|
15
|
+
}
|
|
16
|
+
if (child.nodeType !== 1)
|
|
17
|
+
return;
|
|
18
|
+
const el = child;
|
|
19
|
+
const tag = el.tagName.toLowerCase();
|
|
20
|
+
if (DROP_WITH_CONTENT.has(tag))
|
|
21
|
+
return;
|
|
22
|
+
if (!ALLOWED.has(tag)) {
|
|
23
|
+
clean(el, out, doc); // unknown tag: keep its text, drop the tag
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
const copy = doc.createElement(tag);
|
|
27
|
+
if (tag === "a") {
|
|
28
|
+
const href = safeHref((_b = el.getAttribute("href")) !== null && _b !== void 0 ? _b : "");
|
|
29
|
+
if (href) {
|
|
30
|
+
copy.setAttribute("href", href);
|
|
31
|
+
copy.setAttribute("target", "_blank");
|
|
32
|
+
copy.setAttribute("rel", "noopener noreferrer nofollow");
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
clean(el, copy, doc);
|
|
36
|
+
out.appendChild(copy);
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Allow-list sanitiser for the (already server-sanitised) thread HTML: a small set of text tags, no attributes
|
|
41
|
+
* except a safe `href`, no scripts, styles, event handlers, images or frames. Returns a DocumentFragment-free
|
|
42
|
+
* HTML string built from DOM nodes, so it never re-parses attacker markup.
|
|
43
|
+
*/
|
|
44
|
+
export function sanitizeHtml(html) {
|
|
45
|
+
if (typeof DOMParser === "undefined")
|
|
46
|
+
return html.replace(/<[^>]*>/g, "");
|
|
47
|
+
const parsed = new DOMParser().parseFromString(html, "text/html");
|
|
48
|
+
const wrap = parsed.createElement("div");
|
|
49
|
+
clean(parsed.body, wrap, parsed);
|
|
50
|
+
return wrap.innerHTML;
|
|
51
|
+
}
|
|
52
|
+
/** Fills `el` with sanitised HTML using DOM nodes only. */
|
|
53
|
+
export function setSafeHtml(el, html) {
|
|
54
|
+
const tpl = el.ownerDocument.createElement("div");
|
|
55
|
+
tpl.innerHTML = sanitizeHtml(html);
|
|
56
|
+
el.replaceChildren(...Array.from(tpl.childNodes));
|
|
57
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { ConnectSession, CreateConnectSessionOptions } from "./types.js";
|
|
2
|
+
export * from "./sign.js";
|
|
3
|
+
export * from "./handler.js";
|
|
4
|
+
export type { ConnectSession, ConnectUser, CreateConnectSessionOptions } from "./types.js";
|
|
5
|
+
export type ConnectErrorCode = "invalid_credentials" | "forbidden" | "conflict" | "validation" | "rate_limited" | "server" | "network" | "bad_response";
|
|
6
|
+
/** Thrown by createConnectSession. `status` is the HTTP status (0 when none). */
|
|
7
|
+
export declare class ConnectError extends Error {
|
|
8
|
+
readonly code: ConnectErrorCode;
|
|
9
|
+
readonly status: number;
|
|
10
|
+
constructor(code: ConnectErrorCode, message: string, status?: number);
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Server-to-server: exchange the organisation's credentials and a signed-in
|
|
14
|
+
* user (or their OIDC ID token) for a short-lived connect token. Call this
|
|
15
|
+
* from YOUR backend only - orgSecret must never reach a browser.
|
|
16
|
+
*/
|
|
17
|
+
export declare function createConnectSession(options: CreateConnectSessionOptions): Promise<ConnectSession>;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
export * from "./sign.js";
|
|
2
|
+
export * from "./handler.js";
|
|
3
|
+
/** Thrown by createConnectSession. `status` is the HTTP status (0 when none). */
|
|
4
|
+
export class ConnectError extends Error {
|
|
5
|
+
constructor(code, message, status = 0) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.name = "ConnectError";
|
|
8
|
+
this.code = code;
|
|
9
|
+
this.status = status;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
function codeFor(status) {
|
|
13
|
+
if (status === 401)
|
|
14
|
+
return "invalid_credentials";
|
|
15
|
+
if (status === 403)
|
|
16
|
+
return "forbidden";
|
|
17
|
+
if (status === 409)
|
|
18
|
+
return "conflict";
|
|
19
|
+
if (status === 429)
|
|
20
|
+
return "rate_limited";
|
|
21
|
+
if (status >= 500)
|
|
22
|
+
return "server";
|
|
23
|
+
return "validation";
|
|
24
|
+
}
|
|
25
|
+
function basicAuth(key, secret) {
|
|
26
|
+
// orgKey / orgSecret are ASCII (org_ / cos_ + alphanumerics); btoa is global in Node 16+.
|
|
27
|
+
return `Basic ${btoa(`${key}:${secret}`)}`;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Server-to-server: exchange the organisation's credentials and a signed-in
|
|
31
|
+
* user (or their OIDC ID token) for a short-lived connect token. Call this
|
|
32
|
+
* from YOUR backend only - orgSecret must never reach a browser.
|
|
33
|
+
*/
|
|
34
|
+
export async function createConnectSession(options) {
|
|
35
|
+
var _a, _b;
|
|
36
|
+
const { baseUrl, apiUrl, tenantSlug, orgKey, orgSecret, user, idToken, features, timeoutMs = 10000 } = options;
|
|
37
|
+
if (!baseUrl || !orgKey || !orgSecret)
|
|
38
|
+
throw new ConnectError("validation", "baseUrl, orgKey and orgSecret are required");
|
|
39
|
+
if (!user && !idToken)
|
|
40
|
+
throw new ConnectError("validation", "Pass user or idToken");
|
|
41
|
+
const doFetch = (_a = options.fetch) !== null && _a !== void 0 ? _a : globalThis.fetch;
|
|
42
|
+
if (typeof doFetch !== "function")
|
|
43
|
+
throw new ConnectError("network", "fetch is not available (Node 18+ required)");
|
|
44
|
+
// The desk's web app forwards /api/proxy/* to its API; pass apiUrl to call the API directly.
|
|
45
|
+
const api = apiUrl ? apiUrl.replace(/\/+$/, "") : `${baseUrl.replace(/\/+$/, "")}/api/proxy`;
|
|
46
|
+
const url = `${api}/connect/v1/sessions`;
|
|
47
|
+
const body = {};
|
|
48
|
+
if (user)
|
|
49
|
+
body.user = user;
|
|
50
|
+
if (idToken)
|
|
51
|
+
body.idToken = idToken;
|
|
52
|
+
if (features)
|
|
53
|
+
body.features = features;
|
|
54
|
+
const controller = new AbortController();
|
|
55
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
56
|
+
let res;
|
|
57
|
+
try {
|
|
58
|
+
res = await doFetch(url, {
|
|
59
|
+
method: "POST",
|
|
60
|
+
headers: {
|
|
61
|
+
"Content-Type": "application/json",
|
|
62
|
+
Accept: "application/json",
|
|
63
|
+
Authorization: basicAuth(orgKey, orgSecret),
|
|
64
|
+
...(tenantSlug ? { "X-Tenant-Slug": tenantSlug } : {}),
|
|
65
|
+
},
|
|
66
|
+
body: JSON.stringify(body),
|
|
67
|
+
signal: controller.signal,
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
catch (err) {
|
|
71
|
+
throw new ConnectError("network", err instanceof Error ? `Could not reach ARM Desk: ${err.message}` : "Could not reach ARM Desk");
|
|
72
|
+
}
|
|
73
|
+
finally {
|
|
74
|
+
clearTimeout(timer);
|
|
75
|
+
}
|
|
76
|
+
let json = null;
|
|
77
|
+
try {
|
|
78
|
+
json = await res.json();
|
|
79
|
+
}
|
|
80
|
+
catch (_c) {
|
|
81
|
+
// non-JSON body - handled below
|
|
82
|
+
}
|
|
83
|
+
if (!res.ok) {
|
|
84
|
+
const msg = json === null || json === void 0 ? void 0 : json.message;
|
|
85
|
+
const text = Array.isArray(msg) ? msg.join("; ") : typeof msg === "string" ? msg : `ARM Desk answered ${res.status}`;
|
|
86
|
+
throw new ConnectError(codeFor(res.status), text, res.status);
|
|
87
|
+
}
|
|
88
|
+
const s = json;
|
|
89
|
+
if (!s || typeof s.token !== "string" || typeof s.expiresIn !== "number" || !s.user) {
|
|
90
|
+
throw new ConnectError("bad_response", "ARM Desk returned an unexpected session response", res.status);
|
|
91
|
+
}
|
|
92
|
+
return { token: s.token, expiresIn: s.expiresIn, user: s.user, contactId: (_b = s.contactId) !== null && _b !== void 0 ? _b : null };
|
|
93
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { type KeyObject } from "node:crypto";
|
|
2
|
+
/** The user as your system knows them. `id` is your stable user id (WSO2 `sub`, a database key ...). */
|
|
3
|
+
export interface SignedUser {
|
|
4
|
+
id?: string;
|
|
5
|
+
/** Alias of `id`. */
|
|
6
|
+
uid?: string;
|
|
7
|
+
email?: string;
|
|
8
|
+
name?: string;
|
|
9
|
+
firstName?: string;
|
|
10
|
+
lastName?: string;
|
|
11
|
+
phone?: string;
|
|
12
|
+
/** Your role name; the organisation's role mappings turn it into a CRM contact role. */
|
|
13
|
+
role?: string;
|
|
14
|
+
department?: string;
|
|
15
|
+
/** Free-form extras (<= 4 KB as JSON). */
|
|
16
|
+
attributes?: Record<string, unknown>;
|
|
17
|
+
/** You vouch the e-mail is verified (default: not stated). false = never link an existing account by it. */
|
|
18
|
+
emailVerified?: boolean;
|
|
19
|
+
}
|
|
20
|
+
interface SignBase {
|
|
21
|
+
orgKey: string;
|
|
22
|
+
user: SignedUser;
|
|
23
|
+
/** Lifetime in seconds. Default 300, at most 600. */
|
|
24
|
+
expiresIn?: number;
|
|
25
|
+
/** Test seam: the current time in ms. */
|
|
26
|
+
now?: number;
|
|
27
|
+
}
|
|
28
|
+
export interface SignHmacOptions extends SignBase {
|
|
29
|
+
/** The organisation secret (cos_...). Never leaves your server. */
|
|
30
|
+
orgSecret: string;
|
|
31
|
+
/** The secret's version, taken from the key id ARM Desk shows next to it. Default 1; bump it after a rotation. */
|
|
32
|
+
secretVersion?: number | string;
|
|
33
|
+
privateKey?: undefined;
|
|
34
|
+
}
|
|
35
|
+
export interface SignAsymmetricOptions extends SignBase {
|
|
36
|
+
/** PEM (PKCS8 / PKCS1 / SEC1) or a KeyObject: the private half of the key registered for the organisation. */
|
|
37
|
+
privateKey: string | KeyObject;
|
|
38
|
+
/** The key id registered with ARM Desk. */
|
|
39
|
+
kid: string;
|
|
40
|
+
alg?: "RS256" | "ES256";
|
|
41
|
+
orgSecret?: undefined;
|
|
42
|
+
}
|
|
43
|
+
export type SignUserTokenOptions = SignHmacOptions | SignAsymmetricOptions;
|
|
44
|
+
export declare const MAX_EXPIRES_IN = 600;
|
|
45
|
+
export declare const DEFAULT_EXPIRES_IN = 300;
|
|
46
|
+
/** HMAC-SHA256(orgSecret, "armdesk-connect-assertion-v1"): the signing key, so the raw secret is never the JWT key. */
|
|
47
|
+
export declare function deriveAssertionKey(orgSecret: string): Buffer;
|
|
48
|
+
/**
|
|
49
|
+
* Mints the signed user token (OAuth 2.0 JWT bearer assertion, RFC 7523) your page hands to the browser library as
|
|
50
|
+
* `auth: { userToken }`. Local: no network call, no endpoint of yours. HS256 with the key derived from the org
|
|
51
|
+
* secret, or RS256 / ES256 with your own registered private key.
|
|
52
|
+
*/
|
|
53
|
+
export declare function signUserToken(options: SignUserTokenOptions): string;
|
|
54
|
+
export {};
|
package/dist/esm/sign.js
ADDED
|
@@ -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
|
+
}
|