File size: 3,932 Bytes
765fe0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
'use strict';
// Web Push notifications ("Claude finished", "permission needed") for phones
// where the page is in the background or closed. VAPID keys are generated
// once and kept in ~/.cc-web/push.json with the browsers' subscriptions.

const fs = require('fs');
const path = require('path');

const MAX_SUBSCRIPTIONS = 20;
const THROTTLE_MS = 15000;

let webpush = null;
try {
  webpush = require('web-push');
} catch {
  webpush = null;
}

class PushManager {
  constructor({ home, subject }) {
    this.file = path.join(home, '.cc-web', 'push.json');
    this.subject = subject || 'mailto:agentweb@example.invalid';
    this.last = new Map();
    this.data = this.load();
  }

  get available() {
    return !!webpush;
  }

  load() {
    let data = {};
    try {
      data = JSON.parse(fs.readFileSync(this.file, 'utf8')) || {};
    } catch {
      data = {};
    }
    if (!Array.isArray(data.subs)) data.subs = [];
    if (webpush && (!data.vapid || !data.vapid.publicKey || !data.vapid.privateKey)) {
      data.vapid = webpush.generateVAPIDKeys();
      this.save(data);
    }
    return data;
  }

  save(data = this.data) {
    try {
      fs.mkdirSync(path.dirname(this.file), { recursive: true });
      fs.writeFileSync(this.file, JSON.stringify(data, null, 1), { mode: 0o600 });
    } catch (err) {
      console.error('[push] kaydedilemedi:', err.message);
    }
  }

  publicKey() {
    return this.data.vapid ? this.data.vapid.publicKey : null;
  }

  subscribe(sub, userAgent) {
    if (!webpush) throw Object.assign(new Error('Bildirimler bu kurulumda yok.'), { status: 501 });
    if (!sub || typeof sub.endpoint !== 'string' || !/^https:\/\//.test(sub.endpoint) || !sub.keys || !sub.keys.p256dh || !sub.keys.auth) {
      throw Object.assign(new Error('Geçersiz abonelik.'), { status: 400 });
    }
    this.data.subs = this.data.subs.filter((s) => s.endpoint !== sub.endpoint);
    this.data.subs.push({ endpoint: sub.endpoint, keys: { p256dh: String(sub.keys.p256dh), auth: String(sub.keys.auth) }, ua: String(userAgent || '').slice(0, 160), addedAt: Date.now() });
    if (this.data.subs.length > MAX_SUBSCRIPTIONS) this.data.subs.splice(0, this.data.subs.length - MAX_SUBSCRIPTIONS);
    this.save();
    return { ok: true, count: this.data.subs.length };
  }

  unsubscribe(endpoint) {
    const before = this.data.subs.length;
    this.data.subs = this.data.subs.filter((s) => s.endpoint !== endpoint);
    if (this.data.subs.length !== before) this.save();
    return { ok: true };
  }

  has(endpoint) {
    return this.data.subs.some((s) => s.endpoint === endpoint);
  }

  async send({ session, kind, body, title }) {
    if (!webpush || !this.data.subs.length || !this.data.vapid) return;
    const key = `${session}:${kind}`;
    const now = Date.now();
    if (now - (this.last.get(key) || 0) < THROTTLE_MS) return;
    this.last.set(key, now);
    const payload = JSON.stringify({
      title: title || `Agent Web · ${session}`,
      body: String(body || '').slice(0, 300),
      session,
      kind,
      url: `/?s=${encodeURIComponent(session)}`,
    });
    const options = {
      TTL: 3600,
      urgency: kind === 'done' ? 'normal' : 'high',
      vapidDetails: { subject: this.subject, publicKey: this.data.vapid.publicKey, privateKey: this.data.vapid.privateKey },
    };
    let changed = false;
    await Promise.all(
      this.data.subs.map(async (sub) => {
        try {
          await webpush.sendNotification({ endpoint: sub.endpoint, keys: sub.keys }, payload, options);
        } catch (err) {
          // Gone (unsubscribed, uninstalled): forget it.
          if (err && (err.statusCode === 404 || err.statusCode === 410)) {
            sub.gone = true;
            changed = true;
          }
        }
      })
    );
    if (changed) {
      this.data.subs = this.data.subs.filter((s) => !s.gone);
      this.save();
    }
  }
}

module.exports = { PushManager };