@north-light/cli 0.3.759 → 0.3.760

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/api/error-codes.d.ts +5 -0
  4. package/dist/api/error-codes.js +1 -1
  5. package/dist/builtin-memory/crouter-sdk/release-notes.md +4 -0
  6. package/dist/core/command-plugins/caller-header.d.ts +3 -1
  7. package/dist/core/command-plugins/caller-header.js +1 -1
  8. package/dist/core/grants/owner.d.ts +2 -0
  9. package/dist/core/grants/owner.js +1 -1
  10. package/dist/core/graph/reader.d.ts +5 -0
  11. package/dist/core/graph/reader.js +3 -3
  12. package/dist/core/graph/types.d.ts +2 -0
  13. package/dist/core/permissions/evaluator.js +2 -2
  14. package/dist/core/providers/call.js +1 -1
  15. package/dist/core/providers/errors.js +1 -1
  16. package/dist/core/providers/mint.d.ts +19 -0
  17. package/dist/core/providers/mint.js +1 -1
  18. package/dist/daemon/api/handlers/memory.js +5 -5
  19. package/dist/daemon/api/handlers/plugin-app-token.js +1 -1
  20. package/dist/daemon/api/reader.d.ts +1 -1
  21. package/dist/daemon/api/reader.js +1 -1
  22. package/docs/sdk/release-notes.md +4 -0
  23. package/package.json +3 -3
  24. package/packages/crouter-api/dist/api/contract.js +1 -1
  25. package/packages/crouter-api/dist/api/error-codes.js +2 -0
  26. package/packages/crouter-api/dist/core/command-plugins/caller-header.js +2 -2
  27. package/packages/crouter-api/dist/core/grants/owner.js +6 -0
  28. package/packages/crouter-api/dist/core/graph/reader.js +15 -1
  29. package/packages/crouter-api/dist/core/permissions/evaluator.js +2 -0
  30. package/packages/crouter-api/dist/core/providers/call.js +11 -5
  31. package/packages/crouter-api/dist/core/providers/errors.js +1 -0
  32. package/packages/crouter-api/dist/core/providers/mint.js +58 -29
  33. package/packages/crouter-api/dist/daemon/api/reader.js +10 -2
  34. package/packages/crouter-api/package.json +1 -1
  35. package/packages/crouter-identity/package.json +1 -1
  36. package/packages/crouter-plugin/package.json +3 -3
  37. package/runtime.lock.json +14 -14
@@ -1,5 +1,5 @@
1
1
  /** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
2
- export declare const CONTRACT_LEVEL = "1.80";
2
+ export declare const CONTRACT_LEVEL = "1.81";
3
3
  /** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
4
4
  export declare const REQUIRED_CONTRACT_HEADER = "Crouter-Required-Contract";
5
5
  /** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
@@ -1 +1 @@
1
- var c=Object.defineProperty;var e=(r,t)=>c(r,"name",{value:t,configurable:!0});const f="1.80",i="Crouter-Required-Contract",p="Crouter-Contract";function l(r){const t=/^(\d+)\.(\d+)$/.exec(r.trim());return t===null?null:{major:Number(t[1]),minor:Number(t[2])}}e(l,"parseContractLevel");function a(r){return r==null?[]:r.split(",").map(t=>l(t)).filter(t=>t!==null)}e(a,"parseServedContracts");function s(r,t){const n=l(r);return n===null?!1:(typeof t=="string"||t===null||t===void 0?a(t):t).some(u=>u.major===n.major&&u.minor>=n.minor)}e(s,"contractSatisfies");function C(r,t,n={}){if(r===void 0)return null;if(l(r)===null)return{status:400,code:"invalid_request",param:i,message:`${i} must be a contract level like 1.0.`};if(s(r,t))return null;const o=r.trim();return{status:426,code:"runtime_version_unsupported",message:t===null||a(t).length===0?`The runtime did not name its contract level; the caller requires contract ${o} or later. Roll the runtime forward.`:`The runtime serves contract ${t}; the caller requires contract ${o} or later within the same major. Roll the runtime forward, or pin an SDK whose crouterContract the runtime serves.`,details:{sdk_version:(n.legacyMinimum??"").trim(),runtime_version:n.runtimeVersion??null,required_contract:o,runtime_contract:t}}}e(C,"contractRefusal");export{p as CONTRACT_HEADER,f as CONTRACT_LEVEL,i as REQUIRED_CONTRACT_HEADER,C as contractRefusal,s as contractSatisfies,l as parseContractLevel,a as parseServedContracts};
1
+ var c=Object.defineProperty;var e=(r,t)=>c(r,"name",{value:t,configurable:!0});const f="1.81",i="Crouter-Required-Contract",p="Crouter-Contract";function l(r){const t=/^(\d+)\.(\d+)$/.exec(r.trim());return t===null?null:{major:Number(t[1]),minor:Number(t[2])}}e(l,"parseContractLevel");function a(r){return r==null?[]:r.split(",").map(t=>l(t)).filter(t=>t!==null)}e(a,"parseServedContracts");function s(r,t){const n=l(r);return n===null?!1:(typeof t=="string"||t===null||t===void 0?a(t):t).some(u=>u.major===n.major&&u.minor>=n.minor)}e(s,"contractSatisfies");function C(r,t,n={}){if(r===void 0)return null;if(l(r)===null)return{status:400,code:"invalid_request",param:i,message:`${i} must be a contract level like 1.0.`};if(s(r,t))return null;const o=r.trim();return{status:426,code:"runtime_version_unsupported",message:t===null||a(t).length===0?`The runtime did not name its contract level; the caller requires contract ${o} or later. Roll the runtime forward.`:`The runtime serves contract ${t}; the caller requires contract ${o} or later within the same major. Roll the runtime forward, or pin an SDK whose crouterContract the runtime serves.`,details:{sdk_version:(n.legacyMinimum??"").trim(),runtime_version:n.runtimeVersion??null,required_contract:o,runtime_contract:t}}}e(C,"contractRefusal");export{p as CONTRACT_HEADER,f as CONTRACT_LEVEL,i as REQUIRED_CONTRACT_HEADER,C as contractRefusal,s as contractSatisfies,l as parseContractLevel,a as parseServedContracts};
@@ -39,6 +39,11 @@ export declare const errorCodes: {
39
39
  readonly status: 403;
40
40
  readonly retryable: false;
41
41
  };
42
+ readonly not_granted: {
43
+ readonly type: "permission_error";
44
+ readonly status: 403;
45
+ readonly retryable: false;
46
+ };
42
47
  readonly owner_only: {
43
48
  readonly type: "permission_error";
44
49
  readonly status: 403;
@@ -1 +1 @@
1
- const e={unauthorized:{type:"authentication_error",status:401,retryable:!1},machine_revoked:{type:"authentication_error",status:401,retryable:!1},grant_revoked:{type:"authentication_error",status:401,retryable:!1},grant_removed:{type:"authentication_error",status:401,retryable:!1},grant_suspended:{type:"authentication_error",status:401,retryable:!1},refresh_token_expired:{type:"authentication_error",status:401,retryable:!1},refresh_token_reused:{type:"authentication_error",status:401,retryable:!1},scope_missing:{type:"permission_error",status:403,retryable:!1},owner_only:{type:"permission_error",status:403,retryable:!1},other_app_run:{type:"permission_error",status:403,retryable:!1},payer_not_app:{type:"permission_error",status:403,retryable:!1},approval_pending:{type:"permission_error",status:403,retryable:!1},user_denied:{type:"permission_error",status:403,retryable:!1},provider_refused:{type:"permission_error",status:403,retryable:!1},provider_not_connected:{type:"permission_error",status:403,retryable:!1},provider_setup_pending:{type:"permission_error",status:403,retryable:!1},question_pages_off:{type:"permission_error",status:403,retryable:!1},unsandboxed_machine:{type:"permission_error",status:403,retryable:!1},app_not_granted:{type:"permission_error",status:403,retryable:!1},isolated_run:{type:"permission_error",status:403,retryable:!1},provider_version_retired:{type:"permission_error",status:403,retryable:!1},invalid_scope:{type:"invalid_request_error",status:400,retryable:!1},invalid_request:{type:"invalid_request_error",status:400,retryable:!1},range_not_satisfiable:{type:"invalid_request_error",status:416,retryable:!1},not_here:{type:"invalid_request_error",status:404,retryable:!1},peer_version_too_old:{type:"invalid_request_error",status:426,retryable:!1},conflict:{type:"invalid_request_error",status:409,retryable:!1},model_sign_in_required:{type:"invalid_request_error",status:409,retryable:!1},invalid_argument:{type:"invalid_request_error",status:400,retryable:!1},machine_required:{type:"invalid_request_error",status:409,retryable:!1},device_offline:{type:"server_error",status:503,retryable:!0},device_timeout:{type:"server_error",status:504,retryable:!0},device_disconnected:{type:"server_error",status:503,retryable:!1},not_found:{type:"invalid_request_error",status:404,retryable:!1},model_unavailable:{type:"invalid_request_error",status:404,retryable:!1},upstream_model_unavailable:{type:"server_error",status:503,retryable:!0},substitution_refused:{type:"invalid_request_error",status:400,retryable:!1},idempotency_conflict:{type:"invalid_request_error",status:409,retryable:!1},run_settled:{type:"invalid_request_error",status:409,retryable:!1},cap_exhausted:{type:"rate_limit_error",status:402,retryable:!1},payment_refused:{type:"invalid_request_error",status:402,retryable:!1},concurrency_limit:{type:"rate_limit_error",status:429,retryable:!0},all_routes_exhausted:{type:"rate_limit_error",status:429,retryable:!0},provider_rate_limited:{type:"rate_limit_error",status:429,retryable:!0},rate_limited:{type:"rate_limit_error",status:429,retryable:!0},busy:{type:"rate_limit_error",status:429,retryable:!0},northlight_unreachable:{type:"server_error",status:503,retryable:!0},runtime_unreachable:{type:"server_error",status:503,retryable:!0},isolated_unavailable:{type:"server_error",status:503,retryable:!0},sandbox_unavailable:{type:"server_error",status:503,retryable:!1},runtime_starting:{type:"server_error",status:503,retryable:!0},runtime_provisioning:{type:"server_error",status:503,retryable:!0},provider_unavailable:{type:"server_error",status:503,retryable:!0},upstream_refused:{type:"server_error",status:502,retryable:!1},provider_bad_response:{type:"server_error",status:502,retryable:!1},service_unavailable:{type:"server_error",status:503,retryable:!0},not_implemented:{type:"server_error",status:501,retryable:!1},permission_error:{type:"permission_error",status:403,retryable:!1},storage_unavailable:{type:"server_error",status:503,retryable:!0},server_error:{type:"server_error",status:500,retryable:!0},server_failure:{type:"server_error",status:500,retryable:!1},wake_timeout:{type:"server_error",status:504,retryable:!0}};export{e as errorCodes};
1
+ const e={unauthorized:{type:"authentication_error",status:401,retryable:!1},machine_revoked:{type:"authentication_error",status:401,retryable:!1},grant_revoked:{type:"authentication_error",status:401,retryable:!1},grant_removed:{type:"authentication_error",status:401,retryable:!1},grant_suspended:{type:"authentication_error",status:401,retryable:!1},refresh_token_expired:{type:"authentication_error",status:401,retryable:!1},refresh_token_reused:{type:"authentication_error",status:401,retryable:!1},scope_missing:{type:"permission_error",status:403,retryable:!1},not_granted:{type:"permission_error",status:403,retryable:!1},owner_only:{type:"permission_error",status:403,retryable:!1},other_app_run:{type:"permission_error",status:403,retryable:!1},payer_not_app:{type:"permission_error",status:403,retryable:!1},approval_pending:{type:"permission_error",status:403,retryable:!1},user_denied:{type:"permission_error",status:403,retryable:!1},provider_refused:{type:"permission_error",status:403,retryable:!1},provider_not_connected:{type:"permission_error",status:403,retryable:!1},provider_setup_pending:{type:"permission_error",status:403,retryable:!1},question_pages_off:{type:"permission_error",status:403,retryable:!1},unsandboxed_machine:{type:"permission_error",status:403,retryable:!1},app_not_granted:{type:"permission_error",status:403,retryable:!1},isolated_run:{type:"permission_error",status:403,retryable:!1},provider_version_retired:{type:"permission_error",status:403,retryable:!1},invalid_scope:{type:"invalid_request_error",status:400,retryable:!1},invalid_request:{type:"invalid_request_error",status:400,retryable:!1},range_not_satisfiable:{type:"invalid_request_error",status:416,retryable:!1},not_here:{type:"invalid_request_error",status:404,retryable:!1},peer_version_too_old:{type:"invalid_request_error",status:426,retryable:!1},conflict:{type:"invalid_request_error",status:409,retryable:!1},model_sign_in_required:{type:"invalid_request_error",status:409,retryable:!1},invalid_argument:{type:"invalid_request_error",status:400,retryable:!1},machine_required:{type:"invalid_request_error",status:409,retryable:!1},device_offline:{type:"server_error",status:503,retryable:!0},device_timeout:{type:"server_error",status:504,retryable:!0},device_disconnected:{type:"server_error",status:503,retryable:!1},not_found:{type:"invalid_request_error",status:404,retryable:!1},model_unavailable:{type:"invalid_request_error",status:404,retryable:!1},upstream_model_unavailable:{type:"server_error",status:503,retryable:!0},substitution_refused:{type:"invalid_request_error",status:400,retryable:!1},idempotency_conflict:{type:"invalid_request_error",status:409,retryable:!1},run_settled:{type:"invalid_request_error",status:409,retryable:!1},cap_exhausted:{type:"rate_limit_error",status:402,retryable:!1},payment_refused:{type:"invalid_request_error",status:402,retryable:!1},concurrency_limit:{type:"rate_limit_error",status:429,retryable:!0},all_routes_exhausted:{type:"rate_limit_error",status:429,retryable:!0},provider_rate_limited:{type:"rate_limit_error",status:429,retryable:!0},rate_limited:{type:"rate_limit_error",status:429,retryable:!0},busy:{type:"rate_limit_error",status:429,retryable:!0},northlight_unreachable:{type:"server_error",status:503,retryable:!0},runtime_unreachable:{type:"server_error",status:503,retryable:!0},isolated_unavailable:{type:"server_error",status:503,retryable:!0},sandbox_unavailable:{type:"server_error",status:503,retryable:!1},runtime_starting:{type:"server_error",status:503,retryable:!0},runtime_provisioning:{type:"server_error",status:503,retryable:!0},provider_unavailable:{type:"server_error",status:503,retryable:!0},upstream_refused:{type:"server_error",status:502,retryable:!1},provider_bad_response:{type:"server_error",status:502,retryable:!1},service_unavailable:{type:"server_error",status:503,retryable:!0},not_implemented:{type:"server_error",status:501,retryable:!1},permission_error:{type:"permission_error",status:403,retryable:!1},storage_unavailable:{type:"server_error",status:503,retryable:!0},server_error:{type:"server_error",status:500,retryable:!0},server_failure:{type:"server_error",status:500,retryable:!1},wake_timeout:{type:"server_error",status:504,retryable:!0}};export{e as errorCodes};
@@ -15,6 +15,10 @@ Changes to `@north-light/sdk` that can change what an existing app sees. Newest
15
15
 
16
16
  `grant.get().resolved_scopes` may contain `<provider>:*` (for example `integrations:*`) in place of one entry per group. It means every group of that provider the grant may hold. Check a scope with the new `holds(resolved_scopes, scope)` export instead of comparing strings, because `integrations:gmail` is held while only `integrations:*` is listed. The directory sends this form only to a runtime that understands it.
17
17
 
18
+ ### `--as` acts for another principal
19
+
20
+ A node's provider call, plugin call and memory or object read can name `as`. From a node whose app namespace differs from `as`, crtrd exchanges the node's call token at the directory; the call runs with subject `as`, the node's app as grantee and actor. Reads cover only what the grant from `as` holds. A refusal is 403 `not_granted` (no grant from `as`) or `scope_missing`. `as` inside the node's own namespace needs no grant.
21
+
18
22
  ## 0.3.755
19
23
 
20
24
  ### An app can start runs in its own environment with no person
@@ -3,8 +3,10 @@ export interface CrtrCallerFields {
3
3
  machine?: string | undefined;
4
4
  profile?: string | undefined;
5
5
  run?: string | undefined;
6
+ /** The principal the call acts for (`--as`). */
7
+ as?: string | undefined;
6
8
  }
7
- /** `node=<id>; machine=<id>; profile=<id>; run=<id>`, in that order. A field
9
+ /** `node=<id>; machine=<id>; profile=<id>; run=<id>; as=<principal>`, in that order. A field
8
10
  * that is empty, or whose value holds `;`, `=`, CR or LF, is left out rather
9
11
  * than injected into the header. Returns '' when no field remains. */
10
12
  export declare function formatCrtrCaller(fields: CrtrCallerFields): string;
@@ -1 +1 @@
1
- var f=Object.defineProperty;var e=(o,n)=>f(o,"name",{value:n,configurable:!0});function s(o){const n=[];for(const r of["node","machine","profile","run"]){const t=o[r];typeof t!="string"||t===""||/[;=\r\n]/.test(t)||n.push(`${r}=${t}`)}return n.join("; ")}e(s,"formatCrtrCaller");export{s as formatCrtrCaller};
1
+ var s=Object.defineProperty;var e=(o,n)=>s(o,"name",{value:n,configurable:!0});function i(o){const n=[];for(const r of["node","machine","profile","run","as"]){const t=o[r];typeof t!="string"||t===""||/[;=\r\n]/.test(t)||n.push(`${r}=${t}`)}return n.join("; ")}e(i,"formatCrtrCaller");export{i as formatCrtrCaller};
@@ -5,3 +5,5 @@ export declare function isNamespaceOwner(grantee: string, sub: string): boolean;
5
5
  export declare function ownsWithoutRow(grantee: string, sub: string, grantId: string | null | undefined): boolean;
6
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
7
  export declare function ownerScopes(grantee: string): Scope[];
8
+ /** Whether two principals lie in one namespace; false when either does not parse. */
9
+ export declare function sameNamespace(a: string, b: string): boolean;
@@ -1 +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
+ var a=Object.defineProperty;var o=(e,n)=>a(e,"name",{value:n,configurable:!0});import{parsePrincipal as r,parseScope as c}from"@north-light/identity";import{pluginAppToken as s}from"../secrets.js";function i(e,n){const p=r(n);return p!==null&&p.kind==="app"&&p.namespace===e}o(i,"isNamespaceOwner");function f(e,n,p){return!p&&i(e,n)}o(f,"ownsWithoutRow");function w(e){return(s(e.replace(/^app:/,""))?.scopes??[]).map(n=>c(n))}o(w,"ownerScopes");function x(e,n){const p=r(e),t=r(n);return p!==null&&t!==null&&p.namespace===t.namespace}o(x,"sameNamespace");export{i as isNamespaceOwner,w as ownerScopes,f as ownsWithoutRow,x as sameNamespace};
@@ -20,6 +20,11 @@ export declare function warmNodeRepos(db: CanvasDb, nodeId: string): Promise<voi
20
20
  export declare function warmCloudNodeCheckouts(profileId: string | null, dirs: readonly string[]): Promise<void>;
21
21
  /** Warm the identities of `dirs` for node `nodeId` before a write opens: on a cloud role through its profile's machine, else git here. */
22
22
  export declare function warmNodeDirs(db: CanvasDb, nodeId: string | undefined, dirs: readonly string[]): Promise<void>;
23
+ /** `readerFor` for a call that acts for `as` (`--as`): a node reads as `as` under the grant `as` made to the node's app, never wider than the node's own scopes.
24
+ * `as` in the node's own namespace needs no grant. A node with no such grant is refused 403 `not_granted`. */
25
+ export declare function actingReaderFor(db: CanvasDb, principal: RequestPrincipal, reposFn: ReposFn, as: string): Promise<Exclude<Reader, {
26
+ class: 'object';
27
+ }>>;
23
28
  export declare function readerFor(db: CanvasDb, principal: RequestPrincipal, reposFn: ReposFn): Promise<Exclude<Reader, {
24
29
  class: 'object';
25
30
  }>>;
@@ -1,3 +1,3 @@
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};
1
+ var B=Object.defineProperty;var s=(o,e)=>B(o,"name",{value:e,configurable:!0});import{coveredByAny as _,isSandboxedNode as J}from"../../shared/env.js";import{projectPaths as P}from"../../api/dto/profiles.js";import{existsSync as O}from"node:fs";import{CrtrError as k}from"../errors.js";import{getCachedProfile as L}from"../scoped-state/person-store.js";import{parseScope as M}from"@north-light/identity";import{isNamespaceOwner as N,ownerScopes as v,sameNamespace as G}from"../grants/owner.js";import{activeGrant as T,grantFor as F,runtimeScope as q}from"../grants/mirror.js";import{withCanvasWrite as U}from"../canvas/db.js";import{ApiError as C}from"../../api/errors.js";import{pluginAppToken as Y}from"../secrets.js";import{loadExactProfileManifest as z}from"../profiles/manifest.js";import{ensureOwner as $,getById as K,nodeObject as Q,ownerForGrantee as V,profileHandle as X}from"./objects.js";import{personId as Z,personIdAsync as I}from"../canvas/person.js";import{OBJECT_TYPE as ee}from"../permissions/builtin.js";import{warmCheckoutDirs as H}from"../checkout-identities.js";import{fillProfileProjectRepo as oe}from"../profiles/manifest.js";import{emitEvent as ne}from"../events/emit.js";import{isCloudRole as R}from"../canvas/person-state.js";import{loadReadAccess as te,readableAmong as re,prefetchRepoReads as ae,reposForCwd as se,warmCheckoutIdentities as x}from"./repo-sync/repos.js";async function W(o,e,n,r,t,a){const c=n===null?[]:t.projects(n),p=c.length===0?void 0:a??await I(),i=p===void 0?void 0:await te(o,p);i!==void 0&&p!==void 0&&await ae(o,p,[e,...c.flatMap(l=>l.path!==void 0&&(R()||O(l.path))?[l.path]:[])],i);const f=c.flatMap(l=>l.repo===void 0?[]:[l.repo]),d=p===void 0?new Set:await re(o,p,f,i),g=await r(e,a,i),w=new Set(g.map(l=>l.repo.id)),m=[],E=[];for(const l of c){if(l.repo!==void 0&&!w.has(l.repo)){const u=await t.object(l.repo);u!==null&&u.type==="repo"&&u.deleted_at===null&&d.has(u.id)&&(w.add(u.id),m.push(u))}if(l.path===void 0||!R()&&!O(l.path))continue;let b;try{b=await r(l.path,a,i)}catch(u){if(u instanceof k&&u.code==="git-lookup-failed")continue;throw u}for(const u of b)w.has(u.repo.id)||(w.add(u.repo.id),m.push(u.repo),E.push(u))}return{repos:g.map(l=>l.repo),checkouts:g,projectRepos:m,projectCheckouts:E}}s(W,"viewRepos");async function Te(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?P(j(o).projects(n.profile_id)):[];if(R()){await pe(n.profile_id,[n.cwd,...r]);return}await x(n.cwd);for(const t of r)O(t)&&await x(t)}s(Te,"warmNodeRepos");async function pe(o,e){if(await H(o,e),o!==null){for(const n of L(o)?.manifest.projects??[])if(!(n.path===void 0||n.repo!==void 0))try{const r=(await U(async t=>await se(t,n.path)))[0];r!==void 0&&await oe(o,n.path,r.id)}catch(r){ne({level:"warn",event:"repo.identify.fill_failed",error:r,fields:{profile:o,path:n.path}})}}}s(pe,"warmCloudNodeCheckouts");async function $e(o,e,n){if(!R()){for(const t of n)await x(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($e,"warmNodeDirs");async function He(o,e,n,r){const t=await ce(o,e,n);if(t.class!=="node"||e.class!=="broker")throw new C(403,"not_granted","`--as` is for a node acting for another principal");const a=e.app;if(G(r,a))return{...t,sub:r};const c=await F(a,r);if(c===null)throw new C(403,"not_granted",`${r} has not granted ${a} access`);return{...t,sub:r,scopes:t.launched==null?c.resolved:t.launched.filter(p=>_(c.resolved,p))}}s(He,"actingReaderFor");async function ce(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 A(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 A(o)};const p=await F(e.actor.app,e.sub),i=p?p.resolved:N(e.actor.app,e.sub)?v(e.actor.app):null;if(i===null)throw new C(403,"app_not_granted",`${e.actor.app} holds no active grant for ${e.sub} on this machine`);const f=e.actor.node_scopes;return{class:"app",app:await S(o,e.actor.app),sub:e.sub,place:e.actor.place,launched:f,scopes:f===null?i:f.filter(d=>_(i,d))}}if(e.class==="cron"){const p=e.grant?(await T(e.grant))?.resolved??[]:[],i=e.scopes;return{class:"app",app:await S(o,e.app),scopes:i===null?p:i.filter(f=>_(p,f)),launched:i,place:{run:e.origin_run??"",isolated:e.isolated}}}const r=j(o),t=await Q(o,e.node),a=await o.prepare("SELECT cwd, profile_id, app FROM nodes WHERE node_id = ?").get(e.node),c=a.app===null?null:await r.object(a.app);if(!c)throw new Error(`node ${e.node} has no app`);return{class:"node",node:t,app:c,scopes:await D(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,c)}}s(ce,"readerFor");async function ie(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),c=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||!c)throw new Error(`no node ${e}`);const{grantee:p,sub:i,grant_id:f,scopes_json:d,cwd:g,profile_id:w,app:m}=c,E=m===null?null:await r.object(m);if(!E)throw new Error(`node ${e} has no app`);const l=d===null?null:JSON.parse(d);return{class:"node",node:a,app:E,scopes:await D(p,i??"",f,l,r,t),launched:l,cwd:g,...await W(o,g,w,n,r,i||void 0),profile:w===null?null:await r.profile(w,E)}}s(ie,"readerForNode");class le extends Error{static{s(this,"NoOwningAppError")}constructor(){super("no terminal app or person object"),this.name="NoOwningAppError"}}async function We(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 ue(o,e,t.envelope_json===null?null:JSON.parse(t.envelope_json),r);if(e.type==="node")return await ie(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 le;const i=(await o.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'app'").get(p.id))?.external_id??"app:terminal",f=q(),d=await o.prepare(`SELECT sub, resolved_scopes_json FROM grants WHERE grantee = ? AND status = 'active'${f.sql}`).all(i,...f.args),g=s(h=>JSON.parse(h.resolved_scopes_json).filter(y=>y.mode==="always").map(y=>M(y.scope)),"always"),w=d.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(ee,a.type==="repo"?a.id:e.id)).map(h=>h.subject_id)):null,m=w===null?void 0:d.find(h=>w.has(h.sub.replace(/^user:/,"")))?.sub,E=m===void 0?null:await r.grantFor(i,m),l=a.type==="person"?null:d.length===0?r.pluginScopes(i):d.length===1?g(d[0]):E?.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)??(d.length===1?d[0].sub:E?.sub);return{class:"object",object:e,node:e,owner:a,app:p,scopes:l,...u===void 0?{}:{sub:u},repos:a.type==="repo"?[a]:[]}}s(We,"readerForObject");async function De(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=>M(a.scope))}s(De,"appScopesNow");async function ue(o,e,n,r){const t=await A(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),c=n?.app==null?null:await r.grantFor(n.app,n.sub),p=c!==null?c.resolved:n?.app!=null&&N(n.app,n.sub)?v(n.app):null,i=n===null||p===null?null:n.node_scopes===null?p:n.node_scopes.filter(d=>_(p,d)),f=a??(e.owner===null?t:await r.object(e.owner)??t);return{class:"object",object:e,node:e,owner:f,app:f,scopes:i,launched:n?.node_scopes??null,repos:[],...n?.place==null?{}:{place:n.place}}}s(ue,"readerForStub");function j(o){return{grantById:T,grantFor:F,pluginScopes:s(e=>Y(e.replace(/^app:/,""))?.scopes??null,"pluginScopes"),object:s(async e=>await K(o,e),"object"),profile:s(async(e,n)=>await de(o,e,n),"profile"),projects:s(e=>J()?[]:L(e)?.manifest.projects??[],"projects")}}s(j,"liveLookups");function Be(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(Be,"publishLookups");async function D(o,e,n,r,t,a=!1){const c=n?await t.grantById(n):await t.grantFor(o,e),p=c&&c.grantee===o?c.resolved:c===null&&n===null&&N(o,e)?v(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(i=>_(p,i))}s(D,"nodeScopes");async function A(o){return await V(o,Z())}s(A,"personObject");async function S(o,e){return await $(o,"app","app",e,e.replace(/^app:/,""))}s(S,"appObject");async function de(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 $(o,"profile","profile",e,X(e,z(e).manifest.name),n)}s(de,"profileObject");export{le as NoOwningAppError,He as actingReaderFor,De as appScopesNow,j as liveLookups,de as profileObject,Be as publishLookups,ce as readerFor,ie as readerForNode,We as readerForObject,W as viewRepos,pe as warmCloudNodeCheckouts,$e as warmNodeDirs,Te as warmNodeRepos};
@@ -79,6 +79,8 @@ export type Reader = {
79
79
  app: ObjectRow;
80
80
  scopes: readonly string[] | null;
81
81
  cwd: string;
82
+ /** The principal this read acts for (`--as`), when it is not the node's own `sub`; the scopes are then the grant from it, never wider than the node's. */
83
+ sub?: string;
82
84
  /** The launched `scopes` list as given (see the app reader); null/absent = the run was launched with no list. */
83
85
  launched?: readonly string[] | null;
84
86
  /** The repos enclosing `cwd`, nearest first; `checkouts` pairs each with its checkout root. Only these are repos the node
@@ -1,6 +1,6 @@
1
- var L=Object.defineProperty;var a=(s,e)=>L(s,"name",{value:e,configurable:!0});import{parsePrincipal as x}from"@north-light/identity";import{isCloudRole as _,personIdAsync as H}from"../canvas/person.js";import{requestPersonId as W}from"../canvas/person-state.js";import{OBJECT_TYPE as k,GROUP_TYPE as m}from"./builtin.js";import{ceilingFrag as M,resolveCeiling as U}from"./ceiling.js";import{compilePermission as w}from"./compile.js";import{PermissionError as j}from"./errors.js";import{loadDefinitions as y}from"./schemas.js";import{TRUE as D,and as F,f as d,or as P,raw as u}from"./sql.js";const q=["read","edit","message","use","share"],v={read:"read",use:"read",edit:"write",share:"write",message:"message"},f=a(s=>s.replace(/^user:/,""),"bareUser"),S=a(s=>{const e=x(s);return e?.kind==="user"?f(e.namespace):null},"personSub");async function J(s,e){const t=await A(s,e);if(t!==null)return t;const n=e.class==="app"&&e.sub===void 0;if(e.class==="app"&&!(n&&!_()))throw new j(403,"no_person","an app reader that names no person acts for no one");return f(await H())}a(J,"userOf");async function A(s,e){if(e.class==="person"){const r=await s.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'user'").get(e.person.id);return r===void 0?null:f(r.external_id)}if(e.class==="app")return e.sub===void 0?null:S(e.sub);if(e.class==="object"&&e.sub!==void 0)return S(e.sub);const t=e.class==="node"?e.node.id:e.object.id,n=await s.prepare("SELECT sub FROM nodes WHERE node_id = ?").get(t);return n?.sub==null?null:S(n.sub)}a(A,"namedUserOf");async function O(s,e){const t=[e,"*"],n=await s.prepareUncached(`WITH RECURSIVE g(id) AS (
1
+ var L=Object.defineProperty;var c=(s,e)=>L(s,"name",{value:e,configurable:!0});import{parsePrincipal as x}from"@north-light/identity";import{isCloudRole as _,personIdAsync as H}from"../canvas/person.js";import{requestPersonId as W}from"../canvas/person-state.js";import{OBJECT_TYPE as k,GROUP_TYPE as w}from"./builtin.js";import{ceilingFrag as M,resolveCeiling as U}from"./ceiling.js";import{compilePermission as S}from"./compile.js";import{PermissionError as j}from"./errors.js";import{loadDefinitions as y}from"./schemas.js";import{TRUE as D,and as F,f as d,or as P,raw as u}from"./sql.js";const q=["read","edit","message","use","share"],v={read:"read",use:"read",edit:"write",share:"write",message:"message"},f=c(s=>s.replace(/^user:/,""),"bareUser"),E=c(s=>{const e=x(s);return e?.kind==="user"?f(e.namespace):null},"personSub");async function J(s,e){const n=await A(s,e);if(n!==null)return n;const t=e.class==="app"&&e.sub===void 0;if(e.class==="app"&&!(t&&!_()))throw new j(403,"no_person","an app reader that names no person acts for no one");return f(await H())}c(J,"userOf");async function A(s,e){if(e.class==="person"){const o=await s.prepare("SELECT external_id FROM identities WHERE object = ? AND scheme = 'user'").get(e.person.id);return o===void 0?null:f(o.external_id)}if(e.class==="app")return e.sub===void 0?null:E(e.sub);if(e.class==="object"&&e.sub!==void 0||e.class==="node"&&e.sub!==void 0)return E(e.sub);const n=e.class==="node"?e.node.id:e.object.id,t=await s.prepare("SELECT sub FROM nodes WHERE node_id = ?").get(n);return t?.sub==null?null:E(t.sub)}c(A,"namedUserOf");async function O(s,e){const n=[e,"*"],t=await s.prepareUncached(`WITH RECURSIVE g(id) AS (
2
2
  SELECT resource_id FROM relations WHERE resource_type = ? AND relation = 'member' AND subject_type = 'user' AND subject_id = ANY(?::text[])
3
3
  UNION
4
4
  SELECT r.resource_id FROM relations r JOIN g ON r.subject_type = ? AND r.subject_id = g.id AND r.subject_relation = 'member'
5
5
  WHERE r.resource_type = ? AND r.relation = 'member')
6
- SELECT id FROM g`).all(m,t,m,m);return{userIds:t,groupIds:n.map(r=>r.id)}}a(O,"subjectSet");const p=new WeakMap,ce=a(s=>(p.has(s)||p.set(s,null),s),"shareReads");function Y(s,e){const t=p.get(e);if(t)return t;const n=(async()=>{const r=_()&&W()===void 0?await A(s,e):await J(s,e);return{reader:e,userId:r,subjects:r===null?{userIds:["*"],groupIds:[]}:await O(s,r),defs:await y(s)}})();return t===null&&(p.set(e,n),n.catch(()=>p.set(e,null))),n}a(Y,"resolveReader");const B=a(s=>"subjects"in s,"isEval");async function G(s,e,t,n="o",r={}){if(!q.includes(t))throw new j(400,"unknown_permission",`unknown permission ${t}`);const o=B(e)?e:await Y(s,e),{defs:c}=o,E=u(`${n}.id`),N=w(c,o.subjects,k,t,E),h=t==="read"?P([N,u(`${n}.type = 'app'`)]):N,g=o.reader.class==="person"?null:o.reader.app.id,T=o.reader.class==="app"&&o.reader.place===void 0&&g!==null?await z(s,g):new Set,l=[];for(const[i,I]of c){if(i.startsWith("crtr/")||i==="user"||i==="app"||!(t in I.permissions)&&!(t in I.relations))continue;const C=i.split("/")[0];l.push(d`WHEN ${u(n)}.schema_type = ${i} THEN ${T.has(C)?D:w(c,o.subjects,i,t,E)}`)}const b=l.length===0?d`(CASE WHEN ${u(n)}.schema_type IS NULL THEN ${h} ELSE FALSE END)`:d`(CASE WHEN ${u(n)}.schema_type IS NULL THEN ${h} ${{sql:l.map(i=>i.sql).join(" "),params:l.flatMap(i=>i.params)}} ELSE FALSE END)`,R=await V(s,o,v[t],r);return R===null?b:F([M(R,n),b])}a(G,"permits");const $=new WeakMap;function V(s,e,t,n={}){let r=$.get(e.reader);r===void 0&&$.set(e.reader,r=new Map);const o=`${t} ${n.verb??""} ${e.userId} ${e.subjects.groupIds.join(",")}`;let c=r.get(o);return c===void 0&&(c=U(s,e.reader,e.userId,t,n),r.set(o,c),c.catch(()=>r.delete(o))),c}a(V,"ceilingOf");async function z(s,e){const t=await s.prepare("SELECT s.namespace FROM schemas s JOIN identities i ON i.external_id = s.app AND i.scheme = 'app' WHERE i.object = ?").all(e);return new Set(t.map(n=>n.namespace))}a(z,"ownNamespaceTypes");async function ie(s,e,t,n,r={}){const o=await G(s,e,t,"o",r);return(await s.prepareUncached(`SELECT ${o.sql} AS ok FROM objects o WHERE o.id = ?`).get(...o.params,n))?.ok===!0}a(ie,"check");async function ue(s,e,t,n){const r=await O(s,f(e)),o=await y(s),c=w(o,r,n.type,t,d`${n.id}::text`);return(await s.prepareUncached(`SELECT ${c.sql} AS ok`).get(...c.params))?.ok===!0}a(ue,"checkUser");export{q as PERMISSIONS,V as ceilingOf,ie as check,ue as checkUser,G as permits,Y as resolveReader,ce as shareReads,O as subjectSet,J as userOf};
6
+ SELECT id FROM g`).all(w,n,w,w);return{userIds:n,groupIds:t.map(o=>o.id)}}c(O,"subjectSet");const p=new WeakMap,ae=c(s=>(p.has(s)||p.set(s,null),s),"shareReads");function Y(s,e){const n=p.get(e);if(n)return n;const t=(async()=>{const o=_()&&W()===void 0?await A(s,e):await J(s,e);return{reader:e,userId:o,subjects:o===null?{userIds:["*"],groupIds:[]}:await O(s,o),defs:await y(s)}})();return n===null&&(p.set(e,t),t.catch(()=>p.set(e,null))),t}c(Y,"resolveReader");const B=c(s=>"subjects"in s,"isEval");async function G(s,e,n,t="o",o={}){if(!q.includes(n))throw new j(400,"unknown_permission",`unknown permission ${n}`);const r=B(e)?e:await Y(s,e),{defs:a}=r,m=u(`${t}.id`),N=S(a,r.subjects,k,n,m),b=n==="read"?P([N,u(`${t}.type = 'app'`)]):N,h=r.reader.class==="person"?null:r.reader.app.id,T=r.reader.class==="app"&&r.reader.place===void 0&&h!==null?await z(s,h):new Set,l=[];for(const[i,I]of a){if(i.startsWith("crtr/")||i==="user"||i==="app"||!(n in I.permissions)&&!(n in I.relations))continue;const C=i.split("/")[0];l.push(d`WHEN ${u(t)}.schema_type = ${i} THEN ${T.has(C)?D:S(a,r.subjects,i,n,m)}`)}const g=l.length===0?d`(CASE WHEN ${u(t)}.schema_type IS NULL THEN ${b} ELSE FALSE END)`:d`(CASE WHEN ${u(t)}.schema_type IS NULL THEN ${b} ${{sql:l.map(i=>i.sql).join(" "),params:l.flatMap(i=>i.params)}} ELSE FALSE END)`,R=await V(s,r,v[n],o);return R===null?g:F([M(R,t),g])}c(G,"permits");const $=new WeakMap;function V(s,e,n,t={}){let o=$.get(e.reader);o===void 0&&$.set(e.reader,o=new Map);const r=`${n} ${t.verb??""} ${e.userId} ${e.subjects.groupIds.join(",")}`;let a=o.get(r);return a===void 0&&(a=U(s,e.reader,e.userId,n,t),o.set(r,a),a.catch(()=>o.delete(r))),a}c(V,"ceilingOf");async function z(s,e){const n=await s.prepare("SELECT s.namespace FROM schemas s JOIN identities i ON i.external_id = s.app AND i.scheme = 'app' WHERE i.object = ?").all(e);return new Set(n.map(t=>t.namespace))}c(z,"ownNamespaceTypes");async function ie(s,e,n,t,o={}){const r=await G(s,e,n,"o",o);return(await s.prepareUncached(`SELECT ${r.sql} AS ok FROM objects o WHERE o.id = ?`).get(...r.params,t))?.ok===!0}c(ie,"check");async function ue(s,e,n,t){const o=await O(s,f(e)),r=await y(s),a=S(r,o,t.type,n,d`${t.id}::text`);return(await s.prepareUncached(`SELECT ${a.sql} AS ok`).get(...a.params))?.ok===!0}c(ue,"checkUser");export{q as PERMISSIONS,V as ceilingOf,ie as check,ue as checkUser,G as permits,Y as resolveReader,ae as shareReads,O as subjectSet,J as userOf};
@@ -1 +1 @@
1
- var ue=Object.defineProperty;var m=(e,t)=>ue(e,"name",{value:t,configurable:!0});import{validateDeclaredResult as G}from"../../api/command-manifest/result.js";import{callerAllows as le,requireGroup as pe}from"../../daemon/api/handlers/providers.js";import{callerTerminalGrant as ce}from"../grants/terminal.js";import{environmentPayerOfNode as fe,findRefusal as me,payerOf as ve,refusalError as ge,refusedMark as he,writeCharge as we}from"../ledger/index.js";import{listInstalledPlugins as ye}from"../resolver.js";import{emitEvent as be}from"../events/emit.js";import{ProviderError as c,scopeMissing as _e}from"./errors.js";import{parseProviderPayment as je}from"../provider-failure.js";import{resolveProviderRef as Ae}from"./roots.js";import{providerToolPath as ke}from"../plugin-objects-manifest.js";import{ensureProviderBundle as Pe,refreshProviderBundle as Y,resolveProviderBundle as S,unavailableProviderError as $e}from"./bundles.js";import{prepareFileCall as Ee,resignForRetry as Z,resolveFileResult as ee}from"./files.js";import{consumeApproval as qe,requireProviderApproval as Ce}from"./approval.js";import{outboundToken as Re}from"./mint.js";import{discardFile as Me}from"./token-cache.js";import{registerProviderCall as Oe}from"./inflight.js";import{buildRequestPlan as Te,paramKey as Ie}from"../command-plugins/transport/http-plan.js";import{newTraceId as Ne}from"../../shared/traceparent.js";import{sendProviderRequest as Be,ProviderTransportError as Se}from"./request.js";import{acceptProviderReceipt as Fe}from"./receipts.js";import{writeProviderAudit as De}from"./audit.js";import{selectDevice as Ue,sendDeviceCall as Le,deviceFailure as xe,deviceUnreachable as re,DEFAULT_DEVICE_REQUEST_MS as Je}from"./device.js";import{isLibsSearch as te,wantsBundling as He,callLibsSearch as Ge,bundleExec as ze,mapLibOutcome as Ke,reportLibCalls as Qe}from"./device-libs.js";import{ownMachineId as Ve}from"../peer/directory.js";import{directoryIssuer as We}from"../directory/issuer.js";import{isCloudRole as Xe}from"../canvas/person-state.js";import{formatCrtrCaller as oe}from"../command-plugins/caller-header.js";import{getNode as Ye}from"../canvas/canvas.js";import{envelopeForProviderCaller as Ze,EnvelopeError as er}from"../peer/envelope.js";const rr="app:terminal";function ne(e){const t=[],i=m((l,r,n)=>{const p=[...r,l.name],d=n||l.tier==="hidden";if(l.kind==="branch"){for(const b of l.children)i(b,p,d);return}const h=ke(e.roots.length,p);t.push({tool:h,leaf:l,hidden:d})},"walk");for(const l of e.roots)i(l,[],!1);return t}m(ne,"providerLeaves");function ie(e){if(e.kind!=="branch")return null;const t=[];for(const v of e.children)if(v.kind==="branch"){const _=ie(v);_&&t.push(_)}else if("group"in v&&v.group){const{kind:_,name:s,description:j,whenToUse:w,tier:y,summary:k,params:P,output:o,effects:u,group:A}=v;t.push({kind:_,name:s,description:j,whenToUse:w,...y===void 0?{}:{tier:y},summary:k,params:P,output:o,effects:u,group:A})}if(t.length===0)return null;const{kind:i,name:l,description:r,whenToUse:n,tier:p,summary:d,model:h,rootEntry:b}=e;return{kind:i,name:l,description:r,whenToUse:n,...p===void 0?{}:{tier:p},summary:d,...h===void 0?{}:{model:h},...b===void 0?{}:{rootEntry:b},children:t}}m(ie,"providerHelpBranch");async function Ur(e,t){const i=await S(t),l=ne(i.commands),r=ye("user").find(n=>n.name===t)?.manifest.description??t;return{provider:t,status:"available",major:i.major,display_name:r,transport:i.transport.kind,groups:i.provider.groups.filter(n=>le(e,`${t}:${n.group}`)).map(n=>({group:n.group,leaves:l.filter(({leaf:p,hidden:d})=>!d&&p.group===n.group).map(({tool:p,leaf:d})=>({tool:p,description:d.description,summary:d.summary,params:d.params,output:d.output}))})),commands:i.commands.roots.flatMap(n=>{const p=ie(n);return p?[p]:[]})}}m(Ur,"providerTools");async function tr(e){return await Fe(e.headers["crtr-receipt"],e)}m(tr,"onProviderResponse");async function or(e){if(e.class==="person"){const t=(await ce())?.sub;if(!t)throw new c("grant_revoked","This machine has no active Northlight grant for your terminal. Run `crtr sys signin` again.");return{sub:t,grantee:t}}if(!e.sub||!e.grantee)throw new c("grant_revoked","the caller has no active grant");return{sub:e.sub,grantee:e.grantee}}m(or,"identity");function nr(e,t){return[`${e.id}:${t.group}`]}m(nr,"callScope");function ir(e,t){const i=ne(e.commands).find(l=>l.tool===t);if(!i)throw new c("not_found",`tool "${t}" is not in provider "${e.id}"`,{param:"tool"});if(!i.leaf.group)throw new c("not_found",`tool "${t}" has no group`,{param:"tool"});return i.leaf}m(ir,"leafFor");function z(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=e.error;return!t||typeof t!="object"||Array.isArray(t)?{}:t}m(z,"errorBody");function ar(e){const t=Array.isArray(e)?e[0]:e;if(!t)return;const i=Number(t);if(Number.isFinite(i)&&i>=0)return i;const l=Date.parse(t);return Number.isFinite(l)?Math.max(0,Math.ceil((l-Date.now())/1e3)):void 0}m(ar,"retryAfter");function F(e,t,i,l=!1){const r=z(t),n=typeof r.code=="string"?r.code:void 0,p=typeof r.message=="string"?r.message:`provider answered HTTP ${e}`,d=typeof r.field=="string"?r.field:void 0,h=r.details&&typeof r.details=="object"?r.details:{},b=je(h.payment),v=typeof r.next=="string"?r.next:typeof h.next=="string"?h.next:void 0,s={origin:"provider",details:{code:n??null,message:p,...d?{field:d}:{},...v!==void 0?{next:v}:{},...r.received!==void 0?{received:r.received}:{},...b===void 0?{}:{payment:b},status:e},...d?{param:d}:{}};return e===429?new c("provider_rate_limited",p,{...s,retry_after_s:ar(i["retry-after"])}):e===401||e>=500?new c("provider_unavailable",p,s):e===403&&n==="provider_refused"?new c("provider_refused",p,s):e===403&&n==="approval_required"?new c("provider_error",l?"provider asked for approval again":"provider approval question is invalid",{...s,status:e}):new c("provider_error",p,{...s,status:e})}m(F,"mapProviderResponse");function ae(e,t){return JSON.stringify({major:e.major,endpoint:e.transport.kind==="http"?e.transport.endpoint:null,baseUrl:e.commands.baseUrl??null,rest:t.rest,params:t.params,output:t.output})}m(ae,"approvalShape");async function sr(e){const t=e.origin!==void 0?oe({node:e.origin.node??void 0,run:e.origin.run??void 0,machine:e.origin.machine}):oe({node:e.node_id??void 0,run:e.run_id??void 0,profile:e.node_id?(await Ye(e.node_id))?.profile_id??void 0:void 0,machine:We()!==null?Ve():void 0});return t===""?{}:{"Crtr-Caller":t}}m(sr,"crtrCallerHeader");async function Lr(e,t,i){const l=Ae(t.provider);if(l===null)throw new c("not_found",`provider "${t.provider}" is not available`,{param:"provider"});const r={...t,provider:l},n=new AbortController,p=m(()=>n.abort(i.signal.reason),"abort");i.signal.aborted?p():i.signal.addEventListener("abort",p,{once:!0});let d=i.requestId;const h=i.traceId??Ne(),b=Oe({request_id:d,run_id:e.run_id,node_id:e.node_id,controller:n});let v,_,s,j,w,y,k,P="allowed";try{if(Xe()&&e.class==="person"&&e.resolved!==null&&!e.resolved.some(g=>g.startsWith(`${r.provider}:`)))throw _e(`${r.provider}:*`);try{await Pe(r.provider)}catch{throw $e(r.provider)}let o=await S(r.provider,r.version),u=!1,A=!1,$,D,q,K=!1,Q=!1,U,V=0;for(;;){const g=ir(o,r.tool);if(s=`${o.id}:${g.group}`,pe(e,o.id,g.group),o.transport.kind!=="machine"&&r.machine!==void 0)throw new c("invalid_argument",`provider "${o.id}" is not served by a device, so it takes no machine`,{param:"machine"});o.transport.kind==="machine"&&U===void 0&&(U=await Ue(r.machine,void 0,{newest:te(o.major,r.tool)}),V=Date.now()+(o.commands.timeouts?.requestMs??Je));let L=null;if(r.approval&&!K){const a=await qe(e,r,ae(o,g));q=a.option,L=a.prepared,k=r.approval,d=a.requestId,K=!0}const I={params:g.params.filter(a=>"type"in a&&a.type==="file").map(a=>a.name),output:g.output.find(a=>a.type==="file")?.name??null},W=JSON.stringify(I);if(D!==void 0&&D!==W)throw new c("provider_bad_response","the refreshed manifest changed the tool file contract",{origin:"provider",details:{status:409,message:"manifest_stale changed the tool file contract"}});D=W,L&&($=await Z(e,I,r.arguments,L,{signal:n.signal})),$??=await Ee(e,I,r.arguments,{signal:n.signal});const{sub:M,grantee:N}=await or(e);if(o.transport.kind==="machine"){const a=await ur(e,o,r,g,$,{sub:M,requestId:d,deadlineAt:V,signal:n.signal,machine:U});return y=a.responder,v=a.cleanup,{status:200,body:a.result}}const X=o.transport.endpoint;let C;try{C=await Re({audience:X,sub:M,grantee:N,initiating_app:N,scope:nr(o,g)},{signal:n.signal})}catch(a){if(!(a instanceof c)||a.details?.directory_error!=="invalid_target"||A)throw a;A=!0,await Y(o.id,{conditional:!1,...r.version===void 0?{}:{version:r.version}});const E=await S(o.id,r.version);if(E.transport.kind==="machine"||E.transport.endpoint===X)throw a;o=E;continue}j=C.jti;const x=e.class==="person"?rr:N,O=ve({call:"tool",tokenPayer:C.payer,sub:M,environmentPayer:await fe(e.node_id)}),J=await me({scope:"call",payer:O.payer,funding:O.funding,sub:M,grantee:x,provider:`app:${o.id}`});if(J!==null)throw await we({request:d,kind:"tool",what:`${o.id}:${r.tool}`,usd:0,payer:O.payer,funding:O.funding,sub:M,actor:e.actor??null,grantee:x,node:e.node_id,run:e.run_id,provider:`app:${o.id}`,causedBy:i.causedBy??null,refused:he(J)}),ge(J);const se={registration:{name:o.id,endpoint:o.transport.endpoint},...o.commands.baseUrl?{baseUrl:o.commands.baseUrl}:{},...o.commands.timeouts?{timeouts:o.commands.timeouts}:{},params:g.params,rest:g.rest,output:g.output,commandPath:[o.id,...r.tool.split(" ")]},de=Te(se,$.arguments,void 0,{authorization:`Bearer ${C.access_token}`,requestId:d,traceId:h,fileMode:"pass-through",extraHeaders:{...i.causedBy?{"Crtr-Caused-By":i.causedBy}:{},...e.run_id?{"Crtr-Run-Id":e.run_id}:{},...await sr(e),...q?{"Crtr-Approval":q}:{},...$.headers}});_??=Date.now()+(o.commands.timeouts?.requestMs??3e4);let f;try{if(f=await Be(de,{connectMs:o.commands.timeouts?.connectMs,requestMs:o.commands.timeouts?.requestMs,deadlineAt:_,signal:n.signal}),n.signal.aborted)throw n.signal.reason??new Error("provider call aborted")}catch(a){throw n.signal.aborted?n.signal.reason??a:a instanceof Se?new c("provider_unavailable",a.message,{origin:"provider",details:{status:null,code:a.kind}}):a}if(w??=await tr({provider:o.id,tool:r.tool,request_id:d,run_id:e.run_id,sub:M,grantee:N,payer:C.payer,ledger_grantee:x,funding:O.funding,node_id:e.node_id,actor:e.actor??null,caused_by:i.causedBy??null,jti:C.jti,status:f.status,headers:f.headers}),y=f.headers["crtr-responder"],f.status===401&&Me(C.key),f.status>=200&&f.status<300){const a=f.body;if(!a||typeof a!="object"||Array.isArray(a))throw new c("provider_bad_response","provider result is not a JSON object",{origin:"provider",details:{status:f.status,message:"provider result is not a JSON object"}});let E;try{E=await ee(e,$,a,{signal:n.signal})}catch(T){throw T instanceof c&&T.code==="provider_error"?new c("provider_bad_response",T.message,{origin:"provider",details:{status:f.status,message:T.message}}):T}v=E.cleanup;const B=G(g.output,E.result);if(B)throw new c("provider_bad_response",`provider result has an invalid output field "${B.field}"`,{origin:"provider",param:B.field,details:{status:f.status,...B}});if(n.signal.aborted)throw n.signal.reason??new Error("provider call aborted");return{status:200,body:E.result}}const R=z(f.body);if(f.status===403&&R.code==="approval_required"&&!q&&!Q){Q=!0;const a=await Ce(e,r,d,R.question,n.signal,ae(o,g),$);if(k=a.questionId,q=a.option,$=await Z(e,I,r.arguments,$,{signal:n.signal}),_=void 0,n.signal.aborted)throw new c("user_denied","the approval wait was canceled");continue}if(f.status===403&&R.code==="approval_required"&&q)throw F(f.status,f.body,f.headers,!0);const H=f.status===410&&R.code==="unsupported_major"&&r.version===void 0;if(f.status!==401&&(R.manifest_stale===!0||H)&&!u){u=!0;const a=o.major;await Y(o.id,{conditional:!1,...r.version===void 0?{}:{version:r.version}}),o=await S(o.id,r.version),be({level:"info",event:"daemon.providers.call_retried",fields:{provider:o.id,tool:r.tool,reason:H?"unsupported_major":"manifest_stale",major_before:a,major_after:o.major,...H&&typeof R.received=="number"?{received:R.received}:{}}});continue}throw F(f.status,f.body,f.headers,!!q)}}catch(o){throw o instanceof c&&o.question_id&&(k=o.question_id),y===void 0&&o instanceof c&&typeof o.responder=="string"&&(y=o.responder),P=`refused:${o instanceof c?o.code:"server_error"}`,await v?.(),o}finally{try{await De({request_id:d,caller:e,provider:r.provider,tool:r.tool,scope_checked:s,outcome:P,jti:j,receipt_id:w,responder:y,question_id:k})}finally{b()}i.signal.removeEventListener("abort",p)}}m(Lr,"callProvider");function dr(e,t){const i={...t};for(const{name:l}of e.params){const r=Ie(l);r===l||!Object.hasOwn(i,r)||(i[l]=i[r],delete i[r])}return i}m(dr,"declaredNames");async function ur(e,t,i,l,r,n){const{machine:p}=n;let d;try{d=await Ze(e,n.sub)}catch(u){throw u instanceof er?new c("invalid_request",u.message,{origin:"runtime"}):u}const h={machine:p,envelope:d,signal:n.signal,deadlineAt:n.deadlineAt,mapFailure:F};if(te(t.major,i.tool)){const u=await Ge(h,r.arguments,t.major),A=G(l.output,u);if(A)throw new c("provider_bad_response",`the libraries result has an invalid output field "${A.field}"`,{origin:"provider",param:A.field,details:{status:200,...A}});return{result:u,responder:void 0,cleanup:void 0}}let b=r.arguments,v=null,_="";if(He(t.major,i.tool,r.arguments)){const u=await ze(h,r.arguments,t.major);if(n.deadlineAt-Date.now()<=0)throw re(p,"timeout","");u!==null&&(b=u.arguments,v=u.services,_=u.release)}const s=await Le(p,{tool:i.tool,arguments:dr(l,b),version:t.major,requestId:n.requestId,runId:e.run_id,deadlineAt:n.deadlineAt,upload:r.upload===null?null:{id:r.upload.upload_id,link:r.upload.upload_link}},d,n.signal);if(n.signal.aborted)throw n.signal.reason??new Error("provider call aborted");if("unreachable"in s)throw re(p,s.unreachable.reason,s.unreachable.message);const j=s.headers["crtr-responder"],w=z(s.body);if(s.status<200||s.status>=300){const u=xe(p,s.status,typeof w.code=="string"?w.code:void 0,typeof w.message=="string"?w.message:void 0,s.body),A=u===null&&s.status>=500&&typeof w.code=="string"?new c("provider_error",typeof w.message=="string"?w.message:`the device answered HTTP ${s.status}`,{origin:"runtime",status:s.status,details:{code:w.code,status:s.status}}):null;throw Object.assign(u??A??F(s.status,s.body,s.headers),{responder:j})}const y=s.body&&typeof s.body=="object"&&!Array.isArray(s.body)?s.body.result:void 0;if(!y||typeof y!="object"||Array.isArray(y))throw Object.assign(new c("provider_bad_response","the device result is not a JSON object",{origin:"provider",details:{status:s.status,message:"the device result is not a JSON object"}}),{responder:j});let k=y;if(v!==null){const u=Ke(k,v);if(Qe(p,d,_,u.calls),"error"in u)throw Object.assign(u.error,{responder:j});k=u.result}let P;try{P=await ee(e,r,k,{signal:n.signal})}catch(u){throw u instanceof c&&u.code==="provider_error"?Object.assign(new c("provider_bad_response",u.message,{origin:"provider",details:{status:s.status,message:u.message}}),{responder:j}):u}const o=G(l.output,P.result);if(o)throw await P.cleanup?.(),Object.assign(new c("provider_bad_response",`the device result has an invalid output field "${o.field}"`,{origin:"provider",param:o.field,details:{status:s.status,...o}}),{responder:j});return{result:P.result,responder:j,cleanup:P.cleanup}}m(ur,"callDevice");export{Lr as callProvider,sr as crtrCallerHeader,or as identity,F as mapProviderResponse,tr as onProviderResponse,ne as providerLeaves,Ur as providerTools};
1
+ var pe=Object.defineProperty;var m=(e,t)=>pe(e,"name",{value:t,configurable:!0});import{validateDeclaredResult as K}from"../../api/command-manifest/result.js";import{callerAllows as ce,requireGroup as fe}from"../../daemon/api/handlers/providers.js";import{callerTerminalGrant as me}from"../grants/terminal.js";import{environmentPayerOfNode as ve,findRefusal as ge,payerOf as he,refusalError as we,refusedMark as ye,writeCharge as be}from"../ledger/index.js";import{listInstalledPlugins as _e}from"../resolver.js";import{emitEvent as je}from"../events/emit.js";import{ProviderError as l,scopeMissing as ke}from"./errors.js";import{parseProviderPayment as Ae}from"../provider-failure.js";import{resolveProviderRef as Pe}from"./roots.js";import{providerToolPath as $e}from"../plugin-objects-manifest.js";import{ensureProviderBundle as Ee,refreshProviderBundle as Z,resolveProviderBundle as S,unavailableProviderError as qe}from"./bundles.js";import{prepareFileCall as Ce,resignForRetry as ee,resolveFileResult as re}from"./files.js";import{consumeApproval as Re,requireProviderApproval as Te}from"./approval.js";import{actingToken as Me,outboundToken as Oe}from"./mint.js";import{discardFile as Ie}from"./token-cache.js";import{registerProviderCall as Ne}from"./inflight.js";import{buildRequestPlan as Be,paramKey as Se}from"../command-plugins/transport/http-plan.js";import{newTraceId as Fe}from"../../shared/traceparent.js";import{sendProviderRequest as De,ProviderTransportError as Ue}from"./request.js";import{acceptProviderReceipt as Le}from"./receipts.js";import{writeProviderAudit as xe}from"./audit.js";import{selectDevice as Je,sendDeviceCall as He,deviceFailure as Ge,deviceUnreachable as te,DEFAULT_DEVICE_REQUEST_MS as ze}from"./device.js";import{isLibsSearch as oe,wantsBundling as Ke,callLibsSearch as Qe,bundleExec as Ve,mapLibOutcome as We,reportLibCalls as Xe}from"./device-libs.js";import{ownMachineId as Ye}from"../peer/directory.js";import{directoryIssuer as Ze}from"../directory/issuer.js";import{isCloudRole as er}from"../canvas/person-state.js";import{formatCrtrCaller as ne}from"../command-plugins/caller-header.js";import{getNode as rr}from"../canvas/canvas.js";import{envelopeForProviderCaller as tr,EnvelopeError as or}from"../peer/envelope.js";const nr="app:terminal";function ie(e){const t=[],i=m((p,r,n)=>{const c=[...r,p.name],d=n||p.tier==="hidden";if(p.kind==="branch"){for(const b of p.children)i(b,c,d);return}const h=$e(e.roots.length,c);t.push({tool:h,leaf:p,hidden:d})},"walk");for(const p of e.roots)i(p,[],!1);return t}m(ie,"providerLeaves");function ae(e){if(e.kind!=="branch")return null;const t=[];for(const v of e.children)if(v.kind==="branch"){const _=ae(v);_&&t.push(_)}else if("group"in v&&v.group){const{kind:_,name:s,description:j,whenToUse:w,tier:y,summary:A,params:P,output:o,effects:u,group:k}=v;t.push({kind:_,name:s,description:j,whenToUse:w,...y===void 0?{}:{tier:y},summary:A,params:P,output:o,effects:u,group:k})}if(t.length===0)return null;const{kind:i,name:p,description:r,whenToUse:n,tier:c,summary:d,model:h,rootEntry:b}=e;return{kind:i,name:p,description:r,whenToUse:n,...c===void 0?{}:{tier:c},summary:d,...h===void 0?{}:{model:h},...b===void 0?{}:{rootEntry:b},children:t}}m(ae,"providerHelpBranch");async function xr(e,t){const i=await S(t),p=ie(i.commands),r=_e("user").find(n=>n.name===t)?.manifest.description??t;return{provider:t,status:"available",major:i.major,display_name:r,transport:i.transport.kind,groups:i.provider.groups.filter(n=>ce(e,`${t}:${n.group}`)).map(n=>({group:n.group,leaves:p.filter(({leaf:c,hidden:d})=>!d&&c.group===n.group).map(({tool:c,leaf:d})=>({tool:c,description:d.description,summary:d.summary,params:d.params,output:d.output}))})),commands:i.commands.roots.flatMap(n=>{const c=ae(n);return c?[c]:[]})}}m(xr,"providerTools");async function ir(e){return await Le(e.headers["crtr-receipt"],e)}m(ir,"onProviderResponse");async function ar(e){if(e.class==="person"){const t=(await me())?.sub;if(!t)throw new l("grant_revoked","This machine has no active Northlight grant for your terminal. Run `crtr sys signin` again.");return{sub:t,grantee:t}}if(!e.sub||!e.grantee)throw new l("grant_revoked","the caller has no active grant");return{sub:e.sub,grantee:e.grantee}}m(ar,"identity");function se(e,t){return[`${e.id}:${t.group}`]}m(se,"callScope");function sr(e,t){const i=ie(e.commands).find(p=>p.tool===t);if(!i)throw new l("not_found",`tool "${t}" is not in provider "${e.id}"`,{param:"tool"});if(!i.leaf.group)throw new l("not_found",`tool "${t}" has no group`,{param:"tool"});return i.leaf}m(sr,"leafFor");function Q(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=e.error;return!t||typeof t!="object"||Array.isArray(t)?{}:t}m(Q,"errorBody");function dr(e){const t=Array.isArray(e)?e[0]:e;if(!t)return;const i=Number(t);if(Number.isFinite(i)&&i>=0)return i;const p=Date.parse(t);return Number.isFinite(p)?Math.max(0,Math.ceil((p-Date.now())/1e3)):void 0}m(dr,"retryAfter");function F(e,t,i,p=!1){const r=Q(t),n=typeof r.code=="string"?r.code:void 0,c=typeof r.message=="string"?r.message:`provider answered HTTP ${e}`,d=typeof r.field=="string"?r.field:void 0,h=r.details&&typeof r.details=="object"?r.details:{},b=Ae(h.payment),v=typeof r.next=="string"?r.next:typeof h.next=="string"?h.next:void 0,s={origin:"provider",details:{code:n??null,message:c,...d?{field:d}:{},...v!==void 0?{next:v}:{},...r.received!==void 0?{received:r.received}:{},...b===void 0?{}:{payment:b},status:e},...d?{param:d}:{}};return e===429?new l("provider_rate_limited",c,{...s,retry_after_s:dr(i["retry-after"])}):e===401||e>=500?new l("provider_unavailable",c,s):e===403&&n==="provider_refused"?new l("provider_refused",c,s):e===403&&n==="approval_required"?new l("provider_error",p?"provider asked for approval again":"provider approval question is invalid",{...s,status:e}):new l("provider_error",c,{...s,status:e})}m(F,"mapProviderResponse");function de(e,t){return JSON.stringify({major:e.major,endpoint:e.transport.kind==="http"?e.transport.endpoint:null,baseUrl:e.commands.baseUrl??null,rest:t.rest,params:t.params,output:t.output})}m(de,"approvalShape");async function ur(e){const t=e.origin!==void 0?ne({node:e.origin.node??void 0,run:e.origin.run??void 0,machine:e.origin.machine}):ne({node:e.node_id??void 0,run:e.run_id??void 0,profile:e.node_id?(await rr(e.node_id))?.profile_id??void 0:void 0,machine:Ze()!==null?Ye():void 0});return t===""?{}:{"Crtr-Caller":t}}m(ur,"crtrCallerHeader");async function Jr(e,t,i){const p=Pe(t.provider);if(p===null)throw new l("not_found",`provider "${t.provider}" is not available`,{param:"provider"});const r={...t,provider:p},n=new AbortController,c=m(()=>n.abort(i.signal.reason),"abort");i.signal.aborted?c():i.signal.addEventListener("abort",c,{once:!0});let d=i.requestId;const h=i.traceId??Fe(),b=Ne({request_id:d,run_id:e.run_id,node_id:e.node_id,controller:n});let v,_,s,j,w,y,A,P="allowed";try{if(er()&&e.class==="person"&&e.resolved!==null&&!e.resolved.some(g=>g.startsWith(`${r.provider}:`)))throw ke(`${r.provider}:*`);try{await Ee(r.provider)}catch{throw qe(r.provider)}let o=await S(r.provider,r.version),u=!1,k=!1,$,D,q,V=!1,W=!1,U,X=0;for(;;){const g=sr(o,r.tool);if(s=`${o.id}:${g.group}`,fe(e,o.id,g.group),o.transport.kind!=="machine"&&r.machine!==void 0)throw new l("invalid_argument",`provider "${o.id}" is not served by a device, so it takes no machine`,{param:"machine"});o.transport.kind==="machine"&&U===void 0&&(U=await Je(r.machine,void 0,{newest:oe(o.major,r.tool)}),X=Date.now()+(o.commands.timeouts?.requestMs??ze));let L=null;if(r.approval&&!V){const a=await Re(e,r,de(o,g));q=a.option,L=a.prepared,A=r.approval,d=a.requestId,V=!0}const N={params:g.params.filter(a=>"type"in a&&a.type==="file").map(a=>a.name),output:g.output.find(a=>a.type==="file")?.name??null},Y=JSON.stringify(N);if(D!==void 0&&D!==Y)throw new l("provider_bad_response","the refreshed manifest changed the tool file contract",{origin:"provider",details:{status:409,message:"manifest_stale changed the tool file contract"}});D=Y,L&&($=await ee(e,N,r.arguments,L,{signal:n.signal})),$??=await Ce(e,N,r.arguments,{signal:n.signal});const x=await ar(e),{grantee:T}=x,M=r.as??x.sub;if(o.transport.kind==="machine"){if(r.as!==void 0)throw new l("not_granted","`--as` is not available on a provider served by a device",{param:"as"});const a=await pr(e,o,r,g,$,{sub:M,requestId:d,deadlineAt:X,signal:n.signal,machine:U});return y=a.responder,v=a.cleanup,{status:200,body:a.result}}const J=o.transport.endpoint;let C;try{C=r.as===void 0?await Oe({audience:J,sub:M,grantee:T,initiating_app:T,scope:se(o,g)},{signal:n.signal}):await Me(x,r.as,{audience:J,scope:se(o,g)},{signal:n.signal})}catch(a){if(!(a instanceof l)||a.details?.directory_error!=="invalid_target"||k)throw a;k=!0,await Z(o.id,{conditional:!1,...r.version===void 0?{}:{version:r.version}});const E=await S(o.id,r.version);if(E.transport.kind==="machine"||E.transport.endpoint===J)throw a;o=E;continue}j=C.jti;const H=e.class==="person"?nr:T,O=he({call:"tool",tokenPayer:C.payer,sub:M,environmentPayer:await ve(e.node_id)}),G=await ge({scope:"call",payer:O.payer,funding:O.funding,sub:M,grantee:H,provider:`app:${o.id}`});if(G!==null)throw await be({request:d,kind:"tool",what:`${o.id}:${r.tool}`,usd:0,payer:O.payer,funding:O.funding,sub:M,actor:e.actor??(r.as===void 0?null:T),grantee:H,node:e.node_id,run:e.run_id,provider:`app:${o.id}`,causedBy:i.causedBy??null,refused:ye(G)}),we(G);const ue={registration:{name:o.id,endpoint:o.transport.endpoint},...o.commands.baseUrl?{baseUrl:o.commands.baseUrl}:{},...o.commands.timeouts?{timeouts:o.commands.timeouts}:{},params:g.params,rest:g.rest,output:g.output,commandPath:[o.id,...r.tool.split(" ")]},le=Be(ue,$.arguments,void 0,{authorization:`Bearer ${C.access_token}`,requestId:d,traceId:h,fileMode:"pass-through",extraHeaders:{...i.causedBy?{"Crtr-Caused-By":i.causedBy}:{},...e.run_id?{"Crtr-Run-Id":e.run_id}:{},...await ur(e),...q?{"Crtr-Approval":q}:{},...$.headers}});_??=Date.now()+(o.commands.timeouts?.requestMs??3e4);let f;try{if(f=await De(le,{connectMs:o.commands.timeouts?.connectMs,requestMs:o.commands.timeouts?.requestMs,deadlineAt:_,signal:n.signal}),n.signal.aborted)throw n.signal.reason??new Error("provider call aborted")}catch(a){throw n.signal.aborted?n.signal.reason??a:a instanceof Ue?new l("provider_unavailable",a.message,{origin:"provider",details:{status:null,code:a.kind}}):a}if(w??=await ir({provider:o.id,tool:r.tool,request_id:d,run_id:e.run_id,sub:M,grantee:T,payer:C.payer,ledger_grantee:H,funding:O.funding,node_id:e.node_id,actor:e.actor??(r.as===void 0?null:T),caused_by:i.causedBy??null,jti:C.jti,status:f.status,headers:f.headers}),y=f.headers["crtr-responder"],f.status===401&&Ie(C.key),f.status>=200&&f.status<300){const a=f.body;if(!a||typeof a!="object"||Array.isArray(a))throw new l("provider_bad_response","provider result is not a JSON object",{origin:"provider",details:{status:f.status,message:"provider result is not a JSON object"}});let E;try{E=await re(e,$,a,{signal:n.signal})}catch(I){throw I instanceof l&&I.code==="provider_error"?new l("provider_bad_response",I.message,{origin:"provider",details:{status:f.status,message:I.message}}):I}v=E.cleanup;const B=K(g.output,E.result);if(B)throw new l("provider_bad_response",`provider result has an invalid output field "${B.field}"`,{origin:"provider",param:B.field,details:{status:f.status,...B}});if(n.signal.aborted)throw n.signal.reason??new Error("provider call aborted");return{status:200,body:E.result}}const R=Q(f.body);if(f.status===403&&R.code==="approval_required"&&!q&&!W){W=!0;const a=await Te(e,r,d,R.question,n.signal,de(o,g),$);if(A=a.questionId,q=a.option,$=await ee(e,N,r.arguments,$,{signal:n.signal}),_=void 0,n.signal.aborted)throw new l("user_denied","the approval wait was canceled");continue}if(f.status===403&&R.code==="approval_required"&&q)throw F(f.status,f.body,f.headers,!0);const z=f.status===410&&R.code==="unsupported_major"&&r.version===void 0;if(f.status!==401&&(R.manifest_stale===!0||z)&&!u){u=!0;const a=o.major;await Z(o.id,{conditional:!1,...r.version===void 0?{}:{version:r.version}}),o=await S(o.id,r.version),je({level:"info",event:"daemon.providers.call_retried",fields:{provider:o.id,tool:r.tool,reason:z?"unsupported_major":"manifest_stale",major_before:a,major_after:o.major,...z&&typeof R.received=="number"?{received:R.received}:{}}});continue}throw F(f.status,f.body,f.headers,!!q)}}catch(o){throw o instanceof l&&o.question_id&&(A=o.question_id),y===void 0&&o instanceof l&&typeof o.responder=="string"&&(y=o.responder),P=`refused:${o instanceof l?o.code:"server_error"}`,await v?.(),o}finally{try{await xe({request_id:d,caller:e,provider:r.provider,tool:r.tool,scope_checked:s,outcome:P,jti:j,receipt_id:w,responder:y,question_id:A})}finally{b()}i.signal.removeEventListener("abort",c)}}m(Jr,"callProvider");function lr(e,t){const i={...t};for(const{name:p}of e.params){const r=Se(p);r===p||!Object.hasOwn(i,r)||(i[p]=i[r],delete i[r])}return i}m(lr,"declaredNames");async function pr(e,t,i,p,r,n){const{machine:c}=n;let d;try{d=await tr(e,n.sub)}catch(u){throw u instanceof or?new l("invalid_request",u.message,{origin:"runtime"}):u}const h={machine:c,envelope:d,signal:n.signal,deadlineAt:n.deadlineAt,mapFailure:F};if(oe(t.major,i.tool)){const u=await Qe(h,r.arguments,t.major),k=K(p.output,u);if(k)throw new l("provider_bad_response",`the libraries result has an invalid output field "${k.field}"`,{origin:"provider",param:k.field,details:{status:200,...k}});return{result:u,responder:void 0,cleanup:void 0}}let b=r.arguments,v=null,_="";if(Ke(t.major,i.tool,r.arguments)){const u=await Ve(h,r.arguments,t.major);if(n.deadlineAt-Date.now()<=0)throw te(c,"timeout","");u!==null&&(b=u.arguments,v=u.services,_=u.release)}const s=await He(c,{tool:i.tool,arguments:lr(p,b),version:t.major,requestId:n.requestId,runId:e.run_id,deadlineAt:n.deadlineAt,upload:r.upload===null?null:{id:r.upload.upload_id,link:r.upload.upload_link}},d,n.signal);if(n.signal.aborted)throw n.signal.reason??new Error("provider call aborted");if("unreachable"in s)throw te(c,s.unreachable.reason,s.unreachable.message);const j=s.headers["crtr-responder"],w=Q(s.body);if(s.status<200||s.status>=300){const u=Ge(c,s.status,typeof w.code=="string"?w.code:void 0,typeof w.message=="string"?w.message:void 0,s.body),k=u===null&&s.status>=500&&typeof w.code=="string"?new l("provider_error",typeof w.message=="string"?w.message:`the device answered HTTP ${s.status}`,{origin:"runtime",status:s.status,details:{code:w.code,status:s.status}}):null;throw Object.assign(u??k??F(s.status,s.body,s.headers),{responder:j})}const y=s.body&&typeof s.body=="object"&&!Array.isArray(s.body)?s.body.result:void 0;if(!y||typeof y!="object"||Array.isArray(y))throw Object.assign(new l("provider_bad_response","the device result is not a JSON object",{origin:"provider",details:{status:s.status,message:"the device result is not a JSON object"}}),{responder:j});let A=y;if(v!==null){const u=We(A,v);if(Xe(c,d,_,u.calls),"error"in u)throw Object.assign(u.error,{responder:j});A=u.result}let P;try{P=await re(e,r,A,{signal:n.signal})}catch(u){throw u instanceof l&&u.code==="provider_error"?Object.assign(new l("provider_bad_response",u.message,{origin:"provider",details:{status:s.status,message:u.message}}),{responder:j}):u}const o=K(p.output,P.result);if(o)throw await P.cleanup?.(),Object.assign(new l("provider_bad_response",`the device result has an invalid output field "${o.field}"`,{origin:"provider",param:o.field,details:{status:s.status,...o}}),{responder:j});return{result:P.result,responder:j,cleanup:P.cleanup}}m(pr,"callDevice");export{Jr as callProvider,ur as crtrCallerHeader,ar as identity,F as mapProviderResponse,ir as onProviderResponse,ie as providerLeaves,xr as providerTools};
@@ -1 +1 @@
1
- var g=Object.defineProperty;var d=(t,i)=>g(t,"name",{value:i,configurable:!0});import{RunError as _}from"../runs/operations.js";import{errorCodes as r}from"../../api/error-codes.js";const b={provider_error:{type:"invalid_request_error",status:400,retryable:!1},provider_rate_limited:r.provider_rate_limited,provider_unavailable:r.provider_unavailable,provider_refused:r.provider_refused,provider_not_connected:r.provider_not_connected,provider_version_retired:r.provider_version_retired,storage_unavailable:r.storage_unavailable,approval_pending:{...r.approval_pending,user_action:"answer_question"},user_denied:r.user_denied},q={unauthorized:r.unauthorized,grant_revoked:r.grant_revoked,machine_revoked:r.machine_revoked,scope_missing:r.scope_missing,permission_error:r.permission_error,invalid_request:r.invalid_request,not_found:r.not_found,not_implemented:r.not_implemented,runtime_starting:r.runtime_starting,server_error:r.server_error,provider_bad_response:r.provider_bad_response,invalid_argument:r.invalid_argument,machine_required:r.machine_required,device_offline:r.device_offline,device_timeout:r.device_timeout,device_disconnected:r.device_disconnected,peer_version_too_old:r.peer_version_too_old,outcome_unknown:{type:"invalid_request_error",status:409,retryable:!1},wrong_site:{type:"invalid_request_error",status:409,retryable:!1},site_signed_out:{type:"invalid_request_error",status:409,retryable:!1},js_exception:{type:"invalid_request_error",status:409,retryable:!1},lib_broken:{type:"server_error",status:502,retryable:!1}};function a(t,i){return b[t]??q[t]??(Object.prototype.hasOwnProperty.call(r,t)?r[t]:void 0)??{type:i===401?"authentication_error":i===403?"permission_error":i===429?"rate_limit_error":i>=500?"server_error":"invalid_request_error",status:i,retryable:i>=500}}d(a,"codeRow");class u extends _{static{d(this,"ProviderError")}origin;type;retry_after_s;question_id;user_action;run_id;constructor(i,o,n={}){const e=a(i,n.status??500);super(n.status??e.status,i,o,n.param,n.details,n.scope,e.retryable),this.type=e.type,this.origin=n.origin??"runtime",n.cause!==void 0&&(this.cause=n.cause),n.retry_after_s!==void 0&&(this.retry_after_s=n.retry_after_s),n.question_id!==void 0&&(this.question_id=n.question_id),n.run_id!==void 0&&(this.run_id=n.run_id),e.user_action!==void 0&&(this.user_action=e.user_action)}}function w(t){return new u("scope_missing",`missing scope ${t}`,{scope:t})}d(w,"scopeMissing");function h(t){if(!(t instanceof Error))return null;const{status:i,code:o,details:n,retryable:e}=t;return typeof i!="number"||typeof o!="string"||i<400||i>599?null:new _(i,o,t.message,void 0,n,void 0,typeof e=="boolean"?e:a(o,i).retryable)}d(h,"shaped");function x(t){if(t.code==="unauthorized"||t.code==="grant_revoked")return"reconnect";if(t.code==="scope_missing"&&t.scope)return`grant_scope:${t.scope}`}d(x,"directoryAction");function O(t,i,o,n){const e=t instanceof _?t:h(t)??new u("server_error","provider request failed"),s=e instanceof u?e:null,y=a(e.code,e.status),c=s?.run_id??n,p=e.details?.user_action,l=s?.user_action??(e.code==="cap_exhausted"?typeof p=="string"?p:void 0:o?x(e):void 0),f=e.code==="cap_exhausted"?e.details?.reset_at:void 0,m={code:e.code,message:e.message,...e.details===void 0?{}:{details:e.details},type:s?.type??y.type,...e.param?{param:e.param}:{},origin:s?.origin??"runtime",retryable:e.retryable,...s?.retry_after_s===void 0?{}:{retry_after_s:s.retry_after_s},...typeof f=="string"?{reset_at:f}:{},request_id:i,...c?{run_id:c}:{},...s?.question_id?{question_id:s.question_id}:{},...l?{user_action:l}:{},...e.scope?{scope:e.scope}:{}},v={"Request-Id":i};return s?.retry_after_s!==void 0&&(v["Retry-After"]=String(s.retry_after_s)),{status:e.status,body:{error:m},headers:v}}d(O,"providerErrorBody");export{b as PROVIDER_CODES,u as ProviderError,a as codeRow,O as providerErrorBody,w as scopeMissing};
1
+ var g=Object.defineProperty;var d=(t,i)=>g(t,"name",{value:i,configurable:!0});import{RunError as _}from"../runs/operations.js";import{errorCodes as r}from"../../api/error-codes.js";const b={provider_error:{type:"invalid_request_error",status:400,retryable:!1},provider_rate_limited:r.provider_rate_limited,provider_unavailable:r.provider_unavailable,provider_refused:r.provider_refused,provider_not_connected:r.provider_not_connected,provider_version_retired:r.provider_version_retired,storage_unavailable:r.storage_unavailable,approval_pending:{...r.approval_pending,user_action:"answer_question"},user_denied:r.user_denied},q={unauthorized:r.unauthorized,grant_revoked:r.grant_revoked,machine_revoked:r.machine_revoked,scope_missing:r.scope_missing,not_granted:r.not_granted,permission_error:r.permission_error,invalid_request:r.invalid_request,not_found:r.not_found,not_implemented:r.not_implemented,runtime_starting:r.runtime_starting,server_error:r.server_error,provider_bad_response:r.provider_bad_response,invalid_argument:r.invalid_argument,machine_required:r.machine_required,device_offline:r.device_offline,device_timeout:r.device_timeout,device_disconnected:r.device_disconnected,peer_version_too_old:r.peer_version_too_old,outcome_unknown:{type:"invalid_request_error",status:409,retryable:!1},wrong_site:{type:"invalid_request_error",status:409,retryable:!1},site_signed_out:{type:"invalid_request_error",status:409,retryable:!1},js_exception:{type:"invalid_request_error",status:409,retryable:!1},lib_broken:{type:"server_error",status:502,retryable:!1}};function a(t,i){return b[t]??q[t]??(Object.prototype.hasOwnProperty.call(r,t)?r[t]:void 0)??{type:i===401?"authentication_error":i===403?"permission_error":i===429?"rate_limit_error":i>=500?"server_error":"invalid_request_error",status:i,retryable:i>=500}}d(a,"codeRow");class u extends _{static{d(this,"ProviderError")}origin;type;retry_after_s;question_id;user_action;run_id;constructor(i,o,n={}){const e=a(i,n.status??500);super(n.status??e.status,i,o,n.param,n.details,n.scope,e.retryable),this.type=e.type,this.origin=n.origin??"runtime",n.cause!==void 0&&(this.cause=n.cause),n.retry_after_s!==void 0&&(this.retry_after_s=n.retry_after_s),n.question_id!==void 0&&(this.question_id=n.question_id),n.run_id!==void 0&&(this.run_id=n.run_id),e.user_action!==void 0&&(this.user_action=e.user_action)}}function w(t){return new u("scope_missing",`missing scope ${t}`,{scope:t})}d(w,"scopeMissing");function h(t){if(!(t instanceof Error))return null;const{status:i,code:o,details:n,retryable:e}=t;return typeof i!="number"||typeof o!="string"||i<400||i>599?null:new _(i,o,t.message,void 0,n,void 0,typeof e=="boolean"?e:a(o,i).retryable)}d(h,"shaped");function x(t){if(t.code==="unauthorized"||t.code==="grant_revoked")return"reconnect";if(t.code==="scope_missing"&&t.scope)return`grant_scope:${t.scope}`}d(x,"directoryAction");function O(t,i,o,n){const e=t instanceof _?t:h(t)??new u("server_error","provider request failed"),s=e instanceof u?e:null,y=a(e.code,e.status),c=s?.run_id??n,p=e.details?.user_action,l=s?.user_action??(e.code==="cap_exhausted"?typeof p=="string"?p:void 0:o?x(e):void 0),f=e.code==="cap_exhausted"?e.details?.reset_at:void 0,m={code:e.code,message:e.message,...e.details===void 0?{}:{details:e.details},type:s?.type??y.type,...e.param?{param:e.param}:{},origin:s?.origin??"runtime",retryable:e.retryable,...s?.retry_after_s===void 0?{}:{retry_after_s:s.retry_after_s},...typeof f=="string"?{reset_at:f}:{},request_id:i,...c?{run_id:c}:{},...s?.question_id?{question_id:s.question_id}:{},...l?{user_action:l}:{},...e.scope?{scope:e.scope}:{}},v={"Request-Id":i};return s?.retry_after_s!==void 0&&(v["Retry-After"]=String(s.retry_after_s)),{status:e.status,body:{error:m},headers:v}}d(O,"providerErrorBody");export{b as PROVIDER_CODES,u as ProviderError,a as codeRow,O as providerErrorBody,w as scopeMissing};
@@ -27,3 +27,22 @@ export declare function mintOutboundToken(request: OutboundTokenRequest, options
27
27
  /** The outbound token for `request`: the cached one while `now < exp − 30 s`
28
28
  * (D3-TOK-9), else a fresh mint, cached. Throws a mapped `ProviderError`. */
29
29
  export declare function outboundToken(request: OutboundTokenRequest, options?: MintOptions): Promise<OutboundToken>;
30
+ /** What an acting-for exchange asks the directory (RFC 8693): the node's own call token, the owner principal it acts for, and the call's audience and scope. */
31
+ export interface ExchangeRequest {
32
+ subjectToken: string;
33
+ as: string;
34
+ audience: string;
35
+ scope: readonly string[];
36
+ }
37
+ /** Exchange a node's call token for one whose `sub` is `request.as` and whose `act` is the node (the directory's token exchange). A refusal is 403
38
+ * `not_granted` or `scope_missing`; any other failure is a `server_error`. Nothing is cached: the token is for this call. */
39
+ export declare function exchangeForOwner(request: ExchangeRequest, options?: MintOptions): Promise<CachedToken>;
40
+ /** The token a node presents to act for `as`: its own call token (minted as its `sub` and `grantee`), exchanged at the directory. In the node's own namespace
41
+ * the node mints directly as `as` (an owner link) and no exchange runs. */
42
+ export declare function actingToken(node: {
43
+ sub: string;
44
+ grantee: string;
45
+ }, as: string, call: {
46
+ audience: string;
47
+ scope: readonly string[];
48
+ }, options?: MintOptions): Promise<OutboundToken>;
@@ -1 +1 @@
1
- var E=Object.defineProperty;var c=(r,e)=>E(r,"name",{value:e,configurable:!0});import{createHash as M}from"node:crypto";import{directoryIssuer as j}from"../directory/issuer.js";import{emitEvent as $}from"../events/emit.js";import{OutboundError as A}from"../events/outbound.js";import{grantSyncStateFor as I}from"../grants/mirror.js";import{assertion as N,machineRevokedMessage as O,requestGrantSync as P,runtimeClient as L}from"../grants/sync.js";import{isUnsandboxedMachine as D}from"../runtime/unsandboxed.js";import{ProviderError as g}from"./errors.js";import{cacheKey as F,cachedToken as G,discardEpoch as U,storeToken as J}from"./token-cache.js";import{discardFile as le}from"./token-cache.js";const Y=1e4,B=[300,900];function C(r){const e=r.issuer??j();if(!e)throw new g("not_found","provider calls need a directory-connected runtime");return e}c(C,"issuerOf");function h(r,e,t){return new g(r,e,{origin:"directory",details:t})}c(h,"directoryError");function H(r,e,t,i){const n=typeof e.error=="string"?e.error:null,s=typeof e.error_description=="string"?e.error_description:void 0,o={directory_status:r,...n?{directory_error:n}:{},...s?{directory_description:s}:{}},d=s?`: ${s}`:"";switch(n){case"invalid_client":return D()?{error:h("machine_revoked",O(i),o),grantRefusal:!1}:{error:h("server_error",`the directory refused the outbound token request (${n})${d}`,o),grantRefusal:!1};case"invalid_request":return{error:h("server_error",`the directory refused the outbound token request (${n})${d}`,o),grantRefusal:!1};case"invalid_target":return{error:h("not_found",`the directory knows no provider at ${t.audience}${d}`,o),grantRefusal:!1};case"invalid_grant":return{error:h("grant_revoked",`the directory has no active grant for ${t.grantee}${d}`,o),grantRefusal:!0};case"provider_not_connected":return{error:h("provider_not_connected",s??"The user has not connected this provider.",o),grantRefusal:!1};case"invalid_scope":{const a=typeof e.scope=="string"&&e.scope?e.scope:t.scope.length===1?t.scope[0]:void 0,l=a?`missing scope ${a}`:`the grant does not cover ${t.scope.join(" ")}`;return{error:new g("scope_missing",l,{origin:"directory",details:o,...a?{scope:a}:{}}),grantRefusal:!0}}default:return{error:h("server_error",`the directory token endpoint answered ${r}${n?` ${n}`:""}${d}`,o),grantRefusal:!1}}}c(H,"refusal");function K(r){try{return JSON.parse(Buffer.from(r.split(".")[1]??"","base64url").toString("utf8"))}catch{return{}}}c(K,"claims");function z(r){const e=r.grant_rev,t=r.grant_status;return typeof e!="number"||!Number.isInteger(e)||e<0||typeof t!="string"?null:{rev:e,status:t}}c(z,"refusedGrantState");function Q(r,e){const t=c(i=>i.status==="active"?0:1,"phase");return r.rev>e.rev||r.rev===e.rev&&t(r)>t(e)}c(Q,"newer");async function V(r,e,t){if(!e)return;const i=await I(r.grantee,r.sub)??{rev:0,status:"removed"};if(!Q(e,i))return;const n=t.syncGrants??P;Promise.resolve().then(()=>n({fresh:!0})).catch(()=>{})}c(V,"syncIfNewer");async function W(r,e={}){const t=C(e),i=`${t}/token`,n=L(),s=c(async()=>{const u=new URLSearchParams({grant_type:"client_credentials",client_id:n.client_id,client_assertion_type:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer",client_assertion:N(n,i),audience:r.audience,sub:r.sub,grantee:r.grantee,scope:[...new Set(r.scope)].sort().join(" "),initiating_app:r.initiating_app}),p=AbortSignal.timeout(Y),w=e.signal?AbortSignal.any([e.signal,p]):p,S=await(e.fetch??fetch)(i,{method:"POST",body:u,signal:w,headers:{Accept:"application/json"}});return{response:S,text:await S.text()}},"attempt");let o,d;try{for(let u=0;;u++){({response:o,text:d}=await s());const p=B[u];if(p===void 0||![502,503,504].includes(o.status))break;await new Promise(w=>setTimeout(w,p))}}catch(u){throw e.signal?.aborted?e.signal.reason:new g("server_error",`the directory token endpoint could not be reached: ${u instanceof Error?u.message:String(u)}`,{origin:"directory",cause:new A("directory_token",i,u)})}let a=null;try{a=d?JSON.parse(d):null}catch{a=null}const l=a&&typeof a=="object"&&!Array.isArray(a)?a:{};if(!o.ok){const{error:u,grantRefusal:p}=H(o.status,l,r,t);throw u.code==="machine_revoked"&&$({level:"error",event:"daemon.grants.machine_revoked",fields:{audience:r.audience}}),$({level:"info",event:"daemon.providers.mint_refused",fields:{audience:r.audience,grantee:r.grantee,code:u.code,directory_error:typeof l.error=="string"?l.error:null,status:o.status}}),p&&await V(r,z(l),e),u}const m=l.access_token;if(typeof m!="string"||!m)throw new g("server_error","the directory token response has no access_token",{origin:"directory"});const f=K(m),x=Math.floor((e.now?.()??Date.now())/1e3),y=l.expires_in,_=typeof y=="number"&&Number.isFinite(y)&&y>0?x+Math.floor(y):null,v=typeof f.exp=="number"?f.exp:null,b=_!==null&&v!==null?Math.min(_,v):_??v;if(b===null)throw new g("server_error","the directory token response names no expiry",{origin:"directory"});const R=typeof f.jti=="string"&&f.jti?f.jti:M("sha256").update(m).digest("hex"),T=typeof f.payer=="string"&&f.payer?f.payer:r.sub;return{access_token:m,jti:R,exp:b,payer:T}}c(W,"mintOutboundToken");const k=new Map;async function ce(r,e={}){const t=F(r),i=e.now??Date.now,n=G(t,i());if(n)return{...n,key:t};let s=k.get(t);if(!s){const d=U(t);s=W(r,{...e,signal:void 0}).then(a=>(J(t,a,d),a)).finally(()=>{k.delete(t)}),s.catch(()=>{}),k.set(t,s)}return{...e.signal?await X(s,e.signal):await s,key:t}}c(ce,"outboundToken");function X(r,e){return e.aborted?Promise.reject(e.reason):new Promise((t,i)=>{const n=c(()=>i(e.reason),"onAbort");e.addEventListener("abort",n,{once:!0}),r.then(t,i).finally(()=>e.removeEventListener("abort",n))})}c(X,"abortable");export{B as MINT_RETRY_DELAYS_MS,Y as MINT_TIMEOUT_MS,le as discardFile,W as mintOutboundToken,ce as outboundToken};
1
+ var k=Object.defineProperty;var u=(e,r)=>k(e,"name",{value:r,configurable:!0});import{createHash as b}from"node:crypto";import{directoryIssuer as $}from"../directory/issuer.js";import{emitEvent as y}from"../events/emit.js";import{OutboundError as x}from"../events/outbound.js";import{sameNamespace as j}from"../grants/owner.js";import{grantSyncStateFor as S}from"../grants/mirror.js";import{assertion as T,machineRevokedMessage as R,requestGrantSync as E,runtimeClient as M}from"../grants/sync.js";import{isUnsandboxedMachine as O}from"../runtime/unsandboxed.js";import{ProviderError as f}from"./errors.js";import{cacheKey as N,cachedToken as A,discardEpoch as I,storeToken as P}from"./token-cache.js";import{discardFile as se}from"./token-cache.js";const F=1e4,L=[300,900];function _(e){const r=e.issuer??$();if(!r)throw new f("not_found","provider calls need a directory-connected runtime");return r}u(_,"issuerOf");function p(e,r,t){return new f(e,r,{origin:"directory",details:t})}u(p,"directoryError");function D(e,r,t,o){const n=typeof r.error=="string"?r.error:null,i=typeof r.error_description=="string"?r.error_description:void 0,s={directory_status:e,...n?{directory_error:n}:{},...i?{directory_description:i}:{}},c=i?`: ${i}`:"";switch(n){case"invalid_client":return O()?{error:p("machine_revoked",R(o),s),grantRefusal:!1}:{error:p("server_error",`the directory refused the outbound token request (${n})${c}`,s),grantRefusal:!1};case"invalid_request":return{error:p("server_error",`the directory refused the outbound token request (${n})${c}`,s),grantRefusal:!1};case"invalid_target":return{error:p("not_found",`the directory knows no provider at ${t.audience}${c}`,s),grantRefusal:!1};case"invalid_grant":return{error:p("grant_revoked",`the directory has no active grant for ${t.grantee}${c}`,s),grantRefusal:!0};case"provider_not_connected":return{error:p("provider_not_connected",i??"The user has not connected this provider.",s),grantRefusal:!1};case"invalid_scope":{const a=typeof r.scope=="string"&&r.scope?r.scope:t.scope.length===1?t.scope[0]:void 0,d=a?`missing scope ${a}`:`the grant does not cover ${t.scope.join(" ")}`;return{error:new f("scope_missing",d,{origin:"directory",details:s,...a?{scope:a}:{}}),grantRefusal:!0}}default:return{error:p("server_error",`the directory token endpoint answered ${e}${n?` ${n}`:""}${c}`,s),grantRefusal:!1}}}u(D,"refusal");function G(e){try{return JSON.parse(Buffer.from(e.split(".")[1]??"","base64url").toString("utf8"))}catch{return{}}}u(G,"claims");function U(e){const r=e.grant_rev,t=e.grant_status;return typeof r!="number"||!Number.isInteger(r)||r<0||typeof t!="string"?null:{rev:r,status:t}}u(U,"refusedGrantState");function J(e,r){const t=u(o=>o.status==="active"?0:1,"phase");return e.rev>r.rev||e.rev===r.rev&&t(e)>t(r)}u(J,"newer");async function Y(e,r,t){if(!r)return;const o=await S(e.grantee,e.sub)??{rev:0,status:"removed"};if(!J(r,o))return;const n=t.syncGrants??E;Promise.resolve().then(()=>n({fresh:!0})).catch(()=>{})}u(Y,"syncIfNewer");async function m(e,r,t){const o=M(),n=u(async()=>{const a=new URLSearchParams({client_id:o.client_id,client_assertion_type:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer",client_assertion:T(o,e),...r(o)}),d=AbortSignal.timeout(F),l=t.signal?AbortSignal.any([t.signal,d]):d,g=await(t.fetch??fetch)(e,{method:"POST",body:a,signal:l,headers:{Accept:"application/json"}});return{response:g,text:await g.text()}},"attempt");let i,s;try{for(let a=0;;a++){({response:i,text:s}=await n());const d=L[a];if(d===void 0||![502,503,504].includes(i.status))break;await new Promise(l=>setTimeout(l,d))}}catch(a){throw t.signal?.aborted?t.signal.reason:new f("server_error",`the directory token endpoint could not be reached: ${a instanceof Error?a.message:String(a)}`,{origin:"directory",cause:new x("directory_token",e,a)})}let c=null;try{c=s?JSON.parse(s):null}catch{c=null}return{response:i,json:c&&typeof c=="object"&&!Array.isArray(c)?c:{}}}u(m,"postToken");function w(e,r,t){const o=e.access_token;if(typeof o!="string"||!o)throw new f("server_error","the directory token response has no access_token",{origin:"directory"});const n=G(o),i=Math.floor((t.now?.()??Date.now())/1e3),s=e.expires_in,c=typeof s=="number"&&Number.isFinite(s)&&s>0?i+Math.floor(s):null,a=typeof n.exp=="number"?n.exp:null,d=c!==null&&a!==null?Math.min(c,a):c??a;if(d===null)throw new f("server_error","the directory token response names no expiry",{origin:"directory"});const l=typeof n.jti=="string"&&n.jti?n.jti:b("sha256").update(o).digest("hex"),g=typeof n.payer=="string"&&n.payer?n.payer:r;return{access_token:o,jti:l,exp:d,payer:g}}u(w,"tokenOf");async function B(e,r={}){const t=_(r),o=`${t}/token`,{response:n,json:i}=await m(o,()=>({grant_type:"client_credentials",audience:e.audience,sub:e.sub,grantee:e.grantee,scope:[...new Set(e.scope)].sort().join(" "),initiating_app:e.initiating_app}),r);if(!n.ok){const{error:s,grantRefusal:c}=D(n.status,i,e,t);throw s.code==="machine_revoked"&&y({level:"error",event:"daemon.grants.machine_revoked",fields:{audience:e.audience}}),y({level:"info",event:"daemon.providers.mint_refused",fields:{audience:e.audience,grantee:e.grantee,code:s.code,directory_error:typeof i.error=="string"?i.error:null,status:n.status}}),c&&await Y(e,U(i),r),s}return w(i,e.sub,r)}u(B,"mintOutboundToken");const h=new Map;async function v(e,r={}){const t=N(e),o=r.now??Date.now,n=A(t,o());if(n)return{...n,key:t};let i=h.get(t);if(!i){const c=I(t);i=B(e,{...r,signal:void 0}).then(a=>(P(t,a,c),a)).finally(()=>{h.delete(t)}),i.catch(()=>{}),h.set(t,i)}return{...r.signal?await C(i,r.signal):await i,key:t}}u(v,"outboundToken");function C(e,r){return r.aborted?Promise.reject(r.reason):new Promise((t,o)=>{const n=u(()=>o(r.reason),"onAbort");r.addEventListener("abort",n,{once:!0}),e.then(t,o).finally(()=>r.removeEventListener("abort",n))})}u(C,"abortable");async function H(e,r={}){const{response:t,json:o}=await m(`${_(r)}/token`,()=>({grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token:e.subjectToken,subject_token_type:"urn:ietf:params:oauth:token-type:access_token",requested_subject:e.as,audience:e.audience,scope:[...new Set(e.scope)].sort().join(" ")}),r);if(!t.ok){const n=typeof o.error_description=="string"?o.error_description:void 0,i={directory_status:t.status,...typeof o.error=="string"?{directory_error:o.error}:{},...n?{directory_description:n}:{}};throw o.error==="invalid_grant"&&n==="not_granted"?new f("not_granted",`${e.as} has not granted this caller access`,{origin:"directory",details:i}):o.error==="invalid_grant"&&n==="scope_missing"?new f("scope_missing",`the grant from ${e.as} does not cover ${e.scope.join(" ")}`,{origin:"directory",details:i,...e.scope.length===1?{scope:e.scope[0]}:{}}):new f("server_error",`the directory refused the token exchange (${t.status}${n?` ${n}`:""})`,{origin:"directory",details:i})}return w(o,e.as,r)}u(H,"exchangeForOwner");async function ne(e,r,t,o={}){if(j(r,e.grantee))return await v({...t,sub:r,grantee:e.grantee,initiating_app:e.grantee},o);const n=await v({...t,sub:e.sub,grantee:e.grantee,initiating_app:e.grantee},o),i=await H({subjectToken:n.access_token,as:r,audience:t.audience,scope:t.scope},o);return{...i,key:`exchange:${i.jti}`}}u(ne,"actingToken");export{L as MINT_RETRY_DELAYS_MS,F as MINT_TIMEOUT_MS,ne as actingToken,se as discardFile,H as exchangeForOwner,B as mintOutboundToken,v as outboundToken};
@@ -1,9 +1,9 @@
1
- var x=Object.defineProperty;var r=(e,t)=>x(e,"name",{value:t,configurable:!0});import{createHash as T}from"node:crypto";import{withCanvasWrite as g}from"../../../core/canvas/db.js";import{canRead as k}from"../../../core/graph/access.js";import{permits as M}from"../../../core/permissions/evaluator.js";import{get as b}from"../../../core/graph/bodies.js";import{ownerForGrantee as C}from"../../../core/graph/objects.js";import{readerFor as F}from"../../../core/graph/reader.js";import{checkoutsForCwd as H}from"../../../core/graph/repo-sync/repos.js";import{RunError as h}from"../../../core/runs/operations.js";import{mapAsync as j}from"../../../core/async-array.js";import{personId as B}from"../../../core/canvas/person.js";const ut=new Set(["memory.list","memory.get"]),W=1024*1024,w=/^[A-Za-z0-9_-]+(\/[A-Za-z0-9_-]+)*$/,N=["knowledge","preference"],i=r((e,t)=>new h(400,"invalid_request",e,t),"invalid"),O=r(()=>new h(404,"not_found","no memory document by that name"),"notFound");function _(e){const t=e.get("store");if(t===null)throw i("store is required","store");if(t!=="user")throw i('store must be "user"',"store")}r(_,"store");function J(e){const t=e.get("kind");if(t===null)return null;if(!N.includes(t))throw i("kind must be knowledge or preference","kind");return t}r(J,"kindOf");function Y(e){const t=e.get("limit");if(t===null)return 50;if(!/^(0|[1-9]\d*)$/.test(t)||Number(t)<1||Number(t)>100)throw i("limit must be an integer from 1 to 100","limit");return Number(t)}r(Y,"limitOf");function U(e,t){return T("sha256").update(JSON.stringify(["user",e,t])).digest("base64url").slice(0,16)}r(U,"filterHash");function $(e,t){return Buffer.from(JSON.stringify({n:e,f:t}),"utf8").toString("base64url")}r($,"encodeCursor");function z(e,t){if(e===null)return null;try{if(!/^[A-Za-z0-9_-]+$/.test(e))throw new Error("not base64url");const n=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));if(typeof n.n=="string"&&w.test(n.n)&&n.f===t)return n.n}catch{}throw i("cursor is not the next_cursor of a previous page with the same store, path and kind","cursor")}r(z,"decodeCursor");async function R(e){return await C(e,B())}r(R,"personObject");async function v(e,t){return await F(e,t,async(n,o)=>await H(e,n,o))}r(v,"graphReader");async function S(e,t){const n=await e.prepare(`SELECT r.body_hash, r.created_at FROM revisions r WHERE r.document = ?
2
- AND NOT EXISTS (SELECT 1 FROM revision_parents p WHERE p.parent = r.rev_id) ORDER BY r.number DESC, r.rev_id LIMIT 1`).get(t.id),o=await e.prepare("SELECT created_at, author FROM revisions WHERE document = ? ORDER BY number, created_at LIMIT 1").get(t.id);if(!n||!o)throw O();return{head:n,first:o}}r(S,"revisions");async function A(e,t){const{head:n,first:o}=await S(e,t),a=t.name.lastIndexOf("/");return{name:t.name,folder:a<0?"":t.name.slice(0,a),kind:t.kind,preview:t.preview,summary:t.summary,privacy:t.privacy,revision:t.revision,created_at:o.created_at,updated_at:n.created_at}}r(A,"item");async function G(e,t){return t===null?null:(await e.prepare(`SELECT i.external_id FROM objects a LEFT JOIN nodes n ON n.node_id = a.id
1
+ var x=Object.defineProperty;var r=(e,t)=>x(e,"name",{value:t,configurable:!0});import{createHash as T}from"node:crypto";import{withCanvasWrite as E}from"../../../core/canvas/db.js";import{canRead as k}from"../../../core/graph/access.js";import{permits as M}from"../../../core/permissions/evaluator.js";import{get as b}from"../../../core/graph/bodies.js";import{ownerForGrantee as F}from"../../../core/graph/objects.js";import{actingReaderFor as C,readerFor as H}from"../../../core/graph/reader.js";import{checkoutsForCwd as j}from"../../../core/graph/repo-sync/repos.js";import{RunError as h}from"../../../core/runs/operations.js";import{mapAsync as B}from"../../../core/async-array.js";import{personId as W}from"../../../core/canvas/person.js";const ct=new Set(["memory.list","memory.get"]),J=1024*1024,w=/^[A-Za-z0-9_-]+(\/[A-Za-z0-9_-]+)*$/,N=["knowledge","preference"],i=r((e,t)=>new h(400,"invalid_request",e,t),"invalid"),O=r(()=>new h(404,"not_found","no memory document by that name"),"notFound");function _(e){const t=e.get("store");if(t===null)throw i("store is required","store");if(t!=="user")throw i('store must be "user"',"store")}r(_,"store");function Y(e){const t=e.get("kind");if(t===null)return null;if(!N.includes(t))throw i("kind must be knowledge or preference","kind");return t}r(Y,"kindOf");function U(e){const t=e.get("limit");if(t===null)return 50;if(!/^(0|[1-9]\d*)$/.test(t)||Number(t)<1||Number(t)>100)throw i("limit must be an integer from 1 to 100","limit");return Number(t)}r(U,"limitOf");function $(e,t){return T("sha256").update(JSON.stringify(["user",e,t])).digest("base64url").slice(0,16)}r($,"filterHash");function z(e,t){return Buffer.from(JSON.stringify({n:e,f:t}),"utf8").toString("base64url")}r(z,"encodeCursor");function G(e,t){if(e===null)return null;try{if(!/^[A-Za-z0-9_-]+$/.test(e))throw new Error("not base64url");const n=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));if(typeof n.n=="string"&&w.test(n.n)&&n.f===t)return n.n}catch{}throw i("cursor is not the next_cursor of a previous page with the same store, path and kind","cursor")}r(G,"decodeCursor");async function R(e){return await F(e,W())}r(R,"personObject");async function v(e,t,n=null){const o=r(async(a,c)=>await j(e,a,c),"reposFn");return n===null?await H(e,t,o):await C(e,t,o,n)}r(v,"graphReader");async function S(e,t){const n=await e.prepare(`SELECT r.body_hash, r.created_at FROM revisions r WHERE r.document = ?
2
+ AND NOT EXISTS (SELECT 1 FROM revision_parents p WHERE p.parent = r.rev_id) ORDER BY r.number DESC, r.rev_id LIMIT 1`).get(t.id),o=await e.prepare("SELECT created_at, author FROM revisions WHERE document = ? ORDER BY number, created_at LIMIT 1").get(t.id);if(!n||!o)throw O();return{head:n,first:o}}r(S,"revisions");async function A(e,t){const{head:n,first:o}=await S(e,t),a=t.name.lastIndexOf("/");return{name:t.name,folder:a<0?"":t.name.slice(0,a),kind:t.kind,preview:t.preview,summary:t.summary,privacy:t.privacy,revision:t.revision,created_at:o.created_at,updated_at:n.created_at}}r(A,"item");async function Z(e,t){return t===null?null:(await e.prepare(`SELECT i.external_id FROM objects a LEFT JOIN nodes n ON n.node_id = a.id
3
3
  JOIN identities i ON i.object = CASE WHEN a.type = 'node' THEN n.app ELSE a.id END AND i.scheme = 'app'
4
- WHERE a.id = ?`).get(t))?.external_id??null}r(G,"granteeOf");function Z(e,t){if(e.length<=t)return e;let n=t;for(;n>0&&(e[n]&192)===128;)n--;return e.subarray(0,n)}r(Z,"utf8Prefix");async function P(e,t){_(t);const n=t.get("path");if(n!==null&&!w.test(n))throw i("path must be name segments of letters, digits, `_` or `-` joined by `/`","path");const o=J(t),a=Y(t),d=U(n,o),s=z(t.get("cursor"),d);return await g(async u=>{const l=await v(u,e),c=await R(u),m=n===null?null:`${n}/`,f=o===null?N:[o],y=await M(u,l,"read"),E=await u.prepareUncached(`SELECT o.*, d.summary, d.revision, d.source_path FROM objects o JOIN documents d ON d.object = o.id
4
+ WHERE a.id = ?`).get(t))?.external_id??null}r(Z,"granteeOf");function P(e,t){if(e.length<=t)return e;let n=t;for(;n>0&&(e[n]&192)===128;)n--;return e.subarray(0,n)}r(P,"utf8Prefix");async function X(e,t){_(t);const n=t.get("path");if(n!==null&&!w.test(n))throw i("path must be name segments of letters, digits, `_` or `-` joined by `/`","path");const o=Y(t),a=U(t),c=$(n,o),s=G(t.get("cursor"),c);return await E(async u=>{const l=await v(u,e,t.get("as")),m=await R(u),d=n===null?null:`${n}/`,f=o===null?N:[o],y=await M(u,l,"read"),g=await u.prepareUncached(`SELECT o.*, d.summary, d.revision, d.source_path FROM objects o JOIN documents d ON d.object = o.id
5
5
  WHERE o.owner = ? AND o.type = 'document' AND o.deleted_at IS NULL AND d.unlisted = 0
6
6
  AND o.kind IN (?, ?) AND (?::text IS NULL OR starts_with(o.name, ?::text)) AND (?::text IS NULL OR o.name > ?::text)
7
7
  AND ${y.sql}
8
- ORDER BY o.name LIMIT ?`).all(c.id,f[0],f[f.length-1],m,m,s,s,...y.params,a+1),p=E.slice(0,a),D=E.length>a;return{items:await j(p,async L=>await A(u,L)),next_cursor:D?$(p[p.length-1].name,d):null}})}r(P,"memoryList");async function X(e,t){_(t);const n=t.get("name");if(n===null)throw i("name is required","name");if(!w.test(n))throw i("name must be segments of letters, digits, `_` or `-` joined by `/`","name");return await g(async o=>{const a=await v(o,e),d=await R(o),s=await o.prepare(`SELECT o.*, d.summary, d.revision, d.source_path FROM objects o JOIN documents d ON d.object = o.id
9
- WHERE o.owner = ? AND o.type = 'document' AND o.name = ? AND o.deleted_at IS NULL AND o.kind IN ('knowledge', 'preference')`).get(d.id,n);if(!s||!await k(o,a,s))throw O();const{head:u,first:l}=await S(o,s),c=Buffer.from(await b(o,u.body_hash),"utf8"),m=Z(c,W);return{...await A(o,s),body:m.toString("utf8"),size:c.length,truncated:m.length<c.length,grantee:await G(o,l.author)}})}r(X,"memoryGet");async function I(e,t,n){if(e==="memory.list")return{status:200,body:await P(t,n)};if(e==="memory.get")return{status:200,body:await X(t,n)};throw new h(404,"not_found","unknown operation")}r(I,"handleMemoryOperation");const ct=[{method:"GET",pattern:"/v1/memory",handler:r(async e=>await I("memory.list",e.principal,e.query),"handler")},{method:"GET",pattern:"/v1/memory/document",handler:r(async e=>await I("memory.get",e.principal,e.query),"handler")}];export{W as MEMORY_BODY_MAX_BYTES,ut as MEMORY_OPERATIONS,I as handleMemoryOperation,X as memoryGet,P as memoryList,ct as memoryRoutes,Z as utf8Prefix};
8
+ ORDER BY o.name LIMIT ?`).all(m.id,f[0],f[f.length-1],d,d,s,s,...y.params,a+1),p=g.slice(0,a),D=g.length>a;return{items:await B(p,async L=>await A(u,L)),next_cursor:D?z(p[p.length-1].name,c):null}})}r(X,"memoryList");async function K(e,t){_(t);const n=t.get("name");if(n===null)throw i("name is required","name");if(!w.test(n))throw i("name must be segments of letters, digits, `_` or `-` joined by `/`","name");return await E(async o=>{const a=await v(o,e,t.get("as")),c=await R(o),s=await o.prepare(`SELECT o.*, d.summary, d.revision, d.source_path FROM objects o JOIN documents d ON d.object = o.id
9
+ WHERE o.owner = ? AND o.type = 'document' AND o.name = ? AND o.deleted_at IS NULL AND o.kind IN ('knowledge', 'preference')`).get(c.id,n);if(!s||!await k(o,a,s))throw O();const{head:u,first:l}=await S(o,s),m=Buffer.from(await b(o,u.body_hash),"utf8"),d=P(m,J);return{...await A(o,s),body:d.toString("utf8"),size:m.length,truncated:d.length<m.length,grantee:await Z(o,l.author)}})}r(K,"memoryGet");async function I(e,t,n){if(e==="memory.list")return{status:200,body:await X(t,n)};if(e==="memory.get")return{status:200,body:await K(t,n)};throw new h(404,"not_found","unknown operation")}r(I,"handleMemoryOperation");const mt=[{method:"GET",pattern:"/v1/memory",handler:r(async e=>await I("memory.list",e.principal,e.query),"handler")},{method:"GET",pattern:"/v1/memory/document",handler:r(async e=>await I("memory.get",e.principal,e.query),"handler")}];export{J as MEMORY_BODY_MAX_BYTES,ct as MEMORY_OPERATIONS,I as handleMemoryOperation,K as memoryGet,X as memoryList,mt as memoryRoutes,P as utf8Prefix};
@@ -1 +1 @@
1
- var h=Object.defineProperty;var o=(e,n)=>h(e,"name",{value:n,configurable:!0});import{ApiError as l}from"../../../api/errors.js";import{getNode as g}from"../../../core/canvas/canvas.js";import{formatCrtrCaller as y}from"../../../core/command-plugins/caller-header.js";import{isLoopbackHostname as w}from"../../../core/command-plugins/endpoint.js";import{crtrSignature as _}from"../../../core/command-plugins/transport/sign.js";import{ownMachineId as k}from"../../../core/peer/directory.js";import{directoryIssuer as b}from"../../../core/directory/issuer.js";import{pluginAppCredential as m}from"../../../core/plugin-app.js";import{findPluginByName as v}from"../../../core/resolver.js";import{isRecord as C}from"./validate.js";const c=/^[0-9a-f]{64}$/,p=o(e=>{throw new l(404,"not_found",`plugin "${e}" is not installed, enabled and valid`)},"notFound");function A(e){const{principal:n}=e;if(n.class==="broker"&&n.uid!==process.getuid?.())throw new l(403,"forbidden","this node may not read a plugin app token");const r=e.params.name,t=m(r);return t===null?p(r):{status:200,body:{token:t.token,socket:t.socket}}}o(A,"appToken");function R(e){const n=o(i=>{throw new l(400,"invalid_request",`invalid ${i}`)},"bad");if(!C(e))return n("call-headers request");const{method:r,url:t,body_sha256:s,header_names:d,headers_sha256:a}=e;return(typeof r!="string"||r==="")&&n("method"),typeof t!="string"&&n("url"),(typeof s!="string"||!c.test(s))&&n("body_sha256"),(!Array.isArray(d)||d.some(i=>typeof i!="string"))&&n("header_names"),(typeof a!="string"||!c.test(a))&&n("headers_sha256"),e}o(R,"parseRequest");async function E(e){if(e.class==="forwarded"){const r=e.actor.kind==="app"?e.actor:null;return{node:r?.node??void 0,run:r?.place.run,machine:e.via}}const n=e.class==="broker"?e.node:void 0;return{...n===void 0?{}:{node:n,run:e.class==="broker"?e.run??void 0:void 0,profile:(await g(n))?.profile_id??void 0},machine:b()!==null?k():void 0}}o(E,"callerFields");async function H(e,n,r){const t=v(e);if(t===null||!t.enabled||t.manifest.provider!==void 0)return p(e);const s=y(await E(n)),d={};s!==""&&(d["Crtr-Caller"]=s);const a=m(e);if(a!==null&&a.endpoint!==null){let i;try{i=new URL(r.url)}catch{throw new l(400,"invalid_request","invalid url")}const u=new URL(a.endpoint);if(i.origin===u.origin&&w(u.hostname))try{d["Crtr-Signature"]=_({token:a.token,method:r.method,url:i,body_sha256:r.body_sha256,caller:s,header_names:r.header_names,headers_sha256:r.headers_sha256,now:Date.now()})}catch(f){throw new l(400,"invalid_request",f instanceof Error?f.message:"invalid signed header list")}}return{headers:d}}o(H,"signCallHeaders");async function L(e){return{status:200,body:await H(e.params.name,e.principal,R(e.body))}}o(L,"callHeaders");const G=[{method:"GET",pattern:"/v1/plugins/:name/app-token",handler:A},{method:"POST",pattern:"/v1/plugins/:name/call-headers",handler:L}];export{G as pluginAppRoutes,H as signCallHeaders};
1
+ var g=Object.defineProperty;var s=(e,n)=>g(e,"name",{value:n,configurable:!0});import{parsePrincipal as w}from"@north-light/identity";import{sameNamespace as y}from"../../../core/grants/owner.js";import{ApiError as u}from"../../../api/errors.js";import{getNode as _}from"../../../core/canvas/canvas.js";import{formatCrtrCaller as k}from"../../../core/command-plugins/caller-header.js";import{isLoopbackHostname as b}from"../../../core/command-plugins/endpoint.js";import{crtrSignature as v}from"../../../core/command-plugins/transport/sign.js";import{ownMachineId as C}from"../../../core/peer/directory.js";import{directoryIssuer as A}from"../../../core/directory/issuer.js";import{pluginAppCredential as c}from"../../../core/plugin-app.js";import{findPluginByName as R}from"../../../core/resolver.js";import{isRecord as E}from"./validate.js";const p=/^[0-9a-f]{64}$/,h=s(e=>{throw new u(404,"not_found",`plugin "${e}" is not installed, enabled and valid`)},"notFound");function H(e){const{principal:n}=e;if(n.class==="broker"&&n.uid!==process.getuid?.())throw new u(403,"forbidden","this node may not read a plugin app token");const r=e.params.name,t=c(r);return t===null?h(r):{status:200,body:{token:t.token,socket:t.socket}}}s(H,"appToken");function $(e){const n=s(a=>{throw new u(400,"invalid_request",`invalid ${a}`)},"bad");if(!E(e))return n("call-headers request");const{method:r,url:t,body_sha256:o,header_names:i,headers_sha256:d}=e;return(typeof r!="string"||r==="")&&n("method"),typeof t!="string"&&n("url"),(typeof o!="string"||!p.test(o))&&n("body_sha256"),(!Array.isArray(i)||i.some(a=>typeof a!="string"))&&n("header_names"),(typeof d!="string"||!p.test(d))&&n("headers_sha256"),e.as!==void 0&&(typeof e.as!="string"||w(e.as)===null)&&n("as"),e}s($,"parseRequest");async function L(e){if(e.class==="forwarded"){const r=e.actor.kind==="app"?e.actor:null;return{node:r?.node??void 0,run:r?.place.run,machine:e.via}}const n=e.class==="broker"?e.node:void 0;return{...n===void 0?{}:{node:n,run:e.class==="broker"?e.run??void 0:void 0,profile:(await _(n))?.profile_id??void 0},machine:A()!==null?C():void 0}}s(L,"callerFields");async function N(e,n,r){const t=R(e);if(t===null||!t.enabled||t.manifest.provider!==void 0)return h(e);const o=r.as;if(o!==void 0){const l=n.class==="broker"?n.app:null;if(l===null||!y(o,l))throw new u(403,"not_granted",`${o} has not granted this caller access`)}const i=k({...await L(n),...o===void 0?{}:{as:o}}),d={};i!==""&&(d["Crtr-Caller"]=i);const a=c(e);if(a!==null&&a.endpoint!==null){let l;try{l=new URL(r.url)}catch{throw new u(400,"invalid_request","invalid url")}const f=new URL(a.endpoint);if(l.origin===f.origin&&b(f.hostname))try{d["Crtr-Signature"]=v({token:a.token,method:r.method,url:l,body_sha256:r.body_sha256,caller:i,header_names:r.header_names,headers_sha256:r.headers_sha256,now:Date.now()})}catch(m){throw new u(400,"invalid_request",m instanceof Error?m.message:"invalid signed header list")}}return{headers:d}}s(N,"signCallHeaders");async function P(e){return{status:200,body:await N(e.params.name,e.principal,$(e.body))}}s(P,"callHeaders");const z=[{method:"GET",pattern:"/v1/plugins/:name/app-token",handler:H},{method:"POST",pattern:"/v1/plugins/:name/call-headers",handler:P}];export{z as pluginAppRoutes,N as signCallHeaders};
@@ -3,7 +3,7 @@ import type { ObjectRow, Reader } from '../../core/graph/types.js';
3
3
  import type { RequestContext } from './router.js';
4
4
  import { type CanvasDb } from '../../core/canvas/db.js';
5
5
  /** The graph reader for a request's principal; repos come from the node's cwd. */
6
- export declare function readerFor(db: CanvasDb, ctx: Pick<RequestContext, 'principal'>): Promise<Reader>;
6
+ export declare function readerFor(db: CanvasDb, ctx: Pick<RequestContext, 'principal'> & Partial<Pick<RequestContext, 'query' | 'body'>>): Promise<Reader>;
7
7
  /** Run the git lookups a node caller's reader needs (its cwd and its profile's project paths, and the `cwd` a request names for `--owner repo`) before a canvas write opens, so
8
8
  * `readerFor` inside the write hits the identity cache instead of spawning git while the write holds a pooled connection. */
9
9
  export declare function warmReaderRepos(principal: RequestContext['principal'], requestCwd?: string): Promise<void>;
@@ -1 +1 @@
1
- var R=Object.defineProperty;var p=(n,e)=>R(n,"name",{value:e,configurable:!0});import{ApiError as d}from"../../api/index.js";import{readerFor as N,warmNodeRepos as h}from"../../core/graph/reader.js";import{canRead as I}from"../../core/graph/access.js";import{ownersByHandle as y,resolveName as x,viewOf as F}from"../../core/graph/names.js";import{ensureOwner as j,ownerForGrantee as v,profileHandle as L}from"../../core/graph/objects.js";import{checkoutsForCwd as O,reposForCwd as A,warmCheckoutIdentities as D}from"../../core/graph/repo-sync/repos.js";import{lookupProfile as S}from"../../core/profiles/manifest.js";import{openDb as $}from"../../core/canvas/db.js";import{filterAsync as _,mapAsync as k}from"../../core/async-array.js";import{personId as C}from"../../core/canvas/person.js";async function Q(n,e){return await N(n,e.principal,async(o,r)=>await O(n,o,r))}p(Q,"readerFor");async function V(n,e){e!==void 0&&await D(e),n.class==="broker"&&await h(await $(),n.node)}p(V,"warmReaderRepos");async function X(n){const e=await $(),o=await e.prepareUncached("SELECT DISTINCT w.watcher FROM watches w JOIN objects o ON o.id = w.watcher AND o.type = 'node' WHERE w.object = ?").all(n);for(const{watcher:r}of o)await h(e,r)}p(X,"warmDocumentWatchers");async function Y(n,e,o){const r=await x(n,e,o);if("object"in r)return r.object;if("deleted"in r||"remote"in r)return r;if("ambiguous"in r){const s=await k(r.ambiguous,async m=>`${await W(n,m)}/${m.name}`);throw new d(409,"ambiguous_name",`'${o}' names more than one object: ${s.join(", ")}`,{candidates:s,next:"Read one of them by its full `<type>:<owner>/<name>`."})}const t=o.replace(/^\s*\[\[(.*)\]\]\s*$/,"$1").trim(),i=/^(person|app|repo|profile):([^/]+)$/.exec(t),a=await _(i?await y(n,i[2],i[1]):(await y(n,t)).filter(s=>s.type!=="node"),async s=>await I(n,e,s));if(a.length>0){const s=await F(n,e),m=p(u=>{const f=s.findIndex(g=>g.id===u.id);return f<0?1/0:f},"rank"),l=[...a].sort((u,f)=>m(u)-m(f))[0];if(m(l)===1/0&&a.length>1){const u=a.map(f=>`${f.type}:${f.name}`);throw new d(409,"ambiguous_name",`'${o}' names more than one owner: ${u.join(", ")}`,{candidates:u,next:"Name one as `<type>:<handle>`."})}return l.deleted_at?{deleted:l}:l}const c=`'${o}' not found: no object by that name in your view`,w=`Search for it with \`crtr canvas search ${t}\`.`;throw new d(404,"not_found",c,{error:"not_found",message:c,next:w})}p(Y,"resolveRef");async function W(n,e){if(e.owner===null)return"";const o=await n.prepare("SELECT type, id, name FROM objects WHERE id = ?").get(e.owner);return o.type==="node"?o.id:`${o.type}:${o.name}`}p(W,"typedOwnerHandle");async function Z(n,e,o,r){const t=o??(e.class==="node"?"node":e.class==="person"?"user":"app"),i=p(a=>new d(400,"invalid_owner",a,{next:"Run `crtr doc write --owner -h`."}),"refuse");if(t==="node"){if(e.class!=="node")throw i("`--owner node` needs a node; you are not running as one");return e.node}if(t==="user")return await v(n,C());if(t==="app"){if(e.class==="person")throw i("`--owner app` needs an app; a person has none \u2014 use `--owner user`");return e.app}if(t==="profile"){if(e.class!=="node"||!e.profile)throw i("`--owner profile` needs a profile; you have none");return e.profile}if(t==="repo"){const a=r?await A(n,r):[],c=a[0]?a:e.class==="node"?e.repos:[];if(!c[0])throw i(`\`--owner repo\` needs a repo; ${r??(e.class==="node"?e.cwd:"your directory")} is not inside one`);return c[0]}if(t.startsWith("repo:"))return await E(n,"repo",t.slice(5),i);if(t.startsWith("group:"))return await E(n,"group",t.slice(6),i);if(t.startsWith("profile:")){const a=t.slice(8),c=await n.prepare("SELECT * FROM objects WHERE type = 'profile' AND name = ? AND home_machine IS NULL").get(a);if(c)return c;const w=S(a);if(w.kind!=="resolved")throw i(`no profile named '${a}'`);const s=e.class==="person"?e.person:e.app;return await j(n,"profile","profile",w.entry.profileId,L(w.entry.profileId,w.entry.manifest.name),s)}throw i(`unknown --owner value '${t}'`)}p(Z,"ownerFromFlag");async function E(n,e,o,r){const t=await n.prepare("SELECT * FROM objects WHERE type = ? AND name = ? AND deleted_at IS NULL AND home_machine IS NULL").get(e,o);if(!t)throw r(`no ${e} named '${o}'`);return t}p(E,"namedOwner");export{Z as ownerFromFlag,Q as readerFor,Y as resolveRef,X as warmDocumentWatchers,V as warmReaderRepos};
1
+ var R=Object.defineProperty;var s=(n,e)=>R(n,"name",{value:e,configurable:!0});import{ApiError as u}from"../../api/index.js";import{parsePrincipal as N}from"@north-light/identity";import{actingReaderFor as F,readerFor as I,warmNodeRepos as h}from"../../core/graph/reader.js";import{canRead as j}from"../../core/graph/access.js";import{ownersByHandle as y,resolveName as v,viewOf as b}from"../../core/graph/names.js";import{ensureOwner as L,ownerForGrantee as O,profileHandle as _}from"../../core/graph/objects.js";import{checkoutsForCwd as k,reposForCwd as x,warmCheckoutIdentities as A}from"../../core/graph/repo-sync/repos.js";import{lookupProfile as D}from"../../core/profiles/manifest.js";import{openDb as $}from"../../core/canvas/db.js";import{filterAsync as S,mapAsync as C}from"../../core/async-array.js";import{personId as W}from"../../core/canvas/person.js";async function X(n,e){const t=s(async(i,a)=>await k(n,i,a),"reposFn"),r=e.body,o=e.query?.get("as")??(typeof r=="object"&&r!==null&&typeof r.as=="string"?r.as:null);if(o===null)return await I(n,e.principal,t);if(N(o)===null)throw new u(400,"invalid_request","as must be a principal like user:<id> or app:<id>/<path>");return await F(n,e.principal,t,o)}s(X,"readerFor");async function Y(n,e){e!==void 0&&await A(e),n.class==="broker"&&await h(await $(),n.node)}s(Y,"warmReaderRepos");async function Z(n){const e=await $(),t=await e.prepareUncached("SELECT DISTINCT w.watcher FROM watches w JOIN objects o ON o.id = w.watcher AND o.type = 'node' WHERE w.object = ?").all(n);for(const{watcher:r}of t)await h(e,r)}s(Z,"warmDocumentWatchers");async function ee(n,e,t){const r=await v(n,e,t);if("object"in r)return r.object;if("deleted"in r||"remote"in r)return r;if("ambiguous"in r){const p=await C(r.ambiguous,async m=>`${await H(n,m)}/${m.name}`);throw new u(409,"ambiguous_name",`'${t}' names more than one object: ${p.join(", ")}`,{candidates:p,next:"Read one of them by its full `<type>:<owner>/<name>`."})}const o=t.replace(/^\s*\[\[(.*)\]\]\s*$/,"$1").trim(),i=/^(person|app|repo|profile):([^/]+)$/.exec(o),a=await S(i?await y(n,i[2],i[1]):(await y(n,o)).filter(p=>p.type!=="node"),async p=>await j(n,e,p));if(a.length>0){const p=await b(n,e),m=s(l=>{const f=p.findIndex(E=>E.id===l.id);return f<0?1/0:f},"rank"),d=[...a].sort((l,f)=>m(l)-m(f))[0];if(m(d)===1/0&&a.length>1){const l=a.map(f=>`${f.type}:${f.name}`);throw new u(409,"ambiguous_name",`'${t}' names more than one owner: ${l.join(", ")}`,{candidates:l,next:"Name one as `<type>:<handle>`."})}return d.deleted_at?{deleted:d}:d}const c=`'${t}' not found: no object by that name in your view`,w=`Search for it with \`crtr canvas search ${o}\`.`;throw new u(404,"not_found",c,{error:"not_found",message:c,next:w})}s(ee,"resolveRef");async function H(n,e){if(e.owner===null)return"";const t=await n.prepare("SELECT type, id, name FROM objects WHERE id = ?").get(e.owner);return t.type==="node"?t.id:`${t.type}:${t.name}`}s(H,"typedOwnerHandle");async function ne(n,e,t,r){const o=t??(e.class==="node"?"node":e.class==="person"?"user":"app"),i=s(a=>new u(400,"invalid_owner",a,{next:"Run `crtr doc write --owner -h`."}),"refuse");if(o==="node"){if(e.class!=="node")throw i("`--owner node` needs a node; you are not running as one");return e.node}if(o==="user")return await O(n,W());if(o==="app"){if(e.class==="person")throw i("`--owner app` needs an app; a person has none \u2014 use `--owner user`");return e.app}if(o==="profile"){if(e.class!=="node"||!e.profile)throw i("`--owner profile` needs a profile; you have none");return e.profile}if(o==="repo"){const a=r?await x(n,r):[],c=a[0]?a:e.class==="node"?e.repos:[];if(!c[0])throw i(`\`--owner repo\` needs a repo; ${r??(e.class==="node"?e.cwd:"your directory")} is not inside one`);return c[0]}if(o.startsWith("repo:"))return await g(n,"repo",o.slice(5),i);if(o.startsWith("group:"))return await g(n,"group",o.slice(6),i);if(o.startsWith("profile:")){const a=o.slice(8),c=await n.prepare("SELECT * FROM objects WHERE type = 'profile' AND name = ? AND home_machine IS NULL").get(a);if(c)return c;const w=D(a);if(w.kind!=="resolved")throw i(`no profile named '${a}'`);const p=e.class==="person"?e.person:e.app;return await L(n,"profile","profile",w.entry.profileId,_(w.entry.profileId,w.entry.manifest.name),p)}throw i(`unknown --owner value '${o}'`)}s(ne,"ownerFromFlag");async function g(n,e,t,r){const o=await n.prepare("SELECT * FROM objects WHERE type = ? AND name = ? AND deleted_at IS NULL AND home_machine IS NULL").get(e,t);if(!o)throw r(`no ${e} named '${t}'`);return o}s(g,"namedOwner");export{ne as ownerFromFlag,X as readerFor,ee as resolveRef,Z as warmDocumentWatchers,Y as warmReaderRepos};
@@ -13,6 +13,10 @@ Changes to `@north-light/sdk` that can change what an existing app sees. Newest
13
13
 
14
14
  `grant.get().resolved_scopes` may contain `<provider>:*` (for example `integrations:*`) in place of one entry per group. It means every group of that provider the grant may hold. Check a scope with the new `holds(resolved_scopes, scope)` export instead of comparing strings, because `integrations:gmail` is held while only `integrations:*` is listed. The directory sends this form only to a runtime that understands it.
15
15
 
16
+ ### `--as` acts for another principal
17
+
18
+ A node's provider call, plugin call and memory or object read can name `as`. From a node whose app namespace differs from `as`, crtrd exchanges the node's call token at the directory; the call runs with subject `as`, the node's app as grantee and actor. Reads cover only what the grant from `as` holds. A refusal is 403 `not_granted` (no grant from `as`) or `scope_missing`. `as` inside the node's own namespace needs no grant.
19
+
16
20
  ## 0.3.755
17
21
 
18
22
  ### An app can start runs in its own environment with no person
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.759",
3
+ "version": "0.3.760",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -157,8 +157,8 @@
157
157
  },
158
158
  "license": "UNLICENSED",
159
159
  "dependencies": {
160
- "@north-light/identity": "0.3.759",
161
- "@north-light/plugin": "0.3.759",
160
+ "@north-light/identity": "0.3.760",
161
+ "@north-light/plugin": "0.3.760",
162
162
  "@earendil-works/chord": "1.5.2",
163
163
  "@earendil-works/pi-agent-core": "1.5.2",
164
164
  "@earendil-works/pi-ai": "1.5.2",
@@ -12,7 +12,7 @@
12
12
  //
13
13
  // PURITY (spec §3.1): Node built-ins + `src/api/*` only.
14
14
  /** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
15
- export const CONTRACT_LEVEL = '1.80';
15
+ export const CONTRACT_LEVEL = '1.81';
16
16
  /** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
17
17
  export const REQUIRED_CONTRACT_HEADER = 'Crouter-Required-Contract';
18
18
  /** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
@@ -13,6 +13,8 @@ export const errorCodes = {
13
13
  refresh_token_expired: { type: 'authentication_error', status: 401, retryable: false },
14
14
  refresh_token_reused: { type: 'authentication_error', status: 401, retryable: false },
15
15
  scope_missing: { type: 'permission_error', status: 403, retryable: false },
16
+ // `--as` named an owner who has granted the caller nothing.
17
+ not_granted: { type: 'permission_error', status: 403, retryable: false },
16
18
  owner_only: { type: 'permission_error', status: 403, retryable: false },
17
19
  other_app_run: { type: 'permission_error', status: 403, retryable: false },
18
20
  payer_not_app: { type: 'permission_error', status: 403, retryable: false },
@@ -1,11 +1,11 @@
1
1
  // The `Crtr-Caller` request header: who is behind a plugin call. Canvas-free so
2
2
  // the CLI and the daemon share one formatter.
3
- /** `node=<id>; machine=<id>; profile=<id>; run=<id>`, in that order. A field
3
+ /** `node=<id>; machine=<id>; profile=<id>; run=<id>; as=<principal>`, in that order. A field
4
4
  * that is empty, or whose value holds `;`, `=`, CR or LF, is left out rather
5
5
  * than injected into the header. Returns '' when no field remains. */
6
6
  export function formatCrtrCaller(fields) {
7
7
  const parts = [];
8
- for (const key of ['node', 'machine', 'profile', 'run']) {
8
+ for (const key of ['node', 'machine', 'profile', 'run', 'as']) {
9
9
  const value = fields[key];
10
10
  if (typeof value !== 'string' || value === '' || /[;=\r\n]/.test(value))
11
11
  continue;
@@ -13,3 +13,9 @@ export function ownsWithoutRow(grantee, sub, grantId) {
13
13
  export function ownerScopes(grantee) {
14
14
  return (pluginAppToken(grantee.replace(/^app:/, ''))?.scopes ?? []).map((scope) => parseScope(scope));
15
15
  }
16
+ /** Whether two principals lie in one namespace; false when either does not parse. */
17
+ export function sameNamespace(a, b) {
18
+ const first = parsePrincipal(a);
19
+ const second = parsePrincipal(b);
20
+ return first !== null && second !== null && first.namespace === second.namespace;
21
+ }
@@ -4,7 +4,7 @@ import { existsSync } from 'node:fs';
4
4
  import { CrtrError } from '../errors.js';
5
5
  import { getCachedProfile } from '../scoped-state/person-store.js';
6
6
  import { parseScope } from '@north-light/identity';
7
- import { isNamespaceOwner, ownerScopes } from '../grants/owner.js';
7
+ import { isNamespaceOwner, ownerScopes, sameNamespace } from '../grants/owner.js';
8
8
  import { activeGrant, grantFor, runtimeScope } from '../grants/mirror.js';
9
9
  import { withCanvasWrite } from '../canvas/db.js';
10
10
  import { ApiError } from '../../api/errors.js';
@@ -111,6 +111,20 @@ export async function warmNodeDirs(db, nodeId, dirs) {
111
111
  const row = nodeId === undefined ? undefined : await db.prepare('SELECT profile_id FROM nodes WHERE node_id = ?').get(nodeId);
112
112
  await warmCheckoutDirs(row?.profile_id, dirs);
113
113
  }
114
+ /** `readerFor` for a call that acts for `as` (`--as`): a node reads as `as` under the grant `as` made to the node's app, never wider than the node's own scopes.
115
+ * `as` in the node's own namespace needs no grant. A node with no such grant is refused 403 `not_granted`. */
116
+ export async function actingReaderFor(db, principal, reposFn, as) {
117
+ const reader = await readerFor(db, principal, reposFn);
118
+ if (reader.class !== 'node' || principal.class !== 'broker')
119
+ throw new ApiError(403, 'not_granted', '`--as` is for a node acting for another principal');
120
+ const grantee = principal.app;
121
+ if (sameNamespace(as, grantee))
122
+ return { ...reader, sub: as };
123
+ const grant = await grantFor(grantee, as);
124
+ if (grant === null)
125
+ throw new ApiError(403, 'not_granted', `${as} has not granted ${grantee} access`);
126
+ return { ...reader, sub: as, scopes: reader.launched == null ? grant.resolved : reader.launched.filter((scope) => coveredByAny(grant.resolved, scope)) };
127
+ }
114
128
  export async function readerFor(db, principal, reposFn) {
115
129
  if (principal.class === 'anonymous')
116
130
  throw new Error('a publish token cannot read as a principal');
@@ -35,6 +35,8 @@ async function namedUserOf(db, reader) {
35
35
  return reader.sub === undefined ? null : personSub(reader.sub);
36
36
  if (reader.class === 'object' && reader.sub !== undefined)
37
37
  return personSub(reader.sub);
38
+ if (reader.class === 'node' && reader.sub !== undefined)
39
+ return personSub(reader.sub);
38
40
  const nodeId = reader.class === 'node' ? reader.node.id : reader.object.id;
39
41
  const row = await db.prepare('SELECT sub FROM nodes WHERE node_id = ?').get(nodeId);
40
42
  return row?.sub == null ? null : personSub(row.sub);
@@ -11,7 +11,7 @@ import { providerToolPath } from '../plugin-objects-manifest.js';
11
11
  import { ensureProviderBundle, refreshProviderBundle, resolveProviderBundle, unavailableProviderError } from './bundles.js';
12
12
  import { prepareFileCall, resignForRetry, resolveFileResult } from './files.js';
13
13
  import { consumeApproval, requireProviderApproval } from './approval.js';
14
- import { outboundToken } from './mint.js';
14
+ import { actingToken, outboundToken } from './mint.js';
15
15
  import { discardFile } from './token-cache.js';
16
16
  import { registerProviderCall } from './inflight.js';
17
17
  import { buildRequestPlan, paramKey } from '../command-plugins/transport/http-plan.js';
@@ -255,8 +255,12 @@ export async function callProvider(caller, rawInput, request) {
255
255
  if (repeatedFiles)
256
256
  prepared = await resignForRetry(caller, files, input.arguments, repeatedFiles, { signal: controller.signal });
257
257
  prepared ??= await prepareFileCall(caller, files, input.arguments, { signal: controller.signal });
258
- const { sub, grantee } = await identity(caller);
258
+ const own = await identity(caller);
259
+ const { grantee } = own;
260
+ const sub = input.as ?? own.sub;
259
261
  if (bundle.transport.kind === 'machine') {
262
+ if (input.as !== undefined)
263
+ throw new ProviderError('not_granted', '`--as` is not available on a provider served by a device', { param: 'as' });
260
264
  const device = await callDevice(caller, bundle, input, leaf, prepared, { sub, requestId, deadlineAt: deviceDeadline, signal: controller.signal, machine: deviceMachine });
261
265
  responder = device.responder;
262
266
  cleanup = device.cleanup;
@@ -265,7 +269,9 @@ export async function callProvider(caller, rawInput, request) {
265
269
  const audience = bundle.transport.endpoint;
266
270
  let token;
267
271
  try {
268
- token = await outboundToken({ audience, sub, grantee, initiating_app: grantee, scope: callScope(bundle, leaf) }, { signal: controller.signal });
272
+ token = input.as === undefined
273
+ ? await outboundToken({ audience, sub, grantee, initiating_app: grantee, scope: callScope(bundle, leaf) }, { signal: controller.signal })
274
+ : await actingToken(own, input.as, { audience, scope: callScope(bundle, leaf) }, { signal: controller.signal });
269
275
  }
270
276
  catch (error) {
271
277
  // The directory no longer accepts the cached bundle's endpoint as an audience: fetch the bundle once more and retry only if it names a different endpoint.
@@ -285,7 +291,7 @@ export async function callProvider(caller, rawInput, request) {
285
291
  const paid = payerOf({ call: 'tool', tokenPayer: token.payer, sub, environmentPayer: await environmentPayerOfNode(caller.node_id) });
286
292
  const refusal = await findRefusal({ scope: 'call', payer: paid.payer, funding: paid.funding, sub, grantee: chargeGrantee, provider: `app:${bundle.id}` });
287
293
  if (refusal !== null) {
288
- await writeCharge({ request: requestId, kind: 'tool', what: `${bundle.id}:${input.tool}`, usd: 0, payer: paid.payer, funding: paid.funding, sub, actor: caller.actor ?? null, grantee: chargeGrantee,
294
+ await writeCharge({ request: requestId, kind: 'tool', what: `${bundle.id}:${input.tool}`, usd: 0, payer: paid.payer, funding: paid.funding, sub, actor: caller.actor ?? (input.as === undefined ? null : grantee), grantee: chargeGrantee,
289
295
  node: caller.node_id, run: caller.run_id, provider: `app:${bundle.id}`, causedBy: request.causedBy ?? null, refused: refusedMark(refusal) });
290
296
  throw refusalError(refusal);
291
297
  }
@@ -317,7 +323,7 @@ export async function callProvider(caller, rawInput, request) {
317
323
  }
318
324
  // R7 receives every response, including errors, before the mapping.
319
325
  receiptId ??= await onProviderResponse({ provider: bundle.id, tool: input.tool, request_id: requestId, run_id: caller.run_id,
320
- sub, grantee, payer: token.payer, ledger_grantee: chargeGrantee, funding: paid.funding, node_id: caller.node_id, actor: caller.actor ?? null, caused_by: request.causedBy ?? null, jti: token.jti, status: response.status, headers: response.headers });
326
+ sub, grantee, payer: token.payer, ledger_grantee: chargeGrantee, funding: paid.funding, node_id: caller.node_id, actor: caller.actor ?? (input.as === undefined ? null : grantee), caused_by: request.causedBy ?? null, jti: token.jti, status: response.status, headers: response.headers });
321
327
  responder = response.headers['crtr-responder'];
322
328
  if (response.status === 401)
323
329
  discardFile(token.key);
@@ -27,6 +27,7 @@ const OTHER_CODES = {
27
27
  grant_revoked: errorCodes.grant_revoked,
28
28
  machine_revoked: errorCodes.machine_revoked,
29
29
  scope_missing: errorCodes.scope_missing,
30
+ not_granted: errorCodes.not_granted,
30
31
  permission_error: errorCodes.permission_error,
31
32
  invalid_request: errorCodes.invalid_request,
32
33
  not_found: errorCodes.not_found,
@@ -19,6 +19,7 @@ import { createHash } from 'node:crypto';
19
19
  import { directoryIssuer } from '../directory/issuer.js';
20
20
  import { emitEvent } from '../events/emit.js';
21
21
  import { OutboundError } from '../events/outbound.js';
22
+ import { sameNamespace } from '../grants/owner.js';
22
23
  import { grantSyncStateFor } from '../grants/mirror.js';
23
24
  import { assertion, machineRevokedMessage, requestGrantSync, runtimeClient } from '../grants/sync.js';
24
25
  import { isUnsandboxedMachine } from '../runtime/unsandboxed.js';
@@ -105,24 +106,13 @@ async function syncIfNewer(request, refused, options) {
105
106
  // The sync logs its own failure; the caller already has its answer.
106
107
  void Promise.resolve().then(() => sync({ fresh: true })).catch(() => { });
107
108
  }
108
- /** Mint one outbound token (no cache). Throws a mapped `ProviderError`. */
109
- export async function mintOutboundToken(request, options = {}) {
110
- const issuer = issuerOf(options);
111
- const endpoint = `${issuer}/token`;
109
+ /** POST a form to the directory's token endpoint (each attempt signs its own assertion: the directory accepts a `jti` once). A 502, 503 or 504 is the directory
110
+ * briefly down, not a refusal: ask again before failing. Unreachable or too slow is a retryable `server_error`. */
111
+ async function postToken(endpoint, form, options) {
112
112
  const client = runtimeClient();
113
113
  const attempt = async () => {
114
- // Each attempt signs its own assertion: the directory accepts a `jti` once.
115
- const body = new URLSearchParams({
116
- grant_type: 'client_credentials',
117
- client_id: client.client_id,
118
- client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
119
- client_assertion: assertion(client, endpoint),
120
- audience: request.audience,
121
- sub: request.sub,
122
- grantee: request.grantee,
123
- scope: [...new Set(request.scope)].sort().join(' '),
124
- initiating_app: request.initiating_app,
125
- });
114
+ const body = new URLSearchParams({ client_id: client.client_id, client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
115
+ client_assertion: assertion(client, endpoint), ...form(client) });
126
116
  const timeout = AbortSignal.timeout(MINT_TIMEOUT_MS);
127
117
  const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
128
118
  const response = await (options.fetch ?? fetch)(endpoint, { method: 'POST', body, signal, headers: { Accept: 'application/json' } });
@@ -131,7 +121,6 @@ export async function mintOutboundToken(request, options = {}) {
131
121
  let response;
132
122
  let text;
133
123
  try {
134
- // A 502, 503 or 504 is the directory briefly down, not a refusal of this request: ask again before failing the call.
135
124
  for (let tries = 0;; tries++) {
136
125
  ({ response, text } = await attempt());
137
126
  const delay = MINT_RETRY_DELAYS_MS[tries];
@@ -153,16 +142,10 @@ export async function mintOutboundToken(request, options = {}) {
153
142
  catch {
154
143
  parsed = null;
155
144
  }
156
- const json = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
157
- if (!response.ok) {
158
- const { error, grantRefusal } = refusal(response.status, json, request, issuer);
159
- if (error.code === 'machine_revoked')
160
- emitEvent({ level: 'error', event: 'daemon.grants.machine_revoked', fields: { audience: request.audience } });
161
- emitEvent({ level: 'info', event: 'daemon.providers.mint_refused', fields: { audience: request.audience, grantee: request.grantee, code: error.code, directory_error: typeof json['error'] === 'string' ? json['error'] : null, status: response.status } });
162
- if (grantRefusal)
163
- await syncIfNewer(request, refusedGrantState(json), options);
164
- throw error;
165
- }
145
+ return { response, json: parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {} };
146
+ }
147
+ /** The cacheable token a successful token response carries. The directory names who is charged; a token without the claim (an older directory) is charged to `payerFallback`. */
148
+ function tokenOf(json, payerFallback, options) {
166
149
  const accessToken = json['access_token'];
167
150
  if (typeof accessToken !== 'string' || !accessToken) {
168
151
  throw new ProviderError('server_error', 'the directory token response has no access_token', { origin: 'directory' });
@@ -178,10 +161,28 @@ export async function mintOutboundToken(request, options = {}) {
178
161
  if (exp === null)
179
162
  throw new ProviderError('server_error', 'the directory token response names no expiry', { origin: 'directory' });
180
163
  const jti = typeof payload.jti === 'string' && payload.jti ? payload.jti : createHash('sha256').update(accessToken).digest('hex');
181
- // The directory names who is charged; a token without the claim (an older directory) is charged to its sub.
182
- const payer = typeof payload.payer === 'string' && payload.payer ? payload.payer : request.sub;
164
+ const payer = typeof payload.payer === 'string' && payload.payer ? payload.payer : payerFallback;
183
165
  return { access_token: accessToken, jti, exp, payer };
184
166
  }
167
+ /** Mint one outbound token (no cache). Throws a mapped `ProviderError`. */
168
+ export async function mintOutboundToken(request, options = {}) {
169
+ const issuer = issuerOf(options);
170
+ const endpoint = `${issuer}/token`;
171
+ const { response, json } = await postToken(endpoint, () => ({
172
+ grant_type: 'client_credentials', audience: request.audience, sub: request.sub, grantee: request.grantee,
173
+ scope: [...new Set(request.scope)].sort().join(' '), initiating_app: request.initiating_app,
174
+ }), options);
175
+ if (!response.ok) {
176
+ const { error, grantRefusal } = refusal(response.status, json, request, issuer);
177
+ if (error.code === 'machine_revoked')
178
+ emitEvent({ level: 'error', event: 'daemon.grants.machine_revoked', fields: { audience: request.audience } });
179
+ emitEvent({ level: 'info', event: 'daemon.providers.mint_refused', fields: { audience: request.audience, grantee: request.grantee, code: error.code, directory_error: typeof json['error'] === 'string' ? json['error'] : null, status: response.status } });
180
+ if (grantRefusal)
181
+ await syncIfNewer(request, refusedGrantState(json), options);
182
+ throw error;
183
+ }
184
+ return tokenOf(json, request.sub, options);
185
+ }
185
186
  // Concurrent calls for one key share one mint.
186
187
  const inflight = new Map();
187
188
  /** The outbound token for `request`: the cached one while `now < exp − 30 s`
@@ -217,3 +218,31 @@ function abortable(work, signal) {
217
218
  work.then(resolve, reject).finally(() => signal.removeEventListener('abort', onAbort));
218
219
  });
219
220
  }
221
+ /** Exchange a node's call token for one whose `sub` is `request.as` and whose `act` is the node (the directory's token exchange). A refusal is 403
222
+ * `not_granted` or `scope_missing`; any other failure is a `server_error`. Nothing is cached: the token is for this call. */
223
+ export async function exchangeForOwner(request, options = {}) {
224
+ const { response, json } = await postToken(`${issuerOf(options)}/token`, () => ({
225
+ grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange', subject_token: request.subjectToken,
226
+ subject_token_type: 'urn:ietf:params:oauth:token-type:access_token', requested_subject: request.as, audience: request.audience,
227
+ scope: [...new Set(request.scope)].sort().join(' '),
228
+ }), options);
229
+ if (!response.ok) {
230
+ const reason = typeof json['error_description'] === 'string' ? json['error_description'] : undefined;
231
+ const details = { directory_status: response.status, ...(typeof json['error'] === 'string' ? { directory_error: json['error'] } : {}), ...(reason ? { directory_description: reason } : {}) };
232
+ if (json['error'] === 'invalid_grant' && reason === 'not_granted')
233
+ throw new ProviderError('not_granted', `${request.as} has not granted this caller access`, { origin: 'directory', details });
234
+ if (json['error'] === 'invalid_grant' && reason === 'scope_missing')
235
+ throw new ProviderError('scope_missing', `the grant from ${request.as} does not cover ${request.scope.join(' ')}`, { origin: 'directory', details, ...(request.scope.length === 1 ? { scope: request.scope[0] } : {}) });
236
+ throw new ProviderError('server_error', `the directory refused the token exchange (${response.status}${reason ? ` ${reason}` : ''})`, { origin: 'directory', details });
237
+ }
238
+ return tokenOf(json, request.as, options);
239
+ }
240
+ /** The token a node presents to act for `as`: its own call token (minted as its `sub` and `grantee`), exchanged at the directory. In the node's own namespace
241
+ * the node mints directly as `as` (an owner link) and no exchange runs. */
242
+ export async function actingToken(node, as, call, options = {}) {
243
+ if (sameNamespace(as, node.grantee))
244
+ return await outboundToken({ ...call, sub: as, grantee: node.grantee, initiating_app: node.grantee }, options);
245
+ const subject = await outboundToken({ ...call, sub: node.sub, grantee: node.grantee, initiating_app: node.grantee }, options);
246
+ const token = await exchangeForOwner({ subjectToken: subject.access_token, as, audience: call.audience, scope: call.scope }, options);
247
+ return { ...token, key: `exchange:${token.jti}` };
248
+ }
@@ -1,5 +1,6 @@
1
1
  import { ApiError } from '../../api/index.js';
2
- import { readerFor as graphReaderFor, warmNodeRepos } from '../../core/graph/reader.js';
2
+ import { parsePrincipal } from '@north-light/identity';
3
+ import { actingReaderFor, readerFor as graphReaderFor, warmNodeRepos } from '../../core/graph/reader.js';
3
4
  import { canRead } from '../../core/graph/access.js';
4
5
  import { ownersByHandle, resolveName, viewOf } from '../../core/graph/names.js';
5
6
  import { ensureOwner, ownerForGrantee, profileHandle } from '../../core/graph/objects.js';
@@ -10,7 +11,14 @@ import { filterAsync, mapAsync } from '../../core/async-array.js';
10
11
  import { personId } from '../../core/canvas/person.js';
11
12
  /** The graph reader for a request's principal; repos come from the node's cwd. */
12
13
  export async function readerFor(db, ctx) {
13
- return await graphReaderFor(db, ctx.principal, async (cwd, person) => await checkoutsForCwd(db, cwd, person));
14
+ const reposFn = async (cwd, person) => await checkoutsForCwd(db, cwd, person);
15
+ const body = ctx.body;
16
+ const as = ctx.query?.get('as') ?? (typeof body === 'object' && body !== null && typeof body.as === 'string' ? body.as : null);
17
+ if (as === null)
18
+ return await graphReaderFor(db, ctx.principal, reposFn);
19
+ if (parsePrincipal(as) === null)
20
+ throw new ApiError(400, 'invalid_request', 'as must be a principal like user:<id> or app:<id>/<path>');
21
+ return await actingReaderFor(db, ctx.principal, reposFn, as);
14
22
  }
15
23
  /** Run the git lookups a node caller's reader needs (its cwd and its profile's project paths, and the `cwd` a request names for `--owner repo`) before a canvas write opens, so
16
24
  * `readerFor` inside the write hits the identity cache instead of spawning git while the write holds a pooled connection. */
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.759",
3
+ "version": "0.3.760",
4
4
  "description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/api/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.759",
3
+ "version": "0.3.760",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.759",
3
+ "version": "0.3.760",
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.759",
31
- "@north-light/identity": "0.3.759"
30
+ "@north-light/api": "0.3.760",
31
+ "@north-light/identity": "0.3.760"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.759",
3
+ "version": "0.3.760",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.759",
9
+ "version": "0.3.760",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,8 +28,8 @@
28
28
  "@milkdown/preset-gfm": "^7.22.3",
29
29
  "@milkdown/prose": "^7.22.3",
30
30
  "@milkdown/utils": "^7.22.3",
31
- "@north-light/identity": "0.3.759",
32
- "@north-light/plugin": "0.3.759",
31
+ "@north-light/identity": "0.3.760",
32
+ "@north-light/plugin": "0.3.760",
33
33
  "cron-parser": "^5.6.0",
34
34
  "esbuild": "0.28.2",
35
35
  "jose": "^6.2.12",
@@ -11902,17 +11902,17 @@
11902
11902
  },
11903
11903
  "packages/crouter-api": {
11904
11904
  "name": "@north-light/api",
11905
- "version": "0.3.759",
11905
+ "version": "0.3.760",
11906
11906
  "license": "UNLICENSED"
11907
11907
  },
11908
11908
  "packages/crouter-env-docker": {
11909
11909
  "name": "@north-light/env-docker",
11910
- "version": "0.3.759",
11910
+ "version": "0.3.760",
11911
11911
  "license": "UNLICENSED"
11912
11912
  },
11913
11913
  "packages/crouter-identity": {
11914
11914
  "name": "@north-light/identity",
11915
- "version": "0.3.759",
11915
+ "version": "0.3.760",
11916
11916
  "license": "UNLICENSED",
11917
11917
  "dependencies": {
11918
11918
  "jose": "^6.2.1"
@@ -11920,21 +11920,21 @@
11920
11920
  },
11921
11921
  "packages/crouter-plugin": {
11922
11922
  "name": "@north-light/plugin",
11923
- "version": "0.3.759",
11923
+ "version": "0.3.760",
11924
11924
  "license": "UNLICENSED",
11925
11925
  "dependencies": {
11926
- "@north-light/api": "0.3.759",
11927
- "@north-light/identity": "0.3.759"
11926
+ "@north-light/api": "0.3.760",
11927
+ "@north-light/identity": "0.3.760"
11928
11928
  }
11929
11929
  },
11930
11930
  "packages/crouter-sdk": {
11931
11931
  "name": "@north-light/sdk",
11932
- "version": "0.3.759",
11932
+ "version": "0.3.760",
11933
11933
  "license": "UNLICENSED",
11934
11934
  "dependencies": {
11935
- "@north-light/api": "0.3.759",
11936
- "@north-light/identity": "0.3.759",
11937
- "@north-light/plugin": "0.3.759",
11935
+ "@north-light/api": "0.3.760",
11936
+ "@north-light/identity": "0.3.760",
11937
+ "@north-light/plugin": "0.3.760",
11938
11938
  "jose": "^6.2.1"
11939
11939
  },
11940
11940
  "bin": {