@flowscripter/io-gateway-http 0.0.0-stage → 1.0.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.
Files changed (39) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +83 -2
  3. package/dist/index.d.ts +4 -0
  4. package/dist/index.d.ts.map +1 -0
  5. package/dist/index.js +3 -0
  6. package/dist/src/HttpGateway.d.ts +39 -0
  7. package/dist/src/HttpGateway.d.ts.map +1 -0
  8. package/dist/src/HttpGateway.js +106 -0
  9. package/dist/src/http/parseRange.d.ts +18 -0
  10. package/dist/src/http/parseRange.d.ts.map +1 -0
  11. package/dist/src/http/parseRange.js +41 -0
  12. package/dist/src/http/resolveTokenPath.d.ts +16 -0
  13. package/dist/src/http/resolveTokenPath.d.ts.map +1 -0
  14. package/dist/src/http/resolveTokenPath.js +30 -0
  15. package/dist/src/http/statusForError.d.ts +7 -0
  16. package/dist/src/http/statusForError.d.ts.map +1 -0
  17. package/dist/src/http/statusForError.js +15 -0
  18. package/dist/src/stream/createResumingReadStream.d.ts +19 -0
  19. package/dist/src/stream/createResumingReadStream.d.ts.map +1 -0
  20. package/dist/src/stream/createResumingReadStream.js +46 -0
  21. package/dist/src/token/GatewayGrant.d.ts +36 -0
  22. package/dist/src/token/GatewayGrant.d.ts.map +1 -0
  23. package/dist/src/token/GatewayGrant.js +234 -0
  24. package/dist/src/token/WriteTracker.d.ts +19 -0
  25. package/dist/src/token/WriteTracker.d.ts.map +1 -0
  26. package/dist/src/token/WriteTracker.js +40 -0
  27. package/dist/src/token/keys.d.ts +6 -0
  28. package/dist/src/token/keys.d.ts.map +1 -0
  29. package/dist/src/token/keys.js +16 -0
  30. package/index.ts +3 -0
  31. package/package.json +64 -4
  32. package/src/HttpGateway.ts +142 -0
  33. package/src/http/parseRange.ts +47 -0
  34. package/src/http/resolveTokenPath.ts +34 -0
  35. package/src/http/statusForError.ts +16 -0
  36. package/src/stream/createResumingReadStream.ts +61 -0
  37. package/src/token/GatewayGrant.ts +294 -0
  38. package/src/token/WriteTracker.ts +47 -0
  39. package/src/token/keys.ts +17 -0
@@ -0,0 +1,234 @@
1
+ import { isRangeReadable, PayloadKind, fromWebReadableStream, } from "@flowscripter/pluggable-io-framework-api";
2
+ import { withRetry } from "@flowscripter/pluggable-io-framework";
3
+ import { parseRange } from "../http/parseRange.js";
4
+ import { statusForError } from "../http/statusForError.js";
5
+ import { createResumingReadStream } from "../stream/createResumingReadStream.js";
6
+ import { baseName, joinKey } from "./keys.js";
7
+ import { WriteTracker } from "./WriteTracker.js";
8
+ function text(status, message, headers) {
9
+ return new Response(message, { status, headers });
10
+ }
11
+ /**
12
+ * Serves one root location (a container or a single entry) over HTTP,
13
+ * restricted to a scope. Created by `HttpGateway`; revoking it makes
14
+ * every later request a 404.
15
+ */
16
+ export class GatewayGrant {
17
+ #init;
18
+ #tracker = new WriteTracker();
19
+ #rangeHandles = new Map();
20
+ #revoked = false;
21
+ constructor(init) {
22
+ this.#init = init;
23
+ }
24
+ /** The URL of the root: the container with a trailing slash, or the single entry. */
25
+ get url() {
26
+ const { origin, token, target } = this.#init;
27
+ const base = `${origin}/${token}/`;
28
+ return target.kind === "entry" ? `${base}${encodeURIComponent(baseName(target.key))}` : base;
29
+ }
30
+ /** The URL of a path below a container root. */
31
+ urlFor(path) {
32
+ if (this.#init.target.kind === "entry") {
33
+ throw new TypeError("urlFor is only available for a container root");
34
+ }
35
+ const encoded = path
36
+ .split("/")
37
+ .filter((segment) => segment !== "")
38
+ .map(encodeURIComponent)
39
+ .join("/");
40
+ return `${this.#init.origin}/${this.#init.token}/${encoded}`;
41
+ }
42
+ get revoked() {
43
+ return this.#revoked;
44
+ }
45
+ /** Resolves with every write and delete result once none is in flight. */
46
+ settled() {
47
+ return this.#tracker.settled();
48
+ }
49
+ /** Stops serving requests. Writes already in flight still run to completion. */
50
+ async revoke() {
51
+ if (this.#revoked) {
52
+ return;
53
+ }
54
+ this.#revoked = true;
55
+ this.#rangeHandles.clear();
56
+ if (this.#init.ownsProvider) {
57
+ await this.#tracker.settled();
58
+ await this.#init.provider[Symbol.asyncDispose]();
59
+ }
60
+ }
61
+ async handle(request, segments) {
62
+ const key = this.#resolveKey(segments);
63
+ if (key === undefined) {
64
+ return text(404, "Not Found");
65
+ }
66
+ const path = segments.join("/");
67
+ switch (request.method) {
68
+ case "GET":
69
+ case "HEAD":
70
+ return this.#read(request, key);
71
+ case "PUT":
72
+ case "POST":
73
+ return this.#write(request, key, path);
74
+ case "DELETE":
75
+ return this.#delete(key, path);
76
+ default:
77
+ return text(405, "Method Not Allowed", { Allow: "GET, HEAD, PUT, POST, DELETE" });
78
+ }
79
+ }
80
+ #resolveKey(segments) {
81
+ const { target, provider } = this.#init;
82
+ if (target.kind === "entry") {
83
+ return segments.length === 1 && segments[0] === baseName(target.key) ? target.key : undefined;
84
+ }
85
+ if (segments.length === 0) {
86
+ return undefined;
87
+ }
88
+ return segments.reduce((key, segment) => joinKey(provider, key, segment), target.key);
89
+ }
90
+ async #open(key) {
91
+ return withRetry(() => this.#init.provider.getReadableStream(key), this.#init.retry);
92
+ }
93
+ /** Opens a handle for its range capability only, caching it when it has one. */
94
+ async #rangeHandle(key) {
95
+ const cached = this.#rangeHandles.get(key);
96
+ if (cached !== undefined) {
97
+ return cached;
98
+ }
99
+ const handle = await this.#open(key);
100
+ await handle.stream.cancel();
101
+ if (isRangeReadable(handle)) {
102
+ this.#rangeHandles.set(key, handle);
103
+ }
104
+ return handle;
105
+ }
106
+ async #read(request, key) {
107
+ const { provider, retry } = this.#init;
108
+ const head = request.method === "HEAD";
109
+ const rangeHeader = request.headers.get("range");
110
+ try {
111
+ const properties = await withRetry(() => provider.getProperties(key), retry);
112
+ if (properties.isContainer) {
113
+ return text(404, "Not Found");
114
+ }
115
+ const size = properties.size;
116
+ const headers = new Headers({
117
+ "Content-Type": properties.contentType ?? "application/octet-stream",
118
+ });
119
+ if (properties.lastModified !== undefined) {
120
+ headers.set("Last-Modified", properties.lastModified.toUTCString());
121
+ }
122
+ const etag = properties.properties.etag;
123
+ if (typeof etag === "string") {
124
+ headers.set("ETag", etag);
125
+ }
126
+ if (/\bclose\b/i.test(request.headers.get("connection") ?? "")) {
127
+ headers.set("Connection", "close");
128
+ }
129
+ if (head || rangeHeader !== null) {
130
+ const parked = await this.#rangeHandle(key);
131
+ const rangeable = size !== undefined && parked.bounded !== false && isRangeReadable(parked);
132
+ headers.set("Accept-Ranges", rangeable ? "bytes" : "none");
133
+ if (head) {
134
+ if (size !== undefined && parked.bounded !== false) {
135
+ headers.set("Content-Length", String(size));
136
+ }
137
+ return new Response(null, { status: 200, headers });
138
+ }
139
+ if (rangeable) {
140
+ const range = parseRange(rangeHeader, size);
141
+ if (range.kind === "unsatisfiable") {
142
+ headers.set("Content-Range", `bytes */${size}`);
143
+ headers.set("Content-Length", "0");
144
+ return new Response(null, { status: 416, headers });
145
+ }
146
+ if (range.kind === "range") {
147
+ return await this.#rangeResponse(parked, range.start, range.end, size, headers);
148
+ }
149
+ }
150
+ }
151
+ return await this.#fullResponse(key, size, headers);
152
+ }
153
+ catch (error) {
154
+ return text(statusForError(error, "read"), "Upstream read failed");
155
+ }
156
+ }
157
+ async #rangeResponse(handle, start, end, size, headers) {
158
+ const { retry } = this.#init;
159
+ const open = (offset) => handle.readRange(offset, end);
160
+ const initial = await withRetry(() => open(start), retry);
161
+ headers.set("Content-Range", `bytes ${start}-${end - 1}/${size}`);
162
+ headers.set("Content-Length", String(end - start));
163
+ return new Response(createResumingReadStream({
164
+ initial,
165
+ startOffset: start,
166
+ reopen: (offset) => withRetry(() => open(offset), retry),
167
+ retry,
168
+ }), { status: 206, headers });
169
+ }
170
+ async #fullResponse(key, size, headers) {
171
+ const { retry } = this.#init;
172
+ const handle = await this.#open(key);
173
+ const bounded = size !== undefined && handle.bounded !== false;
174
+ const rangeable = bounded && isRangeReadable(handle);
175
+ headers.set("Accept-Ranges", rangeable ? "bytes" : "none");
176
+ if (bounded) {
177
+ headers.set("Content-Length", String(size));
178
+ }
179
+ if (rangeable) {
180
+ this.#rangeHandles.set(key, handle);
181
+ }
182
+ return new Response(createResumingReadStream({
183
+ initial: handle.stream,
184
+ startOffset: 0,
185
+ reopen: rangeable
186
+ ? (offset) => withRetry(() => handle.readRange(offset, size), retry)
187
+ : undefined,
188
+ retry,
189
+ }), { status: 200, headers });
190
+ }
191
+ async #write(request, key, path) {
192
+ if (this.#init.scope !== "read-write") {
193
+ return text(403, "Forbidden");
194
+ }
195
+ const { provider } = this.#init;
196
+ this.#rangeHandles.delete(key);
197
+ try {
198
+ await this.#tracker.track("write", path, async () => {
199
+ const handle = await provider.getWritableStream(key);
200
+ const sink = handle.stream;
201
+ if (request.body === null) {
202
+ await sink.close();
203
+ }
204
+ else {
205
+ await fromWebReadableStream(request.body).pipeTo(sink);
206
+ }
207
+ });
208
+ return new Response(null, { status: 201 });
209
+ }
210
+ catch (error) {
211
+ return text(statusForError(error, "write"), "Upstream write failed");
212
+ }
213
+ finally {
214
+ this.#rangeHandles.delete(key);
215
+ }
216
+ }
217
+ async #delete(key, path) {
218
+ const { provider, scope } = this.#init;
219
+ if (scope !== "read-write") {
220
+ return text(403, "Forbidden");
221
+ }
222
+ if (provider.delete === undefined) {
223
+ return text(405, "Method Not Allowed", { Allow: "GET, HEAD, PUT, POST" });
224
+ }
225
+ this.#rangeHandles.delete(key);
226
+ try {
227
+ await this.#tracker.track("delete", path, () => withRetry(() => provider.delete(key), this.#init.retry));
228
+ return new Response(null, { status: 204 });
229
+ }
230
+ catch (error) {
231
+ return text(statusForError(error, "read"), "Upstream delete failed");
232
+ }
233
+ }
234
+ }
@@ -0,0 +1,19 @@
1
+ export interface WriteResult {
2
+ readonly operation: "write" | "delete";
3
+ readonly path: string;
4
+ readonly error?: unknown;
5
+ }
6
+ /**
7
+ * Records every write and delete served for a token. A tool's exit code says
8
+ * nothing about whether its uploads committed, so callers wait on
9
+ * `settled` and take success or failure from the results.
10
+ */
11
+ export declare class WriteTracker {
12
+ #private;
13
+ /** Runs `operation`, recording it as a result and as in flight until it settles. */
14
+ track(operation: WriteResult["operation"], path: string, run: () => Promise<void>): Promise<void>;
15
+ get inFlight(): number;
16
+ /** Resolves with every result so far once no write or delete is in flight. */
17
+ settled(): Promise<readonly WriteResult[]>;
18
+ }
19
+ //# sourceMappingURL=WriteTracker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"WriteTracker.d.ts","sourceRoot":"","sources":["../../../src/token/WriteTracker.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,SAAS,EAAE,OAAO,GAAG,QAAQ,CAAC;IACvC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO,CAAC;CAC1B;AAED;;;;GAIG;AACH,qBAAa,YAAY;;IAKvB,oFAAoF;IAC9E,KAAK,CAAC,SAAS,EAAE,WAAW,CAAC,WAAW,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,iBAgBtF;IAED,IAAI,QAAQ,IAAI,MAAM,CAErB;IAED,8EAA8E;IACxE,OAAO,IAAI,OAAO,CAAC,SAAS,WAAW,EAAE,CAAC,CAK/C;CACF"}
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Records every write and delete served for a token. A tool's exit code says
3
+ * nothing about whether its uploads committed, so callers wait on
4
+ * `settled` and take success or failure from the results.
5
+ */
6
+ export class WriteTracker {
7
+ #results = [];
8
+ #waiters = [];
9
+ #inFlight = 0;
10
+ /** Runs `operation`, recording it as a result and as in flight until it settles. */
11
+ async track(operation, path, run) {
12
+ this.#inFlight += 1;
13
+ try {
14
+ await run();
15
+ this.#results.push({ operation, path });
16
+ }
17
+ catch (error) {
18
+ this.#results.push({ operation, path, error });
19
+ throw error;
20
+ }
21
+ finally {
22
+ this.#inFlight -= 1;
23
+ if (this.#inFlight === 0) {
24
+ for (const resolve of this.#waiters.splice(0)) {
25
+ resolve();
26
+ }
27
+ }
28
+ }
29
+ }
30
+ get inFlight() {
31
+ return this.#inFlight;
32
+ }
33
+ /** Resolves with every result so far once no write or delete is in flight. */
34
+ async settled() {
35
+ if (this.#inFlight > 0) {
36
+ await new Promise((resolve) => this.#waiters.push(resolve));
37
+ }
38
+ return [...this.#results];
39
+ }
40
+ }
@@ -0,0 +1,6 @@
1
+ import type { IOProvider } from "@flowscripter/pluggable-io-framework-api";
2
+ /** Joins a child name onto a container key using the provider's own rule, else with `/`. */
3
+ export declare function joinKey(provider: IOProvider, containerKey: string, name: string): string;
4
+ /** The last segment of a key, treating both `/` and `\` as separators. */
5
+ export declare function baseName(key: string): string;
6
+ //# sourceMappingURL=keys.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keys.d.ts","sourceRoot":"","sources":["../../../src/token/keys.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,0CAA0C,CAAC;AAE3E,4FAA4F;AAC5F,wBAAgB,OAAO,CAAC,QAAQ,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAOxF;AAED,0EAA0E;AAC1E,wBAAgB,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAG5C"}
@@ -0,0 +1,16 @@
1
+ /** Joins a child name onto a container key using the provider's own rule, else with `/`. */
2
+ export function joinKey(provider, containerKey, name) {
3
+ if (provider.joinKey) {
4
+ return provider.joinKey(containerKey, name);
5
+ }
6
+ if (name === "")
7
+ return containerKey;
8
+ if (containerKey === "")
9
+ return name;
10
+ return `${containerKey.replace(/\/+$/, "")}/${name}`;
11
+ }
12
+ /** The last segment of a key, treating both `/` and `\` as separators. */
13
+ export function baseName(key) {
14
+ const segments = key.split(/[\\/]+/).filter((segment) => segment !== "");
15
+ return segments.at(-1) ?? key;
16
+ }
package/index.ts ADDED
@@ -0,0 +1,3 @@
1
+ export { HttpGateway, type GrantOptions, type HttpGatewayOptions } from "./src/HttpGateway.ts";
2
+ export { GatewayGrant, type GrantScope } from "./src/token/GatewayGrant.ts";
3
+ export { type WriteResult } from "./src/token/WriteTracker.ts";
package/package.json CHANGED
@@ -1,6 +1,66 @@
1
1
  {
2
2
  "name": "@flowscripter/io-gateway-http",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Local HTTP gateway serving pluggable-io-framework IOProvider locations to tools that only speak HTTP",
5
+ "keywords": [
6
+ "bun",
7
+ "gateway",
8
+ "http",
9
+ "io",
10
+ "library",
11
+ "pluggable-io-framework"
12
+ ],
13
+ "homepage": "https://github.com/flowscripter/io-gateway-http#readme",
14
+ "license": "MIT",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/flowscripter/io-gateway-http.git"
18
+ },
19
+ "files": [
20
+ "dist",
21
+ "src",
22
+ "index.ts",
23
+ "README.md",
24
+ "LICENSE"
25
+ ],
26
+ "type": "module",
27
+ "main": "dist/index.js",
28
+ "module": "dist/index.js",
29
+ "types": "dist/index.d.ts",
30
+ "exports": {
31
+ ".": {
32
+ "bun": "./index.ts",
33
+ "types": "./dist/index.d.ts",
34
+ "default": "./dist/index.js"
35
+ }
36
+ },
37
+ "publishConfig": {
38
+ "access": "public"
39
+ },
40
+ "scripts": {
41
+ "build": "tsc -p tsconfig.build.json",
42
+ "test": "bun test"
43
+ },
44
+ "dependencies": {
45
+ "@flowscripter/pluggable-io-framework": "^2.1.0",
46
+ "@flowscripter/pluggable-io-framework-api": "^3.1.1"
47
+ },
48
+ "devDependencies": {
49
+ "@flowscripter/io-plugin-filesystem": "^2.0.2",
50
+ "@flowscripter/io-plugin-http": "^1.0.0",
51
+ "@flowscripter/io-plugin-s3": "^1.0.0",
52
+ "@types/bun": "^1.4.2",
53
+ "@types/node": "^26.6.3",
54
+ "oxfmt": "0.71.0",
55
+ "oxlint": "1.86.0"
56
+ },
57
+ "peerDependencies": {
58
+ "typescript": "^7.0.2"
59
+ },
60
+ "typedocOptions": {
61
+ "readme": "none",
62
+ "exclude": [
63
+ "tests/**"
64
+ ]
65
+ }
66
+ }
@@ -0,0 +1,142 @@
1
+ import {
2
+ type IOProvider,
3
+ type LocationTarget,
4
+ PayloadKind,
5
+ type ProviderResolver,
6
+ } from "@flowscripter/pluggable-io-framework-api";
7
+ import { DEFAULT_RETRY, type RetryOptions } from "@flowscripter/pluggable-io-framework";
8
+ import { resolveTokenPath } from "./http/resolveTokenPath.ts";
9
+ import { GatewayGrant, type GrantScope } from "./token/GatewayGrant.ts";
10
+
11
+ export interface HttpGatewayOptions {
12
+ /** Retries for transient provider failures, applied by the gateway so the HTTP client never sees them. */
13
+ readonly retry?: RetryOptions;
14
+ }
15
+
16
+ export interface GrantOptions {
17
+ readonly scope: GrantScope;
18
+ }
19
+
20
+ function randomToken(): string {
21
+ return Buffer.from(crypto.getRandomValues(new Uint8Array(24))).toString("base64url");
22
+ }
23
+
24
+ /**
25
+ * A local HTTP server on a loopback ephemeral port that serves
26
+ * IOProvider locations. Access is by grant: each grant has a random token as
27
+ * the first path segment, so relative references below the grant URL resolve
28
+ * against its root and no client configuration is needed.
29
+ */
30
+ export class HttpGateway {
31
+ readonly #server: Bun.Server<undefined>;
32
+ readonly #retry: RetryOptions;
33
+ readonly #grants = new Map<string, GatewayGrant>();
34
+
35
+ private constructor(retry: RetryOptions) {
36
+ this.#retry = retry;
37
+ this.#server = Bun.serve({
38
+ hostname: "127.0.0.1",
39
+ port: 0,
40
+ idleTimeout: 0,
41
+ maxRequestBodySize: Number.MAX_SAFE_INTEGER,
42
+ fetch: (request) => this.#handle(request),
43
+ });
44
+ }
45
+
46
+ static start(options?: HttpGatewayOptions): HttpGateway {
47
+ return new HttpGateway(options?.retry ?? DEFAULT_RETRY);
48
+ }
49
+
50
+ get origin(): string {
51
+ return `http://127.0.0.1:${this.#server.port}`;
52
+ }
53
+
54
+ /**
55
+ * Serves a container or single entry of `provider`. The provider must be
56
+ * of the `js` payload kind and stays owned by the caller.
57
+ */
58
+ grant(
59
+ provider: IOProvider<PayloadKind.Js>,
60
+ target: LocationTarget,
61
+ options: GrantOptions,
62
+ ): GatewayGrant {
63
+ return this.#addGrant(provider, target, options, false);
64
+ }
65
+
66
+ /**
67
+ * Resolves `location` to a `js` provider and serves its target. The grant
68
+ * owns the provider and disposes it when revoked.
69
+ */
70
+ async grantLocation(
71
+ resolver: ProviderResolver,
72
+ location: string,
73
+ options: GrantOptions,
74
+ ): Promise<GatewayGrant> {
75
+ const { provider, target } = await resolver.createProviderForLocation(location, {
76
+ kind: PayloadKind.Js,
77
+ });
78
+ try {
79
+ return this.#addGrant(provider as IOProvider<PayloadKind.Js>, target, options, true);
80
+ } catch (error) {
81
+ await provider[Symbol.asyncDispose]();
82
+ throw error;
83
+ }
84
+ }
85
+
86
+ /**
87
+ * Revokes every grant, waits for in-flight writes to settle, then stops the
88
+ * server: responses in progress get `graceMs` to finish before their
89
+ * connections are closed.
90
+ */
91
+ async close(graceMs = 1000): Promise<void> {
92
+ const grants = [...this.#grants.values()];
93
+ await Promise.all(grants.map((grant) => grant.revoke()));
94
+ await Promise.all(grants.map((grant) => grant.settled()));
95
+ this.#grants.clear();
96
+ const stopping = this.#server.stop();
97
+ const timer = setTimeout(() => void this.#server.stop(true), graceMs);
98
+ await stopping;
99
+ clearTimeout(timer);
100
+ }
101
+
102
+ #addGrant(
103
+ provider: IOProvider,
104
+ target: LocationTarget,
105
+ options: GrantOptions,
106
+ ownsProvider: boolean,
107
+ ): GatewayGrant {
108
+ if (provider.kind !== PayloadKind.Js) {
109
+ throw new TypeError(`The gateway serves js providers, not "${provider.kind}"`);
110
+ }
111
+ if (target.kind === "pattern") {
112
+ throw new TypeError("A pattern location cannot be served; use its container");
113
+ }
114
+ const token = randomToken();
115
+ const grant = new GatewayGrant({
116
+ provider: provider as IOProvider<PayloadKind.Js>,
117
+ target,
118
+ scope: options.scope,
119
+ retry: this.#retry,
120
+ origin: this.origin,
121
+ token,
122
+ ownsProvider,
123
+ });
124
+ this.#grants.set(token, grant);
125
+ return grant;
126
+ }
127
+
128
+ async #handle(request: Request): Promise<Response> {
129
+ const resolved = resolveTokenPath(new URL(request.url).pathname);
130
+ if (resolved.kind === "malformed") {
131
+ return new Response("Bad Request", { status: 400 });
132
+ }
133
+ const grant = resolved.kind === "ok" ? this.#grants.get(resolved.token) : undefined;
134
+ if (resolved.kind === "escape") {
135
+ return new Response("Forbidden", { status: 403 });
136
+ }
137
+ if (grant === undefined || grant.revoked) {
138
+ return new Response("Not Found", { status: 404 });
139
+ }
140
+ return grant.handle(request, resolved.segments);
141
+ }
142
+ }
@@ -0,0 +1,47 @@
1
+ export type RangeRequest =
2
+ | { readonly kind: "none" }
3
+ | { readonly kind: "range"; readonly start: number; readonly end: number }
4
+ | { readonly kind: "unsatisfiable" };
5
+
6
+ const SINGLE_RANGE = /^bytes=(\d*)-(\d*)$/;
7
+
8
+ /**
9
+ * Parses a `Range` header against an entry of `size` bytes into a byte range
10
+ * with an exclusive `end`. A missing header or a malformed or multi-range
11
+ * header, or one in a unit other than bytes, is `none` (the whole entry is
12
+ * served). A bytes header that is malformed, holds several ranges or starts at
13
+ * or past `size` is `unsatisfiable`.
14
+ */
15
+ export function parseRange(header: string | null, size: number): RangeRequest {
16
+ if (header === null) {
17
+ return { kind: "none" };
18
+ }
19
+ const value = header.trim();
20
+ if (!/^bytes\s*=/i.test(value)) {
21
+ return { kind: "none" };
22
+ }
23
+ const match = SINGLE_RANGE.exec(value);
24
+ if (match === null || (match[1] === "" && match[2] === "")) {
25
+ return { kind: "unsatisfiable" };
26
+ }
27
+ const [, first, last] = match as unknown as [string, string, string];
28
+ if (first === "") {
29
+ const suffix = Number(last);
30
+ if (suffix === 0) {
31
+ return { kind: "unsatisfiable" };
32
+ }
33
+ return { kind: "range", start: Math.max(0, size - suffix), end: size };
34
+ }
35
+ const start = Number(first);
36
+ if (start >= size) {
37
+ return { kind: "unsatisfiable" };
38
+ }
39
+ if (last === "") {
40
+ return { kind: "range", start, end: size };
41
+ }
42
+ const inclusiveEnd = Number(last);
43
+ if (inclusiveEnd < start) {
44
+ return { kind: "unsatisfiable" };
45
+ }
46
+ return { kind: "range", start, end: Math.min(inclusiveEnd + 1, size) };
47
+ }
@@ -0,0 +1,34 @@
1
+ export type TokenPath =
2
+ | { readonly kind: "ok"; readonly token: string; readonly segments: readonly string[] }
3
+ | { readonly kind: "malformed" }
4
+ | { readonly kind: "escape" };
5
+
6
+ /**
7
+ * Splits a request pathname into its token and the decoded path segments
8
+ * below it. Empty and `.` segments are dropped. A `..` segment, or a
9
+ * decoded segment containing a path separator or NUL, is an `escape`.
10
+ */
11
+ export function resolveTokenPath(pathname: string): TokenPath {
12
+ const raw = pathname.split("/").filter((segment) => segment !== "");
13
+ const token = raw.shift();
14
+ if (token === undefined) {
15
+ return { kind: "malformed" };
16
+ }
17
+ const segments: string[] = [];
18
+ for (const part of raw) {
19
+ let segment: string;
20
+ try {
21
+ segment = decodeURIComponent(part);
22
+ } catch {
23
+ return { kind: "malformed" };
24
+ }
25
+ if (segment === ".") {
26
+ continue;
27
+ }
28
+ if (segment === ".." || /[/\\\0]/.test(segment)) {
29
+ return { kind: "escape" };
30
+ }
31
+ segments.push(segment);
32
+ }
33
+ return { kind: "ok", token, segments };
34
+ }
@@ -0,0 +1,16 @@
1
+ import { PermanentIOError, TransientIOError } from "@flowscripter/pluggable-io-framework-api";
2
+
3
+ /**
4
+ * The HTTP status for a provider failure. A permanent failure reading or
5
+ * deleting is reported as not found; a permanent write failure and a
6
+ * transient failure that outlived its retries are an upstream error.
7
+ */
8
+ export function statusForError(error: unknown, operation: "read" | "write"): number {
9
+ if (error instanceof PermanentIOError) {
10
+ return operation === "read" ? 404 : 502;
11
+ }
12
+ if (error instanceof TransientIOError) {
13
+ return 502;
14
+ }
15
+ return 500;
16
+ }