passcontrol 0.7.0 → 0.7.2

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.
@@ -8,6 +8,7 @@ import { createInterface } from "node:readline/promises";
8
8
  import { fileURLToPath } from "node:url";
9
9
  import { ed25519 } from "@noble/curves/ed25519";
10
10
  import {
11
+ CLOUD_GATEWAY,
11
12
  CONFIG_FILE,
12
13
  OPENAI_SHAPE_PROVIDERS,
13
14
  PROVIDERS,
@@ -91,7 +92,9 @@ const PUBLIC_REPO_URL = "https://github.com/Vertias3u/PassControl.git";
91
92
  // demo-tenant state and an aborted run would leave the public demo killed. It is
92
93
  // offered as a browser link instead — the one zero-install way to see the
93
94
  // pipeline when there is no local stack yet.
94
- const HOSTED_DEMO_URL = "https://passcontrol.vertias.eu";
95
+ // One literal, in cli/config.mjs. The demo and the Cloud gateway are the same
96
+ // origin, and keeping two copies is how they stop being the same origin.
97
+ const HOSTED_DEMO_URL = CLOUD_GATEWAY;
95
98
  const LOCAL_DASHBOARD_HOSTS = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
96
99
  const LOCAL_STACK_PORTS = [54321, 54322, 54324, 54327, 8079];
97
100
  // The local stack (Supabase + Redis + dashboard) lives in a PassControl repo
package/cli/config.mjs CHANGED
@@ -26,6 +26,20 @@ export const PROVIDERS = ["openai", "anthropic", "groq", "mistral", "together",
26
26
  export const OPENAI_SHAPE_PROVIDERS = new Set(["openai", "groq", "mistral", "together", "deepseek", "gemini"]);
27
27
 
28
28
  const DEFAULT_GATEWAY = "http://localhost:3000";
29
+
30
+ /**
31
+ * The hosted Cloud instance — the one origin this CLI knows by name.
32
+ *
33
+ * Declared HERE, once, because two copies drift: `bin/passcontrol.mjs` had the
34
+ * only literal (as `HOSTED_DEMO_URL`) and now imports this instead.
35
+ *
36
+ * It is NOT the same thing as DEFAULT_GATEWAY above, and the difference matters.
37
+ * DEFAULT_GATEWAY is what an already-configured operator falls back to while
38
+ * working locally. This is where a machine with NO configuration at all should
39
+ * be pointed — which is `passcontrol login` and nothing else, because login is
40
+ * the one command whose whole job is running before any config exists.
41
+ */
42
+ export const CLOUD_GATEWAY = "https://passcontrol.vertias.eu";
29
43
  const DEFAULT_PROVIDER = "anthropic";
30
44
  const CONFIG_KEYS = [
31
45
  "PASSCONTROL_GATEWAY",
package/cli/login.mjs CHANGED
@@ -38,6 +38,9 @@ import os from "node:os";
38
38
  import { ed25519 } from "@noble/curves/ed25519";
39
39
  import fs from "node:fs";
40
40
  import {
41
+ CLOUD_GATEWAY,
42
+ configInjectedKeys,
43
+ configSources,
41
44
  fail,
42
45
  findProjectConfig,
43
46
  globalConfigPath,
@@ -49,6 +52,8 @@ import {
49
52
  warn,
50
53
  } from "./config.mjs";
51
54
 
55
+ export { CLOUD_GATEWAY };
56
+
52
57
  const b64url = (bytes) => Buffer.from(bytes).toString("base64url");
53
58
 
54
59
  /** Display form, `FKDR-8T2W`. Presentation only — the wire form has no hyphen. */
@@ -156,12 +161,19 @@ async function postJson(url, body, { timeoutMs = 15_000, fetchImpl = fetch } = {
156
161
  const controller = new AbortController();
157
162
  const timer = setTimeout(() => controller.abort(), timeoutMs);
158
163
  try {
159
- const res = await fetchImpl(url, {
160
- method: "POST",
161
- headers: { "content-type": "application/json" },
162
- body: JSON.stringify(body ?? {}),
163
- signal: controller.signal,
164
- });
164
+ let res;
165
+ try {
166
+ res = await fetchImpl(url, {
167
+ method: "POST",
168
+ headers: { "content-type": "application/json" },
169
+ body: JSON.stringify(body ?? {}),
170
+ signal: controller.signal,
171
+ });
172
+ } catch (error) {
173
+ const origin = new URL(url).origin;
174
+ const detail = error instanceof Error ? error.message : String(error);
175
+ throw new Error(`Could not reach the gateway at ${origin} (${detail}).`, { cause: error });
176
+ }
165
177
  let parsed = null;
166
178
  try {
167
179
  parsed = await res.json();
@@ -185,9 +197,51 @@ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
185
197
  async function pollForGrant(origin, deviceCode, { interval, expiresIn, fetchImpl, now = Date.now }) {
186
198
  const deadline = now() + expiresIn * 1000;
187
199
  let waitMs = Math.max(500, interval * 1000);
200
+ // A transport failure is NOT fatal here, and this is the one place in the flow
201
+ // where that distinction matters. By the time we are polling, the operator is
202
+ // already looking at a code and waiting; ending the login on a single dropped
203
+ // request costs them the whole flow and a fresh code because a packet went
204
+ // missing or an edge function was cold. Only the deadline ends this loop.
205
+ //
206
+ // The `start` call above is the opposite case and stays fatal: nothing has been
207
+ // shown to anyone yet, and an unreachable gateway there is a configuration
208
+ // problem the operator needs told about immediately, not retried over.
209
+ // Bounded, because "survive a blip" and "hang for ten minutes" are not the same
210
+ // promise. A gateway that is genuinely down would otherwise leave the operator
211
+ // watching "Still waiting…" until the 600s code expiry, which reads as a frozen
212
+ // command. Ninety seconds of continuous failure is long enough to ride out a
213
+ // cold start or a reconnecting VPN and short enough to still feel like an answer.
214
+ const TRANSPORT_GRACE_MS = 90_000;
215
+ let transportFailures = 0;
216
+ let failingSince = 0;
188
217
  while (now() < deadline) {
189
218
  await sleep(waitMs);
190
- const res = await postJson(`${origin}/api/auth/device/token`, { device_code: deviceCode }, { fetchImpl });
219
+ let res;
220
+ try {
221
+ res = await postJson(`${origin}/api/auth/device/token`, { device_code: deviceCode }, { fetchImpl });
222
+ } catch {
223
+ // Back off like a slow_down, and say so once rather than every second — a
224
+ // wall of identical warnings buries the code the operator still needs.
225
+ transportFailures += 1;
226
+ if (transportFailures === 1) {
227
+ failingSince = now();
228
+ warn("Lost contact with the gateway. Still waiting…");
229
+ }
230
+ if (now() - failingSince > TRANSPORT_GRACE_MS) {
231
+ throw new Error(
232
+ `Lost contact with ${origin} and could not get it back. ` +
233
+ "Check the gateway is up, then run `passcontrol login` again."
234
+ );
235
+ }
236
+ waitMs = Math.min(waitMs * 2, 10_000);
237
+ continue;
238
+ }
239
+ if (transportFailures > 0) {
240
+ ok("reconnected");
241
+ transportFailures = 0;
242
+ failingSince = 0;
243
+ waitMs = Math.max(500, interval * 1000);
244
+ }
191
245
  if (res.status === 200 && res.body?.api_key) return res.body;
192
246
  const error = res.body?.error;
193
247
  if (error === "access_denied") {
@@ -266,6 +320,58 @@ async function confirmReplacingPassport(target, confirm) {
266
320
  return confirm("Replace it? [y/N] ", { default: false });
267
321
  }
268
322
 
323
+ /**
324
+ * Resolve login's destination without inheriting the ordinary localhost fallback.
325
+ *
326
+ * An explicit flag wins, then an environment/config value, then Cloud. Other
327
+ * commands keep DEFAULT_GATEWAY because they may intentionally operate a local
328
+ * stack; login is the exception because it is designed to run before any config
329
+ * exists. requireControlGateway keeps the existing bare-origin and HTTPS rules.
330
+ */
331
+ export function resolveLoginGateway(opts = {}, env = process.env) {
332
+ const fromFlag = typeof opts.gateway === "string" ? opts.gateway.trim() : "";
333
+ const fromConfig = typeof env.PASSCONTROL_GATEWAY === "string"
334
+ ? env.PASSCONTROL_GATEWAY.trim()
335
+ : "";
336
+ return requireControlGateway({ gateway: fromFlag || fromConfig || CLOUD_GATEWAY });
337
+ }
338
+
339
+ /**
340
+ * WHERE the destination came from — so a failure can name something editable.
341
+ *
342
+ * This exists because the honest answer is not "the environment". cli/config.mjs
343
+ * injects config-file values into `process.env` at import, so by the time
344
+ * resolveLoginGateway reads PASSCONTROL_GATEWAY the shell and a file on disk are
345
+ * indistinguishable — and an error telling someone to "unset PASSCONTROL_GATEWAY"
346
+ * when their value lives in `~/.config/passcontrol/config` is instructing them to
347
+ * change something that is not set. They run it, nothing moves, and the CLI looks
348
+ * broken rather than merely configured. Reported from a real machine on 0.7.1.
349
+ *
350
+ * `configInjectedKeys` is the same set cli/config.mjs keeps so that "a file said
351
+ * so" and "the operator said so" stay separable for credentials. This is that
352
+ * distinction applied to advice.
353
+ *
354
+ * The file search takes the LAST match, not the first. applyConfigSourcesToEnv
355
+ * pushes global then project and Object.assign()es in order, so a project
356
+ * `.passcontrol` overwrites the global config — and `.find()` would confidently
357
+ * name a file whose value never reached the environment.
358
+ */
359
+ export function gatewaySource(
360
+ opts = {},
361
+ env = process.env,
362
+ { sources = configSources, injected = configInjectedKeys } = {}
363
+ ) {
364
+ if (typeof opts.gateway === "string" && opts.gateway.trim()) return { from: "flag" };
365
+ if (typeof env.PASSCONTROL_GATEWAY === "string" && env.PASSCONTROL_GATEWAY.trim()) {
366
+ if (!injected.has("PASSCONTROL_GATEWAY")) return { from: "env" };
367
+ const file = [...sources]
368
+ .reverse()
369
+ .find((source) => "PASSCONTROL_GATEWAY" in (source?.values ?? {}));
370
+ return file ? { from: "file", path: file.path } : { from: "env" };
371
+ }
372
+ return { from: "default" };
373
+ }
374
+
269
375
  export async function loginCommand(opts = {}, deps = {}) {
270
376
  const fetchImpl = deps.fetch ?? fetch;
271
377
  const openUrl = deps.openUrl ?? (() => {});
@@ -274,16 +380,50 @@ export async function loginCommand(opts = {}, deps = {}) {
274
380
 
275
381
  // Validate the destination BEFORE anything is requested — the ordering mintVisa
276
382
  // uses. A rejected gateway must cost zero sockets.
277
- const origin = requireControlGateway();
383
+ const origin = resolveLoginGateway(opts);
278
384
 
279
385
  const clientName = String(opts.name || os.hostname() || "this machine");
280
- const started = await postJson(
281
- `${origin}/api/auth/device/start`,
282
- { client_name: clientName },
283
- { fetchImpl }
284
- );
386
+ let started;
387
+ try {
388
+ started = await postJson(
389
+ `${origin}/api/auth/device/start`,
390
+ { client_name: clientName },
391
+ { fetchImpl }
392
+ );
393
+ } catch (error) {
394
+ // postJson has already named the host and kept the underlying failure on
395
+ // `cause`. This adds the part a first-run operator actually needs: what to do
396
+ // about it. Read `cause`, not `error.name` — the error reaching here is
397
+ // postJson's plain wrapper, so testing `error.name` for "AbortError" would
398
+ // never be true and the timeout wording would be dead code.
399
+ const underlying = error?.cause ?? error;
400
+ const reason = underlying?.name === "AbortError" ? "timed out" : "could not be reached";
401
+ // Name the place BEFORE offering the remedy — that is the whole job of
402
+ // gatewaySource above. The default origin is nobody's mistake, and blaming a
403
+ // config file that never mentions a gateway sends the operator to edit a line
404
+ // that is not there.
405
+ const source = gatewaySource(opts);
406
+ const lines = [`${origin} ${reason} (${underlying?.message ?? "unknown"}).`];
407
+ if (source.from === "file") {
408
+ lines.push(` That origin comes from ${source.path}, not from your shell.`);
409
+ lines.push(` Edit or delete its PASSCONTROL_GATEWAY line to change it.`);
410
+ } else if (source.from === "env") {
411
+ lines.push(` That origin comes from PASSCONTROL_GATEWAY in your shell.`);
412
+ }
413
+ if (source.from === "default") {
414
+ lines.push(` • Self-hosting? Start your stack, then pass --gateway <origin>.`);
415
+ lines.push(` • Otherwise check your connection and run the command again.`);
416
+ } else {
417
+ lines.push(` • Self-hosting? Start your stack, or pass --gateway <origin>.`);
418
+ lines.push(` • Meant to use Cloud? passcontrol login --gateway ${CLOUD_GATEWAY}`);
419
+ }
420
+ throw new Error(lines.join("\n"), { cause: error });
421
+ }
285
422
  if (started.status !== 200 || !started.body?.user_code) {
286
- throw new Error(`Could not start a login at ${origin} (${started.status}).`);
423
+ throw new Error(
424
+ `${origin} answered ${started.status} to the login request. ` +
425
+ `If that origin is a PassControl instance, it may be older than this CLI.`
426
+ );
287
427
  }
288
428
  const { device_code: deviceCode, user_code: userCode } = started.body;
289
429
  const verificationUri = approvalUrl(origin, started.body.verification_uri, {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "passcontrol",
3
- "version": "0.7.0",
3
+ "version": "0.7.2",
4
4
  "description": "Identity, scope and budget controls for AI agents while provider keys stay server-side.",
5
5
  "license": "BUSL-1.1",
6
6
  "homepage": "https://passcontrol.vertias.eu",