@leeguoo/wrangler-accounts 1.2.2 → 1.3.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.
@@ -442,16 +442,13 @@ function main() {
442
442
  const session = readSessionState(cfgPath);
443
443
  const meta = readMeta(profileDir);
444
444
  const identity = getMetaIdentity(meta);
445
- let status;
446
- if (session.expired === true) status = "expired";
447
- else if (session.expired === false) status = "valid";
448
- else status = "unknown";
449
445
  return {
450
446
  name,
451
447
  isDefault: name === defaultName,
452
448
  isActive: name === activeName,
453
- status,
449
+ status: session.effective, // 'valid' | 'refreshable' | 'expired' | 'unknown'
454
450
  expirationTime: session.expirationTime,
451
+ hasRefreshToken: session.hasRefreshToken,
455
452
  identity,
456
453
  verified: null,
457
454
  verifyError: null,
@@ -528,6 +525,7 @@ function main() {
528
525
  name: e.name,
529
526
  status:
530
527
  e.status === "expired" ? "EXPIRED"
528
+ : e.status === "refreshable" ? "valid*"
531
529
  : e.status === "valid" ? "valid"
532
530
  : "unknown",
533
531
  expires: formatExpiry(e.expirationTime),
@@ -563,17 +561,23 @@ function main() {
563
561
  console.log();
564
562
  if (opts.deep) {
565
563
  console.log(
566
- "Legend: * = default profile, VERIFIED = wrangler whoami succeeded in shadow HOME, = authoritative failure",
564
+ "Legend: * = default profile | STATUS valid = access token fresh | valid* = access token expired but refresh_token will auto-refresh",
565
+ );
566
+ console.log(
567
+ " EXPIRED = access token expired and no refresh_token, must 'login <name>' again",
568
+ );
569
+ console.log(
570
+ " VERIFIED ✓ = 'wrangler whoami' succeeded in shadow HOME (authoritative) | ✗ = failed",
567
571
  );
568
572
  } else {
569
573
  console.log(
570
- "Legend: * = default profile, EXPIRED = access token past expiration_time (wrangler may still auto-refresh)",
574
+ "Legend: * = default profile | STATUS valid = access token fresh | valid* = access token expired but refresh_token will auto-refresh",
571
575
  );
572
576
  console.log(
573
- " STATUS is derived from the saved file only. For a live check that runs 'wrangler whoami' against Cloudflare,",
577
+ " EXPIRED = access token expired and no refresh_token, must 'login <name>' again | unknown = no expiration_time saved",
574
578
  );
575
579
  console.log(
576
- " pass --deep (slower, makes network calls).",
580
+ " STATUS is file-only. For a live check against Cloudflare, pass --deep (slower, makes network calls).",
577
581
  );
578
582
  }
579
583
  return;
@@ -39,20 +39,72 @@ function readExpirationTime(filePath) {
39
39
  return match ? match[1] : null;
40
40
  }
41
41
 
42
+ function hasRefreshToken(filePath) {
43
+ if (!fs.existsSync(filePath)) return false;
44
+ const text = fs.readFileSync(filePath, 'utf8');
45
+ // Any non-empty string value counts. Cloudflare's offline_access scope
46
+ // causes wrangler to store a refresh_token; profiles without that scope
47
+ // won't have one, and those are "really expired" once the access token
48
+ // runs out (~1h).
49
+ return /^\s*refresh_token\s*=\s*"[^"]+"/m.test(text);
50
+ }
51
+
52
+ /**
53
+ * Read the session state of a profile config.toml.
54
+ *
55
+ * Returns:
56
+ * expirationTime: ISO string of access_token expiry, or null
57
+ * expired: boolean — access_token past expirationTime, or null
58
+ * hasRefreshToken: boolean — whether the profile has a refresh_token
59
+ * that wrangler will auto-use for silent refresh
60
+ * effective: 'valid' | 'refreshable' | 'expired' | 'unknown'
61
+ * - 'valid': access_token currently valid
62
+ * - 'refreshable': access_token past expiry but refresh_token present,
63
+ * so wrangler will auto-refresh on next use (no user
64
+ * action needed)
65
+ * - 'expired': access_token past expiry AND no refresh_token,
66
+ * profile is genuinely broken, user must re-login
67
+ * - 'unknown': no expiration_time field, can't tell statically
68
+ */
42
69
  function readSessionState(filePath) {
43
70
  const expirationTime = readExpirationTime(filePath);
71
+ const refreshable = hasRefreshToken(filePath);
72
+
44
73
  if (!expirationTime) {
45
- return { expirationTime: null, expired: null };
74
+ return {
75
+ expirationTime: null,
76
+ expired: null,
77
+ hasRefreshToken: refreshable,
78
+ effective: 'unknown',
79
+ };
46
80
  }
47
81
 
48
82
  const expiresAt = new Date(expirationTime);
49
83
  if (Number.isNaN(expiresAt.getTime())) {
50
- return { expirationTime, expired: null };
84
+ return {
85
+ expirationTime,
86
+ expired: null,
87
+ hasRefreshToken: refreshable,
88
+ effective: 'unknown',
89
+ };
90
+ }
91
+
92
+ const expired = expiresAt.getTime() <= Date.now();
93
+
94
+ let effective;
95
+ if (!expired) {
96
+ effective = 'valid';
97
+ } else if (refreshable) {
98
+ effective = 'refreshable';
99
+ } else {
100
+ effective = 'expired';
51
101
  }
52
102
 
53
103
  return {
54
104
  expirationTime,
55
- expired: expiresAt.getTime() <= Date.now(),
105
+ expired,
106
+ hasRefreshToken: refreshable,
107
+ effective,
56
108
  };
57
109
  }
58
110
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leeguoo/wrangler-accounts",
3
- "version": "1.2.2",
3
+ "version": "1.3.0",
4
4
  "description": "Cloudflare Wrangler multi-account manager — save, switch, and run wrangler against multiple Cloudflare Workers accounts with AWS-style --profile and per-invocation shadow HOME isolation.",
5
5
  "license": "MIT",
6
6
  "bin": {
@@ -77,13 +77,26 @@ Use `--json` for structured output.
77
77
  ### List and inspect profiles
78
78
 
79
79
  - `wrangler-accounts list` — text table with NAME / STATUS / EXPIRES / IDENTITY columns
80
- - `wrangler-accounts list --json` — structured: array of `{name, isDefault, isActive, status, expirationTime, identity}`
80
+ - `wrangler-accounts list --json` — structured: array of `{name, isDefault, isActive, status, expirationTime, hasRefreshToken, identity, verified, verifyError}`
81
81
  - `wrangler-accounts list --plain` — one profile name per line (scriptable)
82
82
  - `wrangler-accounts list --deep` — **authoritative** check: spawns `wrangler whoami` in a shadow HOME for every profile and reports whether Cloudflare actually accepts the credentials. Slower (makes network calls), but the only way to catch revoked refresh tokens or broken profile files.
83
83
  - `wrangler-accounts status` / `status --json`
84
84
  - Pass `--include-backups` to show hidden backup profiles.
85
85
 
86
- **Accuracy note:** the `STATUS` column without `--deep` is derived purely from the saved `expiration_time` and tells you *when the access token will expire*, not whether the profile is actually usable. Wrangler auto-refreshes access tokens via the refresh token, so an `EXPIRED` access token is often fine in practice. When the user needs a real verdict, suggest `wrangler-accounts list --deep`.
86
+ **STATUS values (1.3.0+):**
87
+
88
+ | value | meaning | user action |
89
+ |---|---|---|
90
+ | `valid` | access_token is currently valid | none |
91
+ | `valid*` / `refreshable` | access_token past expiry **BUT** refresh_token present; wrangler will auto-refresh on next use | **none** — this is fine, don't scare the user |
92
+ | `EXPIRED` / `expired` | access_token expired **AND** no refresh_token saved; profile is genuinely broken | `wrangler-accounts login <name>` |
93
+ | `unknown` | profile file has no `expiration_time` field | run `list --deep` to verify live |
94
+
95
+ **Cloudflare OAuth lifecycle reference:** access tokens are short-lived (~1 hour) by design. Every profile with `offline_access` in its scopes also has a long-lived refresh_token (~30 days, silently extended on use). Wrangler refreshes access tokens automatically whenever it runs a command and the current one is past expiry. **Do not tell the user to re-login just because `list` shows an expired access token** — check `hasRefreshToken` first. If the profile's STATUS is `valid*` / `refreshable`, nothing is wrong.
96
+
97
+ The only time a user actually needs `wrangler-accounts login <name>` again is:
98
+ 1. STATUS is `EXPIRED` (no refresh_token at all — profile was saved without `offline_access` scope)
99
+ 2. OR `list --deep` returns `✗` with "Not logged in" / "refresh token may be revoked" (refresh token itself got invalidated)
87
100
 
88
101
  ### Save, sync, login, remove
89
102
 
@@ -238,6 +251,56 @@ Or users can add a shell alias: `alias realhome='cd "$WRANGLER_ACCOUNT_REAL_HOME
238
251
  - "I want this account to stick for a while" → `wrangler-accounts default <name>`
239
252
  - "Just this one command" → `wrangler-accounts --profile <name> <wrangler-args>`
240
253
 
254
+ ### `[ERROR] A request to the Cloudflare API ... Authentication error [code: 10000]` with `code: 7403` ("not authorized to access this service")
255
+
256
+ The OAuth token is fine but **the URL contains the wrong account ID**. wrangler caches the user's selected account in `wrangler-account.json`. If that cache file is shared across profiles, profile A's OAuth token gets paired with profile B's cached account ID, sending API calls to the wrong account. Symptoms:
257
+
258
+ - `deploy` and `secret put` succeed (they don't put account ID in the URL path)
259
+ - `d1 execute --remote`, `r2 object get/put`, anything else with `/accounts/<id>/...` in the URL fails with 7403
260
+
261
+ **Fix path** (in order):
262
+
263
+ 1. **Are you on wrangler-accounts ≥ 1.2.2?** Run `wrangler-accounts --version`. If `< 1.2.2`, upgrade — earlier versions pointed `WRANGLER_CACHE_DIR` at a shared global path. 1.2.2 isolates the cache per profile.
264
+ 2. **Clear the polluted shared cache** (one-time, even after upgrading):
265
+ ```bash
266
+ rm -f ~/.wrangler/cache/wrangler-account.json
267
+ rm -f ~/Library/Preferences/.wrangler/cache/wrangler-account.json # macOS env-paths fallback
268
+ ```
269
+ 3. **Verify with `wrangler-accounts list --deep`** — the VERIFIED column for each profile should be `✓ ok`. If `✗`, the underlying OAuth session itself is broken; run `wrangler-accounts login <name>`.
270
+ 4. **Defense in depth**: set `CLOUDFLARE_ACCOUNT_ID=<correct-id>` in the calling environment. wrangler reads this env var directly and bypasses the cache entirely. Useful for scripts or one-off recovery commands:
271
+ ```bash
272
+ CLOUDFLARE_ACCOUNT_ID=<id> wrangler-accounts <profile> r2 object put ...
273
+ ```
274
+
275
+ **What to tell the user**: "wrangler returned 7403 because it cached the wrong account ID alongside your OAuth token. This was a real bug in wrangler-accounts ≤ 1.2.1 (shared cache directory across profiles). Upgrade to 1.2.2 and clear the polluted cache."
276
+
277
+ ### "The OAuth config seems right, but the wrong account is being used"
278
+
279
+ Same root cause as the 7403 above. Default to the same fix path.
280
+
281
+ ### `wrangler dev` (or any `--local` command) shows stale data after switching profiles
282
+
283
+ Project-local state at `<project>/.wrangler/state/` is **NOT** isolated per profile — wrangler's `getLocalPersistencePath` (cli.js:149025) hardcodes the path next to `wrangler.toml` and the only override is the `--persist-to` CLI flag (no env var hook). So if profile A's `wrangler dev` populated a local D1 emulation, then you switch to profile B and run `wrangler dev` in the same directory, B sees A's emulated rows.
284
+
285
+ This only affects `--local` simulations. **`--remote` commands hit Cloudflare directly and are unaffected** — that's the common case for d1/r2 work in a multi-account setup.
286
+
287
+ Two clean fixes:
288
+
289
+ 1. **Use git worktrees** (recommended for any serious multi-profile dev workflow):
290
+ ```bash
291
+ git worktree add ../my-project-work main
292
+ git worktree add ../my-project-personal main
293
+ cd ../my-project-work && wrangler-accounts exec work # isolated .wrangler/state/
294
+ cd ../my-project-personal && wrangler-accounts exec personal
295
+ ```
296
+ 2. **Clear state manually before switching**:
297
+ ```bash
298
+ rm -rf .wrangler/state
299
+ wrangler-accounts --profile <new> dev
300
+ ```
301
+
302
+ `wrangler-accounts` does not auto-isolate `.wrangler/state/` because the only mechanism would be argv injection of `--persist-to`, which has too many failure modes (different subcommands accept persistTo at different positions, can't override user-supplied flags, path selection is ambiguous between per-profile and per-profile-per-project). The honest tradeoff is documented in the "What is and isn't isolated" table above — partial isolation with hidden gotchas would be worse than honest sharing.
303
+
241
304
  ### Shell history / `.zsh_history` seems to grow when running `exec`
242
305
 
243
306
  Intentional. By design the shadow HOME symlinks all top-level entries of real HOME except `.wrangler`, so shell history writes pass through to the real file. This is a **convenience** bias, not a clean-room sandbox — the goal is that `exec` subshells feel like a normal terminal with a different Cloudflare account, not a jail.