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/LICENSE +21 -0
- package/README.md +89 -2
- package/auth_lab/mint_token.py +596 -0
- package/bin/google-flow-api +78 -0
- package/cookies.py +246 -0
- package/flow_api/__init__.py +43 -0
- package/flow_api/__main__.py +3 -0
- package/flow_api/cli.py +203 -0
- package/flow_api/client.py +881 -0
- package/flow_api/selftest.py +195 -0
- package/package.json +44 -3
- package/postinstall.js +98 -0
- package/scripts/clean-pycache.js +22 -0
- package/server.py +204 -0
|
@@ -0,0 +1,596 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
mint_token.py — mint a Google reCAPTCHA Enterprise token for Flow (flow.google.com)
|
|
4
|
+
without the user's live browser, and optionally prove it against the real RPC.
|
|
5
|
+
|
|
6
|
+
How it works
|
|
7
|
+
------------
|
|
8
|
+
Google Flow's generation RPCs (ogiZ0b image, YhhmEf video) embed a reCAPTCHA
|
|
9
|
+
Enterprise token in their body. That token can only be produced by executing the
|
|
10
|
+
page's own `grecaptcha.enterprise` JS with a real login session. This script:
|
|
11
|
+
|
|
12
|
+
1. launches a *private* Playwright Chromium (headless by default),
|
|
13
|
+
2. injects the exported `.google.com` cookie jar (fixtures/flow_cookies.json),
|
|
14
|
+
3. opens the Flow project page (so the page loads grecaptcha.enterprise),
|
|
15
|
+
4. calls grecaptcha.enterprise.execute(SITE_KEY, {action: ACTION}),
|
|
16
|
+
5. saves the token and, with --prove, immediately POSTs the real ogiZ0b RPC
|
|
17
|
+
from Python and asserts it returns a flow-content URL (not UNUSUAL_ACTIVITY).
|
|
18
|
+
|
|
19
|
+
Tokens are single-use and expire in ~2 minutes: mint + use must be in one run.
|
|
20
|
+
|
|
21
|
+
Actions are RPC-bound (verified against the page bundle and live RPCs):
|
|
22
|
+
image ogiZ0b -> action "IMAGE_GENERATION"
|
|
23
|
+
video YhhmEf -> action "VIDEO_GENERATION"
|
|
24
|
+
Using the wrong action yields PUBLIC_ERROR_UNUSUAL_ACTIVITY.
|
|
25
|
+
|
|
26
|
+
Reliability: Google scores the browser; a burst of mints/generations from the same
|
|
27
|
+
account flips the verdict to PUBLIC_ERROR_UNUSUAL_ACTIVITY. Passes were observed
|
|
28
|
+
headless (no headed/stealth needed), and 3 live images were produced this way. The
|
|
29
|
+
default --warmup 3 (mouse/scroll before executing) plus --retries 1 (pause and
|
|
30
|
+
re-mint) is the mitigation. For sustained use, space mints out (tens of seconds)
|
|
31
|
+
instead of minting in a tight loop.
|
|
32
|
+
|
|
33
|
+
CLI
|
|
34
|
+
---
|
|
35
|
+
python3 auth_lab/mint_token.py --action IMAGE_GENERATION
|
|
36
|
+
python3 auth_lab/mint_token.py --action IMAGE_GENERATION --prove
|
|
37
|
+
python3 auth_lab/mint_token.py --action IMAGE_GENERATION --prove --out /tmp/t.txt
|
|
38
|
+
python3 auth_lab/mint_token.py --action IMAGE_GENERATION --video-probe
|
|
39
|
+
python3 auth_lab/mint_token.py --action IMAGE_GENERATION --headed # if headless is scored badly
|
|
40
|
+
|
|
41
|
+
Exit codes: 0 = success, 2 = browser/mint failure, 3 = prove FAIL.
|
|
42
|
+
"""
|
|
43
|
+
from __future__ import annotations
|
|
44
|
+
|
|
45
|
+
import argparse
|
|
46
|
+
import json
|
|
47
|
+
import os
|
|
48
|
+
import random
|
|
49
|
+
import re
|
|
50
|
+
import sys
|
|
51
|
+
import time
|
|
52
|
+
import urllib.error
|
|
53
|
+
import urllib.parse
|
|
54
|
+
import urllib.request
|
|
55
|
+
import uuid
|
|
56
|
+
from pathlib import Path
|
|
57
|
+
|
|
58
|
+
HERE = Path(__file__).resolve().parent
|
|
59
|
+
REPO = HERE.parent
|
|
60
|
+
|
|
61
|
+
PROJECT_DEFAULT = "f73a2a1b-0904-4cec-8c9e-22ff6c858592"
|
|
62
|
+
SITE_KEY_DEFAULT = "6LdsFiUsAAAAAIjVDZcuLhaHiDn5nnHVXVRQGeMV"
|
|
63
|
+
ACTION_DEFAULT = "IMAGE_GENERATION"
|
|
64
|
+
UA_DEFAULT = (
|
|
65
|
+
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
|
|
66
|
+
"(KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36"
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
FIXTURE_CANDIDATES = [
|
|
70
|
+
Path(os.environ.get("GOOGLE_FLOW_API_HOME", Path.home() / ".config" / "google-flow-api"))
|
|
71
|
+
/ "cookies.json",
|
|
72
|
+
Path.home() / ".config" / "google-flow-api" / "cookies.json",
|
|
73
|
+
REPO / ".team-mode/teams/flow-api/fixtures/flow_cookies.json",
|
|
74
|
+
Path("/tmp/flow_cookies.json"),
|
|
75
|
+
]
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
# --------------------------------------------------------------------------- #
|
|
79
|
+
# fixture / session helpers
|
|
80
|
+
# --------------------------------------------------------------------------- #
|
|
81
|
+
def find_cookies_file(explicit: str | None) -> Path:
|
|
82
|
+
if explicit:
|
|
83
|
+
p = Path(explicit).expanduser()
|
|
84
|
+
if not p.exists():
|
|
85
|
+
raise SystemExit(f"cookies file not found: {p}")
|
|
86
|
+
return p
|
|
87
|
+
env = os.environ.get("FLOW_COOKIES")
|
|
88
|
+
if env and Path(env).expanduser().exists():
|
|
89
|
+
return Path(env).expanduser()
|
|
90
|
+
for p in FIXTURE_CANDIDATES:
|
|
91
|
+
if p.exists():
|
|
92
|
+
return p
|
|
93
|
+
raise SystemExit(
|
|
94
|
+
"no cookie jar found; pass --cookies <playwright-format-json> "
|
|
95
|
+
f"(looked at: {', '.join(str(p) for p in FIXTURE_CANDIDATES)})"
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def normalize_cookie(c: dict) -> dict:
|
|
100
|
+
d = {
|
|
101
|
+
"name": c["name"],
|
|
102
|
+
"value": c["value"],
|
|
103
|
+
"domain": c["domain"],
|
|
104
|
+
"path": c.get("path") or "/",
|
|
105
|
+
}
|
|
106
|
+
if c.get("expires"):
|
|
107
|
+
d["expires"] = float(c["expires"])
|
|
108
|
+
d["httpOnly"] = bool(c.get("httpOnly"))
|
|
109
|
+
d["secure"] = bool(c.get("secure"))
|
|
110
|
+
ss = str(c.get("sameSite") or "").lower()
|
|
111
|
+
d["sameSite"] = {
|
|
112
|
+
"no_restriction": "None",
|
|
113
|
+
"unspecified": "Lax",
|
|
114
|
+
"lax": "Lax",
|
|
115
|
+
"strict": "Strict",
|
|
116
|
+
"none": "None",
|
|
117
|
+
}.get(ss, "Lax")
|
|
118
|
+
return d
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def cookie_header(cookies: list[dict]) -> str:
|
|
122
|
+
return "; ".join(f"{c['name']}={c['value']}" for c in cookies)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
# --------------------------------------------------------------------------- #
|
|
126
|
+
# batchexecute plumbing (mirrors the documented client, small enough to prove)
|
|
127
|
+
# --------------------------------------------------------------------------- #
|
|
128
|
+
def make_batchexecute(cookie_jar_header: str, ua: str, project: str, wiz: dict):
|
|
129
|
+
def bx(rpcid: str, inner_obj) -> tuple[int, str]:
|
|
130
|
+
freq = json.dumps(
|
|
131
|
+
[[[rpcid, json.dumps(inner_obj, separators=(",", ":")), None, "generic"]]],
|
|
132
|
+
separators=(",", ":"),
|
|
133
|
+
)
|
|
134
|
+
body = urllib.parse.urlencode({"f.req": freq, "at": wiz["at"]}).encode()
|
|
135
|
+
url = (
|
|
136
|
+
"https://flow.google.com/_/AiSandboxAngularFrontend/data/batchexecute"
|
|
137
|
+
f"?rpcids={rpcid}&source-path=%2Fproject%2F{project}"
|
|
138
|
+
f"&bl={urllib.parse.quote(wiz['bl'])}&f.sid={wiz['fsid']}"
|
|
139
|
+
f"&hl=en&_reqid={random.randint(100000, 9999999)}&rt=c"
|
|
140
|
+
)
|
|
141
|
+
req = urllib.request.Request(
|
|
142
|
+
url,
|
|
143
|
+
data=body,
|
|
144
|
+
method="POST",
|
|
145
|
+
headers={
|
|
146
|
+
"content-type": "application/x-www-form-urlencoded;charset=utf-8",
|
|
147
|
+
"x-same-domain": "1",
|
|
148
|
+
"origin": "https://flow.google.com",
|
|
149
|
+
"referer": f"https://flow.google.com/project/{project}",
|
|
150
|
+
"cookie": cookie_jar_header,
|
|
151
|
+
"user-agent": ua,
|
|
152
|
+
},
|
|
153
|
+
)
|
|
154
|
+
try:
|
|
155
|
+
with urllib.request.urlopen(req, timeout=90) as r:
|
|
156
|
+
return r.status, r.read().decode("utf-8", "replace")
|
|
157
|
+
except urllib.error.HTTPError as e:
|
|
158
|
+
return e.code, e.read().decode("utf-8", "replace")
|
|
159
|
+
|
|
160
|
+
return bx
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def dechunk(raw: str) -> list[tuple[str, object]]:
|
|
164
|
+
"""Parse a batchexecute response into [(rpcid, parsed_inner_json_or_None)]."""
|
|
165
|
+
text = raw
|
|
166
|
+
if text.startswith(")]}'"):
|
|
167
|
+
text = text[4:]
|
|
168
|
+
lines = [l for l in text.splitlines() if l.strip()]
|
|
169
|
+
out: list[tuple[str, object]] = []
|
|
170
|
+
i = 0
|
|
171
|
+
while i < len(lines):
|
|
172
|
+
line = lines[i].strip()
|
|
173
|
+
if line.isdigit():
|
|
174
|
+
i += 1
|
|
175
|
+
if i >= len(lines):
|
|
176
|
+
break
|
|
177
|
+
try:
|
|
178
|
+
arr = json.loads(lines[i])
|
|
179
|
+
except Exception:
|
|
180
|
+
i += 1
|
|
181
|
+
continue
|
|
182
|
+
if isinstance(arr, list):
|
|
183
|
+
for item in arr:
|
|
184
|
+
if isinstance(item, list) and len(item) >= 3 and item[0] == "wrb.fr":
|
|
185
|
+
payload = item[2]
|
|
186
|
+
try:
|
|
187
|
+
obj = json.loads(payload) if isinstance(payload, str) else payload
|
|
188
|
+
except Exception:
|
|
189
|
+
obj = None
|
|
190
|
+
out.append((item[1], obj))
|
|
191
|
+
i += 1
|
|
192
|
+
else:
|
|
193
|
+
i += 1
|
|
194
|
+
return out
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def walk_strings(obj, pred):
|
|
198
|
+
if isinstance(obj, str):
|
|
199
|
+
if pred(obj):
|
|
200
|
+
yield obj
|
|
201
|
+
elif isinstance(obj, list):
|
|
202
|
+
for x in obj:
|
|
203
|
+
yield from walk_strings(x, pred)
|
|
204
|
+
elif isinstance(obj, dict):
|
|
205
|
+
for x in obj.values():
|
|
206
|
+
yield from walk_strings(x, pred)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
# --------------------------------------------------------------------------- #
|
|
210
|
+
# browser minting
|
|
211
|
+
# --------------------------------------------------------------------------- #
|
|
212
|
+
def mint_token_via_playwright(
|
|
213
|
+
cookies: list[dict],
|
|
214
|
+
project: str,
|
|
215
|
+
site_key: str,
|
|
216
|
+
action: str,
|
|
217
|
+
headed: bool = False,
|
|
218
|
+
channel: str | None = None,
|
|
219
|
+
timeout_ms: int = 60_000,
|
|
220
|
+
keep_open_s: float = 0.0,
|
|
221
|
+
warmup_s: float = 3.0,
|
|
222
|
+
verbose: bool = True,
|
|
223
|
+
) -> dict:
|
|
224
|
+
"""Return dict(token=..., at=..., bl=..., fsid=..., url=...)."""
|
|
225
|
+
from playwright.sync_api import sync_playwright
|
|
226
|
+
|
|
227
|
+
def log(*a):
|
|
228
|
+
if verbose:
|
|
229
|
+
print("[mint]", *a, file=sys.stderr, flush=True)
|
|
230
|
+
|
|
231
|
+
with sync_playwright() as p:
|
|
232
|
+
launch_args = {
|
|
233
|
+
"headless": not headed,
|
|
234
|
+
"args": ["--disable-blink-features=AutomationControlled"],
|
|
235
|
+
}
|
|
236
|
+
if channel:
|
|
237
|
+
launch_args["channel"] = channel
|
|
238
|
+
try:
|
|
239
|
+
browser = p.chromium.launch(**launch_args)
|
|
240
|
+
except Exception as exc:
|
|
241
|
+
# A source checkout may not have run `playwright install`, but the Mac
|
|
242
|
+
# almost always has Google Chrome. Fall back to it instead of dying.
|
|
243
|
+
if channel or "Executable doesn" not in str(exc):
|
|
244
|
+
raise
|
|
245
|
+
log("bundled chromium missing; falling back to system Google Chrome")
|
|
246
|
+
launch_args["channel"] = "chrome"
|
|
247
|
+
browser = p.chromium.launch(**launch_args)
|
|
248
|
+
ctx = browser.new_context(user_agent=UA_DEFAULT, locale="en-US")
|
|
249
|
+
ctx.add_cookies([normalize_cookie(c) for c in cookies])
|
|
250
|
+
# minimal hygiene: hide navigator.webdriver (the page checks Trusted Types
|
|
251
|
+
# only for string eval, not for init scripts)
|
|
252
|
+
ctx.add_init_script(
|
|
253
|
+
"Object.defineProperty(navigator,'webdriver',{get:()=>undefined});"
|
|
254
|
+
)
|
|
255
|
+
page = ctx.new_page()
|
|
256
|
+
url = f"https://flow.google.com/project/{project}"
|
|
257
|
+
log("goto", url, "(headless=%s channel=%s)" % (not headed, channel))
|
|
258
|
+
page.goto(url, wait_until="domcontentloaded", timeout=timeout_ms)
|
|
259
|
+
page.wait_for_timeout(2500)
|
|
260
|
+
log("landed", page.url, "|", page.title())
|
|
261
|
+
|
|
262
|
+
if "accounts.google.com" in page.url:
|
|
263
|
+
browser.close()
|
|
264
|
+
raise RuntimeError(
|
|
265
|
+
"cookies are not authenticated: redirected to Google sign-in. "
|
|
266
|
+
"Re-export the cookie jar from the logged-in browser."
|
|
267
|
+
)
|
|
268
|
+
|
|
269
|
+
deadline = time.time() + timeout_ms / 1000
|
|
270
|
+
ready = False
|
|
271
|
+
while time.time() < deadline:
|
|
272
|
+
try:
|
|
273
|
+
ready = page.evaluate(
|
|
274
|
+
"() => typeof grecaptcha!=='undefined' && !!grecaptcha.enterprise "
|
|
275
|
+
"&& typeof grecaptcha.enterprise.execute==='function'"
|
|
276
|
+
)
|
|
277
|
+
except Exception:
|
|
278
|
+
ready = False
|
|
279
|
+
if ready:
|
|
280
|
+
break
|
|
281
|
+
page.wait_for_timeout(500)
|
|
282
|
+
if not ready:
|
|
283
|
+
browser.close()
|
|
284
|
+
raise RuntimeError("grecaptcha.enterprise never appeared on the page")
|
|
285
|
+
|
|
286
|
+
wiz = page.evaluate(
|
|
287
|
+
"""() => {
|
|
288
|
+
const w = window.WIZ_global_data || {};
|
|
289
|
+
return {at: w.SNlM0e || null, bl: w.cfb2h || null, fsid: w.FdrFJe || null};
|
|
290
|
+
}"""
|
|
291
|
+
)
|
|
292
|
+
log("wiz:", json.dumps(wiz))
|
|
293
|
+
|
|
294
|
+
# Give reCAPTCHA a little genuine interaction to score before asking for a
|
|
295
|
+
# token. This measurably helps: a token minted 0.1s after page load can be
|
|
296
|
+
# scored UNUSUAL_ACTIVITY while the same browser passes after a few seconds
|
|
297
|
+
# of mouse movement / scrolling.
|
|
298
|
+
if warmup_s > 0:
|
|
299
|
+
try:
|
|
300
|
+
page.mouse.move(320, 280)
|
|
301
|
+
steps = max(2, int(warmup_s * 2))
|
|
302
|
+
for i in range(steps):
|
|
303
|
+
page.mouse.move(320 + (i * 37) % 400, 280 + (i * 53) % 260, steps=4)
|
|
304
|
+
if i % 3 == 0:
|
|
305
|
+
page.mouse.wheel(0, 120)
|
|
306
|
+
page.wait_for_timeout(int(warmup_s * 1000 / steps))
|
|
307
|
+
log("warmup %.1fs done" % warmup_s)
|
|
308
|
+
except Exception as e:
|
|
309
|
+
log("warmup skipped:", e)
|
|
310
|
+
|
|
311
|
+
t0 = time.time()
|
|
312
|
+
try:
|
|
313
|
+
token = page.evaluate(
|
|
314
|
+
"""(args) => new Promise((res, rej) => {
|
|
315
|
+
try {
|
|
316
|
+
grecaptcha.enterprise.ready(() => {
|
|
317
|
+
grecaptcha.enterprise.execute(args.key, {action: args.action})
|
|
318
|
+
.then(res, rej);
|
|
319
|
+
});
|
|
320
|
+
} catch (e) { rej(String(e)); }
|
|
321
|
+
})""",
|
|
322
|
+
{"key": site_key, "action": action},
|
|
323
|
+
)
|
|
324
|
+
except Exception as e:
|
|
325
|
+
browser.close()
|
|
326
|
+
raise RuntimeError(f"grecaptcha.enterprise.execute failed: {e}")
|
|
327
|
+
log(
|
|
328
|
+
"token minted in %.2fs len=%d prefix=%s"
|
|
329
|
+
% (time.time() - t0, len(token), token[:10])
|
|
330
|
+
)
|
|
331
|
+
if keep_open_s:
|
|
332
|
+
page.wait_for_timeout(int(keep_open_s * 1000))
|
|
333
|
+
browser.close()
|
|
334
|
+
return {
|
|
335
|
+
"token": token,
|
|
336
|
+
"at": wiz.get("at"),
|
|
337
|
+
"bl": wiz.get("bl"),
|
|
338
|
+
"fsid": wiz.get("fsid"),
|
|
339
|
+
"page_url": url,
|
|
340
|
+
"headless": not headed,
|
|
341
|
+
"channel": channel,
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
# --------------------------------------------------------------------------- #
|
|
346
|
+
# proofs
|
|
347
|
+
# --------------------------------------------------------------------------- #
|
|
348
|
+
def prove_image(bx, project: str, token: str, prompt: str, out_path: Path) -> dict:
|
|
349
|
+
seed = random.randint(10**8, 2**31 - 1)
|
|
350
|
+
u1 = str(uuid.uuid4()).upper()
|
|
351
|
+
u2 = str(uuid.uuid4()).upper()
|
|
352
|
+
inner = [
|
|
353
|
+
None,
|
|
354
|
+
[[None, None, None, seed, 1, "GEM_PIX_2", None,
|
|
355
|
+
[None, 22, None, None, None, project, None, None, None, None, [token, 1]],
|
|
356
|
+
[[[prompt]]],
|
|
357
|
+
None, None, None, u1, u2]],
|
|
358
|
+
1,
|
|
359
|
+
[None, 22, None, None, None, project, None, None, None, None, [token, 1]],
|
|
360
|
+
]
|
|
361
|
+
status, raw = bx("ogiZ0b", inner)
|
|
362
|
+
chunks = dechunk(raw)
|
|
363
|
+
payload = next((o for rid, o in chunks if rid == "ogiZ0b"), None)
|
|
364
|
+
urls = sorted(set(walk_strings(payload, lambda s: s.startswith("https://flow-content.google/"))))
|
|
365
|
+
snippet = raw[:600]
|
|
366
|
+
|
|
367
|
+
failed = False
|
|
368
|
+
error_text = None
|
|
369
|
+
if status != 200:
|
|
370
|
+
failed = True
|
|
371
|
+
error_text = f"HTTP {status}"
|
|
372
|
+
elif not urls:
|
|
373
|
+
failed = True
|
|
374
|
+
# error details live in the wrb.fr item[5], which dechunk() does not expose
|
|
375
|
+
codes = re.findall(r"PUBLIC_ERROR_[A-Z_]+", raw)
|
|
376
|
+
if codes:
|
|
377
|
+
error_text = codes[0]
|
|
378
|
+
elif payload is not None:
|
|
379
|
+
error_text = json.dumps(payload)[:400]
|
|
380
|
+
else:
|
|
381
|
+
error_text = "no flow-content URL in response"
|
|
382
|
+
|
|
383
|
+
saved = None
|
|
384
|
+
if not failed:
|
|
385
|
+
try:
|
|
386
|
+
req = urllib.request.Request(urls[-1], headers={"user-agent": UA_DEFAULT})
|
|
387
|
+
with urllib.request.urlopen(req, timeout=120) as r:
|
|
388
|
+
data = r.read()
|
|
389
|
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
390
|
+
out_path.write_bytes(data)
|
|
391
|
+
saved = {
|
|
392
|
+
"path": str(out_path),
|
|
393
|
+
"bytes": len(data),
|
|
394
|
+
"content_type": r.headers.get("content-type"),
|
|
395
|
+
"magic": data[:12].hex(),
|
|
396
|
+
}
|
|
397
|
+
except Exception as e:
|
|
398
|
+
failed = True
|
|
399
|
+
error_text = f"download failed: {e}"
|
|
400
|
+
|
|
401
|
+
return {
|
|
402
|
+
"ok": not failed,
|
|
403
|
+
"http_status": status,
|
|
404
|
+
"rpc": "ogiZ0b",
|
|
405
|
+
"urls": urls,
|
|
406
|
+
"error": error_text,
|
|
407
|
+
"saved": saved,
|
|
408
|
+
"response_head": snippet.replace("\n", "\\n"),
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def probe_video_rpc(bx, project: str, token: str, prompt: str) -> dict:
|
|
413
|
+
"""Call YhhmEf with the minted token and report whether the *auth* was accepted.
|
|
414
|
+
|
|
415
|
+
A successful (accepted) call creates one 8s video job -> counts as a generation.
|
|
416
|
+
Observed 2026-12-06:
|
|
417
|
+
- action IMAGE_GENERATION -> PUBLIC_ERROR_UNUSUAL_ACTIVITY (token rejected)
|
|
418
|
+
- action VIDEO_GENERATION -> auth accepted, PUBLIC_ERROR_USER_QUOTA_REACHED
|
|
419
|
+
(this account has no video quota; nothing wrong with the token)
|
|
420
|
+
"""
|
|
421
|
+
u1 = str(uuid.uuid4()).upper()
|
|
422
|
+
u2 = str(uuid.uuid4()).upper()
|
|
423
|
+
inner = [
|
|
424
|
+
[[[None, None, [[[prompt]]]],
|
|
425
|
+
"macaron_cookie_t2v_8s", 2, None,
|
|
426
|
+
[None, None, None, None, u1, u2]]],
|
|
427
|
+
[None, 22, None, None, None, project, None, None, None, None, [token, 1]],
|
|
428
|
+
[u1, 1],
|
|
429
|
+
]
|
|
430
|
+
status, raw = bx("YhhmEf", inner)
|
|
431
|
+
chunks = dechunk(raw)
|
|
432
|
+
payload = next((o for rid, o in chunks if rid == "YhhmEf"), None)
|
|
433
|
+
media_ids = []
|
|
434
|
+
if payload is not None:
|
|
435
|
+
for s in walk_strings(payload, lambda s: bool(re.fullmatch(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", s))):
|
|
436
|
+
if s not in media_ids:
|
|
437
|
+
media_ids.append(s)
|
|
438
|
+
rejected = "PUBLIC_ERROR_UNUSUAL_ACTIVITY" in raw
|
|
439
|
+
errors = sorted(set(re.findall(r"PUBLIC_ERROR_[A-Z_]+", raw)))
|
|
440
|
+
return {
|
|
441
|
+
"ok": status == 200 and not rejected and bool(media_ids),
|
|
442
|
+
"auth_accepted": status == 200 and not rejected,
|
|
443
|
+
"http_status": status,
|
|
444
|
+
"rpc": "YhhmEf",
|
|
445
|
+
"media_ids": media_ids,
|
|
446
|
+
"rejected": rejected,
|
|
447
|
+
"errors": errors,
|
|
448
|
+
"response_head": raw[:500].replace("\n", "\\n"),
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
# --------------------------------------------------------------------------- #
|
|
453
|
+
# main
|
|
454
|
+
# --------------------------------------------------------------------------- #
|
|
455
|
+
def main() -> int:
|
|
456
|
+
ap = argparse.ArgumentParser(
|
|
457
|
+
description="Mint a reCAPTCHA Enterprise token for flow.google.com (no user browser needed)."
|
|
458
|
+
)
|
|
459
|
+
ap.add_argument("--action", default=ACTION_DEFAULT,
|
|
460
|
+
help=f"reCAPTCHA action (default {ACTION_DEFAULT})")
|
|
461
|
+
ap.add_argument("--out", default=None,
|
|
462
|
+
help="file to write the token to (default auth_lab/out/recaptcha_token.txt)")
|
|
463
|
+
ap.add_argument("--cookies", default=None,
|
|
464
|
+
help="Playwright-format cookie JSON (default: team fixtures flow_cookies.json)")
|
|
465
|
+
ap.add_argument("--project", default=PROJECT_DEFAULT)
|
|
466
|
+
ap.add_argument("--site-key", default=SITE_KEY_DEFAULT)
|
|
467
|
+
ap.add_argument("--headed", action="store_true", help="run a visible Chromium window")
|
|
468
|
+
ap.add_argument("--channel", default=None,
|
|
469
|
+
help="Playwright browser channel, e.g. 'chrome' to use system Google Chrome")
|
|
470
|
+
ap.add_argument("--timeout", type=int, default=60000, help="page timeout in ms")
|
|
471
|
+
ap.add_argument("--warmup", type=float, default=3.0,
|
|
472
|
+
help="seconds of mouse/scroll warm-up before minting (default 3)")
|
|
473
|
+
ap.add_argument("--retries", type=int, default=1,
|
|
474
|
+
help="with --prove: retry attempts on UNUSUAL_ACTIVITY (default 1 retry)")
|
|
475
|
+
ap.add_argument("--retry-delay", type=float, default=15.0,
|
|
476
|
+
help="seconds to wait between prove attempts (default 15)")
|
|
477
|
+
ap.add_argument("--prove", action="store_true",
|
|
478
|
+
help="immediately run one real ogiZ0b image generation with the token and PASS/FAIL")
|
|
479
|
+
ap.add_argument("--prompt", default="A green pear on a white ceramic plate, soft daylight, photo")
|
|
480
|
+
ap.add_argument("--image-out", default=None,
|
|
481
|
+
help="where --prove saves the generated image (default auth_lab/out/prove_image.jpg)")
|
|
482
|
+
ap.add_argument("--video-probe", action="store_true",
|
|
483
|
+
help="bonus: test whether the minted token (--action) is accepted by the video RPC YhhmEf")
|
|
484
|
+
ap.add_argument("--session-out", default=None,
|
|
485
|
+
help="optional: write {at,bl,fsid,cookie_file} JSON for a client to reuse")
|
|
486
|
+
ap.add_argument("--json", action="store_true", help="print the final result as JSON")
|
|
487
|
+
args = ap.parse_args()
|
|
488
|
+
|
|
489
|
+
cookies_file = find_cookies_file(args.cookies)
|
|
490
|
+
cookies = json.loads(cookies_file.read_text())
|
|
491
|
+
out_path = Path(args.out) if args.out else HERE / "out" / "recaptcha_token.txt"
|
|
492
|
+
image_out = Path(args.image_out) if args.image_out else HERE / "out" / "prove_image.jpg"
|
|
493
|
+
|
|
494
|
+
print(f"[mint] cookies: {cookies_file} ({len(cookies)} cookies)", file=sys.stderr)
|
|
495
|
+
result: dict = {
|
|
496
|
+
"ok": False,
|
|
497
|
+
"action": args.action,
|
|
498
|
+
"token_file": str(out_path),
|
|
499
|
+
"headless": not args.headed,
|
|
500
|
+
}
|
|
501
|
+
attempts = 1 + max(0, args.retries)
|
|
502
|
+
minted = None
|
|
503
|
+
proof = None
|
|
504
|
+
ch = cookie_header(cookies)
|
|
505
|
+
|
|
506
|
+
for attempt in range(1, attempts + 1):
|
|
507
|
+
if attempt > 1:
|
|
508
|
+
print(f"[mint] attempt {attempt}/{attempts} after {args.retry_delay}s", file=sys.stderr)
|
|
509
|
+
time.sleep(args.retry_delay)
|
|
510
|
+
try:
|
|
511
|
+
minted = mint_token_via_playwright(
|
|
512
|
+
cookies=cookies,
|
|
513
|
+
project=args.project,
|
|
514
|
+
site_key=args.site_key,
|
|
515
|
+
action=args.action,
|
|
516
|
+
headed=args.headed,
|
|
517
|
+
channel=args.channel,
|
|
518
|
+
timeout_ms=args.timeout,
|
|
519
|
+
warmup_s=args.warmup,
|
|
520
|
+
)
|
|
521
|
+
except Exception as e:
|
|
522
|
+
print(f"[mint] browser/mint FAIL: {e}", file=sys.stderr)
|
|
523
|
+
if attempt < attempts:
|
|
524
|
+
continue
|
|
525
|
+
return 2
|
|
526
|
+
|
|
527
|
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
528
|
+
out_path.write_text(minted["token"])
|
|
529
|
+
print(f"[mint] token saved: {out_path} ({len(minted['token'])} chars)", file=sys.stderr)
|
|
530
|
+
result.update({
|
|
531
|
+
"token_prefix": minted["token"][:16],
|
|
532
|
+
"token_len": len(minted["token"]),
|
|
533
|
+
"at": minted["at"],
|
|
534
|
+
"bl": minted["bl"],
|
|
535
|
+
"fsid": minted["fsid"],
|
|
536
|
+
})
|
|
537
|
+
|
|
538
|
+
if args.session_out:
|
|
539
|
+
session_path = Path(args.session_out)
|
|
540
|
+
session_path.parent.mkdir(parents=True, exist_ok=True)
|
|
541
|
+
session_path.write_text(json.dumps({
|
|
542
|
+
"at": minted["at"], "bl": minted["bl"], "fsid": minted["fsid"],
|
|
543
|
+
"cookie_file": str(cookies_file),
|
|
544
|
+
}, indent=1))
|
|
545
|
+
print(f"[mint] session saved: {session_path}", file=sys.stderr)
|
|
546
|
+
|
|
547
|
+
if not minted.get("at") or not minted.get("bl") or not minted.get("fsid"):
|
|
548
|
+
print("[mint] WARN: could not scrape at/bl/fsid from page WIZ_global_data", file=sys.stderr)
|
|
549
|
+
|
|
550
|
+
if not args.prove:
|
|
551
|
+
result["ok"] = True
|
|
552
|
+
break
|
|
553
|
+
|
|
554
|
+
bx = make_batchexecute(ch, UA_DEFAULT, args.project,
|
|
555
|
+
{"at": minted["at"], "bl": minted["bl"], "fsid": minted["fsid"]})
|
|
556
|
+
proof = prove_image(bx, args.project, minted["token"], args.prompt, image_out)
|
|
557
|
+
result["prove"] = proof
|
|
558
|
+
print("\n=== PROVE ogiZ0b (attempt %d/%d) ===" % (attempt, attempts))
|
|
559
|
+
print("HTTP", proof["http_status"])
|
|
560
|
+
if proof["ok"]:
|
|
561
|
+
print("PASS: signed URL(s):", proof["urls"])
|
|
562
|
+
print("saved:", proof["saved"])
|
|
563
|
+
result["ok"] = True
|
|
564
|
+
break
|
|
565
|
+
print("FAIL:", proof["error"])
|
|
566
|
+
print("response head:", proof["response_head"][:400])
|
|
567
|
+
result["ok"] = False
|
|
568
|
+
|
|
569
|
+
if args.video_probe:
|
|
570
|
+
# NOTE: does consume one video generation if the account has quota. Use deliberately.
|
|
571
|
+
minted2 = mint_token_via_playwright(
|
|
572
|
+
cookies=cookies, project=args.project, site_key=args.site_key,
|
|
573
|
+
action=args.action, headed=args.headed, channel=args.channel,
|
|
574
|
+
timeout_ms=args.timeout, warmup_s=args.warmup,
|
|
575
|
+
)
|
|
576
|
+
ch = cookie_header(cookies)
|
|
577
|
+
bx = make_batchexecute(ch, UA_DEFAULT, args.project,
|
|
578
|
+
{"at": minted2["at"], "bl": minted2["bl"], "fsid": minted2["fsid"]})
|
|
579
|
+
probe = probe_video_rpc(
|
|
580
|
+
bx, args.project, minted2["token"], "A paper airplane gliding over a wooden desk"
|
|
581
|
+
)
|
|
582
|
+
result["video_probe"] = probe
|
|
583
|
+
print("\n=== BONUS video RPC token check (action=%s) ===" % args.action)
|
|
584
|
+
print("HTTP", probe["http_status"],
|
|
585
|
+
"| auth accepted:", probe["auth_accepted"],
|
|
586
|
+
"| media_ids:", probe["media_ids"],
|
|
587
|
+
"| errors:", probe["errors"])
|
|
588
|
+
print("head:", probe["response_head"][:300])
|
|
589
|
+
|
|
590
|
+
if args.json:
|
|
591
|
+
print(json.dumps(result, indent=1))
|
|
592
|
+
return 0 if result.get("ok") else 3
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
if __name__ == "__main__":
|
|
596
|
+
sys.exit(main())
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
|
|
4
|
+
const { execSync, spawn } = require("child_process");
|
|
5
|
+
const path = require("path");
|
|
6
|
+
const fs = require("fs");
|
|
7
|
+
|
|
8
|
+
const ROOT = path.resolve(__dirname, "..");
|
|
9
|
+
const SERVER = path.join(ROOT, "server.py");
|
|
10
|
+
|
|
11
|
+
function log(msg) {
|
|
12
|
+
process.stderr.write(`\x1b[36m[google-flow-api]\x1b[0m ${msg}\n`);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function findPython() {
|
|
16
|
+
for (const cmd of ["python3", "python"]) {
|
|
17
|
+
try {
|
|
18
|
+
const out = execSync(
|
|
19
|
+
`${cmd} -c "import sys;print('%d.%d' % sys.version_info[:2])"`,
|
|
20
|
+
{ encoding: "utf-8", timeout: 5000, stdio: ["pipe", "pipe", "pipe"] }
|
|
21
|
+
).trim();
|
|
22
|
+
const [major, minor] = out.split(".").map(Number);
|
|
23
|
+
if (major >= 3 && minor >= 10) return cmd;
|
|
24
|
+
} catch {
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function checkDeps(python) {
|
|
32
|
+
const probe =
|
|
33
|
+
"import mcp, requests, browser_cookie3, playwright; print('ok')";
|
|
34
|
+
try {
|
|
35
|
+
execSync(`${python} -c "${probe}"`, { stdio: "ignore", timeout: 8000 });
|
|
36
|
+
return true;
|
|
37
|
+
} catch {
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function main() {
|
|
43
|
+
const python = findPython();
|
|
44
|
+
if (!python) {
|
|
45
|
+
process.stderr.write("Python 3.10+ is required to run google-flow-api-mcp\n");
|
|
46
|
+
process.exit(1);
|
|
47
|
+
}
|
|
48
|
+
if (!checkDeps(python)) {
|
|
49
|
+
log("Python dependencies missing — running postinstall.js");
|
|
50
|
+
try {
|
|
51
|
+
execSync(`node "${path.join(ROOT, "postinstall.js")}"`, { stdio: "inherit" });
|
|
52
|
+
} catch {
|
|
53
|
+
process.stderr.write(
|
|
54
|
+
`pip install failed. Run: ${python} -m pip install mcp requests browser_cookie3 playwright\n`
|
|
55
|
+
);
|
|
56
|
+
process.exit(1);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
if (!fs.existsSync(SERVER)) {
|
|
60
|
+
process.stderr.write(`server.py not found at ${SERVER}\n`);
|
|
61
|
+
process.exit(1);
|
|
62
|
+
}
|
|
63
|
+
const child = spawn(python, [SERVER, ...process.argv.slice(2)], {
|
|
64
|
+
stdio: "inherit",
|
|
65
|
+
cwd: ROOT,
|
|
66
|
+
env: process.env,
|
|
67
|
+
});
|
|
68
|
+
child.on("error", (err) => {
|
|
69
|
+
process.stderr.write(`failed to start: ${err.message}\n`);
|
|
70
|
+
process.exit(1);
|
|
71
|
+
});
|
|
72
|
+
child.on("exit", (code) => process.exit(code ?? 1));
|
|
73
|
+
for (const sig of ["SIGINT", "SIGTERM"]) {
|
|
74
|
+
process.on(sig, () => child.kill(sig));
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
main();
|