norc-cli 0.3.2 → 0.3.3

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 (3) hide show
  1. package/README.md +29 -2
  2. package/dist/index.js +650 -221
  3. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -448,7 +448,7 @@ function __addDisposableResource(env, value, async) {
448
448
  return value;
449
449
  }
450
450
  function __disposeResources(env) {
451
- function fail(e) {
451
+ function fail2(e) {
452
452
  env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
453
453
  env.hasError = true;
454
454
  }
@@ -460,12 +460,12 @@ function __disposeResources(env) {
460
460
  if (r.dispose) {
461
461
  var result = r.dispose.call(r.value);
462
462
  if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
463
- fail(e);
463
+ fail2(e);
464
464
  return next();
465
465
  });
466
466
  } else s |= 1;
467
467
  } catch (e) {
468
- fail(e);
468
+ fail2(e);
469
469
  }
470
470
  }
471
471
  if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
@@ -4398,8 +4398,8 @@ var require_RealtimeChannel = __commonJS({
4398
4398
  }
4399
4399
  /** @internal */
4400
4400
  _notThisChannelEvent(event, ref) {
4401
- const { close, error, leave, join: join7 } = constants_1.CHANNEL_EVENTS;
4402
- const events = [close, error, leave, join7];
4401
+ const { close, error, leave, join: join9 } = constants_1.CHANNEL_EVENTS;
4402
+ const events = [close, error, leave, join9];
4403
4403
  return ref && events.includes(event) && ref !== this.joinPush.ref;
4404
4404
  }
4405
4405
  /** @internal */
@@ -5886,8 +5886,8 @@ var require_helpers = __commonJS({
5886
5886
  });
5887
5887
  return promise;
5888
5888
  }
5889
- function dec2hex(dec) {
5890
- return ("0" + dec.toString(16)).substr(-2);
5889
+ function dec2hex(dec2) {
5890
+ return ("0" + dec2.toString(16)).substr(-2);
5891
5891
  }
5892
5892
  function generatePKCEVerifier() {
5893
5893
  const verifierLength = 56;
@@ -5904,7 +5904,7 @@ var require_helpers = __commonJS({
5904
5904
  crypto.getRandomValues(array);
5905
5905
  return Array.from(array, dec2hex).join("");
5906
5906
  }
5907
- async function sha256(randomString) {
5907
+ async function sha2562(randomString) {
5908
5908
  const encoder = new TextEncoder();
5909
5909
  const encodedData = encoder.encode(randomString);
5910
5910
  const hash = await crypto.subtle.digest("SHA-256", encodedData);
@@ -5917,7 +5917,7 @@ var require_helpers = __commonJS({
5917
5917
  console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256.");
5918
5918
  return verifier;
5919
5919
  }
5920
- const hashed = await sha256(verifier);
5920
+ const hashed = await sha2562(verifier);
5921
5921
  return btoa(hashed).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
5922
5922
  }
5923
5923
  var PKCE_FLOW_ID_PATTERN = /^[a-zA-Z0-9_-]{8,64}$/;
@@ -8063,10 +8063,10 @@ var require_webauthn = __commonJS({
8063
8063
  authenticatorAttachment: (_a = credentialWithAttachment.authenticatorAttachment) !== null && _a !== void 0 ? _a : void 0
8064
8064
  };
8065
8065
  }
8066
- function isValidDomain(hostname3) {
8066
+ function isValidDomain(hostname4) {
8067
8067
  return (
8068
8068
  // Consider localhost valid as well since it's okay wrt Secure Contexts
8069
- hostname3 === "localhost" || /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(hostname3)
8069
+ hostname4 === "localhost" || /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(hostname4)
8070
8070
  );
8071
8071
  }
8072
8072
  function browserSupportsWebAuthn() {
@@ -12881,7 +12881,7 @@ var require_GoTrueClient = __commonJS({
12881
12881
  }
12882
12882
  }
12883
12883
  async _verify(params) {
12884
- const run = async () => {
12884
+ const run2 = async () => {
12885
12885
  try {
12886
12886
  return await this._useSession(async (result) => {
12887
12887
  var _a;
@@ -12912,12 +12912,12 @@ var require_GoTrueClient = __commonJS({
12912
12912
  }
12913
12913
  };
12914
12914
  if (this.lock != null) {
12915
- return this._acquireLock(this.lockAcquireTimeout, run);
12915
+ return this._acquireLock(this.lockAcquireTimeout, run2);
12916
12916
  }
12917
- return run();
12917
+ return run2();
12918
12918
  }
12919
12919
  async _challenge(params) {
12920
- const run = async () => {
12920
+ const run2 = async () => {
12921
12921
  try {
12922
12922
  return await this._useSession(async (result) => {
12923
12923
  var _a;
@@ -12958,9 +12958,9 @@ var require_GoTrueClient = __commonJS({
12958
12958
  }
12959
12959
  };
12960
12960
  if (this.lock != null) {
12961
- return this._acquireLock(this.lockAcquireTimeout, run);
12961
+ return this._acquireLock(this.lockAcquireTimeout, run2);
12962
12962
  }
12963
- return run();
12963
+ return run2();
12964
12964
  }
12965
12965
  /**
12966
12966
  * {@link GoTrueMFAApi#challengeAndVerify}
@@ -13122,7 +13122,7 @@ var require_GoTrueClient = __commonJS({
13122
13122
  */
13123
13123
  async _verifyRecoveryCode(params) {
13124
13124
  (0, helpers_1.assertRecoveryCodesExperimentalEnabled)(this.experimental);
13125
- const run = async () => {
13125
+ const run2 = async () => {
13126
13126
  try {
13127
13127
  return await this._useSession(async (result) => {
13128
13128
  var _a;
@@ -13151,9 +13151,9 @@ var require_GoTrueClient = __commonJS({
13151
13151
  }
13152
13152
  };
13153
13153
  if (this.lock != null) {
13154
- return this._acquireLock(this.lockAcquireTimeout, run);
13154
+ return this._acquireLock(this.lockAcquireTimeout, run2);
13155
13155
  }
13156
- return run();
13156
+ return run2();
13157
13157
  }
13158
13158
  /**
13159
13159
  * {@link AuthMFARecoveryCodesApi#regenerate}
@@ -33546,9 +33546,9 @@ var require_dist = __commonJS({
33546
33546
  });
33547
33547
 
33548
33548
  // src/index.ts
33549
- var import_promises7 = require("node:readline/promises");
33550
- var import_promises8 = require("node:fs/promises");
33551
- var import_node_os9 = require("node:os");
33549
+ var import_promises8 = require("node:readline/promises");
33550
+ var import_promises9 = require("node:fs/promises");
33551
+ var import_node_os10 = require("node:os");
33552
33552
 
33553
33553
  // ../../node_modules/.pnpm/@supabase+supabase-js@2.118.0/node_modules/@supabase/supabase-js/dist/index.mjs
33554
33554
  var dist_exports = {};
@@ -41070,12 +41070,12 @@ function shouldPropagateToTarget(targetUrl, targets) {
41070
41070
  }
41071
41071
  return false;
41072
41072
  }
41073
- function matchStringTarget(hostname3, target) {
41074
- if (target === hostname3) return true;
41073
+ function matchStringTarget(hostname4, target) {
41074
+ if (target === hostname4) return true;
41075
41075
  if (target.startsWith("*.")) {
41076
41076
  const domain = target.slice(2);
41077
- if (hostname3.endsWith(domain)) {
41078
- if (hostname3 === domain || hostname3.endsWith("." + domain)) return true;
41077
+ if (hostname4.endsWith(domain)) {
41078
+ if (hostname4 === domain || hostname4.endsWith("." + domain)) return true;
41079
41079
  }
41080
41080
  }
41081
41081
  return false;
@@ -42232,21 +42232,39 @@ function withLineChanges(io, tracker) {
42232
42232
  }
42233
42233
 
42234
42234
  // ../../packages/entitlements/src/plans.ts
42235
- var FREE = ["byok_ai"];
42236
- var PRO = [...FREE, "remote_ssh", "cross_device_sync", "alerts", "api_write", "run_monitoring"];
42235
+ var FREE = ["byok_ai", "remote_ssh", "cross_device_sync", "api_write"];
42236
+ var PRO = [...FREE, "alerts", "run_monitoring"];
42237
42237
  var POWER = [...PRO, "bulk_ops"];
42238
42238
  var TEAM = [...POWER, "workspaces", "rbac", "audit_log"];
42239
42239
  var PLANS = {
42240
- free: { machineLimit: 2, jobLimit: 15, envVarLimit: 5, historyDays: 7, capabilities: FREE },
42240
+ free: { machineLimit: 1, jobLimit: 15, envVarLimit: 5, historyDays: 7, capabilities: FREE },
42241
+ hobbyist: { machineLimit: 3, jobLimit: 20, envVarLimit: 15, historyDays: 90, capabilities: PRO },
42241
42242
  pro: { machineLimit: 5, jobLimit: 30, envVarLimit: 25, historyDays: 90, capabilities: PRO },
42242
42243
  power: { machineLimit: 25, jobLimit: 150, envVarLimit: 100, historyDays: 365, capabilities: POWER },
42243
42244
  team: { machineLimit: "custom", jobLimit: "custom", envVarLimit: "custom", historyDays: 365, capabilities: TEAM }
42244
42245
  };
42245
42246
 
42246
42247
  // ../../packages/entitlements/src/can.ts
42248
+ function isPlan(v) {
42249
+ return typeof v === "string" && Object.hasOwn(PLANS, v);
42250
+ }
42251
+ var PLAN_NAMES = { free: "Free", hobbyist: "Hobbyist", pro: "Pro", power: "Power", team: "Team" };
42247
42252
  function machineLimit(plan) {
42248
42253
  return PLANS[plan].machineLimit;
42249
42254
  }
42255
+ function nextPlanAllows(plan, limitOf, noun = "") {
42256
+ const plans = Object.keys(PLANS);
42257
+ const next = plans[plans.indexOf(plan) + 1];
42258
+ if (!next) return "";
42259
+ const cap = limitOf(next);
42260
+ return typeof cap === "number" ? `${next.charAt(0).toUpperCase()}${next.slice(1)} allows ${cap}${noun}.` : "";
42261
+ }
42262
+ function machineUpgradeHint(plan) {
42263
+ return nextPlanAllows(plan, machineLimit);
42264
+ }
42265
+ function envVarUpgradeHint(plan) {
42266
+ return nextPlanAllows(plan, envVarLimit, " variables");
42267
+ }
42250
42268
  function jobLimit(plan) {
42251
42269
  return PLANS[plan].jobLimit;
42252
42270
  }
@@ -42265,7 +42283,7 @@ function envVarUsageLabel(plan, count2) {
42265
42283
  function envVarLimitMessage(plan, count2) {
42266
42284
  const limit = envVarLimit(plan);
42267
42285
  if (limit === "custom" || withinEnvVarLimit(plan, count2)) return null;
42268
- return `You've used all ${limit} variables on the ${plan.charAt(0).toUpperCase() + plan.slice(1)} plan. Upgrade to add more.`;
42286
+ return `You've used all ${limit} variables on the ${PLAN_NAMES[plan]} plan. Upgrade to add more.`;
42269
42287
  }
42270
42288
 
42271
42289
  // ../../packages/entitlements/src/trial.ts
@@ -42277,7 +42295,7 @@ function toDate(v) {
42277
42295
  }
42278
42296
  function effectivePlan(plan, trialEndsAt, now = /* @__PURE__ */ new Date()) {
42279
42297
  const end = toDate(trialEndsAt);
42280
- return plan === "free" && end !== null && end.getTime() > now.getTime() ? TRIAL_PLAN : plan;
42298
+ return (plan === "free" || plan === "hobbyist") && end !== null && end.getTime() > now.getTime() ? TRIAL_PLAN : plan;
42281
42299
  }
42282
42300
 
42283
42301
  // ../../packages/bridge/src/pairing.ts
@@ -42337,6 +42355,18 @@ function backoffDelay(attempt, baseMs = 500, capMs = 3e4) {
42337
42355
  return Math.min(capMs, baseMs * 2 ** attempt);
42338
42356
  }
42339
42357
 
42358
+ // ../../packages/bridge/src/quota-pause.ts
42359
+ var QUOTA_PAUSE_MIN_MS = 5 * 6e4;
42360
+ var QUOTA_PAUSE_MAX_MS = 60 * 6e4;
42361
+ var isQuotaRefusal = (status) => status === 402 || status === 429;
42362
+ function nextQuotaPause(prev, retryAfter, now = Date.now()) {
42363
+ const secs = retryAfter !== null && /^\d+$/.test(retryAfter.trim()) ? Number(retryAfter.trim()) : NaN;
42364
+ const want = Number.isFinite(secs) ? secs * 1e3 : (prev?.ms ?? 0) * 2;
42365
+ const ms = Math.min(QUOTA_PAUSE_MAX_MS, Math.max(QUOTA_PAUSE_MIN_MS, want));
42366
+ return { until: now + ms, ms };
42367
+ }
42368
+ var quotaPaused = (p, now = Date.now()) => !!p && now < p.until;
42369
+
42340
42370
  // ../../packages/bridge/src/jwt.ts
42341
42371
  function b64urlToBytes(s) {
42342
42372
  const pad2 = s.length % 4 ? "=".repeat(4 - s.length % 4) : "";
@@ -42463,6 +42493,9 @@ function validateRawCrontab(contents) {
42463
42493
 
42464
42494
  // ../../packages/bridge/src/write-intent.ts
42465
42495
  async function handleWriteIntent(msg, d) {
42496
+ if (!msg || typeof msg.capability !== "string" || !Array.isArray(msg.jobs) || !msg.jobs.every((j) => j && typeof j === "object")) {
42497
+ return { applied: false, reason: "malformed write-intent" };
42498
+ }
42466
42499
  if (!msg.jobs.every((j) => typeof j.id === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(j.id))) return { applied: false, reason: "invalid job id" };
42467
42500
  const intentHash = await canonicalJobsHash(msg.jobs);
42468
42501
  const v = await verifyCapability(msg.capability, {
@@ -42647,17 +42680,17 @@ async function open(payload, o) {
42647
42680
  // ../../packages/bridge/src/secure-url.ts
42648
42681
  var LOCAL_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
42649
42682
  function assertSecureUrl(url, opts = {}) {
42650
- const fail = () => new Error(`Supabase URL must use https:// (got ${JSON.stringify(url ?? null)})`);
42651
- if (!url) throw fail();
42683
+ const fail2 = () => new Error(`Supabase URL must use https:// (got ${JSON.stringify(url ?? null)})`);
42684
+ if (!url) throw fail2();
42652
42685
  let parsed;
42653
42686
  try {
42654
42687
  parsed = new URL(url);
42655
42688
  } catch {
42656
- throw fail();
42689
+ throw fail2();
42657
42690
  }
42658
42691
  if (parsed.protocol === "https:") return url;
42659
42692
  if (opts.allowLocalDev && parsed.protocol === "http:" && LOCAL_HOSTS.has(parsed.hostname)) return url;
42660
- throw fail();
42693
+ throw fail2();
42661
42694
  }
42662
42695
 
42663
42696
  // ../../packages/bridge/src/secure-channel.ts
@@ -42744,9 +42777,10 @@ function vaultUrl() {
42744
42777
 
42745
42778
  // src/config.ts
42746
42779
  var import_promises = require("node:fs/promises");
42747
- var import_node_child_process = require("node:child_process");
42748
- var import_node_os = require("node:os");
42749
- var import_node_path = require("node:path");
42780
+ var import_node_child_process2 = require("node:child_process");
42781
+ var import_node_crypto = require("node:crypto");
42782
+ var import_node_os2 = require("node:os");
42783
+ var import_node_path2 = require("node:path");
42750
42784
 
42751
42785
  // src/debug.ts
42752
42786
  var enabled = false;
@@ -42829,18 +42863,18 @@ function matchStarts(hay, needle) {
42829
42863
  const m = needle.length;
42830
42864
  const out = [];
42831
42865
  if (!m || hay.length < m) return out;
42832
- const fail = new Int32Array(m);
42866
+ const fail2 = new Int32Array(m);
42833
42867
  for (let i = 1, k = 0; i < m; i++) {
42834
- while (k && needle[i] !== needle[k]) k = fail[k - 1];
42868
+ while (k && needle[i] !== needle[k]) k = fail2[k - 1];
42835
42869
  if (needle[i] === needle[k]) k++;
42836
- fail[i] = k;
42870
+ fail2[i] = k;
42837
42871
  }
42838
42872
  for (let i = 0, k = 0; i < hay.length; i++) {
42839
- while (k && hay[i] !== needle[k]) k = fail[k - 1];
42873
+ while (k && hay[i] !== needle[k]) k = fail2[k - 1];
42840
42874
  if (hay[i] === needle[k]) k++;
42841
42875
  if (k === m) {
42842
42876
  out.push(i - m + 1);
42843
- k = fail[k - 1];
42877
+ k = fail2[k - 1];
42844
42878
  }
42845
42879
  }
42846
42880
  return out;
@@ -42883,6 +42917,181 @@ function scrubValues(text, values) {
42883
42917
  return out + text.slice(pos, s) + "[redacted]" + text.slice(e);
42884
42918
  }
42885
42919
 
42920
+ // src/secret-store.ts
42921
+ var import_node_child_process = require("node:child_process");
42922
+ var import_node_os = require("node:os");
42923
+ var import_node_path = require("node:path");
42924
+ var SECRET_SERVICE = "app.norc.cli";
42925
+ var EXEC_TIMEOUT_MS = 1e4;
42926
+ var defaultSecretExec = (cmd, args, { input, timeout }) => new Promise((resolve) => {
42927
+ const child = (0, import_node_child_process.execFile)(cmd, args, { timeout, windowsHide: true }, (err, stdout, stderr) => {
42928
+ const e = err;
42929
+ resolve({ code: !e ? 0 : typeof e.code === "number" ? e.code : null, stdout, stderr, error: e && typeof e.code !== "number" ? e : void 0 });
42930
+ });
42931
+ child.stdin?.on("error", () => {
42932
+ });
42933
+ child.stdin?.end(input ?? "");
42934
+ });
42935
+ var SAFE = /^[A-Za-z0-9._-]+$/;
42936
+ var enc = (v) => Buffer.from(v, "utf8").toString("base64url");
42937
+ var dec = (v) => Buffer.from(v.trim(), "base64url").toString("utf8");
42938
+ async function run(exec, cmd, args, input) {
42939
+ const r = await exec(cmd, args, { input, timeout: EXEC_TIMEOUT_MS });
42940
+ if (r.error?.code === "ENOENT") throw new Error(`${cmd} is not installed (no usable OS keychain)`);
42941
+ return r;
42942
+ }
42943
+ function fail(cmd, r, hint = "") {
42944
+ const why = r.code === null ? `timed out or was killed${r.error ? ` (${r.error.message})` : ""}` : `exit ${r.code}${r.stderr.trim() ? `: ${r.stderr.trim()}` : ""}`;
42945
+ return new Error(`${cmd} failed: ${hint}${why}`);
42946
+ }
42947
+ var MAC_LOCKED = {
42948
+ 36: "the keychain is locked and this session cannot unlock it (errSecInteractionNotAllowed). ",
42949
+ 51: "keychain authorization failed (errSecAuthFailed). ",
42950
+ 37: "no default keychain (errSecNoDefaultKeychain). ",
42951
+ 50: "no such keychain (errSecNoSuchKeychain). "
42952
+ };
42953
+ var macFail = (r) => fail("security", r, r.code !== null && MAC_LOCKED[r.code] || "");
42954
+ function check(service, account) {
42955
+ if (!SAFE.test(service) || !SAFE.test(account)) throw new Error(`invalid keychain service/account: ${service}/${account}`);
42956
+ }
42957
+ function macLoginKeychain() {
42958
+ return (0, import_node_path.join)((0, import_node_os.homedir)(), "Library", "Keychains", "login.keychain-db");
42959
+ }
42960
+ function macSecretStore(service = SECRET_SERVICE, exec = defaultSecretExec, keychain = macLoginKeychain()) {
42961
+ const sec = "/usr/bin/security";
42962
+ const kc = keychain && !/\s/.test(keychain) ? [keychain] : [];
42963
+ const get2 = async (account) => {
42964
+ check(service, account);
42965
+ const r = await run(exec, sec, ["find-generic-password", "-s", service, "-a", account, "-w", ...kc]);
42966
+ if (r.code === 44) return null;
42967
+ if (r.code !== 0) throw macFail(r);
42968
+ return dec(r.stdout);
42969
+ };
42970
+ return {
42971
+ get: get2,
42972
+ async set(account, value) {
42973
+ check(service, account);
42974
+ const r = await run(exec, sec, ["-i"], `add-generic-password -U -s ${service} -a ${account} -w ${enc(value)}${kc.map((k) => ` ${k}`).join("")}
42975
+ `);
42976
+ if (r.code !== 0) throw macFail(r);
42977
+ if (await get2(account) !== value) throw new Error("security failed: the keychain item did not read back after writing it");
42978
+ },
42979
+ async delete(account) {
42980
+ check(service, account);
42981
+ const r = await run(exec, sec, ["delete-generic-password", "-s", service, "-a", account, ...kc]);
42982
+ if (r.code !== 0 && r.code !== 44) throw macFail(r);
42983
+ }
42984
+ };
42985
+ }
42986
+ function linuxSecretStore(service = SECRET_SERVICE, exec = defaultSecretExec) {
42987
+ return {
42988
+ async get(account) {
42989
+ check(service, account);
42990
+ const r = await run(exec, "secret-tool", ["lookup", "service", service, "account", account]);
42991
+ if (r.code === 1 && !r.stdout.trim() && !r.stderr.trim()) return null;
42992
+ if (r.code !== 0) throw fail("secret-tool", r);
42993
+ return dec(r.stdout);
42994
+ },
42995
+ async set(account, value) {
42996
+ check(service, account);
42997
+ const r = await run(exec, "secret-tool", ["store", `--label=norc cli ${account}`, "service", service, "account", account], enc(value));
42998
+ if (r.code !== 0) throw fail("secret-tool", r);
42999
+ },
43000
+ async delete(account) {
43001
+ check(service, account);
43002
+ const r = await run(exec, "secret-tool", ["clear", "service", service, "account", account]);
43003
+ if (r.code !== 0 && !(r.code === 1 && !r.stderr.trim())) throw fail("secret-tool", r);
43004
+ }
43005
+ };
43006
+ }
43007
+ var WIN_PRELUDE = `$ErrorActionPreference='Stop'
43008
+ Add-Type -TypeDefinition @'
43009
+ using System; using System.Runtime.InteropServices; using System.Text;
43010
+ public static class NorcCred {
43011
+ [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
43012
+ struct CREDENTIAL { public int Flags; public int Type; public string TargetName; public string Comment; public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten; public int CredentialBlobSize; public IntPtr CredentialBlob; public int Persist; public int AttributeCount; public IntPtr Attributes; public string TargetAlias; public string UserName; }
43013
+ [DllImport("advapi32.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern bool CredWriteW(ref CREDENTIAL c, int flags);
43014
+ [DllImport("advapi32.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern bool CredReadW(string target, int type, int flags, out IntPtr c);
43015
+ [DllImport("advapi32.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern bool CredDeleteW(string target, int type, int flags);
43016
+ [DllImport("advapi32.dll")] static extern void CredFree(IntPtr p);
43017
+ public static int Read(string target, out string value) {
43018
+ value = null; IntPtr p;
43019
+ if (!CredReadW(target, 1, 0, out p)) return Marshal.GetLastWin32Error();
43020
+ try { CREDENTIAL c = (CREDENTIAL)Marshal.PtrToStructure(p, typeof(CREDENTIAL)); byte[] b = new byte[c.CredentialBlobSize]; Marshal.Copy(c.CredentialBlob, b, 0, b.Length); value = Encoding.UTF8.GetString(b); return 0; }
43021
+ finally { CredFree(p); }
43022
+ }
43023
+ public static int Write(string target, string value) {
43024
+ byte[] v = Encoding.UTF8.GetBytes(value); IntPtr m = Marshal.AllocHGlobal(v.Length);
43025
+ try {
43026
+ Marshal.Copy(v, 0, m, v.Length);
43027
+ CREDENTIAL c = new CREDENTIAL(); c.Type = 1; c.TargetName = target; c.UserName = "norc"; c.CredentialBlobSize = v.Length; c.CredentialBlob = m; c.Persist = 2;
43028
+ return CredWriteW(ref c, 0) ? 0 : Marshal.GetLastWin32Error();
43029
+ } finally { Marshal.FreeHGlobal(m); }
43030
+ }
43031
+ public static int Delete(string target) { return CredDeleteW(target, 1, 0) ? 0 : Marshal.GetLastWin32Error(); }
43032
+ }
43033
+ '@
43034
+ `;
43035
+ function windowsCredScript(op, target) {
43036
+ const done = (call, name) => `$r=${call}
43037
+ if($r -eq 1168){exit 44}; if($r -ne 0){[Console]::Error.Write("${name} failed: $r"); exit 1}`;
43038
+ const body = {
43039
+ get: `$v=$null
43040
+ ${done(`[NorcCred]::Read('${target}',[ref]$v)`, "CredReadW")}
43041
+ [Console]::Out.Write($v)`,
43042
+ set: done(`[NorcCred]::Write('${target}',[Console]::In.ReadToEnd().Trim())`, "CredWriteW"),
43043
+ delete: done(`[NorcCred]::Delete('${target}')`, "CredDeleteW")
43044
+ }[op];
43045
+ return WIN_PRELUDE + body;
43046
+ }
43047
+ function windowsSecretStore(service = SECRET_SERVICE, exec = defaultSecretExec) {
43048
+ const ps = (op, account, input) => {
43049
+ check(service, account);
43050
+ const script = Buffer.from(windowsCredScript(op, `${service}:${account}`), "utf16le").toString("base64");
43051
+ return run(exec, "powershell.exe", ["-NoProfile", "-NonInteractive", "-EncodedCommand", script], input);
43052
+ };
43053
+ return {
43054
+ async get(account) {
43055
+ const r = await ps("get", account);
43056
+ if (r.code === 44) return null;
43057
+ if (r.code !== 0) throw fail("powershell", r);
43058
+ return dec(r.stdout);
43059
+ },
43060
+ async set(account, value) {
43061
+ const r = await ps("set", account, enc(value));
43062
+ if (r.code !== 0) throw fail("powershell", r);
43063
+ },
43064
+ async delete(account) {
43065
+ const r = await ps("delete", account);
43066
+ if (r.code !== 0 && r.code !== 44) throw fail("powershell", r);
43067
+ }
43068
+ };
43069
+ }
43070
+ function platformSecretStore(platform2 = process.platform, service = SECRET_SERVICE, exec) {
43071
+ if (platform2 === "darwin") return macSecretStore(service, exec);
43072
+ if (platform2 === "win32") return windowsSecretStore(service, exec);
43073
+ return linuxSecretStore(service, exec);
43074
+ }
43075
+ var override;
43076
+ var overrideMode = "keychain";
43077
+ var warnedMode = false;
43078
+ function secretStoreMode(env, platform2 = process.platform) {
43079
+ if (env === "keychain" || env === "file") return env;
43080
+ if (env && !warnedMode) {
43081
+ warnedMode = true;
43082
+ console.error(`norc: ignoring NORC_SECRET_STORE=${JSON.stringify(env)} (use "keychain" or "file"); using the platform default.`);
43083
+ }
43084
+ return platform2 === "darwin" ? "keychain" : "file";
43085
+ }
43086
+ function secretStore() {
43087
+ const mode = override !== void 0 ? overrideMode : secretStoreMode(process.env.NORC_SECRET_STORE);
43088
+ return mode === "keychain" ? readSecretStore() : null;
43089
+ }
43090
+ function readSecretStore() {
43091
+ if (override !== void 0) return override;
43092
+ return process.env.NORC_SECRET_STORE_NO_OS === "1" ? null : platformSecretStore();
43093
+ }
43094
+
42886
43095
  // src/config.ts
42887
43096
  function replayFor(config, machineId) {
42888
43097
  const b = config.bridge ??= {};
@@ -42903,7 +43112,7 @@ function windowsOwnerOnlyDirAclSteps(dir, user) {
42903
43112
  function windowsOwnerOnlyFileAclSteps(file, user) {
42904
43113
  return [[file, "/reset"], [file, "/inheritance:r", "/grant:r", `${user}:F`]];
42905
43114
  }
42906
- var defaultExec = (cmd, args, cb) => (0, import_node_child_process.execFile)(cmd, args, (err) => cb(err));
43115
+ var defaultExec = (cmd, args, cb) => (0, import_node_child_process2.execFile)(cmd, args, (err) => cb(err));
42907
43116
  function icacls(args, exec) {
42908
43117
  return new Promise((resolve, reject) => {
42909
43118
  exec("icacls", args, (err) => err ? reject(new Error(`icacls failed, refusing to write credentials: ${err.message}`)) : resolve());
@@ -42912,16 +43121,16 @@ function icacls(args, exec) {
42912
43121
  async function restrictWindowsAcl(dir, file, opts = {}) {
42913
43122
  if ((opts.platform ?? process.platform) !== "win32") return;
42914
43123
  const exec = opts.exec ?? defaultExec;
42915
- const user = opts.user ?? (0, import_node_os.userInfo)().username;
43124
+ const user = opts.user ?? (0, import_node_os2.userInfo)().username;
42916
43125
  for (const step of windowsOwnerOnlyDirAclSteps(dir, user)) await icacls(step, exec);
42917
43126
  if (await (0, import_promises.access)(file).then(() => true, () => false)) {
42918
43127
  for (const step of windowsOwnerOnlyFileAclSteps(file, user)) await icacls(step, exec);
42919
43128
  }
42920
43129
  }
42921
43130
  function configPath() {
42922
- return (0, import_node_path.join)((0, import_node_os.homedir)(), ".config", "norc", "config.json");
43131
+ return (0, import_node_path2.join)((0, import_node_os2.homedir)(), ".config", "norc", "config.json");
42923
43132
  }
42924
- async function loadConfigStrict(path = configPath()) {
43133
+ async function readConfigFile(path = configPath()) {
42925
43134
  try {
42926
43135
  return JSON.parse(await (0, import_promises.readFile)(path, "utf8"));
42927
43136
  } catch (e) {
@@ -42929,15 +43138,123 @@ async function loadConfigStrict(path = configPath()) {
42929
43138
  throw e;
42930
43139
  }
42931
43140
  }
42932
- async function loadConfig(path = configPath()) {
43141
+ async function loadConfig(path = configPath(), opts = {}) {
43142
+ let config;
42933
43143
  try {
42934
- const config = await loadConfigStrict(path);
42935
- debugLog("config: loaded", path, "\u2014 has session:", Boolean(config.session), "has device:", Boolean(config.device));
42936
- return config;
43144
+ config = await readConfigFile(path);
42937
43145
  } catch (e) {
42938
43146
  debugLog("config: no existing config at", path, "(", e instanceof Error ? e.message : String(e), ") \u2014 starting empty");
42939
43147
  return {};
42940
43148
  }
43149
+ await hydrateSecrets(config, path, opts.enc ?? true);
43150
+ debugLog("config: loaded", path, "\u2014 has session:", Boolean(config.session), "has device:", Boolean(config.device));
43151
+ return config;
43152
+ }
43153
+ var sha256 = (v) => (0, import_node_crypto.createHash)("sha256").update(v).digest("hex");
43154
+ var deviceAccount = (tokenSha256) => `device-token-${tokenSha256.slice(0, 16)}`;
43155
+ var encAccount = (pub) => `enc-key-${sha256(`${pub.x}.${pub.y}`).slice(0, 16)}`;
43156
+ var deviceHash = (d) => d && (d.tokenSha256 ?? (d.deviceToken ? sha256(d.deviceToken) : void 0));
43157
+ var accountsOf = (c) => [
43158
+ ...c.device?.tokenSha256 && !c.device.deviceToken ? [deviceAccount(c.device.tokenSha256)] : [],
43159
+ ...c.enc?.publicJwk && !c.enc.privateJwk ? [encAccount(c.enc.publicJwk)] : []
43160
+ ];
43161
+ var secretCache = /* @__PURE__ */ new Map();
43162
+ var setFailed = false;
43163
+ var warned = false;
43164
+ var encNoted = false;
43165
+ function warnOnce(reason) {
43166
+ if (warned) return;
43167
+ warned = true;
43168
+ console.error(`norc: OS keychain unavailable (${reason.replace(/\s+/g, " ").trim()}); keeping the device token and relay key in the 0600 config file.`);
43169
+ }
43170
+ async function getSecret(store, account, what) {
43171
+ const cached2 = secretCache.get(account);
43172
+ if (cached2 !== void 0) return cached2;
43173
+ if (!store) return null;
43174
+ try {
43175
+ return await store.get(account);
43176
+ } catch (e) {
43177
+ throw new Error(`norc: can't read the ${what} from the OS keychain: ${e instanceof Error ? e.message : String(e)}. Unlock the keychain and try again (a Mac that runs norc with nobody logged in: see NORC_SECRET_STORE in the norc README).`);
43178
+ }
43179
+ }
43180
+ async function hydrateSecrets(config, path, enc2, retried = false) {
43181
+ const store = readSecretStore();
43182
+ const d = config.device;
43183
+ if (d && !d.deviceToken && d.tokenSha256) {
43184
+ const want = d.tokenSha256;
43185
+ const v = await getSecret(store, deviceAccount(want), "device token");
43186
+ if (v === null || sha256(v) !== want) {
43187
+ const now = retried ? void 0 : await readConfigFile(path).catch(() => void 0);
43188
+ if (now?.device?.tokenSha256 && now.device.tokenSha256 !== want) {
43189
+ Object.assign(config, now);
43190
+ return hydrateSecrets(config, path, enc2, true);
43191
+ }
43192
+ throw new Error(`norc: the device token is ${v === null ? "missing from" : "wrong in"} the OS keychain. Run \`norc pair\` (or \`norc login --key\`) to pair this machine again.`);
43193
+ }
43194
+ secretCache.set(deviceAccount(want), v);
43195
+ d.deviceToken = v;
43196
+ }
43197
+ const k = config.enc;
43198
+ if (enc2 && k?.publicJwk && !k.privateJwk) {
43199
+ const v = await getSecret(store, encAccount(k.publicJwk), "relay encryption key");
43200
+ let p = null;
43201
+ try {
43202
+ p = v === null ? null : JSON.parse(v);
43203
+ } catch {
43204
+ }
43205
+ if (p && typeof p.d === "string" && p.x === k.publicJwk.x && p.y === k.publicJwk.y) {
43206
+ secretCache.set(encAccount(k.publicJwk), v);
43207
+ k.privateJwk = p;
43208
+ } else {
43209
+ delete config.enc;
43210
+ if (!encNoted) {
43211
+ encNoted = true;
43212
+ console.error("norc: the relay encryption key is missing from the OS keychain; generating a new one.");
43213
+ }
43214
+ }
43215
+ }
43216
+ }
43217
+ async function stashSecrets(c, store) {
43218
+ const put2 = async (account, value) => {
43219
+ if (setFailed || secretCache.get(account) === value) return;
43220
+ try {
43221
+ await store.set(account, value);
43222
+ secretCache.set(account, value);
43223
+ } catch (e) {
43224
+ setFailed = true;
43225
+ warnOnce(e instanceof Error ? e.message : String(e));
43226
+ }
43227
+ };
43228
+ if (c.device?.deviceToken) await put2(deviceAccount(sha256(c.device.deviceToken)), c.device.deviceToken);
43229
+ if (c.enc?.privateJwk && c.enc.publicJwk) await put2(encAccount(c.enc.publicJwk), JSON.stringify(c.enc.privateJwk));
43230
+ }
43231
+ function markSecrets(config, keychain) {
43232
+ const d = config.device;
43233
+ const dev = (rest) => ({ machineId: d.machineId, ...rest, ...d.pairedAt ? { pairedAt: d.pairedAt } : {} });
43234
+ if (d?.deviceToken) {
43235
+ const h = sha256(d.deviceToken);
43236
+ config.device = keychain && secretCache.get(deviceAccount(h)) === d.deviceToken ? dev({ tokenSha256: h }) : dev({ deviceToken: d.deviceToken });
43237
+ } else if (!keychain && d?.tokenSha256) {
43238
+ const v = secretCache.get(deviceAccount(d.tokenSha256));
43239
+ if (v !== void 0) config.device = dev({ deviceToken: v });
43240
+ }
43241
+ const k = config.enc;
43242
+ if (!k?.publicJwk) return;
43243
+ if (k.privateJwk) {
43244
+ if (keychain && secretCache.get(encAccount(k.publicJwk)) === JSON.stringify(k.privateJwk)) config.enc = { publicJwk: k.publicJwk };
43245
+ } else if (!keychain) {
43246
+ const v = secretCache.get(encAccount(k.publicJwk));
43247
+ if (v !== void 0) config.enc = { publicJwk: k.publicJwk, privateJwk: JSON.parse(v) };
43248
+ }
43249
+ }
43250
+ async function migrateSecrets(path = configPath()) {
43251
+ const raw = await readConfigFile(path).catch(() => ({}));
43252
+ if (secretStore()) {
43253
+ if (raw.device?.deviceToken || raw.enc?.privateJwk) await saveConfig({}, path, { keys: [] });
43254
+ } else if (accountsOf(raw).length) {
43255
+ await loadConfig(path);
43256
+ await saveConfig({}, path, { keys: [] });
43257
+ }
42941
43258
  }
42942
43259
  async function refreshRemote(config, path = configPath()) {
42943
43260
  try {
@@ -42947,12 +43264,9 @@ async function refreshRemote(config, path = configPath()) {
42947
43264
  config.remote = void 0;
42948
43265
  }
42949
43266
  }
42950
- var LOCK_STALE_MS = 1e4;
42951
- var LOCK_WAIT_MS = 5e3;
42952
- async function withConfigLock(path, fn) {
42953
- const lock = `${path}.lock`;
42954
- await (0, import_promises.mkdir)((0, import_node_path.join)(path, ".."), { recursive: true, mode: 448 });
42955
- const deadline = Date.now() + LOCK_WAIT_MS;
43267
+ async function withFileLock(lock, o, fn) {
43268
+ await (0, import_promises.mkdir)((0, import_node_path2.dirname)(lock), { recursive: true, mode: 448 });
43269
+ const deadline = Date.now() + o.waitMs;
42956
43270
  for (; ; ) {
42957
43271
  try {
42958
43272
  await (0, import_promises.mkdir)(lock);
@@ -42960,27 +43274,45 @@ async function withConfigLock(path, fn) {
42960
43274
  } catch (e) {
42961
43275
  if (e.code !== "EEXIST") throw e;
42962
43276
  const age = await (0, import_promises.stat)(lock).then((st) => Date.now() - st.mtimeMs).catch(() => 0);
42963
- if (age > LOCK_STALE_MS) {
43277
+ if (age > o.staleMs || await lockHolderDead(lock)) {
42964
43278
  await (0, import_promises.rm)(lock, { recursive: true, force: true });
42965
43279
  continue;
42966
43280
  }
42967
- if (Date.now() > deadline) throw new Error("config is locked by another norc process; try again");
43281
+ if (Date.now() > deadline) throw new Error(o.busy);
42968
43282
  await new Promise((r) => setTimeout(r, 25));
42969
43283
  }
42970
43284
  }
43285
+ await (0, import_promises.writeFile)((0, import_node_path2.join)(lock, "owner"), `${process.pid}
43286
+ ${(0, import_node_os2.hostname)()}`).catch(() => {
43287
+ });
42971
43288
  try {
42972
43289
  return await fn();
42973
43290
  } finally {
42974
43291
  await (0, import_promises.rm)(lock, { recursive: true, force: true });
42975
43292
  }
42976
43293
  }
43294
+ async function lockHolderDead(lock) {
43295
+ const [pid, host] = (await (0, import_promises.readFile)((0, import_node_path2.join)(lock, "owner"), "utf8").catch(() => "")).split("\n");
43296
+ if (host !== (0, import_node_os2.hostname)() || !Number(pid)) return false;
43297
+ try {
43298
+ process.kill(Number(pid), 0);
43299
+ return false;
43300
+ } catch (e) {
43301
+ return e.code === "ESRCH";
43302
+ }
43303
+ }
43304
+ var LOCK_STALE_MS = 3e4;
43305
+ var LOCK_WAIT_MS = 1e4;
43306
+ function withConfigLock(path, fn) {
43307
+ return withFileLock(`${path}.lock`, { staleMs: LOCK_STALE_MS, waitMs: LOCK_WAIT_MS, busy: "config is locked by another norc process; try again" }, fn);
43308
+ }
42977
43309
  async function sweepConfigTemps(path = configPath(), minAgeMs = 6e4) {
42978
- const base = (0, import_node_path.basename)(path).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
43310
+ const base = (0, import_node_path2.basename)(path).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
42979
43311
  const re = new RegExp(`^${base}\\.\\d+\\.\\d+\\.tmp$`);
42980
- const dir = (0, import_node_path.dirname)(path);
43312
+ const dir = (0, import_node_path2.dirname)(path);
42981
43313
  for (const n of (await (0, import_promises.readdir)(dir).catch(() => [])).filter((x) => re.test(x))) {
42982
43314
  try {
42983
- const f = (0, import_node_path.join)(dir, n);
43315
+ const f = (0, import_node_path2.join)(dir, n);
42984
43316
  const st = await (0, import_promises.lstat)(f);
42985
43317
  if (st.isDirectory() || minAgeMs > 0 && Date.now() - st.mtimeMs < minAgeMs) continue;
42986
43318
  await (0, import_promises.rm)(f, { force: true });
@@ -42991,12 +43323,23 @@ async function sweepConfigTemps(path = configPath(), minAgeMs = 6e4) {
42991
43323
  async function saveConfig(config, path, opts) {
42992
43324
  path ??= configPath();
42993
43325
  const file = path;
42994
- await withConfigLock(file, async () => {
42995
- const disk = await loadConfigStrict(file);
43326
+ const store = secretStore();
43327
+ if (store) {
43328
+ const pick = {};
43329
+ for (const k of opts.keys) Object.assign(pick, { [k]: config[k] });
43330
+ await stashSecrets(pick, store);
43331
+ await stashSecrets(await readConfigFile(file).catch(() => ({})), store);
43332
+ }
43333
+ let stale = [];
43334
+ const saved = await withConfigLock(file, async () => {
43335
+ const disk = await readConfigFile(file);
43336
+ if (opts.ifDevice !== void 0 && deviceHash(disk.device) !== opts.ifDevice) return false;
43337
+ const before = accountsOf(disk);
42996
43338
  for (const k of opts.keys) delete disk[k];
42997
43339
  for (const k of opts.keys) if (config[k] !== void 0) Object.assign(disk, { [k]: config[k] });
42998
43340
  config = disk;
42999
- const dir = (0, import_node_path.join)(path, "..");
43341
+ markSecrets(config, store !== null);
43342
+ const dir = (0, import_node_path2.join)(path, "..");
43000
43343
  await (0, import_promises.mkdir)(dir, { recursive: true, mode: 448 });
43001
43344
  await (0, import_promises.chmod)(dir, 448);
43002
43345
  await restrictWindowsAcl(dir, path);
@@ -43016,16 +43359,27 @@ async function saveConfig(config, path, opts) {
43016
43359
  }
43017
43360
  await (0, import_promises.chmod)(path, 384);
43018
43361
  await restrictWindowsAcl(dir, path);
43362
+ const after = new Set(accountsOf(config));
43363
+ stale = before.filter((a) => !after.has(a));
43019
43364
  debugLog("config: saved", path, "\u2014 has session:", Boolean(config.session), "has device:", Boolean(config.device));
43365
+ return true;
43020
43366
  });
43367
+ const del = stale.length ? readSecretStore() : null;
43368
+ for (const a of stale) {
43369
+ secretCache.delete(a);
43370
+ await del?.delete(a).catch((e) => console.error(
43371
+ `norc: could not remove the unused keychain item ${SECRET_SERVICE}/${a} (${e instanceof Error ? e.message : String(e)}). Delete it in your OS keychain manager.`
43372
+ ));
43373
+ }
43374
+ return saved;
43021
43375
  }
43022
43376
 
43023
43377
  // src/crontab-io.ts
43024
- var import_node_child_process2 = require("node:child_process");
43378
+ var import_node_child_process3 = require("node:child_process");
43025
43379
  var systemCrontabIo = {
43026
43380
  read() {
43027
43381
  return new Promise((resolve, reject) => {
43028
- (0, import_node_child_process2.execFile)("crontab", ["-l"], (err, stdout, stderr) => {
43382
+ (0, import_node_child_process3.execFile)("crontab", ["-l"], (err, stdout, stderr) => {
43029
43383
  if (err) {
43030
43384
  if (/no crontab/i.test(stderr)) return resolve("");
43031
43385
  return reject(new Error(stderr.trim() || err.message));
@@ -43036,7 +43390,7 @@ var systemCrontabIo = {
43036
43390
  },
43037
43391
  write(contents) {
43038
43392
  return new Promise((resolve, reject) => {
43039
- const child = (0, import_node_child_process2.execFile)("crontab", ["-"], { timeout: 15e3 }, (err, _stdout, stderr) => {
43393
+ const child = (0, import_node_child_process3.execFile)("crontab", ["-"], { timeout: 15e3 }, (err, _stdout, stderr) => {
43040
43394
  if (err) return reject(new Error(stderr.trim() || err.message));
43041
43395
  resolve();
43042
43396
  });
@@ -43047,9 +43401,10 @@ var systemCrontabIo = {
43047
43401
  };
43048
43402
 
43049
43403
  // src/commands/login.ts
43404
+ var ACCOUNT_PROBE = /signups not allowed|otp_disabled|over_email_send_rate_limit|for security purposes|email rate limit/i;
43050
43405
  async function requestLogin(client, email) {
43051
43406
  const start = await client.auth.signInWithOtp({ email, options: { shouldCreateUser: false } });
43052
- if (start.error) return { ok: false, message: start.error.message };
43407
+ if (start.error && !ACCOUNT_PROBE.test(`${start.error.code ?? ""} ${start.error.message}`)) return { ok: false, message: start.error.message };
43053
43408
  return { ok: true };
43054
43409
  }
43055
43410
  async function verifyLogin(client, email, code) {
@@ -43064,10 +43419,10 @@ async function verifyLogin(client, email, code) {
43064
43419
  }
43065
43420
 
43066
43421
  // src/commands/pair.ts
43067
- var import_node_os3 = require("node:os");
43422
+ var import_node_os4 = require("node:os");
43068
43423
 
43069
43424
  // src/host-info.ts
43070
- var import_node_os2 = require("node:os");
43425
+ var import_node_os3 = require("node:os");
43071
43426
  function normalizeArch(raw) {
43072
43427
  switch (raw) {
43073
43428
  case "arm64":
@@ -43098,12 +43453,12 @@ function firstLanIPv4(interfaces) {
43098
43453
  return null;
43099
43454
  }
43100
43455
  function hostInfo() {
43101
- const h = (0, import_node_os2.hostname)();
43456
+ const h = (0, import_node_os3.hostname)();
43102
43457
  return {
43103
43458
  hostname: h,
43104
43459
  networkName: h,
43105
- ipAddress: firstLanIPv4((0, import_node_os2.networkInterfaces)()),
43106
- cpuArch: normalizeArch((0, import_node_os2.arch)())
43460
+ ipAddress: firstLanIPv4((0, import_node_os3.networkInterfaces)()),
43461
+ cpuArch: normalizeArch((0, import_node_os3.arch)())
43107
43462
  };
43108
43463
  }
43109
43464
 
@@ -43117,7 +43472,7 @@ async function runPairing(client, onProgress, opts = {}) {
43117
43472
  network_name: info.networkName,
43118
43473
  ip_address: info.ipAddress,
43119
43474
  cpu_arch: info.cpuArch,
43120
- os: `${(0, import_node_os3.platform)()} ${(0, import_node_os3.release)()}`
43475
+ os: `${(0, import_node_os4.platform)()} ${(0, import_node_os4.release)()}`
43121
43476
  // shown to the approver in pair_preview (AZ-011)
43122
43477
  });
43123
43478
  if (error || !data?.[0]) {
@@ -43149,13 +43504,13 @@ async function runPairing(client, onProgress, opts = {}) {
43149
43504
  }
43150
43505
 
43151
43506
  // src/commands/pair-key.ts
43152
- async function pairWithApiKey(fetchImpl, vaultUrl2, apiKey, hostname3) {
43507
+ async function pairWithApiKey(fetchImpl, vaultUrl2, apiKey, hostname4) {
43153
43508
  const url = `${vaultUrl2}/api/v1/machines`;
43154
- debugLog("POST", url, { authorization: `Bearer ${redactSecret(apiKey)}`, hostname: hostname3 });
43509
+ debugLog("POST", url, { authorization: `Bearer ${redactSecret(apiKey)}`, hostname: hostname4 });
43155
43510
  const res = await fetchImpl(url, {
43156
43511
  method: "POST",
43157
43512
  headers: { authorization: `Bearer ${apiKey}`, "content-type": "application/json" },
43158
- body: JSON.stringify({ hostname: hostname3 })
43513
+ body: JSON.stringify({ hostname: hostname4 })
43159
43514
  });
43160
43515
  const rawText = await res.text().catch(() => "");
43161
43516
  let body;
@@ -43234,7 +43589,7 @@ function promptSecret(question, { stdin, stdout } = { stdin: process.stdin, stdo
43234
43589
  }
43235
43590
 
43236
43591
  // src/commands/jobs.ts
43237
- var import_node_crypto = require("node:crypto");
43592
+ var import_node_crypto2 = require("node:crypto");
43238
43593
  var CONTROL3 = /[\r\n\0]/;
43239
43594
  function assertSafeField(field, val) {
43240
43595
  if (CONTROL3.test(val)) throw new Error(`${field} contains a control char (\\n/\\r/NUL)`);
@@ -43253,7 +43608,7 @@ function newJob(schedule, command, name) {
43253
43608
  if (errors.length > 0) throw new Error(`invalid schedule: ${errors.map((e) => e.message).join("; ")}`);
43254
43609
  assertSafeField("command", command);
43255
43610
  if (name) assertSafeField("name", name);
43256
- return { kind: "job", id: (0, import_node_crypto.randomUUID)(), name, schedule, command, enabled: true };
43611
+ return { kind: "job", id: (0, import_node_crypto2.randomUUID)(), name, schedule, command, enabled: true };
43257
43612
  }
43258
43613
  var wrapped = (job, envNames = []) => ({ ...job, command: wrapCommand(job.id, job.command, "posix", envNames) });
43259
43614
  async function appendJob(io, job, envNames = []) {
@@ -43400,8 +43755,10 @@ async function set(name, d) {
43400
43755
  d.out(`${existing ? "updated" : "created"} ${name}`);
43401
43756
  return 0;
43402
43757
  }
43403
- if (res.status === 403 && res.body.error === "plan_limit_reached") d.err("plan limit reached: archive or delete a variable, or upgrade your plan");
43404
- else if (res.status === 409) d.err(`${name} already exists`);
43758
+ if (res.status === 403 && res.body.error === "plan_limit_reached") {
43759
+ const plan = await d.plan?.().catch(() => null);
43760
+ d.err(`plan limit reached: archive or delete a variable, or upgrade your plan${plan && envVarUpgradeHint(plan) ? `. ${envVarUpgradeHint(plan)}` : ""}`);
43761
+ } else if (res.status === 409) d.err(`${name} already exists`);
43405
43762
  else d.err(`could not save ${name} (${res.body.error ?? `HTTP ${res.status}`})`);
43406
43763
  return 1;
43407
43764
  }
@@ -43415,19 +43772,19 @@ async function act(d, fn, v, done) {
43415
43772
  return 0;
43416
43773
  }
43417
43774
  async function destructive(sub, name, v, yes, d) {
43418
- const rm5 = sub === "rm";
43775
+ const rm6 = sub === "rm";
43419
43776
  const all = await d.impact(name);
43420
43777
  const rows = all.filter((r) => !r.job_archived);
43421
43778
  const na = all.filter((r) => r.job_archived);
43422
- if (rows.length > 0) d.out(impactText(rm5 ? "Deleting" : "Archiving", name, rows));
43779
+ if (rows.length > 0) d.out(impactText(rm6 ? "Deleting" : "Archiving", name, rows));
43423
43780
  if (na.length > 0) d.out(notAffectedText(na));
43424
43781
  if (!yes) {
43425
43782
  if (!d.isTTY) {
43426
- if (rm5 || rows.length > 0) {
43783
+ if (rm6 || rows.length > 0) {
43427
43784
  d.err("refusing without --yes on a non-interactive terminal");
43428
43785
  return 1;
43429
43786
  }
43430
- } else if (rm5) {
43787
+ } else if (rm6) {
43431
43788
  const answer = await d.readLine(`type ${name} to delete it permanently: `);
43432
43789
  if (answer === null || answer.trim() !== name) {
43433
43790
  d.err("cancelled");
@@ -43441,7 +43798,7 @@ async function destructive(sub, name, v, yes, d) {
43441
43798
  }
43442
43799
  }
43443
43800
  }
43444
- if (!rm5) return act(d, "archive_env_var", v, `archived ${name}`);
43801
+ if (!rm6) return act(d, "archive_env_var", v, `archived ${name}`);
43445
43802
  return remove2(name, v, d);
43446
43803
  }
43447
43804
  async function remove2(name, v, d) {
@@ -43821,17 +44178,22 @@ function withoutPkgEnv(command, platform2 = process.platform) {
43821
44178
  }
43822
44179
 
43823
44180
  // src/commands/run.ts
43824
- var import_node_child_process4 = require("node:child_process");
44181
+ var import_node_child_process5 = require("node:child_process");
44182
+
44183
+ // src/device-session.ts
44184
+ var import_node_path5 = require("node:path");
44185
+ var import_node_crypto4 = require("node:crypto");
44186
+ var import_promises3 = require("node:fs/promises");
43825
44187
 
43826
44188
  // src/host-details.ts
43827
- var import_node_child_process3 = require("node:child_process");
44189
+ var import_node_child_process4 = require("node:child_process");
43828
44190
  var import_node_fs = require("node:fs");
43829
- var import_node_crypto2 = require("node:crypto");
43830
- var import_node_os4 = require("node:os");
43831
- var import_node_path2 = require("node:path");
44191
+ var import_node_crypto3 = require("node:crypto");
44192
+ var import_node_os5 = require("node:os");
44193
+ var import_node_path3 = require("node:path");
43832
44194
 
43833
44195
  // src/version.ts
43834
- var VERSION2 = "0.3.2";
44196
+ var VERSION2 = "0.3.3";
43835
44197
 
43836
44198
  // src/host-details.ts
43837
44199
  var ARCH = { x64: "x86_64", arm64: "arm64", ia32: "x86", arm: "arm" };
@@ -43850,7 +44212,7 @@ function windowsOsName(kernel, isClient) {
43850
44212
  }
43851
44213
  function windowsIsClient() {
43852
44214
  try {
43853
- const out = (0, import_node_child_process3.execFileSync)("powershell.exe", ["-NoProfile", "-Command", "(Get-CimInstance Win32_OperatingSystem).ProductType"], { encoding: "utf8", timeout: 4e3 }).trim();
44215
+ const out = (0, import_node_child_process4.execFileSync)("powershell.exe", ["-NoProfile", "-Command", "(Get-CimInstance Win32_OperatingSystem).ProductType"], { encoding: "utf8", timeout: 4e3 }).trim();
43854
44216
  return out === "1" ? true : out === "2" || out === "3" ? false : void 0;
43855
44217
  } catch {
43856
44218
  return void 0;
@@ -43858,7 +44220,7 @@ function windowsIsClient() {
43858
44220
  }
43859
44221
  function osName(platform2) {
43860
44222
  if (platform2 === "linux") return osNameUncached(platform2);
43861
- const file = (0, import_node_path2.join)((0, import_node_os4.homedir)(), ".config", "norc", `os-${platform2}-${(0, import_node_crypto2.createHash)("sha1").update(`${(0, import_node_os4.release)()}|${(0, import_node_os4.version)()}`).digest("hex").slice(0, 12)}.txt`);
44223
+ const file = (0, import_node_path3.join)((0, import_node_os5.homedir)(), ".config", "norc", `os-${platform2}-${(0, import_node_crypto3.createHash)("sha1").update(`${(0, import_node_os5.release)()}|${(0, import_node_os5.version)()}`).digest("hex").slice(0, 12)}.txt`);
43862
44224
  try {
43863
44225
  const hit = (0, import_node_fs.readFileSync)(file, "utf8").trim();
43864
44226
  if (/^[\w .()+-]{1,64}$/.test(hit)) return hit;
@@ -43876,15 +44238,15 @@ function osName(platform2) {
43876
44238
  function osNameUncached(platform2) {
43877
44239
  try {
43878
44240
  if (platform2 === "linux") return linuxOsName((0, import_node_fs.readFileSync)("/etc/os-release", "utf8"));
43879
- if (platform2 === "darwin") return `macOS ${(0, import_node_child_process3.execFileSync)("sw_vers", ["-productVersion"], { encoding: "utf8", timeout: 2e3 }).trim()}`;
43880
- if (platform2 === "win32") return windowsOsName((0, import_node_os4.release)(), windowsIsClient());
44241
+ if (platform2 === "darwin") return `macOS ${(0, import_node_child_process4.execFileSync)("sw_vers", ["-productVersion"], { encoding: "utf8", timeout: 2e3 }).trim()}`;
44242
+ if (platform2 === "win32") return windowsOsName((0, import_node_os5.release)(), windowsIsClient());
43881
44243
  } catch {
43882
44244
  }
43883
44245
  return void 0;
43884
44246
  }
43885
44247
  function bootedAt() {
43886
44248
  try {
43887
- return new Date(Math.round((Date.now() - (0, import_node_os4.uptime)() * 1e3) / 6e4) * 6e4).toISOString();
44249
+ return new Date(Math.round((Date.now() - (0, import_node_os5.uptime)() * 1e3) / 6e4) * 6e4).toISOString();
43888
44250
  } catch {
43889
44251
  return void 0;
43890
44252
  }
@@ -43897,16 +44259,16 @@ function hostDetails() {
43897
44259
 
43898
44260
  // src/env-cache.ts
43899
44261
  var import_promises2 = require("node:fs/promises");
43900
- var import_node_path3 = require("node:path");
44262
+ var import_node_path4 = require("node:path");
43901
44263
  function envCachePath() {
43902
- return (0, import_node_path3.join)((0, import_node_path3.dirname)(configPath()), "env");
44264
+ return (0, import_node_path4.join)((0, import_node_path4.dirname)(configPath()), "env");
43903
44265
  }
43904
44266
  async function tempLeftovers(path) {
43905
- const re = new RegExp(`^${(0, import_node_path3.basename)(path).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\.\\d+\\.\\d+\\.tmp$`);
43906
- return (await (0, import_promises2.readdir)((0, import_node_path3.dirname)(path)).catch(() => [])).filter((n) => re.test(n)).map((n) => (0, import_node_path3.join)((0, import_node_path3.dirname)(path), n));
44267
+ const re = new RegExp(`^${(0, import_node_path4.basename)(path).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\.\\d+\\.\\d+\\.tmp$`);
44268
+ return (await (0, import_promises2.readdir)((0, import_node_path4.dirname)(path)).catch(() => [])).filter((n) => re.test(n)).map((n) => (0, import_node_path4.join)((0, import_node_path4.dirname)(path), n));
43907
44269
  }
43908
44270
  async function writeEnvCache(body, path = envCachePath()) {
43909
- const dir = (0, import_node_path3.dirname)(path);
44271
+ const dir = (0, import_node_path4.dirname)(path);
43910
44272
  await (0, import_promises2.mkdir)(dir, { recursive: true, mode: 448 });
43911
44273
  await (0, import_promises2.chmod)(dir, 448);
43912
44274
  await restrictWindowsAcl(dir, path);
@@ -43983,55 +44345,103 @@ function resolveJobEnv(body, jobId, required) {
43983
44345
  // src/device-session.ts
43984
44346
  var revoked = null;
43985
44347
  var revokedMint = () => revoked;
43986
- async function deviceSession(supabaseUrl2, anonKey, signal, encPublicJwk, cachePath = envCachePath()) {
43987
- const config = await loadConfig();
43988
- const token = config.device?.deviceToken;
43989
- if (!token) return null;
44348
+ var REUSED_MESSAGE = "norc revoked this machine because its credentials were used from somewhere else. Pair it again: `norc pair` (or `norc login --key`).";
44349
+ var reusedShown = false;
44350
+ var MINT_FETCH_TIMEOUT_MS = 15e3;
44351
+ var MINT_LOCK_STALE_MS = 12e4;
44352
+ var MINT_LOCK_WAIT_MS = 3e4;
44353
+ var mintLockPath = (cfgPath) => (0, import_node_path5.join)((0, import_node_path5.dirname)(cfgPath), "mint.lock");
44354
+ var quotaPausePath = (cfgPath) => (0, import_node_path5.join)((0, import_node_path5.dirname)(cfgPath), "mint-quota-pause.json");
44355
+ var readQuotaPause = async (p) => {
43990
44356
  try {
43991
- const res = await fetch(`${checkedSupabaseUrl(supabaseUrl2)}/functions/v1/device-session`, {
43992
- method: "POST",
43993
- headers: { "Content-Type": "application/json", apikey: anonKey },
43994
- // job_timezone_handling (roadmap #7): best-effort, piggybacked on this
43995
- // already-regular mint — see device-session/index.ts's header comment.
43996
- // Node's global Intl covers this, same as the browser-embedded runtime
43997
- // desktop's copy of this call runs in — no import needed.
43998
- // Machine details (0062): OS, arch and agent version, same piggyback.
43999
- body: JSON.stringify({
44000
- token,
44001
- timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
44002
- ...hostDetails(),
44003
- ...encPublicJwk ? { enc_public_jwk: encPublicJwk } : {}
44004
- }),
44005
- signal
44006
- });
44007
- if (res.status === 401 && (await res.json?.().catch(() => null))?.error === "invalid device token") {
44008
- const before = await readEnvCache(cachePath);
44009
- revoked = { body: before ?? revoked?.body ?? null };
44010
- await clearEnvCache(cachePath);
44011
- return null;
44012
- }
44013
- if (!res.ok) return null;
44014
- const session = await res.json();
44015
- revoked = null;
44016
- return session;
44357
+ const v = JSON.parse(await (0, import_promises3.readFile)(p, "utf8"));
44358
+ return typeof v?.until === "number" && typeof v?.ms === "number" ? v : null;
44359
+ } catch {
44360
+ return null;
44361
+ }
44362
+ };
44363
+ async function deviceSession(supabaseUrl2, anonKey, signal, encPublicJwk, cachePath = envCachePath(), cfgPath = configPath(), lockWaitMs = MINT_LOCK_WAIT_MS) {
44364
+ try {
44365
+ return await withFileLock(mintLockPath(cfgPath), {
44366
+ staleMs: MINT_LOCK_STALE_MS,
44367
+ waitMs: lockWaitMs,
44368
+ busy: "another norc process is minting a device session"
44369
+ }, () => mint(supabaseUrl2, anonKey, signal, encPublicJwk, cachePath, cfgPath));
44017
44370
  } catch (e) {
44018
44371
  console.error("[norc bridge] device-session fetch failed:", e);
44019
44372
  return null;
44020
44373
  }
44021
44374
  }
44375
+ async function mint(supabaseUrl2, anonKey, signal, encPublicJwk, cachePath, cfgPath) {
44376
+ const config = await loadConfig(cfgPath, { enc: false });
44377
+ const device = config.device;
44378
+ const token = device?.deviceToken;
44379
+ if (!device || !token) return null;
44380
+ const pausePath = quotaPausePath(cfgPath);
44381
+ const pause = await readQuotaPause(pausePath);
44382
+ if (quotaPaused(pause)) return null;
44383
+ const res = await fetch(`${checkedSupabaseUrl(supabaseUrl2)}/functions/v1/device-session`, {
44384
+ method: "POST",
44385
+ headers: { "Content-Type": "application/json", apikey: anonKey },
44386
+ // job_timezone_handling (roadmap #7): best-effort, piggybacked on this
44387
+ // already-regular mint — see device-session/index.ts's header comment.
44388
+ // Node's global Intl covers this, same as the browser-embedded runtime
44389
+ // desktop's copy of this call runs in — no import needed.
44390
+ // Machine details (0062): OS, arch and agent version, same piggyback.
44391
+ body: JSON.stringify({
44392
+ token,
44393
+ rotation: 1,
44394
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
44395
+ ...hostDetails(),
44396
+ ...encPublicJwk ? { enc_public_jwk: encPublicJwk } : {}
44397
+ }),
44398
+ // Bounded even without a caller signal: the mint lock is held for the whole request.
44399
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(MINT_FETCH_TIMEOUT_MS)]) : AbortSignal.timeout(MINT_FETCH_TIMEOUT_MS)
44400
+ });
44401
+ const refusal = res.status === 401 ? (await res.json?.().catch(() => null))?.error : void 0;
44402
+ if (refusal === "invalid device token" || refusal === "device token reused") {
44403
+ if (refusal === "device token reused" && !reusedShown) {
44404
+ reusedShown = true;
44405
+ console.error(REUSED_MESSAGE);
44406
+ }
44407
+ const before = await readEnvCache(cachePath);
44408
+ revoked = { body: before ?? revoked?.body ?? null };
44409
+ await clearEnvCache(cachePath);
44410
+ return null;
44411
+ }
44412
+ if (isQuotaRefusal(res.status)) {
44413
+ const next2 = nextQuotaPause(pause, res.headers?.get?.("retry-after") ?? null);
44414
+ await (0, import_promises3.writeFile)(pausePath, JSON.stringify(next2), { mode: 384 }).catch(() => {
44415
+ });
44416
+ console.error(`[norc] device-session refused (HTTP ${res.status}); pausing mints for ${Math.round(next2.ms / 6e4)} min`);
44417
+ return null;
44418
+ }
44419
+ if (!res.ok) return null;
44420
+ if (pause) await (0, import_promises3.rm)(pausePath, { force: true }).catch(() => {
44421
+ });
44422
+ const { next_device_token: next, ...session } = await res.json();
44423
+ if (typeof next === "string" && next) {
44424
+ await saveConfig({ device: { machineId: device.machineId, deviceToken: next, ...device.pairedAt ? { pairedAt: device.pairedAt } : {} } }, cfgPath, {
44425
+ keys: ["device"],
44426
+ ifDevice: (0, import_node_crypto4.createHash)("sha256").update(token).digest("hex")
44427
+ }).catch((e) => console.error("[norc] could not save the rotated device token:", e instanceof Error ? e.message : e));
44428
+ }
44429
+ revoked = null;
44430
+ return session;
44431
+ }
44022
44432
 
44023
44433
  // src/run-queue.ts
44024
- var import_promises3 = require("node:fs/promises");
44025
- var import_node_os5 = require("node:os");
44026
- var import_node_path4 = require("node:path");
44434
+ var import_promises4 = require("node:fs/promises");
44435
+ var import_node_os6 = require("node:os");
44436
+ var import_node_path6 = require("node:path");
44027
44437
  var MAX_QUEUE_LENGTH = 500;
44028
44438
  function runQueuePath() {
44029
- return (0, import_node_path4.join)((0, import_node_os5.homedir)(), ".config", "norc", "run-queue.jsonl");
44439
+ return (0, import_node_path6.join)((0, import_node_os6.homedir)(), ".config", "norc", "run-queue.jsonl");
44030
44440
  }
44031
44441
  async function readQueue(path = runQueuePath()) {
44032
44442
  let text;
44033
44443
  try {
44034
- text = await (0, import_promises3.readFile)(path, "utf8");
44444
+ text = await (0, import_promises4.readFile)(path, "utf8");
44035
44445
  } catch {
44036
44446
  return [];
44037
44447
  }
@@ -44039,26 +44449,26 @@ async function readQueue(path = runQueuePath()) {
44039
44449
  }
44040
44450
  async function writeQueue(entries, path) {
44041
44451
  const tmp = `${path}.${process.pid}.tmp`;
44042
- await (0, import_promises3.writeFile)(tmp, entries.map((e) => JSON.stringify(e)).join("\n") + (entries.length ? "\n" : ""), "utf8");
44043
- await (0, import_promises3.rename)(tmp, path);
44452
+ await (0, import_promises4.writeFile)(tmp, entries.map((e) => JSON.stringify(e)).join("\n") + (entries.length ? "\n" : ""), "utf8");
44453
+ await (0, import_promises4.rename)(tmp, path);
44044
44454
  }
44045
44455
  var LOCK_STALE_MS2 = 3e4;
44046
44456
  var LOCK_RETRY_MS = 25;
44047
44457
  var LOCK_ATTEMPTS = 40;
44048
44458
  async function withLock(path, fn) {
44049
44459
  const lockPath = `${path}.lock`;
44050
- await (0, import_promises3.mkdir)((0, import_node_path4.dirname)(path), { recursive: true });
44460
+ await (0, import_promises4.mkdir)((0, import_node_path6.dirname)(path), { recursive: true });
44051
44461
  let held = false;
44052
44462
  for (let i = 0; i < LOCK_ATTEMPTS; i++) {
44053
44463
  try {
44054
- const fh = await (0, import_promises3.open)(lockPath, "wx");
44464
+ const fh = await (0, import_promises4.open)(lockPath, "wx");
44055
44465
  await fh.close();
44056
44466
  held = true;
44057
44467
  break;
44058
44468
  } catch {
44059
44469
  try {
44060
- const { mtimeMs } = await (0, import_promises3.stat)(lockPath);
44061
- if (Date.now() - mtimeMs > LOCK_STALE_MS2) await (0, import_promises3.rm)(lockPath, { force: true });
44470
+ const { mtimeMs } = await (0, import_promises4.stat)(lockPath);
44471
+ if (Date.now() - mtimeMs > LOCK_STALE_MS2) await (0, import_promises4.rm)(lockPath, { force: true });
44062
44472
  } catch {
44063
44473
  }
44064
44474
  await new Promise((r) => setTimeout(r, LOCK_RETRY_MS));
@@ -44068,14 +44478,14 @@ async function withLock(path, fn) {
44068
44478
  try {
44069
44479
  return await fn();
44070
44480
  } finally {
44071
- await (0, import_promises3.rm)(lockPath, { force: true }).catch(() => {
44481
+ await (0, import_promises4.rm)(lockPath, { force: true }).catch(() => {
44072
44482
  });
44073
44483
  }
44074
44484
  }
44075
- async function enqueueRun(run, path = runQueuePath()) {
44485
+ async function enqueueRun(run2, path = runQueuePath()) {
44076
44486
  await withLock(path, async () => {
44077
44487
  const existing = await readQueue(path);
44078
- const next = [...existing, run].slice(-MAX_QUEUE_LENGTH);
44488
+ const next = [...existing, run2].slice(-MAX_QUEUE_LENGTH);
44079
44489
  await writeQueue(next, path);
44080
44490
  });
44081
44491
  }
@@ -44146,9 +44556,9 @@ async function runWrapped(deps, jobId, command, envNames) {
44146
44556
  const queued = (await deps.readQueue()).slice(0, FLUSH_BATCH);
44147
44557
  const flushed = [];
44148
44558
  const deadline = deps.now().getTime() + FLUSH_BUDGET_MS;
44149
- for (const run2 of queued) {
44559
+ for (const run3 of queued) {
44150
44560
  if (deps.now().getTime() >= deadline) break;
44151
- if (await deps.report(run2)) flushed.push(run2);
44561
+ if (await deps.report(run3)) flushed.push(run3);
44152
44562
  }
44153
44563
  if (flushed.length) await deps.clearQueue(flushed);
44154
44564
  } catch {
@@ -44207,7 +44617,7 @@ async function runWrapped(deps, jobId, command, envNames) {
44207
44617
  const finishedAt = deps.now().toISOString();
44208
44618
  const errorSnippet = exitCode !== 0 ? clean2(stderrTail.trim()) : "";
44209
44619
  const outputSnippet = clean2((outputTail ?? "").trim());
44210
- const run = {
44620
+ const run2 = {
44211
44621
  jobId,
44212
44622
  exitCode,
44213
44623
  startedAt,
@@ -44216,10 +44626,10 @@ async function runWrapped(deps, jobId, command, envNames) {
44216
44626
  ...errorSnippet ? { errorSnippet } : {},
44217
44627
  ...outputSnippet ? { outputSnippet } : {}
44218
44628
  };
44219
- const reported = await deps.report(run).catch(() => false);
44629
+ const reported = await deps.report(run2).catch(() => false);
44220
44630
  if (!reported) {
44221
44631
  try {
44222
- await deps.enqueueRun(run);
44632
+ await deps.enqueueRun(run2);
44223
44633
  } catch {
44224
44634
  }
44225
44635
  }
@@ -44265,7 +44675,7 @@ function realSpawnCommand(command, env) {
44265
44675
  return new Promise((resolve) => {
44266
44676
  let child;
44267
44677
  try {
44268
- child = (0, import_node_child_process4.spawn)(withoutPkgEnv(command.join(" ")), { stdio: ["inherit", "pipe", "pipe"], shell: true, ...env ? { env: { ...process.env, ...env } } : {} });
44678
+ child = (0, import_node_child_process5.spawn)(withoutPkgEnv(command.join(" ")), { stdio: ["inherit", "pipe", "pipe"], shell: true, ...env ? { env: { ...process.env, ...env } } : {} });
44269
44679
  } catch {
44270
44680
  resolve({ exitCode: 1, stderrTail: "env value could not be passed to the command", outputTail: "" });
44271
44681
  return;
@@ -44305,7 +44715,7 @@ function fetchTimeout() {
44305
44715
  return AbortSignal.timeout(FETCH_TIMEOUT_MS);
44306
44716
  }
44307
44717
  var SESSION_REFRESH_BUFFER_MS = 6e4;
44308
- function createSessionCache(anonKey) {
44718
+ function createSessionCache(anonKey, lockWaitMs = () => void 0) {
44309
44719
  let sessionPromise;
44310
44720
  return async function getSession() {
44311
44721
  if (sessionPromise) {
@@ -44313,14 +44723,14 @@ function createSessionCache(anonKey) {
44313
44723
  const expiresAt = cached2 ? new Date(cached2.expires_at).getTime() : 0;
44314
44724
  if (!cached2 || expiresAt - Date.now() < SESSION_REFRESH_BUFFER_MS) sessionPromise = void 0;
44315
44725
  }
44316
- sessionPromise ??= deviceSession(supabaseUrl(), anonKey, fetchTimeout());
44726
+ sessionPromise ??= deviceSession(supabaseUrl(), anonKey, void 0, void 0, void 0, void 0, lockWaitMs());
44317
44727
  return sessionPromise;
44318
44728
  };
44319
44729
  }
44320
44730
  function createReporter(getSession) {
44321
44731
  const anonKey = process.env.NORC_SUPABASE_ANON_KEY ?? DEFAULT_SUPABASE_ANON_KEY;
44322
44732
  const sessionFor = getSession ?? createSessionCache(anonKey);
44323
- return async function report(run) {
44733
+ return async function report(run2) {
44324
44734
  const session = await sessionFor();
44325
44735
  if (!session) return false;
44326
44736
  try {
@@ -44328,14 +44738,14 @@ function createReporter(getSession) {
44328
44738
  method: "POST",
44329
44739
  headers: { "Content-Type": "application/json", apikey: anonKey, Authorization: `Bearer ${session.token}` },
44330
44740
  body: JSON.stringify({
44331
- job_id: run.jobId,
44332
- status: run.status,
44333
- exit_code: run.exitCode,
44334
- started_at: run.startedAt,
44335
- finished_at: run.finishedAt,
44336
- ...run.errorSnippet !== void 0 ? { error_snippet: run.errorSnippet } : {},
44337
- ...run.outputSnippet !== void 0 ? { output_snippet: run.outputSnippet } : {},
44338
- ...run.backfillOf !== void 0 ? { backfill_of: run.backfillOf } : {}
44741
+ job_id: run2.jobId,
44742
+ status: run2.status,
44743
+ exit_code: run2.exitCode,
44744
+ started_at: run2.startedAt,
44745
+ finished_at: run2.finishedAt,
44746
+ ...run2.errorSnippet !== void 0 ? { error_snippet: run2.errorSnippet } : {},
44747
+ ...run2.outputSnippet !== void 0 ? { output_snippet: run2.outputSnippet } : {},
44748
+ ...run2.backfillOf !== void 0 ? { backfill_of: run2.backfillOf } : {}
44339
44749
  }),
44340
44750
  signal: fetchTimeout()
44341
44751
  });
@@ -44366,6 +44776,7 @@ function createBackfillClaimer(getSession) {
44366
44776
  }
44367
44777
  };
44368
44778
  }
44779
+ var RUN_LATE_MINT_WAIT_MS = 18e4;
44369
44780
  var RUN_USAGE = "usage: norc run --job-id <id> [--env NAME,...] -- <command>";
44370
44781
  function parseRunArgs(args) {
44371
44782
  const sepIndex = args.indexOf("--");
@@ -44385,10 +44796,17 @@ function parseRunArgs(args) {
44385
44796
  }
44386
44797
  async function cmdRun(args) {
44387
44798
  const { jobId, envNames, command } = parseRunArgs(args);
44388
- const getSession = createSessionCache(process.env.NORC_SUPABASE_ANON_KEY ?? DEFAULT_SUPABASE_ANON_KEY);
44799
+ let jobRan = false;
44800
+ const getSession = createSessionCache(process.env.NORC_SUPABASE_ANON_KEY ?? DEFAULT_SUPABASE_ANON_KEY, () => jobRan ? RUN_LATE_MINT_WAIT_MS : void 0);
44389
44801
  return runWrapped(
44390
44802
  {
44391
- spawnCommand: realSpawnCommand,
44803
+ spawnCommand: async (c, e) => {
44804
+ try {
44805
+ return await realSpawnCommand(c, e);
44806
+ } finally {
44807
+ jobRan = true;
44808
+ }
44809
+ },
44392
44810
  report: createReporter(getSession),
44393
44811
  readQueue,
44394
44812
  clearQueue,
@@ -44410,7 +44828,6 @@ var UsageParseError = class extends Error {
44410
44828
  this.name = "UsageParseError";
44411
44829
  }
44412
44830
  };
44413
- var PLANS2 = ["free", "pro", "power", "team"];
44414
44831
  var obj = (v, p) => {
44415
44832
  if (typeof v !== "object" || v === null || Array.isArray(v)) throw new UsageParseError(p, "expected object");
44416
44833
  return v;
@@ -44442,7 +44859,7 @@ function parseUsageSummary(raw) {
44442
44859
  const days = count(o.days, "days");
44443
44860
  if (days !== 7 && days !== 30) throw new UsageParseError("days", "expected 7 or 30");
44444
44861
  const plan = str(o.plan, "plan");
44445
- if (!PLANS2.includes(plan)) throw new UsageParseError("plan", `unknown plan "${plan}"`);
44862
+ if (!isPlan(plan)) throw new UsageParseError("plan", `unknown plan "${plan}"`);
44446
44863
  const daily = arr(o.daily, "daily").map((d, i) => {
44447
44864
  const e = obj(d, `daily[${i}]`);
44448
44865
  const date = str(e.date, `daily[${i}].date`);
@@ -44539,7 +44956,6 @@ var MACHINE_STATUS_DISPLAY = {
44539
44956
  var UPDATE_REQUIRED_DISPLAY = { ...MACHINE_STATUS_DISPLAY.offline, label: "Update required" };
44540
44957
 
44541
44958
  // ../../packages/usage/src/view.ts
44542
- var PLAN_NAMES = { free: "Free", pro: "Pro", power: "Power", team: "Team" };
44543
44959
  function headroomTone(used, cap) {
44544
44960
  const p = used / cap;
44545
44961
  return p >= 0.9 ? "failed" : p >= 0.7 ? "warning" : "calm";
@@ -44557,12 +44973,13 @@ function headroomFooter(usedJobs, usedMachines, plan) {
44557
44973
  const n = PLAN_NAMES[plan];
44558
44974
  const jobs = headroom("jobs", usedJobs, plan);
44559
44975
  const mach = headroom("machines", usedMachines, plan);
44976
+ const hint = machineUpgradeHint(plan);
44560
44977
  const messages = [];
44561
44978
  if (jobs.tone !== "calm" && jobs.left != null) {
44562
44979
  messages.push(jobs.left <= 0 ? `Job limit reached on ${n}.` : `${jobs.left} job${jobs.left === 1 ? "" : "s"} left on ${n}.`);
44563
44980
  }
44564
44981
  if (mach.tone !== "calm" && mach.left != null) {
44565
- messages.push(mach.left <= 0 ? `Machine limit reached on ${n}.` : `${mach.left} machine${mach.left === 1 ? "" : "s"} left on ${n}.`);
44982
+ messages.push(mach.left <= 0 ? `Machine limit reached on ${n}.${hint ? ` ${hint}` : ""}` : `${mach.left} machine${mach.left === 1 ? "" : "s"} left on ${n}.`);
44566
44983
  }
44567
44984
  return messages.length ? { messages, note: "Plans scale jobs and machines together.", showUpgrade: plan !== "power" && plan !== "team" } : { messages, note: `Plenty of room on ${n}. You'll see a note here when you pass 70%.`, showUpgrade: false };
44568
44985
  }
@@ -44928,7 +45345,7 @@ ${USAGE2}`);
44928
45345
 
44929
45346
  // src/paired-device.ts
44930
45347
  async function savePairedDevice(device, cfgPath = configPath(), cachePath = envCachePath()) {
44931
- await saveConfig({ device }, cfgPath, { keys: ["device"] });
45348
+ await saveConfig({ device: { ...device, pairedAt: device.pairedAt ?? (/* @__PURE__ */ new Date()).toISOString() } }, cfgPath, { keys: ["device", "enc"] });
44932
45349
  await clearEnvCache(cachePath);
44933
45350
  }
44934
45351
 
@@ -44942,7 +45359,7 @@ async function saveUserSession(session, path = configPath()) {
44942
45359
  await saveConfig({ session }, path, { keys: ["session"] });
44943
45360
  }
44944
45361
  async function logout(path = configPath(), cachePath = envCachePath(), opts = {}) {
44945
- const config = await loadConfig(path);
45362
+ const config = await readConfigFile(path).catch(() => ({}));
44946
45363
  const had = { session: Boolean(config.session), device: Boolean(config.device) };
44947
45364
  if (config.session && opts.signOut) {
44948
45365
  let timer;
@@ -44956,14 +45373,13 @@ async function logout(path = configPath(), cachePath = envCachePath(), opts = {}
44956
45373
  });
44957
45374
  clearTimeout(timer);
44958
45375
  }
44959
- await saveConfig({}, path, { keys: ["session", "device"], sweepAll: true });
45376
+ await saveConfig({}, path, { keys: ["session", "device", "enc"], sweepAll: true });
44960
45377
  await clearEnvCache(cachePath);
44961
45378
  return had;
44962
45379
  }
44963
45380
 
44964
45381
  // src/commands/bridge.ts
44965
- var import_node_child_process6 = require("node:child_process");
44966
- var import_node_crypto3 = require("node:crypto");
45382
+ var import_node_child_process7 = require("node:child_process");
44967
45383
 
44968
45384
  // src/enc-key.ts
44969
45385
  async function loadOrCreateEncKey(config, persist) {
@@ -44978,16 +45394,16 @@ async function loadOrCreateEncKey(config, persist) {
44978
45394
  var CAPABILITY_TRUSTED_KEYS = activeTrustedKeys();
44979
45395
 
44980
45396
  // src/dupe-check.ts
44981
- var import_promises4 = require("node:fs/promises");
44982
- var import_node_child_process5 = require("node:child_process");
45397
+ var import_promises5 = require("node:fs/promises");
45398
+ var import_node_child_process6 = require("node:child_process");
44983
45399
  var import_node_util = require("node:util");
44984
- var execFileAsync = (0, import_node_util.promisify)(import_node_child_process5.execFile);
45400
+ var execFileAsync = (0, import_node_util.promisify)(import_node_child_process6.execFile);
44985
45401
  function defaultDupeCheckDeps() {
44986
45402
  return {
44987
45403
  platform: process.platform,
44988
45404
  fileExists: async (p) => {
44989
45405
  try {
44990
- await (0, import_promises4.access)(p);
45406
+ await (0, import_promises5.access)(p);
44991
45407
  return true;
44992
45408
  } catch {
44993
45409
  return false;
@@ -45002,9 +45418,9 @@ function defaultDupeCheckDeps() {
45002
45418
  }
45003
45419
  },
45004
45420
  checkRegistry: async (displayName) => {
45005
- const script = `$found = Get-ItemProperty 'HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*' -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -eq '${displayName}' } | Select-Object -First 1; if ($found) { exit 0 } else { exit 1 }`;
45421
+ const script = `$found = Get-ItemProperty 'HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*' -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -eq $env:NORC_DISPLAY_NAME } | Select-Object -First 1; if ($found) { exit 0 } else { exit 1 }`;
45006
45422
  try {
45007
- await execFileAsync("powershell", ["-NoProfile", "-Command", script]);
45423
+ await execFileAsync("powershell", ["-NoProfile", "-Command", script], { env: { ...process.env, NORC_DISPLAY_NAME: displayName } });
45008
45424
  return true;
45009
45425
  } catch {
45010
45426
  return false;
@@ -45033,10 +45449,10 @@ async function checkForDesktopInstall(deps = defaultDupeCheckDeps()) {
45033
45449
 
45034
45450
  // src/crontab-changes.ts
45035
45451
  var import_node_fs2 = require("node:fs");
45036
- var import_node_path5 = require("node:path");
45037
- var import_node_os6 = require("node:os");
45452
+ var import_node_path7 = require("node:path");
45453
+ var import_node_os7 = require("node:os");
45038
45454
  function crontabChangesPath() {
45039
- return (0, import_node_path5.join)((0, import_node_os6.homedir)(), ".config", "norc", "crontab-changes.json");
45455
+ return (0, import_node_path7.join)((0, import_node_os7.homedir)(), ".config", "norc", "crontab-changes.json");
45040
45456
  }
45041
45457
  function fileChangeStore(path) {
45042
45458
  return {
@@ -45048,7 +45464,7 @@ function fileChangeStore(path) {
45048
45464
  }
45049
45465
  },
45050
45466
  save: (v) => {
45051
- (0, import_node_fs2.mkdirSync)((0, import_node_path5.dirname)(path), { recursive: true, mode: 448 });
45467
+ (0, import_node_fs2.mkdirSync)((0, import_node_path7.dirname)(path), { recursive: true, mode: 448 });
45052
45468
  (0, import_node_fs2.writeFileSync)(path, v, { mode: 384 });
45053
45469
  }
45054
45470
  };
@@ -45067,8 +45483,8 @@ function trackLineChanges(io, path = crontabChangesPath()) {
45067
45483
  }
45068
45484
 
45069
45485
  // src/remote-consent.ts
45070
- var import_node_os7 = require("node:os");
45071
- var import_promises5 = require("node:readline/promises");
45486
+ var import_node_os8 = require("node:os");
45487
+ var import_promises6 = require("node:readline/promises");
45072
45488
  function sanitize(s, max = 160) {
45073
45489
  const clean2 = s.replace(/[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028-\u202e\u2060-\u2069\ufeff\u{e0000}-\u{e007f}]/gu, " ").trim();
45074
45490
  return clean2.length > max ? `${clean2.slice(0, max)}\u2026` : clean2;
@@ -45121,7 +45537,7 @@ async function cmdRemote(args, config, save, io = defaultIo()) {
45121
45537
  }
45122
45538
  if (sub !== "enable") throw new Error("usage: norc remote enable|disable|status");
45123
45539
  const account = config.session?.email ?? "the account this machine is paired to";
45124
- io.log(`This allows ${account} (via norc web, mobile, desktop, MCP or API keys) to read and write this machine's crontab and run jobs on ${(0, import_node_os7.hostname)()} as the current user.`);
45540
+ io.log(`This allows ${account} (via norc web, mobile, desktop, MCP or API keys) to read and write this machine's crontab and run jobs on ${(0, import_node_os8.hostname)()} as the current user.`);
45125
45541
  io.log("Every remote change is logged here with the exact command. Disable any time with `norc remote disable`.");
45126
45542
  if (!args.includes("--yes")) {
45127
45543
  if (!io.isTTY) throw new Error("not interactive: re-run in a terminal, or pass --yes");
@@ -45139,7 +45555,7 @@ function defaultIo() {
45139
45555
  isTTY: Boolean(process.stdin.isTTY),
45140
45556
  log: (m) => console.log(m),
45141
45557
  ask: async (q) => {
45142
- const rl = (0, import_promises5.createInterface)({ input: process.stdin, output: process.stdout });
45558
+ const rl = (0, import_promises6.createInterface)({ input: process.stdin, output: process.stdout });
45143
45559
  try {
45144
45560
  return (await rl.question(q)).trim();
45145
45561
  } finally {
@@ -45228,7 +45644,7 @@ function pruneExpiredExecuteNonces(nonces, nowSec) {
45228
45644
  }
45229
45645
  function spawnWrappedCommand(command) {
45230
45646
  return new Promise((resolve, reject) => {
45231
- const child = (0, import_node_child_process6.spawn)(withoutPkgEnv(command), { shell: true, detached: true, stdio: "ignore" });
45647
+ const child = (0, import_node_child_process7.spawn)(withoutPkgEnv(command), { shell: true, detached: true, stdio: "ignore" });
45232
45648
  child.once("spawn", () => {
45233
45649
  child.unref();
45234
45650
  resolve();
@@ -45249,6 +45665,7 @@ async function logStartupWarnings(deps) {
45249
45665
  }
45250
45666
  async function runBridge(env, crontabIo) {
45251
45667
  await logStartupWarnings();
45668
+ await migrateSecrets().catch((e) => console.error("[norc bridge] could not move the device token / relay key to where NORC_SECRET_STORE says:", e instanceof Error ? e.message : e));
45252
45669
  const config = await loadConfig();
45253
45670
  if (!config.device) throw new Error("not paired \u2014 run `norc pair` first");
45254
45671
  const lineChanges = trackLineChanges(crontabIo);
@@ -45257,13 +45674,14 @@ async function runBridge(env, crontabIo) {
45257
45674
  void lineChanges.look();
45258
45675
  }, 3e4);
45259
45676
  let configSaveChain = Promise.resolve();
45260
- const persistConfig = () => {
45261
- const save = configSaveChain.then(() => saveConfig(config, void 0, { keys: ["bridge", "enc"] }));
45677
+ const persistConfig = (keys = ["bridge"]) => {
45678
+ const save = configSaveChain.then(async () => {
45679
+ await saveConfig(config, void 0, { keys });
45680
+ });
45262
45681
  configSaveChain = save.catch(() => {
45263
45682
  });
45264
45683
  return save;
45265
45684
  };
45266
- const keyPair = await loadOrCreateEncKey(config, persistConfig);
45267
45685
  let state = "disconnected";
45268
45686
  let attempt = 0;
45269
45687
  let idleLogged = false;
@@ -45277,6 +45695,15 @@ async function runBridge(env, crontabIo) {
45277
45695
  }
45278
45696
  idleLogged = false;
45279
45697
  if (onDisk) config.device = onDisk;
45698
+ let keyPair;
45699
+ try {
45700
+ config.enc = (await loadConfig()).enc;
45701
+ keyPair = await loadOrCreateEncKey(config, () => persistConfig(["bridge", "enc"]));
45702
+ } catch (e) {
45703
+ console.error("[norc bridge] could not load the relay key:", e instanceof Error ? e.message : e);
45704
+ await wait(backoffDelay(attempt++));
45705
+ continue;
45706
+ }
45280
45707
  const machineId = config.device.machineId;
45281
45708
  const builtFor = identityKey(config.device);
45282
45709
  let identityChanged = false;
@@ -45529,36 +45956,36 @@ async function applyEnvNames(crontabIo, names) {
45529
45956
  var IDLE_POLL_MS = 3e4;
45530
45957
  async function readIdentity() {
45531
45958
  try {
45532
- return (await loadConfigStrict()).device ?? null;
45959
+ return (await readConfigFile()).device ?? null;
45533
45960
  } catch {
45534
45961
  return void 0;
45535
45962
  }
45536
45963
  }
45537
45964
  function identityKey(d) {
45538
- return d ? `${d.machineId}:${(0, import_node_crypto3.createHash)("sha256").update(d.deviceToken).digest("hex").slice(0, 16)}` : "";
45965
+ return d ? `${d.machineId}:${d.pairedAt ?? ""}` : "";
45539
45966
  }
45540
45967
  function wait(ms) {
45541
45968
  return new Promise((r) => setTimeout(r, ms));
45542
45969
  }
45543
45970
 
45544
45971
  // src/service.ts
45545
- var import_promises6 = require("node:fs/promises");
45546
- var import_node_child_process7 = require("node:child_process");
45972
+ var import_promises7 = require("node:fs/promises");
45973
+ var import_node_child_process8 = require("node:child_process");
45547
45974
  var import_node_util2 = require("node:util");
45548
- var import_node_os8 = require("node:os");
45549
- var import_node_path6 = require("node:path");
45550
- var execFileAsync2 = (0, import_node_util2.promisify)(import_node_child_process7.execFile);
45975
+ var import_node_os9 = require("node:os");
45976
+ var import_node_path8 = require("node:path");
45977
+ var execFileAsync2 = (0, import_node_util2.promisify)(import_node_child_process8.execFile);
45551
45978
  function resolveBinaryPath(proc = process) {
45552
45979
  return proc.pkg ? proc.execPath : proc.argv[1];
45553
45980
  }
45554
45981
  function defaultServiceDeps(binaryPath) {
45555
45982
  return {
45556
- platform: (0, import_node_os8.platform)(),
45557
- home: (0, import_node_os8.homedir)(),
45983
+ platform: (0, import_node_os9.platform)(),
45984
+ home: (0, import_node_os9.homedir)(),
45558
45985
  binaryPath,
45559
- mkdir: import_promises6.mkdir,
45560
- writeFile: import_promises6.writeFile,
45561
- rm: import_promises6.rm,
45986
+ mkdir: import_promises7.mkdir,
45987
+ writeFile: import_promises7.writeFile,
45988
+ rm: import_promises7.rm,
45562
45989
  exec: async (cmd, args) => {
45563
45990
  await execFileAsync2(cmd, args);
45564
45991
  }
@@ -45566,10 +45993,10 @@ function defaultServiceDeps(binaryPath) {
45566
45993
  }
45567
45994
  var SCHEDULED_TASK_NAME = "norc-cli-bridge";
45568
45995
  function systemdUnitPath(home) {
45569
- return (0, import_node_path6.join)(home, ".config", "systemd", "user", "norc.service");
45996
+ return (0, import_node_path8.join)(home, ".config", "systemd", "user", "norc.service");
45570
45997
  }
45571
45998
  function launchdPlistPath(home) {
45572
- return (0, import_node_path6.join)(home, "Library", "LaunchAgents", "dev.norc.cli.plist");
45999
+ return (0, import_node_path8.join)(home, "Library", "LaunchAgents", "dev.norc.cli.plist");
45573
46000
  }
45574
46001
  var xmlEscape = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
45575
46002
  function systemdUnit(binaryPath) {
@@ -45609,7 +46036,7 @@ async function installService(deps = defaultServiceDeps(process.execPath)) {
45609
46036
  switch (deps.platform) {
45610
46037
  case "linux": {
45611
46038
  const path = systemdUnitPath(deps.home);
45612
- await deps.mkdir((0, import_node_path6.join)(deps.home, ".config", "systemd", "user"), { recursive: true });
46039
+ await deps.mkdir((0, import_node_path8.join)(deps.home, ".config", "systemd", "user"), { recursive: true });
45613
46040
  await deps.writeFile(path, systemdUnit(deps.binaryPath));
45614
46041
  await deps.exec("systemctl", ["--user", "daemon-reload"]);
45615
46042
  await deps.exec("systemctl", ["--user", "enable", "--now", "norc.service"]);
@@ -45617,7 +46044,7 @@ async function installService(deps = defaultServiceDeps(process.execPath)) {
45617
46044
  }
45618
46045
  case "darwin": {
45619
46046
  const path = launchdPlistPath(deps.home);
45620
- await deps.mkdir((0, import_node_path6.join)(deps.home, "Library", "LaunchAgents"), { recursive: true });
46047
+ await deps.mkdir((0, import_node_path8.join)(deps.home, "Library", "LaunchAgents"), { recursive: true });
45621
46048
  await deps.writeFile(path, launchdPlist(deps.binaryPath));
45622
46049
  await deps.exec("launchctl", ["load", "-w", path]);
45623
46050
  return;
@@ -45710,7 +46137,7 @@ function supabase() {
45710
46137
  return createClient(url, anon);
45711
46138
  }
45712
46139
  async function prompt(question) {
45713
- const rl = (0, import_promises7.createInterface)({ input: process.stdin, output: process.stdout });
46140
+ const rl = (0, import_promises8.createInterface)({ input: process.stdin, output: process.stdout });
45714
46141
  try {
45715
46142
  return (await rl.question(question)).trim();
45716
46143
  } finally {
@@ -45732,7 +46159,7 @@ async function cmdLogin(args) {
45732
46159
  }
45733
46160
  if (apiKey) {
45734
46161
  debugLog("login: using API-key path, POST", `${vaultUrl2}/api/v1/machines`, "key:", redactSecret(apiKey));
45735
- const result2 = await pairWithApiKey(fetch, vaultUrl2, apiKey, (0, import_node_os9.hostname)());
46162
+ const result2 = await pairWithApiKey(fetch, vaultUrl2, apiKey, (0, import_node_os10.hostname)());
45736
46163
  debugLog("login: pairWithApiKey result:", result2.ok ? { ok: true, machineId: result2.machineId, deviceToken: redactSecret(result2.deviceToken) } : result2);
45737
46164
  if (!result2.ok) throw new Error(result2.message);
45738
46165
  await savePairedDevice({ machineId: result2.machineId, deviceToken: result2.deviceToken });
@@ -45747,13 +46174,13 @@ async function cmdLogin(args) {
45747
46174
  const started = await requestLogin(client, email);
45748
46175
  debugLog("login: requestLogin result:", started);
45749
46176
  if (!started.ok) throw new Error(started.message);
45750
- console.log(`code sent to ${email}`);
46177
+ console.log(`if ${email} has a norc account, a code is on its way`);
45751
46178
  const code = await prompt("enter the code from your email: ");
45752
46179
  const result = await verifyLogin(client, email, code);
45753
46180
  debugLog("login: verifyLogin result:", result.ok ? { ok: true } : result);
45754
46181
  if (!result.ok) throw new Error(result.message);
45755
46182
  await saveUserSession({ email, accessToken: result.accessToken, refreshToken: result.refreshToken });
45756
- console.log((await loadConfig()).device ? "logged in. this machine stays paired; `norc env` now works here." : "logged in. run `norc pair` next to register this machine.");
46183
+ console.log((await readConfigFile().catch(() => ({}))).device ? "logged in. this machine stays paired; `norc env` now works here." : "logged in. run `norc pair` next to register this machine.");
45757
46184
  }
45758
46185
  async function cmdPair() {
45759
46186
  const client = supabase();
@@ -45773,7 +46200,7 @@ async function cmdPair() {
45773
46200
  });
45774
46201
  }
45775
46202
  async function userClient() {
45776
- const config = await loadConfig();
46203
+ const config = await readConfigFile();
45777
46204
  const session = requireUserSession(config);
45778
46205
  const url = supabaseUrl();
45779
46206
  const sb = createClient(url, process.env.NORC_SUPABASE_ANON_KEY ?? DEFAULT_SUPABASE_ANON_KEY, { auth: { persistSession: false, autoRefreshToken: false } });
@@ -45787,7 +46214,7 @@ async function userClient() {
45787
46214
  async function saveSession(sb) {
45788
46215
  const { data: { session } } = await sb.auth.getSession();
45789
46216
  if (!session) return;
45790
- const config = await loadConfig();
46217
+ const config = await readConfigFile();
45791
46218
  if (!config.session) return;
45792
46219
  await saveUserSession({ ...config.session, accessToken: session.access_token, refreshToken: session.refresh_token });
45793
46220
  }
@@ -45795,7 +46222,7 @@ async function envDeps() {
45795
46222
  const sb = await userClient();
45796
46223
  const url = supabaseUrl();
45797
46224
  const anon = process.env.NORC_SUPABASE_ANON_KEY ?? DEFAULT_SUPABASE_ANON_KEY;
45798
- const rl = () => (0, import_promises7.createInterface)({ input: process.stdin, output: process.stdout });
46225
+ const rl = () => (0, import_promises8.createInterface)({ input: process.stdin, output: process.stdout });
45799
46226
  return {
45800
46227
  isTTY: Boolean(process.stdin.isTTY),
45801
46228
  listVars: async () => {
@@ -45807,7 +46234,7 @@ async function envDeps() {
45807
46234
  const { data, error } = await sb.from("accounts").select("plan, trial_ends_at").limit(1).maybeSingle();
45808
46235
  const row = data;
45809
46236
  const p = row?.plan;
45810
- return error || p !== "free" && p !== "pro" && p !== "power" && p !== "team" ? null : effectivePlan(p, row?.trial_ends_at);
46237
+ return error || !isPlan(p) ? null : effectivePlan(p, row?.trial_ends_at);
45811
46238
  },
45812
46239
  bindingNames: async () => {
45813
46240
  const { data, error } = await sb.from("job_env_bindings").select("name, jobs!inner(archived_at, machines!inner(archived_at, detached_at))").is("jobs.archived_at", null).is("jobs.machines.archived_at", null).is("jobs.machines.detached_at", null);
@@ -45957,7 +46384,7 @@ async function main() {
45957
46384
  case "gitops": {
45958
46385
  const vaultUrl2 = vaultUrl();
45959
46386
  const apiKey = process.env.NORC_API_KEY;
45960
- process.exitCode = await cmdGitops(args, { fetchImpl: fetch, readFile: (p) => (0, import_promises8.readFile)(p, "utf8"), vaultUrl: vaultUrl2, apiKey });
46387
+ process.exitCode = await cmdGitops(args, { fetchImpl: fetch, readFile: (p) => (0, import_promises9.readFile)(p, "utf8"), vaultUrl: vaultUrl2, apiKey });
45961
46388
  return;
45962
46389
  }
45963
46390
  case "run":
@@ -45984,8 +46411,10 @@ async function main() {
45984
46411
  case "bridge":
45985
46412
  return cmdBridge();
45986
46413
  case "remote": {
45987
- const config = await loadConfig();
45988
- return cmdRemote(args, config, (c) => saveConfig(c, void 0, { keys: ["remote"] }));
46414
+ const config = await readConfigFile();
46415
+ return cmdRemote(args, config, async (c) => {
46416
+ await saveConfig(c, void 0, { keys: ["remote"] });
46417
+ });
45989
46418
  }
45990
46419
  case "service": {
45991
46420
  const [sub] = args;