@conloca/content-api 0.2.0 → 0.2.2
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/asset-metadata-store.d.ts.map +1 -1
- package/dist/asset-operations.d.ts +20 -34
- package/dist/asset-operations.d.ts.map +1 -1
- package/dist/asset-operations.js +219 -166
- package/dist/asset-operations.js.map +1 -1
- package/dist/asset-usage.d.ts +5 -4
- package/dist/asset-usage.d.ts.map +1 -1
- package/dist/asset-usage.js +6 -5
- package/dist/asset-usage.js.map +1 -1
- package/dist/cf-access.d.ts +4 -2
- package/dist/cf-access.d.ts.map +1 -1
- package/dist/cf-access.js +29 -13
- package/dist/cf-access.js.map +1 -1
- package/dist/component-registry.d.ts +0 -3
- package/dist/component-registry.d.ts.map +1 -1
- package/dist/content-file-id.d.ts +9 -0
- package/dist/content-file-id.d.ts.map +1 -0
- package/dist/content-file-id.js +33 -0
- package/dist/content-file-id.js.map +1 -0
- package/dist/content-operations.js +2 -2
- package/dist/content-operations.js.map +1 -1
- package/dist/content-path.d.ts +5 -0
- package/dist/content-path.d.ts.map +1 -1
- package/dist/content-path.js +7 -0
- package/dist/content-path.js.map +1 -1
- package/dist/filesystem-content-api.d.ts +0 -15
- package/dist/filesystem-content-api.d.ts.map +1 -1
- package/dist/filesystem-content-api.js +60 -17
- package/dist/filesystem-content-api.js.map +1 -1
- package/dist/git-operations.d.ts.map +1 -1
- package/dist/git-operations.js +162 -34
- package/dist/git-operations.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +0 -1
- package/dist/index.js.map +1 -1
- package/dist/middleware.d.ts +2 -0
- package/dist/middleware.d.ts.map +1 -1
- package/dist/middleware.js +21 -31
- package/dist/middleware.js.map +1 -1
- package/dist/schemas/index.d.ts +9 -97
- package/dist/schemas/index.d.ts.map +1 -1
- package/dist/schemas/index.js +8 -83
- package/dist/schemas/index.js.map +1 -1
- package/dist/schemas/normalize.d.ts +101 -0
- package/dist/schemas/normalize.d.ts.map +1 -0
- package/dist/schemas/normalize.js +168 -0
- package/dist/schemas/normalize.js.map +1 -0
- package/dist/schemas/types.d.ts +135 -0
- package/dist/schemas/types.d.ts.map +1 -0
- package/dist/schemas/types.js +17 -0
- package/dist/schemas/types.js.map +1 -0
- package/dist/schemas/validators.d.ts +46 -0
- package/dist/schemas/validators.d.ts.map +1 -0
- package/dist/schemas/validators.js +938 -0
- package/dist/schemas/validators.js.map +1 -0
- package/dist/types.d.ts +7 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +12 -5
- package/src/asset-operations.ts +260 -187
- package/src/asset-usage.ts +6 -5
- package/src/cf-access.ts +30 -14
- package/src/content-file-id.ts +31 -0
- package/src/content-operations.ts +2 -2
- package/src/content-path.ts +8 -0
- package/src/filesystem-content-api.ts +72 -17
- package/src/git-operations.ts +188 -41
- package/src/index.ts +17 -1
- package/src/middleware.ts +23 -37
- package/src/schemas/index.ts +34 -108
- package/src/schemas/normalize.ts +194 -0
- package/src/schemas/types.ts +154 -0
- package/src/schemas/validators.ts +176 -0
- package/src/types.ts +7 -0
package/src/asset-operations.ts
CHANGED
|
@@ -1,26 +1,32 @@
|
|
|
1
|
-
import type
|
|
2
|
-
import {
|
|
3
|
-
|
|
1
|
+
import { createReadStream, type Dirent, type Stats } from 'node:fs';
|
|
2
|
+
import {
|
|
3
|
+
type FileHandle,
|
|
4
|
+
link,
|
|
5
|
+
lstat,
|
|
6
|
+
mkdir,
|
|
7
|
+
open,
|
|
8
|
+
readdir,
|
|
9
|
+
readFile,
|
|
10
|
+
stat,
|
|
11
|
+
unlink,
|
|
12
|
+
writeFile,
|
|
13
|
+
} from 'node:fs/promises';
|
|
14
|
+
import { basename, dirname, extname, join, parse, resolve, sep } from 'node:path';
|
|
15
|
+
import { pipeline } from 'node:stream/promises';
|
|
4
16
|
import { imageSizeFromFile } from 'image-size/fromFile';
|
|
5
17
|
import { DEFAULT_ACCEPTED_FORMATS, DEFAULT_MAX_FILE_SIZE, IMAGE_EXTENSION_MIME } from './asset-constraints.js';
|
|
6
18
|
import * as assetMetadata from './asset-metadata-store.js';
|
|
7
|
-
import type {
|
|
8
|
-
AssetEntry,
|
|
9
|
-
AssetMetadata,
|
|
10
|
-
AssetMetadataPatch,
|
|
11
|
-
AssetUsage,
|
|
12
|
-
FolderListing,
|
|
13
|
-
FolderTreeNode,
|
|
14
|
-
} from './asset-types.js';
|
|
19
|
+
import type { AssetEntry, AssetMetadata, AssetMetadataPatch, FolderListing, FolderTreeNode } from './asset-types.js';
|
|
15
20
|
import { setupGitLfsAttributes } from './git-operations.js';
|
|
16
|
-
import type { JsonValue } from './types.js';
|
|
17
21
|
import { validateFetchUrl } from './url-validation.js';
|
|
18
22
|
|
|
19
23
|
export interface AssetConfig {
|
|
20
24
|
assetsPath: string;
|
|
21
25
|
maxFileSize?: number;
|
|
26
|
+
/** Wall-clock budget for a URL import: every redirect hop plus reading the whole body */
|
|
27
|
+
importTimeoutMs?: number;
|
|
22
28
|
acceptedFormats?: string[];
|
|
23
|
-
/** The content root: it holds each asset's metadata record
|
|
29
|
+
/** The content root: it holds each asset's metadata record */
|
|
24
30
|
contentRoot: string;
|
|
25
31
|
}
|
|
26
32
|
|
|
@@ -33,23 +39,7 @@ const SYSTEM_FILES = new Set(['.ds_store', 'thumbs.db', '.gitkeep', 'desktop.ini
|
|
|
33
39
|
/** Max redirect hops a URL import may follow (each re-validated before it is requested) */
|
|
34
40
|
const MAX_IMPORT_REDIRECTS = 5;
|
|
35
41
|
|
|
36
|
-
|
|
37
|
-
async function vxjsonFiles(dir: string): Promise<string[]> {
|
|
38
|
-
let entries: Dirent[];
|
|
39
|
-
try {
|
|
40
|
-
entries = await readdir(dir, { withFileTypes: true });
|
|
41
|
-
} catch {
|
|
42
|
-
return [];
|
|
43
|
-
}
|
|
44
|
-
const nested = await Promise.all(
|
|
45
|
-
entries.map(async (entry): Promise<string[]> => {
|
|
46
|
-
const fullPath = join(dir, entry.name);
|
|
47
|
-
if (entry.isDirectory() && !entry.name.startsWith('.')) return vxjsonFiles(fullPath);
|
|
48
|
-
return entry.isFile() && entry.name.endsWith('.vxjson') ? [fullPath] : [];
|
|
49
|
-
}),
|
|
50
|
-
);
|
|
51
|
-
return nested.flat();
|
|
52
|
-
}
|
|
42
|
+
const DEFAULT_IMPORT_TIMEOUT_MS = 30_000;
|
|
53
43
|
|
|
54
44
|
/** Check if filename has a recognized web image extension */
|
|
55
45
|
function isRecognizedImageExtension(filename: string): boolean {
|
|
@@ -81,6 +71,7 @@ export class AssetOperations {
|
|
|
81
71
|
this.config = {
|
|
82
72
|
assetsPath: config.assetsPath,
|
|
83
73
|
maxFileSize: config.maxFileSize ?? DEFAULT_MAX_FILE_SIZE,
|
|
74
|
+
importTimeoutMs: config.importTimeoutMs ?? DEFAULT_IMPORT_TIMEOUT_MS,
|
|
84
75
|
// Copy: the shared default is frozen, but AssetConfig stays a plain string[]
|
|
85
76
|
acceptedFormats: config.acceptedFormats ?? [...DEFAULT_ACCEPTED_FORMATS],
|
|
86
77
|
contentRoot: config.contentRoot,
|
|
@@ -354,7 +345,8 @@ export class AssetOperations {
|
|
|
354
345
|
}
|
|
355
346
|
|
|
356
347
|
/**
|
|
357
|
-
* Get asset by filename and
|
|
348
|
+
* Get asset by filename and folder; the default '/' is the top of the assets folder, never a
|
|
349
|
+
* same-named file in another folder
|
|
358
350
|
*/
|
|
359
351
|
async getAsset(filename: string, folder = '/'): Promise<AssetEntry | undefined> {
|
|
360
352
|
const relativePath = folder === '/' ? filename : `${folder.slice(1)}/${filename}`;
|
|
@@ -390,21 +382,23 @@ export class AssetOperations {
|
|
|
390
382
|
|
|
391
383
|
const relativePath = folder === '/' ? filename : `${folder.slice(1)}/${filename}`;
|
|
392
384
|
|
|
393
|
-
//
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
385
|
+
// Queued with moves: a delete landing mid-move could otherwise remove the only copy
|
|
386
|
+
// between the move's destination check and its removal of the source.
|
|
387
|
+
await withMoveQueue(async () => {
|
|
388
|
+
try {
|
|
389
|
+
await unlink(assetPath);
|
|
390
|
+
} catch {
|
|
391
|
+
// File may already be gone, continue with metadata cleanup
|
|
392
|
+
}
|
|
393
|
+
await assetMetadata.remove(this.config, relativePath);
|
|
394
|
+
});
|
|
401
395
|
return { success: true };
|
|
402
396
|
}
|
|
403
397
|
|
|
404
398
|
/**
|
|
405
399
|
* Import an image from a URL (server-side fetch, no CORS issues)
|
|
406
|
-
* Validates the URL and every redirect hop against SSRF,
|
|
407
|
-
* and
|
|
400
|
+
* Validates the URL and every redirect hop against SSRF, and bounds the whole
|
|
401
|
+
* transfer — headers and body — by one time budget and the max file size.
|
|
408
402
|
*/
|
|
409
403
|
async importFromUrl(
|
|
410
404
|
url: string,
|
|
@@ -417,76 +411,114 @@ export class AssetOperations {
|
|
|
417
411
|
return { success: false, error: err instanceof Error ? err.message : 'Invalid URL' };
|
|
418
412
|
}
|
|
419
413
|
|
|
420
|
-
//
|
|
421
|
-
//
|
|
422
|
-
//
|
|
423
|
-
//
|
|
414
|
+
// One wall-clock budget covers every hop AND the body read: a server that
|
|
415
|
+
// sends headers promptly and then trickles bytes must not hold the import
|
|
416
|
+
// open. Redirects are followed MANUALLY so every hop's target runs through
|
|
417
|
+
// the SSRF guard BEFORE it is requested — otherwise a public URL can
|
|
418
|
+
// redirect into a loopback or link-local (cloud metadata) address that the
|
|
419
|
+
// initial check would have rejected.
|
|
424
420
|
const controller = new AbortController();
|
|
425
|
-
const timeout = setTimeout(() => controller.abort(),
|
|
426
|
-
let response: Response | undefined;
|
|
427
|
-
let current = url;
|
|
421
|
+
const timeout = setTimeout(() => controller.abort(), this.config.importTimeoutMs);
|
|
428
422
|
try {
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
423
|
+
let response: Response | undefined;
|
|
424
|
+
let current = url;
|
|
425
|
+
try {
|
|
426
|
+
for (let hop = 0; hop <= MAX_IMPORT_REDIRECTS; hop += 1) {
|
|
427
|
+
const hopResponse = await fetch(current, { signal: controller.signal, redirect: 'manual' });
|
|
428
|
+
if (hopResponse.status < 300 || hopResponse.status >= 400) {
|
|
429
|
+
response = hopResponse;
|
|
430
|
+
break;
|
|
431
|
+
}
|
|
432
|
+
// A redirect body is never read; release its connection now.
|
|
433
|
+
await hopResponse.body?.cancel().catch(() => {});
|
|
434
|
+
const location = hopResponse.headers.get('location');
|
|
435
|
+
if (location === null) {
|
|
436
|
+
return { success: false, error: 'Redirect missing Location header' };
|
|
437
|
+
}
|
|
438
|
+
try {
|
|
439
|
+
// A relative Location is legal and common; resolve it against the URL
|
|
440
|
+
// that produced it, then validate the absolute result.
|
|
441
|
+
current = validateFetchUrl(new URL(location, current).toString()).toString();
|
|
442
|
+
} catch (err) {
|
|
443
|
+
return { success: false, error: `Redirect blocked: ${err instanceof Error ? err.message : 'Invalid URL'}` };
|
|
444
|
+
}
|
|
445
445
|
}
|
|
446
|
+
} catch {
|
|
447
|
+
return { success: false, error: controller.signal.aborted ? 'URL import timed out' : 'Failed to fetch URL' };
|
|
446
448
|
}
|
|
447
|
-
} catch {
|
|
448
|
-
return { success: false, error: 'Failed to fetch URL' };
|
|
449
|
-
} finally {
|
|
450
|
-
clearTimeout(timeout);
|
|
451
|
-
}
|
|
452
|
-
|
|
453
|
-
// Budget exhausted without a final response — fail closed rather than
|
|
454
|
-
// treating the last redirect as content
|
|
455
|
-
if (!response) {
|
|
456
|
-
return { success: false, error: 'Too many redirects' };
|
|
457
|
-
}
|
|
458
449
|
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
450
|
+
// Budget exhausted without a final response — fail closed rather than
|
|
451
|
+
// treating the last redirect as content
|
|
452
|
+
if (!response) {
|
|
453
|
+
return { success: false, error: 'Too many redirects' };
|
|
454
|
+
}
|
|
462
455
|
|
|
463
|
-
// Early size check from Content-Length header
|
|
464
|
-
const contentLength = response.headers.get('content-length');
|
|
465
|
-
if (contentLength && Number.parseInt(contentLength, 10) > this.config.maxFileSize) {
|
|
466
456
|
const maxMB = Math.round(this.config.maxFileSize / (1024 * 1024));
|
|
467
|
-
|
|
468
|
-
}
|
|
457
|
+
const tooLarge = { success: false as const, error: `Remote file too large. Maximum: ${maxMB}MB` };
|
|
469
458
|
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
const decoded = decodeURIComponent(lastSegment);
|
|
475
|
-
if (!/\p{Cc}/u.test(decoded)) urlFilename = decoded.split(/[/\\]/).pop() || lastSegment;
|
|
476
|
-
} catch {
|
|
477
|
-
// A malformed escape keeps the filename as written in the address.
|
|
478
|
-
}
|
|
459
|
+
if (!response.ok) {
|
|
460
|
+
await response.body?.cancel().catch(() => {});
|
|
461
|
+
return { success: false, error: `Fetch failed with status ${response.status}` };
|
|
462
|
+
}
|
|
479
463
|
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
464
|
+
// Early size check from Content-Length header
|
|
465
|
+
const contentLength = response.headers.get('content-length');
|
|
466
|
+
if (contentLength && Number.parseInt(contentLength, 10) > this.config.maxFileSize) {
|
|
467
|
+
await response.body?.cancel().catch(() => {});
|
|
468
|
+
return tooLarge;
|
|
469
|
+
}
|
|
486
470
|
|
|
487
|
-
|
|
471
|
+
const contentType = response.headers.get('content-type') || '';
|
|
472
|
+
const lastSegment = new URL(url).pathname.split('/').pop() || 'imported-image.jpg';
|
|
473
|
+
let urlFilename = lastSegment;
|
|
474
|
+
try {
|
|
475
|
+
const decoded = decodeURIComponent(lastSegment);
|
|
476
|
+
if (!/\p{Cc}/u.test(decoded)) urlFilename = decoded.split(/[/\\]/).pop() || lastSegment;
|
|
477
|
+
} catch {
|
|
478
|
+
// A malformed escape keeps the filename as written in the address.
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
// Stream the body, stopping the moment it passes the limit: Content-Length
|
|
482
|
+
// is optional and may lie, so it cannot be trusted to bound memory.
|
|
483
|
+
const chunks: Uint8Array[] = [];
|
|
484
|
+
let received = 0;
|
|
485
|
+
if (response.body) {
|
|
486
|
+
const reader = response.body.getReader();
|
|
487
|
+
// A body that ignores the abort signal must still stop at the deadline.
|
|
488
|
+
const onAbort = () => void reader.cancel().catch(() => {});
|
|
489
|
+
controller.signal.addEventListener('abort', onAbort, { once: true });
|
|
490
|
+
try {
|
|
491
|
+
while (true) {
|
|
492
|
+
const { done, value } = await reader.read();
|
|
493
|
+
if (controller.signal.aborted) return { success: false, error: 'URL import timed out' };
|
|
494
|
+
if (done) break;
|
|
495
|
+
received += value.byteLength;
|
|
496
|
+
if (received > this.config.maxFileSize) {
|
|
497
|
+
await reader.cancel().catch(() => {});
|
|
498
|
+
return tooLarge;
|
|
499
|
+
}
|
|
500
|
+
chunks.push(value);
|
|
501
|
+
}
|
|
502
|
+
} catch {
|
|
503
|
+
await reader.cancel().catch(() => {});
|
|
504
|
+
return { success: false, error: controller.signal.aborted ? 'URL import timed out' : 'Failed to fetch URL' };
|
|
505
|
+
} finally {
|
|
506
|
+
controller.signal.removeEventListener('abort', onAbort);
|
|
507
|
+
}
|
|
508
|
+
}
|
|
488
509
|
|
|
489
|
-
|
|
510
|
+
const bytes = new Uint8Array(received);
|
|
511
|
+
let offset = 0;
|
|
512
|
+
for (const chunk of chunks) {
|
|
513
|
+
bytes.set(chunk, offset);
|
|
514
|
+
offset += chunk.byteLength;
|
|
515
|
+
}
|
|
516
|
+
const file = new File([bytes], urlFilename, { type: contentType });
|
|
517
|
+
|
|
518
|
+
return this.upload(file, metadata);
|
|
519
|
+
} finally {
|
|
520
|
+
clearTimeout(timeout);
|
|
521
|
+
}
|
|
490
522
|
}
|
|
491
523
|
|
|
492
524
|
/**
|
|
@@ -616,53 +648,7 @@ export class AssetOperations {
|
|
|
616
648
|
return { success: true, asset: await this.assetEntry(filename, folder, stats, metadata) };
|
|
617
649
|
}
|
|
618
650
|
|
|
619
|
-
/**
|
|
620
|
-
* Get usage information for an asset (which pages reference it)
|
|
621
|
-
* @param filename Asset filename
|
|
622
|
-
*/
|
|
623
|
-
async getUsage(filename: string): Promise<AssetUsage[]> {
|
|
624
|
-
const usages: AssetUsage[] = [];
|
|
625
|
-
|
|
626
|
-
// Search patterns for the asset
|
|
627
|
-
const searchPatterns = [filename, `/assets/uploads/${filename}`, `assets/uploads/${filename}`];
|
|
628
|
-
|
|
629
|
-
const files = await vxjsonFiles(this.config.contentRoot);
|
|
630
|
-
// Promise.all preserves `files` order while avoiding serial disk reads.
|
|
631
|
-
const documents = await Promise.all(
|
|
632
|
-
files.map(async (filePath) => {
|
|
633
|
-
try {
|
|
634
|
-
return { filePath, content: await readFile(filePath, 'utf-8') };
|
|
635
|
-
} catch {
|
|
636
|
-
return null;
|
|
637
|
-
}
|
|
638
|
-
}),
|
|
639
|
-
);
|
|
640
|
-
|
|
641
|
-
for (const document of documents) {
|
|
642
|
-
if (document === null) continue;
|
|
643
|
-
const { filePath, content } = document;
|
|
644
|
-
if (!searchPatterns.some((pattern) => content.includes(pattern))) continue;
|
|
645
|
-
|
|
646
|
-
const relativePath = filePath.replace(this.config.contentRoot, '').replace(/^[/\\]/, '');
|
|
647
|
-
const pageName = relativePath.replace(/\.vxjson$/, '');
|
|
648
|
-
let field = 'content';
|
|
649
|
-
try {
|
|
650
|
-
const json: JsonValue = JSON.parse(content);
|
|
651
|
-
field = this.findFieldWithAsset(json, searchPatterns) || 'content';
|
|
652
|
-
} catch {
|
|
653
|
-
// An unreadable JSON document can still be reported by its text match.
|
|
654
|
-
}
|
|
655
|
-
usages.push({ page: pageName, field });
|
|
656
|
-
}
|
|
657
|
-
|
|
658
|
-
return usages;
|
|
659
|
-
}
|
|
660
|
-
|
|
661
|
-
/**
|
|
662
|
-
* Get the file path for an asset
|
|
663
|
-
* @param filename Asset filename
|
|
664
|
-
* @param folder Optional folder path (defaults to asset's stored folder)
|
|
665
|
-
*/
|
|
651
|
+
/** The file path of an asset in a folder; no folder, or '/', is the top of the assets folder. */
|
|
666
652
|
getAssetPath(filename: string, folder?: string): string {
|
|
667
653
|
const subpath = folder && folder !== '/' ? folder.replace(/^\/+|\/+$/g, '') : '';
|
|
668
654
|
const combined = subpath ? `${subpath}/${filename}` : filename;
|
|
@@ -699,35 +685,6 @@ export class AssetOperations {
|
|
|
699
685
|
}
|
|
700
686
|
}
|
|
701
687
|
|
|
702
|
-
/**
|
|
703
|
-
* Helper to find which field contains an asset reference
|
|
704
|
-
*/
|
|
705
|
-
private findFieldWithAsset(obj: JsonValue, patterns: string[], path = ''): string | null {
|
|
706
|
-
if (typeof obj === 'string') {
|
|
707
|
-
if (patterns.some((p) => obj.includes(p))) {
|
|
708
|
-
return path || 'root';
|
|
709
|
-
}
|
|
710
|
-
return null;
|
|
711
|
-
}
|
|
712
|
-
|
|
713
|
-
if (Array.isArray(obj)) {
|
|
714
|
-
for (let i = 0; i < obj.length; i++) {
|
|
715
|
-
const result = this.findFieldWithAsset(obj[i], patterns, path ? `${path}[${i}]` : `[${i}]`);
|
|
716
|
-
if (result) return result;
|
|
717
|
-
}
|
|
718
|
-
return null;
|
|
719
|
-
}
|
|
720
|
-
|
|
721
|
-
if (obj && typeof obj === 'object') {
|
|
722
|
-
for (const [key, value] of Object.entries(obj)) {
|
|
723
|
-
const result = this.findFieldWithAsset(value, patterns, path ? `${path}.${key}` : key);
|
|
724
|
-
if (result) return result;
|
|
725
|
-
}
|
|
726
|
-
}
|
|
727
|
-
|
|
728
|
-
return null;
|
|
729
|
-
}
|
|
730
|
-
|
|
731
688
|
/**
|
|
732
689
|
* Move assets from one folder to another
|
|
733
690
|
* @param filenames List of filenames to move
|
|
@@ -738,7 +695,7 @@ export class AssetOperations {
|
|
|
738
695
|
filenames: string[],
|
|
739
696
|
sourceFolder: string,
|
|
740
697
|
targetFolder: string,
|
|
741
|
-
): Promise<{ success: true; moved: number } | { success: false; error: string }> {
|
|
698
|
+
): Promise<{ success: true; moved: number } | { success: false; error: string; moved?: number }> {
|
|
742
699
|
// Normalize folder paths
|
|
743
700
|
const normalizedSource = sourceFolder === '/' ? '/' : `/${sourceFolder.replace(/^\/+|\/+$/g, '')}`;
|
|
744
701
|
const normalizedTarget = targetFolder === '/' ? '/' : `/${targetFolder.replace(/^\/+|\/+$/g, '')}`;
|
|
@@ -804,6 +761,7 @@ export class AssetOperations {
|
|
|
804
761
|
// Move each file with its own record, so one failure cannot take the rest
|
|
805
762
|
// of the folder's metadata with it
|
|
806
763
|
let moved = 0;
|
|
764
|
+
const failed: string[] = [];
|
|
807
765
|
for (const filename of filenames) {
|
|
808
766
|
const oldRelativePath = normalizedSource === '/' ? filename : `${normalizedSource.slice(1)}/${filename}`;
|
|
809
767
|
const newRelativePath = normalizedTarget === '/' ? filename : `${normalizedTarget.slice(1)}/${filename}`;
|
|
@@ -817,22 +775,23 @@ export class AssetOperations {
|
|
|
817
775
|
to = this.getAssetPath(filename, normalizedTarget);
|
|
818
776
|
} catch {
|
|
819
777
|
console.error(`[AssetOperations] Refusing to move ${filename}: it points outside the media library`);
|
|
778
|
+
failed.push(`${filename} (outside the media library)`);
|
|
820
779
|
continue;
|
|
821
780
|
}
|
|
822
781
|
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
782
|
+
// oxlint-disable-next-line no-await-in-loop -- each move settles before the next; partial failure stays attributable to one filename.
|
|
783
|
+
const outcome = await moveOneWithoutOverwrite(this.config, from, to, oldRelativePath, newRelativePath);
|
|
784
|
+
if (outcome === 'moved') {
|
|
785
|
+
moved += 1;
|
|
786
|
+
} else {
|
|
787
|
+
console.error(`[AssetOperations] Failed to move ${filename}: ${outcome}`);
|
|
788
|
+
failed.push(`${filename} (${outcome})`);
|
|
829
789
|
}
|
|
830
|
-
|
|
831
|
-
// oxlint-disable-next-line no-await-in-loop -- metadata must follow the file that just moved before the next file starts.
|
|
832
|
-
await assetMetadata.move(this.config, oldRelativePath, newRelativePath);
|
|
833
|
-
moved += 1;
|
|
834
790
|
}
|
|
835
791
|
|
|
792
|
+
if (failed.length > 0) {
|
|
793
|
+
return { success: false, moved, error: `Could not move: ${failed.join(', ')}` };
|
|
794
|
+
}
|
|
836
795
|
return { success: true, moved };
|
|
837
796
|
}
|
|
838
797
|
|
|
@@ -912,3 +871,117 @@ export class AssetOperations {
|
|
|
912
871
|
];
|
|
913
872
|
}
|
|
914
873
|
}
|
|
874
|
+
|
|
875
|
+
/**
|
|
876
|
+
* Asset moves and deletes in this process run one at a time: between claiming a destination
|
|
877
|
+
* and dropping its source, a move holds the asset at two paths, and a delete or second move
|
|
878
|
+
* acting on either path then could split bytes from metadata or remove the only copy.
|
|
879
|
+
* Module-wide because the router builds a fresh AssetOperations per request, and kept on
|
|
880
|
+
* globalThis (as the metadata store's locks are) because a dev server can load this module twice.
|
|
881
|
+
*/
|
|
882
|
+
declare global {
|
|
883
|
+
// Shared across duplicate module instances in one dev-server process.
|
|
884
|
+
var conlocaAssetMoveQueue: Promise<unknown> | undefined;
|
|
885
|
+
}
|
|
886
|
+
function withMoveQueue<T>(operation: () => Promise<T>): Promise<T> {
|
|
887
|
+
const result = (globalThis.conlocaAssetMoveQueue ?? Promise.resolve()).then(operation, operation);
|
|
888
|
+
globalThis.conlocaAssetMoveQueue = result.catch(() => undefined);
|
|
889
|
+
return result;
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
function isErrnoException(error: unknown): error is NodeJS.ErrnoException {
|
|
893
|
+
return error instanceof Error && 'code' in error;
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
/**
|
|
897
|
+
* Move one asset file and its metadata record without ever replacing a file at the destination.
|
|
898
|
+
* The listing check in moveAssets reports ordinary clashes up front; this closes the window in
|
|
899
|
+
* which an upload or another move claims the name afterwards. A hard link (or, where the
|
|
900
|
+
* filesystem has none, an exclusive copy) claims the destination name atomically, and the source
|
|
901
|
+
* stays until the metadata has followed. Any failure undoes what was done, leaving bytes and
|
|
902
|
+
* metadata where they were. Returns 'moved' or the reason the file stayed.
|
|
903
|
+
*/
|
|
904
|
+
function moveOneWithoutOverwrite(
|
|
905
|
+
roots: assetMetadata.MetadataRoots,
|
|
906
|
+
from: string,
|
|
907
|
+
to: string,
|
|
908
|
+
oldRelativePath: string,
|
|
909
|
+
newRelativePath: string,
|
|
910
|
+
): Promise<string> {
|
|
911
|
+
return withMoveQueue(() => moveOneNow(roots, from, to, oldRelativePath, newRelativePath));
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
async function moveOneNow(
|
|
915
|
+
roots: assetMetadata.MetadataRoots,
|
|
916
|
+
from: string,
|
|
917
|
+
to: string,
|
|
918
|
+
oldRelativePath: string,
|
|
919
|
+
newRelativePath: string,
|
|
920
|
+
): Promise<string> {
|
|
921
|
+
// Names differing only in letter case are one file on macOS and Windows. Moves run one at a
|
|
922
|
+
// time, so this re-check sees every earlier move, including earlier files of the same batch.
|
|
923
|
+
const wanted = basename(to).toLowerCase();
|
|
924
|
+
if ((await readdir(dirname(to))).some((name) => name.toLowerCase() === wanted)) {
|
|
925
|
+
return 'already in the target folder';
|
|
926
|
+
}
|
|
927
|
+
try {
|
|
928
|
+
await link(from, to);
|
|
929
|
+
} catch (err) {
|
|
930
|
+
const code = isErrnoException(err) ? err.code : undefined;
|
|
931
|
+
if (code === 'EEXIST') return 'already in the target folder';
|
|
932
|
+
if (code !== 'EPERM' && code !== 'ENOTSUP' && code !== 'EOPNOTSUPP' && code !== 'EXDEV' && code !== 'EMLINK') {
|
|
933
|
+
return err instanceof Error ? err.message : 'move failed';
|
|
934
|
+
}
|
|
935
|
+
// No hard links here: claim the name with an exclusive create first, so a failed copy
|
|
936
|
+
// only ever removes the file this move created, never one another request put there.
|
|
937
|
+
let claimed: FileHandle;
|
|
938
|
+
try {
|
|
939
|
+
claimed = await open(to, 'wx');
|
|
940
|
+
} catch (openErr) {
|
|
941
|
+
if (isErrnoException(openErr) && openErr.code === 'EEXIST') return 'already in the target folder';
|
|
942
|
+
return openErr instanceof Error ? openErr.message : 'move failed';
|
|
943
|
+
}
|
|
944
|
+
let copyError: unknown;
|
|
945
|
+
try {
|
|
946
|
+
// Streamed: an asset placed outside the upload route may be far larger than an upload.
|
|
947
|
+
await pipeline(createReadStream(from), claimed.createWriteStream({ autoClose: false }));
|
|
948
|
+
} catch (pipelineErr) {
|
|
949
|
+
copyError = pipelineErr;
|
|
950
|
+
} finally {
|
|
951
|
+
await claimed.close().catch(() => undefined);
|
|
952
|
+
}
|
|
953
|
+
if (copyError !== undefined) {
|
|
954
|
+
// Closed first: some platforms refuse to remove a file that is still open.
|
|
955
|
+
await unlink(to).catch(() => undefined);
|
|
956
|
+
return copyError instanceof Error ? copyError.message : 'move failed';
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
try {
|
|
961
|
+
await assetMetadata.move(roots, oldRelativePath, newRelativePath);
|
|
962
|
+
} catch (err) {
|
|
963
|
+
await unlink(to).catch(() => undefined);
|
|
964
|
+
return err instanceof Error ? err.message : 'metadata move failed';
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
// A delete aimed at the new path may have removed it meanwhile; dropping the source now
|
|
968
|
+
// would lose the only copy, so keep the source and put its metadata back.
|
|
969
|
+
if (
|
|
970
|
+
!(await lstat(to).then(
|
|
971
|
+
(s) => s.isFile(),
|
|
972
|
+
() => false,
|
|
973
|
+
))
|
|
974
|
+
) {
|
|
975
|
+
await assetMetadata.move(roots, newRelativePath, oldRelativePath).catch(() => undefined);
|
|
976
|
+
return 'removed from the target folder during the move';
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
try {
|
|
980
|
+
await unlink(from);
|
|
981
|
+
} catch (err) {
|
|
982
|
+
await assetMetadata.move(roots, newRelativePath, oldRelativePath).catch(() => undefined);
|
|
983
|
+
await unlink(to).catch(() => undefined);
|
|
984
|
+
return err instanceof Error ? err.message : 'move failed';
|
|
985
|
+
}
|
|
986
|
+
return 'moved';
|
|
987
|
+
}
|
package/src/asset-usage.ts
CHANGED
|
@@ -3,12 +3,13 @@ import type { ContentAPI } from './content-api.interface.js';
|
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Every page, fragment and data entry language whose meta or content links to an asset. The editor
|
|
6
|
-
* links an asset as `/assets/<path
|
|
7
|
-
* is no use of `beach.png` and neither is `/assets/my-beach.png` or
|
|
8
|
-
* such as `https://…/assets/beach.png` never counts, even one to this
|
|
6
|
+
* links an asset as `<assetRefBase>/<path>`, `/assets/<path>` by default; only that link standing whole
|
|
7
|
+
* counts, so `/assets/trip/beach.png` is no use of `beach.png` and neither is `/assets/my-beach.png` or
|
|
8
|
+
* `/assets/beach.png.bak`. A full URL such as `https://…/assets/beach.png` never counts, even one to this
|
|
9
|
+
* site, whose address is not known here.
|
|
9
10
|
*/
|
|
10
|
-
export async function findAssetUsage(api: ContentAPI, path: string): Promise<AssetUsage[]> {
|
|
11
|
-
const link =
|
|
11
|
+
export async function findAssetUsage(api: ContentAPI, path: string, assetRefBase = '/assets'): Promise<AssetUsage[]> {
|
|
12
|
+
const link = `${assetRefBase}/${path.replace(/^\/+|\/+$/g, '')}`;
|
|
12
13
|
const whole = new RegExp(`(?<![\\w.~%/-])${link.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![\\w./-])`);
|
|
13
14
|
const usage: AssetUsage[] = [];
|
|
14
15
|
const severalSites = Object.keys(api.sitesConfig.sites).length > 1;
|
package/src/cf-access.ts
CHANGED
|
@@ -3,18 +3,24 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Validates JWT tokens from CF Access for API authorization and git commit attribution.
|
|
5
5
|
* When CF_ACCESS_TEAM_NAME and CF_ACCESS_AUD env vars are set, requests must have valid tokens.
|
|
6
|
-
* When
|
|
6
|
+
* When neither is set (local dev), validation is skipped. When only one is set, every request is
|
|
7
|
+
* refused: Access was meant to be on, and skipping it would leave the CMS open.
|
|
7
8
|
*/
|
|
8
9
|
|
|
9
|
-
import { createRemoteJWKSet, jwtVerify } from 'jose';
|
|
10
|
+
import { createRemoteJWKSet, type JWTVerifyGetKey, jwtVerify } from 'jose';
|
|
10
11
|
|
|
11
|
-
|
|
12
|
-
|
|
12
|
+
// One JWKS per team, each with jose's built-in caching (handles key rotation automatically).
|
|
13
|
+
// The env is read per request so a config change or a test never sees a stale module-load value.
|
|
14
|
+
const jwksByTeam = new Map<string, JWTVerifyGetKey>();
|
|
13
15
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
16
|
+
function jwksFor(team: string): JWTVerifyGetKey {
|
|
17
|
+
let jwks = jwksByTeam.get(team);
|
|
18
|
+
if (!jwks) {
|
|
19
|
+
jwks = createRemoteJWKSet(new URL(`https://${team}.cloudflareaccess.com/cdn-cgi/access/certs`));
|
|
20
|
+
jwksByTeam.set(team, jwks);
|
|
21
|
+
}
|
|
22
|
+
return jwks;
|
|
23
|
+
}
|
|
18
24
|
|
|
19
25
|
export interface CFAccessUser {
|
|
20
26
|
email?: string;
|
|
@@ -46,15 +52,25 @@ export function extractCFAccessToken(request: Request): string | null {
|
|
|
46
52
|
/**
|
|
47
53
|
* Validate CF Access JWT from request.
|
|
48
54
|
*
|
|
49
|
-
* Returns { valid: true, required: false } when env
|
|
55
|
+
* Returns { valid: true, required: false } when neither env var is set (local dev mode).
|
|
56
|
+
* Returns { valid: false, required: true, error } when only one is set (misconfigured: fail closed).
|
|
50
57
|
* Returns { valid: true, required: true, user } when token is valid.
|
|
51
58
|
* Returns { valid: false, required: true, error } when token is invalid or missing.
|
|
52
59
|
*/
|
|
53
60
|
export async function validateCFAccessRequest(request: Request): Promise<CFAccessResult> {
|
|
54
|
-
//
|
|
55
|
-
|
|
61
|
+
// Whitespace-only counts as unset, so a blank line in an env file does not half-configure Access
|
|
62
|
+
const team = process.env.CF_ACCESS_TEAM_NAME?.trim() || undefined;
|
|
63
|
+
const audience = process.env.CF_ACCESS_AUD?.trim() || undefined;
|
|
64
|
+
if (!team && !audience) {
|
|
56
65
|
return { valid: true, required: false };
|
|
57
66
|
}
|
|
67
|
+
if (!team || !audience) {
|
|
68
|
+
return {
|
|
69
|
+
valid: false,
|
|
70
|
+
required: true,
|
|
71
|
+
error: 'CF Access is partially configured: set both CF_ACCESS_TEAM_NAME and CF_ACCESS_AUD, or neither',
|
|
72
|
+
};
|
|
73
|
+
}
|
|
58
74
|
|
|
59
75
|
const token = extractCFAccessToken(request);
|
|
60
76
|
if (!token) {
|
|
@@ -62,9 +78,9 @@ export async function validateCFAccessRequest(request: Request): Promise<CFAcces
|
|
|
62
78
|
}
|
|
63
79
|
|
|
64
80
|
try {
|
|
65
|
-
const { payload } = await jwtVerify(token,
|
|
66
|
-
issuer: `https://${
|
|
67
|
-
audience
|
|
81
|
+
const { payload } = await jwtVerify(token, jwksFor(team), {
|
|
82
|
+
issuer: `https://${team}.cloudflareaccess.com`,
|
|
83
|
+
audience,
|
|
68
84
|
});
|
|
69
85
|
|
|
70
86
|
return {
|