-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterceptor.js
More file actions
228 lines (196 loc) · 6.88 KB
/
Copy pathinterceptor.js
File metadata and controls
228 lines (196 loc) · 6.88 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
/**
* interceptor.js — Injected into the page context via the content script.
*
* Monkey-patches XMLHttpRequest and fetch() to capture request/response
* details and relay them back to the content script via window.postMessage.
*/
(function () {
'use strict';
if (window.__apiCatcherInjected) return;
window.__apiCatcherInjected = true;
const MSG_TYPE = '__API_CATCHER_LOG__';
// ── Helpers ──────────────────────────────────────────────────────────
function safeStringify(obj) {
try {
return JSON.stringify(obj);
} catch {
return String(obj);
}
}
function headersToObject(headers) {
const out = {};
if (headers instanceof Headers) {
headers.forEach((v, k) => { out[k] = v; });
} else if (Array.isArray(headers)) {
headers.forEach(([k, v]) => { out[k] = v; });
} else if (headers && typeof headers === 'object') {
Object.assign(out, headers);
}
return out;
}
function post(entry) {
window.postMessage({ type: MSG_TYPE, payload: entry }, '*');
}
// ── Fetch interception ──────────────────────────────────────────────
const originalFetch = window.fetch;
window.fetch = async function (...args) {
const [resource, init] = args;
const url = typeof resource === 'string'
? resource
: resource instanceof Request
? resource.url
: String(resource);
const method = (init?.method
|| (resource instanceof Request ? resource.method : 'GET')).toUpperCase();
let reqHeaders = headersToObject(
init?.headers || (resource instanceof Request ? resource.headers : {})
);
let reqBody = null;
if (init?.body !== undefined) {
reqBody = typeof init.body === 'string' ? init.body : safeStringify(init.body);
} else if (resource instanceof Request) {
try { reqBody = await resource.clone().text(); } catch { /* empty */ }
}
// No modification rules applied
// Re-create the arguments for fetch
const newArgs = [...args];
const bodyAllowed = !['GET', 'HEAD'].includes(method);
if (newArgs[1]) { // if init object exists
newArgs[1].headers = reqHeaders;
if (bodyAllowed && reqBody !== null) {
newArgs[1].body = reqBody;
}
} else if (newArgs[0] instanceof Request) {
const oldRequest = newArgs[0];
const newRequestInit = {
method: oldRequest.method,
headers: reqHeaders,
mode: oldRequest.mode,
credentials: oldRequest.credentials,
cache: oldRequest.cache,
redirect: oldRequest.redirect,
referrer: oldRequest.referrer,
integrity: oldRequest.integrity,
};
if (bodyAllowed && reqBody !== null) {
newRequestInit.body = reqBody;
}
newArgs[0] = new Request(oldRequest.url, newRequestInit);
} else {
newArgs[1] = { headers: reqHeaders };
if (bodyAllowed && reqBody !== null) {
newArgs[1].body = reqBody;
}
}
const timestamp = new Date().toISOString();
const startTime = performance.now();
const initiator = {
url: window.location.href,
title: document.title,
};
try {
const response = await originalFetch.apply(this, newArgs);
const duration = Math.round(performance.now() - startTime);
const resHeaders = headersToObject(response.headers);
let resBody = null;
try {
const clone = response.clone();
resBody = await clone.text();
} catch { /* empty */ }
post({
id: crypto.randomUUID(),
type: 'fetch',
method,
url,
status: response.status,
statusText: response.statusText,
timestamp,
duration,
initiator,
request: { headers: reqHeaders, body: reqBody },
response: { headers: resHeaders, body: resBody },
});
return response;
} catch (err) {
const duration = Math.round(performance.now() - startTime);
post({
id: crypto.randomUUID(),
type: 'fetch',
method,
url,
status: 0,
statusText: 'Network Error',
timestamp,
duration,
initiator,
request: { headers: reqHeaders, body: reqBody },
response: { headers: {}, body: null },
error: err.message,
});
throw err;
}
};
// ── XHR interception ────────────────────────────────────────────────
const XHR = XMLHttpRequest;
const originalOpen = XHR.prototype.open;
const originalSend = XHR.prototype.send;
const originalSetRequestHeader = XHR.prototype.setRequestHeader;
XHR.prototype.open = function (method, url, ...rest) {
this.__ac = {
method: method.toUpperCase(),
url: String(url),
reqHeaders: {},
startTime: null,
};
return originalOpen.call(this, method, url, ...rest);
};
XHR.prototype.setRequestHeader = function (name, value) {
if (this.__ac) {
this.__ac.reqHeaders[name] = value;
}
return originalSetRequestHeader.call(this, name, value);
};
XHR.prototype.send = function (body) {
if (this.__ac) {
const meta = this.__ac;
// No modification rules applied
const newBody = body; // Use original body
// Re-apply modified headers
for (const name in meta.reqHeaders) {
originalSetRequestHeader.call(this, name, meta.reqHeaders[name]);
}
meta.startTime = performance.now();
meta.reqBody = typeof newBody === 'string' ? newBody : safeStringify(newBody);
meta.timestamp = new Date().toISOString();
meta.initiator = {
url: window.location.href,
title: document.title,
};
this.addEventListener('loadend', function () {
const duration = Math.round(performance.now() - meta.startTime);
const resHeaders = {};
(this.getAllResponseHeaders() || '').trim().split(/\r?\n/).forEach((line) => {
const idx = line.indexOf(':');
if (idx > 0) {
resHeaders[line.slice(0, idx).trim().toLowerCase()] = line.slice(idx + 1).trim();
}
});
post({
id: crypto.randomUUID(),
type: 'xhr',
method: meta.method,
url: meta.url,
status: this.status,
statusText: this.statusText,
timestamp: meta.timestamp,
duration,
initiator: meta.initiator,
request: { headers: meta.reqHeaders, body: meta.reqBody },
response: { headers: resHeaders, body: this.responseText },
});
});
return originalSend.call(this, newBody);
}
return originalSend.call(this, body);
};
})();