An open-source, self-hosted system for apps built with web technologies.
Every file reaches production through the build: the server imports its assets with ?url, Vite carries them, the pack ships dist alone
zohayrslileh6414c5c48531
diff --git a/scripts/pack.ts b/scripts/pack.tsindex 5fb0374..cace586 100644--- a/scripts/pack.ts+++ b/scripts/pack.ts@@ -1,4 +1,4 @@-import { readFileSync, readdirSync, writeFileSync } from "node:fs"+import { readFileSync, writeFileSync } from "node:fs"import { name, version } from "@/package.json"import { createHash } from "node:crypto"import { resolve } from "node:path"@@ -7,21 +7,9 @@ import AdmZip from "adm-zip"const archive = `${name}@${version}.zip`const zip = new AdmZip()+// Every file the System needs reaches the build through an import.zip.addLocalFolder(resolve("dist"))-// Bundled assets already live in each consumer's build output. Everything-// else retains its filesystem identity and therefore accompanies the build.-for (const asset of readdirSync(resolve("assets"), { withFileTypes: true })) {-- if (asset.name === "bundled" || asset.name.startsWith(".")) continue-- const source = resolve("assets", asset.name)-- if (asset.isDirectory()) zip.addLocalFolder(source, `assets/${asset.name}`)-- else if (asset.isFile()) zip.addLocalFile(source, "assets")-}-zip.writeZip(resolve(archive))const checksum = createHash("sha256").update(readFileSync(resolve(archive))).digest("hex")diff --git a/source/server/core/application.ts b/source/server/core/application.tsindex c6e6b2b..872614c 100644--- a/source/server/core/application.ts+++ b/source/server/core/application.ts@@ -1,7 +1,7 @@import LinkManager from "./link-manager/link-manager"import Authentication from "./authentication/authentication"import FileManager from "@libs/file-manager"-import UploadManager from "./upload-manager"+import UploadManager, { type SystemFiles } from "./upload-manager"import AppearanceManager from "./appearance-manager"import openStore from "./open-store"import Keyv from "keyv"@@ -66,8 +66,8 @@ export default class Application {this.system = new System(this)}- /** `wallpapers` is the directory of the wallpapers the System comes with, named by their upload keys. */- public static async initialize(homePath: string, icons: ApplicationIcons, wallpapers: string) {+ /** `wallpapers` holds the file behind each upload key the System keeps for its own wallpapers. */+ public static async initialize(homePath: string, icons: ApplicationIcons, wallpapers: SystemFiles) {const storage = new FileManager(homePath)diff --git a/source/server/core/upload-manager.ts b/source/server/core/upload-manager.tsindex f141b4c..aabc3d2 100644--- a/source/server/core/upload-manager.ts+++ b/source/server/core/upload-manager.ts@@ -1,15 +1,17 @@-import { createReadStream, createWriteStream, existsSync, lstatSync, mkdirSync, readdirSync } from "node:fs"+import { createReadStream, createWriteStream, lstatSync, mkdirSync } from "node:fs"import FileManager from "@libs/file-manager"import { rename, rm } from "node:fs/promises"import { randomUUID } from "node:crypto"import { Readable } from "node:stream"import { pipeline } from "node:stream/promises"import { type ReadableStream as NodeReadableStream } from "node:stream/web"-import { join } from "node:path"import { isSystemUploadFile, isUploadFile, type FileStat } from "@phreshos/core"export const uploadLimit = 1024 * 1024 * 1024+/** The path of the file behind each upload key the System keeps. */+export type SystemFiles = Readonly<Record<string, string>>+export class MissingUploadValueError extends Error {public constructor() {@@ -35,37 +37,25 @@ export class UploadTooLargeError extends Error {* interruption and refusal remove the temporary file.** The keys the System keeps for its own wallpapers read the files it comes- * with instead, so each release shows its own pictures behind them. Each- * such file is named by its key, with the extension of its format.+ * with instead, so each release shows its own pictures behind them.*/export default class UploadManager {public readonly fileManager: FileManager- private readonly systemFiles: ReadonlyMap<string, string>-- public constructor(fileManager: FileManager, public readonly systemPath: string) {+ /** `systemFiles` holds the file behind each key the System keeps. */+ public constructor(fileManager: FileManager, private readonly systemFiles: SystemFiles) {this.fileManager = fileManagermkdirSync(fileManager.path, { recursive: true })-- const named = existsSync(systemPath) ? readdirSync(systemPath) : []-- this.systemFiles = new Map(named.map(name => [name.replace(/\.[^.]+$/, ""), name]))- }-- /** The file the System comes with behind one of its own keys, by its name in `systemPath`. */- public systemFile(file: string) {-- return this.systemFiles.get(file) ?? file}public path(file: string) {if (!isUploadFile(file)) throw new Error("That is not an upload file")- return isSystemUploadFile(file) ? join(this.systemPath, this.systemFile(file)) : this.fileManager.join(file)+ return (isSystemUploadFile(file) ? this.systemFiles[file] : undefined) ?? this.fileManager.join(file)}public async write(extension: string, content: ReadableStream<Uint8Array> | null, signal?: AbortSignal) {diff --git a/source/server/view/http/uploads.ts b/source/server/view/http/uploads.tsindex ba1a61b..7391c54 100644--- a/source/server/view/http/uploads.ts+++ b/source/server/view/http/uploads.ts@@ -157,7 +157,7 @@ export default function (application: Application) {const uploaded = serveStatic({ root: application.uploads.fileManager.path, rewriteRequestPath: path => path.slice(doors.uploads.length + 1) })- const kept = serveStatic({ root: application.uploads.systemPath, rewriteRequestPath: path => application.uploads.systemFile(path.slice(doors.uploads.length + 1)) })+ const kept = serveStatic({ rewriteRequestPath: path => application.uploads.path(path.slice(doors.uploads.length + 1)) })uploads.use("/:file", (context, next) => (isSystemUploadFile(context.req.param("file")) ? kept : uploaded)(context, next))diff --git a/source/server/view/view.ts b/source/server/view/view.tsindex 990caa9..e6bfe9a 100644--- a/source/server/view/view.ts+++ b/source/server/view/view.ts@@ -12,7 +12,15 @@ import uploads from "./http/uploads"import link from "./http/link"import cfonts from "cfonts"import { Hono } from "hono"-import { resolve } from "node:path"+import { fileURLToPath } from "node:url"+import { join } from "node:path"+import { systemWallpapers } from "@phreshos/core"+import logo from "@/assets/logo.png?url"+import defaultIcon from "@/assets/default-icon.png?url"+import signInLightWallpaper from "@/assets/wallpapers/SIGN_IN_LIGHT_WALLPAPER.webp?url"+import signInDarkWallpaper from "@/assets/wallpapers/SIGN_IN_DARK_WALLPAPER.webp?url"+import desktopLightWallpaper from "@/assets/wallpapers/DESKTOP_LIGHT_WALLPAPER.webp?url"+import desktopDarkWallpaper from "@/assets/wallpapers/DESKTOP_DARK_WALLPAPER.webp?url"import { writeFile } from "node:fs/promises"import { styleText } from "node:util"import { listenOnPorts } from "./configuration"@@ -29,7 +37,12 @@ export default async function (config: Config) {font: "simple"})- const application = await Application.initialize(config.home, { system: resolve("assets/logo.png"), defaultProgram: resolve("assets/default-icon.png") }, resolve("assets/wallpapers"))+ const application = await Application.initialize(config.home, { system: assetFile(logo), defaultProgram: assetFile(defaultIcon) }, {+ [systemWallpapers.light.signIn]: assetFile(signInLightWallpaper),+ [systemWallpapers.dark.signIn]: assetFile(signInDarkWallpaper),+ [systemWallpapers.light.desktop]: assetFile(desktopLightWallpaper),+ [systemWallpapers.dark.desktop]: assetFile(desktopDarkWallpaper)+ })// One server, five doors, each at its own name. A program's client// is still not the API — it is files a browser reads, with no link,@@ -65,7 +78,7 @@ export default async function (config: Config) {const origin = `http://localhost:${port}`- await writeFile(resolve(application.storage.path, "desktop"), `${origin}\n`, { mode: 0o600 })+ await writeFile(join(application.storage.path, "desktop"), `${origin}\n`, { mode: 0o600 })const localGateway = await gateway(application.linkManager, gatewayAddress(application.storage.path))@@ -90,3 +103,12 @@ export interface Config {/** Ordered public port candidates. Omit to let the operating system assign one. */ports?: readonly number[]}++/**+ * The file on disk behind a `?url` import. Vite addresses it under `/@fs/` in development, and+ * beside the built server once built.+ */+function assetFile(url: string) {++ return url.startsWith("/@fs/") ? url.slice("/@fs".length) : fileURLToPath(new URL(`.${url}`, import.meta.url))+}diff --git a/tests/appearance.test.ts b/tests/appearance.test.tsindex bea7ddf..0ada801 100644--- a/tests/appearance.test.ts+++ b/tests/appearance.test.ts@@ -6,8 +6,9 @@ import FileManager from "@libs/file-manager"import UploadManager from "@server/core/upload-manager"import { mkdtemp, rm, truncate, writeFile } from "node:fs/promises"import { tmpdir } from "node:os"-import { join, resolve } from "node:path"+import { join } from "node:path"import { test } from "vitest"+import { systemFiles } from "./system-files"import { randomUUID } from "node:crypto"test("appearance contract", async () => {@@ -32,7 +33,7 @@ test("appearance contract", async () => {const store = new Keyv()const directory = await mkdtemp(join(tmpdir(), "phresh-appearance-"))- const uploads = new UploadManager(new FileManager(directory), resolve("assets/wallpapers"))+ const uploads = new UploadManager(new FileManager(directory), systemFiles)const manager = await AppearanceManager.open(store, uploads)assert.deepEqual(manager.value, defaultAppearance)diff --git a/tests/authentication-domains.test.ts b/tests/authentication-domains.test.tsindex 18ca8e9..4135d5d 100644--- a/tests/authentication-domains.test.ts+++ b/tests/authentication-domains.test.ts@@ -10,7 +10,7 @@ test("browser Connections and Sessions form one authoritative lifecycle", asyncconst application = await Application.initialize(home,{ system: join(home, "logo.png"), defaultProgram: join(home, "icon.png") },- join(home, "wallpapers")+ {})const link = new TheLink()const connection = application.linkManager.addConnection(link, "Chrome on macOS")diff --git a/tests/distribution.test.mjs b/tests/distribution.test.mjsindex 2365b44..cdb1d9b 100644--- a/tests/distribution.test.mjs+++ b/tests/distribution.test.mjs@@ -43,16 +43,20 @@ test("distribution contract", async () => {for (const required of ["package.json","server/main.js",- "client/index.html",- "assets/default-icon.png",- "assets/logo.png"+ "client/index.html"]) {assert(paths.has(required), `the distribution has no ${required}`)}+ // The files the server reads travel inside its build, under content-hashed names.+ for (const name of ["logo", "default-icon", "SIGN_IN_LIGHT_WALLPAPER", "SIGN_IN_DARK_WALLPAPER", "DESKTOP_LIGHT_WALLPAPER", "DESKTOP_DARK_WALLPAPER"]) {+ assert([...paths].some(path => path.startsWith(`server/assets/${name}-`)), `the server build carries no ${name}`)+ }+for (const path of paths) {assert(!path.startsWith("source/"), `TypeScript source entered the distribution: ${path}`)assert(!path.startsWith("storage/"), `runtime storage entered the distribution: ${path}`)+ assert(!path.startsWith("assets/"), `a source asset entered the distribution beside the build: ${path}`)assert(!path.startsWith("node_modules/"), `development dependencies entered the distribution: ${path}`)assert(!path.startsWith(".git"), `repository state entered the distribution: ${path}`)}@@ -125,6 +129,10 @@ test("distribution contract", async () => {runtime.stderr.on("data", data => output.push(data.toString()))await waitForDesktop(port, runtime, output)++ const wallpaper = await fetch(`http://localhost:${port}/uploads/DESKTOP_LIGHT_WALLPAPER`)+ assert.equal(wallpaper.status, 200, output.join(""))+ assert.equal(wallpaper.headers.get("content-type"), "image/webp")}async function waitForDesktop(port, child, output) {diff --git a/tests/link-request-routing.test.ts b/tests/link-request-routing.test.tsindex eec5fa0..e9b10ba 100644--- a/tests/link-request-routing.test.ts+++ b/tests/link-request-routing.test.ts@@ -11,7 +11,7 @@ import { test } from "vitest"test("an RPC result returns only to its requesting boundary", async () => {const home = await mkdtemp(join(tmpdir(), "phreshos-request-routing-"))- const application = await Application.initialize(home, { system: join(home, "logo.png"), defaultProgram: join(home, "icon.png") }, join(home, "wallpapers"))+ const application = await Application.initialize(home, { system: join(home, "logo.png"), defaultProgram: join(home, "icon.png") }, {})const link = new TheLink()const boundary = application.linkManager.addExternalConnection(link)const broadcasts: unknown[][] = []diff --git a/tests/system-about.test.ts b/tests/system-about.test.tsindex e02ed56..3fef1f7 100644--- a/tests/system-about.test.ts+++ b/tests/system-about.test.ts@@ -9,7 +9,7 @@ import { name, release, version } from "@/source/identity"test("the System says what it is from its identity, and when it started", async () => {const home = await mkdtemp(join(tmpdir(), "phreshos-about-"))const before = Date.now()- const application = await Application.initialize(home, { system: join(home, "logo.png"), defaultProgram: join(home, "icon.png") }, join(home, "wallpapers"))+ const application = await Application.initialize(home, { system: join(home, "logo.png"), defaultProgram: join(home, "icon.png") }, {})try {const about = application.system.about()diff --git a/tests/system-files.ts b/tests/system-files.tsnew file mode 100644index 0000000..4c9f6cf--- /dev/null+++ b/tests/system-files.ts@@ -0,0 +1,7 @@+import { resolve } from "node:path"+import { systemWallpapers } from "@phreshos/core"++/** The files behind the upload keys the System keeps, read from the sources as a build carries them. */+export const systemFiles = Object.fromEntries(Object.values(systemWallpapers)+ .flatMap(wallpapers => Object.values(wallpapers))+ .map(key => [key, resolve(`assets/wallpapers/${key}.webp`)]))diff --git a/tests/system-icon.test.ts b/tests/system-icon.test.tsindex daea9b6..44820b0 100644--- a/tests/system-icon.test.ts+++ b/tests/system-icon.test.ts@@ -4,11 +4,12 @@ import { tmpdir } from "node:os"import { join, resolve } from "node:path"import sharp from "sharp"import { test } from "vitest"+import { systemFiles } from "./system-files"import Application from "@server/core/application"test("the System renders its own icon at each standard size, and only those", async () => {const home = await mkdtemp(join(tmpdir(), "phreshos-icon-"))- const application = await Application.initialize(home, { system: resolve("assets/logo.png"), defaultProgram: resolve("assets/default-icon.png") }, resolve("assets/wallpapers"))+ const application = await Application.initialize(home, { system: resolve("assets/logo.png"), defaultProgram: resolve("assets/default-icon.png") }, systemFiles)try {for (const [size, length] of [["small", 32], ["medium", 64], ["large", 128]] as const) {const metadata = await sharp(Buffer.from(await application.system.icon(size))).metadata()diff --git a/tests/uploads.test.ts b/tests/uploads.test.tsindex 12ef3f4..d0f66a2 100644--- a/tests/uploads.test.ts+++ b/tests/uploads.test.ts@@ -8,10 +8,11 @@ import uploadView from "@server/view/http/uploads"import type Application from "@server/core/application"import { Hono } from "hono"import { test } from "vitest"+import { systemFiles } from "./system-files"test("uploads contract", async () => {const directory = await mkdtemp(resolve(".verify-uploads-"))- const uploads = new UploadManager(new FileManager(directory), resolve("assets/wallpapers"))+ const uploads = new UploadManager(new FileManager(directory), systemFiles)try {const file = await uploads.write("txt", new Blob(["hello uploads"]).stream())diff --git a/vite.config.ts b/vite.config.tsindex 8798c4f..c10a22f 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -21,6 +21,9 @@ export default defineConfig({},build: {ssr: true,+ // The files the server reads, imported with `?url`, are carried beside it, never inlined.+ ssrEmitAssets: true,+ assetsInlineLimit: 0,emptyOutDir: true,outDir: resolve(import.meta.dirname, "dist/server"),rolldownOptions: {