sandcms 0.6.3 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -11
- package/dist/admin/Account.svelte +2 -0
- package/dist/admin/Admin.svelte +21 -6
- package/dist/admin/AssetAttachment.svelte +9 -6
- package/dist/admin/AssetAttachment.svelte.d.ts +3 -1
- package/dist/admin/BlueprintFields.svelte +0 -3
- package/dist/admin/BlueprintFields.svelte.d.ts +0 -1
- package/dist/admin/Editor.svelte +5 -10
- package/dist/admin/Fields.svelte +2 -8
- package/dist/admin/Fields.svelte.d.ts +0 -1
- package/dist/admin/Gallery.svelte +221 -80
- package/dist/admin/Gallery.svelte.d.ts +0 -1
- package/dist/admin/Inbox.svelte +3 -2
- package/dist/admin/LinkField.svelte +0 -3
- package/dist/admin/LinkField.svelte.d.ts +0 -1
- package/dist/admin/MediaLibrary.svelte +10 -7
- package/dist/admin/MediaPicker.svelte +43 -35
- package/dist/admin/MediaPicker.svelte.d.ts +0 -1
- package/dist/admin/Navigation.svelte +13 -2
- package/dist/admin/Pages.svelte +195 -0
- package/dist/admin/Pages.svelte.d.ts +7 -0
- package/dist/admin/Shell.svelte +27 -5
- package/dist/admin/SortableList.svelte +82 -61
- package/dist/admin/SortableList.svelte.d.ts +3 -1
- package/dist/admin/ThemePicker.svelte +72 -0
- package/dist/admin/ThemePicker.svelte.d.ts +18 -0
- package/dist/admin/UploadButton.svelte +2 -1
- package/dist/admin/UploadProgress.svelte +24 -0
- package/dist/admin/UploadProgress.svelte.d.ts +7 -0
- package/dist/admin/Users.svelte +8 -3
- package/dist/admin/client.d.ts +3 -670
- package/dist/admin/client.js +2 -1
- package/dist/admin/components/ui/alert/alert.svelte.d.ts +3 -13
- package/dist/admin/components/ui/attachment/attachment-media.svelte.d.ts +3 -13
- package/dist/admin/components/ui/attachment/attachment.svelte.d.ts +6 -26
- package/dist/admin/components/ui/badge/badge.svelte.d.ts +7 -25
- package/dist/admin/components/ui/button/button.svelte.d.ts +15 -53
- package/dist/admin/components/ui/toggle/toggle.svelte.d.ts +6 -26
- package/dist/admin/generated/admin.css +823 -115
- package/dist/admin/navigation.d.ts +9 -0
- package/dist/admin/navigation.js +20 -1
- package/dist/admin/theme-context.d.ts +7 -0
- package/dist/admin/theme-context.js +3 -0
- package/dist/admin/theme.d.ts +7 -0
- package/dist/admin/theme.js +14 -0
- package/dist/admin/types.d.ts +3 -1
- package/dist/admin/uploads.d.ts +8 -1
- package/dist/admin/uploads.js +94 -16
- package/dist/blueprints/files.js +1 -0
- package/dist/blueprints/labels.d.ts +6 -0
- package/dist/blueprints/labels.js +14 -0
- package/dist/blueprints/load.js +16 -2
- package/dist/blueprints/types.d.ts +4 -1
- package/dist/cli/admin.d.ts +39 -0
- package/dist/cli/admin.js +95 -0
- package/dist/cli/backup.js +4 -4
- package/dist/cli/doctor.d.ts +10 -1
- package/dist/cli/doctor.js +98 -33
- package/dist/cli/email-test.d.ts +3 -0
- package/dist/cli/email-test.js +20 -0
- package/dist/cli/files.d.ts +2 -6
- package/dist/cli/files.js +12 -2
- package/dist/cli/index.js +401 -95
- package/dist/cli/rebaseline.d.ts +10 -0
- package/dist/cli/rebaseline.js +117 -0
- package/dist/cli/scaffold.js +8 -8
- package/dist/cli/setup.js +16 -26
- package/dist/cli/upgrade.js +34 -7
- package/dist/env.d.ts +26 -2
- package/dist/env.js +48 -6
- package/dist/notification-fields.js +2 -1
- package/dist/server/admin-load.d.ts +85 -5
- package/dist/server/admin-load.js +26 -1
- package/dist/server/api-access.d.ts +4 -0
- package/dist/server/api-access.js +15 -2
- package/dist/server/api-keys.d.ts +96 -0
- package/dist/server/api-keys.js +115 -0
- package/dist/server/api-pagination.d.ts +3 -0
- package/dist/server/api.js +21 -63
- package/dist/server/auth.d.ts +10 -9
- package/dist/server/cms.d.ts +63 -21
- package/dist/server/cms.js +64 -7
- package/dist/server/db/auto-migrate.d.ts +0 -4
- package/dist/server/db/auto-migrate.js +12 -3
- package/dist/server/db/legacy.d.ts +13 -0
- package/dist/server/db/legacy.js +60 -0
- package/dist/server/db/migration-data.js +2 -34
- package/dist/server/db/migrations/{0000_foundation.sql → 0000_baseline.sql} +120 -4
- package/dist/server/db/migrations/meta/0000_snapshot.json +578 -3
- package/dist/server/db/migrations/meta/_journal.json +2 -58
- package/dist/server/db/schema.d.ts +119 -2
- package/dist/server/db/schema.js +23 -9
- package/dist/server/db/store.d.ts +25 -2
- package/dist/server/db/store.js +90 -26
- package/dist/server/forms.js +2 -1
- package/dist/server/hooks.js +155 -81
- package/dist/server/media/contracts.d.ts +115 -0
- package/dist/server/media/contracts.js +12 -0
- package/dist/server/media/deletions.d.ts +2 -1
- package/dist/server/media/deletions.js +3 -3
- package/dist/server/media/delivery.js +7 -11
- package/dist/server/media/processor-child.d.ts +2 -0
- package/dist/server/media/processor-child.js +236 -0
- package/dist/server/media/processor.d.ts +51 -0
- package/dist/server/media/processor.js +135 -0
- package/dist/server/media/render-math.d.ts +24 -0
- package/dist/server/media/render-math.js +50 -0
- package/dist/server/media/runner.d.ts +30 -1
- package/dist/server/media/runner.js +418 -165
- package/dist/server/media/service.d.ts +53 -11
- package/dist/server/media/service.js +307 -98
- package/dist/server/media/storage.d.ts +5 -0
- package/dist/server/media/storage.js +279 -0
- package/dist/server/media/upload-ticket.d.ts +12 -0
- package/dist/server/media/upload-ticket.js +35 -0
- package/dist/server/media/verify.d.ts +64 -0
- package/dist/server/media/verify.js +201 -0
- package/dist/server/platform/http.d.ts +27 -0
- package/dist/server/platform/http.js +77 -0
- package/dist/server/platform/index.d.ts +52 -0
- package/dist/server/platform/index.js +98 -0
- package/dist/server/platform/snapshots.d.ts +18 -0
- package/dist/server/platform/snapshots.js +110 -0
- package/dist/server/platform/volume.d.ts +20 -0
- package/dist/server/platform/volume.js +60 -0
- package/docs/acceptance.md +7 -5
- package/docs/api.md +56 -4
- package/docs/cloudflare.md +26 -152
- package/docs/content.md +20 -5
- package/docs/deployment.md +222 -57
- package/docs/email.md +6 -0
- package/docs/forms.md +2 -2
- package/docs/media.md +94 -21
- package/docs/package.md +21 -18
- package/docs/plans/0.7-self-hosted.md +264 -0
- package/docs/releases.md +37 -1
- package/docs/upgrades.md +72 -9
- package/package.json +37 -44
- package/templates/Dockerfile +32 -0
- package/templates/integration.ts +26 -5
- package/templates/openship.json +9 -0
- package/templates/railpack.json +1 -1
- package/templates/sandcms/blueprints/files/image.yaml +1 -1
- package/templates/sandcms/config.yaml +1 -1
- package/dist/cli/cloudflare.d.ts +0 -8
- package/dist/cli/cloudflare.js +0 -135
- package/dist/server/db/migrations/0001_independent_password_resets.sql +0 -3
- package/dist/server/db/migrations/0002_email_failure_reason.sql +0 -1
- package/dist/server/db/migrations/0003_direct_r2_uploads.sql +0 -10
- package/dist/server/db/migrations/0004_agent_api_keys.sql +0 -38
- package/dist/server/db/migrations/0005_api_retention_and_pagination.sql +0 -3
- package/dist/server/db/migrations/0006_durable_media_deletion.sql +0 -7
- package/dist/server/db/migrations/0007_content_and_job_indexes.sql +0 -2
- package/dist/server/db/migrations/0008_search_text_cache.sql +0 -45
- package/dist/server/db/migrations/meta/0001_snapshot.json +0 -1197
- package/dist/server/db/migrations/meta/0002_snapshot.json +0 -1204
- package/dist/server/db/migrations/meta/0003_snapshot.json +0 -1281
- package/dist/server/db/migrations/meta/0004_snapshot.json +0 -1546
- package/dist/server/db/migrations/meta/0005_snapshot.json +0 -1572
- package/dist/server/db/migrations/meta/0006_snapshot.json +0 -1627
- package/dist/server/db/migrations/meta/0007_snapshot.json +0 -1643
- package/dist/server/db/migrations/meta/0008_snapshot.json +0 -1711
- package/dist/worker/index.d.ts +0 -10
- package/dist/worker/index.js +0 -460
- package/dist/worker/local.d.ts +0 -5
- package/dist/worker/local.js +0 -57
- package/dist/worker/source.d.ts +0 -2
- package/dist/worker/source.js +0 -31
- package/dist/worker/uploads.d.ts +0 -22
- package/dist/worker/uploads.js +0 -48
- package/templates/sandcms/worker/index.ts +0 -1
- package/templates/sandcms/worker/local.ts +0 -1
- package/templates/sandcms/worker/wrangler.jsonc +0 -6
- /package/dist/{worker → server/media}/svg.d.ts +0 -0
- /package/dist/{worker → server/media}/svg.js +0 -0
package/dist/worker/index.d.ts
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import type { R2Bucket } from '@cloudflare/workers-types/index.ts';
|
|
2
|
-
import { type UploadSigningEnv } from './uploads.js';
|
|
3
|
-
export interface WorkerEnv extends UploadSigningEnv {
|
|
4
|
-
MEDIA: R2Bucket;
|
|
5
|
-
SANDCMS_WORKER_TOKEN: string;
|
|
6
|
-
}
|
|
7
|
-
declare const _default: {
|
|
8
|
-
fetch(request: Request, env: WorkerEnv): Promise<Response>;
|
|
9
|
-
};
|
|
10
|
-
export default _default;
|
package/dist/worker/index.js
DELETED
|
@@ -1,460 +0,0 @@
|
|
|
1
|
-
import { isFocusPoint } from '../blueprints/files.js';
|
|
2
|
-
import { sanitizeSvg, svgDimensions } from './svg.js';
|
|
3
|
-
import { sourceURL, validSource } from './source.js';
|
|
4
|
-
import { presignUpload, uploadInput } from './uploads.js';
|
|
5
|
-
const PROTOCOL = 6;
|
|
6
|
-
const json = (v, status = 200) => Response.json(v, { status, headers: { 'Cache-Control': 'private, no-store' } });
|
|
7
|
-
const idPattern = /^[a-f0-9-]{36}$/;
|
|
8
|
-
const variantPattern = /^([a-f0-9-]{36})\/([a-f0-9]{16})\/([a-z][a-z0-9_-]*)-(\d+)\.(webp|avif|jpeg|svg)$/;
|
|
9
|
-
const isDeleted = (env, id) => env.MEDIA.head('deleted/' + id);
|
|
10
|
-
async function putAsset(env, id, key, value, options) {
|
|
11
|
-
if (await isDeleted(env, id))
|
|
12
|
-
throw new Error('Asset has been deleted');
|
|
13
|
-
const stored = await env.MEDIA.put(key, value, options);
|
|
14
|
-
// A deletion may arrive while R2 is committing the write.
|
|
15
|
-
if (await isDeleted(env, id)) {
|
|
16
|
-
await env.MEDIA.delete(key);
|
|
17
|
-
throw new Error('Asset has been deleted');
|
|
18
|
-
}
|
|
19
|
-
return stored;
|
|
20
|
-
}
|
|
21
|
-
async function authenticated(request, env) {
|
|
22
|
-
if (!env.SANDCMS_WORKER_TOKEN || env.SANDCMS_WORKER_TOKEN.length < 32)
|
|
23
|
-
return false;
|
|
24
|
-
const got = request.headers.get('authorization') ?? '';
|
|
25
|
-
const a = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(got))), b = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(`Bearer ${env.SANDCMS_WORKER_TOKEN}`)));
|
|
26
|
-
let diff = 0;
|
|
27
|
-
for (let i = 0; i < a.length; i++)
|
|
28
|
-
diff |= a[i] ^ b[i];
|
|
29
|
-
return diff === 0;
|
|
30
|
-
}
|
|
31
|
-
async function boundedBody(request, limit) {
|
|
32
|
-
const reader = request.body?.getReader();
|
|
33
|
-
if (!reader)
|
|
34
|
-
throw new Error('Missing body');
|
|
35
|
-
let length = 0;
|
|
36
|
-
const chunks = [];
|
|
37
|
-
while (true) {
|
|
38
|
-
const { done, value } = await reader.read();
|
|
39
|
-
if (done)
|
|
40
|
-
break;
|
|
41
|
-
length += value.length;
|
|
42
|
-
if (length > limit) {
|
|
43
|
-
await reader.cancel();
|
|
44
|
-
throw new Error('Upload exceeds limit');
|
|
45
|
-
}
|
|
46
|
-
chunks.push(value);
|
|
47
|
-
}
|
|
48
|
-
const data = new Uint8Array(length);
|
|
49
|
-
let offset = 0;
|
|
50
|
-
for (const chunk of chunks) {
|
|
51
|
-
data.set(chunk, offset);
|
|
52
|
-
offset += chunk.length;
|
|
53
|
-
}
|
|
54
|
-
return data;
|
|
55
|
-
}
|
|
56
|
-
// Both inspection and encoding use remote transformations, which accept large originals.
|
|
57
|
-
async function transform(source, image, mime) {
|
|
58
|
-
let output;
|
|
59
|
-
try {
|
|
60
|
-
const options = {
|
|
61
|
-
redirect: 'manual',
|
|
62
|
-
cf: { image }
|
|
63
|
-
};
|
|
64
|
-
output = await fetch(source, options);
|
|
65
|
-
}
|
|
66
|
-
catch {
|
|
67
|
-
// Fetch errors can include the signed URL; keep capabilities out of job errors.
|
|
68
|
-
throw new Error('Remote image transformation request failed');
|
|
69
|
-
}
|
|
70
|
-
let error;
|
|
71
|
-
if (!output.ok)
|
|
72
|
-
error = `Remote image transformation failed (${output.status})`;
|
|
73
|
-
else if (output.headers.get('content-type')?.split(';')[0] !== mime)
|
|
74
|
-
error = 'Remote image transformation returned an unexpected format';
|
|
75
|
-
// JSON inspection is verified by MIME type and schema; local emulation omits cf-resized.
|
|
76
|
-
else if ((mime !== 'application/json' && !output.headers.has('cf-resized')) ||
|
|
77
|
-
/err=/i.test(output.headers.get('cf-resized') ?? ''))
|
|
78
|
-
error = 'Remote image transformation was not applied';
|
|
79
|
-
if (error) {
|
|
80
|
-
await output.body?.cancel();
|
|
81
|
-
throw new Error(error);
|
|
82
|
-
}
|
|
83
|
-
return output;
|
|
84
|
-
}
|
|
85
|
-
function dimensions(width, height) {
|
|
86
|
-
if (typeof width !== 'number' ||
|
|
87
|
-
typeof height !== 'number' ||
|
|
88
|
-
!Number.isSafeInteger(width) ||
|
|
89
|
-
!Number.isSafeInteger(height) ||
|
|
90
|
-
width < 1 ||
|
|
91
|
-
height < 1 ||
|
|
92
|
-
width * height > 100_000_000)
|
|
93
|
-
throw new Error('Image must be at most 100 megapixels');
|
|
94
|
-
return { width, height };
|
|
95
|
-
}
|
|
96
|
-
async function inspect(source) {
|
|
97
|
-
const output = await transform(source, { format: 'json', anim: false }, 'application/json');
|
|
98
|
-
const bytes = await boundedBody(output, 4096);
|
|
99
|
-
let info;
|
|
100
|
-
try {
|
|
101
|
-
info = JSON.parse(new TextDecoder().decode(bytes));
|
|
102
|
-
}
|
|
103
|
-
catch {
|
|
104
|
-
throw new Error('Invalid remote image metadata');
|
|
105
|
-
}
|
|
106
|
-
// No resize is requested: top-level dimensions include EXIF orientation.
|
|
107
|
-
dimensions(info?.original?.width, info?.original?.height);
|
|
108
|
-
return dimensions(info?.width, info?.height);
|
|
109
|
-
}
|
|
110
|
-
// Workers allow six concurrent connections; each variant needs R2 reads/writes plus a transform.
|
|
111
|
-
const maxBatch = 32, batchConcurrency = 4;
|
|
112
|
-
const validSpec = (spec) => !!spec &&
|
|
113
|
-
typeof spec === 'object' &&
|
|
114
|
-
(spec.aspectRatio === undefined ||
|
|
115
|
-
(typeof spec.aspectRatio === 'number' &&
|
|
116
|
-
Number.isFinite(spec.aspectRatio) &&
|
|
117
|
-
spec.aspectRatio >= 0.01 &&
|
|
118
|
-
spec.aspectRatio <= 100)) &&
|
|
119
|
-
(spec.focus === undefined || isFocusPoint(spec.focus)) &&
|
|
120
|
-
/^([a-z][a-z0-9_-]*)$/.test(spec.preset) &&
|
|
121
|
-
Number.isInteger(spec.size) &&
|
|
122
|
-
spec.size >= 1 &&
|
|
123
|
-
spec.size <= 8192 &&
|
|
124
|
-
['webp', 'avif', 'jpeg', 'svg'].includes(spec.format) &&
|
|
125
|
-
Number.isInteger(spec.quality) &&
|
|
126
|
-
spec.quality >= 1 &&
|
|
127
|
-
spec.quality <= 100;
|
|
128
|
-
async function mapLimit(items, limit, run) {
|
|
129
|
-
const results = new Array(items.length);
|
|
130
|
-
let next = 0;
|
|
131
|
-
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
|
|
132
|
-
while (next < items.length) {
|
|
133
|
-
const index = next++;
|
|
134
|
-
results[index] = await run(items[index]);
|
|
135
|
-
}
|
|
136
|
-
}));
|
|
137
|
-
return results;
|
|
138
|
-
}
|
|
139
|
-
async function variantSource(env, origin, id) {
|
|
140
|
-
const original = await env.MEDIA.head('originals/' + id);
|
|
141
|
-
if (!original)
|
|
142
|
-
return null;
|
|
143
|
-
if (original.httpMetadata?.contentType === 'image/svg+xml') {
|
|
144
|
-
const object = await env.MEDIA.get('originals/' + id);
|
|
145
|
-
if (!object)
|
|
146
|
-
return null;
|
|
147
|
-
return { svg: sanitizeSvg(await object.text()) };
|
|
148
|
-
}
|
|
149
|
-
// Older originals have no saved dimensions; inspect them remotely on rebuild.
|
|
150
|
-
const metadata = original.customMetadata;
|
|
151
|
-
return metadata?.width && metadata?.height
|
|
152
|
-
? dimensions(Number(metadata.width), Number(metadata.height))
|
|
153
|
-
: inspect(await sourceURL(origin, id, env.SANDCMS_WORKER_TOKEN));
|
|
154
|
-
}
|
|
155
|
-
// Returns null when the original is missing so callers can report a non-retryable upload error.
|
|
156
|
-
async function renderVariant(env, origin, id, version, spec, load) {
|
|
157
|
-
const key = `${id}/${version}/${spec.preset}-${spec.size}.${spec.format}`;
|
|
158
|
-
const existing = await env.MEDIA.head('variants/' + key);
|
|
159
|
-
if (existing?.customMetadata?.ready === 'true')
|
|
160
|
-
return JSON.parse(existing.customMetadata.result);
|
|
161
|
-
const info = await load();
|
|
162
|
-
if (!info)
|
|
163
|
-
return null;
|
|
164
|
-
let output, width, height;
|
|
165
|
-
if ('svg' in info) {
|
|
166
|
-
if (spec.format !== 'svg')
|
|
167
|
-
throw new Error('SVG requires a sanitized derivative');
|
|
168
|
-
output = new Response(info.svg, { headers: { 'Content-Type': 'image/svg+xml' } });
|
|
169
|
-
({ width, height } = svgDimensions(info.svg));
|
|
170
|
-
}
|
|
171
|
-
else {
|
|
172
|
-
if (spec.format === 'svg')
|
|
173
|
-
throw new Error('Raster input cannot become SVG');
|
|
174
|
-
const scale = Math.min(1, spec.size / Math.max(info.width, info.height));
|
|
175
|
-
width = Math.max(1, Math.round(info.width * scale));
|
|
176
|
-
height = Math.max(1, Math.round(info.height * scale));
|
|
177
|
-
if (spec.aspectRatio) {
|
|
178
|
-
const targetWidth = Math.max(1, Math.round(spec.size * Math.min(1, spec.aspectRatio)));
|
|
179
|
-
const targetHeight = Math.max(1, Math.round(spec.size / Math.max(1, spec.aspectRatio)));
|
|
180
|
-
const cropScale = Math.min(1, info.width / targetWidth, info.height / targetHeight);
|
|
181
|
-
width = Math.max(1, Math.round(targetWidth * cropScale));
|
|
182
|
-
height = Math.max(1, Math.round(targetHeight * cropScale));
|
|
183
|
-
}
|
|
184
|
-
// Sign per variant: a five-minute capability must not expire partway through a batch.
|
|
185
|
-
output = await transform(await sourceURL(origin, id, env.SANDCMS_WORKER_TOKEN), {
|
|
186
|
-
width,
|
|
187
|
-
height,
|
|
188
|
-
fit: spec.aspectRatio ? 'cover' : 'scale-down',
|
|
189
|
-
...(spec.aspectRatio && spec.focus ? { gravity: spec.focus } : {}),
|
|
190
|
-
format: spec.format,
|
|
191
|
-
quality: spec.quality
|
|
192
|
-
}, `image/${spec.format}`);
|
|
193
|
-
}
|
|
194
|
-
const result = {
|
|
195
|
-
key,
|
|
196
|
-
preset: spec.preset,
|
|
197
|
-
size: spec.size,
|
|
198
|
-
width,
|
|
199
|
-
height,
|
|
200
|
-
format: spec.format
|
|
201
|
-
};
|
|
202
|
-
// R2 requires a known stream length; the Images result may be streamed without one.
|
|
203
|
-
const bytes = await boundedBody(output, 20_000_000);
|
|
204
|
-
await putAsset(env, id, 'variants/' + key, bytes, {
|
|
205
|
-
httpMetadata: { contentType: output.headers.get('content-type') },
|
|
206
|
-
customMetadata: { ready: 'true', result: JSON.stringify(result) }
|
|
207
|
-
});
|
|
208
|
-
return result;
|
|
209
|
-
}
|
|
210
|
-
export default {
|
|
211
|
-
async fetch(request, env) {
|
|
212
|
-
const url = new URL(request.url), path = url.pathname;
|
|
213
|
-
try {
|
|
214
|
-
if (path.startsWith('/internal/source/')) {
|
|
215
|
-
const [id, staging, ...extra] = path.slice('/internal/source/'.length).split('/');
|
|
216
|
-
if (request.method !== 'GET' ||
|
|
217
|
-
!idPattern.test(id) ||
|
|
218
|
-
(staging !== undefined && !idPattern.test(staging)) ||
|
|
219
|
-
extra.length > 0 ||
|
|
220
|
-
!(await validSource(url, env.SANDCMS_WORKER_TOKEN)))
|
|
221
|
-
return new Response('Not found', {
|
|
222
|
-
status: 404,
|
|
223
|
-
headers: { 'Cache-Control': 'private, no-store' }
|
|
224
|
-
});
|
|
225
|
-
if (await isDeleted(env, id))
|
|
226
|
-
return new Response('Not found', {
|
|
227
|
-
status: 404,
|
|
228
|
-
headers: { 'Cache-Control': 'private, no-store' }
|
|
229
|
-
});
|
|
230
|
-
const original = await env.MEDIA.get(staging ? `incoming/${id}/${staging}` : 'originals/' + id);
|
|
231
|
-
if (!original || original.httpMetadata?.contentType === 'image/svg+xml')
|
|
232
|
-
return new Response('Not found', {
|
|
233
|
-
status: 404,
|
|
234
|
-
headers: { 'Cache-Control': 'private, no-store' }
|
|
235
|
-
});
|
|
236
|
-
return new Response(original.body, {
|
|
237
|
-
headers: {
|
|
238
|
-
'Content-Type': original.httpMetadata?.contentType ?? 'application/octet-stream',
|
|
239
|
-
'Content-Length': String(original.size),
|
|
240
|
-
'Cache-Control': 'private, no-store',
|
|
241
|
-
'X-Content-Type-Options': 'nosniff',
|
|
242
|
-
'Content-Security-Policy': "default-src 'none'; sandbox"
|
|
243
|
-
}
|
|
244
|
-
});
|
|
245
|
-
}
|
|
246
|
-
if (!path.startsWith('/internal/') || !(await authenticated(request, env)))
|
|
247
|
-
return new Response('Not found', { status: 404, headers: { 'Cache-Control': 'no-store' } });
|
|
248
|
-
if (path === '/internal/health')
|
|
249
|
-
return json({ protocol: PROTOCOL });
|
|
250
|
-
if (!['3', '4', '5', String(PROTOCOL)].includes(request.headers.get('x-sandcms-protocol') ?? ''))
|
|
251
|
-
return json({ error: 'Incompatible CMS media protocol' }, 409);
|
|
252
|
-
const uploadMatch = /^\/internal\/uploads\/([a-f0-9-]{36})\/(sign|complete)$/.exec(path);
|
|
253
|
-
if (uploadMatch && request.method === 'POST') {
|
|
254
|
-
if (!['4', '5', String(PROTOCOL)].includes(request.headers.get('x-sandcms-protocol') ?? ''))
|
|
255
|
-
return json({ error: 'Direct uploads require media protocol 4' }, 409);
|
|
256
|
-
const id = uploadMatch[1];
|
|
257
|
-
if (await isDeleted(env, id))
|
|
258
|
-
throw new Error('Asset has been deleted');
|
|
259
|
-
const input = uploadInput(JSON.parse(new TextDecoder().decode(await boundedBody(request, 4096))));
|
|
260
|
-
const staging = `incoming/${id}/${input.attempt}`;
|
|
261
|
-
if (uploadMatch[2] === 'sign')
|
|
262
|
-
return json(await presignUpload(env, staging, input.mime));
|
|
263
|
-
// Recover if promotion succeeded but the CMS never received the response.
|
|
264
|
-
const accepted = await env.MEDIA.head('originals/' + id);
|
|
265
|
-
if (accepted) {
|
|
266
|
-
if (accepted.customMetadata?.uploadAttempt !== input.attempt)
|
|
267
|
-
throw new Error('Original already exists for another upload');
|
|
268
|
-
await env.MEDIA.delete(staging);
|
|
269
|
-
return json({ stored: true });
|
|
270
|
-
}
|
|
271
|
-
const object = await env.MEDIA.get(staging);
|
|
272
|
-
if (!object)
|
|
273
|
-
throw new Error('Upload missing; upload the file again');
|
|
274
|
-
if (object.size !== input.bytes || object.httpMetadata?.contentType !== input.mime) {
|
|
275
|
-
await object.body.cancel();
|
|
276
|
-
throw new Error('Upload size or type does not match');
|
|
277
|
-
}
|
|
278
|
-
// The PUT capability only targets staging. Inspection uses a separate immutable snapshot.
|
|
279
|
-
const validationAttempt = crypto.randomUUID();
|
|
280
|
-
const validation = `incoming/${id}/${validationAttempt}`;
|
|
281
|
-
try {
|
|
282
|
-
if (input.mime === 'image/svg+xml') {
|
|
283
|
-
const data = await boundedBody(new Response(object.body), 1_000_000);
|
|
284
|
-
const svg = sanitizeSvg(new TextDecoder().decode(data));
|
|
285
|
-
const promoted = await putAsset(env, id, 'originals/' + id, svg, {
|
|
286
|
-
httpMetadata: { contentType: input.mime },
|
|
287
|
-
customMetadata: { uploadAttempt: input.attempt },
|
|
288
|
-
onlyIf: { etagDoesNotMatch: '*' }
|
|
289
|
-
});
|
|
290
|
-
if (!promoted &&
|
|
291
|
-
(await env.MEDIA.head('originals/' + id))?.customMetadata?.uploadAttempt !==
|
|
292
|
-
input.attempt)
|
|
293
|
-
throw new Error('Original already exists for another upload');
|
|
294
|
-
}
|
|
295
|
-
else {
|
|
296
|
-
await env.MEDIA.put(validation, object.body, {
|
|
297
|
-
httpMetadata: { contentType: input.mime }
|
|
298
|
-
});
|
|
299
|
-
const info = await inspect(await sourceURL(url.origin, id, env.SANDCMS_WORKER_TOKEN, validationAttempt));
|
|
300
|
-
const validated = await env.MEDIA.get(validation);
|
|
301
|
-
if (!validated)
|
|
302
|
-
throw new Error('Upload snapshot missing');
|
|
303
|
-
const promoted = await putAsset(env, id, 'originals/' + id, validated.body, {
|
|
304
|
-
httpMetadata: { contentType: input.mime },
|
|
305
|
-
customMetadata: {
|
|
306
|
-
width: String(info.width),
|
|
307
|
-
height: String(info.height),
|
|
308
|
-
uploadAttempt: input.attempt
|
|
309
|
-
},
|
|
310
|
-
onlyIf: { etagDoesNotMatch: '*' }
|
|
311
|
-
});
|
|
312
|
-
if (!promoted &&
|
|
313
|
-
(await env.MEDIA.head('originals/' + id))?.customMetadata?.uploadAttempt !==
|
|
314
|
-
input.attempt)
|
|
315
|
-
throw new Error('Original already exists for another upload');
|
|
316
|
-
}
|
|
317
|
-
await env.MEDIA.delete(staging);
|
|
318
|
-
return json({ stored: true });
|
|
319
|
-
}
|
|
320
|
-
finally {
|
|
321
|
-
await env.MEDIA.delete(validation);
|
|
322
|
-
}
|
|
323
|
-
}
|
|
324
|
-
if (path.startsWith('/internal/media/') && ['GET', 'HEAD'].includes(request.method)) {
|
|
325
|
-
if (url.search)
|
|
326
|
-
return json({ error: 'Only named variants are available' }, 400);
|
|
327
|
-
const key = path.slice('/internal/media/'.length);
|
|
328
|
-
if (!variantPattern.test(key))
|
|
329
|
-
return new Response('Not found', { status: 404 });
|
|
330
|
-
if (await isDeleted(env, key.split('/')[0]))
|
|
331
|
-
return new Response('Not found', { status: 404 });
|
|
332
|
-
const object = await env.MEDIA.get('variants/' + key);
|
|
333
|
-
if (!object || object.customMetadata?.ready !== 'true')
|
|
334
|
-
return new Response('Not found', { status: 404 });
|
|
335
|
-
const headers = new Headers({
|
|
336
|
-
'Cache-Control': 'private, no-store',
|
|
337
|
-
'X-Content-Type-Options': 'nosniff',
|
|
338
|
-
'Content-Security-Policy': "default-src 'none'; style-src 'none'; sandbox",
|
|
339
|
-
'Cross-Origin-Resource-Policy': 'cross-origin'
|
|
340
|
-
});
|
|
341
|
-
object.writeHttpMetadata(headers);
|
|
342
|
-
headers.set('ETag', object.httpEtag);
|
|
343
|
-
// GET/HEAD use weak comparison; a validator list may include quoted commas.
|
|
344
|
-
const condition = request.headers.get('If-None-Match');
|
|
345
|
-
const matches = condition?.trim() === '*' ||
|
|
346
|
-
Array.from(condition?.matchAll(/(?:W\/)?"[^"]*"/g) ?? []).some(([tag]) => tag.replace(/^W\//, '') === object.httpEtag);
|
|
347
|
-
if (matches) {
|
|
348
|
-
await object.body.cancel();
|
|
349
|
-
return new Response(null, { status: 304, headers });
|
|
350
|
-
}
|
|
351
|
-
if (request.method === 'HEAD')
|
|
352
|
-
await object.body.cancel();
|
|
353
|
-
return new Response(request.method === 'HEAD' ? null : object.body, { headers });
|
|
354
|
-
}
|
|
355
|
-
const match = /^\/internal\/assets\/([^/]+)(?:\/(variants?))?$/.exec(path);
|
|
356
|
-
if (!match || !idPattern.test(match[1]))
|
|
357
|
-
return json({ error: 'Invalid asset' }, 400);
|
|
358
|
-
const id = match[1];
|
|
359
|
-
if (request.method === 'PUT' && !match[2]) {
|
|
360
|
-
if (await isDeleted(env, id))
|
|
361
|
-
throw new Error('Asset has been deleted');
|
|
362
|
-
const mime = request.headers.get('content-type') ?? '';
|
|
363
|
-
if (![
|
|
364
|
-
'image/jpeg',
|
|
365
|
-
'image/png',
|
|
366
|
-
'image/webp',
|
|
367
|
-
'image/avif',
|
|
368
|
-
'image/gif',
|
|
369
|
-
'image/svg+xml'
|
|
370
|
-
].includes(mime))
|
|
371
|
-
return json({ error: 'Unsupported image' }, 400);
|
|
372
|
-
if (mime === 'image/svg+xml') {
|
|
373
|
-
const data = await boundedBody(request, 1_000_000);
|
|
374
|
-
sanitizeSvg(new TextDecoder().decode(data));
|
|
375
|
-
await putAsset(env, id, 'originals/' + id, data, { httpMetadata: { contentType: mime } });
|
|
376
|
-
}
|
|
377
|
-
else {
|
|
378
|
-
const length = Number(request.headers.get('content-length'));
|
|
379
|
-
if (!Number.isSafeInteger(length) || length < 1 || length > 100_000_000 || !request.body)
|
|
380
|
-
throw new Error('Raster uploads require Content-Length between 1 and 100000000 bytes');
|
|
381
|
-
// Request and R2 bodies have a known length: stream without buffering a 100 MB copy.
|
|
382
|
-
// Validate a private staging object before promoting it to an original.
|
|
383
|
-
const attempt = crypto.randomUUID();
|
|
384
|
-
const staging = `incoming/${id}/${attempt}`;
|
|
385
|
-
try {
|
|
386
|
-
const stored = await env.MEDIA.put(staging, request.body, {
|
|
387
|
-
httpMetadata: { contentType: mime }
|
|
388
|
-
});
|
|
389
|
-
if (!stored || stored.size !== length)
|
|
390
|
-
throw new Error('Upload length mismatch');
|
|
391
|
-
const info = await inspect(await sourceURL(url.origin, id, env.SANDCMS_WORKER_TOKEN, attempt));
|
|
392
|
-
const validated = await env.MEDIA.get(staging);
|
|
393
|
-
if (!validated)
|
|
394
|
-
throw new Error('Upload missing');
|
|
395
|
-
await putAsset(env, id, 'originals/' + id, validated.body, {
|
|
396
|
-
httpMetadata: { contentType: mime },
|
|
397
|
-
customMetadata: { width: String(info.width), height: String(info.height) }
|
|
398
|
-
});
|
|
399
|
-
}
|
|
400
|
-
finally {
|
|
401
|
-
await env.MEDIA.delete(staging);
|
|
402
|
-
}
|
|
403
|
-
}
|
|
404
|
-
return json({ stored: true });
|
|
405
|
-
}
|
|
406
|
-
if (request.method === 'POST' && match[2]) {
|
|
407
|
-
if (await isDeleted(env, id))
|
|
408
|
-
throw new Error('Asset has been deleted');
|
|
409
|
-
const batch = match[2] === 'variants';
|
|
410
|
-
const body = JSON.parse(new TextDecoder().decode(await boundedBody(request, batch ? 65_536 : 4096)));
|
|
411
|
-
const specs = batch ? body.variants : [body];
|
|
412
|
-
if (!/^[a-f0-9]{16}$/.test(body.version) ||
|
|
413
|
-
!Array.isArray(specs) ||
|
|
414
|
-
specs.length < 1 ||
|
|
415
|
-
specs.length > maxBatch ||
|
|
416
|
-
!specs.every(validSpec))
|
|
417
|
-
throw new Error('Invalid variant request');
|
|
418
|
-
let source;
|
|
419
|
-
// Read the original once per request; every variant shares its type and dimensions.
|
|
420
|
-
const load = () => (source ??= variantSource(env, url.origin, id));
|
|
421
|
-
if (!batch) {
|
|
422
|
-
const result = await renderVariant(env, url.origin, id, body.version, specs[0], load);
|
|
423
|
-
return result ? json(result) : json({ error: 'Original missing; upload again' }, 404);
|
|
424
|
-
}
|
|
425
|
-
// Each variant fails independently so one bad encode does not retry the whole set.
|
|
426
|
-
const results = await mapLimit(specs, batchConcurrency, async (spec) => {
|
|
427
|
-
try {
|
|
428
|
-
const variant = await renderVariant(env, url.origin, id, body.version, spec, load);
|
|
429
|
-
return variant ? { variant } : null;
|
|
430
|
-
}
|
|
431
|
-
catch (e) {
|
|
432
|
-
return { error: e instanceof Error ? e.message : 'Media processing failed' };
|
|
433
|
-
}
|
|
434
|
-
});
|
|
435
|
-
if (results.includes(null))
|
|
436
|
-
return json({ error: 'Original missing; upload again' }, 404);
|
|
437
|
-
return json({ results });
|
|
438
|
-
}
|
|
439
|
-
if (request.method === 'DELETE' && !match[2]) {
|
|
440
|
-
// Keep the small marker so late requests can never recreate this asset ID.
|
|
441
|
-
await env.MEDIA.put('deleted/' + id, '', { httpMetadata: { contentType: 'text/plain' } });
|
|
442
|
-
await env.MEDIA.delete('originals/' + id);
|
|
443
|
-
for (const prefix of ['variants/' + id + '/', 'incoming/' + id + '/']) {
|
|
444
|
-
let cursor;
|
|
445
|
-
do {
|
|
446
|
-
const list = await env.MEDIA.list({ prefix, cursor });
|
|
447
|
-
if (list.objects.length)
|
|
448
|
-
await env.MEDIA.delete(list.objects.map((o) => o.key));
|
|
449
|
-
cursor = list.truncated ? list.cursor : undefined;
|
|
450
|
-
} while (cursor);
|
|
451
|
-
}
|
|
452
|
-
return json({ deleted: true });
|
|
453
|
-
}
|
|
454
|
-
return new Response('Not found', { status: 404 });
|
|
455
|
-
}
|
|
456
|
-
catch (e) {
|
|
457
|
-
return json({ error: e instanceof Error ? e.message : 'Media processing failed' }, 400);
|
|
458
|
-
}
|
|
459
|
-
}
|
|
460
|
-
};
|
package/dist/worker/local.d.ts
DELETED
package/dist/worker/local.js
DELETED
|
@@ -1,57 +0,0 @@
|
|
|
1
|
-
// Loopback-only S3 upload emulator for wrangler dev. Production uses the standard Worker entry.
|
|
2
|
-
import worker, {} from './index.js';
|
|
3
|
-
import { uploadSigner } from './uploads.js';
|
|
4
|
-
export default {
|
|
5
|
-
async fetch(request, env) {
|
|
6
|
-
const url = new URL(request.url);
|
|
7
|
-
if (!['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))
|
|
8
|
-
return new Response('Local media Worker requires a loopback hostname', { status: 403 });
|
|
9
|
-
const local = {
|
|
10
|
-
...env,
|
|
11
|
-
SANDCMS_R2_ENDPOINT: url.origin,
|
|
12
|
-
SANDCMS_R2_BUCKET_NAME: 'local-media',
|
|
13
|
-
SANDCMS_R2_ACCESS_KEY_ID: 'local-only',
|
|
14
|
-
SANDCMS_R2_SECRET_ACCESS_KEY: env.SANDCMS_WORKER_TOKEN
|
|
15
|
-
};
|
|
16
|
-
if (!url.pathname.startsWith('/local-media/'))
|
|
17
|
-
return worker.fetch(request, local);
|
|
18
|
-
const origin = request.headers.get('origin');
|
|
19
|
-
const headers = new Headers({ 'Cache-Control': 'private, no-store' });
|
|
20
|
-
if (origin && ['localhost', '127.0.0.1', '[::1]'].includes(new URL(origin).hostname)) {
|
|
21
|
-
headers.set('Access-Control-Allow-Origin', origin);
|
|
22
|
-
headers.set('Access-Control-Allow-Methods', 'PUT');
|
|
23
|
-
headers.set('Access-Control-Allow-Headers', 'Content-Type');
|
|
24
|
-
headers.set('Vary', 'Origin');
|
|
25
|
-
}
|
|
26
|
-
if (request.method === 'OPTIONS')
|
|
27
|
-
return new Response(null, { headers });
|
|
28
|
-
const key = url.pathname.slice('/local-media/'.length);
|
|
29
|
-
const date = url.searchParams.get('X-Amz-Date') ?? '';
|
|
30
|
-
const signature = url.searchParams.get('X-Amz-Signature');
|
|
31
|
-
const expires = Number(url.searchParams.get('X-Amz-Expires'));
|
|
32
|
-
const timestamp = Date.parse(date.replace(/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/, '$1-$2-$3T$4:$5:$6Z'));
|
|
33
|
-
if (!env.SANDCMS_WORKER_TOKEN ||
|
|
34
|
-
request.method !== 'PUT' ||
|
|
35
|
-
!/^incoming\/[a-f0-9-]{36}\/[a-f0-9-]{36}$/.test(key) ||
|
|
36
|
-
!Number.isFinite(timestamp) ||
|
|
37
|
-
expires !== 900 ||
|
|
38
|
-
Date.now() > timestamp + expires * 1000 ||
|
|
39
|
-
timestamp > Date.now() + 60_000)
|
|
40
|
-
return new Response('Invalid upload capability', { status: 403, headers });
|
|
41
|
-
url.searchParams.delete('X-Amz-Signature');
|
|
42
|
-
const signed = await uploadSigner(local).sign(url, {
|
|
43
|
-
method: 'PUT',
|
|
44
|
-
headers: { 'content-type': request.headers.get('content-type') ?? '' },
|
|
45
|
-
aws: { signQuery: true, allHeaders: true, datetime: date }
|
|
46
|
-
});
|
|
47
|
-
if (new URL(signed.url).searchParams.get('X-Amz-Signature') !== signature)
|
|
48
|
-
return new Response('Invalid upload signature', { status: 403, headers });
|
|
49
|
-
const length = Number(request.headers.get('content-length'));
|
|
50
|
-
if (!request.body || !Number.isSafeInteger(length) || length < 1 || length > 100_000_000)
|
|
51
|
-
return new Response('Invalid upload size', { status: 400, headers });
|
|
52
|
-
await env.MEDIA.put(key, request.body, {
|
|
53
|
-
httpMetadata: { contentType: request.headers.get('content-type') ?? '' }
|
|
54
|
-
});
|
|
55
|
-
return new Response(null, { headers });
|
|
56
|
-
}
|
|
57
|
-
};
|
package/dist/worker/source.d.ts
DELETED
package/dist/worker/source.js
DELETED
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
/** Short-lived, asset-scoped source URLs used only by remote transformations. */
|
|
2
|
-
const lifetime = 300;
|
|
3
|
-
async function key(secret) {
|
|
4
|
-
return crypto.subtle.importKey('raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign', 'verify']);
|
|
5
|
-
}
|
|
6
|
-
function message(url, expires) {
|
|
7
|
-
return new TextEncoder().encode(`${url.origin}${url.pathname}\n${expires}`);
|
|
8
|
-
}
|
|
9
|
-
export async function sourceURL(origin, id, secret, staging) {
|
|
10
|
-
const url = new URL('/internal/source/' + id + (staging ? '/' + staging : ''), origin);
|
|
11
|
-
const expires = String(Math.floor(Date.now() / 1000) + lifetime);
|
|
12
|
-
const signature = new Uint8Array(await crypto.subtle.sign('HMAC', await key(secret), message(url, expires)));
|
|
13
|
-
url.searchParams.set('expires', expires);
|
|
14
|
-
url.searchParams.set('signature', Array.from(signature, (v) => v.toString(16).padStart(2, '0')).join(''));
|
|
15
|
-
return url;
|
|
16
|
-
}
|
|
17
|
-
export async function validSource(url, secret) {
|
|
18
|
-
if (!secret || secret.length < 32)
|
|
19
|
-
return false;
|
|
20
|
-
const expires = url.searchParams.get('expires') ?? '';
|
|
21
|
-
const signature = url.searchParams.get('signature') ?? '';
|
|
22
|
-
const now = Math.floor(Date.now() / 1000);
|
|
23
|
-
if (!/^\d+$/.test(expires) ||
|
|
24
|
-
Number(expires) <= now ||
|
|
25
|
-
Number(expires) > now + lifetime ||
|
|
26
|
-
!/^[a-f0-9]{64}$/.test(signature) ||
|
|
27
|
-
[...url.searchParams].length !== 2)
|
|
28
|
-
return false;
|
|
29
|
-
const bytes = Uint8Array.from(signature.match(/../g), (v) => parseInt(v, 16));
|
|
30
|
-
return crypto.subtle.verify('HMAC', await key(secret), bytes, message(url, expires));
|
|
31
|
-
}
|
package/dist/worker/uploads.d.ts
DELETED
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import { AwsClient } from 'aws4fetch';
|
|
2
|
-
export interface UploadSigningEnv {
|
|
3
|
-
SANDCMS_CF_ACCOUNT_ID?: string;
|
|
4
|
-
SANDCMS_R2_BUCKET_NAME?: string;
|
|
5
|
-
SANDCMS_R2_ACCESS_KEY_ID?: string;
|
|
6
|
-
SANDCMS_R2_SECRET_ACCESS_KEY?: string;
|
|
7
|
-
SANDCMS_R2_ENDPOINT?: string;
|
|
8
|
-
}
|
|
9
|
-
export declare const uploadLifetime = 900;
|
|
10
|
-
export declare function uploadSigner(env: UploadSigningEnv): AwsClient;
|
|
11
|
-
export declare function presignUpload(env: UploadSigningEnv, key: string, mime: string): Promise<{
|
|
12
|
-
url: string;
|
|
13
|
-
headers: {
|
|
14
|
-
'content-type': string;
|
|
15
|
-
};
|
|
16
|
-
expiresAt: number;
|
|
17
|
-
}>;
|
|
18
|
-
export declare function uploadInput(input: unknown): {
|
|
19
|
-
mime: string;
|
|
20
|
-
bytes: number;
|
|
21
|
-
attempt: string;
|
|
22
|
-
};
|
package/dist/worker/uploads.js
DELETED
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
import { AwsClient } from 'aws4fetch';
|
|
2
|
-
export const uploadLifetime = 900;
|
|
3
|
-
export function uploadSigner(env) {
|
|
4
|
-
if (!env.SANDCMS_R2_ACCESS_KEY_ID ||
|
|
5
|
-
!env.SANDCMS_R2_SECRET_ACCESS_KEY ||
|
|
6
|
-
!env.SANDCMS_R2_BUCKET_NAME)
|
|
7
|
-
throw new Error('Configure SANDCMS_R2_BUCKET_NAME, SANDCMS_R2_ACCESS_KEY_ID and SANDCMS_R2_SECRET_ACCESS_KEY on the media Worker');
|
|
8
|
-
return new AwsClient({
|
|
9
|
-
service: 's3',
|
|
10
|
-
region: 'auto',
|
|
11
|
-
accessKeyId: env.SANDCMS_R2_ACCESS_KEY_ID,
|
|
12
|
-
secretAccessKey: env.SANDCMS_R2_SECRET_ACCESS_KEY
|
|
13
|
-
});
|
|
14
|
-
}
|
|
15
|
-
export async function presignUpload(env, key, mime) {
|
|
16
|
-
const signer = uploadSigner(env);
|
|
17
|
-
if (!env.SANDCMS_R2_ENDPOINT && !env.SANDCMS_CF_ACCOUNT_ID)
|
|
18
|
-
throw new Error('Configure SANDCMS_CF_ACCOUNT_ID on the media Worker');
|
|
19
|
-
const endpoint = env.SANDCMS_R2_ENDPOINT ?? `https://${env.SANDCMS_CF_ACCOUNT_ID}.r2.cloudflarestorage.com`;
|
|
20
|
-
const url = new URL(`${endpoint.replace(/\/$/, '')}/${encodeURIComponent(env.SANDCMS_R2_BUCKET_NAME)}/${key}`);
|
|
21
|
-
if (url.protocol !== 'https:' && !['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))
|
|
22
|
-
throw new Error('SANDCMS_R2_ENDPOINT must use HTTPS');
|
|
23
|
-
url.searchParams.set('X-Amz-Expires', String(uploadLifetime));
|
|
24
|
-
const signed = await signer.sign(url, {
|
|
25
|
-
method: 'PUT',
|
|
26
|
-
headers: { 'content-type': mime },
|
|
27
|
-
aws: { signQuery: true, allHeaders: true }
|
|
28
|
-
});
|
|
29
|
-
return {
|
|
30
|
-
url: signed.url,
|
|
31
|
-
headers: { 'content-type': mime },
|
|
32
|
-
expiresAt: Date.now() + uploadLifetime * 1000
|
|
33
|
-
};
|
|
34
|
-
}
|
|
35
|
-
export function uploadInput(input) {
|
|
36
|
-
const body = input;
|
|
37
|
-
if (!body ||
|
|
38
|
-
typeof body.mime !== 'string' ||
|
|
39
|
-
!['image/jpeg', 'image/png', 'image/webp', 'image/avif', 'image/gif', 'image/svg+xml'].includes(body.mime) ||
|
|
40
|
-
typeof body.bytes !== 'number' ||
|
|
41
|
-
!Number.isSafeInteger(body.bytes) ||
|
|
42
|
-
body.bytes < 1 ||
|
|
43
|
-
body.bytes > (body.mime === 'image/svg+xml' ? 1_000_000 : 100_000_000) ||
|
|
44
|
-
typeof body.attempt !== 'string' ||
|
|
45
|
-
!/^[a-f0-9-]{36}$/.test(body.attempt))
|
|
46
|
-
throw new Error('Invalid upload metadata');
|
|
47
|
-
return { mime: body.mime, bytes: body.bytes, attempt: body.attempt };
|
|
48
|
-
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { default } from 'sandcms/worker';
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { default } from 'sandcms/worker/local';
|
|
File without changes
|
|
File without changes
|