@north-light/plugin 0.3.556 → 0.3.558

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/index.d.ts CHANGED
@@ -8,6 +8,6 @@ export { parseCrtrCaller, type CrtrCaller } from './caller.js';
8
8
  export * from './serve.js';
9
9
  export { createNodeHandler, type NodeHandlerOptions, type NodeLikeRequest, type NodeLikeResponse } from './node.js';
10
10
  export { createCallerVerifier, type CallerVerifier, type FetchHandlerAuth } from './verify.js';
11
- export { postReceipt, ReceiptPostError, SpendRefusedError, type LedgerCredentials, type Receipt, type ReceiptOptions, type ReceiptOutbox, type SpendCheckAnswer, type SpendPrice } from './receipts.js';
11
+ export { postReceipt, ReceiptPostError, SpendRefusedError, type LedgerCredentials, type Receipt, type ReceiptOptions, type ReceiptRejection, type ReceiptOutbox, type SpendCheckAnswer, type SpendPrice } from './receipts.js';
12
12
  export { LeafError, type LeafErrorOptions, type LeafErrorQuestion } from './errors.js';
13
13
  export { customObjectPublishFailure } from './watchable.js';
@@ -53,10 +53,19 @@ export interface SpendCheckAnswer {
53
53
  /** Present when the tool's group has exactly one price row. */
54
54
  readonly price?: SpendPrice;
55
55
  }
56
+ /** The directory's structured refusal of a receipt: only these four string fields of its error body are kept. */
57
+ export interface ReceiptRejection {
58
+ readonly code?: string;
59
+ readonly message?: string;
60
+ readonly param?: string;
61
+ readonly request_id?: string;
62
+ }
56
63
  export declare class ReceiptPostError extends Error {
57
64
  readonly permanent: boolean;
58
65
  readonly status?: number | undefined;
59
- constructor(message: string, permanent: boolean, status?: number | undefined);
66
+ readonly rejection?: ReceiptRejection | undefined;
67
+ /** Set when the directory answered a non-OK receipt post with a structured error body. */
68
+ constructor(message: string, permanent: boolean, status?: number | undefined, rejection?: ReceiptRejection | undefined);
60
69
  }
61
70
  /**
62
71
  * Thrown by `ctx.checkSpend()` when the directory refuses a priced call (HTTP 402). `code` is the
package/dist/receipts.js CHANGED
@@ -1 +1 @@
1
- var A=Object.defineProperty;var i=(t,e)=>A(t,"name",{value:e,configurable:!0});class u extends Error{static{i(this,"ReceiptPostError")}permanent;status;constructor(e,r,s){super(e),this.permanent=r,this.status=s,this.name="ReceiptPostError"}}class b extends Error{static{i(this,"SpendRefusedError")}code;next;constructor(e,r,s){super(r),this.code=e,this.next=s,this.name="SpendRefusedError"}}async function $(t,e){const r=await g(e);let s;try{s=await fetch(e.url,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(t)})}catch(n){throw new u(`Could not post receipt: ${String(n)}`,!1)}if(!s.ok)throw new u(`Ledger receipt request failed: HTTP ${s.status}`,l(s.status),s.status)}i($,"postReceipt");async function g(t,e){const r=new URL("/token",t.url),s=await P(t,r.href);let n;try{n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials",client_id:t.clientId,client_assertion_type:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer",client_assertion:s}),...e===void 0?{}:{signal:e}})}catch(a){throw new u(`Could not obtain a ledger token: ${String(a)}`,!1)}if(!n.ok)throw new u(`Ledger token request failed: HTTP ${n.status}`,l(n.status),n.status);let c;try{c=(await n.json()).access_token}catch{throw new u("Ledger token response was not JSON",!1)}if(typeof c!="string"||c.length===0)throw new u("Ledger token response has no access_token",!1);return c}i(g,"ledgerToken");async function R(t,e,r,s){const n=AbortSignal.timeout(1e4),c=await g({...s,url:t},n);let a;try{a=await fetch(`${t.replace(/\/+$/,"")}/v1/billing/check`,{method:"POST",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json"},body:JSON.stringify({token:e,tool:r}),signal:n})}catch(o){throw new u(`Could not reach the billing check: ${String(o)}`,!1)}if(a.ok)return x(await a.json().catch(()=>{}));if(a.status===402){let o;try{o=(await a.json()).error}catch{}throw typeof o?.code=="string"&&typeof o.message=="string"?new b(o.code,o.message,typeof o.details?.next=="string"?o.details.next:""):new u("Billing check answered 402 without a code and message",!0,402)}throw new u(`Billing check request failed: HTTP ${a.status}`,l(a.status),a.status)}i(R,"requestSpendCheck");function x(t){const e=typeof t=="object"&&t!==null?t:{},r=typeof e.status=="string"?e.status:"ok",n=(Array.isArray(e.prices)?e.prices:[e.price]).flatMap(c=>T(c)??[]);return{status:r,prices:n,...n.length===1?{price:n[0]}:{}}}i(x,"parseSpendAnswer");function T(t){const e=t;if(!(typeof e!="object"||e===null||typeof e.max_usd_per_call!="number")){if(e.mode==="reported")return{mode:"reported",unit:null,usd_per_unit:null,max_usd_per_call:e.max_usd_per_call};if(e.mode==="unit"&&typeof e.unit=="string"&&typeof e.usd_per_unit=="number"&&Number.isFinite(e.usd_per_unit)&&e.usd_per_unit>=0)return{mode:"unit",unit:e.unit,usd_per_unit:e.usd_per_unit,max_usd_per_call:e.max_usd_per_call}}}i(T,"parseSpendPrice");async function P(t,e){const{privateKey:r}=t,s=typeof r=="string";let n=!s&&r.kty==="RSA"?"RS256":"ES256";if(!s&&r.kty!=="RSA"&&r.kty!=="EC")throw new u("Ledger private key must be an ES256 or RS256 PEM or JWK",!0);const c={name:"ECDSA",namedCurve:"P-256"},a={name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"};let o;try{if(s){const p=/^-----BEGIN PRIVATE KEY-----\s*([A-Za-z0-9+/=\s]+)-----END PRIVATE KEY-----\s*$/.exec(r);if(!p)throw new Error("Expected a PKCS#8 PEM private key");const y=Uint8Array.from(atob(p[1].replace(/\s/g,"")),E=>E.charCodeAt(0));try{o=await crypto.subtle.importKey("pkcs8",y,c,!1,["sign"])}catch{n="RS256",o=await crypto.subtle.importKey("pkcs8",y,a,!1,["sign"])}}else{if(r.alg!==void 0&&r.alg!==n)throw new Error(`JWK alg must be ${n}`);o=await crypto.subtle.importKey("jwk",r,n==="ES256"?c:a,!1,["sign"])}}catch(p){throw new u(`Invalid ledger private key: ${String(p)}`,!0)}const d=Math.floor(Date.now()/1e3),f=i(p=>m(new TextEncoder().encode(JSON.stringify(p))),"encode"),h=t.keyId??(s?void 0:r.kid),S=f({alg:n,typ:"JWT",...h?{kid:h}:{}}),_=f({iss:t.clientId,sub:t.clientId,aud:e,iat:d,exp:d+60,jti:crypto.randomUUID()}),w=`${S}.${_}`,k=await crypto.subtle.sign(n==="ES256"?{name:"ECDSA",hash:"SHA-256"}:"RSASSA-PKCS1-v1_5",o,new TextEncoder().encode(w));return`${w}.${m(new Uint8Array(k))}`}i(P,"clientAssertion");function m(t){let e="";for(const r of t)e+=String.fromCharCode(r);return btoa(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}i(m,"base64url");function l(t){return t>=400&&t<500&&t!==408&&t!==429}i(l,"isPermanent");export{u as ReceiptPostError,b as SpendRefusedError,$ as postReceipt,R as requestSpendCheck};
1
+ var b=Object.defineProperty;var c=(t,e)=>b(t,"name",{value:e,configurable:!0});class u extends Error{static{c(this,"ReceiptPostError")}permanent;status;rejection;constructor(e,r,o,n){super(e),this.permanent=r,this.status=o,this.rejection=n,this.name="ReceiptPostError"}}class A extends Error{static{c(this,"SpendRefusedError")}code;next;constructor(e,r,o){super(r),this.code=e,this.next=o,this.name="SpendRefusedError"}}async function O(t,e){const r=await _(e);let o;try{o=await fetch(e.url,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(t)})}catch(n){throw new u(`Could not post receipt: ${String(n)}`,!1)}if(!o.ok)throw new u(`Ledger receipt request failed: HTTP ${o.status}`,w(o.status),o.status,await P(o))}c(O,"postReceipt");const T=8192,x=2e3;async function P(t){const e=t.body?.getReader();if(e===void 0)return;let r;const o=new Promise((d,l)=>{r=setTimeout(()=>l(new Error("timed out")),x)});o.catch(()=>{});let n;try{const d=new TextDecoder;let l="",f=0;for(;;){const{done:y,value:h}=await Promise.race([e.read(),o]);if(y)break;if(f+=h.byteLength,f>T)return;l+=d.decode(h,{stream:!0})}n=JSON.parse(l+d.decode()).error}catch{return}finally{clearTimeout(r),e.cancel().catch(()=>{})}if(typeof n!="object"||n===null)return;const i=c(d=>typeof d=="string"?d.slice(0,500):void 0,"field"),a={code:i(n.code),message:i(n.message),param:i(n.param),request_id:i(n.request_id)},s=Object.fromEntries(Object.entries(a).filter(([,d])=>d!==void 0));return Object.keys(s).length===0?void 0:s}c(P,"readRejection");async function _(t,e){const r=new URL("/token",t.url),o=await j(t,r.href);let n;try{n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials",client_id:t.clientId,client_assertion_type:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer",client_assertion:o}),...e===void 0?{}:{signal:e}})}catch(a){throw new u(`Could not obtain a ledger token: ${String(a)}`,!1)}if(!n.ok)throw new u(`Ledger token request failed: HTTP ${n.status}`,w(n.status),n.status);let i;try{i=(await n.json()).access_token}catch{throw new u("Ledger token response was not JSON",!1)}if(typeof i!="string"||i.length===0)throw new u("Ledger token response has no access_token",!1);return i}c(_,"ledgerToken");async function I(t,e,r,o){const n=AbortSignal.timeout(1e4),i=await _({...o,url:t},n);let a;try{a=await fetch(`${t.replace(/\/+$/,"")}/v1/billing/check`,{method:"POST",headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"},body:JSON.stringify({token:e,tool:r}),signal:n})}catch(s){throw new u(`Could not reach the billing check: ${String(s)}`,!1)}if(a.ok)return R(await a.json().catch(()=>{}));if(a.status===402){let s;try{s=(await a.json()).error}catch{}throw typeof s?.code=="string"&&typeof s.message=="string"?new A(s.code,s.message,typeof s.details?.next=="string"?s.details.next:""):new u("Billing check answered 402 without a code and message",!0,402)}throw new u(`Billing check request failed: HTTP ${a.status}`,w(a.status),a.status)}c(I,"requestSpendCheck");function R(t){const e=typeof t=="object"&&t!==null?t:{},r=typeof e.status=="string"?e.status:"ok",n=(Array.isArray(e.prices)?e.prices:[e.price]).flatMap(i=>C(i)??[]);return{status:r,prices:n,...n.length===1?{price:n[0]}:{}}}c(R,"parseSpendAnswer");function C(t){const e=t;if(!(typeof e!="object"||e===null||typeof e.max_usd_per_call!="number")){if(e.mode==="reported")return{mode:"reported",unit:null,usd_per_unit:null,max_usd_per_call:e.max_usd_per_call};if(e.mode==="unit"&&typeof e.unit=="string"&&typeof e.usd_per_unit=="number"&&Number.isFinite(e.usd_per_unit)&&e.usd_per_unit>=0)return{mode:"unit",unit:e.unit,usd_per_unit:e.usd_per_unit,max_usd_per_call:e.max_usd_per_call}}}c(C,"parseSpendPrice");async function j(t,e){const{privateKey:r}=t,o=typeof r=="string";let n=!o&&r.kty==="RSA"?"RS256":"ES256";if(!o&&r.kty!=="RSA"&&r.kty!=="EC")throw new u("Ledger private key must be an ES256 or RS256 PEM or JWK",!0);const i={name:"ECDSA",namedCurve:"P-256"},a={name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"};let s;try{if(o){const p=/^-----BEGIN PRIVATE KEY-----\s*([A-Za-z0-9+/=\s]+)-----END PRIVATE KEY-----\s*$/.exec(r);if(!p)throw new Error("Expected a PKCS#8 PEM private key");const g=Uint8Array.from(atob(p[1].replace(/\s/g,"")),E=>E.charCodeAt(0));try{s=await crypto.subtle.importKey("pkcs8",g,i,!1,["sign"])}catch{n="RS256",s=await crypto.subtle.importKey("pkcs8",g,a,!1,["sign"])}}else{if(r.alg!==void 0&&r.alg!==n)throw new Error(`JWK alg must be ${n}`);s=await crypto.subtle.importKey("jwk",r,n==="ES256"?i:a,!1,["sign"])}}catch(p){throw new u(`Invalid ledger private key: ${String(p)}`,!0)}const d=Math.floor(Date.now()/1e3),l=c(p=>S(new TextEncoder().encode(JSON.stringify(p))),"encode"),f=t.keyId??(o?void 0:r.kid),y=l({alg:n,typ:"JWT",...f?{kid:f}:{}}),h=l({iss:t.clientId,sub:t.clientId,aud:e,iat:d,exp:d+60,jti:crypto.randomUUID()}),m=`${y}.${h}`,k=await crypto.subtle.sign(n==="ES256"?{name:"ECDSA",hash:"SHA-256"}:"RSASSA-PKCS1-v1_5",s,new TextEncoder().encode(m));return`${m}.${S(new Uint8Array(k))}`}c(j,"clientAssertion");function S(t){let e="";for(const r of t)e+=String.fromCharCode(r);return btoa(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}c(S,"base64url");function w(t){return t>=400&&t<500&&t!==408&&t!==429}c(w,"isPermanent");export{u as ReceiptPostError,A as SpendRefusedError,O as postReceipt,I as requestSpendCheck};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.556",
3
+ "version": "0.3.558",
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.556",
31
- "@north-light/identity": "0.3.556"
30
+ "@north-light/api": "0.3.558",
31
+ "@north-light/identity": "0.3.558"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {