@botparty/nextjs 0.0.46 → 0.0.47
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/deploy-cmd.d.ts +1 -0
- package/dist/cli/helpers.d.ts +12 -0
- package/dist/cli.js +67 -72
- package/package.json +2 -2
package/dist/cli/deploy-cmd.d.ts
CHANGED
package/dist/cli/helpers.d.ts
CHANGED
|
@@ -64,6 +64,18 @@ export declare function callService(serviceDomain: string, method: string, endpo
|
|
|
64
64
|
data: Record<string, unknown>;
|
|
65
65
|
}>;
|
|
66
66
|
export declare function domainToSlug(domain: string): string;
|
|
67
|
+
export declare function generateBptyCloudDomain(namespace: string, token: string, prefix?: string): Promise<{
|
|
68
|
+
slug: string;
|
|
69
|
+
domain: string;
|
|
70
|
+
}>;
|
|
71
|
+
export declare function purchaseBptyCloudDomain(namespace: string, token: string, domain: string): Promise<Record<string, unknown>>;
|
|
72
|
+
export declare function isDomainManagedByBotparty(domain: string, namespace: string, token: string): Promise<boolean>;
|
|
73
|
+
export declare function createBotpartyDnsRecord(domain: string, namespace: string, token: string, record: {
|
|
74
|
+
type: string;
|
|
75
|
+
host: string;
|
|
76
|
+
answer: string;
|
|
77
|
+
ttl?: number;
|
|
78
|
+
}): Promise<Record<string, unknown>>;
|
|
67
79
|
export declare function requireEnvCredentials(cwd: string): {
|
|
68
80
|
domain: string;
|
|
69
81
|
privateKeyPem: string;
|
package/dist/cli.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
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(`
|
|
2
|
+
var Qt=(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 Ue,mkdirSync as Le,writeFileSync as ae,readdirSync as Er}from"fs";import{resolve as k}from"path";import{generateKeyPairSync as Dt}from"crypto";var de=new TextEncoder,pe=new TextDecoder,qr=2**32;function ze(...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 ue(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 ke(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 me(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 Ye(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e=="string"?e:pe.decode(e),{alphabet:"base64url"});let t=e;t instanceof Uint8Array&&(t=pe.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/");try{return me(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function F(e){let t=e;return typeof t=="string"&&(t=de.encode(t)),Uint8Array.prototype.toBase64?t.toBase64({alphabet:"base64url",omitPadding:!0}):ke(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}var O=(e,t="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),q=(e,t)=>e.name===t;function er(e){return parseInt(e.name.slice(4),10)}function Ce(e,t){if(er(e.hash)!==t)throw O(`SHA-${t}`,"algorithm.hash")}function tr(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function rr(e,t){if(t&&!e.usages.includes(t))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function Fe(e,t,r){switch(t){case"HS256":case"HS384":case"HS512":{if(!q(e.algorithm,"HMAC"))throw O("HMAC");Ce(e.algorithm,parseInt(t.slice(2),10));break}case"RS256":case"RS384":case"RS512":{if(!q(e.algorithm,"RSASSA-PKCS1-v1_5"))throw O("RSASSA-PKCS1-v1_5");Ce(e.algorithm,parseInt(t.slice(2),10));break}case"PS256":case"PS384":case"PS512":{if(!q(e.algorithm,"RSA-PSS"))throw O("RSA-PSS");Ce(e.algorithm,parseInt(t.slice(2),10));break}case"Ed25519":case"EdDSA":{if(!q(e.algorithm,"Ed25519"))throw O("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!q(e.algorithm,t))throw O(t);break}case"ES256":case"ES384":case"ES512":{if(!q(e.algorithm,"ECDSA"))throw O("ECDSA");let n=tr(t);if(e.algorithm.namedCurve!==n)throw O(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}rr(e,r)}function qe(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 fe=(e,...t)=>qe("Key must be ",e,...t),Ie=(e,t,...r)=>qe(`Key for the ${e} algorithm must be `,t,...r);var re=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 v=class extends re{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"};var D=class extends re{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"},ye=class extends re{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"};var ne=e=>{if(e?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return e instanceof CryptoKey}catch{return!1}},se=e=>e?.[Symbol.toStringTag]==="KeyObject",Ke=e=>ne(e)||se(e);var sn=Symbol();function Ne(e,t){if(e)throw new TypeError(`${t} can only be called once`)}var nr=e=>typeof e=="object"&&e!==null;function _e(e){if(!nr(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 Ge(...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 oe=e=>_e(e)&&typeof e.kty=="string",Ve=e=>e.kty!=="oct"&&(e.kty==="AKP"&&typeof e.priv=="string"||typeof e.d=="string"),Xe=e=>e.kty!=="oct"&&e.d===void 0&&e.priv===void 0,Ze=e=>e.kty==="oct"&&typeof e.k=="string";function or(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 ir(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 v(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function ar(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(fe(t,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}return Fe(t,e,r),t}async function Qe(e,t,r){let n=await ar(e,t,"sign");or(e,n);let s=await crypto.subtle.sign(ir(e,n.algorithm),n,r);return new Uint8Array(s)}var ge='Invalid or unsupported JWK "alg" (Algorithm) Parameter value';function cr(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 v(ge)}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 v(ge)}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 v(ge)}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 v(ge)}break}default:throw new v('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}async function et(e){if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:t,keyUsages:r}=cr(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 G="given KeyObject instance cannot be used for this algorithm",V,tt=async(e,t,r,n=!1)=>{V||=new WeakMap;let s=V.get(e);if(s?.[r])return s[r];let o=await et({...t,alg:r});return n&&Object.freeze(e),s?s[r]=o:V.set(e,{[r]:o}),o},lr=(e,t)=>{V||=new WeakMap;let r=V.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(G)}o=e.toCryptoKey(e.asymmetricKeyType,s,n?[]:["deriveBits"])}if(e.asymmetricKeyType==="ed25519"){if(t!=="EdDSA"&&t!=="Ed25519")throw new TypeError(G);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(G);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(G)}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 l=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(e.asymmetricKeyDetails?.namedCurve);if(!l)throw new TypeError(G);let d={ES256:"P-256",ES384:"P-384",ES512:"P-521"};d[t]&&l===d[t]&&(o=e.toCryptoKey({name:"ECDSA",namedCurve:l},s,[n?"verify":"sign"])),t.startsWith("ECDH-ES")&&(o=e.toCryptoKey({name:"ECDH",namedCurve:l},s,n?[]:["deriveBits"]))}if(!o)throw new TypeError(G);return r?r[t]=o:V.set(e,{[t]:o}),o};async function rt(e,t){if(e instanceof Uint8Array||ne(e))return e;if(se(e)){if(e.type==="secret")return e.export();if("toCryptoKey"in e&&typeof e.toCryptoKey=="function")try{return lr(e,t)}catch(n){if(n instanceof TypeError)throw n}let r=e.export({format:"jwk"});return tt(e,r,t)}if(oe(e))return e.k?Ye(e.k):tt(e,e,t,!0);throw new Error("unreachable")}var Oe=(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},nt=e=>({data:e,pos:0}),W=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 B=(e,t,r)=>{if(e.data[e.pos++]!==t)throw new Error(r)},st=(e,t)=>{let r=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,r},dr=e=>{B(e,6,"Expected algorithm OID");let t=W(e);return st(e,t)};function pr(e){B(e,48,"Invalid PKCS#8 structure"),W(e),B(e,2,"Expected version field");let t=W(e);e.pos+=t,B(e,48,"Expected algorithm identifier");let r=W(e);return{algIdStart:e.pos,algIdLength:r}}function ur(e){B(e,48,"Invalid SPKI structure"),W(e),B(e,48,"Expected algorithm identifier");let t=W(e);return{algIdStart:e.pos,algIdLength:t}}var ot=e=>{let t=dr(e);if(Oe(t,[43,101,110]))return"X25519";if(!Oe(t,[42,134,72,206,61,2,1]))throw new Error("Unsupported key algorithm");B(e,6,"Expected curve OID");let r=W(e),n=st(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(Oe(n,o))return s;throw new Error("Unsupported named curve")},it=async(e,t,r,n)=>{let s,o,i=e==="spki",l=()=>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=l();break;case"RS256":case"RS384":case"RS512":s={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.slice(-3)}`},o=l();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=l();break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{try{let a=n.getNamedCurve(t);s=a==="X25519"?{name:"X25519"}:{name:"ECDH",namedCurve:a}}catch{throw new v("Invalid or unsupported key format")}o=i?[]:["deriveBits"];break}case"Ed25519":case"EdDSA":s={name:"Ed25519"},o=l();break;case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":s={name:r},o=l();break;default:throw new v('Invalid or unsupported "alg" (Algorithm) value')}return crypto.subtle.importKey(e,t,s,n?.extractable??!!i,o)},at=(e,t)=>me(e.replace(t,"")),ct=(e,t,r)=>{let n=at(e,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g),s=r;return t?.startsWith?.("ECDH-ES")&&(s||={},s.getNamedCurve=o=>{let i=nt(o);return pr(i),ot(i)}),it("pkcs8",n,t,s)},lt=(e,t,r)=>{let n=at(e,/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g),s=r;return t?.startsWith?.("ECDH-ES")&&(s||={},s.getNamedCurve=o=>{let i=nt(o);return ur(i),ot(i)}),it("spki",n,t,s)};async function X(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return lt(e,t,r)}async function U(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return ct(e,t,r)}async function dt(e){if(se(e))if(e.type==="secret")e=e.export();else return e.export({format:"jwk"});if(e instanceof Uint8Array)return{kty:"oct",k:F(e)};if(!ne(e))throw new TypeError(fe(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 N(e){return dt(e)}function pt(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 v(`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],De=(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},mr=(e,t,r)=>{if(!(t instanceof Uint8Array)){if(oe(t)){if(Ze(t)&&De(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(!Ke(t))throw new TypeError(Ie(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"`)}},fr=(e,t,r)=>{if(oe(t))switch(r){case"decrypt":case"sign":if(Ve(t)&&De(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(Xe(t)&&De(e,t,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!Ke(t))throw new TypeError(Ie(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 ut(e,t,r){switch(e.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":mr(e,t,r);break;default:fr(e,t,r)}}var L=e=>Math.floor(e.getTime()/1e3),mt=60,ft=mt*60,je=ft*24,yr=je*7,gr=je*365.25,hr=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function $e(e){let t=hr.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*mt);break;case"hour":case"hours":case"hr":case"hrs":case"h":s=Math.round(r*ft);break;case"day":case"days":case"d":s=Math.round(r*je);break;case"week":case"weeks":case"w":s=Math.round(r*yr);break;default:s=Math.round(r*gr);break}return t[1]==="-"||t[4]==="ago"?-s:s}function H(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var he=class{#e;constructor(t){if(!_e(t))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(t)}data(){return de.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=H("setNotBefore",t):t instanceof Date?this.#e.nbf=H("setNotBefore",L(t)):this.#e.nbf=L(new Date)+$e(t)}set exp(t){typeof t=="number"?this.#e.exp=H("setExpirationTime",t):t instanceof Date?this.#e.exp=H("setExpirationTime",L(t)):this.#e.exp=L(new Date)+$e(t)}set iat(t){t===void 0?this.#e.iat=L(new Date):t instanceof Date?this.#e.iat=H("setIssuedAt",L(t)):typeof t=="string"?this.#e.iat=H("setIssuedAt",L(new Date)+$e(t)):this.#e.iat=H("setIssuedAt",t)}};var we=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 Ne(this.#t,"setProtectedHeader"),this.#t=t,this}setUnprotectedHeader(t){return Ne(this.#r,"setUnprotectedHeader"),this.#r=t,this}async sign(t,r){if(!this.#t&&!this.#r)throw new D("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Ge(this.#t,this.#r))throw new D("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this.#t,...this.#r},s=pt(D,new Map([["b64",!0]]),r?.crit,this.#t,n),o=!0;if(s.has("b64")&&(o=this.#t.b64,typeof o!="boolean"))throw new D('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=n;if(typeof i!="string"||!i)throw new D('JWS "alg" (Algorithm) Header Parameter missing or invalid');ut(i,t,"sign");let l,d;o?(l=F(this.#e),d=ue(l)):(d=this.#e,l="");let a,b;this.#t?(a=F(JSON.stringify(this.#t)),b=ue(a)):(a="",b=new Uint8Array);let x=ze(b,ue("."),d),S=await rt(t,i),C=await Qe(i,S,x),h={signature:F(C),payload:l};return this.#r&&(h.header=this.#r),this.#t&&(h.protected=a),h}};var be=class{#e;constructor(t){this.#e=new we(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 he(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 be(this.#t.data());if(n.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes("b64")&&this.#e.b64===!1)throw new ye("JWTs MUST NOT use unencoded payload");return n.sign(t,r)}};import{existsSync as T,mkdirSync as ds,readFileSync as yt,writeFileSync as wr}from"fs";import{resolve as R}from"path";import{execSync as br}from"child_process";var xr="https://id.botparty.club";function c(e){console.log(` ${e}`)}function p(e){console.log(` \u2713 ${e}`)}function f(e){console.log(` \u26A0 ${e}`)}function g(e){console.error(` \u2717 ${e}`)}function y(e){console.log(`
|
|
3
3
|
${e}
|
|
4
|
-
${"\u2500".repeat(e.length)}`)}function P(e){let t=R(e,".env");if(!T(t))return{};let r=
|
|
5
|
-
`)){let o=s.trim();if(!o||o.startsWith("#"))continue;let i=o.indexOf("=");if(i<=0)continue;let
|
|
4
|
+
${"\u2500".repeat(e.length)}`)}function P(e){let t=R(e,".env");if(!T(t))return{};let r=yt(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 l=o.slice(0,i).trim(),d=o.slice(i+1).trim();(d.startsWith('"')&&d.endsWith('"')||d.startsWith("'")&&d.endsWith("'"))&&(d=d.slice(1,-1)),n[l]=d}return n}function $(e,t){let r=R(e,".env"),n="";T(r)&&(n=yt(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
|
|
11
|
-
`),"ES256");return new
|
|
12
|
-
`)||"",s=t.BOTPARTY_CLIENT_ID||"";return(!r||!n||!s)&&(
|
|
8
|
+
`)}wr(r,n)}function M(){return process.env.BOTPARTY_AUTH_URL||xr}async function We(e,t){let r=M(),n=await U(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 xe(e,t){try{let r=await We(e,t),n=M();return(await fetch(`${n}/api/v1/clients/${e}`,{headers:{Authorization:`ClientAssertion ${r}`,"X-Client-Id":e}})).ok}catch{return!1}}async function gt(e,t){let r=await fetch(`${M()}/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 ht(e,t){let r=await fetch(`${M()}/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 j(e,t){try{let r=await We(e,t),n=M(),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 ee(e,t,r){try{let n=await We(e,t),s=M();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 ie(e){let t=await U(e.replace(/\\n/g,`
|
|
10
|
+
`),"ES256"),r=await N(t),{d:n,...s}=r;return{...s,use:"sig",alg:"ES256"}}async function Se(e){let t=M();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 Sr(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 wt(e,t){let r=await import("dns"),{resolveTxt:n}=r.promises,s=Sr(e);for(let o of s)try{if((await n(o)).flat().some(d=>d===t||d.includes(t)))return!0}catch{}return!1}async function ve(e,t){let r=await U(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 vr(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 E(e,t,r,n,s,o){let l=(await vr(e)).baseUrl.replace("{namespace}",n),d=`https://${e}${l}${r}`,a={method:t,headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}};o&&["POST","PUT","PATCH"].includes(t)&&(a.body=JSON.stringify(o));let b=await fetch(d,a),x=await b.json().catch(()=>({}));return{ok:b.ok,status:b.status,data:x}}function te(e){return e.replace(/\./g,"-")}var Ee="domains.botparty.club";async function bt(e,t,r){let n=await E(Ee,"POST","/domains/generate",e,t,r?{prefix:r}:{});if(!n.ok)throw new Error(`Failed to generate bpty.cloud slug: ${JSON.stringify(n.data)}`);return{slug:n.data.slug,domain:n.data.domain}}async function xt(e,t,r){let n=await E(Ee,"POST","/domains/purchase",e,t,{domain:r});if(!n.ok)throw new Error(`Failed to purchase bpty.cloud domain: ${JSON.stringify(n.data)}`);return n.data}async function St(e,t,r){try{return(await E(Ee,"GET",`/domains/${encodeURIComponent(e)}`,t,r)).ok}catch{return!1}}async function vt(e,t,r,n){let s=await E(Ee,"POST",`/domains/${encodeURIComponent(e)}/dns`,t,r,n);if(!s.ok)throw new Error(`Failed to create DNS record: ${JSON.stringify(s.data)}`);return s.data}function Ae(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)&&(g("BotParty credentials not found in .env"),c("Run init first:"),console.log(`
|
|
13
13
|
npx @botparty/nextjs init --domain <your-domain>
|
|
14
|
-
`),process.exit(1)),{domain:r,privateKeyPem:n,clientId:s}}function
|
|
14
|
+
`),process.exit(1)),{domain:r,privateKeyPem:n,clientId:s}}function Be(e){return T(R(e,"pnpm-lock.yaml"))?"pnpm":T(R(e,"yarn.lock"))?"yarn":"npm"}function Te(e,t){br(e,{cwd:t,stdio:"inherit"})}function Et(e){return T(R(e,"src"))}function At(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 z(e){return T(R(e,"src/app"))?"src/app":T(R(e,"app"))?"app":"src/app"}function Tt(){return`import type { Metadata } from 'next';
|
|
15
15
|
import { Inter } from 'next/font/google';
|
|
16
16
|
import { BotPartyProvider } from '@botparty/nextjs';
|
|
17
17
|
import '@botparty/react/styles.css';
|
|
@@ -33,7 +33,7 @@ export default function RootLayout({ children }: { children: React.ReactNode })
|
|
|
33
33
|
</html>
|
|
34
34
|
);
|
|
35
35
|
}
|
|
36
|
-
`}function
|
|
36
|
+
`}function Rt(){return`@import "tailwindcss";
|
|
37
37
|
|
|
38
38
|
:root {
|
|
39
39
|
--background: #09090b;
|
|
@@ -49,7 +49,7 @@ body {
|
|
|
49
49
|
background: var(--background);
|
|
50
50
|
color: var(--foreground);
|
|
51
51
|
}
|
|
52
|
-
`}function
|
|
52
|
+
`}function Pt(){return`'use client';
|
|
53
53
|
|
|
54
54
|
import { useState } from 'react';
|
|
55
55
|
import { SignedIn, SignedOut, useAuth, ActionButton } from '@botparty/nextjs';
|
|
@@ -133,7 +133,7 @@ export default function Home() {
|
|
|
133
133
|
</main>
|
|
134
134
|
);
|
|
135
135
|
}
|
|
136
|
-
`}function
|
|
136
|
+
`}function kt(){return`'use client';
|
|
137
137
|
|
|
138
138
|
import { useState } from 'react';
|
|
139
139
|
import {
|
|
@@ -344,7 +344,7 @@ export default function Dashboard() {
|
|
|
344
344
|
</main>
|
|
345
345
|
);
|
|
346
346
|
}
|
|
347
|
-
`}function
|
|
347
|
+
`}function Ct(){return`import { botpartyMiddleware, createRouteMatcher } from '@botparty/nextjs/server';
|
|
348
348
|
|
|
349
349
|
const isPublic = createRouteMatcher([
|
|
350
350
|
'/',
|
|
@@ -359,7 +359,7 @@ export default botpartyMiddleware((auth, req) => {
|
|
|
359
359
|
export const config = {
|
|
360
360
|
matcher: ['/((?!_next|.*\\\\..*).*)'],
|
|
361
361
|
};
|
|
362
|
-
`}function
|
|
362
|
+
`}function It(){return`import { auth } from '@botparty/nextjs/server';
|
|
363
363
|
|
|
364
364
|
const AUTH_URL = process.env.BOTPARTY_AUTH_URL || 'https://id.botparty.club';
|
|
365
365
|
|
|
@@ -393,7 +393,7 @@ export async function GET() {
|
|
|
393
393
|
timestamp: new Date().toISOString(),
|
|
394
394
|
});
|
|
395
395
|
}
|
|
396
|
-
`}function
|
|
396
|
+
`}function Kt(){return`import { auth } from '@botparty/nextjs/server';
|
|
397
397
|
|
|
398
398
|
const AUTH_URL = process.env.BOTPARTY_AUTH_URL || 'https://id.botparty.club';
|
|
399
399
|
|
|
@@ -441,7 +441,7 @@ export async function GET() {
|
|
|
441
441
|
timestamp: new Date().toISOString(),
|
|
442
442
|
});
|
|
443
443
|
}
|
|
444
|
-
`}function
|
|
444
|
+
`}function Nt(){return`import { createPaymentGateway } from '@botparty/nextjs/server';
|
|
445
445
|
|
|
446
446
|
const gateway = createPaymentGateway({ serviceName: 'My API' });
|
|
447
447
|
|
|
@@ -477,7 +477,7 @@ export async function POST(req: Request) {
|
|
|
477
477
|
payer: check.payerNamespace,
|
|
478
478
|
});
|
|
479
479
|
}
|
|
480
|
-
`}function
|
|
480
|
+
`}function _t(){return`import { createPaymentGateway } from '@botparty/nextjs/server';
|
|
481
481
|
|
|
482
482
|
const gateway = createPaymentGateway({ serviceName: 'My API' });
|
|
483
483
|
|
|
@@ -514,61 +514,56 @@ export async function POST(req: Request) {
|
|
|
514
514
|
timestamp: new Date().toISOString(),
|
|
515
515
|
});
|
|
516
516
|
}
|
|
517
|
-
`}function
|
|
518
|
-
`,[`${e}/api/bots/open/route.ts`]:
|
|
517
|
+
`}function Ot(e){let r=e.startsWith("src/")?"src/middleware.ts":"middleware.ts";return{[`${e}/layout.tsx`]:Tt(),[`${e}/globals.css`]:Rt(),[`${e}/page.tsx`]:Pt(),[`${e}/dashboard/page.tsx`]:kt(),[r]:Ct(),[`${e}/api/botparty/[...botparty]/route.ts`]:`export { GET, POST } from '@botparty/nextjs/handlers';
|
|
518
|
+
`,[`${e}/api/bots/open/route.ts`]:It(),[`${e}/api/bots/user-required/route.ts`]:Kt(),[`${e}/api/bots/pay-per-call/route.ts`]:Nt(),[`${e}/api/bots/dynamic-payment/route.ts`]:_t()}}async function $t(e){let t=process.cwd();console.log(`
|
|
519
519
|
@botparty/nextjs init
|
|
520
|
-
`);let r=
|
|
521
|
-
`)||"",i=null;if(!o||e.force){
|
|
522
|
-
Retry with:
|
|
523
|
-
npx @botparty/nextjs init --domain <your-domain>
|
|
524
|
-
|
|
525
|
-
Need a domain? Check available options:
|
|
526
|
-
npx -y botparty@latest domains.botparty.club
|
|
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(`
|
|
520
|
+
`);let r=Ue(k(t,"package.json")),n=!1;if(r)try{let m=JSON.parse(Qt("fs").readFileSync(k(t,"package.json"),"utf-8"));if(!{...m.dependencies,...m.devDependencies}["@botparty/nextjs"]){let w=Be(t);c("Installing @botparty/nextjs..."),Te(`${w==="pnpm"?"pnpm add":w==="yarn"?"yarn add":"npm install"} @botparty/nextjs @botparty/react`,t),p("Dependencies installed")}}catch{}else if(Er(t).filter(u=>!u.startsWith(".")).length===0){y("Scaffolding Next.js project");let u=Be(t);Te('npx -y create-next-app@latest . --ts --tailwind --eslint --app --src-dir --import-alias "@/*" --yes',t),p("Next.js project created"),n=!0,c("Installing @botparty/nextjs..."),Te(`${u==="pnpm"?"pnpm add":u==="yarn"?"yarn add":"npm install"} @botparty/nextjs @botparty/react`,t),p("Dependencies installed")}else g("No Next.js project found in this directory."),c("Run in an empty directory to scaffold a new project, or in an existing Next.js project."),process.exit(1);y("Generating ES256 keypair");let s=P(t),o=s.BOTPARTY_CLIENT_ASSERTION_KEY?.replace(/\\n/g,`
|
|
521
|
+
`)||"",i=null;if(!o||e.force){c("Generating new ES256 keypair...");let{publicKey:m,privateKey:u}=Dt("ec",{namedCurve:"P-256",publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});o=u;let w=await X(m,"ES256");i={...await N(w),use:"sig",alg:"ES256"},p("ES256 keypair generated"),c(`Public JWK: ${JSON.stringify(i)}`)}else{c("Using existing private key from .env");try{let m=await U(o,"ES256");i={...await N(m),use:"sig",alg:"ES256"},delete i.d}catch{f("Could not parse existing private key, generating new one...");let{publicKey:m,privateKey:u}=Dt("ec",{namedCurve:"P-256",publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});o=u;let w=await X(m,"ES256");i={...await N(w),use:"sig",alg:"ES256"}}}y("Configuring BotParty credentials");let l=s.BOTPARTY_CLIENT_ID||"",d=!0;l&&o&&!e.force&&(c("Found existing credentials. Validating..."),await xe(l,o)?(p("Credentials are valid"),d=!1):f("Existing credentials are invalid. Re-registering..."));let a=s.BOTPARTY_DOMAIN||"",b=!1;if(d)if(e.domain&&(a=e.domain),e.clientId)l=e.clientId,d=!1,c(`Using provided Client ID: ${l}`);else{if(!a){y("Auto-generating bpty.cloud domain"),c("No --domain specified, generating a free bpty.cloud subdomain...");let w=await import("@botparty/sdk"),_=new w.BotPartyClient;await _.ensureRegistered();let J=_.whoami().namespace,I=await _.generateToken({role:"admin"}),{slug:Y,domain:K}=await bt(J,I);c(`Generated: ${K}`),await xt(J,I,K),p(`Claimed ${K} (free)`),a=K,b=!0}c(`Registering ${a} with id.botparty.club...`);let m;try{m=(await gt(a,e.force)).txtRecord}catch(u){let w=u instanceof Error?u.message:String(u);if(w.includes("already verified")||w.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.");f("Domain is already registered."),console.log(`
|
|
528
522
|
To use your existing Client ID:
|
|
529
|
-
npx @botparty/nextjs init --domain ${
|
|
523
|
+
npx @botparty/nextjs init --domain ${a} --client-id <your-client-id>
|
|
530
524
|
|
|
531
525
|
To overwrite the previous registration:
|
|
532
|
-
npx @botparty/nextjs init --domain ${
|
|
533
|
-
`),process.exit(1)}else throw
|
|
526
|
+
npx @botparty/nextjs init --domain ${a} --force
|
|
527
|
+
`),process.exit(1)}else throw u}if(d&&m){let u=!1;try{let J=await import("@botparty/sdk"),I=new J.BotPartyClient;await I.ensureRegistered();let K=I.whoami().namespace,le=await I.generateToken({role:"admin"});u=await St(a,K,le),u&&(c("Domain is managed by BotParty. Auto-creating TXT verification record..."),await vt(a,K,le,{type:"TXT",host:"_botparty",answer:m,ttl:60}),p("TXT record created automatically"),c("Waiting for DNS propagation..."),await new Promise(Zt=>setTimeout(Zt,3e3)))}catch(ce){f(`Could not check domain ownership: ${ce.message}`)}if(!u){if(c("Checking DNS for TXT record..."),!await wt(a,m)){let J=a.split("."),I=J.slice(-2).join("."),Y=J.slice(0,-2).join("."),K=Y?`_botparty.${Y}`:"_botparty",le=Y?`
|
|
534
528
|
Alternatively, set the record at your apex domain \u2014 any of these work:
|
|
535
529
|
|
|
536
|
-
Host: ${
|
|
537
|
-
Host: _botparty.${
|
|
538
|
-
Host: ${
|
|
539
|
-
Host: ${
|
|
530
|
+
Host: ${a} Value: ${m}
|
|
531
|
+
Host: _botparty.${a} Value: ${m}
|
|
532
|
+
Host: ${I} Value: ${m}
|
|
533
|
+
Host: ${Y}._botparty.${I} Value: ${m}
|
|
540
534
|
`:`
|
|
541
535
|
Valid record locations (any one works):
|
|
542
536
|
|
|
543
|
-
Host: ${
|
|
544
|
-
Host: _botparty.${
|
|
537
|
+
Host: ${a} Value: ${m}
|
|
538
|
+
Host: _botparty.${a} Value: ${m}
|
|
545
539
|
`;console.log(`
|
|
546
540
|
DNS TXT record not found. Add this record to your domain:
|
|
547
541
|
|
|
548
|
-
Host: _botparty.${
|
|
549
|
-
Value: ${
|
|
550
|
-
${
|
|
542
|
+
Host: _botparty.${a}
|
|
543
|
+
Value: ${m}
|
|
544
|
+
${le}
|
|
551
545
|
Vercel CLI:
|
|
552
|
-
vercel dns add ${
|
|
546
|
+
vercel dns add ${I} ${K} TXT "${m}"
|
|
553
547
|
|
|
554
548
|
Then retry:
|
|
555
|
-
npx @botparty/nextjs init --domain ${
|
|
556
|
-
`),process.exit(1)}
|
|
557
|
-
`),
|
|
549
|
+
npx @botparty/nextjs init --domain ${a}${e.jwks?" --jwks":""}
|
|
550
|
+
`),process.exit(1)}p("DNS TXT record found")}c("Verifying domain with id.botparty.club...");let w={};e.jwks?w.jwksUri=`https://${a}/.well-known/jwks.json`:w.publicKey=i,l=(await ht(a,w)).clientId,p(`Domain verified! Client ID: ${l}`)}}y("Writing environment variables");let x={};if((!s.BOTPARTY_AUTH_URL||e.force)&&(x.BOTPARTY_AUTH_URL="https://id.botparty.club"),l&&(x.BOTPARTY_CLIENT_ID=l),x.BOTPARTY_CLIENT_ASSERTION_KEY=o.replace(/\n/g,"\\n"),a&&(x.BOTPARTY_DOMAIN=a),$(t,x),p(".env updated"),a){let m=k(t,".botparty-deploy.json"),u=a.endsWith(".bpty.cloud")?a.replace(".bpty.cloud",""):te(a);ae(m,JSON.stringify({projectName:u,domain:a},null,2)+`
|
|
551
|
+
`),p(`.botparty-deploy.json created (projectName="${u}", domain="${a}")`)}y("Setting up auth routes");let S=z(t),C=Et(t),h=k(t,S,"api/botparty/[...botparty]"),A=k(h,"route.ts");if(Ue(A)?c("Route handler already exists, skipping"):(Le(h,{recursive:!0}),ae(A,`export { GET, POST } from '@botparty/nextjs/handlers';
|
|
552
|
+
`),p("Created catch-all route handler")),e.jwks){let m=k(t,S,".well-known/jwks.json"),u=k(m,"route.ts");Ue(u)?c("JWKS route already exists, skipping"):(Le(m,{recursive:!0}),ae(u,`import { createJwksResponse } from '@botparty/nextjs/server';
|
|
558
553
|
|
|
559
554
|
export async function GET() {
|
|
560
555
|
return createJwksResponse();
|
|
561
556
|
}
|
|
562
|
-
`),
|
|
557
|
+
`),p("Created .well-known/jwks.json route (--jwks mode)"))}if(At(t))c("Middleware already exists, skipping");else{let m=C?k(t,"src/middleware.ts"):k(t,"middleware.ts"),u=e.jwks?"['/', '/api/public(.*)', '/.well-known(.*)']":"['/', '/api/public(.*)']";ae(m,`import { botpartyMiddleware, createRouteMatcher } from '@botparty/nextjs/server';
|
|
563
558
|
|
|
564
|
-
const isPublic = createRouteMatcher(${
|
|
559
|
+
const isPublic = createRouteMatcher(${u});
|
|
565
560
|
|
|
566
561
|
export default botpartyMiddleware((auth, req) => {
|
|
567
562
|
if (!isPublic(req)) auth.protect();
|
|
568
563
|
});
|
|
569
564
|
|
|
570
565
|
export const config = { matcher: ['/((?!_next|.*\\\\..*).*)'] };
|
|
571
|
-
`),
|
|
566
|
+
`),p("Created middleware.ts")}if(n){y("Scaffolding demo project");let m=Ot(S);for(let[u,w]of Object.entries(m)){let _=k(t,u);Le(k(_,".."),{recursive:!0}),ae(_,w),p(`Created ${u}`)}}console.log(`
|
|
572
567
|
\u2713 BotParty auth is ready!
|
|
573
568
|
|
|
574
569
|
Next steps:
|
|
@@ -577,36 +572,36 @@ export const config = { matcher: ['/((?!_next|.*\\\\..*).*)'] };
|
|
|
577
572
|
${n?` 3. Click "Open Dashboard" to test the auth flow
|
|
578
573
|
4. Try the sample API routes from the dashboard`:""}
|
|
579
574
|
Docs: https://www.npmjs.com/package/@botparty/nextjs
|
|
580
|
-
`)}import{existsSync as
|
|
575
|
+
`)}import{existsSync as jt,readFileSync as Jt}from"fs";import{resolve as Wt}from"path";async function Re(){let e=process.cwd(),t=[];console.log(`
|
|
581
576
|
@botparty/nextjs doctor
|
|
582
|
-
`),
|
|
583
|
-
`)||"",i=r.BOTPARTY_CLIENT_ID||"",
|
|
584
|
-
Summary: ${
|
|
585
|
-
`),
|
|
577
|
+
`),y("Environment variables");let r=P(e),s=["BOTPARTY_AUTH_URL","BOTPARTY_CLIENT_ID","BOTPARTY_CLIENT_ASSERTION_KEY","BOTPARTY_DOMAIN"].filter(h=>!r[h]);s.length===0?(p("All required env vars present"),t.push({id:"env-vars",pass:!0,message:"All required env vars present",fixable:!1})):(g(`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,`
|
|
578
|
+
`)||"",i=r.BOTPARTY_CLIENT_ID||"",l=r.BOTPARTY_DOMAIN||"";y("Private key");let d=null;if(o)try{d=await ie(o),p("Private key is valid ES256 PKCS8"),t.push({id:"key-valid",pass:!0,message:"Valid ES256 key",fixable:!1})}catch{g("Private key is not a valid ES256 PKCS8 key"),t.push({id:"key-valid",pass:!1,message:"Invalid ES256 key",fixable:!1})}else f("No private key to validate (BOTPARTY_CLIENT_ASSERTION_KEY missing)"),t.push({id:"key-valid",pass:!1,message:"No key present",fixable:!1});y("Server authentication");let a=null;if(i&&o)if(await xe(i,o)){p("Credentials validated against id.botparty.club"),t.push({id:"server-auth",pass:!0,message:"Credentials valid",fixable:!0});let A=await j(i,o);A&&(a=A.keyMode,c(`Key mode: ${a??"none"}`),c(`JWKS URI: ${A.jwksUri}`))}else g("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 f("Cannot validate \u2014 missing CLIENT_ID or ASSERTION_KEY"),t.push({id:"server-auth",pass:!1,message:"Missing credentials",fixable:!1});y("Route handler");let b=z(e),x=Wt(e,b,"api/botparty/[...botparty]/route.ts");if(jt(x)?Jt(x,"utf-8").includes("@botparty/nextjs/handlers")?(p("Route handler exists with correct import"),t.push({id:"route-handler",pass:!0,message:"Route handler OK",fixable:!0})):(f("Route handler exists but may have incorrect content"),t.push({id:"route-handler",pass:!1,message:"Route handler has unexpected content",fixable:!0})):(g("Route handler missing: api/botparty/[...botparty]/route.ts"),t.push({id:"route-handler",pass:!1,message:"Route handler missing",fixable:!0})),y("JWKS route"),a==="domain-hosted"){let h=Wt(e,b,".well-known/jwks.json/route.ts");jt(h)?Jt(h,"utf-8").includes("createJwksResponse")?(p("JWKS route handler exists (domain-hosted mode)"),t.push({id:"jwks-route",pass:!0,message:"JWKS route OK",fixable:!0})):(f("JWKS route exists but may have incorrect content"),t.push({id:"jwks-route",pass:!1,message:"JWKS route has unexpected content",fixable:!0})):(g("JWKS route handler missing (required for domain-hosted mode)"),t.push({id:"jwks-route",pass:!1,message:"JWKS route missing",fixable:!0}))}else c("Skipped \u2014 not in domain-hosted mode"),t.push({id:"jwks-route",pass:!0,message:"N/A (botparty-hosted)",fixable:!1});if(y("Remote JWKS"),l&&d){let h=await Se(l);if(h&&h.keys?.length>0){let A=d.x,m=d.y;h.keys.some(w=>w.x===A&&w.y===m)?(p("Remote JWKS contains the correct public key"),t.push({id:"jwks-remote",pass:!0,message:"Remote JWKS matches local key",fixable:!0})):(g("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 f("Could not fetch remote JWKS for domain"),t.push({id:"jwks-remote",pass:!1,message:"Remote JWKS not available",fixable:!0})}else f("Cannot check remote JWKS \u2014 missing domain or key"),t.push({id:"jwks-remote",pass:!1,message:"Missing domain or key",fixable:!1});let S=t.filter(h=>h.pass).length,C=t.filter(h=>!h.pass).length;return console.log(`
|
|
579
|
+
Summary: ${S} passed, ${C} failed
|
|
580
|
+
`),C>0&&c("Run `npx @botparty/nextjs fix` to auto-fix what can be fixed.\n"),t}import{mkdirSync as Bt,writeFileSync as Ut}from"fs";import{resolve as Pe}from"path";async function Lt(){let t=(await Re()).filter(l=>!l.pass);if(t.length===0){console.log(` Nothing to fix \u2014 all checks passed.
|
|
586
581
|
`);return}console.log(`
|
|
587
582
|
Attempting to fix issues...
|
|
588
583
|
`);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
|
|
590
|
-
`),
|
|
584
|
+
`)||"",o=n.BOTPARTY_CLIENT_ID||"",i=n.BOTPARTY_DOMAIN||"";for(let l of t)await Ar(l,{cwd:r,privateKeyPem:s,clientId:o,domain:i});console.log("")}async function Ar(e,t){switch(y(`Fixing: ${e.id}`),e.id){case"env-vars":f("Cannot auto-fix missing env vars. Run `npx @botparty/nextjs init` to set them up.");break;case"key-valid":f("Cannot auto-fix an invalid key. Run `npx @botparty/nextjs init --force` to regenerate.");break;case"server-auth":await Tr(t);break;case"route-handler":Rr(t);break;case"jwks-route":Pr(t);break;case"jwks-remote":await kr(t);break}}async function Tr(e){if(!e.clientId||!e.privateKeyPem){f("Cannot fix \u2014 missing CLIENT_ID or ASSERTION_KEY. Run `npx @botparty/nextjs init --force`.");return}if(await j(e.clientId,e.privateKeyPem)){c("Credentials are actually valid now (may have been a transient failure).");return}c("Attempting to re-upload public key to id.botparty.club...");try{let r=await ie(e.privateKeyPem);await ee(e.clientId,e.privateKeyPem,r)?p("Public key updated on server"):(g("Failed to update key. The local key may not match what the server expects."),f("Run `npx @botparty/nextjs init --force` to re-register with a new key."))}catch{g("Could not derive public key or update server. Run `npx @botparty/nextjs init --force`.")}}function Rr(e){let t=z(e.cwd),r=Pe(e.cwd,t,"api/botparty/[...botparty]"),n=Pe(r,"route.ts");Bt(r,{recursive:!0}),Ut(n,`export { GET, POST } from '@botparty/nextjs/handlers';
|
|
585
|
+
`),p("Created route handler")}function Pr(e){let t=z(e.cwd),r=Pe(e.cwd,t,".well-known/jwks.json"),n=Pe(r,"route.ts");Bt(r,{recursive:!0}),Ut(n,`import { createJwksResponse } from '@botparty/nextjs/server';
|
|
591
586
|
|
|
592
587
|
export async function GET() {
|
|
593
588
|
return createJwksResponse();
|
|
594
589
|
}
|
|
595
|
-
`),
|
|
590
|
+
`),p("Created JWKS route handler")}async function kr(e){if(!e.clientId||!e.privateKeyPem||!e.domain){f("Cannot fix remote JWKS \u2014 missing credentials or domain.");return}let t=await j(e.clientId,e.privateKeyPem);if(!t){f("Cannot determine key mode \u2014 server auth failed.");return}if(t.keyMode==="botparty-hosted"){c("Re-uploading public key to id.botparty.club...");try{let n=await ie(e.privateKeyPem);if(!await ee(e.clientId,e.privateKeyPem,n)){g("Failed to update key on server.");return}p("Public key updated")}catch{g("Could not update key on server.");return}c("Verifying remote JWKS with cache bypass...");let r=await Se(e.domain);r&&r.keys?.length>0?p("Remote JWKS now available"):f("Remote JWKS still not available. It may take a moment for the cache to update.")}else t.keyMode==="domain-hosted"?(f("In domain-hosted mode, the remote JWKS is served by your app."),f("Make sure the JWKS route handler is deployed and redeploy if you recently changed keys.")):f("No key mode detected. Run `npx @botparty/nextjs init` to set up keys.")}import{generateKeyPairSync as Cr}from"crypto";async function Ht(e={}){let t=process.cwd();console.log(`
|
|
596
591
|
@botparty/nextjs rotate
|
|
597
|
-
`),
|
|
598
|
-
`),o=r.BOTPARTY_DOMAIN;n||(
|
|
592
|
+
`),y("Reading current credentials");let r=P(t),n=r.BOTPARTY_CLIENT_ID,s=r.BOTPARTY_CLIENT_ASSERTION_KEY?.replace(/\\n/g,`
|
|
593
|
+
`),o=r.BOTPARTY_DOMAIN;n||(g("BOTPARTY_CLIENT_ID is not set in .env"),process.exit(1)),s||(g("BOTPARTY_CLIENT_ASSERTION_KEY is not set in .env"),process.exit(1)),o||(g("BOTPARTY_DOMAIN is not set in .env"),process.exit(1)),p("Credentials loaded"),y("Detecting key mode");let i=await j(n,s);i||(g("Could not authenticate with id.botparty.club. Is the current key valid?"),process.exit(1));let l=i.keyMode;c(`Key mode: ${l??"none"}`),c(`Domain: ${i.domain}`),y("Generating new ES256 keypair");let{publicKey:d,privateKey:a}=Cr("ec",{namedCurve:"P-256",publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}}),b=await X(d,"ES256"),x={...await N(b),use:"sig",alg:"ES256"};p("New keypair generated"),e.yes||(f("This will invalidate the current key."),console.log(`
|
|
599
594
|
To proceed, confirm with --yes:
|
|
600
595
|
npx @botparty/nextjs rotate --yes
|
|
601
|
-
`),process.exit(1)),
|
|
596
|
+
`),process.exit(1)),l==="botparty-hosted"?(y("Uploading new public key to id.botparty.club"),await ee(n,s,x)||(g("Failed to update public key on id.botparty.club"),process.exit(1)),p("Public key updated on server"),y("Updating local .env"),$(t,{BOTPARTY_CLIENT_ASSERTION_KEY:a.replace(/\n/g,"\\n")}),p(".env updated with new private key")):l==="domain-hosted"?(y("Updating local .env"),$(t,{BOTPARTY_CLIENT_ASSERTION_KEY:a.replace(/\n/g,"\\n")}),p(".env updated with new private key"),f("In domain-hosted mode, your JWKS route handler derives the key from the env var at runtime."),f("You must redeploy your app for the new key to take effect.")):(y("Uploading new public key to id.botparty.club"),await ee(n,s,x)||(g("Failed to update public key on id.botparty.club"),process.exit(1)),p("Public key updated on server"),y("Updating local .env"),$(t,{BOTPARTY_CLIENT_ASSERTION_KEY:a.replace(/\n/g,"\\n")}),p(".env updated with new private key")),y("Verifying new credentials"),await j(n,a)?p("New credentials validated successfully"):(f("Could not validate new credentials immediately \u2014 this may be a caching delay."),f("Run `npx @botparty/nextjs doctor` in a minute to verify.")),console.log(`
|
|
602
597
|
Key rotation complete!
|
|
603
598
|
|
|
604
599
|
Next steps:
|
|
605
600
|
1. Redeploy your application to pick up the new key
|
|
606
601
|
2. Run \`npx @botparty/nextjs doctor\` to verify everything is working
|
|
607
|
-
`)}var
|
|
602
|
+
`)}var Ir={mongo:{domain:"mongo.botparty.club",label:"MongoDB",provision:Kr},upstash:{domain:"upstash.botparty.club",label:"Upstash Redis",provision:Nr},s3:{domain:"s3.botparty.club",label:"S3 Storage",provision:_r}};async function Kr(e){c(`Creating MongoDB database "${e.slug}"...`);let t=await E(e.serviceDomain,"POST","/databases",e.domain,e.token,{slug:e.slug});if(!t.ok&&t.status===409){f(`Database "${e.slug}" already exists. Fetching existing details...`);let r=await E(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 Nr(e){c(`Creating Upstash Redis instance "${e.slug}"...`);let t=await E(e.serviceDomain,"POST","/redis",e.domain,e.token,{slug:e.slug}),r;if(!t.ok&&t.status===409){f(`Redis instance "${e.slug}" already exists. Fetching existing details...`);let s=await E(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}`)}c("Creating Redis credentials...");let n=await E(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 _r(e){c(`Creating S3 bucket "${e.slug}"...`);let t=await E(e.serviceDomain,"POST","/buckets",e.domain,e.token,{slug:e.slug}),r=e.slug;if(!t.ok&&t.status===409)f(`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}`)}c("Creating S3 IAM credentials...");let n=await E(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 Mt(e){let t=process.cwd(),r=e.service.toLowerCase();console.log(`
|
|
608
603
|
@botparty/nextjs add-service ${r}
|
|
609
|
-
`);let n=
|
|
604
|
+
`);let n=Ir[r];n||(g(`Unknown service: ${e.service}`),console.log(`
|
|
610
605
|
Available services:
|
|
611
606
|
mongo MongoDB database
|
|
612
607
|
upstash Upstash Redis
|
|
@@ -614,30 +609,30 @@ export async function GET() {
|
|
|
614
609
|
|
|
615
610
|
Usage:
|
|
616
611
|
npx @botparty/nextjs add-service <service> [--slug <name>]
|
|
617
|
-
`),process.exit(1));let{domain:s,privateKeyPem:o}=
|
|
612
|
+
`),process.exit(1));let{domain:s,privateKeyPem:o}=Ae(t),i=e.slug||te(s);y(`Provisioning ${n.label}`),c(`Service: ${n.domain}`),c(`Slug: ${i}`),c(`Namespace: ${s}`);let l=await ve(s,o),d=await n.provision({domain:s,token:l,slug:i,serviceDomain:n.domain});y("Writing environment variables");for(let[a,b]of Object.entries(d))c(`${a}=${b.length>60?b.slice(0,57)+"...":b}`);$(t,d),p(".env updated"),console.log(`
|
|
618
613
|
${n.label} is ready!
|
|
619
614
|
|
|
620
615
|
Environment variables written to .env:
|
|
621
|
-
${Object.keys(
|
|
616
|
+
${Object.keys(d).map(a=>` ${a}`).join(`
|
|
622
617
|
`)}
|
|
623
618
|
|
|
624
619
|
To deploy with these env vars:
|
|
625
620
|
npx @botparty/nextjs deploy
|
|
626
|
-
`)}import{existsSync as
|
|
627
|
-
`).map(r=>r.trim()).filter(r=>r&&!r.startsWith("#")):[]}function
|
|
621
|
+
`)}import{existsSync as Ft,readFileSync as He,readdirSync as Or}from"fs";import{resolve as qt,relative as Gt,extname as Vt,join as Dr}from"path";function $r(e){let t=qt(e,".botparty-deploy.json");if(!Ft(t))return{};try{let r=He(t,"utf-8"),n=JSON.parse(r);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}return{}}var jr=new Set(["node_modules",".next",".git",".turbo",".vercel","dist",".cache","__pycache__"]),Jr=new Set([".env",".env.local",".env.production",".env.development",".DS_Store"]),Wr=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"]),Br={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 Ur(e){let t=qt(e,".gitignore");return Ft(t)?He(t,"utf-8").split(`
|
|
622
|
+
`).map(r=>r.trim()).filter(r=>r&&!r.startsWith("#")):[]}function zt(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 Lr(e){let t=Vt(e).toLowerCase();return!!(Wr.has(t)||t==="")}function Hr(e,t){let r=He(e),n=Gt(t,e);if(Lr(e))return{path:n,contents:r.toString("utf-8")};let s=Vt(e).toLowerCase().slice(1)||"bin",o=Br[s]||"application/octet-stream";return{path:n,contents:`data:${o};base64,${r.toString("base64")}`}}function Mr(e){let t=Ur(e),r=[];function n(s){let o=Or(s,{withFileTypes:!0});for(let i of o){let l=Dr(s,i.name),d=Gt(e,l);if(i.isDirectory()){if(jr.has(i.name)||zt(d,t))continue;n(l)}else{if(Jr.has(i.name)||i.name.startsWith(".env")||zt(d,t))continue;try{r.push(Hr(l,e))}catch{f(`Skipping unreadable file: ${d}`)}}}}return n(e),r}var Yt="deploy.botparty.club";async function Xt(e){let t=process.cwd();console.log(`
|
|
628
623
|
@botparty/nextjs deploy
|
|
629
|
-
`);let{domain:r,privateKeyPem:n}=
|
|
630
|
-
botparty deploy domains.add --projectName ${
|
|
631
|
-
`))}}console.log(`
|
|
624
|
+
`);let{domain:r,privateKeyPem:n}=Ae(t),s=$r(t),o=e.projectName||s.projectName||te(r),i=e.domain||s.domain;y("Collecting project files");let l=Mr(t);l.length===0&&(g("No files found to deploy."),process.exit(1)),p(`${l.length} files collected`),y("Reading environment variables");let d=P(t),a=Object.keys(d).length;a>0?p(`${a} env vars from .env`):f("No env vars found in .env"),y("Deploying to deploy.botparty.club"),c(`Project: ${o}`),c("Framework: nextjs"),c(`Domain: ${r}`),i&&i!==r&&c(`Deploy domain: ${i}`);let b=await ve(r,n);c("Uploading files and env vars...");let x={projectName:o,files:l,env:d,framework:"nextjs"};i&&(x.domain=i);let S=await E(Yt,"POST","/projects/deploy",r,b,x);if(!S.ok){let u=S.data.error?.message||JSON.stringify(S.data);g(`Deployment failed: ${u}`),process.exit(1)}let C=S.data.url,h=S.data.deploymentId,A=S.data.domain||i||"";if(p(`Deployed: ${C}`),c(`Deployment ID: ${h}`),c(`Status: ${S.data.status}`),A&&c(`Domain: https://${A}`),r&&!A?.endsWith(".bpty.cloud")){y("Configuring domain alias"),c(`Adding ${r} to project...`);let u=await E(Yt,"POST",`/projects/${o}/domains`,r,b,{domain:r});if(u.ok)p(`Domain ${r} added`);else{let w=u.data.error?.message||"";w.toString().includes("already")||u.status===409?c(`Domain ${r} is already configured`):(f(`Could not add domain: ${w}`),c("You can add it manually:"),console.log(`
|
|
625
|
+
botparty deploy domains.add --projectName ${o} --domain ${r}
|
|
626
|
+
`))}}let m=A||r;console.log(`
|
|
632
627
|
Deployment complete!
|
|
633
628
|
|
|
634
|
-
URL: ${
|
|
635
|
-
Domain: https://${
|
|
636
|
-
Status: ${
|
|
629
|
+
URL: ${C}${m?`
|
|
630
|
+
Domain: https://${m}`:""}
|
|
631
|
+
Status: ${S.data.status} (check logs for build progress)
|
|
637
632
|
|
|
638
633
|
View logs:
|
|
639
|
-
npx -y botparty@latest deploy logs --projectName ${
|
|
640
|
-
`)}function
|
|
634
|
+
npx -y botparty@latest deploy logs --projectName ${o}
|
|
635
|
+
`)}function zr(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 l=i.slice(2),d=t[o+1];d&&!d.startsWith("--")?(n[l]=d,o++):n[l]=!0}else s.push(i)}return{command:r,positional:s,flags:n}}function Me(){console.log(`
|
|
641
636
|
@botparty/nextjs CLI
|
|
642
637
|
|
|
643
638
|
Usage:
|
|
@@ -669,5 +664,5 @@ ${Object.keys(p).map(c=>` ${c}`).join(`
|
|
|
669
664
|
|
|
670
665
|
General:
|
|
671
666
|
--help Show this help message
|
|
672
|
-
`)}async function
|
|
667
|
+
`)}async function Yr(){let{command:e,positional:t,flags:r}=zr(process.argv);switch((r.help||r.h)&&(Me(),process.exit(0)),e){case"init":await $t({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 Mt({service:t[0]||"",slug:typeof r.slug=="string"?r.slug:void 0});break;case"deploy":await Xt({projectName:typeof r["project-name"]=="string"?r["project-name"]:void 0});break;case"doctor":await Re();break;case"fix":await Lt();break;case"rotate":await Ht({yes:r.yes===!0});break;case"help":Me();break;default:console.error(`Unknown command: ${e}`),Me(),process.exit(1)}}Yr().catch(e=>{console.error(`
|
|
673
668
|
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.47",
|
|
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.47",
|
|
67
67
|
"jose": "^6.1.2"
|
|
68
68
|
},
|
|
69
69
|
"peerDependencies": {
|