Files
woniu336 38e0dfe103 feat(cases): 卦例上云 —— 匿名设备归属 + D1 存储 + 本地一次性迁移
- ly_device:首次访问下发 HttpOnly UUID Cookie(1 年),服务端作为 owner_id 隔离
- D1CaseStore:按 owner 查询/写入/收藏/删除,每 owner 保留最近 200 条(写入时裁剪)
- getServerCaseStore:有 DB 绑定走 D1,next dev 走内存;客户端探活决定远端/本地
- RemoteCaseStore:/api/cases 的客户端实现;接口不可用自动回退 localStorage
- 一次性迁移:切到远端时把旧 localStorage 卦例批量导入(幂等,失败下次重试)
- /api/cases:probe/list/get/save/import/favorite/delete;parseCaseRecord fail-closed 校验、
  512KB 体限、写入限流、同源校验;设备 Cookie 由服务端签发
- schema 生成物与 ensureD1Schema 移到 lib/db(admin 与 cases 共用)
- /cases 提示区分「云端(匿名设备)」与「本机浏览器」

验证(workerd + D1):保存/列表/打开/收藏/删除、新上下文 owner 隔离、旧本地卦例自动迁移;
58 项测试通过;next/vinext build 与 check 通过。
2026-11-05 13:54:30 +08:00

44 lines
1.6 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 匿名设备标识(卦例归属)。
*
* 不引入登录:首次访问卦例接口时下发一个 HttpOnly UUID Cookie,
* 服务端用它做 `owner_id` 隔离。以后接账号体系时,只换 ownerId 的来源,
* CaseStore 接口与前端都不用改。
*
* 边界(务必如实告知用户):同一浏览器/同一 Cookie 才能看到同一批卦例;
* 换设备、换浏览器或清除 Cookie 都会得到一个新的卦例夹。
*/
export const DEVICE_COOKIE = 'ly_device';
const ONE_YEAR = 365 * 24 * 3600;
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
function readCookie(req: Request, name: string): string | null {
const header = req.headers.get('cookie');
if (!header) return null;
for (const part of header.split(';')) {
const idx = part.indexOf('=');
if (idx < 0) continue;
if (part.slice(0, idx).trim() === name) return decodeURIComponent(part.slice(idx + 1).trim());
}
return null;
}
export interface DeviceIdentity {
ownerId: string;
/** 只在新建/替换时返回,调用方负责加到响应头 */
setCookie?: string;
}
export function getOrCreateDeviceId(req: Request): DeviceIdentity {
const existing = readCookie(req, DEVICE_COOKIE);
if (existing && UUID_RE.test(existing)) return { ownerId: existing };
const ownerId = crypto.randomUUID();
const secure = new URL(req.url).protocol === 'https:' ? '; Secure' : '';
return {
ownerId,
setCookie: `${DEVICE_COOKIE}=${ownerId}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${ONE_YEAR}${secure}`,
};
}