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
17 changes: 16 additions & 1 deletion docs/api-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,21 @@
- 回源失败时回退到昨日缓存图(同样 200);连昨日缓存也无 → `502 {"error":"wallpaper unavailable"}`。
- 服务端按北京时间自然日缓存当天图(内部缓存条目多保留一天以支持次日回退);不向上游透传 `content-length` / `x-msedge-ref` / `nel` / `report-to` 等头。

### GET /api/icon

worker 端图标解析器:服务端读目标站 HTML 的 `<link rel="icon">` 声明、探测根文件,抓到后缓存并**直接回图字节**。无鉴权(公共页未登录也要显示图标)。前端在 `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。
- **解析顺序**(全部限定在登记的 origin):`GET https://{host}/` 读 HTML 里 `rel` 含 `icon` / `apple-touch-icon` 的 `<link>`(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`;**不透传任何上游响应头**。
- 成功与失败响应均带 `vary: Cookie`:同一 URL 匿名可能是 404、带会话才是 200,共享缓存不得把会话结果回给匿名访客。
- **SVG 防护**:第三方 SVG 可能带 `<script>` / 事件属性,因此图标响应一律带 `content-security-policy: default-src 'none'; sandbox` —— `<img>` 加载不受影响,但直接导航到本端点也不会在本站 origin 下执行第三方脚本。
- 无图标 `404 {"error":"icon not found"}` + `cache-control: public, max-age=3600`。
- **缓存**:R2 对象 `_cache/favicons/{host}`(保留前缀,不经 `GET /assets/*` 公开),`customMetadata` 记 `{status:"ok"|"none", fetchedAt, mime?, sourceUrl?}`。「有图」30 天、「无图」7 天视为新鲜;过期时先回旧结果、后台重抓(`waitUntil`),**不用定时任务**;同一 host 的并发解析合并为一次。**刷新失败时保留已在用的好图(只顺延 `fetchedAt`),不会因一次上游抖动把图标降级成负缓存**。R2 未绑定或读写失败时降级为「现抓现发、不缓存」。
- 不读也不改写 `links.icon_url`。

## 私有

### GET /api/private
Expand Down Expand Up @@ -168,6 +183,6 @@ Passkey(WebAuthn,/api/auth/passkey/*,@simplewebauthn/server v14):

## 说明

- favicon 自动抓取不在后端做:前端直接请求目标站 / 公共 favicon 服务,失败回退首字圆;后端只存 `iconUrl` 字段。
- 图标自动抓取由 worker 做:见上方 `GET /api/icon`(服务端解析 + R2 缓存 + 直接回图)。前端只在 `iconUrl` 为空时请求该端点,失败回退首字圆;后端仍只存 `iconUrl` 字段。
- 点击计数、服务健康状态为预留字段,v1 不实现(SPEC 第 5 节)。
- 会话 Cookie `nav_session`:HS256 JWT 签名 + `sessions` 表吊销,7 天有效。
3 changes: 3 additions & 0 deletions worker/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { privateRoutes } from "./routes/private";
import { adminRoutes } from "./routes/admin";
import { setupRoutes } from "./routes/setup";
import { wallpaperRoutes } from "./routes/wallpaper";
import { iconRoutes } from "./routes/icon";
import { assetPublicRoutes } from "./routes/assets";
import { getSetting } from "./db/queries/settings";
import { deleteExpiredSessions } from "./db/queries/users";
Expand Down Expand Up @@ -51,6 +52,8 @@ app.route("/api/public", publicRoutes);
app.route("/api/private", privateRoutes);
app.route("/api/admin", adminRoutes);
app.route("/api/wallpaper", wallpaperRoutes);
// Worker 端图标解析器:回图由 R2 缓存直出(契约 docs/api-contract.md §GET /api/icon)。
app.route("/api/icon", iconRoutes);
// Setup surface: GET /api/setup/state (canonical), GET /api/setup/status
// (legacy alias), POST /api/setup (secret-gated upgrade — SETUP-PAGE-SPEC §3).
app.route("/api", setupRoutes);
Expand Down
27 changes: 20 additions & 7 deletions worker/src/middleware/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,21 +23,34 @@ export function unauthorized(): Response {
});
}

export async function authMiddleware(c: Context<HonoEnv>, next: Next) {
/**
* 会话探测:有效会话返回 user id,否则 null(不抛、不写响应)。`authMiddleware`
* 与需要「有会话则放宽」的端点(`GET /api/icon` 的私有 host)共用这一条判断。
*/
export async function getSessionUserId(
c: Context<HonoEnv>,
): Promise<string | null> {
const token = getCookie(c, SESSION_COOKIE);
if (!token) return unauthorized();
if (!token) return null;

const payload = await verifyJWT(token, c.env.SESSION_SECRET);
if (!payload) return unauthorized();
if (!payload) return null;

const prefix = getTablePrefix(c.env);
const session = await findSession(c.env.DB, prefix, payload.sid);
if (!session || session.expires_at < nowIso()) return unauthorized();
if (session.user_id !== payload.sub) return unauthorized();
if (!session || session.expires_at < nowIso()) return null;
if (session.user_id !== payload.sub) return null;

const user = await findUserById(c.env.DB, prefix, session.user_id);
if (!user?.is_active) return unauthorized();
if (!user?.is_active) return null;

return user.id;
}

export async function authMiddleware(c: Context<HonoEnv>, next: Next) {
const userId = await getSessionUserId(c);
if (!userId) return unauthorized();

c.set("userId", user.id);
c.set("userId", userId);
await next();
}
6 changes: 6 additions & 0 deletions worker/src/routes/assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
assetSizeError,
isAssetPurpose,
mimeForExt,
RESERVED_ASSET_KEY_PREFIX,
validateImageUpload,
} from "../services/assets";

Expand All @@ -35,7 +36,12 @@ assetPublicRoutes.get("/*", async (c) => {
if (!bucket) return c.json({ error: "not found" }, 404);

const key = c.req.path.slice(ASSET_PUBLIC_PREFIX.length);
// 保留前缀是 worker 内部缓存(图标等)。它们不是用户上传物,也不该被
// 按 key 猜出来(猜得到「这个站在主人链接里」这类关联)。
if (!key || key.includes("..")) return c.json({ error: "not found" }, 404);
if (key.startsWith(RESERVED_ASSET_KEY_PREFIX)) {
return c.json({ error: "not found" }, 404);
}

const object = await bucket.get(key);
if (!object) return c.json({ error: "not found" }, 404);
Expand Down
91 changes: 91 additions & 0 deletions worker/src/routes/icon.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { Hono } from "hono";
import type { Context } from "hono";
import { getTablePrefix, type HonoEnv } from "../types";
import { getSessionUserId } from "../middleware/auth";
import {
getIcon,
loadIconRegistry,
parseIconTarget,
type CachedIcon,
} from "../services/favicon";

/**
* `GET /api/icon?url=…` —— worker 端图标解析器的唯一边界(契约见
* docs/api-contract.md §GET /api/icon)。回图按字节返回,前端不与第三方站
* 直连;抓不到就是 404,由前端回退首字圆。
*/
export const iconRoutes = new Hono<HonoEnv>();

const ICON_CACHE_CONTROL = "public, max-age=86400";
const MISS_CACHE_CONTROL = "public, max-age=3600";

/**
* 私有 host 的图标只给带会话的人:同一个 URL 匿名是 404、登录是 200,响应必须
* `Vary: Cookie`,否则共享 CDN/代理可能把带会话拿到的结果回给匿名访客。
*/
const VARY = "Cookie";

/**
* 第三方 SVG 可能带 `<script>` / 事件属性。前端用 `<img>` 加载时不会执行,但
* 直接导航到本端点就会在本站 origin 下当文档跑 —— 沙箱化并禁掉一切外部资源。
*/
const ICON_CSP = "default-src 'none'; sandbox";

function iconNotFound(c: Context<HonoEnv>): Response {
c.header("cache-control", MISS_CACHE_CONTROL);
c.header("vary", VARY);
return c.json({ error: "icon not found" }, 404);
}

/** 后台刷新:有 ExecutionContext 就托管,没有(单测)就让它在 isolate 里跑完。 */
function schedule(c: Context<HonoEnv>, task: Promise<unknown>): void {
const settled = task.catch(() => undefined);
try {
c.executionCtx.waitUntil(settled);
} catch {
// 没有 ExecutionContext 的环境(app.request)无需额外处理。
}
}

function iconResponse(icon: CachedIcon): Response {
return new Response(icon.bytes, {
status: 200,
headers: {
"content-type": icon.mime ?? "application/octet-stream",
"cache-control": ICON_CACHE_CONTROL,
// 第三方图片一律当不可信内容:禁止浏览器重新嗅探类型。
"x-content-type-options": "nosniff",
"content-security-policy": ICON_CSP,
vary: VARY,
},
});
}

iconRoutes.get("/", async (c) => {
const requested = parseIconTarget(c.req.query("url") ?? "");
if (!requested) {
c.header("cache-control", "no-store");
return c.json({ error: "url must be an absolute http(s) URL" }, 400);
}

const prefix = getTablePrefix(c.env);
// 私有链接的 host 需要有效会话;会话查询失败按匿名处理,端点不因未初始化
// 的库变成 500。
const userId = await getSessionUserId(c).catch(() => null);
const registry = await loadIconRegistry(c.env, prefix, {
includePrivate: Boolean(userId),
});

// 出网目标取自注册表里的 origin,而不是请求参数里的 path/query。
const entry = registry.get(requested.host);
if (!entry) return iconNotFound(c);

const icon = await getIcon(
c.env,
{ host: requested.host, origin: entry.origin },
(task) => schedule(c, task),
);
if (icon.status !== "ok" || !icon.bytes) return iconNotFound(c);

return iconResponse(icon);
});
6 changes: 6 additions & 0 deletions worker/src/services/assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,12 @@ export const ASSET_CACHE_CONTROL = "public, max-age=31536000, immutable";
/** Objects are keyed `assets/…` and publicly served at `/assets/{key}`. */
export const ASSET_PUBLIC_PREFIX = "/assets/";

/**
* 保留 key 前缀:worker 内部缓存(如图标)落在这里,`GET /assets/*` 一律
* 拒绝 —— 它们不是用户上传物,也不该被按 key 猜出来。
*/
export const RESERVED_ASSET_KEY_PREFIX = "_cache/";

export function mimeForExt(ext: string): string | null {
const entry = Object.entries(EXT_BY_KIND).find(([, value]) => value === ext);
return entry ? MIME_BY_KIND[entry[0] as ImageKind] : null;
Expand Down
Loading
Loading