Files
AgentHub/server/lib/push.js
T
nntrivi2001 e972267a42 fix(plugins): make the 10 focused plugins installable, finish the AgentHub rename
The ten `agenthub-*` plugins were listed by the marketplace but could never be
installed — two schema mistakes present since the entries were first authored
(57dc915), both invisible until you actually run `claude plugin install`:

- marketplace entries used `"path": "plugins/<name>"`; the CLI only accepts
  `"source"`, so every one failed with
  `This plugin's marketplace entry is invalid: source: Invalid input`
- each `plugin.json` carried npm's `"repository": { "type", "url" }` object;
  the schema wants a plain string, so the next attempt failed with
  `Validation errors: repository: Invalid input`

Verified by installing all 11 entries into a throwaway CLAUDE_CONFIG_DIR:
1/11 before, 11/11 after. `plugins-marketplace.test.js` was asserting the
broken shape, which is why CI stayed green — it now asserts `source` and
rejects `path`.

Marketplace renamed `claude-code-agent-monitor-plugins` -> `agenthub`, so the
install line is `agenthub@agenthub`. ARCHITECTURE.md documented a marketplace
name (`smartgift-claude-code-monitor`) that never existed in any revision.

The documented `/plugin marketplace add Smartgift-AI/Claude-Code-Monitor` also
never worked: the `owner/repo` shorthand resolves to github.com only, and this
repo is self-hosted on Gitea. Confirmed the CLI rejects `host/owner/repo` and
ignores GH_HOST / GITHUB_HOST / CLAUDE_CODE_MARKETPLACE_URL, so the full
https:// clone URL is the only supported form. Same GitHub-habit class fixed
elsewhere: raw.githubusercontent.com icon URLs (404, and the repo ships
favicon.svg not favicon.ico — the client had the same dead /favicon.ico),
a smartgift.github.io docs link (404), and Gitea `/blob/<ref>/` paths that
must be `/src/branch/<ref>/`.

Repository renamed to Smartgift-AI/AgentHub throughout. Gitea 301-redirects
the old name, so these were stale rather than broken; `docs/superpowers/`
keeps the old name because those are dated decision records.

Adds `repo-links.test.js` to guard both classes (it runs under the existing
pre-commit gate) plus an openapi.yaml drift check — the committed spec had
silently fallen a minor version behind package.json. `generate-openapi-yaml.js`
now exports `render()` so the test compares against one definition of the dump
options instead of a second copy.
2026-09-10 11:03:14 +07:00

136 lines
4.8 KiB
JavaScript

/**
* @file Handles web push notifications using the `web-push` library, including generating/loading VAPID keys, sending notifications to all subscribed clients, and cleaning up invalid subscriptions. It provides a function to retrieve the public VAPID key for client registration and a function to broadcast notifications to all subscribers stored in the database.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
const webpush = require("web-push");
const path = require("path");
const fs = require("fs");
const { getDataDir } = require("./claude-home");
// Lives in the shared data dir alongside the SQLite DB (see getDataDir), so the
// web app and the native apps reuse one set of VAPID keys.
const KEYS_PATH = path.join(getDataDir(), "vapid-keys.json");
function loadOrCreateVapidKeys() {
if (fs.existsSync(KEYS_PATH)) {
return JSON.parse(fs.readFileSync(KEYS_PATH, "utf8"));
}
const keys = webpush.generateVAPIDKeys();
fs.mkdirSync(path.dirname(KEYS_PATH), { recursive: true });
fs.writeFileSync(KEYS_PATH, JSON.stringify(keys, null, 2));
return keys;
}
const vapidKeys = loadOrCreateVapidKeys();
webpush.setVapidDetails(
"https://git.smartgift.io.vn/Smartgift-AI/AgentHub",
vapidKeys.publicKey,
vapidKeys.privateKey
);
function getPublicKey() {
return vapidKeys.publicKey;
}
/**
* Fire a native OS notification when this process is the Electron main process
* (i.e. the desktop app embeds the server in-process). Web Push is unreliable
* inside Electron — Chromium-in-Electron ships without Firebase Cloud
* Messaging credentials, so `pushManager.subscribe()` in the renderer either
* fails or returns an endpoint that nothing can ever deliver to, leaving the
* `push_subscriptions` table empty. Calling Electron's main-process
* Notification API directly side-steps the push service entirely.
*
* Returns true when a notification was actually shown.
*
* @param {string} title
* @param {string} body
* @returns {boolean}
*/
function showNativeNotificationIfElectron(title, body) {
if (!process.versions || !process.versions.electron) return false;
try {
// `require("electron")` only resolves inside the Electron runtime; in a
// plain `node server/index.js` host it throws and we fall through.
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { Notification: ElectronNotification } = require("electron");
if (!ElectronNotification) return false;
if (
typeof ElectronNotification.isSupported === "function" &&
!ElectronNotification.isSupported()
) {
return false;
}
new ElectronNotification({ title, body, silent: false }).show();
return true;
} catch {
return false;
}
}
/**
* Dispatch a notification to every reachable surface:
* - A native Electron notification when hosted inside the desktop app.
* - A Web Push delivery to every subscribed browser endpoint.
*
* Both legs run unconditionally so whichever surface the user is on receives
* the alert. Under `npm start` the native leg is a no-op; under the desktop
* app the Web Push leg is typically a no-op (no FCM credentials in Electron,
* so `push_subscriptions` is empty).
*
* Returns `{ native, pushed, failed }` so the caller can surface what actually
* happened in its API response — silent failures stop looking like success.
*/
async function sendPushToAll(db, title, body) {
const native = showNativeNotificationIfElectron(title, body);
const subscriptions = db.prepare("SELECT * FROM push_subscriptions").all();
if (subscriptions.length === 0) {
return { native, pushed: 0, failed: 0 };
}
const payload = JSON.stringify({
title,
body,
// Same-origin path, resolved by the service worker against its own scope
// (client/public/sw.js spreads these straight into showNotification). An
// absolute forge/raw URL would 404 — this repo is self-hosted on Gitea and
// ships favicon.svg, not favicon.ico.
icon: "/favicon.svg",
badge: "/favicon.svg",
silent: false,
sound: "default",
});
const results = await Promise.allSettled(
subscriptions.map((sub) =>
webpush.sendNotification(
{ endpoint: sub.endpoint, keys: { p256dh: sub.p256dh, auth: sub.auth } },
payload
)
)
);
// Remove subscriptions that are gone (HTTP 410); count what landed.
let pushed = 0;
let failed = 0;
for (let index = 0; index < results.length; index++) {
const result = results[index];
if (result.status === "fulfilled") {
pushed++;
} else {
failed++;
if (result.reason?.statusCode === 410) {
db.prepare("DELETE FROM push_subscriptions WHERE endpoint = ?").run(
subscriptions[index].endpoint
);
}
}
}
return { native, pushed, failed };
}
module.exports = { getPublicKey, sendPushToAll, showNativeNotificationIfElectron };