@stacksjs/desktop-build 0.75.717 → 0.75.719
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/webview-agent.js +1 -1
- package/package.json +10 -10
package/dist/webview-agent.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{timingSafeEqual}from"node:crypto";import{mkdirSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname,posix,win32}from"node:path";import process from"node:process";import{internalServerErrorBody}from"@stacksjs/router/error-body";import{isAgentHost,newAgentToken,rememberedPort,sessionCookie,staticContentType,staticFileResponse}from"./agent";export function validWebviewDatabaseFilename(filename){return typeof filename==="string"&&filename.length>0&&!/[<>:"/\\|?*]|[ .]$/.test(filename)&&!Array.from(filename).some((character)=>character.charCodeAt(0)<32)&&!/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(filename)}export const INSTANCE_PATH="/__desktop/instance";export const INSTANCE_HEADER="x-desktop-instance";const ASSET_PREFIXES=["/_stx/","/assets/"];function sameSecret(given,expected){if(!given)return false;const left=Buffer.from(given);const right=Buffer.from(expected);return left.length===right.length&&timingSafeEqual(left,right)}function matchesPath(pathname,patterns){return patterns.some((pattern)=>pattern.endsWith("/")?pathname.startsWith(pattern):pathname===pattern)}const LAUNCH_TOKEN_TTL_MS=60000;export function createWebviewGate(options){const cookieName=options.cookieName??"stacks_desktop";const session=newAgentToken();const pending=new Map;const refusal=`Open ${options.appName??"the app"} to use this.`;return{cookieName,mint(){const token=newAgentToken();pending.set(token,Date.now()+LAUNCH_TOKEN_TTL_MS);return token},check(request){const url=new URL(request.url);if(!isAgentHost(request.headers.get("host"),options.port()))return{response:new Response("Forbidden",{status:403})};if(url.pathname===INSTANCE_PATH){if(request.method!=="POST"||!options.instanceSecret||!sameSecret(request.headers.get(INSTANCE_HEADER),options.instanceSecret))return{response:new Response("Forbidden",{status:403})};return{allow:"instance"}}const offered=url.searchParams.get("session");if(offered!==null){const expires=pending.get(offered);pending.delete(offered);if(request.method!=="GET"||expires===undefined||expires<Date.now())return{response:new Response(refusal,{status:401})};url.searchParams.delete("session");return{response:new Response(null,{status:302,headers:{location:`${url.pathname}${url.search}`,"set-cookie":sessionCookie(cookieName,session),"cache-control":"no-store"}})}}const cookies=request.headers.get("cookie");if(cookies&&cookies.split(/;\s*/).includes(`${cookieName}=${session}`))return{allow:"window"};if(options.publicPaths?.length&&matchesPath(url.pathname,options.publicPaths))return{allow:"public"};if(request.method==="GET"&&matchesPath(url.pathname,ASSET_PREFIXES))return{allow:"asset"};return{response:new Response(refusal,{status:401})}}}}export function portIsFree(port){try{Bun.listen({hostname:"127.0.0.1",port,socket:{data(){}}}).stop(true);return true}catch{return false}}export function pickAgentPort(options={}){const wanted=options.port??rememberedPort(options.portFile);let port=wanted&&portIsFree(wanted)?wanted:0;if(!port){const probe=Bun.listen({hostname:"127.0.0.1",port:0,socket:{data(){}}});port=probe.port;probe.stop(true)}rememberPort(options.portFile,port);return port}function rememberPort(portFile,port){if(!portFile)return;try{mkdirSync(dirname(portFile),{recursive:true});writeFileSync(portFile,String(port))}catch{}}export function desktopAppPaths(appName,options={}){const platform=options.platform??process.platform;const home=options.home??homedir();const env=options.env??process.env;const slug=appName.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"app";let dataDir;let logFile;const path=platform==="win32"?win32:posix;if(platform==="darwin"){dataDir=path.join(home,"Library","Application Support",appName);logFile=path.join(home,"Library","Logs",`${appName}.log`)}else if(platform==="win32"){dataDir=path.join(env.APPDATA||path.join(home,"AppData","Roaming"),appName);logFile=path.join(dataDir,"logs",`${appName}.log`)}else{dataDir=path.join(env.XDG_DATA_HOME||path.join(home,".local","share"),slug);logFile=path.join(env.XDG_STATE_HOME||path.join(home,".local","state"),slug,`${slug}.log`)}return{dataDir,portFile:path.join(dataDir,"agent.port"),lockFile:path.join(dataDir,"agent.lock"),logFile,updatesDir:path.join(dataDir,"updates")}}export function widenedPath(options={}){const platform=options.platform??process.platform;const home=options.home??homedir();const env=options.env??process.env;const current=env.PATH??env.Path??"";const path=platform==="win32"?win32:posix;const delimiter=platform==="win32"?";":":";const added=platform==="win32"?[path.join(home,".bun","bin"),path.join(env.LOCALAPPDATA||path.join(home,"AppData","Local"),"Microsoft","WinGet","Links"),path.join(home,"scoop","shims"),path.join(env.ProgramFiles||"C:\\Program Files","Git","cmd")]:[path.join(home,".local","bin"),path.join(home,".bun","bin"),path.join(home,".npm-global","bin"),path.join(home,".cargo","bin"),...platform==="darwin"?["/opt/homebrew/bin"]:["/home/linuxbrew/.linuxbrew/bin","/snap/bin"],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"];const seen=new Set;return[...added,...current.split(delimiter)].filter((entry)=>{if(!entry||seen.has(entry))return false;seen.add(entry);return true}).join(delimiter)}export function applyWidenedPath(){const path=widenedPath();process.env.PATH=path;if(process.platform==="win32"&&process.env.Path!==undefined)process.env.Path=path}function embeddedFileResponse(files,pathname){let clean;try{clean=decodeURIComponent(pathname).replace(/\/+$/,"")||"/index"}catch{return null}for(const candidate of clean==="/index"?["/index.html"]:[`${clean}.html`,`${clean}/index.html`,clean]){const file=files[candidate];if(!file)continue;const ownType=staticContentType(file);const headers={"content-type":ownType==="application/octet-stream"?staticContentType(candidate):ownType};if(candidate.endsWith(".html"))headers["cache-control"]="no-store";return new Response(Bun.file(file),{headers})}return null}async function readSecondInstance(request){const body=await request.json().catch(()=>null);if(!body||!Array.isArray(body.args)||!body.args.every((arg)=>typeof arg==="string"))return null;return{args:body.args,cwd:typeof body.cwd==="string"?body.cwd:"",...typeof body.url==="string"?{url:body.url}:{}}}export async function startWebviewAgent(options){let port=0;let initialized=!options.initialize;const gate=createWebviewGate({port:()=>port,cookieName:options.cookieName,publicPaths:options.publicPaths,instanceSecret:options.instanceSecret,appName:options.appName});let markReady;const windowReady=new Promise((resolve)=>{markReady=resolve});const context=()=>({appName:options.appName,version:options.version??"0.0.0",origin:`http://127.0.0.1:${port}`,port,dataDir:options.dataDir??""});async function initialize(){await options.initialize?.(context());initialized=true}async function before(request){if(!initialized)return new Response("The desktop workspace is starting.",{status:503,headers:{"cache-control":"no-store"}});const decision=gate.check(request);if("response"in decision)return decision.response;if(decision.allow==="instance"){const launch=await readSecondInstance(request);if(!launch)return new Response("Bad request",{status:400});try{await options.onSecondInstance?.(launch)}catch(error){console.error(`[agent] second instance: ${error instanceof Error?error.message:String(error)}`)}return new Response(null,{status:204})}if(decision.allow==="asset")return;if(decision.allow==="window")markReady();if(!options.handler)return decision.allow==="public"?new Response("Not found",{status:404}):undefined;try{const answer=await options.handler(request,context());if(answer instanceof Response)return answer}catch(error){const message=error instanceof Error?error.message:String(error);console.error(`[agent] ${request.method} ${new URL(request.url).pathname}: ${message}`);return new Response(JSON.stringify(internalServerErrorBody()),{status:500,headers:{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}})}return decision.allow==="public"?new Response("Not found",{status:404}):undefined}const launchUrl=(path="/")=>{const url=new URL(path,`http://127.0.0.1:${port}`);url.searchParams.set("session",gate.mint());return url.toString()};const views=options.views;if(views.kind==="stx"){port=pickAgentPort({port:options.port,portFile:options.portFile});await initialize();const serve=views.serve??(await import(Bun.resolveSync("bun-plugin-stx/serve",views.root))).serve;let stxServer;const{componentsDir,additionalComponentsDirs=[]}=webviewComponentDirs(views.components);serve({patterns:[views.dir],port,quiet:true,...componentsDir?{componentsDir}:{},...additionalComponentsDirs.length?{additionalComponentsDirs}:{},onRequest:(request,server)=>{stxServer=server;return before(request)}});for(let attempt=0;attempt<200;attempt++){try{await fetch(`http://127.0.0.1:${port}/`,{redirect:"manual"});break}catch{await Bun.sleep(25)}}return{port,origin:`http://127.0.0.1:${port}`,launchUrl,windowReady,stop:()=>{stxServer?.stop(true)}}}const fetchHandler=async(request)=>{const answered=await before(request);if(answered)return answered;const pathname=new URL(request.url).pathname;const page=request.method!=="GET"&&request.method!=="HEAD"?null:views.kind==="static"?staticFileResponse(views.dir,pathname):views.kind==="embedded"?embeddedFileResponse(views.files,pathname):null;return page??new Response("Not found",{status:404})};const listen=(wanted)=>Bun.serve({hostname:"127.0.0.1",port:wanted,idleTimeout:0,fetch:fetchHandler});const wanted=options.port??rememberedPort(options.portFile);let server;try{server=listen(wanted)}catch(error){if(wanted===0)throw error;server=listen(0)}port=server.port??0;try{await initialize()}catch(error){server.stop(true);throw error}rememberPort(options.portFile,port);return{port,origin:`http://127.0.0.1:${port}`,launchUrl,windowReady,stop:()=>{server.stop(true)}}}export function webviewComponentDirs(components=[]){const[componentsDir,...additionalComponentsDirs]=components;return{...componentsDir?{componentsDir}:{},...additionalComponentsDirs.length?{additionalComponentsDirs}:{}}}
|
|
1
|
+
import{timingSafeEqual}from"node:crypto";import{mkdirSync,writeFileSync}from"node:fs";import{homedir}from"node:os";import{dirname,posix,win32}from"node:path";import process from"node:process";import{internalServerErrorBody}from"@stacksjs/router/error-body";import{isAgentHost,newAgentToken,rememberedPort,sessionCookie,staticContentType,staticFileResponse}from"./agent";export function validWebviewDatabaseFilename(filename){return typeof filename==="string"&&filename.length>0&&!/[<>:"/\\|?*]|[ .]$/.test(filename)&&!Array.from(filename).some((character)=>character.charCodeAt(0)<32)&&!/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(filename)}export const INSTANCE_PATH="/__desktop/instance";export const INSTANCE_HEADER="x-desktop-instance";const ASSET_PREFIXES=["/_stx/","/assets/"];function sameSecret(given,expected){if(!given)return false;const left=Buffer.from(given);const right=Buffer.from(expected);return left.length===right.length&&timingSafeEqual(left,right)}function matchesPath(pathname,patterns){return patterns.some((pattern)=>pattern.endsWith("/")?pathname.startsWith(pattern):pathname===pattern)}const LAUNCH_TOKEN_TTL_MS=60000;export function createWebviewGate(options){const cookieName=options.cookieName??"stacks_desktop";const session=newAgentToken();const pending=new Map;const refusal=`Open ${options.appName??"the app"} to use this.`;return{cookieName,mint(){const token=newAgentToken();pending.set(token,Date.now()+LAUNCH_TOKEN_TTL_MS);return token},check(request){const url=new URL(request.url);if(!isAgentHost(request.headers.get("host"),options.port()))return{response:new Response("Forbidden",{status:403})};if(url.pathname===INSTANCE_PATH){if(request.method!=="POST"||!options.instanceSecret||!sameSecret(request.headers.get(INSTANCE_HEADER),options.instanceSecret))return{response:new Response("Forbidden",{status:403})};return{allow:"instance"}}const offered=url.searchParams.get("session");if(offered!==null){const expires=pending.get(offered);pending.delete(offered);if(request.method!=="GET"||expires===undefined||expires<Date.now())return{response:new Response(refusal,{status:401})};url.searchParams.delete("session");return{response:new Response(null,{status:302,headers:{location:`${url.pathname}${url.search}`,"set-cookie":sessionCookie(cookieName,session),"cache-control":"no-store"}})}}const cookies=request.headers.get("cookie");if(cookies&&cookies.split(/;\s*/).includes(`${cookieName}=${session}`))return{allow:"window"};if(options.publicPaths?.length&&matchesPath(url.pathname,options.publicPaths))return{allow:"public"};if(request.method==="GET"&&matchesPath(url.pathname,ASSET_PREFIXES))return{allow:"asset"};return{response:new Response(refusal,{status:401})}}}}export function portIsFree(port){try{Bun.listen({hostname:"127.0.0.1",port,socket:{data(){}}}).stop(true);return true}catch{return false}}export function pickAgentPort(options={}){const wanted=options.port??rememberedPort(options.portFile);let port=wanted&&portIsFree(wanted)?wanted:0;if(!port){const probe=Bun.listen({hostname:"127.0.0.1",port:0,socket:{data(){}}});port=probe.port;probe.stop(true)}rememberPort(options.portFile,port);return port}function rememberPort(portFile,port){if(!portFile)return;try{mkdirSync(dirname(portFile),{recursive:true});writeFileSync(portFile,String(port))}catch{}}export function desktopAppPaths(appName,options={}){const platform=options.platform??process.platform;const home=options.home??homedir();const env=options.env??process.env;const slug=appName.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"app";let dataDir;let logFile;const path=platform==="win32"?win32:posix;if(platform==="darwin"){dataDir=path.join(home,"Library","Application Support",appName);logFile=path.join(home,"Library","Logs",`${appName}.log`)}else if(platform==="win32"){dataDir=path.join(env.APPDATA||path.join(home,"AppData","Roaming"),appName);logFile=path.join(dataDir,"logs",`${appName}.log`)}else{dataDir=path.join(env.XDG_DATA_HOME||path.join(home,".local","share"),slug);logFile=path.join(env.XDG_STATE_HOME||path.join(home,".local","state"),slug,`${slug}.log`)}return{dataDir,portFile:path.join(dataDir,"agent.port"),lockFile:path.join(dataDir,"agent.lock"),logFile,updatesDir:path.join(dataDir,"updates")}}export function widenedPath(options={}){const platform=options.platform??process.platform;const home=options.home??homedir();const env=options.env??process.env;const current=env.PATH??env.Path??"";const path=platform==="win32"?win32:posix;const delimiter=platform==="win32"?";":":";const added=platform==="win32"?[path.join(home,".bun","bin"),path.join(env.LOCALAPPDATA||path.join(home,"AppData","Local"),"Microsoft","WinGet","Links"),path.join(home,"scoop","shims"),path.join(env.ProgramFiles||"C:\\Program Files","Git","cmd")]:[path.join(home,".local","bin"),path.join(home,".bun","bin"),path.join(home,".npm-global","bin"),path.join(home,".cargo","bin"),...platform==="darwin"?["/opt/homebrew/bin"]:["/home/linuxbrew/.linuxbrew/bin","/snap/bin"],"/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"];const seen=new Set;return[...added,...current.split(delimiter)].filter((entry)=>{if(!entry||seen.has(entry))return false;seen.add(entry);return true}).join(delimiter)}export function applyWidenedPath(){const path=widenedPath();process.env.PATH=path;if(process.platform==="win32"&&process.env.Path!==undefined)process.env.Path=path}function embeddedFileResponse(files,pathname){let clean;try{clean=decodeURIComponent(pathname).replace(/\/+$/,"")||"/index"}catch{return null}for(const candidate of clean==="/index"?["/index.html"]:[`${clean}.html`,`${clean}/index.html`,clean]){const file=files[candidate];if(!file)continue;const ownType=staticContentType(file);const headers={"content-type":ownType==="application/octet-stream"?staticContentType(candidate):ownType};if(candidate.endsWith(".html"))headers["cache-control"]="no-store";return new Response(Bun.file(file),{headers})}return null}function acceptsGzip(header){let gzip;let wildcard=0;for(const offer of header?.split(",")??[]){const[coding,weight]=offer.trim().toLowerCase().split(/\s*;\s*/,2);if(coding!=="gzip"&&coding!=="*")continue;const quality=weight===undefined?1:Number(weight.match(/^q\s*=\s*([01](?:\.\d{0,3})?)$/)?.[1]);if(quality<0||quality>1||Number.isNaN(quality))continue;if(coding==="gzip")gzip=quality;else wildcard=quality}return(gzip??wildcard)>0}async function staticViewResponse(request,pathname,page){if(!/^\/_stx\/style\.[a-f0-9]{16}\.css$/.test(pathname)||page.headers.get("content-type")!==staticContentType(pathname))return page;page.headers.set("cache-control","public, max-age=31536000, immutable");page.headers.set("vary","Accept-Encoding");if(!acceptsGzip(request.headers.get("accept-encoding")))return page;page.headers.set("content-encoding","gzip");const body=request.method==="HEAD"?null:Bun.gzipSync(await page.arrayBuffer());return new Response(body,{headers:page.headers})}async function readSecondInstance(request){const body=await request.json().catch(()=>null);if(!body||!Array.isArray(body.args)||!body.args.every((arg)=>typeof arg==="string"))return null;return{args:body.args,cwd:typeof body.cwd==="string"?body.cwd:"",...typeof body.url==="string"?{url:body.url}:{}}}export async function startWebviewAgent(options){let port=0;let initialized=!options.initialize;const gate=createWebviewGate({port:()=>port,cookieName:options.cookieName,publicPaths:options.publicPaths,instanceSecret:options.instanceSecret,appName:options.appName});let markReady;const windowReady=new Promise((resolve)=>{markReady=resolve});const context=()=>({appName:options.appName,version:options.version??"0.0.0",origin:`http://127.0.0.1:${port}`,port,dataDir:options.dataDir??""});async function initialize(){await options.initialize?.(context());initialized=true}async function before(request){if(!initialized)return new Response("The desktop workspace is starting.",{status:503,headers:{"cache-control":"no-store"}});const decision=gate.check(request);if("response"in decision)return decision.response;if(decision.allow==="instance"){const launch=await readSecondInstance(request);if(!launch)return new Response("Bad request",{status:400});try{await options.onSecondInstance?.(launch)}catch(error){console.error(`[agent] second instance: ${error instanceof Error?error.message:String(error)}`)}return new Response(null,{status:204})}if(decision.allow==="asset")return;if(decision.allow==="window")markReady();if(!options.handler)return decision.allow==="public"?new Response("Not found",{status:404}):undefined;try{const answer=await options.handler(request,context());if(answer instanceof Response)return answer}catch(error){const message=error instanceof Error?error.message:String(error);console.error(`[agent] ${request.method} ${new URL(request.url).pathname}: ${message}`);return new Response(JSON.stringify(internalServerErrorBody()),{status:500,headers:{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}})}return decision.allow==="public"?new Response("Not found",{status:404}):undefined}const launchUrl=(path="/")=>{const url=new URL(path,`http://127.0.0.1:${port}`);url.searchParams.set("session",gate.mint());return url.toString()};const views=options.views;if(views.kind==="stx"){port=pickAgentPort({port:options.port,portFile:options.portFile});await initialize();const serve=views.serve??(await import(Bun.resolveSync("bun-plugin-stx/serve",views.root))).serve;let stxServer;const{componentsDir,additionalComponentsDirs=[]}=webviewComponentDirs(views.components);serve({patterns:[views.dir],port,quiet:true,...componentsDir?{componentsDir}:{},...additionalComponentsDirs.length?{additionalComponentsDirs}:{},onRequest:(request,server)=>{stxServer=server;return before(request)}});for(let attempt=0;attempt<200;attempt++){try{await fetch(`http://127.0.0.1:${port}/`,{redirect:"manual"});break}catch{await Bun.sleep(25)}}return{port,origin:`http://127.0.0.1:${port}`,launchUrl,windowReady,stop:()=>{stxServer?.stop(true)}}}const fetchHandler=async(request)=>{const answered=await before(request);if(answered)return answered;const pathname=new URL(request.url).pathname;const page=request.method!=="GET"&&request.method!=="HEAD"?null:views.kind==="static"?staticFileResponse(views.dir,pathname):views.kind==="embedded"?embeddedFileResponse(views.files,pathname):null;return page?staticViewResponse(request,pathname,page):new Response("Not found",{status:404})};const listen=(wanted)=>Bun.serve({hostname:"127.0.0.1",port:wanted,idleTimeout:0,fetch:fetchHandler});const wanted=options.port??rememberedPort(options.portFile);let server;try{server=listen(wanted)}catch(error){if(wanted===0)throw error;server=listen(0)}port=server.port??0;try{await initialize()}catch(error){server.stop(true);throw error}rememberPort(options.portFile,port);return{port,origin:`http://127.0.0.1:${port}`,launchUrl,windowReady,stop:()=>{server.stop(true)}}}export function webviewComponentDirs(components=[]){const[componentsDir,...additionalComponentsDirs]=components;return{...componentsDir?{componentsDir}:{},...additionalComponentsDirs.length?{additionalComponentsDirs}:{}}}
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/desktop-build",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.719",
|
|
6
6
|
"description": "Build and launch Craft desktop applications for Stacks",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -73,17 +73,17 @@
|
|
|
73
73
|
"prepublishOnly": "bun run build"
|
|
74
74
|
},
|
|
75
75
|
"dependencies": {
|
|
76
|
-
"@stacksjs/config": "0.75.
|
|
77
|
-
"@stacksjs/router": "0.75.
|
|
78
|
-
"@stacksjs/server": "0.75.
|
|
79
|
-
"@stacksjs/storage": "0.75.
|
|
76
|
+
"@stacksjs/config": "0.75.719",
|
|
77
|
+
"@stacksjs/router": "0.75.719",
|
|
78
|
+
"@stacksjs/server": "0.75.719",
|
|
79
|
+
"@stacksjs/storage": "0.75.719",
|
|
80
80
|
"craft-native": ">=0.0.505"
|
|
81
81
|
},
|
|
82
82
|
"peerDependencies": {
|
|
83
|
-
"@stacksjs/config": "0.75.
|
|
84
|
-
"@stacksjs/router": "0.75.
|
|
85
|
-
"@stacksjs/server": "0.75.
|
|
86
|
-
"@stacksjs/storage": "0.75.
|
|
83
|
+
"@stacksjs/config": "0.75.719",
|
|
84
|
+
"@stacksjs/router": "0.75.719",
|
|
85
|
+
"@stacksjs/server": "0.75.719",
|
|
86
|
+
"@stacksjs/storage": "0.75.719"
|
|
87
87
|
},
|
|
88
88
|
"peerDependenciesMeta": {
|
|
89
89
|
"@stacksjs/config": {
|
|
@@ -100,7 +100,7 @@
|
|
|
100
100
|
}
|
|
101
101
|
},
|
|
102
102
|
"devDependencies": {
|
|
103
|
-
"@stacksjs/build": "0.75.
|
|
103
|
+
"@stacksjs/build": "0.75.719",
|
|
104
104
|
"better-dx": "^0.2.39"
|
|
105
105
|
}
|
|
106
106
|
}
|