@signalhousellc/sdk 1.5.1 → 1.6.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 +5 -56
- package/index.d.ts +1 -0
- package/index.js +2 -0
- package/package.json +32 -34
- package/voice-browser.d.ts +1 -0
- package/voice-browser.js +2 -0
- package/warn.js +7 -0
- package/webhooks.d.ts +1 -0
- package/webhooks.js +2 -0
- package/scripts/install-skills.mjs +0 -329
- package/skills/VENDORED.json +0 -22
- package/skills/signalhouse-10dlc/SKILL.md +0 -172
- package/skills/signalhouse-10dlc/examples/brightsmile-onboarding.md +0 -62
- package/skills/signalhouse-10dlc/references/tcr-rejection-causes.md +0 -104
- package/skills/signalhouse-advisor/SKILL.md +0 -84
- package/skills/signalhouse-numbers/SKILL.md +0 -82
- package/skills/signalhouse-setup/SKILL.md +0 -121
- package/skills/signalhouse-sms/SKILL.md +0 -81
- package/skills/signalhouse-webhooks/SKILL.md +0 -148
- package/src/SignalHouseSDK.js +0 -201
- package/src/domains/Agents.js +0 -987
- package/src/domains/Auth.js +0 -225
- package/src/domains/Billing.js +0 -265
- package/src/domains/Brands.js +0 -566
- package/src/domains/Campaigns.js +0 -691
- package/src/domains/Dnc.js +0 -168
- package/src/domains/Groups.js +0 -187
- package/src/domains/Landings.js +0 -237
- package/src/domains/Messages.js +0 -609
- package/src/domains/Notifications.js +0 -62
- package/src/domains/Numbers.js +0 -574
- package/src/domains/Onboarding.js +0 -128
- package/src/domains/Registrations.js +0 -246
- package/src/domains/Shortlinks.js +0 -80
- package/src/domains/Subgroups.js +0 -136
- package/src/domains/Subscriptions.js +0 -164
- package/src/domains/Templates.js +0 -403
- package/src/domains/Tickets.js +0 -100
- package/src/domains/Users.js +0 -228
- package/src/domains/Voice.js +0 -41
- package/src/domains/Webhooks.js +0 -125
- package/src/domains/voice/Analytics.js +0 -82
- package/src/domains/voice/CallLogs.js +0 -111
- package/src/domains/voice/Calls.js +0 -118
- package/src/domains/voice/GlobalVoiceSettings.js +0 -54
- package/src/domains/voice/NumberRoutes.js +0 -82
- package/src/domains/voice/ProgrammableVoiceProfiles.js +0 -191
- package/src/domains/voice/SipProfiles.js +0 -203
- package/src/domains/voice/SipTrunks.js +0 -203
- package/src/domains/voice/Tokens.js +0 -96
- package/src/domains/voice/browser/Call.js +0 -366
- package/src/domains/voice/browser/Device.js +0 -484
- package/src/domains/voice/browser/index.js +0 -17
- package/src/webhooks/verifySignature.js +0 -66
|
@@ -1,484 +0,0 @@
|
|
|
1
|
-
import JsSIP from "jssip";
|
|
2
|
-
import { Call } from "./Call.js";
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* @typedef {Object} SipCredentials
|
|
6
|
-
* @property {string} username - SIP username (e.g. "wrtc_<hex>"); from /voice/tokens response.
|
|
7
|
-
* @property {string} password - Plaintext SIP password.
|
|
8
|
-
* @property {string} domain - SIP domain (e.g. "webrtc.signalhouse.io").
|
|
9
|
-
* @property {string} wss_url - WebSocket Secure URL to OpenSIPS.
|
|
10
|
-
*/
|
|
11
|
-
|
|
12
|
-
/**
|
|
13
|
-
* @typedef {Object} VoiceTokenResponse
|
|
14
|
-
* @property {string} token - JWT (informational). Tokens are ephemeral: refresh
|
|
15
|
-
* before `expires_at` (see updateToken()) so the softphone keeps a valid
|
|
16
|
-
* registration.
|
|
17
|
-
* @property {string} identity - The wrtc_<hex> SIP username. The refresh
|
|
18
|
-
* endpoint (POST /voice/tokens/refresh) keeps this identity stable; a fresh
|
|
19
|
-
* mint (POST /voice/tokens) returns a new one.
|
|
20
|
-
* @property {string} expires_at - ISO timestamp. The Device schedules a
|
|
21
|
-
* `tokenWillExpire` event at this minus `tokenRefreshMs`.
|
|
22
|
-
* @property {SipCredentials} sip_credentials
|
|
23
|
-
*/
|
|
24
|
-
|
|
25
|
-
/**
|
|
26
|
-
* @typedef {Object} ConnectParams
|
|
27
|
-
* @property {string} to - Destination — E.164 ("+15551234") or full SIP URI.
|
|
28
|
-
* @property {string} [from] - Caller ID to present (must be an account-owned DID).
|
|
29
|
-
* Sent as a P-Preferred-Identity header per RFC 3325; OpenSIPS validates
|
|
30
|
-
* ownership and uses it as the carrier-bound From. If omitted, OpenSIPS
|
|
31
|
-
* falls back to the account's default outbound DID.
|
|
32
|
-
* @property {MediaStream} [mediaStream] - Pre-acquired stream from getUserMedia.
|
|
33
|
-
* When absent the SDK calls getUserMedia({audio: true}) itself.
|
|
34
|
-
* @property {RTCConfiguration} [pcConfig] - WebRTC peer-connection config.
|
|
35
|
-
* @property {string[]} [extraHeaders] - Additional SIP headers to attach to
|
|
36
|
-
* the outbound INVITE (advanced).
|
|
37
|
-
*/
|
|
38
|
-
|
|
39
|
-
/**
|
|
40
|
-
* Browser-side SignalHouse voice client. Wraps JsSIP behind a Twilio-shape
|
|
41
|
-
* Device + Call API.
|
|
42
|
-
*
|
|
43
|
-
* const device = new Device(tokenResponse);
|
|
44
|
-
* await device.register();
|
|
45
|
-
* const call = await device.connect({ to: "+15551234", from: "+15559999" });
|
|
46
|
-
* device.on("incoming", call => call.accept());
|
|
47
|
-
*
|
|
48
|
-
* Token refresh (REQUIRED for long-lived sessions): voice tokens are short-
|
|
49
|
-
* lived — a token's SIP credential authenticates only until `expires_at`. If
|
|
50
|
-
* you let it lapse, the softphone can no longer re-register and inbound calls
|
|
51
|
-
* stop arriving (they go to voicemail). The Device raises a `tokenWillExpire`
|
|
52
|
-
* event shortly before expiry so you can keep it alive. Mirrors Twilio's
|
|
53
|
-
* Device.updateToken() model:
|
|
54
|
-
*
|
|
55
|
-
* // Manual — fetch a fresh token from your backend and hand it back:
|
|
56
|
-
* device.on("tokenWillExpire", async () => {
|
|
57
|
-
* const fresh = await fetch("/my/backend/voice-token").then((r) => r.json());
|
|
58
|
-
* await device.updateToken(fresh);
|
|
59
|
-
* });
|
|
60
|
-
*
|
|
61
|
-
* // Automatic — let the Device refresh itself:
|
|
62
|
-
* const device = new Device(tokenResponse, {
|
|
63
|
-
* tokenProvider: () => fetch("/my/backend/voice-token").then((r) => r.json()),
|
|
64
|
-
* });
|
|
65
|
-
*
|
|
66
|
-
* Preferred: have your backend call POST /voice/tokens/refresh, which extends
|
|
67
|
-
* the SAME identity in place — the Device then just reschedules and keeps its
|
|
68
|
-
* existing registration (no re-register, seamless). If instead you mint a fresh
|
|
69
|
-
* token (new identity), the Device re-registers under it (break-before-make,
|
|
70
|
-
* deferred while a call is active).
|
|
71
|
-
*
|
|
72
|
-
* Events: "registered", "unregistered", "registrationFailed", "incoming",
|
|
73
|
-
* "connected" (WSS established), "disconnected", "tokenWillExpire",
|
|
74
|
-
* "tokenRefreshFailed", "error".
|
|
75
|
-
*/
|
|
76
|
-
/**
|
|
77
|
-
* Narrow a token-or-credentials argument: a VoiceTokenResponse wraps its SIP credentials under `sip_credentials`.
|
|
78
|
-
* @param {VoiceTokenResponse | SipCredentials} value - The argument to inspect.
|
|
79
|
-
* @returns {value is VoiceTokenResponse} - True when the value is a token response.
|
|
80
|
-
*/
|
|
81
|
-
function isTokenResponse(value) {
|
|
82
|
-
return !!value && typeof value === "object" && "sip_credentials" in value;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
export class Device {
|
|
86
|
-
/**
|
|
87
|
-
* @param {VoiceTokenResponse | SipCredentials} tokenOrCreds
|
|
88
|
-
* @param {Object} [opts]
|
|
89
|
-
* @param {number} [opts.registerExpires=600] - REGISTER expires interval, in seconds.
|
|
90
|
-
* @param {string} [opts.userAgent="SignalHouse-Voice-SDK/0.1"]
|
|
91
|
-
* @param {boolean} [opts.autoRegister=false] - Call register() on construct.
|
|
92
|
-
* @param {number} [opts.tokenRefreshMs=30000] - How long before `expires_at`
|
|
93
|
-
* to raise `tokenWillExpire` (and auto-refresh, when `tokenProvider` is set).
|
|
94
|
-
* @param {() => (VoiceTokenResponse|Promise<VoiceTokenResponse>)} [opts.tokenProvider]
|
|
95
|
-
* Optional. A function YOU supply that returns a fresh token — ideally by
|
|
96
|
-
* calling POST /voice/tokens/refresh through your backend (identity-
|
|
97
|
-
* preserving), or a fresh mint. When set, the Device calls it on
|
|
98
|
-
* `tokenWillExpire` and applies the result via updateToken() automatically.
|
|
99
|
-
*/
|
|
100
|
-
constructor(tokenOrCreds, opts = {}) {
|
|
101
|
-
this._credentials = this._parseCreds(tokenOrCreds, "Device");
|
|
102
|
-
const token = isTokenResponse(tokenOrCreds) ? tokenOrCreds : null;
|
|
103
|
-
this.identity = token?.identity || this._credentials.username;
|
|
104
|
-
this.expiresAt = token?.expires_at || null;
|
|
105
|
-
|
|
106
|
-
this._opts = {
|
|
107
|
-
registerExpires: opts.registerExpires ?? 600,
|
|
108
|
-
userAgent: opts.userAgent ?? "SignalHouse-Voice-SDK/0.1",
|
|
109
|
-
tokenRefreshMs: opts.tokenRefreshMs ?? 30000,
|
|
110
|
-
tokenProvider: typeof opts.tokenProvider === "function" ? opts.tokenProvider : null,
|
|
111
|
-
};
|
|
112
|
-
|
|
113
|
-
this._ua = null;
|
|
114
|
-
this._listeners = new Map();
|
|
115
|
-
this._registered = false;
|
|
116
|
-
this._stopped = false; // set by unregister(); guards in-flight refreshes
|
|
117
|
-
|
|
118
|
-
// Token-refresh state.
|
|
119
|
-
this._refreshTimer = null; // fires `tokenWillExpire` before expiry
|
|
120
|
-
this._activeSessions = new Set(); // in-flight calls; defer an identity swap while busy
|
|
121
|
-
this._pendingToken = null; // identity-change token handed to updateToken() while busy
|
|
122
|
-
this._refreshPendingAuto = false; // tokenProvider refresh deferred while busy
|
|
123
|
-
|
|
124
|
-
if (opts.autoRegister) this.register().catch(() => { /* surfaced via "registrationFailed" event */ });
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
// ─── Public API ─────────────────────────────────────────────────────────
|
|
128
|
-
|
|
129
|
-
/**
|
|
130
|
-
* Open the WSS connection and REGISTER. Resolves on first "registered"
|
|
131
|
-
* event, rejects on first "registrationFailed". On success, schedules the
|
|
132
|
-
* `tokenWillExpire` refresh timer from the current token's `expires_at`.
|
|
133
|
-
* @returns {Promise<void>}
|
|
134
|
-
*/
|
|
135
|
-
register() {
|
|
136
|
-
this._stopped = false; // an intentional (re)start re-arms the device
|
|
137
|
-
if (this._registered) return Promise.resolve();
|
|
138
|
-
if (!this._ua) this._initUA();
|
|
139
|
-
|
|
140
|
-
return new Promise((resolve, reject) => {
|
|
141
|
-
const onOk = () => {
|
|
142
|
-
this._ua.removeListener("registered", onOk);
|
|
143
|
-
this._ua.removeListener("registrationFailed", onFail);
|
|
144
|
-
this._scheduleTokenRefresh();
|
|
145
|
-
resolve();
|
|
146
|
-
};
|
|
147
|
-
const onFail = (e) => {
|
|
148
|
-
this._ua.removeListener("registered", onOk);
|
|
149
|
-
this._ua.removeListener("registrationFailed", onFail);
|
|
150
|
-
reject(new Error(`registrationFailed: ${e?.cause || "unknown"}`));
|
|
151
|
-
};
|
|
152
|
-
this._ua.on("registered", onOk);
|
|
153
|
-
this._ua.on("registrationFailed", onFail);
|
|
154
|
-
this._ua.start();
|
|
155
|
-
});
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
/**
|
|
159
|
-
* Unregister and close the WSS connection. Idempotent. Marks the device
|
|
160
|
-
* stopped so any in-flight token refresh cannot bring it back online, and
|
|
161
|
-
* cancels the refresh timer + pending state.
|
|
162
|
-
* @returns {Promise<void>}
|
|
163
|
-
*/
|
|
164
|
-
unregister() {
|
|
165
|
-
this._stopped = true;
|
|
166
|
-
this._clearTokenRefresh();
|
|
167
|
-
this._pendingToken = null;
|
|
168
|
-
this._refreshPendingAuto = false;
|
|
169
|
-
return this._teardownUA();
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
/**
|
|
173
|
-
* Apply a fresh token so the registration never lapses — call this in
|
|
174
|
-
* response to `tokenWillExpire` (or let `tokenProvider` do it).
|
|
175
|
-
*
|
|
176
|
-
* Identity-preserving fast path: if the token carries the SAME identity +
|
|
177
|
-
* password as the current one (i.e. your backend called POST
|
|
178
|
-
* /voice/tokens/refresh to extend in place), the existing registration is
|
|
179
|
-
* still valid, so the Device just updates `expires_at` and reschedules — no
|
|
180
|
-
* re-register, fully seamless, safe even mid-call.
|
|
181
|
-
*
|
|
182
|
-
* Identity change (a fresh mint): the Device re-registers under the new
|
|
183
|
-
* identity (break-before-make), deferred while a call is active and applied
|
|
184
|
-
* once the last call ends, so live audio is never disrupted.
|
|
185
|
-
*
|
|
186
|
-
* @param {VoiceTokenResponse | SipCredentials} tokenOrCreds
|
|
187
|
-
* @returns {Promise<void>} resolves once applied (or immediately when a swap
|
|
188
|
-
* is deferred behind an active call).
|
|
189
|
-
*/
|
|
190
|
-
async updateToken(tokenOrCreds) {
|
|
191
|
-
const creds = this._parseCreds(tokenOrCreds, "Device.updateToken");
|
|
192
|
-
const token = isTokenResponse(tokenOrCreds) ? tokenOrCreds : null;
|
|
193
|
-
const newIdentity = token?.identity || creds.username;
|
|
194
|
-
|
|
195
|
-
// Identity-preserving fast path — same credential, just extended expiry.
|
|
196
|
-
if (this._ua && this._registered && !this._stopped &&
|
|
197
|
-
newIdentity === this.identity && creds.password === this._credentials.password) {
|
|
198
|
-
this.expiresAt = token?.expires_at || this.expiresAt;
|
|
199
|
-
this._scheduleTokenRefresh();
|
|
200
|
-
return;
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
// Identity changed → full re-register; defer while a call is active.
|
|
204
|
-
if (this._activeSessions.size > 0) {
|
|
205
|
-
this._pendingToken = tokenOrCreds;
|
|
206
|
-
return;
|
|
207
|
-
}
|
|
208
|
-
await this._applyToken(tokenOrCreds);
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
/**
|
|
212
|
-
* Place an outbound call. Returns a Call once the INVITE is sent.
|
|
213
|
-
* The returned Call fires "progress" → "accepted" → "confirmed" as
|
|
214
|
-
* the dialog establishes; listen for those before assuming audio is live.
|
|
215
|
-
*
|
|
216
|
-
* @param {ConnectParams} params
|
|
217
|
-
* @returns {Promise<Call>}
|
|
218
|
-
*/
|
|
219
|
-
async connect({ to, from, mediaStream, pcConfig, extraHeaders = [] } = /** @type {ConnectParams} */ ({})) {
|
|
220
|
-
if (!this._ua || !this._registered) {
|
|
221
|
-
throw new Error("Device.connect: not registered yet — call register() first");
|
|
222
|
-
}
|
|
223
|
-
if (!to) throw new Error("Device.connect: 'to' is required");
|
|
224
|
-
|
|
225
|
-
const target = /^sip:/i.test(to)
|
|
226
|
-
? to
|
|
227
|
-
: `sip:${String(to).replace(/^\+?/, "")}@${this._credentials.domain}`;
|
|
228
|
-
|
|
229
|
-
// P-Preferred-Identity (RFC 3325) — OpenSIPS validates this is an
|
|
230
|
-
// account-owned DID, then uses it as the carrier From header. If
|
|
231
|
-
// not supplied, OpenSIPS falls back to the account's default DID.
|
|
232
|
-
const headers = [...extraHeaders];
|
|
233
|
-
if (from) {
|
|
234
|
-
headers.push(`P-Preferred-Identity: <sip:${from}@${this._credentials.domain}>`);
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
const stream = mediaStream || (await navigator.mediaDevices.getUserMedia({ audio: true, video: false }));
|
|
238
|
-
|
|
239
|
-
// Default to no STUN servers — SignalHouse's rtpengine is configured
|
|
240
|
-
// with `trust-address` (uses the actual source IP from incoming RTP
|
|
241
|
-
// packets rather than the SDP), so host candidates are enough and
|
|
242
|
-
// ICE gathering completes in milliseconds instead of waiting on
|
|
243
|
-
// public STUN. Customers behind restrictive NATs can override via
|
|
244
|
-
// `pcConfig: { iceServers: [{urls: "stun:..."}] }`.
|
|
245
|
-
const session = this._ua.call(target, {
|
|
246
|
-
mediaConstraints: { audio: true, video: false },
|
|
247
|
-
mediaStream: stream,
|
|
248
|
-
pcConfig: pcConfig || { iceServers: [] },
|
|
249
|
-
rtcOfferConstraints: { offerToReceiveAudio: true, offerToReceiveVideo: false },
|
|
250
|
-
extraHeaders: headers,
|
|
251
|
-
});
|
|
252
|
-
|
|
253
|
-
this._trackSession(session);
|
|
254
|
-
return new Call({ session, direction: "outbound" });
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
/**
|
|
258
|
-
* Attach event listener. See class JSDoc for event list.
|
|
259
|
-
*/
|
|
260
|
-
on(event, handler) {
|
|
261
|
-
if (!this._listeners.has(event)) this._listeners.set(event, new Set());
|
|
262
|
-
this._listeners.get(event).add(handler);
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
/**
|
|
266
|
-
* Remove a previously-registered listener.
|
|
267
|
-
*/
|
|
268
|
-
off(event, handler) {
|
|
269
|
-
this._listeners.get(event)?.delete(handler);
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
/** True iff currently REGISTERED. */
|
|
273
|
-
get isRegistered() { return this._registered; }
|
|
274
|
-
|
|
275
|
-
// ─── Internal ───────────────────────────────────────────────────────────
|
|
276
|
-
|
|
277
|
-
_emit(event, payload) {
|
|
278
|
-
for (const fn of this._listeners.get(event) || []) {
|
|
279
|
-
try { fn(payload); }
|
|
280
|
-
catch (err) { console.error(`[Device.${event} handler]`, err); }
|
|
281
|
-
}
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
/**
|
|
285
|
-
* Unwrap `sip_credentials` from a token response (or accept a bare creds
|
|
286
|
-
* object) and validate the four required SIP fields.
|
|
287
|
-
* @param {VoiceTokenResponse | SipCredentials} tokenOrCreds
|
|
288
|
-
* @param {string} ctx - Caller label used in the error message.
|
|
289
|
-
* @returns {SipCredentials}
|
|
290
|
-
* @throws {Error} when a required field is missing.
|
|
291
|
-
*/
|
|
292
|
-
_parseCreds(tokenOrCreds, ctx) {
|
|
293
|
-
const creds = /** @type {SipCredentials} */ (isTokenResponse(tokenOrCreds) ? tokenOrCreds.sip_credentials : tokenOrCreds);
|
|
294
|
-
if (!creds?.username || !creds?.password || !creds?.domain || !creds?.wss_url) {
|
|
295
|
-
throw new Error(`${ctx}: token/credentials missing required fields (username, password, domain, wss_url)`);
|
|
296
|
-
}
|
|
297
|
-
return creds;
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
/**
|
|
301
|
-
* Stop the current UA and close its WSS, without touching lifecycle flags —
|
|
302
|
-
* used both by unregister() and by _applyToken()'s break-before-make swap.
|
|
303
|
-
* @returns {Promise<void>}
|
|
304
|
-
*/
|
|
305
|
-
_teardownUA() {
|
|
306
|
-
if (!this._ua) return Promise.resolve();
|
|
307
|
-
return new Promise((resolve) => {
|
|
308
|
-
const ua = this._ua;
|
|
309
|
-
const done = () => { try { ua.stop(); } catch {} resolve(); };
|
|
310
|
-
if (!this._registered) return done();
|
|
311
|
-
ua.once("unregistered", done);
|
|
312
|
-
try { ua.unregister(); }
|
|
313
|
-
catch { done(); }
|
|
314
|
-
});
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
/**
|
|
318
|
-
* Re-register under fresh credentials when the identity changed
|
|
319
|
-
* (break-before-make). Only invoked when no call is active (updateToken
|
|
320
|
-
* defers while busy). Bails if the app tore the device down mid-swap; if the
|
|
321
|
-
* new registration fails, surfaces `tokenRefreshFailed` and re-arms a short
|
|
322
|
-
* retry so the device recovers rather than sitting unregistered.
|
|
323
|
-
* @param {VoiceTokenResponse | SipCredentials} tokenOrCreds
|
|
324
|
-
*/
|
|
325
|
-
async _applyToken(tokenOrCreds) {
|
|
326
|
-
const creds = this._parseCreds(tokenOrCreds, "Device.updateToken");
|
|
327
|
-
this._clearTokenRefresh();
|
|
328
|
-
try { await this._teardownUA(); } catch { /* ignore — tearing down anyway */ }
|
|
329
|
-
if (this._stopped) return; // unregister() ran while we were tearing down
|
|
330
|
-
|
|
331
|
-
this._ua = null;
|
|
332
|
-
this._registered = false;
|
|
333
|
-
this._credentials = creds;
|
|
334
|
-
const token = isTokenResponse(tokenOrCreds) ? tokenOrCreds : null;
|
|
335
|
-
this.identity = token?.identity || creds.username;
|
|
336
|
-
this.expiresAt = token?.expires_at || null;
|
|
337
|
-
|
|
338
|
-
try {
|
|
339
|
-
await this.register(); // rebuilds the UA + reschedules the refresh timer
|
|
340
|
-
} catch (err) {
|
|
341
|
-
this._emit("tokenRefreshFailed", { error: err });
|
|
342
|
-
if (!this._stopped) {
|
|
343
|
-
this._clearTokenRefresh();
|
|
344
|
-
this._refreshTimer = setTimeout(() => this._onTokenWillExpire(), 5000);
|
|
345
|
-
}
|
|
346
|
-
throw err; // propagate to a manual updateToken() caller
|
|
347
|
-
}
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
/** `expires_at` as epoch ms, or null when unparseable/absent. */
|
|
351
|
-
_expiresAtMs() {
|
|
352
|
-
const t = Date.parse(this.expiresAt || "");
|
|
353
|
-
return Number.isFinite(t) ? t : null;
|
|
354
|
-
}
|
|
355
|
-
|
|
356
|
-
/**
|
|
357
|
-
* True if the given token has too little life left to safely apply (would
|
|
358
|
-
* expire within tokenRefreshMs). Tokens with no parseable expiry are treated
|
|
359
|
-
* as usable.
|
|
360
|
-
* @param {VoiceTokenResponse | SipCredentials} tokenOrCreds
|
|
361
|
-
* @returns {boolean}
|
|
362
|
-
*/
|
|
363
|
-
_isTokenStale(tokenOrCreds) {
|
|
364
|
-
const exp = Date.parse((isTokenResponse(tokenOrCreds) && tokenOrCreds.expires_at) || "");
|
|
365
|
-
if (!Number.isFinite(exp)) return false;
|
|
366
|
-
return exp - Date.now() <= this._opts.tokenRefreshMs;
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
/** Arm the one-shot `tokenWillExpire` timer for tokenRefreshMs before expiry. */
|
|
370
|
-
_scheduleTokenRefresh() {
|
|
371
|
-
this._clearTokenRefresh();
|
|
372
|
-
const expMs = this._expiresAtMs();
|
|
373
|
-
if (expMs === null) return; // no expiry info → caller manages refresh manually
|
|
374
|
-
const delay = Math.max(0, expMs - Date.now() - this._opts.tokenRefreshMs);
|
|
375
|
-
this._refreshTimer = setTimeout(() => this._onTokenWillExpire(), delay);
|
|
376
|
-
}
|
|
377
|
-
|
|
378
|
-
/** Cancel the pending `tokenWillExpire` timer, if any. */
|
|
379
|
-
_clearTokenRefresh() {
|
|
380
|
-
if (this._refreshTimer) { clearTimeout(this._refreshTimer); this._refreshTimer = null; }
|
|
381
|
-
}
|
|
382
|
-
|
|
383
|
-
/**
|
|
384
|
-
* Fired shortly before the current token expires. Emits `tokenWillExpire`
|
|
385
|
-
* for manual handlers; if a `tokenProvider` is configured, also fetches a
|
|
386
|
-
* fresh token and applies it. Deferred while a call is active (the fetch
|
|
387
|
-
* happens only once idle, so a fetched token can't go stale in hand). Bails
|
|
388
|
-
* if the device was torn down while the fetch was in flight.
|
|
389
|
-
*/
|
|
390
|
-
async _onTokenWillExpire() {
|
|
391
|
-
if (this._stopped) return;
|
|
392
|
-
this._emit("tokenWillExpire", { identity: this.identity, expiresAt: this.expiresAt });
|
|
393
|
-
if (!this._opts.tokenProvider) return; // app handles it via updateToken()
|
|
394
|
-
if (this._activeSessions.size > 0) {
|
|
395
|
-
this._refreshPendingAuto = true; // fetch + apply once the call ends
|
|
396
|
-
return;
|
|
397
|
-
}
|
|
398
|
-
try {
|
|
399
|
-
const fresh = await this._opts.tokenProvider();
|
|
400
|
-
if (this._stopped) return; // torn down while the provider fetch was pending
|
|
401
|
-
if (!fresh) throw new Error("tokenProvider returned no token");
|
|
402
|
-
await this.updateToken(fresh);
|
|
403
|
-
} catch (err) {
|
|
404
|
-
if (this._stopped) return;
|
|
405
|
-
this._emit("tokenRefreshFailed", { error: err });
|
|
406
|
-
// Retry shortly so a transient failure doesn't strand us, provided
|
|
407
|
-
// there's still time before the current token expires.
|
|
408
|
-
const expMs = this._expiresAtMs();
|
|
409
|
-
if (expMs !== null && expMs - Date.now() > 5000) {
|
|
410
|
-
this._clearTokenRefresh();
|
|
411
|
-
this._refreshTimer = setTimeout(() => this._onTokenWillExpire(), 5000);
|
|
412
|
-
}
|
|
413
|
-
}
|
|
414
|
-
}
|
|
415
|
-
|
|
416
|
-
/** Track a call session so an identity swap can be deferred until it ends. */
|
|
417
|
-
_trackSession(session) {
|
|
418
|
-
if (!session) return;
|
|
419
|
-
this._activeSessions.add(session);
|
|
420
|
-
const done = () => this._untrackSession(session);
|
|
421
|
-
try { session.on("ended", done); session.on("failed", done); }
|
|
422
|
-
catch { /* not a JsSIP session — best-effort tracking only */ }
|
|
423
|
-
}
|
|
424
|
-
|
|
425
|
-
/**
|
|
426
|
-
* Stop tracking a finished session. When the line goes fully idle, apply any
|
|
427
|
-
* token refresh that was deferred behind the call: a `tokenProvider` fetch
|
|
428
|
-
* (fresh) or a stored identity-change token — re-fetching instead if that
|
|
429
|
-
* stored token has gone stale while the call ran.
|
|
430
|
-
* @param {object} session - The JsSIP session that ended/failed.
|
|
431
|
-
*/
|
|
432
|
-
_untrackSession(session) {
|
|
433
|
-
this._activeSessions.delete(session);
|
|
434
|
-
if (this._activeSessions.size > 0 || this._stopped) return;
|
|
435
|
-
|
|
436
|
-
if (this._refreshPendingAuto) {
|
|
437
|
-
this._refreshPendingAuto = false;
|
|
438
|
-
this._onTokenWillExpire();
|
|
439
|
-
} else if (this._pendingToken) {
|
|
440
|
-
const pending = this._pendingToken;
|
|
441
|
-
this._pendingToken = null;
|
|
442
|
-
// A long call can outlive the token we stashed — don't register with
|
|
443
|
-
// stale creds; get a fresh one the same way the timer would.
|
|
444
|
-
if (this._isTokenStale(pending)) {
|
|
445
|
-
this._onTokenWillExpire();
|
|
446
|
-
} else {
|
|
447
|
-
this._applyToken(pending).catch((err) => this._emit("tokenRefreshFailed", { error: err }));
|
|
448
|
-
}
|
|
449
|
-
}
|
|
450
|
-
}
|
|
451
|
-
|
|
452
|
-
_initUA() {
|
|
453
|
-
const socket = new JsSIP.WebSocketInterface(this._credentials.wss_url);
|
|
454
|
-
this._ua = new JsSIP.UA({
|
|
455
|
-
sockets: [socket],
|
|
456
|
-
uri: `sip:${this._credentials.username}@${this._credentials.domain}`,
|
|
457
|
-
password: this._credentials.password,
|
|
458
|
-
register: true,
|
|
459
|
-
register_expires: this._opts.registerExpires,
|
|
460
|
-
user_agent: this._opts.userAgent,
|
|
461
|
-
});
|
|
462
|
-
|
|
463
|
-
this._ua.on("connecting", () => this._emit("connecting"));
|
|
464
|
-
this._ua.on("connected", () => this._emit("connected"));
|
|
465
|
-
this._ua.on("disconnected", (e) => this._emit("disconnected", { reason: e?.reason }));
|
|
466
|
-
this._ua.on("registered", () => { this._registered = true; this._emit("registered"); });
|
|
467
|
-
this._ua.on("unregistered", () => { this._registered = false; this._emit("unregistered"); });
|
|
468
|
-
this._ua.on("registrationFailed", (e) => {
|
|
469
|
-
this._registered = false;
|
|
470
|
-
this._emit("registrationFailed", {
|
|
471
|
-
cause: e?.cause,
|
|
472
|
-
statusCode: e?.response?.status_code,
|
|
473
|
-
reason: e?.response?.reason_phrase,
|
|
474
|
-
});
|
|
475
|
-
});
|
|
476
|
-
|
|
477
|
-
this._ua.on("newRTCSession", (e) => {
|
|
478
|
-
if (e.originator !== "remote") return; // outbound: we already wrap in connect()
|
|
479
|
-
this._trackSession(e.session);
|
|
480
|
-
const call = new Call({ session: e.session, direction: "inbound", request: e.request });
|
|
481
|
-
this._emit("incoming", call);
|
|
482
|
-
});
|
|
483
|
-
}
|
|
484
|
-
}
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Browser-only entry point for the SignalHouse voice SDK.
|
|
3
|
-
*
|
|
4
|
-
* Imported as a subpath:
|
|
5
|
-
*
|
|
6
|
-
* import { Device } from "@signalhousellc/sdk/voice-browser";
|
|
7
|
-
*
|
|
8
|
-
* Loads JsSIP transitively. Node-only consumers should NOT import this
|
|
9
|
-
* subpath; the REST surface (`sdk.voice.calls`, `sdk.voice.tokens`, etc.)
|
|
10
|
-
* is exported from the package root and is JsSIP-free.
|
|
11
|
-
*
|
|
12
|
-
* Pairs with `sdk.voice.tokens.create()` from the REST surface — call that
|
|
13
|
-
* server-side to mint a token, hand the response to `new Device(token)`
|
|
14
|
-
* in the browser.
|
|
15
|
-
*/
|
|
16
|
-
export { Device } from "./Device.js";
|
|
17
|
-
export { Call } from "./Call.js";
|
|
@@ -1,66 +0,0 @@
|
|
|
1
|
-
import crypto from "node:crypto";
|
|
2
|
-
|
|
3
|
-
// Node-only helpers for receiving Signal House webhooks (SHGHL-3486). Kept out of the main entry point,
|
|
4
|
-
// which also runs in browsers, because it depends on node:crypto. Import from "@signalhousellc/sdk/webhooks".
|
|
5
|
-
|
|
6
|
-
const DEFAULT_TOLERANCE_MS = 5 * 60 * 1000;
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* Verify that a webhook delivery came from Signal House and is recent.
|
|
10
|
-
*
|
|
11
|
-
* Checks `X-SignalHouse-Signature-V1` (`t=<ms>,v1=<hex>[,v1=<hex>]`, which carries every currently valid
|
|
12
|
-
* signature during a secret rotation) when present, otherwise the original `X-SignalHouse-Signature` +
|
|
13
|
-
* `X-SignalHouse-Timestamp` pair. Each signature is a hex HMAC-SHA256 of `${timestamp}.${rawBody}`. Comparisons
|
|
14
|
-
* are constant-time.
|
|
15
|
-
*
|
|
16
|
-
* @param {Object} params
|
|
17
|
-
* @param {string|Buffer} params.rawBody - The exact request body as received, before any JSON parsing.
|
|
18
|
-
* @param {Object} params.headers - Request headers (any casing; e.g. Express `req.headers`).
|
|
19
|
-
* @param {string} [params.secret] - Your endpoint's signing secret.
|
|
20
|
-
* @param {string[]} [params.secrets] - Several secrets to accept, e.g. old and new while you roll over.
|
|
21
|
-
* @param {number} [params.toleranceMs=300000] - Reject deliveries whose timestamp is further than this from now.
|
|
22
|
-
* @param {number} [params.now=Date.now()] - Current time in ms (for tests).
|
|
23
|
-
* @returns {{valid: boolean, reason?: string}} - `valid` true when a signature matches within the time window;
|
|
24
|
-
* otherwise `reason` is one of `no_secret`, `no_signature`, `bad_timestamp`, `stale_timestamp`, `bad_signature`.
|
|
25
|
-
*/
|
|
26
|
-
export function verifyWebhookSignature({ rawBody, headers, secret, secrets, toleranceMs = DEFAULT_TOLERANCE_MS, now = Date.now() }) {
|
|
27
|
-
const candidates = (secrets ?? (secret ? [secret] : [])).filter(Boolean);
|
|
28
|
-
if (candidates.length === 0) return { valid: false, reason: "no_secret" };
|
|
29
|
-
|
|
30
|
-
const header = (name) => {
|
|
31
|
-
if (!headers) return undefined;
|
|
32
|
-
const match = Object.keys(headers).find((key) => key.toLowerCase() === name);
|
|
33
|
-
const value = match === undefined ? undefined : headers[match];
|
|
34
|
-
return Array.isArray(value) ? value[0] : value;
|
|
35
|
-
};
|
|
36
|
-
|
|
37
|
-
let timestamp;
|
|
38
|
-
let signatures = [];
|
|
39
|
-
const v1 = header("x-signalhouse-signature-v1");
|
|
40
|
-
if (v1) {
|
|
41
|
-
const parts = String(v1).split(",").map((part) => part.trim());
|
|
42
|
-
timestamp = parts.find((part) => part.startsWith("t="))?.slice(2);
|
|
43
|
-
signatures = parts.filter((part) => part.startsWith("v1=")).map((part) => part.slice(3)).filter(Boolean);
|
|
44
|
-
}
|
|
45
|
-
// No usable V1 (absent, or mangled by an intermediary): fall back to the original header pair
|
|
46
|
-
if (signatures.length === 0) {
|
|
47
|
-
timestamp = header("x-signalhouse-timestamp");
|
|
48
|
-
const legacy = header("x-signalhouse-signature");
|
|
49
|
-
signatures = legacy ? [String(legacy)] : [];
|
|
50
|
-
}
|
|
51
|
-
if (signatures.length === 0) return { valid: false, reason: "no_signature" };
|
|
52
|
-
|
|
53
|
-
const sentAt = Number(timestamp);
|
|
54
|
-
if (!timestamp || !Number.isFinite(sentAt)) return { valid: false, reason: "bad_timestamp" };
|
|
55
|
-
if (Math.abs(now - sentAt) > toleranceMs) return { valid: false, reason: "stale_timestamp" };
|
|
56
|
-
|
|
57
|
-
const body = Buffer.isBuffer(rawBody) ? rawBody.toString("utf8") : String(rawBody ?? "");
|
|
58
|
-
for (const candidate of candidates) {
|
|
59
|
-
const expected = Buffer.from(crypto.createHmac("sha256", candidate).update(`${timestamp}.${body}`).digest("hex"), "utf8");
|
|
60
|
-
for (const signature of signatures) {
|
|
61
|
-
const given = Buffer.from(signature, "utf8");
|
|
62
|
-
if (given.length === expected.length && crypto.timingSafeEqual(given, expected)) return { valid: true };
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
return { valid: false, reason: "bad_signature" };
|
|
66
|
-
}
|