@stacksjs/desktop-build 0.75.735 → 0.75.762
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/craft-runtime.d.ts +5 -2
- package/dist/craft-runtime.js +1 -1
- package/dist/update-feed.d.ts +13 -5
- package/dist/update-feed.js +2 -2
- package/dist/update-signing.d.ts +3 -0
- package/dist/update-signing.js +1 -1
- package/package.json +11 -11
package/dist/craft-runtime.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import type { DesktopTargetName } from '@stacksjs/types';
|
|
2
2
|
/** The archive Craft publishes for a target, or null when it publishes none. */
|
|
3
3
|
export declare function craftRuntimeAsset(target: DesktopTargetName): string | null;
|
|
4
|
-
/** The runtime's file name inside
|
|
5
|
-
export declare function craftRuntimeBinaryName(target: DesktopTargetName): string;
|
|
4
|
+
/** The runtime profile's file name inside the archive. */
|
|
5
|
+
export declare function craftRuntimeBinaryName(target: DesktopTargetName, profile?: CraftRuntimeProfile): string;
|
|
6
6
|
/**
|
|
7
7
|
* The companions found beside a Windows runtime that the app does not
|
|
8
8
|
* already name, so a build includes `WebView2Loader.dll` without being told.
|
|
@@ -40,6 +40,7 @@ export declare interface CraftReleaseManifest {
|
|
|
40
40
|
export declare interface FetchCraftRuntimeOptions {
|
|
41
41
|
target: DesktopTargetName
|
|
42
42
|
version: string
|
|
43
|
+
profile?: CraftRuntimeProfile
|
|
43
44
|
directory: string
|
|
44
45
|
fetcher?: (url: string) => Promise<Response>
|
|
45
46
|
unpack?: (archive: string, directory: string) => void
|
|
@@ -50,3 +51,5 @@ export declare interface CraftRuntime {
|
|
|
50
51
|
version: string
|
|
51
52
|
fetched: boolean
|
|
52
53
|
}
|
|
54
|
+
declare type CraftRuntimeProfile = 'full' | 'webview';
|
|
55
|
+
export {};
|
package/dist/craft-runtime.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash}from"node:crypto";import{existsSync,mkdirSync,readdirSync,readFileSync,renameSync,rmSync,writeFileSync}from"node:fs";import{dirname,join}from"node:path";export const CRAFT_RELEASE_REPOSITORY="craft-native/craft";export function craftRuntimeAsset(target){const names={"darwin-arm64":"craft-darwin-arm64.zip","darwin-x64":"craft-darwin-x64.zip","linux-x64":"craft-linux-x64.zip","win32-x64":"craft-windows-x64.zip"};return names[target]??null}export function craftRuntimeBinaryName(target){return target.startsWith("win32-")
|
|
1
|
+
import{createHash}from"node:crypto";import{existsSync,mkdirSync,readdirSync,readFileSync,renameSync,rmSync,writeFileSync}from"node:fs";import{dirname,join}from"node:path";export const CRAFT_RELEASE_REPOSITORY="craft-native/craft";export function craftRuntimeAsset(target){const names={"darwin-arm64":"craft-darwin-arm64.zip","darwin-x64":"craft-darwin-x64.zip","linux-x64":"craft-linux-x64.zip","win32-x64":"craft-windows-x64.zip"};return names[target]??null}export function craftRuntimeBinaryName(target,profile="full"){const name=profile==="webview"?"craft-webview":"craft";return target.startsWith("win32-")?`${name}.exe`:name}export const WINDOWS_RUNTIME_COMPANIONS=["WebView2Loader.dll"];export function windowsRuntimeCompanions(runtime,alreadyNamed=[]){const named=new Set(alreadyNamed.map((file)=>file.split(/[\\/]/).pop().toLowerCase()));return WINDOWS_RUNTIME_COMPANIONS.filter((name)=>!named.has(name.toLowerCase())).map((name)=>join(dirname(runtime),name)).filter((file)=>existsSync(file))}export function parseCraftReleaseManifest(text,tag){let parsed;try{parsed=JSON.parse(text)}catch{throw new Error(`Craft ${tag}: release-manifest.json is not JSON`)}const manifest=parsed;if(manifest?.tag!==tag)throw new Error(`Craft ${tag}: release-manifest.json is for ${String(manifest?.tag)}`);if(!Array.isArray(manifest.assets))throw new Error(`Craft ${tag}: release-manifest.json lists no assets`);for(const asset of manifest.assets){if(typeof asset?.name!=="string"||!Number.isSafeInteger(asset.size)||typeof asset.sha256!=="string"||!/^[0-9a-f]{64}$/.test(asset.sha256))throw new Error(`Craft ${tag}: release-manifest.json has an asset without a name, size and SHA-256`)}return manifest}function unpackArchive(archive,directory){const attempts=[["unzip","-oq",archive,"-d",directory],["tar","-xf",archive,"-C",directory]];let failure="";for(const command of attempts){try{const result=Bun.spawnSync(command,{stdout:"ignore",stderr:"pipe"});if(result.exitCode===0)return;failure=result.stderr.toString().trim()||`${command[0]} exited with ${result.exitCode}`}catch(error){failure=error instanceof Error?error.message:String(error)}}throw new Error(`Could not unpack ${archive}: ${failure}`)}export async function fetchCraftRuntime(options){const{target,directory}=options;const version=options.version.replace(/^v/,"");if(!/^\d+\.\d+\.\d+(?:-[\w.]+)?$/.test(version))throw new Error(`Not a Craft version: ${options.version}`);const tag=`v${version}`;const asset=craftRuntimeAsset(target);if(!asset)throw new Error(`Craft publishes no runtime for ${target}. Build one there and name it in desktop.webview.runtime['${target}'].`);const binaryName=craftRuntimeBinaryName(target,options.profile);const binary=join(directory,binaryName);const stamp=join(directory,".craft-version");if(existsSync(binary)&&existsSync(stamp)&&readFileSync(stamp,"utf8").split(" ")[0]===tag)return{binary,version,fetched:false};const fetcher=options.fetcher??((url)=>fetch(url));const base=`https://github.com/${CRAFT_RELEASE_REPOSITORY}/releases/download/${tag}`;const get=async(name)=>{const url=`${base}/${name}`;options.onFetch?.(url);let response;try{response=await fetcher(url)}catch(error){throw new Error(`Could not download ${url}: ${error instanceof Error?error.message:String(error)}`)}if(!response.ok)throw new Error(`Could not download ${url}: HTTP ${response.status}`);return response};const manifest=parseCraftReleaseManifest(await(await get("release-manifest.json")).text(),tag);const listed=manifest.assets.find((entry)=>entry.name===asset);if(!listed)throw new Error(`Craft ${tag} lists no ${asset} in its release manifest.`);const bytes=new Uint8Array(await(await get(asset)).arrayBuffer());const sha256=createHash("sha256").update(bytes).digest("hex");if(bytes.byteLength!==listed.size||sha256!==listed.sha256)throw new Error(`${asset} from Craft ${tag} is not the published file: got ${bytes.byteLength} bytes, sha256 ${sha256}; the release manifest says ${listed.size} bytes, sha256 ${listed.sha256}.`);const staging=`${directory}.fetching`;rmSync(staging,{recursive:true,force:true});mkdirSync(staging,{recursive:true});try{const archive=join(staging,asset);writeFileSync(archive,bytes);(options.unpack??unpackArchive)(archive,staging);rmSync(archive,{force:true});if(!existsSync(join(staging,binaryName)))throw new Error(`${asset} from Craft ${tag} has no ${binaryName} inside (it has: ${readdirSync(staging).join(", ")||"nothing"}).`);writeFileSync(join(staging,".craft-version"),`${tag} ${sha256}`);rmSync(directory,{recursive:true,force:true});mkdirSync(dirname(directory),{recursive:true});renameSync(staging,directory)}finally{rmSync(staging,{recursive:true,force:true})}return{binary,version,fetched:true}}export function installedCraftVersion(root){for(const from of[root,import.meta.dir]){try{let folder=dirname(Bun.resolveSync("craft-native",from));for(let depth=0;depth<6;depth++,folder=dirname(folder)){const file=join(folder,"package.json");if(!existsSync(file))continue;const pkg=JSON.parse(readFileSync(file,"utf8"));if(pkg.name==="craft-native"&&pkg.version)return pkg.version}}catch{}}return null}
|
package/dist/update-feed.d.ts
CHANGED
|
@@ -28,11 +28,11 @@ export declare function sliceStream(source: ReadableStream<Uint8Array>, start: n
|
|
|
28
28
|
* only when neither is known.
|
|
29
29
|
*/
|
|
30
30
|
export declare function publishedArtifactUrl(options: UpdateLocation & { store: UpdateStore, artifactBaseUrl?: string, feedUrl?: string }, version: string, fileName: string): Promise<string>;
|
|
31
|
-
/**
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
*/
|
|
31
|
+
/** Describe and sign one update without writing to the destination. */
|
|
32
|
+
export declare function prepareDesktopUpdateManifest(options: PublishDesktopUpdateOptions): Promise<DesktopUpdateManifest>;
|
|
33
|
+
/** Verify staged bytes and their original signature before writing the artifact and then its manifest. */
|
|
34
|
+
export declare function publishPreparedDesktopUpdate(options: PublishPreparedDesktopUpdateOptions): Promise<DesktopUpdateManifest>;
|
|
35
|
+
/** Prepare and publish one update in a single call. */
|
|
36
36
|
export declare function publishDesktopUpdate(options: PublishDesktopUpdateOptions): Promise<DesktopUpdateManifest>;
|
|
37
37
|
/**
|
|
38
38
|
* Answer an app asking for its update: the stored manifest, 204 when the app
|
|
@@ -126,6 +126,14 @@ export declare interface PublishDesktopUpdateOptions extends UpdateLocation {
|
|
|
126
126
|
feedUrl?: string
|
|
127
127
|
publishedAt?: string
|
|
128
128
|
}
|
|
129
|
+
export declare interface PublishPreparedDesktopUpdateOptions extends UpdateLocation {
|
|
130
|
+
store: UpdateStore
|
|
131
|
+
artifact: string
|
|
132
|
+
manifest: DesktopUpdateManifest
|
|
133
|
+
trustedKeys: Record<string, string>
|
|
134
|
+
artifactBaseUrl?: string
|
|
135
|
+
feedUrl?: string
|
|
136
|
+
}
|
|
129
137
|
export declare interface ServeUpdateArtifactOptions {
|
|
130
138
|
store: UpdateStore
|
|
131
139
|
prefix?: string
|
package/dist/update-feed.js
CHANGED
|
@@ -1,2 +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[\w.+-]*$/.test(version)||!/^\w[\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 function updateArtifactUrl(feedUrl,location,version,fileName){const key=updateArtifactKey({...location,prefix:""},version,fileName);return`${feedUrl.replace(/\/+$/,"")}/files/${key.replace(/^\/+/,"").split("/").map(encodeURIComponent).join("/")}`}export function artifactUrlProblem(url){let parsed;try{parsed=new URL(url)}catch{return`${url} is not a URL`}if(parsed.protocol!=="https:"&&parsed.protocol!=="http:")return`${url} is not an http(s) URL`;const host=parsed.hostname.toLowerCase().replace(/^\[|\]$/g,"");const local=host==="localhost"||host.endsWith(".localhost")||host.endsWith(".test")||host.endsWith(".local")||host==="::1"||host==="0.0.0.0"||/^127\./.test(host);return local?`${url} is on this machine (${host}): no installed app could download it`:null}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),open:async(key)=>{if(!await adapter.fileExists(key))return null;const size=await adapter.fileSize(key);return{size,stream:async(range)=>{const whole=typeof adapter.getStream==="function"?await adapter.getStream(key):new Blob([await adapter.readToUint8Array(key)]).stream();return range?sliceStream(whole,range.start,range.end):whole}}}}}export function sliceStream(source,start,end){const reader=source.getReader();let offset=0;return new ReadableStream({async pull(controller){while(true){if(offset>end){await reader.cancel();controller.close();return}const{done,value}=await reader.read();if(done){controller.close();return}const from=Math.max(start-offset,0);const to=Math.min(end+1-offset,value.byteLength);offset+=value.byteLength;if(to>from){controller.enqueue(value.subarray(from,to));return}}},cancel:(reason)=>reader.cancel(reason)})}export async function publishedArtifactUrl(options,version,fileName){const key=updateArtifactKey(options,version,fileName);if(options.artifactBaseUrl)return`${options.artifactBaseUrl.replace(/\/+$/,"")}/${key.split("/").map(encodeURIComponent).join("/")}`;if(options.feedUrl)return updateArtifactUrl(options.feedUrl,options,version,fileName);return options.store.publicUrl(key)}export async function
|
|
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})}const artifactTypes={zip:"application/zip",dmg:"application/x-apple-diskimage",msi:"application/x-msi",exe:"application/vnd.microsoft.portable-executable",appimage:"application/vnd.appimage",deb:"application/vnd.debian.binary-package",rpm:"application/x-rpm"};function refused(status,error,headers={}){return new Response(JSON.stringify({error}),{status,headers:{...feedHeaders,...headers}})}export function parseByteRange(header,size){if(!header)return null;const match=/^bytes=(\d*)-(\d*)$/.exec(header.trim());if(!match||!match[1]&&!match[2])return null;if(!match[1]){const last=Number(match[2]);if(!last||!size)return false;return{start:Math.max(size-last,0),end:size-1}}const start=Number(match[1]);const end=match[2]?Math.min(Number(match[2]),size-1):size-1;if(start>=size||start>end)return false;return{start,end}}export async function serveUpdateArtifact(options){const missing=()=>refused(404,"No such release artifact.");const split=/^([a-z0-9]+)-([a-z0-9_]+)$/.exec(options.target);if(!split)return missing();let key;try{key=updateArtifactKey({platform:split[1],architecture:split[2],channel:options.channel,prefix:options.prefix},options.version,options.file)}catch{return missing()}if(!options.store.open)return missing();const stored=await options.store.open(key);if(!stored)return missing();const range=parseByteRange(options.range,stored.size);if(range===false)return refused(416,"The requested range is outside the file.",{"content-range":`bytes */${stored.size}`});const length=range?range.end-range.start+1:stored.size;const headers={"content-type":artifactTypes[options.file.slice(options.file.lastIndexOf(".")+1).toLowerCase()]??"application/octet-stream","content-length":String(length),"content-disposition":`attachment; filename="${options.file}"`,"accept-ranges":"bytes","cache-control":"public, max-age=31536000, immutable","x-content-type-options":"nosniff"};if(range)headers["content-range"]=`bytes ${range.start}-${range.end}/${stored.size}`;const body=options.method?.toUpperCase()==="HEAD"?null:await stored.stream(range??undefined);return new Response(body,{status:range?206:200,headers})}export function selectDesktopUpdates(config,app){if(app)return config?.[app]?.updates;return config?.webview?.updates??config?.macos?.updates}export function desktopUpdatesCollision(config){const webview=config.webview?.updates;const macos=config.macos?.updates;if(!webview||!macos)return;const folder=(updates)=>(updates.prefix??DEFAULT_UPDATE_PREFIX).replace(/^\/+|\/+$/g,"");if((webview.disk??"")!==(macos.disk??"")||folder(webview)!==folder(macos))return;return`config/desktop.ts: webview.updates and macos.updates publish to the same folder (${folder(macos)}) on the same disk, where each app's release would replace the other's. Give one of them its own \`prefix\`.`}async function projectUpdates(root,app){const file=join(root??process.cwd(),"config/desktop.ts");return existsSync(file)?selectDesktopUpdates((await import(pathToFileURL(file).href)).default,app):undefined}export async function answerUpdateArtifact(options){const updates=options.updates??(options.store?undefined:await projectUpdates(options.root,options.app));if(!updates&&!options.store)return refused(404,"This app publishes no desktop updates.");return serveUpdateArtifact({...options,store:options.store??await storageUpdateStore(updates?.disk),prefix:updates?.prefix})}export async function answerUpdateFeed(options){let updates=options.updates;if(!updates&&!options.store){updates=await projectUpdates(options.root,options.app);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})}export function releaseRecordKey(location){const channel=location.channel||"stable";if(!/^[a-z0-9][a-z0-9._-]*$/i.test(channel))throw new Error(`Invalid release channel: ${channel}`);return`${(location.prefix??DEFAULT_UPDATE_PREFIX).replace(/^\/+|\/+$/g,"")}/${channel}/release.json`}export function mergeReleaseRecord(stored,next){let previous=null;try{previous=stored?JSON.parse(stored):null}catch{previous=null}if(!previous||previous.version!==next.version||previous.channel!==next.channel||!Array.isArray(previous.targets))return next;const published=new Set(next.targets.map((item)=>item.target));const kept=previous.targets.filter((item)=>typeof item?.target==="string"&&item.update&&Array.isArray(item.downloads)&&!published.has(item.target));return{...next,targets:[...kept,...next.targets].sort((a,b)=>a.target.localeCompare(b.target))}}
|
|
1
|
+
import{createHash}from"node:crypto";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,updatePublicKey}from"./update-signing";import{compareVersions,validateUpdateManifest,verifyUpdateManifestSignature}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[\w.+-]*$/.test(version)||!/^\w[\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 function updateArtifactUrl(feedUrl,location,version,fileName){const key=updateArtifactKey({...location,prefix:""},version,fileName);return`${feedUrl.replace(/\/+$/,"")}/files/${key.replace(/^\/+/,"").split("/").map(encodeURIComponent).join("/")}`}export function artifactUrlProblem(url){let parsed;try{parsed=new URL(url)}catch{return`${url} is not a URL`}if(parsed.protocol!=="https:"&&parsed.protocol!=="http:")return`${url} is not an http(s) URL`;const host=parsed.hostname.toLowerCase().replace(/^\[|\]$/g,"");const local=host==="localhost"||host.endsWith(".localhost")||host.endsWith(".test")||host.endsWith(".local")||host==="::1"||host==="0.0.0.0"||/^127\./.test(host);return local?`${url} is on this machine (${host}): no installed app could download it`:null}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),open:async(key)=>{if(!await adapter.fileExists(key))return null;const size=await adapter.fileSize(key);return{size,stream:async(range)=>{const whole=typeof adapter.getStream==="function"?await adapter.getStream(key):new Blob([await adapter.readToUint8Array(key)]).stream();return range?sliceStream(whole,range.start,range.end):whole}}}}}export function sliceStream(source,start,end){const reader=source.getReader();let offset=0;return new ReadableStream({async pull(controller){while(true){if(offset>end){await reader.cancel();controller.close();return}const{done,value}=await reader.read();if(done){controller.close();return}const from=Math.max(start-offset,0);const to=Math.min(end+1-offset,value.byteLength);offset+=value.byteLength;if(to>from){controller.enqueue(value.subarray(from,to));return}}},cancel:(reason)=>reader.cancel(reason)})}export async function publishedArtifactUrl(options,version,fileName){const key=updateArtifactKey(options,version,fileName);if(options.artifactBaseUrl)return`${options.artifactBaseUrl.replace(/\/+$/,"")}/${key.split("/").map(encodeURIComponent).join("/")}`;if(options.feedUrl)return updateArtifactUrl(options.feedUrl,options,version,fileName);return options.store.publicUrl(key)}export async function prepareDesktopUpdateManifest(options){const{size,sha256}=await describeArtifact(options.artifact);const url=await publishedArtifactUrl(options,options.version,basename(options.artifact));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}:{}};return signUpdateManifest(unsigned,options.privateKey,options.keyId)}export async function publishPreparedDesktopUpdate(options){const manifest={...validateUpdateManifest(options.manifest)};verifyUpdateManifestSignature(manifest,options.trustedKeys);const fileName=basename(options.artifact);const artifactKey=updateArtifactKey(options,manifest.version,fileName);const manifestKey=updateManifestKey(options);const url=await publishedArtifactUrl(options,manifest.version,fileName);if(manifest.platform!==options.platform||manifest.architecture!==options.architecture||manifest.url!==url)throw new Error("The signed update does not match the publication destination.");const artifact=readFileSync(options.artifact);const sha256=createHash("sha256").update(artifact).digest("hex");if(artifact.length!==manifest.size||sha256!==manifest.sha256.toLowerCase())throw new Error("The update artifact does not match its signed size and SHA-256.");await options.store.write(artifactKey,artifact);await options.store.write(manifestKey,`${JSON.stringify(manifest,null,2)}
|
|
2
|
+
`);return manifest}export async function publishDesktopUpdate(options){const manifest=await prepareDesktopUpdateManifest(options);const trustedKeys={[manifest.signingKeyId]:updatePublicKey(options.privateKey)};return publishPreparedDesktopUpdate({...options,manifest,trustedKeys})}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})}const artifactTypes={zip:"application/zip",dmg:"application/x-apple-diskimage",msi:"application/x-msi",exe:"application/vnd.microsoft.portable-executable",appimage:"application/vnd.appimage",deb:"application/vnd.debian.binary-package",rpm:"application/x-rpm"};function refused(status,error,headers={}){return new Response(JSON.stringify({error}),{status,headers:{...feedHeaders,...headers}})}export function parseByteRange(header,size){if(!header)return null;const match=/^bytes=(\d*)-(\d*)$/.exec(header.trim());if(!match||!match[1]&&!match[2])return null;if(!match[1]){const last=Number(match[2]);if(!last||!size)return false;return{start:Math.max(size-last,0),end:size-1}}const start=Number(match[1]);const end=match[2]?Math.min(Number(match[2]),size-1):size-1;if(start>=size||start>end)return false;return{start,end}}export async function serveUpdateArtifact(options){const missing=()=>refused(404,"No such release artifact.");const split=/^([a-z0-9]+)-([a-z0-9_]+)$/.exec(options.target);if(!split)return missing();let key;try{key=updateArtifactKey({platform:split[1],architecture:split[2],channel:options.channel,prefix:options.prefix},options.version,options.file)}catch{return missing()}if(!options.store.open)return missing();const stored=await options.store.open(key);if(!stored)return missing();const range=parseByteRange(options.range,stored.size);if(range===false)return refused(416,"The requested range is outside the file.",{"content-range":`bytes */${stored.size}`});const length=range?range.end-range.start+1:stored.size;const headers={"content-type":artifactTypes[options.file.slice(options.file.lastIndexOf(".")+1).toLowerCase()]??"application/octet-stream","content-length":String(length),"content-disposition":`attachment; filename="${options.file}"`,"accept-ranges":"bytes","cache-control":"public, max-age=31536000, immutable","x-content-type-options":"nosniff"};if(range)headers["content-range"]=`bytes ${range.start}-${range.end}/${stored.size}`;const body=options.method?.toUpperCase()==="HEAD"?null:await stored.stream(range??undefined);return new Response(body,{status:range?206:200,headers})}export function selectDesktopUpdates(config,app){if(app)return config?.[app]?.updates;return config?.webview?.updates??config?.macos?.updates}export function desktopUpdatesCollision(config){const webview=config.webview?.updates;const macos=config.macos?.updates;if(!webview||!macos)return;const folder=(updates)=>(updates.prefix??DEFAULT_UPDATE_PREFIX).replace(/^\/+|\/+$/g,"");if((webview.disk??"")!==(macos.disk??"")||folder(webview)!==folder(macos))return;return`config/desktop.ts: webview.updates and macos.updates publish to the same folder (${folder(macos)}) on the same disk, where each app's release would replace the other's. Give one of them its own \`prefix\`.`}async function projectUpdates(root,app){const file=join(root??process.cwd(),"config/desktop.ts");return existsSync(file)?selectDesktopUpdates((await import(pathToFileURL(file).href)).default,app):undefined}export async function answerUpdateArtifact(options){const updates=options.updates??(options.store?undefined:await projectUpdates(options.root,options.app));if(!updates&&!options.store)return refused(404,"This app publishes no desktop updates.");return serveUpdateArtifact({...options,store:options.store??await storageUpdateStore(updates?.disk),prefix:updates?.prefix})}export async function answerUpdateFeed(options){let updates=options.updates;if(!updates&&!options.store){updates=await projectUpdates(options.root,options.app);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})}export function releaseRecordKey(location){const channel=location.channel||"stable";if(!/^[a-z0-9][a-z0-9._-]*$/i.test(channel))throw new Error(`Invalid release channel: ${channel}`);return`${(location.prefix??DEFAULT_UPDATE_PREFIX).replace(/^\/+|\/+$/g,"")}/${channel}/release.json`}export function mergeReleaseRecord(stored,next){let previous=null;try{previous=stored?JSON.parse(stored):null}catch{previous=null}if(!previous||previous.version!==next.version||previous.channel!==next.channel||!Array.isArray(previous.targets))return next;const published=new Set(next.targets.map((item)=>item.target));const kept=previous.targets.filter((item)=>typeof item?.target==="string"&&item.update&&Array.isArray(item.downloads)&&!published.has(item.target));return{...next,targets:[...kept,...next.targets].sort((a,b)=>a.target.localeCompare(b.target))}}
|
package/dist/update-signing.d.ts
CHANGED
|
@@ -15,6 +15,9 @@ export declare function isUpdatePublicKey(encoded: string): boolean;
|
|
|
15
15
|
export declare function desktopUpdatesProblems(updates: DesktopUpdatesConfig, key: string, options?: { decodeKeys?: boolean }): string[];
|
|
16
16
|
/** Sign a manifest. The result is verified against the key's own public half before it is returned. */
|
|
17
17
|
export declare function signUpdateManifest(unsigned: UnsignedUpdateManifest, privateKey: string, keyId?: string): DesktopUpdateManifest;
|
|
18
|
+
/** Sign the staged release index separately from the manifest an app installs. */
|
|
19
|
+
export declare function signDesktopReleaseIndex(index: string, keyId: string, privateKey: string): string;
|
|
20
|
+
export declare function verifyDesktopReleaseIndex(index: string, keyId: string, signature: string, trustedKeys: Record<string, string>): void;
|
|
18
21
|
/** A file's size and SHA-256, read as a stream: an installer is too large to hold twice. */
|
|
19
22
|
export declare function describeArtifact(file: string): Promise<{ size: number, sha256: string }>;
|
|
20
23
|
/**
|
package/dist/update-signing.js
CHANGED
|
@@ -1 +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 isUpdatePublicKey(encoded){if(typeof encoded!=="string"||!encoded.startsWith(UPDATE_PUBLIC_PREFIX))return false;try{return createPublicKey({key:Buffer.from(encoded.slice(UPDATE_PUBLIC_PREFIX.length),"base64url"),format:"der",type:"spki"}).asymmetricKeyType==="ed25519"}catch{return false}}export function desktopUpdatesProblems(updates,key,options={}){const errors=[];try{const url=new URL(updates.feedUrl);if(url.protocol!=="https:"&&!["localhost","127.0.0.1"].includes(url.hostname))errors.push(`${key}.feedUrl must be https`)}catch{errors.push(`${key}.feedUrl is not a URL (got ${JSON.stringify(updates.feedUrl)})`)}const keys=Object.entries(updates.publicKeys??{});if(!keys.length)errors.push(`${key}.publicKeys needs at least one key (run \`buddy desktop:update:keypair\`)`);for(const[id,value]of keys){if(typeof value!=="string"||!value.startsWith(UPDATE_PUBLIC_PREFIX))errors.push(`${key}.publicKeys.${id} is not a public key (it starts with ${UPDATE_PUBLIC_PREFIX})`);else if(options.decodeKeys&&!isUpdatePublicKey(value))errors.push(`${key}.publicKeys.${id} is not a readable Ed25519 public key: paste the one \`buddy desktop:update:keypair\` printed, whole`)}if(updates.checkEveryHours!==undefined&&!(Number.isFinite(updates.checkEveryHours)&&updates.checkEveryHours>=0))errors.push(`${key}.checkEveryHours must be a number of hours, or 0 to turn the automatic check off`);return errors}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")}}
|
|
1
|
+
import{createHash,createPrivateKey,createPublicKey,generateKeyPairSync,sign,verify}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 isUpdatePublicKey(encoded){if(typeof encoded!=="string"||!encoded.startsWith(UPDATE_PUBLIC_PREFIX))return false;try{return createPublicKey({key:Buffer.from(encoded.slice(UPDATE_PUBLIC_PREFIX.length),"base64url"),format:"der",type:"spki"}).asymmetricKeyType==="ed25519"}catch{return false}}export function desktopUpdatesProblems(updates,key,options={}){const errors=[];try{const url=new URL(updates.feedUrl);if(url.protocol!=="https:"&&!["localhost","127.0.0.1"].includes(url.hostname))errors.push(`${key}.feedUrl must be https`)}catch{errors.push(`${key}.feedUrl is not a URL (got ${JSON.stringify(updates.feedUrl)})`)}const keys=Object.entries(updates.publicKeys??{});if(!keys.length)errors.push(`${key}.publicKeys needs at least one key (run \`buddy desktop:update:keypair\`)`);for(const[id,value]of keys){if(typeof value!=="string"||!value.startsWith(UPDATE_PUBLIC_PREFIX))errors.push(`${key}.publicKeys.${id} is not a public key (it starts with ${UPDATE_PUBLIC_PREFIX})`);else if(options.decodeKeys&&!isUpdatePublicKey(value))errors.push(`${key}.publicKeys.${id} is not a readable Ed25519 public key: paste the one \`buddy desktop:update:keypair\` printed, whole`)}if(updates.checkEveryHours!==undefined&&!(Number.isFinite(updates.checkEveryHours)&&updates.checkEveryHours>=0))errors.push(`${key}.checkEveryHours must be a number of hours, or 0 to turn the automatic check off`);return errors}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 function signDesktopReleaseIndex(index,keyId,privateKey){return sign(null,releaseIndexPayload(index,keyId),privateKeyObject(privateKey)).toString("base64url")}export function verifyDesktopReleaseIndex(index,keyId,signature,trustedKeys){const encoded=Object.hasOwn(trustedKeys,keyId)?trustedKeys[keyId]:undefined;if(!encoded?.startsWith(UPDATE_PUBLIC_PREFIX))throw new Error("Desktop release index signing key is not trusted.");const key=createPublicKey({key:Buffer.from(encoded.slice(UPDATE_PUBLIC_PREFIX.length),"base64url"),format:"der",type:"spki"});const bytes=Buffer.from(signature,"base64url");if(key.asymmetricKeyType!=="ed25519"||bytes.length!==64||!verify(null,releaseIndexPayload(index,keyId),key,bytes))throw new Error("Desktop release index signature verification failed.")}function releaseIndexPayload(index,keyId){return Buffer.from(JSON.stringify(["stacks-desktop-release-index-v1",keyId,index]),"utf8")}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/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/desktop-build",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.762",
|
|
6
6
|
"description": "Build and launch Craft desktop applications for Stacks",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -73,17 +73,17 @@
|
|
|
73
73
|
"prepublishOnly": "bun run build"
|
|
74
74
|
},
|
|
75
75
|
"dependencies": {
|
|
76
|
-
"@stacksjs/config": "0.75.
|
|
77
|
-
"@stacksjs/router": "0.75.
|
|
78
|
-
"@stacksjs/server": "0.75.
|
|
79
|
-
"@stacksjs/storage": "0.75.
|
|
76
|
+
"@stacksjs/config": "0.75.762",
|
|
77
|
+
"@stacksjs/router": "0.75.762",
|
|
78
|
+
"@stacksjs/server": "0.75.762",
|
|
79
|
+
"@stacksjs/storage": "0.75.762",
|
|
80
80
|
"craft-native": ">=0.0.505"
|
|
81
81
|
},
|
|
82
82
|
"peerDependencies": {
|
|
83
|
-
"@stacksjs/config": "0.75.
|
|
84
|
-
"@stacksjs/router": "0.75.
|
|
85
|
-
"@stacksjs/server": "0.75.
|
|
86
|
-
"@stacksjs/storage": "0.75.
|
|
83
|
+
"@stacksjs/config": "0.75.762",
|
|
84
|
+
"@stacksjs/router": "0.75.762",
|
|
85
|
+
"@stacksjs/server": "0.75.762",
|
|
86
|
+
"@stacksjs/storage": "0.75.762"
|
|
87
87
|
},
|
|
88
88
|
"peerDependenciesMeta": {
|
|
89
89
|
"@stacksjs/config": {
|
|
@@ -100,7 +100,7 @@
|
|
|
100
100
|
}
|
|
101
101
|
},
|
|
102
102
|
"devDependencies": {
|
|
103
|
-
"@stacksjs/build": "0.75.
|
|
104
|
-
"better-dx": "^0.2.
|
|
103
|
+
"@stacksjs/build": "0.75.762",
|
|
104
|
+
"better-dx": "^0.2.42"
|
|
105
105
|
}
|
|
106
106
|
}
|