Files
cobble/src/functions/backend/db/bot-hooks/insert-bot-hook-event.ts
T
tbenandClaude Opus 5.5 bd9744043e Let outside services and computers' browser notifications give bots work
A bot hook (bot_hooks) is a secret URL, POST /api/hooks/<token>, whose
calls queue the hook's brief plus the raw body as a task, per user and
bot like a routine. Only the token's hash is kept (shown once, rotatable);
an optional HMAC-SHA256 signing secret is stored encrypted. Calls are
rate limited per address and per hook, recorded in bot_hook_events
(pruned daily), deduplicated by delivery id, and a call while the last
run still waits joins its brief instead of queueing another. The payload
is fenced data and HookRunNote tells the bot never to take instructions
from it; failed runs retry like routines.

A hook can instead watch a computer's browser notifications: the app
installs a small watcher that owns org.freedesktop.Notifications on the
sandbox's session bus, so Chrome hands it every notification (it only
looks for that service at start-up, so Chrome is restarted once, never
mid-task), and it posts each one to its hooks, optionally filtered.
Computers reach the app at COMPUTER_APP_URL or the app container's name.

Users make hooks in the conversation's Hooks modal and manage them all
on /admin/routines; bots never create or change hooks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 14:06:59 +01:00

55 lines
1.5 KiB
TypeScript

import BunSQLite from "@moduletrace/bun-sqlite";
import type { BUN_SQLITE_COBBLE_BOT_HOOK_EVENTS, BunSQLiteTables } from "@/db/types/db";
import { AppData } from "@/src/data/app-data";
import type { BotHookEventStatus } from "@/src/dict/bot-hook-dict";
type Params = {
hook_id: number;
payload: string;
content_type?: string | null;
source_ip?: string | null;
idempotency_key?: string | null;
status: BotHookEventStatus;
/**
* The run it queued or joined.
*/
job_id?: number;
error?: string;
now?: number;
};
/**
* Records one call to a hook and what became of it, for its recent calls.
* Returns the event id.
*/
export default async function insertBotHookEvent({
hook_id,
payload,
content_type,
source_ip,
idempotency_key,
status,
job_id,
error,
now = Date.now(),
}: Params) {
const res = await BunSQLite.insert<BUN_SQLITE_COBBLE_BOT_HOOK_EVENTS, (typeof BunSQLiteTables)[number]>({
table: "bot_hook_events",
data: [
{
hook_id,
job_id,
payload: payload.slice(0, AppData.BotHookMaxPayloadBytes),
content_type: content_type?.slice(0, 200) || undefined,
source_ip: source_ip || undefined,
idempotency_key: idempotency_key || undefined,
status,
error,
created_at: now,
},
],
});
return Number(res.singleRes?.id || res.postInsertReturn?.insertId) || undefined;
}