diff --git a/docs/api-contract.md b/docs/api-contract.md
index ae5733f..1c1dd0f 100644
--- a/docs/api-contract.md
+++ b/docs/api-contract.md
@@ -20,14 +20,31 @@
- 分类的 `sort_order` 表示**场景内**排序;链接保持原有全局排序语义不变。
- 默认场景只认 `is_default = 1`,不按 id 或名字「通用」查找;`is_default` 只读,API 不提供转移默认场景的能力。
- 搜索引擎不属于任何场景,全场景共用;`visibility` 逻辑完全不变。
-- `/api/public`、`/api/private` 返回全部场景,以及各场景下按既有可见性规则可见的分类;服务端不按场景裁剪,场景切换由客户端本地过滤。
-- DTO 形状:`SceneDto{id,name,icon,sortOrder,isDefault}`;后台场景额外返回 `AdminSceneDto = SceneDto + {createdAt,updatedAt}`;分类 DTO 增加 `sceneId`。
+- `/api/public`、`/api/private` 返回可见场景(口径见下节「场景可见性」),以及各场景下按既有可见性规则可见的分类;除可见性层外,服务端不按场景切换裁剪,场景切换由客户端本地过滤。
+- DTO 形状:`SceneDto{id,name,icon,sortOrder,isDefault,visibility}`;后台场景额外返回 `AdminSceneDto = SceneDto + {createdAt,updatedAt}`;分类 DTO 增加 `sceneId`。
+
+## 场景可见性(v1.2,nav #19 冻结契约)
+
+### 数据模型(迁移 `schema_v3`)
+
+- `{prefix}scenes` 新增 `visibility TEXT NOT NULL DEFAULT 'public' CHECK (visibility IN ('public','private'))`,与分类同名属性同口径。
+- 存量行由列默认值取 `public`(含种子默认场景),因此升级后的默认场景仍是公开的。
+- 迁移只增不删、由账本保证只执行一次;`ADD COLUMN` 无 `IF NOT EXISTS`,重放安全与 `schema_v2` 的 `categories.scene_id` 同口径(账本已记录即跳过,绝不重复 `ALTER`)。表名随 `TABLE_PREFIX` 三态变化。
+
+### 语义(两层取与)
+
+- 有效可见性 = **场景公开 AND 分类公开**。私有场景整个空间对外不存在:场景本身、它下面的全部分类(无论分类自身标记)、以及这些分类下的链接,都不进入未登录可见数据。
+- 分类自身 `visibility` 保留不动,不做级联改写;公开场景内继续按分类自身 `visibility` 过滤;链接没有独立可见性,跟随分类。
+- 登录(所有者)视角全量可见:`/api/private` 返回全部场景(场景 DTO 带 `visibility` 与 `isDefault`)与全部分类;分类 DTO 形状不变(没有 `visibility`/`isDefault`,前端靠「全量里有、公开列表里没有」判断私有)。
+- 未登录数据里不得出现私有场景的名称、图标、id 等任何字段(图标注册表 `GET /api/icon` 同口径)。
+- 私有场景不得被设为默认:设默认操作遇私有 → 400 `{"error":…}`;默认场景不得改为私有:更新 `visibility` 若当前为默认且目标 `private` → 400,须先移默认。`isDefault` 机制沿用 v1.1,本版不动。
+- 删场景时分类迁入默认场景的既有流程不受影响:分类私有标记保留,由上面的取与规则保证不外露。
## 公开
### GET /api/public
-200 JSON。只含 `visibility=public` 的分类与链接(分类内嵌其公开链接);私有分类、私有链接、以及「private 分类下的 public 链接」(可见性取更严一方)完全不出现。响应 `Cache-Control: public, max-age=60`。
+200 JSON。有效可见性 = 场景公开 AND 分类公开(两层取与,见「场景可见性」):只含公开场景、公开分类与公开链接(分类内嵌其公开链接);私有场景、私有分类、私有链接、以及「private 分类下的 public 链接」完全不出现。响应 `Cache-Control: public, max-age=60`。
```json
{
@@ -57,7 +74,8 @@
"name": "通用",
"icon": null,
"sortOrder": 0,
- "isDefault": true
+ "isDefault": true,
+ "visibility": "public"
}
],
"searchEngines": [
@@ -81,7 +99,7 @@
}
```
-`scenes`:全部场景,按 `sortOrder, createdAt` 排序,**包含只有私有分类的场景**(场景本身没有 visibility;私有分类与链接仍按原可见性规则不出现)。`/api/private` 与 `/api/public` 同结构,两者都返回全量场景,服务端不按场景裁剪;分类的 `sceneId` 为该分类所属场景,`NULL`/悬空 id 会归一化为默认场景 id。
+`scenes`:按 `sortOrder, createdAt` 排序。`/api/public` **只含 `visibility = 'public'` 的场景**(私有场景整个空间对外不存在:场景、其下分类与链接都不出现);`/api/private` 返回全量场景。两者都包含「只有私有分类的公开场景」。分类的 `sceneId` 为该分类所属场景,`NULL`/悬空 id 会归一化为默认场景 id。
`wallpaperSource`:首页壁纸来源,`bing`(默认,Bing 每日壁纸)| `custom`(用 `backgroundUrl` 自定义图)。存量库无此键时按 `bing` 返回。
@@ -97,7 +115,7 @@
worker 端图标解析器:服务端读目标站 HTML 的 `` 声明、探测根文件,抓到后缓存并**直接回图字节**。无鉴权(公共页未登录也要显示图标)。前端在 `iconUrl` 非空时直接用它、不请求本端点;首字圆仍是最终兜底。
- 入参 `url`:必填,`encodeURIComponent` 后的绝对 URL(链接的 `url` 或搜索引擎 `urlTemplate` 去掉 `{q}`)。服务端只用它的 host 与 scheme,**不使用 path/query**。
- 缺失/非法(非 http/https、带账号密码、非默认端口、**内网/回环/保留地址**)→ `400 {"error":"url must be an absolute http(s) URL"}`,`Cache-Control: no-store` —— 这类目标在参数校验阶段就被拒,不进注册表。
-- **站点注册表**:host 必须已登记在本站数据里 —— 公开链接与搜索引擎的 host 匿名可取;链接的可见性取**更严一方**(私有链接、或私有分类下的 public 链接,都需要有效会话),否则按未登记处理。未登记 → `404 {"error":"icon not found"}`,`Cache-Control: public, max-age=3600`,**不发起任何外部请求**(本端点不是开放代理)。同一 host 有多条链接时注册表优先 https。
+- **站点注册表**:host 必须已登记在本站数据里 —— 公开链接与搜索引擎的 host 匿名可取;链接的可见性取**更严一方**(私有链接、或私有分类/私有场景下的 public 链接,都需要有效会话),否则按未登记处理。未登记 → `404 {"error":"icon not found"}`,`Cache-Control: public, max-age=3600`,**不发起任何外部请求**(本端点不是开放代理)。同一 host 有多条链接时注册表优先 https。
- **解析顺序**(全部限定在登记的 origin):`GET https://{host}/` 读 HTML 里 `rel` 含 `icon` / `apple-touch-icon` 的 ``(svg > png > ico,`sizes` 大者优先;相对路径按该 HTML 的真实地址解,含跟随重定向后的路径;声明落在其他 host 的一律忽略)→ 命中即取该图 → 否则依次探测 `/favicon.ico`、`/favicon.svg`、`/favicon.png`、`/apple-touch-icon.png` → 全失败记为「无图」。
- **出网约束**:只请求上述 origin 的根路径与固定根文件;`redirect: "manual"` 自己管重定向 —— **只跟随同一个 host 内的 3xx(最多 2 跳;允许 http→https 升级,禁止降级到 http)**,`Location` 落到别的 host(含子域、CDN)、非默认端口、带账号密码、解析失败或超出跳数,一律视为该候选失败(不扩大出网边界);单次 5s 超时、一次解析总预算 8s;HTML 读 256KB、图标读 512KB 上限;带 `user-agent: nav-favicon/1`。
- 成功 `200`:图标原始字节,`content-type` 为按魔数嗅探出的真实类型(`image/png` / `image/jpeg` / `image/webp` / `image/gif` / `image/svg+xml` / `image/x-icon`),`cache-control: public, max-age=86400`,`x-content-type-options: nosniff`;**不透传任何上游响应头**。
@@ -146,12 +164,14 @@ Passkey(WebAuthn,/api/auth/passkey/*,@simplewebauthn/server v14):
### 场景
-- `GET /api/admin/scenes` → `{scenes:[AdminSceneDto]}`(按 `sortOrder, createdAt` 排序,含默认场景)
-- `POST /api/admin/scenes` body `{name, icon?, sortOrder?}` → 201 `AdminSceneDto`
+- `GET /api/admin/scenes` → `{scenes:[AdminSceneDto]}`(按 `sortOrder, createdAt` 排序,含默认场景,每项带 `visibility`/`isDefault`)
+- `POST /api/admin/scenes` body `{name, icon?, sortOrder?, visibility?}` → 201 `AdminSceneDto`
- `name` 去空格后不可为空,否则 400 `{"error":"name is required"}`;`icon` 非字符串按 `null`;省略 `sortOrder` 时追加到末尾(现有 `MAX(sort_order)+1`)。
- - `isDefault` 只读,传入会被忽略;场景名不做库级唯一约束。
-- `PUT /api/admin/scenes/:id` body `{name?, icon?, sortOrder?}` → 更新后的 `AdminSceneDto`
+ - `visibility`:`public`(缺省)| `private`,其他值 → 400 `{"error":"visibility must be 'public' or 'private'"}`。
+ - `isDefault` 只读,传入会被忽略;场景名不做库级唯一约束。例外:`isDefault: true` 与 `visibility: 'private'` 同时出现 → 400 `{"error":"private scene cannot be set as default"}`(私有场景不得为默认)。
+- `PUT /api/admin/scenes/:id` body `{name?, icon?, sortOrder?, visibility?}` → 更新后的 `AdminSceneDto`
- `name` 去空格后不可为空,否则 400 `{"error":"name must not be empty"}`;`isDefault` 静默忽略;不存在 → 404 `{"error":"not found"}`。
+ - `visibility` 非法值 → 400 `visibility must be 'public' or 'private'`;当前是默认场景而目标 `private` → 400 `{"error":"default scene cannot be private"}`(须先移默认;被拒时整个更新不落库)。私有场景上请求 `isDefault: true` → 400 `private scene cannot be set as default`。
- `DELETE /api/admin/scenes/:id` → `{success:true}`
- 默认场景 → 400 `{"error":"default scene cannot be deleted"}`;不存在 → 404 `{"error":"not found"}`。
- 非默认场景:在**单个 `db.batch` 事务**里,先把该场景的全部分类移动到默认场景,`sort_order` 追加到默认场景现有分类之后(以默认场景内 `MAX(sort_order)+1` 为基数,保持分类相对顺序),再删除场景(SQL 层带 `is_default = 0` 守卫);链接随分类走,不搬不改。
diff --git a/worker/src/db/queries/content.ts b/worker/src/db/queries/content.ts
index 73c6985..9f8b97f 100644
--- a/worker/src/db/queries/content.ts
+++ b/worker/src/db/queries/content.ts
@@ -8,7 +8,13 @@ const CATEGORY_COLUMNS = [
"visibility",
"scene_id",
] as const;
-const SCENE_COLUMNS = ["name", "icon", "sort_order", "is_default"] as const;
+const SCENE_COLUMNS = [
+ "name",
+ "icon",
+ "sort_order",
+ "is_default",
+ "visibility",
+] as const;
const LINK_COLUMNS = [
"category_id",
"title",
@@ -327,13 +333,14 @@ export async function insertScene(
icon: string | null;
sort_order: number;
is_default: number;
+ visibility: string;
},
): Promise {
const now = nowIso();
await db
.prepare(
- `INSERT INTO ${prefix}scenes (id, name, icon, sort_order, is_default, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?)`,
+ `INSERT INTO ${prefix}scenes (id, name, icon, sort_order, is_default, visibility, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
)
.bind(
data.id,
@@ -341,6 +348,7 @@ export async function insertScene(
data.icon,
data.sort_order,
data.is_default,
+ data.visibility,
now,
now,
)
@@ -356,6 +364,7 @@ export async function updateScene(
icon: string | null;
sort_order: number;
is_default: number;
+ visibility: string;
}>,
): Promise {
assertColumns("updateScene", data as Record, SCENE_COLUMNS);
diff --git a/worker/src/lib/migrations.ts b/worker/src/lib/migrations.ts
index eef256e..d7b333f 100644
--- a/worker/src/lib/migrations.ts
+++ b/worker/src/lib/migrations.ts
@@ -47,7 +47,8 @@ export interface Migration {
* The migration list for a prefix. `schema_v1` is the whole nav v1 schema
* (tables, indexes and the `setup_completed` seed): nav v1 shipped without a
* ledger, so its history is collapsed into one baseline migration. `schema_v2`
- * adds the scene dimension (scenes table + `categories.scene_id`).
+ * adds the scene dimension (scenes table + `categories.scene_id`). `schema_v3`
+ * adds `scenes.visibility` (scene-level visibility, ANDed with the category's).
*/
export function getMigrations(prefix: string): Migration[] {
const t = (name: string) => `${prefix}${name}`;
@@ -194,6 +195,20 @@ CREATE INDEX IF NOT EXISTS ${idx("categories_scene_id")}
UPDATE ${t("categories")}
SET scene_id = (SELECT id FROM ${t("scenes")} WHERE is_default = 1 ORDER BY sort_order, created_at LIMIT 1)
WHERE scene_id IS NULL;
+`,
+ },
+ {
+ // Scene-level visibility (nav #19 B1/B3): `public` | `private`, the same
+ // vocabulary the category uses. Existing rows take the DEFAULT 'public',
+ // so the default scene (and every other pre-existing scene) stays public
+ // after the upgrade — the「default scene must be public」invariant holds
+ // for existing data without a backfill.
+ // Same replay rule as schema_v2's `ALTER TABLE categories ADD COLUMN`:
+ // SQLite has no `ADD COLUMN IF NOT EXISTS`, so safety comes from the
+ // ledger (a recorded migration is skipped, the ALTER never runs twice).
+ name: "schema_v3",
+ sql: `
+ALTER TABLE ${t("scenes")} ADD COLUMN visibility TEXT NOT NULL DEFAULT 'public' CHECK (visibility IN ('public', 'private'));
`,
},
];
diff --git a/worker/src/routes/admin.ts b/worker/src/routes/admin.ts
index 8957cba..5eaf681 100644
--- a/worker/src/routes/admin.ts
+++ b/worker/src/routes/admin.ts
@@ -79,6 +79,11 @@ function parseSortOrder(value: unknown, fallback: number): number {
return Number.isFinite(n) ? n : fallback;
}
+/** 「请求把该场景设为默认」的既有载荷口径(`true` 或 `1`;其余一律忽略)。 */
+function wantsDefault(value: unknown): boolean {
+ return value === true || value === 1;
+}
+
// ─── Categories ──────────────────────────────────────────────────────────────
/** Admin category DTO: full row plus the normalised `sceneId`. */
@@ -261,6 +266,18 @@ adminRoutes.post("/scenes", async (c) => {
const name = typeof body.name === "string" ? body.name.trim() : "";
if (!name) return badRequest("name is required");
+ // 场景可见性(nav #19 B3):创建接收 `visibility`,缺省 public,非法值 400。
+ if (body.visibility !== undefined && !isVisibility(body.visibility))
+ return badRequest("visibility must be 'public' or 'private'");
+ const visibility: Visibility = isVisibility(body.visibility)
+ ? body.visibility
+ : "public";
+
+ // B2 ①:私有场景不得被设为默认。`isDefault` 本身仍只读(#17 冻结:公开场景
+ // 传了照旧静默忽略),但「把私有场景设成默认」这个请求直接 400。
+ if (wantsDefault(body.isDefault) && visibility === "private")
+ return badRequest("private scene cannot be set as default");
+
const id = generateId();
const sortOrder = parseSortOrder(
body.sortOrder,
@@ -274,6 +291,7 @@ adminRoutes.post("/scenes", async (c) => {
icon: typeof body.icon === "string" ? body.icon : null,
sort_order: sortOrder,
is_default: 0,
+ visibility,
});
const created = await findScene(c.env.DB, prefix, id);
@@ -301,6 +319,22 @@ adminRoutes.put("/scenes/:id", async (c) => {
data.sort_order = parseSortOrder(body.sortOrder, existing.sort_order);
// `isDefault` is read-only — silently ignored, exactly as frozen in #16.
+ // 场景可见性(nav #19 B2/B3):非法值 400,缺省保持原值。
+ let visibility: Visibility = existing.visibility;
+ if (body.visibility !== undefined) {
+ if (!isVisibility(body.visibility))
+ return badRequest("visibility must be 'public' or 'private'");
+ visibility = body.visibility;
+ }
+ // B2 ②:默认场景不得改为私有 —— 须先把默认移走(#17 契约不提供转移默认的
+ // 接口,所以现有 API 上就是「默认场景只能是公开的」)。
+ if (existing.is_default === 1 && visibility === "private")
+ return badRequest("default scene cannot be private");
+ // B2 ①:私有场景不得被设为默认。
+ if (wantsDefault(body.isDefault) && visibility === "private")
+ return badRequest("private scene cannot be set as default");
+ if (body.visibility !== undefined) data.visibility = visibility;
+
await updateScene(c.env.DB, prefix, id, data);
const updated = await findScene(c.env.DB, prefix, id);
if (!updated) return c.json({ error: "not found" }, 404);
diff --git a/worker/src/routes/public.ts b/worker/src/routes/public.ts
index 1245a48..47c2e85 100644
--- a/worker/src/routes/public.ts
+++ b/worker/src/routes/public.ts
@@ -13,9 +13,11 @@ import { ensureSchema } from "../lib/migrate";
export const publicRoutes = new Hono();
/**
- * GET /api/public — public categories + public links, search engines, site
- * settings. Private rows are never fetched into this payload, so a private
- * category/link cannot leak here (SPEC §2). Publicly cacheable.
+ * GET /api/public — public scenes + public categories + public links, search
+ * engines, site settings. Private rows are never delivered, and a private scene
+ * makes its whole space (scene, categories, links) disappear for anonymous
+ * visitors (nav #19 B1/B3: visibility = scene public AND category public).
+ * Publicly cacheable.
*/
publicRoutes.get("/", async (c) => {
const prefix = getTablePrefix(c.env);
@@ -28,21 +30,12 @@ publicRoutes.get("/", async (c) => {
listScenes(c.env.DB, prefix),
]);
- // Visibility = stricter of category and link: drop public links that live in
- // a private category before assembling the DTO (SPEC §2).
- const privateCategoryIds = new Set(
- categories
- .filter((cat) => cat.visibility === "private")
- .map((cat) => cat.id),
- );
- const publicLinks = links.filter(
- (link) =>
- link.visibility === "public" && !privateCategoryIds.has(link.category_id),
- );
-
+ // 两层取与(场景公开 AND 分类公开)全部由 buildSiteData 收敛:它拿到全量行,
+ // 在输出前把私有场景整个空间(场景/分类/链接)裁掉。这里不预先过滤场景,
+ // 否则「属于私有场景」与「属于默认场景」就分不清了。
const data: SiteDataDto = buildSiteData(
- categories.filter((cat) => cat.visibility === "public"),
- publicLinks,
+ categories,
+ links,
engines,
settings,
scenes,
diff --git a/worker/src/services/favicon.ts b/worker/src/services/favicon.ts
index 6c0454a..3cfa2b5 100644
--- a/worker/src/services/favicon.ts
+++ b/worker/src/services/favicon.ts
@@ -15,8 +15,10 @@ import type { Env } from "../types";
import {
listCategories,
listLinks,
+ listScenes,
listSearchEngines,
} from "../db/queries/content";
+import { publicCategories } from "./site-data";
import {
detectBinaryImageKind,
isSvgDocument,
@@ -590,20 +592,29 @@ export async function loadIconRegistry(
listSearchEngines(env.DB, prefix),
listLinks(env.DB, prefix),
]);
- const privateCategoryIds = new Set(
- categories
- .filter((category) => category.visibility === "private")
- .map((category) => category.id),
+ // 场景维度可能还没迁移(库停在 schema_v1,或 Worker 先于库升级):这时没有
+ // `scenes` 表,`listScenes` 会抛 `no such table`。不能让它把整段查询一起拖
+ // 下水——那会让一次未迁移的读把全部公开 host 变成「未登记」。降级为引入场景
+ // 维度之前的口径:只看分类自身 visibility。
+ const scenes = await listScenes(env.DB, prefix).catch(() => null);
+ // 匿名视角的可见分类 = 场景公开 AND 分类公开(两层取与,与 /api/public
+ // 同一口径):私有场景整个空间对匿名不存在,其下链接的 host 也不算登记。
+ const visibleCategoryIds = new Set(
+ (scenes === null
+ ? categories.filter((category) => category.visibility === "public")
+ : publicCategories(categories, scenes)
+ ).map((category) => category.id),
);
for (const engine of engines) {
add(engine.url_template.replace("{q}", ""));
}
for (const link of links) {
- // 可见性取更严一方:私有分类下的 public 链接同样不算公开(与 /api/public 一致)。
+ // 可见性取更严一方:私有分类下的 public 链接、私有场景下的链接同样不算
+ // 公开(与 /api/public 一致)。
if (!options.includePrivate) {
if (link.visibility !== "public") continue;
- if (privateCategoryIds.has(link.category_id)) continue;
+ if (!visibleCategoryIds.has(link.category_id)) continue;
}
add(link.url);
}
diff --git a/worker/src/services/site-data.ts b/worker/src/services/site-data.ts
index 7cb4758..8a4fa7b 100644
--- a/worker/src/services/site-data.ts
+++ b/worker/src/services/site-data.ts
@@ -55,6 +55,15 @@ export function toSiteSettingsDto(
};
}
+/**
+ * Assembles the public/private site data payload.
+ *
+ * `scenes` must be the **full** scene list (never pre-filtered): the two-layer
+ * visibility rule below needs the private scenes to tell 「belongs to a private
+ * scene」 apart from 「belongs to the default scene」. The caller passes raw rows
+ * and this function is the single place where scene/category/link visibility is
+ * enforced for both surfaces.
+ */
export function buildSiteData(
categories: Category[],
links: Link[],
@@ -63,6 +72,12 @@ export function buildSiteData(
scenes: Scene[],
opts: { includePrivate: boolean },
): SiteDataDto {
+ // 两层取与(nav #19 B1):有效可见性 = 场景公开 AND 分类公开。私有场景整个
+ // 空间对外不存在——场景本身与它下面的全部分类(无论分类自身标记)都不进入
+ // 未登录数据;分类自身 visibility 保留不动,不做级联改写。登录视角全量可见。
+ const visibleScenes = opts.includePrivate ? scenes : publicScenes(scenes);
+ const visibleSceneIds = new Set(visibleScenes.map((scene) => scene.id));
+
const linksByCategory = new Map();
for (const link of links) {
const bucket = linksByCategory.get(link.category_id) ?? [];
@@ -77,6 +92,13 @@ export function buildSiteData(
for (const category of categories) {
const categoryPrivate = category.visibility === "private";
if (categoryPrivate && !opts.includePrivate) continue;
+ // 所属场景在未登录视角不可见(私有场景)→ 该分类整条不出现,链接随分类。
+ if (
+ !opts.includePrivate &&
+ !visibleSceneIds.has(normalizeSceneId(category.scene_id, scenes))
+ ) {
+ continue;
+ }
const visibleLinks = (linksByCategory.get(category.id) ?? []).filter(
(link) => {
@@ -102,7 +124,7 @@ export function buildSiteData(
return {
categories: dtoCategories,
- scenes: scenes.map(toSceneDto),
+ scenes: visibleScenes.map(toSceneDto),
searchEngines: engines.map(toSearchEngineDto),
settings: toSiteSettingsDto(settings),
};
@@ -110,6 +132,37 @@ export function buildSiteData(
// ─── Scenes ──────────────────────────────────────────────────────────────────
+/**
+ * 未登录视角下某个场景是否可见:只有 `visibility = 'public'` 的场景存在。
+ * 库/行上缺值(更早的库或手写行)按公开处理——与列的 `DEFAULT 'public'` 同口径。
+ */
+function isPublicScene(scene: Scene): boolean {
+ return scene.visibility !== "private";
+}
+
+/** 未登录视角可见的场景(保持原有 sort_order, created_at 顺序)。 */
+function publicScenes(scenes: Scene[]): Scene[] {
+ return scenes.filter(isPublicScene);
+}
+
+/**
+ * 未登录视角可见的分类:场景公开 AND 分类公开(两层取与)。私有场景下的分类
+ * 无论自身标记都不出现;NULL/悬空 scene_id 先归一化为默认场景再判可见性。
+ */
+export function publicCategories(
+ categories: Category[],
+ scenes: Scene[],
+): Category[] {
+ const visibleSceneIds = new Set(
+ publicScenes(scenes).map((scene) => scene.id),
+ );
+ return categories.filter(
+ (category) =>
+ category.visibility === "public" &&
+ visibleSceneIds.has(normalizeSceneId(category.scene_id, scenes)),
+ );
+}
+
export function toSceneDto(scene: Scene): SceneDto {
return {
id: scene.id,
@@ -117,6 +170,7 @@ export function toSceneDto(scene: Scene): SceneDto {
icon: scene.icon,
sortOrder: scene.sort_order,
isDefault: scene.is_default === 1,
+ visibility: scene.visibility === "private" ? "private" : "public",
};
}
diff --git a/worker/src/types.ts b/worker/src/types.ts
index 2893fdc..357d4ca 100644
--- a/worker/src/types.ts
+++ b/worker/src/types.ts
@@ -94,6 +94,11 @@ export interface Scene {
icon: string | null;
sort_order: number;
is_default: number;
+ /**
+ * Scene-level visibility (schema_v3). ANDed with the category's own flag: a
+ * private scene makes its whole space invisible to anonymous visitors.
+ */
+ visibility: "public" | "private";
created_at: string;
updated_at: string;
}
@@ -143,6 +148,11 @@ export interface SceneDto {
icon: string | null;
sortOrder: number;
isDefault: boolean;
+ /**
+ * `public` | `private` (schema_v3). The public surface only ever carries
+ * public scenes (a private scene does not exist for anonymous visitors).
+ */
+ visibility: Visibility;
}
/** `GET/POST/PUT /api/admin/scenes` — SceneDto plus timestamps. */
@@ -196,9 +206,10 @@ export interface SiteSettingsDto {
export interface SiteDataDto {
categories: PublicCategoryDto[];
/**
- * Every scene, ordered by sort_order, created_at — including scenes whose
- * only categories are private. The server never filters by scene; clients
- * filter locally.
+ * Ordered by sort_order, created_at. `/api/private` returns every scene;
+ * `/api/public` returns only `visibility = 'public'` scenes (a private scene
+ * and everything under it is invisible to anonymous visitors). Scenes whose
+ * only categories are private are still public scenes and stay listed.
*/
scenes: SceneDto[];
searchEngines: SearchEngineDto[];
diff --git a/worker/test/admin-upgrade.test.ts b/worker/test/admin-upgrade.test.ts
index 661ebd2..5289507 100644
--- a/worker/test/admin-upgrade.test.ts
+++ b/worker/test/admin-upgrade.test.ts
@@ -68,13 +68,13 @@ describe("admin upgrade path (schema_v1-only database)", () => {
expect.objectContaining({ id: "legacy-cat", sceneId: "scene_default" }),
]);
- // The guard applied schema_v2 and backfilled the legacy row.
+ // The guard applied schema_v2 (+ schema_v3) and backfilled the legacy row.
expect(
db
.prepare(`SELECT name FROM ${migrationsTable("")} ORDER BY rowid`)
.all()
.map((row: { name: string }) => row.name),
- ).toEqual(["schema_v1", "schema_v2"]);
+ ).toEqual(["schema_v1", "schema_v2", "schema_v3"]);
expect(
db
.prepare("SELECT scene_id FROM categories WHERE id = 'legacy-cat'")
diff --git a/worker/test/auth.test.ts b/worker/test/auth.test.ts
index b641706..21c12fa 100644
--- a/worker/test/auth.test.ts
+++ b/worker/test/auth.test.ts
@@ -223,6 +223,7 @@ describe("setup response (ledgered migrations)", () => {
expect(body.migrations).toEqual([
{ name: "schema_v1", status: "applied" },
{ name: "schema_v2", status: "applied" },
+ { name: "schema_v3", status: "applied" },
]);
});
diff --git a/worker/test/favicon.test.ts b/worker/test/favicon.test.ts
index c4ef79e..f9b74cf 100644
--- a/worker/test/favicon.test.ts
+++ b/worker/test/favicon.test.ts
@@ -1,6 +1,10 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { Hono } from "hono";
-import { runMigrations } from "../src/lib/migrations-runner";
+import {
+ applyMigrationList,
+ runMigrations,
+} from "../src/lib/migrations-runner";
+import { getMigrations } from "../src/lib/migrations";
import { assetPublicRoutes } from "../src/routes/assets";
import { iconRoutes } from "../src/routes/icon";
import {
@@ -391,6 +395,82 @@ describe("loadIconRegistry", () => {
});
});
+ it("私有场景下的链接对匿名不算登记(两层取与)", async () => {
+ const now = new Date().toISOString();
+ sql(env)
+ .prepare(
+ "INSERT INTO scenes (id, name, icon, sort_order, is_default, visibility, created_at, updated_at) VALUES ('scene_secret', '秘密', NULL, 9, 0, 'private', ?, ?)",
+ )
+ .run(now, now);
+ sql(env)
+ .prepare(
+ "INSERT INTO categories (id, name, icon, sort_order, visibility, scene_id, created_at, updated_at) VALUES ('cat-secret', '秘密分类', NULL, 0, 'public', 'scene_secret', ?, ?)",
+ )
+ .run(now, now);
+ sql(env)
+ .prepare(
+ "INSERT INTO links (id, category_id, title, url, icon_url, description, sort_order, visibility, created_at, updated_at) VALUES ('l-secret', 'cat-secret', 't', 'https://hidden-scene.example/', NULL, NULL, 0, 'public', ?, ?)",
+ )
+ .run(now, now);
+
+ const anonymous = await loadIconRegistry(env, getTablePrefix(env), {
+ includePrivate: false,
+ });
+ expect(anonymous.has("hidden-scene.example")).toBe(false);
+
+ const authed = await loadIconRegistry(env, getTablePrefix(env), {
+ includePrivate: true,
+ });
+ expect(authed.get("hidden-scene.example")).toEqual({
+ origin: "https://hidden-scene.example",
+ });
+ });
+
+ it("库停在 schema_v1(没有 scenes 表)时仍按旧的分类口径登记公开 host", async () => {
+ // Worker 先于库升级时数据库可能还停在 schema_v1:没有 scenes 表,也没有
+ // categories.scene_id。此时必须退化为「只看分类 visibility」,不能因为
+ // listScenes 抛错就把整张注册表清空(全部公开 host 变成 404)。
+ const legacy = makeEnv();
+ const v1 = getMigrations("")[0];
+ if (!v1) throw new Error("schema_v1 missing");
+ await applyMigrationList(legacy.DB, "", [v1]);
+
+ const now = new Date().toISOString();
+ sql(legacy)
+ .prepare(
+ "INSERT INTO categories (id, name, icon, sort_order, visibility, created_at, updated_at) VALUES ('cat-v1', 'v1', NULL, 0, 'public', ?, ?)",
+ )
+ .run(now, now);
+ sql(legacy)
+ .prepare(
+ "INSERT INTO categories (id, name, icon, sort_order, visibility, created_at, updated_at) VALUES ('cat-v1-private', 'v1p', NULL, 1, 'private', ?, ?)",
+ )
+ .run(now, now);
+ sql(legacy)
+ .prepare(
+ "INSERT INTO links (id, category_id, title, url, icon_url, description, sort_order, visibility, created_at, updated_at) VALUES ('l-v1', 'cat-v1', 't', 'https://legacy.example/', NULL, NULL, 0, 'public', ?, ?)",
+ )
+ .run(now, now);
+ sql(legacy)
+ .prepare(
+ "INSERT INTO links (id, category_id, title, url, icon_url, description, sort_order, visibility, created_at, updated_at) VALUES ('l-v1-hidden', 'cat-v1-private', 't', 'https://hidden-v1.example/', NULL, NULL, 0, 'public', ?, ?)",
+ )
+ .run(now, now);
+
+ const registry = await loadIconRegistry(legacy, getTablePrefix(legacy), {
+ includePrivate: false,
+ });
+ expect([...registry.keys()]).toEqual(["legacy.example"]);
+
+ const authed = await loadIconRegistry(legacy, getTablePrefix(legacy), {
+ includePrivate: true,
+ });
+ expect([...authed.keys()].sort()).toEqual([
+ "hidden-v1.example",
+ "legacy.example",
+ ]);
+ });
+
it("库还没初始化时退化为空注册表(不抛)", async () => {
const fresh = makeEnv();
const registry = await loadIconRegistry(fresh, getTablePrefix(fresh), {
diff --git a/worker/test/migrate.test.ts b/worker/test/migrate.test.ts
index dfe6097..2799d75 100644
--- a/worker/test/migrate.test.ts
+++ b/worker/test/migrate.test.ts
@@ -9,6 +9,7 @@ describe("D1 migration", () => {
expect(result.migrations).toEqual([
{ name: "schema_v1", status: "applied" },
{ name: "schema_v2", status: "applied" },
+ { name: "schema_v3", status: "applied" },
]);
const db = (env.DB as unknown as SqliteD1).db;
@@ -43,6 +44,7 @@ describe("D1 migration", () => {
migrations: [
{ name: "schema_v1", status: "skipped" },
{ name: "schema_v2", status: "skipped" },
+ { name: "schema_v3", status: "skipped" },
],
});
await expect(runMigrations(env)).resolves.toEqual({
@@ -50,6 +52,7 @@ describe("D1 migration", () => {
migrations: [
{ name: "schema_v1", status: "skipped" },
{ name: "schema_v2", status: "skipped" },
+ { name: "schema_v3", status: "skipped" },
],
});
});
diff --git a/worker/test/migrations-ledger.test.ts b/worker/test/migrations-ledger.test.ts
index 0df7665..71f409a 100644
--- a/worker/test/migrations-ledger.test.ts
+++ b/worker/test/migrations-ledger.test.ts
@@ -54,10 +54,15 @@ describe("ledgered migration runner", () => {
expect(result.migrations.map((m) => [m.name, m.status])).toEqual([
["schema_v1", "applied"],
["schema_v2", "applied"],
+ ["schema_v3", "applied"],
]);
const ledger = ledgerRows(env.DB, "nav_");
- expect(ledger.map((row) => row.name)).toEqual(["schema_v1", "schema_v2"]);
+ expect(ledger.map((row) => row.name)).toEqual([
+ "schema_v1",
+ "schema_v2",
+ "schema_v3",
+ ]);
expect(ledger[0]?.applied_at).toBeGreaterThan(0);
const tables = tableNames(env.DB);
@@ -94,6 +99,7 @@ describe("ledgered migration runner", () => {
expect(second.migrations).toEqual([
{ name: "schema_v1", status: "skipped" },
{ name: "schema_v2", status: "skipped" },
+ { name: "schema_v3", status: "skipped" },
]);
expect(tableNames(env.DB)).toEqual(schemaBefore);
@@ -116,6 +122,7 @@ describe("ledgered migration runner", () => {
expect(ledgerRows(env.DB, "").map((row) => row.name)).toEqual([
"schema_v1",
"schema_v2",
+ "schema_v3",
]);
});
@@ -133,10 +140,12 @@ describe("ledgered migration runner", () => {
expect(result.migrations).toEqual([
{ name: "schema_v1", status: "applied" },
{ name: "schema_v2", status: "applied" },
+ { name: "schema_v3", status: "applied" },
]);
expect(ledgerRows(env.DB, "nav_").map((row) => row.name)).toEqual([
"schema_v1",
"schema_v2",
+ "schema_v3",
]);
expect(tableNames(env.DB)).toContain("_nav_schema_migrations");
expect(tableNames(env.DB)).toContain("nav_scenes");
@@ -185,10 +194,12 @@ describe("ledgered migration runner", () => {
const result = await runMigrations(env);
expect(result.prefix).toBe("nav_");
- expect(result.migrations).toEqual([
- { name: "schema_v1", status: "applied" },
- { name: "schema_v2", status: "applied" },
+ expect(result.migrations.map((m) => m.name)).toEqual([
+ "schema_v1",
+ "schema_v2",
+ "schema_v3",
]);
+ expect(result.migrations.every((m) => m.status === "applied")).toBe(true);
});
it("stops at the first failing migration, without recording it or running later ones", async () => {
diff --git a/worker/test/scenes.test.ts b/worker/test/scenes.test.ts
index 3334ccf..f06e86f 100644
--- a/worker/test/scenes.test.ts
+++ b/worker/test/scenes.test.ts
@@ -9,7 +9,8 @@ import { publicRoutes } from "../src/routes/public";
import { privateRoutes } from "../src/routes/private";
import { adminRoutes } from "../src/routes/admin";
import { authRoutes } from "../src/routes/auth";
-import type { Env } from "../src/types";
+import { buildSiteData } from "../src/services/site-data";
+import type { Category, Env, Scene } from "../src/types";
import { makeEnv, readJson, type SqliteD1 } from "./helpers";
const SETUP_SECRET = "test-setup-secret";
@@ -77,19 +78,23 @@ function insertSceneRow(
scene: {
id: string;
name: string;
+ icon?: string | null;
sortOrder: number;
isDefault?: boolean;
+ visibility?: "public" | "private";
},
): void {
sqliteOf(env)
.prepare(
- "INSERT INTO scenes (id, name, icon, sort_order, is_default, created_at, updated_at) VALUES (?, ?, NULL, ?, ?, ?, ?)",
+ "INSERT INTO scenes (id, name, icon, sort_order, is_default, visibility, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
)
.run(
scene.id,
scene.name,
+ scene.icon ?? null,
scene.sortOrder,
scene.isDefault ? 1 : 0,
+ scene.visibility ?? "public",
NOW,
NOW,
);
@@ -161,6 +166,7 @@ describe("schema_v2 migration (scenes)", () => {
expect(result.migrations).toEqual([
{ name: "schema_v1", status: "skipped" },
{ name: "schema_v2", status: "applied" },
+ { name: "schema_v3", status: "applied" },
]);
const scenes = sqliteOf(env).prepare("SELECT * FROM scenes").all() as Array<
@@ -228,6 +234,87 @@ describe("schema_v2 migration (scenes)", () => {
});
});
+describe("schema_v3 migration (scene visibility)", () => {
+ it("adds scenes.visibility with a public default and backfills existing rows", async () => {
+ const env = makeEnv();
+ // A schema_v2 database: v1 + v2 applied, scenes exist, no visibility column.
+ const [v1, v2] = getMigrations("");
+ if (!v1 || !v2) throw new Error("schema_v1/v2 missing");
+ await applyMigrationList(env.DB, "", [v1, v2]);
+ // schema_v2-era row: the table has no visibility column yet.
+ sqliteOf(env)
+ .prepare(
+ "INSERT INTO scenes (id, name, icon, sort_order, is_default, created_at, updated_at) VALUES ('old-work', '旧场景', NULL, 1, 0, ?, ?)",
+ )
+ .run(NOW, NOW);
+
+ const result = await runMigrations(env);
+ expect(result.migrations).toEqual([
+ { name: "schema_v1", status: "skipped" },
+ { name: "schema_v2", status: "skipped" },
+ { name: "schema_v3", status: "applied" },
+ ]);
+
+ // Every pre-existing row — including the seeded default scene — is public.
+ expect(
+ sqliteOf(env)
+ .prepare("SELECT id, visibility FROM scenes ORDER BY id")
+ .all(),
+ ).toEqual([
+ { id: "old-work", visibility: "public" },
+ { id: "scene_default", visibility: "public" },
+ ]);
+
+ // New rows fall back to the column default too.
+ insertSceneRow(env, { id: "fresh", name: "新场景", sortOrder: 2 });
+ expect(
+ sqliteOf(env)
+ .prepare("SELECT visibility FROM scenes WHERE id = 'fresh'")
+ .get(),
+ ).toEqual({ visibility: "public" });
+ });
+
+ it("enforces the public/private domain at the database level", async () => {
+ const env = makeEnv();
+ await runMigrations(env);
+ expect(() =>
+ sqliteOf(env)
+ .prepare(
+ "INSERT INTO scenes (id, name, icon, sort_order, is_default, visibility, created_at, updated_at) VALUES ('bad', 'x', NULL, 1, 0, 'hidden', ?, ?)",
+ )
+ .run(NOW, NOW),
+ ).toThrow();
+ });
+
+ it("is replay-safe and keeps the TABLE_PREFIX three-state naming", async () => {
+ const env = makeEnv({ TABLE_PREFIX: "nav_" });
+ await runMigrations(env);
+ // Ledger replay: the ALTER is not attempted twice.
+ await expect(runMigrations(env)).resolves.toEqual({
+ prefix: "nav_",
+ migrations: [
+ { name: "schema_v1", status: "skipped" },
+ { name: "schema_v2", status: "skipped" },
+ { name: "schema_v3", status: "skipped" },
+ ],
+ });
+ expect(
+ sqliteOf(env)
+ .prepare("SELECT visibility FROM nav_scenes WHERE id = 'scene_default'")
+ .get(),
+ ).toEqual({ visibility: "public" });
+
+ // Explicitly empty prefix builds the same column with no prefix at all.
+ const bare = makeEnv({ TABLE_PREFIX: "" });
+ await runMigrations(bare);
+ expect(
+ sqliteOf(bare)
+ .prepare("SELECT visibility FROM scenes WHERE id = 'scene_default'")
+ .get(),
+ ).toEqual({ visibility: "public" });
+ });
+});
+
describe("site data DTOs carry scenes + category sceneId", () => {
let env: Env;
let app: Hono;
@@ -303,6 +390,7 @@ describe("site data DTOs carry scenes + category sceneId", () => {
icon: null,
sortOrder: 0,
isDefault: true,
+ visibility: "public",
},
{
id: "scene_work",
@@ -310,6 +398,7 @@ describe("site data DTOs carry scenes + category sceneId", () => {
icon: null,
sortOrder: 1,
isDefault: false,
+ visibility: "public",
},
{
id: "scene_private",
@@ -317,6 +406,7 @@ describe("site data DTOs carry scenes + category sceneId", () => {
icon: null,
sortOrder: 2,
isDefault: false,
+ visibility: "public",
},
]);
@@ -372,6 +462,145 @@ describe("site data DTOs carry scenes + category sceneId", () => {
});
});
+describe("scene visibility: private scene space is invisible when logged out", () => {
+ let env: Env;
+ let app: Hono;
+ let cookie: string;
+
+ beforeEach(async () => {
+ env = makeEnv();
+ app = makeApp();
+ await runMigrations(env);
+ cookie = await ownerCookie(app, env);
+
+ insertSceneRow(env, {
+ id: "scene_open",
+ name: "公开场景",
+ sortOrder: 1,
+ });
+ insertSceneRow(env, {
+ id: "scene_secret",
+ name: "秘密场景",
+ icon: "secret-icon.svg",
+ sortOrder: 2,
+ visibility: "private",
+ });
+
+ // 公开场景:公开分类 + 私有分类(继续按分类自身 visibility 过滤)
+ insertCategoryRow(env, {
+ id: "cat-open",
+ name: "公开分类",
+ sortOrder: 0,
+ sceneId: "scene_open",
+ });
+ insertCategoryRow(env, {
+ id: "cat-open-private",
+ name: "公开场景里的私有分类",
+ sortOrder: 1,
+ sceneId: "scene_open",
+ visibility: "private",
+ });
+ // 私有场景:无论分类自身标记,整条都不外露
+ insertCategoryRow(env, {
+ id: "cat-secret-public",
+ name: "私有场景里的公开分类",
+ sortOrder: 0,
+ sceneId: "scene_secret",
+ });
+ insertCategoryRow(env, {
+ id: "cat-secret-private",
+ name: "私有场景里的私有分类",
+ sortOrder: 1,
+ sceneId: "scene_secret",
+ visibility: "private",
+ });
+
+ insertLinkRow(env, { id: "link-open", categoryId: "cat-open" });
+ insertLinkRow(env, { id: "link-secret", categoryId: "cat-secret-public" });
+ insertLinkRow(env, {
+ id: "link-secret-private",
+ categoryId: "cat-secret-private",
+ visibility: "private",
+ });
+ });
+
+ it("GET /api/public drops the private scene, its categories and their links", async () => {
+ const res = await app.request("/api/public", {}, env);
+ expect(res.status).toBe(200);
+ const body = await readJson(res);
+ const raw = JSON.stringify(body);
+
+ // 场景出口只剩公开场景,且带 visibility: public
+ expect(body.scenes.map((scene: { id: string }) => scene.id)).toEqual([
+ "scene_default",
+ "scene_open",
+ ]);
+ expect(body.scenes[1]).toEqual({
+ id: "scene_open",
+ name: "公开场景",
+ icon: null,
+ sortOrder: 1,
+ isDefault: false,
+ visibility: "public",
+ });
+
+ // 分类:私有场景下的分类(含公开标记)与公开场景里的私有分类都不出现
+ expect(body.categories.map((cat: { id: string }) => cat.id)).toEqual([
+ "cat-open",
+ ]);
+ expect(
+ body.categories[0].links.map((link: { id: string }) => link.id),
+ ).toEqual(["link-open"]);
+
+ // 私有场景的任何字段(名称/图标/id)都不得出现
+ expect(raw).not.toContain("秘密场景");
+ expect(raw).not.toContain("secret-icon");
+ expect(raw).not.toContain("scene_secret");
+ expect(raw).not.toContain("私有场景里的公开分类");
+ expect(raw).not.toContain("link-secret");
+ });
+
+ it("GET /api/private keeps everything and reports each scene's visibility", async () => {
+ const res = await app.request("/api/private", { headers: { cookie } }, env);
+ const body = await readJson(res);
+ expect(
+ body.scenes.map((scene: { id: string; visibility: string }) => [
+ scene.id,
+ scene.visibility,
+ ]),
+ ).toEqual([
+ ["scene_default", "public"],
+ ["scene_open", "public"],
+ ["scene_secret", "private"],
+ ]);
+ expect(body.categories.map((cat: { id: string }) => cat.id)).toEqual([
+ "cat-open",
+ "cat-secret-public",
+ "cat-open-private",
+ "cat-secret-private",
+ ]);
+ });
+
+ it("admin GET /api/admin/scenes exposes visibility + isDefault", async () => {
+ const body = await readJson(
+ await adminRequest(app, env, cookie, "/api/admin/scenes"),
+ );
+ expect(
+ body.scenes.map(
+ (scene: { id: string; visibility: string; isDefault: boolean }) => [
+ scene.id,
+ scene.visibility,
+ scene.isDefault,
+ ],
+ ),
+ ).toEqual([
+ ["scene_default", "public", true],
+ ["scene_open", "public", false],
+ ["scene_secret", "private", false],
+ ]);
+ });
+});
+
describe("admin scenes CRUD", () => {
let env: Env;
let app: Hono;
@@ -890,6 +1119,325 @@ describe("admin categories accept sceneId (incl. moving a category)", () => {
});
});
+describe("buildSiteData enforces the scene layer itself", () => {
+ function scene(over: Partial & { id: string }): Scene {
+ return {
+ name: over.id,
+ icon: null,
+ sort_order: 0,
+ is_default: 0,
+ visibility: "public",
+ created_at: NOW,
+ updated_at: NOW,
+ ...over,
+ };
+ }
+
+ function category(over: Partial & { id: string }): Category {
+ return {
+ name: over.id,
+ icon: null,
+ sort_order: 0,
+ visibility: "public",
+ scene_id: "scene_default",
+ created_at: NOW,
+ updated_at: NOW,
+ ...over,
+ };
+ }
+
+ it("drops a private scene's categories even when handed raw rows", () => {
+ const scenes = [
+ scene({ id: "scene_default", is_default: 1 }),
+ scene({ id: "scene_secret", visibility: "private" }),
+ ];
+ const categories = [
+ category({ id: "cat-open" }),
+ category({ id: "cat-secret", scene_id: "scene_secret" }),
+ category({
+ id: "cat-secret-private",
+ scene_id: "scene_secret",
+ visibility: "private",
+ }),
+ ];
+
+ const anonymous = buildSiteData(categories, [], [], {}, scenes, {
+ includePrivate: false,
+ });
+ expect(anonymous.categories.map((row) => row.id)).toEqual(["cat-open"]);
+ expect(anonymous.scenes.map((row) => row.id)).toEqual(["scene_default"]);
+ expect(JSON.stringify(anonymous)).not.toContain("scene_secret");
+
+ // 登录视角不做任何裁剪。
+ const full = buildSiteData(categories, [], [], {}, scenes, {
+ includePrivate: true,
+ });
+ expect(full.categories.map((row) => row.id)).toEqual([
+ "cat-open",
+ "cat-secret",
+ "cat-secret-private",
+ ]);
+ expect(full.scenes.map((row) => row.id)).toEqual([
+ "scene_default",
+ "scene_secret",
+ ]);
+ });
+
+ it("keeps normalising NULL/dangling scene ids to the default scene", () => {
+ const scenes = [scene({ id: "scene_default", is_default: 1 })];
+ const categories = [
+ category({ id: "cat-null", scene_id: null }),
+ category({ id: "cat-dangling", scene_id: "ghost" }),
+ ];
+
+ const data = buildSiteData(categories, [], [], {}, scenes, {
+ includePrivate: false,
+ });
+ expect(data.categories.map((row) => [row.id, row.sceneId])).toEqual([
+ ["cat-null", "scene_default"],
+ ["cat-dangling", "scene_default"],
+ ]);
+ });
+});
+
+describe("admin scene visibility + default-scene guards (B2)", () => {
+ let env: Env;
+ let app: Hono;
+ let cookie: string;
+
+ beforeEach(async () => {
+ env = makeEnv();
+ app = makeApp();
+ await runMigrations(env);
+ cookie = await ownerCookie(app, env);
+ });
+
+ function sceneRow(id: string): { visibility: string; is_default: number } {
+ return sqliteOf(env)
+ .prepare("SELECT visibility, is_default FROM scenes WHERE id = ?")
+ .get(id) as { visibility: string; is_default: number };
+ }
+
+ it("POST defaults visibility to public and accepts private", async () => {
+ const plain = await adminRequest(app, env, cookie, "/api/admin/scenes", {
+ method: "POST",
+ body: { name: "无标记" },
+ });
+ expect(plain.status).toBe(201);
+ expect(await readJson(plain)).toMatchObject({ visibility: "public" });
+
+ const priv = await adminRequest(app, env, cookie, "/api/admin/scenes", {
+ method: "POST",
+ body: { name: "私密", visibility: "private" },
+ });
+ expect(priv.status).toBe(201);
+ const created = await readJson(priv);
+ expect(created).toMatchObject({ visibility: "private", isDefault: false });
+ expect(sceneRow(created.id)).toEqual({
+ visibility: "private",
+ is_default: 0,
+ });
+ });
+
+ it("POST/PUT reject an illegal visibility with the {error} shape", async () => {
+ for (const visibility of ["hidden", "", 7, null]) {
+ const res = await adminRequest(app, env, cookie, "/api/admin/scenes", {
+ method: "POST",
+ body: { name: "x", visibility },
+ });
+ expect(res.status).toBe(400);
+ expect(await readJson(res)).toEqual({
+ error: "visibility must be 'public' or 'private'",
+ });
+ }
+
+ const created = await readJson(
+ await adminRequest(app, env, cookie, "/api/admin/scenes", {
+ method: "POST",
+ body: { name: "工作" },
+ }),
+ );
+ const res = await adminRequest(
+ app,
+ env,
+ cookie,
+ `/api/admin/scenes/${created.id}`,
+ { method: "PUT", body: { visibility: "secret" } },
+ );
+ expect(res.status).toBe(400);
+ expect(await readJson(res)).toEqual({
+ error: "visibility must be 'public' or 'private'",
+ });
+ expect(sceneRow(created.id).visibility).toBe("public");
+ });
+
+ it("PUT flips a non-default scene to private and back", async () => {
+ const created = await readJson(
+ await adminRequest(app, env, cookie, "/api/admin/scenes", {
+ method: "POST",
+ body: { name: "工作" },
+ }),
+ );
+
+ const toPrivate = await adminRequest(
+ app,
+ env,
+ cookie,
+ `/api/admin/scenes/${created.id}`,
+ { method: "PUT", body: { visibility: "private" } },
+ );
+ expect(toPrivate.status).toBe(200);
+ expect(await readJson(toPrivate)).toMatchObject({
+ id: created.id,
+ visibility: "private",
+ isDefault: false,
+ });
+
+ const toPublic = await adminRequest(
+ app,
+ env,
+ cookie,
+ `/api/admin/scenes/${created.id}`,
+ { method: "PUT", body: { visibility: "public" } },
+ );
+ expect(toPublic.status).toBe(200);
+ expect(await readJson(toPublic)).toMatchObject({ visibility: "public" });
+ });
+
+ it("PUT the default scene to private is a 400 and writes nothing", async () => {
+ const res = await adminRequest(
+ app,
+ env,
+ cookie,
+ "/api/admin/scenes/scene_default",
+ { method: "PUT", body: { visibility: "private", name: "改名也没写" } },
+ );
+ expect(res.status).toBe(400);
+ expect(await readJson(res)).toEqual({
+ error: "default scene cannot be private",
+ });
+ expect(sceneRow("scene_default")).toEqual({
+ visibility: "public",
+ is_default: 1,
+ });
+ // The whole update was rejected — not just the visibility field.
+ expect(
+ sqliteOf(env)
+ .prepare("SELECT name FROM scenes WHERE id = 'scene_default'")
+ .get(),
+ ).toEqual({ name: "通用" });
+
+ // 公开值仍然可以提交(幂等,不算变更默认场景)。
+ const stillPublic = await adminRequest(
+ app,
+ env,
+ cookie,
+ "/api/admin/scenes/scene_default",
+ { method: "PUT", body: { visibility: "public" } },
+ );
+ expect(stillPublic.status).toBe(200);
+ });
+
+ it("a private scene cannot be made the default (400, {error} shape)", async () => {
+ const priv = await readJson(
+ await adminRequest(app, env, cookie, "/api/admin/scenes", {
+ method: "POST",
+ body: { name: "私密", visibility: "private" },
+ }),
+ );
+
+ const viaPost = await adminRequest(app, env, cookie, "/api/admin/scenes", {
+ method: "POST",
+ body: { name: "又想当默认", visibility: "private", isDefault: true },
+ });
+ expect(viaPost.status).toBe(400);
+ expect(await readJson(viaPost)).toEqual({
+ error: "private scene cannot be set as default",
+ });
+ expect(
+ count(env, "SELECT COUNT(*) AS n FROM scenes WHERE name = '又想当默认'"),
+ ).toBe(0);
+
+ const viaPut = await adminRequest(
+ app,
+ env,
+ cookie,
+ `/api/admin/scenes/${priv.id}`,
+ { method: "PUT", body: { isDefault: true } },
+ );
+ expect(viaPut.status).toBe(400);
+ expect(await readJson(viaPut)).toEqual({
+ error: "private scene cannot be set as default",
+ });
+ expect(sceneRow(priv.id)).toEqual({
+ visibility: "private",
+ is_default: 0,
+ });
+ expect(
+ count(env, "SELECT COUNT(*) AS n FROM scenes WHERE is_default = 1"),
+ ).toBe(1);
+
+ // 公开场景上的 isDefault 仍按 #17 冻结契约静默忽略。
+ const publicScene = await readJson(
+ await adminRequest(app, env, cookie, "/api/admin/scenes", {
+ method: "POST",
+ body: { name: "公开" },
+ }),
+ );
+ const ignored = await adminRequest(
+ app,
+ env,
+ cookie,
+ `/api/admin/scenes/${publicScene.id}`,
+ { method: "PUT", body: { isDefault: true } },
+ );
+ expect(ignored.status).toBe(200);
+ expect(await readJson(ignored)).toMatchObject({ isDefault: false });
+ });
+
+ it("DELETE still moves a private scene's categories into the default scene", async () => {
+ const priv = await readJson(
+ await adminRequest(app, env, cookie, "/api/admin/scenes", {
+ method: "POST",
+ body: { name: "私密", visibility: "private" },
+ }),
+ );
+ insertCategoryRow(env, {
+ id: "cat-secret",
+ name: "私有场景分类",
+ sortOrder: 0,
+ sceneId: priv.id,
+ visibility: "private",
+ });
+
+ const del = await adminRequest(
+ app,
+ env,
+ cookie,
+ `/api/admin/scenes/${priv.id}`,
+ { method: "DELETE" },
+ );
+ expect(del.status).toBe(200);
+
+ // 分类迁入默认场景,自身的私有标记保留不动(由取与规则保证不外露)。
+ expect(
+ sqliteOf(env)
+ .prepare(
+ "SELECT scene_id, visibility FROM categories WHERE id = 'cat-secret'",
+ )
+ .get(),
+ ).toEqual({ scene_id: "scene_default", visibility: "private" });
+ const publicBody = await readJson(
+ await app.request("/api/public", {}, env),
+ );
+ expect(
+ publicBody.categories.some(
+ (cat: { id: string }) => cat.id === "cat-secret",
+ ),
+ ).toBe(false);
+ });
+});
+
describe("SqliteD1.batch transaction semantics", () => {
it("commits all statements and rolls the whole batch back on error", async () => {
const env = makeEnv();
diff --git a/worker/test/setup.test.ts b/worker/test/setup.test.ts
index 528007a..788635b 100644
--- a/worker/test/setup.test.ts
+++ b/worker/test/setup.test.ts
@@ -217,6 +217,7 @@ describe("POST /api/setup (secret-gated upgrade)", () => {
migrations: [
{ name: "schema_v1", status: "applied" },
{ name: "schema_v2", status: "applied" },
+ { name: "schema_v3", status: "applied" },
],
ownerExists: false,
});
@@ -240,6 +241,7 @@ describe("POST /api/setup (secret-gated upgrade)", () => {
migrations: [
{ name: "schema_v1", status: "skipped" },
{ name: "schema_v2", status: "skipped" },
+ { name: "schema_v3", status: "skipped" },
],
ownerExists: true,
});
@@ -305,7 +307,7 @@ describe("admin system endpoints", () => {
expect(await readJson(res)).toEqual({
tablePrefix: "",
setupPageEnabled: false,
- ledger: ["schema_v1", "schema_v2"],
+ ledger: ["schema_v1", "schema_v2", "schema_v3"],
});
});
@@ -325,6 +327,7 @@ describe("admin system endpoints", () => {
migrations: [
{ name: "schema_v1", status: "skipped" },
{ name: "schema_v2", status: "skipped" },
+ { name: "schema_v3", status: "skipped" },
],
ownerExists: true,
});