@vellumai/credential-executor 0.11.6-dev.202608261937.a51ea3f → 0.11.6-dev.202608262202.d09b5d7

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,389 @@
1
+ import { describe, expect, test } from "bun:test";
2
+
3
+ import {
4
+ buildRemoteWebPairingUrl,
5
+ isDnsIndependentLoopbackUrl,
6
+ isLoopbackPublicUrl,
7
+ isPrivateNetworkPublicUrl,
8
+ isRetryablePairingReason,
9
+ pairingSessionSurvives,
10
+ parsePairingAddress,
11
+ parseRemoteWebPairingParams,
12
+ resolvePublicBaseUrl,
13
+ RETRYABLE_PAIRING_REASONS,
14
+ type PairingFailureReason,
15
+ type PublicBaseUrlRejection,
16
+ } from "../remote-web-pairing.js";
17
+
18
+ describe("parseRemoteWebPairingParams", () => {
19
+ test("reads snake_case fragment parameters", () => {
20
+ expect(
21
+ parseRemoteWebPairingParams(
22
+ "https://assistant.example.com/assistant/pair#device_code=device-1&user_code=ABCD-EFGH",
23
+ ),
24
+ ).toEqual({ deviceCode: "device-1", userCode: "ABCD-EFGH" });
25
+ });
26
+
27
+ test("reads camelCase query parameters", () => {
28
+ expect(
29
+ parseRemoteWebPairingParams(
30
+ "https://assistant.example.com/assistant/pair?deviceCode=device-2&userCode=WXYZ-1234",
31
+ ),
32
+ ).toEqual({ deviceCode: "device-2", userCode: "WXYZ-1234" });
33
+ });
34
+
35
+ test("accepts a relative link", () => {
36
+ expect(
37
+ parseRemoteWebPairingParams("/assistant/pair#device_code=device-3"),
38
+ ).toEqual({ deviceCode: "device-3", userCode: null });
39
+ });
40
+
41
+ test("reports null when no codes are present", () => {
42
+ expect(
43
+ parseRemoteWebPairingParams("https://assistant.example.com/assistant"),
44
+ ).toEqual({ deviceCode: null, userCode: null });
45
+ });
46
+ });
47
+
48
+ describe("parsePairingAddress", () => {
49
+ test("splits a pairing link into its base and device code", () => {
50
+ const link = buildRemoteWebPairingUrl({
51
+ verificationUri: "https://assistant.example.com/assistant/pair",
52
+ deviceCode: "device-1",
53
+ });
54
+
55
+ expect(parsePairingAddress(link)).toEqual({
56
+ ok: true,
57
+ publicBaseUrl: "https://assistant.example.com",
58
+ deviceCode: "device-1",
59
+ });
60
+ });
61
+
62
+ test("accepts the device code in the query string", () => {
63
+ expect(
64
+ parsePairingAddress(
65
+ "https://assistant.example.com/assistant/pair?deviceCode=device-2",
66
+ ),
67
+ ).toEqual({
68
+ ok: true,
69
+ publicBaseUrl: "https://assistant.example.com",
70
+ deviceCode: "device-2",
71
+ });
72
+ });
73
+
74
+ test("preserves a path prefix while dropping the app-route suffix", () => {
75
+ expect(
76
+ parsePairingAddress(
77
+ "https://host.example.com/assistant-123/assistant/pair#device_code=device-3",
78
+ ),
79
+ ).toEqual({
80
+ ok: true,
81
+ publicBaseUrl: "https://host.example.com/assistant-123",
82
+ deviceCode: "device-3",
83
+ });
84
+ });
85
+
86
+ test("drops a trailing app-route suffix from a bare address", () => {
87
+ expect(
88
+ parsePairingAddress("https://assistant.example.com/assistant/pair"),
89
+ ).toEqual({
90
+ ok: true,
91
+ publicBaseUrl: "https://assistant.example.com",
92
+ deviceCode: null,
93
+ });
94
+ });
95
+
96
+ test("accepts a bare address with no device code", () => {
97
+ expect(parsePairingAddress("https://assistant.example.com")).toEqual({
98
+ ok: true,
99
+ publicBaseUrl: "https://assistant.example.com",
100
+ deviceCode: null,
101
+ });
102
+ });
103
+
104
+ test.each<[string, PublicBaseUrlRejection]>([
105
+ ["not a url", "unparseable"],
106
+ ["https://localhost:3000", "loopback"],
107
+ ["https://127.0.0.1:3000", "loopback"],
108
+ ["http://assistant.example.com", "non-https"],
109
+ ["https://login.tailscale.com/admin/invite/abc123", "service-website"],
110
+ ])("rejects %s", (raw, reason) => {
111
+ expect(parsePairingAddress(raw)).toEqual({ ok: false, reason });
112
+ });
113
+ });
114
+
115
+ describe("resolvePublicBaseUrl private-address containment", () => {
116
+ // A host POSTs to whatever address was pasted, so an IP literal aimed at the
117
+ // local network (or at 169.254.169.254, the cloud instance metadata
118
+ // endpoint) is a blind SSRF target and is refused before any request.
119
+ test.each([
120
+ ["https://0.0.0.0", "0/8"],
121
+ ["https://10.0.0.1", "10/8"],
122
+ ["https://10.255.255.254:8443", "10/8 with a port"],
123
+ ["https://169.254.169.254", "169.254/16 cloud metadata"],
124
+ ["https://172.16.0.1", "172.16/12 low edge"],
125
+ ["https://172.31.255.254", "172.16/12 high edge"],
126
+ ["https://192.0.0.8", "192.0.0/24"],
127
+ ["https://192.168.1.5", "192.168/16"],
128
+ ["https://198.18.0.1", "198.18/15"],
129
+ ["https://198.19.255.254", "198.18/15 high half"],
130
+ ["https://224.0.0.1", "224/4 multicast"],
131
+ ["https://240.0.0.1", "240/4 reserved"],
132
+ ["https://255.255.255.255", "broadcast"],
133
+ // WHATWG URL canonicalizes these to a dotted-quad before the check.
134
+ ["https://2130706433", "decimal-encoded 127.0.0.1"],
135
+ ["https://0xa000001", "hex-encoded 10.0.0.1"],
136
+ ["https://[::]", "IPv6 unspecified"],
137
+ ["https://[fd00::1]", "fc00::/7 unique-local"],
138
+ ["https://[fc00::5]", "fc00::/7 low edge"],
139
+ ["https://[fe80::1]", "fe80::/10 link-local"],
140
+ ["https://[ff02::1]", "ff00::/8 multicast"],
141
+ ["https://[::ffff:10.0.0.1]", "IPv4-mapped private"],
142
+ ["https://[::ffff:169.254.169.254]", "IPv4-mapped metadata"],
143
+ ["https://[::192.168.1.5]", "IPv4-compatible private"],
144
+ ])("refuses %s (%s)", (raw) => {
145
+ const result = resolvePublicBaseUrl(raw);
146
+ expect(result.ok).toBe(false);
147
+ if (result.ok) {
148
+ return;
149
+ }
150
+ // 127/8 and ::1 keep their more specific loopback reason.
151
+ expect(["private-address", "loopback"]).toContain(result.reason);
152
+ });
153
+
154
+ test.each([
155
+ "https://10.0.0.1",
156
+ "https://169.254.169.254",
157
+ "https://172.20.3.4",
158
+ "https://192.168.1.5",
159
+ "https://198.18.0.1",
160
+ "https://[fd00::1]",
161
+ "https://[fe80::1]",
162
+ "https://[::ffff:10.0.0.1]",
163
+ ])("reports %s as private-address, not loopback", (raw) => {
164
+ expect(resolvePublicBaseUrl(raw)).toEqual({
165
+ ok: false,
166
+ reason: "private-address",
167
+ });
168
+ });
169
+
170
+ // A wildcard bind reaches a listener on the machine that dials it, so it
171
+ // gets the more specific loopback reason and the "points back at this
172
+ // machine" guidance that goes with it.
173
+ test.each([
174
+ ["https://0.0.0.0", "IPv4 wildcard"],
175
+ ["https://[::]", "IPv6 wildcard"],
176
+ ["https://[::ffff:0.0.0.0]", "IPv4-mapped wildcard"],
177
+ ["https://[::ffff:127.0.0.1]", "IPv4-mapped loopback"],
178
+ ])("reports %s (%s) as loopback", (raw) => {
179
+ expect(isLoopbackPublicUrl(raw)).toBe(true);
180
+ expect(resolvePublicBaseUrl(raw)).toEqual({
181
+ ok: false,
182
+ reason: "loopback",
183
+ });
184
+ });
185
+
186
+ // Tailscale hands out 100.64.0.0/10 CGNAT addresses and `*.ts.net` names are
187
+ // a supported pairing target, so neither the range nor any hostname is
188
+ // filtered. Names are never resolved (see isPrivateNetworkPublicUrl).
189
+ test.each([
190
+ "https://my-box.tail1234.ts.net",
191
+ "https://assistant.example.com",
192
+ "https://100.101.102.103",
193
+ "https://[2606:4700::1111]",
194
+ "https://172.32.0.1",
195
+ "https://192.0.1.1",
196
+ "https://198.20.0.1",
197
+ "https://223.255.255.255",
198
+ ])("still resolves %s", (raw) => {
199
+ expect(resolvePublicBaseUrl(raw)).toEqual({ ok: true, url: raw });
200
+ });
201
+
202
+ test("isPrivateNetworkPublicUrl reports a plain hostname as public", () => {
203
+ expect(isPrivateNetworkPublicUrl("https://my-box.tail1234.ts.net")).toBe(
204
+ false,
205
+ );
206
+ expect(isPrivateNetworkPublicUrl("not a url")).toBe(false);
207
+ expect(isPrivateNetworkPublicUrl("https://192.168.0.1")).toBe(true);
208
+ });
209
+ });
210
+
211
+ describe("resolvePublicBaseUrl localhost normalization", () => {
212
+ // A terminal DNS root dot survives WHATWG parsing, and resolvers read the
213
+ // absolute name as loopback, so the dot is stripped before every host
214
+ // comparison. The whole `.localhost` namespace is reserved (RFC 6761) and
215
+ // resolves to loopback too.
216
+ test.each([
217
+ ["https://localhost.", "absolute localhost name"],
218
+ ["https://localhost.:3000", "absolute localhost name with a port"],
219
+ ["https://LOCALHOST.", "uppercase absolute localhost name"],
220
+ ["https://foo.localhost", "reserved .localhost namespace"],
221
+ ["https://foo.localhost.", "absolute .localhost namespace"],
222
+ ["https://a.b.localhost.", "nested .localhost namespace"],
223
+ ["https://127.0.0.1.", "absolute IPv4 loopback literal"],
224
+ ])("reports %s (%s) as loopback", (raw) => {
225
+ expect(isLoopbackPublicUrl(raw)).toBe(true);
226
+ expect(resolvePublicBaseUrl(raw)).toEqual({
227
+ ok: false,
228
+ reason: "loopback",
229
+ });
230
+ });
231
+
232
+ test("reports an absolute private literal as private-address", () => {
233
+ expect(isPrivateNetworkPublicUrl("https://10.0.0.1.")).toBe(true);
234
+ expect(resolvePublicBaseUrl("https://10.0.0.1.")).toEqual({
235
+ ok: false,
236
+ reason: "private-address",
237
+ });
238
+ });
239
+
240
+ test("reports an absolute vendor-site name as service-website", () => {
241
+ expect(resolvePublicBaseUrl("https://login.tailscale.com.")).toEqual({
242
+ ok: false,
243
+ reason: "service-website",
244
+ });
245
+ });
246
+
247
+ test.each([
248
+ "https://my-box.tail1234.ts.net.",
249
+ "https://assistant.example.com.",
250
+ "https://localhostage.example.com",
251
+ "https://mylocalhost.example.com.",
252
+ ])("still resolves %s", (raw) => {
253
+ expect(isLoopbackPublicUrl(raw)).toBe(false);
254
+ expect(resolvePublicBaseUrl(raw)).toEqual({ ok: true, url: raw });
255
+ });
256
+ });
257
+
258
+ describe("isDnsIndependentLoopbackUrl", () => {
259
+ test.each([
260
+ ["http://localhost:7830", "the exact name"],
261
+ ["http://LOCALHOST.:7830", "the absolute, uppercase name"],
262
+ ["http://127.0.0.1:7830", "an IPv4 loopback literal"],
263
+ ["http://127.9.9.9", "the rest of 127/8"],
264
+ ["http://[::1]:7830", "the IPv6 loopback literal"],
265
+ ["http://[::ffff:127.0.0.1]", "an IPv4-mapped loopback literal"],
266
+ ["http://0.0.0.0:7830", "the IPv4 wildcard bind"],
267
+ ["http://[::]:7830", "the IPv6 wildcard bind"],
268
+ ])("%s reaches this machine (%s)", (raw) => {
269
+ expect(isDnsIndependentLoopbackUrl(raw)).toBe(true);
270
+ expect(isLoopbackPublicUrl(raw)).toBe(true);
271
+ });
272
+
273
+ // RFC 6761 reserves the namespace and says resolvers should map it to
274
+ // loopback, but glibc does not by default, so the name is ordinary DNS and
275
+ // can answer with any address. The wide predicate still refuses it as
276
+ // loopback; the narrow one refuses to hand it a loopback privilege.
277
+ test.each([
278
+ ["https://foo.localhost", "reserved .localhost namespace"],
279
+ ["https://foo.localhost.", "absolute .localhost namespace"],
280
+ ["https://a.b.localhost", "nested .localhost namespace"],
281
+ ])("%s is loopback but not DNS-independent (%s)", (raw) => {
282
+ expect(isLoopbackPublicUrl(raw)).toBe(true);
283
+ expect(isDnsIndependentLoopbackUrl(raw)).toBe(false);
284
+ });
285
+
286
+ test.each([
287
+ "https://assistant.example.com",
288
+ "https://localhostage.example.com",
289
+ "https://10.0.0.5",
290
+ "not a url",
291
+ ])("%s is not loopback at all", (raw) => {
292
+ expect(isDnsIndependentLoopbackUrl(raw)).toBe(false);
293
+ expect(isLoopbackPublicUrl(raw)).toBe(false);
294
+ });
295
+ });
296
+
297
+ /** Every reason, so a classification table cannot silently miss one. */
298
+ const EVERY_PAIRING_REASON: PairingFailureReason[] = [
299
+ "invalid-address",
300
+ "unknown-session",
301
+ "expired",
302
+ "unreachable",
303
+ "gateway-retryable",
304
+ "gateway",
305
+ "import",
306
+ "import-precheck",
307
+ ];
308
+
309
+ describe("isRetryablePairingReason", () => {
310
+ test.each([
311
+ // Nothing reached the assistant, so the session and code are untouched.
312
+ "unreachable",
313
+ // The assistant refused with a status that released the code.
314
+ "gateway-retryable",
315
+ ] as const)("%s is worth another attempt", (reason) => {
316
+ expect(isRetryablePairingReason(reason)).toBe(true);
317
+ });
318
+
319
+ test.each([
320
+ "invalid-address",
321
+ "unknown-session",
322
+ "expired",
323
+ // The assistant answered with something unusable, past which the code is
324
+ // spent rather than released.
325
+ "gateway",
326
+ "import",
327
+ // Nothing was spent, but an identical attempt is refused identically:
328
+ // only a caller that changes the name it asked for gets past this.
329
+ "import-precheck",
330
+ ] as const)("%s settles the attempt", (reason) => {
331
+ expect(isRetryablePairingReason(reason)).toBe(false);
332
+ });
333
+
334
+ test("an absent reason settles the attempt", () => {
335
+ expect(isRetryablePairingReason(undefined)).toBe(false);
336
+ expect(isRetryablePairingReason(null)).toBe(false);
337
+ });
338
+
339
+ test("the exported set is exactly the reasons worth another attempt", () => {
340
+ expect(
341
+ EVERY_PAIRING_REASON.filter(isRetryablePairingReason).sort(),
342
+ ).toEqual(["gateway-retryable", "unreachable"]);
343
+ expect([...RETRYABLE_PAIRING_REASONS].sort()).toEqual([
344
+ "gateway-retryable",
345
+ "unreachable",
346
+ ]);
347
+ });
348
+ });
349
+
350
+ describe("pairingSessionSurvives", () => {
351
+ test.each([
352
+ // Nothing reached the assistant, so the session and code are untouched.
353
+ "unreachable",
354
+ // The assistant released the code before answering.
355
+ "gateway-retryable",
356
+ // The refusal happened before the exchange, so the code is unspent.
357
+ "import-precheck",
358
+ ] as const)("%s leaves the session pollable", (reason) => {
359
+ expect(pairingSessionSurvives(reason)).toBe(true);
360
+ });
361
+
362
+ test.each([
363
+ "invalid-address",
364
+ "unknown-session",
365
+ "expired",
366
+ "gateway",
367
+ // The exchange spent the code; only the local write failed.
368
+ "import",
369
+ ] as const)("%s leaves nothing to poll", (reason) => {
370
+ expect(pairingSessionSurvives(reason)).toBe(false);
371
+ });
372
+
373
+ test("an absent reason leaves nothing to poll", () => {
374
+ expect(pairingSessionSurvives(undefined)).toBe(false);
375
+ expect(pairingSessionSurvives(null)).toBe(false);
376
+ });
377
+
378
+ test("a pre-check refusal is the one reason the two axes disagree on", () => {
379
+ // A caller that reads retryability as "keep the session" throws away a
380
+ // device code that is still good, which is what this reason exists to
381
+ // prevent: nothing was spent, so the same handle completes the pairing
382
+ // once the caller supplies a name that is free.
383
+ const disagreeing = EVERY_PAIRING_REASON.filter(
384
+ (reason) =>
385
+ pairingSessionSurvives(reason) !== isRetryablePairingReason(reason),
386
+ );
387
+ expect(disagreeing).toEqual(["import-precheck"]);
388
+ });
389
+ });
@@ -9,8 +9,11 @@
9
9
  * `gateway/src/remote-web/pairing-challenge-store.ts`)
10
10
  * - `POST /v1/remote-web/pairing-verification` approve by user code
11
11
  * (`gateway/src/http/routes/remote-web-pairing-verification.ts`)
12
+ * (loopback-only)
12
13
  * - `POST /v1/remote-web/pairing-token` poll + exchange device code
13
- * (`gateway/src/http/routes/remote-web-pairing-token.ts`)
14
+ * (`gateway/src/http/routes/remote-web-pairing-token.ts`): a browser
15
+ * receives its refresh token as an `HttpOnly` cookie; a request that
16
+ * carries a `deviceId` receives a device-bound one in the body instead
14
17
  * - `GET /v1/remote-web/pairing-requests` list pending challenges
15
18
  * (loopback-only)
16
19
  * - `POST /v1/remote-web/pairing-requests/approve` approve by request id
@@ -19,7 +22,8 @@
19
22
  * (loopback-only)
20
23
  *
21
24
  * These shapes mirror those handlers' request/response bodies exactly so the
22
- * gateway, the `vellum pair` CLI (`cli/src/commands/pair.ts`), and the web SPA
25
+ * gateway, the `vellum pair` CLI (`cli/src/commands/pair.ts`), the host-side
26
+ * pairing sessions (`packages/local-mode/src/pair.ts`), and the web SPA
23
27
  * (`clients/web/src/lib/auth/remote-gateway-session.ts`) share one definition
24
28
  * and cannot silently drift.
25
29
  *
@@ -128,10 +132,51 @@ export interface RemoteWebPairingRequestDenyResponse {
128
132
  status: "denied";
129
133
  }
130
134
 
135
+ /**
136
+ * Platforms a device-bound pairing exchange may declare for itself. The value
137
+ * is what the host's `Paired devices` list renders for the new pairing.
138
+ */
139
+ export const REMOTE_WEB_PAIRING_PLATFORMS = [
140
+ "cli",
141
+ "desktop",
142
+ "ios",
143
+ "android",
144
+ ] as const;
145
+
146
+ export type RemoteWebPairingPlatform =
147
+ (typeof REMOTE_WEB_PAIRING_PLATFORMS)[number];
148
+
149
+ /** Platform recorded when an exchange names none the gateway recognizes. */
150
+ export const DEFAULT_REMOTE_WEB_PAIRING_PLATFORM: RemoteWebPairingPlatform =
151
+ "desktop";
152
+
153
+ /**
154
+ * A requested platform coerced to a known value. The pairing-token route is
155
+ * publicly reachable and the platform renders verbatim in the host's
156
+ * paired-devices list, so an unrecognized value never reaches the DB.
157
+ */
158
+ export function resolveRemoteWebPairingPlatform(
159
+ raw: unknown,
160
+ ): RemoteWebPairingPlatform {
161
+ return (
162
+ REMOTE_WEB_PAIRING_PLATFORMS.find((platform) => platform === raw) ??
163
+ DEFAULT_REMOTE_WEB_PAIRING_PLATFORM
164
+ );
165
+ }
166
+
131
167
  /** `POST /v1/remote-web/pairing-token` request body. */
132
168
  export interface RemoteWebPairingTokenRequest {
133
169
  /** The `deviceCode` from the challenge. */
134
170
  deviceCode: string;
171
+ /**
172
+ * Client-generated device id, sent only by a trusted host completing the
173
+ * exchange for itself. It switches the gateway to a device-bound, per-device
174
+ * revocable credential whose refresh token comes back in the response body.
175
+ * Browsers omit it and keep the cookie delivery.
176
+ */
177
+ deviceId?: string;
178
+ /** Platform to record for the device. Ignored without a `deviceId`. */
179
+ platform?: RemoteWebPairingPlatform;
135
180
  /**
136
181
  * Optional self-reported device name, for example "Vellum iOS app". The gateway
137
182
  * stores it verbatim (capped) and never trusts it for authorization. Absent from
@@ -154,8 +199,9 @@ export interface RemoteWebPairingTokenPendingResponse {
154
199
 
155
200
  /**
156
201
  * `POST /v1/remote-web/pairing-token` approved response body (200) — carries
157
- * the minted browser session credentials. The refresh token is delivered out
158
- * of band as an `HttpOnly` cookie, not in this body.
202
+ * the minted session credentials. A browser exchange (no `deviceId`) receives
203
+ * its refresh token out of band as an `HttpOnly` cookie and so omits the two
204
+ * refresh fields below; a device-bound exchange receives it here instead.
159
205
  */
160
206
  export interface RemoteWebPairingTokenApprovedResponse {
161
207
  status: "approved";
@@ -166,6 +212,10 @@ export interface RemoteWebPairingTokenApprovedResponse {
166
212
  refreshAfter: string;
167
213
  guardianId: string;
168
214
  assistantId: string;
215
+ /** Device-bound refresh token, present only for a `deviceId` exchange. */
216
+ refreshToken?: string;
217
+ /** ISO-8601 instant the device-bound refresh token expires. */
218
+ refreshTokenExpiresAt?: string;
169
219
  }
170
220
 
171
221
  /** Union of the two terminal `pairing-token` response bodies. */
@@ -175,7 +225,7 @@ export type RemoteWebPairingTokenResponse =
175
225
 
176
226
  // ── Shared pairing URL helpers ──────────────────────────────────────────────
177
227
  //
178
- // Every surface that mints a pairing (the `vellum pair --qr` CLI, the web
228
+ // Every surface that mints a pairing (the `vellum pair` CLI, the web
179
229
  // settings "Pair a device" card) must accept the same public URLs and build
180
230
  // the same scannable links. The helpers are environment-neutral (WHATWG URL
181
231
  // only) so both Node and browser callers share one implementation.
@@ -184,6 +234,7 @@ export type RemoteWebPairingTokenResponse =
184
234
  export type PublicBaseUrlRejection =
185
235
  | "unparseable"
186
236
  | "loopback"
237
+ | "private-address"
187
238
  | "non-https"
188
239
  | "service-website";
189
240
 
@@ -210,6 +261,16 @@ export const TUNNEL_PROVIDER_WEBSITE_HOSTS = [
210
261
  "www.cloudflare.com",
211
262
  ] as const;
212
263
 
264
+ /**
265
+ * A hostname with any trailing DNS root dot removed. `example.com.` and
266
+ * `example.com` name the same host, and a resolver reads `localhost.` as the
267
+ * loopback name, so every host comparison below runs on the stripped form.
268
+ * Bracketed IPv6 literals never carry one.
269
+ */
270
+ function hostnameWithoutRootDot(hostname: string): string {
271
+ return hostname.replace(/\.+$/, "");
272
+ }
273
+
213
274
  /**
214
275
  * A URL whose exact host is a tunnel/ingress vendor's own website (see
215
276
  * {@link TUNNEL_PROVIDER_WEBSITE_HOSTS}). Exact-host only: a user's real
@@ -220,7 +281,7 @@ export function isTunnelProviderWebsiteUrl(url: string): boolean {
220
281
  let hostname: string;
221
282
  try {
222
283
  // WHATWG URL lowercases the hostname during parsing.
223
- hostname = new URL(url).hostname;
284
+ hostname = hostnameWithoutRootDot(new URL(url).hostname);
224
285
  } catch {
225
286
  return false;
226
287
  }
@@ -237,7 +298,7 @@ export function isTunnelProviderWebsiteUrl(url: string): boolean {
237
298
  export function tunnelProviderWebsiteName(url: string): string | null {
238
299
  let hostname: string;
239
300
  try {
240
- hostname = new URL(url).hostname;
301
+ hostname = hostnameWithoutRootDot(new URL(url).hostname);
241
302
  } catch {
242
303
  return null;
243
304
  }
@@ -253,21 +314,223 @@ export function tunnelProviderWebsiteName(url: string): string | null {
253
314
  }
254
315
 
255
316
  /**
256
- * A loopback URL — `localhost`, `[::1]`, or `127.x.x.x`. A pairing link that
257
- * encodes a loopback address is unreachable from the scanning device.
317
+ * A URL's comparable host: root dot stripped and IPv6 brackets removed, or
318
+ * null when the value is not a parseable URL.
258
319
  */
259
- export function isLoopbackPublicUrl(url: string): boolean {
320
+ function comparableHost(url: string): string | null {
260
321
  try {
261
- // WHATWG URL canonicalizes hostnames, so IPv6 loopback is always "[::1]".
262
- const hostname = new URL(url).hostname;
263
- return (
264
- hostname === "localhost" ||
265
- hostname === "[::1]" ||
266
- /^127(?:\.\d{1,3}){3}$/.test(hostname)
322
+ // WHATWG URL canonicalizes hostnames: IPv6 loopback is always "[::1]", a
323
+ // bare "0" is "0.0.0.0", and encoded IPv4 literals become dotted quads.
324
+ return hostnameWithoutRootDot(new URL(url).hostname).replace(
325
+ /^\[|\]$/g,
326
+ "",
267
327
  );
268
328
  } catch {
329
+ return null;
330
+ }
331
+ }
332
+
333
+ /**
334
+ * Hosts that reach the dialing machine without a resolver having to agree:
335
+ * `localhost`, `127.x.x.x`, `[::1]`, and the wildcard binds `0.0.0.0` / `[::]`,
336
+ * in their dotted, hex, and IPv4-mapped spellings.
337
+ */
338
+ function isDnsIndependentLoopbackHost(host: string): boolean {
339
+ return (
340
+ host === "localhost" ||
341
+ host === "::1" ||
342
+ host === "0:0:0:0:0:0:0:1" ||
343
+ /^127(?:\.\d{1,3}){3}$/.test(host) ||
344
+ // A wildcard host reaches a local listener when dialed, so it counts as
345
+ // local for the pairing and refresh-channel guards alike.
346
+ host === "0.0.0.0" ||
347
+ host === "0" ||
348
+ host === "::" ||
349
+ host === "0:0:0:0:0:0:0:0" ||
350
+ // IPv4-mapped loopback and wildcard, in dotted and hex encodings.
351
+ /^(?:0:0:0:0:0|:):ffff:127(?:\.\d{1,3}){3}$/.test(host) ||
352
+ /^(?:0:0:0:0:0|:):ffff:7f[0-9a-f]{2}:[0-9a-f]{1,4}$/.test(host) ||
353
+ /^(?:0:0:0:0:0|:):ffff:0\.0\.0\.0$/.test(host) ||
354
+ /^(?:0:0:0:0:0|:):ffff:0:0$/.test(host)
355
+ );
356
+ }
357
+
358
+ /**
359
+ * A URL that reaches a listener on the machine dialing it, judged wide: the
360
+ * literals {@link isDnsIndependentLoopbackHost} covers PLUS the whole reserved
361
+ * `localhost` namespace (RFC 6761, so `foo.localhost` counts). A pairing link
362
+ * that encodes one is unreachable from the scanning device, and a host that
363
+ * POSTs to one is calling a service on its own machine.
364
+ *
365
+ * This is the one loopback predicate the whole pairing path reads (the pasted
366
+ * address, and the gatewayUrl an import registers), so the same address class
367
+ * can never be refused by one entry point and accepted by another. Every read
368
+ * of it REFUSES the address it matches, which is why it is the wide one.
369
+ * A guard that GRANTS something to loopback reads
370
+ * {@link isDnsIndependentLoopbackUrl} instead.
371
+ */
372
+ export function isLoopbackPublicUrl(url: string): boolean {
373
+ const host = comparableHost(url);
374
+ if (host === null) {
269
375
  return false;
270
376
  }
377
+ return host.endsWith(".localhost") || isDnsIndependentLoopbackHost(host);
378
+ }
379
+
380
+ /**
381
+ * A URL that reaches this machine whatever the resolver does, judged narrow:
382
+ * exact `localhost` and the loopback/wildcard IP literals, and NOT the
383
+ * reserved `.localhost` namespace. RFC 6761 says a resolver should map that
384
+ * namespace to loopback, but glibc does not by default, so `evil.localhost`
385
+ * is an ordinary DNS name that can answer with any address at all.
386
+ *
387
+ * Read this wherever loopback EARNS a privilege a public host does not get,
388
+ * such as accepting a plaintext channel as confidential; read the wider
389
+ * {@link isLoopbackPublicUrl} wherever loopback is refused. Both directions
390
+ * then fail safe on a name that only might be local.
391
+ */
392
+ export function isDnsIndependentLoopbackUrl(url: string): boolean {
393
+ const host = comparableHost(url);
394
+ return host !== null && isDnsIndependentLoopbackHost(host);
395
+ }
396
+
397
+ /** Canonical dotted-quad as its four octets, or null when it is not one. */
398
+ function parseIpv4Literal(hostname: string): number[] | null {
399
+ const match = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(hostname);
400
+ if (!match) {
401
+ return null;
402
+ }
403
+ const octets = match.slice(1).map(Number);
404
+ return octets.every((octet) => octet <= 255) ? octets : null;
405
+ }
406
+
407
+ /** Bracketed IPv6 literal as its eight 16-bit pieces, or null. */
408
+ function parseIpv6Literal(hostname: string): number[] | null {
409
+ if (!hostname.startsWith("[") || !hostname.endsWith("]")) {
410
+ return null;
411
+ }
412
+ const halves = hostname.slice(1, -1).split("::");
413
+ if (halves.length > 2) {
414
+ return null;
415
+ }
416
+ const toPieces = (part: string): number[] | null => {
417
+ if (!part) {
418
+ return [];
419
+ }
420
+ const pieces: number[] = [];
421
+ const labels = part.split(":");
422
+ for (const [index, label] of labels.entries()) {
423
+ // A trailing dotted-quad is legal IPv6 text. The WHATWG serializer never
424
+ // emits one, but a hand-built literal can still reach this parser.
425
+ if (index === labels.length - 1 && label.includes(".")) {
426
+ const octets = parseIpv4Literal(label);
427
+ if (!octets) {
428
+ return null;
429
+ }
430
+ pieces.push(
431
+ ((octets[0] ?? 0) << 8) | (octets[1] ?? 0),
432
+ ((octets[2] ?? 0) << 8) | (octets[3] ?? 0),
433
+ );
434
+ continue;
435
+ }
436
+ if (!/^[0-9a-f]{1,4}$/i.test(label)) {
437
+ return null;
438
+ }
439
+ pieces.push(Number.parseInt(label, 16));
440
+ }
441
+ return pieces;
442
+ };
443
+ const head = toPieces(halves[0] ?? "");
444
+ const tail = halves.length === 2 ? toPieces(halves[1] ?? "") : [];
445
+ if (!head || !tail) {
446
+ return null;
447
+ }
448
+ if (halves.length === 1) {
449
+ return head.length === 8 ? head : null;
450
+ }
451
+ const gap = 8 - head.length - tail.length;
452
+ return gap >= 1 ? [...head, ...Array<number>(gap).fill(0), ...tail] : null;
453
+ }
454
+
455
+ /**
456
+ * IPv4 ranges that are not publicly routable, judged from the four octets of a
457
+ * canonical dotted-quad. Loopback (127/8) is included so the predicate is
458
+ * complete on its own; `resolvePublicBaseUrl` still reports it as `loopback`
459
+ * because it checks that first.
460
+ *
461
+ * 100.64.0.0/10 is DELIBERATELY ABSENT. Tailscale hands out CGNAT addresses
462
+ * from that range and a Tailscale endpoint is a supported pairing target.
463
+ */
464
+ function isPrivateIpv4(octets: readonly number[]): boolean {
465
+ const a = octets[0] ?? 0;
466
+ const b = octets[1] ?? 0;
467
+ const c = octets[2] ?? 0;
468
+ return (
469
+ a === 0 || // 0/8 "this network"
470
+ a === 10 || // 10/8 private
471
+ a === 127 || // 127/8 loopback
472
+ (a === 169 && b === 254) || // 169.254/16 link-local, incl. cloud metadata
473
+ (a === 172 && b >= 16 && b <= 31) || // 172.16/12 private
474
+ (a === 192 && b === 0 && c === 0) || // 192.0.0/24 protocol assignments
475
+ (a === 192 && b === 168) || // 192.168/16 private
476
+ (a === 198 && (b === 18 || b === 19)) || // 198.18/15 benchmarking
477
+ a >= 224 // 224/4 multicast, 240/4 reserved, 255.255.255.255 broadcast
478
+ );
479
+ }
480
+
481
+ /**
482
+ * A URL whose hostname is an IP literal outside publicly routable space:
483
+ * private, loopback, link-local (which is where the cloud instance metadata
484
+ * endpoint 169.254.169.254 lives), multicast, or reserved, in either address
485
+ * family. Pairing POSTs to whatever address the user pasted, so a literal
486
+ * aimed at the host's own network is refused before any request is made.
487
+ *
488
+ * Only literals written directly in the address are checked. Hostnames are
489
+ * NEVER resolved and resolved addresses are NEVER filtered, deliberately:
490
+ * Tailscale endpoints (`*.ts.net`) are a supported pairing target and resolve
491
+ * into the 100.64.0.0/10 CGNAT range, so post-DNS filtering would refuse them
492
+ * outright. It would also be TOCTOU-prone, since a name can resolve
493
+ * differently between the check and the connection.
494
+ */
495
+ export function isPrivateNetworkPublicUrl(url: string): boolean {
496
+ let hostname: string;
497
+ try {
498
+ // WHATWG URL canonicalizes IP literals: decimal, octal, and hex IPv4 forms
499
+ // collapse to a dotted-quad, and IPv6 to a bracketed lowercase literal.
500
+ hostname = hostnameWithoutRootDot(new URL(url).hostname);
501
+ } catch {
502
+ return false;
503
+ }
504
+ const ipv4 = parseIpv4Literal(hostname);
505
+ if (ipv4) {
506
+ return isPrivateIpv4(ipv4);
507
+ }
508
+ const ipv6 = parseIpv6Literal(hostname);
509
+ if (!ipv6) {
510
+ return false;
511
+ }
512
+ // IPv4-mapped (::ffff:a.b.c.d) and IPv4-compatible (::a.b.c.d) literals carry
513
+ // an IPv4 destination, so they are unwrapped and judged as IPv4.
514
+ const low = ipv6[5] ?? 0;
515
+ if (
516
+ ipv6.slice(0, 5).every((piece) => piece === 0) &&
517
+ (low === 0xffff || low === 0)
518
+ ) {
519
+ const mapped = ipv6[6] ?? 0;
520
+ const trailing = ipv6[7] ?? 0;
521
+ return isPrivateIpv4([
522
+ mapped >> 8,
523
+ mapped & 0xff,
524
+ trailing >> 8,
525
+ trailing & 0xff,
526
+ ]);
527
+ }
528
+ const top = ipv6[0] ?? 0;
529
+ return (
530
+ (top & 0xfe00) === 0xfc00 || // fc00::/7 unique-local
531
+ (top & 0xffc0) === 0xfe80 || // fe80::/10 link-local
532
+ (top & 0xff00) === 0xff00 // ff00::/8 multicast
533
+ );
271
534
  }
272
535
 
273
536
  /**
@@ -291,8 +554,13 @@ export function normalizePairingBaseUrl(value: string): string {
291
554
 
292
555
  /**
293
556
  * Resolve an address to the public https base URL to advertise in a pairing
294
- * challenge, or report why it can't be used. Loopback and non-https links are
295
- * refused with a specific reason callers turn into their own guidance.
557
+ * challenge, or report why it can't be used. Loopback, private-network IP
558
+ * literals, and non-https links are refused with a specific reason callers
559
+ * turn into their own guidance.
560
+ *
561
+ * Hosts POST to this address during pairing, so the refusals are the SSRF
562
+ * containment for every pairing surface. See
563
+ * {@link isPrivateNetworkPublicUrl} for why resolved addresses are left alone.
296
564
  */
297
565
  export function resolvePublicBaseUrl(raw: string): PublicBaseUrlResult {
298
566
  let normalized: string;
@@ -304,6 +572,9 @@ export function resolvePublicBaseUrl(raw: string): PublicBaseUrlResult {
304
572
  if (isLoopbackPublicUrl(normalized)) {
305
573
  return { ok: false, reason: "loopback" };
306
574
  }
575
+ if (isPrivateNetworkPublicUrl(normalized)) {
576
+ return { ok: false, reason: "private-address" };
577
+ }
307
578
  if (isTunnelProviderWebsiteUrl(normalized)) {
308
579
  return { ok: false, reason: "service-website" };
309
580
  }
@@ -330,3 +601,216 @@ export function buildRemoteWebPairingUrl(
330
601
  }).toString();
331
602
  return url.toString();
332
603
  }
604
+
605
+ /**
606
+ * Base that makes a relative pairing link parseable. Only the query and
607
+ * fragment are read off the result, so it never reaches a caller.
608
+ */
609
+ const RELATIVE_PAIRING_LINK_BASE = "https://pairing.invalid";
610
+
611
+ /** The device/user codes a pairing link can carry. */
612
+ export interface RemoteWebPairingParams {
613
+ deviceCode: string | null;
614
+ userCode: string | null;
615
+ }
616
+
617
+ function firstParam(
618
+ params: URLSearchParams,
619
+ ...names: string[]
620
+ ): string | null {
621
+ for (const name of names) {
622
+ const value = params.get(name)?.trim();
623
+ if (value) {
624
+ return value;
625
+ }
626
+ }
627
+ return null;
628
+ }
629
+
630
+ /**
631
+ * Query parameters merged with fragment parameters, query winning on a clash.
632
+ * Pairing links carry the device code in the fragment so it never reaches the
633
+ * wire, but hand-assembled links put it in the query.
634
+ */
635
+ function pairingLinkParams(url: URL): URLSearchParams {
636
+ const merged = new URLSearchParams(url.search);
637
+ const hash = url.hash.startsWith("#") ? url.hash.slice(1) : url.hash;
638
+ for (const [key, value] of new URLSearchParams(hash)) {
639
+ if (!merged.has(key)) {
640
+ merged.set(key, value);
641
+ }
642
+ }
643
+ return merged;
644
+ }
645
+
646
+ /**
647
+ * Read the pairing codes off a link, accepting either casing (`device_code` /
648
+ * `deviceCode`) from either the query string or the fragment. Relative values
649
+ * are accepted so a router can pass `pathname + search + hash` straight in.
650
+ */
651
+ export function parseRemoteWebPairingParams(
652
+ value: string | URL,
653
+ ): RemoteWebPairingParams {
654
+ const url =
655
+ typeof value === "string"
656
+ ? new URL(value, RELATIVE_PAIRING_LINK_BASE)
657
+ : value;
658
+ const params = pairingLinkParams(url);
659
+ return {
660
+ deviceCode: firstParam(params, "deviceCode", "device_code"),
661
+ userCode: firstParam(params, "userCode", "user_code"),
662
+ };
663
+ }
664
+
665
+ /** Outcome of {@link parsePairingAddress}. */
666
+ export type ParsePairingAddressResult =
667
+ | { ok: true; publicBaseUrl: string; deviceCode: string | null }
668
+ | { ok: false; reason: PublicBaseUrlRejection };
669
+
670
+ /**
671
+ * The inverse of {@link buildRemoteWebPairingUrl}: what a pasted pairing
672
+ * address means. A full pairing link yields its base plus the device code it
673
+ * carries; a bare `https://host` address yields a null device code, leaving
674
+ * the caller to mint its own challenge. The base goes through
675
+ * {@link resolvePublicBaseUrl}, so loopback, private-network literals,
676
+ * non-https, and tunnel-vendor websites are refused with the same reasons
677
+ * every other pairing surface reports.
678
+ */
679
+ export function parsePairingAddress(raw: string): ParsePairingAddressResult {
680
+ const resolved = resolvePublicBaseUrl(raw);
681
+ if (!resolved.ok) {
682
+ return resolved;
683
+ }
684
+ return {
685
+ ok: true,
686
+ publicBaseUrl: resolved.url,
687
+ deviceCode: parseRemoteWebPairingParams(raw).deviceCode,
688
+ };
689
+ }
690
+
691
+ /**
692
+ * What a pairing attempt failed on, for callers picking recovery copy. Every
693
+ * pairing surface reports one of these: the host-side sessions in
694
+ * `@vellumai/local-mode`, the Electron bridge, the desktop connect dialog, and
695
+ * the `vellum connect import` CLI.
696
+ */
697
+ export type PairingFailureReason =
698
+ /** The pasted address is not a usable assistant address. */
699
+ | "invalid-address"
700
+ /** No live session for this handle: it was cancelled or never existed. */
701
+ | "unknown-session"
702
+ /** The device code expired, was denied, or was already spent. */
703
+ | "expired"
704
+ /** The assistant could not be reached. */
705
+ | "unreachable"
706
+ /**
707
+ * The assistant refused the request with a status that left the device code
708
+ * exchangeable, so the same session is worth another attempt.
709
+ */
710
+ | "gateway-retryable"
711
+ /**
712
+ * The assistant answered, but with a reply this device cannot use. The code
713
+ * behind it is spent or unknowable, so the attempt is settled.
714
+ */
715
+ | "gateway"
716
+ /** The credentials arrived, but registering them locally was refused. */
717
+ | "import"
718
+ /**
719
+ * The local destination was refused BEFORE the exchange, so the one-time
720
+ * code is untouched and the session is still pollable. Only a caller that
721
+ * changes what it asked for (a different `name`) can get past it, so it is
722
+ * not worth another identical attempt.
723
+ */
724
+ | "import-precheck";
725
+
726
+ /**
727
+ * Every reason, mapped to whether another attempt against the same session can
728
+ * still succeed. Two classes leave the device code exchangeable host-side:
729
+ *
730
+ * - `unreachable`, the transport class (a thrown fetch, a timeout, a refused
731
+ * redirect, a body that errored mid-stream). Nothing reached the assistant,
732
+ * so the session and the code are untouched.
733
+ * - `gateway-retryable`, a non-200 the assistant answered with. The gateway
734
+ * releases the challenge before a repairable failure (a transient error, or
735
+ * the `GUARDIAN_REPAIR_REQUIRED` 503), so the same code stays exchangeable.
736
+ *
737
+ * Everything else ends the attempt. `invalid-address` and `unknown-session`
738
+ * cannot resolve by waiting; `expired` and `import` mean the one-time code is
739
+ * already spent; `gateway` means the assistant answered with something this
740
+ * device cannot use (an over-cap body, credentials it cannot persist, a 200
741
+ * that is not a pairing reply), past which the code is spent rather than
742
+ * released; and `import-precheck` refused the local destination before the
743
+ * exchange, so an identical attempt is refused identically.
744
+ *
745
+ * `import-precheck` is the one of those that leaves the SESSION alive, which
746
+ * is a separate question from whether to retry: see
747
+ * {@link pairingSessionSurvives}.
748
+ *
749
+ * The `satisfies` clause keeps the map exhaustive, so a new reason does not
750
+ * compile until it is classified here.
751
+ */
752
+ const PAIRING_REASON_RETRYABLE = {
753
+ "invalid-address": false,
754
+ "unknown-session": false,
755
+ expired: false,
756
+ unreachable: true,
757
+ "gateway-retryable": true,
758
+ gateway: false,
759
+ import: false,
760
+ "import-precheck": false,
761
+ } satisfies Record<PairingFailureReason, boolean>;
762
+
763
+ /** The reasons {@link isRetryablePairingReason} accepts. */
764
+ export const RETRYABLE_PAIRING_REASONS: ReadonlySet<PairingFailureReason> =
765
+ new Set(
766
+ (Object.keys(PAIRING_REASON_RETRYABLE) as PairingFailureReason[]).filter(
767
+ (reason) => PAIRING_REASON_RETRYABLE[reason],
768
+ ),
769
+ );
770
+
771
+ /**
772
+ * Whether a refused pairing step is worth another attempt. An unlabelled
773
+ * failure reads as settled, so a host too old to name a reason ends the
774
+ * attempt rather than being spun against until the code expires.
775
+ */
776
+ export function isRetryablePairingReason(
777
+ reason: PairingFailureReason | null | undefined,
778
+ ): boolean {
779
+ return reason != null && RETRYABLE_PAIRING_REASONS.has(reason);
780
+ }
781
+
782
+ /**
783
+ * Every reason, mapped to whether the pairing session it came from is still
784
+ * live host-side. A caller holding the handle reads this to decide whether to
785
+ * release the session: releasing a live one throws away a device code that is
786
+ * still good and costs the user a fresh pairing link.
787
+ *
788
+ * This is deliberately NOT the retryable map. `import-precheck` is the reason
789
+ * the two disagree on: nothing was spent and the same handle still polls, but
790
+ * only once the caller changes the name it asked for, so a blind retry is
791
+ * futile while dropping the session is destructive.
792
+ *
793
+ * `invalid-address` never had a session to begin with, so it reads false the
794
+ * same way a dead one does: there is nothing to hold onto either way.
795
+ */
796
+ const PAIRING_REASON_SESSION_LIVE = {
797
+ "invalid-address": false,
798
+ "unknown-session": false,
799
+ expired: false,
800
+ unreachable: true,
801
+ "gateway-retryable": true,
802
+ gateway: false,
803
+ import: false,
804
+ "import-precheck": true,
805
+ } satisfies Record<PairingFailureReason, boolean>;
806
+
807
+ /**
808
+ * Whether the session behind a refused pairing step is still pollable. An
809
+ * unlabelled failure reads as settled, so a host too old to name a reason has
810
+ * its session released rather than left to time out.
811
+ */
812
+ export function pairingSessionSurvives(
813
+ reason: PairingFailureReason | null | undefined,
814
+ ): boolean {
815
+ return reason != null && PAIRING_REASON_SESSION_LIVE[reason] === true;
816
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/credential-executor",
3
- "version": "0.11.6-dev.202608261937.a51ea3f",
3
+ "version": "0.11.6-dev.202608262202.d09b5d7",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {