@canton-network/wallet-gateway-remote 0.23.1 → 0.24.0
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/web/frontend/404/index.html +2 -2
- package/dist/web/frontend/approve/index.html +5 -5
- package/dist/web/frontend/assets/404-mTP2h7GO.js +8 -0
- package/dist/web/frontend/assets/{approve-sXtkk0nx.js → approve-B7ioWbgg.js} +2 -2
- package/dist/web/frontend/assets/{callback-5r0xYoAY.js → callback-Bbv8zOQx.js} +1 -1
- package/dist/web/frontend/assets/{index-C4_-rNJw.js → index-64ZRFXyL.js} +1 -1
- package/dist/web/frontend/assets/{index-BY0dSIJ0.js → index-CMV7Immb.js} +64 -64
- package/dist/web/frontend/assets/{login-DwOvzCWW.js → login-jo0xuh02.js} +2 -2
- package/dist/web/frontend/assets/{settings-lXZlQ6-V.js → settings-Bv6XHxUD.js} +1 -1
- package/dist/web/frontend/assets/{state-Zh2baU_h.js → state-BsGwKQMR.js} +1 -1
- package/dist/web/frontend/assets/{transactions-gLP4M5t0.js → transactions-Cvi9DMx7.js} +2 -2
- package/dist/web/frontend/assets/{utils-CI12TM_E.js → utils-Ou54c_Bf.js} +1 -1
- package/dist/web/frontend/assets/{wallets-Cmwexted.js → wallets-DFBcTQHX.js} +2 -2
- package/dist/web/frontend/callback/index.html +2 -2
- package/dist/web/frontend/index.html +1 -1
- package/dist/web/frontend/login/index.html +4 -4
- package/dist/web/frontend/settings/index.html +3 -3
- package/dist/web/frontend/transactions/index.html +4 -4
- package/dist/web/frontend/wallets/index.html +4 -4
- package/package.json +19 -19
- package/dist/web/frontend/assets/404-CwWne4gl.js +0 -8
|
@@ -4,8 +4,8 @@
|
|
|
4
4
|
<meta charset="UTF-8" />
|
|
5
5
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
6
6
|
<title>Wallet Gateway - Not found</title>
|
|
7
|
-
<script type="module" crossorigin src="../assets/404-
|
|
8
|
-
<link rel="modulepreload" crossorigin href="../assets/index-
|
|
7
|
+
<script type="module" crossorigin src="../assets/404-mTP2h7GO.js"></script>
|
|
8
|
+
<link rel="modulepreload" crossorigin href="../assets/index-CMV7Immb.js">
|
|
9
9
|
</head>
|
|
10
10
|
|
|
11
11
|
<body>
|
|
@@ -4,12 +4,12 @@
|
|
|
4
4
|
<meta charset="UTF-8" />
|
|
5
5
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
6
6
|
<title>Wallet Gateway - Approve Write Request</title>
|
|
7
|
-
<script type="module" crossorigin src="../assets/approve-
|
|
8
|
-
<link rel="modulepreload" crossorigin href="../assets/index-
|
|
9
|
-
<link rel="modulepreload" crossorigin href="../assets/state-
|
|
7
|
+
<script type="module" crossorigin src="../assets/approve-B7ioWbgg.js"></script>
|
|
8
|
+
<link rel="modulepreload" crossorigin href="../assets/index-CMV7Immb.js">
|
|
9
|
+
<link rel="modulepreload" crossorigin href="../assets/state-BsGwKQMR.js">
|
|
10
10
|
<link rel="modulepreload" crossorigin href="../assets/index-NP2zGQqX.js">
|
|
11
|
-
<link rel="modulepreload" crossorigin href="../assets/utils-
|
|
12
|
-
<link rel="modulepreload" crossorigin href="../assets/index-
|
|
11
|
+
<link rel="modulepreload" crossorigin href="../assets/utils-Ou54c_Bf.js">
|
|
12
|
+
<link rel="modulepreload" crossorigin href="../assets/index-64ZRFXyL.js">
|
|
13
13
|
</head>
|
|
14
14
|
|
|
15
15
|
<body>
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{w as h,i as z,S as g,b as E,t as I}from"./index-CMV7Immb.js";var j=Object.create,s=Object.defineProperty,k=Object.getOwnPropertyDescriptor,x=(r,e)=>(e=Symbol[r])?e:Symbol.for("Symbol."+r),y=r=>{throw TypeError(r)},D=(r,e,a)=>e in r?s(r,e,{enumerable:!0,configurable:!0,writable:!0,value:a}):r[e]=a,F=(r,e)=>s(r,"name",{value:e,configurable:!0}),A=r=>[,,,j(r?.[x("metadata")]??null)],C=["class","method","getter","setter","accessor","field","value","get","set"],S=r=>r!==void 0&&typeof r!="function"?y("Function expected"):r,M=(r,e,a,n,t)=>({kind:C[r],name:e,metadata:n,addInitializer:o=>a._?y("Already initialized"):t.push(S(o||null))}),N=(r,e)=>D(e,x("metadata"),r[3]),T=(r,e,a,n)=>{for(var t=0,o=r[e>>1],i=o&&o.length;t<i;t++)o[t].call(a);return n},$=(r,e,a,n,t,o)=>{var i,p,f,_=e&7,m=!1,b=0,P=r[b]||(r[b]=[]),l=_&&(t=t.prototype,_<5&&(_>3||!m)&&k(t,a));F(t,a);for(var c=n.length-1;c>=0;c--)f=M(_,a,p={},r[3],P),i=(0,n[c])(t,f),p._=1,S(i)&&(t=i);return N(r,t),l&&s(t,a,l),m?_^4?o:l:t},w,v,O;w=[I("user-ui-404")];const u=class u extends(O=h){render(){return E`<not-found href=${g("/")}></not-found>`}};u.styles=[h.styles,z`
|
|
2
|
+
:host {
|
|
3
|
+
display: block;
|
|
4
|
+
max-width: 900px;
|
|
5
|
+
margin: 20% auto;
|
|
6
|
+
padding: 20px;
|
|
7
|
+
}
|
|
8
|
+
`];let d=u;v=A(O);d=$(v,0,"NotFoundUi",w,d);T(v,1,d);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{o as A,s as g,d as Se,l as M,n as Me,a as te,
|
|
1
|
+
import{o as A,s as g,d as Se,l as M,n as Me,a as te,S as We,T as $e,c as W,e as $,Q as se,b as ae,w as Pe,t as De}from"./index-CMV7Immb.js";import{r as h}from"./state-BsGwKQMR.js";import{p as Ee}from"./index-NP2zGQqX.js";import{s as C}from"./utils-Ou54c_Bf.js";import{a as ie,i as Oe}from"./index-64ZRFXyL.js";var P=(e=>(e.CanActAs="CanActAs",e.CanReadAs="CanReadAs",e.CanExecuteAs="CanExecuteAs",e))(P||{}),He=A({baseUrl:g().url()}),Ue=A({id:g(),name:g(),description:g(),synchronizerId:g().includes("::").min(10).optional(),identityProviderId:g(),ledgerApi:He,auth:ie,adminAuth:ie.optional()});A({connection:Se("type",[A({type:M("memory")}),A({type:M("sqlite"),database:g()}),A({type:M("postgres"),host:g(),port:Me(),user:g(),password:g(),database:g()})])});A({idps:te(Oe),networks:te(Ue)});var qe=Object.create,E=Object.defineProperty,Re=Object.getOwnPropertyDescriptor,ce=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),y=e=>{throw TypeError(e)},ze=(e,t,a)=>t in e?E(e,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[t]=a,re=(e,t)=>E(e,"name",{value:t,configurable:!0}),Ge=e=>[,,,qe(e?.[ce("metadata")]??null)],de=["class","method","getter","setter","accessor","field","value","get","set"],I=e=>e!==void 0&&typeof e!="function"?y("Function expected"):e,Le=(e,t,a,c,n)=>({kind:de[e],name:t,metadata:c,addInitializer:d=>a._?y("Already initialized"):n.push(I(d||null))}),Ne=(e,t)=>ze(t,ce("metadata"),e[3]),i=(e,t,a,c)=>{for(var n=0,d=e[t>>1],w=d&&d.length;n<w;n++)t&1?d[n].call(a):c=d[n].call(a,c);return c},l=(e,t,a,c,n,d)=>{var w,_,Y,f,x,r=t&7,T=!!(t&8),v=!!(t&16),b=r>3?e.length+1:r?T?1:2:0,Z=de[r+5],ee=r>3&&(e[b-1]=[]),ke=e[b]||(e[b]=[]),m=r&&(!v&&!T&&(n=n.prototype),r<5&&(r>3||!v)&&Re(r<4?n:{get[a](){return ne(this,d)},set[a](u){return oe(this,d,u)}},a));r?v&&r<4&&re(d,(r>2?"set ":r>1?"get ":"")+a):re(n,a);for(var k=c.length-1;k>=0;k--)f=Le(r,a,Y={},e[3],ke),r&&(f.static=T,f.private=v,x=f.access={has:v?u=>Be(n,u):u=>a in u},r^3&&(x.get=v?u=>(r^1?ne:Fe)(u,n,r^4?d:m.get):u=>u[a]),r>2&&(x.set=v?(u,S)=>oe(u,n,S,r^4?d:m.set):(u,S)=>u[a]=S)),_=(0,c[k])(r?r<4?v?d:m[Z]:r>4?void 0:{get:m.get,set:m.set}:n,f),Y._=1,r^4||_===void 0?I(_)&&(r>4?ee.unshift(_):r?v?d=_:m[Z]=_:n=_):typeof _!="object"||_===null?y("Object expected"):(I(w=_.get)&&(m.get=w),I(w=_.set)&&(m.set=w),I(w=_.init)&&ee.unshift(w));return r||Ne(e,n),m&&E(n,a,m),v?r^4?d:m:n},O=(e,t,a)=>t.has(e)||y("Cannot "+a),Be=(e,t)=>Object(t)!==t?y('Cannot use the "in" operator on this value'):e.has(t),ne=(e,t,a)=>(O(e,t,"read from private field"),a?a.call(e):t.get(e)),p=(e,t,a)=>t.has(e)?y("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,a),oe=(e,t,a,c)=>(O(e,t,"write to private field"),c?c.call(e,a):t.set(e,a),a),Fe=(e,t,a)=>(O(e,t,"access private method"),a),le,he,pe,ue,_e,me,ge,we,ve,Ae,ye,fe,Ce,Ie,xe,Te,D,be,s,H,U,q,R,z,G,L,N,B,F,Q,j,J,K,V,X;be=[De("user-ui-approve")];class o extends(D=Pe,Te=[h()],xe=[h()],Ie=[h()],Ce=[h()],fe=[h()],ye=[h()],Ae=[h()],ve=[h()],we=[h()],ge=[h()],me=[h()],_e=[h()],ue=[h()],pe=[h()],he=[h()],le=[h()],D){constructor(){super(...arguments),p(this,H,i(s,8,this,!1)),i(s,11,this),p(this,U,i(s,12,this,!1)),i(s,15,this),p(this,q,i(s,16,this,!1)),i(s,19,this),p(this,R,i(s,20,this,"")),i(s,23,this),p(this,z,i(s,24,this,"")),i(s,27,this),p(this,G,i(s,28,this,"")),i(s,31,this),p(this,L,i(s,32,this,"")),i(s,35,this),p(this,N,i(s,36,this,null)),i(s,39,this),p(this,B,i(s,40,this,"")),i(s,43,this),p(this,F,i(s,44,this,null)),i(s,47,this),p(this,Q,i(s,48,this,null)),i(s,51,this),p(this,j,i(s,52,this,null)),i(s,55,this),p(this,J,i(s,56,this,null)),i(s,59,this),p(this,K,i(s,60,this,null)),i(s,63,this),p(this,V,i(s,64,this,!0)),i(s,67,this),p(this,X,i(s,68,this,null)),i(s,71,this)}connectedCallback(){super.connectedCallback();const t=new URL(window.location.href);this.commandId=t.searchParams.get("commandId")||"",this.updateState()}closeOrGoToList(){this.disabled=!0;const a=new URLSearchParams(window.location.search).has("closeafteraction");setTimeout(()=>{a&&window.opener?window.close():window.location.href=We($e)},2e3)}async updateState(){const t=await W($.accessToken.get());t.request({method:"getTransaction",params:{commandId:this.commandId}}).then(a=>{this.txHash=a.preparedTransactionHash,this.tx=a.preparedTransaction,this.status=a.status,this.createdAt=a.createdAt||null,this.signedAt=a.signedAt||null,this.origin=a.origin||null;try{this.txParsed=Ee(this.tx)}catch(c){console.error("Error parsing prepared transaction:",c),this.txParsed=null}}),t.request({method:"listWallets",params:{}}).then(a=>{const c=a.find(w=>w.primary===!0);this.partyId=c?.partyId||"";const n=c?.rights,d=!!(n?.includes(P.CanActAs)||n?.includes(P.CanExecuteAs));this.canSubmit=d,this.walletCapabilityMessage=d?null:"The selected wallet is read-only for submission (no CanActAs/CanExecuteAs right)."})}get _detailComponent(){return this.renderRoot.querySelector("wg-transaction-detail")}async handleDelete(){if(confirm(`Delete pending transaction "${this.commandId}"?`)){this.isDeleting=!0;try{await(await W($.accessToken.get())).request({method:"deleteTransaction",params:{commandId:this.commandId}}),C("","Transaction deleted successfully","success"),this.closeOrGoToList()}catch(t){se(t)}finally{this.isDeleting=!1}}}async handleApprove(){if(!this.canSubmit){C("Read-only wallet","This wallet can read but cannot submit transactions. Switch to a wallet with CanActAs or CanExecuteAs.","error");return}this.isApproving=!0;try{const t=await W($.accessToken.get()),a=await t.request({method:"sign",params:{commandId:this.commandId,partyId:this.partyId,preparedTransactionHash:this.txHash,preparedTransaction:this.tx}});if(a.status==="pending"){C("Transaction Pending","Complete the signing in your external provider, then click Approve to finish.","info"),await this.updateState();return}else if(a.status==="signed")await t.request({method:"execute",params:{signature:a.signature,signedBy:a.signedBy,commandId:this.commandId,partyId:this.partyId}}),C("","Transaction executed successfully","success"),this.closeOrGoToList();else{const c=a.status==="rejected"?"Transaction was rejected":"Transaction failed";C("",c,"error"),await this.updateState()}}catch(t){console.error(t),se(t,{message:"Error executing transaction"})}finally{this.isApproving=!1}}render(){return ae`
|
|
2
2
|
${this.walletCapabilityMessage?ae`<div class="alert alert-warning" role="alert">
|
|
3
3
|
${this.walletCapabilityMessage}
|
|
4
4
|
</div>`:""}
|
|
@@ -17,4 +17,4 @@ import{o as A,s as g,d as Se,l as M,n as Me,a as te,A as We,T as $e,c as W,e as
|
|
|
17
17
|
@transaction-approve=${this.handleApprove}
|
|
18
18
|
@transaction-delete=${this.handleDelete}
|
|
19
19
|
></wg-transaction-detail>
|
|
20
|
-
`}}s=Ge(D);H=new WeakMap;U=new WeakMap;q=new WeakMap;R=new WeakMap;z=new WeakMap;G=new WeakMap;L=new WeakMap;N=new WeakMap;B=new WeakMap;F=new WeakMap;
|
|
20
|
+
`}}s=Ge(D);H=new WeakMap;U=new WeakMap;q=new WeakMap;R=new WeakMap;z=new WeakMap;G=new WeakMap;L=new WeakMap;N=new WeakMap;B=new WeakMap;F=new WeakMap;Q=new WeakMap;j=new WeakMap;J=new WeakMap;K=new WeakMap;V=new WeakMap;X=new WeakMap;l(s,4,"isApproving",Te,o,H);l(s,4,"isDeleting",xe,o,U);l(s,4,"disabled",Ie,o,q);l(s,4,"commandId",Ce,o,R);l(s,4,"partyId",fe,o,z);l(s,4,"txHash",ye,o,G);l(s,4,"tx",Ae,o,L);l(s,4,"txParsed",ve,o,N);l(s,4,"status",we,o,B);l(s,4,"message",ge,o,F);l(s,4,"messageType",me,o,Q);l(s,4,"createdAt",_e,o,j);l(s,4,"signedAt",ue,o,J);l(s,4,"origin",pe,o,K);l(s,4,"canSubmit",he,o,V);l(s,4,"walletCapabilityMessage",le,o,X);o=l(s,0,"ApproveUi",be,o);i(s,1,o);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{f as O,
|
|
1
|
+
import{f as O,S as y,e as g,g as C,r as P,b as x,t as L}from"./index-CMV7Immb.js";var R=Object.create,v=Object.defineProperty,U=Object.getOwnPropertyDescriptor,w=(e,r)=>(r=Symbol[e])?r:Symbol.for("Symbol."+e),b=e=>{throw TypeError(e)},z=(e,r,a)=>r in e?v(e,r,{enumerable:!0,configurable:!0,writable:!0,value:a}):e[r]=a,D=(e,r)=>v(e,"name",{value:r,configurable:!0}),E=e=>[,,,R(e?.[w("metadata")]??null)],T=["class","method","getter","setter","accessor","field","value","get","set"],m=e=>e!==void 0&&typeof e!="function"?b("Function expected"):e,j=(e,r,a,o,t)=>({kind:T[e],name:r,metadata:o,addInitializer:n=>a._?b("Already initialized"):t.push(m(n||null))}),N=(e,r)=>z(r,w("metadata"),e[3]),A=(e,r,a,o)=>{for(var t=0,n=e[r>>1],s=n&&n.length;t<s;t++)n[t].call(a);return o},F=(e,r,a,o,t,n)=>{var s,l,d,c=r&7,_=!1,i=0,p=e[i]||(e[i]=[]),f=c&&(t=t.prototype,c<5&&(c>3||!_)&&U(t,a));D(t,a);for(var u=o.length-1;u>=0;u--)d=j(c,a,l={},e[3],p),s=(0,o[u])(t,d),l._=1,m(s)&&(t=s);return N(e,t),f&&v(t,a,f),_?c^4?n:f:t},S,k,I;S=[L("login-callback")];class h extends(I=O){connectedCallback(){super.connectedCallback(),this.handleRedirect()}async handleRedirect(){const r=new URL(window.location.href),a=r.searchParams.get("code"),o=r.searchParams.get("state");if(!a&&!o){console.error("missing state and code");return}if(a&&o){const t=JSON.parse(atob(o)),n=sessionStorage.getItem(`oauth-pkce-${t.stateId}`);if(!n){console.error("missing PKCE verifier for OAuth callback state");return}sessionStorage.removeItem(`oauth-pkce-${t.stateId}`);const d=(await(await fetch(t.configUrl)).json()).token_endpoint,c=new URL(y("/callback"),window.location.origin).toString(),i=await(await fetch(d,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:a,redirect_uri:c,client_id:t.clientId,audience:t.audience,code_verifier:n})})).json();if(i.access_token){const p=JSON.parse(atob(i.access_token.split(".")[1]));g.expirationDate.set(new Date(p.exp*1e3).toISOString()),g.accessToken.set(i.access_token),C(i.access_token,g.networkId.get()||"").then(()=>{P()})}}}render(){return x`<h2>Logged in!</h2>`}}k=E(I);h=F(k,0,"LoginCallback",S,h);A(k,1,h);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{o as p,s as o,l as m,d as D}from"./index-BY0dSIJ0.js";const x=crypto,F=t=>t instanceof CryptoKey,g=new TextEncoder,W=new TextDecoder;function ee(...t){const e=t.reduce((s,{length:i})=>s+i,0),r=new Uint8Array(e);let n=0;for(const s of t)r.set(s,n),n+=s.length;return r}const te=t=>{let e=t;typeof e=="string"&&(e=g.encode(e));const r=32768,n=[];for(let s=0;s<e.length;s+=r)n.push(String.fromCharCode.apply(null,e.subarray(s,s+r)));return btoa(n.join(""))},J=t=>te(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),re=t=>{const e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r},K=t=>{let e=t;e instanceof Uint8Array&&(e=W.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return re(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class c extends Error{constructor(e,r){super(e,r),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}c.code="ERR_JOSE_GENERIC";class ne extends c{constructor(e,r,n="unspecified",s="unspecified"){super(e,{cause:{claim:n,reason:s,payload:r}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=n,this.reason=s,this.payload=r}}ne.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class se extends c{constructor(e,r,n="unspecified",s="unspecified"){super(e,{cause:{claim:n,reason:s,payload:r}}),this.code="ERR_JWT_EXPIRED",this.claim=n,this.reason=s,this.payload=r}}se.code="ERR_JWT_EXPIRED";class oe extends c{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}oe.code="ERR_JOSE_ALG_NOT_ALLOWED";class f extends c{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}f.code="ERR_JOSE_NOT_SUPPORTED";class ie extends c{constructor(e="decryption operation failed",r){super(e,r),this.code="ERR_JWE_DECRYPTION_FAILED"}}ie.code="ERR_JWE_DECRYPTION_FAILED";class ae extends c{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}ae.code="ERR_JWE_INVALID";class w extends c{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}w.code="ERR_JWS_INVALID";class h extends c{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}h.code="ERR_JWT_INVALID";class ce extends c{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}ce.code="ERR_JWK_INVALID";class de extends c{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}de.code="ERR_JWKS_INVALID";class he extends c{constructor(e="no applicable key found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_NO_MATCHING_KEY"}}he.code="ERR_JWKS_NO_MATCHING_KEY";class le extends c{constructor(e="multiple matching keys found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}le.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class ue extends c{constructor(e="request timed out",r){super(e,r),this.code="ERR_JWKS_TIMEOUT"}}ue.code="ERR_JWKS_TIMEOUT";class fe extends c{constructor(e="signature verification failed",r){super(e,r),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}fe.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function d(t,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`)}function _(t,e){return t.name===e}function P(t){return parseInt(t.name.slice(4),10)}function pe(t){switch(t){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function me(t,e){if(e.length&&!e.some(r=>t.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(e.length>2){const n=e.pop();r+=`one of ${e.join(", ")}, or ${n}.`}else e.length===2?r+=`one of ${e[0]} or ${e[1]}.`:r+=`${e[0]}.`;throw new TypeError(r)}}function ye(t,e,...r){switch(e){case"HS256":case"HS384":case"HS512":{if(!_(t.algorithm,"HMAC"))throw d("HMAC");const n=parseInt(e.slice(2),10);if(P(t.algorithm.hash)!==n)throw d(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!_(t.algorithm,"RSASSA-PKCS1-v1_5"))throw d("RSASSA-PKCS1-v1_5");const n=parseInt(e.slice(2),10);if(P(t.algorithm.hash)!==n)throw d(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!_(t.algorithm,"RSA-PSS"))throw d("RSA-PSS");const n=parseInt(e.slice(2),10);if(P(t.algorithm.hash)!==n)throw d(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(t.algorithm.name!=="Ed25519"&&t.algorithm.name!=="Ed448")throw d("Ed25519 or Ed448");break}case"Ed25519":{if(!_(t.algorithm,"Ed25519"))throw d("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!_(t.algorithm,"ECDSA"))throw d("ECDSA");const n=pe(e);if(t.algorithm.namedCurve!==n)throw d(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}me(t,r)}function k(t,e,...r){if(r=r.filter(Boolean),r.length>2){const n=r.pop();t+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?t+=`one of type ${r[0]} or ${r[1]}.`:t+=`of type ${r[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(t+=` Received an instance of ${e.constructor.name}`),t}const M=(t,...e)=>k("Key must be ",t,...e);function j(t,e,...r){return k(`Key for the ${t} algorithm must be `,e,...r)}const V=t=>F(t)?!0:t?.[Symbol.toStringTag]==="KeyObject",v=["CryptoKey"],Se=(...t)=>{const e=t.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(const n of e){const s=Object.keys(n);if(!r||r.size===0){r=new Set(s);continue}for(const i of s){if(r.has(i))return!1;r.add(i)}}return!0};function we(t){return typeof t=="object"&&t!==null}function N(t){if(!we(t)||Object.prototype.toString.call(t)!=="[object Object]")return!1;if(Object.getPrototypeOf(t)===null)return!0;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}const Ee=(t,e)=>{if(t.startsWith("RS")||t.startsWith("PS")){const{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}};function b(t){return N(t)&&typeof t.kty=="string"}function ge(t){return t.kty!=="oct"&&typeof t.d=="string"}function _e(t){return t.kty!=="oct"&&typeof t.d>"u"}function be(t){return b(t)&&t.kty==="oct"&&typeof t.k=="string"}function Te(t){let e,r;switch(t.kty){case"RSA":{switch(t.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(t.alg.slice(-3),10)||1}`},r=t.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new f('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(t.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},r=t.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},r=t.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new f('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(t.alg){case"Ed25519":e={name:"Ed25519"},r=t.d?["sign"]:["verify"];break;case"EdDSA":e={name:t.crv},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new f('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new f('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}const Ae=async t=>{if(!t.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:r}=Te(t),n=[e,t.ext??!1,t.key_ops??r],s={...t};return delete s.alg,delete s.use,x.subtle.importKey("jwk",s,...n)},G=t=>K(t);let y,S;const z=t=>t?.[Symbol.toStringTag]==="KeyObject",C=async(t,e,r,n,s=!1)=>{let i=t.get(e);if(i?.[n])return i[n];const a=await Ae({...r,alg:n});return s&&Object.freeze(e),i?i[n]=a:t.set(e,{[n]:a}),a},Ie=(t,e)=>{if(z(t)){let r=t.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?G(r.k):(S||(S=new WeakMap),C(S,t,r,e))}return b(t)?t.k?K(t.k):(S||(S=new WeakMap),C(S,t,t,e,!0)):t},Re=(t,e)=>{if(z(t)){let r=t.export({format:"jwk"});return r.k?G(r.k):(y||(y=new WeakMap),C(y,t,r,e))}return b(t)?t.k?K(t.k):(y||(y=new WeakMap),C(y,t,t,e,!0)):t},We={normalizePublicKey:Ie,normalizePrivateKey:Re},E=t=>t?.[Symbol.toStringTag],H=(t,e,r)=>{if(e.use!==void 0&&e.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(e.key_ops!==void 0&&e.key_ops.includes?.(r)!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(e.alg!==void 0&&e.alg!==t)throw new TypeError(`Invalid key for this operation, when present its alg must be ${t}`);return!0},ve=(t,e,r,n)=>{if(!(e instanceof Uint8Array)){if(n&&b(e)){if(be(e)&&H(t,e,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!V(e))throw new TypeError(j(t,e,...v,"Uint8Array",n?"JSON Web Key":null));if(e.type!=="secret")throw new TypeError(`${E(e)} instances for symmetric algorithms must be of type "secret"`)}},Ce=(t,e,r,n)=>{if(n&&b(e))switch(r){case"sign":if(ge(e)&&H(t,e,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(_e(e)&&H(t,e,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!V(e))throw new TypeError(j(t,e,...v,n?"JSON Web Key":null));if(e.type==="secret")throw new TypeError(`${E(e)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&e.type==="public")throw new TypeError(`${E(e)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&e.type==="public")throw new TypeError(`${E(e)} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&r==="verify"&&e.type==="private")throw new TypeError(`${E(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&r==="encrypt"&&e.type==="private")throw new TypeError(`${E(e)} instances for asymmetric algorithm encryption must be of type "public"`)};function B(t,e,r,n){e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?ve(e,r,n,t):Ce(e,r,n,t)}B.bind(void 0,!1);const Ke=B.bind(void 0,!0);function Je(t,e,r,n,s){if(s.crit!==void 0&&n?.crit===void 0)throw new t('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(a=>typeof a!="string"||a.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...e.entries()]):i=e;for(const a of n.crit){if(!i.has(a))throw new f(`Extension Header Parameter "${a}" is not recognized`);if(s[a]===void 0)throw new t(`Extension Header Parameter "${a}" is missing`);if(i.get(a)&&n[a]===void 0)throw new t(`Extension Header Parameter "${a}" MUST be integrity protected`)}return new Set(n.crit)}function Pe(t,e){const r=`SHA-${t.slice(-3)}`;switch(t){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:t.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:e.name};default:throw new f(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}async function Oe(t,e,r){if(e=await We.normalizePrivateKey(e,t),F(e))return ye(e,t,r),e;if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(M(e,...v));return x.subtle.importKey("raw",e,{hash:`SHA-${t.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(M(e,...v,"Uint8Array","JSON Web Key"))}const l=t=>Math.floor(t.getTime()/1e3),q=60,Y=q*60,$=Y*24,He=$*7,De=$*365.25,xe=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,O=t=>{const e=xe.exec(t);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");const r=parseFloat(e[2]),n=e[3].toLowerCase();let s;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":s=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":s=Math.round(r*q);break;case"hour":case"hours":case"hr":case"hrs":case"h":s=Math.round(r*Y);break;case"day":case"days":case"d":s=Math.round(r*$);break;case"week":case"weeks":case"w":s=Math.round(r*He);break;default:s=Math.round(r*De);break}return e[1]==="-"||e[4]==="ago"?-s:s},Ne=async(t,e,r)=>{const n=await Oe(t,e,"sign");Ee(t,n);const s=await x.subtle.sign(Pe(t,n.algorithm),n,r);return new Uint8Array(s)};class $e{constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new w("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Se(this._protectedHeader,this._unprotectedHeader))throw new w("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...this._protectedHeader,...this._unprotectedHeader},s=Je(w,new Map([["b64",!0]]),r?.crit,this._protectedHeader,n);let i=!0;if(s.has("b64")&&(i=this._protectedHeader.b64,typeof i!="boolean"))throw new w('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=n;if(typeof a!="string"||!a)throw new w('JWS "alg" (Algorithm) Header Parameter missing or invalid');Ke(a,e,"sign");let T=this._payload;i&&(T=g.encode(J(T)));let A;this._protectedHeader?A=g.encode(J(JSON.stringify(this._protectedHeader))):A=g.encode("");const Z=ee(A,g.encode("."),T),Q=await Ne(a,e,Z),I={signature:J(Q),payload:""};return i&&(I.payload=W.decode(T)),this._unprotectedHeader&&(I.header=this._unprotectedHeader),this._protectedHeader&&(I.protected=W.decode(A)),I}}class Ue{constructor(e){this._flattened=new $e(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,r){const n=await this._flattened.sign(e,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}}function u(t,e){if(!Number.isFinite(e))throw new TypeError(`Invalid ${t} input`);return e}class Me{constructor(e={}){if(!N(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return typeof e=="number"?this._payload={...this._payload,nbf:u("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:u("setNotBefore",l(e))}:this._payload={...this._payload,nbf:l(new Date)+O(e)},this}setExpirationTime(e){return typeof e=="number"?this._payload={...this._payload,exp:u("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:u("setExpirationTime",l(e))}:this._payload={...this._payload,exp:l(new Date)+O(e)},this}setIssuedAt(e){return typeof e>"u"?this._payload={...this._payload,iat:l(new Date)}:e instanceof Date?this._payload={...this._payload,iat:u("setIssuedAt",l(e))}:typeof e=="string"?this._payload={...this._payload,iat:u("setIssuedAt",l(new Date)+O(e))}:this._payload={...this._payload,iat:u("setIssuedAt",e)},this}}class Le extends Me{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,r){const n=new Ue(g.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new h("JWTs MUST NOT use unencoded payload");return n.sign(e,r)}}const Fe=K;function U(t){if(typeof t!="string")throw new h("JWTs must use Compact JWS serialization, JWT must be a string");const{1:e,length:r}=t.split(".");if(r===5)throw new h("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new h("Invalid JWT");if(!e)throw new h("JWTs must contain a payload");let n;try{n=Fe(e)}catch{throw new h("Failed to base64url decode the payload")}let s;try{s=JSON.parse(W.decode(n))}catch{throw new h("Failed to parse the decoded payload as JSON")}if(!N(s))throw new h("Invalid JWT Claims Set");return s}var ke=Object.defineProperty,je=(t,e,r)=>e in t?ke(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ve=(t,e,r)=>je(t,e+"",r);function Ge(t){const{sub:e}=U(t);if(!e)throw new Error("token did not contain a subject field");return e}function ze(t){const{email:e}=U(t);if(!(typeof e!="string"||e.length===0))return e}function L(t){try{const e=U(t),r=Math.floor(Date.now()/1e3);return typeof e.exp=="number"&&e.exp<=r}catch{return!0}}var Be=class{constructor(t,e){this.configUrl=t,this.logger=e}async fetchToken(t){try{const e=await this.getOIDCConfig(this.configUrl);this.logger?.debug({oidcConfig:e},"Fetched OIDC config");const n=await(await this.fetchTokenEndpoint(e.token_endpoint,t)).json();if(this.logger?.info({response:n},`Fetched admin token for clientId: ${t.clientId}`),!n.access_token)throw new Error("No access_token in token endpoint response");return n.access_token}catch(e){throw this.logger?.error({err:e},"Failed to fetch admin token"),e}}async fetchTokenEndpoint(t,e){const r=new URLSearchParams({grant_type:"client_credentials",client_id:e.clientId,client_secret:e.clientSecret,scope:e.scope??"",audience:e.audience??""}),n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()});if(!n.ok)throw this.logger?.error({status:n.status,statusText:n.statusText},"Token endpoint error"),new Error(`Token endpoint error: ${n.status} ${n.statusText}`);return n}async getOIDCConfig(t){const e=await fetch(t);if(!e.ok){const r=await e.text();throw this.logger?.error({status:e.status,statusText:e.statusText,body:r},"Failed to fetch OIDC config"),new Error(`OIDC config error: ${e.status} ${e.statusText}`)}return e.json()}},qe=(t,e)=>({fetchToken:async r=>new Be(t,e).fetchToken(r)}),Ye=class{static async fetchToken(t,e,r,n=3600){const s=new TextEncoder().encode(e.clientSecret),i=Math.floor(Date.now()/1e3),a=await new Le({sub:e.clientId,aud:e.audience||"",scope:e.scope||"",iat:i,exp:i+n,iss:r}).setProtectedHeader({alg:"HS256"}).sign(s);return t.info(`Generated self-signed JWT token: ${a}`),a}},rt=class R{constructor(e,r){this.config=e,this.logger=r,Ve(this,"cachedToken")}static fromToken(e,r){return new R({method:"static",token:e},r)}static fromGatewayConfig(e,r,n){if(r.method==="self_signed")return new R({method:r.method,issuer:r.issuer,credentials:{clientId:r.clientId,clientSecret:r.clientSecret,scope:r.scope,audience:r.audience}},n);if(r.method==="client_credentials"){if(e.type==="oauth")return new R({method:r.method,configUrl:e.configUrl,credentials:{clientId:r.clientId,clientSecret:r.clientSecret,scope:r.scope,audience:r.audience}},n);throw new Error(`IDP type ${e.type} not supported for client_credentials auth`)}throw new Error(`Auth method ${r.method} not supported for programmatic access token`)}async _fetchToken(){switch(this.logger.debug("Fetching user auth token"),this.config.method){case"static":return this.config.token;case"self_signed":return Ye.fetchToken(this.logger,this.config.credentials,this.config.issuer);case"client_credentials":return qe(this.config.configUrl,this.logger).fetchToken(this.config.credentials)}}async getAccessToken(){if(this.cachedToken&&!L(this.cachedToken))return this.cachedToken;{const e=await this._fetchToken();if(L(e))throw new Error("Attempted to refresh a token, but it came back expired.");return this.cachedToken=e,e}}async getAuthContext(){const e=await this.getAccessToken(),r=Ge(e),n=ze(e);return{accessToken:e,userId:r,...n?{email:n}:{}}}},X=p({method:m("authorization_code"),audience:o(),scope:o(),clientId:o()}).meta({description:"Authorization code flow authentication configuration. This is used for browser-based application login."}),Xe=p({method:m("client_credentials"),audience:o(),scope:o(),clientId:o(),clientSecret:o()}),Ze=p({method:m("self_signed"),issuer:o(),audience:o(),scope:o(),clientId:o(),clientSecret:o()}),Qe=p({method:m("client_credentials"),audience:o(),scope:o(),clientId:o(),clientSecretEnv:o()}),et=p({method:m("self_signed"),issuer:o(),audience:o(),scope:o(),clientId:o(),clientSecretEnv:o()}),nt=D("method",[X,Xe,Ze]);D("method",[X,Qe,et]);var st=D("type",[p({id:o(),type:m("self_signed"),issuer:o()}),p({id:o(),type:m("oauth"),issuer:o(),configUrl:o().url()})]);export{rt as A,nt as a,st as i};
|
|
1
|
+
import{o as p,s as o,l as m,d as D}from"./index-CMV7Immb.js";const x=crypto,F=t=>t instanceof CryptoKey,g=new TextEncoder,W=new TextDecoder;function ee(...t){const e=t.reduce((s,{length:i})=>s+i,0),r=new Uint8Array(e);let n=0;for(const s of t)r.set(s,n),n+=s.length;return r}const te=t=>{let e=t;typeof e=="string"&&(e=g.encode(e));const r=32768,n=[];for(let s=0;s<e.length;s+=r)n.push(String.fromCharCode.apply(null,e.subarray(s,s+r)));return btoa(n.join(""))},J=t=>te(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),re=t=>{const e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r},K=t=>{let e=t;e instanceof Uint8Array&&(e=W.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return re(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class c extends Error{constructor(e,r){super(e,r),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}c.code="ERR_JOSE_GENERIC";class ne extends c{constructor(e,r,n="unspecified",s="unspecified"){super(e,{cause:{claim:n,reason:s,payload:r}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=n,this.reason=s,this.payload=r}}ne.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class se extends c{constructor(e,r,n="unspecified",s="unspecified"){super(e,{cause:{claim:n,reason:s,payload:r}}),this.code="ERR_JWT_EXPIRED",this.claim=n,this.reason=s,this.payload=r}}se.code="ERR_JWT_EXPIRED";class oe extends c{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}oe.code="ERR_JOSE_ALG_NOT_ALLOWED";class f extends c{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}f.code="ERR_JOSE_NOT_SUPPORTED";class ie extends c{constructor(e="decryption operation failed",r){super(e,r),this.code="ERR_JWE_DECRYPTION_FAILED"}}ie.code="ERR_JWE_DECRYPTION_FAILED";class ae extends c{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}ae.code="ERR_JWE_INVALID";class w extends c{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}w.code="ERR_JWS_INVALID";class h extends c{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}h.code="ERR_JWT_INVALID";class ce extends c{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}ce.code="ERR_JWK_INVALID";class de extends c{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}de.code="ERR_JWKS_INVALID";class he extends c{constructor(e="no applicable key found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_NO_MATCHING_KEY"}}he.code="ERR_JWKS_NO_MATCHING_KEY";class le extends c{constructor(e="multiple matching keys found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}le.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class ue extends c{constructor(e="request timed out",r){super(e,r),this.code="ERR_JWKS_TIMEOUT"}}ue.code="ERR_JWKS_TIMEOUT";class fe extends c{constructor(e="signature verification failed",r){super(e,r),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}fe.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function d(t,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`)}function _(t,e){return t.name===e}function P(t){return parseInt(t.name.slice(4),10)}function pe(t){switch(t){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function me(t,e){if(e.length&&!e.some(r=>t.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(e.length>2){const n=e.pop();r+=`one of ${e.join(", ")}, or ${n}.`}else e.length===2?r+=`one of ${e[0]} or ${e[1]}.`:r+=`${e[0]}.`;throw new TypeError(r)}}function ye(t,e,...r){switch(e){case"HS256":case"HS384":case"HS512":{if(!_(t.algorithm,"HMAC"))throw d("HMAC");const n=parseInt(e.slice(2),10);if(P(t.algorithm.hash)!==n)throw d(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!_(t.algorithm,"RSASSA-PKCS1-v1_5"))throw d("RSASSA-PKCS1-v1_5");const n=parseInt(e.slice(2),10);if(P(t.algorithm.hash)!==n)throw d(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!_(t.algorithm,"RSA-PSS"))throw d("RSA-PSS");const n=parseInt(e.slice(2),10);if(P(t.algorithm.hash)!==n)throw d(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(t.algorithm.name!=="Ed25519"&&t.algorithm.name!=="Ed448")throw d("Ed25519 or Ed448");break}case"Ed25519":{if(!_(t.algorithm,"Ed25519"))throw d("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!_(t.algorithm,"ECDSA"))throw d("ECDSA");const n=pe(e);if(t.algorithm.namedCurve!==n)throw d(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}me(t,r)}function k(t,e,...r){if(r=r.filter(Boolean),r.length>2){const n=r.pop();t+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?t+=`one of type ${r[0]} or ${r[1]}.`:t+=`of type ${r[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(t+=` Received an instance of ${e.constructor.name}`),t}const M=(t,...e)=>k("Key must be ",t,...e);function j(t,e,...r){return k(`Key for the ${t} algorithm must be `,e,...r)}const V=t=>F(t)?!0:t?.[Symbol.toStringTag]==="KeyObject",v=["CryptoKey"],Se=(...t)=>{const e=t.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(const n of e){const s=Object.keys(n);if(!r||r.size===0){r=new Set(s);continue}for(const i of s){if(r.has(i))return!1;r.add(i)}}return!0};function we(t){return typeof t=="object"&&t!==null}function N(t){if(!we(t)||Object.prototype.toString.call(t)!=="[object Object]")return!1;if(Object.getPrototypeOf(t)===null)return!0;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}const Ee=(t,e)=>{if(t.startsWith("RS")||t.startsWith("PS")){const{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}};function b(t){return N(t)&&typeof t.kty=="string"}function ge(t){return t.kty!=="oct"&&typeof t.d=="string"}function _e(t){return t.kty!=="oct"&&typeof t.d>"u"}function be(t){return b(t)&&t.kty==="oct"&&typeof t.k=="string"}function Te(t){let e,r;switch(t.kty){case"RSA":{switch(t.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(t.alg.slice(-3),10)||1}`},r=t.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new f('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(t.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},r=t.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},r=t.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new f('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(t.alg){case"Ed25519":e={name:"Ed25519"},r=t.d?["sign"]:["verify"];break;case"EdDSA":e={name:t.crv},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new f('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new f('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}const Ae=async t=>{if(!t.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:r}=Te(t),n=[e,t.ext??!1,t.key_ops??r],s={...t};return delete s.alg,delete s.use,x.subtle.importKey("jwk",s,...n)},G=t=>K(t);let y,S;const z=t=>t?.[Symbol.toStringTag]==="KeyObject",C=async(t,e,r,n,s=!1)=>{let i=t.get(e);if(i?.[n])return i[n];const a=await Ae({...r,alg:n});return s&&Object.freeze(e),i?i[n]=a:t.set(e,{[n]:a}),a},Ie=(t,e)=>{if(z(t)){let r=t.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?G(r.k):(S||(S=new WeakMap),C(S,t,r,e))}return b(t)?t.k?K(t.k):(S||(S=new WeakMap),C(S,t,t,e,!0)):t},Re=(t,e)=>{if(z(t)){let r=t.export({format:"jwk"});return r.k?G(r.k):(y||(y=new WeakMap),C(y,t,r,e))}return b(t)?t.k?K(t.k):(y||(y=new WeakMap),C(y,t,t,e,!0)):t},We={normalizePublicKey:Ie,normalizePrivateKey:Re},E=t=>t?.[Symbol.toStringTag],H=(t,e,r)=>{if(e.use!==void 0&&e.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(e.key_ops!==void 0&&e.key_ops.includes?.(r)!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(e.alg!==void 0&&e.alg!==t)throw new TypeError(`Invalid key for this operation, when present its alg must be ${t}`);return!0},ve=(t,e,r,n)=>{if(!(e instanceof Uint8Array)){if(n&&b(e)){if(be(e)&&H(t,e,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!V(e))throw new TypeError(j(t,e,...v,"Uint8Array",n?"JSON Web Key":null));if(e.type!=="secret")throw new TypeError(`${E(e)} instances for symmetric algorithms must be of type "secret"`)}},Ce=(t,e,r,n)=>{if(n&&b(e))switch(r){case"sign":if(ge(e)&&H(t,e,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(_e(e)&&H(t,e,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!V(e))throw new TypeError(j(t,e,...v,n?"JSON Web Key":null));if(e.type==="secret")throw new TypeError(`${E(e)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&e.type==="public")throw new TypeError(`${E(e)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&e.type==="public")throw new TypeError(`${E(e)} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&r==="verify"&&e.type==="private")throw new TypeError(`${E(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&r==="encrypt"&&e.type==="private")throw new TypeError(`${E(e)} instances for asymmetric algorithm encryption must be of type "public"`)};function B(t,e,r,n){e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?ve(e,r,n,t):Ce(e,r,n,t)}B.bind(void 0,!1);const Ke=B.bind(void 0,!0);function Je(t,e,r,n,s){if(s.crit!==void 0&&n?.crit===void 0)throw new t('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(a=>typeof a!="string"||a.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...e.entries()]):i=e;for(const a of n.crit){if(!i.has(a))throw new f(`Extension Header Parameter "${a}" is not recognized`);if(s[a]===void 0)throw new t(`Extension Header Parameter "${a}" is missing`);if(i.get(a)&&n[a]===void 0)throw new t(`Extension Header Parameter "${a}" MUST be integrity protected`)}return new Set(n.crit)}function Pe(t,e){const r=`SHA-${t.slice(-3)}`;switch(t){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:t.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:e.name};default:throw new f(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}async function Oe(t,e,r){if(e=await We.normalizePrivateKey(e,t),F(e))return ye(e,t,r),e;if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(M(e,...v));return x.subtle.importKey("raw",e,{hash:`SHA-${t.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(M(e,...v,"Uint8Array","JSON Web Key"))}const l=t=>Math.floor(t.getTime()/1e3),q=60,Y=q*60,$=Y*24,He=$*7,De=$*365.25,xe=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,O=t=>{const e=xe.exec(t);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");const r=parseFloat(e[2]),n=e[3].toLowerCase();let s;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":s=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":s=Math.round(r*q);break;case"hour":case"hours":case"hr":case"hrs":case"h":s=Math.round(r*Y);break;case"day":case"days":case"d":s=Math.round(r*$);break;case"week":case"weeks":case"w":s=Math.round(r*He);break;default:s=Math.round(r*De);break}return e[1]==="-"||e[4]==="ago"?-s:s},Ne=async(t,e,r)=>{const n=await Oe(t,e,"sign");Ee(t,n);const s=await x.subtle.sign(Pe(t,n.algorithm),n,r);return new Uint8Array(s)};class $e{constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new w("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Se(this._protectedHeader,this._unprotectedHeader))throw new w("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...this._protectedHeader,...this._unprotectedHeader},s=Je(w,new Map([["b64",!0]]),r?.crit,this._protectedHeader,n);let i=!0;if(s.has("b64")&&(i=this._protectedHeader.b64,typeof i!="boolean"))throw new w('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=n;if(typeof a!="string"||!a)throw new w('JWS "alg" (Algorithm) Header Parameter missing or invalid');Ke(a,e,"sign");let T=this._payload;i&&(T=g.encode(J(T)));let A;this._protectedHeader?A=g.encode(J(JSON.stringify(this._protectedHeader))):A=g.encode("");const Z=ee(A,g.encode("."),T),Q=await Ne(a,e,Z),I={signature:J(Q),payload:""};return i&&(I.payload=W.decode(T)),this._unprotectedHeader&&(I.header=this._unprotectedHeader),this._protectedHeader&&(I.protected=W.decode(A)),I}}class Ue{constructor(e){this._flattened=new $e(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,r){const n=await this._flattened.sign(e,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}}function u(t,e){if(!Number.isFinite(e))throw new TypeError(`Invalid ${t} input`);return e}class Me{constructor(e={}){if(!N(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return typeof e=="number"?this._payload={...this._payload,nbf:u("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:u("setNotBefore",l(e))}:this._payload={...this._payload,nbf:l(new Date)+O(e)},this}setExpirationTime(e){return typeof e=="number"?this._payload={...this._payload,exp:u("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:u("setExpirationTime",l(e))}:this._payload={...this._payload,exp:l(new Date)+O(e)},this}setIssuedAt(e){return typeof e>"u"?this._payload={...this._payload,iat:l(new Date)}:e instanceof Date?this._payload={...this._payload,iat:u("setIssuedAt",l(e))}:typeof e=="string"?this._payload={...this._payload,iat:u("setIssuedAt",l(new Date)+O(e))}:this._payload={...this._payload,iat:u("setIssuedAt",e)},this}}class Le extends Me{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,r){const n=new Ue(g.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new h("JWTs MUST NOT use unencoded payload");return n.sign(e,r)}}const Fe=K;function U(t){if(typeof t!="string")throw new h("JWTs must use Compact JWS serialization, JWT must be a string");const{1:e,length:r}=t.split(".");if(r===5)throw new h("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new h("Invalid JWT");if(!e)throw new h("JWTs must contain a payload");let n;try{n=Fe(e)}catch{throw new h("Failed to base64url decode the payload")}let s;try{s=JSON.parse(W.decode(n))}catch{throw new h("Failed to parse the decoded payload as JSON")}if(!N(s))throw new h("Invalid JWT Claims Set");return s}var ke=Object.defineProperty,je=(t,e,r)=>e in t?ke(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ve=(t,e,r)=>je(t,e+"",r);function Ge(t){const{sub:e}=U(t);if(!e)throw new Error("token did not contain a subject field");return e}function ze(t){const{email:e}=U(t);if(!(typeof e!="string"||e.length===0))return e}function L(t){try{const e=U(t),r=Math.floor(Date.now()/1e3);return typeof e.exp=="number"&&e.exp<=r}catch{return!0}}var Be=class{constructor(t,e){this.configUrl=t,this.logger=e}async fetchToken(t){try{const e=await this.getOIDCConfig(this.configUrl);this.logger?.debug({oidcConfig:e},"Fetched OIDC config");const n=await(await this.fetchTokenEndpoint(e.token_endpoint,t)).json();if(this.logger?.info({response:n},`Fetched admin token for clientId: ${t.clientId}`),!n.access_token)throw new Error("No access_token in token endpoint response");return n.access_token}catch(e){throw this.logger?.error({err:e},"Failed to fetch admin token"),e}}async fetchTokenEndpoint(t,e){const r=new URLSearchParams({grant_type:"client_credentials",client_id:e.clientId,client_secret:e.clientSecret,scope:e.scope??"",audience:e.audience??""}),n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()});if(!n.ok)throw this.logger?.error({status:n.status,statusText:n.statusText},"Token endpoint error"),new Error(`Token endpoint error: ${n.status} ${n.statusText}`);return n}async getOIDCConfig(t){const e=await fetch(t);if(!e.ok){const r=await e.text();throw this.logger?.error({status:e.status,statusText:e.statusText,body:r},"Failed to fetch OIDC config"),new Error(`OIDC config error: ${e.status} ${e.statusText}`)}return e.json()}},qe=(t,e)=>({fetchToken:async r=>new Be(t,e).fetchToken(r)}),Ye=class{static async fetchToken(t,e,r,n=3600){const s=new TextEncoder().encode(e.clientSecret),i=Math.floor(Date.now()/1e3),a=await new Le({sub:e.clientId,aud:e.audience||"",scope:e.scope||"",iat:i,exp:i+n,iss:r}).setProtectedHeader({alg:"HS256"}).sign(s);return t.info(`Generated self-signed JWT token: ${a}`),a}},rt=class R{constructor(e,r){this.config=e,this.logger=r,Ve(this,"cachedToken")}static fromToken(e,r){return new R({method:"static",token:e},r)}static fromGatewayConfig(e,r,n){if(r.method==="self_signed")return new R({method:r.method,issuer:r.issuer,credentials:{clientId:r.clientId,clientSecret:r.clientSecret,scope:r.scope,audience:r.audience}},n);if(r.method==="client_credentials"){if(e.type==="oauth")return new R({method:r.method,configUrl:e.configUrl,credentials:{clientId:r.clientId,clientSecret:r.clientSecret,scope:r.scope,audience:r.audience}},n);throw new Error(`IDP type ${e.type} not supported for client_credentials auth`)}throw new Error(`Auth method ${r.method} not supported for programmatic access token`)}async _fetchToken(){switch(this.logger.debug("Fetching user auth token"),this.config.method){case"static":return this.config.token;case"self_signed":return Ye.fetchToken(this.logger,this.config.credentials,this.config.issuer);case"client_credentials":return qe(this.config.configUrl,this.logger).fetchToken(this.config.credentials)}}async getAccessToken(){if(this.cachedToken&&!L(this.cachedToken))return this.cachedToken;{const e=await this._fetchToken();if(L(e))throw new Error("Attempted to refresh a token, but it came back expired.");return this.cachedToken=e,e}}async getAuthContext(){const e=await this.getAccessToken(),r=Ge(e),n=ze(e);return{accessToken:e,userId:r,...n?{email:n}:{}}}},X=p({method:m("authorization_code"),audience:o(),scope:o(),clientId:o()}).meta({description:"Authorization code flow authentication configuration. This is used for browser-based application login."}),Xe=p({method:m("client_credentials"),audience:o(),scope:o(),clientId:o(),clientSecret:o()}),Ze=p({method:m("self_signed"),issuer:o(),audience:o(),scope:o(),clientId:o(),clientSecret:o()}),Qe=p({method:m("client_credentials"),audience:o(),scope:o(),clientId:o(),clientSecretEnv:o()}),et=p({method:m("self_signed"),issuer:o(),audience:o(),scope:o(),clientId:o(),clientSecretEnv:o()}),nt=D("method",[X,Xe,Ze]);D("method",[X,Qe,et]);var st=D("type",[p({id:o(),type:m("self_signed"),issuer:o()}),p({id:o(),type:m("oauth"),issuer:o(),configUrl:o().url()})]);export{rt as A,nt as a,st as i};
|