@botparty/nextjs 0.0.42 → 0.0.44
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/add-service.d.ts +6 -0
- package/dist/cli/deploy-cmd.d.ts +5 -0
- package/dist/cli/helpers.d.ts +26 -0
- package/dist/cli.js +98 -52
- package/package.json +2 -2
package/dist/cli/helpers.d.ts
CHANGED
|
@@ -43,6 +43,32 @@ export declare function fetchRemoteJwks(domain: string): Promise<{
|
|
|
43
43
|
} | null>;
|
|
44
44
|
export declare function checkDns(domain: string, expectedValue: string): Promise<boolean>;
|
|
45
45
|
export declare function pollDns(domain: string, expectedValue: string): Promise<void>;
|
|
46
|
+
export declare function generateServiceToken(domain: string, privateKeyPem: string): Promise<string>;
|
|
47
|
+
export interface ServiceIndex {
|
|
48
|
+
name: string;
|
|
49
|
+
description: string;
|
|
50
|
+
version: string;
|
|
51
|
+
auth: string;
|
|
52
|
+
baseUrl: string;
|
|
53
|
+
actions: Array<{
|
|
54
|
+
slug: string;
|
|
55
|
+
endpoint: string;
|
|
56
|
+
method: string;
|
|
57
|
+
description: string;
|
|
58
|
+
}>;
|
|
59
|
+
}
|
|
60
|
+
export declare function fetchServiceIndex(serviceDomain: string): Promise<ServiceIndex>;
|
|
61
|
+
export declare function callService(serviceDomain: string, method: string, endpoint: string, namespace: string, token: string, body?: Record<string, unknown>): Promise<{
|
|
62
|
+
ok: boolean;
|
|
63
|
+
status: number;
|
|
64
|
+
data: Record<string, unknown>;
|
|
65
|
+
}>;
|
|
66
|
+
export declare function domainToSlug(domain: string): string;
|
|
67
|
+
export declare function requireEnvCredentials(cwd: string): {
|
|
68
|
+
domain: string;
|
|
69
|
+
privateKeyPem: string;
|
|
70
|
+
clientId: string;
|
|
71
|
+
};
|
|
46
72
|
export declare function detectPackageManager(dir: string): 'pnpm' | 'yarn' | 'npm';
|
|
47
73
|
export declare function runCommand(cmd: string, dir: string): void;
|
|
48
74
|
/** Detect if the project uses src/ directory */
|
package/dist/cli.js
CHANGED
|
@@ -1,13 +1,17 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var Ct=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import{existsSync as Ce,mkdirSync as ke,writeFileSync as me,readdirSync as Qt}from"fs";import{resolve as T}from"path";import{generateKeyPairSync as xt}from"crypto";var ee=new TextEncoder,te=new TextDecoder,dr=2**32;function _e(...e){let t=e.reduce((s,{length:o})=>s+o,0),r=new Uint8Array(t),n=0;for(let s of e)r.set(s,n),n+=s.length;return r}function re(e){let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");t[r]=n}return t}function ge(e){if(Uint8Array.prototype.toBase64)return e.toBase64();let t=32768,r=[];for(let n=0;n<e.length;n+=t)r.push(String.fromCharCode.apply(null,e.subarray(n,n+t)));return btoa(r.join(""))}function ne(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function Oe(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e=="string"?e:te.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=te.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return ne(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function W(e){let t=e;return typeof t=="string"&&(t=ee.encode(t)),Uint8Array.prototype.toBase64?t.toBase64({alphabet:"base64url",omitPadding:!0}):ge(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}var K=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),U=(e,t)=>e.name===t;function kt(e){return parseInt(e.name.slice(4),10)}function we(e,t){if(kt(e.hash)!==t)throw K(`SHA-${t}`,"algorithm.hash")}function Nt(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function _t(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function De(e,t,r){switch(t){case"HS256":case"HS384":case"HS512":{if(!U(e.algorithm,"HMAC"))throw K("HMAC");we(e.algorithm,parseInt(t.slice(2),10));break}case"RS256":case"RS384":case"RS512":{if(!U(e.algorithm,"RSASSA-PKCS1-v1_5"))throw K("RSASSA-PKCS1-v1_5");we(e.algorithm,parseInt(t.slice(2),10));break}case"PS256":case"PS384":case"PS512":{if(!U(e.algorithm,"RSA-PSS"))throw K("RSA-PSS");we(e.algorithm,parseInt(t.slice(2),10));break}case"Ed25519":case"EdDSA":{if(!U(e.algorithm,"Ed25519"))throw K("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!U(e.algorithm,t))throw K(t);break}case"ES256":case"ES384":case"ES512":{if(!U(e.algorithm,"ECDSA"))throw K("ECDSA");let n=Nt(t);if(e.algorithm.namedCurve!==n)throw K(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}_t(e,r)}function $e(e,t,...r){if(r=r.filter(Boolean),r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var se=(e,...t)=>$e("Key must be ",e,...t),xe=(e,t,...r)=>$e(`Key for the ${e} algorithm must be `,t,...r);var F=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(t,r){super(t,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};var x=class extends F{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"};var I=class extends F{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},oe=class extends F{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"};var G=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},V=e=>e?.[Symbol.toStringTag]==="KeyObject",be=e=>G(e)||V(e);var Sr=Symbol();function Se(e,t){if(e)throw new TypeError(`${t} can only be called once`)}var Ot=e=>typeof e=="object"&&e!==null;function Ee(e){if(!Ot(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function je(...e){let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let n of t){let s=Object.keys(n);if(!r||r.size===0){r=new Set(s);continue}for(let o of s){if(r.has(o))return!1;r.add(o)}}return!0}var X=e=>Ee(e)&&typeof e.kty=="string",Je=e=>e.kty!=="oct"&&(e.kty==="AKP"&&typeof e.priv=="string"||typeof e.d=="string"),We=e=>e.kty!=="oct"&&e.d===void 0&&e.priv===void 0,Ue=e=>e.kty==="oct"&&typeof e.k=="string";function $t(e,t){if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}function jt(e,t){let r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:e};default:throw new x(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function Jt(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(se(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}return De(t,e,r),t}async function Be(e,t,r){let n=await Jt(e,t,"sign");$t(e,n);let s=await crypto.subtle.sign(jt(e,n.algorithm),n,r);return new Uint8Array(s)}var ie='Invalid or unsupported JWK "alg" (Algorithm) Parameter value';function Wt(e){let t,r;switch(e.kty){case"AKP":{switch(e.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":t={name:e.alg},r=e.priv?["sign"]:["verify"];break;default:throw new x(ie)}break}case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new x(ie)}break}case"EC":{switch(e.alg){case"ES256":case"ES384":case"ES512":t={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[e.alg]},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new x(ie)}break}case"OKP":{switch(e.alg){case"Ed25519":case"EdDSA":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new x(ie)}break}default:throw new x('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}async function Le(e){if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:t,keyUsages:r}=Wt(e),n={...e};return n.kty!=="AKP"&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,t,e.ext??!(e.d||e.priv),e.key_ops??r)}var B="given KeyObject instance cannot be used for this algorithm",L,He=async(e,t,r,n=!1)=>{L||=new WeakMap;let s=L.get(e);if(s?.[r])return s[r];let o=await Le({...t,alg:r});return n&&Object.freeze(e),s?s[r]=o:L.set(e,{[r]:o}),o},Ut=(e,t)=>{L||=new WeakMap;let r=L.get(e);if(r?.[t])return r[t];let n=e.type==="public",s=!!n,o;if(e.asymmetricKeyType==="x25519"){switch(t){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError(B)}o=e.toCryptoKey(e.asymmetricKeyType,s,n?[]:["deriveBits"])}if(e.asymmetricKeyType==="ed25519"){if(t!=="EdDSA"&&t!=="Ed25519")throw new TypeError(B);o=e.toCryptoKey(e.asymmetricKeyType,s,[n?"verify":"sign"])}switch(e.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":{if(t!==e.asymmetricKeyType.toUpperCase())throw new TypeError(B);o=e.toCryptoKey(e.asymmetricKeyType,s,[n?"verify":"sign"])}}if(e.asymmetricKeyType==="rsa"){let i;switch(t){case"RSA-OAEP":i="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":i="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":i="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":i="SHA-512";break;default:throw new TypeError(B)}if(t.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:i},s,n?["encrypt"]:["decrypt"]);o=e.toCryptoKey({name:t.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:i},s,[n?"verify":"sign"])}if(e.asymmetricKeyType==="ec"){let a=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!a)throw new TypeError(B);let d={ES256:"P-256",ES384:"P-384",ES512:"P-521"};d[t]&&a===d[t]&&(o=e.toCryptoKey({name:"ECDSA",namedCurve:a},s,[n?"verify":"sign"])),t.startsWith("ECDH-ES")&&(o=e.toCryptoKey({name:"ECDH",namedCurve:a},s,n?[]:["deriveBits"]))}if(!o)throw new TypeError(B);return r?r[t]=o:L.set(e,{[t]:o}),o};async function Me(e,t){if(e instanceof Uint8Array||G(e))return e;if(V(e)){if(e.type==="secret")return e.export();if("toCryptoKey"in e&&typeof e.toCryptoKey=="function")try{return Ut(e,t)}catch(n){if(n instanceof TypeError)throw n}let r=e.export({format:"jwk"});return He(e,r,t)}if(X(e))return e.k?Oe(e.k):He(e,e,t,!0);throw new Error("unreachable")}var ve=(e,t)=>{if(e.byteLength!==t.length)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0},ze=e=>({data:e,pos:0}),N=e=>{let t=e.data[e.pos++];if(t&128){let r=t&127,n=0;for(let s=0;s<r;s++)n=n<<8|e.data[e.pos++];return n}return t};var _=(e,t,r)=>{if(e.data[e.pos++]!==t)throw new Error(r)},Ye=(e,t)=>{let r=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,r},Bt=e=>{_(e,6,"Expected algorithm OID");let t=N(e);return Ye(e,t)};function Lt(e){_(e,48,"Invalid PKCS#8 structure"),N(e),_(e,2,"Expected version field");let t=N(e);e.pos+=t,_(e,48,"Expected algorithm identifier");let r=N(e);return{algIdStart:e.pos,algIdLength:r}}function Ht(e){_(e,48,"Invalid SPKI structure"),N(e),_(e,48,"Expected algorithm identifier");let t=N(e);return{algIdStart:e.pos,algIdLength:t}}var qe=e=>{let t=Bt(e);if(ve(t,[43,101,110]))return"X25519";if(!ve(t,[42,134,72,206,61,2,1]))throw new Error("Unsupported key algorithm");_(e,6,"Expected curve OID");let r=N(e),n=Ye(e,r);for(let{name:s,oid:o}of[{name:"P-256",oid:[42,134,72,206,61,3,1,7]},{name:"P-384",oid:[43,129,4,0,34]},{name:"P-521",oid:[43,129,4,0,35]}])if(ve(n,o))return s;throw new Error("Unsupported named curve")},Fe=async(e,t,r,n)=>{let s,o,i=e==="spki",a=()=>i?["verify"]:["sign"],d=()=>i?["encrypt","wrapKey"]:["decrypt","unwrapKey"];switch(r){case"PS256":case"PS384":case"PS512":s={name:"RSA-PSS",hash:`SHA-${r.slice(-3)}`},o=a();break;case"RS256":case"RS384":case"RS512":s={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.slice(-3)}`},o=a();break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":s={name:"RSA-OAEP",hash:`SHA-${parseInt(r.slice(-3),10)||1}`},o=d();break;case"ES256":case"ES384":case"ES512":{s={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[r]},o=a();break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{try{let c=n.getNamedCurve(t);s=c==="X25519"?{name:"X25519"}:{name:"ECDH",namedCurve:c}}catch{throw new x("Invalid or unsupported key format")}o=i?[]:["deriveBits"];break}case"Ed25519":case"EdDSA":s={name:"Ed25519"},o=a();break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":s={name:r},o=a();break;default:throw new x('Invalid or unsupported "alg" (Algorithm) value')}return crypto.subtle.importKey(e,t,s,n?.extractable??!!i,o)},Ge=(e,t)=>ne(e.replace(t,"")),Ve=(e,t,r)=>{let n=Ge(e,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g),s=r;return t?.startsWith?.("ECDH-ES")&&(s||={},s.getNamedCurve=o=>{let i=ze(o);return Lt(i),qe(i)}),Fe("pkcs8",n,t,s)},Xe=(e,t,r)=>{let n=Ge(e,/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g),s=r;return t?.startsWith?.("ECDH-ES")&&(s||={},s.getNamedCurve=o=>{let i=ze(o);return Ht(i),qe(i)}),Fe("spki",n,t,s)};async function H(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return Xe(e,t,r)}async function M(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return Ve(e,t,r)}async function Ze(e){if(V(e))if(e.type==="secret")e=e.export();else return e.export({format:"jwk"});if(e instanceof Uint8Array)return{kty:"oct",k:W(e)};if(!G(e))throw new TypeError(se(e,"CryptoKey","KeyObject","Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:t,key_ops:r,alg:n,use:s,...o}=await crypto.subtle.exportKey("jwk",e);return o.kty==="AKP"&&(o.alg=n),o}async function P(e){return Ze(e)}function Qe(e,t,r,n,s){if(s.crit!==void 0&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(i=>typeof i!="string"||i.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o;r!==void 0?o=new Map([...Object.entries(r),...t.entries()]):o=t;for(let i of n.crit){if(!o.has(i))throw new x(`Extension Header Parameter "${i}" is not recognized`);if(s[i]===void 0)throw new e(`Extension Header Parameter "${i}" is missing`);if(o.get(i)&&n[i]===void 0)throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(n.crit)}var z=e=>e?.[Symbol.toStringTag],Ae=(e,t,r)=>{if(t.use!==void 0){let n;switch(r){case"sign":case"verify":n="sig";break;case"encrypt":case"decrypt":n="enc";break}if(t.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let n;switch(!0){case(r==="sign"||r==="verify"):case e==="dir":case e.includes("CBC-HS"):n=r;break;case e.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):!e.includes("GCM")&&e.endsWith("KW")?n=r==="encrypt"?"wrapKey":"unwrapKey":n=r;break;case(r==="encrypt"&&e.startsWith("RSA")):n="wrapKey";break;case r==="decrypt":n=e.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(n&&t.key_ops?.includes?.(n)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0},Mt=(e,t,r)=>{if(!(t instanceof Uint8Array)){if(X(t)){if(Ue(t)&&Ae(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!be(t))throw new TypeError(xe(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(t.type!=="secret")throw new TypeError(`${z(t)} instances for symmetric algorithms must be of type "secret"`)}},zt=(e,t,r)=>{if(X(t))switch(r){case"decrypt":case"sign":if(Je(t)&&Ae(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(We(t)&&Ae(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!be(t))throw new TypeError(xe(e,t,"CryptoKey","KeyObject","JSON Web Key"));if(t.type==="secret")throw new TypeError(`${z(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.type==="public")switch(r){case"sign":throw new TypeError(`${z(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${z(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if(t.type==="private")switch(r){case"verify":throw new TypeError(`${z(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${z(t)} instances for asymmetric algorithm encryption must be of type "public"`)}};function et(e,t,r){switch(e.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":Mt(e,t,r);break;default:zt(e,t,r)}}var O=e=>Math.floor(e.getTime()/1e3),tt=60,rt=tt*60,Pe=rt*24,Yt=Pe*7,qt=Pe*365.25,Ft=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Te(e){let t=Ft.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),n=t[3].toLowerCase(),s;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":s=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":s=Math.round(r*tt);break;case"hour":case"hours":case"hr":case"hrs":case"h":s=Math.round(r*rt);break;case"day":case"days":case"d":s=Math.round(r*Pe);break;case"week":case"weeks":case"w":s=Math.round(r*Yt);break;default:s=Math.round(r*qt);break}return t[1]==="-"||t[4]==="ago"?-s:s}function D(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var ae=class{#e;constructor(t){if(!Ee(t))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(t)}data(){return ee.encode(JSON.stringify(this.#e))}get iss(){return this.#e.iss}set iss(t){this.#e.iss=t}get sub(){return this.#e.sub}set sub(t){this.#e.sub=t}get aud(){return this.#e.aud}set aud(t){this.#e.aud=t}set jti(t){this.#e.jti=t}set nbf(t){typeof t=="number"?this.#e.nbf=D("setNotBefore",t):t instanceof Date?this.#e.nbf=D("setNotBefore",O(t)):this.#e.nbf=O(new Date)+Te(t)}set exp(t){typeof t=="number"?this.#e.exp=D("setExpirationTime",t):t instanceof Date?this.#e.exp=D("setExpirationTime",O(t)):this.#e.exp=O(new Date)+Te(t)}set iat(t){t===void 0?this.#e.iat=O(new Date):t instanceof Date?this.#e.iat=D("setIssuedAt",O(t)):typeof t=="string"?this.#e.iat=D("setIssuedAt",O(new Date)+Te(t)):this.#e.iat=D("setIssuedAt",t)}};var ce=class{#e;#t;#r;constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this.#e=t}setProtectedHeader(t){return Se(this.#t,"setProtectedHeader"),this.#t=t,this}setUnprotectedHeader(t){return Se(this.#r,"setUnprotectedHeader"),this.#r=t,this}async sign(t,r){if(!this.#t&&!this.#r)throw new I("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!je(this.#t,this.#r))throw new I("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this.#t,...this.#r},s=Qe(I,new Map([["b64",!0]]),r?.crit,this.#t,n),o=!0;if(s.has("b64")&&(o=this.#t.b64,typeof o!="boolean"))throw new I('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=n;if(typeof i!="string"||!i)throw new I('JWS "alg" (Algorithm) Header Parameter missing or invalid');et(i,t,"sign");let a,d;o?(a=W(this.#e),d=re(a)):(d=this.#e,a="");let c,b;this.#t?(c=W(JSON.stringify(this.#t)),b=re(c)):(c="",b=new Uint8Array);let S=_e(b,re("."),d),J=await Me(t,i),R=await Be(i,J,S),y={signature:W(R),payload:a};return this.#r&&(y.header=this.#r),this.#t&&(y.protected=c),y}};var pe=class{#e;constructor(t){this.#e=new ce(t)}setProtectedHeader(t){return this.#e.setProtectedHeader(t),this}async sign(t,r){let n=await this.#e.sign(t,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}};var Z=class{#e;#t;constructor(t={}){this.#t=new ae(t)}setIssuer(t){return this.#t.iss=t,this}setSubject(t){return this.#t.sub=t,this}setAudience(t){return this.#t.aud=t,this}setJti(t){return this.#t.jti=t,this}setNotBefore(t){return this.#t.nbf=t,this}setExpirationTime(t){return this.#t.exp=t,this}setIssuedAt(t){return this.#t.iat=t,this}setProtectedHeader(t){return this.#e=t,this}async sign(t,r){let n=new pe(this.#t.data());if(n.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes("b64")&&this.#e.b64===!1)throw new oe("JWTs MUST NOT use unencoded payload");return n.sign(t,r)}};import{existsSync as v,mkdirSync as Rn,readFileSync as nt,writeFileSync as Gt}from"fs";import{resolve as A}from"path";import{execSync as Vt}from"child_process";var Xt="https://id.botparty.club";function m(e){console.log(` ${e}`)}function l(e){console.log(` \u2713 ${e}`)}function f(e){console.log(` \u26A0 ${e}`)}function g(e){console.error(` \u2717 ${e}`)}function h(e){console.log(`
|
|
2
|
+
var Bt=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import{existsSync as Oe,mkdirSync as $e,writeFileSync as ge,readdirSync as dr}from"fs";import{resolve as I}from"path";import{generateKeyPairSync as Et}from"crypto";var te=new TextEncoder,re=new TextDecoder,Wr=2**32;function je(...e){let t=e.reduce((s,{length:o})=>s+o,0),r=new Uint8Array(t),n=0;for(let s of e)r.set(s,n),n+=s.length;return r}function ne(e){let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++){let n=e.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");t[r]=n}return t}function Se(e){if(Uint8Array.prototype.toBase64)return e.toBase64();let t=32768,r=[];for(let n=0;n<e.length;n+=t)r.push(String.fromCharCode.apply(null,e.subarray(n,n+t)));return btoa(r.join(""))}function se(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function Je(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e=="string"?e:re.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=re.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return se(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function L(e){let t=e;return typeof t=="string"&&(t=te.encode(t)),Uint8Array.prototype.toBase64?t.toBase64({alphabet:"base64url",omitPadding:!0}):Se(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}var K=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),H=(e,t)=>e.name===t;function Lt(e){return parseInt(e.name.slice(4),10)}function ve(e,t){if(Lt(e.hash)!==t)throw K(`SHA-${t}`,"algorithm.hash")}function Ht(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Mt(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function We(e,t,r){switch(t){case"HS256":case"HS384":case"HS512":{if(!H(e.algorithm,"HMAC"))throw K("HMAC");ve(e.algorithm,parseInt(t.slice(2),10));break}case"RS256":case"RS384":case"RS512":{if(!H(e.algorithm,"RSASSA-PKCS1-v1_5"))throw K("RSASSA-PKCS1-v1_5");ve(e.algorithm,parseInt(t.slice(2),10));break}case"PS256":case"PS384":case"PS512":{if(!H(e.algorithm,"RSA-PSS"))throw K("RSA-PSS");ve(e.algorithm,parseInt(t.slice(2),10));break}case"Ed25519":case"EdDSA":{if(!H(e.algorithm,"Ed25519"))throw K("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!H(e.algorithm,t))throw K(t);break}case"ES256":case"ES384":case"ES512":{if(!H(e.algorithm,"ECDSA"))throw K("ECDSA");let n=Ht(t);if(e.algorithm.namedCurve!==n)throw K(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Mt(e,r)}function Ue(e,t,...r){if(r=r.filter(Boolean),r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var oe=(e,...t)=>Ue("Key must be ",e,...t),Ee=(e,t,...r)=>Ue(`Key for the ${e} algorithm must be `,t,...r);var V=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(t,r){super(t,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};var S=class extends V{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"};var N=class extends V{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},ie=class extends V{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"};var X=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},Z=e=>e?.[Symbol.toStringTag]==="KeyObject",Ae=e=>X(e)||Z(e);var Gr=Symbol();function Te(e,t){if(e)throw new TypeError(`${t} can only be called once`)}var zt=e=>typeof e=="object"&&e!==null;function Re(e){if(!zt(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function Be(...e){let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let n of t){let s=Object.keys(n);if(!r||r.size===0){r=new Set(s);continue}for(let o of s){if(r.has(o))return!1;r.add(o)}}return!0}var Q=e=>Re(e)&&typeof e.kty=="string",Le=e=>e.kty!=="oct"&&(e.kty==="AKP"&&typeof e.priv=="string"||typeof e.d=="string"),He=e=>e.kty!=="oct"&&e.d===void 0&&e.priv===void 0,Me=e=>e.kty==="oct"&&typeof e.k=="string";function Ft(e,t){if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}function qt(e,t){let r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(e.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:e};default:throw new S(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function Gt(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(oe(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}return We(t,e,r),t}async function ze(e,t,r){let n=await Gt(e,t,"sign");Ft(e,n);let s=await crypto.subtle.sign(qt(e,n.algorithm),n,r);return new Uint8Array(s)}var ae='Invalid or unsupported JWK "alg" (Algorithm) Parameter value';function Vt(e){let t,r;switch(e.kty){case"AKP":{switch(e.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":t={name:e.alg},r=e.priv?["sign"]:["verify"];break;default:throw new S(ae)}break}case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new S(ae)}break}case"EC":{switch(e.alg){case"ES256":case"ES384":case"ES512":t={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[e.alg]},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new S(ae)}break}case"OKP":{switch(e.alg){case"Ed25519":case"EdDSA":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new S(ae)}break}default:throw new S('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}async function Ye(e){if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:t,keyUsages:r}=Vt(e),n={...e};return n.kty!=="AKP"&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,t,e.ext??!(e.d||e.priv),e.key_ops??r)}var M="given KeyObject instance cannot be used for this algorithm",z,Fe=async(e,t,r,n=!1)=>{z||=new WeakMap;let s=z.get(e);if(s?.[r])return s[r];let o=await Ye({...t,alg:r});return n&&Object.freeze(e),s?s[r]=o:z.set(e,{[r]:o}),o},Xt=(e,t)=>{z||=new WeakMap;let r=z.get(e);if(r?.[t])return r[t];let n=e.type==="public",s=!!n,o;if(e.asymmetricKeyType==="x25519"){switch(t){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError(M)}o=e.toCryptoKey(e.asymmetricKeyType,s,n?[]:["deriveBits"])}if(e.asymmetricKeyType==="ed25519"){if(t!=="EdDSA"&&t!=="Ed25519")throw new TypeError(M);o=e.toCryptoKey(e.asymmetricKeyType,s,[n?"verify":"sign"])}switch(e.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":{if(t!==e.asymmetricKeyType.toUpperCase())throw new TypeError(M);o=e.toCryptoKey(e.asymmetricKeyType,s,[n?"verify":"sign"])}}if(e.asymmetricKeyType==="rsa"){let i;switch(t){case"RSA-OAEP":i="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":i="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":i="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":i="SHA-512";break;default:throw new TypeError(M)}if(t.startsWith("RSA-OAEP"))return e.toCryptoKey({name:"RSA-OAEP",hash:i},s,n?["encrypt"]:["decrypt"]);o=e.toCryptoKey({name:t.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:i},s,[n?"verify":"sign"])}if(e.asymmetricKeyType==="ec"){let a=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!a)throw new TypeError(M);let p={ES256:"P-256",ES384:"P-384",ES512:"P-521"};p[t]&&a===p[t]&&(o=e.toCryptoKey({name:"ECDSA",namedCurve:a},s,[n?"verify":"sign"])),t.startsWith("ECDH-ES")&&(o=e.toCryptoKey({name:"ECDH",namedCurve:a},s,n?[]:["deriveBits"]))}if(!o)throw new TypeError(M);return r?r[t]=o:z.set(e,{[t]:o}),o};async function qe(e,t){if(e instanceof Uint8Array||X(e))return e;if(Z(e)){if(e.type==="secret")return e.export();if("toCryptoKey"in e&&typeof e.toCryptoKey=="function")try{return Xt(e,t)}catch(n){if(n instanceof TypeError)throw n}let r=e.export({format:"jwk"});return Fe(e,r,t)}if(Q(e))return e.k?Je(e.k):Fe(e,e,t,!0);throw new Error("unreachable")}var Pe=(e,t)=>{if(e.byteLength!==t.length)return!1;for(let r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0},Ge=e=>({data:e,pos:0}),$=e=>{let t=e.data[e.pos++];if(t&128){let r=t&127,n=0;for(let s=0;s<r;s++)n=n<<8|e.data[e.pos++];return n}return t};var D=(e,t,r)=>{if(e.data[e.pos++]!==t)throw new Error(r)},Ve=(e,t)=>{let r=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,r},Zt=e=>{D(e,6,"Expected algorithm OID");let t=$(e);return Ve(e,t)};function Qt(e){D(e,48,"Invalid PKCS#8 structure"),$(e),D(e,2,"Expected version field");let t=$(e);e.pos+=t,D(e,48,"Expected algorithm identifier");let r=$(e);return{algIdStart:e.pos,algIdLength:r}}function er(e){D(e,48,"Invalid SPKI structure"),$(e),D(e,48,"Expected algorithm identifier");let t=$(e);return{algIdStart:e.pos,algIdLength:t}}var Xe=e=>{let t=Zt(e);if(Pe(t,[43,101,110]))return"X25519";if(!Pe(t,[42,134,72,206,61,2,1]))throw new Error("Unsupported key algorithm");D(e,6,"Expected curve OID");let r=$(e),n=Ve(e,r);for(let{name:s,oid:o}of[{name:"P-256",oid:[42,134,72,206,61,3,1,7]},{name:"P-384",oid:[43,129,4,0,34]},{name:"P-521",oid:[43,129,4,0,35]}])if(Pe(n,o))return s;throw new Error("Unsupported named curve")},Ze=async(e,t,r,n)=>{let s,o,i=e==="spki",a=()=>i?["verify"]:["sign"],p=()=>i?["encrypt","wrapKey"]:["decrypt","unwrapKey"];switch(r){case"PS256":case"PS384":case"PS512":s={name:"RSA-PSS",hash:`SHA-${r.slice(-3)}`},o=a();break;case"RS256":case"RS384":case"RS512":s={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.slice(-3)}`},o=a();break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":s={name:"RSA-OAEP",hash:`SHA-${parseInt(r.slice(-3),10)||1}`},o=p();break;case"ES256":case"ES384":case"ES512":{s={name:"ECDSA",namedCurve:{ES256:"P-256",ES384:"P-384",ES512:"P-521"}[r]},o=a();break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{try{let c=n.getNamedCurve(t);s=c==="X25519"?{name:"X25519"}:{name:"ECDH",namedCurve:c}}catch{throw new S("Invalid or unsupported key format")}o=i?[]:["deriveBits"];break}case"Ed25519":case"EdDSA":s={name:"Ed25519"},o=a();break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":s={name:r},o=a();break;default:throw new S('Invalid or unsupported "alg" (Algorithm) value')}return crypto.subtle.importKey(e,t,s,n?.extractable??!!i,o)},Qe=(e,t)=>se(e.replace(t,"")),et=(e,t,r)=>{let n=Qe(e,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g),s=r;return t?.startsWith?.("ECDH-ES")&&(s||={},s.getNamedCurve=o=>{let i=Ge(o);return Qt(i),Xe(i)}),Ze("pkcs8",n,t,s)},tt=(e,t,r)=>{let n=Qe(e,/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g),s=r;return t?.startsWith?.("ECDH-ES")&&(s||={},s.getNamedCurve=o=>{let i=Ge(o);return er(i),Xe(i)}),Ze("spki",n,t,s)};async function Y(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return tt(e,t,r)}async function j(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return et(e,t,r)}async function rt(e){if(Z(e))if(e.type==="secret")e=e.export();else return e.export({format:"jwk"});if(e instanceof Uint8Array)return{kty:"oct",k:L(e)};if(!X(e))throw new TypeError(oe(e,"CryptoKey","KeyObject","Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:t,key_ops:r,alg:n,use:s,...o}=await crypto.subtle.exportKey("jwk",e);return o.kty==="AKP"&&(o.alg=n),o}async function C(e){return rt(e)}function nt(e,t,r,n,s){if(s.crit!==void 0&&n?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(i=>typeof i!="string"||i.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o;r!==void 0?o=new Map([...Object.entries(r),...t.entries()]):o=t;for(let i of n.crit){if(!o.has(i))throw new S(`Extension Header Parameter "${i}" is not recognized`);if(s[i]===void 0)throw new e(`Extension Header Parameter "${i}" is missing`);if(o.get(i)&&n[i]===void 0)throw new e(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(n.crit)}var F=e=>e?.[Symbol.toStringTag],ke=(e,t,r)=>{if(t.use!==void 0){let n;switch(r){case"sign":case"verify":n="sig";break;case"encrypt":case"decrypt":n="enc";break}if(t.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let n;switch(!0){case(r==="sign"||r==="verify"):case e==="dir":case e.includes("CBC-HS"):n=r;break;case e.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):!e.includes("GCM")&&e.endsWith("KW")?n=r==="encrypt"?"wrapKey":"unwrapKey":n=r;break;case(r==="encrypt"&&e.startsWith("RSA")):n="wrapKey";break;case r==="decrypt":n=e.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(n&&t.key_ops?.includes?.(n)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0},tr=(e,t,r)=>{if(!(t instanceof Uint8Array)){if(Q(t)){if(Me(t)&&ke(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Ae(t))throw new TypeError(Ee(e,t,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(t.type!=="secret")throw new TypeError(`${F(t)} instances for symmetric algorithms must be of type "secret"`)}},rr=(e,t,r)=>{if(Q(t))switch(r){case"decrypt":case"sign":if(Le(t)&&ke(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(He(t)&&ke(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!Ae(t))throw new TypeError(Ee(e,t,"CryptoKey","KeyObject","JSON Web Key"));if(t.type==="secret")throw new TypeError(`${F(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.type==="public")switch(r){case"sign":throw new TypeError(`${F(t)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${F(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if(t.type==="private")switch(r){case"verify":throw new TypeError(`${F(t)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${F(t)} instances for asymmetric algorithm encryption must be of type "public"`)}};function st(e,t,r){switch(e.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":tr(e,t,r);break;default:rr(e,t,r)}}var J=e=>Math.floor(e.getTime()/1e3),ot=60,it=ot*60,Ce=it*24,nr=Ce*7,sr=Ce*365.25,or=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Ie(e){let t=or.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let r=parseFloat(t[2]),n=t[3].toLowerCase(),s;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":s=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":s=Math.round(r*ot);break;case"hour":case"hours":case"hr":case"hrs":case"h":s=Math.round(r*it);break;case"day":case"days":case"d":s=Math.round(r*Ce);break;case"week":case"weeks":case"w":s=Math.round(r*nr);break;default:s=Math.round(r*sr);break}return t[1]==="-"||t[4]==="ago"?-s:s}function W(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var ce=class{#e;constructor(t){if(!Re(t))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(t)}data(){return te.encode(JSON.stringify(this.#e))}get iss(){return this.#e.iss}set iss(t){this.#e.iss=t}get sub(){return this.#e.sub}set sub(t){this.#e.sub=t}get aud(){return this.#e.aud}set aud(t){this.#e.aud=t}set jti(t){this.#e.jti=t}set nbf(t){typeof t=="number"?this.#e.nbf=W("setNotBefore",t):t instanceof Date?this.#e.nbf=W("setNotBefore",J(t)):this.#e.nbf=J(new Date)+Ie(t)}set exp(t){typeof t=="number"?this.#e.exp=W("setExpirationTime",t):t instanceof Date?this.#e.exp=W("setExpirationTime",J(t)):this.#e.exp=J(new Date)+Ie(t)}set iat(t){t===void 0?this.#e.iat=J(new Date):t instanceof Date?this.#e.iat=W("setIssuedAt",J(t)):typeof t=="string"?this.#e.iat=W("setIssuedAt",J(new Date)+Ie(t)):this.#e.iat=W("setIssuedAt",t)}};var le=class{#e;#t;#r;constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this.#e=t}setProtectedHeader(t){return Te(this.#t,"setProtectedHeader"),this.#t=t,this}setUnprotectedHeader(t){return Te(this.#r,"setUnprotectedHeader"),this.#r=t,this}async sign(t,r){if(!this.#t&&!this.#r)throw new N("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Be(this.#t,this.#r))throw new N("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this.#t,...this.#r},s=nt(N,new Map([["b64",!0]]),r?.crit,this.#t,n),o=!0;if(s.has("b64")&&(o=this.#t.b64,typeof o!="boolean"))throw new N('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=n;if(typeof i!="string"||!i)throw new N('JWS "alg" (Algorithm) Header Parameter missing or invalid');st(i,t,"sign");let a,p;o?(a=L(this.#e),p=ne(a)):(p=this.#e,a="");let c,g;this.#t?(c=L(JSON.stringify(this.#t)),g=ne(c)):(c="",g=new Uint8Array);let x=je(g,ne("."),p),v=await qe(t,i),E=await ze(i,v,x),w={signature:L(E),payload:a};return this.#r&&(w.header=this.#r),this.#t&&(w.protected=c),w}};var pe=class{#e;constructor(t){this.#e=new le(t)}setProtectedHeader(t){return this.#e.setProtectedHeader(t),this}async sign(t,r){let n=await this.#e.sign(t,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}};var q=class{#e;#t;constructor(t={}){this.#t=new ce(t)}setIssuer(t){return this.#t.iss=t,this}setSubject(t){return this.#t.sub=t,this}setAudience(t){return this.#t.aud=t,this}setJti(t){return this.#t.jti=t,this}setNotBefore(t){return this.#t.nbf=t,this}setExpirationTime(t){return this.#t.exp=t,this}setIssuedAt(t){return this.#t.iat=t,this}setProtectedHeader(t){return this.#e=t,this}async sign(t,r){let n=new pe(this.#t.data());if(n.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes("b64")&&this.#e.b64===!1)throw new ie("JWTs MUST NOT use unencoded payload");return n.sign(t,r)}};import{existsSync as T,mkdirSync as ts,readFileSync as at,writeFileSync as ir}from"fs";import{resolve as R}from"path";import{execSync as ar}from"child_process";var cr="https://id.botparty.club";function l(e){console.log(` ${e}`)}function d(e){console.log(` \u2713 ${e}`)}function m(e){console.log(` \u26A0 ${e}`)}function h(e){console.error(` \u2717 ${e}`)}function f(e){console.log(`
|
|
3
3
|
${e}
|
|
4
|
-
${"\u2500".repeat(e.length)}`)}function
|
|
5
|
-
`)){let o=s.trim();if(!o||o.startsWith("#"))continue;let i=o.indexOf("=");if(i<=0)continue;let a=o.slice(0,i).trim(),
|
|
4
|
+
${"\u2500".repeat(e.length)}`)}function P(e){let t=R(e,".env");if(!T(t))return{};let r=at(t,"utf-8"),n={};for(let s of r.split(`
|
|
5
|
+
`)){let o=s.trim();if(!o||o.startsWith("#"))continue;let i=o.indexOf("=");if(i<=0)continue;let a=o.slice(0,i).trim(),p=o.slice(i+1).trim();(p.startsWith('"')&&p.endsWith('"')||p.startsWith("'")&&p.endsWith("'"))&&(p=p.slice(1,-1)),n[a]=p}return n}function _(e,t){let r=R(e,".env"),n="";T(r)&&(n=at(r,"utf-8"));for(let[s,o]of Object.entries(t)){let i=new RegExp(`^${s}=.*$`,"m");i.test(n)?n=n.replace(i,`${s}=${o}`):(n&&!n.endsWith(`
|
|
6
6
|
`)&&(n+=`
|
|
7
7
|
`),n+=`${s}=${o}
|
|
8
|
-
`)}
|
|
9
|
-
`),"ES256");return new
|
|
10
|
-
`),"ES256"),r=await
|
|
8
|
+
`)}ir(r,n)}function U(){return process.env.BOTPARTY_AUTH_URL||cr}async function Ne(e,t){let r=U(),n=await j(t.replace(/\\n/g,`
|
|
9
|
+
`),"ES256");return new q({}).setProtectedHeader({alg:"ES256"}).setIssuer(e).setSubject(e).setAudience(`${r}/oauth/token`).setIssuedAt().setExpirationTime("60s").setJti(crypto.randomUUID()).sign(n)}async function de(e,t){try{let r=await Ne(e,t),n=U();return(await fetch(`${n}/api/v1/clients/${e}`,{headers:{Authorization:`ClientAssertion ${r}`,"X-Client-Id":e}})).ok}catch{return!1}}async function ct(e,t){let r=await fetch(`${U()}/api/v1/clients/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e,force:t})});if(!r.ok){let s=await r.json().catch(()=>({}));throw new Error(s.error||`Registration failed (${r.status})`)}return{txtRecord:(await r.json()).txtRecord}}async function lt(e,t){let r=await fetch(`${U()}/api/v1/clients/register/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e,...t})});if(!r.ok){let s=await r.json().catch(()=>({}));throw new Error(s.error||`Verification failed (${r.status})`)}let n=await r.json();return{clientId:n.clientId,domain:n.domain}}async function O(e,t){try{let r=await Ne(e,t),n=U(),s=await fetch(`${n}/api/v1/clients/${e}`,{headers:{Authorization:`ClientAssertion ${r}`,"X-Client-Id":e}});return s.ok?await s.json():null}catch{return null}}async function G(e,t,r){try{let n=await Ne(e,t),s=U();return(await fetch(`${s}/api/v1/clients/${e}`,{method:"PATCH",headers:{Authorization:`ClientAssertion ${n}`,"X-Client-Id":e,"Content-Type":"application/json"},body:JSON.stringify({publicKey:r})})).ok}catch{return!1}}async function ee(e){let t=await j(e.replace(/\\n/g,`
|
|
10
|
+
`),"ES256"),r=await C(t),{d:n,...s}=r;return{...s,use:"sig",alg:"ES256"}}async function ue(e){let t=U();try{let r=await fetch(`${t}/api/v1/namespaces/${encodeURIComponent(e)}/jwks.json?bypass-cache=true`);return r.ok?await r.json():null}catch{return null}}function lr(e){let t=e.split("."),r=t.length>2?t.slice(-2).join("."):e,n=t.length>2?e.slice(0,e.length-r.length-1):"",s=[e,`_botparty.${e}`,...r!==e?[r,`${n}._botparty.${r}`]:[]];return[...new Set(s)]}async function pt(e,t){let r=await import("dns"),{resolveTxt:n}=r.promises,s=lr(e);for(let o of s)try{if((await n(o)).flat().some(p=>p===t||p.includes(t)))return!0}catch{}return!1}async function me(e,t){let r=await j(t.replace(/\\n/g,`
|
|
11
|
+
`),"ES256");return new q({role:"admin"}).setProtectedHeader({alg:"ES256"}).setIssuer(e).setSubject(e).setIssuedAt().setExpirationTime("5m").sign(r)}async function pr(e){let t=`https://${e}/.well-known/botparty/services.json`,r=await fetch(t);if(!r.ok)throw new Error(`Failed to fetch services from ${e} (${r.status})`);return r.json()}async function k(e,t,r,n,s,o){let a=(await pr(e)).baseUrl.replace("{namespace}",n),p=`https://${e}${a}${r}`,c={method:t,headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}};o&&["POST","PUT","PATCH"].includes(t)&&(c.body=JSON.stringify(o));let g=await fetch(p,c),x=await g.json().catch(()=>({}));return{ok:g.ok,status:g.status,data:x}}function fe(e){return e.replace(/\./g,"-")}function ye(e){let t=P(e),r=t.BOTPARTY_DOMAIN||"",n=t.BOTPARTY_CLIENT_ASSERTION_KEY?.replace(/\\n/g,`
|
|
12
|
+
`)||"",s=t.BOTPARTY_CLIENT_ID||"";return(!r||!n||!s)&&(h("BotParty credentials not found in .env"),l("Run init first:"),console.log(`
|
|
13
|
+
npx @botparty/nextjs init --domain <your-domain>
|
|
14
|
+
`),process.exit(1)),{domain:r,privateKeyPem:n,clientId:s}}function _e(e){return T(R(e,"pnpm-lock.yaml"))?"pnpm":T(R(e,"yarn.lock"))?"yarn":"npm"}function he(e,t){ar(e,{cwd:t,stdio:"inherit"})}function dt(e){return T(R(e,"src"))}function ut(e){return T(R(e,"middleware.ts"))||T(R(e,"middleware.js"))||T(R(e,"src/middleware.ts"))||T(R(e,"src/middleware.js"))}function B(e){return T(R(e,"src/app"))?"src/app":T(R(e,"app"))?"app":"src/app"}function mt(){return`import type { Metadata } from 'next';
|
|
11
15
|
import { Inter } from 'next/font/google';
|
|
12
16
|
import { BotPartyProvider } from '@botparty/nextjs';
|
|
13
17
|
import '@botparty/react/styles.css';
|
|
@@ -29,7 +33,7 @@ export default function RootLayout({ children }: { children: React.ReactNode })
|
|
|
29
33
|
</html>
|
|
30
34
|
);
|
|
31
35
|
}
|
|
32
|
-
`}function
|
|
36
|
+
`}function ft(){return`@import "tailwindcss";
|
|
33
37
|
|
|
34
38
|
:root {
|
|
35
39
|
--background: #09090b;
|
|
@@ -45,7 +49,7 @@ body {
|
|
|
45
49
|
background: var(--background);
|
|
46
50
|
color: var(--foreground);
|
|
47
51
|
}
|
|
48
|
-
`}function
|
|
52
|
+
`}function yt(){return`'use client';
|
|
49
53
|
|
|
50
54
|
import { useState } from 'react';
|
|
51
55
|
import { SignedIn, SignedOut, useAuth, ActionButton } from '@botparty/nextjs';
|
|
@@ -129,7 +133,7 @@ export default function Home() {
|
|
|
129
133
|
</main>
|
|
130
134
|
);
|
|
131
135
|
}
|
|
132
|
-
`}function
|
|
136
|
+
`}function ht(){return`'use client';
|
|
133
137
|
|
|
134
138
|
import { useState } from 'react';
|
|
135
139
|
import {
|
|
@@ -340,7 +344,7 @@ export default function Dashboard() {
|
|
|
340
344
|
</main>
|
|
341
345
|
);
|
|
342
346
|
}
|
|
343
|
-
`}function
|
|
347
|
+
`}function gt(){return`import { botpartyMiddleware, createRouteMatcher } from '@botparty/nextjs/server';
|
|
344
348
|
|
|
345
349
|
const isPublic = createRouteMatcher([
|
|
346
350
|
'/',
|
|
@@ -355,7 +359,7 @@ export default botpartyMiddleware((auth, req) => {
|
|
|
355
359
|
export const config = {
|
|
356
360
|
matcher: ['/((?!_next|.*\\\\..*).*)'],
|
|
357
361
|
};
|
|
358
|
-
`}function
|
|
362
|
+
`}function wt(){return`import { auth } from '@botparty/nextjs/server';
|
|
359
363
|
|
|
360
364
|
const AUTH_URL = process.env.BOTPARTY_AUTH_URL || 'https://id.botparty.club';
|
|
361
365
|
|
|
@@ -389,7 +393,7 @@ export async function GET() {
|
|
|
389
393
|
timestamp: new Date().toISOString(),
|
|
390
394
|
});
|
|
391
395
|
}
|
|
392
|
-
`}function
|
|
396
|
+
`}function bt(){return`import { auth } from '@botparty/nextjs/server';
|
|
393
397
|
|
|
394
398
|
const AUTH_URL = process.env.BOTPARTY_AUTH_URL || 'https://id.botparty.club';
|
|
395
399
|
|
|
@@ -437,7 +441,7 @@ export async function GET() {
|
|
|
437
441
|
timestamp: new Date().toISOString(),
|
|
438
442
|
});
|
|
439
443
|
}
|
|
440
|
-
`}function
|
|
444
|
+
`}function xt(){return`import { createPaymentGateway } from '@botparty/nextjs/server';
|
|
441
445
|
|
|
442
446
|
const gateway = createPaymentGateway({ serviceName: 'My API' });
|
|
443
447
|
|
|
@@ -473,7 +477,7 @@ export async function POST(req: Request) {
|
|
|
473
477
|
payer: check.payerNamespace,
|
|
474
478
|
});
|
|
475
479
|
}
|
|
476
|
-
`}function
|
|
480
|
+
`}function St(){return`import { createPaymentGateway } from '@botparty/nextjs/server';
|
|
477
481
|
|
|
478
482
|
const gateway = createPaymentGateway({ serviceName: 'My API' });
|
|
479
483
|
|
|
@@ -510,61 +514,61 @@ export async function POST(req: Request) {
|
|
|
510
514
|
timestamp: new Date().toISOString(),
|
|
511
515
|
});
|
|
512
516
|
}
|
|
513
|
-
`}function
|
|
514
|
-
`,[`${e}/api/bots/open/route.ts`]:
|
|
517
|
+
`}function vt(e){let r=e.startsWith("src/")?"src/middleware.ts":"middleware.ts";return{[`${e}/layout.tsx`]:mt(),[`${e}/globals.css`]:ft(),[`${e}/page.tsx`]:yt(),[`${e}/dashboard/page.tsx`]:ht(),[r]:gt(),[`${e}/api/botparty/[...botparty]/route.ts`]:`export { GET, POST } from '@botparty/nextjs/handlers';
|
|
518
|
+
`,[`${e}/api/bots/open/route.ts`]:wt(),[`${e}/api/bots/user-required/route.ts`]:bt(),[`${e}/api/bots/pay-per-call/route.ts`]:xt(),[`${e}/api/bots/dynamic-payment/route.ts`]:St()}}async function At(e){let t=process.cwd();console.log(`
|
|
515
519
|
@botparty/nextjs init
|
|
516
|
-
`);let r=
|
|
517
|
-
`)||"",i=null;if(!o||e.force){
|
|
520
|
+
`);let r=Oe(I(t,"package.json")),n=!1;if(r)try{let u=JSON.parse(Bt("fs").readFileSync(I(t,"package.json"),"utf-8"));if(!{...u.dependencies,...u.devDependencies}["@botparty/nextjs"]){let b=_e(t);l("Installing @botparty/nextjs..."),he(`${b==="pnpm"?"pnpm add":b==="yarn"?"yarn add":"npm install"} @botparty/nextjs @botparty/react`,t),d("Dependencies installed")}}catch{}else if(dr(t).filter(y=>!y.startsWith(".")).length===0){f("Scaffolding Next.js project");let y=_e(t);he('npx -y create-next-app@latest . --ts --tailwind --eslint --app --src-dir --import-alias "@/*" --yes',t),d("Next.js project created"),n=!0,l("Installing @botparty/nextjs..."),he(`${y==="pnpm"?"pnpm add":y==="yarn"?"yarn add":"npm install"} @botparty/nextjs @botparty/react`,t),d("Dependencies installed")}else h("No Next.js project found in this directory."),l("Run in an empty directory to scaffold a new project, or in an existing Next.js project."),process.exit(1);f("Generating ES256 keypair");let s=P(t),o=s.BOTPARTY_CLIENT_ASSERTION_KEY?.replace(/\\n/g,`
|
|
521
|
+
`)||"",i=null;if(!o||e.force){l("Generating new ES256 keypair...");let{publicKey:u,privateKey:y}=Et("ec",{namedCurve:"P-256",publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});o=y;let b=await Y(u,"ES256");i={...await C(b),use:"sig",alg:"ES256"},d("ES256 keypair generated"),l(`Public JWK: ${JSON.stringify(i)}`)}else{l("Using existing private key from .env");try{let u=await j(o,"ES256");i={...await C(u),use:"sig",alg:"ES256"},delete i.d}catch{m("Could not parse existing private key, generating new one...");let{publicKey:u,privateKey:y}=Et("ec",{namedCurve:"P-256",publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});o=y;let b=await Y(u,"ES256");i={...await C(b),use:"sig",alg:"ES256"}}}f("Configuring BotParty credentials");let a=s.BOTPARTY_CLIENT_ID||"",p=!0;a&&o&&!e.force&&(l("Found existing credentials. Validating..."),await de(a,o)?(d("Credentials are valid"),p=!1):m("Existing credentials are invalid. Re-registering..."));let c=s.BOTPARTY_DOMAIN||"";if(p)if(e.domain&&(c=e.domain),e.clientId)a=e.clientId,p=!1,l(`Using provided Client ID: ${a}`);else{c||(h("Domain is required."),console.log(`
|
|
518
522
|
Retry with:
|
|
519
523
|
npx @botparty/nextjs init --domain <your-domain>
|
|
520
524
|
|
|
521
525
|
Need a domain? Check available options:
|
|
522
526
|
botparty domains.botparty.club
|
|
523
|
-
`),process.exit(1)),
|
|
527
|
+
`),process.exit(1)),l(`Registering ${c} with id.botparty.club...`);let u;try{u=(await ct(c,e.force)).txtRecord}catch(y){let b=y instanceof Error?y.message:String(y);if(b.includes("already verified")||b.includes("already registered")){if(e.force)throw new Error("Server does not support force re-registration yet. Please delete the domain record manually or redeploy the server.");m("Domain is already registered."),console.log(`
|
|
524
528
|
To use your existing Client ID:
|
|
525
529
|
npx @botparty/nextjs init --domain ${c} --client-id <your-client-id>
|
|
526
530
|
|
|
527
531
|
To overwrite the previous registration:
|
|
528
532
|
npx @botparty/nextjs init --domain ${c} --force
|
|
529
|
-
`),process.exit(1)}else throw
|
|
533
|
+
`),process.exit(1)}else throw y}if(p&&u){let y=c.split("."),b=y.slice(-2).join("."),A=y.slice(0,-2).join("."),Wt=A?`_botparty.${A}`:"_botparty";if(l("Checking DNS for TXT record..."),!await pt(c,u)){let Ut=A?`
|
|
530
534
|
Alternatively, set the record at your apex domain \u2014 any of these work:
|
|
531
535
|
|
|
532
|
-
Host: ${c} Value: ${
|
|
533
|
-
Host: _botparty.${c} Value: ${
|
|
534
|
-
Host: ${
|
|
535
|
-
Host: ${
|
|
536
|
+
Host: ${c} Value: ${u}
|
|
537
|
+
Host: _botparty.${c} Value: ${u}
|
|
538
|
+
Host: ${b} Value: ${u}
|
|
539
|
+
Host: ${A}._botparty.${b} Value: ${u}
|
|
536
540
|
`:`
|
|
537
541
|
Valid record locations (any one works):
|
|
538
542
|
|
|
539
|
-
Host: ${c} Value: ${
|
|
540
|
-
Host: _botparty.${c} Value: ${
|
|
543
|
+
Host: ${c} Value: ${u}
|
|
544
|
+
Host: _botparty.${c} Value: ${u}
|
|
541
545
|
`;console.log(`
|
|
542
546
|
DNS TXT record not found. Add this record to your domain:
|
|
543
547
|
|
|
544
548
|
Host: _botparty.${c}
|
|
545
|
-
Value: ${
|
|
546
|
-
${
|
|
549
|
+
Value: ${u}
|
|
550
|
+
${Ut}
|
|
547
551
|
Vercel CLI:
|
|
548
|
-
vercel dns add ${
|
|
552
|
+
vercel dns add ${b} ${Wt} TXT "${u}"
|
|
549
553
|
|
|
550
554
|
Then retry:
|
|
551
555
|
npx @botparty/nextjs init --domain ${c}${e.jwks?" --jwks":""}
|
|
552
|
-
`),process.exit(1)}
|
|
553
|
-
`),
|
|
556
|
+
`),process.exit(1)}d("DNS TXT record found"),l("Verifying domain with id.botparty.club...");let xe={};e.jwks?xe.jwksUri=`https://${c}/.well-known/jwks.json`:xe.publicKey=i,a=(await lt(c,xe)).clientId,d(`Domain verified! Client ID: ${a}`)}}f("Writing environment variables");let g={};(!s.BOTPARTY_AUTH_URL||e.force)&&(g.BOTPARTY_AUTH_URL="https://id.botparty.club"),a&&(g.BOTPARTY_CLIENT_ID=a),g.BOTPARTY_CLIENT_ASSERTION_KEY=o.replace(/\n/g,"\\n"),c&&(g.BOTPARTY_DOMAIN=c),_(t,g),d(".env updated"),f("Setting up auth routes");let x=B(t),v=dt(t),E=I(t,x,"api/botparty/[...botparty]"),w=I(E,"route.ts");if(Oe(w)?l("Route handler already exists, skipping"):($e(E,{recursive:!0}),ge(w,`export { GET, POST } from '@botparty/nextjs/handlers';
|
|
557
|
+
`),d("Created catch-all route handler")),e.jwks){let u=I(t,x,".well-known/jwks.json"),y=I(u,"route.ts");Oe(y)?l("JWKS route already exists, skipping"):($e(u,{recursive:!0}),ge(y,`import { createJwksResponse } from '@botparty/nextjs/server';
|
|
554
558
|
|
|
555
559
|
export async function GET() {
|
|
556
560
|
return createJwksResponse();
|
|
557
561
|
}
|
|
558
|
-
`),
|
|
562
|
+
`),d("Created .well-known/jwks.json route (--jwks mode)"))}if(ut(t))l("Middleware already exists, skipping");else{let u=v?I(t,"src/middleware.ts"):I(t,"middleware.ts"),y=e.jwks?"['/', '/api/public(.*)', '/.well-known(.*)']":"['/', '/api/public(.*)']";ge(u,`import { botpartyMiddleware, createRouteMatcher } from '@botparty/nextjs/server';
|
|
559
563
|
|
|
560
|
-
const isPublic = createRouteMatcher(${
|
|
564
|
+
const isPublic = createRouteMatcher(${y});
|
|
561
565
|
|
|
562
566
|
export default botpartyMiddleware((auth, req) => {
|
|
563
567
|
if (!isPublic(req)) auth.protect();
|
|
564
568
|
});
|
|
565
569
|
|
|
566
570
|
export const config = { matcher: ['/((?!_next|.*\\\\..*).*)'] };
|
|
567
|
-
`),
|
|
571
|
+
`),d("Created middleware.ts")}if(n){f("Scaffolding demo project");let u=vt(x);for(let[y,b]of Object.entries(u)){let A=I(t,y);$e(I(A,".."),{recursive:!0}),ge(A,b),d(`Created ${y}`)}}console.log(`
|
|
568
572
|
\u2713 BotParty auth is ready!
|
|
569
573
|
|
|
570
574
|
Next steps:
|
|
@@ -573,44 +577,79 @@ export const config = { matcher: ['/((?!_next|.*\\\\..*).*)'] };
|
|
|
573
577
|
${n?` 3. Click "Open Dashboard" to test the auth flow
|
|
574
578
|
4. Try the sample API routes from the dashboard`:""}
|
|
575
579
|
Docs: https://www.npmjs.com/package/@botparty/nextjs
|
|
576
|
-
`)}import{existsSync as
|
|
580
|
+
`)}import{existsSync as Tt,readFileSync as Rt}from"fs";import{resolve as Pt}from"path";async function we(){let e=process.cwd(),t=[];console.log(`
|
|
577
581
|
@botparty/nextjs doctor
|
|
578
|
-
`),
|
|
579
|
-
`)||"",i=r.BOTPARTY_CLIENT_ID||"",a=r.BOTPARTY_DOMAIN||"";
|
|
580
|
-
Summary: ${
|
|
581
|
-
`),
|
|
582
|
+
`),f("Environment variables");let r=P(e),s=["BOTPARTY_AUTH_URL","BOTPARTY_CLIENT_ID","BOTPARTY_CLIENT_ASSERTION_KEY","BOTPARTY_DOMAIN"].filter(w=>!r[w]);s.length===0?(d("All required env vars present"),t.push({id:"env-vars",pass:!0,message:"All required env vars present",fixable:!1})):(h(`Missing env vars: ${s.join(", ")}`),t.push({id:"env-vars",pass:!1,message:`Missing: ${s.join(", ")}`,fixable:!1}));let o=r.BOTPARTY_CLIENT_ASSERTION_KEY?.replace(/\\n/g,`
|
|
583
|
+
`)||"",i=r.BOTPARTY_CLIENT_ID||"",a=r.BOTPARTY_DOMAIN||"";f("Private key");let p=null;if(o)try{p=await ee(o),d("Private key is valid ES256 PKCS8"),t.push({id:"key-valid",pass:!0,message:"Valid ES256 key",fixable:!1})}catch{h("Private key is not a valid ES256 PKCS8 key"),t.push({id:"key-valid",pass:!1,message:"Invalid ES256 key",fixable:!1})}else m("No private key to validate (BOTPARTY_CLIENT_ASSERTION_KEY missing)"),t.push({id:"key-valid",pass:!1,message:"No key present",fixable:!1});f("Server authentication");let c=null;if(i&&o)if(await de(i,o)){d("Credentials validated against id.botparty.club"),t.push({id:"server-auth",pass:!0,message:"Credentials valid",fixable:!0});let u=await O(i,o);u&&(c=u.keyMode,l(`Key mode: ${c??"none"}`),l(`JWKS URI: ${u.jwksUri}`))}else h("Credentials are invalid \u2014 key on server does not match local key"),t.push({id:"server-auth",pass:!1,message:"Key mismatch with server",fixable:!0});else m("Cannot validate \u2014 missing CLIENT_ID or ASSERTION_KEY"),t.push({id:"server-auth",pass:!1,message:"Missing credentials",fixable:!1});f("Route handler");let g=B(e),x=Pt(e,g,"api/botparty/[...botparty]/route.ts");if(Tt(x)?Rt(x,"utf-8").includes("@botparty/nextjs/handlers")?(d("Route handler exists with correct import"),t.push({id:"route-handler",pass:!0,message:"Route handler OK",fixable:!0})):(m("Route handler exists but may have incorrect content"),t.push({id:"route-handler",pass:!1,message:"Route handler has unexpected content",fixable:!0})):(h("Route handler missing: api/botparty/[...botparty]/route.ts"),t.push({id:"route-handler",pass:!1,message:"Route handler missing",fixable:!0})),f("JWKS route"),c==="domain-hosted"){let w=Pt(e,g,".well-known/jwks.json/route.ts");Tt(w)?Rt(w,"utf-8").includes("createJwksResponse")?(d("JWKS route handler exists (domain-hosted mode)"),t.push({id:"jwks-route",pass:!0,message:"JWKS route OK",fixable:!0})):(m("JWKS route exists but may have incorrect content"),t.push({id:"jwks-route",pass:!1,message:"JWKS route has unexpected content",fixable:!0})):(h("JWKS route handler missing (required for domain-hosted mode)"),t.push({id:"jwks-route",pass:!1,message:"JWKS route missing",fixable:!0}))}else l("Skipped \u2014 not in domain-hosted mode"),t.push({id:"jwks-route",pass:!0,message:"N/A (botparty-hosted)",fixable:!1});if(f("Remote JWKS"),a&&p){let w=await ue(a);if(w&&w.keys?.length>0){let u=p.x,y=p.y;w.keys.some(A=>A.x===u&&A.y===y)?(d("Remote JWKS contains the correct public key"),t.push({id:"jwks-remote",pass:!0,message:"Remote JWKS matches local key",fixable:!0})):(h("Remote JWKS does not contain the local public key"),t.push({id:"jwks-remote",pass:!1,message:"Key mismatch in remote JWKS",fixable:!0}))}else m("Could not fetch remote JWKS for domain"),t.push({id:"jwks-remote",pass:!1,message:"Remote JWKS not available",fixable:!0})}else m("Cannot check remote JWKS \u2014 missing domain or key"),t.push({id:"jwks-remote",pass:!1,message:"Missing domain or key",fixable:!1});let v=t.filter(w=>w.pass).length,E=t.filter(w=>!w.pass).length;return console.log(`
|
|
584
|
+
Summary: ${v} passed, ${E} failed
|
|
585
|
+
`),E>0&&l("Run `npx @botparty/nextjs fix` to auto-fix what can be fixed.\n"),t}import{mkdirSync as kt,writeFileSync as It}from"fs";import{resolve as be}from"path";async function Ct(){let t=(await we()).filter(a=>!a.pass);if(t.length===0){console.log(` Nothing to fix \u2014 all checks passed.
|
|
582
586
|
`);return}console.log(`
|
|
583
587
|
Attempting to fix issues...
|
|
584
|
-
`);let r=process.cwd(),n=
|
|
585
|
-
`)||"",o=n.BOTPARTY_CLIENT_ID||"",i=n.BOTPARTY_DOMAIN||"";for(let a of t)await
|
|
586
|
-
`),
|
|
588
|
+
`);let r=process.cwd(),n=P(r),s=n.BOTPARTY_CLIENT_ASSERTION_KEY?.replace(/\\n/g,`
|
|
589
|
+
`)||"",o=n.BOTPARTY_CLIENT_ID||"",i=n.BOTPARTY_DOMAIN||"";for(let a of t)await ur(a,{cwd:r,privateKeyPem:s,clientId:o,domain:i});console.log("")}async function ur(e,t){switch(f(`Fixing: ${e.id}`),e.id){case"env-vars":m("Cannot auto-fix missing env vars. Run `npx @botparty/nextjs init` to set them up.");break;case"key-valid":m("Cannot auto-fix an invalid key. Run `npx @botparty/nextjs init --force` to regenerate.");break;case"server-auth":await mr(t);break;case"route-handler":fr(t);break;case"jwks-route":yr(t);break;case"jwks-remote":await hr(t);break}}async function mr(e){if(!e.clientId||!e.privateKeyPem){m("Cannot fix \u2014 missing CLIENT_ID or ASSERTION_KEY. Run `npx @botparty/nextjs init --force`.");return}if(await O(e.clientId,e.privateKeyPem)){l("Credentials are actually valid now (may have been a transient failure).");return}l("Attempting to re-upload public key to id.botparty.club...");try{let r=await ee(e.privateKeyPem);await G(e.clientId,e.privateKeyPem,r)?d("Public key updated on server"):(h("Failed to update key. The local key may not match what the server expects."),m("Run `npx @botparty/nextjs init --force` to re-register with a new key."))}catch{h("Could not derive public key or update server. Run `npx @botparty/nextjs init --force`.")}}function fr(e){let t=B(e.cwd),r=be(e.cwd,t,"api/botparty/[...botparty]"),n=be(r,"route.ts");kt(r,{recursive:!0}),It(n,`export { GET, POST } from '@botparty/nextjs/handlers';
|
|
590
|
+
`),d("Created route handler")}function yr(e){let t=B(e.cwd),r=be(e.cwd,t,".well-known/jwks.json"),n=be(r,"route.ts");kt(r,{recursive:!0}),It(n,`import { createJwksResponse } from '@botparty/nextjs/server';
|
|
587
591
|
|
|
588
592
|
export async function GET() {
|
|
589
593
|
return createJwksResponse();
|
|
590
594
|
}
|
|
591
|
-
`),
|
|
595
|
+
`),d("Created JWKS route handler")}async function hr(e){if(!e.clientId||!e.privateKeyPem||!e.domain){m("Cannot fix remote JWKS \u2014 missing credentials or domain.");return}let t=await O(e.clientId,e.privateKeyPem);if(!t){m("Cannot determine key mode \u2014 server auth failed.");return}if(t.keyMode==="botparty-hosted"){l("Re-uploading public key to id.botparty.club...");try{let n=await ee(e.privateKeyPem);if(!await G(e.clientId,e.privateKeyPem,n)){h("Failed to update key on server.");return}d("Public key updated")}catch{h("Could not update key on server.");return}l("Verifying remote JWKS with cache bypass...");let r=await ue(e.domain);r&&r.keys?.length>0?d("Remote JWKS now available"):m("Remote JWKS still not available. It may take a moment for the cache to update.")}else t.keyMode==="domain-hosted"?(m("In domain-hosted mode, the remote JWKS is served by your app."),m("Make sure the JWKS route handler is deployed and redeploy if you recently changed keys.")):m("No key mode detected. Run `npx @botparty/nextjs init` to set up keys.")}import{generateKeyPairSync as gr}from"crypto";async function Kt(e={}){let t=process.cwd();console.log(`
|
|
592
596
|
@botparty/nextjs rotate
|
|
593
|
-
`),
|
|
594
|
-
`),o=r.BOTPARTY_DOMAIN;n||(
|
|
597
|
+
`),f("Reading current credentials");let r=P(t),n=r.BOTPARTY_CLIENT_ID,s=r.BOTPARTY_CLIENT_ASSERTION_KEY?.replace(/\\n/g,`
|
|
598
|
+
`),o=r.BOTPARTY_DOMAIN;n||(h("BOTPARTY_CLIENT_ID is not set in .env"),process.exit(1)),s||(h("BOTPARTY_CLIENT_ASSERTION_KEY is not set in .env"),process.exit(1)),o||(h("BOTPARTY_DOMAIN is not set in .env"),process.exit(1)),d("Credentials loaded"),f("Detecting key mode");let i=await O(n,s);i||(h("Could not authenticate with id.botparty.club. Is the current key valid?"),process.exit(1));let a=i.keyMode;l(`Key mode: ${a??"none"}`),l(`Domain: ${i.domain}`),f("Generating new ES256 keypair");let{publicKey:p,privateKey:c}=gr("ec",{namedCurve:"P-256",publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}}),g=await Y(p,"ES256"),x={...await C(g),use:"sig",alg:"ES256"};d("New keypair generated"),e.yes||(m("This will invalidate the current key."),console.log(`
|
|
595
599
|
To proceed, confirm with --yes:
|
|
596
600
|
npx @botparty/nextjs rotate --yes
|
|
597
|
-
`),process.exit(1)),a==="botparty-hosted"?(
|
|
601
|
+
`),process.exit(1)),a==="botparty-hosted"?(f("Uploading new public key to id.botparty.club"),await G(n,s,x)||(h("Failed to update public key on id.botparty.club"),process.exit(1)),d("Public key updated on server"),f("Updating local .env"),_(t,{BOTPARTY_CLIENT_ASSERTION_KEY:c.replace(/\n/g,"\\n")}),d(".env updated with new private key")):a==="domain-hosted"?(f("Updating local .env"),_(t,{BOTPARTY_CLIENT_ASSERTION_KEY:c.replace(/\n/g,"\\n")}),d(".env updated with new private key"),m("In domain-hosted mode, your JWKS route handler derives the key from the env var at runtime."),m("You must redeploy your app for the new key to take effect.")):(f("Uploading new public key to id.botparty.club"),await G(n,s,x)||(h("Failed to update public key on id.botparty.club"),process.exit(1)),d("Public key updated on server"),f("Updating local .env"),_(t,{BOTPARTY_CLIENT_ASSERTION_KEY:c.replace(/\n/g,"\\n")}),d(".env updated with new private key")),f("Verifying new credentials"),await O(n,c)?d("New credentials validated successfully"):(m("Could not validate new credentials immediately \u2014 this may be a caching delay."),m("Run `npx @botparty/nextjs doctor` in a minute to verify.")),console.log(`
|
|
598
602
|
Key rotation complete!
|
|
599
603
|
|
|
600
604
|
Next steps:
|
|
601
605
|
1. Redeploy your application to pick up the new key
|
|
602
606
|
2. Run \`npx @botparty/nextjs doctor\` to verify everything is working
|
|
603
|
-
`)}function
|
|
607
|
+
`)}var wr={mongo:{domain:"mongo.botparty.club",label:"MongoDB",provision:br},upstash:{domain:"upstash.botparty.club",label:"Upstash Redis",provision:xr},s3:{domain:"s3.botparty.club",label:"S3 Storage",provision:Sr}};async function br(e){l(`Creating MongoDB database "${e.slug}"...`);let t=await k(e.serviceDomain,"POST","/databases",e.domain,e.token,{slug:e.slug});if(!t.ok&&t.status===409){m(`Database "${e.slug}" already exists. Fetching existing details...`);let r=await k(e.serviceDomain,"GET",`/databases/${e.slug}`,e.domain,e.token);if(!r.ok)throw new Error(`Failed to fetch existing database: ${JSON.stringify(r.data)}`);let n=r.data.connectionString;if(!n)throw new Error("Existing database has no connectionString. Check it manually.");return{MONGODB_URI:n}}if(!t.ok){let r=t.data.error?.message||JSON.stringify(t.data);throw new Error(`Failed to create MongoDB database: ${r}`)}return{MONGODB_URI:t.data.connectionString}}async function xr(e){l(`Creating Upstash Redis instance "${e.slug}"...`);let t=await k(e.serviceDomain,"POST","/redis",e.domain,e.token,{slug:e.slug}),r;if(!t.ok&&t.status===409){m(`Redis instance "${e.slug}" already exists. Fetching existing details...`);let s=await k(e.serviceDomain,"GET",`/redis/${e.slug}`,e.domain,e.token);if(!s.ok)throw new Error(`Failed to fetch existing Redis instance: ${JSON.stringify(s.data)}`);r=s.data.endpoint}else if(t.ok)r=t.data.endpoint;else{let s=t.data.error?.message||JSON.stringify(t.data);throw new Error(`Failed to create Redis instance: ${s}`)}l("Creating Redis credentials...");let n=await k(e.serviceDomain,"POST",`/redis/${e.slug}/credentials`,e.domain,e.token,{permission:"full"});if(!n.ok){let s=n.data.error?.message||JSON.stringify(n.data);throw new Error(`Failed to create Redis credentials: ${s}`)}return{UPSTASH_REDIS_REST_URL:`https://${r}`,UPSTASH_REDIS_REST_TOKEN:n.data.token}}async function Sr(e){l(`Creating S3 bucket "${e.slug}"...`);let t=await k(e.serviceDomain,"POST","/buckets",e.domain,e.token,{slug:e.slug}),r=e.slug;if(!t.ok&&t.status===409)m(`Bucket "${e.slug}" already exists.`);else if(t.ok)r=t.data.slug||e.slug;else{let s=t.data.error?.message||JSON.stringify(t.data);throw new Error(`Failed to create S3 bucket: ${s}`)}l("Creating S3 IAM credentials...");let n=await k(e.serviceDomain,"POST",`/buckets/${r}/credentials`,e.domain,e.token,{permission:"readWrite"});if(!n.ok){let s=n.data.error?.message||JSON.stringify(n.data);throw new Error(`Failed to create S3 credentials: ${s}`)}return{S3_BUCKET:t.data.bucketName||r,AWS_ACCESS_KEY_ID:n.data.accessKeyId,AWS_SECRET_ACCESS_KEY:n.data.secretAccessKey,AWS_REGION:n.data.region||"us-east-1"}}async function Nt(e){let t=process.cwd(),r=e.service.toLowerCase();console.log(`
|
|
608
|
+
@botparty/nextjs add-service ${r}
|
|
609
|
+
`);let n=wr[r];n||(h(`Unknown service: ${e.service}`),console.log(`
|
|
610
|
+
Available services:
|
|
611
|
+
mongo MongoDB database
|
|
612
|
+
upstash Upstash Redis
|
|
613
|
+
s3 S3 storage bucket
|
|
614
|
+
|
|
615
|
+
Usage:
|
|
616
|
+
npx @botparty/nextjs add-service <service> [--slug <name>]
|
|
617
|
+
`),process.exit(1));let{domain:s,privateKeyPem:o}=ye(t),i=e.slug||fe(s);f(`Provisioning ${n.label}`),l(`Service: ${n.domain}`),l(`Slug: ${i}`),l(`Namespace: ${s}`);let a=await me(s,o),p=await n.provision({domain:s,token:a,slug:i,serviceDomain:n.domain});f("Writing environment variables");for(let[c,g]of Object.entries(p))l(`${c}=${g.length>60?g.slice(0,57)+"...":g}`);_(t,p),d(".env updated"),console.log(`
|
|
618
|
+
${n.label} is ready!
|
|
619
|
+
|
|
620
|
+
Environment variables written to .env:
|
|
621
|
+
${Object.keys(p).map(c=>` ${c}`).join(`
|
|
622
|
+
`)}
|
|
623
|
+
|
|
624
|
+
To deploy with these env vars:
|
|
625
|
+
npx @botparty/nextjs deploy
|
|
626
|
+
`)}import{existsSync as vr,readFileSync as $t,readdirSync as Er}from"fs";import{resolve as Ar,relative as Dt,extname as jt,join as Tr}from"path";var Rr=new Set(["node_modules",".next",".git",".turbo",".vercel","dist",".cache","__pycache__"]),Pr=new Set([".env",".env.local",".env.production",".env.development",".DS_Store"]),kr=new Set([".txt",".md",".html",".htm",".css",".js",".ts",".jsx",".tsx",".json",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".sh",".bash",".zsh",".fish",".bat",".ps1",".py",".rb",".go",".rs",".java",".c",".cpp",".h",".hpp",".cs",".php",".swift",".kt",".scala",".r",".sql",".graphql",".proto",".gitignore",".dockerignore",".editorconfig",".prettierrc",".eslintrc",".svg",".csv",".tsv",".log",".mjs",".cjs",".mts",".cts"]),Ir={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",ico:"image/x-icon",pdf:"application/pdf",zip:"application/zip",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf"};function Cr(e){let t=Ar(e,".gitignore");return vr(t)?$t(t,"utf-8").split(`
|
|
627
|
+
`).map(r=>r.trim()).filter(r=>r&&!r.startsWith("#")):[]}function _t(e,t){for(let r of t){let n=r.replace(/\/$/,"");if(e===n||e.startsWith(n+"/")||e.split("/").some(o=>o===n))return!0}return!1}function Kr(e){let t=jt(e).toLowerCase();return!!(kr.has(t)||t==="")}function Nr(e,t){let r=$t(e),n=Dt(t,e);if(Kr(e))return{path:n,contents:r.toString("utf-8")};let s=jt(e).toLowerCase().slice(1)||"bin",o=Ir[s]||"application/octet-stream";return{path:n,contents:`data:${o};base64,${r.toString("base64")}`}}function _r(e){let t=Cr(e),r=[];function n(s){let o=Er(s,{withFileTypes:!0});for(let i of o){let a=Tr(s,i.name),p=Dt(e,a);if(i.isDirectory()){if(Rr.has(i.name)||_t(p,t))continue;n(a)}else{if(Pr.has(i.name)||i.name.startsWith(".env")||_t(p,t))continue;try{r.push(Nr(a,e))}catch{m(`Skipping unreadable file: ${p}`)}}}}return n(e),r}var Ot="deploy.botparty.club";async function Jt(e){let t=process.cwd();console.log(`
|
|
628
|
+
@botparty/nextjs deploy
|
|
629
|
+
`);let{domain:r,privateKeyPem:n}=ye(t),s=e.projectName||fe(r);f("Collecting project files");let o=_r(t);o.length===0&&(h("No files found to deploy."),process.exit(1)),d(`${o.length} files collected`),f("Reading environment variables");let i=P(t),a=Object.keys(i).length;a>0?d(`${a} env vars from .env`):m("No env vars found in .env"),f("Deploying to deploy.botparty.club"),l(`Project: ${s}`),l("Framework: nextjs"),l(`Domain: ${r}`);let p=await me(r,n);l("Uploading files and env vars...");let c=await k(Ot,"POST",`/projects/${s}/deploy`,r,p,{files:o,env:i,framework:"nextjs"});if(!c.ok){let v=c.data.error?.message||JSON.stringify(c.data);h(`Deployment failed: ${v}`),process.exit(1)}let g=c.data.url,x=c.data.deploymentId;if(d(`Deployed: ${g}`),l(`Deployment ID: ${x}`),l(`Status: ${c.data.status}`),r){f("Configuring domain alias"),l(`Adding ${r} to project...`);let v=await k(Ot,"POST",`/projects/${s}/domains`,r,p,{domain:r});if(v.ok)d(`Domain ${r} added`);else{let E=v.data.error?.message||"";E.toString().includes("already")||v.status===409?l(`Domain ${r} is already configured`):(m(`Could not add domain: ${E}`),l("You can add it manually:"),console.log(`
|
|
630
|
+
botparty deploy domains.add --projectName ${s} --domain ${r}
|
|
631
|
+
`))}}console.log(`
|
|
632
|
+
Deployment complete!
|
|
633
|
+
|
|
634
|
+
URL: ${g}
|
|
635
|
+
Domain: https://${r}
|
|
636
|
+
Status: ${c.data.status} (check logs for build progress)
|
|
637
|
+
|
|
638
|
+
View logs:
|
|
639
|
+
botparty deploy logs --projectName ${s}
|
|
640
|
+
`)}function Or(e){let t=e.slice(2),r=t[0]??"help",n={},s=[];for(let o=1;o<t.length;o++){let i=t[o];if(i.startsWith("--")){let a=i.slice(2),p=t[o+1];p&&!p.startsWith("--")?(n[a]=p,o++):n[a]=!0}else s.push(i)}return{command:r,positional:s,flags:n}}function De(){console.log(`
|
|
604
641
|
@botparty/nextjs CLI
|
|
605
642
|
|
|
606
643
|
Usage:
|
|
607
644
|
npx @botparty/nextjs <command> [options]
|
|
608
645
|
|
|
609
646
|
Commands:
|
|
610
|
-
init
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
647
|
+
init Set up BotParty auth in your Next.js project
|
|
648
|
+
add-service <svc> Provision infrastructure and add env vars
|
|
649
|
+
deploy Deploy your project to deploy.botparty.club
|
|
650
|
+
doctor Check that BotParty is properly configured
|
|
651
|
+
fix Auto-fix issues found by doctor
|
|
652
|
+
rotate Rotate the BOTPARTY_CLIENT_ASSERTION_KEY
|
|
614
653
|
|
|
615
654
|
Options (init):
|
|
616
655
|
--domain <domain> Domain to register (required)
|
|
@@ -618,10 +657,17 @@ export async function GET() {
|
|
|
618
657
|
--jwks Host JWKS on your domain (route handler mode)
|
|
619
658
|
--force Re-register domain and regenerate secrets
|
|
620
659
|
|
|
660
|
+
Options (add-service):
|
|
661
|
+
<service> mongo | upstash | s3
|
|
662
|
+
--slug <name> Resource name (defaults to domain slug)
|
|
663
|
+
|
|
664
|
+
Options (deploy):
|
|
665
|
+
--project-name <name> Vercel project name (defaults to domain slug)
|
|
666
|
+
|
|
621
667
|
Options (rotate):
|
|
622
668
|
--yes Confirm key rotation without prompting
|
|
623
669
|
|
|
624
670
|
General:
|
|
625
671
|
--help Show this help message
|
|
626
|
-
`)}async function
|
|
672
|
+
`)}async function $r(){let{command:e,positional:t,flags:r}=Or(process.argv);switch((r.help||r.h)&&(De(),process.exit(0)),e){case"init":await At({domain:typeof r.domain=="string"?r.domain:void 0,clientId:typeof r["client-id"]=="string"?r["client-id"]:void 0,force:r.force===!0,jwks:r.jwks===!0});break;case"add-service":await Nt({service:t[0]||"",slug:typeof r.slug=="string"?r.slug:void 0});break;case"deploy":await Jt({projectName:typeof r["project-name"]=="string"?r["project-name"]:void 0});break;case"doctor":await we();break;case"fix":await Ct();break;case"rotate":await Kt({yes:r.yes===!0});break;case"help":De();break;default:console.error(`Unknown command: ${e}`),De(),process.exit(1)}}$r().catch(e=>{console.error(`
|
|
627
673
|
Error:`,e.message||e),process.exit(1)});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@botparty/nextjs",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.44",
|
|
4
4
|
"description": "Next.js SDK for BotParty auth — middleware, server auth(), route handlers, SSR provider",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.cjs",
|
|
@@ -63,7 +63,7 @@
|
|
|
63
63
|
"dev": "tsc --watch"
|
|
64
64
|
},
|
|
65
65
|
"dependencies": {
|
|
66
|
-
"@botparty/react": "0.0.
|
|
66
|
+
"@botparty/react": "0.0.44",
|
|
67
67
|
"jose": "^6.1.2"
|
|
68
68
|
},
|
|
69
69
|
"peerDependencies": {
|