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
@@ -0,0 +1,93 @@
1
+ import { type Digest, type NodeID, type PublicKey, type Signature, type StreamID } from "../protocol/ids.js";
2
+ import type { WireKind } from "../protocol/constants.js";
3
+ /** 指向同一节目中一个已提交节点的完整文件 MasterSeed Seed Hash。 */
4
+ export interface NodeRef {
5
+ /** 被引用节点的序号。 */
6
+ nodeId: NodeID;
7
+ /** 被引用完整节点文件的 32 字节 MasterSeed Seed Hash。 */
8
+ seedHash: Digest;
9
+ }
10
+ /** 构造 Node 时的公共定位字段。 */
11
+ export interface NodeFields {
12
+ /** Node 所属的 stream ID。 */
13
+ streamId: StreamID;
14
+ /** Node 在 stream 中的 bigint 编号。 */
15
+ nodeId: NodeID;
16
+ /** 必须与 signer.publicKey() 相同。 */
17
+ publisherPublicKey: PublicKey;
18
+ /** 严格降序的紧邻前序引用;序号 0 必须为空。 */
19
+ refs: readonly NodeRef[];
20
+ }
21
+ /** DATA/END 共用的六元认证子文档。 */
22
+ export interface NodeDocument {
23
+ /** Node 所属的 stream ID。 */
24
+ streamId: StreamID;
25
+ /** 从 0 开始递增的 Node 编号。 */
26
+ nodeId: NodeID;
27
+ /** 签署此 Node 的 Ed25519 公钥。 */
28
+ publisherPublicKey: PublicKey;
29
+ /** exact media-container CBOR 的完整字节数;END 必须为 0。 */
30
+ payloadSize: bigint;
31
+ /** exact media-container CBOR 的 SHA-256;END 必须是 SHA-256(empty)。 */
32
+ payloadHash: Digest;
33
+ /** 最多 64 条严格降序的紧邻前序引用。 */
34
+ refs: NodeRef[];
35
+ }
36
+ /** typed signer 收到的结构化签名字段。 */
37
+ export interface NodeSigningFields {
38
+ /** 2=DATA,3=END,防止跨 Kind 换壳。 */
39
+ kind: Exclude<WireKind, 1>;
40
+ /** 待签名的认证子文档。 */
41
+ document: NodeDocument;
42
+ }
43
+ declare const DECODED_NODE_TOKEN: unique symbol;
44
+ /** 严格解析但尚未绑定目标 ProgramInfo 或签名信任的 Node;byte getter 返回副本。 */
45
+ export declare class DecodedNode {
46
+ #private;
47
+ /** @internal 只有 node codec 通过模块内 token 创建实例。 */
48
+ constructor(kind: Exclude<WireKind, 1>, document: NodeDocument, documentBytes: Uint8Array, signature: Signature, seedHash: Digest, mediaContainer: Uint8Array | undefined, mediaBlocks: Uint8Array[] | undefined, objectBytes: Uint8Array, token: typeof DECODED_NODE_TOKEN);
49
+ get kind(): Exclude<WireKind, 1>;
50
+ get document(): NodeDocument;
51
+ get documentBytes(): Uint8Array;
52
+ get signature(): Signature;
53
+ get seedHash(): Digest;
54
+ get mediaContainer(): Uint8Array | undefined;
55
+ get mediaBlocks(): Uint8Array[] | undefined;
56
+ /** 保留为 mediaContainer 的兼容名称。 */
57
+ get payload(): Uint8Array | undefined;
58
+ get objectBytes(): Uint8Array;
59
+ }
60
+ /** 构造成功且已对 signer 返回的签名做本地复验的 Node。 */
61
+ export type BuiltNode = DecodedNode;
62
+ /** @internal 供 node codec 使用;不从 SDK 根入口导出。 */
63
+ export declare function createDecodedNode(kind: Exclude<WireKind, 1>, document: NodeDocument, documentBytes: Uint8Array, signature: Signature, seedHash: Digest, mediaContainer: Uint8Array | undefined, mediaBlocks: Uint8Array[] | undefined, objectBytes: Uint8Array): DecodedNode;
64
+ declare const VERIFIED_NODE_TOKEN: unique symbol;
65
+ /** 已绑定期望 Seed Hash、序号、ProgramInfo 公钥并通过签名验证的 Node。 */
66
+ export declare class VerifiedNode {
67
+ #private;
68
+ /** @internal 只有 verifyNodeObject 通过模块内 token 创建实例。 */
69
+ constructor(kind: Exclude<WireKind, 1>, document: NodeDocument, documentBytes: Uint8Array, signature: Signature, seedHash: Digest, mediaContainer: Uint8Array | undefined, mediaBlocks: Uint8Array[] | undefined, objectBytes: Uint8Array, token: typeof VERIFIED_NODE_TOKEN);
70
+ get kind(): Exclude<WireKind, 1>;
71
+ get document(): NodeDocument;
72
+ get documentBytes(): Uint8Array;
73
+ get signature(): Signature;
74
+ get seedHash(): Digest;
75
+ get mediaContainer(): Uint8Array | undefined;
76
+ get mediaBlocks(): Uint8Array[] | undefined;
77
+ /** 保留为 mediaContainer 的兼容名称。 */
78
+ get payload(): Uint8Array | undefined;
79
+ get objectBytes(): Uint8Array;
80
+ }
81
+ /** @internal 供 node codec 使用;不从 SDK 根入口导出。 */
82
+ export declare function createVerifiedNode(kind: Exclude<WireKind, 1>, document: NodeDocument, documentBytes: Uint8Array, signature: Signature, seedHash: Digest, mediaContainer: Uint8Array | undefined, mediaBlocks: Uint8Array[] | undefined, objectBytes: Uint8Array): VerifiedNode;
83
+ /** 判断值是否为 SDK verifyNodeObject 生成的实例。 */
84
+ export declare function isVerifiedNode(value: unknown): value is VerifiedNode;
85
+ /** NodeSigner 是可由本地私钥、Worker、Vault 或 HSM 实现的异步窄接口。 */
86
+ export interface NodeSigner {
87
+ /** 返回 signer 公钥的独立副本。 */
88
+ publicKey(): PublicKey;
89
+ /** 根据结构化字段签署唯一的 V1 域分离消息。 */
90
+ signNode(fields: NodeSigningFields, signal?: AbortSignal): Promise<Signature>;
91
+ }
92
+ export {};
93
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1,105 @@
1
+ import { cloneMediaBlocks } from "./media.js";
2
+ import { copyBytes } from "../protocol/ids.js";
3
+ const DECODED_NODE_TOKEN = Symbol("streamseed.decoded-node");
4
+ /** 严格解析但尚未绑定目标 ProgramInfo 或签名信任的 Node;byte getter 返回副本。 */
5
+ export class DecodedNode {
6
+ #storedKind;
7
+ #storedDocument;
8
+ #storedDocumentBytes;
9
+ #storedSignature;
10
+ #storedSeedHash;
11
+ #storedMediaContainer;
12
+ #storedMediaBlocks;
13
+ #storedObjectBytes;
14
+ /** @internal 只有 node codec 通过模块内 token 创建实例。 */
15
+ constructor(kind, document, documentBytes, signature, seedHash, mediaContainer, mediaBlocks, objectBytes, token) {
16
+ if (token !== DECODED_NODE_TOKEN)
17
+ throw new TypeError("DecodedNode must be created by node codec");
18
+ this.#storedKind = kind;
19
+ this.#storedDocument = cloneDocument(document);
20
+ this.#storedDocumentBytes = copyBytes(documentBytes);
21
+ this.#storedSignature = copyBytes(signature);
22
+ this.#storedSeedHash = copyBytes(seedHash);
23
+ this.#storedMediaContainer = mediaContainer === undefined ? undefined : copyBytes(mediaContainer);
24
+ this.#storedMediaBlocks = cloneMediaBlocks(mediaBlocks);
25
+ this.#storedObjectBytes = copyBytes(objectBytes);
26
+ Object.freeze(this);
27
+ }
28
+ get kind() { return this.#storedKind; }
29
+ get document() { return cloneDocument(this.#storedDocument); }
30
+ get documentBytes() { return copyBytes(this.#storedDocumentBytes); }
31
+ get signature() { return copyBytes(this.#storedSignature); }
32
+ get seedHash() { return copyBytes(this.#storedSeedHash); }
33
+ get mediaContainer() {
34
+ return this.#storedMediaContainer === undefined ? undefined : copyBytes(this.#storedMediaContainer);
35
+ }
36
+ get mediaBlocks() { return cloneMediaBlocks(this.#storedMediaBlocks); }
37
+ /** 保留为 mediaContainer 的兼容名称。 */
38
+ get payload() { return this.mediaContainer; }
39
+ get objectBytes() { return copyBytes(this.#storedObjectBytes); }
40
+ }
41
+ Object.freeze(DecodedNode.prototype);
42
+ /** @internal 供 node codec 使用;不从 SDK 根入口导出。 */
43
+ export function createDecodedNode(kind, document, documentBytes, signature, seedHash, mediaContainer, mediaBlocks, objectBytes) {
44
+ return new DecodedNode(kind, document, documentBytes, signature, seedHash, mediaContainer, mediaBlocks, objectBytes, DECODED_NODE_TOKEN);
45
+ }
46
+ const VERIFIED_NODE_TOKEN = Symbol("streamseed.verified-node");
47
+ const verifiedNodeInstances = new WeakSet();
48
+ /** 已绑定期望 Seed Hash、序号、ProgramInfo 公钥并通过签名验证的 Node。 */
49
+ export class VerifiedNode {
50
+ #storedKind;
51
+ #storedDocument;
52
+ #storedDocumentBytes;
53
+ #storedSignature;
54
+ #storedSeedHash;
55
+ #storedMediaContainer;
56
+ #storedMediaBlocks;
57
+ #storedObjectBytes;
58
+ /** @internal 只有 verifyNodeObject 通过模块内 token 创建实例。 */
59
+ constructor(kind, document, documentBytes, signature, seedHash, mediaContainer, mediaBlocks, objectBytes, token) {
60
+ if (token !== VERIFIED_NODE_TOKEN)
61
+ throw new TypeError("VerifiedNode must be created by verifyNodeObject");
62
+ this.#storedKind = kind;
63
+ this.#storedDocument = cloneDocument(document);
64
+ this.#storedDocumentBytes = copyBytes(documentBytes);
65
+ this.#storedSignature = copyBytes(signature);
66
+ this.#storedSeedHash = copyBytes(seedHash);
67
+ this.#storedMediaContainer = mediaContainer === undefined ? undefined : copyBytes(mediaContainer);
68
+ this.#storedMediaBlocks = cloneMediaBlocks(mediaBlocks);
69
+ this.#storedObjectBytes = copyBytes(objectBytes);
70
+ verifiedNodeInstances.add(this);
71
+ Object.freeze(this);
72
+ }
73
+ get kind() { return this.#storedKind; }
74
+ get document() { return cloneDocument(this.#storedDocument); }
75
+ get documentBytes() { return copyBytes(this.#storedDocumentBytes); }
76
+ get signature() { return copyBytes(this.#storedSignature); }
77
+ get seedHash() { return copyBytes(this.#storedSeedHash); }
78
+ get mediaContainer() {
79
+ return this.#storedMediaContainer === undefined ? undefined : copyBytes(this.#storedMediaContainer);
80
+ }
81
+ get mediaBlocks() { return cloneMediaBlocks(this.#storedMediaBlocks); }
82
+ /** 保留为 mediaContainer 的兼容名称。 */
83
+ get payload() { return this.mediaContainer; }
84
+ get objectBytes() { return copyBytes(this.#storedObjectBytes); }
85
+ }
86
+ Object.freeze(VerifiedNode.prototype);
87
+ /** @internal 供 node codec 使用;不从 SDK 根入口导出。 */
88
+ export function createVerifiedNode(kind, document, documentBytes, signature, seedHash, mediaContainer, mediaBlocks, objectBytes) {
89
+ return new VerifiedNode(kind, document, documentBytes, signature, seedHash, mediaContainer, mediaBlocks, objectBytes, VERIFIED_NODE_TOKEN);
90
+ }
91
+ /** 判断值是否为 SDK verifyNodeObject 生成的实例。 */
92
+ export function isVerifiedNode(value) {
93
+ return typeof value === "object" && value !== null && verifiedNodeInstances.has(value);
94
+ }
95
+ function cloneDocument(document) {
96
+ return {
97
+ streamId: copyBytes(document.streamId),
98
+ nodeId: document.nodeId,
99
+ publisherPublicKey: copyBytes(document.publisherPublicKey),
100
+ payloadSize: document.payloadSize,
101
+ payloadHash: copyBytes(document.payloadHash),
102
+ refs: document.refs.map((ref) => ({ nodeId: ref.nodeId, seedHash: copyBytes(ref.seedHash) }))
103
+ };
104
+ }
105
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1,10 @@
1
+ import { type DecodedProgram, type ProgramInfo, type ProgramObject, type VerifiedProgram } from "./types.js";
2
+ /** 规范化并编码 ProgramInfo,同时计算 MasterSeed stream ID。 */
3
+ export declare function buildProgramObject(info: ProgramInfo): Promise<ProgramObject>;
4
+ /** 编码 ProgramInfo 的唯一 V1 deterministic-CBOR。 */
5
+ export declare function encodeProgramInfo(info: ProgramInfo): Uint8Array;
6
+ /** 只做严格结构解析,不建立 stream ID 或发布者信任。 */
7
+ export declare function decodeProgramObject(data: Uint8Array): DecodedProgram;
8
+ /** 先验证完整对象 MasterSeed Seed Hash,再严格解析并返回 VerifiedProgram。 */
9
+ export declare function verifyProgramObject(expectedStreamId: Uint8Array, data: Uint8Array, signal?: AbortSignal): Promise<VerifiedProgram>;
10
+ //# sourceMappingURL=codec.d.ts.map
@@ -0,0 +1,165 @@
1
+ import { KIND_PROGRAM_INFO, MAX_COVER_BYTES, MAX_DESCRIPTION_BYTES, MAX_NAME_BYTES, MAX_PROGRAM_OBJECT_SIZE, PROGRAM_INFO_ARRAY_LENGTH, WIRE_VERSION } from "../protocol/constants.js";
2
+ import { ERROR_CODES, streamSeedError } from "../protocol/errors.js";
3
+ import { bytesEqual, newChannelPublicKey, newPublicKey, newReleaseSalt, newStreamID, copyBytes } from "../protocol/ids.js";
4
+ import { masterSeedHash } from "../protocol/hash.js";
5
+ import { CBORDecoder, CBOREncoder } from "../internal/cbor-codec.js";
6
+ import { isValidPublicKey } from "../internal/ed25519.js";
7
+ import { cloneProgramInfo, createDecodedProgram, createProgramObject, createVerifiedProgram } from "./types.js";
8
+ const encoder = new TextEncoder();
9
+ /** 规范化并编码 ProgramInfo,同时计算 MasterSeed stream ID。 */
10
+ export async function buildProgramObject(info) {
11
+ const normalized = normalizeForBuild(info);
12
+ const bytes = encodeNormalizedProgramInfo(normalized);
13
+ return createProgramObject(cloneProgramInfo(normalized), newStreamID(await masterSeedHash(bytes)), bytes);
14
+ }
15
+ /** 编码 ProgramInfo 的唯一 V1 deterministic-CBOR。 */
16
+ export function encodeProgramInfo(info) {
17
+ return encodeNormalizedProgramInfo(normalizeForBuild(info));
18
+ }
19
+ /** 只做严格结构解析,不建立 stream ID 或发布者信任。 */
20
+ export function decodeProgramObject(data) {
21
+ if (data.length > MAX_PROGRAM_OBJECT_SIZE) {
22
+ throw streamSeedError(ERROR_CODES.FIELD_TOO_LARGE, `program object exceeds ${MAX_PROGRAM_OBJECT_SIZE} bytes`);
23
+ }
24
+ const info = decodeProgramInfo(data);
25
+ return createDecodedProgram(cloneProgramInfo(info), data);
26
+ }
27
+ /** 先验证完整对象 MasterSeed Seed Hash,再严格解析并返回 VerifiedProgram。 */
28
+ export async function verifyProgramObject(expectedStreamId, data, signal) {
29
+ if (data.length > MAX_PROGRAM_OBJECT_SIZE) {
30
+ throw streamSeedError(ERROR_CODES.FIELD_TOO_LARGE, `program object exceeds ${MAX_PROGRAM_OBJECT_SIZE} bytes`);
31
+ }
32
+ const snapshot = copyBytes(data);
33
+ const expected = newStreamID(expectedStreamId);
34
+ if (!bytesEqual(await masterSeedHash(snapshot, signal), expected)) {
35
+ throw streamSeedError(ERROR_CODES.STREAM_ID_MISMATCH, "program object MasterSeed hash does not match expected stream ID");
36
+ }
37
+ const decoded = decodeProgramObject(snapshot);
38
+ return createVerifiedProgram(decoded.info, expected, snapshot);
39
+ }
40
+ function encodeNormalizedProgramInfo(info) {
41
+ const output = new CBOREncoder();
42
+ output.array(PROGRAM_INFO_ARRAY_LENGTH);
43
+ output.uint(BigInt(WIRE_VERSION));
44
+ output.uint(BigInt(KIND_PROGRAM_INFO));
45
+ output.text(info.name);
46
+ output.uint(info.publishedAtMs);
47
+ output.bytes(info.nodePublisherKey);
48
+ output.text(info.description);
49
+ output.text(info.coverMediaType);
50
+ output.bytes(info.coverBytes);
51
+ output.bytes(info.releaseSalt);
52
+ output.bytes(info.channelPublisherKey);
53
+ return output.finish();
54
+ }
55
+ function decodeProgramInfo(data) {
56
+ const input = new CBORDecoder(data, BigInt(MAX_PROGRAM_OBJECT_SIZE));
57
+ if (input.array() !== PROGRAM_INFO_ARRAY_LENGTH) {
58
+ throw streamSeedError(ERROR_CODES.INVALID_LENGTH, "ProgramInfo array must contain exactly 10 items");
59
+ }
60
+ if (input.uint() !== BigInt(WIRE_VERSION)) {
61
+ throw streamSeedError(ERROR_CODES.UNSUPPORTED_VERSION, "unsupported ProgramInfo wire version");
62
+ }
63
+ if (input.uint() !== BigInt(KIND_PROGRAM_INFO)) {
64
+ throw streamSeedError(ERROR_CODES.UNSUPPORTED_KIND, "unsupported ProgramInfo kind");
65
+ }
66
+ const name = input.text(MAX_NAME_BYTES);
67
+ const publishedAtMs = input.uint();
68
+ const nodeKeyBytes = input.bytes(32);
69
+ if (nodeKeyBytes.length !== 32 || !isValidPublicKey(nodeKeyBytes)) {
70
+ throw streamSeedError(ERROR_CODES.INVALID_PUBLIC_KEY, "ProgramInfo node public key is not a strict Ed25519 key");
71
+ }
72
+ const description = input.text(MAX_DESCRIPTION_BYTES);
73
+ const coverMediaType = input.text(64);
74
+ const coverBytes = input.bytes(MAX_COVER_BYTES);
75
+ const saltBytes = input.bytes(32);
76
+ if (saltBytes.length !== 32 || saltBytes.every((byte) => byte === 0)) {
77
+ throw streamSeedError(ERROR_CODES.INVALID_LENGTH, "release salt must be 32 non-zero bytes");
78
+ }
79
+ const channelKeyBytes = input.bytes(33);
80
+ const channelPublisherKey = newChannelPublicKey(channelKeyBytes);
81
+ input.requireEOF();
82
+ const info = {
83
+ name,
84
+ publishedAtMs,
85
+ nodePublisherKey: newPublicKey(nodeKeyBytes),
86
+ description,
87
+ coverMediaType,
88
+ coverBytes,
89
+ releaseSalt: newReleaseSalt(saltBytes),
90
+ channelPublisherKey
91
+ };
92
+ validateCanonicalText(info.name, MAX_NAME_BYTES, false);
93
+ validateCanonicalText(info.description, MAX_DESCRIPTION_BYTES, true);
94
+ validateCoverMediaType(info.coverMediaType);
95
+ if (!bytesEqual(encodeNormalizedProgramInfo(info), data)) {
96
+ throw streamSeedError(ERROR_CODES.NON_CANONICAL_CBOR, "ProgramInfo does not re-encode byte-for-byte");
97
+ }
98
+ return info;
99
+ }
100
+ function normalizeForBuild(info) {
101
+ const name = normalizeText(info.name, MAX_NAME_BYTES, false);
102
+ const description = normalizeText(info.description, MAX_DESCRIPTION_BYTES, true);
103
+ if (!isValidPublicKey(info.nodePublisherKey)) {
104
+ throw streamSeedError(ERROR_CODES.INVALID_PUBLIC_KEY, "ProgramInfo node public key is not a strict Ed25519 key");
105
+ }
106
+ validateCoverMediaType(info.coverMediaType);
107
+ if (!(info.coverBytes instanceof Uint8Array))
108
+ throw streamSeedError(ERROR_CODES.INVALID_LENGTH, "coverBytes must be Uint8Array");
109
+ if (info.coverBytes.length > MAX_COVER_BYTES) {
110
+ throw streamSeedError(ERROR_CODES.FIELD_TOO_LARGE, `cover exceeds ${MAX_COVER_BYTES} bytes`);
111
+ }
112
+ const releaseSalt = newReleaseSalt(info.releaseSalt);
113
+ if (typeof info.publishedAtMs !== "bigint" || info.publishedAtMs < 0n || info.publishedAtMs > 0xffffffffffffffffn) {
114
+ throw streamSeedError(ERROR_CODES.INVALID_LENGTH, "publishedAtMs must be bigint in uint64 range");
115
+ }
116
+ return {
117
+ name,
118
+ publishedAtMs: info.publishedAtMs,
119
+ nodePublisherKey: newPublicKey(info.nodePublisherKey),
120
+ description,
121
+ coverMediaType: info.coverMediaType,
122
+ coverBytes: copyBytes(info.coverBytes),
123
+ releaseSalt,
124
+ channelPublisherKey: newChannelPublicKey(info.channelPublisherKey)
125
+ };
126
+ }
127
+ function validateCoverMediaType(value) {
128
+ if (value !== "image/jpeg" && value !== "image/png" && value !== "image/webp") {
129
+ throw streamSeedError(ERROR_CODES.UNSUPPORTED_MEDIA_TYPE, `unsupported cover media type ${value}`);
130
+ }
131
+ }
132
+ function normalizeText(value, limit, allowEmpty) {
133
+ if (typeof value !== "string" || hasUnpairedSurrogate(value)) {
134
+ throw streamSeedError(ERROR_CODES.INVALID_UTF8, "text is not valid UTF-8");
135
+ }
136
+ const normalized = value.normalize("NFC");
137
+ validateCanonicalText(normalized, limit, allowEmpty);
138
+ return normalized;
139
+ }
140
+ function validateCanonicalText(value, limit, allowEmpty) {
141
+ if (hasUnpairedSurrogate(value))
142
+ throw streamSeedError(ERROR_CODES.INVALID_UTF8, "text is not valid UTF-8");
143
+ if (value.normalize("NFC") !== value)
144
+ throw streamSeedError(ERROR_CODES.NON_CANONICAL_TEXT, "text is not Unicode NFC");
145
+ const length = encoder.encode(value).length;
146
+ if ((!allowEmpty && length === 0) || length > limit) {
147
+ throw streamSeedError(ERROR_CODES.INVALID_LENGTH, `text UTF-8 length ${length} is outside allowed range`);
148
+ }
149
+ }
150
+ function hasUnpairedSurrogate(value) {
151
+ for (let index = 0; index < value.length; index += 1) {
152
+ const code = value.charCodeAt(index);
153
+ if (code >= 0xd800 && code <= 0xdbff) {
154
+ const next = value.charCodeAt(index + 1);
155
+ if (next < 0xdc00 || next > 0xdfff)
156
+ return true;
157
+ index += 1;
158
+ }
159
+ else if (code >= 0xdc00 && code <= 0xdfff) {
160
+ return true;
161
+ }
162
+ }
163
+ return false;
164
+ }
165
+ //# sourceMappingURL=codec.js.map
@@ -0,0 +1,25 @@
1
+ import { type Digest } from "../protocol/ids.js";
2
+ import type { VerifiedProgram } from "./types.js";
3
+ /** 调用方提供的按 32 字节摘要获取 exact object bytes 的抽象。 */
4
+ export type GetByHash = (hash: Digest, signal?: AbortSignal) => Promise<Uint8Array>;
5
+ /** 可被 SDK 限制读取量的异步字节流。 */
6
+ export type ByteStream = AsyncIterable<Uint8Array> | ReadableStream<Uint8Array>;
7
+ /** 流式内容寻址获取函数;SDK 会在读取阶段执行 maxBytes 限制。 */
8
+ export type GetByHashReader = (hash: Digest, signal?: AbortSignal) => Promise<ByteStream>;
9
+ /** 获取并验证 ProgramInfo;普通 []byte getter 使用协议默认上限。 */
10
+ export declare function resolveProgram(streamId: Uint8Array, getter: GetByHash, signal?: AbortSignal): Promise<VerifiedProgram>;
11
+ /**
12
+ * 为 []byte getter 增加调用方大小上限。
13
+ *
14
+ * 该上限保护 SDK 的 hash/解析阶段;若要限制供应商读取阶段的内存,请使用
15
+ * resolveProgramReader。供应商在 GetByHash 回调内部如何分配内存不受此函数控制。
16
+ */
17
+ export declare function resolveProgramWithMaxBytes(streamId: Uint8Array, getter: GetByHash, maxBytes: number, signal?: AbortSignal): Promise<VerifiedProgram>;
18
+ /**
19
+ * 流式获取并验证 ProgramInfo。
20
+ *
21
+ * 内部最多保留 maxBytes+1 字节;读到超限时立即取消 ReadableStream,或停止消费
22
+ * AsyncIterable,避免超大对象被完整读入内存。
23
+ */
24
+ export declare function resolveProgramReader(streamId: Uint8Array, getter: GetByHashReader, maxBytes?: number, signal?: AbortSignal): Promise<VerifiedProgram>;
25
+ //# sourceMappingURL=resolver.d.ts.map
@@ -0,0 +1,189 @@
1
+ import { MAX_PROGRAM_OBJECT_SIZE } from "../protocol/constants.js";
2
+ import { ERROR_CODES, StreamSeedError, streamSeedError } from "../protocol/errors.js";
3
+ import { copyBytes, newDigest, newStreamID } from "../protocol/ids.js";
4
+ import { verifyProgramObject } from "./codec.js";
5
+ import { awaitWithAbort } from "../internal/abort.js";
6
+ /** 获取并验证 ProgramInfo;普通 []byte getter 使用协议默认上限。 */
7
+ export async function resolveProgram(streamId, getter, signal) {
8
+ return resolveProgramWithMaxBytes(streamId, getter, MAX_PROGRAM_OBJECT_SIZE, signal);
9
+ }
10
+ /**
11
+ * 为 []byte getter 增加调用方大小上限。
12
+ *
13
+ * 该上限保护 SDK 的 hash/解析阶段;若要限制供应商读取阶段的内存,请使用
14
+ * resolveProgramReader。供应商在 GetByHash 回调内部如何分配内存不受此函数控制。
15
+ */
16
+ export async function resolveProgramWithMaxBytes(streamId, getter, maxBytes, signal) {
17
+ validateMaxBytes(maxBytes);
18
+ checkAbort(signal);
19
+ const expected = newStreamID(streamId);
20
+ if (typeof getter !== "function")
21
+ throw streamSeedError(ERROR_CODES.READ_FAILURE, "getter must be a function");
22
+ let object;
23
+ try {
24
+ object = await awaitWithAbort(getter(newDigest(expected), signal), signal);
25
+ }
26
+ catch (error) {
27
+ throw mapReadError(error, signal);
28
+ }
29
+ checkAbort(signal);
30
+ if (!(object instanceof Uint8Array))
31
+ throw streamSeedError(ERROR_CODES.READ_FAILURE, "GetByHash did not return Uint8Array");
32
+ if (object.length > maxBytes)
33
+ throw streamSeedError(ERROR_CODES.FIELD_TOO_LARGE, `program object exceeds ${maxBytes} bytes`);
34
+ return verifyProgramObject(expected, object, signal);
35
+ }
36
+ /**
37
+ * 流式获取并验证 ProgramInfo。
38
+ *
39
+ * 内部最多保留 maxBytes+1 字节;读到超限时立即取消 ReadableStream,或停止消费
40
+ * AsyncIterable,避免超大对象被完整读入内存。
41
+ */
42
+ export async function resolveProgramReader(streamId, getter, maxBytes = MAX_PROGRAM_OBJECT_SIZE, signal) {
43
+ validateMaxBytes(maxBytes);
44
+ checkAbort(signal);
45
+ const expected = newStreamID(streamId);
46
+ if (typeof getter !== "function")
47
+ throw streamSeedError(ERROR_CODES.READ_FAILURE, "reader getter must be a function");
48
+ let stream;
49
+ try {
50
+ stream = await awaitWithAbort(getter(newDigest(expected), signal), signal);
51
+ }
52
+ catch (error) {
53
+ throw mapReadError(error, signal);
54
+ }
55
+ checkAbort(signal);
56
+ let object;
57
+ try {
58
+ object = await readLimitedBytes(stream, maxBytes, signal);
59
+ }
60
+ catch (error) {
61
+ throw mapReadError(error, signal);
62
+ }
63
+ checkAbort(signal);
64
+ return verifyProgramObject(expected, object, signal);
65
+ }
66
+ function validateMaxBytes(maxBytes) {
67
+ if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0 || maxBytes > MAX_PROGRAM_OBJECT_SIZE) {
68
+ throw streamSeedError(ERROR_CODES.INVALID_LENGTH, `maxBytes must be between 1 and ${MAX_PROGRAM_OBJECT_SIZE}`);
69
+ }
70
+ }
71
+ async function readLimitedBytes(stream, maxBytes, signal) {
72
+ if (isReadableStream(stream)) {
73
+ const reader = stream.getReader();
74
+ const chunks = [];
75
+ let total = 0;
76
+ const abortCleanup = () => cancelReader(reader, "ProgramInfo resolution was aborted");
77
+ signal?.addEventListener("abort", abortCleanup, { once: true });
78
+ try {
79
+ while (true) {
80
+ checkAbort(signal);
81
+ const result = await awaitWithAbort(reader.read(), signal);
82
+ if (result.done)
83
+ break;
84
+ const chunk = result.value;
85
+ if (!(chunk instanceof Uint8Array))
86
+ throw streamSeedError(ERROR_CODES.READ_FAILURE, "ReadableStream returned non-byte data");
87
+ total += chunk.length;
88
+ if (total > maxBytes) {
89
+ cancelReader(reader, "ProgramInfo exceeds maxBytes");
90
+ throw streamSeedError(ERROR_CODES.FIELD_TOO_LARGE, `program object exceeds ${maxBytes} bytes`);
91
+ }
92
+ chunks.push(copyBytes(chunk));
93
+ }
94
+ }
95
+ finally {
96
+ signal?.removeEventListener("abort", abortCleanup);
97
+ try {
98
+ reader.releaseLock();
99
+ }
100
+ catch {
101
+ // abort 时底层 read 可能仍在等待;cancel 已被触发,不能让清理覆盖 CANCELLED。
102
+ }
103
+ }
104
+ return joinChunks(chunks, total);
105
+ }
106
+ if (isAsyncIterable(stream)) {
107
+ const chunks = [];
108
+ let total = 0;
109
+ const iterator = stream[Symbol.asyncIterator]();
110
+ let completed = false;
111
+ let returned = false;
112
+ const returnIterator = () => {
113
+ if (returned || completed)
114
+ return;
115
+ returned = true;
116
+ try {
117
+ const result = iterator.return?.();
118
+ if (result !== undefined)
119
+ void Promise.resolve(result).catch(() => undefined);
120
+ }
121
+ catch {
122
+ // 清理阶段不能覆盖原始读取/取消错误。
123
+ }
124
+ };
125
+ const abortCleanup = () => returnIterator();
126
+ signal?.addEventListener("abort", abortCleanup, { once: true });
127
+ try {
128
+ while (true) {
129
+ checkAbort(signal);
130
+ const result = await awaitWithAbort(iterator.next(), signal);
131
+ if (result.done) {
132
+ completed = true;
133
+ break;
134
+ }
135
+ const chunk = result.value;
136
+ if (!(chunk instanceof Uint8Array))
137
+ throw streamSeedError(ERROR_CODES.READ_FAILURE, "AsyncIterable returned non-byte data");
138
+ total += chunk.length;
139
+ if (total > maxBytes)
140
+ throw streamSeedError(ERROR_CODES.FIELD_TOO_LARGE, `program object exceeds ${maxBytes} bytes`);
141
+ chunks.push(copyBytes(chunk));
142
+ }
143
+ }
144
+ finally {
145
+ signal?.removeEventListener("abort", abortCleanup);
146
+ returnIterator();
147
+ }
148
+ return joinChunks(chunks, total);
149
+ }
150
+ throw streamSeedError(ERROR_CODES.READ_FAILURE, "reader getter did not return a byte stream");
151
+ }
152
+ function cancelReader(reader, reason) {
153
+ try {
154
+ void Promise.resolve(reader.cancel(reason)).catch(() => undefined);
155
+ }
156
+ catch {
157
+ // 资源清理不得覆盖 awaitWithAbort 返回的 CANCELLED。
158
+ }
159
+ }
160
+ function joinChunks(chunks, total) {
161
+ const output = new Uint8Array(total);
162
+ let offset = 0;
163
+ for (const chunk of chunks) {
164
+ output.set(chunk, offset);
165
+ offset += chunk.length;
166
+ }
167
+ return output;
168
+ }
169
+ function isReadableStream(value) {
170
+ return typeof value === "object" && value !== null && typeof value.getReader === "function";
171
+ }
172
+ function isAsyncIterable(value) {
173
+ return typeof value === "object" && value !== null && Symbol.asyncIterator in value;
174
+ }
175
+ function checkAbort(signal) {
176
+ if (signal?.aborted)
177
+ throw streamSeedError(ERROR_CODES.CANCELLED, "program resolution was aborted");
178
+ }
179
+ function mapReadError(error, signal) {
180
+ if (signal?.aborted || isAbortError(error))
181
+ return streamSeedError(ERROR_CODES.CANCELLED, "program resolution was aborted", error);
182
+ if (error instanceof StreamSeedError)
183
+ return error;
184
+ return streamSeedError(ERROR_CODES.READ_FAILURE, "program resolution failed", error);
185
+ }
186
+ function isAbortError(error) {
187
+ return typeof DOMException !== "undefined" && error instanceof DOMException && error.name === "AbortError";
188
+ }
189
+ //# sourceMappingURL=resolver.js.map
@@ -0,0 +1,61 @@
1
+ import { type ChannelPublicKey, type PublicKey, type ReleaseSalt, type StreamID } from "../protocol/ids.js";
2
+ /** 参与 stream ID 计算的不可变节目发行信息。 */
3
+ export interface ProgramInfo {
4
+ /** NFC 规范化后的节目名称。 */
5
+ name: string;
6
+ /** 发布者声明的 Unix Epoch 毫秒,完整 uint64。 */
7
+ publishedAtMs: bigint;
8
+ /** 签署 Node 的严格 Ed25519 公钥。 */
9
+ nodePublisherKey: PublicKey;
10
+ /** NFC 规范化后的节目简介,可以为空。 */
11
+ description: string;
12
+ /** image/jpeg、image/png 或 image/webp。 */
13
+ coverMediaType: string;
14
+ /** 内嵌封面原始字节,最多 1 MiB。 */
15
+ coverBytes: Uint8Array;
16
+ /** 本次发行的非全零随机盐。 */
17
+ releaseSalt: ReleaseSalt;
18
+ /** 签署 Channel 公共消息的压缩 secp256k1 公钥。 */
19
+ channelPublisherKey: ChannelPublicKey;
20
+ }
21
+ declare const PROGRAM_OBJECT_TOKEN: unique symbol;
22
+ declare const DECODED_PROGRAM_TOKEN: unique symbol;
23
+ declare const VERIFIED_PROGRAM_TOKEN: unique symbol;
24
+ /** 构造成功的完整 ProgramInfo CBOR 和 MasterSeed stream ID。byte getter 返回副本。 */
25
+ export declare class ProgramObject {
26
+ #private;
27
+ /** @internal 只有 buildProgramObject 通过模块内 token 创建实例。 */
28
+ constructor(info: ProgramInfo, streamId: StreamID, bytes: Uint8Array, token: typeof PROGRAM_OBJECT_TOKEN);
29
+ get info(): ProgramInfo;
30
+ get streamId(): StreamID;
31
+ get bytes(): Uint8Array;
32
+ }
33
+ /** 严格解析但尚未通过目标 Seed Hash 验证的 ProgramInfo;byte getter 返回副本。 */
34
+ export declare class DecodedProgram {
35
+ #private;
36
+ /** @internal 只有 decodeProgramObject 通过模块内 token 创建实例。 */
37
+ constructor(info: ProgramInfo, objectBytes: Uint8Array, token: typeof DECODED_PROGRAM_TOKEN);
38
+ get info(): ProgramInfo;
39
+ get objectBytes(): Uint8Array;
40
+ }
41
+ /** 已与 expected stream ID 做 MasterSeed Seed Hash 校验的 ProgramInfo。 */
42
+ export declare class VerifiedProgram {
43
+ #private;
44
+ /** @internal 只有 verifyProgramObject 通过模块内 token 创建实例。 */
45
+ constructor(info: ProgramInfo, streamId: StreamID, objectBytes: Uint8Array, token: typeof VERIFIED_PROGRAM_TOKEN);
46
+ get info(): ProgramInfo;
47
+ get streamId(): StreamID;
48
+ get objectBytes(): Uint8Array;
49
+ }
50
+ /** @internal 供 program codec 使用;不从 SDK 根入口导出。 */
51
+ export declare function createProgramObject(info: ProgramInfo, streamId: StreamID, bytes: Uint8Array): ProgramObject;
52
+ /** @internal 供 program codec 使用;不从 SDK 根入口导出。 */
53
+ export declare function createDecodedProgram(info: ProgramInfo, objectBytes: Uint8Array): DecodedProgram;
54
+ /** @internal 供 program codec 使用;不从 SDK 根入口导出。 */
55
+ export declare function createVerifiedProgram(info: ProgramInfo, streamId: StreamID, objectBytes: Uint8Array): VerifiedProgram;
56
+ /** 判断值是否为 SDK 验证流程生成的 VerifiedProgram 实例。 */
57
+ export declare function isVerifiedProgram(value: unknown): value is VerifiedProgram;
58
+ /** @internal 供 node codec 使用;不从 SDK 根入口导出。 */
59
+ export declare function cloneProgramInfo(info: ProgramInfo): ProgramInfo;
60
+ export {};
61
+ //# sourceMappingURL=types.d.ts.map