foldkit-media 0.6.0 → 0.7.0
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/README.md +200 -7
- package/dist/browser/index.d.ts +2 -2
- package/dist/browser/index.js +2 -2
- package/dist/browser/index.js.map +1 -1
- package/dist/browser/upload.d.ts +32 -2
- package/dist/browser/upload.d.ts.map +1 -1
- package/dist/browser/upload.js +52 -25
- package/dist/browser/upload.js.map +1 -1
- package/dist/file.d.ts +16 -0
- package/dist/file.d.ts.map +1 -0
- package/dist/file.js +18 -0
- package/dist/file.js.map +1 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/server/diagnostics.d.ts +9 -1
- package/dist/server/diagnostics.d.ts.map +1 -1
- package/dist/server/diagnostics.js +7 -1
- package/dist/server/diagnostics.js.map +1 -1
- package/dist/server/fetch.d.ts +9 -2
- package/dist/server/fetch.d.ts.map +1 -1
- package/dist/server/fetch.js +7 -5
- package/dist/server/fetch.js.map +1 -1
- package/dist/server/fileRules.d.ts +34 -0
- package/dist/server/fileRules.d.ts.map +1 -0
- package/dist/server/fileRules.js +78 -0
- package/dist/server/fileRules.js.map +1 -0
- package/dist/server/fileStore.d.ts +68 -0
- package/dist/server/fileStore.d.ts.map +1 -0
- package/dist/server/fileStore.js +95 -0
- package/dist/server/fileStore.js.map +1 -0
- package/dist/server/files.d.ts +88 -0
- package/dist/server/files.d.ts.map +1 -0
- package/dist/server/files.js +195 -0
- package/dist/server/files.js.map +1 -0
- package/dist/server/index.d.ts +5 -2
- package/dist/server/index.js +3 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import * as Variant from "./variant.js";
|
|
2
2
|
import { Focus, HashedAsset, ImageAsset, Placeholder, isHashed } from "./asset.js";
|
|
3
|
+
import { FileAsset, FileKey } from "./file.js";
|
|
3
4
|
import { Inspector, describe } from "./describe.js";
|
|
4
5
|
import { Format, mimeType } from "./format.js";
|
|
5
6
|
import * as Icon from "./icon.js";
|
|
@@ -7,4 +8,4 @@ import * as Layout from "./layout.js";
|
|
|
7
8
|
import * as Picture from "./picture.js";
|
|
8
9
|
import * as Provider from "./provider.js";
|
|
9
10
|
import * as Widths from "./widths.js";
|
|
10
|
-
export { Focus, Format, HashedAsset, Icon, ImageAsset, Inspector, Layout, Picture, Placeholder, Provider, Variant, Widths, describe, isHashed, mimeType };
|
|
11
|
+
export { FileAsset, FileKey, Focus, Format, HashedAsset, Icon, ImageAsset, Inspector, Layout, Picture, Placeholder, Provider, Variant, Widths, describe, isHashed, mimeType };
|
|
@@ -44,10 +44,18 @@ export interface RequestDefect extends Diagnostic {
|
|
|
44
44
|
readonly cause: Cause.Cause<unknown>;
|
|
45
45
|
}
|
|
46
46
|
/** Every diagnostic the media server reports. */
|
|
47
|
-
export type MediaDiagnostic = StoreFailed | AdmissionFailed | ImageFailed | FactsUnanswered | RequestDefect;
|
|
47
|
+
export type MediaDiagnostic = StoreFailed | AdmissionFailed | ImageFailed | FactsUnanswered | RequestDefect | OwnerMissing;
|
|
48
48
|
export declare const storeFailed: (facts: Pick<StoreFailed, 'store' | 'operation' | 'key' | 'cause'>) => StoreFailed;
|
|
49
49
|
export declare const admissionFailed: (facts: Pick<AdmissionFailed, 'limiter' | 'client' | 'cause'>) => AdmissionFailed;
|
|
50
50
|
export declare const imageFailed: (step: ImageFailed['step'], cause: unknown) => ImageFailed;
|
|
51
51
|
export declare const factsUnanswered: (url: string, reason: string) => FactsUnanswered;
|
|
52
52
|
export declare const requestDefect: (cause: Cause.Cause<unknown>) => RequestDefect;
|
|
53
|
+
/**
|
|
54
|
+
* A `FileUploadPolicy` answered an empty owner, so the upload was refused:
|
|
55
|
+
* with one owner for every visitor, anyone could claim anyone's upload.
|
|
56
|
+
*/
|
|
57
|
+
export interface OwnerMissing extends Diagnostic {
|
|
58
|
+
readonly _tag: 'OwnerMissing';
|
|
59
|
+
}
|
|
60
|
+
export declare const ownerMissing: OwnerMissing;
|
|
53
61
|
//# sourceMappingURL=diagnostics.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"diagnostics.d.ts","names":[],"sources":["../../src/server/diagnostics.ts"],"mappings":";;;;;;;iBAiBiB,oBAAoB;WAC1B;;WAEA;WACA;WACA;WACA;;;iBAIM,wBAAwB;WAC9B;;WAEA;WACA;WACA;;;;;;;;iBASM,oBAAoB;WAC1B;WACA;WACA;;;iBAIM,wBAAwB;WAC9B;WACA;WACA;;;iBAIM,sBAAsB;WAC5B;WACA,OAAO,MAAM;;;YAIZ,kBACR,cACA,kBACA,cACA,kBACA;qBAES,cAAW,OACf,KAAK,0DACX;qBAQU,kBAAe,OACnB,KAAK,qDACX;qBAQU,cAAW,MAAU,qBAAmB,mBAAmB;qBAS3D,kBAAe,aAAe,mBAAmB;qBASjD,gBAAa,OAAW,MAAM,mBAAiB"}
|
|
1
|
+
{"version":3,"file":"diagnostics.d.ts","names":[],"sources":["../../src/server/diagnostics.ts"],"mappings":";;;;;;;iBAiBiB,oBAAoB;WAC1B;;WAEA;WACA;WACA;WACA;;;iBAIM,wBAAwB;WAC9B;;WAEA;WACA;WACA;;;;;;;;iBASM,oBAAoB;WAC1B;WACA;WACA;;;iBAIM,wBAAwB;WAC9B;WACA;WACA;;;iBAIM,sBAAsB;WAC5B;WACA,OAAO,MAAM;;;YAIZ,kBACR,cACA,kBACA,cACA,kBACA,gBACA;qBAES,cAAW,OACf,KAAK,0DACX;qBAQU,kBAAe,OACnB,KAAK,qDACX;qBAQU,cAAW,MAAU,qBAAmB,mBAAmB;qBAS3D,kBAAe,aAAe,mBAAmB;qBASjD,gBAAa,OAAW,MAAM,mBAAiB;;;;;iBAY3C,qBAAqB;WAC3B;;qBAGE,cAAc"}
|
|
@@ -45,6 +45,12 @@ const requestDefect = (cause) => ({
|
|
|
45
45
|
message: `a media request failed on this side, and its caller was answered 500\n${Cause.pretty(cause)}`,
|
|
46
46
|
cause
|
|
47
47
|
});
|
|
48
|
-
|
|
48
|
+
const ownerMissing = {
|
|
49
|
+
_tag: "OwnerMissing",
|
|
50
|
+
source,
|
|
51
|
+
level: "error",
|
|
52
|
+
message: "the FileUploadPolicy admitted an upload with an empty owner, so it was refused 403: answer each uploader’s stable id."
|
|
53
|
+
};
|
|
54
|
+
export { admissionFailed, factsUnanswered, imageFailed, ownerMissing, requestDefect, storeFailed };
|
|
49
55
|
|
|
50
56
|
//# sourceMappingURL=diagnostics.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"diagnostics.js","names":[],"sources":["../../src/server/diagnostics.ts"],"sourcesContent":["/**\n * What the media server answers past without telling the caller why: a store\n * or rate limiter that broke and was worked around, an image it could not\n * transform or inspect, facts it could not read, and a defect answered 500.\n * Each is reported through `Diagnostics.report`, so a host's log (a Worker's\n * `wrangler tail`) shows it by default.\n */\nimport { Cause } from 'effect'\nimport type { Diagnostic } from 'foldkit-surface'\n\nconst source = 'foldkit-media'\n\n/**\n * A store that failed and was worked around: a read is taken as a miss and a\n * write is dropped, since what it keeps (a variant, an edge copy, an\n * original's facts) is made again when missed.\n */\nexport interface StoreFailed extends Diagnostic {\n readonly _tag: 'StoreFailed'\n /** `variants` (the `Variants` store), `edge` (the Workers cache in front of it), `facts` (`factsOf`'s `cache`). */\n readonly store: 'variants' | 'edge' | 'facts'\n readonly operation: 'read' | 'write'\n readonly key: string\n readonly cause: unknown\n}\n\n/** A rate limiter that failed, so the request was admitted unlimited. */\nexport interface AdmissionFailed extends Diagnostic {\n readonly _tag: 'AdmissionFailed'\n /** `RateLimiter` (`admissionRateLimiter`) or `binding` (`admissionRateLimit`). */\n readonly limiter: 'RateLimiter' | 'binding'\n readonly client: string\n readonly cause: unknown\n}\n\n/**\n * An image the transformer could not transform, or the inspector could not\n * read, answered `TransformFailed` with no cause. An inspection is most often\n * a file that is no image, so it is a warning; a transform, of an original\n * already taken in, is an error.\n */\nexport interface ImageFailed extends Diagnostic {\n readonly _tag: 'ImageFailed'\n readonly step: 'transform' | 'inspect'\n readonly cause: unknown\n}\n\n/** The facts route answered `Unavailable`, whose reason the caller is not told. */\nexport interface FactsUnanswered extends Diagnostic {\n readonly _tag: 'FactsUnanswered'\n readonly url: string\n readonly reason: string\n}\n\n/** A defect `serveFetch` answered 500, which its caller is told nothing of. */\nexport interface RequestDefect extends Diagnostic {\n readonly _tag: 'RequestDefect'\n readonly cause: Cause.Cause<unknown>\n}\n\n/** Every diagnostic the media server reports. */\nexport type MediaDiagnostic =\n | StoreFailed\n | AdmissionFailed\n | ImageFailed\n | FactsUnanswered\n | RequestDefect\n\nexport const storeFailed = (\n facts: Pick<StoreFailed, 'store' | 'operation' | 'key' | 'cause'>,\n): StoreFailed => ({\n _tag: 'StoreFailed',\n source,\n level: 'error',\n message: `the ${facts.store} store failed a ${facts.operation} of ${facts.key} (${String(facts.cause)}), ${facts.operation === 'read' ? 'which was taken as a miss' : 'which was dropped'}: the request was answered, and what it keeps is made again.`,\n ...facts,\n})\n\nexport const admissionFailed = (\n facts: Pick<AdmissionFailed, 'limiter' | 'client' | 'cause'>,\n): AdmissionFailed => ({\n _tag: 'AdmissionFailed',\n source,\n level: 'error',\n message: `the ${facts.limiter === 'binding' ? 'rate limit binding' : 'RateLimiter'} failed (${String(facts.cause)}), so ${facts.client} was admitted with no limit.`,\n ...facts,\n})\n\nexport const imageFailed = (step: ImageFailed['step'], cause: unknown): ImageFailed => ({\n _tag: 'ImageFailed',\n source,\n level: step === 'inspect' ? 'warning' : 'error',\n message: `Media.${step} failed (${String(cause)}), and was answered TransformFailed${step === 'inspect' ? ': most often a file that is no image' : ''}.`,\n step,\n cause,\n})\n\nexport const factsUnanswered = (url: string, reason: string): FactsUnanswered => ({\n _tag: 'FactsUnanswered',\n source,\n level: 'warning',\n message: `the facts of ${url} were answered Unavailable: ${reason}.`,\n url,\n reason,\n})\n\nexport const requestDefect = (cause: Cause.Cause<unknown>): RequestDefect => ({\n _tag: 'RequestDefect',\n source,\n level: 'error',\n message: `a media request failed on this side, and its caller was answered 500\\n${Cause.pretty(cause)}`,\n cause,\n})\n"],"mappings":";;;;;;;;;AAUA,MAAM,SAAS;
|
|
1
|
+
{"version":3,"file":"diagnostics.js","names":[],"sources":["../../src/server/diagnostics.ts"],"sourcesContent":["/**\n * What the media server answers past without telling the caller why: a store\n * or rate limiter that broke and was worked around, an image it could not\n * transform or inspect, facts it could not read, and a defect answered 500.\n * Each is reported through `Diagnostics.report`, so a host's log (a Worker's\n * `wrangler tail`) shows it by default.\n */\nimport { Cause } from 'effect'\nimport type { Diagnostic } from 'foldkit-surface'\n\nconst source = 'foldkit-media'\n\n/**\n * A store that failed and was worked around: a read is taken as a miss and a\n * write is dropped, since what it keeps (a variant, an edge copy, an\n * original's facts) is made again when missed.\n */\nexport interface StoreFailed extends Diagnostic {\n readonly _tag: 'StoreFailed'\n /** `variants` (the `Variants` store), `edge` (the Workers cache in front of it), `facts` (`factsOf`'s `cache`). */\n readonly store: 'variants' | 'edge' | 'facts'\n readonly operation: 'read' | 'write'\n readonly key: string\n readonly cause: unknown\n}\n\n/** A rate limiter that failed, so the request was admitted unlimited. */\nexport interface AdmissionFailed extends Diagnostic {\n readonly _tag: 'AdmissionFailed'\n /** `RateLimiter` (`admissionRateLimiter`) or `binding` (`admissionRateLimit`). */\n readonly limiter: 'RateLimiter' | 'binding'\n readonly client: string\n readonly cause: unknown\n}\n\n/**\n * An image the transformer could not transform, or the inspector could not\n * read, answered `TransformFailed` with no cause. An inspection is most often\n * a file that is no image, so it is a warning; a transform, of an original\n * already taken in, is an error.\n */\nexport interface ImageFailed extends Diagnostic {\n readonly _tag: 'ImageFailed'\n readonly step: 'transform' | 'inspect'\n readonly cause: unknown\n}\n\n/** The facts route answered `Unavailable`, whose reason the caller is not told. */\nexport interface FactsUnanswered extends Diagnostic {\n readonly _tag: 'FactsUnanswered'\n readonly url: string\n readonly reason: string\n}\n\n/** A defect `serveFetch` answered 500, which its caller is told nothing of. */\nexport interface RequestDefect extends Diagnostic {\n readonly _tag: 'RequestDefect'\n readonly cause: Cause.Cause<unknown>\n}\n\n/** Every diagnostic the media server reports. */\nexport type MediaDiagnostic =\n | StoreFailed\n | AdmissionFailed\n | ImageFailed\n | FactsUnanswered\n | RequestDefect\n | OwnerMissing\n\nexport const storeFailed = (\n facts: Pick<StoreFailed, 'store' | 'operation' | 'key' | 'cause'>,\n): StoreFailed => ({\n _tag: 'StoreFailed',\n source,\n level: 'error',\n message: `the ${facts.store} store failed a ${facts.operation} of ${facts.key} (${String(facts.cause)}), ${facts.operation === 'read' ? 'which was taken as a miss' : 'which was dropped'}: the request was answered, and what it keeps is made again.`,\n ...facts,\n})\n\nexport const admissionFailed = (\n facts: Pick<AdmissionFailed, 'limiter' | 'client' | 'cause'>,\n): AdmissionFailed => ({\n _tag: 'AdmissionFailed',\n source,\n level: 'error',\n message: `the ${facts.limiter === 'binding' ? 'rate limit binding' : 'RateLimiter'} failed (${String(facts.cause)}), so ${facts.client} was admitted with no limit.`,\n ...facts,\n})\n\nexport const imageFailed = (step: ImageFailed['step'], cause: unknown): ImageFailed => ({\n _tag: 'ImageFailed',\n source,\n level: step === 'inspect' ? 'warning' : 'error',\n message: `Media.${step} failed (${String(cause)}), and was answered TransformFailed${step === 'inspect' ? ': most often a file that is no image' : ''}.`,\n step,\n cause,\n})\n\nexport const factsUnanswered = (url: string, reason: string): FactsUnanswered => ({\n _tag: 'FactsUnanswered',\n source,\n level: 'warning',\n message: `the facts of ${url} were answered Unavailable: ${reason}.`,\n url,\n reason,\n})\n\nexport const requestDefect = (cause: Cause.Cause<unknown>): RequestDefect => ({\n _tag: 'RequestDefect',\n source,\n level: 'error',\n message: `a media request failed on this side, and its caller was answered 500\\n${Cause.pretty(cause)}`,\n cause,\n})\n\n/**\n * A `FileUploadPolicy` answered an empty owner, so the upload was refused:\n * with one owner for every visitor, anyone could claim anyone's upload.\n */\nexport interface OwnerMissing extends Diagnostic {\n readonly _tag: 'OwnerMissing'\n}\n\nexport const ownerMissing: OwnerMissing = {\n _tag: 'OwnerMissing',\n source,\n level: 'error',\n message:\n 'the FileUploadPolicy admitted an upload with an empty owner, so it was refused 403: answer each uploader’s stable id.',\n}\n"],"mappings":";;;;;;;;;AAUA,MAAM,SAAS;AA2Df,MAAa,eACX,WACiB;CACjB,MAAM;CACN;CACA,OAAO;CACP,SAAS,OAAO,MAAM,MAAM,kBAAkB,MAAM,UAAU,MAAM,MAAM,IAAI,IAAI,OAAO,MAAM,KAAK,EAAE,KAAK,MAAM,cAAc,SAAS,8BAA8B,oBAAoB;CAC1L,GAAG;AACL;AAEA,MAAa,mBACX,WACqB;CACrB,MAAM;CACN;CACA,OAAO;CACP,SAAS,OAAO,MAAM,YAAY,YAAY,uBAAuB,cAAc,WAAW,OAAO,MAAM,KAAK,EAAE,QAAQ,MAAM,OAAO;CACvI,GAAG;AACL;AAEA,MAAa,eAAe,MAA2B,WAAiC;CACtF,MAAM;CACN;CACA,OAAO,SAAS,YAAY,YAAY;CACxC,SAAS,SAAS,KAAK,WAAW,OAAO,KAAK,EAAE,qCAAqC,SAAS,YAAY,yCAAyC,GAAG;CACtJ;CACA;AACF;AAEA,MAAa,mBAAmB,KAAa,YAAqC;CAChF,MAAM;CACN;CACA,OAAO;CACP,SAAS,gBAAgB,IAAI,8BAA8B,OAAO;CAClE;CACA;AACF;AAEA,MAAa,iBAAiB,WAAgD;CAC5E,MAAM;CACN;CACA,OAAO;CACP,SAAS,yEAAyE,MAAM,OAAO,KAAK;CACpG;AACF;AAUA,MAAa,eAA6B;CACxC,MAAM;CACN;CACA,OAAO;CACP,SACE;AACJ"}
|
package/dist/server/fetch.d.ts
CHANGED
|
@@ -2,7 +2,9 @@ import { Layer } from "effect";
|
|
|
2
2
|
import { Inspector } from "../describe.js";
|
|
3
3
|
import { Originals, Transformer, Variants } from "./services.js";
|
|
4
4
|
import { UploadOptions, UploadPolicy, Uploads } from "./upload.js";
|
|
5
|
+
import { FileOptions, FileReadPolicy, FileUploadPolicy } from "./files.js";
|
|
5
6
|
import { Options } from "./handlers.js";
|
|
7
|
+
import { FileStore } from "./fileStore.js";
|
|
6
8
|
/** What `serveFetch` answers, each side's services built from the request's bindings. */
|
|
7
9
|
export interface FetchOptions<Env> {
|
|
8
10
|
/** `GET /_image/…`: the variants. A Worker request cannot wait on another's, so nothing coalesces. */
|
|
@@ -13,6 +15,10 @@ export interface FetchOptions<Env> {
|
|
|
13
15
|
readonly uploads?: UploadOptions & {
|
|
14
16
|
readonly layer: (env: Env) => Layer.Layer<Uploads | Inspector | UploadPolicy, unknown>;
|
|
15
17
|
};
|
|
18
|
+
/** `POST /_media/files` and `GET /_media/files/:key`: any file, kept and served back as a download. */
|
|
19
|
+
readonly files?: FileOptions & {
|
|
20
|
+
readonly layer: (env: Env) => Layer.Layer<FileStore | FileUploadPolicy | FileReadPolicy, unknown>;
|
|
21
|
+
};
|
|
16
22
|
/** Every path outside `/_image/` and `/_media/`: the application's own routes. A 404 when omitted. */
|
|
17
23
|
readonly otherwise?: (request: Request, env: Env) => Promise<Response>;
|
|
18
24
|
}
|
|
@@ -22,8 +28,9 @@ export interface FetchOptions<Env> {
|
|
|
22
28
|
* preflight, which the upload route never answers), or another path under
|
|
23
29
|
* them is a 404, and everything else goes to `otherwise`. The services are
|
|
24
30
|
* built from each environment's bindings once and kept; a layer that fails
|
|
25
|
-
* to build answers a 500. When
|
|
26
|
-
* defect answered 500 on
|
|
31
|
+
* to build answers a 500. When several layers give a `Diagnostics.Reporter`,
|
|
32
|
+
* a defect answered 500 on any side is reported to the last one's: uploads,
|
|
33
|
+
* then files, then images.
|
|
27
34
|
*/
|
|
28
35
|
export declare const serveFetch: <Env extends object>(options: FetchOptions<Env>) => ((request: Request, env: Env) => Promise<Response>);
|
|
29
36
|
//# sourceMappingURL=fetch.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch.d.ts","names":[],"sources":["../../src/server/fetch.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"fetch.d.ts","names":[],"sources":["../../src/server/fetch.ts"],"mappings":";;;;;;;;iBAaiB,aAAa;;WAEnB,SAAS,KAAK;aACZ,QAAQ,KAAK,QAAQ,MAAM,MAAM,YAAY,cAAc;;;WAG7D,UAAU;aACR,QAAQ,KAAK,QAAQ,MAAM,MAAM,UAAU,YAAY;;;WAGzD,QAAQ;aACN,QACP,KAAK,QACF,MAAM,MAAM,YAAY,mBAAmB;;;WAGzC,aAAa,SAAS,SAAS,KAAK,QAAQ,QAAQ;;;;;;;;;;;;qBAalD,aAAc,oBAAkB,SAClC,aAAa,WACnB,SAAS,SAAS,KAAK,QAAQ,QAAQ"}
|
package/dist/server/fetch.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { Layer } from "effect";
|
|
2
2
|
import * as Variant$1 from "../variant.js";
|
|
3
3
|
import { uploadLayer } from "./upload.js";
|
|
4
|
+
import { fileLayer } from "./files.js";
|
|
4
5
|
import { fetchOf, layer } from "./handlers.js";
|
|
5
6
|
// src/server/fetch.ts
|
|
6
7
|
const IMAGES = Variant$1.PATH.slice(0, Variant$1.PATH.indexOf(":"));
|
|
@@ -11,16 +12,17 @@ const UPLOADS = "/_media/";
|
|
|
11
12
|
* preflight, which the upload route never answers), or another path under
|
|
12
13
|
* them is a 404, and everything else goes to `otherwise`. The services are
|
|
13
14
|
* built from each environment's bindings once and kept; a layer that fails
|
|
14
|
-
* to build answers a 500. When
|
|
15
|
-
* defect answered 500 on
|
|
15
|
+
* to build answers a 500. When several layers give a `Diagnostics.Reporter`,
|
|
16
|
+
* a defect answered 500 on any side is reported to the last one's: uploads,
|
|
17
|
+
* then files, then images.
|
|
16
18
|
*/
|
|
17
19
|
const serveFetch = (options) => {
|
|
18
|
-
const { images, uploads, otherwise } = options;
|
|
19
|
-
if (images === void 0 && uploads === void 0) throw new Error("serveFetch: give it `images`, `uploads`, or
|
|
20
|
+
const { images, uploads, files, otherwise } = options;
|
|
21
|
+
if (images === void 0 && uploads === void 0 && files === void 0) throw new Error("serveFetch: give it `images`, `uploads`, `files`, or several");
|
|
20
22
|
const media = fetchOf((env) => Layer.mergeAll(images === void 0 ? Layer.empty : layer({
|
|
21
23
|
...images,
|
|
22
24
|
coalesce: false
|
|
23
|
-
}).pipe(Layer.provideMerge(images.layer(env))), uploads === void 0 ? Layer.empty : uploadLayer(uploads).pipe(Layer.provideMerge(uploads.layer(env)))));
|
|
25
|
+
}).pipe(Layer.provideMerge(images.layer(env))), files === void 0 ? Layer.empty : fileLayer(files).pipe(Layer.provideMerge(files.layer(env))), uploads === void 0 ? Layer.empty : uploadLayer(uploads).pipe(Layer.provideMerge(uploads.layer(env)))));
|
|
24
26
|
return (request, env) => {
|
|
25
27
|
const { pathname } = new URL(request.url);
|
|
26
28
|
if (pathname.startsWith(IMAGES) || pathname.startsWith(UPLOADS)) return media(request, env);
|
package/dist/server/fetch.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch.js","names":["Variant"],"sources":["../../src/server/fetch.ts"],"sourcesContent":["import { Layer } from 'effect'\nimport type { Inspector } from '../describe.js'\nimport * as Variant from '../variant.js'\nimport { fetchOf, layer, type Options } from './handlers.js'\nimport type { Originals, Transformer, Variants } from './services.js'\nimport { uploadLayer, type UploadOptions, type UploadPolicy, type Uploads } from './upload.js'\n\nconst IMAGES = Variant.PATH.slice(0, Variant.PATH.indexOf(':'))\nconst UPLOADS = '/_media/'\n\n/** What `serveFetch` answers, each side's services built from the request's bindings. */\nexport interface FetchOptions<Env> {\n /** `GET /_image/…`: the variants. A Worker request cannot wait on another's, so nothing coalesces. */\n readonly images?: Omit<Options, 'coalesce'> & {\n readonly layer: (env: Env) => Layer.Layer<Originals | Transformer | Variants, unknown>\n }\n /** `POST /_media/upload` and `GET /_media/facts`: originals entering. */\n readonly uploads?: UploadOptions & {\n readonly layer: (env: Env) => Layer.Layer<Uploads | Inspector | UploadPolicy, unknown>\n }\n /** Every path outside `/_image/` and `/_media/`: the application's own routes. A 404 when omitted. */\n readonly otherwise?: (request: Request, env: Env) => Promise<Response>\n}\n\n/**\n * The media server as a Worker's fetch handler. It owns `/_image/` and\n * `/_media/`: a route of either it was not given, another method (a\n * preflight, which the upload route never answers), or another path under\n * them is a 404, and everything else goes to `otherwise`. The services are\n * built from each environment's bindings once and kept; a layer that fails\n * to build answers a 500. When
|
|
1
|
+
{"version":3,"file":"fetch.js","names":["Variant"],"sources":["../../src/server/fetch.ts"],"sourcesContent":["import { Layer } from 'effect'\nimport type { Inspector } from '../describe.js'\nimport * as Variant from '../variant.js'\nimport { fileLayer, type FileOptions, type FileReadPolicy, type FileUploadPolicy } from './files.js'\nimport type { FileStore } from './fileStore.js'\nimport { fetchOf, layer, type Options } from './handlers.js'\nimport type { Originals, Transformer, Variants } from './services.js'\nimport { uploadLayer, type UploadOptions, type UploadPolicy, type Uploads } from './upload.js'\n\nconst IMAGES = Variant.PATH.slice(0, Variant.PATH.indexOf(':'))\nconst UPLOADS = '/_media/'\n\n/** What `serveFetch` answers, each side's services built from the request's bindings. */\nexport interface FetchOptions<Env> {\n /** `GET /_image/…`: the variants. A Worker request cannot wait on another's, so nothing coalesces. */\n readonly images?: Omit<Options, 'coalesce'> & {\n readonly layer: (env: Env) => Layer.Layer<Originals | Transformer | Variants, unknown>\n }\n /** `POST /_media/upload` and `GET /_media/facts`: originals entering. */\n readonly uploads?: UploadOptions & {\n readonly layer: (env: Env) => Layer.Layer<Uploads | Inspector | UploadPolicy, unknown>\n }\n /** `POST /_media/files` and `GET /_media/files/:key`: any file, kept and served back as a download. */\n readonly files?: FileOptions & {\n readonly layer: (\n env: Env,\n ) => Layer.Layer<FileStore | FileUploadPolicy | FileReadPolicy, unknown>\n }\n /** Every path outside `/_image/` and `/_media/`: the application's own routes. A 404 when omitted. */\n readonly otherwise?: (request: Request, env: Env) => Promise<Response>\n}\n\n/**\n * The media server as a Worker's fetch handler. It owns `/_image/` and\n * `/_media/`: a route of either it was not given, another method (a\n * preflight, which the upload route never answers), or another path under\n * them is a 404, and everything else goes to `otherwise`. The services are\n * built from each environment's bindings once and kept; a layer that fails\n * to build answers a 500. When several layers give a `Diagnostics.Reporter`,\n * a defect answered 500 on any side is reported to the last one's: uploads,\n * then files, then images.\n */\nexport const serveFetch = <Env extends object>(\n options: FetchOptions<Env>,\n): ((request: Request, env: Env) => Promise<Response>) => {\n const { images, uploads, files, otherwise } = options\n if (images === undefined && uploads === undefined && files === undefined) {\n throw new Error('serveFetch: give it `images`, `uploads`, `files`, or several')\n }\n // Merged, not provided: a `Diagnostics.Reporter` in a layer reaches what\n // runs around the routes too, the report of a defect answered 500. One\n // build, so a layer both sides name is made once and shared. A service\n // several layers give reaches each side's routes from its own layer, and\n // what runs around them from the layer merged last.\n const media = fetchOf<Env>(env =>\n Layer.mergeAll(\n images === undefined\n ? Layer.empty\n : layer({ ...images, coalesce: false }).pipe(Layer.provideMerge(images.layer(env))),\n files === undefined\n ? Layer.empty\n : fileLayer(files).pipe(Layer.provideMerge(files.layer(env))),\n uploads === undefined\n ? Layer.empty\n : uploadLayer(uploads).pipe(Layer.provideMerge(uploads.layer(env))),\n ),\n )\n return (request, env) => {\n const { pathname } = new URL(request.url)\n if (pathname.startsWith(IMAGES) || pathname.startsWith(UPLOADS)) return media(request, env)\n return otherwise === undefined\n ? Promise.resolve(new Response(null, { status: 404 }))\n : otherwise(request, env)\n }\n}\n"],"mappings":";;;;;;AASA,MAAM,SAASA,UAAQ,KAAK,MAAM,GAAGA,UAAQ,KAAK,QAAQ,GAAG,CAAC;AAC9D,MAAM,UAAU;;;;;;;;;;;AAgChB,MAAa,cACX,YACwD;CACxD,MAAM,EAAE,QAAQ,SAAS,OAAO,cAAc;CAC9C,IAAI,WAAW,KAAA,KAAa,YAAY,KAAA,KAAa,UAAU,KAAA,GAC7D,MAAM,IAAI,MAAM,8DAA8D;CAOhF,MAAM,QAAQ,SAAa,QACzB,MAAM,SACJ,WAAW,KAAA,IACP,MAAM,QACN,MAAM;EAAE,GAAG;EAAQ,UAAU;CAAM,CAAC,CAAC,CAAC,KAAK,MAAM,aAAa,OAAO,MAAM,GAAG,CAAC,CAAC,GACpF,UAAU,KAAA,IACN,MAAM,QACN,UAAU,KAAK,CAAC,CAAC,KAAK,MAAM,aAAa,MAAM,MAAM,GAAG,CAAC,CAAC,GAC9D,YAAY,KAAA,IACR,MAAM,QACN,YAAY,OAAO,CAAC,CAAC,KAAK,MAAM,aAAa,QAAQ,MAAM,GAAG,CAAC,CAAC,CACtE,CACF;CACA,QAAQ,SAAS,QAAQ;EACvB,MAAM,EAAE,aAAa,IAAI,IAAI,QAAQ,GAAG;EACxC,IAAI,SAAS,WAAW,MAAM,KAAK,SAAS,WAAW,OAAO,GAAG,OAAO,MAAM,SAAS,GAAG;EAC1F,OAAO,cAAc,KAAA,IACjB,QAAQ,QAAQ,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC,CAAC,IACnD,UAAU,SAAS,GAAG;CAC5B;AACF"}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { Option } from "effect";
|
|
2
|
+
/** Whether a key is one the server could have minted, and so names nothing else in a store. */
|
|
3
|
+
export declare const isFileKey: (key: string) => boolean;
|
|
4
|
+
/** Whether a decoded name is one a download may carry. */
|
|
5
|
+
export declare const isFileName: (name: string) => boolean;
|
|
6
|
+
/**
|
|
7
|
+
* The file name a client sent, percent-encoded UTF-8, if it is one a
|
|
8
|
+
* download may carry: non-empty, at most 255 bytes, and holding no control,
|
|
9
|
+
* format or separator character and no slash. A malformed encoding is none.
|
|
10
|
+
*/
|
|
11
|
+
export declare const fileNameOf: (header: string | undefined) => Option.Option<string>;
|
|
12
|
+
/**
|
|
13
|
+
* The `type/subtype` of a media type, lowercased, its parameters dropped:
|
|
14
|
+
* `Text/HTML; x=image/png` is `text/html`. Anything outside the grammar is none.
|
|
15
|
+
*/
|
|
16
|
+
export declare const mediaTypeOf: (header: string | undefined) => Option.Option<string>;
|
|
17
|
+
/** What an upload route takes: media types or `type/*` patterns, or `'*'` for any type. */
|
|
18
|
+
export type Accept = '*' | ReadonlyArray<string>;
|
|
19
|
+
/**
|
|
20
|
+
* Whether `accept` takes a parsed media type (from `mediaTypeOf`). Throws for
|
|
21
|
+
* a pattern outside the grammar, so a typo fails where the route is made
|
|
22
|
+
* rather than refusing every upload.
|
|
23
|
+
*/
|
|
24
|
+
export declare const acceptor: (accept: Accept) => ((type: string) => boolean);
|
|
25
|
+
/**
|
|
26
|
+
* `Content-Disposition: attachment` with the name twice: as RFC 6266's
|
|
27
|
+
* `filename*`, everything outside RFC 5987's attribute characters
|
|
28
|
+
* percent-encoded, and as an ASCII fallback keeping letters, digits, space,
|
|
29
|
+
* `.`, `_` and `-` (so no `"`, `\` or `%`, which Chromium decodes there).
|
|
30
|
+
*/
|
|
31
|
+
export declare const dispositionOf: (name: string) => string;
|
|
32
|
+
/** A download's headers: a file's, named, or a refusal's, with none. */
|
|
33
|
+
export declare const fileHeaders: (name: Option.Option<string>) => Readonly<Record<string, string>>;
|
|
34
|
+
//# sourceMappingURL=fileRules.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fileRules.d.ts","names":[],"sources":["../../src/server/fileRules.ts"],"mappings":";;qBAOa,YAAY;;qBAUZ,aAAU;;;;;;qBAUV,aAAU,+BAAiC,OAAO;;;;;qBAoBlD,cAAW,+BAAiC,OAAO;;YAOpD,eAAe;;;;;;qBAOd,WAAQ,QAAY,aAAW;;;;;;;qBAgC/B,gBAAa;;qBAUb,cAAW,MAAU,OAAO,mBAAiB,SAAS"}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { Option, Schema } from "effect";
|
|
2
|
+
import { FileKey } from "../file.js";
|
|
3
|
+
// src/server/fileRules.ts
|
|
4
|
+
/** Whether a key is one the server could have minted, and so names nothing else in a store. */
|
|
5
|
+
const isFileKey = Schema.is(FileKey);
|
|
6
|
+
const MAX_NAME_BYTES = 255;
|
|
7
|
+
const REFUSED_IN_NAME = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Cs}/\\]/u;
|
|
8
|
+
/** Whether a decoded name is one a download may carry. */
|
|
9
|
+
const isFileName = (name) => name.length > 0 && new TextEncoder().encode(name).length <= MAX_NAME_BYTES && !REFUSED_IN_NAME.test(name);
|
|
10
|
+
/**
|
|
11
|
+
* The file name a client sent, percent-encoded UTF-8, if it is one a
|
|
12
|
+
* download may carry: non-empty, at most 255 bytes, and holding no control,
|
|
13
|
+
* format or separator character and no slash. A malformed encoding is none.
|
|
14
|
+
*/
|
|
15
|
+
const fileNameOf = (header) => {
|
|
16
|
+
if (header === void 0 || !/^[\x20-\x7e]*$/.test(header)) return Option.none();
|
|
17
|
+
let name;
|
|
18
|
+
try {
|
|
19
|
+
name = decodeURIComponent(header);
|
|
20
|
+
} catch {
|
|
21
|
+
return Option.none();
|
|
22
|
+
}
|
|
23
|
+
return isFileName(name) ? Option.some(name) : Option.none();
|
|
24
|
+
};
|
|
25
|
+
const TOKEN = "[!#$%&'*+.^_`|~0-9A-Za-z-]+";
|
|
26
|
+
const MEDIA_TYPE = new RegExp(`^${TOKEN}/${TOKEN}$`);
|
|
27
|
+
const PATTERN = new RegExp(`^${TOKEN}/(?:${TOKEN}|\\*)$`);
|
|
28
|
+
/**
|
|
29
|
+
* The `type/subtype` of a media type, lowercased, its parameters dropped:
|
|
30
|
+
* `Text/HTML; x=image/png` is `text/html`. Anything outside the grammar is none.
|
|
31
|
+
*/
|
|
32
|
+
const mediaTypeOf = (header) => {
|
|
33
|
+
if (header === void 0) return Option.none();
|
|
34
|
+
const essence = header.split(";", 1)[0].trim();
|
|
35
|
+
return MEDIA_TYPE.test(essence) ? Option.some(essence.toLowerCase()) : Option.none();
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* Whether `accept` takes a parsed media type (from `mediaTypeOf`). Throws for
|
|
39
|
+
* a pattern outside the grammar, so a typo fails where the route is made
|
|
40
|
+
* rather than refusing every upload.
|
|
41
|
+
*/
|
|
42
|
+
const acceptor = (accept) => {
|
|
43
|
+
if (accept === "*") return () => true;
|
|
44
|
+
if (accept.length === 0) throw new Error("accept lists no type: give one, or '*' for any");
|
|
45
|
+
const patterns = accept.map((pattern) => {
|
|
46
|
+
if (!PATTERN.test(pattern) || pattern.startsWith("*/")) throw new Error(`"${pattern}" is not a media type or type/* pattern`);
|
|
47
|
+
return pattern.toLowerCase();
|
|
48
|
+
});
|
|
49
|
+
return (type) => patterns.some((pattern) => pattern.endsWith("/*") ? type.startsWith(pattern.slice(0, -1)) : type === pattern);
|
|
50
|
+
};
|
|
51
|
+
const SERVED = {
|
|
52
|
+
"content-type": "application/octet-stream",
|
|
53
|
+
"x-content-type-options": "nosniff",
|
|
54
|
+
"content-security-policy": "sandbox; default-src 'none'",
|
|
55
|
+
"cross-origin-resource-policy": "same-origin",
|
|
56
|
+
"cache-control": "private, no-store"
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* `Content-Disposition: attachment` with the name twice: as RFC 6266's
|
|
60
|
+
* `filename*`, everything outside RFC 5987's attribute characters
|
|
61
|
+
* percent-encoded, and as an ASCII fallback keeping letters, digits, space,
|
|
62
|
+
* `.`, `_` and `-` (so no `"`, `\` or `%`, which Chromium decodes there).
|
|
63
|
+
*/
|
|
64
|
+
const dispositionOf = (name) => {
|
|
65
|
+
const encoded = encodeURIComponent(name).replace(/['()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
66
|
+
return `attachment; filename="${name.replace(/[^A-Za-z0-9 ._-]/gu, "_")}"; filename*=UTF-8''${encoded}`;
|
|
67
|
+
};
|
|
68
|
+
/** A download's headers: a file's, named, or a refusal's, with none. */
|
|
69
|
+
const fileHeaders = (name) => Option.match(name, {
|
|
70
|
+
onNone: () => SERVED,
|
|
71
|
+
onSome: (name) => ({
|
|
72
|
+
...SERVED,
|
|
73
|
+
"content-disposition": dispositionOf(name)
|
|
74
|
+
})
|
|
75
|
+
});
|
|
76
|
+
export { acceptor, dispositionOf, fileHeaders, fileNameOf, isFileKey, isFileName, mediaTypeOf };
|
|
77
|
+
|
|
78
|
+
//# sourceMappingURL=fileRules.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fileRules.js","names":[],"sources":["../../src/server/fileRules.ts"],"sourcesContent":["import { Option, Schema } from 'effect'\nimport { FileKey } from '../file.js'\n\n// The rules a file upload and download are held to, apart from any I/O, so\n// each can be tested and broken alone.\n\n/** Whether a key is one the server could have minted, and so names nothing else in a store. */\nexport const isFileKey: (key: string) => boolean = Schema.is(FileKey)\n\nconst MAX_NAME_BYTES = 255\n\n// Control, format (bidi marks and overrides, zero-width characters, U+061C,\n// U+FEFF), line and paragraph separators, half a surrogate pair (which no\n// header can carry, and which a download could not encode), and either slash.\nconst REFUSED_IN_NAME = /[\\p{Cc}\\p{Cf}\\p{Zl}\\p{Zp}\\p{Cs}/\\\\]/u\n\n/** Whether a decoded name is one a download may carry. */\nexport const isFileName = (name: string): boolean =>\n name.length > 0 &&\n new TextEncoder().encode(name).length <= MAX_NAME_BYTES &&\n !REFUSED_IN_NAME.test(name)\n\n/**\n * The file name a client sent, percent-encoded UTF-8, if it is one a\n * download may carry: non-empty, at most 255 bytes, and holding no control,\n * format or separator character and no slash. A malformed encoding is none.\n */\nexport const fileNameOf = (header: string | undefined): Option.Option<string> => {\n // Sent percent-encoded, so a raw byte past ASCII is a client that did not encode.\n if (header === undefined || !/^[\\x20-\\x7e]*$/.test(header)) return Option.none()\n let name: string\n try {\n name = decodeURIComponent(header)\n } catch {\n return Option.none()\n }\n return isFileName(name) ? Option.some(name) : Option.none()\n}\n\nconst TOKEN = \"[!#$%&'*+.^_`|~0-9A-Za-z-]+\"\nconst MEDIA_TYPE = new RegExp(`^${TOKEN}/${TOKEN}$`)\nconst PATTERN = new RegExp(`^${TOKEN}/(?:${TOKEN}|\\\\*)$`)\n\n/**\n * The `type/subtype` of a media type, lowercased, its parameters dropped:\n * `Text/HTML; x=image/png` is `text/html`. Anything outside the grammar is none.\n */\nexport const mediaTypeOf = (header: string | undefined): Option.Option<string> => {\n if (header === undefined) return Option.none()\n const essence = header.split(';', 1)[0]!.trim()\n return MEDIA_TYPE.test(essence) ? Option.some(essence.toLowerCase()) : Option.none()\n}\n\n/** What an upload route takes: media types or `type/*` patterns, or `'*'` for any type. */\nexport type Accept = '*' | ReadonlyArray<string>\n\n/**\n * Whether `accept` takes a parsed media type (from `mediaTypeOf`). Throws for\n * a pattern outside the grammar, so a typo fails where the route is made\n * rather than refusing every upload.\n */\nexport const acceptor = (accept: Accept): ((type: string) => boolean) => {\n if (accept === '*') return () => true\n // An empty list would refuse every upload: no type at all is not a choice anyone means.\n if (accept.length === 0) throw new Error(\"accept lists no type: give one, or '*' for any\")\n const patterns = accept.map(pattern => {\n // `*/*` would read as a pattern and take nothing: any type is `'*'`, said so.\n if (!PATTERN.test(pattern) || pattern.startsWith('*/'))\n throw new Error(`\"${pattern}\" is not a media type or type/* pattern`)\n return pattern.toLowerCase()\n })\n return type =>\n patterns.some(pattern =>\n pattern.endsWith('/*') ? type.startsWith(pattern.slice(0, -1)) : type === pattern,\n )\n}\n\n// What a download carries on every answer, refusals included: nothing on\n// the application's origin may run it, read it from another site, or keep it.\nconst SERVED: Readonly<Record<string, string>> = {\n 'content-type': 'application/octet-stream',\n 'x-content-type-options': 'nosniff',\n 'content-security-policy': \"sandbox; default-src 'none'\",\n 'cross-origin-resource-policy': 'same-origin',\n 'cache-control': 'private, no-store',\n}\n\n/**\n * `Content-Disposition: attachment` with the name twice: as RFC 6266's\n * `filename*`, everything outside RFC 5987's attribute characters\n * percent-encoded, and as an ASCII fallback keeping letters, digits, space,\n * `.`, `_` and `-` (so no `\"`, `\\` or `%`, which Chromium decodes there).\n */\nexport const dispositionOf = (name: string): string => {\n const encoded = encodeURIComponent(name).replace(\n /['()*]/g,\n char => `%${char.charCodeAt(0).toString(16).toUpperCase()}`,\n )\n const fallback = name.replace(/[^A-Za-z0-9 ._-]/gu, '_')\n return `attachment; filename=\"${fallback}\"; filename*=UTF-8''${encoded}`\n}\n\n/** A download's headers: a file's, named, or a refusal's, with none. */\nexport const fileHeaders = (name: Option.Option<string>): Readonly<Record<string, string>> =>\n Option.match(name, {\n onNone: () => SERVED,\n onSome: name => ({ ...SERVED, 'content-disposition': dispositionOf(name) }),\n })\n"],"mappings":";;;;AAOA,MAAa,YAAsC,OAAO,GAAG,OAAO;AAEpE,MAAM,iBAAiB;AAKvB,MAAM,kBAAkB;;AAGxB,MAAa,cAAc,SACzB,KAAK,SAAS,KACd,IAAI,YAAY,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,UAAU,kBACzC,CAAC,gBAAgB,KAAK,IAAI;;;;;;AAO5B,MAAa,cAAc,WAAsD;CAE/E,IAAI,WAAW,KAAA,KAAa,CAAC,iBAAiB,KAAK,MAAM,GAAG,OAAO,OAAO,KAAK;CAC/E,IAAI;CACJ,IAAI;EACF,OAAO,mBAAmB,MAAM;CAClC,QAAQ;EACN,OAAO,OAAO,KAAK;CACrB;CACA,OAAO,WAAW,IAAI,IAAI,OAAO,KAAK,IAAI,IAAI,OAAO,KAAK;AAC5D;AAEA,MAAM,QAAQ;AACd,MAAM,aAAa,IAAI,OAAO,IAAI,MAAM,GAAG,MAAM,EAAE;AACnD,MAAM,UAAU,IAAI,OAAO,IAAI,MAAM,MAAM,MAAM,OAAO;;;;;AAMxD,MAAa,eAAe,WAAsD;CAChF,IAAI,WAAW,KAAA,GAAW,OAAO,OAAO,KAAK;CAC7C,MAAM,UAAU,OAAO,MAAM,KAAK,CAAC,CAAC,CAAC,EAAE,CAAE,KAAK;CAC9C,OAAO,WAAW,KAAK,OAAO,IAAI,OAAO,KAAK,QAAQ,YAAY,CAAC,IAAI,OAAO,KAAK;AACrF;;;;;;AAUA,MAAa,YAAY,WAAgD;CACvE,IAAI,WAAW,KAAK,aAAa;CAEjC,IAAI,OAAO,WAAW,GAAG,MAAM,IAAI,MAAM,gDAAgD;CACzF,MAAM,WAAW,OAAO,KAAI,YAAW;EAErC,IAAI,CAAC,QAAQ,KAAK,OAAO,KAAK,QAAQ,WAAW,IAAI,GACnD,MAAM,IAAI,MAAM,IAAI,QAAQ,wCAAwC;EACtE,OAAO,QAAQ,YAAY;CAC7B,CAAC;CACD,QAAO,SACL,SAAS,MAAK,YACZ,QAAQ,SAAS,IAAI,IAAI,KAAK,WAAW,QAAQ,MAAM,GAAG,EAAE,CAAC,IAAI,SAAS,OAC5E;AACJ;AAIA,MAAM,SAA2C;CAC/C,gBAAgB;CAChB,0BAA0B;CAC1B,2BAA2B;CAC3B,gCAAgC;CAChC,iBAAiB;AACnB;;;;;;;AAQA,MAAa,iBAAiB,SAAyB;CACrD,MAAM,UAAU,mBAAmB,IAAI,CAAC,CAAC,QACvC,YACA,SAAQ,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,YAAY,GAC1D;CAEA,OAAO,yBADU,KAAK,QAAQ,sBAAsB,GACb,EAAE,sBAAsB;AACjE;;AAGA,MAAa,eAAe,SAC1B,OAAO,MAAM,MAAM;CACjB,cAAc;CACd,SAAQ,UAAS;EAAE,GAAG;EAAQ,uBAAuB,cAAc,IAAI;CAAE;AAC3E,CAAC"}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { Context, Duration, Effect, Layer, Option, Schema } from "effect";
|
|
2
|
+
import { FileAsset } from "../file.js";
|
|
3
|
+
import { KeyValueStore } from "effect/persistence";
|
|
4
|
+
import { SecureRandom } from "effect/crypto";
|
|
5
|
+
/** What the upload route was told about a file, beside its bytes. */
|
|
6
|
+
export interface Declared {
|
|
7
|
+
readonly name: string;
|
|
8
|
+
readonly type: string;
|
|
9
|
+
/** Who uploaded it: `FileUploadPolicy`'s answer. */
|
|
10
|
+
readonly owner: string;
|
|
11
|
+
}
|
|
12
|
+
/** A kept file's bytes and the facts its upload recorded. */
|
|
13
|
+
export interface StoredFile {
|
|
14
|
+
readonly asset: FileAsset;
|
|
15
|
+
readonly bytes: Uint8Array<ArrayBuffer>;
|
|
16
|
+
}
|
|
17
|
+
declare const FileUnclaimed_base: Schema.Class<FileUnclaimed, Schema.TaggedStruct<"FileUnclaimed", {
|
|
18
|
+
readonly key: Schema.String;
|
|
19
|
+
}>, import("effect/Cause").YieldableError>;
|
|
20
|
+
/**
|
|
21
|
+
* No file the asking owner may claim under this key: unknown, expired,
|
|
22
|
+
* another's, or claimed already. Each reads alike, so a refusal never says
|
|
23
|
+
* which.
|
|
24
|
+
*/
|
|
25
|
+
export declare class FileUnclaimed extends FileUnclaimed_base {}
|
|
26
|
+
declare const FileStore_base: Context.ServiceClass<FileStore, "foldkit-media/FileStore", {
|
|
27
|
+
/** Keeps a file's bytes, then its record, under a key it mints. */
|
|
28
|
+
readonly keep: (bytes: Uint8Array, declared: Declared) => Effect.Effect<FileAsset>;
|
|
29
|
+
/** A kept file, by its key; none for a key outside the grammar. */
|
|
30
|
+
readonly read: (key: string) => Effect.Effect<Option.Option<StoredFile>>;
|
|
31
|
+
/**
|
|
32
|
+
* The facts the upload recorded, for the application to store in place of
|
|
33
|
+
* what its client sent: once, by the file's owner, within `claimWithin`
|
|
34
|
+
* of its upload.
|
|
35
|
+
*/
|
|
36
|
+
readonly claim: (key: string, owner: string) => Effect.Effect<FileAsset, FileUnclaimed>;
|
|
37
|
+
}>;
|
|
38
|
+
/**
|
|
39
|
+
* Where uploaded files live, apart from `Originals`, so no file is ever read
|
|
40
|
+
* as an image to transform.
|
|
41
|
+
*/
|
|
42
|
+
export declare class FileStore extends FileStore_base {}
|
|
43
|
+
export interface FileStoreOptions {
|
|
44
|
+
/** Where in the store files are kept; `files/` by default. */
|
|
45
|
+
readonly prefix?: string;
|
|
46
|
+
/** How long after its upload a file may be claimed; a day by default. */
|
|
47
|
+
readonly claimWithin?: Duration.Input;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Files in the application's `KeyValueStore`, each key minted from
|
|
51
|
+
* `SecureRandom`. Bytes are never shared between uploads, even equal ones, so
|
|
52
|
+
* an upload's speed says nothing of what others hold. A store that fails is a
|
|
53
|
+
* defect: the file is data.
|
|
54
|
+
*
|
|
55
|
+
* A key-value store cannot compare and set, so two claims racing by the same
|
|
56
|
+
* owner may both succeed; a claim by anyone else cannot.
|
|
57
|
+
*/
|
|
58
|
+
export declare const filesKeyValueStore: (options?: FileStoreOptions) => Layer.Layer<FileStore, never, KeyValueStore.KeyValueStore | SecureRandom.SecureRandom>;
|
|
59
|
+
/**
|
|
60
|
+
* The file a row should hold after a save: the one it holds already when the
|
|
61
|
+
* submitted key is that file's, so a re-save claims nothing, and otherwise
|
|
62
|
+
* the submitted key claimed for `owner`. The facts come from the server
|
|
63
|
+
* either way, never from the client. Call it after the write is authorized,
|
|
64
|
+
* so a refused write claims nothing.
|
|
65
|
+
*/
|
|
66
|
+
export declare const keepOrClaim: (current: Option.Option<FileAsset>, submitted: FileAsset, owner: string) => Effect.Effect<FileAsset, FileUnclaimed, FileStore>;
|
|
67
|
+
export {};
|
|
68
|
+
//# sourceMappingURL=fileStore.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fileStore.d.ts","names":[],"sources":["../../src/server/fileStore.ts"],"mappings":";;;;;iBAOiB;WACN;WACA;;WAEA;;;iBAIM;WACN,OAAO;WACP,OAAO,WAAW;;;;;;;;;;qBAQhB,sBAAsB;;;WAYhB,OAAC,OAAO,YAAY,UAAU,aAAa,OAAO,OAAO;;WAEzD,OAAC,gBAAgB,OAAO,OAAO,OAAO,OAAO;;;;;;WAM5C,QAAC,aAAa,kBAAkB,OAAO,OAAO,WAAW;;;;;;qBAZhE,kBAAkB;iBA8Bd;;WAEN;;WAEA,cAAc,SAAS;;;;;;;;;;;qBAYrB,qBAAkB,UACpB,qBACR,MAAM,MAAM,kBAAkB,cAAc,gBAAgB,aAAa;;;;;;;;qBAmF/D,cAAW,SACb,OAAO,OAAO,YAAU,WACtB,WAAS,kBAEnB,OAAO,OAAO,WAAW,eAAe"}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { Clock, Context, Duration, Effect, Layer, Option, Schema } from "effect";
|
|
2
|
+
import { FileAsset } from "../file.js";
|
|
3
|
+
import { KeyValueStore } from "effect/persistence";
|
|
4
|
+
import { SecureRandom } from "effect/crypto";
|
|
5
|
+
import { isFileKey, isFileName } from "./fileRules.js";
|
|
6
|
+
// src/server/fileStore.ts
|
|
7
|
+
/**
|
|
8
|
+
* No file the asking owner may claim under this key: unknown, expired,
|
|
9
|
+
* another's, or claimed already. Each reads alike, so a refusal never says
|
|
10
|
+
* which.
|
|
11
|
+
*/
|
|
12
|
+
var FileUnclaimed = class extends Schema.TaggedError()("FileUnclaimed", { key: Schema.String }) {};
|
|
13
|
+
/**
|
|
14
|
+
* Where uploaded files live, apart from `Originals`, so no file is ever read
|
|
15
|
+
* as an image to transform.
|
|
16
|
+
*/
|
|
17
|
+
var FileStore = class extends Context.Service()("foldkit-media/FileStore") {};
|
|
18
|
+
const FileRecord = Schema.Struct({
|
|
19
|
+
asset: FileAsset,
|
|
20
|
+
owner: Schema.String,
|
|
21
|
+
uploadedAt: Schema.Number,
|
|
22
|
+
claimed: Schema.Boolean
|
|
23
|
+
});
|
|
24
|
+
const RecordJson = Schema.fromJsonString(FileRecord);
|
|
25
|
+
const encodeRecord = Schema.encodeSync(RecordJson);
|
|
26
|
+
const decodeRecord = Schema.decodeUnknownSync(RecordJson);
|
|
27
|
+
const hex = (bytes) => Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
28
|
+
/**
|
|
29
|
+
* Files in the application's `KeyValueStore`, each key minted from
|
|
30
|
+
* `SecureRandom`. Bytes are never shared between uploads, even equal ones, so
|
|
31
|
+
* an upload's speed says nothing of what others hold. A store that fails is a
|
|
32
|
+
* defect: the file is data.
|
|
33
|
+
*
|
|
34
|
+
* A key-value store cannot compare and set, so two claims racing by the same
|
|
35
|
+
* owner may both succeed; a claim by anyone else cannot.
|
|
36
|
+
*/
|
|
37
|
+
const filesKeyValueStore = (options = {}) => Layer.effect(FileStore, Effect.gen(function* () {
|
|
38
|
+
const store = KeyValueStore.prefix(yield* KeyValueStore.KeyValueStore, options.prefix ?? "files/");
|
|
39
|
+
const random = yield* SecureRandom.SecureRandom;
|
|
40
|
+
const claimWithin = Duration.toMillis(options.claimWithin ?? "24 hours");
|
|
41
|
+
const bytesKey = (key) => `bytes/${key}`;
|
|
42
|
+
const recordKey = (key) => `records/${key}`;
|
|
43
|
+
const recordOf = (key) => isFileKey(key) ? store.get(recordKey(key)).pipe(Effect.orDie, Effect.map((stored) => Option.map(Option.fromNullishOr(stored), decodeRecord))) : Effect.succeed(Option.none());
|
|
44
|
+
return {
|
|
45
|
+
keep: (bytes, declared) => Effect.gen(function* () {
|
|
46
|
+
if (!isFileName(declared.name)) return yield* Effect.die(/* @__PURE__ */ new Error(`"${declared.name}" is not a file name`));
|
|
47
|
+
const key = hex(yield* random.randomBytes(16));
|
|
48
|
+
const asset = {
|
|
49
|
+
key,
|
|
50
|
+
name: declared.name,
|
|
51
|
+
type: declared.type,
|
|
52
|
+
size: bytes.byteLength
|
|
53
|
+
};
|
|
54
|
+
yield* store.set(bytesKey(key), bytes);
|
|
55
|
+
yield* store.set(recordKey(key), encodeRecord({
|
|
56
|
+
asset,
|
|
57
|
+
owner: declared.owner,
|
|
58
|
+
uploadedAt: yield* Clock.currentTimeMillis,
|
|
59
|
+
claimed: false
|
|
60
|
+
}));
|
|
61
|
+
return asset;
|
|
62
|
+
}).pipe(Effect.orDie),
|
|
63
|
+
read: (key) => recordOf(key).pipe(Effect.flatMap(Option.match({
|
|
64
|
+
onNone: () => Effect.succeedNone,
|
|
65
|
+
onSome: (record) => store.getUint8Array(bytesKey(key)).pipe(Effect.orDie, Effect.flatMap((bytes) => bytes === void 0 ? Effect.die(/* @__PURE__ */ new Error(`The bytes of file ${key} are missing`)) : Effect.succeedSome({
|
|
66
|
+
asset: record.asset,
|
|
67
|
+
bytes: new Uint8Array(bytes)
|
|
68
|
+
})))
|
|
69
|
+
}))),
|
|
70
|
+
claim: (key, owner) => Effect.gen(function* () {
|
|
71
|
+
const now = yield* Clock.currentTimeMillis;
|
|
72
|
+
const record = Option.filter(yield* recordOf(key), (record) => !record.claimed && record.owner === owner && now - record.uploadedAt <= claimWithin);
|
|
73
|
+
if (Option.isNone(record)) return yield* new FileUnclaimed({ key });
|
|
74
|
+
yield* store.set(recordKey(key), encodeRecord({
|
|
75
|
+
...record.value,
|
|
76
|
+
claimed: true
|
|
77
|
+
})).pipe(Effect.orDie);
|
|
78
|
+
return record.value.asset;
|
|
79
|
+
})
|
|
80
|
+
};
|
|
81
|
+
}));
|
|
82
|
+
/**
|
|
83
|
+
* The file a row should hold after a save: the one it holds already when the
|
|
84
|
+
* submitted key is that file's, so a re-save claims nothing, and otherwise
|
|
85
|
+
* the submitted key claimed for `owner`. The facts come from the server
|
|
86
|
+
* either way, never from the client. Call it after the write is authorized,
|
|
87
|
+
* so a refused write claims nothing.
|
|
88
|
+
*/
|
|
89
|
+
const keepOrClaim = (current, submitted, owner) => Option.match(Option.filter(current, (kept) => kept.key === submitted.key), {
|
|
90
|
+
onSome: Effect.succeed,
|
|
91
|
+
onNone: () => FileStore.use((files) => files.claim(submitted.key, owner))
|
|
92
|
+
});
|
|
93
|
+
export { FileStore, FileUnclaimed, filesKeyValueStore, keepOrClaim };
|
|
94
|
+
|
|
95
|
+
//# sourceMappingURL=fileStore.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fileStore.js","names":[],"sources":["../../src/server/fileStore.ts"],"sourcesContent":["import { Clock, Context, Duration, Effect, Layer, Option, Schema } from 'effect'\nimport { SecureRandom } from 'effect/crypto'\nimport { KeyValueStore } from 'effect/persistence'\nimport { FileAsset } from '../file.js'\nimport { isFileKey, isFileName } from './fileRules.js'\n\n/** What the upload route was told about a file, beside its bytes. */\nexport interface Declared {\n readonly name: string\n readonly type: string\n /** Who uploaded it: `FileUploadPolicy`'s answer. */\n readonly owner: string\n}\n\n/** A kept file's bytes and the facts its upload recorded. */\nexport interface StoredFile {\n readonly asset: FileAsset\n readonly bytes: Uint8Array<ArrayBuffer>\n}\n\n/**\n * No file the asking owner may claim under this key: unknown, expired,\n * another's, or claimed already. Each reads alike, so a refusal never says\n * which.\n */\nexport class FileUnclaimed extends Schema.TaggedError<FileUnclaimed>()('FileUnclaimed', {\n key: Schema.String,\n}) {}\n\n/**\n * Where uploaded files live, apart from `Originals`, so no file is ever read\n * as an image to transform.\n */\nexport class FileStore extends Context.Service<\n FileStore,\n {\n /** Keeps a file's bytes, then its record, under a key it mints. */\n readonly keep: (bytes: Uint8Array, declared: Declared) => Effect.Effect<FileAsset>\n /** A kept file, by its key; none for a key outside the grammar. */\n readonly read: (key: string) => Effect.Effect<Option.Option<StoredFile>>\n /**\n * The facts the upload recorded, for the application to store in place of\n * what its client sent: once, by the file's owner, within `claimWithin`\n * of its upload.\n */\n readonly claim: (key: string, owner: string) => Effect.Effect<FileAsset, FileUnclaimed>\n }\n>()('foldkit-media/FileStore') {}\n\nconst FileRecord = Schema.Struct({\n asset: FileAsset,\n owner: Schema.String,\n uploadedAt: Schema.Number,\n claimed: Schema.Boolean,\n})\nconst RecordJson = Schema.fromJsonString(FileRecord)\nconst encodeRecord = Schema.encodeSync(RecordJson)\n// The store wrote every record, so one that does not decode is a defect, never a miss.\nconst decodeRecord = Schema.decodeUnknownSync(RecordJson)\n\nconst hex = (bytes: Uint8Array): string =>\n Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('')\n\nexport interface FileStoreOptions {\n /** Where in the store files are kept; `files/` by default. */\n readonly prefix?: string\n /** How long after its upload a file may be claimed; a day by default. */\n readonly claimWithin?: Duration.Input\n}\n\n/**\n * Files in the application's `KeyValueStore`, each key minted from\n * `SecureRandom`. Bytes are never shared between uploads, even equal ones, so\n * an upload's speed says nothing of what others hold. A store that fails is a\n * defect: the file is data.\n *\n * A key-value store cannot compare and set, so two claims racing by the same\n * owner may both succeed; a claim by anyone else cannot.\n */\nexport const filesKeyValueStore = (\n options: FileStoreOptions = {},\n): Layer.Layer<FileStore, never, KeyValueStore.KeyValueStore | SecureRandom.SecureRandom> =>\n Layer.effect(\n FileStore,\n Effect.gen(function* () {\n const store = KeyValueStore.prefix(\n yield* KeyValueStore.KeyValueStore,\n options.prefix ?? 'files/',\n )\n const random = yield* SecureRandom.SecureRandom\n const claimWithin = Duration.toMillis(options.claimWithin ?? '24 hours')\n const bytesKey = (key: string) => `bytes/${key}`\n const recordKey = (key: string) => `records/${key}`\n const recordOf = (key: string) =>\n isFileKey(key)\n ? store.get(recordKey(key)).pipe(\n Effect.orDie,\n Effect.map(stored => Option.map(Option.fromNullishOr(stored), decodeRecord)),\n )\n : Effect.succeed(Option.none())\n\n return {\n keep: (bytes, declared) =>\n Effect.gen(function* () {\n // The route checked it; a name the route would refuse could not be downloaded.\n if (!isFileName(declared.name))\n return yield* Effect.die(new Error(`\"${declared.name}\" is not a file name`))\n const key = hex(yield* random.randomBytes(16))\n const asset = { key, name: declared.name, type: declared.type, size: bytes.byteLength }\n // Bytes first: a record is never read for bytes not yet written.\n yield* store.set(bytesKey(key), bytes)\n yield* store.set(\n recordKey(key),\n encodeRecord({\n asset,\n owner: declared.owner,\n uploadedAt: yield* Clock.currentTimeMillis,\n claimed: false,\n }),\n )\n return asset\n }).pipe(Effect.orDie),\n read: key =>\n recordOf(key).pipe(\n Effect.flatMap(\n Option.match({\n onNone: () => Effect.succeedNone,\n onSome: record =>\n store.getUint8Array(bytesKey(key)).pipe(\n Effect.orDie,\n Effect.flatMap(bytes =>\n bytes === undefined\n ? Effect.die(new Error(`The bytes of file ${key} are missing`))\n : Effect.succeedSome({ asset: record.asset, bytes: new Uint8Array(bytes) }),\n ),\n ),\n }),\n ),\n ),\n claim: (key, owner) =>\n Effect.gen(function* () {\n const now = yield* Clock.currentTimeMillis\n const record = Option.filter(\n yield* recordOf(key),\n record =>\n !record.claimed && record.owner === owner && now - record.uploadedAt <= claimWithin,\n )\n if (Option.isNone(record)) return yield* new FileUnclaimed({ key })\n yield* store\n .set(recordKey(key), encodeRecord({ ...record.value, claimed: true }))\n .pipe(Effect.orDie)\n return record.value.asset\n }),\n }\n }),\n )\n\n/**\n * The file a row should hold after a save: the one it holds already when the\n * submitted key is that file's, so a re-save claims nothing, and otherwise\n * the submitted key claimed for `owner`. The facts come from the server\n * either way, never from the client. Call it after the write is authorized,\n * so a refused write claims nothing.\n */\nexport const keepOrClaim = (\n current: Option.Option<FileAsset>,\n submitted: FileAsset,\n owner: string,\n): Effect.Effect<FileAsset, FileUnclaimed, FileStore> =>\n Option.match(\n Option.filter(current, kept => kept.key === submitted.key),\n {\n onSome: Effect.succeed,\n onNone: () => FileStore.use(files => files.claim(submitted.key, owner)),\n },\n )\n"],"mappings":";;;;;;;;;;;AAyBA,IAAa,gBAAb,cAAmC,OAAO,YAA2B,CAAC,CAAC,iBAAiB,EACtF,KAAK,OAAO,OACd,CAAC,CAAC,CAAC,CAAC;;;;;AAMJ,IAAa,YAAb,cAA+B,QAAQ,QAcrC,CAAC,CAAC,yBAAyB,CAAC,CAAC,CAAC;AAEhC,MAAM,aAAa,OAAO,OAAO;CAC/B,OAAO;CACP,OAAO,OAAO;CACd,YAAY,OAAO;CACnB,SAAS,OAAO;AAClB,CAAC;AACD,MAAM,aAAa,OAAO,eAAe,UAAU;AACnD,MAAM,eAAe,OAAO,WAAW,UAAU;AAEjD,MAAM,eAAe,OAAO,kBAAkB,UAAU;AAExD,MAAM,OAAO,UACX,MAAM,KAAK,QAAO,SAAQ,KAAK,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE;;;;;;;;;;AAkBvE,MAAa,sBACX,UAA4B,CAAC,MAE7B,MAAM,OACJ,WACA,OAAO,IAAI,aAAa;CACtB,MAAM,QAAQ,cAAc,OAC1B,OAAO,cAAc,eACrB,QAAQ,UAAU,QACpB;CACA,MAAM,SAAS,OAAO,aAAa;CACnC,MAAM,cAAc,SAAS,SAAS,QAAQ,eAAe,UAAU;CACvE,MAAM,YAAY,QAAgB,SAAS;CAC3C,MAAM,aAAa,QAAgB,WAAW;CAC9C,MAAM,YAAY,QAChB,UAAU,GAAG,IACT,MAAM,IAAI,UAAU,GAAG,CAAC,CAAC,CAAC,KACxB,OAAO,OACP,OAAO,KAAI,WAAU,OAAO,IAAI,OAAO,cAAc,MAAM,GAAG,YAAY,CAAC,CAC7E,IACA,OAAO,QAAQ,OAAO,KAAK,CAAC;CAElC,OAAO;EACL,OAAO,OAAO,aACZ,OAAO,IAAI,aAAa;GAEtB,IAAI,CAAC,WAAW,SAAS,IAAI,GAC3B,OAAO,OAAO,OAAO,oBAAI,IAAI,MAAM,IAAI,SAAS,KAAK,qBAAqB,CAAC;GAC7E,MAAM,MAAM,IAAI,OAAO,OAAO,YAAY,EAAE,CAAC;GAC7C,MAAM,QAAQ;IAAE;IAAK,MAAM,SAAS;IAAM,MAAM,SAAS;IAAM,MAAM,MAAM;GAAW;GAEtF,OAAO,MAAM,IAAI,SAAS,GAAG,GAAG,KAAK;GACrC,OAAO,MAAM,IACX,UAAU,GAAG,GACb,aAAa;IACX;IACA,OAAO,SAAS;IAChB,YAAY,OAAO,MAAM;IACzB,SAAS;GACX,CAAC,CACH;GACA,OAAO;EACT,CAAC,CAAC,CAAC,KAAK,OAAO,KAAK;EACtB,OAAM,QACJ,SAAS,GAAG,CAAC,CAAC,KACZ,OAAO,QACL,OAAO,MAAM;GACX,cAAc,OAAO;GACrB,SAAQ,WACN,MAAM,cAAc,SAAS,GAAG,CAAC,CAAC,CAAC,KACjC,OAAO,OACP,OAAO,SAAQ,UACb,UAAU,KAAA,IACN,OAAO,oBAAI,IAAI,MAAM,qBAAqB,IAAI,aAAa,CAAC,IAC5D,OAAO,YAAY;IAAE,OAAO,OAAO;IAAO,OAAO,IAAI,WAAW,KAAK;GAAE,CAAC,CAC9E,CACF;EACJ,CAAC,CACH,CACF;EACF,QAAQ,KAAK,UACX,OAAO,IAAI,aAAa;GACtB,MAAM,MAAM,OAAO,MAAM;GACzB,MAAM,SAAS,OAAO,OACpB,OAAO,SAAS,GAAG,IACnB,WACE,CAAC,OAAO,WAAW,OAAO,UAAU,SAAS,MAAM,OAAO,cAAc,WAC5E;GACA,IAAI,OAAO,OAAO,MAAM,GAAG,OAAO,OAAO,IAAI,cAAc,EAAE,IAAI,CAAC;GAClE,OAAO,MACJ,IAAI,UAAU,GAAG,GAAG,aAAa;IAAE,GAAG,OAAO;IAAO,SAAS;GAAK,CAAC,CAAC,CAAC,CACrE,KAAK,OAAO,KAAK;GACpB,OAAO,OAAO,MAAM;EACtB,CAAC;CACL;AACF,CAAC,CACH;;;;;;;;AASF,MAAa,eACX,SACA,WACA,UAEA,OAAO,MACL,OAAO,OAAO,UAAS,SAAQ,KAAK,QAAQ,UAAU,GAAG,GACzD;CACE,QAAQ,OAAO;CACf,cAAc,UAAU,KAAI,UAAS,MAAM,MAAM,UAAU,KAAK,KAAK,CAAC;AACxE,CACF"}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { Context, Effect, Layer, Schema } from "effect";
|
|
2
|
+
import { UploadForbidden, UploadUnauthenticated } from "./upload.js";
|
|
3
|
+
import { HttpApi, HttpApiEndpoint, HttpApiGroup } from "effect/http-api";
|
|
4
|
+
import { Accept } from "./fileRules.js";
|
|
5
|
+
import { HttpServerRequest } from "effect/http";
|
|
6
|
+
import { FileStore } from "./fileStore.js";
|
|
7
|
+
/** The file routes, mounted alone: `fileLayer`. */
|
|
8
|
+
export declare const FileApi: HttpApi.HttpApi<"foldkit-media-files", HttpApiGroup.HttpApiGroup<"files", HttpApiEndpoint.HttpApiEndpoint<"download", "GET", "/_media/files/:key", Schema.toCodecStringTree<Schema.Struct<{
|
|
9
|
+
key: Schema.String;
|
|
10
|
+
}>>, never, never, never, Schema.toCodecJson<import("effect/http-api/HttpApiSchema").NoContent>, never, never, never> | HttpApiEndpoint.HttpApiEndpoint<"upload", "POST", "/_media/files", never, never, never, never, Schema.toCodecJson<import("effect/http-api/HttpApiSchema").NoContent>, never, never, never>, false>>;
|
|
11
|
+
declare const FileUploadPolicy_base: Context.ServiceClass<FileUploadPolicy, "foldkit-media/FileUploadPolicy", {
|
|
12
|
+
readonly admit: (request: HttpServerRequest.HttpServerRequest) => Effect.Effect<string, UploadForbidden | UploadUnauthenticated>;
|
|
13
|
+
}>;
|
|
14
|
+
/**
|
|
15
|
+
* Who may upload a file, asked before the body is read, answering the
|
|
16
|
+
* uploader's id: only that id may later claim the file. It must be stable
|
|
17
|
+
* and never given to anyone else; an empty id is refused. No default, so a
|
|
18
|
+
* server is never open to uploads by omission.
|
|
19
|
+
*/
|
|
20
|
+
export declare class FileUploadPolicy extends FileUploadPolicy_base {}
|
|
21
|
+
declare const FileUnauthenticated_base: Schema.Class<FileUnauthenticated, Schema.TaggedStruct<"FileUnauthenticated", {}>, import("effect/Cause").YieldableError>;
|
|
22
|
+
/** The read policy could not tell who is asking: the download answers 401. */
|
|
23
|
+
export declare class FileUnauthenticated extends FileUnauthenticated_base {}
|
|
24
|
+
/** Whether the asker may read the file under a key. */
|
|
25
|
+
export type FileReader = (key: string) => Effect.Effect<boolean>;
|
|
26
|
+
declare const FileReadPolicy_base: Context.ServiceClass<FileReadPolicy, "foldkit-media/FileReadPolicy", {
|
|
27
|
+
readonly resolve: (request: HttpServerRequest.HttpServerRequest) => Effect.Effect<FileReader, FileUnauthenticated>;
|
|
28
|
+
}>;
|
|
29
|
+
/**
|
|
30
|
+
* Who may read which file, asked before the store is read: `resolve` says who
|
|
31
|
+
* is asking from the request alone, never the key, and answers what they may
|
|
32
|
+
* read. Build it with `fileReadPolicy`.
|
|
33
|
+
*/
|
|
34
|
+
export declare class FileReadPolicy extends FileReadPolicy_base {}
|
|
35
|
+
/**
|
|
36
|
+
* A `FileReadPolicy` in its two steps: `resolve` says who is asking (a
|
|
37
|
+
* principal, a visitor) or fails `FileUnauthenticated`; `read` says whether
|
|
38
|
+
* they may read a key, typically by finding the application's row that holds
|
|
39
|
+
* it. A no is a 404, as an unknown key is.
|
|
40
|
+
*/
|
|
41
|
+
export declare const fileReadPolicy: <Asker>(policy: {
|
|
42
|
+
readonly resolve: (request: HttpServerRequest.HttpServerRequest) => Effect.Effect<Asker, FileUnauthenticated>;
|
|
43
|
+
readonly read: (asker: Asker, key: string) => Effect.Effect<boolean>;
|
|
44
|
+
}) => Layer.Layer<FileReadPolicy>;
|
|
45
|
+
declare const FileRefused_base: Schema.Class<FileRefused, Schema.TaggedStruct<"FileRefused", {}>, import("effect/Cause").YieldableError>;
|
|
46
|
+
/** An `inspect` hook's refusal of an upload: answered 415, with nothing kept. */
|
|
47
|
+
export declare class FileRefused extends FileRefused_base {}
|
|
48
|
+
export interface FileOptions {
|
|
49
|
+
/**
|
|
50
|
+
* The declared types an upload may have: media types or `type/*` patterns,
|
|
51
|
+
* or `'*'` for any. The client writes the type, so this shapes the product
|
|
52
|
+
* and secures nothing: a download is never served as its type.
|
|
53
|
+
*/
|
|
54
|
+
readonly accept: Accept;
|
|
55
|
+
/** The largest file read, in bytes, counted as it streams; 20 MB by default. */
|
|
56
|
+
readonly maxBytes?: number;
|
|
57
|
+
/**
|
|
58
|
+
* Uploads read at once, each holding about twice its size; 2 by default.
|
|
59
|
+
* One past it, or a second from one owner, answers 503 rather than waiting.
|
|
60
|
+
*/
|
|
61
|
+
readonly maxConcurrent?: number;
|
|
62
|
+
/** The slowest a body may arrive, over each 10 seconds, before it is cut off (408); 32 KB/s by default. */
|
|
63
|
+
readonly minBytesPerSecond?: number;
|
|
64
|
+
/** Reads the bytes before anything is kept: a magic-number check, a scan. */
|
|
65
|
+
readonly inspect?: (bytes: Uint8Array<ArrayBuffer>, declared: {
|
|
66
|
+
readonly name: string;
|
|
67
|
+
readonly type: string;
|
|
68
|
+
}) => Effect.Effect<void, FileRefused>;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* The file routes' handlers. An upload is asked of the `FileUploadPolicy`
|
|
72
|
+
* first, then must be `application/octet-stream` (which no page on another
|
|
73
|
+
* site can send without a preflight this route never answers), declare a
|
|
74
|
+
* name and an accepted type in its headers, pass `Admission` when one is
|
|
75
|
+
* given, find a free slot, arrive within `maxBytes` and the minimum rate, and
|
|
76
|
+
* pass `inspect`; it answers the kept `FileAsset`, 201. A download checks
|
|
77
|
+
* the key's grammar, then the `FileReadPolicy`, then the store, and answers
|
|
78
|
+
* the bytes as an attachment that cannot run on this origin.
|
|
79
|
+
*/
|
|
80
|
+
export declare const fileHandlers: (options: FileOptions) => Layer.Layer<HttpApiGroup.Service<"foldkit-media-files", "files">, never, FileReadPolicy | FileStore | FileUploadPolicy>;
|
|
81
|
+
/**
|
|
82
|
+
* The file routes as an Effect HTTP application, registered with the
|
|
83
|
+
* `HttpRouter`, needing a `FileStore`, a `FileUploadPolicy` and a
|
|
84
|
+
* `FileReadPolicy`, and `Admission` if one is given.
|
|
85
|
+
*/
|
|
86
|
+
export declare const fileLayer: (options: FileOptions) => Layer.Layer<never, never, FileReadPolicy | FileStore | import("effect/FileSystem").FileSystem | FileUploadPolicy | import("effect/http/Etag").Generator | import("effect/http/HttpPlatform").HttpPlatform | import("effect/http/HttpRouter").HttpRouter | import("effect/Path").Path>;
|
|
87
|
+
export {};
|
|
88
|
+
//# sourceMappingURL=files.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"files.d.ts","names":[],"sources":["../../src/server/files.ts"],"mappings":";;;;;;;qBA0Ba,SAAO,QAAA,+BAAA,aAAA,sBAAA,gBAAA,yDAAA,OAAA,kBAAA,OAAA;;0BAKnB,OAAA,oDAAA,mCAAA,gBAAA,+EAAA,OAAA,oDAAA;;WAWmB,QACd,SAAS,kBAAkB,sBACxB,OAAO,eAAe,kBAAkB;;;;;;;;qBALpC,yBAAyB;;;qBAUzB,4BAA4B;;YAM7B,cAAc,gBAAgB,OAAO;;WAU3B,UAChB,SAAS,kBAAkB,sBACxB,OAAO,OAAO,YAAY;;;;;;;qBALtB,uBAAuB;;;;;;;qBAevB,iBAAkB,OAAK;WACzB,UACP,SAAS,kBAAkB,sBACxB,OAAO,OAAO,OAAO;WACjB,OAAO,OAAO,OAAO,gBAAgB,OAAO;MACnD,MAAM,MAAM;;;qBAOH,oBAAoB;iBAEhB;;;;;;WAMN,QAAQ;;WAER;;;;;WAKA;;WAEA;;WAEA,WACP,OAAO,WAAW,cAClB;aAAqB;aAAuB;QACzC,OAAO,aAAa;;;;;;;;;;;;qBA6Ed,eAAY,SAAa,gBAAW,MAAA,MAAA,aAAA,gDAAA,iBAAA,YAAA;;;;;;qBA4HpC,YAAS,SAAa,gBAAW,MAAA,oBAAA,iBAAA,wCAAA,aAAA,8CAAA,+CAAA,gDAAA,mCAAA"}
|