reg-cli 0.18.16 → 0.19.0-rc1

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.
File without changes
@@ -0,0 +1,422 @@
1
+ import { createRequire } from "node:module";
2
+ import path from "path";
3
+ import { fileURLToPath } from "url";
4
+ import { readFile } from "node:fs/promises";
5
+ import { dirname, join } from "node:path";
6
+ import { env } from "node:process";
7
+ //#region src/utils.ts
8
+ const isCJS = typeof __dirname !== "undefined";
9
+ const readWasm = () => {
10
+ return readFile(join(isCJS ? __dirname : path.dirname(fileURLToPath(import.meta.url)), "./reg.wasm"));
11
+ };
12
+ const resolveExtention = () => {
13
+ return isCJS ? "cjs" : "mjs";
14
+ };
15
+ /**
16
+ * Restrict the WASI namespace passed to `WebAssembly.instantiate` to only the
17
+ * functions the wasm module actually imports. `@tybys/wasm-util` exposes the
18
+ * full WASI preview1 surface (~46 fns) but `reg.wasm` declares ~20. The unused
19
+ * 26 include capabilities reg-cli never needs (`path_unlink_file`,
20
+ * `path_remove_directory`, `sock_*`, `proc_raise`, ...). Withholding them
21
+ * shrinks the blast radius if the bundled wasm or one of its image-decoder
22
+ * dependencies (libpng/libwebp/libjpeg) is ever compromised.
23
+ */
24
+ const filterWasiImports = (module, full) => {
25
+ const needed = new Set(WebAssembly.Module.imports(module).filter((i) => i.module === "wasi_snapshot_preview1").map((i) => i.name));
26
+ const filtered = {};
27
+ const src = full;
28
+ for (const name of needed) if (name in src) filtered[name] = src[name];
29
+ return filtered;
30
+ };
31
+ /**
32
+ * Host environment variables intentionally forwarded into the Wasm sandbox.
33
+ * Everything else (shell secrets, CI credentials, AWS_*, NPM_TOKEN, ...) is
34
+ * filtered out.
35
+ */
36
+ const FORWARDED_ENV = [
37
+ "OTEL_ENABLED",
38
+ "JAEGER_ENABLED",
39
+ "OTEL_DEBUG",
40
+ "OTEL_EXPORTER_OTLP_ENDPOINT",
41
+ "OTEL_EXPORTER_OTLP_PROTOCOL",
42
+ "OTEL_SERVICE_NAME",
43
+ "OTEL_TRACES_EXPORTER",
44
+ "OTEL_RESOURCE_ATTRIBUTES"
45
+ ];
46
+ /**
47
+ * Longest directory path that every input in `paths` lives under. Treats
48
+ * each path as a sequence of "/"-separated segments; absolute-vs-relative
49
+ * mixes fall back to '.'.
50
+ */
51
+ const commonAncestor = (paths) => {
52
+ const defined = paths.filter(Boolean);
53
+ if (defined.length === 0) return ".";
54
+ if (defined.length === 1) return defined[0];
55
+ const isAbs = (p) => p.startsWith("/");
56
+ const anyAbs = defined.some(isAbs);
57
+ const allAbs = defined.every(isAbs);
58
+ if (anyAbs && !allAbs) return ".";
59
+ const split = defined.map((p) => p.split("/").filter(Boolean));
60
+ const shortest = Math.min(...split.map((s) => s.length));
61
+ const common = [];
62
+ for (let i = 0; i < shortest; i++) {
63
+ const seg = split[0][i];
64
+ if (split.every((s) => s[i] === seg)) common.push(seg);
65
+ else break;
66
+ }
67
+ if (common.length === 0) return allAbs ? "/" : ".";
68
+ return (allAbs ? "/" : "") + common.join("/");
69
+ };
70
+ const WASI_PATH_FLAGS = new Set([
71
+ "--report",
72
+ "-R",
73
+ "--json",
74
+ "-J",
75
+ "--junit",
76
+ "--from",
77
+ "-F"
78
+ ]);
79
+ /**
80
+ * Normalize `./foo` to `foo` for paths passed into WASI. wasm-util does not
81
+ * match a guest path beginning with `./` to an otherwise equivalent relative
82
+ * preopen, so leaving the prefix intact makes valid paths unreachable.
83
+ */
84
+ const normalizeWasiArgv = (argv) => {
85
+ const normalized = [...argv];
86
+ const stripDot = (value) => value.startsWith("./") ? value.slice(2) || "." : value;
87
+ const offset = normalized[0] === "--" ? 1 : 0;
88
+ for (let i = offset; i < normalized.length && i < offset + 3; i++) {
89
+ if (normalized[i].startsWith("-")) break;
90
+ normalized[i] = stripDot(normalized[i]);
91
+ }
92
+ for (let i = offset; i < normalized.length - 1; i++) if (WASI_PATH_FLAGS.has(normalized[i])) {
93
+ normalized[i + 1] = stripDot(normalized[i + 1]);
94
+ i++;
95
+ }
96
+ return normalized;
97
+ };
98
+ /**
99
+ * Compute the minimum-capability WASI sandbox for a given reg-cli invocation:
100
+ *
101
+ * - preopen only the smallest ancestor directory that covers every path
102
+ * this run touches (actualDir, expectedDir, diffDir, and the parents
103
+ * of --report / --json)
104
+ * - forward only an allowlisted subset of host env into Wasm
105
+ *
106
+ * Before this, entry.ts / worker.ts did `preopens: { './': './' }` which
107
+ * exposed the entire cwd (and therefore `.npmrc`, `.env`, `node_modules`,
108
+ * etc.) to whatever runs inside Wasm. Narrowing matters because reg-cli
109
+ * deliberately ingests untrusted images from CI and image decoders
110
+ * (libpng, libwebp, libjpeg) have a long history of RCE-class CVEs.
111
+ *
112
+ * Why a single common-ancestor and not one preopen per directory:
113
+ * On the `wasm32-wasip1-threads` target, Rust's libstd only enumerates
114
+ * the first preopen returned by WASI (`fd_prestat_get(3)` is queried but
115
+ * `fd_prestat_get(4)` is never issued). Until that's fixed upstream,
116
+ * registering one preopen per dir effectively hides every dir but the
117
+ * first. Picking the narrowest *single* ancestor that still contains
118
+ * every touched path gives us a real-world win without tripping the bug.
119
+ *
120
+ * Caveats (follow-ups, not in this PR):
121
+ * - Symlinks and FIFOs inside the preopened directory are still resolved
122
+ * by the host, so an attacker who can plant files under `./diff/` could
123
+ * still exfiltrate via an evil symlink pointing outside the sandbox.
124
+ * Addressing this needs host-side WASI changes.
125
+ * - `@tybys/wasm-util`'s WASI still runs on top of Node's `fs` with full
126
+ * privilege (`fs: fs as IFs`); we only constrain *what paths Wasm is
127
+ * allowed to name*, not what the host fs underneath could do.
128
+ * - One-preopen-per-dir limitation above.
129
+ */
130
+ const computeWasiSandbox = (argv) => {
131
+ const args = argv[0] === "--" ? argv.slice(1) : argv;
132
+ const positional = [];
133
+ for (let i = 0; i < args.length && positional.length < 3; i++) {
134
+ if (args[i].startsWith("--")) break;
135
+ positional.push(args[i]);
136
+ }
137
+ const flagValue = (name) => {
138
+ const i = args.indexOf(name);
139
+ return i >= 0 && i + 1 < args.length ? args[i + 1] : void 0;
140
+ };
141
+ const dirs = [];
142
+ for (const p of positional) if (p) dirs.push(p);
143
+ const report = flagValue("--report");
144
+ const json = flagValue("--json");
145
+ const junit = flagValue("--junit");
146
+ const from = flagValue("--from") ?? flagValue("-F");
147
+ if (report) dirs.push(dirname(report) || ".");
148
+ if (json) dirs.push(dirname(json) || ".");
149
+ if (junit) dirs.push(dirname(junit) || ".");
150
+ if (from) dirs.push(dirname(from) || ".");
151
+ const preopenRoot = commonAncestor(dirs) || ".";
152
+ const mapWasm = (p) => p === "." || p === "./" || p.startsWith("/") || p.startsWith("./") ? p : `./${p}`;
153
+ const preopens = { [mapWasm(preopenRoot)]: preopenRoot };
154
+ if (!preopenRoot || preopenRoot === "." || preopenRoot === "./") preopens["./"] = "./";
155
+ const env$1 = {};
156
+ for (const k of FORWARDED_ENV) {
157
+ const v = env[k];
158
+ if (v !== void 0) env$1[k] = v;
159
+ }
160
+ return {
161
+ preopens,
162
+ env: env$1
163
+ };
164
+ };
165
+ //#endregion
166
+ //#region src/tracing.ts
167
+ /**
168
+ * OpenTelemetry tracing utilities for reg-cli
169
+ *
170
+ * This module receives trace data from the Rust/WASM side and converts it
171
+ * to OpenTelemetry spans that can be exported to Jaeger or other backends.
172
+ *
173
+ * The @opentelemetry/* packages are declared as **optional peer
174
+ * dependencies** — they are loaded lazily inside `initTracing()` only when
175
+ * `OTEL_ENABLED=true` (or `JAEGER_ENABLED=true`). Default installs of this
176
+ * package therefore pay zero install or runtime cost for OTel.
177
+ */
178
+ const PKG_VERSION = (() => {
179
+ try {
180
+ return createRequire(import.meta.url)("../package.json").version ?? "unknown";
181
+ } catch {
182
+ return "unknown";
183
+ }
184
+ })();
185
+ let otel = null;
186
+ let provider = null;
187
+ let isInitialized = false;
188
+ let currentRootSpan = null;
189
+ let currentRootContext = null;
190
+ /**
191
+ * Check if tracing is enabled via environment variable
192
+ */
193
+ const isTracingEnabled = () => {
194
+ return process.env.OTEL_ENABLED === "true" || process.env.JAEGER_ENABLED === "true";
195
+ };
196
+ /**
197
+ * Lazily import the @opentelemetry/* packages. Returns null and prints a
198
+ * single warning if any are missing — keeps the CLI working without OTel
199
+ * installed even when the env vars are set.
200
+ */
201
+ const loadOtel = async () => {
202
+ if (otel) return otel;
203
+ try {
204
+ const [api, resources, sdkBase, sdkNode, exporter, semconv] = await Promise.all([
205
+ import("@opentelemetry/api"),
206
+ import("@opentelemetry/resources"),
207
+ import("@opentelemetry/sdk-trace-base"),
208
+ import("@opentelemetry/sdk-trace-node"),
209
+ import("@opentelemetry/exporter-trace-otlp-http"),
210
+ import("@opentelemetry/semantic-conventions")
211
+ ]);
212
+ otel = {
213
+ api,
214
+ resources,
215
+ sdkBase,
216
+ sdkNode,
217
+ exporter,
218
+ semconv
219
+ };
220
+ return otel;
221
+ } catch (err) {
222
+ const pkgs = [
223
+ "@opentelemetry/api",
224
+ "@opentelemetry/exporter-trace-otlp-http",
225
+ "@opentelemetry/resources",
226
+ "@opentelemetry/sdk-trace-base",
227
+ "@opentelemetry/sdk-trace-node",
228
+ "@opentelemetry/semantic-conventions"
229
+ ].join(" ");
230
+ console.warn(`[Tracing] OTEL_ENABLED is set but the @opentelemetry/* peer dependencies are not installed. Continuing without tracing. To enable, install the peers alongside reg-cli, e.g.:
231
+ npm i -g ${pkgs} # if reg-cli is installed globally\n npm i ${pkgs} # if reg-cli is a project dependency`);
232
+ if (process.env.OTEL_DEBUG === "true") console.warn("[Tracing] Import error:", err);
233
+ return null;
234
+ }
235
+ };
236
+ /**
237
+ * Initialize OpenTelemetry SDK
238
+ */
239
+ const initTracing = async () => {
240
+ if (!isTracingEnabled() || isInitialized) return;
241
+ const mods = await loadOtel();
242
+ if (!mods) return;
243
+ const otlpEndpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT || "http://localhost:4318/v1/traces";
244
+ const otlpExporter = new mods.exporter.OTLPTraceExporter({ url: otlpEndpoint });
245
+ provider = new mods.sdkNode.NodeTracerProvider({
246
+ resource: mods.resources.resourceFromAttributes({
247
+ [mods.semconv.ATTR_SERVICE_NAME]: "reg-cli",
248
+ [mods.semconv.ATTR_SERVICE_VERSION]: "0.18.10"
249
+ }),
250
+ spanProcessors: [new mods.sdkBase.BatchSpanProcessor(otlpExporter)]
251
+ });
252
+ provider.register();
253
+ isInitialized = true;
254
+ if (process.env.OTEL_DEBUG === "true") {
255
+ console.log("[Tracing] OpenTelemetry initialized");
256
+ console.log(`[Tracing] OTLP endpoint: ${otlpEndpoint}`);
257
+ }
258
+ };
259
+ /**
260
+ * Shutdown OpenTelemetry SDK gracefully
261
+ */
262
+ const shutdownTracing = async () => {
263
+ if (!provider || !isInitialized) return;
264
+ if (process.env.OTEL_DEBUG === "true") console.log("[Tracing] Starting SDK shutdown...");
265
+ try {
266
+ await provider.shutdown();
267
+ } catch (err) {
268
+ console.error("[Tracing] Error during shutdown:", err);
269
+ }
270
+ isInitialized = false;
271
+ provider = null;
272
+ if (process.env.OTEL_DEBUG === "true") console.log("[Tracing] OpenTelemetry SDK shut down");
273
+ };
274
+ /**
275
+ * Get the tracer instance
276
+ */
277
+ const getTracer = () => {
278
+ return otel.api.trace.getTracer("reg-cli", PKG_VERSION);
279
+ };
280
+ /**
281
+ * Start a root span and return context info to pass to Rust
282
+ */
283
+ const startRootSpan = (name) => {
284
+ if (!isTracingEnabled() || !isInitialized || !otel) return null;
285
+ currentRootSpan = getTracer().startSpan(name);
286
+ currentRootContext = otel.api.trace.setSpan(otel.api.ROOT_CONTEXT, currentRootSpan);
287
+ const spanContext = currentRootSpan.spanContext();
288
+ if (process.env.OTEL_DEBUG === "true") {
289
+ console.log(`[Tracing] Started root span: ${name}`);
290
+ console.log(`[Tracing] Trace ID: ${spanContext.traceId}`);
291
+ console.log(`[Tracing] Span ID: ${spanContext.spanId}`);
292
+ }
293
+ return {
294
+ traceId: spanContext.traceId,
295
+ spanId: spanContext.spanId
296
+ };
297
+ };
298
+ /**
299
+ * End the current root span
300
+ */
301
+ const endRootSpan = (success = true) => {
302
+ if (currentRootSpan && otel) {
303
+ if (success) currentRootSpan.setStatus({ code: otel.api.SpanStatusCode.OK });
304
+ else currentRootSpan.setStatus({ code: otel.api.SpanStatusCode.ERROR });
305
+ currentRootSpan.end();
306
+ if (process.env.OTEL_DEBUG === "true") console.log("[Tracing] Ended root span");
307
+ currentRootSpan = null;
308
+ currentRootContext = null;
309
+ }
310
+ };
311
+ /**
312
+ * Topologically sort spans so parents are always processed before children
313
+ */
314
+ const topologicalSortSpans = (spans) => {
315
+ const spanMap = /* @__PURE__ */ new Map();
316
+ const childrenMap = /* @__PURE__ */ new Map();
317
+ const rootSpans = [];
318
+ for (const span of spans) {
319
+ spanMap.set(span.span_id, span);
320
+ if (!span.parent_span_id) rootSpans.push(span.span_id);
321
+ else {
322
+ const children = childrenMap.get(span.parent_span_id) || [];
323
+ children.push(span.span_id);
324
+ childrenMap.set(span.parent_span_id, children);
325
+ }
326
+ }
327
+ if (process.env.OTEL_DEBUG === "true") {
328
+ console.log(`[Tracing] Total spans: ${spans.length}, Unique IDs in spanMap: ${spanMap.size}`);
329
+ console.log(`[Tracing] Root spans: ${rootSpans.join(", ")}`);
330
+ console.log(`[Tracing] All spans:`);
331
+ for (const span of spans) console.log(` ${span.span_id}: ${span.name} (parent: ${span.parent_span_id || "none"})`);
332
+ console.log(`[Tracing] Parent->Children map:`);
333
+ for (const [parent, children] of childrenMap.entries()) console.log(` ${parent} -> ${children.join(", ")}`);
334
+ }
335
+ const result = [];
336
+ const queue = [...rootSpans];
337
+ const visited = /* @__PURE__ */ new Set();
338
+ while (queue.length > 0) {
339
+ const spanId = queue.shift();
340
+ if (visited.has(spanId)) continue;
341
+ visited.add(spanId);
342
+ const span = spanMap.get(spanId);
343
+ if (span) {
344
+ result.push(span);
345
+ const children = childrenMap.get(spanId) || [];
346
+ queue.push(...children);
347
+ }
348
+ }
349
+ for (const span of spans) if (!visited.has(span.span_id)) {
350
+ if (process.env.OTEL_DEBUG === "true") console.log(`[Tracing] Orphan span: ${span.name} (id: ${span.span_id}, parent: ${span.parent_span_id})`);
351
+ result.push(span);
352
+ }
353
+ return result;
354
+ };
355
+ /**
356
+ * Convert Rust trace data to OpenTelemetry spans
357
+ *
358
+ * Since Rust spans have already ended by the time we receive them,
359
+ * we reconstruct them with their recorded timestamps.
360
+ */
361
+ const processRustTraceData = (traceData) => {
362
+ if (!isTracingEnabled() || !isInitialized || !otel) return;
363
+ const tracer = getTracer();
364
+ if (process.env.OTEL_DEBUG === "true") {
365
+ console.log(`[Tracing] Processing ${traceData.spans.length} spans from Rust`);
366
+ console.log(`[Tracing] JS parent context available: ${currentRootContext !== null}`);
367
+ }
368
+ const sortedSpans = topologicalSortSpans(traceData.spans);
369
+ const spanContextMap = /* @__PURE__ */ new Map();
370
+ for (const rustSpan of sortedSpans) {
371
+ const startTimeNs = rustSpan.start_time_ms * 1e6;
372
+ const endTimeNs = rustSpan.end_time_ms * 1e6;
373
+ let parentContext;
374
+ let parentInfo;
375
+ if (rustSpan.parent_span_id && spanContextMap.has(rustSpan.parent_span_id)) {
376
+ parentContext = spanContextMap.get(rustSpan.parent_span_id);
377
+ parentInfo = `rust parent: ${rustSpan.parent_span_id}`;
378
+ } else if (!rustSpan.parent_span_id && currentRootContext) {
379
+ parentContext = currentRootContext;
380
+ parentInfo = `js parent: ${currentRootSpan?.spanContext().spanId}`;
381
+ } else {
382
+ parentContext = currentRootContext || otel.api.ROOT_CONTEXT;
383
+ parentInfo = rustSpan.parent_span_id ? `orphan (parent ${rustSpan.parent_span_id} not found)` : "root (no js context)";
384
+ }
385
+ const span = tracer.startSpan(rustSpan.name, { startTime: [Math.floor(startTimeNs / 1e9), startTimeNs % 1e9] }, parentContext);
386
+ span.setAttribute("rust.target", rustSpan.target);
387
+ span.setAttribute("rust.level", rustSpan.level);
388
+ span.setAttribute("rust.span_id", rustSpan.span_id);
389
+ span.setAttribute("duration_ms", rustSpan.duration_ms);
390
+ for (const [key, value] of Object.entries(rustSpan.attributes)) span.setAttribute(`rust.${key}`, value);
391
+ if (rustSpan.status === "error") span.setStatus({
392
+ code: otel.api.SpanStatusCode.ERROR,
393
+ message: rustSpan.error_message || "Unknown error"
394
+ });
395
+ else span.setStatus({ code: otel.api.SpanStatusCode.OK });
396
+ span.end([Math.floor(endTimeNs / 1e9), endTimeNs % 1e9]);
397
+ const ctx = otel.api.trace.setSpan(parentContext, span);
398
+ spanContextMap.set(rustSpan.span_id, ctx);
399
+ if (process.env.OTEL_DEBUG === "true") console.log(`[Tracing] Created span: ${rustSpan.name} (${rustSpan.duration_ms}ms) [${parentInfo}] start=${rustSpan.start_time_ms}, end=${rustSpan.end_time_ms}`);
400
+ }
401
+ };
402
+ /**
403
+ * Convert worker-side timing events to OpenTelemetry spans attached under the
404
+ * current root span. Used to surface JS-bridge costs (Worker creation, wasm
405
+ * compile / instantiate, message round-trips) that Rust-side tracing cannot see.
406
+ */
407
+ const processWorkerSpans = (spans, workerLabel) => {
408
+ if (!isTracingEnabled() || !isInitialized || !otel || !spans?.length) return;
409
+ const tracer = getTracer();
410
+ const parentCtx = currentRootContext ?? otel.api.ROOT_CONTEXT;
411
+ for (const s of spans) {
412
+ const startNs = s.start_ms * 1e6;
413
+ const endNs = s.end_ms * 1e6;
414
+ const span = tracer.startSpan(s.name, { startTime: [Math.floor(startNs / 1e9), startNs % 1e9] }, parentCtx);
415
+ span.setAttribute("worker", s.worker_label ?? workerLabel);
416
+ span.setAttribute("duration_ms", s.end_ms - s.start_ms);
417
+ if (s.attributes) for (const [k, v] of Object.entries(s.attributes)) span.setAttribute(k, v);
418
+ span.end([Math.floor(endNs / 1e9), endNs % 1e9]);
419
+ }
420
+ };
421
+ //#endregion
422
+ export { processWorkerSpans as a, computeWasiSandbox as c, normalizeWasiArgv as d, readWasm as f, processRustTraceData as i, filterWasiImports as l, initTracing as n, shutdownTracing as o, resolveExtention as p, isTracingEnabled as r, startRootSpan as s, endRootSpan as t, isCJS as u };