cloudflare-model-host 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/stage.js ADDED
@@ -0,0 +1,150 @@
1
+ // Staging (fm-3osh), from classic hosting/next/prepare-runtime.py's publish/rewrite core: every asset a
2
+ // manifest names is checked against its declared digest and size, copied to the same relative path under the
3
+ // output root (or cut into chunks when it exceeds the static file limit), and the manifest is rewritten to
4
+ // hosted URLs under `base`. Application policy (phone admission, promotion, the photo sub-bundle) stays in the
5
+ // app's hosting. Nothing private is copied: the source inventory and any local path stay behind.
6
+ import { copyFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
7
+ import { dirname, isAbsolute, join, normalize, relative, resolve, sep } from 'node:path';
8
+ import { fileDigest, freeze, needsChunks, reconstruct, writeChunks, } from './chunks.js';
9
+ import { assets, checkContract, provenanceFindings } from './manifest.js';
10
+ export class StageError extends Error {
11
+ code;
12
+ constructor(code, message) {
13
+ super(message);
14
+ this.code = code;
15
+ }
16
+ }
17
+ const trim = (s) => s.replace(/\/+$/u, '');
18
+ /** Resolves a manifest-relative path inside `root`, refusing absolute paths and `..` escapes. */
19
+ export function inside(root, rel) {
20
+ const clean = normalize(rel);
21
+ if (isAbsolute(rel) || clean === '..' || clean.startsWith(`..${sep}`) || rel.includes('\0'))
22
+ throw new StageError('unsafe-path', `unsafe asset path: ${rel}`);
23
+ const full = resolve(root, clean);
24
+ if (relative(resolve(root), full).startsWith('..'))
25
+ throw new StageError('unsafe-path', `unsafe asset path: ${rel}`);
26
+ return full;
27
+ }
28
+ function relativeOf(asset, fromBase, where) {
29
+ if (typeof asset.file === 'string')
30
+ return asset.file;
31
+ if (fromBase && typeof asset.url === 'string' && asset.url.startsWith(`${trim(fromBase)}/`))
32
+ return asset.url.slice(trim(fromBase).length + 1);
33
+ throw new StageError('unmapped-url', `${where}: ${asset.url ?? '(no url)'} is not under --from-base`);
34
+ }
35
+ /** Stages a manifest's assets; see StageOptions. Throws StageError on the first refusal. */
36
+ export function stage(options) {
37
+ const base = trim(options.base);
38
+ if (!/^https:\/\/[^/@\s]+(\/\S*)?$/u.test(base))
39
+ throw new StageError('not-https', `base must be an https origin: ${base}`);
40
+ const source = resolve(options.source);
41
+ const manifest = JSON.parse(readFileSync(join(source, options.manifest ?? 'manifest.json'), 'utf8'));
42
+ const unpublished = assets(manifest).some(({ asset }) => typeof asset.file === 'string');
43
+ const before = checkContract(manifest, { unpublished });
44
+ if (!before.ok)
45
+ throw new StageError('contract', `${before.error.code} at ${before.error.path}: ${before.error.message}`);
46
+ const files = new Map();
47
+ const published = new Map();
48
+ let chunked = 0;
49
+ const found = assets(manifest);
50
+ for (const { path, asset } of found) {
51
+ const rel = relativeOf(asset, options.fromBase, path).split('\\').join('/');
52
+ const prior = published.get(rel);
53
+ if (prior) {
54
+ if (prior.sha256 !== asset.sha256 || prior.size !== asset.size)
55
+ throw new StageError('descriptor-conflict', `${path}: ${rel} is declared twice with different digests`);
56
+ }
57
+ else {
58
+ const src = inside(source, rel);
59
+ if (!existsSync(src) && asset.chunks && needsChunks(asset.size)) {
60
+ // A hosted tree keeps large assets only as chunks: verify them and the whole, then carry them over.
61
+ const chunks = asset.chunks.map((c, i) => ({
62
+ path: relativeOf(c, options.fromBase, `${path}.chunks[${i}]`),
63
+ sha256: c.sha256,
64
+ size: c.size,
65
+ }));
66
+ const whole = reconstruct(chunks, source);
67
+ if (whole.problems.length || whole.sha256 !== asset.sha256 || whole.size !== asset.size)
68
+ throw new StageError('integrity', `${path}: the chunks of ${rel} do not reconstruct its declared digest`);
69
+ for (const c of chunks) {
70
+ if (!options.dryRun)
71
+ freeze(inside(options.out, c.path), readFileSync(inside(source, c.path)));
72
+ files.set(c.path, { path: c.path, sha256: c.sha256, bytes: c.size });
73
+ }
74
+ published.set(rel, { sha256: asset.sha256, size: asset.size, chunks });
75
+ chunked++;
76
+ const entry = published.get(rel);
77
+ delete asset.file;
78
+ asset.url = `${base}/${rel}`;
79
+ asset.chunks = entry.chunks.map((c) => ({
80
+ url: `${base}/${c.path}`,
81
+ size: c.size,
82
+ sha256: c.sha256,
83
+ }));
84
+ continue;
85
+ }
86
+ const got = existsSync(src) ? fileDigest(src) : undefined;
87
+ if (!got || got.sha256 !== asset.sha256 || got.size !== asset.size)
88
+ throw new StageError('integrity', `${path}: ${rel} does not match its declared digest and size`);
89
+ if (needsChunks(asset.size)) {
90
+ const chunks = writeChunks(src, options.out, { dryRun: options.dryRun === true });
91
+ for (const c of chunks)
92
+ files.set(c.path, { path: c.path, sha256: c.sha256, bytes: c.size });
93
+ published.set(rel, { sha256: asset.sha256, size: asset.size, chunks });
94
+ chunked++;
95
+ }
96
+ else {
97
+ if (!options.dryRun) {
98
+ const dest = inside(options.out, rel);
99
+ if (existsSync(dest)) {
100
+ const have = fileDigest(dest);
101
+ if (have.sha256 !== asset.sha256 || have.size !== asset.size)
102
+ throw new Error(`Immutable destination changed: ${rel}`);
103
+ }
104
+ else {
105
+ mkdirSync(dirname(dest), { recursive: true });
106
+ copyFileSync(src, dest);
107
+ }
108
+ }
109
+ files.set(rel, { path: rel, sha256: asset.sha256, bytes: asset.size });
110
+ published.set(rel, { sha256: asset.sha256, size: asset.size });
111
+ }
112
+ }
113
+ const entry = published.get(rel);
114
+ delete asset.file;
115
+ asset.url = `${base}/${rel}`;
116
+ if (entry.chunks)
117
+ asset.chunks = entry.chunks.map((c) => ({
118
+ url: `${base}/${c.path}`,
119
+ size: c.size,
120
+ sha256: c.sha256,
121
+ }));
122
+ else
123
+ delete asset.chunks;
124
+ }
125
+ // Strings elsewhere that still point at the old prefix (wasmPaths, asset bases) move with the assets.
126
+ const rewritten = rebase(manifest, options.fromBase ? trim(options.fromBase) : undefined, base);
127
+ const after = checkContract(rewritten);
128
+ if (!after.ok)
129
+ throw new StageError('contract', `staged manifest: ${after.error.code} at ${after.error.path}`);
130
+ const leaks = provenanceFindings(rewritten);
131
+ if (leaks.length)
132
+ throw new StageError('private-provenance', `staged manifest leaks ${leaks.map((l) => `${l.rule} at ${l.path}`).join(', ')}`);
133
+ if (!options.dryRun)
134
+ freeze(join(options.out, 'manifest.json'), new TextEncoder().encode(`${JSON.stringify(rewritten, null, 2)}\n`));
135
+ return {
136
+ manifest: rewritten,
137
+ files: [...files.values()].sort((a, b) => (a.path < b.path ? -1 : 1)),
138
+ assets: found.length,
139
+ chunked,
140
+ };
141
+ }
142
+ function rebase(v, from, to) {
143
+ if (typeof v === 'string')
144
+ return from && (v === from || v.startsWith(`${from}/`)) ? to + v.slice(from.length) : v;
145
+ if (Array.isArray(v))
146
+ return v.map((x) => rebase(x, from, to));
147
+ if (typeof v === 'object' && v !== null)
148
+ return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, rebase(x, from, to)]));
149
+ return v;
150
+ }
@@ -0,0 +1,31 @@
1
+ import { type LimitFinding, type Plan } from './limits.ts';
2
+ export interface VerifyFinding {
3
+ readonly path: string;
4
+ readonly problem: string;
5
+ }
6
+ export interface VerifyReport {
7
+ readonly ok: boolean;
8
+ readonly assets: number;
9
+ readonly chunked: number;
10
+ readonly chunks: number;
11
+ readonly files: number;
12
+ readonly bytes: number;
13
+ readonly largestFile: {
14
+ readonly path: string;
15
+ readonly bytes: number;
16
+ };
17
+ readonly findings: readonly VerifyFinding[];
18
+ readonly limits: readonly LimitFinding[];
19
+ }
20
+ /** Every regular file under `root`, relative and posix, with its size. */
21
+ export declare function listFiles(root: string): {
22
+ path: string;
23
+ bytes: number;
24
+ }[];
25
+ /** Verifies `root` against `root/manifest.json` (or `manifest`), whose URLs start with `base`. */
26
+ export declare function verifyRoot(options: {
27
+ readonly root: string;
28
+ readonly base: string;
29
+ readonly manifest?: string;
30
+ readonly plan?: Plan;
31
+ }): VerifyReport;
package/dist/verify.js ADDED
@@ -0,0 +1,89 @@
1
+ // Reconstruction verification of a staged or published root (fm-3osh): every asset the manifest names is read
2
+ // back from the root by its URL path, a chunked asset through its chunks, and must match its declared digest and
3
+ // size; every file in the root must fit the static file limit and the plan's file count.
4
+ import { readdirSync, readFileSync, statSync } from 'node:fs';
5
+ import { join, relative } from 'node:path';
6
+ import { fileDigest, reconstruct } from './chunks.js';
7
+ import { limitFindings } from './limits.js';
8
+ import { assets, checkContract, provenanceFindings } from './manifest.js';
9
+ import { inside } from './stage.js';
10
+ /** Every regular file under `root`, relative and posix, with its size. */
11
+ export function listFiles(root) {
12
+ const out = [];
13
+ const walk = (dir) => {
14
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
15
+ const full = join(dir, e.name);
16
+ if (e.isDirectory())
17
+ walk(full);
18
+ else if (e.isFile())
19
+ out.push({ path: relative(root, full).split('\\').join('/'), bytes: statSync(full).size });
20
+ }
21
+ };
22
+ walk(root);
23
+ return out.sort((a, b) => (a.path < b.path ? -1 : 1));
24
+ }
25
+ /** Verifies `root` against `root/manifest.json` (or `manifest`), whose URLs start with `base`. */
26
+ export function verifyRoot(options) {
27
+ const base = options.base.replace(/\/+$/u, '');
28
+ const manifest = JSON.parse(readFileSync(join(options.root, options.manifest ?? 'manifest.json'), 'utf8'));
29
+ const findings = [];
30
+ const contract = checkContract(manifest);
31
+ if (!contract.ok)
32
+ findings.push({ path: contract.error.path, problem: `contract: ${contract.error.code}` });
33
+ for (const p of provenanceFindings(manifest))
34
+ findings.push({ path: p.path, problem: `private provenance: ${p.rule}` });
35
+ const pathOf = (url, where) => {
36
+ if (typeof url === 'string' && url.startsWith(`${base}/`))
37
+ return url.slice(base.length + 1);
38
+ findings.push({ path: where, problem: `url not under ${base}` });
39
+ return undefined;
40
+ };
41
+ let chunked = 0;
42
+ let chunks = 0;
43
+ const found = assets(manifest);
44
+ for (const { path, asset } of found) {
45
+ if (asset.chunks) {
46
+ chunked++;
47
+ chunks += asset.chunks.length;
48
+ const list = asset.chunks.map((c, i) => ({
49
+ path: pathOf(c.url, `${path}.chunks[${i}]`) ?? '',
50
+ sha256: c.sha256,
51
+ size: c.size,
52
+ }));
53
+ const whole = reconstruct(list, options.root);
54
+ for (const p of whole.problems)
55
+ findings.push({ path: `${path} ${p.path}`, problem: p.problem });
56
+ if (whole.sha256 !== asset.sha256 || whole.size !== asset.size)
57
+ findings.push({ path, problem: 'reconstruction differs from the asset digest' });
58
+ continue;
59
+ }
60
+ const rel = pathOf(asset.url, path);
61
+ if (rel === undefined)
62
+ continue;
63
+ let got;
64
+ try {
65
+ got = fileDigest(inside(options.root, rel));
66
+ }
67
+ catch {
68
+ got = undefined;
69
+ }
70
+ if (!got)
71
+ findings.push({ path, problem: `missing: ${rel}` });
72
+ else if (got.sha256 !== asset.sha256 || got.size !== asset.size)
73
+ findings.push({ path, problem: `digest differs: ${rel}` });
74
+ }
75
+ const files = listFiles(options.root);
76
+ const limits = limitFindings(files, options.plan ?? 'workers-free');
77
+ const largest = files.reduce((a, f) => (f.bytes > a.bytes ? f : a), { path: '', bytes: 0 });
78
+ return {
79
+ ok: findings.length === 0 && limits.length === 0,
80
+ assets: found.length,
81
+ chunked,
82
+ chunks,
83
+ files: files.length,
84
+ bytes: files.reduce((n, f) => n + f.bytes, 0),
85
+ largestFile: largest,
86
+ findings,
87
+ limits,
88
+ };
89
+ }
package/package.json CHANGED
@@ -1,6 +1,58 @@
1
1
  {
2
2
  "name": "cloudflare-model-host",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "description": "Stages, verifies and publishes verified model bytes for Cloudflare static hosting: chunking above the 25 MiB file limit, manifest rewriting against the manager's contract, reconstruction verification, dry-run-first publication with paid-service and model-terms refusals (fm-3osh).",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/facemorph-me/facemorph.me.git",
10
+ "directory": "packages/cloudflare-model-host"
11
+ },
12
+ "homepage": "https://github.com/facemorph-me/facemorph.me/tree/main/packages/cloudflare-model-host#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/facemorph-me/facemorph.me/issues"
15
+ },
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "default": "./dist/index.js"
20
+ }
21
+ },
22
+ "bin": {
23
+ "facemorph-model-host": "./dist/cli.js"
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "README.md",
28
+ "THIRD_PARTY_NOTICES",
29
+ "PROVENANCE.json",
30
+ "CHANGELOG.md",
31
+ "cloudflare.config.ts",
32
+ "vite.config.ts",
33
+ "src/mirror/worker.ts",
34
+ "LICENSE"
35
+ ],
36
+ "engines": {
37
+ "node": ">=24"
38
+ },
39
+ "scripts": {
40
+ "typecheck": "tsc -p tsconfig.json --incremental && tsc -p tsconfig.test.json --incremental",
41
+ "build": "tsc -p tsconfig.build.json && node ../../scripts/packages/write-provenance.mjs",
42
+ "test": "node --test test/*.test.ts",
43
+ "test:workerd": "node --test test/*.workerd.ts",
44
+ "test:staging": "node --test test/*.e2e.ts"
45
+ },
46
+ "dependencies": {
47
+ "@cloudflare/vite-plugin": "^2.0.0-beta.v.4",
48
+ "browser-model-manager": "^0.1.0",
49
+ "cf": "^1.0.0-beta.21",
50
+ "vite": "^8.3.5"
51
+ },
52
+ "devDependencies": {
53
+ "@types/node": "^26.6.5",
54
+ "ajv": "^8.20.0",
55
+ "miniflare": "^4.20260730.0",
56
+ "typescript": "^7.0.2"
57
+ }
58
+ }
@@ -0,0 +1,124 @@
1
+ // The mirror Worker (fm-fy2.14): a second copy of an upstream site's immutable, content-addressed runtime files,
2
+ // held in an R2 bucket and served with CORS and CORP so another origin's page can fetch them. Ported from classic
3
+ // hosting/next-mirror/worker.mjs (see ../../mirror/provenance.json): the upstream origin and the mirrored prefixes are
4
+ // configuration, so the Worker names no host of its own. On 20 October one Cloudflare edge answered HTTP 500 from
5
+ // static-asset storage for single encoder chunks for ten minutes at a time; a page retries such a file here, on
6
+ // separate storage.
7
+ //
8
+ // A file not yet held is copied from the upstream on first request (a deploy warms every runtime path with HEAD), and
9
+ // only under the configured prefixes: those paths are immutable and the page checks every byte against its pin, so a
10
+ // stale or wrong copy can only fail. Anything else is refused without a fetch.
11
+ //
12
+ // Configuration (Worker vars and bindings):
13
+ // UPSTREAM the origin copied from, e.g. https://example.org/ (required; a trailing slash is added if missing)
14
+ // PREFIXES comma-separated immutable path prefixes, e.g. runtime/chunks/,runtime/assets/ (required)
15
+ // MIRROR the R2 bucket binding
16
+ // SITE optional service binding to the upstream Worker; fetches go through it when bound
17
+
18
+ /** The R2 object fields the Worker reads (a subset of the Workers runtime's R2Object). */
19
+ export interface HeldObject {
20
+ size: number;
21
+ httpEtag: string;
22
+ httpMetadata?: { contentType?: string };
23
+ }
24
+ export interface HeldObjectBody extends HeldObject {
25
+ body: ReadableStream;
26
+ }
27
+ /** The R2 bucket methods the Worker calls. */
28
+ export interface MirrorBucket {
29
+ head(key: string): Promise<HeldObject | null>;
30
+ get(key: string): Promise<HeldObjectBody | null>;
31
+ put(
32
+ key: string,
33
+ value: ArrayBuffer,
34
+ options: { httpMetadata: { contentType: string } },
35
+ ): Promise<HeldObject>;
36
+ }
37
+ export interface MirrorEnv {
38
+ UPSTREAM?: string;
39
+ PREFIXES?: string;
40
+ MIRROR: MirrorBucket;
41
+ SITE?: { fetch(request: Request): Promise<Response> };
42
+ }
43
+
44
+ const SHARED = {
45
+ 'Access-Control-Allow-Origin': '*',
46
+ 'Cross-Origin-Resource-Policy': 'cross-origin',
47
+ 'X-Content-Type-Options': 'nosniff',
48
+ };
49
+ const IMMUTABLE = 'public, max-age=31536000, immutable';
50
+
51
+ const empty = (status: number, extra: Record<string, string> = {}) =>
52
+ new Response(null, { status, headers: { ...SHARED, 'Cache-Control': 'no-store', ...extra } });
53
+
54
+ function reply(object: HeldObject, body: BodyInit | null): Response {
55
+ return new Response(body, {
56
+ status: 200,
57
+ headers: {
58
+ ...SHARED,
59
+ 'Content-Type': object.httpMetadata?.contentType || 'application/octet-stream',
60
+ 'Content-Length': String(object.size),
61
+ ETag: object.httpEtag,
62
+ 'Cache-Control': IMMUTABLE,
63
+ },
64
+ });
65
+ }
66
+
67
+ /** The configured prefixes; an empty or missing list mirrors nothing. Pure. */
68
+ export function prefixes(config: string | undefined): string[] {
69
+ return (config ?? '')
70
+ .split(',')
71
+ .map((p) => p.trim())
72
+ .filter((p) => p.length > 0)
73
+ .map((p) => (p.endsWith('/') ? p : `${p}/`));
74
+ }
75
+
76
+ /** Whether `key` is a mirrored path: under a configured prefix, with no empty or `..` segment. Pure. */
77
+ export function mirrored(key: string, allowed: readonly string[]): boolean {
78
+ return (
79
+ allowed.some((prefix) => key.startsWith(prefix)) &&
80
+ !key.split('/').some((part) => part === '..' || part === '')
81
+ );
82
+ }
83
+
84
+ export default {
85
+ async fetch(request: Request, env: MirrorEnv): Promise<Response> {
86
+ if (request.method === 'OPTIONS')
87
+ return empty(204, {
88
+ 'Access-Control-Allow-Methods': 'GET, HEAD',
89
+ 'Access-Control-Max-Age': '86400',
90
+ });
91
+ if (request.method !== 'GET' && request.method !== 'HEAD')
92
+ return empty(405, { Allow: 'GET, HEAD' });
93
+ const upstream = env.UPSTREAM?.trim();
94
+ if (!upstream) return empty(503);
95
+ let key: string;
96
+ try {
97
+ key = decodeURIComponent(new URL(request.url).pathname.slice(1));
98
+ } catch {
99
+ return empty(404);
100
+ }
101
+ if (!mirrored(key, prefixes(env.PREFIXES))) return empty(404);
102
+ const head = request.method === 'HEAD';
103
+ const held = head ? await env.MIRROR.head(key) : await env.MIRROR.get(key);
104
+ if (held) return reply(held, head ? null : (held as HeldObjectBody).body);
105
+ const base = new URL(upstream.endsWith('/') ? upstream : `${upstream}/`);
106
+ const url = new URL(key, base);
107
+ // The configured upstream is the only origin fetched.
108
+ if (url.origin !== base.origin || !url.pathname.startsWith(base.pathname)) return empty(404);
109
+ const source = new Request(url);
110
+ const origin = await (env.SITE ? env.SITE.fetch(source) : fetch(source));
111
+ if (origin.status !== 200) {
112
+ void origin.body?.cancel();
113
+ return empty(origin.status === 404 ? 404 : 502);
114
+ }
115
+ // Runtime files are at most 25 MiB (the static-asset limit), so buffering one is cheap.
116
+ const bytes = await origin.arrayBuffer();
117
+ const saved = await env.MIRROR.put(key, bytes, {
118
+ httpMetadata: {
119
+ contentType: origin.headers.get('Content-Type') || 'application/octet-stream',
120
+ },
121
+ });
122
+ return reply(saved, head ? null : bytes);
123
+ },
124
+ };
package/vite.config.ts ADDED
@@ -0,0 +1,9 @@
1
+ // cf builds the package's cf project (cloudflare.config.ts) through the Cloudflare Vite plugin (fm-fy2.14). In the
2
+ // model-origin mode the prepared public directory (the staged root at its base path, with `_headers`) is the assets.
3
+ import { cloudflare } from '@cloudflare/vite-plugin';
4
+ import { defineConfig } from 'vite';
5
+
6
+ export default defineConfig(({ mode }) => ({
7
+ publicDir: mode === 'model-origin' ? process.env['MODEL_ORIGIN_PUBLIC'] : false,
8
+ plugins: [cloudflare()],
9
+ }));