inplan 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/bin/cli.js +183 -14
  2. package/package.json +1 -1
package/bin/cli.js CHANGED
@@ -1156,22 +1156,48 @@ async function reuseCached(auth, skewS = ACCESS_SKEW_S) {
1156
1156
  return error || !data.session ? null : { db, session: data.session };
1157
1157
  }
1158
1158
  var LIVE_REFRESH_SKEW_S = 10 * 60;
1159
- async function authedSession(skewS = ACCESS_SKEW_S) {
1159
+ var REJECTING_STATUSES = /* @__PURE__ */ new Set([400, 401, 403]);
1160
+ function isSpentRefreshToken(error) {
1161
+ const e = error ?? {};
1162
+ if (e.code === "refresh_token_already_used") return true;
1163
+ return typeof e.message === "string" && /already used/i.test(e.message);
1164
+ }
1165
+ function authFailureKind(error) {
1166
+ const status = error?.status;
1167
+ const rejected = typeof status === "number" && REJECTING_STATUSES.has(status);
1168
+ if (!rejected) return { reason: "inconclusive", cause: "unspecified" };
1169
+ return { reason: "rejected", cause: isSpentRefreshToken(error) ? "refresh-token-spent" : "unspecified" };
1170
+ }
1171
+ async function authedSession(skewS = ACCESS_SKEW_S, onFailure) {
1160
1172
  const cached = loadAuth();
1161
- if (!cached) return null;
1173
+ if (!cached) {
1174
+ onFailure?.("inconclusive");
1175
+ return null;
1176
+ }
1162
1177
  const reused = await reuseCached(cached, skewS);
1163
1178
  if (reused) return reused;
1164
1179
  const locked = await withAuthLock(async ({ stillMine }) => {
1165
1180
  const auth = loadAuth();
1166
- if (!auth) return null;
1181
+ if (!auth) {
1182
+ onFailure?.("inconclusive");
1183
+ return null;
1184
+ }
1167
1185
  const fresh = await reuseCached(auth, skewS);
1168
1186
  if (fresh) return fresh;
1169
- if (!stillMine()) return null;
1187
+ if (!stillMine()) {
1188
+ onFailure?.("inconclusive");
1189
+ return null;
1190
+ }
1170
1191
  const db = newClient(auth);
1171
1192
  const { data, error } = await db.auth.refreshSession({ refresh_token: auth.refreshToken });
1172
- if (error || !data.session) return null;
1193
+ if (error || !data.session) {
1194
+ const graded = error ? authFailureKind(error) : { reason: "inconclusive", cause: "unspecified" };
1195
+ onFailure?.(graded.reason, graded.cause);
1196
+ return null;
1197
+ }
1173
1198
  if (!data.session.refresh_token) {
1174
1199
  process.stderr.write("inplan: refresh returned no new refresh token; keeping the stored one and retrying rather than persisting a possibly-spent token\n");
1200
+ onFailure?.("inconclusive");
1175
1201
  return null;
1176
1202
  }
1177
1203
  saveAuth({
@@ -1184,7 +1210,18 @@ async function authedSession(skewS = ACCESS_SKEW_S) {
1184
1210
  return { db, session: data.session };
1185
1211
  });
1186
1212
  if (locked.acquired) return locked.value;
1187
- return reuseCached(loadAuth() ?? cached, 0);
1213
+ const contended = await reuseCached(loadAuth() ?? cached, 0);
1214
+ if (!contended) onFailure?.("inconclusive");
1215
+ return contended;
1216
+ }
1217
+ async function verifyCachedAccessToken() {
1218
+ const auth = loadAuth();
1219
+ if (!auth) return "absent";
1220
+ const bound = await reuseCached(auth);
1221
+ if (!bound) return "absent";
1222
+ const { data, error } = await bound.db.auth.getUser(auth.accessToken);
1223
+ if (!error && data?.user) return "ok";
1224
+ return error ? authFailureKind(error).reason : "inconclusive";
1188
1225
  }
1189
1226
  async function currentUser() {
1190
1227
  const s = await authedSession();
@@ -1476,19 +1513,36 @@ async function createLoginSession(opts = {}) {
1476
1513
  }
1477
1514
  var LoginSessionExpiredError = class extends Error {
1478
1515
  };
1516
+ var BrowserDidNotOpenError = class extends Error {
1517
+ };
1518
+ function pollRequestBudgetMs(nowMs, deadline, openAckDeadline) {
1519
+ const budgets = [REQUEST_TIMEOUT_MS, deadline - nowMs];
1520
+ if (openAckDeadline !== void 0) budgets.push(openAckDeadline - nowMs);
1521
+ return Math.max(1, Math.min(...budgets));
1522
+ }
1523
+ function launchAwareSignal(budgetMs, launchSignal) {
1524
+ const budget = AbortSignal.timeout(budgetMs);
1525
+ return launchSignal ? AbortSignal.any([budget, launchSignal]) : budget;
1526
+ }
1479
1527
  async function pollLoginSession(pending, opts = {}) {
1480
1528
  const fetchImpl = opts.fetchImpl ?? fetch;
1481
1529
  const now = opts.now ?? Date.now;
1482
1530
  const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
1483
1531
  const deadline = now() + (opts.timeoutMs ?? DEFAULT_TIMEOUT_MS);
1484
1532
  const nudgeAt = now() + NUDGE_MS;
1533
+ const openAckDeadline = opts.openAckMs === void 0 ? void 0 : now() + opts.openAckMs;
1485
1534
  let nudged = false;
1486
1535
  let sawOpened = false;
1536
+ const launchDead = () => !sawOpened && Boolean(opts.launchSignal?.aborted);
1487
1537
  while (true) {
1488
1538
  if (!nudged && !sawOpened && now() >= nudgeAt) {
1489
1539
  nudged = true;
1490
1540
  opts.onNudge?.();
1491
1541
  }
1542
+ if (launchDead()) throw new BrowserDidNotOpenError("the browser could not be launched");
1543
+ if (openAckDeadline !== void 0 && !sawOpened && now() >= openAckDeadline) {
1544
+ throw new BrowserDidNotOpenError("the browser did not open");
1545
+ }
1492
1546
  if (now() >= pending.expiresAt) {
1493
1547
  await clearPendingLoginFor(pending.sessionId);
1494
1548
  throw new LoginSessionExpiredError("the sign-in link expired \u2014 run the command again for a fresh one");
@@ -1501,11 +1555,26 @@ async function pollLoginSession(pending, opts = {}) {
1501
1555
  // The poll credential rides a header (never a URL, so never an access log) — see
1502
1556
  // PendingLogin.pollToken: the session id alone must not read or destroy the handoff.
1503
1557
  headers: { "x-inplan-poll-token": pending.pollToken },
1504
- // Capped to the REMAINING deadline: an in-flight request must not let the foreground
1505
- // wait overrun its budget by a whole request-timeout.
1506
- signal: AbortSignal.timeout(Math.max(1, Math.min(REQUEST_TIMEOUT_MS, deadline - now())))
1558
+ // Capped to the REMAINING deadline — and to the openAck deadline when one is set: an
1559
+ // in-flight request must not let either budget overrun by a whole request-timeout. Without
1560
+ // the second cap a stalled poll could burn the full REQUEST_TIMEOUT_MS (plus a POLL_MS
1561
+ // sleep) before the loop ever re-checks a 6-second ack window.
1562
+ // Cut the request short on a launch failure too, not just on the budget: the opener reports
1563
+ // asynchronously, so without this a report landing mid-request would sit behind a stalled
1564
+ // connection for the whole budget before the loop could act on it.
1565
+ // BOTH extra bounds fall away once the page has acked. The ack window has done its job — and
1566
+ // an AbortSignal stays aborted forever, so a launch signal that has already fired would make
1567
+ // AbortSignal.any born-aborted for every remaining request: each one dies before it leaves,
1568
+ // `launchDead()` rightly declines to throw (the page acked), so the loop sleeps and retries
1569
+ // into the same instant abort until the foreground deadline. A login that was about to
1570
+ // complete would end as "login timed out" instead.
1571
+ signal: launchAwareSignal(
1572
+ pollRequestBudgetMs(now(), deadline, sawOpened ? void 0 : openAckDeadline),
1573
+ sawOpened ? void 0 : opts.launchSignal
1574
+ )
1507
1575
  });
1508
1576
  } catch {
1577
+ if (launchDead()) throw new BrowserDidNotOpenError("the browser could not be launched");
1509
1578
  await sleep(POLL_MS);
1510
1579
  continue;
1511
1580
  }
@@ -1543,15 +1612,24 @@ async function rendezvousLogin(opts = {}) {
1543
1612
  (opts.open ?? openInBrowser)(pending.url);
1544
1613
  return pollLoginSession(pending, opts);
1545
1614
  }
1546
- function openInBrowser(url) {
1615
+ function openInBrowser(url, onLaunchFailure) {
1547
1616
  const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
1548
1617
  const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
1618
+ let reported = false;
1619
+ const failed = (kind) => {
1620
+ if (reported) return;
1621
+ reported = true;
1622
+ onLaunchFailure?.(kind);
1623
+ };
1549
1624
  try {
1550
1625
  const child = spawn(cmd, args, { detached: true, stdio: "ignore" });
1551
- child.on("error", () => {
1626
+ child.on("error", () => failed("no-opener"));
1627
+ child.on("exit", (code) => {
1628
+ if (code !== 0) failed("opener-declined");
1552
1629
  });
1553
1630
  child.unref();
1554
1631
  } catch {
1632
+ failed("no-opener");
1555
1633
  }
1556
1634
  }
1557
1635
  async function unsealHandoff(privateKeyPkcs8, sealed) {
@@ -1573,7 +1651,14 @@ async function unsealHandoff(privateKeyPkcs8, sealed) {
1573
1651
  if (typeof parsed.url !== "string" || typeof parsed.anon !== "string" || typeof parsed.refresh !== "string") {
1574
1652
  throw new Error("sign-in handoff was malformed");
1575
1653
  }
1576
- return { url: parsed.url, anonKey: parsed.anon, refreshToken: parsed.refresh, ...parsed.email ? { email: parsed.email } : {} };
1654
+ const cached = typeof parsed.access === "string" && typeof parsed.expiresAt === "number" ? { accessToken: parsed.access, expiresAt: parsed.expiresAt } : {};
1655
+ return {
1656
+ url: parsed.url,
1657
+ anonKey: parsed.anon,
1658
+ refreshToken: parsed.refresh,
1659
+ ...parsed.email ? { email: parsed.email } : {},
1660
+ ...cached
1661
+ };
1577
1662
  }
1578
1663
 
1579
1664
  // src/cliProfile.ts
@@ -2869,6 +2954,7 @@ async function doLogin(args) {
2869
2954
  `);
2870
2955
  const auth = await pollLoginSession(pending, { onNudge: printLoginNudge });
2871
2956
  saveAuth(auth);
2957
+ await primeSessionOrFail();
2872
2958
  await persistCloudIdentity();
2873
2959
  output({ status: "logged_in", url: auth.url, ...auth.email ? { email: auth.email } : {} });
2874
2960
  return;
@@ -2880,6 +2966,38 @@ async function doLogin(args) {
2880
2966
  }
2881
2967
  }
2882
2968
  }
2969
+ if (canAttemptBrowserLaunch()) {
2970
+ let minted;
2971
+ try {
2972
+ minted = await createLoginSession();
2973
+ const launch = new AbortController();
2974
+ openInBrowser(minted.url, (kind) => {
2975
+ if (kind === "no-opener") launch.abort();
2976
+ });
2977
+ const auth = await pollLoginSession(minted, {
2978
+ openAckMs: OPEN_ACK_MS,
2979
+ launchSignal: launch.signal,
2980
+ onNudge: printLoginNudge
2981
+ });
2982
+ saveAuth(auth);
2983
+ await primeSessionOrFail();
2984
+ await persistCloudIdentity();
2985
+ output({ status: "logged_in", url: auth.url, ...auth.email ? { email: auth.email } : {} });
2986
+ return;
2987
+ } catch (e) {
2988
+ if (e instanceof BrowserDidNotOpenError) {
2989
+ await pendingLoginExit(minted);
2990
+ process.exit(1);
2991
+ }
2992
+ if (e instanceof LoginSessionExpiredError) {
2993
+ await pendingLoginExit();
2994
+ process.exit(1);
2995
+ }
2996
+ process.stderr.write(`inplan login: ${e instanceof Error ? e.message : String(e)}
2997
+ `);
2998
+ process.exit(1);
2999
+ }
3000
+ }
2883
3001
  await pendingLoginExit();
2884
3002
  process.exit(1);
2885
3003
  }
@@ -2895,6 +3013,7 @@ async function doLogin(args) {
2895
3013
  // INPLAN_NO_BROWSER: never launch one — the printed URL is the flow
2896
3014
  }) : await defaultRendezvousLogin();
2897
3015
  saveAuth(auth);
3016
+ await primeSessionOrFail();
2898
3017
  await persistCloudIdentity();
2899
3018
  output({ status: "logged_in", url: auth.url, ...auth.email ? { email: auth.email } : {} });
2900
3019
  } catch (e) {
@@ -2903,6 +3022,55 @@ async function doLogin(args) {
2903
3022
  process.exit(1);
2904
3023
  }
2905
3024
  }
3025
+ var OPEN_ACK_MS = 2e4;
3026
+ function canAttemptBrowserLaunch() {
3027
+ return !process.env.CI && !process.env.INPLAN_NO_BROWSER;
3028
+ }
3029
+ async function primeSessionOrFail(retryDelayMs = 750) {
3030
+ const refused = (what) => {
3031
+ clearAuth();
3032
+ process.stderr.write(
3033
+ `inplan login: signed in, but the server rejected the credential the browser handed over \u2014 ${what}
3034
+ Sign in again. If this repeats, the browser session is rotating the token before the CLI
3035
+ can claim it, and the sign-in page needs to hand over an unused token (or an access token).
3036
+ `
3037
+ );
3038
+ process.exit(1);
3039
+ };
3040
+ const unproven = () => {
3041
+ process.stderr.write(
3042
+ "inplan login: signed in, but the credential could not be verified \u2014 the check did not get an\n answer from the server (network, an outage, or another `inplan` holding the refresh lock).\n The credential is KEPT, not discarded: run the command again, or `inplan whoami` to check.\n"
3043
+ );
3044
+ process.exit(1);
3045
+ };
3046
+ const withOneRetry = async (check) => {
3047
+ const first = await check();
3048
+ if (first !== "inconclusive") return first;
3049
+ await new Promise((r) => setTimeout(r, retryDelayMs));
3050
+ return check();
3051
+ };
3052
+ const cached = await withOneRetry(verifyCachedAccessToken);
3053
+ if (cached === "ok") return;
3054
+ if (cached === "rejected") refused("its access token was not accepted.");
3055
+ if (cached === "inconclusive") unproven();
3056
+ const FORCE_REFRESH_SKEW_S = 10 * 365 * 24 * 3600;
3057
+ const forceRefresh = async () => {
3058
+ const before = loadAuth()?.refreshToken;
3059
+ let refusal = "inconclusive";
3060
+ const session = await authedSession(FORCE_REFRESH_SKEW_S, (reason, cause) => {
3061
+ refusal = reason === "inconclusive" ? "inconclusive" : cause === "refresh-token-spent" ? "rejected-spent" : "rejected-other";
3062
+ });
3063
+ if (!session) return refusal;
3064
+ return loadAuth()?.refreshToken !== before ? "ok" : "inconclusive";
3065
+ };
3066
+ const refreshed = await withOneRetry(forceRefresh);
3067
+ if (refreshed === "ok") return;
3068
+ if (refreshed === "rejected-spent") refused("its refresh token had already been spent, so it could never have been used.");
3069
+ if (refreshed === "rejected-other") {
3070
+ refused("the server refused it \u2014 the token may be invalid or revoked, or this deployment's anon key may no longer match.");
3071
+ }
3072
+ unproven();
3073
+ }
2906
3074
  async function persistCloudIdentity() {
2907
3075
  try {
2908
3076
  const user = await currentUser();
@@ -2978,11 +3146,11 @@ function scrubAgentEnv(env) {
2978
3146
  }
2979
3147
  return out;
2980
3148
  }
2981
- async function pendingLoginExit() {
3149
+ async function pendingLoginExit(existing) {
2982
3150
  let url;
2983
3151
  let expiresInSec;
2984
3152
  try {
2985
- const pending = await createLoginSession();
3153
+ const pending = existing ?? await createLoginSession();
2986
3154
  url = pending.url;
2987
3155
  expiresInSec = Math.max(0, Math.floor((pending.expiresAt - Date.now()) / 1e3));
2988
3156
  } catch (e) {
@@ -4312,6 +4480,7 @@ export {
4312
4480
  explainNoGate,
4313
4481
  isKnownAgentEnv,
4314
4482
  notesFromHook,
4483
+ primeSessionOrFail,
4315
4484
  scrubAgentEnv,
4316
4485
  shellQuote,
4317
4486
  transcriptTextBlocks,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "inplan",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "inplan — a Markdown editor for human ⇄ coding-agent planning. CLI + desktop editor.",
5
5
  "license": "AGPL-3.0-or-later",
6
6
  "repository": {