s3deck 0.0.0-stage → 0.1.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/dist/cli.mjs ADDED
@@ -0,0 +1,3522 @@
1
+ #!/usr/bin/env node
2
+ import { createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID, scrypt as scrypt$1, scryptSync, timingSafeEqual } from "node:crypto";
3
+ import { existsSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import pc from "picocolors";
7
+ import { AbortMultipartUploadCommand, CompleteMultipartUploadCommand, CopyObjectCommand, CreateBucketCommand, CreateMultipartUploadCommand, DeleteBucketCommand, DeleteBucketCorsCommand, DeleteBucketLifecycleCommand, DeleteBucketPolicyCommand, DeleteObjectCommand, DeleteObjectTaggingCommand, DeleteObjectsCommand, DeletePublicAccessBlockCommand, GetBucketCorsCommand, GetBucketEncryptionCommand, GetBucketLifecycleConfigurationCommand, GetBucketLocationCommand, GetBucketPolicyCommand, GetBucketVersioningCommand, GetObjectCommand, GetObjectLegalHoldCommand, GetObjectLockConfigurationCommand, GetObjectTaggingCommand, GetPublicAccessBlockCommand, HeadBucketCommand, HeadObjectCommand, ListBucketsCommand, ListMultipartUploadsCommand, ListObjectVersionsCommand, ListObjectsV2Command, ListPartsCommand, PutBucketCorsCommand, PutBucketLifecycleConfigurationCommand, PutBucketPolicyCommand, PutBucketVersioningCommand, PutObjectCommand, PutObjectTaggingCommand, PutPublicAccessBlockCommand, RestoreObjectCommand, S3Client, S3ServiceException, UploadPartCommand, UploadPartCopyCommand } from "@aws-sdk/client-s3";
8
+ import { once } from "node:events";
9
+ import { Upload } from "@aws-sdk/lib-storage";
10
+ import { ZipArchive } from "archiver";
11
+ import { ZodError, z } from "zod";
12
+ import * as oidc from "openid-client";
13
+ import { appendFile, chmod, mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
14
+ import os, { networkInterfaces } from "node:os";
15
+ import { promisify } from "node:util";
16
+ import { serve } from "@hono/node-server";
17
+ import { Readable } from "node:stream";
18
+ import { Hono } from "hono";
19
+ import { secureHeaders } from "hono/secure-headers";
20
+ import { getConnInfo } from "@hono/node-server/conninfo";
21
+ import { deleteCookie, getCookie, setCookie } from "hono/cookie";
22
+ import { zValidator } from "@hono/zod-validator";
23
+ import mime from "mime-types";
24
+ import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
25
+ import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
26
+ import { Command, Option } from "commander";
27
+ // package.json
28
+ var version = "0.1.0";
29
+ // src/s3/errors.ts
30
+ /** A request that can't be carried out as asked (maps to HTTP 400). */
31
+ var UserError = class extends Error {
32
+ name = "UserError";
33
+ };
34
+ /** Error codes that mean "this provider doesn't implement the feature". */
35
+ const UNSUPPORTED = /* @__PURE__ */ new Set([
36
+ "NotImplemented",
37
+ "NotSupported",
38
+ "XNotImplemented",
39
+ "MethodNotAllowed",
40
+ "UnsupportedOperation"
41
+ ]);
42
+ /** Error codes that mean "the setting isn't configured" for bucket settings reads. */
43
+ const NOT_CONFIGURED = /* @__PURE__ */ new Set([
44
+ "NoSuchCORSConfiguration",
45
+ "NoSuchLifecycleConfiguration",
46
+ "NoSuchBucketPolicy",
47
+ "NoSuchPublicAccessBlockConfiguration",
48
+ "NoSuchTagSet",
49
+ "NoSuchTagSetError",
50
+ "ServerSideEncryptionConfigurationNotFoundError",
51
+ "ObjectLockConfigurationNotFoundError",
52
+ "NoSuchObjectLockConfiguration"
53
+ ]);
54
+ function errorCode(err) {
55
+ if (err instanceof S3ServiceException) return err.name;
56
+ if (err && typeof err === "object" && "name" in err && typeof err.name === "string") return err.name;
57
+ return "Error";
58
+ }
59
+ function errorStatus(err) {
60
+ if (err instanceof S3ServiceException) return err.$metadata.httpStatusCode;
61
+ }
62
+ function isUnsupported(err) {
63
+ const status = errorStatus(err);
64
+ return UNSUPPORTED.has(errorCode(err)) || status === 501;
65
+ }
66
+ function isNotConfigured(err) {
67
+ return NOT_CONFIGURED.has(errorCode(err));
68
+ }
69
+ function isAccessDenied(err) {
70
+ return errorCode(err) === "AccessDenied" || errorStatus(err) === 403;
71
+ }
72
+ function errorMessage(err) {
73
+ if (err instanceof Error) {
74
+ if (err.message && err.message !== "UnknownError") return err.message;
75
+ const status = errorStatus(err);
76
+ if (status === 403) return "Access denied";
77
+ if (status === 404) return "Not found";
78
+ return `${errorCode(err)}${status ? ` (HTTP ${status})` : ""}`;
79
+ }
80
+ return String(err);
81
+ }
82
+ // src/s3/provider.ts
83
+ const AWS_STORAGE_CLASSES = [
84
+ "STANDARD",
85
+ "INTELLIGENT_TIERING",
86
+ "STANDARD_IA",
87
+ "ONEZONE_IA",
88
+ "GLACIER_IR",
89
+ "GLACIER",
90
+ "DEEP_ARCHIVE"
91
+ ];
92
+ /** Classes whose objects must be restored before they can be read. */
93
+ const ARCHIVE_CLASSES = /* @__PURE__ */ new Set(["GLACIER", "DEEP_ARCHIVE"]);
94
+ const ALL = {
95
+ versioning: true,
96
+ tagging: true,
97
+ bucketPolicy: true,
98
+ publicAccessBlock: true,
99
+ lifecycle: true,
100
+ cors: true,
101
+ bucketCreate: true,
102
+ storageClasses: AWS_STORAGE_CLASSES,
103
+ archiveRestore: true,
104
+ objectLock: true,
105
+ encryption: true
106
+ };
107
+ const NO_AWS_EXTRAS = {
108
+ ...ALL,
109
+ publicAccessBlock: false,
110
+ storageClasses: [],
111
+ archiveRestore: false
112
+ };
113
+ /** Guesses the provider from the endpoint URL. Unknown endpoints use path-style URLs. */
114
+ function detectProvider(endpoint) {
115
+ if (!endpoint) return {
116
+ id: "aws",
117
+ name: "AWS S3",
118
+ pathStyle: false,
119
+ capabilities: ALL
120
+ };
121
+ const host = new URL(endpoint).hostname.toLowerCase();
122
+ if (host.endsWith(".amazonaws.com")) return {
123
+ id: "aws",
124
+ name: "AWS S3",
125
+ pathStyle: false,
126
+ capabilities: ALL
127
+ };
128
+ if (host.endsWith(".r2.cloudflarestorage.com")) return {
129
+ id: "r2",
130
+ name: "Cloudflare R2",
131
+ defaultRegion: "auto",
132
+ pathStyle: true,
133
+ capabilities: {
134
+ ...ALL,
135
+ versioning: false,
136
+ tagging: false,
137
+ bucketPolicy: false,
138
+ publicAccessBlock: false,
139
+ storageClasses: ["STANDARD", "STANDARD_IA"],
140
+ archiveRestore: false,
141
+ objectLock: false,
142
+ encryption: false
143
+ }
144
+ };
145
+ if (host.endsWith(".backblazeb2.com")) return {
146
+ id: "b2",
147
+ name: "Backblaze B2",
148
+ defaultRegion: host.match(/^s3\.([a-z0-9-]+)\./)?.[1],
149
+ pathStyle: false,
150
+ capabilities: {
151
+ ...NO_AWS_EXTRAS,
152
+ bucketPolicy: false,
153
+ tagging: false
154
+ }
155
+ };
156
+ if (host.endsWith(".digitaloceanspaces.com")) return {
157
+ id: "spaces",
158
+ name: "DigitalOcean Spaces",
159
+ defaultRegion: host.split(".")[0],
160
+ pathStyle: false,
161
+ capabilities: NO_AWS_EXTRAS
162
+ };
163
+ if (host.endsWith(".wasabisys.com")) return {
164
+ id: "wasabi",
165
+ name: "Wasabi",
166
+ defaultRegion: host.match(/^s3\.([a-z0-9-]+)\./)?.[1],
167
+ pathStyle: false,
168
+ capabilities: NO_AWS_EXTRAS
169
+ };
170
+ if (host === "storage.googleapis.com") return {
171
+ id: "gcs",
172
+ name: "Google Cloud Storage",
173
+ defaultRegion: "auto",
174
+ pathStyle: true,
175
+ capabilities: NO_AWS_EXTRAS
176
+ };
177
+ return {
178
+ id: "other",
179
+ name: "S3-compatible",
180
+ pathStyle: true,
181
+ capabilities: NO_AWS_EXTRAS
182
+ };
183
+ }
184
+ /** Refines the provider once we've seen a response (MinIO identifies itself in the Server header). */
185
+ function refineProvider(info, serverHeader) {
186
+ if (info.id === "other" && serverHeader?.toLowerCase().includes("minio")) return {
187
+ ...info,
188
+ id: "minio",
189
+ name: "MinIO",
190
+ capabilities: { ...NO_AWS_EXTRAS }
191
+ };
192
+ return info;
193
+ }
194
+ // src/s3/client.ts
195
+ function createS3Client(config) {
196
+ const provider = detectProvider(config.endpoint);
197
+ const forcePathStyle = config.pathStyle === "auto" ? provider.pathStyle : config.pathStyle === "path";
198
+ const client = new S3Client({
199
+ region: config.region,
200
+ endpoint: config.endpoint || void 0,
201
+ forcePathStyle,
202
+ credentials: config.credentials,
203
+ followRegionRedirects: provider.id === "aws",
204
+ requestChecksumCalculation: "WHEN_REQUIRED",
205
+ responseChecksumValidation: "WHEN_REQUIRED",
206
+ maxAttempts: 3
207
+ });
208
+ let server;
209
+ client.middlewareStack.add((next) => async (args) => {
210
+ const result = await next(args);
211
+ const headers = result.response?.headers;
212
+ if (headers?.server) server = headers.server;
213
+ return result;
214
+ }, {
215
+ step: "deserialize",
216
+ name: "s3deckServerHeader"
217
+ });
218
+ return {
219
+ client,
220
+ provider,
221
+ forcePathStyle,
222
+ serverHeader: () => server
223
+ };
224
+ }
225
+ /** Encodes a key for the x-amz-copy-source header. */
226
+ function copySource(bucket, key, versionId) {
227
+ const path = `${bucket}/${key.split("/").map(encodeURIComponent).join("/")}`;
228
+ return versionId ? `${path}?versionId=${encodeURIComponent(versionId)}` : path;
229
+ }
230
+ /** Direct (unsigned) URL of an object, or under a custom public domain. */
231
+ function publicObjectUrl(opts) {
232
+ const encodedKey = opts.key.split("/").map(encodeURIComponent).join("/");
233
+ if (opts.publicUrlBase) return `${opts.publicUrlBase.replace(/\/+$/, "")}/${encodedKey}`;
234
+ if (!opts.endpoint) {
235
+ const host = opts.region === "us-east-1" ? "s3.amazonaws.com" : `s3.${opts.region}.amazonaws.com`;
236
+ return opts.forcePathStyle || opts.bucket.includes(".") ? `https://${host}/${opts.bucket}/${encodedKey}` : `https://${opts.bucket}.${host}/${encodedKey}`;
237
+ }
238
+ const u = new URL(opts.endpoint);
239
+ const base = u.pathname.replace(/\/+$/, "");
240
+ if (opts.forcePathStyle) return `${u.origin}${base}/${opts.bucket}/${encodedKey}`;
241
+ return `${u.protocol}//${opts.bucket}.${u.host}${base}/${encodedKey}`;
242
+ }
243
+ // src/shared/constants.ts
244
+ /** Header every state-changing API call must carry (CSRF protection). */
245
+ const CSRF_HEADER = "x-s3deck-csrf";
246
+ const SESSION_COOKIE = "s3deck_session";
247
+ const DEFAULT_PORT = 47715;
248
+ const DEFAULT_HOST = "127.0.0.1";
249
+ const DEFAULT_USER = "admin";
250
+ const DEFAULT_REGION = "us-east-1";
251
+ /** S3 limits */
252
+ const MAX_DELETE_BATCH = 1e3;
253
+ const MAX_SINGLE_COPY_BYTES = 5 * 1024 ** 3;
254
+ const MAX_PRESIGN_SECONDS = 604800;
255
+ // src/s3/listing.ts
256
+ function baseName(key, prefix) {
257
+ return key.slice(prefix.length).replace(/\/$/, "");
258
+ }
259
+ function toObjectEntry(o) {
260
+ const key = o.Key ?? "";
261
+ return {
262
+ type: "object",
263
+ key,
264
+ name: key.split("/").pop() || key,
265
+ size: o.Size ?? 0,
266
+ lastModified: o.LastModified?.toISOString() ?? null,
267
+ etag: o.ETag ?? null,
268
+ storageClass: o.StorageClass ?? null
269
+ };
270
+ }
271
+ /** Lists one page of a "folder" (prefix + "/" delimiter), or a flat page for search. */
272
+ async function listPage(client, bucket, opts) {
273
+ const out = await client.send(new ListObjectsV2Command({
274
+ Bucket: bucket,
275
+ Prefix: opts.prefix || void 0,
276
+ Delimiter: opts.flat ? void 0 : "/",
277
+ ContinuationToken: opts.cursor,
278
+ MaxKeys: opts.limit
279
+ }));
280
+ const folders = (out.CommonPrefixes ?? []).map((p) => p.Prefix).filter((p) => !!p).map((key) => ({
281
+ type: "folder",
282
+ key,
283
+ name: baseName(key, opts.prefix)
284
+ }));
285
+ const objects = (out.Contents ?? []).filter((o) => o.Key && o.Key !== opts.prefix && !o.Key.endsWith("/")).map((o) => toObjectEntry(o));
286
+ return {
287
+ prefix: opts.prefix,
288
+ folders,
289
+ objects,
290
+ nextCursor: out.IsTruncated ? out.NextContinuationToken ?? null : null
291
+ };
292
+ }
293
+ /** Yields every object under a prefix, page by page (1,000 at a time). */
294
+ async function* walkObjects(client, bucket, prefix, signal) {
295
+ let token;
296
+ do {
297
+ signal?.throwIfAborted();
298
+ const out = await client.send(new ListObjectsV2Command({
299
+ Bucket: bucket,
300
+ Prefix: prefix || void 0,
301
+ ContinuationToken: token
302
+ }), { abortSignal: signal });
303
+ const page = (out.Contents ?? []).filter((o) => o.Key);
304
+ if (page.length) yield page;
305
+ token = out.IsTruncated ? out.NextContinuationToken : void 0;
306
+ } while (token);
307
+ }
308
+ /** Counts objects and bytes under a set of prefixes and keys. */
309
+ async function summarize(client, bucket, prefixes, objectSizes = /* @__PURE__ */ new Map(), signal) {
310
+ let objects = objectSizes.size;
311
+ let bytes = [...objectSizes.values()].reduce((a, b) => a + b, 0);
312
+ for (const prefix of prefixes) for await (const page of walkObjects(client, bucket, prefix, signal)) {
313
+ objects += page.length;
314
+ for (const o of page) bytes += o.Size ?? 0;
315
+ }
316
+ return {
317
+ objects,
318
+ bytes
319
+ };
320
+ }
321
+ // src/s3/transfers.ts
322
+ /** Runs `fn` over `items` with at most `limit` in flight. */
323
+ async function mapLimit(items, limit, fn) {
324
+ const results = new Array(items.length);
325
+ let next = 0;
326
+ const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
327
+ while (next < items.length) {
328
+ const i = next++;
329
+ results[i] = await fn(items[i]);
330
+ }
331
+ });
332
+ await Promise.all(workers);
333
+ return results;
334
+ }
335
+ const UPLOAD_PART_SIZE = 16777216;
336
+ /** Streams a body to S3. Large bodies use multipart upload with parallel parts. */
337
+ async function uploadStream(client, opts) {
338
+ const upload = new Upload({
339
+ client,
340
+ params: {
341
+ Bucket: opts.bucket,
342
+ Key: opts.key,
343
+ Body: opts.body,
344
+ ContentType: opts.contentType
345
+ },
346
+ partSize: UPLOAD_PART_SIZE,
347
+ queueSize: 4,
348
+ leavePartsOnError: false
349
+ });
350
+ const onAbort = () => void upload.abort().catch(() => {});
351
+ opts.signal?.addEventListener("abort", onAbort, { once: true });
352
+ try {
353
+ return { etag: (await upload.done()).ETag ?? null };
354
+ } finally {
355
+ opts.signal?.removeEventListener("abort", onAbort);
356
+ }
357
+ }
358
+ const COPY_PART_SIZE = 536870912;
359
+ /** Server-side copy. Uses multipart copy above 5 GB. `replace` rewrites headers and metadata. */
360
+ async function copyObject(client, o) {
361
+ const source = copySource(o.sourceBucket, o.sourceKey, o.sourceVersionId);
362
+ if (o.size <= MAX_SINGLE_COPY_BYTES) {
363
+ await client.send(new CopyObjectCommand({
364
+ Bucket: o.destinationBucket,
365
+ Key: o.destinationKey,
366
+ CopySource: source,
367
+ ...o.replace ? {
368
+ MetadataDirective: "REPLACE",
369
+ ...o.replace
370
+ } : {}
371
+ }));
372
+ return;
373
+ }
374
+ let headers = o.replace;
375
+ if (!headers) {
376
+ const h = await client.send(new HeadObjectCommand({
377
+ Bucket: o.sourceBucket,
378
+ Key: o.sourceKey,
379
+ VersionId: o.sourceVersionId
380
+ }));
381
+ headers = {
382
+ ContentType: h.ContentType,
383
+ CacheControl: h.CacheControl,
384
+ ContentDisposition: h.ContentDisposition,
385
+ ContentEncoding: h.ContentEncoding,
386
+ ContentLanguage: h.ContentLanguage,
387
+ Metadata: h.Metadata,
388
+ StorageClass: h.StorageClass
389
+ };
390
+ }
391
+ const { UploadId } = await client.send(new CreateMultipartUploadCommand({
392
+ Bucket: o.destinationBucket,
393
+ Key: o.destinationKey,
394
+ ...headers
395
+ }));
396
+ try {
397
+ const ranges = [];
398
+ for (let start = 0, part = 1; start < o.size; start += COPY_PART_SIZE, part++) ranges.push({
399
+ part,
400
+ start,
401
+ end: Math.min(start + COPY_PART_SIZE, o.size) - 1
402
+ });
403
+ const parts = await mapLimit(ranges, 4, async (r) => {
404
+ const out = await client.send(new UploadPartCopyCommand({
405
+ Bucket: o.destinationBucket,
406
+ Key: o.destinationKey,
407
+ UploadId,
408
+ PartNumber: r.part,
409
+ CopySource: source,
410
+ CopySourceRange: `bytes=${r.start}-${r.end}`
411
+ }));
412
+ return {
413
+ PartNumber: r.part,
414
+ ETag: out.CopyPartResult?.ETag
415
+ };
416
+ });
417
+ await client.send(new CompleteMultipartUploadCommand({
418
+ Bucket: o.destinationBucket,
419
+ Key: o.destinationKey,
420
+ UploadId,
421
+ MultipartUpload: { Parts: parts }
422
+ }));
423
+ } catch (err) {
424
+ await client.send(new AbortMultipartUploadCommand({
425
+ Bucket: o.destinationBucket,
426
+ Key: o.destinationKey,
427
+ UploadId
428
+ })).catch(() => {});
429
+ throw err;
430
+ }
431
+ }
432
+ /** Copies (or moves) keys and folders. Folder sources end in "/" and copy everything under them. */
433
+ async function copyItems(client, sourceBucket, input) {
434
+ let copied = 0;
435
+ let deleted = 0;
436
+ const toDelete = [];
437
+ for (const item of input.items) {
438
+ if (item.source === item.destination && sourceBucket === input.destinationBucket) continue;
439
+ if (item.source.endsWith("/")) {
440
+ if (sourceBucket === input.destinationBucket && item.destination.startsWith(item.source)) throw new UserError(`Can't copy "${item.source}" into itself`);
441
+ for await (const page of walkObjects(client, sourceBucket, item.source)) await mapLimit(page, 8, async (obj) => {
442
+ const key = obj.Key;
443
+ await copyObject(client, {
444
+ sourceBucket,
445
+ sourceKey: key,
446
+ destinationBucket: input.destinationBucket,
447
+ destinationKey: item.destination + key.slice(item.source.length),
448
+ size: obj.Size ?? 0
449
+ });
450
+ copied++;
451
+ if (input.move) toDelete.push(key);
452
+ });
453
+ } else {
454
+ const head = await client.send(new HeadObjectCommand({
455
+ Bucket: sourceBucket,
456
+ Key: item.source
457
+ }));
458
+ await copyObject(client, {
459
+ sourceBucket,
460
+ sourceKey: item.source,
461
+ destinationBucket: input.destinationBucket,
462
+ destinationKey: item.destination,
463
+ size: head.ContentLength ?? 0
464
+ });
465
+ copied++;
466
+ if (input.move) toDelete.push(item.source);
467
+ }
468
+ }
469
+ if (input.move && toDelete.length) {
470
+ const result = await deleteKeys(client, sourceBucket, toDelete);
471
+ deleted = result.deleted;
472
+ if (result.errors.length) throw new Error(`Copied ${copied} objects, but ${result.errors.length} originals could not be deleted: ${result.errors[0]?.message}`);
473
+ }
474
+ return {
475
+ copied,
476
+ deleted
477
+ };
478
+ }
479
+ /** Deletes keys in batches of 1,000. */
480
+ async function deleteKeys(client, bucket, keys) {
481
+ const result = {
482
+ deleted: 0,
483
+ errors: []
484
+ };
485
+ for (let i = 0; i < keys.length; i += MAX_DELETE_BATCH) {
486
+ const batch = keys.slice(i, i + MAX_DELETE_BATCH);
487
+ const errors = ((await client.send(new DeleteObjectsCommand({
488
+ Bucket: bucket,
489
+ Delete: {
490
+ Objects: batch.map((Key) => ({ Key })),
491
+ Quiet: true
492
+ }
493
+ }))).Errors ?? []).map((e) => ({
494
+ key: e.Key ?? "",
495
+ message: e.Message ?? e.Code ?? "Failed"
496
+ }));
497
+ result.errors.push(...errors);
498
+ result.deleted += batch.length - errors.length;
499
+ }
500
+ return result;
501
+ }
502
+ /** Deletes keys and everything under the given folder prefixes. */
503
+ async function deleteItems(client, bucket, input) {
504
+ const result = await deleteKeys(client, bucket, input.keys);
505
+ for (const prefix of input.prefixes) {
506
+ if (!prefix) throw new UserError("Refusing to delete the whole bucket this way");
507
+ let batch = [];
508
+ const flush = async () => {
509
+ const r = await deleteKeys(client, bucket, batch);
510
+ result.deleted += r.deleted;
511
+ result.errors.push(...r.errors);
512
+ batch = [];
513
+ };
514
+ for await (const page of walkObjects(client, bucket, prefix)) {
515
+ for (const o of page) batch.push(o.Key);
516
+ if (batch.length >= 1e3) await flush();
517
+ }
518
+ if (batch.length) await flush();
519
+ }
520
+ return result;
521
+ }
522
+ /** Builds a ZIP on the fly from keys and folders. Objects are fetched one at a time. */
523
+ function zipStream(client, bucket, input, signal) {
524
+ const archive = new ZipArchive({ zlib: { level: 1 } });
525
+ const entryName = (key) => (key.startsWith(input.base) ? key.slice(input.base.length) : key) || key;
526
+ const appendOne = async (key, lastModified) => {
527
+ if (key.endsWith("/")) return;
528
+ const out = await client.send(new GetObjectCommand({
529
+ Bucket: bucket,
530
+ Key: key
531
+ }), { abortSignal: signal });
532
+ const body = out.Body;
533
+ const done = once(archive, "entry", { signal });
534
+ archive.append(body, {
535
+ name: entryName(key),
536
+ date: lastModified ?? out.LastModified ?? /* @__PURE__ */ new Date()
537
+ });
538
+ await done;
539
+ };
540
+ (async () => {
541
+ for (const key of input.keys) await appendOne(key);
542
+ for (const prefix of input.prefixes) for await (const page of walkObjects(client, bucket, prefix, signal)) for (const o of page) await appendOne(o.Key, o.LastModified);
543
+ await archive.finalize();
544
+ })().catch((err) => {
545
+ if (!signal?.aborted) console.error(` ZIP download failed: ${errorMessage(err)}`);
546
+ archive.abort();
547
+ archive.destroy(err instanceof Error ? err : new Error(String(err)));
548
+ });
549
+ return archive;
550
+ }
551
+ // src/s3/buckets.ts
552
+ async function listBuckets(client) {
553
+ const buckets = [];
554
+ let token;
555
+ do {
556
+ const out = await client.send(new ListBucketsCommand({ ContinuationToken: token }));
557
+ for (const b of out.Buckets ?? []) {
558
+ if (!b.Name) continue;
559
+ buckets.push({
560
+ name: b.Name,
561
+ createdAt: b.CreationDate?.toISOString() ?? null,
562
+ region: b.BucketRegion ?? null
563
+ });
564
+ }
565
+ token = out.ContinuationToken;
566
+ } while (token);
567
+ return buckets.sort((a, b) => a.name.localeCompare(b.name));
568
+ }
569
+ async function headBucket(client, bucket) {
570
+ return client.send(new HeadBucketCommand({ Bucket: bucket }));
571
+ }
572
+ async function createBucket(client, name, region, defaultRegion) {
573
+ const r = region || defaultRegion;
574
+ const needsConstraint = r && r !== "us-east-1" && r !== "auto";
575
+ await client.send(new CreateBucketCommand({
576
+ Bucket: name,
577
+ CreateBucketConfiguration: needsConstraint ? { LocationConstraint: r } : void 0
578
+ }));
579
+ }
580
+ /** Removes every object (and, on versioned buckets, every version and delete marker). */
581
+ async function emptyBucket(client, bucket, versioned) {
582
+ if (!versioned) {
583
+ await deleteItemsUnderRoot(client, bucket);
584
+ return;
585
+ }
586
+ let keyMarker;
587
+ let versionMarker;
588
+ do {
589
+ const out = await client.send(new ListObjectVersionsCommand({
590
+ Bucket: bucket,
591
+ KeyMarker: keyMarker,
592
+ VersionIdMarker: versionMarker
593
+ }));
594
+ const objects = [...out.Versions ?? [], ...out.DeleteMarkers ?? []].filter((v) => v.Key).map((v) => ({
595
+ Key: v.Key,
596
+ VersionId: v.VersionId
597
+ }));
598
+ for (let i = 0; i < objects.length; i += MAX_DELETE_BATCH) await client.send(new DeleteObjectsCommand({
599
+ Bucket: bucket,
600
+ Delete: {
601
+ Objects: objects.slice(i, i + MAX_DELETE_BATCH),
602
+ Quiet: true
603
+ }
604
+ }));
605
+ keyMarker = out.IsTruncated ? out.NextKeyMarker : void 0;
606
+ versionMarker = out.IsTruncated ? out.NextVersionIdMarker : void 0;
607
+ } while (keyMarker);
608
+ }
609
+ async function deleteItemsUnderRoot(client, bucket) {
610
+ for await (const page of walkObjects(client, bucket, "")) await deleteKeys(client, bucket, page.map((o) => o.Key));
611
+ }
612
+ async function deleteBucket(client, bucket, force, caps) {
613
+ if (force) {
614
+ let versioned = false;
615
+ if (caps.versioning) try {
616
+ versioned = !!(await client.send(new GetBucketVersioningCommand({ Bucket: bucket }))).Status;
617
+ } catch (err) {
618
+ if (!isUnsupported(err)) throw err;
619
+ }
620
+ await emptyBucket(client, bucket, versioned);
621
+ }
622
+ await client.send(new DeleteBucketCommand({ Bucket: bucket }));
623
+ }
624
+ async function read(enabled, empty, fn) {
625
+ if (!enabled) return {
626
+ supported: false,
627
+ value: empty
628
+ };
629
+ try {
630
+ return {
631
+ supported: true,
632
+ value: await fn()
633
+ };
634
+ } catch (err) {
635
+ if (isNotConfigured(err)) return {
636
+ supported: true,
637
+ value: empty
638
+ };
639
+ if (isUnsupported(err)) return {
640
+ supported: false,
641
+ value: empty
642
+ };
643
+ return {
644
+ supported: true,
645
+ value: empty,
646
+ error: errorMessage(err)
647
+ };
648
+ }
649
+ }
650
+ async function getBucketSettings(client, bucket, caps) {
651
+ const [region, versioning, cors, lifecycle, policy, publicAccessBlock, encryption, objectLock] = await Promise.all([
652
+ client.send(new GetBucketLocationCommand({ Bucket: bucket })).then((o) => o.LocationConstraint || "us-east-1").catch(() => null),
653
+ read(caps.versioning, "Off", async () => {
654
+ return (await client.send(new GetBucketVersioningCommand({ Bucket: bucket }))).Status ?? "Off";
655
+ }),
656
+ read(caps.cors, [], async () => {
657
+ return (await client.send(new GetBucketCorsCommand({ Bucket: bucket }))).CORSRules ?? [];
658
+ }),
659
+ read(caps.lifecycle, [], async () => {
660
+ return (await client.send(new GetBucketLifecycleConfigurationCommand({ Bucket: bucket }))).Rules ?? [];
661
+ }),
662
+ read(caps.bucketPolicy, null, async () => {
663
+ const o = await client.send(new GetBucketPolicyCommand({ Bucket: bucket }));
664
+ return o.Policy ? JSON.parse(o.Policy) : null;
665
+ }),
666
+ read(caps.publicAccessBlock, null, async () => {
667
+ const c = (await client.send(new GetPublicAccessBlockCommand({ Bucket: bucket }))).PublicAccessBlockConfiguration ?? {};
668
+ return {
669
+ BlockPublicAcls: !!c.BlockPublicAcls,
670
+ IgnorePublicAcls: !!c.IgnorePublicAcls,
671
+ BlockPublicPolicy: !!c.BlockPublicPolicy,
672
+ RestrictPublicBuckets: !!c.RestrictPublicBuckets
673
+ };
674
+ }),
675
+ read(caps.encryption, null, async () => {
676
+ const rule = (await client.send(new GetBucketEncryptionCommand({ Bucket: bucket }))).ServerSideEncryptionConfiguration?.Rules?.[0];
677
+ const d = rule?.ApplyServerSideEncryptionByDefault;
678
+ return d?.SSEAlgorithm ? {
679
+ algorithm: d.SSEAlgorithm,
680
+ kmsKeyId: d.KMSMasterKeyID ?? null,
681
+ bucketKeyEnabled: !!rule?.BucketKeyEnabled
682
+ } : null;
683
+ }),
684
+ read(caps.objectLock, null, async () => {
685
+ const c = (await client.send(new GetObjectLockConfigurationCommand({ Bucket: bucket }))).ObjectLockConfiguration;
686
+ if (!c) return null;
687
+ const r = c.Rule?.DefaultRetention;
688
+ return {
689
+ enabled: c.ObjectLockEnabled === "Enabled",
690
+ mode: r?.Mode ?? null,
691
+ days: r?.Days ?? null,
692
+ years: r?.Years ?? null
693
+ };
694
+ })
695
+ ]);
696
+ return {
697
+ region,
698
+ versioning,
699
+ cors,
700
+ lifecycle,
701
+ policy,
702
+ publicAccessBlock,
703
+ encryption,
704
+ objectLock
705
+ };
706
+ }
707
+ async function setVersioning(client, bucket, enabled) {
708
+ await client.send(new PutBucketVersioningCommand({
709
+ Bucket: bucket,
710
+ VersioningConfiguration: { Status: enabled ? "Enabled" : "Suspended" }
711
+ }));
712
+ }
713
+ async function setCors(client, bucket, rules) {
714
+ if (rules.length === 0) {
715
+ await client.send(new DeleteBucketCorsCommand({ Bucket: bucket }));
716
+ return;
717
+ }
718
+ await client.send(new PutBucketCorsCommand({
719
+ Bucket: bucket,
720
+ CORSConfiguration: { CORSRules: rules }
721
+ }));
722
+ }
723
+ async function setLifecycle(client, bucket, rules) {
724
+ if (rules.length === 0) {
725
+ await client.send(new DeleteBucketLifecycleCommand({ Bucket: bucket }));
726
+ return;
727
+ }
728
+ const normalized = rules.map((r) => {
729
+ const rule = structuredClone(r);
730
+ if (typeof rule.Expiration?.Date === "string") rule.Expiration.Date = new Date(rule.Expiration.Date);
731
+ for (const t of rule.Transitions ?? []) if (typeof t.Date === "string") t.Date = new Date(t.Date);
732
+ return rule;
733
+ });
734
+ await client.send(new PutBucketLifecycleConfigurationCommand({
735
+ Bucket: bucket,
736
+ LifecycleConfiguration: { Rules: normalized }
737
+ }));
738
+ }
739
+ async function setPolicy(client, bucket, policy) {
740
+ if (policy === null) {
741
+ await client.send(new DeleteBucketPolicyCommand({ Bucket: bucket }));
742
+ return;
743
+ }
744
+ await client.send(new PutBucketPolicyCommand({
745
+ Bucket: bucket,
746
+ Policy: JSON.stringify(policy)
747
+ }));
748
+ }
749
+ async function setPublicAccessBlock(client, bucket, config) {
750
+ if (config === null) {
751
+ await client.send(new DeletePublicAccessBlockCommand({ Bucket: bucket }));
752
+ return;
753
+ }
754
+ await client.send(new PutPublicAccessBlockCommand({
755
+ Bucket: bucket,
756
+ PublicAccessBlockConfiguration: config
757
+ }));
758
+ }
759
+ // src/shared/schemas.ts
760
+ /** Any existing bucket name. Lenient, since legacy buckets may not follow today's rules. */
761
+ const bucketParamSchema = z.string().min(1).max(255);
762
+ /** Name for a bucket we create. Follows the S3 naming rules. */
763
+ const newBucketNameSchema = z.string().trim().min(3, "At least 3 characters").max(63, "At most 63 characters").regex(/^[a-z0-9][a-z0-9.-]*[a-z0-9]$/, "Lowercase letters, digits, dots and hyphens; start and end with a letter or digit").refine((v) => !/\.\.|\.-|-\./.test(v), "No adjacent dots, or dots next to hyphens").refine((v) => !/^\d{1,3}(\.\d{1,3}){3}$/.test(v), "Must not look like an IP address");
764
+ const objectKeySchema = z.string().min(1, "Key is required").refine((v) => new TextEncoder().encode(v).length <= 1024, "Keys are limited to 1,024 bytes");
765
+ const prefixSchema = z.string().refine((v) => new TextEncoder().encode(v).length <= 1024, "Prefix is limited to 1,024 bytes");
766
+ const regionSchema = z.string().trim().max(64).regex(/^[a-zA-Z0-9-]*$/, "Letters, digits and hyphens only");
767
+ const httpUrl = z.string().trim().refine((v) => {
768
+ try {
769
+ const u = new URL(v);
770
+ return (u.protocol === "http:" || u.protocol === "https:") && !u.username && !u.password;
771
+ } catch {
772
+ return false;
773
+ }
774
+ }, "Enter an http(s) URL, e.g. http://localhost:9000");
775
+ const loginSchema = z.object({
776
+ username: z.string().trim().min(1, "Username is required").max(128),
777
+ password: z.string().min(1, "Password is required").max(256)
778
+ });
779
+ const pathStyleSchema = z.enum([
780
+ "auto",
781
+ "path",
782
+ "virtual"
783
+ ]);
784
+ /** Credentials and endpoint a user enters in the browser. Sent once, kept server-side only. */
785
+ const connectionInputSchema = z.object({
786
+ label: z.string().trim().max(64).optional(),
787
+ endpoint: z.union([z.literal(""), httpUrl]).optional(),
788
+ region: regionSchema.optional(),
789
+ accessKeyId: z.string().trim().min(1, "Access key ID is required").max(256),
790
+ secretAccessKey: z.string().min(1, "Secret access key is required").max(1024),
791
+ sessionToken: z.string().trim().max(8192).optional(),
792
+ pathStyle: pathStyleSchema.optional(),
793
+ buckets: z.array(bucketParamSchema).max(50).optional(),
794
+ publicUrlBase: z.union([z.literal(""), httpUrl]).optional(),
795
+ /** Keep this connection (encrypted on the server) across restarts. */
796
+ remember: z.boolean().optional()
797
+ });
798
+ const listQuerySchema = z.object({
799
+ prefix: prefixSchema.default(""),
800
+ cursor: z.string().max(4096).optional(),
801
+ /** "1" lists every key under the prefix (no folders); used for search. */
802
+ flat: z.enum(["0", "1"]).default("0"),
803
+ limit: z.coerce.number().int().min(1).max(1e3).default(500)
804
+ });
805
+ const keyQuerySchema = z.object({
806
+ key: objectKeySchema,
807
+ versionId: z.string().max(1024).optional()
808
+ });
809
+ const downloadQuerySchema = keyQuerySchema.extend({ inline: z.enum(["0", "1"]).default("0") });
810
+ const prefixQuerySchema = z.object({ prefix: prefixSchema.default("") });
811
+ const uploadQuerySchema = z.object({
812
+ key: objectKeySchema,
813
+ contentType: z.string().max(255).optional()
814
+ });
815
+ const createFolderSchema = z.object({ prefix: prefixSchema.refine((v) => v.length > 0 && v.endsWith("/"), "Folder must end with \"/\"") });
816
+ const deleteSchema = z.object({
817
+ keys: z.array(objectKeySchema).max(1e5).default([]),
818
+ prefixes: z.array(prefixSchema.refine((v) => v.endsWith("/"), "Folders end with \"/\"")).max(1e3).default([])
819
+ }).refine((v) => v.keys.length + v.prefixes.length > 0, "Nothing to delete");
820
+ const summarySchema = z.object({
821
+ keys: z.array(objectKeySchema).max(1e5).default([]),
822
+ prefixes: z.array(prefixSchema).max(1e3).default([])
823
+ });
824
+ /** Copy or move. A source ending in "/" is a folder and copies everything under it. */
825
+ const copySchema = z.object({
826
+ destinationBucket: bucketParamSchema,
827
+ move: z.boolean().default(false),
828
+ items: z.array(z.object({
829
+ source: objectKeySchema,
830
+ destination: objectKeySchema
831
+ })).min(1).max(1e4)
832
+ }).refine((v) => v.items.every((i) => i.source.endsWith("/") === i.destination.endsWith("/")), "Folders must be copied to folders");
833
+ const presignSchema = z.object({
834
+ key: objectKeySchema,
835
+ method: z.enum(["GET", "PUT"]),
836
+ expiresIn: z.number().int().min(60).max(MAX_PRESIGN_SECONDS),
837
+ versionId: z.string().max(1024).optional(),
838
+ contentType: z.string().max(255).optional()
839
+ });
840
+ const headerValue = z.string().max(2048).regex(/^[^\r\n]*$/, "No line breaks");
841
+ const metaKey = z.string().min(1).max(128).regex(/^[a-zA-Z0-9-_]+$/, "Letters, digits, \"-\" and \"_\" only");
842
+ const metadataSchema = z.object({
843
+ keys: z.array(objectKeySchema).min(1).max(1e3),
844
+ /** Only the fields present are changed. Empty string clears the header. */
845
+ contentType: headerValue.optional(),
846
+ cacheControl: headerValue.optional(),
847
+ contentDisposition: headerValue.optional(),
848
+ contentEncoding: headerValue.optional(),
849
+ /** When present, replaces all x-amz-meta-* fields. */
850
+ metadata: z.record(metaKey, headerValue).optional()
851
+ });
852
+ const tagSchema = z.object({
853
+ Key: z.string().min(1).max(128),
854
+ Value: z.string().max(256)
855
+ });
856
+ const tagsSchema = z.object({
857
+ keys: z.array(objectKeySchema).min(1).max(1e3),
858
+ versionId: z.string().max(1024).optional(),
859
+ tags: z.array(tagSchema).max(10, `At most 10 tags`).refine((t) => new Set(t.map((x) => x.Key)).size === t.length, "Tag keys must be unique")
860
+ });
861
+ const versionActionSchema = z.object({
862
+ key: objectKeySchema,
863
+ versionId: z.string().min(1).max(1024)
864
+ });
865
+ const zipSchema = z.object({
866
+ /** Folder the selection lives in; ZIP entry names are relative to it. */
867
+ base: prefixSchema.default(""),
868
+ keys: z.array(objectKeySchema).max(1e5).default([]),
869
+ prefixes: z.array(prefixSchema).max(1e3).default([]),
870
+ name: z.string().max(200).optional()
871
+ });
872
+ const createBucketSchema = z.object({
873
+ name: newBucketNameSchema,
874
+ region: regionSchema.optional()
875
+ });
876
+ const deleteBucketQuerySchema = z.object({ force: z.enum(["0", "1"]).default("0") });
877
+ const versioningSchema = z.object({ enabled: z.boolean() });
878
+ const httpMethod = z.enum([
879
+ "GET",
880
+ "PUT",
881
+ "POST",
882
+ "DELETE",
883
+ "HEAD"
884
+ ]);
885
+ const corsRuleSchema = z.strictObject({
886
+ ID: z.string().max(255).optional(),
887
+ AllowedOrigins: z.array(z.string().min(1)).min(1, "AllowedOrigins needs at least one origin"),
888
+ AllowedMethods: z.array(httpMethod).min(1, "AllowedMethods needs at least one method"),
889
+ AllowedHeaders: z.array(z.string()).optional(),
890
+ ExposeHeaders: z.array(z.string()).optional(),
891
+ MaxAgeSeconds: z.number().int().min(0).optional()
892
+ });
893
+ const corsSchema = z.array(corsRuleSchema).max(100);
894
+ const lifecycleFilter = z.looseObject({
895
+ Prefix: z.string().optional(),
896
+ Tag: tagSchema.optional(),
897
+ ObjectSizeGreaterThan: z.number().int().min(0).optional(),
898
+ ObjectSizeLessThan: z.number().int().min(0).optional(),
899
+ And: z.looseObject({}).optional()
900
+ });
901
+ const lifecycleRuleSchema = z.looseObject({
902
+ ID: z.string().max(255).optional(),
903
+ Status: z.enum(["Enabled", "Disabled"]),
904
+ Filter: lifecycleFilter.optional(),
905
+ Prefix: z.string().optional(),
906
+ Expiration: z.looseObject({
907
+ Days: z.number().int().min(1).optional(),
908
+ Date: z.string().optional()
909
+ }).optional(),
910
+ Transitions: z.array(z.looseObject({ StorageClass: z.string() })).optional(),
911
+ NoncurrentVersionExpiration: z.looseObject({ NoncurrentDays: z.number().int().min(1).optional() }).optional(),
912
+ AbortIncompleteMultipartUpload: z.looseObject({ DaysAfterInitiation: z.number().int().min(1) }).optional()
913
+ });
914
+ const lifecycleSchema = z.array(lifecycleRuleSchema).max(1e3);
915
+ const policySchema = z.looseObject({
916
+ Version: z.string().optional(),
917
+ Statement: z.array(z.looseObject({ Effect: z.enum(["Allow", "Deny"]) })).min(1, "A policy needs at least one statement")
918
+ }).nullable();
919
+ const publicAccessBlockSchema = z.strictObject({
920
+ BlockPublicAcls: z.boolean(),
921
+ IgnorePublicAcls: z.boolean(),
922
+ BlockPublicPolicy: z.boolean(),
923
+ RestrictPublicBuckets: z.boolean()
924
+ });
925
+ const roleSchema = z.enum([
926
+ "viewer",
927
+ "editor",
928
+ "admin"
929
+ ]);
930
+ const usernameSchema = z.string().trim().min(2, "At least 2 characters").max(128).regex(/^[A-Za-z0-9._@+-]+$/, "Letters, digits and . _ @ + - only");
931
+ const passwordSchema = z.string().min(10, "At least 10 characters").max(256);
932
+ const createUserSchema = z.object({
933
+ username: usernameSchema,
934
+ password: passwordSchema.optional(),
935
+ role: roleSchema
936
+ });
937
+ const updateUserSchema = z.object({
938
+ role: roleSchema.optional(),
939
+ disabled: z.boolean().optional(),
940
+ password: passwordSchema.optional()
941
+ }).refine((v) => Object.keys(v).length > 0, "Nothing to change");
942
+ const activityQuerySchema = z.object({
943
+ user: z.string().max(128).optional(),
944
+ bucket: z.string().max(255).optional(),
945
+ limit: z.coerce.number().int().min(1).max(2e3).default(200)
946
+ });
947
+ const multipartCreateSchema = z.object({
948
+ key: objectKeySchema.refine((k) => !k.endsWith("/"), "File keys must not end with \"/\""),
949
+ contentType: z.string().max(255).optional()
950
+ });
951
+ const multipartRefSchema = z.object({
952
+ key: objectKeySchema,
953
+ uploadId: z.string().min(1).max(1024)
954
+ });
955
+ const multipartPartQuerySchema = multipartRefSchema.extend({ partNumber: z.coerce.number().int().min(1).max(1e4) });
956
+ const multipartCompleteSchema = multipartRefSchema.extend({ parts: z.array(z.object({
957
+ PartNumber: z.number().int().min(1).max(1e4),
958
+ ETag: z.string().min(1).max(256)
959
+ })).min(1).max(1e4) });
960
+ const storageClassSchema = z.object({
961
+ keys: z.array(objectKeySchema).min(1).max(1e3),
962
+ storageClass: z.string().regex(/^[A-Z_]+$/, "Unknown storage class").max(64)
963
+ });
964
+ const restoreArchiveSchema = z.object({
965
+ keys: z.array(objectKeySchema).min(1).max(1e3),
966
+ days: z.number().int().min(1).max(365),
967
+ tier: z.enum([
968
+ "Expedited",
969
+ "Standard",
970
+ "Bulk"
971
+ ])
972
+ });
973
+ const deletedQuerySchema = z.object({
974
+ prefix: prefixSchema.default(""),
975
+ cursor: z.string().max(4096).optional()
976
+ });
977
+ const locationSchema = z.object({
978
+ connectionId: z.string().min(1).max(128),
979
+ bucket: bucketParamSchema,
980
+ prefix: prefixSchema.default("")
981
+ });
982
+ const compareSchema = z.object({
983
+ source: locationSchema,
984
+ target: locationSchema
985
+ });
986
+ const syncSchema = compareSchema.extend({
987
+ /** "copy": copy missing and changed objects. "mirror": also delete objects only in the target. */
988
+ mode: z.enum(["copy", "mirror"]) });
989
+ /** Turns a zod error into a short, readable message. */
990
+ function formatZodError(error) {
991
+ return error.issues.slice(0, 5).map((i) => i.path.length ? `${i.path.map(String).join(".")}: ${i.message}` : i.message).join("; ");
992
+ }
993
+ // src/server/errors.ts
994
+ var HttpError = class extends Error {
995
+ status;
996
+ code;
997
+ constructor(status, code, message) {
998
+ super(message);
999
+ this.status = status;
1000
+ this.code = code;
1001
+ }
1002
+ };
1003
+ const S3_STATUS = {
1004
+ NoSuchBucket: 404,
1005
+ NoSuchKey: 404,
1006
+ NoSuchVersion: 404,
1007
+ NotFound: 404,
1008
+ AccessDenied: 403,
1009
+ InvalidAccessKeyId: 400,
1010
+ SignatureDoesNotMatch: 400,
1011
+ ExpiredToken: 400,
1012
+ BucketNotEmpty: 409,
1013
+ BucketAlreadyExists: 409,
1014
+ BucketAlreadyOwnedByYou: 409,
1015
+ InvalidBucketName: 400,
1016
+ InvalidArgument: 400,
1017
+ InvalidRequest: 400,
1018
+ MalformedXML: 400,
1019
+ MalformedPolicy: 400,
1020
+ NotImplemented: 501,
1021
+ InvalidObjectState: 409,
1022
+ NoSuchUpload: 404,
1023
+ EntityTooSmall: 400,
1024
+ InvalidPart: 400
1025
+ };
1026
+ function toErrorResponse(err) {
1027
+ if (err instanceof HttpError) return {
1028
+ status: err.status,
1029
+ body: { error: {
1030
+ code: err.code,
1031
+ message: err.message
1032
+ } }
1033
+ };
1034
+ if (err instanceof UserError) return {
1035
+ status: 400,
1036
+ body: { error: {
1037
+ code: "BAD_REQUEST",
1038
+ message: err.message
1039
+ } }
1040
+ };
1041
+ if (err instanceof ZodError) return {
1042
+ status: 400,
1043
+ body: { error: {
1044
+ code: "VALIDATION",
1045
+ message: formatZodError(err)
1046
+ } }
1047
+ };
1048
+ if (err instanceof Error && err.name === "CredentialsProviderError") return {
1049
+ status: 400,
1050
+ body: { error: {
1051
+ code: "CREDENTIALS",
1052
+ message: err.message
1053
+ } }
1054
+ };
1055
+ const code = errorCode(err);
1056
+ const httpStatus = errorStatus(err);
1057
+ if (httpStatus || code in S3_STATUS) {
1058
+ let status = S3_STATUS[code] ?? (httpStatus && httpStatus >= 400 && httpStatus < 600 ? httpStatus : 502);
1059
+ if (status === 401) status = 400;
1060
+ return {
1061
+ status,
1062
+ body: { error: {
1063
+ code,
1064
+ message: errorMessage(err)
1065
+ } }
1066
+ };
1067
+ }
1068
+ if (err instanceof Error && (err.name === "AbortError" || err.name === "TimeoutError")) return {
1069
+ status: 499,
1070
+ body: { error: {
1071
+ code: "ABORTED",
1072
+ message: "Request was cancelled"
1073
+ } }
1074
+ };
1075
+ const sysCode = err?.code;
1076
+ if (sysCode && /^E[A-Z]+$/.test(sysCode)) return {
1077
+ status: 502,
1078
+ body: { error: {
1079
+ code: sysCode,
1080
+ message: `Can't reach the storage endpoint (${sysCode})`
1081
+ } }
1082
+ };
1083
+ return {
1084
+ status: 500,
1085
+ body: { error: {
1086
+ code: "INTERNAL",
1087
+ message: errorMessage(err)
1088
+ } }
1089
+ };
1090
+ }
1091
+ function onError(err, c) {
1092
+ const { status, body } = toErrorResponse(err);
1093
+ if (status >= 500 && status !== 501) console.error(` ${c.req.method} ${c.req.path} failed:`, err);
1094
+ return c.json(body, status);
1095
+ }
1096
+ // src/server/connections.ts
1097
+ function maskKey(id) {
1098
+ if (!id) return null;
1099
+ if (id.length <= 8) return "••••";
1100
+ return `${id.slice(0, 4)}…${id.slice(-4)}`;
1101
+ }
1102
+ function connectionInfo(c) {
1103
+ return {
1104
+ id: c.id,
1105
+ label: c.label,
1106
+ provider: c.provider.id,
1107
+ providerName: c.provider.name,
1108
+ endpoint: c.endpoint,
1109
+ region: c.region,
1110
+ pathStyle: c.handle.forcePathStyle,
1111
+ source: c.source,
1112
+ accessKeyHint: c.accessKeyHint,
1113
+ pinnedBuckets: c.pinnedBuckets,
1114
+ publicUrlBase: c.publicUrlBase,
1115
+ capabilities: c.provider.capabilities
1116
+ };
1117
+ }
1118
+ /**
1119
+ * Builds a client and checks the credentials work: ListBuckets, or HeadBucket on the
1120
+ * pinned buckets when the key isn't allowed to list.
1121
+ */
1122
+ async function openConnection(spec) {
1123
+ const handle = createS3Client(spec);
1124
+ let bucketCount = null;
1125
+ try {
1126
+ bucketCount = (await handle.client.send(new ListBucketsCommand({}))).Buckets?.length ?? 0;
1127
+ } catch (err) {
1128
+ if (!isAccessDenied(err) || spec.pinnedBuckets.length === 0) {
1129
+ handle.client.destroy();
1130
+ throw err;
1131
+ }
1132
+ try {
1133
+ await headBucket(handle.client, spec.pinnedBuckets[0]);
1134
+ } catch (headErr) {
1135
+ handle.client.destroy();
1136
+ throw headErr;
1137
+ }
1138
+ }
1139
+ handle.provider = refineProvider(handle.provider, handle.serverHeader());
1140
+ return {
1141
+ bucketCount,
1142
+ connection: buildConnection(spec, handle)
1143
+ };
1144
+ }
1145
+ function defaultLabel(spec, providerName) {
1146
+ return spec.label?.trim() || (spec.endpoint ? `${providerName} · ${new URL(spec.endpoint).host}` : `${providerName} · ${spec.region}`);
1147
+ }
1148
+ function buildConnection(spec, handle) {
1149
+ const provider = handle.provider;
1150
+ return {
1151
+ id: spec.id ?? (spec.source === "cli" ? "default" : randomUUID()),
1152
+ label: defaultLabel(spec, provider.name),
1153
+ source: spec.source,
1154
+ ownerSessionId: spec.ownerSessionId,
1155
+ ownerUser: spec.ownerUser,
1156
+ handle,
1157
+ provider,
1158
+ endpoint: spec.endpoint || null,
1159
+ region: spec.region,
1160
+ accessKeyHint: maskKey(spec.accessKeyId),
1161
+ pinnedBuckets: spec.pinnedBuckets,
1162
+ publicUrlBase: spec.publicUrlBase || null
1163
+ };
1164
+ }
1165
+ /** Rebuilds a remembered connection without probing it (that happens on first use). */
1166
+ function connectionFromSaved(item) {
1167
+ const spec = {
1168
+ id: item.id,
1169
+ source: "saved",
1170
+ ownerUser: item.owner,
1171
+ label: item.label,
1172
+ endpoint: item.endpoint,
1173
+ region: item.region,
1174
+ pathStyle: item.pathStyle,
1175
+ accessKeyId: item.accessKeyId,
1176
+ credentials: {
1177
+ accessKeyId: item.accessKeyId,
1178
+ secretAccessKey: item.secretAccessKey,
1179
+ sessionToken: item.sessionToken
1180
+ },
1181
+ pinnedBuckets: item.buckets,
1182
+ publicUrlBase: item.publicUrlBase
1183
+ };
1184
+ return buildConnection(spec, createS3Client(spec));
1185
+ }
1186
+ const MAX_BROWSER_CONNECTIONS_PER_SESSION = 10;
1187
+ /**
1188
+ * All live connections. The startup ("cli") connection is shared by every session;
1189
+ * connections added from the browser belong to the session that added them.
1190
+ */
1191
+ var ConnectionRegistry = class {
1192
+ connections = /* @__PURE__ */ new Map();
1193
+ defaultId = null;
1194
+ setDefault(c) {
1195
+ this.connections.set(c.id, c);
1196
+ this.defaultId = c.id;
1197
+ }
1198
+ /** Adds a connection owned by a session or user. */
1199
+ add(c) {
1200
+ this.connections.set(c.id, c);
1201
+ }
1202
+ addForSession(c) {
1203
+ if ([...this.connections.values()].filter((x) => c.ownerSessionId && x.ownerSessionId === c.ownerSessionId || c.ownerUser && x.ownerUser === c.ownerUser).length >= MAX_BROWSER_CONNECTIONS_PER_SESSION) {
1204
+ c.handle.client.destroy();
1205
+ throw new HttpError(400, "TOO_MANY_CONNECTIONS", `At most ${MAX_BROWSER_CONNECTIONS_PER_SESSION} connections per session`);
1206
+ }
1207
+ this.connections.set(c.id, c);
1208
+ }
1209
+ visible(c, session) {
1210
+ if (c.source === "cli") return true;
1211
+ if (c.source === "browser") return c.ownerSessionId === session.id;
1212
+ return c.ownerUser === session.user;
1213
+ }
1214
+ /** Returns the connection if this session may use it. */
1215
+ getForSession(id, session) {
1216
+ if (!id) return null;
1217
+ const c = this.connections.get(id);
1218
+ return c && this.visible(c, session) ? c : null;
1219
+ }
1220
+ listForSession(session) {
1221
+ const order = {
1222
+ cli: 0,
1223
+ saved: 1,
1224
+ browser: 2
1225
+ };
1226
+ return [...this.connections.values()].filter((c) => this.visible(c, session)).sort((a, b) => order[a.source] - order[b.source]);
1227
+ }
1228
+ remove(id) {
1229
+ const c = this.connections.get(id);
1230
+ if (!c) return;
1231
+ this.connections.delete(id);
1232
+ c.handle.client.destroy();
1233
+ }
1234
+ removeOwnedBy(sessionId) {
1235
+ for (const c of [...this.connections.values()]) if (c.ownerSessionId === sessionId) this.remove(c.id);
1236
+ }
1237
+ };
1238
+ // src/server/jobs.ts
1239
+ const KEEP_FINISHED_MS = 864e5;
1240
+ /** Background jobs (sync) with live progress. In memory: they stop if s3deck restarts. */
1241
+ var JobRegistry = class {
1242
+ jobs = /* @__PURE__ */ new Map();
1243
+ start(owner, title, run) {
1244
+ this.sweep();
1245
+ const job = {
1246
+ id: randomUUID(),
1247
+ type: "sync",
1248
+ owner,
1249
+ title,
1250
+ status: "running",
1251
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
1252
+ finishedAt: null,
1253
+ total: 0,
1254
+ done: 0,
1255
+ bytesDone: 0,
1256
+ bytesTotal: 0,
1257
+ errors: [],
1258
+ controller: new AbortController()
1259
+ };
1260
+ this.jobs.set(job.id, job);
1261
+ run(job.controller.signal, job).then(() => {
1262
+ job.status = job.controller.signal.aborted ? "cancelled" : "done";
1263
+ }).catch((err) => {
1264
+ job.status = job.controller.signal.aborted ? "cancelled" : "failed";
1265
+ if (!job.controller.signal.aborted) job.errors.push({
1266
+ key: "",
1267
+ message: errorMessage(err)
1268
+ });
1269
+ }).finally(() => {
1270
+ job.finishedAt = (/* @__PURE__ */ new Date()).toISOString();
1271
+ if (job.errors.length > 500) job.errors.length = 500;
1272
+ });
1273
+ return this.info(job);
1274
+ }
1275
+ info(job) {
1276
+ const { controller: _c, ...rest } = job;
1277
+ return {
1278
+ ...rest,
1279
+ errors: rest.errors.slice(0, 100)
1280
+ };
1281
+ }
1282
+ list(owner) {
1283
+ return [...this.jobs.values()].filter((j) => owner === null || j.owner === owner).sort((a, b) => b.startedAt.localeCompare(a.startedAt)).map((j) => this.info(j));
1284
+ }
1285
+ get(id, owner) {
1286
+ const j = this.jobs.get(id);
1287
+ return j && (owner === null || j.owner === owner) ? this.info(j) : null;
1288
+ }
1289
+ cancel(id, owner) {
1290
+ const j = this.jobs.get(id);
1291
+ if (!j || owner !== null && j.owner !== owner || j.status !== "running") return false;
1292
+ j.controller.abort();
1293
+ return true;
1294
+ }
1295
+ sweep() {
1296
+ const now = Date.now();
1297
+ for (const [id, j] of this.jobs) if (j.finishedAt && now - Date.parse(j.finishedAt) > KEEP_FINISHED_MS) this.jobs.delete(id);
1298
+ }
1299
+ };
1300
+ // src/server/sso.ts
1301
+ /** SSO settings from the environment, or null when not configured. */
1302
+ function ssoConfigFromEnv(env = process.env) {
1303
+ const issuer = env.S3DECK_OIDC_ISSUER;
1304
+ const clientId = env.S3DECK_OIDC_CLIENT_ID;
1305
+ if (!issuer || !clientId) return null;
1306
+ const role = env.S3DECK_OIDC_DEFAULT_ROLE;
1307
+ return {
1308
+ issuer,
1309
+ clientId,
1310
+ clientSecret: env.S3DECK_OIDC_CLIENT_SECRET || void 0,
1311
+ label: env.S3DECK_OIDC_LABEL || "Sign in with SSO",
1312
+ allow: (env.S3DECK_OIDC_ALLOW ?? "").split(/[\s,]+/).map((s) => s.trim().toLowerCase()).filter(Boolean),
1313
+ defaultRole: role === "editor" || role === "admin" ? role : "viewer"
1314
+ };
1315
+ }
1316
+ const PENDING_TTL_MS = 6e5;
1317
+ /** OpenID Connect sign-in (authorization code flow with PKCE). */
1318
+ var SsoService = class {
1319
+ config;
1320
+ configuration = null;
1321
+ pending = /* @__PURE__ */ new Map();
1322
+ constructor(config) {
1323
+ this.config = config;
1324
+ }
1325
+ discover() {
1326
+ this.configuration ??= oidc.discovery(new URL(this.config.issuer), this.config.clientId, this.config.clientSecret).catch((err) => {
1327
+ this.configuration = null;
1328
+ throw err;
1329
+ });
1330
+ return this.configuration;
1331
+ }
1332
+ /** Whether someone not in users.json may sign in, and with which role. */
1333
+ defaultRoleFor(email) {
1334
+ const e = email.toLowerCase();
1335
+ const domain = e.slice(e.indexOf("@"));
1336
+ return this.config.allow.includes(e) || this.config.allow.includes(domain) ? this.config.defaultRole : null;
1337
+ }
1338
+ async authorizationUrl(redirectUri) {
1339
+ const config = await this.discover();
1340
+ this.sweep();
1341
+ const verifier = oidc.randomPKCECodeVerifier();
1342
+ const state = oidc.randomState();
1343
+ const nonce = oidc.randomNonce();
1344
+ this.pending.set(state, {
1345
+ verifier,
1346
+ nonce,
1347
+ redirectUri,
1348
+ createdAt: Date.now()
1349
+ });
1350
+ return oidc.buildAuthorizationUrl(config, {
1351
+ redirect_uri: redirectUri,
1352
+ scope: "openid email profile",
1353
+ code_challenge: await oidc.calculatePKCECodeChallenge(verifier),
1354
+ code_challenge_method: "S256",
1355
+ state,
1356
+ nonce
1357
+ }).toString();
1358
+ }
1359
+ /** Exchanges the code for tokens and returns the verified email. */
1360
+ async finish(callbackUrl) {
1361
+ const state = callbackUrl.searchParams.get("state") ?? "";
1362
+ const pending = this.pending.get(state);
1363
+ this.pending.delete(state);
1364
+ if (!pending || Date.now() - pending.createdAt > PENDING_TTL_MS) throw new Error("Sign-in expired. Please try again.");
1365
+ const config = await this.discover();
1366
+ const claims = (await oidc.authorizationCodeGrant(config, callbackUrl, {
1367
+ pkceCodeVerifier: pending.verifier,
1368
+ expectedState: state,
1369
+ expectedNonce: pending.nonce
1370
+ })).claims();
1371
+ const email = typeof claims?.email === "string" ? claims.email : null;
1372
+ if (!email) throw new Error("The identity provider did not share an email address.");
1373
+ if (claims?.email_verified === false) throw new Error("Your email address is not verified with the identity provider.");
1374
+ return {
1375
+ email,
1376
+ name: typeof claims?.name === "string" ? claims.name : null
1377
+ };
1378
+ }
1379
+ sweep() {
1380
+ const now = Date.now();
1381
+ for (const [k, v] of this.pending) if (now - v.createdAt > PENDING_TTL_MS) this.pending.delete(k);
1382
+ }
1383
+ };
1384
+ // src/server/store/files.ts
1385
+ /** Where s3deck keeps users, remembered connections, its secret key and the activity log. */
1386
+ function resolveDataDir(explicit) {
1387
+ if (explicit) return path.resolve(explicit);
1388
+ if (process.env.S3DECK_DATA_DIR) return path.resolve(process.env.S3DECK_DATA_DIR);
1389
+ const base = process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
1390
+ return path.join(base, "s3deck");
1391
+ }
1392
+ async function ensureDir(dir) {
1393
+ await mkdir(dir, {
1394
+ recursive: true,
1395
+ mode: 448
1396
+ });
1397
+ }
1398
+ async function readJson(file, fallback) {
1399
+ try {
1400
+ return JSON.parse(await readFile(file, "utf8"));
1401
+ } catch (err) {
1402
+ if (err.code === "ENOENT") return fallback;
1403
+ throw err;
1404
+ }
1405
+ }
1406
+ /** Writes via a temp file + rename, so a crash never leaves a half-written file. Owner-only permissions. */
1407
+ async function writeFileAtomic(file, data) {
1408
+ await ensureDir(path.dirname(file));
1409
+ const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
1410
+ await writeFile(tmp, data, { mode: 384 });
1411
+ await rename(tmp, file);
1412
+ await chmod(file, 384).catch(() => {});
1413
+ }
1414
+ function writeJsonAtomic(file, value) {
1415
+ return writeFileAtomic(file, `${JSON.stringify(value, null, 2)}\n`);
1416
+ }
1417
+ // src/server/store/activity.ts
1418
+ const MAX_MEMORY = 2e3;
1419
+ const MAX_FILE_BYTES = 0xa00000;
1420
+ /** Append-only log of changes (activity.jsonl, rotated at 10 MB) plus the latest entries in memory. */
1421
+ var ActivityLog = class {
1422
+ dataDir;
1423
+ recent = [];
1424
+ seq = 0;
1425
+ writing = Promise.resolve();
1426
+ constructor(dataDir) {
1427
+ this.dataDir = dataDir;
1428
+ }
1429
+ /** Loads the most recent entries from disk, so the log survives restarts. */
1430
+ async load() {
1431
+ if (!this.dataDir) return;
1432
+ const lines = [];
1433
+ for (const name of ["activity.jsonl.1", "activity.jsonl"]) try {
1434
+ lines.push(...(await readFile(path.join(this.dataDir, name), "utf8")).split("\n").filter(Boolean));
1435
+ } catch {}
1436
+ const entries = [];
1437
+ for (const line of lines.slice(-2e3)) try {
1438
+ entries.push(JSON.parse(line));
1439
+ } catch {}
1440
+ this.recent = entries.reverse();
1441
+ }
1442
+ record(entry) {
1443
+ const full = {
1444
+ id: `${Date.now().toString(36)}-${(++this.seq).toString(36)}`,
1445
+ at: (/* @__PURE__ */ new Date()).toISOString(),
1446
+ ...entry
1447
+ };
1448
+ this.recent.unshift(full);
1449
+ if (this.recent.length > MAX_MEMORY) this.recent.length = MAX_MEMORY;
1450
+ if (this.dataDir) {
1451
+ const dir = this.dataDir;
1452
+ this.writing = this.writing.then(() => this.append(dir, full)).catch(() => {});
1453
+ }
1454
+ }
1455
+ async append(dir, entry) {
1456
+ const file = path.join(dir, "activity.jsonl");
1457
+ await ensureDir(dir);
1458
+ try {
1459
+ if ((await stat(file)).size > MAX_FILE_BYTES) await rename(file, `${file}.1`);
1460
+ } catch {}
1461
+ await appendFile(file, `${JSON.stringify(entry)}\n`, { mode: 384 });
1462
+ }
1463
+ list(filter) {
1464
+ return this.recent.filter((e) => (!filter.user || e.user === filter.user) && (!filter.bucket || e.bucket === filter.bucket)).slice(0, filter.limit);
1465
+ }
1466
+ };
1467
+ // src/server/store/crypto.ts
1468
+ const ALGO = "aes-256-gcm";
1469
+ /**
1470
+ * The key that encrypts data at rest. From S3DECK_SECRET if set (derived with scrypt),
1471
+ * otherwise a random key generated once and kept in <data-dir>/secret.key (mode 0600).
1472
+ */
1473
+ async function loadSecretKey(dataDir, secret = process.env.S3DECK_SECRET) {
1474
+ if (secret) return scryptSync(secret, "s3deck-at-rest-v1", 32);
1475
+ const file = path.join(dataDir, "secret.key");
1476
+ try {
1477
+ const key = Buffer.from((await readFile(file, "utf8")).trim(), "base64");
1478
+ if (key.length === 32) return key;
1479
+ throw new Error(`${file} is not a valid key`);
1480
+ } catch (err) {
1481
+ if (err.code !== "ENOENT") throw err;
1482
+ const key = randomBytes(32);
1483
+ await writeFileAtomic(file, `${key.toString("base64")}\n`);
1484
+ return key;
1485
+ }
1486
+ }
1487
+ function seal(key, value) {
1488
+ const iv = randomBytes(12);
1489
+ const cipher = createCipheriv(ALGO, key, iv);
1490
+ const data = Buffer.concat([cipher.update(JSON.stringify(value), "utf8"), cipher.final()]);
1491
+ return {
1492
+ v: 1,
1493
+ iv: iv.toString("base64"),
1494
+ tag: cipher.getAuthTag().toString("base64"),
1495
+ data: data.toString("base64")
1496
+ };
1497
+ }
1498
+ function unseal(key, sealed) {
1499
+ const decipher = createDecipheriv(ALGO, key, Buffer.from(sealed.iv, "base64"));
1500
+ decipher.setAuthTag(Buffer.from(sealed.tag, "base64"));
1501
+ const plain = Buffer.concat([decipher.update(Buffer.from(sealed.data, "base64")), decipher.final()]);
1502
+ return JSON.parse(plain.toString("utf8"));
1503
+ }
1504
+ // src/server/store/saved-connections.ts
1505
+ /** <data-dir>/connections.enc: every remembered connection, sealed with AES-256-GCM. */
1506
+ var SavedConnectionStore = class {
1507
+ key;
1508
+ items = [];
1509
+ file;
1510
+ constructor(dataDir, key) {
1511
+ this.key = key;
1512
+ this.file = path.join(dataDir, "connections.enc");
1513
+ }
1514
+ async load() {
1515
+ const sealed = await readJson(this.file, null);
1516
+ this.items = sealed ? unseal(this.key, sealed) : [];
1517
+ }
1518
+ all() {
1519
+ return this.items;
1520
+ }
1521
+ async add(item) {
1522
+ this.items = [...this.items.filter((i) => i.id !== item.id), item];
1523
+ await writeJsonAtomic(this.file, seal(this.key, this.items));
1524
+ }
1525
+ async remove(id) {
1526
+ const before = this.items.length;
1527
+ this.items = this.items.filter((i) => i.id !== id);
1528
+ if (this.items.length !== before) await writeJsonAtomic(this.file, seal(this.key, this.items));
1529
+ }
1530
+ };
1531
+ // src/server/store/users.ts
1532
+ const scrypt = promisify(scrypt$1);
1533
+ async function hashPassword(password) {
1534
+ const salt = randomBytes(16);
1535
+ const hash = await scrypt(password, salt, 32);
1536
+ return `scrypt$${salt.toString("base64")}$${hash.toString("base64")}`;
1537
+ }
1538
+ async function verifyPassword(password, stored) {
1539
+ if (!stored) return false;
1540
+ const [algo, salt, hash] = stored.split("$");
1541
+ if (algo !== "scrypt" || !salt || !hash) return false;
1542
+ const expected = Buffer.from(hash, "base64");
1543
+ const actual = await scrypt(password, Buffer.from(salt, "base64"), expected.length);
1544
+ return timingSafeEqual(actual, expected);
1545
+ }
1546
+ /** Users kept in <data-dir>/users.json. Usernames are case-insensitive. */
1547
+ var UserStore = class {
1548
+ users = /* @__PURE__ */ new Map();
1549
+ file;
1550
+ constructor(dataDir) {
1551
+ this.file = path.join(dataDir, "users.json");
1552
+ }
1553
+ async load() {
1554
+ const list = await readJson(this.file, []);
1555
+ this.users = new Map(list.map((u) => [u.username.toLowerCase(), u]));
1556
+ }
1557
+ persist() {
1558
+ return writeJsonAtomic(this.file, [...this.users.values()]);
1559
+ }
1560
+ list() {
1561
+ return [...this.users.values()].sort((a, b) => a.username.localeCompare(b.username));
1562
+ }
1563
+ get(username) {
1564
+ return this.users.get(username.toLowerCase());
1565
+ }
1566
+ async create(input) {
1567
+ const record = {
1568
+ username: input.username,
1569
+ passwordHash: input.password ? await hashPassword(input.password) : null,
1570
+ role: input.role,
1571
+ disabled: false,
1572
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
1573
+ };
1574
+ this.users.set(input.username.toLowerCase(), record);
1575
+ await this.persist();
1576
+ return record;
1577
+ }
1578
+ async update(username, patch) {
1579
+ const u = this.get(username);
1580
+ if (!u) return void 0;
1581
+ if (patch.role) u.role = patch.role;
1582
+ if (patch.disabled !== void 0) u.disabled = patch.disabled;
1583
+ if (patch.password) u.passwordHash = await hashPassword(patch.password);
1584
+ await this.persist();
1585
+ return u;
1586
+ }
1587
+ async remove(username) {
1588
+ const ok = this.users.delete(username.toLowerCase());
1589
+ if (ok) await this.persist();
1590
+ return ok;
1591
+ }
1592
+ };
1593
+ // src/server/middleware/rate-limit.ts
1594
+ /** Fixed-window counter per client address (used for failed logins). */
1595
+ var RateLimiter = class {
1596
+ max;
1597
+ windowMs;
1598
+ hits = /* @__PURE__ */ new Map();
1599
+ constructor(max, windowMs) {
1600
+ this.max = max;
1601
+ this.windowMs = windowMs;
1602
+ }
1603
+ /** Seconds until the client may try again, or 0 if allowed. */
1604
+ retryAfter(key) {
1605
+ const b = this.hits.get(key);
1606
+ if (!b || b.resetAt <= Date.now()) return 0;
1607
+ return b.count >= this.max ? Math.ceil((b.resetAt - Date.now()) / 1e3) : 0;
1608
+ }
1609
+ hit(key) {
1610
+ const now = Date.now();
1611
+ let b = this.hits.get(key);
1612
+ if (!b || b.resetAt <= now) {
1613
+ b = {
1614
+ count: 0,
1615
+ resetAt: now + this.windowMs
1616
+ };
1617
+ this.hits.set(key, b);
1618
+ }
1619
+ b.count++;
1620
+ if (this.hits.size > 1e4) {
1621
+ for (const [k, v] of this.hits) if (v.resetAt <= now) this.hits.delete(k);
1622
+ }
1623
+ }
1624
+ reset(key) {
1625
+ this.hits.delete(key);
1626
+ }
1627
+ };
1628
+ // src/server/sessions.ts
1629
+ const IDLE_TIMEOUT_MS = 432e5;
1630
+ const MAX_AGE_MS = 6048e5;
1631
+ /** In-memory sessions. Restarting s3deck logs everyone out. */
1632
+ var SessionStore = class {
1633
+ sessions = /* @__PURE__ */ new Map();
1634
+ listeners = [];
1635
+ timer;
1636
+ constructor() {
1637
+ this.timer = setInterval(() => this.sweep(), 6e5);
1638
+ this.timer.unref();
1639
+ }
1640
+ /** Called whenever a session ends (logout or expiry). */
1641
+ onDestroy(fn) {
1642
+ this.listeners.push(fn);
1643
+ }
1644
+ create(user, source, role, activeConnectionId) {
1645
+ const now = Date.now();
1646
+ const session = {
1647
+ id: randomBytes(32).toString("base64url"),
1648
+ user,
1649
+ source,
1650
+ role,
1651
+ createdAt: now,
1652
+ lastSeen: now,
1653
+ activeConnectionId
1654
+ };
1655
+ this.sessions.set(session.id, session);
1656
+ return session;
1657
+ }
1658
+ get(id) {
1659
+ if (!id) return null;
1660
+ const s = this.sessions.get(id);
1661
+ if (!s) return null;
1662
+ const now = Date.now();
1663
+ if (now - s.lastSeen > IDLE_TIMEOUT_MS || now - s.createdAt > MAX_AGE_MS) {
1664
+ this.destroy(id);
1665
+ return null;
1666
+ }
1667
+ s.lastSeen = now;
1668
+ return s;
1669
+ }
1670
+ destroy(id) {
1671
+ const s = this.sessions.get(id);
1672
+ if (!s) return;
1673
+ this.sessions.delete(id);
1674
+ for (const fn of this.listeners) fn(s);
1675
+ }
1676
+ /** Points every session at `to` when connection `from` goes away. */
1677
+ reassign(from, to) {
1678
+ for (const s of this.sessions.values()) if (s.activeConnectionId === from) s.activeConnectionId = to;
1679
+ }
1680
+ sweep() {
1681
+ for (const id of [...this.sessions.keys()]) this.get(id);
1682
+ }
1683
+ close() {
1684
+ clearInterval(this.timer);
1685
+ }
1686
+ };
1687
+ // src/server/middleware/index.ts
1688
+ /** Header the UI may send to run a request against a specific connection (e.g. a running upload). */
1689
+ const CONNECTION_HEADER = "x-s3deck-connection";
1690
+ const RANK = {
1691
+ viewer: 0,
1692
+ editor: 1,
1693
+ admin: 2
1694
+ };
1695
+ function hasRole(role, min) {
1696
+ return RANK[role] >= RANK[min];
1697
+ }
1698
+ /**
1699
+ * The role a session has right now, or null if it should end (user removed or disabled).
1700
+ * Startup-admin and anonymous (--no-auth) sessions are admins.
1701
+ */
1702
+ function resolveRole(ctx, s) {
1703
+ if (s.source === "bootstrap" || s.source === "anonymous") return "admin";
1704
+ const record = ctx.users?.get(s.user);
1705
+ if (record) return record.disabled ? null : record.role;
1706
+ if (s.source === "sso") return ctx.sso?.defaultRoleFor(s.user) ?? null;
1707
+ return null;
1708
+ }
1709
+ const SAFE_METHODS = /* @__PURE__ */ new Set([
1710
+ "GET",
1711
+ "HEAD",
1712
+ "OPTIONS"
1713
+ ]);
1714
+ /** State-changing API calls must carry a custom header. Browsers won't send it cross-site without CORS. */
1715
+ function csrf() {
1716
+ return async (c, next) => {
1717
+ if (!SAFE_METHODS.has(c.req.method) && c.req.header("x-s3deck-csrf") !== "1") throw new HttpError(403, "CSRF", `Missing ${CSRF_HEADER} header`);
1718
+ await next();
1719
+ };
1720
+ }
1721
+ function isHttps(c) {
1722
+ return c.req.header("x-forwarded-proto")?.split(",")[0]?.trim() === "https" || new URL(c.req.url).protocol === "https:";
1723
+ }
1724
+ function setSessionCookie(c, ctx, session) {
1725
+ setCookie(c, SESSION_COOKIE, session.id, {
1726
+ httpOnly: true,
1727
+ sameSite: "Strict",
1728
+ secure: isHttps(c),
1729
+ path: `${ctx.config.basePath}/`
1730
+ });
1731
+ }
1732
+ function clearSessionCookie(c, ctx) {
1733
+ deleteCookie(c, SESSION_COOKIE, { path: `${ctx.config.basePath}/` });
1734
+ }
1735
+ /** Loads the session from the cookie. With auth disabled, everyone gets an anonymous session. */
1736
+ function loadSession(ctx) {
1737
+ return async (c, next) => {
1738
+ let session = ctx.sessions.get(getCookie(c, SESSION_COOKIE));
1739
+ if (session) {
1740
+ const role = resolveRole(ctx, session);
1741
+ if (role) session.role = role;
1742
+ else {
1743
+ ctx.sessions.destroy(session.id);
1744
+ session = null;
1745
+ }
1746
+ }
1747
+ if (!session && !ctx.config.auth.enabled) {
1748
+ session = ctx.sessions.create("anonymous", "anonymous", "admin", ctx.connections.defaultId);
1749
+ setSessionCookie(c, ctx, session);
1750
+ }
1751
+ c.set("session", session);
1752
+ await next();
1753
+ };
1754
+ }
1755
+ function requireAuth() {
1756
+ return async (c, next) => {
1757
+ if (!c.get("session")) throw new HttpError(401, "UNAUTHENTICATED", "Please log in");
1758
+ await next();
1759
+ };
1760
+ }
1761
+ function requireRole(min) {
1762
+ return async (c, next) => {
1763
+ const s = c.get("session");
1764
+ if (!s) throw new HttpError(401, "UNAUTHENTICATED", "Please log in");
1765
+ if (!hasRole(s.role, min)) throw new HttpError(403, "FORBIDDEN", `This needs the ${min} role`);
1766
+ await next();
1767
+ };
1768
+ }
1769
+ /**
1770
+ * Guards a change: blocked in --readonly mode, and needs at least `min`
1771
+ * (editors change objects; admins change buckets and their settings).
1772
+ */
1773
+ function writable(ctx, min = "editor") {
1774
+ return async (c, next) => {
1775
+ if (ctx.config.readonly) throw new HttpError(403, "READONLY", "s3deck is running in read-only mode");
1776
+ const s = c.get("session");
1777
+ if (!s || !hasRole(s.role, min)) throw new HttpError(403, "FORBIDDEN", `This needs the ${min} role`);
1778
+ await next();
1779
+ };
1780
+ }
1781
+ /** Records a change in the activity log. */
1782
+ function logActivity(ctx, c, action, details = {}) {
1783
+ const session = c.get("session");
1784
+ const conn = c.get("conn") ?? void 0;
1785
+ ctx.activity.record({
1786
+ user: session?.user ?? "unknown",
1787
+ ip: clientAddress(c),
1788
+ action,
1789
+ connection: conn?.label ?? null,
1790
+ bucket: details.bucket ?? null,
1791
+ detail: details.detail ? details.detail.slice(0, 500) : null
1792
+ });
1793
+ }
1794
+ /** A short description of a list of keys for the activity log. */
1795
+ function describeKeys(keys) {
1796
+ if (keys.length <= 3) return keys.join(", ");
1797
+ return `${keys.slice(0, 3).join(", ")} and ${keys.length - 3} more`;
1798
+ }
1799
+ /** Resolves the session's active storage connection. */
1800
+ function withConnection(ctx) {
1801
+ return async (c, next) => {
1802
+ const session = c.get("session");
1803
+ const requested = c.req.header(CONNECTION_HEADER);
1804
+ if (requested) {
1805
+ const conn = ctx.connections.getForSession(requested, session);
1806
+ if (!conn) throw new HttpError(409, "NO_CONNECTION", "That connection is no longer available");
1807
+ c.set("conn", conn);
1808
+ return next();
1809
+ }
1810
+ let conn = ctx.connections.getForSession(session.activeConnectionId, session);
1811
+ if (!conn && ctx.connections.defaultId) {
1812
+ conn = ctx.connections.getForSession(ctx.connections.defaultId, session);
1813
+ if (conn) session.activeConnectionId = conn.id;
1814
+ }
1815
+ if (!conn) throw new HttpError(409, "NO_CONNECTION", "Connect to a storage provider first");
1816
+ c.set("conn", conn);
1817
+ await next();
1818
+ };
1819
+ }
1820
+ /** Client address for rate limiting. Trusts X-Forwarded-For only from a local proxy. */
1821
+ function clientAddress(c) {
1822
+ let remote = "unknown";
1823
+ try {
1824
+ remote = getConnInfo(c).remote.address ?? "unknown";
1825
+ } catch {}
1826
+ const local = remote === "127.0.0.1" || remote === "::1" || remote === "::ffff:127.0.0.1";
1827
+ const forwarded = c.req.header("x-forwarded-for")?.split(",")[0]?.trim();
1828
+ return local && forwarded ? forwarded : remote;
1829
+ }
1830
+ // src/server/validate.ts
1831
+ /** zod validation for a request part, answering 400 with a readable message on failure. */
1832
+ function validate(target, schema) {
1833
+ return zValidator(target, schema, (result, c) => {
1834
+ if (!result.success) return c.json({ error: {
1835
+ code: "VALIDATION",
1836
+ message: formatZodError(result.error)
1837
+ } }, 400);
1838
+ });
1839
+ }
1840
+ // src/server/routes/admin.ts
1841
+ const toInfo = (u) => ({
1842
+ username: u.username,
1843
+ role: u.role,
1844
+ disabled: u.disabled,
1845
+ hasPassword: !!u.passwordHash,
1846
+ createdAt: u.createdAt
1847
+ });
1848
+ /** User management and the activity log. Admins only. */
1849
+ function adminRoutes(ctx) {
1850
+ const usersOrFail = () => {
1851
+ if (!ctx.users) throw new HttpError(400, "NO_PERSISTENCE", "This server has no data directory, so users can’t be stored");
1852
+ return ctx.users;
1853
+ };
1854
+ const userParam = z.object({ username: usernameSchema });
1855
+ return new Hono().use(requireRole("admin")).get("/users", (c) => c.json({
1856
+ users: (ctx.users?.list() ?? []).map(toInfo),
1857
+ startupAdmin: ctx.config.auth.user
1858
+ })).post("/users", validate("json", createUserSchema), async (c) => {
1859
+ const users = usersOrFail();
1860
+ const input = c.req.valid("json");
1861
+ if (users.get(input.username) || input.username.toLowerCase() === ctx.config.auth.user.toLowerCase()) throw new HttpError(409, "EXISTS", "A user with that name already exists");
1862
+ if (!input.password && !input.username.includes("@")) throw new HttpError(400, "VALIDATION", "Without a password, the username must be the email used for single sign-on");
1863
+ const record = await users.create(input);
1864
+ logActivity(ctx, c, "user.create", { detail: `${record.username} (${record.role})` });
1865
+ return c.json(toInfo(record), 201);
1866
+ }).patch("/users/:username", validate("param", userParam), validate("json", updateUserSchema), async (c) => {
1867
+ const users = usersOrFail();
1868
+ const { username } = c.req.valid("param");
1869
+ const patch = c.req.valid("json");
1870
+ if (c.get("session").user.toLowerCase() === username.toLowerCase() && (patch.disabled || patch.role && patch.role !== "admin")) throw new HttpError(400, "NOT_ALLOWED", "You can’t disable yourself or remove your own admin role");
1871
+ const record = await users.update(username, patch);
1872
+ if (!record) throw new HttpError(404, "NOT_FOUND", "User not found");
1873
+ const what = [
1874
+ patch.role && `role ${patch.role}`,
1875
+ patch.disabled !== void 0 && (patch.disabled ? "disabled" : "enabled"),
1876
+ patch.password && "password reset"
1877
+ ].filter(Boolean).join(", ");
1878
+ logActivity(ctx, c, "user.update", { detail: `${record.username}: ${what}` });
1879
+ return c.json(toInfo(record));
1880
+ }).delete("/users/:username", validate("param", userParam), async (c) => {
1881
+ const users = usersOrFail();
1882
+ const { username } = c.req.valid("param");
1883
+ if (c.get("session").user.toLowerCase() === username.toLowerCase()) throw new HttpError(400, "NOT_ALLOWED", "You can’t delete yourself");
1884
+ if (!await users.remove(username)) throw new HttpError(404, "NOT_FOUND", "User not found");
1885
+ logActivity(ctx, c, "user.delete", { detail: username });
1886
+ return c.json({ ok: true });
1887
+ }).get("/activity", validate("query", activityQuerySchema), (c) => {
1888
+ const q = c.req.valid("query");
1889
+ return c.json({
1890
+ entries: ctx.activity.list(q),
1891
+ persisted: !!ctx.config.dataDir
1892
+ });
1893
+ });
1894
+ }
1895
+ // src/server/routes/auth.ts
1896
+ /** Constant-time string comparison (hashing first so lengths don't leak). */
1897
+ function safeEqual(a, b) {
1898
+ const ha = createHash("sha256").update(a).digest();
1899
+ const hb = createHash("sha256").update(b).digest();
1900
+ return timingSafeEqual(ha, hb);
1901
+ }
1902
+ /** The public origin + base path, for SSO redirect URLs. */
1903
+ function publicBase(c, ctx) {
1904
+ if (ctx.config.publicUrl) return ctx.config.publicUrl.replace(/\/+$/, "");
1905
+ const url = new URL(c.req.url);
1906
+ return `${c.req.header("x-forwarded-proto")?.split(",")[0]?.trim() || url.protocol.replace(":", "")}://${c.req.header("x-forwarded-host")?.split(",")[0]?.trim() || c.req.header("host") || url.host}${ctx.config.basePath}`;
1907
+ }
1908
+ function authRoutes(ctx) {
1909
+ const { config } = ctx;
1910
+ const startSession = (c, user, source, role) => {
1911
+ const previous = getCookie(c, SESSION_COOKIE);
1912
+ if (previous) ctx.sessions.destroy(previous);
1913
+ const session = ctx.sessions.create(user, source, role, ctx.connections.defaultId);
1914
+ setSessionCookie(c, ctx, session);
1915
+ c.set("session", session);
1916
+ return session;
1917
+ };
1918
+ return new Hono().get("/me", (c) => {
1919
+ const session = c.get("session");
1920
+ const role = session?.role ?? null;
1921
+ const body = {
1922
+ authenticated: !!session,
1923
+ authRequired: config.auth.enabled,
1924
+ user: session?.user ?? null,
1925
+ readonly: config.readonly,
1926
+ browserConnections: config.allowBrowserConnections,
1927
+ version: config.version,
1928
+ role,
1929
+ can: {
1930
+ write: !!role && !config.readonly && hasRole(role, "editor"),
1931
+ admin: !!role && hasRole(role, "admin")
1932
+ },
1933
+ sso: {
1934
+ enabled: !!ctx.sso,
1935
+ label: ctx.sso?.config.label ?? ""
1936
+ },
1937
+ persistence: !!ctx.saved
1938
+ };
1939
+ return c.json(body);
1940
+ }).post("/login", validate("json", loginSchema), async (c) => {
1941
+ if (!config.auth.enabled) return c.json({ ok: true });
1942
+ const ip = clientAddress(c);
1943
+ const wait = ctx.loginLimiter.retryAfter(ip);
1944
+ if (wait > 0) {
1945
+ c.header("Retry-After", String(wait));
1946
+ throw new HttpError(429, "RATE_LIMITED", `Too many failed logins. Try again in ${Math.ceil(wait / 60)} min.`);
1947
+ }
1948
+ const { username, password } = c.req.valid("json");
1949
+ const userOk = safeEqual(username, config.auth.user);
1950
+ const passOk = safeEqual(password, config.auth.password);
1951
+ if (userOk && passOk) {
1952
+ ctx.loginLimiter.reset(ip);
1953
+ startSession(c, username, "bootstrap", "admin");
1954
+ logActivity(ctx, c, "login");
1955
+ return c.json({ ok: true });
1956
+ }
1957
+ const record = ctx.users?.get(username);
1958
+ if (record && !record.disabled && await verifyPassword(password, record.passwordHash)) {
1959
+ ctx.loginLimiter.reset(ip);
1960
+ startSession(c, record.username, "local", record.role);
1961
+ logActivity(ctx, c, "login");
1962
+ return c.json({ ok: true });
1963
+ }
1964
+ ctx.loginLimiter.hit(ip);
1965
+ ctx.activity.record({
1966
+ user: username,
1967
+ ip,
1968
+ action: "login.failed",
1969
+ connection: null,
1970
+ bucket: null,
1971
+ detail: null
1972
+ });
1973
+ throw new HttpError(401, "BAD_CREDENTIALS", "Wrong username or password");
1974
+ }).post("/logout", (c) => {
1975
+ const session = c.get("session");
1976
+ if (session) ctx.sessions.destroy(session.id);
1977
+ clearSessionCookie(c, ctx);
1978
+ return c.json({ ok: true });
1979
+ }).get("/sso/start", async (c) => {
1980
+ if (!ctx.sso) throw new HttpError(404, "NOT_FOUND", "Single sign-on is not configured");
1981
+ const url = await ctx.sso.authorizationUrl(`${publicBase(c, ctx)}/api/auth/sso/callback`);
1982
+ return c.redirect(url, 302);
1983
+ }).get("/sso/callback", async (c) => {
1984
+ if (!ctx.sso) throw new HttpError(404, "NOT_FOUND", "Single sign-on is not configured");
1985
+ const home = `${config.basePath}/`;
1986
+ const fail = (message) => c.redirect(`${home}?login_error=${encodeURIComponent(message)}`, 302);
1987
+ try {
1988
+ const callbackUrl = new URL(`${publicBase(c, ctx)}/api/auth/sso/callback${new URL(c.req.url).search}`);
1989
+ const { email } = await ctx.sso.finish(callbackUrl);
1990
+ const record = ctx.users?.get(email);
1991
+ const role = record ? record.disabled ? null : record.role : ctx.sso.defaultRoleFor(email);
1992
+ if (!role) {
1993
+ ctx.activity.record({
1994
+ user: email,
1995
+ ip: clientAddress(c),
1996
+ action: "login.denied",
1997
+ connection: null,
1998
+ bucket: null,
1999
+ detail: "sso"
2000
+ });
2001
+ return fail(`${email} is not allowed to use this s3deck.`);
2002
+ }
2003
+ startSession(c, record?.username ?? email, "sso", role);
2004
+ logActivity(ctx, c, "login", { detail: "sso" });
2005
+ return c.redirect(home, 302);
2006
+ } catch (err) {
2007
+ return fail(err instanceof Error ? err.message : "Sign-in failed");
2008
+ }
2009
+ });
2010
+ }
2011
+ // src/s3/usage.ts
2012
+ /** Lists every object under a prefix and adds up sizes by subfolder and storage class. */
2013
+ async function calculateUsage(client, bucket, prefix, signal) {
2014
+ const started = Date.now();
2015
+ const byFolder = /* @__PURE__ */ new Map();
2016
+ const byClass = /* @__PURE__ */ new Map();
2017
+ let objects = 0;
2018
+ let bytes = 0;
2019
+ const add = (map, name, size) => {
2020
+ const g = map.get(name) ?? {
2021
+ name,
2022
+ objects: 0,
2023
+ bytes: 0
2024
+ };
2025
+ g.objects++;
2026
+ g.bytes += size;
2027
+ map.set(name, g);
2028
+ };
2029
+ for await (const page of walkObjects(client, bucket, prefix, signal)) for (const o of page) {
2030
+ const size = o.Size ?? 0;
2031
+ const rest = o.Key.slice(prefix.length);
2032
+ const slash = rest.indexOf("/");
2033
+ objects++;
2034
+ bytes += size;
2035
+ add(byFolder, slash === -1 ? "(files in this folder)" : `${rest.slice(0, slash + 1)}`, size);
2036
+ add(byClass, o.StorageClass ?? "STANDARD", size);
2037
+ }
2038
+ const sorted = (m) => [...m.values()].sort((a, b) => b.bytes - a.bytes);
2039
+ return {
2040
+ prefix,
2041
+ objects,
2042
+ bytes,
2043
+ byFolder: sorted(byFolder),
2044
+ byStorageClass: sorted(byClass),
2045
+ durationMs: Date.now() - started
2046
+ };
2047
+ }
2048
+ // src/server/routes/buckets.ts
2049
+ const bucketParam$1 = z.object({ bucket: bucketParamSchema });
2050
+ function bucketRoutes(ctx) {
2051
+ const write = writable(ctx, "admin");
2052
+ const requireCapability = (enabled, what) => {
2053
+ if (!enabled) throw new HttpError(501, "UNSUPPORTED", `${what} is not supported by this provider`);
2054
+ };
2055
+ return new Hono().get("/", async (c) => {
2056
+ const conn = c.get("conn");
2057
+ let body;
2058
+ try {
2059
+ const buckets = await listBuckets(conn.handle.client);
2060
+ const names = new Set(buckets.map((b) => b.name));
2061
+ for (const name of conn.pinnedBuckets) if (!names.has(name)) buckets.push({
2062
+ name,
2063
+ createdAt: null,
2064
+ region: null
2065
+ });
2066
+ body = {
2067
+ buckets,
2068
+ fallback: false
2069
+ };
2070
+ } catch (err) {
2071
+ if (!isAccessDenied(err) || conn.pinnedBuckets.length === 0) throw err;
2072
+ body = {
2073
+ buckets: conn.pinnedBuckets.map((name) => ({
2074
+ name,
2075
+ createdAt: null,
2076
+ region: null
2077
+ })),
2078
+ fallback: true
2079
+ };
2080
+ }
2081
+ return c.json(body);
2082
+ }).post("/", write, validate("json", createBucketSchema), async (c) => {
2083
+ const conn = c.get("conn");
2084
+ const { name, region } = c.req.valid("json");
2085
+ await createBucket(conn.handle.client, name, region, conn.region);
2086
+ logActivity(ctx, c, "bucket.create", { bucket: name });
2087
+ return c.json({ ok: true }, 201);
2088
+ }).delete("/:bucket", write, validate("param", bucketParam$1), validate("query", deleteBucketQuerySchema), async (c) => {
2089
+ const conn = c.get("conn");
2090
+ const { bucket } = c.req.valid("param");
2091
+ const { force } = c.req.valid("query");
2092
+ await deleteBucket(conn.handle.client, bucket, force === "1", conn.provider.capabilities);
2093
+ logActivity(ctx, c, force === "1" ? "bucket.empty-and-delete" : "bucket.delete", { bucket });
2094
+ return c.json({ ok: true });
2095
+ }).get("/:bucket/settings", validate("param", bucketParam$1), async (c) => {
2096
+ const conn = c.get("conn");
2097
+ const { bucket } = c.req.valid("param");
2098
+ return c.json(await getBucketSettings(conn.handle.client, bucket, conn.provider.capabilities));
2099
+ }).put("/:bucket/settings/versioning", write, validate("param", bucketParam$1), validate("json", versioningSchema), async (c) => {
2100
+ const conn = c.get("conn");
2101
+ requireCapability(conn.provider.capabilities.versioning, "Versioning");
2102
+ await setVersioning(conn.handle.client, c.req.valid("param").bucket, c.req.valid("json").enabled);
2103
+ logActivity(ctx, c, "settings.versioning", {
2104
+ bucket: c.req.valid("param").bucket,
2105
+ detail: c.req.valid("json").enabled ? "enabled" : "suspended"
2106
+ });
2107
+ return c.json({ ok: true });
2108
+ }).put("/:bucket/settings/cors", write, validate("param", bucketParam$1), validate("json", z.object({ rules: corsSchema })), async (c) => {
2109
+ const conn = c.get("conn");
2110
+ requireCapability(conn.provider.capabilities.cors, "CORS");
2111
+ await setCors(conn.handle.client, c.req.valid("param").bucket, c.req.valid("json").rules);
2112
+ logActivity(ctx, c, "settings.cors", {
2113
+ bucket: c.req.valid("param").bucket,
2114
+ detail: `${c.req.valid("json").rules.length} rules`
2115
+ });
2116
+ return c.json({ ok: true });
2117
+ }).put("/:bucket/settings/lifecycle", write, validate("param", bucketParam$1), validate("json", z.object({ rules: lifecycleSchema })), async (c) => {
2118
+ const conn = c.get("conn");
2119
+ requireCapability(conn.provider.capabilities.lifecycle, "Lifecycle rules");
2120
+ await setLifecycle(conn.handle.client, c.req.valid("param").bucket, c.req.valid("json").rules);
2121
+ logActivity(ctx, c, "settings.lifecycle", {
2122
+ bucket: c.req.valid("param").bucket,
2123
+ detail: `${c.req.valid("json").rules.length} rules`
2124
+ });
2125
+ return c.json({ ok: true });
2126
+ }).put("/:bucket/settings/policy", write, validate("param", bucketParam$1), validate("json", z.object({ policy: policySchema })), async (c) => {
2127
+ const conn = c.get("conn");
2128
+ requireCapability(conn.provider.capabilities.bucketPolicy, "Bucket policies");
2129
+ await setPolicy(conn.handle.client, c.req.valid("param").bucket, c.req.valid("json").policy);
2130
+ logActivity(ctx, c, "settings.policy", {
2131
+ bucket: c.req.valid("param").bucket,
2132
+ detail: c.req.valid("json").policy ? "updated" : "removed"
2133
+ });
2134
+ return c.json({ ok: true });
2135
+ }).put("/:bucket/settings/public-access", write, validate("param", bucketParam$1), validate("json", z.object({ config: publicAccessBlockSchema.nullable() })), async (c) => {
2136
+ const conn = c.get("conn");
2137
+ requireCapability(conn.provider.capabilities.publicAccessBlock, "Public access settings");
2138
+ await setPublicAccessBlock(conn.handle.client, c.req.valid("param").bucket, c.req.valid("json").config);
2139
+ logActivity(ctx, c, "settings.public-access", { bucket: c.req.valid("param").bucket });
2140
+ return c.json({ ok: true });
2141
+ }).get("/:bucket/usage", validate("param", bucketParam$1), validate("query", prefixQuerySchema), async (c) => {
2142
+ const conn = c.get("conn");
2143
+ const { bucket } = c.req.valid("param");
2144
+ const { prefix } = c.req.valid("query");
2145
+ return c.json(await calculateUsage(conn.handle.client, bucket, prefix, c.req.raw.signal));
2146
+ });
2147
+ }
2148
+ // src/server/routes/connections.ts
2149
+ function connectionRoutes(ctx) {
2150
+ const list = (session) => {
2151
+ const conns = ctx.connections.listForSession(session);
2152
+ const active = conns.find((c) => c.id === session.activeConnectionId) ?? conns.find((c) => c.id === ctx.connections.defaultId) ?? conns[0] ?? null;
2153
+ if (active) session.activeConnectionId = active.id;
2154
+ return {
2155
+ activeId: active?.id ?? null,
2156
+ connections: conns.map(connectionInfo)
2157
+ };
2158
+ };
2159
+ return new Hono().get("/", (c) => c.json(list(c.get("session")))).post("/", validate("json", connectionInputSchema), async (c) => {
2160
+ if (!ctx.config.allowBrowserConnections) throw new HttpError(403, "DISABLED", "Adding connections from the browser is disabled on this server");
2161
+ const session = c.get("session");
2162
+ const input = c.req.valid("json");
2163
+ if (input.remember && !ctx.saved) throw new HttpError(400, "NO_PERSISTENCE", "This server has no data directory, so connections can’t be remembered");
2164
+ const endpoint = input.endpoint || null;
2165
+ const provider = detectProvider(endpoint);
2166
+ const region = input.region || provider.defaultRegion || "us-east-1";
2167
+ const pathStyle = input.pathStyle ?? "auto";
2168
+ const credentials = {
2169
+ accessKeyId: input.accessKeyId,
2170
+ secretAccessKey: input.secretAccessKey,
2171
+ sessionToken: input.sessionToken || void 0
2172
+ };
2173
+ let result;
2174
+ try {
2175
+ result = await openConnection({
2176
+ source: input.remember ? "saved" : "browser",
2177
+ ownerSessionId: input.remember ? void 0 : session.id,
2178
+ ownerUser: input.remember ? session.user : void 0,
2179
+ label: input.label,
2180
+ endpoint,
2181
+ region,
2182
+ pathStyle,
2183
+ accessKeyId: input.accessKeyId,
2184
+ credentials,
2185
+ pinnedBuckets: input.buckets ?? [],
2186
+ publicUrlBase: input.publicUrlBase || null
2187
+ });
2188
+ } catch (err) {
2189
+ const { body } = toErrorResponse(err);
2190
+ const hint = body.error.code === "AccessDenied" ? " The key works but cannot list buckets; add the bucket names you want to open." : "";
2191
+ throw new HttpError(400, "CONNECT_FAILED", `Could not connect: ${body.error.message.replace(/\.+$/, "")}.${hint}`);
2192
+ }
2193
+ const conn = result.connection;
2194
+ ctx.connections.addForSession(conn);
2195
+ if (input.remember && ctx.saved) try {
2196
+ await ctx.saved.add({
2197
+ id: conn.id,
2198
+ owner: session.user,
2199
+ label: input.label,
2200
+ endpoint,
2201
+ region,
2202
+ pathStyle,
2203
+ ...credentials,
2204
+ buckets: input.buckets ?? [],
2205
+ publicUrlBase: input.publicUrlBase || null,
2206
+ savedAt: (/* @__PURE__ */ new Date()).toISOString()
2207
+ });
2208
+ } catch (err) {
2209
+ ctx.connections.remove(conn.id);
2210
+ throw err;
2211
+ }
2212
+ session.activeConnectionId = conn.id;
2213
+ logActivity(ctx, c, input.remember ? "connection.remember" : "connection.add", { detail: conn.label });
2214
+ return c.json({
2215
+ ...list(session),
2216
+ bucketCount: result.bucketCount
2217
+ }, 201);
2218
+ }).post("/:id/activate", (c) => {
2219
+ const session = c.get("session");
2220
+ const conn = ctx.connections.getForSession(c.req.param("id"), session);
2221
+ if (!conn) throw new HttpError(404, "NOT_FOUND", "Connection not found");
2222
+ session.activeConnectionId = conn.id;
2223
+ return c.json(list(session));
2224
+ }).delete("/:id", async (c) => {
2225
+ const session = c.get("session");
2226
+ const conn = ctx.connections.getForSession(c.req.param("id"), session);
2227
+ if (!conn) throw new HttpError(404, "NOT_FOUND", "Connection not found");
2228
+ if (conn.source === "cli") throw new HttpError(400, "NOT_ALLOWED", "The startup connection cannot be removed");
2229
+ if (conn.source === "saved") await ctx.saved?.remove(conn.id);
2230
+ ctx.connections.remove(conn.id);
2231
+ ctx.sessions.reassign(conn.id, ctx.connections.defaultId);
2232
+ logActivity(ctx, c, conn.source === "saved" ? "connection.forget" : "connection.remove", { detail: conn.label });
2233
+ return c.json(list(session));
2234
+ });
2235
+ }
2236
+ // src/s3/multipart.ts
2237
+ /**
2238
+ * Client-driven multipart uploads. The browser splits a file into parts and sends them one by
2239
+ * one, so an interrupted upload can resume from the parts S3 already has.
2240
+ */
2241
+ async function createMultipart(client, bucket, key, contentType) {
2242
+ const out = await client.send(new CreateMultipartUploadCommand({
2243
+ Bucket: bucket,
2244
+ Key: key,
2245
+ ContentType: contentType
2246
+ }));
2247
+ if (!out.UploadId) throw new Error("Storage did not return an upload ID");
2248
+ return { uploadId: out.UploadId };
2249
+ }
2250
+ async function uploadPart(client, bucket, key, uploadId, partNumber, body) {
2251
+ return { etag: (await client.send(new UploadPartCommand({
2252
+ Bucket: bucket,
2253
+ Key: key,
2254
+ UploadId: uploadId,
2255
+ PartNumber: partNumber,
2256
+ Body: body,
2257
+ ContentLength: body.byteLength
2258
+ }))).ETag ?? "" };
2259
+ }
2260
+ async function listParts(client, bucket, key, uploadId) {
2261
+ const parts = [];
2262
+ let marker;
2263
+ do {
2264
+ const out = await client.send(new ListPartsCommand({
2265
+ Bucket: bucket,
2266
+ Key: key,
2267
+ UploadId: uploadId,
2268
+ PartNumberMarker: marker
2269
+ }));
2270
+ for (const p of out.Parts ?? []) if (p.PartNumber && p.ETag) parts.push({
2271
+ partNumber: p.PartNumber,
2272
+ etag: p.ETag,
2273
+ size: p.Size ?? 0
2274
+ });
2275
+ marker = out.IsTruncated ? out.NextPartNumberMarker : void 0;
2276
+ } while (marker);
2277
+ return parts;
2278
+ }
2279
+ async function completeMultipart(client, bucket, key, uploadId, parts) {
2280
+ const sorted = [...parts].sort((a, b) => a.PartNumber - b.PartNumber);
2281
+ return { etag: (await client.send(new CompleteMultipartUploadCommand({
2282
+ Bucket: bucket,
2283
+ Key: key,
2284
+ UploadId: uploadId,
2285
+ MultipartUpload: { Parts: sorted }
2286
+ }))).ETag ?? null };
2287
+ }
2288
+ async function abortMultipart(client, bucket, key, uploadId) {
2289
+ await client.send(new AbortMultipartUploadCommand({
2290
+ Bucket: bucket,
2291
+ Key: key,
2292
+ UploadId: uploadId
2293
+ }));
2294
+ }
2295
+ /** Unfinished multipart uploads in a bucket. Their parts are billed until aborted. */
2296
+ async function listIncomplete(client, bucket, limit = 5e3) {
2297
+ const out = [];
2298
+ let keyMarker;
2299
+ let idMarker;
2300
+ do {
2301
+ const page = await client.send(new ListMultipartUploadsCommand({
2302
+ Bucket: bucket,
2303
+ KeyMarker: keyMarker,
2304
+ UploadIdMarker: idMarker
2305
+ }));
2306
+ for (const u of page.Uploads ?? []) if (u.Key && u.UploadId) out.push({
2307
+ key: u.Key,
2308
+ uploadId: u.UploadId,
2309
+ initiated: u.Initiated?.toISOString() ?? null,
2310
+ storageClass: u.StorageClass ?? null
2311
+ });
2312
+ keyMarker = page.IsTruncated ? page.NextKeyMarker : void 0;
2313
+ idMarker = page.IsTruncated ? page.NextUploadIdMarker : void 0;
2314
+ } while (keyMarker && out.length < limit);
2315
+ return out;
2316
+ }
2317
+ // src/s3/objects.ts
2318
+ async function headObject(client, bucket, key, versionId) {
2319
+ return client.send(new HeadObjectCommand({
2320
+ Bucket: bucket,
2321
+ Key: key,
2322
+ VersionId: versionId
2323
+ }));
2324
+ }
2325
+ function headersOf(h) {
2326
+ const out = {};
2327
+ const add = (name, v) => {
2328
+ if (v === void 0 || v === null || v === "") return;
2329
+ out[name] = v instanceof Date ? v.toUTCString() : String(v);
2330
+ };
2331
+ add("Content-Type", h.ContentType);
2332
+ add("Content-Length", h.ContentLength);
2333
+ add("Content-Encoding", h.ContentEncoding);
2334
+ add("Content-Disposition", h.ContentDisposition);
2335
+ add("Content-Language", h.ContentLanguage);
2336
+ add("Cache-Control", h.CacheControl);
2337
+ add("Expires", h.ExpiresString ?? h.Expires);
2338
+ add("ETag", h.ETag);
2339
+ add("Last-Modified", h.LastModified);
2340
+ add("x-amz-version-id", h.VersionId);
2341
+ add("x-amz-storage-class", h.StorageClass);
2342
+ add("x-amz-server-side-encryption", h.ServerSideEncryption);
2343
+ add("x-amz-website-redirect-location", h.WebsiteRedirectLocation);
2344
+ add("x-amz-replication-status", h.ReplicationStatus);
2345
+ add("x-amz-restore", h.Restore);
2346
+ add("x-amz-object-lock-mode", h.ObjectLockMode);
2347
+ add("x-amz-object-lock-retain-until-date", h.ObjectLockRetainUntilDate);
2348
+ add("x-amz-tagging-count", h.TagCount);
2349
+ return out;
2350
+ }
2351
+ async function createFolder(client, bucket, prefix) {
2352
+ await client.send(new PutObjectCommand({
2353
+ Bucket: bucket,
2354
+ Key: prefix,
2355
+ Body: "",
2356
+ ContentLength: 0
2357
+ }));
2358
+ }
2359
+ async function presign(client, bucket, input) {
2360
+ const command = input.method === "GET" ? new GetObjectCommand({
2361
+ Bucket: bucket,
2362
+ Key: input.key,
2363
+ VersionId: input.versionId
2364
+ }) : new PutObjectCommand({
2365
+ Bucket: bucket,
2366
+ Key: input.key,
2367
+ ContentType: input.contentType || void 0
2368
+ });
2369
+ return {
2370
+ url: await getSignedUrl(client, command, { expiresIn: input.expiresIn }),
2371
+ expiresAt: new Date(Date.now() + input.expiresIn * 1e3).toISOString()
2372
+ };
2373
+ }
2374
+ /** Rewrites an object's headers and metadata in place (copy onto itself with REPLACE). */
2375
+ async function updateMetadata(client, bucket, key, input) {
2376
+ const head = await headObject(client, bucket, key);
2377
+ const pick = (next, current) => next === void 0 ? current : next === "" ? void 0 : next;
2378
+ await copyObject(client, {
2379
+ sourceBucket: bucket,
2380
+ sourceKey: key,
2381
+ destinationBucket: bucket,
2382
+ destinationKey: key,
2383
+ size: head.ContentLength ?? 0,
2384
+ replace: {
2385
+ ContentType: pick(input.contentType, head.ContentType),
2386
+ CacheControl: pick(input.cacheControl, head.CacheControl),
2387
+ ContentDisposition: pick(input.contentDisposition, head.ContentDisposition),
2388
+ ContentEncoding: pick(input.contentEncoding, head.ContentEncoding),
2389
+ ContentLanguage: head.ContentLanguage,
2390
+ Metadata: input.metadata ?? head.Metadata ?? {},
2391
+ StorageClass: head.StorageClass
2392
+ }
2393
+ });
2394
+ }
2395
+ async function getTags(client, bucket, key, versionId) {
2396
+ return ((await client.send(new GetObjectTaggingCommand({
2397
+ Bucket: bucket,
2398
+ Key: key,
2399
+ VersionId: versionId
2400
+ }))).TagSet ?? []).map((t) => ({
2401
+ Key: t.Key ?? "",
2402
+ Value: t.Value ?? ""
2403
+ }));
2404
+ }
2405
+ async function setTags(client, bucket, key, tags, versionId) {
2406
+ if (tags.length === 0) {
2407
+ await client.send(new DeleteObjectTaggingCommand({
2408
+ Bucket: bucket,
2409
+ Key: key,
2410
+ VersionId: versionId
2411
+ }));
2412
+ return;
2413
+ }
2414
+ await client.send(new PutObjectTaggingCommand({
2415
+ Bucket: bucket,
2416
+ Key: key,
2417
+ VersionId: versionId,
2418
+ Tagging: { TagSet: tags }
2419
+ }));
2420
+ }
2421
+ /** Lists the versions and delete markers of one key, newest first. */
2422
+ async function listVersions(client, bucket, key) {
2423
+ const entries = [];
2424
+ let keyMarker;
2425
+ let versionMarker;
2426
+ do {
2427
+ const out = await client.send(new ListObjectVersionsCommand({
2428
+ Bucket: bucket,
2429
+ Prefix: key,
2430
+ KeyMarker: keyMarker,
2431
+ VersionIdMarker: versionMarker
2432
+ }));
2433
+ for (const v of out.Versions ?? []) {
2434
+ if (v.Key !== key) continue;
2435
+ entries.push({
2436
+ versionId: v.VersionId ?? "null",
2437
+ isLatest: !!v.IsLatest,
2438
+ isDeleteMarker: false,
2439
+ size: v.Size ?? 0,
2440
+ lastModified: v.LastModified?.toISOString() ?? null,
2441
+ etag: v.ETag ?? null,
2442
+ storageClass: v.StorageClass ?? null
2443
+ });
2444
+ }
2445
+ for (const m of out.DeleteMarkers ?? []) {
2446
+ if (m.Key !== key) continue;
2447
+ entries.push({
2448
+ versionId: m.VersionId ?? "null",
2449
+ isLatest: !!m.IsLatest,
2450
+ isDeleteMarker: true,
2451
+ size: 0,
2452
+ lastModified: m.LastModified?.toISOString() ?? null,
2453
+ etag: null,
2454
+ storageClass: null
2455
+ });
2456
+ }
2457
+ const passed = out.NextKeyMarker !== void 0 && out.NextKeyMarker !== key;
2458
+ keyMarker = out.IsTruncated && !passed ? out.NextKeyMarker : void 0;
2459
+ versionMarker = out.IsTruncated && !passed ? out.NextVersionIdMarker : void 0;
2460
+ } while (keyMarker);
2461
+ return entries.sort((a, b) => (b.lastModified ?? "").localeCompare(a.lastModified ?? ""));
2462
+ }
2463
+ /** Makes an older version the current one by copying it on top. */
2464
+ async function restoreVersion(client, bucket, key, versionId) {
2465
+ await copyObject(client, {
2466
+ sourceBucket: bucket,
2467
+ sourceKey: key,
2468
+ sourceVersionId: versionId,
2469
+ destinationBucket: bucket,
2470
+ destinationKey: key,
2471
+ size: (await headObject(client, bucket, key, versionId)).ContentLength ?? 0
2472
+ });
2473
+ }
2474
+ async function deleteVersion(client, bucket, key, versionId) {
2475
+ await client.send(new DeleteObjectCommand({
2476
+ Bucket: bucket,
2477
+ Key: key,
2478
+ VersionId: versionId
2479
+ }));
2480
+ }
2481
+ /** Parses the x-amz-restore header: ongoing-request="false", expiry-date="Fri, 21 Dec 2012 00:00:00 GMT" */
2482
+ function parseRestore(header) {
2483
+ if (!header) return {
2484
+ restore: "none",
2485
+ restoreExpiry: null
2486
+ };
2487
+ if (/ongoing-request="true"/.test(header)) return {
2488
+ restore: "in-progress",
2489
+ restoreExpiry: null
2490
+ };
2491
+ const expiry = header.match(/expiry-date="([^"]+)"/)?.[1];
2492
+ return {
2493
+ restore: "restored",
2494
+ restoreExpiry: expiry ? new Date(expiry).toISOString() : null
2495
+ };
2496
+ }
2497
+ async function objectExtras(client, bucket, key, h, opts) {
2498
+ let legalHold = null;
2499
+ if (opts.objectLock && (h.ObjectLockMode || h.ObjectLockLegalHoldStatus === void 0)) try {
2500
+ legalHold = (await client.send(new GetObjectLegalHoldCommand({
2501
+ Bucket: bucket,
2502
+ Key: key,
2503
+ VersionId: h.VersionId
2504
+ }))).LegalHold?.Status === "ON";
2505
+ } catch {
2506
+ legalHold = null;
2507
+ }
2508
+ if (h.ObjectLockLegalHoldStatus) legalHold = h.ObjectLockLegalHoldStatus === "ON";
2509
+ const hasLock = !!h.ObjectLockMode || legalHold !== null;
2510
+ return {
2511
+ encryption: h.ServerSideEncryption ? {
2512
+ algorithm: h.ServerSideEncryption,
2513
+ kmsKeyId: h.SSEKMSKeyId ?? null,
2514
+ bucketKeyEnabled: !!h.BucketKeyEnabled
2515
+ } : null,
2516
+ lock: hasLock ? {
2517
+ mode: h.ObjectLockMode ?? null,
2518
+ retainUntil: h.ObjectLockRetainUntilDate?.toISOString() ?? null,
2519
+ legalHold
2520
+ } : null,
2521
+ archive: {
2522
+ archived: ARCHIVE_CLASSES.has(h.StorageClass ?? ""),
2523
+ ...parseRestore(h.Restore)
2524
+ }
2525
+ };
2526
+ }
2527
+ /** Rewrites the object in place with a new storage class, keeping its headers and metadata. */
2528
+ async function changeStorageClass(client, bucket, key, storageClass) {
2529
+ const head = await headObject(client, bucket, key);
2530
+ if (ARCHIVE_CLASSES.has(head.StorageClass ?? "") && parseRestore(head.Restore).restore !== "restored") throw new UserError(`"${key}" is archived. Restore it before changing its storage class.`);
2531
+ await copyObject(client, {
2532
+ sourceBucket: bucket,
2533
+ sourceKey: key,
2534
+ destinationBucket: bucket,
2535
+ destinationKey: key,
2536
+ size: head.ContentLength ?? 0,
2537
+ replace: {
2538
+ ContentType: head.ContentType,
2539
+ CacheControl: head.CacheControl,
2540
+ ContentDisposition: head.ContentDisposition,
2541
+ ContentEncoding: head.ContentEncoding,
2542
+ ContentLanguage: head.ContentLanguage,
2543
+ Metadata: head.Metadata ?? {},
2544
+ StorageClass: storageClass
2545
+ }
2546
+ });
2547
+ }
2548
+ /** Asks for a temporary readable copy of an archived (Glacier / Deep Archive) object. */
2549
+ async function restoreArchived(client, bucket, key, days, tier) {
2550
+ try {
2551
+ await client.send(new RestoreObjectCommand({
2552
+ Bucket: bucket,
2553
+ Key: key,
2554
+ RestoreRequest: {
2555
+ Days: days,
2556
+ GlacierJobParameters: { Tier: tier }
2557
+ }
2558
+ }));
2559
+ } catch (err) {
2560
+ if (err.name === "RestoreAlreadyInProgress") return;
2561
+ throw err;
2562
+ }
2563
+ }
2564
+ /**
2565
+ * Objects in a folder whose latest version is a delete marker. Removing that marker restores
2566
+ * the object. Pages through ListObjectVersions with "/" as delimiter.
2567
+ */
2568
+ async function listDeleted(client, bucket, prefix, cursor) {
2569
+ let keyMarker;
2570
+ let versionMarker;
2571
+ if (cursor) [keyMarker, versionMarker] = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
2572
+ const objects = [];
2573
+ let next = null;
2574
+ for (let i = 0; i < 5; i++) {
2575
+ const out = await client.send(new ListObjectVersionsCommand({
2576
+ Bucket: bucket,
2577
+ Prefix: prefix || void 0,
2578
+ Delimiter: "/",
2579
+ KeyMarker: keyMarker,
2580
+ VersionIdMarker: versionMarker,
2581
+ MaxKeys: 1e3
2582
+ }));
2583
+ for (const m of out.DeleteMarkers ?? []) {
2584
+ if (!m.IsLatest || !m.Key || !m.VersionId || m.Key.endsWith("/")) continue;
2585
+ objects.push({
2586
+ key: m.Key,
2587
+ name: m.Key.split("/").pop() || m.Key,
2588
+ deletedAt: m.LastModified?.toISOString() ?? null,
2589
+ markerVersionId: m.VersionId
2590
+ });
2591
+ }
2592
+ if (!out.IsTruncated) {
2593
+ next = null;
2594
+ break;
2595
+ }
2596
+ keyMarker = out.NextKeyMarker;
2597
+ versionMarker = out.NextVersionIdMarker;
2598
+ next = Buffer.from(JSON.stringify([keyMarker, versionMarker])).toString("base64url");
2599
+ if (objects.length >= 200) break;
2600
+ }
2601
+ return {
2602
+ objects,
2603
+ nextCursor: next
2604
+ };
2605
+ }
2606
+ // src/server/routes/objects.ts
2607
+ const bucketParam = z.object({ bucket: bucketParamSchema });
2608
+ /** Types the browser may render inline. Everything else is shown as text or downloaded. */
2609
+ const INLINE_SAFE = /^(image\/(png|jpe?g|gif|webp|avif|bmp|x-icon|vnd\.microsoft\.icon)|video\/[\w.+-]+|audio\/[\w.+-]+|application\/pdf|text\/plain)$/i;
2610
+ /** RFC 6266 Content-Disposition with a UTF-8 filename. */
2611
+ function contentDisposition(type, filename) {
2612
+ return `${type}; filename="${filename.replace(/[^\x20-\x7e]/g, "_").replace(/["\\]/g, "_")}"; filename*=UTF-8''${encodeURIComponent(filename)}`;
2613
+ }
2614
+ function fileName(key) {
2615
+ return key.split("/").filter(Boolean).pop() ?? "download";
2616
+ }
2617
+ function objectRoutes(ctx) {
2618
+ const write = writable(ctx);
2619
+ return new Hono().get("/:bucket/objects", validate("param", bucketParam), validate("query", listQuerySchema), async (c) => {
2620
+ const conn = c.get("conn");
2621
+ const q = c.req.valid("query");
2622
+ const page = await listPage(conn.handle.client, c.req.valid("param").bucket, {
2623
+ prefix: q.prefix,
2624
+ cursor: q.cursor,
2625
+ flat: q.flat === "1",
2626
+ limit: q.limit
2627
+ });
2628
+ return c.json(page);
2629
+ }).get("/:bucket/details", validate("param", bucketParam), validate("query", keyQuerySchema), async (c) => {
2630
+ const conn = c.get("conn");
2631
+ const { bucket } = c.req.valid("param");
2632
+ const { key, versionId } = c.req.valid("query");
2633
+ const h = await headObject(conn.handle.client, bucket, key, versionId);
2634
+ const body = {
2635
+ key,
2636
+ size: h.ContentLength ?? 0,
2637
+ etag: h.ETag ?? null,
2638
+ lastModified: h.LastModified?.toISOString() ?? null,
2639
+ storageClass: h.StorageClass ?? "STANDARD",
2640
+ versionId: h.VersionId ?? null,
2641
+ contentType: h.ContentType ?? null,
2642
+ cacheControl: h.CacheControl ?? null,
2643
+ contentDisposition: h.ContentDisposition ?? null,
2644
+ contentEncoding: h.ContentEncoding ?? null,
2645
+ metadata: h.Metadata ?? {},
2646
+ headers: headersOf(h),
2647
+ publicUrl: publicObjectUrl({
2648
+ bucket,
2649
+ key,
2650
+ endpoint: conn.endpoint,
2651
+ region: conn.region,
2652
+ forcePathStyle: conn.handle.forcePathStyle,
2653
+ publicUrlBase: conn.publicUrlBase
2654
+ }),
2655
+ ...await objectExtras(conn.handle.client, bucket, key, h, { objectLock: conn.provider.capabilities.objectLock })
2656
+ };
2657
+ return c.json(body);
2658
+ }).get("/:bucket/download", validate("param", bucketParam), validate("query", downloadQuerySchema), async (c) => {
2659
+ const conn = c.get("conn");
2660
+ const { bucket } = c.req.valid("param");
2661
+ const { key, versionId, inline } = c.req.valid("query");
2662
+ const range = c.req.header("range");
2663
+ if (range && !/^bytes=\d*-\d*$/.test(range)) throw new HttpError(416, "BAD_RANGE", "Unsupported Range header");
2664
+ const out = await conn.handle.client.send(new GetObjectCommand({
2665
+ Bucket: bucket,
2666
+ Key: key,
2667
+ VersionId: versionId,
2668
+ Range: range
2669
+ }), { abortSignal: c.req.raw.signal });
2670
+ const name = fileName(key);
2671
+ const storedType = (out.ContentType || mime.lookup(name) || "application/octet-stream").toLowerCase();
2672
+ const baseType = storedType.split(";")[0]?.trim() ?? "";
2673
+ const isInline = inline === "1";
2674
+ const safe = INLINE_SAFE.test(baseType);
2675
+ const headers = new Headers({
2676
+ "Content-Type": isInline && !safe ? "text/plain; charset=utf-8" : storedType,
2677
+ "Content-Disposition": contentDisposition(isInline ? "inline" : "attachment", name),
2678
+ "X-Content-Type-Options": "nosniff",
2679
+ "Cache-Control": "private, no-store",
2680
+ "Accept-Ranges": "bytes"
2681
+ });
2682
+ if (baseType !== "application/pdf") headers.set("Content-Security-Policy", "default-src 'none'; img-src 'self' data:; media-src 'self'; style-src 'unsafe-inline'; sandbox");
2683
+ if (out.ContentLength !== void 0) headers.set("Content-Length", String(out.ContentLength));
2684
+ if (out.ContentRange) headers.set("Content-Range", out.ContentRange);
2685
+ if (out.ETag) headers.set("ETag", out.ETag);
2686
+ if (out.LastModified) headers.set("Last-Modified", out.LastModified.toUTCString());
2687
+ if (out.ContentEncoding && isInline) headers.set("Content-Encoding", out.ContentEncoding);
2688
+ const body = out.Body?.transformToWebStream() ?? null;
2689
+ return new Response(body, {
2690
+ status: out.ContentRange ? 206 : 200,
2691
+ headers
2692
+ });
2693
+ }).put("/:bucket/upload", write, validate("param", bucketParam), validate("query", uploadQuerySchema), async (c) => {
2694
+ const conn = c.get("conn");
2695
+ const { bucket } = c.req.valid("param");
2696
+ const { key, contentType } = c.req.valid("query");
2697
+ if (key.endsWith("/")) throw new HttpError(400, "VALIDATION", "File keys must not end with \"/\"");
2698
+ const raw = c.req.raw.body;
2699
+ if (!raw) throw new HttpError(400, "VALIDATION", "Missing request body");
2700
+ const type = contentType || c.req.header("content-type") || mime.lookup(key) || "application/octet-stream";
2701
+ const body = Readable.fromWeb(raw);
2702
+ const { etag } = await uploadStream(conn.handle.client, {
2703
+ bucket,
2704
+ key,
2705
+ body,
2706
+ contentType: type,
2707
+ signal: c.req.raw.signal
2708
+ });
2709
+ logActivity(ctx, c, "object.upload", {
2710
+ bucket,
2711
+ detail: key
2712
+ });
2713
+ return c.json({
2714
+ key,
2715
+ etag
2716
+ }, 201);
2717
+ }).post("/:bucket/folder", write, validate("param", bucketParam), validate("json", createFolderSchema), async (c) => {
2718
+ await createFolder(c.get("conn").handle.client, c.req.valid("param").bucket, c.req.valid("json").prefix);
2719
+ logActivity(ctx, c, "folder.create", {
2720
+ bucket: c.req.valid("param").bucket,
2721
+ detail: c.req.valid("json").prefix
2722
+ });
2723
+ return c.json({ ok: true }, 201);
2724
+ }).post("/:bucket/summary", validate("param", bucketParam), validate("json", summarySchema), async (c) => {
2725
+ const conn = c.get("conn");
2726
+ const { bucket } = c.req.valid("param");
2727
+ const { keys, prefixes } = c.req.valid("json");
2728
+ const sizes = /* @__PURE__ */ new Map();
2729
+ await mapLimit(keys, 8, async (key) => {
2730
+ const h = await headObject(conn.handle.client, bucket, key);
2731
+ sizes.set(key, h.ContentLength ?? 0);
2732
+ });
2733
+ return c.json(await summarize(conn.handle.client, bucket, prefixes, sizes, c.req.raw.signal));
2734
+ }).post("/:bucket/delete", write, validate("param", bucketParam), validate("json", deleteSchema), async (c) => {
2735
+ const conn = c.get("conn");
2736
+ const input = c.req.valid("json");
2737
+ const result = await deleteItems(conn.handle.client, c.req.valid("param").bucket, input);
2738
+ logActivity(ctx, c, "object.delete", {
2739
+ bucket: c.req.valid("param").bucket,
2740
+ detail: `${describeKeys([...input.prefixes, ...input.keys])} (${result.deleted} objects)`
2741
+ });
2742
+ return c.json(result);
2743
+ }).post("/:bucket/copy", write, validate("param", bucketParam), validate("json", copySchema), async (c) => {
2744
+ const conn = c.get("conn");
2745
+ const input = c.req.valid("json");
2746
+ const result = await copyItems(conn.handle.client, c.req.valid("param").bucket, input);
2747
+ logActivity(ctx, c, input.move ? "object.move" : "object.copy", {
2748
+ bucket: c.req.valid("param").bucket,
2749
+ detail: `${describeKeys(input.items.map((i) => `${i.source} → ${input.destinationBucket}/${i.destination}`))}`
2750
+ });
2751
+ return c.json(result);
2752
+ }).post("/:bucket/presign", validate("param", bucketParam), validate("json", presignSchema), async (c) => {
2753
+ const conn = c.get("conn");
2754
+ const input = c.req.valid("json");
2755
+ if (input.method === "PUT" && ctx.config.readonly) throw new HttpError(403, "READONLY", "Upload links are disabled in read-only mode");
2756
+ return c.json(await presign(conn.handle.client, c.req.valid("param").bucket, input));
2757
+ }).post("/:bucket/metadata", write, validate("param", bucketParam), validate("json", metadataSchema), async (c) => {
2758
+ const conn = c.get("conn");
2759
+ const { bucket } = c.req.valid("param");
2760
+ const { keys, ...changes } = c.req.valid("json");
2761
+ await mapLimit(keys, 8, (key) => updateMetadata(conn.handle.client, bucket, key, changes));
2762
+ logActivity(ctx, c, "object.metadata", {
2763
+ bucket,
2764
+ detail: describeKeys(keys)
2765
+ });
2766
+ return c.json({ updated: keys.length });
2767
+ }).get("/:bucket/tags", validate("param", bucketParam), validate("query", keyQuerySchema), async (c) => {
2768
+ const conn = c.get("conn");
2769
+ const { key, versionId } = c.req.valid("query");
2770
+ return c.json({ tags: await getTags(conn.handle.client, c.req.valid("param").bucket, key, versionId) });
2771
+ }).put("/:bucket/tags", write, validate("param", bucketParam), validate("json", tagsSchema), async (c) => {
2772
+ const conn = c.get("conn");
2773
+ if (!conn.provider.capabilities.tagging) throw new HttpError(501, "UNSUPPORTED", "Tags are not supported by this provider");
2774
+ const { bucket } = c.req.valid("param");
2775
+ const { keys, tags, versionId } = c.req.valid("json");
2776
+ await mapLimit(keys, 8, (key) => setTags(conn.handle.client, bucket, key, tags, keys.length === 1 ? versionId : void 0));
2777
+ logActivity(ctx, c, "object.tags", {
2778
+ bucket,
2779
+ detail: describeKeys(keys)
2780
+ });
2781
+ return c.json({ updated: keys.length });
2782
+ }).get("/:bucket/versions", validate("param", bucketParam), validate("query", z.object({ key: objectKeySchema })), async (c) => {
2783
+ const conn = c.get("conn");
2784
+ return c.json({ versions: await listVersions(conn.handle.client, c.req.valid("param").bucket, c.req.valid("query").key) });
2785
+ }).post("/:bucket/versions/restore", write, validate("param", bucketParam), validate("json", versionActionSchema), async (c) => {
2786
+ const conn = c.get("conn");
2787
+ const { key, versionId } = c.req.valid("json");
2788
+ await restoreVersion(conn.handle.client, c.req.valid("param").bucket, key, versionId);
2789
+ logActivity(ctx, c, "version.restore", {
2790
+ bucket: c.req.valid("param").bucket,
2791
+ detail: `${key} @ ${versionId}`
2792
+ });
2793
+ return c.json({ ok: true });
2794
+ }).post("/:bucket/versions/delete", write, validate("param", bucketParam), validate("json", versionActionSchema), async (c) => {
2795
+ const conn = c.get("conn");
2796
+ const { key, versionId } = c.req.valid("json");
2797
+ await deleteVersion(conn.handle.client, c.req.valid("param").bucket, key, versionId);
2798
+ logActivity(ctx, c, "version.delete", {
2799
+ bucket: c.req.valid("param").bucket,
2800
+ detail: `${key} @ ${versionId}`
2801
+ });
2802
+ return c.json({ ok: true });
2803
+ }).post("/:bucket/zip", validate("param", bucketParam), validate("json", zipSchema), async (c) => {
2804
+ const conn = c.get("conn");
2805
+ const session = c.get("session");
2806
+ const { bucket } = c.req.valid("param");
2807
+ const input = c.req.valid("json");
2808
+ if (input.keys.length + input.prefixes.length === 0) throw new HttpError(400, "VALIDATION", "Nothing selected");
2809
+ const folderName = input.base.split("/").filter(Boolean).pop();
2810
+ const name = (input.name || folderName || bucket).replace(/[^\w.-]+/g, "_");
2811
+ const token = ctx.zipTokens.create({
2812
+ sessionId: session.id,
2813
+ connectionId: conn.id,
2814
+ bucket,
2815
+ base: input.base,
2816
+ keys: input.keys,
2817
+ prefixes: input.prefixes,
2818
+ name: name.endsWith(".zip") ? name : `${name}.zip`
2819
+ });
2820
+ return c.json({ token });
2821
+ }).post("/:bucket/multipart", write, validate("param", bucketParam), validate("json", multipartCreateSchema), async (c) => {
2822
+ const conn = c.get("conn");
2823
+ const { key, contentType } = c.req.valid("json");
2824
+ const type = contentType || mime.lookup(key) || "application/octet-stream";
2825
+ return c.json(await createMultipart(conn.handle.client, c.req.valid("param").bucket, key, type), 201);
2826
+ }).get("/:bucket/multipart/parts", validate("param", bucketParam), validate("query", multipartRefSchema), async (c) => {
2827
+ const conn = c.get("conn");
2828
+ const { key, uploadId } = c.req.valid("query");
2829
+ return c.json({ parts: await listParts(conn.handle.client, c.req.valid("param").bucket, key, uploadId) });
2830
+ }).put("/:bucket/multipart/part", write, validate("param", bucketParam), validate("query", multipartPartQuerySchema), async (c) => {
2831
+ const conn = c.get("conn");
2832
+ const declared = Number(c.req.header("content-length") ?? NaN);
2833
+ if (!Number.isFinite(declared) || declared <= 0) throw new HttpError(411, "LENGTH_REQUIRED", "Parts need a Content-Length");
2834
+ if (declared > 0x8000000) throw new HttpError(413, "TOO_LARGE", "Part is too large");
2835
+ const body = new Uint8Array(await c.req.arrayBuffer());
2836
+ if (body.byteLength !== declared) throw new HttpError(400, "INCOMPLETE", "Part was not fully received");
2837
+ const { key, uploadId, partNumber } = c.req.valid("query");
2838
+ return c.json(await uploadPart(conn.handle.client, c.req.valid("param").bucket, key, uploadId, partNumber, body));
2839
+ }).post("/:bucket/multipart/complete", write, validate("param", bucketParam), validate("json", multipartCompleteSchema), async (c) => {
2840
+ const conn = c.get("conn");
2841
+ const { bucket } = c.req.valid("param");
2842
+ const { key, uploadId, parts } = c.req.valid("json");
2843
+ const result = await completeMultipart(conn.handle.client, bucket, key, uploadId, parts);
2844
+ logActivity(ctx, c, "object.upload", {
2845
+ bucket,
2846
+ detail: key
2847
+ });
2848
+ return c.json({
2849
+ key,
2850
+ ...result
2851
+ });
2852
+ }).post("/:bucket/multipart/abort", write, validate("param", bucketParam), validate("json", multipartRefSchema), async (c) => {
2853
+ const conn = c.get("conn");
2854
+ const { bucket } = c.req.valid("param");
2855
+ const { key, uploadId } = c.req.valid("json");
2856
+ await abortMultipart(conn.handle.client, bucket, key, uploadId);
2857
+ logActivity(ctx, c, "upload.abort", {
2858
+ bucket,
2859
+ detail: key
2860
+ });
2861
+ return c.json({ ok: true });
2862
+ }).get("/:bucket/multipart", validate("param", bucketParam), async (c) => {
2863
+ const conn = c.get("conn");
2864
+ return c.json({ uploads: await listIncomplete(conn.handle.client, c.req.valid("param").bucket) });
2865
+ }).get("/:bucket/deleted", validate("param", bucketParam), validate("query", deletedQuerySchema), async (c) => {
2866
+ const conn = c.get("conn");
2867
+ const { prefix, cursor } = c.req.valid("query");
2868
+ return c.json(await listDeleted(conn.handle.client, c.req.valid("param").bucket, prefix, cursor));
2869
+ }).post("/:bucket/storage-class", write, validate("param", bucketParam), validate("json", storageClassSchema), async (c) => {
2870
+ const conn = c.get("conn");
2871
+ const { bucket } = c.req.valid("param");
2872
+ const { keys, storageClass } = c.req.valid("json");
2873
+ if (!conn.provider.capabilities.storageClasses.includes(storageClass)) throw new HttpError(400, "UNSUPPORTED", `${conn.provider.name} doesn't offer the ${storageClass} storage class`);
2874
+ await mapLimit(keys, 4, (key) => changeStorageClass(conn.handle.client, bucket, key, storageClass));
2875
+ logActivity(ctx, c, "object.storage-class", {
2876
+ bucket,
2877
+ detail: `${describeKeys(keys)} → ${storageClass}`
2878
+ });
2879
+ return c.json({ updated: keys.length });
2880
+ }).post("/:bucket/restore-archive", write, validate("param", bucketParam), validate("json", restoreArchiveSchema), async (c) => {
2881
+ const conn = c.get("conn");
2882
+ if (!conn.provider.capabilities.archiveRestore) throw new HttpError(501, "UNSUPPORTED", "Archive restore is not supported by this provider");
2883
+ const { bucket } = c.req.valid("param");
2884
+ const { keys, days, tier } = c.req.valid("json");
2885
+ await mapLimit(keys, 8, (key) => restoreArchived(conn.handle.client, bucket, key, days, tier));
2886
+ logActivity(ctx, c, "object.restore-archive", {
2887
+ bucket,
2888
+ detail: `${describeKeys(keys)} (${tier}, ${days} days)`
2889
+ });
2890
+ return c.json({ requested: keys.length });
2891
+ });
2892
+ }
2893
+ async function index(loc, signal) {
2894
+ const map = /* @__PURE__ */ new Map();
2895
+ for await (const page of walkObjects(loc.client, loc.bucket, loc.prefix, signal)) for (const o of page) {
2896
+ const key = o.Key;
2897
+ if (key.endsWith("/")) continue;
2898
+ map.set(key.slice(loc.prefix.length), {
2899
+ size: o.Size ?? 0,
2900
+ etag: o.ETag?.replaceAll("\"", "") ?? null
2901
+ });
2902
+ if (map.size >= 2e5) return {
2903
+ map,
2904
+ truncated: true
2905
+ };
2906
+ }
2907
+ return {
2908
+ map,
2909
+ truncated: false
2910
+ };
2911
+ }
2912
+ /** Same content? Size must match; single-part ETags (plain MD5) must match when both sides have one. */
2913
+ function sameObject(a, b) {
2914
+ if (a.size !== b.size) return false;
2915
+ return a.etag && b.etag && !a.etag.includes("-") && !b.etag.includes("-") ? a.etag === b.etag : true;
2916
+ }
2917
+ async function compareLocations(source, target, signal) {
2918
+ const [s, t] = await Promise.all([index(source, signal), index(target, signal)]);
2919
+ const items = [];
2920
+ const counts = {
2921
+ missing: 0,
2922
+ changed: 0,
2923
+ extra: 0,
2924
+ same: 0
2925
+ };
2926
+ let bytesToCopy = 0;
2927
+ for (const [key, meta] of s.map) {
2928
+ const other = t.map.get(key);
2929
+ const status = !other ? "missing" : sameObject(meta, other) ? "same" : "changed";
2930
+ counts[status]++;
2931
+ if (status !== "same") bytesToCopy += meta.size;
2932
+ items.push({
2933
+ key,
2934
+ status,
2935
+ sourceSize: meta.size,
2936
+ targetSize: other?.size ?? null
2937
+ });
2938
+ }
2939
+ for (const [key, meta] of t.map) {
2940
+ if (s.map.has(key)) continue;
2941
+ counts.extra++;
2942
+ items.push({
2943
+ key,
2944
+ status: "extra",
2945
+ sourceSize: null,
2946
+ targetSize: meta.size
2947
+ });
2948
+ }
2949
+ items.sort((a, b) => a.key.localeCompare(b.key));
2950
+ return {
2951
+ items,
2952
+ counts,
2953
+ bytesToCopy,
2954
+ truncated: s.truncated || t.truncated
2955
+ };
2956
+ }
2957
+ /**
2958
+ * Copies missing and changed objects from source to target ("mirror" also deletes extras).
2959
+ * Same connection: server-side copy. Different connections: streamed through s3deck.
2960
+ */
2961
+ async function runSync(opts) {
2962
+ const { source, target, progress, signal } = opts;
2963
+ const diff = await compareLocations(source, target, signal);
2964
+ const toCopy = diff.items.filter((i) => i.status === "missing" || i.status === "changed");
2965
+ const toDelete = opts.mode === "mirror" ? diff.items.filter((i) => i.status === "extra") : [];
2966
+ progress.total = toCopy.length + toDelete.length;
2967
+ progress.bytesTotal = diff.bytesToCopy;
2968
+ await mapLimit(toCopy, 4, async (item) => {
2969
+ if (signal.aborted) return;
2970
+ const sourceKey = source.prefix + item.key;
2971
+ const targetKey = target.prefix + item.key;
2972
+ try {
2973
+ if (opts.sameConnection) await copyObject(source.client, {
2974
+ sourceBucket: source.bucket,
2975
+ sourceKey,
2976
+ destinationBucket: target.bucket,
2977
+ destinationKey: targetKey,
2978
+ size: item.sourceSize ?? 0
2979
+ });
2980
+ else {
2981
+ const got = await source.client.send(new GetObjectCommand({
2982
+ Bucket: source.bucket,
2983
+ Key: sourceKey
2984
+ }), { abortSignal: signal });
2985
+ const upload = new Upload({
2986
+ client: target.client,
2987
+ params: {
2988
+ Bucket: target.bucket,
2989
+ Key: targetKey,
2990
+ Body: got.Body,
2991
+ ContentType: got.ContentType,
2992
+ CacheControl: got.CacheControl,
2993
+ ContentDisposition: got.ContentDisposition,
2994
+ ContentEncoding: got.ContentEncoding,
2995
+ Metadata: got.Metadata
2996
+ },
2997
+ partSize: 16777216,
2998
+ queueSize: 2
2999
+ });
3000
+ const onAbort = () => void upload.abort().catch(() => {});
3001
+ signal.addEventListener("abort", onAbort, { once: true });
3002
+ try {
3003
+ await upload.done();
3004
+ } finally {
3005
+ signal.removeEventListener("abort", onAbort);
3006
+ }
3007
+ }
3008
+ progress.bytesDone += item.sourceSize ?? 0;
3009
+ } catch (err) {
3010
+ if (!signal.aborted) progress.errors.push({
3011
+ key: item.key,
3012
+ message: errorMessage(err)
3013
+ });
3014
+ } finally {
3015
+ progress.done++;
3016
+ }
3017
+ });
3018
+ if (toDelete.length && !signal.aborted) {
3019
+ const result = await deleteKeys(target.client, target.bucket, toDelete.map((i) => target.prefix + i.key));
3020
+ progress.errors.push(...result.errors);
3021
+ progress.done += toDelete.length;
3022
+ }
3023
+ }
3024
+ // src/server/routes/sync.ts
3025
+ /** Compare two folders (on any connections) and copy or mirror one onto the other in the background. */
3026
+ function syncRoutes(ctx) {
3027
+ const resolve = (c, loc) => {
3028
+ const conn = ctx.connections.getForSession(loc.connectionId, c.get("session"));
3029
+ if (!conn) throw new HttpError(404, "NOT_FOUND", "Connection not found");
3030
+ const prefix = loc.prefix && !loc.prefix.endsWith("/") ? `${loc.prefix}/` : loc.prefix;
3031
+ return {
3032
+ client: conn.handle.client,
3033
+ bucket: loc.bucket,
3034
+ prefix,
3035
+ connectionId: conn.id,
3036
+ label: conn.label
3037
+ };
3038
+ };
3039
+ const describe = (l) => `${l.bucket}/${l.prefix}`;
3040
+ const owner = (c) => hasRole(c.get("session").role, "admin") ? null : c.get("session").user;
3041
+ return new Hono().post("/sync/compare", validate("json", compareSchema), async (c) => {
3042
+ const { source, target } = c.req.valid("json");
3043
+ return c.json(await compareLocations(resolve(c, source), resolve(c, target), c.req.raw.signal));
3044
+ }).post("/sync", writable(ctx), validate("json", syncSchema), (c) => {
3045
+ const input = c.req.valid("json");
3046
+ const source = resolve(c, input.source);
3047
+ const target = resolve(c, input.target);
3048
+ if (source.connectionId === target.connectionId && source.bucket === target.bucket) {
3049
+ if (target.prefix.startsWith(source.prefix) || source.prefix.startsWith(target.prefix)) throw new HttpError(400, "VALIDATION", "Source and target folders overlap");
3050
+ }
3051
+ const title = `${input.mode === "mirror" ? "Mirror" : "Copy"} ${describe(source)} → ${describe(target)}`;
3052
+ const job = ctx.jobs.start(c.get("session").user, title, (signal, progress) => runSync({
3053
+ source,
3054
+ target,
3055
+ sameConnection: source.connectionId === target.connectionId,
3056
+ mode: input.mode,
3057
+ signal,
3058
+ progress
3059
+ }));
3060
+ logActivity(ctx, c, `sync.${input.mode}`, {
3061
+ bucket: target.bucket,
3062
+ detail: `${source.label}:${describe(source)} → ${target.label}:${describe(target)}`
3063
+ });
3064
+ return c.json(job, 201);
3065
+ }).get("/jobs", (c) => c.json({ jobs: ctx.jobs.list(owner(c)) })).get("/jobs/:id", (c) => {
3066
+ const job = ctx.jobs.get(c.req.param("id"), owner(c));
3067
+ if (!job) throw new HttpError(404, "NOT_FOUND", "Job not found");
3068
+ return c.json(job);
3069
+ }).delete("/jobs/:id", (c) => {
3070
+ if (!ctx.jobs.cancel(c.req.param("id"), owner(c))) throw new HttpError(404, "NOT_FOUND", "No running job with that ID");
3071
+ return c.json({ ok: true });
3072
+ });
3073
+ }
3074
+ // src/server/static.ts
3075
+ /** Serves the built UI. Hashed assets are cached forever; index.html never is. */
3076
+ function createStaticHandler(webRoot) {
3077
+ const root = path.resolve(webRoot);
3078
+ const index = (c) => {
3079
+ return readFile(path.join(root, "index.html"), "utf8").then((html) => {
3080
+ c.header("Cache-Control", "no-cache");
3081
+ c.header("X-Content-Type-Options", "nosniff");
3082
+ c.header("Referrer-Policy", "no-referrer");
3083
+ c.header("X-Frame-Options", "DENY");
3084
+ c.header("Content-Security-Policy", [
3085
+ "default-src 'self'",
3086
+ "script-src 'self'",
3087
+ "style-src 'self' 'unsafe-inline'",
3088
+ "img-src 'self' data: blob:",
3089
+ "media-src 'self' blob:",
3090
+ "frame-src 'self' blob:",
3091
+ "connect-src 'self'",
3092
+ "object-src 'none'",
3093
+ "base-uri 'self'",
3094
+ "form-action 'self'",
3095
+ "frame-ancestors 'none'"
3096
+ ].join("; "));
3097
+ return c.html(html);
3098
+ }, () => c.text("The web UI is not built. Run \"pnpm build\".", 500));
3099
+ };
3100
+ return async (c, relPath) => {
3101
+ if (relPath === "" || relPath === "index.html") return index(c);
3102
+ const file = path.resolve(root, relPath);
3103
+ if (!file.startsWith(root + path.sep)) return c.notFound();
3104
+ try {
3105
+ if (!(await stat(file)).isFile()) throw new Error("not a file");
3106
+ const data = await readFile(file);
3107
+ c.header("Content-Type", mime.contentType(path.extname(file)) || "application/octet-stream");
3108
+ c.header("X-Content-Type-Options", "nosniff");
3109
+ c.header("Cache-Control", relPath.startsWith("assets/") ? "public, max-age=31536000, immutable" : "no-cache");
3110
+ return c.body(data);
3111
+ } catch {
3112
+ return relPath.startsWith("assets/") ? c.notFound() : index(c);
3113
+ }
3114
+ };
3115
+ }
3116
+ // src/server/app.ts
3117
+ function createApp(ctx) {
3118
+ const { config } = ctx;
3119
+ ctx.sessions.onDestroy((s) => ctx.connections.removeOwnedBy(s.id));
3120
+ const api = new Hono();
3121
+ api.use(csrf());
3122
+ api.use(loadSession(ctx));
3123
+ api.route("/auth", authRoutes(ctx));
3124
+ const authed = new Hono();
3125
+ authed.use(requireAuth());
3126
+ authed.route("/connections", connectionRoutes(ctx));
3127
+ authed.route("/admin", adminRoutes(ctx));
3128
+ authed.route("/", syncRoutes(ctx));
3129
+ const storage = new Hono();
3130
+ storage.use(withConnection(ctx));
3131
+ storage.route("/buckets", bucketRoutes(ctx));
3132
+ storage.route("/buckets", objectRoutes(ctx));
3133
+ /** Step 2 of a ZIP download: a plain GET the browser can navigate to. */
3134
+ storage.get("/zip/:token", async (c) => {
3135
+ const session = c.get("session");
3136
+ const req = ctx.zipTokens.take(c.req.param("token"), session.id);
3137
+ if (!req) throw new HttpError(404, "NOT_FOUND", "This download link has expired");
3138
+ const conn = ctx.connections.getForSession(req.connectionId, session);
3139
+ if (!conn) throw new HttpError(409, "NO_CONNECTION", "Connection is gone");
3140
+ const archive = zipStream(conn.handle.client, req.bucket, req, c.req.raw.signal);
3141
+ return new Response(Readable.toWeb(archive), { headers: {
3142
+ "Content-Type": "application/zip",
3143
+ "Content-Disposition": contentDisposition("attachment", req.name),
3144
+ "Cache-Control": "no-store",
3145
+ "X-Content-Type-Options": "nosniff"
3146
+ } });
3147
+ });
3148
+ authed.route("/", storage);
3149
+ api.route("/", authed);
3150
+ api.all("*", () => {
3151
+ throw new HttpError(404, "NOT_FOUND", "No such API route");
3152
+ });
3153
+ const app = new Hono();
3154
+ app.onError(onError);
3155
+ app.use(secureHeaders({
3156
+ contentSecurityPolicy: void 0,
3157
+ crossOriginEmbedderPolicy: false,
3158
+ crossOriginResourcePolicy: "same-origin",
3159
+ referrerPolicy: "no-referrer",
3160
+ xFrameOptions: "SAMEORIGIN"
3161
+ }));
3162
+ const base = config.basePath;
3163
+ if (base) app.get(base, (c) => c.redirect(`${base}/`, 301));
3164
+ app.get(`${base}/healthz`, (c) => c.json({ ok: true }));
3165
+ app.route(`${base}/api`, api);
3166
+ if (config.webRoot) {
3167
+ const serve = createStaticHandler(config.webRoot);
3168
+ app.get(`${base}/*`, (c) => {
3169
+ const rel = decodeURIComponent(c.req.path.slice(base.length + 1));
3170
+ return serve(c, rel);
3171
+ });
3172
+ }
3173
+ return app;
3174
+ }
3175
+ // src/server/start.ts
3176
+ /** Starts the HTTP server and resolves once it's listening. */
3177
+ function startServer(ctx) {
3178
+ const app = createApp(ctx);
3179
+ return new Promise((resolve, reject) => {
3180
+ const server = serve({
3181
+ fetch: app.fetch,
3182
+ hostname: ctx.config.host,
3183
+ port: ctx.config.port
3184
+ }, (info) => {
3185
+ resolve({
3186
+ server,
3187
+ port: info.port
3188
+ });
3189
+ });
3190
+ server.once("error", reject);
3191
+ if ("requestTimeout" in server) server.requestTimeout = 0;
3192
+ if ("headersTimeout" in server) server.headersTimeout = 6e4;
3193
+ });
3194
+ }
3195
+ // src/server/zip-tokens.ts
3196
+ const TTL_MS = 3e5;
3197
+ /**
3198
+ * ZIP downloads are started with a POST (so the selection can be large and the request
3199
+ * carries the CSRF header), which returns a one-time token the browser then GETs.
3200
+ */
3201
+ var ZipTokens = class {
3202
+ tokens = /* @__PURE__ */ new Map();
3203
+ create(req) {
3204
+ this.sweep();
3205
+ const token = randomBytes(24).toString("base64url");
3206
+ this.tokens.set(token, {
3207
+ ...req,
3208
+ expiresAt: Date.now() + TTL_MS
3209
+ });
3210
+ return token;
3211
+ }
3212
+ /** Returns and removes the request, if it exists, hasn't expired and belongs to the session. */
3213
+ take(token, sessionId) {
3214
+ const req = this.tokens.get(token);
3215
+ if (!req) return null;
3216
+ this.tokens.delete(token);
3217
+ if (req.expiresAt < Date.now() || req.sessionId !== sessionId) return null;
3218
+ return req;
3219
+ }
3220
+ sweep() {
3221
+ const now = Date.now();
3222
+ for (const [t, r] of this.tokens) if (r.expiresAt < now) this.tokens.delete(t);
3223
+ }
3224
+ };
3225
+ // src/cli/banner.ts
3226
+ const LOOPBACK = /* @__PURE__ */ new Set([
3227
+ "127.0.0.1",
3228
+ "localhost",
3229
+ "::1"
3230
+ ]);
3231
+ function lanAddresses() {
3232
+ return Object.values(networkInterfaces()).flat().filter((i) => i && i.family === "IPv4" && !i.internal).map((i) => i.address);
3233
+ }
3234
+ function printBanner(b) {
3235
+ const label = (s) => pc.dim(s.padEnd(11));
3236
+ const lines = [
3237
+ "",
3238
+ ` ${pc.bold("s3deck")} ${pc.dim(`v${b.version}`)}`,
3239
+ ""
3240
+ ];
3241
+ if (b.connection.ok) {
3242
+ const c = b.connection;
3243
+ const where = c.endpoint ? `${c.providerName} at ${c.endpoint}` : c.providerName;
3244
+ lines.push(` ${pc.green("✓")} ${label("Connected")} ${where} ${pc.dim(`(region ${c.region})`)}`);
3245
+ const count = c.bucketCount !== null ? `${c.bucketCount} available` : `${c.pinned} configured (key can't list buckets)`;
3246
+ lines.push(` ${label("Buckets")} ${count}`);
3247
+ } else {
3248
+ lines.push(` ${pc.yellow("!")} ${label("No storage")} ${b.connection.message}`);
3249
+ lines.push(` ${label("")} ${b.data.savedConnections ? "Remembered connections are available after signing in." : b.browserConnections ? "Enter credentials in the browser to connect." : pc.red("Browser connections are disabled.")}`);
3250
+ }
3251
+ lines.push(` ${pc.cyan("➜")} ${label("Web UI")} ${pc.cyan(pc.underline(b.url))}`);
3252
+ if (b.dev) lines.push(` ${label("Dev UI")} ${pc.cyan("http://localhost:47716/")} ${pc.dim("(Vite, hot reload)")}`);
3253
+ if (LOOPBACK.has(b.host)) lines.push(` ${label("Reachable")} from this machine only ${pc.dim(`(remote: ssh -L ${b.port}:127.0.0.1:${b.port} …)`)}`);
3254
+ else if (b.host === "0.0.0.0" || b.host === "::") {
3255
+ const lan = lanAddresses().map((a) => `http://${a}:${b.port}/`);
3256
+ lines.push(` ${label("Reachable")} on all interfaces${lan.length ? ` ${pc.dim(lan.join(" "))}` : ""}`);
3257
+ } else lines.push(` ${label("Reachable")} on ${b.host}`);
3258
+ if (b.auth.enabled) lines.push(` ${label("Login")} ${b.auth.user} / ${b.auth.generated ? pc.bold(b.auth.password) : pc.dim("(your password)")}`);
3259
+ else lines.push(` ${label("Login")} ${pc.yellow("disabled (--no-auth)")}`);
3260
+ if (b.readonly) lines.push(` ${label("Mode")} read-only`);
3261
+ lines.push(` ${label("Data")} ${b.data.dir}`);
3262
+ const extras = [b.data.users ? `${b.data.users} user${b.data.users === 1 ? "" : "s"}` : "", b.data.savedConnections ? `${b.data.savedConnections} remembered connection${b.data.savedConnections === 1 ? "" : "s"}` : ""].filter(Boolean);
3263
+ if (extras.length) lines.push(` ${label("")} ${pc.dim(extras.join(" · "))}`);
3264
+ if (b.data.sso) lines.push(` ${label("SSO")} ${b.data.sso}`);
3265
+ if (!b.auth.enabled && !LOOPBACK.has(b.host)) lines.push("", ` ${pc.red("⚠")} ${pc.red(pc.bold("Login is disabled on a public interface."))} Anyone who can reach this port gets full access to your storage.`);
3266
+ lines.push("");
3267
+ console.log(lines.join("\n"));
3268
+ }
3269
+ // src/cli/credentials.ts
3270
+ /** Region from --region / AWS_REGION, then the profile's config file, then the provider default. */
3271
+ async function resolveRegion(opts) {
3272
+ if (opts.region) return opts.region;
3273
+ if (process.env.AWS_DEFAULT_REGION) return process.env.AWS_DEFAULT_REGION;
3274
+ const provider = detectProvider(opts.endpoint);
3275
+ if (provider.defaultRegion) return provider.defaultRegion;
3276
+ try {
3277
+ const probe = new S3Client({ profile: opts.profile });
3278
+ const region = await probe.config.region();
3279
+ probe.destroy();
3280
+ if (region) return region;
3281
+ } catch {}
3282
+ return DEFAULT_REGION;
3283
+ }
3284
+ /**
3285
+ * Credentials, in order: --access-key/--secret-key, AWS_* env vars, a profile from
3286
+ * ~/.aws (incl. SSO and assumed roles), then instance/container/web identity.
3287
+ */
3288
+ async function resolveStartupConnection(opts) {
3289
+ if (!!opts.accessKey !== !!opts.secretKey) throw new Error("--access-key and --secret-key must be used together");
3290
+ const region = await resolveRegion(opts);
3291
+ const base = {
3292
+ source: "cli",
3293
+ endpoint: opts.endpoint ?? null,
3294
+ region,
3295
+ pathStyle: opts.pathStyle === void 0 ? "auto" : "path",
3296
+ pinnedBuckets: opts.bucket
3297
+ };
3298
+ if (opts.accessKey && opts.secretKey) return { spec: {
3299
+ ...base,
3300
+ accessKeyId: opts.accessKey,
3301
+ credentials: {
3302
+ accessKeyId: opts.accessKey,
3303
+ secretAccessKey: opts.secretKey,
3304
+ sessionToken: opts.sessionToken
3305
+ }
3306
+ } };
3307
+ const provider = fromNodeProviderChain({ profile: opts.profile });
3308
+ try {
3309
+ const creds = await provider();
3310
+ return { spec: {
3311
+ ...base,
3312
+ accessKeyId: creds.accessKeyId,
3313
+ credentials: provider
3314
+ } };
3315
+ } catch (err) {
3316
+ return {
3317
+ spec: null,
3318
+ reason: err instanceof Error ? err.message.split("\n")[0] : String(err)
3319
+ };
3320
+ }
3321
+ }
3322
+ // src/cli/options.ts
3323
+ const optionsSchema = z.object({
3324
+ endpoint: z.string().trim().refine((v) => {
3325
+ try {
3326
+ return ["http:", "https:"].includes(new URL(v).protocol);
3327
+ } catch {
3328
+ return false;
3329
+ }
3330
+ }, "endpoint must be an http(s) URL, e.g. http://localhost:9000").optional(),
3331
+ port: z.coerce.number().int().min(0).max(65535),
3332
+ host: z.string().trim().min(1),
3333
+ user: z.string().trim().min(1).max(128),
3334
+ password: z.string().min(8, "password must be at least 8 characters").max(256).optional(),
3335
+ auth: z.boolean(),
3336
+ region: regionSchema.optional(),
3337
+ profile: z.string().trim().min(1).optional(),
3338
+ accessKey: z.string().trim().min(1).optional(),
3339
+ secretKey: z.string().min(1).optional(),
3340
+ sessionToken: z.string().min(1).optional(),
3341
+ pathStyle: z.boolean().optional(),
3342
+ bucket: z.array(bucketParamSchema).default([]),
3343
+ readonly: z.boolean().default(false),
3344
+ basePath: z.string().trim().regex(/^\/?[\w\-./~]*$/, "base path may only contain URL path characters").transform((v) => {
3345
+ const trimmed = v.replace(/^\/+|\/+$/g, "");
3346
+ return trimmed ? `/${trimmed}` : "";
3347
+ }).default(""),
3348
+ open: z.boolean().default(false),
3349
+ browserConnections: z.boolean().default(true),
3350
+ dataDir: z.string().trim().min(1).optional(),
3351
+ persist: z.boolean().default(true),
3352
+ publicUrl: z.string().trim().refine((v) => {
3353
+ try {
3354
+ return ["http:", "https:"].includes(new URL(v).protocol);
3355
+ } catch {
3356
+ return false;
3357
+ }
3358
+ }, "public URL must be an http(s) URL").optional(),
3359
+ dev: z.boolean().default(false)
3360
+ });
3361
+ const collect = (value, previous = []) => [...previous, value];
3362
+ function buildProgram(version) {
3363
+ return new Command().name("s3deck").description("A fast, modern web UI for S3 and S3-compatible storage.").argument("[endpoint]", "S3 endpoint URL. Leave out for AWS S3").addOption(new Option("-p, --port <port>", "port for the web UI").env("PORT").default(String(DEFAULT_PORT))).addOption(new Option("-H, --host <host>", "interface to bind (0.0.0.0 for containers/LAN)").default(DEFAULT_HOST)).addOption(new Option("-u, --user <name>", "login username").default(DEFAULT_USER)).addOption(new Option("-P, --password <password>", "login password (random if not set)").env("S3DECK_PASSWORD")).option("--no-auth", "disable the login page (trusted machines only)").addOption(new Option("--region <region>", "region to sign requests for").env("AWS_REGION")).addOption(new Option("--profile <name>", "AWS profile to use").env("AWS_PROFILE")).option("--access-key <id>", "access key ID (prefer AWS_ACCESS_KEY_ID)").option("--secret-key <secret>", "secret access key (prefer AWS_SECRET_ACCESS_KEY)").option("--session-token <token>", "session token for temporary credentials").option("--path-style", "use path-style URLs (host/bucket/key)").option("--bucket <name>", "open this bucket directly; repeat for several", collect).option("--readonly", "disable uploads, edits and deletes").option("--base-path <path>", "serve under a path prefix such as /s3").option("--open", "open the UI in your browser").option("--no-browser-connections", "don't let users enter credentials in the browser").addOption(new Option("--data-dir <dir>", "where users, remembered connections and the activity log are kept").env("S3DECK_DATA_DIR")).option("--no-persist", "don't write anything to disk (no users, remembered connections or activity file)").addOption(new Option("--public-url <url>", "public URL of this s3deck, for single sign-on redirects").env("S3DECK_PUBLIC_URL")).addOption(new Option("--dev", "development mode (UI served by Vite)").hideHelp()).version(version, "-v, --version", "print the version").helpOption("-h, --help", "show help").showHelpAfterError("(run s3deck --help for usage)");
3364
+ }
3365
+ function parseOptions(program) {
3366
+ const raw = program.opts();
3367
+ const endpoint = program.args[0] ?? process.env.AWS_ENDPOINT_URL_S3 ?? process.env.AWS_ENDPOINT_URL;
3368
+ const result = optionsSchema.safeParse({
3369
+ ...raw,
3370
+ endpoint: endpoint || void 0
3371
+ });
3372
+ if (!result.success) program.error(`error: ${formatZodError(result.error)}`, { exitCode: 2 });
3373
+ return result.data;
3374
+ }
3375
+ // src/cli/index.ts
3376
+ function generatePassword() {
3377
+ return randomBytes(9).toString("base64url");
3378
+ }
3379
+ /** dist/web next to the built CLI, or the repo's dist/web when running from source. */
3380
+ function findWebRoot() {
3381
+ const here = path.dirname(fileURLToPath(import.meta.url));
3382
+ return [path.join(here, "web"), path.resolve(here, "../../dist/web")].find((p) => existsSync(path.join(p, "index.html"))) ?? null;
3383
+ }
3384
+ async function main() {
3385
+ const program = buildProgram(version);
3386
+ program.parse();
3387
+ const opts = parseOptions(program);
3388
+ const password = opts.password ?? generatePassword();
3389
+ const registry = new ConnectionRegistry();
3390
+ let connection;
3391
+ try {
3392
+ const { spec, reason } = await resolveStartupConnection(opts);
3393
+ if (!spec) connection = {
3394
+ ok: false,
3395
+ message: `no credentials found ${pc.dim(`(${reason})`)}`
3396
+ };
3397
+ else {
3398
+ const { connection: conn, bucketCount } = await openConnection(spec);
3399
+ registry.setDefault(conn);
3400
+ connection = {
3401
+ ok: true,
3402
+ providerName: conn.provider.name,
3403
+ endpoint: conn.endpoint,
3404
+ region: conn.region,
3405
+ bucketCount,
3406
+ pinned: conn.pinnedBuckets.length
3407
+ };
3408
+ }
3409
+ } catch (err) {
3410
+ connection = {
3411
+ ok: false,
3412
+ message: `could not connect: ${errorMessage(err)}`
3413
+ };
3414
+ }
3415
+ if (!connection.ok && !opts.browserConnections) {
3416
+ console.error(pc.red(`\n s3deck: ${connection.message}\n`));
3417
+ process.exit(1);
3418
+ }
3419
+ let dataDir = null;
3420
+ let users = null;
3421
+ let saved = null;
3422
+ let persistNote;
3423
+ if (opts.persist) {
3424
+ const dir = resolveDataDir(opts.dataDir);
3425
+ try {
3426
+ await ensureDir(dir);
3427
+ const key = await loadSecretKey(dir);
3428
+ users = new UserStore(dir);
3429
+ await users.load();
3430
+ saved = new SavedConnectionStore(dir, key);
3431
+ await saved.load();
3432
+ for (const item of saved.all()) registry.add(connectionFromSaved(item));
3433
+ dataDir = dir;
3434
+ persistNote = dir;
3435
+ } catch (err) {
3436
+ users = null;
3437
+ saved = null;
3438
+ persistNote = pc.yellow(`unavailable (${errorMessage(err)})`);
3439
+ }
3440
+ } else persistNote = "off (--no-persist)";
3441
+ const ssoConfig = ssoConfigFromEnv();
3442
+ const activity = new ActivityLog(dataDir);
3443
+ await activity.load().catch(() => {});
3444
+ const webRoot = opts.dev ? null : findWebRoot();
3445
+ if (!opts.dev && !webRoot) console.warn(pc.yellow(" Web UI not found. Run \"pnpm build\" first."));
3446
+ const ctx = {
3447
+ config: {
3448
+ host: opts.host,
3449
+ port: opts.port,
3450
+ basePath: opts.basePath,
3451
+ auth: {
3452
+ enabled: opts.auth,
3453
+ user: opts.user,
3454
+ password
3455
+ },
3456
+ readonly: opts.readonly,
3457
+ version,
3458
+ webRoot,
3459
+ allowBrowserConnections: opts.browserConnections,
3460
+ dataDir,
3461
+ publicUrl: opts.publicUrl ?? null,
3462
+ dev: opts.dev
3463
+ },
3464
+ sessions: new SessionStore(),
3465
+ connections: registry,
3466
+ zipTokens: new ZipTokens(),
3467
+ loginLimiter: new RateLimiter(10, 9e5),
3468
+ users,
3469
+ saved,
3470
+ activity,
3471
+ jobs: new JobRegistry(),
3472
+ sso: ssoConfig ? new SsoService(ssoConfig) : null
3473
+ };
3474
+ let started;
3475
+ try {
3476
+ started = await startServer(ctx);
3477
+ } catch (err) {
3478
+ const msg = err.code === "EADDRINUSE" ? `port ${opts.port} is already in use (try --port)` : errorMessage(err);
3479
+ console.error(pc.red(`\n s3deck: ${msg}\n`));
3480
+ process.exit(1);
3481
+ }
3482
+ const displayHost = opts.host === "0.0.0.0" || opts.host === "::" ? "127.0.0.1" : opts.host;
3483
+ const url = `http://${displayHost.includes(":") ? `[${displayHost}]` : displayHost}:${started.port}${opts.basePath}/`;
3484
+ printBanner({
3485
+ version,
3486
+ connection,
3487
+ url,
3488
+ host: opts.host,
3489
+ port: started.port,
3490
+ auth: {
3491
+ enabled: opts.auth,
3492
+ user: opts.user,
3493
+ password,
3494
+ generated: !opts.password
3495
+ },
3496
+ readonly: opts.readonly,
3497
+ browserConnections: opts.browserConnections,
3498
+ dev: opts.dev,
3499
+ data: {
3500
+ dir: persistNote,
3501
+ users: users?.list().length ?? 0,
3502
+ savedConnections: saved?.all().length ?? 0,
3503
+ sso: ssoConfig ? ssoConfig.issuer : null
3504
+ }
3505
+ });
3506
+ if (opts.open) {
3507
+ const { default: open } = await import("open");
3508
+ await open(opts.dev ? "http://localhost:47716/" : url).catch(() => {});
3509
+ }
3510
+ const shutdown = () => {
3511
+ ctx.sessions.close();
3512
+ started.server.close();
3513
+ process.exit(0);
3514
+ };
3515
+ process.once("SIGINT", shutdown);
3516
+ process.once("SIGTERM", shutdown);
3517
+ }
3518
+ main().catch((err) => {
3519
+ console.error(pc.red(`\n s3deck: ${errorMessage(err)}\n`));
3520
+ process.exit(1);
3521
+ });
3522
+ export {};