@conloca/content-api 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/dist/.build-inputs.json +71 -0
  2. package/dist/address-site.d.ts +6 -0
  3. package/dist/address-site.d.ts.map +1 -0
  4. package/dist/address-site.js +15 -0
  5. package/dist/address-site.js.map +1 -0
  6. package/dist/asset-operations.d.ts +15 -2
  7. package/dist/asset-operations.d.ts.map +1 -1
  8. package/dist/asset-operations.js +216 -78
  9. package/dist/asset-operations.js.map +1 -1
  10. package/dist/cf-access.d.ts +4 -2
  11. package/dist/cf-access.d.ts.map +1 -1
  12. package/dist/cf-access.js +29 -13
  13. package/dist/cf-access.js.map +1 -1
  14. package/dist/content-file-id.d.ts +9 -0
  15. package/dist/content-file-id.d.ts.map +1 -0
  16. package/dist/content-file-id.js +33 -0
  17. package/dist/content-file-id.js.map +1 -0
  18. package/dist/content-utils.d.ts +4 -1
  19. package/dist/content-utils.d.ts.map +1 -1
  20. package/dist/content-utils.js +14 -1
  21. package/dist/content-utils.js.map +1 -1
  22. package/dist/editor-host.d.ts +121 -0
  23. package/dist/editor-host.d.ts.map +1 -0
  24. package/dist/editor-host.js +212 -0
  25. package/dist/editor-host.js.map +1 -0
  26. package/dist/filesystem-content-api.d.ts.map +1 -1
  27. package/dist/filesystem-content-api.js +3 -2
  28. package/dist/filesystem-content-api.js.map +1 -1
  29. package/dist/git-operations.d.ts.map +1 -1
  30. package/dist/git-operations.js +162 -34
  31. package/dist/git-operations.js.map +1 -1
  32. package/dist/index.d.ts +2 -1
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +2 -1
  35. package/dist/index.js.map +1 -1
  36. package/dist/middleware.d.ts.map +1 -1
  37. package/dist/middleware.js +5 -0
  38. package/dist/middleware.js.map +1 -1
  39. package/dist/schemas/index.d.ts +9 -97
  40. package/dist/schemas/index.d.ts.map +1 -1
  41. package/dist/schemas/index.js +8 -83
  42. package/dist/schemas/index.js.map +1 -1
  43. package/dist/schemas/normalize.d.ts +101 -0
  44. package/dist/schemas/normalize.d.ts.map +1 -0
  45. package/dist/schemas/normalize.js +168 -0
  46. package/dist/schemas/normalize.js.map +1 -0
  47. package/dist/schemas/types.d.ts +135 -0
  48. package/dist/schemas/types.d.ts.map +1 -0
  49. package/dist/schemas/types.js +17 -0
  50. package/dist/schemas/types.js.map +1 -0
  51. package/dist/schemas/validators.d.ts +46 -0
  52. package/dist/schemas/validators.d.ts.map +1 -0
  53. package/dist/schemas/validators.js +938 -0
  54. package/dist/schemas/validators.js.map +1 -0
  55. package/dist/site.d.ts.map +1 -1
  56. package/dist/site.js +3 -1
  57. package/dist/site.js.map +1 -1
  58. package/dist/types.d.ts +9 -0
  59. package/dist/types.d.ts.map +1 -1
  60. package/package.json +17 -5
  61. package/src/address-site.ts +19 -0
  62. package/src/asset-operations.ts +256 -83
  63. package/src/cf-access.ts +30 -14
  64. package/src/content-file-id.ts +31 -0
  65. package/src/content-utils.ts +18 -2
  66. package/src/editor-host.ts +268 -0
  67. package/src/filesystem-content-api.ts +3 -2
  68. package/src/git-operations.ts +188 -41
  69. package/src/index.ts +19 -1
  70. package/src/middleware.ts +5 -0
  71. package/src/schemas/index.ts +34 -108
  72. package/src/schemas/normalize.ts +194 -0
  73. package/src/schemas/types.ts +154 -0
  74. package/src/schemas/validators.ts +176 -0
  75. package/src/site.ts +3 -1
  76. package/src/types.ts +9 -0
@@ -1,6 +1,18 @@
1
- import type { Dirent, Stats } from 'node:fs';
2
- import { lstat, mkdir, readdir, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises';
3
- import { extname, join, parse, resolve, sep } from 'node:path';
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';
@@ -11,6 +23,8 @@ import { validateFetchUrl } from './url-validation.js';
11
23
  export interface AssetConfig {
12
24
  assetsPath: string;
13
25
  maxFileSize?: number;
26
+ /** Wall-clock budget for a URL import: every redirect hop plus reading the whole body */
27
+ importTimeoutMs?: number;
14
28
  acceptedFormats?: string[];
15
29
  /** The content root: it holds each asset's metadata record */
16
30
  contentRoot: string;
@@ -25,6 +39,8 @@ const SYSTEM_FILES = new Set(['.ds_store', 'thumbs.db', '.gitkeep', 'desktop.ini
25
39
  /** Max redirect hops a URL import may follow (each re-validated before it is requested) */
26
40
  const MAX_IMPORT_REDIRECTS = 5;
27
41
 
42
+ const DEFAULT_IMPORT_TIMEOUT_MS = 30_000;
43
+
28
44
  /** Check if filename has a recognized web image extension */
29
45
  function isRecognizedImageExtension(filename: string): boolean {
30
46
  const ext = extname(filename).slice(1).toLowerCase();
@@ -55,6 +71,7 @@ export class AssetOperations {
55
71
  this.config = {
56
72
  assetsPath: config.assetsPath,
57
73
  maxFileSize: config.maxFileSize ?? DEFAULT_MAX_FILE_SIZE,
74
+ importTimeoutMs: config.importTimeoutMs ?? DEFAULT_IMPORT_TIMEOUT_MS,
58
75
  // Copy: the shared default is frozen, but AssetConfig stays a plain string[]
59
76
  acceptedFormats: config.acceptedFormats ?? [...DEFAULT_ACCEPTED_FORMATS],
60
77
  contentRoot: config.contentRoot,
@@ -365,21 +382,23 @@ export class AssetOperations {
365
382
 
366
383
  const relativePath = folder === '/' ? filename : `${folder.slice(1)}/${filename}`;
367
384
 
368
- // Delete file from disk (ignore if already gone)
369
- try {
370
- await unlink(assetPath);
371
- } catch {
372
- // File may already be gone, continue with metadata cleanup
373
- }
374
-
375
- await assetMetadata.remove(this.config, relativePath);
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
+ });
376
395
  return { success: true };
377
396
  }
378
397
 
379
398
  /**
380
399
  * Import an image from a URL (server-side fetch, no CORS issues)
381
- * Validates the URL and every redirect hop against SSRF, enforces 30s timeout,
382
- * and checks response size.
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.
383
402
  */
384
403
  async importFromUrl(
385
404
  url: string,
@@ -392,76 +411,114 @@ export class AssetOperations {
392
411
  return { success: false, error: err instanceof Error ? err.message : 'Invalid URL' };
393
412
  }
394
413
 
395
- // Fetch with 30-second timeout, following redirects MANUALLY so every hop's
396
- // target runs through the SSRF guard BEFORE it is requested — otherwise a
397
- // public URL can redirect into a loopback or link-local (cloud metadata)
398
- // address that the initial check would have rejected.
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.
399
420
  const controller = new AbortController();
400
- const timeout = setTimeout(() => controller.abort(), 30_000);
401
- let response: Response | undefined;
402
- let current = url;
421
+ const timeout = setTimeout(() => controller.abort(), this.config.importTimeoutMs);
403
422
  try {
404
- for (let hop = 0; hop <= MAX_IMPORT_REDIRECTS; hop += 1) {
405
- const hopResponse = await fetch(current, { signal: controller.signal, redirect: 'manual' });
406
- if (hopResponse.status < 300 || hopResponse.status >= 400) {
407
- response = hopResponse;
408
- break;
409
- }
410
- const location = hopResponse.headers.get('location');
411
- if (location === null) {
412
- return { success: false, error: 'Redirect missing Location header' };
413
- }
414
- try {
415
- // A relative Location is legal and common; resolve it against the URL
416
- // that produced it, then validate the absolute result.
417
- current = validateFetchUrl(new URL(location, current).toString()).toString();
418
- } catch (err) {
419
- return { success: false, error: `Redirect blocked: ${err instanceof Error ? err.message : 'Invalid URL'}` };
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
+ }
420
445
  }
446
+ } catch {
447
+ return { success: false, error: controller.signal.aborted ? 'URL import timed out' : 'Failed to fetch URL' };
421
448
  }
422
- } catch {
423
- return { success: false, error: 'Failed to fetch URL' };
424
- } finally {
425
- clearTimeout(timeout);
426
- }
427
-
428
- // Budget exhausted without a final response — fail closed rather than
429
- // treating the last redirect as content
430
- if (!response) {
431
- return { success: false, error: 'Too many redirects' };
432
- }
433
449
 
434
- if (!response.ok) {
435
- return { success: false, error: `Fetch failed with status ${response.status}` };
436
- }
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
+ }
437
455
 
438
- // Early size check from Content-Length header
439
- const contentLength = response.headers.get('content-length');
440
- if (contentLength && Number.parseInt(contentLength, 10) > this.config.maxFileSize) {
441
456
  const maxMB = Math.round(this.config.maxFileSize / (1024 * 1024));
442
- return { success: false, error: `Remote file too large. Maximum: ${maxMB}MB` };
443
- }
457
+ const tooLarge = { success: false as const, error: `Remote file too large. Maximum: ${maxMB}MB` };
444
458
 
445
- const contentType = response.headers.get('content-type') || '';
446
- const lastSegment = new URL(url).pathname.split('/').pop() || 'imported-image.jpg';
447
- let urlFilename = lastSegment;
448
- try {
449
- const decoded = decodeURIComponent(lastSegment);
450
- if (!/\p{Cc}/u.test(decoded)) urlFilename = decoded.split(/[/\\]/).pop() || lastSegment;
451
- } catch {
452
- // A malformed escape keeps the filename as written in the address.
453
- }
459
+ if (!response.ok) {
460
+ await response.body?.cancel().catch(() => {});
461
+ return { success: false, error: `Fetch failed with status ${response.status}` };
462
+ }
454
463
 
455
- // Read response body and verify actual size
456
- const arrayBuffer = await response.arrayBuffer();
457
- if (arrayBuffer.byteLength > this.config.maxFileSize) {
458
- const maxMB = Math.round(this.config.maxFileSize / (1024 * 1024));
459
- return { success: false, error: `Remote file too large. Maximum: ${maxMB}MB` };
460
- }
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
+ }
461
470
 
462
- const file = new File([new Uint8Array(arrayBuffer)], urlFilename, { type: contentType });
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
+ }
463
480
 
464
- return this.upload(file, metadata);
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
+ }
509
+
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
+ }
465
522
  }
466
523
 
467
524
  /**
@@ -638,7 +695,7 @@ export class AssetOperations {
638
695
  filenames: string[],
639
696
  sourceFolder: string,
640
697
  targetFolder: string,
641
- ): Promise<{ success: true; moved: number } | { success: false; error: string }> {
698
+ ): Promise<{ success: true; moved: number } | { success: false; error: string; moved?: number }> {
642
699
  // Normalize folder paths
643
700
  const normalizedSource = sourceFolder === '/' ? '/' : `/${sourceFolder.replace(/^\/+|\/+$/g, '')}`;
644
701
  const normalizedTarget = targetFolder === '/' ? '/' : `/${targetFolder.replace(/^\/+|\/+$/g, '')}`;
@@ -704,6 +761,7 @@ export class AssetOperations {
704
761
  // Move each file with its own record, so one failure cannot take the rest
705
762
  // of the folder's metadata with it
706
763
  let moved = 0;
764
+ const failed: string[] = [];
707
765
  for (const filename of filenames) {
708
766
  const oldRelativePath = normalizedSource === '/' ? filename : `${normalizedSource.slice(1)}/${filename}`;
709
767
  const newRelativePath = normalizedTarget === '/' ? filename : `${normalizedTarget.slice(1)}/${filename}`;
@@ -717,22 +775,23 @@ export class AssetOperations {
717
775
  to = this.getAssetPath(filename, normalizedTarget);
718
776
  } catch {
719
777
  console.error(`[AssetOperations] Refusing to move ${filename}: it points outside the media library`);
778
+ failed.push(`${filename} (outside the media library)`);
720
779
  continue;
721
780
  }
722
781
 
723
- try {
724
- // oxlint-disable-next-line no-await-in-loop -- each move is committed before its metadata follows; partial failure stays attributable to one filename.
725
- await rename(from, to);
726
- } catch (err) {
727
- console.error(`[AssetOperations] Failed to move ${filename}:`, err);
728
- continue;
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})`);
729
789
  }
730
-
731
- // oxlint-disable-next-line no-await-in-loop -- metadata must follow the file that just moved before the next file starts.
732
- await assetMetadata.move(this.config, oldRelativePath, newRelativePath);
733
- moved += 1;
734
790
  }
735
791
 
792
+ if (failed.length > 0) {
793
+ return { success: false, moved, error: `Could not move: ${failed.join(', ')}` };
794
+ }
736
795
  return { success: true, moved };
737
796
  }
738
797
 
@@ -812,3 +871,117 @@ export class AssetOperations {
812
871
  ];
813
872
  }
814
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/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 env vars are not set (local dev), validation is skipped.
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
- const CF_ACCESS_TEAM_NAME = process.env.CF_ACCESS_TEAM_NAME;
12
- const CF_ACCESS_AUD = process.env.CF_ACCESS_AUD;
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
- // JWKS with built-in caching (handles key rotation automatically)
15
- const JWKS = CF_ACCESS_TEAM_NAME
16
- ? createRemoteJWKSet(new URL(`https://${CF_ACCESS_TEAM_NAME}.cloudflareaccess.com/cdn-cgi/access/certs`))
17
- : null;
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 vars not set (local dev mode).
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
- // If CF Access not configured, skip validation (local dev)
55
- if (!CF_ACCESS_TEAM_NAME || !CF_ACCESS_AUD || !JWKS) {
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, JWKS, {
66
- issuer: `https://${CF_ACCESS_TEAM_NAME}.cloudflareaccess.com`,
67
- audience: CF_ACCESS_AUD,
81
+ const { payload } = await jwtVerify(token, jwksFor(team), {
82
+ issuer: `https://${team}.cloudflareaccess.com`,
83
+ audience,
68
84
  });
69
85
 
70
86
  return {
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The entry id a complete content file declares, for callers that hold a
3
+ * repository path rather than a content-layout one (a file a commit removed)
4
+ * and must name the entry the index knew it by.
5
+ *
6
+ * Its own subpath, apart from `./indexing`: that chunk evaluates WASM-backed
7
+ * hashing at import time, which a runtime that forbids compiling WASM from
8
+ * bytes refuses. This module imports only the frontmatter parser.
9
+ */
10
+ import matter from 'gray-matter';
11
+
12
+ const textDecoder = new TextDecoder();
13
+
14
+ /**
15
+ * The id `parseContentHeader` would index the file under, read the same way:
16
+ * YAML frontmatter through gray-matter (fresh options, so no memo cache) for
17
+ * `.mdx`, the top-level `id` of the JSON document for `.json` and `.vxjson`
18
+ * (canonicalizing a complete VXJSON file keeps that field as it is). Null for
19
+ * a non-content file, an unparseable one, or one that declares no id.
20
+ */
21
+ export function contentFileId(path: string, bytes: Uint8Array): string | null {
22
+ const text = textDecoder.decode(bytes);
23
+ let id: unknown;
24
+ try {
25
+ if (path.endsWith('.mdx')) id = matter(text, {}).data.id;
26
+ else if (path.endsWith('.json') || path.endsWith('.vxjson')) id = (JSON.parse(text) as { id?: unknown } | null)?.id;
27
+ } catch {
28
+ return null;
29
+ }
30
+ return typeof id === 'string' && id !== '' ? id : null;
31
+ }
@@ -193,12 +193,18 @@ export function getMetadataSize(meta: ContentMeta): number {
193
193
  * - Must start with /
194
194
  * - Cannot contain spaces (should be URL-encoded)
195
195
  * - Cannot contain special characters that would break URLs
196
+ * - Cannot be under the reserved `/_conloca/` prefix
196
197
  */
197
198
  export function isValidPathname(pathname: string): boolean {
198
199
  if (!pathname?.startsWith('/')) return false;
199
200
  if (pathname.includes(' ')) return false;
200
201
  if (pathname.includes('?') || pathname.includes('#')) return false;
201
- return true;
202
+ return !isReservedPathname(pathname);
203
+ }
204
+
205
+ /** True for `/_conloca` and everything under it: the editor page a site build writes there owns those paths. */
206
+ export function isReservedPathname(pathname: string): boolean {
207
+ return pathname === '/_conloca' || pathname.startsWith('/_conloca/');
202
208
  }
203
209
 
204
210
  /**
@@ -241,7 +247,8 @@ export type PathnameValidationReason =
241
247
  | 'non_ascii'
242
248
  | 'traversal_segment'
243
249
  | 'index_segment'
244
- | 'disallowed_char';
250
+ | 'disallowed_char'
251
+ | 'reserved_prefix';
245
252
 
246
253
  export interface PathnameValidationResult {
247
254
  /** When valid: the normalized pathname. When invalid: the raw (trimmed) input. */
@@ -302,6 +309,15 @@ export function normalizeAndValidatePathname(input: string | undefined | null):
302
309
  value = value.replace(/\/+/g, '/');
303
310
  if (value !== '/' && value.endsWith('/')) value = value.slice(0, -1);
304
311
 
312
+ if (isReservedPathname(value)) {
313
+ return {
314
+ value,
315
+ valid: false,
316
+ reason: 'reserved_prefix',
317
+ message: 'Paths under `/_conloca/` are reserved for the editor page',
318
+ };
319
+ }
320
+
305
321
  // Segment-level check: `.` and `..` are never valid path segments.
306
322
  // Run before the generic disallowed-char check so the user gets the
307
323
  // more specific "traversal" message.