@testsprite/testsprite-cli 0.7.0 → 0.9.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.
Files changed (74) hide show
  1. package/README.md +62 -45
  2. package/dist/commands/agent.d.ts +3 -0
  3. package/dist/commands/agent.js +79 -10
  4. package/dist/commands/ci.d.ts +88 -0
  5. package/dist/commands/ci.js +432 -0
  6. package/dist/commands/doctor.js +100 -1
  7. package/dist/commands/init.d.ts +45 -2
  8. package/dist/commands/init.js +198 -29
  9. package/dist/commands/project.d.ts +78 -0
  10. package/dist/commands/project.js +439 -5
  11. package/dist/commands/test.d.ts +193 -4
  12. package/dist/commands/test.js +1948 -398
  13. package/dist/commands/testlist.js +15 -9
  14. package/dist/commands/tunnel.d.ts +72 -0
  15. package/dist/commands/tunnel.js +367 -0
  16. package/dist/index.js +107 -38
  17. package/dist/lib/agent-detect.d.ts +53 -0
  18. package/dist/lib/agent-detect.js +198 -0
  19. package/dist/lib/dry-run/samples.d.ts +9 -0
  20. package/dist/lib/dry-run/samples.js +116 -0
  21. package/dist/lib/gh-output.d.ts +7 -0
  22. package/dist/lib/gh-output.js +50 -7
  23. package/dist/lib/http.d.ts +104 -0
  24. package/dist/lib/http.js +126 -7
  25. package/dist/lib/interrupt.d.ts +38 -13
  26. package/dist/lib/interrupt.js +130 -15
  27. package/dist/lib/local-target.d.ts +95 -0
  28. package/dist/lib/local-target.js +184 -0
  29. package/dist/lib/plan-poll.d.ts +171 -0
  30. package/dist/lib/plan-poll.js +442 -0
  31. package/dist/lib/plans.types.d.ts +130 -0
  32. package/dist/lib/plans.types.js +31 -0
  33. package/dist/lib/poll-support.d.ts +26 -0
  34. package/dist/lib/poll-support.js +65 -0
  35. package/dist/lib/poll.d.ts +1 -0
  36. package/dist/lib/poll.js +2 -40
  37. package/dist/lib/response-schemas.d.ts +13 -0
  38. package/dist/lib/response-schemas.js +46 -0
  39. package/dist/lib/run-progress.d.ts +41 -0
  40. package/dist/lib/run-progress.js +56 -0
  41. package/dist/lib/runs.types.d.ts +50 -0
  42. package/dist/lib/skill-nudge.d.ts +13 -5
  43. package/dist/lib/skill-nudge.js +40 -14
  44. package/dist/lib/target-url-preflight.js +3 -3
  45. package/dist/lib/target-url.d.ts +54 -8
  46. package/dist/lib/target-url.js +274 -68
  47. package/dist/lib/telemetry.d.ts +11 -0
  48. package/dist/lib/telemetry.js +1 -0
  49. package/dist/lib/ticker.d.ts +8 -0
  50. package/dist/lib/ticker.js +3 -0
  51. package/dist/lib/tunnel-session.d.ts +138 -0
  52. package/dist/lib/tunnel-session.js +249 -0
  53. package/dist/lib/tunnel.types.d.ts +54 -0
  54. package/dist/lib/tunnel.types.js +8 -0
  55. package/dist/vendor/tunnel-client/client.d.ts +82 -0
  56. package/dist/vendor/tunnel-client/client.js +924 -0
  57. package/dist/vendor/tunnel-client/config.d.ts +49 -0
  58. package/dist/vendor/tunnel-client/config.js +50 -0
  59. package/dist/vendor/tunnel-client/index.d.ts +9 -0
  60. package/dist/vendor/tunnel-client/index.js +9 -0
  61. package/dist/vendor/tunnel-client/lodash-lite.d.ts +14 -0
  62. package/dist/vendor/tunnel-client/lodash-lite.js +24 -0
  63. package/dist/vendor/tunnel-client/protocol.d.ts +60 -0
  64. package/dist/vendor/tunnel-client/protocol.js +143 -0
  65. package/dist/vendor/tunnel-client/types.d.ts +101 -0
  66. package/dist/vendor/tunnel-client/types.js +10 -0
  67. package/dist/vendor/tunnel-client/ws-compat.d.ts +206 -0
  68. package/dist/vendor/tunnel-client/ws-compat.js +316 -0
  69. package/dist/version.d.ts +1 -1
  70. package/dist/version.js +1 -1
  71. package/package.json +2 -1
  72. package/skills/testsprite-onboard.skill.md +60 -4
  73. package/skills/testsprite-verify.codex.md +22 -16
  74. package/skills/testsprite-verify.skill.md +27 -18
@@ -1,6 +1,7 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
- import { MANAGED_SECTION_BEGIN, MANAGED_SECTION_END, TARGETS } from './agent-targets.js';
3
+ import { MANAGED_SECTION_BEGIN, MANAGED_SECTION_END, TARGETS, } from './agent-targets.js';
4
+ import { detectCallerFromEnv } from './agent-detect.js';
4
5
  import { defaultCredentialsPath, readProfile } from './credentials.js';
5
6
  /**
6
7
  * Full command paths (group + leaf) that signal the caller is actively driving
@@ -51,11 +52,11 @@ export function isPlanTemplateInvocation(commandPath, planTemplate) {
51
52
  return commandPath === 'test create' && planTemplate === true;
52
53
  }
53
54
  /**
54
- * True if the `testsprite-verify` skill is installed for ANY supported agent in
55
- * `dir`. own-file targets (claude/cursor/cline/antigravity): the landing file
56
- * exists. managed-section target (codex / AGENTS.md): the file exists AND
57
- * carries one complete managed section — a user-authored AGENTS.md without the
58
- * sentinels, or with a truncated section, does NOT count as our skill.
55
+ * True if the `testsprite-verify` skill is installed in `dir` — for any
56
+ * supported agent, or only for `deps.requiredTargets` when given. own-file
57
+ * targets: the landing file exists. managed-section target (codex / AGENTS.md):
58
+ * the file exists AND carries one complete managed section — a user-authored
59
+ * AGENTS.md without the sentinels, or with a truncated section, does NOT count.
59
60
  *
60
61
  * The TARGETS table is the single source of truth for landing paths, so this
61
62
  * stays in lockstep with `agent install` without re-listing paths. Best-effort:
@@ -64,7 +65,11 @@ export function isPlanTemplateInvocation(commandPath, planTemplate) {
64
65
  export function isVerifySkillInstalled(dir, deps = {}) {
65
66
  const exists = deps.existsSync ?? existsSync;
66
67
  const read = deps.readFileSync ?? ((p) => readFileSync(p, 'utf8'));
67
- for (const spec of Object.values(TARGETS)) {
68
+ const wanted = new Set(deps.requiredTargets ?? []);
69
+ const specs = Object.entries(TARGETS)
70
+ .filter(([target]) => wanted.size === 0 || wanted.has(target))
71
+ .map(([, spec]) => spec);
72
+ for (const spec of specs) {
68
73
  const full = join(dir, spec.path);
69
74
  if (!exists(full))
70
75
  continue;
@@ -117,16 +122,37 @@ export function maybeEmitSkillNudge(ctx) {
117
122
  const profile = lookup(ctx.profile, { path: credsPath });
118
123
  if (!profile?.apiKey)
119
124
  return;
120
- if (isVerifySkillInstalled(ctx.cwd, {
121
- existsSync: ctx.existsSync,
122
- readFileSync: ctx.readFileSync,
123
- })) {
125
+ const presence = { existsSync: ctx.existsSync, readFileSync: ctx.readFileSync };
126
+ // When the environment names the calling agent, only that agent's skill
127
+ // counts — an install for a different agent is one this caller cannot read.
128
+ //
129
+ // Checked PER caller and ANDed, never as one set. `isVerifySkillInstalled`
130
+ // answers "any of these targets", so handing it the whole set lets one
131
+ // satisfied caller hide another's miss: with both CLAUDECODE and
132
+ // CURSOR_AGENT present — a nested shell that still carries the outer
133
+ // agent's variable — a project wired only for claude would fall silent for
134
+ // cursor, which is the exact silent miss this check exists to remove.
135
+ const callers = detectCallerFromEnv(ctx.env).map(d => d.target);
136
+ const missing = callers.filter(target => !isVerifySkillInstalled(ctx.cwd, { ...presence, requiredTargets: [target] }));
137
+ if (callers.length > 0) {
138
+ if (missing.length === 0)
139
+ return;
140
+ }
141
+ else if (isVerifySkillInstalled(ctx.cwd, presence)) {
142
+ // No identified caller: the any-target answer is all this can support.
124
143
  return;
125
144
  }
126
145
  const write = ctx.stderr ?? ((line) => process.stderr.write(`${line}\n`));
127
- write('[warn] No TestSprite verification skill is installed in this project — your coding ' +
128
- 'agent will not verify its changes against TestSprite. Run `testsprite setup` (or ' +
129
- `\`testsprite agent install\`) to set it up. Silence: ${SKILL_NUDGE_OPT_OUT_ENV}=1`);
146
+ // Names the callers actually missing a skill, not every caller detected —
147
+ // with one of two satisfied, "not for cursor" is the actionable half and
148
+ // "not for claude or cursor" would be wrong about claude.
149
+ const forOtherAgent = missing.length > 0 && isVerifySkillInstalled(ctx.cwd, presence);
150
+ const subject = forOtherAgent
151
+ ? `The TestSprite verification skill is installed, but not for ${missing.join(' or ')}`
152
+ : 'No TestSprite verification skill is installed in this project';
153
+ write(`[warn] ${subject} — your coding agent will not verify its changes against ` +
154
+ 'TestSprite. Run `testsprite setup` (or `testsprite agent install`) to set it up. ' +
155
+ `Silence: ${SKILL_NUDGE_OPT_OUT_ENV}=1`);
130
156
  }
131
157
  catch {
132
158
  // A nudge must never break, delay, or alter the exit status of a real
@@ -148,11 +148,11 @@ export async function probeTargetUrl(rawUrl, deps = {}) {
148
148
  // "can't tell from here" result, and a false positive has a documented
149
149
  // escape hatch (`--skip-preflight`) rather than a broken workflow.
150
150
  for (const address of resolvedAddresses(lookupResult)) {
151
- const blockedReason = disallowedIpReason(address);
152
- if (blockedReason !== undefined) {
151
+ const blocked = disallowedIpReason(address);
152
+ if (blocked !== undefined) {
153
153
  return {
154
154
  verdict: 'refuse',
155
- reason: `--target-url host "${host}" resolves to ${address} (${blockedReason})`,
155
+ reason: `--target-url host "${host}" resolves to ${address} (${blocked.reason})`,
156
156
  };
157
157
  }
158
158
  }
@@ -2,7 +2,7 @@
2
2
  * CLI-side pre-flight guard for `--target-url`.
3
3
  *
4
4
  * Defense-in-depth: the backend is the trust boundary and performs DNS
5
- * resolution. `assertNotLocal` below does **string/literal-only** checks
5
+ * resolution. `assertNotLocal` below does **literal-only** checks
6
6
  * to give a fast, friendly error before sending the request — it cannot by
7
7
  * itself detect DNS rebinding (a public hostname that resolves to a private
8
8
  * IP). That gap is closed one layer up: `target-url-preflight.ts` reuses
@@ -12,24 +12,69 @@
12
12
  *
13
13
  * CLI-side target-url guard (exit 5 on any rejection):
14
14
  * - Reject non-http(s) schemes
15
- * - Reject `localhost`, `127.0.0.0/8`, `0.0.0.0`, and IPv6 loopback/unspecified (`::1`, `::`)
15
+ * - Reject `localhost`, `127.0.0.0/8`, `0.0.0.0/8`, and IPv6 loopback/unspecified (`::1`, `::`)
16
16
  * - Reject `169.254.0.0/16` link-local and the `169.254.169.254` metadata address
17
17
  * - Reject RFC1918 literal IPv4 (10.x, 172.16-31.x, 192.168.x)
18
- * - Reject IPv4-mapped IPv6 (`::ffff:…`), IPv6 link-local (`fe80::/10`), unique-local (`fc00::/7`)
18
+ * - Reject carrier-grade NAT (`100.64.0.0/10`), multicast (`224.0.0.0/4`),
19
+ * and class E / limited broadcast (`240.0.0.0/4`)
20
+ * - Decode and re-classify the low 32 bits of standard embedded-IPv4 forms:
21
+ * IPv4-mapped/translated, RFC 6052 NAT64 (`64:ff9b::/96`), and deprecated
22
+ * IPv4-compatible (`::/96`); public embedded IPv4 addresses stay allowed
23
+ * - Reject RFC 8215's NAT64 local-use range (`64:ff9b:1::/48`) wholesale
24
+ * - Reject IPv6 link-local (`fe80::/10`), unique-local (`fc00::/7`), and
25
+ * deprecated site-local (`fec0::/10`)
19
26
  */
27
+ type TargetUrlHintContext = 'runtime' | 'bootstrap';
28
+ export interface TargetUrlCaller {
29
+ /** CLI flag name without the leading `--`, used in the error envelope. */
30
+ field: string;
31
+ /** Command prefix without `--help`, for example `testsprite project create`. */
32
+ helpCommand: string;
33
+ hintContext?: TargetUrlHintContext;
34
+ }
20
35
  /**
21
36
  * Throws a local `VALIDATION_ERROR` (exit 5) when `rawUrl` is a
22
- * disallowed target — localhost, RFC1918 literal IP, link-local, or
23
- * metadata-service address. Also rejects non-http(s) schemes.
37
+ * disallowed target — localhost or a private/reserved literal IP. Also rejects
38
+ * non-http(s) schemes.
24
39
  *
25
40
  * Silently returns on allowed URLs.
26
41
  */
27
- export declare function assertNotLocal(rawUrl: string): void;
42
+ export declare function assertNotLocal(rawUrl: string, caller?: TargetUrlCaller): void;
43
+ /**
44
+ * One disallowed-address classification: the human-readable reason (used
45
+ * verbatim in the rejection message — unchanged wording, not a new
46
+ * classification) plus a `hintKind` telling `assertNotLocal` which hint, if
47
+ * any, is honest to attach:
48
+ * - `'loopback'` — exactly the host set `--local-host` accepts
49
+ * (`localhost`, `127.0.0.1`, `::1`) plus the two unspecified addresses
50
+ * (`0.0.0.0`, `::`), which `--local`'s default dial also reaches because
51
+ * binding to "all interfaces" includes the loopback one; hint `--local`.
52
+ * - `'loopback-other'` — the REST of `127.0.0.0/8` (e.g. `127.0.0.2`). This
53
+ * is loopback-range and unreachable from outside the machine, same as
54
+ * `'loopback'` above, but `--local-host` cannot dial it by name — an app
55
+ * bound only to `127.0.0.2` does not answer on `127.0.0.1`. Hinting
56
+ * `--local` here would recommend a command that cannot reach the address
57
+ * it was just told about, so this gets no hint (a caller who reads the
58
+ * reason can rebind their dev server onto `127.0.0.1` and get `--local`
59
+ * to work, but that's their call to make, not a claim this code asserts).
60
+ * - `'private'` — `--local` can never reach this class even in principle;
61
+ * hint that plainly, with no tunnel suggestion.
62
+ * - `'undecided'` — the address genuinely cannot be decoded safely (currently
63
+ * RFC 8215's `/48` NAT64 local-use range, whose embedded bit position differs
64
+ * from the `/96` well-known prefix), so neither hint is knowably true.
65
+ *
66
+ * `target-url-preflight.ts` uses only `.reason` and is unaffected by this
67
+ * field's addition.
68
+ */
69
+ export interface DisallowedIpClassification {
70
+ reason: string;
71
+ hintKind: 'loopback' | 'loopback-other' | 'private' | 'undecided';
72
+ }
28
73
  /**
29
74
  * Classify a bare IP-address literal — IPv4 dotted form, or IPv6 optionally
30
75
  * wrapped in the `[...]` bracket notation `URL.hostname` uses — against the
31
76
  * private/loopback/link-local/metadata blocklist. Returns the disallowed
32
- * reason string, or `undefined` when the address is allowed.
77
+ * classification, or `undefined` when the address is allowed.
33
78
  *
34
79
  * This is the single source of truth for the range list: `assertNotLocal`
35
80
  * calls it for the literal `--target-url` string above, and the reachability
@@ -39,4 +84,5 @@ export declare function assertNotLocal(rawUrl: string): void;
39
84
  * literal private IP typed on the command line, and both need the same
40
85
  * range list, not two drifting copies of it.
41
86
  */
42
- export declare function disallowedIpReason(host: string): string | undefined;
87
+ export declare function disallowedIpReason(host: string): DisallowedIpClassification | undefined;
88
+ export {};
@@ -2,7 +2,7 @@
2
2
  * CLI-side pre-flight guard for `--target-url`.
3
3
  *
4
4
  * Defense-in-depth: the backend is the trust boundary and performs DNS
5
- * resolution. `assertNotLocal` below does **string/literal-only** checks
5
+ * resolution. `assertNotLocal` below does **literal-only** checks
6
6
  * to give a fast, friendly error before sending the request — it cannot by
7
7
  * itself detect DNS rebinding (a public hostname that resolves to a private
8
8
  * IP). That gap is closed one layer up: `target-url-preflight.ts` reuses
@@ -12,31 +12,70 @@
12
12
  *
13
13
  * CLI-side target-url guard (exit 5 on any rejection):
14
14
  * - Reject non-http(s) schemes
15
- * - Reject `localhost`, `127.0.0.0/8`, `0.0.0.0`, and IPv6 loopback/unspecified (`::1`, `::`)
15
+ * - Reject `localhost`, `127.0.0.0/8`, `0.0.0.0/8`, and IPv6 loopback/unspecified (`::1`, `::`)
16
16
  * - Reject `169.254.0.0/16` link-local and the `169.254.169.254` metadata address
17
17
  * - Reject RFC1918 literal IPv4 (10.x, 172.16-31.x, 192.168.x)
18
- * - Reject IPv4-mapped IPv6 (`::ffff:…`), IPv6 link-local (`fe80::/10`), unique-local (`fc00::/7`)
18
+ * - Reject carrier-grade NAT (`100.64.0.0/10`), multicast (`224.0.0.0/4`),
19
+ * and class E / limited broadcast (`240.0.0.0/4`)
20
+ * - Decode and re-classify the low 32 bits of standard embedded-IPv4 forms:
21
+ * IPv4-mapped/translated, RFC 6052 NAT64 (`64:ff9b::/96`), and deprecated
22
+ * IPv4-compatible (`::/96`); public embedded IPv4 addresses stay allowed
23
+ * - Reject RFC 8215's NAT64 local-use range (`64:ff9b:1::/48`) wholesale
24
+ * - Reject IPv6 link-local (`fe80::/10`), unique-local (`fc00::/7`), and
25
+ * deprecated site-local (`fec0::/10`)
19
26
  */
27
+ import * as net from 'node:net';
20
28
  import { ApiError } from './errors.js';
21
- const LOCAL_DEV_HINT = 'Local-dev tests are out of scope for the CLI; use testsprite-mcp-plugin for the local tunnel.';
29
+ // `--local-host` accepts EXACTLY `localhost`, `127.0.0.1`, `::1` (mirroring
30
+ // the server's `isLoopbackString`) — not "anything loopback-shaped". This
31
+ // hint is only honest for those three literal hosts (`0.0.0.0` and `::`
32
+ // join them below because binding to the unspecified address also answers
33
+ // on `127.0.0.1`/`::1`, so `--local`'s default dial reaches it) — NOT for
34
+ // the rest of `127.0.0.0/8`, which `--local` cannot dial by name at all. See
35
+ // `'loopback-other'` below for that distinction.
36
+ const LOCAL_DEV_RUNTIME_HINT = "This looks like a local-dev target. Run it with `testsprite test run <test-id> --local <port>` instead — it tunnels this machine's loopback address to the test runner (frontend tests only; requires an API key with the `run:tunnel` scope).";
37
+ // Project/test creation happens before the caller necessarily has a test id
38
+ // (and project create happens before they have a project at all). Lead those
39
+ // callers through the required public project URL first, then name the per-run
40
+ // loopback tunnel only after the test exists.
41
+ const LOCAL_DEV_BOOTSTRAP_HINT = "TestSprite executes tests from the cloud, so a project's URL must be an internet-reachable address the runner can use. " +
42
+ 'Set the project to its deployed or staging URL. ' +
43
+ 'After a test exists, target an app on this machine for an individual run with ' +
44
+ "`testsprite test run <test-id> --local <port>`; that tunnel is per-run and does not make localhost the project's URL.";
45
+ const DEFAULT_TARGET_URL_CALLER = {
46
+ field: 'target-url',
47
+ helpCommand: 'testsprite test run',
48
+ hintContext: 'runtime',
49
+ };
50
+ // Private, reserved, link-local, and metadata addresses are network-reachable from
51
+ // the caller's own machine in general (a LAN or VPN address usually answers)
52
+ // — what is actually true, and all this hint claims, is that TestSprite's
53
+ // execution modes cannot target them: `--target-url` refuses them outright,
54
+ // and `--local`'s tunnel only ever dials `localhost` / `127.0.0.1` / `::1`
55
+ // on THIS machine, never a LAN/VPC address. Embedded IPv4 addresses inherit
56
+ // this hint only after their decoded IPv4 address lands in this class.
57
+ const PRIVATE_NETWORK_HINT = 'This is a private/reserved network address (private, link-local, multicast, or metadata). ' +
58
+ 'TestSprite cannot use it as --target-url, and --local cannot tunnel it either — --local only ' +
59
+ 'reaches localhost, 127.0.0.1, or ::1 on this machine.';
22
60
  /**
23
61
  * Throws a local `VALIDATION_ERROR` (exit 5) when `rawUrl` is a
24
- * disallowed target — localhost, RFC1918 literal IP, link-local, or
25
- * metadata-service address. Also rejects non-http(s) schemes.
62
+ * disallowed target — localhost or a private/reserved literal IP. Also rejects
63
+ * non-http(s) schemes.
26
64
  *
27
65
  * Silently returns on allowed URLs.
28
66
  */
29
- export function assertNotLocal(rawUrl) {
67
+ export function assertNotLocal(rawUrl, caller = DEFAULT_TARGET_URL_CALLER) {
68
+ const { field, helpCommand, hintContext = 'runtime' } = caller;
30
69
  let parsed;
31
70
  try {
32
71
  parsed = new URL(rawUrl);
33
72
  }
34
73
  catch {
35
- throw localTargetError('target-url', 'must be a valid URL');
74
+ throw localTargetError(field, 'must be a valid URL', helpCommand);
36
75
  }
37
76
  // Scheme check.
38
77
  if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
39
- throw localTargetError('target-url', 'must use http or https scheme');
78
+ throw localTargetError(field, 'must use http or https scheme', helpCommand);
40
79
  }
41
80
  // Normalize a single trailing dot in the hostname. `localhost.` is the
42
81
  // fully-qualified form of `localhost` (RFC 6761 reserves both to resolve to
@@ -48,19 +87,42 @@ export function assertNotLocal(rawUrl) {
48
87
  const host = parsed.hostname.toLowerCase().replace(/\.$/, '');
49
88
  // 'localhost' is a name, not an IP literal, so it sits outside
50
89
  // `disallowedIpReason` below (which classifies IPv4/IPv6 address forms).
90
+ // It is also always loopback — the same class `--local` can reach.
51
91
  if (host === 'localhost') {
52
- throw localTargetError('target-url', 'localhost targets are not allowed', LOCAL_DEV_HINT);
92
+ throw localTargetError(field, 'localhost targets are not allowed', helpCommand, localDevHintFor(hintContext));
53
93
  }
54
- const reason = disallowedIpReason(host);
55
- if (reason !== undefined) {
56
- throw localTargetError('target-url', reason, LOCAL_DEV_HINT);
94
+ const disallowed = disallowedIpReason(host);
95
+ if (disallowed !== undefined) {
96
+ throw localTargetError(field, disallowed.reason, helpCommand, hintFor(disallowed.hintKind, hintContext));
97
+ }
98
+ }
99
+ function localDevHintFor(hintContext) {
100
+ return hintContext === 'bootstrap' ? LOCAL_DEV_BOOTSTRAP_HINT : LOCAL_DEV_RUNTIME_HINT;
101
+ }
102
+ /**
103
+ * Map a classification's `hintKind` to the hint text `assertNotLocal` attaches
104
+ * to the rejection — or no hint at all for `'loopback-other'`/`'undecided'`.
105
+ * Kept as its own function so the four-way mapping is a single, testable
106
+ * spot rather than a nested ternary repeated wherever a classification is
107
+ * consumed.
108
+ */
109
+ function hintFor(hintKind, hintContext) {
110
+ switch (hintKind) {
111
+ case 'loopback':
112
+ return localDevHintFor(hintContext);
113
+ case 'loopback-other':
114
+ return undefined;
115
+ case 'private':
116
+ return PRIVATE_NETWORK_HINT;
117
+ case 'undecided':
118
+ return undefined;
57
119
  }
58
120
  }
59
121
  /**
60
122
  * Classify a bare IP-address literal — IPv4 dotted form, or IPv6 optionally
61
123
  * wrapped in the `[...]` bracket notation `URL.hostname` uses — against the
62
124
  * private/loopback/link-local/metadata blocklist. Returns the disallowed
63
- * reason string, or `undefined` when the address is allowed.
125
+ * classification, or `undefined` when the address is allowed.
64
126
  *
65
127
  * This is the single source of truth for the range list: `assertNotLocal`
66
128
  * calls it for the literal `--target-url` string above, and the reachability
@@ -78,86 +140,230 @@ export function disallowedIpReason(host) {
78
140
  // address family explicitly. A DNS-resolved IPv6 address arrives
79
141
  // unbracketed already; stripping is a no-op for that shape.
80
142
  const bare = host.startsWith('[') && host.endsWith(']') ? host.slice(1, -1) : host;
81
- if (bare.includes(':')) {
82
- return disallowedIpv6Reason(bare);
143
+ const addressFamily = net.isIP(bare);
144
+ if (addressFamily === 6) {
145
+ return disallowedIpv6Reason(bare.toLowerCase());
146
+ }
147
+ return addressFamily === 4 ? disallowedIpv4Reason(bare) : undefined;
148
+ }
149
+ function disallowedIpv4Reason(address) {
150
+ // Unspecified — binds every interface, including loopback.
151
+ if (address === '0.0.0.0') {
152
+ return { reason: 'localhost targets are not allowed', hintKind: 'loopback' };
153
+ }
154
+ // Only the literal 127.0.0.1 is in `--local-host`'s exact accepted set.
155
+ if (ipv4LoopbackBlocklist.check(address, 'ipv4')) {
156
+ return {
157
+ reason: 'loopback addresses are not allowed',
158
+ hintKind: address === '127.0.0.1' ? 'loopback' : 'loopback-other',
159
+ };
83
160
  }
84
- // Unspecified.
85
- if (bare === '0.0.0.0') {
86
- return 'localhost targets are not allowed';
161
+ // AWS instance-metadata service. Keep the specific diagnostic ahead of the
162
+ // enclosing link-local subnet rule.
163
+ if (address === '169.254.169.254') {
164
+ return {
165
+ reason: '169.254.169.254 (AWS metadata service) is not allowed',
166
+ hintKind: 'private',
167
+ };
87
168
  }
88
- // 127.0.0.0/8 loopback range.
89
- if (/^127\.\d+\.\d+\.\d+$/.test(bare)) {
90
- return 'loopback addresses are not allowed';
169
+ if (ipv4ThisNetworkBlocklist.check(address, 'ipv4')) {
170
+ return { reason: 'reserved "this network" addresses are not allowed', hintKind: 'private' };
91
171
  }
92
- // AWS instance-metadata service.
93
- if (bare === '169.254.169.254') {
94
- return '169.254.169.254 (AWS metadata service) is not allowed';
172
+ if (ipv4LinkLocalBlocklist.check(address, 'ipv4')) {
173
+ return { reason: 'link-local addresses are not allowed', hintKind: 'private' };
95
174
  }
96
- // 169.254.x.x link-local (IPv4).
97
- if (/^169\.254\.\d+\.\d+$/.test(bare)) {
98
- return 'link-local addresses are not allowed';
175
+ if (ipv4Rfc1918Blocklist.check(address, 'ipv4')) {
176
+ return { reason: 'private/RFC1918 addresses are not allowed', hintKind: 'private' };
99
177
  }
100
- // RFC1918 literal IP addresses.
101
- if (isRfc1918Literal(bare)) {
102
- return 'private/RFC1918 addresses are not allowed';
178
+ if (ipv4CgnatBlocklist.check(address, 'ipv4')) {
179
+ return { reason: 'carrier-grade NAT addresses are not allowed', hintKind: 'private' };
180
+ }
181
+ if (ipv4MulticastBlocklist.check(address, 'ipv4')) {
182
+ return { reason: 'multicast addresses are not allowed', hintKind: 'private' };
183
+ }
184
+ if (ipv4ClassEBlocklist.check(address, 'ipv4')) {
185
+ return { reason: 'reserved/class E addresses are not allowed', hintKind: 'private' };
103
186
  }
104
187
  return undefined;
105
188
  }
106
- function isRfc1918Literal(host) {
107
- // 10.0.0.0/8
108
- if (/^10\.\d+\.\d+\.\d+$/.test(host))
109
- return true;
110
- // 192.168.0.0/16
111
- if (/^192\.168\.\d+\.\d+$/.test(host))
112
- return true;
113
- // 172.16.0.0/12 (172.16.x.x – 172.31.x.x)
114
- const m = host.match(/^172\.(\d+)\.\d+\.\d+$/);
115
- if (m) {
116
- const second = parseInt(m[1], 10);
117
- if (second >= 16 && second <= 31)
118
- return true;
119
- }
120
- return false;
189
+ /**
190
+ * Standard IPv6 forms that encode a literal IPv4 address in their low 32 bits —
191
+ * IPv4-mapped (`::ffff:a.b.c.d`), IPv4-translated (`::ffff:0:a.b.c.d`),
192
+ * RFC 6052's well-known NAT64 prefix (`64:ff9b::/96`), and IPv4-compatible
193
+ * (deprecated, `::a.b.c.d`). RFC 8215's local-use `64:ff9b:1::/48` is a
194
+ * separate blanket refusal because its embedded address is not in the low
195
+ * 32 bits.
196
+ *
197
+ * `net.BlockList` — binary subnet matching, not a per-spelling regex or
198
+ * `startsWith` — is what makes the spelling question go away entirely: the
199
+ * WHATWG URL parser COMPRESSES some of these forms
200
+ * (`0:0:0:0:0:ffff:a9fe:a9fe` → `::ffff:a9fe:a9fe`) while it PRESERVES others
201
+ * verbatim (`::ffff:0:a9fe:a9fe` stays exactly as typed), so a check tuned to
202
+ * one textual shape reliably misses the other — which is exactly how
203
+ * `64:ff9b::a9fe:a9fe` (NAT64-encoded AWS metadata) once reached the network
204
+ * unrejected. Binary matching also holds for NON-canonical input, which a
205
+ * `startsWith` check on a canonical-form assumption does not.
206
+ *
207
+ * Each class keeps its own list so it can be decoded only where its prefix
208
+ * defines the low 32 bits as IPv4. The three are checked mapped → NAT64 →
209
+ * compatible, preserving the established class precedence.
210
+ *
211
+ * This is the SAME primitive `src/vendor/tunnel-client/client.ts`'s
212
+ * `blockedTargetReason` already uses for the identical problem (see its
213
+ * VENDOR.md deltas #7/#10) — the two host classifiers in this repo now
214
+ * share one mechanism instead of two independently maintained spelling
215
+ * lists, so a future NAT64-shaped bypass can't reopen only one of them.
216
+ *
217
+ * The matched `/96` forms are decoded from their final two 16-bit groups and
218
+ * re-classified through the IPv4 blocklists. This makes an embedded public
219
+ * address public while preserving the decoded address's exact hint class.
220
+ */
221
+ const IPV4_MAPPED_SUBNETS = [
222
+ // Exact `/96` prefixes whose canonical `::` head contains only zero/ffff
223
+ // groups. Keeping them exact avoids the old `/80` rule's false positives on
224
+ // a non-embedded group while covering mapped, translated, and repeated-ffff
225
+ // spellings on the same binary value seen by URL and DNS paths.
226
+ ['0:0:0:0:0:ffff:0:0', 96],
227
+ ['0:0:0:0:ffff:0:0:0', 96],
228
+ ['0:0:0:0:ffff:ffff:0:0', 96],
229
+ ['0:0:0:ffff:0:0:0:0', 96],
230
+ ['0:0:0:ffff:0:ffff:0:0', 96],
231
+ ['0:0:0:ffff:ffff:0:0:0', 96],
232
+ ['0:0:0:ffff:ffff:ffff:0:0', 96],
233
+ ['0:0:ffff:0:0:ffff:0:0', 96],
234
+ ['0:0:ffff:0:ffff:0:0:0', 96],
235
+ ['0:0:ffff:0:ffff:ffff:0:0', 96],
236
+ ['0:0:ffff:ffff:0:0:0:0', 96],
237
+ ['0:0:ffff:ffff:0:ffff:0:0', 96],
238
+ ['0:0:ffff:ffff:ffff:0:0:0', 96],
239
+ ['0:0:ffff:ffff:ffff:ffff:0:0', 96],
240
+ ];
241
+ /**
242
+ * The RFC 6052 well-known prefix stores IPv4 in the final 32 bits, so it can
243
+ * be decoded. RFC 8215 local-use has a different bit layout and stays a
244
+ * separate, undecoded `/48` blanket refusal.
245
+ */
246
+ const NAT64_SUBNETS = [['64:ff9b::', 96]];
247
+ const NAT64_LOCAL_USE_SUBNETS = [['64:ff9b:1::', 48]];
248
+ /**
249
+ * Deprecated IPv4-compatible addresses use `::/96`; a broader `::/32` would
250
+ * read genuine IPv6 interface bits as IPv4 and reject targets the backend
251
+ * accepts. `::` and `::1` are exact-matched before this list is consulted.
252
+ */
253
+ const IPV4_COMPATIBLE_SUBNETS = [['::', 96]];
254
+ function blocklistOf(subnets, family) {
255
+ const list = new net.BlockList();
256
+ for (const [network, prefix] of subnets) {
257
+ list.addSubnet(network, prefix, family);
258
+ }
259
+ return list;
260
+ }
261
+ const ipv4ThisNetworkBlocklist = blocklistOf([['0.0.0.0', 8]], 'ipv4');
262
+ const ipv4LoopbackBlocklist = blocklistOf([['127.0.0.0', 8]], 'ipv4');
263
+ const ipv4Rfc1918Blocklist = blocklistOf([
264
+ ['10.0.0.0', 8],
265
+ ['172.16.0.0', 12],
266
+ ['192.168.0.0', 16],
267
+ ], 'ipv4');
268
+ const ipv4CgnatBlocklist = blocklistOf([['100.64.0.0', 10]], 'ipv4');
269
+ const ipv4LinkLocalBlocklist = blocklistOf([['169.254.0.0', 16]], 'ipv4');
270
+ const ipv4MulticastBlocklist = blocklistOf([['224.0.0.0', 4]], 'ipv4');
271
+ const ipv4ClassEBlocklist = blocklistOf([['240.0.0.0', 4]], 'ipv4');
272
+ const ipv4MappedBlocklist = blocklistOf(IPV4_MAPPED_SUBNETS, 'ipv6');
273
+ const nat64Blocklist = blocklistOf(NAT64_SUBNETS, 'ipv6');
274
+ const nat64LocalUseBlocklist = blocklistOf(NAT64_LOCAL_USE_SUBNETS, 'ipv6');
275
+ const ipv4CompatibleBlocklist = blocklistOf(IPV4_COMPATIBLE_SUBNETS, 'ipv6');
276
+ const ipv6LinkLocalBlocklist = blocklistOf([['fe80::', 10]], 'ipv6');
277
+ const ipv6UniqueLocalBlocklist = blocklistOf([['fc00::', 7]], 'ipv6');
278
+ const ipv6SiteLocalBlocklist = blocklistOf([['fec0::', 10]], 'ipv6');
279
+ function decodeLow32BitsAsIpv4(address) {
280
+ const groups = address.split(':');
281
+ const last = groups.at(-1);
282
+ if (last === undefined)
283
+ return undefined;
284
+ // A DNS result can preserve the human-written dotted tail even though the
285
+ // WHATWG URL path canonicalises it to two hex groups.
286
+ if (net.isIP(last) === 4)
287
+ return last;
288
+ const secondLast = groups.at(-2);
289
+ if (secondLast === undefined)
290
+ return undefined;
291
+ const high = Number.parseInt(secondLast, 16);
292
+ const low = Number.parseInt(last, 16);
293
+ if (!Number.isInteger(high) || !Number.isInteger(low))
294
+ return undefined;
295
+ return `${(high >> 8) & 0xff}.${high & 0xff}.${(low >> 8) & 0xff}.${low & 0xff}`;
296
+ }
297
+ function reclassifyEmbeddedIpv4(address, label) {
298
+ const decoded = decodeLow32BitsAsIpv4(address);
299
+ if (decoded === undefined) {
300
+ return {
301
+ reason: `${label} address could not be decoded safely`,
302
+ hintKind: 'undecided',
303
+ };
304
+ }
305
+ const decodedClassification = disallowedIpv4Reason(decoded);
306
+ if (decodedClassification === undefined)
307
+ return undefined;
308
+ return {
309
+ reason: `${label} address embeds disallowed IPv4 address ${decoded}: ${decodedClassification.reason}`,
310
+ hintKind: decodedClassification.hintKind,
311
+ };
121
312
  }
122
313
  /**
123
314
  * Classify disallowed IPv6 literals: loopback (`::1`), unspecified (`::`),
124
- * IPv4-mapped (`::ffff:…`), link-local (`fe80::/10`), and unique-local
125
- * (`fc00::/7`). `inner` is the bracket-stripped host; callers are
126
- * responsible for lowercasing (the URL parser already lowercases hostnames,
127
- * a DNS-resolved address is emitted lowercase by Node).
128
- *
129
- * The IPv4-mapped class is rejected wholesale rather than decoding the
130
- * embedded v4 address: no legitimate target is expressed as a mapped
131
- * literal, and the hex-normalized form (`::ffff:7f00:1`) is error-prone to
132
- * decode. This closes the `http://[::ffff:127.0.0.1]` SSRF-guard bypass.
315
+ * the embedded-IPv4 family (see {@link IPV4_MAPPED_SUBNETS}'s doc comment),
316
+ * link-local (`fe80::/10`), unique-local (`fc00::/7`), and deprecated
317
+ * site-local (`fec0::/10`). `inner` is the
318
+ * bracket-stripped, already-lowercased host — `disallowedIpReason` lowercases
319
+ * it on the way in rather than trusting every caller to.
133
320
  */
134
321
  function disallowedIpv6Reason(inner) {
135
322
  // Loopback (::1) and unspecified (::).
136
323
  if (inner === '::1' || inner === '::') {
137
- return 'localhost targets are not allowed';
324
+ return { reason: 'localhost targets are not allowed', hintKind: 'loopback' };
325
+ }
326
+ // Embedded-IPv4 family, checked mapped → NAT64 → compatible. Standard /96
327
+ // forms inherit the decoded IPv4 classification; RFC 8215 local-use stays
328
+ // wholesale and undecided because its embedded address has a different bit
329
+ // position.
330
+ if (ipv4MappedBlocklist.check(inner, 'ipv6')) {
331
+ return reclassifyEmbeddedIpv4(inner, 'IPv4-mapped/translated IPv6');
332
+ }
333
+ if (nat64Blocklist.check(inner, 'ipv6')) {
334
+ return reclassifyEmbeddedIpv4(inner, 'NAT64-translated IPv6');
335
+ }
336
+ if (nat64LocalUseBlocklist.check(inner, 'ipv6')) {
337
+ return {
338
+ reason: 'NAT64 local-use addresses are not allowed',
339
+ hintKind: 'undecided',
340
+ };
341
+ }
342
+ if (ipv4CompatibleBlocklist.check(inner, 'ipv6')) {
343
+ return reclassifyEmbeddedIpv4(inner, 'IPv4-compatible/deprecated IPv6');
138
344
  }
139
- // IPv4-mapped IPv6 (`::ffff:a.b.c.d`, normalized to `::ffff:hhhh:hhhh`).
140
- if (inner.startsWith('::ffff:')) {
141
- return 'IPv4-mapped IPv6 addresses are not allowed; use the IPv4 form or a hostname';
345
+ if (ipv6LinkLocalBlocklist.check(inner, 'ipv6')) {
346
+ return { reason: 'link-local addresses are not allowed', hintKind: 'private' };
142
347
  }
143
- // Link-local fe80::/10 (first hextet fe80–febf).
144
- if (/^fe[89ab][0-9a-f]:/.test(inner)) {
145
- return 'link-local addresses are not allowed';
348
+ if (ipv6UniqueLocalBlocklist.check(inner, 'ipv6')) {
349
+ return { reason: 'unique-local (private) addresses are not allowed', hintKind: 'private' };
146
350
  }
147
- // Unique-local fc00::/7 (first hextet fc00–fdff).
148
- if (/^f[cd][0-9a-f]{2}:/.test(inner)) {
149
- return 'unique-local (private) addresses are not allowed';
351
+ if (ipv6SiteLocalBlocklist.check(inner, 'ipv6')) {
352
+ return {
353
+ reason: 'site-local (deprecated private) addresses are not allowed',
354
+ hintKind: 'private',
355
+ };
150
356
  }
151
357
  return undefined;
152
358
  }
153
- function localTargetError(field, reason, hint) {
359
+ function localTargetError(field, reason, helpCommand, hint) {
154
360
  return ApiError.fromEnvelope({
155
361
  error: {
156
362
  code: 'VALIDATION_ERROR',
157
363
  message: `Field \`${field}\` is invalid: ${reason}.`,
158
364
  nextAction: hint
159
- ? hint + ' See `testsprite test run --help` for accepted values.'
160
- : `See \`testsprite test run --help\` for accepted values.`,
365
+ ? hint + ` See \`${helpCommand} --help\` for accepted values.`
366
+ : `See \`${helpCommand} --help\` for accepted values.`,
161
367
  requestId: 'local',
162
368
  details: { field, reason, ...(hint ? { hint } : {}) },
163
369
  },
@@ -19,6 +19,15 @@ export interface TelemetryOutcomeInput {
19
19
  endpointUrl?: string;
20
20
  output?: string;
21
21
  dryRun?: boolean;
22
+ /**
23
+ * True when the invocation requested a local tunnel target (`test run
24
+ * --local <port>`) — the flag's mere presence, never its port number or
25
+ * host. Reported regardless of outcome, including a zero-network refusal
26
+ * (dead port, `--local` combined with an incompatible flag): those are
27
+ * exactly the attempts nothing server-side ever sees, which is why this
28
+ * field is not redundant with a backend-side mint/attach analytics event.
29
+ */
30
+ local?: boolean;
22
31
  }
23
32
  export interface TelemetryDeps {
24
33
  env?: NodeJS.ProcessEnv;
@@ -51,6 +60,8 @@ export interface TelemetryEvent {
51
60
  nodeVersion?: string;
52
61
  output?: string;
53
62
  ci?: boolean;
63
+ /** Present (always `true`) only for a `test run --local` invocation; absent otherwise. */
64
+ local?: boolean;
54
65
  }
55
66
  /**
56
67
  * Map a thrown CLI error to its telemetry disposition — mirrors the exit-code
@@ -88,6 +88,7 @@ export function buildTelemetryEvent(input, env, isTTY) {
88
88
  nodeVersion: process.versions.node,
89
89
  ...(input.output === 'json' || input.output === 'text' ? { output: input.output } : {}),
90
90
  ci: isTruthyEnv(env.CI) || !isTTY,
91
+ ...(input.local ? { local: true } : {}),
91
92
  };
92
93
  }
93
94
  /**