dsh-siwc 0.1.5 → 0.1.6
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/README.md +1 -1
- package/dist/server/index.js +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -37,7 +37,7 @@ Build this plugin and install it into your Web profile:
|
|
|
37
37
|
|
|
38
38
|
```sh
|
|
39
39
|
pnpm --filter dsh-siwc pack --pack-destination ./artifacts
|
|
40
|
-
dsh plugin --profile web add ./artifacts/dsh-siwc-0.1.
|
|
40
|
+
dsh plugin --profile web add ./artifacts/dsh-siwc-0.1.6.tgz --ignore-scripts
|
|
41
41
|
```
|
|
42
42
|
|
|
43
43
|
## Use
|
package/dist/server/index.js
CHANGED
|
@@ -18,4 +18,4 @@ function wt(e,t){return new Ct({type:`literal`,values:Array.isArray(e)?e:[e],...
|
|
|
18
18
|
function F(e){return new Tt({type:`optional`,innerType:e})}const Et=/*@__PURE__*/ C(`ZodMiniCustom`,(e,t)=>{nt.init(e,t),j.init(e,t)});// @__NO_SIDE_EFFECTS__
|
|
19
19
|
function Dt(e,t={}){return/* @__PURE__ */ dt(Et,e,t)}const Ot=new TextEncoder,kt=new TextDecoder,At=new TextDecoder(`utf-8`,{fatal:!0});function jt(...e){let t=e.reduce((e,{length:t})=>e+t,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}const Mt=/[^\x00-\x7f]/;function Nt(e){if(typeof e==`string`&&e.length>=128){if(Mt.test(e))throw TypeError(`non-ASCII string encountered in encode()`);return Ot.encode(e)}let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>127)throw TypeError(`non-ASCII string encountered in encode()`);t[n]=r}return t}function Pt(e,t=!1){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e,{alphabet:t?`base64url`:`base64`});if(t){if(e.includes(`+`)||e.includes(`/`))throw TypeError(`Invalid base64url`);e=e.replace(/-/g,`+`).replace(/_/g,`/`)}let n=atob(e),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return r}var I=class extends Error{static code=`ERR_JOSE_GENERIC`;code=`ERR_JOSE_GENERIC`;constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},L=class extends I{static code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},Ft=class extends I{static code=`ERR_JWT_EXPIRED`;code=`ERR_JWT_EXPIRED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},It=class extends I{static code=`ERR_JOSE_ALG_NOT_ALLOWED`;code=`ERR_JOSE_ALG_NOT_ALLOWED`},R=class extends I{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},z=class extends I{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},Lt=class extends I{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`},Rt=class extends I{static code=`ERR_JWKS_INVALID`;code=`ERR_JWKS_INVALID`},zt=class extends I{static code=`ERR_JWKS_NO_MATCHING_KEY`;code=`ERR_JWKS_NO_MATCHING_KEY`;constructor(e=`no applicable key found in the JSON Web Key Set`,t){super(e,t)}},Bt=class extends I{[Symbol.asyncIterator]=async function*(){};static code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;constructor(e=`multiple matching keys found in the JSON Web Key Set`,t){super(e,t)}},Vt=class extends I{static code=`ERR_JWKS_TIMEOUT`;code=`ERR_JWKS_TIMEOUT`;constructor(e=`request timed out`,t){super(e,t)}},Ht=class extends I{static code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;constructor(e=`signature verification failed`,t){super(e,t)}};function Ut(e){try{return Pt(typeof e==`string`?e:kt.decode(e),!0)}catch(e){throw TypeError(`The input to be decoded is not correctly encoded.`,{cause:e})}}function B(e){if(typeof e!=`object`||!e||Object.prototype.toString.call(e)!==`[object Object]`)return!1;let t=Object.getPrototypeOf(e);return t===null||Object.getPrototypeOf(t)===null}function Wt(e){return B(e)&&Array.isArray(e.keys)&&Array.from(e.keys).every(B)}function Gt(...e){let t=/* @__PURE__ */ new Set;for(let n of e)if(n)for(let e of Object.keys(n)){if(t.has(e))return!1;t.add(e)}return!0}function Kt(e,t,n){try{return Ut(e)}catch{throw new n(`Failed to base64url decode the ${t}`)}}function qt(e,t,n){try{return Nt(e)}catch{throw new n(`The ${t} is not a valid base64url string`)}}function Jt(e,t,n){let r;try{r=JSON.parse(At.decode(Ut(e)))}catch{throw new t(n)}if(!B(r))throw new t(n);return r}const Yt={__proto__:null,b64:!0};function Xt(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(e=>typeof e!=`string`)))throw TypeError(`"${e}" option must be an array of strings`);return t===void 0?void 0:new Set(t)}function Zt(e,t,n,r,i){if(i.crit!==void 0&&r?.crit===void 0)throw new e(`"crit" (Critical) Header Parameter MUST be integrity protected`);if(!r||r.crit===void 0)return[];if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(e=>typeof e!=`string`||e.length===0))throw new e(`"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present`);let a=n===void 0?t:{__proto__:null,...n,...t};for(let t of r.crit){if(!(t in a))throw new R(`Extension Header Parameter "${t}" is not recognized`);if(!Object.hasOwn(i,t)||i[t]===void 0)throw new e(`Extension Header Parameter "${t}" is missing`);if(a[t]&&(!Object.hasOwn(r,t)||r[t]===void 0))throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return r.crit}function Qt(e,t){if(t.includes(`b64`)){let t=e.b64;if(typeof t!=`boolean`)throw new z(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);return t}return!0}const $t=e=>e[Symbol.toStringTag],en=(e,t,n)=>{let{alg:r}=e;if(t.use!==void 0){let e=n===`sign`||n===`verify`?`sig`:`enc`;if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(t.alg!==void 0&&t.alg!==r)throw TypeError(`Invalid key for this operation, its "alg" must be "${r}" when present`);if(Array.isArray(t.key_ops)){let r=n===`encrypt`||n===`decrypt`?e.ops?.[n===`encrypt`?0:1]:n;if(r&&!t.key_ops.includes(r))throw TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}};async function tn(e,t,n){let{alg:r,secret:i}=e,a=n===`decrypt`||n===`sign`;if(i&&t instanceof Uint8Array)return t;let o,s;if(B(t)){if(o=hn(t),typeof o.kty!=`string`)throw ln(r,t,i);if(!(i?o.kty===`oct`&&typeof o.k==`string`:o.kty!==`oct`&&(a?o.kty===`AKP`&&typeof o.priv==`string`||typeof o.d==`string`:o.d===void 0&&o.priv===void 0)))throw TypeError(i?`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`:`JSON Web Key for this operation must be a ${a?`private`:`public`} JWK`);if(en(e,o,n),o.kty===`oct`)return Ut(o.k);if(!Object.isFrozen(t)){let{key_ops:e}=t;Array.isArray(e)&&Object.freeze(e),Object.freeze(t)}}else{if(!sn(t))throw ln(r,t,i);let e=i?`secret`:a?`private`:`public`;if(t.type!==e&&(i||[`secret`,`public`,`private`].includes(t.type)))throw TypeError(`${$t(t)} instances must be of type "${e}" for the ${r} algorithm`);if(an(t))return t;if(s=t,s.type===`secret`)return s.export()}nn||=/* @__PURE__ */ new WeakMap;let c=t,l=nn.get(c);if(l?.[r])return l[r];if(l||nn.set(c,l={}),s&&typeof s.toCryptoKey==`function`){let t=s.type===`public`,n=rn[s.asymmetricKeyDetails?.namedCurve],i=e.resolve?.({crv:n,asymmetricKeyType:s.asymmetricKeyType})??e.subtle;return l[r]=s.toCryptoKey(i,t,e.usages[+!t])}return o??=s.export({format:`jwk`}),o.alg=r,l[r]=await gn(e,o)}let nn;const rn={__proto__:null,prime256v1:`P-256`,secp384r1:`P-384`,secp521r1:`P-521`},an=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},on=e=>e?.[Symbol.toStringTag]===`KeyObject`,sn=e=>an(e)||on(e);function cn(e,t,...n){if(n.length>2){let t=n.pop();e+=`one of type ${n.join(`, `)}, or ${t}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return t==null?e+=` Received ${t}`:typeof t==`function`&&t.name?e+=` Received function ${t.name}`:typeof t==`object`&&t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}function ln(e,t,n){let r=[`CryptoKey`,`KeyObject`,`JSON Web Key`];return n&&r.push(`Uint8Array`),TypeError(cn(`Key for the ${e} algorithm must be `,t,...r))}const un=(e,t=`algorithm.name`)=>/* @__PURE__ */ TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`);function dn(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function fn(e,t){let{modulusLength:n}=t.algorithm;if(typeof n!=`number`||n<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}function pn(e,t,n){let r=e.algorithm;if(r.name!==t.name)throw un(t.name);if(t.hash&&r.hash?.name!==t.hash)throw un(t.hash,`algorithm.hash`);if(t.namedCurve&&r.namedCurve!==t.namedCurve)throw un(t.namedCurve,`algorithm.namedCurve`);if(t.length!==void 0&&r.length!==t.length)throw un(t.length,`algorithm.length`);dn(e,n)}function mn(e){return{__proto__:null,...e}}function hn(e){let t=mn(e);if(t.ext!==void 0&&typeof t.ext!=`boolean`)throw TypeError(`"ext" (Extractable) Parameter must be a boolean`);if(t.key_ops!==void 0){let e=t.key_ops,n=Array.isArray(e)?[...e]:void 0;if(!n||n.some(e=>typeof e!=`string`)||new Set(n).size!==n.length)throw TypeError(`"key_ops" (Key Operations) Parameter must be an array of unique strings`);t.key_ops=n}return t}async function gn(e,t,n){if(!e.kty.includes(t.kty))throw new R(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`);let r=e.resolve?.({kty:t.kty,crv:t.crv})??e.subtle,i=!!(t.d||t.priv),a={...t,ext:n??t.ext};return a.kty!==`AKP`&&delete a.alg,delete a.use,crypto.subtle.importKey(`jwk`,a,r,a.ext??!i,t.key_ops??e.usages[+!!i])}async function _n(e,t,n,r=!1){return e instanceof Uint8Array&&(e=await crypto.subtle.importKey(`raw`,e,t,r,[n])),pn(e,t,n),e}function vn(e){let t={__proto__:null};for(let n in e)t[n]={...e[n],alg:n};return t}const V=[[`verify`],[`sign`]];function yn(e){let t={name:`HMAC`,hash:`SHA-${e}`};return{kty:[`oct`],secret:!0,subtle:t,signing:t,usages:V}}function H(e,t){let n={name:t?`RSA-PSS`:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e}`};return{kty:[`RSA`],subtle:n,signing:t?{...n,saltLength:t}:n,usages:V,minRsaBits:2048}}function bn(e,t){return{kty:[`EC`],crv:e,subtle:{name:`ECDSA`,namedCurve:e},signing:{name:`ECDSA`,hash:`SHA-${t}`},usages:V}}function xn(){let e={name:`Ed25519`};return{kty:[`OKP`],crv:`Ed25519`,subtle:e,signing:e,usages:V}}function Sn(e){let t={name:`ML-DSA-${e}`};return{kty:[`AKP`],subtle:t,signing:t,usages:V}}const Cn=vn({HS256:yn(256),HS384:yn(384),HS512:yn(512),RS256:H(256),RS384:H(384),RS512:H(512),PS256:H(256,32),PS384:H(384,48),PS512:H(512,64),ES256:bn(`P-256`,256),ES384:bn(`P-384`,384),ES512:bn(`P-521`,512),EdDSA:xn(),Ed25519:xn(),"ML-DSA-44":Sn(44),"ML-DSA-65":Sn(65),"ML-DSA-87":Sn(87)});function wn(e){let t=typeof e==`string`?Cn[e]:void 0;if(!t)throw new R(`alg ${e} is not supported either by JOSE or your javascript runtime`);return t}function Tn(e){return[e&&Xt(`algorithms`,e.algorithms),e?.crit]}function En(e){return e===void 0?{}:Jt(e,z,`JWS Protected Header is invalid`)}function Dn(e){try{return Nt(e)}catch{throw new z(`JWS Compact Serialization payload must use only ASCII characters`)}}async function On(e,t,n,r,i){let{protected:a,header:o,payload:s}=e,c=i??En(a);if(!Gt(c,o))throw new z(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let l={...c,...o},u=Qt(c,Zt(z,Yt,t[1],c,l)),{alg:d}=l;if(typeof d!=`string`||!d)throw new z(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);if(t[0]&&!t[0].has(d))throw new It(`"alg" (Algorithm) Header Parameter value not allowed`);if(u){if(typeof s!=`string`)throw new z(`JWS Payload must be a string`)}else if(typeof s!=`string`&&!(s instanceof Uint8Array))throw new z(`JWS Payload must be a string or an Uint8Array instance`);let f=u||typeof s!=`string`?s:r(s),p=!1;typeof n==`function`&&(n=await n(c,e),p=!0);let m=wn(d),h=jt(a===void 0?/* @__PURE__ */ new Uint8Array:Nt(a),Nt(`.`),typeof f==`string`?t[2]??=qt(f,`payload`,z):f),g=Kt(e.signature,`signature`,z),_=await tn(m,n,`verify`),v=await _n(_,m.subtle,`verify`);m.minRsaBits&&fn(m.alg,v);let ee=!1;try{ee=await crypto.subtle.verify(m.signing,v,g,h)}catch{}if(!ee)throw new Ht;let y={payload:typeof f==`string`?Kt(f,`payload`,z):f};return a!==void 0&&(y.protectedHeader=c),o!==void 0&&(y.unprotectedHeader=o),p?[{...y,key:_},u]:[y,u]}async function kn(e,t,n){if(e instanceof Uint8Array&&(e=kt.decode(e)),typeof e!=`string`)throw new z(`Compact JWS must be a string or Uint8Array`);let{0:r,1:i,2:a,length:o}=e.split(`.`);if(o!==3)throw new z(`Invalid Compact JWS`);return On({payload:i,protected:r,signature:a},t,n,Dn)}const An=e=>Math.floor(e.getTime()/1e3),jn={s:1,m:60,h:3600,d:86400,w:604800,y:31557600},Mn=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,U=`check_failed`;function Nn(){throw TypeError(`Invalid time period format`)}function Pn(e){typeof e!=`string`&&Nn();let t=Mn.exec(e);(!t||t[4]&&t[1])&&Nn();let n=parseFloat(t[2]),r=Math.round(n*jn[t[3][0].toLowerCase()]);return Number.isFinite(r)||Nn(),t[1]===`-`||t[4]===`ago`?-r:r}function Fn(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}const In=e=>{let t=e.toLowerCase();return e.includes(`/`)?t:`application/${t}`},Ln=(e,t)=>typeof e==`string`?t.includes(e):Array.isArray(e)?t.some(t=>e.includes(t)):!1;function Rn(e,t,n=!1){let r=e[t];if(r!==void 0||n){if(typeof r!=`number`)throw new L(`"${t}" claim must be a number`,e,t,`invalid`);return r}}function zn(e,t){throw new L(`unexpected "${t}" claim value`,e,t,U)}function Bn(e,t,n={}){let r;try{r=JSON.parse(At.decode(t))}catch{}if(!B(r))throw new Lt(`JWT Claims Set must be a top-level JSON object`);let{typ:i}=n;if(i!==void 0&&(typeof e.typ!=`string`||In(e.typ)!==In(i)))throw new L(`unexpected "typ" JWT header value`,r,`typ`,U);let{requiredClaims:a=[],issuer:o,subject:s,audience:c,maxTokenAge:l}=n,u=[...a];l!==void 0&&u.push(`iat`),c!==void 0&&u.push(`aud`),s!==void 0&&u.push(`sub`),o!==void 0&&u.push(`iss`);for(let e of new Set(u.reverse()))if(!Object.hasOwn(r,e))throw new L(`missing required "${e}" claim`,r,e,`missing`);o!==void 0&&!(Array.isArray(o)?o:[o]).includes(r.iss)&&zn(r,`iss`),s!==void 0&&r.sub!==s&&zn(r,`sub`),c!==void 0&&!Ln(r.aud,typeof c==`string`?[c]:c)&&zn(r,`aud`);let{clockTolerance:d}=n,f=0;if(typeof d==`string`)f=Pn(d);else if(d!==void 0){if(typeof d!=`number`)throw TypeError(`Invalid clockTolerance option type`);f=d}Fn(`clockTolerance option`,f);let{currentDate:p}=n,m=Fn(`currentDate option`,An(p===void 0?/* @__PURE__ */ new Date:p)),h=Rn(r,`iat`,l!==void 0),g=Rn(r,`nbf`);if(g!==void 0&&g>m+f)throw new L(`"nbf" claim timestamp check failed`,r,`nbf`,U);let _=Rn(r,`exp`);if(_!==void 0&&_<=m-f)throw new Ft(`"exp" claim timestamp check failed`,r,`exp`,U);if(l!==void 0){let e=m-h,t=Fn(`maxTokenAge option`,typeof l==`number`?l:Pn(l));if(e-f>t)throw new Ft(`"iat" claim timestamp check failed (too far in the past)`,r,`iat`,U);if(e<-f)throw new L(`"iat" claim timestamp check failed (it should be in the past)`,r,`iat`,U)}return r}async function Vn(e,t,n){let[r,i]=await kn(e,Tn(n),t);if(!i)throw new Lt(`JWTs MUST NOT use unencoded payload`);let a=Bn(r.protectedHeader,r.payload,n);return{...r,payload:a}}function Hn(e,t,n,r){let{kty:i,key_ops:a,ext:o,kid:s,alg:c,use:l,crv:u}=e;return(o===void 0||typeof o==`boolean`)&&(a===void 0||Array.isArray(a)&&a.every((e,t)=>typeof e==`string`&&a.indexOf(e)===t)&&a.includes(`verify`))&&t.kty.includes(i)&&(r===void 0||typeof r==`string`&&r===s)&&(c===void 0?i!==`AKP`:n===c)&&(l===void 0||l===`sig`)&&(!t.crv||u===t.crv)}async function Un(e,t,n){let r=e.get(t)||e.set(t,{}).get(t),{alg:i}=n;if(r[i]===void 0){let e=gn(n,t,!0).then(e=>{if(e.type!==`public`)throw new Rt(`JSON Web Key Set members must be public keys`);return r[i]=e,e}).catch(t=>{throw r[i]===e&&delete r[i],t});r[i]=e}return r[i]}function Wn(e){let t;try{t=structuredClone(e)}catch{}if(!Wt(t))throw new Rt(`JSON Web Key Set malformed`);let n=t.keys.map(e=>{let t=mn(e);return Array.isArray(t.key_ops)&&(t.key_ops=[...t.key_ops]),t}),r=/* @__PURE__ */ new WeakMap;return Object.defineProperty(async(e,i)=>{let{alg:a,kid:o}={...e,...i?.header},s=typeof a==`string`?Cn[a]:void 0;if(!s||s.secret)throw new R(`Unsupported "alg" value for a JSON Web Key Set`);let c=t.keys.filter((e,t)=>Hn(n[t],s,a,o)),{0:l,length:u}=c;if(!u)throw new zt;if(u!==1){let e=new Bt;throw e[Symbol.asyncIterator]=async function*(){for(let e of c)try{yield await Un(r,e,s)}catch{}},e}return Un(r,l,s)},"jwks",{value:()=>structuredClone(t)})}function Gn(){return typeof WebSocketPair<`u`||typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`||typeof EdgeRuntime<`u`&&EdgeRuntime===`vercel`}let Kn;(typeof navigator>`u`||!navigator.userAgent?.startsWith?.(`Mozilla/5.0 `))&&(Kn=`jose/v6.2.12`);const qn=/* @__PURE__ */ Symbol();async function Jn(e,t,n,r=fetch){let i=await r(e,{method:`GET`,signal:n,redirect:`manual`,headers:t}).catch(e=>{throw e.name===`TimeoutError`?new Vt:e});if(i.status!==200)throw new I(`Expected 200 OK from the JSON Web Key Set HTTP response`);try{return await i.json()}catch{throw new I(`Failed to parse the JSON Web Key Set HTTP response as JSON`)}}const Yn=/* @__PURE__ */ Symbol();function W(e,t){return Number.isFinite(e)&&Date.now()<e+t}function Xn(e,t,n){if(Number.isNaN(e))throw TypeError(`"${n}" option must not be NaN`);return typeof e==`number`?e:t}function Zn(e,t){if(!(e instanceof URL))throw TypeError(`url must be an instance of URL`);let n=new URL(e.href).href,r=t??{},i=r.timeoutDuration;if(typeof i==`number`&&(!Number.isInteger(i)||i<0))throw TypeError(`"timeoutDuration" option must be a non-negative integer`);let a=typeof i==`number`?i:5e3,o=Xn(r.cooldownDuration,3e4,`cooldownDuration`),s=Xn(r.cacheMaxAge,6e5,`cacheMaxAge`),c=new Headers(r.headers);Kn&&!c.has(`User-Agent`)&&c.set(`User-Agent`,Kn),c.has(`accept`)||c.set(`accept`,`application/json, application/jwk-set+json`);let l=r[qn],u=r[Yn],d,f,p=0,m=0,h;if(u&&typeof u==`object`){let{uat:e,jwks:t}=u;W(e,s)&&Wt(t)&&(d=e,h=Wn(t))}let g=async()=>{if(f&&Gn()&&(f=void 0),!f){let e=++p,t=f=Jn(n,c,AbortSignal.timeout(a),l).then(t=>{let n=Wn(t);if(e<=m)return;h=n;let r=Date.now();u&&(u.uat=r,u.jwks=t),d=r,m=e}).finally(()=>{f===t&&(f=void 0)})}await f};return Object.defineProperties(async(e,t)=>{(!h||!W(d,s))&&await g();try{return await h(e,t)}catch(n){if(n instanceof zt&&!W(d,o))return await g(),h(e,t);throw n}},{coolingDown:{get:()=>W(d,o),enumerable:!0},fresh:{get:()=>W(d,s),enumerable:!0},reload:{value:g,enumerable:!0},reloading:{get:()=>!!f,enumerable:!0},jwks:{value:()=>h?.jwks(),enumerable:!0}})}const G=`https://auth.openai.com`,K=`https://api.openai.com/v1`,Qn=`https://chatgpt.com/settings/usage`;var q=class extends Error{},$n=class extends Error{},er=class extends Error{status;code;requestId;constructor(e,t,n){super(`OpenAI request failed (${e}${t?`: ${t}`:``}). Reconnect in Settings → SIWC; manage usage: ${Qn}`),this.status=e,this.code=t,this.requestId=n}};const tr=/* @__PURE__ */ new Set([`invalid_grant`,`invalid_refresh_token`,`token_expired`,`refresh_token_expired`,`refresh_token_invalidated`,`refresh_token_reused`]);function nr(e){n.ok(typeof e==`object`&&!!e&&!Array.isArray(e),`Invalid OpenAI response`)}function J(e,t){n.ok(typeof e==`string`&&e.trim(),`OpenAI returned invalid ${t}`)}async function rr(e,t={}){let n=await fetch(e,{...t,signal:AbortSignal.any([AbortSignal.timeout(2e4),...t.signal?[t.signal]:[]])}).catch(e=>{throw new $n(`Could not reach OpenAI. Check your connection and try again.`,{cause:e})});if(!n.ok){let e;if(n.headers.get(`content-type`)?.includes(`json`))try{let t=await n.json();nr(t),typeof t.error==`string`?e=t.error:t.error&&typeof t.error==`object`&&`code`in t.error&&typeof t.error.code==`string`&&(e=t.error.code)}catch{e=void 0}throw new er(n.status,e,n.headers.get(`x-request-id`))}let r;try{r=await n.json()}catch{throw new $n(`OpenAI returned an invalid JSON response.`)}return nr(r),r}async function Y(e){let t=await rr(`${G}/.well-known/openid-configuration`,{signal:e});n.equal(t.issuer,G,`Unexpected OpenAI issuer`);for(let e of[`authorization_endpoint`,`token_endpoint`,`jwks_uri`])J(t[e],e),n.equal(new URL(t[e]).origin,G,`Unexpected OpenAI ${e}`);return t.revocation_endpoint!==void 0&&(J(t.revocation_endpoint,`revocation_endpoint`),n.equal(new URL(t.revocation_endpoint).origin,G,`Unexpected OpenAI revocation endpoint`)),t}async function ir(e,t,r,i,a){let o=await Y(a).catch(()=>{throw new q(`OpenAI identity service is unavailable. Try again.`)}),s=Zn(new URL(o.jwks_uri)),{payload:c}=await Vn(e,async(e,t)=>{try{return await s(e,t)}catch(e){throw e instanceof zt?e:new q(`OpenAI signing keys are unavailable. Try again.`)}},{issuer:G,audience:t,algorithms:[`RS256`],requiredClaims:[`iss`,`sub`,`aud`,`iat`,`exp`],...i===void 0?{}:{currentDate:new Date(i)}});return J(c.sub,`ID token subject`),r!==void 0&&n.equal(c.nonce,r,`OpenAI ID token nonce mismatch`),(c.azp!==void 0||Array.isArray(c.aud)&&c.aud.length>1)&&n.equal(c.azp,t,`OpenAI ID token authorized party mismatch`),{subject:c.sub,...typeof c.email==`string`?{email:c.email}:{}}}async function ar(e,t){let r=await rr((await Y(t)).token_endpoint,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:e,signal:t});J(r.access_token,`access_token`),J(r.refresh_token,`refresh_token`),J(r.scope,`scope`),n.equal(String(r.token_type).toLowerCase(),`bearer`,`Unexpected OpenAI token type`),n.ok(typeof r.expires_in==`number`&&Number.isFinite(r.expires_in)&&r.expires_in>0,`Invalid OpenAI token expiry`);let i=r.scope.split(/\s+/);n.ok(i.includes(`chatgpt.tokens.use.direct`),`ChatGPT plan usage was not granted`);let a;return r.earliest_refresh_at!==void 0&&(a=typeof r.earliest_refresh_at==`number`?r.earliest_refresh_at*1e3:Date.parse(String(r.earliest_refresh_at)),n.ok(Number.isFinite(a),`Invalid earliest_refresh_at`)),r.id_token!==void 0&&J(r.id_token,`id_token`),{tokens:{access:r.access_token,refresh:r.refresh_token,expires:Date.now()+r.expires_in*1e3,scopes:i,...a===void 0?{}:{refreshAfter:a}},receivedAt:Date.now(),...r.id_token===void 0?{}:{idToken:r.id_token}}}function or(e,t){return n.ok(e.tokens,`Sign in with ChatGPT in Settings first`),ar(new URLSearchParams({grant_type:`refresh_token`,client_id:e.clientId,refresh_token:e.tokens.refresh,resource:K}),t)}async function sr(e){let t=AbortSignal.timeout(1e4),r=await Y(t);n.ok(r.revocation_endpoint,`OpenAI did not publish a revocation endpoint`);let i=e.pending?.tokens.refresh??e.tokens?.refresh;n.ok(i,`No renewable ChatGPT session`);for(let n=0;;n++){try{let n=await fetch(r.revocation_endpoint,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},signal:t,body:new URLSearchParams({token:i,token_type_hint:`refresh_token`,client_id:e.clientId})});if(n.status===200)return;if(n.status<500)throw Error(`ChatGPT session revocation failed (${n.status})`)}catch(e){if(!(e instanceof TypeError)||t.aborted||n===2)throw e}if(n===2)throw Error(`ChatGPT session revocation is unavailable`);await v(200*2**n,void 0,{signal:t})}}async function cr(e,t){let r=await rr(`${K}/models`,{headers:{authorization:`Bearer ${e}`},signal:t});return n.ok(Array.isArray(r.models),`Invalid ChatGPT model catalog`),r.models.filter(e=>(nr(e),e.visibility===`list`&&(e.supported_in_api!==void 0&&n.equal(typeof e.supported_in_api,`boolean`,`Invalid ChatGPT API support flag`),e.supported_in_api!==!1))).map(e=>{J(e.slug,`model slug`),J(e.display_name,`model display name`);let t={id:e.slug,name:e.display_name};if(e.supported_in_api!==void 0&&(t.supportedInApi=e.supported_in_api),e.context_window!==void 0&&(n.ok(typeof e.context_window==`number`&&Number.isSafeInteger(e.context_window)&&e.context_window>0,`Invalid ChatGPT context window`),t.contextWindow=e.context_window),e.input_modalities!==void 0){n.ok(Array.isArray(e.input_modalities),`Invalid ChatGPT input modalities`);for(let t of e.input_modalities)J(t,`input modality`);t.input=[...e.input_modalities]}return e.supported_reasoning_levels!==void 0&&(n.ok(Array.isArray(e.supported_reasoning_levels),`Invalid ChatGPT reasoning levels`),t.reasoningEfforts=e.supported_reasoning_levels.map(e=>(nr(e),J(e.effort,`reasoning effort`),e.effort))),t})}async function lr(e,t,a,o){let s=await Y(e.signal),c=i(32).toString(`base64url`),l=i(32).toString(`base64url`),u=i(32).toString(`base64url`),d=AbortSignal.any([e.signal,AbortSignal.timeout(3e5)]),f,p,m=new Promise((e,t)=>{f=e,p=t}),h=()=>p(d.reason);d.addEventListener(`abort`,h,{once:!0}),m.catch(()=>{});let v,y=_((e,t)=>{t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`Referrer-Policy`,`no-referrer`),t.setHeader(`Content-Type`,`text/plain; charset=utf-8`);let n=new URL(e.url??`/`,`http://127.0.0.1`);if(e.method===`GET`&&n.pathname===`/auth/start`&&n.searchParams.get(`state`)===c){t.writeHead(302,{Location:v}).end();return}if(e.method!==`GET`||n.pathname!==`/auth/callback`){t.writeHead(404).end(`Not found`);return}if(n.searchParams.get(`state`)!==c){t.writeHead(400).end(`OAuth state mismatch`);return}if(n.searchParams.has(`error`)){t.writeHead(400).end(`ChatGPT sign-in was declined. Return to DSH.`),p(/* @__PURE__ */ Error(`ChatGPT sign-in was declined`));return}let r=n.searchParams.get(`code`),i=n.searchParams.get(`client_id`)??a.clientId;!r||!i||i===`dynamic_agent_client`||a.clientId!==`dynamic_agent_client`&&a.clientId!==i?(t.writeHead(400).end(`Invalid OAuth registration callback`),p(/* @__PURE__ */ Error(`Invalid OpenAI OAuth registration callback`))):(t.end(`Return to DSH to finish connecting your ChatGPT account.`),f({code:r,clientId:i}))}),b=new AbortController;try{d.throwIfAborted(),y.listen(0,`127.0.0.1`),await g(y,`listening`);let i=y.address();n.ok(i&&typeof i==`object`);let f=`http://127.0.0.1:${i.port}/auth/callback`,p=new URL(s.authorization_endpoint);p.search=new URLSearchParams({client_id:a.clientId,ext_agent_host_id:t,response_type:`code`,redirect_uri:f,resource:K,scope:`openid profile email offline_access resource.invoke chatgpt.tokens.use.direct`,state:c,nonce:l,code_challenge_method:`S256`,code_challenge:r(`sha256`).update(u).digest(`base64url`),...a.clientId===`dynamic_agent_client`?{agent_name_hint:`DSH SIWC`}:{},...a.idToken?{id_token_hint:a.idToken}:{},...a.email?{login_hint:a.email}:{}}).toString(),v=p.toString(),e.notify({message:`Continue with ChatGPT`,url:`http://127.0.0.1:${i.port}/auth/start?state=${c}`});let h=e.prompt({kind:`select`,message:`Open the sign-in link, then finish in your browser.`,options:[{id:`cancel`,label:`Cancel sign-in`}],signal:AbortSignal.any([d,b.signal])}).then(()=>{throw new ee}),_=await Promise.race([m,h]);b.abort(),d.throwIfAborted(),await o(_.clientId);let x=await ar(new URLSearchParams({grant_type:`authorization_code`,client_id:_.clientId,code:_.code,code_verifier:u,redirect_uri:f,resource:K}),d);J(x.idToken,`id_token`);let te=await ir(x.idToken,_.clientId,l,void 0,d);return a.subject&&n.equal(te.subject,a.subject,`ChatGPT account changed during reauthorization`),d.throwIfAborted(),{...te,tokens:x.tokens,idToken:x.idToken}}finally{b.abort(),d.removeEventListener(`abort`,h),y.close(),y.closeAllConnections()}}T(at());const X=d(`siwc`,`chatgpt`),ur=/* @__PURE__ */ P({access:(/* @__PURE__ */ M()).check(/* @__PURE__ */ A(1)),refresh:(/* @__PURE__ */ M()).check(/* @__PURE__ */ A(1)),expires:/* @__PURE__ */ mt(),scopes:/* @__PURE__ */ N(/* @__PURE__ */ M()),refreshAfter:/* @__PURE__ */ F(/* @__PURE__ */ mt())}),dr=/* @__PURE__ */ P({version:/* @__PURE__ */ wt(1),activeId:/* @__PURE__ */ F(/* @__PURE__ */ M()),welcomed:/* @__PURE__ */ F(/* @__PURE__ */ vt()),accounts:/* @__PURE__ */ N(/* @__PURE__ */ P({id:(/* @__PURE__ */ M()).check(/* @__PURE__ */ A(1)),clientId:(/* @__PURE__ */ M()).check(/* @__PURE__ */ A(1)),subject:/* @__PURE__ */ F(/* @__PURE__ */ M()),email:/* @__PURE__ */ F(/* @__PURE__ */ M()),idToken:/* @__PURE__ */ F(/* @__PURE__ */ M()),tokens:/* @__PURE__ */ F(ur),pending:/* @__PURE__ */ F(/* @__PURE__ */ P({tokens:ur,idToken:/* @__PURE__ */ F(/* @__PURE__ */ M()),receivedAt:/* @__PURE__ */ mt()})),models:/* @__PURE__ */ F(/* @__PURE__ */ N(/* @__PURE__ */ P({id:(/* @__PURE__ */ M()).check(/* @__PURE__ */ A(1)),name:(/* @__PURE__ */ M()).check(/* @__PURE__ */ A(1)),supportedInApi:/* @__PURE__ */ F(/* @__PURE__ */ vt()),contextWindow:/* @__PURE__ */ F((/* @__PURE__ */ mt()).check(/* @__PURE__ */ gt(),/* @__PURE__ */ Dt(e=>e>0,`Expected a positive integer`))),input:/* @__PURE__ */ F(/* @__PURE__ */ N((/* @__PURE__ */ M()).check(/* @__PURE__ */ A(1)))),reasoningEfforts:/* @__PURE__ */ F(/* @__PURE__ */ N((/* @__PURE__ */ M()).check(/* @__PURE__ */ A(1))))})))}))}),fr=e=>`${e.email??`Saved registration`} (${e.id.slice(0,8)})`;function Z(e){return e===void 0?{version:1,accounts:[]}:(n.ok(e.kind===`grant`,`Invalid SIWC credential record`),dr.parse(e.payload))}async function pr(){let e=f(`siwc`,`host-id`);return await o(c(e),{recursive:!0,mode:448}),l(e,async()=>{let t;try{t=(await s(e,`utf8`)).trim()}catch(n){if(n.code!==`ENOENT`)throw n;t=`urn:uuid:${a()}`,await u(e,t,{mode:384,dirMode:448})}return n.match(t,/^urn:uuid:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,`Invalid saved SIWC host ID`),t})}var mr=class{credentials;constructor(e){this.credentials=e}async read(){return Z(await this.credentials.readRecord(X))}async change(e){return Z(await this.credentials.modifyRecord(X,async t=>{let n=Z(t);return await e(n),{kind:`grant`,payload:n}}))}async accessToken(e,t){let r,i=AbortSignal.timeout(2e4),a=await this.credentials.modifyRecord(X,async a=>{let o=Z(a),s=o.accounts.find(t=>t.id===(e??o.activeId));if(!s?.tokens)throw new p(`Continue with ChatGPT in Settings → SIWC.`,`MISSING_CREDENTIAL`);let c=Date.now();if(t!==void 0&&s.tokens.access!==t||!s.pending&&(t===void 0&&c<s.tokens.expires-6e4||s.tokens.refreshAfter!==void 0&&c<s.tokens.refreshAfter&&c<s.tokens.expires))return;if(!s.pending&&s.tokens.refreshAfter!==void 0&&c<s.tokens.refreshAfter)throw Error(`ChatGPT token expired before its refresh window. Try again later or reconnect.`);let l;try{if(l=s.pending??await or(s,i),l.idToken){let e=await ir(l.idToken,s.clientId,void 0,l.receivedAt,i);n.equal(e.subject,s.subject,`Refreshed ChatGPT identity changed`),s.idToken=l.idToken}s.tokens=l.tokens,delete s.pending}catch(e){if(e instanceof q&&l)s.pending=l;else if(l||e instanceof er&&e.code!==void 0&&tr.has(e.code))delete s.tokens,delete s.pending,o.activeId===s.id&&delete o.activeId;else throw e;r=e}return{kind:`grant`,payload:o}});if(r)throw r;let o=Z(a);return o.accounts.find(t=>t.id===(e??o.activeId)).tokens.access}},Q=class extends Error{name=`SiwcAccountError`};function hr(e){return e instanceof ee||e instanceof y&&e.code===`CANCELLED`?`Sign-in cancelled.`:e instanceof Q||e instanceof $n||e instanceof er||e instanceof q?e.message:`Could not finish the account action. Try again.`}var gr=class{current;preferredAccountId;operations=Promise.resolve();ctx;accounts;syncAdapter;constructor(e,t,n){this.ctx=e,this.accounts=t,this.syncAdapter=n}async status(){let e=await this.accounts.read(),t=e.accounts.find(t=>t.id===e.activeId&&t.tokens),n=e.accounts.map(t=>({id:t.id,label:fr(t),active:t.id===e.activeId,signedIn:t.tokens!==void 0})).sort((e,t)=>Number(t.active)-Number(e.active));return{...t?{account:{id:t.id,label:fr(t)}}:{},accounts:n,models:t?.models?.map(({id:e,name:t})=>({id:e,name:t}))??[],usageUrl:Qn,...this.current?{attempt:this.projectAttempt(this.current)}:{}}}authorize(e,t){return this.enqueue(()=>this.startAuthorize(e,t))}async startAuthorize(e,t){if(this.current?.phase===`running`)return{status:await this.status()};if(t!==void 0){if(!t)throw new Q(`Choose a saved ChatGPT account.`);if(t!==`new`&&!(await this.accounts.read()).accounts.some(e=>e.id===t))throw new Q(`Saved ChatGPT account not found.`)}let n={id:a(),method:e,controller:new AbortController,phase:`running`,done:Promise.resolve()};return this.current=n,this.preferredAccountId=t,n.done=this.ctx.authorization.begin({key:X,method:e,signal:n.controller.signal,interaction:{notify:e=>this.notify(n,e),prompt:e=>this.prompt(n,e)}}).then(e=>{n.phase=e.status===`authorized`?`authorized`:`cancelled`,n.notice={message:n.phase===`authorized`?`ChatGPT account connected.`:`Sign-in cancelled. Your active account was not changed.`},n.pending=void 0}).catch(e=>{n.phase=`failed`,n.error=hr(e),n.pending=void 0,this.ctx.logger.warn(`SIWC Settings authorization failed: %s`,hr(e))}).finally(()=>{this.current===n&&(this.preferredAccountId=void 0)}),{status:await this.status()}}async answer(e,t){let n=this.current;if(n?.id!==t)throw new Q(`This sign-in attempt is no longer active.`);if(n.phase!==`running`||!n.pending)throw new Q(`There is no sign-in question to answer.`);let r=n.pending;if(!r.prompt.options.some(t=>t.id===e))throw new Q(`Choose one of the available sign-in options.`);return r.resolve(e),{status:await this.status()}}async cancel(e){let t=this.current;if(t?.id!==e)throw new Q(`This sign-in attempt is no longer active.`);return t.phase===`running`&&(t.controller.abort(),this.ctx.authorization.cancel(X),await t.done),{status:await this.status()}}logout(){return this.enqueue(()=>this.performLogout())}async performLogout(){let e=this.current;e?.phase===`running`&&await this.cancel(e.id);let t=!0;return await this.accounts.change(async e=>{let n=e.accounts.find(t=>t.id===e.activeId);if(n?.tokens||n?.pending)try{await sr(n)}catch{t=!1}n&&(delete n.tokens,delete n.idToken,delete n.pending),delete e.activeId}),await this.syncAdapter(),this.current===e&&(this.current=void 0),{status:await this.status(),message:t?`Signed out. Saved registrations were kept.`:`Signed out locally. Remote revocation was not confirmed; disconnect this app in ChatGPT settings.`}}async authorizeSession(e){let t=await this.accounts.read(),n=t.accounts.filter(t=>e.method===`oauth`||t.tokens!==void 0),r=n.map(e=>({id:e.id,label:fr(e)}));if(e.method===`oauth`&&r.push({id:`new`,label:`Add ChatGPT account or workspace`}),!r.length)throw new Q(`Sign in with ChatGPT in Settings first.`);let i=this.preferredAccountId,o;if(i===`new`){if(e.method!==`oauth`)throw new Q(`Only sign-in can add a ChatGPT account.`);o=`new`}else if(i!==void 0){if(!n.some(e=>e.id===i))throw new Q(`This saved ChatGPT account cannot be selected.`);o=i}else o=r.length===1?r[0].id:await e.prompt({kind:`select`,message:`Choose your ChatGPT account`,options:r,signal:e.signal});let s=t.accounts.find(e=>e.id===o);if(o!==`new`&&!s)throw new Q(`Unknown ChatGPT account.`);let c=s?.tokens?.access,l=s?.subject,u=s??{id:a(),clientId:`dynamic_agent_client`};if(e.method===`oauth`){let t=await lr(e,await pr(),u,async t=>{e.signal.throwIfAborted(),u.clientId=t,await this.accounts.change(n=>{e.signal.throwIfAborted();let r=n.accounts.find(e=>e.id===u.id);r?r.clientId=t:n.accounts.push({...u,clientId:t}),e.signal.throwIfAborted()})});Object.assign(u,t)}if(!u.tokens)throw new Q(`This account is signed out. Reconnect it in Settings.`);let d=e.method===`oauth`?u.tokens.access:await this.accounts.accessToken(u.id),f=await cr(d,e.signal);t.welcomed||(e.notify({message:`Manage usage`,url:Qn}),await e.prompt({kind:`select`,message:`You're using your ChatGPT plan. Eligible requests use your plan allowance. Manage usage in ChatGPT settings.`,options:[{id:`ok`,label:`Got it`}],signal:e.signal})),e.signal.throwIfAborted();let p=Z(await this.accounts.credentials.readRecord(X)),m=p.accounts.find(e=>e.id===u.id);if(!m)throw new Q(`ChatGPT registration was removed during sign-in. Please retry.`);if(e.method===`oauth`){if(m.clientId!==u.clientId||s!==void 0&&m.subject!==l||s!==void 0&&m.tokens?.access!==c)throw new Q(`ChatGPT account changed during sign-in. Please retry.`);Object.assign(m,u),delete m.pending}else if(!m.tokens||m.tokens.access!==d)throw new Q(`ChatGPT account changed while switching. Please retry.`);m.models=f,p.activeId=u.id,p.welcomed=!0,await e.commit({kind:`grant`,payload:p}),await this.syncAdapter(),e.notify({message:`Using ChatGPT plan. Manage usage`,url:Qn})}dispose(){this.current?.controller.abort(),this.current?.phase===`running`&&this.ctx.authorization.cancel(X)}enqueue(e){let t=this.operations.then(e,e);return this.operations=t.then(()=>void 0,()=>void 0),t}notify(e,t){e.phase===`running`&&(e.notice={message:t.message,...t.url?{url:t.url}:{}})}prompt(e,t){return t.kind===`select`?e.pending?Promise.reject(new Q(`A sign-in question is already open.`)):new Promise((n,r)=>{let i=()=>{e.pending=void 0,t.signal?.removeEventListener(`abort`,a)},a=()=>{i(),r(new Q(`Sign-in prompt was withdrawn.`))};e.pending={prompt:t,resolve:e=>{i(),n(e)}},t.signal?.addEventListener(`abort`,a,{once:!0}),t.signal?.aborted&&a()}):Promise.reject(new Q(`This sign-in step does not accept typed input.`))}projectAttempt(e){return{id:e.id,method:e.method,phase:e.phase,...e.notice?{notice:e.notice}:{},...e.pending?{prompt:{kind:`select`,message:e.pending.prompt.message,options:e.pending.prompt.options.map(({id:e,label:t})=>({id:e,label:t}))}}:{},...e.error?{error:e.error}:{}}}};const _r=/(?:^|-)(?:image|tts|transcribe|realtime|audio|embedding)(?:-|$)/i,vr=/* @__PURE__ */ new Set([`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`]);function yr(e){return e.startsWith(`gpt-`)&&!_r.test(e)}function br(e){return e===`text`||e===`image`}function xr(e,t){let n=t.get(e);if(n)return n;let r=[...t.values()].filter(e=>yr(e.id)&&e.api===`openai-responses`&&e.reasoning),i=(e,t)=>t.id.localeCompare(e.id,void 0,{numeric:!0}),a=e.match(/-([a-z]+)$/i)?.[1]?.toLowerCase(),o=a?r.filter(e=>e.id.toLowerCase().endsWith(`-${a}`)):[];if(o.sort(i),o[0])return o[0];let s=e.match(/^gpt-(\d+)/)?.[1],c=s?r.filter(e=>RegExp(`^gpt-${s}(?:[.-]|$)`).test(e.id)):[];return c.sort(i),c[0]?c[0]:r.sort((e,t)=>t.contextWindow-e.contextWindow||i(e,t))[0]}function Sr(e){return yr(e.id)&&e.supportedInApi===!0&&e.contextWindow!==void 0&&e.input?.includes(`text`)===!0}function Cr(e){if(e===void 0||!e.some(e=>vr.has(e)))return;let t=new Set(e);return{off:t.has(`none`)?`none`:null,minimal:t.has(`minimal`)?`minimal`:null,low:t.has(`low`)?`low`:null,medium:t.has(`medium`)?`medium`:null,high:t.has(`high`)?`high`:null,xhigh:t.has(`xhigh`)?`xhigh`:null,max:t.has(`max`)?`max`:null}}function wr(e,t){let n=ne(),r=new Map(n.getModels().map(e=>[e.id,e])),i=(t?.models??[]).flatMap(t=>{if(t.supportedInApi===!1||_r.test(t.id))return[];let n=r.get(t.id);if(!n&&!Sr(t))return e.logger.warn(`Skipping ChatGPT model %s: missing SIWC chat capabilities.`,t.id),[];let i=xr(t.id,r);if(!i)return e.logger.warn(`Skipping ChatGPT model %s: no pi-ai template.`,t.id),[];let a=t.input===void 0?i.input:t.input.filter(br);if(!a.includes(`text`))return e.logger.warn(`Skipping ChatGPT model %s: no supported text input.`,t.id),[];let o=t.contextWindow??(n?i.contextWindow:void 0);return o===void 0?(e.logger.warn(`Skipping ChatGPT model %s: missing SIWC context window.`,t.id),[]):(n||e.logger.info(`Synthesizing ChatGPT model %s from template %s`,t.id,i.id),[{id:t.id,name:t.name,api:`openai-responses`,provider:`openai`,baseUrl:K,input:a,cost:i.cost,reasoning:t.reasoningEfforts===void 0?!!(n&&i.reasoning):t.reasoningEfforts.some(e=>vr.has(e)),thinkingLevelMap:t.reasoningEfforts===void 0&&n?i.thinkingLevelMap:Cr(t.reasoningEfforts),contextWindow:o,maxTokens:i.maxTokens,...i.compat?{compat:i.compat}:{}}])});return/* @__PURE__ */ new Map([[`openai`,{provider:`openai`,displayName:`ChatGPT Subscription Plan`,...t?{accountId:t.id}:{},piProvider:{...n,getModels:()=>i,getAllModels:()=>i},streamIdleTimeoutMs:3e5,maxRequestImageBytes:20971520,requestImagePixelBudget:4194304,requestImageMaxBytes:1048576,retryPolicy:h(void 0,`siwc`),modelErrors:/* @__PURE__ */ new Map,configuredMaxTokens:/* @__PURE__ */ new Map}]])}var Tr=class extends b{ctx;accounts;currentProfiles;options;constructor(e,t){let n={value:wr(e),stamp:``},r={profiles:()=>n.value,resolveApiKey:(e,n)=>t.accessToken(n.accountId),auth:{credentials:new x,authContext:te()},resolveAttachments:()=>e.get(`attachments`),resolveImageAccess:(t,n)=>m(t,t=>e.get(`fs`)?.processPathFromHostPath(t),n)};super(r),this.ctx=e,this.options=r,this.accounts=t,this.currentProfiles=n}async sync(){let e=await this.accounts.read(),t=e.accounts.find(t=>t.id===e.activeId),n=JSON.stringify([t?.id,t?.email,t?.models]);n!==this.currentProfiles.stamp&&(this.currentProfiles.value=wr(this.ctx,t),this.currentProfiles.stamp=n)}async listModels(e){return await this.sync(),super.listModels(e)}async resolveModel(e,t,n){return await this.sync(),super.resolveModel(e,t,n)}async prepareCall(e,t,n){await this.sync();let r=this.currentProfiles.value,i=r.get(e)?.accountId,a,o=await new b({...this.options,profiles:()=>r,resolveApiKey:async()=>(a=await this.accounts.accessToken(i),a)}).prepareCall(e,t,n);return{model:o.model,stream:e=>this.recoverAuth(o.stream(e),i,()=>a)}}async*recoverAuth(e,t,n){let r=!1,i=async e=>{let i=n();t&&i&&/\b401\b|subscription_sharing_invalid_user/.test(e)&&(r=!0,await this.accounts.accessToken(t,i))};try{for await(let t of e)t.type===`finish`&&t.reason.kind===`error`&&await i(t.reason.failure.message),yield t}catch(e){throw!r&&e instanceof Error&&await i(e.message),e}}async*stream(e){yield*(await this.prepareCall(e.provider,e.model,e.signal)).stream(e)}};function Er(e){try{let t=new URL(e);if((t.protocol===`https:`||t.protocol===`http:`)&&!t.username&&!t.password)return t.href}catch{}}function Dr(e){return e.replace(/[\\[\]]/g,`\\$&`)}function Or(e){return e.replace(/</g,`%3C`).replace(/>/g,`%3E`)}function kr(e){let t=e.filter(e=>e.type===`web_search_call`);if(!t.some(e=>e.status===`completed`&&e.action.type===`search`))throw new S(`ChatGPT did not complete a web search.`,`SIWC_SEARCH_NOT_EXECUTED`);let n=/* @__PURE__ */ new Map,r=(e,t)=>{let r=Er(e);if(!r)return;let i=n.get(r);return n.set(r,{url:r,...i?.title||t?{title:i?.title||t}:{}}),r};for(let e of t)if(e.status===`completed`&&e.action.type===`search`)for(let t of e.action.sources??[])r(t.url);let i=[];for(let t of e)if(t.type===`message`)for(let e of t.content){if(e.type!==`output_text`)continue;let t=e.annotations.filter(e=>e.type===`url_citation`),n=``,a=0;for(let i of t.toSorted((e,t)=>e.start_index-t.start_index)){let t=r(i.url,i.title),{start_index:o,end_index:s}=i;if(!t||!Number.isInteger(o)||!Number.isInteger(s)||o<a||s<=o||s>e.text.length)continue;n+=e.text.slice(a,o);let c=e.text.slice(o,s),l=i.title&&/^(\[\d+\]|.*)$/u.test(c)?i.title:c;n+=`[${Dr(l)}](<${Or(t)}>)`,a=s}i.push(n+e.text.slice(a))}return{...i.length?{content:i.join(`
|
|
20
20
|
|
|
21
|
-
`)}:{},sources:[...n.values()],truncated:!1}}function Ar(e,t,n={}){return{id:`siwc`,available:()=>t().trim().length>0,async search(r,i){let a=AbortSignal.timeout(n.timeoutMs??6e4),o=i?AbortSignal.any([i,a]):a,s,c,l,u=(e,t)=>typeof e==`string`&&t.test(e)&&(!l||!e.includes(l))?e:void 0,d=(e,t=c,n=`ChatGPT web search failed.`)=>{let r=u(e,/^[A-Za-z][A-Za-z0-9_]{0,99}$/)??`WEB_PROVIDER_ERROR`;return new S(n,r,{cause:{...t===void 0?{}:{status:t},code:r,...s?{requestId:s}:{}}})};try{o.throwIfAborted();let i=t();if(!i.trim())throw new S(`Select a ChatGPT search model.`,`SIWC_SEARCH_MODEL_UNAVAILABLE`);let a=await e.read();o.throwIfAborted();let f=a.accounts.find(e=>e.id===a.activeId);if(!f?.tokens)throw new S(`Continue with ChatGPT in Settings → SIWC.`,`MISSING_CREDENTIAL`);if(!f.models?.some(e=>e.id===i))throw new S(`The selected search model is not available for this ChatGPT account.`,`SIWC_SEARCH_MODEL_UNAVAILABLE`);l=await e.accessToken(f.id),o.throwIfAborted();let{data:p,request_id:m,response:h}=await new re({apiKey:l,baseURL:`https://api.openai.com/v1`,organization:null,project:null,maxRetries:0,fetch:n.fetch}).responses.create({model:i,store:!1,stream:!0,input:[{role:`user`,content:r.query}],tools:[{type:`web_search`}],tool_choice:`required`,include:[`web_search_call.action.sources`]},{signal:o}).withResponse();s=u(m,/^[A-Za-z0-9_-]{1,200}$/),c=h.status;let g,_=/* @__PURE__ */ new Map;for await(let e of p){if(o.throwIfAborted(),e.type===`error`)throw d(e.code);if(e.type===`response.failed`)throw d(e.response.error?.code);if(e.type===`response.incomplete`)throw d(`SIWC_SEARCH_INCOMPLETE`);if(e.type===`response.output_item.done`&&_.set(e.output_index,e.item),e.type===`response.completed`){if(e.response.status!==`completed`)throw d(`SIWC_SEARCH_INCOMPLETE`);g=e.response}}if(o.throwIfAborted(),!g)throw d(`SIWC_SEARCH_INCOMPLETE`);return kr(g.output.length?g.output:[..._].sort(([e],[t])=>e-t).map(([,e])=>e))}catch(e){throw o.aborted?d(i?.aborted?`WEB_ABORTED`:`WEB_TIMEOUT`,c,i?.aborted?`ChatGPT web search was cancelled.`:`ChatGPT web search timed out.`):e instanceof S?e:e instanceof re.APIError?(s=u(e.requestID,/^[A-Za-z0-9_-]{1,200}$/)??s,d(e.code,e.status)):d(e instanceof Error&&`code`in e?e.code:void 0)}}}}function jr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Mr(e){return jr(e)&&Object.keys(e).length===0}function $(e){return{ok:!1,error:{code:`invalid-input`,message:e,details:{}}}}async function Nr(e,t,n,r,i){i.throwIfAborted();try{return n===`status`?Mr(r)?{ok:!0,value:await t.status()}:$(`SIWC status takes no parameters.`):n===`authorize`?!jr(r)||r.method!==`oauth`&&r.method!==`select`||r.accountId!==void 0&&(typeof r.accountId!=`string`||!r.accountId)||Object.keys(r).some(e=>e!==`method`&&e!==`accountId`)?$(`Choose a valid SIWC authorization method.`):{ok:!0,value:await t.authorize(r.method,r.accountId)}:n===`answer`?!jr(r)||Object.keys(r).length!==2||typeof r.attemptId!=`string`||!r.attemptId||typeof r.choice!=`string`||!r.choice?$(`Choose one of the available sign-in options.`):{ok:!0,value:await t.answer(r.choice,r.attemptId)}:n===`cancel`?!jr(r)||Object.keys(r).length!==1||typeof r.attemptId!=`string`||!r.attemptId?$(`Choose an active SIWC sign-in attempt.`):{ok:!0,value:await t.cancel(r.attemptId)}:n===`logout`?Mr(r)?{ok:!0,value:await t.logout()}:$(`SIWC logout takes no parameters.`):$(`Unknown SIWC Settings action.`)}catch(t){let r=hr(t);return e.logger.warn(`SIWC Settings action %s failed: %s`,n,r),{ok:!1,error:{code:`siwc/action-failed`,message:r,details:{}}}}}function Pr(e,t){for(let n of[`status`,`authorize`,`answer`,`cancel`,`logout`])e.connection.fetch.register({path:`/api/siwc/${n}`,methods:[`POST`],requestBody:`buffered`,async fetch(r){if(r.headers.get(`content-type`)?.split(`;`,1)[0]?.trim()!==`application/json`)return new Response(`Expected application/json`,{status:415});let i;try{i=await r.json()}catch{return new Response(`Invalid JSON`,{status:400})}let a=ie.safeParse(i);if(!a.success||a.data.method!==`siwc/${n}`)return new Response(`Invalid SIWC request`,{status:400});let{rpcId:o,payload:s}=a.data,c=await Nr(e,t,n,s,r.signal);return Response.json({type:`server-response`,rpcId:o,result:c},{headers:{"cache-control":`no-store`}})}})}const Fr=`siwc`,Ir=[`credentials`,`authorization`,`llm`],Lr=t.object({searchModel:t.string().default(``).volatile()}),Rr=[`0.2.1-rc.2`,`0.2.2-alpha.2`,`0.2.2-alpha.3`,`0.2.2-rc.5`];async function zr(e,t){let n=await t.read(),r=n.accounts.find(e=>e.id===n.activeId);if(!r?.tokens)return;let i,a;try{i=await t.accessToken(r.id),a=await cr(i)}catch(t){if(!(t instanceof $n)&&!(t instanceof er)&&!(t instanceof q))throw t;e.logger.warn(`Could not refresh ChatGPT models at startup; keeping the saved catalog: %s`,t.message);return}await t.change(e=>{let t=e.accounts.find(e=>e.id===r.id);t?.tokens?.access===i&&(t.models=a)})}async function Br(t,n){let r=e();Rr.includes(r)||t.logger.warn(`dsh-siwc expects DSH %s; running %s. Compatibility is unverified; continuing.`,Rr.join(`, `),r);let i=new mr(t.credentials)
|
|
21
|
+
`)}:{},sources:[...n.values()],truncated:!1}}function Ar(e,t,n={}){return{id:`siwc`,available:()=>t().trim().length>0,async search(r,i){let a=AbortSignal.timeout(n.timeoutMs??6e4),o=i?AbortSignal.any([i,a]):a,s,c,l,u=(e,t)=>typeof e==`string`&&t.test(e)&&(!l||!e.includes(l))?e:void 0,d=(e,t=c,n=`ChatGPT web search failed.`)=>{let r=u(e,/^[A-Za-z][A-Za-z0-9_]{0,99}$/)??`WEB_PROVIDER_ERROR`;return new S(n,r,{cause:{...t===void 0?{}:{status:t},code:r,...s?{requestId:s}:{}}})};try{o.throwIfAborted();let i=t();if(!i.trim())throw new S(`Select a ChatGPT search model.`,`SIWC_SEARCH_MODEL_UNAVAILABLE`);let a=await e.read();o.throwIfAborted();let f=a.accounts.find(e=>e.id===a.activeId);if(!f?.tokens)throw new S(`Continue with ChatGPT in Settings → SIWC.`,`MISSING_CREDENTIAL`);if(!f.models?.some(e=>e.id===i))throw new S(`The selected search model is not available for this ChatGPT account.`,`SIWC_SEARCH_MODEL_UNAVAILABLE`);l=await e.accessToken(f.id),o.throwIfAborted();let{data:p,request_id:m,response:h}=await new re({apiKey:l,baseURL:`https://api.openai.com/v1`,organization:null,project:null,maxRetries:0,fetch:n.fetch}).responses.create({model:i,store:!1,stream:!0,input:[{role:`user`,content:r.query}],tools:[{type:`web_search`}],tool_choice:`required`,include:[`web_search_call.action.sources`]},{signal:o}).withResponse();s=u(m,/^[A-Za-z0-9_-]{1,200}$/),c=h.status;let g,_=/* @__PURE__ */ new Map;for await(let e of p){if(o.throwIfAborted(),e.type===`error`)throw d(e.code);if(e.type===`response.failed`)throw d(e.response.error?.code);if(e.type===`response.incomplete`)throw d(`SIWC_SEARCH_INCOMPLETE`);if(e.type===`response.output_item.done`&&_.set(e.output_index,e.item),e.type===`response.completed`){if(e.response.status!==`completed`)throw d(`SIWC_SEARCH_INCOMPLETE`);g=e.response}}if(o.throwIfAborted(),!g)throw d(`SIWC_SEARCH_INCOMPLETE`);return kr(g.output.length?g.output:[..._].sort(([e],[t])=>e-t).map(([,e])=>e))}catch(e){throw o.aborted?d(i?.aborted?`WEB_ABORTED`:`WEB_TIMEOUT`,c,i?.aborted?`ChatGPT web search was cancelled.`:`ChatGPT web search timed out.`):e instanceof S?e:e instanceof re.APIError?(s=u(e.requestID,/^[A-Za-z0-9_-]{1,200}$/)??s,d(e.code,e.status)):d(e instanceof Error&&`code`in e?e.code:void 0)}}}}function jr(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Mr(e){return jr(e)&&Object.keys(e).length===0}function $(e){return{ok:!1,error:{code:`invalid-input`,message:e,details:{}}}}async function Nr(e,t,n,r,i){i.throwIfAborted();try{return n===`status`?Mr(r)?{ok:!0,value:await t.status()}:$(`SIWC status takes no parameters.`):n===`authorize`?!jr(r)||r.method!==`oauth`&&r.method!==`select`||r.accountId!==void 0&&(typeof r.accountId!=`string`||!r.accountId)||Object.keys(r).some(e=>e!==`method`&&e!==`accountId`)?$(`Choose a valid SIWC authorization method.`):{ok:!0,value:await t.authorize(r.method,r.accountId)}:n===`answer`?!jr(r)||Object.keys(r).length!==2||typeof r.attemptId!=`string`||!r.attemptId||typeof r.choice!=`string`||!r.choice?$(`Choose one of the available sign-in options.`):{ok:!0,value:await t.answer(r.choice,r.attemptId)}:n===`cancel`?!jr(r)||Object.keys(r).length!==1||typeof r.attemptId!=`string`||!r.attemptId?$(`Choose an active SIWC sign-in attempt.`):{ok:!0,value:await t.cancel(r.attemptId)}:n===`logout`?Mr(r)?{ok:!0,value:await t.logout()}:$(`SIWC logout takes no parameters.`):$(`Unknown SIWC Settings action.`)}catch(t){let r=hr(t);return e.logger.warn(`SIWC Settings action %s failed: %s`,n,r),{ok:!1,error:{code:`siwc/action-failed`,message:r,details:{}}}}}function Pr(e,t){for(let n of[`status`,`authorize`,`answer`,`cancel`,`logout`])e.connection.fetch.register({path:`/api/siwc/${n}`,methods:[`POST`],requestBody:`buffered`,async fetch(r){if(r.headers.get(`content-type`)?.split(`;`,1)[0]?.trim()!==`application/json`)return new Response(`Expected application/json`,{status:415});let i;try{i=await r.json()}catch{return new Response(`Invalid JSON`,{status:400})}let a=ie.safeParse(i);if(!a.success||a.data.method!==`siwc/${n}`)return new Response(`Invalid SIWC request`,{status:400});let{rpcId:o,payload:s}=a.data,c=await Nr(e,t,n,s,r.signal);return Response.json({type:`server-response`,rpcId:o,result:c},{headers:{"cache-control":`no-store`}})}})}const Fr=`siwc`,Ir=[`credentials`,`authorization`,`llm`],Lr=t.object({searchModel:t.string().default(``).volatile()}),Rr=[`0.2.1-rc.2`,`0.2.2-alpha.2`,`0.2.2-alpha.3`,`0.2.2-rc.5`];async function zr(e,t){let n=await t.read(),r=n.accounts.find(e=>e.id===n.activeId);if(!r?.tokens)return;let i,a;try{i=await t.accessToken(r.id),a=await cr(i)}catch(t){if(!(t instanceof $n)&&!(t instanceof er)&&!(t instanceof q))throw t;e.logger.warn(`Could not refresh ChatGPT models at startup; keeping the saved catalog: %s`,t.message);return}await t.change(e=>{let t=e.accounts.find(e=>e.id===r.id);t?.tokens?.access===i&&(t.models=a)})}async function Br(t,n){let r=e();Rr.includes(r)||t.logger.warn(`dsh-siwc expects DSH %s; running %s. Compatibility is unverified; continuing.`,Rr.join(`, `),r);let i=new mr(t.credentials),a=new Tr(t,i);t.llm.registerAdapter([`openai`],a),t.inject([`web`],e=>{e.web.registerSearchProvider(Ar(i,()=>n.searchModel.get()))});let o=new gr(t,i,()=>a.sync());t.effect(()=>()=>o.dispose()),t.inject([`connection`],e=>Pr(e,o)),t.inject([`settings`],e=>{e.effect(()=>e.settings.configure({auto:!1},t.fiber))}),t.effect(()=>t.authorization.registerFlow({key:X,label:`ChatGPT plan`,methods:[{id:`oauth`,label:`Continue with ChatGPT`},{id:`select`,label:`Switch saved account`}],run:e=>o.authorizeSession(e)})),await zr(t,i),await a.sync()}export{Lr as Config,Br as apply,Ir as inject,Fr as name};
|
package/package.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-siwc",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.6",
|
|
4
4
|
"description": "Sign in with ChatGPT for DeepSeek Harness",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"dsh",
|
|
7
7
|
"deepseek-harness"
|
|
8
8
|
],
|
|
9
|
-
"homepage": "https://github.com/ph0ryn/dsh-plugins#readme",
|
|
9
|
+
"homepage": "https://github.com/ph0ryn/dsh-plugins/tree/main/packages/siwc#readme",
|
|
10
10
|
"bugs": {
|
|
11
11
|
"url": "https://github.com/ph0ryn/dsh-plugins/issues"
|
|
12
12
|
},
|