@north-light/cli 0.3.735 → 0.3.737

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.
@@ -0,0 +1,102 @@
1
+ // Grant-evaluation phase 3 (shadow). On the fleet, each stored-column grant read is compared with the directory's live answer for that account.
2
+ // The stored column still decides; this only counts and logs disagreements. Every failure here is swallowed into a log line, never into the decision.
3
+ import { directoryIssuer } from '../directory/issuer.js';
4
+ import { outboundFetch } from '../events/outbound.js';
5
+ import { warn } from '../output.js';
6
+ import { canonicalJson } from './mirror.js';
7
+ let ttlMs = 5_000;
8
+ /** Test hook: how long a cached answer is used before its epochs are re-checked. */
9
+ export function setShadowTtl(ms) { ttlMs = ms; }
10
+ const MAX_SUBS = 512;
11
+ const COMPARED = ['status', 'scopes', 'resolved_scopes', 'spend_cap', 'payer', 'dependencies', 'run_notice_url', 'inference_endpoint'];
12
+ // Insertion-ordered Map used as an LRU: a read re-inserts the key.
13
+ /** Test hook: forget every cached answer. */
14
+ export function resetShadowCache() { cache.clear(); }
15
+ const cache = new Map();
16
+ const inflight = new Map();
17
+ /** How many checks agreed, disagreed (live answer differs at the same rev), lagged (live rev differs: a sync has not landed) or failed since this process started. */
18
+ export const shadowCounts = { agree: 0, disagree: 0, lagging: 0, error: 0 };
19
+ async function fetchAnswer(base, sub, held) {
20
+ // Imported here, not at the top: sync.js reaches the whole canvas, and a static edge made mirror.js -> shadow.js -> sync.js close an import cycle that broke module load order.
21
+ const { mintDirectoryToken } = await import('./sync.js');
22
+ const token = await mintDirectoryToken(base);
23
+ const epochs = held ? `&epochs=${held.epochs.global},${held.epochs.sub}` : '';
24
+ const url = `${base}/v1/runtime/grant-answers?sub=${encodeURIComponent(sub)}${epochs}`;
25
+ const response = await outboundFetch('grant_shadow', url, { headers: { Authorization: `Bearer ${token.access_token}` }, signal: AbortSignal.timeout(10_000) });
26
+ if (!response.ok)
27
+ throw new Error(`grant-answers ${response.status}`);
28
+ const body = await response.json();
29
+ if (body.unchanged) {
30
+ if (!held)
31
+ throw new Error('grant-answers said unchanged to a caller holding nothing');
32
+ return { ...held, epochs: body.epochs, checkedAt: Date.now() };
33
+ }
34
+ return { epochs: body.epochs, grants: new Map((body.grants ?? []).map((grant) => [String(grant['id']), grant])), checkedAt: Date.now() };
35
+ }
36
+ async function answerFor(base, sub) {
37
+ const held = cache.get(sub);
38
+ if (held && Date.now() - held.checkedAt < ttlMs)
39
+ return held;
40
+ const pending = inflight.get(sub);
41
+ if (pending)
42
+ return pending;
43
+ const run = fetchAnswer(base, sub, held).then((answer) => {
44
+ cache.delete(sub);
45
+ cache.set(sub, answer);
46
+ if (cache.size > MAX_SUBS)
47
+ cache.delete(cache.keys().next().value);
48
+ return answer;
49
+ }).finally(() => inflight.delete(sub));
50
+ inflight.set(sub, run);
51
+ return run;
52
+ }
53
+ /** Resolves once every comparison started so far has finished. Test hook. */
54
+ const running = new Set();
55
+ export async function shadowIdle() { await Promise.all([...running]); }
56
+ async function compare(stored) {
57
+ const base = directoryIssuer();
58
+ if (base === null)
59
+ return;
60
+ const live = (await answerFor(base, stored.sub)).grants.get(stored.id);
61
+ if (!live) {
62
+ shadowCounts.disagree++;
63
+ warn(`grant_shadow disagree ${JSON.stringify({ grant: stored.id, sub: stored.sub, fields: ['missing'] })}`);
64
+ return;
65
+ }
66
+ if (live['rev'] !== stored.rev) {
67
+ shadowCounts.lagging++;
68
+ return;
69
+ }
70
+ const fields = COMPARED.filter((key) => canonicalJson(live[key] ?? null) !== canonicalJson(stored[key] ?? null));
71
+ if (fields.length === 0) {
72
+ shadowCounts.agree++;
73
+ return;
74
+ }
75
+ shadowCounts.disagree++;
76
+ warn(`grant_shadow disagree ${JSON.stringify({ grant: stored.id, sub: stored.sub, rev: stored.rev, fields })}`);
77
+ }
78
+ let summaryTimer;
79
+ let reported = { agree: 0, disagree: 0, lagging: 0, error: 0 };
80
+ // One greppable line a minute while checks are happening: `grep grant_shadow_summary`; sum `disagree` across pods over 7 days.
81
+ function startSummary() {
82
+ if (summaryTimer)
83
+ return;
84
+ summaryTimer = setInterval(() => {
85
+ const delta = { agree: shadowCounts.agree - reported.agree, disagree: shadowCounts.disagree - reported.disagree, lagging: shadowCounts.lagging - reported.lagging, error: shadowCounts.error - reported.error };
86
+ reported = { ...shadowCounts };
87
+ if (delta.agree + delta.disagree + delta.lagging + delta.error > 0)
88
+ warn(`grant_shadow_summary ${JSON.stringify({ window_s: 60, ...delta })}`);
89
+ }, 60_000);
90
+ summaryTimer.unref();
91
+ }
92
+ /** Compare one stored grant with the directory's live answer, in the background, on the fleet only. Never throws and never delays the caller. */
93
+ export function shadowCheck(stored) {
94
+ if (!process.env['CRTR_RUNTIME'])
95
+ return;
96
+ startSummary();
97
+ const task = compare(stored).catch((error) => {
98
+ shadowCounts.error++;
99
+ warn(`grant_shadow error ${JSON.stringify({ grant: stored.id, message: error instanceof Error ? error.message : String(error) })}`);
100
+ }).finally(() => running.delete(task));
101
+ running.add(task);
102
+ }
@@ -205,6 +205,7 @@ export const OPERATIONS = [
205
205
  { name: 'import.get', method: 'GET', path: '/v1/imports/:run_id', classes: ['person', 'import'], resource: 'none' },
206
206
  { name: 'import.rollback', method: 'POST', path: '/v1/imports/:run_id/rollback', classes: ['person'], resource: 'none' },
207
207
  { name: 'machine.register', method: 'POST', path: '/v1/machines', classes: ['person'], resource: 'none' },
208
+ { name: 'machine.revoke', method: 'DELETE', path: '/v1/machines/:environment_id', classes: ['person'], resource: 'none' },
208
209
  { name: 'import.machine-credential', method: 'POST', path: '/v1/imports/:run_id/machine-credential', classes: ['person'], resource: 'none' },
209
210
  { name: 'execution.import-unpacked', method: 'POST', path: '/v1/executions/:execution_id/import-unpacked', classes: ['broker'], resource: 'none' },
210
211
  { name: 'execution.start', method: 'GET', path: '/v1/executions/:execution_id/start', classes: ['broker'], resource: 'none' },
@@ -4,6 +4,7 @@
4
4
  // Also the move record `runtime/import/move.json` (0600): where a move to Northlight that `crtr sys signin` started stands, from before the drain until the
5
5
  // computer has switched over (design-crtr-northlight-signin component 4).
6
6
  import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
7
+ import { randomBytes } from 'node:crypto';
7
8
  import { dirname, join } from 'node:path';
8
9
  import { runtimeRoot, secretsDir } from '../../core/layout.js';
9
10
  import { CrtrError } from '../../core/errors.js';
@@ -17,10 +18,10 @@ export function readMachineConfig() {
17
18
  if (!existsSync(path))
18
19
  return undefined;
19
20
  const raw = JSON.parse(readFileSync(path, 'utf8'));
20
- if (typeof raw.apiUrl !== 'string' || typeof raw.environmentId !== 'string' || typeof raw.runId !== 'string' || typeof raw.directoryUrl !== 'string')
21
- throw new Error(`${path} must hold {apiUrl, environmentId, runId, directoryUrl}`);
21
+ if (typeof raw.apiUrl !== 'string' || typeof raw.environmentId !== 'string' || (raw.runId !== undefined && typeof raw.runId !== 'string') || typeof raw.directoryUrl !== 'string')
22
+ throw new Error(`${path} must hold {apiUrl, environmentId, directoryUrl}`);
22
23
  const account = raw.account !== undefined && typeof raw.account?.id === 'string' && typeof raw.account.display === 'string' ? { id: raw.account.id, display: raw.account.display } : undefined;
23
- return { apiUrl: raw.apiUrl, environmentId: raw.environmentId, runId: raw.runId, directoryUrl: raw.directoryUrl, ...(account === undefined ? {} : { account }) };
24
+ return { apiUrl: raw.apiUrl, environmentId: raw.environmentId, ...(raw.runId === undefined ? {} : { runId: raw.runId }), directoryUrl: raw.directoryUrl, ...(account === undefined ? {} : { account }) };
24
25
  }
25
26
  export function writeMachineConfig(config) {
26
27
  mkdirSync(dirname(machineConfigPath()), { recursive: true });
@@ -61,3 +62,16 @@ export function deleteMoveRecord() {
61
62
  export const isMoveCommitted = () => readMoveRecord()?.state === 'committed';
62
63
  /** The one `move_unfinished` error: every command, `crtr sys import resume` and a move whose switch-over failed answer it alike (exit code USAGE, as `not_signed_in`). */
63
64
  export const moveUnfinishedError = (reason) => new CrtrError('move_unfinished', `crtr's records are already in your Northlight account, but this computer has not switched over${reason === undefined ? '.' : `: ${reason}`}`, ExitCode.USAGE, { next: 'Run `crtr sys signin` to finish.' });
65
+ /** This computer's install id, kept under `runtime/` so it exists before any daemon: the machine registration names it, and a reinstall that keeps `runtime/` registers the same machine again. */
66
+ export const installIdPath = () => join(runtimeRoot(), 'install-id');
67
+ export function readOrCreateInstallId() {
68
+ const path = installIdPath();
69
+ if (existsSync(path))
70
+ return readFileSync(path, 'utf8').trim();
71
+ const id = Array.from(randomBytes(8), (b) => 'abcdefghijklmnopqrstuvwxyz0123456789'[b % 36]).join('');
72
+ mkdirSync(dirname(path), { recursive: true });
73
+ writeFileSync(path, `${id}\n`);
74
+ return id;
75
+ }
76
+ /** Whether this computer still holds a local canvas from before crtr was fleet-only (a supervised Postgres or a SQLite file). */
77
+ export const hasLocalCanvas = () => ['pg', 'canvas.db', 'canvas.db.imported'].some((name) => existsSync(join(runtimeRoot(), name)));
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.735",
3
+ "version": "0.3.737",
4
4
  "description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/api/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.735",
3
+ "version": "0.3.737",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.735",
3
+ "version": "0.3.737",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -27,8 +27,8 @@
27
27
  "postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
28
28
  },
29
29
  "dependencies": {
30
- "@north-light/api": "0.3.735",
31
- "@north-light/identity": "0.3.735"
30
+ "@north-light/api": "0.3.737",
31
+ "@north-light/identity": "0.3.737"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.735",
3
+ "version": "0.3.737",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.735",
9
+ "version": "0.3.737",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,8 +28,8 @@
28
28
  "@milkdown/preset-gfm": "^7.22.3",
29
29
  "@milkdown/prose": "^7.22.3",
30
30
  "@milkdown/utils": "^7.22.3",
31
- "@north-light/identity": "0.3.735",
32
- "@north-light/plugin": "0.3.735",
31
+ "@north-light/identity": "0.3.737",
32
+ "@north-light/plugin": "0.3.737",
33
33
  "cron-parser": "^5.6.0",
34
34
  "esbuild": "0.28.2",
35
35
  "jose": "^6.2.12",
@@ -11902,17 +11902,17 @@
11902
11902
  },
11903
11903
  "packages/crouter-api": {
11904
11904
  "name": "@north-light/api",
11905
- "version": "0.3.735",
11905
+ "version": "0.3.737",
11906
11906
  "license": "UNLICENSED"
11907
11907
  },
11908
11908
  "packages/crouter-env-docker": {
11909
11909
  "name": "@north-light/env-docker",
11910
- "version": "0.3.735",
11910
+ "version": "0.3.737",
11911
11911
  "license": "UNLICENSED"
11912
11912
  },
11913
11913
  "packages/crouter-identity": {
11914
11914
  "name": "@north-light/identity",
11915
- "version": "0.3.735",
11915
+ "version": "0.3.737",
11916
11916
  "license": "UNLICENSED",
11917
11917
  "dependencies": {
11918
11918
  "jose": "^6.2.1"
@@ -11920,21 +11920,21 @@
11920
11920
  },
11921
11921
  "packages/crouter-plugin": {
11922
11922
  "name": "@north-light/plugin",
11923
- "version": "0.3.735",
11923
+ "version": "0.3.737",
11924
11924
  "license": "UNLICENSED",
11925
11925
  "dependencies": {
11926
- "@north-light/api": "0.3.735",
11927
- "@north-light/identity": "0.3.735"
11926
+ "@north-light/api": "0.3.737",
11927
+ "@north-light/identity": "0.3.737"
11928
11928
  }
11929
11929
  },
11930
11930
  "packages/crouter-sdk": {
11931
11931
  "name": "@north-light/sdk",
11932
- "version": "0.3.735",
11932
+ "version": "0.3.737",
11933
11933
  "license": "UNLICENSED",
11934
11934
  "dependencies": {
11935
- "@north-light/api": "0.3.735",
11936
- "@north-light/identity": "0.3.735",
11937
- "@north-light/plugin": "0.3.735",
11935
+ "@north-light/api": "0.3.737",
11936
+ "@north-light/identity": "0.3.737",
11937
+ "@north-light/plugin": "0.3.737",
11938
11938
  "jose": "^6.2.1"
11939
11939
  },
11940
11940
  "bin": {
@@ -460,10 +460,9 @@ async function start(env) {
460
460
  const fetchEnv = { ...gitEnv, GIT_TERMINAL_PROMPT: '0', ...(relay ? { CRTR_API_SOCKET: relay.socketPath, CRTR_ENVIRONMENT_ID: environment } : {}) };
461
461
  delete fetchEnv.CRTR_NODE_TOKEN;
462
462
  try {
463
- for (const repo of cloned) {
464
- const r = await gitAsync(join(work, repo.name), ['fetch', '--prune'], 60_000, fetchEnv);
465
- if (r.status !== 0) fetchFailures.push({ repository: repo.name, error: r.stderr.slice(0, 300) });
466
- }
463
+ // In parallel: the start waits for the slowest fetch, not the sum of them.
464
+ const results = await Promise.all(cloned.map((repo) => gitAsync(join(work, repo.name), ['fetch', '--prune'], 60_000, fetchEnv)));
465
+ results.forEach((r, i) => { if (r.status !== 0) fetchFailures.push({ repository: cloned[i].name, error: r.stderr.slice(0, 300) }); });
467
466
  } finally { await relay?.close(); }
468
467
  }
469
468