@midsummer-ai/sdk 0.1.0-staging.3428 → 0.1.0-staging.3434

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 (43) hide show
  1. package/auth-B7rCtXFQ.d.mts +36 -0
  2. package/{build-DQo-JrlN.d.mts → build-BhmOZmGQ.d.mts} +2 -27
  3. package/client.mjs +1 -1
  4. package/contract.mjs +2 -2
  5. package/database/build.d.mts +1 -1
  6. package/database/build.mjs +35 -2
  7. package/database/server.mjs +1 -1
  8. package/database/stand-in.d.mts +2 -1
  9. package/database/stand-in.mjs +2 -2
  10. package/email/client.d.mts +5 -4
  11. package/email/client.mjs +1 -1
  12. package/email/contract.d.mts +3 -1
  13. package/email/contract.mjs +111 -4
  14. package/email/index.d.mts +85 -16
  15. package/email/index.mjs +2 -2
  16. package/email/smtp.mjs +24 -8
  17. package/email/stand-in.d.mts +3 -0
  18. package/email/stand-in.mjs +17 -7
  19. package/email-IH5OllU2.mjs +337 -0
  20. package/errors-B1tO_wdm.mjs +28 -0
  21. package/flows/contract.d.mts +13 -0
  22. package/flows/contract.mjs +483 -0
  23. package/flows/index.d.mts +148 -0
  24. package/flows/index.mjs +347 -0
  25. package/index.mjs +2 -2
  26. package/{names-DfCBKupJ.mjs → names-Do0ot5Ha.mjs} +2 -28
  27. package/package.json +29 -1
  28. package/queues/contract.mjs +144 -1
  29. package/queues/index.d.mts +149 -5
  30. package/queues/index.mjs +56 -12
  31. package/queues/stand-in.mjs +333 -31
  32. package/queues/wire.mjs +302 -16
  33. package/s3.mjs +3 -2
  34. package/{server-EDRbF2u-.mjs → server-Drjni3-F.mjs} +4 -2
  35. package/socket.mjs +1 -1
  36. package/{src-BKrQAqJN.mjs → src-CkP59_Qu.mjs} +2 -1
  37. package/stand-in.mjs +2 -1
  38. package/storage/contract.d.mts +25 -0
  39. package/storage/contract.mjs +153 -0
  40. package/storage/files.d.mts +144 -0
  41. package/storage/files.mjs +513 -0
  42. package/wire.mjs +2 -1
  43. package/email-DXtpr7pT.mjs +0 -214
@@ -0,0 +1,144 @@
1
+ import { m as StorageEngine, t as Body } from "../index-Ci6mGXqz.mjs";
2
+ import { n as AuthProvider, r as VerifierOptions } from "../auth-B7rCtXFQ.mjs";
3
+ //#region src/storage/files.d.ts
4
+ /** Whether a rule only reads its folder, or reads, puts and deletes in it. */
5
+ type FileAccess = "read" | "write";
6
+ /**
7
+ * One folder of a bucket and who reaches it: every signed-in user, or with `{subject}` each user their own; anyone too
8
+ * when `public`. A `write` rule may bound what is put: `maxBytes` a file, and `contentTypes`, as `image/png` or `image/*`.
9
+ */
10
+ interface FileRule {
11
+ readonly prefix: string;
12
+ readonly access: FileAccess;
13
+ readonly public?: boolean;
14
+ readonly maxBytes?: number;
15
+ readonly contentTypes?: ReadonlyArray<string>;
16
+ }
17
+ /** A bucket's settings for app users: the sign-in providers it trusts and its rules. No rules: app users reach nothing. */
18
+ interface BucketAccess {
19
+ readonly providers: ReadonlyArray<AuthProvider>;
20
+ readonly rules: ReadonlyArray<FileRule>;
21
+ }
22
+ /** The bounds of a bucket's settings and of what its app users send. */
23
+ declare const FILE_LIMITS: {
24
+ readonly rules: 20;
25
+ readonly providers: 8;
26
+ readonly prefixBytes: 512;
27
+ readonly keyBytes: 1024;
28
+ readonly contentTypes: 20;
29
+ readonly defaultBytes: number;
30
+ readonly maxBytes: number;
31
+ readonly subject: 256;
32
+ readonly list: 1000;
33
+ };
34
+ /** The part of a rule's folder that stands for each user's own. */
35
+ declare const SUBJECT = "{subject}";
36
+ /** Why a subject can't name a user's folder, or undefined. */
37
+ declare function subjectProblem(subject: string): string | undefined;
38
+ /**
39
+ * A bucket's settings, checked: the shape `storage bucket settings set` sends. Throws `StorageError` `invalid` saying
40
+ * what is wrong. Providers are the shape `db/auth.config.ts` writes, with every value written out: a bucket has no
41
+ * Environment to read one from.
42
+ */
43
+ declare function bucketAccessOf(value: unknown): BucketAccess;
44
+ /** What an app user asks of a bucket: to read, list, put or delete, at a key (or, listing, a prefix). */
45
+ type FileOp = "read" | "list" | "write" | "delete";
46
+ /** Why a request is refused, with the status it returns and words that say what to do. */
47
+ interface FileRefusal {
48
+ readonly status: 400 | 401 | 403 | 413 | 415;
49
+ readonly code: "invalid" | "unauthenticated" | "forbidden" | "too_large" | "unsupported_type";
50
+ readonly message: string;
51
+ }
52
+ /**
53
+ * Whether a bucket's rules let a caller do `op` at `path`: undefined when they do, else why not. `subject` is the
54
+ * caller's verified subject, null for anyone. A write gives its `size` in bytes and its `contentType`. Pure: the same
55
+ * settings and ask always return the same.
56
+ */
57
+ declare function fileRefusal(access: BucketAccess, ask: {
58
+ readonly op: FileOp;
59
+ readonly path: string;
60
+ readonly subject: string | null;
61
+ readonly size?: number;
62
+ readonly contentType?: string;
63
+ }): FileRefusal | undefined;
64
+ /** Where the files of a Team's buckets are served, on the API origin: `/storage/app/<team>/<bucket>/<key>`. */
65
+ declare const FILES_BASE = "/storage/app";
66
+ /** Whether a path on the API origin is the files endpoint's. */
67
+ declare const isAppPath: (path: string) => boolean;
68
+ /** A bucket as the files endpoint finds it: the name the engine knows it by, its settings, and whether writes are paused. */
69
+ interface FilesBucket {
70
+ readonly bucket: string;
71
+ readonly access: BucketAccess;
72
+ readonly paused?: boolean;
73
+ }
74
+ /** A file as an app's users see it. */
75
+ interface AppFile {
76
+ readonly key: string;
77
+ readonly size: number;
78
+ readonly etag: string;
79
+ readonly contentType: string;
80
+ readonly uploadedAt: number;
81
+ }
82
+ /**
83
+ * The files endpoint: serves a request at `FILES_BASE` as the bucket's settings let its caller, over `engine`.
84
+ * `bucket` finds a Team's bucket by handle and name (undefined: none, or app users reach none of it); `counted` is told
85
+ * each served request's bucket and class (`a` puts, deletes and lists, `b` reads), as the S3 endpoint counts them.
86
+ * Tokens are checked with `verify`'s fetch, resolve and clock; a verifier is kept per set of providers, so a provider's
87
+ * keys are fetched once for every bucket that trusts it.
88
+ */
89
+ declare function filesServer(options: {
90
+ readonly engine: StorageEngine;
91
+ readonly bucket: (team: string, name: string) => Promise<FilesBucket | undefined>;
92
+ readonly verify?: VerifierOptions;
93
+ readonly counted?: (bucket: string, kind: "a" | "b") => void;
94
+ }): (request: Request) => Promise<Response>;
95
+ /** A bucket's files as an app's signed-in user reaches them (`files`). Every failure is a `StorageError`. */
96
+ interface Files {
97
+ /** Where a file is, as an address: for an `<img src>` of a public one. */
98
+ url(key: string): string;
99
+ /** Puts a file, replacing what was there; with `ifNoneMatch: "*"`, only where there is none (`conflict` else). */
100
+ put(key: string, body: Body, options?: {
101
+ readonly contentType?: string;
102
+ readonly ifNoneMatch?: "*";
103
+ }): Promise<AppFile>;
104
+ /** A file and its bytes, or null when there is none. */
105
+ get(key: string): Promise<(AppFile & {
106
+ readonly body: Uint8Array;
107
+ }) | null>;
108
+ /** A page of the files under `prefix`, the folders under it with `delimiter`, and `next` to go on from. */
109
+ list(options?: {
110
+ readonly prefix?: string;
111
+ readonly after?: string;
112
+ readonly limit?: number;
113
+ readonly delimiter?: string;
114
+ }): Promise<{
115
+ readonly files: ReadonlyArray<AppFile>;
116
+ readonly folders: ReadonlyArray<string>;
117
+ readonly next?: string;
118
+ }>;
119
+ delete(key: string): Promise<void>;
120
+ }
121
+ /**
122
+ * A bucket's files for one of your app's users, from their browser or your own code: `origin` is the API's address
123
+ * (`https://api.midsummer.new`), and `token` gives the user's token from your sign-in provider, or nothing for anyone.
124
+ */
125
+ declare function files(options: {
126
+ readonly origin: string;
127
+ readonly team: string;
128
+ readonly bucket: string;
129
+ readonly token?: () => string | null | undefined | Promise<string | null | undefined>;
130
+ readonly fetch?: (url: string, init: RequestInit) => Promise<Response>;
131
+ }): Files;
132
+ /**
133
+ * The files endpoint in memory, for tests and `midsummer dev`: each bucket of each team is a bucket of `engine` by its
134
+ * own name, and `set` gives one its settings as `storage bucket settings set` does, checked the same way.
135
+ */
136
+ declare function filesStandIn(options: {
137
+ readonly engine: StorageEngine;
138
+ readonly verify?: VerifierOptions;
139
+ }): {
140
+ set(team: string, bucket: string, access: unknown): void;
141
+ fetch: (request: Request) => Promise<Response>;
142
+ };
143
+ //#endregion
144
+ export { AppFile, BucketAccess, FILES_BASE, FILE_LIMITS, FileAccess, FileOp, FileRefusal, FileRule, Files, FilesBucket, SUBJECT, bucketAccessOf, fileRefusal, files, filesServer, filesStandIn, isAppPath, subjectProblem };
@@ -0,0 +1,513 @@
1
+ import { t as StorageError } from "../errors-B1tO_wdm.mjs";
2
+ import { n as checkBucketName } from "../names-Do0ot5Ha.mjs";
3
+ import { DatabaseError } from "../database/errors.mjs";
4
+ import { i as verifier, r as trustedOf, t as authConfigOf } from "../auth-1W-SzpD3.mjs";
5
+ //#region src/storage/files.ts
6
+ /**
7
+ * `@midsummer-ai/sdk/files`: a bucket's files for your app's own signed-in users, straight from their browser, with no
8
+ * server of yours in between. A bucket's settings (`midsummer storage bucket settings set`) say whom it trusts to sign
9
+ * users in, in the same terms as a database's `db/auth.config.ts`, and which folders each user reaches:
10
+ *
11
+ * {
12
+ * providers: [{ domain: "https://auth.acme.dev/", applicationID: "acme-web" }],
13
+ * rules: [
14
+ * // Each user reads and writes their own folder: `{subject}` is their token's `sub`, the `subject`
15
+ * // `ctx.auth.getUserIdentity()` gives the same user in the database.
16
+ * { prefix: "users/{subject}/", access: "write", maxBytes: 5_000_000, contentTypes: ["image/*"] },
17
+ * // Every signed-in user reads what is shared; anyone, signed in or not, reads what is public.
18
+ * { prefix: "shared/", access: "read" },
19
+ * { prefix: "public/", access: "read", public: true },
20
+ * ],
21
+ * }
22
+ *
23
+ * In the browser, with the token your sign-in provider gives the user:
24
+ *
25
+ * import { files } from "@midsummer-ai/sdk/files"
26
+ *
27
+ * const avatars = files({ origin: "https://api.midsummer.new", team: "acme", bucket: "avatars", token: () => auth.getToken() })
28
+ * await avatars.put(`users/${user.id}/photo.png`, file, { contentType: file.type })
29
+ * const mine = await avatars.list({ prefix: `users/${user.id}/` })
30
+ *
31
+ * A token is checked as a database checks one (`../database/auth.ts`): its signature, issuer, audience and times. A
32
+ * request with no token is anyone's. A rule `write` reaches what `read` does and puts and deletes too; a `public` rule
33
+ * only reads. A key reaches a rule when it starts with the rule's folder, `{subject}` replaced by the caller's subject;
34
+ * a listing reaches it when its prefix does. A bucket with no rules reaches nothing, and the first rule that fits a
35
+ * request decides it.
36
+ *
37
+ * Every limit is named when it refuses: 20 rules a bucket, a folder of 512 bytes, keys of 1,024, and a file put
38
+ * of at most `maxBytes` (10 MiB unless the rule says, at most 100 MiB; a larger file goes through the S3 API). A
39
+ * subject that has a slash can't name a folder, and a bucket whose rules name `{subject}` trusts one provider, since
40
+ * two could give one subject to two different people. Nothing here reaches a preview's folder (`.previews/`).
41
+ */
42
+ /** The bounds of a bucket's settings and of what its app users send. */
43
+ const FILE_LIMITS = {
44
+ rules: 20,
45
+ providers: 8,
46
+ prefixBytes: 512,
47
+ keyBytes: 1024,
48
+ contentTypes: 20,
49
+ defaultBytes: 10485760,
50
+ maxBytes: 104857600,
51
+ subject: 256,
52
+ list: 1e3
53
+ };
54
+ /** The part of a rule's folder that stands for each user's own. */
55
+ const SUBJECT = "{subject}";
56
+ /** Where previews keep their own files in a bucket: never reached by an app's users. */
57
+ const PREVIEWS = ".previews/";
58
+ const encoder = new TextEncoder();
59
+ const bytes = (text) => encoder.encode(text).length;
60
+ const CONTROL = /[\u0000-\u001f\u007f]/u;
61
+ const MEDIA = /^[a-z0-9][a-z0-9!#$&^_.+-]*\/(?:\*|[a-z0-9][a-z0-9!#$&^_.+-]*)$/u;
62
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
63
+ /** Why a path can't be a key or folder an app user names, or undefined. `folder`: it may be empty and ends in `/` when not. */
64
+ function pathProblem(path, what) {
65
+ if (what === "key" && path.length === 0) return "A file's key is 1 to 1,024 bytes.";
66
+ if (bytes(path) > FILE_LIMITS.keyBytes) return `A ${what === "key" ? "file's key" : "listing's prefix"} is at most 1,024 bytes.`;
67
+ if (CONTROL.test(path)) return `A ${what} holds no control characters.`;
68
+ if (path.startsWith("/") || path.includes("//")) return `A ${what} doesn't start with a slash or hold two together: name it as users/ada/photo.png.`;
69
+ if (path.split("/").some((part) => part === "." || part === "..")) return `A ${what} has no . or .. folder: name the file's own folder.`;
70
+ if (path.startsWith(PREVIEWS)) return "A preview's files are its own: an app's users never reach .previews/.";
71
+ }
72
+ /** Why a subject can't name a user's folder, or undefined. */
73
+ function subjectProblem(subject) {
74
+ if (subject.length < 1 || subject.length > FILE_LIMITS.subject) return `The user's subject is 1 to ${FILE_LIMITS.subject} characters.`;
75
+ if (subject.includes("/") || CONTROL.test(subject) || subject === "." || subject === "..") return "The user's subject has a slash or a character a folder can't, so it names no folder of theirs.";
76
+ }
77
+ /**
78
+ * A bucket's settings, checked: the shape `storage bucket settings set` sends. Throws `StorageError` `invalid` saying
79
+ * what is wrong. Providers are the shape `db/auth.config.ts` writes, with every value written out: a bucket has no
80
+ * Environment to read one from.
81
+ */
82
+ function bucketAccessOf(value) {
83
+ const refuse = (why) => {
84
+ throw new StorageError("invalid", why);
85
+ };
86
+ if (!isObject(value)) refuse("A bucket's settings are { providers, rules }.");
87
+ const { providers = [], rules = [], ...other } = value;
88
+ const extra = Object.keys(other)[0];
89
+ if (extra !== void 0) refuse(`A bucket's settings have no ${JSON.stringify(extra)}: they take providers and rules.`);
90
+ if (!Array.isArray(rules) || rules.length > FILE_LIMITS.rules) refuse(`A bucket has at most ${FILE_LIMITS.rules} rules.`);
91
+ if (!Array.isArray(providers) || providers.length > FILE_LIMITS.providers) refuse(`A bucket trusts at most ${FILE_LIMITS.providers} sign-in providers.`);
92
+ for (const provider of providers) if (isObject(provider) && Object.values(provider).some((field) => typeof field !== "string")) refuse("A bucket's sign-in providers are written out: their issuer and applicationID are no secrets, so name them as text.");
93
+ let checked;
94
+ try {
95
+ checked = authConfigOf({ providers }).providers;
96
+ } catch (error) {
97
+ return refuse(`A bucket's sign-in providers: ${error.message}.`);
98
+ }
99
+ const read = rules.map((rule, at) => {
100
+ const where = `Rule ${at + 1}`;
101
+ if (!isObject(rule)) return refuse(`${where} is { prefix, access }.`);
102
+ const { prefix, access, public: open, maxBytes, contentTypes, ...rest } = rule;
103
+ const unknown = Object.keys(rest)[0];
104
+ if (unknown !== void 0) refuse(`${where} has no ${JSON.stringify(unknown)}: a rule takes prefix, access, public, maxBytes and contentTypes.`);
105
+ if (typeof prefix !== "string") return refuse(`${where}'s prefix is the folder it reaches, such as users/{subject}/.`);
106
+ if (access !== "read" && access !== "write") refuse(`${where}'s access is read or write.`);
107
+ if (bytes(prefix) > FILE_LIMITS.prefixBytes) refuse(`${where}'s prefix is at most ${FILE_LIMITS.prefixBytes} bytes.`);
108
+ const named = prefix.split(SUBJECT).length - 1;
109
+ const bare = prefix.replaceAll(SUBJECT, "x");
110
+ if (named > 1) refuse(`${where} names ${SUBJECT} once at most.`);
111
+ if (bare.includes("{") || bare.includes("}")) refuse(`${where}'s prefix names nothing in braces but ${SUBJECT}.`);
112
+ if (named === 1 && !new RegExp(`(?:^|/)\\{subject\\}/`, "u").test(prefix)) refuse(`${where} names ${SUBJECT} as a whole folder, followed by a slash: users/${SUBJECT}/.`);
113
+ if (prefix) {
114
+ const problem = pathProblem(bare, "prefix");
115
+ if (problem) refuse(`${where}: ${problem}`);
116
+ }
117
+ if (open !== void 0 && typeof open !== "boolean") refuse(`${where}'s public is true or false.`);
118
+ if (open && (access !== "read" || named)) refuse(`${where} is public, so it only reads, and reaches no one's own folder: drop ${SUBJECT} or public.`);
119
+ if ((maxBytes !== void 0 || contentTypes !== void 0) && access !== "write") refuse(`${where} only reads: maxBytes and contentTypes bound what a write rule puts.`);
120
+ if (maxBytes !== void 0 && !(Number.isInteger(maxBytes) && maxBytes >= 1 && maxBytes <= FILE_LIMITS.maxBytes)) refuse(`${where}'s maxBytes is 1 to ${FILE_LIMITS.maxBytes.toLocaleString("en")} (100 MiB). A larger file goes through the S3 API.`);
121
+ if (contentTypes !== void 0 && !(Array.isArray(contentTypes) && contentTypes.length >= 1 && contentTypes.length <= FILE_LIMITS.contentTypes && contentTypes.every((type) => typeof type === "string" && MEDIA.test(type)))) refuse(`${where}'s contentTypes are 1 to ${FILE_LIMITS.contentTypes} lowercase media types, such as image/png or image/*.`);
122
+ return Object.freeze({
123
+ prefix,
124
+ access,
125
+ ...open ? { public: true } : {},
126
+ ...maxBytes !== void 0 ? { maxBytes } : {},
127
+ ...contentTypes !== void 0 ? { contentTypes: Object.freeze([...contentTypes]) } : {}
128
+ });
129
+ });
130
+ if (read.some((rule) => !rule.public) && checked.length === 0) refuse("Name the sign-in provider whose users the bucket's rules reach: the one in your db/auth.config.ts.");
131
+ if (read.some((rule) => rule.prefix.includes("{subject}")) && checked.length > 1) refuse(`A bucket whose rules name ${SUBJECT} trusts one sign-in provider: two could give one subject to two different people.`);
132
+ return Object.freeze({
133
+ providers: checked,
134
+ rules: Object.freeze(read)
135
+ });
136
+ }
137
+ const VERBS = {
138
+ read: "read",
139
+ list: "list",
140
+ write: "put",
141
+ delete: "delete"
142
+ };
143
+ /** A rule's folder for a caller: `{subject}` made theirs; undefined where the rule needs a subject the caller can't give. */
144
+ function folderOf(rule, subject) {
145
+ if (!rule.prefix.includes("{subject}")) return rule.prefix;
146
+ return subject !== null && !subjectProblem(subject) ? rule.prefix.replace(SUBJECT, subject) : void 0;
147
+ }
148
+ /** Whether a media type is one of `types`, each exact or `type/*`. Parameters such as `; charset=utf-8` are not compared. */
149
+ const takes = (types, contentType) => {
150
+ const type = contentType.split(";")[0].trim().toLowerCase();
151
+ return types.some((one) => one === type || one.endsWith("/*") && type.startsWith(one.slice(0, -1)));
152
+ };
153
+ /**
154
+ * Whether a bucket's rules let a caller do `op` at `path`: undefined when they do, else why not. `subject` is the
155
+ * caller's verified subject, null for anyone. A write gives its `size` in bytes and its `contentType`. Pure: the same
156
+ * settings and ask always return the same.
157
+ */
158
+ function fileRefusal(access, ask) {
159
+ const problem = ask.op === "list" ? ask.path ? pathProblem(ask.path, "prefix") : void 0 : pathProblem(ask.path, "key");
160
+ if (problem) return {
161
+ status: 400,
162
+ code: "invalid",
163
+ message: problem
164
+ };
165
+ const writes = ask.op === "write" || ask.op === "delete";
166
+ const allowed = access.rules.filter((rule) => (writes ? rule.access === "write" : true) && (rule.public || ask.subject !== null));
167
+ const fits = allowed.filter((rule) => {
168
+ const folder = folderOf(rule, ask.subject);
169
+ return folder !== void 0 && ask.path.startsWith(folder);
170
+ });
171
+ const verb = VERBS[ask.op];
172
+ if (fits.length === 0) {
173
+ if (ask.subject === null) return {
174
+ status: 401,
175
+ code: "unauthenticated",
176
+ message: `Sign in to ${verb} this: send the user's token from your sign-in provider as Authorization: Bearer <token>.`
177
+ };
178
+ const subject = access.rules.some((rule) => rule.prefix.includes("{subject}")) ? subjectProblem(ask.subject) : void 0;
179
+ if (subject) return {
180
+ status: 403,
181
+ code: "forbidden",
182
+ message: subject
183
+ };
184
+ const theirs = [...new Set(allowed.flatMap((rule) => (rule.public ? [] : [folderOf(rule, ask.subject)]).filter((folder) => folder !== "")))];
185
+ return {
186
+ status: 403,
187
+ code: "forbidden",
188
+ message: `No rule of this bucket lets this user ${verb} ${ask.path || "the whole bucket"}.${theirs.length ? ` They may ${verb} under ${theirs.join(", ")}.` : ""}`
189
+ };
190
+ }
191
+ if (ask.op !== "write") return void 0;
192
+ const size = ask.size ?? 0;
193
+ const sized = fits.filter((rule) => size <= (rule.maxBytes ?? FILE_LIMITS.defaultBytes));
194
+ if (sized.length === 0) {
195
+ const most = Math.max(...fits.map((rule) => rule.maxBytes ?? FILE_LIMITS.defaultBytes));
196
+ return {
197
+ status: 413,
198
+ code: "too_large",
199
+ message: `This file is ${size.toLocaleString("en")} bytes; this bucket takes at most ${most.toLocaleString("en")} here.`
200
+ };
201
+ }
202
+ const contentType = ask.contentType ?? "application/octet-stream";
203
+ if (!sized.some((rule) => !rule.contentTypes || takes(rule.contentTypes, contentType))) return {
204
+ status: 415,
205
+ code: "unsupported_type",
206
+ message: `This bucket takes ${[...new Set(sized.flatMap((rule) => rule.contentTypes ?? []))].join(", ")} here, not ${contentType.split(";")[0]}.`
207
+ };
208
+ }
209
+ /** Where the files of a Team's buckets are served, on the API origin: `/storage/app/<team>/<bucket>/<key>`. */
210
+ const FILES_BASE = "/storage/app";
211
+ /** Whether a path on the API origin is the files endpoint's. */
212
+ const isAppPath = (path) => path === "/storage/app" || path.startsWith(`/storage/app/`);
213
+ /** Kinds of media a browser runs as a page: served from the API's origin, they are only ever downloaded. */
214
+ const ACTIVE = /^(?:text\/html|application\/xhtml\+xml|image\/svg\+xml|text\/xml|application\/xml|text\/javascript|application\/javascript)\b/iu;
215
+ const CORS = {
216
+ "Access-Control-Allow-Origin": "*",
217
+ "Access-Control-Expose-Headers": "ETag, Content-Length, Content-Type, Last-Modified"
218
+ };
219
+ const answer = (status, code, message) => Response.json({ error: {
220
+ code,
221
+ message
222
+ } }, {
223
+ status,
224
+ headers: CORS
225
+ });
226
+ const fileOf = (object) => ({
227
+ key: object.key,
228
+ size: object.size,
229
+ etag: object.etag,
230
+ contentType: object.contentType,
231
+ uploadedAt: object.uploadedAt
232
+ });
233
+ /** At most `size` bytes of `body`, or undefined when it holds more or fewer. */
234
+ async function exactly(body, size) {
235
+ const out = new Uint8Array(size);
236
+ let at = 0;
237
+ const reader = body?.getReader();
238
+ for (;;) {
239
+ const read = reader ? await reader.read() : {
240
+ done: true,
241
+ value: void 0
242
+ };
243
+ if (read.done) break;
244
+ if (at + read.value.byteLength > size) {
245
+ await reader.cancel();
246
+ return;
247
+ }
248
+ out.set(read.value, at);
249
+ at += read.value.byteLength;
250
+ }
251
+ return at === size ? out : void 0;
252
+ }
253
+ /**
254
+ * The files endpoint: serves a request at `FILES_BASE` as the bucket's settings let its caller, over `engine`.
255
+ * `bucket` finds a Team's bucket by handle and name (undefined: none, or app users reach none of it); `counted` is told
256
+ * each served request's bucket and class (`a` puts, deletes and lists, `b` reads), as the S3 endpoint counts them.
257
+ * Tokens are checked with `verify`'s fetch, resolve and clock; a verifier is kept per set of providers, so a provider's
258
+ * keys are fetched once for every bucket that trusts it.
259
+ */
260
+ function filesServer(options) {
261
+ const { engine } = options;
262
+ const verifiers = /* @__PURE__ */ new Map();
263
+ const verifierOf = (providers) => {
264
+ const id = JSON.stringify(providers);
265
+ let found = verifiers.get(id);
266
+ if (!found) {
267
+ if (verifiers.size >= 64) verifiers.delete(verifiers.keys().next().value);
268
+ found = verifier(trustedOf({
269
+ providers,
270
+ anonymous: true
271
+ }, () => void 0), options.verify);
272
+ verifiers.set(id, found);
273
+ }
274
+ return found;
275
+ };
276
+ return async (request) => {
277
+ if (request.method === "OPTIONS") return new Response(null, {
278
+ status: 204,
279
+ headers: {
280
+ ...CORS,
281
+ "Access-Control-Allow-Methods": "GET, HEAD, PUT, DELETE, OPTIONS",
282
+ "Access-Control-Allow-Headers": "Authorization, Content-Type, If-None-Match",
283
+ "Access-Control-Max-Age": "600"
284
+ }
285
+ });
286
+ const url = new URL(request.url);
287
+ const [team, name, ...rest] = url.pathname.slice(13).split("/");
288
+ if (!team || !name) return answer(404, "not_found", "Name the team and bucket: /storage/app/<team>/<bucket>/<key>.");
289
+ try {
290
+ checkBucketName(name);
291
+ } catch {
292
+ return answer(404, "not_found", `${name} is not a bucket name.`);
293
+ }
294
+ let key;
295
+ try {
296
+ key = rest.map((part) => decodeURIComponent(part)).join("/");
297
+ } catch {
298
+ return answer(400, "invalid", "The file's key is not percent-encoded as an address takes it.");
299
+ }
300
+ const found = await options.bucket(team, name);
301
+ if (!found || !found.access.rules.length) return answer(404, "not_found", `${team} has no bucket ${name} whose files its app's users reach.`);
302
+ let subject = null;
303
+ const header = request.headers.get("Authorization");
304
+ if (header) {
305
+ const token = /^Bearer\s+(\S+)$/iu.exec(header)?.[1];
306
+ if (!token) return answer(401, "unauthenticated", "Send the user's token as Authorization: Bearer <token>.");
307
+ if (found.access.providers.length) try {
308
+ subject = (await verifierOf(found.access.providers)(token)).subject;
309
+ } catch (error) {
310
+ if (error instanceof DatabaseError && error.code === "unavailable") return answer(503, "unavailable", `${error.message}. Try again.`);
311
+ if (error instanceof DatabaseError) return answer(401, "unauthenticated", `The token was refused: ${error.message}.`);
312
+ throw error;
313
+ }
314
+ }
315
+ const method = request.method === "HEAD" ? "GET" : request.method;
316
+ const op = method === "GET" ? key ? "read" : "list" : method === "PUT" && key ? "write" : method === "DELETE" && key ? "delete" : void 0;
317
+ if (!op) return answer(405, "invalid", key ? "Use GET, HEAD, PUT or DELETE on a file." : "List a bucket's files with GET; name a file to put or delete it.");
318
+ const path = op === "list" ? url.searchParams.get("prefix") ?? "" : key;
319
+ const contentType = request.headers.get("Content-Type") ?? "application/octet-stream";
320
+ const length = request.headers.get("Content-Length");
321
+ const size = length === null ? void 0 : Number(length);
322
+ if (op === "write" && (size === void 0 || !Number.isSafeInteger(size) || size < 0)) return answer(400, "invalid", "Send the file's size in bytes as Content-Length.");
323
+ const refused = fileRefusal(found.access, {
324
+ op,
325
+ path,
326
+ subject,
327
+ ...size === void 0 ? {} : { size },
328
+ contentType
329
+ });
330
+ if (refused) return answer(refused.status, refused.code, refused.message);
331
+ try {
332
+ if (op === "list") {
333
+ const limit = Number(url.searchParams.get("limit") ?? 100);
334
+ if (!Number.isInteger(limit) || limit < 1 || limit > FILE_LIMITS.list) return answer(400, "invalid", `A listing's limit is 1 to ${FILE_LIMITS.list.toLocaleString("en")}.`);
335
+ const after = url.searchParams.get("after"), delimiter = url.searchParams.get("delimiter");
336
+ const listed = await engine.list(found.bucket, {
337
+ prefix: path,
338
+ limit,
339
+ ...after ? { after } : {},
340
+ ...delimiter ? { delimiter } : {}
341
+ });
342
+ options.counted?.(found.bucket, "a");
343
+ return Response.json({
344
+ files: listed.objects.filter((object) => !object.key.startsWith(PREVIEWS)).map(fileOf),
345
+ folders: listed.prefixes.filter((prefix) => !prefix.startsWith(PREVIEWS)),
346
+ ...listed.next !== void 0 ? { next: listed.next } : {}
347
+ }, { headers: {
348
+ ...CORS,
349
+ "Cache-Control": "private, no-store"
350
+ } });
351
+ }
352
+ if (op === "read") {
353
+ const head = await engine.head(found.bucket, key);
354
+ options.counted?.(found.bucket, "b");
355
+ if (!head) return answer(404, "not_found", `There is no file ${key}.`);
356
+ const open = fileRefusal(found.access, {
357
+ op,
358
+ path,
359
+ subject: null
360
+ }) === void 0;
361
+ const headers = {
362
+ ...CORS,
363
+ "Content-Type": head.contentType,
364
+ "Content-Length": String(head.size),
365
+ ETag: `"${head.etag}"`,
366
+ "Cache-Control": open ? "no-cache" : "private, no-store",
367
+ "Last-Modified": new Date(head.uploadedAt).toUTCString(),
368
+ "X-Content-Type-Options": "nosniff",
369
+ "Content-Security-Policy": "sandbox; default-src 'none'",
370
+ ...ACTIVE.test(head.contentType) ? { "Content-Disposition": `attachment; filename*=UTF-8''${encodeURIComponent(key.split("/").at(-1))}` } : {}
371
+ };
372
+ if (request.headers.get("If-None-Match")?.replaceAll("\"", "") === head.etag) return new Response(null, {
373
+ status: 304,
374
+ headers
375
+ });
376
+ if (request.method === "HEAD") return new Response(null, { headers });
377
+ const streamed = engine.stream ? await engine.stream(found.bucket, key) : null;
378
+ if (streamed) return new Response(streamed.body, { headers });
379
+ const read = await engine.get(found.bucket, key);
380
+ if (!read) return answer(404, "not_found", `There is no file ${key}.`);
381
+ return new Response(read.body, { headers });
382
+ }
383
+ if (found.paused) return answer(403, "forbidden", "This bucket's team reached its budget, so its files can't change until the budget is raised. Reading goes on.");
384
+ if (op === "delete") {
385
+ await engine.delete(found.bucket, key);
386
+ options.counted?.(found.bucket, "a");
387
+ return new Response(null, {
388
+ status: 204,
389
+ headers: CORS
390
+ });
391
+ }
392
+ const put = {
393
+ contentType,
394
+ metadata: {},
395
+ ...request.headers.get("If-None-Match") === "*" ? { ifNoneMatch: "*" } : {}
396
+ };
397
+ let stored;
398
+ if (engine.putStream && request.body) stored = await engine.putStream(found.bucket, key, request.body, size, put);
399
+ else {
400
+ const body = await exactly(request.body, size);
401
+ if (!body) return answer(400, "invalid", "The file's bytes are not as many as its Content-Length says.");
402
+ stored = await engine.put(found.bucket, key, body, put);
403
+ }
404
+ options.counted?.(found.bucket, "a");
405
+ return Response.json(fileOf(stored), {
406
+ status: 201,
407
+ headers: CORS
408
+ });
409
+ } catch (error) {
410
+ if (error instanceof StorageError && error.code === "conflict") return answer(412, "conflict", `There is a file ${key} already.`);
411
+ if (error instanceof StorageError && error.code === "invalid") return answer(400, "invalid", error.message);
412
+ throw error;
413
+ }
414
+ };
415
+ }
416
+ /**
417
+ * A bucket's files for one of your app's users, from their browser or your own code: `origin` is the API's address
418
+ * (`https://api.midsummer.new`), and `token` gives the user's token from your sign-in provider, or nothing for anyone.
419
+ */
420
+ function files(options) {
421
+ checkBucketName(options.bucket);
422
+ const send = options.fetch ?? ((url, init) => fetch(url, init));
423
+ const base = `${options.origin.replace(/\/+$/u, "")}${FILES_BASE}/${encodeURIComponent(options.team)}/${options.bucket}`;
424
+ const at = (key) => {
425
+ const problem = pathProblem(key, "key");
426
+ if (problem) throw new StorageError("invalid", problem);
427
+ return `${base}/${key.split("/").map(encodeURIComponent).join("/")}`;
428
+ };
429
+ const call = async (url, init = {}) => {
430
+ const token = await options.token?.();
431
+ let response;
432
+ try {
433
+ response = await send(url, {
434
+ ...init,
435
+ headers: {
436
+ ...init.headers,
437
+ ...token ? { Authorization: `Bearer ${token}` } : {}
438
+ }
439
+ });
440
+ } catch {
441
+ throw new StorageError("unavailable", "The files endpoint could not be reached. Try again.");
442
+ }
443
+ if (response.ok || response.status === 304 || response.status === 404 && init.method === void 0) return response;
444
+ const message = (await response.json().catch(() => ({}))).error?.message ?? `The files endpoint answered ${response.status}.`;
445
+ const code = response.status === 401 || response.status === 403 ? "forbidden" : response.status === 404 ? "not_found" : response.status === 412 ? "conflict" : response.status === 429 || response.status >= 500 ? "unavailable" : "invalid";
446
+ throw new StorageError(code, message);
447
+ };
448
+ return {
449
+ url: at,
450
+ async put(key, body, put = {}) {
451
+ const url = at(key);
452
+ const bytes = typeof body === "string" ? encoder.encode(body) : body instanceof Blob ? new Uint8Array(await body.arrayBuffer()) : body instanceof Uint8Array ? body : new Uint8Array(body);
453
+ const contentType = put.contentType ?? (body instanceof Blob && body.type ? body.type : "application/octet-stream");
454
+ return await (await call(url, {
455
+ method: "PUT",
456
+ body: bytes,
457
+ headers: {
458
+ "Content-Type": contentType,
459
+ "Content-Length": String(bytes.byteLength),
460
+ ...put.ifNoneMatch ? { "If-None-Match": "*" } : {}
461
+ }
462
+ })).json();
463
+ },
464
+ async get(key) {
465
+ const response = await call(at(key));
466
+ if (response.status === 404) return null;
467
+ return {
468
+ key,
469
+ size: Number(response.headers.get("Content-Length") ?? 0),
470
+ etag: (response.headers.get("ETag") ?? "").replaceAll("\"", ""),
471
+ contentType: response.headers.get("Content-Type") ?? "application/octet-stream",
472
+ uploadedAt: Date.parse(response.headers.get("Last-Modified") ?? "") || 0,
473
+ body: new Uint8Array(await response.arrayBuffer())
474
+ };
475
+ },
476
+ async list(listing = {}) {
477
+ const query = new URLSearchParams();
478
+ if (listing.prefix) query.set("prefix", listing.prefix);
479
+ if (listing.after) query.set("after", listing.after);
480
+ if (listing.limit !== void 0) query.set("limit", String(listing.limit));
481
+ if (listing.delimiter) query.set("delimiter", listing.delimiter);
482
+ return await (await call(`${base}${query.size ? `?${query}` : ""}`, { method: "GET" })).json();
483
+ },
484
+ async delete(key) {
485
+ await call(at(key), { method: "DELETE" });
486
+ }
487
+ };
488
+ }
489
+ /**
490
+ * The files endpoint in memory, for tests and `midsummer dev`: each bucket of each team is a bucket of `engine` by its
491
+ * own name, and `set` gives one its settings as `storage bucket settings set` does, checked the same way.
492
+ */
493
+ function filesStandIn(options) {
494
+ const settings = /* @__PURE__ */ new Map();
495
+ return {
496
+ set(team, bucket, access) {
497
+ settings.set(`${team}/${bucket}`, bucketAccessOf(access));
498
+ },
499
+ fetch: filesServer({
500
+ engine: options.engine,
501
+ ...options.verify ? { verify: options.verify } : {},
502
+ bucket: async (team, name) => {
503
+ const access = settings.get(`${team}/${name}`);
504
+ return access && {
505
+ bucket: name,
506
+ access
507
+ };
508
+ }
509
+ })
510
+ };
511
+ }
512
+ //#endregion
513
+ export { FILES_BASE, FILE_LIMITS, SUBJECT, bucketAccessOf, fileRefusal, files, filesServer, filesStandIn, isAppPath, subjectProblem };
package/wire.mjs CHANGED
@@ -1,4 +1,5 @@
1
- import { _ as storageErrorReasons, a as checkMetadata, c as checkRange, g as storageErrorCodes, h as StorageError, i as checkListLimit, l as checkUploadId, n as checkBucketName, o as checkPartNumber, r as checkKey, s as checkParts } from "./names-DfCBKupJ.mjs";
1
+ import { n as storageErrorCodes, r as storageErrorReasons, t as StorageError } from "./errors-B1tO_wdm.mjs";
2
+ import { a as checkMetadata, c as checkRange, i as checkListLimit, l as checkUploadId, n as checkBucketName, o as checkPartNumber, r as checkKey, s as checkParts } from "./names-Do0ot5Ha.mjs";
2
3
  import { z } from "zod";
3
4
  //#region src/wire.ts
4
5
  /**