@north-light/plugin 0.3.750 → 0.3.751

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/define.d.ts CHANGED
@@ -19,8 +19,8 @@ export interface LeafCaller {
19
19
  /** The principal the grant was issued to: `app:<id>`, or the user for the person's own authority. */
20
20
  readonly grantee: string;
21
21
  /**
22
- * The principal charged for this call, `user:<id>` or `app:<id>`: the token's `payer` claim, or
23
- * `sub` when the token has none (a directory that predates payers). Receipts from `ctx.meter` carry it.
22
+ * The principal charged for this call: the token's `payer` claim, or the namespace owner of
23
+ * `grantee` when the token has none. Never defaults to `sub`. Receipts from `ctx.meter` carry it.
24
24
  */
25
25
  readonly payer: string;
26
26
  /** The OAuth client id of the runtime that presented the token; it authorizes nothing. */
@@ -33,6 +33,12 @@ export interface LeafCaller {
33
33
  readonly act: LeafCallerActor;
34
34
  /** The token's unique id, for the provider's audit. */
35
35
  readonly jti: string;
36
+ /** The innermost `act.sub`: the principal that actually made the call. */
37
+ readonly actor: string;
38
+ /** Accounts the token narrows the call to, by service; absent means no narrowing. */
39
+ readonly accounts?: Readonly<Record<string, readonly string[]>>;
40
+ /** Tool names the token allows; when present, a leaf outside it is refused. */
41
+ readonly tools?: readonly string[];
36
42
  /** The request's `Crtr-Request-Id`. */
37
43
  readonly requestId: string;
38
44
  /** The request's `Crtr-Run-Id`, when it carries one. */
@@ -6,6 +6,8 @@ export interface Receipt {
6
6
  readonly sub: string;
7
7
  readonly grantee: string;
8
8
  readonly payer: string;
9
+ /** The innermost `act.sub` of the token that made the call. */
10
+ readonly actor?: string;
9
11
  readonly units: number;
10
12
  readonly unit: string;
11
13
  readonly usd_equivalent: number;
package/dist/serve.js CHANGED
@@ -1,3 +1,3 @@
1
- var ne=Object.defineProperty;var s=(n,e)=>ne(n,"name",{value:e,configurable:!0});import{approvalFor as te}from"./approval.js";import{requestSpendCheck as re}from"./receipts.js";import{validateDeclaredResult as ie,validateValue as oe}from"@north-light/api/command-manifest";import{errorResponse as E,LeafError as T,leafErrorResponse as W,storedAnswerHeaders as de}from"./errors.js";import{buildCommandManifest as ae}from"./manifest.js";import{buildBundle as se}from"./bundle.js";import{parseCrtrCaller as ce}from"./caller.js";import{createCallerVerifier as ue,normalizeProviderId as fe,scopeMissing as le}from"./verify.js";const D=/^v([1-9][0-9]*)$/;function Ne(n,e={}){if(e.token!==void 0&&e.auth!==void 0)throw new Error("createFetchHandler takes either token or auth, not both");if(e.token!==void 0&&e.receipts!==void 0)throw new Error("createFetchHandler cannot meter with a static token");if(e.receipts!==void 0&&!/^app:[A-Za-z0-9_-]{1,64}$/.test(e.receipts.provider))throw new Error("createFetchHandler receipts.provider must be an app principal (app:<id>)");const i=e.auth===void 0?void 0:fe(e.auth),t=Array.isArray(n)||n.version!==void 0,r=pe(Array.isArray(n)?n:[n],Array.isArray(n),i),a=r[0].plugin.name;for(const f of r)for(const y of f.commands.values())if(y.leaf.sideEffect&&e.requests===void 0)throw new Error(`createFetchHandler needs requests for side-effect leaf ${y.path.join(" ")}`);const c=e.auth===void 0?void 0:ue(e.auth);if(c!==void 0){for(const f of r)for(const y of f.commands.values())if(y.scope===void 0)throw new Error(`createFetchHandler auth needs a group on every leaf; ${y.path.join(" ")} has none`)}const d=new Map,b=e.baseUrl===void 0?void 0:L(new URL(e.baseUrl).pathname),h=r[r.length-1];e.token===void 0&&e.auth===void 0&&console.warn(`crouter plugin ${a} is serving without bearer authentication`);const m=s(async(f,y,M)=>{const u=`${y.version}\0${M}`;let l=d.get(u);if(l===void 0){const _=await se(y.plugin,{mountPath:M,...i!==void 0?{providerId:i}:{},...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{}});l={tar:_.tar,etag:_.etag},d.set(u,l)}const p={ETag:l.etag};return f.headers.get("if-none-match")===l.etag?new Response(null,{status:304,headers:p}):new Response(new Uint8Array(l.tar).buffer,{headers:{...p,"Content-Type":"application/x-tar"}})},"archiveResponse");return async f=>{if(f.method!=="POST"&&e.token!==void 0&&!ee(f.headers.get("authorization")??"",`Bearer ${e.token}`))return E(401,{code:"unauthorized",message:"A valid bearer token is required.",next:"Send Authorization: Bearer <token>."});const y=new URL(f.url).pathname;if(f.method==="GET"){if(!t)return m(f,h,b??L(y));const w=H(y),$=w[w.length-1],R=b??L(`/${w.slice(0,-1).join("/")}`);if($==="versions")return Response.json({latest:h.version,supported:r.map(A=>A.version)});const N=$===void 0?null:D.exec($),k=N===null?void 0:r.find(A=>A.version===Number(N[1]));return k===void 0?G():m(f,k,`${R}/v${k.version}`)}if(f.method!=="POST")return G();const M=performance.now();let u,l;const p=[];let _=[],B=null,J=!1,P=!1;const v=s(w=>{if(l!==void 0)try{e.onAnswer?.({...u===void 0?{}:{sub:u.sub,grantee:u.grantee,initiatingApp:u.initiatingApp,act:u.act,jti:u.jti,requestId:u.requestId,...u.runId===void 0?{}:{runId:u.runId}},...u===void 0&&g!==null&&g!==""?{requestId:g}:{},tool:l.path.slice(1).join(" "),status:w.status,durationMs:performance.now()-M,...p.length===0?{}:{receiptId:p[0].receipt_id},...p.length>1?{receiptIds:p.map($=>$.receipt_id)}:{},replayed:P})}catch{}return w},"answer");let g=f.headers.get("crtr-request-id");try{if(l=t?ye(r,y):ge(h.commands,y),e.token!==void 0&&!ee(f.headers.get("authorization")??"",`Bearer ${e.token}`))return v(E(401,{code:"unauthorized",message:"A valid bearer token is required.",next:"Send Authorization: Bearer <token>."}));const w=c===void 0?void 0:await c(f);if(l===void 0){const o=t?be(r,y):void 0;return v(o===void 0?G():ke(o,r))}if(w!==void 0&&!w.scope.includes(l.scope)){u=Object.freeze({...w,requestId:g??"",...f.headers.get("crtr-run-id")?{runId:f.headers.get("crtr-run-id")}:{}});const o=l.leaf.group,j=i===void 0&&o!==void 0?w.scope.find(x=>x.endsWith(`:${o}`)&&x.length>o.length+1)?.slice(0,-(o.length+1)):void 0;throw le(l.scope,j)}if(w!==void 0){if(g===null||g==="")return v(E(400,{code:"invalid_request",message:"The request carries no Crtr-Request-Id header."}));const o=f.headers.get("crtr-run-id"),j=ce(f.headers.get("crtr-caller"));u=Object.freeze({...w,requestId:g,...o!==null&&o!==""?{runId:o}:{},...Object.keys(j).length>0?{crtr:Object.freeze(j)}:{}})}const $=await je(f,l.manifest,w!==void 0);if(l.leaf.sideEffect){if(g===null||g==="")return v(E(400,{code:"invalid_request",message:"The request carries no Crtr-Request-Id header."}));const o=u===void 0?null:{sub:u.sub,grantee:u.grantee};if(!await e.requests.record(g,o)){P=!0;const x=await me(e.requests,g,o,l.plugin.timeouts?.requestMs??3e4);if(x!==!0){const S=x.headers.get("Crtr-Receipt");if(S!==null)try{const C=JSON.parse(S);p.push(...Array.isArray(C)?C:[C])}catch{}return v(x)}P=!1}J=!0}const R=l,N={request:f,...u!==void 0?{caller:u}:{},...g!==null&&g!==""?{causedBy:`request:${g}`}:{},approval:te(f),meter(o){if(u===void 0)throw new Error("ctx.meter needs an authenticated caller");if(p.some(I=>I.unit===o.unit))throw new Error(`ctx.meter may be called only once for unit ${o.unit}`);if(e.receipts===void 0)throw new Error("ctx.meter needs receipts with a provider and outbox");const j=o.receiptId??u.requestId;if(p.some(I=>I.receipt_id===j))throw new Error(`ctx.meter needs a distinct receiptId for each unit; ${j} is taken`);const x=R.path.slice(1).join(" "),S=_.find(I=>I.mode==="unit"&&I.unit===o.unit),C=o.usdEquivalent??(S?.usd_per_unit!=null?o.units*S.usd_per_unit:0),V={receipt_id:j,provider:e.receipts.provider,tool:x,sub:u.sub,grantee:u.grantee,payer:u.payer,units:o.units,unit:o.unit,usd_equivalent:C,request_id:u.requestId,...u.runId!==void 0?{run_id:u.runId}:{},...B!==null?{admission_id:B}:{},time:new Date().toISOString()};return p.push(V),V},async checkSpend(){if(u===void 0)throw new Error("ctx.checkSpend needs an authenticated caller");if(e.receipts===void 0)throw new Error("ctx.checkSpend needs receipts with a provider and outbox");if(e.receipts.ledger===void 0)throw new Error("ctx.checkSpend needs receipts.ledger (the provider's directory client credentials)");const o=/^Bearer ([^\s]+)$/.exec(f.headers.get("authorization")??"")?.[1];if(o===void 0)throw new Error("ctx.checkSpend needs the request's bearer token");const j=await re(e.auth.issuer,o,R.path.slice(1).join(" "),e.receipts.ledger);return _=j.prices,B=j.admission_id,j}};let k,A;try{const o=await l.leaf.run($,N);k=l.leaf.streaming?await $e(o,e.onError,l.path):Ee(o,l.manifest)}catch(o){o instanceof T?(k=W(o),A=o.headers):(U(e.onError,o,l.path),k=z(o))}if(J&&k.status===403&&await he(k))return await e.requests.delete(g),v(Z(k,p));try{if(J)await e.requests.store(g,{status:k.status,body:await k.clone().text(),...A!==void 0?{headers:{...A}}:{},...p.length>0?{receipt:p[0]}:{},...p.length>1?{receipts:[...p]}:{}});else if(p.length>0){if(e.receipts===void 0)throw new Error(`No receipt outbox for ${R.path.join(" ")}`);for(const o of p)await e.receipts.outbox.save(o)}}catch(o){return U(e.onError,o,l.path,p),v(z(o))}return v(Z(k,p))}catch(w){return w instanceof T?v(W(w)):(U(e.onError,w,l?.path??[]),v(z(w)))}}}s(Ne,"createFetchHandler");function z(n){return E(500,{code:"handler_failed",message:n instanceof Error?n.message:String(n)})}s(z,"handlerFailed");function Z(n,e){if(e.length===0)return n;const i=new Headers(n.headers);return i.set("Crtr-Receipt",K(e)),new Response(n.body,{status:n.status,headers:i})}s(Z,"responseWithReceipts");function K(n){return JSON.stringify(n.length===1?n[0]:n)}s(K,"receiptHeader");async function he(n){try{const e=await n.clone().json();return F(e)&&F(e.error)&&e.error.code==="approval_required"}catch{return!1}}s(he,"isApprovalRequired");async function me(n,e,i,t){for(;;){const r=await n.read(e);if(r===null){if(await n.record(e,i))return!0;continue}if(r.identity?.sub!==i?.sub||r.identity?.grantee!==i?.grantee)return E(403,{code:"provider_refused",message:"This request id belongs to a different caller."});if(r.answer!==null){const a=de(r.answer.headers);a.set("Content-Type","application/json");const c=r.answer.receipts??(r.answer.receipt===void 0?[]:[r.answer.receipt]);return c.length>0&&a.set("Crtr-Receipt",K(c)),new Response(r.answer.body,{status:r.answer.status,headers:a})}if(Date.now()>=new Date(r.recordedAt).getTime()+t)return z(new Error("The earlier request has no stored answer."));await new Promise(a=>setTimeout(a,Math.min(25,Math.max(1,new Date(r.recordedAt).getTime()+t-Date.now()))))}}s(me,"replay");function pe(n,e,i){if(n.length===0)throw new Error("createFetchHandler needs at least one plugin definition");const t=n[0].name,r=new Map;for(const a of n){if(a.name!==t)throw new Error(`createFetchHandler serves one plugin; got ${t} and ${a.name}`);if(e&&a.version===void 0)throw new Error(`createFetchHandler needs an explicit version on every definition in an array; ${t} has none`);const c=a.version??1;if(r.has(c))throw new Error(`createFetchHandler got two definitions of ${t} major ${c}`);r.set(c,{version:c,plugin:a,commands:we(a,i)})}return[...r.values()].sort((a,c)=>a.version-c.version)}s(pe,"servedMajors");function we(n,e){const t=ae(n,{mountPath:""}).mounts[0]?.node;if(t===void 0||t.kind!=="branch")throw new Error("Generated plugin manifest has no root branch");const r=new Map;return Q(t.children,n.commands,[t.name],n,r,e),r}s(we,"commandMap");function Q(n,e,i,t,r,a){const c=Object.entries(e);if(n.length!==c.length)throw new Error("Generated plugin manifest does not match the command definition");for(const[d,[b,h]]of c.entries()){const m=n[d];if(m===void 0||m.kind!==h.kind)throw new Error(`Generated plugin manifest does not match command ${b}`);const f=[...i,m.name];if(m.kind==="branch"&&h.kind==="branch"){Q(m.children,h.children,f,t,r,a);continue}if(m.kind==="leaf"&&h.kind==="leaf"){r.set(f.join("/"),{path:f,leaf:h,plugin:t,manifest:m,...h.group!==void 0?{scope:`${a??t.name}:${h.group}`}:{}});continue}throw new Error(`Generated plugin manifest does not match command ${b}`)}}s(Q,"collectCommands");function ge(n,e){const i=H(e);for(let t=0;t<i.length;t+=1){const r=n.get(i.slice(t).join("/"));if(r!==void 0)return r}}s(ge,"findCommand");function ye(n,e){const i=H(e);for(let t=i.length-2;t>=0;t-=1){const r=D.exec(i[t]);if(r===null)continue;const c=n.find(d=>d.version===Number(r[1]))?.commands.get(i.slice(t+1).join("/"));if(c!==void 0)return c}}s(ye,"findVersionedCommand");function be(n,e){const i=H(e);for(let t=i.length-2;t>=0;t-=1){const r=D.exec(i[t]);if(r!==null)return n.some(a=>a.version===Number(r[1]))?void 0:Number(r[1])}}s(be,"unservedMajor");function ke(n,e){return E(410,{code:"unsupported_major",message:`Major ${n} is not served; supported majors: ${e.map(i=>i.version).join(", ")}.`,next:"Refetch the provider bundle and retry with its current major.",received:n})}s(ke,"unsupportedMajor");function H(n){return n.split("/").filter(e=>e.length>0)}s(H,"pathSegments");async function je(n,e,i){const t=n.body===null?"":await n.text();let r;if(t.length===0)r={};else try{const d=JSON.parse(t);if(!F(d))throw new Error("not an object");r=d}catch{throw q("Request body must be a JSON object.",i?"body":void 0,i,t)}const a=new Map(e.params.map(d=>[d.name,d]));for(const d of Object.keys(r))if(!a.has(d))throw i?q(`Unknown parameter ${d}.`,d,!0,r[d]):new T({code:"unknown_parameter",message:`Unknown parameter ${d}.`,field:d});const c={};for(const d of e.params){if(!Object.hasOwn(r,d.name)){if(d.required)throw q(`Missing required parameter ${d.name}.`,d.name,i,null);continue}const b=r[d.name];if(d.kind==="flag"&&d.type==="json"){const m=oe(d.shape,b,d.name);if(m!==null)throw q(`Invalid value for ${m.path}: expected ${m.expected}, got ${m.receivedType}.`,m.path,i,b);c[Y(d.name)]=b;continue}const h=ve(b,d);if(h===void 0)throw q(`Invalid value for parameter ${d.name}.`,d.name,i,b);c[Y(d.name)]=h}return c}s(je,"decodeInput");function ve(n,e){if(e.kind!=="stdin"&&e.kind!=="context-file"&&e.repeatable){if(!Array.isArray(n))return;const i=n.map(t=>X(t,e));return i.some(t=>t===void 0)?void 0:i}return X(n,e)}s(ve,"decodeParameter");function X(n,e){if(e.kind==="stdin"||e.kind==="positional")return typeof n=="string"?n:void 0;if(e.kind!=="context-file"){if(e.type==="string")return typeof n=="string"?n:void 0;if(e.type==="int")return typeof n=="number"&&Number.isInteger(n)?n:void 0;if(e.type==="bool")return typeof n=="boolean"?n:void 0;if(e.type==="enum")return typeof n=="string"&&Array.isArray(e.choices)&&e.choices.includes(n)?n:void 0;if(e.type==="file")return typeof n=="string"?n:void 0;if(e.type==="path")return typeof n!="string"?void 0:e.encoding==="base64"?xe(n):n}}s(X,"decodeScalar");function xe(n){if(!(!/^[A-Za-z0-9+/]*={0,2}$/.test(n)||n.length%4!==0))try{const e=atob(n);return Uint8Array.from(e,i=>i.charCodeAt(0))}catch{return}}s(xe,"decodeBase64");function Ee(n,e){let i,t;try{i=JSON.stringify(n),t=JSON.parse(i)}catch{throw O("result")}if(!F(t))throw O("result");const r=ie(e.output,t,!0);if(r!==null)throw O(r.field,r.receivedType);for(const a of Object.keys(t))if(!e.output.some(c=>c.name===a))throw O(a);return new Response(i,{headers:{"Content-Type":"application/json"}})}s(Ee,"resultResponse");async function $e(n,e,i){if(!Ae(n))throw O("result");const t=n[Symbol.asyncIterator](),r=new TextEncoder,a=await t.next();let c=a.done,d=c?void 0:r.encode(`${JSON.stringify(a.value)}
2
- `);const b=new ReadableStream({async pull(h){if(d!==void 0){h.enqueue(d),d=void 0;return}if(c){h.close();return}try{const m=await t.next();m.done?(c=!0,h.close()):h.enqueue(r.encode(`${JSON.stringify(m.value)}
3
- `))}catch(m){U(e,m,i),h.error(m)}},async cancel(h){await t.return?.(h)}});return new Response(b,{headers:{"Content-Type":"application/x-ndjson"}})}s($e,"streamResponse");function U(n,e,i,t=[]){try{t.length>1?n?.(e,i,t[0],t):n?.(e,i,t[0])}catch{}}s(U,"reportUnhandledError");function O(n,e){return new T({code:"handler_output_invalid",message:`Handler returned an invalid value for ${n}.`,status:500,field:n,...e!==void 0?{received:e}:{}})}s(O,"outputInvalid");function q(n,e,i=!1,t){return new T({code:i?"invalid_argument":"invalid_input",message:n,...e!==void 0?{field:e}:{},...i?{received:t}:{}})}s(q,"invalidInput");function G(){return E(404,{code:"no_such_command",message:"No command matches this request."})}s(G,"noSuchCommand");function L(n){return n==="/"?"":n.replace(/\/+$/,"")}s(L,"mountPath");function Y(n){return n.replace(/-([a-z])/g,(e,i)=>i.toUpperCase())}s(Y,"camel");function ee(n,e){const i=new TextEncoder().encode(n),t=new TextEncoder().encode(e);let r=i.length^t.length;for(let a=0;a<Math.min(i.length,t.length);a+=1)r|=i[a]^t[a];return r===0}s(ee,"constantTimeEqual");function F(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}s(F,"isRecord");function Ae(n){return typeof n=="object"&&n!==null&&Symbol.asyncIterator in n}s(Ae,"isAsyncIterable");export{Ne as createFetchHandler};
1
+ var te=Object.defineProperty;var s=(n,e)=>te(n,"name",{value:e,configurable:!0});import{approvalFor as re}from"./approval.js";import{requestSpendCheck as ie}from"./receipts.js";import{validateDeclaredResult as oe,validateValue as de}from"@north-light/api/command-manifest";import{errorResponse as E,LeafError as T,leafErrorResponse as W,storedAnswerHeaders as ae}from"./errors.js";import{buildCommandManifest as se}from"./manifest.js";import{buildBundle as ce}from"./bundle.js";import{parseCrtrCaller as ue}from"./caller.js";import{createCallerVerifier as fe,normalizeProviderId as le,scopeMissing as Z}from"./verify.js";const D=/^v([1-9][0-9]*)$/;function Ne(n,e={}){if(e.token!==void 0&&e.auth!==void 0)throw new Error("createFetchHandler takes either token or auth, not both");if(e.token!==void 0&&e.receipts!==void 0)throw new Error("createFetchHandler cannot meter with a static token");if(e.receipts!==void 0&&!/^app:[A-Za-z0-9_-]{1,64}$/.test(e.receipts.provider))throw new Error("createFetchHandler receipts.provider must be an app principal (app:<id>)");const i=e.auth===void 0?void 0:le(e.auth),t=Array.isArray(n)||n.version!==void 0,r=pe(Array.isArray(n)?n:[n],Array.isArray(n),i),a=r[0].plugin.name;for(const f of r)for(const y of f.commands.values())if(y.leaf.sideEffect&&e.requests===void 0)throw new Error(`createFetchHandler needs requests for side-effect leaf ${y.path.join(" ")}`);const u=e.auth===void 0?void 0:fe(e.auth);if(u!==void 0){for(const f of r)for(const y of f.commands.values())if(y.scope===void 0)throw new Error(`createFetchHandler auth needs a group on every leaf; ${y.path.join(" ")} has none`)}const d=new Map,b=e.baseUrl===void 0?void 0:L(new URL(e.baseUrl).pathname),h=r[r.length-1];e.token===void 0&&e.auth===void 0&&console.warn(`crouter plugin ${a} is serving without bearer authentication`);const m=s(async(f,y,M)=>{const c=`${y.version}\0${M}`;let l=d.get(c);if(l===void 0){const _=await ce(y.plugin,{mountPath:M,...i!==void 0?{providerId:i}:{},...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{}});l={tar:_.tar,etag:_.etag},d.set(c,l)}const w={ETag:l.etag};return f.headers.get("if-none-match")===l.etag?new Response(null,{status:304,headers:w}):new Response(new Uint8Array(l.tar).buffer,{headers:{...w,"Content-Type":"application/x-tar"}})},"archiveResponse");return async f=>{if(f.method!=="POST"&&e.token!==void 0&&!ne(f.headers.get("authorization")??"",`Bearer ${e.token}`))return E(401,{code:"unauthorized",message:"A valid bearer token is required.",next:"Send Authorization: Bearer <token>."});const y=new URL(f.url).pathname;if(f.method==="GET"){if(!t)return m(f,h,b??L(y));const p=H(y),$=p[p.length-1],R=b??L(`/${p.slice(0,-1).join("/")}`);if($==="versions")return Response.json({latest:h.version,supported:r.map(A=>A.version)});const N=$===void 0?null:D.exec($),j=N===null?void 0:r.find(A=>A.version===Number(N[1]));return j===void 0?G():m(f,j,`${R}/v${j.version}`)}if(f.method!=="POST")return G();const M=performance.now();let c,l;const w=[];let _=[],B=null,J=!1,P=!1;const v=s(p=>{if(l!==void 0)try{e.onAnswer?.({...c===void 0?{}:{sub:c.sub,grantee:c.grantee,initiatingApp:c.initiatingApp,act:c.act,jti:c.jti,requestId:c.requestId,...c.runId===void 0?{}:{runId:c.runId}},...c===void 0&&g!==null&&g!==""?{requestId:g}:{},tool:l.path.slice(1).join(" "),status:p.status,durationMs:performance.now()-M,...w.length===0?{}:{receiptId:w[0].receipt_id},...w.length>1?{receiptIds:w.map($=>$.receipt_id)}:{},replayed:P})}catch{}return p},"answer");let g=f.headers.get("crtr-request-id");try{if(l=t?ye(r,y):ge(h.commands,y),e.token!==void 0&&!ne(f.headers.get("authorization")??"",`Bearer ${e.token}`))return v(E(401,{code:"unauthorized",message:"A valid bearer token is required.",next:"Send Authorization: Bearer <token>."}));const p=u===void 0?void 0:await u(f);if(l===void 0){const o=t?be(r,y):void 0;return v(o===void 0?G():je(o,r))}if(p!==void 0&&!p.scope.includes(l.scope)){c=Object.freeze({...p,requestId:g??"",...f.headers.get("crtr-run-id")?{runId:f.headers.get("crtr-run-id")}:{}});const o=l.leaf.group,k=i===void 0&&o!==void 0?p.scope.find(x=>x.endsWith(`:${o}`)&&x.length>o.length+1)?.slice(0,-(o.length+1)):void 0;throw Z(l.scope,k)}if(p?.tools!==void 0&&!p.tools.includes(l.path.slice(1).join(" ")))throw Z(`${l.scope} (tool ${l.path.slice(1).join(" ")})`);if(p!==void 0){if(g===null||g==="")return v(E(400,{code:"invalid_request",message:"The request carries no Crtr-Request-Id header."}));const o=f.headers.get("crtr-run-id"),k=ue(f.headers.get("crtr-caller"));c=Object.freeze({...p,requestId:g,...o!==null&&o!==""?{runId:o}:{},...Object.keys(k).length>0?{crtr:Object.freeze(k)}:{}})}const $=await ke(f,l.manifest,p!==void 0);if(l.leaf.sideEffect){if(g===null||g==="")return v(E(400,{code:"invalid_request",message:"The request carries no Crtr-Request-Id header."}));const o=c===void 0?null:{sub:c.sub,grantee:c.grantee};if(!await e.requests.record(g,o)){P=!0;const x=await me(e.requests,g,o,l.plugin.timeouts?.requestMs??3e4);if(x!==!0){const S=x.headers.get("Crtr-Receipt");if(S!==null)try{const C=JSON.parse(S);w.push(...Array.isArray(C)?C:[C])}catch{}return v(x)}P=!1}J=!0}const R=l,N={request:f,...c!==void 0?{caller:c}:{},...g!==null&&g!==""?{causedBy:`request:${g}`}:{},approval:re(f),meter(o){if(c===void 0)throw new Error("ctx.meter needs an authenticated caller");if(w.some(I=>I.unit===o.unit))throw new Error(`ctx.meter may be called only once for unit ${o.unit}`);if(e.receipts===void 0)throw new Error("ctx.meter needs receipts with a provider and outbox");const k=o.receiptId??c.requestId;if(w.some(I=>I.receipt_id===k))throw new Error(`ctx.meter needs a distinct receiptId for each unit; ${k} is taken`);const x=R.path.slice(1).join(" "),S=_.find(I=>I.mode==="unit"&&I.unit===o.unit),C=o.usdEquivalent??(S?.usd_per_unit!=null?o.units*S.usd_per_unit:0),V={receipt_id:k,provider:e.receipts.provider,tool:x,sub:c.sub,grantee:c.grantee,payer:c.payer,actor:c.actor,units:o.units,unit:o.unit,usd_equivalent:C,request_id:c.requestId,...c.runId!==void 0?{run_id:c.runId}:{},...B!==null?{admission_id:B}:{},time:new Date().toISOString()};return w.push(V),V},async checkSpend(){if(c===void 0)throw new Error("ctx.checkSpend needs an authenticated caller");if(e.receipts===void 0)throw new Error("ctx.checkSpend needs receipts with a provider and outbox");if(e.receipts.ledger===void 0)throw new Error("ctx.checkSpend needs receipts.ledger (the provider's directory client credentials)");const o=/^Bearer ([^\s]+)$/.exec(f.headers.get("authorization")??"")?.[1];if(o===void 0)throw new Error("ctx.checkSpend needs the request's bearer token");const k=await ie(e.auth.issuer,o,R.path.slice(1).join(" "),e.receipts.ledger);return _=k.prices,B=k.admission_id,k}};let j,A;try{const o=await l.leaf.run($,N);j=l.leaf.streaming?await $e(o,e.onError,l.path):Ee(o,l.manifest)}catch(o){o instanceof T?(j=W(o),A=o.headers):(U(e.onError,o,l.path),j=z(o))}if(J&&j.status===403&&await he(j))return await e.requests.delete(g),v(K(j,w));try{if(J)await e.requests.store(g,{status:j.status,body:await j.clone().text(),...A!==void 0?{headers:{...A}}:{},...w.length>0?{receipt:w[0]}:{},...w.length>1?{receipts:[...w]}:{}});else if(w.length>0){if(e.receipts===void 0)throw new Error(`No receipt outbox for ${R.path.join(" ")}`);for(const o of w)await e.receipts.outbox.save(o)}}catch(o){return U(e.onError,o,l.path,w),v(z(o))}return v(K(j,w))}catch(p){return p instanceof T?v(W(p)):(U(e.onError,p,l?.path??[]),v(z(p)))}}}s(Ne,"createFetchHandler");function z(n){return E(500,{code:"handler_failed",message:n instanceof Error?n.message:String(n)})}s(z,"handlerFailed");function K(n,e){if(e.length===0)return n;const i=new Headers(n.headers);return i.set("Crtr-Receipt",Q(e)),new Response(n.body,{status:n.status,headers:i})}s(K,"responseWithReceipts");function Q(n){return JSON.stringify(n.length===1?n[0]:n)}s(Q,"receiptHeader");async function he(n){try{const e=await n.clone().json();return F(e)&&F(e.error)&&e.error.code==="approval_required"}catch{return!1}}s(he,"isApprovalRequired");async function me(n,e,i,t){for(;;){const r=await n.read(e);if(r===null){if(await n.record(e,i))return!0;continue}if(r.identity?.sub!==i?.sub||r.identity?.grantee!==i?.grantee)return E(403,{code:"provider_refused",message:"This request id belongs to a different caller."});if(r.answer!==null){const a=ae(r.answer.headers);a.set("Content-Type","application/json");const u=r.answer.receipts??(r.answer.receipt===void 0?[]:[r.answer.receipt]);return u.length>0&&a.set("Crtr-Receipt",Q(u)),new Response(r.answer.body,{status:r.answer.status,headers:a})}if(Date.now()>=new Date(r.recordedAt).getTime()+t)return z(new Error("The earlier request has no stored answer."));await new Promise(a=>setTimeout(a,Math.min(25,Math.max(1,new Date(r.recordedAt).getTime()+t-Date.now()))))}}s(me,"replay");function pe(n,e,i){if(n.length===0)throw new Error("createFetchHandler needs at least one plugin definition");const t=n[0].name,r=new Map;for(const a of n){if(a.name!==t)throw new Error(`createFetchHandler serves one plugin; got ${t} and ${a.name}`);if(e&&a.version===void 0)throw new Error(`createFetchHandler needs an explicit version on every definition in an array; ${t} has none`);const u=a.version??1;if(r.has(u))throw new Error(`createFetchHandler got two definitions of ${t} major ${u}`);r.set(u,{version:u,plugin:a,commands:we(a,i)})}return[...r.values()].sort((a,u)=>a.version-u.version)}s(pe,"servedMajors");function we(n,e){const t=se(n,{mountPath:""}).mounts[0]?.node;if(t===void 0||t.kind!=="branch")throw new Error("Generated plugin manifest has no root branch");const r=new Map;return X(t.children,n.commands,[t.name],n,r,e),r}s(we,"commandMap");function X(n,e,i,t,r,a){const u=Object.entries(e);if(n.length!==u.length)throw new Error("Generated plugin manifest does not match the command definition");for(const[d,[b,h]]of u.entries()){const m=n[d];if(m===void 0||m.kind!==h.kind)throw new Error(`Generated plugin manifest does not match command ${b}`);const f=[...i,m.name];if(m.kind==="branch"&&h.kind==="branch"){X(m.children,h.children,f,t,r,a);continue}if(m.kind==="leaf"&&h.kind==="leaf"){r.set(f.join("/"),{path:f,leaf:h,plugin:t,manifest:m,...h.group!==void 0?{scope:`${a??t.name}:${h.group}`}:{}});continue}throw new Error(`Generated plugin manifest does not match command ${b}`)}}s(X,"collectCommands");function ge(n,e){const i=H(e);for(let t=0;t<i.length;t+=1){const r=n.get(i.slice(t).join("/"));if(r!==void 0)return r}}s(ge,"findCommand");function ye(n,e){const i=H(e);for(let t=i.length-2;t>=0;t-=1){const r=D.exec(i[t]);if(r===null)continue;const u=n.find(d=>d.version===Number(r[1]))?.commands.get(i.slice(t+1).join("/"));if(u!==void 0)return u}}s(ye,"findVersionedCommand");function be(n,e){const i=H(e);for(let t=i.length-2;t>=0;t-=1){const r=D.exec(i[t]);if(r!==null)return n.some(a=>a.version===Number(r[1]))?void 0:Number(r[1])}}s(be,"unservedMajor");function je(n,e){return E(410,{code:"unsupported_major",message:`Major ${n} is not served; supported majors: ${e.map(i=>i.version).join(", ")}.`,next:"Refetch the provider bundle and retry with its current major.",received:n})}s(je,"unsupportedMajor");function H(n){return n.split("/").filter(e=>e.length>0)}s(H,"pathSegments");async function ke(n,e,i){const t=n.body===null?"":await n.text();let r;if(t.length===0)r={};else try{const d=JSON.parse(t);if(!F(d))throw new Error("not an object");r=d}catch{throw q("Request body must be a JSON object.",i?"body":void 0,i,t)}const a=new Map(e.params.map(d=>[d.name,d]));for(const d of Object.keys(r))if(!a.has(d))throw i?q(`Unknown parameter ${d}.`,d,!0,r[d]):new T({code:"unknown_parameter",message:`Unknown parameter ${d}.`,field:d});const u={};for(const d of e.params){if(!Object.hasOwn(r,d.name)){if(d.required)throw q(`Missing required parameter ${d.name}.`,d.name,i,null);continue}const b=r[d.name];if(d.kind==="flag"&&d.type==="json"){const m=de(d.shape,b,d.name);if(m!==null)throw q(`Invalid value for ${m.path}: expected ${m.expected}, got ${m.receivedType}.`,m.path,i,b);u[ee(d.name)]=b;continue}const h=ve(b,d);if(h===void 0)throw q(`Invalid value for parameter ${d.name}.`,d.name,i,b);u[ee(d.name)]=h}return u}s(ke,"decodeInput");function ve(n,e){if(e.kind!=="stdin"&&e.kind!=="context-file"&&e.repeatable){if(!Array.isArray(n))return;const i=n.map(t=>Y(t,e));return i.some(t=>t===void 0)?void 0:i}return Y(n,e)}s(ve,"decodeParameter");function Y(n,e){if(e.kind==="stdin"||e.kind==="positional")return typeof n=="string"?n:void 0;if(e.kind!=="context-file"){if(e.type==="string")return typeof n=="string"?n:void 0;if(e.type==="int")return typeof n=="number"&&Number.isInteger(n)?n:void 0;if(e.type==="bool")return typeof n=="boolean"?n:void 0;if(e.type==="enum")return typeof n=="string"&&Array.isArray(e.choices)&&e.choices.includes(n)?n:void 0;if(e.type==="file")return typeof n=="string"?n:void 0;if(e.type==="path")return typeof n!="string"?void 0:e.encoding==="base64"?xe(n):n}}s(Y,"decodeScalar");function xe(n){if(!(!/^[A-Za-z0-9+/]*={0,2}$/.test(n)||n.length%4!==0))try{const e=atob(n);return Uint8Array.from(e,i=>i.charCodeAt(0))}catch{return}}s(xe,"decodeBase64");function Ee(n,e){let i,t;try{i=JSON.stringify(n),t=JSON.parse(i)}catch{throw O("result")}if(!F(t))throw O("result");const r=oe(e.output,t,!0);if(r!==null)throw O(r.field,r.receivedType);for(const a of Object.keys(t))if(!e.output.some(u=>u.name===a))throw O(a);return new Response(i,{headers:{"Content-Type":"application/json"}})}s(Ee,"resultResponse");async function $e(n,e,i){if(!Ae(n))throw O("result");const t=n[Symbol.asyncIterator](),r=new TextEncoder,a=await t.next();let u=a.done,d=u?void 0:r.encode(`${JSON.stringify(a.value)}
2
+ `);const b=new ReadableStream({async pull(h){if(d!==void 0){h.enqueue(d),d=void 0;return}if(u){h.close();return}try{const m=await t.next();m.done?(u=!0,h.close()):h.enqueue(r.encode(`${JSON.stringify(m.value)}
3
+ `))}catch(m){U(e,m,i),h.error(m)}},async cancel(h){await t.return?.(h)}});return new Response(b,{headers:{"Content-Type":"application/x-ndjson"}})}s($e,"streamResponse");function U(n,e,i,t=[]){try{t.length>1?n?.(e,i,t[0],t):n?.(e,i,t[0])}catch{}}s(U,"reportUnhandledError");function O(n,e){return new T({code:"handler_output_invalid",message:`Handler returned an invalid value for ${n}.`,status:500,field:n,...e!==void 0?{received:e}:{}})}s(O,"outputInvalid");function q(n,e,i=!1,t){return new T({code:i?"invalid_argument":"invalid_input",message:n,...e!==void 0?{field:e}:{},...i?{received:t}:{}})}s(q,"invalidInput");function G(){return E(404,{code:"no_such_command",message:"No command matches this request."})}s(G,"noSuchCommand");function L(n){return n==="/"?"":n.replace(/\/+$/,"")}s(L,"mountPath");function ee(n){return n.replace(/-([a-z])/g,(e,i)=>i.toUpperCase())}s(ee,"camel");function ne(n,e){const i=new TextEncoder().encode(n),t=new TextEncoder().encode(e);let r=i.length^t.length;for(let a=0;a<Math.min(i.length,t.length);a+=1)r|=i[a]^t[a];return r===0}s(ne,"constantTimeEqual");function F(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}s(F,"isRecord");function Ae(n){return typeof n=="object"&&n!==null&&Symbol.asyncIterator in n}s(Ae,"isAsyncIterable");export{Ne as createFetchHandler};
package/dist/verify.js CHANGED
@@ -1 +1 @@
1
- var I=Object.defineProperty;var t=(e,r)=>I(e,"name",{value:r,configurable:!0});import{JwksCache as z,verifyCallToken as A}from"@north-light/identity";import{kitLeafError as b}from"./errors.js";const j=/^[A-Za-z0-9_-]{1,64}$/,_=/^(app|user):[A-Za-z0-9_-]{1,64}$/,w=t(e=>typeof e=="string"&&_.test(e),"isAppOrUser"),y=t(e=>typeof e=="string"&&e!=="","isNonEmpty");function $(e){if(e.providerId===void 0)return;const r=typeof e.providerId=="string"&&e.providerId.startsWith("app:")?e.providerId.slice(4):e.providerId;if(typeof r!="string"||!j.test(r))throw new Error("createFetchHandler auth.providerId must be a provider id (1-64 characters of A-Z a-z 0-9 _ -), bare or as app:<id>");return r}t($,"normalizeProviderId");function C(e){if(typeof e!="object"||e===null)throw new Error("createFetchHandler auth must be {issuer, audience}");if(typeof e.issuer!="string"||e.issuer==="")throw new Error("createFetchHandler auth.issuer must be a non-empty string");if(typeof e.audience!="string"||e.audience==="")throw new Error("createFetchHandler auth.audience must be a non-empty string");$(e);const{issuer:r,audience:g}=e,m=new z(r,(d,n)=>fetch(d,n),`${r.replace(/\/+$/,"")}/.well-known/jwks.json`);return async d=>{const n=/^Bearer ([^\s]+)$/.exec(d.headers.get("authorization")??"");if(n===null)throw a("The request carries no bearer token.");let i;try{i=await A({token:n[1],jwks:m,issuer:r,audience:g})}catch{throw a("The bearer token is not a valid outbound token for this provider.")}const{claims:c,chain:k,scope:p}=i,{grantee:u,initiating_app:f,jti:h,act:l}=c,o=l;if(p===void 0||!w(u)||!w(f)||!y(h)||k.length===0||typeof o!="object"||o===null||Array.isArray(o)||!y(o.sub))throw a("The bearer token is not a valid outbound token for this provider.");const s=c.payer;if(s!==void 0&&!/^(user|app):[A-Za-z0-9_-]{1,64}$/.test(String(s)))throw a("The bearer token is not a valid outbound token for this provider.");return Object.freeze({sub:i.sub,grantee:u,payer:s===void 0?i.sub:String(s),clientId:c.client_id,scope:Object.freeze(p.split(" ").filter(v=>v.length>0)),initiatingApp:f,act:l,jti:h})}}t(C,"createCallerVerifier");function F(e,r){return b({code:"scope_missing",status:403,message:`The token does not carry ${e}, which this command needs.`,field:e,received:e,...r!==void 0?{next:`Set auth.providerId to your app's client id (${r}).`}:{}})}t(F,"scopeMissing");function a(e){return b({code:"unauthorized",status:401,message:e,next:"Send a current outbound token for this provider as Authorization: Bearer <token>."})}t(a,"unauthorized");export{C as createCallerVerifier,$ as normalizeProviderId,F as scopeMissing};
1
+ var E=Object.defineProperty;var t=(e,r)=>E(e,"name",{value:r,configurable:!0});import{JwksCache as x,parsePrincipal as j,verifyCallToken as O}from"@north-light/identity";import{kitLeafError as A}from"./errors.js";const _=/^[A-Za-z0-9_-]{1,64}$/,y=t(e=>typeof e=="string"&&j(e)!==null,"isPrincipal"),d=t(e=>typeof e=="string"&&e!=="","isNonEmpty");function $(e){if(e.providerId===void 0)return;const r=typeof e.providerId=="string"&&e.providerId.startsWith("app:")?e.providerId.slice(4):e.providerId;if(typeof r!="string"||!_.test(r))throw new Error("createFetchHandler auth.providerId must be a provider id (1-64 characters of A-Z a-z 0-9 _ -), bare or as app:<id>");return r}t($,"normalizeProviderId");function R(e){if(typeof e!="object"||e===null)throw new Error("createFetchHandler auth must be {issuer, audience}");if(typeof e.issuer!="string"||e.issuer==="")throw new Error("createFetchHandler auth.issuer must be a non-empty string");if(typeof e.audience!="string"||e.audience==="")throw new Error("createFetchHandler auth.audience must be a non-empty string");$(e);const{issuer:r,audience:u}=e,o=new x(r,(f,s)=>fetch(f,s),`${r.replace(/\/+$/,"")}/.well-known/jwks.json`);return async f=>{const s=/^Bearer ([^\s]+)$/.exec(f.headers.get("authorization")??"");if(s===null)throw n("The request carries no bearer token.");let p;try{p=await O({token:s[1],jwks:o,issuer:r,audience:u})}catch{throw n("The bearer token is not a valid outbound token for this provider.")}const{claims:i,chain:z,scope:w}=p,{grantee:h,initiating_app:k,jti:m,act:l}=i,a=l;if(w===void 0||!y(h)||!y(k)||!d(m)||z.length===0||typeof a!="object"||a===null||Array.isArray(a)||!d(a.sub))throw n("The bearer token is not a valid outbound token for this provider.");const b=i.payer;if(b!==void 0&&!y(b))throw n("The bearer token is not a valid outbound token for this provider.");const I=b??j(h).namespace,v=C(i.accounts),g=F(i.tools);let c=l;for(;c.act!==void 0;)c=c.act;return Object.freeze({sub:p.sub,grantee:h,payer:I,clientId:i.client_id,scope:Object.freeze(w.split(" ").filter(T=>T.length>0)),initiatingApp:k,act:l,jti:m,actor:c.sub,...v!==void 0?{accounts:v}:{},...g!==void 0?{tools:g}:{}})}}t(R,"createCallerVerifier");function C(e){if(e===void 0)return;if(typeof e!="object"||e===null||Array.isArray(e))throw n("The bearer token is not a valid outbound token for this provider.");const r={};for(const[u,o]of Object.entries(e)){if(!Array.isArray(o)||!o.every(d))throw n("The bearer token is not a valid outbound token for this provider.");r[u]=Object.freeze([...o])}return Object.freeze(r)}t(C,"parseAccounts");function F(e){if(e!==void 0){if(!Array.isArray(e)||!e.every(d))throw n("The bearer token is not a valid outbound token for this provider.");return Object.freeze([...e])}}t(F,"parseTools");function S(e,r){return A({code:"scope_missing",status:403,message:`The token does not carry ${e}, which this command needs.`,field:e,received:e,...r!==void 0?{next:`Set auth.providerId to your app's client id (${r}).`}:{}})}t(S,"scopeMissing");function n(e){return A({code:"unauthorized",status:401,message:e,next:"Send a current outbound token for this provider as Authorization: Bearer <token>."})}t(n,"unauthorized");export{R as createCallerVerifier,$ as normalizeProviderId,S as scopeMissing};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.750",
3
+ "version": "0.3.751",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -27,8 +27,8 @@
27
27
  "postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
28
28
  },
29
29
  "dependencies": {
30
- "@north-light/api": "0.3.750",
31
- "@north-light/identity": "0.3.750"
30
+ "@north-light/api": "0.3.751",
31
+ "@north-light/identity": "0.3.751"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {