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]>
This commit is contained in:
2026-10-25 14:06:59 +01:00
co-authored by Claude Opus 5.5
parent a596722e59
commit bd9744043e
69 changed files with 3777 additions and 18 deletions
+57
View File
@@ -0,0 +1,57 @@
import userAuth from "@/src/functions/backend/auth/user-auth";
import createBotHook from "@/src/functions/backend/db/bot-hooks/create-bot-hook";
import type { BotHookSignatureFormat, BotHookSource } from "@/src/dict/bot-hook-dict";
import { CreateBotHookRequestSchema } from "@/src/schemas/bot-hook-schema";
import type { BotHookWithToken } from "@/src/types";
import AppError from "@/src/utils/app-error";
import parseWithSchema from "@/src/utils/parse-with-schema";
import isReadOnlyUser from "@/src/utils/rbac/is-read-only-user";
import safeErrorMessage from "@/src/utils/safe-error-message";
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
/**
* Gives a bot the session user can chat with a hook: a secret URL whose calls queue its brief as a task. Returns the hook and its token, shown this once.
*/
export const handler: BunextAPIRouteHandler<APIResponseObject<BotHookWithToken>> = async ({ req, body }) => {
try {
if (req.method != "POST") {
throw new AppError(`Method not allowed`);
}
const { user, user_types } = await userAuth({ req });
if (!user?.logged_in_status || !user.id) {
return { success: false, msg: `Unauthorized`, logoutUser: true };
}
if (isReadOnlyUser({ user_types: user_types || [] })) {
throw new AppError(`This user can only read records.`);
}
const { bot_id, workspace_id, signature_format, source, ...rest } = parseWithSchema({
schema: CreateBotHookRequestSchema,
data: body,
});
const created = await createBotHook({
user_id: user.id,
bot_id,
workspace_id: workspace_id || null,
signature_format: signature_format as BotHookSignatureFormat | undefined,
source: source as BotHookSource | undefined,
...rest,
});
return {
success: true,
singleRes: created,
msg: created.token
? `Hook made. Copy its URL now: it is shown only once.`
: created.watch?.ok
? `Hook made. It gets this computer's browser notifications.`
: `Hook made, but the computer's watcher isn't running yet: ${created.watch?.error || "unknown error"}`,
};
} catch (error: unknown) {
return { success: false, msg: safeErrorMessage({ error }) };
}
};
+36
View File
@@ -0,0 +1,36 @@
import userAuth from "@/src/functions/backend/auth/user-auth";
import deleteBotHook from "@/src/functions/backend/db/bot-hooks/delete-bot-hook";
import { BotHookIdRequestSchema } from "@/src/schemas/bot-hook-schema";
import type { BotHookWithNames } from "@/src/types";
import AppError from "@/src/utils/app-error";
import parseWithSchema from "@/src/utils/parse-with-schema";
import isReadOnlyUser from "@/src/utils/rbac/is-read-only-user";
import safeErrorMessage from "@/src/utils/safe-error-message";
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
/**
* Deletes one of the session user's hooks and its recorded calls. A run already queued carries on.
*/
export const handler: BunextAPIRouteHandler<APIResponseObject<BotHookWithNames>> = async ({ req, body }) => {
try {
if (req.method != "POST") {
throw new AppError(`Method not allowed`);
}
const { user, user_types } = await userAuth({ req });
if (!user?.logged_in_status || !user.id) {
return { success: false, msg: `Unauthorized`, logoutUser: true };
}
if (isReadOnlyUser({ user_types: user_types || [] })) {
throw new AppError(`This user can only read records.`);
}
const { hook_id } = parseWithSchema({ schema: BotHookIdRequestSchema, data: body });
return { success: true, singleRes: await deleteBotHook({ user_id: user.id, hook_id }), msg: `Deleted.` };
} catch (error: unknown) {
return { success: false, msg: safeErrorMessage({ error }) };
}
};
+33
View File
@@ -0,0 +1,33 @@
import type { BUN_SQLITE_COBBLE_BOT_HOOK_EVENTS } from "@/db/types/db";
import userAuth from "@/src/functions/backend/auth/user-auth";
import grabBotHookEvents from "@/src/functions/backend/db/bot-hooks/grab-bot-hook-events";
import safeErrorMessage from "@/src/utils/safe-error-message";
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
/**
* The latest calls to one of the session user's hooks (`?hook_id=`), each
* payload cut to a preview.
*/
export const handler: BunextAPIRouteHandler<APIResponseObject<BUN_SQLITE_COBBLE_BOT_HOOK_EVENTS>> = async ({ req }) => {
try {
if (req.method != "GET") {
return { success: false, msg: `Method not allowed` };
}
const { user } = await userAuth({ req });
if (!user?.logged_in_status || !user.id) {
return { success: false, msg: `Unauthorized`, logoutUser: true };
}
const hook_id = Number(new URL(req.url).searchParams.get("hook_id")) || undefined;
if (!hook_id) {
return { success: false, msg: `Pick a hook.` };
}
return { success: true, payload: await grabBotHookEvents({ user_id: user.id, hook_id }) };
} catch (error: unknown) {
return { success: false, msg: safeErrorMessage({ error }) };
}
};
+46
View File
@@ -0,0 +1,46 @@
import userAuth from "@/src/functions/backend/auth/user-auth";
import grabUserConversation from "@/src/functions/backend/db/bot-sessions/grab-user-conversation";
import grabBotHooks from "@/src/functions/backend/db/bot-hooks/grab-bot-hooks";
import type { BotHookWithNames } from "@/src/types";
import safeErrorMessage from "@/src/utils/safe-error-message";
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
/**
* One conversation's hooks of the session user: a bot's own in its chat
* (`?workspace_id=` left out) or the ones that run in that workspace. The
* modal loads them when it opens, so the page's props stay small.
*/
export const handler: BunextAPIRouteHandler<APIResponseObject<BotHookWithNames>> = async ({ req }) => {
try {
if (req.method != "GET") {
return { success: false, msg: `Method not allowed` };
}
const { user } = await userAuth({ req });
if (!user?.logged_in_status || !user.id) {
return { success: false, msg: `Unauthorized`, logoutUser: true };
}
const url = new URL(req.url);
const bot_id = Number(url.searchParams.get("bot_id")) || undefined;
const workspace_id = Number(url.searchParams.get("workspace_id")) || undefined;
if (!bot_id) {
return { success: false, msg: `Pick a bot.` };
}
const conversation = await grabUserConversation({ user_id: user.id, bot_id, workspace_id });
return {
success: true,
payload: await grabBotHooks({
user_id: user.id,
bot_id: conversation.bot.id,
workspace_id: conversation.workspace_id,
}),
};
} catch (error: unknown) {
return { success: false, msg: safeErrorMessage({ error }) };
}
};
+40
View File
@@ -0,0 +1,40 @@
import userAuth from "@/src/functions/backend/auth/user-auth";
import rotateBotHookToken from "@/src/functions/backend/db/bot-hooks/rotate-bot-hook-token";
import { BotHookIdRequestSchema } from "@/src/schemas/bot-hook-schema";
import type { BotHookWithToken } from "@/src/types";
import AppError from "@/src/utils/app-error";
import parseWithSchema from "@/src/utils/parse-with-schema";
import isReadOnlyUser from "@/src/utils/rbac/is-read-only-user";
import safeErrorMessage from "@/src/utils/safe-error-message";
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
/**
* Gives one of the session user's hooks a new URL; the old one stops working at once. Returns the hook and its new token, shown this once.
*/
export const handler: BunextAPIRouteHandler<APIResponseObject<BotHookWithToken>> = async ({ req, body }) => {
try {
if (req.method != "POST") {
throw new AppError(`Method not allowed`);
}
const { user, user_types } = await userAuth({ req });
if (!user?.logged_in_status || !user.id) {
return { success: false, msg: `Unauthorized`, logoutUser: true };
}
if (isReadOnlyUser({ user_types: user_types || [] })) {
throw new AppError(`This user can only read records.`);
}
const { hook_id } = parseWithSchema({ schema: BotHookIdRequestSchema, data: body });
return {
success: true,
singleRes: await rotateBotHookToken({ user_id: user.id, hook_id }),
msg: `New URL made. The old one no longer works.`,
};
} catch (error: unknown) {
return { success: false, msg: safeErrorMessage({ error }) };
}
};
+47
View File
@@ -0,0 +1,47 @@
import userAuth from "@/src/functions/backend/auth/user-auth";
import updateBotHook from "@/src/functions/backend/db/bot-hooks/update-bot-hook";
import type { BotHookSignatureFormat } from "@/src/dict/bot-hook-dict";
import { UpdateBotHookRequestSchema } from "@/src/schemas/bot-hook-schema";
import type { BotHookWithNames } from "@/src/types";
import AppError from "@/src/utils/app-error";
import parseWithSchema from "@/src/utils/parse-with-schema";
import isReadOnlyUser from "@/src/utils/rbac/is-read-only-user";
import safeErrorMessage from "@/src/utils/safe-error-message";
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
/**
* Changes one of the session user's hooks: its name, brief, whether it's on, or how its calls are signed. Returns the hook.
*/
export const handler: BunextAPIRouteHandler<APIResponseObject<BotHookWithNames>> = async ({ req, body }) => {
try {
if (req.method != "POST") {
throw new AppError(`Method not allowed`);
}
const { user, user_types } = await userAuth({ req });
if (!user?.logged_in_status || !user.id) {
return { success: false, msg: `Unauthorized`, logoutUser: true };
}
if (isReadOnlyUser({ user_types: user_types || [] })) {
throw new AppError(`This user can only read records.`);
}
const { hook_id, signature_format, ...data } = parseWithSchema({ schema: UpdateBotHookRequestSchema, data: body });
const hook = await updateBotHook({
user_id: user.id,
hook_id,
data: { ...data, signature_format: signature_format as BotHookSignatureFormat | undefined },
});
return {
success: true,
singleRes: hook,
msg: data.enabled === undefined ? `Saved.` : data.enabled ? `${hook.title} is back on.` : `${hook.title} is paused.`,
};
} catch (error: unknown) {
return { success: false, msg: safeErrorMessage({ error }) };
}
};
+106
View File
@@ -0,0 +1,106 @@
import type { BunextAPIRouteHandler, BunextServerRouteConfig } from "@moduletrace/bunext/types";
import { AppData } from "@/src/data/app-data";
import { BotHookIdempotencyHeaders, type BotHookSignatureFormat } from "@/src/dict/bot-hook-dict";
import findBotHookByToken from "@/src/functions/backend/db/bot-hooks/find-bot-hook-by-token";
import fireBotHook from "@/src/functions/backend/db/bot-hooks/fire-bot-hook";
import insertBotHookEvent from "@/src/functions/backend/db/bot-hooks/insert-bot-hook-event";
import { grabRequestIP } from "@/src/functions/backend/logger";
import { decrypt } from "@/src/utils/crypt";
import rateLimit from "@/src/utils/rate-limit";
import safeErrorMessage from "@/src/utils/safe-error-message";
import verifyHookSignature from "@/src/utils/verify-hook-signature";
/**
* Bodies past this are refused (413) before the handler runs.
*/
export const config: BunextServerRouteConfig = {
max_request_body_mb: AppData.BotHookMaxPayloadBytes / (1024 * 1024),
};
/**
* The public end of a bot's hook: `POST /api/hooks/<token>` queues the
* hook's brief, with the raw body as data, as a task for its bot
* (`fireBotHook`). There's no session: the token is the key, checked
* against its hash in constant time, and, when the hook has a signing
* secret, the HMAC-SHA256 of the body too. Calls are rate limited per
* address before any lookup and per hook after. Every unknown token gets
* the same 404. Answers 202 once the run is queued (or the call joined one
* still waiting), 200 for a delivery already taken or a notification the
* hook's filter leaves out. Computers' notification watchers call it too.
*/
export const handler: BunextAPIRouteHandler = async ({ req, query }) => {
try {
if (req.method != "POST") {
return reply({ status: 405, msg: `Use POST.` });
}
const ip = grabRequestIP(req) || "unknown";
const minute = 60 * 1000;
if (!rateLimit({ key: `bot-hook-ip:${ip}`, limit: AppData.BotHookIpRateLimit, window_ms: minute }).allowed) {
return reply({ status: 429, msg: `Too many calls. Try again in a minute.` });
}
const token = String(query?.token || "");
const hook = token ? await findBotHookByToken({ token }) : null;
if (!hook?.id) {
return reply({ status: 404, msg: `Not found.` });
}
if (!rateLimit({ key: `bot-hook:${hook.id}`, limit: AppData.BotHookRateLimit, window_ms: minute }).allowed) {
return reply({ status: 429, msg: `Too many calls to this hook. Try again in a minute.` });
}
const payload = await req.text();
const content_type = req.headers.get("content-type");
if (hook.signing_secret) {
const secret = await decrypt(hook.signing_secret).catch(() => "");
const signed = verifyHookSignature({
body: payload,
secret,
signature: hook.signature_header ? req.headers.get(hook.signature_header) : null,
format: (hook.signature_format || "sha256=hex") as BotHookSignatureFormat,
});
if (!signed) {
await insertBotHookEvent({
hook_id: hook.id,
payload: payload.slice(0, 2000),
content_type,
source_ip: ip,
status: "rejected",
error: `Bad or missing signature`,
});
return reply({ status: 401, msg: `Bad or missing signature.` });
}
}
const idempotency_key =
BotHookIdempotencyHeaders.map((name) => req.headers.get(name)).find(Boolean) || null;
const result = await fireBotHook({ hook, payload, content_type, source_ip: ip, idempotency_key });
if (result.status == "rejected") {
return reply({ status: 409, msg: result.error || `This hook can't run now.` });
}
return reply({
status: result.status == "duplicate" || result.status == "ignored" ? 200 : 202,
ok: true,
msg: result.status == "duplicate" ? `Already taken.` : result.status == "ignored" ? `Ignored.` : `Queued.`,
event_id: result.event_id,
});
} catch (error: unknown) {
return reply({ status: 500, msg: safeErrorMessage({ error }) });
}
};
function reply({ status, ok = false, msg, event_id }: { status: number; ok?: boolean; msg: string; event_id?: number }) {
return Response.json(
{ ok, msg, event_id },
{ status, headers: { "Cache-Control": "no-store", ...(status == 429 ? { "Retry-After": "60" } : {}) } },
);
}