streamseed 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 (57) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +117 -2
  3. package/dist/control/control.d.ts +89 -0
  4. package/dist/control/control.js +396 -0
  5. package/dist/index.d.ts +19 -0
  6. package/dist/index.js +15 -0
  7. package/dist/internal/abort.d.ts +8 -0
  8. package/dist/internal/abort.js +52 -0
  9. package/dist/internal/cbor-codec.d.ts +25 -0
  10. package/dist/internal/cbor-codec.js +134 -0
  11. package/dist/internal/ed25519.d.ts +15 -0
  12. package/dist/internal/ed25519.js +55 -0
  13. package/dist/internal/secp256k1.d.ts +3 -0
  14. package/dist/internal/secp256k1.js +15 -0
  15. package/dist/manifest/cbor.d.ts +54 -0
  16. package/dist/manifest/cbor.js +306 -0
  17. package/dist/manifest/codec.d.ts +6 -0
  18. package/dist/manifest/codec.js +360 -0
  19. package/dist/manifest/constants.d.ts +2 -0
  20. package/dist/manifest/constants.js +2 -0
  21. package/dist/manifest/errors.d.ts +20 -0
  22. package/dist/manifest/errors.js +23 -0
  23. package/dist/manifest/index.d.ts +6 -0
  24. package/dist/manifest/index.js +6 -0
  25. package/dist/manifest/language.d.ts +4 -0
  26. package/dist/manifest/language.js +26 -0
  27. package/dist/manifest/types.d.ts +73 -0
  28. package/dist/manifest/types.js +2 -0
  29. package/dist/node/codec.d.ts +23 -0
  30. package/dist/node/codec.js +231 -0
  31. package/dist/node/document.d.ts +10 -0
  32. package/dist/node/document.js +123 -0
  33. package/dist/node/media.d.ts +6 -0
  34. package/dist/node/media.js +69 -0
  35. package/dist/node/sequence.d.ts +44 -0
  36. package/dist/node/sequence.js +137 -0
  37. package/dist/node/types.d.ts +93 -0
  38. package/dist/node/types.js +105 -0
  39. package/dist/program/codec.d.ts +10 -0
  40. package/dist/program/codec.js +165 -0
  41. package/dist/program/resolver.d.ts +25 -0
  42. package/dist/program/resolver.js +189 -0
  43. package/dist/program/types.d.ts +61 -0
  44. package/dist/program/types.js +90 -0
  45. package/dist/protocol/constants.d.ts +33 -0
  46. package/dist/protocol/constants.js +32 -0
  47. package/dist/protocol/errors.d.ts +46 -0
  48. package/dist/protocol/errors.js +57 -0
  49. package/dist/protocol/hash.d.ts +14 -0
  50. package/dist/protocol/hash.js +42 -0
  51. package/dist/protocol/ids.d.ts +60 -0
  52. package/dist/protocol/ids.js +139 -0
  53. package/dist/wire/artifact.d.ts +28 -0
  54. package/dist/wire/artifact.js +74 -0
  55. package/dist/wire/codec.d.ts +12 -0
  56. package/dist/wire/codec.js +42 -0
  57. package/package.json +92 -3
package/README.md CHANGED
@@ -1,3 +1,118 @@
1
- # Temporary Holding Version
1
+ # streamseed
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ StreamSeed V1 TypeScript SDK:发布者签名、无头、连续媒体块节点文件。核心只负责确定性 CBOR、MasterSeed Seed Hash、节点签名验证和按 hash 获取,不实现网络、供应商发现、缓存、播放器或 BitFS 采购。
4
+
5
+ 运行环境要求 Node.js `>=20` 或支持 ES2022/Web Crypto 的现代浏览器;核心二进制接口使用 `Uint8Array`,`publishedAtMs`、`nodeId` 和 `payloadSize` 使用 `bigint`。
6
+
7
+ ## 安装
8
+
9
+ ```sh
10
+ pnpm add streamseed
11
+ ```
12
+
13
+ ## 最小流程
14
+
15
+ ```ts
16
+ import {
17
+ NodeBuilder,
18
+ buildProgramObject,
19
+ newChannelPublicKey,
20
+ newReleaseSalt,
21
+ verifyNodeObject,
22
+ verifyProgramObject
23
+ } from "streamseed";
24
+ import type { NodeSigner } from "streamseed";
25
+
26
+ declare const signer: NodeSigner;
27
+ declare const coverBytes: Uint8Array;
28
+ declare const releaseSaltBytes: Uint8Array;
29
+ declare const channelKeyBytes: Uint8Array;
30
+
31
+ const program = await buildProgramObject({
32
+ name: "我的节目",
33
+ publishedAtMs: 1n,
34
+ nodePublisherKey: signer.publicKey(),
35
+ description: "简介",
36
+ coverMediaType: "image/jpeg",
37
+ coverBytes,
38
+ releaseSalt: newReleaseSalt(releaseSaltBytes),
39
+ channelPublisherKey: newChannelPublicKey(channelKeyBytes)
40
+ });
41
+
42
+ const builder = new NodeBuilder(program.streamId, signer);
43
+ const node = await builder.buildNextData([
44
+ new TextEncoder().encode("media block 0"),
45
+ new TextEncoder().encode("media block 1")
46
+ ]);
47
+ const verifiedProgram = await verifyProgramObject(program.streamId, program.bytes);
48
+ const verifiedNode = await verifyNodeObject(
49
+ node.objectBytes,
50
+ node.seedHash,
51
+ node.document.nodeId,
52
+ verifiedProgram
53
+ );
54
+ console.log(verifiedNode.mediaBlocks);
55
+ ```
56
+
57
+ `buildProgramObject`、`verifyProgramObject`、`decodeNode`、`parseArtifact` 和 `verifyNodeObject` 都是异步 API;官方 MasterSeed `createSeed` 需要对完整文件分块。`encodeProgramInfo`、`encodeNode` 和 `decodeProgramObject` 保持同步。
58
+
59
+ ## 媒体块与前序引用
60
+
61
+ DATA 的 `mediaContainer` 是 exact `[bstr, ...]` CBOR,`mediaBlocks` 返回其中的媒体块副本。`payloadSize`/`payloadHash` 绑定完整容器 CBOR,而不是拼接后的媒体字节。每个节点最多携带 64 条 `i-1, i-2, ...` 引用;每条引用是前序完整节点文件的 MasterSeed Seed Hash。
62
+
63
+ `NodeBuilder.state()` 返回下一序号、近期引用、sealed、exhausted 和引用数量;使用 `NodeBuilder.restore(streamId, signer, state)` 恢复。默认引用最近 16 条。
64
+
65
+ 宿主已经通过 BitFS 验收完整文件 Seed Hash 时,可调用同步的 `verifyNodeObjectWithSeedHash(data, seedHash, nodeId, verifiedProgram)` 避免重复计算 MasterSeed。普通场景应使用 `verifyNodeObject`。
66
+
67
+ ## 点对点控制
68
+
69
+ `buildProgramQuote`、`buildNodeRequest`、`buildControlError` 生成 `/streamseed/control/1.0.0` 上的确定性 CBOR 控制消息;`decodeControl` 严格解析,`verifyControl` 验证 strict-DER/low-S secp256k1 签名及认证 remote key。控制消息不进入普通 BitFS Artifact 流。
70
+
71
+ ## 获取 ProgramInfo
72
+
73
+ `resolveProgram(streamId, getter, signal?)` 返回已验证节目单。需要在供应商读取阶段限制内存时使用 `resolveProgramReader`,支持 `AsyncIterable<Uint8Array>` 和 `ReadableStream<Uint8Array>`。所有等待与 MasterSeed 计算都传播 `AbortSignal`,取消返回 `CANCELLED`。
74
+
75
+ ## 信任与复制
76
+
77
+ `VerifiedProgram` 只能由 SDK 验证流程生成;普通对象不能伪造。`VerifiedNode`、`DecodedNode`、`ProgramInfo`、`NodeDocument` 和 `Artifact` 的字节 getter 都返回深拷贝,包括封面、公钥、引用和媒体块。
78
+
79
+ 错误应读取 `StreamSeedError.code`。常见代码包括 `SEED_HASH_MISMATCH`、`STREAM_ID_MISMATCH`、`NODE_ID_MISMATCH`、`INVALID_REFERENCE`、`INVALID_MEDIA_CONTAINER`、`PAYLOAD_HASH_MISMATCH`、`SIGNATURE_MISMATCH`、`FIELD_TOO_LARGE` 和 `INVALID_VERIFIED_PROGRAM`。
80
+
81
+ ## 发布节目单
82
+
83
+ 静态与直播节目单从独立子路径导入,不与旧 `ProgramInfo` 入口混淆:
84
+
85
+ ```ts
86
+ import { encodeProgramManifest, decodeProgramManifest, normalizeLanguageTag } from "streamseed/manifest";
87
+ import type { LiveProgramManifest } from "streamseed/manifest";
88
+
89
+ declare const coverBytes: Uint8Array;
90
+ const manifest: LiveProgramManifest = {
91
+ schema: "bsv8.program-manifest",
92
+ version: 1,
93
+ kind: "live",
94
+ title: "城市夜景直播",
95
+ description: "",
96
+ cover: { mediaType: "image/png", data: coverBytes },
97
+ source: { transport: "streamseed", sessionId: "live_city_walk_01" },
98
+ tracks: {
99
+ video: [{ id: "main", width: 1920, height: 1080 }],
100
+ audio: [{ id: "ja-main", language: "ja" }],
101
+ subtitles: [{ id: "zh-sub", language: normalizeLanguageTag("ZH-hans-cn") }]
102
+ }
103
+ };
104
+ const bytes = encodeProgramManifest(manifest);
105
+ const decoded = decodeProgramManifest(bytes);
106
+ ```
107
+
108
+ `encodeProgramManifest` 和 `decodeProgramManifest` 是同步 API,输入输出使用 `Uint8Array`,封面不设固定大小上限。解码错误使用 `ProgramManifestError.code` 和 `path`;`path` 是 RFC 6901 JSON Pointer。
109
+
110
+ ## 本地开发
111
+
112
+ ```sh
113
+ pnpm install --frozen-lockfile
114
+ pnpm run build
115
+ pnpm run pack:check
116
+ ```
117
+
118
+ 生产包不提供本地私钥 signer。生产环境应实现 typed `NodeSigner` 并接入 Web Crypto、Vault、HSM 或远程签名服务;可运行 `examples/typescript-basic` 查看最小接入示例。
@@ -0,0 +1,89 @@
1
+ import { type ChannelPublicKey, type Digest, type NodeID } from "../protocol/ids.js";
2
+ export declare const CONTROL_PROTOCOL_ID = "/streamseed/control/1.0.0";
3
+ export declare const MAX_CONTROL_MESSAGE_BYTES: number;
4
+ export declare const CONTROL_SIGNATURE_DOMAIN = "streamseed/control-signature";
5
+ export declare const CONTROL_KIND_PROGRAM_QUOTE = 1;
6
+ export declare const CONTROL_KIND_NODE_REQUEST = 2;
7
+ export declare const CONTROL_KIND_CONTROL_ERROR = 3;
8
+ export type ControlKind = 1 | 2 | 3;
9
+ export declare const CONTROL_ERROR_CODES: {
10
+ readonly UNSUPPORTED_VERSION: "UNSUPPORTED_VERSION";
11
+ readonly MALFORMED_CONTROL: "MALFORMED_CONTROL";
12
+ readonly UNSUPPORTED_MESSAGE_KIND: "UNSUPPORTED_MESSAGE_KIND";
13
+ readonly INVALID_SIGNATURE: "INVALID_SIGNATURE";
14
+ readonly IDENTITY_MISMATCH: "IDENTITY_MISMATCH";
15
+ readonly INVALID_BODY: "INVALID_BODY";
16
+ readonly QUOTE_EXPIRED: "QUOTE_EXPIRED";
17
+ readonly REQUEST_BINDING_MISMATCH: "REQUEST_BINDING_MISMATCH";
18
+ readonly PROGRAM_NOT_FOUND: "PROGRAM_NOT_FOUND";
19
+ readonly PROGRAM_UNVERIFIED: "PROGRAM_UNVERIFIED";
20
+ readonly NODE_NOT_IN_PROGRAM: "NODE_NOT_IN_PROGRAM";
21
+ readonly CONTENT_UNAVAILABLE: "CONTENT_UNAVAILABLE";
22
+ readonly PRICE_MISMATCH: "PRICE_MISMATCH";
23
+ readonly ARCHIVE_INCOMPLETE: "ARCHIVE_INCOMPLETE";
24
+ readonly SEQUENCE_CONFLICT: "SEQUENCE_CONFLICT";
25
+ readonly RATE_LIMITED: "RATE_LIMITED";
26
+ readonly INTERNAL: "INTERNAL";
27
+ };
28
+ export type ControlErrorCode = (typeof CONTROL_ERROR_CODES)[keyof typeof CONTROL_ERROR_CODES];
29
+ export declare class ControlProtocolError extends Error {
30
+ readonly code: string;
31
+ constructor(code: string, message?: string, options?: {
32
+ cause?: unknown;
33
+ });
34
+ }
35
+ export interface ControlSigner {
36
+ publicKey(): ChannelPublicKey;
37
+ signDigest(digest: Uint8Array, signal?: AbortSignal): Promise<Uint8Array>;
38
+ }
39
+ export interface ProgramQuoteBody {
40
+ programSeedHash: Digest;
41
+ buyerPublicKey: ChannelPublicKey;
42
+ sellerPublicKey: ChannelPublicKey;
43
+ demandId: Uint8Array;
44
+ demandDigest: Digest;
45
+ expiresAtMs: bigint;
46
+ fullBlockPriceSatoshis: bigint;
47
+ hasEnd: boolean;
48
+ endNodeId: NodeID;
49
+ endNodeSeedHash: Digest;
50
+ }
51
+ export interface NodeRequestBody {
52
+ programSeedHash: Digest;
53
+ buyerPublicKey: ChannelPublicKey;
54
+ sellerPublicKey: ChannelPublicKey;
55
+ demandId: Uint8Array;
56
+ requestId: Uint8Array;
57
+ expiresAtMs: bigint;
58
+ quoteDigest: Digest;
59
+ nodeId: NodeID;
60
+ nodeSeedHash: Digest;
61
+ }
62
+ export interface ControlErrorBody {
63
+ buyerPublicKey: ChannelPublicKey;
64
+ sellerPublicKey: ChannelPublicKey;
65
+ requestId: Uint8Array;
66
+ code: ControlErrorCode;
67
+ }
68
+ declare const MESSAGE_TOKEN: unique symbol;
69
+ export declare class ControlMessage {
70
+ #private;
71
+ /** @internal */
72
+ constructor(kind: ControlKind, quote: ProgramQuoteBody | undefined, request: NodeRequestBody | undefined, errorBody: ControlErrorBody | undefined, bodyBytes: Uint8Array, signature: Uint8Array, bytes: Uint8Array, verified: boolean, token: typeof MESSAGE_TOKEN);
73
+ get kind(): ControlKind;
74
+ get isVerified(): boolean;
75
+ get bytes(): Uint8Array;
76
+ get bodyBytes(): Uint8Array;
77
+ get signature(): Uint8Array;
78
+ get quote(): ProgramQuoteBody | undefined;
79
+ get request(): NodeRequestBody | undefined;
80
+ get errorBody(): ControlErrorBody | undefined;
81
+ }
82
+ export declare function buildProgramQuote(body: ProgramQuoteBody, signer: ControlSigner, signal?: AbortSignal): Promise<ControlMessage>;
83
+ export declare function buildNodeRequest(body: NodeRequestBody, signer: ControlSigner, signal?: AbortSignal): Promise<ControlMessage>;
84
+ export declare function buildControlError(body: ControlErrorBody, signer: ControlSigner, signal?: AbortSignal): Promise<ControlMessage>;
85
+ export declare function decodeControl(data: Uint8Array): ControlMessage;
86
+ export declare function controlSignatureInput(kind: ControlKind, exactBodyCBOR: Uint8Array): Uint8Array;
87
+ export declare function verifyControl(data: Uint8Array, expectedKind: ControlKind, remoteKey: Uint8Array): ControlMessage;
88
+ export {};
89
+ //# sourceMappingURL=control.d.ts.map
@@ -0,0 +1,396 @@
1
+ import { sha256 } from "../protocol/hash.js";
2
+ import { CHANNEL_PUBLIC_KEY_SIZE } from "../protocol/constants.js";
3
+ import { assertNodeID, bytesEqual, copyBytes, newChannelPublicKey, newDigest } from "../protocol/ids.js";
4
+ import { CBORDecoder, CBOREncoder } from "../internal/cbor-codec.js";
5
+ import { awaitWithAbort } from "../internal/abort.js";
6
+ import { secp256k1 } from "@noble/curves/secp256k1.js";
7
+ export const CONTROL_PROTOCOL_ID = "/streamseed/control/1.0.0";
8
+ export const MAX_CONTROL_MESSAGE_BYTES = 64 * 1024;
9
+ export const CONTROL_SIGNATURE_DOMAIN = "streamseed/control-signature";
10
+ const QUOTE_DOMAIN = "streamseed/program-quote";
11
+ const REQUEST_DOMAIN = "streamseed/node-request";
12
+ const ERROR_DOMAIN = "streamseed/control-error";
13
+ export const CONTROL_KIND_PROGRAM_QUOTE = 1;
14
+ export const CONTROL_KIND_NODE_REQUEST = 2;
15
+ export const CONTROL_KIND_CONTROL_ERROR = 3;
16
+ export const CONTROL_ERROR_CODES = {
17
+ UNSUPPORTED_VERSION: "UNSUPPORTED_VERSION",
18
+ MALFORMED_CONTROL: "MALFORMED_CONTROL",
19
+ UNSUPPORTED_MESSAGE_KIND: "UNSUPPORTED_MESSAGE_KIND",
20
+ INVALID_SIGNATURE: "INVALID_SIGNATURE",
21
+ IDENTITY_MISMATCH: "IDENTITY_MISMATCH",
22
+ INVALID_BODY: "INVALID_BODY",
23
+ QUOTE_EXPIRED: "QUOTE_EXPIRED",
24
+ REQUEST_BINDING_MISMATCH: "REQUEST_BINDING_MISMATCH",
25
+ PROGRAM_NOT_FOUND: "PROGRAM_NOT_FOUND",
26
+ PROGRAM_UNVERIFIED: "PROGRAM_UNVERIFIED",
27
+ NODE_NOT_IN_PROGRAM: "NODE_NOT_IN_PROGRAM",
28
+ CONTENT_UNAVAILABLE: "CONTENT_UNAVAILABLE",
29
+ PRICE_MISMATCH: "PRICE_MISMATCH",
30
+ ARCHIVE_INCOMPLETE: "ARCHIVE_INCOMPLETE",
31
+ SEQUENCE_CONFLICT: "SEQUENCE_CONFLICT",
32
+ RATE_LIMITED: "RATE_LIMITED",
33
+ INTERNAL: "INTERNAL"
34
+ };
35
+ export class ControlProtocolError extends Error {
36
+ code;
37
+ constructor(code, message, options) {
38
+ super(message ?? code, options);
39
+ this.name = "ControlProtocolError";
40
+ this.code = code;
41
+ }
42
+ }
43
+ function controlError(code, message, cause) {
44
+ return cause === undefined ? new ControlProtocolError(code, message) : new ControlProtocolError(code, message, { cause });
45
+ }
46
+ const MESSAGE_TOKEN = Symbol("streamseed.control-message");
47
+ export class ControlMessage {
48
+ #kind;
49
+ #quote;
50
+ #request;
51
+ #errorBody;
52
+ #bodyBytes;
53
+ #signature;
54
+ #bytes;
55
+ #verified;
56
+ /** @internal */
57
+ constructor(kind, quote, request, errorBody, bodyBytes, signature, bytes, verified, token) {
58
+ if (token !== MESSAGE_TOKEN)
59
+ throw new TypeError("ControlMessage must be created by the StreamSeed control codec");
60
+ this.#kind = kind;
61
+ this.#quote = quote === undefined ? undefined : cloneQuote(quote);
62
+ this.#request = request === undefined ? undefined : cloneRequest(request);
63
+ this.#errorBody = errorBody === undefined ? undefined : cloneError(errorBody);
64
+ this.#bodyBytes = copyBytes(bodyBytes);
65
+ this.#signature = copyBytes(signature);
66
+ this.#bytes = copyBytes(bytes);
67
+ this.#verified = verified;
68
+ Object.freeze(this);
69
+ }
70
+ get kind() { return this.#kind; }
71
+ get isVerified() { return this.#verified; }
72
+ get bytes() { return copyBytes(this.#bytes); }
73
+ get bodyBytes() { return copyBytes(this.#bodyBytes); }
74
+ get signature() { return copyBytes(this.#signature); }
75
+ get quote() { return this.#quote === undefined ? undefined : cloneQuote(this.#quote); }
76
+ get request() { return this.#request === undefined ? undefined : cloneRequest(this.#request); }
77
+ get errorBody() { return this.#errorBody === undefined ? undefined : cloneError(this.#errorBody); }
78
+ }
79
+ Object.freeze(ControlMessage.prototype);
80
+ export async function buildProgramQuote(body, signer, signal) {
81
+ return build(CONTROL_KIND_PROGRAM_QUOTE, encodeQuote(body), body.sellerPublicKey, signer, signal);
82
+ }
83
+ export async function buildNodeRequest(body, signer, signal) {
84
+ return build(CONTROL_KIND_NODE_REQUEST, encodeRequest(body), body.buyerPublicKey, signer, signal);
85
+ }
86
+ export async function buildControlError(body, signer, signal) {
87
+ return build(CONTROL_KIND_CONTROL_ERROR, encodeError(body), body.sellerPublicKey, signer, signal);
88
+ }
89
+ export function decodeControl(data) {
90
+ try {
91
+ return decodeControlValue(data);
92
+ }
93
+ catch (error) {
94
+ if (error instanceof ControlProtocolError)
95
+ throw error;
96
+ throw controlError("MALFORMED_CONTROL", "malformed StreamSeed control message", error);
97
+ }
98
+ }
99
+ function decodeControlValue(data) {
100
+ if (data.length === 0 || data.length > MAX_CONTROL_MESSAGE_BYTES)
101
+ throw controlError("MALFORMED_CONTROL", `control message size ${data.length}`);
102
+ const snapshot = copyBytes(data);
103
+ const input = new CBORDecoder(snapshot, BigInt(MAX_CONTROL_MESSAGE_BYTES));
104
+ if (input.array() !== 4)
105
+ throw controlError("MALFORMED_CONTROL", "control envelope must contain 4 items");
106
+ if (input.uint() !== 1n)
107
+ throw controlError("UNSUPPORTED_VERSION", "unsupported control version");
108
+ const kindValue = input.uint();
109
+ if (kindValue !== 1n && kindValue !== 2n && kindValue !== 3n)
110
+ throw controlError("UNSUPPORTED_MESSAGE_KIND", `unsupported control kind ${kindValue}`);
111
+ const kind = Number(kindValue);
112
+ const bodyBytes = input.bytes(MAX_CONTROL_MESSAGE_BYTES);
113
+ const signature = input.bytes(72);
114
+ if (signature.length < 8 || signature.length > 72)
115
+ throw controlError("INVALID_SIGNATURE", `DER signature length ${signature.length}`);
116
+ input.requireEOF();
117
+ let quote;
118
+ let request;
119
+ let errorBody;
120
+ if (kind === CONTROL_KIND_PROGRAM_QUOTE)
121
+ quote = decodeQuote(bodyBytes);
122
+ else if (kind === CONTROL_KIND_NODE_REQUEST)
123
+ request = decodeRequest(bodyBytes);
124
+ else
125
+ errorBody = decodeError(bodyBytes);
126
+ const canonical = encodeEnvelope(kind, bodyBytes, signature);
127
+ if (!bytesEqual(canonical, snapshot))
128
+ throw controlError("MALFORMED_CONTROL", "control message is not canonical CBOR");
129
+ return new ControlMessage(kind, quote, request, errorBody, bodyBytes, signature, snapshot, false, MESSAGE_TOKEN);
130
+ }
131
+ export function controlSignatureInput(kind, exactBodyCBOR) {
132
+ if (kind !== CONTROL_KIND_PROGRAM_QUOTE && kind !== CONTROL_KIND_NODE_REQUEST && kind !== CONTROL_KIND_CONTROL_ERROR) {
133
+ throw controlError("UNSUPPORTED_MESSAGE_KIND", `unsupported control kind ${kind}`);
134
+ }
135
+ if (exactBodyCBOR.length === 0 || exactBodyCBOR.length > MAX_CONTROL_MESSAGE_BYTES) {
136
+ throw controlError("INVALID_BODY", `control body size ${exactBodyCBOR.length}`);
137
+ }
138
+ decodeControl(encodeEnvelope(kind, exactBodyCBOR, new Uint8Array(64)));
139
+ return signatureInput(kind, exactBodyCBOR);
140
+ }
141
+ export function verifyControl(data, expectedKind, remoteKey) {
142
+ const message = decodeControl(data);
143
+ if (message.kind !== expectedKind)
144
+ throw controlError("UNSUPPORTED_MESSAGE_KIND", `expected control kind ${expectedKind}, got ${message.kind}`);
145
+ const remote = readRemoteKey(remoteKey);
146
+ const signingKey = message.kind === CONTROL_KIND_PROGRAM_QUOTE
147
+ ? message.quote.sellerPublicKey
148
+ : message.kind === CONTROL_KIND_NODE_REQUEST
149
+ ? message.request.buyerPublicKey
150
+ : message.errorBody.sellerPublicKey;
151
+ if (!bytesEqual(signingKey, remote))
152
+ throw controlError("IDENTITY_MISMATCH", "control signing key does not match authenticated remote");
153
+ const digest = sha256(signatureInput(message.kind, message.bodyBytes));
154
+ let valid = false;
155
+ try {
156
+ valid = secp256k1.verify(message.signature, digest, signingKey, { format: "der", prehash: false, lowS: true });
157
+ }
158
+ catch {
159
+ valid = false;
160
+ }
161
+ if (!valid)
162
+ throw controlError("INVALID_SIGNATURE", "control signature verification failed");
163
+ return new ControlMessage(message.kind, message.quote, message.request, message.errorBody, message.bodyBytes, message.signature, message.bytes, true, MESSAGE_TOKEN);
164
+ }
165
+ async function build(kind, bodyBytes, signingKey, signer, signal) {
166
+ if (signal?.aborted)
167
+ throw controlError("CANCELLED", "control signing was aborted");
168
+ if (!signer || typeof signer.publicKey !== "function" || typeof signer.signDigest !== "function")
169
+ throw controlError("SIGNER_FAILURE", "invalid control signer");
170
+ const keySnapshot = copyBytes(signingKey);
171
+ if (!bytesEqual(signer.publicKey(), keySnapshot))
172
+ throw controlError("IDENTITY_MISMATCH", "control body key does not match signer");
173
+ // Validate the complete body before requesting an external signature.
174
+ decodeControl(encodeEnvelope(kind, bodyBytes, new Uint8Array(64)));
175
+ const digest = sha256(signatureInput(kind, bodyBytes));
176
+ let signature;
177
+ try {
178
+ signature = await awaitWithAbort(signer.signDigest(digest, signal), signal);
179
+ }
180
+ catch (error) {
181
+ if (signal?.aborted || (typeof DOMException !== "undefined" && error instanceof DOMException && error.name === "AbortError")) {
182
+ throw controlError("CANCELLED", "control signing was aborted", error);
183
+ }
184
+ throw controlError("SIGNER_FAILURE", "control signer failed", error);
185
+ }
186
+ if (signal?.aborted)
187
+ throw controlError("CANCELLED", "control signing was aborted");
188
+ const message = decodeControl(encodeEnvelope(kind, bodyBytes, signature));
189
+ return verifyControl(message.bytes, kind, keySnapshot);
190
+ }
191
+ function encodeEnvelope(kind, bodyBytes, signature) {
192
+ const output = new CBOREncoder();
193
+ output.array(4);
194
+ output.uint(1n);
195
+ output.uint(BigInt(kind));
196
+ output.bytes(bodyBytes);
197
+ output.bytes(signature);
198
+ return output.finish();
199
+ }
200
+ function signatureInput(kind, bodyBytes) {
201
+ const output = new CBOREncoder();
202
+ output.array(4);
203
+ output.text(CONTROL_SIGNATURE_DOMAIN);
204
+ output.uint(1n);
205
+ output.uint(BigInt(kind));
206
+ output.bytes(bodyBytes);
207
+ return output.finish();
208
+ }
209
+ function encodeQuote(body) {
210
+ const output = new CBOREncoder();
211
+ output.array(12);
212
+ output.text(QUOTE_DOMAIN);
213
+ output.uint(2n);
214
+ output.bytes(body.programSeedHash);
215
+ output.bytes(body.buyerPublicKey);
216
+ output.bytes(body.sellerPublicKey);
217
+ output.bytes(body.demandId);
218
+ output.bytes(body.demandDigest);
219
+ output.uint(body.expiresAtMs);
220
+ output.uint(body.fullBlockPriceSatoshis);
221
+ output.uint(body.hasEnd ? 1n : 0n);
222
+ output.uint(body.endNodeId);
223
+ output.bytes(body.endNodeSeedHash);
224
+ return output.finish();
225
+ }
226
+ function decodeQuote(data) {
227
+ const input = new CBORDecoder(data, BigInt(MAX_CONTROL_MESSAGE_BYTES));
228
+ if (input.array() !== 12)
229
+ throw controlError("INVALID_BODY", "program quote body must contain 12 items");
230
+ if (input.text(64) !== QUOTE_DOMAIN)
231
+ throw controlError("INVALID_BODY", "unexpected program quote domain");
232
+ if (input.uint() !== 2n)
233
+ throw controlError("INVALID_BODY", "program quote type must be stream");
234
+ const body = {
235
+ programSeedHash: readDigest(input),
236
+ buyerPublicKey: readChannelKey(input),
237
+ sellerPublicKey: readChannelKey(input),
238
+ demandId: readID(input),
239
+ demandDigest: readDigest(input),
240
+ expiresAtMs: input.uint(),
241
+ fullBlockPriceSatoshis: input.uint(),
242
+ hasEnd: false,
243
+ endNodeId: 0n,
244
+ endNodeSeedHash: newDigest(new Uint8Array(32))
245
+ };
246
+ const hasEnd = input.uint();
247
+ if (hasEnd !== 0n && hasEnd !== 1n)
248
+ throw controlError("INVALID_BODY", "hasEnd must be 0 or 1");
249
+ body.hasEnd = hasEnd === 1n;
250
+ body.endNodeId = input.uint();
251
+ assertNodeID(body.endNodeId);
252
+ body.endNodeSeedHash = readDigest(input);
253
+ input.requireEOF();
254
+ if (!body.hasEnd && (body.endNodeId !== 0n || !bytesEqual(body.endNodeSeedHash, new Uint8Array(32)))) {
255
+ throw controlError("INVALID_BODY", "non-archive quote END fields must be zero");
256
+ }
257
+ if (!bytesEqual(encodeQuote(body), data))
258
+ throw controlError("MALFORMED_CONTROL", "program quote body is not canonical CBOR");
259
+ return body;
260
+ }
261
+ function encodeRequest(body) {
262
+ const output = new CBOREncoder();
263
+ output.array(10);
264
+ output.text(REQUEST_DOMAIN);
265
+ output.bytes(body.programSeedHash);
266
+ output.bytes(body.buyerPublicKey);
267
+ output.bytes(body.sellerPublicKey);
268
+ output.bytes(body.demandId);
269
+ output.bytes(body.requestId);
270
+ output.uint(body.expiresAtMs);
271
+ output.bytes(body.quoteDigest);
272
+ output.uint(body.nodeId);
273
+ output.bytes(body.nodeSeedHash);
274
+ return output.finish();
275
+ }
276
+ function decodeRequest(data) {
277
+ const input = new CBORDecoder(data, BigInt(MAX_CONTROL_MESSAGE_BYTES));
278
+ if (input.array() !== 10)
279
+ throw controlError("INVALID_BODY", "node request body must contain 10 items");
280
+ if (input.text(64) !== REQUEST_DOMAIN)
281
+ throw controlError("INVALID_BODY", "unexpected node request domain");
282
+ const body = {
283
+ programSeedHash: readDigest(input),
284
+ buyerPublicKey: readChannelKey(input),
285
+ sellerPublicKey: readChannelKey(input),
286
+ demandId: readID(input),
287
+ requestId: readID(input),
288
+ expiresAtMs: input.uint(),
289
+ quoteDigest: readDigest(input),
290
+ nodeId: 0n,
291
+ nodeSeedHash: newDigest(new Uint8Array(32))
292
+ };
293
+ body.nodeId = input.uint();
294
+ assertNodeID(body.nodeId);
295
+ body.nodeSeedHash = readDigest(input);
296
+ input.requireEOF();
297
+ if (!bytesEqual(encodeRequest(body), data))
298
+ throw controlError("MALFORMED_CONTROL", "node request body is not canonical CBOR");
299
+ return body;
300
+ }
301
+ function encodeError(body) {
302
+ const output = new CBOREncoder();
303
+ output.array(5);
304
+ output.text(ERROR_DOMAIN);
305
+ output.bytes(body.buyerPublicKey);
306
+ output.bytes(body.sellerPublicKey);
307
+ output.bytes(body.requestId);
308
+ output.text(body.code);
309
+ return output.finish();
310
+ }
311
+ function decodeError(data) {
312
+ const input = new CBORDecoder(data, BigInt(MAX_CONTROL_MESSAGE_BYTES));
313
+ if (input.array() !== 5)
314
+ throw controlError("INVALID_BODY", "control error body must contain 5 items");
315
+ if (input.text(64) !== ERROR_DOMAIN)
316
+ throw controlError("INVALID_BODY", "unexpected control error domain");
317
+ const body = {
318
+ buyerPublicKey: readChannelKey(input),
319
+ sellerPublicKey: readChannelKey(input),
320
+ requestId: readID(input),
321
+ code: "INTERNAL"
322
+ };
323
+ const code = input.text(64);
324
+ if (!Object.values(CONTROL_ERROR_CODES).includes(code))
325
+ throw controlError("INVALID_BODY", `unknown control error code ${code}`);
326
+ body.code = code;
327
+ input.requireEOF();
328
+ if (!bytesEqual(encodeError(body), data))
329
+ throw controlError("MALFORMED_CONTROL", "control error body is not canonical CBOR");
330
+ return body;
331
+ }
332
+ function readDigest(input) {
333
+ const value = input.bytes(32);
334
+ if (value.length !== 32)
335
+ throw controlError("INVALID_BODY", "digest must be 32 bytes");
336
+ return newDigest(value);
337
+ }
338
+ function readChannelKey(input) {
339
+ const value = input.bytes(CHANNEL_PUBLIC_KEY_SIZE);
340
+ try {
341
+ return newChannelPublicKey(value);
342
+ }
343
+ catch (error) {
344
+ throw controlError("INVALID_BODY", "invalid Channel public key", error);
345
+ }
346
+ }
347
+ function readRemoteKey(value) {
348
+ try {
349
+ return newChannelPublicKey(value);
350
+ }
351
+ catch (error) {
352
+ throw controlError("IDENTITY_MISMATCH", "invalid authenticated remote key", error);
353
+ }
354
+ }
355
+ function readID(input) {
356
+ const value = input.bytes(32);
357
+ if (value.length !== 32)
358
+ throw controlError("INVALID_BODY", "ID must be 32 bytes");
359
+ return value;
360
+ }
361
+ function cloneQuote(body) {
362
+ return {
363
+ programSeedHash: copyBytes(body.programSeedHash),
364
+ buyerPublicKey: copyBytes(body.buyerPublicKey),
365
+ sellerPublicKey: copyBytes(body.sellerPublicKey),
366
+ demandId: copyBytes(body.demandId),
367
+ demandDigest: copyBytes(body.demandDigest),
368
+ expiresAtMs: body.expiresAtMs,
369
+ fullBlockPriceSatoshis: body.fullBlockPriceSatoshis,
370
+ hasEnd: body.hasEnd,
371
+ endNodeId: body.endNodeId,
372
+ endNodeSeedHash: copyBytes(body.endNodeSeedHash)
373
+ };
374
+ }
375
+ function cloneRequest(body) {
376
+ return {
377
+ programSeedHash: copyBytes(body.programSeedHash),
378
+ buyerPublicKey: copyBytes(body.buyerPublicKey),
379
+ sellerPublicKey: copyBytes(body.sellerPublicKey),
380
+ demandId: copyBytes(body.demandId),
381
+ requestId: copyBytes(body.requestId),
382
+ expiresAtMs: body.expiresAtMs,
383
+ quoteDigest: copyBytes(body.quoteDigest),
384
+ nodeId: body.nodeId,
385
+ nodeSeedHash: copyBytes(body.nodeSeedHash)
386
+ };
387
+ }
388
+ function cloneError(body) {
389
+ return {
390
+ buyerPublicKey: copyBytes(body.buyerPublicKey),
391
+ sellerPublicKey: copyBytes(body.sellerPublicKey),
392
+ requestId: copyBytes(body.requestId),
393
+ code: body.code
394
+ };
395
+ }
396
+ //# sourceMappingURL=control.js.map
@@ -0,0 +1,19 @@
1
+ export * from "./protocol/constants.js";
2
+ export * from "./protocol/errors.js";
3
+ export * from "./protocol/ids.js";
4
+ export { sha256, sha512, masterSeedHash } from "./protocol/hash.js";
5
+ export { DecodedProgram, ProgramObject, VerifiedProgram } from "./program/types.js";
6
+ export type { ProgramInfo } from "./program/types.js";
7
+ export { buildProgramObject, encodeProgramInfo, decodeProgramObject, verifyProgramObject } from "./program/codec.js";
8
+ export { resolveProgram, resolveProgramWithMaxBytes, resolveProgramReader } from "./program/resolver.js";
9
+ export type { ByteStream, GetByHash, GetByHashReader } from "./program/resolver.js";
10
+ export { DecodedNode, VerifiedNode } from "./node/types.js";
11
+ export type { BuiltNode, NodeDocument, NodeFields, NodeRef, NodeSigner, NodeSigningFields } from "./node/types.js";
12
+ export { encodeNodeDocument, decodeNodeDocument, buildNodeSignatureInput } from "./node/document.js";
13
+ export { buildDataNode, buildEndNode, encodeDataNode, encodeEndNode, encodeNode, decodeNode, verifyNodeObject, verifyNodeObjectWithSeedHash } from "./node/codec.js";
14
+ export { NodeBuilder } from "./node/sequence.js";
15
+ export type { NodeBuilderState } from "./node/sequence.js";
16
+ export * from "./control/control.js";
17
+ export { Artifact } from "./wire/artifact.js";
18
+ export { parseArtifact, parseArtifactAs, readVersionKind } from "./wire/codec.js";
19
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,15 @@
1
+ export * from "./protocol/constants.js";
2
+ export * from "./protocol/errors.js";
3
+ export * from "./protocol/ids.js";
4
+ export { sha256, sha512, masterSeedHash } from "./protocol/hash.js";
5
+ export { DecodedProgram, ProgramObject, VerifiedProgram } from "./program/types.js";
6
+ export { buildProgramObject, encodeProgramInfo, decodeProgramObject, verifyProgramObject } from "./program/codec.js";
7
+ export { resolveProgram, resolveProgramWithMaxBytes, resolveProgramReader } from "./program/resolver.js";
8
+ export { DecodedNode, VerifiedNode } from "./node/types.js";
9
+ export { encodeNodeDocument, decodeNodeDocument, buildNodeSignatureInput } from "./node/document.js";
10
+ export { buildDataNode, buildEndNode, encodeDataNode, encodeEndNode, encodeNode, decodeNode, verifyNodeObject, verifyNodeObjectWithSeedHash } from "./node/codec.js";
11
+ export { NodeBuilder } from "./node/sequence.js";
12
+ export * from "./control/control.js";
13
+ export { Artifact } from "./wire/artifact.js";
14
+ export { parseArtifact, parseArtifactAs, readVersionKind } from "./wire/codec.js";
15
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,8 @@
1
+ /**
2
+ * 等待可取消的异步操作。
3
+ *
4
+ * AbortSignal 不能强制终止外部 Promise 的执行,但可以让 SDK 的等待方立即结束;
5
+ * 调用方若拥有底层资源,还应在 abort 监听器中主动关闭该资源。
6
+ */
7
+ export declare function awaitWithAbort<T>(promise: PromiseLike<T>, signal?: AbortSignal): Promise<T>;
8
+ //# sourceMappingURL=abort.d.ts.map