falsepath 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ falsepath installer licence
2
+
3
+ Copyright (c) 2026 falsepath. All rights reserved.
4
+
5
+ You may download and run this software only to install, update, check and
6
+ remove the falsepath Worker in a Cloudflare account you control, for use with
7
+ the falsepath service under your agreement with falsepath.
8
+
9
+ You may not copy, modify, redistribute, sublicense or sell this software, or
10
+ use it for any other purpose, without written permission from falsepath.
11
+
12
+ The software is provided "as is", without warranty of any kind, express or
13
+ implied. In no event shall falsepath be liable for any claim, damages or other
14
+ liability arising from the software or its use, except where the law does not
15
+ allow this to be excluded.
16
+
17
+ Third-party packages this software depends on (wrangler, zod) are installed
18
+ separately by npm and keep their own licences.
19
+
20
+ Contact: engineering@falsepath.ai
package/README.md CHANGED
@@ -1,3 +1,25 @@
1
- # Temporary Holding Version
1
+ # falsepath
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Installs, updates and removes the falsepath Worker on your own Cloudflare account.
4
+
5
+ You get the command, with a one-time code, from the falsepath console:
6
+
7
+ ```
8
+ npx falsepath install --code ABCD-EFGH-JKMN
9
+ ```
10
+
11
+ **Install and update** sign you in to Cloudflare with your own login (Wrangler), check that the release is signed by falsepath and meant for your application's route, and deploy the Worker there. Then they check themselves: your application still gives the same status codes and headers at about the same speed, it keeps answering if the Worker fails, and the Worker reaches the falsepath console. The result shows in the terminal and in the console.
12
+
13
+ **Remove** takes the Worker and its storage off your account.
14
+
15
+ Each command needs its own code from the console, and each code works once.
16
+
17
+ Requirements:
18
+
19
+ - Node.js 22 or later
20
+ - a Cloudflare login that can deploy Workers and attach routes on your application's zone
21
+ - the Workers Paid plan on that account
22
+
23
+ Questions: engineering@falsepath.ai. Security reports: security@falsepath.ai.
24
+
25
+ This package is not open source; see LICENSE.
package/dist/cli.js ADDED
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env node
2
+ import{createInterface as Dt}from"node:readline";import{z as u}from"zod";var U={forbidden:"forbidden",notFound:"not_found",invalid:"invalid_request",tooLarge:"payload_too_large",rateLimited:"rate_limited",pending:"instruction_pending",codeSpent:"code_spent",codeExpired:"code_expired",clientOnly:"client_only",confirmationNeeded:"confirmation_needed",intakeMissing:"intake_missing",noVersion:"no_version",downgrade:"downgrade",specRefused:"spec_refused",unavailable:"unavailable"},G={installId:/^ins_[0-9a-f]{16}$/,appId:/^app_[0-9a-f]{12}$/,workerName:/^fp-[a-z0-9-]{1,59}$/},rn=u.string().regex(G.installId),ae=u.string().regex(G.appId),on=u.strictObject({appId:ae,version:u.number().int().min(1),kind:u.enum(["capture","enforce"]),workerSha256:u.string(),wranglerSha256:u.string(),manifestSha256:u.string(),builtAt:u.string(),workerName:u.string(),zone:u.string(),routes:u.array(u.string())}),sn=u.string().regex(G.workerName),ie=u.strictObject({action:u.enum(["install","update","remove"]),session:u.string().length(43),app:u.strictObject({id:ae,workerName:sn,zone:u.string(),routes:u.array(u.string()).min(1),checkPath:u.string().startsWith("/"),behindAccess:u.boolean()}),installId:rn,controlToken:u.string().nullable(),version:u.strictObject({number:u.number().int().min(1),kind:u.enum(["capture","enforce"]),release:on,signature:u.string()}).nullable(),secrets:u.record(u.string().regex(/^HP_[A-Z0-9_]+$/),u.string())}),Ft=u.strictObject({ok:u.boolean(),checks:u.array(u.strictObject({name:u.string().max(40),ok:u.boolean(),detail:u.string().max(200).optional()})).max(20)});import{z as T}from"zod";var C=class extends Error{constructor(t,r){super(`falsepath: the control plane refused (${t}, ${r})`);this.code=t;this.status=r}code;status},q="falsepath: the control address must be an https origin with no path, query or credentials",an=T.object({checkedIn:T.boolean(),lastSeenAt:T.number().nullable(),version:T.number().nullable(),ai:T.string().nullable()}),cn=new Set(Object.values(U));function ln(e,n={}){let t;try{t=new URL(e)}catch{throw new Error(q)}let r=n.allowLoopbackHttp===!0&&t.protocol==="http:"&&t.hostname==="127.0.0.1";if(t.protocol!=="https:"&&!r)throw new Error(q);if(t.username!==""||t.password!==""||t.search!==""||t.hash!==""||t.pathname!=="/"&&t.pathname!=="")throw new Error(q);return t.origin}var un={worker:9*1024*1024,file:256*1024,json:64*1024},dn=2e4,x=e=>new C(U.unavailable,e);async function ce(e,n,t){if(e.body===null)return"";let r=e.body.getReader(),o=[],s=0;try{for(;;){if(t.aborted)throw x(e.status);let{done:a,value:c}=await r.read();if(a)break;if(s+=c.byteLength,s>n)throw x(e.status);o.push(c)}}catch(a){throw await r.cancel().catch(()=>{}),a instanceof C?a:x(e.status)}return new TextDecoder().decode(Buffer.concat(o))}function le(e,n=fetch,t={}){let r=ln(e,t),o={...un,...t.caps},s=t.timeoutMs??dn,a=async(p,f,b={})=>{let E=AbortSignal.timeout(s),R;try{R=await n(`${r}${p}`,{...b,redirect:"error",signal:E})}catch{throw x(0)}if(R.ok)return ce(R,f,E);let nn=await ce(R,o.json,E),L={};try{L=JSON.parse(nn)}catch{}let tn=typeof L?.error=="string"&&cn.has(L.error)?L.error:U.unavailable;throw new C(tn,R.status)},c=async(p,f={})=>{let b=await a(p,o.json,f);try{return JSON.parse(b)}catch{throw x(200)}},l={"content-type":"application/json"},g=p=>({authorization:`Bearer ${p}`});return{async enrol(p,f){return ie.parse(await c("/v1/enrol",{method:"POST",headers:l,body:JSON.stringify({code:p,action:f})}))},async file(p,f){return a(`/v1/install/files/${f}`,f==="worker.js"?o.worker:o.file,{headers:g(p)})},async status(p){return an.parse(await c("/v1/install/status",{headers:g(p)}))},async report(p,f){await a("/v1/install/report",o.json,{method:"POST",headers:{...l,...g(p)},body:JSON.stringify(f)})}}}import{z as i}from"zod";function ue(e,n,t){Object.defineProperty(e,n,{value:t,enumerable:!0,configurable:!0,writable:!0})}var pn=(e,n)=>e<n?-1:e>n?1:0;function de(e){return JSON.stringify(J(e))}function J(e){if(Array.isArray(e))return e.map(J);if(e!==null&&typeof e=="object"){let n={};for(let t of Object.keys(e).sort(pn))ue(n,t,J(e[t]));return n}return e}var pe=/^[0-9a-f]{12}$/,fe=/^cap_[A-Za-z0-9_-]{4,40}$/;var fn=new TextEncoder,qt=new TextDecoder;function ge(e){return fn.encode(e)}function D(e){let n="";for(let t of e)n+=String.fromCharCode(t);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function M(e){if(/[^A-Za-z0-9_-]/.test(e))throw new Error("invalid base64url");let n=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-e.length%4)%4),t=atob(n),r=new Uint8Array(t.length);for(let o=0;o<t.length;o++)r[o]=t.charCodeAt(o);return r}var he=/^app_[0-9a-f]{12}$/,Z=/^ins_[0-9a-f]{16}$/,we=/^[A-Za-z0-9_-]{43}$/;function ye(e){let n;try{n=M(e)}catch{return null}return D(n)===e?n:null}var Y=["set-mode","pause","start-recording","send-samples","release-session","analyse"],me=i.strictObject({id:i.string().regex(fe),epoch:i.number().int().min(1)}),er={"set-mode":i.strictObject({mode:i.enum(["observe","enforce"])}),pause:i.strictObject({on:i.boolean()}),"start-recording":i.strictObject({windowDays:i.number().int().min(1).max(30)}),"send-samples":me,"release-session":i.strictObject({sid:i.string().regex(pe)}),analyse:me},gn={signature:"signature",install:"install",replay:"replay",expired:"expired",schema:"schema",unsupported:"unsupported",pinned:"pinned",store:"store"},mn=Object.values(gn),nr=i.strictObject({installId:i.string().regex(Z),seq:i.number().int().min(1),verb:i.enum(Y),args:i.unknown(),issuedAt:i.number().int().nonnegative(),expiresAt:i.number().int().nonnegative()}),hn=i.union([i.strictObject({seq:i.number().int().min(0),verb:i.enum(Y),result:i.literal("applied")}),i.strictObject({seq:i.number().int().min(0),verb:i.enum(Y).nullable(),result:i.literal("refused"),reason:i.enum(mn)})]);var wn="falsepath-release-v1",be={name:"Ed25519"},yn=(e,n)=>ge(`${e}
3
+ ${de(n)}`);async function bn(e){return crypto.subtle.importKey("raw",e,be,!1,["verify"])}async function Rn(e,n,t){let r=ye(n);if(r===null||r.length!==64)return!1;try{return await crypto.subtle.verify(be,await bn(e),r,t)}catch{return!1}}function Re(e){let n=e.split(".");if(n.length!==2)return null;let[t,r]=n;return Z.test(t)&&we.test(r)?{installId:t,secret:r}:null}var Se="https://control.falsepath.ai",Q="x-hp-probe",ke=(e,n)=>`probe:${e}.${n}`;var tr=i.object({v:i.literal(1),installId:i.string().regex(Z).optional(),lastSeq:i.number().int().min(0),mode:i.enum(["observe","enforce"]).optional(),epoch:i.number().int().min(1).optional(),windowDays:i.number().int().min(1).max(30).optional(),samples:i.array(i.string()).max(64),outcomes:i.array(hn).max(64),sent:i.array(i.string()).max(400),scannedAt:i.number().int().nonnegative().optional()});var ve=/^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,Sn=/^fp-[a-z0-9-]{1,59}$/,kn=8,vn=/^([^/]+)(\/(?:[A-Za-z0-9._~-]+\/)*)\*$/;function En(e,n){let t=vn.exec(e);if(t===null)return!1;let[,r,o]=t;return!ve.test(r)||!(r===n||r.endsWith(`.${n}`))?!1:!o.split("/").some(s=>s==="."||s==="..")}var Ee=i.strictObject({appId:i.string().regex(he),version:i.number().int().min(1),kind:i.enum(["capture","enforce"]),workerSha256:i.string().regex(/^[0-9a-f]{64}$/),wranglerSha256:i.string().regex(/^[0-9a-f]{64}$/),manifestSha256:i.string().regex(/^[0-9a-f]{64}$/),builtAt:i.string().min(1),workerName:i.string().regex(Sn),zone:i.string().regex(ve),routes:i.array(i.string().max(300)).min(1).max(kn)}).refine(e=>e.routes.every(n=>En(n,e.zone)),{path:["routes"],message:"each route is <host><path>* on the zone"});async function _e(e,n,t){return Rn(e,t,yn(wn,n))}var rr=i.strictObject({url:i.url().refine(e=>{if(!URL.canParse(e))return!1;let n=new URL(e);return n.protocol==="https:"&&n.username===""&&n.password===""&&(n.pathname==="/"||n.pathname==="")&&n.search===""&&n.hash===""},{message:"control.url is an https origin with no user, path, query or fragment"}).transform(e=>new URL(e).origin),instructionKey:i.string().regex(we,"control.instructionKey is a raw Ed25519 public key in base64url (43 characters)").refine(e=>ye(e)!==null,{message:"control.instructionKey is canonical base64url (no padding bits set)"}),appId:i.string().regex(he),version:i.number().int().min(1)});import{parseArgs as Ot}from"node:util";var $={SIGINT:130,SIGTERM:143,SIGHUP:129},F=class{signalled=null;stop=new AbortController;exited;markExited;constructor(){this.exited=new Promise(n=>{this.markExited=n})}tasks=new Map;next=0;add(n){let t=this.next++;return this.tasks.set(t,n),()=>{this.tasks.delete(t)}}async runAll(){let n=[...this.tasks.entries()].sort(([t],[r])=>r-t).map(([,t])=>t);this.tasks.clear();for(let t of n)try{await t()}catch{}}};function Ae(e,n,t,r){let o=!1,s=Object.keys($).map(a=>{let c=()=>{o||(o=!0,e.signalled=a,e.stop.abort(),e.runAll().finally(()=>{try{r?.()}catch{}t($[a]),e.markExited()}))};return n.on(a,c),[a,c]});return()=>{for(let[a,c]of s)n.off(a,c)}}import{randomBytes as Fn}from"node:crypto";import{z as v}from"zod";import{mkdtempSync as jn,rmSync as re,writeFileSync as z}from"node:fs";import{tmpdir as Wn}from"node:os";import{join as H}from"node:path";import{createHmac as _n,randomBytes as An}from"node:crypto";var Tn=new Set(["date","age","cf-ray","cf-cache-status","server-timing","report-to","nel","alt-svc","content-length","etag","last-modified","x-request-id","set-cookie","expires","vary","cache-control","server","transfer-encoding","connection","keep-alive"]),X=15e3;async function ee(e,n,t,r=5,o={}){let s=[];for(let a=0;a<r;a++){let c=t(),l=await n(e,{redirect:"manual",headers:o,signal:AbortSignal.timeout(X)});await l.arrayBuffer().catch(()=>{});let g=[];l.headers.forEach((f,b)=>{Tn.has(b)||g.push(b)});let p=l.headers.get("location");s.push({status:l.status,headers:g.sort(),ms:t()-c,location:xn(p),accessLogin:Cn(p)})}return s}var xn=e=>{if(e===null)return null;try{return new URL(e).origin}catch{return null}},Cn=e=>{if(e===null)return!1;try{let n=new URL(e);return n.hostname.endsWith(".cloudflareaccess.com")||n.pathname.startsWith("/cdn-cgi/access/")}catch{return!1}},Te=e=>[...e].sort((n,t)=>n-t)[Math.floor(e.length/2)];function ne(e,n){let t=new Set(e.map(a=>a.status));if(!n.every(a=>t.has(a.status)))return"app-changed";let r=e[0].headers.join(",");if(!n.every(a=>a.headers.join(",")===r))return"app-changed";let o=Te(e.map(a=>a.ms));return Te(n.map(a=>a.ms))<=o+Math.max(o*.25,50)?"same":"slower"}var On=new Set([301,302,303,307,308]);function O(e){return e.status===401||e.status===403||On.has(e.status)&&e.accessLogin}function xe(e,n){let t=e[0];return O(t)&&n.every(r=>O(r)&&r.status===t.status&&r.location===t.location)}function Ce(e,n,t=An(8).toString("hex")){let r=_n("sha256",Buffer.from(e,"utf8")).update(ke(String(n),t)).digest();return{header:`${n}.${t}.${D(new Uint8Array(r))}`,nonce:t}}function Oe(e){let n=e.map(t=>t.split("/")[0]);return n.find(t=>!t.includes("*"))??n[0].replace(/^\*\.?/,"")}function Ie(e){return/"id":\s*"([0-9a-f]{32})"/.exec(e)?.[1]??null}function I(e,n){let t=n==="{"?"}":"]",r=e.indexOf(n),o=e.lastIndexOf(t);if(!(r===-1||o<r))try{return JSON.parse(e.slice(r,o+1))}catch{return}}function Pe(e){return/permission to access the zone/i.test(e)||/\/routes\b/.test(e)&&/Authentication error|permission/i.test(e)}function Ne(e){let[n]=e.split(".").map(Number);return n>=22}import{createHash as In}from"node:crypto";var w={signature:"falsepath: the version is not signed by falsepath; nothing was deployed",sums:"falsepath: the downloaded files do not match the signed version; nothing was deployed",app:"falsepath: the version is for another app; nothing was deployed",downgrade:"falsepath: the version is older than the installed one; pass --allow-downgrade to install it anyway",target:"falsepath: the app's Worker, zone or routes are not the ones the version is signed for; nothing was deployed"},te=e=>In("sha256").update(e).digest("hex");async function Le(e,n,t,r){let{signature:o}=e.version;if(!await _e(M(t),e.version.release,o))throw new Error(w.signature);let s=Ee.safeParse(e.version.release);if(!s.success)throw new Error(w.target);let a=s.data;if(a.appId!==e.app.id||a.version!==e.version.number)throw new Error(w.app);let{workerName:c,zone:l,routes:g}=e.app;if(a.workerName!==c||a.zone!==l||JSON.stringify(a.routes)!==JSON.stringify(g))throw new Error(w.target);if(te(n.worker)!==a.workerSha256||te(n.wrangler)!==a.wranglerSha256||te(n.manifest)!==a.manifestSha256)throw new Error(w.sums);if(r.installedVersion!==void 0&&a.version<r.installedVersion&&r.allowDowngrade!==!0)throw new Error(w.downgrade);return a}var _={"not-logged-in":"Run `npx wrangler login` with the Cloudflare account that holds the zone, then run the command again.","route-permission":"Your login cannot attach routes on this zone, and the run stopped before the route was added, so the Worker is deployed without it. Have someone who can edit the zone add the route shown above in Workers Routes, then run `npx falsepath update` with a fresh code from the console. To take the Worker out instead, run `npx falsepath remove --code <new code>`.","route-permission-pipeline":"Your login cannot attach routes on this zone, so the Worker is deployed without its route. Run the install again on a terminal, where it shows the route to add and waits while you add it; or have someone who can edit the zone add the app's route for its Worker in Workers Routes, then run `npx falsepath update` with a fresh code from the console. To take the Worker out instead, run `npx falsepath remove --code <new code>`.","app-changed":"The app answered differently after the install. Run `npx falsepath remove --code <new code>` from the console to take it out, and tell us.",slower:"The app got slower after the install beyond the allowed margin. Remove it as above and tell us.","fail-open":"The app did not keep working when the Worker failed on purpose. Remove it as above and tell us.","no-check-in":"The Worker has not reached falsepath yet. Check that outgoing requests to the control plane are allowed, then run update again.","route-missing":"The Worker is deployed but its route did not answer the signed probe. Check the route in Workers Routes, and check that this machine's clock is right (the probe is refused when it is more than five minutes off).","node-too-old":"falsepath needs Node.js 22 or newer. Update Node, then run the command again.","account-ambiguous":"Your login holds several Cloudflare accounts. Set CLOUDFLARE_ACCOUNT_ID to the account that holds the zone, then run the command again.","no-account":"Your login holds no Cloudflare account this command can use. Log in with the account that holds the zone, then run the command again.","enrol-refused":"The control plane refused the code (it works once, for one action, for 24 hours). Copy a fresh command from the console.","control-unreachable":"The control plane did not answer during the run. Check that this machine can reach it, then copy a fresh command from the console.","no-version":"There is no version to deploy for this app yet. Check the app page in the console.","verify-signature":w.signature,"verify-sums":w.sums,"verify-app":w.app,"verify-downgrade":w.downgrade,"app-unreachable":"The app did not answer on its registered check path from this machine. Check the address in the console, then run the command again.","wrangler-failed":"A Wrangler command failed. Run the command again; if it fails the same way, tell us which step failed.","deploy-failed":"Wrangler could not deploy the Worker. Check that your login may edit Workers on this account, then run the command again.","access-enforced":"The app no longer asks for the Cloudflare Access login after the install. Run `npx falsepath remove --code <new code>` from the console at once, and tell us.","drill-left":"The fail-open drill could not be switched off. Run `npx wrangler secret delete HP_FAIL_OPEN_DRILL --name` followed by your Worker's name, then tell us.","bad-app":"The app's settings name a Worker this installer will not create (names start with fp- and use lower-case letters, digits and dashes), or a Worker, zone or routes the version is not signed for. Nothing was deployed. Tell us.","access-baseline":"The app is registered as behind Cloudflare Access, but its check path did not ask for the Access login before the install. Check the Access application and the check path in the console, then copy a fresh command.","floor-missing":"The installed version could not be read from your own Cloudflare account (the installer keeps it in the Worker's KV namespace), so nothing was deployed. Copy a fresh install command from the console and run it; install writes it again.","floor-unreadable":"The installed version recorded in your own Cloudflare account (in the Worker's KV namespace) could not be read, so nothing was deployed. Run remove with a fresh remove command from the console, then install again; if that fails too, tell us.","target-changed":"This version installs to another Worker, zone or routes than the version installed now, so nothing was deployed. If the console shows the app's new address and you expect the change, run the command again on a terminal and answer yes, or add --accept-target-change in a pipeline; otherwise tell us.","app-mismatch":"The Worker named for removal is not recorded as this app's in your Cloudflare account, so nothing was removed. Tell us.","route-unchecked-access":"Warning: route not checked (behind Access; set a service token to check it). Cloudflare Access answers before the Worker, so this run could not reach it. Create an Access service token the app's Access policy admits (a Service Auth rule), set FALSEPATH_ACCESS_CLIENT_ID and FALSEPATH_ACCESS_CLIENT_SECRET to it, and run the command again with a fresh code to check the route.","access-token-partial":"Set both FALSEPATH_ACCESS_CLIENT_ID and FALSEPATH_ACCESS_CLIENT_SECRET (an Access service token), or neither, then run the command again.","access-token-refused":"Cloudflare Access did not admit the service token in FALSEPATH_ACCESS_CLIENT_ID and FALSEPATH_ACCESS_CLIENT_SECRET. Add it to the app's Access policy (a Service Auth rule), or unset both, then run the command again with a fresh code. Nothing was deployed.","session-ending":"The one-hour install session is about to end. Copy a fresh command from the console and run it again.","wrangler-timeout":"A Wrangler command took too long and was stopped. Check this machine's connection to Cloudflare, then run the command again.",unexpected:"The installer stopped on an unexpected error. Run the command again with a fresh code; if it repeats, tell us.","ai-absent":"Warning: the Worker reports no AI binding. It works without it; the AI-written answers stay off until the binding is available."},Ue=e=>e!==void 0&&Object.hasOwn(_,e),Pn=e=>e===!0?"\u2713":e===!1?"\u2717":"\u2026";function De(e){let n=e.map(r=>`${Pn(r.ok)} ${r.name}`),t=e.find(r=>r.ok===!1);return t!==void 0&&n.push("",Ue(t.detail)?_[t.detail]:`The step "${t.name}" failed.`),n}function j(e){return{ok:e.every(n=>n.ok===!0),checks:e.map(n=>({name:n.name,ok:n.ok===!0,...Ue(n.detail)?{detail:n.detail}:{}}))}}import{spawn as Nn}from"node:child_process";import{createRequire as Ln}from"node:module";import{dirname as Un,join as Dn}from"node:path";var W={code:124,stdout:"",stderr:"falsepath: the Wrangler command took too long and was stopped"},Me={code:130,stdout:"",stderr:"falsepath: the Wrangler command was stopped"},Mn=5e3;function $e(e=Dn(Un(Ln(import.meta.url).resolve("wrangler/package.json")),"bin","wrangler.js")){return{run:(n,t={})=>new Promise((r,o)=>{if(t.signal?.aborted===!0){r(Me);return}let s=Nn(process.execPath,[e,...n],{cwd:t.cwd,env:{...process.env,...t.env},stdio:t.inherit===!0?"inherit":["pipe","pipe","pipe"],shell:!1,detached:t.detached===!0}),a="",c="",l=!1,g=t.timeoutMs===void 0?void 0:setTimeout(()=>{l=!0,s.kill("SIGKILL")},t.timeoutMs),p=!1,f,b=()=>{p=!0,s.kill("SIGTERM"),f=setTimeout(()=>{s.kill("SIGKILL")},Mn),f.unref()};t.signal?.addEventListener("abort",b,{once:!0});let E=()=>{clearTimeout(g),clearTimeout(f),t.signal?.removeEventListener("abort",b)};s.stdout?.setEncoding("utf8"),s.stderr?.setEncoding("utf8"),s.stdout?.on("data",R=>{a+=R}),s.stderr?.on("data",R=>{c+=R}),s.stdin?.on("error",()=>{}),s.on("error",R=>{E(),o(R)}),s.on("close",R=>{E(),r(l?W:p?Me:{code:R??1,stdout:a,stderr:c})}),s.stdin?.end(t.input??"")})}}var $n=["compatibility_date","compatibility_flags","durable_objects","migrations","observability","vars"];function Fe(e,n){let t=JSON.parse(e),r=Object.fromEntries($n.filter(o=>Object.hasOwn(t,o)).map(o=>[o,t[o]]));return`${JSON.stringify({...r,name:n.workerName,main:"worker.js",no_bundle:!0,workers_dev:!1,routes:n.routes.map(o=>({pattern:o,zone_name:n.zone})),kv_namespaces:[{binding:"HP_FLAGS",id:n.kvId}],triggers:{crons:["* * * * *"]},ai:{binding:"AI"}},null,2)}
4
+ `}function je(e){let{routes:n,...t}=JSON.parse(e);return`${JSON.stringify(t,null,2)}
5
+ `}var zn=10*6e4,Hn=2*6e4,Vn=10*6e4,P=1e4,Bn=6,oe=45*6e4,Kn=55*6e4,Gn=/^fp-[a-z0-9-]{1,59}$/,qn=/\[code: (?:10007|10090)\]/,Jn=96,V=5,Yn=2,Zn=3,Qn=/^[0-9a-f]{32}$/,Xn=new Set(["HP_SIGNING_SECRET","HP_INGEST_SECRET","HP_ACCESS_CLIENT_ID","HP_ACCESS_CLIENT_SECRET"]),Be="installer:floor",Ke="installer:app",et=v.object({appId:v.string(),version:v.number().int().min(0),workerName:v.string(),zone:v.string(),routes:v.array(v.string())}),nt=/ - 404: Not Found/,tt="route (warning: not checked)",rt="falsepath: the result could not be sent to the control plane; the checklist above is the result.",ot="Waiting for the Worker's first check-in: Cloudflare starts its schedule within a few minutes, at most 15.",st=e=>` still waiting: ${e} min of up to 16`,We=6e4/P,B=class extends Error{},N=class extends Error{},k=e=>{if(e.d.cleanup?.signalled!=null)throw new N},K=e=>!e.d.pipeline&&e.d.ask!==void 0,h=(e,n)=>{e.d.pipeline||e.d.print?.(n)},Ge=(e,n)=>{e.steps.push(n),h(e,`${n.ok===!0?"\u2713":n.ok===!1?"\u2717":"\u2026"} ${n.name}`)},m=(e,n,t)=>{k(e),Ge(e,{name:n,ok:!0,...t!==void 0?{detail:t}:{}})},d=(e,n,t)=>{throw Ge(e,{name:n,ok:!1,detail:t}),new B};async function y(e,n,t={}){t.detached!==!0&&k(e);let r=e.env!==void 0&&!n.includes("--config")?[...n,"--config",e.config]:n,o=t.detached===!0?void 0:e.d.cleanup?.stop.signal,s,a=new Promise(l=>{s=l}),c=o===void 0?void 0:e.d.cleanup?.add(()=>a);try{return await e.d.runner.run(r,{cwd:e.dir,timeoutMs:Hn,...e.env!==void 0?{env:e.env}:{},...o!==void 0?{signal:o}:{},...t})}catch{return{code:1,stdout:"",stderr:""}}finally{s(),c?.()}}var qe=e=>e.code===W.code&&e.stderr===W.stderr,S=(e,n,t,r="wrangler-failed")=>d(e,n,qe(t)?"wrangler-timeout":r);async function Je(e){let n=jn(H(Wn(),"falsepath-")),t={d:e,steps:[],dir:n,config:H(n,"wrangler.jsonc"),enrolledAt:e.now(),through:{}},r=e.cleanup?.add(()=>re(n,{recursive:!0,force:!0}));try{Ne(e.nodeVersion??process.versions.node)||d(t,"node","node-too-old"),m(t,"node"),await it(t);let s=await lt(t);e.action==="remove"?await ut(t,s):await dt(t,s)}catch(s){!(s instanceof B)&&!(s instanceof N)&&e.cleanup?.signalled==null&&t.steps.push({name:"installer",ok:!1,detail:"unexpected"})}finally{re(n,{recursive:!0,force:!0}),r?.(),e.cleanup?.signalled==null&&await at(t)}let o=e.cleanup?.signalled;return{ok:o==null&&t.steps.every(s=>s.ok===!0),steps:t.steps,...o!=null?{aborted:o}:{}}}async function at(e){if(e.session!==void 0)try{await e.d.control.report(e.session,j(e.steps))}catch{h(e,rt)}}async function ze(e){let n=await y(e,["whoami","--json"]);if(n.code!==0)return null;let t=I(n.stdout,"{");return t?.loggedIn!==!0||!Array.isArray(t.accounts)?null:{accounts:t.accounts.filter(o=>typeof o?.id=="string"&&Qn.test(o.id)).map(o=>({id:o.id,name:typeof o.name=="string"?o.name:""}))}}async function it(e){let n=await ze(e);if(n===null&&K(e)&&(await y(e,["login"],{inherit:!0,timeoutMs:Vn}),n=await ze(e)),n===null)return d(e,"wrangler login","not-logged-in");let t=await ct(e,n.accounts);z(e.config,`${JSON.stringify({account_id:t})}
6
+ `),e.env={CLOUDFLARE_ACCOUNT_ID:t},m(e,"wrangler login")}async function ct(e,n){if(n.length===0)return d(e,"wrangler login","no-account");let t=e.d.env?.CLOUDFLARE_ACCOUNT_ID;if(t!==void 0&&t!=="")return n.find(o=>o.id===t)?.id??d(e,"wrangler login","account-ambiguous");if(n.length===1)return n[0].id;if(!K(e))return d(e,"wrangler login","account-ambiguous");h(e,"Your login holds several Cloudflare accounts:"),n.forEach((o,s)=>h(e,` ${s+1}. ${o.name} (${o.id})`));let r=Number((await e.d.ask("The number of the account that holds the zone: ").catch(()=>"")).trim());return k(e),n[r-1]?.id??d(e,"wrangler login","account-ambiguous")}async function lt(e){let n;try{n=await e.d.control.enrol(e.d.code,e.d.action)}catch{return d(e,"enrol","enrol-refused")}return e.session=n.session,e.enrolledAt=e.d.now(),Gn.test(n.app.workerName)||d(e,"enrol","bad-app"),m(e,"enrol"),n}async function ut(e,n){let t=await Ye(e,n.app.workerName,"kv namespace");if(t!==null){let s=await Ze(e,Ke,t);s.missing!==!0&&s.value===void 0&&S(e,"remove worker",s.res),s.value?.trim()!==n.app.id&&d(e,"remove worker","app-mismatch")}let r=await y(e,["delete","--name",n.app.workerName,"--force"]);if(r.code!==0&&!qn.test(`${r.stdout}
7
+ ${r.stderr}`)&&S(e,"remove worker",r),m(e,"remove worker"),t===null)return m(e,"remove kv namespace");let o=await y(e,["kv","namespace","delete","--namespace-id",t,"--skip-confirmation"]);o.code!==0&&S(e,"remove kv namespace",o),m(e,"remove kv namespace")}async function dt(e,n){let t=await pt(e,n),r=t.release,o=await Ye(e,r.workerName,"installed version");await wt(e,r,o);let s=`https://${Oe(r.routes)}${n.app.checkPath}`,{open:a,baseline:c}=await ft(e,n,s),l=o??await mt(e,r.workerName);await Qe(e,"kv namespace",Ke,r.appId,l),m(e,"kv namespace"),h(e,`Deploying to ${se(r)}`);let g=await Rt(e,t,l);await St(e,n,t.release);let p=g?null:e.enrolledAt+oe;g||await vt(e,r,e.enrolledAt+oe);let f=!n.app.behindAccess||Object.keys(e.through).length>0;e.d.action==="install"&&await(f?Et(e,n,s,l,p):He(e)),await _t(e,s,c),e.d.action==="update"&&await(f?m(e,"route (checked by the app check)"):He(e)),await Tt(e,r.workerName,s,c),n.app.behindAccess&&await xt(e,s,a),await Ct(e,t.release.version)}async function pt(e,n){if(n.version===null)return d(e,"verify","no-version");let t,r;try{let s=n.session,[a,c,l]=await Promise.all([e.d.control.file(s,"worker.js"),e.d.control.file(s,"wrangler.jsonc"),e.d.control.file(s,"MANIFEST.json")]);t={worker:a,wrangler:c,manifest:l},e.d.action==="update"&&(r=(await e.d.control.status(s)).version??void 0)}catch{return d(e,"verify","control-unreachable")}let o;try{o=await Le({app:n.app,version:n.version},t,e.d.releaseKey,{...r!==void 0?{installedVersion:r}:{},allowDowngrade:e.d.allowDowngrade===!0})}catch(s){let a=Object.keys(w).find(c=>s instanceof Error&&s.message===w[c]);return d(e,"verify",a==="target"?"bad-app":`verify-${a??"signature"}`)}return m(e,"verify"),{files:t,release:o}}async function ft(e,n,t){let r=n.app.behindAccess?gt(e):null,o=await A(e,"baseline",t,r===null?V:1,{open:!0});n.app.behindAccess&&!O(o[0])&&d(e,"baseline","access-baseline"),r!==null&&(e.through=r);let s=r===null?o:await A(e,"baseline",t,V);return r!==null&&s.some(O)&&d(e,"baseline","access-token-refused"),m(e,"baseline"),{open:o,baseline:s}}function gt(e){let n=e.d.env?.FALSEPATH_ACCESS_CLIENT_ID,t=e.d.env?.FALSEPATH_ACCESS_CLIENT_SECRET,r=o=>o!==void 0&&o!=="";return r(n)!==r(t)?d(e,"baseline","access-token-partial"):r(n)?{"cf-access-client-id":n,"cf-access-client-secret":t}:null}function He(e){m(e,tt,"route-unchecked-access"),h(e,_["route-unchecked-access"])}async function A(e,n,t,r,o={}){try{return await ee(t,e.d.appFetch,e.d.now,r,o.open===!0?{}:e.through)}catch{return d(e,n,"app-unreachable")}}async function Ye(e,n,t){let r=`${n}-flags`,o=await y(e,["kv","namespace","list"]),s=o.code===0?I(o.stdout,"["):void 0;return Array.isArray(s)?s.find(c=>c?.title===r&&typeof c.id=="string"&&/^[0-9a-f]{32}$/.test(c.id))?.id??null:S(e,t,o)}async function mt(e,n){let t=await y(e,["kv","namespace","create",`${n}-flags`]),r=t.code===0?Ie(t.stdout):null;return r===null?S(e,"kv namespace",t):r}async function Ze(e,n,t){let r=await y(e,["kv","key","get",n,"--namespace-id",t,"--remote"]);return r.code===0?{value:r.stdout,res:r}:nt.test(`${r.stdout}
8
+ ${r.stderr}`)?{missing:!0,res:r}:{res:r}}var se=e=>`Worker ${e.workerName}, zone ${e.zone}, routes ${e.routes.join(", ")}`,ht=(e,n)=>e.workerName===n.workerName&&e.zone===n.zone&&JSON.stringify(e.routes)===JSON.stringify(n.routes);async function wt(e,n,t){let r="installed version",o=t===null?{missing:!0}:await Ze(e,Be,t);if(o.missing!==!0&&o.value===void 0&&S(e,r,o.res),o.value===void 0)return e.d.action==="update"&&d(e,r,"floor-missing"),m(e,r);let s=et.safeParse(I(o.value,"{"));if(!s.success)return d(e,r,"floor-unreadable");let a=s.data;a.appId!==n.appId&&d(e,r,"bad-app"),n.version<a.version&&e.d.allowDowngrade!==!0&&d(e,r,"verify-downgrade"),!ht(a,n)&&!await yt(e,a,n)&&d(e,r,"target-changed"),m(e,r)}async function yt(e,n,t){if(e.d.acceptTargetChange===!0)return!0;if(!K(e))return!1;h(e,"This version installs to another target than the one installed:"),h(e,` installed: ${se(n)}`),h(e,` this version: ${se(t)}`);let r=await e.d.ask("Type yes to install it there: ").catch(()=>"");return k(e),r.trim().toLowerCase()==="yes"}async function Qe(e,n,t,r,o){let s=await y(e,["kv","key","put",t,r,"--namespace-id",o,"--remote"]);s.code!==0&&S(e,n,s)}async function bt(e,n,t){let{appId:r,version:o,workerName:s,zone:a,routes:c}=n;await Qe(e,"deploy",Be,JSON.stringify({appId:r,version:o,workerName:s,zone:a,routes:c}),t)}async function Rt(e,n,t){z(H(e.dir,"worker.js"),n.files.worker);let{workerName:r,routes:o,zone:s}=n.release,a=JSON.parse(Fe(n.files.wrangler,{workerName:r,routes:o,zone:s,kvId:t})),c=`${JSON.stringify({...a,account_id:e.env.CLOUDFLARE_ACCOUNT_ID},null,2)}
9
+ `,l=async b=>(z(e.config,b),y(e,["deploy"],{timeoutMs:zn})),g=async()=>{await bt(e,n.release,t),m(e,"deploy"),h(e,`Worker ${r}`)},p=await l(c);if(p.code===0)return await g(),!0;if(!Pe(`${p.stdout}
10
+ ${p.stderr}`))return S(e,"deploy",p,"deploy-failed");let f=await l(je(c));return f.code!==0?S(e,"deploy",f,"deploy-failed"):(await g(),!1)}async function St(e,n,t){let r=await y(e,["secret","list","--name",t.workerName]),o=r.code===0?I(r.stdout,"["):void 0;if(!Array.isArray(o))return S(e,"secrets",r);let s=new Set(o.map(l=>l?.name).filter(l=>typeof l=="string")),a=kt(e,n,t,s);if(Object.keys(a).length===0)return m(e,"secrets");let c=H(e.dir,"secrets.json");try{z(c,JSON.stringify(a),{mode:384});let l=await y(e,["secret","bulk",c,"--name",t.workerName]);l.code!==0&&S(e,"secrets",l)}finally{re(c,{force:!0})}m(e,"secrets")}var Ve=()=>Fn(32).toString("hex");function kt(e,n,t,r){let o={};if(t.kind==="enforce")for(let[s,a]of Object.entries(n.secrets))Xn.has(s)&&(o[s]=a);if(e.d.action==="install"){if(n.controlToken===null)return d(e,"secrets","enrol-refused");o.HP_CONTROL_TOKEN=n.controlToken}for(let s of["HP_SIGNING_SECRET","HP_INGEST_SECRET"])!Object.hasOwn(o,s)&&!r.has(s)&&(o[s]=Ve());return r.has("HP_ORIGIN_READ_SECRET")||(o.HP_ORIGIN_READ_SECRET=Ve()),o}async function vt(e,n,t){K(e)||d(e,"route","route-permission-pipeline"),h(e,"Your login cannot attach routes on this zone. In the Cloudflare dashboard, Workers Routes, add:");for(let s of n.routes)h(e,` route ${s} -> Worker ${n.workerName}`);let r=e.d.ask("Press Enter once the route is added. ").then(()=>"enter",()=>"closed"),o=await Promise.race([r,e.d.sleep(Math.max(0,t-e.d.now())).then(()=>"late")]);k(e),o==="late"&&d(e,"route","session-ending"),o==="closed"&&d(e,"route","route-permission")}async function Et(e,n,t,r,o){let s=n.controlToken===null?null:Re(n.controlToken);if(s===null)return d(e,"route","enrol-refused");let a=o===null?Bn:Math.ceil(oe/P);for(let c=0;c<a;c++){c>0&&await e.d.sleep(P);let{header:l,nonce:g}=Ce(s.secret,e.d.now());try{await(await e.d.appFetch(t,{redirect:"manual",headers:{...e.through,[Q]:l},signal:AbortSignal.timeout(X)})).arrayBuffer()}catch{}let p=await y(e,["kv","key","get",`probe:${g}`,"--namespace-id",r,"--remote"]);if(p.code===0&&p.stdout.trim()!=="")return m(e,"route");o!==null&&e.d.now()>=o&&d(e,"route","session-ending")}d(e,"route","route-missing")}async function _t(e,n,t){await A(e,"app-unchanged",n,Yn);let r=ne(t,await A(e,"app-unchanged",n,V));r==="slower"&&(await e.d.sleep(P),r=ne(t,await A(e,"app-unchanged",n,V))),r!=="same"&&d(e,"app-unchanged",r),m(e,"app-unchanged")}function At(e,n){let t=null,r=null;return{put(){return t=Promise.resolve().then(()=>y(e,["secret","put","HP_FAIL_OPEN_DRILL","--name",n],{input:"1"})),t},off(){return r??=(async()=>t===null?{code:0,stdout:"",stderr:""}:(await t.catch(()=>{}),y(e,["secret","delete","HP_FAIL_OPEN_DRILL","--name",n],{detached:!0})))(),r}}}async function Tt(e,n,t,r){let o=new Set(r.map(l=>l.status)),s=At(e,n),a=e.d.cleanup?.add(async()=>{(await s.off()).code!==0&&e.d.warn?.(_["drill-left"])}),c="fail-open";try{k(e);let l=await s.put();k(e),l.code!==0?c=qe(l)?"wrangler-timeout":"wrangler-failed":(await ee(t,e.d.appFetch,e.d.now,Zn,e.through)).every(g=>o.has(g.status))&&(c=null)}catch(l){if(l instanceof N)throw l}finally{(await s.off()).code!==0&&(c="drill-left"),a?.()}k(e),c!==null&&d(e,"fail-open",c),m(e,"fail-open")}async function xt(e,n,t){xe(t,await A(e,"access-enforced",n,1,{open:!0}))||d(e,"access-enforced","access-enforced"),m(e,"access-enforced")}async function Ct(e,n){for(let t=0;t<Jn;t++){t>0&&await e.d.sleep(P),k(e),e.d.now()>=e.enrolledAt+Kn&&d(e,"check-in","session-ending");let r=await e.d.control.status(e.session).catch(()=>null);if(r===null||!r.checkedIn||r.version!==n){t===0?h(e,ot):t%We===0&&h(e,st(t/We));continue}return m(e,"check-in"),r.ai==="bound"?m(e,"ai"):(m(e,"ai (warning: not bound)","ai-absent"),h(e,_["ai-absent"]))}d(e,"check-in","no-check-in")}var It=`usage: npx falsepath <install|update|remove> --code <code> [--pipeline] [--allow-downgrade] [--accept-target-change] [--control <origin>]
11
+
12
+ Copy the command from your falsepath console; the code is filled in and works once.
13
+ --pipeline ask nothing and print the result as JSON (for CI; uses CLOUDFLARE_API_TOKEN)
14
+ --allow-downgrade install a version older than the installed one
15
+ --accept-target-change install a version signed for another Worker, zone or routes than the installed one
16
+ --control <origin> the control plane's address, when the console's command names one`,Pt="falsepath: aborted",Nt={ok:!1,checks:[{name:"aborted",ok:!1}]},Lt="A".repeat(43),Ut="falsepath: this build carries no release key yet, so it cannot install anything";async function Xe(e,n){let{positionals:t,values:r}=Ot({args:e,allowPositionals:!0,options:{code:{type:"string"},pipeline:{type:"boolean"},"allow-downgrade":{type:"boolean"},"accept-target-change":{type:"boolean"},control:{type:"string"},help:{type:"boolean"}}}),o=t[0];if(r.help===!0||o!=="install"&&o!=="update"&&o!=="remove"||r.code===void 0)return n.log(It),r.help===!0?0:2;if(n.releaseKey===Lt)return n.error(Ut),1;let s=r.pipeline===!0,a=r.control??n.env.FALSEPATH_CONTROL??Se,c=n.control(a),l=!1;n.onBeforeExit(()=>{l||n.exit(1)});let g=new F,p=Ae(g,n.signals,n.exit,()=>{n.error(Pt),s&&n.log(JSON.stringify(Nt))});try{let f=await Je({action:o,code:r.code,pipeline:s,allowDowngrade:r["allow-downgrade"]===!0,acceptTargetChange:r["accept-target-change"]===!0,runner:n.runner(),control:c,appFetch:n.appFetch,releaseKey:n.releaseKey,now:n.now,sleep:n.sleep,print:n.log,warn:n.error,env:n.env,cleanup:g,...s||!n.stdinIsTTY?{}:{ask:n.ask},...n.nodeVersion!==void 0?{nodeVersion:n.nodeVersion}:{}});if(f.aborted!==void 0)return await g.exited,$[f.aborted];if(s)n.log(JSON.stringify(j(f.steps)));else for(let b of De(f.steps).slice(f.steps.length))n.log(b);return f.ok?0:1}finally{l=!0,p()}}var en="UTcFBumaqEHC2OWiAz2PD6pliJ1USBIopQ1qYB39Bgw";function Mt(e){return new Promise((n,t)=>{let r=Dt({input:process.stdin,output:process.stdout}),o=!1;r.once("SIGINT",()=>{o=!0,r.close(),process.emit("SIGINT","SIGINT"),t(new Error("falsepath: aborted"))}),r.once("close",()=>{o||t(new Error("falsepath: the terminal closed"))}),r.question(e,s=>{o=!0,r.close(),n(s)})})}Xe(process.argv.slice(2),{stdinIsTTY:process.stdin.isTTY===!0,env:process.env,log:e=>console.log(e),error:e=>console.error(e),ask:Mt,runner:$e,control:e=>le(e),appFetch:fetch,releaseKey:en,signals:process,exit:e=>process.exit(e),onBeforeExit:e=>{process.on("beforeExit",e)},now:Date.now,sleep:e=>new Promise(n=>setTimeout(n,e))}).then(e=>process.exit(e),e=>{console.error(e instanceof Error?e.message:"falsepath: failed"),process.exit(1)});