norc-cli 0.1.11 → 0.2.0
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.
- package/README.md +4 -0
- package/dist/index.js +401 -247
- 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
|
|
14575
|
-
|
|
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 (!
|
|
14578
|
-
closest =
|
|
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
|
-
|
|
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
|
|
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 =
|
|
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(
|
|
41381
|
+
function getDefaultPropagationTargets(supabaseUrl2) {
|
|
41382
41382
|
const targets = [];
|
|
41383
41383
|
try {
|
|
41384
|
-
const url = new URL(
|
|
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,
|
|
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(
|
|
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(
|
|
41512
|
-
const trimmedUrl =
|
|
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(
|
|
41738
|
+
constructor(supabaseUrl2, supabaseKey, options) {
|
|
41739
41739
|
var _settings$auth$storag, _settings$global$head;
|
|
41740
|
-
this.supabaseUrl =
|
|
41740
|
+
this.supabaseUrl = supabaseUrl2;
|
|
41741
41741
|
this.supabaseKey = supabaseKey;
|
|
41742
|
-
const baseUrl = validateSupabaseUrl(
|
|
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,
|
|
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 = (
|
|
41955
|
-
return new SupabaseClient(
|
|
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) {
|
|
@@ -43256,7 +43422,7 @@ var import_node_os3 = require("node:os");
|
|
|
43256
43422
|
var import_node_path2 = require("node:path");
|
|
43257
43423
|
|
|
43258
43424
|
// src/version.ts
|
|
43259
|
-
var
|
|
43425
|
+
var VERSION2 = "0.2.0";
|
|
43260
43426
|
|
|
43261
43427
|
// src/host-details.ts
|
|
43262
43428
|
var ARCH = { x64: "x86_64", arm64: "arm64", ia32: "x86", arm: "arm" };
|
|
@@ -43307,19 +43473,26 @@ function osNameUncached(platform) {
|
|
|
43307
43473
|
}
|
|
43308
43474
|
return void 0;
|
|
43309
43475
|
}
|
|
43476
|
+
function bootedAt() {
|
|
43477
|
+
try {
|
|
43478
|
+
return new Date(Math.round((Date.now() - (0, import_node_os3.uptime)() * 1e3) / 6e4) * 6e4).toISOString();
|
|
43479
|
+
} catch {
|
|
43480
|
+
return void 0;
|
|
43481
|
+
}
|
|
43482
|
+
}
|
|
43310
43483
|
var cached;
|
|
43311
43484
|
function hostDetails() {
|
|
43312
|
-
cached ??= { os: osName(process.platform), arch: ARCH[process.arch] ?? process.arch, agent_version: `norc-cli ${
|
|
43485
|
+
cached ??= { os: osName(process.platform), arch: ARCH[process.arch] ?? process.arch, agent_version: `norc-cli ${VERSION2}`, booted_at: bootedAt() };
|
|
43313
43486
|
return cached;
|
|
43314
43487
|
}
|
|
43315
43488
|
|
|
43316
43489
|
// src/device-session.ts
|
|
43317
|
-
async function deviceSession(
|
|
43490
|
+
async function deviceSession(supabaseUrl2, anonKey, signal, encPublicJwk) {
|
|
43318
43491
|
const config = await loadConfig();
|
|
43319
43492
|
const token = config.device?.deviceToken;
|
|
43320
43493
|
if (!token) return null;
|
|
43321
43494
|
try {
|
|
43322
|
-
const res = await fetch(`${
|
|
43495
|
+
const res = await fetch(`${checkedSupabaseUrl(supabaseUrl2)}/functions/v1/device-session`, {
|
|
43323
43496
|
method: "POST",
|
|
43324
43497
|
headers: { "Content-Type": "application/json", apikey: anonKey },
|
|
43325
43498
|
// job_timezone_handling (roadmap #7): best-effort, piggybacked on this
|
|
@@ -43327,7 +43500,12 @@ async function deviceSession(supabaseUrl, anonKey, signal) {
|
|
|
43327
43500
|
// Node's global Intl covers this, same as the browser-embedded runtime
|
|
43328
43501
|
// desktop's copy of this call runs in — no import needed.
|
|
43329
43502
|
// Machine details (0062): OS, arch and agent version, same piggyback.
|
|
43330
|
-
body: JSON.stringify({
|
|
43503
|
+
body: JSON.stringify({
|
|
43504
|
+
token,
|
|
43505
|
+
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
43506
|
+
...hostDetails(),
|
|
43507
|
+
...encPublicJwk ? { enc_public_jwk: encPublicJwk } : {}
|
|
43508
|
+
}),
|
|
43331
43509
|
signal
|
|
43332
43510
|
});
|
|
43333
43511
|
if (!res.ok) return null;
|
|
@@ -43522,7 +43700,7 @@ function fetchTimeout() {
|
|
|
43522
43700
|
return AbortSignal.timeout(FETCH_TIMEOUT_MS);
|
|
43523
43701
|
}
|
|
43524
43702
|
var SESSION_REFRESH_BUFFER_MS = 6e4;
|
|
43525
|
-
function createSessionCache(
|
|
43703
|
+
function createSessionCache(anonKey) {
|
|
43526
43704
|
let sessionPromise;
|
|
43527
43705
|
return async function getSession() {
|
|
43528
43706
|
if (sessionPromise) {
|
|
@@ -43530,19 +43708,18 @@ function createSessionCache(url, anonKey) {
|
|
|
43530
43708
|
const expiresAt = cached2 ? new Date(cached2.expires_at).getTime() : 0;
|
|
43531
43709
|
if (!cached2 || expiresAt - Date.now() < SESSION_REFRESH_BUFFER_MS) sessionPromise = void 0;
|
|
43532
43710
|
}
|
|
43533
|
-
sessionPromise ??= deviceSession(
|
|
43711
|
+
sessionPromise ??= deviceSession(supabaseUrl(), anonKey, fetchTimeout());
|
|
43534
43712
|
return sessionPromise;
|
|
43535
43713
|
};
|
|
43536
43714
|
}
|
|
43537
43715
|
function createReporter(getSession) {
|
|
43538
|
-
const url = process.env.NORC_SUPABASE_URL ?? DEFAULT_SUPABASE_URL;
|
|
43539
43716
|
const anonKey = process.env.NORC_SUPABASE_ANON_KEY ?? DEFAULT_SUPABASE_ANON_KEY;
|
|
43540
|
-
const sessionFor = getSession ?? createSessionCache(
|
|
43717
|
+
const sessionFor = getSession ?? createSessionCache(anonKey);
|
|
43541
43718
|
return async function report(run) {
|
|
43542
43719
|
const session = await sessionFor();
|
|
43543
43720
|
if (!session) return false;
|
|
43544
43721
|
try {
|
|
43545
|
-
const res = await fetch(`${
|
|
43722
|
+
const res = await fetch(`${supabaseUrl()}/functions/v1/run-report`, {
|
|
43546
43723
|
method: "POST",
|
|
43547
43724
|
headers: { "Content-Type": "application/json", apikey: anonKey, Authorization: `Bearer ${session.token}` },
|
|
43548
43725
|
body: JSON.stringify({
|
|
@@ -43564,14 +43741,13 @@ function createReporter(getSession) {
|
|
|
43564
43741
|
};
|
|
43565
43742
|
}
|
|
43566
43743
|
function createBackfillClaimer(getSession) {
|
|
43567
|
-
const url = process.env.NORC_SUPABASE_URL ?? DEFAULT_SUPABASE_URL;
|
|
43568
43744
|
const anonKey = process.env.NORC_SUPABASE_ANON_KEY ?? DEFAULT_SUPABASE_ANON_KEY;
|
|
43569
|
-
const sessionFor = getSession ?? createSessionCache(
|
|
43745
|
+
const sessionFor = getSession ?? createSessionCache(anonKey);
|
|
43570
43746
|
return async function claimBackfills(jobId) {
|
|
43571
43747
|
const session = await sessionFor();
|
|
43572
43748
|
if (!session) return [];
|
|
43573
43749
|
try {
|
|
43574
|
-
const res = await fetch(`${
|
|
43750
|
+
const res = await fetch(`${supabaseUrl()}/functions/v1/backfill-claim`, {
|
|
43575
43751
|
method: "POST",
|
|
43576
43752
|
headers: { "Content-Type": "application/json", apikey: anonKey, Authorization: `Bearer ${session.token}` },
|
|
43577
43753
|
body: JSON.stringify({ job_id: jobId }),
|
|
@@ -43594,10 +43770,7 @@ async function cmdRun(args) {
|
|
|
43594
43770
|
const jobId = args[jobIdFlagIndex + 1];
|
|
43595
43771
|
const command = args.slice(sepIndex + 1);
|
|
43596
43772
|
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
|
-
);
|
|
43773
|
+
const getSession = createSessionCache(process.env.NORC_SUPABASE_ANON_KEY ?? DEFAULT_SUPABASE_ANON_KEY);
|
|
43601
43774
|
return runWrapped(
|
|
43602
43775
|
{
|
|
43603
43776
|
spawnCommand: realSpawnCommand,
|
|
@@ -43616,22 +43789,14 @@ async function cmdRun(args) {
|
|
|
43616
43789
|
// src/commands/bridge.ts
|
|
43617
43790
|
var import_node_child_process5 = require("node:child_process");
|
|
43618
43791
|
|
|
43619
|
-
// src/
|
|
43620
|
-
|
|
43621
|
-
|
|
43622
|
-
|
|
43623
|
-
|
|
43624
|
-
|
|
43625
|
-
|
|
43626
|
-
|
|
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
|
-
};
|
|
43792
|
+
// src/enc-key.ts
|
|
43793
|
+
async function loadOrCreateEncKey(config, persist) {
|
|
43794
|
+
const k = config.enc;
|
|
43795
|
+
if (k && isEcPublicJwk(k.publicJwk) && typeof k.privateJwk?.d === "string") return k;
|
|
43796
|
+
config.enc = await generateKeyPair();
|
|
43797
|
+
await persist();
|
|
43798
|
+
return config.enc;
|
|
43799
|
+
}
|
|
43635
43800
|
|
|
43636
43801
|
// src/capability-key.ts
|
|
43637
43802
|
var CAPABILITY_PUBLIC_JWK = {
|
|
@@ -43850,6 +44015,7 @@ async function runBridge(env, crontabIo) {
|
|
|
43850
44015
|
});
|
|
43851
44016
|
return save;
|
|
43852
44017
|
};
|
|
44018
|
+
const keyPair = await loadOrCreateEncKey(config, persistConfig);
|
|
43853
44019
|
let state = "disconnected";
|
|
43854
44020
|
let attempt = 0;
|
|
43855
44021
|
while (true) {
|
|
@@ -43860,7 +44026,7 @@ async function runBridge(env, crontabIo) {
|
|
|
43860
44026
|
const enqueueMutation = serialize();
|
|
43861
44027
|
try {
|
|
43862
44028
|
state = reduceConn(state, "connect");
|
|
43863
|
-
const sess = await deviceSession(env.supabaseUrl, env.anonKey);
|
|
44029
|
+
const sess = await deviceSession(env.supabaseUrl, env.anonKey, void 0, keyPair.publicJwk);
|
|
43864
44030
|
if (!sess) {
|
|
43865
44031
|
console.error("[norc bridge] device session mint failed");
|
|
43866
44032
|
await wait(backoffDelay(attempt++));
|
|
@@ -43875,11 +44041,15 @@ async function runBridge(env, crontabIo) {
|
|
|
43875
44041
|
const channel = sb.channel(`machine:${sess.machine_id}`, {
|
|
43876
44042
|
config: { private: true, broadcast: { self: false }, presence: { key: sess.machine_id } }
|
|
43877
44043
|
});
|
|
43878
|
-
|
|
44044
|
+
const sec = secureMachineChannel(channel, {
|
|
44045
|
+
machineId: sess.machine_id,
|
|
44046
|
+
keyPair,
|
|
44047
|
+
onDrop: (event) => console.warn("[norc bridge] dropped unauthenticated relay payload on", event)
|
|
44048
|
+
});
|
|
44049
|
+
serveBridge(new SealedBridgeTransport(sec), lineChanges.io, { allow: [...READ_ONLY] });
|
|
43879
44050
|
const deps = buildWriteIntentDeps(config, machineId, crontabIo, () => void persistConfig());
|
|
43880
44051
|
const rawDeps = buildRawWriteIntentDeps(config, machineId, crontabIo, () => void persistConfig());
|
|
43881
|
-
|
|
43882
|
-
bcast.on("broadcast", { event: "write-intent" }, ({ payload }) => {
|
|
44052
|
+
sec.on("write-intent", (payload, from) => {
|
|
43883
44053
|
let msg;
|
|
43884
44054
|
try {
|
|
43885
44055
|
msg = JSON.parse(payload);
|
|
@@ -43889,18 +44059,14 @@ async function runBridge(env, crontabIo) {
|
|
|
43889
44059
|
enqueueMutation(() => handleWriteIntent(msg, deps).then((r) => {
|
|
43890
44060
|
if (r.applied) {
|
|
43891
44061
|
console.log("[norc bridge] write-intent applied");
|
|
43892
|
-
void
|
|
43893
|
-
type: "broadcast",
|
|
43894
|
-
event: "write-applied",
|
|
43895
|
-
payload: JSON.stringify({ jobIds: msg.jobs.map((j) => j.id) })
|
|
43896
|
-
});
|
|
44062
|
+
void sec.send("write-applied", JSON.stringify({ jobIds: msg.jobs.map((j) => j.id) }), from);
|
|
43897
44063
|
queueSyncJobs();
|
|
43898
44064
|
} else {
|
|
43899
44065
|
console.error("[norc bridge] write-intent rejected:", r.reason);
|
|
43900
44066
|
}
|
|
43901
44067
|
}));
|
|
43902
44068
|
});
|
|
43903
|
-
|
|
44069
|
+
sec.on("raw-write-intent", (payload, from) => {
|
|
43904
44070
|
let msg;
|
|
43905
44071
|
try {
|
|
43906
44072
|
msg = JSON.parse(payload);
|
|
@@ -43911,29 +44077,17 @@ async function runBridge(env, crontabIo) {
|
|
|
43911
44077
|
enqueueMutation(() => handleRawWriteIntent(msg, rawDeps).then((r) => {
|
|
43912
44078
|
console.log("[norc bridge] raw-write-intent result", r);
|
|
43913
44079
|
if (r.applied && r.nextHash) {
|
|
43914
|
-
void
|
|
43915
|
-
type: "broadcast",
|
|
43916
|
-
event: "raw-write-applied",
|
|
43917
|
-
payload: JSON.stringify({ nextHash: r.nextHash })
|
|
43918
|
-
});
|
|
44080
|
+
void sec.send("raw-write-applied", JSON.stringify({ nextHash: r.nextHash }), from);
|
|
43919
44081
|
queueSyncJobs();
|
|
43920
44082
|
} else if (!r.applied) {
|
|
43921
|
-
void
|
|
43922
|
-
type: "broadcast",
|
|
43923
|
-
event: "raw-write-rejected",
|
|
43924
|
-
payload: JSON.stringify({ reason: r.reason ?? "rejected" })
|
|
43925
|
-
});
|
|
44083
|
+
void sec.send("raw-write-rejected", JSON.stringify({ reason: r.reason ?? "rejected" }), from);
|
|
43926
44084
|
}
|
|
43927
44085
|
}).catch((e) => {
|
|
43928
44086
|
console.error("[norc bridge] raw-write-intent failed", e);
|
|
43929
|
-
void
|
|
43930
|
-
type: "broadcast",
|
|
43931
|
-
event: "raw-write-rejected",
|
|
43932
|
-
payload: JSON.stringify({ reason: "rejected" })
|
|
43933
|
-
});
|
|
44087
|
+
void sec.send("raw-write-rejected", JSON.stringify({ reason: "rejected" }), from);
|
|
43934
44088
|
}));
|
|
43935
44089
|
});
|
|
43936
|
-
|
|
44090
|
+
sec.on("execute-now-intent", (payload, from) => {
|
|
43937
44091
|
let msg;
|
|
43938
44092
|
try {
|
|
43939
44093
|
msg = JSON.parse(payload);
|
|
@@ -43944,11 +44098,7 @@ async function runBridge(env, crontabIo) {
|
|
|
43944
44098
|
const { capability, jobId } = msg;
|
|
43945
44099
|
const reject = (reason) => {
|
|
43946
44100
|
console.error("[norc bridge] execute-now-intent rejected:", reason);
|
|
43947
|
-
void
|
|
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));
|
|
44101
|
+
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
44102
|
};
|
|
43953
44103
|
enqueueMutation(async () => {
|
|
43954
44104
|
try {
|
|
@@ -43978,18 +44128,14 @@ async function runBridge(env, crontabIo) {
|
|
|
43978
44128
|
await persistConfig();
|
|
43979
44129
|
await spawnWrappedCommand(wrapCommand(job.id, job.command, process.platform === "win32" ? "windows" : "posix"));
|
|
43980
44130
|
console.log("[norc bridge] execute-now-intent applied");
|
|
43981
|
-
void
|
|
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));
|
|
44131
|
+
void sec.send("execute-now-applied", JSON.stringify({ jobId }), from).catch((e) => console.error("[norc bridge] failed to broadcast execute-now-applied", e));
|
|
43986
44132
|
} catch (e) {
|
|
43987
44133
|
console.error("[norc bridge] execute-now-intent failed", e);
|
|
43988
44134
|
reject("rejected");
|
|
43989
44135
|
}
|
|
43990
44136
|
});
|
|
43991
44137
|
});
|
|
43992
|
-
|
|
44138
|
+
sec.on("jobs-deleted", (payload) => {
|
|
43993
44139
|
let msg;
|
|
43994
44140
|
try {
|
|
43995
44141
|
msg = JSON.parse(payload);
|
|
@@ -44020,7 +44166,7 @@ async function runBridge(env, crontabIo) {
|
|
|
44020
44166
|
void channel.track({ online_at: (/* @__PURE__ */ new Date()).toISOString() });
|
|
44021
44167
|
queueSyncJobs();
|
|
44022
44168
|
heartbeat = setInterval(() => {
|
|
44023
|
-
void deviceSession(env.supabaseUrl, env.anonKey);
|
|
44169
|
+
void deviceSession(env.supabaseUrl, env.anonKey, void 0, keyPair.publicJwk);
|
|
44024
44170
|
}, 1e4);
|
|
44025
44171
|
}
|
|
44026
44172
|
if (status === "CLOSED" || status === "CHANNEL_ERROR" || status === "TIMED_OUT") {
|
|
@@ -44207,7 +44353,7 @@ which backend URLs/config paths are in play, and full request/response
|
|
|
44207
44353
|
detail for every network call (secrets shown as a redacted prefix only).
|
|
44208
44354
|
`;
|
|
44209
44355
|
function supabase() {
|
|
44210
|
-
const url =
|
|
44356
|
+
const url = supabaseUrl();
|
|
44211
44357
|
const anon = process.env.NORC_SUPABASE_ANON_KEY ?? DEFAULT_SUPABASE_ANON_KEY;
|
|
44212
44358
|
return createClient(url, anon);
|
|
44213
44359
|
}
|
|
@@ -44321,7 +44467,7 @@ async function cmdJobs(args) {
|
|
|
44321
44467
|
}
|
|
44322
44468
|
}
|
|
44323
44469
|
async function cmdBridge() {
|
|
44324
|
-
const url =
|
|
44470
|
+
const url = supabaseUrl();
|
|
44325
44471
|
const anonKey = process.env.NORC_SUPABASE_ANON_KEY ?? DEFAULT_SUPABASE_ANON_KEY;
|
|
44326
44472
|
await runBridge({ supabaseUrl: url, anonKey }, systemCrontabIo);
|
|
44327
44473
|
}
|
|
@@ -44332,13 +44478,21 @@ async function main() {
|
|
|
44332
44478
|
const [cmd, ...args] = argv;
|
|
44333
44479
|
debugLog("command:", cmd || "(none)", "args:", redactArgs(args));
|
|
44334
44480
|
debugLog("vault url:", process.env.NORC_VAULT_URL ?? DEFAULT_VAULT_URL, process.env.NORC_VAULT_URL ? "(NORC_VAULT_URL override)" : "(default)");
|
|
44335
|
-
|
|
44481
|
+
if (debugFlag || process.env.NORC_DEBUG === "1") {
|
|
44482
|
+
let sb;
|
|
44483
|
+
try {
|
|
44484
|
+
sb = supabaseUrl();
|
|
44485
|
+
} catch (e) {
|
|
44486
|
+
sb = e.message;
|
|
44487
|
+
}
|
|
44488
|
+
debugLog("supabase url:", sb, sb === DEFAULT_SUPABASE_URL ? "(default)" : "(NORC_SUPABASE_URL override)");
|
|
44489
|
+
}
|
|
44336
44490
|
if (!cmd || cmd === "--help" || cmd === "-h") {
|
|
44337
44491
|
console.log(HELP);
|
|
44338
44492
|
return;
|
|
44339
44493
|
}
|
|
44340
44494
|
if (cmd === "--version" || cmd === "-v") {
|
|
44341
|
-
console.log(
|
|
44495
|
+
console.log(VERSION2);
|
|
44342
44496
|
return;
|
|
44343
44497
|
}
|
|
44344
44498
|
switch (cmd) {
|