@native-engagement/cli 0.0.0-stage → 0.8.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/README.md CHANGED
@@ -1,3 +1,24 @@
1
- # Temporary Holding Version
1
+ # Native Engagement CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Node.js 24.22.1+ (24 LTS) command line access to the same authenticated Native Engagement HTTPS contracts.
4
+
5
+ ```sh
6
+ npm install -g @native-engagement/cli@beta
7
+ native-engagement --help
8
+ native-engagement --version
9
+ native-engagement login
10
+ native-engagement auth status
11
+ npx @native-engagement/cli@beta contracts list
12
+ ```
13
+
14
+ The default service is https://engagement.shipkitx.com. Override it with NATIVE_ENGAGEMENT_API_URL when using your own trusted center. Interactive login uses your system browser and a dedicated public PKCE client. It requests only engagement read/write, work read, asset read and message draft; it does not request Desktop installation or identity administration. The service still intersects each request with your current tenant permissions. Privileged automation uses its separately authorized short-lived machine grant. The saved access grant is short-lived: it uses a private current-user file on macOS/Linux and current-user DPAPI protection on Windows. Run login again after expiry; refresh tokens are not persisted. Use `native-engagement logout` to revoke and remove the grant. For noninteractive protected queries and commands, supply NATIVE_ENGAGEMENT_BEARER_TOKEN through the host's protected process environment. It is a short-lived authorized access token, not an npm token. No credential or principal override is accepted in command arguments.
15
+
16
+ ```sh
17
+ native-engagement schema get conversation.list
18
+ native-engagement query conversation.list --input @request.json
19
+ native-engagement command <contract-name> --input @command.json
20
+ ```
21
+
22
+ Read each contract schema before supplying input. Commands require a stable idempotencyKey. Results are JSON: exit 0 for success, 2 for rejected input/access, 1 for service failures. An unknown physical effect must be checked through its original operation and must not be retried as a new send.
23
+
24
+ This client does not initialize a second local business database or start an execution Node. Desktop and its local channel authorization have their own installation flow. The beta is distributed with license `UNLICENSED`. Documentation: https://engagement.shipkitx.com/downloads
@@ -0,0 +1,50 @@
1
+ oauth4webapi@3.8.8
2
+
3
+ The MIT License (MIT)
4
+
5
+ Copyright (c) 2022 Filip Skokan
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
24
+
25
+
26
+ ---
27
+
28
+ openid-client@6.8.7
29
+
30
+ The MIT License (MIT)
31
+
32
+ Copyright (c) 2016 Filip Skokan
33
+
34
+ Permission is hereby granted, free of charge, to any person obtaining a copy
35
+ of this software and associated documentation files (the "Software"), to deal
36
+ in the Software without restriction, including without limitation the rights
37
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
38
+ copies of the Software, and to permit persons to whom the Software is
39
+ furnished to do so, subject to the following conditions:
40
+
41
+ The above copyright notice and this permission notice shall be included in all
42
+ copies or substantial portions of the Software.
43
+
44
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
45
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
46
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
47
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
48
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
49
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
50
+ SOFTWARE.
package/dist/index.js ADDED
@@ -0,0 +1,31 @@
1
+ #!/usr/bin/env node
2
+ import ve from"node:fs";var st=e=>e==="execution.node.media.output.report"?524288:e?.startsWith("execution.node.")&&!["execution.node.report.append","execution.node.execution.report.append","execution.node.social.report.append","execution.node.social.selection.preview.append","execution.node.bridge.report.append","execution.node.recovery.evidence.append"].includes(e)?65536:e==="work.invocation.request"?2097152:1048576;function xe(e){return e==="SEND_BUDGET_EXHAUSTED"?{retryable:!0,hint:"WAIT_FOR_ACCOUNT_BUDGET_AND_RETRY_SAME_KEY"}:e==="SEND_GATE_DISABLED"?{retryable:!1,hint:"REQUIRE_ACCOUNT_OWNER_TO_ENABLE_SENDING"}:e==="SEND_RESERVATION_REQUIRED"?{retryable:!1,hint:"CANCEL_AND_REVIEW_A_NEW_RESERVED_INTENT"}:["AUTH_VERIFICATION_UNAVAILABLE","AGENT_STACK_AUTHORITY_UNAVAILABLE","REDIS_RATE_LIMIT_UNAVAILABLE","SERVICE_NOT_CONFIGURED","RATE_LIMIT_EXCEEDED"].includes(e)?{retryable:!0,hint:"WAIT_AND_RETRY_SAME_IDEMPOTENCY_KEY"}:["AUTH_TOKEN_EXPIRED","AUTHENTICATION_REQUIRED","AUTH_TOKEN_REVOKED"].includes(e)?{retryable:!1,hint:"REAUTHENTICATE_AND_RECHECK_CURRENT_AUTHORITY"}:["ENTITY_CONFLICT","SEARCH_CURSOR_STALE","HOST_INBOX_CURSOR_STALE"].includes(e)?{retryable:!1,hint:"READ_CURRENT_STATE_AND_REPLAN"}:e==="IDEMPOTENCY_CONFLICT"?{retryable:!1,hint:"RESTORE_ORIGINAL_INPUT_FOR_KEY"}:["HOST_EXECUTION_FAILED","HOST_BRIDGE_UNAVAILABLE"].includes(e)?{retryable:!1,hint:"VERIFY_KNOWN_OPERATION_BEFORE_ANY_SEND"}:e==="SUPPRESSED"?{retryable:!1,hint:"STOP_CONTACT_AND_REQUIRE_HUMAN_REVIEW"}:e.startsWith("AUTH")||e==="TENANT_NOT_PROVISIONED"?{retryable:!1,hint:"REQUIRE_OPERATOR_AUTHORITY_REVIEW"}:{retryable:!1,hint:"FIX_INPUT_OR_INSPECT_STATE_BEFORE_RETRY"}}var N=class extends Error{code;statusCode;details;constructor(t,n,r,o={}){super(n),this.code=t,this.statusCode=r,this.details=o,this.name="NativeEngagementError"}};function it(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new N("VALIDATION_FAILED",`${t} must be an object.`,400,{field:t});return e}function Ce(e){let t=it(e??{},"payload"),n=t.idempotencyKey;if(typeof n!="string"||!n.trim()||n.length>1024*1024)throw new N("VALIDATION_FAILED","Every command requires a bounded idempotencyKey.",400,{field:"idempotencyKey"});return t}async function ct(e,t=2*1024*1024){if(Number(e.headers.get("content-length"))>t||!e.body)throw Error("NODE_REMOTE_RESPONSE_TOO_LARGE");let n=e.body.getReader(),r=[],o=0;try{for(;;){let i=await n.read();if(i.done)break;if(o+=i.value.byteLength,o>t)throw Error("NODE_REMOTE_RESPONSE_TOO_LARGE");r.push(i.value)}let s=new Uint8Array(o),a=0;for(let i of r)s.set(i,a),a+=i.byteLength;return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(s))}finally{await n.cancel().catch(()=>{}),n.releaseLock()}}var S=class extends Error{code;status;details;retryable;hint;retryAfterSeconds;reasonCode;constructor(t,n,r,o={}){super(n),this.code=t,this.status=r,this.details=o,this.name="RemoteNativeEngagementError";let s=xe(t);this.retryable=s.retryable,this.hint=s.hint;let a=o.retryAfterSeconds,i=o.reasonCode;this.retryAfterSeconds=Number.isInteger(a)&&Number(a)>=0&&Number(a)<=3600?Number(a):void 0,this.reasonCode=typeof i=="string"&&/^[A-Z][A-Z_]{1,120}$/.test(i)?i:void 0}};function hn(e){let t;try{t=new URL(e)}catch{throw new Error("Invalid native-engagement service URL.")}let n=t.hostname==="127.0.0.1"||t.hostname==="localhost"||t.hostname==="[::1]";if(!(t.protocol==="https:"||t.protocol==="http:"&&n)||t.username||t.password||t.search||t.hash||t.pathname!=="/")throw new Error("native-engagement requires HTTPS or HTTP loopback without URL credentials.");return t.origin}var le=class{#o;#a;#s;#n;#t;#r;constructor(t){if(this.#o=hn(t.baseUrl),this.#a=t.accessToken,this.#s=t.fetchImpl??fetch,this.#r=t.tenantId,this.#n=t.nodeProof,this.#t=t.maximumResponseBytes??16*1024*1024,!Number.isSafeInteger(this.#t)||this.#t<1024||this.#t>64*1024*1024)throw Error("Invalid maximum JSON response size.")}async#e(t,n,r,o=!0,s=3e4,a){let i={accept:"application/json","content-type":"application/json"};if(o){let d=await this.#a();if(!/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(d))throw new S("AUTHENTICATION_REQUIRED","An access token is required for the remote operation.",401);i.authorization=`Bearer ${d}`,this.#r&&(i["x-tenant-id"]=this.#r)}this.#n&&/^\/v1\/(query|command)\/execution\.node\./.test(n)&&(i["x-execution-node-proof"]=Buffer.from(JSON.stringify(this.#n(t,n,r??{}))).toString("base64url"));let c=await this.#s(`${this.#o}${n}`,{method:t,headers:i,...t==="POST"?{body:JSON.stringify(r??{})}:{},redirect:"error",signal:a?AbortSignal.any([a,AbortSignal.timeout(s)]):AbortSignal.timeout(s)}),u;try{u=await ct(c,this.#n&&n.includes("/execution.node.")?2*1024*1024:this.#t)}catch{throw new S("REMOTE_RESPONSE_INVALID","The service did not return valid JSON.",c.status)}if(!c.ok){let d=u&&typeof u=="object"&&"error"in u?u.error:void 0;throw new S(d?.code??"REMOTE_REQUEST_FAILED",d?.message??"The native-engagement service rejected the request.",c.status,d?.details&&typeof d.details=="object"&&!Array.isArray(d.details)?d.details:{})}return u}contracts(){return this.#e("GET","/v1/contracts",void 0,!1)}schema(t){return this.#e("GET",`/v1/contracts/${encodeURIComponent(t)}`,void 0,!1)}query(t,n){let r=["channel.status.inspect","profile.host.inspect","wechat.session.inspect","wechat.thread.observe","browser.session.inspect","browser.thread.observe"].includes(t.name)?12e4:3e4;return this.#e("POST",`/v1/query/${encodeURIComponent(t.name)}`,t.payload,!0,r,n)}command(t,n){try{Ce(t.payload)}catch{throw new S("VALIDATION_FAILED","Every command requires a bounded idempotencyKey.",400)}let r=["conversation.source.sync","conversation.source.rebase","wechat.conversation.sync","wechat.thread.link","wechat.watch.resume"].includes(t.name)||t.name==="asset.speech.synthesize"?12e4:["message.text.execute","message.text.verify","wechat.message.execute","wechat.message.verify"].includes(t.name)?18e4:["asset.parse","message.attachment.capture","work.content.prepare","work.mail.content.prepare","work.source.content.prepare"].includes(t.name)?2e5:3e4;return this.#e("POST",`/v1/command/${encodeURIComponent(t.name)}`,t.payload,!0,r,n)}search(t){return this.#e("POST","/v1/search",t)}enquiry(t){return this.#e("POST","/v1/enquiry",t)}agentStackPreflight(t){return this.#e("POST","/v1/integrations/agent-stack/preflight",t)}};function De(e,t){let n=e.indexOf(t);return n<0?void 0:e[n+1]}function Y(e){let t=De(e,"--input-json"),n=De(e,"--input");if(t&&n)throw new Error("Use either --input-json or --input.");let r=st(e[0]==="command"?e[1]:void 0),o={};if(n){let s=n.startsWith("@")?n.slice(1):n,a=ve.openSync(s,"r"),i=Buffer.alloc(r+1);try{let c=0,u=0;do u=ve.readSync(a,i,c,i.length-c,null),c+=u;while(u>0&&c<i.length);if(c>r)throw new Error("Input exceeds its command limit.");o=JSON.parse(i.subarray(0,c).toString("utf8"))}finally{ve.closeSync(a)}}else if(t){if(Buffer.byteLength(t)>r)throw new Error("Input exceeds its command limit.");o=JSON.parse(t)}if(!o||Array.isArray(o)||typeof o!="object")throw new Error("Input must be a JSON object.");return o}function ln(e){return["--principal","--actor","--scope","--token","--authorization"].some(t=>e.includes(t))}async function ut(e,t=r=>console.log(r),n=process.env){try{if(ln(e))throw new S("AUTH_CONTEXT_OVERRIDE_FORBIDDEN","Principal, actor, scopes and tokens cannot be supplied as CLI arguments.",403);let r=n.NATIVE_ENGAGEMENT_API_URL;if(!r)throw new S("SERVICE_NOT_CONFIGURED","NATIVE_ENGAGEMENT_API_URL must identify an authenticated service.",503);let o=De(e,"--tenant"),s=new le({baseUrl:r,accessToken:()=>n.NATIVE_ENGAGEMENT_BEARER_TOKEN??"",...o?{tenantId:o}:{}}),a;if(e[0]==="contracts"&&e[1]==="list")a=await s.contracts();else if(e[0]==="schema"&&e[1]==="get"&&e[2])a=await s.schema(e[2]);else if(e[0]==="search")a=await s.search(Y(e));else if(e[0]==="enquiry")a=await s.enquiry(Y(e));else if(e[0]==="agent-stack-preflight")a=await s.agentStackPreflight(Y(e));else if(e[0]==="query"&&e[1])a=await s.query({name:e[1],payload:Y(e)});else if(e[0]==="command"&&e[1])a=await s.command({name:e[1],payload:Y(e)});else throw new S("VALIDATION_FAILED","Commands: contracts list, schema get <name>, query <name>, command <name>.",400);return t(JSON.stringify(a)),0}catch(r){let o=r instanceof S?{code:r.code,message:r.message,retryable:r.retryable,hint:r.hint}:{code:"CLI_REQUEST_FAILED",message:"CLI input or service request failed.",retryable:!1,hint:"FIX_INPUT_OR_INSPECT_STATE_BEFORE_RETRY"};return t(JSON.stringify({ok:!1,error:o})),r instanceof S&&r.status<500?2:1}}import{readFile as Er}from"node:fs/promises";import{execFile as _r}from"node:child_process";var Ue;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Ue="oauth4webapi/v3.8.8");function ne(e,t){if(e==null)return!1;try{return e instanceof t||Object.getPrototypeOf(e)[Symbol.toStringTag]===t.prototype[Symbol.toStringTag]}catch{return!1}}var g="ERR_INVALID_ARG_VALUE",I="ERR_INVALID_ARG_TYPE";function w(e,t,n){let r=new TypeError(e,{cause:n});return Object.assign(r,{code:t}),r}var v=Symbol(),_e=Symbol(),Ee=Symbol(),D=Symbol();var W=Symbol(),x=Symbol(),fn=new TextEncoder,pn=new TextDecoder;function Q(e){return typeof e=="string"?fn.encode(e):pn.decode(e)}var je;Uint8Array.prototype.toBase64?je=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0})):je=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));let n=[];for(let r=0;r<t.byteLength;r+=32768)n.push(String.fromCharCode.apply(null,t.subarray(r,r+32768)));return btoa(n.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};var He;Uint8Array.fromBase64?He=e=>{try{return Uint8Array.fromBase64(e,{alphabet:"base64url"})}catch(t){throw w("The input to be decoded is not correctly encoded.",g,t)}}:He=e=>{try{let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}catch(t){throw w("The input to be decoded is not correctly encoded.",g,t)}};function K(e){return typeof e=="string"?He(e):je(e)}var y=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=Se,Error.captureStackTrace?.(this,this.constructor)}},Z=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,n?.code&&(this.code=n?.code),Error.captureStackTrace?.(this,this.constructor)}};function h(e,t,n){return new Z(e,{code:t,cause:n})}function H(e){return!(e===null||typeof e!="object"||Array.isArray(e))}function Me(e){ne(e,Headers)&&(e=Object.fromEntries(e.entries()));let t=new Headers(e??{});if(Ue&&!t.has("user-agent")&&t.set("user-agent",Ue),t.has("authorization"))throw w('"options.headers" must not include the "authorization" header name',g);return t}function pt(e,t){if(t!==void 0){if(typeof t=="function"&&(t=t(e.href)),!(t instanceof AbortSignal))throw w('"options.signal" must return or be an instance of AbortSignal',I);return t}}function pe(e,t,n,r,o){try{if(typeof e!="number"||!Number.isFinite(e))throw w(`${n} must be a number`,I,o);if(e>0)return;if(t){if(e!==0)throw w(`${n} must be a non-negative number`,g,o);return}throw w(`${n} must be a positive number`,g,o)}catch(s){throw r?h(s.message,r,o):s}}function _(e,t,n,r){try{if(typeof e!="string")throw w(`${t} must be a string`,I,r);if(e.length===0)throw w(`${t} must not be empty`,g,r)}catch(o){throw n?h(o.message,n,r):o}}function mt(e){wn(e,"application/json")}function wt(e,...t){let n='"response" content-type must be ';if(t.length>2){let r=t.pop();n+=`${t.join(", ")}, or ${r}`}else t.length===2?n+=`${t[0]} or ${t[1]}`:n+=t[0];return h(n,$e,e)}function mn(e,...t){if(!t.includes(ge(e)))throw wt(e,...t)}function wn(e,t){if(ge(e)!==t)throw wt(e,t)}function Ge(){return K(crypto.getRandomValues(new Uint8Array(32)))}function yt(){return Ge()}function _t(){return Ge()}function Et(){return Ge()}async function gt(e){return _(e,"codeVerifier"),K(await crypto.subtle.digest("SHA-256",Q(e)))}function Rt(e){let t=e?.[_e];return typeof t=="number"&&Number.isFinite(t)?t:0}function St(e){let t=e?.[Ee];return typeof t=="number"&&Number.isFinite(t)&&Math.sign(t)!==-1?t:30}function $(){return Math.floor(Date.now()/1e3)}function J(e){if(typeof e!="object"||e===null)throw w('"as" must be an object',I);_(e.issuer,'"as.issuer"')}function re(e){if(typeof e!="object"||e===null)throw w('"client" must be an object',I);_(e.client_id,'"client.client_id"')}function We(e){return _(e,'"clientSecret"'),(t,n,r,o)=>{r.set("client_id",n.client_id),r.set("client_secret",e)}}function At(){return(e,t,n,r)=>{n.set("client_id",t.client_id)}}var yn=URL.parse?(e,t)=>URL.parse(e,t):(e,t)=>{try{return new URL(e,t)}catch{return null}};function bt(e,t){if(t&&e.protocol!=="https:")throw h("only requests to HTTPS are allowed",Be,e);if(e.protocol!=="https:"&&e.protocol!=="http:")throw h("only HTTP and HTTPS requests are allowed",Ye,e)}function dt(e,t,n,r){let o;if(typeof e!="string"||!(o=yn(e)))throw h(`authorization server metadata does not contain a valid ${n?`"as.mtls_endpoint_aliases.${t}"`:`"as.${t}"`}`,e===void 0?Wn:Kn,{attribute:n?`mtls_endpoint_aliases.${t}`:t});return bt(o,r),o}function oe(e,t,n,r){return n&&e.mtls_endpoint_aliases&&t in e.mtls_endpoint_aliases?dt(e.mtls_endpoint_aliases[t],t,n,r):dt(e[t],t,n,r)}function Tt(e){return e instanceof F?e.cause.some(t=>t.scheme==="dpop"&&t.parameters.error==="use_dpop_nonce"):e instanceof V?e.error==="use_dpop_nonce":!1}var V=class extends Error{cause;code;error;status;error_description;response;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=Mn,this.cause=n.cause,this.error=n.cause.error,this.status=n.response.status,this.error_description=n.cause.error_description,Object.defineProperty(this,"response",{enumerable:!1,value:n.response}),Error.captureStackTrace?.(this,this.constructor)}},X=class extends Error{cause;code;error;error_description;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=Gn,this.cause=n.cause,this.error=n.cause.get("error"),this.error_description=n.cause.get("error_description")??void 0,Error.captureStackTrace?.(this,this.constructor)}},F=class extends Error{cause;code;response;status;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=qn,this.cause=n.cause,this.status=n.response.status,this.response=n.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},me="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",_n="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",En='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',gn="("+me+")\\s*=\\s*"+En,Rn="("+me+")\\s*=\\s*("+me+")",Sn=new RegExp("^[,\\s]*("+me+")"),An=new RegExp("^[,\\s]*"+gn+"[,\\s]*(.*)"),bn=new RegExp("^[,\\s]*"+Rn+"[,\\s]*(.*)"),Tn=new RegExp("^("+_n+")(?:$|[,\\s])(.*)");function In(e){if(!ne(e,Response))throw w('"response" must be an instance of Response',I);let t=e.headers.get("www-authenticate");if(t===null)return;let n=[],r=t;for(;r;){let o=r.match(Sn),s=o?.[1].toLowerCase();if(!s)return;let a=r.substring(o[0].length);if(a&&!a.match(/^[\s,]/))return;let i=a.match(/^\s+(.*)$/),c=!!i;r=i?i[1]:void 0;let u={},d;if(c)for(;r;){let m,f;if(o=r.match(An)){[,m,f,r]=o,f.includes("\\")&&(f=f.replace(/\\([\s\S])/g,"$1")),u[m.toLowerCase()]=f;continue}if(o=r.match(bn)){[,m,f,r]=o,u[m.toLowerCase()]=f;continue}if(o=r.match(Tn)){if(Object.keys(u).length)break;[,d,r]=o;break}return}else r=a||void 0;let l={scheme:s,parameters:u};d&&(l.token68=d),n.push(l)}if(n.length)return n}async function Pn(e){if(e.status>399&&e.status<500){Qe(e),mt(e);try{let t=await e.clone().json();if(H(t)&&typeof t.error=="string"&&t.error.length)return t}catch{}}}async function It(e,t,n){if(e.status!==t){Nn(e);let r;throw(r=await Pn(e))?(await e.body?.cancel(),new V("server responded with an error in the response body",{cause:r,response:e})):h(`"response" is not a conform ${n} response (unexpected HTTP status code)`,Ae,e)}}function On(e){if(!Ve.has(e))throw w('"options.DPoP" is not a valid DPoPHandle',g)}var G,fe,Le;function Je(e,t,n,r){G||=new WeakMap,G.set(e,{jwks:t,uat:n,get age(){return $()-this.uat}}),r&&Object.assign(r,{jwks:structuredClone(t),uat:n})}function kn(e){return!(typeof e!="object"||e===null||!("uat"in e)||typeof e.uat!="number"||$()-e.uat>=300||!("jwks"in e)||!H(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,H))}function ht(e,t){G?.delete(e),delete t?.jwks,delete t?.uat}async function ze(e,t,n){let{alg:r,kid:o}=n;Bn(n),!G?.has(e)&&kn(t?.[x])&&Je(e,t?.[x].jwks,t?.[x].uat);let s,a;if(G?.has(e)){if({jwks:s,age:a}=G.get(e),a>=300)return ht(e,t?.[x]),ze(e,t,n)}else{let f=await Vn(e,t);s=f.jwks,a=$()-f.uat,Je(e,s,f.uat,t?.[x])}let i;switch(r.slice(0,2)){case"RS":case"PS":i="RSA";break;case"ES":i="EC";break;case"Ed":i="OKP";break;case"ML":i="AKP";break;default:throw new y("unsupported JWS algorithm",{cause:{alg:r}})}let c=s.keys.filter(f=>{if(f.kty!==i||o!==void 0&&o!==f.kid||f.alg!==void 0&&r!==f.alg||f.use!==void 0&&f.use!=="sig"||f.key_ops?.includes("verify")===!1)return!1;switch(!0){case(r==="ES256"&&f.crv!=="P-256"):case(r==="ES384"&&f.crv!=="P-384"):case(r==="ES512"&&f.crv!=="P-521"):case(r==="Ed25519"&&f.crv!=="Ed25519"):case(r==="EdDSA"&&f.crv!=="Ed25519"):return!1}return!0}),{0:u,length:d}=c;if(!d){if(a>=60)return ht(e,t?.[x]),ze(e,t,n);throw h("error when selecting a JWT verification key, no applicable keys found",lt,{header:n,candidates:c,jwks_uri:new URL(e.jwks_uri)})}if(d!==1)throw h('error when selecting a JWT verification key, multiple applicable keys found, a "kid" JWT Header Parameter is required',lt,{header:n,candidates:c,jwks_uri:new URL(e.jwks_uri)});Le||=new WeakMap;let l=Le.get(u);l||(l=new Map,Le.set(u,l));let m=l.get(r);return m||(m=or(r,u).catch(f=>{throw l.delete(r),f}),l.set(r,m)),m}function ge(e){return e.headers.get("content-type")?.split(";")[0]}async function Pt(e,t,n,r,o,s,a){return await n(e,t,o,s),s.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(a?.[D]||fetch)(r.href,{body:o,headers:Object.fromEntries(s.entries()),method:"POST",redirect:"manual",signal:pt(r,a?.signal)})}async function Ot(e,t,n,r,o,s){let a=oe(e,"token_endpoint",t.use_mtls_endpoint_aliases,s?.[v]!==!0);o.set("grant_type",r);let i=Me(s?.headers);i.set("accept","application/json"),s?.DPoP!==void 0&&(On(s.DPoP),await s.DPoP.addProof(a,i,"POST"));let c=await Pt(e,t,n,a,o,i,s);return s?.DPoP?.cacheNonce(c,a),c}async function kt(e,t,n,r,o){J(e),re(t),_(r,'"refreshToken"');let s=new URLSearchParams(o?.additionalParameters);return s.set("refresh_token",r),Ot(e,t,n,"refresh_token",s,o)}var Nt=new WeakMap,qe=new WeakMap;function Re(e){if(!e.id_token)return;let t=Nt.get(e);if(!t)throw w('"ref" was already garbage collected or did not resolve from the proper sources',g);return t}async function xt(e,t,n){if(J(e),!qe.has(t))throw w('"ref" does not contain a processed JWT Response to verify the signature of',g);let{0:r,1:o,2:s}=qe.get(t).split("."),a=JSON.parse(Q(K(r)));if(a.alg.startsWith("HS"))throw new y("unsupported JWS algorithm",{cause:{alg:a.alg}});let i;i=await ze(e,n,a),await Zn(r,o,i,K(s))}async function Ke(e,t,n,r,o,s){if(J(e),re(t),!ne(n,Response))throw w('"response" must be an instance of Response',I);await It(n,200,"Token Endpoint"),Qe(n);let a=await Kt(n);if(_(a.access_token,'"response" body "access_token" property',p,{body:a}),_(a.token_type,'"response" body "token_type" property',p,{body:a}),a.token_type=a.token_type.toLowerCase(),a.expires_in!==void 0){let i=typeof a.expires_in!="number"?parseFloat(a.expires_in):a.expires_in;pe(i,!0,'"response" body "expires_in" property',p,{body:a}),a.expires_in=i}if(a.refresh_token!==void 0&&_(a.refresh_token,'"response" body "refresh_token" property',p,{body:a}),a.scope!==void 0&&typeof a.scope!="string")throw h('"response" body "scope" property must be a string',p,{body:a});if(a.id_token!==void 0){_(a.id_token,'"response" body "id_token" property',p,{body:a});let i=[];t.require_auth_time===!0&&i.push("auth_time"),t.default_max_age!==void 0&&(pe(t.default_max_age,!0,'"client.default_max_age"'),i.push("auth_time")),r?.length&&i.push(...r);let{claims:c,jwt:u}=await Un(e,t,a.id_token,i,o);Hn(t,c),jn(c),qe.set(n,u),Nt.set(a,c)}if(s?.[a.token_type]!==void 0)s[a.token_type](n,a);else if(a.token_type!=="dpop"&&a.token_type!=="bearer")throw new y("unsupported `token_type` value",{cause:{body:a}});return a}function Nn(e){let t;if(t=In(e))throw new F("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:t,response:e})}async function Ct(e,t,n,r){return Ke(e,t,n,void 0,r?.[W],r?.recognizedTokenTypes)}function xn(e,t){if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e))throw h('unexpected JWT "aud" (audience) claim value',C,{expected:e,claims:t.claims,claim:"aud"})}else if(t.claims.aud!==e)throw h('unexpected JWT "aud" (audience) claim value',C,{expected:e,claims:t.claims,claim:"aud"});return t}function Cn(e,t){let n=e[Ze]?.(t)??e.issuer;if(t.claims.iss!==n)throw h('unexpected JWT "iss" (issuer) claim value',C,{expected:n,claims:t.claims,claim:"iss"});return t}var Ve=new WeakSet;function vn(e){return Ve.add(e),e}var Fe=Symbol();async function vt(e,t,n,r,o,s,a){if(J(e),re(t),!Ve.has(r))throw w('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',g);_(o,'"redirectUri"');let i=j(r,"code");if(!i)throw h('no authorization code in "callbackParameters"',p);let c=new URLSearchParams(a?.additionalParameters);return c.set("redirect_uri",o),c.set("code",i),s!==Fe&&(_(s,'"codeVerifier"'),c.set("code_verifier",s)),Ot(e,t,n,"authorization_code",c,a)}var Dt={aud:"audience",c_hash:"code hash",client_id:"client id",exp:"expiration time",iat:"issued at",iss:"issuer",jti:"jwt id",nonce:"nonce",s_hash:"state hash",sub:"subject",ath:"access token hash",htm:"http method",htu:"http uri",cnf:"confirmation",auth_time:"authentication time"};function Dn(e,t){for(let n of e)if(t.claims[n]===void 0)throw h(`JWT "${n}" (${Dt[n]}) claim missing`,p,{claims:t.claims});return t}function Ln(e,t){if(typeof t.claims[e]!="string")throw h(`unexpected JWT "${e}" (${Dt[e]}) claim type`,p,{claims:t.claims});return t}function Un(e,t,n,r,o){return Xn(n,tr.bind(void 0,t.id_token_signed_response_alg,e.id_token_signing_alg_values_supported,"RS256"),Rt(t),St(t),o).then(Dn.bind(void 0,["aud","exp","iat","iss","sub",...r])).then(Cn.bind(void 0,e)).then(xn.bind(void 0,t.client_id)).then(Ln.bind(void 0,"sub"))}function Lt(e,t){if(t===ye)return t;let n=t===void 0;return n&&(t=e.default_max_age),t===void 0?ye:(pe(t,!0,n?'"client.default_max_age"':'"maxAge" argument'),t)}function jn(e){e.auth_time!==void 0&&pe(e.auth_time,!0,'ID Token "auth_time" (authentication time)',p,{claims:e})}function Ut(e,t,n){if(n===ye)return;let r=$()+Rt(e),o=St(e);if(t.auth_time+n<r-o)throw h("too much time has elapsed since the last End-User authentication",te,{claims:t,now:r,tolerance:o,claim:"auth_time"})}function jt(e,t){let n=t===we?void 0:t;if(e.nonce!==n)throw h('unexpected ID Token "nonce" claim value',C,{expected:n,claims:e,claim:"nonce"})}function Hn(e,t){if(Array.isArray(t.aud)&&t.aud.length!==1){if(t.azp===void 0)throw h('ID Token "aud" (audience) claim includes additional untrusted audiences',C,{claims:t,claim:"aud"});if(t.azp!==e.client_id)throw h('unexpected ID Token "azp" (authorized party) claim value',C,{expected:e.client_id,claims:t,claim:"azp"})}}var we=Symbol(),ye=Symbol();async function Ht(e,t,n,r){return typeof r?.expectedNonce=="string"||typeof r?.maxAge=="number"||r?.requireIdToken?Jn(e,t,n,r.expectedNonce,r.maxAge,r[W],r.recognizedTokenTypes):zn(e,t,n,r?.maxAge,r?.[W],r?.recognizedTokenTypes)}async function Jn(e,t,n,r,o,s,a){let i=[];switch(r){case void 0:r=we;break;case we:break;default:_(r,'"expectedNonce" argument'),i.push("nonce")}o=Lt(t,o),o!==ye&&i.push("auth_time");let c=await Ke(e,t,n,i,s,a);_(c.id_token,'"response" body "id_token" property',p,{body:c});let u=Re(c);return Ut(t,u,o),jt(u,r),c}async function zn(e,t,n,r,o,s){let a=await Ke(e,t,n,void 0,o,s),i=Re(a);return i&&(Ut(t,i,Lt(t,r)),jt(i,we)),a}var qn="OAUTH_WWW_AUTHENTICATE_CHALLENGE",Mn="OAUTH_RESPONSE_BODY_ERROR",Se="OAUTH_UNSUPPORTED_OPERATION",Gn="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var ee="OAUTH_PARSE_ERROR",p="OAUTH_INVALID_RESPONSE";var $e="OAUTH_RESPONSE_IS_NOT_JSON",Ae="OAUTH_RESPONSE_IS_NOT_CONFORM",Be="OAUTH_HTTP_REQUEST_FORBIDDEN",Ye="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",te="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",C="OAUTH_JWT_CLAIM_COMPARISON_FAILED",Jt="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED",lt="OAUTH_KEY_SELECTION_FAILED",Wn="OAUTH_MISSING_SERVER_METADATA",Kn="OAUTH_INVALID_SERVER_METADATA";async function zt(e,t,n,r,o){J(e),re(t),_(r,'"token"');let s=oe(e,"revocation_endpoint",t.use_mtls_endpoint_aliases,o?.[v]!==!0),a=new URLSearchParams(o?.additionalParameters);a.set("token",r);let i=Me(o?.headers);return i.delete("accept"),Pt(e,t,n,s,a,i,o)}async function qt(e){if(!ne(e,Response))throw w('"response" must be an instance of Response',I);await It(e,200,"Revocation Endpoint")}function Qe(e){if(e.bodyUsed)throw w('"response" body has been used already',g)}async function Vn(e,t){J(e);let n=oe(e,"jwks_uri",!1,t?.[v]!==!0),r=Me(t?.headers);r.set("accept","application/json"),r.append("accept","application/jwk-set+json");let o=Object.fromEntries(r.entries()),s=JSON.stringify(o),a=t?.[D]||fetch,i=pt(n,t?.signal);fe||=new WeakMap;let c=fe.get(e)??new Set;for(let d of c)if(d.url===n.href&&d.headers===s&&d.fetch===a&&d.signal===i)return d.promise;let u={url:n.href,headers:s,fetch:a,signal:i,promise:Promise.resolve().then(()=>a(n.href,{body:void 0,headers:o,method:"GET",redirect:"manual",signal:i})).then(Fn).then(d=>{let l=$();return Je(e,d,l),{jwks:d,uat:l}}).finally(()=>{c.delete(u),c.size||fe.delete(e)})};return c.add(u),fe.set(e,c),u.promise}async function Fn(e){if(!ne(e,Response))throw w('"response" must be an instance of Response',I);if(e.status!==200)throw h('"response" is not a conform JSON Web Key Set response (unexpected HTTP status code)',Ae,e);Qe(e);let t=await Kt(e,n=>mn(n,"application/json","application/jwk-set+json"));if(!Array.isArray(t.keys))throw h('"response" body "keys" property must be an array',p,{body:t});if(!Array.prototype.every.call(t.keys,H))throw h('"response" body "keys" property members must be JWK formatted objects',p,{body:t});return t}function $n(e){switch(e){case"PS256":case"ES256":case"RS256":case"PS384":case"ES384":case"RS384":case"PS512":case"ES512":case"RS512":case"Ed25519":case"EdDSA":case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return!0;default:return!1}}function Bn(e){if(!$n(e.alg))throw new y('unsupported JWS "alg" identifier',{cause:{alg:e.alg}})}function ft(e){let{algorithm:t}=e;if(typeof t.modulusLength!="number"||t.modulusLength<2048)throw new y(`unsupported ${t.name} modulusLength`,{cause:e})}function Yn(e){let{algorithm:t}=e;switch(t.namedCurve){case"P-256":return"SHA-256";case"P-384":return"SHA-384";case"P-521":return"SHA-512";default:throw new y("unsupported ECDSA namedCurve",{cause:e})}}function Qn(e){switch(e.algorithm.name){case"ECDSA":return{name:e.algorithm.name,hash:Yn(e)};case"RSA-PSS":switch(ft(e),e.algorithm.hash.name){case"SHA-256":case"SHA-384":case"SHA-512":return{name:e.algorithm.name,saltLength:parseInt(e.algorithm.hash.name.slice(-3),10)>>3};default:throw new y("unsupported RSA-PSS hash name",{cause:e})}case"RSASSA-PKCS1-v1_5":return ft(e),e.algorithm.name;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":case"Ed25519":return e.algorithm.name}throw new y("unsupported CryptoKey algorithm name",{cause:e})}async function Zn(e,t,n,r){let o=Q(`${e}.${t}`),s=Qn(n);if(!await crypto.subtle.verify(s,n,r,o))throw h("JWT signature verification failed",p,{key:n,data:o,signature:r,algorithm:s})}async function Xn(e,t,n,r,o){let{0:s,1:a,length:i}=e.split(".");if(i===5)if(o!==void 0)e=await o(e),{0:s,1:a,length:i}=e.split(".");else throw new y("JWE decryption is not configured",{cause:e});if(i!==3)throw h("Invalid JWT",p,e);let c;try{c=JSON.parse(Q(K(s)))}catch(l){throw h("failed to parse JWT Header body as base64url encoded JSON",ee,l)}if(!H(c))throw h("JWT Header must be a top level object",p,e);if(t(c),c.crit!==void 0)throw new y('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(Q(K(a)))}catch(l){throw h("failed to parse JWT Payload body as base64url encoded JSON",ee,l)}if(!H(u))throw h("JWT Payload must be a top level object",p,e);let d=$()+n;if(u.exp!==void 0){if(typeof u.exp!="number")throw h('unexpected JWT "exp" (expiration time) claim type',p,{claims:u});if(u.exp<=d-r)throw h('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',te,{claims:u,now:d,tolerance:r,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw h('unexpected JWT "iat" (issued at) claim type',p,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw h('unexpected JWT "iss" (issuer) claim type',p,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw h('unexpected JWT "nbf" (not before) claim type',p,{claims:u});if(u.nbf>d+r)throw h('unexpected JWT "nbf" (not before) claim value',te,{claims:u,now:d,tolerance:r,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw h('unexpected JWT "aud" (audience) claim type',p,{claims:u});return{header:c,claims:u,jwt:e}}async function er(e){if(e.bodyUsed)throw w("form_post Request instances must contain a readable body",g,{cause:e});return e.text()}async function Mt(e){if(e.method!=="POST")throw w("form_post responses are expected to use the POST method",g,{cause:e});if(ge(e)!=="application/x-www-form-urlencoded")throw w("form_post responses are expected to use the application/x-www-form-urlencoded content-type",g,{cause:e});return er(e)}function tr(e,t,n,r){if(e!==void 0){if(typeof e=="string"?r.alg!==e:!e.includes(r.alg))throw h('unexpected JWT "alg" header parameter',p,{header:r,expected:e,reason:"client configuration"});return}if(Array.isArray(t)){if(!t.includes(r.alg))throw h('unexpected JWT "alg" header parameter',p,{header:r,expected:t,reason:"authorization server metadata"});return}if(n!==void 0){if(typeof n=="string"?r.alg!==n:typeof n=="function"?!n(r.alg):!n.includes(r.alg))throw h('unexpected JWT "alg" header parameter',p,{header:r,expected:n,reason:"default value"});return}throw h('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:e,issuer:t,fallback:n})}function j(e,t){let{0:n,length:r}=e.getAll(t);if(r>1)throw h(`"${t}" parameter must be provided only once`,p);return n}var Gt=Symbol(),nr=Symbol();function Wt(e,t,n,r){if(J(e),re(t),n instanceof URL&&(n=n.searchParams),!(n instanceof URLSearchParams))throw w('"parameters" must be an instance of URLSearchParams, or URL',I);if(j(n,"response"))throw h('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',p,{parameters:n});let o=j(n,"iss"),s=j(n,"state");if(!o&&e.authorization_response_iss_parameter_supported)throw h('response parameter "iss" (issuer) missing',p,{parameters:n});if(o&&o!==e.issuer)throw h('unexpected "iss" (issuer) response parameter value',p,{expected:e.issuer,parameters:n});switch(r){case void 0:case nr:if(s!==void 0)throw h('unexpected "state" response parameter encountered',p,{expected:void 0,parameters:n});break;case Gt:break;default:if(_(r,'"expectedState" argument'),s!==r)throw h(s===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',p,{expected:r,parameters:n})}if(j(n,"error"))throw new X("authorization response from the server is an error",{cause:n});let i=j(n,"id_token"),c=j(n,"token");if(i!==void 0||c!==void 0)throw new y("implicit and hybrid flows are not supported");return vn(new URLSearchParams(n))}function rr(e){switch(e){case"PS256":case"PS384":case"PS512":return{name:"RSA-PSS",hash:`SHA-${e.slice(-3)}`};case"RS256":case"RS384":case"RS512":return{name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.slice(-3)}`};case"ES256":case"ES384":return{name:"ECDSA",namedCurve:`P-${e.slice(-3)}`};case"ES512":return{name:"ECDSA",namedCurve:"P-521"};case"EdDSA":return"Ed25519";case"Ed25519":case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return e;default:throw new y("unsupported JWS algorithm",{cause:{alg:e}})}}async function or(e,t){let{ext:n,key_ops:r,use:o,...s}=t;return crypto.subtle.importKey("jwk",s,rr(e),!0,["verify"])}async function Kt(e,t=mt){let n;try{n=await e.json()}catch(r){throw t(e),h('failed to parse "response" body as JSON',ee,r)}if(!H(n))throw h('"response" body must be a top level object',p,{body:n});return n}var Ze=Symbol();var ie,Vt;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Vt="openid-client/v6.8.7",ie={"user-agent":Vt});var A=e=>et.get(e),et,Xe;function sr(e){return e!==void 0?We(e):(Xe||=new WeakMap,(t,n,r,o)=>{let s;return(s=Xe.get(n))||(ir(n.client_secret,'"metadata.client_secret"'),s=We(n.client_secret),Xe.set(n,s)),s(t,n,r,o)})}function ir(e,t){if(typeof e!="string")throw k(`${t} must be a string`,Te);if(e.length===0)throw k(`${t} must not be empty`,ce)}function tt(){return At()}var be=D;var ce="ERR_INVALID_ARG_VALUE",Te="ERR_INVALID_ARG_TYPE";function k(e,t,n){let r=new TypeError(e,{cause:n});return Object.assign(r,{code:t}),r}function Ft(e){return gt(e)}function $t(){return yt()}function Bt(){return Et()}function Yt(){return _t()}var se=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=n?.code,Error.captureStackTrace?.(this,this.constructor)}},Do=new TextDecoder;function E(e,t,n){return new se(e,{cause:t,code:n})}function z(e){if(e instanceof TypeError||e instanceof se||e instanceof V||e instanceof X||e instanceof F)throw e;if(e instanceof Z)switch(e.code){case Be:throw E("only requests to HTTPS are allowed",e,e.code);case Ye:throw E("only requests to HTTP or HTTPS are allowed",e,e.code);case Ae:throw E("unexpected HTTP response status code",e.cause,e.code);case $e:throw E("unexpected response content-type",e.cause,e.code);case ee:throw E("parsing error occured",e,e.code);case p:throw E("invalid response encountered",e,e.code);case C:throw E("unexpected JWT claim value encountered",e,e.code);case Jt:throw E("unexpected JSON attribute value encountered",e,e.code);case te:throw E("JWT timestamp claim value failed validation",e,e.code);default:throw E(e.message,e,e.code)}if(e instanceof y)throw E("unsupported operation",e,e.code);if(e instanceof DOMException)switch(e.name){case"OperationError":throw E("runtime operation error",e,Se);case"NotSupportedError":throw E("runtime unsupported operation",e,Se);case"TimeoutError":throw E("operation timed out",e,"OAUTH_TIMEOUT");case"AbortError":throw E("operation aborted",e,"OAUTH_ABORT")}throw new se("something went wrong",{cause:e})}function cr(e){return{supportsPKCE:{__proto__:null,value(t="S256"){return e.code_challenge_methods_supported?.includes(t)===!0}}}}function ur(e){Object.defineProperties(e,cr(e))}var dr=Symbol(),q=class{constructor(t,n,r,o){if(typeof n!="string"||!n.length)throw k('"clientId" must be a non-empty string',Te);if(typeof r=="string"&&(r={client_secret:r}),r?.client_id!==void 0&&n!==r.client_id)throw k('"clientId" and "metadata.client_id" must be the same',ce);let s={...structuredClone(r),client_id:n};s[_e]=r?.[_e]??0,s[Ee]=r?.[Ee]??30;let a;o?a=o:typeof s.client_secret=="string"&&s.client_secret.length?a=sr(s.client_secret):a=tt();let i=Object.freeze(s),c=structuredClone(t);dr in t&&(c[Ze]=({claims:{tid:d}})=>t.issuer.replace("{tenantid}",d));let u=Object.freeze(c);et||=new WeakMap,et.set(this,{__proto__:null,as:u,c:i,auth:a,tlsOnly:!0,jwksCache:{}})}serverMetadata(){let t=structuredClone(A(this).as);return ur(t),t}clientMetadata(){return structuredClone(A(this).c)}get timeout(){return A(this).timeout}set timeout(t){A(this).timeout=t}get[be](){return A(this).fetch}set[be](t){A(this).fetch=t}};Object.freeze(q.prototype);function hr(e){let t;if(e.expires_in!==void 0){let n=new Date;n.setSeconds(n.getSeconds()+e.expires_in),t=n.getTime()}return{expiresIn:{__proto__:null,value(){if(t){let n=Date.now();return t>n?Math.floor((t-n)/1e3):0}}},claims:{__proto__:null,value(){return Re(e)}}}}function Qt(e){Object.defineProperties(e,hr(e))}function Zt(e){ue(e),A(e).nonRepudiation=t=>{let{as:n,fetch:r,tlsOnly:o,timeout:s,jwksCache:a}=A(e);return xt(n,t,{[D]:r,[v]:!o,headers:new Headers(ie),signal:Ie(s),[x]:a}).catch(z)}}function lr(e){return e=new URL(e),e.search="",e.hash="",e.href}function fr(e,t){try{return Object.getPrototypeOf(e)[Symbol.toStringTag]===t}catch{return!1}}async function nt(e,t,n,r,o){if(ue(e),o?.flag!==ae&&!(t instanceof URL)&&!fr(t,"Request"))throw k('"currentUrl" must be an instance of URL, or Request',Te);let s,a,{as:i,c,auth:u,fetch:d,tlsOnly:l,jarm:m,hybrid:f,nonRepudiation:P,timeout:T,decrypt:Oe,implicit:b}=A(e);if(o?.flag===ae)s=o.authResponse,a=o.redirectUri;else{if(!(t instanceof URL)){let O=t;switch(t=new URL(t.url),O.method){case"GET":break;case"POST":let he=new URLSearchParams(await Mt(O));if(f)t.hash=he.toString();else for(let[Ne,dn]of he.entries())t.searchParams.append(Ne,dn);break;default:throw k("unexpected Request HTTP method",ce)}}switch(a=lr(t),!0){case!!m:s=await m(t,n?.expectedState);break;case!!f:s=await f(t,n?.expectedNonce,n?.expectedState,n?.maxAge);break;case!!b:throw new TypeError("authorizationCodeGrant() cannot be used by response_type=id_token clients");default:try{s=Wt(i,c,t.searchParams,n?.expectedState)}catch(O){z(O)}}}let U=await vt(i,c,u,s,a,n?.pkceCodeVerifier||Fe,{additionalParameters:r,[D]:d,[v]:!l,DPoP:o?.DPoP,headers:new Headers(ie),signal:Ie(T)}).catch(z);(typeof n?.expectedNonce=="string"||typeof n?.maxAge=="number")&&(n.idTokenExpected=!0);let ke=Ht(i,c,U,{expectedNonce:n?.expectedNonce,maxAge:n?.maxAge,requireIdToken:n?.idTokenExpected,[W]:Oe}),M;try{M=await ke}catch(O){if(en(O,o))return nt(e,void 0,n,r,{...o,flag:ae,authResponse:s,redirectUri:a});z(O)}return M.id_token&&await P?.(U),Qt(M),M}async function rt(e,t,n,r){ue(e),n=new URLSearchParams(n);let{as:o,c:s,auth:a,fetch:i,tlsOnly:c,nonRepudiation:u,timeout:d,decrypt:l}=A(e),m=await kt(o,s,a,t,{[D]:i,[v]:!c,additionalParameters:n,DPoP:r?.DPoP,headers:new Headers(ie),signal:Ie(d)}).catch(z),f=Ct(o,s,m,{[W]:l}),P;try{P=await f}catch(T){if(en(T,r))return rt(e,t,n,{...r,flag:ae});z(T)}return P.id_token&&await u?.(m),Qt(P),P}function Xt(e,t){ue(e);let{as:n,c:r,tlsOnly:o,hybrid:s,jarm:a,implicit:i}=A(e),c=oe(n,"authorization_endpoint",!1,o);if(t=new URLSearchParams(t),t.has("client_id")||t.set("client_id",r.client_id),!t.has("request_uri")&&!t.has("request")){if(t.has("response_type")||t.set("response_type",s?"code id_token":i?"id_token":"code"),i&&!t.has("nonce"))throw k("response_type=id_token clients must provide a nonce parameter in their authorization request parameters",ce);a&&t.set("response_mode","jwt")}for(let[u,d]of t.entries())c.searchParams.append(u,d);return c}function ue(e){if(!(e instanceof q))throw k('"config" must be an instance of Configuration',Te);if(Object.getPrototypeOf(e)!==q.prototype)throw k("subclassing Configuration is not allowed",ce)}function Ie(e){return e?AbortSignal.timeout(e*1e3):void 0}function en(e,t){return t?.DPoP&&t.flag!==ae?Tt(e):!1}var ae=Symbol();async function tn(e,t,n){ue(e);let{as:r,c:o,auth:s,fetch:a,tlsOnly:i,timeout:c}=A(e);return zt(r,o,s,t,{[D]:a,[v]:!i,additionalParameters:new URLSearchParams(n),headers:new Headers(ie),signal:Ie(c)}).then(qt).catch(z)}import{createServer as mr}from"node:http";async function nn(e,t,n){n.throwIfAborted();let r=new URL(e);if(r.protocol!=="http:"||r.hostname!=="127.0.0.1"||!r.port||r.search||r.hash||r.username||r.password)throw Error("DESKTOP_LOGIN_CALLBACK_INVALID");let o,s,a=!1,i=new Promise((d,l)=>{o=d,s=l});i.catch(()=>{});let c=mr((d,l)=>{l.setHeader("cache-control","no-store"),l.setHeader("content-security-policy","default-src 'none'"),l.setHeader("content-type","text/plain; charset=utf-8");let m;try{m=new URL(d.url??"/",r.origin)}catch{l.writeHead(400).end("Invalid callback.");return}if(a||d.method!=="GET"||!["127.0.0.1","::ffff:127.0.0.1"].includes(d.socket.remoteAddress??"")||d.headers.host!==r.host||m.origin+m.pathname!==e||m.searchParams.getAll("state").length!==1||m.searchParams.get("state")!==t||m.searchParams.getAll("code").length!==1&&!m.searchParams.has("error")){l.writeHead(400).end("Invalid callback.");return}a=!0,l.end("Authorization received. Return to Native Engagement."),o(m)});c.maxConnections=4,c.requestTimeout=3e3,c.headersTimeout=3e3,c.keepAliveTimeout=1e3,c.maxHeadersCount=32;let u=()=>{s(Error("DESKTOP_LOGIN_CANCELLED")),c.close(),c.closeAllConnections()};n.addEventListener("abort",u,{once:!0});try{await new Promise((d,l)=>{c.once("error",l),c.listen({host:"127.0.0.1",port:Number(r.port),signal:n},()=>{c.removeListener("error",l),d()})})}catch(d){throw n.removeEventListener("abort",u),d}return{callback:i,async close(){n.removeEventListener("abort",u),c.closeAllConnections(),await new Promise(d=>c.close(()=>d()))}}}var de=class{installation;config;constructor(t,n=fetch){this.installation=t;let r=t,o=new URL(r.issuer);if(o.protocol!=="https:"||o.username||o.password||o.search||o.hash)throw Error("DESKTOP_LOGIN_CONFIGURATION_INVALID");for(let s of[r.authorizationEndpoint,r.tokenEndpoint,r.jwksUri,r.revocationEndpoint]){let a=new URL(s);if(a.origin!==o.origin||a.protocol!=="https:"||a.username||a.password||a.search||a.hash)throw Error("DESKTOP_LOGIN_CONFIGURATION_INVALID")}this.config=new q({issuer:r.issuer,authorization_endpoint:r.authorizationEndpoint,token_endpoint:r.tokenEndpoint,jwks_uri:r.jwksUri,revocation_endpoint:r.revocationEndpoint,response_types_supported:["code"],code_challenge_methods_supported:["S256"]},r.clientId,{token_endpoint_auth_method:"none"},tt()),this.config.timeout=5,Zt(this.config),this.config[be]=async(s,a)=>{if(![r.tokenEndpoint,r.jwksUri,r.revocationEndpoint].includes(String(s)))throw Error("DESKTOP_LOGIN_ENDPOINT_CHANGED");let{body:i,...c}=a;return n(s,{...c,...i!==void 0?{body:i instanceof Uint8Array?new Uint8Array(i).buffer:i}:{},redirect:"error",signal:a.signal?AbortSignal.any([a.signal,AbortSignal.timeout(5e3)]):AbortSignal.timeout(5e3)})}}async authorize(t,n){let r=this.installation,o=Yt(),s=Bt(),a=$t(),i=await nn(r.redirectUri,o,t);try{let c=Xt(this.config,{redirect_uri:r.redirectUri,state:o,nonce:s,scope:r.scopes.join(" "),resource:r.resource,code_challenge:await Ft(a),code_challenge_method:"S256"});t.throwIfAborted(),await n(c.href);let u=await i.callback;t.throwIfAborted();let d=await nt(this.config,u,{expectedState:o,expectedNonce:s,pkceCodeVerifier:a,idTokenExpected:!0},{resource:r.resource}),l=d.claims()?.sub,m=Number(d.expires_in);if(!d.access_token||!l||!Number.isSafeInteger(m)||m<1||m>86400)throw Error("DESKTOP_LOGIN_GRANT_INVALID");return{accessToken:d.access_token,refreshToken:d.refresh_token??null,subject:l,expiresAt:Date.now()+m*1e3}}finally{await i.close()}}async revoke(t){await tn(this.config,t.refreshToken??t.accessToken,{token_type_hint:t.refreshToken?"refresh_token":"access_token"})}async refresh(t){if(!t.refreshToken)throw Error("DESKTOP_LOGIN_REQUIRED");let n=await rt(this.config,t.refreshToken,{resource:this.installation.resource}),r=Number(n.expires_in),o=n.claims()?.sub??t.subject;if(!n.access_token||o!==t.subject||!Number.isSafeInteger(r)||r<1||r>86400)throw Error("DESKTOP_LOGIN_GRANT_INVALID");return{accessToken:n.access_token,refreshToken:n.refresh_token??t.refreshToken,subject:o,expiresAt:Date.now()+r*1e3}}};import L from"node:fs/promises";import{constants as rn}from"node:fs";import wr from"node:os";import B from"node:path";import{execFile as yr}from"node:child_process";function ot(e){return B.join(e.NATIVE_ENGAGEMENT_CLI_HOME??B.join(wr.homedir(),".native-engagement-cli"),"session.json")}async function at(e,t){let n=B.dirname(e);if(!B.isAbsolute(n)||B.normalize(n)!==n)throw Error("CLI_PRIVATE_DIRECTORY_REQUIRED");t&&await L.mkdir(n,{recursive:!0,mode:448});let r=await L.lstat(n),o=await L.realpath(n);if(!r.isDirectory()||r.isSymbolicLink()||o.toLowerCase()!==n.toLowerCase()||process.platform!=="win32"&&(r.uid!==process.getuid?.()||r.mode&63))throw Error("CLI_PRIVATE_DIRECTORY_REQUIRED")}async function on(e,t){let n=t?"Protect":"Unprotect",r="Add-Type -AssemblyName System.Security; $v=[Console]::In.ReadToEnd(); "+(t?"$b=[Text.Encoding]::UTF8.GetBytes($v); ":"$b=[Convert]::FromBase64String($v); ")+`$r=[Security.Cryptography.ProtectedData]::${n}($b,$null,[Security.Cryptography.DataProtectionScope]::CurrentUser); `+(t?"[Console]::Out.Write([Convert]::ToBase64String($r))":"[Console]::Out.Write([Text.Encoding]::UTF8.GetString($r))");return new Promise((o,s)=>{yr(B.join(process.env.SystemRoot??"C:\\Windows","System32/WindowsPowerShell/v1.0/powershell.exe"),["-NoProfile","-NonInteractive","-Command",r],{timeout:1e4,maxBuffer:131072,windowsHide:!0},(i,c)=>i?s(Error("CLI_CREDENTIAL_STORE_UNAVAILABLE")):o(c)).stdin?.end(e)})}async function an(e,t=process.env){let n=ot(t);await at(n,!0);let r=JSON.stringify({...e,grant:{...e.grant,refreshToken:null}}),o=process.platform==="win32"?JSON.stringify({protection:"WINDOWS_DPAPI_CURRENT_USER",value:await on(r,!0)}):r,s=n+"."+process.pid+".new";try{let a=await L.open(s,"wx",384);try{await a.writeFile(o),await a.sync()}finally{await a.close()}await L.rename(s,n)}finally{await L.rm(s,{force:!0})}}async function Pe(e=process.env){let t=ot(e);try{await at(t,!1);let n=await L.open(t,rn.O_RDONLY|(process.platform==="win32"?0:rn.O_NOFOLLOW)),r;try{let a=await n.stat();if(!a.isFile()||a.nlink!==1||a.size>65536||process.platform!=="win32"&&(a.uid!==process.getuid?.()||a.mode&63))throw Error("CLI_PRIVATE_SESSION_REQUIRED");let i=Buffer.alloc(65537),c=await n.read(i,0,i.length,0);if(c.bytesRead>65536)throw Error("CLI_PRIVATE_SESSION_REQUIRED");r=i.subarray(0,c.bytesRead).toString("utf8")}finally{await n.close()}if(process.platform==="win32"){let a=JSON.parse(r);if(a.protection!=="WINDOWS_DPAPI_CURRENT_USER"||typeof a.value!="string")throw Error("CLI_PRIVATE_SESSION_REQUIRED");r=await on(a.value,!1)}let o=JSON.parse(r);if(o.schemaVersion!==1||typeof o.origin!="string"||!o.login||!o.grant||!Number.isSafeInteger(o.grant.expiresAt)||typeof o.grant.accessToken!="string"||!/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(o.grant.accessToken)||o.grant.refreshToken!==null)throw Error("CLI_PRIVATE_SESSION_REQUIRED");let s=new URL(o.origin);if(s.protocol!=="https:"||s.origin!==o.origin)throw Error("CLI_PRIVATE_SESSION_REQUIRED");return o}catch(n){if(n.code==="ENOENT")return null;throw Error("CLI_SESSION_UNAVAILABLE_REAUTHORIZE")}}async function sn(e=process.env){let t=ot(e);await at(t,!1),await L.unlink(t)}async function cn(e,t=process.env){let n=await Pe(t);if(e==="status"){console.log(JSON.stringify({ok:!0,result:{authenticated:!!n&&n.grant.expiresAt>Date.now(),origin:n?.origin??null,expiresAt:n?new Date(n.grant.expiresAt).toISOString():null}}));return}if(e==="logout"){if(n)try{await new de(n.login).revoke(n.grant)}finally{await sn(t)}console.log(JSON.stringify({ok:!0,result:{authenticated:!1}}));return}if(e!=="login")throw Error("CLI_AUTH_OPERATION_INVALID");let r=t.NATIVE_ENGAGEMENT_API_URL??"https://engagement.shipkitx.com",o=new URL(r);if(o.protocol!=="https:"||o.origin!==r||o.username||o.password)throw Error("CLI_HTTPS_CENTER_REQUIRED");if(n&&n.origin!==r)throw Error("CLI_LOGOUT_BEFORE_CENTER_CHANGE");let s=await fetch(r+"/releases/cli-login.json",{redirect:"error",signal:AbortSignal.timeout(1e4)});if(!s.ok||Number(s.headers.get("content-length"))>32768)throw Error("CLI_LOGIN_SERVICE_UNAVAILABLE");if(!s.body)throw Error("CLI_LOGIN_CONFIGURATION_INVALID");let a=s.body.getReader(),i=[],c=0;try{for(;;){let b=await a.read();if(b.done)break;if(c+=b.value.byteLength,c>32768)throw Error("CLI_LOGIN_CONFIGURATION_INVALID");i.push(b.value)}}finally{await a.cancel().catch(()=>{})}let u=new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.concat(i)),d=JSON.parse(u);if(d.ok!==!0||d.result?.serviceOrigin!==r||!d.result.login)throw Error("CLI_LOGIN_CONFIGURATION_INVALID");let l=d.result.login,m=new Set(["openid","engagement:read","engagement:write","work:read","asset:reader","message:draft"]);if(new URL(l.issuer).origin!==r||l.resource!==r+"/mcp"||l.clientId!=="native-engagement-cli"||!Array.isArray(l.scopes)||!l.scopes.includes("openid")||l.scopes.some(b=>!m.has(b)))throw Error("CLI_LOGIN_CONFIGURATION_INVALID");let f=new de(l),P=new AbortController,T=()=>P.abort(),Oe=setTimeout(T,18e4);process.once("SIGINT",T),process.once("SIGTERM",T);try{let b=await f.authorize(P.signal,async U=>{let ke=process.platform==="darwin"?"/usr/bin/open":process.platform==="win32"?"rundll32.exe":"/usr/bin/xdg-open",M=process.platform==="win32"?["url.dll,FileProtocolHandler",U]:[U];await new Promise((O,he)=>_r(ke,M,{timeout:1e4,windowsHide:!0},Ne=>Ne?he(Error("CLI_BROWSER_UNAVAILABLE")):O()))});try{await an({schemaVersion:1,origin:r,login:d.result.login,grant:b},t)}catch(U){throw await f.revoke(b).catch(()=>{}),U}console.log(JSON.stringify({ok:!0,result:{authenticated:!0,expiresAt:new Date(b.expiresAt).toISOString()}}))}finally{clearTimeout(Oe),process.removeListener("SIGINT",T),process.removeListener("SIGTERM",T)}}var un=JSON.parse(await Er(new URL("../package.json",import.meta.url),"utf8")),R=process.argv.slice(2);if(R.length===1&&["--version","-v"].includes(R[0]))console.log(un.version);else if(!R.length||R.length===1&&["--help","-h","help"].includes(R[0]))console.log(`Native Engagement ${un.version}
3
+
4
+ Usage: native-engagement <command> [options]
5
+
6
+ contracts list Discover canonical tools
7
+ schema get <name> Read an input/output schema
8
+ query <name> Run an authorized query
9
+ command <name> Submit an authorized command
10
+ search Search current authorized facts
11
+ enquiry Request a structured explanation
12
+ login Authorize in your system browser
13
+ logout Remove and revoke the saved access grant
14
+ auth status Inspect login status without showing credentials
15
+
16
+ Options:
17
+ --input @file.json Read bounded JSON input
18
+ --input-json <json> Inline non-secret JSON input
19
+ --tenant <tenant> Compare the authenticated tenant
20
+ --help Show this help
21
+ --version Show the installed version
22
+
23
+ Authentication:
24
+ Run native-engagement login for interactive access.
25
+ NATIVE_ENGAGEMENT_API_URL identifies the HTTPS service.
26
+ NATIVE_ENGAGEMENT_BEARER_TOKEN is a short-lived access token supplied
27
+ through your host's protected environment. Never pass credentials in argv.
28
+ Commands require an idempotencyKey in their input.
29
+
30
+ Results: structured JSON; exit 0 success, 2 rejected input/access, 1 unavailable.
31
+ Documentation: https://engagement.shipkitx.com/downloads`);else try{if(R.length===1&&["login","logout"].includes(R[0])||R.length===2&&R[0]==="auth"&&R[1]==="status")await cn(R[0]==="auth"?"status":R[0]);else{let e=process.env.NATIVE_ENGAGEMENT_BEARER_TOKEN?null:await Pe(),t=process.env.NATIVE_ENGAGEMENT_API_URL??e?.origin??"https://engagement.shipkitx.com";if(e&&e.origin!==t)throw Error("CLI_SAVED_CENTER_MISMATCH");process.exitCode=await ut(R,void 0,{...process.env,NATIVE_ENGAGEMENT_API_URL:t,...e&&e.grant.expiresAt>Date.now()?{NATIVE_ENGAGEMENT_BEARER_TOKEN:e.grant.accessToken}:{}})}}catch{console.error(JSON.stringify({ok:!1,error:{code:"CLI_AUTHENTICATION_OR_CONFIGURATION_FAILED",hint:"CHECK_CENTER_AND_LOGIN_AGAIN"}})),process.exitCode=1}
package/package.json CHANGED
@@ -1,6 +1,28 @@
1
1
  {
2
2
  "name": "@native-engagement/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.8.0",
4
+ "type": "module",
5
+ "description": "Authenticated Native Engagement command line client",
6
+ "engines": {
7
+ "node": ">=24.22.1 <25"
8
+ },
9
+ "license": "UNLICENSED",
10
+ "files": [
11
+ "dist",
12
+ "README.md",
13
+ "release.json",
14
+ "THIRD_PARTY_LICENSES.txt"
15
+ ],
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/SENLIN746/native-engagement.git"
19
+ },
20
+ "homepage": "https://engagement.shipkitx.com/downloads",
21
+ "publishConfig": {
22
+ "access": "public",
23
+ "tag": "beta"
24
+ },
25
+ "bin": {
26
+ "native-engagement": "./dist/index.js"
27
+ }
28
+ }
package/release.json ADDED
@@ -0,0 +1,18 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "sourceCommit": "5402e30207f693b0a0e28cb49e54720b402e1db9",
4
+ "channel": "beta",
5
+ "bundledComponents": [
6
+ {
7
+ "name": "oauth4webapi",
8
+ "version": "3.8.8",
9
+ "license": "MIT"
10
+ },
11
+ {
12
+ "name": "openid-client",
13
+ "version": "6.8.7",
14
+ "license": "MIT"
15
+ }
16
+ ],
17
+ "lockSha256": "421cbab359e454443023383a61d63b1fc9f562e79c4e7c5174b09bdfb640d76c"
18
+ }