google-flow-api-mcp 0.0.0-stage → 1.0.0

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/cookies.py ADDED
@@ -0,0 +1,246 @@
1
+ """Cookie acquisition and session validation for google-flow-api.
2
+
3
+ The Flow RPCs authenticate with the ordinary `.google.com` browser session, so
4
+ "relogin" means: read the cookie jar straight out of the browser the machine
5
+ already uses, store it where the client expects it, and prove the session opens
6
+ a Flow project page (instead of the Google sign-in screen).
7
+
8
+ Everything here is read-only with respect to the browser: we copy cookies, we
9
+ never write to the browser's profile.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import http.cookiejar
15
+ import json
16
+ import os
17
+ import plistlib
18
+ import re
19
+ import time
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ import browser_cookie3
24
+ import requests
25
+
26
+ from flow_api.client import (
27
+ DEFAULT_PROJECT_ID,
28
+ PAGE_URL,
29
+ FlowError,
30
+ parse_wiz,
31
+ )
32
+
33
+ CONFIG_HOME = Path(
34
+ os.environ.get("GOOGLE_FLOW_API_HOME", Path.home() / ".config" / "google-flow-api")
35
+ ).expanduser()
36
+ COOKIE_FILE = CONFIG_HOME / "cookies.json"
37
+ WIZ_FILE = CONFIG_HOME / "wiz.json"
38
+
39
+ LAUNCHSERVICES_PLIST = (
40
+ Path.home()
41
+ / "Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist"
42
+ )
43
+
44
+ # bundle id -> (human label, browser_cookie3 loader)
45
+ BROWSERS: dict[str, tuple[str, Any]] = {
46
+ "com.google.chrome": ("Chrome", browser_cookie3.chrome),
47
+ "com.microsoft.edgemac": ("Edge", browser_cookie3.edge),
48
+ "com.brave.Browser": ("Brave", browser_cookie3.brave),
49
+ "company.thebrowser.Browser": ("Arc", browser_cookie3.arc),
50
+ "org.mozilla.firefox": ("Firefox", browser_cookie3.firefox),
51
+ "com.apple.Safari": ("Safari", browser_cookie3.safari),
52
+ "com.operasoftware.Opera": ("Opera", browser_cookie3.opera),
53
+ "com.vivaldi.Vivaldi": ("Vivaldi", browser_cookie3.vivaldi),
54
+ "org.chromium.Chromium": ("Chromium", browser_cookie3.chromium),
55
+ }
56
+
57
+ # Cookies that only exist on a real signed-in Google session.
58
+ AUTH_COOKIES = ("SID", "SAPISID", "__Secure-1PSID", "__Secure-3PSID", "HSID", "SSID")
59
+
60
+
61
+ def default_browser_bundle() -> str | None:
62
+ """Bundle id handling https:// per macOS LaunchServices."""
63
+ try:
64
+ with LAUNCHSERVICES_PLIST.open("rb") as fh:
65
+ handlers = plistlib.load(fh).get("LSHandlers", [])
66
+ except (OSError, plistlib.InvalidFileException):
67
+ return None
68
+ for handler in handlers:
69
+ if (
70
+ handler.get("LSHandlerURLScheme") == "https"
71
+ and handler.get("LSHandlerRoleAll")
72
+ ):
73
+ return str(handler["LSHandlerRoleAll"]).lower()
74
+ return None
75
+
76
+
77
+ def default_browser_label() -> str:
78
+ bundle = default_browser_bundle()
79
+ if bundle and bundle in BROWSERS:
80
+ return BROWSERS[bundle][0]
81
+ return "unknown"
82
+
83
+
84
+ def _cookie_dicts(jar: http.cookiejar.CookieJar) -> list[dict[str, Any]]:
85
+ now = time.time()
86
+ out: list[dict[str, Any]] = []
87
+ for c in jar:
88
+ if not c.name:
89
+ continue
90
+ if c.expires and c.expires < now:
91
+ continue
92
+ rest = getattr(c, "_rest", {}) or {}
93
+ same_site = str(rest.get("SameSite", "Lax") or "Lax").capitalize()
94
+ if same_site not in ("Strict", "Lax", "None"):
95
+ same_site = "Lax"
96
+ out.append(
97
+ {
98
+ "name": c.name,
99
+ "value": c.value or "",
100
+ "domain": c.domain or ".google.com",
101
+ "path": c.path or "/",
102
+ "expires": c.expires if c.expires else -1,
103
+ "httpOnly": bool(c._rest.get("HTTPOnly")) if getattr(c, "_rest", None) else False,
104
+ "secure": bool(c.secure),
105
+ "sameSite": same_site,
106
+ }
107
+ )
108
+ return out
109
+
110
+
111
+ def extract_google_cookies(
112
+ browser: str | None = None,
113
+ ) -> tuple[str, list[dict[str, Any]], list[str]]:
114
+ """Read `.google.com` cookies from the requested browser, else every browser.
115
+
116
+ Returns (label, cookies, tried_labels). Raises FlowError if no signed-in
117
+ Google jar is found anywhere.
118
+ """
119
+ tries: list[tuple[str, Any]] = []
120
+ if browser:
121
+ wanted = browser.lower()
122
+ for label, loader in BROWSERS.values():
123
+ if label.lower() == wanted:
124
+ tries.append((label, loader))
125
+ else:
126
+ bundle = default_browser_bundle()
127
+ if bundle and bundle in BROWSERS:
128
+ tries.append(BROWSERS[bundle])
129
+ for label, loader in BROWSERS.values():
130
+ if (label, loader) not in tries:
131
+ tries.append((label, loader))
132
+
133
+ tried: list[str] = []
134
+ errors: list[str] = []
135
+ for label, loader in tries:
136
+ tried.append(label)
137
+ try:
138
+ jar = loader(domain_name="google.com")
139
+ cookies = _cookie_dicts(jar)
140
+ except Exception as exc: # browser not installed, locked DB, keychain denied...
141
+ errors.append(f"{label}: {type(exc).__name__}: {exc}")
142
+ continue
143
+ names = {c["name"] for c in cookies}
144
+ if names & set(AUTH_COOKIES):
145
+ return label, cookies, tried
146
+ errors.append(f"{label}: {len(cookies)} google cookies, none of {AUTH_COOKIES}")
147
+ raise FlowError(
148
+ "no signed-in Google cookie jar found; tried "
149
+ + ", ".join(tried)
150
+ + ". Close the browser if its cookie DB is locked. Details: "
151
+ + " | ".join(errors[:4])
152
+ )
153
+
154
+
155
+ def save_cookies(cookies: list[dict[str, Any]], path: Path = COOKIE_FILE) -> Path:
156
+ path.parent.mkdir(parents=True, exist_ok=True)
157
+ tmp = path.with_suffix(".tmp")
158
+ tmp.write_text(json.dumps(cookies, indent=1))
159
+ os.chmod(tmp, 0o600)
160
+ tmp.replace(path)
161
+ return path
162
+
163
+
164
+ def validate_session(
165
+ cookies: list[dict[str, Any]], project: str | None = None
166
+ ) -> dict[str, Any]:
167
+ """Prove the jar opens a Flow project page and harvest the RPC tokens."""
168
+ project = project or os.environ.get("FLOW_PROJECT_ID") or DEFAULT_PROJECT_ID
169
+ session = requests.Session()
170
+ session.headers.update(
171
+ {
172
+ "user-agent": (
173
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
174
+ "AppleWebKit/537.36 (KHTML, like Gecko) "
175
+ "Chrome/140.0.0.0 Safari/537.36"
176
+ ),
177
+ "accept": "text/html,application/xhtml+xml",
178
+ }
179
+ )
180
+ for c in cookies:
181
+ session.cookies.set(
182
+ c["name"],
183
+ c.get("value", ""),
184
+ domain=c.get("domain") or ".google.com",
185
+ path=c.get("path") or "/",
186
+ )
187
+ url = PAGE_URL.format(project=project)
188
+ resp = session.get(url, timeout=45, allow_redirects=True)
189
+ final = resp.url
190
+ if "accounts.google.com" in final or "/signin" in final:
191
+ raise FlowError(
192
+ "cookies are not signed in to Google (project page redirected to sign-in)"
193
+ )
194
+ if resp.status_code != 200:
195
+ raise FlowError(f"project page returned HTTP {resp.status_code}")
196
+ wiz = parse_wiz(resp.text)
197
+ email = _scrape_email(resp.text)
198
+ return {
199
+ "project": project,
200
+ "final_url": final,
201
+ "title": _title(resp.text),
202
+ "email": email,
203
+ "at_prefix": wiz["at"][:18] + "…",
204
+ "bl": wiz["bl"],
205
+ "fsid": wiz["fsid"],
206
+ "_wiz": wiz,
207
+ }
208
+
209
+
210
+ def _title(html_text: str) -> str:
211
+ m = re.search(r"<title[^>]*>(.*?)</title>", html_text, re.S | re.I)
212
+ return re.sub(r"\s+", " ", m.group(1)).strip() if m else ""
213
+
214
+
215
+ def _scrape_email(html_text: str) -> str | None:
216
+ for pattern in (r'"oPEP7c"\s*:\s*"([^"@]+@[^"]+)"', r'([\w.+-]+@gmail\.com)'):
217
+ m = re.search(pattern, html_text)
218
+ if m:
219
+ return m.group(1)
220
+ return None
221
+
222
+
223
+ def relogin(browser: str | None = None, project: str | None = None) -> dict[str, Any]:
224
+ """Extract fresh cookies from the machine's browser and validate them.
225
+
226
+ This is the tool to run when generation starts failing with sign-in/HTML,
227
+ or on a fresh machine after logging into Google Flow in the browser.
228
+ """
229
+ bundle = default_browser_bundle()
230
+ label, cookies, tried = extract_google_cookies(browser)
231
+ path = save_cookies(cookies)
232
+ account = validate_session(cookies, project)
233
+ wiz_path = CONFIG_HOME / "wiz.json"
234
+ wiz_path.write_text(json.dumps(account["_wiz"], indent=1))
235
+ os.chmod(wiz_path, 0o600)
236
+ account.pop("_wiz", None)
237
+ return {
238
+ "ok": True,
239
+ "browser": label,
240
+ "default_browser": BROWSERS.get(bundle or "", ("unknown",))[0] if bundle else "unknown",
241
+ "browsers_tried": tried,
242
+ "cookies": len(cookies),
243
+ "cookie_file": str(path),
244
+ "wiz_file": str(wiz_path),
245
+ "account": account,
246
+ }
@@ -0,0 +1,43 @@
1
+ """flow_api — minimal Google Flow (flow.google.com) client.
2
+
3
+ Reverse-engineered batchexecute wrapper for:
4
+ * image generation : RPC ``ogiZ0b`` + model ``GEM_PIX_2`` (Nano Banana Pro)
5
+ * video generation : RPC ``YhhmEf`` + model ``macaron_cookie_t2v_8s`` (Omni 1.2 Flash)
6
+ * video status : RPC ``jwpduf``
7
+ * media metadata : RPC ``as29s``
8
+
9
+ Entry point::
10
+
11
+ python3 -m flow_api image "a blue mug on a desk"
12
+ python3 -m flow_api video "a paper plane over a desk"
13
+ """
14
+
15
+ from .client import (
16
+ DEFAULT_PROJECT_ID,
17
+ IMAGE_MODEL,
18
+ IMAGE_RPC,
19
+ MEDIA_FETCH_RPC,
20
+ RECAPTCHA_SITE_KEY,
21
+ VIDEO_MODEL,
22
+ VIDEO_RPC,
23
+ VIDEO_STATUS_RPC,
24
+ FlowClient,
25
+ FlowError,
26
+ RecaptchaRejected,
27
+ deframe,
28
+ )
29
+
30
+ __all__ = [
31
+ "FlowClient",
32
+ "FlowError",
33
+ "RecaptchaRejected",
34
+ "deframe",
35
+ "IMAGE_RPC",
36
+ "VIDEO_RPC",
37
+ "VIDEO_STATUS_RPC",
38
+ "MEDIA_FETCH_RPC",
39
+ "IMAGE_MODEL",
40
+ "VIDEO_MODEL",
41
+ "RECAPTCHA_SITE_KEY",
42
+ "DEFAULT_PROJECT_ID",
43
+ ]
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,203 @@
1
+ """Command line interface for flow_api.
2
+
3
+ Usage::
4
+
5
+ python3 -m flow_api image "a blue ceramic mug on a wooden desk"
6
+ python3 -m flow_api video "a paper airplane gliding over a desk" --timeout 600
7
+ python3 -m flow_api wiz --project <id> # validate cookies + dump tokens
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import json
14
+ import os
15
+ import sys
16
+ from pathlib import Path
17
+
18
+ from .client import (
19
+ DEFAULT_FIXTURES,
20
+ DEFAULT_OUT_DIR,
21
+ DEFAULT_PROJECT_ID,
22
+ FlowClient,
23
+ FlowError,
24
+ RecaptchaRejected,
25
+ )
26
+
27
+
28
+ def _default_wiz() -> str | None:
29
+ candidate = DEFAULT_FIXTURES / "wiz.json"
30
+ return str(candidate) if candidate.exists() else None
31
+
32
+
33
+ def _default_cookies() -> str | None:
34
+ candidate = DEFAULT_FIXTURES / "cookies.json"
35
+ return str(candidate) if candidate.exists() else None
36
+
37
+
38
+ def _default_tokens() -> str | None:
39
+ candidate = DEFAULT_FIXTURES / "tokens"
40
+ return str(candidate) if candidate.exists() else None
41
+
42
+
43
+ def build_client(args: argparse.Namespace) -> FlowClient:
44
+ cookies = args.cookies or _default_cookies()
45
+ if not cookies:
46
+ raise FlowError(
47
+ "no cookie jar: pass --cookies fixtures/flow_cookies.json or export one"
48
+ )
49
+ client = FlowClient(
50
+ project_id=args.project or os.environ.get("FLOW_PROJECT_ID") or DEFAULT_PROJECT_ID,
51
+ cookie_file=cookies,
52
+ wiz_file=args.wiz if args.wiz is not None else _default_wiz(),
53
+ token_file=args.token_file if args.token_file is not None else _default_tokens(),
54
+ timeout=args.http_timeout,
55
+ out_dir=args.out_dir or DEFAULT_OUT_DIR,
56
+ verbose=not args.quiet,
57
+ )
58
+ client.auto_mint = not args.no_mint
59
+ return client
60
+
61
+
62
+ def cmd_image(args: argparse.Namespace) -> int:
63
+ client = build_client(args)
64
+ result = client.generate_image(
65
+ args.prompt,
66
+ out=args.out,
67
+ recaptcha_token=args.recaptcha_token,
68
+ download=not args.no_download,
69
+ )
70
+ _report(result, args)
71
+ return 0
72
+
73
+
74
+ def cmd_video(args: argparse.Namespace) -> int:
75
+ if not args.prompt and not args.media_id:
76
+ raise FlowError("video: give a prompt or --media-id")
77
+ client = build_client(args)
78
+ result = client.generate_video(
79
+ args.prompt or "",
80
+ out=args.out,
81
+ recaptcha_token=args.recaptcha_token,
82
+ timeout=args.timeout,
83
+ poll_interval=args.poll,
84
+ download=not args.no_download,
85
+ media_id=args.media_id,
86
+ )
87
+ _report(result, args)
88
+ return 0
89
+
90
+
91
+ def cmd_download(args: argparse.Namespace) -> int:
92
+ client = build_client(args)
93
+ url = client.fetch_media_url(args.media_id, kind=args.kind)
94
+ if not url:
95
+ raise FlowError(f"as29s returned no {args.kind} URL for media {args.media_id}")
96
+ result = client.download(
97
+ url,
98
+ prompt=args.prompt or f"media {args.media_id}",
99
+ kind=args.kind,
100
+ out=args.out,
101
+ )
102
+ result.update(
103
+ {"kind": args.kind, "model": "media", "prompt": args.prompt or "", "media_id": args.media_id, "url": url}
104
+ )
105
+ _report(result, args)
106
+ return 0
107
+
108
+
109
+ def cmd_wiz(args: argparse.Namespace) -> int:
110
+ client = build_client(args)
111
+ wiz = client.refresh_wiz()
112
+ info = {
113
+ "project": client.project_id,
114
+ "cookies": client.cookie_count,
115
+ "at_prefix": wiz["at"][:20] + "…",
116
+ "bl": wiz["bl"],
117
+ "fsid": wiz["fsid"],
118
+ }
119
+ print(json.dumps(info, indent=2))
120
+ return 0
121
+
122
+
123
+ def _report(result: dict, args: argparse.Namespace) -> None:
124
+ payload = {k: v for k, v in result.items()}
125
+ if args.json:
126
+ print(json.dumps(payload, indent=2))
127
+ return
128
+ path = payload.get("path")
129
+ print(f"OK {payload['kind']} model={payload['model']}")
130
+ if payload.get("url"):
131
+ print(f"url: {payload['url'][:140]}")
132
+ if path:
133
+ size = payload.get("bytes", 0)
134
+ print(f"file: {path} ({size} bytes, {payload.get('via', '?')})")
135
+ else:
136
+ print(json.dumps(payload, indent=2))
137
+
138
+
139
+ def add_common(parser: argparse.ArgumentParser) -> None:
140
+ parser.add_argument("--cookies", help="cookie JSON exported from the browser")
141
+ parser.add_argument("--wiz", help="JSON with at/bl/fsid (skips the page scrape)")
142
+ parser.add_argument("--project", help=f"Flow project id (default {DEFAULT_PROJECT_ID})")
143
+ parser.add_argument("--token-file", help="reCAPTCHA token JSON file or directory")
144
+ parser.add_argument("--recaptcha-token", help="reCAPTCHA token, inline")
145
+ parser.add_argument("--out", help="explicit output file path")
146
+ parser.add_argument("--out-dir", help=f"output directory (default {DEFAULT_OUT_DIR})")
147
+ parser.add_argument("--http-timeout", type=int, default=60)
148
+ parser.add_argument("--no-mint", action="store_true", help="never auto-mint a reCAPTCHA token")
149
+ parser.add_argument("--no-download", action="store_true")
150
+ parser.add_argument("--json", action="store_true", help="machine-readable output")
151
+ parser.add_argument("--quiet", action="store_true")
152
+
153
+
154
+ def build_parser() -> argparse.ArgumentParser:
155
+ parser = argparse.ArgumentParser(prog="flow_api", description="Google Flow client")
156
+ sub = parser.add_subparsers(dest="command", required=True)
157
+
158
+ image = sub.add_parser("image", help="generate one image (Nano Banana Pro / GEM_PIX_2)")
159
+ image.add_argument("prompt")
160
+ add_common(image)
161
+ image.set_defaults(func=cmd_image)
162
+
163
+ video = sub.add_parser("video", help="generate one video (Omni 1.2 Flash)")
164
+ video.add_argument("prompt", nargs="?", default=None)
165
+ add_common(video)
166
+ video.add_argument("--timeout", type=int, default=600)
167
+ video.add_argument("--poll", type=float, default=5.0)
168
+ video.add_argument("--media-id", help="resume polling an already submitted media id")
169
+ video.set_defaults(func=cmd_video)
170
+
171
+ download = sub.add_parser(
172
+ "download", help="download an existing media id (no generation, no reCAPTCHA)"
173
+ )
174
+ download.add_argument("media_id")
175
+ download.add_argument("--kind", choices=("video", "image"), default="video")
176
+ download.add_argument("--prompt", help="label used for the output filename slug")
177
+ add_common(download)
178
+ download.set_defaults(func=cmd_download)
179
+
180
+ wiz = sub.add_parser("wiz", help="validate cookies and dump at/bl/fsid")
181
+ add_common(wiz)
182
+ wiz.set_defaults(func=cmd_wiz)
183
+ return parser
184
+
185
+
186
+ def main(argv: list[str] | None = None) -> int:
187
+ parser = build_parser()
188
+ args = parser.parse_args(argv)
189
+ try:
190
+ return args.func(args)
191
+ except RecaptchaRejected as exc:
192
+ print(f"RECAPTCHA: {exc}", file=sys.stderr)
193
+ return 3
194
+ except FlowError as exc:
195
+ print(f"ERROR: {exc}", file=sys.stderr)
196
+ return 4
197
+ except KeyboardInterrupt:
198
+ print("interrupted", file=sys.stderr)
199
+ return 130
200
+
201
+
202
+ if __name__ == "__main__":
203
+ raise SystemExit(main())