@stacksjs/desktop-build 0.75.544 → 0.75.548

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/agent.d.ts CHANGED
@@ -8,6 +8,14 @@ export declare function sessionCookie(name: string, token: string): string;
8
8
  export declare function hasSessionCookie(request: Request, name: string, token: string): boolean;
9
9
  /** The port remembered from the last launch, or 0 (any free port) when there is none worth trying. */
10
10
  export declare function rememberedPort(portFile: string | undefined): number;
11
+ /**
12
+ * A file under `root` for a request path, or null: `/about` is `about.html`,
13
+ * then `about/index.html`, then the file itself. Never outside `root`. HTML is
14
+ * not cached, so a rebuilt page is the one the next launch shows.
15
+ */
16
+ export declare function staticFileResponse(root: string, pathname: string): Response | null;
17
+ /** The content type for a file name, by extension. */
18
+ export declare function staticContentType(file: string): string;
11
19
  export declare function startDesktopAgent(options: DesktopAgentOptions): Promise<DesktopAgent>;
12
20
  export declare interface DesktopAgentOptions {
13
21
  handler: AgentHandler
package/dist/agent.js CHANGED
@@ -1 +1 @@
1
- import{randomBytes}from"node:crypto";import{existsSync,mkdirSync,readFileSync,statSync,writeFileSync}from"node:fs";import{dirname,extname,join,normalize,sep}from"node:path";const MIME={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".woff2":"font/woff2",".woff":"font/woff",".txt":"text/plain; charset=utf-8"};export function newAgentToken(){return randomBytes(24).toString("hex")}export function isAgentHost(host,port){return host===`127.0.0.1:${port}`||host===`localhost:${port}`}export function sessionCookie(name,token){return`${name}=${token}; Path=/; HttpOnly; SameSite=Strict`}export function hasSessionCookie(request,name,token){const cookies=request.headers.get("cookie");if(!cookies)return false;return cookies.split(/;\s*/).includes(`${name}=${token}`)}export function rememberedPort(portFile){if(!portFile)return 0;try{const port=Number(readFileSync(portFile,"utf8").trim());return Number.isInteger(port)&&port>1024&&port<65536?port:0}catch{return 0}}function json(data,status=200){return new Response(JSON.stringify(data),{status,headers:{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}})}export async function startDesktopAgent(options){const cookieName=options.cookieName??"stacks_desktop";let token=newAgentToken();let port=0;function serveStatic(pathname){if(!options.staticDir)return null;const root=normalize(options.staticDir);let clean;try{clean=decodeURIComponent(pathname).replace(/\/+$/,"")||"/index"}catch{return null}const candidates=clean==="/index"?["index.html"]:[`${clean}.html`,`${clean}/index.html`,clean];for(const candidate of candidates){const file=normalize(join(root,candidate));if(file!==root&&!file.startsWith(`${root}${sep}`))continue;if(!existsSync(file)||!statSync(file).isFile())continue;const headers={"content-type":MIME[extname(file)]??"application/octet-stream"};if(extname(file)===".html"){headers["cache-control"]="no-store";headers["set-cookie"]=sessionCookie(cookieName,token)}return new Response(Bun.file(file),{headers})}return null}async function fetch(request){const url=new URL(request.url);const host=request.headers.get("host");if(url.pathname==="/native/session"){if(request.method!=="GET")return json({error:"Method not allowed"},405);if(!isAgentHost(host,port))return json({error:"Forbidden"},403);const response=json({name:options.name??null,version:options.version??null,renderer:"appkit"});response.headers.set("set-cookie",sessionCookie(cookieName,token));return response}if(!isAgentHost(host,port))return json({error:"Forbidden"},403);if(request.method==="GET"&&!url.pathname.startsWith("/api/")){const file=serveStatic(url.pathname);if(file)return file}if(!hasSessionCookie(request,cookieName,token))return json({error:"Forbidden"},403);try{return await options.handler(request)}catch(error){const message=error instanceof Error?error.message:String(error);console.error(`[agent] ${request.method} ${url.pathname}: ${message}`);return json({error:message},500)}}const serve=(wanted)=>Bun.serve({hostname:"127.0.0.1",port:wanted,idleTimeout:0,fetch});const wanted=options.port??rememberedPort(options.portFile);let server;try{server=serve(wanted)}catch(error){if(wanted===0)throw error;server=serve(0)}port=server.port??0;if(options.portFile){try{mkdirSync(dirname(options.portFile),{recursive:true});writeFileSync(options.portFile,String(port))}catch{}}return{port,url:`http://127.0.0.1:${port}`,server,get token(){return token},rotateToken(){token=newAgentToken();return token},stop(){server.stop(true)}}}
1
+ import{randomBytes}from"node:crypto";import{existsSync,mkdirSync,readFileSync,statSync,writeFileSync}from"node:fs";import{dirname,extname,join,normalize,sep}from"node:path";const MIME={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".ico":"image/x-icon",".woff2":"font/woff2",".woff":"font/woff",".txt":"text/plain; charset=utf-8"};export function newAgentToken(){return randomBytes(24).toString("hex")}export function isAgentHost(host,port){return host===`127.0.0.1:${port}`||host===`localhost:${port}`}export function sessionCookie(name,token){return`${name}=${token}; Path=/; HttpOnly; SameSite=Strict`}export function hasSessionCookie(request,name,token){const cookies=request.headers.get("cookie");if(!cookies)return false;return cookies.split(/;\s*/).includes(`${name}=${token}`)}export function rememberedPort(portFile){if(!portFile)return 0;try{const port=Number(readFileSync(portFile,"utf8").trim());return Number.isInteger(port)&&port>1024&&port<65536?port:0}catch{return 0}}export function staticFileResponse(root,pathname){const base=normalize(root);let clean;try{clean=decodeURIComponent(pathname).replace(/\/+$/,"")||"/index"}catch{return null}const candidates=clean==="/index"?["index.html"]:[`${clean}.html`,`${clean}/index.html`,clean];for(const candidate of candidates){const file=normalize(join(base,candidate));if(file!==base&&!file.startsWith(`${base}${sep}`))continue;if(!existsSync(file)||!statSync(file).isFile())continue;const headers={"content-type":MIME[extname(file)]??"application/octet-stream"};if(extname(file)===".html")headers["cache-control"]="no-store";return new Response(Bun.file(file),{headers})}return null}export function staticContentType(file){return MIME[extname(file)]??"application/octet-stream"}function json(data,status=200){return new Response(JSON.stringify(data),{status,headers:{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}})}export async function startDesktopAgent(options){const cookieName=options.cookieName??"stacks_desktop";let token=newAgentToken();let port=0;function serveStatic(pathname){if(!options.staticDir)return null;const response=staticFileResponse(options.staticDir,pathname);if(response?.headers.get("content-type")?.startsWith("text/html"))response.headers.set("set-cookie",sessionCookie(cookieName,token));return response}async function fetch(request){const url=new URL(request.url);const host=request.headers.get("host");if(url.pathname==="/native/session"){if(request.method!=="GET")return json({error:"Method not allowed"},405);if(!isAgentHost(host,port))return json({error:"Forbidden"},403);const response=json({name:options.name??null,version:options.version??null,renderer:"appkit"});response.headers.set("set-cookie",sessionCookie(cookieName,token));return response}if(!isAgentHost(host,port))return json({error:"Forbidden"},403);if(request.method==="GET"&&!url.pathname.startsWith("/api/")){const file=serveStatic(url.pathname);if(file)return file}if(!hasSessionCookie(request,cookieName,token))return json({error:"Forbidden"},403);try{return await options.handler(request)}catch(error){const message=error instanceof Error?error.message:String(error);console.error(`[agent] ${request.method} ${url.pathname}: ${message}`);return json({error:message},500)}}const serve=(wanted)=>Bun.serve({hostname:"127.0.0.1",port:wanted,idleTimeout:0,fetch});const wanted=options.port??rememberedPort(options.portFile);let server;try{server=serve(wanted)}catch(error){if(wanted===0)throw error;server=serve(0)}port=server.port??0;if(options.portFile){try{mkdirSync(dirname(options.portFile),{recursive:true});writeFileSync(options.portFile,String(port))}catch{}}return{port,url:`http://127.0.0.1:${port}`,server,get token(){return token},rotateToken(){token=newAgentToken();return token},stop(){server.stop(true)}}}
package/dist/index.d.ts CHANGED
@@ -359,6 +359,12 @@ export * from './agent';
359
359
  export * from './agent-launcher';
360
360
  export * from './invites';
361
361
  export * from './updater';
362
+ export * from './update-signing';
363
+ export * from './update-feed';
364
+ export * from './update-install';
365
+ export * from './webview-agent';
366
+ export * from './webview-launcher';
367
+ export * from './webview-app';
362
368
  export * from './support';
363
369
  export * from './macos-app';
364
370
  export * from './macos-bundle';
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{closeSync,existsSync,openSync,readSync,statSync}from"node:fs";import{dirname,join}from"node:path";import process from"node:process";import{fileURLToPath}from"node:url";import{craftBinaryNotFoundMessage,resolveCraftBinary as resolveCraftNativeBinary}from"craft-native";export*from"./agent";export*from"./agent-launcher";export*from"./invites";export*from"./updater";export*from"./support";export*from"./macos-app";export*from"./macos-bundle";export function resolveCraftBinary(explicit=process.env.CRAFT_BIN){return resolveCraftNativeBinary(explicit)}export function resolveCraftExecutable(explicit=process.env.CRAFT_BIN,findOnPath=(binary)=>Bun.which(binary)){const resolved=resolveCraftBinary(explicit);if(resolved!=="craft")return resolved;const executable=findOnPath(resolved);if(!executable)throw new Error(craftBinaryNotFoundMessage(resolved));return executable}export const USERLAND_LAUNCHER="app/Desktop/launcher.ts";export function hasUserlandDesktopLauncher(projectRoot=process.cwd()){return existsSync(join(projectRoot,USERLAND_LAUNCHER))}export function desktopLauncherCompileArgs(options){return["build","--compile",...options.minify===false?[]:["--minify"],...options.bytecode===false?[]:["--bytecode","--format=esm"],"--no-compile-autoload-bunfig","--no-compile-autoload-dotenv",options.entry,"--outfile",options.outfile]}export function resolveDesktopLauncher(projectRoot=process.cwd()){const userland=join(projectRoot,USERLAND_LAUNCHER);if(existsSync(userland))return userland;const here=dirname(fileURLToPath(import.meta.url));const candidates=[join(here,"launcher.ts"),join(here,"launcher.js")];const launcher=candidates.find((candidate)=>existsSync(candidate));if(!launcher){throw new Error("Desktop launcher entrypoint not found. Reinstall @stacksjs/desktop - the package must ship dist/launcher.js.")}return launcher}export const RESERVED_PLIST_KEYS=new Set(["CFBundleName","CFBundleDisplayName","CFBundleIdentifier","CFBundleVersion","CFBundleShortVersionString","CFBundleExecutable","CFBundlePackageType","CFBundleInfoDictionaryVersion","CFBundleIconFile"]);export function xmlEscape(value){return value.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}export function plistValue(value,indent=""){if(typeof value==="string")return`<string>${xmlEscape(value)}</string>`;if(typeof value==="boolean")return value?"<true/>":"<false/>";if(typeof value==="number"){if(!Number.isFinite(value))throw new Error(`Unsupported Info.plist number: ${value}`);return Number.isInteger(value)?`<integer>${value}</integer>`:`<real>${value}</real>`}if(Array.isArray(value)){if(value.length===0)return"<array/>";const items=value.map((item)=>`${indent} ${plistValue(item,`${indent} `)}`).join(`
1
+ import{closeSync,existsSync,openSync,readSync,statSync}from"node:fs";import{dirname,join}from"node:path";import process from"node:process";import{fileURLToPath}from"node:url";import{craftBinaryNotFoundMessage,resolveCraftBinary as resolveCraftNativeBinary}from"craft-native";export*from"./agent";export*from"./agent-launcher";export*from"./invites";export*from"./updater";export*from"./update-signing";export*from"./update-feed";export*from"./update-install";export*from"./webview-agent";export*from"./webview-launcher";export*from"./webview-app";export*from"./support";export*from"./macos-app";export*from"./macos-bundle";export function resolveCraftBinary(explicit=process.env.CRAFT_BIN){return resolveCraftNativeBinary(explicit)}export function resolveCraftExecutable(explicit=process.env.CRAFT_BIN,findOnPath=(binary)=>Bun.which(binary)){const resolved=resolveCraftBinary(explicit);if(resolved!=="craft")return resolved;const executable=findOnPath(resolved);if(!executable)throw new Error(craftBinaryNotFoundMessage(resolved));return executable}export const USERLAND_LAUNCHER="app/Desktop/launcher.ts";export function hasUserlandDesktopLauncher(projectRoot=process.cwd()){return existsSync(join(projectRoot,USERLAND_LAUNCHER))}export function desktopLauncherCompileArgs(options){return["build","--compile",...options.minify===false?[]:["--minify"],...options.bytecode===false?[]:["--bytecode","--format=esm"],"--no-compile-autoload-bunfig","--no-compile-autoload-dotenv",options.entry,"--outfile",options.outfile]}export function resolveDesktopLauncher(projectRoot=process.cwd()){const userland=join(projectRoot,USERLAND_LAUNCHER);if(existsSync(userland))return userland;const here=dirname(fileURLToPath(import.meta.url));const candidates=[join(here,"launcher.ts"),join(here,"launcher.js")];const launcher=candidates.find((candidate)=>existsSync(candidate));if(!launcher){throw new Error("Desktop launcher entrypoint not found. Reinstall @stacksjs/desktop - the package must ship dist/launcher.js.")}return launcher}export const RESERVED_PLIST_KEYS=new Set(["CFBundleName","CFBundleDisplayName","CFBundleIdentifier","CFBundleVersion","CFBundleShortVersionString","CFBundleExecutable","CFBundlePackageType","CFBundleInfoDictionaryVersion","CFBundleIconFile"]);export function xmlEscape(value){return value.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}export function plistValue(value,indent=""){if(typeof value==="string")return`<string>${xmlEscape(value)}</string>`;if(typeof value==="boolean")return value?"<true/>":"<false/>";if(typeof value==="number"){if(!Number.isFinite(value))throw new Error(`Unsupported Info.plist number: ${value}`);return Number.isInteger(value)?`<integer>${value}</integer>`:`<real>${value}</real>`}if(Array.isArray(value)){if(value.length===0)return"<array/>";const items=value.map((item)=>`${indent} ${plistValue(item,`${indent} `)}`).join(`
2
2
  `);return`<array>
3
3
  ${items}
4
4
  ${indent}</array>`}if(value&&typeof value==="object"){const entries=Object.entries(value);if(entries.length===0)return"<dict/>";const body=entries.map(([key,val])=>`${indent} <key>${xmlEscape(key)}</key>${plistValue(val,`${indent} `)}`).join(`
@@ -0,0 +1,70 @@
1
+ import type { DesktopUpdateManifest } from './updater';
2
+ /** The storage key of the manifest an app on this channel, platform and architecture is served. */
3
+ export declare function updateManifestKey(location: UpdateLocation): string;
4
+ /** The storage key of one version's artifact. Versioned, so a published file is never overwritten by the next release. */
5
+ export declare function updateArtifactKey(location: UpdateLocation, version: string, fileName: string): string;
6
+ /** The URL an app asks: `<feedUrl>/<platform>/<arch>`, with its channel and version so the feed can answer "nothing new". */
7
+ export declare function updateFeedUrl(feedUrl: string, target: { platform: string, architecture: string }, query?: { channel?: string, currentVersion?: string }): string;
8
+ /** A disk from `@stacksjs/storage` (`config/filesystems.ts`), as an `UpdateStore`. Default: the default disk. */
9
+ export declare function storageUpdateStore(disk?: string): Promise<UpdateStore>;
10
+ /**
11
+ * Publish one platform's update: the artifact first, then the signed manifest
12
+ * that points at it. In that order, so the feed never names a file that is
13
+ * not there yet.
14
+ */
15
+ export declare function publishDesktopUpdate(options: PublishDesktopUpdateOptions): Promise<DesktopUpdateManifest>;
16
+ /**
17
+ * Answer an app asking for its update: the stored manifest, 204 when the app
18
+ * says it already runs that version or newer, 404 when nothing was published
19
+ * for its platform. The manifest is served as stored: its signature covers it,
20
+ * so the server holds no key and cannot alter what an app will accept.
21
+ */
22
+ export declare function serveUpdateFeed(options: UpdateLocation & { store: UpdateStore, currentVersion?: string | null }): Promise<Response>;
23
+ /**
24
+ * The update feed for the app this project builds, as a route handler's
25
+ * answer: `GET /api/updates/{platform}/{arch}`. Reads the manifest
26
+ * `buddy release:desktop` published, from the disk and folder
27
+ * `webview.updates` names. A project that publishes no desktop updates
28
+ * answers 404.
29
+ */
30
+ export declare function answerUpdateFeed(options: AnswerUpdateFeedOptions): Promise<Response>;
31
+ /**
32
+ * Where a release's artifacts and manifests live, and the feed an app reads
33
+ * them through. One manifest per channel, platform and architecture, at a
34
+ * fixed key, so publishing a release is writing the artifact and then that one
35
+ * file, and serving the feed is reading it back.
36
+ */
37
+ export declare const UPDATE_PLATFORMS: readonly ['darwin', 'linux', 'win32'];
38
+ export declare const DEFAULT_UPDATE_PREFIX: 'desktop-updates';
39
+ export declare interface UpdateLocation {
40
+ platform: string
41
+ architecture: string
42
+ channel?: string
43
+ prefix?: string
44
+ }
45
+ /** As much of a storage disk as updates use. `storageUpdateStore()` adapts `@stacksjs/storage`. */
46
+ export declare interface UpdateStore {
47
+ read: (key: string) => Promise<string | null>
48
+ write: (key: string, contents: string | Uint8Array) => Promise<void>
49
+ publicUrl: (key: string) => Promise<string>
50
+ }
51
+ export declare interface PublishDesktopUpdateOptions extends UpdateLocation {
52
+ store: UpdateStore
53
+ artifact: string
54
+ version: string
55
+ sourceRevision: string
56
+ privateKey: string
57
+ keyId?: string
58
+ notes?: string
59
+ artifactBaseUrl?: string
60
+ publishedAt?: string
61
+ }
62
+ export declare interface AnswerUpdateFeedOptions {
63
+ platform: string
64
+ architecture: string
65
+ channel?: string | null
66
+ currentVersion?: string | null
67
+ root?: string
68
+ updates?: { disk?: string, prefix?: string, channel?: string }
69
+ store?: UpdateStore
70
+ }
@@ -0,0 +1,2 @@
1
+ import{existsSync,readFileSync}from"node:fs";import{basename,join}from"node:path";import process from"node:process";import{pathToFileURL}from"node:url";import{describeArtifact,signUpdateManifest}from"./update-signing";import{compareVersions,validateUpdateManifest}from"./updater";export const UPDATE_PLATFORMS=["darwin","linux","win32"];export const DEFAULT_UPDATE_PREFIX="desktop-updates";function checkedLocation(location){const channel=location.channel||"stable";const prefix=(location.prefix??DEFAULT_UPDATE_PREFIX).replace(/^\/+|\/+$/g,"");if(!UPDATE_PLATFORMS.includes(location.platform))throw new Error(`Unknown desktop platform: ${location.platform}`);if(!/^[a-z0-9_]+$/.test(location.architecture))throw new Error(`Unknown desktop architecture: ${location.architecture}`);if(!/^[a-z0-9][a-z0-9._-]*$/i.test(channel))throw new Error(`Invalid release channel: ${channel}`);return{platform:location.platform,architecture:location.architecture,channel,prefix}}export function updateManifestKey(location){const at=checkedLocation(location);return`${at.prefix}/${at.channel}/${at.platform}-${at.architecture}/latest.json`}export function updateArtifactKey(location,version,fileName){const at=checkedLocation(location);if(!/^[\w.+-]+$/.test(version)||!/^[\w.+ -]+$/.test(fileName))throw new Error(`Invalid artifact name: ${version}/${fileName}`);return`${at.prefix}/${at.channel}/${at.platform}-${at.architecture}/${version}/${fileName}`}export function updateFeedUrl(feedUrl,target,query={}){const url=new URL(`${feedUrl.replace(/\/+$/,"")}/${target.platform}/${target.architecture}`);if(query.channel&&query.channel!=="stable")url.searchParams.set("channel",query.channel);if(query.currentVersion)url.searchParams.set("current",query.currentVersion);return url.toString()}export async function storageUpdateStore(disk){const{Storage}=await import("@stacksjs/storage");const adapter=Storage.disk(disk);return{read:async(key)=>await adapter.fileExists(key)?adapter.readToString(key):null,write:async(key,contents)=>{await adapter.write(key,typeof contents==="string"?contents:Buffer.from(contents))},publicUrl:(key)=>adapter.publicUrl(key)}}export async function publishDesktopUpdate(options){const{size,sha256}=await describeArtifact(options.artifact);const artifactKey=updateArtifactKey(options,options.version,basename(options.artifact));await options.store.write(artifactKey,readFileSync(options.artifact));const url=options.artifactBaseUrl?`${options.artifactBaseUrl.replace(/\/+$/,"")}/${artifactKey}`:await options.store.publicUrl(artifactKey);const unsigned={version:options.version,url,sha256,size,sourceRevision:options.sourceRevision,platform:options.platform,architecture:options.architecture,publishedAt:options.publishedAt??new Date().toISOString(),...options.notes?{notes:options.notes}:{}};const manifest=signUpdateManifest(unsigned,options.privateKey,options.keyId);await options.store.write(updateManifestKey(options),`${JSON.stringify(manifest,null,2)}
2
+ `);return manifest}const feedHeaders={"content-type":"application/json; charset=utf-8","cache-control":"no-store"};export async function serveUpdateFeed(options){let key;try{key=updateManifestKey(options)}catch(error){return new Response(JSON.stringify({error:error instanceof Error?error.message:String(error)}),{status:404,headers:feedHeaders})}const stored=await options.store.read(key);if(!stored)return new Response(JSON.stringify({error:"No update has been published for this platform."}),{status:404,headers:feedHeaders});let manifest;try{manifest=validateUpdateManifest(JSON.parse(stored))}catch{return new Response(JSON.stringify({error:"The published update manifest is not valid."}),{status:500,headers:feedHeaders})}if(options.currentVersion){try{if(compareVersions(manifest.version,options.currentVersion)<=0)return new Response(null,{status:204,headers:{"cache-control":"no-store"}})}catch{}}return new Response(stored,{headers:feedHeaders})}export async function answerUpdateFeed(options){let updates=options.updates;if(!updates&&!options.store){const file=join(options.root??process.cwd(),"config/desktop.ts");updates=existsSync(file)?(await import(pathToFileURL(file).href)).default?.webview?.updates:undefined;if(!updates)return new Response(JSON.stringify({error:"This app publishes no desktop updates."}),{status:404,headers:feedHeaders})}return serveUpdateFeed({store:options.store??await storageUpdateStore(updates?.disk),platform:options.platform,architecture:options.architecture,channel:options.channel||updates?.channel,prefix:updates?.prefix,currentVersion:options.currentVersion})}
@@ -0,0 +1,127 @@
1
+ import process from 'node:process';
2
+ import type { DesktopFetcher, DesktopUpdateManifest, DesktopUpdateTarget } from './updater';
3
+ /** How this copy of the app was installed, from where its executable is and what started it. */
4
+ export declare function detectInstallation(options?: { platform?: string, execPath?: string, env?: Record<string, string | undefined> }): DesktopInstallation;
5
+ /** Who signed a macOS bundle: its Developer ID team, or nothing for an ad hoc or unsigned one. */
6
+ export declare function macosSigner(bundle: string, run?: RunUpdateCommand): { teamId?: string, identifier?: string };
7
+ /**
8
+ * Whether a new bundle may replace the running one. Its signature has to be
9
+ * intact, and it has to come from the same Developer ID team and carry the
10
+ * same identifier as the app being replaced. An update manifest signed with a
11
+ * stolen key still cannot install someone else's app over this one.
12
+ *
13
+ * A running app with no team (an ad hoc development build) has no signer to
14
+ * compare with, so it is only replaced when `allowUnsigned` says so.
15
+ */
16
+ export declare function assertMacosBundleTrusted(current: string, next: string, options?: { run?: RunUpdateCommand, allowUnsigned?: boolean }): void;
17
+ /**
18
+ * Replace a macOS bundle with the one in a staged archive. The old bundle is
19
+ * moved aside first and put back if the new one cannot take its place, so a
20
+ * failure at any step leaves a working app where it was.
21
+ */
22
+ export declare function swapMacosBundle(options: { archive: string, bundle: string, extract?: ExtractBundle, run?: RunUpdateCommand, allowUnsigned?: boolean }): void;
23
+ /** Replace an AppImage with a staged one, by a rename beside it so no half-written image is ever at its path. */
24
+ export declare function replaceAppImage(staged: string, appImage: string): void;
25
+ /** Who signed a Windows file, by Authenticode: the signer's subject when the signature is valid. */
26
+ export declare function windowsSigner(file: string, run?: RunUpdateCommand): { valid: boolean, subject?: string };
27
+ /**
28
+ * Whether a staged MSI may be run: when the running executable is
29
+ * Authenticode-signed, the installer has to be validly signed by the same
30
+ * publisher. An unsigned app has no publisher to compare with and relies on
31
+ * the manifest's signature and checksum alone, unless `allowUnsigned` is false.
32
+ */
33
+ export declare function assertWindowsInstallerTrusted(executable: string, installer: string, options?: { run?: RunUpdateCommand, allowUnsigned?: boolean }): void;
34
+ /** Install a staged update for the way this copy of the app was installed. */
35
+ export declare function installDesktopUpdate(options: InstallDesktopUpdateOptions): InstallDesktopUpdateResult;
36
+ /** The update flow as one object an agent holds: check, the app's say, stage, install, relaunch. */
37
+ export declare function createDesktopUpdater(options: DesktopUpdaterOptions): DesktopUpdater;
38
+ /**
39
+ * The window's view of the updater, at `/__desktop/update`: `GET` is the
40
+ * status, `POST { action: 'check' }` asks the feed, and `POST { action:
41
+ * 'install', acknowledge? }` installs. Behind the session cookie like every
42
+ * other agent path, so only the app's own page can start an install.
43
+ */
44
+ export declare function updateRequestHandler(updater: DesktopUpdater): (request: Request) => Promise<Response | undefined>;
45
+ /** Whether a path exists and is a macOS bundle with an executable inside: what a fixture or a build check asks. */
46
+ export declare function isMacosBundle(path: string): boolean;
47
+ export declare const UPDATE_PATH: '/__desktop/update';
48
+ export declare interface DesktopInstallation {
49
+ kind: DesktopInstallKind
50
+ path?: string
51
+ executable: string
52
+ }
53
+ export declare interface UpdateCommandResult {
54
+ exitCode: number
55
+ stdout: string
56
+ stderr: string
57
+ }
58
+ export declare interface InstallDesktopUpdateOptions {
59
+ staged: string
60
+ manifest: Pick<DesktopUpdateManifest, 'version' | 'url'>
61
+ appName?: string
62
+ installation?: DesktopInstallation
63
+ allowUnsigned?: boolean
64
+ run?: RunUpdateCommand
65
+ extract?: ExtractBundle
66
+ spawn?: SpawnDetached
67
+ pid?: number
68
+ }
69
+ export declare interface DesktopUpdateStatus {
70
+ currentVersion: string
71
+ state: 'idle' | 'checking' | 'current' | 'available' | 'refused' | 'installed' | 'installing' | 'error'
72
+ installKind: DesktopInstallKind
73
+ selfUpdating: boolean
74
+ version?: string
75
+ notes?: string
76
+ publishedAt?: string
77
+ warning?: string
78
+ message?: string
79
+ error?: string
80
+ }
81
+ export declare interface DesktopUpdaterOptions {
82
+ currentVersion: string
83
+ feedUrl: string
84
+ trustedKeys: Record<string, string>
85
+ updatesDir: string
86
+ appName?: string
87
+ channel?: string
88
+ beforeUpdate?: BeforeDesktopUpdate
89
+ target?: DesktopUpdateTarget
90
+ fetcher?: DesktopFetcher
91
+ installation?: DesktopInstallation
92
+ install?: (options: InstallDesktopUpdateOptions) => InstallDesktopUpdateResult
93
+ allowUnsigned?: boolean
94
+ }
95
+ export declare interface DesktopUpdater {
96
+ status: () => DesktopUpdateStatus
97
+ check: () => Promise<DesktopUpdateStatus>
98
+ install: (options?: { acknowledge?: boolean }) => Promise<DesktopUpdateStatus>
99
+ relaunchIfInstalled: () => Promise<void>
100
+ }
101
+ /**
102
+ * The client half of desktop updates after the download: install what was
103
+ * staged and start the new version.
104
+ *
105
+ * How depends on how the app was installed. A macOS bundle is swapped for the
106
+ * new one after a signature check against the running app. A Windows install
107
+ * runs the new MSI. A Linux AppImage is replaced in place. A deb or rpm
108
+ * install is the package manager's to update, so the app only says a new
109
+ * version exists. A run from source has nothing to replace.
110
+ */
111
+ export type DesktopInstallKind = 'macos-bundle' | 'windows-msi' | 'linux-appimage' | 'linux-package' | 'unmanaged';
112
+ export type RunUpdateCommand = (command: string[]) => UpdateCommandResult;
113
+ export type SpawnDetached = (command: string[]) => void;
114
+ /** Unpack a zipped `.app`, keeping its signature, extended attributes and symlinks. */
115
+ export type ExtractBundle = (archive: string, into: string) => void;
116
+ export type InstallDesktopUpdateResult = | { status: 'installed', relaunch: () => void }
117
+ /** An installer was started and will replace the app once this process exits; it starts the new version itself. */
118
+ | { status: 'installing' }
119
+ /** Nothing was installed: the app says this instead. */
120
+ | { status: 'notice', message: string }
121
+ /**
122
+ * An app's say before an update is installed, called with the manifest that
123
+ * was verified. Return nothing to allow it; `{ refuse }` to stop it; `{ warn }`
124
+ * to make the person confirm first (a license whose updates ended before this
125
+ * version: it would run, but as the free tier).
126
+ */
127
+ export type BeforeDesktopUpdate = (manifest: DesktopUpdateManifest, current: { version: string }) => void | undefined | { refuse: string } | { warn: string } | Promise<void | undefined | { refuse: string } | { warn: string }>;
@@ -0,0 +1,2 @@
1
+ import{chmodSync,copyFileSync,existsSync,mkdirSync,mkdtempSync,readdirSync,renameSync,rmSync}from"node:fs";import{basename,dirname,join}from"node:path";import process from"node:process";import{updateFeedUrl}from"./update-feed";import{checkForDesktopUpdate,stageDesktopUpdate}from"./updater";export function detectInstallation(options={}){const platform=options.platform??process.platform;const execPath=options.execPath??process.execPath;const env=options.env??process.env;const name=basename(execPath).toLowerCase();if(name==="bun"||name==="bun.exe")return{kind:"unmanaged",executable:execPath};if(platform==="darwin"){const bundle=execPath.match(/^(.*\.app)\/Contents\/MacOS\/[^/]+$/);return bundle?{kind:"macos-bundle",path:bundle[1],executable:execPath}:{kind:"unmanaged",executable:execPath}}if(platform==="win32")return{kind:"windows-msi",executable:execPath};if(env.APPIMAGE)return{kind:"linux-appimage",path:env.APPIMAGE,executable:env.APPIMAGE};return execPath.startsWith("/usr/")||execPath.startsWith("/opt/")?{kind:"linux-package",executable:execPath}:{kind:"unmanaged",executable:execPath}}const runCommand=(command)=>{const result=Bun.spawnSync(command,{stdout:"pipe",stderr:"pipe"});return{exitCode:result.exitCode??1,stdout:result.stdout.toString(),stderr:result.stderr.toString()}};const spawnDetached=(command)=>{Bun.spawn(command,{stdio:["ignore","ignore","ignore"],detached:true}).unref()};export function macosSigner(bundle,run=runCommand){const described=run(["codesign","-dv","--verbose=4",bundle]);const text=`${described.stdout}
2
+ ${described.stderr}`;const teamId=text.match(/^TeamIdentifier=(.+)$/m)?.[1]?.trim();const identifier=text.match(/^Identifier=(.+)$/m)?.[1]?.trim();return{...teamId&&teamId!=="not set"?{teamId}:{},...identifier?{identifier}:{}}}export function assertMacosBundleTrusted(current,next,options={}){const run=options.run??runCommand;const verified=run(["codesign","--verify","--deep","--strict",next]);const running=macosSigner(current,run);const incoming=macosSigner(next,run);if(!running.teamId){if(!options.allowUnsigned)throw new Error("The running app is not signed with a Developer ID, so an update cannot be checked against it.");return}if(verified.exitCode!==0)throw new Error(`The update's signature is not valid: ${(verified.stderr||verified.stdout).trim()}`);if(incoming.teamId!==running.teamId)throw new Error(`The update is signed by ${incoming.teamId??"no one"}, not by this app's team ${running.teamId}.`);if(incoming.identifier!==running.identifier)throw new Error(`The update is a different app (${incoming.identifier??"unknown"}), not ${running.identifier}.`)}const dittoExtract=(archive,into)=>{const result=runCommand(["ditto","-x","-k",archive,into]);if(result.exitCode!==0)throw new Error(`Unpacking the update failed: ${result.stderr.trim()}`)};export function swapMacosBundle(options){const{bundle}=options;const scratch=mkdtempSync(join(dirname(bundle),".update-"));const aside=`${bundle}.previous-${process.pid}`;try{(options.extract??dittoExtract)(options.archive,scratch);const unpacked=readdirSync(scratch).filter((entry)=>entry.endsWith(".app"));if(unpacked.length!==1)throw new Error(`The update archive holds ${unpacked.length} apps; it has to hold exactly one.`);const next=join(scratch,unpacked[0]);assertMacosBundleTrusted(bundle,next,{run:options.run,allowUnsigned:options.allowUnsigned});renameSync(bundle,aside);try{renameSync(next,bundle)}catch(error){renameSync(aside,bundle);throw error}rmSync(aside,{recursive:true,force:true})}finally{rmSync(scratch,{recursive:true,force:true})}}export function replaceAppImage(staged,appImage){const incoming=`${appImage}.update-${process.pid}`;try{copyFileSync(staged,incoming);chmodSync(incoming,493);renameSync(incoming,appImage)}catch(error){rmSync(incoming,{force:true});throw error}}export function windowsSigner(file,run=runCommand){const script=`$s = Get-AuthenticodeSignature -LiteralPath '${file.replace(/'/g,"''")}'; Write-Output $s.Status; if ($s.SignerCertificate) { Write-Output $s.SignerCertificate.Subject }`;const result=run(["powershell.exe","-NoProfile","-NonInteractive","-Command",script]);const[status,subject]=result.stdout.split(/\r?\n/).map((line)=>line.trim()).filter(Boolean);return{valid:result.exitCode===0&&status==="Valid",...subject?{subject}:{}}}export function assertWindowsInstallerTrusted(executable,installer,options={}){const running=windowsSigner(executable,options.run);if(!running.valid){if(options.allowUnsigned===false)throw new Error("The running app is not Authenticode-signed, so an update cannot be checked against it.");return}const incoming=windowsSigner(installer,options.run);if(!incoming.valid)throw new Error("The update installer is not validly signed.");if(incoming.subject!==running.subject)throw new Error(`The update is signed by ${incoming.subject??"no one"}, not by this app's publisher ${running.subject}.`)}export function installDesktopUpdate(options){const installation=options.installation??detectInstallation();const spawn=options.spawn??spawnDetached;const pid=options.pid??process.pid;const name=options.appName??"The app";switch(installation.kind){case"macos-bundle":{swapMacosBundle({archive:options.staged,bundle:installation.path,extract:options.extract,run:options.run,allowUnsigned:options.allowUnsigned});return{status:"installed",relaunch:()=>spawn(["open","-n",installation.path,"--args",`--wait-pid=${pid}`])}}case"linux-appimage":{replaceAppImage(options.staged,installation.path);return{status:"installed",relaunch:()=>spawn([installation.path,`--wait-pid=${pid}`])}}case"windows-msi":{assertWindowsInstallerTrusted(installation.executable,options.staged,{run:options.run,allowUnsigned:options.allowUnsigned});spawn(["cmd.exe","/d","/s","/c",`msiexec /i "${options.staged}" /passive /norestart && start "" "${installation.executable}" --wait-pid=${pid}`]);return{status:"installing"}}case"linux-package":return{status:"notice",message:`${name} ${options.manifest.version} is available. This copy was installed as a system package: update it with your package manager, or download the new package from ${new URL(options.manifest.url).origin}.`};default:return{status:"notice",message:`${name} ${options.manifest.version} is available, but this copy was not installed in a way that can update itself.`}}}const ARTIFACT_NAMES={darwin:"update.zip",win32:"update.msi",linux:"update.AppImage"};export function createDesktopUpdater(options){const installation=options.installation??detectInstallation();const target=options.target??{platform:process.platform,architecture:process.arch};const selfUpdating=["macos-bundle","windows-msi","linux-appimage"].includes(installation.kind);let state="idle";let manifest=null;let warning;let message;let error;let relaunch;let busy;const status=()=>({currentVersion:options.currentVersion,state,installKind:installation.kind,selfUpdating,...manifest?{version:manifest.version,...manifest.notes?{notes:manifest.notes}:{},...manifest.publishedAt?{publishedAt:manifest.publishedAt}:{}}:{},...warning?{warning}:{},...message?{message}:{},...error?{error}:{}});const once=(work)=>{busy??=work().catch((failure)=>{state="error";error=failure instanceof Error?failure.message:String(failure)}).then(()=>{busy=undefined;return status()});return busy};return{status,check:()=>once(async()=>{if(state==="installed"||state==="installing")return;state="checking";error=warning=message=undefined;manifest=await checkForDesktopUpdate({currentVersion:options.currentVersion,manifestUrl:updateFeedUrl(options.feedUrl,target,{channel:options.channel,currentVersion:options.currentVersion}),trustedKeys:options.trustedKeys,fetcher:options.fetcher,target});if(!manifest){state="current";return}const verdict=await options.beforeUpdate?.(manifest,{version:options.currentVersion});if(verdict&&"refuse"in verdict){state="refused";message=verdict.refuse;return}if(verdict&&"warn"in verdict)warning=verdict.warn;state="available"}),install:(install={})=>once(async()=>{if(state!=="available"||!manifest)throw new Error("There is no update to install. Check first.");if(warning&&!install.acknowledge)throw new Error(warning);if(!selfUpdating){const outcome=(options.install??installDesktopUpdate)({staged:"",manifest,appName:options.appName,installation});message=outcome.status==="notice"?outcome.message:undefined;return}const directory=join(options.updatesDir,manifest.version);mkdirSync(directory,{recursive:true});const staged=await stageDesktopUpdate(manifest,join(directory,ARTIFACT_NAMES[target.platform]??"update.bin"),options.fetcher,options.trustedKeys,target);const outcome=(options.install??installDesktopUpdate)({staged:staged.path,manifest,appName:options.appName,installation,allowUnsigned:options.allowUnsigned});if(outcome.status==="notice"){message=outcome.message;return}state=outcome.status;if(outcome.status==="installed"){relaunch=outcome.relaunch;rmSync(directory,{recursive:true,force:true})}}),async relaunchIfInstalled(){relaunch?.();relaunch=undefined}}}export const UPDATE_PATH="/__desktop/update";export function updateRequestHandler(updater){const json=(body,status=200)=>new Response(JSON.stringify(body),{status,headers:{"content-type":"application/json; charset=utf-8","cache-control":"no-store"}});return async(request)=>{if(new URL(request.url).pathname!==UPDATE_PATH)return;if(request.method==="GET")return json(updater.status());if(request.method!=="POST")return json({error:"Method not allowed"},405);const body=await request.json().catch(()=>null);if(body?.action==="check")return json(await updater.check());if(body?.action==="install")return json(await updater.install({acknowledge:body.acknowledge===true}));return json({error:'Send { action: "check" } or { action: "install" }.'},400)}}export function isMacosBundle(path){return path.endsWith(".app")&&existsSync(join(path,"Contents","MacOS"))}
@@ -0,0 +1,22 @@
1
+ import type { DesktopUpdateManifest } from './updater';
2
+ export declare function generateUpdateKeypair(keyId?: string): UpdateKeypair;
3
+ /** The public key that verifies what a private key signs, in the encoding the app trusts. */
4
+ export declare function updatePublicKey(privateKey: string): string;
5
+ /** Sign a manifest. The result is verified against the key's own public half before it is returned. */
6
+ export declare function signUpdateManifest(unsigned: UnsignedUpdateManifest, privateKey: string, keyId?: string): DesktopUpdateManifest;
7
+ /** A file's size and SHA-256, read as a stream: an installer is too large to hold twice. */
8
+ export declare function describeArtifact(file: string): Promise<{ size: number, sha256: string }>;
9
+ /**
10
+ * The signing half of desktop updates. A release signs one manifest per
11
+ * platform and architecture with an Ed25519 private key that stays with the
12
+ * person releasing; the app carries the public key and refuses a manifest it
13
+ * does not verify (`updater.ts`).
14
+ */
15
+ export declare const UPDATE_PUBLIC_PREFIX: 'ed25519-public:';
16
+ export declare const UPDATE_PRIVATE_PREFIX: 'ed25519-private:';
17
+ export declare interface UpdateKeypair {
18
+ keyId: string
19
+ publicKey: string
20
+ privateKey: string
21
+ }
22
+ export type UnsignedUpdateManifest = Omit<DesktopUpdateManifest, 'signature' | 'signingKeyId'>;
@@ -0,0 +1 @@
1
+ import{createHash,createPrivateKey,createPublicKey,generateKeyPairSync,sign}from"node:crypto";import{createReadStream,statSync}from"node:fs";import{updateManifestPayload,validateUpdateManifest,verifyUpdateManifestSignature}from"./updater";export const UPDATE_PUBLIC_PREFIX="ed25519-public:";export const UPDATE_PRIVATE_PREFIX="ed25519-private:";export function generateUpdateKeypair(keyId="main"){if(!/^[\w.-]+$/.test(keyId))throw new Error(`A key id is letters, digits, dots, dashes and underscores: ${keyId}`);const{publicKey,privateKey}=generateKeyPairSync("ed25519");return{keyId,publicKey:`${UPDATE_PUBLIC_PREFIX}${publicKey.export({format:"der",type:"spki"}).toString("base64url")}`,privateKey:`${UPDATE_PRIVATE_PREFIX}${privateKey.export({format:"der",type:"pkcs8"}).toString("base64url")}`}}function privateKeyObject(encoded){if(!encoded.startsWith(UPDATE_PRIVATE_PREFIX))throw new Error(`A desktop update private key starts with ${UPDATE_PRIVATE_PREFIX}`);let key;try{key=createPrivateKey({key:Buffer.from(encoded.slice(UPDATE_PRIVATE_PREFIX.length),"base64url"),format:"der",type:"pkcs8"})}catch{throw new Error("The desktop update private key could not be read")}if(key.asymmetricKeyType!=="ed25519")throw new Error("The desktop update private key is not an Ed25519 key");return key}export function updatePublicKey(privateKey){return`${UPDATE_PUBLIC_PREFIX}${createPublicKey(privateKeyObject(privateKey)).export({format:"der",type:"spki"}).toString("base64url")}`}export function signUpdateManifest(unsigned,privateKey,keyId="main"){const key=privateKeyObject(privateKey);const manifest={...unsigned,sha256:unsigned.sha256.toLowerCase(),signingKeyId:keyId,signature:""};manifest.signature=sign(null,updateManifestPayload(manifest),key).toString("base64url");validateUpdateManifest(manifest);verifyUpdateManifestSignature(manifest,{[keyId]:updatePublicKey(privateKey)});return manifest}export async function describeArtifact(file){const hash=createHash("sha256");await new Promise((resolve,reject)=>{createReadStream(file).on("data",(chunk)=>hash.update(chunk)).on("end",resolve).on("error",reject)});return{size:statSync(file).size,sha256:hash.digest("hex")}}
package/dist/updater.js CHANGED
@@ -1 +1 @@
1
- import{createHash,createPublicKey,verify}from"node:crypto";import{mkdir,rename,rm,writeFile}from"node:fs/promises";import process from"node:process";import{dirname}from"node:path";export async function checkForDesktopUpdate(options){assertSecureUrl(options.manifestUrl);const response=await(options.fetcher||fetch)(options.manifestUrl,{headers:{Accept:"application/json"}});if(!response.ok)throw new Error(`Desktop update check failed with HTTP ${response.status}`);const manifest=validateUpdateManifest(await response.json());verifyUpdateManifestSignature(manifest,options.trustedKeys);assertUpdateTarget(manifest,options.target);return compareVersions(manifest.version,options.currentVersion)>0?manifest:null}export async function stageDesktopUpdate(manifest,destination,fetcher=fetch,trustedKeys,target){validateUpdateManifest(manifest);if(!trustedKeys)throw new Error("Desktop update staging requires trusted signing keys");verifyUpdateManifestSignature(manifest,trustedKeys);assertUpdateTarget(manifest,target);assertSecureUrl(manifest.url);const response=await fetcher(manifest.url);if(!response.ok)throw new Error(`Desktop update download failed with HTTP ${response.status}`);const bytes=new Uint8Array(await response.arrayBuffer());if(bytes.byteLength!==manifest.size)throw new Error(`Desktop update size mismatch: expected ${manifest.size}, received ${bytes.byteLength}`);const checksum=createHash("sha256").update(bytes).digest("hex");if(checksum!==manifest.sha256.toLowerCase())throw new Error("Desktop update checksum mismatch");await mkdir(dirname(destination),{recursive:true});const temporaryPath=`${destination}.download-${crypto.randomUUID()}`;try{await writeFile(temporaryPath,bytes,{mode:448});await rename(temporaryPath,destination)}catch(error){await rm(temporaryPath,{force:true});throw error}return{manifest,path:destination,bytes:bytes.byteLength}}export function compareVersions(left,right){const leftParts=parseVersion(left);const rightParts=parseVersion(right);for(let index=0;index<3;index++){const difference=leftParts[index]-rightParts[index];if(difference!==0)return Math.sign(difference)}return 0}export function validateUpdateManifest(input){if(!input||typeof input!=="object")throw new Error("Desktop update manifest must be an object");const manifest=input;parseVersion(manifest.version||"");if(typeof manifest.url!=="string")throw new Error("Desktop update manifest requires a URL");if(typeof manifest.sha256!=="string"||!/^[a-f0-9]{64}$/i.test(manifest.sha256))throw new Error("Desktop update manifest requires a SHA-256 checksum");if(!Number.isInteger(manifest.size)||manifest.size<0)throw new Error("Desktop update manifest requires a non-negative integer size");if(typeof manifest.sourceRevision!=="string"||!/^[0-9a-f]{40}$/.test(manifest.sourceRevision))throw new Error("Desktop update manifest requires a full source revision");if(typeof manifest.platform!=="string"||!["darwin","linux","win32"].includes(manifest.platform))throw new Error("Desktop update manifest requires a supported platform identifier");if(typeof manifest.architecture!=="string"||!/^[a-z0-9_-]+$/.test(manifest.architecture))throw new Error("Desktop update manifest requires an architecture");if(typeof manifest.signingKeyId!=="string"||!/^[a-zA-Z0-9._-]+$/.test(manifest.signingKeyId))throw new Error("Desktop update manifest requires a signing key ID");if(typeof manifest.signature!=="string"||!/^[A-Za-z0-9_-]+$/.test(manifest.signature))throw new Error("Desktop update manifest requires an Ed25519 signature");return manifest}export function updateManifestPayload(manifest){return Buffer.from(JSON.stringify({version:manifest.version,url:manifest.url,sha256:manifest.sha256.toLowerCase(),size:manifest.size,sourceRevision:manifest.sourceRevision,platform:manifest.platform,architecture:manifest.architecture,signingKeyId:manifest.signingKeyId,publishedAt:manifest.publishedAt||null,notes:manifest.notes||null}),"utf8")}export function verifyUpdateManifestSignature(manifest,trustedKeys){const encodedKey=trustedKeys[manifest.signingKeyId];if(!encodedKey)throw new Error(`Desktop update signing key is not trusted: ${manifest.signingKeyId}`);const prefix="ed25519-public:";if(!encodedKey.startsWith(prefix))throw new Error("Desktop update signing key has an invalid encoding");try{const publicKey=createPublicKey({key:Buffer.from(encodedKey.slice(prefix.length),"base64url"),format:"der",type:"spki"});const signature=Buffer.from(manifest.signature,"base64url");if(publicKey.asymmetricKeyType!=="ed25519"||signature.length!==64||!verify(null,updateManifestPayload(manifest),publicKey,signature))throw new Error("invalid")}catch{throw new Error("Desktop update manifest signature verification failed")}}function assertUpdateTarget(manifest,target={platform:process.platform,architecture:process.arch}){if(manifest.platform!==target.platform||manifest.architecture!==target.architecture)throw new Error(`Desktop update is built for ${manifest.platform}-${manifest.architecture}, not this app's ${target.platform}-${target.architecture}`)}function parseVersion(version){const match=version.match(/^v?(\d+)\.(\d+)\.(\d+)(?:-[0-9A-Za-z.-]+)?$/);if(!match)throw new Error(`Invalid semantic version: ${version}`);return[Number(match[1]),Number(match[2]),Number(match[3])]}function assertSecureUrl(value){const url=new URL(value);const isLoopback=["localhost","127.0.0.1","::1"].includes(url.hostname);if(url.protocol!=="https:"&&!(url.protocol==="http:"&&isLoopback))throw new Error("Desktop updates require HTTPS outside loopback development")}
1
+ import{createHash,createPublicKey,verify}from"node:crypto";import{mkdir,rename,rm,writeFile}from"node:fs/promises";import process from"node:process";import{dirname}from"node:path";export async function checkForDesktopUpdate(options){assertSecureUrl(options.manifestUrl);const response=await(options.fetcher||fetch)(options.manifestUrl,{headers:{Accept:"application/json"}});if(response.status===204)return null;if(!response.ok)throw new Error(`Desktop update check failed with HTTP ${response.status}`);const manifest=validateUpdateManifest(await response.json());verifyUpdateManifestSignature(manifest,options.trustedKeys);assertUpdateTarget(manifest,options.target);return compareVersions(manifest.version,options.currentVersion)>0?manifest:null}export async function stageDesktopUpdate(manifest,destination,fetcher=fetch,trustedKeys,target){validateUpdateManifest(manifest);if(!trustedKeys)throw new Error("Desktop update staging requires trusted signing keys");verifyUpdateManifestSignature(manifest,trustedKeys);assertUpdateTarget(manifest,target);assertSecureUrl(manifest.url);const response=await fetcher(manifest.url);if(!response.ok)throw new Error(`Desktop update download failed with HTTP ${response.status}`);const bytes=new Uint8Array(await response.arrayBuffer());if(bytes.byteLength!==manifest.size)throw new Error(`Desktop update size mismatch: expected ${manifest.size}, received ${bytes.byteLength}`);const checksum=createHash("sha256").update(bytes).digest("hex");if(checksum!==manifest.sha256.toLowerCase())throw new Error("Desktop update checksum mismatch");await mkdir(dirname(destination),{recursive:true});const temporaryPath=`${destination}.download-${crypto.randomUUID()}`;try{await writeFile(temporaryPath,bytes,{mode:448});await rename(temporaryPath,destination)}catch(error){await rm(temporaryPath,{force:true});throw error}return{manifest,path:destination,bytes:bytes.byteLength}}export function compareVersions(left,right){const leftParts=parseVersion(left);const rightParts=parseVersion(right);for(let index=0;index<3;index++){const difference=leftParts[index]-rightParts[index];if(difference!==0)return Math.sign(difference)}return 0}export function validateUpdateManifest(input){if(!input||typeof input!=="object")throw new Error("Desktop update manifest must be an object");const manifest=input;parseVersion(manifest.version||"");if(typeof manifest.url!=="string")throw new Error("Desktop update manifest requires a URL");if(typeof manifest.sha256!=="string"||!/^[a-f0-9]{64}$/i.test(manifest.sha256))throw new Error("Desktop update manifest requires a SHA-256 checksum");if(!Number.isInteger(manifest.size)||manifest.size<0)throw new Error("Desktop update manifest requires a non-negative integer size");if(typeof manifest.sourceRevision!=="string"||!/^[0-9a-f]{40}$/.test(manifest.sourceRevision))throw new Error("Desktop update manifest requires a full source revision");if(typeof manifest.platform!=="string"||!["darwin","linux","win32"].includes(manifest.platform))throw new Error("Desktop update manifest requires a supported platform identifier");if(typeof manifest.architecture!=="string"||!/^[a-z0-9_-]+$/.test(manifest.architecture))throw new Error("Desktop update manifest requires an architecture");if(typeof manifest.signingKeyId!=="string"||!/^[a-zA-Z0-9._-]+$/.test(manifest.signingKeyId))throw new Error("Desktop update manifest requires a signing key ID");if(typeof manifest.signature!=="string"||!/^[A-Za-z0-9_-]+$/.test(manifest.signature))throw new Error("Desktop update manifest requires an Ed25519 signature");return manifest}export function updateManifestPayload(manifest){return Buffer.from(JSON.stringify({version:manifest.version,url:manifest.url,sha256:manifest.sha256.toLowerCase(),size:manifest.size,sourceRevision:manifest.sourceRevision,platform:manifest.platform,architecture:manifest.architecture,signingKeyId:manifest.signingKeyId,publishedAt:manifest.publishedAt||null,notes:manifest.notes||null}),"utf8")}export function verifyUpdateManifestSignature(manifest,trustedKeys){const encodedKey=trustedKeys[manifest.signingKeyId];if(!encodedKey)throw new Error(`Desktop update signing key is not trusted: ${manifest.signingKeyId}`);const prefix="ed25519-public:";if(!encodedKey.startsWith(prefix))throw new Error("Desktop update signing key has an invalid encoding");try{const publicKey=createPublicKey({key:Buffer.from(encodedKey.slice(prefix.length),"base64url"),format:"der",type:"spki"});const signature=Buffer.from(manifest.signature,"base64url");if(publicKey.asymmetricKeyType!=="ed25519"||signature.length!==64||!verify(null,updateManifestPayload(manifest),publicKey,signature))throw new Error("invalid")}catch{throw new Error("Desktop update manifest signature verification failed")}}function assertUpdateTarget(manifest,target={platform:process.platform,architecture:process.arch}){if(manifest.platform!==target.platform||manifest.architecture!==target.architecture)throw new Error(`Desktop update is built for ${manifest.platform}-${manifest.architecture}, not this app's ${target.platform}-${target.architecture}`)}function parseVersion(version){const match=version.match(/^v?(\d+)\.(\d+)\.(\d+)(?:-[0-9A-Za-z.-]+)?$/);if(!match)throw new Error(`Invalid semantic version: ${version}`);return[Number(match[1]),Number(match[2]),Number(match[3])]}function assertSecureUrl(value){const url=new URL(value);const isLoopback=["localhost","127.0.0.1","::1"].includes(url.hostname);if(url.protocol!=="https:"&&!(url.protocol==="http:"&&isLoopback))throw new Error("Desktop updates require HTTPS outside loopback development")}
@@ -0,0 +1,131 @@
1
+ /**
2
+ * The rules every request passes before the app or the views see it. Kept
3
+ * apart from the server so both ways of serving views (the agent's own server
4
+ * and stx's) apply the same ones.
5
+ */
6
+ export declare function createWebviewGate(options: WebviewGateOptions): WebviewGate;
7
+ /** Whether nothing is listening on a loopback port. */
8
+ export declare function portIsFree(port: number): boolean;
9
+ /**
10
+ * The port to serve on: the one asked for, else the one remembered from the
11
+ * last launch, when it is still free; otherwise any free port. The choice is
12
+ * written back, so the next launch starts from it.
13
+ */
14
+ export declare function pickAgentPort(options?: { port?: number, portFile?: string }): number;
15
+ /**
16
+ * Where a desktop app keeps its own files, by platform: Application Support
17
+ * and `~/Library/Logs` on macOS, `%APPDATA%` on Windows, the XDG data and
18
+ * state directories on Linux.
19
+ */
20
+ export declare function desktopAppPaths(appName: string, options?: { platform?: string, home?: string, env?: Record<string, string | undefined> }): DesktopAppPaths;
21
+ /**
22
+ * The PATH an agent needs to find the tools a person installed.
23
+ *
24
+ * An app started from Finder, Explorer or a `.desktop` file does not get the
25
+ * PATH a terminal has: launchd hands out `/usr/bin:/bin:/usr/sbin:/sbin`, and a
26
+ * desktop session on Linux skips the shell profile where `~/.bun/bin` and its
27
+ * like are added. So `bun`, `git`, `docker` or `ssh` installed by a package
28
+ * manager is invisible to the app on a machine where it works in a terminal.
29
+ * The places installers use come first, and whatever PATH exists is kept last.
30
+ */
31
+ export declare function widenedPath(options?: { platform?: string, home?: string, env?: Record<string, string | undefined> }): string;
32
+ /** Set this process's PATH (and so its children's) to `widenedPath()`. */
33
+ export declare function applyWidenedPath(): void;
34
+ export declare function startWebviewAgent(options: WebviewAgentOptions): Promise<WebviewAgent>;
35
+ export declare const INSTANCE_PATH: '/__desktop/instance';
36
+ export declare const INSTANCE_HEADER: 'x-desktop-instance';
37
+ /**
38
+ * The agent behind a web view desktop app (`desktop.webview`): a loopback
39
+ * server that serves the app's views and its own request handling, with a
40
+ * Craft web view window as its only caller. The same on macOS, Windows and
41
+ * Linux.
42
+ *
43
+ * Only the app's own window may call it. The launcher opens the window on a
44
+ * URL carrying a one-time token; that request trades it for an HttpOnly,
45
+ * SameSite=Strict cookie and is redirected to the same page without it. Every
46
+ * later request must carry the cookie and name this server in its Host header,
47
+ * so a page in a browser on the same machine cannot reach the agent, and a
48
+ * DNS-rebinding page (whose Host is its own name) cannot pose as the app. The
49
+ * token and the cookie are new on every launch.
50
+ */
51
+ /** What a request handler is told about the agent it runs in. */
52
+ export declare interface WebviewAgentContext {
53
+ appName: string
54
+ version: string
55
+ origin: string
56
+ port: number
57
+ dataDir: string
58
+ }
59
+ /** A second launch of the app, forwarded to the one already running. */
60
+ export declare interface SecondInstanceLaunch {
61
+ args: string[]
62
+ url?: string
63
+ cwd: string
64
+ }
65
+ export declare interface WebviewAgentOptions {
66
+ appName: string
67
+ version?: string
68
+ views: WebviewViews
69
+ handler?: WebviewHandler
70
+ port?: number
71
+ portFile?: string
72
+ dataDir?: string
73
+ cookieName?: string
74
+ publicPaths?: string[]
75
+ instanceSecret?: string
76
+ onSecondInstance?: (launch: SecondInstanceLaunch) => void | Promise<void>
77
+ }
78
+ export declare interface WebviewAgent {
79
+ port: number
80
+ origin: string
81
+ launchUrl: (path?: string) => string
82
+ windowReady: Promise<void>
83
+ stop: () => void
84
+ }
85
+ export declare interface WebviewGateOptions {
86
+ port: () => number
87
+ cookieName?: string
88
+ publicPaths?: string[]
89
+ instanceSecret?: string
90
+ appName?: string
91
+ }
92
+ export declare interface WebviewGate {
93
+ check: (request: Request) => GateDecision
94
+ mint: () => string
95
+ readonly cookieName: string
96
+ }
97
+ export declare interface DesktopAppPaths {
98
+ dataDir: string
99
+ portFile: string
100
+ lockFile: string
101
+ logFile: string
102
+ updatesDir: string
103
+ }
104
+ /** Answers a request the window made. Returning nothing lets the views answer it. */
105
+ export type WebviewHandler = (request: Request, context: WebviewAgentContext) => Response | undefined | null | void | Promise<Response | undefined | null | void>;
106
+ /** How the views are served. */
107
+ export type WebviewViews = | { kind: 'static', dir: string }
108
+ /** Built pages compiled into the agent: request path to embedded file. */
109
+ | { kind: 'embedded', files: Record<string, string> }
110
+ /** The project's stx views, rendered live (`buddy dev:desktop`). */
111
+ | { kind: 'stx', dir: string, components?: string[], root: string, serve?: StxServe }
112
+ | { kind: 'none' }
113
+ /** `serve` from `bun-plugin-stx/serve`, as much of it as the agent uses. */
114
+ export type StxServe = (options: {
115
+ patterns: string[]
116
+ port: number
117
+ quiet?: boolean
118
+ componentsDir?: string
119
+ additionalComponentsDirs?: string[]
120
+ onRequest: (request: Request, server: { stop: (force?: boolean) => unknown }) => Response | undefined | Promise<Response | undefined>
121
+ }) => Promise<void>;
122
+ /** What the gate decided about one request. */
123
+ export type GateDecision = | { response: Response }
124
+ /** The app's own window. */
125
+ | { allow: 'window' }
126
+ /** A path the app opened to callers without the cookie. */
127
+ | { allow: 'public' }
128
+ /** A framework asset: the views answer it, the app's handler does not see it. */
129
+ | { allow: 'asset' }
130
+ /** A second launch, already authenticated by the instance secret. */
131
+ | { allow: 'instance' }
@@ -0,0 +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{isAgentHost,newAgentToken,rememberedPort,sessionCookie,staticContentType,staticFileResponse}from"./agent";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 headers={"content-type":staticContentType(candidate)};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;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 before(request){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({error:message}),{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});const serve=views.serve??(await import(Bun.resolveSync("bun-plugin-stx/serve",views.root))).serve;let stxServer;const[componentsDir,...additionalComponentsDirs]=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;rememberPort(options.portFile,port);return{port,origin:`http://127.0.0.1:${port}`,launchUrl,windowReady,stop:()=>{server.stop(true)}}}
@@ -0,0 +1,106 @@
1
+ import type { BundleCommand } from './macos-bundle';
2
+ import type { DesktopTargetName, WebviewDesktopConfig } from '@stacksjs/types';
3
+ import type { WebviewAppManifest } from './webview-launcher';
4
+ /** Whether the project declares a web view desktop app. */
5
+ export declare function hasWebviewDesktop(root: string): Promise<boolean>;
6
+ export declare function loadWebviewDesktop(root: string, packageVersion?: string): Promise<ResolvedWebviewDesktop | null>;
7
+ export declare function resolveWebviewDesktop(config: WebviewDesktopConfig, packageVersion?: string): ResolvedWebviewDesktop;
8
+ /** Why a config cannot build, as a list; empty when it can. */
9
+ export declare function validateWebviewDesktop(config: ResolvedWebviewDesktop): string[];
10
+ export declare function hostDesktopTarget(): DesktopTargetName;
11
+ /** `darwin-arm64,linux-x64`, or `all`, as targets. Default: the machine's own. */
12
+ export declare function parseDesktopTargets(input: string | undefined, host?: DesktopTargetName): DesktopTargetName[];
13
+ export declare function splitDesktopTarget(target: DesktopTargetName): { platform: 'darwin' | 'linux' | 'win32', architecture: 'arm64' | 'x64' };
14
+ /** Bun's name for a compile target (`--target=bun-windows-x64`). */
15
+ export declare function bunCompileTarget(target: DesktopTargetName): string;
16
+ /**
17
+ * The `bun build` arguments for an agent executable. Another machine's target
18
+ * is cross-compiled by Bun, which downloads that target's runtime; bytecode is
19
+ * left out there, because it is produced by the build machine's engine.
20
+ */
21
+ export declare function webviewCompileArgs(options: { entry: string, outfile: string, target: DesktopTargetName, host?: DesktopTargetName, minify?: boolean }): string[];
22
+ /**
23
+ * The Craft web view binary for a target: the path the config names, then
24
+ * `CRAFT_BIN_<PLATFORM>_<ARCH>`, then (for the build machine's own target)
25
+ * `hostRuntime`. Craft publishes one per platform with each release
26
+ * (`craft-<os>-<arch>.zip`); a cross-build needs the other platforms' unpacked
27
+ * somewhere and named here.
28
+ */
29
+ export declare function webviewRuntimeFor(config: Pick<WebviewDesktopConfig, 'runtime'>, target: DesktopTargetName, options: { root: string, env?: Record<string, string | undefined>, host?: DesktopTargetName, hostRuntime?: () => string }): string;
30
+ /**
31
+ * Which of the optional flags a Craft binary understands, read from the binary
32
+ * itself: a flag it parses is a string inside it. Nothing is run, so this
33
+ * works for another platform's runtime too. An older Craft that is handed a
34
+ * flag it does not know opens its demo window instead of the app's.
35
+ */
36
+ export declare function probeCraftFlags(runtime: string, flags?: readonly string[]): string[];
37
+ /** What the launcher reads, from the config. `runtime` says where the Craft binary will be. */
38
+ export declare function webviewManifest(config: ResolvedWebviewDesktop, options: { runtime: string, runtimeFlags?: string[], development?: boolean, sourceRevision?: string }): WebviewAppManifest;
39
+ /** Every file under a directory of built views, as request path (`/about/index.html`) to file. */
40
+ export declare function collectViewFiles(directory: string): Record<string, string>;
41
+ export declare function renderWebviewEntitlements(config: Pick<ResolvedWebviewDesktop, 'macos'>): string;
42
+ export declare function renderWebviewInfoPlist(config: ResolvedWebviewDesktop, options?: { iconFile?: string }): { xml: string, ignored: string[] };
43
+ /**
44
+ * Lay out and sign `<App>.app`: the agent as the executable, Craft beside it.
45
+ * Inside out, as codesign wants: the runtime first, then the bundle, both with
46
+ * the hardened runtime so the same bundle can be notarized.
47
+ */
48
+ export declare function assembleWebviewMacosApp(options: AssembleWebviewMacosAppOptions): { appPath: string, entitlementsPath: string, ignoredPlistKeys: string[] };
49
+ /**
50
+ * The input to Craft's packaging (`packageApp` from `craft-native`) for a
51
+ * Windows or Linux target, written beside the staged files as
52
+ * `craft-package.json`. On Windows the Craft runtime rides along as an
53
+ * additional file; on Linux it is compiled into the one binary Craft's
54
+ * AppImage, deb and rpm builders take.
55
+ */
56
+ export declare function webviewPackageConfig(config: ResolvedWebviewDesktop, target: DesktopTargetName, staged: { binary: string, additionalFiles?: string[], outDir: string, icon?: string, certificatePassword?: string }): Record<string, unknown>;
57
+ /**
58
+ * Which steps of a target's build need that target's own operating system.
59
+ * Compiling the agent does not: Bun cross-compiles. Everything that makes an
60
+ * installer does.
61
+ */
62
+ export declare function nativeBuildSteps(target: DesktopTargetName): string;
63
+ /** `signtool` arguments that sign one Windows file with a `.pfx`, SHA-256, with a trusted timestamp so the signature outlives the certificate. */
64
+ export declare function signtoolArgs(options: { file: string, certificatePath: string, certificatePassword?: string, timestampUrl?: string }): string[];
65
+ /** The file names a release publishes for a target: the one an installed app updates from, and what a person downloads first. */
66
+ export declare function releaseArtifactNames(config: Pick<ResolvedWebviewDesktop, 'appName' | 'version'>, target: DesktopTargetName): { update: string, downloads: string[] };
67
+ /**
68
+ * Why a version must not be published over what a channel already serves, or
69
+ * nothing when it may. A feed that went backwards, or served two different
70
+ * builds under one version, would leave installed apps unable to tell which
71
+ * they have.
72
+ */
73
+ export declare function releaseVersionProblem(version: string, published: string | null | undefined, compare: (left: string, right: string) => number): string | undefined;
74
+ /**
75
+ * `desktop.webview` resolved, and the pieces `buddy build:desktop` puts
76
+ * together for it: which targets, how each is compiled, and what each
77
+ * platform's package is made from.
78
+ */
79
+ export declare const DESKTOP_TARGETS: readonly DesktopTargetName[];
80
+ export declare const WEBVIEW_DEFAULTS: {
81
+ readonly views: 'resources/desktop';
82
+ readonly output: 'storage/framework/desktop/webview';
83
+ readonly width: 1280;
84
+ readonly height: 800;
85
+ readonly minimumSystemVersion: '13.0';
86
+ readonly category: 'public.app-category.developer-tools'
87
+ };
88
+ /** What a compiled Bun executable needs under the hardened runtime, which notarization requires: a JIT, and the memory it writes code into. */
89
+ export declare const BUN_HARDENED_ENTITLEMENTS: Readonly<Record<string, boolean>>;
90
+ export declare interface ResolvedWebviewDesktop extends WebviewDesktopConfig {
91
+ version: string
92
+ window: Required<Pick<NonNullable<WebviewDesktopConfig['window']>, 'title' | 'width' | 'height'>> & NonNullable<WebviewDesktopConfig['window']>
93
+ agent: NonNullable<WebviewDesktopConfig['agent']> & { views: string }
94
+ output: string
95
+ executable: string
96
+ slug: string
97
+ }
98
+ export declare interface AssembleWebviewMacosAppOptions {
99
+ config: ResolvedWebviewDesktop
100
+ root: string
101
+ agent: string
102
+ runtime: string
103
+ output: string
104
+ signingIdentity?: string
105
+ run?: BundleCommand
106
+ }
@@ -0,0 +1,6 @@
1
+ import{chmodSync,copyFileSync,existsSync,mkdirSync,readdirSync,readFileSync,rmSync,statSync,writeFileSync}from"node:fs";import{isAbsolute,join,relative,resolve,sep}from"node:path";import process from"node:process";import{codesignArgs,plistValue,renderInfoPlist}from"./index";import{loadDesktopConfig}from"./macos-app";import{makeIcns,runBundleCommand}from"./macos-bundle";import{OPTIONAL_CRAFT_FLAGS,WEBVIEW_RUNTIME_NAME}from"./webview-launcher";export const DESKTOP_TARGETS=["darwin-arm64","darwin-x64","linux-x64","linux-arm64","win32-x64","win32-arm64"];export const WEBVIEW_DEFAULTS={views:"resources/desktop",output:"storage/framework/desktop/webview",width:1280,height:800,minimumSystemVersion:"13.0",category:"public.app-category.developer-tools"};export async function hasWebviewDesktop(root){return Boolean((await loadDesktopConfig(root))?.webview)}export async function loadWebviewDesktop(root,packageVersion="0.0.0"){const config=await loadDesktopConfig(root);return config?.webview?resolveWebviewDesktop(config.webview,packageVersion):null}export function resolveWebviewDesktop(config,packageVersion="0.0.0"){return{...config,version:config.version??packageVersion,window:{...config.window,title:config.window?.title??config.appName,width:config.window?.width??WEBVIEW_DEFAULTS.width,height:config.window?.height??WEBVIEW_DEFAULTS.height},agent:{...config.agent,views:config.agent?.views??WEBVIEW_DEFAULTS.views},output:config.output??WEBVIEW_DEFAULTS.output,executable:config.appName.replace(/[^\w .-]+/g,"").trim()||"App",slug:config.appName.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"app"}}export function validateWebviewDesktop(config){const errors=[];if(!config.appName?.trim())errors.push("webview.appName is required");if(!/^[a-z0-9-]+(\.[a-z0-9-]+)+$/i.test(config.appId??""))errors.push(`webview.appId must be reverse-DNS, like org.example.app (got ${JSON.stringify(config.appId)})`);if(!/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(config.version))errors.push(`webview.version must be a semantic version (got ${JSON.stringify(config.version)})`);for(const scheme of config.urlSchemes??[]){if(!/^[a-z][a-z0-9+.-]*$/i.test(scheme))errors.push(`webview.urlSchemes: ${JSON.stringify(scheme)} is not a URL scheme`)}if(config.updates){try{const url=new URL(config.updates.feedUrl);if(url.protocol!=="https:"&&!["localhost","127.0.0.1"].includes(url.hostname))errors.push("webview.updates.feedUrl must be https")}catch{errors.push(`webview.updates.feedUrl is not a URL (got ${JSON.stringify(config.updates.feedUrl)})`)}const keys=Object.entries(config.updates.publicKeys??{});if(!keys.length)errors.push("webview.updates.publicKeys needs at least one key (run `buddy desktop:update:keypair`)");for(const[id,key]of keys){if(!key.startsWith("ed25519-public:"))errors.push(`webview.updates.publicKeys.${id} is not a public key (it starts with ed25519-public:)`)}}return errors}export function hostDesktopTarget(){return`${process.platform}-${process.arch}`}export function parseDesktopTargets(input,host=hostDesktopTarget()){if(!input?.trim())return[host];if(input.trim()==="all")return[...DESKTOP_TARGETS];const targets=input.split(",").map((part)=>part.trim()).filter(Boolean).map((part)=>{const name=part.replace(/^macos-/,"darwin-").replace(/^windows-/,"win32-");if(!DESKTOP_TARGETS.includes(name))throw new Error(`Unknown desktop target ${JSON.stringify(part)}. Targets: ${DESKTOP_TARGETS.join(", ")}, or all.`);return name});return[...new Set(targets)]}export function splitDesktopTarget(target){const[platform,architecture]=target.split("-");return{platform,architecture}}export function bunCompileTarget(target){const{platform,architecture}=splitDesktopTarget(target);return`bun-${platform==="win32"?"windows":platform}-${architecture}`}export function webviewCompileArgs(options){const cross=options.target!==(options.host??hostDesktopTarget());return["build","--compile",...options.minify===false?[]:["--minify"],...cross?[`--target=${bunCompileTarget(options.target)}`]:["--bytecode","--format=esm"],"--no-compile-autoload-bunfig","--no-compile-autoload-dotenv",...options.target.startsWith("win32-")?["--windows-hide-console"]:[],options.entry,"--outfile",options.outfile]}export function webviewRuntimeFor(config,target,options){const env=options.env??process.env;const variable=`CRAFT_BIN_${target.replace("-","_").toUpperCase()}`;const named=config.runtime?.[target]??env[variable];if(named){const file=isAbsolute(named)?named:resolve(options.root,named);if(!existsSync(file))throw new Error(`The Craft runtime for ${target} does not exist: ${file}`);return file}if(target===(options.host??hostDesktopTarget())&&options.hostRuntime)return options.hostRuntime();throw new Error(`No Craft runtime for ${target}. Unpack that platform's Craft release and name its binary in desktop.webview.runtime['${target}'] or ${variable}.`)}export function probeCraftFlags(runtime,flags=OPTIONAL_CRAFT_FLAGS){const binary=readFileSync(runtime);return flags.filter((flag)=>binary.includes(flag))}export function webviewManifest(config,options){return{appName:config.appName,appId:config.appId,version:config.version,runtime:options.runtime,window:{title:config.window.title,width:config.window.width,height:config.window.height,...config.window.darkMode!==undefined?{darkMode:config.window.darkMode}:{},...options.development||config.window.devtools?{devtools:true}:{},...config.window.titlebarHidden?{titlebarHidden:true}:{},...config.window.arguments?.length?{arguments:config.window.arguments}:{}},...config.agent.port?{port:config.agent.port}:{},...config.agent.startPath?{startPath:config.agent.startPath}:{},...config.agent.publicPaths?.length?{publicPaths:config.agent.publicPaths}:{},...config.urlSchemes?.length?{urlSchemes:config.urlSchemes}:{},...config.updates&&!options.development?{updates:{feedUrl:config.updates.feedUrl,publicKeys:config.updates.publicKeys,...config.updates.channel?{channel:config.updates.channel}:{},...config.updates.checkEveryHours!==undefined?{checkEveryHours:config.updates.checkEveryHours}:{}}}:{},...options.runtimeFlags?.length?{runtimeFlags:options.runtimeFlags}:{},...options.sourceRevision?{sourceRevision:options.sourceRevision}:{}}}export function collectViewFiles(directory){const files={};const walk=(current)=>{for(const entry of readdirSync(current).sort()){if(entry===".DS_Store")continue;const file=join(current,entry);if(statSync(file).isDirectory())walk(file);else files[`/${relative(directory,file).split(sep).join("/")}`]=file}};if(existsSync(directory))walk(directory);return files}export const BUN_HARDENED_ENTITLEMENTS={"com.apple.security.cs.allow-jit":true,"com.apple.security.cs.allow-unsigned-executable-memory":true,"com.apple.security.cs.disable-library-validation":true};export function renderWebviewEntitlements(config){return`<?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "https://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <plist version="1.0">
4
+ ${plistValue({...BUN_HARDENED_ENTITLEMENTS,...config.macos?.entitlements})}
5
+ </plist>
6
+ `}export function renderWebviewInfoPlist(config,options={}){const schemes=config.urlSchemes??[];return renderInfoPlist({appName:config.appName,bundleId:config.macos?.bundleId??config.appId,version:config.version,executable:config.executable,iconFile:options.iconFile,ownsLauncher:true,declared:{LSMinimumSystemVersion:config.macos?.minimumSystemVersion??WEBVIEW_DEFAULTS.minimumSystemVersion,LSApplicationCategoryType:config.macos?.category??WEBVIEW_DEFAULTS.category,...schemes.length?{CFBundleURLTypes:[{CFBundleURLName:config.appId,CFBundleURLSchemes:schemes}]}:{},...config.macos?.usageDescriptions,...config.macos?.infoPlist}})}export function assembleWebviewMacosApp(options){const{config}=options;const run=options.run??runBundleCommand;const identity=options.signingIdentity??"-";const appPath=join(options.output,`${config.appName}.app`);const macos=join(appPath,"Contents","MacOS");const resources=join(appPath,"Contents","Resources");rmSync(appPath,{recursive:true,force:true});mkdirSync(macos,{recursive:true});mkdirSync(resources,{recursive:true});const executable=join(macos,config.executable);const runtime=join(macos,WEBVIEW_RUNTIME_NAME);copyFileSync(options.agent,executable);copyFileSync(options.runtime,runtime);chmodSync(executable,493);chmodSync(runtime,493);let iconFile;if(config.icon){const icon=resolve(options.root,config.icon);if(!existsSync(icon))throw new Error(`webview.icon does not exist: ${icon}`);if(icon.endsWith(".icns"))copyFileSync(icon,join(resources,"AppIcon.icns"));else makeIcns(icon,join(resources,"AppIcon.icns"),options.output,run);iconFile="AppIcon"}const plist=renderWebviewInfoPlist(config,{iconFile});writeFileSync(join(appPath,"Contents","Info.plist"),plist.xml);const entitlementsPath=join(options.output,`${config.appName}.entitlements`);writeFileSync(entitlementsPath,renderWebviewEntitlements(config));run(codesignArgs({identity,target:runtime}));run(codesignArgs({identity,target:appPath,entitlements:entitlementsPath}));return{appPath,entitlementsPath,ignoredPlistKeys:plist.ignored}}export function webviewPackageConfig(config,target,staged){const{platform,architecture}=splitDesktopTarget(target);const base={name:config.appName,version:config.version,...config.description?{description:config.description}:{},...config.publisher?{author:config.publisher}:{},...config.homepage?{homepage:config.homepage}:{},bundleId:config.appId,binaryPath:staged.binary,...staged.icon?{iconPath:staged.icon}:{},outDir:staged.outDir};if(platform==="win32"){return{...base,platforms:["windows"],windows:{msi:true,zip:true,architecture,...staged.additionalFiles?.length?{additionalFiles:staged.additionalFiles}:{},...config.urlSchemes?.length?{urlSchemes:config.urlSchemes}:{},...config.windows?.certificatePath?{certificatePath:config.windows.certificatePath,...staged.certificatePassword?{certificatePassword:staged.certificatePassword}:{}}:{}}}}return{...base,platforms:["linux"],linux:{appImage:true,deb:true,rpm:true,categories:config.linux?.categories??["Development"],...config.urlSchemes?.length?{urlSchemes:config.urlSchemes}:{},...config.linux?.debDependencies?{debDependencies:config.linux.debDependencies}:{},...config.linux?.rpmDependencies?{rpmDependencies:config.linux.rpmDependencies}:{}}}}export function nativeBuildSteps(target){const{platform}=splitDesktopTarget(target);if(platform==="darwin")return"The .app is assembled and signed with codesign, notarized with notarytool and imaged with hdiutil: macOS only.";if(platform==="win32")return"The MSI is built with WiX (candle, light) and signed with signtool: Windows only.";return"The AppImage (appimagetool), deb (dpkg-deb) and rpm (rpmbuild) are built with Linux tools: Linux only."}export function signtoolArgs(options){return["signtool.exe","sign","/f",options.certificatePath,...options.certificatePassword?["/p",options.certificatePassword]:[],"/fd","SHA256","/tr",options.timestampUrl??"http://timestamp.digicert.com","/td","SHA256",options.file]}export function releaseArtifactNames(config,target){const{platform,architecture}=splitDesktopTarget(target);const base=`${config.appName.replace(/[^\w.-]+/g,"-")}-${config.version}-${architecture}`;if(platform==="darwin")return{update:`${base}.zip`,downloads:[`${base}.dmg`]};if(platform==="win32")return{update:`${base}.msi`,downloads:[]};return{update:`${base}.AppImage`,downloads:[`${base}.deb`,`${base}.rpm`]}}export function releaseVersionProblem(version,published,compare){if(!published)return;const order=compare(version,published);if(order===0)return`${version} is already published. Bump the version; a published build is never replaced under the same number.`;if(order<0)return`${published} is already published, which is newer than ${version}.`;return}
@@ -0,0 +1,135 @@
1
+ import { desktopAppPaths } from './webview-agent';
2
+ import type { BeforeDesktopUpdate, DesktopUpdater } from './update-install';
3
+ import type { SecondInstanceLaunch, WebviewAgent, WebviewAgentContext, WebviewHandler, WebviewViews } from './webview-agent';
4
+ /** A module's default export, as a `WebviewAgentModule`: a bare function is its `fetch`. */
5
+ export declare function agentModuleOf(loaded: unknown): WebviewAgentModule;
6
+ /**
7
+ * Take the instance lock, or learn who holds it. A lock left by a process
8
+ * that is gone is taken over.
9
+ */
10
+ export declare function acquireWebviewInstance(lockFile: string, pid?: number): { acquired: true, record: InstanceRecord } | { acquired: false, holder: InstanceRecord };
11
+ /** Record the port once the agent is serving, so a second launch can reach it. */
12
+ export declare function publishInstancePort(lockFile: string, record: InstanceRecord, port: number): void;
13
+ export declare function releaseWebviewInstance(lockFile: string, pid?: number): void;
14
+ /**
15
+ * A launch's arguments, sorted: the link that started it (an argument in one
16
+ * of the app's URL schemes), the process to wait for after a relaunch, and
17
+ * the rest, which are the app's own.
18
+ */
19
+ export declare function parseLaunchArguments(argv: readonly string[], urlSchemes?: readonly string[]): { args: string[], url?: string, waitPid?: number };
20
+ /**
21
+ * Hand a launch to the instance that holds the lock. The holder may still be
22
+ * starting (its port is 0 until it serves), so the lock is re-read for a few
23
+ * seconds. Resolves false when it could not be reached.
24
+ */
25
+ export declare function forwardToInstance(lockFile: string, launch: SecondInstanceLaunch, options?: { fetcher?: typeof fetch, attempts?: number, delayMs?: number }): Promise<boolean>;
26
+ /**
27
+ * Craft's command line for the app's window. `--single-instance` (where the
28
+ * runtime has it) makes a second Craft with the same id forward to this one
29
+ * and bring its window forward, which is how a second launch raises the app.
30
+ */
31
+ export declare function craftWindowCommand(manifest: Pick<WebviewAppManifest, 'appName' | 'appId' | 'window' | 'runtimeFlags'>, runtime: string, url: string, launch?: { args?: string[], url?: string }): string[];
32
+ /**
33
+ * Where the Craft binary is. An embedded one is unpacked to the data
34
+ * directory, under its own digest, so an update that ships a new runtime
35
+ * unpacks beside the old one and a tampered copy is replaced.
36
+ */
37
+ export declare function resolveWebviewRuntime(manifest: Pick<WebviewAppManifest, 'runtime'>, options: { execPath?: string, embedded?: string, dataDir: string, platform?: string }): string;
38
+ /**
39
+ * Lock, agent, window; resolves with the exit code once the window closes. A
40
+ * second launch forwards its arguments to the first, raises its window, and
41
+ * resolves 0 without booting anything.
42
+ */
43
+ export declare function runWebviewApp(options: RunWebviewAppOptions): Promise<number>;
44
+ /**
45
+ * The executable's entrypoint, written by the build and compiled (or, in
46
+ * development, run) from there. The agent module, the manifest and every
47
+ * built view are named statically, so the compiled executable carries them:
48
+ * nothing is read from beside it but the Craft runtime.
49
+ */
50
+ export declare function renderWebviewEntry(options: {
51
+ manifest: WebviewAppManifest
52
+ agentEntry?: string
53
+
54
+ viewFiles?: Record<string, string>
55
+
56
+ stxViews?: { dir: string, components?: string[], root: string }
57
+ embeddedRuntime?: string
58
+ launcherModule?: string
59
+ }): string;
60
+ /** The agent module a project uses: `agent.entry`, else `app/Desktop/Agent.ts` when it exists. */
61
+ export declare function webviewAgentEntry(root: string, entry?: string): string | undefined;
62
+ /** Copy a file and keep it executable. */
63
+ export declare function copyExecutable(from: string, to: string): void;
64
+ /** Craft flags the launcher uses when the runtime has them. */
65
+ export declare const OPTIONAL_CRAFT_FLAGS: readonly ['--single-instance', '--deep-link', '--app-name'];
66
+ export declare const WEBVIEW_RUNTIME_NAME: 'craft-runtime';
67
+ /** Passed to a relaunched app: wait for this process (the one being replaced) to end before taking the lock. */
68
+ export declare const WAIT_PID_FLAG: '--wait-pid=';
69
+ /**
70
+ * The executable of a web view desktop app (`desktop.webview`), on macOS,
71
+ * Windows and Linux. It takes the instance lock, starts the agent, and opens
72
+ * a Craft web view window on it; when the window closes, the app ends. A
73
+ * second launch hands its arguments to the first and exits.
74
+ *
75
+ * `buddy dev:desktop` runs this from source in the project, with the views
76
+ * rendered live by stx. `buddy build:desktop` compiles it, with the built
77
+ * views and this manifest inside the executable.
78
+ */
79
+ export declare interface WebviewAppManifest {
80
+ appName: string
81
+ appId: string
82
+ version: string
83
+ runtime: string
84
+ window: {
85
+ title: string
86
+ width: number
87
+ height: number
88
+ darkMode?: boolean
89
+ devtools?: boolean
90
+ titlebarHidden?: boolean
91
+ arguments?: string[]
92
+ }
93
+ port?: number
94
+ startPath?: string
95
+ publicPaths?: string[]
96
+ urlSchemes?: string[]
97
+ updates?: {
98
+ feedUrl: string
99
+ publicKeys: Record<string, string>
100
+ channel?: string
101
+ checkEveryHours?: number
102
+ }
103
+ runtimeFlags?: string[]
104
+ sourceRevision?: string
105
+ }
106
+ /** What an app's agent module (`app/Desktop/Agent.ts`) may export as its default. */
107
+ export declare interface WebviewAgentModule {
108
+ fetch?: WebviewHandler
109
+ start?: (context: WebviewAgentContext & { launch: SecondInstanceLaunch, updater?: DesktopUpdater }) => void | Promise<void>
110
+ secondInstance?: (launch: SecondInstanceLaunch) => void | Promise<void>
111
+ beforeUpdate?: BeforeDesktopUpdate
112
+ stop?: () => void | Promise<void>
113
+ }
114
+ /** What the lock file holds: enough for a second launch to reach the first. */
115
+ export declare interface InstanceRecord {
116
+ pid: number
117
+ port: number
118
+ secret: string
119
+ }
120
+ export declare interface SpawnedWindow {
121
+ exited: Promise<number>
122
+ kill: () => void
123
+ }
124
+ export declare interface RunWebviewAppOptions {
125
+ manifest: WebviewAppManifest
126
+ views: WebviewViews
127
+ module?: () => Promise<unknown>
128
+ embeddedRuntime?: string
129
+ argv?: string[]
130
+ paths?: ReturnType<typeof desktopAppPaths>
131
+ logWhenDetached?: boolean
132
+ spawn?: (command: string[], env: Record<string, string>) => SpawnedWindow
133
+ platform?: string
134
+ onAgent?: (agent: WebviewAgent) => void
135
+ }
@@ -0,0 +1,19 @@
1
+ import{createHash}from"node:crypto";import{chmodSync,copyFileSync,existsSync,mkdirSync,readFileSync,renameSync,rmSync,writeFileSync}from"node:fs";import{dirname,isAbsolute,join,resolve}from"node:path";import process from"node:process";import{fileURLToPath}from"node:url";import{newAgentToken}from"./agent";import{logToFileWhenDetached}from"./agent-launcher";import{createDesktopUpdater,updateRequestHandler}from"./update-install";import{applyWidenedPath,desktopAppPaths,INSTANCE_HEADER,INSTANCE_PATH,startWebviewAgent}from"./webview-agent";export const OPTIONAL_CRAFT_FLAGS=["--single-instance","--deep-link","--app-name"];export const WEBVIEW_RUNTIME_NAME="craft-runtime";export const WAIT_PID_FLAG="--wait-pid=";export function agentModuleOf(loaded){const value=loaded&&typeof loaded==="object"&&"default"in loaded?loaded.default:loaded;if(typeof value==="function")return{fetch:value};return value&&typeof value==="object"?value:{}}function readInstance(lockFile){try{const record=JSON.parse(readFileSync(lockFile,"utf8"));return Number.isInteger(record.pid)&&typeof record.secret==="string"?{pid:record.pid,port:Number(record.port)||0,secret:record.secret}:null}catch{return null}}function isAlive(pid){try{process.kill(pid,0);return true}catch(error){return error.code==="EPERM"}}function writeInstance(lockFile,record){mkdirSync(dirname(lockFile),{recursive:true});const temporary=`${lockFile}.${record.pid}`;writeFileSync(temporary,JSON.stringify(record),{mode:384});renameSync(temporary,lockFile)}export function acquireWebviewInstance(lockFile,pid=process.pid){const holder=readInstance(lockFile);if(holder&&holder.pid!==pid&&isAlive(holder.pid))return{acquired:false,holder};const record={pid,port:0,secret:newAgentToken()};writeInstance(lockFile,record);return{acquired:true,record}}export function publishInstancePort(lockFile,record,port){record.port=port;writeInstance(lockFile,record)}export function releaseWebviewInstance(lockFile,pid=process.pid){if(readInstance(lockFile)?.pid===pid)rmSync(lockFile,{force:true})}export function parseLaunchArguments(argv,urlSchemes=[]){const args=[];let url;let waitPid;for(const arg of argv){if(arg.startsWith(WAIT_PID_FLAG)){const pid=Number(arg.slice(WAIT_PID_FLAG.length));if(Number.isInteger(pid)&&pid>0)waitPid=pid;continue}if(arg.startsWith("-psn_"))continue;if(!url&&urlSchemes.some((scheme)=>arg.toLowerCase().startsWith(`${scheme.toLowerCase()}:`))){url=arg;continue}args.push(arg)}return{args,...url?{url}:{},...waitPid?{waitPid}:{}}}export async function forwardToInstance(lockFile,launch,options={}){const fetcher=options.fetcher??fetch;for(let attempt=0;attempt<(options.attempts??40);attempt++){const holder=readInstance(lockFile);if(!holder||!isAlive(holder.pid))return false;if(holder.port){try{const response=await fetcher(`http://127.0.0.1:${holder.port}${INSTANCE_PATH}`,{method:"POST",headers:{"content-type":"application/json",[INSTANCE_HEADER]:holder.secret},body:JSON.stringify(launch)});if(response.status===204)return true}catch{}}await Bun.sleep(options.delayMs??125)}return false}export function craftWindowCommand(manifest,runtime,url,launch={}){const{window}=manifest;const has=(flag)=>manifest.runtimeFlags?.includes(flag)===true;return[runtime,"--url",url,"--title",window.title,"--width",String(window.width),"--height",String(window.height),...has("--app-name")?["--app-name",manifest.appName]:[],...has("--single-instance")?["--single-instance",manifest.appId,...(launch.args??[]).flatMap((arg)=>["--instance-arg",arg])]:[],...launch.url&&has("--deep-link")?["--deep-link",launch.url]:[],...window.devtools?[]:["--no-devtools"],...window.darkMode===true?["--dark"]:window.darkMode===false?["--light"]:[],...window.titlebarHidden?["--titlebar-hidden"]:[],...window.arguments??[]]}export function resolveWebviewRuntime(manifest,options){const platform=options.platform??process.platform;const name=platform==="win32"?`${WEBVIEW_RUNTIME_NAME}.exe`:WEBVIEW_RUNTIME_NAME;if(manifest.runtime==="beside")return join(dirname(options.execPath??process.execPath),name);if(manifest.runtime!=="embedded")return manifest.runtime;if(!options.embedded)throw new Error("This app was built with an embedded Craft runtime, but none was compiled in.");const bytes=readFileSync(options.embedded);const digest=createHash("sha256").update(bytes).digest("hex");const target=join(options.dataDir,"runtime",digest.slice(0,16),name);const current=existsSync(target)?createHash("sha256").update(readFileSync(target)).digest("hex"):"";if(current!==digest){mkdirSync(dirname(target),{recursive:true});const temporary=`${target}.${process.pid}`;writeFileSync(temporary,bytes,{mode:493});renameSync(temporary,target)}if(platform!=="win32")chmodSync(target,493);return target}async function waitForExit(pid,timeoutMs=15000){const until=Date.now()+timeoutMs;while(isAlive(pid)&&Date.now()<until)await Bun.sleep(100)}function defaultArgv(){return process.argv.slice(2)}function spawnCraft(command,env){const child=Bun.spawn(command,{env:{...process.env,...env},stdio:["ignore","inherit","pipe"]});new Response(child.stderr).text().then((stderr)=>{const lines=stderr.split(`
2
+ `).filter((line)=>line.trim());if(lines.length)console.error(`[craft] ${lines.join(`
3
+ `)}`)});return{exited:child.exited,kill:()=>child.kill()}}export async function runWebviewApp(options){const{manifest}=options;const paths=options.paths??desktopAppPaths(manifest.appName);const tag=`[${manifest.appName}]`;if(options.logWhenDetached!==false)logToFileWhenDetached(paths.logFile);const launch=parseLaunchArguments(options.argv??defaultArgv(),manifest.urlSchemes);const incoming={args:launch.args,cwd:process.cwd(),...launch.url?{url:launch.url}:{}};const spawn=options.spawn??spawnCraft;if(launch.waitPid)await waitForExit(launch.waitPid);let runtime;try{runtime=resolveWebviewRuntime(manifest,{embedded:options.embeddedRuntime,dataDir:paths.dataDir});if(!existsSync(runtime))throw new Error(`the Craft runtime is missing: ${runtime}`)}catch(error){console.error(`${tag} could not start: ${error instanceof Error?error.message:String(error)}`);return 1}const lock=acquireWebviewInstance(paths.lockFile);if(!lock.acquired){const reached=await forwardToInstance(paths.lockFile,incoming);if((options.platform??process.platform)!=="darwin"&&manifest.runtimeFlags?.includes("--single-instance"))await spawn(craftWindowCommand(manifest,runtime,"about:blank",incoming),{}).exited.catch(()=>0);console.log(reached?`${tag} already running; handed over`:`${tag} already running`);return 0}applyWidenedPath();let module={};let agent;let updater;try{module=options.module?agentModuleOf(await options.module()):{};if(manifest.updates){updater=createDesktopUpdater({appName:manifest.appName,currentVersion:manifest.version,feedUrl:manifest.updates.feedUrl,trustedKeys:manifest.updates.publicKeys,channel:manifest.updates.channel,updatesDir:paths.updatesDir,beforeUpdate:module.beforeUpdate})}const answerUpdate=updater?updateRequestHandler(updater):undefined;agent=await startWebviewAgent({appName:manifest.appName,version:manifest.version,views:options.views,port:manifest.port,portFile:paths.portFile,dataDir:paths.dataDir,publicPaths:manifest.publicPaths,instanceSecret:lock.record.secret,handler:async(request,context)=>await answerUpdate?.(request)??module.fetch?.(request,context),onSecondInstance:(next)=>module.secondInstance?.(next)});publishInstancePort(paths.lockFile,lock.record,agent.port);await module.start?.({appName:manifest.appName,version:manifest.version,origin:agent.origin,port:agent.port,dataDir:paths.dataDir,launch:incoming,...updater?{updater}:{}})}catch(error){console.error(`${tag} could not start: ${error instanceof Error?error.stack??error.message:String(error)}`);releaseWebviewInstance(paths.lockFile);return 1}options.onAgent?.(agent);console.log(`${tag} ${manifest.version} serving on ${agent.origin}`);const window=spawn(craftWindowCommand(manifest,runtime,agent.launchUrl(manifest.startPath),incoming),{CRAFT_RELAUNCH_EXECUTABLE:process.execPath,CRAFT_RELAUNCH_ARGS:JSON.stringify([...process.execPath.endsWith("bun")||process.execPath.endsWith("bun.exe")?[process.argv[1]??""]:[],`${WAIT_PID_FLAG}${process.pid}`])});const hours=manifest.updates?.checkEveryHours??24;let timer;if(updater&&hours>0){const check=()=>{updater.check().catch(()=>{})};agent.windowReady.then(check);timer=setInterval(check,hours*3600000);timer.unref?.()}let stopped=false;const stop=async()=>{if(stopped)return;stopped=true;if(timer)clearInterval(timer);window.kill();try{await module.stop?.()}catch(error){console.error(`${tag} stop: ${error instanceof Error?error.message:String(error)}`)}agent.stop();releaseWebviewInstance(paths.lockFile)};const signals=process.platform==="win32"?["SIGINT","SIGTERM"]:["SIGTERM","SIGINT","SIGHUP"];const onSignal=()=>{stop().then(()=>process.exit(0))};for(const signal of signals)process.on(signal,onSignal);const code=await window.exited;console.log(`${tag} window closed (${code})`);for(const signal of signals)process.off(signal,onSignal);await stop();await updater?.relaunchIfInstalled();return 0}export function renderWebviewEntry(options){const launcher=options.launcherModule??fileURLToPath(import.meta.url);const files=Object.entries(options.viewFiles??{});const imports=files.map(([,file],index)=>`import view${index} from ${JSON.stringify(file)} with { type: 'file' }`);if(options.embeddedRuntime)imports.push(`import embeddedRuntime from ${JSON.stringify(options.embeddedRuntime)} with { type: 'file' }`);const views=options.stxViews?`{ kind: 'stx', ...${JSON.stringify(options.stxViews)} }`:files.length?`{ kind: 'embedded', files: {
4
+ ${files.map(([path],index)=>` ${JSON.stringify(path)}: view${index},`).join(`
5
+ `)}
6
+ } }`:`{ kind: 'none' }`;return`// Written by buddy build:desktop and buddy dev:desktop (desktop.webview). Do not edit.
7
+ import process from 'node:process'
8
+ import { runWebviewApp } from ${JSON.stringify(launcher)}
9
+ ${imports.join(`
10
+ `)}
11
+
12
+ process.exit(await runWebviewApp({
13
+ manifest: ${JSON.stringify(options.manifest,null,2).replace(/\n/g,`
14
+ `)},
15
+ views: ${views},
16
+ module: ${options.agentEntry?`() => import(${JSON.stringify(options.agentEntry)})`:"undefined"},${options.embeddedRuntime?`
17
+ embeddedRuntime,`:""}
18
+ }))
19
+ `}export function webviewAgentEntry(root,entry){if(entry){const file=isAbsolute(entry)?entry:resolve(root,entry);if(!existsSync(file))throw new Error(`desktop.webview.agent.entry does not exist: ${file}`);return file}const conventional=join(root,"app/Desktop/Agent.ts");return existsSync(conventional)?conventional:undefined}export function copyExecutable(from,to){mkdirSync(dirname(to),{recursive:true});copyFileSync(from,to);if(process.platform!=="win32")chmodSync(to,493)}
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.544",
5
+ "version": "0.75.548",
6
6
  "description": "Build and launch Craft desktop applications for Stacks",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -73,15 +73,17 @@
73
73
  "prepublishOnly": "bun run build"
74
74
  },
75
75
  "dependencies": {
76
- "@stacksjs/config": "0.75.544",
77
- "@stacksjs/router": "0.75.544",
78
- "@stacksjs/server": "0.75.544",
76
+ "@stacksjs/config": "0.75.548",
77
+ "@stacksjs/router": "0.75.548",
78
+ "@stacksjs/server": "0.75.548",
79
+ "@stacksjs/storage": "0.75.548",
79
80
  "craft-native": ">=0.0.497"
80
81
  },
81
82
  "peerDependencies": {
82
- "@stacksjs/config": "0.75.544",
83
- "@stacksjs/router": "0.75.544",
84
- "@stacksjs/server": "0.75.544"
83
+ "@stacksjs/config": "0.75.548",
84
+ "@stacksjs/router": "0.75.548",
85
+ "@stacksjs/server": "0.75.548",
86
+ "@stacksjs/storage": "0.75.548"
85
87
  },
86
88
  "peerDependenciesMeta": {
87
89
  "@stacksjs/config": {
@@ -92,10 +94,13 @@
92
94
  },
93
95
  "@stacksjs/server": {
94
96
  "optional": true
97
+ },
98
+ "@stacksjs/storage": {
99
+ "optional": true
95
100
  }
96
101
  },
97
102
  "devDependencies": {
98
- "@stacksjs/build": "0.75.544",
103
+ "@stacksjs/build": "0.75.548",
99
104
  "better-dx": "^0.2.24"
100
105
  }
101
106
  }