feat(browser): unify site credentials with browser profiles (BR-2)

- Inject the site account Cookie (manual + auto-login session, session wins)
  into the camofox profile before the first tab opens; password accounts
  without a session run refresh-login first; API Key sites are skipped.
- Cookie expired after injection -> credential.status=expired; cookie
  accounts go to waiting/login_required ("log in once, applies site-wide").
- Write back site-domain cookies from the browser on handover, session close,
  every 10 min of activity, and from refresh-login when the stored cookie is
  invalid (verified before saving). user_info.cookieOrigin records
  source=browser; source shown as manual/login/browser in the origin view.
- New camofox plugin umt-cookies (GET/POST /umt/sessions/:userId/cookies
  under the access key); profile dir 0700/files 0600 in the desktop image.
- Single entry: sources-identity/service/credentials.ts.
- Real check: HHClub cookie injected into a fresh profile -> home page
  logged in (logout link present), 5 cookies read back.

Requires rebuilding umt-browser-desktop (docker compose build camofox &&
docker compose up -d camofox) to take effect.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
rootandClaude Opus 5.5 committed 2026-09-29 15:25:07 +08:00
1 parent 901b01d1a1
commit 28974d1e1a
58 files changed
+2843 -1112

No files matched your search

+100 -1
View File
@@ -34,8 +34,16 @@ export interface MockCamofoxSite {
/** 下载内容;缺省返回固定字节 */
torrent?: (id: string) => Uint8Array;
passkey?: string;
/**
* 登录态 Cookie(BR-2):注入的 Cookie 里 name 的值在 valid 中 → 该 profile 视为已登录;值不在其中 → 视为未登录(过期)。
* 表单登录成功后把 name=fresh 写进该 profile 的 Cookie(读回时可见)。
*/
sessionCookie?: { name: string; valid: string[]; fresh: string };
}
/** mock 的 Cookie 接口形态:plugin = umt-cookies 插件(读写);upstream = 只有上游导入端点(要求 CAMOFOX_API_KEY);none = 都没有 */
export type MockCookieApi = "plugin" | "upstream" | "none";
export const MOCK_VIEWPORT = { width: 1280, height: 800 } as const;
export const MOCK_ROW_Y0 = 20;
export const MOCK_ROW_H = 40;
@@ -52,6 +60,21 @@ export interface MockCamofoxOptions {
/** 视口(CSS 像素)与设备像素比:截图尺寸 = 视口 × DPR;元素行坐标按 CSS 像素。缺省 MOCK_VIEWPORT、DPR 1 */
viewport?: { width: number; height: number };
devicePixelRatio?: number;
/** 缺省 plugin */
cookieApi?: MockCookieApi;
/** upstream 模式下上游导入端点认的口令(模拟 CAMOFOX_API_KEY);缺省不设 → 403 */
cookieImportKey?: string;
}
export interface MockCamofoxCookie {
name: string;
value: string;
domain: string;
path: string;
expires: number;
httpOnly: boolean;
secure: boolean;
sameSite?: string;
}
export interface MockCamofoxTab {
@@ -90,6 +113,8 @@ export type MockCamofox = MockHttp & {
actions: MockCamofoxAction[];
/** 已登录的 userId(profile) */
loggedIn: Set<string>;
/** 各 profile 的 Cookie(注入的 + 表单登录写入的) */
cookieJars: Map<string, MockCamofoxCookie[]>;
/** 模拟站点登录过期(全部 profile 或指定 profile) */
expireLogin(userId?: string): void;
/** 模拟上游回收标签页(空闲超时 / 重启) */
@@ -298,7 +323,40 @@ export async function createMockCamofox(opts: MockCamofoxOptions = {}): Promise<
const tabs = new Map<string, MockCamofoxTab>();
const actions: MockCamofoxAction[] = [];
const loggedIn = new Set<string>();
const cookieJars = new Map<string, MockCamofoxCookie[]>();
const cookieApi = opts.cookieApi ?? "plugin";
const site = opts.site;
const putCookie = (userId: string, c: MockCamofoxCookie) => {
const jar = (cookieJars.get(userId) ?? []).filter(
(x) => !(x.name === c.name && x.domain === c.domain && x.path === c.path),
);
jar.push(c);
cookieJars.set(userId, jar);
const sc = site?.sessionCookie;
if (sc && c.name === sc.name && new URL(site.origin).hostname.endsWith(c.domain.replace(/^\./, ""))) {
if (sc.valid.includes(c.value)) loggedIn.add(userId);
else loggedIn.delete(userId);
}
};
const importCookies = (userId: string, b: Body): MockReply => {
const list = Array.isArray(b.cookies) ? (b.cookies as Record<string, unknown>[]) : null;
if (!list) return err(400, "cookies must be an array");
for (const c of list) {
if (typeof c.name !== "string" || typeof c.value !== "string" || typeof c.domain !== "string")
return err(400, "invalid cookie objects");
putCookie(userId, {
name: c.name,
value: c.value,
domain: c.domain,
path: typeof c.path === "string" ? c.path : "/",
expires: typeof c.expires === "number" ? c.expires : -1,
httpOnly: c.httpOnly === true,
secure: c.secure === true,
...(typeof c.sameSite === "string" ? { sameSite: c.sameSite } : {}),
});
}
return { json: { ok: true, userId, count: list.length } };
};
const viewport = opts.viewport ?? MOCK_VIEWPORT;
const dpr = opts.devicePixelRatio ?? 1;
const loginPath = site?.loginPath ?? "/login.php";
@@ -351,6 +409,19 @@ export async function createMockCamofox(opts: MockCamofoxOptions = {}): Promise<
return;
}
loggedIn.add(t.userId);
if (site.sessionCookie) {
if (!site.sessionCookie.valid.includes(site.sessionCookie.fresh))
site.sessionCookie.valid.push(site.sessionCookie.fresh);
putCookie(t.userId, {
name: site.sessionCookie.name,
value: site.sessionCookie.fresh,
domain: new URL(site.origin).hostname,
path: "/",
expires: Math.floor(Date.now() / 1000) + 86400,
httpOnly: true,
secure: site.origin.startsWith("https:"),
});
}
go(t, `${site.origin}${back}`);
};
@@ -713,6 +784,32 @@ export async function createMockCamofox(opts: MockCamofoxOptions = {}): Promise<
return { json: { downloads: list } };
},
],
[
/^\/umt\/sessions\/([^/]+)\/cookies$/,
(m, q, req, b) => {
if (cookieApi !== "plugin") return err(404, "no route");
const userId = decodeURIComponent(m[1]!);
if (req.method === "POST") return importCookies(userId, b);
const hosts = (q.urls ?? "")
.split(",")
.filter(Boolean)
.map((u) => new URL(u).hostname);
const cookies = (cookieJars.get(userId) ?? []).filter((c) => {
const d = c.domain.replace(/^\./, "");
return hosts.some((h) => h === d || h.endsWith(`.${d}`));
});
return { json: { source: "live", cookies } };
},
],
[
/^\/sessions\/([^/]+)\/cookies$/,
(m, _q, req, b) => {
if (cookieApi === "none") return err(404, "no route");
if (!opts.cookieImportKey || req.headers.authorization !== `Bearer ${opts.cookieImportKey}`)
return err(403, "Forbidden");
return importCookies(decodeURIComponent(m[1]!), b);
},
],
[
/^\/sessions\/([^/]+)$/,
(m) => {
@@ -731,7 +828,8 @@ export async function createMockCamofox(opts: MockCamofoxOptions = {}): Promise<
port: opts.port,
guard: (req) => {
const path = new URL(req.url ?? "/", "http://mock").pathname;
if (!opts.accessKey || path === "/health") return null;
// 与上游一致:导入端点有自己的口令(CAMOFOX_API_KEY),不走访问凭据
if (!opts.accessKey || path === "/health" || /^\/sessions\/[^/]+\/cookies$/.test(path)) return null;
return req.headers.authorization === `Bearer ${opts.accessKey}` ? null : err(401, "Unauthorized");
},
},
@@ -740,6 +838,7 @@ export async function createMockCamofox(opts: MockCamofoxOptions = {}): Promise<
tabs,
actions,
loggedIn,
cookieJars,
expireLogin(userId?: string) {
if (userId) loggedIn.delete(userId);
else loggedIn.clear();