@convokitapp/chat-embed 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -25,7 +25,7 @@ from **Dashboard → your app → Chat widget**.
25
25
  | Mode | Needs a backend | Who the visitor is | Use it for |
26
26
  | --- | --- | --- | --- |
27
27
  | `guest` | No | A new anonymous guest, resumed on return visits | Support chat, pre-sales, public sites |
28
- | `uid` | No | Whatever `uid` the page passes; created on first use | Demos, or apps whose chats are not private |
28
+ | `uid` | A hash from your server | The `uid` your server signed; created on first use | Signed-in users, including Shopify and other no-backend-code sites with server templates |
29
29
  | `authToken` | Yes | The user your server verified | Logged-in users with private conversations |
30
30
 
31
31
  ### `guest`
@@ -35,26 +35,56 @@ resume token in `localStorage` (or `sessionStorage` with
35
35
  `storageMode: "SESSION"`), so returning visitors keep their conversation. A
36
36
  guest can never be made to log in as an existing user.
37
37
 
38
+ A resume token expires after 30 days without a visit, and rotating the widget
39
+ key in the dashboard invalidates every token issued before the rotation. Either
40
+ way the visitor starts over as a new guest; rotate the key if you suspect
41
+ resume tokens were copied from visitors' browsers.
42
+
38
43
  ### `uid`
39
44
 
45
+ Your server signs the user ID with the widget's **identity secret** (Dashboard →
46
+ your app → Chat widget) and puts the result in the page as `userHash`. Never put
47
+ the identity secret itself in page code.
48
+
49
+ ```js
50
+ ConvoKitWidget.start({ clientId, mode: "uid", widgetKey, uid: "customer_42", userHash: "<from your server>", user: { name: "Ada" } })
51
+ ```
52
+
53
+ `userHash` is the hex HMAC-SHA256 of the exact `uid` string:
54
+
40
55
  ```js
41
- ConvoKitWidget.start({ clientId, mode: "uid", widgetKey, uid: "customer_42", user: { name: "Ada" } })
56
+ // Node
57
+ crypto.createHmac("sha256", process.env.CONVOKIT_IDENTITY_SECRET).update(uid).digest("hex")
58
+ ```
59
+
60
+ ```php
61
+ // PHP
62
+ hash_hmac('sha256', $uid, getenv('CONVOKIT_IDENTITY_SECRET'));
63
+ ```
64
+
65
+ ```python
66
+ # Python
67
+ hmac.new(secret.encode(), uid.encode(), hashlib.sha256).hexdigest()
42
68
  ```
43
69
 
44
- > **Security:** the widget key is public. With `uid` mode enabled, anyone who
45
- > copies it can log in as **any user ID of the app** and read that user's
46
- > conversations. This matches CometChat's auth-key login. Enable it only for
47
- > demos or apps without private chats, and prefer `authToken` for real
48
- > accounts. It is off by default and is enabled separately from guest mode.
70
+ A missing or wrong hash is refused with `INVALID_USER_HASH`, so copying the
71
+ public widget key is not enough to log in as someone else. Rotating the
72
+ identity secret in the dashboard invalidates every hash signed with the old
73
+ one; rotating the widget key does not change it.
49
74
 
50
- Shopify example (`layout/theme.liquid`), using the customer when signed in:
75
+ Shopify example (`layout/theme.liquid`, rendered on Shopify's servers), using
76
+ the customer when signed in. Store the secret in a theme setting, not in
77
+ JavaScript:
51
78
 
52
79
  ```liquid
53
80
  {% if customer %}
81
+ {% assign convokit_uid = "shopify_" | append: customer.id %}
54
82
  <script>
55
83
  window.addEventListener("load", function () {
56
84
  ConvoKitWidget.start({ clientId: "…", mode: "uid", widgetKey: "…",
57
- uid: "shopify_" + {{ customer.id | json }}, user: { name: {{ customer.first_name | json }} },
85
+ uid: {{ convokit_uid | json }},
86
+ userHash: {{ convokit_uid | hmac_sha256: settings.convokit_identity_secret | json }},
87
+ user: { name: {{ customer.first_name | json }} },
58
88
  startConversationWith: ["support"] });
59
89
  });
60
90
  </script>
@@ -83,6 +113,7 @@ pass `tokenProvider: async (appUserId) => token` instead of `tokenUrl`.
83
113
  | `mode` | — | `"guest"`, `"uid"` or `"authToken"` (required). |
84
114
  | `widgetKey` | — | Publishable key; `guest`/`uid` only. |
85
115
  | `uid`, `user` | — | `uid` mode: the user ID, and `{ name, imageUrl }` applied on creation. |
116
+ | `userHash` | — | `uid` mode, required: hex HMAC-SHA256 of `uid` with the identity secret, made on your server. |
86
117
  | `userId`, `tokenUrl` / `tokenProvider` | — | `authToken` mode. |
87
118
  | `startConversationWith` | `[]` | User IDs to chat with. Opens the existing conversation with exactly those members, or creates it. Without it the widget shows the user's inbox. |
88
119
  | `conversationTitle` | — | Title for a conversation the widget creates. |
@@ -125,9 +156,12 @@ the widget shows the cards your support agent sends:
125
156
  - **The welcome message**, if you set one up, is posted when a visitor opens a
126
157
  new chat: your greeting with up to three options shown as tiles, two per
127
158
  row. Tapping a tile sends that card straight away.
128
- - **"Talk to a person"** appears under the newest link or quick-reply card. It
129
- hands the conversation to your team and pauses automatic replies for 24
130
- hours.
159
+ - **AI answers**, if you turned on the AI agent and added FAQ entries, appear
160
+ as ordinary bubbles labelled "AI answer", so visitors know they are not
161
+ talking to a person.
162
+ - **"Talk to a person"** appears under the newest link, quick-reply card or AI
163
+ answer. It hands the conversation to your team and pauses automatic replies
164
+ for 24 hours.
131
165
  - **Handoff and "submitted" notices** appear as small centred lines, as does
132
166
  the reply sent when nothing matches ("Our support team will get back to
133
167
  you.", or your own wording).
package/dist/index.d.ts CHANGED
@@ -13,6 +13,9 @@ interface WidgetConfig {
13
13
  widgetKey?: string;
14
14
  /** `uid` mode: the user to log in as, created on first use. */
15
15
  uid?: string;
16
+ /** `uid` mode: hex HMAC-SHA256 of `uid` keyed with the widget's identity
17
+ * secret, computed on your server. Never put the secret in page code. */
18
+ userHash?: string;
16
19
  /** Profile applied when the widget creates the user. */
17
20
  user?: WidgetUserProfile;
18
21
  /** `authToken` mode: the signed-in user's ID in your app. */
package/dist/index.js CHANGED
@@ -17,6 +17,8 @@ function resolveConfig(input) {
17
17
  if (mode !== "guest" && mode !== "uid" && mode !== "authToken") fail('mode must be "guest", "uid" or "authToken"');
18
18
  if (mode !== "authToken" && !text(input.widgetKey)) fail(`widgetKey is required in ${mode} mode`);
19
19
  if (mode === "uid" && !text(input.uid)) fail("uid is required in uid mode");
20
+ if (mode === "uid" && !/^[0-9a-f]{64}$/i.test(text(input.userHash))) fail("userHash is required in uid mode: the hex HMAC-SHA256 of uid, signed on your server with the widget identity secret");
21
+ if (mode !== "uid" && input.userHash !== void 0) fail("userHash is only used in uid mode");
20
22
  if (mode === "authToken") {
21
23
  if (!text(input.userId)) fail("userId is required in authToken mode");
22
24
  if (!input.tokenProvider && !text(input.tokenUrl)) fail("tokenUrl or tokenProvider is required in authToken mode");
@@ -33,6 +35,7 @@ function resolveConfig(input) {
33
35
  mode,
34
36
  widgetKey: text(input.widgetKey) || void 0,
35
37
  uid: text(input.uid) || void 0,
38
+ userHash: text(input.userHash) || void 0,
36
39
  userId: text(input.userId) || void 0,
37
40
  startConversationWith: [...new Set((input.startConversationWith ?? []).map((id) => id.trim()))],
38
41
  isDocked: input.isDocked ?? true,
@@ -122,7 +125,7 @@ async function openWidgetSession(config, fetchImpl = fetch) {
122
125
  return cachedFirst(await request(), request);
123
126
  }
124
127
  if (config.mode === "uid") {
125
- const request = () => requestWidgetSession(config, { mode: "uid", uid: config.uid, ...profile(config) }, fetchImpl);
128
+ const request = () => requestWidgetSession(config, { mode: "uid", uid: config.uid, userHash: config.userHash, ...profile(config) }, fetchImpl);
126
129
  return cachedFirst(await request(), request);
127
130
  }
128
131
  const tokenProvider = config.tokenProvider ?? (async (appUserId) => {
@@ -194,6 +197,8 @@ header h2 { flex: 1; margin: 0; font-size: 15px; font-weight: 600; white-space:
194
197
  .option.chosen:disabled { opacity: 1; }
195
198
  .options.grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 6px; }
196
199
  .options.grid .option { border-radius: 10px; padding: 10px 8px; min-height: 44px; font-weight: 600; text-align: center; overflow-wrap: anywhere; }
200
+ .ai-label { font-size: 11px; font-weight: 600; color: var(--ck-muted); text-transform: uppercase; letter-spacing: .04em; }
201
+ .msg .bubble.ai { border: 1px solid var(--ck-border); }
197
202
  .escape { align-self: flex-start; border: 0; background: transparent; padding: 2px 0; color: var(--ck-muted); font-size: 12px; text-decoration: underline; }
198
203
  .escape:disabled { cursor: default; opacity: .6; }
199
204
  .card-error { color: var(--ck-danger); }
@@ -218,6 +223,7 @@ var ICONS = {
218
223
  back: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><path d="m15 18-6-6 6-6"/></svg>'
219
224
  };
220
225
  var FRIENDLY = {
226
+ INVALID_USER_HASH: "This chat could not verify who you are. The site must sign the uid with its ConvoKit identity secret (userHash).",
221
227
  WIDGET_USER_LIMIT_REACHED: "Chat is busy right now. Please try again later.",
222
228
  PLAN_USER_LIMIT_REACHED: "Chat is busy right now. Please try again later.",
223
229
  PLAN_UPGRADE_REQUIRED: "Chat is currently unavailable.",
@@ -533,8 +539,9 @@ var ChatWidget = class {
533
539
  if (!mine && message.senderId !== previousSender) item.append(el("span", { className: "who", textContent: thread.names.get(message.senderId) ?? message.senderId }));
534
540
  if (card?.kind === "link") item.append(this.linkCard(message, card));
535
541
  else if (card?.kind === "quick_replies") item.append(this.quickReplies(thread, message, card, ordered));
542
+ else if (card?.kind === "answer") item.append(el("span", { className: "ai-label", textContent: "AI answer" }), el("div", { className: "bubble ai", textContent: message.text ?? "" }));
536
543
  else if (message.text) item.append(el("div", { className: "bubble", textContent: message.text }));
537
- if (latestCard === message && (card?.kind === "link" || card?.kind === "quick_replies")) item.append(this.escapeButton(thread, message));
544
+ if (latestCard === message && (card?.kind === "link" || card?.kind === "quick_replies" || card?.kind === "answer")) item.append(this.escapeButton(thread, message));
538
545
  const cardError = thread.cards.errors.get(message.id);
539
546
  if (cardError) item.append(el("span", { className: "meta card-error", textContent: cardError }));
540
547
  if (message.media.length) item.append(el("span", { className: "attachment", textContent: `\u{1F4CE} ${message.media.length === 1 ? "1 attachment" : `${message.media.length} attachments`}` }));