@north-light/cli 0.3.750 → 0.3.752

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/api/dto/environments.d.ts +37 -0
  4. package/dist/api/routes.d.ts +2 -0
  5. package/dist/api/routes.js +1 -1
  6. package/dist/builtin-memory/crouter-sdk/release-notes.md +10 -0
  7. package/dist/clients/attach/viewer.js +1 -1
  8. package/dist/core/canvas/schema-pg/037-grant-principals.sql +50 -0
  9. package/dist/core/canvas/schema-version.d.ts +1 -1
  10. package/dist/core/canvas/schema-version.js +1 -1
  11. package/dist/core/environments.js +1 -1
  12. package/dist/core/grants/local.js +1 -1
  13. package/dist/core/grants/mirror.d.ts +11 -3
  14. package/dist/core/grants/mirror.js +12 -12
  15. package/dist/core/grants/shadow.js +1 -1
  16. package/dist/core/grants/sync.js +1 -1
  17. package/dist/core/graph/objects.d.ts +3 -1
  18. package/dist/core/graph/objects.js +10 -10
  19. package/dist/core/ledger/payer.d.ts +4 -4
  20. package/dist/core/ledger/payer.js +1 -1
  21. package/dist/core/llm/app-rungs.js +1 -1
  22. package/dist/core/llm/run.d.ts +2 -2
  23. package/dist/core/llm/run.js +2 -2
  24. package/dist/core/profiles/manifest.d.ts +5 -0
  25. package/dist/core/profiles/manifest.js +1 -1
  26. package/dist/core/runtime/runner/blaxel/image-build.d.ts +10 -11
  27. package/dist/core/runtime/runner/blaxel/image-build.js +7 -6
  28. package/dist/core/runtime/start-check.js +1 -1
  29. package/dist/daemon/api/app-listener.js +12 -12
  30. package/dist/daemon/api/handlers/app-environments.d.ts +2 -0
  31. package/dist/daemon/api/handlers/app-environments.js +1 -0
  32. package/dist/daemon/api/handlers/git-credential.js +1 -1
  33. package/dist/daemon/api/handlers/runs.js +1 -1
  34. package/dist/daemon/api/operations.js +1 -1
  35. package/dist/daemon/api/principal.d.ts +11 -5
  36. package/dist/daemon/api/principal.js +1 -1
  37. package/dist/daemon/api/server.js +1 -1
  38. package/dist/daemon/crtrd.js +12 -12
  39. package/dist/daemon/reconcilers/recipe-image.d.ts +2 -0
  40. package/dist/daemon/reconcilers/recipe-image.js +5 -5
  41. package/docs/ci-runner.md +1 -1
  42. package/docs/sdk/release-notes.md +10 -0
  43. package/package.json +3 -3
  44. package/packages/crouter-api/dist/api/contract.js +1 -1
  45. package/packages/crouter-api/dist/api/routes.js +2 -0
  46. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  47. package/packages/crouter-api/dist/core/environments.js +3 -2
  48. package/packages/crouter-api/dist/core/grants/local.js +1 -1
  49. package/packages/crouter-api/dist/core/grants/mirror.js +35 -11
  50. package/packages/crouter-api/dist/core/grants/shadow.js +4 -2
  51. package/packages/crouter-api/dist/core/grants/sync.js +5 -4
  52. package/packages/crouter-api/dist/core/graph/objects.js +2 -2
  53. package/packages/crouter-api/dist/core/ledger/payer.js +8 -3
  54. package/packages/crouter-api/dist/core/llm/app-rungs.js +2 -2
  55. package/packages/crouter-api/dist/core/llm/run.js +3 -2
  56. package/packages/crouter-api/dist/core/profiles/manifest.js +1 -1
  57. package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +42 -44
  58. package/packages/crouter-api/dist/core/runtime/start-check.js +2 -2
  59. package/packages/crouter-api/dist/daemon/api/handlers/git-credential.js +12 -2
  60. package/packages/crouter-api/dist/daemon/api/operations.js +4 -0
  61. package/packages/crouter-api/dist/daemon/api/principal.js +26 -7
  62. package/packages/crouter-api/dist/daemon/reconcilers/recipe-image.js +9 -1
  63. package/packages/crouter-api/package.json +1 -1
  64. package/packages/crouter-identity/dist/index.d.ts +4 -2
  65. package/packages/crouter-identity/dist/index.js +31 -12
  66. package/packages/crouter-identity/package.json +1 -1
  67. package/packages/crouter-plugin/dist/serve.js +4 -1
  68. package/packages/crouter-plugin/dist/verify.js +36 -8
  69. package/packages/crouter-plugin/package.json +3 -3
  70. package/runtime.lock.json +14 -14
@@ -15,6 +15,7 @@ import { eligibleHostedEndpoint, readHostedEndpoint } from '../grants/hosted-end
15
15
  import { parseProviderPayment } from '../provider-failure.js';
16
16
  import { personIdAsync } from '../canvas/person.js';
17
17
  import { getNode } from '../canvas/canvas.js';
18
+ import { endpointPays } from '../grants/mirror.js';
18
19
  import { outboundToken } from '../providers/mint.js';
19
20
  import { discardFile } from '../providers/token-cache.js';
20
21
  import { ProviderError } from '../providers/errors.js';
@@ -154,7 +155,7 @@ function allowedFallback(model, responseModel) {
154
155
  return fallbacks?.find((fallback) => fallback.provider === model.provider && fallback.model === responseModel);
155
156
  }
156
157
  export function llmCallerOf(grant) {
157
- return grant ? { payer: grant.payer ?? 'user', sub: grant.sub, grantee: grant.grantee, inference_endpoint: grant.inference_endpoint ?? null } : undefined;
158
+ return grant ? { payer: grant.payer, sub: grant.sub, grantee: grant.grantee, inference_endpoint: grant.inference_endpoint ?? null } : undefined;
158
159
  }
159
160
  /** A directory-token failure as the `llm` refusal it is (RT-RTE-26): the directory unreachable or failing is
160
161
  * transient, a refused mint is a configuration fault. */
@@ -184,7 +185,7 @@ function vendorRequestId(headers) {
184
185
  * and a completed call writes one `charges` row. Omitted, the call is neither checked nor recorded.
185
186
  * `causedBy`: the request's `Crtr-Caused-By` value (`message:<id>`, `request:<id>`, `cron_run:<id>`), when it carried one; stored on the row. */
186
187
  export async function runLlm(input, signal, onChunk, target, spend, caller, causedBy) {
187
- const app = caller?.payer === 'app' ? caller : undefined;
188
+ const app = caller && endpointPays(caller) ? caller : undefined;
188
189
  if (input.payer === 'app' && !app)
189
190
  throw new RunError(403, 'payer_not_app', 'this grant is not app-paid');
190
191
  if (input.payer === 'user' && app)
@@ -367,7 +367,7 @@ export async function createProfile(name, projects = [], opts = {}) {
367
367
  else if (cloudProfileWriter === null)
368
368
  throw new Error('a cloud role has no profile environment writer registered');
369
369
  else
370
- await cloudProfileWriter({ profileId, grantee: profileApp(manifest), person: personId(), ...(opts.memoryMb === undefined ? {} : { memoryMb: opts.memoryMb }), ...(opts.recipe === undefined ? {} : { recipe: opts.recipe }) }, async (environmentId) => { manifest.environment_id = environmentId; await insert(); });
370
+ await cloudProfileWriter({ profileId, grantee: profileApp(manifest), person: opts.appEnvironment === true ? profileApp(manifest) : personId(), ...(opts.appEnvironment === true ? { payer: opts.payer ?? profileApp(manifest) } : {}), ...(opts.memoryMb === undefined ? {} : { memoryMb: opts.memoryMb }), ...(opts.recipe === undefined ? {} : { recipe: opts.recipe }) }, async (environmentId) => { manifest.environment_id = environmentId; await insert(); });
371
371
  return { profileId, manifest };
372
372
  }
373
373
  export async function ensureAppProfile(grantee) {
@@ -1,12 +1,12 @@
1
- // src/core/runtime/runner/blaxel/image-build.ts — the recipe image: Dockerfile writer, build-directory clone, Blaxel image build (C-A5, D25/D93/D94).
1
+ // src/core/runtime/runner/blaxel/image-build.ts — the recipe image: Dockerfile writer, build-directory writer, Blaxel image build (C-A5, D25/D93/D94).
2
2
  //
3
3
  // An environment recipe (repositories, pi packages, setup script) becomes one Blaxel sandbox image per recipe revision. The control plane
4
- // clones each repository into a build directory with a short-lived GitHub token, writes a Dockerfile that only COPYs the clones, zips the
5
- // directory and uploads it to Blaxel's build API. The token is handed to `git` through the environment of the clone process: it is in no
6
- // file, no Dockerfile line, no build argument and no `.git/config`, so it is in no image layer. Nothing of the person's secrets reaches the build.
7
- // `fetch` and `git` are injectable so the unit lane runs the whole flow against fakes.
8
- import { spawn } from 'node:child_process';
9
- import { constants as fsConstants, lstatSync, mkdirSync, readFileSync, readdirSync, readlinkSync, rmSync, writeFileSync } from 'node:fs';
4
+ // writes a small build directory (Dockerfile, setup script, `blaxel.toml`, `.env.build`), zips it and uploads it to Blaxel's build API. The
5
+ // repositories are cloned by the build stage on Blaxel, never on the control plane, so a large repository costs the control plane nothing.
6
+ // The short-lived GitHub installation token reaches that stage as the build argument `CRTR_GIT_TOKEN` (its value only in `.env.build`), as
7
+ // the packages token does: the final stage declares no ARG and copies only the installed trees, so neither token is in the final image.
8
+ // `fetch` is injectable so the unit lane runs the whole flow against fakes.
9
+ import { constants as fsConstants, lstatSync, readFileSync, readdirSync, readlinkSync, rmSync, writeFileSync } from 'node:fs';
10
10
  import { join, relative } from 'node:path';
11
11
  import { crc32, deflateRawSync } from 'node:zlib';
12
12
  import { BlaxelApiError } from './client.js';
@@ -34,7 +34,8 @@ export const RUN_USER_NPMRC = [
34
34
  * this pins their user config to it for every app. pnpm 12 reads credentials from no other non-repository file (not npm's or pnpm's global config). */
35
35
  export const RUN_USER_NPMRC_ENV = `ENV NPM_CONFIG_USERCONFIG=/home/${RUN_USER}/.npmrc`;
36
36
  const writeRunUserNpmrc = () => `printf '%s\\n' ${RUN_USER_NPMRC.map((l) => `'${l}'`).join(' ')} > /home/${RUN_USER}/.npmrc`;
37
- export const REPOS_DIR = 'repos';
37
+ /** The build argument that carries the GitHub installation token into the build stage. */
38
+ export const GIT_TOKEN_ARG = 'CRTR_GIT_TOKEN';
38
39
  /** Where the image keeps the setup script's output, and its exit status when it failed. `sandbox-start.mjs` reads both (it derives them from `/work/.crtr`). */
39
40
  export const SETUP_LOG_FILE = '/work/.crtr/setup.log';
40
41
  export const SETUP_FAILED_FILE = '/work/.crtr/setup-failed';
@@ -52,10 +53,27 @@ const lines = (text) => (text ?? '').split('\n').map((l) => l.trim()).filter((l)
52
53
  /** A RUN step that cannot fail the build (Blaxel hangs on a failed step and its build log is unreadable): its output goes to `SETUP_LOG_FILE` and a
53
54
  * failure appends `<label> exited <status>` to `SETUP_FAILED_FILE`, which the sandbox start script refuses to start on. */
54
55
  const guarded = (label, command) => `RUN { ${command}; } >> ${SETUP_LOG_FILE} 2>&1 || echo ${shellQuote(label)} "exited $?" >> ${SETUP_FAILED_FILE}`;
55
- /** The Dockerfile for a recipe revision. Pure. It clones and fetches nothing: the repositories arrive by `COPY`, so a git token cannot appear here.
56
- * Two stages: `build` runs the setup script as root; the final image copies only the installed trees out of it, never `/root`. With `packagesToken`
57
- * the build stage declares `ARG NODE_AUTH_TOKEN` (its value comes from `.env.build` in the upload), so the token is in no layer of the final image. */
58
- export function recipeDockerfile(recipe, revision, packagesToken = false) {
56
+ /** A repository's clone step in the build stage. Blobless (`--filter=blob:none`): full history, file contents fetched for the checkout only, so a
57
+ * large repository stays small in the image while `git log` and branching still work; older contents are fetched on demand through the sandbox's
58
+ * credential helper. The token is handed to git as a config entry of that one process: not in the URL, not in `.git/config`. */
59
+ const cloneStep = (repo, revision, withToken) => {
60
+ const auth = withToken ? `-c http.https://github.com/.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$${GIT_TOKEN_ARG}" | base64 | tr -d '\\n')" ` : '';
61
+ // `: r<revision>` keeps a rebuild from reusing a cached clone layer of an earlier revision.
62
+ return guarded(`clone ${repo.github_full_name}`, `: r${Math.trunc(revision)}; GIT_TERMINAL_PROMPT=0 git ${auth}clone --quiet --filter=blob:none --branch ${shellQuote(repo.default_branch)} ${shellQuote(`https://github.com/${repo.github_full_name}.git`)} ${shellQuote(`/work/${repo.name}`)}`);
63
+ };
64
+ /** Throws when a repository's name, full name or branch could escape its place in the Dockerfile. */
65
+ export function assertRepositoryShape(repo) {
66
+ if (!/^[A-Za-z0-9._-]+$/.test(repo.name) || repo.name === '.' || repo.name === '..')
67
+ throw new Error(`repository name ${JSON.stringify(repo.name)} is not a plain directory name`);
68
+ if (!/^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/.test(repo.github_full_name))
69
+ throw new Error(`repository ${JSON.stringify(repo.github_full_name)} is not an owner/name pair`);
70
+ if (repo.default_branch === '' || /[\s\x00-\x1f'"`$\\]/.test(repo.default_branch))
71
+ throw new Error(`branch ${JSON.stringify(repo.default_branch)} of ${repo.github_full_name} is not a plain branch name`);
72
+ }
73
+ /** The Dockerfile for a recipe revision. Pure. Two stages: `build` clones the repositories and runs the setup script as root; the final image copies
74
+ * only the installed trees out of it, never `/root`. Each token the build stage needs is declared there as an ARG (its value comes from `.env.build`
75
+ * in the upload) and never in the final stage, so no token is in a layer of the final image. */
76
+ export function recipeDockerfile(recipe, revision, packagesToken = false, gitToken = false) {
59
77
  const packages = lines(recipe.pi_packages);
60
78
  const hasScript = recipe.setup_script !== null && recipe.setup_script.trim() !== '';
61
79
  const base = [
@@ -65,10 +83,12 @@ export function recipeDockerfile(recipe, revision, packagesToken = false) {
65
83
  `COPY --from=${SANDBOX_API_IMAGE} /sandbox-api /usr/local/bin/sandbox-api`,
66
84
  `RUN adduser -D -h /home/${RUN_USER} -s /bin/sh ${RUN_USER} && mkdir -p /work/.crtr ${RECIPE_PI_AGENT_DIR} && chown -R ${RUN_USER} /work /var/lib/crtr`,
67
85
  ];
68
- const out = [`${base[0]} AS build`, ...(packagesToken ? ['ARG NODE_AUTH_TOKEN'] : []), ...base.slice(1), `RUN rm -f ${SETUP_FAILED_FILE} ${SETUP_LOG_FILE}`, guarded('npm install -g pnpm', 'npm install -g pnpm && mkdir -p /var/lib/postgresql')];
69
- // An empty `repos/` is not in the zip, and a COPY of a missing directory fails the build.
70
- if (recipe.repositories.length > 0)
71
- out.push(`COPY --chown=${RUN_USER} ${REPOS_DIR}/ /work/`);
86
+ for (const repo of recipe.repositories)
87
+ assertRepositoryShape(repo);
88
+ const out = [`${base[0]} AS build`, ...(packagesToken ? ['ARG NODE_AUTH_TOKEN'] : []), ...(gitToken && recipe.repositories.length > 0 ? [`ARG ${GIT_TOKEN_ARG}`] : []), ...base.slice(1), `RUN rm -f ${SETUP_FAILED_FILE} ${SETUP_LOG_FILE}`, guarded('npm install -g pnpm', 'npm install -g pnpm && mkdir -p /var/lib/postgresql')];
89
+ // A failed clone fails no step (see `guarded`): it is in the setup log, and the sandbox start script refuses to start on it.
90
+ for (const repo of recipe.repositories)
91
+ out.push(cloneStep(repo, revision, gitToken));
72
92
  if (packages.length > 0)
73
93
  out.push(guarded('npm install pi', `npm install -g @earendil-works/pi-coding-agent@${PI_VERSION}`));
74
94
  if (hasScript)
@@ -99,37 +119,15 @@ export function recipeDockerfile(recipe, revision, packagesToken = false) {
99
119
  out.push(RUN_USER_NPMRC_ENV, `USER ${RUN_USER}`, 'WORKDIR /work', 'ENTRYPOINT ["/usr/local/bin/sandbox-api"]', '');
100
120
  return out.join('\n');
101
121
  }
102
- const runGit = (args, env, cwd) => new Promise((resolve, reject) => {
103
- const child = spawn('git', args, { cwd, env: { ...process.env, ...env, GIT_TERMINAL_PROMPT: '0' }, stdio: ['ignore', 'ignore', 'pipe'] });
104
- let stderr = '';
105
- child.stderr.on('data', (chunk) => { stderr += chunk.toString(); });
106
- child.on('error', reject);
107
- child.on('close', (code) => { if (code === 0)
108
- resolve();
109
- else
110
- reject(new Error(`git ${args[0]} failed (${code}): ${stderr.slice(0, 300)}`)); });
111
- });
112
- /** Clones each repository into `<dir>/repos/<name>` and writes the Dockerfile and the setup script beside it. */
122
+ /** Writes the Dockerfile, `blaxel.toml`, the setup script and `.env.build` into `dir`. Clones nothing: the build stage on Blaxel does. */
113
123
  export async function prepareBuildDir(input) {
114
- const git = input.git ?? runGit;
115
124
  const packagesToken = input.packagesToken ?? null;
116
- const cloneUrl = input.cloneUrl ?? ((full) => `https://github.com/${full}.git`);
117
- mkdirSync(join(input.dir, REPOS_DIR), { recursive: true });
118
- // The token travels as a git config entry in the clone process's environment: not in argv, not written to `.git/config`.
119
- const auth = input.token === null ? {} : {
120
- GIT_CONFIG_COUNT: '1',
121
- GIT_CONFIG_KEY_0: 'http.https://github.com/.extraheader',
122
- GIT_CONFIG_VALUE_0: `AUTHORIZATION: basic ${Buffer.from(`x-access-token:${input.token}`).toString('base64')}`,
123
- };
124
- for (const repo of input.recipe.repositories) {
125
- if (!/^[A-Za-z0-9._-]+$/.test(repo.name) || repo.name === '.' || repo.name === '..')
126
- throw new Error(`repository name ${JSON.stringify(repo.name)} is not a plain directory name`);
127
- await git(['clone', '--quiet', '--branch', repo.default_branch, cloneUrl(repo.github_full_name), join(REPOS_DIR, repo.name)], auth, input.dir);
128
- }
125
+ const gitToken = input.recipe.repositories.length > 0 ? input.token : null;
129
126
  writeFileSync(join(input.dir, BLAXEL_TOML_FILE), BLAXEL_TOML);
130
- writeFileSync(join(input.dir, 'Dockerfile'), recipeDockerfile(input.recipe, input.revision, packagesToken !== null));
131
- if (packagesToken !== null)
132
- writeFileSync(join(input.dir, '.env.build'), `NODE_AUTH_TOKEN=${packagesToken}\n`, { mode: 0o600 });
127
+ writeFileSync(join(input.dir, 'Dockerfile'), recipeDockerfile(input.recipe, input.revision, packagesToken !== null, gitToken !== null));
128
+ const buildEnv = [...(packagesToken !== null ? [`NODE_AUTH_TOKEN=${packagesToken}`] : []), ...(gitToken !== null ? [`${GIT_TOKEN_ARG}=${gitToken}`] : [])];
129
+ if (buildEnv.length > 0)
130
+ writeFileSync(join(input.dir, '.env.build'), `${buildEnv.join('\n')}\n`, { mode: 0o600 });
133
131
  if (input.recipe.setup_script !== null && input.recipe.setup_script.trim() !== '')
134
132
  writeFileSync(join(input.dir, SETUP_SCRIPT_FILE), input.recipe.setup_script.endsWith('\n') ? input.recipe.setup_script : `${input.recipe.setup_script}\n`);
135
133
  }
@@ -2,7 +2,7 @@
2
2
  // starts or a dormant node revives. The candidate's payer is whoever pays the node's model calls.
3
3
  import { check, environmentPayerOfProfile, findRefusal, payerOf } from '../ledger/index.js';
4
4
  import { RunError } from '../runs/operations.js';
5
- import { grantStanding, payerOfGrant } from '../grants/mirror.js';
5
+ import { grantRecord, grantStanding } from '../grants/mirror.js';
6
6
  import { callerTerminalGrant } from '../grants/terminal.js';
7
7
  /** The start candidate for an identity, or null when no person is known yet (a terminal node before its first grant snapshot). */
8
8
  export async function startCandidateOf(who) {
@@ -10,7 +10,7 @@ export async function startCandidateOf(who) {
10
10
  const sub = who.sub ?? (grantee === 'app:terminal' ? (await callerTerminalGrant())?.sub : undefined) ?? null;
11
11
  if (sub === null)
12
12
  return null;
13
- const paid = await payerOfGrant(who.grant_id);
13
+ const paid = who.grant_id ? (await grantRecord(who.grant_id))?.payer : null;
14
14
  const payer = payerOf({ call: 'start', grantPayer: paid, sub, grantee, environmentPayer: await environmentPayerOfProfile(who.profile_id) });
15
15
  return { scope: 'start', payer: payer.payer, sub, grantee };
16
16
  }
@@ -48,8 +48,18 @@ export async function mintInstallationToken(sub, repositories, allowPullRequestW
48
48
  if (!response.ok) {
49
49
  const code = typeof parsed.error === 'object' ? parsed.error?.code : parsed.code;
50
50
  const message = (typeof parsed.error === 'object' ? parsed.error?.message : parsed.message) ?? `the GitHub service answered ${response.status}`;
51
- if (response.status === 409 && (code === 'repositories_span_installations' || code === 'github_not_connected'))
52
- throw new ApiError(409, code, message, { repositories });
51
+ // The GitHub app names the page where the person links GitHub and installs the App; the CLI shows it as the next step.
52
+ const next = typeof parsed.error === 'object' ? parsed.error?.next : parsed.next;
53
+ if (response.status === 409 && (code === 'repositories_span_installations' || code === 'github_not_connected')) {
54
+ const connect = typeof next === 'string' && next !== '' ? next : undefined;
55
+ throw new ApiError(409, code, message, { repositories, ...(connect === undefined ? {} : {
56
+ error: code, message,
57
+ next: code === 'github_not_connected'
58
+ ? `Ask the person to open ${connect}, link GitHub and install the Northlight GitHub App on the account that owns these repositories (choose "All repositories"), then retry.`
59
+ : `List repositories from one GitHub account only; manage installations at ${connect}.`,
60
+ url: connect,
61
+ }) });
62
+ }
53
63
  throw new ApiError(502, 'github_service_failed', message, { status: response.status, ...(code === undefined ? {} : { code }) });
54
64
  }
55
65
  if (typeof parsed.token !== 'string' || typeof parsed.expires_at !== 'string')
@@ -195,6 +195,10 @@ export const OPERATIONS = [
195
195
  { name: 'profile.env.remove', method: 'DELETE', path: '/v1/profiles/:name/env/:var', classes: ['person', 'app', 'broker'], resource: 'profile' },
196
196
  { name: 'profile.environment.get', method: 'GET', path: '/v1/profiles/:name/environment', classes: ['person', 'broker', 'cron'], resource: 'profile' },
197
197
  { name: 'profile.environment.set', method: 'PUT', path: '/v1/profiles/:name/environment', classes: ['person', 'broker'], resource: 'profile' },
198
+ { name: 'environment.create', method: 'POST', path: '/v1/environments', classes: ['app'], resource: 'profile' },
199
+ { name: 'environment.list', method: 'GET', path: '/v1/environments', classes: ['app', 'person'], resource: 'profile' },
200
+ { name: 'environment.patch', method: 'PATCH', path: '/v1/environments/:name', classes: ['app', 'person'], resource: 'profile' },
201
+ { name: 'environment.delete', method: 'DELETE', path: '/v1/environments/:name', classes: ['app', 'person'], resource: 'profile' },
198
202
  { name: 'profiles.delete.116', method: 'DELETE', path: '/v1/profiles/:name', classes: ['person', 'app', 'broker'], resource: 'profile' },
199
203
  { name: 'profile.list', method: 'GET', path: '/v1/profiles', classes: ['person', 'app', 'broker', 'cron'], resource: 'profile', stage: 'chat' },
200
204
  { name: 'profiles.get.118', method: 'GET', path: '/v1/profiles/:name', classes: ['person', 'app', 'broker'], resource: 'profile' },
@@ -1,6 +1,7 @@
1
- import { covers, JwksCache, MissingRevClaimError, verifyCallToken } from '@north-light/identity';
1
+ import { covers, JwksCache, parsePrincipal, MissingRevClaimError, verifyCallToken } from '@north-light/identity';
2
2
  import { createLocalJWKSet, decodeProtectedHeader, jwtVerify } from 'jose';
3
3
  import { callerGrantOf, coverGrant } from '../../core/grants/cover.js';
4
+ import { ownerScopes } from '../../core/grants/owner.js';
4
5
  import { RunError } from '../../core/runs/operations.js';
5
6
  import { NoticeLedger } from './sync-notice.js';
6
7
  /** The 401 for a handoff that does not verify; one message per purpose, shared by the resolver and the vendor and key pages. */
@@ -119,21 +120,33 @@ export class AppPrincipalResolver {
119
120
  async resolve(authorization, scope) {
120
121
  return this.resolveVerified(await this.verifyCall(authorization), scope);
121
122
  }
122
- /** The caller an already-verified app token names. Grantee, grant and rev come from the token's app link
123
- * (`chain[0]`, which must be the whole chain); the mirror is made to cover the link's `rev` and the grant
124
- * is read now (`coverGrant`). A token whose presenter is not an app link holding a grant is refused 401. */
123
+ /** The caller an already-verified token names, from `chain[0]` (which must be the whole chain): (a) an app link holding a
124
+ * grant, (b) an owner link (a grantless app link whose app owns `sub`'s namespace: no grant row, the app's declared
125
+ * scopes), or (c) a person's grant-bearing link on an exchanged token. A grant is covered by the mirror and read now
126
+ * (`coverGrant`). Any other presenter is refused 401. */
125
127
  async resolveVerified(token, scope) {
126
128
  const link = token.chain[0];
127
129
  const claims = token.claims;
128
- if (token.chain.length !== 1 || !link || !link.sub.startsWith('app:') || link.grant === undefined || link.rev === undefined || !/^[A-Za-z0-9_-]{1,64}$/.test(claims.client_id) ||
130
+ const grantLink = link !== undefined && link.grant !== undefined && link.rev !== undefined;
131
+ const person = link !== undefined && parsePrincipal(link.sub)?.kind === 'user';
132
+ if (token.chain.length !== 1 || !link || !/^[A-Za-z0-9_-]{1,64}$/.test(claims.client_id) ||
133
+ !(link.owner === true || (grantLink && (link.sub.startsWith('app:') || person))) ||
129
134
  (claims.grantee !== undefined && claims.grantee !== link.sub) || (claims['rev'] !== undefined && claims['rev'] !== link.rev)) {
130
135
  throw new RunError(401, 'unauthorized', 'invalid directory access token');
131
136
  }
137
+ if (link.owner === true) {
138
+ const resolved = ownerScopes(link.sub);
139
+ if (scope && !resolved.some((held) => covers(held, scope))) {
140
+ throw new RunError(403, 'scope_missing', `missing scope ${scope}`, undefined, undefined, scope);
141
+ }
142
+ return { sub: token.sub, grantee: link.sub, actor: link.sub, client_id: claims.client_id, grant: null, rev: null, resolved,
143
+ resolved_scopes: resolved.map((held) => ({ scope: held, mode: 'always' })), spend_cap: null, dependencies: {}, exp: claims.exp };
144
+ }
132
145
  const grant = await coverGrant(link.grant, link.rev, token.sub, link.sub, this.syncGrants);
133
146
  if (scope && !grant.resolved.some((held) => covers(held, scope))) {
134
147
  throw new RunError(403, 'scope_missing', `missing scope ${scope}`, undefined, undefined, scope);
135
148
  }
136
- return { sub: token.sub, grantee: link.sub, client_id: claims.client_id, grant: link.grant,
149
+ return { sub: token.sub, grantee: link.sub, actor: link.sub, client_id: claims.client_id, grant: link.grant,
137
150
  rev: grant.rev, resolved: grant.resolved, resolved_scopes: grant.resolved_scopes,
138
151
  spend_cap: grant.spend_cap, dependencies: grant.dependencies ?? {}, exp: claims.exp };
139
152
  }
@@ -143,5 +156,11 @@ export class AppPrincipalResolver {
143
156
  * Otherwise 401 `grant_revoked`. `resolve()` and every later re-read during a
144
157
  * request (a `grant.get` long-poll waking) apply this one check. */
145
158
  export async function callerGrant(caller) {
146
- return await callerGrantOf(caller.grant, caller.sub, caller.grantee);
159
+ return await callerGrantOf(grantIdOf(caller), caller.sub, caller.grantee);
160
+ }
161
+ /** The grant id of a caller that must hold a grant row; an owner principal (CR-9 (b)) holds none, so the operation is 403. */
162
+ export function grantIdOf(caller) {
163
+ if (caller.grant === null)
164
+ throw new RunError(403, 'permission_error', 'this operation needs a grant; an owner token holds none');
165
+ return caller.grant;
147
166
  }
@@ -12,7 +12,7 @@
12
12
  // the image with every tag (a 404 is done); success clears all four image columns, so a later undelete finds an unbuilt environment and
13
13
  // the build pass rebuilds it; failure writes `image_error` and a retry time in `image_building_at`, as a failed build does. A build that
14
14
  // finishes after the environment was deleted records nothing and deletes the image it made.
15
- import { mkdtempSync } from 'node:fs';
15
+ import { mkdtempSync, readdirSync, rmSync } from 'node:fs';
16
16
  import { tmpdir } from 'node:os';
17
17
  import { join } from 'node:path';
18
18
  import { hasUnseenWakeMail } from '../../core/canvas/deliveries.js';
@@ -62,6 +62,12 @@ async function defaultBuild(input, config) {
62
62
  removeBuildDir(dir);
63
63
  }
64
64
  }
65
+ /** Deletes build folders a previous process left behind when it died mid-build; run once at startup. */
66
+ export function removeLeftoverBuildDirs(root = tmpdir()) {
67
+ for (const name of readdirSync(root))
68
+ if (name.startsWith('crtr-recipe-image-'))
69
+ rmSync(join(root, name), { recursive: true, force: true });
70
+ }
65
71
  export class RecipeImageReconciler {
66
72
  deps;
67
73
  constructor(deps = {}) {
@@ -148,6 +154,8 @@ export class RecipeImageReconciler {
148
154
  const person = await (await openDb()).prepare('SELECT person FROM profiles WHERE environment_id = ? ORDER BY created_at LIMIT 1').get(environmentId);
149
155
  if (person === undefined)
150
156
  throw new Error(`no profile runs in environment ${environmentId}, so there is no person to take a GitHub token for`);
157
+ // Recorded before the build so a process that dies mid-build leaves the reason; success clears it.
158
+ await (await openDb()).prepare('UPDATE environments SET image_error = ? WHERE object = ? AND image_building_at = ?').run(`the build of revision ${revision} started and its process exited before it finished`, environmentId, currentLease());
151
159
  const input = { environmentId, revision, recipe, person: person.person };
152
160
  built = await (this.deps.build ?? ((i) => defaultBuild(i, blaxelConfigFromEnv())))(input);
153
161
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.750",
3
+ "version": "0.3.752",
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",
@@ -59,10 +59,12 @@ export declare class JwksCache {
59
59
  forKid(kid: string | undefined): Promise<JSONWebKeySet>;
60
60
  }
61
61
  /** One link of a call token's actor chain. `grant` and `rev` appear only on an `app:` link. */
62
+ /** `owner` marks an app link with no grant whose app owns the namespace of the token's `sub`. */
62
63
  export interface CallLink {
63
64
  sub: string;
64
65
  grant?: string;
65
66
  rev?: number;
67
+ owner?: true;
66
68
  }
67
69
  /** The verified payload of a call token. Fields beyond `sub`/`aud`/`client_id` are present on some uses only. */
68
70
  export interface CallTokenClaims extends JWTPayload {
@@ -85,7 +87,7 @@ export interface CallTokenClaims extends JWTPayload {
85
87
  }
86
88
  /** A verified call token. The verifier authorizes nothing: the caller decides authority from `chain`. */
87
89
  export interface CallToken {
88
- /** `user:<id>`. */
90
+ /** Any principal `parsePrincipal` accepts. */
89
91
  sub: string;
90
92
  aud: string;
91
93
  /** The actor chain, index 0 = the presenter. */
@@ -97,7 +99,7 @@ export interface CallToken {
97
99
  /**
98
100
  * Verifies a call token of any use (peer, app access, outbound provider, run notice) and returns its actor chain,
99
101
  * presenter first. Checks in order: header `typ` `at+jwt`, `alg` ES256 or RS256, non-empty `kid`; signature; `iss`;
100
- * `aud` a string equal to `audience`; `exp` and `iat` numbers; `sub` = `user:<id>`; `client_id` non-empty; `scope`
102
+ * `aud` a string equal to `audience`; `exp` and `iat` numbers; `sub` a principal `parsePrincipal` accepts; `client_id` non-empty; `scope`
101
103
  * a string when present; then the chain. A token with no `act` is refused: the legacy machine and app shapes are not
102
104
  * accepted. Any `machine_id` must equal the first link, any top-level `grant` an app link's, and, on a token without
103
105
  * `scope`, any `grantee` and `rev` the app link's (or, with no app link, `grantee` = `sub` and no `rev`). It authorizes
@@ -245,9 +245,7 @@ function isDeveloperCredentialEnvelope(p) {
245
245
  function chainOf(payload) {
246
246
  const p = payload;
247
247
  const bad = () => { throw new Error('Invalid call token claims'); };
248
- const appLink = (sub, grant, rev) => {
249
- if (grant === undefined)
250
- return { sub };
248
+ const grantLink = (sub, grant, rev) => {
251
249
  if (typeof grant !== 'string' || grant === '')
252
250
  return bad();
253
251
  if (rev === undefined)
@@ -256,6 +254,7 @@ function chainOf(payload) {
256
254
  return bad();
257
255
  return { sub, grant, rev };
258
256
  };
257
+ const tokenSub = typeof p.sub === 'string' ? parsePrincipal(p.sub) : null;
259
258
  if (p.act === undefined)
260
259
  return bad();
261
260
  const chain = [];
@@ -273,19 +272,39 @@ function chainOf(payload) {
273
272
  chain.push({ sub: link.sub });
274
273
  break;
275
274
  }
276
- if (!(validatePrincipal(link.sub, 'runtime') || validatePrincipal(link.sub, 'app') || validatePrincipal(link.sub, 'user')))
275
+ if (typeof link.sub !== 'string')
277
276
  return bad();
278
- if (link.sub.startsWith('app:'))
279
- chain.push(appLink(link.sub, link.grant, link.rev));
280
- else if (link.grant !== undefined || link.rev !== undefined)
281
- return bad();
282
- else
277
+ if (link.sub.startsWith('runtime:')) {
278
+ if (!validatePrincipal(link.sub, 'runtime') || link.grant !== undefined || link.rev !== undefined)
279
+ return bad();
283
280
  chain.push({ sub: link.sub });
281
+ }
282
+ else {
283
+ const parsed = parsePrincipal(link.sub);
284
+ // A link names a namespace root, never a path principal.
285
+ if (parsed === null || parsed.path.length > 0)
286
+ return bad();
287
+ if (parsed.kind === 'app' && link.grant === undefined) {
288
+ if (link.rev !== undefined)
289
+ return bad();
290
+ // Marked `owner` when the app owns the namespace of the token's `sub`; otherwise the existing outbound shape (an app link without a grant).
291
+ chain.push(tokenSub !== null && tokenSub.namespace === link.sub ? { sub: link.sub, owner: true } : { sub: link.sub });
292
+ }
293
+ else if (parsed.kind === 'app')
294
+ chain.push(grantLink(link.sub, link.grant, link.rev));
295
+ else if (link.grant === undefined && link.rev === undefined)
296
+ chain.push({ sub: link.sub });
297
+ // A person's grant-bearing link is accepted only on an exchanged token: the person acts for a different subject.
298
+ else if (p.sub !== link.sub)
299
+ chain.push(grantLink(link.sub, link.grant, link.rev));
300
+ else
301
+ return bad();
302
+ }
284
303
  node = link.act;
285
304
  }
286
305
  if (p.machine_id !== undefined && p.machine_id !== chain[0].sub)
287
306
  return bad();
288
- if (p.grant !== undefined && !chain.some((l) => l.sub.startsWith('app:') && l.grant === p.grant))
307
+ if (p.grant !== undefined && !chain.some((l) => l.grant === p.grant))
289
308
  return bad();
290
309
  // A token's top-level claims (kept for providers pinned to an older `@north-light/plugin`, which read them instead of
291
310
  // `act`) must say what its chain says, or the old and new verifiers authorize different identities from one signed token.
@@ -311,7 +330,7 @@ function chainOf(payload) {
311
330
  /**
312
331
  * Verifies a call token of any use (peer, app access, outbound provider, run notice) and returns its actor chain,
313
332
  * presenter first. Checks in order: header `typ` `at+jwt`, `alg` ES256 or RS256, non-empty `kid`; signature; `iss`;
314
- * `aud` a string equal to `audience`; `exp` and `iat` numbers; `sub` = `user:<id>`; `client_id` non-empty; `scope`
333
+ * `aud` a string equal to `audience`; `exp` and `iat` numbers; `sub` a principal `parsePrincipal` accepts; `client_id` non-empty; `scope`
315
334
  * a string when present; then the chain. A token with no `act` is refused: the legacy machine and app shapes are not
316
335
  * accepted. Any `machine_id` must equal the first link, any top-level `grant` an app link's, and, on a token without
317
336
  * `scope`, any `grantee` and `rev` the app link's (or, with no app link, `grantee` = `sub` and no `rev`). It authorizes
@@ -329,7 +348,7 @@ export async function verifyCallToken(options) {
329
348
  issuer: options.issuer, audience: options.audience, algorithms: ['ES256', 'RS256'], typ: 'at+jwt', requiredClaims: ['exp'],
330
349
  });
331
350
  if (payload.aud !== options.audience || typeof payload.exp !== 'number' || typeof payload.iat !== 'number' ||
332
- !validatePrincipal(payload.sub, 'user') || !nonEmptyString(payload.client_id) ||
351
+ typeof payload.sub !== 'string' || parsePrincipal(payload.sub) === null || !nonEmptyString(payload.client_id) ||
333
352
  (payload.scope !== undefined && typeof payload.scope !== 'string')) {
334
353
  throw new Error('Invalid call token claims');
335
354
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.750",
3
+ "version": "0.3.752",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -153,6 +153,9 @@ export function createFetchHandler(plugins, options = {}) {
153
153
  : undefined;
154
154
  throw scopeMissing(command.scope, other);
155
155
  }
156
+ if (verified?.tools !== undefined && !verified.tools.includes(command.path.slice(1).join(' '))) {
157
+ throw scopeMissing(`${command.scope} (tool ${command.path.slice(1).join(' ')})`);
158
+ }
156
159
  if (verified !== undefined) {
157
160
  if (requestId === null || requestId === '') {
158
161
  return answer(errorResponse(400, { code: 'invalid_request', message: 'The request carries no Crtr-Request-Id header.' }));
@@ -211,7 +214,7 @@ export function createFetchHandler(plugins, options = {}) {
211
214
  const price = usage.usdEquivalent ?? (row?.usd_per_unit != null ? usage.units * row.usd_per_unit : 0);
212
215
  const receipt = {
213
216
  receipt_id: receiptId, provider: options.receipts.provider, tool,
214
- sub: caller.sub, grantee: caller.grantee, payer: caller.payer,
217
+ sub: caller.sub, grantee: caller.grantee, payer: caller.payer, actor: caller.actor,
215
218
  units: usage.units, unit: usage.unit, usd_equivalent: price,
216
219
  request_id: caller.requestId,
217
220
  ...(caller.runId !== undefined ? { run_id: caller.runId } : {}),
@@ -1,8 +1,7 @@
1
- import { JwksCache, verifyCallToken } from '@north-light/identity';
1
+ import { JwksCache, parsePrincipal, verifyCallToken } from '@north-light/identity';
2
2
  import { kitLeafError } from './errors.js';
3
3
  const PROVIDER_ID = /^[A-Za-z0-9_-]{1,64}$/;
4
- const PRINCIPAL = /^(app|user):[A-Za-z0-9_-]{1,64}$/;
5
- const isAppOrUser = (value) => typeof value === 'string' && PRINCIPAL.test(value);
4
+ const isPrincipal = (value) => typeof value === 'string' && parsePrincipal(value) !== null;
6
5
  const isNonEmpty = (value) => typeof value === 'string' && value !== '';
7
6
  /** Validates `auth.providerId` and returns it bare, or undefined when none is configured. */
8
7
  export function normalizeProviderId(auth) {
@@ -42,27 +41,56 @@ export function createCallerVerifier(auth) {
42
41
  const { claims, chain, scope } = verified;
43
42
  const { grantee, initiating_app: initiatingApp, jti, act } = claims;
44
43
  const actor = act;
45
- if (scope === undefined || !isAppOrUser(grantee) || !isAppOrUser(initiatingApp) || !isNonEmpty(jti) || chain.length === 0 ||
44
+ if (scope === undefined || !isPrincipal(grantee) || !isPrincipal(initiatingApp) || !isNonEmpty(jti) || chain.length === 0 ||
46
45
  typeof actor !== 'object' || actor === null || Array.isArray(actor) || !isNonEmpty(actor.sub)) {
47
46
  throw unauthorized('The bearer token is not a valid outbound token for this provider.');
48
47
  }
49
- // A token from a directory that predates payers has no claim; its payer is the user.
50
- const payer = claims.payer;
51
- if (payer !== undefined && !/^(user|app):[A-Za-z0-9_-]{1,64}$/.test(String(payer))) {
48
+ // An absent payer claim means the namespace owner of the grantee, never `sub`.
49
+ const payerClaim = claims.payer;
50
+ if (payerClaim !== undefined && !isPrincipal(payerClaim)) {
52
51
  throw unauthorized('The bearer token is not a valid outbound token for this provider.');
53
52
  }
53
+ const payer = payerClaim ?? parsePrincipal(grantee).namespace;
54
+ const accounts = parseAccounts(claims.accounts);
55
+ const tools = parseTools(claims.tools);
56
+ let innermost = act;
57
+ while (innermost.act !== undefined)
58
+ innermost = innermost.act;
54
59
  return Object.freeze({
55
60
  sub: verified.sub,
56
61
  grantee,
57
- payer: payer === undefined ? verified.sub : String(payer),
62
+ payer,
58
63
  clientId: claims.client_id,
59
64
  scope: Object.freeze(scope.split(' ').filter((entry) => entry.length > 0)),
60
65
  initiatingApp,
61
66
  act: act,
62
67
  jti,
68
+ actor: innermost.sub,
69
+ ...(accounts !== undefined ? { accounts } : {}),
70
+ ...(tools !== undefined ? { tools } : {}),
63
71
  });
64
72
  };
65
73
  }
74
+ function parseAccounts(value) {
75
+ if (value === undefined)
76
+ return undefined;
77
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
78
+ throw unauthorized('The bearer token is not a valid outbound token for this provider.');
79
+ const out = {};
80
+ for (const [service, labels] of Object.entries(value)) {
81
+ if (!Array.isArray(labels) || !labels.every(isNonEmpty))
82
+ throw unauthorized('The bearer token is not a valid outbound token for this provider.');
83
+ out[service] = Object.freeze([...labels]);
84
+ }
85
+ return Object.freeze(out);
86
+ }
87
+ function parseTools(value) {
88
+ if (value === undefined)
89
+ return undefined;
90
+ if (!Array.isArray(value) || !value.every(isNonEmpty))
91
+ throw unauthorized('The bearer token is not a valid outbound token for this provider.');
92
+ return Object.freeze([...value]);
93
+ }
66
94
  /** The 403 for a leaf whose `<provider>:<group>` the verified token does not carry. */
67
95
  export function scopeMissing(scope, heldByOtherProvider) {
68
96
  return kitLeafError({
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.750",
3
+ "version": "0.3.752",
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.750",
31
- "@north-light/identity": "0.3.750"
30
+ "@north-light/api": "0.3.752",
31
+ "@north-light/identity": "0.3.752"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {