@retasc/cli 1.3.1 → 1.3.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.
Files changed (2) hide show
  1. package/dist/config.js +149 -4
  2. package/package.json +1 -1
package/dist/config.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { homedir } from "node:os";
2
2
  import { join } from "node:path";
3
- import { mkdirSync, readFileSync, writeFileSync, renameSync, unlinkSync, existsSync, chmodSync, } from "node:fs";
3
+ import { mkdirSync, readFileSync, writeFileSync, renameSync, unlinkSync, existsSync, chmodSync, openSync, closeSync, writeSync, statSync, readdirSync, } from "node:fs";
4
4
  import { randomUUID } from "node:crypto";
5
5
  // Production defaults. Overridable via env for dev/testing.
6
6
  // RETASC_DEPLOYMENT_URL — Convex deployment (.cloud) for management calls
@@ -101,11 +101,156 @@ export function saveConfig(cfg) {
101
101
  }
102
102
  throw err;
103
103
  }
104
+ // Best-effort GC of temp siblings orphaned by a hard kill (SIGKILL / power loss)
105
+ // between writeFileSync(tmp) and renameSync above — otherwise they accumulate in
106
+ // ~/.retasc forever across crashes. Runs after our own rename so our temp is
107
+ // already gone. Age-gated (see sweepStaleTemps) so it never touches a concurrent
108
+ // writer's in-flight temp.
109
+ sweepStaleTemps(dir);
110
+ }
111
+ /** A temp sibling this much older than now was orphaned by a crash, not left by a
112
+ * live writer — any real writeFileSync→renameSync window is milliseconds. */
113
+ const TEMP_STALE_MS = 60_000;
114
+ /** Delete `.config.json.<uuid>.tmp` leftovers only once they're demonstrably stale,
115
+ * so an unconditional sweep can't race-delete a concurrent writer's fresh temp
116
+ * (which would reintroduce the very lost-update class this file guards against). */
117
+ function sweepStaleTemps(dir) {
118
+ let entries;
119
+ try {
120
+ entries = readdirSync(dir);
121
+ }
122
+ catch {
123
+ return; // dir vanished / unreadable — nothing to sweep
124
+ }
125
+ const now = Date.now();
126
+ for (const name of entries) {
127
+ if (!name.startsWith(".config.json.") || !name.endsWith(".tmp"))
128
+ continue;
129
+ const p = join(dir, name);
130
+ try {
131
+ if (now - statSync(p).mtimeMs > TEMP_STALE_MS)
132
+ unlinkSync(p);
133
+ }
134
+ catch {
135
+ /* raced another sweeper or a writer's own rename — fine, leave it */
136
+ }
137
+ }
138
+ }
139
+ // --- Cross-process config lock -------------------------------------------------
140
+ // saveConfig is byte-atomic (temp + rename) but that is NOT isolation: two
141
+ // concurrent load→modify→save sequences both read the old file and the last
142
+ // rename wins, silently dropping the other's fields (RTSC-250). The dangerous
143
+ // case: a `defaultProjectPrefix` write that began before a token refresh writes
144
+ // back the OLD single-use refreshToken, so the next refresh fails and a
145
+ // non-interactive MCP context can't re-run the device flow. An advisory lock file
146
+ // serializes the whole read-modify-write across processes, so every patcher
147
+ // re-reads the freshest config (including a just-rotated token) before writing.
148
+ //
149
+ // Assumes a coherent LOCAL clock: the staleness heuristic compares a lock file's
150
+ // mtime (set by the host that created it) against this host's Date.now(). That
151
+ // holds for the intended case — several processes on ONE machine sharing one
152
+ // ~/.retasc. On a network home with a skewed server clock it degrades to
153
+ // best-effort (over-eager or over-lazy stealing); we don't target that here.
154
+ // Any whole-file mutating writer MUST go through patchConfig so it takes the
155
+ // lock — saveConfig alone is not self-locking (logout's delete is the one benign
156
+ // exception: racing a refresh there is a user-intent race, not a durability bug).
157
+ /** A lock whose mtime is older than this belongs to a holder that died without
158
+ * releasing it (a crash leaves the O_EXCL file behind); break it so a crash
159
+ * can't wedge every future patch forever. Far larger than any real hold, which
160
+ * is a synchronous read+write of a tiny file (single-digit ms). */
161
+ const LOCK_STALE_MS = 30_000;
162
+ /** Absolute backstop: if staleness somehow never frees the lock, force it after
163
+ * this. Kept ABOVE the stale threshold so normal breaking is governed by
164
+ * staleness, not by a timer that could guillotine a merely-slow live holder. */
165
+ const LOCK_TIMEOUT_MS = 60_000;
166
+ const LOCK_BACKOFF_MS = 25;
167
+ /** Block this (single) thread for `ms` without busy-spinning. Node is
168
+ * single-threaded; the lock we wait on is released by ANOTHER process, so
169
+ * parking the thread is correct — nothing here could release it. */
170
+ function sleepSync(ms) {
171
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
172
+ }
173
+ /** The current holder's identity + age, or undefined if the lock just vanished. */
174
+ function readLockHolder(lockPath) {
175
+ try {
176
+ const nonce = readFileSync(lockPath, "utf8");
177
+ return { nonce, ageMs: Date.now() - statSync(lockPath).mtimeMs };
178
+ }
179
+ catch {
180
+ return undefined; // gone between our failed create and this read → just retry
181
+ }
182
+ }
183
+ /** Run `fn` holding an exclusive on-disk lock, so its read-modify-write of the
184
+ * config can't interleave with another process's. Each acquirer stamps a unique
185
+ * nonce into the lock file; steal and release only ever remove a lock whose nonce
186
+ * still matches the one we observed, so a holder that was judged stale and had its
187
+ * lock stolen can't later delete the DIFFERENT holder's lock (which would collapse
188
+ * mutual exclusion back into the lost-update this whole mechanism prevents). */
189
+ function withConfigLock(fn) {
190
+ const dir = configDir();
191
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
192
+ const lockPath = join(dir, ".config.json.lock");
193
+ const nonce = randomUUID();
194
+ const deadline = Date.now() + LOCK_TIMEOUT_MS;
195
+ let fd;
196
+ for (;;) {
197
+ try {
198
+ // "wx" = O_CREAT | O_EXCL | O_WRONLY — atomically fails if the lock is held.
199
+ fd = openSync(lockPath, "wx", 0o600);
200
+ writeSync(fd, nonce); // stamp our identity so steal/release can verify it
201
+ break;
202
+ }
203
+ catch (err) {
204
+ if (err.code !== "EEXIST")
205
+ throw err;
206
+ const holder = readLockHolder(lockPath);
207
+ if (!holder)
208
+ continue; // vanished → retry the create immediately
209
+ if (holder.ageMs > LOCK_STALE_MS || Date.now() > deadline) {
210
+ // Dead holder (stale) or backstop expired: break THIS holder's lock only.
211
+ // If a fresh acquirer replaced it since our read, the nonce differs and we
212
+ // leave it — never steal a live lock out from under a new owner.
213
+ breakLockIf(lockPath, holder.nonce);
214
+ continue;
215
+ }
216
+ sleepSync(LOCK_BACKOFF_MS);
217
+ }
218
+ }
219
+ try {
220
+ return fn();
221
+ }
222
+ finally {
223
+ try {
224
+ closeSync(fd);
225
+ }
226
+ catch {
227
+ /* already closed */
228
+ }
229
+ // Only remove the lock if it's still OURS. If we were stolen from while stalled,
230
+ // the file now holds another holder's nonce — leave it for them.
231
+ breakLockIf(lockPath, nonce);
232
+ }
233
+ }
234
+ /** Unlink the lock only if it still carries `nonce` — a nonce-checked delete, so
235
+ * we never remove a lock a different process now owns. */
236
+ function breakLockIf(lockPath, nonce) {
237
+ try {
238
+ if (readFileSync(lockPath, "utf8") === nonce)
239
+ unlinkSync(lockPath);
240
+ }
241
+ catch {
242
+ /* already gone, replaced, or unreadable — nothing safe to do */
243
+ }
104
244
  }
105
245
  export function patchConfig(patch) {
106
- const next = { ...loadConfig(), ...patch };
107
- saveConfig(next);
108
- return next;
246
+ // Load AND save under the lock: re-reading inside the critical section is what
247
+ // makes this safe — a patch that only sets `defaultProjectPrefix` still picks up
248
+ // a refreshToken another process rotated a moment ago, instead of clobbering it.
249
+ return withConfigLock(() => {
250
+ const next = { ...loadConfig(), ...patch };
251
+ saveConfig(next);
252
+ return next;
253
+ });
109
254
  }
110
255
  export function isLoggedIn(cfg = loadConfig()) {
111
256
  return Boolean(cfg.token);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@retasc/cli",
3
- "version": "1.3.1",
3
+ "version": "1.3.2",
4
4
  "description": "Retasc CLI — sign in with GitHub, create projects, mint agent API keys, and wire your agent to the Retasc MCP server in one command.",
5
5
  "type": "module",
6
6
  "bin": {