norc-cli 0.1.11 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +4 -0
  2. package/dist/index.js +408 -249
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -72,6 +72,10 @@ NORC_DEBUG=1 norc login
72
72
 
73
73
  Useful for anything that fails with a generic message like `pairing failed (500)` — `--debug` shows the raw server response instead.
74
74
 
75
+ ## End-to-end encryption
76
+
77
+ Everything the norc web, mobile and desktop apps send to `norc bridge` (and its replies) is end-to-end encrypted: ECIES with ECDH P-256 and AES-256-GCM, sealed to this machine's own key. The private key never leaves the machine; it lives in `~/.config/norc/config.json` (mode 0600). Machines must run norc-cli 0.2.0 or later to be reachable; older versions show as "Update required".
78
+
75
79
  ## Background service
76
80
 
77
81
  `norc service install` registers a per-user background service (LaunchAgent on macOS) that runs the bridge daemon automatically. Uninstall it before removing the CLI:
package/dist/index.js CHANGED
@@ -14571,11 +14571,11 @@ var require_dijkstra = __commonJS({
14571
14571
  var predecessors = {};
14572
14572
  var costs = {};
14573
14573
  costs[s] = 0;
14574
- var open2 = dijkstra.PriorityQueue.make();
14575
- open2.push(s, 0);
14574
+ var open3 = dijkstra.PriorityQueue.make();
14575
+ open3.push(s, 0);
14576
14576
  var closest, u, v, cost_of_s_to_u, adjacent_nodes, cost_of_e, cost_of_s_to_u_plus_cost_of_e, cost_of_s_to_v, first_visit;
14577
- while (!open2.empty()) {
14578
- closest = open2.pop();
14577
+ while (!open3.empty()) {
14578
+ closest = open3.pop();
14579
14579
  u = closest.value;
14580
14580
  cost_of_s_to_u = closest.cost;
14581
14581
  adjacent_nodes = graph[u] || {};
@@ -14587,7 +14587,7 @@ var require_dijkstra = __commonJS({
14587
14587
  first_visit = typeof costs[v] === "undefined";
14588
14588
  if (first_visit || cost_of_s_to_v > cost_of_s_to_u_plus_cost_of_e) {
14589
14589
  costs[v] = cost_of_s_to_u_plus_cost_of_e;
14590
- open2.push(v, cost_of_s_to_u_plus_cost_of_e);
14590
+ open3.push(v, cost_of_s_to_u_plus_cost_of_e);
14591
14591
  predecessors[v] = u;
14592
14592
  }
14593
14593
  }
@@ -24572,7 +24572,7 @@ var require_luxon = __commonJS({
24572
24572
  throw new InvalidArgumentError(`Unknown datetime argument: ${dateTimeish}, of type ${typeof dateTimeish}`);
24573
24573
  }
24574
24574
  }
24575
- var VERSION2 = "3.7.2";
24575
+ var VERSION3 = "3.7.2";
24576
24576
  exports2.DateTime = DateTime;
24577
24577
  exports2.Duration = Duration;
24578
24578
  exports2.FixedOffsetZone = FixedOffsetZone;
@@ -24582,7 +24582,7 @@ var require_luxon = __commonJS({
24582
24582
  exports2.InvalidZone = InvalidZone;
24583
24583
  exports2.Settings = Settings;
24584
24584
  exports2.SystemZone = SystemZone;
24585
- exports2.VERSION = VERSION2;
24585
+ exports2.VERSION = VERSION3;
24586
24586
  exports2.Zone = Zone;
24587
24587
  }
24588
24588
  });
@@ -41378,10 +41378,10 @@ function matchStringTarget(hostname2, target) {
41378
41378
  }
41379
41379
  return false;
41380
41380
  }
41381
- function getDefaultPropagationTargets(supabaseUrl) {
41381
+ function getDefaultPropagationTargets(supabaseUrl2) {
41382
41382
  const targets = [];
41383
41383
  try {
41384
- const url = new URL(supabaseUrl);
41384
+ const url = new URL(supabaseUrl2);
41385
41385
  targets.push(url.hostname);
41386
41386
  } catch (error) {
41387
41387
  }
@@ -41447,12 +41447,12 @@ var resolveFetch2 = (customFetch) => {
41447
41447
  var resolveHeadersConstructor = () => {
41448
41448
  return Headers;
41449
41449
  };
41450
- var fetchWithAuth = (supabaseKey, supabaseUrl, getAccessToken, customFetch, tracePropagationOptions) => {
41450
+ var fetchWithAuth = (supabaseKey, supabaseUrl2, getAccessToken, customFetch, tracePropagationOptions) => {
41451
41451
  const fetch$1 = resolveFetch2(customFetch);
41452
41452
  const HeadersConstructor = resolveHeadersConstructor();
41453
41453
  const traceEnabled = (tracePropagationOptions === null || tracePropagationOptions === void 0 ? void 0 : tracePropagationOptions.enabled) === true;
41454
41454
  const respectSampling = (tracePropagationOptions === null || tracePropagationOptions === void 0 ? void 0 : tracePropagationOptions.respectSamplingDecision) !== false;
41455
- const traceTargets = traceEnabled ? getDefaultPropagationTargets(supabaseUrl) : null;
41455
+ const traceTargets = traceEnabled ? getDefaultPropagationTargets(supabaseUrl2) : null;
41456
41456
  return async (input, init) => {
41457
41457
  var _await$getAccessToken;
41458
41458
  const accessToken = (_await$getAccessToken = await getAccessToken()) !== null && _await$getAccessToken !== void 0 ? _await$getAccessToken : supabaseKey;
@@ -41508,8 +41508,8 @@ function applySettingDefaults(options, defaults) {
41508
41508
  else delete result.accessToken;
41509
41509
  return result;
41510
41510
  }
41511
- function validateSupabaseUrl(supabaseUrl) {
41512
- const trimmedUrl = supabaseUrl === null || supabaseUrl === void 0 ? void 0 : supabaseUrl.trim();
41511
+ function validateSupabaseUrl(supabaseUrl2) {
41512
+ const trimmedUrl = supabaseUrl2 === null || supabaseUrl2 === void 0 ? void 0 : supabaseUrl2.trim();
41513
41513
  if (!trimmedUrl) throw new Error("supabaseUrl is required.");
41514
41514
  if (!trimmedUrl.match(/^https?:\/\//i)) throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");
41515
41515
  try {
@@ -41735,11 +41735,11 @@ var SupabaseClient = class {
41735
41735
  * })
41736
41736
  * ```
41737
41737
  */
41738
- constructor(supabaseUrl, supabaseKey, options) {
41738
+ constructor(supabaseUrl2, supabaseKey, options) {
41739
41739
  var _settings$auth$storag, _settings$global$head;
41740
- this.supabaseUrl = supabaseUrl;
41740
+ this.supabaseUrl = supabaseUrl2;
41741
41741
  this.supabaseKey = supabaseKey;
41742
- const baseUrl = validateSupabaseUrl(supabaseUrl);
41742
+ const baseUrl = validateSupabaseUrl(supabaseUrl2);
41743
41743
  if (!supabaseKey) throw new Error("supabaseKey is required.");
41744
41744
  this.realtimeUrl = new URL("realtime/v1", baseUrl);
41745
41745
  this.realtimeUrl.protocol = this.realtimeUrl.protocol.replace("http", "ws");
@@ -41767,7 +41767,7 @@ var SupabaseClient = class {
41767
41767
  throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(prop)} is not possible`);
41768
41768
  } });
41769
41769
  }
41770
- this.fetch = fetchWithAuth(supabaseKey, supabaseUrl, this._getAccessToken.bind(this), settings.global.fetch, settings.tracePropagation);
41770
+ this.fetch = fetchWithAuth(supabaseKey, supabaseUrl2, this._getAccessToken.bind(this), settings.global.fetch, settings.tracePropagation);
41771
41771
  this.realtime = this._initRealtimeClient(_objectSpread23({
41772
41772
  headers: this.headers,
41773
41773
  accessToken: this._getAccessToken.bind(this),
@@ -41951,8 +41951,8 @@ var SupabaseClient = class {
41951
41951
  }
41952
41952
  }
41953
41953
  };
41954
- var createClient = (supabaseUrl, supabaseKey, options) => {
41955
- return new SupabaseClient(supabaseUrl, supabaseKey, options);
41954
+ var createClient = (supabaseUrl2, supabaseKey, options) => {
41955
+ return new SupabaseClient(supabaseUrl2, supabaseKey, options);
41956
41956
  };
41957
41957
  function shouldShowDeprecationWarning() {
41958
41958
  if (typeof window !== "undefined") return false;
@@ -41969,157 +41969,6 @@ if (shouldShowDeprecationWarning()) console.warn("\u26A0\uFE0F Node.js 18 and b
41969
41969
  // src/index.ts
41970
41970
  var import_qrcode = __toESM(require_lib());
41971
41971
 
41972
- // src/supabase-config.ts
41973
- var DEFAULT_SUPABASE_URL = "https://eiuegfdaddrisfboijyy.supabase.co";
41974
- var DEFAULT_SUPABASE_ANON_KEY = "sb_publishable_qGCC0eLvfmXwL86zA1SLHA_q8rFMCcG";
41975
- var DEFAULT_VAULT_URL = "https://vault.norc.app";
41976
-
41977
- // src/config.ts
41978
- var import_promises = require("node:fs/promises");
41979
- var import_node_os = require("node:os");
41980
- var import_node_path = require("node:path");
41981
-
41982
- // src/debug.ts
41983
- var enabled = false;
41984
- function setDebugEnabled(value) {
41985
- enabled = value;
41986
- }
41987
- function isDebugEnabled() {
41988
- return enabled;
41989
- }
41990
- function stripDebugFlag(rawArgs) {
41991
- const sepIndex = rawArgs.indexOf("--");
41992
- const scanLimit = sepIndex === -1 ? rawArgs.length : sepIndex;
41993
- const i = rawArgs.slice(0, scanLimit).indexOf("--debug");
41994
- if (i === -1) return { debug: false, argv: rawArgs };
41995
- return { debug: true, argv: [...rawArgs.slice(0, i), ...rawArgs.slice(i + 1)] };
41996
- }
41997
- function debugLog(...args) {
41998
- if (!enabled) return;
41999
- console.error("[debug]", ...args);
42000
- }
42001
- function redactSecret(value) {
42002
- if (!value) return "(none)";
42003
- if (value.length <= 12) return "***";
42004
- return `${value.slice(0, 12)}\u2026(${value.length} chars)`;
42005
- }
42006
- function redactArgs(args) {
42007
- return args.map((arg, i) => {
42008
- const flag = args[i - 1];
42009
- if (flag === "--key") return redactSecret(arg);
42010
- if (flag === "--email") return "[redacted email]";
42011
- return arg;
42012
- });
42013
- }
42014
- var SENSITIVE_REPLACEMENTS = [
42015
- // Bearer <token> — must run BEFORE the generic key=value pattern below:
42016
- // "Authorization: Bearer xyz" would otherwise match key="Authorization",
42017
- // value="Bearer" only (\S+ stops at the space), leaving the real token
42018
- // after it untouched.
42019
- [/\bBearer\s+\S+/gi, "Bearer [redacted]"],
42020
- // Authorization: <scheme> <credential> — schemes other than Bearer (e.g.
42021
- // "Basic dXNlcjpwYXNz") have a space-separated value too, which the
42022
- // generic \S+ pattern below would truncate at the scheme, leaving the
42023
- // credential itself untouched. `["']?` before the separator tolerates a
42024
- // closing quote intervening before the colon, as in JSON output
42025
- // (`"authorization":"Bearer ..."`).
42026
- [/\b(authorization\s*["']?\s*[:=]\s*)("[^"\n]*"|'[^'\n]*'|\S+(?:\s+\S+)?)/gi, "$1[redacted]"],
42027
- // key=value / key: "value" pairs whose key names something secret. Same
42028
- // `["']?` tolerance — JSON output like `"api_key":"sk-live-..."` or
42029
- // `"access_token": "ya29..."` has a closing quote right before the colon,
42030
- // which the CLI/API responses landing in captured stdout are full of.
42031
- [/\b((?:api[_-]?key|access[_-]?key|access[_-]?token|refresh[_-]?token|secret|token|password|passwd|pwd|credential|private[_-]?key|client[_-]?secret)\s*["']?\s*[:=]\s*)("[^"\n]*"|'[^'\n]*'|\S+)/gi, "$1[redacted]"],
42032
- // scheme://user:password@host — keep the scheme/host, drop the credential.
42033
- [/\b([a-z][a-z0-9+.-]*:\/\/)[^\s:/@]+:[^\s@]+@/gi, "$1[redacted]@"],
42034
- // AWS-style access key ids.
42035
- [/\bAKIA[0-9A-Z]{16}\b/g, "[redacted]"],
42036
- // JWT-shaped three-part base64url tokens.
42037
- [/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g, "[redacted]"],
42038
- // PEM private key blocks, in full (may legitimately span many lines).
42039
- [/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, "[redacted private key]"],
42040
- // Opaque secret-token prefixes that no key-name pattern above catches —
42041
- // these are self-identifying regardless of what (if anything) precedes
42042
- // them, so they're matched on the token value itself: GitHub personal
42043
- // access tokens, OpenAI/Stripe-style secret keys, Slack tokens.
42044
- [/\bghp_[A-Za-z0-9]{20,}\b/g, "[redacted]"],
42045
- [/\bsk-[A-Za-z0-9-]{10,}\b/g, "[redacted]"],
42046
- [/\bsk_live_[A-Za-z0-9]{10,}\b/g, "[redacted]"],
42047
- [/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g, "[redacted]"],
42048
- // norc's own API key format (norc_sk_<base64url>, actions.ts:10) — the
42049
- // key=value pattern above only catches these behind a recognized field
42050
- // name; a bare key printed on its own line (e.g. a script that echoes it)
42051
- // needs its own self-identifying match, same as the other prefixes above.
42052
- [/\bnorc_sk_[A-Za-z0-9_-]{16,}\b/g, "[redacted]"]
42053
- ];
42054
- function redactSensitiveOutput(text) {
42055
- let out = text;
42056
- for (const [pattern, replacement] of SENSITIVE_REPLACEMENTS) out = out.replace(pattern, replacement);
42057
- return out;
42058
- }
42059
-
42060
- // src/config.ts
42061
- function configPath() {
42062
- return (0, import_node_path.join)((0, import_node_os.homedir)(), ".config", "norc", "config.json");
42063
- }
42064
- async function loadConfig(path = configPath()) {
42065
- try {
42066
- const config = JSON.parse(await (0, import_promises.readFile)(path, "utf8"));
42067
- debugLog("config: loaded", path, "\u2014 has session:", Boolean(config.session), "has device:", Boolean(config.device));
42068
- return config;
42069
- } catch (e) {
42070
- debugLog("config: no existing config at", path, "(", e instanceof Error ? e.message : String(e), ") \u2014 starting empty");
42071
- return {};
42072
- }
42073
- }
42074
- async function saveConfig(config, path = configPath()) {
42075
- await (0, import_promises.mkdir)((0, import_node_path.join)(path, ".."), { recursive: true, mode: 448 });
42076
- await (0, import_promises.writeFile)(path, JSON.stringify(config, null, 2), { mode: 384 });
42077
- debugLog("config: saved", path, "\u2014 has session:", Boolean(config.session), "has device:", Boolean(config.device));
42078
- }
42079
-
42080
- // src/crontab-io.ts
42081
- var import_node_child_process = require("node:child_process");
42082
- var systemCrontabIo = {
42083
- read() {
42084
- return new Promise((resolve, reject) => {
42085
- (0, import_node_child_process.execFile)("crontab", ["-l"], (err, stdout, stderr) => {
42086
- if (err) {
42087
- if (/no crontab/i.test(stderr)) return resolve("");
42088
- return reject(new Error(stderr.trim() || err.message));
42089
- }
42090
- resolve(stdout);
42091
- });
42092
- });
42093
- },
42094
- write(contents) {
42095
- return new Promise((resolve, reject) => {
42096
- const child = (0, import_node_child_process.execFile)("crontab", ["-"], { timeout: 15e3 }, (err, _stdout, stderr) => {
42097
- if (err) return reject(new Error(stderr.trim() || err.message));
42098
- resolve();
42099
- });
42100
- child.stdin.end(contents.endsWith("\n") ? contents : `${contents}
42101
- `);
42102
- });
42103
- }
42104
- };
42105
-
42106
- // src/commands/login.ts
42107
- async function requestLogin(client, email) {
42108
- const start = await client.auth.signInWithOtp({ email, options: { shouldCreateUser: false } });
42109
- if (start.error) return { ok: false, message: start.error.message };
42110
- return { ok: true };
42111
- }
42112
- async function verifyLogin(client, email, code) {
42113
- const verified = await client.auth.verifyOtp({ email, token: code, type: "email" });
42114
- if (verified.error) return { ok: false, message: verified.error.message };
42115
- if (!verified.data.session) return { ok: false, message: "no session returned" };
42116
- return {
42117
- ok: true,
42118
- accessToken: verified.data.session.access_token,
42119
- refreshToken: verified.data.session.refresh_token
42120
- };
42121
- }
42122
-
42123
41972
  // ../../packages/cron/src/macros.ts
42124
41973
  var CRON_MACROS = {
42125
41974
  "@yearly": "0 0 1 1 *",
@@ -42578,9 +42427,9 @@ async function handleMessage(io, data, allow) {
42578
42427
  return JSON.stringify(reply);
42579
42428
  }
42580
42429
  function serveBridge(transport, io, opts) {
42581
- transport.onMessage(async (data) => {
42430
+ transport.onMessage(async (data, respond) => {
42582
42431
  const out = await handleMessage(io, data, opts?.allow);
42583
- if (out !== null) transport.send(out);
42432
+ if (out !== null) (respond ?? ((o) => transport.send(o)))(out);
42584
42433
  });
42585
42434
  }
42586
42435
 
@@ -42771,6 +42620,323 @@ async function handleRawWriteIntent(msg, d) {
42771
42620
  return { applied: true, nextHash: intentHash };
42772
42621
  }
42773
42622
 
42623
+ // ../../packages/bridge/src/crypto.ts
42624
+ var VERSION = 1;
42625
+ var ECDH = { name: "ECDH", namedCurve: "P-256" };
42626
+ function b64url(bytes) {
42627
+ let bin = "";
42628
+ for (const b of bytes) bin += String.fromCharCode(b);
42629
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
42630
+ }
42631
+ function unb64url(s) {
42632
+ const pad = s.length % 4 === 0 ? "" : "=".repeat(4 - s.length % 4);
42633
+ const bin = atob(s.replace(/-/g, "+").replace(/_/g, "/") + pad);
42634
+ const out = new Uint8Array(bin.length);
42635
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
42636
+ return out;
42637
+ }
42638
+ function clean(jwk) {
42639
+ const out = { kty: "EC", crv: "P-256", x: jwk.x, y: jwk.y };
42640
+ if (jwk.d !== void 0) out.d = jwk.d;
42641
+ return out;
42642
+ }
42643
+ function isEcPublicJwk(v) {
42644
+ const k = v;
42645
+ return !!k && k.kty === "EC" && k.crv === "P-256" && typeof k.x === "string" && typeof k.y === "string" && k.x.length === 43 && k.y.length === 43 && /^[A-Za-z0-9_-]+$/.test(k.x) && /^[A-Za-z0-9_-]+$/.test(k.y);
42646
+ }
42647
+ async function generateKeyPair() {
42648
+ const pair = await crypto.subtle.generateKey(ECDH, true, ["deriveBits"]);
42649
+ const publicJwk = clean(await crypto.subtle.exportKey("jwk", pair.publicKey));
42650
+ const privateJwk = clean(await crypto.subtle.exportKey("jwk", pair.privateKey));
42651
+ return { publicJwk, privateJwk };
42652
+ }
42653
+ async function thumbprint(pub) {
42654
+ const canonical = `{"crv":"P-256","kty":"EC","x":"${pub.x}","y":"${pub.y}"}`;
42655
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonical));
42656
+ return b64url(new Uint8Array(digest));
42657
+ }
42658
+ async function deriveKey(privateJwk, peerPublicJwk, machineId, event, direction) {
42659
+ const priv = await crypto.subtle.importKey("jwk", clean(privateJwk), ECDH, false, ["deriveBits"]);
42660
+ const pub = await crypto.subtle.importKey("jwk", clean({ ...peerPublicJwk, d: void 0 }), ECDH, false, []);
42661
+ const secret = await crypto.subtle.deriveBits({ name: "ECDH", public: pub }, priv, 256);
42662
+ const hkdfKey = await crypto.subtle.importKey("raw", secret, "HKDF", false, ["deriveKey"]);
42663
+ return crypto.subtle.deriveKey(
42664
+ {
42665
+ name: "HKDF",
42666
+ hash: "SHA-256",
42667
+ salt: new Uint8Array(0),
42668
+ info: new TextEncoder().encode(`norc-bridge-v${VERSION}|${machineId}|${event}|${direction}`)
42669
+ },
42670
+ hkdfKey,
42671
+ { name: "AES-GCM", length: 256 },
42672
+ false,
42673
+ ["encrypt", "decrypt"]
42674
+ );
42675
+ }
42676
+ var aad = (machineId, event) => new TextEncoder().encode(`${machineId}|${event}`);
42677
+ async function seal(plaintext, o) {
42678
+ const sender = o.senderKey ?? await generateKeyPair();
42679
+ const key = await deriveKey(sender.privateJwk, o.recipientPublicJwk, o.machineId, o.event, o.direction);
42680
+ const iv = o.testIv ?? crypto.getRandomValues(new Uint8Array(12));
42681
+ const ct = await crypto.subtle.encrypt(
42682
+ { name: "AES-GCM", iv, additionalData: aad(o.machineId, o.event) },
42683
+ key,
42684
+ new TextEncoder().encode(plaintext)
42685
+ );
42686
+ const env = {
42687
+ v: VERSION,
42688
+ kid: await thumbprint(o.recipientPublicJwk),
42689
+ epk: clean({ ...sender.publicJwk, d: void 0 }),
42690
+ iv: b64url(iv),
42691
+ ct: b64url(new Uint8Array(ct))
42692
+ };
42693
+ return JSON.stringify(env);
42694
+ }
42695
+ async function open(payload, o) {
42696
+ try {
42697
+ const env = JSON.parse(payload);
42698
+ if (!env || env.v !== VERSION || typeof env.kid !== "string" || typeof env.iv !== "string" || typeof env.ct !== "string" || !isEcPublicJwk(env.epk)) return null;
42699
+ if (env.kid !== await thumbprint(o.recipient.publicJwk)) return null;
42700
+ const iv = unb64url(env.iv);
42701
+ if (iv.length !== 12) return null;
42702
+ const key = await deriveKey(o.recipient.privateJwk, env.epk, o.machineId, o.event, o.direction);
42703
+ const pt = await crypto.subtle.decrypt(
42704
+ { name: "AES-GCM", iv, additionalData: aad(o.machineId, o.event) },
42705
+ key,
42706
+ unb64url(env.ct)
42707
+ );
42708
+ return { plaintext: new TextDecoder().decode(pt), senderPublicJwk: clean({ ...env.epk, d: void 0 }) };
42709
+ } catch {
42710
+ return null;
42711
+ }
42712
+ }
42713
+
42714
+ // ../../packages/bridge/src/secure-url.ts
42715
+ var LOCAL_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
42716
+ function assertSecureUrl(url, opts = {}) {
42717
+ const fail = () => new Error(`Supabase URL must use https:// (got ${JSON.stringify(url ?? null)})`);
42718
+ if (!url) throw fail();
42719
+ let parsed;
42720
+ try {
42721
+ parsed = new URL(url);
42722
+ } catch {
42723
+ throw fail();
42724
+ }
42725
+ if (parsed.protocol === "https:") return url;
42726
+ if (opts.allowLocalDev && parsed.protocol === "http:" && LOCAL_HOSTS.has(parsed.hostname)) return url;
42727
+ throw fail();
42728
+ }
42729
+
42730
+ // ../../packages/bridge/src/secure-channel.ts
42731
+ function secureMachineChannel(channel, opts) {
42732
+ const { machineId, keyPair, onDrop } = opts;
42733
+ let chain = Promise.resolve();
42734
+ return {
42735
+ on(event, cb) {
42736
+ channel.on("broadcast", { event }, ({ payload }) => {
42737
+ chain = chain.then(
42738
+ () => open(payload, { machineId, event, direction: "to-machine", recipient: keyPair }).then((o) => {
42739
+ if (!o) {
42740
+ onDrop?.(event);
42741
+ return;
42742
+ }
42743
+ cb(o.plaintext, o.senderPublicJwk);
42744
+ })
42745
+ ).catch(() => {
42746
+ try {
42747
+ onDrop?.(event);
42748
+ } catch {
42749
+ }
42750
+ });
42751
+ });
42752
+ },
42753
+ async send(event, plaintext, to) {
42754
+ const payload = await seal(plaintext, { machineId, event, direction: "to-client", recipientPublicJwk: to });
42755
+ await channel.send({ type: "broadcast", event, payload });
42756
+ }
42757
+ };
42758
+ }
42759
+
42760
+ // ../../packages/bridge/src/sealed-transport.ts
42761
+ var SealedBridgeTransport = class {
42762
+ constructor(sec) {
42763
+ this.sec = sec;
42764
+ }
42765
+ send() {
42766
+ throw new Error("SealedBridgeTransport replies through respond(), not send()");
42767
+ }
42768
+ onMessage(handler) {
42769
+ this.sec.on("req", (plaintext, from) => {
42770
+ handler(plaintext, (out) => {
42771
+ void this.sec.send("reply", out, from).catch((e) => console.warn("[norc bridge] reply send failed", e));
42772
+ });
42773
+ });
42774
+ }
42775
+ };
42776
+
42777
+ // src/supabase-config.ts
42778
+ var DEFAULT_SUPABASE_URL = "https://eiuegfdaddrisfboijyy.supabase.co";
42779
+ var DEFAULT_SUPABASE_ANON_KEY = "sb_publishable_qGCC0eLvfmXwL86zA1SLHA_q8rFMCcG";
42780
+ function checkedSupabaseUrl(url) {
42781
+ return assertSecureUrl(url, { allowLocalDev: process.env.NORC_ALLOW_INSECURE_LOCAL === "1" });
42782
+ }
42783
+ function supabaseUrl() {
42784
+ return checkedSupabaseUrl(process.env.NORC_SUPABASE_URL ?? DEFAULT_SUPABASE_URL);
42785
+ }
42786
+ var DEFAULT_VAULT_URL = "https://vault.norc.app";
42787
+
42788
+ // src/config.ts
42789
+ var import_promises = require("node:fs/promises");
42790
+ var import_node_os = require("node:os");
42791
+ var import_node_path = require("node:path");
42792
+
42793
+ // src/debug.ts
42794
+ var enabled = false;
42795
+ function setDebugEnabled(value) {
42796
+ enabled = value;
42797
+ }
42798
+ function isDebugEnabled() {
42799
+ return enabled;
42800
+ }
42801
+ function stripDebugFlag(rawArgs) {
42802
+ const sepIndex = rawArgs.indexOf("--");
42803
+ const scanLimit = sepIndex === -1 ? rawArgs.length : sepIndex;
42804
+ const i = rawArgs.slice(0, scanLimit).indexOf("--debug");
42805
+ if (i === -1) return { debug: false, argv: rawArgs };
42806
+ return { debug: true, argv: [...rawArgs.slice(0, i), ...rawArgs.slice(i + 1)] };
42807
+ }
42808
+ function debugLog(...args) {
42809
+ if (!enabled) return;
42810
+ console.error("[debug]", ...args);
42811
+ }
42812
+ function redactSecret(value) {
42813
+ if (!value) return "(none)";
42814
+ if (value.length <= 12) return "***";
42815
+ return `${value.slice(0, 12)}\u2026(${value.length} chars)`;
42816
+ }
42817
+ function redactArgs(args) {
42818
+ return args.map((arg, i) => {
42819
+ const flag = args[i - 1];
42820
+ if (flag === "--key") return redactSecret(arg);
42821
+ if (flag === "--email") return "[redacted email]";
42822
+ return arg;
42823
+ });
42824
+ }
42825
+ var SENSITIVE_REPLACEMENTS = [
42826
+ // Bearer <token> — must run BEFORE the generic key=value pattern below:
42827
+ // "Authorization: Bearer xyz" would otherwise match key="Authorization",
42828
+ // value="Bearer" only (\S+ stops at the space), leaving the real token
42829
+ // after it untouched.
42830
+ [/\bBearer\s+\S+/gi, "Bearer [redacted]"],
42831
+ // Authorization: <scheme> <credential> — schemes other than Bearer (e.g.
42832
+ // "Basic dXNlcjpwYXNz") have a space-separated value too, which the
42833
+ // generic \S+ pattern below would truncate at the scheme, leaving the
42834
+ // credential itself untouched. `["']?` before the separator tolerates a
42835
+ // closing quote intervening before the colon, as in JSON output
42836
+ // (`"authorization":"Bearer ..."`).
42837
+ [/\b(authorization\s*["']?\s*[:=]\s*)("[^"\n]*"|'[^'\n]*'|\S+(?:\s+\S+)?)/gi, "$1[redacted]"],
42838
+ // key=value / key: "value" pairs whose key names something secret. Same
42839
+ // `["']?` tolerance — JSON output like `"api_key":"sk-live-..."` or
42840
+ // `"access_token": "ya29..."` has a closing quote right before the colon,
42841
+ // which the CLI/API responses landing in captured stdout are full of.
42842
+ [/\b((?:api[_-]?key|access[_-]?key|access[_-]?token|refresh[_-]?token|secret|token|password|passwd|pwd|credential|private[_-]?key|client[_-]?secret)\s*["']?\s*[:=]\s*)("[^"\n]*"|'[^'\n]*'|\S+)/gi, "$1[redacted]"],
42843
+ // scheme://user:password@host — keep the scheme/host, drop the credential.
42844
+ [/\b([a-z][a-z0-9+.-]*:\/\/)[^\s:/@]+:[^\s@]+@/gi, "$1[redacted]@"],
42845
+ // AWS-style access key ids.
42846
+ [/\bAKIA[0-9A-Z]{16}\b/g, "[redacted]"],
42847
+ // JWT-shaped three-part base64url tokens.
42848
+ [/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g, "[redacted]"],
42849
+ // PEM private key blocks, in full (may legitimately span many lines).
42850
+ [/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, "[redacted private key]"],
42851
+ // Opaque secret-token prefixes that no key-name pattern above catches —
42852
+ // these are self-identifying regardless of what (if anything) precedes
42853
+ // them, so they're matched on the token value itself: GitHub personal
42854
+ // access tokens, OpenAI/Stripe-style secret keys, Slack tokens.
42855
+ [/\bghp_[A-Za-z0-9]{20,}\b/g, "[redacted]"],
42856
+ [/\bsk-[A-Za-z0-9-]{10,}\b/g, "[redacted]"],
42857
+ [/\bsk_live_[A-Za-z0-9]{10,}\b/g, "[redacted]"],
42858
+ [/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g, "[redacted]"],
42859
+ // norc's own API key format (norc_sk_<base64url>, actions.ts:10) — the
42860
+ // key=value pattern above only catches these behind a recognized field
42861
+ // name; a bare key printed on its own line (e.g. a script that echoes it)
42862
+ // needs its own self-identifying match, same as the other prefixes above.
42863
+ [/\bnorc_sk_[A-Za-z0-9_-]{16,}\b/g, "[redacted]"]
42864
+ ];
42865
+ function redactSensitiveOutput(text) {
42866
+ let out = text;
42867
+ for (const [pattern, replacement] of SENSITIVE_REPLACEMENTS) out = out.replace(pattern, replacement);
42868
+ return out;
42869
+ }
42870
+
42871
+ // src/config.ts
42872
+ function configPath() {
42873
+ return (0, import_node_path.join)((0, import_node_os.homedir)(), ".config", "norc", "config.json");
42874
+ }
42875
+ async function loadConfig(path = configPath()) {
42876
+ try {
42877
+ const config = JSON.parse(await (0, import_promises.readFile)(path, "utf8"));
42878
+ debugLog("config: loaded", path, "\u2014 has session:", Boolean(config.session), "has device:", Boolean(config.device));
42879
+ return config;
42880
+ } catch (e) {
42881
+ debugLog("config: no existing config at", path, "(", e instanceof Error ? e.message : String(e), ") \u2014 starting empty");
42882
+ return {};
42883
+ }
42884
+ }
42885
+ async function saveConfig(config, path = configPath()) {
42886
+ const dir = (0, import_node_path.join)(path, "..");
42887
+ await (0, import_promises.mkdir)(dir, { recursive: true, mode: 448 });
42888
+ await (0, import_promises.chmod)(dir, 448);
42889
+ await (0, import_promises.chmod)(path, 384).catch((e) => {
42890
+ if (e.code !== "ENOENT") throw e;
42891
+ });
42892
+ await (0, import_promises.writeFile)(path, JSON.stringify(config, null, 2), { mode: 384 });
42893
+ await (0, import_promises.chmod)(path, 384);
42894
+ debugLog("config: saved", path, "\u2014 has session:", Boolean(config.session), "has device:", Boolean(config.device));
42895
+ }
42896
+
42897
+ // src/crontab-io.ts
42898
+ var import_node_child_process = require("node:child_process");
42899
+ var systemCrontabIo = {
42900
+ read() {
42901
+ return new Promise((resolve, reject) => {
42902
+ (0, import_node_child_process.execFile)("crontab", ["-l"], (err, stdout, stderr) => {
42903
+ if (err) {
42904
+ if (/no crontab/i.test(stderr)) return resolve("");
42905
+ return reject(new Error(stderr.trim() || err.message));
42906
+ }
42907
+ resolve(stdout);
42908
+ });
42909
+ });
42910
+ },
42911
+ write(contents) {
42912
+ return new Promise((resolve, reject) => {
42913
+ const child = (0, import_node_child_process.execFile)("crontab", ["-"], { timeout: 15e3 }, (err, _stdout, stderr) => {
42914
+ if (err) return reject(new Error(stderr.trim() || err.message));
42915
+ resolve();
42916
+ });
42917
+ child.stdin.end(contents.endsWith("\n") ? contents : `${contents}
42918
+ `);
42919
+ });
42920
+ }
42921
+ };
42922
+
42923
+ // src/commands/login.ts
42924
+ async function requestLogin(client, email) {
42925
+ const start = await client.auth.signInWithOtp({ email, options: { shouldCreateUser: false } });
42926
+ if (start.error) return { ok: false, message: start.error.message };
42927
+ return { ok: true };
42928
+ }
42929
+ async function verifyLogin(client, email, code) {
42930
+ const verified = await client.auth.verifyOtp({ email, token: code, type: "email" });
42931
+ if (verified.error) return { ok: false, message: verified.error.message };
42932
+ if (!verified.data.session) return { ok: false, message: "no session returned" };
42933
+ return {
42934
+ ok: true,
42935
+ accessToken: verified.data.session.access_token,
42936
+ refreshToken: verified.data.session.refresh_token
42937
+ };
42938
+ }
42939
+
42774
42940
  // src/host-info.ts
42775
42941
  var import_node_os2 = require("node:os");
42776
42942
  function normalizeArch(raw) {
@@ -43245,6 +43411,11 @@ function tailRunsMessage() {
43245
43411
  return 'norc runs --tail: not available yet \u2014 run-capture/sync to the cloud is not implemented (see shinpo notes on "runs-capture deferred"). Nothing to tail.';
43246
43412
  }
43247
43413
 
43414
+ // src/child-env.ts
43415
+ function withoutPkgEnv(command, platform = process.platform) {
43416
+ return platform === "win32" ? `set "PKG_EXECPATH=" && ${command}` : `unset PKG_EXECPATH; ${command}`;
43417
+ }
43418
+
43248
43419
  // src/commands/run.ts
43249
43420
  var import_node_child_process3 = require("node:child_process");
43250
43421
 
@@ -43256,7 +43427,7 @@ var import_node_os3 = require("node:os");
43256
43427
  var import_node_path2 = require("node:path");
43257
43428
 
43258
43429
  // src/version.ts
43259
- var VERSION = "0.1.11";
43430
+ var VERSION2 = "0.2.1";
43260
43431
 
43261
43432
  // src/host-details.ts
43262
43433
  var ARCH = { x64: "x86_64", arm64: "arm64", ia32: "x86", arm: "arm" };
@@ -43307,19 +43478,26 @@ function osNameUncached(platform) {
43307
43478
  }
43308
43479
  return void 0;
43309
43480
  }
43481
+ function bootedAt() {
43482
+ try {
43483
+ return new Date(Math.round((Date.now() - (0, import_node_os3.uptime)() * 1e3) / 6e4) * 6e4).toISOString();
43484
+ } catch {
43485
+ return void 0;
43486
+ }
43487
+ }
43310
43488
  var cached;
43311
43489
  function hostDetails() {
43312
- cached ??= { os: osName(process.platform), arch: ARCH[process.arch] ?? process.arch, agent_version: `norc-cli ${VERSION}` };
43490
+ cached ??= { os: osName(process.platform), arch: ARCH[process.arch] ?? process.arch, agent_version: `norc-cli ${VERSION2}`, booted_at: bootedAt() };
43313
43491
  return cached;
43314
43492
  }
43315
43493
 
43316
43494
  // src/device-session.ts
43317
- async function deviceSession(supabaseUrl, anonKey, signal) {
43495
+ async function deviceSession(supabaseUrl2, anonKey, signal, encPublicJwk) {
43318
43496
  const config = await loadConfig();
43319
43497
  const token = config.device?.deviceToken;
43320
43498
  if (!token) return null;
43321
43499
  try {
43322
- const res = await fetch(`${supabaseUrl}/functions/v1/device-session`, {
43500
+ const res = await fetch(`${checkedSupabaseUrl(supabaseUrl2)}/functions/v1/device-session`, {
43323
43501
  method: "POST",
43324
43502
  headers: { "Content-Type": "application/json", apikey: anonKey },
43325
43503
  // job_timezone_handling (roadmap #7): best-effort, piggybacked on this
@@ -43327,7 +43505,12 @@ async function deviceSession(supabaseUrl, anonKey, signal) {
43327
43505
  // Node's global Intl covers this, same as the browser-embedded runtime
43328
43506
  // desktop's copy of this call runs in — no import needed.
43329
43507
  // Machine details (0062): OS, arch and agent version, same piggyback.
43330
- body: JSON.stringify({ token, timezone: Intl.DateTimeFormat().resolvedOptions().timeZone, ...hostDetails() }),
43508
+ body: JSON.stringify({
43509
+ token,
43510
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
43511
+ ...hostDetails(),
43512
+ ...encPublicJwk ? { enc_public_jwk: encPublicJwk } : {}
43513
+ }),
43331
43514
  signal
43332
43515
  });
43333
43516
  if (!res.ok) return null;
@@ -43495,7 +43678,7 @@ function decodeOutputTail(tail) {
43495
43678
  }
43496
43679
  function realSpawnCommand(command) {
43497
43680
  return new Promise((resolve) => {
43498
- const child = (0, import_node_child_process3.spawn)(command.join(" "), { stdio: ["inherit", "pipe", "pipe"], shell: true });
43681
+ const child = (0, import_node_child_process3.spawn)(withoutPkgEnv(command.join(" ")), { stdio: ["inherit", "pipe", "pipe"], shell: true });
43499
43682
  let tail = Buffer.alloc(0);
43500
43683
  let outputTail = Buffer.alloc(0);
43501
43684
  child.stdout?.on("data", (chunk) => {
@@ -43522,7 +43705,7 @@ function fetchTimeout() {
43522
43705
  return AbortSignal.timeout(FETCH_TIMEOUT_MS);
43523
43706
  }
43524
43707
  var SESSION_REFRESH_BUFFER_MS = 6e4;
43525
- function createSessionCache(url, anonKey) {
43708
+ function createSessionCache(anonKey) {
43526
43709
  let sessionPromise;
43527
43710
  return async function getSession() {
43528
43711
  if (sessionPromise) {
@@ -43530,19 +43713,18 @@ function createSessionCache(url, anonKey) {
43530
43713
  const expiresAt = cached2 ? new Date(cached2.expires_at).getTime() : 0;
43531
43714
  if (!cached2 || expiresAt - Date.now() < SESSION_REFRESH_BUFFER_MS) sessionPromise = void 0;
43532
43715
  }
43533
- sessionPromise ??= deviceSession(url, anonKey, fetchTimeout());
43716
+ sessionPromise ??= deviceSession(supabaseUrl(), anonKey, fetchTimeout());
43534
43717
  return sessionPromise;
43535
43718
  };
43536
43719
  }
43537
43720
  function createReporter(getSession) {
43538
- const url = process.env.NORC_SUPABASE_URL ?? DEFAULT_SUPABASE_URL;
43539
43721
  const anonKey = process.env.NORC_SUPABASE_ANON_KEY ?? DEFAULT_SUPABASE_ANON_KEY;
43540
- const sessionFor = getSession ?? createSessionCache(url, anonKey);
43722
+ const sessionFor = getSession ?? createSessionCache(anonKey);
43541
43723
  return async function report(run) {
43542
43724
  const session = await sessionFor();
43543
43725
  if (!session) return false;
43544
43726
  try {
43545
- const res = await fetch(`${url}/functions/v1/run-report`, {
43727
+ const res = await fetch(`${supabaseUrl()}/functions/v1/run-report`, {
43546
43728
  method: "POST",
43547
43729
  headers: { "Content-Type": "application/json", apikey: anonKey, Authorization: `Bearer ${session.token}` },
43548
43730
  body: JSON.stringify({
@@ -43564,14 +43746,13 @@ function createReporter(getSession) {
43564
43746
  };
43565
43747
  }
43566
43748
  function createBackfillClaimer(getSession) {
43567
- const url = process.env.NORC_SUPABASE_URL ?? DEFAULT_SUPABASE_URL;
43568
43749
  const anonKey = process.env.NORC_SUPABASE_ANON_KEY ?? DEFAULT_SUPABASE_ANON_KEY;
43569
- const sessionFor = getSession ?? createSessionCache(url, anonKey);
43750
+ const sessionFor = getSession ?? createSessionCache(anonKey);
43570
43751
  return async function claimBackfills(jobId) {
43571
43752
  const session = await sessionFor();
43572
43753
  if (!session) return [];
43573
43754
  try {
43574
- const res = await fetch(`${url}/functions/v1/backfill-claim`, {
43755
+ const res = await fetch(`${supabaseUrl()}/functions/v1/backfill-claim`, {
43575
43756
  method: "POST",
43576
43757
  headers: { "Content-Type": "application/json", apikey: anonKey, Authorization: `Bearer ${session.token}` },
43577
43758
  body: JSON.stringify({ job_id: jobId }),
@@ -43594,10 +43775,7 @@ async function cmdRun(args) {
43594
43775
  const jobId = args[jobIdFlagIndex + 1];
43595
43776
  const command = args.slice(sepIndex + 1);
43596
43777
  if (!jobId || command.length === 0) throw new Error("usage: norc run --job-id <id> -- <command>");
43597
- const getSession = createSessionCache(
43598
- process.env.NORC_SUPABASE_URL ?? DEFAULT_SUPABASE_URL,
43599
- process.env.NORC_SUPABASE_ANON_KEY ?? DEFAULT_SUPABASE_ANON_KEY
43600
- );
43778
+ const getSession = createSessionCache(process.env.NORC_SUPABASE_ANON_KEY ?? DEFAULT_SUPABASE_ANON_KEY);
43601
43779
  return runWrapped(
43602
43780
  {
43603
43781
  spawnCommand: realSpawnCommand,
@@ -43616,22 +43794,14 @@ async function cmdRun(args) {
43616
43794
  // src/commands/bridge.ts
43617
43795
  var import_node_child_process5 = require("node:child_process");
43618
43796
 
43619
- // src/realtime-transport.ts
43620
- var RealtimeBridgeTransport = class {
43621
- constructor(channel) {
43622
- this.channel = channel;
43623
- }
43624
- send(data) {
43625
- console.log("[norc bridge] transport.send reply:", data.slice(0, 200));
43626
- void this.channel.send({ type: "broadcast", event: "reply", payload: data });
43627
- }
43628
- onMessage(handler) {
43629
- this.channel.on("broadcast", { event: "req" }, (p) => {
43630
- console.log("[norc bridge] transport.onMessage req:", (p.payload ?? "").slice(0, 200));
43631
- handler(p.payload);
43632
- });
43633
- }
43634
- };
43797
+ // src/enc-key.ts
43798
+ async function loadOrCreateEncKey(config, persist) {
43799
+ const k = config.enc;
43800
+ if (k && isEcPublicJwk(k.publicJwk) && typeof k.privateJwk?.d === "string") return k;
43801
+ config.enc = await generateKeyPair();
43802
+ await persist();
43803
+ return config.enc;
43804
+ }
43635
43805
 
43636
43806
  // src/capability-key.ts
43637
43807
  var CAPABILITY_PUBLIC_JWK = {
@@ -43814,7 +43984,7 @@ function pruneExpiredExecuteNonces(nonces, nowSec) {
43814
43984
  }
43815
43985
  function spawnWrappedCommand(command) {
43816
43986
  return new Promise((resolve, reject) => {
43817
- const child = (0, import_node_child_process5.spawn)(command, { shell: true, detached: true, stdio: "ignore" });
43987
+ const child = (0, import_node_child_process5.spawn)(withoutPkgEnv(command), { shell: true, detached: true, stdio: "ignore" });
43818
43988
  child.once("spawn", () => {
43819
43989
  child.unref();
43820
43990
  resolve();
@@ -43850,6 +44020,7 @@ async function runBridge(env, crontabIo) {
43850
44020
  });
43851
44021
  return save;
43852
44022
  };
44023
+ const keyPair = await loadOrCreateEncKey(config, persistConfig);
43853
44024
  let state = "disconnected";
43854
44025
  let attempt = 0;
43855
44026
  while (true) {
@@ -43860,7 +44031,7 @@ async function runBridge(env, crontabIo) {
43860
44031
  const enqueueMutation = serialize();
43861
44032
  try {
43862
44033
  state = reduceConn(state, "connect");
43863
- const sess = await deviceSession(env.supabaseUrl, env.anonKey);
44034
+ const sess = await deviceSession(env.supabaseUrl, env.anonKey, void 0, keyPair.publicJwk);
43864
44035
  if (!sess) {
43865
44036
  console.error("[norc bridge] device session mint failed");
43866
44037
  await wait(backoffDelay(attempt++));
@@ -43875,11 +44046,15 @@ async function runBridge(env, crontabIo) {
43875
44046
  const channel = sb.channel(`machine:${sess.machine_id}`, {
43876
44047
  config: { private: true, broadcast: { self: false }, presence: { key: sess.machine_id } }
43877
44048
  });
43878
- serveBridge(new RealtimeBridgeTransport(channel), lineChanges.io, { allow: [...READ_ONLY] });
44049
+ const sec = secureMachineChannel(channel, {
44050
+ machineId: sess.machine_id,
44051
+ keyPair,
44052
+ onDrop: (event) => console.warn("[norc bridge] dropped unauthenticated relay payload on", event)
44053
+ });
44054
+ serveBridge(new SealedBridgeTransport(sec), lineChanges.io, { allow: [...READ_ONLY] });
43879
44055
  const deps = buildWriteIntentDeps(config, machineId, crontabIo, () => void persistConfig());
43880
44056
  const rawDeps = buildRawWriteIntentDeps(config, machineId, crontabIo, () => void persistConfig());
43881
- const bcast = channel;
43882
- bcast.on("broadcast", { event: "write-intent" }, ({ payload }) => {
44057
+ sec.on("write-intent", (payload, from) => {
43883
44058
  let msg;
43884
44059
  try {
43885
44060
  msg = JSON.parse(payload);
@@ -43889,18 +44064,14 @@ async function runBridge(env, crontabIo) {
43889
44064
  enqueueMutation(() => handleWriteIntent(msg, deps).then((r) => {
43890
44065
  if (r.applied) {
43891
44066
  console.log("[norc bridge] write-intent applied");
43892
- void bcast.send({
43893
- type: "broadcast",
43894
- event: "write-applied",
43895
- payload: JSON.stringify({ jobIds: msg.jobs.map((j) => j.id) })
43896
- });
44067
+ void sec.send("write-applied", JSON.stringify({ jobIds: msg.jobs.map((j) => j.id) }), from);
43897
44068
  queueSyncJobs();
43898
44069
  } else {
43899
44070
  console.error("[norc bridge] write-intent rejected:", r.reason);
43900
44071
  }
43901
44072
  }));
43902
44073
  });
43903
- bcast.on("broadcast", { event: "raw-write-intent" }, ({ payload }) => {
44074
+ sec.on("raw-write-intent", (payload, from) => {
43904
44075
  let msg;
43905
44076
  try {
43906
44077
  msg = JSON.parse(payload);
@@ -43911,29 +44082,17 @@ async function runBridge(env, crontabIo) {
43911
44082
  enqueueMutation(() => handleRawWriteIntent(msg, rawDeps).then((r) => {
43912
44083
  console.log("[norc bridge] raw-write-intent result", r);
43913
44084
  if (r.applied && r.nextHash) {
43914
- void bcast.send({
43915
- type: "broadcast",
43916
- event: "raw-write-applied",
43917
- payload: JSON.stringify({ nextHash: r.nextHash })
43918
- });
44085
+ void sec.send("raw-write-applied", JSON.stringify({ nextHash: r.nextHash }), from);
43919
44086
  queueSyncJobs();
43920
44087
  } else if (!r.applied) {
43921
- void bcast.send({
43922
- type: "broadcast",
43923
- event: "raw-write-rejected",
43924
- payload: JSON.stringify({ reason: r.reason ?? "rejected" })
43925
- });
44088
+ void sec.send("raw-write-rejected", JSON.stringify({ reason: r.reason ?? "rejected" }), from);
43926
44089
  }
43927
44090
  }).catch((e) => {
43928
44091
  console.error("[norc bridge] raw-write-intent failed", e);
43929
- void bcast.send({
43930
- type: "broadcast",
43931
- event: "raw-write-rejected",
43932
- payload: JSON.stringify({ reason: "rejected" })
43933
- });
44092
+ void sec.send("raw-write-rejected", JSON.stringify({ reason: "rejected" }), from);
43934
44093
  }));
43935
44094
  });
43936
- bcast.on("broadcast", { event: "execute-now-intent" }, ({ payload }) => {
44095
+ sec.on("execute-now-intent", (payload, from) => {
43937
44096
  let msg;
43938
44097
  try {
43939
44098
  msg = JSON.parse(payload);
@@ -43944,11 +44103,7 @@ async function runBridge(env, crontabIo) {
43944
44103
  const { capability, jobId } = msg;
43945
44104
  const reject = (reason) => {
43946
44105
  console.error("[norc bridge] execute-now-intent rejected:", reason);
43947
- void bcast.send({
43948
- type: "broadcast",
43949
- event: "execute-now-rejected",
43950
- payload: JSON.stringify({ jobId, reason })
43951
- }).catch((e) => console.error("[norc bridge] failed to broadcast execute-now-rejected", e));
44106
+ void sec.send("execute-now-rejected", JSON.stringify({ jobId, reason }), from).catch((e) => console.error("[norc bridge] failed to broadcast execute-now-rejected", e));
43952
44107
  };
43953
44108
  enqueueMutation(async () => {
43954
44109
  try {
@@ -43978,18 +44133,14 @@ async function runBridge(env, crontabIo) {
43978
44133
  await persistConfig();
43979
44134
  await spawnWrappedCommand(wrapCommand(job.id, job.command, process.platform === "win32" ? "windows" : "posix"));
43980
44135
  console.log("[norc bridge] execute-now-intent applied");
43981
- void bcast.send({
43982
- type: "broadcast",
43983
- event: "execute-now-applied",
43984
- payload: JSON.stringify({ jobId })
43985
- }).catch((e) => console.error("[norc bridge] failed to broadcast execute-now-applied", e));
44136
+ void sec.send("execute-now-applied", JSON.stringify({ jobId }), from).catch((e) => console.error("[norc bridge] failed to broadcast execute-now-applied", e));
43986
44137
  } catch (e) {
43987
44138
  console.error("[norc bridge] execute-now-intent failed", e);
43988
44139
  reject("rejected");
43989
44140
  }
43990
44141
  });
43991
44142
  });
43992
- bcast.on("broadcast", { event: "jobs-deleted" }, ({ payload }) => {
44143
+ sec.on("jobs-deleted", (payload) => {
43993
44144
  let msg;
43994
44145
  try {
43995
44146
  msg = JSON.parse(payload);
@@ -44020,7 +44171,7 @@ async function runBridge(env, crontabIo) {
44020
44171
  void channel.track({ online_at: (/* @__PURE__ */ new Date()).toISOString() });
44021
44172
  queueSyncJobs();
44022
44173
  heartbeat = setInterval(() => {
44023
- void deviceSession(env.supabaseUrl, env.anonKey);
44174
+ void deviceSession(env.supabaseUrl, env.anonKey, void 0, keyPair.publicJwk);
44024
44175
  }, 1e4);
44025
44176
  }
44026
44177
  if (status === "CLOSED" || status === "CHANNEL_ERROR" || status === "TIMED_OUT") {
@@ -44207,7 +44358,7 @@ which backend URLs/config paths are in play, and full request/response
44207
44358
  detail for every network call (secrets shown as a redacted prefix only).
44208
44359
  `;
44209
44360
  function supabase() {
44210
- const url = process.env.NORC_SUPABASE_URL ?? DEFAULT_SUPABASE_URL;
44361
+ const url = supabaseUrl();
44211
44362
  const anon = process.env.NORC_SUPABASE_ANON_KEY ?? DEFAULT_SUPABASE_ANON_KEY;
44212
44363
  return createClient(url, anon);
44213
44364
  }
@@ -44321,7 +44472,7 @@ async function cmdJobs(args) {
44321
44472
  }
44322
44473
  }
44323
44474
  async function cmdBridge() {
44324
- const url = process.env.NORC_SUPABASE_URL ?? DEFAULT_SUPABASE_URL;
44475
+ const url = supabaseUrl();
44325
44476
  const anonKey = process.env.NORC_SUPABASE_ANON_KEY ?? DEFAULT_SUPABASE_ANON_KEY;
44326
44477
  await runBridge({ supabaseUrl: url, anonKey }, systemCrontabIo);
44327
44478
  }
@@ -44332,13 +44483,21 @@ async function main() {
44332
44483
  const [cmd, ...args] = argv;
44333
44484
  debugLog("command:", cmd || "(none)", "args:", redactArgs(args));
44334
44485
  debugLog("vault url:", process.env.NORC_VAULT_URL ?? DEFAULT_VAULT_URL, process.env.NORC_VAULT_URL ? "(NORC_VAULT_URL override)" : "(default)");
44335
- debugLog("supabase url:", process.env.NORC_SUPABASE_URL ?? DEFAULT_SUPABASE_URL, process.env.NORC_SUPABASE_URL ? "(NORC_SUPABASE_URL override)" : "(default)");
44486
+ if (debugFlag || process.env.NORC_DEBUG === "1") {
44487
+ let sb;
44488
+ try {
44489
+ sb = supabaseUrl();
44490
+ } catch (e) {
44491
+ sb = e.message;
44492
+ }
44493
+ debugLog("supabase url:", sb, sb === DEFAULT_SUPABASE_URL ? "(default)" : "(NORC_SUPABASE_URL override)");
44494
+ }
44336
44495
  if (!cmd || cmd === "--help" || cmd === "-h") {
44337
44496
  console.log(HELP);
44338
44497
  return;
44339
44498
  }
44340
44499
  if (cmd === "--version" || cmd === "-v") {
44341
- console.log(VERSION);
44500
+ console.log(VERSION2);
44342
44501
  return;
44343
44502
  }
44344
44503
  switch (cmd) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "norc-cli",
3
- "version": "0.1.11",
3
+ "version": "0.2.1",
4
4
  "description": "Headless cron job scheduler for norc — manage crontab, pair machines, run the bridge daemon.",
5
5
  "homepage": "https://norc.app/cli",
6
6
  "repository": {