Personal Telegram developer console for GitHub
feat: add approval replay durable object
davoodmehraban89 committed
Oct 3, 2026 at 06:30 UTC
b8c86744f7447082a70b2a7eb57da94a2d37ed69
1 file changed
+47
src/durable/approval-replay-guard.js
new
+47
@@ -0,0 +1,47 @@
1
+const json = (payload, status = 200) => Response.json(payload, { status });
2
+
3
+export class ApprovalReplayGuard {
4
+ constructor(state) {
5
+ this.state = state;
6
+ }
7
+
8
+ async fetch(request) {
9
+ const url = new URL(request.url);
10
+ if (request.method !== 'POST' || url.pathname !== '/consume') {
11
+ return new Response('Not Found', { status: 404 });
12
+ }
13
+
14
+ let payload;
15
+ try {
16
+ payload = await request.json();
17
+ } catch {
18
+ return json({ accepted: false, reason: 'invalid_payload' }, 400);
19
+ }
20
+
21
+ const expiresAt = Number(payload?.expiresAt);
22
+ if (!Number.isFinite(expiresAt)) {
23
+ return json({ accepted: false, reason: 'invalid_expiry' }, 400);
24
+ }
25
+ if (expiresAt < Date.now()) {
26
+ return json({ accepted: false, reason: 'expired' }, 410);
27
+ }
28
+
29
+ const accepted = await this.state.storage.transaction(async txn => {
30
+ const usedUntil = await txn.get('used');
31
+ if (usedUntil) return false;
32
+ await txn.put('used', expiresAt);
33
+ return true;
34
+ });
35
+
36
+ if (!accepted) {
37
+ return json({ accepted: false, reason: 'already_used' }, 409);
38
+ }
39
+
40
+ await this.state.storage.setAlarm(expiresAt);
41
+ return json({ accepted: true });
42
+ }
43
+
44
+ async alarm() {
45
+ await this.state.storage.deleteAll();
46
+ }
47
+}