@north-light/cli 0.3.758 → 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 (44) 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 +10 -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/mirror.js +2 -2
  9. package/dist/core/grants/owner.d.ts +2 -0
  10. package/dist/core/grants/owner.js +1 -1
  11. package/dist/core/grants/shadow.js +1 -1
  12. package/dist/core/graph/reader.d.ts +5 -0
  13. package/dist/core/graph/reader.js +3 -3
  14. package/dist/core/graph/types.d.ts +2 -0
  15. package/dist/core/permissions/evaluator.js +2 -2
  16. package/dist/core/providers/call.js +1 -1
  17. package/dist/core/providers/errors.js +1 -1
  18. package/dist/core/providers/mint.d.ts +19 -0
  19. package/dist/core/providers/mint.js +1 -1
  20. package/dist/daemon/api/handlers/memory.js +5 -5
  21. package/dist/daemon/api/handlers/plugin-app-token.js +1 -1
  22. package/dist/daemon/api/handlers/providers.js +1 -1
  23. package/dist/daemon/api/reader.d.ts +1 -1
  24. package/dist/daemon/api/reader.js +1 -1
  25. package/docs/sdk/release-notes.md +10 -0
  26. package/package.json +3 -3
  27. package/packages/crouter-api/dist/api/contract.js +1 -1
  28. package/packages/crouter-api/dist/api/error-codes.js +2 -0
  29. package/packages/crouter-api/dist/core/command-plugins/caller-header.js +2 -2
  30. package/packages/crouter-api/dist/core/grants/mirror.js +2 -2
  31. package/packages/crouter-api/dist/core/grants/owner.js +6 -0
  32. package/packages/crouter-api/dist/core/grants/shadow.js +25 -1
  33. package/packages/crouter-api/dist/core/graph/reader.js +15 -1
  34. package/packages/crouter-api/dist/core/permissions/evaluator.js +2 -0
  35. package/packages/crouter-api/dist/core/providers/call.js +11 -5
  36. package/packages/crouter-api/dist/core/providers/errors.js +1 -0
  37. package/packages/crouter-api/dist/core/providers/mint.js +58 -29
  38. package/packages/crouter-api/dist/daemon/api/handlers/providers.js +6 -4
  39. package/packages/crouter-api/dist/daemon/api/reader.js +10 -2
  40. package/packages/crouter-api/package.json +1 -1
  41. package/packages/crouter-identity/dist/index.js +5 -2
  42. package/packages/crouter-identity/package.json +1 -1
  43. package/packages/crouter-plugin/package.json +3 -3
  44. package/runtime.lock.json +14 -14
@@ -1 +1 @@
1
- var q=Object.defineProperty;var s=(e,r)=>q(e,"name",{value:r,configurable:!0});import{parsePrincipal as G}from"@north-light/identity";import{randomUUID as N}from"node:crypto";import{cloudPersonScope as T}from"../../../core/runs/operations.js";import{directoryIssuer as F}from"../../../core/directory/issuer.js";import{activeGrantForApp as k,grantFor as x,grantsOfPerson as C,localGrants as j,providerIdsFromGrants as S}from"../../../core/grants/mirror.js";import{getNode as B}from"../../../core/canvas/canvas.js";import{scopeAllowed as D}from"../../../core/scopes.js";import{ProviderError as f,providerErrorBody as M,scopeMissing as U}from"../../../core/providers/errors.js";import{callProvider as z,providerTools as L}from"../../../core/providers/call.js";import{providerInstallState as V}from"../../../core/providers/bundles.js";import{installedProviderPlugins as Z,providerRootClaims as W,resolveProviderRef as J}from"../../../core/providers/roots.js";import{isCloudRole as h}from"../../../core/canvas/person-state.js";import{listAudit as X,writeProviderAudit as H}from"../../../core/providers/audit.js";import{emitEvent as P}from"../../../core/events/emit.js";import{resolvedScopes as _}from"../router.js";const Re=new Set(["provider.tools","provider.call","audit.list"]);async function K(e){if(e.class==="forwarded"){if(e.actor.kind==="person")return{class:"person",sub:null,grantee:null,client_id:null,resolved:null,nodeScopes:null,run_id:null,node_id:null,origin:{node:null,run:null,machine:e.via}};const r=await x(e.actor.app,e.sub);if(!r)throw new f("grant_revoked",`app ${e.actor.app} has no active grant`);return{class:"app",sub:e.sub,grantee:e.actor.app,client_id:null,resolved:r.resolved,nodeScopes:e.actor.node_scopes,run_id:null,node_id:null,origin:{node:e.actor.node,run:e.actor.place?.run??null,machine:e.via}}}if(e.class==="machine"||e.class==="import")throw new f("permission_error","this operation is not available to the caller");if(e.class==="person"&&e.sub!==void 0){if(!h())throw new f("permission_error","provider calls are made by the install's person, a node or an app");return{class:"person",sub:e.sub,grantee:null,client_id:null,resolved:await _(e),nodeScopes:null,run_id:null,node_id:null}}if(e.class==="person")return{class:"person",sub:null,grantee:null,client_id:null,resolved:null,nodeScopes:null,run_id:null,node_id:null};if(e.class==="app"){const r=await k(e.app);if(!r)throw new f("grant_revoked",`app ${e.app} has no active grant`);return{class:"app",sub:r.sub,grantee:e.app,client_id:null,resolved:r.resolved,nodeScopes:e.scopes,run_id:null,node_id:null}}return e.class==="cron"?{class:"app",sub:e.sub,grantee:e.app,client_id:null,resolved:await _(e),nodeScopes:e.scopes,run_id:e.origin_run,node_id:null}:{class:"broker",sub:e.sub,grantee:e.app,client_id:e.client_id,resolved:await _(e),nodeScopes:e.scopes,run_id:e.run??(await B(e.node))?.run_id??null,node_id:e.node}}s(K,"callerFromRequest");function Ie(e){return{class:"app",sub:e.sub,grantee:e.grantee,client_id:e.client_id,actor:e.actor,resolved:e.resolved,nodeScopes:null,run_id:null,node_id:null}}s(Ie,"callerFromApp");const Q=/^([A-Za-z0-9_-]{1,64}):([A-Za-z0-9_-]{1,64})$/;function Y(e){const r=Q.exec(e);return r!==null&&r[1]!=="crtr"}s(Y,"isProviderScope");const A=new WeakMap;function ee(e){let r=A.get(e);return r===void 0&&(r=new Set(e),A.set(e,r)),r}s(ee,"heldSet");function E(e,r){return e===null?!0:Y(r)?ee(e).has(r):D(e,r)}s(E,"holds");function R(e,r){return e.class==="person"&&e.resolved===null?!0:E(e.resolved??[],r)&&E(e.nodeScopes,r)}s(R,"callerAllows");function Oe(e,r,n){const o=`${r}:${n}`;if(!R(e,o))throw U(o)}s(Oe,"requireGroup");function re(){return!!F()}s(re,"providerOperationsEnabled");const oe=/^[A-Za-z0-9_-]{1,64}$/;function p(e,r){return new f("invalid_request",e,{param:r})}s(p,"invalid");function I(e){if(typeof e!="string"||!oe.test(e)||e==="crtr")throw p("provider must be a provider id","provider");return e}s(I,"parseProvider");function te(e){if(!e||typeof e!="object"||Array.isArray(e))throw new f("invalid_request","a JSON object is required");const r=e,n=I(r.provider),o=r.tool;if(typeof o!="string"||!o.trim())throw p("tool must be a non-empty string","tool");const d=r.arguments??{};if(!d||typeof d!="object"||Array.isArray(d))throw p("arguments must be an object","arguments");const a=r.version;if(a!==void 0&&(typeof a!="number"||!Number.isInteger(a)||a<1))throw p("version must be an integer >= 1","version");const u=r.approval;if(u!==void 0&&(typeof u!="string"||!u))throw p("approval must be a question id","approval");const l=r.machine;if(l!==void 0&&(typeof l!="string"||!l.trim()))throw p("machine must be a machine id","machine");const i=r.as;if(i!==void 0&&(typeof i!="string"||G(i)===null))throw p("as must be a principal like user:<id> or app:<id>/<path>","as");return{provider:n,tool:o.trim(),arguments:d,...a===void 0?{}:{version:a},...u===void 0?{}:{approval:u},...l===void 0?{}:{machine:l.trim()},...i===void 0?{}:{as:i}}}s(te,"parseCallInput");async function ne(e,r=new URLSearchParams){const n=s((i,v,b)=>{const m=r.get(i);if(m===null)return v;if(!/^\d+$/.test(m)||Number(m)>b||Number(m)<1)throw p(`invalid ${i}`,i);return Number(m)},"numeric"),o=r.has("after")?n("after",0,Number.MAX_SAFE_INTEGER):void 0,d=n("limit",100,1e3),a=Object.fromEntries(["operation","outcome","run_id","since","until"].filter(i=>r.has(i)).map(i=>[i,r.get(i)])),u=T(e.sub),l=u===void 0?{}:{sub:u};return{status:200,body:await X(e.class==="person"?null:e.grantee,{after:o,limit:d,...l,...a})}}s(ne,"auditList");async function se(e,r,n){let o=r;const d=performance.now(),a=Z(),{skipped:u}=W(a),l=h()?e.sub?await C(e.sub):[]:await j(),i=h()?new Set(S(l.filter(t=>t.sub===e.sub))):null,v=s(t=>!u.has(t)&&(i===null||i.has(t)),"shown"),b=new Set(a.filter(t=>t.enabled&&t.manifest.provider?.id===t.name&&v(t.name)).map(t=>t.name)),m=S(l).filter(v),g=[...new Set([...b,...m])].sort();if(o!==void 0){const t=J(o);if(t===null)throw new f("not_found",`provider "${o}" is not available`);o=t}if(o!==void 0&&!g.includes(o))throw new f("not_found",`provider "${o}" is not available`);const O=o===void 0?g:[o],$=e.class==="person"?l.flatMap(t=>t.status==="active"&&(!h()||t.sub===e.sub)?t.resolved_scopes.map(({scope:c})=>c):[]):e.resolved??[],w=await Promise.all(O.map(async t=>{if(b.has(t))return L(e,t);if(!$.some(y=>y.startsWith(`${t}:`)&&R(e,y)))return null;const c=V(t);return c===void 0?null:{provider:t,display_name:t,status:c.status,...c.error?{error:c.error}:{},groups:[],commands:[]}})).then(t=>t.filter(c=>c!==null));if(P({level:"debug",event:"api.provider.tools",duration_ms:performance.now()-d,fields:{caller:e.class,provider:o??null,providers:w.length}}),o!==void 0){if(w.length===0)throw new f("not_found",`provider "${o}" is not available`);return{status:200,body:w[0]}}return{status:200,body:{providers:w}}}s(se,"providerTools");async function ie(e,r,n){return z(e,r,n)}s(ie,"providerCall");async function de(e,r,n,o){if(!re())throw new f("not_found","provider operations need a directory-connected runtime");if(e==="audit.list")return await ne(r,n.query);if(e==="provider.tools")return se(r,n.params.provider===void 0?void 0:I(n.params.provider),o);if(e==="provider.call"){let d;try{d=te(n.body)}catch(a){const u=n.body&&typeof n.body=="object"&&!Array.isArray(n.body)?n.body:{};throw await H({request_id:o.requestId,caller:r,provider:typeof u.provider=="string"?u.provider:"",tool:typeof u.tool=="string"?u.tool:"",outcome:`refused:${a instanceof f?a.code:"invalid_request"}`}),a}return ie(r,d,o)}throw new f("not_found","unknown operation")}s(de,"handleProviderOperation");function ae(e){const r=new AbortController,n=s(()=>{e.writableFinished||r.abort()},"abort");return e.on("close",n),{signal:r.signal,release:s(()=>e.off("close",n),"release")}}s(ae,"abortOnClose");function ue(e,r,n,o){const d=M(e,r,n,o??void 0);return d.status>=500&&!(e instanceof f)&&P({event:"api.provider.failed",level:"error",error:e instanceof Error?e:new Error(String(e)),fields:{request_id:r}}),d}s(ue,"providerFailure");const $e=[{method:"GET",pattern:"/v1/audit",name:"audit.list"},{method:"GET",pattern:"/v1/providers/tools",name:"provider.tools"},{method:"GET",pattern:"/v1/providers/:provider/tools",name:"provider.tools"},{method:"POST",pattern:"/v1/provider/call",name:"provider.call"}].map(({method:e,pattern:r,name:n})=>({method:e,pattern:r,handler:s(async o=>{const d=N(),{signal:a,release:u}=ae(o.res);let l=null;try{return l=await K(o.principal),{...await de(n,l,{params:o.params,body:o.body,query:new URL(o.req.url??"/","http://runtime.local").searchParams},{requestId:d,signal:a,...o.causedBy===void 0?{}:{causedBy:o.causedBy}}),headers:{"Request-Id":d}}}catch(i){return ue(i,d,!1,l?.run_id)}finally{u()}},"handler")}));export{Re as PROVIDER_OPERATIONS,ae as abortOnClose,R as callerAllows,Ie as callerFromApp,K as callerFromRequest,de as handleProviderOperation,te as parseCallInput,I as parseProvider,ue as providerFailure,re as providerOperationsEnabled,$e as providerRoutes,Oe as requireGroup};
1
+ var q=Object.defineProperty;var s=(e,r)=>q(e,"name",{value:r,configurable:!0});import{parsePrincipal as G}from"@north-light/identity";import{randomUUID as N}from"node:crypto";import{cloudPersonScope as T}from"../../../core/runs/operations.js";import{directoryIssuer as x}from"../../../core/directory/issuer.js";import{activeGrantForApp as F,grantFor as k,grantsOfPerson as C,localGrants as j,providerIdsFromGrants as S}from"../../../core/grants/mirror.js";import{getNode as B}from"../../../core/canvas/canvas.js";import{scopeAllowed as D}from"../../../core/scopes.js";import{ProviderError as f,providerErrorBody as M,scopeMissing as U}from"../../../core/providers/errors.js";import{callProvider as z,providerTools as L}from"../../../core/providers/call.js";import{providerInstallState as V}from"../../../core/providers/bundles.js";import{installedProviderPlugins as Z,providerRootClaims as W,resolveProviderRef as J}from"../../../core/providers/roots.js";import{isCloudRole as w}from"../../../core/canvas/person-state.js";import{listAudit as X,writeProviderAudit as H}from"../../../core/providers/audit.js";import{emitEvent as P}from"../../../core/events/emit.js";import{resolvedScopes as _}from"../router.js";const Re=new Set(["provider.tools","provider.call","audit.list"]);async function K(e){if(e.class==="forwarded"){if(e.actor.kind==="person")return{class:"person",sub:null,grantee:null,client_id:null,resolved:null,nodeScopes:null,run_id:null,node_id:null,origin:{node:null,run:null,machine:e.via}};const r=await k(e.actor.app,e.sub);if(!r)throw new f("grant_revoked",`app ${e.actor.app} has no active grant`);return{class:"app",sub:e.sub,grantee:e.actor.app,client_id:null,resolved:r.resolved,nodeScopes:e.actor.node_scopes,run_id:null,node_id:null,origin:{node:e.actor.node,run:e.actor.place?.run??null,machine:e.via}}}if(e.class==="machine"||e.class==="import")throw new f("permission_error","this operation is not available to the caller");if(e.class==="person"&&e.sub!==void 0){if(!w())throw new f("permission_error","provider calls are made by the install's person, a node or an app");return{class:"person",sub:e.sub,grantee:null,client_id:null,resolved:await _(e),nodeScopes:null,run_id:null,node_id:null}}if(e.class==="person")return{class:"person",sub:null,grantee:null,client_id:null,resolved:null,nodeScopes:null,run_id:null,node_id:null};if(e.class==="app"){const r=await F(e.app);if(!r)throw new f("grant_revoked",`app ${e.app} has no active grant`);return{class:"app",sub:r.sub,grantee:e.app,client_id:null,resolved:r.resolved,nodeScopes:e.scopes,run_id:null,node_id:null}}return e.class==="cron"?{class:"app",sub:e.sub,grantee:e.app,client_id:null,resolved:await _(e),nodeScopes:e.scopes,run_id:e.origin_run,node_id:null}:{class:"broker",sub:e.sub,grantee:e.app,client_id:e.client_id,resolved:await _(e),nodeScopes:e.scopes,run_id:e.run??(await B(e.node))?.run_id??null,node_id:e.node}}s(K,"callerFromRequest");function Ie(e){return{class:"app",sub:e.sub,grantee:e.grantee,client_id:e.client_id,actor:e.actor,resolved:e.resolved,nodeScopes:null,run_id:null,node_id:null}}s(Ie,"callerFromApp");const Q=/^([A-Za-z0-9_-]{1,64}):([A-Za-z0-9_-]{1,64})$/;function Y(e){const r=Q.exec(e);return r!==null&&r[1]!=="crtr"}s(Y,"isProviderScope");const A=new WeakMap;function ee(e){let r=A.get(e);return r===void 0&&(r=new Set(e),A.set(e,r)),r}s(ee,"heldSet");function E(e,r){if(e===null)return!0;if(Y(r)){const t=ee(e);return t.has(r)||t.has(`${r.slice(0,r.indexOf(":"))}:*`)}return D(e,r)}s(E,"holds");function R(e,r){return e.class==="person"&&e.resolved===null?!0:E(e.resolved??[],r)&&E(e.nodeScopes,r)}s(R,"callerAllows");function Oe(e,r,t){const o=`${r}:${t}`;if(!R(e,o))throw U(o)}s(Oe,"requireGroup");function re(){return!!x()}s(re,"providerOperationsEnabled");const oe=/^[A-Za-z0-9_-]{1,64}$/;function p(e,r){return new f("invalid_request",e,{param:r})}s(p,"invalid");function I(e){if(typeof e!="string"||!oe.test(e)||e==="crtr")throw p("provider must be a provider id","provider");return e}s(I,"parseProvider");function te(e){if(!e||typeof e!="object"||Array.isArray(e))throw new f("invalid_request","a JSON object is required");const r=e,t=I(r.provider),o=r.tool;if(typeof o!="string"||!o.trim())throw p("tool must be a non-empty string","tool");const d=r.arguments??{};if(!d||typeof d!="object"||Array.isArray(d))throw p("arguments must be an object","arguments");const a=r.version;if(a!==void 0&&(typeof a!="number"||!Number.isInteger(a)||a<1))throw p("version must be an integer >= 1","version");const u=r.approval;if(u!==void 0&&(typeof u!="string"||!u))throw p("approval must be a question id","approval");const l=r.machine;if(l!==void 0&&(typeof l!="string"||!l.trim()))throw p("machine must be a machine id","machine");const i=r.as;if(i!==void 0&&(typeof i!="string"||G(i)===null))throw p("as must be a principal like user:<id> or app:<id>/<path>","as");return{provider:t,tool:o.trim(),arguments:d,...a===void 0?{}:{version:a},...u===void 0?{}:{approval:u},...l===void 0?{}:{machine:l.trim()},...i===void 0?{}:{as:i}}}s(te,"parseCallInput");async function ne(e,r=new URLSearchParams){const t=s((i,v,b)=>{const m=r.get(i);if(m===null)return v;if(!/^\d+$/.test(m)||Number(m)>b||Number(m)<1)throw p(`invalid ${i}`,i);return Number(m)},"numeric"),o=r.has("after")?t("after",0,Number.MAX_SAFE_INTEGER):void 0,d=t("limit",100,1e3),a=Object.fromEntries(["operation","outcome","run_id","since","until"].filter(i=>r.has(i)).map(i=>[i,r.get(i)])),u=T(e.sub),l=u===void 0?{}:{sub:u};return{status:200,body:await X(e.class==="person"?null:e.grantee,{after:o,limit:d,...l,...a})}}s(ne,"auditList");async function se(e,r,t){let o=r;const d=performance.now(),a=Z(),{skipped:u}=W(a),l=w()?e.sub?await C(e.sub):[]:await j(),i=w()?new Set(S(l.filter(n=>n.sub===e.sub))):null,v=s(n=>!u.has(n)&&(i===null||i.has(n)),"shown"),b=new Set(a.filter(n=>n.enabled&&n.manifest.provider?.id===n.name&&v(n.name)).map(n=>n.name)),m=S(l).filter(v),g=[...new Set([...b,...m])].sort();if(o!==void 0){const n=J(o);if(n===null)throw new f("not_found",`provider "${o}" is not available`);o=n}if(o!==void 0&&!g.includes(o))throw new f("not_found",`provider "${o}" is not available`);const O=o===void 0?g:[o],$=e.class==="person"?l.flatMap(n=>n.status==="active"&&(!w()||n.sub===e.sub)?n.resolved_scopes.map(({scope:c})=>c):[]):e.resolved??[],h=await Promise.all(O.map(async n=>{if(b.has(n))return L(e,n);if(!$.some(y=>y.startsWith(`${n}:`)&&R(e,y)))return null;const c=V(n);return c===void 0?null:{provider:n,display_name:n,status:c.status,...c.error?{error:c.error}:{},groups:[],commands:[]}})).then(n=>n.filter(c=>c!==null));if(P({level:"debug",event:"api.provider.tools",duration_ms:performance.now()-d,fields:{caller:e.class,provider:o??null,providers:h.length}}),o!==void 0){if(h.length===0)throw new f("not_found",`provider "${o}" is not available`);return{status:200,body:h[0]}}return{status:200,body:{providers:h}}}s(se,"providerTools");async function ie(e,r,t){return z(e,r,t)}s(ie,"providerCall");async function de(e,r,t,o){if(!re())throw new f("not_found","provider operations need a directory-connected runtime");if(e==="audit.list")return await ne(r,t.query);if(e==="provider.tools")return se(r,t.params.provider===void 0?void 0:I(t.params.provider),o);if(e==="provider.call"){let d;try{d=te(t.body)}catch(a){const u=t.body&&typeof t.body=="object"&&!Array.isArray(t.body)?t.body:{};throw await H({request_id:o.requestId,caller:r,provider:typeof u.provider=="string"?u.provider:"",tool:typeof u.tool=="string"?u.tool:"",outcome:`refused:${a instanceof f?a.code:"invalid_request"}`}),a}return ie(r,d,o)}throw new f("not_found","unknown operation")}s(de,"handleProviderOperation");function ae(e){const r=new AbortController,t=s(()=>{e.writableFinished||r.abort()},"abort");return e.on("close",t),{signal:r.signal,release:s(()=>e.off("close",t),"release")}}s(ae,"abortOnClose");function ue(e,r,t,o){const d=M(e,r,t,o??void 0);return d.status>=500&&!(e instanceof f)&&P({event:"api.provider.failed",level:"error",error:e instanceof Error?e:new Error(String(e)),fields:{request_id:r}}),d}s(ue,"providerFailure");const $e=[{method:"GET",pattern:"/v1/audit",name:"audit.list"},{method:"GET",pattern:"/v1/providers/tools",name:"provider.tools"},{method:"GET",pattern:"/v1/providers/:provider/tools",name:"provider.tools"},{method:"POST",pattern:"/v1/provider/call",name:"provider.call"}].map(({method:e,pattern:r,name:t})=>({method:e,pattern:r,handler:s(async o=>{const d=N(),{signal:a,release:u}=ae(o.res);let l=null;try{return l=await K(o.principal),{...await de(t,l,{params:o.params,body:o.body,query:new URL(o.req.url??"/","http://runtime.local").searchParams},{requestId:d,signal:a,...o.causedBy===void 0?{}:{causedBy:o.causedBy}}),headers:{"Request-Id":d}}}catch(i){return ue(i,d,!1,l?.run_id)}finally{u()}},"handler")}));export{Re as PROVIDER_OPERATIONS,ae as abortOnClose,R as callerAllows,Ie as callerFromApp,K as callerFromRequest,de as handleProviderOperation,te as parseCallInput,I as parseProvider,ue as providerFailure,re as providerOperationsEnabled,$e as providerRoutes,Oe as requireGroup};
@@ -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};
@@ -7,6 +7,16 @@ description: Behavior changes in @north-light/sdk that an app must act on, newes
7
7
 
8
8
  Changes to `@north-light/sdk` that can change what an existing app sees. Newest first.
9
9
 
10
+ ## 0.3.759
11
+
12
+ ### A grant can hold a whole provider as `<provider>:*`
13
+
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
+
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
+
10
20
  ## 0.3.755
11
21
 
12
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.758",
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.758",
161
- "@north-light/plugin": "0.3.758",
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.79';
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;
@@ -150,7 +150,7 @@ export async function otherLiveGrantOfApp(app, sub) {
150
150
  }
151
151
  /** Contract 1's `<id>` grammar, shared by provider ids and group ids. */
152
152
  const ID = '[A-Za-z0-9_-]{1,64}';
153
- const PROVIDER_SCOPE = new RegExp(`^(${ID}):(${ID})$`);
153
+ const PROVIDER_SCOPE = new RegExp(`^(${ID}):(${ID}|\\*)$`);
154
154
  /** Every provider id a scope of an active grant's resolved set names: a
155
155
  * `<id>:<group>` string whose id is not `crtr` (the runtime's own namespace). */
156
156
  export function providerIdsFromGrants(grants) {
@@ -180,7 +180,7 @@ export async function activeProviderIds() {
180
180
  SELECT DISTINCT e->>'scope' AS scope FROM (
181
181
  SELECT t::jsonb AS j FROM (SELECT DISTINCT resolved_scopes_json AS t FROM grants WHERE ${ACTIVE_COMPUTED}${localOnly()}${scope.sql}) d OFFSET 0) p
182
182
  CROSS JOIN LATERAL jsonb_array_elements(CASE WHEN jsonb_typeof(p.j) = 'array' THEN p.j ELSE '[]' END) e) s
183
- CROSS JOIN LATERAL regexp_match(s.scope, '^(${ID}):${ID}$') m
183
+ CROSS JOIN LATERAL regexp_match(s.scope, '^(${ID}):(?:${ID}|\\*)$') m
184
184
  WHERE m[1] <> 'crtr'`).all(...scope.args);
185
185
  return rows.map((row) => row.id).sort();
186
186
  }
@@ -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
+ }
@@ -69,7 +69,8 @@ async function compare(stored) {
69
69
  }
70
70
  // The directory may still send the older `'user'`/`'app'` payer; the mirror stores it as a principal.
71
71
  const liveSide = { ...live, payer: principalPayer(live['payer'], stored.sub, stored.grantee) };
72
- const fields = COMPARED.filter((key) => canonicalJson(liveSide[key] ?? null) !== canonicalJson(stored[key] ?? null));
72
+ const storedSide = { ...stored, resolved_scopes: compactLike(stored.resolved_scopes, live['resolved_scopes']) };
73
+ const fields = COMPARED.filter((key) => canonicalJson(liveSide[key] ?? null) !== canonicalJson(storedSide[key] ?? null));
73
74
  if (fields.length === 0) {
74
75
  shadowCounts.agree++;
75
76
  return;
@@ -77,6 +78,29 @@ async function compare(stored) {
77
78
  shadowCounts.disagree++;
78
79
  warn(`grant_shadow disagree ${JSON.stringify({ grant: stored.id, sub: stored.sub, rev: stored.rev, fields })}`);
79
80
  }
81
+ // The live answer may hold `<provider>:*` where the stored column still lists each group (phase 4). Fold the stored groups of each such
82
+ // provider into its wildcard, keeping the first group's mode and position, so the two forms compare equal when they name the same providers. A group the live answer still names (an `own` group) stays.
83
+ function compactLike(stored, live) {
84
+ if (!Array.isArray(live))
85
+ return stored;
86
+ const named = new Set(live.flatMap((entry) => {
87
+ const scope = entry?.scope;
88
+ return typeof scope === 'string' ? [scope] : [];
89
+ }));
90
+ const wild = new Set([...named].filter((scope) => scope.endsWith(':*')).map((scope) => scope.slice(0, -2)));
91
+ if (wild.size === 0)
92
+ return stored;
93
+ const seen = new Set();
94
+ return stored.flatMap((entry) => {
95
+ const provider = entry.scope.slice(0, entry.scope.indexOf(':'));
96
+ if (provider === 'crtr' || !wild.has(provider) || named.has(entry.scope))
97
+ return [entry];
98
+ if (seen.has(provider))
99
+ return [];
100
+ seen.add(provider);
101
+ return [{ ...entry, scope: `${provider}:*` }];
102
+ });
103
+ }
80
104
  let summaryTimer;
81
105
  let reported = { agree: 0, disagree: 0, lagging: 0, error: 0 };
82
106
  // One greppable line a minute while checks are happening: `grep grant_shadow_summary`; sum `disagree` across pods over 7 days.
@@ -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
+ }
@@ -68,7 +68,7 @@ export function callerFromApp(principal) {
68
68
  return { class: 'app', sub: principal.sub, grantee: principal.grantee, client_id: principal.client_id, actor: principal.actor, resolved: principal.resolved, nodeScopes: null, run_id: null, node_id: null };
69
69
  }
70
70
  /** A provider scope `<provider>:<group>` (the identity grammar's `provider`
71
- * selector kind). `covers()` grants such a scope only by exact equality. */
71
+ * selector kind). It is held by itself or by the wildcard `<provider>:*`. */
72
72
  const PROVIDER_SCOPE = /^([A-Za-z0-9_-]{1,64}):([A-Za-z0-9_-]{1,64})$/;
73
73
  function isProviderScope(scope) {
74
74
  const match = PROVIDER_SCOPE.exec(scope);
@@ -87,13 +87,15 @@ function heldSet(scopes) {
87
87
  return set;
88
88
  }
89
89
  /** `scopeAllowed` with the provider-scope case answered by set membership:
90
- * `covers(held, '<p>:<g>')` is true only for `held === '<p>:<g>'`, so the
90
+ * `covers(held, '<p>:<g>')` is true only for `held` = `<p>:<g>` or `<p>:*`, so the
91
91
  * answer is identical and costs O(1) instead of a selector parse per held scope. */
92
92
  function holds(scopes, scope) {
93
93
  if (scopes === null)
94
94
  return true;
95
- if (isProviderScope(scope))
96
- return heldSet(scopes).has(scope);
95
+ if (isProviderScope(scope)) {
96
+ const set = heldSet(scopes);
97
+ return set.has(scope) || set.has(`${scope.slice(0, scope.indexOf(':'))}:*`);
98
+ }
97
99
  return scopeAllowed(scopes, scope);
98
100
  }
99
101
  /** Does the caller hold `<provider>:<group>`? Both the resolved set and a
@@ -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.758",
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",
@@ -59,8 +59,9 @@ function parseSelector(value) {
59
59
  if (match)
60
60
  return { kind: 'peer', value };
61
61
  match = /^([^:]+):([^:]+)$/.exec(value);
62
- if (match && match[1] !== 'crtr' && id.test(match[1]) && id.test(match[2]))
63
- return { kind: 'provider', value };
62
+ // `<provider>:*` means every group of that provider the grant may hold; it covers each `<provider>:<group>`.
63
+ if (match && match[1] !== 'crtr' && id.test(match[1]) && (match[2] === '*' || id.test(match[2])))
64
+ return { kind: 'provider', value, provider: match[1], group: match[2] };
64
65
  throw new TypeError(`Unsupported scope: ${value}`);
65
66
  }
66
67
  export function parseScope(value, grantee) {
@@ -90,6 +91,8 @@ export function covers(held, requested) {
90
91
  return h.holder === r.holder && (h.access === 'rw' || r.access === 'read') &&
91
92
  (h.path === '.' || h.path === r.path || r.path.startsWith(`${h.path}/`));
92
93
  }
94
+ if (h.kind === 'provider' && r.kind === 'provider')
95
+ return h.provider === r.provider && (h.group === '*' || h.group === r.group);
93
96
  return held === requested;
94
97
  }
95
98
  /** A directory fetch ran past its deadline (or was aborted by its caller before that). `code` is `deadline_exceeded`;
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.758",
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.758",
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.758",
31
- "@north-light/identity": "0.3.758"
30
+ "@north-light/api": "0.3.760",
31
+ "@north-light/identity": "0.3.760"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {