ringcentral-softphone 1.3.2 → 1.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/README.md +1 -1
  2. package/dist/call-session/inbound.cjs +93 -0
  3. package/dist/call-session/inbound.js +64 -0
  4. package/dist/call-session/index.cjs +270 -0
  5. package/dist/{esm/call-session → call-session}/index.d.ts +3 -3
  6. package/dist/call-session/index.js +244 -0
  7. package/dist/call-session/outbound.cjs +100 -0
  8. package/dist/call-session/outbound.js +71 -0
  9. package/dist/call-session/streamer.cjs +112 -0
  10. package/dist/call-session/streamer.js +83 -0
  11. package/dist/codec.cjs +85 -0
  12. package/dist/codec.js +66 -0
  13. package/dist/dtmf.cjs +65 -0
  14. package/dist/dtmf.js +46 -0
  15. package/dist/index.cjs +258 -0
  16. package/dist/{cjs/index.d.ts → index.d.ts} +3 -3
  17. package/dist/index.js +240 -0
  18. package/dist/sip-message/inbound/index.cjs +51 -0
  19. package/dist/sip-message/inbound/index.js +22 -0
  20. package/dist/sip-message/index.cjs +49 -0
  21. package/dist/sip-message/index.js +12 -0
  22. package/dist/sip-message/outbound/index.cjs +41 -0
  23. package/dist/sip-message/outbound/index.js +12 -0
  24. package/dist/sip-message/outbound/request.cjs +62 -0
  25. package/dist/sip-message/outbound/request.js +33 -0
  26. package/dist/sip-message/outbound/response.cjs +55 -0
  27. package/dist/sip-message/outbound/response.js +26 -0
  28. package/dist/sip-message/response-codes.cjs +102 -0
  29. package/dist/sip-message/response-codes.js +83 -0
  30. package/dist/sip-message/sip-message.cjs +53 -0
  31. package/dist/sip-message/sip-message.js +34 -0
  32. package/dist/types.cjs +15 -0
  33. package/dist/types.js +0 -0
  34. package/dist/utils.cjs +80 -0
  35. package/dist/{cjs/utils.d.ts → utils.d.ts} +2 -2
  36. package/dist/utils.js +41 -0
  37. package/package.json +19 -13
  38. package/dist/cjs/call-session/inbound.js +0 -57
  39. package/dist/cjs/call-session/index.d.ts +0 -44
  40. package/dist/cjs/call-session/index.js +0 -239
  41. package/dist/cjs/call-session/outbound.js +0 -66
  42. package/dist/cjs/call-session/streamer.d.ts +0 -17
  43. package/dist/cjs/call-session/streamer.js +0 -76
  44. package/dist/cjs/codec.js +0 -65
  45. package/dist/cjs/dtmf.js +0 -45
  46. package/dist/cjs/index.js +0 -209
  47. package/dist/cjs/sip-message/inbound/index.js +0 -22
  48. package/dist/cjs/sip-message/index.d.ts +0 -5
  49. package/dist/cjs/sip-message/index.js +0 -16
  50. package/dist/cjs/sip-message/outbound/index.js +0 -14
  51. package/dist/cjs/sip-message/outbound/request.js +0 -28
  52. package/dist/cjs/sip-message/outbound/response.js +0 -25
  53. package/dist/cjs/sip-message/response-codes.js +0 -83
  54. package/dist/cjs/sip-message/sip-message.js +0 -34
  55. package/dist/cjs/types.js +0 -2
  56. package/dist/cjs/utils.js +0 -40
  57. package/dist/esm/call-session/inbound.d.ts +0 -8
  58. package/dist/esm/call-session/inbound.js +0 -52
  59. package/dist/esm/call-session/index.js +0 -234
  60. package/dist/esm/call-session/outbound.d.ts +0 -11
  61. package/dist/esm/call-session/outbound.js +0 -61
  62. package/dist/esm/call-session/streamer.js +0 -71
  63. package/dist/esm/codec.d.ts +0 -15
  64. package/dist/esm/codec.js +0 -63
  65. package/dist/esm/dtmf.d.ts +0 -8
  66. package/dist/esm/dtmf.js +0 -43
  67. package/dist/esm/index.d.ts +0 -28
  68. package/dist/esm/index.js +0 -204
  69. package/dist/esm/sip-message/inbound/index.d.ts +0 -5
  70. package/dist/esm/sip-message/inbound/index.js +0 -17
  71. package/dist/esm/sip-message/index.js +0 -5
  72. package/dist/esm/sip-message/outbound/index.d.ts +0 -5
  73. package/dist/esm/sip-message/outbound/index.js +0 -9
  74. package/dist/esm/sip-message/outbound/request.d.ts +0 -7
  75. package/dist/esm/sip-message/outbound/request.js +0 -23
  76. package/dist/esm/sip-message/outbound/response.d.ts +0 -6
  77. package/dist/esm/sip-message/outbound/response.js +0 -20
  78. package/dist/esm/sip-message/response-codes.d.ts +0 -4
  79. package/dist/esm/sip-message/response-codes.js +0 -81
  80. package/dist/esm/sip-message/sip-message.d.ts +0 -11
  81. package/dist/esm/sip-message/sip-message.js +0 -32
  82. package/dist/esm/types.d.ts +0 -9
  83. package/dist/esm/types.js +0 -1
  84. package/dist/esm/utils.d.ts +0 -8
  85. package/dist/esm/utils.js +0 -28
  86. package/dist/{cjs/call-session → call-session}/inbound.d.ts +2 -2
  87. package/dist/{cjs/call-session → call-session}/outbound.d.ts +2 -2
  88. package/dist/{esm/call-session → call-session}/streamer.d.ts +1 -1
  89. package/dist/{cjs/codec.d.ts → codec.d.ts} +0 -0
  90. package/dist/{cjs/dtmf.d.ts → dtmf.d.ts} +0 -0
  91. package/dist/{cjs/sip-message → sip-message}/inbound/index.d.ts +0 -0
  92. package/dist/{esm/sip-message → sip-message}/index.d.ts +2 -2
  93. package/dist/{cjs/sip-message → sip-message}/outbound/index.d.ts +0 -0
  94. package/dist/{cjs/sip-message → sip-message}/outbound/request.d.ts +0 -0
  95. package/dist/{cjs/sip-message → sip-message}/outbound/response.d.ts +1 -1
  96. /package/dist/{cjs/sip-message → sip-message}/response-codes.d.ts +0 -0
  97. /package/dist/{cjs/sip-message → sip-message}/sip-message.d.ts +0 -0
  98. /package/dist/{cjs/types.d.ts → types.d.ts} +0 -0
package/dist/codec.js ADDED
@@ -0,0 +1,66 @@
1
+ import { Buffer } from "node:buffer";
2
+ import { Decoder, Encoder } from "@evan/opus";
3
+ class Codec {
4
+ id;
5
+ name;
6
+ packetSize;
7
+ timestampInterval;
8
+ createEncoder;
9
+ createDecoder;
10
+ constructor(name) {
11
+ this.name = name;
12
+ switch (name) {
13
+ case "OPUS/16000": {
14
+ this.createEncoder = () => {
15
+ const encoder = new Encoder({ channels: 1, sample_rate: 16e3 });
16
+ return { encode: (pcm) => Buffer.from(encoder.encode(pcm)) };
17
+ };
18
+ this.createDecoder = () => {
19
+ const decoder = new Decoder({ channels: 1, sample_rate: 16e3 });
20
+ return {
21
+ decode: (opus) => Buffer.from(decoder.decode(opus))
22
+ };
23
+ };
24
+ this.id = 109;
25
+ this.packetSize = 640;
26
+ this.timestampInterval = 320;
27
+ break;
28
+ }
29
+ case "OPUS/48000/2": {
30
+ this.createEncoder = () => {
31
+ const encoder = new Encoder({ channels: 2, sample_rate: 48e3 });
32
+ return { encode: (pcm) => Buffer.from(encoder.encode(pcm)) };
33
+ };
34
+ this.createDecoder = () => {
35
+ const decoder = new Decoder({ channels: 2, sample_rate: 48e3 });
36
+ return {
37
+ decode: (opus) => Buffer.from(decoder.decode(opus))
38
+ };
39
+ };
40
+ this.id = 111;
41
+ this.packetSize = 3840;
42
+ this.timestampInterval = 960;
43
+ break;
44
+ }
45
+ case "PCMU/8000": {
46
+ this.createEncoder = () => {
47
+ return { encode: (pcm) => pcm };
48
+ };
49
+ this.createDecoder = () => {
50
+ return { decode: (audio) => audio };
51
+ };
52
+ this.id = 0;
53
+ this.packetSize = 160;
54
+ this.timestampInterval = 160;
55
+ break;
56
+ }
57
+ default: {
58
+ throw new Error(`unsupported codec: ${name}`);
59
+ }
60
+ }
61
+ }
62
+ }
63
+ var codec_default = Codec;
64
+ export {
65
+ codec_default as default
66
+ };
package/dist/dtmf.cjs ADDED
@@ -0,0 +1,65 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+ var dtmf_exports = {};
19
+ __export(dtmf_exports, {
20
+ default: () => dtmf_default
21
+ });
22
+ module.exports = __toCommonJS(dtmf_exports);
23
+ var import_node_buffer = require("node:buffer");
24
+ class DTMF {
25
+ static phoneChars = [
26
+ "0",
27
+ "1",
28
+ "2",
29
+ "3",
30
+ "4",
31
+ "5",
32
+ "6",
33
+ "7",
34
+ "8",
35
+ "9",
36
+ "*",
37
+ "#"
38
+ ];
39
+ static payloads = [
40
+ 393216,
41
+ 393376,
42
+ 393536,
43
+ 8782624,
44
+ 8782624,
45
+ 8782624
46
+ ];
47
+ static charToPayloads = (char) => {
48
+ const index = DTMF.phoneChars.indexOf(char[0]);
49
+ if (index === -1) {
50
+ throw new Error("invalid phone char");
51
+ }
52
+ return DTMF.payloads.map((payload) => {
53
+ const temp = payload + index * 16777216;
54
+ const buffer = import_node_buffer.Buffer.alloc(4);
55
+ buffer.writeIntBE(temp, 0, 4);
56
+ return buffer;
57
+ });
58
+ };
59
+ static payloadToChar = (payload) => {
60
+ const intBE = payload.readIntBE(0, 4);
61
+ const index = (intBE - 393216) / 16777216;
62
+ return DTMF.phoneChars[index];
63
+ };
64
+ }
65
+ var dtmf_default = DTMF;
package/dist/dtmf.js ADDED
@@ -0,0 +1,46 @@
1
+ import { Buffer } from "node:buffer";
2
+ class DTMF {
3
+ static phoneChars = [
4
+ "0",
5
+ "1",
6
+ "2",
7
+ "3",
8
+ "4",
9
+ "5",
10
+ "6",
11
+ "7",
12
+ "8",
13
+ "9",
14
+ "*",
15
+ "#"
16
+ ];
17
+ static payloads = [
18
+ 393216,
19
+ 393376,
20
+ 393536,
21
+ 8782624,
22
+ 8782624,
23
+ 8782624
24
+ ];
25
+ static charToPayloads = (char) => {
26
+ const index = DTMF.phoneChars.indexOf(char[0]);
27
+ if (index === -1) {
28
+ throw new Error("invalid phone char");
29
+ }
30
+ return DTMF.payloads.map((payload) => {
31
+ const temp = payload + index * 16777216;
32
+ const buffer = Buffer.alloc(4);
33
+ buffer.writeIntBE(temp, 0, 4);
34
+ return buffer;
35
+ });
36
+ };
37
+ static payloadToChar = (payload) => {
38
+ const intBE = payload.readIntBE(0, 4);
39
+ const index = (intBE - 393216) / 16777216;
40
+ return DTMF.phoneChars[index];
41
+ };
42
+ }
43
+ var dtmf_default = DTMF;
44
+ export {
45
+ dtmf_default as default
46
+ };
package/dist/index.cjs ADDED
@@ -0,0 +1,258 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+ var index_exports = {};
29
+ __export(index_exports, {
30
+ default: () => index_default
31
+ });
32
+ module.exports = __toCommonJS(index_exports);
33
+ var import_node_events = __toESM(require("node:events"), 1);
34
+ var import_node_tls = __toESM(require("node:tls"), 1);
35
+ var import_wait_for_async = __toESM(require("wait-for-async"), 1);
36
+ var import_inbound = __toESM(require("./call-session/inbound.js"), 1);
37
+ var import_outbound = __toESM(require("./call-session/outbound.js"), 1);
38
+ var import_codec = __toESM(require("./codec.js"), 1);
39
+ var import_sip_message = require("./sip-message/index.js");
40
+ var import_utils = require("./utils.js");
41
+ class Softphone extends import_node_events.default {
42
+ sipInfo;
43
+ client;
44
+ codec;
45
+ fakeDomain = `${(0, import_utils.uuid)()}.invalid`;
46
+ fakeEmail = `${(0, import_utils.uuid)()}@${this.fakeDomain}`;
47
+ intervalHandle;
48
+ connected = false;
49
+ constructor(sipInfo) {
50
+ super();
51
+ if (sipInfo.codec === void 0) {
52
+ sipInfo.codec = "OPUS/16000";
53
+ }
54
+ this.codec = new import_codec.default(sipInfo.codec);
55
+ this.sipInfo = sipInfo;
56
+ if (this.sipInfo.domain === void 0) {
57
+ this.sipInfo.domain = "sip.ringcentral.com";
58
+ }
59
+ if (this.sipInfo.outboundProxy === void 0) {
60
+ this.sipInfo.outboundProxy = "sip10.ringcentral.com:5096";
61
+ }
62
+ const tokens = this.sipInfo.outboundProxy.split(":");
63
+ this.client = import_node_tls.default.connect(
64
+ {
65
+ host: tokens[0],
66
+ port: parseInt(tokens[1], 10),
67
+ rejectUnauthorized: !this.sipInfo.ignoreTlsCertErrors
68
+ },
69
+ () => {
70
+ this.connected = true;
71
+ }
72
+ );
73
+ let cache = "";
74
+ this.client.on("data", (data) => {
75
+ cache += data.toString("utf-8");
76
+ if (!cache.endsWith("\r\n")) {
77
+ return;
78
+ }
79
+ const tempMessages = cache.split("\r\nContent-Length: 0\r\n\r\n").filter((message) => message.trim() !== "");
80
+ cache = "";
81
+ for (let i = 0; i < tempMessages.length; i++) {
82
+ if (!tempMessages[i].includes("Content-Length: ")) {
83
+ tempMessages[i] = `${tempMessages[i]}\r
84
+ Content-Length: 0`;
85
+ }
86
+ }
87
+ for (const message of tempMessages) {
88
+ this.emit("message", import_sip_message.InboundMessage.fromString(message));
89
+ }
90
+ });
91
+ }
92
+ instanceId = (0, import_utils.uuid)();
93
+ registerCallId = (0, import_utils.uuid)();
94
+ async register() {
95
+ if (!this.connected) {
96
+ await (0, import_wait_for_async.default)({
97
+ interval: 100,
98
+ times: 100,
99
+ condition: () => this.connected
100
+ });
101
+ if (!this.connected) {
102
+ throw new Error("Failed to register: connect to TLS timeout");
103
+ }
104
+ }
105
+ const sipRegister = async () => {
106
+ const fromTag = (0, import_utils.uuid)();
107
+ const requestMessage = new import_sip_message.RequestMessage(
108
+ `REGISTER sip:${this.sipInfo.domain} SIP/2.0`,
109
+ {
110
+ Via: `SIP/2.0/TLS ${this.client.localAddress}:${this.client.localPort};rport;branch=${(0, import_utils.branch)()};alias`,
111
+ "Max-Forwards": "70",
112
+ From: `<sip:${this.sipInfo.username}@${this.sipInfo.domain}>;tag=${fromTag}`,
113
+ To: `<sip:${this.sipInfo.username}@${this.sipInfo.domain}>`,
114
+ "Call-ID": this.registerCallId,
115
+ Contact: `<sip:${this.sipInfo.username}@${this.client.localAddress}:${this.client.localPort};transport=TLS;ob>;reg-id=1;+sip.instance="<urn:uuid:${this.instanceId}>"`,
116
+ Expires: 3600,
117
+ Allow: "PRACK, INVITE, ACK, BYE, CANCEL, UPDATE, INFO, SUBSCRIBE, NOTIFY, REFER, MESSAGE, OPTIONS"
118
+ }
119
+ );
120
+ const inboundMessage = await this.send(requestMessage, true);
121
+ if (inboundMessage.subject.startsWith("SIP/2.0 200 ")) {
122
+ return;
123
+ }
124
+ const wwwAuth = inboundMessage.getHeader("Www-Authenticate");
125
+ const nonce = wwwAuth.match(/, nonce="(.+?)"/)[1];
126
+ const newMessage = requestMessage.fork();
127
+ newMessage.headers.Authorization = (0, import_utils.generateAuthorization)(
128
+ this.sipInfo,
129
+ nonce,
130
+ "REGISTER"
131
+ );
132
+ const message = await this.send(newMessage, true);
133
+ if (!message.subject.startsWith("SIP/2.0 200 ")) {
134
+ throw new Error(`Failed to register: ${message.subject}`);
135
+ }
136
+ };
137
+ await sipRegister();
138
+ this.intervalHandle = setInterval(
139
+ () => {
140
+ sipRegister();
141
+ },
142
+ 30 * 1e3
143
+ // refresh registration every 30 seconds
144
+ );
145
+ this.on("message", (inboundMessage) => {
146
+ if (!inboundMessage.subject.startsWith("INVITE sip:")) {
147
+ return;
148
+ }
149
+ const outboundMessage = new import_sip_message.OutboundMessage("SIP/2.0 100 Trying", {
150
+ Via: inboundMessage.headers.Via,
151
+ "Call-ID": inboundMessage.getHeader("Call-ID"),
152
+ From: inboundMessage.headers.From,
153
+ To: inboundMessage.headers.To,
154
+ CSeq: inboundMessage.headers.CSeq,
155
+ "Content-Length": "0"
156
+ });
157
+ this.send(outboundMessage);
158
+ this.emit("invite", inboundMessage);
159
+ });
160
+ }
161
+ enableDebugMode() {
162
+ this.on(
163
+ "message",
164
+ (message) => console.log(`Receiving...(${/* @__PURE__ */ new Date()})
165
+ ${message.toString()}`)
166
+ );
167
+ const tlsWrite = this.client.write.bind(this.client);
168
+ this.client.write = (message) => {
169
+ console.log(`Sending...(${/* @__PURE__ */ new Date()})
170
+ ${message}`);
171
+ return tlsWrite(message);
172
+ };
173
+ }
174
+ revoke() {
175
+ clearInterval(this.intervalHandle);
176
+ this.removeAllListeners();
177
+ this.client.removeAllListeners();
178
+ this.client.destroy();
179
+ }
180
+ send(message, waitForReply = false) {
181
+ this.client.write(message.toString());
182
+ if (!waitForReply) {
183
+ return new Promise((resolve) => {
184
+ resolve(void 0);
185
+ });
186
+ }
187
+ return new Promise((resolve) => {
188
+ const messageListerner = (inboundMessage) => {
189
+ if (inboundMessage.headers.CSeq.trim().split(/\s+/)[0] !== message.headers.CSeq.trim().split(/\s+/)[0]) {
190
+ return;
191
+ }
192
+ if (inboundMessage.subject.startsWith("SIP/2.0 100 ")) {
193
+ return;
194
+ }
195
+ this.off("message", messageListerner);
196
+ resolve(inboundMessage);
197
+ };
198
+ this.on("message", messageListerner);
199
+ });
200
+ }
201
+ async answer(inviteMessage) {
202
+ const inboundCallSession = new import_inbound.default(this, inviteMessage);
203
+ await inboundCallSession.answer();
204
+ return inboundCallSession;
205
+ }
206
+ // decline an inbound call
207
+ async decline(inviteMessage) {
208
+ const newMessage = new import_sip_message.ResponseMessage(inviteMessage, 603);
209
+ await this.send(newMessage);
210
+ }
211
+ async call(callee) {
212
+ const offerSDP = `
213
+ v=0
214
+ o=- ${Date.now()} 0 IN IP4 ${this.client.localAddress}
215
+ s=rc-softphone-ts
216
+ c=IN IP4 ${this.client.localAddress}
217
+ t=0 0
218
+ m=audio ${(0, import_utils.randomInt)()} RTP/SAVP ${this.codec.id} 101
219
+ a=rtpmap:${this.codec.id} ${this.codec.name}
220
+ a=rtpmap:101 telephone-event/8000
221
+ a=fmtp:101 0-15
222
+ a=sendrecv
223
+ a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:${import_utils.localKey}
224
+ `.trim();
225
+ const inviteMessage = new import_sip_message.RequestMessage(
226
+ `INVITE sip:${callee}@${this.sipInfo.domain} SIP/2.0`,
227
+ {
228
+ Via: `SIP/2.0/TLS ${this.client.localAddress}:${this.client.localPort};rport;branch=${(0, import_utils.branch)()};alias`,
229
+ "Max-Forwards": 70,
230
+ From: `<sip:${this.sipInfo.username}@${this.sipInfo.domain}>;tag=${(0, import_utils.uuid)()}`,
231
+ To: `<sip:${callee}@sip.ringcentral.com>`,
232
+ Contact: ` <sip:${this.sipInfo.username}@${this.client.localAddress}:${this.client.localPort};transport=TLS;ob>`,
233
+ "Call-ID": (0, import_utils.uuid)(),
234
+ Route: `<sip:${this.sipInfo.outboundProxy};transport=tls;lr>`,
235
+ Allow: `PRACK, INVITE, ACK, BYE, CANCEL, UPDATE, INFO, SUBSCRIBE, NOTIFY, REFER, MESSAGE, OPTIONS`,
236
+ Supported: `replaces, 100rel, timer, norefersub`,
237
+ "Session-Expires": 1800,
238
+ "Min-SE": 90,
239
+ "Content-Type": "application/sdp"
240
+ },
241
+ offerSDP
242
+ );
243
+ const inboundMessage = await this.send(inviteMessage, true);
244
+ const proxyAuthenticate = inboundMessage.getHeader("Proxy-Authenticate");
245
+ const nonce = proxyAuthenticate.match(/, nonce="(.+?)"/)[1];
246
+ const newMessage = inviteMessage.fork();
247
+ newMessage.headers["Proxy-Authorization"] = (0, import_utils.generateAuthorization)(
248
+ this.sipInfo,
249
+ nonce,
250
+ "INVITE"
251
+ );
252
+ const progressMessage = await this.send(newMessage, true);
253
+ const outboundCallSession = new import_outbound.default(this, progressMessage);
254
+ outboundCallSession.sdp = offerSDP;
255
+ return outboundCallSession;
256
+ }
257
+ }
258
+ var index_default = Softphone;
@@ -1,10 +1,10 @@
1
1
  import EventEmitter from "node:events";
2
- import { TLSSocket } from "node:tls";
2
+ import { type TLSSocket } from "node:tls";
3
3
  import InboundCallSession from "./call-session/inbound.js";
4
4
  import OutboundCallSession from "./call-session/outbound.js";
5
- import { InboundMessage, OutboundMessage } from "./sip-message/index.js";
6
- import { SoftPhoneOptions } from "./types.js";
7
5
  import Codec from "./codec.js";
6
+ import { InboundMessage, OutboundMessage } from "./sip-message/index.js";
7
+ import type { SoftPhoneOptions } from "./types.js";
8
8
  declare class Softphone extends EventEmitter {
9
9
  sipInfo: SoftPhoneOptions;
10
10
  client: TLSSocket;
package/dist/index.js ADDED
@@ -0,0 +1,240 @@
1
+ import EventEmitter from "node:events";
2
+ import tls from "node:tls";
3
+ import waitFor from "wait-for-async";
4
+ import InboundCallSession from "./call-session/inbound.js";
5
+ import OutboundCallSession from "./call-session/outbound.js";
6
+ import Codec from "./codec.js";
7
+ import {
8
+ InboundMessage,
9
+ OutboundMessage,
10
+ RequestMessage,
11
+ ResponseMessage
12
+ } from "./sip-message/index.js";
13
+ import {
14
+ branch,
15
+ generateAuthorization,
16
+ localKey,
17
+ randomInt,
18
+ uuid
19
+ } from "./utils.js";
20
+ class Softphone extends EventEmitter {
21
+ sipInfo;
22
+ client;
23
+ codec;
24
+ fakeDomain = `${uuid()}.invalid`;
25
+ fakeEmail = `${uuid()}@${this.fakeDomain}`;
26
+ intervalHandle;
27
+ connected = false;
28
+ constructor(sipInfo) {
29
+ super();
30
+ if (sipInfo.codec === void 0) {
31
+ sipInfo.codec = "OPUS/16000";
32
+ }
33
+ this.codec = new Codec(sipInfo.codec);
34
+ this.sipInfo = sipInfo;
35
+ if (this.sipInfo.domain === void 0) {
36
+ this.sipInfo.domain = "sip.ringcentral.com";
37
+ }
38
+ if (this.sipInfo.outboundProxy === void 0) {
39
+ this.sipInfo.outboundProxy = "sip10.ringcentral.com:5096";
40
+ }
41
+ const tokens = this.sipInfo.outboundProxy.split(":");
42
+ this.client = tls.connect(
43
+ {
44
+ host: tokens[0],
45
+ port: parseInt(tokens[1], 10),
46
+ rejectUnauthorized: !this.sipInfo.ignoreTlsCertErrors
47
+ },
48
+ () => {
49
+ this.connected = true;
50
+ }
51
+ );
52
+ let cache = "";
53
+ this.client.on("data", (data) => {
54
+ cache += data.toString("utf-8");
55
+ if (!cache.endsWith("\r\n")) {
56
+ return;
57
+ }
58
+ const tempMessages = cache.split("\r\nContent-Length: 0\r\n\r\n").filter((message) => message.trim() !== "");
59
+ cache = "";
60
+ for (let i = 0; i < tempMessages.length; i++) {
61
+ if (!tempMessages[i].includes("Content-Length: ")) {
62
+ tempMessages[i] = `${tempMessages[i]}\r
63
+ Content-Length: 0`;
64
+ }
65
+ }
66
+ for (const message of tempMessages) {
67
+ this.emit("message", InboundMessage.fromString(message));
68
+ }
69
+ });
70
+ }
71
+ instanceId = uuid();
72
+ registerCallId = uuid();
73
+ async register() {
74
+ if (!this.connected) {
75
+ await waitFor({
76
+ interval: 100,
77
+ times: 100,
78
+ condition: () => this.connected
79
+ });
80
+ if (!this.connected) {
81
+ throw new Error("Failed to register: connect to TLS timeout");
82
+ }
83
+ }
84
+ const sipRegister = async () => {
85
+ const fromTag = uuid();
86
+ const requestMessage = new RequestMessage(
87
+ `REGISTER sip:${this.sipInfo.domain} SIP/2.0`,
88
+ {
89
+ Via: `SIP/2.0/TLS ${this.client.localAddress}:${this.client.localPort};rport;branch=${branch()};alias`,
90
+ "Max-Forwards": "70",
91
+ From: `<sip:${this.sipInfo.username}@${this.sipInfo.domain}>;tag=${fromTag}`,
92
+ To: `<sip:${this.sipInfo.username}@${this.sipInfo.domain}>`,
93
+ "Call-ID": this.registerCallId,
94
+ Contact: `<sip:${this.sipInfo.username}@${this.client.localAddress}:${this.client.localPort};transport=TLS;ob>;reg-id=1;+sip.instance="<urn:uuid:${this.instanceId}>"`,
95
+ Expires: 3600,
96
+ Allow: "PRACK, INVITE, ACK, BYE, CANCEL, UPDATE, INFO, SUBSCRIBE, NOTIFY, REFER, MESSAGE, OPTIONS"
97
+ }
98
+ );
99
+ const inboundMessage = await this.send(requestMessage, true);
100
+ if (inboundMessage.subject.startsWith("SIP/2.0 200 ")) {
101
+ return;
102
+ }
103
+ const wwwAuth = inboundMessage.getHeader("Www-Authenticate");
104
+ const nonce = wwwAuth.match(/, nonce="(.+?)"/)[1];
105
+ const newMessage = requestMessage.fork();
106
+ newMessage.headers.Authorization = generateAuthorization(
107
+ this.sipInfo,
108
+ nonce,
109
+ "REGISTER"
110
+ );
111
+ const message = await this.send(newMessage, true);
112
+ if (!message.subject.startsWith("SIP/2.0 200 ")) {
113
+ throw new Error(`Failed to register: ${message.subject}`);
114
+ }
115
+ };
116
+ await sipRegister();
117
+ this.intervalHandle = setInterval(
118
+ () => {
119
+ sipRegister();
120
+ },
121
+ 30 * 1e3
122
+ // refresh registration every 30 seconds
123
+ );
124
+ this.on("message", (inboundMessage) => {
125
+ if (!inboundMessage.subject.startsWith("INVITE sip:")) {
126
+ return;
127
+ }
128
+ const outboundMessage = new OutboundMessage("SIP/2.0 100 Trying", {
129
+ Via: inboundMessage.headers.Via,
130
+ "Call-ID": inboundMessage.getHeader("Call-ID"),
131
+ From: inboundMessage.headers.From,
132
+ To: inboundMessage.headers.To,
133
+ CSeq: inboundMessage.headers.CSeq,
134
+ "Content-Length": "0"
135
+ });
136
+ this.send(outboundMessage);
137
+ this.emit("invite", inboundMessage);
138
+ });
139
+ }
140
+ enableDebugMode() {
141
+ this.on(
142
+ "message",
143
+ (message) => console.log(`Receiving...(${/* @__PURE__ */ new Date()})
144
+ ${message.toString()}`)
145
+ );
146
+ const tlsWrite = this.client.write.bind(this.client);
147
+ this.client.write = (message) => {
148
+ console.log(`Sending...(${/* @__PURE__ */ new Date()})
149
+ ${message}`);
150
+ return tlsWrite(message);
151
+ };
152
+ }
153
+ revoke() {
154
+ clearInterval(this.intervalHandle);
155
+ this.removeAllListeners();
156
+ this.client.removeAllListeners();
157
+ this.client.destroy();
158
+ }
159
+ send(message, waitForReply = false) {
160
+ this.client.write(message.toString());
161
+ if (!waitForReply) {
162
+ return new Promise((resolve) => {
163
+ resolve(void 0);
164
+ });
165
+ }
166
+ return new Promise((resolve) => {
167
+ const messageListerner = (inboundMessage) => {
168
+ if (inboundMessage.headers.CSeq.trim().split(/\s+/)[0] !== message.headers.CSeq.trim().split(/\s+/)[0]) {
169
+ return;
170
+ }
171
+ if (inboundMessage.subject.startsWith("SIP/2.0 100 ")) {
172
+ return;
173
+ }
174
+ this.off("message", messageListerner);
175
+ resolve(inboundMessage);
176
+ };
177
+ this.on("message", messageListerner);
178
+ });
179
+ }
180
+ async answer(inviteMessage) {
181
+ const inboundCallSession = new InboundCallSession(this, inviteMessage);
182
+ await inboundCallSession.answer();
183
+ return inboundCallSession;
184
+ }
185
+ // decline an inbound call
186
+ async decline(inviteMessage) {
187
+ const newMessage = new ResponseMessage(inviteMessage, 603);
188
+ await this.send(newMessage);
189
+ }
190
+ async call(callee) {
191
+ const offerSDP = `
192
+ v=0
193
+ o=- ${Date.now()} 0 IN IP4 ${this.client.localAddress}
194
+ s=rc-softphone-ts
195
+ c=IN IP4 ${this.client.localAddress}
196
+ t=0 0
197
+ m=audio ${randomInt()} RTP/SAVP ${this.codec.id} 101
198
+ a=rtpmap:${this.codec.id} ${this.codec.name}
199
+ a=rtpmap:101 telephone-event/8000
200
+ a=fmtp:101 0-15
201
+ a=sendrecv
202
+ a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:${localKey}
203
+ `.trim();
204
+ const inviteMessage = new RequestMessage(
205
+ `INVITE sip:${callee}@${this.sipInfo.domain} SIP/2.0`,
206
+ {
207
+ Via: `SIP/2.0/TLS ${this.client.localAddress}:${this.client.localPort};rport;branch=${branch()};alias`,
208
+ "Max-Forwards": 70,
209
+ From: `<sip:${this.sipInfo.username}@${this.sipInfo.domain}>;tag=${uuid()}`,
210
+ To: `<sip:${callee}@sip.ringcentral.com>`,
211
+ Contact: ` <sip:${this.sipInfo.username}@${this.client.localAddress}:${this.client.localPort};transport=TLS;ob>`,
212
+ "Call-ID": uuid(),
213
+ Route: `<sip:${this.sipInfo.outboundProxy};transport=tls;lr>`,
214
+ Allow: `PRACK, INVITE, ACK, BYE, CANCEL, UPDATE, INFO, SUBSCRIBE, NOTIFY, REFER, MESSAGE, OPTIONS`,
215
+ Supported: `replaces, 100rel, timer, norefersub`,
216
+ "Session-Expires": 1800,
217
+ "Min-SE": 90,
218
+ "Content-Type": "application/sdp"
219
+ },
220
+ offerSDP
221
+ );
222
+ const inboundMessage = await this.send(inviteMessage, true);
223
+ const proxyAuthenticate = inboundMessage.getHeader("Proxy-Authenticate");
224
+ const nonce = proxyAuthenticate.match(/, nonce="(.+?)"/)[1];
225
+ const newMessage = inviteMessage.fork();
226
+ newMessage.headers["Proxy-Authorization"] = generateAuthorization(
227
+ this.sipInfo,
228
+ nonce,
229
+ "INVITE"
230
+ );
231
+ const progressMessage = await this.send(newMessage, true);
232
+ const outboundCallSession = new OutboundCallSession(this, progressMessage);
233
+ outboundCallSession.sdp = offerSDP;
234
+ return outboundCallSession;
235
+ }
236
+ }
237
+ var index_default = Softphone;
238
+ export {
239
+ index_default as default
240
+ };