@humain/terminal 0.0.3-beta.0 → 0.0.3-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +4 -3
- package/dist/config.js.map +1 -1
- package/dist/humain/mcp-adapter/vendor/CHANGELOG.md +13 -0
- package/dist/humain/mcp-adapter/vendor/README.md +4 -1
- package/dist/humain/mcp-adapter/vendor/agent-dir.ts +12 -4
- package/dist/humain/mcp-adapter/vendor/cli.js +25 -4
- package/dist/humain/mcp-adapter/vendor/config.ts +4 -4
- package/dist/humain/mcp-adapter/vendor/direct-tools.ts +18 -15
- package/dist/humain/mcp-adapter/vendor/index.bundle.mjs +416 -60
- package/dist/humain/mcp-adapter/vendor/mcp-setup-panel.ts +2 -1
- package/dist/humain/mcp-adapter/vendor/metadata-cache.ts +18 -8
- package/dist/humain/mcp-adapter/vendor/package.json +177 -176
- package/dist/humain/mcp-adapter/vendor/request-headers-command.ts +336 -0
- package/dist/humain/mcp-adapter/vendor/server-manager.ts +5 -0
- package/dist/humain/mcp-adapter/vendor/tool-metadata.ts +38 -18
- package/dist/humain/mcp-adapter/vendor/types.ts +93 -10
- package/dist/humain/web-access/vendor/auth-fetch.d.ts +13 -0
- package/dist/humain/web-access/vendor/auth-fetch.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/auth-fetch.js +134 -0
- package/dist/humain/web-access/vendor/auth-fetch.js.map +1 -0
- package/dist/humain/web-access/vendor/chrome-cookies.d.ts +13 -0
- package/dist/humain/web-access/vendor/chrome-cookies.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/chrome-cookies.js +106 -22
- package/dist/humain/web-access/vendor/chrome-cookies.js.map +1 -1
- package/dist/humain/web-access/vendor/curator-page.d.ts +1 -0
- package/dist/humain/web-access/vendor/curator-page.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/curator-page.js +3 -1
- package/dist/humain/web-access/vendor/curator-page.js.map +1 -1
- package/dist/humain/web-access/vendor/curator-server.d.ts +1 -0
- package/dist/humain/web-access/vendor/curator-server.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/curator-server.js +2 -0
- package/dist/humain/web-access/vendor/curator-server.js.map +1 -1
- package/dist/humain/web-access/vendor/extract.d.ts +2 -0
- package/dist/humain/web-access/vendor/extract.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/extract.js +79 -17
- package/dist/humain/web-access/vendor/extract.js.map +1 -1
- package/dist/humain/web-access/vendor/fetch-params.d.ts +2 -0
- package/dist/humain/web-access/vendor/fetch-params.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/fetch-params.js +17 -3
- package/dist/humain/web-access/vendor/fetch-params.js.map +1 -1
- package/dist/humain/web-access/vendor/firecrawl.d.ts +7 -0
- package/dist/humain/web-access/vendor/firecrawl.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/firecrawl.js +141 -10
- package/dist/humain/web-access/vendor/firecrawl.js.map +1 -1
- package/dist/humain/web-access/vendor/gemini-search.d.ts +2 -2
- package/dist/humain/web-access/vendor/gemini-search.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/gemini-search.js +22 -4
- package/dist/humain/web-access/vendor/gemini-search.js.map +1 -1
- package/dist/humain/web-access/vendor/index.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/index.js +122 -48
- package/dist/humain/web-access/vendor/index.js.map +1 -1
- package/dist/humain/web-access/vendor/summary-review.d.ts +3 -1
- package/dist/humain/web-access/vendor/summary-review.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/summary-review.js +6 -3
- package/dist/humain/web-access/vendor/summary-review.js.map +1 -1
- package/dist/humain/web-access/vendor/youtube-extract.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/youtube-extract.js +2 -2
- package/dist/humain/web-access/vendor/youtube-extract.js.map +1 -1
- package/dist/utils/clipboard-image.d.ts.map +1 -1
- package/dist/utils/clipboard-image.js +2 -0
- package/dist/utils/clipboard-image.js.map +1 -1
- package/npm-shrinkwrap.json +7 -7
- package/package.json +6 -6
- package/src/humain/mcp-adapter/UPSTREAM.md +1 -1
- package/src/humain/mcp-adapter/upstream.json +3 -3
- package/src/humain/mcp-adapter/vendor/CHANGELOG.md +13 -0
- package/src/humain/web-access/UPSTREAM.md +1 -1
- package/src/humain/web-access/upstream.json +4 -4
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { getWebSearchConfigPath } from "./utils.js";
|
|
3
|
+
const WEB_SEARCH_CONFIG_PATH = getWebSearchConfigPath();
|
|
4
|
+
const AUTH_PROFILE_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
|
|
5
|
+
export function resolveAuthFetchProfile(request) {
|
|
6
|
+
const profiles = loadAuthFetchProfiles();
|
|
7
|
+
if (profiles.length === 0) {
|
|
8
|
+
throw new Error(`auth requires at least one authFetch profile in ${WEB_SEARCH_CONFIG_PATH}`);
|
|
9
|
+
}
|
|
10
|
+
if (request === true) {
|
|
11
|
+
if (profiles.length !== 1) {
|
|
12
|
+
throw new Error("auth: true requires exactly one authFetch profile; use a profile name instead");
|
|
13
|
+
}
|
|
14
|
+
return profiles[0];
|
|
15
|
+
}
|
|
16
|
+
const name = request.trim();
|
|
17
|
+
const profile = profiles.find(candidate => candidate.name === name);
|
|
18
|
+
if (!profile)
|
|
19
|
+
throw new Error(`Unknown authFetch profile: ${name}`);
|
|
20
|
+
return profile;
|
|
21
|
+
}
|
|
22
|
+
export function assertAuthFetchUrl(profile, rawUrl) {
|
|
23
|
+
let url;
|
|
24
|
+
try {
|
|
25
|
+
url = new URL(rawUrl);
|
|
26
|
+
}
|
|
27
|
+
catch (err) {
|
|
28
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
29
|
+
throw new Error(`Authenticated fetch requires an HTTPS URL: ${message}`);
|
|
30
|
+
}
|
|
31
|
+
if (url.protocol !== "https:")
|
|
32
|
+
throw new Error("Authenticated fetch requires an HTTPS URL");
|
|
33
|
+
const hostname = normalizeHostname(url.hostname);
|
|
34
|
+
if (!profile.hosts.some(host => hostMatches(hostname, host))) {
|
|
35
|
+
throw new Error(`URL host ${hostname} is not allowed by authFetch profile ${profile.name}`);
|
|
36
|
+
}
|
|
37
|
+
return url;
|
|
38
|
+
}
|
|
39
|
+
export function authFetchRedirectGuard(profile, from, to) {
|
|
40
|
+
if (profile.redirects === "same-origin" && to.origin !== from.origin) {
|
|
41
|
+
throw new Error(`Authenticated fetch refused cross-origin redirect: ${from.origin} -> ${to.origin}`);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
function loadAuthFetchProfiles() {
|
|
45
|
+
if (!existsSync(WEB_SEARCH_CONFIG_PATH))
|
|
46
|
+
return [];
|
|
47
|
+
const raw = readFileSync(WEB_SEARCH_CONFIG_PATH, "utf-8");
|
|
48
|
+
let parsed;
|
|
49
|
+
try {
|
|
50
|
+
const value = JSON.parse(raw);
|
|
51
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
52
|
+
throw new Error("expected a JSON object");
|
|
53
|
+
parsed = value;
|
|
54
|
+
}
|
|
55
|
+
catch (err) {
|
|
56
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
57
|
+
throw new Error(`Failed to parse ${WEB_SEARCH_CONFIG_PATH}: ${message}`);
|
|
58
|
+
}
|
|
59
|
+
if (parsed.authFetch === undefined || parsed.authFetch === null)
|
|
60
|
+
return [];
|
|
61
|
+
if (typeof parsed.authFetch !== "object" || Array.isArray(parsed.authFetch)) {
|
|
62
|
+
throw new Error(`authFetch in ${WEB_SEARCH_CONFIG_PATH} must be an object`);
|
|
63
|
+
}
|
|
64
|
+
return Object.entries(parsed.authFetch).map(([name, value]) => parseProfile(name, value));
|
|
65
|
+
}
|
|
66
|
+
function parseProfile(name, value) {
|
|
67
|
+
if (!AUTH_PROFILE_NAME_PATTERN.test(name)) {
|
|
68
|
+
throw new Error(`authFetch profile name ${JSON.stringify(name)} must start with a letter and contain only letters, numbers, underscores, or hyphens`);
|
|
69
|
+
}
|
|
70
|
+
if (Array.isArray(value)) {
|
|
71
|
+
return { name, hosts: parseHosts(value, `authFetch.${name}`), redirects: "same-origin", cache: "session" };
|
|
72
|
+
}
|
|
73
|
+
if (!value || typeof value !== "object") {
|
|
74
|
+
throw new Error(`authFetch.${name} in ${WEB_SEARCH_CONFIG_PATH} must be an array of hosts or an object`);
|
|
75
|
+
}
|
|
76
|
+
const config = value;
|
|
77
|
+
if (!Array.isArray(config.hosts)) {
|
|
78
|
+
throw new Error(`authFetch.${name}.hosts in ${WEB_SEARCH_CONFIG_PATH} must be a non-empty array of hostnames`);
|
|
79
|
+
}
|
|
80
|
+
const redirects = config.redirects ?? "same-origin";
|
|
81
|
+
if (redirects !== "same-origin") {
|
|
82
|
+
throw new Error(`authFetch.${name}.redirects in ${WEB_SEARCH_CONFIG_PATH} must be "same-origin"`);
|
|
83
|
+
}
|
|
84
|
+
const cache = config.cache ?? "session";
|
|
85
|
+
if (cache !== "session" && cache !== "off") {
|
|
86
|
+
throw new Error(`authFetch.${name}.cache in ${WEB_SEARCH_CONFIG_PATH} must be "session" or "off"`);
|
|
87
|
+
}
|
|
88
|
+
const chromeProfile = parseChromeProfile(config.chromeProfile, `authFetch.${name}.chromeProfile`);
|
|
89
|
+
return {
|
|
90
|
+
name,
|
|
91
|
+
hosts: parseHosts(config.hosts, `authFetch.${name}.hosts`),
|
|
92
|
+
...(chromeProfile ? { chromeProfile } : {}),
|
|
93
|
+
redirects,
|
|
94
|
+
cache,
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
function parseHosts(value, label) {
|
|
98
|
+
if (value.length === 0)
|
|
99
|
+
throw new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} must be a non-empty array of hostnames`);
|
|
100
|
+
const hosts = value.map((entry) => {
|
|
101
|
+
if (typeof entry !== "string")
|
|
102
|
+
throw new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} must contain only hostnames`);
|
|
103
|
+
return parseHost(entry, label);
|
|
104
|
+
});
|
|
105
|
+
return [...new Set(hosts)];
|
|
106
|
+
}
|
|
107
|
+
function parseHost(value, label) {
|
|
108
|
+
const host = normalizeHostname(value.trim());
|
|
109
|
+
if (!host || host.startsWith(".") || host.endsWith(".") || /\s|[\\/?:#@*]/.test(host)) {
|
|
110
|
+
throw new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} contains an invalid hostname: ${JSON.stringify(value)}`);
|
|
111
|
+
}
|
|
112
|
+
if (host.length > 253 || !/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(host)) {
|
|
113
|
+
throw new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} contains an invalid hostname: ${JSON.stringify(value)}`);
|
|
114
|
+
}
|
|
115
|
+
return host;
|
|
116
|
+
}
|
|
117
|
+
function parseChromeProfile(value, label) {
|
|
118
|
+
if (value === undefined || value === null)
|
|
119
|
+
return undefined;
|
|
120
|
+
if (typeof value !== "string")
|
|
121
|
+
throw new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} must be a string`);
|
|
122
|
+
const normalized = value.trim();
|
|
123
|
+
if (!normalized || normalized === "." || normalized === ".." || normalized.includes("/") || normalized.includes("\\")) {
|
|
124
|
+
throw new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} must be a profile directory name, not a path`);
|
|
125
|
+
}
|
|
126
|
+
return normalized;
|
|
127
|
+
}
|
|
128
|
+
function normalizeHostname(hostname) {
|
|
129
|
+
return hostname.toLowerCase().replace(/^\[|\]$/g, "").replace(/\.$/, "");
|
|
130
|
+
}
|
|
131
|
+
function hostMatches(hostname, allowedHost) {
|
|
132
|
+
return hostname === allowedHost || hostname.endsWith(`.${allowedHost}`);
|
|
133
|
+
}
|
|
134
|
+
//# sourceMappingURL=auth-fetch.js.map
|
|
@@ -0,0 +1 @@
|
|
|
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AAsB;IAC9E,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,SAAS,CAAC;IAC5D,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,OAAO,sBAAsB,mBAAmB,CAAC,CAAC;IACzG,MAAM,UAAU,GAAG,KAAK,CAAC,IAAI,EAAE,CAAC;IAChC,IAAI,CAAC,UAAU,IAAI,UAAU,KAAK,GAAG,IAAI,UAAU,KAAK,IAAI,IAAI,UAAU,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;QACvH,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,OAAO,sBAAsB,+CAA+C,CAAC,CAAC;IACvG,CAAC;IACD,OAAO,UAAU,CAAC;AAAA,CAClB;AAED,SAAS,iBAAiB,CAAC,QAAgB,EAAU;IACpD,OAAO,QAAQ,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;AAAA,CACzE;AAED,SAAS,WAAW,CAAC,QAAgB,EAAE,WAAmB,EAAW;IACpE,OAAO,QAAQ,KAAK,WAAW,IAAI,QAAQ,CAAC,QAAQ,CAAC,IAAI,WAAW,EAAE,CAAC,CAAC;AAAA,CACxE","sourcesContent":["import { existsSync, readFileSync } from \"node:fs\";\nimport { getWebSearchConfigPath } from \"./utils.ts\";\n\nconst WEB_SEARCH_CONFIG_PATH = getWebSearchConfigPath();\nconst AUTH_PROFILE_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;\n\nexport type AuthFetchRequest = true | string;\nexport type AuthFetchCache = \"session\" | \"off\";\n\nexport interface AuthFetchProfile {\n\tname: string;\n\thosts: string[];\n\tchromeProfile?: string;\n\tredirects: \"same-origin\";\n\tcache: AuthFetchCache;\n}\n\ninterface AuthFetchConfigRoot {\n\tauthFetch?: unknown;\n}\n\nexport function resolveAuthFetchProfile(request: AuthFetchRequest): AuthFetchProfile {\n\tconst profiles = loadAuthFetchProfiles();\n\tif (profiles.length === 0) {\n\t\tthrow new Error(`auth requires at least one authFetch profile in ${WEB_SEARCH_CONFIG_PATH}`);\n\t}\n\tif (request === true) {\n\t\tif (profiles.length !== 1) {\n\t\t\tthrow new Error(\"auth: true requires exactly one authFetch profile; use a profile name instead\");\n\t\t}\n\t\treturn profiles[0];\n\t}\n\tconst name = request.trim();\n\tconst profile = profiles.find(candidate => candidate.name === name);\n\tif (!profile) throw new Error(`Unknown authFetch profile: ${name}`);\n\treturn profile;\n}\n\nexport function assertAuthFetchUrl(profile: AuthFetchProfile, rawUrl: string): URL {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(rawUrl);\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\tthrow new Error(`Authenticated fetch requires an HTTPS URL: ${message}`);\n\t}\n\tif (url.protocol !== \"https:\") throw new Error(\"Authenticated fetch requires an HTTPS URL\");\n\tconst hostname = normalizeHostname(url.hostname);\n\tif (!profile.hosts.some(host => hostMatches(hostname, host))) {\n\t\tthrow new Error(`URL host ${hostname} is not allowed by authFetch profile ${profile.name}`);\n\t}\n\treturn url;\n}\n\nexport function authFetchRedirectGuard(profile: AuthFetchProfile, from: URL, to: URL): void {\n\tif (profile.redirects === \"same-origin\" && to.origin !== from.origin) {\n\t\tthrow new Error(`Authenticated fetch refused cross-origin redirect: ${from.origin} -> ${to.origin}`);\n\t}\n}\n\nfunction loadAuthFetchProfiles(): AuthFetchProfile[] {\n\tif (!existsSync(WEB_SEARCH_CONFIG_PATH)) return [];\n\tconst raw = readFileSync(WEB_SEARCH_CONFIG_PATH, \"utf-8\");\n\tlet parsed: AuthFetchConfigRoot;\n\ttry {\n\t\tconst value: unknown = JSON.parse(raw);\n\t\tif (!value || typeof value !== \"object\" || Array.isArray(value)) throw new Error(\"expected a JSON object\");\n\t\tparsed = value as AuthFetchConfigRoot;\n\t} catch (err) {\n\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\tthrow new Error(`Failed to parse ${WEB_SEARCH_CONFIG_PATH}: ${message}`);\n\t}\n\tif (parsed.authFetch === undefined || parsed.authFetch === null) return [];\n\tif (typeof parsed.authFetch !== \"object\" || Array.isArray(parsed.authFetch)) {\n\t\tthrow new Error(`authFetch in ${WEB_SEARCH_CONFIG_PATH} must be an object`);\n\t}\n\treturn Object.entries(parsed.authFetch as Record<string, unknown>).map(([name, value]) => parseProfile(name, value));\n}\n\nfunction parseProfile(name: string, value: unknown): AuthFetchProfile {\n\tif (!AUTH_PROFILE_NAME_PATTERN.test(name)) {\n\t\tthrow new Error(`authFetch profile name ${JSON.stringify(name)} must start with a letter and contain only letters, numbers, underscores, or hyphens`);\n\t}\n\tif (Array.isArray(value)) {\n\t\treturn { name, hosts: parseHosts(value, `authFetch.${name}`), redirects: \"same-origin\", cache: \"session\" };\n\t}\n\tif (!value || typeof value !== \"object\") {\n\t\tthrow new Error(`authFetch.${name} in ${WEB_SEARCH_CONFIG_PATH} must be an array of hosts or an object`);\n\t}\n\tconst config = value as Record<string, unknown>;\n\tif (!Array.isArray(config.hosts)) {\n\t\tthrow new Error(`authFetch.${name}.hosts in ${WEB_SEARCH_CONFIG_PATH} must be a non-empty array of hostnames`);\n\t}\n\tconst redirects = config.redirects ?? \"same-origin\";\n\tif (redirects !== \"same-origin\") {\n\t\tthrow new Error(`authFetch.${name}.redirects in ${WEB_SEARCH_CONFIG_PATH} must be \"same-origin\"`);\n\t}\n\tconst cache = config.cache ?? \"session\";\n\tif (cache !== \"session\" && cache !== \"off\") {\n\t\tthrow new Error(`authFetch.${name}.cache in ${WEB_SEARCH_CONFIG_PATH} must be \"session\" or \"off\"`);\n\t}\n\tconst chromeProfile = parseChromeProfile(config.chromeProfile, `authFetch.${name}.chromeProfile`);\n\treturn {\n\t\tname,\n\t\thosts: parseHosts(config.hosts, `authFetch.${name}.hosts`),\n\t\t...(chromeProfile ? { chromeProfile } : {}),\n\t\tredirects,\n\t\tcache,\n\t};\n}\n\nfunction parseHosts(value: unknown[], label: string): string[] {\n\tif (value.length === 0) throw new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} must be a non-empty array of hostnames`);\n\tconst hosts = value.map((entry) => {\n\t\tif (typeof entry !== \"string\") throw new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} must contain only hostnames`);\n\t\treturn parseHost(entry, label);\n\t});\n\treturn [...new Set(hosts)];\n}\n\nfunction parseHost(value: string, label: string): string {\n\tconst host = normalizeHostname(value.trim());\n\tif (!host || host.startsWith(\".\") || host.endsWith(\".\") || /\\s|[\\\\/?:#@*]/.test(host)) {\n\t\tthrow new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} contains an invalid hostname: ${JSON.stringify(value)}`);\n\t}\n\tif (host.length > 253 || !/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(host)) {\n\t\tthrow new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} contains an invalid hostname: ${JSON.stringify(value)}`);\n\t}\n\treturn host;\n}\n\nfunction parseChromeProfile(value: unknown, label: string): string | undefined {\n\tif (value === undefined || value === null) return undefined;\n\tif (typeof value !== \"string\") throw new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} must be a string`);\n\tconst normalized = value.trim();\n\tif (!normalized || normalized === \".\" || normalized === \"..\" || normalized.includes(\"/\") || normalized.includes(\"\\\\\")) {\n\t\tthrow new Error(`${label} in ${WEB_SEARCH_CONFIG_PATH} must be a profile directory name, not a path`);\n\t}\n\treturn normalized;\n}\n\nfunction normalizeHostname(hostname: string): string {\n\treturn hostname.toLowerCase().replace(/^\\[|\\]$/g, \"\").replace(/\\.$/, \"\");\n}\n\nfunction hostMatches(hostname: string, allowedHost: string): boolean {\n\treturn hostname === allowedHost || hostname.endsWith(`.${allowedHost}`);\n}\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export type CookieMap = Record<string, string>;
|
|
2
2
|
export declare function getLastGoogleCookieDiagnostic(): string | null;
|
|
3
|
+
export declare function getLastBrowserCookieDiagnostic(): string | null;
|
|
3
4
|
export declare function getGoogleCookies(options?: {
|
|
4
5
|
profile?: string;
|
|
5
6
|
requiredCookies?: string[];
|
|
@@ -7,4 +8,16 @@ export declare function getGoogleCookies(options?: {
|
|
|
7
8
|
cookies: CookieMap;
|
|
8
9
|
warnings: string[];
|
|
9
10
|
} | null>;
|
|
11
|
+
export declare function getBrowserCookiesForHosts(options: {
|
|
12
|
+
hosts: string[];
|
|
13
|
+
profile?: string;
|
|
14
|
+
requiredCookies?: string[];
|
|
15
|
+
cookieNames?: Iterable<string>;
|
|
16
|
+
requiredLabel?: string;
|
|
17
|
+
requestUrl?: URL;
|
|
18
|
+
}): Promise<{
|
|
19
|
+
cookies: CookieMap;
|
|
20
|
+
warnings: string[];
|
|
21
|
+
cookieHeader?: string;
|
|
22
|
+
} | null>;
|
|
10
23
|
//# sourceMappingURL=chrome-cookies.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chrome-cookies.d.ts","sourceRoot":"","sources":["../../../../src/humain/web-access/vendor/chrome-cookies.ts"],"names":[],"mappings":"AAOA,MAAM,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAyC/C,wBAAgB,6BAA6B,IAAI,MAAM,GAAG,IAAI,CAE7D;AAED,wBAAsB,gBAAgB,CACrC,OAAO,CAAC,EAAE;IAAE,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,eAAe,CAAC,EAAE,MAAM,EAAE,CAAA;CAAE,GACxD,OAAO,CAAC;IAAE,OAAO,EAAE,SAAS,CAAC;IAAC,QAAQ,EAAE,MAAM,EAAE,CAAA;CAAE,GAAG,IAAI,CAAC,CA4G5D","sourcesContent":["import { execFile } from \"node:child_process\";\nimport { pbkdf2Sync, createDecipheriv } from \"node:crypto\";\nimport { copyFileSync, existsSync, mkdtempSync, readdirSync, realpathSync, rmSync } from \"node:fs\";\nimport { tmpdir, homedir, platform } from \"node:os\";\nimport { isAbsolute, join, sep } from \"node:path\";\nimport { isBrowserCookieAccessAllowed } from \"./gemini-web-config.ts\";\n\nexport type CookieMap = Record<string, string>;\n\ninterface BrowserConfig {\n\tname: string;\n\tbaseDir: string;\n\tkeychainService?: string;\n\tkeychainAccount?: string;\n\tsecretToolApp?: string;\n}\n\ntype SqliteRow = Record<string, unknown>;\ntype SqliteFailure = \"unavailable\" | \"query\";\n\nconst GOOGLE_ORIGINS = [\n\t\"https://gemini.google.com\",\n\t\"https://accounts.google.com\",\n\t\"https://www.google.com\",\n];\n\nconst ALL_COOKIE_NAMES = new Set([\n\t\"__Secure-1PSID\", \"__Secure-1PSIDTS\", \"__Secure-1PSIDCC\", \"__Secure-1PAPISID\", \"NID\", \"AEC\", \"SOCS\",\n\t\"__Secure-BUCKET\", \"__Secure-ENID\", \"SID\", \"HSID\", \"SSID\", \"APISID\", \"SAPISID\", \"__Secure-3PSID\",\n\t\"__Secure-3PSIDTS\", \"__Secure-3PAPISID\", \"SIDCC\",\n]);\n\nconst MACOS_BROWSER_CONFIGS: BrowserConfig[] = [\n\t{ name: \"Helium\", baseDir: \"Library/Application Support/net.imput.helium\", keychainService: \"Helium Storage Key\", keychainAccount: \"Helium\" },\n\t{ name: \"Chrome\", baseDir: \"Library/Application Support/Google/Chrome\", keychainService: \"Chrome Safe Storage\", keychainAccount: \"Chrome\" },\n\t{ name: \"Arc\", baseDir: \"Library/Application Support/Arc/User Data\", keychainService: \"Arc Safe Storage\", keychainAccount: \"Arc\" },\n];\n\nconst LINUX_BROWSER_CONFIGS: BrowserConfig[] = [\n\t{ name: \"Chromium\", baseDir: \".config/chromium\", secretToolApp: \"chromium\" },\n\t{ name: \"Chrome\", baseDir: \".config/google-chrome\", secretToolApp: \"chrome\" },\n];\n\nconst browserPasswordCache = new Map<string, Promise<string | null>>();\nlet lastCookieDiagnostic: string | null = null;\nlet sqliteModule: typeof import(\"node:sqlite\") | null = null;\nlet sqliteImportAttempted = false;\n\nexport function getLastGoogleCookieDiagnostic(): string | null {\n\treturn lastCookieDiagnostic;\n}\n\nexport async function getGoogleCookies(\n\toptions?: { profile?: string; requiredCookies?: string[] },\n): Promise<{ cookies: CookieMap; warnings: string[] } | null> {\n\tlastCookieDiagnostic = null;\n\tif (!isBrowserCookieAccessAllowed()) {\n\t\tlastCookieDiagnostic = \"Browser cookie access is disabled; enable allowBrowserCookies to use Gemini Web cookies.\";\n\t\treturn null;\n\t}\n\n\tconst currentPlatform = platform();\n\tconst configs = currentPlatform === \"darwin\" ? MACOS_BROWSER_CONFIGS : currentPlatform === \"linux\" ? LINUX_BROWSER_CONFIGS : [];\n\tif (configs.length === 0) {\n\t\tlastCookieDiagnostic = \"Chromium cookie extraction is unsupported on this platform.\";\n\t\treturn null;\n\t}\n\n\tconst warningSet = new Set<string>();\n\tconst rawProfile = typeof options?.profile === \"string\" ? options.profile.trim() : \"\";\n\tconst requestedProfile = normalizeProfileName(options?.profile);\n\tif (rawProfile && !requestedProfile) {\n\t\tlastCookieDiagnostic = \"Configured Chromium profile must be a profile directory name, not a path.\";\n\t\treturn null;\n\t}\n\tconst requiredCookies = normalizeCookieNames(options?.requiredCookies);\n\tconst hosts = GOOGLE_ORIGINS.map((origin) => new URL(origin).hostname);\n\tconst home = homedir();\n\tlet sawCookieDatabase = false;\n\tlet sawRequiredCookies = false;\n\tlet sawBackendFailure: SqliteFailure | undefined;\n\tlet sawUnsafeProfilePath = false;\n\n\tfor (const config of configs) {\n\t\tconst profiles = requestedProfile ? [requestedProfile] : listBrowserProfiles(home, config);\n\t\tfor (const profile of profiles) {\n\t\t\tconst profilePath = resolveProfilePath(home, config, profile);\n\t\t\tif (profilePath === \"outside-root\") {\n\t\t\t\tsawUnsafeProfilePath = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!profilePath) continue;\n\t\t\tconst cookiesPath = join(profilePath, \"Cookies\");\n\t\t\tsawCookieDatabase = true;\n\n\t\t\tconst tempDir = mkdtempSync(join(tmpdir(), \"pi-chrome-cookies-\"));\n\t\t\ttry {\n\t\t\t\tconst tempDb = join(tempDir, \"Cookies\");\n\t\t\t\tcopyFileSync(cookiesPath, tempDb);\n\t\t\t\tcopySidecar(cookiesPath, tempDb, \"-wal\");\n\t\t\t\tcopySidecar(cookiesPath, tempDb, \"-shm\");\n\n\t\t\t\tif (requiredCookies?.length) {\n\t\t\t\t\tconst preflight = await hasCookieNames(tempDb, hosts, requiredCookies);\n\t\t\t\t\tif (preflight.failure) sawBackendFailure = preflight.failure;\n\t\t\t\t\tif (!preflight.present) continue;\n\t\t\t\t\tsawRequiredCookies = true;\n\t\t\t\t}\n\n\t\t\t\tconst password = await readBrowserPassword(config, currentPlatform);\n\t\t\t\tif (!password) {\n\t\t\t\t\twarningSet.add(`Could not read ${config.name} cookie encryption password`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tconst key = pbkdf2Sync(password, \"saltysalt\", currentPlatform === \"darwin\" ? 1003 : 1, 16, \"sha1\");\n\t\t\t\tconst metaVersion = await readMetaVersion(tempDb);\n\t\t\t\tif (metaVersion.failure) sawBackendFailure = metaVersion.failure;\n\t\t\t\tif (metaVersion.value === null) continue;\n\t\t\t\tconst rowsResult = await queryCookieRows(tempDb, hosts, ALL_COOKIE_NAMES);\n\t\t\t\tif (rowsResult.status === \"failure\") {\n\t\t\t\t\tsawBackendFailure = rowsResult.failure;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tconst cookies: CookieMap = {};\n\t\t\t\tfor (const row of rowsResult.rows) {\n\t\t\t\t\tconst name = typeof row.name === \"string\" ? row.name : \"\";\n\t\t\t\t\tif (!ALL_COOKIE_NAMES.has(name) || cookies[name]) continue;\n\t\t\t\t\tlet value = typeof row.value === \"string\" && row.value.length > 0 ? row.value : null;\n\t\t\t\t\tif (!value && typeof row.encrypted_value_hex === \"string\" && /^[0-9a-f]*$/i.test(row.encrypted_value_hex)) {\n\t\t\t\t\t\tvalue = decryptCookieValue(Buffer.from(row.encrypted_value_hex, \"hex\"), key, metaVersion.value >= 24);\n\t\t\t\t\t}\n\t\t\t\t\tif (value) cookies[name] = value;\n\t\t\t\t}\n\n\t\t\t\tif (requiredCookies?.length && !requiredCookies.every((name) => Boolean(cookies[name]))) continue;\n\t\t\t\treturn { cookies, warnings: [...warningSet] };\n\t\t\t} finally {\n\t\t\t\trmSync(tempDir, { recursive: true, force: true });\n\t\t\t}\n\t\t}\n\t}\n\n\tif (sawBackendFailure === \"unavailable\") {\n\t\tlastCookieDiagnostic = \"SQLite backend unavailable: install sqlite3 or use a runtime with SQLite support.\";\n\t} else if (sawBackendFailure === \"query\") {\n\t\tlastCookieDiagnostic = \"SQLite query failed while reading the copied Chromium cookie database.\";\n\t} else if (sawUnsafeProfilePath) {\n\t\tlastCookieDiagnostic = \"Configured Chromium profile must resolve inside the browser profile root.\";\n\t} else if (!sawCookieDatabase) {\n\t\tlastCookieDiagnostic = requestedProfile\n\t\t\t? `Chromium profile '${requestedProfile}' does not contain a cookie database.`\n\t\t\t: \"No detected Chromium profile contains a cookie database.\";\n\t} else if (requiredCookies?.length && !sawRequiredCookies) {\n\t\tlastCookieDiagnostic = \"No detected Chromium profile contains the required Gemini cookies.\";\n\t} else if (warningSet.size > 0) {\n\t\tlastCookieDiagnostic = [...warningSet][0];\n\t} else {\n\t\tlastCookieDiagnostic = \"Required Gemini cookies were not available or could not be decrypted.\";\n\t}\n\treturn null;\n}\n\nfunction normalizeProfileName(value: string | undefined): string | undefined {\n\tif (typeof value !== \"string\") return undefined;\n\tconst normalized = value.trim();\n\tif (!normalized) return undefined;\n\tif (isAbsolute(normalized) || normalized === \".\" || normalized === \"..\" || normalized.includes(\"/\") || normalized.includes(\"\\\\\")) {\n\t\treturn undefined;\n\t}\n\treturn normalized;\n}\n\nfunction resolveProfilePath(home: string, config: BrowserConfig, profile: string): string | \"outside-root\" | null {\n\tconst basePath = join(home, config.baseDir);\n\tconst profilePath = join(basePath, profile);\n\tconst cookiesPath = join(profilePath, \"Cookies\");\n\tif (!existsSync(cookiesPath)) return null;\n\ttry {\n\t\tconst baseRealPath = realpathSync(basePath);\n\t\tconst profileRealPath = realpathSync(profilePath);\n\t\tif (profileRealPath !== baseRealPath && !profileRealPath.startsWith(`${baseRealPath}${sep}`)) return \"outside-root\";\n\t\treturn profileRealPath;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction normalizeCookieNames(names: string[] | undefined): string[] | undefined {\n\tif (!names?.length) return undefined;\n\tconst normalized = names.filter((name): name is string => typeof name === \"string\").map((name) => name.trim()).filter(Boolean);\n\treturn normalized.length > 0 ? [...new Set(normalized)] : undefined;\n}\n\nfunction listBrowserProfiles(home: string, config: BrowserConfig): string[] {\n\tconst basePath = join(home, config.baseDir);\n\tif (!existsSync(basePath)) return [\"Default\"];\n\tconst profiles = new Set<string>();\n\ttry {\n\t\tfor (const entry of readdirSync(basePath, { withFileTypes: true })) {\n\t\t\tif (entry.isDirectory() && existsSync(join(basePath, entry.name, \"Cookies\"))) profiles.add(entry.name);\n\t\t}\n\t} catch {\n\t}\n\tif (profiles.size === 0) return [\"Default\"];\n\treturn [...profiles].sort(compareProfileNames);\n}\n\nfunction compareProfileNames(a: string, b: string): number {\n\tconst key = (name: string): [number, number] => {\n\t\tif (name === \"Default\") return [0, 0];\n\t\tconst profile = /^Profile\\s+(\\d+)$/i.exec(name);\n\t\tif (profile) return [1, Number(profile[1])];\n\t\tconst person = /^Person\\s+(\\d+)$/i.exec(name);\n\t\tif (person) return [2, Number(person[1])];\n\t\treturn [3, Number.MAX_SAFE_INTEGER];\n\t};\n\tconst [ap, ai] = key(a);\n\tconst [bp, bi] = key(b);\n\treturn ap - bp || ai - bi || a.localeCompare(b, undefined, { sensitivity: \"base\", numeric: true });\n}\n\nfunction decryptCookieValue(encrypted: Uint8Array, key: Buffer, stripHash: boolean): string | null {\n\tconst buf = Buffer.from(encrypted);\n\tif (buf.length < 3 || !/^v\\d\\d$/.test(buf.subarray(0, 3).toString(\"utf8\"))) return null;\n\tconst ciphertext = buf.subarray(3);\n\tif (!ciphertext.length) return \"\";\n\ttry {\n\t\tconst decipher = createDecipheriv(\"aes-128-cbc\", key, Buffer.alloc(16, 0x20));\n\t\tdecipher.setAutoPadding(false);\n\t\tconst unpadded = removePkcs7Padding(Buffer.concat([decipher.update(ciphertext), decipher.final()]));\n\t\tconst bytes = stripHash && unpadded.length >= 32 ? unpadded.subarray(32) : unpadded;\n\t\tconst decoded = new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n\t\tlet i = 0;\n\t\twhile (i < decoded.length && decoded.charCodeAt(i) < 0x20) i++;\n\t\treturn decoded.slice(i);\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction removePkcs7Padding(buf: Buffer): Buffer {\n\tif (!buf.length) return buf;\n\tconst padding = buf[buf.length - 1];\n\treturn !padding || padding > 16 ? buf : buf.subarray(0, buf.length - padding);\n}\n\nfunction readBrowserPassword(config: BrowserConfig, currentPlatform: ReturnType<typeof platform>): Promise<string | null> {\n\tconst cacheKey = `${currentPlatform}:${config.name}`;\n\tconst cached = browserPasswordCache.get(cacheKey);\n\tif (cached) return cached;\n\tconst passwordResult = currentPlatform === \"darwin\"\n\t\t? config.keychainAccount && config.keychainService\n\t\t\t? readKeychainPassword(config.keychainAccount, config.keychainService).then(password => ({ password, cacheable: Boolean(password) }))\n\t\t\t: Promise.resolve({ password: null, cacheable: false })\n\t\t: currentPlatform === \"linux\"\n\t\t\t? readLinuxPassword(config.secretToolApp)\n\t\t\t: Promise.resolve({ password: null, cacheable: false });\n\tconst passwordPromise = passwordResult.then(({ password, cacheable }) => {\n\t\tif (!cacheable) browserPasswordCache.delete(cacheKey);\n\t\treturn password;\n\t}, (error) => {\n\t\tbrowserPasswordCache.delete(cacheKey);\n\t\tthrow error;\n\t});\n\tbrowserPasswordCache.set(cacheKey, passwordPromise);\n\treturn passwordPromise;\n}\n\nfunction readKeychainPassword(account: string, service: string): Promise<string | null> {\n\treturn new Promise((resolve) => {\n\t\texecFile(\"security\", [\"find-generic-password\", \"-w\", \"-a\", account, \"-s\", service], { timeout: 5000 }, (err, stdout) => {\n\t\t\tif (err) { resolve(null); return; }\n\t\t\tresolve(stdout.trim() || null);\n\t\t});\n\t});\n}\n\nfunction readLinuxPassword(secretToolApp: string | undefined): Promise<{ password: string; cacheable: boolean }> {\n\tif (!secretToolApp) return Promise.resolve({ password: \"peanuts\", cacheable: true });\n\treturn new Promise((resolve) => {\n\t\texecFile(\"secret-tool\", [\"lookup\", \"application\", secretToolApp], { timeout: 5000 }, (err, stdout) => {\n\t\t\tif (err) { resolve({ password: \"peanuts\", cacheable: false }); return; }\n\t\t\tconst password = stdout.trim();\n\t\t\tresolve(password ? { password, cacheable: true } : { password: \"peanuts\", cacheable: false });\n\t\t});\n\t});\n}\n\nasync function importSqlite(): Promise<typeof import(\"node:sqlite\") | null> {\n\tif (process.env.PI_WEB_ACCESS_DISABLE_NODE_SQLITE === \"1\") return null;\n\tif (sqliteImportAttempted) return sqliteModule;\n\tsqliteImportAttempted = true;\n\tconst orig = process.emitWarning.bind(process);\n\tprocess.emitWarning = ((warning: string | Error, ...args: unknown[]) => {\n\t\tconst msg = typeof warning === \"string\" ? warning : warning?.message ?? \"\";\n\t\tif (msg.includes(\"SQLite is an experimental feature\")) return;\n\t\treturn (orig as Function)(warning, ...args);\n\t}) as typeof process.emitWarning;\n\ttry {\n\t\tsqliteModule = await import(\"node:sqlite\");\n\t} catch {\n\t\tsqliteModule = null;\n\t} finally {\n\t\tprocess.emitWarning = orig;\n\t}\n\treturn sqliteModule;\n}\n\ntype QueryResult =\n\t| { status: \"success\"; rows: SqliteRow[] }\n\t| { status: \"failure\"; failure: SqliteFailure };\n\nasync function runSqliteQuery(dbPath: string, sql: string): Promise<QueryResult> {\n\tconst sqlite = await importSqlite();\n\tlet queryFailed = false;\n\tif (sqlite) {\n\t\ttry {\n\t\t\tconst db = new sqlite.DatabaseSync(dbPath, { readOnly: true });\n\t\t\ttry {\n\t\t\t\treturn { status: \"success\", rows: db.prepare(sql).all() as SqliteRow[] };\n\t\t\t} finally {\n\t\t\t\tdb.close();\n\t\t\t}\n\t\t} catch {\n\t\t\tqueryFailed = true;\n\t\t}\n\t}\n\n\tconst cli = await runSqliteCli(dbPath, sql);\n\tif (cli.status === \"success\") return cli;\n\tif (cli.failure === \"query\") queryFailed = true;\n\tconst python = await runPythonSqlite(dbPath, sql);\n\tif (python.status === \"success\") return python;\n\tif (python.failure === \"query\") queryFailed = true;\n\treturn { status: \"failure\", failure: queryFailed ? \"query\" : \"unavailable\" };\n}\n\nfunction runSqliteCli(dbPath: string, sql: string): Promise<QueryResult> {\n\treturn new Promise((resolve) => {\n\t\texecFile(\"sqlite3\", [\"-readonly\", \"-json\", dbPath, sql], { timeout: 5000, maxBuffer: 1024 * 1024 }, (err, stdout) => {\n\t\t\tif (err) { resolve({ status: \"failure\", failure: err.code === \"ENOENT\" ? \"unavailable\" : \"query\" }); return; }\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse(stdout || \"[]\");\n\t\t\t\tresolve(Array.isArray(parsed) ? { status: \"success\", rows: parsed as SqliteRow[] } : { status: \"failure\", failure: \"query\" });\n\t\t\t} catch {\n\t\t\t\tresolve({ status: \"failure\", failure: \"query\" });\n\t\t\t}\n\t\t});\n\t});\n}\n\nfunction runPythonSqlite(dbPath: string, sql: string): Promise<QueryResult> {\n\tconst script = \"import json,sqlite3,sys\\ntry:\\n c=sqlite3.connect('file:'+sys.argv[1]+'?mode=ro',uri=True)\\n c.row_factory=sqlite3.Row\\n print(json.dumps([dict(r) for r in c.execute(sys.argv[2]).fetchall()]))\\nexcept Exception:\\n sys.exit(1)\";\n\treturn new Promise((resolve) => {\n\t\texecFile(\"python3\", [\"-c\", script, dbPath, sql], { timeout: 5000, maxBuffer: 1024 * 1024 }, (err, stdout) => {\n\t\t\tif (err) { resolve({ status: \"failure\", failure: err.code === \"ENOENT\" ? \"unavailable\" : \"query\" }); return; }\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse(stdout || \"[]\");\n\t\t\t\tresolve(Array.isArray(parsed) ? { status: \"success\", rows: parsed as SqliteRow[] } : { status: \"failure\", failure: \"query\" });\n\t\t\t} catch {\n\t\t\t\tresolve({ status: \"failure\", failure: \"query\" });\n\t\t\t}\n\t\t});\n\t});\n}\n\nasync function readMetaVersion(dbPath: string): Promise<{ value: number | null; failure?: SqliteFailure }> {\n\tconst result = await runSqliteQuery(dbPath, \"SELECT value FROM meta WHERE key = 'version'\");\n\tif (result.status === \"failure\") {\n\t\treturn result.failure === \"unavailable\"\n\t\t\t? { value: null, failure: result.failure }\n\t\t\t: { value: 0 };\n\t}\n\tconst value = result.rows[0]?.value;\n\tif (typeof value === \"number\") return { value: Math.floor(value) };\n\tif (typeof value === \"string\") return { value: parseInt(value, 10) || 0 };\n\treturn { value: 0 };\n}\n\nasync function hasCookieNames(dbPath: string, hosts: string[], names: string[]): Promise<{ present: boolean; failure?: SqliteFailure }> {\n\tconst result = await runSqliteQuery(dbPath, `SELECT DISTINCT name FROM cookies WHERE ${buildCookieWhere(hosts, names)}`);\n\tif (result.status === \"failure\") return { present: false, failure: result.failure };\n\tconst present = new Set(result.rows.map((row) => typeof row.name === \"string\" ? row.name : \"\"));\n\treturn { present: names.every((name) => present.has(name)) };\n}\n\nasync function queryCookieRows(dbPath: string, hosts: string[], names: Iterable<string>): Promise<QueryResult> {\n\treturn runSqliteQuery(dbPath, `SELECT name, value, host_key, hex(encrypted_value) AS encrypted_value_hex FROM cookies WHERE ${buildCookieWhere(hosts, names)} ORDER BY expires_utc DESC`);\n}\n\nfunction buildCookieWhere(hosts: string[], cookieNames?: Iterable<string>): string {\n\tconst hostClauses: string[] = [];\n\tfor (const host of hosts) {\n\t\tfor (const candidate of expandHosts(host)) {\n\t\t\tconst escaped = escapeSqlString(candidate);\n\t\t\thostClauses.push(`host_key = '${escaped}'`, `host_key = '.${escaped}'`, `host_key LIKE '%.${escaped}'`);\n\t\t}\n\t}\n\tlet where = `(${hostClauses.join(\" OR \")})`;\n\tconst names = cookieNames ? [...cookieNames].filter(Boolean) : [];\n\tif (names.length) where += ` AND name IN (${names.map((name) => `'${escapeSqlString(name)}'`).join(\", \")})`;\n\treturn where;\n}\n\nfunction escapeSqlString(value: string): string {\n\treturn value.replaceAll(\"'\", \"''\");\n}\n\nfunction expandHosts(host: string): string[] {\n\tconst parts = host.split(\".\").filter(Boolean);\n\tif (parts.length <= 1) return [host];\n\tconst candidates = new Set([host]);\n\tfor (let i = 1; i <= parts.length - 2; i++) candidates.add(parts.slice(i).join(\".\"));\n\treturn [...candidates];\n}\n\nfunction copySidecar(srcDb: string, targetDb: string, suffix: string): void {\n\tconst sidecar = `${srcDb}${suffix}`;\n\tif (!existsSync(sidecar)) return;\n\ttry {\n\t\tcopyFileSync(sidecar, `${targetDb}${suffix}`);\n\t} catch {\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"chrome-cookies.d.ts","sourceRoot":"","sources":["../../../../src/humain/web-access/vendor/chrome-cookies.ts"],"names":[],"mappings":"AAOA,MAAM,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAgD/C,wBAAgB,6BAA6B,IAAI,MAAM,GAAG,IAAI,CAE7D;AAED,wBAAgB,8BAA8B,IAAI,MAAM,GAAG,IAAI,CAE9D;AAED,wBAAsB,gBAAgB,CACrC,OAAO,CAAC,EAAE;IAAE,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,eAAe,CAAC,EAAE,MAAM,EAAE,CAAA;CAAE,GACxD,OAAO,CAAC;IAAE,OAAO,EAAE,SAAS,CAAC;IAAC,QAAQ,EAAE,MAAM,EAAE,CAAA;CAAE,GAAG,IAAI,CAAC,CAQ5D;AAED,wBAAsB,yBAAyB,CAC9C,OAAO,EAAE;IAAE,KAAK,EAAE,MAAM,EAAE,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;IAAC,WAAW,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC;IAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IAAC,UAAU,CAAC,EAAE,GAAG,CAAA;CAAE,GAClJ,OAAO,CAAC;IAAE,OAAO,EAAE,SAAS,CAAC;IAAC,QAAQ,EAAE,MAAM,EAAE,CAAC;IAAC,YAAY,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAAC,CAiInF","sourcesContent":["import { execFile } from \"node:child_process\";\nimport { pbkdf2Sync, createDecipheriv } from \"node:crypto\";\nimport { copyFileSync, existsSync, mkdtempSync, readdirSync, realpathSync, rmSync } from \"node:fs\";\nimport { tmpdir, homedir } from \"node:os\";\nimport { isAbsolute, join, sep } from \"node:path\";\nimport { isBrowserCookieAccessAllowed } from \"./gemini-web-config.ts\";\n\nexport type CookieMap = Record<string, string>;\n\ninterface BrowserConfig {\n\tname: string;\n\tbaseDir: string;\n\tkeychainService?: string;\n\tkeychainAccount?: string;\n\tsecretToolApp?: string;\n}\n\ntype SqliteRow = Record<string, unknown>;\ntype SqliteFailure = \"unavailable\" | \"query\";\n\ninterface BrowserCookieEntry {\n\tname: string;\n\tvalue: string;\n\tpath: string;\n}\n\nconst GOOGLE_ORIGINS = [\n\t\"https://gemini.google.com\",\n\t\"https://accounts.google.com\",\n\t\"https://www.google.com\",\n];\n\nconst ALL_COOKIE_NAMES = new Set([\n\t\"__Secure-1PSID\", \"__Secure-1PSIDTS\", \"__Secure-1PSIDCC\", \"__Secure-1PAPISID\", \"NID\", \"AEC\", \"SOCS\",\n\t\"__Secure-BUCKET\", \"__Secure-ENID\", \"SID\", \"HSID\", \"SSID\", \"APISID\", \"SAPISID\", \"__Secure-3PSID\",\n\t\"__Secure-3PSIDTS\", \"__Secure-3PAPISID\", \"SIDCC\",\n]);\n\nconst MACOS_BROWSER_CONFIGS: BrowserConfig[] = [\n\t{ name: \"Helium\", baseDir: \"Library/Application Support/net.imput.helium\", keychainService: \"Helium Storage Key\", keychainAccount: \"Helium\" },\n\t{ name: \"Chrome\", baseDir: \"Library/Application Support/Google/Chrome\", keychainService: \"Chrome Safe Storage\", keychainAccount: \"Chrome\" },\n\t{ name: \"Brave\", baseDir: \"Library/Application Support/BraveSoftware/Brave-Browser\", keychainService: \"Brave Safe Storage\", keychainAccount: \"Brave\" },\n\t{ name: \"Arc\", baseDir: \"Library/Application Support/Arc/User Data\", keychainService: \"Arc Safe Storage\", keychainAccount: \"Arc\" },\n];\n\nconst LINUX_BROWSER_CONFIGS: BrowserConfig[] = [\n\t{ name: \"Chromium\", baseDir: \".config/chromium\", secretToolApp: \"chromium\" },\n\t{ name: \"Chrome\", baseDir: \".config/google-chrome\", secretToolApp: \"chrome\" },\n];\n\nconst browserPasswordCache = new Map<string, Promise<string | null>>();\nlet lastCookieDiagnostic: string | null = null;\nlet sqliteModule: typeof import(\"node:sqlite\") | null = null;\nlet sqliteImportAttempted = false;\n\nexport function getLastGoogleCookieDiagnostic(): string | null {\n\treturn lastCookieDiagnostic;\n}\n\nexport function getLastBrowserCookieDiagnostic(): string | null {\n\treturn lastCookieDiagnostic;\n}\n\nexport async function getGoogleCookies(\n\toptions?: { profile?: string; requiredCookies?: string[] },\n): Promise<{ cookies: CookieMap; warnings: string[] } | null> {\n\treturn getBrowserCookiesForHosts({\n\t\thosts: GOOGLE_ORIGINS.map((origin) => new URL(origin).hostname),\n\t\tprofile: options?.profile,\n\t\trequiredCookies: options?.requiredCookies,\n\t\tcookieNames: ALL_COOKIE_NAMES,\n\t\trequiredLabel: \"Gemini\",\n\t});\n}\n\nexport async function getBrowserCookiesForHosts(\n\toptions: { hosts: string[]; profile?: string; requiredCookies?: string[]; cookieNames?: Iterable<string>; requiredLabel?: string; requestUrl?: URL },\n): Promise<{ cookies: CookieMap; warnings: string[]; cookieHeader?: string } | null> {\n\tlastCookieDiagnostic = null;\n\tif (!isBrowserCookieAccessAllowed()) {\n\t\tlastCookieDiagnostic = \"Browser cookie access is disabled; enable allowBrowserCookies to use browser cookies.\";\n\t\treturn null;\n\t}\n\n\tconst currentPlatform = process.platform;\n\tconst configs = currentPlatform === \"darwin\" ? MACOS_BROWSER_CONFIGS : currentPlatform === \"linux\" ? LINUX_BROWSER_CONFIGS : [];\n\tif (configs.length === 0) {\n\t\tlastCookieDiagnostic = \"Chromium cookie extraction is unsupported on this platform.\";\n\t\treturn null;\n\t}\n\n\tconst warningSet = new Set<string>();\n\tconst rawProfile = typeof options.profile === \"string\" ? options.profile.trim() : \"\";\n\tconst requestedProfile = normalizeProfileName(options.profile);\n\tif (rawProfile && !requestedProfile) {\n\t\tlastCookieDiagnostic = \"Configured Chromium profile must be a profile directory name, not a path.\";\n\t\treturn null;\n\t}\n\tconst requiredCookies = normalizeCookieNames(options.requiredCookies);\n\tconst cookieNames = normalizeCookieNames(options.cookieNames ? [...options.cookieNames] : undefined);\n\tconst hosts = normalizeHosts(options.hosts);\n\tif (hosts.length === 0) {\n\t\tlastCookieDiagnostic = \"No valid cookie hosts were requested.\";\n\t\treturn null;\n\t}\n\tconst home = homedir();\n\tlet sawCookieDatabase = false;\n\tlet sawRequiredCookies = false;\n\tlet sawAnyHostCookie = false;\n\tlet sawBackendFailure: SqliteFailure | undefined;\n\tlet sawUnsafeProfilePath = false;\n\n\tfor (const config of configs) {\n\t\tconst profiles = requestedProfile ? [requestedProfile] : listBrowserProfiles(home, config);\n\t\tfor (const profile of profiles) {\n\t\t\tconst profilePath = resolveProfilePath(home, config, profile);\n\t\t\tif (profilePath === \"outside-root\") {\n\t\t\t\tsawUnsafeProfilePath = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!profilePath) continue;\n\t\t\tconst cookiesPath = join(profilePath, \"Cookies\");\n\t\t\tsawCookieDatabase = true;\n\n\t\t\tconst tempDir = mkdtempSync(join(tmpdir(), \"pi-chrome-cookies-\"));\n\t\t\ttry {\n\t\t\t\tconst tempDb = join(tempDir, \"Cookies\");\n\t\t\t\tcopyFileSync(cookiesPath, tempDb);\n\t\t\t\tcopySidecar(cookiesPath, tempDb, \"-wal\");\n\t\t\t\tcopySidecar(cookiesPath, tempDb, \"-shm\");\n\n\t\t\t\tif (requiredCookies?.length) {\n\t\t\t\t\tconst preflight = await hasCookieNames(tempDb, hosts, requiredCookies);\n\t\t\t\t\tif (preflight.failure) sawBackendFailure = preflight.failure;\n\t\t\t\t\tif (!preflight.present) continue;\n\t\t\t\t\tsawRequiredCookies = true;\n\t\t\t\t}\n\n\t\t\t\tconst password = await readBrowserPassword(config, currentPlatform);\n\t\t\t\tif (!password) {\n\t\t\t\t\twarningSet.add(`Could not read ${config.name} cookie encryption password`);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tconst key = pbkdf2Sync(password, \"saltysalt\", currentPlatform === \"darwin\" ? 1003 : 1, 16, \"sha1\");\n\t\t\t\tconst metaVersion = await readMetaVersion(tempDb);\n\t\t\t\tif (metaVersion.failure) sawBackendFailure = metaVersion.failure;\n\t\t\t\tif (metaVersion.value === null) continue;\n\t\t\t\tconst rowsResult = await queryCookieRows(tempDb, hosts, cookieNames ?? null, Boolean(options.requestUrl));\n\t\t\t\tif (rowsResult.status === \"failure\") {\n\t\t\t\t\tsawBackendFailure = rowsResult.failure;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tconst entries: BrowserCookieEntry[] = [];\n\t\t\t\tconst cookies: CookieMap = {};\n\t\t\t\tfor (const row of rowsResult.rows) {\n\t\t\t\t\tconst name = typeof row.name === \"string\" ? row.name : \"\";\n\t\t\t\t\tif (!name) continue;\n\t\t\t\t\tlet value = typeof row.value === \"string\" && row.value.length > 0 ? row.value : null;\n\t\t\t\t\tif (!value && typeof row.encrypted_value_hex === \"string\" && /^[0-9a-f]*$/i.test(row.encrypted_value_hex)) {\n\t\t\t\t\t\tvalue = decryptCookieValue(Buffer.from(row.encrypted_value_hex, \"hex\"), key, metaVersion.value >= 24);\n\t\t\t\t\t}\n\t\t\t\t\tif (!value) continue;\n\t\t\t\t\tconst path = typeof row.path === \"string\" && row.path.startsWith(\"/\") ? row.path : \"/\";\n\t\t\t\t\tif (options.requestUrl && !pathMatches(options.requestUrl.pathname || \"/\", path)) continue;\n\t\t\t\t\tentries.push({ name, value, path });\n\t\t\t\t\tif (!cookies[name]) cookies[name] = value;\n\t\t\t\t}\n\n\t\t\t\tif (entries.length > 0) sawAnyHostCookie = true;\n\t\t\t\tif (requiredCookies?.length && !requiredCookies.every((name) => Boolean(cookies[name]))) continue;\n\t\t\t\tif (entries.length === 0) continue;\n\t\t\t\treturn {\n\t\t\t\t\tcookies,\n\t\t\t\t\twarnings: [...warningSet],\n\t\t\t\t\t...(options.requestUrl ? { cookieHeader: buildCookieHeader(entries) } : {}),\n\t\t\t\t};\n\t\t\t} finally {\n\t\t\t\trmSync(tempDir, { recursive: true, force: true });\n\t\t\t}\n\t\t}\n\t}\n\n\tif (sawBackendFailure === \"unavailable\") {\n\t\tlastCookieDiagnostic = \"SQLite backend unavailable: install sqlite3 or use a runtime with SQLite support.\";\n\t} else if (sawBackendFailure === \"query\") {\n\t\tlastCookieDiagnostic = \"SQLite query failed while reading the copied Chromium cookie database.\";\n\t} else if (sawUnsafeProfilePath) {\n\t\tlastCookieDiagnostic = \"Configured Chromium profile must resolve inside the browser profile root.\";\n\t} else if (!sawCookieDatabase) {\n\t\tlastCookieDiagnostic = requestedProfile\n\t\t\t? `Chromium profile '${requestedProfile}' does not contain a cookie database.`\n\t\t\t: \"No detected Chromium profile contains a cookie database.\";\n\t} else if (requiredCookies?.length && !sawRequiredCookies) {\n\t\tlastCookieDiagnostic = `No detected Chromium profile contains the required ${options.requiredLabel ?? \"browser\"} cookies.`;\n\t} else if (!sawAnyHostCookie) {\n\t\tlastCookieDiagnostic = options.requestUrl\n\t\t\t? \"No detected Chromium profile contains cookies for the requested URL.\"\n\t\t\t: \"No detected Chromium profile contains cookies for the requested host.\";\n\t} else if (warningSet.size > 0) {\n\t\tlastCookieDiagnostic = [...warningSet][0];\n\t} else {\n\t\tlastCookieDiagnostic = \"Required Gemini cookies were not available or could not be decrypted.\";\n\t}\n\treturn null;\n}\n\nfunction normalizeProfileName(value: string | undefined): string | undefined {\n\tif (typeof value !== \"string\") return undefined;\n\tconst normalized = value.trim();\n\tif (!normalized) return undefined;\n\tif (isAbsolute(normalized) || normalized === \".\" || normalized === \"..\" || normalized.includes(\"/\") || normalized.includes(\"\\\\\")) {\n\t\treturn undefined;\n\t}\n\treturn normalized;\n}\n\nfunction resolveProfilePath(home: string, config: BrowserConfig, profile: string): string | \"outside-root\" | null {\n\tconst basePath = join(home, config.baseDir);\n\tconst profilePath = join(basePath, profile);\n\tconst cookiesPath = join(profilePath, \"Cookies\");\n\tif (!existsSync(cookiesPath)) return null;\n\ttry {\n\t\tconst baseRealPath = realpathSync(basePath);\n\t\tconst profileRealPath = realpathSync(profilePath);\n\t\tif (profileRealPath !== baseRealPath && !profileRealPath.startsWith(`${baseRealPath}${sep}`)) return \"outside-root\";\n\t\treturn profileRealPath;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction normalizeCookieNames(names: string[] | undefined): string[] | undefined {\n\tif (!names?.length) return undefined;\n\tconst normalized = names.filter((name): name is string => typeof name === \"string\").map((name) => name.trim()).filter(Boolean);\n\treturn normalized.length > 0 ? [...new Set(normalized)] : undefined;\n}\n\nfunction normalizeHosts(hosts: string[]): string[] {\n\treturn [...new Set(hosts.map(host => host.trim().toLowerCase().replace(/^\\[|\\]$/g, \"\").replace(/\\.$/, \"\")).filter(Boolean))];\n}\n\nfunction listBrowserProfiles(home: string, config: BrowserConfig): string[] {\n\tconst basePath = join(home, config.baseDir);\n\tif (!existsSync(basePath)) return [\"Default\"];\n\tconst profiles = new Set<string>();\n\ttry {\n\t\tfor (const entry of readdirSync(basePath, { withFileTypes: true })) {\n\t\t\tif (entry.isDirectory() && existsSync(join(basePath, entry.name, \"Cookies\"))) profiles.add(entry.name);\n\t\t}\n\t} catch {\n\t}\n\tif (profiles.size === 0) return [\"Default\"];\n\treturn [...profiles].sort(compareProfileNames);\n}\n\nfunction compareProfileNames(a: string, b: string): number {\n\tconst key = (name: string): [number, number] => {\n\t\tif (name === \"Default\") return [0, 0];\n\t\tconst profile = /^Profile\\s+(\\d+)$/i.exec(name);\n\t\tif (profile) return [1, Number(profile[1])];\n\t\tconst person = /^Person\\s+(\\d+)$/i.exec(name);\n\t\tif (person) return [2, Number(person[1])];\n\t\treturn [3, Number.MAX_SAFE_INTEGER];\n\t};\n\tconst [ap, ai] = key(a);\n\tconst [bp, bi] = key(b);\n\treturn ap - bp || ai - bi || a.localeCompare(b, undefined, { sensitivity: \"base\", numeric: true });\n}\n\nfunction decryptCookieValue(encrypted: Uint8Array, key: Buffer, stripHash: boolean): string | null {\n\tconst buf = Buffer.from(encrypted);\n\tif (buf.length < 3 || !/^v\\d\\d$/.test(buf.subarray(0, 3).toString(\"utf8\"))) return null;\n\tconst ciphertext = buf.subarray(3);\n\tif (!ciphertext.length) return \"\";\n\ttry {\n\t\tconst decipher = createDecipheriv(\"aes-128-cbc\", key, Buffer.alloc(16, 0x20));\n\t\tdecipher.setAutoPadding(false);\n\t\tconst unpadded = removePkcs7Padding(Buffer.concat([decipher.update(ciphertext), decipher.final()]));\n\t\tconst bytes = stripHash && unpadded.length >= 32 ? unpadded.subarray(32) : unpadded;\n\t\tconst decoded = new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n\t\tlet i = 0;\n\t\twhile (i < decoded.length && decoded.charCodeAt(i) < 0x20) i++;\n\t\treturn decoded.slice(i);\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction removePkcs7Padding(buf: Buffer): Buffer {\n\tif (!buf.length) return buf;\n\tconst padding = buf[buf.length - 1];\n\treturn !padding || padding > 16 ? buf : buf.subarray(0, buf.length - padding);\n}\n\nfunction readBrowserPassword(config: BrowserConfig, currentPlatform: typeof process.platform): Promise<string | null> {\n\tconst cacheKey = `${currentPlatform}:${config.name}`;\n\tconst cached = browserPasswordCache.get(cacheKey);\n\tif (cached) return cached;\n\tconst passwordResult = currentPlatform === \"darwin\"\n\t\t? config.keychainAccount && config.keychainService\n\t\t\t? readKeychainPassword(config.keychainAccount, config.keychainService).then(password => ({ password, cacheable: Boolean(password) }))\n\t\t\t: Promise.resolve({ password: null, cacheable: false })\n\t\t: currentPlatform === \"linux\"\n\t\t\t? readLinuxPassword(config.secretToolApp)\n\t\t\t: Promise.resolve({ password: null, cacheable: false });\n\tconst passwordPromise = passwordResult.then(({ password, cacheable }) => {\n\t\tif (!cacheable) browserPasswordCache.delete(cacheKey);\n\t\treturn password;\n\t}, (error) => {\n\t\tbrowserPasswordCache.delete(cacheKey);\n\t\tthrow error;\n\t});\n\tbrowserPasswordCache.set(cacheKey, passwordPromise);\n\treturn passwordPromise;\n}\n\nfunction readKeychainPassword(account: string, service: string): Promise<string | null> {\n\treturn new Promise((resolve) => {\n\t\texecFile(\"security\", [\"find-generic-password\", \"-w\", \"-a\", account, \"-s\", service], { timeout: 5000 }, (err, stdout) => {\n\t\t\tif (err) { resolve(null); return; }\n\t\t\tresolve(stdout.trim() || null);\n\t\t});\n\t});\n}\n\nfunction readLinuxPassword(secretToolApp: string | undefined): Promise<{ password: string; cacheable: boolean }> {\n\tif (!secretToolApp) return Promise.resolve({ password: \"peanuts\", cacheable: true });\n\treturn new Promise((resolve) => {\n\t\texecFile(\"secret-tool\", [\"lookup\", \"application\", secretToolApp], { timeout: 5000 }, (err, stdout) => {\n\t\t\tif (err) { resolve({ password: \"peanuts\", cacheable: false }); return; }\n\t\t\tconst password = stdout.trim();\n\t\t\tresolve(password ? { password, cacheable: true } : { password: \"peanuts\", cacheable: false });\n\t\t});\n\t});\n}\n\nasync function importSqlite(): Promise<typeof import(\"node:sqlite\") | null> {\n\tif (process.env.PI_WEB_ACCESS_DISABLE_NODE_SQLITE === \"1\") return null;\n\tif (sqliteImportAttempted) return sqliteModule;\n\tsqliteImportAttempted = true;\n\tconst orig = process.emitWarning.bind(process);\n\tprocess.emitWarning = ((warning: string | Error, ...args: unknown[]) => {\n\t\tconst msg = typeof warning === \"string\" ? warning : warning?.message ?? \"\";\n\t\tif (msg.includes(\"SQLite is an experimental feature\")) return;\n\t\treturn (orig as Function)(warning, ...args);\n\t}) as typeof process.emitWarning;\n\ttry {\n\t\tsqliteModule = await import(\"node:sqlite\");\n\t} catch {\n\t\tsqliteModule = null;\n\t} finally {\n\t\tprocess.emitWarning = orig;\n\t}\n\treturn sqliteModule;\n}\n\ntype QueryResult =\n\t| { status: \"success\"; rows: SqliteRow[] }\n\t| { status: \"failure\"; failure: SqliteFailure };\n\nasync function runSqliteQuery(dbPath: string, sql: string): Promise<QueryResult> {\n\tconst sqlite = await importSqlite();\n\tlet queryFailed = false;\n\tif (sqlite) {\n\t\ttry {\n\t\t\tconst db = new sqlite.DatabaseSync(dbPath, { readOnly: true });\n\t\t\ttry {\n\t\t\t\treturn { status: \"success\", rows: db.prepare(sql).all() as SqliteRow[] };\n\t\t\t} finally {\n\t\t\t\tdb.close();\n\t\t\t}\n\t\t} catch {\n\t\t\tqueryFailed = true;\n\t\t}\n\t}\n\n\tconst cli = await runSqliteCli(dbPath, sql);\n\tif (cli.status === \"success\") return cli;\n\tif (cli.failure === \"query\") queryFailed = true;\n\tconst python = await runPythonSqlite(dbPath, sql);\n\tif (python.status === \"success\") return python;\n\tif (python.failure === \"query\") queryFailed = true;\n\treturn { status: \"failure\", failure: queryFailed ? \"query\" : \"unavailable\" };\n}\n\nfunction runSqliteCli(dbPath: string, sql: string): Promise<QueryResult> {\n\treturn new Promise((resolve) => {\n\t\texecFile(\"sqlite3\", [\"-readonly\", \"-json\", dbPath, sql], { timeout: 5000, maxBuffer: 1024 * 1024 }, (err, stdout) => {\n\t\t\tif (err) { resolve({ status: \"failure\", failure: err.code === \"ENOENT\" ? \"unavailable\" : \"query\" }); return; }\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse(stdout || \"[]\");\n\t\t\t\tresolve(Array.isArray(parsed) ? { status: \"success\", rows: parsed as SqliteRow[] } : { status: \"failure\", failure: \"query\" });\n\t\t\t} catch {\n\t\t\t\tresolve({ status: \"failure\", failure: \"query\" });\n\t\t\t}\n\t\t});\n\t});\n}\n\nfunction runPythonSqlite(dbPath: string, sql: string): Promise<QueryResult> {\n\tconst script = \"import json,sqlite3,sys\\ntry:\\n c=sqlite3.connect('file:'+sys.argv[1]+'?mode=ro',uri=True)\\n c.row_factory=sqlite3.Row\\n print(json.dumps([dict(r) for r in c.execute(sys.argv[2]).fetchall()]))\\nexcept Exception:\\n sys.exit(1)\";\n\treturn new Promise((resolve) => {\n\t\texecFile(\"python3\", [\"-c\", script, dbPath, sql], { timeout: 5000, maxBuffer: 1024 * 1024 }, (err, stdout) => {\n\t\t\tif (err) { resolve({ status: \"failure\", failure: err.code === \"ENOENT\" ? \"unavailable\" : \"query\" }); return; }\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse(stdout || \"[]\");\n\t\t\t\tresolve(Array.isArray(parsed) ? { status: \"success\", rows: parsed as SqliteRow[] } : { status: \"failure\", failure: \"query\" });\n\t\t\t} catch {\n\t\t\t\tresolve({ status: \"failure\", failure: \"query\" });\n\t\t\t}\n\t\t});\n\t});\n}\n\nasync function readMetaVersion(dbPath: string): Promise<{ value: number | null; failure?: SqliteFailure }> {\n\tconst result = await runSqliteQuery(dbPath, \"SELECT value FROM meta WHERE key = 'version'\");\n\tif (result.status === \"failure\") {\n\t\treturn result.failure === \"unavailable\"\n\t\t\t? { value: null, failure: result.failure }\n\t\t\t: { value: 0 };\n\t}\n\tconst value = result.rows[0]?.value;\n\tif (typeof value === \"number\") return { value: Math.floor(value) };\n\tif (typeof value === \"string\") return { value: parseInt(value, 10) || 0 };\n\treturn { value: 0 };\n}\n\nasync function hasCookieNames(dbPath: string, hosts: string[], names: string[]): Promise<{ present: boolean; failure?: SqliteFailure }> {\n\tconst result = await runSqliteQuery(dbPath, `SELECT DISTINCT name FROM cookies WHERE ${buildCookieWhere(hosts, names)}`);\n\tif (result.status === \"failure\") return { present: false, failure: result.failure };\n\tconst present = new Set(result.rows.map((row) => typeof row.name === \"string\" ? row.name : \"\"));\n\treturn { present: names.every((name) => present.has(name)) };\n}\n\nasync function queryCookieRows(dbPath: string, hosts: string[], names: Iterable<string> | null, filterExpired: boolean): Promise<QueryResult> {\n\tconst columns = await readCookieColumns(dbPath);\n\tif (columns.status === \"failure\") return columns;\n\tconst pathExpr = columns.columns.has(\"path\") ? \"path\" : \"'/' AS path\";\n\tconst expiresExpr = columns.columns.has(\"expires_utc\") ? \"expires_utc\" : \"0 AS expires_utc\";\n\tconst expiryFilter = filterExpired && columns.columns.has(\"expires_utc\") ? ` AND (expires_utc = 0 OR expires_utc > ${chromeExpiryNowMicros()})` : \"\";\n\tconst partitionFilter = filterExpired ? unpartitionedCookieFilter(columns.columns) : \"\";\n\treturn runSqliteQuery(dbPath, `SELECT name, value, host_key, ${pathExpr}, ${expiresExpr}, hex(encrypted_value) AS encrypted_value_hex FROM cookies WHERE ${buildCookieWhere(hosts, names ?? undefined)}${expiryFilter}${partitionFilter} ORDER BY length(path) DESC, expires_utc ASC`);\n}\n\nasync function readCookieColumns(dbPath: string): Promise<{ status: \"success\"; columns: Set<string> } | { status: \"failure\"; failure: SqliteFailure }> {\n\tconst result = await runSqliteQuery(dbPath, \"PRAGMA table_info(cookies)\");\n\tif (result.status === \"failure\") return result;\n\treturn { status: \"success\", columns: new Set(result.rows.map(row => typeof row.name === \"string\" ? row.name : \"\")) };\n}\n\nfunction chromeExpiryNowMicros(): number {\n\treturn (Date.now() + 11644473600000) * 1000;\n}\n\nfunction unpartitionedCookieFilter(columns: Set<string>): string {\n\tconst clauses: string[] = [];\n\tif (columns.has(\"top_frame_site_key\")) clauses.push(\"(top_frame_site_key IS NULL OR top_frame_site_key = '')\");\n\tif (columns.has(\"partition_key\")) clauses.push(\"(partition_key IS NULL OR partition_key = '')\");\n\tif (columns.has(\"is_partitioned\")) clauses.push(\"(is_partitioned IS NULL OR is_partitioned = 0)\");\n\treturn clauses.length > 0 ? ` AND ${clauses.join(\" AND \")}` : \"\";\n}\n\nfunction buildCookieHeader(entries: BrowserCookieEntry[]): string {\n\treturn entries\n\t\t.sort((a, b) => b.path.length - a.path.length)\n\t\t.map(({ name, value }) => `${name}=${value}`)\n\t\t.join(\"; \");\n}\n\nfunction pathMatches(requestPath: string, cookiePath: string): boolean {\n\tif (requestPath === cookiePath) return true;\n\tif (!requestPath.startsWith(cookiePath)) return false;\n\tif (cookiePath.endsWith(\"/\")) return true;\n\treturn requestPath[cookiePath.length] === \"/\";\n}\n\nfunction buildCookieWhere(hosts: string[], cookieNames?: Iterable<string>): string {\n\tconst hostClauses: string[] = [];\n\tfor (const host of hosts) {\n\t\tconst escapedHost = escapeSqlString(host);\n\t\thostClauses.push(`host_key = '${escapedHost}'`);\n\t\tfor (const candidate of domainCookieHosts(host)) {\n\t\t\thostClauses.push(`host_key = '.${escapeSqlString(candidate)}'`);\n\t\t}\n\t}\n\tlet where = `(${[...new Set(hostClauses)].join(\" OR \")})`;\n\tconst names = cookieNames ? [...cookieNames].filter(Boolean) : [];\n\tif (names.length) where += ` AND name IN (${names.map((name) => `'${escapeSqlString(name)}'`).join(\", \")})`;\n\treturn where;\n}\n\nfunction escapeSqlString(value: string): string {\n\treturn value.replaceAll(\"'\", \"''\");\n}\n\nfunction domainCookieHosts(host: string): string[] {\n\tconst parts = host.split(\".\").filter(Boolean);\n\tif (parts.length <= 1) return [];\n\tconst candidates = new Set<string>();\n\tfor (let i = 0; i <= parts.length - 2; i++) candidates.add(parts.slice(i).join(\".\"));\n\treturn [...candidates];\n}\n\nfunction copySidecar(srcDb: string, targetDb: string, suffix: string): void {\n\tconst sidecar = `${srcDb}${suffix}`;\n\tif (!existsSync(sidecar)) return;\n\ttry {\n\t\tcopyFileSync(sidecar, `${targetDb}${suffix}`);\n\t} catch {\n\t}\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { execFile } from "node:child_process";
|
|
2
2
|
import { pbkdf2Sync, createDecipheriv } from "node:crypto";
|
|
3
3
|
import { copyFileSync, existsSync, mkdtempSync, readdirSync, realpathSync, rmSync } from "node:fs";
|
|
4
|
-
import { tmpdir, homedir
|
|
4
|
+
import { tmpdir, homedir } from "node:os";
|
|
5
5
|
import { isAbsolute, join, sep } from "node:path";
|
|
6
6
|
import { isBrowserCookieAccessAllowed } from "./gemini-web-config.js";
|
|
7
7
|
const GOOGLE_ORIGINS = [
|
|
@@ -17,6 +17,7 @@ const ALL_COOKIE_NAMES = new Set([
|
|
|
17
17
|
const MACOS_BROWSER_CONFIGS = [
|
|
18
18
|
{ name: "Helium", baseDir: "Library/Application Support/net.imput.helium", keychainService: "Helium Storage Key", keychainAccount: "Helium" },
|
|
19
19
|
{ name: "Chrome", baseDir: "Library/Application Support/Google/Chrome", keychainService: "Chrome Safe Storage", keychainAccount: "Chrome" },
|
|
20
|
+
{ name: "Brave", baseDir: "Library/Application Support/BraveSoftware/Brave-Browser", keychainService: "Brave Safe Storage", keychainAccount: "Brave" },
|
|
20
21
|
{ name: "Arc", baseDir: "Library/Application Support/Arc/User Data", keychainService: "Arc Safe Storage", keychainAccount: "Arc" },
|
|
21
22
|
];
|
|
22
23
|
const LINUX_BROWSER_CONFIGS = [
|
|
@@ -30,30 +31,48 @@ let sqliteImportAttempted = false;
|
|
|
30
31
|
export function getLastGoogleCookieDiagnostic() {
|
|
31
32
|
return lastCookieDiagnostic;
|
|
32
33
|
}
|
|
34
|
+
export function getLastBrowserCookieDiagnostic() {
|
|
35
|
+
return lastCookieDiagnostic;
|
|
36
|
+
}
|
|
33
37
|
export async function getGoogleCookies(options) {
|
|
38
|
+
return getBrowserCookiesForHosts({
|
|
39
|
+
hosts: GOOGLE_ORIGINS.map((origin) => new URL(origin).hostname),
|
|
40
|
+
profile: options?.profile,
|
|
41
|
+
requiredCookies: options?.requiredCookies,
|
|
42
|
+
cookieNames: ALL_COOKIE_NAMES,
|
|
43
|
+
requiredLabel: "Gemini",
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
export async function getBrowserCookiesForHosts(options) {
|
|
34
47
|
lastCookieDiagnostic = null;
|
|
35
48
|
if (!isBrowserCookieAccessAllowed()) {
|
|
36
|
-
lastCookieDiagnostic = "Browser cookie access is disabled; enable allowBrowserCookies to use
|
|
49
|
+
lastCookieDiagnostic = "Browser cookie access is disabled; enable allowBrowserCookies to use browser cookies.";
|
|
37
50
|
return null;
|
|
38
51
|
}
|
|
39
|
-
const currentPlatform = platform
|
|
52
|
+
const currentPlatform = process.platform;
|
|
40
53
|
const configs = currentPlatform === "darwin" ? MACOS_BROWSER_CONFIGS : currentPlatform === "linux" ? LINUX_BROWSER_CONFIGS : [];
|
|
41
54
|
if (configs.length === 0) {
|
|
42
55
|
lastCookieDiagnostic = "Chromium cookie extraction is unsupported on this platform.";
|
|
43
56
|
return null;
|
|
44
57
|
}
|
|
45
58
|
const warningSet = new Set();
|
|
46
|
-
const rawProfile = typeof options
|
|
47
|
-
const requestedProfile = normalizeProfileName(options
|
|
59
|
+
const rawProfile = typeof options.profile === "string" ? options.profile.trim() : "";
|
|
60
|
+
const requestedProfile = normalizeProfileName(options.profile);
|
|
48
61
|
if (rawProfile && !requestedProfile) {
|
|
49
62
|
lastCookieDiagnostic = "Configured Chromium profile must be a profile directory name, not a path.";
|
|
50
63
|
return null;
|
|
51
64
|
}
|
|
52
|
-
const requiredCookies = normalizeCookieNames(options
|
|
53
|
-
const
|
|
65
|
+
const requiredCookies = normalizeCookieNames(options.requiredCookies);
|
|
66
|
+
const cookieNames = normalizeCookieNames(options.cookieNames ? [...options.cookieNames] : undefined);
|
|
67
|
+
const hosts = normalizeHosts(options.hosts);
|
|
68
|
+
if (hosts.length === 0) {
|
|
69
|
+
lastCookieDiagnostic = "No valid cookie hosts were requested.";
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
54
72
|
const home = homedir();
|
|
55
73
|
let sawCookieDatabase = false;
|
|
56
74
|
let sawRequiredCookies = false;
|
|
75
|
+
let sawAnyHostCookie = false;
|
|
57
76
|
let sawBackendFailure;
|
|
58
77
|
let sawUnsafeProfilePath = false;
|
|
59
78
|
for (const config of configs) {
|
|
@@ -93,26 +112,41 @@ export async function getGoogleCookies(options) {
|
|
|
93
112
|
sawBackendFailure = metaVersion.failure;
|
|
94
113
|
if (metaVersion.value === null)
|
|
95
114
|
continue;
|
|
96
|
-
const rowsResult = await queryCookieRows(tempDb, hosts,
|
|
115
|
+
const rowsResult = await queryCookieRows(tempDb, hosts, cookieNames ?? null, Boolean(options.requestUrl));
|
|
97
116
|
if (rowsResult.status === "failure") {
|
|
98
117
|
sawBackendFailure = rowsResult.failure;
|
|
99
118
|
continue;
|
|
100
119
|
}
|
|
120
|
+
const entries = [];
|
|
101
121
|
const cookies = {};
|
|
102
122
|
for (const row of rowsResult.rows) {
|
|
103
123
|
const name = typeof row.name === "string" ? row.name : "";
|
|
104
|
-
if (!
|
|
124
|
+
if (!name)
|
|
105
125
|
continue;
|
|
106
126
|
let value = typeof row.value === "string" && row.value.length > 0 ? row.value : null;
|
|
107
127
|
if (!value && typeof row.encrypted_value_hex === "string" && /^[0-9a-f]*$/i.test(row.encrypted_value_hex)) {
|
|
108
128
|
value = decryptCookieValue(Buffer.from(row.encrypted_value_hex, "hex"), key, metaVersion.value >= 24);
|
|
109
129
|
}
|
|
110
|
-
if (value)
|
|
130
|
+
if (!value)
|
|
131
|
+
continue;
|
|
132
|
+
const path = typeof row.path === "string" && row.path.startsWith("/") ? row.path : "/";
|
|
133
|
+
if (options.requestUrl && !pathMatches(options.requestUrl.pathname || "/", path))
|
|
134
|
+
continue;
|
|
135
|
+
entries.push({ name, value, path });
|
|
136
|
+
if (!cookies[name])
|
|
111
137
|
cookies[name] = value;
|
|
112
138
|
}
|
|
139
|
+
if (entries.length > 0)
|
|
140
|
+
sawAnyHostCookie = true;
|
|
113
141
|
if (requiredCookies?.length && !requiredCookies.every((name) => Boolean(cookies[name])))
|
|
114
142
|
continue;
|
|
115
|
-
|
|
143
|
+
if (entries.length === 0)
|
|
144
|
+
continue;
|
|
145
|
+
return {
|
|
146
|
+
cookies,
|
|
147
|
+
warnings: [...warningSet],
|
|
148
|
+
...(options.requestUrl ? { cookieHeader: buildCookieHeader(entries) } : {}),
|
|
149
|
+
};
|
|
116
150
|
}
|
|
117
151
|
finally {
|
|
118
152
|
rmSync(tempDir, { recursive: true, force: true });
|
|
@@ -134,7 +168,12 @@ export async function getGoogleCookies(options) {
|
|
|
134
168
|
: "No detected Chromium profile contains a cookie database.";
|
|
135
169
|
}
|
|
136
170
|
else if (requiredCookies?.length && !sawRequiredCookies) {
|
|
137
|
-
lastCookieDiagnostic =
|
|
171
|
+
lastCookieDiagnostic = `No detected Chromium profile contains the required ${options.requiredLabel ?? "browser"} cookies.`;
|
|
172
|
+
}
|
|
173
|
+
else if (!sawAnyHostCookie) {
|
|
174
|
+
lastCookieDiagnostic = options.requestUrl
|
|
175
|
+
? "No detected Chromium profile contains cookies for the requested URL."
|
|
176
|
+
: "No detected Chromium profile contains cookies for the requested host.";
|
|
138
177
|
}
|
|
139
178
|
else if (warningSet.size > 0) {
|
|
140
179
|
lastCookieDiagnostic = [...warningSet][0];
|
|
@@ -178,6 +217,9 @@ function normalizeCookieNames(names) {
|
|
|
178
217
|
const normalized = names.filter((name) => typeof name === "string").map((name) => name.trim()).filter(Boolean);
|
|
179
218
|
return normalized.length > 0 ? [...new Set(normalized)] : undefined;
|
|
180
219
|
}
|
|
220
|
+
function normalizeHosts(hosts) {
|
|
221
|
+
return [...new Set(hosts.map(host => host.trim().toLowerCase().replace(/^\[|\]$/g, "").replace(/\.$/, "")).filter(Boolean))];
|
|
222
|
+
}
|
|
181
223
|
function listBrowserProfiles(home, config) {
|
|
182
224
|
const basePath = join(home, config.baseDir);
|
|
183
225
|
if (!existsSync(basePath))
|
|
@@ -396,18 +438,60 @@ async function hasCookieNames(dbPath, hosts, names) {
|
|
|
396
438
|
const present = new Set(result.rows.map((row) => typeof row.name === "string" ? row.name : ""));
|
|
397
439
|
return { present: names.every((name) => present.has(name)) };
|
|
398
440
|
}
|
|
399
|
-
async function queryCookieRows(dbPath, hosts, names) {
|
|
400
|
-
|
|
441
|
+
async function queryCookieRows(dbPath, hosts, names, filterExpired) {
|
|
442
|
+
const columns = await readCookieColumns(dbPath);
|
|
443
|
+
if (columns.status === "failure")
|
|
444
|
+
return columns;
|
|
445
|
+
const pathExpr = columns.columns.has("path") ? "path" : "'/' AS path";
|
|
446
|
+
const expiresExpr = columns.columns.has("expires_utc") ? "expires_utc" : "0 AS expires_utc";
|
|
447
|
+
const expiryFilter = filterExpired && columns.columns.has("expires_utc") ? ` AND (expires_utc = 0 OR expires_utc > ${chromeExpiryNowMicros()})` : "";
|
|
448
|
+
const partitionFilter = filterExpired ? unpartitionedCookieFilter(columns.columns) : "";
|
|
449
|
+
return runSqliteQuery(dbPath, `SELECT name, value, host_key, ${pathExpr}, ${expiresExpr}, hex(encrypted_value) AS encrypted_value_hex FROM cookies WHERE ${buildCookieWhere(hosts, names ?? undefined)}${expiryFilter}${partitionFilter} ORDER BY length(path) DESC, expires_utc ASC`);
|
|
450
|
+
}
|
|
451
|
+
async function readCookieColumns(dbPath) {
|
|
452
|
+
const result = await runSqliteQuery(dbPath, "PRAGMA table_info(cookies)");
|
|
453
|
+
if (result.status === "failure")
|
|
454
|
+
return result;
|
|
455
|
+
return { status: "success", columns: new Set(result.rows.map(row => typeof row.name === "string" ? row.name : "")) };
|
|
456
|
+
}
|
|
457
|
+
function chromeExpiryNowMicros() {
|
|
458
|
+
return (Date.now() + 11644473600000) * 1000;
|
|
459
|
+
}
|
|
460
|
+
function unpartitionedCookieFilter(columns) {
|
|
461
|
+
const clauses = [];
|
|
462
|
+
if (columns.has("top_frame_site_key"))
|
|
463
|
+
clauses.push("(top_frame_site_key IS NULL OR top_frame_site_key = '')");
|
|
464
|
+
if (columns.has("partition_key"))
|
|
465
|
+
clauses.push("(partition_key IS NULL OR partition_key = '')");
|
|
466
|
+
if (columns.has("is_partitioned"))
|
|
467
|
+
clauses.push("(is_partitioned IS NULL OR is_partitioned = 0)");
|
|
468
|
+
return clauses.length > 0 ? ` AND ${clauses.join(" AND ")}` : "";
|
|
469
|
+
}
|
|
470
|
+
function buildCookieHeader(entries) {
|
|
471
|
+
return entries
|
|
472
|
+
.sort((a, b) => b.path.length - a.path.length)
|
|
473
|
+
.map(({ name, value }) => `${name}=${value}`)
|
|
474
|
+
.join("; ");
|
|
475
|
+
}
|
|
476
|
+
function pathMatches(requestPath, cookiePath) {
|
|
477
|
+
if (requestPath === cookiePath)
|
|
478
|
+
return true;
|
|
479
|
+
if (!requestPath.startsWith(cookiePath))
|
|
480
|
+
return false;
|
|
481
|
+
if (cookiePath.endsWith("/"))
|
|
482
|
+
return true;
|
|
483
|
+
return requestPath[cookiePath.length] === "/";
|
|
401
484
|
}
|
|
402
485
|
function buildCookieWhere(hosts, cookieNames) {
|
|
403
486
|
const hostClauses = [];
|
|
404
487
|
for (const host of hosts) {
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
488
|
+
const escapedHost = escapeSqlString(host);
|
|
489
|
+
hostClauses.push(`host_key = '${escapedHost}'`);
|
|
490
|
+
for (const candidate of domainCookieHosts(host)) {
|
|
491
|
+
hostClauses.push(`host_key = '.${escapeSqlString(candidate)}'`);
|
|
408
492
|
}
|
|
409
493
|
}
|
|
410
|
-
let where = `(${hostClauses.join(" OR ")})`;
|
|
494
|
+
let where = `(${[...new Set(hostClauses)].join(" OR ")})`;
|
|
411
495
|
const names = cookieNames ? [...cookieNames].filter(Boolean) : [];
|
|
412
496
|
if (names.length)
|
|
413
497
|
where += ` AND name IN (${names.map((name) => `'${escapeSqlString(name)}'`).join(", ")})`;
|
|
@@ -416,12 +500,12 @@ function buildCookieWhere(hosts, cookieNames) {
|
|
|
416
500
|
function escapeSqlString(value) {
|
|
417
501
|
return value.replaceAll("'", "''");
|
|
418
502
|
}
|
|
419
|
-
function
|
|
503
|
+
function domainCookieHosts(host) {
|
|
420
504
|
const parts = host.split(".").filter(Boolean);
|
|
421
505
|
if (parts.length <= 1)
|
|
422
|
-
return [
|
|
423
|
-
const candidates = new Set(
|
|
424
|
-
for (let i =
|
|
506
|
+
return [];
|
|
507
|
+
const candidates = new Set();
|
|
508
|
+
for (let i = 0; i <= parts.length - 2; i++)
|
|
425
509
|
candidates.add(parts.slice(i).join("."));
|
|
426
510
|
return [...candidates];
|
|
427
511
|
}
|