Skip to content

archive ​

@c9up/archive: file storage on named disks: a local driver with HMAC-signed URLs, and S3-compatible and Google Cloud Storage drivers, behind one driver contract. Guide: Drive.

Installation ​

bash
pnpm add @c9up/archive

ream configure @c9up/archive registers the provider, writes config/archive.ts and adds DRIVE_DISK=fs to .env. driveFake in @c9up/archive/testing needs @c9up/helix; the template helpers need @c9up/inker (both optional peers).

Entry points ​

ImportContents
@c9up/archiveDriveManager, StorageManager, defineConfig, services, the three drivers, DriveFile, DriveDirectory, StaticMiddleware, createSignedRouteHandler, errors, types
@c9up/archive/providerArchiveProvider (default export)
@c9up/archive/services/mainThe default disk, a StorageManager (default export), setStorage, setStorageResolver, getStorage, clearStorage
@c9up/archive/signed-routecreateSignedRouteHandler and its types
@c9up/archive/testingFakeStorage, FakeStorageManager, driveFake
@c9up/archive/configureconfigure(codemods), run by ream configure

Exports ​

@c9up/archive ​

ExportKindDescription
DriveManagerclassThe configured disks, built on first use; can swap a disk for a fake.
StorageManagerclassOne disk: every key normalized and checked before its driver sees it.
defineConfigfunctiondefineConfig<T extends DriveConfig | ArchiveConfig>(config: T): T.
servicesconstDisk factories: fs(options?: FsServiceOptions), s3(config: S3Config), gcs(config: GcsConfig).
LocalDriverclassFiles under a root directory; signed URLs served by the signed route. new LocalDriver(root: string, options?: LocalDriverOptions).
S3DriverclassAny S3-compatible service. new S3Driver(config: S3Config).
GcsDriverclassGoogle Cloud Storage with a service account. new GcsDriver(config: GcsConfig).
DriveFileclassA handle on one file, read only when a method asks.
DriveDirectoryclassA directory entry of listAll(): { isFile: false; isDirectory: true; name; prefix }.
StaticMiddlewareclassServes a directory under a URL prefix, with ETag and Last-Modified. Dot-files are not served by default. new StaticMiddleware(config: StaticConfig).
createSignedRouteHandlerfunctioncreateSignedRouteHandler(options: SignedRouteOptions): middleware that verifies the local disk's signed URLs and serves the file.
errorsnamespaceThe package's errors, one class per code, see Errors
DriveConfiginterface{ default: string; services: Record<string, DriveServiceFactory> }.
ArchiveConfiginterfaceThe single-disk shape: { driver: 'local' | 's3' | 'gcs'; local?: { root; signingSecret?; routeBasePath?; visibility? }; s3?: S3Config; gcs?: GcsConfig }. Run as one disk named default.
DriveServiceFactorytype() => StorageDriver.
FsServiceOptionsinterface{ location?: string; root?: string; signingSecret?: string | ReleasableSecret; routeBasePath?: string; visibility: Visibility }.
LocalDriverOptionsinterface{ signingSecret?: string | ReleasableSecret; routeBasePath?: string; visibility?: Visibility }. visibility defaults to 'public' here.
S3Configinterface{ bucket; region?; endpoint?; accessKeyId; secretAccessKey; publicUrl?; requestTimeoutMs? }.
GcsConfiginterface{ bucket; serviceAccount: GcsServiceAccount; publicUrl?; requestTimeoutMs? }.
GcsServiceAccountinterface{ client_email: string; private_key: string; project_id?: string }.
StorageDriverinterfaceThe driver contract: every method of the table below.
Visibilitytype'public' | 'private'.
WriteOptionsinterface{ visibility?; contentType?; cacheControl?; contentDisposition?; contentLength? }.
PutStreamOptionsinterface{ visibility?: Visibility; contentType?: string; contentLength?: number }.
SignedUrlOptionsinterface{ expiresIn?: number | string; contentType?: string; contentDisposition?: string }. expiresIn in seconds or as '30mins'; default 300, at most 604800.
Metadatainterface{ size; contentLength; mimeType; contentType; lastModified: Date; etag; visibility }.
StorageEntryinterface{ path: string; size: number; lastModified: Date }.
ListAllOptionsinterface{ recursive?: boolean; paginationToken?: string }.
ListAllResultinterface{ paginationToken?: string; objects: Iterable<DriveFile | DriveDirectory> }.
FileSnapshotinterface{ key; name; contentLength; contentType?; lastModified: string; etag }.
MoveToDiskOptionsinterfaceWriteOptions & { moveAs?: 'stream' | 'buffer' }; 'stream' by default.
ReleasableSecretinterface{ release(): string }.
StaticConfiginterface{ root: string; prefix?: string; maxAge?: number; extensions?: string[]; dotFiles?: DotFilesPolicy }.
DotFilesPolicytype'allow' | 'deny' | 'ignore'.
StaticMiddlewareHttpContext / StaticMiddlewareResponseinterfaceThe slice of the HTTP context the static middleware uses.
SignedRouteOptionsinterface{ storage: StorageManager; driver: LocalDriver; prefix?: string }.
SignedRouteHttpContext / SignedRouteResponseinterfaceThe slice of the HTTP context the signed route uses.

@c9up/archive/provider ​

ExportKindDescription
default (ArchiveProvider)providerregister() binds the DriveManager and the default disk, both built on first use from the archive config (a local disk on ./storage without one); boot() seats the disk on services/main, adds moveToDisk() to ream's uploaded files and, when the app renders with inker, publishes the driveUrl and driveSignedUrl template helpers.
ArchiveAppContextinterface{ container; config; usingInker? }: the host the provider needs.

The provider adds to ream's MultipartFile:

ts
moveToDisk(key: string, disk?: string, options?: MoveToDiskOptions): Promise<void>
moveToDisk(key: string, options?: MoveToDiskOptions): Promise<void>

@c9up/archive/services/main ​

ExportKindDescription
defaultconstThe default disk; a member read before the provider booted throws.
setStoragefunctionsetStorage(value: StorageManager): void.
setStorageResolverfunctionsetStorageResolver(factory: () => StorageManager): void: build the disk on first read.
getStoragefunctiongetStorage(): StorageManager | undefined.
clearStoragefunctionclearStorage(): void.

@c9up/archive/testing ​

ExportKindDescription
FakeStorageclassAn in-memory StorageDriver with clear(), reset(), dump(), getStored() and the assertions below.
FakeStorageManagerclassA StorageManager on a FakeStorage, what drive.fake() returns.
driveFakefunctiondriveFake(drive: FakeableDrive): a helix plugin that sets ctx.drive to a fake disk for each test and restores the real one after it.
FakeStoragePredicateinterface{ contentContaining?: string; mimeType?: string }.
FakeStoragePredicateArgtypeFakeStoragePredicate | ((entry: { path: string; content: Buffer; mimeType: string }) => boolean).
FakeableDriveinterface{ fake(service?: string): FakeStorageManager; restore(service?: string): void }.
DriveHost / DriveContexttypeThe slices of helix's plugin API and test context the plugin uses.
MemberSignatureDescription
assertExistsassertExists(paths: string | string[]): voidThrows an AssertionError unless every path exists.
assertMissingassertMissing(paths: string | string[]): voidThrows unless none exists.
assertStoredassertStored(path: string, predicate?: FakeStoragePredicateArg): voidThrows unless a stored file matches.
assertNotStoredassertNotStored(path: string, predicate?: FakeStoragePredicateArg): voidThrows if one matches.
getStoredgetStored(): Array<{ path; content: Buffer; mimeType; visibility }>Copies of the stored files.
clearclear(): voidWipe the fake.

DriveManager ​

new DriveManager(config: DriveConfig); throws E_ARCHIVE_UNKNOWN_DISK when default is not a declared service.

MemberSignatureDescription
useuse(service?: string): StorageManagerThe named disk (default one without a name), built once; its fake while one is active.
fakefake(service?: string): FakeStorageManagerSwap a disk for an in-memory fake.
restorerestore(service?: string): voidPut the real disk back.

StorageManager ​

new StorageManager(driver: StorageDriver). The driver contract has the same methods, minus file, fromSnapshot, copyFromFs, moveFromFs and the aliases. Every operation but list / listAll wraps a driver failure in its own E_CANNOT_* error (see Errors), the driver's error as cause; a refused key keeps its own code.

MemberSignatureDescription
putput(filePath: string, content: Buffer | string, options?: WriteOptions): Promise<void>Write a file.
putStreamputStream(filePath: string, readable: NodeJS.ReadableStream, options?: PutStreamOptions): Promise<void>Write from a stream.
copyFromFs / moveFromFscopyFromFs(source: string | URL, destination: string, options?: WriteOptions): Promise<void>Copy (or move) a file of the local filesystem onto the disk. options.visibility applies, as on put.
getget(filePath: string): Promise<Buffer | null>Contents, null when absent.
getBytes / getArrayBuffergetBytes(filePath: string): Promise<Uint8Array>Contents; an absent file throws E_CANNOT_READ_FILE, E_ARCHIVE_NOT_FOUND as its cause.
getStreamgetStream(filePath: string): Promise<NodeJS.ReadableStream>An absent file throws E_CANNOT_READ_FILE, E_ARCHIVE_NOT_FOUND as its cause.
existsexists(filePath: string): Promise<boolean>
deletedelete(filePath: string): Promise<boolean>
deleteAlldeleteAll(prefix: string): Promise<void>Every file under the directory prefix names: 'users/1' and 'users/1/' delete users/1/…, never users/10/…. '' is the whole disk.
copy / movecopy(from: string, to: string, options?: WriteOptions): Promise<void>Within the disk. Both keep the source's visibility unless options.visibility is given.
url / getUrlurl(filePath: string): Promise<string>Public URL for a public file, signed URL for a private one.
publicUrlpublicUrl(filePath: string): stringUnsigned URL, visibility ignored.
getSignedUrlgetSignedUrl(filePath: string, options?: SignedUrlOptions): string | Promise<string>Time-boxed read URL.
getSignedUploadUrlgetSignedUploadUrl(filePath: string, options?: SignedUrlOptions): string | Promise<string>Time-boxed upload URL; cloud disks only.
getMetadata / getMetaDatagetMetadata(filePath: string): Promise<Metadata>An absent file throws E_CANNOT_GET_METADATA, E_ARCHIVE_NOT_FOUND as its cause.
getVisibility / setVisibilitysetVisibility(filePath: string, visibility: Visibility): Promise<void>
listlist(prefix: string): AsyncIterable<StorageEntry>Every file under the directory prefix names (same rule as deleteAll), paged lazily.
listAlllistAll(prefix: string, options?: ListAllOptions): Promise<ListAllResult>One page of files and directories.
filefile(key: string): DriveFileA handle, nothing fetched.
fromSnapshotfromSnapshot(snapshot: FileSnapshot): DriveFileA handle rebuilt from a stored snapshot.

LocalDriver adds getRouteBasePath(): string and getSigningSecret(): string | null.

DriveFile ​

MemberSignatureDescription
key / namekey: stringThe key, and its last segment.
exists / get / getBytes / getArrayBuffer / getStreamas on the disk
getMetaData / getVisibilityas on the disk
getUrl / getSignedUrl / getSignedUploadUrlas on the disk
toSnapshottoSnapshot(): Promise<FileSnapshot>Data to store and rebuild the handle from.

Configuration ​

config/archive.ts, read under the archive key.

OptionTypeDefaultDescription
defaultstring—The disk use() returns without a name. The generated config reads DRIVE_DISK (fs when unset).
servicesRecord<string, DriveServiceFactory>—Named disks, built on first use.
services.fs({ location })string'./storage'Root directory (root is accepted too).
services.fs({ signingSecret })string | ReleasableSecretnoneEnables getSignedUrl on the local disk; at least 16 characters.
services.fs({ routeBasePath })string'/storage'URL path the local disk's URLs are built on.
services.fs({ visibility })'public' | 'private'required'private': every file of the disk is private, whatever a write asks; getUrl() signs, and the signed route refuses every unsigned request. 'public': a file written without a visibility is public, and put(…, { visibility: 'private' }) or setVisibility() makes one private.
S3Config.requestTimeoutMs / GcsConfig.requestTimeoutMsnumber30000Longest silence from the provider during a request; 0 disables it.
StaticConfig.prefixstring'/static'URL prefix of the static middleware.
StaticConfig.maxAgenumber0max-age in seconds.
StaticConfig.dotFiles'ignore' | 'deny' | 'allow''ignore'A path with a segment starting with . (.vite/manifest.json, %2Eenv once decoded): 'ignore' passes it to the next middleware, 'deny' answers 403, 'allow' serves it.

Container bindings ​

TokenResolves to
DriveManager (class)The DriveManager
'archive.drive'The same DriveManager
'drive'The same DriveManager
StorageManager (class)The default disk
'archive.storage'The default disk
'storage'The default disk

The string tokens are typed on ContainerBindings once @c9up/archive is imported.

Errors ​

CodeRaised when
E_ARCHIVE_INVALID_SIGNATUREA signed URL's signature is missing a part, malformed or does not match (403).
E_ARCHIVE_EXPIRED_SIGNATUREA signed URL has expired (403).
E_ARCHIVE_ACCESS_DENIEDAn unsigned request asked for anything but a stored public file: a private file, a name that is not stored, any file of a private disk (403).
E_ARCHIVE_INVALID_KEYThe signed route refused the path (403); also thrown for a key naming a visibility marker, or a moveToDisk() key that is not a string.
E_ARCHIVE_NOT_FOUNDNo file under the key (status 404). A disk operation hands it on as the cause of its E_CANNOT_* error.
E_CANNOT_WRITE_FILEput, putStream, copyFromFs or moveFromFs could not write the file; the driver's error is the cause.
E_CANNOT_READ_FILEget, getBytes, getArrayBuffer or getStream could not read the file, an absent one included (cause: E_ARCHIVE_NOT_FOUND); get answers null for an absent file instead.
E_CANNOT_DELETE_FILEdelete failed; the driver's error is the cause.
E_CANNOT_DELETE_DIRECTORYdeleteAll failed; the driver's error is the cause.
E_CANNOT_COPY_FILEcopy failed, a missing source included; the driver's error is the cause.
E_CANNOT_MOVE_FILEmove failed, a missing source included; the driver's error is the cause.
E_CANNOT_CHECK_FILE_EXISTENCEexists could not tell; an absent file answers false instead.
E_CANNOT_GET_METADATAgetMetadata / getMetaData or getVisibility failed, an absent file included (cause: E_ARCHIVE_NOT_FOUND).
E_CANNOT_SET_VISIBILITYsetVisibility failed; the driver's error is the cause.
E_CANNOT_GENERATE_URLurl / getUrl, publicUrl, getSignedUrl or getSignedUploadUrl could not build the URL (cause: E_ARCHIVE_SIGNING_DISABLED, E_ARCHIVE_SIGNED_UPLOAD_UNSUPPORTED, E_ARCHIVE_INVALID_EXPIRY, …).
E_CANNOT_SERVE_FILEThe signed-URL route could not serve a file for a reason other than its absence (which answers 404); the failure is the cause.
E_ARCHIVE_PATH_TRAVERSAL_DETECTEDA local path resolves outside the disk root, or through a link that points outside it.
E_UNALLOWED_CHARACTERSA key holds a control character, a backslash or an encoded separator.
E_PATH_TRAVERSAL_DETECTEDA key has a dot-only segment such as ...
E_INVALID_KEYA key is empty, or only separators, once normalised.
E_ARCHIVE_INVALID_EXPIRYexpiresIn is not a positive duration within bounds.
E_ARCHIVE_SIGNING_DISABLEDgetSignedUrl() on a local disk without signingSecret.
E_ARCHIVE_WEAK_SIGNING_SECRETThe local signingSecret is shorter than 16 characters.
E_ARCHIVE_SIGNED_UPLOAD_UNSUPPORTEDgetSignedUploadUrl() on a local disk.
E_ARCHIVE_INVALID_HEADER_VALUEA header value to sign holds a control character.
E_ARCHIVE_INVALID_ROUTE_BASE_PATHrouteBasePath is not an absolute URL path.
E_ARCHIVE_PREFIX_MISMATCHcreateSignedRouteHandler() got a prefix other than the disk's routeBasePath.
E_ARCHIVE_VISIBILITY_CORRUPTA file's visibility record cannot be read.
E_ARCHIVE_VISIBILITY_MOVE_FAILEDmove() moved the file but could not write its visibility.
E_ARCHIVE_INVALID_MOVE_OPTIONSmoveToDisk() got options it cannot use.
E_ARCHIVE_MULTIPART_NOT_MACROABLEThe installed ream cannot receive moveToDisk().
E_ARCHIVE_REQUEST_TIMEOUTThe storage provider stayed silent past requestTimeoutMs.
E_ARCHIVE_UNEXPECTED_RESPONSEThe storage provider answered something archive cannot use.
E_ARCHIVE_UNKNOWN_DISKA disk name, or the default disk, is not configured.
E_ARCHIVE_INVALID_DRIVERdriver is not 'local', 's3' or 'gcs'.
E_ARCHIVE_CONFIG_MISSINGThe driver is s3 or gcs and its section is missing.
E_ARCHIVE_PROVIDER_NOT_REGISTEREDboot() ran before register().
E_ARCHIVE_TEMPLATE_ENGINEThe template helpers cannot be published on inker.
E_ARCHIVE_REMOTE_FAILEDS3 or GCS refused a request or reported a failure; the provider's HTTP status is in providerStatus, while status stays 500.
E_ARCHIVE_INVALID_DRIVER_CONFIGS3Driver got neither region nor endpoint, GcsDriver lacks bucket or the service account's client_email / private_key, or a local disk's visibility is neither 'public' nor 'private'.
E_ARCHIVE_CONTENT_LENGTH_EXCEEDEDputStream() read more bytes than its declared contentLength.
E_ARCHIVE_INVALID_STATIC_PREFIXStaticMiddleware was given an empty prefix.
E_ARCHIVE_NOT_BOOTEDThe storage service was read before ArchiveProvider booted.
E_ARCHIVE_INVALID_PREDICATEA fake assertion got an empty contentContaining, which would match every file.
E_ARCHIVE_INTERNALAn internal invariant broke: a bug in archive.

Each code is a class of the errors namespace and a @c9up/flare Exception, with status 500 unless the table says otherwise: branch on error.code or on error instanceof errors.E_*. The advice an error carries is in help; for E_UNALLOWED_CHARACTERS, help names the refused character. A fake's assertExists(), assertMissing(), assertStored() and assertNotStored() throw node:assert's AssertionError.

Migration ​

  • services.fs() now requires visibility. Add visibility: 'public' to keep the old behaviour, or visibility: 'private' to sign every file of the disk.
  • copyFromFs(), moveFromFs() and putStream() now apply options.visibility. A file written with visibility: 'private' used to land public on the local disk: check those files with getVisibility() and call setVisibility(key, 'private') where needed.
  • copy() now gives the copy the source's visibility. The copy of a private file is private; pass { visibility: 'public' } to make it public.
  • deleteAll(prefix), list(prefix) and listAll(prefix, { recursive: true }) now read prefix as a directory: 'users/1' no longer reaches users/10/…. To match a part of a name, list the parent directory and filter the keys.
  • A local signed URL now signs the disk's routeBasePath with the key. URLs signed before the update stop working (they expire within 7 days anyway): sign them again.
  • The signed route answers an unsigned request for a name that is not stored with 403 E_ARCHIVE_ACCESS_DENIED, as it answers a private file. It no longer passes it to the next middleware.
  • copy(), and move() across two devices, now refuse a link at the target or the source, as put() and get() do.
  • StaticMiddleware no longer serves dot-files: set dotFiles: 'allow' to serve them again.
  • The signed route and StaticMiddleware now send charset=utf-8 with a text type (text/html; charset=utf-8).
  • DriveConfig has no fakes key any more. fakes.location was accepted and never read: drive.fake() keeps its files in memory. Remove fakes from config/archive.ts; TypeScript now refuses it.
  • ArchiveError is gone: test error.code, or error instanceof errors.E_ARCHIVE_* with import { errors } from '@c9up/archive'.
  • ArchiveRemoteError becomes errors.E_ARCHIVE_REMOTE_FAILED; providerStatus is unchanged.
  • error.hint becomes error.help.
  • The key refusals use new codes: E_ARCHIVE_UNALLOWED_CHARACTERS becomes E_UNALLOWED_CHARACTERS; a .. segment raises E_PATH_TRAVERSAL_DETECTED and an empty key E_INVALID_KEY, where both raised E_ARCHIVE_PATH_TRAVERSAL_DETECTED / E_ARCHIVE_INVALID_KEY before.
  • E_ARCHIVE_NOT_FOUND now has status 404.
  • Each disk operation now wraps a driver failure in its own error, the driver's as cause: E_CANNOT_WRITE_FILE, E_CANNOT_READ_FILE, E_CANNOT_DELETE_FILE, E_CANNOT_DELETE_DIRECTORY, E_CANNOT_COPY_FILE, E_CANNOT_MOVE_FILE, E_CANNOT_CHECK_FILE_EXISTENCE, E_CANNOT_GET_METADATA, E_CANNOT_SET_VISIBILITY, E_CANNOT_GENERATE_URL (status 500). E_ARCHIVE_NOT_FOUND, E_ARCHIVE_REMOTE_FAILED and errno errors now reach you as that cause: read error.cause where you tested the error itself. A refused key keeps its own code.
  • The signed-URL route throws E_CANNOT_SERVE_FILE for a file it cannot serve, other than an absent one.
  • The key refusals read as the storage library writes them: The key "a\\b" has unallowed characters (the refused character is in help), Path traversal segment detected in key "../a", Invalid key "//". After normalization results in an empty string.
  • E_ARCHIVE_ASSERTION_FAILED is gone: assertStored() / assertNotStored() throw node:assert's AssertionError, as assertExists() / assertMissing() already did.

See also ​