Repository navigation
Expand file tree
/
Copy pathengine.js
More file actions
296 lines (256 loc) · 9.5 KB
/
Copy pathengine.js
File metadata and controls
296 lines (256 loc) · 9.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
(() => {
'use strict';
if (typeof window !== 'undefined' && window.__flowLocalDiagnostic) return;
const DIAGNOSTIC_ATTR = 'data-flow-local-diagnostic';
const diagnostic = (typeof window !== 'undefined' && (window.__flowLocalDiagnostic = {
state: 'armed',
applied: 0,
before: null,
})) || { state: 'armed', applied: 0 };
let spec = {
origin: 'https://flow.google.com',
path: '/_/AiSandboxAngularFrontend/data/batchexecute',
rpcids: 'cPZSdc',
tag: 'wrb.fr',
flagIndex: 30,
minLength: 32,
};
function setDiagnostic(state, before) {
diagnostic.state = state;
if (before !== undefined) diagnostic.before = before;
console.info('[FlowPass]', JSON.stringify(diagnostic));
const syncAttr = () => {
if (typeof document !== 'undefined' && document.documentElement) {
document.documentElement.setAttribute(DIAGNOSTIC_ATTR, JSON.stringify(diagnostic));
}
};
if (typeof document !== 'undefined') {
if (document.documentElement) {
syncAttr();
} else {
document.addEventListener('DOMContentLoaded', syncAttr, { once: true });
}
}
}
function reportEngineError(code, err, context = {}) {
if (typeof window === 'undefined' || typeof window.postMessage !== 'function') return;
try {
const origin = (typeof location !== 'undefined' && location.origin && location.origin !== 'null')
? location.origin
: (spec.origin || 'https://flow.google.com');
window.postMessage({
type: 'cfc-flow-error',
error: {
source: 'engine',
code,
message: err?.message || String(err || 'Unknown engine error'),
stack: err?.stack || '',
context: {
specVersion: spec.v ?? 1,
rpcids: spec.rpcids,
...context,
},
},
}, origin);
} catch {}
}
function isBatchexecuteRequest(rawUrl) {
if (!rawUrl) return false;
try {
const defaultOrigin = (typeof location !== 'undefined' && location.origin) || spec.origin || 'https://flow.google.com';
const parsedUrl = new URL(rawUrl, defaultOrigin);
if (parsedUrl.origin !== defaultOrigin) return false;
if (!parsedUrl.pathname.includes('/data/batchexecute')) return false;
const rpcidsParam = parsedUrl.searchParams.get('rpcids');
if (rpcidsParam) {
const ids = rpcidsParam.split(',');
if (ids.includes(spec.rpcids)) return true;
}
if (parsedUrl.search.includes(spec.rpcids)) return true;
return false;
} catch {
return false;
}
}
function patchResponseBody(responseBody, currentSpec) {
const lines = responseBody.split('\n');
let beforeValue;
let patchCount = 0;
for (let i = 0; i < lines.length; i++) {
if (!lines[i].startsWith('[[')) continue;
let envelopes;
try {
envelopes = JSON.parse(lines[i]);
} catch {
continue;
}
let modified = false;
for (const item of envelopes) {
if (!Array.isArray(item) || item[0] !== currentSpec.tag || item[1] !== currentSpec.rpcids) {
continue;
}
let payload;
try {
payload = JSON.parse(item[2]);
} catch {
continue;
}
if (!Array.isArray(payload)) {
throw new Error('Unexpected config schema: payload is not an array');
}
// Expand payload if it was truncated
const minLen = Math.max(currentSpec.minLength || 32, currentSpec.flagIndex + 2);
while (payload.length < minLen) {
payload.push(null);
}
beforeValue = payload[currentSpec.flagIndex];
payload[currentSpec.flagIndex] = true;
// Also ensure age-restriction flag (index 31, field 32) is not false
if (payload[currentSpec.flagIndex + 1] === false || payload[currentSpec.flagIndex + 1] === null) {
payload[currentSpec.flagIndex + 1] = true;
}
patchCount++;
item[2] = JSON.stringify(payload);
modified = true;
}
if (modified) {
const rawLine = lines[i].replace(/\r$/, '');
const prevLength = Number(lines[i - 1]);
const byteLen = (str) => new TextEncoder().encode(str).length;
const lenFns = [byteLen, (str) => str.length];
const matchFn = lenFns.find((fn) => [0, 1, 2].includes(prevLength - fn(rawLine)));
const newJsonStr = JSON.stringify(envelopes);
if (matchFn && !Number.isNaN(prevLength)) {
lines[i - 1] = String(prevLength + matchFn(newJsonStr) - matchFn(rawLine));
}
lines[i] = newJsonStr;
}
}
if (patchCount === 0) {
throw new Error('Expected at least one config response');
}
return {
body: lines.join('\n'),
before: beforeValue,
};
}
// CommonJS export support for testing
if (typeof module !== 'undefined' && module.exports) {
module.exports = {
patch: (body) => patchResponseBody(body, spec),
isBatchexecuteRequest,
};
}
if (typeof window === 'undefined') return;
// 1. Hook window.fetch (used by modern Angular/Boq transport in flow.google.com)
if (typeof window.fetch === 'function') {
const originalFetch = window.fetch;
window.fetch = async function(input, init) {
const rawUrl = input instanceof Request ? input.url : String(input);
if (!isBatchexecuteRequest(rawUrl)) {
return originalFetch.apply(this, arguments);
}
const response = await originalFetch.apply(this, arguments);
try {
const cloned = response.clone();
const text = await cloned.text();
if (text.includes(spec.tag) && text.includes(spec.rpcids)) {
const patched = patchResponseBody(text, spec);
diagnostic.applied++;
setDiagnostic('applied', patched.before);
const newHeaders = new Headers(response.headers);
newHeaders.delete('content-length');
return new Response(patched.body, {
status: response.status,
statusText: response.statusText,
headers: newHeaders,
});
}
} catch (err) {
console.warn('[FlowPass] Fetch patch failed:', err);
setDiagnostic('schema mismatch — unchanged');
reportEngineError('SCHEMA_MISMATCH', err, { transport: 'fetch' });
}
return response;
};
}
// 2. Hook XMLHttpRequest (fallback / legacy transport)
if (typeof XMLHttpRequest !== 'undefined') {
const targetXhrMap = new WeakMap();
const appliedXhrMap = new WeakMap();
const xhrProto = XMLHttpRequest.prototype;
const originalXhrOpen = xhrProto.open;
xhrProto.open = function(method, url, ...args) {
let isTarget = false;
try {
isTarget = isBatchexecuteRequest(url);
} catch {}
targetXhrMap.set(this, isTarget);
appliedXhrMap.delete(this);
return Reflect.apply(originalXhrOpen, this, [method, url, ...args]);
};
for (const prop of ['responseText', 'response']) {
const desc = Object.getOwnPropertyDescriptor(xhrProto, prop);
if (!desc?.get || !desc.configurable) continue;
Object.defineProperty(xhrProto, prop, {
...desc,
get() {
const raw = Reflect.apply(desc.get, this, []);
if (!targetXhrMap.get(this) || typeof raw !== 'string') return raw;
if (this.readyState !== 4) return raw;
if (!appliedXhrMap.has(this)) {
try {
if (raw.includes(spec.tag) && raw.includes(spec.rpcids)) {
const patched = patchResponseBody(raw, spec);
appliedXhrMap.set(this, patched.body);
diagnostic.applied++;
setDiagnostic('applied', patched.before);
} else {
appliedXhrMap.set(this, raw);
}
} catch (err) {
console.warn('[FlowPass] XHR patch failed:', err);
appliedXhrMap.set(this, raw);
setDiagnostic('schema mismatch — unchanged');
reportEngineError('SCHEMA_MISMATCH', err, { transport: 'xhr' });
}
}
return appliedXhrMap.get(this);
},
});
}
}
// 3. Listen for spec updates from link.js
window.addEventListener('message', (event) => {
if (event.source !== window) return;
const data = event.data;
if (!data || data.type !== 'cfc-flow-spec') return;
if (data.spec && typeof data.spec === 'object') {
spec = Object.assign({}, spec, data.spec);
}
});
// 4. Router guard: Prevent client-side redirection to /unsupported-country
if (typeof window.history !== 'undefined') {
const originalPushState = window.history.pushState;
if (typeof originalPushState === 'function') {
window.history.pushState = function(state, title, url) {
if (typeof url === 'string' && url.includes('/unsupported-country')) {
console.info('[FlowPass] Intercepted router navigation to /unsupported-country');
return;
}
return Reflect.apply(originalPushState, this, arguments);
};
}
const originalReplaceState = window.history.replaceState;
if (typeof originalReplaceState === 'function') {
window.history.replaceState = function(state, title, url) {
if (typeof url === 'string' && url.includes('/unsupported-country')) {
console.info('[FlowPass] Intercepted router replaceState to /unsupported-country');
return;
}
return Reflect.apply(originalReplaceState, this, arguments);
};
}
}
setDiagnostic('armed');
})();