@hamur/blob 0.0.0-stage → 0.0.1
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/LICENSE +22 -0
- package/README.md +51 -2
- package/dist/src/client/index.js +158 -0
- package/dist/src/index.js +220 -0
- package/dist/src/server/index.js +498 -0
- package/dist/types/src/build/setup.d.ts +7 -0
- package/dist/types/src/client/index.d.ts +28 -0
- package/dist/types/src/drivers/cloudflare-r2.d.ts +75 -0
- package/dist/types/src/drivers/fs.d.ts +14 -0
- package/dist/types/src/drivers/s3.d.ts +12 -0
- package/dist/types/src/drivers/suite.d.ts +9 -0
- package/dist/types/src/index.d.ts +2 -0
- package/dist/types/src/module.d.ts +3 -0
- package/dist/types/src/options.d.ts +19 -0
- package/dist/types/src/runtime/choose.d.ts +3 -0
- package/dist/types/src/runtime/driver.d.ts +29 -0
- package/dist/types/src/runtime/mime.d.ts +6 -0
- package/dist/types/src/runtime/multipart.d.ts +34 -0
- package/dist/types/src/runtime/store.d.ts +10 -0
- package/dist/types/src/server/blob.d.ts +3 -0
- package/dist/types/src/server/ensure.d.ts +22 -0
- package/dist/types/src/server/index.d.ts +12 -0
- package/dist/types/src/types.d.ts +152 -0
- package/package.json +32 -4
- package/src/build/setup.ts +137 -0
- package/src/client/index.ts +206 -0
- package/src/drivers/cloudflare-r2.ts +232 -0
- package/src/drivers/fs.ts +398 -0
- package/src/drivers/s3.ts +311 -0
- package/src/drivers/suite.ts +314 -0
- package/src/env.d.ts +16 -0
- package/src/index.ts +10 -0
- package/src/module.ts +11 -0
- package/src/options.ts +102 -0
- package/src/runtime/choose.ts +18 -0
- package/src/runtime/driver.ts +82 -0
- package/src/runtime/mime.ts +18 -0
- package/src/runtime/multipart.ts +319 -0
- package/src/runtime/store.ts +190 -0
- package/src/server/blob.ts +26 -0
- package/src/server/ensure.ts +52 -0
- package/src/server/index.ts +20 -0
- package/src/types.ts +155 -0
package/src/options.ts
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import type { ResolvedBlobDriver, Secret } from "./types.ts"
|
|
2
|
+
import { DiagnosticError, isEnvRef } from "hamur/kit"
|
|
3
|
+
|
|
4
|
+
/** Each driver and the presets it runs on (`static` runs the server only at build, on Bun). */
|
|
5
|
+
export const DRIVERS: Record<ResolvedBlobDriver["driver"], { presets: string[]; keys: string[] }> = {
|
|
6
|
+
fs: { presets: ["bun", "node", "static"], keys: ["base"] },
|
|
7
|
+
s3: {
|
|
8
|
+
presets: ["bun", "node", "static", "cloudflare", "vercel", "netlify"],
|
|
9
|
+
keys: [
|
|
10
|
+
"bucket",
|
|
11
|
+
"region",
|
|
12
|
+
"endpoint",
|
|
13
|
+
"accessKeyId",
|
|
14
|
+
"secretAccessKey",
|
|
15
|
+
"sessionToken",
|
|
16
|
+
"virtualHostedStyle",
|
|
17
|
+
"base",
|
|
18
|
+
],
|
|
19
|
+
},
|
|
20
|
+
"cloudflare-r2": { presets: ["cloudflare"], keys: ["binding", "base"] },
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const SECRETS = ["bucket", "region", "endpoint", "accessKeyId", "secretAccessKey", "sessionToken"] as const
|
|
24
|
+
const BINDING = /^[A-Za-z_][A-Za-z0-9_]*$/
|
|
25
|
+
|
|
26
|
+
export const DEFAULT_FS: Extract<ResolvedBlobDriver, { driver: "fs" }> = { driver: "fs", base: ".data/blob" }
|
|
27
|
+
export const DEFAULT_R2: Extract<ResolvedBlobDriver, { driver: "cloudflare-r2" }> = {
|
|
28
|
+
driver: "cloudflare-r2",
|
|
29
|
+
binding: "BLOB",
|
|
30
|
+
base: "",
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface ResolvedBlobOptions {
|
|
34
|
+
/** The configured driver; undefined gives the preset's default. */
|
|
35
|
+
driver?: ResolvedBlobDriver
|
|
36
|
+
dev?: ResolvedBlobDriver
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function fail(message: string): never {
|
|
40
|
+
throw new DiagnosticError("HAMUR_E5201", message)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function shown(value: unknown): string {
|
|
44
|
+
if (Array.isArray(value)) return "an array"
|
|
45
|
+
if (typeof value === "function") return "a function"
|
|
46
|
+
if (value === undefined) return "undefined"
|
|
47
|
+
return JSON.stringify(value)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const isObject = (value: unknown): value is Record<string, unknown> =>
|
|
51
|
+
typeof value === "object" && value !== null && !Array.isArray(value)
|
|
52
|
+
|
|
53
|
+
const isSecret = (value: unknown): value is Secret => (typeof value === "string" && value !== "") || isEnvRef(value)
|
|
54
|
+
|
|
55
|
+
function resolveDriver(at: string, options: Record<string, unknown>): ResolvedBlobDriver {
|
|
56
|
+
const driver = options.driver
|
|
57
|
+
if (typeof driver !== "string" || !Object.hasOwn(DRIVERS, driver))
|
|
58
|
+
fail(`${at}.driver must be "fs", "s3" or "cloudflare-r2" (got ${shown(driver)})`)
|
|
59
|
+
const { keys } = DRIVERS[driver as ResolvedBlobDriver["driver"]]
|
|
60
|
+
for (const key of Object.keys(options)) {
|
|
61
|
+
if (key !== "driver" && key !== "dev" && !keys.includes(key))
|
|
62
|
+
fail(`${at} has no ${JSON.stringify(key)} on the "${driver}" driver (it takes: ${keys.join(", ")})`)
|
|
63
|
+
}
|
|
64
|
+
const base = options.base
|
|
65
|
+
if (base !== undefined && typeof base !== "string") fail(`${at}.base must be a string (got ${shown(base)})`)
|
|
66
|
+
if (driver === "fs") {
|
|
67
|
+
if (base === "") fail(`${at}.base must be a directory (got "")`)
|
|
68
|
+
return { driver, base: (base as string | undefined) ?? DEFAULT_FS.base }
|
|
69
|
+
}
|
|
70
|
+
if (driver === "cloudflare-r2") {
|
|
71
|
+
const binding = options.binding ?? DEFAULT_R2.binding
|
|
72
|
+
if (typeof binding !== "string" || !BINDING.test(binding))
|
|
73
|
+
fail(`${at}.binding must be a binding name (got ${shown(binding)})`)
|
|
74
|
+
return { driver, binding, base: (base as string | undefined) ?? "" }
|
|
75
|
+
}
|
|
76
|
+
const resolved: ResolvedBlobDriver = { driver: "s3", base: (base as string | undefined) ?? "" }
|
|
77
|
+
for (const key of SECRETS) {
|
|
78
|
+
const value = options[key]
|
|
79
|
+
if (value === undefined) continue
|
|
80
|
+
if (!isSecret(value)) fail(`${at}.${key} must be a string or env("NAME") (got ${shown(value)})`)
|
|
81
|
+
resolved[key] = value
|
|
82
|
+
}
|
|
83
|
+
const hosted = options.virtualHostedStyle
|
|
84
|
+
if (hosted !== undefined && typeof hosted !== "boolean")
|
|
85
|
+
fail(`${at}.virtualHostedStyle must be a boolean (got ${shown(hosted)})`)
|
|
86
|
+
if (hosted !== undefined) resolved.virtualHostedStyle = hosted
|
|
87
|
+
return resolved
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** The checked options, or the build error of the first value that is wrong. */
|
|
91
|
+
export function resolveOptions(input: unknown): ResolvedBlobOptions {
|
|
92
|
+
if (input === undefined) return {}
|
|
93
|
+
if (!isObject(input)) fail(`blob must be an object (got ${shown(input)})`)
|
|
94
|
+
const resolved: ResolvedBlobOptions = {}
|
|
95
|
+
if (input.dev !== undefined) {
|
|
96
|
+
if (!isObject(input.dev)) fail(`blob.dev must be an object (got ${shown(input.dev)})`)
|
|
97
|
+
if (input.dev.dev !== undefined) fail("blob.dev cannot hold a dev of its own")
|
|
98
|
+
resolved.dev = resolveDriver("blob.dev", input.dev)
|
|
99
|
+
}
|
|
100
|
+
if (Object.keys(input).some((key) => key !== "dev")) resolved.driver = resolveDriver("blob", input)
|
|
101
|
+
return resolved
|
|
102
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { ResolvedBlobDriver } from "../types.ts"
|
|
2
|
+
|
|
3
|
+
/** The driver of this run: `prerender` (`blob.dev`, else the build's driver) while prerendering, else `config`. */
|
|
4
|
+
export function chooseDriver(
|
|
5
|
+
prerendering: boolean,
|
|
6
|
+
config: ResolvedBlobDriver | null,
|
|
7
|
+
prerender: ResolvedBlobDriver | null,
|
|
8
|
+
): ResolvedBlobDriver {
|
|
9
|
+
const chosen = prerendering ? prerender : config
|
|
10
|
+
if (!chosen) throw new Error("@hamur/blob has no driver for this preset; set blob.driver")
|
|
11
|
+
// the prerender runs the server in the build's Bun process, where no R2 binding exists
|
|
12
|
+
if (prerendering && chosen.driver === "cloudflare-r2") {
|
|
13
|
+
throw new Error(
|
|
14
|
+
'@hamur/blob: the "cloudflare-r2" driver cannot run in the prerender (it runs on: cloudflare); set blob.dev',
|
|
15
|
+
)
|
|
16
|
+
}
|
|
17
|
+
return chosen
|
|
18
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { createError } from "hamur/server"
|
|
2
|
+
import type { BlobDriver, ReadSecret, ResolvedBlobDriver } from "../types.ts"
|
|
3
|
+
|
|
4
|
+
export type OpenDriver<C extends ResolvedBlobDriver = ResolvedBlobDriver> = (
|
|
5
|
+
config: C,
|
|
6
|
+
secret: ReadSecret,
|
|
7
|
+
) => BlobDriver
|
|
8
|
+
|
|
9
|
+
/** The pathname error; a driver throws it too for a pathname its backend cannot hold. */
|
|
10
|
+
export const invalidPathname = (pathname: unknown) =>
|
|
11
|
+
new TypeError(`Invalid blob pathname ${JSON.stringify(String(pathname))}`)
|
|
12
|
+
|
|
13
|
+
/** The error from a driver that cannot sign a URL. */
|
|
14
|
+
export const presignUnavailable = (driver: string) =>
|
|
15
|
+
new Error(`presign is not available on the ${driver} driver; use serve(event, pathname), or the s3 driver`)
|
|
16
|
+
|
|
17
|
+
/** A multipart step on an upload the backend does not hold for the pathname. */
|
|
18
|
+
export const uploadNotFound = () => createError({ status: 404, message: "Upload not found" })
|
|
19
|
+
|
|
20
|
+
/** A malformed upload step, or one storage refuses for what the client sent. */
|
|
21
|
+
export const invalidUpload = (cause?: unknown) =>
|
|
22
|
+
createError({ status: 400, message: "Invalid upload request", ...(cause === undefined ? {} : { cause }) })
|
|
23
|
+
|
|
24
|
+
/** A stream of unknown length on `s3` and `cloudflare-r2` is written in parts of this size. */
|
|
25
|
+
export const PART_SIZE = 10 * 1024 * 1024
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The stream cut into `size`-byte parts (the last one shorter), each read before it is yielded, so at most one part is
|
|
29
|
+
* held; a stream that ends inside the first part yields that one part.
|
|
30
|
+
*/
|
|
31
|
+
export async function* parts(stream: ReadableStream<Uint8Array>, size = PART_SIZE): AsyncGenerator<Uint8Array> {
|
|
32
|
+
const reader = stream.getReader()
|
|
33
|
+
let part = new Uint8Array(size)
|
|
34
|
+
let filled = 0
|
|
35
|
+
try {
|
|
36
|
+
while (true) {
|
|
37
|
+
const { done, value } = await reader.read()
|
|
38
|
+
if (done) break
|
|
39
|
+
let at = 0
|
|
40
|
+
while (at < value.length) {
|
|
41
|
+
const take = Math.min(size - filled, value.length - at)
|
|
42
|
+
part.set(value.subarray(at, at + take), filled)
|
|
43
|
+
filled += take
|
|
44
|
+
at += take
|
|
45
|
+
if (filled === size) {
|
|
46
|
+
yield part
|
|
47
|
+
part = new Uint8Array(size)
|
|
48
|
+
filled = 0
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
} finally {
|
|
53
|
+
reader.releaseLock()
|
|
54
|
+
}
|
|
55
|
+
if (filled > 0) yield part.subarray(0, filled)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The first part and an iterator over the rest; `rest` is undefined when the stream fit in one part. */
|
|
59
|
+
export async function firstPart(
|
|
60
|
+
stream: ReadableStream<Uint8Array>,
|
|
61
|
+
size = PART_SIZE,
|
|
62
|
+
): Promise<{ first: Uint8Array; rest?: AsyncGenerator<Uint8Array> }> {
|
|
63
|
+
const all = parts(stream, size)
|
|
64
|
+
const first = await all.next()
|
|
65
|
+
if (first.done) return { first: new Uint8Array(0) }
|
|
66
|
+
if (first.value.length < size) {
|
|
67
|
+
await all.return(undefined)
|
|
68
|
+
return { first: first.value }
|
|
69
|
+
}
|
|
70
|
+
return { first: first.value, rest: all }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Pages through `items` sorted by `name`: those after `after`, at most `limit`. */
|
|
74
|
+
export function page<T extends { name: string }>(
|
|
75
|
+
items: T[],
|
|
76
|
+
after: string | undefined,
|
|
77
|
+
limit: number,
|
|
78
|
+
): { items: T[]; hasMore: boolean } {
|
|
79
|
+
const from = after === undefined ? 0 : items.findIndex((item) => item.name > after)
|
|
80
|
+
const rest = from === -1 ? [] : items.slice(from)
|
|
81
|
+
return { items: rest.slice(0, limit), hasMore: rest.length > limit }
|
|
82
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
const TOKEN = "[!#$%&'*+.^_`|~0-9A-Za-z-]+"
|
|
2
|
+
const QUOTED = '"(?:[\\x20\\x21\\x23-\\x2b\\x2d-\\x5b\\x5d-\\x7e]|\\\\[\\x20-\\x7e])*"'
|
|
3
|
+
const PARAM = `[ \\t]*;[ \\t]*(${TOKEN})=(${TOKEN}|${QUOTED})`
|
|
4
|
+
const TYPE = new RegExp(`^[ \\t]*(${TOKEN})/(${TOKEN})((?:${PARAM})*)[ \\t]*$`)
|
|
5
|
+
const PARAMS = new RegExp(PARAM, "g")
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* One `type/subtype` with optional `; name=value` parameters, in canonical form (type, subtype and parameter names in
|
|
9
|
+
* lowercase), or undefined. A comma is refused anywhere, quoted or not: a browser reading `image/png, text/html` keeps the
|
|
10
|
+
* last type, so a list would pass a check on its first.
|
|
11
|
+
*/
|
|
12
|
+
export function parseContentType(value: string): string | undefined {
|
|
13
|
+
if (value.includes(",")) return undefined
|
|
14
|
+
const match = TYPE.exec(value)
|
|
15
|
+
if (!match) return undefined
|
|
16
|
+
const params = [...match[3]!.matchAll(PARAMS)].map(([, name, param]) => `; ${name!.toLowerCase()}=${param}`).join("")
|
|
17
|
+
return `${match[1]!.toLowerCase()}/${match[2]!.toLowerCase()}${params}`
|
|
18
|
+
}
|
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
import { createError, isHamurError, readBodyBytes, type HamurEvent, type Secret } from "hamur/server"
|
|
2
|
+
import { isEnvRef, readSecret } from "hamur/server/internal"
|
|
3
|
+
import { contentType as defaultContentType } from "hamur/server/http"
|
|
4
|
+
import { ensureBlob, type BlobSize } from "../server/ensure.ts"
|
|
5
|
+
import type { BlobDriver, BlobObject, BlobUploadedPart } from "../types.ts"
|
|
6
|
+
import { invalidUpload, uploadNotFound } from "./driver.ts"
|
|
7
|
+
import { checkContentType, checkMetadata, checkPathname, withRandomSuffix } from "./store.ts"
|
|
8
|
+
|
|
9
|
+
export interface MultipartUploadOptions {
|
|
10
|
+
/** The step, the `:action` param of the route: `create`, `upload`, `complete` or `abort`. */
|
|
11
|
+
action: string
|
|
12
|
+
/** Maps the client's name to the stored pathname, on every step: the app decides where a user may write. */
|
|
13
|
+
pathname?: (name: string) => string
|
|
14
|
+
ensure?: { maxSize?: BlobSize; types?: string[] }
|
|
15
|
+
put?: { addRandomSuffix?: boolean; customMetadata?: Record<string, string> }
|
|
16
|
+
/** Parts go from the browser to storage on presigned `UploadPart` URLs; the `s3` driver only. */
|
|
17
|
+
direct?: boolean
|
|
18
|
+
/** Seconds a direct part URL is valid, default 900. */
|
|
19
|
+
expiresIn?: number
|
|
20
|
+
/** The secret (at least 32 characters) that signs the upload tokens: a value of `#hamur/env/private`, or `env("NAME")`. */
|
|
21
|
+
secret: Secret
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Where the handler runs: the preset of a build (null under `hamur dev`), and its request body limit in bytes. */
|
|
25
|
+
export interface MultipartTarget {
|
|
26
|
+
preset: string | null
|
|
27
|
+
bodyLimit: number
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** S3's limits: part numbers, and the size of every part but the last. */
|
|
31
|
+
const MAX_PARTS = 10_000
|
|
32
|
+
const MIN_PART_SIZE = 5 * 1024 * 1024
|
|
33
|
+
const MAX_PART_SIZE = 5 * 1024 * 1024 * 1024
|
|
34
|
+
const DEFAULT_PART_SIZE = 10 * 1024 * 1024
|
|
35
|
+
const MIN_SECRET_LENGTH = 32
|
|
36
|
+
/** A token is taken this long after `create`, the age at which `fs` drops an upload folder. */
|
|
37
|
+
const TOKEN_LIFETIME_MS = 24 * 60 * 60 * 1000
|
|
38
|
+
const TOKEN_LABEL = "hamur blob multipart upload token"
|
|
39
|
+
|
|
40
|
+
/** A part of at least 5 MiB leaves no room under these presets' request body limits. */
|
|
41
|
+
const BODY_LIMITS: Record<string, string> = {
|
|
42
|
+
vercel: "is over the function's 4.5 MB request body",
|
|
43
|
+
netlify: "is within 1 MB of the function's 6 MB request body",
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const STEP_METHODS: Record<string, string> = { create: "POST", complete: "POST", abort: "DELETE" }
|
|
47
|
+
|
|
48
|
+
const isObject = (value: unknown): value is Record<string, unknown> =>
|
|
49
|
+
typeof value === "object" && value !== null && !Array.isArray(value)
|
|
50
|
+
const isCount = (value: unknown): value is number =>
|
|
51
|
+
typeof value === "number" && Number.isSafeInteger(value) && value >= 0
|
|
52
|
+
const isPartNumber = (value: unknown): value is number =>
|
|
53
|
+
typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= MAX_PARTS
|
|
54
|
+
|
|
55
|
+
const encoder = new TextEncoder()
|
|
56
|
+
const base64url = (bytes: Uint8Array) =>
|
|
57
|
+
btoa(String.fromCharCode(...bytes))
|
|
58
|
+
.replace(/\+/g, "-")
|
|
59
|
+
.replace(/\//g, "_")
|
|
60
|
+
.replace(/=+$/, "")
|
|
61
|
+
|
|
62
|
+
/** Unpadded base64url in its one canonical form, or undefined: no padding, whitespace or stray trailing bits. */
|
|
63
|
+
function fromBase64url(text: string): Uint8Array<ArrayBuffer> | undefined {
|
|
64
|
+
if (!/^[A-Za-z0-9_-]*$/.test(text)) return undefined
|
|
65
|
+
let bytes: Uint8Array<ArrayBuffer>
|
|
66
|
+
try {
|
|
67
|
+
bytes = Uint8Array.from(atob(text.replace(/-/g, "+").replace(/_/g, "/")), (char) => char.charCodeAt(0))
|
|
68
|
+
} catch {
|
|
69
|
+
return undefined
|
|
70
|
+
}
|
|
71
|
+
return base64url(bytes) === text ? bytes : undefined
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** What an upload token carries: the stored pathname, the declared size and part size, the backend's id, and when it expires (ms). */
|
|
75
|
+
interface Upload {
|
|
76
|
+
pathname: string
|
|
77
|
+
size: number
|
|
78
|
+
partSize: number
|
|
79
|
+
uploadId: string
|
|
80
|
+
expires: number
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const keys = new Map<string, Promise<CryptoKey>>()
|
|
84
|
+
|
|
85
|
+
/** The HMAC key of upload tokens, derived from the app's secret with a fixed label so it is not the secret itself. */
|
|
86
|
+
function tokenKey(secret: string): Promise<CryptoKey> {
|
|
87
|
+
let key = keys.get(secret)
|
|
88
|
+
if (!key) {
|
|
89
|
+
key = (async () => {
|
|
90
|
+
const root = await crypto.subtle.importKey(
|
|
91
|
+
"raw",
|
|
92
|
+
encoder.encode(secret),
|
|
93
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
94
|
+
false,
|
|
95
|
+
["sign"],
|
|
96
|
+
)
|
|
97
|
+
const derived = await crypto.subtle.sign("HMAC", root, encoder.encode(TOKEN_LABEL))
|
|
98
|
+
return crypto.subtle.importKey("raw", derived, { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"])
|
|
99
|
+
})()
|
|
100
|
+
keys.set(secret, key)
|
|
101
|
+
}
|
|
102
|
+
return key
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function signToken(secret: string, upload: Upload): Promise<string> {
|
|
106
|
+
const payload = base64url(
|
|
107
|
+
encoder.encode(JSON.stringify([upload.pathname, upload.size, upload.partSize, upload.uploadId, upload.expires])),
|
|
108
|
+
)
|
|
109
|
+
const signature = new Uint8Array(await crypto.subtle.sign("HMAC", await tokenKey(secret), encoder.encode(payload)))
|
|
110
|
+
return `${payload}.${base64url(signature)}`
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** The upload a token names, when its signature holds, it has not expired and it was made for `pathname`; any other token is not found. */
|
|
114
|
+
async function readToken(secret: string, token: unknown, pathname: string): Promise<Upload> {
|
|
115
|
+
if (typeof token !== "string" || token === "") throw invalidUpload()
|
|
116
|
+
const dot = token.lastIndexOf(".")
|
|
117
|
+
const signature = fromBase64url(token.slice(dot + 1))
|
|
118
|
+
const payload = dot < 1 ? undefined : fromBase64url(token.slice(0, dot))
|
|
119
|
+
if (
|
|
120
|
+
!payload ||
|
|
121
|
+
!signature ||
|
|
122
|
+
!(await crypto.subtle.verify("HMAC", await tokenKey(secret), signature, encoder.encode(token.slice(0, dot))))
|
|
123
|
+
)
|
|
124
|
+
throw uploadNotFound()
|
|
125
|
+
const [stored, size, partSize, uploadId, expires] = JSON.parse(new TextDecoder().decode(payload)) as [
|
|
126
|
+
string,
|
|
127
|
+
number,
|
|
128
|
+
number,
|
|
129
|
+
string,
|
|
130
|
+
number,
|
|
131
|
+
]
|
|
132
|
+
if (stored !== pathname || Date.now() >= expires) throw uploadNotFound()
|
|
133
|
+
return { pathname: stored, size, partSize, uploadId, expires }
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const partCount = (upload: Pick<Upload, "size" | "partSize">) => Math.max(1, Math.ceil(upload.size / upload.partSize))
|
|
137
|
+
|
|
138
|
+
/** The bytes part `partNumber` must hold: `partSize` for every part but the last, the rest of `size` for the last. */
|
|
139
|
+
const partBytes = (upload: Upload, partNumber: number) =>
|
|
140
|
+
partNumber < partCount(upload) ? upload.partSize : upload.size - (partCount(upload) - 1) * upload.partSize
|
|
141
|
+
|
|
142
|
+
async function readJson(event: HamurEvent): Promise<Record<string, unknown>> {
|
|
143
|
+
const bytes = await readBodyBytes(event)
|
|
144
|
+
try {
|
|
145
|
+
const value: unknown = JSON.parse(new TextDecoder().decode(bytes ?? new Uint8Array(0)))
|
|
146
|
+
if (isObject(value)) return value
|
|
147
|
+
} catch {}
|
|
148
|
+
throw invalidUpload()
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** The secret of `options.secret`; an unset or short value is a 503 logged once per key. */
|
|
152
|
+
const warned = new Set<string>()
|
|
153
|
+
|
|
154
|
+
function uploadSecret(event: HamurEvent, option: MultipartUploadOptions["secret"]): string {
|
|
155
|
+
if (typeof option !== "string" && !isEnvRef(option))
|
|
156
|
+
throw new TypeError('handleMultipartUpload secret must be a string or env("NAME")')
|
|
157
|
+
const key = typeof option === "string" ? "secret" : `env ${JSON.stringify(option["~env"])}`
|
|
158
|
+
let value: string | undefined
|
|
159
|
+
try {
|
|
160
|
+
value = readSecret(option, "handleMultipartUpload secret")
|
|
161
|
+
} catch {}
|
|
162
|
+
if (value !== undefined && value.length >= MIN_SECRET_LENGTH) return value
|
|
163
|
+
if (!warned.has(key)) {
|
|
164
|
+
warned.add(key)
|
|
165
|
+
event.log.error(`handleMultipartUpload needs ${key} (at least ${MIN_SECRET_LENGTH} characters)`)
|
|
166
|
+
}
|
|
167
|
+
throw createError({ status: 503, message: "Upload endpoint is not configured" })
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* `handleMultipartUpload` over the driver the store opens and the preset the build wrote. Each part must hold
|
|
172
|
+
* exactly its share of the size `create` declared and checked, and `complete` takes exactly the parts 1 – n, so the object
|
|
173
|
+
* that takes the pathname is the one `ensure` allowed; a refused upload never replaces what is there.
|
|
174
|
+
*/
|
|
175
|
+
export function createMultipartUpload(
|
|
176
|
+
driver: () => Promise<BlobDriver>,
|
|
177
|
+
{ preset, bodyLimit }: MultipartTarget,
|
|
178
|
+
): (event: HamurEvent, options: MultipartUploadOptions) => Promise<Response> {
|
|
179
|
+
return async function handleMultipartUpload(event, options) {
|
|
180
|
+
const { action, direct = false, expiresIn = 900 } = options
|
|
181
|
+
if (!direct && preset !== null && BODY_LIMITS[preset]) {
|
|
182
|
+
throw new Error(
|
|
183
|
+
`handleMultipartUpload on the ${preset} preset needs direct: true: a part of at least 5 MiB ${BODY_LIMITS[preset]}`,
|
|
184
|
+
)
|
|
185
|
+
}
|
|
186
|
+
const backend = await driver()
|
|
187
|
+
if (direct && backend.name !== "s3")
|
|
188
|
+
throw new Error(`handleMultipartUpload direct: true needs the s3 driver (blob.driver is "${backend.name}")`)
|
|
189
|
+
|
|
190
|
+
const method =
|
|
191
|
+
action === "upload"
|
|
192
|
+
? direct
|
|
193
|
+
? "POST"
|
|
194
|
+
: "PUT"
|
|
195
|
+
: Object.hasOwn(STEP_METHODS, action)
|
|
196
|
+
? STEP_METHODS[action]
|
|
197
|
+
: undefined
|
|
198
|
+
if (!method) throw createError({ status: 404, message: `Unknown upload step ${JSON.stringify(action)}` })
|
|
199
|
+
if (event.request.method !== method) {
|
|
200
|
+
event.response.headers.set("allow", method)
|
|
201
|
+
throw createError({ status: 405, message: `The upload step ${JSON.stringify(action)} takes ${method}` })
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const secret = uploadSecret(event, options.secret)
|
|
205
|
+
const stored = (name: unknown): string => {
|
|
206
|
+
if (typeof name !== "string") throw invalidUpload()
|
|
207
|
+
let checked: string
|
|
208
|
+
try {
|
|
209
|
+
checked = checkPathname(name)
|
|
210
|
+
} catch (error) {
|
|
211
|
+
throw createError({ status: 400, message: (error as Error).message })
|
|
212
|
+
}
|
|
213
|
+
try {
|
|
214
|
+
return checkPathname(options.pathname ? options.pathname(checked) : checked)
|
|
215
|
+
} catch (error) {
|
|
216
|
+
if (isHamurError(error)) throw error
|
|
217
|
+
throw createError({ status: 500, cause: error })
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
if (action === "create") {
|
|
222
|
+
const body = await readJson(event)
|
|
223
|
+
if (typeof body.pathname !== "string" || (body.contentType !== undefined && typeof body.contentType !== "string"))
|
|
224
|
+
throw invalidUpload()
|
|
225
|
+
if (!isCount(body.size)) throw createError({ status: 400, message: "create needs size (the file's bytes)" })
|
|
226
|
+
const size = body.size
|
|
227
|
+
const partSize = body.partSize ?? DEFAULT_PART_SIZE
|
|
228
|
+
if (!isCount(partSize) || partSize < MIN_PART_SIZE || partSize > MAX_PART_SIZE) {
|
|
229
|
+
throw createError({
|
|
230
|
+
status: 400,
|
|
231
|
+
message: `create partSize must be a whole number of bytes from 5 MiB to 5 GiB (got ${JSON.stringify(partSize)})`,
|
|
232
|
+
})
|
|
233
|
+
}
|
|
234
|
+
if (!direct && partSize > bodyLimit) {
|
|
235
|
+
throw createError({
|
|
236
|
+
status: 400,
|
|
237
|
+
message: `create partSize ${partSize} is over the request body limit of ${bodyLimit} bytes${preset ? ` on the ${preset} preset` : ""}; send smaller parts, or use direct: true`,
|
|
238
|
+
})
|
|
239
|
+
}
|
|
240
|
+
if (partCount({ size, partSize }) > MAX_PARTS)
|
|
241
|
+
throw createError({
|
|
242
|
+
status: 400,
|
|
243
|
+
message: `A file of ${size} bytes needs more than ${MAX_PARTS} parts of ${partSize} bytes`,
|
|
244
|
+
})
|
|
245
|
+
let name = body.pathname
|
|
246
|
+
try {
|
|
247
|
+
name = checkPathname(name)
|
|
248
|
+
if (options.put?.addRandomSuffix) name = checkPathname(withRandomSuffix(name))
|
|
249
|
+
} catch (error) {
|
|
250
|
+
throw createError({ status: 400, message: (error as Error).message })
|
|
251
|
+
}
|
|
252
|
+
const pathname = stored(name)
|
|
253
|
+
const given = (body.contentType as string | undefined) || defaultContentType(pathname)
|
|
254
|
+
if (options.ensure) ensureBlob({ size, contentType: given } as BlobObject, options.ensure)
|
|
255
|
+
let contentType: string
|
|
256
|
+
try {
|
|
257
|
+
contentType = checkContentType(given)
|
|
258
|
+
} catch (error) {
|
|
259
|
+
throw createError({ status: 400, message: (error as Error).message })
|
|
260
|
+
}
|
|
261
|
+
const uploadId = await backend.multipart.create(pathname, {
|
|
262
|
+
contentType,
|
|
263
|
+
customMetadata: checkMetadata(options.put?.customMetadata),
|
|
264
|
+
})
|
|
265
|
+
const token = await signToken(secret, {
|
|
266
|
+
pathname,
|
|
267
|
+
size,
|
|
268
|
+
partSize,
|
|
269
|
+
uploadId,
|
|
270
|
+
expires: Date.now() + TOKEN_LIFETIME_MS,
|
|
271
|
+
})
|
|
272
|
+
return Response.json({ pathname: name, uploadId: token, partSize, ...(direct ? { direct: true } : {}) })
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
if (action === "abort") {
|
|
276
|
+
const query = event.url.searchParams
|
|
277
|
+
const upload = await readToken(secret, query.get("uploadId"), stored(query.get("pathname")))
|
|
278
|
+
await backend.multipart.abort(upload.pathname, upload.uploadId)
|
|
279
|
+
return new Response(null, { status: 204 })
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
if (action === "upload" && !direct) {
|
|
283
|
+
const query = event.url.searchParams
|
|
284
|
+
const upload = await readToken(secret, query.get("uploadId"), stored(query.get("pathname")))
|
|
285
|
+
const partNumber = Number(query.get("partNumber"))
|
|
286
|
+
if (!isPartNumber(partNumber) || partNumber > partCount(upload)) throw invalidUpload()
|
|
287
|
+
const expected = partBytes(upload, partNumber)
|
|
288
|
+
const bytes = (await readBodyBytes(event, { maxBodySize: expected })) ?? new Uint8Array(0)
|
|
289
|
+
if (bytes.length !== expected) throw invalidUpload()
|
|
290
|
+
const etag = await backend.multipart.uploadPart(upload.pathname, upload.uploadId, partNumber, bytes)
|
|
291
|
+
return Response.json({ partNumber, etag })
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
const body = await readJson(event)
|
|
295
|
+
const upload = await readToken(secret, body.uploadId, stored(body.pathname))
|
|
296
|
+
|
|
297
|
+
if (action === "upload") {
|
|
298
|
+
if (
|
|
299
|
+
!isPartNumber(body.partNumber) ||
|
|
300
|
+
body.partNumber > partCount(upload) ||
|
|
301
|
+
body.size !== partBytes(upload, body.partNumber)
|
|
302
|
+
)
|
|
303
|
+
throw invalidUpload()
|
|
304
|
+
const query = { partNumber: String(body.partNumber), uploadId: upload.uploadId }
|
|
305
|
+
const url = await backend.presign(upload.pathname, { method: "PUT", expiresIn, contentLength: body.size, query })
|
|
306
|
+
return Response.json({ partNumber: body.partNumber, url })
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
const parts = body.parts
|
|
310
|
+
if (!Array.isArray(parts) || parts.length !== partCount(upload)) throw invalidUpload()
|
|
311
|
+
const listed: BlobUploadedPart[] = []
|
|
312
|
+
for (const [at, part] of parts.entries()) {
|
|
313
|
+
if (!isObject(part) || part.partNumber !== at + 1 || typeof part.etag !== "string" || part.etag === "")
|
|
314
|
+
throw invalidUpload()
|
|
315
|
+
listed.push({ partNumber: at + 1, etag: part.etag })
|
|
316
|
+
}
|
|
317
|
+
return Response.json(await backend.multipart.complete(upload.pathname, upload.uploadId, listed))
|
|
318
|
+
}
|
|
319
|
+
}
|