@native-engagement/cli 0.8.0 → 0.8.2

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,24 +1,54 @@
1
1
  # Native Engagement CLI
2
2
 
3
- Node.js 24.22.1+ (24 LTS) command line access to the same authenticated Native Engagement HTTPS contracts.
3
+ Node.js 24.22.1+ (24 LTS) client for the Native Engagement HTTPS service.
4
4
 
5
5
  ```sh
6
- npm install -g @native-engagement/cli@beta
7
- native-engagement --help
6
+ npm install --global @native-engagement/cli@0.8.2
8
7
  native-engagement --version
9
8
  native-engagement login
10
9
  native-engagement auth status
11
- npx @native-engagement/cli@beta contracts list
12
10
  ```
13
11
 
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.
12
+ ## Account and password sign-in
13
+
14
+ `login` opens your system browser. Enter your account, password and any MFA challenge on the identity service's page and approve the requested permissions. OAuth Authorization Code with S256 PKCE returns the result to the CLI on loopback. A current browser SSO session can avoid repeated password entry. Your administrator must provision your account and tenant permissions first.
15
+
16
+ The default center is https://engagement.shipkitx.com. Use `NATIVE_ENGAGEMENT_API_URL` for another trusted HTTPS center. The browser callback must reach the machine running the CLI. For an application-managed browser on macOS/Linux, run `native-engagement login --no-open`: stderr reports the path of a private `authorization-url.txt` file. Open its URL in a browser on this machine; the file is removed on completion or cancellation. Authorization URLs and passwords are not printed in command results. `NATIVE_ENGAGEMENT_CLI_HOME` selects an absolute private current-user directory.
17
+
18
+ The access grant uses a private current-user file on macOS/Linux and current-user DPAPI on Windows. Refresh tokens are not persisted. Run `login` again after expiry. `native-engagement logout` revokes and removes the grant. Login requests engagement read/write, work read, asset read and message draft, intersected with current tenant permissions. Desktop installation and identity administration use their own authorization.
19
+
20
+ For automation, supply a separately authorized short-lived `NATIVE_ENGAGEMENT_BEARER_TOKEN` through the protected environment. Password, token and principal overrides are not accepted in argv. An npm publishing token is unrelated to service login.
21
+
22
+ ## Complete prospect workflow
15
23
 
16
24
  ```sh
17
- native-engagement schema get conversation.list
18
- native-engagement query conversation.list --input @request.json
25
+ native-engagement schema get prospect.batch.import
26
+ native-engagement prospect preview --input @import.json
27
+ native-engagement prospect import --input @import.json
28
+ native-engagement prospect batch --input @batch.json
29
+ native-engagement prospect company --input @company.json
30
+ native-engagement prospect engage --input @engage.json
31
+ native-engagement prospect engagements --input @association.json
32
+ native-engagement prospect batches --input @page.json
33
+ ```
34
+
35
+ Inputs follow the canonical schemas from `schema get`. `import.json` supports country, industry, address, contact name/title and original score in each row's optional `profile`; the SDK README has a complete input. Source URLs are optional; provide an actual credential-free HTTP(S) page when known. Preserve source reference/version, observation time and current/historical status. Original research and verification stay with their owner; Native stores observations and receipts.
36
+
37
+ `batch.json`: `{"batchRef":"YOUR_BATCH_REF"}`. `company.json`: `{"prospectRef":"YOUR_EXACT_PROSPECT_REF"}`. `engage.json` selects the exact imported CURRENT contact/source observation and supplies an engagement reference, why-fit/why-now and stable idempotency key. Creating an engagement does not send or schedule work. Retry an unchanged input with its original key.
38
+
39
+ `association.json`: `{"prospectRef":"YOUR_EXACT_PROSPECT_REF","limit":20}`; pass returned `nextCursor` as `cursor`. `page.json`: `{"offset":0,"limit":20}`; continue with `nextOffset` until null. Batch history has no 100-total cap; responses contain at most 100 records. `prospect list` queries the company catalog.
40
+
41
+ ```sh
42
+ native-engagement contracts list
43
+ native-engagement query <contract-name> --input @request.json
19
44
  native-engagement command <contract-name> --input @command.json
45
+ npx @native-engagement/cli@0.8.2 --help
20
46
  ```
21
47
 
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.
48
+ Results are JSON: exit 0 success, 2 rejected input/access, 1 unavailable. Unknown external effects require original-operation inspection before retrying. Local execution nodes and channel authorization use the Desktop installation flow.
49
+
50
+ ## MCP OAuth
51
+
52
+ Connect your MCP host to `https://engagement.shipkitx.com/mcp` using Streamable HTTP and OAuth. It discovers the authorization server from the 401 resource-metadata challenge, opens its own browser sign-in and receives its own grant. The center currently uses pre-registered MCP clients with exact registered callbacks. Ask your administrator to register the host first if it has no client configuration; the CLI client identifier is reserved for the CLI/SDK loopback flow. Current directory permissions govern each MCP call.
23
53
 
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
54
+ This beta uses license `UNLICENSED`. [Complete account and OAuth guide](https://engagement.shipkitx.com/releases/authentication.md) · [Downloads](https://engagement.shipkitx.com/downloads)
package/dist/index.js CHANGED
@@ -1,7 +1,5 @@
1
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]
2
+ var A=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 Ne(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"}}function it(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new A("VALIDATION_FAILED",`${t} must be an object.`,400,{field:t});return e}function xe(e){let t=it(e??{},"payload"),n=t.idempotencyKey;if(typeof n!="string"||!n.trim()||n.length>1024*1024)throw new A("VALIDATION_FAILED","Every command requires a bounded idempotencyKey.",400,{field:"idempotencyKey"});return t}var _n={preview:["query","prospect.batch.preview"],import:["command","prospect.batch.import"],batch:["query","prospect.batch.get"],batches:["query","prospect.batch.list"],company:["query","prospect.company.get"],list:["query","prospect.catalog.list"],engage:["command","prospect.engagement.create"],engagements:["query","engagement.catalog.list"]};function ct(e){if(e[0]!=="prospect")return e;let t=_n[e[1]??""];if(!t)throw new A("VALIDATION_FAILED","prospect: preview, import, batch, batches, company, list, engage, engagements; use --input <json-file>.",400);return[...t,...e.slice(2)]}function F(e){if(!e.length||e[0]==="help")return!0;for(let t=0;t<e.length;t+=1){if(e[t]==="--help"||e[t]==="-h")return!0;["--input","--input-json","--tenant"].includes(e[t])&&(t+=1)}return!1}var B=`Usage: native-engagement <command> [options]
5
3
 
6
4
  contracts list Discover canonical tools
7
5
  schema get <name> Read an input/output schema
@@ -9,7 +7,10 @@ Usage: native-engagement <command> [options]
9
7
  command <name> Submit an authorized command
10
8
  search Search current authorized facts
11
9
  enquiry Request a structured explanation
10
+ prospect <operation> preview, import, batch, batches, company, list,
11
+ engage, engagements (canonical JSON input)
12
12
  login Authorize in your system browser
13
+ login --no-open Write a private browser URL file (macOS/Linux)
13
14
  logout Remove and revoke the saved access grant
14
15
  auth status Inspect login status without showing credentials
15
16
 
@@ -21,11 +22,15 @@ Options:
21
22
  --version Show the installed version
22
23
 
23
24
  Authentication:
24
- Run native-engagement login for interactive access.
25
+ Run native-engagement login for browser-based account/password sign-in.
26
+ Password entry and MFA belong to the identity service's browser page.
25
27
  NATIVE_ENGAGEMENT_API_URL identifies the HTTPS service.
26
28
  NATIVE_ENGAGEMENT_BEARER_TOKEN is a short-lived access token supplied
27
29
  through your host's protected environment. Never pass credentials in argv.
28
30
  Commands require an idempotencyKey in their input.
29
31
 
30
32
  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}
33
+ Documentation: https://engagement.shipkitx.com/downloads`;import ke from"node:fs";var ut=e=>["execution.node.media.output.report","execution.node.file.report"].includes(e??"")?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;async function dt(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=Ne(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 gn(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 he=class{#o;#a;#s;#n;#t;#r;constructor(t){if(this.#o=gn(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 dt(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=t.name==="asset.original.get"?18e4:["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{xe(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","message.draft.sync","message.execution.execute","message.execution.verify","message.inbox.sync"].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 Ce(e,t){let n=e.indexOf(t);return n<0?void 0:e[n+1]}function $(e){let t=Ce(e,"--input-json"),n=Ce(e,"--input");if(t&&n)throw new Error("Use either --input-json or --input.");let r=ut(e[0]==="command"?e[1]:void 0),o={};if(n){let s=n.startsWith("@")?n.slice(1):n,a=ke.openSync(s,"r"),i=Buffer.alloc(r+1);try{let c=0,u=0;do u=ke.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{ke.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 En(e){return["--principal","--actor","--scope","--token","--authorization"].some(t=>e.includes(t))}async function ht(e,t=r=>console.log(r),n=process.env){try{if(F(e))return t(JSON.stringify({help:B})),0;if(e=ct(e),En(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=Ce(e,"--tenant"),s=new he({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($(e));else if(e[0]==="enquiry")a=await s.enquiry($(e));else if(e[0]==="agent-stack-preflight")a=await s.agentStackPreflight($(e));else if(e[0]==="query"&&e[1])a=await s.query({name:e[1],payload:$(e)});else if(e[0]==="command"&&e[1])a=await s.command({name:e[1],payload:$(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 A?new S(r.code,r.message,r.statusCode):r,s=o instanceof S?{code:o.code,message:o.message,retryable:o.retryable,hint:o.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:s})),o instanceof S&&o.status<500?2:1}}import{readFile as Or}from"node:fs/promises";var De;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(De="oauth4webapi/v3.8.8");function te(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 R="ERR_INVALID_ARG_VALUE",T="ERR_INVALID_ARG_TYPE";function w(e,t,n){let r=new TypeError(e,{cause:n});return Object.assign(r,{code:t}),r}var x=Symbol(),ye=Symbol(),_e=Symbol(),k=Symbol();var M=Symbol(),O=Symbol(),Rn=new TextEncoder,An=new TextDecoder;function Y(e){return typeof e=="string"?Rn.encode(e):An.decode(e)}var Le;Uint8Array.prototype.toBase64?Le=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0})):Le=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 Ue;Uint8Array.fromBase64?Ue=e=>{try{return Uint8Array.fromBase64(e,{alphabet:"base64url"})}catch(t){throw w("The input to be decoded is not correctly encoded.",R,t)}}:Ue=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.",R,t)}};function G(e){return typeof e=="string"?Ue(e):Le(e)}var y=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=Re,Error.captureStackTrace?.(this,this.constructor)}},Q=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 Q(e,{code:t,cause:n})}function L(e){return!(e===null||typeof e!="object"||Array.isArray(e))}function qe(e){te(e,Headers)&&(e=Object.fromEntries(e.entries()));let t=new Headers(e??{});if(De&&!t.has("user-agent")&&t.set("user-agent",De),t.has("authorization"))throw w('"options.headers" must not include the "authorization" header name',R);return t}function wt(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',T);return t}}function fe(e,t,n,r,o){try{if(typeof e!="number"||!Number.isFinite(e))throw w(`${n} must be a number`,T,o);if(e>0)return;if(t){if(e!==0)throw w(`${n} must be a non-negative number`,R,o);return}throw w(`${n} must be a positive number`,R,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`,T,r);if(e.length===0)throw w(`${t} must not be empty`,R,r)}catch(o){throw n?h(o.message,n,r):o}}function yt(e){bn(e,"application/json")}function _t(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,Ke,e)}function Sn(e,...t){if(!t.includes(ge(e)))throw _t(e,...t)}function bn(e,t){if(ge(e)!==t)throw _t(e,t)}function ze(){return G(crypto.getRandomValues(new Uint8Array(32)))}function gt(){return ze()}function Et(){return ze()}function Rt(){return ze()}async function At(e){return _(e,"codeVerifier"),G(await crypto.subtle.digest("SHA-256",Y(e)))}function St(e){let t=e?.[ye];return typeof t=="number"&&Number.isFinite(t)?t:0}function bt(e){let t=e?.[_e];return typeof t=="number"&&Number.isFinite(t)&&Math.sign(t)!==-1?t:30}function K(){return Math.floor(Date.now()/1e3)}function U(e){if(typeof e!="object"||e===null)throw w('"as" must be an object',T);_(e.issuer,'"as.issuer"')}function ne(e){if(typeof e!="object"||e===null)throw w('"client" must be an object',T);_(e.client_id,'"client.client_id"')}function Me(e){return _(e,'"clientSecret"'),(t,n,r,o)=>{r.set("client_id",n.client_id),r.set("client_secret",e)}}function Tt(){return(e,t,n,r)=>{n.set("client_id",t.client_id)}}var Tn=URL.parse?(e,t)=>URL.parse(e,t):(e,t)=>{try{return new URL(e,t)}catch{return null}};function It(e,t){if(t&&e.protocol!=="https:")throw h("only requests to HTTPS are allowed",Fe,e);if(e.protocol!=="https:"&&e.protocol!=="http:")throw h("only HTTP and HTTPS requests are allowed",Be,e)}function lt(e,t,n,r){let o;if(typeof e!="string"||!(o=Tn(e)))throw h(`authorization server metadata does not contain a valid ${n?`"as.mtls_endpoint_aliases.${t}"`:`"as.${t}"`}`,e===void 0?Zn:Xn,{attribute:n?`mtls_endpoint_aliases.${t}`:t});return It(o,r),o}function re(e,t,n,r){return n&&e.mtls_endpoint_aliases&&t in e.mtls_endpoint_aliases?lt(e.mtls_endpoint_aliases[t],t,n,r):lt(e[t],t,n,r)}function Pt(e){return e instanceof V?e.cause.some(t=>t.scheme==="dpop"&&t.parameters.error==="use_dpop_nonce"):e instanceof W?e.error==="use_dpop_nonce":!1}var W=class extends Error{cause;code;error;status;error_description;response;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=Yn,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)}},Z=class extends Error{cause;code;error;error_description;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=Qn,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)}},V=class extends Error{cause;code;response;status;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=$n,this.cause=n.cause,this.status=n.response.status,this.response=n.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},pe="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",In="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",Pn='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',On="("+pe+")\\s*=\\s*"+Pn,Nn="("+pe+")\\s*=\\s*("+pe+")",xn=new RegExp("^[,\\s]*("+pe+")"),kn=new RegExp("^[,\\s]*"+On+"[,\\s]*(.*)"),Cn=new RegExp("^[,\\s]*"+Nn+"[,\\s]*(.*)"),vn=new RegExp("^("+In+")(?:$|[,\\s])(.*)");function Dn(e){if(!te(e,Response))throw w('"response" must be an instance of Response',T);let t=e.headers.get("www-authenticate");if(t===null)return;let n=[],r=t;for(;r;){let o=r.match(xn),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 f,m;if(o=r.match(kn)){[,f,m,r]=o,m.includes("\\")&&(m=m.replace(/\\([\s\S])/g,"$1")),u[f.toLowerCase()]=m;continue}if(o=r.match(Cn)){[,f,m,r]=o,u[f.toLowerCase()]=m;continue}if(o=r.match(vn)){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 Ln(e){if(e.status>399&&e.status<500){$e(e),yt(e);try{let t=await e.clone().json();if(L(t)&&typeof t.error=="string"&&t.error.length)return t}catch{}}}async function Ot(e,t,n){if(e.status!==t){jn(e);let r;throw(r=await Ln(e))?(await e.body?.cancel(),new W("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 Un(e){if(!We.has(e))throw w('"options.DPoP" is not a valid DPoPHandle',R)}var z,le,ve;function He(e,t,n,r){z||=new WeakMap,z.set(e,{jwks:t,uat:n,get age(){return K()-this.uat}}),r&&Object.assign(r,{jwks:structuredClone(t),uat:n})}function Hn(e){return!(typeof e!="object"||e===null||!("uat"in e)||typeof e.uat!="number"||K()-e.uat>=300||!("jwks"in e)||!L(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,L))}function ft(e,t){z?.delete(e),delete t?.jwks,delete t?.uat}async function je(e,t,n){let{alg:r,kid:o}=n;rr(n),!z?.has(e)&&Hn(t?.[O])&&He(e,t?.[O].jwks,t?.[O].uat);let s,a;if(z?.has(e)){if({jwks:s,age:a}=z.get(e),a>=300)return ft(e,t?.[O]),je(e,t,n)}else{let m=await er(e,t);s=m.jwks,a=K()-m.uat,He(e,s,m.uat,t?.[O])}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(m=>{if(m.kty!==i||o!==void 0&&o!==m.kid||m.alg!==void 0&&r!==m.alg||m.use!==void 0&&m.use!=="sig"||m.key_ops?.includes("verify")===!1)return!1;switch(!0){case(r==="ES256"&&m.crv!=="P-256"):case(r==="ES384"&&m.crv!=="P-384"):case(r==="ES512"&&m.crv!=="P-521"):case(r==="Ed25519"&&m.crv!=="Ed25519"):case(r==="EdDSA"&&m.crv!=="Ed25519"):return!1}return!0}),{0:u,length:d}=c;if(!d){if(a>=60)return ft(e,t?.[O]),je(e,t,n);throw h("error when selecting a JWT verification key, no applicable keys found",pt,{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',pt,{header:n,candidates:c,jwks_uri:new URL(e.jwks_uri)});ve||=new WeakMap;let l=ve.get(u);l||(l=new Map,ve.set(u,l));let f=l.get(r);return f||(f=lr(r,u).catch(m=>{throw l.delete(r),m}),l.set(r,f)),f}function ge(e){return e.headers.get("content-type")?.split(";")[0]}async function Nt(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?.[k]||fetch)(r.href,{body:o,headers:Object.fromEntries(s.entries()),method:"POST",redirect:"manual",signal:wt(r,a?.signal)})}async function xt(e,t,n,r,o,s){let a=re(e,"token_endpoint",t.use_mtls_endpoint_aliases,s?.[x]!==!0);o.set("grant_type",r);let i=qe(s?.headers);i.set("accept","application/json"),s?.DPoP!==void 0&&(Un(s.DPoP),await s.DPoP.addProof(a,i,"POST"));let c=await Nt(e,t,n,a,o,i,s);return s?.DPoP?.cacheNonce(c,a),c}async function kt(e,t,n,r,o){U(e),ne(t),_(r,'"refreshToken"');let s=new URLSearchParams(o?.additionalParameters);return s.set("refresh_token",r),xt(e,t,n,"refresh_token",s,o)}var Ct=new WeakMap,Je=new WeakMap;function Ee(e){if(!e.id_token)return;let t=Ct.get(e);if(!t)throw w('"ref" was already garbage collected or did not resolve from the proper sources',R);return t}async function vt(e,t,n){if(U(e),!Je.has(t))throw w('"ref" does not contain a processed JWT Response to verify the signature of',R);let{0:r,1:o,2:s}=Je.get(t).split("."),a=JSON.parse(Y(G(r)));if(a.alg.startsWith("HS"))throw new y("unsupported JWS algorithm",{cause:{alg:a.alg}});let i;i=await je(e,n,a),await sr(r,o,i,G(s))}async function Ge(e,t,n,r,o,s){if(U(e),ne(t),!te(n,Response))throw w('"response" must be an instance of Response',T);await Ot(n,200,"Token Endpoint"),$e(n);let a=await Ft(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;fe(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&&(fe(t.default_max_age,!0,'"client.default_max_age"'),i.push("auth_time")),r?.length&&i.push(...r);let{claims:c,jwt:u}=await Wn(e,t,a.id_token,i,o);Kn(t,c),Vn(c),Je.set(n,u),Ct.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 jn(e){let t;if(t=Dn(e))throw new V("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:t,response:e})}async function Dt(e,t,n,r){return Ge(e,t,n,void 0,r?.[M],r?.recognizedTokenTypes)}function Jn(e,t){if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e))throw h('unexpected JWT "aud" (audience) claim value',N,{expected:e,claims:t.claims,claim:"aud"})}else if(t.claims.aud!==e)throw h('unexpected JWT "aud" (audience) claim value',N,{expected:e,claims:t.claims,claim:"aud"});return t}function qn(e,t){let n=e[Ye]?.(t)??e.issuer;if(t.claims.iss!==n)throw h('unexpected JWT "iss" (issuer) claim value',N,{expected:n,claims:t.claims,claim:"iss"});return t}var We=new WeakSet;function zn(e){return We.add(e),e}var Ve=Symbol();async function Lt(e,t,n,r,o,s,a){if(U(e),ne(t),!We.has(r))throw w('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',R);_(o,'"redirectUri"');let i=D(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!==Ve&&(_(s,'"codeVerifier"'),c.set("code_verifier",s)),xt(e,t,n,"authorization_code",c,a)}var Ut={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 Mn(e,t){for(let n of e)if(t.claims[n]===void 0)throw h(`JWT "${n}" (${Ut[n]}) claim missing`,p,{claims:t.claims});return t}function Gn(e,t){if(typeof t.claims[e]!="string")throw h(`unexpected JWT "${e}" (${Ut[e]}) claim type`,p,{claims:t.claims});return t}function Wn(e,t,n,r,o){return ir(n,ur.bind(void 0,t.id_token_signed_response_alg,e.id_token_signing_alg_values_supported,"RS256"),St(t),bt(t),o).then(Mn.bind(void 0,["aud","exp","iat","iss","sub",...r])).then(qn.bind(void 0,e)).then(Jn.bind(void 0,t.client_id)).then(Gn.bind(void 0,"sub"))}function Ht(e,t){if(t===we)return t;let n=t===void 0;return n&&(t=e.default_max_age),t===void 0?we:(fe(t,!0,n?'"client.default_max_age"':'"maxAge" argument'),t)}function Vn(e){e.auth_time!==void 0&&fe(e.auth_time,!0,'ID Token "auth_time" (authentication time)',p,{claims:e})}function jt(e,t,n){if(n===we)return;let r=K()+St(e),o=bt(e);if(t.auth_time+n<r-o)throw h("too much time has elapsed since the last End-User authentication",ee,{claims:t,now:r,tolerance:o,claim:"auth_time"})}function Jt(e,t){let n=t===me?void 0:t;if(e.nonce!==n)throw h('unexpected ID Token "nonce" claim value',N,{expected:n,claims:e,claim:"nonce"})}function Kn(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',N,{claims:t,claim:"aud"});if(t.azp!==e.client_id)throw h('unexpected ID Token "azp" (authorized party) claim value',N,{expected:e.client_id,claims:t,claim:"azp"})}}var me=Symbol(),we=Symbol();async function qt(e,t,n,r){return typeof r?.expectedNonce=="string"||typeof r?.maxAge=="number"||r?.requireIdToken?Fn(e,t,n,r.expectedNonce,r.maxAge,r[M],r.recognizedTokenTypes):Bn(e,t,n,r?.maxAge,r?.[M],r?.recognizedTokenTypes)}async function Fn(e,t,n,r,o,s,a){let i=[];switch(r){case void 0:r=me;break;case me:break;default:_(r,'"expectedNonce" argument'),i.push("nonce")}o=Ht(t,o),o!==we&&i.push("auth_time");let c=await Ge(e,t,n,i,s,a);_(c.id_token,'"response" body "id_token" property',p,{body:c});let u=Ee(c);return jt(t,u,o),Jt(u,r),c}async function Bn(e,t,n,r,o,s){let a=await Ge(e,t,n,void 0,o,s),i=Ee(a);return i&&(jt(t,i,Ht(t,r)),Jt(i,me)),a}var $n="OAUTH_WWW_AUTHENTICATE_CHALLENGE",Yn="OAUTH_RESPONSE_BODY_ERROR",Re="OAUTH_UNSUPPORTED_OPERATION",Qn="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var X="OAUTH_PARSE_ERROR",p="OAUTH_INVALID_RESPONSE";var Ke="OAUTH_RESPONSE_IS_NOT_JSON",Ae="OAUTH_RESPONSE_IS_NOT_CONFORM",Fe="OAUTH_HTTP_REQUEST_FORBIDDEN",Be="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",ee="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",N="OAUTH_JWT_CLAIM_COMPARISON_FAILED",zt="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED",pt="OAUTH_KEY_SELECTION_FAILED",Zn="OAUTH_MISSING_SERVER_METADATA",Xn="OAUTH_INVALID_SERVER_METADATA";async function Mt(e,t,n,r,o){U(e),ne(t),_(r,'"token"');let s=re(e,"revocation_endpoint",t.use_mtls_endpoint_aliases,o?.[x]!==!0),a=new URLSearchParams(o?.additionalParameters);a.set("token",r);let i=qe(o?.headers);return i.delete("accept"),Nt(e,t,n,s,a,i,o)}async function Gt(e){if(!te(e,Response))throw w('"response" must be an instance of Response',T);await Ot(e,200,"Revocation Endpoint")}function $e(e){if(e.bodyUsed)throw w('"response" body has been used already',R)}async function er(e,t){U(e);let n=re(e,"jwks_uri",!1,t?.[x]!==!0),r=qe(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?.[k]||fetch,i=wt(n,t?.signal);le||=new WeakMap;let c=le.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(tr).then(d=>{let l=K();return He(e,d,l),{jwks:d,uat:l}}).finally(()=>{c.delete(u),c.size||le.delete(e)})};return c.add(u),le.set(e,c),u.promise}async function tr(e){if(!te(e,Response))throw w('"response" must be an instance of Response',T);if(e.status!==200)throw h('"response" is not a conform JSON Web Key Set response (unexpected HTTP status code)',Ae,e);$e(e);let t=await Ft(e,n=>Sn(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,L))throw h('"response" body "keys" property members must be JWK formatted objects',p,{body:t});return t}function nr(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 rr(e){if(!nr(e.alg))throw new y('unsupported JWS "alg" identifier',{cause:{alg:e.alg}})}function mt(e){let{algorithm:t}=e;if(typeof t.modulusLength!="number"||t.modulusLength<2048)throw new y(`unsupported ${t.name} modulusLength`,{cause:e})}function or(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 ar(e){switch(e.algorithm.name){case"ECDSA":return{name:e.algorithm.name,hash:or(e)};case"RSA-PSS":switch(mt(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 mt(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 sr(e,t,n,r){let o=Y(`${e}.${t}`),s=ar(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 ir(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(Y(G(s)))}catch(l){throw h("failed to parse JWT Header body as base64url encoded JSON",X,l)}if(!L(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(Y(G(a)))}catch(l){throw h("failed to parse JWT Payload body as base64url encoded JSON",X,l)}if(!L(u))throw h("JWT Payload must be a top level object",p,e);let d=K()+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',ee,{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',ee,{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 cr(e){if(e.bodyUsed)throw w("form_post Request instances must contain a readable body",R,{cause:e});return e.text()}async function Wt(e){if(e.method!=="POST")throw w("form_post responses are expected to use the POST method",R,{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",R,{cause:e});return cr(e)}function ur(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 D(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 Vt=Symbol(),dr=Symbol();function Kt(e,t,n,r){if(U(e),ne(t),n instanceof URL&&(n=n.searchParams),!(n instanceof URLSearchParams))throw w('"parameters" must be an instance of URLSearchParams, or URL',T);if(D(n,"response"))throw h('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',p,{parameters:n});let o=D(n,"iss"),s=D(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 dr:if(s!==void 0)throw h('unexpected "state" response parameter encountered',p,{expected:void 0,parameters:n});break;case Vt: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(D(n,"error"))throw new Z("authorization response from the server is an error",{cause:n});let i=D(n,"id_token"),c=D(n,"token");if(i!==void 0||c!==void 0)throw new y("implicit and hybrid flows are not supported");return zn(new URLSearchParams(n))}function hr(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 lr(e,t){let{ext:n,key_ops:r,use:o,...s}=t;return crypto.subtle.importKey("jwk",s,hr(e),!0,["verify"])}async function Ft(e,t=yt){let n;try{n=await e.json()}catch(r){throw t(e),h('failed to parse "response" body as JSON',X,r)}if(!L(n))throw h('"response" body must be a top level object',p,{body:n});return n}var Ye=Symbol();var se,Bt;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(Bt="openid-client/v6.8.7",se={"user-agent":Bt});var b=e=>Ze.get(e),Ze,Qe;function pr(e){return e!==void 0?Me(e):(Qe||=new WeakMap,(t,n,r,o)=>{let s;return(s=Qe.get(n))||(mr(n.client_secret,'"metadata.client_secret"'),s=Me(n.client_secret),Qe.set(n,s)),s(t,n,r,o)})}function mr(e,t){if(typeof e!="string")throw P(`${t} must be a string`,be);if(e.length===0)throw P(`${t} must not be empty`,ie)}function Xe(){return Tt()}var Se=k;var ie="ERR_INVALID_ARG_VALUE",be="ERR_INVALID_ARG_TYPE";function P(e,t,n){let r=new TypeError(e,{cause:n});return Object.assign(r,{code:t}),r}function $t(e){return At(e)}function Yt(){return gt()}function Qt(){return Rt()}function Zt(){return Et()}var ae=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=n?.code,Error.captureStackTrace?.(this,this.constructor)}},Zo=new TextDecoder;function g(e,t,n){return new ae(e,{cause:t,code:n})}function H(e){if(e instanceof TypeError||e instanceof ae||e instanceof W||e instanceof Z||e instanceof V)throw e;if(e instanceof Q)switch(e.code){case Fe:throw g("only requests to HTTPS are allowed",e,e.code);case Be:throw g("only requests to HTTP or HTTPS are allowed",e,e.code);case Ae:throw g("unexpected HTTP response status code",e.cause,e.code);case Ke:throw g("unexpected response content-type",e.cause,e.code);case X:throw g("parsing error occured",e,e.code);case p:throw g("invalid response encountered",e,e.code);case N:throw g("unexpected JWT claim value encountered",e,e.code);case zt:throw g("unexpected JSON attribute value encountered",e,e.code);case ee:throw g("JWT timestamp claim value failed validation",e,e.code);default:throw g(e.message,e,e.code)}if(e instanceof y)throw g("unsupported operation",e,e.code);if(e instanceof DOMException)switch(e.name){case"OperationError":throw g("runtime operation error",e,Re);case"NotSupportedError":throw g("runtime unsupported operation",e,Re);case"TimeoutError":throw g("operation timed out",e,"OAUTH_TIMEOUT");case"AbortError":throw g("operation aborted",e,"OAUTH_ABORT")}throw new ae("something went wrong",{cause:e})}function wr(e){return{supportsPKCE:{__proto__:null,value(t="S256"){return e.code_challenge_methods_supported?.includes(t)===!0}}}}function yr(e){Object.defineProperties(e,wr(e))}var _r=Symbol(),j=class{constructor(t,n,r,o){if(typeof n!="string"||!n.length)throw P('"clientId" must be a non-empty string',be);if(typeof r=="string"&&(r={client_secret:r}),r?.client_id!==void 0&&n!==r.client_id)throw P('"clientId" and "metadata.client_id" must be the same',ie);let s={...structuredClone(r),client_id:n};s[ye]=r?.[ye]??0,s[_e]=r?.[_e]??30;let a;o?a=o:typeof s.client_secret=="string"&&s.client_secret.length?a=pr(s.client_secret):a=Xe();let i=Object.freeze(s),c=structuredClone(t);_r in t&&(c[Ye]=({claims:{tid:d}})=>t.issuer.replace("{tenantid}",d));let u=Object.freeze(c);Ze||=new WeakMap,Ze.set(this,{__proto__:null,as:u,c:i,auth:a,tlsOnly:!0,jwksCache:{}})}serverMetadata(){let t=structuredClone(b(this).as);return yr(t),t}clientMetadata(){return structuredClone(b(this).c)}get timeout(){return b(this).timeout}set timeout(t){b(this).timeout=t}get[Se](){return b(this).fetch}set[Se](t){b(this).fetch=t}};Object.freeze(j.prototype);function gr(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 Ee(e)}}}}function Xt(e){Object.defineProperties(e,gr(e))}function en(e){ce(e),b(e).nonRepudiation=t=>{let{as:n,fetch:r,tlsOnly:o,timeout:s,jwksCache:a}=b(e);return vt(n,t,{[k]:r,[x]:!o,headers:new Headers(se),signal:Te(s),[O]:a}).catch(H)}}function Er(e){return e=new URL(e),e.search="",e.hash="",e.href}function Rr(e,t){try{return Object.getPrototypeOf(e)[Symbol.toStringTag]===t}catch{return!1}}async function et(e,t,n,r,o){if(ce(e),o?.flag!==oe&&!(t instanceof URL)&&!Rr(t,"Request"))throw P('"currentUrl" must be an instance of URL, or Request',be);let s,a,{as:i,c,auth:u,fetch:d,tlsOnly:l,jarm:f,hybrid:m,nonRepudiation:q,timeout:ue,decrypt:fn,implicit:pn}=b(e);if(o?.flag===oe)s=o.authResponse,a=o.redirectUri;else{if(!(t instanceof URL)){let v=t;switch(t=new URL(t.url),v.method){case"GET":break;case"POST":let st=new URLSearchParams(await Wt(v));if(m)t.hash=st.toString();else for(let[wn,yn]of st.entries())t.searchParams.append(wn,yn);break;default:throw P("unexpected Request HTTP method",ie)}}switch(a=Er(t),!0){case!!f:s=await f(t,n?.expectedState);break;case!!m:s=await m(t,n?.expectedNonce,n?.expectedState,n?.maxAge);break;case!!pn:throw new TypeError("authorizationCodeGrant() cannot be used by response_type=id_token clients");default:try{s=Kt(i,c,t.searchParams,n?.expectedState)}catch(v){H(v)}}}let at=await Lt(i,c,u,s,a,n?.pkceCodeVerifier||Ve,{additionalParameters:r,[k]:d,[x]:!l,DPoP:o?.DPoP,headers:new Headers(se),signal:Te(ue)}).catch(H);(typeof n?.expectedNonce=="string"||typeof n?.maxAge=="number")&&(n.idTokenExpected=!0);let mn=qt(i,c,at,{expectedNonce:n?.expectedNonce,maxAge:n?.maxAge,requireIdToken:n?.idTokenExpected,[M]:fn}),de;try{de=await mn}catch(v){if(nn(v,o))return et(e,void 0,n,r,{...o,flag:oe,authResponse:s,redirectUri:a});H(v)}return de.id_token&&await q?.(at),Xt(de),de}async function tt(e,t,n,r){ce(e),n=new URLSearchParams(n);let{as:o,c:s,auth:a,fetch:i,tlsOnly:c,nonRepudiation:u,timeout:d,decrypt:l}=b(e),f=await kt(o,s,a,t,{[k]:i,[x]:!c,additionalParameters:n,DPoP:r?.DPoP,headers:new Headers(se),signal:Te(d)}).catch(H),m=Dt(o,s,f,{[M]:l}),q;try{q=await m}catch(ue){if(nn(ue,r))return tt(e,t,n,{...r,flag:oe});H(ue)}return q.id_token&&await u?.(f),Xt(q),q}function tn(e,t){ce(e);let{as:n,c:r,tlsOnly:o,hybrid:s,jarm:a,implicit:i}=b(e),c=re(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 P("response_type=id_token clients must provide a nonce parameter in their authorization request parameters",ie);a&&t.set("response_mode","jwt")}for(let[u,d]of t.entries())c.searchParams.append(u,d);return c}function ce(e){if(!(e instanceof j))throw P('"config" must be an instance of Configuration',be);if(Object.getPrototypeOf(e)!==j.prototype)throw P("subclassing Configuration is not allowed",ie)}function Te(e){return e?AbortSignal.timeout(e*1e3):void 0}function nn(e,t){return t?.DPoP&&t.flag!==oe?Pt(e):!1}var oe=Symbol();async function rn(e,t,n){ce(e);let{as:r,c:o,auth:s,fetch:a,tlsOnly:i,timeout:c}=b(e);return Mt(r,o,s,t,{[k]:a,[x]:!i,additionalParameters:new URLSearchParams(n),headers:new Headers(se),signal:Te(c)}).then(Gt).catch(H)}import{createServer as Sr}from"node:http";async function on(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=Sr((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 f;try{f=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||f.origin+f.pathname!==e||f.searchParams.getAll("state").length!==1||f.searchParams.get("state")!==t||f.searchParams.getAll("code").length!==1&&!f.searchParams.has("error")){l.writeHead(400).end("Invalid callback.");return}a=!0,l.end("Authorization received. Return to Native Engagement."),o(f)});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 nt=3e4,J=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 j({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"},Xe()),this.config.timeout=nt/1e3,en(this.config),this.config[Se]=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(nt)]):AbortSignal.timeout(nt)})}}async authorize(t,n){let r=this.installation,o=Zt(),s=Qt(),a=Yt(),i=await on(r.redirectUri,o,t);try{let c=tn(this.config,{redirect_uri:r.redirectUri,state:o,nonce:s,scope:r.scopes.join(" "),resource:r.resource,code_challenge:await $t(a),code_challenge_method:"S256"});t.throwIfAborted(),await n(c.href);let u=await i.callback;t.throwIfAborted();let d=await et(this.config,u,{expectedState:o,expectedNonce:s,pkceCodeVerifier:a,idTokenExpected:!0},{resource:r.resource}),l=d.claims()?.sub,f=Number(d.expires_in);if(!d.access_token||!l||!Number.isSafeInteger(f)||f<1||f>86400)throw Error("DESKTOP_LOGIN_GRANT_INVALID");return{accessToken:d.access_token,refreshToken:d.refresh_token??null,subject:l,expiresAt:Date.now()+f*1e3}}finally{await i.close()}}async revoke(t){await rn(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 tt(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{execFile as br}from"node:child_process";var Tr=new Set(["openid","engagement:read","engagement:write","work:read","asset:reader","message:draft"]);async function rt(e="https://engagement.shipkitx.com",t=fetch){let n=new URL(e);if(n.protocol!=="https:"||n.origin!==e||n.username||n.password)throw Error("NATIVE_PUBLIC_LOGIN_HTTPS_CENTER_REQUIRED");let r=await t(e+"/releases/cli-login.json",{redirect:"error",signal:AbortSignal.timeout(1e4)});if(!r.ok||!r.body||Number(r.headers.get("content-length"))>32768)throw Error("NATIVE_PUBLIC_LOGIN_CONFIGURATION_UNAVAILABLE");let o=r.body.getReader(),s=[],a=0;try{for(;;){let d=await o.read();if(d.done)break;if(a+=d.value.byteLength,a>32768)throw Error("NATIVE_PUBLIC_LOGIN_CONFIGURATION_TOO_LARGE");s.push(d.value)}}finally{await o.cancel().catch(()=>{})}let i;try{i=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(Buffer.concat(s)))}catch{throw Error("NATIVE_PUBLIC_LOGIN_CONFIGURATION_INVALID")}let c=i.result?.login;if(i.ok!==!0||i.result?.serviceOrigin!==e||!c||new URL(c.issuer).origin!==e||c.resource!==e+"/mcp"||c.clientId!=="native-engagement-cli"||!Array.isArray(c.scopes)||!c.scopes.includes("openid")||c.scopes.some(d=>!Tr.has(d)))throw Error("NATIVE_PUBLIC_LOGIN_CONFIGURATION_INVALID");let u=new URL(c.redirectUri);if(u.protocol!=="http:"||u.hostname!=="127.0.0.1"||!u.port||u.username||u.password||u.search||u.hash)throw Error("NATIVE_PUBLIC_LOGIN_CALLBACK_INVALID");return new J(c,t)}async function ot(e){let t=new URL(e);if(t.protocol!=="https:"||t.username||t.password)throw Error("NATIVE_PUBLIC_LOGIN_AUTHORIZATION_URL_INVALID");let n=process.platform==="darwin"?"/usr/bin/open":process.platform==="win32"?"rundll32.exe":"/usr/bin/xdg-open",r=process.platform==="win32"?["url.dll,FileProtocolHandler",e]:[e];await new Promise((o,s)=>br(n,r,{timeout:1e4,windowsHide:!0},a=>a?s(Error("NATIVE_PUBLIC_LOGIN_BROWSER_UNAVAILABLE")):o()))}import I from"node:fs/promises";import{constants as an}from"node:fs";import Ir from"node:os";import C from"node:path";import{execFile as Pr}from"node:child_process";function Ie(e){return C.join(e.NATIVE_ENGAGEMENT_CLI_HOME??C.join(Ir.homedir(),".native-engagement-cli"),"session.json")}async function Pe(e,t){let n=C.dirname(e);if(!C.isAbsolute(n)||C.normalize(n)!==n)throw Error("CLI_PRIVATE_DIRECTORY_REQUIRED");t&&await I.mkdir(n,{recursive:!0,mode:448});let r=await I.lstat(n),o=await I.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 sn(e,t=process.env){if(process.platform==="win32")throw Error("CLI_MANUAL_BROWSER_UNAVAILABLE_USE_SYSTEM_BROWSER");let n=C.join(C.dirname(Ie(t)),"authorization-url.txt");await Pe(n,!0);let r=await I.open(n,"wx",384);try{await r.writeFile(e+`
34
+ `),await r.sync()}finally{await r.close()}return{file:n,async remove(){await I.unlink(n)}}}async function cn(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)=>{Pr(C.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 un(e,t=process.env){let n=Ie(t);await Pe(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 cn(r,!0)}):r,s=n+"."+process.pid+".new";try{let a=await I.open(s,"wx",384);try{await a.writeFile(o),await a.sync()}finally{await a.close()}await I.rename(s,n)}finally{await I.rm(s,{force:!0})}}async function Oe(e=process.env){let t=Ie(e);try{await Pe(t,!1);let n=await I.open(t,an.O_RDONLY|(process.platform==="win32"?0:an.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 cn(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 dn(e=process.env){let t=Ie(e);await Pe(t,!1),await I.unlink(t)}async function hn(e,t=process.env,n=!1){let r=await Oe(t);if(e==="status"){console.log(JSON.stringify({ok:!0,result:{authenticated:!!r&&r.grant.expiresAt>Date.now(),origin:r?.origin??null,expiresAt:r?new Date(r.grant.expiresAt).toISOString():null}}));return}if(e==="logout"){if(r)try{await new J(r.login).revoke(r.grant)}finally{await dn(t)}console.log(JSON.stringify({ok:!0,result:{authenticated:!1}}));return}if(e!=="login")throw Error("CLI_AUTH_OPERATION_INVALID");let o=t.NATIVE_ENGAGEMENT_API_URL??"https://engagement.shipkitx.com",s=new URL(o);if(s.protocol!=="https:"||s.origin!==o||s.username||s.password)throw Error("CLI_HTTPS_CENTER_REQUIRED");if(r&&r.origin!==o)throw Error("CLI_LOGOUT_BEFORE_CENTER_CHANGE");let a=await rt(o),i=new AbortController,c,u=()=>i.abort(),d=setTimeout(u,18e4);process.once("SIGINT",u),process.once("SIGTERM",u);try{console.error("Sign in with your account on the identity service browser page. The browser callback must reach this machine.");let l=await a.authorize(i.signal,async f=>{if(!n){await ot(f);return}c=await sn(f,t),console.error(JSON.stringify({event:"NATIVE_LOGIN_BROWSER_REQUIRED",authorizationUrlFile:c.file}))});try{await un({schemaVersion:1,origin:o,login:a.installation,grant:l},t)}catch(f){throw await a.revoke(l).catch(()=>{}),f}console.log(JSON.stringify({ok:!0,result:{authenticated:!0,expiresAt:new Date(l.expiresAt).toISOString()}}))}finally{try{await c?.remove()}finally{clearTimeout(d),process.removeListener("SIGINT",u),process.removeListener("SIGTERM",u)}}}var ln=JSON.parse(await Or(new URL("../package.json",import.meta.url),"utf8")),E=process.argv.slice(2);if(E.length===1&&["--version","-v"].includes(E[0]))console.log(ln.version);else if(F(E))console.log(`Native Engagement ${ln.version}
35
+
36
+ ${B}`);else try{if(E.length===1&&["login","logout"].includes(E[0])||E.length===2&&E[0]==="auth"&&E[1]==="status"||E.length===2&&E[0]==="login"&&E[1]==="--no-open")await hn(E[0]==="auth"?"status":E[0],process.env,E[1]==="--no-open");else{let e=process.env.NATIVE_ENGAGEMENT_BEARER_TOKEN?null:await Oe(),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 ht(E,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,6 @@
1
1
  {
2
2
  "name": "@native-engagement/cli",
3
- "version": "0.8.0",
3
+ "version": "0.8.2",
4
4
  "type": "module",
5
5
  "description": "Authenticated Native Engagement command line client",
6
6
  "engines": {
package/release.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "sourceCommit": "5402e30207f693b0a0e28cb49e54720b402e1db9",
3
+ "sourceCommit": "0270865d1f69c5c4c01d3acab37090346699763a",
4
4
  "channel": "beta",
5
5
  "bundledComponents": [
6
6
  {
@@ -14,5 +14,5 @@
14
14
  "license": "MIT"
15
15
  }
16
16
  ],
17
- "lockSha256": "421cbab359e454443023383a61d63b1fc9f562e79c4e7c5174b09bdfb640d76c"
17
+ "lockSha256": "6fed06159024d6c915e45acdd81734e0ec37fc25230cb6c1a9c00013d7a2ed66"
18
18
  }