@north-light/api 0.3.736 → 0.3.738

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.
@@ -1,5 +1,5 @@
1
1
  /** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
2
- export declare const CONTRACT_LEVEL = "1.73";
2
+ export declare const CONTRACT_LEVEL = "1.74";
3
3
  /** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
4
4
  export declare const REQUIRED_CONTRACT_HEADER = "Crouter-Required-Contract";
5
5
  /** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
@@ -12,7 +12,7 @@
12
12
  //
13
13
  // PURITY (spec §3.1): Node built-ins + `src/api/*` only.
14
14
  /** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
15
- export const CONTRACT_LEVEL = '1.73';
15
+ export const CONTRACT_LEVEL = '1.74';
16
16
  /** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
17
17
  export const REQUIRED_CONTRACT_HEADER = 'Crouter-Required-Contract';
18
18
  /** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
@@ -12,6 +12,7 @@ import { pathExists, listDirs, removePath } from '../../core/fs-utils.js';
12
12
  import { lsRemote } from '../../core/git.js';
13
13
  import { cliClient } from '../api-client.js';
14
14
  import { detectNerdFont, nerdFontInstallCommand, NERD_FONT_SELECT_HINT } from '../../core/runtime/nerd-font.js';
15
+ import { oldPackageInstalled } from './old-package.js';
15
16
  import { detectPackageManager } from './setup-core.js';
16
17
  import { validateEffectiveCommandPlugins } from '../../core/command-plugins/discovery.js';
17
18
  import { adaptPluginContributions } from '../../core/command-plugins/compose.js';
@@ -386,6 +387,13 @@ function runNerdFontCheck() {
386
387
  ...(plan.command ? { command: plan.command } : {}),
387
388
  });
388
389
  }
390
+ /** `@crouton-kit/crouter` installed beside this package fights it for the `crtr` bin, and npm refuses to install over it; only uninstalling it first works. */
391
+ function oldPackageCheck() {
392
+ const old = oldPackageInstalled();
393
+ if (old === undefined)
394
+ return pass('canvas', 'package:old-crouter', 'the old @crouton-kit/crouter package is not installed');
395
+ return failCheck('canvas', 'package:old-crouter', old.message, { kind: 'human_action', description: 'Remove the old package, then reinstall this one', command: `${old.uninstall} && npm i -g @north-light/cli@latest` });
396
+ }
389
397
  /** Where the generation was installed from (`<id>.source.json` beside it, written by install-runtime). */
390
398
  function installSourceCheck(label, generation) {
391
399
  const name = `runtime:${label}:source`;
@@ -630,6 +638,7 @@ export const sysDoctorLeaf = defineLeaf({
630
638
  allResults.push(...runBinContributionChecks(scopes));
631
639
  allResults.push(...runHumanActionChecks(scopes));
632
640
  allResults.push(...await runRequiresChecks(scopes));
641
+ allResults.push(oldPackageCheck());
633
642
  allResults.push(...await runFaultChecks());
634
643
  const processLocation = processGeneration();
635
644
  allResults.push(...await generationChecks('selected', selectedGeneration(), processLocation === null));
@@ -0,0 +1,9 @@
1
+ export declare const OLD_PACKAGE = "@crouton-kit/crouter";
2
+ export declare const OLD_PACKAGE_UNINSTALL = "npm uninstall -g @crouton-kit/crouter";
3
+ /** Where a global install of this package sits beside the old one: `<lib>/node_modules/@north-light/cli` → `<lib>/node_modules/@crouton-kit/crouter`. */
4
+ export declare function oldPackageDir(packageRoot: string): string | undefined;
5
+ /** The old package installed next to this one, with the message that names the command that removes it; undefined when it is absent. */
6
+ export declare function oldPackageInstalled(packageRoot?: string): {
7
+ uninstall: string;
8
+ message: string;
9
+ } | undefined;
@@ -0,0 +1,20 @@
1
+ // The old `@crouton-kit/crouter` package declares the same `crtr` bin as `@north-light/cli`. npm checks bin ownership before any install script runs,
2
+ // so `npm i -g @north-light/cli` over it fails with EEXIST and no script of ours can prevent that; the old package has to be uninstalled first.
3
+ import { existsSync } from 'node:fs';
4
+ import { dirname, join, sep } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ export const OLD_PACKAGE = '@crouton-kit/crouter';
7
+ export const OLD_PACKAGE_UNINSTALL = `npm uninstall -g ${OLD_PACKAGE}`;
8
+ /** Where a global install of this package sits beside the old one: `<lib>/node_modules/@north-light/cli` → `<lib>/node_modules/@crouton-kit/crouter`. */
9
+ export function oldPackageDir(packageRoot) {
10
+ const marker = `${sep}node_modules${sep}@north-light${sep}cli`;
11
+ const at = packageRoot.lastIndexOf(marker);
12
+ return at < 0 ? undefined : join(packageRoot.slice(0, at), 'node_modules', OLD_PACKAGE);
13
+ }
14
+ /** The old package installed next to this one, with the message that names the command that removes it; undefined when it is absent. */
15
+ export function oldPackageInstalled(packageRoot = join(dirname(fileURLToPath(import.meta.url)), '..', '..', '..')) {
16
+ const dir = oldPackageDir(packageRoot);
17
+ if (dir === undefined || !existsSync(join(dir, 'package.json')))
18
+ return undefined;
19
+ return { uninstall: OLD_PACKAGE_UNINSTALL, message: `The old ${OLD_PACKAGE} package is still installed at ${dir} and owns the \`crtr\` command. Run \`${OLD_PACKAGE_UNINSTALL}\`, then \`npm i -g @north-light/cli@latest\`.` };
20
+ }
@@ -3,5 +3,10 @@ import { type SignInPrompt } from '../../core/directory/person-credential.js';
3
3
  export declare function showSignIn(prompt: SignInPrompt & {
4
4
  complete: string;
5
5
  }): void;
6
+ /** A computer with no `machine.json` and no local canvas becomes a fleet machine: `POST /v1/machines`, then `machine.json`, the credential, the directory registration and the machine daemon.
7
+ * The stored sign-in is reused when present, so running this again after `northlight_unreachable` resumes at registration. */
8
+ export declare function registerFreshComputer(directoryUrl: string): Promise<{
9
+ account: string;
10
+ }>;
6
11
  export declare const sysSigninLeaf: import("../../core/command.js").LeafDef;
7
12
  export declare const sysSignoutLeaf: import("../../core/command.js").LeafDef;
@@ -4,15 +4,16 @@ import { mkdirSync, openSync } from 'node:fs';
4
4
  import { dirname, join } from 'node:path';
5
5
  import { defineLeaf } from '../../core/command.js';
6
6
  import { CrtrError } from '../../core/errors.js';
7
- import { signIn, signOut } from '../../core/directory/person-credential.js';
8
- import { moveRecordPath, readMachineConfig } from '../../daemon/machine-link/config.js';
9
- import { sanitizedDaemonEnv, spawnDaemon, stopAllDaemons } from '../../daemon/manage.js';
7
+ import { controlPlaneUrl, personAccount, personBearer, readPersonCredential, signIn, signOut } from '../../core/directory/person-credential.js';
8
+ import { hasLocalCanvas, moveRecordPath, readMachineConfig, readOrCreateInstallId, writeMachineConfig, writeMachineCredential } from '../../daemon/machine-link/config.js';
9
+ import { probeDaemonHealth, sanitizedDaemonEnv, spawnDaemon, stopAllDaemons } from '../../daemon/manage.js';
10
+ import { hostname } from 'node:os';
10
11
  import { northlightUnreachable } from '../../core/directory/reach.js';
11
12
  import { envNodeId } from '../../shared/env.js';
12
13
  import { ExitCode } from '../../types.js';
13
14
  import { insideBroker } from './join.js';
14
- import { cliClient } from '../api-client.js';
15
15
  import { defaultDirectoryUrl, finishMove, registerThisMac, runMove, settleEarlierMove } from './import/move.js';
16
+ import { oldPackageInstalled } from './old-package.js';
16
17
  import { WAIT_FOR_PID_ENV } from './import/start.js';
17
18
  /** Open the confirm page in the person's browser; a failure to open it is harmless because the code and address are printed too. */
18
19
  function openBrowser(url) {
@@ -31,6 +32,10 @@ export function showSignIn(prompt) {
31
32
  * to the run's own person (404 `import_not_found` to anyone else). */
32
33
  function sameAccountOnly(machine) {
33
34
  return async (approved) => {
35
+ if (machine.runId === undefined) {
36
+ return machine.account === undefined || machine.account.id === approved.account.id ? undefined
37
+ : new CrtrError('signin_other_account', `This computer belongs to the Northlight account ${machine.account.display}. Sign in to that account.`, ExitCode.USAGE);
38
+ }
34
39
  let response;
35
40
  try {
36
41
  response = await fetch(new URL(`/v1/imports/${machine.runId}`, machine.apiUrl), { headers: { authorization: `Bearer ${approved.bearer}` }, signal: AbortSignal.timeout(30_000) });
@@ -59,6 +64,37 @@ function startDetachedMove(notify) {
59
64
  const args = [...process.execArgv, process.argv[1], 'sys', 'import', 'start', '--kind', 'machine', ...(notify === undefined ? [] : ['--notify', notify])];
60
65
  spawn(process.execPath, args, { detached: true, stdio: ['ignore', fd, fd], env }).unref();
61
66
  }
67
+ /** A computer with no `machine.json` and no local canvas becomes a fleet machine: `POST /v1/machines`, then `machine.json`, the credential, the directory registration and the machine daemon.
68
+ * The stored sign-in is reused when present, so running this again after `northlight_unreachable` resumes at registration. */
69
+ export async function registerFreshComputer(directoryUrl) {
70
+ const account = readPersonCredential() === undefined ? (await signIn(directoryUrl, showSignIn), await personAccount(directoryUrl)) : await personAccount(directoryUrl);
71
+ const apiUrl = await controlPlaneUrl(directoryUrl);
72
+ const bearer = await personBearer(directoryUrl);
73
+ const post = async (rotate) => {
74
+ try {
75
+ return await fetch(new URL(`/v1/machines${rotate ? '?rotate=1' : ''}`, apiUrl), { method: 'POST', headers: { authorization: `Bearer ${bearer}`, 'content-type': 'application/json' },
76
+ body: JSON.stringify({ install_id: readOrCreateInstallId(), name: hostname().slice(0, 64) }), signal: AbortSignal.timeout(30_000) });
77
+ }
78
+ catch (error) {
79
+ throw northlightUnreachable(error, apiUrl);
80
+ }
81
+ };
82
+ let response = await post(false);
83
+ if (response.status === 409 && (await response.clone().text()).includes('credential_exists'))
84
+ response = await post(true);
85
+ const text = await response.text();
86
+ if (!response.ok)
87
+ throw new CrtrError('machine_registration_failed', `Northlight refused to register this computer (HTTP ${response.status}): ${text.slice(0, 300)}`, ExitCode.GENERAL, { next: 'Run `crtr sys signin` again.' });
88
+ const body = JSON.parse(text);
89
+ if (typeof body.credential !== 'string' || typeof body.environment_id !== 'string')
90
+ throw new CrtrError('machine_registration_failed', 'Northlight answered without a credential', ExitCode.GENERAL);
91
+ writeMachineCredential(body.credential);
92
+ writeMachineConfig({ apiUrl, environmentId: body.environment_id, directoryUrl, account });
93
+ await registerThisMac(directoryUrl);
94
+ await stopAllDaemons();
95
+ await spawnDaemon();
96
+ return { account: account.display };
97
+ }
62
98
  const MOVING = (account) => `Signed in as ${account}. crtr is now moving this computer's records to Northlight; every agent here pauses for seconds to minutes. End your turn now; this conversation carries on when the move finishes.`;
63
99
  export const sysSigninLeaf = defineLeaf({
64
100
  name: 'signin',
@@ -79,12 +115,19 @@ export const sysSigninLeaf = defineLeaf({
79
115
  outputKind: 'object',
80
116
  effects: [
81
117
  'Calls the directory (`POST /v1/developer/logins`, then polls `/v1/developer/logins/poll`) and, once approved, writes `runtime/secrets/person-credential` (0600) and replaces the cached bearer. A declined, abandoned or refused sign-in writes nothing and leaves an existing sign-in as it was.',
118
+ 'Starts the local daemon first when it is not running, and waits until it serves.',
82
119
  'On a computer whose records are local: the move of `crtr sys import start --kind machine` (drains the daemon, uploads, restarts it in machine role); a move confirmed failed before the account holds the records ends the drain and signs this computer out again. If the account\'s result is unknown, the move record and drain remain for recovery. From inside a node it runs as a detached process logging to `runtime/import/move.log`.',
120
+ 'On a computer with no local records: registers it with `POST /v1/machines`, writes `runtime/machine.json` and `runtime/secrets/machine-credential`, and starts the machine daemon. Run again after `northlight_unreachable`, it resumes at registration with the stored sign-in.',
83
121
  'On a moved computer: restarts the daemon so it reconnects to Northlight.',
84
122
  'Unless this computer is already registered: calls `PUT <directory>/v1/runtimes/registration` with the sign-in bearer and a new public ES256 key, then writes `runtime/secrets/runtime-client.json` (0600) holding the private key and the returned runtime identity.',
85
123
  ],
86
124
  },
87
125
  run: async (input) => {
126
+ // A fresh home has no daemon yet, and the move reads the canvas through it: start it (a no-op when it already serves) before anything else.
127
+ await spawnDaemon();
128
+ const oldPackage = oldPackageInstalled();
129
+ if (oldPackage !== undefined)
130
+ process.stderr.write(`${oldPackage.message}\n`);
88
131
  const directoryUrl = input.directoryUrl === undefined ? defaultDirectoryUrl() : String(input.directoryUrl);
89
132
  const unfinished = await settleEarlierMove(showSignIn);
90
133
  if (unfinished !== undefined) {
@@ -103,6 +146,8 @@ export const sysSigninLeaf = defineLeaf({
103
146
  await spawnDaemon();
104
147
  return { account };
105
148
  }
149
+ if (!hasLocalCanvas())
150
+ return await registerFreshComputer(directoryUrl);
106
151
  const { account } = await signIn(directoryUrl, showSignIn);
107
152
  if (insideBroker()) {
108
153
  startDetachedMove(envNodeId());
@@ -120,8 +165,22 @@ export const sysSigninLeaf = defineLeaf({
120
165
  async function stopMovedComputer() {
121
166
  await stopAllDaemons();
122
167
  await spawnDaemon();
123
- const health = await cliClient({ local: true }).healthz();
124
- return health.signed_in === false;
168
+ return (await probeDaemonHealth()).signed_in === false;
169
+ }
170
+ /** End this computer's machine credential at the control plane with the stored sign-in, so signing out works with no daemon running. Skipped when there is no sign-in to authenticate with. */
171
+ async function revokeMachine(machine) {
172
+ if (readPersonCredential() === undefined)
173
+ return;
174
+ const bearer = await personBearer(machine.directoryUrl);
175
+ let response;
176
+ try {
177
+ response = await fetch(new URL(`/v1/machines/${machine.environmentId}`, machine.apiUrl), { method: 'DELETE', headers: { authorization: `Bearer ${bearer}` }, signal: AbortSignal.timeout(30_000) });
178
+ }
179
+ catch (error) {
180
+ throw northlightUnreachable(error, machine.apiUrl);
181
+ }
182
+ if (!response.ok && response.status !== 404)
183
+ throw new CrtrError('machine_revoke_failed', `Northlight refused to revoke this computer's machine credential (HTTP ${response.status}): ${(await response.text()).slice(0, 300)}`, ExitCode.GENERAL, { next: 'Run `crtr sys signout` again.' });
125
184
  }
126
185
  export const sysSignoutLeaf = defineLeaf({
127
186
  name: 'signout',
@@ -138,13 +197,16 @@ export const sysSignoutLeaf = defineLeaf({
138
197
  ],
139
198
  outputKind: 'object',
140
199
  effects: [
141
- 'Calls `POST /v1/developer/token/revoke` with the stored secret, then deletes `runtime/secrets/person-credential` and `person-bearer.json`. A bearer already issued stays valid for at most 5 minutes.',
200
+ 'On a fleet machine first calls `DELETE /v1/machines/<environment>` with the stored sign-in, which ends the machine credential (no running daemon needed). Then calls `POST /v1/developer/token/revoke` with the stored secret, then deletes `runtime/secrets/person-credential` and `person-bearer.json`. A bearer already issued stays valid for at most 5 minutes.',
142
201
  'On a computer whose records are in Northlight: restarts the daemon, which stops every agent and running cron here and takes no new work until `crtr sys signin`; agents keep their mail on Northlight and wake after it. Commands answer `not_signed_in`.',
143
202
  ],
144
203
  },
145
204
  run: async () => {
205
+ const machine = readMachineConfig();
206
+ if (machine !== undefined)
207
+ await revokeMachine(machine);
146
208
  const { signedOut, revoked } = await signOut();
147
- const stopped = readMachineConfig() === undefined ? false : await stopMovedComputer();
209
+ const stopped = machine === undefined ? false : await stopMovedComputer();
148
210
  return { signed_out: signedOut, revoked, stopped };
149
211
  },
150
212
  render: (r) => `<signout signed_out="${r['signed_out']}" revoked="${r['revoked']}" stopped="${r['stopped']}"/>`,
@@ -111,6 +111,8 @@ export declare function grantsOfPerson(person: string): Promise<Array<Pick<Grant
111
111
  export declare function grantExpired(grant: Pick<GrantRecord, 'expires_at'>): boolean;
112
112
  /** The active form of a grant record read earlier, or null when it is not active, is past `expires_at`, or is unparsable. */
113
113
  export declare function activeRecord(grant: GrantRecord): ActiveGrant | null;
114
+ /** JSON with every object's keys sorted, at every depth, and arrays kept in order. */
115
+ export declare function canonicalJson(value: unknown): string;
114
116
  /** `grant.get`'s `version`: an opaque string that changes exactly when what an app
115
117
  * reads from its grant changes — `rev`, `resolved_scopes` (order kept), `spend_cap`,
116
118
  * `payer`, `inference_endpoint`, `dependencies`. `synced_at` and the token's claims are left out, so a
@@ -4,6 +4,7 @@ import { openDb, withCanvasWrite } from '../canvas/db.js';
4
4
  import { isUnsandboxedMachine } from '../runtime/unsandboxed.js';
5
5
  import { replaceWrittenBy, userSubject } from '../permissions/facts.js';
6
6
  import { GROUP_TYPE } from '../permissions/builtin.js';
7
+ import { shadowCheck } from './shadow.js';
7
8
  const SETUP_STATES = ['not_started', 'pending', 'ready', 'failed', 'unavailable'];
8
9
  const STRENGTHS = ['ultra', 'strong', 'medium', 'light'];
9
10
  /** The fleet's runtime principal (`CRTR_RUNTIME`): a cloud role reads only its own runtime's grants, so a person's VM or laptop grants are never used. A Mac sets none. */
@@ -104,7 +105,10 @@ function active(row) {
104
105
  if (!row || row.status !== 'active')
105
106
  return null;
106
107
  try {
107
- return activeRecord(record(row));
108
+ const grant = activeRecord(record(row));
109
+ if (grant !== null)
110
+ shadowCheck(grant);
111
+ return grant;
108
112
  }
109
113
  catch (error) {
110
114
  if (error instanceof TypeError || error instanceof SyntaxError)
@@ -278,7 +282,7 @@ export function activeRecord(grant) {
278
282
  }
279
283
  }
280
284
  /** JSON with every object's keys sorted, at every depth, and arrays kept in order. */
281
- function canonicalJson(value) {
285
+ export function canonicalJson(value) {
282
286
  if (Array.isArray(value))
283
287
  return `[${value.map(canonicalJson).join(',')}]`;
284
288
  if (value && typeof value === 'object') {
@@ -0,0 +1,15 @@
1
+ import { type GrantRecord } from './mirror.js';
2
+ /** Test hook: how long a cached answer is used before its epochs are re-checked. */
3
+ export declare function setShadowTtl(ms: number): void;
4
+ /** Test hook: forget every cached answer. */
5
+ export declare function resetShadowCache(): void;
6
+ /** 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. */
7
+ export declare const shadowCounts: {
8
+ agree: number;
9
+ disagree: number;
10
+ lagging: number;
11
+ error: number;
12
+ };
13
+ export declare function shadowIdle(): Promise<void>;
14
+ /** Compare one stored grant with the directory's live answer, in the background, on the fleet only. Never throws and never delays the caller. */
15
+ export declare function shadowCheck(stored: GrantRecord): void;
@@ -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
+ }
@@ -1,7 +1,10 @@
1
+ import { CrtrError } from '../../errors.js';
1
2
  import type { ImportRunDTO, ImportStartRequest, ImportStartedDTO, ImportStoreNameDTO, ImportUploadUrlsDTO } from '../../../api/dto/imports.js';
2
3
  /** The dump directory's file holding the opened file stores, and the order they are uploaded in. */
3
4
  export declare const STORE_FILE = "stores.json";
4
5
  export declare const STORE_ORDER: readonly ImportStoreNameDTO[];
6
+ /** The control plane refuses a source that runs another release than its own: name the release it accepts and the command that installs it. */
7
+ export declare function releaseMismatch(accepted: string, status: number): CrtrError;
5
8
  export declare class ImportCloud {
6
9
  private readonly apiUrl;
7
10
  private readonly token;
@@ -1,6 +1,8 @@
1
1
  // The exporter's HTTP side: `/v1/imports` on the control plane with the person's (or the operator's) bearer token, and signed R2 PUTs.
2
2
  // Imports Node built-ins only, so a CLI leaf can use it.
3
3
  import { CrtrError, general } from '../../errors.js';
4
+ import { ExitCode } from '../../../types.js';
5
+ import { crtrVersion } from '../../../shared/crtr-version.js';
4
6
  import { NORTHLIGHT_UNREACHABLE } from '../../directory/reach.js';
5
7
  /** The dump directory's file holding the opened file stores, and the order they are uploaded in. */
6
8
  export const STORE_FILE = 'stores.json';
@@ -17,6 +19,11 @@ function failureText(error) {
17
19
  const cause = error.cause;
18
20
  return `failed: ${error instanceof Error ? error.message : String(error)}${typeof cause?.code === 'string' ? ` (${cause.code})` : ''}`;
19
21
  }
22
+ /** The control plane refuses a source that runs another release than its own: name the release it accepts and the command that installs it. */
23
+ export function releaseMismatch(accepted, status) {
24
+ const command = `npm i -g @north-light/cli@${accepted}`;
25
+ return new CrtrError('release_mismatch', `Northlight accepts only crtr ${accepted} for this step, and this computer runs ${crtrVersion()}. Install it with \`${command}\`, then run \`crtr sys signin\` again.`, ExitCode.GENERAL, { status, code: 'release_mismatch', accepted, next: `Run \`${command}\`, then \`crtr sys signin\`.` });
26
+ }
20
27
  export class ImportCloud {
21
28
  apiUrl;
22
29
  token;
@@ -83,6 +90,9 @@ export class ImportCloud {
83
90
  catch {
84
91
  code = undefined;
85
92
  }
93
+ const accepted = code === 'release_mismatch' ? /control plane accepts (\S+)/.exec(text)?.[1]?.replace(/[^0-9A-Za-z.+-]+$/, '') : undefined;
94
+ if (accepted !== undefined)
95
+ throw releaseMismatch(accepted, response.status);
86
96
  throw general(`${method} ${path} answered ${response.status}: ${text.slice(0, 500)}`, { status: response.status, ...(typeof code === 'string' ? { code } : {}) });
87
97
  }
88
98
  return (text === '' ? undefined : JSON.parse(text));
@@ -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' },
@@ -5,11 +5,11 @@ export interface NorthlightAccount {
5
5
  display: string;
6
6
  }
7
7
  /** `directoryUrl` is the directory the person signs in against (`crtr sys signin`).
8
- * `account` is the account the records moved into, kept only to name it when another account signs in; a Mac moved before it existed has none. */
8
+ * `runId` is present only on a computer whose records were moved by an import. `account` is the account this computer belongs to (always written now; a Mac moved before it existed has none). */
9
9
  export interface MachineConfig {
10
10
  apiUrl: string;
11
11
  environmentId: string;
12
- runId: string;
12
+ runId?: string;
13
13
  directoryUrl: string;
14
14
  account?: NorthlightAccount;
15
15
  }
@@ -43,3 +43,8 @@ export declare function deleteMoveRecord(): void;
43
43
  export declare const isMoveCommitted: () => boolean;
44
44
  /** 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`). */
45
45
  export declare const moveUnfinishedError: (reason?: string) => CrtrError;
46
+ /** 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. */
47
+ export declare const installIdPath: () => string;
48
+ export declare function readOrCreateInstallId(): string;
49
+ /** Whether this computer still holds a local canvas from before crtr was fleet-only (a supervised Postgres or a SQLite file). */
50
+ export declare const hasLocalCanvas: () => boolean;
@@ -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)));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.736",
3
+ "version": "0.3.738",
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",