@north-light/cli 0.3.747 → 0.3.749
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/objects.d.ts +6 -1
- package/dist/api/dto/plugins.d.ts +2 -0
- package/dist/clients/attach/chrome/canvas-panels.d.ts +2 -0
- package/dist/clients/attach/chrome/canvas-panels.js +1 -1
- package/dist/clients/attach/chrome/roster.d.ts +2 -0
- package/dist/clients/attach/chrome/roster.js +5 -5
- package/dist/clients/attach/chrome/run-facts.d.ts +12 -0
- package/dist/clients/attach/chrome/run-facts.js +1 -0
- package/dist/clients/attach/chrome/widgets.d.ts +3 -1
- package/dist/clients/attach/chrome/widgets.js +1 -1
- package/dist/clients/attach/viewer.js +487 -487
- package/dist/commands/canvas/list.js +2 -2
- package/dist/commands/canvas/read.js +4 -4
- package/dist/commands/canvas/search.js +1 -1
- package/dist/core/canvas/canvas.js +16 -16
- package/dist/core/canvas/schema-pg/035-environment-payer.sql +2 -0
- package/dist/core/canvas/schema-pg/036-ledger-holder-app-path.sql +13 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/command-manifests/registry.d.ts +2 -1
- package/dist/core/command-plugins/compose.js +1 -1
- package/dist/core/command.d.ts +11 -0
- package/dist/core/command.js +9 -9
- package/dist/core/environments.d.ts +2 -1
- package/dist/core/environments.js +1 -1
- package/dist/core/grants/mirror.d.ts +4 -0
- package/dist/core/grants/mirror.js +8 -6
- package/dist/core/grants/on-sync.js +1 -1
- package/dist/core/graph/reader.js +1 -1
- package/dist/core/ledger/environment-payer.d.ts +2 -0
- package/dist/core/ledger/environment-payer.js +1 -0
- package/dist/core/ledger/index.d.ts +1 -0
- package/dist/core/ledger/index.js +1 -1
- package/dist/core/ledger/payer.d.ts +4 -1
- package/dist/core/ledger/payer.js +1 -1
- package/dist/core/llm/run.d.ts +1 -0
- package/dist/core/llm/run.js +2 -2
- package/dist/core/peer/envelope.js +1 -1
- package/dist/core/peer/stubs.js +1 -1
- package/dist/core/permissions/ceiling.js +10 -10
- package/dist/core/permissions/evaluator.js +2 -2
- package/dist/core/providers/call.js +1 -1
- package/dist/core/runs/node-sub.d.ts +2 -0
- package/dist/core/runs/node-sub.js +1 -0
- package/dist/core/runtime/host.js +3 -3
- package/dist/core/runtime/recap.js +6 -6
- package/dist/core/runtime/spawn.js +2 -2
- package/dist/core/runtime/start-check.d.ts +1 -0
- package/dist/core/runtime/start-check.js +1 -1
- package/dist/core/runtime/warm-pool.js +1 -1
- package/dist/core/spaces/process.js +1 -1
- package/dist/daemon/api/handlers/bash-jobs.js +2 -2
- package/dist/daemon/api/handlers/hook-exec.js +1 -1
- package/dist/daemon/api/handlers/llm.js +3 -3
- package/dist/daemon/api/handlers/providers.d.ts +2 -0
- package/dist/daemon/api/handlers/providers.js +1 -1
- package/dist/daemon/peer/authority.d.ts +1 -1
- package/dist/daemon/peer/authority.js +1 -1
- package/package.json +4 -4
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/clients/attach/chrome/canvas-panels.js +19 -1
- package/packages/crouter-api/dist/clients/attach/chrome/roster.js +1 -0
- package/packages/crouter-api/dist/clients/attach/chrome/run-facts.js +76 -0
- package/packages/crouter-api/dist/clients/attach/chrome/widgets.js +14 -5
- package/packages/crouter-api/dist/clients/attach/viewer.js +7 -1
- package/packages/crouter-api/dist/commands/canvas/list.js +3 -1
- package/packages/crouter-api/dist/commands/canvas/read.js +4 -2
- package/packages/crouter-api/dist/commands/canvas/search.js +3 -1
- package/packages/crouter-api/dist/core/canvas/canvas.js +2 -1
- package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
- package/packages/crouter-api/dist/core/command-plugins/compose.js +5 -3
- package/packages/crouter-api/dist/core/command.js +34 -1
- package/packages/crouter-api/dist/core/environments.js +2 -2
- package/packages/crouter-api/dist/core/grants/mirror.js +16 -1
- package/packages/crouter-api/dist/core/grants/on-sync.js +2 -2
- package/packages/crouter-api/dist/core/graph/reader.js +1 -1
- package/packages/crouter-api/dist/core/ledger/environment-payer.js +15 -0
- package/packages/crouter-api/dist/core/ledger/index.js +1 -0
- package/packages/crouter-api/dist/core/ledger/payer.js +4 -0
- package/packages/crouter-api/dist/core/llm/run.js +2 -1
- package/packages/crouter-api/dist/core/peer/envelope.js +2 -1
- package/packages/crouter-api/dist/core/peer/stubs.js +5 -1
- package/packages/crouter-api/dist/core/permissions/ceiling.js +4 -0
- package/packages/crouter-api/dist/core/permissions/evaluator.js +16 -5
- package/packages/crouter-api/dist/core/providers/call.js +2 -2
- package/packages/crouter-api/dist/core/runs/node-sub.js +10 -0
- package/packages/crouter-api/dist/core/runtime/host.js +2 -2
- package/packages/crouter-api/dist/core/runtime/spawn.js +1 -1
- package/packages/crouter-api/dist/core/runtime/start-check.js +2 -2
- package/packages/crouter-api/dist/core/runtime/warm-pool.js +1 -1
- package/packages/crouter-api/dist/core/spaces/process.js +5 -4
- package/packages/crouter-api/dist/daemon/api/handlers/bash-jobs.js +1 -1
- package/packages/crouter-api/dist/daemon/api/handlers/providers.js +5 -1
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/dist/index.d.ts +8 -0
- package/packages/crouter-identity/dist/index.js +18 -0
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/scripts/lib/install-source.mjs +5 -1
|
@@ -56,6 +56,7 @@ function providerLeafAdapter(provider, tool, leaf, machineTransport = false) {
|
|
|
56
56
|
return {
|
|
57
57
|
outputKind: 'object',
|
|
58
58
|
...(machineTransport ? { machineSelector: true } : {}),
|
|
59
|
+
actingAs: true,
|
|
59
60
|
run: async (input, context) => {
|
|
60
61
|
const argumentsForDaemon = { ...input };
|
|
61
62
|
for (const param of leaf.params) {
|
|
@@ -79,7 +80,7 @@ function providerLeafAdapter(provider, tool, leaf, machineTransport = false) {
|
|
|
79
80
|
}
|
|
80
81
|
try {
|
|
81
82
|
const result = await cliClient({ timeoutMs: 0 }).request('POST', '/v1/provider/call', {
|
|
82
|
-
provider, tool, arguments: argumentsForDaemon, ...(context?.machine === undefined ? {} : { machine: context.machine }),
|
|
83
|
+
provider, tool, arguments: argumentsForDaemon, ...(context?.machine === undefined ? {} : { machine: context.machine }), ...(context?.as === undefined ? {} : { as: context.as }),
|
|
83
84
|
}, { timeout: 0 });
|
|
84
85
|
if (filesCrossByUpload()) {
|
|
85
86
|
for (const field of leaf.output ?? []) {
|
|
@@ -201,6 +202,7 @@ function adaptLeaf(contribution, commandPathFor) {
|
|
|
201
202
|
const httpLeaf = leaf;
|
|
202
203
|
return {
|
|
203
204
|
outputKind: httpLeaf.rest.streaming === true ? 'jsonl' : 'object',
|
|
205
|
+
actingAs: true,
|
|
204
206
|
run: (input, context) => invokeHttpLeaf({
|
|
205
207
|
registration: { name: contribution.plugin.name, endpoint: transport.endpoint, ...(transport.authEnv !== undefined ? { authEnv: transport.authEnv } : {}) },
|
|
206
208
|
...(contribution.manifest?.baseUrl !== undefined ? { baseUrl: contribution.manifest.baseUrl } : {}),
|
|
@@ -209,7 +211,7 @@ function adaptLeaf(contribution, commandPathFor) {
|
|
|
209
211
|
}, input, context, {
|
|
210
212
|
// crtrd names the caller and decides, from the final URL, whether to sign. Only digests leave this process.
|
|
211
213
|
callHeaders: (plan) => cliClient().plugins.callHeaders(contribution.plugin.name, {
|
|
212
|
-
method: plan.method, url: plan.url.href, body_sha256: sha256Hex(plan.body), ...signedHeaderDigest(plan.headers),
|
|
214
|
+
method: plan.method, url: plan.url.href, body_sha256: sha256Hex(plan.body), ...signedHeaderDigest(plan.headers), ...(context?.as === undefined ? {} : { as: context.as }),
|
|
213
215
|
}).then((answer) => answer.headers, (error) => { throw error instanceof ApiError ? apiErrorToCliError(error) : error; }),
|
|
214
216
|
}),
|
|
215
217
|
};
|
|
@@ -257,5 +259,5 @@ function buildBranch(contribution, node, path, toolPrefixLength = 1, allowedTool
|
|
|
257
259
|
}
|
|
258
260
|
function buildLeaf(contribution, node, path) {
|
|
259
261
|
const adapted = contribution.adaptLeaf(node, path);
|
|
260
|
-
return defineLeaf({ name: node.name, description: node.description, whenToUse: node.whenToUse, ...(node.tier !== undefined ? { tier: node.tier } : {}), ...(contribution.plugin !== undefined ? { plugin: contribution.plugin } : {}), ...(adapted.machineSelector === true ? { machineSelector: true } : {}), help: { name: path.join(' '), summary: node.summary, ...(adapted.machineSelector === true ? { guide: MACHINE_SELECTOR_GUIDE } : {}), params: node.params, output: node.output, outputKind: adapted.outputKind, effects: [...node.effects] }, run: adapted.run });
|
|
262
|
+
return defineLeaf({ name: node.name, description: node.description, whenToUse: node.whenToUse, ...(node.tier !== undefined ? { tier: node.tier } : {}), ...(contribution.plugin !== undefined ? { plugin: contribution.plugin } : {}), ...(adapted.machineSelector === true ? { machineSelector: true } : {}), ...(adapted.actingAs === true ? { actingAs: true } : {}), help: { name: path.join(' '), summary: node.summary, ...(adapted.machineSelector === true ? { guide: MACHINE_SELECTOR_GUIDE } : {}), params: node.params, output: node.output, outputKind: adapted.outputKind, effects: [...node.effects] }, run: adapted.run });
|
|
261
263
|
}
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
// complexity than a plain array walk for this interface contract.
|
|
5
5
|
// A plain array walk + a small flag parser is ~120 lines and has no surprising
|
|
6
6
|
// edge cases.
|
|
7
|
+
import { parsePrincipal } from '@north-light/identity';
|
|
7
8
|
import { renderRoot, renderBranch, renderLeafArgv, withAsyncHelpState, collapseWideChildren, rootPromotedChildren } from './help.js';
|
|
8
9
|
import { beginPreview, publishPreviewResult, readStdinRaw, peekStdinRaw, emit, handle, setJsonOutput, isJsonOutput } from './io.js';
|
|
9
10
|
import { renderResult } from './render.js';
|
|
@@ -42,6 +43,7 @@ export function defineLeaf(opts) {
|
|
|
42
43
|
hookEligible: opts.hookEligible,
|
|
43
44
|
plugin: opts.plugin,
|
|
44
45
|
machineSelector: opts.machineSelector,
|
|
46
|
+
actingAs: opts.actingAs,
|
|
45
47
|
run: opts.run,
|
|
46
48
|
render: opts.render,
|
|
47
49
|
preview: opts.preview,
|
|
@@ -720,6 +722,31 @@ export function takeMachineSelector(tokens) {
|
|
|
720
722
|
}
|
|
721
723
|
return machine === undefined ? { rest } : { rest, machine };
|
|
722
724
|
}
|
|
725
|
+
/** Take the `--as <principal>` / `--as=<user:id>` option out of an opted-in leaf's argv. Nothing after a bare `--` is a flag. */
|
|
726
|
+
export function takeActingAs(tokens) {
|
|
727
|
+
const rest = [];
|
|
728
|
+
let as;
|
|
729
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
730
|
+
const token = tokens[i];
|
|
731
|
+
if (token === '--') {
|
|
732
|
+
rest.push(...tokens.slice(i));
|
|
733
|
+
break;
|
|
734
|
+
}
|
|
735
|
+
const inline = token.startsWith('--as=') ? token.slice('--as='.length) : undefined;
|
|
736
|
+
if (token !== '--as' && inline === undefined) {
|
|
737
|
+
rest.push(token);
|
|
738
|
+
continue;
|
|
739
|
+
}
|
|
740
|
+
const value = inline ?? tokens[i + 1];
|
|
741
|
+
if (value === undefined || parsePrincipal(value) === null) {
|
|
742
|
+
throw parseArgvError('missing_parameter', '--as requires a principal like user:<id> or app:<id>/<path>', '--as', 'as', 'Name the principal this call acts for, for example `--as user:alice`.');
|
|
743
|
+
}
|
|
744
|
+
if (inline === undefined)
|
|
745
|
+
i++;
|
|
746
|
+
as = value;
|
|
747
|
+
}
|
|
748
|
+
return as === undefined ? { rest } : { rest, as };
|
|
749
|
+
}
|
|
723
750
|
export const GLOBAL_TOKENS = new Set(['--json', '--no-autostart']);
|
|
724
751
|
export async function runCli(root, argv) {
|
|
725
752
|
// argv is process.argv — strip node binary + script path. `--json` is a
|
|
@@ -826,6 +853,12 @@ export async function runCli(root, argv) {
|
|
|
826
853
|
leafTokens = selected.rest;
|
|
827
854
|
machine = selected.machine;
|
|
828
855
|
}
|
|
856
|
+
let acting;
|
|
857
|
+
if (leaf.actingAs === true && !params.some((param) => param.kind === 'flag' && param.name === 'as')) {
|
|
858
|
+
const taken = takeActingAs(leafTokens);
|
|
859
|
+
leafTokens = taken.rest;
|
|
860
|
+
acting = taken.as;
|
|
861
|
+
}
|
|
829
862
|
const input = await parseArgv(params, leafTokens, {
|
|
830
863
|
leafPath: path,
|
|
831
864
|
onProvidedParams: (provided) => {
|
|
@@ -835,7 +868,7 @@ export async function runCli(root, argv) {
|
|
|
835
868
|
contextFilePaths = paths;
|
|
836
869
|
},
|
|
837
870
|
});
|
|
838
|
-
const context = { providedParams, contextFilePaths, ...(machine === undefined ? {} : { machine }) };
|
|
871
|
+
const context = { providedParams, contextFilePaths, ...(machine === undefined ? {} : { machine }), ...(acting === undefined ? {} : { as: acting }) };
|
|
839
872
|
const result = await operationIdContext.fresh(() => leaf.run(input, context));
|
|
840
873
|
publishPreviewResult(result === undefined || result === null ? result : leaf.preview?.(result) ?? result);
|
|
841
874
|
if (result !== undefined && result !== null) {
|
|
@@ -5,7 +5,7 @@ import { writeActsFor } from './permissions/facts.js';
|
|
|
5
5
|
import { writeEnvironmentRecipe } from './environment-recipe.js';
|
|
6
6
|
import { setCloudProfileWriter } from './profiles/manifest.js';
|
|
7
7
|
/** A cloud profile's own `blaxel` environment (D105): an `environment` object owned by the profile's object, acting for `person`, and
|
|
8
|
-
* its `environments` row with the `memory_mb` (default 2048), no recipe (so the Blaxel base image) and no machine id. Runs in the
|
|
8
|
+
* its `environments` row with the `memory_mb` (default 2048), no recipe (so the Blaxel base image) and no machine id. `payer` (null by default: the run's `sub` pays) names who pays; an app environment passes `person` and `grantee` as `app:<id>` and `payer` the same. Runs in the
|
|
9
9
|
* caller's write, before the profile row exists, so the profile and its environment commit together. The profile object is made
|
|
10
10
|
* here under `grantee`'s app, with the profile id as its handle: a cloud role serves many people and a profile name is not unique
|
|
11
11
|
* across them, while the handle is unique per object type. Returns the environment's object id. */
|
|
@@ -14,7 +14,7 @@ export async function createProfileBlaxelEnvironment(db, spec) {
|
|
|
14
14
|
const profile = await ensureOwner(db, 'profile', 'profile', spec.profileId, spec.profileId, app);
|
|
15
15
|
const object = await createObject(db, { type: 'environment', kind: 'blaxel', owner: profile.id, privacy: 'private', name: spec.profileId, preview: 'blaxel' });
|
|
16
16
|
await writeActsFor(db, object.id, spec.person);
|
|
17
|
-
await db.prepare(`INSERT INTO environments (object, kind, machine_id, memory_mb, allow_pull_request_write, last_seen_at) VALUES (?, 'blaxel', NULL, ?, true, ?)`).run(object.id, spec.memoryMb ?? 2048, new Date().toISOString());
|
|
17
|
+
await db.prepare(`INSERT INTO environments (object, kind, machine_id, memory_mb, allow_pull_request_write, payer, last_seen_at) VALUES (?, 'blaxel', NULL, ?, true, ?, ?)`).run(object.id, spec.memoryMb ?? 2048, spec.payer ?? null, new Date().toISOString());
|
|
18
18
|
if (spec.recipe !== undefined)
|
|
19
19
|
await writeEnvironmentRecipe(db, object.id, spec.recipe);
|
|
20
20
|
return object.id;
|
|
@@ -3,7 +3,7 @@ import { parseScope } from '@north-light/identity';
|
|
|
3
3
|
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
|
-
import { GROUP_TYPE } from '../permissions/builtin.js';
|
|
6
|
+
import { GROUP_TYPE, OBJECT_TYPE } from '../permissions/builtin.js';
|
|
7
7
|
import { shadowCheck } from './shadow.js';
|
|
8
8
|
const SETUP_STATES = ['not_started', 'pending', 'ready', 'failed', 'unavailable'];
|
|
9
9
|
const STRENGTHS = ['ultra', 'strong', 'medium', 'light'];
|
|
@@ -461,11 +461,26 @@ export async function replaceGrants(grants, syncedAt, source, teams = []) {
|
|
|
461
461
|
changed += Number((await upsert.run(grant.id, grant.runtime, grant.sub, grant.grantee, grant.rev, JSON.stringify(grant.scopes), JSON.stringify(grant.resolved_scopes), grant.spend_cap, grant.expires_at, grant.status, grant.revoked_at, grant.approved_at, grant.payer, JSON.stringify(dependenciesOf(grant.dependencies)), grant.run_notice_url ?? null, grant.inference_endpoint ? JSON.stringify(grant.inference_endpoint) : null, grant.synced_at, grant.rev)).changes);
|
|
462
462
|
}
|
|
463
463
|
await replaceWrittenBy(db, 'directory', GROUP_TYPE, 'member', teams.flatMap(({ team, members }) => members.map((member) => ({ resourceId: team, subject: userSubject(member) }))));
|
|
464
|
+
await reconcileAppAdminFacts(db);
|
|
464
465
|
await db.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_source', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(source);
|
|
465
466
|
if (changed > 0)
|
|
466
467
|
await db.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_generation', '1') ON CONFLICT(key) DO UPDATE SET value = CAST(CAST(runtime_state.value AS INTEGER) + 1 AS TEXT)").run();
|
|
467
468
|
});
|
|
468
469
|
}
|
|
470
|
+
/** The relations an app's admins hold on the app object: they reach its profiles, environments and nodes through `parent->` (app-runtimes D8). */
|
|
471
|
+
const ADMIN_RELATIONS = ['editor', 'messenger', 'user_of'];
|
|
472
|
+
export const APP_ADMIN_WRITER = 'app-admin';
|
|
473
|
+
/** Make `editor`, `messenger` and `user_of` on each app object exactly its app's `admin` tuples (a `user` or a `crtr/group#member` team),
|
|
474
|
+
* so a removed admin loses them. Runs in the caller's transaction; the admin tuples are the directory's, the facts it writes are `written_by = 'app-admin'`. */
|
|
475
|
+
export async function reconcileAppAdminFacts(db) {
|
|
476
|
+
const admins = await db.prepare(`SELECT o.id AS object, r.subject_type, r.subject_id FROM objects o
|
|
477
|
+
JOIN relations r ON r.resource_type = 'app' AND r.resource_id = o.name AND r.relation = 'admin' AND r.subject_type IN ('user', ?)
|
|
478
|
+
WHERE o.type = 'app' AND o.deleted_at IS NULL`).all(GROUP_TYPE);
|
|
479
|
+
const facts = admins.map((a) => ({ resourceId: a.object,
|
|
480
|
+
subject: a.subject_type === GROUP_TYPE ? { type: GROUP_TYPE, id: a.subject_id, relation: 'member' } : { type: 'user', id: a.subject_id, relation: '' } }));
|
|
481
|
+
for (const relation of ADMIN_RELATIONS)
|
|
482
|
+
await replaceWrittenBy(db, APP_ADMIN_WRITER, OBJECT_TYPE, relation, facts);
|
|
483
|
+
}
|
|
469
484
|
/** Bumped by every `replaceGrants`. A launch compiled against one generation
|
|
470
485
|
* and started under another may hold mounts the new mirror no longer grants. */
|
|
471
486
|
export async function grantsGeneration() {
|
|
@@ -14,7 +14,7 @@ import { checkCronFire } from '../../daemon/cron/authority.js';
|
|
|
14
14
|
import { cronExecutionFor } from '../../daemon/cron/live-runs.js';
|
|
15
15
|
import { cronExecutionsReady } from '../../daemon/cron/run-socket.js';
|
|
16
16
|
import { flatMapAsync } from '../async-array.js';
|
|
17
|
-
import {
|
|
17
|
+
import { launchSub } from '../runs/node-sub.js';
|
|
18
18
|
async function appUserOwners() {
|
|
19
19
|
return new Map((await (await openDb()).prepare('SELECT uid, app, status FROM app_users').all())
|
|
20
20
|
.map((row) => [row.uid, { app: row.app, status: row.status }]));
|
|
@@ -51,7 +51,7 @@ export async function exceeds(sandbox, owners) {
|
|
|
51
51
|
permissions = await permissionsForRun(cronExecution.grantee, cronExecution.sub, cronExecution.grantId, cronScopes);
|
|
52
52
|
}
|
|
53
53
|
else if (node && node.grantee === owner.app) {
|
|
54
|
-
permissions = await permissionsForRun(owner.app, node.sub
|
|
54
|
+
permissions = await permissionsForRun(owner.app, launchSub(node.sub, node.node_id), node.grant_id ?? null, node.scopes ?? null);
|
|
55
55
|
}
|
|
56
56
|
else {
|
|
57
57
|
// A process without a node (an unanchored cron, a delivery) runs on the app's whole grant.
|
|
@@ -128,7 +128,7 @@ export async function readerFor(db, principal, reposFn) {
|
|
|
128
128
|
if (!grant)
|
|
129
129
|
throw new ApiError(403, 'app_not_granted', `${principal.actor.app} holds no active grant for ${principal.sub} on this machine`);
|
|
130
130
|
const stored = principal.actor.node_scopes;
|
|
131
|
-
return { class: 'app', app: await appObject(db, principal.actor.app), place: principal.actor.place, launched: stored,
|
|
131
|
+
return { class: 'app', app: await appObject(db, principal.actor.app), sub: principal.sub, place: principal.actor.place, launched: stored,
|
|
132
132
|
scopes: stored === null ? grant.resolved : stored.filter((scope) => coveredByAny(grant.resolved, scope)) };
|
|
133
133
|
}
|
|
134
134
|
if (principal.class === 'cron') {
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// The payer stored on the environment a profile or node runs in (`environments.payer`); null when the profile has no environment
|
|
2
|
+
// or the environment names none, in which case the run's `sub` pays as before.
|
|
3
|
+
import { openDb } from '../canvas/db.js';
|
|
4
|
+
export async function environmentPayerOfProfile(profileId) {
|
|
5
|
+
if (!profileId)
|
|
6
|
+
return null;
|
|
7
|
+
const row = await (await openDb()).prepare('SELECT e.payer AS payer FROM profiles p JOIN environments e ON e.object = p.environment_id WHERE p.id = ?').get(profileId);
|
|
8
|
+
return row?.payer ?? null;
|
|
9
|
+
}
|
|
10
|
+
export async function environmentPayerOfNode(nodeId) {
|
|
11
|
+
if (!nodeId)
|
|
12
|
+
return null;
|
|
13
|
+
const row = await (await openDb()).prepare('SELECT e.payer AS payer FROM nodes n JOIN profiles p ON p.id = n.profile_id JOIN environments e ON e.object = p.environment_id WHERE n.node_id = ?').get(nodeId);
|
|
14
|
+
return row?.payer ?? null;
|
|
15
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// The ledger core (design-ledger, cycle 4). Every site calls these.
|
|
2
2
|
export * from './types.js';
|
|
3
3
|
export * from './months.js';
|
|
4
|
+
export { environmentPayerOfNode, environmentPayerOfProfile } from './environment-payer.js';
|
|
4
5
|
export { payerOf } from './payer.js';
|
|
5
6
|
export { writeCharge, receiptChargeId, chargeOf } from './charges.js';
|
|
6
7
|
export { check, findRefusal, refusalError, refusedMark, userActionOf } from './check.js';
|
|
@@ -2,6 +2,10 @@
|
|
|
2
2
|
// never a request header, so a caller cannot name its payer.
|
|
3
3
|
/** Who pays, and with what funding. A device call is not priced and never asks. */
|
|
4
4
|
export function payerOf(call) {
|
|
5
|
+
const paid = fundedBy(call);
|
|
6
|
+
return call.environmentPayer ? { payer: call.environmentPayer, funding: paid.funding } : paid;
|
|
7
|
+
}
|
|
8
|
+
function fundedBy(call) {
|
|
5
9
|
switch (call.call) {
|
|
6
10
|
case 'model':
|
|
7
11
|
return call.route === 'endpoint' ? { payer: call.grantee, funding: 'endpoint' } : { payer: call.sub, funding: call.route };
|
|
@@ -324,7 +324,8 @@ export async function runLlm(input, signal, onChunk, target, spend, caller, caus
|
|
|
324
324
|
const served = `${model.provider}/${model.id}`;
|
|
325
325
|
const requested = input.model ?? served;
|
|
326
326
|
// The ledger check, once the account, key or endpoint is chosen and before this candidate's vendor request or token mint.
|
|
327
|
-
const
|
|
327
|
+
const environmentPayer = spend?.environmentPayer;
|
|
328
|
+
const paid = hosted ? (sub === null ? null : { payer: environmentPayer ?? sub, funding: 'endpoint' }) : app ? payerOf({ call: 'model', route: 'endpoint', grantee: app.grantee, environmentPayer }) : sub === null ? null : payerOf({ call: 'model', route: account ? 'subscription' : 'key', sub, environmentPayer });
|
|
328
329
|
if (spend !== undefined && paid !== null) {
|
|
329
330
|
const refusal = await findRefusal({ scope: 'call', payer: paid.payer, funding: paid.funding, sub, grantee: spend.grantee, provider });
|
|
330
331
|
if (refusal !== null) {
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
// Wire form: `Crtr-Envelope: <base64url JSON>` of
|
|
9
9
|
// {sub:"user:<id>", act:{sub:"runtime:<via>", act?:{sub:"app:<x>", node, node_scopes, place}}}
|
|
10
10
|
// A missing inner `act` means the person.
|
|
11
|
+
import { parsePrincipal } from '@north-light/identity';
|
|
11
12
|
import { joinedOwner } from '../directory/join.js';
|
|
12
13
|
import { nodePlace } from '../permissions/ceiling.js';
|
|
13
14
|
import { openDb } from '../canvas/db.js';
|
|
@@ -75,7 +76,7 @@ export function decodeEnvelope(header) {
|
|
|
75
76
|
const inner = act['act'];
|
|
76
77
|
if (inner === undefined)
|
|
77
78
|
return { sub: raw['sub'], act: { sub: act['sub'] } };
|
|
78
|
-
if (!isRecord(inner) || !isString(inner['sub']) ||
|
|
79
|
+
if (!isRecord(inner) || !isString(inner['sub']) || parsePrincipal(inner['sub'])?.kind !== 'app')
|
|
79
80
|
throw new EnvelopeError('the envelope names no calling app');
|
|
80
81
|
const { node, node_scopes: scopes, place } = inner;
|
|
81
82
|
if (node !== null && !isString(node))
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
// A stub that watches carries the envelope identity it acts under (app, node, node_scopes, place).
|
|
10
10
|
// That identity names who the remote watcher is; it is never authority. What the stub may read is
|
|
11
11
|
// recomputed from the current mirrored grant every time an event is published (`readerForObject`).
|
|
12
|
+
import { parsePrincipal } from '@north-light/identity';
|
|
12
13
|
import { createObject, getById, ownerForGrantee, ownerLockKey } from '../graph/objects.js';
|
|
13
14
|
import { readLegacyPrivacy } from '../graph/types.js';
|
|
14
15
|
import { upsertKind } from '../graph/custom.js';
|
|
@@ -83,7 +84,10 @@ export async function lockInOrder(db, keys) {
|
|
|
83
84
|
}
|
|
84
85
|
/** The lock key to create the owner `grantee` names, or none when it exists (`ensureOwner` locks only a first sighting). */
|
|
85
86
|
async function missingOwnerKey(db, grantee) {
|
|
86
|
-
const
|
|
87
|
+
const principal = parsePrincipal(grantee);
|
|
88
|
+
if (principal === null)
|
|
89
|
+
throw new Error(`grantee ${JSON.stringify(grantee)} is not a principal`);
|
|
90
|
+
const [scheme, externalId] = principal.kind === 'app' ? ['app', principal.namespace] : ['user', grantee];
|
|
87
91
|
return await db.prepare('SELECT 1 FROM identities WHERE scheme = ? AND external_id = ?').get(scheme, externalId) === undefined ? [ownerLockKey(scheme, externalId)] : [];
|
|
88
92
|
}
|
|
89
93
|
/** Every advisory lock `ensureStub` takes for this object: the stub, the custom kind its reference declares, and each owner it may create.
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// The ceiling: what one of a person's agents may reach, computed in TypeScript from the reader's grant scopes and node row before the query,
|
|
2
2
|
// then applied inside the same query as the schema check (`ceilingFrag`). A person reader has no ceiling. Privacy (`private` per root), run
|
|
3
3
|
// confinement (`place`) and the launched own-memory narrowing are all rules here; none of them is schema text.
|
|
4
|
+
import { parsePrincipal } from '@north-light/identity';
|
|
4
5
|
import { covers } from '@north-light/identity';
|
|
5
6
|
import { isCloudRole } from '../canvas/person-state.js';
|
|
6
7
|
import { eligiblePackageApps } from '../packages/eligibility.js';
|
|
@@ -147,6 +148,9 @@ export async function resolveCeiling(db, reader, user, access, options = {}) {
|
|
|
147
148
|
const objVerb = access === 'write' ? 'write' : options.verb ?? 'read';
|
|
148
149
|
const watching = reader.class === 'object' && reader.object.type.includes('.');
|
|
149
150
|
const appRoot = async (ext, match) => {
|
|
151
|
+
const principal = parsePrincipal(ext);
|
|
152
|
+
if (principal?.kind !== 'app' || principal.path.length > 0)
|
|
153
|
+
return;
|
|
150
154
|
const id = await objectOf(db, 'app', ext);
|
|
151
155
|
if (id === null || id === reader.app.id)
|
|
152
156
|
return;
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
// check / permits: the reader's user (schema) AND the reader's ceiling, in one SQL condition over the candidate object.
|
|
2
|
+
import { parsePrincipal } from '@north-light/identity';
|
|
1
3
|
import { isCloudRole, personIdAsync } from '../canvas/person.js';
|
|
2
4
|
import { requestPersonId } from '../canvas/person-state.js';
|
|
3
5
|
import { OBJECT_TYPE, GROUP_TYPE } from './builtin.js';
|
|
@@ -10,9 +12,18 @@ export const PERMISSIONS = ['read', 'edit', 'message', 'use', 'share'];
|
|
|
10
12
|
/** The ceiling access class a permission asks: read/use → read, edit/share → write, message → message. */
|
|
11
13
|
const ACCESS = { read: 'read', use: 'read', edit: 'write', share: 'write', message: 'message' };
|
|
12
14
|
const bareUser = (principal) => principal.replace(/^user:/, '');
|
|
15
|
+
/** A `sub` is a person only when the shared parser says `user:<id>`; an app principal, a bare id and any unknown prefix are no person (denied). An app acting as its own subject (`app:<id>`) is no person: it never becomes a user, so no `acts_for` or subject set is built from it. */
|
|
16
|
+
const personSub = (sub) => { const p = parsePrincipal(sub); return p?.kind === 'user' ? bareUser(p.namespace) : null; };
|
|
13
17
|
/** The user a reader acts for: a person's own identity; an app call's `sub`; a node's `sub`; otherwise the install's person. */
|
|
14
18
|
export async function userOf(db, reader) {
|
|
15
|
-
|
|
19
|
+
const named = await namedUserOf(db, reader);
|
|
20
|
+
if (named !== null)
|
|
21
|
+
return named;
|
|
22
|
+
// A sub the parser rejects, or an app principal, never falls back. A reader with no sub falls back to the install's person on a local install only (one person there); a cloud role denies it.
|
|
23
|
+
const subless = reader.class === 'app' && reader.sub === undefined;
|
|
24
|
+
if (reader.class === 'app' && !(subless && !isCloudRole()))
|
|
25
|
+
throw new PermissionError(403, 'no_person', 'an app reader that names no person acts for no one');
|
|
26
|
+
return bareUser(await personIdAsync());
|
|
16
27
|
}
|
|
17
28
|
/** The user a reader names itself, without falling back to the process's person; null when it names none. */
|
|
18
29
|
async function namedUserOf(db, reader) {
|
|
@@ -21,12 +32,12 @@ async function namedUserOf(db, reader) {
|
|
|
21
32
|
return row === undefined ? null : bareUser(row.external_id);
|
|
22
33
|
}
|
|
23
34
|
if (reader.class === 'app')
|
|
24
|
-
return reader.sub === undefined ? null :
|
|
35
|
+
return reader.sub === undefined ? null : personSub(reader.sub);
|
|
25
36
|
if (reader.class === 'object' && reader.sub !== undefined)
|
|
26
|
-
return
|
|
37
|
+
return personSub(reader.sub);
|
|
27
38
|
const nodeId = reader.class === 'node' ? reader.node.id : reader.object.id;
|
|
28
39
|
const row = await db.prepare('SELECT sub FROM nodes WHERE node_id = ?').get(nodeId);
|
|
29
|
-
return row?.sub == null ? null :
|
|
40
|
+
return row?.sub == null ? null : personSub(row.sub);
|
|
30
41
|
}
|
|
31
42
|
/** The user ids a subject stands for (the user and `*`) and every group it reaches, directly or through nested groups. */
|
|
32
43
|
export async function subjectSet(db, userId) {
|
|
@@ -51,7 +62,7 @@ export function resolveReader(db, reader) {
|
|
|
51
62
|
if (shared)
|
|
52
63
|
return shared;
|
|
53
64
|
const ev = (async () => {
|
|
54
|
-
const userId = isCloudRole() && requestPersonId() === undefined ? await namedUserOf(db, reader) : await userOf(db, reader);
|
|
65
|
+
const userId = (isCloudRole() && requestPersonId() === undefined) ? await namedUserOf(db, reader) : await userOf(db, reader);
|
|
55
66
|
return { reader, userId, subjects: userId === null ? { userIds: ['*'], groupIds: [] } : await subjectSet(db, userId), defs: await loadDefinitions(db) };
|
|
56
67
|
})();
|
|
57
68
|
if (shared === null) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { validateDeclaredResult } from '../../api/command-manifest/result.js';
|
|
2
2
|
import { callerAllows, requireGroup } from '../../daemon/api/handlers/providers.js';
|
|
3
3
|
import { callerTerminalGrant } from '../grants/terminal.js';
|
|
4
|
-
import { findRefusal, payerOf, refusalError, refusedMark, writeCharge } from '../ledger/index.js';
|
|
4
|
+
import { environmentPayerOfNode, findRefusal, payerOf, refusalError, refusedMark, writeCharge } from '../ledger/index.js';
|
|
5
5
|
import { listInstalledPlugins } from '../resolver.js';
|
|
6
6
|
import { emitEvent } from '../events/emit.js';
|
|
7
7
|
import { ProviderError, scopeMissing } from './errors.js';
|
|
@@ -282,7 +282,7 @@ export async function callProvider(caller, rawInput, request) {
|
|
|
282
282
|
jti = token.jti;
|
|
283
283
|
// The payer is the token's claim, so the check runs once the token is in hand and before anything is sent to the provider.
|
|
284
284
|
const chargeGrantee = caller.class === 'person' ? TERMINAL_GRANTEE : grantee;
|
|
285
|
-
const paid = payerOf({ call: 'tool', tokenPayer: token.payer, sub });
|
|
285
|
+
const paid = payerOf({ call: 'tool', tokenPayer: token.payer, sub, environmentPayer: await environmentPayerOfNode(caller.node_id) });
|
|
286
286
|
const refusal = await findRefusal({ scope: 'call', payer: paid.payer, funding: paid.funding, sub, grantee: chargeGrantee, provider: `app:${bundle.id}` });
|
|
287
287
|
if (refusal !== null) {
|
|
288
288
|
await writeCharge({ request: requestId, kind: 'tool', what: `${bundle.id}:${input.tool}`, usd: 0, payer: paid.payer, funding: paid.funding, sub, grantee: chargeGrantee,
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { isCloudRole, personId } from '../canvas/person.js';
|
|
2
|
+
import { RunError } from './operations.js';
|
|
3
|
+
/** The subject a node launches as. A node carries its own `sub`; only an unjoined single-person install, whose nodes may predate it, falls back to the install's person. A cloud role never does: it serves many subjects and has no person of its own. */
|
|
4
|
+
export function launchSub(sub, nodeId) {
|
|
5
|
+
if (sub != null)
|
|
6
|
+
return sub;
|
|
7
|
+
if (isCloudRole())
|
|
8
|
+
throw new RunError(500, 'node_without_sub', `node ${nodeId} has no sub`);
|
|
9
|
+
return personId();
|
|
10
|
+
}
|
|
@@ -43,7 +43,7 @@ import { bindBrokerEventSource, eventSource } from '../events/source.js';
|
|
|
43
43
|
import { envBrokerEngine } from '../../shared/env.js';
|
|
44
44
|
import { conversationIdFromPath, conversationStore, ConversationNotFoundError } from '../conversation-store/index.js';
|
|
45
45
|
import { mintNodeToken } from '../canvas/node-tokens.js';
|
|
46
|
-
import {
|
|
46
|
+
import { launchSub } from '../runs/node-sub.js';
|
|
47
47
|
// HeadlessBrokerHost (design §3.3): a detached broker PROCESS, no tmux pane. It
|
|
48
48
|
// boots the dedicated broker-cli entry directly (NEVER src/cli.ts), supervises
|
|
49
49
|
// via the broker pid recorded as pi_pid, and tears down over the node's unix
|
|
@@ -532,7 +532,7 @@ export const headlessBrokerHost = {
|
|
|
532
532
|
// The second serves the one relaunch a grant sync during launch can force.
|
|
533
533
|
const readFds = [openSync(`/proc/self/fd/${tokenFd}`, 'r'), openSync(`/proc/self/fd/${tokenFd}`, 'r')];
|
|
534
534
|
closeSync(tokenFd);
|
|
535
|
-
const launchNode = { nodeId, app, sub: row.sub
|
|
535
|
+
const launchNode = { nodeId, app, sub: launchSub(row.sub, nodeId), grantId: row.grant_id ?? null,
|
|
536
536
|
scopes: row.scopes ?? null, isolated: row.isolated === true,
|
|
537
537
|
...(row.isolated === true ? { cwd: row.cwd } : {}),
|
|
538
538
|
command: [process.execPath, resolveBrokerEntry(), '--canvas-home', crtrHome(), '--epoch', fleet.epoch(), nodeId],
|
|
@@ -441,7 +441,7 @@ export async function spawnChildPrepared(opts, beforeBrokerLaunch, afterNodeCrea
|
|
|
441
441
|
})).launch, launchGrant, opts.model);
|
|
442
442
|
await assertLaunchModelRegistered(requestFromLaunch(preflightLaunch), { cwd: birthCwd, profileId });
|
|
443
443
|
// The start check, before any worktree or node row exists: a refusal leaves nothing behind.
|
|
444
|
-
await checkStart({ grantee: payerSource?.grantee ?? 'app:terminal', sub: payerSource?.sub, grant_id: payerSource?.grant_id });
|
|
444
|
+
await checkStart({ grantee: payerSource?.grantee ?? 'app:terminal', sub: payerSource?.sub, grant_id: payerSource?.grant_id, profile_id: profileId });
|
|
445
445
|
const forkSourceNodeId = forkSourceMeta?.node_id ?? null;
|
|
446
446
|
let managedWorktree;
|
|
447
447
|
let spawnCwd = birthCwd;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// The start check (design-ledger, "The check → Start check"): run before a node is born, a run starts, a cron fires, a job
|
|
2
2
|
// starts or a dormant node revives. The candidate's payer is whoever pays the node's model calls.
|
|
3
|
-
import { check, findRefusal, payerOf } from '../ledger/index.js';
|
|
3
|
+
import { check, environmentPayerOfProfile, findRefusal, payerOf } from '../ledger/index.js';
|
|
4
4
|
import { RunError } from '../runs/operations.js';
|
|
5
5
|
import { grantStanding, payerOfGrant } from '../grants/mirror.js';
|
|
6
6
|
import { callerTerminalGrant } from '../grants/terminal.js';
|
|
@@ -11,7 +11,7 @@ export async function startCandidateOf(who) {
|
|
|
11
11
|
if (sub === null)
|
|
12
12
|
return null;
|
|
13
13
|
const paid = await payerOfGrant(who.grant_id);
|
|
14
|
-
const payer = payerOf({ call: 'start', grantPayer: paid, sub, grantee });
|
|
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
|
}
|
|
17
17
|
/** Throw `402 cap_exhausted` (limit named) when a limit covering every charge of this identity's payer is reached. */
|
|
@@ -123,7 +123,7 @@ async function resolveRecipe(request) {
|
|
|
123
123
|
* and the create request uncommitted. A claimed spare is a started node like any birth. */
|
|
124
124
|
async function checkClaimantStart(request) {
|
|
125
125
|
const creator = request.creator === null ? null : await getNode(request.creator);
|
|
126
|
-
await checkStart({ grantee: creator?.grantee ?? 'app:terminal', sub: creator?.sub, grant_id: creator?.grant_id });
|
|
126
|
+
await checkStart({ grantee: creator?.grantee ?? 'app:terminal', sub: creator?.sub, grant_id: creator?.grant_id, profile_id: creator?.profile_id });
|
|
127
127
|
}
|
|
128
128
|
/** Claim a spare for `request`, reshaped onto its persona — or null when the
|
|
129
129
|
* pool cannot serve it. The caller falls back to a cold spawn; a refused
|
|
@@ -13,7 +13,8 @@ import { pinSandboxRuntimeHome } from './runtime-home.js';
|
|
|
13
13
|
import { sandboxCacheEnv } from './cache-env.js';
|
|
14
14
|
import { launcherRequest } from '../../launcher/client.js';
|
|
15
15
|
import { LAUNCHER_SOCKET } from '../../launcher/spec.js';
|
|
16
|
-
import { isCloudRole
|
|
16
|
+
import { isCloudRole } from '../canvas/person.js';
|
|
17
|
+
import { launchSub } from '../runs/node-sub.js';
|
|
17
18
|
/** The launcher's node id for one cron execution; its run folder is `nodeRunDir(<this>)`. */
|
|
18
19
|
export function cronLaunchId(executionId) { return `cron-${executionId}`; }
|
|
19
20
|
/** The same mount compiler and launcher request used by broker launches. A node
|
|
@@ -48,7 +49,7 @@ export async function cwdIsMounted(app, cwd, nodeId, isolated = false, folder, p
|
|
|
48
49
|
const spec = await compileLaunch({ nodeId: nodeId ?? `proc-cwd-check`, app,
|
|
49
50
|
...(principal !== undefined
|
|
50
51
|
? { sub: principal.sub, grantId: grant?.id ?? null, scopes: principal.scopes }
|
|
51
|
-
: { sub: row ? row.sub
|
|
52
|
+
: { sub: row ? launchSub(row.sub, row.node_id) : grant.sub, grantId: row ? row.grant_id ?? null : grant.id, scopes: row?.scopes ?? null }),
|
|
52
53
|
command: ['true'], env: {},
|
|
53
54
|
...(nodeId === undefined ? { withoutNode: true } : {}),
|
|
54
55
|
...(folder === undefined ? {} : { folder }),
|
|
@@ -91,7 +92,7 @@ export async function launchAppProcess(options) {
|
|
|
91
92
|
throw new Error(`no active grant for ${app}`);
|
|
92
93
|
}
|
|
93
94
|
else if (row) {
|
|
94
|
-
if (app !== 'app:terminal' && !(row.grant_id ? await activeGrant(row.grant_id) : await grantFor(app, row.sub
|
|
95
|
+
if (app !== 'app:terminal' && !(row.grant_id ? await activeGrant(row.grant_id) : await grantFor(app, launchSub(row.sub, row.node_id)))) {
|
|
95
96
|
throw new Error(`no active grant for ${app}`);
|
|
96
97
|
}
|
|
97
98
|
}
|
|
@@ -117,7 +118,7 @@ export async function launchAppProcess(options) {
|
|
|
117
118
|
}).filter((entry) => entry[1] !== undefined)));
|
|
118
119
|
const launchNode = stored !== undefined
|
|
119
120
|
? { nodeId, app, sub: stored.sub, grantId: grant?.id ?? null, scopes: stored.scopes }
|
|
120
|
-
: { nodeId, app, sub: row ? row.sub
|
|
121
|
+
: { nodeId, app, sub: row ? launchSub(row.sub, row.node_id) : grant.sub, grantId: row ? row.grant_id ?? null : grant.id, scopes: row?.scopes ?? null };
|
|
121
122
|
const compile = async () => {
|
|
122
123
|
const spec = await compileLaunch({ ...launchNode, command: options.command, env,
|
|
123
124
|
...(options.nodeId === undefined ? { withoutNode: true } : {}),
|
|
@@ -62,7 +62,7 @@ async function handleStart(ctx) {
|
|
|
62
62
|
}
|
|
63
63
|
// The start check with the node's payer, before the job is marked started: a refusal launches nothing.
|
|
64
64
|
const owner = (await getNode(nodeId));
|
|
65
|
-
await checkStart({ grantee: owner.grantee ?? 'app:terminal', sub: owner.sub, grant_id: owner.grant_id });
|
|
65
|
+
await checkStart({ grantee: owner.grantee ?? 'app:terminal', sub: owner.sub, grant_id: owner.grant_id, profile_id: owner.profile_id });
|
|
66
66
|
if (!appProcessSandboxed())
|
|
67
67
|
throw new ApiError(400, 'invalid_request', 'job.start is only used with the root launcher');
|
|
68
68
|
const paths = bashJobPaths(dir, jobId);
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
// Past the gate, the bodies are filled in by later tasks — `provider.call` by
|
|
10
10
|
// R4 (`core/providers/call.ts`), `provider.tools` by R8 — and answer
|
|
11
11
|
// `not_implemented` until then.
|
|
12
|
+
import { parsePrincipal } from '@north-light/identity';
|
|
12
13
|
import { randomUUID } from 'node:crypto';
|
|
13
14
|
import { cloudPersonScope } from '../../../core/runs/operations.js';
|
|
14
15
|
import { directoryIssuer } from '../../../core/directory/issuer.js';
|
|
@@ -140,8 +141,11 @@ export function parseCallInput(body) {
|
|
|
140
141
|
const machine = fields['machine'];
|
|
141
142
|
if (machine !== undefined && (typeof machine !== 'string' || !machine.trim()))
|
|
142
143
|
throw invalid('machine must be a machine id', 'machine');
|
|
144
|
+
const as = fields['as'];
|
|
145
|
+
if (as !== undefined && (typeof as !== 'string' || parsePrincipal(as) === null))
|
|
146
|
+
throw invalid('as must be a principal like user:<id> or app:<id>/<path>', 'as');
|
|
143
147
|
return { provider, tool: tool.trim(), arguments: args, ...(version === undefined ? {} : { version }), ...(approval === undefined ? {} : { approval }),
|
|
144
|
-
...(machine === undefined ? {} : { machine: machine.trim() }) };
|
|
148
|
+
...(machine === undefined ? {} : { machine: machine.trim() }), ...(as === undefined ? {} : { as }) };
|
|
145
149
|
}
|
|
146
150
|
async function auditList(caller, query = new URLSearchParams()) {
|
|
147
151
|
const numeric = (name, fallback, max) => {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/api",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.749",
|
|
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",
|
|
@@ -131,3 +131,11 @@ export declare function verifyIdToken(options: {
|
|
|
131
131
|
issuer: string;
|
|
132
132
|
audience: string;
|
|
133
133
|
}): Promise<IdTokenClaims>;
|
|
134
|
+
/** A parsed principal: `user:<id>`, `app:<id>`, or `app:<id>/<segment>(/<segment>)*`. `namespace` is `user:<id>` or `app:<id>`; `path` is the segments under an app (empty for a namespace root). */
|
|
135
|
+
export interface Principal {
|
|
136
|
+
kind: 'user' | 'app';
|
|
137
|
+
namespace: string;
|
|
138
|
+
path: string[];
|
|
139
|
+
}
|
|
140
|
+
/** The one principal parser: every site that reads a principal string denies a `null`. Segments may contain `:` but not `/`; a bare id, an unknown prefix, an empty segment or a path under `user:` is rejected. */
|
|
141
|
+
export declare function parsePrincipal(value: string): Principal | null;
|
|
@@ -368,3 +368,21 @@ export async function verifyIdToken(options) {
|
|
|
368
368
|
throw new Error('Invalid ID token claims');
|
|
369
369
|
return payload;
|
|
370
370
|
}
|
|
371
|
+
const PRINCIPAL_ID = /^[A-Za-z0-9_-]{1,64}$/;
|
|
372
|
+
const PRINCIPAL_SEGMENT = /^[^/\s]+$/;
|
|
373
|
+
/** The one principal parser: every site that reads a principal string denies a `null`. Segments may contain `:` but not `/`; a bare id, an unknown prefix, an empty segment or a path under `user:` is rejected. */
|
|
374
|
+
export function parsePrincipal(value) {
|
|
375
|
+
const m = /^(user|app):([^/]*)((?:\/.*)?)$/.exec(value);
|
|
376
|
+
if (m === null || !PRINCIPAL_ID.test(m[2]))
|
|
377
|
+
return null;
|
|
378
|
+
const kind = m[1];
|
|
379
|
+
const rest = m[3];
|
|
380
|
+
if (rest === '')
|
|
381
|
+
return { kind, namespace: `${kind}:${m[2]}`, path: [] };
|
|
382
|
+
if (kind === 'user')
|
|
383
|
+
return null;
|
|
384
|
+
const path = rest.slice(1).split('/');
|
|
385
|
+
if (!path.every((s) => PRINCIPAL_SEGMENT.test(s)))
|
|
386
|
+
return null;
|
|
387
|
+
return { kind, namespace: `app:${m[2]}`, path };
|
|
388
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/plugin",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.749",
|
|
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.
|
|
31
|
-
"@north-light/identity": "0.3.
|
|
30
|
+
"@north-light/api": "0.3.749",
|
|
31
|
+
"@north-light/identity": "0.3.749"
|
|
32
32
|
},
|
|
33
33
|
"license": "UNLICENSED",
|
|
34
34
|
"publishConfig": {
|