norc-cli 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1402 -271
  2. package/package.json +6 -4
package/dist/index.js CHANGED
@@ -4184,8 +4184,8 @@ var require_RealtimeChannel = __commonJS({
4184
4184
  }
4185
4185
  /** @internal */
4186
4186
  _notThisChannelEvent(event, ref) {
4187
- const { close, error, leave, join: join6 } = constants_1.CHANNEL_EVENTS;
4188
- const events = [close, error, leave, join6];
4187
+ const { close, error, leave, join: join7 } = constants_1.CHANNEL_EVENTS;
4188
+ const events = [close, error, leave, join7];
4189
4189
  return ref && events.includes(event) && ref !== this.joinPush.ref;
4190
4190
  }
4191
4191
  /** @internal */
@@ -7731,10 +7731,10 @@ var require_webauthn = __commonJS({
7731
7731
  authenticatorAttachment: (_a = credentialWithAttachment.authenticatorAttachment) !== null && _a !== void 0 ? _a : void 0
7732
7732
  };
7733
7733
  }
7734
- function isValidDomain(hostname2) {
7734
+ function isValidDomain(hostname3) {
7735
7735
  return (
7736
7736
  // Consider localhost valid as well since it's okay wrt Secure Contexts
7737
- hostname2 === "localhost" || /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(hostname2)
7737
+ hostname3 === "localhost" || /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(hostname3)
7738
7738
  );
7739
7739
  }
7740
7740
  function browserSupportsWebAuthn() {
@@ -25554,7 +25554,7 @@ var require_parser2 = __commonJS({
25554
25554
  throw new Error("Invalid entry: " + entry);
25555
25555
  }
25556
25556
  };
25557
- CronParser.parseExpression = function parseExpression2(expression, options) {
25557
+ CronParser.parseExpression = function parseExpression(expression, options) {
25558
25558
  return CronExpression.parse(expression, options);
25559
25559
  };
25560
25560
  CronParser.fieldsToExpression = function fieldsToExpression(fields, options) {
@@ -28590,18 +28590,18 @@ var require_set = __commonJS({
28590
28590
  }
28591
28591
  static from(schema, iterable, ctx) {
28592
28592
  const { replacer } = ctx;
28593
- const set2 = new this(schema);
28593
+ const set3 = new this(schema);
28594
28594
  if (iterable && Symbol.iterator in Object(iterable))
28595
28595
  for (let value of iterable) {
28596
28596
  if (typeof replacer === "function")
28597
28597
  value = replacer.call(iterable, value, value);
28598
- set2.items.push(Pair.createPair(value, null, ctx));
28598
+ set3.items.push(Pair.createPair(value, null, ctx));
28599
28599
  }
28600
- return set2;
28600
+ return set3;
28601
28601
  }
28602
28602
  };
28603
28603
  YAMLSet.tag = "tag:yaml.org,2002:set";
28604
- var set = {
28604
+ var set2 = {
28605
28605
  collection: "map",
28606
28606
  identify: (value) => value instanceof Set,
28607
28607
  nodeClass: YAMLSet,
@@ -28620,7 +28620,7 @@ var require_set = __commonJS({
28620
28620
  }
28621
28621
  };
28622
28622
  exports2.YAMLSet = YAMLSet;
28623
- exports2.set = set;
28623
+ exports2.set = set2;
28624
28624
  }
28625
28625
  });
28626
28626
 
@@ -28727,7 +28727,7 @@ var require_schema3 = __commonJS({
28727
28727
  var merge = require_merge();
28728
28728
  var omap = require_omap();
28729
28729
  var pairs = require_pairs();
28730
- var set = require_set();
28730
+ var set2 = require_set();
28731
28731
  var timestamp = require_timestamp();
28732
28732
  var schema = [
28733
28733
  map.map,
@@ -28747,7 +28747,7 @@ var require_schema3 = __commonJS({
28747
28747
  merge.merge,
28748
28748
  omap.omap,
28749
28749
  pairs.pairs,
28750
- set.set,
28750
+ set2.set,
28751
28751
  timestamp.intTime,
28752
28752
  timestamp.floatTime,
28753
28753
  timestamp.timestamp
@@ -28774,7 +28774,7 @@ var require_tags = __commonJS({
28774
28774
  var omap = require_omap();
28775
28775
  var pairs = require_pairs();
28776
28776
  var schema$2 = require_schema3();
28777
- var set = require_set();
28777
+ var set2 = require_set();
28778
28778
  var timestamp = require_timestamp();
28779
28779
  var schemas = /* @__PURE__ */ new Map([
28780
28780
  ["core", schema.schema],
@@ -28800,7 +28800,7 @@ var require_tags = __commonJS({
28800
28800
  omap: omap.omap,
28801
28801
  pairs: pairs.pairs,
28802
28802
  seq: seq.seq,
28803
- set: set.set,
28803
+ set: set2.set,
28804
28804
  timestamp: timestamp.timestamp
28805
28805
  };
28806
28806
  var coreKnownTags = {
@@ -28808,7 +28808,7 @@ var require_tags = __commonJS({
28808
28808
  "tag:yaml.org,2002:merge": merge.merge,
28809
28809
  "tag:yaml.org,2002:omap": omap.omap,
28810
28810
  "tag:yaml.org,2002:pairs": pairs.pairs,
28811
- "tag:yaml.org,2002:set": set.set,
28811
+ "tag:yaml.org,2002:set": set2.set,
28812
28812
  "tag:yaml.org,2002:timestamp": timestamp.timestamp
28813
28813
  };
28814
28814
  function getTags(customTags, schemaName, addMergeTag) {
@@ -32933,9 +32933,9 @@ var require_dist = __commonJS({
32933
32933
  });
32934
32934
 
32935
32935
  // src/index.ts
32936
- var import_promises5 = require("node:readline/promises");
32937
- var import_promises6 = require("node:fs/promises");
32938
- var import_node_os7 = require("node:os");
32936
+ var import_promises7 = require("node:readline/promises");
32937
+ var import_promises8 = require("node:fs/promises");
32938
+ var import_node_os9 = require("node:os");
32939
32939
 
32940
32940
  // ../../node_modules/.pnpm/@supabase+supabase-js@2.108.2/node_modules/@supabase/supabase-js/dist/index.mjs
32941
32941
  var dist_exports = {};
@@ -41368,12 +41368,12 @@ function shouldPropagateToTarget(targetUrl, targets) {
41368
41368
  }
41369
41369
  return false;
41370
41370
  }
41371
- function matchStringTarget(hostname2, target) {
41372
- if (target === hostname2) return true;
41371
+ function matchStringTarget(hostname3, target) {
41372
+ if (target === hostname3) return true;
41373
41373
  if (target.startsWith("*.")) {
41374
41374
  const domain = target.slice(2);
41375
- if (hostname2.endsWith(domain)) {
41376
- if (hostname2 === domain || hostname2.endsWith("." + domain)) return true;
41375
+ if (hostname3.endsWith(domain)) {
41376
+ if (hostname3 === domain || hostname3.endsWith("." + domain)) return true;
41377
41377
  }
41378
41378
  }
41379
41379
  return false;
@@ -42126,6 +42126,9 @@ function isTemplateExample(lines, i) {
42126
42126
  return entry.kind === "comment" && TEMPLATE_EXAMPLE_RE.test(entry.text) && prev?.kind === "comment" && TEMPLATE_LEAD_IN_RE.test(prev.text);
42127
42127
  }
42128
42128
  function parseCrontab(text) {
42129
+ return parseCrontabLines(text).map((l) => l.entry);
42130
+ }
42131
+ function parseCrontabLines(text) {
42129
42132
  const lines = text.split("\n").map((l) => parseLine(l.replace(/\r$/, "")));
42130
42133
  const out = [];
42131
42134
  for (let i = 0; i < lines.length; i++) {
@@ -42136,14 +42139,14 @@ function parseCrontab(text) {
42136
42139
  if (m && next) {
42137
42140
  const ann = splitAnnotation(m[1]);
42138
42141
  if (next.kind === "job") {
42139
- out.push({ ...next, ...ann, enabled: true });
42142
+ out.push({ entry: { ...next, ...ann, enabled: true }, line: i + 1 });
42140
42143
  i++;
42141
42144
  continue;
42142
42145
  }
42143
42146
  if (next.kind === "comment") {
42144
42147
  const disabled = parseDisabledJob(next.text);
42145
42148
  if (disabled) {
42146
- out.push({ kind: "job", ...disabled, ...ann, enabled: false });
42149
+ out.push({ entry: { kind: "job", ...disabled, ...ann, enabled: false }, line: i + 1 });
42147
42150
  i++;
42148
42151
  continue;
42149
42152
  }
@@ -42153,11 +42156,11 @@ function parseCrontab(text) {
42153
42156
  if (entry.kind === "comment" && !isTemplateExample(lines, i)) {
42154
42157
  const disabled = parseDisabledJob(entry.text);
42155
42158
  if (disabled) {
42156
- out.push({ kind: "job", ...disabled, enabled: false });
42159
+ out.push({ entry: { kind: "job", ...disabled, enabled: false }, line: i });
42157
42160
  continue;
42158
42161
  }
42159
42162
  }
42160
- out.push(entry);
42163
+ out.push({ entry, line: i });
42161
42164
  }
42162
42165
  return out;
42163
42166
  }
@@ -42203,14 +42206,22 @@ var norcBinary = "norc";
42203
42206
  function setNorcBinary(path) {
42204
42207
  norcBinary = path;
42205
42208
  }
42206
- function wrapCommand(jobId, command, platform = "posix") {
42209
+ var ENV_NAME_RE = /^[A-Z_][A-Z0-9_]{0,127}$/;
42210
+ function normalizeEnvNames(names) {
42211
+ for (const n of names) if (!ENV_NAME_RE.test(n)) throw new Error(`invalid env name: ${JSON.stringify(n).slice(0, 40)}`);
42212
+ return [...new Set(names)].sort();
42213
+ }
42214
+ function wrapCommand(jobId, command, platform2 = "posix", envNames = []) {
42215
+ const names = normalizeEnvNames(envNames);
42207
42216
  if (norcBinary === null) return command;
42208
- const quote = platform === "windows" ? cmdQuote : shQuote;
42217
+ const quote = platform2 === "windows" ? cmdQuote : shQuote;
42209
42218
  const bin = SAFE_PATH.test(norcBinary) ? norcBinary : quote(norcBinary);
42210
- return `${bin} run --job-id ${jobId} -- ${quote(command)}`;
42219
+ const env = names.length > 0 ? ` --env ${names.join(",")}` : "";
42220
+ return `${bin} run --job-id ${jobId}${env} -- ${quote(command)}`;
42211
42221
  }
42212
42222
  var BINARY_TOKEN = String.raw`(?:'(?:[^']|'\\'')*'|"(?:[^"\\]|\\.)*"|[^\s'"]+)`;
42213
- var WRAPPED = new RegExp(String.raw`^${BINARY_TOKEN}\s+run\s+--job-id\s+(\S+)\s+--\s+([\s\S]+)$`);
42223
+ var ENV_LIST = String.raw`[A-Z_][A-Z0-9_]{0,127}(?:,[A-Z_][A-Z0-9_]{0,127})*`;
42224
+ var WRAPPED = new RegExp(String.raw`^${BINARY_TOKEN}\s+run\s+--job-id\s+(\S+)(?:\s+--env\s+(${ENV_LIST}))?\s+--\s+([\s\S]+)$`);
42214
42225
  function unquote(s) {
42215
42226
  if (s.length >= 2 && s.startsWith("'") && s.endsWith("'")) {
42216
42227
  return s.slice(1, -1).replace(/'\\''/g, "'");
@@ -42220,9 +42231,23 @@ function unquote(s) {
42220
42231
  }
42221
42232
  return s;
42222
42233
  }
42223
- function unwrapCommand(wrapped) {
42224
- const m = WRAPPED.exec(wrapped);
42225
- return m ? unquote(m[2]) : wrapped;
42234
+ function unwrapCommand(wrapped2) {
42235
+ const m = WRAPPED.exec(wrapped2);
42236
+ return m ? unquote(m[3]) : wrapped2;
42237
+ }
42238
+ function wrappedJobId(wrapped2) {
42239
+ const m = WRAPPED.exec(wrapped2);
42240
+ return m ? m[1] : null;
42241
+ }
42242
+ var WRAPPED_PARTS = new RegExp(String.raw`^(${BINARY_TOKEN}\s+run\s+--job-id\s+\S+)(?:\s+--env\s+${ENV_LIST})?(\s+--\s+[\s\S]+)$`);
42243
+ function setEnvNames(wrapped2, envNames) {
42244
+ const names = normalizeEnvNames(envNames);
42245
+ const m = WRAPPED_PARTS.exec(wrapped2);
42246
+ return m ? `${m[1]}${names.length > 0 ? ` --env ${names.join(",")}` : ""}${m[2]}` : null;
42247
+ }
42248
+ function wrappedEnvNames(wrapped2) {
42249
+ const m = WRAPPED.exec(wrapped2);
42250
+ return m ? m[2] ? m[2].split(",") : [] : null;
42226
42251
  }
42227
42252
 
42228
42253
  // ../../packages/crontab/src/jobs.ts
@@ -42248,14 +42273,14 @@ function assertSafeJobs(jobs) {
42248
42273
  if (val.length > MAX_FIELD) throw new Error(`job ${j.id}: ${field} exceeds ${MAX_FIELD} chars`);
42249
42274
  }
42250
42275
  }
42251
- const wrapped = new Map(jobs.map((j) => [j.id, wrapCommand(j.id, j.command)]));
42276
+ const wrapped2 = new Map(jobs.map((j) => [j.id, wrapCommand(j.id, j.command, "posix", j.envNames ?? [])]));
42252
42277
  const entries = parseCrontab(renderCrontab(jobs.map((j) => ({
42253
42278
  kind: "job",
42254
42279
  id: j.id,
42255
42280
  name: j.name,
42256
42281
  enabled: j.enabled,
42257
42282
  schedule: j.schedule,
42258
- command: wrapped.get(j.id)
42283
+ command: wrapped2.get(j.id)
42259
42284
  }))));
42260
42285
  const got = entries.filter((e) => e.kind === "job" && e.id !== void 0);
42261
42286
  if (got.length !== jobs.length) throw new Error("job set does not round-trip (line count mismatch)");
@@ -42263,21 +42288,38 @@ function assertSafeJobs(jobs) {
42263
42288
  for (const e of got) {
42264
42289
  if (e.kind !== "job") continue;
42265
42290
  const j = byId.get(e.id);
42266
- if (!j || e.schedule !== j.schedule || e.command !== wrapped.get(j.id) || e.name !== j.name || e.enabled !== j.enabled) {
42291
+ if (!j || e.schedule !== j.schedule || e.command !== wrapped2.get(j.id) || e.name !== j.name || e.enabled !== j.enabled) {
42267
42292
  throw new Error(`job ${e.id} does not round-trip`);
42268
42293
  }
42269
42294
  }
42270
42295
  }
42271
42296
 
42272
42297
  // ../../packages/crontab/src/projection.ts
42273
- function jobToEntry(job) {
42298
+ function rewriteEnvNames(currentCrontab, names) {
42299
+ const lines = currentCrontab.split("\n");
42300
+ let changed = false;
42301
+ for (const { entry: e, line } of parseCrontabLines(currentCrontab)) {
42302
+ if (e.kind !== "job" || e.id === void 0 || !names.has(e.id) || wrappedJobId(e.command) !== e.id) continue;
42303
+ const live = wrappedEnvNames(e.command);
42304
+ const want = normalizeEnvNames(names.get(e.id));
42305
+ if (live.length === want.length && live.every((n, i) => n === want[i])) continue;
42306
+ const raw = lines[line];
42307
+ const cr = raw.endsWith("\r") ? "\r" : "";
42308
+ const body = cr ? raw.slice(0, -1) : raw;
42309
+ if (!body.endsWith(e.command)) continue;
42310
+ lines[line] = body.slice(0, body.length - e.command.length) + setEnvNames(e.command, want) + cr;
42311
+ changed = true;
42312
+ }
42313
+ return changed ? lines.join("\n") : currentCrontab;
42314
+ }
42315
+ function jobToEntry(job, liveNames = null) {
42274
42316
  return {
42275
42317
  kind: "job",
42276
42318
  id: job.id,
42277
42319
  name: job.name,
42278
42320
  enabled: job.enabled,
42279
42321
  schedule: job.schedule,
42280
- command: wrapCommand(job.id, job.command)
42322
+ command: wrapCommand(job.id, job.command, "posix", job.envNames ?? liveNames ?? [])
42281
42323
  };
42282
42324
  }
42283
42325
  function renderJobsToCrontab(currentCrontab, allJobs) {
@@ -42290,7 +42332,7 @@ function renderJobsToCrontab(currentCrontab, allJobs) {
42290
42332
  if (entry.kind === "job" && entry.id !== void 0) {
42291
42333
  const job = byId.get(entry.id);
42292
42334
  if (!job || rendered.has(job.id)) continue;
42293
- out.push(jobToEntry(job));
42335
+ out.push(jobToEntry(job, wrappedEnvNames(entry.command)));
42294
42336
  rendered.add(job.id);
42295
42337
  continue;
42296
42338
  }
@@ -42320,6 +42362,12 @@ function tagUnmanagedInCrontab(currentCrontab, job, occurrence) {
42320
42362
  return renderCrontab(out);
42321
42363
  }
42322
42364
 
42365
+ // ../../packages/bridge/src/text-hash.ts
42366
+ async function sha256Hex(text) {
42367
+ const buf = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
42368
+ return [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, "0")).join("");
42369
+ }
42370
+
42323
42371
  // ../../packages/bridge/src/handler.ts
42324
42372
  async function handleCommand(cmd, io) {
42325
42373
  try {
@@ -42331,6 +42379,14 @@ async function handleCommand(cmd, io) {
42331
42379
  const changedAt = io.changedAt?.(contents);
42332
42380
  return changedAt && Object.keys(changedAt).length > 0 ? { type: "crontab", contents, changedAt } : { type: "crontab", contents };
42333
42381
  }
42382
+ case "read_managed": {
42383
+ const contents = await io.read();
42384
+ const changedAt = io.changedAt?.(contents);
42385
+ const managed = renderCrontab(parseCrontab(contents).filter((e) => e.kind === "job" && e.id !== void 0));
42386
+ return changedAt && Object.keys(changedAt).length > 0 ? { type: "crontab", contents: managed, changedAt } : { type: "crontab", contents: managed };
42387
+ }
42388
+ case "crontab_hash":
42389
+ return { type: "crontab_hash", hash: await sha256Hex(await io.read()) };
42334
42390
  case "list_jobs":
42335
42391
  return { type: "jobs", jobs: jobsOf(parseCrontab(await io.read())) };
42336
42392
  case "write_crontab": {
@@ -42402,14 +42458,14 @@ function withLineChanges(io, tracker) {
42402
42458
 
42403
42459
  // ../../packages/entitlements/src/plans.ts
42404
42460
  var FREE = ["byok_ai"];
42405
- var PRO = [...FREE, "remote_ssh", "cross_device_sync", "alerts"];
42461
+ var PRO = [...FREE, "remote_ssh", "cross_device_sync", "alerts", "api_write", "run_monitoring"];
42406
42462
  var POWER = [...PRO, "bulk_ops"];
42407
42463
  var TEAM = [...POWER, "workspaces", "rbac", "audit_log"];
42408
42464
  var PLANS = {
42409
- free: { machineLimit: 2, jobLimit: 15, capabilities: FREE },
42410
- pro: { machineLimit: 5, jobLimit: 30, capabilities: PRO },
42411
- power: { machineLimit: 25, jobLimit: 150, capabilities: POWER },
42412
- team: { machineLimit: "custom", jobLimit: "custom", capabilities: TEAM }
42465
+ free: { machineLimit: 2, jobLimit: 15, envVarLimit: 5, historyDays: 7, capabilities: FREE },
42466
+ pro: { machineLimit: 5, jobLimit: 30, envVarLimit: 25, historyDays: 90, capabilities: PRO },
42467
+ power: { machineLimit: 25, jobLimit: 150, envVarLimit: 100, historyDays: 365, capabilities: POWER },
42468
+ team: { machineLimit: "custom", jobLimit: "custom", envVarLimit: "custom", historyDays: 365, capabilities: TEAM }
42413
42469
  };
42414
42470
 
42415
42471
  // ../../packages/entitlements/src/can.ts
@@ -42419,14 +42475,53 @@ function machineLimit(plan) {
42419
42475
  function jobLimit(plan) {
42420
42476
  return PLANS[plan].jobLimit;
42421
42477
  }
42478
+ function envVarLimit(plan) {
42479
+ return PLANS[plan].envVarLimit;
42480
+ }
42481
+ function withinEnvVarLimit(plan, currentCount) {
42482
+ const limit = envVarLimit(plan);
42483
+ return limit === "custom" ? true : currentCount < limit;
42484
+ }
42485
+ function envVarUsageLabel(plan, count2) {
42486
+ const limit = envVarLimit(plan);
42487
+ const noun = `variable${count2 === 1 ? "" : "s"}`;
42488
+ return limit === "custom" ? `${count2} ${noun}` : `${count2} of ${limit} variables used`;
42489
+ }
42490
+ function envVarLimitMessage(plan, count2) {
42491
+ const limit = envVarLimit(plan);
42492
+ if (limit === "custom" || withinEnvVarLimit(plan, count2)) return null;
42493
+ return `You've used all ${limit} variables on the ${plan.charAt(0).toUpperCase() + plan.slice(1)} plan. Upgrade to add more.`;
42494
+ }
42495
+
42496
+ // ../../packages/entitlements/src/trial.ts
42497
+ var TRIAL_PLAN = "pro";
42498
+ function toDate(v) {
42499
+ if (v == null) return null;
42500
+ const d = v instanceof Date ? v : new Date(v);
42501
+ return Number.isNaN(d.getTime()) ? null : d;
42502
+ }
42503
+ function effectivePlan(plan, trialEndsAt, now = /* @__PURE__ */ new Date()) {
42504
+ const end = toDate(trialEndsAt);
42505
+ return plan === "free" && end !== null && end.getTime() > now.getTime() ? TRIAL_PLAN : plan;
42506
+ }
42422
42507
 
42423
42508
  // ../../packages/bridge/src/pairing.ts
42424
42509
  function formatPairingCode(raw) {
42425
42510
  return `${raw.slice(0, 4)}-${raw.slice(4, 8)}`;
42426
42511
  }
42512
+ var PAIR_RATE_LIMITED_MESSAGE = "Too many attempts. Wait 10 minutes and try again.";
42513
+ function isPairRateLimited(e) {
42514
+ return !!e && (e.code === "PT429" || /PAIR_RATE_LIMITED/.test(e.message ?? ""));
42515
+ }
42516
+
42517
+ // ../../packages/bridge/src/protocol.ts
42518
+ var FULL_READ_COMMANDS = ["read_crontab", "list_jobs"];
42427
42519
 
42428
42520
  // ../../packages/bridge/src/transport.ts
42429
- async function handleMessage(io, data, allow) {
42521
+ function fullReadGate(consent, message = "device owner has not allowed remote crontab reads") {
42522
+ return async (type) => FULL_READ_COMMANDS.includes(type) && !await consent() ? message : null;
42523
+ }
42524
+ async function handleMessage(io, data, allow, authorize) {
42430
42525
  let req;
42431
42526
  try {
42432
42527
  req = JSON.parse(data);
@@ -42437,12 +42532,14 @@ async function handleMessage(io, data, allow) {
42437
42532
  if (allow && !allow.includes(req.command.type)) {
42438
42533
  return JSON.stringify({ id: req.id, response: { type: "error", message: "command not allowed" } });
42439
42534
  }
42535
+ const denied = await authorize?.(req.command.type).catch(() => "consent check failed");
42536
+ if (denied) return JSON.stringify({ id: req.id, response: { type: "error", message: denied } });
42440
42537
  const reply = await handleRequest(req, io);
42441
42538
  return JSON.stringify(reply);
42442
42539
  }
42443
42540
  function serveBridge(transport, io, opts) {
42444
42541
  transport.onMessage(async (data, respond) => {
42445
- const out = await handleMessage(io, data, opts?.allow);
42542
+ const out = await handleMessage(io, data, opts?.allow, opts?.authorize);
42446
42543
  if (out !== null) (respond ?? ((o) => transport.send(o)))(out);
42447
42544
  });
42448
42545
  }
@@ -42474,16 +42571,28 @@ function b64urlToBytes(s) {
42474
42571
  for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
42475
42572
  return out;
42476
42573
  }
42477
- async function verifyEs256Jwt(jwt, publicJwk) {
42574
+ async function verifyEs256Jwt(jwt, trust) {
42478
42575
  const parts = jwt.split(".");
42479
42576
  if (parts.length !== 3) return { valid: false, payload: null };
42480
42577
  const [h, p, s] = parts;
42578
+ let candidates = Array.isArray(trust) ? trust : [trust];
42579
+ if (Array.isArray(trust)) {
42580
+ try {
42581
+ const kid = JSON.parse(new TextDecoder().decode(b64urlToBytes(h))).kid;
42582
+ if (typeof kid === "string") candidates = candidates.filter((k) => k.kid === kid);
42583
+ } catch {
42584
+ return { valid: false, payload: null };
42585
+ }
42586
+ }
42481
42587
  let valid = false;
42482
- try {
42483
- const key = await crypto.subtle.importKey("jwk", publicJwk, { name: "ECDSA", namedCurve: "P-256" }, false, ["verify"]);
42484
- valid = await crypto.subtle.verify({ name: "ECDSA", hash: "SHA-256" }, key, b64urlToBytes(s), new TextEncoder().encode(`${h}.${p}`));
42485
- } catch {
42486
- valid = false;
42588
+ for (const publicJwk of candidates) {
42589
+ try {
42590
+ const key = await crypto.subtle.importKey("jwk", publicJwk, { name: "ECDSA", namedCurve: "P-256" }, false, ["verify"]);
42591
+ valid = await crypto.subtle.verify({ name: "ECDSA", hash: "SHA-256" }, key, b64urlToBytes(s), new TextEncoder().encode(`${h}.${p}`));
42592
+ } catch {
42593
+ valid = false;
42594
+ }
42595
+ if (valid) break;
42487
42596
  }
42488
42597
  if (!valid) return { valid: false, payload: null };
42489
42598
  try {
@@ -42520,10 +42629,21 @@ function extractRaw(payload) {
42520
42629
  if (typeof baseHash !== "string" || !HEX64.test(baseHash)) return void 0;
42521
42630
  return { baseHash };
42522
42631
  }
42632
+ var MAX_LIFETIME_S = 60;
42633
+ var MAX_SKEW_S = 60;
42634
+ function lifetimeProblem(payload, nowSec) {
42635
+ const iat = payload.iat, exp = payload.exp;
42636
+ if (typeof iat !== "number" || typeof exp !== "number") return "missing iat/exp";
42637
+ if (iat > nowSec + MAX_SKEW_S) return "issued in the future";
42638
+ if (exp - iat > MAX_LIFETIME_S) return "lifetime too long";
42639
+ return null;
42640
+ }
42523
42641
  async function verifyCapability(jws, opts) {
42524
42642
  const { valid, payload } = await verifyEs256Jwt(jws, opts.publicJwk);
42525
42643
  if (!valid || !payload) return { ok: false, reason: "bad signature" };
42526
42644
  if (payload.aud !== "norc-device-write") return { ok: false, reason: "bad audience" };
42645
+ const lp = lifetimeProblem(payload, opts.nowSec);
42646
+ if (lp) return { ok: false, reason: lp };
42527
42647
  if (payload.machine_id !== opts.machineId) return { ok: false, reason: "wrong machine" };
42528
42648
  const exp = typeof payload.exp === "number" ? payload.exp : 0;
42529
42649
  if (opts.nowSec > exp) return { ok: false, reason: "expired" };
@@ -42538,6 +42658,8 @@ async function verifyExecuteCapability(jws, opts) {
42538
42658
  const { valid, payload } = await verifyEs256Jwt(jws, opts.publicJwk);
42539
42659
  if (!valid || !payload) return { ok: false, reason: "bad signature" };
42540
42660
  if (payload.aud !== "norc-device-execute") return { ok: false, reason: "bad audience" };
42661
+ const lp = lifetimeProblem(payload, opts.nowSec);
42662
+ if (lp) return { ok: false, reason: lp };
42541
42663
  if (payload.machine_id !== opts.machineId) return { ok: false, reason: "wrong machine" };
42542
42664
  if (payload.job_id !== opts.jobId) return { ok: false, reason: "wrong job" };
42543
42665
  const exp = typeof payload.exp === "number" ? payload.exp : 0;
@@ -42547,12 +42669,6 @@ async function verifyExecuteCapability(jws, opts) {
42547
42669
  return { ok: true, nonce, nonceExp: exp };
42548
42670
  }
42549
42671
 
42550
- // ../../packages/bridge/src/text-hash.ts
42551
- async function sha256Hex(text) {
42552
- const buf = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
42553
- return [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, "0")).join("");
42554
- }
42555
-
42556
42672
  // ../../packages/bridge/src/raw-guard.ts
42557
42673
  var MAX_CRONTAB_BYTES = 65536;
42558
42674
  var MAX_CRONTAB_LINES = 1e3;
@@ -42572,6 +42688,7 @@ function validateRawCrontab(contents) {
42572
42688
 
42573
42689
  // ../../packages/bridge/src/write-intent.ts
42574
42690
  async function handleWriteIntent(msg, d) {
42691
+ 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" };
42575
42692
  const intentHash = await canonicalJobsHash(msg.jobs);
42576
42693
  const v = await verifyCapability(msg.capability, {
42577
42694
  publicJwk: d.publicJwk,
@@ -42583,22 +42700,30 @@ async function handleWriteIntent(msg, d) {
42583
42700
  });
42584
42701
  if (!v.ok) return { applied: false, reason: v.reason };
42585
42702
  if (v.raw) return { applied: false, reason: "raw capability not valid for job-set write" };
42586
- if (!d.consentGranted()) {
42587
- const granted = await d.requestConsent();
42588
- if (!granted) return { applied: false, reason: "consent denied" };
42589
- }
42590
42703
  const now = new Date(d.nowSec() * 1e3).toISOString();
42591
- const jobs = msg.jobs.map((j) => ({ ...j, createdAt: now, updatedAt: now }));
42592
- let crontab = await d.readCrontab();
42704
+ let held = /* @__PURE__ */ new Set();
42705
+ if (d.heldJobIds) {
42706
+ try {
42707
+ held = await d.heldJobIds(msg.jobs);
42708
+ } catch {
42709
+ return { applied: false, reason: "could not check which jobs are held; retry" };
42710
+ }
42711
+ }
42712
+ const names = d.envNames ? await d.envNames(msg.jobs).catch(() => null) : null;
42713
+ const jobs = msg.jobs.filter((j) => !held.has(j.id)).map((j) => ({ ...j, createdAt: now, updatedAt: now, ...names ? { envNames: Object.hasOwn(names, j.id) ? names[j.id] : [] } : {} }));
42714
+ const base = await d.readCrontab();
42715
+ let crontab = base;
42593
42716
  if (v.adopt) {
42594
42717
  const adoptedJob = jobs.find((j) => j.id === v.adopt.jobId);
42595
42718
  if (adoptedJob) crontab = tagUnmanagedInCrontab(crontab, adoptedJob, v.adopt.occurrence);
42596
42719
  }
42597
42720
  const next = renderJobsToCrontab(crontab, jobs);
42598
- await d.writeCrontab(next);
42599
42721
  d.rememberNonce(v.nonce);
42722
+ if (!await d.requestConsent({ before: base, after: next, jobs: msg.jobs })) return { applied: false, reason: "consent denied" };
42723
+ if (await d.readCrontab() !== base) return { applied: false, reason: "crontab changed while waiting for consent; retry" };
42724
+ await d.writeCrontab(next);
42600
42725
  d.setGeneration(v.generation);
42601
- return { applied: true };
42726
+ return { applied: true, held: [...held] };
42602
42727
  }
42603
42728
 
42604
42729
  // ../../packages/bridge/src/raw-write-intent.ts
@@ -42623,7 +42748,9 @@ async function handleRawWriteIntent(msg, d) {
42623
42748
  }
42624
42749
  const granted = await d.requestRawConsent({
42625
42750
  beforeLines: current.split("\n").length,
42626
- afterLines: msg.contents.split("\n").length
42751
+ afterLines: msg.contents.split("\n").length,
42752
+ before: current,
42753
+ after: msg.contents
42627
42754
  });
42628
42755
  if (!granted) return { applied: false, reason: "consent denied" };
42629
42756
  const atWrite = await d.readCrontab();
@@ -42634,6 +42761,22 @@ async function handleRawWriteIntent(msg, d) {
42634
42761
  return { applied: true, nextHash: intentHash };
42635
42762
  }
42636
42763
 
42764
+ // ../../packages/bridge/src/step-up.ts
42765
+ var StepUpRequired = class extends Error {
42766
+ constructor(method) {
42767
+ super("step_up_required");
42768
+ this.method = method;
42769
+ }
42770
+ };
42771
+ var STEP_UP_MARKS = ["step_up_required", "AAL2_REQUIRED", "FRESH_AUTH_REQUIRED"];
42772
+ function stepUpMethodOf(e) {
42773
+ if (e instanceof StepUpRequired) return e.method;
42774
+ if (!e || typeof e !== "object") return null;
42775
+ const o = e;
42776
+ const hit = ["message", "hint", "details", "code", "error"].some((k) => typeof o[k] === "string" && STEP_UP_MARKS.some((m) => o[k].includes(m)));
42777
+ return hit ? o.method === "reauth" || o.hint === "reauth" ? "reauth" : "totp" : null;
42778
+ }
42779
+
42637
42780
  // ../../packages/bridge/src/crypto.ts
42638
42781
  var VERSION = 1;
42639
42782
  var ECDH = { name: "ECDH", namedCurve: "P-256" };
@@ -42788,6 +42931,26 @@ var SealedBridgeTransport = class {
42788
42931
  }
42789
42932
  };
42790
42933
 
42934
+ // ../../packages/bridge/src/capability-trust.ts
42935
+ var CAPABILITY_TRUST_LIST = [
42936
+ {
42937
+ kid: "09621c79-698f-4328-bdac-1c347546708e",
42938
+ status: "active",
42939
+ jwk: {
42940
+ kty: "EC",
42941
+ crv: "P-256",
42942
+ alg: "ES256",
42943
+ use: "sig",
42944
+ x: "yRbJAsSJpAtBBWIXUg_5tVi0n574uZjComtLR9O6Jwk",
42945
+ y: "dVHs6ZeMH10d6IypZgM2-Q9i18_bf_Jj8vsybRPX0Fk"
42946
+ }
42947
+ }
42948
+ // Pre-staged next key goes here as { kid, status: 'inactive', jwk: <public JWK> }.
42949
+ ];
42950
+ function activeTrustedKeys(list = CAPABILITY_TRUST_LIST) {
42951
+ return list.filter((e) => e.status === "active" && e.kid && e.jwk.kty === "EC" && e.jwk.crv === "P-256" && !("d" in e.jwk)).map((e) => ({ ...e.jwk, kid: e.kid }));
42952
+ }
42953
+
42791
42954
  // src/supabase-config.ts
42792
42955
  var DEFAULT_SUPABASE_URL = "https://eiuegfdaddrisfboijyy.supabase.co";
42793
42956
  var DEFAULT_SUPABASE_ANON_KEY = "sb_publishable_qGCC0eLvfmXwL86zA1SLHA_q8rFMCcG";
@@ -42798,9 +42961,13 @@ function supabaseUrl() {
42798
42961
  return checkedSupabaseUrl(process.env.NORC_SUPABASE_URL ?? DEFAULT_SUPABASE_URL);
42799
42962
  }
42800
42963
  var DEFAULT_VAULT_URL = "https://vault.norc.app";
42964
+ function vaultUrl() {
42965
+ return assertSecureUrl(process.env.NORC_VAULT_URL ?? DEFAULT_VAULT_URL, { allowLocalDev: process.env.NORC_ALLOW_INSECURE_LOCAL === "1" });
42966
+ }
42801
42967
 
42802
42968
  // src/config.ts
42803
42969
  var import_promises = require("node:fs/promises");
42970
+ var import_node_child_process = require("node:child_process");
42804
42971
  var import_node_os = require("node:os");
42805
42972
  var import_node_path = require("node:path");
42806
42973
 
@@ -42881,14 +43048,113 @@ function redactSensitiveOutput(text) {
42881
43048
  for (const [pattern, replacement] of SENSITIVE_REPLACEMENTS) out = out.replace(pattern, replacement);
42882
43049
  return out;
42883
43050
  }
43051
+ function matchStarts(hay, needle) {
43052
+ const m = needle.length;
43053
+ const out = [];
43054
+ if (!m || hay.length < m) return out;
43055
+ const fail = new Int32Array(m);
43056
+ for (let i = 1, k = 0; i < m; i++) {
43057
+ while (k && needle[i] !== needle[k]) k = fail[k - 1];
43058
+ if (needle[i] === needle[k]) k++;
43059
+ fail[i] = k;
43060
+ }
43061
+ for (let i = 0, k = 0; i < hay.length; i++) {
43062
+ while (k && hay[i] !== needle[k]) k = fail[k - 1];
43063
+ if (hay[i] === needle[k]) k++;
43064
+ if (k === m) {
43065
+ out.push(i - m + 1);
43066
+ k = fail[k - 1];
43067
+ }
43068
+ }
43069
+ return out;
43070
+ }
43071
+ var toUnits = (s) => {
43072
+ const u = new Uint16Array(s.length);
43073
+ for (let i = 0; i < s.length; i++) u[i] = s.charCodeAt(i);
43074
+ return u;
43075
+ };
43076
+ function scrubValues(text, values) {
43077
+ let reach;
43078
+ let hay;
43079
+ for (const v of new Set(values)) {
43080
+ if (v.length < 4) continue;
43081
+ hay ??= toUnits(text);
43082
+ for (const s2 of matchStarts(hay, toUnits(v))) {
43083
+ reach ??= new Int32Array(text.length);
43084
+ if (reach[s2] < s2 + v.length) reach[s2] = s2 + v.length;
43085
+ }
43086
+ }
43087
+ if (!reach) return text;
43088
+ let out = "";
43089
+ let pos = 0;
43090
+ let s = -1;
43091
+ let e = -1;
43092
+ for (let i = 0; i < reach.length; i++) {
43093
+ const re = reach[i];
43094
+ if (!re) continue;
43095
+ if (s >= 0 && i <= e) {
43096
+ if (re > e) e = re;
43097
+ continue;
43098
+ }
43099
+ if (s >= 0) {
43100
+ out += text.slice(pos, s) + "[redacted]";
43101
+ pos = e;
43102
+ }
43103
+ s = i;
43104
+ e = re;
43105
+ }
43106
+ return out + text.slice(pos, s) + "[redacted]" + text.slice(e);
43107
+ }
42884
43108
 
42885
43109
  // src/config.ts
43110
+ function replayFor(config, machineId) {
43111
+ const b = config.bridge ??= {};
43112
+ const by = b.byMachine ??= {};
43113
+ if (b.generation !== void 0 || b.nonces !== void 0) {
43114
+ by[machineId] ??= { generation: b.generation ?? 0, nonces: b.nonces ?? [] };
43115
+ delete b.generation;
43116
+ delete b.nonces;
43117
+ }
43118
+ return by[machineId] ??= { generation: 0, nonces: [] };
43119
+ }
43120
+ function windowsOwnerOnlyAclArgs(dir, user) {
43121
+ return [dir, "/inheritance:r", "/grant:r", `${user}:(OI)(CI)F`];
43122
+ }
43123
+ function windowsOwnerOnlyDirAclSteps(dir, user) {
43124
+ return [[dir, "/reset"], windowsOwnerOnlyAclArgs(dir, user)];
43125
+ }
43126
+ function windowsOwnerOnlyFileAclSteps(file, user) {
43127
+ return [[file, "/reset"], [file, "/inheritance:r", "/grant:r", `${user}:F`]];
43128
+ }
43129
+ var defaultExec = (cmd, args, cb) => (0, import_node_child_process.execFile)(cmd, args, (err) => cb(err));
43130
+ function icacls(args, exec) {
43131
+ return new Promise((resolve, reject) => {
43132
+ exec("icacls", args, (err) => err ? reject(new Error(`icacls failed, refusing to write credentials: ${err.message}`)) : resolve());
43133
+ });
43134
+ }
43135
+ async function restrictWindowsAcl(dir, file, opts = {}) {
43136
+ if ((opts.platform ?? process.platform) !== "win32") return;
43137
+ const exec = opts.exec ?? defaultExec;
43138
+ const user = opts.user ?? (0, import_node_os.userInfo)().username;
43139
+ for (const step of windowsOwnerOnlyDirAclSteps(dir, user)) await icacls(step, exec);
43140
+ if (await (0, import_promises.access)(file).then(() => true, () => false)) {
43141
+ for (const step of windowsOwnerOnlyFileAclSteps(file, user)) await icacls(step, exec);
43142
+ }
43143
+ }
42886
43144
  function configPath() {
42887
43145
  return (0, import_node_path.join)((0, import_node_os.homedir)(), ".config", "norc", "config.json");
42888
43146
  }
43147
+ async function loadConfigStrict(path = configPath()) {
43148
+ try {
43149
+ return JSON.parse(await (0, import_promises.readFile)(path, "utf8"));
43150
+ } catch (e) {
43151
+ if (e.code === "ENOENT") return {};
43152
+ throw e;
43153
+ }
43154
+ }
42889
43155
  async function loadConfig(path = configPath()) {
42890
43156
  try {
42891
- const config = JSON.parse(await (0, import_promises.readFile)(path, "utf8"));
43157
+ const config = await loadConfigStrict(path);
42892
43158
  debugLog("config: loaded", path, "\u2014 has session:", Boolean(config.session), "has device:", Boolean(config.device));
42893
43159
  return config;
42894
43160
  } catch (e) {
@@ -42896,24 +43162,93 @@ async function loadConfig(path = configPath()) {
42896
43162
  return {};
42897
43163
  }
42898
43164
  }
42899
- async function saveConfig(config, path = configPath()) {
42900
- const dir = (0, import_node_path.join)(path, "..");
42901
- await (0, import_promises.mkdir)(dir, { recursive: true, mode: 448 });
42902
- await (0, import_promises.chmod)(dir, 448);
42903
- await (0, import_promises.chmod)(path, 384).catch((e) => {
42904
- if (e.code !== "ENOENT") throw e;
43165
+ async function refreshRemote(config, path = configPath()) {
43166
+ try {
43167
+ const disk = JSON.parse(await (0, import_promises.readFile)(path, "utf8"));
43168
+ config.remote = disk.remote;
43169
+ } catch {
43170
+ config.remote = void 0;
43171
+ }
43172
+ }
43173
+ var LOCK_STALE_MS = 1e4;
43174
+ var LOCK_WAIT_MS = 5e3;
43175
+ async function withConfigLock(path, fn) {
43176
+ const lock = `${path}.lock`;
43177
+ await (0, import_promises.mkdir)((0, import_node_path.join)(path, ".."), { recursive: true, mode: 448 });
43178
+ const deadline = Date.now() + LOCK_WAIT_MS;
43179
+ for (; ; ) {
43180
+ try {
43181
+ await (0, import_promises.mkdir)(lock);
43182
+ break;
43183
+ } catch (e) {
43184
+ if (e.code !== "EEXIST") throw e;
43185
+ const age = await (0, import_promises.stat)(lock).then((st) => Date.now() - st.mtimeMs).catch(() => 0);
43186
+ if (age > LOCK_STALE_MS) {
43187
+ await (0, import_promises.rm)(lock, { recursive: true, force: true });
43188
+ continue;
43189
+ }
43190
+ if (Date.now() > deadline) throw new Error("config is locked by another norc process; try again");
43191
+ await new Promise((r) => setTimeout(r, 25));
43192
+ }
43193
+ }
43194
+ try {
43195
+ return await fn();
43196
+ } finally {
43197
+ await (0, import_promises.rm)(lock, { recursive: true, force: true });
43198
+ }
43199
+ }
43200
+ async function sweepConfigTemps(path = configPath(), minAgeMs = 6e4) {
43201
+ const base = (0, import_node_path.basename)(path).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
43202
+ const re = new RegExp(`^${base}\\.\\d+\\.\\d+\\.tmp$`);
43203
+ const dir = (0, import_node_path.dirname)(path);
43204
+ for (const n of (await (0, import_promises.readdir)(dir).catch(() => [])).filter((x) => re.test(x))) {
43205
+ try {
43206
+ const f = (0, import_node_path.join)(dir, n);
43207
+ const st = await (0, import_promises.lstat)(f);
43208
+ if (st.isDirectory() || minAgeMs > 0 && Date.now() - st.mtimeMs < minAgeMs) continue;
43209
+ await (0, import_promises.rm)(f, { force: true });
43210
+ } catch {
43211
+ }
43212
+ }
43213
+ }
43214
+ async function saveConfig(config, path, opts) {
43215
+ path ??= configPath();
43216
+ const file = path;
43217
+ await withConfigLock(file, async () => {
43218
+ const disk = await loadConfigStrict(file);
43219
+ for (const k of opts.keys) delete disk[k];
43220
+ for (const k of opts.keys) if (config[k] !== void 0) Object.assign(disk, { [k]: config[k] });
43221
+ config = disk;
43222
+ const dir = (0, import_node_path.join)(path, "..");
43223
+ await (0, import_promises.mkdir)(dir, { recursive: true, mode: 448 });
43224
+ await (0, import_promises.chmod)(dir, 448);
43225
+ await restrictWindowsAcl(dir, path);
43226
+ await (0, import_promises.chmod)(path, 384).catch((e) => {
43227
+ if (e.code !== "ENOENT") throw e;
43228
+ });
43229
+ await sweepConfigTemps(path, opts.sweepAll ? 0 : 6e4);
43230
+ const tmp = `${path}.${process.pid}.${Date.now()}.tmp`;
43231
+ try {
43232
+ await (0, import_promises.writeFile)(tmp, JSON.stringify(config, null, 2), { mode: 384 });
43233
+ await (0, import_promises.chmod)(tmp, 384);
43234
+ await (0, import_promises.rename)(tmp, path);
43235
+ } catch (e) {
43236
+ await (0, import_promises.rm)(tmp, { force: true }).catch(() => {
43237
+ });
43238
+ throw e;
43239
+ }
43240
+ await (0, import_promises.chmod)(path, 384);
43241
+ await restrictWindowsAcl(dir, path);
43242
+ debugLog("config: saved", path, "\u2014 has session:", Boolean(config.session), "has device:", Boolean(config.device));
42905
43243
  });
42906
- await (0, import_promises.writeFile)(path, JSON.stringify(config, null, 2), { mode: 384 });
42907
- await (0, import_promises.chmod)(path, 384);
42908
- debugLog("config: saved", path, "\u2014 has session:", Boolean(config.session), "has device:", Boolean(config.device));
42909
43244
  }
42910
43245
 
42911
43246
  // src/crontab-io.ts
42912
- var import_node_child_process = require("node:child_process");
43247
+ var import_node_child_process2 = require("node:child_process");
42913
43248
  var systemCrontabIo = {
42914
43249
  read() {
42915
43250
  return new Promise((resolve, reject) => {
42916
- (0, import_node_child_process.execFile)("crontab", ["-l"], (err, stdout, stderr) => {
43251
+ (0, import_node_child_process2.execFile)("crontab", ["-l"], (err, stdout, stderr) => {
42917
43252
  if (err) {
42918
43253
  if (/no crontab/i.test(stderr)) return resolve("");
42919
43254
  return reject(new Error(stderr.trim() || err.message));
@@ -42924,7 +43259,7 @@ var systemCrontabIo = {
42924
43259
  },
42925
43260
  write(contents) {
42926
43261
  return new Promise((resolve, reject) => {
42927
- const child = (0, import_node_child_process.execFile)("crontab", ["-"], { timeout: 15e3 }, (err, _stdout, stderr) => {
43262
+ const child = (0, import_node_child_process2.execFile)("crontab", ["-"], { timeout: 15e3 }, (err, _stdout, stderr) => {
42928
43263
  if (err) return reject(new Error(stderr.trim() || err.message));
42929
43264
  resolve();
42930
43265
  });
@@ -42951,6 +43286,9 @@ async function verifyLogin(client, email, code) {
42951
43286
  };
42952
43287
  }
42953
43288
 
43289
+ // src/commands/pair.ts
43290
+ var import_node_os3 = require("node:os");
43291
+
42954
43292
  // src/host-info.ts
42955
43293
  var import_node_os2 = require("node:os");
42956
43294
  function normalizeArch(raw) {
@@ -43001,10 +43339,12 @@ async function runPairing(client, onProgress, opts = {}) {
43001
43339
  hostname: info.hostname,
43002
43340
  network_name: info.networkName,
43003
43341
  ip_address: info.ipAddress,
43004
- cpu_arch: info.cpuArch
43342
+ cpu_arch: info.cpuArch,
43343
+ os: `${(0, import_node_os3.platform)()} ${(0, import_node_os3.release)()}`
43344
+ // shown to the approver in pair_preview (AZ-011)
43005
43345
  });
43006
43346
  if (error || !data?.[0]) {
43007
- onProgress({ phase: "error", message: error?.message ?? "start failed" });
43347
+ onProgress({ phase: "error", message: isPairRateLimited(error) ? PAIR_RATE_LIMITED_MESSAGE : error?.message ?? "start failed" });
43008
43348
  return;
43009
43349
  }
43010
43350
  const { code, poll_secret } = data[0];
@@ -43032,13 +43372,13 @@ async function runPairing(client, onProgress, opts = {}) {
43032
43372
  }
43033
43373
 
43034
43374
  // src/commands/pair-key.ts
43035
- async function pairWithApiKey(fetchImpl, vaultUrl, apiKey, hostname2) {
43036
- const url = `${vaultUrl}/api/v1/machines`;
43037
- debugLog("POST", url, { authorization: `Bearer ${redactSecret(apiKey)}`, hostname: hostname2 });
43375
+ async function pairWithApiKey(fetchImpl, vaultUrl2, apiKey, hostname3) {
43376
+ const url = `${vaultUrl2}/api/v1/machines`;
43377
+ debugLog("POST", url, { authorization: `Bearer ${redactSecret(apiKey)}`, hostname: hostname3 });
43038
43378
  const res = await fetchImpl(url, {
43039
43379
  method: "POST",
43040
43380
  headers: { authorization: `Bearer ${apiKey}`, "content-type": "application/json" },
43041
- body: JSON.stringify({ hostname: hostname2 })
43381
+ body: JSON.stringify({ hostname: hostname3 })
43042
43382
  });
43043
43383
  const rawText = await res.text().catch(() => "");
43044
43384
  let body;
@@ -43127,14 +43467,53 @@ async function listJobs(io) {
43127
43467
  return jobsOf(parseCrontab(await io.read()));
43128
43468
  }
43129
43469
  async function addJob(io, schedule, command, name) {
43470
+ const job = newJob(schedule, command, name);
43471
+ await appendJob(io, job);
43472
+ return job;
43473
+ }
43474
+ function newJob(schedule, command, name) {
43130
43475
  const errors = validateCron(schedule);
43131
43476
  if (errors.length > 0) throw new Error(`invalid schedule: ${errors.map((e) => e.message).join("; ")}`);
43132
43477
  assertSafeField("command", command);
43133
43478
  if (name) assertSafeField("name", name);
43479
+ return { kind: "job", id: (0, import_node_crypto.randomUUID)(), name, schedule, command, enabled: true };
43480
+ }
43481
+ var wrapped = (job, envNames = []) => ({ ...job, command: wrapCommand(job.id, job.command, "posix", envNames) });
43482
+ async function appendJob(io, job, envNames = []) {
43134
43483
  const entries = parseCrontab(await io.read());
43135
- const job = { kind: "job", id: (0, import_node_crypto.randomUUID)(), name, schedule, command, enabled: true };
43136
- entries.push({ ...job, command: wrapCommand(job.id, command) });
43484
+ entries.push(wrapped(job, envNames));
43137
43485
  await io.write(renderCrontab(entries));
43486
+ }
43487
+ var ENV_NAME_RE2 = /^[A-Z_][A-Z0-9_]{0,127}$/;
43488
+ function splitTrailingEnv(parts) {
43489
+ if (parts.at(-1) === "--env") throw new Error("--env needs a NAME");
43490
+ let end = parts.length;
43491
+ const envNames = [];
43492
+ while (end >= 2 && parts[end - 2] === "--env") {
43493
+ envNames.unshift(parts[end - 1]);
43494
+ end -= 2;
43495
+ }
43496
+ return { command: parts.slice(0, end).join(" "), envNames };
43497
+ }
43498
+ async function addJobWithEnv(io, schedule, command, envNames, deps, name) {
43499
+ for (const n of envNames) if (!ENV_NAME_RE2.test(n)) throw new Error(`invalid env name: ${n}`);
43500
+ await deps.prepare();
43501
+ const job = newJob(schedule, command, name);
43502
+ let step = "syncing the job to the cloud";
43503
+ try {
43504
+ await deps.sync(wrapped(job, envNames));
43505
+ step = "binding env vars";
43506
+ await deps.bind(job.id, envNames);
43507
+ } catch (e) {
43508
+ const why = `${step} failed (${e instanceof Error ? e.message : String(e)})`;
43509
+ try {
43510
+ await deps.sync();
43511
+ } catch {
43512
+ throw new Error(`${why}; the job was not added to the crontab, and its cloud copy clears on the next sync.`);
43513
+ }
43514
+ throw new Error(`${why}; the job was not added. Fix the problem and run the command again.`);
43515
+ }
43516
+ await appendJob(io, job, envNames);
43138
43517
  return job;
43139
43518
  }
43140
43519
  async function withJob(io, id, fn) {
@@ -43156,6 +43535,236 @@ function setEnabled(io, id, enabled2) {
43156
43535
  return withJob(io, id, (e) => ({ ...e, enabled: enabled2 }));
43157
43536
  }
43158
43537
 
43538
+ // src/commands/env.ts
43539
+ var NAME_RE = /^[A-Z_][A-Z0-9_]{0,127}$/;
43540
+ var MAX_ROWS = 10;
43541
+ var MAX_NA = 3;
43542
+ var USAGE = "usage: norc env <ls|set NAME|archive NAME [--yes]|restore NAME|rm NAME [--yes]>";
43543
+ function impactText(verb, name, rows) {
43544
+ const machines = new Set(rows.map((r) => r.machine_id)).size;
43545
+ const lines = [
43546
+ `${verb} \`${name}\` will break ${rows.length} job${rows.length === 1 ? "" : "s"} on ${machines} machine${machines === 1 ? "" : "s"}. They will fail on their next run until you restore it or unbind it.`,
43547
+ ...rows.slice(0, MAX_ROWS).map((r) => ` ${r.job_name} \xB7 ${r.machine_name}`)
43548
+ ];
43549
+ if (rows.length > MAX_ROWS) lines.push(` and ${rows.length - MAX_ROWS} more`);
43550
+ return lines.join("\n");
43551
+ }
43552
+ function notAffectedText(rows) {
43553
+ return [
43554
+ "Not affected \xB7 archived jobs",
43555
+ ...rows.slice(0, MAX_NA).map((r) => ` ${r.job_name} \xB7 ${r.machine_name}`),
43556
+ ...rows.length > MAX_NA ? [` and ${rows.length - MAX_NA} more`] : []
43557
+ ].join("\n");
43558
+ }
43559
+ async function cmdEnv(args, d) {
43560
+ const yes = args.includes("--yes");
43561
+ const [sub, ...rest] = args.filter((a) => a !== "--yes");
43562
+ try {
43563
+ if (sub === "ls" && rest.length === 0) return await ls(d);
43564
+ if (sub && ["set", "archive", "restore", "rm"].includes(sub)) {
43565
+ if (rest.length !== 1) {
43566
+ d.err(sub === "set" && rest.length > 1 ? 'refusing a value on the command line (it lands in shell history). Pipe it in: echo "$VALUE" | norc env set NAME' : USAGE);
43567
+ return 2;
43568
+ }
43569
+ const name = rest[0];
43570
+ if (!NAME_RE.test(name)) {
43571
+ d.err("invalid name: use A-Z, 0-9 and _, not starting with a digit (max 128)");
43572
+ return 2;
43573
+ }
43574
+ if (sub === "set") return await set(name, d);
43575
+ const v = (await d.listVars()).find((x) => x.name === name);
43576
+ if (!v) {
43577
+ d.err(`no environment variable named ${name}`);
43578
+ return 1;
43579
+ }
43580
+ if (sub === "restore") return await act(d, "restore_env_var", v, `restored ${name}`);
43581
+ return await destructive(sub, name, v, yes, d);
43582
+ }
43583
+ d.err(USAGE);
43584
+ return 2;
43585
+ } catch (e) {
43586
+ d.err(e instanceof Error ? e.message : String(e));
43587
+ return 1;
43588
+ }
43589
+ }
43590
+ async function ls(d) {
43591
+ const [vars, bound] = await Promise.all([d.listVars(), d.bindingNames()]);
43592
+ const counts2 = /* @__PURE__ */ new Map();
43593
+ for (const n of bound) counts2.set(n, (counts2.get(n) ?? 0) + 1);
43594
+ if (vars.length === 0) d.out("no environment variables.");
43595
+ for (const v of [...vars].sort((a, b) => a.name.localeCompare(b.name))) {
43596
+ d.out(`${v.name} ${v.archived ? "archived" : "active "} ${counts2.get(v.name) ?? 0} jobs`);
43597
+ }
43598
+ const plan = await d.plan?.().catch(() => null);
43599
+ if (plan) {
43600
+ d.err(`${envVarUsageLabel(plan, vars.length)} (${plan.charAt(0).toUpperCase() + plan.slice(1)} plan)`);
43601
+ const full = envVarLimitMessage(plan, vars.length);
43602
+ if (full) d.err(full);
43603
+ }
43604
+ return 0;
43605
+ }
43606
+ async function set(name, d) {
43607
+ const existing = (await d.listVars()).find((x) => x.name === name);
43608
+ if (existing?.archived) {
43609
+ d.err(`${name} is archived; restore it first (norc env restore ${name})`);
43610
+ return 1;
43611
+ }
43612
+ const value = await d.readSecret(`value for ${name} (hidden): `);
43613
+ if (!value) {
43614
+ d.err("empty value, nothing saved");
43615
+ return 1;
43616
+ }
43617
+ if (value.includes("\0")) {
43618
+ d.err("value contains a NUL byte, which a command cannot receive; nothing saved");
43619
+ return 1;
43620
+ }
43621
+ const res = existing ? await d.write({ action: "set_value", id: existing.id, value }) : await d.write({ action: "create", name, value });
43622
+ if (res.status >= 200 && res.status < 300) {
43623
+ d.out(`${existing ? "updated" : "created"} ${name}`);
43624
+ return 0;
43625
+ }
43626
+ if (res.status === 403 && res.body.error === "plan_limit_reached") d.err("plan limit reached: archive or delete a variable, or upgrade your plan");
43627
+ else if (res.status === 409) d.err(`${name} already exists`);
43628
+ else d.err(`could not save ${name} (${res.body.error ?? `HTTP ${res.status}`})`);
43629
+ return 1;
43630
+ }
43631
+ async function act(d, fn, v, done) {
43632
+ const e = await d.rpc(fn, v.id);
43633
+ if (e) {
43634
+ d.err(e);
43635
+ return 1;
43636
+ }
43637
+ d.out(done);
43638
+ return 0;
43639
+ }
43640
+ async function destructive(sub, name, v, yes, d) {
43641
+ const rm5 = sub === "rm";
43642
+ const all = await d.impact(name);
43643
+ const rows = all.filter((r) => !r.job_archived);
43644
+ const na = all.filter((r) => r.job_archived);
43645
+ if (rows.length > 0) d.out(impactText(rm5 ? "Deleting" : "Archiving", name, rows));
43646
+ if (na.length > 0) d.out(notAffectedText(na));
43647
+ if (!yes) {
43648
+ if (!d.isTTY) {
43649
+ if (rm5 || rows.length > 0) {
43650
+ d.err("refusing without --yes on a non-interactive terminal");
43651
+ return 1;
43652
+ }
43653
+ } else if (rm5) {
43654
+ const answer = await d.readLine(`type ${name} to delete it permanently: `);
43655
+ if (answer === null || answer.trim() !== name) {
43656
+ d.err("cancelled");
43657
+ return 1;
43658
+ }
43659
+ } else {
43660
+ const answer = await d.readLine(`archive ${name}? [y/N] `);
43661
+ if (answer === null || !/^y(es)?$/i.test(answer.trim())) {
43662
+ d.err("cancelled");
43663
+ return 1;
43664
+ }
43665
+ }
43666
+ }
43667
+ if (!rm5) return act(d, "archive_env_var", v, `archived ${name}`);
43668
+ return remove2(name, v, d);
43669
+ }
43670
+ async function remove2(name, v, d) {
43671
+ const fallback = `Deleting a variable needs a fresh sign-in. Delete it in the web vault (Environment), or archive it with \`norc env archive ${name}\`.`;
43672
+ let e = await d.deleteVar(v.id);
43673
+ const method = e && stepUpMethodOf(e);
43674
+ if (e && method) {
43675
+ if (!d.isTTY || !await stepUp(method, d)) {
43676
+ d.err(fallback);
43677
+ return 1;
43678
+ }
43679
+ e = await d.deleteVar(v.id);
43680
+ if (e && stepUpMethodOf(e)) {
43681
+ d.err(fallback);
43682
+ return 1;
43683
+ }
43684
+ }
43685
+ if (e) {
43686
+ d.err(e.message);
43687
+ return 1;
43688
+ }
43689
+ d.out(`deleted ${name}`);
43690
+ return 0;
43691
+ }
43692
+ async function stepUp(method, d) {
43693
+ const ask = (q) => d.readSecret(q).then((c) => c.trim(), () => "");
43694
+ if (method === "totp") {
43695
+ const code = await ask("6-digit code from your authenticator app (hidden): ");
43696
+ if (!code) return false;
43697
+ const e2 = await d.verifyTotp(code);
43698
+ if (e2) d.err(e2);
43699
+ return !e2;
43700
+ }
43701
+ const started = await d.reauth({ action: "start" });
43702
+ if (started) {
43703
+ d.err(started);
43704
+ return false;
43705
+ }
43706
+ d.out("To confirm it is you, we emailed a one-time code to your account address.");
43707
+ const token = await ask("code from your email (hidden): ");
43708
+ if (!token) return false;
43709
+ const e = await d.reauth({ action: "verify", method: "email_otp", token });
43710
+ if (e) d.err(e);
43711
+ return !e;
43712
+ }
43713
+
43714
+ // src/commands/env-auth.ts
43715
+ function makeStepUpDeps(sb, fetchImpl, url, anon, saveSession2) {
43716
+ return {
43717
+ verifyTotp: async (code) => {
43718
+ const { data, error } = await sb.auth.mfa.listFactors();
43719
+ const factor = data?.totp[0];
43720
+ if (error || !factor) return "Could not start the 2FA check.";
43721
+ const { error: e } = await sb.auth.mfa.challengeAndVerify({ factorId: factor.id, code });
43722
+ if (e) return "That code did not work.";
43723
+ try {
43724
+ await saveSession2();
43725
+ } catch {
43726
+ return "Could not save the new sign-in on this machine.";
43727
+ }
43728
+ return null;
43729
+ },
43730
+ reauth: async (body) => {
43731
+ const { data: { session } } = await sb.auth.getSession();
43732
+ try {
43733
+ const res = await fetchImpl(`${url}/functions/v1/reauth`, {
43734
+ method: "POST",
43735
+ headers: { "Content-Type": "application/json", apikey: anon, Authorization: `Bearer ${session?.access_token ?? ""}` },
43736
+ body: JSON.stringify(body)
43737
+ });
43738
+ if (res.ok) return null;
43739
+ if (res.status === 429) return "Too many attempts. Wait a minute and try again.";
43740
+ return res.status >= 400 && res.status < 500 ? "That did not work." : "Could not confirm right now.";
43741
+ } catch {
43742
+ return "Could not reach norc. Check your connection.";
43743
+ }
43744
+ }
43745
+ };
43746
+ }
43747
+
43748
+ // src/commands/read-value.ts
43749
+ async function readStdinValue(stdin) {
43750
+ const chunks = [];
43751
+ for await (const c of stdin) chunks.push(typeof c === "string" ? Buffer.from(c) : c);
43752
+ return Buffer.concat(chunks).toString("utf8").replace(/\r?\n$/, "");
43753
+ }
43754
+
43755
+ // src/machines.ts
43756
+ async function syncJobs(sb, entries) {
43757
+ const jobs = jobsOf(entries).filter((j) => typeof j.id === "string").map((j) => ({
43758
+ id: j.id,
43759
+ name: j.name ?? "",
43760
+ schedule: j.schedule,
43761
+ command: j.command,
43762
+ enabled: j.enabled ?? true
43763
+ }));
43764
+ const { error } = await sb.rpc("sync_account_jobs", { p_jobs: jobs, p_authoritative_empty: true });
43765
+ if (error) throw new Error(error.message);
43766
+ }
43767
+
43159
43768
  // src/commands/gitops.ts
43160
43769
  var import_yaml = __toESM(require_dist());
43161
43770
  var CONTROL4 = /[\r\n\0]/;
@@ -43285,10 +43894,10 @@ async function getJson(fetchImpl, url, apiKey) {
43285
43894
  if (!Array.isArray(body)) return { ok: false, message: "malformed response from vault API" };
43286
43895
  return { ok: true, data: body };
43287
43896
  }
43288
- async function fetchLiveJobs(fetchImpl, vaultUrl, apiKey) {
43289
- const machinesResult = await getJson(fetchImpl, `${vaultUrl}/api/v1/machines`, apiKey);
43897
+ async function fetchLiveJobs(fetchImpl, vaultUrl2, apiKey) {
43898
+ const machinesResult = await getJson(fetchImpl, `${vaultUrl2}/api/v1/machines`, apiKey);
43290
43899
  if (!machinesResult.ok) return machinesResult;
43291
- const jobsResult = await getJson(fetchImpl, `${vaultUrl}/api/v1/jobs`, apiKey);
43900
+ const jobsResult = await getJson(fetchImpl, `${vaultUrl2}/api/v1/jobs`, apiKey);
43292
43901
  if (!jobsResult.ok) return jobsResult;
43293
43902
  const machineNameById = new Map(machinesResult.data.map((m) => [m.id, m.name]));
43294
43903
  const jobs = [];
@@ -43299,7 +43908,7 @@ async function fetchLiveJobs(fetchImpl, vaultUrl, apiKey) {
43299
43908
  }
43300
43909
  return { ok: true, jobs, machines: machinesResult.data };
43301
43910
  }
43302
- async function applySync(fetchImpl, vaultUrl, apiKey, diff, machineNameToId) {
43911
+ async function applySync(fetchImpl, vaultUrl2, apiKey, diff, machineNameToId) {
43303
43912
  const creates = diff.creates.map((c) => ({
43304
43913
  key: `${c.machineName}/${c.jobName}`,
43305
43914
  machineId: machineNameToId.get(c.machineName),
@@ -43314,7 +43923,7 @@ async function applySync(fetchImpl, vaultUrl, apiKey, diff, machineNameToId) {
43314
43923
  patch: { schedule: u.desired.schedule, command: u.desired.command, enabled: u.desired.enabled }
43315
43924
  }));
43316
43925
  const deletes = diff.deletes.map((d) => ({ key: `${d.machineName}/${d.jobName}`, id: d.id }));
43317
- const url = `${vaultUrl}/api/v1/jobs/sync`;
43926
+ const url = `${vaultUrl2}/api/v1/jobs/sync`;
43318
43927
  debugLog("POST", url, { authorization: `Bearer ${redactSecret(apiKey)}`, creates: creates.length, updates: updates.length, deletes: deletes.length });
43319
43928
  let res;
43320
43929
  try {
@@ -43430,22 +44039,22 @@ function tailRunsMessage() {
43430
44039
  }
43431
44040
 
43432
44041
  // src/child-env.ts
43433
- function withoutPkgEnv(command, platform = process.platform) {
43434
- return platform === "win32" ? `set "PKG_EXECPATH=" && ${command}` : `unset PKG_EXECPATH; ${command}`;
44042
+ function withoutPkgEnv(command, platform2 = process.platform) {
44043
+ return platform2 === "win32" ? `set "PKG_EXECPATH=" && ${command}` : `unset PKG_EXECPATH; ${command}`;
43435
44044
  }
43436
44045
 
43437
44046
  // src/commands/run.ts
43438
- var import_node_child_process3 = require("node:child_process");
44047
+ var import_node_child_process4 = require("node:child_process");
43439
44048
 
43440
44049
  // src/host-details.ts
43441
- var import_node_child_process2 = require("node:child_process");
44050
+ var import_node_child_process3 = require("node:child_process");
43442
44051
  var import_node_fs = require("node:fs");
43443
44052
  var import_node_crypto2 = require("node:crypto");
43444
- var import_node_os3 = require("node:os");
44053
+ var import_node_os4 = require("node:os");
43445
44054
  var import_node_path2 = require("node:path");
43446
44055
 
43447
44056
  // src/version.ts
43448
- var VERSION2 = "0.3.0";
44057
+ var VERSION2 = "0.3.1";
43449
44058
 
43450
44059
  // src/host-details.ts
43451
44060
  var ARCH = { x64: "x86_64", arm64: "arm64", ia32: "x86", arm: "arm" };
@@ -43464,21 +44073,21 @@ function windowsOsName(kernel, isClient) {
43464
44073
  }
43465
44074
  function windowsIsClient() {
43466
44075
  try {
43467
- const out = (0, import_node_child_process2.execFileSync)("powershell.exe", ["-NoProfile", "-Command", "(Get-CimInstance Win32_OperatingSystem).ProductType"], { encoding: "utf8", timeout: 4e3 }).trim();
44076
+ const out = (0, import_node_child_process3.execFileSync)("powershell.exe", ["-NoProfile", "-Command", "(Get-CimInstance Win32_OperatingSystem).ProductType"], { encoding: "utf8", timeout: 4e3 }).trim();
43468
44077
  return out === "1" ? true : out === "2" || out === "3" ? false : void 0;
43469
44078
  } catch {
43470
44079
  return void 0;
43471
44080
  }
43472
44081
  }
43473
- function osName(platform) {
43474
- if (platform === "linux") return osNameUncached(platform);
43475
- const file = (0, import_node_path2.join)((0, import_node_os3.homedir)(), ".config", "norc", `os-${platform}-${(0, import_node_crypto2.createHash)("sha1").update(`${(0, import_node_os3.release)()}|${(0, import_node_os3.version)()}`).digest("hex").slice(0, 12)}.txt`);
44082
+ function osName(platform2) {
44083
+ if (platform2 === "linux") return osNameUncached(platform2);
44084
+ 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`);
43476
44085
  try {
43477
44086
  const hit = (0, import_node_fs.readFileSync)(file, "utf8").trim();
43478
44087
  if (/^[\w .()+-]{1,64}$/.test(hit)) return hit;
43479
44088
  } catch {
43480
44089
  }
43481
- const name = osNameUncached(platform);
44090
+ const name = osNameUncached(platform2);
43482
44091
  if (name) {
43483
44092
  try {
43484
44093
  (0, import_node_fs.writeFileSync)(file, name);
@@ -43487,18 +44096,18 @@ function osName(platform) {
43487
44096
  }
43488
44097
  return name;
43489
44098
  }
43490
- function osNameUncached(platform) {
44099
+ function osNameUncached(platform2) {
43491
44100
  try {
43492
- if (platform === "linux") return linuxOsName((0, import_node_fs.readFileSync)("/etc/os-release", "utf8"));
43493
- if (platform === "darwin") return `macOS ${(0, import_node_child_process2.execFileSync)("sw_vers", ["-productVersion"], { encoding: "utf8", timeout: 2e3 }).trim()}`;
43494
- if (platform === "win32") return windowsOsName((0, import_node_os3.release)(), windowsIsClient());
44101
+ if (platform2 === "linux") return linuxOsName((0, import_node_fs.readFileSync)("/etc/os-release", "utf8"));
44102
+ if (platform2 === "darwin") return `macOS ${(0, import_node_child_process3.execFileSync)("sw_vers", ["-productVersion"], { encoding: "utf8", timeout: 2e3 }).trim()}`;
44103
+ if (platform2 === "win32") return windowsOsName((0, import_node_os4.release)(), windowsIsClient());
43495
44104
  } catch {
43496
44105
  }
43497
44106
  return void 0;
43498
44107
  }
43499
44108
  function bootedAt() {
43500
44109
  try {
43501
- return new Date(Math.round((Date.now() - (0, import_node_os3.uptime)() * 1e3) / 6e4) * 6e4).toISOString();
44110
+ return new Date(Math.round((Date.now() - (0, import_node_os4.uptime)() * 1e3) / 6e4) * 6e4).toISOString();
43502
44111
  } catch {
43503
44112
  return void 0;
43504
44113
  }
@@ -43509,8 +44118,95 @@ function hostDetails() {
43509
44118
  return cached;
43510
44119
  }
43511
44120
 
44121
+ // src/env-cache.ts
44122
+ var import_promises2 = require("node:fs/promises");
44123
+ var import_node_path3 = require("node:path");
44124
+ function envCachePath() {
44125
+ return (0, import_node_path3.join)((0, import_node_path3.dirname)(configPath()), "env");
44126
+ }
44127
+ async function tempLeftovers(path) {
44128
+ const re = new RegExp(`^${(0, import_node_path3.basename)(path).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\.\\d+\\.\\d+\\.tmp$`);
44129
+ 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));
44130
+ }
44131
+ async function writeEnvCache(body, path = envCachePath()) {
44132
+ const dir = (0, import_node_path3.dirname)(path);
44133
+ await (0, import_promises2.mkdir)(dir, { recursive: true, mode: 448 });
44134
+ await (0, import_promises2.chmod)(dir, 448);
44135
+ await restrictWindowsAcl(dir, path);
44136
+ for (const f of await tempLeftovers(path)) {
44137
+ const st = await (0, import_promises2.stat)(f).catch(() => null);
44138
+ if (st && Date.now() - st.mtimeMs > 6e4) await (0, import_promises2.rm)(f, { force: true }).catch(() => {
44139
+ });
44140
+ }
44141
+ const tmp = `${path}.${process.pid}.${Date.now()}.tmp`;
44142
+ try {
44143
+ await (0, import_promises2.writeFile)(tmp, JSON.stringify(body), { mode: 384 });
44144
+ await (0, import_promises2.chmod)(tmp, 384);
44145
+ await (0, import_promises2.rename)(tmp, path);
44146
+ } catch (e) {
44147
+ await (0, import_promises2.rm)(tmp, { force: true }).catch(() => {
44148
+ });
44149
+ throw e;
44150
+ }
44151
+ await (0, import_promises2.chmod)(path, 384);
44152
+ await restrictWindowsAcl(dir, path);
44153
+ }
44154
+ async function clearEnvCache(path = envCachePath()) {
44155
+ try {
44156
+ await (0, import_promises2.rm)(path, { force: true });
44157
+ let ok = true;
44158
+ for (const f of await tempLeftovers(path)) await (0, import_promises2.rm)(f, { force: true }).catch(() => {
44159
+ ok = false;
44160
+ });
44161
+ return ok;
44162
+ } catch {
44163
+ return false;
44164
+ }
44165
+ }
44166
+ var isObj = (x) => typeof x === "object" && x !== null && !Array.isArray(x);
44167
+ function parseEnvSyncBody(x) {
44168
+ if (!isObj(x) || !isObj(x.jobs) || !isObj(x.vars)) return null;
44169
+ for (const names of Object.values(x.jobs)) {
44170
+ if (!Array.isArray(names) || !names.every((n) => typeof n === "string")) return null;
44171
+ }
44172
+ for (const v of Object.values(x.vars)) {
44173
+ if (!isObj(v)) return null;
44174
+ if (v.state === "active") {
44175
+ if (typeof v.value !== "string") return null;
44176
+ } else if (v.state !== "archived" && v.state !== "missing" || "value" in v) return null;
44177
+ }
44178
+ const body = x;
44179
+ return {
44180
+ jobs: Object.fromEntries(Object.entries(body.jobs).map(([id, names]) => [id, names.filter((n) => ENV_NAME_RE.test(n))])),
44181
+ vars: Object.fromEntries(Object.entries(body.vars).filter(([n]) => ENV_NAME_RE.test(n)))
44182
+ };
44183
+ }
44184
+ async function readEnvCache(path = envCachePath()) {
44185
+ try {
44186
+ return parseEnvSyncBody(JSON.parse(await (0, import_promises2.readFile)(path, "utf8")));
44187
+ } catch {
44188
+ return null;
44189
+ }
44190
+ }
44191
+ function resolveJobEnv(body, jobId, required) {
44192
+ const names = [.../* @__PURE__ */ new Set([...required ?? [], ...body?.jobs[jobId] ?? []])].sort();
44193
+ if (names.length === 0) return { ok: true, env: {} };
44194
+ const env = {};
44195
+ for (const name of names) {
44196
+ const v = body?.vars[name];
44197
+ if (v?.state === "active" && v.value.includes("\0")) return { ok: false, message: `env ${name} has an invalid value` };
44198
+ if (v?.state === "active") env[name] = v.value;
44199
+ else if (v?.state === "archived") return { ok: false, message: `env ${name} is archived` };
44200
+ else if (!v && required?.includes(name)) return { ok: false, message: `env ${name} is unavailable (norc could not sync)` };
44201
+ else return { ok: false, message: `env ${name} not found` };
44202
+ }
44203
+ return { ok: true, env };
44204
+ }
44205
+
43512
44206
  // src/device-session.ts
43513
- async function deviceSession(supabaseUrl2, anonKey, signal, encPublicJwk) {
44207
+ var revoked = null;
44208
+ var revokedMint = () => revoked;
44209
+ async function deviceSession(supabaseUrl2, anonKey, signal, encPublicJwk, cachePath = envCachePath()) {
43514
44210
  const config = await loadConfig();
43515
44211
  const token = config.device?.deviceToken;
43516
44212
  if (!token) return null;
@@ -43531,8 +44227,16 @@ async function deviceSession(supabaseUrl2, anonKey, signal, encPublicJwk) {
43531
44227
  }),
43532
44228
  signal
43533
44229
  });
44230
+ if (res.status === 401 && (await res.json?.().catch(() => null))?.error === "invalid device token") {
44231
+ const before = await readEnvCache(cachePath);
44232
+ revoked = { body: before ?? revoked?.body ?? null };
44233
+ await clearEnvCache(cachePath);
44234
+ return null;
44235
+ }
43534
44236
  if (!res.ok) return null;
43535
- return await res.json();
44237
+ const session = await res.json();
44238
+ revoked = null;
44239
+ return session;
43536
44240
  } catch (e) {
43537
44241
  console.error("[norc bridge] device-session fetch failed:", e);
43538
44242
  return null;
@@ -43540,17 +44244,17 @@ async function deviceSession(supabaseUrl2, anonKey, signal, encPublicJwk) {
43540
44244
  }
43541
44245
 
43542
44246
  // src/run-queue.ts
43543
- var import_promises2 = require("node:fs/promises");
43544
- var import_node_os4 = require("node:os");
43545
- var import_node_path3 = require("node:path");
44247
+ var import_promises3 = require("node:fs/promises");
44248
+ var import_node_os5 = require("node:os");
44249
+ var import_node_path4 = require("node:path");
43546
44250
  var MAX_QUEUE_LENGTH = 500;
43547
44251
  function runQueuePath() {
43548
- return (0, import_node_path3.join)((0, import_node_os4.homedir)(), ".config", "norc", "run-queue.jsonl");
44252
+ return (0, import_node_path4.join)((0, import_node_os5.homedir)(), ".config", "norc", "run-queue.jsonl");
43549
44253
  }
43550
44254
  async function readQueue(path = runQueuePath()) {
43551
44255
  let text;
43552
44256
  try {
43553
- text = await (0, import_promises2.readFile)(path, "utf8");
44257
+ text = await (0, import_promises3.readFile)(path, "utf8");
43554
44258
  } catch {
43555
44259
  return [];
43556
44260
  }
@@ -43558,26 +44262,26 @@ async function readQueue(path = runQueuePath()) {
43558
44262
  }
43559
44263
  async function writeQueue(entries, path) {
43560
44264
  const tmp = `${path}.${process.pid}.tmp`;
43561
- await (0, import_promises2.writeFile)(tmp, entries.map((e) => JSON.stringify(e)).join("\n") + (entries.length ? "\n" : ""), "utf8");
43562
- await (0, import_promises2.rename)(tmp, path);
44265
+ await (0, import_promises3.writeFile)(tmp, entries.map((e) => JSON.stringify(e)).join("\n") + (entries.length ? "\n" : ""), "utf8");
44266
+ await (0, import_promises3.rename)(tmp, path);
43563
44267
  }
43564
- var LOCK_STALE_MS = 3e4;
44268
+ var LOCK_STALE_MS2 = 3e4;
43565
44269
  var LOCK_RETRY_MS = 25;
43566
44270
  var LOCK_ATTEMPTS = 40;
43567
44271
  async function withLock(path, fn) {
43568
44272
  const lockPath = `${path}.lock`;
43569
- await (0, import_promises2.mkdir)((0, import_node_path3.dirname)(path), { recursive: true });
44273
+ await (0, import_promises3.mkdir)((0, import_node_path4.dirname)(path), { recursive: true });
43570
44274
  let held = false;
43571
44275
  for (let i = 0; i < LOCK_ATTEMPTS; i++) {
43572
44276
  try {
43573
- const fh = await (0, import_promises2.open)(lockPath, "wx");
44277
+ const fh = await (0, import_promises3.open)(lockPath, "wx");
43574
44278
  await fh.close();
43575
44279
  held = true;
43576
44280
  break;
43577
44281
  } catch {
43578
44282
  try {
43579
- const { mtimeMs } = await (0, import_promises2.stat)(lockPath);
43580
- if (Date.now() - mtimeMs > LOCK_STALE_MS) await (0, import_promises2.rm)(lockPath, { force: true });
44283
+ const { mtimeMs } = await (0, import_promises3.stat)(lockPath);
44284
+ if (Date.now() - mtimeMs > LOCK_STALE_MS2) await (0, import_promises3.rm)(lockPath, { force: true });
43581
44285
  } catch {
43582
44286
  }
43583
44287
  await new Promise((r) => setTimeout(r, LOCK_RETRY_MS));
@@ -43587,7 +44291,7 @@ async function withLock(path, fn) {
43587
44291
  try {
43588
44292
  return await fn();
43589
44293
  } finally {
43590
- await (0, import_promises2.rm)(lockPath, { force: true }).catch(() => {
44294
+ await (0, import_promises3.rm)(lockPath, { force: true }).catch(() => {
43591
44295
  });
43592
44296
  }
43593
44297
  }
@@ -43617,10 +44321,50 @@ async function clearQueue(toRemove, path = runQueuePath()) {
43617
44321
  });
43618
44322
  }
43619
44323
 
44324
+ // src/commands/env-sync.ts
44325
+ async function pullEnv(fetchFn, session, timeoutMs, path, clear) {
44326
+ if (!session) return { body: null, written: false };
44327
+ try {
44328
+ const res = await fetchFn(`${supabaseUrl()}/functions/v1/device-env-sync`, {
44329
+ method: "POST",
44330
+ headers: { apikey: process.env.NORC_SUPABASE_ANON_KEY ?? DEFAULT_SUPABASE_ANON_KEY, Authorization: `Bearer ${session.token}` },
44331
+ signal: AbortSignal.timeout(timeoutMs)
44332
+ });
44333
+ if (res.status === 403) {
44334
+ const denied = await readEnvCache(path);
44335
+ await clear(path);
44336
+ return { body: null, written: false, denied };
44337
+ }
44338
+ if (!res.ok) return { body: null, written: false };
44339
+ const body = parseEnvSyncBody(await res.json());
44340
+ if (!body) return { body: null, written: false };
44341
+ const written = await writeEnvCache(body, path).then(() => true, () => false);
44342
+ return { body, written };
44343
+ } catch {
44344
+ return { body: null, written: false };
44345
+ }
44346
+ }
44347
+ async function pullEnvNames(fetchFn, session, timeoutMs, path = envCachePath()) {
44348
+ return (await pullEnv(fetchFn, session, timeoutMs, path, clearEnvCache)).body?.jobs ?? null;
44349
+ }
44350
+ var REFRESH_BUDGET_MS = 3e3;
44351
+ function createJobEnvLoader(getSession, path = envCachePath(), fetchFn = fetch, clear = clearEnvCache) {
44352
+ return async (jobId, envNames) => {
44353
+ const session = await getSession().catch(() => null);
44354
+ const pulled = await pullEnv(fetchFn, session, REFRESH_BUDGET_MS, path, clear);
44355
+ const { body } = pulled;
44356
+ const denied = pulled.denied !== void 0 ? pulled.denied : !session ? revokedMint()?.body : void 0;
44357
+ if (denied !== void 0 && ((denied?.jobs[jobId]?.length ?? 0) > 0 || (envNames?.length ?? 0) > 0)) return { ok: false, message: "this machine is no longer authorized to read env vars" };
44358
+ if (denied !== void 0) return { ok: true, env: {} };
44359
+ if (body) return resolveJobEnv(body, jobId);
44360
+ return resolveJobEnv(await readEnvCache(path), jobId, envNames);
44361
+ };
44362
+ }
44363
+
43620
44364
  // src/commands/run.ts
43621
44365
  var FLUSH_BATCH = 25;
43622
44366
  var FLUSH_BUDGET_MS = 2e4;
43623
- async function runWrapped(deps, jobId, command) {
44367
+ async function runWrapped(deps, jobId, command, envNames) {
43624
44368
  try {
43625
44369
  const queued = (await deps.readQueue()).slice(0, FLUSH_BATCH);
43626
44370
  const flushed = [];
@@ -43632,6 +44376,25 @@ async function runWrapped(deps, jobId, command) {
43632
44376
  if (flushed.length) await deps.clearQueue(flushed);
43633
44377
  } catch {
43634
44378
  }
44379
+ let jobEnv;
44380
+ try {
44381
+ jobEnv = await deps.loadJobEnv(jobId, envNames);
44382
+ } catch {
44383
+ jobEnv = { ok: false, message: "env could not be loaded" };
44384
+ }
44385
+ if (!jobEnv.ok) {
44386
+ const at = deps.now().toISOString();
44387
+ const failed = { jobId, exitCode: 1, startedAt: at, finishedAt: at, status: "failed", errorSnippet: jobEnv.message, outputSnippet: jobEnv.message };
44388
+ const ok = await deps.report(failed).catch(() => false);
44389
+ if (!ok) await deps.enqueueRun(failed).catch(() => {
44390
+ });
44391
+ return 1;
44392
+ }
44393
+ const env = jobEnv.env;
44394
+ const hasEnv = Object.keys(env).length > 0;
44395
+ const spawnIt = () => hasEnv ? deps.spawnCommand(command, env) : deps.spawnCommand(command);
44396
+ const secrets = Object.values(env);
44397
+ const clean2 = (t) => redactSensitiveOutput(scrubValues(t, secrets));
43635
44398
  let claimed = [];
43636
44399
  try {
43637
44400
  claimed = await deps.claimBackfills(jobId);
@@ -43640,10 +44403,10 @@ async function runWrapped(deps, jobId, command) {
43640
44403
  }
43641
44404
  for (const backfill of claimed) {
43642
44405
  const backfillStartedAt = deps.now().toISOString();
43643
- const { exitCode: backfillExitCode, stderrTail: backfillStderrTail, outputTail: backfillOutputTail } = await deps.spawnCommand(command);
44406
+ const { exitCode: backfillExitCode, stderrTail: backfillStderrTail, outputTail: backfillOutputTail } = await spawnIt();
43644
44407
  const backfillFinishedAt = deps.now().toISOString();
43645
- const backfillErrorSnippet = backfillExitCode !== 0 ? redactSensitiveOutput(backfillStderrTail.trim()) : "";
43646
- const backfillOutputSnippet = redactSensitiveOutput((backfillOutputTail ?? "").trim());
44408
+ const backfillErrorSnippet = backfillExitCode !== 0 ? clean2(backfillStderrTail.trim()) : "";
44409
+ const backfillOutputSnippet = clean2((backfillOutputTail ?? "").trim());
43647
44410
  const replayRun = {
43648
44411
  jobId,
43649
44412
  exitCode: backfillExitCode,
@@ -43663,10 +44426,10 @@ async function runWrapped(deps, jobId, command) {
43663
44426
  }
43664
44427
  }
43665
44428
  const startedAt = deps.now().toISOString();
43666
- const { exitCode, stderrTail, outputTail } = await deps.spawnCommand(command);
44429
+ const { exitCode, stderrTail, outputTail } = await spawnIt();
43667
44430
  const finishedAt = deps.now().toISOString();
43668
- const errorSnippet = exitCode !== 0 ? redactSensitiveOutput(stderrTail.trim()) : "";
43669
- const outputSnippet = redactSensitiveOutput((outputTail ?? "").trim());
44431
+ const errorSnippet = exitCode !== 0 ? clean2(stderrTail.trim()) : "";
44432
+ const outputSnippet = clean2((outputTail ?? "").trim());
43670
44433
  const run = {
43671
44434
  jobId,
43672
44435
  exitCode,
@@ -43689,33 +44452,75 @@ var STDERR_TAIL_BYTES = 4096;
43689
44452
  var OUTPUT_SNIPPET_MAX_CHARS = 4e3;
43690
44453
  var OUTPUT_SNIPPET_MAX_LINES = 20;
43691
44454
  var OUTPUT_TAIL_MAX_BYTES = OUTPUT_SNIPPET_MAX_CHARS * 4;
43692
- function decodeOutputTail(tail) {
43693
- const decoded = redactSensitiveOutput(tail.toString("utf8"));
44455
+ function scrubTail(tail, secrets, truncated, extra) {
44456
+ if (!truncated) return Buffer.from(scrubValues(tail.toString("utf8"), secrets), "utf8");
44457
+ const needles = secrets.filter((v) => v.length >= 4).map((v) => {
44458
+ const n = Buffer.from(v, "utf8");
44459
+ return { len: n.length, starts: matchStarts(tail, n), next: 0 };
44460
+ });
44461
+ let cut = Math.min(extra, tail.length);
44462
+ let crossed = false;
44463
+ for (let moved = true; moved; ) {
44464
+ moved = false;
44465
+ while (cut < tail.length && (tail[cut] & 192) === 128) {
44466
+ cut++;
44467
+ moved = true;
44468
+ }
44469
+ for (const n of needles) {
44470
+ for (; n.next < n.starts.length && n.starts[n.next] < cut; n.next++) {
44471
+ const end = n.starts[n.next] + n.len;
44472
+ if (end > cut) {
44473
+ cut = end;
44474
+ crossed = moved = true;
44475
+ }
44476
+ }
44477
+ }
44478
+ }
44479
+ const rest = scrubValues(tail.subarray(cut).toString("utf8"), secrets);
44480
+ return Buffer.from((crossed ? "[redacted]" : "") + rest, "utf8");
44481
+ }
44482
+ function decodeOutputTail(tail, secrets = [], truncated = false, extra = 0) {
44483
+ const decoded = redactSensitiveOutput(scrubTail(tail, secrets, truncated, extra).toString("utf8"));
43694
44484
  const lines = decoded.split("\n");
43695
44485
  return lines.slice(-OUTPUT_SNIPPET_MAX_LINES).join("\n").slice(-OUTPUT_SNIPPET_MAX_CHARS);
43696
44486
  }
43697
- function realSpawnCommand(command) {
44487
+ function realSpawnCommand(command, env) {
43698
44488
  return new Promise((resolve) => {
43699
- const child = (0, import_node_child_process3.spawn)(withoutPkgEnv(command.join(" ")), { stdio: ["inherit", "pipe", "pipe"], shell: true });
44489
+ let child;
44490
+ try {
44491
+ child = (0, import_node_child_process4.spawn)(withoutPkgEnv(command.join(" ")), { stdio: ["inherit", "pipe", "pipe"], shell: true, ...env ? { env: { ...process.env, ...env } } : {} });
44492
+ } catch {
44493
+ resolve({ exitCode: 1, stderrTail: "env value could not be passed to the command", outputTail: "" });
44494
+ return;
44495
+ }
44496
+ const secrets = Object.values(env ?? {});
44497
+ const extra = Math.max(0, ...secrets.map((v) => Buffer.byteLength(v)));
44498
+ const finishStderr = () => scrubTail(tail, secrets, tailSeen > tail.length, extra).subarray(-STDERR_TAIL_BYTES).toString("utf8");
44499
+ const finishOutput = () => decodeOutputTail(outputTail, secrets, outputSeen > outputTail.length, extra);
43700
44500
  let tail = Buffer.alloc(0);
43701
44501
  let outputTail = Buffer.alloc(0);
44502
+ let tailSeen = 0;
44503
+ let outputSeen = 0;
43702
44504
  child.stdout?.on("data", (chunk) => {
43703
44505
  if (!process.stdout.write(chunk)) {
43704
44506
  child.stdout?.pause();
43705
44507
  process.stdout.once("drain", () => child.stdout?.resume());
43706
44508
  }
43707
- outputTail = Buffer.concat([outputTail, chunk]).subarray(-OUTPUT_TAIL_MAX_BYTES);
44509
+ outputSeen += chunk.length;
44510
+ outputTail = Buffer.concat([outputTail, chunk]).subarray(-(OUTPUT_TAIL_MAX_BYTES + extra));
43708
44511
  });
43709
44512
  child.stderr?.on("data", (chunk) => {
43710
44513
  if (!process.stderr.write(chunk)) {
43711
44514
  child.stderr?.pause();
43712
44515
  process.stderr.once("drain", () => child.stderr?.resume());
43713
44516
  }
43714
- tail = Buffer.concat([tail, chunk]).subarray(-STDERR_TAIL_BYTES);
43715
- outputTail = Buffer.concat([outputTail, chunk]).subarray(-OUTPUT_TAIL_MAX_BYTES);
44517
+ tailSeen += chunk.length;
44518
+ outputSeen += chunk.length;
44519
+ tail = Buffer.concat([tail, chunk]).subarray(-(STDERR_TAIL_BYTES + extra));
44520
+ outputTail = Buffer.concat([outputTail, chunk]).subarray(-(OUTPUT_TAIL_MAX_BYTES + extra));
43716
44521
  });
43717
- child.on("close", (code) => resolve({ exitCode: code ?? 1, stderrTail: tail.toString("utf8"), outputTail: decodeOutputTail(outputTail) }));
43718
- child.on("error", () => resolve({ exitCode: 1, stderrTail: tail.toString("utf8"), outputTail: decodeOutputTail(outputTail) }));
44522
+ child.on("close", (code) => resolve({ exitCode: code ?? 1, stderrTail: finishStderr(), outputTail: finishOutput() }));
44523
+ child.on("error", () => resolve({ exitCode: 1, stderrTail: finishStderr(), outputTail: finishOutput() }));
43719
44524
  });
43720
44525
  }
43721
44526
  var FETCH_TIMEOUT_MS = 8e3;
@@ -43784,15 +44589,25 @@ function createBackfillClaimer(getSession) {
43784
44589
  }
43785
44590
  };
43786
44591
  }
43787
- async function cmdRun(args) {
44592
+ var RUN_USAGE = "usage: norc run --job-id <id> [--env NAME,...] -- <command>";
44593
+ function parseRunArgs(args) {
43788
44594
  const sepIndex = args.indexOf("--");
43789
- const jobIdFlagIndex = (sepIndex === -1 ? args : args.slice(0, sepIndex)).indexOf("--job-id");
43790
- if (jobIdFlagIndex === -1 || sepIndex === -1 || sepIndex < jobIdFlagIndex + 2) {
43791
- throw new Error("usage: norc run --job-id <id> -- <command>");
43792
- }
44595
+ const flags = sepIndex === -1 ? args : args.slice(0, sepIndex);
44596
+ const jobIdFlagIndex = flags.indexOf("--job-id");
44597
+ if (jobIdFlagIndex === -1 || sepIndex === -1 || sepIndex < jobIdFlagIndex + 2) throw new Error(RUN_USAGE);
43793
44598
  const jobId = args[jobIdFlagIndex + 1];
43794
44599
  const command = args.slice(sepIndex + 1);
43795
- if (!jobId || command.length === 0) throw new Error("usage: norc run --job-id <id> -- <command>");
44600
+ if (!jobId || jobId.startsWith("-") || command.length === 0) throw new Error(RUN_USAGE);
44601
+ const envFlagIndex = flags.indexOf("--env");
44602
+ let envNames;
44603
+ if (envFlagIndex !== -1) {
44604
+ envNames = (flags[envFlagIndex + 1] ?? "").split(",");
44605
+ if (!envNames.every((n) => ENV_NAME_RE.test(n))) throw new Error(`invalid --env list; ${RUN_USAGE}`);
44606
+ }
44607
+ return { jobId, envNames, command };
44608
+ }
44609
+ async function cmdRun(args) {
44610
+ const { jobId, envNames, command } = parseRunArgs(args);
43796
44611
  const getSession = createSessionCache(process.env.NORC_SUPABASE_ANON_KEY ?? DEFAULT_SUPABASE_ANON_KEY);
43797
44612
  return runWrapped(
43798
44613
  {
@@ -43802,10 +44617,12 @@ async function cmdRun(args) {
43802
44617
  clearQueue,
43803
44618
  enqueueRun,
43804
44619
  now: () => /* @__PURE__ */ new Date(),
43805
- claimBackfills: createBackfillClaimer(getSession)
44620
+ claimBackfills: createBackfillClaimer(getSession),
44621
+ loadJobEnv: createJobEnvLoader(getSession)
43806
44622
  },
43807
44623
  jobId,
43808
- command
44624
+ command,
44625
+ envNames
43809
44626
  );
43810
44627
  }
43811
44628
 
@@ -44282,10 +45099,10 @@ function renderUsage(s, opts) {
44282
45099
  }
44283
45100
 
44284
45101
  // src/commands/usage.ts
44285
- var USAGE = "usage: norc usage [--days 7|30] [--json] [--no-color] [--plain]";
44286
- function utf8Locale(env, platform) {
45102
+ var USAGE2 = "usage: norc usage [--days 7|30] [--json] [--no-color] [--plain]";
45103
+ function utf8Locale(env, platform2) {
44287
45104
  const loc = env.LC_ALL || env.LC_CTYPE || env.LANG || "";
44288
- return /utf-?8/i.test(loc) || platform === "win32" && Boolean(env.WT_SESSION);
45105
+ return /utf-?8/i.test(loc) || platform2 === "win32" && Boolean(env.WT_SESSION);
44289
45106
  }
44290
45107
  async function cmdUsage(args, deps, log = console.log, err = console.error) {
44291
45108
  const known = /* @__PURE__ */ new Set(["--days", "--json", "--no-color", "--plain"]);
@@ -44296,13 +45113,13 @@ async function cmdUsage(args, deps, log = console.log, err = console.error) {
44296
45113
  const v = Number(args[++i]);
44297
45114
  if (v !== 7 && v !== 30) {
44298
45115
  err(`error: --days must be 7 or 30
44299
- ${USAGE}`);
45116
+ ${USAGE2}`);
44300
45117
  return 2;
44301
45118
  }
44302
45119
  days = v;
44303
45120
  } else if (!known.has(a)) {
44304
45121
  err(`error: unknown option ${a}
44305
- ${USAGE}`);
45122
+ ${USAGE2}`);
44306
45123
  return 2;
44307
45124
  }
44308
45125
  }
@@ -44332,8 +45149,44 @@ ${USAGE}`);
44332
45149
  return 0;
44333
45150
  }
44334
45151
 
45152
+ // src/paired-device.ts
45153
+ async function savePairedDevice(device, cfgPath = configPath(), cachePath = envCachePath()) {
45154
+ await saveConfig({ device }, cfgPath, { keys: ["device"] });
45155
+ await clearEnvCache(cachePath);
45156
+ }
45157
+
45158
+ // src/user-session.ts
45159
+ var NO_USER_SESSION = "no user session on this machine: `norc env` needs one, and an API-key login only pairs the machine. Run `norc login --email <your-email>` (the pairing is kept).";
45160
+ function requireUserSession(config) {
45161
+ if (!config.session) throw new Error(NO_USER_SESSION);
45162
+ return config.session;
45163
+ }
45164
+ async function saveUserSession(session, path = configPath()) {
45165
+ await saveConfig({ session }, path, { keys: ["session"] });
45166
+ }
45167
+ async function logout(path = configPath(), cachePath = envCachePath(), opts = {}) {
45168
+ const config = await loadConfig(path);
45169
+ const had = { session: Boolean(config.session), device: Boolean(config.device) };
45170
+ if (config.session && opts.signOut) {
45171
+ let timer;
45172
+ await Promise.race([
45173
+ opts.signOut(config.session).catch(() => {
45174
+ }),
45175
+ new Promise((r) => {
45176
+ timer = setTimeout(r, opts.timeoutMs ?? 5e3);
45177
+ })
45178
+ ]).catch(() => {
45179
+ });
45180
+ clearTimeout(timer);
45181
+ }
45182
+ await saveConfig({}, path, { keys: ["session", "device"], sweepAll: true });
45183
+ await clearEnvCache(cachePath);
45184
+ return had;
45185
+ }
45186
+
44335
45187
  // src/commands/bridge.ts
44336
- var import_node_child_process5 = require("node:child_process");
45188
+ var import_node_child_process6 = require("node:child_process");
45189
+ var import_node_crypto3 = require("node:crypto");
44337
45190
 
44338
45191
  // src/enc-key.ts
44339
45192
  async function loadOrCreateEncKey(config, persist) {
@@ -44345,27 +45198,19 @@ async function loadOrCreateEncKey(config, persist) {
44345
45198
  }
44346
45199
 
44347
45200
  // src/capability-key.ts
44348
- var CAPABILITY_PUBLIC_JWK = {
44349
- kty: "EC",
44350
- crv: "P-256",
44351
- alg: "ES256",
44352
- use: "sig",
44353
- kid: "09621c79-698f-4328-bdac-1c347546708e",
44354
- x: "yRbJAsSJpAtBBWIXUg_5tVi0n574uZjComtLR9O6Jwk",
44355
- y: "dVHs6ZeMH10d6IypZgM2-Q9i18_bf_Jj8vsybRPX0Fk"
44356
- };
45201
+ var CAPABILITY_TRUSTED_KEYS = activeTrustedKeys();
44357
45202
 
44358
45203
  // src/dupe-check.ts
44359
- var import_promises3 = require("node:fs/promises");
44360
- var import_node_child_process4 = require("node:child_process");
45204
+ var import_promises4 = require("node:fs/promises");
45205
+ var import_node_child_process5 = require("node:child_process");
44361
45206
  var import_node_util = require("node:util");
44362
- var execFileAsync = (0, import_node_util.promisify)(import_node_child_process4.execFile);
45207
+ var execFileAsync = (0, import_node_util.promisify)(import_node_child_process5.execFile);
44363
45208
  function defaultDupeCheckDeps() {
44364
45209
  return {
44365
45210
  platform: process.platform,
44366
45211
  fileExists: async (p) => {
44367
45212
  try {
44368
- await (0, import_promises3.access)(p);
45213
+ await (0, import_promises4.access)(p);
44369
45214
  return true;
44370
45215
  } catch {
44371
45216
  return false;
@@ -44409,25 +45254,12 @@ async function checkForDesktopInstall(deps = defaultDupeCheckDeps()) {
44409
45254
  return found ? WARNING : null;
44410
45255
  }
44411
45256
 
44412
- // src/machines.ts
44413
- async function syncJobs(sb, entries) {
44414
- const jobs = jobsOf(entries).filter((j) => typeof j.id === "string").map((j) => ({
44415
- id: j.id,
44416
- name: j.name ?? "",
44417
- schedule: j.schedule,
44418
- command: j.command,
44419
- enabled: j.enabled ?? true
44420
- }));
44421
- const { error } = await sb.rpc("sync_account_jobs", { p_jobs: jobs, p_authoritative_empty: true });
44422
- if (error) throw new Error(error.message);
44423
- }
44424
-
44425
45257
  // src/crontab-changes.ts
44426
45258
  var import_node_fs2 = require("node:fs");
44427
- var import_node_path4 = require("node:path");
44428
- var import_node_os5 = require("node:os");
45259
+ var import_node_path5 = require("node:path");
45260
+ var import_node_os6 = require("node:os");
44429
45261
  function crontabChangesPath() {
44430
- return (0, import_node_path4.join)((0, import_node_os5.homedir)(), ".config", "norc", "crontab-changes.json");
45262
+ return (0, import_node_path5.join)((0, import_node_os6.homedir)(), ".config", "norc", "crontab-changes.json");
44431
45263
  }
44432
45264
  function fileChangeStore(path) {
44433
45265
  return {
@@ -44439,7 +45271,7 @@ function fileChangeStore(path) {
44439
45271
  }
44440
45272
  },
44441
45273
  save: (v) => {
44442
- (0, import_node_fs2.mkdirSync)((0, import_node_path4.dirname)(path), { recursive: true, mode: 448 });
45274
+ (0, import_node_fs2.mkdirSync)((0, import_node_path5.dirname)(path), { recursive: true, mode: 448 });
44443
45275
  (0, import_node_fs2.writeFileSync)(path, v, { mode: 384 });
44444
45276
  }
44445
45277
  };
@@ -44457,56 +45289,137 @@ function trackLineChanges(io, path = crontabChangesPath()) {
44457
45289
  };
44458
45290
  }
44459
45291
 
45292
+ // src/remote-consent.ts
45293
+ var import_node_os7 = require("node:os");
45294
+ var import_promises5 = require("node:readline/promises");
45295
+ function sanitize(s, max = 160) {
45296
+ const clean2 = s.replace(/[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028-\u202e\u2060-\u2069\ufeff\u{e0000}-\u{e007f}]/gu, " ").trim();
45297
+ return clean2.length > max ? `${clean2.slice(0, max)}\u2026` : clean2;
45298
+ }
45299
+ function diffLines(before, after) {
45300
+ const eff = (t) => t.split("\n").map((l) => l.trimEnd()).filter((l) => l.trim() !== "");
45301
+ const only = (x, y) => {
45302
+ const left = /* @__PURE__ */ new Map();
45303
+ for (const l of y) left.set(l, (left.get(l) ?? 0) + 1);
45304
+ return x.filter((l) => {
45305
+ const n = left.get(l) ?? 0;
45306
+ if (n > 0) {
45307
+ left.set(l, n - 1);
45308
+ return false;
45309
+ }
45310
+ return true;
45311
+ });
45312
+ };
45313
+ const b = eff(before), a = eff(after);
45314
+ return { added: only(a, b), removed: only(b, a) };
45315
+ }
45316
+ function remoteEnabled(config) {
45317
+ return config.remote?.enabled === true;
45318
+ }
45319
+ function decideWrite(config, before, after, log = console.log) {
45320
+ const { added, removed } = diffLines(before, after);
45321
+ const eff = (t) => t.split("\n").map((l) => l.trimEnd()).filter((l) => l.trim() !== "");
45322
+ const reordered = added.length === 0 && removed.length === 0 && eff(before).join("\n") !== eff(after).join("\n");
45323
+ if (added.length === 0 && removed.length === 0 && !reordered) return true;
45324
+ if (!remoteEnabled(config)) {
45325
+ log("[norc bridge] remote change refused: remote writes are disabled on this host. Run `norc remote enable` to allow them.");
45326
+ return false;
45327
+ }
45328
+ if (reordered) log(`[norc bridge] remote change (${sanitize(config.remote?.account ?? "", 80)}) reordered existing lines`);
45329
+ for (const l of added.slice(0, 20)) log(`[norc bridge] remote change (${sanitize(config.remote?.account ?? "", 80)}) + ${sanitize(l)}`);
45330
+ for (const l of removed.slice(0, 20)) log(`[norc bridge] remote change (${sanitize(config.remote?.account ?? "", 80)}) - ${sanitize(l)}`);
45331
+ return true;
45332
+ }
45333
+ async function cmdRemote(args, config, save, io = defaultIo()) {
45334
+ const sub = args[0] ?? "status";
45335
+ if (sub === "status") {
45336
+ io.log(remoteEnabled(config) ? `remote writes: enabled for ${config.remote?.account} since ${config.remote?.enabledAt}` : "remote writes: disabled");
45337
+ return;
45338
+ }
45339
+ if (sub === "disable") {
45340
+ config.remote = { enabled: false, account: config.remote?.account ?? "", enabledAt: "" };
45341
+ await save(config);
45342
+ io.log("remote writes disabled.");
45343
+ return;
45344
+ }
45345
+ if (sub !== "enable") throw new Error("usage: norc remote enable|disable|status");
45346
+ const account = config.session?.email ?? "the account this machine is paired to";
45347
+ 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.`);
45348
+ io.log("Every remote change is logged here with the exact command. Disable any time with `norc remote disable`.");
45349
+ if (!args.includes("--yes")) {
45350
+ if (!io.isTTY) throw new Error("not interactive: re-run in a terminal, or pass --yes");
45351
+ if ((await io.ask("Allow remote writes? [y/N] ")).toLowerCase() !== "y") {
45352
+ io.log("left disabled.");
45353
+ return;
45354
+ }
45355
+ }
45356
+ config.remote = { enabled: true, account, enabledAt: (/* @__PURE__ */ new Date()).toISOString() };
45357
+ await save(config);
45358
+ io.log("remote writes enabled.");
45359
+ }
45360
+ function defaultIo() {
45361
+ return {
45362
+ isTTY: Boolean(process.stdin.isTTY),
45363
+ log: (m) => console.log(m),
45364
+ ask: async (q) => {
45365
+ const rl = (0, import_promises5.createInterface)({ input: process.stdin, output: process.stdout });
45366
+ try {
45367
+ return (await rl.question(q)).trim();
45368
+ } finally {
45369
+ rl.close();
45370
+ }
45371
+ }
45372
+ };
45373
+ }
45374
+
44460
45375
  // src/commands/bridge.ts
44461
- var READ_ONLY = ["ping", "read_crontab", "list_jobs"];
45376
+ var READ_ONLY = ["ping", "read_crontab", "list_jobs", "read_managed", "crontab_hash"];
44462
45377
  var MAX_REMEMBERED_NONCES = 20;
44463
- function buildWriteIntentDeps(config, machineId, crontabIo, persist) {
45378
+ function replayGuard(config, machineId, persist) {
44464
45379
  return {
44465
- machineId,
44466
- nowSec: () => Math.floor(Date.now() / 1e3),
44467
- publicJwk: CAPABILITY_PUBLIC_JWK,
44468
- lastGeneration: () => config.bridge?.generation ?? 0,
45380
+ lastGeneration: () => replayFor(config, machineId).generation,
44469
45381
  setGeneration: (g) => {
44470
- config.bridge = { generation: g, nonces: config.bridge?.nonces ?? [], executeNonces: config.bridge?.executeNonces };
45382
+ replayFor(config, machineId).generation = g;
44471
45383
  persist(config);
44472
45384
  },
44473
- seenNonce: (n) => (config.bridge?.nonces ?? []).includes(n),
45385
+ seenNonce: (n) => replayFor(config, machineId).nonces.includes(n),
44474
45386
  rememberNonce: (n) => {
44475
- const nonces = [...config.bridge?.nonces ?? [], n].slice(-MAX_REMEMBERED_NONCES);
44476
- config.bridge = { generation: config.bridge?.generation ?? 0, nonces, executeNonces: config.bridge?.executeNonces };
45387
+ const r = replayFor(config, machineId);
45388
+ r.nonces = [...r.nonces, n].slice(-MAX_REMEMBERED_NONCES);
44477
45389
  persist(config);
45390
+ }
45391
+ };
45392
+ }
45393
+ function buildWriteIntentDeps(config, machineId, crontabIo, persist, refresh = async () => {
45394
+ }, envNames) {
45395
+ return {
45396
+ machineId,
45397
+ envNames,
45398
+ nowSec: () => Math.floor(Date.now() / 1e3),
45399
+ publicJwk: CAPABILITY_TRUSTED_KEYS,
45400
+ ...replayGuard(config, machineId, persist),
45401
+ // NAT-002: headless hosts have no one to click a dialog, so the local opt-in
45402
+ // (`norc remote enable`, stored in the 0600 config) is the consent; every
45403
+ // applied change is logged with its exact diff. Default is OFF.
45404
+ requestConsent: async ({ before, after }) => {
45405
+ await refresh(config);
45406
+ return decideWrite(config, before, after);
44478
45407
  },
44479
- // ponytail: no human at a keyboard for a headless server — pairing itself
44480
- // (`norc pair`, claimed from the account owner's web vault) IS the consent
44481
- // to be remotely administered from then on. Desktop gates writes on a
44482
- // native Yes/No dialog because a person might be sitting at that machine;
44483
- // that threat model doesn't apply to an unattended box, so every
44484
- // capability-verified write (already authorized server-side by the
44485
- // device-command edge fn) is auto-approved here. Upgrade path if that
44486
- // changes: a --require-consent flag gating on an interactive prompt.
44487
- consentGranted: () => true,
44488
- requestConsent: async () => true,
44489
45408
  readCrontab: () => crontabIo.read(),
44490
45409
  writeCrontab: (c) => crontabIo.write(c)
44491
45410
  };
44492
45411
  }
44493
- function buildRawWriteIntentDeps(config, machineId, crontabIo, persist) {
45412
+ function buildRawWriteIntentDeps(config, machineId, crontabIo, persist, refresh = async () => {
45413
+ }) {
44494
45414
  return {
44495
45415
  machineId,
44496
45416
  nowSec: () => Math.floor(Date.now() / 1e3),
44497
- publicJwk: CAPABILITY_PUBLIC_JWK,
44498
- lastGeneration: () => config.bridge?.generation ?? 0,
44499
- setGeneration: (g) => {
44500
- config.bridge = { generation: g, nonces: config.bridge?.nonces ?? [], executeNonces: config.bridge?.executeNonces };
44501
- persist(config);
45417
+ publicJwk: CAPABILITY_TRUSTED_KEYS,
45418
+ ...replayGuard(config, machineId, persist),
45419
+ requestRawConsent: async ({ before, after }) => {
45420
+ await refresh(config);
45421
+ return decideWrite(config, before, after);
44502
45422
  },
44503
- seenNonce: (n) => (config.bridge?.nonces ?? []).includes(n),
44504
- rememberNonce: (n) => {
44505
- const nonces = [...config.bridge?.nonces ?? [], n].slice(-MAX_REMEMBERED_NONCES);
44506
- config.bridge = { generation: config.bridge?.generation ?? 0, nonces, executeNonces: config.bridge?.executeNonces };
44507
- persist(config);
44508
- },
44509
- requestRawConsent: async () => true,
44510
45423
  readCrontab: () => crontabIo.read(),
44511
45424
  writeCrontab: (c) => crontabIo.write(c)
44512
45425
  };
@@ -44516,16 +45429,29 @@ function projectJobsRemoved(currentCrontab, jobIds) {
44516
45429
  const remaining = jobsOf(parseCrontab(currentCrontab)).filter((j) => typeof j.id === "string" && !jobIds.includes(j.id)).map((j) => ({ ...j, name: j.name ?? "", enabled: j.enabled ?? true, createdAt: now, updatedAt: now }));
44517
45430
  return renderJobsToCrontab(currentCrontab, remaining);
44518
45431
  }
45432
+ async function confirmJobsGone(sb, ids) {
45433
+ const { data, error } = await sb.rpc("get_live_job_ids", {});
45434
+ if (error || !Array.isArray(data)) return [];
45435
+ const live = new Set(data.map((r) => r.job_id));
45436
+ return ids.filter((id) => !live.has(id));
45437
+ }
44519
45438
  function findManagedJob(currentCrontab, jobId) {
44520
- const job = jobsOf(parseCrontab(currentCrontab)).find((j) => j.id === jobId);
44521
- return job && typeof job.id === "string" ? { id: job.id, command: job.command } : null;
45439
+ const entry = parseCrontab(currentCrontab).find((e) => e.kind === "job" && e.id === jobId);
45440
+ return entry ? { id: jobId, command: unwrapCommand(entry.command), envNames: wrappedEnvNames(entry.command) ?? [] } : null;
45441
+ }
45442
+ function reprojectEnvNames(currentCrontab, names) {
45443
+ const want = /* @__PURE__ */ new Map();
45444
+ for (const e of parseCrontab(currentCrontab)) {
45445
+ if (e.kind === "job" && e.id !== void 0) want.set(e.id, Object.hasOwn(names, e.id) ? names[e.id] : []);
45446
+ }
45447
+ return rewriteEnvNames(currentCrontab, want);
44522
45448
  }
44523
45449
  function pruneExpiredExecuteNonces(nonces, nowSec) {
44524
45450
  return (nonces ?? []).filter((n) => n.expiresAt >= nowSec);
44525
45451
  }
44526
45452
  function spawnWrappedCommand(command) {
44527
45453
  return new Promise((resolve, reject) => {
44528
- const child = (0, import_node_child_process5.spawn)(withoutPkgEnv(command), { shell: true, detached: true, stdio: "ignore" });
45454
+ const child = (0, import_node_child_process6.spawn)(withoutPkgEnv(command), { shell: true, detached: true, stdio: "ignore" });
44529
45455
  child.once("spawn", () => {
44530
45456
  child.unref();
44531
45457
  resolve();
@@ -44548,7 +45474,6 @@ async function runBridge(env, crontabIo) {
44548
45474
  await logStartupWarnings();
44549
45475
  const config = await loadConfig();
44550
45476
  if (!config.device) throw new Error("not paired \u2014 run `norc pair` first");
44551
- const { machineId } = config.device;
44552
45477
  const lineChanges = trackLineChanges(crontabIo);
44553
45478
  void lineChanges.look();
44554
45479
  setInterval(() => {
@@ -44556,7 +45481,7 @@ async function runBridge(env, crontabIo) {
44556
45481
  }, 3e4);
44557
45482
  let configSaveChain = Promise.resolve();
44558
45483
  const persistConfig = () => {
44559
- const save = configSaveChain.then(() => saveConfig(config));
45484
+ const save = configSaveChain.then(() => saveConfig(config, void 0, { keys: ["bridge", "enc"] }));
44560
45485
  configSaveChain = save.catch(() => {
44561
45486
  });
44562
45487
  return save;
@@ -44564,12 +45489,43 @@ async function runBridge(env, crontabIo) {
44564
45489
  const keyPair = await loadOrCreateEncKey(config, persistConfig);
44565
45490
  let state = "disconnected";
44566
45491
  let attempt = 0;
45492
+ let idleLogged = false;
44567
45493
  while (true) {
45494
+ const onDisk = await readIdentity();
45495
+ if (onDisk === null) {
45496
+ if (!idleLogged) console.log("[norc bridge] no paired device (logged out?): idle, run `norc pair` to resume");
45497
+ idleLogged = true;
45498
+ await wait(IDLE_POLL_MS);
45499
+ continue;
45500
+ }
45501
+ idleLogged = false;
45502
+ if (onDisk) config.device = onDisk;
45503
+ const machineId = config.device.machineId;
45504
+ const builtFor = identityKey(config.device);
45505
+ let identityChanged = false;
45506
+ let endCycle = () => {
45507
+ };
45508
+ const stillCurrent = async () => {
45509
+ const id = await readIdentity();
45510
+ return id === void 0 || identityKey(id) === builtFor;
45511
+ };
45512
+ const watchIdentity = async () => {
45513
+ if (identityChanged) return false;
45514
+ if (await stillCurrent()) return true;
45515
+ identityChanged = true;
45516
+ console.log("[norc bridge] device identity changed on disk: reconnecting");
45517
+ endCycle();
45518
+ return false;
45519
+ };
44568
45520
  let sb = null;
44569
45521
  let heartbeat = null;
45522
+ let envRefresh = null;
44570
45523
  const enqueueSync = serialize();
44571
45524
  const queueSyncJobs = () => enqueueSync(() => syncJobsQuiet(sb, crontabIo));
44572
- const enqueueMutation = serialize();
45525
+ const enqueueRaw = serialize();
45526
+ const enqueueMutation = (task) => enqueueRaw(async () => {
45527
+ if (await watchIdentity()) await task();
45528
+ });
44573
45529
  try {
44574
45530
  state = reduceConn(state, "connect");
44575
45531
  const sess = await deviceSession(env.supabaseUrl, env.anonKey, void 0, keyPair.publicJwk);
@@ -44592,9 +45548,13 @@ async function runBridge(env, crontabIo) {
44592
45548
  keyPair,
44593
45549
  onDrop: (event) => console.warn("[norc bridge] dropped unauthenticated relay payload on", event)
44594
45550
  });
44595
- serveBridge(new SealedBridgeTransport(sec), lineChanges.io, { allow: [...READ_ONLY] });
44596
- const deps = buildWriteIntentDeps(config, machineId, crontabIo, () => void persistConfig());
44597
- const rawDeps = buildRawWriteIntentDeps(config, machineId, crontabIo, () => void persistConfig());
45551
+ serveBridge(new SealedBridgeTransport(sec), lineChanges.io, { allow: [...READ_ONLY], authorize: fullReadGate(async () => {
45552
+ await refreshRemote(config);
45553
+ return remoteEnabled(config);
45554
+ }, "remote reads are disabled on this host (run `norc remote enable`)") });
45555
+ const pullNames = () => deviceSession(env.supabaseUrl, env.anonKey, AbortSignal.timeout(1e4), keyPair.publicJwk).then((s) => pullEnvNames(fetch, s, 1e4)).catch(() => null);
45556
+ const deps = buildWriteIntentDeps(config, machineId, crontabIo, () => void persistConfig(), refreshRemote, pullNames);
45557
+ const rawDeps = buildRawWriteIntentDeps(config, machineId, crontabIo, () => void persistConfig(), refreshRemote);
44598
45558
  sec.on("write-intent", (payload, from) => {
44599
45559
  let msg;
44600
45560
  try {
@@ -44651,7 +45611,7 @@ async function runBridge(env, crontabIo) {
44651
45611
  const nowSec = Math.floor(Date.now() / 1e3);
44652
45612
  const live = pruneExpiredExecuteNonces(config.bridge?.executeNonces, nowSec);
44653
45613
  const verify = await verifyExecuteCapability(capability, {
44654
- publicJwk: CAPABILITY_PUBLIC_JWK,
45614
+ publicJwk: CAPABILITY_TRUSTED_KEYS,
44655
45615
  machineId,
44656
45616
  jobId,
44657
45617
  nowSec,
@@ -44666,13 +45626,19 @@ async function runBridge(env, crontabIo) {
44666
45626
  reject("unknown job");
44667
45627
  return;
44668
45628
  }
45629
+ await refreshRemote(config);
45630
+ if (!remoteEnabled(config)) {
45631
+ reject("remote execution is disabled on this host (norc remote enable)");
45632
+ return;
45633
+ }
45634
+ console.log(`[norc bridge] execute-now (${sanitize(config.remote?.account ?? "", 80)}) ${sanitize(job.command, 400)}`);
45635
+ replayFor(config, machineId);
44669
45636
  config.bridge = {
44670
- generation: config.bridge?.generation ?? 0,
44671
- nonces: config.bridge?.nonces ?? [],
45637
+ ...config.bridge,
44672
45638
  executeNonces: [...live, { nonce: verify.nonce, expiresAt: verify.nonceExp }]
44673
45639
  };
44674
45640
  await persistConfig();
44675
- await spawnWrappedCommand(wrapCommand(job.id, job.command, process.platform === "win32" ? "windows" : "posix"));
45641
+ await spawnWrappedCommand(wrapCommand(job.id, job.command, process.platform === "win32" ? "windows" : "posix", job.envNames));
44676
45642
  console.log("[norc bridge] execute-now-intent applied");
44677
45643
  void sec.send("execute-now-applied", JSON.stringify({ jobId }), from).catch((e) => console.error("[norc bridge] failed to broadcast execute-now-applied", e));
44678
45644
  } catch (e) {
@@ -44690,10 +45656,22 @@ async function runBridge(env, crontabIo) {
44690
45656
  }
44691
45657
  if (!msg || !Array.isArray(msg.jobIds) || !msg.jobIds.every((id) => typeof id === "string") || msg.jobIds.length === 0) return;
44692
45658
  enqueueMutation(async () => {
45659
+ await refreshRemote(config);
45660
+ if (!remoteEnabled(config)) {
45661
+ console.warn("[norc bridge] jobs-deleted ignored: remote changes are disabled on this host");
45662
+ return;
45663
+ }
45664
+ const gone = await confirmJobsGone(sb, msg.jobIds);
45665
+ if (gone.length === 0) {
45666
+ console.warn("[norc bridge] jobs-deleted ignored: server still lists those jobs (or could not be asked)");
45667
+ return;
45668
+ }
44693
45669
  for (let attempt2 = 0; attempt2 < 3; attempt2++) {
44694
45670
  try {
44695
45671
  const current = await crontabIo.read();
44696
- await crontabIo.write(projectJobsRemoved(current, msg.jobIds));
45672
+ const next = projectJobsRemoved(current, gone);
45673
+ if (next !== current) console.log(`[norc bridge] jobs-deleted (${sanitize(config.remote?.account ?? "", 80)}): removing ${gone.length} job(s) the server no longer has`);
45674
+ await crontabIo.write(next);
44697
45675
  queueSyncJobs();
44698
45676
  return;
44699
45677
  } catch (err) {
@@ -44704,6 +45682,7 @@ async function runBridge(env, crontabIo) {
44704
45682
  });
44705
45683
  });
44706
45684
  const closed = new Promise((resolve) => {
45685
+ endCycle = resolve;
44707
45686
  channel.subscribe((status, err) => {
44708
45687
  console.log(`[norc bridge] channel status: ${status}${err ? ` (${err})` : ""}`);
44709
45688
  if (status === "SUBSCRIBED") {
@@ -44711,9 +45690,19 @@ async function runBridge(env, crontabIo) {
44711
45690
  attempt = 0;
44712
45691
  void channel.track({ online_at: (/* @__PURE__ */ new Date()).toISOString() });
44713
45692
  queueSyncJobs();
45693
+ if (heartbeat) clearInterval(heartbeat);
45694
+ if (envRefresh) clearInterval(envRefresh);
44714
45695
  heartbeat = setInterval(() => {
44715
- void deviceSession(env.supabaseUrl, env.anonKey, void 0, keyPair.publicJwk);
44716
- }, 1e4);
45696
+ void watchIdentity().then((ok) => {
45697
+ if (ok) return deviceSession(env.supabaseUrl, env.anonKey, void 0, keyPair.publicJwk);
45698
+ });
45699
+ }, 6e4);
45700
+ const pullEnv2 = () => enqueueMutation(async () => {
45701
+ const names = await pullNames();
45702
+ if (names) await applyEnvNames(crontabIo, names);
45703
+ });
45704
+ pullEnv2();
45705
+ envRefresh = setInterval(pullEnv2, 5 * 6e4);
44717
45706
  }
44718
45707
  if (status === "CLOSED" || status === "CHANNEL_ERROR" || status === "TIMED_OUT") {
44719
45708
  state = reduceConn(state, "error");
@@ -44728,9 +45717,14 @@ async function runBridge(env, crontabIo) {
44728
45717
  console.error("[norc bridge] connect cycle failed:", e instanceof Error ? e.message : e);
44729
45718
  } finally {
44730
45719
  if (heartbeat) clearInterval(heartbeat);
45720
+ if (envRefresh) clearInterval(envRefresh);
44731
45721
  if (sb) await sb.removeAllChannels().catch(() => {
44732
45722
  });
44733
45723
  }
45724
+ if (identityChanged) {
45725
+ attempt = 0;
45726
+ continue;
45727
+ }
44734
45728
  const delay = backoffDelay(attempt++);
44735
45729
  console.log(`[norc bridge] reconnecting in ${delay}ms`);
44736
45730
  await wait(delay);
@@ -44744,28 +45738,50 @@ async function syncJobsQuiet(sb, crontabIo) {
44744
45738
  console.error("[norc bridge] syncJobs failed:", e instanceof Error ? e.message : e);
44745
45739
  }
44746
45740
  }
45741
+ async function applyEnvNames(crontabIo, names) {
45742
+ try {
45743
+ const current = await crontabIo.read();
45744
+ const next = reprojectEnvNames(current, names);
45745
+ if (next === current) return;
45746
+ await crontabIo.write(next);
45747
+ console.log("[norc bridge] updated the env var names on managed crontab lines");
45748
+ } catch (e) {
45749
+ console.error("[norc bridge] updating env var names failed:", e instanceof Error ? e.message : e);
45750
+ }
45751
+ }
45752
+ var IDLE_POLL_MS = 3e4;
45753
+ async function readIdentity() {
45754
+ try {
45755
+ return (await loadConfigStrict()).device ?? null;
45756
+ } catch {
45757
+ return void 0;
45758
+ }
45759
+ }
45760
+ function identityKey(d) {
45761
+ return d ? `${d.machineId}:${(0, import_node_crypto3.createHash)("sha256").update(d.deviceToken).digest("hex").slice(0, 16)}` : "";
45762
+ }
44747
45763
  function wait(ms) {
44748
45764
  return new Promise((r) => setTimeout(r, ms));
44749
45765
  }
44750
45766
 
44751
45767
  // src/service.ts
44752
- var import_promises4 = require("node:fs/promises");
44753
- var import_node_child_process6 = require("node:child_process");
45768
+ var import_promises6 = require("node:fs/promises");
45769
+ var import_node_child_process7 = require("node:child_process");
44754
45770
  var import_node_util2 = require("node:util");
44755
- var import_node_os6 = require("node:os");
44756
- var import_node_path5 = require("node:path");
44757
- var execFileAsync2 = (0, import_node_util2.promisify)(import_node_child_process6.execFile);
45771
+ var import_node_os8 = require("node:os");
45772
+ var import_node_path6 = require("node:path");
45773
+ var execFileAsync2 = (0, import_node_util2.promisify)(import_node_child_process7.execFile);
44758
45774
  function resolveBinaryPath(proc = process) {
44759
45775
  return proc.pkg ? proc.execPath : proc.argv[1];
44760
45776
  }
44761
45777
  function defaultServiceDeps(binaryPath) {
44762
45778
  return {
44763
- platform: (0, import_node_os6.platform)(),
44764
- home: (0, import_node_os6.homedir)(),
45779
+ platform: (0, import_node_os8.platform)(),
45780
+ home: (0, import_node_os8.homedir)(),
44765
45781
  binaryPath,
44766
- mkdir: import_promises4.mkdir,
44767
- writeFile: import_promises4.writeFile,
44768
- rm: import_promises4.rm,
45782
+ mkdir: import_promises6.mkdir,
45783
+ writeFile: import_promises6.writeFile,
45784
+ rm: import_promises6.rm,
44769
45785
  exec: async (cmd, args) => {
44770
45786
  await execFileAsync2(cmd, args);
44771
45787
  }
@@ -44773,11 +45789,12 @@ function defaultServiceDeps(binaryPath) {
44773
45789
  }
44774
45790
  var SCHEDULED_TASK_NAME = "norc-cli-bridge";
44775
45791
  function systemdUnitPath(home) {
44776
- return (0, import_node_path5.join)(home, ".config", "systemd", "user", "norc.service");
45792
+ return (0, import_node_path6.join)(home, ".config", "systemd", "user", "norc.service");
44777
45793
  }
44778
45794
  function launchdPlistPath(home) {
44779
- return (0, import_node_path5.join)(home, "Library", "LaunchAgents", "dev.norc.cli.plist");
45795
+ return (0, import_node_path6.join)(home, "Library", "LaunchAgents", "dev.norc.cli.plist");
44780
45796
  }
45797
+ var xmlEscape = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
44781
45798
  function systemdUnit(binaryPath) {
44782
45799
  return `[Unit]
44783
45800
  Description=norc headless cron scheduler bridge
@@ -44786,7 +45803,7 @@ Wants=network-online.target
44786
45803
 
44787
45804
  [Service]
44788
45805
  Type=simple
44789
- ExecStart=${binaryPath} bridge
45806
+ ExecStart="${binaryPath.replace(/[\\"]/g, "\\$&").replace(/%/g, "%%").replace(/\$/g, "$$$$")}" bridge
44790
45807
  Restart=on-failure
44791
45808
  RestartSec=5
44792
45809
 
@@ -44802,7 +45819,7 @@ function launchdPlist(binaryPath) {
44802
45819
  <key>Label</key><string>dev.norc.cli</string>
44803
45820
  <key>ProgramArguments</key>
44804
45821
  <array>
44805
- <string>${binaryPath}</string>
45822
+ <string>${xmlEscape(binaryPath)}</string>
44806
45823
  <string>bridge</string>
44807
45824
  </array>
44808
45825
  <key>RunAtLoad</key><true/>
@@ -44815,7 +45832,7 @@ async function installService(deps = defaultServiceDeps(process.execPath)) {
44815
45832
  switch (deps.platform) {
44816
45833
  case "linux": {
44817
45834
  const path = systemdUnitPath(deps.home);
44818
- await deps.mkdir((0, import_node_path5.join)(deps.home, ".config", "systemd", "user"), { recursive: true });
45835
+ await deps.mkdir((0, import_node_path6.join)(deps.home, ".config", "systemd", "user"), { recursive: true });
44819
45836
  await deps.writeFile(path, systemdUnit(deps.binaryPath));
44820
45837
  await deps.exec("systemctl", ["--user", "daemon-reload"]);
44821
45838
  await deps.exec("systemctl", ["--user", "enable", "--now", "norc.service"]);
@@ -44823,7 +45840,7 @@ async function installService(deps = defaultServiceDeps(process.execPath)) {
44823
45840
  }
44824
45841
  case "darwin": {
44825
45842
  const path = launchdPlistPath(deps.home);
44826
- await deps.mkdir((0, import_node_path5.join)(deps.home, "Library", "LaunchAgents"), { recursive: true });
45843
+ await deps.mkdir((0, import_node_path6.join)(deps.home, "Library", "LaunchAgents"), { recursive: true });
44827
45844
  await deps.writeFile(path, launchdPlist(deps.binaryPath));
44828
45845
  await deps.exec("launchctl", ["load", "-w", path]);
44829
45846
  return;
@@ -44880,12 +45897,21 @@ var HELP = `norc \u2014 headless job scheduler CLI
44880
45897
  Usage:
44881
45898
  norc login --email <email> start email one-time-code login (prompts for an API key first if no email given; empty falls back to email)
44882
45899
  norc login --key <api-key> log in + pair headlessly with a norc API key (vault \u2192 Settings \u2192 API Keys) \u2014 no email/browser
45900
+ (pairs only; \`norc env\` also needs \`norc login --email\`, both are kept)
44883
45901
  norc pair pair this machine with your norc account (after norc login)
45902
+ norc logout remove this machine's user session and pairing (both kinds of login)
44884
45903
  norc jobs list list jobs in this machine's crontab
44885
45904
  norc jobs add <schedule> <cmd> add a job (schedule in 5-field cron syntax)
44886
45905
  norc jobs rm <id> remove a job by id
44887
45906
  norc jobs enable <id> enable a job
44888
45907
  norc jobs disable <id> disable a job
45908
+ norc jobs add <schedule> <cmd> --env NAME [--env NAME2] also bind account env vars to the job
45909
+ norc env ls list env vars (name, state, bound jobs; never values)
45910
+ echo "$V" | norc env set NAME create/update a var; value from stdin or hidden prompt, never argv
45911
+ norc env archive NAME [--yes] stop delivering a var (lists the jobs it would break)
45912
+ norc env restore NAME resume delivery of an archived var
45913
+ norc env rm NAME [--yes] delete a var permanently (lists the jobs it would break, asks you to type
45914
+ the name); asks for your 2FA code or an emailed code to confirm it is you
44889
45915
  norc gitops plan --file <path> [--json] diff a YAML file against live jobs (read-only)
44890
45916
  norc gitops apply --file <path> apply the diff (create/update/delete to match the file)
44891
45917
  norc run --job-id <id> -- <cmd> exec <cmd> and report its result (used internally by wrapped crontab entries)
@@ -44893,6 +45919,7 @@ Usage:
44893
45919
  norc usage [--days 7|30] [--json] [--no-color] [--plain]
44894
45920
  usage dashboard in the terminal: headroom, health, runs, activity
44895
45921
  norc bridge run the bridge daemon (stay online, admin from norc web)
45922
+ norc remote enable|disable|status allow/deny remote crontab writes + execute-now from your account (default: disabled)
44896
45923
  norc service install register+start the per-user background service
44897
45924
  norc service uninstall stop+remove the per-user background service
44898
45925
 
@@ -44906,7 +45933,7 @@ function supabase() {
44906
45933
  return createClient(url, anon);
44907
45934
  }
44908
45935
  async function prompt(question) {
44909
- const rl = (0, import_promises5.createInterface)({ input: process.stdin, output: process.stdout });
45936
+ const rl = (0, import_promises7.createInterface)({ input: process.stdin, output: process.stdout });
44910
45937
  try {
44911
45938
  return (await rl.question(question)).trim();
44912
45939
  } finally {
@@ -44916,23 +45943,22 @@ async function prompt(question) {
44916
45943
  async function cmdLogin(args) {
44917
45944
  const keyFlagIndex = args.indexOf("--key");
44918
45945
  const emailFlagIndex = args.indexOf("--email");
44919
- const vaultUrl = process.env.NORC_VAULT_URL ?? DEFAULT_VAULT_URL;
45946
+ const vaultUrl2 = vaultUrl();
45947
+ if (keyFlagIndex !== -1) console.error("warning: --key puts the API key on the command line (visible in `ps` and shell history). Prefer NORC_API_KEY or the interactive prompt.");
44920
45948
  let apiKey = keyFlagIndex !== -1 ? args[keyFlagIndex + 1] : process.env.NORC_API_KEY;
44921
45949
  const positionalEmail = emailFlagIndex !== -1 ? args[emailFlagIndex + 1] : void 0;
44922
45950
  debugLog("login: --key present:", keyFlagIndex !== -1, "NORC_API_KEY set:", Boolean(process.env.NORC_API_KEY), "--email:", positionalEmail ?? "(none)");
44923
45951
  if (!apiKey && !positionalEmail) {
44924
45952
  debugLog("login: no --key/--email/NORC_API_KEY given, prompting for API key");
44925
- apiKey = await promptSecret(`API key (create one at ${vaultUrl}/settings/api-keys \u2014 press enter to use email instead): `);
45953
+ apiKey = await promptSecret(`API key (create one at ${vaultUrl2}/settings/api-keys \u2014 press enter to use email instead): `);
44926
45954
  debugLog("login: prompt returned key:", redactSecret(apiKey));
44927
45955
  }
44928
45956
  if (apiKey) {
44929
- debugLog("login: using API-key path, POST", `${vaultUrl}/api/v1/machines`, "key:", redactSecret(apiKey));
44930
- const result2 = await pairWithApiKey(fetch, vaultUrl, apiKey, (0, import_node_os7.hostname)());
45957
+ debugLog("login: using API-key path, POST", `${vaultUrl2}/api/v1/machines`, "key:", redactSecret(apiKey));
45958
+ const result2 = await pairWithApiKey(fetch, vaultUrl2, apiKey, (0, import_node_os9.hostname)());
44931
45959
  debugLog("login: pairWithApiKey result:", result2.ok ? { ok: true, machineId: result2.machineId, deviceToken: redactSecret(result2.deviceToken) } : result2);
44932
45960
  if (!result2.ok) throw new Error(result2.message);
44933
- const config2 = await loadConfig();
44934
- config2.device = { machineId: result2.machineId, deviceToken: result2.deviceToken };
44935
- await saveConfig(config2);
45961
+ await savePairedDevice({ machineId: result2.machineId, deviceToken: result2.deviceToken });
44936
45962
  console.log(`logged in. machine id: ${result2.machineId}`);
44937
45963
  return;
44938
45964
  }
@@ -44949,10 +45975,8 @@ async function cmdLogin(args) {
44949
45975
  const result = await verifyLogin(client, email, code);
44950
45976
  debugLog("login: verifyLogin result:", result.ok ? { ok: true } : result);
44951
45977
  if (!result.ok) throw new Error(result.message);
44952
- const config = await loadConfig();
44953
- config.session = { email, accessToken: result.accessToken, refreshToken: result.refreshToken };
44954
- await saveConfig(config);
44955
- console.log("logged in. run `norc pair` next to register this machine.");
45978
+ await saveUserSession({ email, accessToken: result.accessToken, refreshToken: result.refreshToken });
45979
+ 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.");
44956
45980
  }
44957
45981
  async function cmdPair() {
44958
45982
  const client = supabase();
@@ -44962,9 +45986,7 @@ async function cmdPair() {
44962
45986
  console.log(qr);
44963
45987
  console.log(`scan this QR with the norc mobile app, or enter the code in the norc web app to pair this machine: ${p.display}`);
44964
45988
  } else if (p.phase === "paired") {
44965
- const config = await loadConfig();
44966
- config.device = { machineId: p.machineId, deviceToken: p.deviceToken };
44967
- await saveConfig(config);
45989
+ await savePairedDevice({ machineId: p.machineId, deviceToken: p.deviceToken });
44968
45990
  console.log(`paired. machine id: ${p.machineId}`);
44969
45991
  } else if (p.phase === "expired") {
44970
45992
  console.log("pairing code expired \u2014 run `norc pair` again.");
@@ -44973,6 +45995,80 @@ async function cmdPair() {
44973
45995
  }
44974
45996
  });
44975
45997
  }
45998
+ async function userClient() {
45999
+ const config = await loadConfig();
46000
+ const session = requireUserSession(config);
46001
+ const url = supabaseUrl();
46002
+ const sb = createClient(url, process.env.NORC_SUPABASE_ANON_KEY ?? DEFAULT_SUPABASE_ANON_KEY, { auth: { persistSession: false, autoRefreshToken: false } });
46003
+ const { data, error } = await sb.auth.setSession({ access_token: session.accessToken, refresh_token: session.refreshToken });
46004
+ if (error || !data.session) throw new Error("session expired: run `norc login --email <your-email>` again (the pairing is kept)");
46005
+ if (data.session.access_token !== session.accessToken) {
46006
+ await saveUserSession({ ...session, accessToken: data.session.access_token, refreshToken: data.session.refresh_token });
46007
+ }
46008
+ return sb;
46009
+ }
46010
+ async function saveSession(sb) {
46011
+ const { data: { session } } = await sb.auth.getSession();
46012
+ if (!session) return;
46013
+ const config = await loadConfig();
46014
+ if (!config.session) return;
46015
+ await saveUserSession({ ...config.session, accessToken: session.access_token, refreshToken: session.refresh_token });
46016
+ }
46017
+ async function envDeps() {
46018
+ const sb = await userClient();
46019
+ const url = supabaseUrl();
46020
+ const anon = process.env.NORC_SUPABASE_ANON_KEY ?? DEFAULT_SUPABASE_ANON_KEY;
46021
+ const rl = () => (0, import_promises7.createInterface)({ input: process.stdin, output: process.stdout });
46022
+ return {
46023
+ isTTY: Boolean(process.stdin.isTTY),
46024
+ listVars: async () => {
46025
+ const { data, error } = await sb.from("env_vars").select("id,name,archived_at");
46026
+ if (error) throw new Error(error.message);
46027
+ return (data ?? []).map((r) => ({ id: r.id, name: r.name, archived: r.archived_at != null }));
46028
+ },
46029
+ plan: async () => {
46030
+ const { data, error } = await sb.from("accounts").select("plan, trial_ends_at").limit(1).maybeSingle();
46031
+ const row = data;
46032
+ const p = row?.plan;
46033
+ return error || p !== "free" && p !== "pro" && p !== "power" && p !== "team" ? null : effectivePlan(p, row?.trial_ends_at);
46034
+ },
46035
+ bindingNames: async () => {
46036
+ 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);
46037
+ if (error) throw new Error(error.message);
46038
+ return (data ?? []).map((r) => r.name);
46039
+ },
46040
+ impact: async (name) => {
46041
+ const { data, error } = await sb.rpc("env_var_impact", { p_name: name });
46042
+ if (error) throw new Error(error.message);
46043
+ return data ?? [];
46044
+ },
46045
+ write: async (body) => {
46046
+ const { data: { session } } = await sb.auth.getSession();
46047
+ const res = await fetch(`${url}/functions/v1/env-write`, {
46048
+ method: "POST",
46049
+ headers: { "Content-Type": "application/json", apikey: anon, Authorization: `Bearer ${session?.access_token ?? ""}` },
46050
+ body: JSON.stringify(body)
46051
+ });
46052
+ const json = await res.json().catch(() => ({}));
46053
+ return { status: res.status, body: json };
46054
+ },
46055
+ rpc: async (fn, id) => (await sb.rpc(fn, { p_id: id })).error?.message ?? null,
46056
+ deleteVar: async (id) => {
46057
+ const { error } = await sb.rpc("delete_env_var", { p_id: id });
46058
+ return error ? { message: error.message, code: error.code, hint: error.hint } : null;
46059
+ },
46060
+ ...makeStepUpDeps(sb, fetch, url, anon, () => saveSession(sb)),
46061
+ readSecret: (q) => process.stdin.isTTY ? promptSecret(q) : readStdinValue(process.stdin),
46062
+ // EOF closes the interface; resolve null (cancel) instead of hanging or throwing.
46063
+ readLine: (q) => new Promise((resolve) => {
46064
+ const r = rl();
46065
+ r.once("close", () => resolve(null));
46066
+ r.question(q).then(resolve, () => resolve(null)).finally(() => r.close());
46067
+ }),
46068
+ out: (s) => console.log(s),
46069
+ err: (s) => console.error(s)
46070
+ };
46071
+ }
44976
46072
  async function cmdJobs(args) {
44977
46073
  const [sub, ...rest] = args;
44978
46074
  switch (sub) {
@@ -44988,10 +46084,27 @@ async function cmdJobs(args) {
44988
46084
  return;
44989
46085
  }
44990
46086
  case "add": {
44991
- const [schedule, ...cmdParts] = rest;
44992
- const command = cmdParts.join(" ");
44993
- if (!schedule || !command) throw new Error("usage: norc jobs add <schedule> <command>");
44994
- const job = await addJob(systemCrontabIo, schedule, command);
46087
+ const [schedule, ...parts] = rest;
46088
+ const { command, envNames } = splitTrailingEnv(parts);
46089
+ let user;
46090
+ if (!schedule || !command) throw new Error("usage: norc jobs add <schedule> <command> [--env NAME]... (--env flags go last)");
46091
+ const job = envNames.length === 0 ? await addJob(systemCrontabIo, schedule, command) : await addJobWithEnv(systemCrontabIo, schedule, command, envNames, {
46092
+ prepare: async () => {
46093
+ user = await userClient();
46094
+ },
46095
+ sync: async (extra) => {
46096
+ const url = supabaseUrl();
46097
+ const anon = process.env.NORC_SUPABASE_ANON_KEY ?? DEFAULT_SUPABASE_ANON_KEY;
46098
+ const sess = await deviceSession(url, anon);
46099
+ if (!sess) throw new Error("not paired \u2014 run `norc pair` first");
46100
+ const dev = createClient(url, anon, { auth: { persistSession: false }, global: { headers: { Authorization: `Bearer ${sess.token}` } } });
46101
+ await syncJobs(dev, [...parseCrontab(await systemCrontabIo.read()), ...extra ? [extra] : []]);
46102
+ },
46103
+ bind: async (id, names) => {
46104
+ const { error } = await user.rpc("set_job_env_bindings", { p_job_id: id, p_names: names });
46105
+ if (error) throw new Error(error.message);
46106
+ }
46107
+ });
44995
46108
  console.log(`added job ${job.id}`);
44996
46109
  return;
44997
46110
  }
@@ -45048,12 +46161,26 @@ async function main() {
45048
46161
  return cmdLogin(args);
45049
46162
  case "pair":
45050
46163
  return cmdPair();
46164
+ case "logout": {
46165
+ const had = await logout(void 0, void 0, {
46166
+ signOut: async (sess) => {
46167
+ const sb = createClient(supabaseUrl(), process.env.NORC_SUPABASE_ANON_KEY ?? DEFAULT_SUPABASE_ANON_KEY, { auth: { persistSession: false, autoRefreshToken: false } });
46168
+ await sb.auth.setSession({ access_token: sess.accessToken, refresh_token: sess.refreshToken });
46169
+ await sb.auth.signOut({ scope: "local" });
46170
+ }
46171
+ });
46172
+ console.log(had.session || had.device ? `logged out: removed ${[had.session && "the user session", had.device && "this machine's pairing"].filter(Boolean).join(" and ")}. The machine stays listed in the vault; remove it there. A running norc service stops acting on its own; to remove it, run \`norc service uninstall\`.` : "not logged in; nothing to remove.");
46173
+ return;
46174
+ }
45051
46175
  case "jobs":
45052
46176
  return cmdJobs(args);
46177
+ case "env":
46178
+ process.exitCode = await cmdEnv(args, await envDeps());
46179
+ return;
45053
46180
  case "gitops": {
45054
- const vaultUrl = process.env.NORC_VAULT_URL ?? DEFAULT_VAULT_URL;
46181
+ const vaultUrl2 = vaultUrl();
45055
46182
  const apiKey = process.env.NORC_API_KEY;
45056
- process.exitCode = await cmdGitops(args, { fetchImpl: fetch, readFile: (p) => (0, import_promises6.readFile)(p, "utf8"), vaultUrl, apiKey });
46183
+ process.exitCode = await cmdGitops(args, { fetchImpl: fetch, readFile: (p) => (0, import_promises8.readFile)(p, "utf8"), vaultUrl: vaultUrl2, apiKey });
45057
46184
  return;
45058
46185
  }
45059
46186
  case "run":
@@ -45069,7 +46196,7 @@ async function main() {
45069
46196
  fetchImpl: fetch,
45070
46197
  getJwt: async () => (await deviceSession(base, anonKey))?.token ?? null,
45071
46198
  functionsUrl: `${base}/functions/v1`,
45072
- vaultUrl: process.env.NORC_VAULT_URL ?? DEFAULT_VAULT_URL,
46199
+ vaultUrl: vaultUrl(),
45073
46200
  columns: process.stdout.columns ?? 80,
45074
46201
  isTTY: Boolean(process.stdout.isTTY),
45075
46202
  env: process.env,
@@ -45079,6 +46206,10 @@ async function main() {
45079
46206
  }
45080
46207
  case "bridge":
45081
46208
  return cmdBridge();
46209
+ case "remote": {
46210
+ const config = await loadConfig();
46211
+ return cmdRemote(args, config, (c) => saveConfig(c, void 0, { keys: ["remote"] }));
46212
+ }
45082
46213
  case "service": {
45083
46214
  const [sub] = args;
45084
46215
  if (sub === "install") {