Skip to content

An open-source, self-hosted system for apps built with web technologies.

Own the uploads collection

zohayrslileh785d731767fe
diff --git a/package.json b/package.json
index 2db041d..6163779 100644
--- a/package.json
+++ b/package.json
@@ -30,7 +30,7 @@
"build": "vite-node scripts/build.ts",
"start": "node --run build && node dist/server/main.js",
"pack": "node --run build && vite-node scripts/pack.ts",
- "verify:contracts": "vite-node scripts/verify-client-launch.mjs && vite-node scripts/verify-process-find-or-create.mjs && vite-node scripts/verify-client-surface.mjs && vite-node scripts/verify-window-geometry.mjs && vite-node scripts/verify-readiness.mjs && vite-node scripts/verify-storage.mjs && vite-node scripts/verify-endpoint-services.mjs && vite-node scripts/verify-program-install.mjs && vite-node scripts/verify-host-traffic.mjs && vite-node scripts/verify-gateway-address.mjs && vite-node scripts/verify-gateway.mjs && vite-node scripts/verify-appearance.mjs",
+ "verify:contracts": "vite-node scripts/verify-client-launch.mjs && vite-node scripts/verify-process-find-or-create.mjs && vite-node scripts/verify-client-surface.mjs && vite-node scripts/verify-window-geometry.mjs && vite-node scripts/verify-readiness.mjs && vite-node scripts/verify-storage.mjs && vite-node scripts/verify-uploads.mjs && vite-node scripts/verify-endpoint-services.mjs && vite-node scripts/verify-program-install.mjs && vite-node scripts/verify-host-traffic.mjs && vite-node scripts/verify-gateway-address.mjs && vite-node scripts/verify-gateway.mjs && vite-node scripts/verify-appearance.mjs",
"verify:distribution": "node scripts/verify-distribution.mjs",
"verify": "node --run check && node --run verify:contracts && node --run verify:distribution"
},
diff --git a/scripts/verify-uploads.mjs b/scripts/verify-uploads.mjs
new file mode 100644
index 0000000..8e003c3
--- /dev/null
+++ b/scripts/verify-uploads.mjs
@@ -0,0 +1,67 @@
+import assert from "node:assert/strict"
+import { mkdtemp, readFile, rm } from "node:fs/promises"
+import { resolve } from "node:path"
+import FileManager from "../source/libs/file-manager.ts"
+import UploadManager from "../source/server/core/upload-manager.ts"
+import uploadView from "../source/server/view/uploads.ts"
+import { Hono } from "hono"
+
+const directory = await mkdtemp(resolve(".verify-uploads-"))
+const uploads = new UploadManager(new FileManager(directory))
+
+try {
+ const file = await uploads.write("txt", new Blob(["hello uploads"]).stream())
+ const upload = uploads.stat(file)
+
+ assert(upload)
+ assert.equal(upload.file, file)
+ assert.equal(upload.type, "text/plain")
+ assert.equal(upload.size, 13)
+ assert.equal(await readFile(uploads.path(file), "utf8"), "hello uploads")
+ assert.equal(uploads.stat("00000000-0000-0000-0000-000000000000.txt"), null)
+ assert.throws(() => uploads.stat("../outside.txt"), /not an upload file/)
+
+ const view = new Hono()
+
+ view.route("/uploads", uploadView({
+ uploads,
+ linkManager: {
+ authManager: {
+ verify(value) {
+ if (value !== "allowed") throw new Error("Unauthorized")
+ },
+ async upload(authorization, content, extension, signal) {
+ this.verify(authorization)
+ const written = await uploads.write(extension, content, signal)
+ return uploads.stat(written)
+ }
+ }
+ }
+ }))
+ const response = await view.request("http://system/uploads", {
+ method: "POST",
+ headers: {
+ authorization: "allowed",
+ "content-disposition": "attachment; filename=value.json",
+ "content-type": "application/json"
+ },
+ body: JSON.stringify({ ready: true })
+ })
+ assert.equal(response.status, 200)
+ const created = await response.json()
+
+ assert.equal(created.type, "application/json")
+ const described = await view.request(`http://system/uploads/${created.file}/stat`)
+ const downloaded = await view.request(`http://system/uploads/${created.file}`)
+
+ assert.equal(described.status, 200)
+ assert.equal(downloaded.status, 200)
+ assert.deepEqual(await described.json(), created)
+ assert.deepEqual(JSON.parse(await downloaded.text()), { ready: true })
+ assert.equal((await view.request("http://system/uploads/not-a-key")).status, 400)
+ assert.equal((await view.request("http://system/uploads/00000000-0000-0000-0000-000000000000.txt")).status, 404)
+} finally {
+ await rm(directory, { recursive: true, force: true })
+}
+
+console.log("uploads verified")
diff --git a/source/client/core/application.ts b/source/client/core/application.ts
index cf4668e..d6e7862 100644
--- a/source/client/core/application.ts
+++ b/source/client/core/application.ts
@@ -3,6 +3,7 @@ import { type ProxyOutcome, type ProxyRequest, type ProxyResponse, proxyMediaTyp
import { storageMediaType, type StorageRequest } from "@server/core/protocol/storage"
import { frame, frameBlob, unframe } from "@libs/framing"
import messagepack from "@libs/messagepack"
+import type { Upload } from "@phreshos/core"
export default class Application {
@@ -38,7 +39,7 @@ export default class Application {
// browsers refuse unknown-length streaming requests over HTTP/1 before the
// server ever sees them. Authorization belongs to the desktop and is added
// here, never exposed to the pane.
- public async serve(content: ClientBody, description: ServedValue, authorization: string, signal?: AbortSignal): Promise<ServedFile> {
+ public async uploadWrite(content: ClientBody, description: UploadValue, authorization: string, signal?: AbortSignal): Promise<Upload> {
const headers: Record<string, string> = {
@@ -56,6 +57,25 @@ export default class Application {
return await response.json()
}
+ public async uploadStream(file: string, signal?: AbortSignal) {
+
+ const response = await fetch(`${this.doors.uploads}/${encodeURIComponent(file)}`, { signal })
+
+ if (!response.ok || !response.body) throw new Error(response.ok ? "The upload response has no body" : `The upload could not be read (${response.status})`)
+
+ return response.body
+ }
+
+ public async uploadStat(file: string): Promise<Upload | null> {
+
+ const response = await fetch(`${this.doors.uploads}/${encodeURIComponent(file)}/stat`)
+
+ if (response.status === 404) return null
+ if (!response.ok) throw new Error(await response.text())
+
+ return await response.json()
+ }
+
/** Carry an unrestricted request through the desktop's authorized proxy. */
public async proxy(request: ProxyRequest, body: ClientBody | null, authorization: string, signal?: AbortSignal): Promise<ProxiedResponse> {
@@ -213,18 +233,7 @@ interface PreparedBody {
remove: () => Promise<void>
}
-export interface ServedFile {
-
- file: string
-
- type: string | null
-
- size: number
-
- time: number
-}
-
-export interface ServedValue {
+export interface UploadValue {
extension: string
diff --git a/source/client/view/components/desktop-host/host.ts b/source/client/view/components/desktop-host/host.ts
index 54556e2..545a74d 100644
--- a/source/client/view/components/desktop-host/host.ts
+++ b/source/client/view/components/desktop-host/host.ts
@@ -1,11 +1,11 @@
import { type Launch } from "@server/core/link-manager/auth-manager/program-manager/program-manager"
import { type ProxyRequest } from "@server/core/protocol/proxy"
import AuthManager from "@client/core/link-manager/auth-manager/auth-manager"
-import { type ClientBody, type ProxiedResponse, type ServedValue } from "@client/core/application"
+import { type ClientBody, type ProxiedResponse, type UploadValue } from "@client/core/application"
import { type PointerHost } from "./pointer"
import { type TrafficKind } from "@server/core/link-manager/auth-manager/process-manager/process-traffic"
import { sdkProcess, sdkProgram } from "./sdk-records"
-import { isPermissionName, isServiceKey, type ProgramIconSize } from "@phreshos/core"
+import { isPermissionName, isServiceKey, isUploadFile, type ProgramIconSize } from "@phreshos/core"
import {
localGeometry,
localPosition,
@@ -718,28 +718,64 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()
return [pointer.position()]
}
- // A pane normalizes any writable value before it reaches the frame wall:
- // finite bytes retain their native Blob and an open stream is transferred.
- // The desktop sends either through its authorized uploads door and returns
- // only the served file's description.
- if (word === "serve") {
+ // Uploads are one flat public collection. A pane may provide bytes or
+ // one opaque file key; it never receives a filesystem path or route.
+ if (word === "uploads") {
- if (!clientBody(args[0])) throw new Error("Serving takes bytes")
+ const operation = args[0]
- const description = args[1] as Partial<ServedValue> | null
+ if (operation === "stat") {
+
+ if (!isUploadFile(args[1])) throw new Error("Uploads stat takes one upload file")
+
+ return [await authManager.linkManager.application.uploadStat(args[1])]
+ }
+
+ if (operation === "stream") {
+
+ if (!isUploadFile(args[1])) throw new Error("Uploads stream takes one upload file")
+
+ const { control, controller } = cancellation(args[2], "uploads stream")
+
+ try {
+
+ const body = controlled(
+
+ await authManager.linkManager.application.uploadStream(args[1], controller.signal),
+
+ controller,
+
+ control
+ )
+
+ return new TransferredAnswer([body], [body])
+ }
+
+ catch (exception) {
+
+ control.close()
+
+ throw exception
+ }
+ }
+
+ if (operation !== "write") throw new Error(`Uploads does not know the operation "${String(operation)}"`)
+ if (!clientBody(args[1])) throw new Error("Uploads write takes bytes")
+
+ const description = args[2] as Partial<UploadValue> | null
if (!description || typeof description.type !== "string" || typeof description.extension !== "string" || !/^[a-z0-9]+$/.test(description.extension)) {
- throw new Error("Serving takes a value description")
+ throw new Error("Uploads write takes a value description")
}
- const { control, controller } = cancellation(args[2], "serve")
+ const { control, controller } = cancellation(args[3], "uploads write")
try {
- const served = await authManager.linkManager.application.serve(
+ const upload = await authManager.linkManager.application.uploadWrite(
- args[0],
+ args[1],
{ extension: description.extension, type: description.type },
@@ -750,7 +786,7 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()
control.close()
- return [served]
+ return [upload]
}
catch (exception) {
diff --git a/source/server/core/appearance-manager.ts b/source/server/core/appearance-manager.ts
index dba40de..37a2c61 100644
--- a/source/server/core/appearance-manager.ts
+++ b/source/server/core/appearance-manager.ts
@@ -8,7 +8,7 @@ import {
type Appearance,
type AppearanceRange
} from "@phreshos/core"
-import ServedFileManager from "./served-file-manager"
+import UploadManager from "./upload-manager"
const servedFileSchema = z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.[a-z0-9]+$/)
const wallpaperSchema = servedFileSchema.nullable()
@@ -44,11 +44,11 @@ const properties = Object.keys(standardAppearance) as (keyof Appearance)[]
export default class AppearanceManager {
private constructor(
private readonly store: Keyv,
- private readonly servedFiles: ServedFileManager,
+ private readonly uploads: UploadManager,
private current: Appearance
) { }
- public static async open(store: Keyv, servedFiles: ServedFileManager) {
+ public static async open(store: Keyv, uploads: UploadManager) {
const entries = await Promise.all(properties.map(async property => ({
property,
value: await store.get(`appearance:${property}`)
@@ -63,7 +63,7 @@ export default class AppearanceManager {
.filter(({ value }) => value === undefined)
.map(({ property }) => store.set(`appearance:${property}`, appearance[property])))
- return new AppearanceManager(store, servedFiles, appearance)
+ return new AppearanceManager(store, uploads, appearance)
}
public get value() { return this.current }
@@ -85,7 +85,7 @@ export default class AppearanceManager {
private validateWallpaper(file: string | null) {
if (file === null) return
if (!wallpaperExtensions.has(extname(file).slice(1))) throw new Error("A wallpaper must be an image file")
- this.servedFiles.describe(file)
+ if (!this.uploads.stat(file)) throw new Error("The wallpaper upload does not exist")
}
}
diff --git a/source/server/core/application.ts b/source/server/core/application.ts
index 44ee283..800a1ca 100644
--- a/source/server/core/application.ts
+++ b/source/server/core/application.ts
@@ -2,7 +2,7 @@ import LinkManager from "./link-manager/link-manager"
import Authentication from "./authentication/authentication"
import FileManager from "@libs/file-manager"
import Encryptor from "@libs/encryptor"
-import ServedFileManager from "./served-file-manager"
+import UploadManager from "./upload-manager"
import DialogManager from "./dialog-manager"
import AppearanceManager from "./appearance-manager"
import openStore from "./open-store"
@@ -34,7 +34,7 @@ export default class Application {
public readonly authentication: Authentication
- public readonly servedFiles: ServedFileManager
+ public readonly uploads: UploadManager
public readonly dialogManager: DialogManager
@@ -64,7 +64,7 @@ export default class Application {
this.authentication = payload.authentication
- this.servedFiles = payload.servedFiles
+ this.uploads = payload.uploads
this.appearanceManager = payload.appearanceManager
@@ -87,11 +87,11 @@ export default class Application {
const authentication = await Authentication.open(storage.join("credentials.json"), store)
- const servedFiles = new ServedFileManager(storage.navigateTo("uploads"))
+ const uploads = new UploadManager(storage.navigateTo("uploads"))
- const appearanceManager = await AppearanceManager.open(store, servedFiles)
+ const appearanceManager = await AppearanceManager.open(store, uploads)
- const application = new Application({ name, displayName, version, defaultProgramIcon, storage, home, store, encryptor, authentication, appearanceManager, servedFiles })
+ const application = new Application({ name, displayName, version, defaultProgramIcon, storage, home, store, encryptor, authentication, appearanceManager, uploads })
await application.linkManager.authManager.programManager.initialize()
@@ -121,5 +121,5 @@ interface ApplicationPayload {
appearanceManager: AppearanceManager
- servedFiles: ServedFileManager
+ uploads: UploadManager
}
diff --git a/source/server/core/link-manager/auth-manager/auth-manager.ts b/source/server/core/link-manager/auth-manager/auth-manager.ts
index 7b37e8c..1a5848f 100644
--- a/source/server/core/link-manager/auth-manager/auth-manager.ts
+++ b/source/server/core/link-manager/auth-manager/auth-manager.ts
@@ -1,5 +1,5 @@
import { Connect, Forward, Intercept, Subscribe } from "@libs/the-link/decorators/escript"
-import ServedFileManager from "@server/core/served-file-manager"
+import UploadManager from "@server/core/upload-manager"
import DialogManager from "@server/core/dialog-manager"
import ProcessManager from "./process-manager/process-manager"
import ProgramManager from "./program-manager/program-manager"
@@ -35,9 +35,9 @@ export default class AuthManager extends TheLink {
this.subscribeTo(this.linkManager, "/auth")
}
- private get servedFiles(): ServedFileManager {
+ private get uploads(): UploadManager {
- return this.linkManager.application.servedFiles
+ return this.linkManager.application.uploads
}
// What being authorized means, decided once. Every road in asks
@@ -58,15 +58,15 @@ export default class AuthManager extends TheLink {
return values
}
- // Making a value public is authorized here; the uploads door is only the
- // client transport that brings its bytes to this operation.
- public async serve(authorization: unknown, content: ReadableStream<Uint8Array> | null, type: string | null, extension: string, signal?: AbortSignal) {
+ // Writing a public value is authorized here; the uploads door is only the
+ // Client transport that brings its bytes to this operation.
+ public async upload(authorization: unknown, content: ReadableStream<Uint8Array> | null, extension: string, signal?: AbortSignal) {
this.verify(authorization)
- const file = await this.servedFiles.write(extension, content, signal)
+ const file = await this.uploads.write(extension, content, signal)
- return { ...this.servedFiles.describe(file), type }
+ return this.uploads.stat(file)!
}
/** Perform a server-side request after the desktop door proves authorization. */
@@ -158,14 +158,3 @@ export default class AuthManager extends TheLink {
}
export type TransmittedAuthManager = Transmitted<AuthManager>
-
-export interface ServedFile {
-
- file: string
-
- type: string | null
-
- size: number
-
- time: number
-}
diff --git a/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts b/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts
index 4828b08..44c1f24 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts
@@ -1,5 +1,5 @@
import { Connect, Subscribe } from "@libs/the-link/decorators/escript"
-import { serveLimit } from "@server/core/served-file-manager"
+import { uploadLimit } from "@server/core/upload-manager"
import { ChildProcess } from "node:child_process"
import { type Launch, type LaunchClient, type Options } from "../program-manager/program-manager"
import Program from "../program-manager/program"
@@ -1918,14 +1918,17 @@ export default class ProcessManager extends TheLink {
return [programManager.databaseOf(program).query(String(rest[1]), Array.isArray(rest[2]) ? rest[2] : [])]
}
- // A server half writes served values locally, as it does its program
- // areas. The SDK asks for the one managed root and canonical limit;
- // neither becomes a separate public capability.
- if (word === "serve") {
+ // A Server Endpoint performs upload byte I/O locally. The SDK receives
+ // the managed root only for stream and write operations; upload keys
+ // remain flat and validated by both sides.
+ if (word === "uploads") {
- const { servedFiles } = this.authManager.linkManager.application
+ const { uploads } = this.authManager.linkManager.application
- return [servedFiles.fileManager.path, serveLimit]
+ if (rest[0] === "access") return [uploads.fileManager.path, uploadLimit]
+ if (rest[0] === "stat") return [uploads.stat(String(rest[1]))]
+
+ throw new Error(`The uploads capability does not know the operation "${String(rest[0])}"`)
}
// A program's own persistent key-value store. A Program handle names
diff --git a/source/server/core/served-file-manager.ts b/source/server/core/upload-manager.ts
similarity index 51%
rename from source/server/core/served-file-manager.ts
rename to source/server/core/upload-manager.ts
index 6993910..19fdcb3 100644
--- a/source/server/core/served-file-manager.ts
+++ b/source/server/core/upload-manager.ts
@@ -1,14 +1,15 @@
-import { createWriteStream, mkdirSync, statSync } from "node:fs"
+import { 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 { isUploadFile, type Upload } from "@phreshos/core"
-export const serveLimit = 1024 * 1024 * 1024
+export const uploadLimit = 1024 * 1024 * 1024
-export class MissingServedValueError extends Error {
+export class MissingUploadValueError extends Error {
public constructor() {
@@ -16,11 +17,11 @@ export class MissingServedValueError extends Error {
}
}
-export class ServedValueTooLargeError extends Error {
+export class UploadTooLargeError extends Error {
public constructor() {
- super(`The served value exceeds ${serveLimit / 1024 / 1024 / 1024} GB`)
+ super(`The upload exceeds ${uploadLimit / 1024 / 1024 / 1024} GB`)
}
}
@@ -32,9 +33,7 @@ export class ServedValueTooLargeError extends Error {
* Only a complete value at or below the limit is renamed into public reach;
* interruption and refusal remove the temporary file.
*/
-const shape = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.[a-z0-9]+$/
-
-export default class ServedFileManager {
+export default class UploadManager {
public readonly fileManager: FileManager
@@ -47,22 +46,22 @@ export default class ServedFileManager {
public path(file: string) {
- if (!shape.test(file)) throw new Error("That is not a served file")
+ if (!isUploadFile(file)) throw new Error("That is not an upload file")
return this.fileManager.join(file)
}
public async write(extension: string, content: ReadableStream<Uint8Array> | null, signal?: AbortSignal) {
- if (!/^[a-z0-9]+$/.test(extension)) throw new Error("A served file needs a valid extension")
+ if (!/^[a-z0-9]+$/.test(extension)) throw new Error("An upload needs a valid extension")
- if (!content) throw new MissingServedValueError()
+ if (!content) throw new MissingUploadValueError()
const uuid = randomUUID()
const file = `${uuid}.${extension}`
- const temporary = this.fileManager.join(`.${uuid}.serving`)
+ const temporary = this.fileManager.join(`.${uuid}.uploading`)
let size = 0
@@ -78,7 +77,7 @@ export default class ServedFileManager {
size += chunk.byteLength
- if (size > serveLimit) throw new ServedValueTooLargeError()
+ if (size > uploadLimit) throw new UploadTooLargeError()
yield chunk
}
@@ -102,11 +101,49 @@ export default class ServedFileManager {
return file
}
- public describe(file: string) {
+ public stat(file: string): Upload | null {
+
+ let stat
+
+ try { stat = lstatSync(this.path(file)) }
+ catch (error) {
+
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return null
+ throw error
+ }
- const stat = statSync(this.path(file))
+ if (!stat.isFile()) throw new Error("That upload key does not identify a file")
- return { file, size: stat.size, time: Math.round(stat.mtimeMs) }
+ return { file, type: mediaType(file), size: stat.size, time: Math.round(stat.mtimeMs) }
}
}
+
+function mediaType(file: string) {
+
+ return types[file.slice(file.lastIndexOf(".") + 1)] ?? null
+}
+
+const types: Readonly<Record<string, string>> = {
+ avif: "image/avif",
+ bin: "application/octet-stream",
+ bmp: "image/bmp",
+ css: "text/css",
+ csv: "text/csv",
+ gif: "image/gif",
+ gz: "application/gzip",
+ html: "text/html",
+ jpeg: "image/jpeg",
+ jpg: "image/jpeg",
+ js: "text/javascript",
+ json: "application/json",
+ mp3: "audio/mpeg",
+ mp4: "video/mp4",
+ pdf: "application/pdf",
+ png: "image/png",
+ svg: "image/svg+xml",
+ txt: "text/plain",
+ wasm: "application/wasm",
+ webp: "image/webp",
+ zip: "application/zip"
+}
diff --git a/source/server/view/uploads.ts b/source/server/view/uploads.ts
index dc3c2f8..9625e66 100644
--- a/source/server/view/uploads.ts
+++ b/source/server/view/uploads.ts
@@ -1,8 +1,9 @@
import { serveStatic } from "@hono/node-server/serve-static"
-import { MissingServedValueError, ServedValueTooLargeError, serveLimit } from "@server/core/served-file-manager"
+import { MissingUploadValueError, UploadTooLargeError, uploadLimit } from "@server/core/upload-manager"
import Application from "@server/core/application"
import doors from "./doors"
import { Hono } from "hono"
+import { isUploadFile } from "@phreshos/core"
/**
* The door bytes come through, and the one they go back out of.
@@ -10,7 +11,7 @@ import { Hono } from "hono"
* Transport only: making a value public is an authorized operation on the
* auth manager. Reading the completed file needs no authorization.
*
- * The request body remains a stream all the way into ServedFileManager. Declared
+ * The request body remains a stream all the way into UploadManager. Declared
* oversize bodies are refused before reading; undeclared ones are counted as
* they arrive, with incomplete temporary files removed on every failure.
*/
@@ -34,44 +35,69 @@ export default function (application: Application) {
return context.text(exception instanceof Error ? exception.message : "Unauthorized", 401)
}
- if (Number(context.req.header("content-length")) > serveLimit) return context.text(new ServedValueTooLargeError().message, 413)
+ if (Number(context.req.header("content-length")) > uploadLimit) return context.text(new UploadTooLargeError().message, 413)
try {
- const type = context.req.header("content-type") ?? null
-
- const served = await authManager.serve(
+ const upload = await authManager.upload(
authorization,
context.req.raw.body,
- type,
-
- extension(filename(context.req.header("content-disposition"))) ?? typeExtension(type),
+ extension(filename(context.req.header("content-disposition"))) ?? typeExtension(context.req.header("content-type") ?? null),
context.req.raw.signal
)
- return context.json(served)
+ return context.json(upload)
}
catch (exception) {
- if (exception instanceof MissingServedValueError) return context.text(exception.message, 400)
+ if (exception instanceof MissingUploadValueError) return context.text(exception.message, 400)
- if (exception instanceof ServedValueTooLargeError) return context.text(exception.message, 413)
+ if (exception instanceof UploadTooLargeError) return context.text(exception.message, 413)
if (exception instanceof Error && exception.message === "Unauthorized") return context.text(exception.message, 401)
console.error(exception)
- return context.text("The value could not be served", 500)
+ return context.text("The value could not be uploaded", 500)
+ }
+ })
+
+ uploads.get("/:file/stat", function (context) {
+
+ try {
+
+ const upload = application.uploads.stat(context.req.param("file"))
+
+ return upload ? context.json(upload) : context.body(null, 404)
+ }
+
+ catch (error) {
+
+ return context.text(error instanceof Error ? error.message : "Invalid upload", 400)
}
})
uploads.use("/:file", async function (context, next) {
+ const file = context.req.param("file")
+
+ if (!isUploadFile(file)) return context.text("That is not an upload file", 400)
+
+ try {
+
+ if (!application.uploads.stat(file)) return context.body(null, 404)
+ }
+
+ catch (error) {
+
+ return context.text(error instanceof Error ? error.message : "Invalid upload", 400)
+ }
+
await next()
context.header("Access-Control-Allow-Origin", "*")
@@ -79,7 +105,7 @@ export default function (application: Application) {
uploads.use("/:file", serveStatic({
- root: application.servedFiles.fileManager.path,
+ root: application.uploads.fileManager.path,
rewriteRequestPath: path => path.slice(doors.uploads.length + 1)
}))