@sharedcontext/sdk 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/LICENSE-APACHE +201 -0
- package/LICENSE-MIT +21 -0
- package/NOTICE +8 -0
- package/README.md +84 -2
- package/dist/canonical.d.ts +47 -0
- package/dist/canonical.js +257 -0
- package/dist/client.d.ts +96 -0
- package/dist/client.js +205 -0
- package/dist/constants.d.ts +19 -0
- package/dist/constants.js +21 -0
- package/dist/event.d.ts +104 -0
- package/dist/event.js +173 -0
- package/dist/generated/content.d.ts +588 -0
- package/dist/generated/content.js +3 -0
- package/dist/generated/schemas.d.ts +5 -0
- package/dist/generated/schemas.js +15 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +8 -0
- package/dist/reasons.d.ts +14 -0
- package/dist/reasons.js +142 -0
- package/dist/schema.d.ts +29 -0
- package/dist/schema.js +265 -0
- package/dist/types.d.ts +230 -0
- package/dist/types.js +3 -0
- package/package.json +44 -4
- package/schemas/sharedcontext-1/changes.schema.json +128 -0
- package/schemas/sharedcontext-1/content.schema.json +2076 -0
- package/schemas/sharedcontext-1/context.schema.json +218 -0
- package/schemas/sharedcontext-1/event.schema.json +55 -0
- package/schemas/sharedcontext-1/execution.schema.json +342 -0
- package/schemas/sharedcontext-1/history/content-1.0.schema.json +1915 -0
- package/schemas/sharedcontext-1/lineage.schema.json +753 -0
- package/schemas/sharedcontext-1/mcp-tools.schema.json +1357 -0
- package/schemas/sharedcontext-1/stored-event.schema.json +14 -0
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { type EventTemplate, type SharedcontextSigner, type SignedEvent } from "./event.js";
|
|
2
|
+
import type { Appended, ChangesArgs, ChangesPage, ClaimNextArgs, ClaimNextResult, CloseResult, DraftResult, FoldedView, NextArgs, NextResult, StatsResult, StreamEvent, SubscribeResult, ToolInfo } from "./types.js";
|
|
3
|
+
/** How long one call (request and answer body) may take by default. */
|
|
4
|
+
export declare const DEFAULT_TIMEOUT_MS = 10000;
|
|
5
|
+
/** The response fields the client reads. */
|
|
6
|
+
export interface FetchResponseLike {
|
|
7
|
+
readonly ok: boolean;
|
|
8
|
+
readonly status: number;
|
|
9
|
+
text(): Promise<string>;
|
|
10
|
+
}
|
|
11
|
+
/** The `fetch` the client calls; the global one by default. */
|
|
12
|
+
export type FetchLike = (url: string, init: {
|
|
13
|
+
method: string;
|
|
14
|
+
headers: Record<string, string>;
|
|
15
|
+
body: string;
|
|
16
|
+
signal?: unknown;
|
|
17
|
+
}) => Promise<FetchResponseLike>;
|
|
18
|
+
export interface SharedcontextClientOptions {
|
|
19
|
+
/** The service's origin, such as `https://work.example.com`; `/mcp` is appended. */
|
|
20
|
+
baseUrl: string;
|
|
21
|
+
/** Sent as `Authorization: Bearer <token>`. */
|
|
22
|
+
token?: string;
|
|
23
|
+
/** Another `fetch` (a test double, a bound service, a proxy). */
|
|
24
|
+
fetch?: FetchLike;
|
|
25
|
+
/** Per call; default `DEFAULT_TIMEOUT_MS`. */
|
|
26
|
+
timeoutMs?: number;
|
|
27
|
+
/** More request headers. */
|
|
28
|
+
headers?: Record<string, string>;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* The service said no. `reason` is a stable code: a known refusal (`role_not_allowed`,
|
|
32
|
+
* `node_not_found`, `signer_not_caller`, …), `http_<status>`, or `refused` when the answer carried no
|
|
33
|
+
* known code. The message holds only that code, so logging the error cannot print what the server
|
|
34
|
+
* sent; the structured answer is kept, not enumerable, as `body`.
|
|
35
|
+
*/
|
|
36
|
+
export declare class SharedcontextRefused extends Error {
|
|
37
|
+
readonly reason: string;
|
|
38
|
+
readonly body: unknown;
|
|
39
|
+
constructor(reason: string, body?: unknown);
|
|
40
|
+
}
|
|
41
|
+
/** The service could not be reached in time, or answered outside the protocol. */
|
|
42
|
+
export declare class SharedcontextUnavailable extends Error {
|
|
43
|
+
constructor(message: string);
|
|
44
|
+
}
|
|
45
|
+
export declare class SharedcontextClient {
|
|
46
|
+
readonly url: string;
|
|
47
|
+
private readonly token;
|
|
48
|
+
private readonly doFetch;
|
|
49
|
+
private readonly timeoutMs;
|
|
50
|
+
private readonly headers;
|
|
51
|
+
private nextId;
|
|
52
|
+
constructor(opts: SharedcontextClientOptions);
|
|
53
|
+
/** One JSON-RPC request; its `result`. */
|
|
54
|
+
private rpc;
|
|
55
|
+
/**
|
|
56
|
+
* One `tools/call`: the answer's `structuredContent`. A structured error result throws
|
|
57
|
+
* `SharedcontextRefused` with its `reason` (or, for `changes`, its `refused`) when that is a
|
|
58
|
+
* known code.
|
|
59
|
+
*/
|
|
60
|
+
call<T>(tool: string, args?: Record<string, unknown>): Promise<T>;
|
|
61
|
+
/** The tools the service serves (`tools/list`). */
|
|
62
|
+
listTools(): Promise<ToolInfo[]>;
|
|
63
|
+
/** Append a signed event. An exact resend answers the first append (`duplicate: true`); another event on the same `c` tag is refused `duplicate`. */
|
|
64
|
+
submit(event: SignedEvent): Promise<Appended>;
|
|
65
|
+
/** Sign `template` with `signer` (checking it answered this template), then `submit` it. */
|
|
66
|
+
write(signer: SharedcontextSigner, template: EventTemplate): Promise<Appended>;
|
|
67
|
+
/** One node folded; null when the log has no such node. */
|
|
68
|
+
state(node: string): Promise<FoldedView | null>;
|
|
69
|
+
/** The context bundle of one node. */
|
|
70
|
+
context(node: string): Promise<FoldedView>;
|
|
71
|
+
/** Events after `afterSeq` (a page; call again from `next_after_seq` to follow), optionally of one node. */
|
|
72
|
+
subscribe(afterSeq: number, opts?: {
|
|
73
|
+
node?: string;
|
|
74
|
+
limit?: number;
|
|
75
|
+
}): Promise<SubscribeResult>;
|
|
76
|
+
/** What changed after a cursor, without the body (served only where the deployment turns the change feed on). */
|
|
77
|
+
changes(args?: ChangesArgs): Promise<ChangesPage>;
|
|
78
|
+
/** Claimable nodes for `viewer`, best first. */
|
|
79
|
+
next(args?: NextArgs): Promise<NextResult>;
|
|
80
|
+
/**
|
|
81
|
+
* The best ready node: with a signed `claim.taken` in `event`, one call; with only `pubkey`, a
|
|
82
|
+
* short reservation and the unsigned claim to sign and send to `submit` before it ends.
|
|
83
|
+
*/
|
|
84
|
+
claimNext(args: ClaimNextArgs): Promise<ClaimNextResult>;
|
|
85
|
+
/** The unsigned event a write tool would append, for the caller to sign and `submit`. */
|
|
86
|
+
draft(tool: string, pubkey: string, args: Record<string, unknown>): Promise<DraftResult>;
|
|
87
|
+
/** Evaluate the close rule of a node now. When it does not hold, throws `SharedcontextRefused` with the `{unmet}` answer as `body`. */
|
|
88
|
+
close(node: string, runId?: string): Promise<CloseResult>;
|
|
89
|
+
/** The log's counts and the tail of its reject journal. */
|
|
90
|
+
stats(): Promise<StatsResult>;
|
|
91
|
+
/** Every event of one node, page by page, at most `maxPages` pages of `limit`. */
|
|
92
|
+
nodeEvents(node: string, opts?: {
|
|
93
|
+
maxPages?: number;
|
|
94
|
+
limit?: number;
|
|
95
|
+
}): Promise<StreamEvent[]>;
|
|
96
|
+
}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
// A small client for the service's MCP tools over streamable HTTP at `/mcp`: stateless, JSON
|
|
2
|
+
// answers, one `tools/call` per request. It runs wherever `fetch` does (Node 20+, browsers,
|
|
3
|
+
// Workers) and holds no key: writes are events the caller signs (`write` takes a signer).
|
|
4
|
+
import { signEvent } from "./event.js";
|
|
5
|
+
import { KNOWN_REASONS, knownCode } from "./reasons.js";
|
|
6
|
+
/** How long one call (request and answer body) may take by default. */
|
|
7
|
+
export const DEFAULT_TIMEOUT_MS = 10_000;
|
|
8
|
+
/**
|
|
9
|
+
* The service said no. `reason` is a stable code: a known refusal (`role_not_allowed`,
|
|
10
|
+
* `node_not_found`, `signer_not_caller`, …), `http_<status>`, or `refused` when the answer carried no
|
|
11
|
+
* known code. The message holds only that code, so logging the error cannot print what the server
|
|
12
|
+
* sent; the structured answer is kept, not enumerable, as `body`.
|
|
13
|
+
*/
|
|
14
|
+
export class SharedcontextRefused extends Error {
|
|
15
|
+
reason;
|
|
16
|
+
constructor(reason, body) {
|
|
17
|
+
super(`sharedcontext refused: ${reason}`);
|
|
18
|
+
this.reason = reason;
|
|
19
|
+
this.name = "SharedcontextRefused";
|
|
20
|
+
Object.defineProperty(this, "body", { value: body, enumerable: false });
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/** The service could not be reached in time, or answered outside the protocol. */
|
|
24
|
+
export class SharedcontextUnavailable extends Error {
|
|
25
|
+
constructor(message) {
|
|
26
|
+
super(message);
|
|
27
|
+
this.name = "SharedcontextUnavailable";
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
class TimedOut extends Error {
|
|
31
|
+
}
|
|
32
|
+
/** One request and its answer text within `ms`, even when the fetch ignores its abort signal. */
|
|
33
|
+
async function fetchTextWithin(doFetch, url, init, ms) {
|
|
34
|
+
const ctl = new AbortController();
|
|
35
|
+
let timer;
|
|
36
|
+
const deadline = new Promise((_, reject) => {
|
|
37
|
+
timer = setTimeout(() => {
|
|
38
|
+
ctl.abort();
|
|
39
|
+
reject(new TimedOut());
|
|
40
|
+
}, ms);
|
|
41
|
+
});
|
|
42
|
+
try {
|
|
43
|
+
return await Promise.race([
|
|
44
|
+
(async () => {
|
|
45
|
+
const res = await doFetch(url, { ...init, signal: ctl.signal });
|
|
46
|
+
return { res, text: await res.text() };
|
|
47
|
+
})(),
|
|
48
|
+
deadline,
|
|
49
|
+
]);
|
|
50
|
+
}
|
|
51
|
+
finally {
|
|
52
|
+
clearTimeout(timer);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
export class SharedcontextClient {
|
|
56
|
+
url;
|
|
57
|
+
token;
|
|
58
|
+
doFetch;
|
|
59
|
+
timeoutMs;
|
|
60
|
+
headers;
|
|
61
|
+
nextId = 1;
|
|
62
|
+
constructor(opts) {
|
|
63
|
+
this.url = `${opts.baseUrl.replace(/\/+$/, "")}/mcp`;
|
|
64
|
+
this.token = opts.token;
|
|
65
|
+
this.doFetch = opts.fetch ?? ((url, init) => fetch(url, init));
|
|
66
|
+
this.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
67
|
+
this.headers = { ...(opts.headers ?? {}) };
|
|
68
|
+
}
|
|
69
|
+
/** One JSON-RPC request; its `result`. */
|
|
70
|
+
async rpc(method, params, what) {
|
|
71
|
+
const headers = { ...this.headers, "content-type": "application/json", accept: "application/json, text/event-stream" };
|
|
72
|
+
if (this.token)
|
|
73
|
+
headers.authorization = `Bearer ${this.token}`;
|
|
74
|
+
// Errors carry the tool, the HTTP status and a stable code only: never the answer's body or
|
|
75
|
+
// the network error's text.
|
|
76
|
+
let res;
|
|
77
|
+
let text;
|
|
78
|
+
try {
|
|
79
|
+
({ res, text } = await fetchTextWithin(this.doFetch, this.url, { method: "POST", headers, body: JSON.stringify({ jsonrpc: "2.0", id: this.nextId++, method, params }) }, this.timeoutMs));
|
|
80
|
+
}
|
|
81
|
+
catch (err) {
|
|
82
|
+
throw new SharedcontextUnavailable(err instanceof TimedOut ? `sharedcontext ${what}: timed out after ${this.timeoutMs} ms` : `sharedcontext ${what}: unreachable`);
|
|
83
|
+
}
|
|
84
|
+
if (!res.ok) {
|
|
85
|
+
// 401 and 403 (sign-in, `signer_not_caller`) carry {error, reason, detail}: keep a known reason
|
|
86
|
+
if (res.status === 401 || res.status === 403) {
|
|
87
|
+
let body;
|
|
88
|
+
try {
|
|
89
|
+
body = JSON.parse(text);
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
/* not JSON */
|
|
93
|
+
}
|
|
94
|
+
throw new SharedcontextRefused(knownCode(body?.reason) ?? knownCode(body?.error) ?? `http_${res.status}`, body);
|
|
95
|
+
}
|
|
96
|
+
throw new SharedcontextUnavailable(`sharedcontext ${what}: HTTP ${res.status}`);
|
|
97
|
+
}
|
|
98
|
+
let body;
|
|
99
|
+
try {
|
|
100
|
+
body = JSON.parse(text);
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
throw new SharedcontextUnavailable(`sharedcontext ${what}: the answer is not JSON`);
|
|
104
|
+
}
|
|
105
|
+
if (body.error) {
|
|
106
|
+
const code = Number.isInteger(body.error.code) ? ` ${String(body.error.code)}` : "";
|
|
107
|
+
throw new SharedcontextUnavailable(`sharedcontext ${what}: JSON-RPC error${code}`);
|
|
108
|
+
}
|
|
109
|
+
if (!body.result || typeof body.result !== "object")
|
|
110
|
+
throw new SharedcontextUnavailable(`sharedcontext ${what}: no result`);
|
|
111
|
+
return body.result;
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* One `tools/call`: the answer's `structuredContent`. A structured error result throws
|
|
115
|
+
* `SharedcontextRefused` with its `reason` (or, for `changes`, its `refused`) when that is a
|
|
116
|
+
* known code.
|
|
117
|
+
*/
|
|
118
|
+
async call(tool, args = {}) {
|
|
119
|
+
const result = await this.rpc("tools/call", { name: tool, arguments: dropUndefined(args) }, tool);
|
|
120
|
+
const sc = result.structuredContent;
|
|
121
|
+
if (result.isError)
|
|
122
|
+
throw new SharedcontextRefused(knownCode(sc?.reason, KNOWN_REASONS) ?? knownCode(sc?.refused, KNOWN_REASONS) ?? "refused", sc);
|
|
123
|
+
if (sc === undefined)
|
|
124
|
+
throw new SharedcontextUnavailable(`sharedcontext ${tool}: no structured content`);
|
|
125
|
+
return sc;
|
|
126
|
+
}
|
|
127
|
+
/** The tools the service serves (`tools/list`). */
|
|
128
|
+
async listTools() {
|
|
129
|
+
const result = await this.rpc("tools/list", {}, "tools/list");
|
|
130
|
+
if (!Array.isArray(result.tools))
|
|
131
|
+
throw new SharedcontextUnavailable("sharedcontext tools/list: no tools");
|
|
132
|
+
return result.tools;
|
|
133
|
+
}
|
|
134
|
+
/** Append a signed event. An exact resend answers the first append (`duplicate: true`); another event on the same `c` tag is refused `duplicate`. */
|
|
135
|
+
submit(event) {
|
|
136
|
+
return this.call("submit", { event });
|
|
137
|
+
}
|
|
138
|
+
/** Sign `template` with `signer` (checking it answered this template), then `submit` it. */
|
|
139
|
+
async write(signer, template) {
|
|
140
|
+
return this.submit(await signEvent(signer, template));
|
|
141
|
+
}
|
|
142
|
+
/** One node folded; null when the log has no such node. */
|
|
143
|
+
async state(node) {
|
|
144
|
+
try {
|
|
145
|
+
return await this.call("state", { node });
|
|
146
|
+
}
|
|
147
|
+
catch (err) {
|
|
148
|
+
if (err instanceof SharedcontextRefused && err.reason === "node_not_found")
|
|
149
|
+
return null;
|
|
150
|
+
throw err;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
/** The context bundle of one node. */
|
|
154
|
+
context(node) {
|
|
155
|
+
return this.call("context", { node });
|
|
156
|
+
}
|
|
157
|
+
/** Events after `afterSeq` (a page; call again from `next_after_seq` to follow), optionally of one node. */
|
|
158
|
+
subscribe(afterSeq, opts = {}) {
|
|
159
|
+
return this.call("subscribe", { after_seq: afterSeq, node: opts.node, limit: opts.limit });
|
|
160
|
+
}
|
|
161
|
+
/** What changed after a cursor, without the body (served only where the deployment turns the change feed on). */
|
|
162
|
+
changes(args = {}) {
|
|
163
|
+
return this.call("changes", { ...args });
|
|
164
|
+
}
|
|
165
|
+
/** Claimable nodes for `viewer`, best first. */
|
|
166
|
+
next(args = {}) {
|
|
167
|
+
return this.call("next", { ...args });
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* The best ready node: with a signed `claim.taken` in `event`, one call; with only `pubkey`, a
|
|
171
|
+
* short reservation and the unsigned claim to sign and send to `submit` before it ends.
|
|
172
|
+
*/
|
|
173
|
+
claimNext(args) {
|
|
174
|
+
return this.call("claim_next", { ...args });
|
|
175
|
+
}
|
|
176
|
+
/** The unsigned event a write tool would append, for the caller to sign and `submit`. */
|
|
177
|
+
draft(tool, pubkey, args) {
|
|
178
|
+
return this.call("draft", { tool, pubkey, args });
|
|
179
|
+
}
|
|
180
|
+
/** Evaluate the close rule of a node now. When it does not hold, throws `SharedcontextRefused` with the `{unmet}` answer as `body`. */
|
|
181
|
+
close(node, runId) {
|
|
182
|
+
return this.call("close", { node, run_id: runId });
|
|
183
|
+
}
|
|
184
|
+
/** The log's counts and the tail of its reject journal. */
|
|
185
|
+
stats() {
|
|
186
|
+
return this.call("stats", {});
|
|
187
|
+
}
|
|
188
|
+
/** Every event of one node, page by page, at most `maxPages` pages of `limit`. */
|
|
189
|
+
async nodeEvents(node, opts = {}) {
|
|
190
|
+
const out = [];
|
|
191
|
+
let after = 0;
|
|
192
|
+
for (let page = 0; page < (opts.maxPages ?? 10); page++) {
|
|
193
|
+
const p = await this.subscribe(after, { node, limit: opts.limit ?? 500 });
|
|
194
|
+
out.push(...p.events);
|
|
195
|
+
const next = p.next_after_seq ?? p.events.at(-1)?.seq ?? after;
|
|
196
|
+
if (p.events.length === 0 || next <= after || next >= p.head_seq)
|
|
197
|
+
break;
|
|
198
|
+
after = next;
|
|
199
|
+
}
|
|
200
|
+
return out;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
function dropUndefined(o) {
|
|
204
|
+
return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
|
|
205
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** The contract this package implements. */
|
|
2
|
+
export declare const CONTRACT = "sharedcontext/1";
|
|
3
|
+
/** The one Nostr kind of every work event (`signed::TICKET_KIND`). */
|
|
4
|
+
export declare const TICKET_KIND = 7411;
|
|
5
|
+
/** The schema major every event carries in its `v` tag (`signed::SCHEMA_MAJOR`). */
|
|
6
|
+
export declare const SCHEMA_MAJOR = "1";
|
|
7
|
+
/** The type tag: `w`, the event type, such as `node.created` (`signed::TYPE_TAG`). */
|
|
8
|
+
export declare const TYPE_TAG = "w";
|
|
9
|
+
/** The `c` tag (client id) bound, in UTF-8 bytes (`signed::CLIENT_ID_MAX`). */
|
|
10
|
+
export declare const CLIENT_ID_MAX = 64;
|
|
11
|
+
/** How far `created_at` may lie after the log's receipt time, in seconds (`signed::FUTURE_SKEW_S`). */
|
|
12
|
+
export declare const FUTURE_SKEW_S = 900;
|
|
13
|
+
/** The bound on a node's `body` and a note's `text`, in UTF-8 bytes (`work::MAX_BODY_BYTES`). */
|
|
14
|
+
export declare const MAX_BODY_BYTES: number;
|
|
15
|
+
/**
|
|
16
|
+
* The deepest nesting of arrays and objects the core parses in an event's content: its JSON
|
|
17
|
+
* parser stops at 128 levels, so 127 is the most that is accepted.
|
|
18
|
+
*/
|
|
19
|
+
export declare const MAX_CONTENT_DEPTH = 127;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// The wire constants of sharedcontext/1, each the same as the Rust core's (test/constants.test.mjs
|
|
2
|
+
// reads them from crates/sharedcontext/src and compares).
|
|
3
|
+
/** The contract this package implements. */
|
|
4
|
+
export const CONTRACT = "sharedcontext/1";
|
|
5
|
+
/** The one Nostr kind of every work event (`signed::TICKET_KIND`). */
|
|
6
|
+
export const TICKET_KIND = 7411;
|
|
7
|
+
/** The schema major every event carries in its `v` tag (`signed::SCHEMA_MAJOR`). */
|
|
8
|
+
export const SCHEMA_MAJOR = "1";
|
|
9
|
+
/** The type tag: `w`, the event type, such as `node.created` (`signed::TYPE_TAG`). */
|
|
10
|
+
export const TYPE_TAG = "w";
|
|
11
|
+
/** The `c` tag (client id) bound, in UTF-8 bytes (`signed::CLIENT_ID_MAX`). */
|
|
12
|
+
export const CLIENT_ID_MAX = 64;
|
|
13
|
+
/** How far `created_at` may lie after the log's receipt time, in seconds (`signed::FUTURE_SKEW_S`). */
|
|
14
|
+
export const FUTURE_SKEW_S = 900;
|
|
15
|
+
/** The bound on a node's `body` and a note's `text`, in UTF-8 bytes (`work::MAX_BODY_BYTES`). */
|
|
16
|
+
export const MAX_BODY_BYTES = 16 * 1024;
|
|
17
|
+
/**
|
|
18
|
+
* The deepest nesting of arrays and objects the core parses in an event's content: its JSON
|
|
19
|
+
* parser stops at 128 levels, so 127 is the most that is accepted.
|
|
20
|
+
*/
|
|
21
|
+
export const MAX_CONTENT_DEPTH = 127;
|
package/dist/event.d.ts
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { CanonicalJsonError } from "./canonical.js";
|
|
2
|
+
import type { ContentByType, EventType } from "./generated/content.js";
|
|
3
|
+
import type { EnvelopeReason } from "./reasons.js";
|
|
4
|
+
/** The unsigned NIP-01 body: what a signer signs. */
|
|
5
|
+
export interface EventTemplate {
|
|
6
|
+
pubkey: string;
|
|
7
|
+
created_at: number;
|
|
8
|
+
kind: number;
|
|
9
|
+
tags: string[][];
|
|
10
|
+
content: string;
|
|
11
|
+
}
|
|
12
|
+
/** A signed event: the template with its NIP-01 `id` and BIP-340 `sig`. */
|
|
13
|
+
export interface SignedEvent extends EventTemplate {
|
|
14
|
+
id: string;
|
|
15
|
+
sig: string;
|
|
16
|
+
}
|
|
17
|
+
/** An event as the log stores and serves it (`stored-event.schema.json`). */
|
|
18
|
+
export interface StoredEvent {
|
|
19
|
+
seq: number;
|
|
20
|
+
received_at: number;
|
|
21
|
+
policy_version: string;
|
|
22
|
+
event: SignedEvent;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Signs a template as one key. The package never holds keys: the caller's signer (a remote signer,
|
|
26
|
+
* a NIP-46 bunker, a local key in a test) answers the signed event.
|
|
27
|
+
*/
|
|
28
|
+
export interface SharedcontextSigner {
|
|
29
|
+
/** The x-only public key, 64 lowercase hex characters. */
|
|
30
|
+
readonly pubkey: string;
|
|
31
|
+
sign(template: EventTemplate): Promise<SignedEvent>;
|
|
32
|
+
}
|
|
33
|
+
/** NIP-01 serialization: `[0, pubkey, created_at, kind, tags, content]`, compact. */
|
|
34
|
+
export declare function serializeNip01(t: EventTemplate): string;
|
|
35
|
+
/** sha256 of the UTF-8 bytes of `s`, as lowercase hex (Web Crypto: Node 20+, browsers, Workers). */
|
|
36
|
+
export declare function sha256Hex(s: string): Promise<string>;
|
|
37
|
+
/** The NIP-01 id: sha256 of the serialization, lowercase hex. */
|
|
38
|
+
export declare function eventId(t: EventTemplate): Promise<string>;
|
|
39
|
+
/** Types that may leave out the `n` tag: every `project.*` type, and `cost.recorded` (`signed::node_tag_optional`). */
|
|
40
|
+
export declare function nodeTagOptional(type: string): boolean;
|
|
41
|
+
/** What `eventTemplate` takes. */
|
|
42
|
+
export interface TemplateInput<T extends string = string> {
|
|
43
|
+
pubkey: string;
|
|
44
|
+
/** Unix seconds. */
|
|
45
|
+
createdAt: number;
|
|
46
|
+
/** The event type (`w` tag), such as `node.created`. */
|
|
47
|
+
type: T;
|
|
48
|
+
/** The project id (`j` tag). */
|
|
49
|
+
project: string;
|
|
50
|
+
/**
|
|
51
|
+
* The client id (`c` tag), 1 to `CLIENT_ID_MAX` UTF-8 bytes, which makes the write idempotent: an
|
|
52
|
+
* exact resend answers the first append, and a different event on the same `(pubkey, c)` is
|
|
53
|
+
* refused as `duplicate`.
|
|
54
|
+
*/
|
|
55
|
+
clientId: string;
|
|
56
|
+
/** The node (`n` tag); required unless `nodeTagOptional(type)`. */
|
|
57
|
+
node?: string;
|
|
58
|
+
/** More tags after the standard ones, such as `["e", <event id>]` or `["p", <pubkey>]`. */
|
|
59
|
+
tags?: readonly (readonly string[])[];
|
|
60
|
+
/**
|
|
61
|
+
* The content; written as canonical JSON, `undefined` fields left out. For a type of
|
|
62
|
+
* content.schema.json its fields are typed; fields of a later minor behind a policy switch (node
|
|
63
|
+
* fields, the execution vocabulary) may be added, and the log decides whether it takes them.
|
|
64
|
+
*/
|
|
65
|
+
content: T extends EventType ? ContentByType[T] & {
|
|
66
|
+
readonly [key: string]: unknown;
|
|
67
|
+
} : {
|
|
68
|
+
readonly [key: string]: unknown;
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
/** A template input the core would refuse whatever its state. */
|
|
72
|
+
export declare class TemplateError extends Error {
|
|
73
|
+
readonly reason: EnvelopeReason;
|
|
74
|
+
constructor(reason: EnvelopeReason, message: string);
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* The unsigned event, with its tags in the order the core writes them: `w`, `n`, `j`, `c`, `v`,
|
|
78
|
+
* then `tags`. Content is canonical JSON. Throws `TemplateError` for what the envelope check would
|
|
79
|
+
* refuse (a type without a dot, a missing node, a client id out of bounds, a bad tag) and
|
|
80
|
+
* `CanonicalJsonError` for content that is not JSON the core reads back.
|
|
81
|
+
*/
|
|
82
|
+
export declare function eventTemplate<T extends string>(i: TemplateInput<T>): EventTemplate;
|
|
83
|
+
export { CanonicalJsonError };
|
|
84
|
+
/**
|
|
85
|
+
* The core's envelope rules for an event already parsed (`Event::verify_shape`): kind 7411;
|
|
86
|
+
* `created_at` at most `FUTURE_SKEW_S` after `receivedAt` (only when it is given); every tag name
|
|
87
|
+
* one ASCII letter with a non-empty value; `w` (with a dot), `j`, `n` (unless the type may omit it),
|
|
88
|
+
* `v` and `c` (at most `CLIENT_ID_MAX` bytes) present; canonical content. Null when it passes.
|
|
89
|
+
*/
|
|
90
|
+
export declare function verifyShape(e: EventTemplate, receivedAt?: number): EnvelopeReason | null;
|
|
91
|
+
/**
|
|
92
|
+
* The core's stateless check of one event, in its order, without the signature: the NIP-01 shape
|
|
93
|
+
* (`malformed`), the id (`bad_id`), then `verifyShape`. Null when it passes. A passing event can
|
|
94
|
+
* still carry a bad signature (`bad_signature`) and can still be refused by the log's state and
|
|
95
|
+
* policy rules.
|
|
96
|
+
*/
|
|
97
|
+
export declare function verifyEvent(e: unknown, opts?: {
|
|
98
|
+
receivedAt?: number;
|
|
99
|
+
}): Promise<EnvelopeReason | null>;
|
|
100
|
+
/**
|
|
101
|
+
* Sign a template with `signer`, and check that the signer answered this template: the same key,
|
|
102
|
+
* fields and id. The signature itself is the signer's.
|
|
103
|
+
*/
|
|
104
|
+
export declare function signEvent(signer: SharedcontextSigner, template: EventTemplate): Promise<SignedEvent>;
|
package/dist/event.js
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
// The signed envelope: a NIP-01 event of kind 7411. This module builds the unsigned template,
|
|
2
|
+
// computes its id and checks an event's shape as the core does (`signed::Event::verify_shape`).
|
|
3
|
+
// It never holds a key: signing goes through a `SharedcontextSigner`, and the BIP-340 signature
|
|
4
|
+
// itself is not verified here (use any NIP-01 library for that; the core verifies every event).
|
|
5
|
+
import { CanonicalJsonError, canonicalContent, isCanonicalContent, isWellFormed, utf8, utf8Length } from "./canonical.js";
|
|
6
|
+
import { CLIENT_ID_MAX, FUTURE_SKEW_S, SCHEMA_MAJOR, TICKET_KIND, TYPE_TAG } from "./constants.js";
|
|
7
|
+
/** NIP-01 serialization: `[0, pubkey, created_at, kind, tags, content]`, compact. */
|
|
8
|
+
export function serializeNip01(t) {
|
|
9
|
+
return JSON.stringify([0, t.pubkey, t.created_at, t.kind, t.tags, t.content]);
|
|
10
|
+
}
|
|
11
|
+
const HEX = "0123456789abcdef";
|
|
12
|
+
function hex(bytes) {
|
|
13
|
+
let s = "";
|
|
14
|
+
for (const b of bytes)
|
|
15
|
+
s += HEX[b >> 4] + HEX[b & 15];
|
|
16
|
+
return s;
|
|
17
|
+
}
|
|
18
|
+
/** sha256 of the UTF-8 bytes of `s`, as lowercase hex (Web Crypto: Node 20+, browsers, Workers). */
|
|
19
|
+
export async function sha256Hex(s) {
|
|
20
|
+
return hex(new Uint8Array(await crypto.subtle.digest("SHA-256", utf8(s))));
|
|
21
|
+
}
|
|
22
|
+
/** The NIP-01 id: sha256 of the serialization, lowercase hex. */
|
|
23
|
+
export function eventId(t) {
|
|
24
|
+
return sha256Hex(serializeNip01(t));
|
|
25
|
+
}
|
|
26
|
+
/** Types that may leave out the `n` tag: every `project.*` type, and `cost.recorded` (`signed::node_tag_optional`). */
|
|
27
|
+
export function nodeTagOptional(type) {
|
|
28
|
+
return type.startsWith("project.") || type === "cost.recorded";
|
|
29
|
+
}
|
|
30
|
+
/** A template input the core would refuse whatever its state. */
|
|
31
|
+
export class TemplateError extends Error {
|
|
32
|
+
reason;
|
|
33
|
+
constructor(reason, message) {
|
|
34
|
+
super(`${reason}: ${message}`);
|
|
35
|
+
this.reason = reason;
|
|
36
|
+
this.name = "TemplateError";
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
function tagError(t) {
|
|
40
|
+
const name = t[0];
|
|
41
|
+
if (name === undefined || name.length !== 1 || !/^[A-Za-z]$/.test(name))
|
|
42
|
+
return "a tag's name must be one ASCII letter";
|
|
43
|
+
if (t.length < 2 || t[1] === "")
|
|
44
|
+
return `tag ${name} needs a non-empty value`;
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* The unsigned event, with its tags in the order the core writes them: `w`, `n`, `j`, `c`, `v`,
|
|
49
|
+
* then `tags`. Content is canonical JSON. Throws `TemplateError` for what the envelope check would
|
|
50
|
+
* refuse (a type without a dot, a missing node, a client id out of bounds, a bad tag) and
|
|
51
|
+
* `CanonicalJsonError` for content that is not JSON the core reads back.
|
|
52
|
+
*/
|
|
53
|
+
export function eventTemplate(i) {
|
|
54
|
+
if (!i.type.includes("."))
|
|
55
|
+
throw new TemplateError("bad_tag", `the type ${JSON.stringify(i.type)} has no dot`);
|
|
56
|
+
const cBytes = utf8Length(i.clientId);
|
|
57
|
+
if (cBytes === 0 || cBytes > CLIENT_ID_MAX)
|
|
58
|
+
throw new TemplateError("bad_tag", `the client id must be 1 to ${CLIENT_ID_MAX} UTF-8 bytes`);
|
|
59
|
+
if (!i.project)
|
|
60
|
+
throw new TemplateError("missing_tag", "the project (j tag) is required");
|
|
61
|
+
if (!i.node && !nodeTagOptional(i.type))
|
|
62
|
+
throw new TemplateError("missing_tag", `a ${i.type} event names its node (n tag)`);
|
|
63
|
+
if (!Number.isSafeInteger(i.createdAt) || i.createdAt < 0)
|
|
64
|
+
throw new TemplateError("malformed", "createdAt must be unix seconds");
|
|
65
|
+
const tags = [[TYPE_TAG, i.type]];
|
|
66
|
+
if (i.node)
|
|
67
|
+
tags.push(["n", i.node]);
|
|
68
|
+
tags.push(["j", i.project], ["c", i.clientId], ["v", SCHEMA_MAJOR]);
|
|
69
|
+
for (const t of i.tags ?? [])
|
|
70
|
+
tags.push([...t]);
|
|
71
|
+
for (const t of tags) {
|
|
72
|
+
const e = tagError(t);
|
|
73
|
+
if (e)
|
|
74
|
+
throw new TemplateError("bad_tag", e);
|
|
75
|
+
if (!t.every(isWellFormed))
|
|
76
|
+
throw new TemplateError("malformed", "a tag value has a lone surrogate");
|
|
77
|
+
}
|
|
78
|
+
if (!isWellFormed(i.pubkey))
|
|
79
|
+
throw new TemplateError("malformed", "the pubkey has a lone surrogate");
|
|
80
|
+
return { pubkey: i.pubkey, created_at: i.createdAt, kind: TICKET_KIND, tags, content: canonicalContent(i.content) };
|
|
81
|
+
}
|
|
82
|
+
export { CanonicalJsonError };
|
|
83
|
+
const FIELDS = ["id", "pubkey", "created_at", "kind", "tags", "content", "sig"];
|
|
84
|
+
/** The event has the seven NIP-01 fields and no other, each of the type the core parses. */
|
|
85
|
+
function wellFormed(e) {
|
|
86
|
+
if (e === null || typeof e !== "object" || Array.isArray(e))
|
|
87
|
+
return false;
|
|
88
|
+
const o = e;
|
|
89
|
+
const keys = Object.keys(o);
|
|
90
|
+
if (keys.length !== FIELDS.length || !FIELDS.every((f) => f in o))
|
|
91
|
+
return false;
|
|
92
|
+
const str = (v) => typeof v === "string" && isWellFormed(v);
|
|
93
|
+
return (str(o.id) &&
|
|
94
|
+
str(o.pubkey) &&
|
|
95
|
+
str(o.content) &&
|
|
96
|
+
str(o.sig) &&
|
|
97
|
+
Number.isSafeInteger(o.created_at) &&
|
|
98
|
+
o.created_at >= 0 &&
|
|
99
|
+
Number.isInteger(o.kind) &&
|
|
100
|
+
o.kind >= 0 &&
|
|
101
|
+
o.kind <= 0xffffffff &&
|
|
102
|
+
Array.isArray(o.tags) &&
|
|
103
|
+
o.tags.every((t) => Array.isArray(t) && t.every(str)));
|
|
104
|
+
}
|
|
105
|
+
function firstTag(tags, name) {
|
|
106
|
+
return tags.find((t) => t[0] === name)?.[1];
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* The core's envelope rules for an event already parsed (`Event::verify_shape`): kind 7411;
|
|
110
|
+
* `created_at` at most `FUTURE_SKEW_S` after `receivedAt` (only when it is given); every tag name
|
|
111
|
+
* one ASCII letter with a non-empty value; `w` (with a dot), `j`, `n` (unless the type may omit it),
|
|
112
|
+
* `v` and `c` (at most `CLIENT_ID_MAX` bytes) present; canonical content. Null when it passes.
|
|
113
|
+
*/
|
|
114
|
+
export function verifyShape(e, receivedAt) {
|
|
115
|
+
if (e.kind !== TICKET_KIND)
|
|
116
|
+
return "wrong_kind";
|
|
117
|
+
if (receivedAt !== undefined && e.created_at > receivedAt + FUTURE_SKEW_S)
|
|
118
|
+
return "future_timestamp";
|
|
119
|
+
for (const t of e.tags)
|
|
120
|
+
if (tagError(t))
|
|
121
|
+
return "bad_tag";
|
|
122
|
+
const w = firstTag(e.tags, TYPE_TAG);
|
|
123
|
+
if (w === undefined)
|
|
124
|
+
return "missing_tag";
|
|
125
|
+
if (!w.includes("."))
|
|
126
|
+
return "bad_tag";
|
|
127
|
+
if (firstTag(e.tags, "j") === undefined)
|
|
128
|
+
return "missing_tag";
|
|
129
|
+
if (!nodeTagOptional(w) && firstTag(e.tags, "n") === undefined)
|
|
130
|
+
return "missing_tag";
|
|
131
|
+
if (firstTag(e.tags, "v") === undefined)
|
|
132
|
+
return "missing_tag";
|
|
133
|
+
const c = firstTag(e.tags, "c");
|
|
134
|
+
if (c === undefined)
|
|
135
|
+
return "missing_tag";
|
|
136
|
+
if (utf8Length(c) > CLIENT_ID_MAX)
|
|
137
|
+
return "bad_tag";
|
|
138
|
+
if (!isCanonicalContent(e.content))
|
|
139
|
+
return "content_not_canonical";
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* The core's stateless check of one event, in its order, without the signature: the NIP-01 shape
|
|
144
|
+
* (`malformed`), the id (`bad_id`), then `verifyShape`. Null when it passes. A passing event can
|
|
145
|
+
* still carry a bad signature (`bad_signature`) and can still be refused by the log's state and
|
|
146
|
+
* policy rules.
|
|
147
|
+
*/
|
|
148
|
+
export async function verifyEvent(e, opts = {}) {
|
|
149
|
+
if (!wellFormed(e))
|
|
150
|
+
return "malformed";
|
|
151
|
+
if ((await eventId(e)) !== e.id)
|
|
152
|
+
return "bad_id";
|
|
153
|
+
return verifyShape(e, opts.receivedAt);
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Sign a template with `signer`, and check that the signer answered this template: the same key,
|
|
157
|
+
* fields and id. The signature itself is the signer's.
|
|
158
|
+
*/
|
|
159
|
+
export async function signEvent(signer, template) {
|
|
160
|
+
if (template.pubkey !== signer.pubkey)
|
|
161
|
+
throw new Error("the template names another key than the signer's");
|
|
162
|
+
const signed = await signer.sign(template);
|
|
163
|
+
const same = signed.pubkey === template.pubkey &&
|
|
164
|
+
signed.created_at === template.created_at &&
|
|
165
|
+
signed.kind === template.kind &&
|
|
166
|
+
signed.content === template.content &&
|
|
167
|
+
JSON.stringify(signed.tags) === JSON.stringify(template.tags);
|
|
168
|
+
if (!same || signed.id !== (await eventId(template)))
|
|
169
|
+
throw new Error("the signer answered another event than the template");
|
|
170
|
+
if (typeof signed.sig !== "string" || !/^[0-9a-f]{128}$/.test(signed.sig))
|
|
171
|
+
throw new Error("the signer answered no BIP-340 signature");
|
|
172
|
+
return { id: signed.id, pubkey: signed.pubkey, created_at: signed.created_at, kind: signed.kind, tags: signed.tags, content: signed.content, sig: signed.sig };
|
|
173
|
+
}
|