@erniai/web 0.0.0-stage → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,49 @@
1
+ # Changelog
2
+
3
+ Each release pins its loader at `https://widget.erni.ai/widget/<version>.js`. A pinned file never changes, so the `integrity` hash below stays valid for good. `loadErni` from a given package version loads that version's pinned loader and checks this hash.
4
+
5
+ ## 1.3.0
6
+
7
+ Pinned loader: `https://widget.erni.ai/widget/1.3.0.js`
8
+
9
+ `integrity`: `sha384-DyDVVh4lXF7oe04ARzwtfBLMpD2Pr13yK1zMoUdLi/EYp33nnYg6fwYeg4ZI6HTJ`
10
+
11
+ - Passthrough widgets: `identify({ idToken })` hands the widget your own login token, and `identify(null)` forgets it. The token is opaque (a non-empty string of at most 8192 UTF-8 bytes), kept in memory only, attached to each message the visitor sends, and delivered to your webhook as `data.identity_token`.
12
+ - The loader learns the widget's identity mode from the chat frame. On a passthrough widget the signed-identity `identify()` is refused with a `console.error`; on an `erni` widget `identify({ idToken })` and `identify(null)` are. The identity-secret guard still runs first for the signed-identity shape.
13
+ - `identify({ idToken })` refuses a token that looks like an Erni secret (`wis_...`, `erni_sk_...`, `erni_pk_...`).
14
+ - New export: the `PassthroughIdentity` type. `ErniApi.identify` now takes `IdentityPayload | PassthroughIdentity | null`.
15
+ - The chat frame keeps accepting messages from the 1.1.0 and 1.2.0 loaders.
16
+ - The package ships one declaration file, `dist/index.d.ts`, with the public API only (it also types `window.Erni`). The `IdentifyPayload` alias is removed; use `IdentityPayload`. No npm release carried the alias.
17
+ - Chat frame, served by the widget host for every loader version: a visitor without a conversation yet opens the live stream after their first message instead of retrying it, with no error shown; a request refused as too large (413) is shown as not sent and never retried.
18
+ - A chat open while its widget is switched to passthrough resumes the device's anonymous chat and tells the loader, so `identify({ idToken })` works without a reload. A message the ended signed-in session could not send stays on screen as not sent, with Retry.
19
+ - A host-page element with `id="Erni"` or `name="Erni"` (DOM clobbering) no longer stops the widget: the loader treats `window.Erni` as an existing loader only when it has the loader's methods, and otherwise installs itself. `loadErni` resolves only with a real loader API, and rejects (on timeout, or when `init` throws) instead of hanging.
20
+ - When `document.currentScript` is unavailable or clobbered (`<img name="currentScript">`), the loader finds its own `<script>` only when that is unambiguous: the single loader-looking script with `data-widget`, or else the only loader-looking script on the page. Another vendor's `/widget.js` is never taken as the widget host; when it cannot tell, the loader logs "could not locate the loader script" and does not start.
21
+
22
+ ## 1.2.0
23
+
24
+ Pinned loader: `https://widget.erni.ai/widget/1.2.0.js`
25
+
26
+ `integrity`: `sha384-mu0SXlumc+bAq0arqZzTzSvB57mngAqztaIcM9fsutHHjTU4N2CG2o/t6yOpZCN4`
27
+
28
+ - `loadErni` loads the pinned loader for this version with its `integrity` and `crossorigin="anonymous"` by default, instead of the always-latest `/widget.js`.
29
+ - `loadErni` has a new `integrity` option for a custom `src`. A custom `src` must be an absolute `https:` URL.
30
+ - `identify()` refuses an `identityToken` that is not 64 lowercase hex characters, and refuses with a loud `console.error` any `identify()`, `init()` or `loadErni()` option that looks like the identity secret (`wis_...`).
31
+ - `shutdown()` now clears the device even when it is called before the chat has loaded: the clear is delivered when the frame is ready, or else at the next page load.
32
+ - A logout in one tab now reaches the other open tabs. Their chat resets to a fresh anonymous one, and they never write the previous visitor's credential back.
33
+ - `on()` ignores unknown event names instead of throwing.
34
+ - A second copy of the loader on the same page is ignored, with a warning, instead of creating a second widget.
35
+ - New exports: `LoadErniOptions` and `DEFAULT_LOADER_INTEGRITY`. `DEFAULT_LOADER_SRC` is now the pinned URL.
36
+
37
+ ## 1.1.0
38
+
39
+ Pinned loader: `https://widget.erni.ai/widget/1.1.0.js`
40
+
41
+ `integrity`: `sha384-v3WVYOEtSmnh5n6DxFBIC4QMuntq3z9PBzqg5dFlg7sZKH07Ep8cj/MQD4sQUH/k`
42
+
43
+ - Verified visitors: `identify()` with an identity your server signed.
44
+ - First pinned loader release.
45
+ - Known gaps, fixed in 1.2.0: `shutdown()` before the chat has loaded does not clear the device, and a logout in one tab does not reach other open tabs. Pinned files never change, so move to 1.2.0.
46
+
47
+ ## 1.0.0
48
+
49
+ - Website chat widget: the loader, the chat frame and `loadErni`. No pinned loader was published for this version.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ @erniai/web
2
+ Copyright 2026 Erni
3
+
4
+ Licensed under the Apache License, Version 2.0. See the LICENSE file.
package/README.md CHANGED
@@ -1,3 +1,251 @@
1
- # Temporary Holding Version
1
+ # @erniai/web
2
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.
3
+ The Erni website chat widget: a chat bubble on your site that your team answers from the Erni inbox, next to your WhatsApp, Instagram, Messenger, iMessage and Telegram conversations.
4
+
5
+ You can add it in two ways:
6
+
7
+ - a `<script>` tag, with no build step;
8
+ - this package, which loads the same script from your own code with `loadErni()`.
9
+
10
+ Either way, the chat itself runs in an iframe on `https://widget.erni.ai`. Your page and the chat cannot read each other's storage or DOM, and they talk only through origin-checked `postMessage`.
11
+
12
+ ## Install
13
+
14
+ ```sh
15
+ npm install @erniai/web
16
+ ```
17
+
18
+ The package is ESM only (`import`, not `require`). It has no runtime dependencies and works in current browsers (the code targets ES2019). It does nothing on the server: `loadErni` rejects when there is no `window`.
19
+
20
+ You need a widget key (`wk_...`). Create the widget in the Erni inbox (channel setup, Web), list the sites allowed to show it, and copy the key. The key is public: it names the widget and grants nothing on a site that is not on its allowed list.
21
+
22
+ ## Script tag
23
+
24
+ Use the pinned loader with its Subresource Integrity hash. A pinned file never changes, so the browser refuses to run it if a single byte differs:
25
+
26
+ ```html
27
+ <script src="https://widget.erni.ai/widget/1.3.0.js"
28
+ integrity="sha384-DyDVVh4lXF7oe04ARzwtfBLMpD2Pr13yK1zMoUdLi/EYp33nnYg6fwYeg4ZI6HTJ"
29
+ crossorigin="anonymous" async
30
+ data-widget="wk_your_key"></script>
31
+ ```
32
+
33
+ Optional attributes: `data-locale="he"` (default `en`) and `data-position="left"` (default `right`).
34
+
35
+ `https://widget.erni.ai/widget.js` always serves the latest loader. It cannot carry an `integrity` hash, so prefer a pinned version. Every version and its hash is listed in [CHANGELOG.md](./CHANGELOG.md), which is part of this package.
36
+
37
+ ## loadErni
38
+
39
+ ```ts
40
+ import { loadErni } from '@erniai/web';
41
+
42
+ const erni = await loadErni({ widget: 'wk_your_key', locale: 'en', position: 'right' });
43
+ erni.open();
44
+ ```
45
+
46
+ `loadErni(options)`:
47
+
48
+ - injects the loader pinned to this package's version (`https://widget.erni.ai/widget/<version>.js`), with that version's sha384 as `integrity` and `crossorigin="anonymous"`;
49
+ - calls `init` with your options and resolves with the widget API (`window.Erni`);
50
+ - rejects after 10 seconds, when the script fails to load (an integrity mismatch counts as a failure), or when there is no `window`.
51
+
52
+ Concurrent calls share one script and one promise.
53
+
54
+ | Option | |
55
+ |---|---|
56
+ | `widget` | Your widget key. Required. |
57
+ | `locale` | `'en'` (default) or `'he'`. |
58
+ | `position` | `'right'` (default) or `'left'`. |
59
+ | `src` | Load the loader from another URL. It must be an absolute `https:` URL; anything else is rejected. |
60
+ | `integrity` | The SRI hash for a custom `src`, such as `sha384-...`. Without it the script is not verified, and `loadErni` logs a warning. The built-in hash is only ever applied to the default URL. |
61
+
62
+ The pinned loader never changes. The chat frame it opens is updated by Erni on the server. The frame runs on the widget origin, in a sandboxed cross-origin iframe, so it can reach the chat but not your page, its cookies or its DOM.
63
+
64
+ ## Content Security Policy on your page
65
+
66
+ If your site sends a CSP, allow:
67
+
68
+ ```
69
+ script-src https://widget.erni.ai;
70
+ frame-src https://widget.erni.ai;
71
+ ```
72
+
73
+ - With `loadErni` under a nonce-based policy, `'strict-dynamic'` also covers the injected loader.
74
+ - No `connect-src`, `style-src` or `'unsafe-inline'` is needed: the loader draws the bubble through the CSSOM and opens no connections from your page.
75
+ - Trusted Types: if you enforce `require-trusted-types-for 'script'`, assigning `script.src` in `loadErni` needs a policy that allows `https://widget.erni.ai`. Otherwise, use the script tag.
76
+
77
+ ## Allowed sites
78
+
79
+ Each widget has a list of sites allowed to show it, enforced by the browser (`frame-ancestors` on the chat frame) and by the server. Entries are exact origins (`https://shop.example.com`) or a single wildcard label (`https://*.example.com`).
80
+
81
+ Do not use a wildcard for a domain whose subdomains serve content you do not control, such as user pages or customer sites. Every allowed subdomain shares the visitor's chat on that site.
82
+
83
+ ## Verified visitors
84
+
85
+ By default visitors are anonymous. If your site has a login, your server can tell the widget who the visitor is. The chat then follows the user across visits and devices, shows up in the inbox as that contact, and, for a phone or email you have verified, includes their earlier WhatsApp and iMessage conversations with you.
86
+
87
+ ### The identity secret never leaves your server
88
+
89
+ In the widget settings, create an **identity secret** (`wis_...`). It is shown once.
90
+
91
+ - Store it like a password, on your server only: in a secret manager or a server-side environment variable.
92
+ - Never put it in browser code, a public env var (`NEXT_PUBLIC_...`, `VITE_...`), a mobile app or a repository. Anyone who has it can sign in as any of your users and read their chats.
93
+ - Planned rotation: **rotate once** in the widget settings. The previous secret keeps working for 24 hours, so you can deploy the new one without signing anyone out.
94
+ - If it was ever exposed, **rotate twice** right away and deploy the newest secret. One rotation leaves the leaked secret valid for those 24 hours, and the second rotation retires it immediately. Users signed with the leaked secret are signed out, which is the point.
95
+
96
+ The widget refuses, with a `console.error`, any `identify()` or `init()` call that contains something shaped like the identity secret. If you see that error, treat the secret as exposed and rotate it twice.
97
+
98
+ ### Only sign a phone or email your login has verified
99
+
100
+ A signed `phone` or `email` unlocks that customer's WhatsApp and iMessage history with your business in the widget. Sign one only if your own login has verified it, by an SMS or email code or an equivalent check. If users can type any phone or email into their profile and you sign it, a user can enter someone else's number and read that person's history.
101
+
102
+ When a value is not verified, leave it out. The visitor can still prove it in the widget with a one-time code.
103
+
104
+ ### Sign the identity on your server
105
+
106
+ The token is HMAC-SHA256, as 64 lowercase hex characters, over a canonical JSON string, keyed with the identity secret.
107
+
108
+ The JSON is compact (no spaces) and has these keys, in this order; leave out any key you don't use:
109
+
110
+ | Claim | Rules |
111
+ |---|---|
112
+ | `userId` | Your stable id for the user, 1 to 256 characters. Required. |
113
+ | `phone` | Optional. E.164, for example `+14155550123`. Verified numbers only. |
114
+ | `email` | Optional. Contains `@`, at most 254 characters. Verified addresses only. |
115
+ | `iat` | Seconds since the epoch, an integer. |
116
+
117
+ A token is valid for **600 seconds** after `iat`. An `iat` more than 60 seconds in the future is refused. Sign a fresh token on every page load and never store it.
118
+
119
+ `name` can be passed to the widget too, but it is **not signed**: it is a display name only.
120
+
121
+ Node:
122
+
123
+ ```js
124
+ import { createHmac } from 'node:crypto';
125
+
126
+ function signIdentity(secret, { userId, phone, email }) {
127
+ const iat = Math.floor(Date.now() / 1000);
128
+ const claims = { userId };
129
+ if (phone !== undefined) claims.phone = phone;
130
+ if (email !== undefined) claims.email = email;
131
+ claims.iat = iat;
132
+ const identityToken = createHmac('sha256', secret).update(JSON.stringify(claims)).digest('hex');
133
+ return { ...claims, identityToken };
134
+ }
135
+ ```
136
+
137
+ Python (3.10+):
138
+
139
+ ```python
140
+ import hashlib, hmac, json, time
141
+
142
+ def sign_identity(secret: str, user_id: str, phone: str | None = None, email: str | None = None) -> dict:
143
+ claims = {"userId": user_id}
144
+ if phone is not None:
145
+ claims["phone"] = phone
146
+ if email is not None:
147
+ claims["email"] = email
148
+ claims["iat"] = int(time.time())
149
+ payload = json.dumps(claims, separators=(",", ":"), ensure_ascii=False)
150
+ token = hmac.new(secret.encode(), payload.encode(), hashlib.sha256).hexdigest()
151
+ return {**claims, "identityToken": token}
152
+ ```
153
+
154
+ ### Hand the identity to the widget
155
+
156
+ Treat the signed identity like a password for its ten minutes: never put it in a URL, a log or an analytics event.
157
+
158
+ With `loadErni`, fetch it from your own API or read it from the page, then call `identify`:
159
+
160
+ ```ts
161
+ const erni = await loadErni({ widget: 'wk_your_key' });
162
+ erni.identify(await fetch('/api/erni-identity').then((r) => r.json())); // { userId, name?, phone?, email?, iat, identityToken }
163
+ ```
164
+
165
+ With the script tag, render the identity into the page as JSON data, not as code, and read it from a script file on your own origin:
166
+
167
+ ```html
168
+ <!-- Server-rendered. JSON-encode the object and escape every "<" as \u003c, so a value (a name like "</script><script>...") can never close the tag. -->
169
+ <script type="application/json" id="erni-identity">{"userId":"u_123","name":"Dana","iat":1768000000,"identityToken":"<64 hex>"}</script>
170
+ <script src="https://widget.erni.ai/widget/1.3.0.js" integrity="sha384-DyDVVh4lXF7oe04ARzwtfBLMpD2Pr13yK1zMoUdLi/EYp33nnYg6fwYeg4ZI6HTJ"
171
+ crossorigin="anonymous" async data-widget="wk_your_key"></script>
172
+ <script src="/js/erni-identify.js" defer></script>
173
+ ```
174
+
175
+ On your server, `JSON.stringify` does not escape `<`, so add it:
176
+
177
+ ```js
178
+ const json = JSON.stringify(signIdentity(secret, user)).replace(/</g, '\\u003c'); // put `json` inside the block
179
+ ```
180
+
181
+ ```js
182
+ // /js/erni-identify.js
183
+ (function () {
184
+ var data = document.getElementById('erni-identity');
185
+ if (!data) return;
186
+ var identity = JSON.parse(data.textContent);
187
+ function identify() { window.Erni.identify(identity); }
188
+ if (window.Erni) identify();
189
+ else document.querySelector('script[data-widget]').addEventListener('load', identify);
190
+ })();
191
+ ```
192
+
193
+ Do not template the identity into an inline handler such as `onload='Erni.identify({...})'`. A user-controlled value like the name can break out of the attribute and run as script on your page, and inline handlers need `'unsafe-inline'` in your CSP.
194
+
195
+ Call `identify` on every page load. Calling it with a different `userId` switches the chat to that user. If the visitor started a chat anonymously on this page, wrote in it, and then logs in, that chat moves to their account. `identify` refuses, with a `console.error`, a token that is not 64 hex characters, and an unknown field. An invalid or expired token leaves the visitor anonymous.
196
+
197
+ ### Log out
198
+
199
+ Call `erni.shutdown()` (or `window.Erni.shutdown()`) when the user logs out. It removes the widget and clears the chat stored on this device, so the next person on a shared computer starts a new anonymous chat. It is safe to call at any time, including before the widget has finished loading. If the chat has not loaded yet, it is cleared as soon as it does, or else at the next page load on your site.
200
+
201
+ ## Passthrough widgets: your own login token
202
+
203
+ A widget in **passthrough** mode does no identity work of its own. Your page hands the widget the token your own login already issued (a session token, a JWT, any string), and each message the visitor sends carries it to your webhook as `data.identity_token` on `message.received`. Your server decides who the visitor is. The widget's mode is set through the partner API (`PATCH /api/v1/web/widgets/{id}`, `identity_mode`); the inbox shows it read-only. Erni's signed identity, one-time codes and linked history are off in this mode.
204
+
205
+ ```ts
206
+ erni.identify({ idToken: currentUser.token }); // after login, and on every page load while signed in
207
+ erni.shutdown(); // on logout: clears the visitor and chat on this device
208
+ ```
209
+
210
+ On logout call `shutdown()`, not `identify(null)`. The chat belongs to this device's anonymous visitor, not to your user, so only `shutdown()` keeps the next person on the same browser from seeing and continuing the previous user's chat. `identify(null)` only stops attaching a token to later messages and keeps the chat. So the same conversation can carry different tokens over time (or none): read `identity_token` on each message and never assume one conversation is one user.
211
+
212
+ - The token is opaque to Erni: it must be a non-empty string of at most 8192 UTF-8 bytes, and nothing else about it is checked.
213
+ - It is kept in memory only, in the loader and the chat frame, never in `localStorage`, `sessionStorage` or a cookie. A reload of the chat frame gets it again from the loader; a reload of your page needs a new `identify` call. `shutdown()` forgets it.
214
+ - Between the widget and your webhook it is stored encrypted, and removed once the delivery is done. It never appears in the inbox, the message history or the API.
215
+ - Only webhooks registered with the API key that created the widget, or last updated it through the API, receive `identity_token`. After replacing a key, `PATCH` the widget once with the new key.
216
+ - `identify({ idToken })` refuses, with a `console.error`, a token that looks like an Erni secret (`wis_...`, `erni_sk_...`, `erni_pk_...`): those must never be in browser code.
217
+ - On a passthrough widget, `identify({ userId, iat, identityToken })` is refused with a `console.error`, and on an `erni` widget `identify({ idToken })` and `identify(null)` are. The error never prints the token.
218
+
219
+ Your webhook must still check the token itself, the way your API checks it on any other request.
220
+
221
+ ## API
222
+
223
+ `loadErni` resolves with, and the script tag sets `window.Erni` to, this object:
224
+
225
+ | Method | |
226
+ |---|---|
227
+ | `init({ widget, locale?, position? })` | Start the widget. The script tag calls it for you from `data-widget`. |
228
+ | `open()`, `close()`, `toggle()` | Show or hide the chat. |
229
+ | `prefill(text)` | Put text in the message box. It is never sent without the visitor. |
230
+ | `identify(identity)` | Sign the visitor in (see above). Passthrough widgets: `identify({ idToken })`, and `identify(null)` to stop sending it (on logout use `shutdown()`). |
231
+ | `shutdown()` | Remove the widget and clear this device's chat (see above). |
232
+ | `on(event, listener)` | Subscribe to an event. Returns a function that unsubscribes. |
233
+
234
+ | Event | Payload |
235
+ |---|---|
236
+ | `open` | none |
237
+ | `close` | none |
238
+ | `message` | none. A new message from your team arrived (the content stays in the chat frame). |
239
+ | `unread` | The number of unread messages (a number). |
240
+
241
+ Exported types: `ErniApi`, `InitOptions`, `LoadErniOptions`, `IdentityPayload`, `PassthroughIdentity`, `EventName`. Exported constants: `DEFAULT_LOADER_SRC` and `DEFAULT_LOADER_INTEGRITY`. All types are in one declaration file, `dist/index.d.ts`, which also types `window.Erni`.
242
+
243
+ ## Support and security
244
+
245
+ - Send bug reports and questions to the contact in [SECURITY.md](./SECURITY.md), which is part of this package.
246
+ - Report a vulnerability privately to the same contact, as described there, and do not disclose it publicly before it is fixed.
247
+ - Releases and their loader hashes are in [CHANGELOG.md](./CHANGELOG.md).
248
+
249
+ ## License
250
+
251
+ Apache-2.0, copyright 2026 Erni. See [LICENSE](./LICENSE) and [NOTICE](./NOTICE).
package/SECURITY.md ADDED
@@ -0,0 +1,49 @@
1
+ # Security policy
2
+
3
+ ## Reporting a vulnerability
4
+
5
+ Please report security issues privately by email to **info@simplestoolbar.com**, and do not disclose a vulnerability publicly before it is fixed. Bug reports that are not security issues go to the same address.
6
+
7
+ Include what you can of:
8
+
9
+ - the affected component and version (for example `@erniai/web@1.2.0` or `widget.erni.ai/widget/1.2.0.js`);
10
+ - the steps to reproduce, or a proof of concept;
11
+ - the impact as you understand it.
12
+
13
+ We aim to acknowledge a report within 3 business days and to give a first assessment within 10 business days. We will keep you informed while we fix it and agree a disclosure date with you. If you wish, we will credit you once the fix is released.
14
+
15
+ ## Scope
16
+
17
+ In scope:
18
+
19
+ - the `@erniai/web` package;
20
+ - the loader served from `https://widget.erni.ai/widget.js` and `https://widget.erni.ai/widget/<version>.js`;
21
+ - the chat frame on `https://widget.erni.ai`;
22
+ - the widget's public HTTP API under `https://widget.erni.ai/api/widget/`;
23
+ - identity signing and verification (the identity token and the identity secret).
24
+
25
+ Out of scope:
26
+
27
+ - vulnerabilities in a website that embeds the widget, unless the widget causes them;
28
+ - denial of service through traffic volume, and rate-limit tuning;
29
+ - reports from automated scanners without a demonstrated impact;
30
+ - social engineering of Erni staff or customers.
31
+
32
+ ## Supported versions
33
+
34
+ Security fixes go into the latest minor release. Pinned loader files (`/widget/<version>.js`) never change: a fix ships as a new version, and older pinned versions stay available so existing integrity hashes keep working. Upgrade to the newest version listed in [CHANGELOG.md](./CHANGELOG.md).
35
+
36
+ ## Testing rules
37
+
38
+ - Test only against a widget you created yourself, on a site you control.
39
+ - Never test against another business's widget, and never access, change or delete data that is not yours.
40
+ - Do not send messages to real customers, and do not trigger one-time codes to phone numbers or email addresses you do not own.
41
+ - Stop and report as soon as you have shown the issue.
42
+
43
+ ## Safe harbour
44
+
45
+ We will not take legal action against you for security research that follows this policy, is done in good faith, and is reported to us privately before any public disclosure.
46
+
47
+ ## If your identity secret is exposed
48
+
49
+ The identity secret (`wis_...`) belongs on your server only. If it was ever in browser code, a repository or a log, rotate it **twice** at once in the widget settings and deploy the newest secret. A single rotation keeps the previous (leaked) secret valid for 24 hours; the second rotation retires it immediately. This is not something to report to us. It is a step for you to take now.
@@ -0,0 +1,89 @@
1
+ /**
2
+ * `@erniai/web`: load the Erni website chat widget from your own bundle.
3
+ * This file is the package's whole public API: `loadErni`, its constants and the types below.
4
+ */
5
+ /** Options for `Erni.init` and `loadErni`. */
6
+ export interface InitOptions {
7
+ /** The widget key from the widget settings. */
8
+ widget: string;
9
+ /** Interface language. Default `en`. */
10
+ locale?: 'en' | 'he';
11
+ /** Which bottom corner the launcher sits in. Default `right`. */
12
+ position?: 'right' | 'left';
13
+ }
14
+ /** Events passed to `Erni.on`. `unread` listeners receive the unread count. */
15
+ export type EventName = 'open' | 'close' | 'message' | 'unread';
16
+ type Listener = (payload?: number) => void;
17
+ /**
18
+ * A signed-in user, signed by your server (never in the browser). `identityToken` is HMAC-SHA256 of
19
+ * the claims with your widget identity secret, as 64 lowercase hex characters.
20
+ */
21
+ export interface IdentityPayload {
22
+ userId: string;
23
+ name?: string;
24
+ /** Sign only a verified phone: it unlocks that customer's history on other channels. */
25
+ phone?: string;
26
+ /** Sign only an email your login has verified, for the same reason. */
27
+ email?: string;
28
+ /** Issue time, in seconds since the epoch. */
29
+ iat: number;
30
+ identityToken: string;
31
+ }
32
+ /**
33
+ * Passthrough widgets: your own login token for the signed-in user. Erni never reads it; it is kept in
34
+ * memory and attached to each message, and your webhook receives it as `data.identity_token`.
35
+ */
36
+ export interface PassthroughIdentity {
37
+ idToken: string;
38
+ }
39
+ /** The API the loader script puts on `window.Erni`. */
40
+ export interface ErniApi {
41
+ /** Starts the widget. Called for you when the script tag has `data-widget`. */
42
+ init(opts: InitOptions): void;
43
+ open(): void;
44
+ close(): void;
45
+ toggle(): void;
46
+ /** Puts text in the message box without sending it. */
47
+ prefill(text: string): void;
48
+ /** Subscribes to an event; returns a function that unsubscribes. */
49
+ on(event: EventName, fn: Listener): () => void;
50
+ /**
51
+ * Tells the widget who the visitor is. Call on every page load while a user is signed in.
52
+ *
53
+ * - Erni widgets (the default): pass the {@link IdentityPayload} your server signed. A different
54
+ * user switches the chat to that user. Malformed payloads, and anything that looks like the
55
+ * identity secret, are refused with a `console.error` and never sent.
56
+ * - Passthrough widgets: pass `{ idToken }` (a non-empty string of at most 8192 UTF-8 bytes).
57
+ * `identify(null)` stops attaching a token but keeps the chat, so one conversation can carry
58
+ * several tokens over time. A token that looks like an Erni secret is refused.
59
+ */
60
+ identify(payload: IdentityPayload | PassthroughIdentity | null): void;
61
+ /**
62
+ * Call on logout. Removes the widget and clears this device's chat, so the next person starts a new
63
+ * anonymous chat. Safe to call at any time, also before the widget has loaded.
64
+ */
65
+ shutdown(): void;
66
+ }
67
+ declare global {
68
+ interface Window {
69
+ Erni?: ErniApi;
70
+ }
71
+ }
72
+ /** The loader pinned to this package's version. */
73
+ export declare const DEFAULT_LOADER_SRC = "https://widget.erni.ai/widget/1.3.0.js";
74
+ /** The Subresource Integrity hash of `DEFAULT_LOADER_SRC`. */
75
+ export declare const DEFAULT_LOADER_INTEGRITY = "sha384-DyDVVh4lXF7oe04ARzwtfBLMpD2Pr13yK1zMoUdLi/EYp33nnYg6fwYeg4ZI6HTJ";
76
+ export interface LoadErniOptions extends InitOptions {
77
+ /** Load the loader from another absolute `https:` URL instead of `DEFAULT_LOADER_SRC`. */
78
+ src?: string;
79
+ /** SRI hash for a custom `src`, such as `sha384-...`. Without it the script is not verified. */
80
+ integrity?: string;
81
+ }
82
+ /**
83
+ * Loads the widget loader script (once) and initialises it.
84
+ *
85
+ * @param opts - `init` options, plus an optional custom `src` and `integrity`.
86
+ * @returns The `window.Erni` API. Concurrent calls with the same `src` share one load.
87
+ */
88
+ export declare function loadErni(opts: LoadErniOptions): Promise<ErniApi>;
89
+ export {};
package/dist/index.mjs ADDED
@@ -0,0 +1,143 @@
1
+ // src/is-api.ts
2
+ var API_METHODS = ["init", "open", "close", "toggle", "prefill", "on", "identify", "shutdown"];
3
+ function isErniApi(value) {
4
+ if (typeof value !== "object" || value === null) return false;
5
+ if (typeof Node !== "undefined" && value instanceof Node) return false;
6
+ if (typeof HTMLCollection !== "undefined" && value instanceof HTMLCollection) return false;
7
+ const v = value;
8
+ return API_METHODS.every((m) => typeof v[m] === "function");
9
+ }
10
+
11
+ // src/protocol.ts
12
+ function asRecord(value) {
13
+ return typeof value === "object" && value !== null ? value : null;
14
+ }
15
+ var IDENTITY_SECRET_PREFIX = "wis";
16
+ var SECRET_PREFIXES = [IDENTITY_SECRET_PREFIX, "erni_sk", "erni_pk"];
17
+ function secretPattern(prefixes, atBoundary) {
18
+ return new RegExp(`${atBoundary ? "(?:^|[^A-Za-z0-9-])" : ""}(?:${prefixes.join("|")})_[A-Za-z0-9_-]{20,}`);
19
+ }
20
+ var IDENTITY_SECRET_PATTERN = secretPattern([IDENTITY_SECRET_PREFIX], false);
21
+ var ANY_SECRET_PATTERN = secretPattern(SECRET_PREFIXES, true);
22
+ function looksLikeIdentitySecret(value) {
23
+ if (typeof value === "string") return IDENTITY_SECRET_PATTERN.test(value);
24
+ const v = asRecord(value);
25
+ return v !== null && Object.values(v).some((x) => typeof x === "string" && IDENTITY_SECRET_PATTERN.test(x));
26
+ }
27
+ var IDENTITY_SECRET_ERROR = "Erni: this looks like your Erni identity secret (wis_...). It must never be in browser code: anyone can read it there. Rotate it twice in the widget settings now (the second rotation retires the exposed secret), keep the new one on your server, and pass identify() the token your server signed.";
28
+
29
+ // src/release.ts
30
+ var LOADER_VERSION = "1.3.0";
31
+ var LOADER_INTEGRITY = "sha384-DyDVVh4lXF7oe04ARzwtfBLMpD2Pr13yK1zMoUdLi/EYp33nnYg6fwYeg4ZI6HTJ";
32
+
33
+ // src/index.ts
34
+ var DEFAULT_LOADER_SRC = `https://widget.erni.ai/widget/${LOADER_VERSION}.js`;
35
+ var DEFAULT_LOADER_INTEGRITY = LOADER_INTEGRITY;
36
+ var LOAD_TIMEOUT_MS = 1e4;
37
+ var SRI_PATTERN = /^sha(256|384|512)-[A-Za-z0-9+/]+={0,2}( sha(256|384|512)-[A-Za-z0-9+/]+={0,2})*$/;
38
+ var pending = /* @__PURE__ */ new Map();
39
+ var injected = /* @__PURE__ */ new Map();
40
+ function findScript(src) {
41
+ for (const s of Array.from(document.querySelectorAll("script[src]"))) {
42
+ if (s.src === src) return s;
43
+ }
44
+ return null;
45
+ }
46
+ function httpsUrl(raw) {
47
+ try {
48
+ const url = new URL(raw);
49
+ return url.protocol === "https:" ? url.href : null;
50
+ } catch {
51
+ return null;
52
+ }
53
+ }
54
+ function loadErni(opts) {
55
+ if (typeof window === "undefined" || typeof document === "undefined") {
56
+ return Promise.reject(new Error("loadErni needs a browser (window is undefined)"));
57
+ }
58
+ const { src: rawSrc, integrity: rawIntegrity, ...init } = opts;
59
+ if (looksLikeIdentitySecret(opts)) {
60
+ console.error(IDENTITY_SECRET_ERROR);
61
+ return Promise.reject(new Error("loadErni: refused an option that looks like the identity secret"));
62
+ }
63
+ const src = rawSrc === void 0 ? DEFAULT_LOADER_SRC : httpsUrl(rawSrc);
64
+ if (src === null) return Promise.reject(new Error("loadErni: src must be an absolute https: URL"));
65
+ if (rawIntegrity !== void 0 && !SRI_PATTERN.test(rawIntegrity)) {
66
+ return Promise.reject(new Error("loadErni: integrity must be an SRI hash such as sha384-..."));
67
+ }
68
+ const integrity = rawIntegrity != null ? rawIntegrity : src === DEFAULT_LOADER_SRC ? DEFAULT_LOADER_INTEGRITY : void 0;
69
+ if (integrity === void 0) {
70
+ console.warn(
71
+ `loadErni: loading ${src} without integrity; pass the release's sha384 so a changed script is refused`
72
+ );
73
+ }
74
+ let loading = pending.get(src);
75
+ if (!loading) {
76
+ const created = new Promise((resolve, reject) => {
77
+ const existing = findScript(src);
78
+ let script;
79
+ if (existing) script = existing;
80
+ else {
81
+ script = document.createElement("script");
82
+ script.src = src;
83
+ script.async = true;
84
+ if (integrity) {
85
+ script.setAttribute("integrity", integrity);
86
+ script.setAttribute("crossorigin", "anonymous");
87
+ }
88
+ document.head.appendChild(script);
89
+ }
90
+ injected.set(src, existing === null);
91
+ let settled = false;
92
+ const finish = (fn) => {
93
+ if (settled) return;
94
+ settled = true;
95
+ clearTimeout(timer);
96
+ clearInterval(poll);
97
+ script.removeEventListener("load", onLoad);
98
+ script.removeEventListener("error", onError);
99
+ fn();
100
+ };
101
+ const check = () => {
102
+ const api = window.Erni;
103
+ if (!isErniApi(api)) return;
104
+ finish(() => {
105
+ try {
106
+ api.init(init);
107
+ } catch (err) {
108
+ reject(err instanceof Error ? err : new Error("Erni.init failed"));
109
+ return;
110
+ }
111
+ resolve(api);
112
+ });
113
+ };
114
+ const onLoad = () => check();
115
+ const onError = () => finish(() => reject(new Error(`Could not load the Erni widget from ${src}`)));
116
+ const timer = setTimeout(
117
+ () => finish(() => reject(new Error("Timed out loading the Erni widget"))),
118
+ LOAD_TIMEOUT_MS
119
+ );
120
+ const poll = setInterval(check, 50);
121
+ script.addEventListener("load", onLoad);
122
+ script.addEventListener("error", onError);
123
+ check();
124
+ });
125
+ loading = created;
126
+ pending.set(src, created);
127
+ const forget = () => {
128
+ if (pending.get(src) === created) pending.delete(src);
129
+ };
130
+ created.then(forget, () => {
131
+ var _a;
132
+ forget();
133
+ if (injected.get(src)) (_a = findScript(src)) == null ? void 0 : _a.remove();
134
+ injected.delete(src);
135
+ });
136
+ }
137
+ return loading;
138
+ }
139
+ export {
140
+ DEFAULT_LOADER_INTEGRITY,
141
+ DEFAULT_LOADER_SRC,
142
+ loadErni
143
+ };
package/package.json CHANGED
@@ -1,6 +1,60 @@
1
1
  {
2
2
  "name": "@erniai/web",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.3.0",
4
+ "description": "Erni website chat widget SDK: add the Erni chat widget to your site from your own code, with TypeScript types.",
5
+ "keywords": [
6
+ "erni",
7
+ "chat",
8
+ "chat-widget",
9
+ "live-chat",
10
+ "website-chat",
11
+ "customer-support",
12
+ "messaging",
13
+ "widget"
14
+ ],
15
+ "license": "Apache-2.0",
16
+ "author": "Erni",
17
+ "bugs": {
18
+ "email": "info@simplestoolbar.com"
19
+ },
20
+ "type": "module",
21
+ "main": "./dist/index.mjs",
22
+ "module": "./dist/index.mjs",
23
+ "types": "./dist/index.d.ts",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.ts",
27
+ "import": "./dist/index.mjs",
28
+ "default": "./dist/index.mjs"
29
+ },
30
+ "./package.json": "./package.json"
31
+ },
32
+ "files": [
33
+ "dist/index.mjs",
34
+ "dist/index.d.ts",
35
+ "README.md",
36
+ "LICENSE",
37
+ "NOTICE",
38
+ "SECURITY.md",
39
+ "CHANGELOG.md"
40
+ ],
41
+ "sideEffects": false,
42
+ "publishConfig": {
43
+ "access": "public"
44
+ },
45
+ "scripts": {
46
+ "build": "node build.mjs",
47
+ "prepack": "node build.mjs",
48
+ "typecheck": "tsc --noEmit",
49
+ "test": "vitest run",
50
+ "lint": "eslint .",
51
+ "format": "prettier --write .",
52
+ "format:check": "prettier --check ."
53
+ },
54
+ "devDependencies": {
55
+ "esbuild": "~0.25.12",
56
+ "jsdom": "^27.4.0",
57
+ "typescript": "^5.3.0",
58
+ "vitest": "^1.0.0"
59
+ }
60
+ }