Skip to content

Commit 7d03026

Browse files
committed
added rate-limiting fetch function
1 parent b0a67fe commit 7d03026

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

app/templates/index.html

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,27 @@ <h2>Ask Defang</h2>
207207
}
208208
});
209209

210+
async function rateLimitingFetch(url, options = {}) {
211+
if (window.crypto && window.crypto.subtle) {
212+
let bodyHash, nonceArray = new Uint32Array(1), nonce = 0;
213+
const body = new TextEncoder().encode(options.body);
214+
const bodyWithNonce = new Uint8Array(nonceArray.byteLength + body.byteLength);
215+
bodyWithNonce.set(body, nonceArray.byteLength);
216+
217+
do {
218+
nonceArray[0] = ++nonce;
219+
bodyWithNonce.set(new Uint8Array(nonceArray.buffer));
220+
bodyHash = await crypto.subtle.digest('SHA-256', bodyWithNonce);
221+
} while(new DataView(bodyHash).getUint32(0) > 0x50000);
222+
223+
options.headers = {
224+
...options.headers,
225+
'X-Nonce': nonce
226+
}
227+
return fetch(url, options);
228+
}
229+
}
230+
210231
function sendQuery() {
211232
const query = queryInput.value.trim();
212233
if (query === '') return;
@@ -228,7 +249,7 @@ <h2>Ask Defang</h2>
228249
sendButton.disabled = true;
229250

230251
// Send query to server
231-
fetch('/ask', {
252+
rateLimitingFetch('/ask', {
232253
method: 'POST',
233254
headers: {
234255
'Content-Type': 'application/json',

0 commit comments

Comments
 (0)