gencow 0.1.299 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/gencow.mjs +0 -6
- package/core/package.json +1 -1
- package/docs/packaging.md +14 -4
- package/lib/cli-artifact-guard.mjs +53 -3
- package/lib/cli-dev-runtime.mjs +1 -0
- package/lib/cli-project-runtime.mjs +26 -14
- package/lib/codegen-command.mjs +16 -0
- package/lib/coding-guardrails.mjs +2 -0
- package/lib/dashboard-artifact.mjs +65 -0
- package/lib/dashboard-assets.mjs +20 -0
- package/lib/db-command.mjs +121 -80
- package/lib/db-migration-command-steps.mjs +19 -16
- package/lib/db-push-command.mjs +1 -1
- package/lib/deploy-codegen-preflight.mjs +1 -0
- package/lib/dev-cloud-command.mjs +1 -1
- package/lib/dev-local-command.mjs +19 -56
- package/lib/document-local-converter.mjs +11 -0
- package/lib/local-dashboard-plan.mjs +60 -0
- package/lib/local-database-commands.mjs +127 -0
- package/lib/local-development-migrations.mjs +157 -0
- package/lib/local-drizzle-database.config.mjs +10 -0
- package/lib/local-runtime-features.mjs +12 -0
- package/lib/rag-selection.mjs +7 -0
- package/lib/runtime-local-worker.mjs +116 -0
- package/lib/runtime-mode.mjs +3 -0
- package/lib/standalone-codegen-adapter.mjs +91 -0
- package/lib/ts-codegen-import-extension.mjs +228 -19
- package/package.json +15 -8
- package/runtime/config.mjs +218 -2
- package/runtime/engine/chunk-2HA4CUMS.mjs +90 -0
- package/runtime/engine/chunk-2JLO3KMM.mjs +305 -0
- package/runtime/engine/chunk-2SR2M7SR.mjs +1045 -0
- package/runtime/engine/chunk-3D7MHEUC.mjs +253 -0
- package/runtime/engine/chunk-3R7COBWG.mjs +309 -0
- package/runtime/engine/chunk-3ZKA54UW.mjs +1560 -0
- package/runtime/engine/chunk-45I4YR2J.mjs +9 -0
- package/runtime/engine/chunk-4MLRXO7F.mjs +74 -0
- package/runtime/engine/chunk-5575APCJ.mjs +215 -0
- package/runtime/engine/chunk-5GUJZQF3.mjs +114 -0
- package/runtime/engine/chunk-5MXY3T75.mjs +428 -0
- package/runtime/engine/chunk-5TACQ2US.mjs +44 -0
- package/runtime/engine/chunk-66G4YEDT.mjs +3104 -0
- package/runtime/engine/chunk-67YO53WW.mjs +1426 -0
- package/runtime/engine/chunk-6GQRM7XY.mjs +87 -0
- package/runtime/engine/chunk-6JO72SPP.mjs +68 -0
- package/runtime/engine/chunk-6W653LXI.mjs +13 -0
- package/runtime/engine/chunk-7ITSMI3S.mjs +69 -0
- package/runtime/engine/chunk-7KUJ2H2S.mjs +128 -0
- package/runtime/engine/chunk-A5BMQ5IC.mjs +45 -0
- package/runtime/engine/chunk-ADF3UR6L.mjs +428 -0
- package/runtime/engine/chunk-AEBW7XZJ.mjs +4510 -0
- package/runtime/engine/chunk-AGPQ5XIV.mjs +156 -0
- package/runtime/engine/chunk-CPU4OZSX.mjs +753 -0
- package/runtime/engine/chunk-CSWPPWBL.mjs +50 -0
- package/runtime/engine/chunk-DPWXSMWO.mjs +53 -0
- package/runtime/engine/chunk-EAIELFKU.mjs +151 -0
- package/runtime/engine/chunk-EDU5CBKT.mjs +10 -0
- package/runtime/engine/chunk-EQCTAET7.mjs +173 -0
- package/runtime/engine/chunk-EQCXDF2Z.mjs +70 -0
- package/runtime/engine/chunk-F3G4UGV4.mjs +330 -0
- package/runtime/engine/chunk-F62NUNOO.mjs +26 -0
- package/runtime/engine/chunk-FKPNIFRP.mjs +2492 -0
- package/runtime/engine/chunk-FM23RGVI.mjs +81 -0
- package/runtime/engine/chunk-FW5AK4YP.mjs +1041 -0
- package/runtime/engine/chunk-GDWYAGWV.mjs +23 -0
- package/runtime/engine/chunk-GO5PZUYW.mjs +53 -0
- package/runtime/engine/chunk-GOLP7OSG.mjs +340 -0
- package/runtime/engine/chunk-GSLM44EF.mjs +242 -0
- package/runtime/engine/chunk-GYAJ7OX2.mjs +125 -0
- package/runtime/engine/chunk-I3GWR43K.mjs +14 -0
- package/runtime/engine/chunk-IFMOTJNU.mjs +106 -0
- package/runtime/engine/chunk-IKQKBE2G.mjs +128 -0
- package/runtime/engine/chunk-ITH2NEKM.mjs +282 -0
- package/runtime/engine/chunk-J6SDRCG4.mjs +96 -0
- package/runtime/engine/chunk-JODRNM3S.mjs +29596 -0
- package/runtime/engine/chunk-JUDKX53X.mjs +137 -0
- package/runtime/engine/chunk-K2YZVPJ4.mjs +827 -0
- package/runtime/engine/chunk-KEZJUXEE.mjs +151 -0
- package/runtime/engine/chunk-KVLTJFCH.mjs +234 -0
- package/runtime/engine/chunk-KX2PRQPS.mjs +126 -0
- package/runtime/engine/chunk-LEW5ZMLR.mjs +76 -0
- package/runtime/engine/chunk-LINVSJEM.mjs +175 -0
- package/runtime/engine/chunk-M7K2ICSM.mjs +11 -0
- package/runtime/engine/chunk-MZXDXSDC.mjs +292 -0
- package/runtime/engine/chunk-N2TA2IK2.mjs +678 -0
- package/runtime/engine/chunk-N4LTCKJP.mjs +695 -0
- package/runtime/engine/chunk-N6GCLOUX.mjs +13 -0
- package/runtime/engine/chunk-NAG2OXS5.mjs +37 -0
- package/runtime/engine/chunk-NNZ2QJUG.mjs +381 -0
- package/runtime/engine/chunk-NZPPLDNW.mjs +15 -0
- package/runtime/engine/chunk-ODWM57W6.mjs +138 -0
- package/runtime/engine/chunk-P5IIXAIE.mjs +23 -0
- package/runtime/engine/chunk-PBOXB2BV.mjs +6 -0
- package/runtime/engine/chunk-PMOJLN2P.mjs +8 -0
- package/runtime/engine/chunk-PZFMKFHO.mjs +180 -0
- package/runtime/engine/chunk-QL2TQX2N.mjs +114 -0
- package/runtime/engine/chunk-RITT2RSJ.mjs +258 -0
- package/runtime/engine/chunk-RODBVJ5M.mjs +135 -0
- package/runtime/engine/chunk-RW65MPVY.mjs +261 -0
- package/runtime/engine/chunk-S67UYPB6.mjs +25 -0
- package/runtime/engine/chunk-SVJCOUI3.mjs +47 -0
- package/runtime/engine/chunk-TCN3ZASV.mjs +957 -0
- package/runtime/engine/chunk-U2NRG6KC.mjs +32 -0
- package/runtime/engine/chunk-UM3F7HUV.mjs +432 -0
- package/runtime/engine/chunk-VWU7JJ3P.mjs +146 -0
- package/runtime/engine/chunk-WDTKPPMU.mjs +310 -0
- package/runtime/engine/chunk-WJOO4XTB.mjs +31 -0
- package/runtime/engine/chunk-XNFVL2OY.mjs +63 -0
- package/runtime/engine/chunk-XPWJXP2J.mjs +58 -0
- package/runtime/engine/chunk-Y3HSBJ3I.mjs +1132 -0
- package/runtime/engine/chunk-YMH4RYSX.mjs +317 -0
- package/runtime/engine/chunk-YNOMPSGS.mjs +8 -0
- package/runtime/engine/chunk-YRBAYTEZ.mjs +251 -0
- package/runtime/engine/chunk-YRHM272W.mjs +528 -0
- package/runtime/engine/chunk-ZQUZAGIQ.mjs +149 -0
- package/runtime/engine/chunk-ZXMM7QFP.mjs +176 -0
- package/runtime/engine/chunk-ZZJSIPV2.mjs +262 -0
- package/runtime/engine/composition.mjs +325 -0
- package/runtime/engine/document-local.mjs +504 -0
- package/runtime/engine/graph.json +4134 -0
- package/runtime/engine/index.mjs +265 -0
- package/runtime/engine/local-postgres-support.mjs +69 -0
- package/runtime/engine/local.mjs +3275 -0
- package/runtime/engine/pglite-directory-lock.mjs +8 -0
- package/runtime/engine/rag.mjs +11 -0
- package/runtime/engine/search.mjs +18 -0
- package/runtime/framework-migrations/foundation-bootstrap/rag.sql +115 -0
- package/runtime/framework-migrations/foundation-bootstrap/workflow.sql +194 -0
- package/runtime/framework-migrations/journal-bootstrap/migration.sql +26 -0
- package/runtime/framework-migrations/manifest.json +56 -0
- package/runtime/framework-migrations/rag/20261006111509_mushy_warhawk/migration.sql +121 -0
- package/runtime/framework-migrations/rag/20261013234621_rag_v2_lifecycle_markers/migration.sql +6 -0
- package/runtime/framework-migrations/workflow/20261006111508_perpetual_star_brand/migration.sql +31 -0
- package/runtime/runtime-metadata.json +27 -0
- package/runtime/tooling.mjs +10399 -8951
- package/scripts/bundle-runtime-config.mjs +23 -0
- package/scripts/bundle-runtime.mjs +100 -0
- package/scripts/bundle-runtime.test.mjs +33 -0
- package/scripts/bundle-shared.mjs +3 -0
- package/scripts/copy-dashboard.mjs +16 -0
- package/scripts/pre-publish-check.mjs +23 -11
- package/templateFeature/ai/ai-facade.ts +38 -15
- package/templateFeature/ai/manifest.json +1 -0
- package/templateFeature/sso/sso-auth-callback.tsx +37 -5
- package/templateFeature/tools/manifest.json +5 -2
- package/templateFeature/tools/tools.ts +3 -3
- package/runtime/server.mjs +0 -14389
- package/scripts/bundle-server.mjs +0 -223
- package/server/config.js +0 -1
- package/server/index.js +0 -1
- package/server/package.json +0 -6
|
@@ -0,0 +1,2492 @@
|
|
|
1
|
+
import {
|
|
2
|
+
decodeStorageCursor,
|
|
3
|
+
encodeStorageCursor,
|
|
4
|
+
invalidStorageCursor,
|
|
5
|
+
storageListOptions
|
|
6
|
+
} from "./chunk-7ITSMI3S.mjs";
|
|
7
|
+
import {
|
|
8
|
+
formatStorageContentResponse,
|
|
9
|
+
publicStorageObjectNotFound,
|
|
10
|
+
publicStorageObjectNotFoundResponse,
|
|
11
|
+
resolveRuntimeFilesystemImagePolicy,
|
|
12
|
+
runtimeFilesystemImagePolicy,
|
|
13
|
+
selectRuntimeImageTransform
|
|
14
|
+
} from "./chunk-2JLO3KMM.mjs";
|
|
15
|
+
import {
|
|
16
|
+
administrationMetadata,
|
|
17
|
+
assertAdministrationStorageId,
|
|
18
|
+
assertAdministrationUpload,
|
|
19
|
+
assertAdministrationVisibility,
|
|
20
|
+
filesystemLegacyMetadataSuffix,
|
|
21
|
+
filesystemMetadataMaxSerializedBytes,
|
|
22
|
+
filesystemMetadataSuffix,
|
|
23
|
+
filesystemReadGrantKeyFilename,
|
|
24
|
+
filesystemRootInternalDirectories,
|
|
25
|
+
filesystemRootOwnerFilename,
|
|
26
|
+
isValidStorageObjectId,
|
|
27
|
+
resolveRuntimeUploadLimits,
|
|
28
|
+
storageAdministrationInputInvalid,
|
|
29
|
+
storageAdministrationReadLimit,
|
|
30
|
+
storageAdministrationWrite
|
|
31
|
+
} from "./chunk-N4LTCKJP.mjs";
|
|
32
|
+
import {
|
|
33
|
+
filesystemCall,
|
|
34
|
+
filesystemErrorCode,
|
|
35
|
+
filesystemFailure,
|
|
36
|
+
filesystemMetadataInputInvalid,
|
|
37
|
+
filesystemMetadataInvalid,
|
|
38
|
+
filesystemMetadataUpdateLimitExceeded,
|
|
39
|
+
filesystemMutationWrite,
|
|
40
|
+
filesystemObjectNotFound,
|
|
41
|
+
filesystemStorageInputInvalid
|
|
42
|
+
} from "./chunk-GYAJ7OX2.mjs";
|
|
43
|
+
import {
|
|
44
|
+
assertRuntimeFileSize
|
|
45
|
+
} from "./chunk-GDWYAGWV.mjs";
|
|
46
|
+
import "./chunk-N2TA2IK2.mjs";
|
|
47
|
+
import {
|
|
48
|
+
snapshotRuntimeBinding
|
|
49
|
+
} from "./chunk-WDTKPPMU.mjs";
|
|
50
|
+
import "./chunk-NAG2OXS5.mjs";
|
|
51
|
+
import "./chunk-IKQKBE2G.mjs";
|
|
52
|
+
import {
|
|
53
|
+
runtimeStartupError
|
|
54
|
+
} from "./chunk-IFMOTJNU.mjs";
|
|
55
|
+
import {
|
|
56
|
+
DocumentConversionError
|
|
57
|
+
} from "./chunk-6JO72SPP.mjs";
|
|
58
|
+
import {
|
|
59
|
+
RuntimeDiagnosticError,
|
|
60
|
+
createBoundedWorkAdmission,
|
|
61
|
+
runtimeDiagnostic
|
|
62
|
+
} from "./chunk-AEBW7XZJ.mjs";
|
|
63
|
+
|
|
64
|
+
// ../runtime/dist/adapters/storage/filesystem-administration.js
|
|
65
|
+
function createFilesystemAdministration(input) {
|
|
66
|
+
const inspect = async (id) => {
|
|
67
|
+
assertAdministrationStorageId(id);
|
|
68
|
+
input.assertObjectAvailable(id);
|
|
69
|
+
const value = await input.resolveMetadata(id, 65536);
|
|
70
|
+
return value && administrationMetadata(value, value.createdAt, value.source);
|
|
71
|
+
};
|
|
72
|
+
return Object.freeze({
|
|
73
|
+
limits: input.limits,
|
|
74
|
+
order: "storage-id-asc",
|
|
75
|
+
...input.uploadReadGrants ? { uploadReadGrants: input.uploadReadGrants } : {},
|
|
76
|
+
inspect,
|
|
77
|
+
async scan(query) {
|
|
78
|
+
if (!Number.isSafeInteger(query.limit) || query.limit < 1 || query.limit > 1e3)
|
|
79
|
+
throw storageAdministrationInputInvalid();
|
|
80
|
+
const cursor = query.cursor ? decodeStorageCursor(query.cursor, input.catalog, "asc") : void 0;
|
|
81
|
+
if (cursor) {
|
|
82
|
+
try {
|
|
83
|
+
assertAdministrationStorageId(cursor.id);
|
|
84
|
+
} catch {
|
|
85
|
+
invalidStorageCursor();
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
input.boundary.assertRoot();
|
|
89
|
+
const ids = [...await input.listObjectIds()].filter((id) => !cursor || id > cursor.id).sort();
|
|
90
|
+
const page = ids.slice(0, query.limit);
|
|
91
|
+
const items = [];
|
|
92
|
+
for (const id of page) {
|
|
93
|
+
try {
|
|
94
|
+
assertAdministrationStorageId(id);
|
|
95
|
+
} catch {
|
|
96
|
+
throw filesystemMetadataInvalid();
|
|
97
|
+
}
|
|
98
|
+
const metadata = await inspect(id);
|
|
99
|
+
if (metadata)
|
|
100
|
+
items.push(metadata);
|
|
101
|
+
}
|
|
102
|
+
return {
|
|
103
|
+
items,
|
|
104
|
+
scanned: page.length,
|
|
105
|
+
nextCursor: ids.length > page.length && page.length ? encodeStorageCursor({ catalog: input.catalog, order: "asc", id: page.at(-1) }) : null
|
|
106
|
+
};
|
|
107
|
+
},
|
|
108
|
+
async upload(value) {
|
|
109
|
+
const captured = Object.freeze({ name: value.name, type: value.type, visibility: value.visibility });
|
|
110
|
+
assertAdministrationUpload(captured);
|
|
111
|
+
if (!(value.bytes instanceof Uint8Array))
|
|
112
|
+
throw storageAdministrationInputInvalid();
|
|
113
|
+
assertRuntimeFileSize(value.bytes.byteLength, input.limits.maxFileSizeBytes);
|
|
114
|
+
const data = Buffer.from(value.bytes);
|
|
115
|
+
return storageAdministrationWrite(async () => {
|
|
116
|
+
const stored = await input.put(data, captured.name, captured.type, captured.visibility, "dashboard");
|
|
117
|
+
return administrationMetadata(stored, stored.createdAt, stored.source);
|
|
118
|
+
});
|
|
119
|
+
},
|
|
120
|
+
async content(id) {
|
|
121
|
+
const metadata = await inspect(id);
|
|
122
|
+
if (!metadata)
|
|
123
|
+
return null;
|
|
124
|
+
if (metadata.size > input.limits.maxFileSizeBytes)
|
|
125
|
+
throw storageAdministrationReadLimit(input.limits.maxFileSizeBytes);
|
|
126
|
+
const bytes = await input.boundary.read(input.boundary.paths(id).data, input.limits.maxFileSizeBytes);
|
|
127
|
+
if (bytes.byteLength !== metadata.size)
|
|
128
|
+
throw filesystemMetadataInvalid();
|
|
129
|
+
return { metadata, bytes };
|
|
130
|
+
},
|
|
131
|
+
async setVisibility(id, visibility) {
|
|
132
|
+
assertAdministrationStorageId(id);
|
|
133
|
+
assertAdministrationVisibility(visibility);
|
|
134
|
+
if (!await inspect(id))
|
|
135
|
+
throw filesystemObjectNotFound();
|
|
136
|
+
return storageAdministrationWrite(async () => {
|
|
137
|
+
await input.storage.setVisibility(id, visibility);
|
|
138
|
+
const updated = await inspect(id);
|
|
139
|
+
if (!updated || updated.visibility !== visibility)
|
|
140
|
+
throw filesystemMetadataInvalid();
|
|
141
|
+
return updated;
|
|
142
|
+
});
|
|
143
|
+
},
|
|
144
|
+
async delete(id) {
|
|
145
|
+
assertAdministrationStorageId(id);
|
|
146
|
+
if (!await inspect(id))
|
|
147
|
+
throw filesystemObjectNotFound();
|
|
148
|
+
return storageAdministrationWrite(async () => {
|
|
149
|
+
await input.storage.delete(id);
|
|
150
|
+
if (await inspect(id))
|
|
151
|
+
throw filesystemMetadataInvalid();
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// ../runtime/dist/adapters/storage/filesystem-implementation.js
|
|
158
|
+
import { createHash as createHash4, randomBytes as randomBytes2, randomUUID as randomUUID5 } from "node:crypto";
|
|
159
|
+
import { constants as constants5 } from "node:fs";
|
|
160
|
+
import { link as link3, mkdir as mkdir3, open as open5, readFile as readFile2, readdir as readdir2, rm as rm2, writeFile as writeFile3 } from "node:fs/promises";
|
|
161
|
+
import { join as join5 } from "node:path";
|
|
162
|
+
import { pathToFileURL } from "node:url";
|
|
163
|
+
|
|
164
|
+
// ../runtime/dist/adapters/storage/document-owner.js
|
|
165
|
+
var documentOwnerKey = "__gencow_document_owner";
|
|
166
|
+
function assertDocumentStorageBinding(scope, binding) {
|
|
167
|
+
if (scope.binding.appId !== binding.appId || scope.binding.generationId !== binding.generationId)
|
|
168
|
+
throw new DocumentConversionError("DOCUMENT_STORAGE_SCOPE_FORBIDDEN", scope.correlationId);
|
|
169
|
+
}
|
|
170
|
+
function assertDocumentStorageScope(scope, binding) {
|
|
171
|
+
if (scope.signal.aborted)
|
|
172
|
+
throw new DocumentConversionError("DOCUMENT_STORAGE_SCOPE_EXPIRED", scope.correlationId);
|
|
173
|
+
assertDocumentStorageBinding(scope, binding);
|
|
174
|
+
}
|
|
175
|
+
function documentOwnerFromBoundScope(scope, binding) {
|
|
176
|
+
assertDocumentStorageBinding(scope, binding);
|
|
177
|
+
const userId = scope.identity?.id;
|
|
178
|
+
if (userId === void 0)
|
|
179
|
+
return void 0;
|
|
180
|
+
if (typeof userId !== "string" || !userId.trim() || userId.length > 1024)
|
|
181
|
+
throw new DocumentConversionError("DOCUMENT_STORAGE_SCOPE_FORBIDDEN", scope.correlationId);
|
|
182
|
+
return Object.freeze({ version: 1, appId: binding.appId, userId });
|
|
183
|
+
}
|
|
184
|
+
function documentUploadOwner(scope, binding) {
|
|
185
|
+
assertDocumentStorageScope(scope, binding);
|
|
186
|
+
return documentOwnerFromBoundScope(scope, binding);
|
|
187
|
+
}
|
|
188
|
+
function assertDocumentUploadOwner(value, scope, binding) {
|
|
189
|
+
const actual = documentUploadOwner(scope, binding);
|
|
190
|
+
if (!actual || !value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).length !== 3 || !("version" in value) || value.version !== 1 || !("appId" in value) || value.appId !== actual.appId || !("userId" in value) || value.userId !== actual.userId)
|
|
191
|
+
throw new DocumentConversionError("DOCUMENT_STORAGE_SCOPE_FORBIDDEN", scope.correlationId);
|
|
192
|
+
}
|
|
193
|
+
function lendDocumentUploadStorage(storage, scope, binding, assert, maxBytes, publish, assertGrantAdmission, createReadGrant) {
|
|
194
|
+
function guard() {
|
|
195
|
+
assert();
|
|
196
|
+
assertDocumentStorageBinding(scope, binding);
|
|
197
|
+
}
|
|
198
|
+
guard();
|
|
199
|
+
const owner = documentOwnerFromBoundScope(scope, binding);
|
|
200
|
+
const uploads = {
|
|
201
|
+
async store(file, options2) {
|
|
202
|
+
guard();
|
|
203
|
+
assertRuntimeFileSize(file.size, maxBytes);
|
|
204
|
+
const name = typeof options2 === "string" ? options2 : options2?.filename;
|
|
205
|
+
const visibility = typeof options2 === "string" ? "private" : options2?.visibility ?? "private";
|
|
206
|
+
const type = file.type || "application/octet-stream";
|
|
207
|
+
const filename = name || (file instanceof File ? file.name : void 0);
|
|
208
|
+
const bytes = Buffer.from(new Uint8Array(await file.arrayBuffer()));
|
|
209
|
+
guard();
|
|
210
|
+
assertRuntimeFileSize(bytes.length, maxBytes);
|
|
211
|
+
const id = await publish(bytes, filename, type, visibility, owner, guard);
|
|
212
|
+
guard();
|
|
213
|
+
return id;
|
|
214
|
+
},
|
|
215
|
+
async storeBuffer(bytes, filename, type = "application/octet-stream", options2) {
|
|
216
|
+
guard();
|
|
217
|
+
assertRuntimeFileSize(bytes.length, maxBytes);
|
|
218
|
+
const id = await publish(Buffer.from(bytes), filename, type, options2?.visibility ?? "private", owner, guard);
|
|
219
|
+
guard();
|
|
220
|
+
return id;
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
return new Proxy(storage, {
|
|
224
|
+
get(target, key) {
|
|
225
|
+
if (key === "store" || key === "storeBuffer")
|
|
226
|
+
return uploads[key];
|
|
227
|
+
if (key === "createReadGrant")
|
|
228
|
+
return async (storageId, input) => {
|
|
229
|
+
assertGrantAdmission?.();
|
|
230
|
+
guard();
|
|
231
|
+
const result = createReadGrant ? await createReadGrant(storageId, input) : await target.createReadGrant(storageId, input);
|
|
232
|
+
assertGrantAdmission?.();
|
|
233
|
+
guard();
|
|
234
|
+
return result;
|
|
235
|
+
};
|
|
236
|
+
const value = Reflect.get(target, key, target);
|
|
237
|
+
if (typeof value !== "function")
|
|
238
|
+
return value;
|
|
239
|
+
return (...args) => {
|
|
240
|
+
guard();
|
|
241
|
+
const result = Reflect.apply(value, target, args);
|
|
242
|
+
if (result instanceof Promise)
|
|
243
|
+
return result.then((output) => {
|
|
244
|
+
guard();
|
|
245
|
+
return output;
|
|
246
|
+
});
|
|
247
|
+
guard();
|
|
248
|
+
return result;
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// ../runtime/dist/adapters/storage/filesystem-boundary.js
|
|
255
|
+
import { constants, lstatSync, realpathSync } from "node:fs";
|
|
256
|
+
import { open } from "node:fs/promises";
|
|
257
|
+
import { join } from "node:path";
|
|
258
|
+
function containmentFailure(code) {
|
|
259
|
+
const invalidId = code === "RUNTIME_STORAGE_OBJECT_ID_INVALID";
|
|
260
|
+
return new RuntimeDiagnosticError({
|
|
261
|
+
code,
|
|
262
|
+
stage: "request",
|
|
263
|
+
capability: "storage",
|
|
264
|
+
servingStarted: "unchanged",
|
|
265
|
+
// A boundary rejection cannot undo earlier writes in this call or handler;
|
|
266
|
+
// the adapter cannot prove request-wide rollback.
|
|
267
|
+
dataImpact: "unknown",
|
|
268
|
+
retryable: false,
|
|
269
|
+
retryPrecondition: invalidId ? "Supply a valid storage object ID and verify any earlier request effects before retrying." : "Restore the configured storage directory and regular object files before retrying; do not use symbolic or hard links for objects.",
|
|
270
|
+
nextAction: invalidId ? "Use the opaque object ID returned by storage.store or storage.storeBuffer; do not supply a file path." : "Inspect the filesystem storage configuration and prior operation effects; restore its original directory and unlinked regular object files before retrying."
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
function errorCode(error) {
|
|
274
|
+
return error && typeof error === "object" && "code" in error ? error.code : void 0;
|
|
275
|
+
}
|
|
276
|
+
function createFilesystemBoundary(directory) {
|
|
277
|
+
const root = realpathSync(directory);
|
|
278
|
+
const owner = lstatSync(root);
|
|
279
|
+
function assertRoot() {
|
|
280
|
+
try {
|
|
281
|
+
const current = lstatSync(root);
|
|
282
|
+
if (!current.isDirectory() || current.isSymbolicLink() || current.dev !== owner.dev || current.ino !== owner.ino || realpathSync(root) !== root)
|
|
283
|
+
throw containmentFailure("RUNTIME_STORAGE_PATH_UNSAFE");
|
|
284
|
+
} catch {
|
|
285
|
+
throw containmentFailure("RUNTIME_STORAGE_PATH_UNSAFE");
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
function assertFile(path) {
|
|
289
|
+
try {
|
|
290
|
+
const file2 = lstatSync(path);
|
|
291
|
+
if (!file2.isFile() || file2.isSymbolicLink() || file2.nlink !== 1)
|
|
292
|
+
throw containmentFailure("RUNTIME_STORAGE_PATH_UNSAFE");
|
|
293
|
+
} catch (error) {
|
|
294
|
+
if (errorCode(error) !== "ENOENT")
|
|
295
|
+
throw filesystemFailure(error, false);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
function paths(id) {
|
|
299
|
+
if (!isValidStorageObjectId(id))
|
|
300
|
+
throw containmentFailure("RUNTIME_STORAGE_OBJECT_ID_INVALID");
|
|
301
|
+
assertRoot();
|
|
302
|
+
const data = join(root, id);
|
|
303
|
+
const metadata = join(root, `${id}${filesystemMetadataSuffix}`);
|
|
304
|
+
const legacyMetadata = join(root, `${id}${filesystemLegacyMetadataSuffix}`);
|
|
305
|
+
assertFile(data);
|
|
306
|
+
assertFile(metadata);
|
|
307
|
+
assertFile(legacyMetadata);
|
|
308
|
+
return { data, metadata, legacyMetadata };
|
|
309
|
+
}
|
|
310
|
+
async function file(path, flags) {
|
|
311
|
+
assertRoot();
|
|
312
|
+
let handle;
|
|
313
|
+
try {
|
|
314
|
+
handle = await open(path, flags | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
315
|
+
const info = await handle.stat();
|
|
316
|
+
if (!info.isFile() || info.nlink !== 1)
|
|
317
|
+
throw containmentFailure("RUNTIME_STORAGE_PATH_UNSAFE");
|
|
318
|
+
return handle;
|
|
319
|
+
} catch (error) {
|
|
320
|
+
await handle?.close();
|
|
321
|
+
if (errorCode(error) === "ELOOP")
|
|
322
|
+
throw containmentFailure("RUNTIME_STORAGE_PATH_UNSAFE");
|
|
323
|
+
throw error;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
return {
|
|
327
|
+
root,
|
|
328
|
+
identity: Object.freeze({ dev: owner.dev, ino: owner.ino }),
|
|
329
|
+
ownerMarker: join(root, filesystemRootOwnerFilename),
|
|
330
|
+
assertRoot,
|
|
331
|
+
isKnownInternalDirectory(name) {
|
|
332
|
+
if (!filesystemRootInternalDirectories.includes(name))
|
|
333
|
+
return false;
|
|
334
|
+
assertRoot();
|
|
335
|
+
try {
|
|
336
|
+
const info = lstatSync(join(root, name));
|
|
337
|
+
if (!info.isDirectory() || info.isSymbolicLink())
|
|
338
|
+
throw containmentFailure("RUNTIME_STORAGE_PATH_UNSAFE");
|
|
339
|
+
} catch (error) {
|
|
340
|
+
if (filesystemErrorCode(error) !== "ENOENT")
|
|
341
|
+
throw filesystemFailure(error, false);
|
|
342
|
+
}
|
|
343
|
+
return true;
|
|
344
|
+
},
|
|
345
|
+
paths,
|
|
346
|
+
async fileSize(path) {
|
|
347
|
+
let handle;
|
|
348
|
+
try {
|
|
349
|
+
handle = await file(path, constants.O_RDONLY);
|
|
350
|
+
return (await handle.stat()).size;
|
|
351
|
+
} catch (error) {
|
|
352
|
+
if (filesystemErrorCode(error) === "ENOENT")
|
|
353
|
+
return null;
|
|
354
|
+
throw filesystemFailure(error, false);
|
|
355
|
+
} finally {
|
|
356
|
+
await handle?.close();
|
|
357
|
+
}
|
|
358
|
+
},
|
|
359
|
+
async read(path, limit) {
|
|
360
|
+
try {
|
|
361
|
+
const handle = await file(path, constants.O_RDONLY);
|
|
362
|
+
try {
|
|
363
|
+
if (limit === void 0)
|
|
364
|
+
return await handle.readFile();
|
|
365
|
+
const statSize = !Number.isSafeInteger(limit) || limit < 0 ? -1 : (await handle.stat()).size;
|
|
366
|
+
if (statSize < 0 || statSize > limit)
|
|
367
|
+
throw storageAdministrationReadLimit(limit);
|
|
368
|
+
let target = Buffer.allocUnsafe(statSize + 1);
|
|
369
|
+
let total = 0;
|
|
370
|
+
while (total <= limit) {
|
|
371
|
+
if (total === target.length) {
|
|
372
|
+
const wider = Buffer.allocUnsafe(Math.min(limit + 1, target.length * 2 + 65536));
|
|
373
|
+
target.copy(wider, 0, 0, total);
|
|
374
|
+
target = wider;
|
|
375
|
+
}
|
|
376
|
+
const { bytesRead } = await handle.read(target, total, target.length - total, null);
|
|
377
|
+
if (!bytesRead)
|
|
378
|
+
break;
|
|
379
|
+
total += bytesRead;
|
|
380
|
+
if (total > limit)
|
|
381
|
+
throw storageAdministrationReadLimit(limit);
|
|
382
|
+
}
|
|
383
|
+
return target.subarray(0, total);
|
|
384
|
+
} finally {
|
|
385
|
+
await handle.close();
|
|
386
|
+
}
|
|
387
|
+
} catch (error) {
|
|
388
|
+
if (filesystemErrorCode(error) === "ENOENT")
|
|
389
|
+
throw error;
|
|
390
|
+
throw filesystemFailure(error, false);
|
|
391
|
+
}
|
|
392
|
+
},
|
|
393
|
+
/** Bounded document IO on the same no-follow regular-file handle. */
|
|
394
|
+
async readBounded(path, maxBytes) {
|
|
395
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0)
|
|
396
|
+
throw new DocumentConversionError("DOCUMENT_INPUT_INVALID");
|
|
397
|
+
const handle = await file(path, constants.O_RDONLY);
|
|
398
|
+
try {
|
|
399
|
+
const size = (await handle.stat()).size;
|
|
400
|
+
if (size > maxBytes)
|
|
401
|
+
throw new DocumentConversionError("DOCUMENT_SIZE_LIMIT_EXCEEDED");
|
|
402
|
+
const bytes = Buffer.alloc(size + 1);
|
|
403
|
+
let length = 0;
|
|
404
|
+
while (length < bytes.length) {
|
|
405
|
+
const read = await handle.read(bytes, length, bytes.length - length, null);
|
|
406
|
+
if (!read.bytesRead)
|
|
407
|
+
break;
|
|
408
|
+
length += read.bytesRead;
|
|
409
|
+
}
|
|
410
|
+
if (length > maxBytes)
|
|
411
|
+
throw new DocumentConversionError("DOCUMENT_SIZE_LIMIT_EXCEEDED");
|
|
412
|
+
if (length !== size)
|
|
413
|
+
throw new DocumentConversionError("DOCUMENT_INPUT_INVALID");
|
|
414
|
+
return bytes.subarray(0, length);
|
|
415
|
+
} catch (error) {
|
|
416
|
+
if (filesystemErrorCode(error) === "ENOENT")
|
|
417
|
+
throw error;
|
|
418
|
+
throw filesystemFailure(error, false);
|
|
419
|
+
} finally {
|
|
420
|
+
await handle.close();
|
|
421
|
+
}
|
|
422
|
+
},
|
|
423
|
+
async write(path, bytes, create) {
|
|
424
|
+
return filesystemCall(true, async () => {
|
|
425
|
+
const handle = await file(path, constants.O_WRONLY | (create ? constants.O_CREAT | constants.O_EXCL : 0));
|
|
426
|
+
try {
|
|
427
|
+
if (!create)
|
|
428
|
+
await handle.truncate(0);
|
|
429
|
+
await handle.writeFile(bytes);
|
|
430
|
+
} finally {
|
|
431
|
+
await handle.close();
|
|
432
|
+
}
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
};
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
// ../runtime/dist/adapters/storage/filesystem-image-transforms.js
|
|
439
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
440
|
+
import { Writable } from "node:stream";
|
|
441
|
+
import { pipeline as runPipeline } from "node:stream/promises";
|
|
442
|
+
|
|
443
|
+
// ../runtime/dist/adapters/storage/filesystem-image-cache.js
|
|
444
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
445
|
+
import { constants as constants3 } from "node:fs";
|
|
446
|
+
|
|
447
|
+
// ../runtime/dist/adapters/storage/filesystem-image-cache-directory.js
|
|
448
|
+
import { constants as constants2 } from "node:fs";
|
|
449
|
+
import { link, lstat, mkdir, open as open2, opendir, realpath, unlink } from "node:fs/promises";
|
|
450
|
+
import { join as join2 } from "node:path";
|
|
451
|
+
var noFollow = constants2.O_NOFOLLOW;
|
|
452
|
+
var directoryFlag = constants2.O_DIRECTORY;
|
|
453
|
+
var cacheParentName = ".cache";
|
|
454
|
+
var cacheDirectoryName = "runtime-image-transforms-v1";
|
|
455
|
+
var RuntimeFilesystemImageCacheDirectoryError = class extends Error {
|
|
456
|
+
constructor() {
|
|
457
|
+
super("The private image cache directory is unavailable");
|
|
458
|
+
this.name = "RuntimeFilesystemImageCacheDirectoryError";
|
|
459
|
+
}
|
|
460
|
+
};
|
|
461
|
+
function identity(info) {
|
|
462
|
+
return {
|
|
463
|
+
dev: info.dev,
|
|
464
|
+
ino: info.ino,
|
|
465
|
+
size: info.size,
|
|
466
|
+
uid: info.uid,
|
|
467
|
+
mode: info.mode & 511,
|
|
468
|
+
nlink: info.nlink
|
|
469
|
+
};
|
|
470
|
+
}
|
|
471
|
+
function sameIdentity(left, right, includeMutableShape = true) {
|
|
472
|
+
return left.dev === right.dev && left.ino === right.ino && (!includeMutableShape || left.size === right.size && left.uid === right.uid && left.mode === right.mode && left.nlink === right.nlink);
|
|
473
|
+
}
|
|
474
|
+
var directoryPaths = /* @__PURE__ */ new WeakMap();
|
|
475
|
+
function descriptorPath(handle) {
|
|
476
|
+
const path = directoryPaths.get(handle);
|
|
477
|
+
if (!path)
|
|
478
|
+
throw new RuntimeFilesystemImageCacheDirectoryError();
|
|
479
|
+
return path;
|
|
480
|
+
}
|
|
481
|
+
function isDirectory(info, expected) {
|
|
482
|
+
const actual = identity(info);
|
|
483
|
+
return info.isDirectory() && !info.isSymbolicLink() && sameIdentity(actual, expected, false) && actual.uid === expected.uid && actual.mode === expected.mode;
|
|
484
|
+
}
|
|
485
|
+
function isSafeParent(info) {
|
|
486
|
+
return info.isDirectory() && !info.isSymbolicLink() && (typeof process.getuid !== "function" || info.uid === process.getuid()) && (info.mode & 18) === 0;
|
|
487
|
+
}
|
|
488
|
+
function isSafeLeaf(info) {
|
|
489
|
+
return info.isDirectory() && !info.isSymbolicLink() && (info.mode & 511) === 448 && (typeof process.getuid !== "function" || info.uid === process.getuid());
|
|
490
|
+
}
|
|
491
|
+
async function openChildDirectory(parent, name, expectedPath, createMode, validate) {
|
|
492
|
+
const anchoredPath = join2(descriptorPath(parent), name);
|
|
493
|
+
try {
|
|
494
|
+
await mkdir(anchoredPath, { mode: createMode });
|
|
495
|
+
} catch (error) {
|
|
496
|
+
if (!error || typeof error !== "object" || !("code" in error) || error.code !== "EEXIST")
|
|
497
|
+
throw error;
|
|
498
|
+
}
|
|
499
|
+
const before = await lstat(anchoredPath);
|
|
500
|
+
if (!validate(before))
|
|
501
|
+
throw new RuntimeFilesystemImageCacheDirectoryError();
|
|
502
|
+
const handle = await open2(anchoredPath, constants2.O_RDONLY | (directoryFlag ?? 0) | (noFollow ?? 0));
|
|
503
|
+
directoryPaths.set(handle, expectedPath);
|
|
504
|
+
try {
|
|
505
|
+
const opened = await handle.stat();
|
|
506
|
+
const attached = await lstat(expectedPath);
|
|
507
|
+
if (!validate(opened) || !sameIdentity(identity(before), identity(opened)) || !sameIdentity(identity(opened), identity(attached)) || await realpath(expectedPath) !== expectedPath)
|
|
508
|
+
throw new RuntimeFilesystemImageCacheDirectoryError();
|
|
509
|
+
return handle;
|
|
510
|
+
} catch (error) {
|
|
511
|
+
await handle.close().catch(() => {
|
|
512
|
+
});
|
|
513
|
+
throw error;
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
async function openRuntimeFilesystemImageCacheDirectory(input) {
|
|
517
|
+
if (process.platform !== "linux" || !noFollow || !directoryFlag)
|
|
518
|
+
return null;
|
|
519
|
+
const parentPath = join2(input.root, cacheParentName);
|
|
520
|
+
const directoryPath = join2(parentPath, cacheDirectoryName);
|
|
521
|
+
let rootHandle;
|
|
522
|
+
let parentHandle;
|
|
523
|
+
let leafHandle;
|
|
524
|
+
try {
|
|
525
|
+
input.assertRoot?.();
|
|
526
|
+
const rootInfo = await lstat(input.root);
|
|
527
|
+
if (!rootInfo.isDirectory() || rootInfo.isSymbolicLink() || await realpath(input.root) !== input.root || input.expectedRoot && (rootInfo.dev !== input.expectedRoot.dev || rootInfo.ino !== input.expectedRoot.ino))
|
|
528
|
+
return null;
|
|
529
|
+
rootHandle = await open2(input.root, constants2.O_RDONLY | directoryFlag | noFollow);
|
|
530
|
+
directoryPaths.set(rootHandle, input.root);
|
|
531
|
+
const openedRoot = await rootHandle.stat();
|
|
532
|
+
if (!openedRoot.isDirectory() || openedRoot.dev !== rootInfo.dev || openedRoot.ino !== rootInfo.ino || typeof process.getuid === "function" && openedRoot.uid !== process.getuid() || (openedRoot.mode & 18) !== 0)
|
|
533
|
+
throw new RuntimeFilesystemImageCacheDirectoryError();
|
|
534
|
+
parentHandle = await openChildDirectory(rootHandle, cacheParentName, parentPath, 493, isSafeParent);
|
|
535
|
+
const parentInfo = await parentHandle.stat();
|
|
536
|
+
const parentIdentity = identity(parentInfo);
|
|
537
|
+
leafHandle = await openChildDirectory(parentHandle, cacheDirectoryName, directoryPath, 448, isSafeLeaf);
|
|
538
|
+
const leafIdentity = identity(await leafHandle.stat());
|
|
539
|
+
const rootIdentity = identity(openedRoot);
|
|
540
|
+
const assertAttached = async () => {
|
|
541
|
+
try {
|
|
542
|
+
input.assertRoot?.();
|
|
543
|
+
const [rootPathInfo, parentPathInfo, leafPathInfo, rootFdInfo, parentFdInfo, leafFdInfo] = await Promise.all([
|
|
544
|
+
lstat(input.root),
|
|
545
|
+
lstat(parentPath),
|
|
546
|
+
lstat(directoryPath),
|
|
547
|
+
rootHandle.stat(),
|
|
548
|
+
parentHandle.stat(),
|
|
549
|
+
leafHandle.stat()
|
|
550
|
+
]);
|
|
551
|
+
if (!isDirectory(rootPathInfo, rootIdentity) || !isDirectory(rootFdInfo, rootIdentity) || !isSafeParent(parentPathInfo) || !isSafeParent(parentFdInfo) || !sameIdentity(identity(parentPathInfo), parentIdentity, false) || !sameIdentity(identity(parentFdInfo), parentIdentity, false) || !isSafeLeaf(leafPathInfo) || !isSafeLeaf(leafFdInfo) || !sameIdentity(identity(leafPathInfo), leafIdentity, false) || !sameIdentity(identity(leafFdInfo), leafIdentity, false) || await realpath(input.root) !== input.root || await realpath(parentPath) !== parentPath || await realpath(directoryPath) !== directoryPath)
|
|
552
|
+
throw new RuntimeFilesystemImageCacheDirectoryError();
|
|
553
|
+
} catch {
|
|
554
|
+
throw new RuntimeFilesystemImageCacheDirectoryError();
|
|
555
|
+
}
|
|
556
|
+
};
|
|
557
|
+
const childPath = (name) => {
|
|
558
|
+
if (!/^(?:[0-9a-f]{64}\.bin|\.tmp-[0-9a-f-]{36})$/u.test(name))
|
|
559
|
+
throw new RuntimeFilesystemImageCacheDirectoryError();
|
|
560
|
+
return join2(descriptorPath(leafHandle), name);
|
|
561
|
+
};
|
|
562
|
+
const authority = {
|
|
563
|
+
parentPath,
|
|
564
|
+
directoryPath,
|
|
565
|
+
assertAttached,
|
|
566
|
+
lstat(name) {
|
|
567
|
+
return lstat(childPath(name));
|
|
568
|
+
},
|
|
569
|
+
open(name, flags, mode) {
|
|
570
|
+
return open2(childPath(name), flags | noFollow, mode);
|
|
571
|
+
},
|
|
572
|
+
async readdir(maximumNames) {
|
|
573
|
+
const handle = await opendir(descriptorPath(leafHandle));
|
|
574
|
+
const names = [];
|
|
575
|
+
try {
|
|
576
|
+
while (true) {
|
|
577
|
+
const entry = await handle.read();
|
|
578
|
+
if (!entry)
|
|
579
|
+
return names;
|
|
580
|
+
if (names.length >= maximumNames)
|
|
581
|
+
throw new RuntimeFilesystemImageCacheDirectoryError();
|
|
582
|
+
names.push(entry.name);
|
|
583
|
+
}
|
|
584
|
+
} finally {
|
|
585
|
+
await handle.close();
|
|
586
|
+
}
|
|
587
|
+
},
|
|
588
|
+
async link(sourceName, destinationName) {
|
|
589
|
+
await link(childPath(sourceName), childPath(destinationName));
|
|
590
|
+
},
|
|
591
|
+
async unlink(name) {
|
|
592
|
+
await unlink(childPath(name));
|
|
593
|
+
},
|
|
594
|
+
async sync() {
|
|
595
|
+
await leafHandle.sync();
|
|
596
|
+
},
|
|
597
|
+
async dispose() {
|
|
598
|
+
const handles = [leafHandle, parentHandle, rootHandle];
|
|
599
|
+
leafHandle = void 0;
|
|
600
|
+
parentHandle = void 0;
|
|
601
|
+
rootHandle = void 0;
|
|
602
|
+
await Promise.all(handles.map((handle) => handle?.close().catch(() => void 0)));
|
|
603
|
+
}
|
|
604
|
+
};
|
|
605
|
+
await authority.assertAttached();
|
|
606
|
+
return authority;
|
|
607
|
+
} catch {
|
|
608
|
+
await Promise.all([leafHandle, parentHandle, rootHandle].map((handle) => handle?.close().catch(() => void 0)));
|
|
609
|
+
return null;
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
function runtimeImageCacheFileIdentity(info) {
|
|
613
|
+
return identity(info);
|
|
614
|
+
}
|
|
615
|
+
function runtimeImageCacheFileIdentityMatches(left, right, includeMutableShape = true) {
|
|
616
|
+
return sameIdentity(left, right, includeMutableShape);
|
|
617
|
+
}
|
|
618
|
+
function runtimeImageCacheFileIsSafe(info) {
|
|
619
|
+
return info.isFile() && !info.isSymbolicLink() && info.nlink === 1 && (info.mode & 511) === 384 && (typeof process.getuid !== "function" || info.uid === process.getuid());
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
// ../runtime/dist/adapters/storage/filesystem-image-cache.js
|
|
623
|
+
var magic = Buffer.from("GCIMG001", "ascii");
|
|
624
|
+
var maximumManifestBytes = 2048;
|
|
625
|
+
var maximumEnvelopeBytes = magic.byteLength + 4 + maximumManifestBytes;
|
|
626
|
+
var noFollow2 = constants3.O_NOFOLLOW;
|
|
627
|
+
var nonBlock = constants3.O_NONBLOCK;
|
|
628
|
+
var sameShape = runtimeImageCacheFileIdentityMatches;
|
|
629
|
+
var safeFile = runtimeImageCacheFileIsSafe;
|
|
630
|
+
function isMissing(error) {
|
|
631
|
+
return Boolean(error && typeof error === "object" && "code" in error && error.code === "ENOENT");
|
|
632
|
+
}
|
|
633
|
+
function safeOwnedFile(info, allowTwoLinks) {
|
|
634
|
+
return info.isFile() && !info.isSymbolicLink() && (info.nlink === 1 || allowTwoLinks && info.nlink === 2) && (info.mode & 511) === 384 && (typeof process.getuid !== "function" || info.uid === process.getuid());
|
|
635
|
+
}
|
|
636
|
+
function decodeEnvelope(key, envelope, maximumOutputBytes) {
|
|
637
|
+
if (envelope.byteLength < magic.byteLength + 4 || !envelope.subarray(0, magic.byteLength).equals(magic))
|
|
638
|
+
throw new Error("Invalid image cache entry");
|
|
639
|
+
const manifestBytes = envelope.readUInt32BE(magic.byteLength);
|
|
640
|
+
const payloadOffset = magic.byteLength + 4 + manifestBytes;
|
|
641
|
+
if (manifestBytes < 2 || manifestBytes > maximumManifestBytes || payloadOffset > envelope.byteLength)
|
|
642
|
+
throw new Error("Invalid image cache entry");
|
|
643
|
+
const manifest = JSON.parse(envelope.subarray(magic.byteLength + 4, payloadOffset).toString("utf8"));
|
|
644
|
+
const bytes = envelope.subarray(payloadOffset);
|
|
645
|
+
if (manifest.key !== key || manifest.size !== bytes.byteLength || bytes.byteLength > maximumOutputBytes || typeof manifest.digest !== "string" || manifest.digest !== createHash("sha256").update(bytes).digest("hex") || !["image/webp", "image/avif", "image/jpeg", "image/png"].includes(String(manifest.type)) || !Number.isSafeInteger(manifest.width) || Number(manifest.width) < 1 || Number(manifest.width) > 4096 || !Number.isSafeInteger(manifest.height) || Number(manifest.height) < 1 || Number(manifest.height) > 4096)
|
|
646
|
+
throw new Error("Invalid image cache entry");
|
|
647
|
+
return {
|
|
648
|
+
bytes: Buffer.from(bytes),
|
|
649
|
+
type: manifest.type,
|
|
650
|
+
width: manifest.width,
|
|
651
|
+
height: manifest.height
|
|
652
|
+
};
|
|
653
|
+
}
|
|
654
|
+
function encodeEnvelope(key, entry) {
|
|
655
|
+
const manifest = Buffer.from(JSON.stringify({
|
|
656
|
+
key,
|
|
657
|
+
type: entry.type,
|
|
658
|
+
width: entry.width,
|
|
659
|
+
height: entry.height,
|
|
660
|
+
size: entry.bytes.byteLength,
|
|
661
|
+
digest: createHash("sha256").update(entry.bytes).digest("hex")
|
|
662
|
+
}), "utf8");
|
|
663
|
+
if (manifest.byteLength > maximumManifestBytes)
|
|
664
|
+
throw new Error("Invalid image cache manifest");
|
|
665
|
+
const header = Buffer.alloc(magic.byteLength + 4 + manifest.byteLength);
|
|
666
|
+
magic.copy(header);
|
|
667
|
+
header.writeUInt32BE(manifest.byteLength, magic.byteLength);
|
|
668
|
+
manifest.copy(header, magic.byteLength + 4);
|
|
669
|
+
return Buffer.concat([header, entry.bytes]);
|
|
670
|
+
}
|
|
671
|
+
function createFilesystemImageCache(input) {
|
|
672
|
+
const entries = /* @__PURE__ */ new Map();
|
|
673
|
+
let bytes = 0;
|
|
674
|
+
let reservedBytes = 0;
|
|
675
|
+
let reservedEntries = 0;
|
|
676
|
+
let available = false;
|
|
677
|
+
let disposed = false;
|
|
678
|
+
let initialized = false;
|
|
679
|
+
let accessClock = 0;
|
|
680
|
+
let directory;
|
|
681
|
+
let operation = Promise.resolve();
|
|
682
|
+
function nextAccessTime(base = Date.now()) {
|
|
683
|
+
accessClock = Math.max(accessClock + 1, Math.floor(base * 1e3));
|
|
684
|
+
return accessClock;
|
|
685
|
+
}
|
|
686
|
+
async function locked(action) {
|
|
687
|
+
const result = operation.then(action, action);
|
|
688
|
+
operation = result.then(() => void 0, () => void 0);
|
|
689
|
+
return result;
|
|
690
|
+
}
|
|
691
|
+
function disable() {
|
|
692
|
+
available = false;
|
|
693
|
+
entries.clear();
|
|
694
|
+
bytes = 0;
|
|
695
|
+
reservedBytes = 0;
|
|
696
|
+
reservedEntries = 0;
|
|
697
|
+
}
|
|
698
|
+
async function ensureAttached() {
|
|
699
|
+
if (!directory)
|
|
700
|
+
throw new RuntimeFilesystemImageCacheDirectoryError();
|
|
701
|
+
await directory.assertAttached();
|
|
702
|
+
}
|
|
703
|
+
async function unlinkOwned(name, expected, allowTwoLinks = false) {
|
|
704
|
+
if (!directory)
|
|
705
|
+
throw new RuntimeFilesystemImageCacheDirectoryError();
|
|
706
|
+
await ensureAttached();
|
|
707
|
+
const info = await directory.lstat(name).catch((error) => {
|
|
708
|
+
if (isMissing(error))
|
|
709
|
+
return null;
|
|
710
|
+
throw error;
|
|
711
|
+
});
|
|
712
|
+
if (!info)
|
|
713
|
+
return;
|
|
714
|
+
const current = runtimeImageCacheFileIdentity(info);
|
|
715
|
+
if (!safeOwnedFile(info, allowTwoLinks) || !sameShape(current, expected, false) || (allowTwoLinks ? current.nlink < 1 || current.nlink > 2 : current.nlink !== 1))
|
|
716
|
+
throw new RuntimeFilesystemImageCacheDirectoryError();
|
|
717
|
+
await ensureAttached();
|
|
718
|
+
const beforeUnlink = await directory.lstat(name);
|
|
719
|
+
const beforeIdentity = runtimeImageCacheFileIdentity(beforeUnlink);
|
|
720
|
+
if (!sameShape(current, beforeIdentity) || !safeOwnedFile(beforeUnlink, allowTwoLinks))
|
|
721
|
+
throw new RuntimeFilesystemImageCacheDirectoryError();
|
|
722
|
+
await directory.unlink(name);
|
|
723
|
+
}
|
|
724
|
+
async function assertNameIdentity(name, expected) {
|
|
725
|
+
if (!directory)
|
|
726
|
+
throw new RuntimeFilesystemImageCacheDirectoryError();
|
|
727
|
+
await ensureAttached();
|
|
728
|
+
const current = await directory.lstat(name);
|
|
729
|
+
if (!safeFile(current) || !sameShape(runtimeImageCacheFileIdentity(current), expected))
|
|
730
|
+
throw new RuntimeFilesystemImageCacheDirectoryError();
|
|
731
|
+
}
|
|
732
|
+
async function safeRemove(key) {
|
|
733
|
+
const name = `${key}.bin`;
|
|
734
|
+
await ensureAttached();
|
|
735
|
+
const info = await directory.lstat(name).catch((error) => {
|
|
736
|
+
if (isMissing(error))
|
|
737
|
+
return null;
|
|
738
|
+
throw error;
|
|
739
|
+
});
|
|
740
|
+
const prior = entries.get(key);
|
|
741
|
+
if (info) {
|
|
742
|
+
const current = runtimeImageCacheFileIdentity(info);
|
|
743
|
+
if (!safeFile(info) || prior && (current.dev !== prior.dev || current.ino !== prior.ino))
|
|
744
|
+
throw new RuntimeFilesystemImageCacheDirectoryError();
|
|
745
|
+
await unlinkOwned(name, current);
|
|
746
|
+
}
|
|
747
|
+
if (prior)
|
|
748
|
+
bytes = Math.max(0, bytes - prior.size);
|
|
749
|
+
entries.delete(key);
|
|
750
|
+
}
|
|
751
|
+
async function evictOldest() {
|
|
752
|
+
const oldest = [...entries.entries()].sort((a, b) => a[1].lastAccess - b[1].lastAccess)[0];
|
|
753
|
+
if (!oldest)
|
|
754
|
+
return false;
|
|
755
|
+
await safeRemove(oldest[0]);
|
|
756
|
+
return true;
|
|
757
|
+
}
|
|
758
|
+
async function initialize() {
|
|
759
|
+
if (initialized || disposed || noFollow2 === void 0 || !Number.isSafeInteger(input.maxBytes) || input.maxBytes < 1 || input.maxBytes > 128 * 1024 * 1024 || !Number.isSafeInteger(input.maxEntries) || input.maxEntries < 1 || input.maxEntries > 1e3 || !Number.isSafeInteger(input.maxOutputBytes) || input.maxOutputBytes < 1 || input.maxOutputBytes > 16 * 1024 * 1024)
|
|
760
|
+
return false;
|
|
761
|
+
initialized = true;
|
|
762
|
+
const failInitialization = async () => {
|
|
763
|
+
disable();
|
|
764
|
+
await directory?.dispose().catch(() => {
|
|
765
|
+
});
|
|
766
|
+
directory = void 0;
|
|
767
|
+
return false;
|
|
768
|
+
};
|
|
769
|
+
try {
|
|
770
|
+
const opened = await openRuntimeFilesystemImageCacheDirectory({
|
|
771
|
+
root: input.root,
|
|
772
|
+
expectedRoot: input.expectedRoot,
|
|
773
|
+
assertRoot: input.assertRoot
|
|
774
|
+
});
|
|
775
|
+
if (!opened)
|
|
776
|
+
return failInitialization();
|
|
777
|
+
directory = opened;
|
|
778
|
+
await ensureAttached();
|
|
779
|
+
const names = await directory.readdir(input.maxEntries + 8);
|
|
780
|
+
for (const name of names) {
|
|
781
|
+
await ensureAttached();
|
|
782
|
+
if (/^\.tmp-[0-9a-f-]{36}$/u.test(name)) {
|
|
783
|
+
const info2 = await directory.lstat(name);
|
|
784
|
+
if (!safeFile(info2) || info2.size > input.maxOutputBytes + maximumEnvelopeBytes)
|
|
785
|
+
return failInitialization();
|
|
786
|
+
await unlinkOwned(name, runtimeImageCacheFileIdentity(info2));
|
|
787
|
+
continue;
|
|
788
|
+
}
|
|
789
|
+
const match = /^([0-9a-f]{64})\.bin$/u.exec(name);
|
|
790
|
+
if (!match)
|
|
791
|
+
return failInitialization();
|
|
792
|
+
const info = await directory.lstat(name);
|
|
793
|
+
if (!safeFile(info) || info.size < magic.byteLength + 4 || info.size > input.maxOutputBytes + maximumEnvelopeBytes)
|
|
794
|
+
return failInitialization();
|
|
795
|
+
const fileIdentity = runtimeImageCacheFileIdentity(info);
|
|
796
|
+
entries.set(match[1], {
|
|
797
|
+
size: info.size,
|
|
798
|
+
dev: fileIdentity.dev,
|
|
799
|
+
ino: fileIdentity.ino,
|
|
800
|
+
lastAccess: nextAccessTime(info.mtimeMs)
|
|
801
|
+
});
|
|
802
|
+
bytes += info.size;
|
|
803
|
+
if (bytes > input.maxBytes + input.maxOutputBytes + maximumEnvelopeBytes)
|
|
804
|
+
return failInitialization();
|
|
805
|
+
}
|
|
806
|
+
while (bytes > input.maxBytes || entries.size > input.maxEntries) {
|
|
807
|
+
if (!await evictOldest())
|
|
808
|
+
return failInitialization();
|
|
809
|
+
}
|
|
810
|
+
await ensureAttached();
|
|
811
|
+
available = true;
|
|
812
|
+
return true;
|
|
813
|
+
} catch {
|
|
814
|
+
disable();
|
|
815
|
+
await directory?.dispose().catch(() => {
|
|
816
|
+
});
|
|
817
|
+
directory = void 0;
|
|
818
|
+
return false;
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
async function get(key) {
|
|
822
|
+
if (!available || disposed || !/^[0-9a-f]{64}$/u.test(key))
|
|
823
|
+
return null;
|
|
824
|
+
return locked(async () => {
|
|
825
|
+
if (!available || disposed || !directory)
|
|
826
|
+
return null;
|
|
827
|
+
const indexed = entries.get(key);
|
|
828
|
+
if (!indexed)
|
|
829
|
+
return null;
|
|
830
|
+
try {
|
|
831
|
+
await ensureAttached();
|
|
832
|
+
const name = `${key}.bin`;
|
|
833
|
+
const before = await directory.lstat(name);
|
|
834
|
+
const beforeShape = runtimeImageCacheFileIdentity(before);
|
|
835
|
+
if (!safeFile(before) || before.size > input.maxOutputBytes + maximumEnvelopeBytes || before.dev !== indexed.dev || before.ino !== indexed.ino || before.size !== indexed.size)
|
|
836
|
+
throw new Error("Unsafe image cache entry");
|
|
837
|
+
const handle = await directory.open(name, constants3.O_RDONLY | (nonBlock ?? 0));
|
|
838
|
+
let envelope;
|
|
839
|
+
try {
|
|
840
|
+
const opened = await handle.stat();
|
|
841
|
+
const openedShape = runtimeImageCacheFileIdentity(opened);
|
|
842
|
+
if (!opened.isFile() || !sameShape(beforeShape, openedShape))
|
|
843
|
+
throw new Error("Unsafe image cache entry");
|
|
844
|
+
const result2 = Buffer.alloc(opened.size + 1);
|
|
845
|
+
let total = 0;
|
|
846
|
+
while (total < result2.byteLength) {
|
|
847
|
+
const { bytesRead } = await handle.read(result2, total, result2.byteLength - total, null);
|
|
848
|
+
if (bytesRead === 0)
|
|
849
|
+
break;
|
|
850
|
+
total += bytesRead;
|
|
851
|
+
if (total > input.maxOutputBytes + maximumEnvelopeBytes)
|
|
852
|
+
throw new Error("Image cache entry exceeded its bound");
|
|
853
|
+
}
|
|
854
|
+
const [afterHandle, afterPath] = await Promise.all([handle.stat(), directory.lstat(name)]);
|
|
855
|
+
if (total !== opened.size || !sameShape(openedShape, runtimeImageCacheFileIdentity(afterHandle)) || !sameShape(openedShape, runtimeImageCacheFileIdentity(afterPath)))
|
|
856
|
+
throw new Error("Image cache entry changed during read");
|
|
857
|
+
envelope = result2.subarray(0, total);
|
|
858
|
+
} finally {
|
|
859
|
+
await handle.close();
|
|
860
|
+
}
|
|
861
|
+
const result = decodeEnvelope(key, envelope, input.maxOutputBytes);
|
|
862
|
+
await ensureAttached();
|
|
863
|
+
indexed.lastAccess = nextAccessTime();
|
|
864
|
+
return result;
|
|
865
|
+
} catch (error) {
|
|
866
|
+
if (error instanceof RuntimeFilesystemImageCacheDirectoryError) {
|
|
867
|
+
disable();
|
|
868
|
+
return null;
|
|
869
|
+
}
|
|
870
|
+
try {
|
|
871
|
+
await safeRemove(key);
|
|
872
|
+
} catch {
|
|
873
|
+
disable();
|
|
874
|
+
}
|
|
875
|
+
return null;
|
|
876
|
+
}
|
|
877
|
+
});
|
|
878
|
+
}
|
|
879
|
+
async function reserve() {
|
|
880
|
+
if (!available || disposed)
|
|
881
|
+
return null;
|
|
882
|
+
return locked(async () => {
|
|
883
|
+
if (!available || disposed || !directory)
|
|
884
|
+
return null;
|
|
885
|
+
try {
|
|
886
|
+
await ensureAttached();
|
|
887
|
+
} catch {
|
|
888
|
+
disable();
|
|
889
|
+
return null;
|
|
890
|
+
}
|
|
891
|
+
const maximumReservation = input.maxOutputBytes + maximumEnvelopeBytes;
|
|
892
|
+
try {
|
|
893
|
+
while (bytes + reservedBytes + maximumReservation > input.maxBytes || entries.size + reservedEntries >= input.maxEntries) {
|
|
894
|
+
if (!await evictOldest())
|
|
895
|
+
return null;
|
|
896
|
+
}
|
|
897
|
+
} catch {
|
|
898
|
+
disable();
|
|
899
|
+
return null;
|
|
900
|
+
}
|
|
901
|
+
reservedBytes += maximumReservation;
|
|
902
|
+
reservedEntries += 1;
|
|
903
|
+
let state = "reserved";
|
|
904
|
+
const releaseLocked = () => {
|
|
905
|
+
if (state !== "reserved")
|
|
906
|
+
return;
|
|
907
|
+
state = "released";
|
|
908
|
+
reservedBytes = Math.max(0, reservedBytes - maximumReservation);
|
|
909
|
+
reservedEntries = Math.max(0, reservedEntries - 1);
|
|
910
|
+
};
|
|
911
|
+
return {
|
|
912
|
+
async release() {
|
|
913
|
+
await locked(async () => releaseLocked());
|
|
914
|
+
},
|
|
915
|
+
async publish(key, entry, validateBeforePublish) {
|
|
916
|
+
return locked(async () => {
|
|
917
|
+
if (state !== "reserved" || disposed || !available || !directory || !/^[0-9a-f]{64}$/u.test(key)) {
|
|
918
|
+
releaseLocked();
|
|
919
|
+
return false;
|
|
920
|
+
}
|
|
921
|
+
if (entry.bytes.byteLength > input.maxOutputBytes || entry.width < 1 || entry.height < 1 || entry.width > 4096 || entry.height > 4096) {
|
|
922
|
+
releaseLocked();
|
|
923
|
+
return false;
|
|
924
|
+
}
|
|
925
|
+
const envelope = encodeEnvelope(key, entry);
|
|
926
|
+
const tempName = `.tmp-${randomUUID()}`;
|
|
927
|
+
let handle;
|
|
928
|
+
let temporaryIdentity;
|
|
929
|
+
let publishedIdentity;
|
|
930
|
+
try {
|
|
931
|
+
await ensureAttached();
|
|
932
|
+
handle = await directory.open(tempName, constants3.O_WRONLY | constants3.O_CREAT | constants3.O_EXCL | (noFollow2 ?? 0), 384);
|
|
933
|
+
await input.faults?.afterOpen?.();
|
|
934
|
+
const created = await handle.stat();
|
|
935
|
+
temporaryIdentity = runtimeImageCacheFileIdentity(created);
|
|
936
|
+
if (!safeFile(created) || created.size !== 0)
|
|
937
|
+
throw new Error("Unsafe image cache temporary");
|
|
938
|
+
await input.faults?.beforeWrite?.();
|
|
939
|
+
await handle.writeFile(envelope);
|
|
940
|
+
await input.faults?.beforeSync?.();
|
|
941
|
+
await handle.sync();
|
|
942
|
+
await input.faults?.beforePostWriteStat?.();
|
|
943
|
+
const tempStats = await handle.stat();
|
|
944
|
+
const writtenIdentity = runtimeImageCacheFileIdentity(tempStats);
|
|
945
|
+
if (!sameShape(writtenIdentity, temporaryIdentity, false) || !safeFile(tempStats) || tempStats.size !== envelope.byteLength)
|
|
946
|
+
throw new Error("Unsafe image cache temporary");
|
|
947
|
+
temporaryIdentity = writtenIdentity;
|
|
948
|
+
await handle.close();
|
|
949
|
+
handle = void 0;
|
|
950
|
+
await ensureAttached();
|
|
951
|
+
await assertNameIdentity(tempName, temporaryIdentity);
|
|
952
|
+
if (!await validateBeforePublish()) {
|
|
953
|
+
await ensureAttached();
|
|
954
|
+
await unlinkOwned(tempName, temporaryIdentity);
|
|
955
|
+
releaseLocked();
|
|
956
|
+
return false;
|
|
957
|
+
}
|
|
958
|
+
await ensureAttached();
|
|
959
|
+
await assertNameIdentity(tempName, temporaryIdentity);
|
|
960
|
+
await directory.link(tempName, `${key}.bin`);
|
|
961
|
+
publishedIdentity = temporaryIdentity;
|
|
962
|
+
await input.faults?.afterLink?.();
|
|
963
|
+
const linked = await directory.lstat(`${key}.bin`);
|
|
964
|
+
const linkedIdentity = runtimeImageCacheFileIdentity(linked);
|
|
965
|
+
if (!linked.isFile() || linked.isSymbolicLink() || linked.nlink !== 2 || linked.size !== envelope.byteLength || !sameShape(linkedIdentity, temporaryIdentity, false))
|
|
966
|
+
throw new Error("Unsafe image cache entry");
|
|
967
|
+
await unlinkOwned(tempName, temporaryIdentity, true);
|
|
968
|
+
await directory.sync();
|
|
969
|
+
await ensureAttached();
|
|
970
|
+
const info = await directory.lstat(`${key}.bin`);
|
|
971
|
+
const finalIdentity = runtimeImageCacheFileIdentity(info);
|
|
972
|
+
if (!safeFile(info) || info.size !== envelope.byteLength || !sameShape(finalIdentity, temporaryIdentity, false))
|
|
973
|
+
throw new Error("Unsafe image cache entry");
|
|
974
|
+
entries.set(key, {
|
|
975
|
+
size: info.size,
|
|
976
|
+
dev: finalIdentity.dev,
|
|
977
|
+
ino: finalIdentity.ino,
|
|
978
|
+
lastAccess: nextAccessTime()
|
|
979
|
+
});
|
|
980
|
+
bytes += info.size;
|
|
981
|
+
reservedBytes = Math.max(0, reservedBytes - maximumReservation);
|
|
982
|
+
reservedEntries = Math.max(0, reservedEntries - 1);
|
|
983
|
+
state = "committed";
|
|
984
|
+
return true;
|
|
985
|
+
} catch (error) {
|
|
986
|
+
await handle?.close().catch(() => {
|
|
987
|
+
});
|
|
988
|
+
let cleanupProven = true;
|
|
989
|
+
if (handle && !temporaryIdentity)
|
|
990
|
+
cleanupProven = false;
|
|
991
|
+
if (temporaryIdentity) {
|
|
992
|
+
if (publishedIdentity)
|
|
993
|
+
await unlinkOwned(`${key}.bin`, publishedIdentity, true).catch(() => {
|
|
994
|
+
cleanupProven = false;
|
|
995
|
+
});
|
|
996
|
+
await unlinkOwned(tempName, temporaryIdentity, true).catch(() => {
|
|
997
|
+
cleanupProven = false;
|
|
998
|
+
});
|
|
999
|
+
}
|
|
1000
|
+
if (error instanceof RuntimeFilesystemImageCacheDirectoryError || !cleanupProven || !temporaryIdentity && Boolean(handle))
|
|
1001
|
+
disable();
|
|
1002
|
+
releaseLocked();
|
|
1003
|
+
return false;
|
|
1004
|
+
}
|
|
1005
|
+
});
|
|
1006
|
+
}
|
|
1007
|
+
};
|
|
1008
|
+
});
|
|
1009
|
+
}
|
|
1010
|
+
return {
|
|
1011
|
+
initialize,
|
|
1012
|
+
get,
|
|
1013
|
+
reserve,
|
|
1014
|
+
async dispose() {
|
|
1015
|
+
await locked(async () => {
|
|
1016
|
+
disposed = true;
|
|
1017
|
+
available = false;
|
|
1018
|
+
});
|
|
1019
|
+
await locked(async () => void 0);
|
|
1020
|
+
await directory?.dispose();
|
|
1021
|
+
directory = void 0;
|
|
1022
|
+
},
|
|
1023
|
+
snapshot() {
|
|
1024
|
+
return { available, bytes, entries: entries.size };
|
|
1025
|
+
}
|
|
1026
|
+
};
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
// ../runtime/dist/adapters/storage/filesystem-image-transforms.js
|
|
1030
|
+
function sniffRuntimeImageSource(source) {
|
|
1031
|
+
if (source.length >= 3 && source[0] === 255 && source[1] === 216 && source[2] === 255)
|
|
1032
|
+
return "jpeg";
|
|
1033
|
+
if (source.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])))
|
|
1034
|
+
return "png";
|
|
1035
|
+
if (source.subarray(0, 4).toString("latin1") === "RIFF" && source.subarray(8, 12).toString("latin1") === "WEBP")
|
|
1036
|
+
return "webp";
|
|
1037
|
+
return null;
|
|
1038
|
+
}
|
|
1039
|
+
async function loadSharpEncoder() {
|
|
1040
|
+
try {
|
|
1041
|
+
const sharpModule = await import("sharp");
|
|
1042
|
+
const sharp = sharpModule.default;
|
|
1043
|
+
const version = `sharp-${sharp.versions.sharp}-vips-${sharp.versions.vips}`;
|
|
1044
|
+
return {
|
|
1045
|
+
version,
|
|
1046
|
+
async encode(source, transform, policy, sourceType) {
|
|
1047
|
+
if (!sniffRuntimeImageSource(source))
|
|
1048
|
+
throw new Error("Image bytes do not match a supported source signature");
|
|
1049
|
+
const input = sharp(source, { limitInputPixels: policy.maxPixels });
|
|
1050
|
+
const metadata = await input.metadata();
|
|
1051
|
+
const width = metadata.width;
|
|
1052
|
+
const height = metadata.height;
|
|
1053
|
+
if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 1 || height < 1 || width > policy.maxDimension || height > policy.maxDimension || width * height > policy.maxPixels)
|
|
1054
|
+
throw new Error("Image input exceeds the selected pixel or dimension bound");
|
|
1055
|
+
const normalizedSourceType = sourceType?.split(";", 1)[0]?.trim().toLowerCase();
|
|
1056
|
+
const expectedDecodedFormat = normalizedSourceType === "image/png" ? "png" : normalizedSourceType === "image/webp" ? "webp" : normalizedSourceType === "image/jpeg" || normalizedSourceType === "image/jpg" ? "jpeg" : void 0;
|
|
1057
|
+
if (!expectedDecodedFormat || metadata.format !== expectedDecodedFormat || !["jpeg", "png", "webp"].includes(metadata.format ?? ""))
|
|
1058
|
+
throw new Error("Image bytes do not match a supported declared source format");
|
|
1059
|
+
let imagePipeline = input;
|
|
1060
|
+
if (transform.width !== void 0 || transform.height !== void 0) {
|
|
1061
|
+
const derivedWidth = transform.width ?? Math.min(policy.maxDimension, Math.max(1, Math.round(width * transform.height / height)));
|
|
1062
|
+
const derivedHeight = transform.height ?? Math.min(policy.maxDimension, Math.max(1, Math.round(height * transform.width / width)));
|
|
1063
|
+
imagePipeline = imagePipeline.resize({
|
|
1064
|
+
width: Math.min(policy.maxDimension, derivedWidth),
|
|
1065
|
+
height: Math.min(policy.maxDimension, derivedHeight),
|
|
1066
|
+
fit: transform.fit,
|
|
1067
|
+
withoutEnlargement: true
|
|
1068
|
+
});
|
|
1069
|
+
}
|
|
1070
|
+
switch (transform.format) {
|
|
1071
|
+
case "webp":
|
|
1072
|
+
imagePipeline = imagePipeline.webp({ quality: transform.quality, alphaQuality: 100 });
|
|
1073
|
+
break;
|
|
1074
|
+
case "avif":
|
|
1075
|
+
imagePipeline = imagePipeline.avif({ quality: transform.quality });
|
|
1076
|
+
break;
|
|
1077
|
+
case "jpeg":
|
|
1078
|
+
imagePipeline = imagePipeline.jpeg({ quality: transform.quality, mozjpeg: true });
|
|
1079
|
+
break;
|
|
1080
|
+
case "png":
|
|
1081
|
+
imagePipeline = imagePipeline.png({
|
|
1082
|
+
palette: true,
|
|
1083
|
+
quality: transform.quality,
|
|
1084
|
+
compressionLevel: 9
|
|
1085
|
+
});
|
|
1086
|
+
break;
|
|
1087
|
+
}
|
|
1088
|
+
const chunks = [];
|
|
1089
|
+
let byteLength = 0;
|
|
1090
|
+
let overLimit = false;
|
|
1091
|
+
const boundedSink = new Writable({
|
|
1092
|
+
write(chunk, _encoding, callback) {
|
|
1093
|
+
const bytes2 = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
1094
|
+
if (byteLength + bytes2.byteLength > policy.maxOutputBytes)
|
|
1095
|
+
overLimit = true;
|
|
1096
|
+
else {
|
|
1097
|
+
chunks.push(Buffer.from(bytes2));
|
|
1098
|
+
byteLength += bytes2.byteLength;
|
|
1099
|
+
}
|
|
1100
|
+
callback();
|
|
1101
|
+
}
|
|
1102
|
+
});
|
|
1103
|
+
await runPipeline(imagePipeline, boundedSink);
|
|
1104
|
+
if (overLimit)
|
|
1105
|
+
throw new Error("Image output exceeds the selected byte bound");
|
|
1106
|
+
const bytes = Buffer.concat(chunks, byteLength);
|
|
1107
|
+
const outputMetadata = await sharp(bytes, { limitInputPixels: policy.maxPixels }).metadata();
|
|
1108
|
+
const outputWidth = outputMetadata.width;
|
|
1109
|
+
const outputHeight = outputMetadata.height;
|
|
1110
|
+
if (!Number.isSafeInteger(outputWidth) || !Number.isSafeInteger(outputHeight) || outputWidth < 1 || outputHeight < 1 || outputWidth > policy.maxDimension || outputHeight > policy.maxDimension || outputWidth * outputHeight > policy.maxPixels)
|
|
1111
|
+
throw new Error("Image output exceeds the selected pixel or dimension bound");
|
|
1112
|
+
return {
|
|
1113
|
+
bytes,
|
|
1114
|
+
type: `image/${transform.format}`,
|
|
1115
|
+
width: outputWidth,
|
|
1116
|
+
height: outputHeight
|
|
1117
|
+
};
|
|
1118
|
+
}
|
|
1119
|
+
};
|
|
1120
|
+
} catch {
|
|
1121
|
+
return null;
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
function createFilesystemImageTransforms(input, dependencies = {}) {
|
|
1125
|
+
const policy = Object.freeze({
|
|
1126
|
+
...runtimeFilesystemImagePolicy,
|
|
1127
|
+
maxInputBytes: Math.min(input.maxFileSizeBytes, runtimeFilesystemImagePolicy.maxInputBytes),
|
|
1128
|
+
maxOutputBytes: Math.min(input.maxFileSizeBytes, runtimeFilesystemImagePolicy.maxOutputBytes)
|
|
1129
|
+
});
|
|
1130
|
+
const cache = createFilesystemImageCache({
|
|
1131
|
+
root: input.root,
|
|
1132
|
+
expectedRoot: input.rootIdentity,
|
|
1133
|
+
assertRoot: input.assertRoot,
|
|
1134
|
+
maxBytes: policy.maxCacheBytes,
|
|
1135
|
+
maxEntries: policy.maxCacheEntries,
|
|
1136
|
+
maxOutputBytes: policy.maxOutputBytes
|
|
1137
|
+
});
|
|
1138
|
+
const admission = createBoundedWorkAdmission({
|
|
1139
|
+
maxActive: policy.maxActive,
|
|
1140
|
+
maxQueued: policy.maxQueued,
|
|
1141
|
+
queueWaitMs: policy.queueWaitMs,
|
|
1142
|
+
workTimeoutMs: policy.workTimeoutMs
|
|
1143
|
+
});
|
|
1144
|
+
let encoderPromise;
|
|
1145
|
+
const loadEncoder = dependencies.loadEncoder ?? loadSharpEncoder;
|
|
1146
|
+
function cacheKey(inputValue) {
|
|
1147
|
+
const sourceDigest = createHash2("sha256").update(inputValue.source).digest("hex");
|
|
1148
|
+
const material = JSON.stringify([
|
|
1149
|
+
"runtime-filesystem-image-v2",
|
|
1150
|
+
input.appId,
|
|
1151
|
+
input.root,
|
|
1152
|
+
inputValue.objectId,
|
|
1153
|
+
sourceDigest,
|
|
1154
|
+
inputValue.metadataVersion,
|
|
1155
|
+
inputValue.transform,
|
|
1156
|
+
inputValue.encoderVersion
|
|
1157
|
+
]);
|
|
1158
|
+
return createHash2("sha256").update(material).digest("hex");
|
|
1159
|
+
}
|
|
1160
|
+
return {
|
|
1161
|
+
policy,
|
|
1162
|
+
async initialize() {
|
|
1163
|
+
await cache.initialize();
|
|
1164
|
+
},
|
|
1165
|
+
async render(inputValue) {
|
|
1166
|
+
if (!inputValue.trackWork || inputValue.source.byteLength > policy.maxInputBytes || !/^image\/(?:png|jpeg|jpg|webp)$/u.test(inputValue.sourceType.split(";", 1)[0].trim().toLowerCase()))
|
|
1167
|
+
return null;
|
|
1168
|
+
const provisionalKey = cacheKey({ ...inputValue, encoderVersion: "admission-before-codec-load" });
|
|
1169
|
+
const handle = admission.runTracked(provisionalKey, async (signal) => {
|
|
1170
|
+
encoderPromise ??= Promise.resolve().then(loadEncoder);
|
|
1171
|
+
const encoder = await encoderPromise;
|
|
1172
|
+
if (!encoder || signal.aborted)
|
|
1173
|
+
return null;
|
|
1174
|
+
const key = cacheKey({ ...inputValue, encoderVersion: encoder.version });
|
|
1175
|
+
const cached = await cache.get(key);
|
|
1176
|
+
if (cached)
|
|
1177
|
+
return { entry: cached, key };
|
|
1178
|
+
const reservation = await cache.reserve();
|
|
1179
|
+
if (!reservation)
|
|
1180
|
+
return null;
|
|
1181
|
+
try {
|
|
1182
|
+
if (signal.aborted)
|
|
1183
|
+
return null;
|
|
1184
|
+
const entry = await encoder.encode(inputValue.source, inputValue.transform, {
|
|
1185
|
+
maxPixels: policy.maxDecodedPixels,
|
|
1186
|
+
maxOutputBytes: policy.maxOutputBytes,
|
|
1187
|
+
maxDimension: policy.maxDimension
|
|
1188
|
+
}, inputValue.sourceType);
|
|
1189
|
+
if (signal.aborted)
|
|
1190
|
+
return null;
|
|
1191
|
+
if (inputValue.isAutomaticWebp && entry.bytes.byteLength >= inputValue.source.byteLength)
|
|
1192
|
+
return null;
|
|
1193
|
+
const published = await reservation.publish(key, entry, inputValue.sourceStillCurrent);
|
|
1194
|
+
return published ? { entry, key } : null;
|
|
1195
|
+
} finally {
|
|
1196
|
+
await reservation.release();
|
|
1197
|
+
}
|
|
1198
|
+
}, { signal: inputValue.signal });
|
|
1199
|
+
void inputValue.trackWork.track(handle.settled);
|
|
1200
|
+
const result = await handle.result;
|
|
1201
|
+
return result.status === "completed" ? result.value : null;
|
|
1202
|
+
},
|
|
1203
|
+
dispose() {
|
|
1204
|
+
return cache.dispose();
|
|
1205
|
+
},
|
|
1206
|
+
snapshot() {
|
|
1207
|
+
return admission.snapshot();
|
|
1208
|
+
}
|
|
1209
|
+
};
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
// ../runtime/dist/adapters/storage/filesystem-read-grant.js
|
|
1213
|
+
import { createHmac, randomBytes, randomUUID as randomUUID2, timingSafeEqual } from "node:crypto";
|
|
1214
|
+
import { constants as constants4 } from "node:fs";
|
|
1215
|
+
import { link as link2, lstat as lstat2, open as open3, readdir, unlink as unlink2, writeFile } from "node:fs/promises";
|
|
1216
|
+
import { join as join3 } from "node:path";
|
|
1217
|
+
var KEY_BYTES = 32;
|
|
1218
|
+
var MAX_GRANT_BYTES = 8192;
|
|
1219
|
+
var GRANT_TTL_DEFAULT_SECONDS = 60;
|
|
1220
|
+
var GRANT_TTL_MIN_SECONDS = 1;
|
|
1221
|
+
var GRANT_TTL_MAX_SECONDS = 300;
|
|
1222
|
+
var KEY_TEMP_PREFIX = `${filesystemReadGrantKeyFilename}.tmp-`;
|
|
1223
|
+
var KEY_RACE_ATTEMPTS = 100;
|
|
1224
|
+
var KEY_RACE_DELAY_MS = 10;
|
|
1225
|
+
async function loadPortableFilesystemReadGrantKey(root) {
|
|
1226
|
+
const path = join3(root, filesystemReadGrantKeyFilename);
|
|
1227
|
+
const temporary = `${path}.tmp-${randomUUID2()}`;
|
|
1228
|
+
try {
|
|
1229
|
+
await writeFile(temporary, randomBytes(KEY_BYTES), { flag: "wx", mode: 384 });
|
|
1230
|
+
try {
|
|
1231
|
+
await link2(temporary, path);
|
|
1232
|
+
} catch (error) {
|
|
1233
|
+
if (!error || typeof error !== "object" || !("code" in error) || error.code !== "EEXIST")
|
|
1234
|
+
throw error;
|
|
1235
|
+
}
|
|
1236
|
+
} finally {
|
|
1237
|
+
await unlink2(temporary).catch(() => {
|
|
1238
|
+
});
|
|
1239
|
+
}
|
|
1240
|
+
return readValidatedKey(path, true);
|
|
1241
|
+
}
|
|
1242
|
+
function keyFailure() {
|
|
1243
|
+
return new RuntimeDiagnosticError({
|
|
1244
|
+
code: "RUNTIME_STORAGE_READ_GRANT_KEY_UNAVAILABLE",
|
|
1245
|
+
stage: "startup",
|
|
1246
|
+
capability: "storage",
|
|
1247
|
+
servingStarted: false,
|
|
1248
|
+
dataImpact: "unknown",
|
|
1249
|
+
retryable: false,
|
|
1250
|
+
retryPrecondition: "Restore a complete, owner-readable grant key with its protected permissions, then restart the selected storage generation.",
|
|
1251
|
+
nextAction: "Preserve existing storage files. Check the trusted storage directory's key-file ownership and permissions; do not delete, edit, or regenerate an existing key.",
|
|
1252
|
+
correlationId: randomUUID2()
|
|
1253
|
+
});
|
|
1254
|
+
}
|
|
1255
|
+
function grantInputInvalid() {
|
|
1256
|
+
return new RuntimeDiagnosticError({
|
|
1257
|
+
code: "RUNTIME_STORAGE_READ_GRANT_INPUT_INVALID",
|
|
1258
|
+
stage: "request",
|
|
1259
|
+
capability: "storage",
|
|
1260
|
+
servingStarted: "unchanged",
|
|
1261
|
+
dataImpact: "none",
|
|
1262
|
+
retryable: false,
|
|
1263
|
+
retryPrecondition: "Use a valid flat stored object ID and supported read-grant options.",
|
|
1264
|
+
nextAction: "Request a new grant through the selected Storage API with a valid ID, bounded TTL, and supported disposition or verified principal restriction. Inspect earlier containing-operation effects before deliberate retry."
|
|
1265
|
+
});
|
|
1266
|
+
}
|
|
1267
|
+
function grantBindingUnavailable() {
|
|
1268
|
+
return new RuntimeDiagnosticError({
|
|
1269
|
+
code: "RUNTIME_STORAGE_READ_GRANT_BINDING_UNAVAILABLE",
|
|
1270
|
+
stage: "request",
|
|
1271
|
+
capability: "storage",
|
|
1272
|
+
servingStarted: "unchanged",
|
|
1273
|
+
dataImpact: "none",
|
|
1274
|
+
retryable: false,
|
|
1275
|
+
retryPrecondition: "Use the selected verified request identity/session that owns the requested grant restriction.",
|
|
1276
|
+
nextAction: "Issue a subject- or session-bound grant only from a request whose selected Auth adapter has verified that same principal; this rejected grant call changed no storage object."
|
|
1277
|
+
});
|
|
1278
|
+
}
|
|
1279
|
+
function filesystemKeyPath(root) {
|
|
1280
|
+
return join3(root, filesystemReadGrantKeyFilename);
|
|
1281
|
+
}
|
|
1282
|
+
function hasExpectedFileMetadata(stats, portable = false) {
|
|
1283
|
+
const expectedUid = process.getuid?.();
|
|
1284
|
+
const mode = Number(stats.mode);
|
|
1285
|
+
return stats.isFile() && stats.size === KEY_BYTES && (portable || (mode & 511) === 384) && (portable || expectedUid === void 0 || stats.uid === expectedUid);
|
|
1286
|
+
}
|
|
1287
|
+
function hasExpectedFileShape(stats, expectedLinks = 1, portable = false) {
|
|
1288
|
+
return hasExpectedFileMetadata(stats, portable) && stats.nlink === expectedLinks;
|
|
1289
|
+
}
|
|
1290
|
+
async function readValidatedKey(path, portable = false) {
|
|
1291
|
+
let handle;
|
|
1292
|
+
try {
|
|
1293
|
+
const before = await lstat2(path);
|
|
1294
|
+
if (!hasExpectedFileShape(before, 1, portable))
|
|
1295
|
+
throw keyFailure();
|
|
1296
|
+
handle = await open3(path, constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK);
|
|
1297
|
+
const after = await handle.stat();
|
|
1298
|
+
if (!hasExpectedFileShape(after, 1, portable) || before.dev !== after.dev || before.ino !== after.ino)
|
|
1299
|
+
throw keyFailure();
|
|
1300
|
+
const bytes = Buffer.alloc(KEY_BYTES + 1);
|
|
1301
|
+
let bytesRead = 0;
|
|
1302
|
+
while (bytesRead < bytes.length) {
|
|
1303
|
+
const result = await handle.read(bytes, bytesRead, bytes.length - bytesRead, bytesRead);
|
|
1304
|
+
if (result.bytesRead === 0)
|
|
1305
|
+
break;
|
|
1306
|
+
bytesRead += result.bytesRead;
|
|
1307
|
+
}
|
|
1308
|
+
const afterRead = await handle.stat();
|
|
1309
|
+
const finalPath = await lstat2(path);
|
|
1310
|
+
if (bytesRead !== KEY_BYTES || !hasExpectedFileShape(afterRead, 1, portable) || !hasExpectedFileShape(finalPath, 1, portable) || afterRead.dev !== before.dev || afterRead.ino !== before.ino || finalPath.dev !== before.dev || finalPath.ino !== before.ino)
|
|
1311
|
+
throw keyFailure();
|
|
1312
|
+
return bytes.subarray(0, KEY_BYTES);
|
|
1313
|
+
} catch (error) {
|
|
1314
|
+
if (error instanceof RuntimeDiagnosticError)
|
|
1315
|
+
throw error;
|
|
1316
|
+
throw keyFailure();
|
|
1317
|
+
} finally {
|
|
1318
|
+
await handle?.close().catch(() => {
|
|
1319
|
+
});
|
|
1320
|
+
}
|
|
1321
|
+
}
|
|
1322
|
+
async function syncDirectory(root) {
|
|
1323
|
+
const directory = await open3(root, constants4.O_RDONLY);
|
|
1324
|
+
try {
|
|
1325
|
+
await directory.sync();
|
|
1326
|
+
} finally {
|
|
1327
|
+
await directory.close();
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
async function temporaryKeyEntries(root) {
|
|
1331
|
+
return (await readdir(root)).filter((entry) => entry.startsWith(KEY_TEMP_PREFIX));
|
|
1332
|
+
}
|
|
1333
|
+
async function delay(ms) {
|
|
1334
|
+
await new Promise((resolveDelay) => setTimeout(resolveDelay, ms));
|
|
1335
|
+
}
|
|
1336
|
+
async function validatePublishedWinner(root, observeTemporaryStat) {
|
|
1337
|
+
const path = filesystemKeyPath(root);
|
|
1338
|
+
for (let attempt = 0; attempt < KEY_RACE_ATTEMPTS; attempt++) {
|
|
1339
|
+
let finalStats;
|
|
1340
|
+
try {
|
|
1341
|
+
finalStats = await lstat2(path);
|
|
1342
|
+
} catch (error) {
|
|
1343
|
+
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
|
|
1344
|
+
await delay(KEY_RACE_DELAY_MS);
|
|
1345
|
+
continue;
|
|
1346
|
+
}
|
|
1347
|
+
throw keyFailure();
|
|
1348
|
+
}
|
|
1349
|
+
const expectedUid = process.getuid?.();
|
|
1350
|
+
const mode = Number(finalStats.mode);
|
|
1351
|
+
if (!finalStats.isFile() || finalStats.size !== KEY_BYTES || (mode & 511) !== 384 || expectedUid !== void 0 && finalStats.uid !== expectedUid || finalStats.nlink !== 1 && finalStats.nlink !== 2)
|
|
1352
|
+
throw keyFailure();
|
|
1353
|
+
const entries = await temporaryKeyEntries(root);
|
|
1354
|
+
const sameInodeTemps = [];
|
|
1355
|
+
let temporarySnapshotIsStale = false;
|
|
1356
|
+
for (const entry of entries) {
|
|
1357
|
+
let stats;
|
|
1358
|
+
try {
|
|
1359
|
+
stats = await lstat2(join3(root, entry));
|
|
1360
|
+
} catch {
|
|
1361
|
+
continue;
|
|
1362
|
+
}
|
|
1363
|
+
const observedStats = observeTemporaryStat ? await observeTemporaryStat(entry, stats) : stats;
|
|
1364
|
+
if (observedStats.dev === finalStats.dev && observedStats.ino === finalStats.ino) {
|
|
1365
|
+
if (hasExpectedFileMetadata(observedStats) && observedStats.nlink === 1) {
|
|
1366
|
+
temporarySnapshotIsStale = true;
|
|
1367
|
+
break;
|
|
1368
|
+
}
|
|
1369
|
+
if (!hasExpectedFileShape(observedStats, 2))
|
|
1370
|
+
throw keyFailure();
|
|
1371
|
+
sameInodeTemps.push(entry);
|
|
1372
|
+
}
|
|
1373
|
+
}
|
|
1374
|
+
if (temporarySnapshotIsStale) {
|
|
1375
|
+
await delay(KEY_RACE_DELAY_MS);
|
|
1376
|
+
continue;
|
|
1377
|
+
}
|
|
1378
|
+
if (finalStats.nlink === 2 && sameInodeTemps.length === 1) {
|
|
1379
|
+
await unlink2(join3(root, sameInodeTemps[0])).catch((error) => {
|
|
1380
|
+
if (!(error && typeof error === "object" && "code" in error && error.code === "ENOENT"))
|
|
1381
|
+
throw keyFailure();
|
|
1382
|
+
});
|
|
1383
|
+
await syncDirectory(root).catch(() => {
|
|
1384
|
+
throw keyFailure();
|
|
1385
|
+
});
|
|
1386
|
+
continue;
|
|
1387
|
+
}
|
|
1388
|
+
if (finalStats.nlink !== 1 || entries.length > 0) {
|
|
1389
|
+
await delay(KEY_RACE_DELAY_MS);
|
|
1390
|
+
continue;
|
|
1391
|
+
}
|
|
1392
|
+
return await readValidatedKey(path);
|
|
1393
|
+
}
|
|
1394
|
+
throw keyFailure();
|
|
1395
|
+
}
|
|
1396
|
+
async function loadOrCreateFilesystemReadGrantKey(root, observeTemporaryStat) {
|
|
1397
|
+
const finalPath = filesystemKeyPath(root);
|
|
1398
|
+
const existingTemps = await temporaryKeyEntries(root).catch(() => {
|
|
1399
|
+
throw keyFailure();
|
|
1400
|
+
});
|
|
1401
|
+
if (existingTemps.length) {
|
|
1402
|
+
try {
|
|
1403
|
+
return await validatePublishedWinner(root, observeTemporaryStat);
|
|
1404
|
+
} catch {
|
|
1405
|
+
throw keyFailure();
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
try {
|
|
1409
|
+
const current = await lstat2(finalPath);
|
|
1410
|
+
if (current)
|
|
1411
|
+
return await validatePublishedWinner(root, observeTemporaryStat);
|
|
1412
|
+
} catch (error) {
|
|
1413
|
+
if (!(error && typeof error === "object" && "code" in error && error.code === "ENOENT"))
|
|
1414
|
+
throw keyFailure();
|
|
1415
|
+
}
|
|
1416
|
+
const temporaryPath = join3(root, `${KEY_TEMP_PREFIX}${randomUUID2()}`);
|
|
1417
|
+
let handle;
|
|
1418
|
+
try {
|
|
1419
|
+
handle = await open3(temporaryPath, constants4.O_WRONLY | constants4.O_CREAT | constants4.O_EXCL | constants4.O_NOFOLLOW, 384);
|
|
1420
|
+
await handle.chmod(384);
|
|
1421
|
+
const key = randomBytes(KEY_BYTES);
|
|
1422
|
+
await handle.writeFile(key);
|
|
1423
|
+
await handle.sync();
|
|
1424
|
+
const written = await handle.stat();
|
|
1425
|
+
if (!hasExpectedFileShape(written))
|
|
1426
|
+
throw keyFailure();
|
|
1427
|
+
await handle.close();
|
|
1428
|
+
handle = void 0;
|
|
1429
|
+
let published = false;
|
|
1430
|
+
try {
|
|
1431
|
+
await link2(temporaryPath, finalPath);
|
|
1432
|
+
published = true;
|
|
1433
|
+
await syncDirectory(root);
|
|
1434
|
+
try {
|
|
1435
|
+
await unlink2(temporaryPath);
|
|
1436
|
+
} catch (error) {
|
|
1437
|
+
if (!(error && typeof error === "object" && "code" in error && error.code === "ENOENT"))
|
|
1438
|
+
throw error;
|
|
1439
|
+
}
|
|
1440
|
+
await syncDirectory(root);
|
|
1441
|
+
} catch (error) {
|
|
1442
|
+
if (published) {
|
|
1443
|
+
await unlink2(temporaryPath).catch(() => {
|
|
1444
|
+
});
|
|
1445
|
+
await syncDirectory(root).catch(() => {
|
|
1446
|
+
});
|
|
1447
|
+
} else {
|
|
1448
|
+
await unlink2(temporaryPath).catch(() => {
|
|
1449
|
+
});
|
|
1450
|
+
}
|
|
1451
|
+
if (error && typeof error === "object" && "code" in error && (error.code === "EEXIST" || published && error.code === "ENOENT"))
|
|
1452
|
+
return await validatePublishedWinner(root, observeTemporaryStat);
|
|
1453
|
+
throw keyFailure();
|
|
1454
|
+
}
|
|
1455
|
+
return await validatePublishedWinner(root, observeTemporaryStat);
|
|
1456
|
+
} catch (error) {
|
|
1457
|
+
await handle?.close().catch(() => {
|
|
1458
|
+
});
|
|
1459
|
+
if (error instanceof RuntimeDiagnosticError)
|
|
1460
|
+
throw error;
|
|
1461
|
+
throw keyFailure();
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
function base64url(bytes) {
|
|
1465
|
+
return Buffer.from(bytes).toString("base64url");
|
|
1466
|
+
}
|
|
1467
|
+
function decodeBase64url(value) {
|
|
1468
|
+
if (!/^[A-Za-z0-9_-]+$/u.test(value))
|
|
1469
|
+
return null;
|
|
1470
|
+
const decoded = Buffer.from(value, "base64url");
|
|
1471
|
+
return base64url(decoded) === value ? decoded : null;
|
|
1472
|
+
}
|
|
1473
|
+
function normalizedTtl(input) {
|
|
1474
|
+
const requested = input && typeof input === "object" && "ttlSeconds" in input ? input.ttlSeconds : void 0;
|
|
1475
|
+
const raw = typeof requested === "number" && Number.isFinite(requested) ? Math.floor(requested) : GRANT_TTL_DEFAULT_SECONDS;
|
|
1476
|
+
return Math.max(GRANT_TTL_MIN_SECONDS, Math.min(GRANT_TTL_MAX_SECONDS, raw));
|
|
1477
|
+
}
|
|
1478
|
+
function safeDisposition(value) {
|
|
1479
|
+
return value === "attachment" ? "attachment" : "inline";
|
|
1480
|
+
}
|
|
1481
|
+
function exactKeys(value, expected) {
|
|
1482
|
+
const keys = Object.keys(value).sort();
|
|
1483
|
+
const sorted = [...expected].sort();
|
|
1484
|
+
return keys.length === sorted.length && keys.every((key, index) => key === sorted[index]);
|
|
1485
|
+
}
|
|
1486
|
+
function createRuntimeReadGrantSigner(input) {
|
|
1487
|
+
if (input.key.length !== KEY_BYTES)
|
|
1488
|
+
throw keyFailure();
|
|
1489
|
+
const key = Buffer.from(input.key);
|
|
1490
|
+
const now = input.now ?? Date.now;
|
|
1491
|
+
const rootClaim = createHmac("sha256", key).update("gencow-storage-root-v1\0", "utf8").update(input.appId, "utf8").update("\0", "utf8").update(input.root, "utf8").digest("base64url");
|
|
1492
|
+
function sessionClaim(sessionId) {
|
|
1493
|
+
return createHmac("sha256", key).update("gencow-storage-session-v1\0", "utf8").update(sessionId, "utf8").digest("base64url");
|
|
1494
|
+
}
|
|
1495
|
+
function sign(storageId, options2, principal) {
|
|
1496
|
+
if (options2 !== void 0 && (!options2 || typeof options2 !== "object" || Array.isArray(options2)))
|
|
1497
|
+
throw grantInputInvalid();
|
|
1498
|
+
const subject = options2?.subject;
|
|
1499
|
+
const sessionId = options2?.sessionId;
|
|
1500
|
+
if (subject !== void 0 && (typeof subject !== "string" || !subject.trim() || subject.length > 2048) || sessionId !== void 0 && (typeof sessionId !== "string" || !sessionId.trim() || sessionId.length > 2048))
|
|
1501
|
+
throw grantInputInvalid();
|
|
1502
|
+
if ((subject !== void 0 || sessionId !== void 0) && principal?.credentialStatus !== "verified" || subject !== void 0 && principal?.identityId !== subject || sessionId !== void 0 && principal?.sessionId !== sessionId)
|
|
1503
|
+
throw grantBindingUnavailable();
|
|
1504
|
+
const nowMs = now();
|
|
1505
|
+
const expiresAtMs = nowMs + normalizedTtl(options2) * 1e3;
|
|
1506
|
+
if (!Number.isSafeInteger(expiresAtMs) || expiresAtMs <= nowMs)
|
|
1507
|
+
throw grantInputInvalid();
|
|
1508
|
+
const claims = {
|
|
1509
|
+
v: 1,
|
|
1510
|
+
app: input.appId,
|
|
1511
|
+
root: rootClaim,
|
|
1512
|
+
object: storageId,
|
|
1513
|
+
exp: expiresAtMs,
|
|
1514
|
+
disposition: safeDisposition(options2?.disposition),
|
|
1515
|
+
...subject !== void 0 ? { subject } : {},
|
|
1516
|
+
...sessionId !== void 0 ? { session: sessionClaim(sessionId) } : {}
|
|
1517
|
+
};
|
|
1518
|
+
const encoded = base64url(Buffer.from(JSON.stringify(claims), "utf8"));
|
|
1519
|
+
const signature = base64url(createHmac("sha256", key).update(encoded, "ascii").digest());
|
|
1520
|
+
const token = `${encoded}.${signature}`;
|
|
1521
|
+
if (Buffer.byteLength(token, "utf8") > MAX_GRANT_BYTES)
|
|
1522
|
+
throw grantInputInvalid();
|
|
1523
|
+
return {
|
|
1524
|
+
url: `/api/storage/${encodeURIComponent(storageId)}?grant=${encodeURIComponent(token)}`,
|
|
1525
|
+
expiresAt: new Date(expiresAtMs).toISOString()
|
|
1526
|
+
};
|
|
1527
|
+
}
|
|
1528
|
+
function verify(storageId, token, principal) {
|
|
1529
|
+
if (!token || Buffer.byteLength(token, "utf8") > MAX_GRANT_BYTES)
|
|
1530
|
+
return null;
|
|
1531
|
+
const parts = token.split(".");
|
|
1532
|
+
if (parts.length !== 2)
|
|
1533
|
+
return null;
|
|
1534
|
+
const [encoded, suppliedText] = parts;
|
|
1535
|
+
const payload = decodeBase64url(encoded);
|
|
1536
|
+
const supplied = decodeBase64url(suppliedText);
|
|
1537
|
+
if (!payload || !supplied || supplied.length !== 32)
|
|
1538
|
+
return null;
|
|
1539
|
+
const expectedSignature = createHmac("sha256", key).update(encoded, "ascii").digest();
|
|
1540
|
+
if (!timingSafeEqual(expectedSignature, supplied))
|
|
1541
|
+
return null;
|
|
1542
|
+
let claims;
|
|
1543
|
+
try {
|
|
1544
|
+
claims = JSON.parse(payload.toString("utf8"));
|
|
1545
|
+
} catch {
|
|
1546
|
+
return null;
|
|
1547
|
+
}
|
|
1548
|
+
if (!claims || typeof claims !== "object" || Array.isArray(claims))
|
|
1549
|
+
return null;
|
|
1550
|
+
const value = claims;
|
|
1551
|
+
const hasSubject = Object.hasOwn(value, "subject");
|
|
1552
|
+
const hasSession = Object.hasOwn(value, "session");
|
|
1553
|
+
const expected = [
|
|
1554
|
+
"v",
|
|
1555
|
+
"app",
|
|
1556
|
+
"root",
|
|
1557
|
+
"object",
|
|
1558
|
+
"exp",
|
|
1559
|
+
"disposition",
|
|
1560
|
+
...hasSubject ? ["subject"] : [],
|
|
1561
|
+
...hasSession ? ["session"] : []
|
|
1562
|
+
];
|
|
1563
|
+
if (!exactKeys(value, expected) || base64url(Buffer.from(JSON.stringify(value), "utf8")) !== encoded || value.v !== 1 || value.app !== input.appId || value.root !== rootClaim || value.object !== storageId || typeof value.exp !== "number" || !Number.isSafeInteger(value.exp) || value.exp <= now() || value.disposition !== "inline" && value.disposition !== "attachment" || hasSubject && (typeof value.subject !== "string" || principal?.credentialStatus !== "verified" || !principal.identityId || value.subject !== principal.identityId) || hasSession && (typeof value.session !== "string" || principal?.credentialStatus !== "verified" || !principal.sessionId || value.session !== sessionClaim(principal.sessionId)))
|
|
1564
|
+
return null;
|
|
1565
|
+
return value.disposition;
|
|
1566
|
+
}
|
|
1567
|
+
return Object.freeze({ sign, verify, dispose: () => key.fill(0) });
|
|
1568
|
+
}
|
|
1569
|
+
|
|
1570
|
+
// ../runtime/dist/adapters/storage/filesystem-object-fence.js
|
|
1571
|
+
function createFilesystemObjectFence() {
|
|
1572
|
+
const tails = /* @__PURE__ */ new Map();
|
|
1573
|
+
const blocked = /* @__PURE__ */ new Map();
|
|
1574
|
+
async function enqueue(objectId, mayRecover, operation) {
|
|
1575
|
+
const prior = tails.get(objectId) ?? Promise.resolve();
|
|
1576
|
+
let release;
|
|
1577
|
+
const gate = new Promise((resolve) => {
|
|
1578
|
+
release = resolve;
|
|
1579
|
+
});
|
|
1580
|
+
tails.set(objectId, gate);
|
|
1581
|
+
await prior;
|
|
1582
|
+
try {
|
|
1583
|
+
const failure = blocked.get(objectId);
|
|
1584
|
+
if (failure && !mayRecover())
|
|
1585
|
+
throw failure();
|
|
1586
|
+
return await operation();
|
|
1587
|
+
} finally {
|
|
1588
|
+
release();
|
|
1589
|
+
if (tails.get(objectId) === gate)
|
|
1590
|
+
tails.delete(objectId);
|
|
1591
|
+
}
|
|
1592
|
+
}
|
|
1593
|
+
const run = (objectId, operation) => enqueue(objectId, () => false, operation);
|
|
1594
|
+
const runRecovery = (objectId, mayRecover, operation) => enqueue(objectId, mayRecover, operation);
|
|
1595
|
+
return Object.freeze({
|
|
1596
|
+
run,
|
|
1597
|
+
runRecovery,
|
|
1598
|
+
quarantine(objectId, failure) {
|
|
1599
|
+
blocked.set(objectId, failure);
|
|
1600
|
+
},
|
|
1601
|
+
isQuarantined(objectId) {
|
|
1602
|
+
return blocked.has(objectId);
|
|
1603
|
+
},
|
|
1604
|
+
clearQuarantine(objectId) {
|
|
1605
|
+
blocked.delete(objectId);
|
|
1606
|
+
},
|
|
1607
|
+
assertAvailable(objectId) {
|
|
1608
|
+
const failure = blocked.get(objectId);
|
|
1609
|
+
if (failure)
|
|
1610
|
+
throw failure();
|
|
1611
|
+
}
|
|
1612
|
+
});
|
|
1613
|
+
}
|
|
1614
|
+
|
|
1615
|
+
// ../runtime/dist/adapters/storage/filesystem-upload-errors.js
|
|
1616
|
+
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
1617
|
+
function filesystemUploadIoFailure(error, stage, dataImpact, publishedAssetId) {
|
|
1618
|
+
const diagnosed = runtimeDiagnostic(error);
|
|
1619
|
+
if (diagnosed)
|
|
1620
|
+
return new RuntimeDiagnosticError(diagnosed);
|
|
1621
|
+
const code = error && typeof error === "object" && "code" in error ? error.code : void 0;
|
|
1622
|
+
const denied = code === "EACCES" || code === "EPERM" || code === "EROFS";
|
|
1623
|
+
return filesystemUploadFailure("RUNTIME_STORAGE_UPLOAD_STORAGE_UNAVAILABLE", stage, {
|
|
1624
|
+
dataImpact,
|
|
1625
|
+
retryable: false,
|
|
1626
|
+
retryPrecondition: publishedAssetId ? "Publication succeeded but upload cleanup failed. Inspect the published object and containing operation before any new mutation." : "Restore verified filesystem access and availability, then inspect this upload and any earlier application effects before retrying.",
|
|
1627
|
+
nextAction: publishedAssetId ? `Inspect ctx.storage.getMeta(${JSON.stringify(publishedAssetId)}) and the containing application's operation status. Do not repeat finalize or the business mutation; abort cannot roll back the published object.` : denied ? "Restore access to the configured storage directory, then verify its availability. Preserve existing files and inspect the containing operation before deliberately retrying." : "Check the configured storage directory, available disk space, and access. Preserve existing files; inspect the containing operation before a deliberate retry. Do not edit upload records or blindly repeat mutations."
|
|
1628
|
+
});
|
|
1629
|
+
}
|
|
1630
|
+
function pendingGuidance(stage) {
|
|
1631
|
+
switch (stage) {
|
|
1632
|
+
case "grant":
|
|
1633
|
+
return {
|
|
1634
|
+
retryPrecondition: "Check the containing application operation and selected storage owner for a durable grant before starting another mutation.",
|
|
1635
|
+
nextAction: "A grant response was not confirmed, so its upload ID may be unavailable. Inspect the same application operation; do not blindly repeat it or create another grant."
|
|
1636
|
+
};
|
|
1637
|
+
case "receive":
|
|
1638
|
+
return {
|
|
1639
|
+
retryPrecondition: "Wait for the selected owner to verify whether this PUT's stage pointer committed and confirm that publication has not begun.",
|
|
1640
|
+
nextAction: "Keep the same upload ID. Do not finalize unverified bytes; repeat only this PUT after the owner confirms the previous stage remains current and replacement is allowed."
|
|
1641
|
+
};
|
|
1642
|
+
case "finalize":
|
|
1643
|
+
return {
|
|
1644
|
+
retryPrecondition: "Let the same app-root owner reconcile the durable publication for this upload ID before any retry.",
|
|
1645
|
+
nextAction: "Keep the original upload ID. Retry only its idempotent Storage finalize operation if the owner permits; do not replay the containing application mutation or create a replacement grant."
|
|
1646
|
+
};
|
|
1647
|
+
case "abort":
|
|
1648
|
+
return {
|
|
1649
|
+
retryPrecondition: "Verify whether publication finalized for this upload ID before taking another action.",
|
|
1650
|
+
nextAction: "Abort cannot roll back a published object. Preserve the original upload ID and inspect the selected owner; do not assume that bytes were removed or blindly finalize."
|
|
1651
|
+
};
|
|
1652
|
+
case "recovery":
|
|
1653
|
+
return {
|
|
1654
|
+
retryPrecondition: "Wait until the selected app-root owner can verify the same upload record and its publication evidence.",
|
|
1655
|
+
nextAction: "Preserve the known upload ID and let the selected owner reconcile it. Do not edit internal records, create another grant, or replay the containing application mutation."
|
|
1656
|
+
};
|
|
1657
|
+
default:
|
|
1658
|
+
return {
|
|
1659
|
+
retryPrecondition: "Verify that no upload owner was initialized and restore safe access to the selected filesystem before restarting.",
|
|
1660
|
+
nextAction: "Preserve existing storage and upload records; restore the selected owner prerequisites before accepting upload operations."
|
|
1661
|
+
};
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
function capacityGuidance(stage, pressure) {
|
|
1665
|
+
if (pressure === "receipt_slots" || pressure === "journal_bytes")
|
|
1666
|
+
return {
|
|
1667
|
+
retryPrecondition: "Wait for an eligible terminal receipt to pass the 24-hour retention horizon and for safe owner cleanup to finish.",
|
|
1668
|
+
nextAction: "Terminal upload receipts cannot be evicted early. Preserve the current upload state and retry this operation only after the owner confirms journal capacity is available."
|
|
1669
|
+
};
|
|
1670
|
+
if (pressure === "staging_bytes")
|
|
1671
|
+
return {
|
|
1672
|
+
retryPrecondition: "Wait until the selected owner verifies that retained staging and candidate bytes have been safely cleaned.",
|
|
1673
|
+
nextAction: "Keep the same upload ID and its previous committed stage. Retry only this PUT after bounded staging capacity is available; do not start a replacement application mutation."
|
|
1674
|
+
};
|
|
1675
|
+
if (stage === "receive")
|
|
1676
|
+
return {
|
|
1677
|
+
retryPrecondition: "Resolve known pending upload work or wait until its declared reservation is released by the owner.",
|
|
1678
|
+
nextAction: "This PUT did not publish an object and the previous committed stage remains selected. Keep the same upload ID; retry only this PUT after the owner confirms capacity."
|
|
1679
|
+
};
|
|
1680
|
+
return {
|
|
1681
|
+
retryPrecondition: "Resolve known pending upload work or wait until the owner releases declared reservations.",
|
|
1682
|
+
nextAction: "No grant was created by this denial. Resolve or abort known pending uploads, then start a new grant only after the owner confirms capacity; do not replay an earlier containing mutation without checking its effects."
|
|
1683
|
+
};
|
|
1684
|
+
}
|
|
1685
|
+
var presentation = {
|
|
1686
|
+
RUNTIME_STORAGE_UPLOAD_INVALID: { status: 400, message: "The storage upload request is invalid." },
|
|
1687
|
+
RUNTIME_STORAGE_UPLOAD_LENGTH_REQUIRED: {
|
|
1688
|
+
status: 411,
|
|
1689
|
+
message: "The storage upload requires a valid Content-Length header."
|
|
1690
|
+
},
|
|
1691
|
+
RUNTIME_STORAGE_UPLOAD_TOO_LARGE: { status: 413, message: "The storage upload exceeds its limit." },
|
|
1692
|
+
RUNTIME_STORAGE_UPLOAD_CAPACITY_EXCEEDED: {
|
|
1693
|
+
status: 503,
|
|
1694
|
+
message: "The selected storage upload capacity is full."
|
|
1695
|
+
},
|
|
1696
|
+
RUNTIME_STORAGE_UPLOAD_CONFLICT: { status: 409, message: "The storage upload is not in a writable state." },
|
|
1697
|
+
RUNTIME_STORAGE_UPLOAD_EXPIRED: { status: 410, message: "The storage upload grant has expired." },
|
|
1698
|
+
RUNTIME_STORAGE_UPLOAD_NOT_FOUND: { status: 404, message: "The storage upload is unavailable." },
|
|
1699
|
+
RUNTIME_STORAGE_UPLOAD_PENDING: {
|
|
1700
|
+
status: 503,
|
|
1701
|
+
message: "The storage upload outcome is still being reconciled."
|
|
1702
|
+
},
|
|
1703
|
+
RUNTIME_STORAGE_UPLOAD_ABORTED: { status: 409, message: "The storage upload was aborted." },
|
|
1704
|
+
RUNTIME_STORAGE_UPLOAD_STORAGE_UNAVAILABLE: {
|
|
1705
|
+
status: 503,
|
|
1706
|
+
message: "The selected filesystem upload storage is unavailable."
|
|
1707
|
+
}
|
|
1708
|
+
};
|
|
1709
|
+
function filesystemUploadFailure(code, stage, options2 = {}) {
|
|
1710
|
+
const message = presentation[code].message;
|
|
1711
|
+
const startup = stage === "startup";
|
|
1712
|
+
const pending = code === "RUNTIME_STORAGE_UPLOAD_PENDING" ? pendingGuidance(stage) : void 0;
|
|
1713
|
+
const capacity = code === "RUNTIME_STORAGE_UPLOAD_CAPACITY_EXCEEDED" && (stage === "grant" || stage === "receive") && options2.uploadPressure ? capacityGuidance(stage, options2.uploadPressure) : void 0;
|
|
1714
|
+
return new RuntimeDiagnosticError({
|
|
1715
|
+
code,
|
|
1716
|
+
stage,
|
|
1717
|
+
capability: "storage",
|
|
1718
|
+
servingStarted: startup ? false : "unchanged",
|
|
1719
|
+
dataImpact: options2.dataImpact ?? (startup ? "unknown" : "none"),
|
|
1720
|
+
retryable: options2.retryable ?? false,
|
|
1721
|
+
retryPrecondition: options2.retryPrecondition ?? pending?.retryPrecondition ?? capacity?.retryPrecondition ?? "Correct the upload request or selected filesystem condition and verify its current state before retrying.",
|
|
1722
|
+
nextAction: options2.nextAction ?? pending?.nextAction ?? capacity?.nextAction ?? message,
|
|
1723
|
+
correlationId: options2.correlationId ?? randomUUID3(),
|
|
1724
|
+
...options2.uploadPressure ? { uploadPressure: options2.uploadPressure } : {}
|
|
1725
|
+
});
|
|
1726
|
+
}
|
|
1727
|
+
|
|
1728
|
+
// ../runtime/dist/adapters/storage/filesystem-portable-upload.js
|
|
1729
|
+
import { createHash as createHash3, randomUUID as randomUUID4 } from "node:crypto";
|
|
1730
|
+
import { mkdir as mkdir2, open as open4, readFile, rename, rm, writeFile as writeFile2 } from "node:fs/promises";
|
|
1731
|
+
import { join as join4 } from "node:path";
|
|
1732
|
+
|
|
1733
|
+
// ../runtime/dist/adapters/storage/filesystem-upload-model.js
|
|
1734
|
+
var filesystemUploadApiLimit = 50 * 1024 * 1024;
|
|
1735
|
+
var filesystemUploadUuidV4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
|
|
1736
|
+
var checksumPattern = /^[0-9a-f]{64}$/u;
|
|
1737
|
+
function normalizeUploadChecksum(value) {
|
|
1738
|
+
if (typeof value !== "string")
|
|
1739
|
+
return void 0;
|
|
1740
|
+
const normalized = value.trim().toLowerCase();
|
|
1741
|
+
return checksumPattern.test(normalized) ? normalized : void 0;
|
|
1742
|
+
}
|
|
1743
|
+
function isUploadChecksumInputValid(value) {
|
|
1744
|
+
return value === void 0 || normalizeUploadChecksum(value) !== void 0;
|
|
1745
|
+
}
|
|
1746
|
+
|
|
1747
|
+
// ../runtime/dist/adapters/storage/filesystem-portable-upload.js
|
|
1748
|
+
function createPortableFilesystemUploads(input) {
|
|
1749
|
+
const directory = join4(input.root, ".uploads");
|
|
1750
|
+
const failure = filesystemUploadFailure;
|
|
1751
|
+
const consumedAction = "Inspect the containing application's operation status and ctx.storage.listMeta before creating a replacement upload. Do not repeat finalize or blindly replay the business mutation; this upload may already have published an object.";
|
|
1752
|
+
const notPending = (stage) => failure("RUNTIME_STORAGE_UPLOAD_NOT_FOUND", stage, {
|
|
1753
|
+
retryPrecondition: "The upload ID is no longer pending or does not exist. Verify the containing operation's previous outcome before any new upload mutation.",
|
|
1754
|
+
nextAction: consumedAction
|
|
1755
|
+
});
|
|
1756
|
+
function paths(id, stage) {
|
|
1757
|
+
if (!filesystemUploadUuidV4.test(id))
|
|
1758
|
+
throw failure("RUNTIME_STORAGE_UPLOAD_NOT_FOUND", stage);
|
|
1759
|
+
return { data: join4(directory, id), meta: join4(directory, `${id}.json`) };
|
|
1760
|
+
}
|
|
1761
|
+
async function pending(id, stage) {
|
|
1762
|
+
const path = paths(id, stage).meta;
|
|
1763
|
+
let text;
|
|
1764
|
+
try {
|
|
1765
|
+
text = await readFile(path, "utf8");
|
|
1766
|
+
} catch (error) {
|
|
1767
|
+
if (filesystemErrorCode(error) === "ENOENT")
|
|
1768
|
+
throw notPending(stage);
|
|
1769
|
+
throw filesystemUploadIoFailure(error, stage, "none");
|
|
1770
|
+
}
|
|
1771
|
+
let value;
|
|
1772
|
+
try {
|
|
1773
|
+
const parsed = JSON.parse(text);
|
|
1774
|
+
if (!parsed || typeof parsed !== "object")
|
|
1775
|
+
throw new Error("Invalid pending metadata");
|
|
1776
|
+
value = parsed;
|
|
1777
|
+
if (typeof value.filename !== "string" || !value.filename || value.filename.length > 500 || typeof value.contentType !== "string" || !value.contentType || value.contentType.length > 200 || !Number.isSafeInteger(value.declaredSize) || value.declaredSize < 0 || !isUploadChecksumInputValid(value.checksum) || typeof value.expiresAt !== "string" || !Number.isFinite(Date.parse(value.expiresAt)))
|
|
1778
|
+
throw new Error("Invalid pending metadata");
|
|
1779
|
+
} catch {
|
|
1780
|
+
throw failure("RUNTIME_STORAGE_UPLOAD_STORAGE_UNAVAILABLE", stage, {
|
|
1781
|
+
dataImpact: "none",
|
|
1782
|
+
retryPrecondition: "Restore valid pending upload metadata through the trusted storage owner before retrying.",
|
|
1783
|
+
nextAction: "Preserve existing upload files and published objects. Have the trusted storage owner restore valid metadata from a verified backup; do not edit upload records or blindly replay the containing mutation."
|
|
1784
|
+
});
|
|
1785
|
+
}
|
|
1786
|
+
if (Date.parse(value.expiresAt) <= Date.now())
|
|
1787
|
+
throw failure("RUNTIME_STORAGE_UPLOAD_EXPIRED", stage);
|
|
1788
|
+
return value;
|
|
1789
|
+
}
|
|
1790
|
+
return {
|
|
1791
|
+
async createUploadGrant(value) {
|
|
1792
|
+
if (!value || typeof value.filename !== "string" || !value.filename || value.filename.length > 500 || typeof value.contentType !== "string" || !value.contentType || value.contentType.length > 200 || !Number.isSafeInteger(value.size) || value.size < 0 || value.size > input.maxFileSizeBytes || !isUploadChecksumInputValid(value.checksum))
|
|
1793
|
+
throw failure("RUNTIME_STORAGE_UPLOAD_INVALID", "grant");
|
|
1794
|
+
const uploadId = randomUUID4();
|
|
1795
|
+
const expiresAt = new Date(Date.now() + 15 * 60 * 1e3).toISOString();
|
|
1796
|
+
const meta = {
|
|
1797
|
+
filename: value.filename,
|
|
1798
|
+
contentType: value.contentType,
|
|
1799
|
+
declaredSize: value.size,
|
|
1800
|
+
...value.checksum ? { checksum: normalizeUploadChecksum(value.checksum) } : {},
|
|
1801
|
+
expiresAt
|
|
1802
|
+
};
|
|
1803
|
+
try {
|
|
1804
|
+
await mkdir2(directory, { recursive: true });
|
|
1805
|
+
await writeFile2(join4(directory, `${uploadId}.json`), JSON.stringify(meta));
|
|
1806
|
+
} catch (error) {
|
|
1807
|
+
throw filesystemUploadIoFailure(error, "grant", "unknown");
|
|
1808
|
+
}
|
|
1809
|
+
return {
|
|
1810
|
+
uploadId,
|
|
1811
|
+
url: `/api/storage/upload/${uploadId}`,
|
|
1812
|
+
method: "PUT",
|
|
1813
|
+
headers: { "Content-Type": value.contentType },
|
|
1814
|
+
expiresAt
|
|
1815
|
+
};
|
|
1816
|
+
},
|
|
1817
|
+
async receiveUpload(request, uploadId) {
|
|
1818
|
+
const raw = request.headers.get("content-length");
|
|
1819
|
+
if (raw === null)
|
|
1820
|
+
throw failure("RUNTIME_STORAGE_UPLOAD_LENGTH_REQUIRED", "receive");
|
|
1821
|
+
if (!/^(?:0|[1-9][0-9]*)$/u.test(raw) || !Number.isSafeInteger(Number(raw)))
|
|
1822
|
+
throw failure("RUNTIME_STORAGE_UPLOAD_INVALID", "receive");
|
|
1823
|
+
const max = Math.min(filesystemUploadApiLimit, input.maxFileSizeBytes);
|
|
1824
|
+
if (Number(raw) > max)
|
|
1825
|
+
throw failure("RUNTIME_STORAGE_UPLOAD_TOO_LARGE", "receive");
|
|
1826
|
+
const meta = await pending(uploadId, "receive");
|
|
1827
|
+
if (request.headers.get("content-type") !== meta.contentType)
|
|
1828
|
+
throw failure("RUNTIME_STORAGE_UPLOAD_INVALID", "receive");
|
|
1829
|
+
const target = paths(uploadId, "receive").data;
|
|
1830
|
+
const temporary = `${target}.recv-${randomUUID4()}`;
|
|
1831
|
+
let file;
|
|
1832
|
+
let size = 0;
|
|
1833
|
+
try {
|
|
1834
|
+
file = await open4(temporary, "wx");
|
|
1835
|
+
const reader = request.body?.getReader();
|
|
1836
|
+
if (reader) {
|
|
1837
|
+
try {
|
|
1838
|
+
while (true) {
|
|
1839
|
+
const chunk = await reader.read();
|
|
1840
|
+
if (chunk.done)
|
|
1841
|
+
break;
|
|
1842
|
+
size += chunk.value.byteLength;
|
|
1843
|
+
if (size > max || size > Number(raw))
|
|
1844
|
+
throw failure("RUNTIME_STORAGE_UPLOAD_TOO_LARGE", "receive");
|
|
1845
|
+
await file.writeFile(chunk.value);
|
|
1846
|
+
}
|
|
1847
|
+
} finally {
|
|
1848
|
+
reader.releaseLock();
|
|
1849
|
+
}
|
|
1850
|
+
}
|
|
1851
|
+
if (size !== Number(raw))
|
|
1852
|
+
throw failure("RUNTIME_STORAGE_UPLOAD_INVALID", "receive");
|
|
1853
|
+
await file.close();
|
|
1854
|
+
await rename(temporary, target);
|
|
1855
|
+
} catch (error) {
|
|
1856
|
+
await file?.close().catch(() => {
|
|
1857
|
+
});
|
|
1858
|
+
await rm(temporary, { force: true }).catch(() => {
|
|
1859
|
+
});
|
|
1860
|
+
throw filesystemUploadIoFailure(error, "receive", "unknown");
|
|
1861
|
+
}
|
|
1862
|
+
return Response.json({ ok: true }, { headers: { "cache-control": "no-store" } });
|
|
1863
|
+
},
|
|
1864
|
+
async finalizeUpload(value) {
|
|
1865
|
+
if (!value || !isUploadChecksumInputValid(value.checksum) || value.visibility !== void 0 && value.visibility !== "private" && value.visibility !== "public")
|
|
1866
|
+
throw failure("RUNTIME_STORAGE_UPLOAD_INVALID", "finalize");
|
|
1867
|
+
const meta = await pending(value.uploadId, "finalize");
|
|
1868
|
+
const path = paths(value.uploadId, "finalize");
|
|
1869
|
+
let bytes;
|
|
1870
|
+
try {
|
|
1871
|
+
bytes = await readFile(path.data);
|
|
1872
|
+
} catch (error) {
|
|
1873
|
+
if (filesystemErrorCode(error) === "ENOENT")
|
|
1874
|
+
throw failure("RUNTIME_STORAGE_UPLOAD_CONFLICT", "finalize", {
|
|
1875
|
+
retryPrecondition: "Verify that the original PUT completed and inspect any prior finalization before retrying.",
|
|
1876
|
+
nextAction: "Inspect the containing application's operation status and the original PUT outcome. Do not repeat finalize or create replacement work until any previous publication outcome is known."
|
|
1877
|
+
});
|
|
1878
|
+
throw filesystemUploadIoFailure(error, "finalize", "none");
|
|
1879
|
+
}
|
|
1880
|
+
const checksum = normalizeUploadChecksum(value.checksum) ?? meta.checksum;
|
|
1881
|
+
if (bytes.length !== meta.declaredSize || bytes.length > input.maxFileSizeBytes || checksum && createHash3("sha256").update(bytes).digest("hex") !== checksum)
|
|
1882
|
+
throw failure("RUNTIME_STORAGE_UPLOAD_INVALID", "finalize");
|
|
1883
|
+
const claimedMetadata = join4(directory, `${value.uploadId}.finalizing-${randomUUID4()}.json`);
|
|
1884
|
+
try {
|
|
1885
|
+
await rename(path.meta, claimedMetadata);
|
|
1886
|
+
} catch (error) {
|
|
1887
|
+
if (filesystemErrorCode(error) === "ENOENT")
|
|
1888
|
+
throw notPending("finalize");
|
|
1889
|
+
throw filesystemUploadIoFailure(error, "finalize", "unknown");
|
|
1890
|
+
}
|
|
1891
|
+
let assetId;
|
|
1892
|
+
try {
|
|
1893
|
+
assetId = await input.publish(bytes, meta.filename, meta.contentType, value.visibility ?? "private");
|
|
1894
|
+
} catch (error) {
|
|
1895
|
+
const diagnostic = filesystemUploadIoFailure(error, "finalize", "unknown").diagnostic;
|
|
1896
|
+
throw new RuntimeDiagnosticError({
|
|
1897
|
+
...diagnostic,
|
|
1898
|
+
retryable: false,
|
|
1899
|
+
retryPrecondition: "This upload ID was consumed before publication. Verify the containing operation's outcome; this ID cannot be finalized again.",
|
|
1900
|
+
nextAction: `${consumedAction} Provider recovery guidance: ${diagnostic.nextAction}`
|
|
1901
|
+
});
|
|
1902
|
+
}
|
|
1903
|
+
try {
|
|
1904
|
+
await rm(path.data, { force: true });
|
|
1905
|
+
await rm(claimedMetadata, { force: true });
|
|
1906
|
+
} catch (error) {
|
|
1907
|
+
throw filesystemUploadIoFailure(error, "finalize", "committed", assetId);
|
|
1908
|
+
}
|
|
1909
|
+
return { assetId };
|
|
1910
|
+
},
|
|
1911
|
+
async abortUpload(uploadId) {
|
|
1912
|
+
const path = paths(uploadId, "abort");
|
|
1913
|
+
try {
|
|
1914
|
+
await rm(path.data, { force: true });
|
|
1915
|
+
await rm(path.meta, { force: true });
|
|
1916
|
+
} catch (error) {
|
|
1917
|
+
throw filesystemUploadIoFailure(error, "abort", "unknown");
|
|
1918
|
+
}
|
|
1919
|
+
}
|
|
1920
|
+
};
|
|
1921
|
+
}
|
|
1922
|
+
|
|
1923
|
+
// ../runtime/dist/adapters/storage/filesystem-startup-resources.js
|
|
1924
|
+
function createFilesystemStartupResources() {
|
|
1925
|
+
const resources = [];
|
|
1926
|
+
let disposal;
|
|
1927
|
+
return Object.freeze({
|
|
1928
|
+
own(resource) {
|
|
1929
|
+
if (disposal)
|
|
1930
|
+
throw new Error("Filesystem startup resource ownership has already closed");
|
|
1931
|
+
resources.push(resource);
|
|
1932
|
+
return resource;
|
|
1933
|
+
},
|
|
1934
|
+
dispose() {
|
|
1935
|
+
if (!disposal) {
|
|
1936
|
+
disposal = (async () => {
|
|
1937
|
+
let firstFailure;
|
|
1938
|
+
for (const resource of resources.splice(0).reverse()) {
|
|
1939
|
+
try {
|
|
1940
|
+
await resource.dispose();
|
|
1941
|
+
} catch (error) {
|
|
1942
|
+
firstFailure ??= error;
|
|
1943
|
+
}
|
|
1944
|
+
}
|
|
1945
|
+
if (firstFailure)
|
|
1946
|
+
throw firstFailure;
|
|
1947
|
+
})();
|
|
1948
|
+
}
|
|
1949
|
+
return disposal;
|
|
1950
|
+
}
|
|
1951
|
+
});
|
|
1952
|
+
}
|
|
1953
|
+
|
|
1954
|
+
// ../runtime/dist/adapters/storage/filesystem-admission.js
|
|
1955
|
+
function admitFilesystemStorageConfiguration(input) {
|
|
1956
|
+
if (!input || typeof input !== "object" || Array.isArray(input))
|
|
1957
|
+
throw runtimeStartupError("RUNTIME_STORAGE_CONFIG_INVALID", "Supply a trusted filesystem storage configuration before restarting.", "none", "storage");
|
|
1958
|
+
const directory = input.directory;
|
|
1959
|
+
if (typeof directory !== "string" || directory.length === 0)
|
|
1960
|
+
throw runtimeStartupError("RUNTIME_STORAGE_CONFIG_INVALID", "Set a non-empty trusted filesystem storage directory before restarting.", "none", "storage");
|
|
1961
|
+
const imageSelection = input.image;
|
|
1962
|
+
const uploadLimitSelection = Object.freeze({
|
|
1963
|
+
maxFileSizeBytes: input.maxFileSizeBytes,
|
|
1964
|
+
maxMultipartBodyBytes: input.maxMultipartBodyBytes,
|
|
1965
|
+
maxFilesPerRequest: input.maxFilesPerRequest
|
|
1966
|
+
});
|
|
1967
|
+
const bindingSelection = input.binding;
|
|
1968
|
+
const imagePolicy = resolveRuntimeFilesystemImagePolicy(imageSelection);
|
|
1969
|
+
const limits = resolveRuntimeUploadLimits(uploadLimitSelection);
|
|
1970
|
+
const binding = bindingSelection === void 0 ? void 0 : snapshotRuntimeBinding(bindingSelection);
|
|
1971
|
+
return Object.freeze({
|
|
1972
|
+
directory,
|
|
1973
|
+
imagePolicy,
|
|
1974
|
+
limits,
|
|
1975
|
+
...binding ? { binding } : {}
|
|
1976
|
+
});
|
|
1977
|
+
}
|
|
1978
|
+
|
|
1979
|
+
// ../runtime/dist/adapters/storage/filesystem-implementation.js
|
|
1980
|
+
function publicMetadata(meta) {
|
|
1981
|
+
return { id: meta.id, name: meta.name, size: meta.size, type: meta.type, visibility: meta.visibility };
|
|
1982
|
+
}
|
|
1983
|
+
function insertionTime(meta) {
|
|
1984
|
+
return Number.isFinite(meta.createdAt) ? meta.createdAt : 0;
|
|
1985
|
+
}
|
|
1986
|
+
function compareMetadata(a, b) {
|
|
1987
|
+
return insertionTime(a) - insertionTime(b) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
|
|
1988
|
+
}
|
|
1989
|
+
function sameMetadataVersion(a, b) {
|
|
1990
|
+
return a.format === b.format && JSON.stringify(a.raw) === JSON.stringify(b.raw);
|
|
1991
|
+
}
|
|
1992
|
+
function options(input) {
|
|
1993
|
+
return typeof input === "string" ? { filename: input, visibility: "private" } : { filename: input?.filename, visibility: input?.visibility ?? "private" };
|
|
1994
|
+
}
|
|
1995
|
+
function rootBindingFailure() {
|
|
1996
|
+
return new RuntimeDiagnosticError({
|
|
1997
|
+
code: "RUNTIME_STORAGE_ROOT_APP_MISMATCH",
|
|
1998
|
+
stage: "startup",
|
|
1999
|
+
capability: "storage",
|
|
2000
|
+
servingStarted: false,
|
|
2001
|
+
dataImpact: "none",
|
|
2002
|
+
retryable: false,
|
|
2003
|
+
retryPrecondition: "Use a storage directory bound to this trusted app and verify its owner marker before restarting.",
|
|
2004
|
+
nextAction: "Configure a dedicated storage root for this app. Do not edit the owner marker or copy private data between app roots.",
|
|
2005
|
+
correlationId: randomUUID5()
|
|
2006
|
+
});
|
|
2007
|
+
}
|
|
2008
|
+
function rootBindingUnavailable() {
|
|
2009
|
+
return new RuntimeDiagnosticError({
|
|
2010
|
+
code: "RUNTIME_STORAGE_ROOT_BINDING_UNAVAILABLE",
|
|
2011
|
+
stage: "startup",
|
|
2012
|
+
capability: "storage",
|
|
2013
|
+
servingStarted: false,
|
|
2014
|
+
dataImpact: "unknown",
|
|
2015
|
+
retryable: false,
|
|
2016
|
+
retryPrecondition: "Restore safe access to the configured filesystem root and restart after inspecting any owner-marker write.",
|
|
2017
|
+
nextAction: "Check the trusted storage directory and its permissions; preserve existing files and do not replay mutations.",
|
|
2018
|
+
correlationId: randomUUID5()
|
|
2019
|
+
});
|
|
2020
|
+
}
|
|
2021
|
+
async function bindRootToApp(boundary, binding) {
|
|
2022
|
+
const marker = boundary.ownerMarker;
|
|
2023
|
+
if (!binding) {
|
|
2024
|
+
try {
|
|
2025
|
+
const size = await boundary.fileSize(marker);
|
|
2026
|
+
if (size !== null)
|
|
2027
|
+
throw rootBindingFailure();
|
|
2028
|
+
return;
|
|
2029
|
+
} catch (error) {
|
|
2030
|
+
if (runtimeDiagnostic(error))
|
|
2031
|
+
throw error;
|
|
2032
|
+
if (filesystemErrorCode(error) !== "ENOENT")
|
|
2033
|
+
throw rootBindingUnavailable();
|
|
2034
|
+
return;
|
|
2035
|
+
}
|
|
2036
|
+
}
|
|
2037
|
+
boundary.assertRoot();
|
|
2038
|
+
let handle;
|
|
2039
|
+
try {
|
|
2040
|
+
handle = await open5(marker, constants5.O_WRONLY | constants5.O_CREAT | constants5.O_EXCL | constants5.O_NOFOLLOW, 384);
|
|
2041
|
+
await handle.writeFile(JSON.stringify({ version: 1, appId: binding.appId }));
|
|
2042
|
+
await handle.sync();
|
|
2043
|
+
await handle.close();
|
|
2044
|
+
return;
|
|
2045
|
+
} catch (error) {
|
|
2046
|
+
await handle?.close().catch(() => {
|
|
2047
|
+
});
|
|
2048
|
+
if (filesystemErrorCode(error) !== "EEXIST") {
|
|
2049
|
+
if (runtimeDiagnostic(error))
|
|
2050
|
+
throw error;
|
|
2051
|
+
throw rootBindingUnavailable();
|
|
2052
|
+
}
|
|
2053
|
+
}
|
|
2054
|
+
try {
|
|
2055
|
+
const value = JSON.parse((await boundary.read(marker, 4096)).toString("utf8"));
|
|
2056
|
+
if (!value || typeof value !== "object" || value.version !== 1 || value.appId !== binding.appId)
|
|
2057
|
+
throw rootBindingFailure();
|
|
2058
|
+
} catch (error) {
|
|
2059
|
+
if (runtimeDiagnostic(error))
|
|
2060
|
+
throw error;
|
|
2061
|
+
throw rootBindingFailure();
|
|
2062
|
+
}
|
|
2063
|
+
}
|
|
2064
|
+
function unavailableReadGrant(keyUnavailable = false) {
|
|
2065
|
+
return new RuntimeDiagnosticError({
|
|
2066
|
+
code: keyUnavailable ? "RUNTIME_STORAGE_READ_GRANT_KEY_UNAVAILABLE" : "RUNTIME_STORAGE_DELIVERY_UNAVAILABLE",
|
|
2067
|
+
stage: "request",
|
|
2068
|
+
capability: "storage",
|
|
2069
|
+
servingStarted: "unchanged",
|
|
2070
|
+
dataImpact: "none",
|
|
2071
|
+
retryable: false,
|
|
2072
|
+
retryPrecondition: keyUnavailable ? "Restore access to the existing storage signing key and restart the Runtime before requesting private read grants." : "Select a bound filesystem storage adapter with signed-read support after verifying its trusted configuration.",
|
|
2073
|
+
nextAction: keyUnavailable ? "Preserve the existing storage and signing key. Check the configured storage directory and key access, restore the original key from backup if damaged, then restart. Do not replace or regenerate the key." : "Bind the selected filesystem storage root to the trusted Runtime application before requesting a signed read grant."
|
|
2074
|
+
});
|
|
2075
|
+
}
|
|
2076
|
+
async function createFilesystemStorageInternal(input, dependencies = {}) {
|
|
2077
|
+
const admitted = admitFilesystemStorageConfiguration(input);
|
|
2078
|
+
await mkdir3(admitted.directory, { recursive: true, mode: 448 });
|
|
2079
|
+
const boundary = createFilesystemBoundary(admitted.directory);
|
|
2080
|
+
const startupResources = createFilesystemStartupResources();
|
|
2081
|
+
try {
|
|
2082
|
+
return await createFilesystemStorageReady(admitted, dependencies, boundary, startupResources);
|
|
2083
|
+
} catch (error) {
|
|
2084
|
+
await startupResources.dispose().catch(() => {
|
|
2085
|
+
});
|
|
2086
|
+
throw error;
|
|
2087
|
+
}
|
|
2088
|
+
}
|
|
2089
|
+
async function createFilesystemStorageReady(admitted, dependencies, boundary, startupResources) {
|
|
2090
|
+
const { imagePolicy, limits, binding } = admitted;
|
|
2091
|
+
await bindRootToApp(boundary, binding);
|
|
2092
|
+
let readGrantKey;
|
|
2093
|
+
if (binding) {
|
|
2094
|
+
try {
|
|
2095
|
+
readGrantKey = process.platform === "win32" ? await loadPortableFilesystemReadGrantKey(boundary.root) : await loadOrCreateFilesystemReadGrantKey(boundary.root);
|
|
2096
|
+
} catch {
|
|
2097
|
+
}
|
|
2098
|
+
}
|
|
2099
|
+
const readGrantSigner = binding && readGrantKey ? createRuntimeReadGrantSigner({ key: readGrantKey, root: boundary.root, appId: binding.appId }) : void 0;
|
|
2100
|
+
if (readGrantSigner)
|
|
2101
|
+
startupResources.own(readGrantSigner);
|
|
2102
|
+
const imageTransforms = imagePolicy.enabled ? createFilesystemImageTransforms({
|
|
2103
|
+
root: boundary.root,
|
|
2104
|
+
rootIdentity: boundary.identity,
|
|
2105
|
+
assertRoot: boundary.assertRoot,
|
|
2106
|
+
appId: binding?.appId ?? "unbound-filesystem",
|
|
2107
|
+
maxFileSizeBytes: limits.maxFileSizeBytes
|
|
2108
|
+
}, { loadEncoder: dependencies.loadImageEncoder }) : void 0;
|
|
2109
|
+
if (imageTransforms)
|
|
2110
|
+
startupResources.own(imageTransforms);
|
|
2111
|
+
await imageTransforms?.initialize();
|
|
2112
|
+
const catalog = createHash4("sha256").update(`filesystem:${boundary.root}`).digest("hex");
|
|
2113
|
+
async function readRawMetadata(path, limit = filesystemMetadataMaxSerializedBytes) {
|
|
2114
|
+
let bytes;
|
|
2115
|
+
try {
|
|
2116
|
+
bytes = await boundary.read(path, limit);
|
|
2117
|
+
} catch (error) {
|
|
2118
|
+
if (filesystemErrorCode(error) === "ENOENT")
|
|
2119
|
+
return null;
|
|
2120
|
+
if (runtimeDiagnostic(error)?.code === "RUNTIME_STORAGE_READ_LIMIT_EXCEEDED")
|
|
2121
|
+
throw filesystemMetadataInvalid();
|
|
2122
|
+
throw error;
|
|
2123
|
+
}
|
|
2124
|
+
const text = bytes.toString("utf8");
|
|
2125
|
+
if (!Buffer.from(text, "utf8").equals(bytes))
|
|
2126
|
+
throw filesystemMetadataInvalid();
|
|
2127
|
+
let value;
|
|
2128
|
+
try {
|
|
2129
|
+
value = JSON.parse(text);
|
|
2130
|
+
} catch {
|
|
2131
|
+
throw filesystemMetadataInvalid();
|
|
2132
|
+
}
|
|
2133
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
2134
|
+
throw filesystemMetadataInvalid();
|
|
2135
|
+
return value;
|
|
2136
|
+
}
|
|
2137
|
+
function metadataRecord(raw, id, format, path) {
|
|
2138
|
+
const visibility = raw.visibility === void 0 ? "private" : raw.visibility;
|
|
2139
|
+
if ((format === "runtime" ? raw.id !== id : raw.id !== void 0) || typeof raw.name !== "string" || typeof raw.type !== "string" || typeof raw.size !== "number" || !Number.isSafeInteger(raw.size) || raw.size < 0 || visibility !== "private" && visibility !== "public" || format === "runtime" && raw.createdAt !== void 0 && (typeof raw.createdAt !== "number" || !Number.isFinite(raw.createdAt)))
|
|
2140
|
+
throw filesystemMetadataInvalid();
|
|
2141
|
+
const metadata = {
|
|
2142
|
+
...raw,
|
|
2143
|
+
id,
|
|
2144
|
+
name: raw.name,
|
|
2145
|
+
type: raw.type,
|
|
2146
|
+
size: raw.size,
|
|
2147
|
+
visibility
|
|
2148
|
+
};
|
|
2149
|
+
if (format === "server")
|
|
2150
|
+
delete metadata.createdAt;
|
|
2151
|
+
return { metadata, format, path, raw };
|
|
2152
|
+
}
|
|
2153
|
+
async function resolveMetadata(id, limit = 64 * 1024) {
|
|
2154
|
+
const paths = boundary.paths(id);
|
|
2155
|
+
const [dataSize, runtimeRaw, serverRaw] = await Promise.all([
|
|
2156
|
+
boundary.fileSize(paths.data),
|
|
2157
|
+
readRawMetadata(paths.metadata, limit),
|
|
2158
|
+
readRawMetadata(paths.legacyMetadata, limit)
|
|
2159
|
+
]);
|
|
2160
|
+
if (runtimeRaw && serverRaw)
|
|
2161
|
+
throw filesystemMetadataInvalid();
|
|
2162
|
+
if (dataSize === null && !runtimeRaw && !serverRaw)
|
|
2163
|
+
return null;
|
|
2164
|
+
if (dataSize === null || !runtimeRaw && !serverRaw)
|
|
2165
|
+
throw filesystemMetadataInvalid();
|
|
2166
|
+
const resolved = runtimeRaw ? metadataRecord(runtimeRaw, id, "runtime", paths.metadata) : metadataRecord(serverRaw, id, "server", paths.legacyMetadata);
|
|
2167
|
+
if (dataSize !== resolved.metadata.size)
|
|
2168
|
+
throw filesystemMetadataInvalid();
|
|
2169
|
+
return resolved;
|
|
2170
|
+
}
|
|
2171
|
+
const objectFence = createFilesystemObjectFence();
|
|
2172
|
+
async function listObjectIds() {
|
|
2173
|
+
boundary.assertRoot();
|
|
2174
|
+
const entries = await filesystemCall(false, () => readdir2(boundary.root));
|
|
2175
|
+
const ids = /* @__PURE__ */ new Set();
|
|
2176
|
+
for (const entry of entries) {
|
|
2177
|
+
if (entry === filesystemRootOwnerFilename || entry.startsWith(`${filesystemReadGrantKeyFilename}.tmp-`))
|
|
2178
|
+
continue;
|
|
2179
|
+
if (entry === filesystemReadGrantKeyFilename) {
|
|
2180
|
+
continue;
|
|
2181
|
+
}
|
|
2182
|
+
if (boundary.isKnownInternalDirectory(entry))
|
|
2183
|
+
continue;
|
|
2184
|
+
const id = entry.endsWith(filesystemMetadataSuffix) ? entry.slice(0, -filesystemMetadataSuffix.length) : entry.endsWith(filesystemLegacyMetadataSuffix) ? entry.slice(0, -filesystemLegacyMetadataSuffix.length) : entry;
|
|
2185
|
+
if (!objectFence.isQuarantined(id))
|
|
2186
|
+
ids.add(id);
|
|
2187
|
+
}
|
|
2188
|
+
return [...ids];
|
|
2189
|
+
}
|
|
2190
|
+
const put = async (data, name, type, visibility, source, owner, guard = () => {
|
|
2191
|
+
}) => {
|
|
2192
|
+
guard();
|
|
2193
|
+
assertRuntimeFileSize(data.length, limits.maxFileSizeBytes);
|
|
2194
|
+
const id = randomUUID5();
|
|
2195
|
+
const meta = {
|
|
2196
|
+
createdAt: Date.now(),
|
|
2197
|
+
id,
|
|
2198
|
+
name: name ?? `${id}.bin`,
|
|
2199
|
+
size: data.length,
|
|
2200
|
+
type,
|
|
2201
|
+
visibility: visibility === "public" ? "public" : "private",
|
|
2202
|
+
...source ? { source } : {},
|
|
2203
|
+
...owner && { [documentOwnerKey]: owner }
|
|
2204
|
+
};
|
|
2205
|
+
if (typeof meta.name !== "string" || typeof meta.type !== "string" || meta.name.length > filesystemMetadataMaxSerializedBytes || meta.type.length > filesystemMetadataMaxSerializedBytes)
|
|
2206
|
+
throw filesystemMetadataInputInvalid();
|
|
2207
|
+
const serializedMetadata = JSON.stringify(meta);
|
|
2208
|
+
if (Buffer.byteLength(serializedMetadata, "utf8") > filesystemMetadataMaxSerializedBytes)
|
|
2209
|
+
throw filesystemMetadataInputInvalid();
|
|
2210
|
+
return await objectFence.run(id, async () => {
|
|
2211
|
+
guard();
|
|
2212
|
+
const paths = boundary.paths(id);
|
|
2213
|
+
await boundary.write(paths.data, data, true);
|
|
2214
|
+
guard();
|
|
2215
|
+
await boundary.write(paths.metadata, serializedMetadata, true);
|
|
2216
|
+
guard();
|
|
2217
|
+
return meta;
|
|
2218
|
+
});
|
|
2219
|
+
};
|
|
2220
|
+
const createGrant = async (id, grantInput, principal) => {
|
|
2221
|
+
boundary.paths(id);
|
|
2222
|
+
if (!binding || !readGrantSigner)
|
|
2223
|
+
throw unavailableReadGrant(Boolean(binding));
|
|
2224
|
+
const metadata = await resolveMetadata(id);
|
|
2225
|
+
if (!metadata)
|
|
2226
|
+
throw filesystemObjectNotFound();
|
|
2227
|
+
return readGrantSigner.sign(id, grantInput, principal);
|
|
2228
|
+
};
|
|
2229
|
+
async function publish(data, filename, type, visibility, owner, guard = () => {
|
|
2230
|
+
}) {
|
|
2231
|
+
return (await put(data, filename, type, visibility, void 0, owner, guard)).id;
|
|
2232
|
+
}
|
|
2233
|
+
const storage = {
|
|
2234
|
+
async store(file, filenameOrOptions) {
|
|
2235
|
+
assertRuntimeFileSize(file.size, limits.maxFileSizeBytes);
|
|
2236
|
+
const data = Buffer.from(await file.arrayBuffer());
|
|
2237
|
+
assertRuntimeFileSize(data.length, limits.maxFileSizeBytes);
|
|
2238
|
+
const value = options(filenameOrOptions);
|
|
2239
|
+
return (await put(data, value.filename || (file instanceof File ? file.name ?? "" : void 0), file.type || "application/octet-stream", value.visibility)).id;
|
|
2240
|
+
},
|
|
2241
|
+
async storeBuffer(buffer, filename, type = "application/octet-stream", value) {
|
|
2242
|
+
return (await put(buffer, filename, type, value?.visibility ?? "private")).id;
|
|
2243
|
+
},
|
|
2244
|
+
async get(id) {
|
|
2245
|
+
objectFence.assertAvailable(id);
|
|
2246
|
+
const paths = boundary.paths(id);
|
|
2247
|
+
const before = await resolveMetadata(id);
|
|
2248
|
+
if (!before)
|
|
2249
|
+
return null;
|
|
2250
|
+
const buffer = await boundary.read(paths.data, limits.maxFileSizeBytes);
|
|
2251
|
+
if (buffer.byteLength !== before.metadata.size)
|
|
2252
|
+
throw filesystemMetadataInvalid();
|
|
2253
|
+
const after = await resolveMetadata(id);
|
|
2254
|
+
if (!after || !sameMetadataVersion(before, after))
|
|
2255
|
+
throw filesystemMetadataInvalid();
|
|
2256
|
+
return { ...publicMetadata(before.metadata), buffer };
|
|
2257
|
+
},
|
|
2258
|
+
getUrl(id) {
|
|
2259
|
+
const data = boundary.paths(id).data;
|
|
2260
|
+
return binding ? `/api/storage/${encodeURIComponent(id)}` : pathToFileURL(data).href;
|
|
2261
|
+
},
|
|
2262
|
+
getPublicUrl(id) {
|
|
2263
|
+
const data = boundary.paths(id).data;
|
|
2264
|
+
return binding ? `/api/storage/${encodeURIComponent(id)}` : pathToFileURL(data).href;
|
|
2265
|
+
},
|
|
2266
|
+
async createReadGrant(id, grantInput) {
|
|
2267
|
+
objectFence.assertAvailable(id);
|
|
2268
|
+
return await createGrant(id, grantInput);
|
|
2269
|
+
},
|
|
2270
|
+
async getMeta(id) {
|
|
2271
|
+
objectFence.assertAvailable(id);
|
|
2272
|
+
const resolved = await resolveMetadata(id);
|
|
2273
|
+
return resolved && publicMetadata(resolved.metadata);
|
|
2274
|
+
},
|
|
2275
|
+
async setVisibility(id, visibility) {
|
|
2276
|
+
await objectFence.run(id, async () => {
|
|
2277
|
+
const currentVisibility = visibility;
|
|
2278
|
+
if (currentVisibility !== "private" && currentVisibility !== "public")
|
|
2279
|
+
throw filesystemStorageInputInvalid();
|
|
2280
|
+
const before = await resolveMetadata(id);
|
|
2281
|
+
if (!before)
|
|
2282
|
+
throw filesystemObjectNotFound();
|
|
2283
|
+
if (before.metadata.visibility === currentVisibility)
|
|
2284
|
+
return;
|
|
2285
|
+
let nextRaw = { ...before.raw, visibility: currentVisibility };
|
|
2286
|
+
let serialized = JSON.stringify(nextRaw);
|
|
2287
|
+
if (Buffer.byteLength(serialized, "utf8") > filesystemMetadataMaxSerializedBytes) {
|
|
2288
|
+
if (currentVisibility === "public")
|
|
2289
|
+
throw filesystemMetadataUpdateLimitExceeded();
|
|
2290
|
+
nextRaw = { ...before.raw };
|
|
2291
|
+
delete nextRaw.visibility;
|
|
2292
|
+
serialized = JSON.stringify(nextRaw);
|
|
2293
|
+
if (Buffer.byteLength(serialized, "utf8") > filesystemMetadataMaxSerializedBytes)
|
|
2294
|
+
throw filesystemMetadataUpdateLimitExceeded();
|
|
2295
|
+
}
|
|
2296
|
+
await filesystemMutationWrite(async () => {
|
|
2297
|
+
await boundary.write(before.path, serialized, false);
|
|
2298
|
+
const after = await resolveMetadata(id);
|
|
2299
|
+
if (!after || after.metadata.visibility !== currentVisibility || after.format !== before.format)
|
|
2300
|
+
throw filesystemMetadataInvalid();
|
|
2301
|
+
});
|
|
2302
|
+
});
|
|
2303
|
+
},
|
|
2304
|
+
async listMeta(inputOptions) {
|
|
2305
|
+
boundary.assertRoot();
|
|
2306
|
+
const all = await Promise.all((await listObjectIds()).map(async (id) => (await resolveMetadata(id))?.metadata ?? null));
|
|
2307
|
+
const { limit, order } = storageListOptions(inputOptions);
|
|
2308
|
+
const cursor = inputOptions?.cursor ? decodeStorageCursor(inputOptions.cursor, catalog, order) : null;
|
|
2309
|
+
if (cursor && (typeof cursor.id !== "string" || typeof cursor.time !== "number" || !Number.isFinite(cursor.time)))
|
|
2310
|
+
invalidStorageCursor();
|
|
2311
|
+
const position = cursor && { id: cursor.id, createdAt: cursor.time };
|
|
2312
|
+
const items = all.filter((value) => value !== null).filter((value) => !position || (order === "asc" ? compareMetadata(value, position) > 0 : compareMetadata(value, position) < 0)).sort(compareMetadata);
|
|
2313
|
+
if (order === "desc")
|
|
2314
|
+
items.reverse();
|
|
2315
|
+
const page = items.slice(0, limit);
|
|
2316
|
+
const last = page.at(-1);
|
|
2317
|
+
return {
|
|
2318
|
+
items: page.map(publicMetadata),
|
|
2319
|
+
nextCursor: items.length > limit && last ? encodeStorageCursor({ catalog, order, id: last.id, time: insertionTime(last) }) : null
|
|
2320
|
+
};
|
|
2321
|
+
},
|
|
2322
|
+
async delete(id) {
|
|
2323
|
+
await objectFence.run(id, async () => {
|
|
2324
|
+
const resolved = await resolveMetadata(id);
|
|
2325
|
+
if (!resolved)
|
|
2326
|
+
return;
|
|
2327
|
+
const paths = boundary.paths(id);
|
|
2328
|
+
await filesystemCall(true, () => rm2(paths.data, { force: true }));
|
|
2329
|
+
await filesystemCall(true, () => rm2(resolved.path, { force: true }));
|
|
2330
|
+
});
|
|
2331
|
+
}
|
|
2332
|
+
};
|
|
2333
|
+
const administration = createFilesystemAdministration({
|
|
2334
|
+
boundary,
|
|
2335
|
+
storage,
|
|
2336
|
+
limits,
|
|
2337
|
+
catalog,
|
|
2338
|
+
resolveMetadata: async (id, limit) => (await resolveMetadata(id, limit))?.metadata ?? null,
|
|
2339
|
+
listObjectIds,
|
|
2340
|
+
assertObjectAvailable: objectFence.assertAvailable,
|
|
2341
|
+
uploadReadGrants: {
|
|
2342
|
+
assertAvailable() {
|
|
2343
|
+
if (!binding || !readGrantSigner)
|
|
2344
|
+
throw unavailableReadGrant(Boolean(binding));
|
|
2345
|
+
},
|
|
2346
|
+
create: (id, disposition) => createGrant(id, { ttlSeconds: 300, disposition }),
|
|
2347
|
+
verify: (id, token) => !!readGrantSigner?.verify(id, token)
|
|
2348
|
+
},
|
|
2349
|
+
put
|
|
2350
|
+
});
|
|
2351
|
+
const uploadOwner = binding ? createPortableFilesystemUploads({
|
|
2352
|
+
root: boundary.root,
|
|
2353
|
+
maxFileSizeBytes: limits.maxFileSizeBytes,
|
|
2354
|
+
publish
|
|
2355
|
+
}) : void 0;
|
|
2356
|
+
Object.assign(storage, {
|
|
2357
|
+
createUploadGrant: uploadOwner?.createUploadGrant ?? (async () => {
|
|
2358
|
+
throw filesystemUploadFailure("RUNTIME_STORAGE_UPLOAD_STORAGE_UNAVAILABLE", "grant");
|
|
2359
|
+
}),
|
|
2360
|
+
finalizeUpload: uploadOwner?.finalizeUpload ?? (async () => {
|
|
2361
|
+
throw filesystemUploadFailure("RUNTIME_STORAGE_UPLOAD_STORAGE_UNAVAILABLE", "finalize");
|
|
2362
|
+
}),
|
|
2363
|
+
abortUpload: uploadOwner?.abortUpload ?? (async () => {
|
|
2364
|
+
throw filesystemUploadFailure("RUNTIME_STORAGE_UPLOAD_STORAGE_UNAVAILABLE", "abort");
|
|
2365
|
+
})
|
|
2366
|
+
});
|
|
2367
|
+
if (!binding)
|
|
2368
|
+
return {
|
|
2369
|
+
storage,
|
|
2370
|
+
administration,
|
|
2371
|
+
async dispose() {
|
|
2372
|
+
await startupResources.dispose();
|
|
2373
|
+
}
|
|
2374
|
+
};
|
|
2375
|
+
return {
|
|
2376
|
+
storage,
|
|
2377
|
+
administration,
|
|
2378
|
+
uploadReceiver: uploadOwner ? Object.freeze({ receiveUpload: uploadOwner.receiveUpload }) : void 0,
|
|
2379
|
+
createRequestStorage: (request, assert, assertGrantAdmission) => lendDocumentUploadStorage(storage, request, binding, () => assert(request), limits.maxFileSizeBytes, publish, assertGrantAdmission, (id, grantInput) => createGrant(id, grantInput, {
|
|
2380
|
+
identityId: request.identity?.id ?? null,
|
|
2381
|
+
...request.authentication.method === "session" && request.authentication.session ? { sessionId: request.authentication.session.id } : {},
|
|
2382
|
+
credentialStatus: request.authentication.credentialStatus ?? "unknown"
|
|
2383
|
+
})),
|
|
2384
|
+
createWorkflowStorage: (attempt, assert) => lendDocumentUploadStorage(storage, attempt, binding, () => assert(attempt), limits.maxFileSizeBytes, publish, void 0, (id, grantInput) => createGrant(id, grantInput)),
|
|
2385
|
+
async readDocument(scope, id, maxBytes) {
|
|
2386
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0 || maxBytes > 50 * 1024 * 1024)
|
|
2387
|
+
throw new DocumentConversionError("DOCUMENT_INPUT_INVALID", scope.correlationId);
|
|
2388
|
+
if (!documentUploadOwner(scope, binding))
|
|
2389
|
+
throw new DocumentConversionError("DOCUMENT_STORAGE_SCOPE_FORBIDDEN", scope.correlationId);
|
|
2390
|
+
const paths = boundary.paths(id);
|
|
2391
|
+
const resolved = await resolveMetadata(id);
|
|
2392
|
+
documentUploadOwner(scope, binding);
|
|
2393
|
+
if (!resolved)
|
|
2394
|
+
return null;
|
|
2395
|
+
const meta = resolved.metadata;
|
|
2396
|
+
assertDocumentUploadOwner(meta[documentOwnerKey], scope, binding);
|
|
2397
|
+
if (meta.size > maxBytes)
|
|
2398
|
+
throw new DocumentConversionError("DOCUMENT_SIZE_LIMIT_EXCEEDED", scope.correlationId);
|
|
2399
|
+
let buffer;
|
|
2400
|
+
try {
|
|
2401
|
+
buffer = await boundary.readBounded(paths.data, maxBytes);
|
|
2402
|
+
} catch (error) {
|
|
2403
|
+
documentUploadOwner(scope, binding);
|
|
2404
|
+
throw error;
|
|
2405
|
+
}
|
|
2406
|
+
assertDocumentUploadOwner(meta[documentOwnerKey], scope, binding);
|
|
2407
|
+
if (buffer.length !== meta.size)
|
|
2408
|
+
throw new DocumentConversionError("DOCUMENT_INPUT_INVALID", scope.correlationId);
|
|
2409
|
+
const current = await resolveMetadata(id);
|
|
2410
|
+
documentUploadOwner(scope, binding);
|
|
2411
|
+
if (!current || !sameMetadataVersion(resolved, current))
|
|
2412
|
+
throw new DocumentConversionError("DOCUMENT_INPUT_INVALID", scope.correlationId);
|
|
2413
|
+
return { ...publicMetadata(meta), buffer };
|
|
2414
|
+
},
|
|
2415
|
+
delivery: Object.freeze({
|
|
2416
|
+
async publicContent(request, id, principal, trackWork) {
|
|
2417
|
+
try {
|
|
2418
|
+
if (request.method !== "GET" && request.method !== "HEAD" || request.body !== null)
|
|
2419
|
+
throw publicStorageObjectNotFound();
|
|
2420
|
+
objectFence.assertAvailable(id);
|
|
2421
|
+
const values = new URL(request.url).searchParams.getAll("grant");
|
|
2422
|
+
const authorize = (metadata) => {
|
|
2423
|
+
if (metadata.visibility === "public")
|
|
2424
|
+
return void 0;
|
|
2425
|
+
return readGrantSigner?.verify(id, values.length === 1 ? values[0] : null, principal) ?? null;
|
|
2426
|
+
};
|
|
2427
|
+
const readAuthorized = async () => {
|
|
2428
|
+
const before = await resolveMetadata(id);
|
|
2429
|
+
if (!before || authorize(before.metadata) === null)
|
|
2430
|
+
throw publicStorageObjectNotFound();
|
|
2431
|
+
const bytes = await boundary.read(boundary.paths(id).data, limits.maxFileSizeBytes);
|
|
2432
|
+
if (bytes.byteLength !== before.metadata.size)
|
|
2433
|
+
throw publicStorageObjectNotFound();
|
|
2434
|
+
const after = await resolveMetadata(id);
|
|
2435
|
+
if (!after || !sameMetadataVersion(before, after) || authorize(after.metadata) === null)
|
|
2436
|
+
throw publicStorageObjectNotFound();
|
|
2437
|
+
return { version: after, bytes, disposition: authorize(after.metadata) };
|
|
2438
|
+
};
|
|
2439
|
+
const original = await readAuthorized();
|
|
2440
|
+
if (!imageTransforms)
|
|
2441
|
+
return formatStorageContentResponse(original.version.metadata, original.bytes, request, original.disposition ?? void 0);
|
|
2442
|
+
const selection = selectRuntimeImageTransform(request, original.version.metadata.type);
|
|
2443
|
+
if (selection.kind !== "transform")
|
|
2444
|
+
return formatStorageContentResponse(original.version.metadata, original.bytes, request, original.disposition ?? void 0, selection.varyAccept);
|
|
2445
|
+
const sourceDigest = createHash4("sha256").update(original.bytes).digest("hex");
|
|
2446
|
+
const transformed = await imageTransforms.render({
|
|
2447
|
+
objectId: id,
|
|
2448
|
+
source: original.bytes,
|
|
2449
|
+
sourceType: original.version.metadata.type,
|
|
2450
|
+
metadataVersion: JSON.stringify(original.version.raw),
|
|
2451
|
+
transform: selection.transform,
|
|
2452
|
+
isAutomaticWebp: selection.varyAccept,
|
|
2453
|
+
trackWork,
|
|
2454
|
+
signal: request.signal,
|
|
2455
|
+
sourceStillCurrent: async () => {
|
|
2456
|
+
try {
|
|
2457
|
+
const current2 = await readAuthorized();
|
|
2458
|
+
return sameMetadataVersion(original.version, current2.version) && createHash4("sha256").update(current2.bytes).digest("hex") === sourceDigest;
|
|
2459
|
+
} catch {
|
|
2460
|
+
return false;
|
|
2461
|
+
}
|
|
2462
|
+
}
|
|
2463
|
+
});
|
|
2464
|
+
const current = await readAuthorized();
|
|
2465
|
+
const unchanged = sameMetadataVersion(original.version, current.version) && createHash4("sha256").update(current.bytes).digest("hex") === sourceDigest;
|
|
2466
|
+
if (transformed && unchanged)
|
|
2467
|
+
return formatStorageContentResponse({
|
|
2468
|
+
...current.version.metadata,
|
|
2469
|
+
type: transformed.entry.type,
|
|
2470
|
+
size: transformed.entry.bytes.byteLength
|
|
2471
|
+
}, transformed.entry.bytes, request, current.disposition ?? void 0, selection.varyAccept);
|
|
2472
|
+
return formatStorageContentResponse(current.version.metadata, current.bytes, request, current.disposition ?? void 0, selection.varyAccept);
|
|
2473
|
+
} catch (error) {
|
|
2474
|
+
if (runtimeDiagnostic(error))
|
|
2475
|
+
return publicStorageObjectNotFoundResponse(request);
|
|
2476
|
+
throw error;
|
|
2477
|
+
}
|
|
2478
|
+
}
|
|
2479
|
+
}),
|
|
2480
|
+
async dispose() {
|
|
2481
|
+
await startupResources.dispose();
|
|
2482
|
+
}
|
|
2483
|
+
};
|
|
2484
|
+
}
|
|
2485
|
+
|
|
2486
|
+
// ../runtime/dist/adapters/storage/filesystem.js
|
|
2487
|
+
async function createFilesystemStorage(input) {
|
|
2488
|
+
return createFilesystemStorageInternal(input);
|
|
2489
|
+
}
|
|
2490
|
+
export {
|
|
2491
|
+
createFilesystemStorage
|
|
2492
|
+
};
|