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.
- package/ARCHITECTURE.md +103 -0
- package/CONTRIBUTING.md +56 -0
- package/LICENSE +22 -0
- package/README.md +281 -2
- package/SECURITY.md +55 -0
- package/THIRD_PARTY_NOTICES.md +51 -0
- package/dist/allowlist.d.ts +3 -0
- package/dist/allowlist.js +9 -0
- package/dist/announcements.d.ts +25 -0
- package/dist/announcements.js +142 -0
- package/dist/attachments.d.ts +43 -0
- package/dist/attachments.js +340 -0
- package/dist/blossom.d.ts +30 -0
- package/dist/blossom.js +233 -0
- package/dist/bot-handlers.d.ts +70 -0
- package/dist/bot-handlers.js +317 -0
- package/dist/bot.d.ts +63 -0
- package/dist/bot.js +244 -0
- package/dist/client.d.ts +221 -0
- package/dist/client.js +1197 -0
- package/dist/command-discovery.d.ts +4 -0
- package/dist/command-discovery.js +33 -0
- package/dist/command-schema.d.ts +4 -0
- package/dist/command-schema.js +101 -0
- package/dist/commands.d.ts +32 -0
- package/dist/commands.js +253 -0
- package/dist/defaults.d.ts +9 -0
- package/dist/defaults.js +22 -0
- package/dist/errors.d.ts +55 -0
- package/dist/errors.js +126 -0
- package/dist/inbox.d.ts +55 -0
- package/dist/inbox.js +376 -0
- package/dist/index.d.ts +25 -0
- package/dist/index.js +11 -0
- package/dist/key-sync.d.ts +33 -0
- package/dist/key-sync.js +293 -0
- package/dist/keys.d.ts +66 -0
- package/dist/keys.js +418 -0
- package/dist/message-storage-sqlite.d.ts +6 -0
- package/dist/message-storage-sqlite.js +90 -0
- package/dist/message-storage.d.ts +32 -0
- package/dist/message-storage.js +1 -0
- package/dist/messaging-metadata.d.ts +48 -0
- package/dist/messaging-metadata.js +280 -0
- package/dist/metadata.d.ts +7 -0
- package/dist/metadata.js +63 -0
- package/dist/modes.d.ts +26 -0
- package/dist/modes.js +108 -0
- package/dist/nip4e-compat.d.ts +4 -0
- package/dist/nip4e-compat.js +14 -0
- package/dist/nipcd.d.ts +109 -0
- package/dist/nipcd.js +555 -0
- package/dist/protocol.d.ts +68 -0
- package/dist/protocol.js +302 -0
- package/dist/public-inbox.d.ts +66 -0
- package/dist/public-inbox.js +295 -0
- package/dist/public-thread.d.ts +62 -0
- package/dist/public-thread.js +436 -0
- package/dist/relay-pool.d.ts +43 -0
- package/dist/relay-pool.js +429 -0
- package/dist/relay-roles.d.ts +18 -0
- package/dist/relay-roles.js +55 -0
- package/dist/relay.d.ts +52 -0
- package/dist/relay.js +493 -0
- package/dist/request-timing.d.ts +12 -0
- package/dist/request-timing.js +37 -0
- package/dist/session.d.ts +16 -0
- package/dist/session.js +51 -0
- package/dist/signer.d.ts +13 -0
- package/dist/signer.js +1 -0
- package/dist/signers/bunker-relays.d.ts +15 -0
- package/dist/signers/bunker-relays.js +87 -0
- package/dist/signers/bunker.d.ts +7 -0
- package/dist/signers/bunker.js +194 -0
- package/dist/signers/nsec.d.ts +3 -0
- package/dist/signers/nsec.js +62 -0
- package/dist/signers.d.ts +18 -0
- package/dist/signers.js +59 -0
- package/dist/storage-sqlite.d.ts +29 -0
- package/dist/storage-sqlite.js +221 -0
- package/dist/storage.d.ts +85 -0
- package/dist/storage.js +1 -0
- package/dist/store.d.ts +96 -0
- package/dist/store.js +404 -0
- package/docs/ACCESS.md +28 -0
- package/docs/API.md +382 -0
- package/docs/INTEROPERABILITY.md +32 -0
- package/docs/KEYS.md +75 -0
- package/docs/NIP-CD.md +112 -0
- package/docs/PUBLIC.md +88 -0
- package/docs/RECOVERY.md +59 -0
- package/docs/RELAYS.md +145 -0
- package/docs/SESSIONS.md +108 -0
- package/docs/SIGNERS.md +59 -0
- package/docs/STORAGE.md +71 -0
- package/docs/TUTORIAL.md +178 -0
- package/package.json +47 -4
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { Transport } from "./relay.js";
|
|
2
|
+
import { type DiscoverCommandsOptions } from "./nipcd.js";
|
|
3
|
+
/** Read-only discovery never changes registrations or publishes account metadata. */
|
|
4
|
+
export declare function discoverCommandCatalog(transport: Transport, options: DiscoverCommandsOptions): Promise<import("./nipcd.js").CommandDiscoveryResult>;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { hexKey } from "./protocol.js";
|
|
2
|
+
import { commandRelayURL, selectCommandDefinitions, } from "./nipcd.js";
|
|
3
|
+
function discoveryRelays(relays) {
|
|
4
|
+
if (!Array.isArray(relays) || !relays.length) {
|
|
5
|
+
throw new TypeError("Explicit command metadata relays are required");
|
|
6
|
+
}
|
|
7
|
+
return [...new Set(relays.map(commandRelayURL))];
|
|
8
|
+
}
|
|
9
|
+
/** Read-only discovery never changes registrations or publishes account metadata. */
|
|
10
|
+
export async function discoverCommandCatalog(transport, options) {
|
|
11
|
+
if (!options.authors?.length ||
|
|
12
|
+
!options.authors.every(hexKey) ||
|
|
13
|
+
(options.ids !== undefined &&
|
|
14
|
+
(!options.ids.length ||
|
|
15
|
+
!options.ids.every((id) => typeof id === "string")))) {
|
|
16
|
+
throw new TypeError("Explicit valid command authors/IDs are required");
|
|
17
|
+
}
|
|
18
|
+
const limit = options.limit ?? 200;
|
|
19
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1000) {
|
|
20
|
+
throw new TypeError("Command discovery limit must be in 1..1000");
|
|
21
|
+
}
|
|
22
|
+
const relays = discoveryRelays(options.relays), authors = [...new Set(options.authors)];
|
|
23
|
+
const [definitions, deletions] = await Promise.all([
|
|
24
|
+
transport.query(relays, {
|
|
25
|
+
kinds: [31992],
|
|
26
|
+
authors,
|
|
27
|
+
...(options.ids ? { "#d": options.ids } : {}),
|
|
28
|
+
limit,
|
|
29
|
+
}),
|
|
30
|
+
transport.query(relays, { kinds: [5], authors, limit }),
|
|
31
|
+
]);
|
|
32
|
+
return selectCommandDefinitions([...definitions, ...deletions], authors, options.ids);
|
|
33
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
/** Positional NIP-CD schemas deliberately accept a small, predictable Zod subset. */
|
|
3
|
+
export function commandArguments(schema) {
|
|
4
|
+
const fail = (name, reason) => {
|
|
5
|
+
throw new TypeError(`Unsupported command args schema at ${name}: ${reason}`);
|
|
6
|
+
};
|
|
7
|
+
const check = (field, name) => {
|
|
8
|
+
const def = field._zod.def;
|
|
9
|
+
if (def.coerce ||
|
|
10
|
+
def.checks?.some((item) => item._zod.def.check === "overwrite"))
|
|
11
|
+
fail(name, "coercions and overwrites/transforms are not supported");
|
|
12
|
+
};
|
|
13
|
+
if (!(schema instanceof z.ZodObject))
|
|
14
|
+
fail("args", "expected a Zod 4 z.object");
|
|
15
|
+
check(schema, "args");
|
|
16
|
+
const catchall = schema._zod.def.catchall;
|
|
17
|
+
if (catchall && catchall._zod.def.type !== "never")
|
|
18
|
+
fail("args", "catchall/loose objects cannot declare positional arguments");
|
|
19
|
+
return Object.entries(schema.shape).map(([name, outer]) => {
|
|
20
|
+
if (name === "__proto__")
|
|
21
|
+
fail(name, "reserved top-level argument name");
|
|
22
|
+
let field = outer, required = true;
|
|
23
|
+
check(field, name);
|
|
24
|
+
const meta = field.meta() ?? {};
|
|
25
|
+
if (field instanceof z.ZodOptional) {
|
|
26
|
+
required = false;
|
|
27
|
+
field = field.unwrap();
|
|
28
|
+
}
|
|
29
|
+
const metadata = { ...field.meta(), ...meta };
|
|
30
|
+
check(field, name);
|
|
31
|
+
const type = field._zod.def.type;
|
|
32
|
+
const inferred = type === "string"
|
|
33
|
+
? "word"
|
|
34
|
+
: type === "bigint"
|
|
35
|
+
? "number"
|
|
36
|
+
: type === "boolean"
|
|
37
|
+
? "bool"
|
|
38
|
+
: type === "enum"
|
|
39
|
+
? "enum"
|
|
40
|
+
: undefined;
|
|
41
|
+
const explicit = metadata.nipcdType;
|
|
42
|
+
if (explicit !== undefined &&
|
|
43
|
+
![
|
|
44
|
+
"word",
|
|
45
|
+
"text",
|
|
46
|
+
"pubkey",
|
|
47
|
+
"event",
|
|
48
|
+
"relay",
|
|
49
|
+
"address",
|
|
50
|
+
"number",
|
|
51
|
+
"bool",
|
|
52
|
+
"enum",
|
|
53
|
+
].includes(explicit))
|
|
54
|
+
fail(name, "unknown nipcdType metadata");
|
|
55
|
+
const wire = (explicit ?? inferred);
|
|
56
|
+
if (wire === "address") {
|
|
57
|
+
if (!(field instanceof z.ZodObject))
|
|
58
|
+
fail(name, "address requires an object matching CommandAddress");
|
|
59
|
+
const shape = field.shape;
|
|
60
|
+
if (Object.keys(shape).sort().join(",") !== "identifier,kind,pubkey,relays")
|
|
61
|
+
fail(name, "address needs kind, pubkey, identifier and relays");
|
|
62
|
+
for (const [key, child] of Object.entries(shape)) {
|
|
63
|
+
const value = child;
|
|
64
|
+
check(value, `${name}.${key}`);
|
|
65
|
+
const expected = key === "kind" ? "number" : key === "relays" ? "array" : "string";
|
|
66
|
+
if (value._zod.def.type !== expected)
|
|
67
|
+
fail(name, `invalid address ${key} schema`);
|
|
68
|
+
if (key === "relays") {
|
|
69
|
+
const element = value.element;
|
|
70
|
+
check(element, `${name}.relays`);
|
|
71
|
+
if (element._zod.def.type !== "string")
|
|
72
|
+
fail(name, "address relays must be strings");
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
check(field, name);
|
|
76
|
+
if (field._zod.def.catchall &&
|
|
77
|
+
field._zod.def.catchall?._zod.def.type !== "never")
|
|
78
|
+
fail(name, "address catchall is unsupported");
|
|
79
|
+
}
|
|
80
|
+
else if (!inferred ||
|
|
81
|
+
!(wire === inferred ||
|
|
82
|
+
(inferred === "word" &&
|
|
83
|
+
["text", "pubkey", "event", "relay"].includes(wire))))
|
|
84
|
+
fail(name, "use string, bigint, boolean, string enum, optional(), or an explicitly annotated address object");
|
|
85
|
+
if (metadata.label !== undefined && typeof metadata.label !== "string")
|
|
86
|
+
fail(name, "label metadata must be a string");
|
|
87
|
+
const argument = {
|
|
88
|
+
name,
|
|
89
|
+
type: wire,
|
|
90
|
+
required,
|
|
91
|
+
label: metadata.label ?? name,
|
|
92
|
+
};
|
|
93
|
+
if (wire === "enum") {
|
|
94
|
+
const choices = Object.values(field._zod.def.entries);
|
|
95
|
+
if (!choices.every((value) => typeof value === "string"))
|
|
96
|
+
fail(name, "only string enum choices are supported");
|
|
97
|
+
argument.choices = choices;
|
|
98
|
+
}
|
|
99
|
+
return argument;
|
|
100
|
+
});
|
|
101
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type Event } from "nostr-tools";
|
|
2
|
+
import { type Identity } from "./protocol.js";
|
|
3
|
+
import { type CommandDefinition } from "./nipcd.js";
|
|
4
|
+
import type { Store } from "./store.js";
|
|
5
|
+
import type { Transport } from "./relay.js";
|
|
6
|
+
export interface CommandSyncResult {
|
|
7
|
+
added: string[];
|
|
8
|
+
updated: string[];
|
|
9
|
+
removed: string[];
|
|
10
|
+
}
|
|
11
|
+
/** Reconciles one account's authoritative command registry on its configured write relays. */
|
|
12
|
+
export declare class CommandCatalog {
|
|
13
|
+
private identity;
|
|
14
|
+
private store;
|
|
15
|
+
private transport;
|
|
16
|
+
private relays;
|
|
17
|
+
private state;
|
|
18
|
+
private operation?;
|
|
19
|
+
constructor(identity: Identity, store: Store, transport: Transport, relays: string[]);
|
|
20
|
+
private verified;
|
|
21
|
+
private save;
|
|
22
|
+
private check;
|
|
23
|
+
private readKind;
|
|
24
|
+
private compact;
|
|
25
|
+
private deleted;
|
|
26
|
+
sync(definitions: CommandDefinition[], removals?: string[], active?: () => boolean): Promise<CommandSyncResult>;
|
|
27
|
+
private reconcile;
|
|
28
|
+
definition(id: string): Event | undefined;
|
|
29
|
+
revocation(id: string): Event | undefined;
|
|
30
|
+
hasPending(): boolean;
|
|
31
|
+
idle(): Promise<void>;
|
|
32
|
+
}
|
package/dist/commands.js
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
import { verifyEvent } from "nostr-tools";
|
|
2
|
+
import { signChecked, validTimestamp } from "./protocol.js";
|
|
3
|
+
import { commandAddress, decodeCommandDefinition, encodeCommandDefinition, encodeCommandRevocation, validateCommandDefinition, } from "./nipcd.js";
|
|
4
|
+
const PAGE_SIZE = 1000;
|
|
5
|
+
const MAX_PAGES = 100;
|
|
6
|
+
const identifier = (event) => event.tags.find((tag) => tag[0] === "d")?.[1] ?? "";
|
|
7
|
+
const newer = (a, b) => a.created_at > b.created_at || (a.created_at === b.created_at && a.id < b.id);
|
|
8
|
+
const equal = (a, b) => JSON.stringify(validateCommandDefinition(a)) ===
|
|
9
|
+
JSON.stringify(validateCommandDefinition(b));
|
|
10
|
+
/** Reconciles one account's authoritative command registry on its configured write relays. */
|
|
11
|
+
export class CommandCatalog {
|
|
12
|
+
identity;
|
|
13
|
+
store;
|
|
14
|
+
transport;
|
|
15
|
+
relays;
|
|
16
|
+
state;
|
|
17
|
+
operation;
|
|
18
|
+
constructor(identity, store, transport, relays) {
|
|
19
|
+
this.identity = identity;
|
|
20
|
+
this.store = store;
|
|
21
|
+
this.transport = transport;
|
|
22
|
+
this.relays = relays;
|
|
23
|
+
this.state = store.metadata("command-catalog") ?? {
|
|
24
|
+
version: 1,
|
|
25
|
+
known: [],
|
|
26
|
+
pending: [],
|
|
27
|
+
};
|
|
28
|
+
if (this.state.version !== 1 ||
|
|
29
|
+
!Array.isArray(this.state.known) ||
|
|
30
|
+
!Array.isArray(this.state.pending)) {
|
|
31
|
+
throw new Error("Unsupported command catalog state");
|
|
32
|
+
}
|
|
33
|
+
// Old journals may contain unrelated event kinds. Retain only supported command operations.
|
|
34
|
+
const supported = (events) => events.flatMap((event) => {
|
|
35
|
+
const valid = event && (event.kind === 31992 || event.kind === 5)
|
|
36
|
+
? this.verified(event, event.kind)
|
|
37
|
+
: undefined;
|
|
38
|
+
return valid ? [valid] : [];
|
|
39
|
+
});
|
|
40
|
+
const known = supported(this.state.known), pending = supported(this.state.pending);
|
|
41
|
+
if (known.length !== this.state.known.length ||
|
|
42
|
+
pending.length !== this.state.pending.length) {
|
|
43
|
+
this.save({ version: 1, known, pending });
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
verified(input, kind) {
|
|
47
|
+
try {
|
|
48
|
+
const event = JSON.parse(JSON.stringify(input));
|
|
49
|
+
if (event.kind === kind &&
|
|
50
|
+
event.pubkey === this.identity.pubkey &&
|
|
51
|
+
validTimestamp(event.created_at) &&
|
|
52
|
+
verifyEvent(event))
|
|
53
|
+
return event;
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
/* Untrusted frames never become registry or deletion evidence. */
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
save(state) {
|
|
60
|
+
this.store.saveMetadata("command-catalog", state);
|
|
61
|
+
this.state = state;
|
|
62
|
+
}
|
|
63
|
+
check(active) {
|
|
64
|
+
if (!active())
|
|
65
|
+
throw new Error("Command synchronization canceled");
|
|
66
|
+
}
|
|
67
|
+
async readKind(relay, kind, active) {
|
|
68
|
+
const events = new Map();
|
|
69
|
+
let until;
|
|
70
|
+
for (let page = 0; page < MAX_PAGES; page++) {
|
|
71
|
+
this.check(active);
|
|
72
|
+
const frames = await this.transport.query([relay], {
|
|
73
|
+
kinds: [kind],
|
|
74
|
+
authors: [this.identity.pubkey],
|
|
75
|
+
limit: PAGE_SIZE,
|
|
76
|
+
...(until === undefined ? {} : { until }),
|
|
77
|
+
});
|
|
78
|
+
this.check(active);
|
|
79
|
+
const valid = frames.flatMap((frame) => {
|
|
80
|
+
const event = this.verified(frame, kind);
|
|
81
|
+
return event && (until === undefined || event.created_at <= until)
|
|
82
|
+
? [event]
|
|
83
|
+
: [];
|
|
84
|
+
});
|
|
85
|
+
for (const event of valid)
|
|
86
|
+
events.set(event.id, event);
|
|
87
|
+
if (frames.length < PAGE_SIZE)
|
|
88
|
+
return [...events.values()];
|
|
89
|
+
const oldest = Math.min(...valid.map((event) => event.created_at));
|
|
90
|
+
// Never infer deletions from a truncated or saturated timestamp bucket.
|
|
91
|
+
if (!Number.isFinite(oldest) || oldest === until)
|
|
92
|
+
throw new Error("Command query incomplete: timestamp boundary saturated");
|
|
93
|
+
until = oldest;
|
|
94
|
+
}
|
|
95
|
+
throw new Error("Command query incomplete: page limit reached");
|
|
96
|
+
}
|
|
97
|
+
compact(events) {
|
|
98
|
+
const slots = new Map();
|
|
99
|
+
for (const event of events) {
|
|
100
|
+
const keys = event.kind === 31992
|
|
101
|
+
? [`definition:${identifier(event)}`]
|
|
102
|
+
: event.kind === 5
|
|
103
|
+
? event.tags
|
|
104
|
+
.filter((tag) => tag[0] === "a" || tag[0] === "e")
|
|
105
|
+
.map((tag) => `${tag[0]}:${tag[1]}`)
|
|
106
|
+
: [];
|
|
107
|
+
for (const key of keys) {
|
|
108
|
+
const old = slots.get(key);
|
|
109
|
+
if (!old || newer(event, old))
|
|
110
|
+
slots.set(key, event);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return [
|
|
114
|
+
...new Map([...slots.values()].map((event) => [event.id, event])).values(),
|
|
115
|
+
];
|
|
116
|
+
}
|
|
117
|
+
deleted(event, events) {
|
|
118
|
+
const address = commandAddress(this.identity.pubkey, identifier(event));
|
|
119
|
+
return events.some((deletion) => deletion.kind === 5 &&
|
|
120
|
+
deletion.tags.some((tag) => (tag[0] === "a" &&
|
|
121
|
+
tag[1] === address &&
|
|
122
|
+
deletion.created_at >= event.created_at) ||
|
|
123
|
+
(tag[0] === "e" && tag[1] === event.id)));
|
|
124
|
+
}
|
|
125
|
+
sync(definitions, removals = [], active = () => true) {
|
|
126
|
+
const desired = definitions.map(validateCommandDefinition);
|
|
127
|
+
const task = (this.operation ?? Promise.resolve())
|
|
128
|
+
.catch(() => { })
|
|
129
|
+
.then(() => this.reconcile(desired, removals, active));
|
|
130
|
+
this.operation = task;
|
|
131
|
+
void task
|
|
132
|
+
.finally(() => {
|
|
133
|
+
if (this.operation === task)
|
|
134
|
+
this.operation = undefined;
|
|
135
|
+
})
|
|
136
|
+
.catch(() => { });
|
|
137
|
+
return task;
|
|
138
|
+
}
|
|
139
|
+
async reconcile(definitions, removals, active) {
|
|
140
|
+
// Query every write relay independently. Partial transport query success is unsafe here.
|
|
141
|
+
const reads = await Promise.all(this.relays.map((relay) => this.readKind(relay, 31992, active)));
|
|
142
|
+
this.check(active);
|
|
143
|
+
const events = [
|
|
144
|
+
...new Map([...reads.flat(), ...this.state.known, ...this.state.pending].map((event) => [event.id, event])).values(),
|
|
145
|
+
];
|
|
146
|
+
const desired = new Map(definitions.map((definition) => [definition.id, definition]));
|
|
147
|
+
const latest = new Map();
|
|
148
|
+
// Fresh relay presence and unacknowledged definitions are actionable; confirmed cache alone is not.
|
|
149
|
+
for (const event of [...reads.flat(), ...this.state.pending]) {
|
|
150
|
+
if (event.kind !== 31992)
|
|
151
|
+
continue;
|
|
152
|
+
const id = identifier(event), old = latest.get(id);
|
|
153
|
+
if (!old || newer(event, old))
|
|
154
|
+
latest.set(id, event);
|
|
155
|
+
}
|
|
156
|
+
const pending = [], known = new Map(events.map((event) => [event.id, event]));
|
|
157
|
+
const result = {
|
|
158
|
+
added: [],
|
|
159
|
+
updated: [],
|
|
160
|
+
removed: [],
|
|
161
|
+
};
|
|
162
|
+
const now = Math.floor(Date.now() / 1000);
|
|
163
|
+
const onEveryRelay = (event) => reads.every((read) => read.some((copy) => copy.id === event.id));
|
|
164
|
+
const enqueue = (event) => {
|
|
165
|
+
known.set(event.id, event);
|
|
166
|
+
if (!onEveryRelay(event))
|
|
167
|
+
pending.push(event);
|
|
168
|
+
};
|
|
169
|
+
const timeFor = (id) => {
|
|
170
|
+
const address = commandAddress(this.identity.pubkey, id);
|
|
171
|
+
return Math.max(now, ...events
|
|
172
|
+
.filter((event) => (event.kind === 31992 && identifier(event) === id) ||
|
|
173
|
+
(event.kind === 5 &&
|
|
174
|
+
event.tags.some((tag) => tag[0] === "a" && tag[1] === address)))
|
|
175
|
+
.map((event) => event.created_at + 1));
|
|
176
|
+
};
|
|
177
|
+
for (const [id, definition] of desired) {
|
|
178
|
+
this.check(active);
|
|
179
|
+
const previous = latest.get(id), parsed = previous && !this.deleted(previous, events)
|
|
180
|
+
? decodeCommandDefinition(previous)
|
|
181
|
+
: undefined;
|
|
182
|
+
if (previous && parsed && equal(parsed.definition, definition)) {
|
|
183
|
+
enqueue(previous);
|
|
184
|
+
}
|
|
185
|
+
else {
|
|
186
|
+
const event = await signChecked(this.identity, encodeCommandDefinition(definition, timeFor(id)));
|
|
187
|
+
enqueue(event);
|
|
188
|
+
(previous ? result.updated : result.added).push(id);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
const prefix = `31992:${this.identity.pubkey}:`;
|
|
192
|
+
const withdrawn = this.state.pending.flatMap((event) => event.kind === 5
|
|
193
|
+
? event.tags.flatMap((tag) => tag[0] === "a" && tag[1]?.startsWith(prefix)
|
|
194
|
+
? [tag[1].slice(prefix.length)]
|
|
195
|
+
: [])
|
|
196
|
+
: []);
|
|
197
|
+
for (const id of new Set([...latest.keys(), ...withdrawn, ...removals])) {
|
|
198
|
+
if (desired.has(id))
|
|
199
|
+
continue;
|
|
200
|
+
const previous = latest.get(id);
|
|
201
|
+
const address = commandAddress(this.identity.pubkey, id);
|
|
202
|
+
const deletion = events
|
|
203
|
+
.filter((event) => event.kind === 5 &&
|
|
204
|
+
event.tags.some((tag) => tag[0] === "a" && tag[1] === address))
|
|
205
|
+
.sort((a, b) => b.created_at - a.created_at || a.id.localeCompare(b.id))[0];
|
|
206
|
+
if (deletion &&
|
|
207
|
+
(!previous || deletion.created_at >= previous.created_at)) {
|
|
208
|
+
// A tombstone staged before a crash is not proof every relay received it.
|
|
209
|
+
if (!onEveryRelay(deletion))
|
|
210
|
+
result.removed.push(id);
|
|
211
|
+
enqueue(deletion);
|
|
212
|
+
}
|
|
213
|
+
else {
|
|
214
|
+
enqueue(await signChecked(this.identity, encodeCommandRevocation(this.identity.pubkey, id, timeFor(id))));
|
|
215
|
+
result.removed.push(id);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
this.check(active);
|
|
219
|
+
this.save({
|
|
220
|
+
version: 1,
|
|
221
|
+
known: this.compact([...known.values()]),
|
|
222
|
+
pending,
|
|
223
|
+
});
|
|
224
|
+
while (this.state.pending.length) {
|
|
225
|
+
this.check(active);
|
|
226
|
+
const event = this.state.pending[0];
|
|
227
|
+
const outcomes = await Promise.allSettled(this.relays.map((relay) => this.transport.publish([relay], event)));
|
|
228
|
+
const failures = outcomes.flatMap((outcome) => outcome.status === "rejected" ? [outcome.reason] : []);
|
|
229
|
+
if (failures.length)
|
|
230
|
+
throw new AggregateError(failures, "Command publication failed on write relays");
|
|
231
|
+
this.save({ ...this.state, pending: this.state.pending.slice(1) });
|
|
232
|
+
}
|
|
233
|
+
return result;
|
|
234
|
+
}
|
|
235
|
+
definition(id) {
|
|
236
|
+
return this.state.known
|
|
237
|
+
.filter((event) => event.kind === 31992 && identifier(event) === id)
|
|
238
|
+
.sort((a, b) => b.created_at - a.created_at || a.id.localeCompare(b.id))[0];
|
|
239
|
+
}
|
|
240
|
+
revocation(id) {
|
|
241
|
+
const address = commandAddress(this.identity.pubkey, id);
|
|
242
|
+
return this.state.known
|
|
243
|
+
.filter((event) => event.kind === 5 &&
|
|
244
|
+
event.tags.some((tag) => tag[0] === "a" && tag[1] === address))
|
|
245
|
+
.sort((a, b) => b.created_at - a.created_at || a.id.localeCompare(b.id))[0];
|
|
246
|
+
}
|
|
247
|
+
hasPending() {
|
|
248
|
+
return this.state.pending.length > 0;
|
|
249
|
+
}
|
|
250
|
+
async idle() {
|
|
251
|
+
await this.operation?.catch(() => { });
|
|
252
|
+
}
|
|
253
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** PsstPsst-derived DM defaults; nip17.com intentionally excluded. Availability is not guaranteed. */
|
|
2
|
+
export declare const DEFAULT_DM_RELAYS: readonly string[];
|
|
3
|
+
/** PsstPsst's loadAccountReadRelays/loadAccountWriteRelays fall back to DISCOVERY_RELAYS. */
|
|
4
|
+
export declare const DEFAULT_READ_RELAYS: readonly string[];
|
|
5
|
+
export declare const DEFAULT_WRITE_RELAYS: readonly string[];
|
|
6
|
+
/** Default Blossom server for encrypted attachment uploads. */
|
|
7
|
+
export declare const DEFAULT_BLOSSOM_SERVERS: readonly string[];
|
|
8
|
+
/** Large relays used to help clients discover public account metadata. */
|
|
9
|
+
export declare const DEFAULT_DISCOVERY_RELAYS: readonly string[];
|
package/dist/defaults.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** PsstPsst-derived DM defaults; nip17.com intentionally excluded. Availability is not guaranteed. */
|
|
2
|
+
export const DEFAULT_DM_RELAYS = Object.freeze([
|
|
3
|
+
"wss://relay.psstpsst.chat/",
|
|
4
|
+
"wss://nos.lol/",
|
|
5
|
+
"wss://relay.ditto.pub/",
|
|
6
|
+
]);
|
|
7
|
+
/** PsstPsst's loadAccountReadRelays/loadAccountWriteRelays fall back to DISCOVERY_RELAYS. */
|
|
8
|
+
export const DEFAULT_READ_RELAYS = Object.freeze([
|
|
9
|
+
"wss://nos.lol/",
|
|
10
|
+
"wss://relay.primal.net/",
|
|
11
|
+
"wss://relay.ditto.pub/",
|
|
12
|
+
"wss://offchain.pub/",
|
|
13
|
+
]);
|
|
14
|
+
export const DEFAULT_WRITE_RELAYS = Object.freeze([
|
|
15
|
+
...DEFAULT_READ_RELAYS,
|
|
16
|
+
]);
|
|
17
|
+
/** Default Blossom server for encrypted attachment uploads. */
|
|
18
|
+
export const DEFAULT_BLOSSOM_SERVERS = Object.freeze([
|
|
19
|
+
"https://blossom.jumble.social/",
|
|
20
|
+
]);
|
|
21
|
+
/** Large relays used to help clients discover public account metadata. */
|
|
22
|
+
export const DEFAULT_DISCOVERY_RELAYS = DEFAULT_READ_RELAYS;
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/** Sanitized operational failure: remote responses and credential strings are not included. */
|
|
2
|
+
export declare class SignerError extends Error {
|
|
3
|
+
readonly operation: string;
|
|
4
|
+
readonly code: "SIGNER_FAILED" | "SIGNER_TIMEOUT" | "SIGNER_CLOSED";
|
|
5
|
+
constructor(operation: string, code?: "SIGNER_FAILED" | "SIGNER_TIMEOUT" | "SIGNER_CLOSED");
|
|
6
|
+
}
|
|
7
|
+
/** Compatibility never silently replaces a known unrelated account encryption declaration. */
|
|
8
|
+
export declare class Nip4eCompatibilityError extends Error {
|
|
9
|
+
readonly code: "NIP4E_KEY_CONFLICT" | "NIP4E_DECLARATION_INVALID";
|
|
10
|
+
constructor(code: "NIP4E_KEY_CONFLICT" | "NIP4E_DECLARATION_INVALID");
|
|
11
|
+
}
|
|
12
|
+
/** Never reinterpret existing ciphertext as plaintext or silently change an account's storage mode. */
|
|
13
|
+
export declare class StorageEncryptionError extends Error {
|
|
14
|
+
readonly code: "STORAGE_KEY_REQUIRED" | "STORAGE_MODE_MISMATCH";
|
|
15
|
+
constructor(code: "STORAGE_KEY_REQUIRED" | "STORAGE_MODE_MISMATCH");
|
|
16
|
+
}
|
|
17
|
+
export type RelayOperation = "connect" | "subscribe" | "publish" | "auth" | "history";
|
|
18
|
+
export type RelayErrorCode = "RELAY_CONNECTION_FAILED" | "RELAY_CONNECT_TIMEOUT" | "RELAY_HTTP_REJECTED" | "RELAY_EOSE_TIMEOUT" | "RELAY_ACK_TIMEOUT" | "RELAY_CLOSED" | "RELAY_AUTH_REQUIRED" | "RELAY_AUTH_TIMEOUT" | "RELAY_AUTH_REJECTED" | "RELAY_AUTH_SIGNING_FAILED" | "RELAY_SUBSCRIPTION_REJECTED" | "RELAY_SUBSCRIPTION_FAILED" | "RELAY_EVENT_REJECTED" | "RELAY_HISTORY_INCOMPLETE";
|
|
19
|
+
export interface RelayErrorDetails {
|
|
20
|
+
relay: string;
|
|
21
|
+
operation: RelayOperation;
|
|
22
|
+
code: RelayErrorCode;
|
|
23
|
+
networkCode?: string;
|
|
24
|
+
statusCode?: number;
|
|
25
|
+
closeCode?: number;
|
|
26
|
+
eventKind?: number;
|
|
27
|
+
reason?: string;
|
|
28
|
+
historyReason?: "page-limit" | "boundary-overflow" | "query-failed";
|
|
29
|
+
}
|
|
30
|
+
/** Diagnostic metadata only: no query/path/credentials, raw relay reason, frame, or plaintext. */
|
|
31
|
+
export declare class RelayError extends Error {
|
|
32
|
+
readonly relay: string;
|
|
33
|
+
readonly operation: RelayOperation;
|
|
34
|
+
readonly code: RelayErrorCode;
|
|
35
|
+
readonly networkCode?: string;
|
|
36
|
+
readonly statusCode?: number;
|
|
37
|
+
readonly closeCode?: number;
|
|
38
|
+
readonly eventKind?: number;
|
|
39
|
+
readonly reason?: string;
|
|
40
|
+
readonly historyReason?: RelayErrorDetails["historyReason"];
|
|
41
|
+
constructor(message: string, details: RelayErrorDetails);
|
|
42
|
+
}
|
|
43
|
+
/** Terminal input rejection, with no submitted values, raw Zod messages or credentials. */
|
|
44
|
+
export declare class InvalidArgsError extends Error {
|
|
45
|
+
readonly command: string;
|
|
46
|
+
readonly category: "decode" | "validation";
|
|
47
|
+
readonly issues: readonly {
|
|
48
|
+
readonly code: string;
|
|
49
|
+
readonly path: readonly string[];
|
|
50
|
+
}[];
|
|
51
|
+
constructor(command: string, category: "decode" | "validation", issues?: readonly {
|
|
52
|
+
code: string;
|
|
53
|
+
path: readonly string[];
|
|
54
|
+
}[]);
|
|
55
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/** Sanitized operational failure: remote responses and credential strings are not included. */
|
|
2
|
+
export class SignerError extends Error {
|
|
3
|
+
operation;
|
|
4
|
+
code;
|
|
5
|
+
constructor(operation, code = "SIGNER_FAILED") {
|
|
6
|
+
super(`Signer ${operation} failed (${code})`);
|
|
7
|
+
this.operation = operation;
|
|
8
|
+
this.code = code;
|
|
9
|
+
this.name = "SignerError";
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
/** Compatibility never silently replaces a known unrelated account encryption declaration. */
|
|
13
|
+
export class Nip4eCompatibilityError extends Error {
|
|
14
|
+
code;
|
|
15
|
+
constructor(code) {
|
|
16
|
+
super(`Cannot use the configured encryption key: existing NIP-4E declaration conflicts or is invalid (${code}). Keep the declared key, use a separate identity, or explicitly migrate a locally held key with announce({replaceEncryptionKey}).`);
|
|
17
|
+
this.code = code;
|
|
18
|
+
this.name = "Nip4eCompatibilityError";
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/** Never reinterpret existing ciphertext as plaintext or silently change an account's storage mode. */
|
|
22
|
+
export class StorageEncryptionError extends Error {
|
|
23
|
+
code;
|
|
24
|
+
constructor(code) {
|
|
25
|
+
super(code === "STORAGE_KEY_REQUIRED"
|
|
26
|
+
? "Existing encrypted data requires its original storageKey."
|
|
27
|
+
: "Existing plaintext data cannot be opened as encrypted; use its original mode or explicitly migrate to a separate database.");
|
|
28
|
+
this.code = code;
|
|
29
|
+
this.name = "StorageEncryptionError";
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
const networkCodes = new Set([
|
|
33
|
+
"ECONNREFUSED",
|
|
34
|
+
"ECONNRESET",
|
|
35
|
+
"ETIMEDOUT",
|
|
36
|
+
"ENOTFOUND",
|
|
37
|
+
"EAI_AGAIN",
|
|
38
|
+
"ENETUNREACH",
|
|
39
|
+
"EHOSTUNREACH",
|
|
40
|
+
"ECONNABORTED",
|
|
41
|
+
"EPROTO",
|
|
42
|
+
"CERT_HAS_EXPIRED",
|
|
43
|
+
"DEPTH_ZERO_SELF_SIGNED_CERT",
|
|
44
|
+
"UNABLE_TO_VERIFY_LEAF_SIGNATURE",
|
|
45
|
+
"ERR_TLS_CERT_ALTNAME_INVALID",
|
|
46
|
+
]);
|
|
47
|
+
const reasonCodes = new Set([
|
|
48
|
+
"auth-required",
|
|
49
|
+
"restricted",
|
|
50
|
+
"blocked",
|
|
51
|
+
"rate-limited",
|
|
52
|
+
"pow",
|
|
53
|
+
"payment-required",
|
|
54
|
+
"duplicate",
|
|
55
|
+
"invalid",
|
|
56
|
+
"error",
|
|
57
|
+
]);
|
|
58
|
+
/** Diagnostic metadata only: no query/path/credentials, raw relay reason, frame, or plaintext. */
|
|
59
|
+
export class RelayError extends Error {
|
|
60
|
+
relay;
|
|
61
|
+
operation;
|
|
62
|
+
code;
|
|
63
|
+
networkCode;
|
|
64
|
+
statusCode;
|
|
65
|
+
closeCode;
|
|
66
|
+
eventKind;
|
|
67
|
+
reason;
|
|
68
|
+
historyReason;
|
|
69
|
+
constructor(message, details) {
|
|
70
|
+
let relay = "(invalid relay URL)";
|
|
71
|
+
try {
|
|
72
|
+
const url = new URL(details.relay);
|
|
73
|
+
if (["ws:", "wss:"].includes(url.protocol)) {
|
|
74
|
+
relay = url.origin;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
catch { }
|
|
78
|
+
super(`${message} [${relay}] (${details.code})`);
|
|
79
|
+
this.name = "RelayError";
|
|
80
|
+
this.relay = relay;
|
|
81
|
+
this.operation = details.operation;
|
|
82
|
+
this.code = details.code;
|
|
83
|
+
if (details.networkCode && networkCodes.has(details.networkCode)) {
|
|
84
|
+
this.networkCode = details.networkCode;
|
|
85
|
+
}
|
|
86
|
+
if (typeof details.statusCode === "number" &&
|
|
87
|
+
Number.isInteger(details.statusCode) &&
|
|
88
|
+
details.statusCode >= 100 &&
|
|
89
|
+
details.statusCode <= 599) {
|
|
90
|
+
this.statusCode = details.statusCode;
|
|
91
|
+
}
|
|
92
|
+
if (typeof details.closeCode === "number" &&
|
|
93
|
+
Number.isInteger(details.closeCode) &&
|
|
94
|
+
details.closeCode >= 1000 &&
|
|
95
|
+
details.closeCode <= 4999) {
|
|
96
|
+
this.closeCode = details.closeCode;
|
|
97
|
+
}
|
|
98
|
+
if (typeof details.eventKind === "number" &&
|
|
99
|
+
Number.isInteger(details.eventKind) &&
|
|
100
|
+
details.eventKind >= 0 &&
|
|
101
|
+
details.eventKind <= 65535) {
|
|
102
|
+
this.eventKind = details.eventKind;
|
|
103
|
+
}
|
|
104
|
+
const reason = details.reason?.split(":")[0];
|
|
105
|
+
if (reason && reasonCodes.has(reason)) {
|
|
106
|
+
this.reason = reason;
|
|
107
|
+
}
|
|
108
|
+
this.historyReason = details.historyReason;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
/** Terminal input rejection, with no submitted values, raw Zod messages or credentials. */
|
|
112
|
+
export class InvalidArgsError extends Error {
|
|
113
|
+
command;
|
|
114
|
+
category;
|
|
115
|
+
issues;
|
|
116
|
+
constructor(command, category, issues = []) {
|
|
117
|
+
super(`Invalid arguments for /${command}`);
|
|
118
|
+
this.command = command;
|
|
119
|
+
this.category = category;
|
|
120
|
+
this.name = "InvalidArgsError";
|
|
121
|
+
this.issues = Object.freeze(issues.map((issue) => Object.freeze({
|
|
122
|
+
code: issue.code,
|
|
123
|
+
path: Object.freeze([...issue.path]),
|
|
124
|
+
})));
|
|
125
|
+
}
|
|
126
|
+
}
|