@north-light/cli 0.3.749 → 0.3.751
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/builtin-memory/crouter-sdk/release-notes.md +10 -0
- package/dist/core/canvas/schema-pg/037-grant-principals.sql +50 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/grants/local.js +1 -1
- package/dist/core/grants/mirror.d.ts +11 -3
- package/dist/core/grants/mirror.js +12 -12
- package/dist/core/grants/owner.d.ts +7 -0
- package/dist/core/grants/owner.js +1 -0
- package/dist/core/grants/shadow.js +1 -1
- package/dist/core/grants/sync.js +1 -1
- package/dist/core/graph/reader.js +3 -3
- package/dist/core/import/load/bind.d.ts +1 -1
- package/dist/core/import/load/bind.js +11 -8
- package/dist/core/ledger/payer.d.ts +4 -4
- package/dist/core/ledger/payer.js +1 -1
- package/dist/core/llm/app-rungs.js +1 -1
- package/dist/core/llm/run.d.ts +2 -2
- package/dist/core/llm/run.js +2 -2
- package/dist/core/runtime/start-check.js +1 -1
- package/dist/core/spaces/permissions.js +1 -1
- package/dist/core/spaces/process.js +1 -1
- package/dist/daemon/api/app-listener.js +12 -12
- package/dist/daemon/api/handlers/git-credential.js +1 -1
- package/dist/daemon/api/handlers/runs.js +1 -1
- package/dist/daemon/api/principal.d.ts +11 -5
- package/dist/daemon/api/principal.js +1 -1
- package/docs/ci-runner.md +1 -1
- package/docs/sdk/release-notes.md +10 -0
- package/package.json +3 -3
- package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
- package/packages/crouter-api/dist/core/grants/local.js +1 -1
- package/packages/crouter-api/dist/core/grants/mirror.js +35 -11
- package/packages/crouter-api/dist/core/grants/owner.js +15 -0
- package/packages/crouter-api/dist/core/grants/shadow.js +4 -2
- package/packages/crouter-api/dist/core/grants/sync.js +5 -4
- package/packages/crouter-api/dist/core/graph/reader.js +8 -5
- package/packages/crouter-api/dist/core/ledger/payer.js +8 -3
- package/packages/crouter-api/dist/core/llm/app-rungs.js +2 -2
- package/packages/crouter-api/dist/core/llm/run.js +3 -2
- package/packages/crouter-api/dist/core/runtime/start-check.js +2 -2
- package/packages/crouter-api/dist/core/spaces/permissions.js +10 -4
- package/packages/crouter-api/dist/core/spaces/process.js +5 -3
- package/packages/crouter-api/dist/daemon/api/handlers/git-credential.js +12 -2
- package/packages/crouter-api/dist/daemon/api/principal.js +26 -7
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/dist/index.d.ts +4 -2
- package/packages/crouter-identity/dist/index.js +31 -12
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/dist/serve.js +4 -1
- package/packages/crouter-plugin/dist/verify.js +36 -8
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
|
@@ -9,6 +9,16 @@ when-and-why-to-read: When you need Release notes, this knowledge should be read
|
|
|
9
9
|
|
|
10
10
|
Changes to `@north-light/sdk` that can change what an existing app sees. Newest first.
|
|
11
11
|
|
|
12
|
+
## 0.3.751
|
|
13
|
+
|
|
14
|
+
### Call tokens may name any principal
|
|
15
|
+
|
|
16
|
+
The identity verifier accepts an `app:<id>` or `app:<id>/<path>` subject, and an app link with no grant when that app owns the subject's namespace (`chain[i].owner`). Strings that are not `user:`, `app:` or an app path are refused.
|
|
17
|
+
|
|
18
|
+
### The daemon resolves owner tokens and exchanged person tokens
|
|
19
|
+
|
|
20
|
+
A token whose only link is an owner link now resolves to a caller holding the app's declared scopes and no grant (`grant` and `rev` are null). Operations that read or stream a grant (`grant.get`, `llm.*`) answer 403 `permission_error` to it. A grant-bearing `user:` link on an exchanged token resolves like an app link, with the person as the caller.
|
|
21
|
+
|
|
12
22
|
## 0.3.721
|
|
13
23
|
|
|
14
24
|
### `inferenceEndpoint` serves an app that pays for its own model calls (`billing: 'app'`)
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
-- 037-grant-principals.sql — a grant can name a grantee subtree (`grantee_prefix`), its payer is a principal, and it can narrow to resources; the spend cap sits on the payer.
|
|
2
|
+
|
|
3
|
+
-- A wildcard row stores `grantee = '*'` (the column stays NOT NULL, the (runtime, sub, grantee) unique index is unchanged) and the prefix it covers in `grantee_prefix`.
|
|
4
|
+
ALTER TABLE grants ADD COLUMN grantee_prefix text;
|
|
5
|
+
ALTER TABLE grants ADD CONSTRAINT grants_wildcard_check CHECK ((grantee = '*') = (grantee_prefix IS NOT NULL));
|
|
6
|
+
CREATE UNIQUE INDEX idx_grants_runtime_sub_grantee_prefix ON grants(runtime, sub, grantee_prefix) WHERE grantee_prefix IS NOT NULL;
|
|
7
|
+
|
|
8
|
+
-- `payer` held `'user'` or `'app'`; it now holds the principal that pays: `'user'` is the grant's `sub`, `'app'` its `grantee`.
|
|
9
|
+
UPDATE grants SET payer = sub WHERE payer = 'user';
|
|
10
|
+
UPDATE grants SET payer = grantee WHERE payer = 'app';
|
|
11
|
+
|
|
12
|
+
CREATE TABLE grant_resources (
|
|
13
|
+
grant_id text NOT NULL REFERENCES grants(id) ON DELETE CASCADE,
|
|
14
|
+
service text NOT NULL,
|
|
15
|
+
resource_kind text NOT NULL,
|
|
16
|
+
resource_id text NOT NULL,
|
|
17
|
+
PRIMARY KEY (grant_id, service, resource_kind, resource_id)
|
|
18
|
+
);
|
|
19
|
+
|
|
20
|
+
DROP TRIGGER crtr_sig_grant_upd ON grants;
|
|
21
|
+
CREATE TRIGGER crtr_sig_grant_upd AFTER UPDATE OF
|
|
22
|
+
id, runtime, sub, grantee, grantee_prefix, rev, scopes_json, resolved_scopes_json, spend_cap, expires_at, status, revoked_at,
|
|
23
|
+
approved_at, payer, synced_at, dependencies_json, run_notice_url, inference_endpoint_json, created_at,
|
|
24
|
+
computed_rev, app_pays_until_vendor
|
|
25
|
+
ON grants FOR EACH ROW EXECUTE FUNCTION crtr_signal_grant();
|
|
26
|
+
|
|
27
|
+
-- The cap is the payer's: an active capped grant limits its payer (`sub` when none) for its grantee. As before, a grant its own grantee pays (the app's endpoint pays) and `app:terminal`'s have none.
|
|
28
|
+
CREATE OR REPLACE FUNCTION crtr_grant_limit() RETURNS trigger LANGUAGE plpgsql AS $$
|
|
29
|
+
BEGIN
|
|
30
|
+
IF TG_OP = 'DELETE' THEN
|
|
31
|
+
DELETE FROM limits WHERE source = 'grant_sync' AND id = 'grant:' || OLD.id;
|
|
32
|
+
RETURN OLD;
|
|
33
|
+
END IF;
|
|
34
|
+
IF NEW.status = 'active' AND NEW.spend_cap IS NOT NULL AND NEW.payer IS DISTINCT FROM NEW.grantee AND NEW.grantee <> 'app:terminal' THEN
|
|
35
|
+
INSERT INTO limits (id, payer, grantee, usd_per_month, source, updated_at)
|
|
36
|
+
VALUES ('grant:' || NEW.id, COALESCE(NEW.payer, NEW.sub), NEW.grantee, NEW.spend_cap::numeric, 'grant_sync',
|
|
37
|
+
to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'))
|
|
38
|
+
ON CONFLICT (id) DO UPDATE SET payer = EXCLUDED.payer, funding = NULL, grantee = EXCLUDED.grantee, provider = NULL, sub = NULL,
|
|
39
|
+
account = NULL, usd_per_month = EXCLUDED.usd_per_month, source = 'grant_sync', updated_at = EXCLUDED.updated_at
|
|
40
|
+
WHERE limits.source = 'grant_sync';
|
|
41
|
+
ELSE
|
|
42
|
+
DELETE FROM limits WHERE source = 'grant_sync' AND id = 'grant:' || NEW.id;
|
|
43
|
+
END IF;
|
|
44
|
+
RETURN NULL;
|
|
45
|
+
END $$;
|
|
46
|
+
-- Rows already mirrored get their limit under the new rule on the next sync write; rebuild them now.
|
|
47
|
+
UPDATE grants SET spend_cap = spend_cap WHERE spend_cap IS NOT NULL;
|
|
48
|
+
|
|
49
|
+
-- Version 36 reads `payer = 'app'` to mean app-paid; it would read an app-paid grant's principal payer as owner-paid, so it is refused.
|
|
50
|
+
INSERT INTO canvas_meta (key, value) VALUES ('schema_min_reader', '37') ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
|
|
2
2
|
* `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
|
|
3
3
|
* one below the live database's `schema_min_reader`. */
|
|
4
|
-
export declare const CANVAS_SCHEMA_VERSION =
|
|
4
|
+
export declare const CANVAS_SCHEMA_VERSION = 37;
|
|
5
5
|
/** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
|
|
6
6
|
* means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
|
|
7
7
|
* it is put in a `search_path` connection option. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=
|
|
1
|
+
var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=37;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var u=Object.defineProperty;var i=(r,t)=>u(r,"name",{value:t,configurable:!0});import{withCanvasWrite as p}from"../canvas/db.js";import{replaceGrants as m}from"./mirror.js";const a=["crtr:llm","crtr:act","crtr:schedule","crtr:memory:rw:user","crtr:memory:manage:user","crtr:files:rw:user:."].map(r=>({scope:r,mode:"always"}));async function g(r,t){const n=`terminal:${r}`,
|
|
1
|
+
var u=Object.defineProperty;var i=(r,t)=>u(r,"name",{value:t,configurable:!0});import{withCanvasWrite as p}from"../canvas/db.js";import{replaceGrants as m}from"./mirror.js";const a=["crtr:llm","crtr:act","crtr:schedule","crtr:memory:rw:user","crtr:memory:manage:user","crtr:files:rw:user:."].map(r=>({scope:r,mode:"always"}));async function g(r,t){const n=`terminal:${r}`,c=JSON.stringify(a);if(await p(async o=>{const l=await o.prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get(),e=await o.prepare("SELECT id, runtime, sub, grantee, status, scopes_json, resolved_scopes_json FROM grants").all();return l?.value==="local"&&e.length===1&&e[0].id===n&&e[0].runtime===r&&e[0].sub===t&&e[0].grantee==="app:terminal"&&e[0].status==="active"&&e[0].scopes_json===c&&e[0].resolved_scopes_json===c}))return;const s=new Date().toISOString();await m([{id:n,runtime:r,sub:t,grantee:"app:terminal",rev:1,scopes:a,resolved_scopes:a,spend_cap:null,expires_at:null,status:"active",revoked_at:null,approved_at:s,payer:t,dependencies:{},synced_at:s}],s,"local")}i(g,"installLocalTerminalGrant");export{g as installLocalTerminalGrant};
|
|
@@ -17,6 +17,8 @@ export interface GrantRecord {
|
|
|
17
17
|
runtime: string;
|
|
18
18
|
sub: string;
|
|
19
19
|
grantee: string;
|
|
20
|
+
/** A wildcard grant (`grantee = '*'`): the grantee-principal prefix it covers; null on an exact grant. */
|
|
21
|
+
grantee_prefix?: string | null;
|
|
20
22
|
rev: number;
|
|
21
23
|
scopes: GrantScope[];
|
|
22
24
|
resolved_scopes: GrantScope[];
|
|
@@ -25,15 +27,20 @@ export interface GrantRecord {
|
|
|
25
27
|
status: 'active' | 'revoked' | 'removed';
|
|
26
28
|
revoked_at: string | null;
|
|
27
29
|
approved_at: string | null;
|
|
28
|
-
|
|
30
|
+
/** The principal that pays: the grant's `sub` for an owner-paid grant, its `grantee` for an app-paid one. Null reads as `sub`. */
|
|
31
|
+
payer: string | null;
|
|
29
32
|
/** The directory's setup entry (`{ state, message?, next, step? }`) per setup id the grantee requires. Absent (an older directory) reads as `{}`. */
|
|
30
33
|
dependencies?: GrantDependencies;
|
|
31
34
|
/** The grantee's registered run-notice endpoint (https), or null: runs of this grant send no notice. */
|
|
32
35
|
run_notice_url?: string | null;
|
|
33
|
-
/** The endpoint of an app-paid grant (
|
|
36
|
+
/** The endpoint of an app-paid grant (its payer is an app namespace root); null on a grant that app does not pay or one the directory sent no valid endpoint for. */
|
|
34
37
|
inference_endpoint?: InferenceEndpoint | null;
|
|
35
38
|
synced_at: string;
|
|
36
39
|
}
|
|
40
|
+
/** The payer a mirrored grant carries, as a principal. The directory's older `'user'` (the grant's `sub`) and `'app'` (its `grantee`) read as those principals; anything else must parse as a principal. */
|
|
41
|
+
export declare function principalPayer(payer: unknown, sub: string, grantee: string): string;
|
|
42
|
+
/** Whether the app's inference endpoint pays for this grant's model calls: its payer is an `app:` namespace root. */
|
|
43
|
+
export declare function endpointPays(grant: Pick<GrantRecord, 'payer'>): boolean;
|
|
37
44
|
export interface ActiveGrant extends GrantRecord {
|
|
38
45
|
resolved: Scope[];
|
|
39
46
|
}
|
|
@@ -147,9 +154,10 @@ export interface GrantStanding {
|
|
|
147
154
|
export declare function grantStanding(grantId: string): Promise<GrantStanding>;
|
|
148
155
|
/** Ids of the grants in `status` (this runtime's), for a catch-up pass. */
|
|
149
156
|
export declare function grantIdsWhere(where: string): Promise<string[]>;
|
|
150
|
-
/** Who a grant's model calls are charged to: `app` only
|
|
157
|
+
/** Who a grant's model calls are charged to: `app` only when the app's endpoint pays (`endpointPays`), else the person. */
|
|
151
158
|
export declare function payerOfGrant(grantId: string | null | undefined): Promise<'user' | 'app'>;
|
|
152
159
|
export declare function activeGrant(grantId: string): Promise<ActiveGrant | null>;
|
|
160
|
+
/** `sub`'s active grant to `grantee`: the exact row, else the wildcard row whose `grantee_prefix` is the longest prefix of `grantee`. The `'*'` sentinel never matches as an exact grantee. */
|
|
153
161
|
export declare function grantFor(grantee: string, sub: string): Promise<ActiveGrant | null>;
|
|
154
162
|
/** The app's own active grant on this machine. Null for a mirror-only grant: an
|
|
155
163
|
* unsandboxed machine runs no app, so a fanned-out hosted grant is never "the
|
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
var
|
|
1
|
+
var L=Object.defineProperty;var n=(e,r)=>L(e,"name",{value:r,configurable:!0});import{createHash as C}from"node:crypto";import{parsePrincipal as T,parseScope as M}from"@north-light/identity";import{openDb as d,withCanvasWrite as A}from"../canvas/db.js";import{isUnsandboxedMachine as O}from"../runtime/unsandboxed.js";import{replaceWrittenBy as j,userSubject as F}from"../permissions/facts.js";import{GROUP_TYPE as f,OBJECT_TYPE as $}from"../permissions/builtin.js";import{shadowCheck as k}from"./shadow.js";const U=["not_started","pending","ready","failed","unavailable"],P=["ultra","strong","medium","light"];function G(e,r,t){if(e==null||e==="user")return r;if(e==="app")return t;if(typeof e!="string"||T(e)===null)throw new TypeError("invalid grant payer");return e}n(G,"principalPayer");function H(e){const r=e.payer===null?null:T(e.payer);return r!==null&&r.kind==="app"&&r.path.length===0}n(H,"endpointPays");function x(){const e=process.env.CRTR_RUNTIME;return e?{sql:" AND runtime = ?",args:[e]}:{sql:"",args:[]}}n(x,"runtimeScope");async function i(e,r,t=[]){const s=x();return await(await d()).prepare(`SELECT ${e} FROM grants WHERE (${r})${s.sql}`).all(...t,...s.args)}n(i,"grantRows");async function u(e,r,t=[]){return(await i(e,r,t))[0]}n(u,"grantRow");function W(e){return!/\u0000|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/.test(e)}n(W,"jsonbSafe");function l(e){if(!Array.isArray(e))throw new TypeError("grant scopes must be a list");return e.map(r=>{if(!r||typeof r!="object"||typeof r.scope!="string"||!W(r.scope)||!["always","ask"].includes(r.mode))throw new TypeError("invalid grant scope entry");return{scope:r.scope,mode:r.mode}})}n(l,"entries");function J(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{state:r,message:t,next:s,step:o}=e;return typeof r!="string"||!U.includes(r)||t!==void 0&&typeof t!="string"||o!==void 0&&typeof o!="string"||typeof s!="string"||!s?null:{state:r,...t===void 0?{}:{message:t},next:s,...o===void 0?{}:{step:o}}}n(J,"dependencyOf");function w(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const r={};for(const[t,s]of Object.entries(e)){const o=J(s);o&&(r[t]=o)}return r}n(w,"dependenciesOf");function V(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{base_url:r,rungs:t}=e;if(typeof r!="string"||!r||!t||typeof t!="object"||Array.isArray(t))return null;const s={};for(const o of P){const a=t[o];typeof a=="string"&&a&&(s[o]=a)}return Object.keys(s).length?{base_url:r.replace(/\/+$/,""),rungs:s}:null}n(V,"inferenceEndpointOf");function b(e,r,t,s){return r===e&&t&&s}n(b,"computedFor");function _(e){if(!b(e.rev,e.computed_rev,e.scopes_json!==null,e.resolved_scopes_json!==null))throw new TypeError("grant columns are not computed for this revision");return{id:e.id,runtime:e.runtime,sub:e.sub,grantee:e.grantee,grantee_prefix:e.grantee_prefix??null,rev:e.rev,scopes:l(JSON.parse(e.scopes_json)),resolved_scopes:l(JSON.parse(e.resolved_scopes_json)),spend_cap:e.spend_cap,expires_at:e.expires_at,status:e.status,revoked_at:e.revoked_at,approved_at:e.approved_at,payer:e.payer,dependencies:w(JSON.parse(e.dependencies_json??"{}")),run_notice_url:e.run_notice_url??null,inference_endpoint:e.inference_endpoint_json?V(JSON.parse(e.inference_endpoint_json)):null,synced_at:e.synced_at??""}}n(_,"record");function p(e){if(!e||e.status!=="active")return null;try{const r=Z(_(e));return r!==null&&k(r),r}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}n(p,"active");function y(e){return e.grantee!=="app:terminal"&&O()}n(y,"mirrorOnly");async function de(){return(await Y()).filter(e=>!y(e))}n(de,"localGrants");async function le(e,r){return!y({grantee:e})&&await u("1","grantee = ? AND sub <> ? AND status <> 'removed'",[e,r])!==void 0}n(le,"otherLiveGrantOfApp");const g="[A-Za-z0-9_-]{1,64}",q=new RegExp(`^(${g}):(${g})$`);function B(e){const r=new Set;for(const t of e)if(t.status==="active")for(const{scope:s}of t.resolved_scopes){const o=q.exec(s);o&&o[1]!=="crtr"&&r.add(o[1])}return[...r].sort()}n(B,"providerIdsFromGrants");async function fe(){const e=x();return(await(await d()).prepare(`SELECT DISTINCT m[1] AS id FROM (
|
|
2
2
|
SELECT DISTINCT e->>'scope' AS scope FROM (
|
|
3
|
-
SELECT t::jsonb AS j FROM (SELECT DISTINCT resolved_scopes_json AS t FROM grants WHERE ${
|
|
3
|
+
SELECT t::jsonb AS j FROM (SELECT DISTINCT resolved_scopes_json AS t FROM grants WHERE ${m}${N()}${e.sql}) d OFFSET 0) p
|
|
4
4
|
CROSS JOIN LATERAL jsonb_array_elements(CASE WHEN jsonb_typeof(p.j) = 'array' THEN p.j ELSE '[]' END) e) s
|
|
5
|
-
CROSS JOIN LATERAL regexp_match(s.scope, '^(${
|
|
6
|
-
WHERE m[1] <> 'crtr'`).all(...e.args)).map(
|
|
5
|
+
CROSS JOIN LATERAL regexp_match(s.scope, '^(${g}):${g}$') m
|
|
6
|
+
WHERE m[1] <> 'crtr'`).all(...e.args)).map(t=>t.id).sort()}n(fe,"activeProviderIds");async function _e(){const e=x();return await(await d()).prepare(`SELECT 1 FROM grants WHERE ${m}${N()}${e.sql} LIMIT 1`).get(...e.args)!==void 0}n(_e,"anyActiveGrant");async function ye(e,r){return await u("1",`sub = ? AND ${m}${N()} AND EXISTS (
|
|
7
7
|
SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof(resolved_scopes_json::jsonb) = 'array' THEN resolved_scopes_json::jsonb ELSE '[]' END) e
|
|
8
|
-
WHERE starts_with(e->>'scope', ?))`,[e,`${
|
|
9
|
-
(id, runtime, sub, grantee, rev, scopes_json, resolved_scopes_json, spend_cap, expires_at,
|
|
8
|
+
WHERE starts_with(e->>'scope', ?))`,[e,`${r}:`])!==void 0}n(ye,"activeGrantNamesApp");const m="status = 'active' AND computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL",X="computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL";function N(){return O()?" AND grantee = 'app:terminal'":""}n(N,"localOnly");async function ge(){return(await i("DISTINCT sub",X)).map(e=>e.sub)}n(ge,"grantSubs");async function Ee(e){return h(e===void 0?await i("*","status = 'active'"):await i("*","sub = ? AND status = 'active'",[e]))}n(Ee,"activeGrants");async function ve(e){const r=await i("*","sub = ? AND status = 'active'",[e]);return new Set(B(r.flatMap(t=>{try{return[_(t)]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})))}n(ve,"grantedProviderIds");function xe(e,r){return e.source_marketplace===null&&e.source_path===null&&r.has(e.name)}n(xe,"isProviderBundleRow");async function me(e){return(await i("*","sub = ? AND status = 'active'",[e])).flatMap(t=>{const s=p(t);return s===null?[]:[s]})}n(me,"activeGrantsOfPerson");async function Y(){return h(await i("*","true"))}n(Y,"allGrants");async function Ne(e){return(await i("sub, status, rev, computed_rev, resolved_scopes_json, scopes_json IS NOT NULL AS has_scopes","sub = ?",[e])).flatMap(t=>{if(!b(t.rev,t.computed_rev,t.has_scopes,t.resolved_scopes_json!==null))return[];try{return[{sub:t.sub,status:t.status,resolved_scopes:l(JSON.parse(t.resolved_scopes_json))}]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})}n(Ne,"grantsOfPerson");function h(e){return e.flatMap(r=>{try{return[_(r)]}catch(t){if(t instanceof TypeError||t instanceof SyntaxError)return[];throw t}})}n(h,"records");function z(e){return e.expires_at!==null&&!(Date.parse(e.expires_at)>Date.now())}n(z,"grantExpired");function Z(e){if(e.status!=="active"||z(e))return null;try{const r=e.resolved_scopes.map(({scope:t})=>M(t));return{...e,resolved:e.resolved_scopes.flatMap(({mode:t},s)=>t==="always"?[r[s]]:[])}}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}n(Z,"activeRecord");function S(e){return Array.isArray(e)?`[${e.map(S).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().filter(r=>e[r]!==void 0).map(r=>`${JSON.stringify(r)}:${S(e[r])}`).join(",")}}`:JSON.stringify(e)??"null"}n(S,"canonicalJson");function Se(e){const r={rev:e.rev,resolved_scopes:e.resolved_scopes,spend_cap:e.spend_cap,payer:e.payer,dependencies:e.dependencies??{},...e.inference_endpoint?{inference_endpoint:e.inference_endpoint}:{}};return C("sha256").update(S(r)).digest("base64url").slice(0,22)}n(Se,"grantVersion");async function Te(e){return!!await u("1","id = ?",[e])}n(Te,"hasGrant");async function Ae(e){return await u("rev, status","id = ?",[e])??null}n(Ae,"grantSyncState");async function Oe(e,r){return await u("rev, status","grantee = ? AND sub = ?",[e,r])??null}n(Oe,"grantSyncStateFor");async function K(e){const r=await u("*","id = ?",[e]);if(!r)return null;try{return _(r)}catch(t){if(t instanceof TypeError||t instanceof SyntaxError)return null;throw t}}n(K,"grantRecord");async function je(e){const r=await u("*","id = ?",[e]);if(!r)return{standing:"inactive",rev:null,sub:null,grantee:null,status:null,removal_done_at:null,record:null};const t={rev:r.rev,sub:r.sub,grantee:r.grantee,status:r.status,removal_done_at:r.removal_done_at??null};if(r.status!=="active")return{...t,standing:"inactive",record:null};if(r.computed_rev!==r.rev)return{...t,standing:"lagging",record:null};const s=p(r);return s===null?{...t,standing:"inactive",record:null}:{...t,standing:"active",record:s}}n(je,"grantStanding");async function we(e){return(await i("id",e)).map(r=>r.id)}n(we,"grantIdsWhere");async function be(e){const r=e?await K(e):null;return r!==null&&H(r)?"app":"user"}n(be,"payerOfGrant");async function Q(e){return p(await u("*","id = ?",[e]))}n(Q,"activeGrant");async function he(e,r){const t=await u("*","grantee = ? AND grantee_prefix IS NULL AND sub = ?",[e,r]);if(t)return p(t);const s=await i("*","sub = ? AND grantee_prefix IS NOT NULL AND starts_with(?, grantee_prefix)",[r,e]);return s.sort((o,a)=>a.grantee_prefix.length-o.grantee_prefix.length),p(s[0])}n(he,"grantFor");async function Re(e){if(y({grantee:e}))return null;const r=await i("*","grantee = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active grants for ${e}`);return p(r[0])}n(Re,"activeGrantForApp");async function De(e){const r=await Q(e);return r&&r.run_notice_url&&!y(r)?{url:r.run_notice_url,sub:r.sub,grantee:r.grantee}:null}n(De,"runNoticeTarget");async function Ie(e){const r=await i("*","grantee = 'app:terminal' AND sub = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active terminal grants for ${e}`);return p(r[0])}n(Ie,"terminalGrant");async function Le(){return(await(await d()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value??null}n(Le,"grantsSource");async function Ce(e){return(await(await d()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value===e}n(Ce,"hasSyncedGrants");async function Me(e){return(await e.prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value!=="local"?0:(await e.prepare("DELETE FROM runtime_state WHERE key = 'grants_source'").run(),Number((await e.prepare("DELETE FROM grants").run()).changes))}n(Me,"dropLocalGrantMirror");async function Fe(){return await A(async e=>Number((await e.prepare("UPDATE grants SET computed_rev = rev WHERE computed_rev IS NULL AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL").run()).changes))}n(Fe,"backfillComputedRev");function $e(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError("invalid grant sync response");const r=[];for(const t of e){const{team:s,members:o}=t??{};if(!(typeof s!="string"||!/^team:\S+$/.test(s))){if(!Array.isArray(o)||o.some(a=>typeof a!="string"||!/^user:[^\s*]+$/.test(a)))throw new TypeError("invalid grant sync response");r.push({team:s,members:o})}}return r}n($e,"teamsOf");async function ke(e,r,t,s=[]){const o=new Set;for(const a of e){if(o.has(a.id)||!a.id||!a.runtime||!a.sub||!a.grantee||!Number.isInteger(a.rev)||!["active","revoked","removed"].includes(a.status))throw new TypeError("invalid grant sync response");if(a.grantee==="*"!=(a.grantee_prefix!=null))throw new TypeError("invalid grant sync response");o.add(a.id),l(a.scopes),l(a.resolved_scopes)}await A(async a=>{let E=0;const v=[...o];E+=Number((await(v.length?a.prepareUncached(`DELETE FROM grants WHERE id NOT IN (${v.map(()=>"?").join(",")})`).run(...v):a.prepareUncached("DELETE FROM grants").run())).changes);const R=a.prepare(`INSERT INTO grants
|
|
9
|
+
(id, runtime, sub, grantee, grantee_prefix, rev, scopes_json, resolved_scopes_json, spend_cap, expires_at,
|
|
10
10
|
status, revoked_at, approved_at, payer, dependencies_json, run_notice_url, inference_endpoint_json, synced_at, computed_rev)
|
|
11
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
12
|
-
ON CONFLICT (id) DO UPDATE SET runtime = excluded.runtime, sub = excluded.sub, grantee = excluded.grantee, rev = excluded.rev,
|
|
11
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
12
|
+
ON CONFLICT (id) DO UPDATE SET runtime = excluded.runtime, sub = excluded.sub, grantee = excluded.grantee, grantee_prefix = excluded.grantee_prefix, rev = excluded.rev,
|
|
13
13
|
scopes_json = excluded.scopes_json, resolved_scopes_json = excluded.resolved_scopes_json, spend_cap = excluded.spend_cap,
|
|
14
14
|
expires_at = excluded.expires_at, status = excluded.status, revoked_at = excluded.revoked_at, approved_at = excluded.approved_at,
|
|
15
15
|
payer = excluded.payer, dependencies_json = excluded.dependencies_json, run_notice_url = excluded.run_notice_url,
|
|
16
16
|
inference_endpoint_json = excluded.inference_endpoint_json, synced_at = excluded.synced_at, computed_rev = excluded.computed_rev
|
|
17
|
-
WHERE (grants.runtime, grants.sub, grants.grantee, grants.rev, grants.scopes_json, grants.resolved_scopes_json, grants.spend_cap,
|
|
17
|
+
WHERE (grants.runtime, grants.sub, grants.grantee, grants.grantee_prefix, grants.rev, grants.scopes_json, grants.resolved_scopes_json, grants.spend_cap,
|
|
18
18
|
grants.expires_at, grants.status, grants.revoked_at, grants.approved_at, grants.payer, grants.dependencies_json,
|
|
19
19
|
grants.run_notice_url, grants.inference_endpoint_json, grants.computed_rev)
|
|
20
|
-
IS DISTINCT FROM (excluded.runtime, excluded.sub, excluded.grantee, excluded.rev, excluded.scopes_json, excluded.resolved_scopes_json,
|
|
20
|
+
IS DISTINCT FROM (excluded.runtime, excluded.sub, excluded.grantee, excluded.grantee_prefix, excluded.rev, excluded.scopes_json, excluded.resolved_scopes_json,
|
|
21
21
|
excluded.spend_cap, excluded.expires_at, excluded.status, excluded.revoked_at, excluded.approved_at, excluded.payer,
|
|
22
|
-
excluded.dependencies_json, excluded.run_notice_url, excluded.inference_endpoint_json, excluded.computed_rev)`);for(const c of e)
|
|
22
|
+
excluded.dependencies_json, excluded.run_notice_url, excluded.inference_endpoint_json, excluded.computed_rev)`);for(const c of e)E+=Number((await R.run(c.id,c.runtime,c.sub,c.grantee,c.grantee_prefix??null,c.rev,JSON.stringify(c.scopes),JSON.stringify(c.resolved_scopes),c.spend_cap,c.expires_at,c.status,c.revoked_at,c.approved_at,G(c.payer,c.sub,c.grantee),JSON.stringify(w(c.dependencies)),c.run_notice_url??null,c.inference_endpoint?JSON.stringify(c.inference_endpoint):null,c.synced_at,c.rev)).changes);await j(a,"directory",f,"member",s.flatMap(({team:c,members:D})=>D.map(I=>({resourceId:c,subject:F(I)})))),await te(a),await a.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_source', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t),E>0&&await a.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()})}n(ke,"replaceGrants");const ee=["editor","messenger","user_of"],re="app-admin";async function te(e){const t=(await e.prepare(`SELECT o.id AS object, r.subject_type, r.subject_id FROM objects o
|
|
23
23
|
JOIN relations r ON r.resource_type = 'app' AND r.resource_id = o.name AND r.relation = 'admin' AND r.subject_type IN ('user', ?)
|
|
24
|
-
WHERE o.type = 'app' AND o.deleted_at IS NULL`).all(
|
|
24
|
+
WHERE o.type = 'app' AND o.deleted_at IS NULL`).all(f)).map(s=>({resourceId:s.object,subject:s.subject_type===f?{type:f,id:s.subject_id,relation:"member"}:{type:"user",id:s.subject_id,relation:""}}));for(const s of ee)await j(e,re,$,s,t)}n(te,"reconcileAppAdminFacts");async function Ue(){const e=await(await d()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_generation'").get();return e?Number(e.value):0}n(Ue,"grantsGeneration");export{re as APP_ADMIN_WRITER,Q as activeGrant,Re as activeGrantForApp,ye as activeGrantNamesApp,Ee as activeGrants,me as activeGrantsOfPerson,fe as activeProviderIds,Z as activeRecord,Y as allGrants,_e as anyActiveGrant,Fe as backfillComputedRev,S as canonicalJson,w as dependenciesOf,Me as dropLocalGrantMirror,H as endpointPays,z as grantExpired,he as grantFor,we as grantIdsWhere,K as grantRecord,je as grantStanding,ge as grantSubs,Ae as grantSyncState,Oe as grantSyncStateFor,Se as grantVersion,ve as grantedProviderIds,Ue as grantsGeneration,Ne as grantsOfPerson,Le as grantsSource,Te as hasGrant,Ce as hasSyncedGrants,V as inferenceEndpointOf,xe as isProviderBundleRow,de as localGrants,y as mirrorOnly,le as otherLiveGrantOfApp,be as payerOfGrant,G as principalPayer,B as providerIdsFromGrants,te as reconcileAppAdminFacts,ke as replaceGrants,De as runNoticeTarget,x as runtimeScope,$e as teamsOf,Ie as terminalGrant};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type Scope } from '@north-light/identity';
|
|
2
|
+
/** Whether `sub` lies in `grantee`'s own namespace (`app:x` for `app:x` and `app:x/…`). A namespace owns itself and needs no grant row. */
|
|
3
|
+
export declare function isNamespaceOwner(grantee: string, sub: string): boolean;
|
|
4
|
+
/** Whether a run with no grant row may proceed as its namespace owner: `sub` is in the grantee's namespace and no grant id is named (a named grant that is gone or revoked still refuses). */
|
|
5
|
+
export declare function ownsWithoutRow(grantee: string, sub: string, grantId: string | null | undefined): boolean;
|
|
6
|
+
/** The scopes an owner principal holds with no grant row: the app's declared scopes (its `crtr_app_` token's), none when it declares none. */
|
|
7
|
+
export declare function ownerScopes(grantee: string): Scope[];
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var o=Object.defineProperty;var r=(p,e)=>o(p,"name",{value:e,configurable:!0});import{parsePrincipal as t,parseScope as i}from"@north-light/identity";import{pluginAppToken as a}from"../secrets.js";function c(p,e){const n=t(e);return n!==null&&n.kind==="app"&&n.namespace===p}r(c,"isNamespaceOwner");function l(p,e,n){return!n&&c(p,e)}r(l,"ownsWithoutRow");function f(p){return(a(p.replace(/^app:/,""))?.scopes??[]).map(e=>i(e))}r(f,"ownerScopes");export{c as isNamespaceOwner,f as ownerScopes,l as ownsWithoutRow};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var S=Object.defineProperty;var a=(e,r)=>S(e,"name",{value:r,configurable:!0});import{directoryIssuer as
|
|
1
|
+
var S=Object.defineProperty;var a=(e,r)=>S(e,"name",{value:r,configurable:!0});import{directoryIssuer as v}from"../directory/issuer.js";import{outboundFetch as $}from"../events/outbound.js";import{warn as u}from"../output.js";import{canonicalJson as m,principalPayer as k}from"./mirror.js";let y=5e3;function R(e){y=e}a(R,"setShadowTtl");const A=512,M=["status","scopes","resolved_scopes","spend_cap","payer","dependencies","run_notice_url","inference_endpoint"];function T(){o.clear()}a(T,"resetShadowCache");const o=new Map,f=new Map,t={agree:0,disagree:0,lagging:0,error:0};async function b(e,r,n){const{mintDirectoryToken:c}=await import("./sync.js"),s=await c(e),i=n?`&epochs=${n.epochs.global},${n.epochs.sub}`:"",_=`${e}/v1/runtime/grant-answers?sub=${encodeURIComponent(r)}${i}`,d=await $("grant_shadow",_,{headers:{Authorization:`Bearer ${s.access_token}`},signal:AbortSignal.timeout(1e4)});if(!d.ok)throw new Error(`grant-answers ${d.status}`);const l=await d.json();if(l.unchanged){if(!n)throw new Error("grant-answers said unchanged to a caller holding nothing");return{...n,epochs:l.epochs,checkedAt:Date.now()}}return{epochs:l.epochs,grants:new Map((l.grants??[]).map(w=>[String(w.id),w])),checkedAt:Date.now()}}a(b,"fetchAnswer");async function x(e,r){const n=o.get(r);if(n&&Date.now()-n.checkedAt<y)return n;const c=f.get(r);if(c)return c;const s=b(e,r,n).then(i=>(o.delete(r),o.set(r,i),o.size>A&&o.delete(o.keys().next().value),i)).finally(()=>f.delete(r));return f.set(r,s),s}a(x,"answerFor");const p=new Set;async function P(){await Promise.all([...p])}a(P,"shadowIdle");async function C(e){const r=v();if(r===null)return;const n=(await x(r,e.sub)).grants.get(e.id);if(!n){t.disagree++,u(`grant_shadow disagree ${JSON.stringify({grant:e.id,sub:e.sub,fields:["missing"]})}`);return}if(n.rev!==e.rev){t.lagging++;return}const c={...n,payer:k(n.payer,e.sub,e.grantee)},s=M.filter(i=>m(c[i]??null)!==m(e[i]??null));if(s.length===0){t.agree++;return}t.disagree++,u(`grant_shadow disagree ${JSON.stringify({grant:e.id,sub:e.sub,rev:e.rev,fields:s})}`)}a(C,"compare");let h,g={agree:0,disagree:0,lagging:0,error:0};function D(){h||(h=setInterval(()=>{const e={agree:t.agree-g.agree,disagree:t.disagree-g.disagree,lagging:t.lagging-g.lagging,error:t.error-g.error};g={...t},e.agree+e.disagree+e.lagging+e.error>0&&u(`grant_shadow_summary ${JSON.stringify({window_s:60,...e})}`)},6e4),h.unref())}a(D,"startSummary");function U(e){if(!process.env.CRTR_RUNTIME)return;D();const r=C(e).catch(n=>{t.error++,u(`grant_shadow error ${JSON.stringify({grant:e.id,message:n instanceof Error?n.message:String(n)})}`)}).finally(()=>p.delete(r));p.add(r)}a(U,"shadowCheck");export{T as resetShadowCache,R as setShadowTtl,U as shadowCheck,t as shadowCounts,P as shadowIdle};
|
package/dist/core/grants/sync.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var j=Object.defineProperty;var r=(e,n)=>j(e,"name",{value:n,configurable:!0});import{createPrivateKey as O,randomUUID as $,sign as A}from"node:crypto";import{readFileSync as T}from"node:fs";import{join as N}from"node:path";import{crtrHome as R}from"../canvas/paths.js";import{withCanvasWrite as v}from"../canvas/db.js";import{reconcilePackages as G}from"../graph/package-reconcile.js";import{isUnsandboxedMachine as k}from"../runtime/unsandboxed.js";import{emitEvent as f}from"../events/emit.js";import{describeOutboundFailure as J,outboundFetch as b,outboundJson as E,outboundRefusal as S}from"../events/outbound.js";import{dependenciesOf as U,endpointPays as B,inferenceEndpointOf as C,principalPayer as D,replaceGrants as F,teamsOf as I}from"./mirror.js";import{onGrantSync as M}from"./on-sync.js";import{hostedEndpointOf as W,paymentSetupUrlOf as q,storeHostedEndpoint as L}from"./hosted-endpoint.js";import{adoptInstallPerson as H}from"../scoped-state/migrate.js";import{PersonOutsideRequestError as z,PersonUnresolvedError as K,personId as V,resolvePerson as Y,retireLocalPerson as Q,setPersonId as X}from"../canvas/person.js";const be=300;function Z(e,n){const t=Math.floor(Date.now()/1e3),i=Buffer.from(JSON.stringify({alg:"ES256",typ:"JWT",kid:e.kid})).toString("base64url"),c=Buffer.from(JSON.stringify({iss:e.client_id,sub:e.client_id,aud:n,iat:t,exp:t+300,jti:$()})).toString("base64url"),u=`${i}.${c}`,o=A("sha256",Buffer.from(u),{key:O({key:e.jwk,format:"jwk"}),dsaEncoding:"ieee-p1363"});return`${u}.${o.toString("base64url")}`}r(Z,"assertion");function y(){const e=JSON.parse(T(N(R(),"secrets","runtime-client.json"),"utf8"));if(!e.jwk||e.alg!=="ES256"||!e.kid||!e.client_id||!e.runtime||e.jwk.kid!==e.kid||e.jwk.kty!=="EC"||e.jwk.crv!=="P-256"||!e.jwk.d)throw new TypeError("invalid runtime client key");return e}r(y,"runtimeClient");function Ee(e=y()){return e.runtime.startsWith("runtime:")?e.runtime.slice(8):e.runtime}r(Ee,"runtimeId");function ee(e){return"This machine was removed from your Northlight account. To use it again, run `crtr sys signin`."}r(ee,"machineRevokedMessage");class x extends Error{static{r(this,"MachineRevokedError")}constructor(n){super(ee(n)),this.name="MachineRevokedError"}}async function te(e,n,t){const i=y(),c=`${e.replace(/\/$/,"")}/token`,u=new URLSearchParams({grant_type:"client_credentials",client_id:i.client_id,client_assertion_type:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer",client_assertion:Z(i,c),...n===void 0?{}:{audience:n},...t===void 0?{}:{sub:t}}),o=await b("directory_token",c,{method:"POST",body:u,signal:AbortSignal.timeout(1e4)});if(!o.ok)throw o.status===401&&k()&&await ne(o)?new x(e):S("directory_token",c,`directory token request failed: ${o.status}`);const a=await E("directory_token",c,o);if(typeof a.access_token!="string")throw new TypeError("directory token response has no access_token");return{access_token:a.access_token,expires_at:re(a.access_token,a.expires_in)}}r(te,"mintDirectoryToken");async function ne(e){try{return(await e.json()).error==="invalid_client"}catch{return!1}}r(ne,"isInvalidClient");function re(e,n){if(typeof n=="number"&&Number.isFinite(n)&&n>0)return Date.now()+n*1e3;try{const t=JSON.parse(Buffer.from(e.split(".")[1]??"","base64url").toString("utf8"));if(typeof t.exp=="number")return t.exp*1e3}catch{}return Date.now()+3e5}r(re,"tokenExpiry");function oe(e,n){if(!e||typeof e!="object")throw new TypeError("invalid grant sync response");const t=e,i=n.runtime.startsWith("runtime:")?n.runtime:`runtime:${n.runtime}`;if(!(t.runtime===i||k()&&typeof t.runtime=="string"&&t.runtime.startsWith("runtime:")&&t.grantee!=="app:terminal")||typeof t.id!="string"||typeof t.sub!="string"||typeof t.grantee!="string"||!Number.isInteger(t.rev)||!Array.isArray(t.scopes)||!Array.isArray(t.resolved_scopes)||!["active","revoked","removed"].includes(t.status??"")||typeof t.synced_at!="string")throw new TypeError("invalid grant sync response");const o=e.revisions?.find(d=>d.rev===t.rev)?.approved_at;if(typeof o!="string")throw new TypeError("grant revision has no approval time");const a=D(t.payer,t.sub,t.grantee);return{...t,spend_cap:t.spend_cap??null,expires_at:t.expires_at??null,grantee_prefix:typeof t.grantee_prefix=="string"?t.grantee_prefix:null,revoked_at:t.revoked_at??null,approved_at:o,payer:a,dependencies:U(t.dependencies),inference_endpoint:B({payer:a})?C(t.inference_endpoint):null,run_notice_url:typeof t.run_notice_url=="string"&&t.run_notice_url!==""?t.run_notice_url:null}}r(oe,"responseGrant");async function ie(){try{return{id:V(),late:null}}catch(n){if(n instanceof z)return null;if(!(n instanceof K))throw n}const e=await Y();return e===null?null:{id:e.id,late:e}}r(ie,"pullPerson");async function se(e){X(e.id),await H(e.id);const n=await Q();await v(async t=>await G(t)),f({level:"info",event:"daemon.person.resolved",fields:{person_id:e.id,source:e.source}}),f({level:"info",event:"daemon.person.retired",fields:{person_id:n.person,retired:n.retired,columns:n.columns}})}r(se,"bindLatePerson");let _;function Se(e){return _?_(e):Promise.resolve()}r(Se,"requestGrantSync");function xe(e,n=t=>{}){let t;const i=e.replace(/\/$/,""),c=r(async()=>{const d=y(),p=await te(i),m=await b("grant_sync",`${i}/v1/runtime/grants`,{headers:{Authorization:`Bearer ${p.access_token}`},signal:AbortSignal.timeout(1e4)});if(!m.ok)throw S("grant_sync",`${i}/v1/runtime/grants`,`directory grant sync failed: ${m.status}`);const s=await E("grant_sync",`${i}/v1/runtime/grants`,m);if(!Array.isArray(s.grants)||typeof s.synced_at!="string")throw new TypeError("invalid grant sync response");const g="hosted_endpoint"in s||"payment_setup_url"in s?{hosted_endpoint:W(s.hosted_endpoint??null),payment_setup_url:q(s.payment_setup_url??null),synced_at:s.synced_at}:void 0,P=s.synced_at,h=s.grants.map(l=>oe(l,d)),w=await v(async()=>{await F(h,P,i,I(s.teams));const l=await ie();return g&&l&&await L(g,l.id),l});f({level:"info",event:"daemon.grants.synced",fields:{grants:h.length,synced_at:s.synced_at}}),w?.late&&await se(w.late);try{await M(n)}catch(l){f({level:"error",event:"daemon.grants.on_sync_failed",error:l})}},"run");let u;const o=r(()=>{const d=c().catch(p=>{throw p instanceof x?f({level:"error",event:"daemon.grants.machine_revoked",error:p}):f({level:"error",event:"daemon.grants.sync_failed",error:p,fields:J(p)}),p}).finally(()=>{t===d&&(t=void 0)});return t=d,d},"start"),a=r((d={})=>t?d.fresh?(u??=t.catch(()=>{}).then(()=>(u=void 0,t??o())),u):t:o(),"sync");return _=a,a}r(xe,"createGrantSync");export{be as GRANT_SYNC_INTERVAL_S,x as MachineRevokedError,Z as assertion,xe as createGrantSync,ee as machineRevokedMessage,te as mintDirectoryToken,Se as requestGrantSync,y as runtimeClient,Ee as runtimeId};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
2
|
-
sub, grant_id, scopes_json, cwd, profile_id, app FROM nodes WHERE node_id = ?`).get(e);if(!a||!l)throw new Error(`no node ${e}`);const{grantee:p,sub:c,grant_id:d,scopes_json:f,cwd:
|
|
3
|
-
WHERE i.scheme = 'profile' AND i.external_id = ?`).get(e)??await
|
|
1
|
+
var D=Object.defineProperty;var s=(o,e)=>D(o,"name",{value:e,configurable:!0});import{coveredByAny as _,isSandboxedNode as B}from"../../shared/env.js";import{projectPaths as J}from"../../api/dto/profiles.js";import{existsSync as b}from"node:fs";import{CrtrError as P}from"../errors.js";import{getCachedProfile as x}from"../scoped-state/person-store.js";import{parseScope as A}from"@north-light/identity";import{isNamespaceOwner as N,ownerScopes as F}from"../grants/owner.js";import{activeGrant as L,grantFor as M,runtimeScope as k}from"../grants/mirror.js";import{withCanvasWrite as G}from"../canvas/db.js";import{ApiError as q}from"../../api/errors.js";import{pluginAppToken as U}from"../secrets.js";import{loadExactProfileManifest as Y}from"../profiles/manifest.js";import{ensureOwner as T,getById as z,nodeObject as K,ownerForGrantee as Q,profileHandle as V}from"./objects.js";import{personId as X,personIdAsync as Z}from"../canvas/person.js";import{OBJECT_TYPE as I}from"../permissions/builtin.js";import{warmCheckoutDirs as H}from"../checkout-identities.js";import{fillProfileProjectRepo as ee}from"../profiles/manifest.js";import{emitEvent as oe}from"../events/emit.js";import{isCloudRole as R}from"../canvas/person-state.js";import{loadReadAccess as ne,readableAmong as te,prefetchRepoReads as re,reposForCwd as ae,warmCheckoutIdentities as v}from"./repo-sync/repos.js";async function W(o,e,n,r,t,a){const l=n===null?[]:t.projects(n),p=l.length===0?void 0:a??await Z(),c=p===void 0?void 0:await ne(o,p);c!==void 0&&p!==void 0&&await re(o,p,[e,...l.flatMap(i=>i.path!==void 0&&(R()||b(i.path))?[i.path]:[])],c);const d=l.flatMap(i=>i.repo===void 0?[]:[i.repo]),f=p===void 0?new Set:await te(o,p,d,c),h=await r(e,a,c),w=new Set(h.map(i=>i.repo.id)),E=[],m=[];for(const i of l){if(i.repo!==void 0&&!w.has(i.repo)){const u=await t.object(i.repo);u!==null&&u.type==="repo"&&u.deleted_at===null&&f.has(u.id)&&(w.add(u.id),E.push(u))}if(i.path===void 0||!R()&&!b(i.path))continue;let O;try{O=await r(i.path,a,c)}catch(u){if(u instanceof P&&u.code==="git-lookup-failed")continue;throw u}for(const u of O)w.has(u.repo.id)||(w.add(u.repo.id),E.push(u.repo),m.push(u))}return{repos:h.map(i=>i.repo),checkouts:h,projectRepos:E,projectCheckouts:m}}s(W,"viewRepos");async function Le(o,e){const n=await o.prepare("SELECT cwd, profile_id FROM nodes WHERE node_id = ?").get(e);if(n===void 0)return;const r=n.profile_id?J(j(o).projects(n.profile_id)):[];if(R()){await se(n.profile_id,[n.cwd,...r]);return}await v(n.cwd);for(const t of r)b(t)&&await v(t)}s(Le,"warmNodeRepos");async function se(o,e){if(await H(o,e),o!==null){for(const n of x(o)?.manifest.projects??[])if(!(n.path===void 0||n.repo!==void 0))try{const r=(await G(async t=>await ae(t,n.path)))[0];r!==void 0&&await ee(o,n.path,r.id)}catch(r){oe({level:"warn",event:"repo.identify.fill_failed",error:r,fields:{profile:o,path:n.path}})}}}s(se,"warmCloudNodeCheckouts");async function Me(o,e,n){if(!R()){for(const t of n)await v(t);return}const r=e===void 0?void 0:await o.prepare("SELECT profile_id FROM nodes WHERE node_id = ?").get(e);await H(r?.profile_id,n)}s(Me,"warmNodeDirs");async function Te(o,e,n){if(e.class==="anonymous")throw new Error("a publish token cannot read as a principal");if(e.class==="person")return{class:"person",person:await C(o)};if(e.class==="app")return{class:"app",app:await S(o,e.app),scopes:e.scopes,...e.sub===void 0?{}:{sub:e.sub}};if(e.class==="machine"||e.class==="import")throw new Error(`a ${e.class} token cannot read as a principal`);if(e.class==="forwarded"){if(e.actor.kind==="person")return{class:"person",person:await C(o)};const p=await M(e.actor.app,e.sub),c=p?p.resolved:N(e.actor.app,e.sub)?F(e.actor.app):null;if(c===null)throw new q(403,"app_not_granted",`${e.actor.app} holds no active grant for ${e.sub} on this machine`);const d=e.actor.node_scopes;return{class:"app",app:await S(o,e.actor.app),sub:e.sub,place:e.actor.place,launched:d,scopes:d===null?c:d.filter(f=>_(c,f))}}if(e.class==="cron"){const p=e.grant?(await L(e.grant))?.resolved??[]:[],c=e.scopes;return{class:"app",app:await S(o,e.app),scopes:c===null?p:c.filter(d=>_(p,d)),launched:c,place:{run:e.origin_run??"",isolated:e.isolated}}}const r=j(o),t=await K(o,e.node),a=await o.prepare("SELECT cwd, profile_id, app FROM nodes WHERE node_id = ?").get(e.node),l=a.app===null?null:await r.object(a.app);if(!l)throw new Error(`node ${e.node} has no app`);return{class:"node",node:t,app:l,scopes:await $(e.app,e.sub,e.grant,e.scopes,r),launched:e.scopes,cwd:a.cwd,...await W(o,a.cwd,a.profile_id,n,r,e.sub||void 0),profile:a.profile_id===null?null:await r.profile(a.profile_id,l)}}s(Te,"readerFor");async function pe(o,e,n,r=j(o),t=!1){const a=await o.prepare("SELECT o.* FROM objects o WHERE o.id = ? AND o.type = 'node'").get(e),l=await o.prepare(`SELECT (SELECT external_id FROM identities WHERE object = nodes.app) AS grantee,
|
|
2
|
+
sub, grant_id, scopes_json, cwd, profile_id, app FROM nodes WHERE node_id = ?`).get(e);if(!a||!l)throw new Error(`no node ${e}`);const{grantee:p,sub:c,grant_id:d,scopes_json:f,cwd:h,profile_id:w,app:E}=l,m=E===null?null:await r.object(E);if(!m)throw new Error(`node ${e} has no app`);const i=f===null?null:JSON.parse(f);return{class:"node",node:a,app:m,scopes:await $(p,c??"",d,i,r,t),launched:i,cwd:h,...await W(o,h,w,n,r,c||void 0),profile:w===null?null:await r.profile(w,m)}}s(pe,"readerForNode");class ce extends Error{static{s(this,"NoOwningAppError")}constructor(){super("no terminal app or person object"),this.name="NoOwningAppError"}}async function He(o,e,n=async()=>[],r=j(o)){const t=await o.prepare("SELECT envelope_json FROM peer_stubs WHERE object = ?").get(e.id);if(t!==void 0)return await ie(o,e,t.envelope_json===null?null:JSON.parse(t.envelope_json),r);if(e.type==="node")return await pe(o,e.id,n,r,!0);const a=e.owner===null?null:await r.object(e.owner);if(!a)throw new Error(`watcher ${e.id} has no owner`);const p=(a.type==="app"?a:a.type==="profile"&&a.owner!==null?await r.object(a.owner):null)??await o.prepare("SELECT o.* FROM identities i JOIN objects o ON o.id = i.object WHERE i.external_id = 'app:terminal' AND i.scheme = 'app'").get()??await o.prepare("SELECT * FROM objects WHERE type = 'person' AND name = 'user' AND home_machine IS NULL").get();if(!p)throw new ce;const c=(await o.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'app'").get(p.id))?.external_id??"app:terminal",d=k(),f=await o.prepare(`SELECT sub, resolved_scopes_json FROM grants WHERE grantee = ? AND status = 'active'${d.sql}`).all(c,...d.args),h=s(g=>JSON.parse(g.resolved_scopes_json).filter(y=>y.mode==="always").map(y=>A(y.scope)),"always"),w=f.length>1&&(a.type==="app"||a.type==="repo")?new Set((await o.prepare("SELECT subject_id FROM relations WHERE resource_type = ? AND resource_id = ? AND relation = 'acts_for' AND subject_type = 'user'").all(I,a.type==="repo"?a.id:e.id)).map(g=>g.subject_id)):null,E=w===null?void 0:f.find(g=>w.has(g.sub.replace(/^user:/,"")))?.sub,m=E===void 0?null:await r.grantFor(c,E),i=a.type==="person"?null:f.length===0?r.pluginScopes(c):f.length===1?h(f[0]):m?.resolved??null,u=(a.type==="person"?(await o.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'user'").get(a.id))?.external_id:void 0)??(f.length===1?f[0].sub:m?.sub);return{class:"object",object:e,node:e,owner:a,app:p,scopes:i,...u===void 0?{}:{sub:u},repos:a.type==="repo"?[a]:[]}}s(He,"readerForObject");async function We(o,e,n){const r=(await o.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'app'").get(e.id))?.external_id;if(r===void 0)return null;const t=await o.prepare("SELECT resolved_scopes_json FROM grants WHERE grantee = ? AND status = 'active'").all(r);return t.length===0?n.pluginScopes(r):t.length>1?null:JSON.parse(t[0].resolved_scopes_json).filter(a=>a.mode==="always").map(a=>A(a.scope))}s(We,"appScopesNow");async function ie(o,e,n,r){const t=await C(o);if(n!==null&&n.app===null)return{class:"object",object:e,node:e,owner:t,app:t,scopes:null,repos:[]};const a=n?.app==null?null:await S(o,n.app),l=n?.app==null?null:await r.grantFor(n.app,n.sub),p=l!==null?l.resolved:n?.app!=null&&N(n.app,n.sub)?F(n.app):null,c=n===null||p===null?null:n.node_scopes===null?p:n.node_scopes.filter(f=>_(p,f)),d=a??(e.owner===null?t:await r.object(e.owner)??t);return{class:"object",object:e,node:e,owner:d,app:d,scopes:c,launched:n?.node_scopes??null,repos:[],...n?.place==null?{}:{place:n.place}}}s(ie,"readerForStub");function j(o){return{grantById:L,grantFor:M,pluginScopes:s(e=>U(e.replace(/^app:/,""))?.scopes??null,"pluginScopes"),object:s(async e=>await z(o,e),"object"),profile:s(async(e,n)=>await le(o,e,n),"profile"),projects:s(e=>B()?[]:x(e)?.manifest.projects??[],"projects")}}s(j,"liveLookups");function $e(o){const e=j(o),n=new Map,r=s((t,a)=>(n.has(t)||n.set(t,a()),n.get(t)),"memo");return{grantById:s(t=>r(`g\0${t}`,()=>e.grantById(t)),"grantById"),grantFor:s((t,a)=>r(`a\0${t}\0${a}`,()=>e.grantFor(t,a)),"grantFor"),pluginScopes:s(t=>r(`t\0${t}`,()=>e.pluginScopes(t)),"pluginScopes"),object:s(async t=>await r(`o\0${t}`,async()=>await e.object(t)),"object"),profile:s(async(t,a)=>await r(`p\0${t}\0${a.id}`,async()=>await e.profile(t,a)),"profile"),projects:s(t=>r(`j\0${t}`,()=>e.projects(t)),"projects")}}s($e,"publishLookups");async function $(o,e,n,r,t,a=!1){const l=n?await t.grantById(n):await t.grantFor(o,e),p=l&&l.grantee===o?l.resolved:l===null&&n===null&&N(o,e)?F(o):null;if(p===null){if(a)return null;throw new Error(`the grant of ${o} is not active`)}return r===null?p:r.filter(c=>_(p,c))}s($,"nodeScopes");async function C(o){return await Q(o,X())}s(C,"personObject");async function S(o,e){return await T(o,"app","app",e,e.replace(/^app:/,""))}s(S,"appObject");async function le(o,e,n){return await o.prepare(`SELECT o.* FROM identities i JOIN objects o ON o.id = i.object
|
|
3
|
+
WHERE i.scheme = 'profile' AND i.external_id = ?`).get(e)??await T(o,"profile","profile",e,V(e,Y(e).manifest.name),n)}s(le,"profileObject");export{ce as NoOwningAppError,We as appScopesNow,j as liveLookups,le as profileObject,$e as publishLookups,Te as readerFor,pe as readerForNode,He as readerForObject,W as viewRepos,se as warmCloudNodeCheckouts,Me as warmNodeDirs,Le as warmNodeRepos};
|
|
@@ -8,7 +8,7 @@ export declare function checkSourcePerson(db: CanvasDb, target: string, source:
|
|
|
8
8
|
* (`crtr/group` relations). Returns rows dropped per table. */
|
|
9
9
|
export declare function checkStagedPersons(input: RewriteInput): Promise<Record<string, number>>;
|
|
10
10
|
/** After rewrite 2 and the drop: every reference from a staged row to a target row reaches a row the run's person owns or acts for (an app, a shipped
|
|
11
|
-
* document, the person's own object, an object with an `acts_for` fact for the person, an object this person's earlier run of the same install inserted,
|
|
11
|
+
* document, the person's own object, an object with an `acts_for` fact for the person, an object a group the person is a member of is granted (a repo document its team shares), an object this person's earlier run of the same install inserted,
|
|
12
12
|
* or anything below those that is not directly under an app), and no profile or grant the rows name belongs to another person.
|
|
13
13
|
*
|
|
14
14
|
* The earlier run's objects are the person's by construction, and a re-load must accept them: the drop step removes every staged document the target already
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var P=Object.defineProperty;var c=(n,t)=>P(n,"name",{value:t,configurable:!0});import{parseBlobKey as
|
|
2
|
-
UNION ALL SELECT 'grants' FROM ${
|
|
3
|
-
UNION ALL SELECT 'nodes' FROM ${
|
|
4
|
-
WHERE adapter_json::jsonb #>> '{principal,sub}' IS NOT NULL AND adapter_json::jsonb #>> '{principal,sub}' NOT IN (?, ?) LIMIT 5`,p,
|
|
5
|
-
WHERE m.table_name = 'objects' AND r.source_install_id = ? AND r.person = ? AND r.run_id <> ? AND r.state IN ('committed', 'done', 'failed')`,t.installId,t.person,t.runId)).flatMap(p=>J(p.inserted_keys).map(
|
|
6
|
-
AND ${f(
|
|
1
|
+
var P=Object.defineProperty;var c=(n,t)=>P(n,"name",{value:t,configurable:!0});import{parseBlobKey as w}from"../bundle/blob-keys.js";import{q as f}from"./catalog.js";import{decodeKeys as J}from"./copy.js";import{objectIdColumns as Y}from"./rewrite.js";import{ImportLaneError as F}from"./stage.js";const K=/^user:[A-Za-z0-9._-]+$/,C=c(n=>n.replace(/^user:/,""),"bare"),g=c((n,t)=>`${f(n)}.${f(t)}`,"sq"),N=c(async(n,t,...a)=>await n.prepareUncached(t).all(...a),"all");function T(n,t){return new F("bind","person_mismatch",n,t)}c(T,"mismatch");function se(n,t,a,p){if(n===t||n===a)return a;throw T(`${p} names ${n}, which is neither the bundle's person nor the importing person`,{where:p,value:n})}c(se,"boundSub");async function ne(n,t,a,p){if(!K.test(a))throw T(`the bundle's person ${JSON.stringify(a)} is not a user:<id> principal`,{where:"source.json person",value:a});if(a===p)return;const u=c(r=>g(t,r),"T"),o=await n.prepareUncached(`SELECT 'identities' AS tbl FROM ${u("identities")} WHERE scheme IN ('user', 'local-user') AND external_id = ?
|
|
2
|
+
UNION ALL SELECT 'grants' FROM ${u("grants")} WHERE sub = ? UNION ALL SELECT 'profiles' FROM ${u("profiles")} WHERE person = ?
|
|
3
|
+
UNION ALL SELECT 'nodes' FROM ${u("nodes")} WHERE sub = ? LIMIT 1`).get(a,a,a,a);if(o!==void 0)throw T(`the bundle's person ${a} is already a person in the target (${o.tbl}), not the importing person ${p}`,{where:`${o.tbl}`,value:a})}c(ne,"checkSourcePerson");const B=[["nodes","sub"],["crons","sub"],["grants","sub"],["profiles","person"],["charges","sub"],["limits","sub"],["audit_rows","sub"],["provider_approvals","sub"],["uploads","sub"],["files","sub"],["shares","sub"]],z=[["charges","payer"],["limits","payer"],["audit_rows","payer"],["audit_rows","grantee"],["charges","grantee"],["run_events","grantee"],["idempotency_keys","grantee"],["uploads","grantee"],["files","grantee"],["provider_approvals","grantee"],["profiles","grantee"],["crons","grantee"]];async function re(n){const{db:t,schema:a,sourcePerson:p,targetPerson:u}=n,o=c(s=>g(a,s),"S"),r=c((s,d)=>{throw T(`${s} names ${d.join(", ")}, who is neither the bundle's person ${p} nor the importing person ${u}`,{where:s,values:d})},"refuse");for(const[s,d]of B){const _=await N(t,`SELECT DISTINCT ${f(d)} AS v FROM ${o(s)} WHERE ${f(d)} IS NOT NULL AND ${f(d)} <> '' AND ${f(d)} NOT IN (?, ?) LIMIT 5`,p,u);_.length>0&&r(`${s}.${d}`,_.map($=>$.v))}for(const[s,d]of z){const _=await N(t,`SELECT DISTINCT ${f(d)} AS v FROM ${o(s)} WHERE ${f(d)} LIKE 'user:%' AND ${f(d)} NOT IN (?, ?) LIMIT 5`,p,u);_.length>0&&r(`${s}.${d}`,_.map($=>$.v))}const b=await N(t,`SELECT DISTINCT external_id AS v FROM ${o("identities")} WHERE scheme IN ('user', 'local-user') AND external_id NOT IN (?, ?) LIMIT 5`,p,u);b.length>0&&r("identities.external_id",b.map(s=>s.v));const h=await N(t,`SELECT DISTINCT adapter_json::jsonb #>> '{principal,sub}' AS v FROM ${o("daemon_actions")}
|
|
4
|
+
WHERE adapter_json::jsonb #>> '{principal,sub}' IS NOT NULL AND adapter_json::jsonb #>> '{principal,sub}' NOT IN (?, ?) LIMIT 5`,p,u);h.length>0&&r("daemon_actions principal.sub",h.map(s=>s.v));const l=await N(t,`SELECT DISTINCT subject_id AS v FROM ${o("relations")} WHERE relation = 'acts_for' AND subject_type = 'user' AND subject_id NOT IN (?, ?) LIMIT 5`,C(p),C(u));l.length>0&&r("relations acts_for subject",l.map(s=>s.v));const E=Number((await t.prepareUncached(`DELETE FROM ${o("relations")} WHERE resource_type = 'crtr/group'`).run()).changes);return E>0?{relations:E}:{}}c(re,"checkStagedPersons");async function G(n,t){return(await N(n,`SELECT m.inserted_keys FROM import_manifest m JOIN import_runs r ON r.run_id = m.run_id
|
|
5
|
+
WHERE m.table_name = 'objects' AND r.source_install_id = ? AND r.person = ? AND r.run_id <> ? AND r.state IN ('committed', 'done', 'failed')`,t.installId,t.person,t.runId)).flatMap(p=>J(p.inserted_keys).map(u=>u[0]))}c(G,"earlierImportedObjects");async function ae(n,t){const{db:a,schema:p,catalog:u,targetPerson:o}=n,r=await H(n,t);if(r.length>0)throw T(`the bundle refers to objects that are not ${o}'s: ${r.slice(0,10).map(b=>`${b.tbl}.${b.col}=${b.value}`).join(", ")}`,{references:r.slice(0,10)});await V(n)}c(ae,"checkStagedReferences");async function ie(n,t){const{db:a,schema:p,catalog:u}=n;if(!u.tables.has("messages"))return{};const o=c(s=>g(p,s),"S"),r=[...new Set((await H(n,t)).filter(s=>s.tbl==="messages").map(s=>s.value))];if(r.length===0)return{};const b="(object_id = ANY(?::text[]) OR actor_id = ANY(?::text[]))",h=`(SELECT message_id FROM ${o("messages")} WHERE ${b})`,l={};for(const[s,d]of[["deliveries","message_id"],["message_causes","message_id"]]){if(!u.tables.has(s))continue;const _=Number((await a.prepareUncached(`DELETE FROM ${o(s)} WHERE ${d} IN ${h}`).run(r,r)).changes);_>0&&(l[s]=_)}const E=Number((await a.prepareUncached(`DELETE FROM ${o("messages")} WHERE ${b}`).run(r,r)).changes);return E>0&&(l.messages=E),l}c(ie,"dropRefusedMessages");async function H(n,t){const{db:a,schema:p,target:u,catalog:o,targetPerson:r}=n,b=c(_=>g(p,_),"S"),h=c(_=>g(u,_),"T"),l=C(r);await a.exec(`CREATE TABLE ${b("_refs")} (tbl text NOT NULL, col text NOT NULL, value text NOT NULL)`);const E=[];for(const[_,$]of Y(o))if(!(!o.tables.has(_)||_==="relations"))for(const m of $)!(_==="nodes"&&m==="profile_id")&&!(_==="crons"&&m==="profile")&&E.push([_,m,""]);E.push(["relations","resource_id","WHERE resource_type = 'crtr/object'"]);for(const[_,$,m]of E)await a.prepareUncached(`INSERT INTO ${b("_refs")} SELECT ?, ?, ${f($)}::text FROM ${b(_)} ${m===""?"WHERE":`${m} AND`} ${f($)} IS NOT NULL
|
|
6
|
+
AND ${f($)}::text NOT IN (SELECT id FROM ${b("objects")}) AND ${f($)}::text IN (SELECT id FROM ${h("objects")})`).run(_,$);const s=await G(a,t),d=await N(a,`WITH RECURSIVE chain(start, id) AS (
|
|
7
7
|
SELECT DISTINCT value, value FROM ${b("_refs")}
|
|
8
8
|
UNION SELECT c.start, o.owner FROM chain c JOIN ${h("objects")} o ON o.id = c.id JOIN ${h("objects")} up ON up.id = o.owner AND up.type <> 'app'),
|
|
9
9
|
ok(id) AS (
|
|
@@ -11,7 +11,10 @@ var P=Object.defineProperty;var c=(n,t)=>P(n,"name",{value:t,configurable:!0});i
|
|
|
11
11
|
UNION SELECT d.object FROM ${h("documents")} d WHERE d.source_path IS NOT NULL
|
|
12
12
|
UNION SELECT i.object FROM ${h("identities")} i WHERE i.scheme IN ('user', 'local-user') AND i.external_id = ?
|
|
13
13
|
UNION SELECT r.resource_id FROM ${h("relations")} r WHERE r.resource_type = 'crtr/object' AND r.relation = 'acts_for' AND r.subject_type = 'user' AND r.subject_id = ?
|
|
14
|
+
UNION SELECT r.resource_id FROM ${h("relations")} r JOIN ${h("relations")} m ON m.resource_type = 'crtr/group' AND m.relation = 'member' AND m.resource_id = r.subject_id
|
|
15
|
+
AND m.subject_type = 'user' AND m.subject_id = ?
|
|
16
|
+
WHERE r.resource_type = 'crtr/object' AND r.relation IN ('reader', 'editor', 'messenger', 'user_of') AND r.subject_type = 'crtr/group' AND r.subject_relation = 'member'
|
|
14
17
|
UNION SELECT unnest(?::text[]))
|
|
15
18
|
SELECT r.tbl, r.col, r.value FROM ${b("_refs")} r
|
|
16
|
-
WHERE NOT EXISTS (SELECT 1 FROM chain c JOIN ok ON ok.id = c.id WHERE c.start = r.value)`,r,l,s);return await a.exec(`DROP TABLE ${b("_refs")}`),
|
|
17
|
-
JOIN ${r("grants")} g ON g.id = d.adapter_json::jsonb #>> '{principal,grant_id}' WHERE g.sub <> ? LIMIT 5`,
|
|
19
|
+
WHERE NOT EXISTS (SELECT 1 FROM chain c JOIN ok ON ok.id = c.id WHERE c.start = r.value)`,r,l,l,s);return await a.exec(`DROP TABLE ${b("_refs")}`),d}c(H,"foreignReferences");async function V(n){const{db:t,schema:a,target:p,targetPerson:u}=n,o=c(l=>g(a,l),"S"),r=c(l=>g(p,l),"T"),b=[["nodes","profile_id"],["crons","profile"],["profiles","id"]];for(const[l,E]of b){const s=await N(t,`SELECT DISTINCT s.${f(E)} AS v FROM ${o(l)} s JOIN ${r("profiles")} p ON p.id = s.${f(E)} WHERE p.person <> ? LIMIT 5`,u);if(s.length>0)throw T(`${l}.${E} names profiles that belong to another person: ${s.map(d=>d.v).join(", ")}`,{where:`${l}.${E}`,values:s.map(d=>d.v)})}for(const[l,E]of[["nodes","grant_id"],["crons","grant_id"]]){const s=await N(t,`SELECT DISTINCT s.${f(E)} AS v FROM ${o(l)} s JOIN ${r("grants")} g ON g.id = s.${f(E)} WHERE g.sub <> ? LIMIT 5`,u);if(s.length>0)throw T(`${l}.${E} names grants that belong to another person: ${s.map(d=>d.v).join(", ")}`,{where:`${l}.${E}`,values:s.map(d=>d.v)})}const h=await N(t,`SELECT DISTINCT d.adapter_json::jsonb #>> '{principal,grant_id}' AS v FROM ${o("daemon_actions")} d
|
|
20
|
+
JOIN ${r("grants")} g ON g.id = d.adapter_json::jsonb #>> '{principal,grant_id}' WHERE g.sub <> ? LIMIT 5`,u);if(h.length>0)throw T(`a queued action names grants that belong to another person: ${h.map(l=>l.v).join(", ")}`,{where:"daemon_actions principal.grant_id",values:h.map(l=>l.v)})}c(V,"checkStagedProfilesAndGrants");const k=c((n,t)=>new F("bind","bundle_invalid",n,t),"bundleInvalid");async function ce(n){const{db:t,schema:a,target:p,targetPerson:u}=n,o=c(e=>g(a,e),"S"),r=new Set((await N(t,`SELECT node_id AS v FROM ${o("nodes")}`)).map(e=>e.v)),b=await N(t,`SELECT conversation_id, seq::text AS seq, blob_key FROM ${o("conversation_parts")}`),h=await N(t,`SELECT run_id, path, blob_key FROM ${o("upload_uses")} WHERE blob_key IS NOT NULL`),l=await N(t,`SELECT object, output_key FROM ${o("jobs")} WHERE output_key IS NOT NULL`),E=c(e=>e.split("/")[1]??"","jobOwner"),s=c((e,i,S,O)=>{const D=w(i);if(D===null||D.kind!==S||O!==void 0&&i!==O)throw k(`${e} holds ${JSON.stringify(i)}, which is not a ${S} blob key${O===void 0?"":` of the shape ${O}`}`,{where:e,value:i})},"shaped");for(const e of b)if(s("conversation_parts.blob_key",e.blob_key,"conversation"),e.blob_key.split("/")[2]!==e.conversation_id)throw k(`conversation_parts.blob_key ${e.blob_key} is not under its conversation ${e.conversation_id}`,{where:"conversation_parts.blob_key",value:e.blob_key});for(const e of h)s("upload_uses.blob_key",e.blob_key,"attachment");for(const e of l)s("jobs.output_key",e.output_key,"job",`jobs/${E(e.output_key)}/${e.object}/output`);const d=new Set;for(const{blob_key:e}of b){const i=w(e);i!==null&&i.kind==="conversation"&&!r.has(i.owner)&&d.add(i.owner)}for(const{blob_key:e}of h){const i=w(e);i!==null&&i.kind==="attachment"&&!r.has(i.owner)&&d.add(i.owner)}for(const{output_key:e}of l)r.has(E(e))||d.add(E(e));const _=new Map((d.size===0?[]:await N(t,`SELECT node_id, sub FROM ${g(p,"nodes")} WHERE node_id = ANY(?::text[])`,[...d])).map(e=>[e.node_id,e.sub])),$=c(e=>r.has(e)||_.get(e)===u,"held"),m=c(e=>!r.has(e)&&!_.has(e),"gone"),A={},I=c((e,i)=>{i>0&&(A[e]=(A[e]??0)+i)},"count"),R=c(async(e,...i)=>Number((await t.prepareUncached(e).run(...i)).changes),"drop"),W=new Set((await N(t,`SELECT DISTINCT session_id AS v FROM ${o("sessions")} WHERE session_id IS NOT NULL`)).map(e=>e.v)),L=new Map;for(const{conversation_id:e,blob_key:i}of b){const S=w(i),O=L.get(e);O!==null&&(S===null||S.kind!=="conversation"?L.set(e,null):L.set(e,[...O??[],S.owner]))}const v=[...L].filter(([e,i])=>i!==null&&!W.has(e)&&i.every(m)).map(([e])=>e);v.length>0&&(I("conversation_parts",await R(`DELETE FROM ${o("conversation_parts")} WHERE conversation_id = ANY(?::text[])`,v)),I("conversation_entries",await R(`DELETE FROM ${o("conversation_entries")} WHERE conversation_id = ANY(?::text[])`,v)));const U=new Set(v),j=c((e,i)=>{const S=w(i).owner;if(!$(S))throw T(`${e} holds ${i}, which belongs to node ${S}, who is not in the bundle`,{where:e,value:i})},"owned");for(const e of b)U.has(e.conversation_id)||j("conversation_parts.blob_key",e.blob_key);const y=h.filter(e=>{const i=w(e.blob_key);return i!==null&&i.kind==="attachment"&&m(i.owner)&&!r.has(e.run_id)});y.length>0&&I("upload_uses",await R(`DELETE FROM ${o("upload_uses")} u USING unnest(?::text[], ?::text[]) d(run_id, path) WHERE u.run_id = d.run_id AND u.path = d.path`,y.map(e=>e.run_id),y.map(e=>e.path)));const x=new Set(y);for(const e of h)x.has(e)||j("upload_uses.blob_key",e.blob_key);const M=l.filter(e=>e.output_key===`jobs/${E(e.output_key)}/${e.object}/output`&&m(E(e.output_key)));M.length>0&&I("jobs",await R(`DELETE FROM ${o("jobs")} WHERE object = ANY(?::text[])`,M.map(e=>e.object)));const q=new Set(M);for(const e of l)q.has(e)||j("jobs.output_key",e.output_key);return A}c(ce,"checkStagedBlobKeys");async function ue(n){const{db:t,schema:a}=n;for(const p of await N(t,`SELECT request_id, request_dir, presentation_dir, file FROM ${g(a,"human_requests")}`))for(const u of["request_dir","presentation_dir","file"]){const o=p[u];if(o===null||!o.startsWith("requests/"))continue;const r=w(o.includes("/",9)?o:`${o}/x`);if(r===null||r.kind!=="request")throw k(`human_requests.${u} holds ${JSON.stringify(o)}, which is not a request blob key`,{where:`human_requests.${u}`,value:o});if(r.owner!==p.request_id)throw T(`human_requests.${u} of ${p.request_id} holds ${o}, which belongs to request ${r.owner}`,{where:`human_requests.${u}`,value:o})}}c(ue,"checkStagedRequestKeys");export{se as boundSub,ne as checkSourcePerson,ce as checkStagedBlobKeys,re as checkStagedPersons,ae as checkStagedReferences,ue as checkStagedRequestKeys,ie as dropRefusedMessages};
|
|
@@ -18,16 +18,16 @@ export type PayerCall = (
|
|
|
18
18
|
route: 'subscription' | 'key';
|
|
19
19
|
sub: string;
|
|
20
20
|
}
|
|
21
|
-
/** A tool call over HTTP: the outbound token's `payer` claim
|
|
21
|
+
/** A tool call over HTTP: the outbound token's `payer` claim, any principal. It is always `bill`; `sub` is used only when the claim is absent. */
|
|
22
22
|
| {
|
|
23
23
|
call: 'tool';
|
|
24
|
-
tokenPayer: string;
|
|
24
|
+
tokenPayer: string | null | undefined;
|
|
25
25
|
sub: string;
|
|
26
26
|
}
|
|
27
|
-
/** The payer of a node's model calls, for the start check:
|
|
27
|
+
/** The payer of a node's model calls, for the start check: the grant's principal payer. With none, the grantee's namespace owner when `sub` is in that namespace, else `sub`. */
|
|
28
28
|
| {
|
|
29
29
|
call: 'start';
|
|
30
|
-
grantPayer:
|
|
30
|
+
grantPayer: string | null | undefined;
|
|
31
31
|
sub: string;
|
|
32
32
|
grantee: string;
|
|
33
33
|
}) & {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var t=Object.defineProperty;var r=(n,e)=>t(n,"name",{value:e,configurable:!0});function
|
|
1
|
+
var t=Object.defineProperty;var r=(n,e)=>t(n,"name",{value:e,configurable:!0});import{endpointPays as i}from"../grants/mirror.js";import{isNamespaceOwner as u}from"../grants/owner.js";function a(n){const e=o(n);return n.environmentPayer?{payer:n.environmentPayer,funding:e.funding}:e}r(a,"payerOf");function o(n){switch(n.call){case"model":return n.route==="endpoint"?{payer:n.grantee,funding:"endpoint"}:{payer:n.sub,funding:n.route};case"tool":return{payer:n.tokenPayer||n.sub,funding:"bill"};case"start":return n.grantPayer?{payer:n.grantPayer,funding:i({payer:n.grantPayer})?"endpoint":"bill"}:{payer:u(n.grantee,n.sub)?n.grantee:n.sub,funding:"bill"}}}r(o,"fundedBy");export{a as payerOf};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var h=Object.defineProperty;var s=(e,r)=>h(e,"name",{value:r,configurable:!0});import{defaultModelLaddersConfig as b}from"../../types.js";import{MODEL_STRENGTHS as w,stripThinkingSuffix as u}from"../runtime/model-selection.js";import{modelTokenStrength as O}from"../runtime/launch.js";import{RunError as d}from"../runs/operations.js";import{grantRecord as
|
|
1
|
+
var h=Object.defineProperty;var s=(e,r)=>h(e,"name",{value:r,configurable:!0});import{defaultModelLaddersConfig as b}from"../../types.js";import{MODEL_STRENGTHS as w,stripThinkingSuffix as u}from"../runtime/model-selection.js";import{modelTokenStrength as O}from"../runtime/launch.js";import{RunError as d}from"../runs/operations.js";import{endpointPays as x,grantRecord as R}from"../grants/mirror.js";const o=w;function g(e,r){const t=o.indexOf(r);return o.filter(n=>e.rungs[n]!==void 0).sort((n,i)=>Math.abs(o.indexOf(n)-t)-Math.abs(o.indexOf(i)-t)||o.indexOf(n)-o.indexOf(i)).map(n=>({strength:n,model:e.rungs[n]}))}s(g,"rungsByDistance");function l(e,r){const t=g(e,r)[0];if(t===void 0)throw new d(404,"model_unavailable","the app's inference endpoint declares no rung");return t}s(l,"rungAt");function p(e,r,t=!1){if(r===void 0||r==="")return l(e,"strong");const n=O(r)??void 0;if(n!==void 0)return l(e,n);const i=u(r),f=o.find(a=>e.rungs[a]===i);if(f!==void 0)return{strength:f,model:`${e.rungs[f]}${t?r.slice(i.length):""}`};if(t)throw new d(400,"substitution_refused",`model '${r}' is not one of this app's inference rungs`);const c=b(),m=[...Object.entries(c.anthropic),...Object.entries(c.openai)].find(([,a])=>u(a)===i);return l(e,m?.[0]??"strong")}s(p,"resolveAppRung");function v(e,r,t=!1){const n=p(e,r,t);if(t)return[n];const i=g(e,n.strength).filter(f=>f.strength!==n.strength);return[n,...i]}s(v,"appCandidates");async function y(e,r,t=!1){const n=e?await R(e):null;if(!n||!x(n))return null;if(!n.inference_endpoint)throw new d(404,"model_unavailable",`${n.grantee} is app-paid but its grant carries no inference endpoint`);const i=p(n.inference_endpoint,r,t);return t?i:{...i,model:u(i.model)}}s(y,"appRungForGrant");export{v as appCandidates,y as appRungForGrant,p as resolveAppRung,l as rungAt};
|