Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,43 @@ jobs:
- run: pnpm typecheck
- run: pnpm test:coverage

# 単独アプリ (apps/web) に対して現像の E2E を回す。WebGL は SwiftShader。公開リポジトリで時間の制約が無く、
# 30 秒ほどで終わるので、すべての PR で回す
e2e:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
node-version: 24.21.0
cache: pnpm
- run: pnpm install --frozen-lockfile
# 認識のモデル (約 60 MB) は一覧 (bin/assets.ts) が変わらない限り同じ。毎回ダウンロードしない
- uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: apps/web/models
key: models-${{ hashFiles('packages/editor-engine/bin/assets.ts', 'pnpm-lock.yaml') }}
# Chromium 本体は Playwright の版でキャッシュし、OS のライブラリだけ毎回入れる
- id: playwright-version
run: echo "version=$(node -p "require('@playwright/test/package.json').version")" >> "$GITHUB_OUTPUT"
- id: playwright-cache
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ~/.cache/ms-playwright
key: playwright-${{ runner.os }}-${{ steps.playwright-version.outputs.version }}
- if: steps.playwright-cache.outputs.cache-hit != 'true'
run: pnpm exec playwright install --with-deps chromium
- if: steps.playwright-cache.outputs.cache-hit == 'true'
run: pnpm exec playwright install-deps chromium
- run: pnpm e2e
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
if: failure()
with:
name: playwright-results
path: test-results/
retention-days: 7

# シークレットの混入と高リスクの脆弱性。audit は警告に留める
security:
runs-on: ubuntu-latest
Expand Down
8 changes: 5 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ lumorphia/editor: ブラウザで動く写真の現像エディタ。描画 (Pix
packages/editor-recipe @lumorphia/editor-recipe 編集レシピ (zod)。ブラウザでもサーバーでも動く
packages/editor-engine @lumorphia/editor-engine 状態、描画、推論 (Worker)、下書き、CLI editor-models
packages/editor-react @lumorphia/editor-react UI。<Editor host={...} />
apps/web 単独アプリ (E2E の土台を兼ねる)
e2e/ E2E (prismtone から移した。apps/web を土台にして回す: #3)
apps/web 単独アプリ (Vite + React。server/serve.ts が COOP / COEP / CSP 付きで配る。E2E の土台を兼ねる)
e2e/ E2E (apps/web に対して Playwright で回す。e2e/README.md)
docs/design/ 設計 (edit-recipe.md: レシピ、editor.md: 画面・描画・推論・テスト)
docs/adr/ 設計判断 (README.md に一覧と prismtone の番号との対応)
```
Expand Down Expand Up @@ -67,5 +67,7 @@ pnpm test # 単体テスト (ビルド不要)
pnpm test:coverage # カバレッジ付き
pnpm typecheck
pnpm lint && pnpm format:check
pnpm build # 各パッケージを dist に
pnpm build:packages # 各パッケージを dist に
pnpm e2e # パッケージと apps/web をビルドして E2E
pnpm --filter @lumorphia/editor-web dev # 単独アプリの dev サーバー
```
13 changes: 13 additions & 0 deletions apps/web/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="ja">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="robots" content="noindex" />
<title>現像 - Lumorphia</title>
</head>
<body class="bg-surface text-ink">
<div id="root" class="flex h-dvh flex-col p-2"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
27 changes: 27 additions & 0 deletions apps/web/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"name": "@lumorphia/editor-web",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "pnpm --dir ../.. build:packages && pnpm models && vite",
"build": "pnpm --dir ../.. build:packages && pnpm models && vite build",
"models": "editor-models fetch --out models",
"serve": "node server/serve.ts",
"typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.server.json",
"test": "vitest run"
},
"dependencies": {
"@lumorphia/editor-engine": "workspace:*",
"@lumorphia/editor-react": "workspace:*",
"react": "^19.3.0",
"react-dom": "^19.3.0"
},
"devDependencies": {
"@tailwindcss/vite": "^4.3.3",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"tailwindcss": "^4.3.3",
"vite": "^8.3.2"
}
}
66 changes: 66 additions & 0 deletions apps/web/server/serve.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/**
* 単独アプリを配る。vite build の dist と、editor-models が揃えた models/ (/models/ で配る) を返す。
* E2E の土台を兼ねる。ヘッダの決まりは static.ts
*
* PORT (既定 4300)、HOST (既定 127.0.0.1)
*/
import { createReadStream } from "node:fs";
import { stat } from "node:fs/promises";
import { createServer } from "node:http";
import path from "node:path";
import { cacheControl, contentType, resolveStatic, securityHeaders } from "./static.ts";

const here = import.meta.dirname;
const DIST = path.resolve(here, "../dist");
const MODELS = path.resolve(here, "../models");
const PORT = Number(process.env.PORT ?? 4300);
const HOST = process.env.HOST ?? "127.0.0.1";

async function isFile(file: string): Promise<boolean> {
try {
return (await stat(file)).isFile();
} catch {
return false;
}
}

/** URL を配るファイルに。モデルは models/、それ以外は dist/。拡張子の無いパスはページ (index.html) */
async function fileFor(url: string): Promise<string | null> {
const pathname = url.split("?")[0] ?? "/";
if (pathname.startsWith("/models/")) {
return resolveStatic(MODELS, pathname.slice("/models".length));
}
const file = resolveStatic(DIST, pathname);
if (file && (await isFile(file))) return file;
return path.extname(pathname) === "" ? path.join(DIST, "index.html") : null;
}

const server = createServer(async (req, res) => {
const headers = securityHeaders();
if (req.method !== "GET" && req.method !== "HEAD") {
res.writeHead(405, { ...headers, allow: "GET, HEAD" }).end();
return;
}
const url = req.url ?? "/";
const file = await fileFor(url);
if (!file || !(await isFile(file))) {
res
.writeHead(404, { ...headers, "content-type": "text/plain; charset=utf-8" })
.end("not found");
return;
}
res.writeHead(200, {
...headers,
"content-type": contentType(file),
"cache-control": cacheControl(url),
});
if (req.method === "HEAD") {
res.end();
return;
}
createReadStream(file).pipe(res);
});

server.listen(PORT, HOST, () => {
console.log(`editor-web: http://${HOST}:${PORT}`);
});
86 changes: 86 additions & 0 deletions apps/web/server/static.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import path from "node:path";
import { describe, expect, it } from "vitest";
import { cacheControl, contentType, resolveStatic, securityHeaders } from "./static.ts";

const root = "/srv/web";

describe("resolveStatic", () => {
it("maps a URL path to a file under the root", () => {
expect(resolveStatic(root, "/assets/app.js")).toBe(path.join(root, "assets/app.js"));
});

it("serves index.html for the root", () => {
expect(resolveStatic(root, "/")).toBe(path.join(root, "index.html"));
});

it("ignores the query string", () => {
expect(resolveStatic(root, "/?draft=abc")).toBe(path.join(root, "index.html"));
});

it("refuses to climb out of the root", () => {
expect(resolveStatic(root, "/../etc/passwd")).toBeNull();
});

it("refuses an encoded climb out of the root", () => {
expect(resolveStatic(root, "/%2e%2e/%2e%2e/etc/passwd")).toBeNull();
});

it("refuses a null byte", () => {
expect(resolveStatic(root, "/index.html%00.js")).toBeNull();
});

it("refuses a malformed escape", () => {
expect(resolveStatic(root, "/%E0%A4%A")).toBeNull();
});
});

describe("contentType", () => {
it("serves WASM with its own type so it can be compiled while streaming", () => {
expect(contentType("/x/ort.wasm")).toBe("application/wasm");
});

it("serves .mjs as JavaScript", () => {
expect(contentType("/x/ort.mjs")).toBe("text/javascript; charset=utf-8");
});

it("falls back to binary for model files", () => {
expect(contentType("/x/face_landmarker.task")).toBe("application/octet-stream");
});
});

describe("cacheControl", () => {
it("caches hashed assets forever", () => {
expect(cacheControl("/assets/app-abc123.js")).toBe("public, max-age=31536000, immutable");
});

it("caches versioned models forever", () => {
expect(cacheControl("/models/ort-v1/x.wasm")).toBe("public, max-age=31536000, immutable");
});

it("revalidates the page itself", () => {
expect(cacheControl("/")).toBe("no-cache");
});
});

describe("securityHeaders", () => {
const headers = securityHeaders();

it("isolates the page so the segmenter can use threads (COOP + COEP)", () => {
expect(headers["cross-origin-opener-policy"]).toBe("same-origin");
expect(headers["cross-origin-embedder-policy"]).toBe("credentialless");
});

it("allows WebAssembly without allowing eval", () => {
const csp = headers["content-security-policy"] ?? "";
expect(csp).toContain("script-src 'self' 'wasm-unsafe-eval'");
expect(csp).not.toContain("'unsafe-eval'");
});

it("allows blob and data images for the preview", () => {
expect(headers["content-security-policy"]).toContain("img-src 'self' data: blob:");
});

it("refuses to be framed", () => {
expect(headers["content-security-policy"]).toContain("frame-ancestors 'none'");
});
});
78 changes: 78 additions & 0 deletions apps/web/server/static.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/**
* 単独アプリの配信 (serve.ts) の決まり。外から来るパスを扱うので、純粋関数にしてテストする。
* ヘッダは lumorphia/prismtone の /edit と同じ考え方 (ADR-0005: ブラウザで描く、COOP / COEP で
* SharedArrayBuffer を使えるようにして onnxruntime-web をマルチスレッドで動かす、CSP に unsafe-eval を入れない)
*/
import path from "node:path";

/** URL のパスを root の下のファイルに。外に出る・不正なものは null */
export function resolveStatic(root: string, urlPath: string): string | null {
const pathname = urlPath.split("?")[0] ?? "/";
let decoded: string;
try {
decoded = decodeURIComponent(pathname);
} catch {
return null;
}
if (decoded.includes("\0")) return null;
const relative = decoded === "/" ? "index.html" : decoded.replace(/^\/+/, "");
const resolved = path.resolve(root, relative);
const base = path.resolve(root);
if (resolved !== base && !resolved.startsWith(base + path.sep)) return null;
return resolved;
}

const TYPES: Readonly<Record<string, string>> = {
".html": "text/html; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".mjs": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".json": "application/json; charset=utf-8",
".wasm": "application/wasm",
".png": "image/png",
".jpg": "image/jpeg",
".svg": "image/svg+xml",
".ico": "image/x-icon",
".webmanifest": "application/manifest+json",
};

export function contentType(file: string): string {
return TYPES[path.extname(file).toLowerCase()] ?? "application/octet-stream";
}

/** ファイル名にハッシュが付くもの (Vite の assets) と版付きのモデルは変わらない */
export function cacheControl(urlPath: string): string {
return urlPath.startsWith("/assets/") || urlPath.startsWith("/models/")
? "public, max-age=31536000, immutable"
: "no-cache";
}

const CSP: Readonly<Record<string, readonly string[]>> = {
"default-src": ["'self'"],
// PixiJS と MediaPipe / onnxruntime-web の WASM に 'wasm-unsafe-eval'。インラインのスクリプトは無い
"script-src": ["'self'", "'wasm-unsafe-eval'"],
// React の style 属性
"style-src": ["'self'", "'unsafe-inline'"],
// 現像のプレビューと書き出し
"img-src": ["'self'", "data:", "blob:"],
"font-src": ["'self'", "data:"],
"connect-src": ["'self'"],
"worker-src": ["'self'", "blob:"],
"frame-ancestors": ["'none'"],
"form-action": ["'self'"],
"base-uri": ["'self'"],
"object-src": ["'none'"],
};

export function securityHeaders(): Record<string, string> {
return {
"content-security-policy": Object.entries(CSP)
.map(([k, v]) => `${k} ${v.join(" ")}`)
.join("; "),
"cross-origin-opener-policy": "same-origin",
"cross-origin-embedder-policy": "credentialless",
"x-content-type-options": "nosniff",
"referrer-policy": "strict-origin-when-cross-origin",
"permissions-policy": "camera=(), microphone=(), geolocation=()",
};
}
Loading
Loading