@conloca/content-api 0.2.2 → 0.2.4
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/.build-inputs.json +82 -0
- package/dist/address-site.d.ts +6 -0
- package/dist/address-site.d.ts.map +1 -0
- package/dist/address-site.js +15 -0
- package/dist/address-site.js.map +1 -0
- package/dist/asset-constraints.d.ts +9 -1
- package/dist/asset-constraints.d.ts.map +1 -1
- package/dist/asset-constraints.js +10 -2
- package/dist/asset-constraints.js.map +1 -1
- package/dist/asset-metadata-record.d.ts +18 -0
- package/dist/asset-metadata-record.d.ts.map +1 -0
- package/dist/asset-metadata-record.js +59 -0
- package/dist/asset-metadata-record.js.map +1 -0
- package/dist/asset-metadata-store.d.ts.map +1 -1
- package/dist/asset-metadata-store.js +7 -26
- package/dist/asset-metadata-store.js.map +1 -1
- package/dist/asset-naming.d.ts +39 -0
- package/dist/asset-naming.d.ts.map +1 -0
- package/dist/asset-naming.js +123 -0
- package/dist/asset-naming.js.map +1 -0
- package/dist/asset-operations.d.ts +15 -2
- package/dist/asset-operations.d.ts.map +1 -1
- package/dist/asset-operations.js +99 -90
- package/dist/asset-operations.js.map +1 -1
- package/dist/asset-types.d.ts +2 -0
- package/dist/asset-types.d.ts.map +1 -1
- package/dist/asset-usage.d.ts +8 -1
- package/dist/asset-usage.d.ts.map +1 -1
- package/dist/asset-usage.js +4 -1
- package/dist/asset-usage.js.map +1 -1
- package/dist/component-registry.d.ts +3 -0
- package/dist/component-registry.d.ts.map +1 -1
- package/dist/content-utils.d.ts +4 -1
- package/dist/content-utils.d.ts.map +1 -1
- package/dist/content-utils.js +14 -1
- package/dist/content-utils.js.map +1 -1
- package/dist/draft-media-ref.d.ts +9 -0
- package/dist/draft-media-ref.d.ts.map +1 -0
- package/dist/draft-media-ref.js +47 -0
- package/dist/draft-media-ref.js.map +1 -0
- package/dist/editor-host.d.ts +174 -0
- package/dist/editor-host.d.ts.map +1 -0
- package/dist/editor-host.js +304 -0
- package/dist/editor-host.js.map +1 -0
- package/dist/filesystem-content-api.d.ts +15 -0
- package/dist/filesystem-content-api.d.ts.map +1 -1
- package/dist/filesystem-content-api.js +3 -2
- package/dist/filesystem-content-api.js.map +1 -1
- package/dist/git-operations.d.ts +0 -5
- package/dist/git-operations.d.ts.map +1 -1
- package/dist/git-operations.js +1 -33
- package/dist/git-operations.js.map +1 -1
- package/dist/image-format.d.ts +9 -0
- package/dist/image-format.d.ts.map +1 -0
- package/dist/image-format.js +100 -0
- package/dist/image-format.js.map +1 -0
- package/dist/image-metadata.d.ts +11 -0
- package/dist/image-metadata.d.ts.map +1 -0
- package/dist/image-metadata.js +283 -0
- package/dist/image-metadata.js.map +1 -0
- package/dist/image-shrink.d.ts +15 -0
- package/dist/image-shrink.d.ts.map +1 -0
- package/dist/image-shrink.js +52 -0
- package/dist/image-shrink.js.map +1 -0
- package/dist/index.d.ts +8 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +16 -3
- package/dist/index.js.map +1 -1
- package/dist/lfs-attributes.d.ts +26 -0
- package/dist/lfs-attributes.d.ts.map +1 -0
- package/dist/lfs-attributes.js +285 -0
- package/dist/lfs-attributes.js.map +1 -0
- package/dist/site.d.ts.map +1 -1
- package/dist/site.js +3 -1
- package/dist/site.js.map +1 -1
- package/dist/skill-stamp.d.ts +10 -0
- package/dist/skill-stamp.d.ts.map +1 -0
- package/dist/skill-stamp.js +42 -0
- package/dist/skill-stamp.js.map +1 -0
- package/dist/svg-sanitize.d.ts +8 -0
- package/dist/svg-sanitize.d.ts.map +1 -0
- package/dist/svg-sanitize.js +260 -0
- package/dist/svg-sanitize.js.map +1 -0
- package/dist/types.d.ts +9 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/upload-bytes.d.ts +17 -0
- package/dist/upload-bytes.d.ts.map +1 -0
- package/dist/upload-bytes.js +43 -0
- package/dist/upload-bytes.js.map +1 -0
- package/dist/upload-refusals.d.ts +24 -0
- package/dist/upload-refusals.d.ts.map +1 -0
- package/dist/upload-refusals.js +49 -0
- package/dist/upload-refusals.js.map +1 -0
- package/package.json +49 -6
- package/src/address-site.ts +19 -0
- package/src/asset-constraints.ts +14 -2
- package/src/asset-metadata-record.ts +57 -0
- package/src/asset-metadata-store.ts +12 -21
- package/src/asset-naming.ts +120 -0
- package/src/asset-operations.ts +108 -91
- package/src/asset-types.ts +2 -0
- package/src/asset-usage.ts +16 -2
- package/src/content-utils.ts +18 -2
- package/src/draft-media-ref.ts +46 -0
- package/src/editor-host.ts +384 -0
- package/src/filesystem-content-api.ts +3 -2
- package/src/git-operations.ts +1 -38
- package/src/image-format.ts +87 -0
- package/src/image-metadata.ts +266 -0
- package/src/image-shrink.ts +57 -0
- package/src/index.ts +47 -3
- package/src/lfs-attributes.ts +291 -0
- package/src/site.ts +3 -1
- package/src/skill-stamp.ts +45 -0
- package/src/svg-sanitize.ts +260 -0
- package/src/types.ts +9 -0
- package/src/upload-bytes.ts +46 -0
- package/src/upload-refusals.ts +59 -0
package/src/content-utils.ts
CHANGED
|
@@ -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
|
|
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.
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where the editor links an image uploaded on a branch but not yet published: a path no site serves, so it is never
|
|
3
|
+
* mistaken for one of the site's own images.
|
|
4
|
+
*/
|
|
5
|
+
import { IMAGE_EXTENSION_MIME } from './asset-constraints.js';
|
|
6
|
+
|
|
7
|
+
/** The path every draft address starts with. */
|
|
8
|
+
export const DRAFT_MEDIA_REF_BASE = '/api/v1/assets/serve';
|
|
9
|
+
|
|
10
|
+
/** The draft address of a path inside the media library, written raw, never URL-encoded. */
|
|
11
|
+
export function draftMediaRef(path: string): string {
|
|
12
|
+
return `${DRAFT_MEDIA_REF_BASE}/${path}`;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** The raw media path of a link that is exactly `${base}/<path>`, or `undefined` when it is not a safe image path. */
|
|
16
|
+
export function mediaRefPath(value: string, base: string): string | undefined {
|
|
17
|
+
if (!value.startsWith(`${base}/`)) return undefined;
|
|
18
|
+
const path = value.slice(base.length + 1);
|
|
19
|
+
if (/[\\?#]/.test(path)) return undefined;
|
|
20
|
+
const segments = path.split('/');
|
|
21
|
+
for (const part of segments) {
|
|
22
|
+
if (part === '' || part === '.' || part === '..' || hasControlChar(part)) {
|
|
23
|
+
return undefined;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
const filename = segments[segments.length - 1] ?? '';
|
|
27
|
+
const dot = filename.lastIndexOf('.');
|
|
28
|
+
if (dot <= 0) return undefined;
|
|
29
|
+
const extension = filename.slice(dot + 1).toLowerCase();
|
|
30
|
+
if (!Object.prototype.hasOwnProperty.call(IMAGE_EXTENSION_MIME, extension)) return undefined;
|
|
31
|
+
return path;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Whether `text` holds an ASCII control character (U+0000–U+001F or U+007F). */
|
|
35
|
+
function hasControlChar(text: string): boolean {
|
|
36
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
37
|
+
const code = text.charCodeAt(index);
|
|
38
|
+
if (code < 32 || code === 127) return true;
|
|
39
|
+
}
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The raw media path of a draft address, or `undefined` when the value is not one. */
|
|
44
|
+
export function draftMediaRefPath(value: string): string | undefined {
|
|
45
|
+
return mediaRefPath(value, DRAFT_MEDIA_REF_BASE);
|
|
46
|
+
}
|
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
import { folderPathError } from './asset-naming.js';
|
|
2
|
+
import { isRecord } from './component-vocabulary.js';
|
|
3
|
+
|
|
4
|
+
/** The wire protocol an editor page built by this release speaks; the editor UI path is /host/v<this>/. */
|
|
5
|
+
export const EDITOR_HOST_PROTOCOL = 1;
|
|
6
|
+
/** Protocols the current editor UI accepts. */
|
|
7
|
+
export const EDITOR_HOST_PROTOCOLS = { min: 1, max: 1 } as const;
|
|
8
|
+
/**
|
|
9
|
+
* The draft-preview protocol a preview server built by this release speaks. Protocol 1 keeps the pass out of the
|
|
10
|
+
* page; protocol 2 opens a preview with a single-use code the server trades for the pass, so no pass travels in a
|
|
11
|
+
* link. conloca.json `preview.protocol` and the exit route's `conloca-preview-protocol` header carry it.
|
|
12
|
+
*/
|
|
13
|
+
export const PREVIEW_PROTOCOL = 2;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* How a build serves draft previews: `d2` from the site's own server deploy, `d3` from a dispatcher in front of a
|
|
17
|
+
* static site under `<base>_conloca/preview/<branch slug>/`, `d4` from a separate preview deploy, `off` not at all.
|
|
18
|
+
*/
|
|
19
|
+
export type PreviewMode = 'd2' | 'd3' | 'd4' | 'off';
|
|
20
|
+
|
|
21
|
+
const PREVIEW_MODES: readonly PreviewMode[] = ['d2', 'd3', 'd4', 'off'];
|
|
22
|
+
|
|
23
|
+
function isPreviewMode(value: unknown): value is PreviewMode {
|
|
24
|
+
return PREVIEW_MODES.some((mode) => mode === value);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** conloca.json `preview`: the build's preview mode and the preview protocol it speaks. */
|
|
28
|
+
export interface PreviewSignal {
|
|
29
|
+
mode: PreviewMode;
|
|
30
|
+
protocol: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** A branch name as one path segment and cookie-name suffix: its UTF-8 bytes as unpadded base64url, one slug per name. */
|
|
34
|
+
export function previewBranchSlug(branch: string): string {
|
|
35
|
+
let binary = '';
|
|
36
|
+
for (const byte of new TextEncoder().encode(branch)) binary += String.fromCharCode(byte);
|
|
37
|
+
return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/u, '');
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** The branch a slug names, or null unless it is the slug of a valid branch name (at most 765 UTF-8 bytes, 1020 characters; 1360 bounds it with room). */
|
|
41
|
+
export function branchOfPreviewSlug(slug: string): string | null {
|
|
42
|
+
if (!/^[A-Za-z0-9_-]{1,1360}$/u.test(slug)) return null;
|
|
43
|
+
let bytes: Uint8Array;
|
|
44
|
+
try {
|
|
45
|
+
bytes = Uint8Array.from(atob(slug.replaceAll('-', '+').replaceAll('_', '/')), (char) => char.charCodeAt(0));
|
|
46
|
+
} catch {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
let branch: string;
|
|
50
|
+
try {
|
|
51
|
+
branch = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
|
52
|
+
} catch {
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
return isValidBranchName(branch) && previewBranchSlug(branch) === slug ? branch : null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Whether a branch's slug leaves room in a 1024-byte cookie `Path` (`<base>_conloca/preview/<slug>`). */
|
|
59
|
+
export function previewSlugFits(branch: string): boolean {
|
|
60
|
+
return previewBranchSlug(branch).length <= 900;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** conloca.json `preview`; `undefined` when absent or malformed, so a bad optional field never makes the page invalid. */
|
|
64
|
+
export function previewSignalOf(info: ConlocaJson): PreviewSignal | undefined {
|
|
65
|
+
const value: unknown = Reflect.get(info, 'preview');
|
|
66
|
+
if (!isRecord(value)) return undefined;
|
|
67
|
+
const { mode, protocol } = value;
|
|
68
|
+
return isPreviewMode(mode) && typeof protocol === 'number' && Number.isSafeInteger(protocol)
|
|
69
|
+
? { mode, protocol }
|
|
70
|
+
: undefined;
|
|
71
|
+
}
|
|
72
|
+
export const DEFAULT_EDITOR_ENDPOINT = 'https://app.conloca.com';
|
|
73
|
+
/** Where the editor page is served, below the site's base. */
|
|
74
|
+
export const EDITOR_PAGE_PATH = '/_conloca/editor/';
|
|
75
|
+
/** The deployable-site id grammar (moved here from cloud-astro's site-id.ts; the census imports it too). */
|
|
76
|
+
export const SITE_ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
|
77
|
+
|
|
78
|
+
/** The parsed http(s) URL when its host is `app.` plus at least two non-empty labels, else null. */
|
|
79
|
+
function appUrl(url: string): URL | null {
|
|
80
|
+
let parsed: URL;
|
|
81
|
+
try {
|
|
82
|
+
parsed = new URL(url);
|
|
83
|
+
} catch {
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;
|
|
87
|
+
const labels = parsed.hostname.split('.');
|
|
88
|
+
return labels.length >= 3 && labels[0] === 'app' && labels.every((label) => label !== '') ? parsed : null;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The editor UI origin for an endpoint, or null unless its host is `app.` plus at least two labels. */
|
|
92
|
+
export function editorUiOrigin(endpoint: string | undefined): string | null {
|
|
93
|
+
return appUrl(endpoint ?? DEFAULT_EDITOR_ENDPOINT)?.origin ?? null;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** The parent root for a URL on the editor UI origin (`app.conloca.com` → `conloca.com`), or null under the same rule. */
|
|
97
|
+
export function parentRoot(url: string): string | null {
|
|
98
|
+
return appUrl(url)?.hostname.slice('app.'.length) ?? null;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Editor UI file per bare specifier the page's bundle keeps external, under `<origin>/host/v<protocol>/`. */
|
|
102
|
+
export const EDITOR_UI_MODULE_FILES = {
|
|
103
|
+
react: 'react.js',
|
|
104
|
+
'react-dom': 'react-dom.js',
|
|
105
|
+
'react-dom/client': 'react-dom-client.js',
|
|
106
|
+
'react/jsx-runtime': 'jsx-runtime.js',
|
|
107
|
+
'react/jsx-dev-runtime': 'jsx-dev-runtime.js',
|
|
108
|
+
'@puckeditor/core': 'puck.js',
|
|
109
|
+
} as const;
|
|
110
|
+
|
|
111
|
+
export type EditorHostStatus =
|
|
112
|
+
| 'ready'
|
|
113
|
+
| 'no-address'
|
|
114
|
+
| 'blocked-address'
|
|
115
|
+
| 'unreachable'
|
|
116
|
+
| 'protected'
|
|
117
|
+
| 'not-found'
|
|
118
|
+
| 'invalid'
|
|
119
|
+
| 'wrong-repo'
|
|
120
|
+
| 'wrong-site'
|
|
121
|
+
| 'unsupported-protocol'
|
|
122
|
+
| 'frame-blocked';
|
|
123
|
+
|
|
124
|
+
export type EditorFrameFailure = 'handshake-timeout' | 'origin-rejected' | 'unsupported-protocol' | 'site-load-failed';
|
|
125
|
+
|
|
126
|
+
/** The page's inline JSON block, `<script type="application/json" id="conloca-editor-host">`. URLs are base-absolute. */
|
|
127
|
+
export interface EditorHostPageData {
|
|
128
|
+
protocol: number;
|
|
129
|
+
repo: string | null;
|
|
130
|
+
siteId: string;
|
|
131
|
+
site: string;
|
|
132
|
+
css: string[];
|
|
133
|
+
editorCss: string | null;
|
|
134
|
+
sandboxFrame: string;
|
|
135
|
+
info: string;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** conloca.json: public facts about one deploy of the editor page. Grants nothing. */
|
|
139
|
+
export interface EditorPageInfo {
|
|
140
|
+
protocol: number;
|
|
141
|
+
repo: string | null;
|
|
142
|
+
siteId: string;
|
|
143
|
+
commit: string | null;
|
|
144
|
+
branch: string | null;
|
|
145
|
+
builtWith: string;
|
|
146
|
+
/** `path` is relative to the editor folder. */
|
|
147
|
+
componentManifest: { path: string; sha256: string } | null;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** The file beside conloca.json holding each `dataSchemas` collection's JSON schema, as `{ collections }`. */
|
|
151
|
+
export const DATA_SCHEMAS_FILE = 'data-schemas.json';
|
|
152
|
+
|
|
153
|
+
export const EDITOR_PAGE_INFO_FORMATS = {
|
|
154
|
+
commit: /^[0-9a-f]{40}$/,
|
|
155
|
+
builtWith: /^@conloca\/cloud-astro@\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/,
|
|
156
|
+
repo: /^[A-Za-z0-9-]{1,39}\/[A-Za-z0-9._-]{1,100}$/,
|
|
157
|
+
siteId: SITE_ID_RE,
|
|
158
|
+
sha256: /^[0-9a-f]{64}$/,
|
|
159
|
+
manifestPath: /^component-manifest\.[0-9a-f]{16}\.json$/,
|
|
160
|
+
} as const;
|
|
161
|
+
|
|
162
|
+
/** Where the host serves a build of every other branch, recorded by the production build. */
|
|
163
|
+
export type BranchDeploys = { host: 'cloudflare-pages'; project: string };
|
|
164
|
+
|
|
165
|
+
// One DNS label: the Pages project names the first label of its `pages.dev` address.
|
|
166
|
+
const PAGES_PROJECT_RE = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
167
|
+
|
|
168
|
+
/** A parsed conloca.json object, whether or not it passed `isEditorPageInfo`, as the optional-field readers take it. */
|
|
169
|
+
export type ConlocaJson =
|
|
170
|
+
| EditorPageInfo
|
|
171
|
+
| { branchDeploys?: unknown; contentPaths?: unknown; preview?: unknown; routes?: unknown; media?: unknown };
|
|
172
|
+
|
|
173
|
+
/** conloca.json `branchDeploys`; `undefined` when absent or malformed, so a bad optional field never makes the page invalid. */
|
|
174
|
+
export function branchDeploysOf(info: ConlocaJson): BranchDeploys | undefined {
|
|
175
|
+
const value: unknown = Reflect.get(info, 'branchDeploys');
|
|
176
|
+
if (!isRecord(value) || value.host !== 'cloudflare-pages') return undefined;
|
|
177
|
+
const { project } = value;
|
|
178
|
+
return typeof project === 'string' && PAGES_PROJECT_RE.test(project)
|
|
179
|
+
? { host: 'cloudflare-pages', project }
|
|
180
|
+
: undefined;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export const CONTENT_PATHS_MAX = 16;
|
|
184
|
+
|
|
185
|
+
/** '' (the repository root) or a relative path of plain segments, at most 255 characters. */
|
|
186
|
+
function isContentPath(path: unknown): path is string {
|
|
187
|
+
if (path === '') return true;
|
|
188
|
+
if (typeof path !== 'string' || path.length > 255 || path.includes('\\')) return false;
|
|
189
|
+
return path.split('/').every((segment) => segment !== '' && segment !== '.' && segment !== '..');
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* conloca.json `contentPaths`: repository paths the site's content lives under, duplicates removed;
|
|
194
|
+
* `undefined` when absent or malformed, so a bad optional field never makes the page invalid.
|
|
195
|
+
*/
|
|
196
|
+
export function contentPathsOf(info: ConlocaJson): string[] | undefined {
|
|
197
|
+
const value: unknown = Reflect.get(info, 'contentPaths');
|
|
198
|
+
if (!Array.isArray(value) || value.length === 0 || value.length > CONTENT_PATHS_MAX) return undefined;
|
|
199
|
+
if (!value.every(isContentPath)) return undefined;
|
|
200
|
+
return [...new Set<string>(value)];
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** The most bytes of conloca.json the workspace editor reads; a build never writes more. */
|
|
204
|
+
export const CONLOCA_JSON_MAX_BYTES = 16 * 1024;
|
|
205
|
+
|
|
206
|
+
/** A page route: `/` then at most 200 unreserved URL characters or `/`, so no route carries prompt or shell syntax. */
|
|
207
|
+
export const EDITOR_ROUTE_RE = /^\/[A-Za-z0-9._~\-/]{0,200}$/;
|
|
208
|
+
/** The most routes a conloca.json lists. */
|
|
209
|
+
export const ROUTES_MAX = 500;
|
|
210
|
+
|
|
211
|
+
/** Whether `route` is a string matching `EDITOR_ROUTE_RE`. */
|
|
212
|
+
export function isEditorRoute(route: unknown): route is string {
|
|
213
|
+
return typeof route === 'string' && EDITOR_ROUTE_RE.test(route);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* conloca.json `routes`: the page routes a build lists, those outside `EDITOR_ROUTE_RE` and duplicates dropped,
|
|
218
|
+
* at most `ROUTES_MAX`; `undefined` when absent or not a list, so a bad optional field never makes the page invalid.
|
|
219
|
+
*/
|
|
220
|
+
export function routesOf(info: ConlocaJson): string[] | undefined {
|
|
221
|
+
const value: unknown = Reflect.get(info, 'routes');
|
|
222
|
+
if (!Array.isArray(value)) return undefined;
|
|
223
|
+
return [...new Set(value.filter(isEditorRoute))].slice(0, ROUTES_MAX);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** conloca.json `media`: the repository folder uploaded images go to and the URL the site serves it at. */
|
|
227
|
+
export interface EditorMedia {
|
|
228
|
+
path: string;
|
|
229
|
+
refBase: string;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** A link base: `''`, or `/`-led segments of URL-safe characters with no `.` or `..` segment and no trailing `/`. */
|
|
233
|
+
const REF_BASE_RE = /^(\/(?!\.\.?(?:\/|$))[A-Za-z0-9._~-]+)*$/;
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* conloca.json `media`; `undefined` when absent or malformed (the repository root, a folder `folderPathError`
|
|
237
|
+
* refuses, or a link base {@link REF_BASE_RE} refuses), so a bad optional field never makes the page invalid. The
|
|
238
|
+
* link base is written into saved pages, so it may hold nothing a page's JSON, front matter or MDX would read.
|
|
239
|
+
*/
|
|
240
|
+
export function mediaOf(info: ConlocaJson): EditorMedia | undefined {
|
|
241
|
+
const value: unknown = Reflect.get(info, 'media');
|
|
242
|
+
if (!isRecord(value)) return undefined;
|
|
243
|
+
const { path, refBase } = value;
|
|
244
|
+
if (typeof path !== 'string' || path === '' || path.length > 255 || folderPathError(path) !== null) return undefined;
|
|
245
|
+
if (typeof refBase !== 'string' || refBase.length > 255 || !REF_BASE_RE.test(refBase)) return undefined;
|
|
246
|
+
return { path, refBase };
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// `~^:?*[\`, `..`, `@{` and `//` anywhere (`git check-ref-format`); space and control characters are checked apart.
|
|
250
|
+
const BRANCH_FORBIDDEN_RE = /[~^:?*[\\]|\.\.|@\{|\/\//;
|
|
251
|
+
|
|
252
|
+
/** Git's ref-name rules for one branch name, at most 255 characters. */
|
|
253
|
+
export function isValidBranchName(name: string): boolean {
|
|
254
|
+
if (name === '' || name.length > 255 || name === '@' || BRANCH_FORBIDDEN_RE.test(name)) return false;
|
|
255
|
+
for (let index = 0; index < name.length; index++) {
|
|
256
|
+
const code = name.charCodeAt(index);
|
|
257
|
+
if (code <= 0x20 || code === 0x7f) return false;
|
|
258
|
+
}
|
|
259
|
+
if (name.startsWith('-') || name.startsWith('/') || name.endsWith('/') || name.endsWith('.')) return false;
|
|
260
|
+
return name.split('/').every((segment) => !segment.startsWith('.') && !segment.endsWith('.lock'));
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** Shape and field formats of a parsed conloca.json; null allowed where the type allows it. */
|
|
264
|
+
export function isEditorPageInfo(value: unknown): value is EditorPageInfo {
|
|
265
|
+
if (!isRecord(value)) return false;
|
|
266
|
+
const { protocol, repo, siteId, commit, branch, builtWith, componentManifest } = value;
|
|
267
|
+
const formats = EDITOR_PAGE_INFO_FORMATS;
|
|
268
|
+
return (
|
|
269
|
+
typeof protocol === 'number' &&
|
|
270
|
+
Number.isSafeInteger(protocol) &&
|
|
271
|
+
(repo === null || (typeof repo === 'string' && formats.repo.test(repo))) &&
|
|
272
|
+
typeof siteId === 'string' &&
|
|
273
|
+
formats.siteId.test(siteId) &&
|
|
274
|
+
(commit === null || (typeof commit === 'string' && formats.commit.test(commit))) &&
|
|
275
|
+
(branch === null || (typeof branch === 'string' && isValidBranchName(branch))) &&
|
|
276
|
+
typeof builtWith === 'string' &&
|
|
277
|
+
formats.builtWith.test(builtWith) &&
|
|
278
|
+
(componentManifest === null ||
|
|
279
|
+
(isRecord(componentManifest) &&
|
|
280
|
+
typeof componentManifest.path === 'string' &&
|
|
281
|
+
formats.manifestPath.test(componentManifest.path) &&
|
|
282
|
+
typeof componentManifest.sha256 === 'string' &&
|
|
283
|
+
formats.sha256.test(componentManifest.sha256)))
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** True when `location` is an absolute URL on vercel.com or a subdomain (Vercel's sign-in redirect). */
|
|
288
|
+
export function isVercelSignIn(location: string | null): boolean {
|
|
289
|
+
if (location === null) return false;
|
|
290
|
+
let host: string;
|
|
291
|
+
try {
|
|
292
|
+
host = new URL(location).hostname;
|
|
293
|
+
} catch {
|
|
294
|
+
return false;
|
|
295
|
+
}
|
|
296
|
+
return host === 'vercel.com' || host.endsWith('.vercel.com');
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** Any Vercel signal on an answer: an `x-vercel-*` header or a sign-in redirect. Feeds the classifier's `vercel`. */
|
|
300
|
+
export function isFromVercel(headers: Headers): boolean {
|
|
301
|
+
for (const [name] of headers) if (name.startsWith('x-vercel-')) return true;
|
|
302
|
+
return isVercelSignIn(headers.get('location'));
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** What one conloca.json answer means; `info` is the parsed file once it passed the format checks. */
|
|
306
|
+
export interface EditorHostVerdict {
|
|
307
|
+
status: EditorHostStatus;
|
|
308
|
+
reason?: 'repo-missing';
|
|
309
|
+
info?: EditorPageInfo;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* One conloca.json answer → status; body is null when not read (non-200 or over the cap).
|
|
314
|
+
* `vercel` (any Vercel signal) only picks the caller's message: an ordinary redirect on Vercel stays `invalid`.
|
|
315
|
+
*/
|
|
316
|
+
export function classifyEditorHostResponse(
|
|
317
|
+
response: {
|
|
318
|
+
status: number;
|
|
319
|
+
contentType: string | null;
|
|
320
|
+
location: string | null;
|
|
321
|
+
vercel: boolean;
|
|
322
|
+
body: string | null;
|
|
323
|
+
},
|
|
324
|
+
expected: { repoUri: string; siteId: string; protocols: { min: number; max: number } },
|
|
325
|
+
): EditorHostVerdict {
|
|
326
|
+
const { status, contentType, body } = response;
|
|
327
|
+
if (status >= 500 || status === 429) return { status: 'unreachable' };
|
|
328
|
+
if (status === 401 || status === 403) return { status: 'protected' };
|
|
329
|
+
if (status === 404) return { status: 'not-found' };
|
|
330
|
+
if (status >= 300 && status < 400) return { status: isVercelSignIn(response.location) ? 'protected' : 'invalid' };
|
|
331
|
+
if (status !== 200) return { status: 'invalid' };
|
|
332
|
+
// A host serving its HTML fallback for unknown paths.
|
|
333
|
+
if (contentType?.split(';')[0]?.trim().toLowerCase() === 'text/html') return { status: 'not-found' };
|
|
334
|
+
if (body === null) return { status: 'invalid' };
|
|
335
|
+
if (body.trimStart().startsWith('<')) return { status: 'not-found' };
|
|
336
|
+
let parsed: unknown;
|
|
337
|
+
try {
|
|
338
|
+
parsed = JSON.parse(body);
|
|
339
|
+
} catch {
|
|
340
|
+
return { status: 'invalid' };
|
|
341
|
+
}
|
|
342
|
+
if (!isEditorPageInfo(parsed)) return { status: 'invalid' };
|
|
343
|
+
const info = parsed;
|
|
344
|
+
if (info.protocol < expected.protocols.min || info.protocol > expected.protocols.max) {
|
|
345
|
+
return { status: 'unsupported-protocol', info };
|
|
346
|
+
}
|
|
347
|
+
if (info.repo === null) return { status: 'wrong-repo', reason: 'repo-missing', info };
|
|
348
|
+
if (info.repo.toLowerCase() !== expected.repoUri.toLowerCase()) return { status: 'wrong-repo', info };
|
|
349
|
+
if (info.siteId !== expected.siteId) return { status: 'wrong-site', info };
|
|
350
|
+
return { status: 'ready', info };
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/** A CSP source expression compared as a token: case-insensitive, without a trailing `/`. */
|
|
354
|
+
function sourceToken(source: string): string {
|
|
355
|
+
return source.toLowerCase().replace(/\/$/, '');
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* Frame headers of the page → whether a workspace parent may frame it. `allowedAncestors` are the source expressions
|
|
360
|
+
* that admit the workspace; `*` and `https:` always do. A `frame-ancestors` directive overrides X-Frame-Options.
|
|
361
|
+
* shortcut: sources match as exact tokens, so a broader host wildcard (`https://*.com`) reads as blocked; parse
|
|
362
|
+
* host patterns if a real site needs one.
|
|
363
|
+
*/
|
|
364
|
+
export function classifyFrameHeaders(
|
|
365
|
+
headers: { xFrameOptions: string | null; csp: string | null },
|
|
366
|
+
allowedAncestors: readonly string[],
|
|
367
|
+
): 'ok' | 'frame-blocked' {
|
|
368
|
+
const admitting = new Set(['*', 'https:', ...allowedAncestors.map(sourceToken)]);
|
|
369
|
+
// A combined header joins policies with commas; every policy is enforced on its own, by its first frame-ancestors.
|
|
370
|
+
const ancestorLists = (headers.csp ?? '').split(',').flatMap((policy) => {
|
|
371
|
+
const directive = policy
|
|
372
|
+
.split(';')
|
|
373
|
+
.map((part) => part.trim().split(/\s+/))
|
|
374
|
+
.find(([name]) => name?.toLowerCase() === 'frame-ancestors');
|
|
375
|
+
return directive ? [directive.slice(1)] : [];
|
|
376
|
+
});
|
|
377
|
+
if (ancestorLists.length > 0) {
|
|
378
|
+
return ancestorLists.every((sources) => sources.some((source) => admitting.has(sourceToken(source))))
|
|
379
|
+
? 'ok'
|
|
380
|
+
: 'frame-blocked';
|
|
381
|
+
}
|
|
382
|
+
const xfo = new Set((headers.xFrameOptions ?? '').split(',').map((value) => value.trim().toLowerCase()));
|
|
383
|
+
return xfo.has('deny') || xfo.has('sameorigin') ? 'frame-blocked' : 'ok';
|
|
384
|
+
}
|
|
@@ -431,8 +431,8 @@ export class FileSystemContentAPI implements ContentAPI {
|
|
|
431
431
|
// site's locales array) both have slots for every option-declared
|
|
432
432
|
// locale. Without this, the parser would correctly identify a file's
|
|
433
433
|
// locale but `addContent` would crash on a missing index bucket.
|
|
434
|
-
// We preserve the resolved site's existing `mdxPages
|
|
435
|
-
// through the rewrite so the locale-override doesn't clobber the
|
|
434
|
+
// We preserve the resolved site's existing `mdxPages`, `domains` and
|
|
435
|
+
// `base` through the rewrite so the locale-override doesn't clobber the
|
|
436
436
|
// per-site content config.
|
|
437
437
|
if (options.availableLocales && options.availableLocales.length > 0) {
|
|
438
438
|
const optionDefaultLocale = options.defaultLocale ?? options.availableLocales[0];
|
|
@@ -445,6 +445,7 @@ export class FileSystemContentAPI implements ContentAPI {
|
|
|
445
445
|
locales: options.availableLocales,
|
|
446
446
|
defaultLocale: optionDefaultLocale,
|
|
447
447
|
...(existingSite?.domains && { domains: existingSite.domains }),
|
|
448
|
+
...(existingSite?.base && { base: existingSite.base }),
|
|
448
449
|
...(existingSite?.mdxPages && { mdxPages: existingSite.mdxPages }),
|
|
449
450
|
},
|
|
450
451
|
},
|
package/src/git-operations.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
|
-
import {
|
|
2
|
+
import { mkdtemp, rm } from 'node:fs/promises';
|
|
3
3
|
import { tmpdir } from 'node:os';
|
|
4
4
|
import { dirname, join, resolve } from 'node:path';
|
|
5
5
|
import { setTimeout as sleep } from 'node:timers/promises';
|
|
@@ -448,40 +448,3 @@ export function createGitOperations(config: GitConfig): GitOperations {
|
|
|
448
448
|
},
|
|
449
449
|
};
|
|
450
450
|
}
|
|
451
|
-
|
|
452
|
-
const LFS_PATTERNS = [
|
|
453
|
-
'*.jpg filter=lfs diff=lfs merge=lfs -text',
|
|
454
|
-
'*.jpeg filter=lfs diff=lfs merge=lfs -text',
|
|
455
|
-
'*.png filter=lfs diff=lfs merge=lfs -text',
|
|
456
|
-
'*.gif filter=lfs diff=lfs merge=lfs -text',
|
|
457
|
-
'*.svg filter=lfs diff=lfs merge=lfs -text',
|
|
458
|
-
'*.webp filter=lfs diff=lfs merge=lfs -text',
|
|
459
|
-
'*.avif filter=lfs diff=lfs merge=lfs -text',
|
|
460
|
-
'*.ico filter=lfs diff=lfs merge=lfs -text',
|
|
461
|
-
];
|
|
462
|
-
|
|
463
|
-
/**
|
|
464
|
-
* Ensure .gitattributes exists at contentRoot with LFS tracking patterns for web image extensions.
|
|
465
|
-
* Creates the file if missing, or appends missing patterns if file exists.
|
|
466
|
-
*/
|
|
467
|
-
export async function setupGitLfsAttributes(contentRoot: string): Promise<void> {
|
|
468
|
-
const gitattributesPath = join(contentRoot, '.gitattributes');
|
|
469
|
-
let existing = '';
|
|
470
|
-
|
|
471
|
-
try {
|
|
472
|
-
await access(gitattributesPath);
|
|
473
|
-
existing = await readFile(gitattributesPath, 'utf-8');
|
|
474
|
-
} catch {
|
|
475
|
-
// File doesn't exist — will create fresh
|
|
476
|
-
}
|
|
477
|
-
|
|
478
|
-
const missingPatterns = LFS_PATTERNS.filter((pattern) => !existing.includes(pattern));
|
|
479
|
-
|
|
480
|
-
if (missingPatterns.length === 0) return;
|
|
481
|
-
|
|
482
|
-
const newContent = existing
|
|
483
|
-
? `${existing.trimEnd()}\n${missingPatterns.join('\n')}\n`
|
|
484
|
-
: `${missingPatterns.join('\n')}\n`;
|
|
485
|
-
|
|
486
|
-
await writeFile(gitattributesPath, newContent, 'utf-8');
|
|
487
|
-
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What an upload is, read from its bytes rather than its name: a server stores a file by what it actually holds.
|
|
3
|
+
* Pure and runtime-neutral, so the browser entry can re-export it.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/** The image formats the editors store, by content. */
|
|
7
|
+
export type ImageFormat = 'jpeg' | 'png' | 'webp' | 'gif' | 'avif' | 'ico' | 'svg';
|
|
8
|
+
|
|
9
|
+
/** How much of a text file is read to find its first element: room for a long comment and an Illustrator DOCTYPE. */
|
|
10
|
+
const SVG_PROLOG_BYTES = 64 * 1024;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* True when `text` opens with an optional BOM, then whitespace, the XML declaration, comments, processing
|
|
14
|
+
* instructions and DOCTYPEs, then `<svg`. Each skip searches forward from where the last one ended, so the scan stays
|
|
15
|
+
* linear however the prolog is built (a backtracking pattern took seconds on a few KB of empty comments).
|
|
16
|
+
*/
|
|
17
|
+
function startsWithSvg(text: string): boolean {
|
|
18
|
+
let at = text.startsWith('\uFEFF') ? 1 : 0;
|
|
19
|
+
const past = (close: string, from: number) => {
|
|
20
|
+
const found = text.indexOf(close, from);
|
|
21
|
+
return found === -1 ? -1 : found + close.length;
|
|
22
|
+
};
|
|
23
|
+
while (at < text.length) {
|
|
24
|
+
if (/\s/.test(text[at] ?? '')) at += 1;
|
|
25
|
+
else if (text.startsWith('<?', at)) at = past('?>', at + 2);
|
|
26
|
+
else if (text.startsWith('<!--', at)) at = past('-->', at + 4);
|
|
27
|
+
else if (text.startsWith('<!DOCTYPE', at)) at = doctypeEnd(text, at);
|
|
28
|
+
else return /^<svg[\s/>]/.test(text.slice(at, at + 5));
|
|
29
|
+
if (at === -1) return false; // never closed
|
|
30
|
+
}
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The index just past the `>` that closes the DOCTYPE at `start`, after its internal subset when it has one; -1 if none. */
|
|
35
|
+
function doctypeEnd(text: string, start: number): number {
|
|
36
|
+
const close = text.indexOf('>', start);
|
|
37
|
+
if (close === -1) return -1;
|
|
38
|
+
// Looked for only up to that `>`, so a run of DOCTYPEs never rescans the rest of the text.
|
|
39
|
+
const open = text.slice(start, close).indexOf('[');
|
|
40
|
+
if (open === -1) return close + 1;
|
|
41
|
+
const bracket = start + open;
|
|
42
|
+
// The subset ends at the first `]` that only whitespace separates from `>`.
|
|
43
|
+
for (let end = text.indexOf(']', bracket); end !== -1; end = text.indexOf(']', end + 1)) {
|
|
44
|
+
let next = end + 1;
|
|
45
|
+
while (/\s/.test(text[next] ?? '')) next += 1;
|
|
46
|
+
if (text[next] === '>') return next + 1;
|
|
47
|
+
}
|
|
48
|
+
return -1;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function ascii(bytes: Uint8Array, start: number, text: string): boolean {
|
|
52
|
+
if (bytes.length < start + text.length) return false;
|
|
53
|
+
for (let i = 0; i < text.length; i += 1) if (bytes[start + i] !== text.charCodeAt(i)) return false;
|
|
54
|
+
return true;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** True when an ISO-BMFF `ftyp` box names an AVIF brand, as its major brand or a compatible one. */
|
|
58
|
+
function isAvif(bytes: Uint8Array): boolean {
|
|
59
|
+
if (!ascii(bytes, 4, 'ftyp')) return false;
|
|
60
|
+
const boxEnd = Math.min(new DataView(bytes.buffer, bytes.byteOffset, 4).getUint32(0), bytes.length);
|
|
61
|
+
for (let brand = 8; brand + 4 <= boxEnd; brand += brand === 8 ? 8 : 4) {
|
|
62
|
+
if (ascii(bytes, brand, 'avif') || ascii(bytes, brand, 'avis')) return true;
|
|
63
|
+
}
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function isSvg(bytes: Uint8Array): boolean {
|
|
68
|
+
let prolog: string;
|
|
69
|
+
try {
|
|
70
|
+
// `stream` holds back a character the cut splits instead of failing on it.
|
|
71
|
+
prolog = new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(0, SVG_PROLOG_BYTES), { stream: true });
|
|
72
|
+
} catch {
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
75
|
+
return startsWithSvg(prolog);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The image format `bytes` hold, or `null` when they are no image the editors store. */
|
|
79
|
+
export function sniffImageFormat(bytes: Uint8Array): ImageFormat | null {
|
|
80
|
+
if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'jpeg';
|
|
81
|
+
if (ascii(bytes, 0, '\x89PNG\r\n\x1a\n')) return 'png';
|
|
82
|
+
if (ascii(bytes, 0, 'RIFF') && ascii(bytes, 8, 'WEBP')) return 'webp';
|
|
83
|
+
if (ascii(bytes, 0, 'GIF8')) return 'gif';
|
|
84
|
+
if (isAvif(bytes)) return 'avif';
|
|
85
|
+
if (ascii(bytes, 0, '\x00\x00\x01\x00')) return 'ico';
|
|
86
|
+
return isSvg(bytes) ? 'svg' : null;
|
|
87
|
+
}
|