@tokenoftrust/cli 6.12.6 → 6.12.8

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.
package/README.md CHANGED
@@ -54,7 +54,7 @@ The same `tot` does the right thing wherever you run it (walks up like `git`):
54
54
 
55
55
  `tot` talks to the Token of Trust MCP (default `https://mcp.tokenoftrust.com`, override with `--mcp` or `MCP_BASE_URL`). It is **single-plane**: the only identity is **you**, signed in against the MCP over OAuth.
56
56
 
57
- - Run `tot login` once — it opens your browser (or falls back to a device code on a headless box), you sign in as yourself, and the session is cached privately under `~/.tot/` for that MCP authority and refreshed silently. Every later command (`tot clone`, `tot start`, `tot preview`, `tot ship`, …) runs as you, with no re-auth. Entitlement is derived server-side from your ToT memberships.
57
+ - Run `tot login` once — it opens your browser and prints the sign-in URL (so WSL or SSH can finish in any browser that reaches this machine's localhost; with no browser at all, use `tot login --code <handle>` from your cockpit), you sign in as yourself, and the session is cached privately under `~/.tot/` for that MCP authority and refreshed silently. Every later command (`tot clone`, `tot start`, `tot preview`, `tot ship`, …) runs as you, with no re-auth. Entitlement is derived server-side from your ToT memberships.
58
58
  - Not signed in? On a terminal, `tot start` / `tot clone` **offer to sign you in right there** and continue in-flow — no "run `tot login`, then re-run".
59
59
  - The old operator env-triple (`TOT_API_KEY` / `TOT_SECRET_KEY` / `TOT_APP_DOMAIN`) **no longer signs the CLI in** — tot-mcp went OAuth-first on 2026-07-23. If those vars are set, `tot` prints a one-line advisory and uses your `tot login` session anyway; it never reads them for auth.
60
60
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/cli",
3
- "version": "6.12.6",
3
+ "version": "6.12.8",
4
4
  "description": "Token of Trust developer CLI — clone a tenant store, run it locally with save→reload, and submit it for preview. Installs the `tot` command.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Token of Trust",
@@ -16,7 +16,7 @@
16
16
  */
17
17
  import { existsSync, readFileSync } from "node:fs";
18
18
  import { join, resolve } from "node:path";
19
- import { resolveViewerTransport } from "../../viewer-session.mjs";
19
+ import { DEFAULT_STOREFRONT_ORIGIN, resolveViewerTransport } from "../../viewer-session.mjs";
20
20
  import { missingGrantsOf, refusalHint } from "../../admission-hint.mjs";
21
21
  import { validateManifest } from "../../vendor/private-apps-devkit.mjs";
22
22
 
@@ -35,7 +35,10 @@ export const ADMIN_USAGE = `tot app — manage Private App installs on your stor
35
35
 
36
36
  Options (all online commands):
37
37
  --tenant <appDomain> the store (default: the current checkout's store)
38
- --url <origin> storefront origin (default: $TOT_STOREFRONT_URL or the hosted storefront)
38
+ --url <origin> storefront origin (default: $TOT_STOREFRONT_URL, else
39
+ ${DEFAULT_STOREFRONT_ORIGIN}, which serves both
40
+ production- and QA-signed sessions; there is no separate
41
+ QA storefront)
39
42
  --json machine-readable output
40
43
 
41
44
  --env defaults to test. A production install needs --env=production, and the store owner.`;
@@ -921,12 +921,18 @@ export function rendererCacheHealthy(runnerDir, opts = {}) {
921
921
  * follows links, so a `node_modules` entry whose target is gone (a junction left
922
922
  * pointing into a renamed staging directory) reads as absent. A tree with no
923
923
  * `apps/storefront/package.json` has nothing to check and passes.
924
+ *
925
+ * Resolution follows Node's walk from the app up to the runner root and no further:
926
+ * pnpm links astro into `apps/storefront/node_modules`, while npm workspaces hoist it
927
+ * to the runner root's `node_modules`. A copy outside the runner never counts.
924
928
  * @param {string} runnerDir
925
929
  */
926
930
  export function rendererDepsResolve(runnerDir) {
927
931
  const app = join(runnerDir, "apps", "storefront");
928
932
  if (!existsSync(join(app, "package.json"))) return true;
929
- return existsSync(join(app, "node_modules", "astro", "package.json"));
933
+ return [app, join(runnerDir, "apps"), runnerDir].some((dir) =>
934
+ existsSync(join(dir, "node_modules", "astro", "package.json")),
935
+ );
930
936
  }
931
937
 
932
938
  /**
@@ -11,15 +11,13 @@
11
11
  * TOT_MCP_URL, else the production MCP) so the cached token matches where it's
12
12
  * spent — point both at qa with `--mcp https://mcp.qa.tokenoftrust.com` or the env.
13
13
  *
14
- * `--device` forces the RFC 8628 device-code flow (headless/SSH/no-browser:
15
- * print a code, poll until it's approved elsewhere). It's also the automatic
16
- * fallback for a bare `tot login` when there's no browser opener on this box at
17
- * all (oauth.mjs's loopback flow would otherwise hang forever waiting for a
18
- * callback nothing can deliver — see NoOpenerError).
14
+ * The authorize URL is always printed, so a machine whose browser can't be launched
15
+ * (WSL, SSH) can finish in any browser that reaches its localhost. A machine with no
16
+ * browser at all signs in with `--code <handle>` (the rendezvous flow).
19
17
  *
20
18
  * Dependency-free (node built-ins via oauth.mjs).
21
19
  */
22
- import { loginFlow, deviceLoginFlow, rendezvousLoginFlow, NoOpenerError } from "../oauth.mjs";
20
+ import { loginFlow, rendezvousLoginFlow } from "../oauth.mjs";
23
21
  import { defaultCredentialsPath, readCredentials, writeCredentials, normalizeAuthority, selectedAuthority, recordRepositoryAuthority } from "../token-store.mjs";
24
22
  import { execFileSync } from "node:child_process";
25
23
  import { detectContext } from "../context.mjs";
@@ -32,13 +30,12 @@ import { versionStamp } from "../mcp.mjs";
32
30
 
33
31
  function parseArgs(argv) {
34
32
  const a = {
35
- mcp: null, device: false, code: null, help: false,
33
+ mcp: null, code: null, help: false,
36
34
  activityToken: null, activityUrl: null, traceId: null, emailHint: null,
37
35
  };
38
36
  for (let i = 0; i < argv.length; i++) {
39
37
  const t = argv[i];
40
38
  if (t === "--mcp") a.mcp = argv[++i];
41
- else if (t === "--device") a.device = true;
42
39
  else if (t === "--code" || t === "--token") a.code = argv[++i];
43
40
  else if (t === "--activity-token") a.activityToken = argv[++i];
44
41
  else if (t === "--activity-url") a.activityUrl = argv[++i];
@@ -97,14 +94,15 @@ function cacheActivityBridge(env, activityToken, activityUrl) {
97
94
 
98
95
  const USAGE = `tot login — sign in to Token of Trust
99
96
 
100
- tot login open the browser, sign in, cache your session
101
- tot login --code <token> paste the sign-in token from your invite — no browser,
102
- no email code (alias: --token)
103
- tot login --device headless/SSH: print a code, poll until approved
104
- elsewhere (also the automatic fallback when no
105
- browser opener exists on this box)
97
+ tot login open the browser, sign in, cache your session (the
98
+ sign-in URL is printed too, for any browser that
99
+ reaches this machine's localhost — e.g. WSL's host)
100
+ tot login --code <handle> no browser on this machine: paste the sign-in code
101
+ from your cockpit and approve it there (alias: --token)
106
102
  tot login --mcp <url> MCP base URL (default: env MCP_BASE_URL / TOT_MCP_URL)
107
103
 
104
+ Set $BROWSER to choose which browser opens.
105
+
108
106
  --activity-token/--activity-url/--trace-id/--email-hint are set automatically by the pasted
109
107
  invite command (report local dev-loop activity to your hosted /dev panel, and
110
108
  link a later \`tot feedback\` report to your invite + session) — not meant to be
@@ -113,15 +111,16 @@ const USAGE = `tot login — sign in to Token of Trust
113
111
  After signing in, run \`tot whoami\` to confirm, then \`tot clone\` / \`tot submit\`.`;
114
112
 
115
113
  /**
116
- * The core of `tot login`: run the OAuth ceremony (browser loopback, or the
117
- * device-code flow if `device` is set or the loopback can't be reached at
118
- * all) and cache the result, reusing a previously-registered client for THIS
119
- * MCP so we don't re-register (and burn the DCR rate limit) on every login.
120
- * Exported so `tot doctor --fix` can re-login as an auto-remediation
121
- * without duplicating this.
114
+ * The core of `tot login`: run the browser loopback OAuth ceremony and cache the
115
+ * result, reusing a previously-registered client for THIS MCP so we don't
116
+ * re-register (and burn the DCR rate limit) on every login. Exported so
117
+ * `tot doctor --fix` can re-login as an auto-remediation without duplicating this.
122
118
  * @returns {Promise<object>} the credentials written to disk.
123
119
  */
124
- export async function loginAndCache(mcpUrl, env = process.env, { log = /** @type {(m?: string) => void} */ (() => {}), device = false } = {}) {
120
+ export async function loginAndCache(mcpUrl, env = process.env, {
121
+ log = /** @type {(m?: string) => void} */ (() => {}),
122
+ open = openBrowser,
123
+ } = {}) {
125
124
  mcpUrl = normalizeAuthority(mcpUrl);
126
125
  const path = defaultCredentialsPath(env, mcpUrl);
127
126
  let prior = readCredentials(path);
@@ -129,18 +128,7 @@ export async function loginAndCache(mcpUrl, env = process.env, { log = /** @type
129
128
  catch { prior = null; }
130
129
  const clientId = prior?.clientId;
131
130
 
132
- let creds;
133
- if (device) {
134
- creds = await deviceLoginFlow({ mcpUrl, clientId, log });
135
- } else {
136
- try {
137
- creds = await loginFlow({ mcpUrl, clientId, open: openBrowser, log });
138
- } catch (e) {
139
- if (!(e instanceof NoOpenerError)) throw e;
140
- log(" no browser available here — falling back to device-code sign-in …");
141
- creds = await deviceLoginFlow({ mcpUrl, clientId, log });
142
- }
143
- }
131
+ const creds = await loginFlow({ mcpUrl, clientId, open, log });
144
132
  const merged = mergeActivityBridge(prior, mcpUrl, creds);
145
133
  writeCredentials(path, merged);
146
134
  return merged;
@@ -211,8 +199,8 @@ export async function redeemAndCache(mcpUrl, code, env = process.env, { log = /*
211
199
  }
212
200
 
213
201
  /**
214
- * `loginFlow`/`deviceLoginFlow`/`rendezvousLoginFlow` all return the bare OAuth shape —
215
- * none of them know about activityToken/activityUrl, a SEPARATE credential this
202
+ * `loginFlow`/`rendezvousLoginFlow` both return the bare OAuth shape —
203
+ * neither knows about activityToken/activityUrl, a SEPARATE credential this
216
204
  * same file caches via cacheActivityBridge. A bare re-login (no --code) after a
217
205
  * prior --code sign-in would otherwise silently drop it on the next `writeCredentials`
218
206
  * (a full-object overwrite, not a merge) — carry it forward when re-authing against
@@ -300,7 +288,7 @@ export async function run(argv, _ctx) {
300
288
 
301
289
  console.error(`~ signing in to Token of Trust (${mcpUrl})`);
302
290
  try {
303
- await loginAndCache(mcpUrl, loginEnv, { log: (m) => console.error(m), device: args.device });
291
+ await loginAndCache(mcpUrl, loginEnv, { log: (m) => console.error(m) });
304
292
  cacheTraceId(loginEnv, args.traceId);
305
293
  bindCheckout();
306
294
  console.log("\n+ signed in. Session cached privately for this MCP authority.");
@@ -310,7 +298,7 @@ export async function run(argv, _ctx) {
310
298
  console.error(
311
299
  fail(
312
300
  `sign-in didn't complete: ${e?.message || e}`,
313
- loginFailureNext({ device: args.device }),
301
+ loginFailureNext(),
314
302
  ),
315
303
  );
316
304
  return 1;
package/src/oauth.mjs CHANGED
@@ -14,10 +14,8 @@
14
14
  * 5. exchange code -> { access_token, refresh_token, expires_in } with the PKCE
15
15
  * verifier, and hand back a credentials record the token-store persists.
16
16
  *
17
- * This adds the RFC 8628 device-authorization grant (deviceLoginFlow, below) for
18
- * headless/SSH/no-browser boxes where the loopback can never be reached — same
19
- * dynamically-registered client_id, same credentials shape, just a different
20
- * dance: print a code, poll the token endpoint until it's approved elsewhere.
17
+ * A machine with no browser signs in with the rendezvous flow (rendezvousLoginFlow,
18
+ * `tot login --code <handle>`): same credentials shape, approved from the cockpit.
21
19
  *
22
20
  * The pieces are exported individually so the flow is unit-testable against a
23
21
  * mocked `fetch` with no network. Dependency-free (node:http/crypto/timers + open.mjs).
@@ -121,16 +119,6 @@ function oauthShapeFailure(message, context) {
121
119
  const b64url = (buf) =>
122
120
  buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
123
121
 
124
- /** Thrown by loginFlow() when no browser opener exists on this box. Callers
125
- * catch it to fall through to deviceLoginFlow() instead of hanging. */
126
- export class NoOpenerError extends Error {
127
- constructor(authorizeUrl) {
128
- super("no browser opener available on this machine");
129
- this.name = "NoOpenerError";
130
- this.authorizeUrl = authorizeUrl;
131
- }
132
- }
133
-
134
122
  /** A PKCE verifier + its S256 challenge (OAuth 2.1 mandates S256). */
135
123
  export function generatePkce() {
136
124
  const verifier = b64url(crypto.randomBytes(32));
@@ -169,8 +157,8 @@ export async function registerClient(
169
157
  headers: { "Content-Type": "application/json", Accept: "application/json" },
170
158
  body: JSON.stringify({
171
159
  client_name: CLIENT_NAME,
172
- // Include the device-code grant: the browserless rendezvous + device flows
173
- // redeem their device_code at /oauth/token with this grant, so a client
160
+ // Include the device-code grant: the browserless rendezvous flow redeems
161
+ // its device_code at /oauth/token with this grant, so a client
174
162
  // registered WITHOUT it gets "unauthorized_client: grant_type is invalid".
175
163
  grant_types: [
176
164
  "authorization_code",
@@ -343,14 +331,14 @@ export async function loginFlow({
343
331
  clientId: resolvedClientId, redirectUri, challenge, state,
344
332
  });
345
333
 
346
- log(" opening your browser to sign in …");
334
+ // Print the URL before waiting, opener or not: a launched opener can still fail
335
+ // to show a window, and with none at all a browser elsewhere on this machine
336
+ // (the Windows host, for WSL2, which forwards localhost) completes the loopback.
347
337
  const opened = open(authorizeUrl);
348
- if (!opened) {
349
- // No opener on this box (headless/SSH) — the loopback can never be hit
350
- // from here, so waiting on it would hang forever. Let the caller
351
- // (login.mjs#loginAndCache) fall through to deviceLoginFlow() instead.
352
- throw new NoOpenerError(authorizeUrl);
353
- }
338
+ log(opened ? " opening your browser to sign in …" : " no browser opener found on this machine.");
339
+ log(` If your browser didn't open, visit: ${authorizeUrl}`);
340
+ if (!opened) log(" No browser on this machine at all? Use `tot login --code <handle>` with the sign-in code from your cockpit.");
341
+ log(" Waiting for you to finish signing in …");
354
342
 
355
343
  const { code, state: returnedState } = await listener.waitForCallback();
356
344
  if (!code) throw new Error("no authorization code came back from the browser");
@@ -381,7 +369,7 @@ export async function loginFlow({
381
369
  // challenge to the pending rendezvous, prints a human-verifiable fingerprint, and
382
370
  // polls the standard token endpoint (device_code grant + PKCE) until the developer
383
371
  // approves that fingerprint in the cockpit. Same credentials shape as
384
- // loginFlow/deviceLoginFlow, same dynamically-registered client_id, so later silent
372
+ // loginFlow, same dynamically-registered client_id, so later silent
385
373
  // refreshes go through the standard token endpoint like any other session.
386
374
  //
387
375
  // Wire contract (CLI → MCP), all off the MCP origin (from the AS token endpoint):
@@ -430,7 +418,7 @@ export async function attachRendezvous(attachEndpoint, { rendezvousCode, clientI
430
418
 
431
419
  /**
432
420
  * Run the full browserless rendezvous sign-in and return a persistable credentials
433
- * record — the invite sibling of loginFlow()/deviceLoginFlow(), same credentials
421
+ * record — the invite sibling of loginFlow(), same credentials
434
422
  * shape + dynamically-registered client_id (reused when the caller cached one for
435
423
  * this MCP). The terminal generates its own PKCE key, attaches, surfaces the
436
424
  * fingerprint via `log` for the developer to confirm in the cockpit, then polls the
@@ -451,7 +439,7 @@ export async function rendezvousLoginFlow({
451
439
  // clientId. A client cached by an older CLI build was registered without the
452
440
  // device-code grant, so /oauth/token would reject the device grant with
453
441
  // "unauthorized_client". Registration is cheap and a rendezvous has no consent
454
- // screen to re-trigger (unlike the loopback/device flows, which reuse the cache).
442
+ // screen to re-trigger (unlike the loopback flow, which reuses the cache).
455
443
  const resolvedClientId = await registerClient(meta.registration_endpoint, LOOPBACK_REDIRECT, fetchImpl);
456
444
  const { verifier, challenge } = generatePkce();
457
445
 
@@ -486,29 +474,7 @@ export async function rendezvousLoginFlow({
486
474
  });
487
475
  }
488
476
 
489
- // ── Device-code grant (RFC 8628) — headless/SSH/no-browser sign-in ────────
490
-
491
- /**
492
- * RFC 8628 §3.1 — request a device_code + user_code to display. Same request
493
- * shape as any other token-endpoint-adjacent POST (form-urlencoded, JSON back).
494
- * @returns {Promise<{device_code, user_code, verification_uri,
495
- * verification_uri_complete?, expires_in, interval}>}
496
- */
497
- export async function deviceAuthorize(deviceAuthorizationEndpoint, { clientId, scope = SCOPE }, fetchImpl = fetch) {
498
- const { res, body, context } = await oauthJson(deviceAuthorizationEndpoint, {
499
- method: "POST",
500
- headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
501
- body: new URLSearchParams({ client_id: clientId, scope }).toString(),
502
- }, "oauth_device_authorization", fetchImpl);
503
- if (!res.ok) {
504
- const detail = [body.error, body.error_description].filter(Boolean).join(" — ");
505
- throw oauthFailure(`device authorization request failed (HTTP ${res.status}${detail ? `: ${detail}` : ""})`, context);
506
- }
507
- if (!body.device_code || !body.user_code) {
508
- throw oauthShapeFailure("device authorization response is missing device_code/user_code", context);
509
- }
510
- return body;
511
- }
477
+ // ── Device-code token polling (RFC 8628 §3.4/§3.5) — the rendezvous redemption ──
512
478
 
513
479
  /**
514
480
  * One device-flow poll attempt (RFC 8628 §3.4/§3.5). Unlike tokenRequest(),
@@ -526,7 +492,6 @@ async function deviceTokenPoll(tokenEndpoint, { deviceCode, clientId, codeVerifi
526
492
  client_id: clientId,
527
493
  // The rendezvous flow binds the grant to the terminal's PKCE key: the
528
494
  // verifier proves this is the same terminal that attached the challenge.
529
- // Absent for the plain RFC 8628 device flow (no PKCE) — omitted then.
530
495
  ...(codeVerifier ? { code_verifier: codeVerifier } : {}),
531
496
  }).toString(),
532
497
  }, "oauth_device_token", fetchImpl);
@@ -568,45 +533,3 @@ export async function pollDeviceToken(
568
533
  if (r.slowDown) intervalMs += 5000;
569
534
  }
570
535
  }
571
-
572
- /**
573
- * Run the full device-code login (RFC 8628) and return a persistable
574
- * credentials record — the headless/SSH-friendly sibling of loginFlow(),
575
- * same credentials shape, same dynamically-registered client_id. Injectable
576
- * (`fetchImpl`, `log`, `sleep`, `now`) so it's testable with no network and
577
- * no real waiting.
578
- * @returns {Promise<object>} credentials to hand to writeCredentials()
579
- */
580
- export async function deviceLoginFlow({
581
- mcpUrl,
582
- clientId,
583
- fetchImpl = fetch,
584
- log = /** @type {(m?: string) => void} */ (() => {}),
585
- sleep = delay,
586
- now = () => Date.now(),
587
- }) {
588
- const meta = await discoverMetadata(mcpUrl, fetchImpl);
589
- if (!meta.device_authorization_endpoint) {
590
- throw new Error("this MCP doesn't support device-code sign-in yet — try `tot login` (browser) from a machine with one");
591
- }
592
- const resolvedClientId = clientId || (await registerClient(meta.registration_endpoint, LOOPBACK_REDIRECT, fetchImpl));
593
- const auth = await deviceAuthorize(meta.device_authorization_endpoint, { clientId: resolvedClientId }, fetchImpl);
594
-
595
- log(` Go to: ${auth.verification_uri_complete || auth.verification_uri}`);
596
- if (!auth.verification_uri_complete) log(` Enter code: ${auth.user_code}`);
597
- log(" Waiting for approval …");
598
-
599
- const token = await pollDeviceToken(
600
- meta.token_endpoint,
601
- { deviceCode: auth.device_code, clientId: resolvedClientId, intervalSec: auth.interval, expiresInSec: auth.expires_in },
602
- fetchImpl,
603
- { sleep, now },
604
- );
605
- return credentialsFromToken({
606
- mcpUrl,
607
- clientId: resolvedClientId,
608
- tokenEndpoint: meta.token_endpoint,
609
- token,
610
- now: now(),
611
- });
612
- }
package/src/open.mjs CHANGED
@@ -1,13 +1,16 @@
1
1
  /**
2
2
  * Tiny cross-platform helpers for the "and then it just opens" moment:
3
- * - openBrowser(url) — hand the URL to the OS (macOS `open` / Linux `xdg-open`
4
- * / Windows `start`), detached, so `tot` doesn't babysit the browser.
3
+ * - openBrowser(url) — hand the URL to the OS opener (`$BROWSER`, macOS `open`,
4
+ * Windows `rundll32`, WSL `wslview`/`explorer.exe`, Linux `xdg-open`),
5
+ * detached, so `tot` doesn't babysit the browser.
5
6
  * - waitForServer(url) — poll until the dev server answers, so we open the tab
6
7
  * the instant the site is live (not before, not on a fixed sleep).
7
8
  *
8
9
  * Dependency-free (global fetch, node:child_process, Node 20+).
9
10
  */
10
11
  import { spawn } from "node:child_process";
12
+ import { accessSync, constants as fsConstants, readFileSync, statSync } from "node:fs";
13
+ import { delimiter, join } from "node:path";
11
14
  import net from "node:net";
12
15
  import { setTimeout as delay } from "node:timers/promises";
13
16
 
@@ -59,27 +62,109 @@ export async function firstFreePort(preferred, maxTries = 64) {
59
62
  }
60
63
 
61
64
  /**
62
- * The OS opener as [command, args]. Windows goes through `rundll32` with no shell:
63
- * `cmd /c start` would treat the `&` in an OAuth URL as a command separator.
64
- * @param {string} url @param {string} platform @returns {[string, string[]]}
65
+ * The executable `cmd` resolves to on `env.PATH`, or null. A command containing a
66
+ * path separator is checked as given. Synchronous, so the caller knows whether an
67
+ * opener exists BEFORE it spawns one (a missing binary only fails asynchronously).
68
+ * @param {string} cmd @param {NodeJS.ProcessEnv} [env] @returns {string|null}
65
69
  */
66
- export function openerCommand(url, platform) {
70
+ export function findExecutable(cmd, env = process.env) {
71
+ /** @param {string} p */
72
+ const isExecutable = (p) => {
73
+ try {
74
+ if (!statSync(p).isFile()) return false;
75
+ accessSync(p, fsConstants.X_OK);
76
+ return true;
77
+ } catch {
78
+ return false;
79
+ }
80
+ };
81
+ if (cmd.includes("/") || cmd.includes("\\")) return isExecutable(cmd) ? cmd : null;
82
+ for (const dir of String(env.PATH || "").split(delimiter)) {
83
+ if (!dir) continue;
84
+ const candidate = join(dir, cmd);
85
+ if (isExecutable(candidate)) return candidate;
86
+ }
87
+ return null;
88
+ }
89
+
90
+ /**
91
+ * True under Windows Subsystem for Linux: `WSL_DISTRO_NAME` is set, or the kernel
92
+ * banner in `/proc/version` names Microsoft.
93
+ * @param {NodeJS.ProcessEnv} [env] @param {(p: string) => string} [readFile]
94
+ */
95
+ export function isWsl(env = process.env, readFile = (p) => readFileSync(p, "utf8")) {
96
+ if (env.WSL_DISTRO_NAME) return true;
97
+ try {
98
+ return /microsoft/i.test(readFile("/proc/version"));
99
+ } catch {
100
+ return false;
101
+ }
102
+ }
103
+
104
+ /** `cmd.exe /c start` re-parses its command line, so escape every metacharacter
105
+ * (`&` above all, which would split an OAuth URL into a second command).
106
+ * @param {string} url */
107
+ const cmdEscape = (url) => url.replace(/[\^&|<>()%!"]/g, "^$&");
108
+
109
+ /**
110
+ * The opener for `url` as [command, args], resolved synchronously, or null when
111
+ * this machine has none. No opener runs through a shell, so the `&` in an OAuth
112
+ * URL arrives intact.
113
+ * 1. `$BROWSER`, when set and resolvable (each `:`-separated entry; `%s` marks
114
+ * where the URL goes, otherwise the URL is the only argument);
115
+ * 2. macOS `open`; Windows `rundll32 url.dll,FileProtocolHandler`;
116
+ * 3. WSL: `wslview`, else `explorer.exe`, else `cmd.exe /c start` (escaped);
117
+ * 4. any other Unix: `xdg-open`.
118
+ * @param {string} url
119
+ * @param {{ platform?: string, env?: NodeJS.ProcessEnv, which?: (cmd: string) => string|null, wsl?: boolean }} [opts]
120
+ * @returns {[string, string[]] | null}
121
+ */
122
+ export function resolveOpener(url, {
123
+ platform = process.platform,
124
+ env = process.env,
125
+ which = (cmd) => findExecutable(cmd, env),
126
+ wsl = platform === "linux" && isWsl(env),
127
+ } = {}) {
128
+ const browser = String(env.BROWSER || "").trim();
129
+ if (browser) {
130
+ for (const entry of browser.split(platform === "win32" ? ";" : ":")) {
131
+ const spec = entry.trim();
132
+ if (!spec) continue;
133
+ if (spec.includes("%s")) {
134
+ const [cmd, ...args] = spec.split(/\s+/);
135
+ if (which(cmd)) return [cmd, args.map((a) => a.replaceAll("%s", url))];
136
+ } else if (which(spec)) {
137
+ return [spec, [url]];
138
+ }
139
+ }
140
+ }
67
141
  if (platform === "darwin") return ["open", [url]];
68
142
  if (platform === "win32") return ["rundll32", ["url.dll,FileProtocolHandler", url]];
69
- return ["xdg-open", [url]];
143
+ if (wsl) {
144
+ if (which("wslview")) return ["wslview", [url]];
145
+ if (which("explorer.exe")) return ["explorer.exe", [url]];
146
+ if (which("cmd.exe")) return ["cmd.exe", ["/c", "start", '""', cmdEscape(url)]];
147
+ }
148
+ if (which("xdg-open")) return ["xdg-open", [url]];
149
+ return null;
70
150
  }
71
151
 
72
152
  /**
73
- * Open `url` in the user's default browser. Best-effort and non-blocking: the
74
- * child is detached + unref'd so it never holds `tot` open, and any failure
75
- * (headless box, no opener) returns false instead of throwing.
76
- * @returns {boolean} whether we managed to launch an opener.
153
+ * Open `url` in the user's default browser. Non-blocking: the child is detached +
154
+ * unref'd so it never holds `tot` open.
155
+ * @param {string} url
156
+ * @param {string} [platform]
157
+ * @param {{ env?: NodeJS.ProcessEnv, which?: (cmd: string) => string|null, wsl?: boolean,
158
+ * spawnImpl?: typeof spawn }} [deps]
159
+ * @returns {boolean} false only when this machine has no opener at all.
77
160
  */
78
- export function openBrowser(url, platform = process.platform) {
79
- const [cmd, args] = openerCommand(url, platform);
161
+ export function openBrowser(url, platform = process.platform, { spawnImpl = spawn, ...opts } = {}) {
162
+ const opener = resolveOpener(url, { platform, ...opts });
163
+ if (!opener) return false;
164
+ const [cmd, args] = opener;
80
165
  try {
81
- const child = spawn(cmd, args, { stdio: "ignore", detached: true });
82
- child.on("error", () => {}); // swallow "opener not found" async errors
166
+ const child = spawnImpl(cmd, args, { stdio: "ignore", detached: true });
167
+ child.on("error", () => {});
83
168
  child.unref();
84
169
  return true;
85
170
  } catch {
package/src/platform.mjs CHANGED
@@ -20,12 +20,8 @@ export function nativeWindowsDetail() {
20
20
  return `native Windows — if \`tot dev\` or \`tot start\` misbehaves, WSL is the better-trodden path (${WSL_INSTALL_URL})`;
21
21
  }
22
22
 
23
- /**
24
- * Recovery hint after a failed `tot login`.
25
- * @param {{ device?: boolean }} [opts]
26
- */
27
- export function loginFailureNext(opts = {}) {
28
- return opts.device
29
- ? "re-run `tot login --device` and approve the code."
30
- : "re-run `tot login` and finish the browser sign-in (approve the request) — or try `tot login --device`.";
23
+ /** Recovery hint after a failed `tot login`. */
24
+ export function loginFailureNext() {
25
+ return "re-run `tot login` and finish the browser sign-in (approve the request) — on a machine with no browser, " +
26
+ "use `tot login --code <handle>` with the sign-in code from your cockpit.";
31
27
  }
@@ -45,6 +45,20 @@ export function parseSessionCookie(setCookie) {
45
45
  return m ? m[1] : null;
46
46
  }
47
47
 
48
+ /**
49
+ * The refusal for a store the storefront origin does not serve (a 404 on
50
+ * `/api/dev/cli-session`): wrong tenant name, or a store on another origin.
51
+ * @param {string} tenant @param {string|null} [storefrontUrl]
52
+ * @returns {{ message: string, hint: string }}
53
+ */
54
+ export function describeUnknownStore(tenant, storefrontUrl = null) {
55
+ const origin = String(storefrontUrl || DEFAULT_STOREFRONT_ORIGIN).trim().replace(/\/+$/, "");
56
+ return {
57
+ message: `no store named ${String(tenant || "").trim().toLowerCase()} is served at ${origin}.`,
58
+ hint: "run `tot whoami` to list the stores you can build on, then pass one with --tenant.",
59
+ };
60
+ }
61
+
48
62
  /** @param {string|null|undefined} url @returns {string|null} */
49
63
  function originOf(url) {
50
64
  if (!url) return null;
@@ -163,6 +177,7 @@ export async function resolveViewerTransport({
163
177
  if (discovery.status === 502 || discovery.status === 503) {
164
178
  return { ok: false, ...describeCliSessionRefusal(discovery.status, await readJson(discovery), dev.mcpUrl) };
165
179
  }
180
+ if (discovery.status === 404) return { ok: false, ...describeUnknownStore(tenant, storefrontUrl) };
166
181
  return { ok: false, message: `couldn't discover the store's identity issuer (HTTP ${discovery.status}).`,
167
182
  hint: "retry shortly; if it persists, report it with `tot feedback`." };
168
183
  }