chirli 0.0.0-stage → 0.2.0

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.
Files changed (97) hide show
  1. package/ARCHITECTURE.md +103 -0
  2. package/CONTRIBUTING.md +56 -0
  3. package/LICENSE +22 -0
  4. package/README.md +281 -2
  5. package/SECURITY.md +55 -0
  6. package/THIRD_PARTY_NOTICES.md +51 -0
  7. package/dist/allowlist.d.ts +3 -0
  8. package/dist/allowlist.js +9 -0
  9. package/dist/announcements.d.ts +25 -0
  10. package/dist/announcements.js +142 -0
  11. package/dist/attachments.d.ts +43 -0
  12. package/dist/attachments.js +340 -0
  13. package/dist/blossom.d.ts +30 -0
  14. package/dist/blossom.js +233 -0
  15. package/dist/bot-handlers.d.ts +70 -0
  16. package/dist/bot-handlers.js +317 -0
  17. package/dist/bot.d.ts +63 -0
  18. package/dist/bot.js +244 -0
  19. package/dist/client.d.ts +221 -0
  20. package/dist/client.js +1197 -0
  21. package/dist/command-discovery.d.ts +4 -0
  22. package/dist/command-discovery.js +33 -0
  23. package/dist/command-schema.d.ts +4 -0
  24. package/dist/command-schema.js +101 -0
  25. package/dist/commands.d.ts +32 -0
  26. package/dist/commands.js +253 -0
  27. package/dist/defaults.d.ts +9 -0
  28. package/dist/defaults.js +22 -0
  29. package/dist/errors.d.ts +55 -0
  30. package/dist/errors.js +126 -0
  31. package/dist/inbox.d.ts +55 -0
  32. package/dist/inbox.js +376 -0
  33. package/dist/index.d.ts +25 -0
  34. package/dist/index.js +11 -0
  35. package/dist/key-sync.d.ts +33 -0
  36. package/dist/key-sync.js +293 -0
  37. package/dist/keys.d.ts +66 -0
  38. package/dist/keys.js +418 -0
  39. package/dist/message-storage-sqlite.d.ts +6 -0
  40. package/dist/message-storage-sqlite.js +90 -0
  41. package/dist/message-storage.d.ts +32 -0
  42. package/dist/message-storage.js +1 -0
  43. package/dist/messaging-metadata.d.ts +48 -0
  44. package/dist/messaging-metadata.js +280 -0
  45. package/dist/metadata.d.ts +7 -0
  46. package/dist/metadata.js +63 -0
  47. package/dist/modes.d.ts +26 -0
  48. package/dist/modes.js +108 -0
  49. package/dist/nip4e-compat.d.ts +4 -0
  50. package/dist/nip4e-compat.js +14 -0
  51. package/dist/nipcd.d.ts +109 -0
  52. package/dist/nipcd.js +555 -0
  53. package/dist/protocol.d.ts +68 -0
  54. package/dist/protocol.js +302 -0
  55. package/dist/public-inbox.d.ts +66 -0
  56. package/dist/public-inbox.js +295 -0
  57. package/dist/public-thread.d.ts +62 -0
  58. package/dist/public-thread.js +436 -0
  59. package/dist/relay-pool.d.ts +43 -0
  60. package/dist/relay-pool.js +429 -0
  61. package/dist/relay-roles.d.ts +18 -0
  62. package/dist/relay-roles.js +55 -0
  63. package/dist/relay.d.ts +52 -0
  64. package/dist/relay.js +493 -0
  65. package/dist/request-timing.d.ts +12 -0
  66. package/dist/request-timing.js +37 -0
  67. package/dist/session.d.ts +16 -0
  68. package/dist/session.js +51 -0
  69. package/dist/signer.d.ts +13 -0
  70. package/dist/signer.js +1 -0
  71. package/dist/signers/bunker-relays.d.ts +15 -0
  72. package/dist/signers/bunker-relays.js +87 -0
  73. package/dist/signers/bunker.d.ts +7 -0
  74. package/dist/signers/bunker.js +194 -0
  75. package/dist/signers/nsec.d.ts +3 -0
  76. package/dist/signers/nsec.js +62 -0
  77. package/dist/signers.d.ts +18 -0
  78. package/dist/signers.js +59 -0
  79. package/dist/storage-sqlite.d.ts +29 -0
  80. package/dist/storage-sqlite.js +221 -0
  81. package/dist/storage.d.ts +85 -0
  82. package/dist/storage.js +1 -0
  83. package/dist/store.d.ts +96 -0
  84. package/dist/store.js +404 -0
  85. package/docs/ACCESS.md +28 -0
  86. package/docs/API.md +382 -0
  87. package/docs/INTEROPERABILITY.md +32 -0
  88. package/docs/KEYS.md +75 -0
  89. package/docs/NIP-CD.md +112 -0
  90. package/docs/PUBLIC.md +88 -0
  91. package/docs/RECOVERY.md +59 -0
  92. package/docs/RELAYS.md +145 -0
  93. package/docs/SESSIONS.md +108 -0
  94. package/docs/SIGNERS.md +59 -0
  95. package/docs/STORAGE.md +71 -0
  96. package/docs/TUTORIAL.md +178 -0
  97. package/package.json +47 -4
@@ -0,0 +1,233 @@
1
+ import { createCipheriv, createHash, randomBytes } from "node:crypto";
2
+ import { DEFAULT_BLOSSOM_SERVERS } from "./defaults.js";
3
+ import { signChecked } from "./protocol.js";
4
+ const maxFileBytes = 64 * 1024 * 1024;
5
+ const maxDescriptorBytes = 16 * 1024;
6
+ const uploadTimeoutMs = 60_000;
7
+ const mirrorTimeoutMs = 10_000;
8
+ const hash = (bytes) => createHash("sha256").update(bytes).digest("hex");
9
+ const loopbackHost = (host) => ["localhost", "127.0.0.1", "[::1]"].includes(host);
10
+ function httpUrl(value) {
11
+ if (typeof value !== "string" || value.length > 2048 || /\s/.test(value))
12
+ return;
13
+ try {
14
+ const url = new URL(value);
15
+ if ((url.protocol === "https:" ||
16
+ (loopbackHost(url.hostname) && url.protocol === "http:")) &&
17
+ !url.username &&
18
+ !url.password &&
19
+ !url.search &&
20
+ !url.hash)
21
+ return url;
22
+ }
23
+ catch {
24
+ /* Invalid URL */
25
+ }
26
+ }
27
+ export function normalizeBlossomServers(values) {
28
+ values ??= DEFAULT_BLOSSOM_SERVERS;
29
+ if (!Array.isArray(values))
30
+ throw new TypeError("blossomServers must be an array of HTTP(S) URLs");
31
+ const servers = Array.from(values, (value) => {
32
+ const url = httpUrl(value);
33
+ if (!url)
34
+ throw new TypeError("Blossom URLs must use HTTPS (HTTP is allowed on loopback), without credentials, query or fragment");
35
+ return url.pathname === "/" ? url.href : url.href.replace(/\/+$/, "");
36
+ });
37
+ return [...new Set(servers)];
38
+ }
39
+ /** Additional trusted HTTPS origins that may host a server's blob descriptors. */
40
+ export function normalizeBlossomDownloadOrigins(values) {
41
+ if (values === undefined)
42
+ return new Set();
43
+ if (!Array.isArray(values))
44
+ throw new TypeError("blossomDownloadOrigins must be an array of HTTPS origins");
45
+ return new Set(Array.from(values, (value) => {
46
+ const url = httpUrl(value);
47
+ if (url?.protocol !== "https:" ||
48
+ url.pathname !== "/" ||
49
+ loopbackHost(url.hostname)) {
50
+ throw new TypeError("blossomDownloadOrigins must contain HTTPS origins, without paths, credentials, queries or fragments");
51
+ }
52
+ return url.origin;
53
+ }));
54
+ }
55
+ function validateSize(data, overhead = 0) {
56
+ if (!(data instanceof Uint8Array) ||
57
+ data.byteLength === 0 ||
58
+ data.byteLength + overhead > maxFileBytes) {
59
+ throw new TypeError("File must be a nonempty Uint8Array with an upload size of at most 64 MiB");
60
+ }
61
+ }
62
+ function validateMimeType(mimeType) {
63
+ if (typeof mimeType !== "string" ||
64
+ mimeType.length > 127 ||
65
+ !/^[\w!#$&^.+-]+\/[\w!#$&^.+-]+$/.test(mimeType)) {
66
+ throw new TypeError("Invalid file MIME type");
67
+ }
68
+ }
69
+ export function snapshotFile(data) {
70
+ validateSize(data);
71
+ return Buffer.from(data);
72
+ }
73
+ export function encryptAttachment(data, { mimeType = "application/octet-stream", name }) {
74
+ validateSize(data, 16);
75
+ validateMimeType(mimeType);
76
+ if (name !== undefined &&
77
+ (typeof name !== "string" ||
78
+ !name.length ||
79
+ Buffer.byteLength(name) > 255 ||
80
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: Reject ASCII control characters in attachment names.
81
+ /[\x00-\x1f\x7f]/.test(name))) {
82
+ throw new TypeError("Attachment name must be nonempty, without control characters, and at most 255 UTF-8 bytes");
83
+ }
84
+ const key = randomBytes(32), nonce = randomBytes(12);
85
+ const cipher = createCipheriv("aes-256-gcm", key, nonce);
86
+ const bytes = Buffer.concat([
87
+ cipher.update(data),
88
+ cipher.final(),
89
+ cipher.getAuthTag(),
90
+ ]);
91
+ return {
92
+ bytes,
93
+ tags: [
94
+ ["file-type", mimeType],
95
+ ["encryption-algorithm", "aes-gcm"],
96
+ ["decryption-key", key.toString("hex")],
97
+ ["decryption-nonce", nonce.toString("hex")],
98
+ ["ox", hash(data)],
99
+ ["plain-size", String(data.byteLength)],
100
+ ...(name === undefined ? [] : [["name", name]]),
101
+ ],
102
+ };
103
+ }
104
+ async function descriptor(response, sha256, size, server, downloadOrigins) {
105
+ const reader = response.body?.getReader();
106
+ if (!reader)
107
+ throw new Error("Missing Blossom descriptor");
108
+ const chunks = [];
109
+ let length = 0;
110
+ try {
111
+ while (true) {
112
+ const { done, value } = await reader.read();
113
+ if (done)
114
+ break;
115
+ length += value.length;
116
+ if (length > maxDescriptorBytes)
117
+ throw new Error("Blossom descriptor too large");
118
+ chunks.push(value);
119
+ }
120
+ }
121
+ finally {
122
+ void reader.cancel().catch(() => { });
123
+ }
124
+ const input = JSON.parse(Buffer.concat(chunks).toString("utf8"));
125
+ const url = typeof input?.url === "string" ? httpUrl(input.url) : undefined;
126
+ const serverOrigin = new URL(server).origin;
127
+ const trustedOrigin = url &&
128
+ (url.origin === serverOrigin ||
129
+ (!loopbackHost(url.hostname) && downloadOrigins.has(url.origin)));
130
+ const filenameHash = url?.pathname
131
+ .split("/")
132
+ .at(-1)
133
+ ?.match(/^([0-9a-f]{64})(?:\.[a-z0-9_-]+)?$/i)?.[1]
134
+ .toLowerCase();
135
+ if (!url ||
136
+ !trustedOrigin ||
137
+ filenameHash !== sha256 ||
138
+ input?.sha256 !== sha256 ||
139
+ input.size !== size) {
140
+ throw new Error("Invalid Blossom upload descriptor");
141
+ }
142
+ return url.href;
143
+ }
144
+ async function uploadAuthorization(identity, servers, sha256, size) {
145
+ const hosts = [...new Set(servers.map((server) => new URL(server).hostname))];
146
+ const now = Math.floor(Date.now() / 1000), expiration = now + 300;
147
+ const event = await signChecked(identity, {
148
+ kind: 24242,
149
+ created_at: now,
150
+ content: "Upload file to Blossom",
151
+ tags: [
152
+ ["t", "upload"],
153
+ ["x", sha256],
154
+ ["size", String(size)],
155
+ ...hosts.map((host) => ["server", host]),
156
+ ["expiration", String(expiration)],
157
+ ],
158
+ });
159
+ const token = Buffer.from(JSON.stringify(event));
160
+ return {
161
+ base64url: token.toString("base64url"),
162
+ base64: token.toString("base64"),
163
+ expiresAt: expiration * 1000,
164
+ };
165
+ }
166
+ async function putBlossom(authorization, server, operation, body, headers, sha256, size, downloadOrigins) {
167
+ const remaining = authorization.expiresAt - Date.now();
168
+ if (remaining <= 0)
169
+ throw new Error("Blossom authorization expired while waiting for the signer");
170
+ const signal = AbortSignal.timeout(Math.min(remaining, operation === "mirror" ? mirrorTimeoutMs : uploadTimeoutMs));
171
+ const put = (encoding) => fetch(`${server.replace(/\/+$/, "")}/${operation}`, {
172
+ method: "PUT",
173
+ redirect: "error",
174
+ signal,
175
+ body,
176
+ headers: {
177
+ ...headers,
178
+ authorization: `Nostr ${authorization[encoding]}`,
179
+ "content-length": String(body.length),
180
+ "x-sha-256": sha256,
181
+ },
182
+ });
183
+ try {
184
+ let response = await put("base64url");
185
+ if ((response.status === 400 || response.status === 401) &&
186
+ authorization.base64url !== authorization.base64) {
187
+ void response.body?.cancel().catch(() => { });
188
+ response = await put("base64");
189
+ }
190
+ if (!response.ok) {
191
+ void response.body?.cancel().catch(() => { });
192
+ return;
193
+ }
194
+ return await descriptor(response, sha256, size, server, downloadOrigins);
195
+ }
196
+ catch {
197
+ /* Do not copy server responses or tokens into errors. */
198
+ }
199
+ }
200
+ /** Use only configured servers, in priority order. Auth is not published to relays. */
201
+ export async function uploadFile(identity, servers, downloadOrigins, data, { mimeType = "application/octet-stream" } = {}) {
202
+ if (!servers.length)
203
+ throw new Error("Configure blossomServers before uploading files");
204
+ validateMimeType(mimeType);
205
+ const bytes = snapshotFile(data), size = bytes.length, sha256 = hash(bytes);
206
+ let authorization;
207
+ for (const [index, server] of servers.entries()) {
208
+ if (!authorization ||
209
+ authorization.expiresAt - Date.now() <= uploadTimeoutMs + mirrorTimeoutMs) {
210
+ authorization = await uploadAuthorization(identity, servers.slice(index), sha256, size);
211
+ }
212
+ const signed = authorization;
213
+ const url = await putBlossom(signed, server, "upload", bytes, { "content-type": mimeType }, sha256, size, downloadOrigins);
214
+ if (!url)
215
+ continue;
216
+ // A descriptor may point at a CDN. Do not instruct another server to fetch an
217
+ // arbitrary origin chosen by the descriptor; the configured primary serves
218
+ // the same blob via the standard raw-hash endpoint.
219
+ const source = `${server.replace(/\/+$/, "")}/${sha256}`;
220
+ const body = Buffer.from(JSON.stringify({ url: source }));
221
+ const targets = servers
222
+ .slice(index + 1)
223
+ .filter((target) => !loopbackHost(new URL(source).hostname) ||
224
+ loopbackHost(new URL(target).hostname));
225
+ await Promise.allSettled(targets.map((target) => putBlossom(signed, target, "mirror", body, {
226
+ "content-type": "application/json",
227
+ "x-content-type": mimeType,
228
+ "x-content-length": String(size),
229
+ }, sha256, size, downloadOrigins)));
230
+ return { url, sha256, size, mimeType };
231
+ }
232
+ throw new Error("No configured Blossom server accepted the file");
233
+ }
@@ -0,0 +1,70 @@
1
+ import type { ReplyFileOptions } from "./blossom.js";
2
+ import { type Input, type ThreadOptions, type ThreadResult } from "./public-thread.js";
3
+ import { type Session, type SessionStore } from "./session.js";
4
+ import type { Client, SendOptions } from "./client.js";
5
+ import { type BotCommandDefinition, type CommandArgs, type CommandDefinition, type CommandInvocation } from "./nipcd.js";
6
+ export interface Context<S = Record<string, unknown>> {
7
+ input: Input;
8
+ thread(options?: ThreadOptions): Promise<ThreadResult>;
9
+ sender: string;
10
+ conversation: string;
11
+ reply(text: string, options?: SendOptions): ReturnType<Client["send"]> | ReturnType<Client["replyPublic"]>;
12
+ /** Attach a file using the visibility of the triggering event. */
13
+ replyFile(data: Uint8Array, options?: ReplyFileOptions): ReturnType<Client["replyFile"]>;
14
+ /** React to the current input, keeping its visibility. */
15
+ react(reaction?: string): ReturnType<Client["react"]>;
16
+ session: Session<S>;
17
+ }
18
+ export interface CommandContext<A, S = Record<string, unknown>> extends Context<S> {
19
+ readonly args: A;
20
+ }
21
+ export type Next = () => Promise<void>;
22
+ export type Middleware<S = Record<string, unknown>> = (ctx: Context<S>, next: Next) => unknown | Promise<unknown>;
23
+ export type MessageHandler<S = Record<string, unknown>> = (ctx: Context<S>) => unknown;
24
+ export type CommandHandler<D extends BotCommandDefinition, S = Record<string, unknown>> = (ctx: CommandContext<CommandArgs<D>, S>, args: CommandArgs<D>) => unknown;
25
+ export interface BotCommandOptions<S = Record<string, unknown>, D extends BotCommandDefinition = BotCommandDefinition> {
26
+ /** Fallback public metadata; fields on the definition take precedence. */
27
+ title?: string;
28
+ description?: string;
29
+ authorize?: (ctx: Context<S>, invocation: CommandInvocation<CommandArgs<D>>) => boolean | Promise<boolean>;
30
+ }
31
+ export declare class BotHandlers<S = Record<string, unknown>> {
32
+ private readonly options;
33
+ private middleware;
34
+ private fallback?;
35
+ private definitions;
36
+ private errorHandler?;
37
+ private detach?;
38
+ private detachPublic?;
39
+ private validatorFailures;
40
+ private invalidArgs;
41
+ private argumentError;
42
+ private routing;
43
+ private disposed;
44
+ private boundClient?;
45
+ get client(): Client;
46
+ private releaseDefinitions;
47
+ private commandHandlers;
48
+ constructor(client?: Client, options?: {
49
+ sessionStore?: SessionStore<S>;
50
+ });
51
+ attach(client: Client): void;
52
+ private assertActive;
53
+ use(fn: Middleware<S>): this;
54
+ private register;
55
+ /** All definitions are public on configured write relays. Authorization stays separate. */
56
+ command<const D extends BotCommandDefinition>(command: D, fn: CommandHandler<NoInfer<D>, S>, options?: BotCommandOptions<S, NoInfer<D>>): this;
57
+ getCommandDefinitions(): CommandDefinition[];
58
+ /** Register the handler for messages with no matching command. */
59
+ handle(fn: MessageHandler<S>): () => void;
60
+ catch(fn: (error: unknown, ctx: Context<S>) => unknown | Promise<unknown>): this;
61
+ sessionStore(client: Client): SessionStore<S>;
62
+ private dispatchMessage;
63
+ private dispatchPublic;
64
+ private dispatch;
65
+ start(): Promise<void>;
66
+ stop(): Promise<void>;
67
+ /** Detach this Bot and queue catalog synchronization; in-flight handlers can finish. */
68
+ dispose(): void;
69
+ close(): Promise<void>;
70
+ }
@@ -0,0 +1,317 @@
1
+ import { z } from "zod";
2
+ import { markDeferredRequestFailure } from "./request-timing.js";
3
+ import { commandArguments } from "./command-schema.js";
4
+ import { InvalidArgsError } from "./errors.js";
5
+ import { inputOf, } from "./public-thread.js";
6
+ import { messageSession } from "./session.js";
7
+ import { parseCommandHead, matchesCommandScopes, parseCommand, validateCommandDefinition, } from "./nipcd.js";
8
+ const defaultCommandScopes = [
9
+ "kind:14",
10
+ "kind:1",
11
+ "kind:1111",
12
+ ];
13
+ export class BotHandlers {
14
+ options;
15
+ middleware = [];
16
+ fallback;
17
+ definitions = new Map();
18
+ errorHandler;
19
+ detach;
20
+ detachPublic;
21
+ validatorFailures = new WeakMap();
22
+ invalidArgs = new WeakMap();
23
+ argumentError(ctx, error) {
24
+ this.invalidArgs.set(ctx, error);
25
+ return error;
26
+ }
27
+ routing = new WeakMap();
28
+ disposed = false;
29
+ boundClient;
30
+ get client() {
31
+ if (!this.boundClient)
32
+ throw new Error("Bot handlers are not attached");
33
+ return this.boundClient;
34
+ }
35
+ releaseDefinitions = new Map();
36
+ commandHandlers = new Map();
37
+ constructor(client, options = {}) {
38
+ this.options = options;
39
+ if (client)
40
+ this.attach(client);
41
+ }
42
+ attach(client) {
43
+ this.boundClient = client;
44
+ client.manageCommands();
45
+ for (const definition of this.definitions.values()) {
46
+ this.releaseDefinitions.set(definition.id, client.registerCommandDefinition(definition));
47
+ }
48
+ this.detach = client.handle((message, admit, evidence) => this.dispatchMessage(client, message, admit, evidence), true);
49
+ this.detachPublic = client.handlePublic((input) => this.dispatchPublic(client, input));
50
+ }
51
+ assertActive() {
52
+ if (this.disposed) {
53
+ throw new Error("Bot is disposed");
54
+ }
55
+ }
56
+ use(fn) {
57
+ this.assertActive();
58
+ this.middleware.push(fn);
59
+ return this;
60
+ }
61
+ register(definition) {
62
+ if (this.definitions.has(definition.id))
63
+ throw new TypeError("Duplicate local command definition id");
64
+ if (this.boundClient)
65
+ this.releaseDefinitions.set(definition.id, this.client.registerCommandDefinition(definition));
66
+ this.definitions.set(definition.id, definition);
67
+ }
68
+ /** All definitions are public on configured write relays. Authorization stays separate. */
69
+ command(command, fn, options = {}) {
70
+ this.assertActive();
71
+ if ("publish" in options)
72
+ throw new TypeError("Commands are always public");
73
+ if ("id" in options ||
74
+ (typeof command === "object" && command !== null && "id" in command))
75
+ throw new TypeError("Custom command id is not supported; the command name determines its published identifier");
76
+ const { title, description, authorize } = options;
77
+ if (typeof command !== "object" || command === null)
78
+ throw new TypeError("Use a command definition object");
79
+ const schema = command.args ?? z.object({});
80
+ const definition = {
81
+ ...command,
82
+ scopes: command.scopes ?? defaultCommandScopes,
83
+ args: commandArguments(schema),
84
+ id: command.command,
85
+ title: command.title ?? title ?? command.command,
86
+ description: command.description ?? description ?? `Run /${command.command}.`,
87
+ };
88
+ const snapshot = validateCommandDefinition(definition);
89
+ const kinds = (snapshot.scopes ?? []).filter((scope) => scope.startsWith("kind:"));
90
+ if (!kinds.length ||
91
+ kinds.some((scope) => !defaultCommandScopes.includes(scope)) ||
92
+ new Set(kinds).size !== kinds.length)
93
+ throw new TypeError(`Commands require distinct supported kind scopes: ${defaultCommandScopes.join(", ")}`);
94
+ this.register(snapshot);
95
+ this.commandHandlers.set(snapshot.id, async (ctx, executor) => {
96
+ if (this.definitions.get(snapshot.id) !== snapshot ||
97
+ !this.releaseDefinitions.get(snapshot.id)?.active()) {
98
+ return false;
99
+ }
100
+ const routing = this.routing.get(ctx);
101
+ if (!routing)
102
+ throw new Error("Missing authenticated command context");
103
+ const head = parseCommandHead(routing.event.content, snapshot.command, executor);
104
+ if (head.status !== "matched" ||
105
+ !matchesCommandScopes(snapshot.scopes ?? [], routing.event, {
106
+ relay: routing.relay,
107
+ }))
108
+ return false;
109
+ const parsed = parseCommand(snapshot, routing.event, {
110
+ executor,
111
+ relay: routing.relay,
112
+ });
113
+ // An args-dependent authorization cannot authorize an error response for malformed input.
114
+ if (parsed.status !== "matched") {
115
+ if (authorize)
116
+ return true;
117
+ throw this.argumentError(ctx, new InvalidArgsError(snapshot.command, "decode"));
118
+ }
119
+ let validated;
120
+ try {
121
+ validated = await schema.safeParseAsync(parsed.invocation.args);
122
+ }
123
+ catch (error) {
124
+ if (!authorize)
125
+ throw error;
126
+ this.validatorFailures.set(ctx, { error });
127
+ markDeferredRequestFailure(ctx);
128
+ return true;
129
+ }
130
+ if (!validated.success) {
131
+ if (authorize)
132
+ return true;
133
+ const names = new Set((snapshot.args ?? []).map((argument) => argument.name));
134
+ const codes = new Set([
135
+ "invalid_type",
136
+ "too_small",
137
+ "too_big",
138
+ "invalid_format",
139
+ "invalid_value",
140
+ "custom",
141
+ "unrecognized_keys",
142
+ "invalid_union",
143
+ "not_multiple_of",
144
+ ]);
145
+ throw this.argumentError(ctx, new InvalidArgsError(snapshot.command, "validation", validated.error.issues.slice(0, 20).map((issue) => ({
146
+ code: codes.has(issue.code) ? issue.code : "custom",
147
+ path: typeof issue.path[0] === "string" && names.has(issue.path[0])
148
+ ? [issue.path[0]]
149
+ : [],
150
+ }))));
151
+ }
152
+ const args = validated.data;
153
+ const invocation = { ...parsed.invocation, args };
154
+ if (!authorize || (await authorize(ctx, invocation))) {
155
+ const descriptors = Object.getOwnPropertyDescriptors(ctx);
156
+ descriptors.args = {
157
+ value: args,
158
+ enumerable: true,
159
+ configurable: false,
160
+ writable: false,
161
+ };
162
+ const commandContext = Object.create(Object.getPrototypeOf(ctx), descriptors);
163
+ await fn(commandContext, args);
164
+ }
165
+ // A matched command owns the route even when its authorization denies execution.
166
+ return true;
167
+ });
168
+ return this;
169
+ }
170
+ getCommandDefinitions() {
171
+ return structuredClone([...this.definitions.values()].filter((definition) => !this.boundClient ||
172
+ this.releaseDefinitions.get(definition.id)?.active()));
173
+ }
174
+ /** Register the handler for messages with no matching command. */
175
+ handle(fn) {
176
+ this.assertActive();
177
+ if (this.fallback)
178
+ throw new Error("A message handler is already registered");
179
+ const fallback = (ctx) => fn(ctx);
180
+ this.fallback = fallback;
181
+ return () => {
182
+ if (this.fallback === fallback)
183
+ this.fallback = undefined;
184
+ };
185
+ }
186
+ catch(fn) {
187
+ this.errorHandler = fn;
188
+ return this;
189
+ }
190
+ sessionStore(client) {
191
+ return (this.options.sessionStore ?? {
192
+ get: (peer) => client.getSession(peer),
193
+ set: (peer, value) => client.setSession(peer, value),
194
+ });
195
+ }
196
+ async dispatchMessage(client, message, admit, evidence) {
197
+ if (this.disposed) {
198
+ return;
199
+ }
200
+ const anchor = structuredClone(message);
201
+ const { session, commit } = messageSession(this.sessionStore(client), message.conversation);
202
+ const ctx = {
203
+ session,
204
+ input: client.inputForMessage(message),
205
+ thread: (options) => client.threadPrivate(anchor, options),
206
+ sender: message.sender,
207
+ conversation: message.conversation,
208
+ reply: (text, options) => client.send(anchor.conversation, text, options, evidence),
209
+ replyFile: (data, options) => client.sendFile(anchor.conversation, data, { ...options, replyTo: anchor.id }, evidence),
210
+ react: (reaction) => client.reactToMessage(anchor, reaction, evidence),
211
+ };
212
+ return this.dispatch(client, ctx, commit, anchor.rumor, anchor.relay, admit);
213
+ }
214
+ async dispatchPublic(client, input) {
215
+ if (this.disposed)
216
+ return;
217
+ const anchor = structuredClone(input);
218
+ const store = this.options.sessionStore ?? {
219
+ get: (key) => client.getPublicSession(key),
220
+ set: (key, value) => client.setPublicSession(key, value),
221
+ };
222
+ const { session, commit } = messageSession(store, input.conversation);
223
+ const ctx = {
224
+ input: inputOf(input.event),
225
+ sender: input.event.pubkey,
226
+ conversation: input.conversation,
227
+ session,
228
+ reply: (text, options) => {
229
+ if (options && Object.keys(options).length)
230
+ return Promise.reject(new TypeError("DM send options are not valid for public replies"));
231
+ return client.replyPublic(anchor, text);
232
+ },
233
+ replyFile: (data, options) => client.replyPublicFile(anchor, data, options),
234
+ thread: (options) => client.threadPublic(anchor, options),
235
+ react: (reaction) => client.reactPublic(anchor, reaction),
236
+ };
237
+ return this.dispatch(client, ctx, commit, input.event, input.relay);
238
+ }
239
+ async dispatch(client, ctx, commit, event, relay, admit) {
240
+ this.routing.set(ctx, { event: structuredClone(event), relay });
241
+ const middleware = [...this.middleware];
242
+ const commands = [...this.commandHandlers.values()];
243
+ const fallback = this.fallback;
244
+ let last = -1;
245
+ const dispatch = async (i) => {
246
+ if (i <= last) {
247
+ throw new Error("next() called more than once");
248
+ }
249
+ last = i;
250
+ if (middleware[i]) {
251
+ await middleware[i](ctx, () => dispatch(i + 1));
252
+ }
253
+ else {
254
+ admit?.();
255
+ if (event.kind !== 15) {
256
+ for (const command of commands) {
257
+ if (await command(ctx, client.pubkey))
258
+ return;
259
+ }
260
+ }
261
+ await fallback?.(ctx);
262
+ }
263
+ };
264
+ try {
265
+ await dispatch(0);
266
+ if (!this.validatorFailures.has(ctx))
267
+ await commit();
268
+ }
269
+ catch (e) {
270
+ const failure = this.validatorFailures.get(ctx);
271
+ if (failure)
272
+ throw failure.error;
273
+ if (this.errorHandler) {
274
+ try {
275
+ await this.errorHandler(e, ctx);
276
+ }
277
+ catch {
278
+ // An observer failure must not replace the original error.
279
+ }
280
+ }
281
+ if (e instanceof InvalidArgsError && e === this.invalidArgs.get(ctx))
282
+ return; // Expected input errors are observed once and not reported as operations.
283
+ // Business errors reach the operational observer; the input ID stays claimed.
284
+ throw e;
285
+ }
286
+ // Exit the reply-capable middleware/catch chain before reporting an unapproved validator exception.
287
+ const failure = this.validatorFailures.get(ctx);
288
+ if (failure)
289
+ throw failure.error;
290
+ }
291
+ start() {
292
+ this.assertActive();
293
+ return this.client.start();
294
+ }
295
+ stop() {
296
+ return this.client.stop();
297
+ }
298
+ /** Detach this Bot and queue catalog synchronization; in-flight handlers can finish. */
299
+ dispose() {
300
+ if (this.disposed) {
301
+ return;
302
+ }
303
+ this.disposed = true;
304
+ this.detach?.();
305
+ this.detachPublic?.();
306
+ this.fallback = undefined;
307
+ for (const release of this.releaseDefinitions.values()) {
308
+ release();
309
+ }
310
+ this.releaseDefinitions.clear();
311
+ this.definitions.clear();
312
+ this.commandHandlers.clear();
313
+ }
314
+ async close() {
315
+ this.dispose();
316
+ }
317
+ }
package/dist/bot.d.ts ADDED
@@ -0,0 +1,63 @@
1
+ import type { ReplyFileOptions, SendFileOptions, UploadFileOptions } from "./blossom.js";
2
+ import type { SessionStore } from "./session.js";
3
+ import { type ClientOptions, type ErrorHandler, type IntakeMetadata, type SendOptions, type MessageObserver } from "./client.js";
4
+ import { type Middleware } from "./bot-handlers.js";
5
+ import type { AnnounceOptions } from "./keys.js";
6
+ import type { BotCommandOptions, CommandHandler, Context, MessageHandler } from "./bot-handlers.js";
7
+ import type { BotCommandDefinition, DiscoverCommandsOptions } from "./nipcd.js";
8
+ import type { Event } from "nostr-tools";
9
+ import type { Rumor } from "./protocol.js";
10
+ import type { ThreadOptions } from "./public-thread.js";
11
+ import type { Message, MessageListOptions } from "./store.js";
12
+ export type { CommandContext, BotCommandOptions, CommandHandler, Context, MessageHandler, Middleware, Next, } from "./bot-handlers.js";
13
+ export type { Session, SessionStore } from "./session.js";
14
+ export type BotOptions<S = Record<string, unknown>> = ClientOptions & {
15
+ sessionStore?: SessionStore<S>;
16
+ };
17
+ export declare class Bot<S = Record<string, unknown>> {
18
+ #private;
19
+ constructor(input: BotOptions<S>);
20
+ get pubkey(): string;
21
+ get mode(): import("./modes.js").ProtocolMode;
22
+ use(fn: Middleware<S>): this;
23
+ catch(fn: (error: unknown, ctx: Context<S>) => unknown): this;
24
+ command<const D extends BotCommandDefinition>(command: D, fn: CommandHandler<NoInfer<D>, S>, options?: BotCommandOptions<S, NoInfer<D>>): this;
25
+ getCommandDefinitions(): import("./nipcd.js").CommandDefinition[];
26
+ handle(handler: MessageHandler<S>): () => void;
27
+ observe(observer: MessageObserver): () => void;
28
+ onError(handler: ErrorHandler): () => void;
29
+ start(): Promise<void>;
30
+ stop(): Promise<void>;
31
+ close(): Promise<void>;
32
+ requestStop(): void;
33
+ announce(options?: AnnounceOptions): Promise<void>;
34
+ reply(event: Event | Rumor, text: string, options?: SendOptions): Promise<import("./client.js").SendResult>;
35
+ replyFile(event: Event | Rumor, data: Uint8Array, options?: ReplyFileOptions): Promise<import("./client.js").SendResult>;
36
+ thread(event: Event | Rumor, options?: ThreadOptions): Promise<import("./public-thread.js").ThreadResult>;
37
+ send(peer: string, text: string, options?: SendOptions): Promise<import("./client.js").SendResult>;
38
+ uploadFile(data: Uint8Array, options?: UploadFileOptions): Promise<import("./blossom.js").UploadFileResult>;
39
+ sendFile(peer: string, data: Uint8Array, options?: SendFileOptions): Promise<import("./client.js").SendResult>;
40
+ dmHistory(peerPubkey: string, options?: {
41
+ limit?: number;
42
+ cursor?: string;
43
+ }): import("./store.js").HistoryPage;
44
+ react(event: Event | Rumor, reaction?: string): Promise<import("./client.js").SendResult>;
45
+ getMessage(id: string): Message | undefined;
46
+ idle(): Promise<void>;
47
+ receive(event: Event, source: "live" | "history", metadata?: IntakeMetadata): Promise<boolean>;
48
+ getMessageState(id: string): import("./storage.js").MessageState | undefined;
49
+ listMessages(options?: MessageListOptions): import("./store.js").MessageList;
50
+ getSession(peer: string): Promise<Partial<S> | undefined>;
51
+ setSession(peer: string, value: Partial<S>): Promise<void>;
52
+ syncHistory(): Promise<import("./inbox.js").HistorySyncResult[]>;
53
+ syncCommands(): Promise<import("./commands.js").CommandSyncResult>;
54
+ discoverCommands(options: DiscoverCommandsOptions): Promise<import("./nipcd.js").CommandDiscoveryResult>;
55
+ flushAnnouncements(): Promise<void>;
56
+ flushOutbox(): Promise<void>;
57
+ encryptionKeys(): import("./keys.js").EncryptionKeyStatus;
58
+ rotateEncryptionKey(): Promise<import("./keys.js").EncryptionKeyStatus>;
59
+ refreshPeer(peer: string): Promise<{
60
+ encryptionPubkey: string;
61
+ relays: string[];
62
+ }>;
63
+ }