forked from renniepak/CSPBypass
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
227 lines (204 loc) · 7.85 KB
/
script.js
File metadata and controls
227 lines (204 loc) · 7.85 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
document.addEventListener('DOMContentLoaded', () => {
/**
* Elements from the DOM
*/
const searchInput = document.getElementById('search');
const resultsList = document.getElementById('results');
const resultsCount = document.getElementById('resultsCount');
const creditsSpan = document.getElementById('credits');
const copyStatus = document.getElementById('copy-status'); // Screen‑reader only
const toast = document.getElementById('toast'); // Visible toast
/**
* Data variables
*/
let tsvData = [];
let debounceTimeout;
/**
* Encodes a string to prevent HTML injection.
* @param {string} str - The string to encode.
* @returns {string} - The encoded string.
*/
const htmlEncode = (str) => {
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
};
/**
* Debounces a function to limit the rate at which it can fire.
* @param {Function} func - The function to debounce.
* @param {number} delay - The delay in milliseconds.
* @returns {Function} - The debounced function.
*/
const debounce = (func, delay) => {
return (...args) => {
clearTimeout(debounceTimeout);
debounceTimeout = setTimeout(() => func(...args), delay);
};
};
/**
* Parses TSV data into an array of objects.
* @param {string} tsv - The TSV data as a string.
* @returns {Array} - An array of parsed objects.
*/
const parseTSV = (tsv) => {
return tsv
.trim()
// Split on newlines, then ignore the first line (which is presumably headers)
.split('\n')
.slice(1)
.map(line => {
line = line.trim();
// This regex captures:
// ^(\S+) => first sequence of non-whitespace (domain)
// \s+ => the first block of whitespace
// (.*) => everything else (the code) as the second capture
const match = line.match(/^(\S+)\s+(.*)$/);
// If the line doesn't match our pattern, skip it
if (!match) return null;
// match[1] = domain, match[2] = entire code block
const domain = match[1];
const code = match[2];
return domain && code ? {
domain,
code
} : null;
})
.filter(Boolean);
};
/**
* Shows a short-lived toast message.
* @param {string} message - The message to display.
*/
const showToast = (message) => {
toast.textContent = message;
toast.classList.add('show');
clearTimeout(showToast.timeoutId);
showToast.timeoutId = setTimeout(() => toast.classList.remove('show'), 1500);
};
/**
* Fetches and displays credits from GitHub.
*/
const fetchCredits = async () => {
try {
const response = await fetch('https://api.github.com/repos/renniepak/CSPBypass/contents/credits.txt?ref=main', {
headers: {
'Accept': 'application/vnd.github.v3.raw'
}
});
const data = await response.text();
creditsSpan.textContent = data.trim().split(/\r?\n/).join(', ');
} catch (error) {
console.error('Error fetching credits:', error);
}
};
/**
* Displays the search results in the results list.
* @param {Array} data - The data to display.
*/
const displayResults = (data) => {
resultsList.innerHTML = data.length ?
data.map(item => `<li><strong>${htmlEncode(item.domain)}</strong><br><br><span class="code">${htmlEncode(item.code)}</span></li>`).join('') :
'<li>No results found</li>';
resultsCount.textContent = data.length;
};
/**
* Copy handler (event delegation on the results <ul>).
*/
resultsList.addEventListener('click', (event) => {
const li = event.target.closest('li');
if (!li || !resultsList.contains(li)) return;
const codeSpan = li.querySelector('.code');
if (!codeSpan) return;
const payload = codeSpan.textContent;
navigator.clipboard.writeText(payload)
.then(() => {
// Visual feedback
li.classList.add('copied');
setTimeout(() => li.classList.remove('copied'), 800);
showToast('Payload copied 📋');
// Screen‑reader feedback
copyStatus.textContent = 'Payload copied';
})
.catch(err => console.error('Clipboard copy failed:', err));
});
/**
* Processes script-src or default-src directives.
* @param {string} cspDirective - The CSP directive string.
* @returns {Array} - An array of processed items.
*/
const processCSPDirective = (cspDirective) => {
const items = cspDirective.split(' ').flatMap(item => {
if (item.includes('*')) {
const cleanItem = item.replace(/https?:\/\//, '').split('*').slice(-2).join('');
return [cleanItem.startsWith('.') ? cleanItem : '.' + cleanItem];
}
return item.includes('.') ? item : [];
});
return Array.from(new Set(items));
};
/**
* Filters the data based on query items and displays the results.
* @param {Array} queryItems - The items to filter by.
*/
const filterAndDisplay = (queryItems) => {
const results = tsvData.filter(data =>
queryItems.some(item => data.domain.includes(item) || data.code.includes(item))
);
displayResults(results);
};
/**
* Applies the search logic based on the query.
* @param {string} query - The search query.
*/
const applySearch = (query) => {
const trimmedQuery = query.trim().toLowerCase();
if (!trimmedQuery) {
resultsList.innerHTML = '';
resultsCount.textContent = 0;
return;
}
if (trimmedQuery.includes('script-src') || trimmedQuery.includes('default-src')) {
const directive = trimmedQuery.includes('script-src') ? 'script-src' : 'default-src';
const cspDirective = trimmedQuery.split(directive)[1]?.split(';')[0]?.trim();
if (cspDirective) {
const processedItems = processCSPDirective(cspDirective);
filterAndDisplay(processedItems);
return;
}
}
const results = tsvData.filter(item =>
item.domain.toLowerCase().includes(trimmedQuery) ||
item.code.toLowerCase().includes(trimmedQuery)
);
displayResults(results);
};
/**
* Initializes the application by fetching data and setting up event listeners.
*/
const initialize = async () => {
await fetchCredits();
try {
const response = await fetch('https://api.github.com/repos/renniepak/CSPBypass/contents/data.tsv?ref=main', {
headers: {
'Accept': 'application/vnd.github.v3.raw'
}
});
const data = await response.text();
tsvData = parseTSV(data);
if (window.location.hash) {
const query = decodeURIComponent(window.location.hash.substring(1));
searchInput.value = query;
applySearch(query);
}
} catch (error) {
console.error('Error fetching TSV data:', error);
}
searchInput.addEventListener('input', debounce(() => {
const query = searchInput.value;
applySearch(query);
window.location.hash = encodeURIComponent(query);
}, 300));
};
// Start the application
initialize();
});