@webrtc-node/webrtc 0.2.1

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.
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+
3
+ const fs = require("node:fs");
4
+ const path = require("node:path");
5
+
6
+ const root = path.resolve(__dirname, "..");
7
+ const moduleName = "webrtc_node.node";
8
+
9
+ function existing(file) {
10
+ return fs.existsSync(file) ? file : null;
11
+ }
12
+
13
+ function localBuildCandidates() {
14
+ return [
15
+ path.join(root, "build", "Release", moduleName),
16
+ path.join(root, "build", "Debug", moduleName),
17
+ ];
18
+ }
19
+
20
+ function loadNative() {
21
+ const override = process.env.WEBRTC_NODE_NATIVE_PATH;
22
+ const candidates = [...(override ? [path.resolve(override)] : []), ...localBuildCandidates()];
23
+
24
+ for (const candidate of candidates) {
25
+ if (!existing(candidate)) continue;
26
+ try {
27
+ return require(candidate);
28
+ } catch (error) {
29
+ error.message = `Failed to load native addon at ${candidate}: ${error.message}`;
30
+ throw error;
31
+ }
32
+ }
33
+
34
+ const searched = candidates.map((candidate) => ` - ${candidate}`).join("\n");
35
+ throw new Error(
36
+ `Native addon not found for ${process.platform}-${process.arch}.\n` +
37
+ `Searched:\n${searched}\n` +
38
+ 'Install a package with a matching prebuild or run "npm run build".',
39
+ );
40
+ }
41
+
42
+ module.exports = loadNative();
package/package.json ADDED
@@ -0,0 +1,91 @@
1
+ {
2
+ "name": "@webrtc-node/webrtc",
3
+ "version": "0.2.1",
4
+ "description": "Data-channel-first WebRTC for Node.js with W3C-style RTCPeerConnection and RTCDataChannel APIs.",
5
+ "author": "webrtc-node contributors",
6
+ "homepage": "https://github.com/webrtc-node/webrtc#readme",
7
+ "bugs": {
8
+ "url": "https://github.com/webrtc-node/webrtc/issues"
9
+ },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/webrtc-node/webrtc.git"
13
+ },
14
+ "publishConfig": {
15
+ "access": "public"
16
+ },
17
+ "keywords": [
18
+ "webrtc",
19
+ "webrtc-node",
20
+ "rtcpeerconnection",
21
+ "rtcdatachannel",
22
+ "datachannel",
23
+ "node",
24
+ "node-api",
25
+ "n-api",
26
+ "libdatachannel",
27
+ "web-platform-tests"
28
+ ],
29
+ "main": "lib/index.js",
30
+ "types": "index.d.ts",
31
+ "exports": {
32
+ ".": {
33
+ "types": "./index.d.ts",
34
+ "require": "./lib/index.js",
35
+ "import": "./lib/index.js",
36
+ "default": "./lib/index.js"
37
+ },
38
+ "./package.json": "./package.json"
39
+ },
40
+ "files": [
41
+ "lib",
42
+ "scripts/install-native.js",
43
+ "scripts/prebuild-integrity.js",
44
+ "src/native/addon.cc",
45
+ "src/native/certificate.cc",
46
+ "src/native/certificate.hpp",
47
+ "CMakeLists.txt",
48
+ "index.d.ts"
49
+ ],
50
+ "scripts": {
51
+ "build": "cmake-js compile",
52
+ "check": "biome check .",
53
+ "clean": "cmake-js clean",
54
+ "e2e:chrome": "node test/e2e/run-chrome.js",
55
+ "example:datachannel": "node examples/datachannel.js",
56
+ "format": "biome format --write .",
57
+ "format:check": "biome format .",
58
+ "install": "node scripts/install-native.js",
59
+ "lint": "biome lint .",
60
+ "native:check": "node scripts/check-native-integration.js",
61
+ "prebuild:package": "node scripts/package-prebuild.js",
62
+ "prebuild:check": "node scripts/check-prebuilds.js",
63
+ "api:check": "node scripts/check-api-surface.js",
64
+ "test": "node --test --test-force-exit --test-timeout=30000 test/basic.test.js test/nonstandard.test.js test/prebuild-integrity.test.js test/wpt-sharding.test.js",
65
+ "types:check": "tsc -p tsconfig.types.json",
66
+ "wpt:ensure": "node scripts/ensure-wpt.js",
67
+ "wpt:smoke": "node scripts/run-wpt-smoke.js",
68
+ "wpt:smoke:check": "node scripts/check-wpt-results.js --fail-on-retries --expected-total 4",
69
+ "wpt:test": "node scripts/run-wpt-subset.js",
70
+ "wpt:test:sharded": "node scripts/run-wpt-sharded.js",
71
+ "wpt:check": "node scripts/check-wpt-results.js",
72
+ "wpt:check:strict": "node scripts/check-wpt-results.js --fail-on-retries",
73
+ "wpt:selection:check": "node scripts/check-wpt-selection.js",
74
+ "wpt:report": "node scripts/write-wpt-report.js"
75
+ },
76
+ "dependencies": {
77
+ "cmake-js": "^8.0.0",
78
+ "detect-libc": "^2.1.2",
79
+ "node-addon-api": "^8.3.1",
80
+ "tar": "^7.5.15"
81
+ },
82
+ "devDependencies": {
83
+ "@biomejs/biome": "2.5.0",
84
+ "playwright-core": "1.61.0",
85
+ "typescript": "^6.0.3"
86
+ },
87
+ "engines": {
88
+ "node": ">=20"
89
+ },
90
+ "license": "MPL-2.0"
91
+ }
@@ -0,0 +1,154 @@
1
+ "use strict";
2
+
3
+ const fs = require("node:fs");
4
+ const path = require("node:path");
5
+ const { spawnSync } = require("node:child_process");
6
+ const libc = require("detect-libc");
7
+ const {
8
+ checksumFileName,
9
+ installArchive,
10
+ maxArchiveBytes,
11
+ moduleName,
12
+ } = require("./prebuild-integrity");
13
+
14
+ const root = path.resolve(__dirname, "..");
15
+ const packageJson = require("../package.json");
16
+ const releaseBaseUrl = "https://github.com/webrtc-node/webrtc/releases/download";
17
+
18
+ function envFlag(name) {
19
+ return /^(1|true|yes)$/i.test(String(process.env[name] || ""));
20
+ }
21
+
22
+ function isSourceCheckout() {
23
+ return fs.existsSync(path.join(root, ".git")) && !root.split(path.sep).includes("node_modules");
24
+ }
25
+
26
+ function hasNativeAddon() {
27
+ try {
28
+ require("../lib/load-native");
29
+ return true;
30
+ } catch {
31
+ return false;
32
+ }
33
+ }
34
+
35
+ function linuxLibcTag() {
36
+ if (process.platform !== "linux") return null;
37
+ const family = libc.familySync();
38
+ if (family === libc.MUSL) return "musl";
39
+ if (family === libc.GLIBC) return "glibc";
40
+ return null;
41
+ }
42
+
43
+ function targetTuple() {
44
+ return [process.platform, process.arch, linuxLibcTag()].filter(Boolean).join("-");
45
+ }
46
+
47
+ function releaseTag() {
48
+ return process.env.WEBRTC_NODE_PREBUILD_TAG || `v${packageJson.version}`;
49
+ }
50
+
51
+ function prebuildAssetName() {
52
+ return `webrtc-node-${releaseTag()}-napi-v8-${targetTuple()}.tar.gz`;
53
+ }
54
+
55
+ async function download(url, maximumBytes, label) {
56
+ const response = await fetch(url, {
57
+ headers: { "user-agent": "webrtc-node-install" },
58
+ });
59
+ if (!response.ok) {
60
+ throw new Error(`${label} download failed: HTTP ${response.status} ${response.statusText}`);
61
+ }
62
+ const contentLength = Number(response.headers.get("content-length"));
63
+ if (Number.isFinite(contentLength) && contentLength > maximumBytes) {
64
+ throw new Error(`${label} exceeds the maximum allowed size`);
65
+ }
66
+ if (!response.body) throw new Error(`${label} response body is unavailable`);
67
+ const chunks = [];
68
+ let totalBytes = 0;
69
+ for await (const chunk of response.body) {
70
+ const buffer = Buffer.from(chunk);
71
+ totalBytes += buffer.length;
72
+ if (totalBytes > maximumBytes) throw new Error(`${label} exceeds the maximum allowed size`);
73
+ chunks.push(buffer);
74
+ }
75
+ return Buffer.concat(chunks, totalBytes);
76
+ }
77
+
78
+ async function downloadPrebuild() {
79
+ const archiveName = prebuildAssetName();
80
+ const checksumName = checksumFileName(archiveName);
81
+ const baseUrl = `${releaseBaseUrl}/${releaseTag()}`;
82
+ const checksumBuffer = await download(`${baseUrl}/${checksumName}`, 4096, "checksum");
83
+ const archiveBuffer = await download(`${baseUrl}/${archiveName}`, maxArchiveBytes, "prebuild");
84
+ const outputDir = path.join(root, "build", "Release");
85
+ fs.mkdirSync(outputDir, { recursive: true });
86
+ const downloadDir = fs.mkdtempSync(path.join(outputDir, ".download-"));
87
+ const archivePath = path.join(downloadDir, archiveName);
88
+
89
+ try {
90
+ fs.writeFileSync(archivePath, archiveBuffer);
91
+ await installArchive({
92
+ archivePath,
93
+ checksumContents: checksumBuffer.toString("utf8"),
94
+ archiveName,
95
+ platform: process.platform,
96
+ arch: process.arch,
97
+ libcTag: linuxLibcTag(),
98
+ destinationPath: path.join(outputDir, moduleName),
99
+ });
100
+ } finally {
101
+ fs.rmSync(downloadDir, { recursive: true, force: true });
102
+ }
103
+ }
104
+
105
+ function runBuild() {
106
+ const npm = process.env.npm_execpath
107
+ ? process.execPath
108
+ : process.platform === "win32"
109
+ ? "npm.cmd"
110
+ : "npm";
111
+ const args = process.env.npm_execpath
112
+ ? [process.env.npm_execpath, "run", "build"]
113
+ : ["run", "build"];
114
+ const result = spawnSync(npm, args, {
115
+ cwd: root,
116
+ stdio: "inherit",
117
+ });
118
+ return result.status === 0 && !result.signal;
119
+ }
120
+
121
+ async function main() {
122
+ const buildFromSource = envFlag("npm_config_build_from_source");
123
+ const prebuildOnly = envFlag("WEBRTC_NODE_PREBUILD_ONLY");
124
+ if (!buildFromSource && hasNativeAddon()) return;
125
+
126
+ if (isSourceCheckout() && !buildFromSource) {
127
+ console.log("Skipping native install in source checkout. Run npm run build explicitly.");
128
+ return;
129
+ }
130
+
131
+ if (!buildFromSource) {
132
+ try {
133
+ await downloadPrebuild();
134
+ if (hasNativeAddon()) return;
135
+ throw new Error(`downloaded archive did not provide ${moduleName}`);
136
+ } catch (error) {
137
+ console.warn(`Prebuilt binary unavailable for ${targetTuple()}: ${error.message}`);
138
+ if (prebuildOnly) {
139
+ console.error("Prebuild-only install requested; refusing to build from source.");
140
+ process.exit(1);
141
+ }
142
+ }
143
+ }
144
+
145
+ if (!runBuild()) {
146
+ console.error("No compatible prebuilt binary was found and the cmake-js source build failed.");
147
+ process.exit(1);
148
+ }
149
+ }
150
+
151
+ main().catch((error) => {
152
+ console.error(error);
153
+ process.exit(1);
154
+ });
@@ -0,0 +1,227 @@
1
+ "use strict";
2
+
3
+ const crypto = require("node:crypto");
4
+ const fs = require("node:fs");
5
+ const path = require("node:path");
6
+ const tar = require("tar");
7
+
8
+ const moduleName = "webrtc_node.node";
9
+ const maxArchiveBytes = 64 * 1024 * 1024;
10
+ const maxAddonBytes = 128 * 1024 * 1024;
11
+
12
+ function sha256(buffer) {
13
+ return crypto.createHash("sha256").update(buffer).digest("hex");
14
+ }
15
+
16
+ function checksumFileName(archiveName) {
17
+ return `${archiveName}.sha256`;
18
+ }
19
+
20
+ function checksumFileContents(archiveName, digest) {
21
+ if (!/^[a-f0-9]{64}$/.test(digest)) throw new Error("invalid SHA-256 digest");
22
+ return `${digest} ${archiveName}\n`;
23
+ }
24
+
25
+ function parseChecksumFile(contents, archiveName) {
26
+ if (Buffer.byteLength(contents, "utf8") > 4096) throw new Error("checksum file is too large");
27
+ const lines = contents.trimEnd().split(/\r?\n/);
28
+ if (lines.length !== 1) throw new Error("checksum file must contain exactly one entry");
29
+ const match = /^([a-fA-F0-9]{64}) {2}([A-Za-z0-9][A-Za-z0-9._-]*)$/.exec(lines[0]);
30
+ if (!match) throw new Error("checksum file has an invalid format");
31
+ if (match[2] !== archiveName) throw new Error(`checksum file names unexpected asset ${match[2]}`);
32
+ return match[1].toLowerCase();
33
+ }
34
+
35
+ function verifyArchiveChecksum(archiveBuffer, checksumContents, archiveName) {
36
+ if (archiveBuffer.length === 0) throw new Error("prebuild archive is empty");
37
+ if (archiveBuffer.length > maxArchiveBytes) throw new Error("prebuild archive is too large");
38
+ const expected = Buffer.from(parseChecksumFile(checksumContents, archiveName), "hex");
39
+ const actual = Buffer.from(sha256(archiveBuffer), "hex");
40
+ if (!crypto.timingSafeEqual(actual, expected)) throw new Error("prebuild SHA-256 mismatch");
41
+ }
42
+
43
+ function expectedBinary(platform, arch, libcTag) {
44
+ if (platform === "linux" && arch === "x64") {
45
+ if (libcTag !== "glibc" && libcTag !== "musl") {
46
+ throw new Error(`unsupported Linux libc target ${libcTag || "unknown"}`);
47
+ }
48
+ return { format: "ELF", machine: 62, libcTag };
49
+ }
50
+ if (platform === "win32" && arch === "x64") {
51
+ return { format: "PE", machine: 0x8664 };
52
+ }
53
+ if (platform === "win32" && arch === "arm64") {
54
+ return { format: "PE", machine: 0xaa64 };
55
+ }
56
+ if (platform === "darwin" && arch === "x64") {
57
+ return { format: "Mach-O", machine: 0x01000007 };
58
+ }
59
+ if (platform === "darwin" && arch === "arm64") {
60
+ return { format: "Mach-O", machine: 0x0100000c };
61
+ }
62
+ throw new Error(`unsupported prebuild target ${platform}-${arch}`);
63
+ }
64
+
65
+ function readBinaryIdentity(buffer) {
66
+ if (buffer.length >= 20 && buffer.subarray(0, 4).equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46]))) {
67
+ if (buffer[4] !== 2) throw new Error("prebuild ELF binary is not 64-bit");
68
+ const byteOrder = buffer[5];
69
+ if (byteOrder !== 1 && byteOrder !== 2) throw new Error("prebuild ELF byte order is invalid");
70
+ return {
71
+ format: "ELF",
72
+ machine: byteOrder === 1 ? buffer.readUInt16LE(18) : buffer.readUInt16BE(18),
73
+ };
74
+ }
75
+
76
+ if (buffer.length >= 64 && buffer.subarray(0, 2).toString("ascii") === "MZ") {
77
+ const headerOffset = buffer.readUInt32LE(0x3c);
78
+ if (
79
+ headerOffset > buffer.length - 6 ||
80
+ !buffer.subarray(headerOffset, headerOffset + 4).equals(Buffer.from("PE\0\0", "binary"))
81
+ ) {
82
+ throw new Error("prebuild PE header is invalid");
83
+ }
84
+ return { format: "PE", machine: buffer.readUInt16LE(headerOffset + 4) };
85
+ }
86
+
87
+ if (buffer.length >= 8 && buffer.subarray(0, 4).equals(Buffer.from([0xcf, 0xfa, 0xed, 0xfe]))) {
88
+ return { format: "Mach-O", machine: buffer.readUInt32LE(4) };
89
+ }
90
+
91
+ throw new Error("prebuild binary format is not recognized");
92
+ }
93
+
94
+ function verifyBinaryTarget(buffer, platform, arch, libcTag = null) {
95
+ if (buffer.length === 0) throw new Error("prebuild addon is empty");
96
+ if (buffer.length > maxAddonBytes) throw new Error("prebuild addon is too large");
97
+ const expected = expectedBinary(platform, arch, libcTag);
98
+ const actual = readBinaryIdentity(buffer);
99
+ if (actual.format !== expected.format || actual.machine !== expected.machine) {
100
+ throw new Error(
101
+ `prebuild binary target mismatch: expected ${platform}-${arch}, found ${actual.format} machine 0x${actual.machine.toString(16)}`,
102
+ );
103
+ }
104
+ if (expected.libcTag === "glibc" && !buffer.includes(Buffer.from("libc.so.6"))) {
105
+ throw new Error("prebuild binary target mismatch: expected glibc linkage");
106
+ }
107
+ if (expected.libcTag === "musl" && !buffer.includes(Buffer.from("libc.musl-x86_64.so.1"))) {
108
+ throw new Error("prebuild binary target mismatch: expected musl linkage");
109
+ }
110
+ }
111
+
112
+ async function inspectArchive(archivePath) {
113
+ const entries = [];
114
+ let validationError = null;
115
+ await tar.t({
116
+ file: archivePath,
117
+ strict: true,
118
+ onReadEntry(entry) {
119
+ const archiveEntry = {
120
+ path: entry.path,
121
+ size: entry.size,
122
+ type: entry.type,
123
+ };
124
+ entries.push(archiveEntry);
125
+ const invalidEntry =
126
+ entries.length > 1 ||
127
+ archiveEntry.path !== moduleName ||
128
+ archiveEntry.type !== "File" ||
129
+ !Number.isSafeInteger(archiveEntry.size) ||
130
+ archiveEntry.size <= 0 ||
131
+ archiveEntry.size > maxAddonBytes;
132
+ if (!validationError && invalidEntry) {
133
+ validationError = new Error(
134
+ `prebuild archive contains invalid entry ${archiveEntry.path} (${archiveEntry.type})`,
135
+ );
136
+ }
137
+ entry.resume();
138
+ },
139
+ });
140
+
141
+ if (validationError) throw validationError;
142
+ if (entries.length !== 1) {
143
+ throw new Error(`prebuild archive must contain exactly ${moduleName}`);
144
+ }
145
+ const [entry] = entries;
146
+ if (entry.path !== moduleName || entry.type !== "File") {
147
+ throw new Error(`prebuild archive contains unexpected entry ${entry.path} (${entry.type})`);
148
+ }
149
+ if (!Number.isSafeInteger(entry.size) || entry.size <= 0 || entry.size > maxAddonBytes) {
150
+ throw new Error("prebuild archive addon size is invalid");
151
+ }
152
+ return entry;
153
+ }
154
+
155
+ async function validateArchiveFile({
156
+ archivePath,
157
+ checksumContents,
158
+ archiveName = path.basename(archivePath),
159
+ platform,
160
+ arch,
161
+ libcTag = null,
162
+ }) {
163
+ const archiveBuffer = fs.readFileSync(archivePath);
164
+ verifyArchiveChecksum(archiveBuffer, checksumContents, archiveName);
165
+ const entry = await inspectArchive(archivePath);
166
+ const extractionRoot = fs.mkdtempSync(path.join(path.dirname(archivePath), ".verified-"));
167
+
168
+ try {
169
+ await tar.x({
170
+ file: archivePath,
171
+ cwd: extractionRoot,
172
+ strict: true,
173
+ filter(entryPath, tarEntry) {
174
+ return entryPath === moduleName && tarEntry.type === "File";
175
+ },
176
+ });
177
+ const addonPath = path.join(extractionRoot, moduleName);
178
+ const stat = fs.lstatSync(addonPath);
179
+ if (!stat.isFile() || stat.size !== entry.size) {
180
+ throw new Error("extracted prebuild addon does not match the archive entry");
181
+ }
182
+ verifyBinaryTarget(fs.readFileSync(addonPath), platform, arch, libcTag);
183
+ return addonPath;
184
+ } catch (error) {
185
+ fs.rmSync(extractionRoot, { recursive: true, force: true });
186
+ throw error;
187
+ }
188
+ }
189
+
190
+ async function installArchive(options) {
191
+ const addonPath = await validateArchiveFile(options);
192
+ const extractionRoot = path.dirname(addonPath);
193
+ const destinationPath = options.destinationPath;
194
+ const temporaryPath = `${destinationPath}.verified-${process.pid}`;
195
+
196
+ try {
197
+ fs.mkdirSync(path.dirname(destinationPath), { recursive: true });
198
+ fs.copyFileSync(addonPath, temporaryPath);
199
+ fs.rmSync(destinationPath, { force: true });
200
+ fs.renameSync(temporaryPath, destinationPath);
201
+ } finally {
202
+ fs.rmSync(temporaryPath, { force: true });
203
+ fs.rmSync(extractionRoot, { recursive: true, force: true });
204
+ }
205
+ }
206
+
207
+ function writeChecksumFile(archivePath) {
208
+ const archiveName = path.basename(archivePath);
209
+ const digest = sha256(fs.readFileSync(archivePath));
210
+ const checksumPath = `${archivePath}.sha256`;
211
+ fs.writeFileSync(checksumPath, checksumFileContents(archiveName, digest), "utf8");
212
+ return checksumPath;
213
+ }
214
+
215
+ module.exports = {
216
+ checksumFileContents,
217
+ checksumFileName,
218
+ installArchive,
219
+ maxArchiveBytes,
220
+ moduleName,
221
+ parseChecksumFile,
222
+ sha256,
223
+ validateArchiveFile,
224
+ verifyArchiveChecksum,
225
+ verifyBinaryTarget,
226
+ writeChecksumFile,
227
+ };