-
Notifications
You must be signed in to change notification settings - Fork 6
/
LabelerServer.ts
494 lines (431 loc) · 14.1 KB
/
LabelerServer.ts
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
import "@atcute/ozone/lexicons";
import { XRPCError } from "@atcute/client";
import type {
At,
ComAtprotoLabelQueryLabels,
ToolsOzoneModerationEmitEvent,
} from "@atcute/client/lexicons";
import { fastifyWebsocket } from "@fastify/websocket";
import fastify, { type FastifyInstance, type FastifyRequest } from "fastify";
import Database, { type Database as SQLiteDatabase } from "libsql";
import type { WebSocket } from "ws";
import { parsePrivateKey, verifyJwt } from "./util/crypto.js";
import { formatLabel, labelIsSigned, signLabel } from "./util/labels.js";
import type {
CreateLabelData,
ProcedureHandler,
QueryHandler,
SavedLabel,
SignedLabel,
SubscriptionHandler,
UnsignedLabel,
} from "./util/types.js";
import { excludeNullish, frameToBytes } from "./util/util.js";
const INVALID_SIGNING_KEY_ERROR = `Make sure to provide a private signing key, not a public key.
If you don't have a key, generate and set one using the \`npx @skyware/labeler setup\` command or the \`import { plcSetupLabeler } from "@skyware/labeler/scripts"\` function.
For more information, see https://skyware.js.org/guides/labeler/introduction/getting-started/`;
/**
* Options for the {@link LabelerServer} class.
*/
export interface LabelerOptions {
/** The DID of the labeler account. */
did: string;
/**
* The private signing key used for the labeler.
* If you don't have a key, generate and set one using {@link plcSetupLabeler}.
*/
signingKey: string;
/**
* A function that returns whether a DID is authorized to create labels.
* By default, only the labeler account is authorized.
* @param did The DID to check.
*/
auth?: (did: string) => boolean | Promise<boolean>;
/**
* The path to the SQLite `.db` database file.
* @default labels.db
*/
dbPath?: string;
}
export class LabelerServer {
/** The Fastify application instance. */
app: FastifyInstance;
/** The SQLite database instance. */
db: SQLiteDatabase;
/** The DID of the labeler account. */
did: At.DID;
/** A function that returns whether a DID is authorized to create labels. */
private auth: (did: string) => boolean | Promise<boolean>;
/** Open WebSocket connections, mapped by request NSID. */
private connections = new Map<string, Set<WebSocket>>();
/** The signing key used for the labeler. */
#signingKey: Uint8Array;
/**
* Create a labeler server.
* @param options Configuration options.
*/
constructor(options: LabelerOptions) {
this.did = options.did as At.DID;
this.auth = options.auth ?? ((did) => did === this.did);
try {
if (options.signingKey.startsWith("did:key:")) throw 0;
this.#signingKey = parsePrivateKey(options.signingKey);
if (this.#signingKey.byteLength !== 32) throw 0;
} catch {
throw new Error(INVALID_SIGNING_KEY_ERROR);
}
this.db = new Database(options.dbPath ?? "labels.db");
this.db.pragma("journal_mode = WAL");
this.db.exec(`
CREATE TABLE IF NOT EXISTS labels (
id INTEGER PRIMARY KEY AUTOINCREMENT,
src TEXT NOT NULL,
uri TEXT NOT NULL,
cid TEXT,
val TEXT NOT NULL,
neg BOOLEAN DEFAULT FALSE,
cts DATETIME NOT NULL,
exp DATETIME,
sig BLOB
);
`);
this.app = fastify();
void this.app.register(fastifyWebsocket).then(() => {
this.app.get("/xrpc/com.atproto.label.queryLabels", this.queryLabelsHandler);
this.app.post("/xrpc/tools.ozone.moderation.emitEvent", this.emitEventHandler);
this.app.get(
"/xrpc/com.atproto.label.subscribeLabels",
{ websocket: true },
this.subscribeLabelsHandler,
);
this.app.get("/xrpc/*", this.unknownMethodHandler);
this.app.setErrorHandler(this.errorHandler);
});
}
/**
* Start the server.
* @param port The port to listen on.
* @param callback A callback to run when the server is started.
*/
start(port: number, callback: (error: Error | null, address: string) => void = () => {}) {
this.app.listen({ port }, callback);
}
/**
* Stop the server.
* @param callback A callback to run when the server is stopped.
*/
close(callback: () => void = () => {}) {
this.app.close(callback);
}
/**
* Alias for {@link LabelerServer#close}.
* @param callback A callback to run when the server is stopped.
*/
stop(callback: () => void = () => {}) {
this.close(callback);
}
/**
* Insert a label into the database, emitting it to subscribers.
* @param label The label to insert.
* @returns The inserted label.
*/
private saveLabel(label: UnsignedLabel): SavedLabel {
const signed = labelIsSigned(label) ? label : signLabel(label, this.#signingKey);
const stmt = this.db.prepare(`
INSERT INTO labels (src, uri, cid, val, neg, cts, exp, sig)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
`);
const { src, uri, cid, val, neg, cts, exp, sig } = signed;
const result = stmt.run(src, uri, cid, val, neg ? 1 : 0, cts, exp, sig);
if (!result.changes) throw new Error("Failed to insert label");
const id = Number(result.lastInsertRowid);
this.emitLabel(id, signed);
return { id, ...signed };
}
/**
* Create and insert a label into the database, emitting it to subscribers.
* @param label The label to create.
* @returns The created label.
*/
createLabel(label: CreateLabelData): SavedLabel {
return this.saveLabel(
excludeNullish({
...label,
src: (label.src ?? this.did) as At.DID,
cts: label.cts ?? new Date().toISOString(),
}),
);
}
/**
* Create and insert labels into the database, emitting them to subscribers.
* @param subject The subject of the labels.
* @param labels The labels to create.
* @returns The created labels.
*/
createLabels(
subject: { uri: string; cid?: string | undefined },
labels: { create?: Array<string>; negate?: Array<string> },
): Array<SavedLabel> {
const { uri, cid } = subject;
const { create, negate } = labels;
const createdLabels: Array<SavedLabel> = [];
if (create) {
for (const val of create) {
const created = this.createLabel({ uri, cid, val });
createdLabels.push(created);
}
}
if (negate) {
for (const val of negate) {
const negated = this.createLabel({ uri, cid, val, neg: true });
createdLabels.push(negated);
}
}
return createdLabels;
}
/**
* Emit a label to all subscribers.
* @param seq The label's id.
* @param label The label to emit.
*/
private emitLabel(seq: number, label: SignedLabel) {
const bytes = frameToBytes("message", { seq, labels: [formatLabel(label)] }, "#labels");
this.connections.get("com.atproto.label.subscribeLabels")?.forEach((ws) => {
ws.send(bytes);
});
}
/**
* Parse a user DID from an Authorization header JWT.
* @param req The Express request object.
*/
private async parseAuthHeaderDid(req: FastifyRequest): Promise<string> {
const authHeader = req.headers.authorization;
if (!authHeader) {
throw new XRPCError(401, {
kind: "AuthRequired",
description: "Authorization header is required",
});
}
const [type, token] = authHeader.split(" ");
if (type !== "Bearer" || !token) {
throw new XRPCError(400, {
kind: "MissingJwt",
description: "Missing or invalid bearer token",
});
}
const nsid = (req.originalUrl || req.url || "").split("?")[0].replace("/xrpc/", "").replace(
/\/$/,
"",
);
const payload = await verifyJwt(token, this.did, nsid);
return payload.iss;
}
/**
* Handler for [com.atproto.label.queryLabels](https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/label/queryLabels.json).
*/
queryLabelsHandler: QueryHandler<ComAtprotoLabelQueryLabels.Params> = async (req, res) => {
let uriPatterns: Array<string>;
if (!req.query.uriPatterns) {
uriPatterns = [];
} else if (typeof req.query.uriPatterns === "string") {
uriPatterns = [req.query.uriPatterns];
} else {
uriPatterns = req.query.uriPatterns || [];
}
let sources: Array<string>;
if (!req.query.sources) {
sources = [];
} else if (typeof req.query.sources === "string") {
sources = [req.query.sources];
} else {
sources = req.query.sources || [];
}
const cursor = parseInt(`${req.query.cursor || 0}`, 10);
if (cursor !== undefined && Number.isNaN(cursor)) {
throw new XRPCError(400, {
kind: "InvalidRequest",
description: "Cursor must be an integer",
});
}
const limit = parseInt(`${req.query.limit || 50}`, 10);
if (Number.isNaN(limit) || limit < 1 || limit > 250) {
throw new XRPCError(400, {
kind: "InvalidRequest",
description: "Limit must be an integer between 1 and 250",
});
}
const patterns = uriPatterns.includes("*") ? [] : uriPatterns.map((pattern) => {
pattern = pattern.replaceAll(/%/g, "").replaceAll(/_/g, "\\_");
const starIndex = pattern.indexOf("*");
if (starIndex === -1) return pattern;
if (starIndex !== pattern.length - 1) {
throw new XRPCError(400, {
kind: "InvalidRequest",
description: "Only trailing wildcards are supported in uriPatterns",
});
}
return pattern.slice(0, -1) + "%";
});
const stmt = this.db.prepare(`
SELECT * FROM labels
WHERE 1 = 1
${patterns.length ? "AND " + patterns.map(() => "uri LIKE ?").join(" OR ") : ""}
${sources.length ? `AND src IN (${sources.map(() => "?").join(", ")})` : ""}
${cursor ? "AND id > ?" : ""}
ORDER BY id ASC
LIMIT ?
`);
const params = [];
if (patterns.length) params.push(...patterns);
if (sources.length) params.push(...sources);
if (cursor) params.push(cursor);
params.push(limit);
const rows = stmt.all(params) as Array<SavedLabel>;
const labels = rows.map(formatLabel);
const nextCursor = rows[rows.length - 1]?.id?.toString(10) || "0";
await res.send({ cursor: nextCursor, labels } satisfies ComAtprotoLabelQueryLabels.Output);
};
/**
* Handler for [com.atproto.label.subscribeLabels](https://github.com/bluesky-social/atproto/blob/main/lexicons/com/atproto/label/subscribeLabels.json).
*/
subscribeLabelsHandler: SubscriptionHandler<{ cursor?: string }> = (ws, req) => {
const cursor = parseInt(req.query.cursor ?? "NaN", 10);
if (!Number.isNaN(cursor)) {
const latest = this.db.prepare(`
SELECT MAX(id) AS id FROM labels
`).get() as { id: number };
if (cursor > (latest.id ?? 0)) {
const errorBytes = frameToBytes("error", {
error: "FutureCursor",
message: "Cursor is in the future",
});
ws.send(errorBytes);
ws.terminate();
}
const stmt = this.db.prepare<[number]>(`
SELECT * FROM labels
WHERE id > ?
ORDER BY id ASC
`);
try {
for (const row of stmt.iterate(cursor)) {
const { id: seq, ...label } = row as SavedLabel;
const bytes = frameToBytes(
"message",
{ seq, labels: [formatLabel(label)] },
"#labels",
);
ws.send(bytes);
}
} catch (e) {
console.error(e);
const errorBytes = frameToBytes("error", {
error: "InternalServerError",
message: "An unknown error occurred",
});
ws.send(errorBytes);
ws.terminate();
}
}
this.addSubscription("com.atproto.label.subscribeLabels", ws);
ws.on("close", () => {
this.removeSubscription("com.atproto.label.subscribeLabels", ws);
});
};
/**
* Handler for [tools.ozone.moderation.emitEvent](https://github.com/bluesky-social/atproto/blob/main/lexicons/tools/ozone/moderation/emitEvent.json).
*/
emitEventHandler: ProcedureHandler<ToolsOzoneModerationEmitEvent.Input> = async (req, res) => {
const actorDid = await this.parseAuthHeaderDid(req);
const authed = await this.auth(actorDid);
if (!authed) {
throw new XRPCError(401, { kind: "AuthRequired", description: "Unauthorized" });
}
const { event, subject, subjectBlobCids = [], createdBy } = req.body;
if (!event || !subject || !createdBy) {
throw new XRPCError(400, {
kind: "InvalidRequest",
description: "Missing required field(s)",
});
}
if (event.$type !== "tools.ozone.moderation.defs#modEventLabel") {
throw new XRPCError(400, {
kind: "InvalidRequest",
description: "Unsupported event type",
});
}
if (!event.createLabelVals?.length && !event.negateLabelVals?.length) {
throw new XRPCError(400, {
kind: "InvalidRequest",
description: "Must provide at least one label value",
});
}
const uri = subject.$type === "com.atproto.admin.defs#repoRef"
? subject.did
: subject.$type === "com.atproto.repo.strongRef"
? subject.uri
: null;
const cid = subject.$type === "com.atproto.repo.strongRef" ? subject.cid : undefined;
if (!uri) {
throw new XRPCError(400, { kind: "InvalidRequest", description: "Invalid subject" });
}
const labels = this.createLabels({ uri, cid }, {
create: event.createLabelVals,
negate: event.negateLabelVals,
});
if (!labels.length || !labels[0]?.id) {
throw new Error(`No labels were created\nEvent:\n${JSON.stringify(event, null, 2)}`);
}
await res.send(
{
id: labels[0].id,
event,
subject,
subjectBlobCids,
createdBy,
createdAt: new Date().toISOString(),
} satisfies ToolsOzoneModerationEmitEvent.Output,
);
};
/**
* Catch-all handler for unknown XRPC methods.
*/
unknownMethodHandler: QueryHandler = async (_req, res) =>
res.status(501).send({ error: "MethodNotImplemented", message: "Method Not Implemented" });
/**
* Default error handler.
*/
errorHandler: typeof this.app.errorHandler = async (err, _req, res) => {
if (err instanceof XRPCError) {
return res.status(err.status).send({ error: err.kind, message: err.description });
} else {
console.error(err);
return res.status(500).send({
error: "InternalServerError",
message: "An unknown error occurred",
});
}
};
/**
* Add a WebSocket connection to the list of subscribers for a given lexicon.
* @param nsid The NSID of the lexicon to subscribe to.
* @param ws The WebSocket connection to add.
*/
private addSubscription(nsid: string, ws: WebSocket) {
const subs = this.connections.get(nsid) ?? new Set();
subs.add(ws);
this.connections.set(nsid, subs);
}
/**
* Remove a WebSocket connection from the list of subscribers for a given lexicon.
* @param nsid The NSID of the lexicon to unsubscribe from.
* @param ws The WebSocket connection to remove.
*/
private removeSubscription(nsid: string, ws: WebSocket) {
const subs = this.connections.get(nsid);
if (subs) {
subs.delete(ws);
if (!subs.size) this.connections.delete(nsid);
}
}
}