@alexsun-top/opencode-chat-room 0.4.0 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -0
- package/README.md +38 -5
- package/README.zh-CN.md +34 -4
- package/docs/administrator-rooms.md +51 -0
- package/package.json +11 -1
- package/plugin.ts +28 -17
- package/server/admin-auth.ts +16 -0
- package/server/admin-plan-routes.ts +79 -0
- package/server/admin-routes.ts +154 -0
- package/server/admin-scheduler.ts +42 -0
- package/server/admin-state.ts +61 -0
- package/server/admin-task-routes.ts +182 -0
- package/server/announcement-routes.ts +34 -0
- package/server/assets/MERMAID-LICENSE +21 -0
- package/server/assets/NOTICE.txt +2 -1
- package/server/assets/base.css +60 -43
- package/server/assets/chat/admin.js +196 -0
- package/server/assets/chat/announcements.js +119 -0
- package/server/assets/chat/attachments.js +240 -0
- package/server/assets/chat/events.js +206 -10
- package/server/assets/chat/index.js +6 -0
- package/server/assets/chat/markdown.js +208 -16
- package/server/assets/chat/members.js +5 -2
- package/server/assets/chat/messages.js +85 -23
- package/server/assets/chat/receipts.js +22 -17
- package/server/assets/chat/rooms.js +32 -10
- package/server/assets/chat/state.js +88 -22
- package/server/assets/conversation.css +100 -40
- package/server/assets/mermaid-11.12.2.min.js +2811 -0
- package/server/assets/responsive.css +108 -49
- package/server/chat-server.ts +10 -11
- package/server/chat.html +85 -32
- package/server/member-routes.ts +3 -0
- package/server/newrooms.ts +29 -10
- package/server/resource-routes.ts +68 -0
- package/server/wake.ts +7 -14
- package/skills/chatroom/SKILL.md +104 -0
- package/src/admin-client.ts +130 -0
- package/src/admin-credentials.ts +58 -0
- package/src/agent-receipts.ts +4 -4
- package/src/announcement-tool.ts +25 -0
- package/src/announcements.ts +16 -0
- package/src/center-client.ts +27 -1
- package/src/center-inbox.ts +11 -9
- package/src/chatroom-skill.ts +15 -0
- package/src/plugin-notifications.ts +7 -9
- package/src/resource-upload.ts +50 -0
- package/src/resources.ts +104 -0
- package/src/sqlite-state.ts +81 -12
- package/src/store.ts +1 -10
- package/src/supervision-inbox.ts +62 -0
- package/src/v1-plugin.ts +19 -4
- package/src/v2-plugin.ts +45 -8
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { databasePath } from "../src/store";
|
|
2
|
+
import { readHistoryPage } from "../src/sqlite-state";
|
|
3
|
+
import { adminEnabled, hasAdminCapability, isOperator } from "./admin-auth";
|
|
4
|
+
import { adminPlanRoutes } from "./admin-plan-routes";
|
|
5
|
+
import { adminTaskRoutes } from "./admin-task-routes";
|
|
6
|
+
import { binding, digest, ensureAdminSchema, exec, isAgentMember, many, matchesHash, newSecret, one, publicRoom, tx, validCurrent, enroll } from "./admin-state";
|
|
7
|
+
import type { Binding } from "./admin-state";
|
|
8
|
+
import { startAdminScheduler } from "./admin-scheduler";
|
|
9
|
+
|
|
10
|
+
const json = (body: unknown, status = 200) => Response.json(body, { status, headers: { "Cache-Control": "no-store" } });
|
|
11
|
+
const object = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && !Array.isArray(value);
|
|
12
|
+
startAdminScheduler();
|
|
13
|
+
|
|
14
|
+
export async function adminRoutes(request: Request, url: URL): Promise<Response | undefined> {
|
|
15
|
+
if (!url.pathname.startsWith("/admin/") && !url.pathname.startsWith("/supervision/")) return undefined;
|
|
16
|
+
if (!adminEnabled) return json({ error: "admin API is disabled" }, 503);
|
|
17
|
+
try {
|
|
18
|
+
await ensureAdminSchema();
|
|
19
|
+
const task = await adminTaskRoutes(request, url);
|
|
20
|
+
if (task) return task;
|
|
21
|
+
const plan = await adminPlanRoutes(request, url);
|
|
22
|
+
if (plan) return plan;
|
|
23
|
+
return await rootRoutes(request, url);
|
|
24
|
+
} catch (error) {
|
|
25
|
+
if (error instanceof SyntaxError || error instanceof URIError) return json({ error: "invalid request" }, 400);
|
|
26
|
+
return json({ error: "admin request failed" }, 500);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function rootRoutes(request: Request, url: URL): Promise<Response> {
|
|
31
|
+
const path = url.pathname;
|
|
32
|
+
if (request.method === "GET" && path === "/admin/rooms") return listRooms(request);
|
|
33
|
+
if (request.method === "POST" && path === "/admin/rooms") return createBinding(request);
|
|
34
|
+
const claim = path.match(/^\/admin\/rooms\/([^/]+)\/claim$/);
|
|
35
|
+
if (claim && request.method === "POST") return claimBinding(request, decodeURIComponent(claim[1]!));
|
|
36
|
+
const room = path.match(/^\/admin\/rooms\/([^/]+)(?:\/(overview|history))?$/);
|
|
37
|
+
if (!room) return json({ error: "not found" }, 404);
|
|
38
|
+
const roomID = decodeURIComponent(room[1]!);
|
|
39
|
+
if (request.method === "PUT" && !room[2]) return rotateBinding(request, roomID);
|
|
40
|
+
if (request.method === "DELETE" && !room[2]) return revokeBinding(request, roomID);
|
|
41
|
+
if (request.method === "GET" && room[2] === "overview") return overview(request, roomID);
|
|
42
|
+
if (request.method === "GET" && room[2] === "history") return history(request, url, roomID);
|
|
43
|
+
return json({ error: "method not allowed" }, 405);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function listRooms(request: Request): Promise<Response> {
|
|
47
|
+
if (!isOperator(request)) return json({ error: "operator token required" }, 401);
|
|
48
|
+
return json({ rooms: await tx(db => many<Binding>(db, "SELECT * FROM admin_rooms ORDER BY created_at LIMIT 200").map(publicRoom)) });
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function createBinding(request: Request): Promise<Response> {
|
|
52
|
+
if (!isOperator(request)) return json({ error: "operator token required" }, 401);
|
|
53
|
+
const body: unknown = await request.json();
|
|
54
|
+
if (!object(body) || !bounded(body.roomId, 128) || !bounded(body.targetRoomId, 128) ||
|
|
55
|
+
!bounded(body.sessionID, 128) || typeof body.receiverOwnerID !== "string" || body.receiverOwnerID.length > 128 ||
|
|
56
|
+
!bounded(body.membershipID, 128)) return json({ error: "invalid admin binding" }, 400);
|
|
57
|
+
const { roomId, targetRoomId, sessionID, receiverOwnerID, membershipID } = body as {
|
|
58
|
+
roomId: string; targetRoomId: string; sessionID: string; receiverOwnerID: string; membershipID: string;
|
|
59
|
+
};
|
|
60
|
+
const result = await tx(db => {
|
|
61
|
+
const admin = one<{ kind: string }>(db, "SELECT kind FROM rooms WHERE id=?", roomId);
|
|
62
|
+
if (!admin) return { status: 404 as const, error: "admin room not found" };
|
|
63
|
+
if (admin.kind !== "group") return { status: 400 as const, error: "admin room must be a group room" };
|
|
64
|
+
if (one(db, "SELECT 1 FROM admin_rooms WHERE room_id=?", roomId)) return { status: 409 as const, error: "admin room already designated; use PUT to rotate" };
|
|
65
|
+
if (!one(db, "SELECT 1 FROM rooms WHERE id=?", targetRoomId)) return { status: 404 as const, error: "target room not found" };
|
|
66
|
+
if (!isAgentMember(db, targetRoomId, sessionID, receiverOwnerID, membershipID)) return { status: 409 as const, error: "target agent binding is not active" };
|
|
67
|
+
const issued = enroll(db, roomId, targetRoomId, sessionID, receiverOwnerID, membershipID, 1);
|
|
68
|
+
const adminBinding = binding(db, roomId);
|
|
69
|
+
return issued && adminBinding ? { status: 201 as const, issued, adminRoom: publicRoom(adminBinding) } : { status: 409 as const, error: "admin room cannot be designated" };
|
|
70
|
+
});
|
|
71
|
+
return "issued" in result ? json({ adminRoom: result.adminRoom, ...result.issued }, result.status) : json({ error: result.error }, result.status);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function bounded(value: unknown, max: number): value is string {
|
|
75
|
+
return typeof value === "string" && value.trim().length > 0 && value.length <= max;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async function claimBinding(request: Request, roomID: string): Promise<Response> {
|
|
79
|
+
const body: unknown = await request.json();
|
|
80
|
+
if (!object(body) || !bounded(body.sessionID, 128) || typeof body.receiverOwnerID !== "string" ||
|
|
81
|
+
body.receiverOwnerID.length > 128 || !bounded(body.enrollmentKey, 256)) return json({ error: "invalid claim" }, 400);
|
|
82
|
+
const { sessionID, receiverOwnerID, enrollmentKey } = body as { sessionID: string; receiverOwnerID: string; enrollmentKey: string };
|
|
83
|
+
const result = await tx(db => {
|
|
84
|
+
const b = binding(db, roomID);
|
|
85
|
+
if (!b || b.session_id !== sessionID || b.receiver_owner_id !== receiverOwnerID ||
|
|
86
|
+
b.enrollment_expires <= Date.now() || !matchesHash(enrollmentKey, b.enrollment_hash) ||
|
|
87
|
+
!isAgentMember(db, b.target_room_id, b.session_id, b.receiver_owner_id, b.membership_id)) return null;
|
|
88
|
+
const capability = newSecret();
|
|
89
|
+
const saved = exec(db, "UPDATE admin_rooms SET capability_hash=?,enrollment_hash='',enrollment_expires=0 WHERE room_id=? AND generation=? AND enrollment_hash=? AND enrollment_expires>?",
|
|
90
|
+
digest(capability), roomID, b.generation, b.enrollment_hash, Date.now());
|
|
91
|
+
return saved.changes === 1 ? { capability, adminRoom: publicRoom({ ...b, capability_hash: digest(capability) }) } : null;
|
|
92
|
+
});
|
|
93
|
+
return result ? json(result) : json({ error: "claim rejected" }, 409);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async function rotateBinding(request: Request, roomID: string): Promise<Response> {
|
|
97
|
+
if (!isOperator(request)) return json({ error: "operator token required" }, 401);
|
|
98
|
+
const body: unknown = await request.json();
|
|
99
|
+
if (!object(body) || !bounded(body.targetRoomId, 128) || !bounded(body.sessionID, 128) ||
|
|
100
|
+
typeof body.receiverOwnerID !== "string" || body.receiverOwnerID.length > 128 || !bounded(body.membershipID, 128)) return json({ error: "invalid binding" }, 400);
|
|
101
|
+
const { targetRoomId, sessionID, receiverOwnerID, membershipID } = body as {
|
|
102
|
+
targetRoomId: string; sessionID: string; receiverOwnerID: string; membershipID: string;
|
|
103
|
+
};
|
|
104
|
+
const result = await tx(db => {
|
|
105
|
+
const old = binding(db, roomID);
|
|
106
|
+
if (!old) return null;
|
|
107
|
+
if (!isAgentMember(db, targetRoomId, sessionID, receiverOwnerID, membershipID)) return null;
|
|
108
|
+
const issued = enroll(db, roomID, targetRoomId, sessionID, receiverOwnerID, membershipID, old.generation + 1);
|
|
109
|
+
const current = binding(db, roomID);
|
|
110
|
+
return issued && current ? { issued, adminRoom: publicRoom(current) } : null;
|
|
111
|
+
});
|
|
112
|
+
return result ? json({ adminRoom: result.adminRoom, ...result.issued }) : json({ error: "admin room or active agent binding not found" }, 409);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async function revokeBinding(request: Request, roomID: string): Promise<Response> {
|
|
116
|
+
if (!isOperator(request)) return json({ error: "operator token required" }, 401);
|
|
117
|
+
const deleted = await tx(db => exec(db, "DELETE FROM admin_rooms WHERE room_id=?", roomID).changes);
|
|
118
|
+
return deleted ? json({ ok: true }) : json({ error: "admin room not found" }, 404);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
async function overview(request: Request, roomID: string): Promise<Response> {
|
|
122
|
+
const result = await tx(db => {
|
|
123
|
+
const b = binding(db, roomID);
|
|
124
|
+
if (!b) return { status: 404 as const };
|
|
125
|
+
if (!authorized(request, b)) return { status: 401 as const };
|
|
126
|
+
if (!isOperator(request) && !validCurrent(db, b)) return { status: 409 as const };
|
|
127
|
+
const rooms = many<{ id: string; name: string; createdAt: number }>(db, "SELECT id,name,created_at AS createdAt FROM rooms ORDER BY created_at DESC LIMIT 200")
|
|
128
|
+
.map(room => ({ ...room, members: many(db, "SELECT g.session_id AS sessionID,g.name,g.protocol,g.receiver_owner_id AS receiverOwnerID,g.work_state AS workState,g.last_seen_at AS lastSeenAt FROM registry g WHERE g.room_id=? ORDER BY g.name", room.id) }));
|
|
129
|
+
const tasks = many(db, "SELECT id,admin_room_id AS adminRoomId,admin_generation AS generation,target_room_id AS targetRoomId,target_session_id AS targetSessionID,text,status,progress,created_at AS createdAt,updated_at AS updatedAt FROM admin_tasks WHERE admin_room_id=? ORDER BY created_at DESC LIMIT 200", roomID);
|
|
130
|
+
const plans = many(db, "SELECT id,admin_room_id AS adminRoomId,name,interval_seconds AS intervalSeconds,text,paused,next_run_at AS nextRunAt,created_at AS createdAt FROM admin_plans WHERE admin_room_id=? ORDER BY created_at DESC LIMIT 200", roomID);
|
|
131
|
+
return { rooms, tasks, plans };
|
|
132
|
+
});
|
|
133
|
+
return "status" in result ? json({ error: result.status === 404 ? "admin room not found" : result.status === 401 ? "unauthorized" : "binding is no longer active" }, result.status) : json(result);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async function history(request: Request, url: URL, roomID: string): Promise<Response> {
|
|
137
|
+
const targetRoomID = url.searchParams.get("targetRoomId") ?? "";
|
|
138
|
+
const rawLimit = url.searchParams.get("limit");
|
|
139
|
+
const limit = rawLimit === null ? 20 : Number(rawLimit);
|
|
140
|
+
if (!bounded(targetRoomID, 128) || !Number.isSafeInteger(limit) || limit < 1 || limit > 50) return json({ error: "invalid history request" }, 400);
|
|
141
|
+
const allowed = await tx(db => {
|
|
142
|
+
const b = binding(db, roomID);
|
|
143
|
+
if (!b) return 404;
|
|
144
|
+
if (!authorized(request, b)) return 401;
|
|
145
|
+
if (!isOperator(request) && !validCurrent(db, b)) return 409;
|
|
146
|
+
return one(db, "SELECT 1 FROM rooms WHERE id=?", targetRoomID) ? 200 : 404;
|
|
147
|
+
});
|
|
148
|
+
if (allowed !== 200) return json({ error: allowed === 401 ? "unauthorized" : allowed === 404 ? "room not found" : "binding is no longer active" }, allowed);
|
|
149
|
+
return json(await readHistoryPage(databasePath(), targetRoomID, undefined, limit));
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function authorized(request: Request, b: import("./admin-state").Binding): boolean {
|
|
153
|
+
return isOperator(request) || hasAdminCapability(request, b);
|
|
154
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { binding, exec, many, tx, validCurrent } from "./admin-state";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
|
|
4
|
+
type PlanRow = { id: string; admin_room_id: string; interval_seconds: number; next_run_at: number; text: string };
|
|
5
|
+
type OpenTask = { text: string; status: string; progress: string };
|
|
6
|
+
type Reminder = { id: string; acknowledged: number };
|
|
7
|
+
|
|
8
|
+
export async function tickAdminScheduler(now = Date.now()): Promise<void> {
|
|
9
|
+
await tx((db) => {
|
|
10
|
+
const due = many<PlanRow>(db, "SELECT * FROM admin_plans WHERE paused=0 AND next_run_at<=? ORDER BY next_run_at LIMIT 100", now);
|
|
11
|
+
for (const plan of due) {
|
|
12
|
+
const b = binding(db, plan.admin_room_id);
|
|
13
|
+
if (!b || !validCurrent(db, b)) {
|
|
14
|
+
exec(db, "UPDATE admin_plans SET next_run_at=? WHERE id=?", now + plan.interval_seconds * 1000, plan.id);
|
|
15
|
+
continue;
|
|
16
|
+
}
|
|
17
|
+
const tasks = many<OpenTask>(db, "SELECT text,status,progress FROM admin_tasks WHERE admin_room_id=? AND status IN ('pending','working','blocked') ORDER BY created_at DESC LIMIT 20", b.room_id);
|
|
18
|
+
const summary = tasks.length ? `\nOpen tasks:\n${tasks.map(t => `- ${t.status}: ${t.text}${t.progress ? ` (${t.progress})` : ""}`).join("\n")}` : "\nNo open tasks.";
|
|
19
|
+
const text = `${plan.text}${summary}`.slice(0, 5000);
|
|
20
|
+
const taskID = `plan:${plan.id}`;
|
|
21
|
+
const existing = db.query("SELECT id,acknowledged FROM admin_deliveries WHERE admin_room_id=? AND kind='supervision' AND task_id=?").get(b.room_id, taskID) as Reminder | null;
|
|
22
|
+
if (existing && !existing.acknowledged) {
|
|
23
|
+
exec(db, "UPDATE admin_deliveries SET text=?,created_at=?,generation=?,recipient_room_id=?,session_id=?,owner_id=?,membership_id=? WHERE id=?", text, now, b.generation, b.target_room_id, b.session_id, b.receiver_owner_id, b.membership_id, existing.id);
|
|
24
|
+
} else if (existing) {
|
|
25
|
+
const id = randomUUID();
|
|
26
|
+
exec(db, "UPDATE admin_deliveries SET id=?,admission_id=?,text=?,created_at=?,generation=?,recipient_room_id=?,session_id=?,owner_id=?,membership_id=?,acknowledged=0 WHERE id=?", id, `msg_${id}`, text, now, b.generation, b.target_room_id, b.session_id, b.receiver_owner_id, b.membership_id, existing.id);
|
|
27
|
+
} else {
|
|
28
|
+
const id = randomUUID();
|
|
29
|
+
exec(db, "INSERT INTO admin_deliveries(id,admin_room_id,generation,recipient_room_id,session_id,owner_id,membership_id,kind,text,task_id,admission_id,created_at) VALUES(?,?,?,?,?,?,?,'supervision',?,?,?,?)", id,b.room_id,b.generation,b.target_room_id,b.session_id,b.receiver_owner_id,b.membership_id,text,taskID,`msg_${id}`,now);
|
|
30
|
+
}
|
|
31
|
+
exec(db, "UPDATE admin_plans SET next_run_at=? WHERE id=?", now + plan.interval_seconds * 1000, plan.id);
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
let timer: ReturnType<typeof setInterval> | undefined;
|
|
37
|
+
export function startAdminScheduler(): void {
|
|
38
|
+
if (timer || !process.env.CHAT_ROOM_ADMIN_TOKEN || !process.env.CHAT_ROOM_SERVER_TOKEN || process.env.CHAT_ROOM_ADMIN_TOKEN === process.env.CHAT_ROOM_SERVER_TOKEN) return;
|
|
39
|
+
timer = setInterval(() => { void tickAdminScheduler().catch(() => {}); }, 5000);
|
|
40
|
+
timer.unref?.();
|
|
41
|
+
}
|
|
42
|
+
export function stopAdminScheduler(): void { if (timer) clearInterval(timer); timer = undefined; }
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import type { Database, SQLQueryBindings } from "bun:sqlite";
|
|
3
|
+
import { databasePath } from "../src/store";
|
|
4
|
+
import { initializeAdminSchema, withStateTransaction } from "../src/sqlite-state";
|
|
5
|
+
|
|
6
|
+
const hash = (value: string) => createHash("sha256").update(value).digest("hex");
|
|
7
|
+
const secret = () => randomBytes(32).toString("base64url");
|
|
8
|
+
const row = <T>(db: Database, sql: string, ...args: SQLQueryBindings[]) => db.query(sql).get(...args) as T | null;
|
|
9
|
+
const all = <T>(db: Database, sql: string, ...args: SQLQueryBindings[]) => db.query(sql).all(...args) as T[];
|
|
10
|
+
const run = (db: Database, sql: string, ...args: SQLQueryBindings[]) => db.query(sql).run(...args);
|
|
11
|
+
export type AdminRoom = { roomId: string; targetRoomId: string; sessionID: string; receiverOwnerID: string; membershipID: string; generation: number; enrolled: boolean; createdAt: number };
|
|
12
|
+
export type Binding = { room_id: string; target_room_id: string; session_id: string; receiver_owner_id: string; membership_id: string; generation: number; enrollment_hash: string; enrollment_expires: number; capability_hash: string | null; created_at: number };
|
|
13
|
+
export const digest = hash;
|
|
14
|
+
export const newSecret = secret;
|
|
15
|
+
export function safeEqual(a: string, b: string): boolean {
|
|
16
|
+
const left = Buffer.from(hash(a), "hex"), right = Buffer.from(hash(b), "hex");
|
|
17
|
+
return timingSafeEqual(left, right);
|
|
18
|
+
}
|
|
19
|
+
export function matchesHash(value: string, stored: string): boolean {
|
|
20
|
+
const left = Buffer.from(hash(value), "hex"), right = Buffer.from(stored, "hex");
|
|
21
|
+
return right.length === 32 && timingSafeEqual(left, right);
|
|
22
|
+
}
|
|
23
|
+
export async function ensureAdminSchema() { await initializeAdminSchema(databasePath()); }
|
|
24
|
+
export async function tx<T>(fn: (db: Database) => T) { await ensureAdminSchema(); return withStateTransaction(databasePath(), fn); }
|
|
25
|
+
export function publicRoom(b: Binding): AdminRoom { return { roomId: b.room_id, targetRoomId: b.target_room_id, sessionID: b.session_id, receiverOwnerID: b.receiver_owner_id, membershipID: b.membership_id, generation: b.generation, enrolled: Boolean(b.capability_hash), createdAt: b.created_at }; }
|
|
26
|
+
export function binding(db: Database, roomID: string) { return row<Binding>(db, "SELECT * FROM admin_rooms WHERE room_id=?", roomID); }
|
|
27
|
+
export function currentMember(db: Database, b: Binding) {
|
|
28
|
+
return row(db, `SELECT g.membership_id,g.receiver_owner_id,g.protocol,g.host,p.id AS participant_id
|
|
29
|
+
FROM registry g JOIN participants p ON p.room_id=g.room_id AND p.id=CASE WHEN (SELECT kind FROM rooms WHERE id=g.room_id)='direct' THEN g.session_id ELSE g.name END
|
|
30
|
+
WHERE g.room_id=? AND g.session_id=?`, b.target_room_id, b.session_id) as { membership_id: string; receiver_owner_id: string | null; protocol: string | null; host: string | null; participant_id: string } | null;
|
|
31
|
+
}
|
|
32
|
+
export function validCurrent(db: Database, b: Binding): boolean {
|
|
33
|
+
const m = currentMember(db, b);
|
|
34
|
+
return !!m && m.membership_id === b.membership_id && (m.receiver_owner_id ?? "") === b.receiver_owner_id && (m.protocol === "v1" || m.protocol === "v2" || Boolean(m.host));
|
|
35
|
+
}
|
|
36
|
+
export function enroll(db: Database, roomID: string, targetRoomID: string, sessionID: string, ownerID: string, membershipID: string, generation: number, createdAt = Date.now()) {
|
|
37
|
+
if (!row(db, "SELECT 1 FROM rooms WHERE id=? AND kind='group'", roomID) || !row(db, "SELECT 1 FROM rooms WHERE id=?", targetRoomID)) return undefined;
|
|
38
|
+
const nextKey = secret(), expiresAt = Date.now() + 600_000;
|
|
39
|
+
run(db, `INSERT INTO admin_rooms(room_id,target_room_id,session_id,receiver_owner_id,membership_id,generation,enrollment_hash,enrollment_expires,capability_hash,created_at)
|
|
40
|
+
VALUES(?,?,?,?,?,?,?,?,NULL,?) ON CONFLICT(room_id) DO UPDATE SET target_room_id=excluded.target_room_id,session_id=excluded.session_id,receiver_owner_id=excluded.receiver_owner_id,membership_id=excluded.membership_id,generation=excluded.generation,enrollment_hash=excluded.enrollment_hash,enrollment_expires=excluded.enrollment_expires,capability_hash=NULL`,
|
|
41
|
+
roomID, targetRoomID, sessionID, ownerID, membershipID, generation, hash(nextKey), expiresAt, createdAt);
|
|
42
|
+
run(db, "UPDATE admin_tasks SET status='cancelled',delivery_token_hash='',updated_at=? WHERE admin_room_id=? AND status IN ('pending','working','blocked')", Date.now(), roomID);
|
|
43
|
+
run(db, "DELETE FROM admin_deliveries WHERE admin_room_id=?", roomID);
|
|
44
|
+
run(db, "UPDATE admin_plans SET paused=1 WHERE admin_room_id=?", roomID);
|
|
45
|
+
return { enrollmentKey: nextKey, expiresAt };
|
|
46
|
+
}
|
|
47
|
+
export function isAgentMember(db: Database, roomID: string, sessionID: string, ownerID: string, membershipID: string) {
|
|
48
|
+
const entry = row<{ membership_id: string; receiver_owner_id: string | null; protocol: string | null; host: string | null }>(db,
|
|
49
|
+
`SELECT g.membership_id,g.receiver_owner_id,g.protocol,g.host FROM registry g JOIN participants p ON p.room_id=g.room_id AND p.id=CASE WHEN (SELECT kind FROM rooms WHERE id=g.room_id)='direct' THEN g.session_id ELSE g.name END WHERE g.room_id=? AND g.session_id=?`, roomID, sessionID);
|
|
50
|
+
return !!entry && entry.membership_id === membershipID && (entry.receiver_owner_id ?? "") === ownerID && (entry.protocol === "v1" || entry.protocol === "v2" || Boolean(entry.host));
|
|
51
|
+
}
|
|
52
|
+
export type Recipient = { roomID: string; sessionID: string; ownerID: string; membershipID: string };
|
|
53
|
+
export function queue(db: Database, b: Binding, kind: string, text: string, taskID: string | null = null, taskToken: string | null = null, recipient: Recipient = { roomID: b.target_room_id, sessionID: b.session_id, ownerID: b.receiver_owner_id, membershipID: b.membership_id }) {
|
|
54
|
+
const id = randomUUID();
|
|
55
|
+
run(db, `INSERT INTO admin_deliveries(id,admin_room_id,generation,recipient_room_id,session_id,owner_id,membership_id,kind,text,task_id,task_token,admission_id,created_at)
|
|
56
|
+
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(admin_room_id,kind,task_id) DO UPDATE SET text=excluded.text,task_token=excluded.task_token,generation=excluded.generation,recipient_room_id=excluded.recipient_room_id,session_id=excluded.session_id,owner_id=excluded.owner_id,membership_id=excluded.membership_id,created_at=excluded.created_at,acknowledged=0`,
|
|
57
|
+
id,b.room_id,b.generation,recipient.roomID,recipient.sessionID,recipient.ownerID,recipient.membershipID,kind,text,taskID,taskToken,`msg_${id}`,Date.now());
|
|
58
|
+
}
|
|
59
|
+
export function one<T>(db: Database, sql: string, ...args: SQLQueryBindings[]) { return row<T>(db, sql, ...args); }
|
|
60
|
+
export function many<T>(db: Database, sql: string, ...args: SQLQueryBindings[]) { return all<T>(db, sql, ...args); }
|
|
61
|
+
export { run as exec, randomUUID };
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import type { Database } from "bun:sqlite";
|
|
3
|
+
import { hasAdminCapability, isOperator } from "./admin-auth";
|
|
4
|
+
import { binding, digest, exec, isAgentMember, many, matchesHash, newSecret, one, queue, tx, validCurrent } from "./admin-state";
|
|
5
|
+
import type { Binding } from "./admin-state";
|
|
6
|
+
|
|
7
|
+
const json = (body: unknown, status = 200) => Response.json(body, { status, headers: { "Cache-Control": "no-store" } });
|
|
8
|
+
const object = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && !Array.isArray(value);
|
|
9
|
+
const statuses = ["pending", "working", "blocked", "completed", "cancelled"] as const;
|
|
10
|
+
type TaskStatus = typeof statuses[number];
|
|
11
|
+
const auth = (request: Request, b: Binding) => isOperator(request) || hasAdminCapability(request, b);
|
|
12
|
+
type TaskRow = { id: string; admin_room_id: string; admin_generation: number; target_room_id: string; target_session_id: string; target_owner_id: string; target_membership_id: string; text: string; status: string; progress: string; delivery_token_hash: string; created_at: number; updated_at: number };
|
|
13
|
+
type DeliveryRow = { id: string; admissionID: string; adminRoomId: string; generation: number; recipientRoomId: string; membershipID: string; kind: string; text: string; taskId: string | null; taskToken: string | null; createdAt: number };
|
|
14
|
+
type TaskView = { id: string; adminRoomId: string; generation: number; targetRoomId: string; targetSessionID: string; text: string; status: string; progress: string; createdAt: number; updatedAt: number };
|
|
15
|
+
type AckDelivery = { id: string; admin_room_id: string; generation: number; recipient_room_id: string; session_id: string; owner_id: string; membership_id: string; kind: string };
|
|
16
|
+
const revokeTaskDelivery = (db: Database, roomID: string, taskID: string) => {
|
|
17
|
+
exec(db, "DELETE FROM admin_deliveries WHERE admin_room_id=? AND kind='task' AND task_id=? AND acknowledged=0", roomID, taskID);
|
|
18
|
+
// A delivered prompt cannot be recalled; revoke its token so it cannot report progress.
|
|
19
|
+
exec(db, "UPDATE admin_deliveries SET task_token=NULL WHERE admin_room_id=? AND kind='task' AND task_id=?", roomID, taskID);
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export async function adminTaskRoutes(request: Request, url: URL): Promise<Response | undefined> {
|
|
23
|
+
const base = url.pathname.match(/^\/admin\/rooms\/([^/]+)\/tasks$/);
|
|
24
|
+
const update = url.pathname.match(/^\/admin\/rooms\/([^/]+)\/tasks\/([^/]+)$/);
|
|
25
|
+
if (base && request.method === "GET") return tx(db => {
|
|
26
|
+
const b = binding(db, decodeURIComponent(base[1]!));
|
|
27
|
+
if (!b) return { error: "admin room not found", status: 404 };
|
|
28
|
+
if (!auth(request, b)) return { error: "unauthorized", status: 401 };
|
|
29
|
+
if (!isOperator(request) && !validCurrent(db, b)) return { error: "binding is no longer active", status: 409 };
|
|
30
|
+
return { tasks: many<TaskView>(db, "SELECT id,admin_room_id AS adminRoomId,admin_generation AS generation,target_room_id AS targetRoomId,target_session_id AS targetSessionID,text,status,progress,created_at AS createdAt,updated_at AS updatedAt FROM admin_tasks WHERE admin_room_id=? ORDER BY created_at DESC LIMIT 200", b.room_id) };
|
|
31
|
+
}).then(result => "status" in result ? json({ error: result.error }, result.status) : json(result));
|
|
32
|
+
if (base && request.method === "POST") return createTask(request, decodeURIComponent(base[1]!));
|
|
33
|
+
if (update && request.method === "PATCH") return updateTask(request, decodeURIComponent(update[1]!), decodeURIComponent(update[2]!));
|
|
34
|
+
if (url.pathname === "/supervision/inbox" && request.method === "GET") return inbox(request, url);
|
|
35
|
+
if (url.pathname === "/supervision/ack" && request.method === "POST") return acknowledge(request);
|
|
36
|
+
const progress = url.pathname.match(/^\/supervision\/tasks\/([^/]+)\/progress$/);
|
|
37
|
+
if (progress && request.method === "POST") return reportProgress(request, decodeURIComponent(progress[1]!));
|
|
38
|
+
return undefined;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function createTask(request: Request, roomID: string): Promise<Response> {
|
|
42
|
+
const body: unknown = await request.json();
|
|
43
|
+
if (!object(body) || typeof body.targetRoomId !== "string" || !body.targetRoomId || typeof body.targetSessionID !== "string" || !body.targetSessionID || typeof body.text !== "string" || !body.text.trim() || body.text.trim().length > 2000) return json({ error: "invalid task" }, 400);
|
|
44
|
+
const targetRoomID = body.targetRoomId, targetSessionID = body.targetSessionID, text = body.text.trim();
|
|
45
|
+
const result = await tx(db => {
|
|
46
|
+
const b = binding(db, roomID);
|
|
47
|
+
if (!b) return { status: 404 as const };
|
|
48
|
+
if (!auth(request, b)) return { status: 401 as const };
|
|
49
|
+
if (!validCurrent(db, b)) return { status: 409 as const };
|
|
50
|
+
const recipient = one<{ receiver_owner_id: string | null; membership_id: string }>(db, "SELECT receiver_owner_id,membership_id FROM registry WHERE room_id=? AND session_id=?", targetRoomID, targetSessionID);
|
|
51
|
+
if (!recipient || !isAgentMember(db, targetRoomID, targetSessionID, recipient.receiver_owner_id ?? "", recipient.membership_id)) return { status: 409 as const };
|
|
52
|
+
const id = randomUUID(), now = Date.now(), taskToken = newSecret();
|
|
53
|
+
exec(db, "INSERT INTO admin_tasks(id,admin_room_id,admin_generation,target_room_id,target_session_id,target_owner_id,target_membership_id,text,status,progress,delivery_token_hash,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,'pending','',?,?,?)",
|
|
54
|
+
id, roomID, b.generation, targetRoomID, targetSessionID, recipient.receiver_owner_id ?? "", recipient.membership_id, text, digest(taskToken), now, now);
|
|
55
|
+
queue(db, b, "task", text, id, taskToken, { roomID: targetRoomID, sessionID: targetSessionID, ownerID: recipient.receiver_owner_id ?? "", membershipID: recipient.membership_id });
|
|
56
|
+
return { task: { id, adminRoomId: roomID, generation: b.generation, targetRoomId: targetRoomID, targetSessionID, text, status: "pending", progress: "", createdAt: now, updatedAt: now } };
|
|
57
|
+
});
|
|
58
|
+
if ("status" in result) return json({ error: result.status === 404 ? "admin room not found" : result.status === 401 ? "unauthorized" : "active agent target not found" }, result.status);
|
|
59
|
+
return json(result, 201);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function updateTask(request: Request, roomID: string, taskID: string): Promise<Response> {
|
|
63
|
+
const body: unknown = await request.json();
|
|
64
|
+
if (!object(body) || (body.status !== undefined && !statuses.includes(body.status as typeof statuses[number])) ||
|
|
65
|
+
(body.progress !== undefined && (typeof body.progress !== "string" || body.progress.length > 2000))) return json({ error: "invalid task update" }, 400);
|
|
66
|
+
const update = body as { status?: TaskStatus; progress?: string };
|
|
67
|
+
const result = await tx(db => {
|
|
68
|
+
const b = binding(db, roomID);
|
|
69
|
+
if (!b) return { status: 404 as const };
|
|
70
|
+
if (!auth(request, b)) return { status: 401 as const };
|
|
71
|
+
if (!validCurrent(db, b)) return { status: 409 as const };
|
|
72
|
+
const task = one<TaskRow>(db, "SELECT * FROM admin_tasks WHERE id=? AND admin_room_id=?", taskID, roomID);
|
|
73
|
+
if (!task || task.admin_generation !== b.generation) return { status: 404 as const };
|
|
74
|
+
const status = update.status ?? task.status;
|
|
75
|
+
if (task.status === "completed" || task.status === "cancelled") return { status: 409 as const };
|
|
76
|
+
const progress = update.progress === undefined ? task.progress : update.progress.trim();
|
|
77
|
+
const updatedAt = Date.now();
|
|
78
|
+
const terminal = status === "completed" || status === "cancelled";
|
|
79
|
+
exec(db, "UPDATE admin_tasks SET status=?,progress=?,delivery_token_hash=?,updated_at=? WHERE id=? AND admin_generation=?", status, progress, terminal ? "" : task.delivery_token_hash, updatedAt, taskID, b.generation);
|
|
80
|
+
if (terminal) revokeTaskDelivery(db, roomID, taskID);
|
|
81
|
+
return { task: { id: taskID, adminRoomId: roomID, generation: b.generation, targetRoomId: task.target_room_id,
|
|
82
|
+
targetSessionID: task.target_session_id, text: task.text, status, progress, createdAt: task.created_at, updatedAt } };
|
|
83
|
+
});
|
|
84
|
+
if ("status" in result) return json({ error: result.status === 401 ? "unauthorized" : result.status === 404 ? "task not found" : "binding is no longer active" }, result.status);
|
|
85
|
+
return json(result);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function reportProgress(request: Request, taskID: string): Promise<Response> {
|
|
89
|
+
const body: unknown = await request.json();
|
|
90
|
+
const sessionID = request.headers.get("x-chat-agent-session") ?? "";
|
|
91
|
+
const ownerID = request.headers.get("x-chat-agent-owner") ?? "";
|
|
92
|
+
if (!object(body) || typeof body.taskToken !== "string" || typeof body.status !== "string" ||
|
|
93
|
+
!statuses.includes(body.status as TaskStatus) || typeof body.progress !== "string" || body.progress.length > 2000) return json({ error: "invalid task progress" }, 400);
|
|
94
|
+
const update = body as { taskToken: string; status: TaskStatus; progress: string };
|
|
95
|
+
const result = await tx(db => {
|
|
96
|
+
const task = one<TaskRow>(db, "SELECT * FROM admin_tasks WHERE id=?", taskID);
|
|
97
|
+
if (!task) return false;
|
|
98
|
+
const b = binding(db, task.admin_room_id);
|
|
99
|
+
if (!b || task.admin_generation !== b.generation || task.status === "completed" || task.status === "cancelled" || !validCurrent(db, b) ||
|
|
100
|
+
sessionID !== task.target_session_id || ownerID !== task.target_owner_id ||
|
|
101
|
+
!isAgentMember(db, task.target_room_id, task.target_session_id, task.target_owner_id, task.target_membership_id) ||
|
|
102
|
+
!task.delivery_token_hash || !matchesHash(update.taskToken, task.delivery_token_hash)) return null;
|
|
103
|
+
const terminal = update.status === "completed" || update.status === "cancelled";
|
|
104
|
+
exec(db, "UPDATE admin_tasks SET status=?,progress=?,delivery_token_hash=?,updated_at=? WHERE id=? AND admin_generation=?",
|
|
105
|
+
update.status, update.progress.trim(), terminal ? "" : task.delivery_token_hash, Date.now(), taskID, b.generation);
|
|
106
|
+
if (terminal) revokeTaskDelivery(db, b.room_id, taskID);
|
|
107
|
+
return true;
|
|
108
|
+
});
|
|
109
|
+
if (result === null) return json({ error: "task progress credential rejected" }, 401);
|
|
110
|
+
return result ? json({ ok: true }) : json({ error: "task not found" }, 404);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
async function inbox(request: Request, url: URL): Promise<Response> {
|
|
114
|
+
const sessionID = url.searchParams.get("sessionID") ?? "";
|
|
115
|
+
const ownerID = url.searchParams.get("receiverOwnerID") ?? "";
|
|
116
|
+
const adminRoomID = url.searchParams.get("adminRoomId");
|
|
117
|
+
if (!sessionID || sessionID.length > 128 || ownerID.length > 128) return json({ error: "invalid agent identity" }, 400);
|
|
118
|
+
return adminRoomID ? protectedInbox(request, sessionID, ownerID, adminRoomID) : taskInbox(sessionID, ownerID);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function pruneStale(db: Database, sessionID: string, ownerID: string): void {
|
|
122
|
+
db.query(`DELETE FROM admin_deliveries AS d WHERE d.acknowledged=0 AND d.session_id=? AND d.owner_id=? AND (
|
|
123
|
+
NOT EXISTS(SELECT 1 FROM admin_rooms a WHERE a.room_id=d.admin_room_id AND a.generation=d.generation AND EXISTS(
|
|
124
|
+
SELECT 1 FROM registry g JOIN rooms r ON r.id=g.room_id JOIN participants p ON p.room_id=g.room_id AND p.id=CASE WHEN r.kind='direct' THEN g.session_id ELSE g.name END
|
|
125
|
+
WHERE g.room_id=a.target_room_id AND g.session_id=a.session_id AND g.membership_id=a.membership_id AND coalesce(g.receiver_owner_id,'')=a.receiver_owner_id AND (g.protocol IN ('v1','v2') OR coalesce(g.host,'')!='')))
|
|
126
|
+
OR NOT EXISTS(SELECT 1 FROM registry g JOIN rooms r ON r.id=g.room_id JOIN participants p ON p.room_id=g.room_id AND p.id=CASE WHEN r.kind='direct' THEN g.session_id ELSE g.name END
|
|
127
|
+
WHERE g.room_id=d.recipient_room_id AND g.session_id=d.session_id AND g.membership_id=d.membership_id AND coalesce(g.receiver_owner_id,'')=d.owner_id AND (g.protocol IN ('v1','v2') OR coalesce(g.host,'')!='')))`)
|
|
128
|
+
.run(sessionID, ownerID);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async function taskInbox(sessionID: string, ownerID: string): Promise<Response> {
|
|
132
|
+
const result = await tx(db => {
|
|
133
|
+
pruneStale(db, sessionID, ownerID);
|
|
134
|
+
const deliveries = many<DeliveryRow>(db, `SELECT d.id,d.admission_id AS admissionID,d.admin_room_id AS adminRoomId,d.generation,
|
|
135
|
+
d.recipient_room_id AS recipientRoomId,d.membership_id AS membershipID,d.kind,d.text,d.task_id AS taskId,d.task_token AS taskToken,d.created_at AS createdAt
|
|
136
|
+
FROM admin_deliveries d JOIN admin_tasks t ON t.id=d.task_id AND t.admin_room_id=d.admin_room_id AND t.admin_generation=d.generation
|
|
137
|
+
AND t.target_room_id=d.recipient_room_id AND t.target_session_id=d.session_id AND t.target_owner_id=d.owner_id AND t.target_membership_id=d.membership_id
|
|
138
|
+
WHERE d.session_id=? AND d.owner_id=? AND d.kind='task' AND d.acknowledged=0 ORDER BY d.created_at LIMIT 100`, sessionID, ownerID)
|
|
139
|
+
.map(({ taskToken, recipientRoomId, membershipID, ...delivery }) => ({ ...delivery, targetRoomId: recipientRoomId, ...(taskToken ? { taskToken } : {}) }));
|
|
140
|
+
const supervisionRoomIds = many<{ admin_room_id: string }>(db, `SELECT DISTINCT d.admin_room_id FROM admin_deliveries d JOIN admin_rooms a ON a.room_id=d.admin_room_id
|
|
141
|
+
WHERE d.session_id=a.session_id AND d.owner_id=a.receiver_owner_id AND d.membership_id=a.membership_id AND d.recipient_room_id=a.target_room_id
|
|
142
|
+
AND d.generation=a.generation AND d.session_id=? AND d.owner_id=? AND d.kind='supervision' AND d.acknowledged=0 ORDER BY d.admin_room_id LIMIT 100`, sessionID, ownerID).map(row => row.admin_room_id);
|
|
143
|
+
return { deliveries, supervisionRoomIds };
|
|
144
|
+
});
|
|
145
|
+
return json(result);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async function protectedInbox(request: Request, sessionID: string, ownerID: string, roomID: string): Promise<Response> {
|
|
149
|
+
const result = await tx(db => {
|
|
150
|
+
const b = binding(db, roomID);
|
|
151
|
+
if (!b) return { status: 404 as const };
|
|
152
|
+
const operator = isOperator(request);
|
|
153
|
+
if (!operator && (sessionID !== b.session_id || ownerID !== b.receiver_owner_id || !hasAdminCapability(request, b))) return { status: 401 as const };
|
|
154
|
+
if (!validCurrent(db, b)) return { status: 409 as const };
|
|
155
|
+
pruneStale(db, b.session_id, b.receiver_owner_id);
|
|
156
|
+
return { deliveries: many<DeliveryRow>(db, `SELECT id,admission_id AS admissionID,admin_room_id AS adminRoomId,generation,
|
|
157
|
+
recipient_room_id AS recipientRoomId,membership_id AS membershipID,kind,text,task_id AS taskId,task_token AS taskToken,created_at AS createdAt
|
|
158
|
+
FROM admin_deliveries WHERE admin_room_id=? AND generation=? AND recipient_room_id=? AND session_id=? AND owner_id=? AND membership_id=? AND kind='supervision' AND acknowledged=0 ORDER BY created_at LIMIT 100`,
|
|
159
|
+
roomID, b.generation, b.target_room_id, b.session_id, b.receiver_owner_id, b.membership_id).map(({ taskToken, membershipID, recipientRoomId, ...delivery }) => delivery) };
|
|
160
|
+
});
|
|
161
|
+
if ("status" in result) return json({ error: result.status === 401 ? "unauthorized" : result.status === 404 ? "admin room not found" : "binding is no longer active" }, result.status);
|
|
162
|
+
return json(result);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async function acknowledge(request: Request): Promise<Response> {
|
|
166
|
+
const body: unknown = await request.json();
|
|
167
|
+
if (!object(body) || typeof body.id !== "string" || typeof body.sessionID !== "string" || typeof body.receiverOwnerID !== "string") return json({ error: "invalid acknowledgement" }, 400);
|
|
168
|
+
const ack = body as { id: string; sessionID: string; receiverOwnerID: string };
|
|
169
|
+
const ok = await tx(db => {
|
|
170
|
+
const delivery = one<AckDelivery>(db, "SELECT * FROM admin_deliveries WHERE id=? AND acknowledged=0", ack.id);
|
|
171
|
+
if (!delivery || delivery.session_id !== ack.sessionID || delivery.owner_id !== ack.receiverOwnerID) return false;
|
|
172
|
+
const b = binding(db, delivery.admin_room_id);
|
|
173
|
+
if (!b || b.generation !== delivery.generation || !validCurrent(db, b) ||
|
|
174
|
+
!isAgentMember(db, delivery.recipient_room_id, delivery.session_id, delivery.owner_id, delivery.membership_id)) return false;
|
|
175
|
+
if (delivery.kind === "supervision" && (delivery.recipient_room_id !== b.target_room_id ||
|
|
176
|
+
delivery.session_id !== b.session_id || delivery.owner_id !== b.receiver_owner_id || delivery.membership_id !== b.membership_id ||
|
|
177
|
+
(!isOperator(request) && !hasAdminCapability(request, b)))) return false;
|
|
178
|
+
if (delivery.kind !== "task" && delivery.kind !== "supervision") return false;
|
|
179
|
+
return exec(db, "UPDATE admin_deliveries SET acknowledged=1 WHERE id=? AND acknowledged=0", ack.id).changes === 1;
|
|
180
|
+
});
|
|
181
|
+
return json({ ok });
|
|
182
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { deleteAnnouncement, getAnnouncement, listAnnouncements, putAnnouncement, validateAnnouncement } from "../src/announcements";
|
|
2
|
+
import { readState } from "../src/store";
|
|
3
|
+
|
|
4
|
+
const json = (body: unknown, status = 200) => Response.json(body, { status });
|
|
5
|
+
const object = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
6
|
+
|
|
7
|
+
export async function announcementRoutes(req: Request, url: URL): Promise<Response | undefined> {
|
|
8
|
+
const match = url.pathname.match(/^\/rooms\/([^/]+)\/announcements(?:\/([^/]+))?$/);
|
|
9
|
+
if (!match || !["GET", "PUT", "DELETE"].includes(req.method)) return undefined;
|
|
10
|
+
let roomID: string, name: string | undefined;
|
|
11
|
+
try { roomID = decodeURIComponent(match[1]!); name = match[2] === undefined ? undefined : decodeURIComponent(match[2]); }
|
|
12
|
+
catch { return json({ error: "invalid path" }, 400); }
|
|
13
|
+
const roomExists = await readState((svc) => { try { svc.getRoom(roomID); return true; } catch { return false; } });
|
|
14
|
+
if (!roomExists) return json({ error: "room not found" }, 404);
|
|
15
|
+
if (req.method === "GET") {
|
|
16
|
+
if (!name) return json({ announcements: await listAnnouncements(roomID) });
|
|
17
|
+
if (validateAnnouncement(name)) return json({ error: "invalid announcement name" }, 400);
|
|
18
|
+
const announcement = await getAnnouncement(roomID, name);
|
|
19
|
+
return announcement ? json({ announcement }) : json({ error: "announcement not found" }, 404);
|
|
20
|
+
}
|
|
21
|
+
let body: unknown;
|
|
22
|
+
try { body = await req.json(); } catch { return json({ error: "invalid JSON body" }, 400); }
|
|
23
|
+
if (!object(body) || typeof body.sessionID !== "string" || !body.sessionID) return json({ error: "sessionID is required" }, 400);
|
|
24
|
+
const member = await readState((_svc, registry) => Boolean(registry[roomID]?.[body.sessionID as string]));
|
|
25
|
+
if (!member) return json({ error: "not a room member" }, 403);
|
|
26
|
+
if (req.method === "PUT") {
|
|
27
|
+
const error = validateAnnouncement(name, body.content, true);
|
|
28
|
+
if (error) return json({ error }, 400);
|
|
29
|
+
const announcement = await putAnnouncement(roomID, name!.trim(), body.content as string);
|
|
30
|
+
return announcement ? json({ announcement }) : json({ error: "room not found" }, 404);
|
|
31
|
+
}
|
|
32
|
+
if (!name || validateAnnouncement(name)) return json({ error: "invalid announcement name" }, 400);
|
|
33
|
+
return await deleteAnnouncement(roomID, name) ? json({ ok: true }) : json({ error: "announcement not found" }, 404);
|
|
34
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2014 - 2022 Knut Sveidqvist
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/server/assets/NOTICE.txt
CHANGED
|
@@ -2,5 +2,6 @@ Browser vendors bundled locally; no external requests are made at runtime.
|
|
|
2
2
|
|
|
3
3
|
marked 18.0.4 — MIT License, see MARKED-LICENSE.
|
|
4
4
|
DOMPurify 3.4.7 — MPL 2.0 or Apache License 2.0, see DOMPURIFY-LICENSE.
|
|
5
|
+
Mermaid 11.12.2 — MIT License, see MERMAID-LICENSE.
|
|
5
6
|
|
|
6
|
-
Sources: https://www.npmjs.com/package/marked and https://www.npmjs.com/package/
|
|
7
|
+
Sources: https://www.npmjs.com/package/marked, https://www.npmjs.com/package/dompurify and https://www.npmjs.com/package/mermaid
|