@941design/marmot-engine 0.0.0-stage → 0.2.0-alpha.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 (196) hide show
  1. package/CHANGELOG.md +434 -0
  2. package/LICENSE +49 -0
  3. package/README.md +33 -2
  4. package/dist/audit/emitter.d.ts +17 -0
  5. package/dist/audit/emitter.js +30 -0
  6. package/dist/audit/helpers.d.ts +16 -0
  7. package/dist/audit/helpers.js +103 -0
  8. package/dist/audit/index.d.ts +6 -0
  9. package/dist/audit/index.js +6 -0
  10. package/dist/audit/recorder.d.ts +13 -0
  11. package/dist/audit/recorder.js +24 -0
  12. package/dist/audit/sink.d.ts +16 -0
  13. package/dist/audit/sink.js +27 -0
  14. package/dist/audit/types-internal.d.ts +7 -0
  15. package/dist/audit/types-internal.js +1 -0
  16. package/dist/audit/types.d.ts +289 -0
  17. package/dist/audit/types.js +2 -0
  18. package/dist/core/account-identity-proof.d.ts +165 -0
  19. package/dist/core/account-identity-proof.js +277 -0
  20. package/dist/core/application-rumor.d.ts +45 -0
  21. package/dist/core/application-rumor.js +120 -0
  22. package/dist/core/auth-service.d.ts +2 -0
  23. package/dist/core/auth-service.js +52 -0
  24. package/dist/core/binary.d.ts +142 -0
  25. package/dist/core/binary.js +363 -0
  26. package/dist/core/capabilities.d.ts +51 -0
  27. package/dist/core/capabilities.js +102 -0
  28. package/dist/core/client-state.d.ts +119 -0
  29. package/dist/core/client-state.js +226 -0
  30. package/dist/core/commit-authorization.d.ts +26 -0
  31. package/dist/core/commit-authorization.js +26 -0
  32. package/dist/core/components/admin-policy.d.ts +4 -0
  33. package/dist/core/components/admin-policy.js +69 -0
  34. package/dist/core/components/agent-text-stream.d.ts +51 -0
  35. package/dist/core/components/agent-text-stream.js +112 -0
  36. package/dist/core/components/app-components-list.d.ts +17 -0
  37. package/dist/core/components/app-components-list.js +35 -0
  38. package/dist/core/components/avatar-url.d.ts +12 -0
  39. package/dist/core/components/avatar-url.js +85 -0
  40. package/dist/core/components/bytes.d.ts +5 -0
  41. package/dist/core/components/bytes.js +18 -0
  42. package/dist/core/components/dictionary.d.ts +80 -0
  43. package/dist/core/components/dictionary.js +175 -0
  44. package/dist/core/components/disband-validation.d.ts +21 -0
  45. package/dist/core/components/disband-validation.js +173 -0
  46. package/dist/core/components/encrypted-media.d.ts +44 -0
  47. package/dist/core/components/encrypted-media.js +210 -0
  48. package/dist/core/components/group-lifecycle.d.ts +10 -0
  49. package/dist/core/components/group-lifecycle.js +32 -0
  50. package/dist/core/components/group-profile.d.ts +24 -0
  51. package/dist/core/components/group-profile.js +35 -0
  52. package/dist/core/components/host-safety.d.ts +9 -0
  53. package/dist/core/components/host-safety.js +148 -0
  54. package/dist/core/components/ids.d.ts +74 -0
  55. package/dist/core/components/ids.js +73 -0
  56. package/dist/core/components/index.d.ts +14 -0
  57. package/dist/core/components/index.js +14 -0
  58. package/dist/core/components/integrity.d.ts +141 -0
  59. package/dist/core/components/integrity.js +293 -0
  60. package/dist/core/components/message-retention.d.ts +17 -0
  61. package/dist/core/components/message-retention.js +26 -0
  62. package/dist/core/components/nostr-routing.d.ts +8 -0
  63. package/dist/core/components/nostr-routing.js +92 -0
  64. package/dist/core/components/url.d.ts +26 -0
  65. package/dist/core/components/url.js +44 -0
  66. package/dist/core/convergence-status.d.ts +84 -0
  67. package/dist/core/convergence-status.js +82 -0
  68. package/dist/core/convergence.d.ts +567 -0
  69. package/dist/core/convergence.js +1150 -0
  70. package/dist/core/credential.d.ts +16 -0
  71. package/dist/core/credential.js +64 -0
  72. package/dist/core/default-capabilities.d.ts +9 -0
  73. package/dist/core/default-capabilities.js +34 -0
  74. package/dist/core/extensions.d.ts +9 -0
  75. package/dist/core/extensions.js +5 -0
  76. package/dist/core/grease.d.ts +2 -0
  77. package/dist/core/grease.js +6 -0
  78. package/dist/core/group-event.d.ts +18 -0
  79. package/dist/core/group-event.js +30 -0
  80. package/dist/core/group-lifecycle.d.ts +42 -0
  81. package/dist/core/group-lifecycle.js +66 -0
  82. package/dist/core/group-members.d.ts +37 -0
  83. package/dist/core/group-members.js +99 -0
  84. package/dist/core/group-message-classify.d.ts +42 -0
  85. package/dist/core/group-message-classify.js +57 -0
  86. package/dist/core/group-message-crypto.d.ts +53 -0
  87. package/dist/core/group-message-crypto.js +140 -0
  88. package/dist/core/group-message.d.ts +5 -0
  89. package/dist/core/group-message.js +11 -0
  90. package/dist/core/group.d.ts +45 -0
  91. package/dist/core/group.js +78 -0
  92. package/dist/core/inbound.d.ts +102 -0
  93. package/dist/core/inbound.js +79 -0
  94. package/dist/core/index.d.ts +28 -0
  95. package/dist/core/index.js +26 -0
  96. package/dist/core/key-package-eligibility.d.ts +31 -0
  97. package/dist/core/key-package-eligibility.js +116 -0
  98. package/dist/core/key-package-event-decode.d.ts +43 -0
  99. package/dist/core/key-package-event-decode.js +118 -0
  100. package/dist/core/key-package-event-delete.d.ts +16 -0
  101. package/dist/core/key-package-event-delete.js +46 -0
  102. package/dist/core/key-package-event-encode.d.ts +28 -0
  103. package/dist/core/key-package-event-encode.js +102 -0
  104. package/dist/core/key-package-event.d.ts +4 -0
  105. package/dist/core/key-package-event.js +8 -0
  106. package/dist/core/key-package.d.ts +55 -0
  107. package/dist/core/key-package.js +115 -0
  108. package/dist/core/leaf-succession.d.ts +83 -0
  109. package/dist/core/leaf-succession.js +97 -0
  110. package/dist/core/media/canonical.d.ts +34 -0
  111. package/dist/core/media/canonical.js +57 -0
  112. package/dist/core/media/crypto.d.ts +79 -0
  113. package/dist/core/media/crypto.js +215 -0
  114. package/dist/core/media/imeta.d.ts +33 -0
  115. package/dist/core/media/imeta.js +188 -0
  116. package/dist/core/media/locator.d.ts +44 -0
  117. package/dist/core/media/locator.js +69 -0
  118. package/dist/core/media/types.d.ts +83 -0
  119. package/dist/core/media/types.js +12 -0
  120. package/dist/core/media.d.ts +6 -0
  121. package/dist/core/media.js +12 -0
  122. package/dist/core/protocol.d.ts +51 -0
  123. package/dist/core/protocol.js +41 -0
  124. package/dist/core/relay-lists.d.ts +52 -0
  125. package/dist/core/relay-lists.js +86 -0
  126. package/dist/core/retained-history.d.ts +78 -0
  127. package/dist/core/retained-history.js +59 -0
  128. package/dist/core/transport.d.ts +43 -0
  129. package/dist/core/transport.js +21 -0
  130. package/dist/core/welcome-event.d.ts +61 -0
  131. package/dist/core/welcome-event.js +116 -0
  132. package/dist/core/welcome-join.d.ts +155 -0
  133. package/dist/core/welcome-join.js +243 -0
  134. package/dist/core/welcome.d.ts +3 -0
  135. package/dist/core/welcome.js +6 -0
  136. package/dist/engine/admin-policy.d.ts +58 -0
  137. package/dist/engine/admin-policy.js +137 -0
  138. package/dist/engine/auto-committer.d.ts +39 -0
  139. package/dist/engine/auto-committer.js +42 -0
  140. package/dist/engine/delivered-payloads.d.ts +61 -0
  141. package/dist/engine/delivered-payloads.js +84 -0
  142. package/dist/engine/disband-request.d.ts +41 -0
  143. package/dist/engine/disband-request.js +86 -0
  144. package/dist/engine/disband-tombstone.d.ts +14 -0
  145. package/dist/engine/disband-tombstone.js +66 -0
  146. package/dist/engine/fork-recovery.d.ts +672 -0
  147. package/dist/engine/fork-recovery.js +1615 -0
  148. package/dist/engine/group-engine.d.ts +571 -0
  149. package/dist/engine/group-engine.js +5112 -0
  150. package/dist/engine/history-tree.d.ts +232 -0
  151. package/dist/engine/history-tree.js +651 -0
  152. package/dist/engine/index.d.ts +16 -0
  153. package/dist/engine/index.js +15 -0
  154. package/dist/engine/ingest-disposition.d.ts +5 -0
  155. package/dist/engine/ingest-disposition.js +63 -0
  156. package/dist/engine/ingest.d.ts +390 -0
  157. package/dist/engine/ingest.js +1258 -0
  158. package/dist/engine/ingestion-pool.d.ts +74 -0
  159. package/dist/engine/ingestion-pool.js +95 -0
  160. package/dist/engine/message-dedup.d.ts +16 -0
  161. package/dist/engine/message-dedup.js +20 -0
  162. package/dist/engine/own-commit-stamp.d.ts +30 -0
  163. package/dist/engine/own-commit-stamp.js +71 -0
  164. package/dist/engine/retained-store.d.ts +79 -0
  165. package/dist/engine/retained-store.js +133 -0
  166. package/dist/engine/sender-ratchet.d.ts +50 -0
  167. package/dist/engine/sender-ratchet.js +196 -0
  168. package/dist/engine/state-notifications.d.ts +122 -0
  169. package/dist/engine/state-notifications.js +173 -0
  170. package/dist/engine/tree-convergence.d.ts +41 -0
  171. package/dist/engine/tree-convergence.js +90 -0
  172. package/dist/engine/types.d.ts +366 -0
  173. package/dist/engine/types.js +14 -0
  174. package/dist/engine/wire-format.d.ts +77 -0
  175. package/dist/engine/wire-format.js +120 -0
  176. package/dist/index.d.ts +12 -0
  177. package/dist/index.js +1 -0
  178. package/dist/mls.d.ts +11 -0
  179. package/dist/mls.js +11 -0
  180. package/dist/utils/debug.d.ts +3 -0
  181. package/dist/utils/debug.js +3 -0
  182. package/dist/utils/encoding.d.ts +38 -0
  183. package/dist/utils/encoding.js +91 -0
  184. package/dist/utils/key-value.d.ts +18 -0
  185. package/dist/utils/key-value.js +2 -0
  186. package/dist/utils/nostr.d.ts +35 -0
  187. package/dist/utils/nostr.js +26 -0
  188. package/dist/utils/relay-url.d.ts +10 -0
  189. package/dist/utils/relay-url.js +23 -0
  190. package/dist/utils/tag-cardinality.d.ts +50 -0
  191. package/dist/utils/tag-cardinality.js +91 -0
  192. package/dist/utils/timestamp.d.ts +50 -0
  193. package/dist/utils/timestamp.js +95 -0
  194. package/dist/version.d.ts +112 -0
  195. package/dist/version.js +112 -0
  196. package/package.json +68 -3
@@ -0,0 +1,91 @@
1
+ /** @module @category Utilities */
2
+ import { bytesToHex, hexToBytes } from "@noble/hashes/utils.js";
3
+ import { base64 } from "@scure/base";
4
+ /**
5
+ * Encodes binary data to a string using the specified format.
6
+ *
7
+ * @param bytes - The binary data to encode
8
+ * @param format - The encoding format ('base64' or 'hex')
9
+ * @returns The encoded string
10
+ */
11
+ export function encodeContent(bytes, format) {
12
+ if (format === "base64") {
13
+ return base64.encode(bytes);
14
+ }
15
+ else {
16
+ // hex format
17
+ return bytesToHex(bytes);
18
+ }
19
+ }
20
+ /**
21
+ * Decodes a string to binary data using the specified or auto-detected format.
22
+ *
23
+ * @param content - The encoded string
24
+ * @param format - Optional encoding format. If not specified, will auto-detect.
25
+ * @returns The decoded binary data
26
+ * @throws Error if the content cannot be decoded
27
+ */
28
+ export function decodeContent(content, format) {
29
+ const actualFormat = format ?? detectEncoding(content);
30
+ if (actualFormat === "base64") {
31
+ try {
32
+ return base64.decode(content);
33
+ }
34
+ catch (error) {
35
+ throw new Error(`Failed to decode base64 content: ${error instanceof Error ? error.message : String(error)}`);
36
+ }
37
+ }
38
+ else {
39
+ try {
40
+ return hexToBytes(content);
41
+ }
42
+ catch (error) {
43
+ throw new Error(`Failed to decode hex content: ${error instanceof Error ? error.message : String(error)}`);
44
+ }
45
+ }
46
+ }
47
+ /**
48
+ * Detects the encoding format of a content string.
49
+ *
50
+ * @param content - The encoded string to analyze
51
+ * @returns The detected encoding format
52
+ */
53
+ export function detectEncoding(content) {
54
+ // Remove whitespace for analysis
55
+ const cleaned = content.trim();
56
+ // Check if it's valid hex (only contains 0-9, a-f, A-F)
57
+ const isHex = /^[0-9a-fA-F]+$/.test(cleaned);
58
+ // If it's valid hex and has even length, it's likely hex
59
+ // (hex encoding always produces even-length strings)
60
+ if (isHex && cleaned.length % 2 === 0) {
61
+ return "hex";
62
+ }
63
+ // If it contains characters outside hex range (like +, /) or has base64 padding,
64
+ // it's definitely base64
65
+ if (/[+/=]/.test(cleaned) || !isHex) {
66
+ return "base64";
67
+ }
68
+ // If it's valid hex but odd length, it's malformed hex, try base64
69
+ if (isHex && cleaned.length % 2 !== 0) {
70
+ return "base64";
71
+ }
72
+ // Default to base64 for ambiguous cases
73
+ return "base64";
74
+ }
75
+ /**
76
+ * Extracts the encoding tag from a Nostr event.
77
+ *
78
+ * @param event - The Nostr event to check
79
+ * @returns The encoding format specified in the event, or undefined if not present
80
+ */
81
+ export function getEncodingTag(event) {
82
+ const encodingTag = event.tags.find((tag) => tag[0] === "encoding");
83
+ if (!encodingTag || encodingTag.length < 2) {
84
+ return undefined;
85
+ }
86
+ const value = encodingTag[1];
87
+ if (value === "base64" || value === "hex") {
88
+ return value;
89
+ }
90
+ return undefined;
91
+ }
@@ -0,0 +1,18 @@
1
+ /** @module @category Utilities */
2
+ /**
3
+ * A generic interface for a key-value store
4
+ */
5
+ export interface GenericKeyValueStore<T> {
6
+ /** Get an item from the store */
7
+ getItem(key: string): Promise<T | null>;
8
+ /** Set an item in the store */
9
+ setItem(key: string, value: T): Promise<T>;
10
+ /** Remove an item from the store */
11
+ removeItem(key: string): Promise<void>;
12
+ /** Clear all items from the store */
13
+ clear(): Promise<void>;
14
+ /** Get all keys in the store */
15
+ keys(): Promise<string[]>;
16
+ }
17
+ /** @deprecated Use {@link GenericKeyValueStore} instead */
18
+ export type KeyValueStoreBackend<I> = GenericKeyValueStore<I>;
@@ -0,0 +1,2 @@
1
+ /** @module @category Utilities */
2
+ export {};
@@ -0,0 +1,35 @@
1
+ /** @module @category Utilities */
2
+ import { type EventTemplate, finalizeEvent, generateSecretKey, getEventHash, type NostrEvent, type UnsignedEvent } from "nostr-tools/pure";
3
+ export type { EventTemplate, NostrEvent, UnsignedEvent };
4
+ export { finalizeEvent, generateSecretKey, getEventHash };
5
+ /**
6
+ * An unsigned Nostr event with a known `id` but no `sig` yet — the NIP-59
7
+ * "rumor" shape used for gift-wrapped welcome/message payloads.
8
+ *
9
+ * Ported locally rather than imported: upstream sources this (and `isRumor`)
10
+ * from a third-party Nostr helper library `marmot-engine` does not depend on
11
+ * (AC-VENDOR-2). The shape matches that library's
12
+ * `export type Rumor = UnsignedEvent & { id: string }` exactly, and `isRumor`
13
+ * below mirrors its structural predicate.
14
+ */
15
+ export type Rumor = UnsignedEvent & {
16
+ id: string;
17
+ };
18
+ /** Checks if an object is a Rumor (an unsigned event with a known id). */
19
+ export declare function isRumor(event: any): event is Rumor;
20
+ /** Returns the value of a name / value tag */
21
+ export declare function getTagValue(event: NostrEvent, name: string): string | undefined;
22
+ /** Returns the current Unix timestamp in seconds */
23
+ export declare function unixNow(): number;
24
+ /**
25
+ * A single relay's publish outcome.
26
+ *
27
+ * Ported locally: upstream imports this from `../client/nostr-interface.js`,
28
+ * the one non-test `client/` import in the vendored surface
29
+ * (`utils/nostr.ts:7`) — `marmot-engine` does not vendor `client/` (AC-VENDOR-3).
30
+ */
31
+ export interface PublishResponse {
32
+ ok: boolean;
33
+ message?: string;
34
+ }
35
+ export declare const hasAck: (publishResult: Record<string, PublishResponse>) => boolean;
@@ -0,0 +1,26 @@
1
+ /** @module @category Utilities */
2
+ import { finalizeEvent, generateSecretKey, getEventHash, } from "nostr-tools/pure";
3
+ export { finalizeEvent, generateSecretKey, getEventHash };
4
+ /** Checks if an object is a Rumor (an unsigned event with a known id). */
5
+ export function isRumor(event) {
6
+ if (event === undefined || event === null)
7
+ return false;
8
+ return (typeof event.id === "string" &&
9
+ event.id.length === 64 &&
10
+ !("sig" in event) &&
11
+ typeof event.pubkey === "string" &&
12
+ event.pubkey.length === 64 &&
13
+ typeof event.content === "string" &&
14
+ Array.isArray(event.tags) &&
15
+ typeof event.created_at === "number" &&
16
+ event.created_at > 0);
17
+ }
18
+ /** Returns the value of a name / value tag */
19
+ export function getTagValue(event, name) {
20
+ return event.tags.find((t) => t[0] === name)?.[1];
21
+ }
22
+ /** Returns the current Unix timestamp in seconds */
23
+ export function unixNow() {
24
+ return Math.floor(Date.now() / 1000);
25
+ }
26
+ export const hasAck = (publishResult) => Object.values(publishResult).some((res) => res.ok);
@@ -0,0 +1,10 @@
1
+ /** @module @category Utilities */
2
+ /**
3
+ * Validates a relay URL to ensure it is a valid WebSocket URL.
4
+ *
5
+ * @param relay - Relay URL to validate
6
+ * @returns True if the relay URL is valid, false otherwise
7
+ */
8
+ export declare function isValidRelayUrl(relay: string): boolean;
9
+ /** Normalizes a relay URL */
10
+ export declare function normalizeRelayUrl(relay: string): string;
@@ -0,0 +1,23 @@
1
+ /** @module @category Utilities */
2
+ /**
3
+ * Validates a relay URL to ensure it is a valid WebSocket URL.
4
+ *
5
+ * @param relay - Relay URL to validate
6
+ * @returns True if the relay URL is valid, false otherwise
7
+ */
8
+ export function isValidRelayUrl(relay) {
9
+ if (!URL.canParse(relay))
10
+ return false;
11
+ try {
12
+ const url = new URL(relay);
13
+ return url.protocol === "wss:" || url.protocol === "ws:";
14
+ }
15
+ catch {
16
+ return false;
17
+ }
18
+ }
19
+ /** Normalizes a relay URL */
20
+ export function normalizeRelayUrl(relay) {
21
+ const url = new URL(relay);
22
+ return url.toString();
23
+ }
@@ -0,0 +1,50 @@
1
+ /** @module @category Utilities */
2
+ /** The cardinality rule for a required tag: exactly one value, or a non-empty deduplicated list. */
3
+ export type TagCardinality = "singleton" | "list";
4
+ /**
5
+ * The #236 wire-boundary tag-cardinality table (`refs/marmot/transports/nostr.md`),
6
+ * encoded as `(kind, tagName) -> "singleton" | "list"` data (D-10/D-11).
7
+ *
8
+ * This table is descriptive only — it does not itself validate anything; use
9
+ * {@link getSingletonTagValue}/{@link getListTag} at each required-tag read site.
10
+ */
11
+ export declare const TAG_CARDINALITY: Record<number, Record<string, TagCardinality>>;
12
+ /**
13
+ * Strictly reads a required singleton tag: returns the value only when
14
+ * exactly one tag named `name` exists on the event and it has exactly one
15
+ * value slot. Rejects (returns `undefined`) when the tag is absent,
16
+ * repeated, has no value, has extra values, or the value is empty (D-10/D-11).
17
+ *
18
+ * Never throws — malformed input is a typed reject, not an exception.
19
+ *
20
+ * Generic over any tagged event shape (mirrors `getTagValue`'s constraint) so
21
+ * it works for both signed {@link NostrEvent}s (445, 1059) and unsigned
22
+ * rumors (444 welcome), which carry no `sig`/`id`.
23
+ *
24
+ * @param event - The Nostr event (or rumor) to read the tag from
25
+ * @param name - The tag name to look up
26
+ * @returns The tag's single value, or `undefined` if the cardinality rule is violated
27
+ */
28
+ export declare function getSingletonTagValue<T extends {
29
+ tags: string[][];
30
+ }>(event: T, name: string): string | undefined;
31
+ /**
32
+ * Strictly reads a required list tag: returns all values only when exactly
33
+ * one tag named `name` exists on the event, it has at least one value, and
34
+ * none of the values are empty or duplicated. Rejects (returns `undefined`)
35
+ * when the tag is absent, repeated, empty, or contains duplicate values
36
+ * (D-10/D-11).
37
+ *
38
+ * Never throws — malformed input is a typed reject, not an exception.
39
+ *
40
+ * Generic over any tagged event shape (mirrors `getTagValue`'s constraint) so
41
+ * it works for both signed {@link NostrEvent}s (445, 1059) and unsigned
42
+ * rumors (444 welcome), which carry no `sig`/`id`.
43
+ *
44
+ * @param event - The Nostr event (or rumor) to read the tag from
45
+ * @param name - The tag name to look up
46
+ * @returns The tag's values, or `undefined` if the cardinality rule is violated
47
+ */
48
+ export declare function getListTag<T extends {
49
+ tags: string[][];
50
+ }>(event: T, name: string): string[] | undefined;
@@ -0,0 +1,91 @@
1
+ /** @module @category Utilities */
2
+ /**
3
+ * The #236 wire-boundary tag-cardinality table (`refs/marmot/transports/nostr.md`),
4
+ * encoded as `(kind, tagName) -> "singleton" | "list"` data (D-10/D-11).
5
+ *
6
+ * This table is descriptive only — it does not itself validate anything; use
7
+ * {@link getSingletonTagValue}/{@link getListTag} at each required-tag read site.
8
+ */
9
+ export const TAG_CARDINALITY = {
10
+ // kind 445 group message
11
+ 445: {
12
+ h: "singleton",
13
+ },
14
+ // kind 1059 welcome gift wrap
15
+ 1059: {
16
+ p: "singleton",
17
+ },
18
+ // kind 444 welcome rumor
19
+ 444: {
20
+ e: "singleton",
21
+ relays: "list",
22
+ },
23
+ // kind 30443 KeyPackage
24
+ 30443: {
25
+ d: "singleton",
26
+ i: "singleton",
27
+ mls_protocol_version: "singleton",
28
+ mls_ciphersuite: "list",
29
+ mls_extensions: "list",
30
+ mls_proposals: "list",
31
+ app_components: "list",
32
+ },
33
+ };
34
+ /**
35
+ * Strictly reads a required singleton tag: returns the value only when
36
+ * exactly one tag named `name` exists on the event and it has exactly one
37
+ * value slot. Rejects (returns `undefined`) when the tag is absent,
38
+ * repeated, has no value, has extra values, or the value is empty (D-10/D-11).
39
+ *
40
+ * Never throws — malformed input is a typed reject, not an exception.
41
+ *
42
+ * Generic over any tagged event shape (mirrors `getTagValue`'s constraint) so
43
+ * it works for both signed {@link NostrEvent}s (445, 1059) and unsigned
44
+ * rumors (444 welcome), which carry no `sig`/`id`.
45
+ *
46
+ * @param event - The Nostr event (or rumor) to read the tag from
47
+ * @param name - The tag name to look up
48
+ * @returns The tag's single value, or `undefined` if the cardinality rule is violated
49
+ */
50
+ export function getSingletonTagValue(event, name) {
51
+ const matches = event.tags.filter((t) => t[0] === name);
52
+ if (matches.length !== 1)
53
+ return undefined;
54
+ const tag = matches[0];
55
+ if (tag.length !== 2)
56
+ return undefined;
57
+ const value = tag[1];
58
+ if (!value)
59
+ return undefined;
60
+ return value;
61
+ }
62
+ /**
63
+ * Strictly reads a required list tag: returns all values only when exactly
64
+ * one tag named `name` exists on the event, it has at least one value, and
65
+ * none of the values are empty or duplicated. Rejects (returns `undefined`)
66
+ * when the tag is absent, repeated, empty, or contains duplicate values
67
+ * (D-10/D-11).
68
+ *
69
+ * Never throws — malformed input is a typed reject, not an exception.
70
+ *
71
+ * Generic over any tagged event shape (mirrors `getTagValue`'s constraint) so
72
+ * it works for both signed {@link NostrEvent}s (445, 1059) and unsigned
73
+ * rumors (444 welcome), which carry no `sig`/`id`.
74
+ *
75
+ * @param event - The Nostr event (or rumor) to read the tag from
76
+ * @param name - The tag name to look up
77
+ * @returns The tag's values, or `undefined` if the cardinality rule is violated
78
+ */
79
+ export function getListTag(event, name) {
80
+ const matches = event.tags.filter((t) => t[0] === name);
81
+ if (matches.length !== 1)
82
+ return undefined;
83
+ const values = matches[0].slice(1);
84
+ if (values.length === 0)
85
+ return undefined;
86
+ if (values.some((v) => !v))
87
+ return undefined;
88
+ if (new Set(values).size !== values.length)
89
+ return undefined;
90
+ return values;
91
+ }
@@ -0,0 +1,50 @@
1
+ /** @module @category Utilities */
2
+ import { Lifetime } from "ts-mls";
3
+ /**
4
+ * Formats a bigint timestamp to a readable date string, handling special MLS timestamp values.
5
+ *
6
+ * @param timestamp - The timestamp as a bigint (typically from MLS lifetime fields)
7
+ * @returns A formatted date string or descriptive text for special values
8
+ */
9
+ export declare function formatMlsTimestamp(timestamp: bigint): string;
10
+ /**
11
+ * Checks if a lifetime is currently valid, handling the "no expiration" case.
12
+ *
13
+ * @param lifetime - The lifetime object with notBefore and notAfter fields
14
+ * @returns True if the lifetime is currently valid, false otherwise
15
+ */
16
+ export declare function isLifetimeValid(lifetime: Lifetime): boolean;
17
+ /**
18
+ * Creates the default produced KeyPackage lifetime: an 84-day range
19
+ * (7,257,600 s — deliberately ~1h under the 7,261,200 s cap for headroom),
20
+ * with `notBefore` backdated ~1h so a peer's minor clock skew does not
21
+ * reject a just-published KeyPackage as not-yet-valid (D-07).
22
+ *
23
+ * @returns A lifetime object with notBefore backdated ~1h and notAfter 84 days after notBefore
24
+ */
25
+ export declare function createDefaultKeyPackageLifetime(): Lifetime;
26
+ /**
27
+ * Creates a lifetime with a 3-month expiration from the current time.
28
+ *
29
+ * @deprecated Use {@link createDefaultKeyPackageLifetime} instead.
30
+ * @returns A lifetime object with notBefore set to current time and notAfter set to 3 months from now
31
+ */
32
+ export declare function createThreeMonthLifetime(): Lifetime;
33
+ /**
34
+ * Checks whether a lifetime's range is within the ≤7,261,200 s (84 days + 1h)
35
+ * cap (D-08). This is a strict check — no grace is applied to the range
36
+ * itself (only to the current-check, see {@link isLifetimeCurrentWithGrace}).
37
+ *
38
+ * @param lifetime - The lifetime object with notBefore and notAfter fields
39
+ * @returns True if `notAfter - notBefore` is within the cap, false otherwise
40
+ */
41
+ export declare function isLifetimeWithinCap(lifetime: Lifetime): boolean;
42
+ /**
43
+ * Checks whether a lifetime is current, applying a symmetric ~1h grace
44
+ * window to tolerate minor clock skew (D-08): rejects only if `now` is
45
+ * before `notBefore - 3600` or after `notAfter + 3600`.
46
+ *
47
+ * @param lifetime - The lifetime object with notBefore and notAfter fields
48
+ * @returns True if `now` is within the lifetime's range plus grace, false otherwise
49
+ */
50
+ export declare function isLifetimeCurrentWithGrace(lifetime: Lifetime): boolean;
@@ -0,0 +1,95 @@
1
+ /** @module @category Utilities */
2
+ import { defaultLifetime } from "ts-mls";
3
+ /**
4
+ * The maximum allowed KeyPackage `Lifetime` range (84 days + 1h headroom,
5
+ * 7,261,200 s), per the post-#236 wire-boundary cap (D-08).
6
+ */
7
+ const MAX_KEY_PACKAGE_LIFETIME_SECONDS = 7261200n;
8
+ /**
9
+ * The symmetric clock-skew grace window (~1h, 3600 s) applied both to the
10
+ * produce-side backdate and the inbound current-check (D-07/D-08).
11
+ */
12
+ const LIFETIME_GRACE_SECONDS = 3600n;
13
+ /**
14
+ * Formats a bigint timestamp to a readable date string, handling special MLS timestamp values.
15
+ *
16
+ * @param timestamp - The timestamp as a bigint (typically from MLS lifetime fields)
17
+ * @returns A formatted date string or descriptive text for special values
18
+ */
19
+ export function formatMlsTimestamp(timestamp) {
20
+ const lifetime = defaultLifetime();
21
+ if (timestamp === lifetime.notAfter) {
22
+ return "No expiration";
23
+ }
24
+ if (timestamp === lifetime.notBefore) {
25
+ return "Epoch (1970-01-01)";
26
+ }
27
+ // Convert to milliseconds and create Date object
28
+ const date = new Date(Number(timestamp) * 1000);
29
+ // Check if the date is valid (not NaN)
30
+ if (isNaN(date.getTime())) {
31
+ return "Invalid date";
32
+ }
33
+ return date.toLocaleString();
34
+ }
35
+ /**
36
+ * Checks if a lifetime is currently valid, handling the "no expiration" case.
37
+ *
38
+ * @param lifetime - The lifetime object with notBefore and notAfter fields
39
+ * @returns True if the lifetime is currently valid, false otherwise
40
+ */
41
+ export function isLifetimeValid(lifetime) {
42
+ const currentTime = BigInt(Math.floor(Date.now() / 1000));
43
+ const defaultLt = defaultLifetime();
44
+ return (currentTime >= lifetime.notBefore &&
45
+ (lifetime.notAfter === defaultLt.notAfter ||
46
+ currentTime <= lifetime.notAfter));
47
+ }
48
+ /**
49
+ * Creates the default produced KeyPackage lifetime: an 84-day range
50
+ * (7,257,600 s — deliberately ~1h under the 7,261,200 s cap for headroom),
51
+ * with `notBefore` backdated ~1h so a peer's minor clock skew does not
52
+ * reject a just-published KeyPackage as not-yet-valid (D-07).
53
+ *
54
+ * @returns A lifetime object with notBefore backdated ~1h and notAfter 84 days after notBefore
55
+ */
56
+ export function createDefaultKeyPackageLifetime() {
57
+ const now = BigInt(Math.floor(Date.now() / 1000));
58
+ const notBefore = now - LIFETIME_GRACE_SECONDS;
59
+ const eightyFourDaysInSeconds = 84n * 24n * 60n * 60n;
60
+ const notAfter = notBefore + eightyFourDaysInSeconds;
61
+ return { notBefore, notAfter };
62
+ }
63
+ /**
64
+ * Creates a lifetime with a 3-month expiration from the current time.
65
+ *
66
+ * @deprecated Use {@link createDefaultKeyPackageLifetime} instead.
67
+ * @returns A lifetime object with notBefore set to current time and notAfter set to 3 months from now
68
+ */
69
+ export function createThreeMonthLifetime() {
70
+ return createDefaultKeyPackageLifetime();
71
+ }
72
+ /**
73
+ * Checks whether a lifetime's range is within the ≤7,261,200 s (84 days + 1h)
74
+ * cap (D-08). This is a strict check — no grace is applied to the range
75
+ * itself (only to the current-check, see {@link isLifetimeCurrentWithGrace}).
76
+ *
77
+ * @param lifetime - The lifetime object with notBefore and notAfter fields
78
+ * @returns True if `notAfter - notBefore` is within the cap, false otherwise
79
+ */
80
+ export function isLifetimeWithinCap(lifetime) {
81
+ return (lifetime.notAfter - lifetime.notBefore <= MAX_KEY_PACKAGE_LIFETIME_SECONDS);
82
+ }
83
+ /**
84
+ * Checks whether a lifetime is current, applying a symmetric ~1h grace
85
+ * window to tolerate minor clock skew (D-08): rejects only if `now` is
86
+ * before `notBefore - 3600` or after `notAfter + 3600`.
87
+ *
88
+ * @param lifetime - The lifetime object with notBefore and notAfter fields
89
+ * @returns True if `now` is within the lifetime's range plus grace, false otherwise
90
+ */
91
+ export function isLifetimeCurrentWithGrace(lifetime) {
92
+ const now = BigInt(Math.floor(Date.now() / 1000));
93
+ return (now >= lifetime.notBefore - LIFETIME_GRACE_SECONDS &&
94
+ now <= lifetime.notAfter + LIFETIME_GRACE_SECONDS);
95
+ }
@@ -0,0 +1,112 @@
1
+ /**
2
+ * @module @category Build identity
3
+ *
4
+ * Locally authored (not vendored from marmot-ts; listed in VENDOR.md's
5
+ * "Locally authored (not vendored)" section). The constants identify the
6
+ * engine build that wrote a stored artifact: `@941design/marmot`'s storage
7
+ * envelope (ADR-007 §3, epic-marmot-client AC-STORE-2) stamps
8
+ * `ENGINE_VERSION` and `TS_MLS_PIN` on every write and refuses any envelope
9
+ * whose stamp differs.
10
+ *
11
+ * `ENGINE_VERSION` is the compared stamp: `state.<ENGINE_STATE_FORMAT>`, a
12
+ * hand-maintained state-format number (BACKLOG
13
+ * `engine-version-digest-overtriggers`, 2026-11-09). It must change whenever
14
+ * an engine change could make a stored artifact read differently: a
15
+ * serialized format, a selection/convergence rule whose decisions marmot
16
+ * persists (rewind tree, terminal ledger, held set, own-commit stamps), or a
17
+ * decoder of stored bytes. It need not change for an edit that touches none of
18
+ * these (a comment, a new read-only accessor), so such an edit no longer
19
+ * refuses every existing store.
20
+ *
21
+ * The decision is forced, not optional: the digests below still identify the
22
+ * engine code, and `state-format-ledger.json` (package root) records, per
23
+ * digest pair, the state format it was judged to be. Its last entry must
24
+ * match the digests on disk (`packages/marmot/test/engine-version.test.ts`),
25
+ * so every code change makes the author either bump `ENGINE_STATE_FORMAT` or
26
+ * append a same-format entry whose `note` says why nothing stored reads
27
+ * differently. When in doubt, bump. `ENGINE_BUILD` keeps the full code
28
+ * identity for diagnostics.
29
+ *
30
+ * The digests change whenever the engine code changes. The vendored source is
31
+ * upstream `marmot-ts` at the VENDOR.md pin plus `patches/*.diff`; the
32
+ * locally-authored (never-vendored) source is VENDOR.md's "Locally
33
+ * authored (not vendored)" list. `ENGINE_BUILD` folds in all three: the
34
+ * package version, `PATCHSET_DIGEST` (the vendored+patched side), and
35
+ * `LOCAL_SOURCE_DIGEST` (the locally-authored side). Changes that must
36
+ * update this file (and, for a digest, the ledger):
37
+ * - a package.json `version` bump → `ENGINE_PACKAGE_VERSION`;
38
+ * - any added, removed, renamed or edited `patches/*.diff` that touches a
39
+ * non-test engine source file, or a move of the marmot-ts pin in
40
+ * VENDOR.md → `PATCHSET_DIGEST`;
41
+ * - an edit to a non-test file in VENDOR.md's "Locally authored (not
42
+ * vendored)" list (other than this file itself — see below) →
43
+ * `LOCAL_SOURCE_DIGEST`;
44
+ * - a move of the `ts-mls` git+SHA pin → `TS_MLS_PIN` (compared separately).
45
+ *
46
+ * A patch is test-only — and excluded from `PATCHSET_DIGEST` — when every
47
+ * file it touches sits under a `__tests__/` directory: a `*.test.ts` spec, a
48
+ * test-only helper, or a test fixture. A file's target path is read from
49
+ * every `---`/`+++` header (so deletions count) AND every `rename from`/
50
+ * `rename to`/`copy from`/`copy to` header — a pure rename or copy carries
51
+ * no `---`/`+++` lines of its own, so a patch that combines a pure rename of
52
+ * a production file with a genuinely test-only hunk would otherwise be
53
+ * misclassified as test-only by the `---`/`+++` paths alone. Such a patch
54
+ * can never change the shape of state the engine serializes, so folding it
55
+ * into the stamp would force spurious envelope-mismatch churn on stored
56
+ * artifacts whenever a test or conformance/flake patch is touched. A patch
57
+ * that touches even one non-test file (source under `core/`, `engine/`,
58
+ * `audit/`, `utils/`, `index.ts`, `mls.ts`, …) is hashed in full, in the
59
+ * order below.
60
+ *
61
+ * `LOCAL_SOURCE_DIGEST` covers the other half of locally-authored source
62
+ * that `PATCHSET_DIGEST` cannot see: files in VENDOR.md's "Locally authored
63
+ * (not vendored)" list have no `patches/*.diff` entry (they were never
64
+ * vendored, so there is nothing to diff against upstream), so an edit to
65
+ * one is otherwise invisible to the stamp. It is a digest over every listed
66
+ * path that is (a) not itself under a `__tests__/` directory and (b) not
67
+ * this file (`src/version.ts` folding itself in would be circular — a
68
+ * change to this file already bumps `ENGINE_VERSION` directly, since the
69
+ * literals live here). Today the one such path is `src/core/leaf-succession.ts`
70
+ * (every other listed path is a test path), so the digest covers that file;
71
+ * it closes the gap for each non-test locally-authored file added to that
72
+ * list, without a second remediation round.
73
+ *
74
+ * Literals rather than a runtime read so the value is fixed at build time and
75
+ * needs no JSON or fs import. `packages/marmot/test/engine-version.test.ts`
76
+ * recomputes each from disk and fails — printing the expected value — when
77
+ * any drifts, so a patch or locally-authored-source change cannot ship with
78
+ * a stale stamp.
79
+ */
80
+ /** `@941design/marmot-engine` package version. */
81
+ export declare const ENGINE_PACKAGE_VERSION = "0.1.0";
82
+ /**
83
+ * First 16 hex chars of SHA-256 over `marmot-ts@<pin SHA>\n` followed by,
84
+ * for each non-test `patches/*.diff` (a patch excluded only when every one
85
+ * of its diff's `---`/`+++`/`rename from`/`rename to`/`copy from`/`copy to`
86
+ * paths sits under a `__tests__/` directory) in code-unit order,
87
+ * `<file name>\n<byte length>\n<bytes>`.
88
+ *
89
+ * Blind spot: it hashes the patch files, not the vendored tree, so a direct
90
+ * edit to a vendored file (bypassing `patches/`) or a new production file not
91
+ * listed as locally authored moves neither digest. `scripts/vendor/verify.sh`'s
92
+ * full re-derivation is the authoritative guard for that.
93
+ */
94
+ export declare const PATCHSET_DIGEST = "bd07cca1c2873857";
95
+ /**
96
+ * First 16 hex chars of SHA-256 over `local-source\n` followed by, for each
97
+ * non-test, non-`src/version.ts` path in VENDOR.md's "Locally authored (not
98
+ * vendored)" list, in code-unit order, `<path>\n<byte length>\n<bytes>`.
99
+ */
100
+ export declare const LOCAL_SOURCE_DIGEST = "dda4692d9eb4c034";
101
+ /**
102
+ * The engine's stored-state format. Bump it for any change that could make a
103
+ * stored artifact read differently (see the module doc); record each digest
104
+ * move in `state-format-ledger.json` either way.
105
+ */
106
+ export declare const ENGINE_STATE_FORMAT = 1;
107
+ /** The envelope's engine stamp (compared on every read): the state format. */
108
+ export declare const ENGINE_VERSION = "state.1";
109
+ /** The engine build's full code identity (diagnostics): package version plus the vendored patch set and the locally-authored source. */
110
+ export declare const ENGINE_BUILD = "0.1.0+patches.bd07cca1c2873857.local.dda4692d9eb4c034";
111
+ /** Commit SHA of the `941design/ts-mls` pin recorded in VENDOR.md (consumed via the `@941design/ts-mls` registry alias). */
112
+ export declare const TS_MLS_PIN = "26afb1d69fd4c5a613b8319610a69e4f4239e5b5";