@941design/marmot 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 (192) hide show
  1. package/CHANGELOG.md +709 -0
  2. package/LICENSE +21 -0
  3. package/README.md +33 -2
  4. package/dist/account/admin.d.ts +72 -0
  5. package/dist/account/admin.js +209 -0
  6. package/dist/account/device-deps.d.ts +379 -0
  7. package/dist/account/device-deps.js +36 -0
  8. package/dist/account/device-lineage.d.ts +199 -0
  9. package/dist/account/device-lineage.js +390 -0
  10. package/dist/account/device-registry.d.ts +93 -0
  11. package/dist/account/device-registry.js +1290 -0
  12. package/dist/account/device-rotation.d.ts +61 -0
  13. package/dist/account/device-rotation.js +827 -0
  14. package/dist/account/enrolment.d.ts +339 -0
  15. package/dist/account/enrolment.js +1247 -0
  16. package/dist/account/identity-proof.d.ts +79 -0
  17. package/dist/account/identity-proof.js +264 -0
  18. package/dist/account/index.d.ts +17 -0
  19. package/dist/account/index.js +16 -0
  20. package/dist/account/restore-rotation.d.ts +21 -0
  21. package/dist/account/restore-rotation.js +22 -0
  22. package/dist/account/same-account-authorization.d.ts +86 -0
  23. package/dist/account/same-account-authorization.js +180 -0
  24. package/dist/account/teardown.d.ts +127 -0
  25. package/dist/account/teardown.js +856 -0
  26. package/dist/client/before-create-group.d.ts +18 -0
  27. package/dist/client/before-create-group.js +65 -0
  28. package/dist/client/before-publish-hooks.d.ts +121 -0
  29. package/dist/client/before-publish-hooks.js +180 -0
  30. package/dist/client/client-config.d.ts +42 -0
  31. package/dist/client/client-config.js +13 -0
  32. package/dist/client/commit-redrive.d.ts +68 -0
  33. package/dist/client/commit-redrive.js +221 -0
  34. package/dist/client/component-update.d.ts +43 -0
  35. package/dist/client/component-update.js +53 -0
  36. package/dist/client/confirm-hooks.d.ts +50 -0
  37. package/dist/client/confirm-hooks.js +59 -0
  38. package/dist/client/create-client.d.ts +1022 -0
  39. package/dist/client/create-client.js +1125 -0
  40. package/dist/client/group-disband.d.ts +28 -0
  41. package/dist/client/group-disband.js +64 -0
  42. package/dist/client/group-history.d.ts +435 -0
  43. package/dist/client/group-history.js +1295 -0
  44. package/dist/client/group-profile.d.ts +31 -0
  45. package/dist/client/group-profile.js +62 -0
  46. package/dist/client/group-records.d.ts +485 -0
  47. package/dist/client/group-records.js +1034 -0
  48. package/dist/client/group-removal.d.ts +36 -0
  49. package/dist/client/group-removal.js +127 -0
  50. package/dist/client/group-remove-member.d.ts +49 -0
  51. package/dist/client/group-remove-member.js +163 -0
  52. package/dist/client/group-runtime.d.ts +388 -0
  53. package/dist/client/group-runtime.js +2701 -0
  54. package/dist/client/group-snapshot.d.ts +98 -0
  55. package/dist/client/group-snapshot.js +453 -0
  56. package/dist/client/history-pages.d.ts +107 -0
  57. package/dist/client/history-pages.js +194 -0
  58. package/dist/client/inbox-send.d.ts +19 -0
  59. package/dist/client/inbox-send.js +71 -0
  60. package/dist/client/index.d.ts +21 -0
  61. package/dist/client/index.js +13 -0
  62. package/dist/client/ingest.d.ts +82 -0
  63. package/dist/client/ingest.js +1550 -0
  64. package/dist/client/lifecycle-events.d.ts +63 -0
  65. package/dist/client/lifecycle-events.js +35 -0
  66. package/dist/client/opaque-candidates.d.ts +81 -0
  67. package/dist/client/opaque-candidates.js +169 -0
  68. package/dist/client/own-change-outbox.d.ts +66 -0
  69. package/dist/client/own-change-outbox.js +156 -0
  70. package/dist/client/pending-leaf.d.ts +116 -0
  71. package/dist/client/pending-leaf.js +378 -0
  72. package/dist/client/permissions.d.ts +9 -0
  73. package/dist/client/permissions.js +12 -0
  74. package/dist/client/pipeline.d.ts +554 -0
  75. package/dist/client/pipeline.js +3545 -0
  76. package/dist/client/reentrancy-guard.d.ts +96 -0
  77. package/dist/client/reentrancy-guard.js +153 -0
  78. package/dist/client/rekey.d.ts +58 -0
  79. package/dist/client/rekey.js +149 -0
  80. package/dist/client/transport-policy.d.ts +181 -0
  81. package/dist/client/transport-policy.js +214 -0
  82. package/dist/history/equivocation.d.ts +55 -0
  83. package/dist/history/equivocation.js +113 -0
  84. package/dist/history/fencing.d.ts +25 -0
  85. package/dist/history/fencing.js +61 -0
  86. package/dist/history/hex.d.ts +3 -0
  87. package/dist/history/hex.js +10 -0
  88. package/dist/history/index.d.ts +73 -0
  89. package/dist/history/index.js +31 -0
  90. package/dist/history/notifications.d.ts +270 -0
  91. package/dist/history/notifications.js +264 -0
  92. package/dist/history/ordering-key.d.ts +24 -0
  93. package/dist/history/ordering-key.js +101 -0
  94. package/dist/history/own-change-fork.d.ts +112 -0
  95. package/dist/history/own-change-fork.js +196 -0
  96. package/dist/history/own-change.d.ts +106 -0
  97. package/dist/history/own-change.js +146 -0
  98. package/dist/history/policy.d.ts +48 -0
  99. package/dist/history/policy.js +52 -0
  100. package/dist/history/retained-window.d.ts +215 -0
  101. package/dist/history/retained-window.js +565 -0
  102. package/dist/inbox/demux.d.ts +90 -0
  103. package/dist/inbox/demux.js +78 -0
  104. package/dist/inbox/handler-registry.d.ts +42 -0
  105. package/dist/inbox/handler-registry.js +37 -0
  106. package/dist/inbox/index.d.ts +11 -0
  107. package/dist/inbox/index.js +10 -0
  108. package/dist/inbox/seen-set.d.ts +82 -0
  109. package/dist/inbox/seen-set.js +202 -0
  110. package/dist/inbox/subscription.d.ts +236 -0
  111. package/dist/inbox/subscription.js +644 -0
  112. package/dist/index.d.ts +10 -0
  113. package/dist/index.js +9 -0
  114. package/dist/invitations/competing-welcome.d.ts +223 -0
  115. package/dist/invitations/competing-welcome.js +128 -0
  116. package/dist/invitations/decline.d.ts +61 -0
  117. package/dist/invitations/decline.js +143 -0
  118. package/dist/invitations/expect-welcome.d.ts +66 -0
  119. package/dist/invitations/expect-welcome.js +138 -0
  120. package/dist/invitations/index.d.ts +16 -0
  121. package/dist/invitations/index.js +16 -0
  122. package/dist/invitations/invite.d.ts +303 -0
  123. package/dist/invitations/invite.js +966 -0
  124. package/dist/invitations/offers.d.ts +79 -0
  125. package/dist/invitations/offers.js +115 -0
  126. package/dist/invitations/on-proposal.d.ts +47 -0
  127. package/dist/invitations/on-proposal.js +40 -0
  128. package/dist/invitations/pending-proposal-policy.d.ts +52 -0
  129. package/dist/invitations/pending-proposal-policy.js +139 -0
  130. package/dist/invitations/proposal-deadline.d.ts +133 -0
  131. package/dist/invitations/proposal-deadline.js +164 -0
  132. package/dist/invitations/relay-planes.d.ts +43 -0
  133. package/dist/invitations/relay-planes.js +70 -0
  134. package/dist/invitations/welcome-processor.d.ts +253 -0
  135. package/dist/invitations/welcome-processor.js +1180 -0
  136. package/dist/key-packages/device-key.d.ts +131 -0
  137. package/dist/key-packages/device-key.js +272 -0
  138. package/dist/key-packages/device-rotation-records.d.ts +83 -0
  139. package/dist/key-packages/device-rotation-records.js +173 -0
  140. package/dist/key-packages/group-refs.d.ts +40 -0
  141. package/dist/key-packages/group-refs.js +79 -0
  142. package/dist/key-packages/index.d.ts +18 -0
  143. package/dist/key-packages/index.js +18 -0
  144. package/dist/key-packages/key-package-ref.d.ts +16 -0
  145. package/dist/key-packages/key-package-ref.js +21 -0
  146. package/dist/key-packages/observation-stream.d.ts +4 -0
  147. package/dist/key-packages/observation-stream.js +120 -0
  148. package/dist/key-packages/offer-rumor.d.ts +26 -0
  149. package/dist/key-packages/offer-rumor.js +69 -0
  150. package/dist/key-packages/publisher.d.ts +174 -0
  151. package/dist/key-packages/publisher.js +1247 -0
  152. package/dist/key-packages/select-key-package.d.ts +24 -0
  153. package/dist/key-packages/select-key-package.js +90 -0
  154. package/dist/key-packages/slot-manager.d.ts +167 -0
  155. package/dist/key-packages/slot-manager.js +327 -0
  156. package/dist/key-packages/validate-key-package-event.d.ts +3 -0
  157. package/dist/key-packages/validate-key-package-event.js +49 -0
  158. package/dist/media/cache.d.ts +14 -0
  159. package/dist/media/cache.js +10 -0
  160. package/dist/media/index.d.ts +52 -0
  161. package/dist/media/index.js +71 -0
  162. package/dist/mls.d.ts +15 -0
  163. package/dist/mls.js +15 -0
  164. package/dist/shared/account-pubkey.d.ts +4 -0
  165. package/dist/shared/account-pubkey.js +10 -0
  166. package/dist/shared/errors.d.ts +21 -0
  167. package/dist/shared/errors.js +85 -0
  168. package/dist/shared/hex.d.ts +4 -0
  169. package/dist/shared/hex.js +13 -0
  170. package/dist/shared/index.d.ts +14 -0
  171. package/dist/shared/index.js +14 -0
  172. package/dist/shared/kinds.d.ts +8 -0
  173. package/dist/shared/kinds.js +28 -0
  174. package/dist/shared/publish-classification.d.ts +26 -0
  175. package/dist/shared/publish-classification.js +31 -0
  176. package/dist/storage/envelope.d.ts +39 -0
  177. package/dist/storage/envelope.js +201 -0
  178. package/dist/storage/index.d.ts +227 -0
  179. package/dist/storage/index.js +459 -0
  180. package/dist/storage/indexeddb/idb-types.d.ts +68 -0
  181. package/dist/storage/indexeddb/idb-types.js +1 -0
  182. package/dist/storage/indexeddb/index.d.ts +17 -0
  183. package/dist/storage/indexeddb/index.js +141 -0
  184. package/dist/storage/lease.d.ts +41 -0
  185. package/dist/storage/lease.js +117 -0
  186. package/dist/storage/memory/deterministic-signer.d.ts +27 -0
  187. package/dist/storage/memory/deterministic-signer.js +65 -0
  188. package/dist/storage/memory/index.d.ts +32 -0
  189. package/dist/storage/memory/index.js +87 -0
  190. package/dist/storage/memory/lock-manager.d.ts +8 -0
  191. package/dist/storage/memory/lock-manager.js +71 -0
  192. package/package.json +66 -3
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The media cache seam (AC-MEDIA-2): where `group.encryptMedia` leaves a
3
+ * ciphertext and `group.decryptMedia` finds one it was not handed, keyed by
4
+ * the blob's locator (the hex SHA-256 of the ciphertext — its content
5
+ * address). `marmot` never uploads or downloads media: moving blobs to and
6
+ * from Blossom (or any store) stays with the application, which may back
7
+ * this seam with its own persistent cache.
8
+ */
9
+ export interface MediaCache {
10
+ get(locator: string): Uint8Array | undefined | Promise<Uint8Array | undefined>;
11
+ put(locator: string, ciphertext: Uint8Array): void | Promise<void>;
12
+ }
13
+ /** A `MediaCache` over process memory: a map, nothing else (no network, no persistence). */
14
+ export declare function createMemoryMediaCache(): MediaCache;
@@ -0,0 +1,10 @@
1
+ /** A `MediaCache` over process memory: a map, nothing else (no network, no persistence). */
2
+ export function createMemoryMediaCache() {
3
+ const blobs = new Map();
4
+ return {
5
+ get: (locator) => blobs.get(locator)?.slice(),
6
+ put: (locator, ciphertext) => {
7
+ blobs.set(locator, ciphertext.slice());
8
+ },
9
+ };
10
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * `history-media` (S10), media half: `encrypted-media-v1` over the group key
3
+ * (AC-MEDIA-1), through the vendored `core/media` — key derivation from the
4
+ * epoch's MLS exporter, ChaCha20-Poly1305, the `imeta` tag codec — and the
5
+ * media cache seam (AC-MEDIA-2, `cache.ts`).
6
+ *
7
+ * A media key is derived from the epoch the carrying message is sent in, and
8
+ * a receiver does not learn that epoch from the blob: decryption tries every
9
+ * epoch the group still retains (the rollback horizon), newest first, exactly
10
+ * as the engine's `retainedStates()` is documented for.
11
+ */
12
+ import { type MediaAttachment } from '@941design/marmot-engine/core';
13
+ import type { CiphersuiteImpl, ClientState } from '@941design/marmot-engine/mls';
14
+ export { createMemoryMediaCache, type MediaCache } from './cache.js';
15
+ /** What `encryptMedia` returns: the ciphertext, its `imeta` tag set and its locator. */
16
+ export interface EncryptedMedia {
17
+ readonly ciphertext: Uint8Array;
18
+ /** One `encrypted-media-v1` `imeta` tag (`core/media` codec) — put it on the rumor carrying the attachment. */
19
+ readonly imeta: readonly (readonly string[])[];
20
+ /** The blob's content address: hex SHA-256 of `ciphertext` (the Blossom blob id, and the media cache key). */
21
+ readonly locator: string;
22
+ }
23
+ export interface EncryptMediaOptions {
24
+ /** MIME type (canonicalized); default `application/octet-stream`. */
25
+ readonly mediaType?: string;
26
+ /** Display filename (part of the key derivation); default `media`. */
27
+ readonly filename?: string;
28
+ /** `<width>x<height>` render hint. */
29
+ readonly dim?: string;
30
+ readonly thumbhash?: string;
31
+ /**
32
+ * Blossom servers the application will upload the ciphertext to: each
33
+ * becomes a `blossom-v1` locator `<server>/<locator>` (a Blossom blob URL is
34
+ * its SHA-256). Omitted: the tag carries one `marmot-cache-v1` locator — a
35
+ * kind receivers skip as unfetchable — until the application adds its own.
36
+ */
37
+ readonly blossomServers?: readonly string[];
38
+ }
39
+ /** The locator kind naming only the local media cache (not fetchable by anyone else). */
40
+ export declare const CACHE_LOCATOR_KIND = "marmot-cache-v1";
41
+ /** Hex SHA-256 of `bytes` (a blob's content address). */
42
+ export declare function sha256Hex(bytes: Uint8Array): Promise<string>;
43
+ /** Encrypts `bytes` under `state`'s epoch (the epoch the carrying message goes out in). */
44
+ export declare function encryptMedia(state: ClientState, cs: CiphersuiteImpl, bytes: Uint8Array, options?: EncryptMediaOptions): Promise<EncryptedMedia>;
45
+ /** The `encrypted-media-v1` attachment an `imeta` tag set describes (the first valid one), or `undefined`. */
46
+ export declare function attachmentOf(imeta: readonly (readonly string[])[]): MediaAttachment | undefined;
47
+ /**
48
+ * Decrypts `ciphertext` described by `attachment`, trying the media key of
49
+ * every state in `states` (the retained epochs, newest first). Throws when
50
+ * the ciphertext does not match the attachment's hash or no epoch's key opens it.
51
+ */
52
+ export declare function decryptMedia(states: readonly ClientState[], cs: CiphersuiteImpl, ciphertext: Uint8Array, attachment: MediaAttachment): Promise<Uint8Array>;
@@ -0,0 +1,71 @@
1
+ /**
2
+ * `history-media` (S10), media half: `encrypted-media-v1` over the group key
3
+ * (AC-MEDIA-1), through the vendored `core/media` — key derivation from the
4
+ * epoch's MLS exporter, ChaCha20-Poly1305, the `imeta` tag codec — and the
5
+ * media cache seam (AC-MEDIA-2, `cache.ts`).
6
+ *
7
+ * A media key is derived from the epoch the carrying message is sent in, and
8
+ * a receiver does not learn that epoch from the blob: decryption tries every
9
+ * epoch the group still retains (the rollback horizon), newest first, exactly
10
+ * as the engine's `retainedStates()` is documented for.
11
+ */
12
+ import { BLOSSOM_LOCATOR_KIND, decryptMediaFileWithKeys, deriveMediaEncryptionKey, encodeMediaImetaTag, encryptMediaFile, parseMediaImetaTag, } from '@941design/marmot-engine/core';
13
+ export { createMemoryMediaCache } from './cache.js';
14
+ /** The locator kind naming only the local media cache (not fetchable by anyone else). */
15
+ export const CACHE_LOCATOR_KIND = 'marmot-cache-v1';
16
+ /** Hex SHA-256 of `bytes` (a blob's content address). */
17
+ export async function sha256Hex(bytes) {
18
+ const digest = new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', bytes));
19
+ return Array.from(digest, (b) => b.toString(16).padStart(2, '0')).join('');
20
+ }
21
+ function locatorsFor(options, ciphertextSha256) {
22
+ const servers = options.blossomServers ?? [];
23
+ if (servers.length === 0)
24
+ return [{ kind: CACHE_LOCATOR_KIND, value: `marmot-cache:${ciphertextSha256}` }];
25
+ return servers.map((server) => ({ kind: BLOSSOM_LOCATOR_KIND, value: `${server.replace(/\/+$/, '')}/${ciphertextSha256}` }));
26
+ }
27
+ /** Encrypts `bytes` under `state`'s epoch (the epoch the carrying message goes out in). */
28
+ export async function encryptMedia(state, cs, bytes, options = {}) {
29
+ const fields = {
30
+ plaintextSha256: await sha256Hex(bytes),
31
+ mediaType: options.mediaType ?? 'application/octet-stream',
32
+ filename: options.filename ?? 'media',
33
+ };
34
+ const key = await deriveMediaEncryptionKey(state, cs, fields);
35
+ const { encrypted, attachment } = encryptMediaFile(bytes, key, {
36
+ ...fields,
37
+ ...(options.dim === undefined ? {} : { dim: options.dim }),
38
+ ...(options.thumbhash === undefined ? {} : { thumbhash: options.thumbhash }),
39
+ });
40
+ const withLocators = { ...attachment, locators: locatorsFor(options, attachment.ciphertextSha256) };
41
+ return Object.freeze({
42
+ ciphertext: encrypted,
43
+ imeta: Object.freeze([Object.freeze(encodeMediaImetaTag(withLocators))]),
44
+ locator: attachment.ciphertextSha256,
45
+ });
46
+ }
47
+ /** The `encrypted-media-v1` attachment an `imeta` tag set describes (the first valid one), or `undefined`. */
48
+ export function attachmentOf(imeta) {
49
+ for (const tag of imeta) {
50
+ try {
51
+ const attachment = parseMediaImetaTag([...tag]);
52
+ if (attachment !== null)
53
+ return attachment;
54
+ }
55
+ catch {
56
+ // not a valid encrypted-media-v1 imeta tag: try the next one
57
+ }
58
+ }
59
+ return undefined;
60
+ }
61
+ /**
62
+ * Decrypts `ciphertext` described by `attachment`, trying the media key of
63
+ * every state in `states` (the retained epochs, newest first). Throws when
64
+ * the ciphertext does not match the attachment's hash or no epoch's key opens it.
65
+ */
66
+ export async function decryptMedia(states, cs, ciphertext, attachment) {
67
+ const keys = [];
68
+ for (const state of states)
69
+ keys.push(await deriveMediaEncryptionKey(state, cs, attachment));
70
+ return decryptMediaFileWithKeys(ciphertext, keys, attachment);
71
+ }
package/dist/mls.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * @module @category MLS re-export seam (AC-API-6)
3
+ *
4
+ * `marmot` never depends on `ts-mls` directly (ADR-005, single-instance
5
+ * rule — see architecture.md boundary rule 2 and
6
+ * `packages/marmot-engine/src/mls.ts`). This file re-exports the full
7
+ * `ts-mls` surface reachable through `@941design/marmot-engine/mls`, so a
8
+ * consumer importing `@941design/marmot/mls` and one importing
9
+ * `@941design/marmot-engine/mls` resolve to the exact same module
10
+ * instance — proven by `fixtures/consumers/harness/harness.test.ts`'s
11
+ * AC-API-6 describe block: a `tsc` two-copy assignment check
12
+ * (`mls-identity.probe.ts`) and a runtime identity probe, both run against
13
+ * the BUILT packages exactly as a consumer would resolve them.
14
+ */
15
+ export * from "@941design/marmot-engine/mls";
package/dist/mls.js ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * @module @category MLS re-export seam (AC-API-6)
3
+ *
4
+ * `marmot` never depends on `ts-mls` directly (ADR-005, single-instance
5
+ * rule — see architecture.md boundary rule 2 and
6
+ * `packages/marmot-engine/src/mls.ts`). This file re-exports the full
7
+ * `ts-mls` surface reachable through `@941design/marmot-engine/mls`, so a
8
+ * consumer importing `@941design/marmot/mls` and one importing
9
+ * `@941design/marmot-engine/mls` resolve to the exact same module
10
+ * instance — proven by `fixtures/consumers/harness/harness.test.ts`'s
11
+ * AC-API-6 describe block: a `tsc` two-copy assignment check
12
+ * (`mls-identity.probe.ts`) and a runtime identity probe, both run against
13
+ * the BUILT packages exactly as a consumer would resolve them.
14
+ */
15
+ export * from "@941design/marmot-engine/mls";
@@ -0,0 +1,4 @@
1
+ /** Whether `value` is a string of exactly 64 lowercase hex characters (a pubkey, a leaf signature key). */
2
+ export declare function isHex64(value: unknown): value is string;
3
+ /** Whether `account` is a well-formed account pubkey (a string of 64 lowercase hex characters). */
4
+ export declare function isAccountPubkey(account: unknown): account is string;
@@ -0,0 +1,10 @@
1
+ /** A 64-character lowercase hex string. */
2
+ const HEX64_PATTERN = /^[0-9a-f]{64}$/;
3
+ /** Whether `value` is a string of exactly 64 lowercase hex characters (a pubkey, a leaf signature key). */
4
+ export function isHex64(value) {
5
+ return typeof value === 'string' && HEX64_PATTERN.test(value);
6
+ }
7
+ /** Whether `account` is a well-formed account pubkey (a string of 64 lowercase hex characters). */
8
+ export function isAccountPubkey(account) {
9
+ return isHex64(account);
10
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * `MarmotError` — the one error type `@941design/marmot` throws, discriminated
3
+ * by `code` (architecture.md boundary rule; mirrors `nostr-events`'
4
+ * `SignerError` / `GiftWrapError`).
5
+ *
6
+ * The code set is closed and declared up front for the whole epic so later
7
+ * stories raise an existing code instead of widening the union ad hoc. Each
8
+ * entry names the acceptance criterion that produces it.
9
+ */
10
+ export declare const MARMOT_ERROR_CODES: readonly ["missing-budget", "invalid-options", "not-implemented", "disposed", "envelope-mismatch", "no-lease", "lease-held", "transaction-closed", "store-failed", "reentrant", "publish-failed", "send-rejected", "confirm-blocked", "commit-pending", "fenced", "handler-exists", "reserved-kind", "not-a-member", "no-inbox-relays", "last-admin", "invalid-admin-policy", "use-forget", "already-member"];
11
+ export type MarmotErrorCode = (typeof MARMOT_ERROR_CODES)[number];
12
+ export declare class MarmotError extends Error {
13
+ readonly code: MarmotErrorCode;
14
+ readonly details?: Readonly<Record<string, unknown>>;
15
+ constructor(code: MarmotErrorCode, message: string, opts?: {
16
+ cause?: unknown;
17
+ details?: Record<string, unknown>;
18
+ });
19
+ }
20
+ /** Type guard; with `code`, also narrows to that one code. */
21
+ export declare function isMarmotError(value: unknown, code?: MarmotErrorCode): value is MarmotError;
@@ -0,0 +1,85 @@
1
+ /**
2
+ * `MarmotError` — the one error type `@941design/marmot` throws, discriminated
3
+ * by `code` (architecture.md boundary rule; mirrors `nostr-events`'
4
+ * `SignerError` / `GiftWrapError`).
5
+ *
6
+ * The code set is closed and declared up front for the whole epic so later
7
+ * stories raise an existing code instead of widening the union ad hoc. Each
8
+ * entry names the acceptance criterion that produces it.
9
+ */
10
+ export const MARMOT_ERROR_CODES = Object.freeze([
11
+ /** Construction without a `budget` option (AC-API-5). */
12
+ 'missing-budget',
13
+ /** Construction or call argument that fails validation. */
14
+ 'invalid-options',
15
+ /** A surface member whose owning story has not landed yet (removed by AC-FIX-6). */
16
+ 'not-implemented',
17
+ /** Any call on a client after `dispose()`. */
18
+ 'disposed',
19
+ /** Stored envelope written by a different engine / ts-mls build (AC-STORE-2). */
20
+ 'envelope-mismatch',
21
+ /** Store opened for writing without holding the lease (AC-STORE-3). */
22
+ 'no-lease',
23
+ /** Lease for the same (backend instance, account) already held (AC-STORE-3). */
24
+ 'lease-held',
25
+ /** Store transaction used after it settled, or invalidated by a concurrent account wipe (AC-STORE-1). */
26
+ 'transaction-closed',
27
+ /** The storage backend failed to read or commit (e.g. an IndexedDB transaction abort). */
28
+ 'store-failed',
29
+ /** Synchronous re-entry into a mutating operation (AC-PIPE-11, ADR-013). */
30
+ 'reentrant',
31
+ /** No relay accepted a publish; the intent stays durable and `retryable` (AC-PIPE-3). */
32
+ 'publish-failed',
33
+ /** The engine refused an intent, or it went `terminal`; the intent was dropped (AC-PIPE-3, AC-PROOF-2). */
34
+ 'send-rejected',
35
+ /** A throwing `onConfirm` hook blocks confirmation of a published intent (AC-PIPE-13). */
36
+ 'confirm-blocked',
37
+ /**
38
+ * A commit-kind `send` while an own commit-kind intent is still
39
+ * `pending-publish` (a second own commit at that epoch would fork the
40
+ * group). Transient, nothing recorded: retryable once the pending commit
41
+ * confirms or goes terminal.
42
+ */
43
+ 'commit-pending',
44
+ /** ts-mls fork/fencing failure mapped from `InternalError` (AC-HIST-4). */
45
+ 'fenced',
46
+ /** Second `registerInboxHandler` for the same kind (AC-INBOX-5). */
47
+ 'handler-exists',
48
+ /** `registerInboxHandler` for a `RUMOR_KINDS` value (AC-INBOX-5). */
49
+ 'reserved-kind',
50
+ /** Operation requires group membership the caller no longer has. */
51
+ 'not-a-member',
52
+ /** Invitee has no resolvable inbox relay (AC-INVITE). */
53
+ 'no-inbox-relays',
54
+ /** Admin operation would leave no active admin (AC-ADMIN). */
55
+ 'last-admin',
56
+ /** `setAdmins` input violates the admin policy (AC-ADMIN). */
57
+ 'invalid-admin-policy',
58
+ /** Own-leaf removal must go through `devices.forget()` (AC-DEV / AC-ADMIN). */
59
+ 'use-forget',
60
+ /** `groups.restore(groupId, snapshot)` for a group this client already holds (AC-MX-2). */
61
+ 'already-member',
62
+ ]);
63
+ const CODE_SET = new Set(MARMOT_ERROR_CODES);
64
+ export class MarmotError extends Error {
65
+ code;
66
+ constructor(code, message, opts) {
67
+ // A caller bypassing the type system must not mint an unknown code — the
68
+ // closed set is what makes `code` a reliable discriminant.
69
+ if (!CODE_SET.has(code)) {
70
+ throw new TypeError(`MarmotError: unknown code ${JSON.stringify(code)}`);
71
+ }
72
+ super(message, opts?.cause === undefined ? undefined : { cause: opts.cause });
73
+ this.name = 'MarmotError';
74
+ this.code = code;
75
+ if (opts?.details !== undefined) {
76
+ this.details = Object.freeze({ ...opts.details });
77
+ }
78
+ }
79
+ }
80
+ /** Type guard; with `code`, also narrows to that one code. */
81
+ export function isMarmotError(value, code) {
82
+ if (!(value instanceof MarmotError))
83
+ return false;
84
+ return code === undefined || value.code === code;
85
+ }
@@ -0,0 +1,4 @@
1
+ /** Lowercase hex of `bytes`. */
2
+ export declare function hexOfBytes(bytes: Uint8Array): string;
3
+ /** The 32 bytes of a 64-character lowercase hex string, else `undefined`. */
4
+ export declare function bytesOfHex64(value: unknown): Uint8Array | undefined;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Lowercase-hex helpers shared by the modules that read or write hex digests and account keys (the Welcome `commit`
3
+ * tag in `invitations`, the join evidence in `history`); the format predicate is `isHex64` of account-pubkey.ts.
4
+ */
5
+ import { isHex64 } from './account-pubkey.js';
6
+ /** Lowercase hex of `bytes`. */
7
+ export function hexOfBytes(bytes) {
8
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
9
+ }
10
+ /** The 32 bytes of a 64-character lowercase hex string, else `undefined`. */
11
+ export function bytesOfHex64(value) {
12
+ return isHex64(value) ? Uint8Array.from(value.match(/../g), (h) => parseInt(h, 16)) : undefined;
13
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Leaf module (architecture.md `shared` row): `MarmotError`/`MARMOT_ERROR_CODES`,
3
+ * `RUMOR_KINDS` and `classifyPublish`, constants/helpers every other `marmot`
4
+ * module — and `client`, which re-exports them as part of the public surface
5
+ * or (for `classifyPublish`) re-exports them from `client/transport-policy.ts`
6
+ * — needs without creating an in-package import back into `client`. Imports
7
+ * nothing else in-package; `kinds.ts` imports `@941design/marmot-engine/core`
8
+ * for `WELCOME_EVENT_KIND`.
9
+ */
10
+ export { MarmotError, isMarmotError, MARMOT_ERROR_CODES, type MarmotErrorCode } from './errors.js';
11
+ export { RUMOR_KINDS, type RumorKind, type RumorKindConstants } from './kinds.js';
12
+ export { classifyPublish, type PublishOutcome } from './publish-classification.js';
13
+ export { isAccountPubkey, isHex64 } from './account-pubkey.js';
14
+ export { bytesOfHex64, hexOfBytes } from './hex.js';
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Leaf module (architecture.md `shared` row): `MarmotError`/`MARMOT_ERROR_CODES`,
3
+ * `RUMOR_KINDS` and `classifyPublish`, constants/helpers every other `marmot`
4
+ * module — and `client`, which re-exports them as part of the public surface
5
+ * or (for `classifyPublish`) re-exports them from `client/transport-policy.ts`
6
+ * — needs without creating an in-package import back into `client`. Imports
7
+ * nothing else in-package; `kinds.ts` imports `@941design/marmot-engine/core`
8
+ * for `WELCOME_EVENT_KIND`.
9
+ */
10
+ export { MarmotError, isMarmotError, MARMOT_ERROR_CODES } from './errors.js';
11
+ export { RUMOR_KINDS } from './kinds.js';
12
+ export { classifyPublish } from './publish-classification.js';
13
+ export { isAccountPubkey, isHex64 } from './account-pubkey.js';
14
+ export { bytesOfHex64, hexOfBytes } from './hex.js';
@@ -0,0 +1,8 @@
1
+ export declare const RUMOR_KINDS: Readonly<{
2
+ readonly WELCOME: 444;
3
+ readonly ENROLMENT_REQUEST: 4460;
4
+ readonly KEYPACKAGE_OFFER: 4461;
5
+ readonly DECLINE: 4462;
6
+ }>;
7
+ export type RumorKindConstants = typeof RUMOR_KINDS;
8
+ export type RumorKind = RumorKindConstants[keyof RumorKindConstants];
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Rumor kinds pinned once for the whole package (spec Design Decision 14,
3
+ * AC-API-8). Every story that encodes or matches one of these rumors imports
4
+ * `RUMOR_KINDS` — never a numeric literal — and `registerInboxHandler`
5
+ * refuses all four (`reserved-kind`, AC-INBOX-5).
6
+ *
7
+ * `WELCOME` is the Marmot Welcome rumor kind, taken from
8
+ * `@941design/marmot-engine/core`'s `WELCOME_EVENT_KIND` rather than
9
+ * restated as a literal, so the two can never drift (AC-API-8's scan also
10
+ * flags a direct `WELCOME_EVENT_KIND` import anywhere outside this file).
11
+ * The other three are marmot-local rumors with no kind assigned by any
12
+ * Marmot spec surface (ADR-003 enrolment, ADR-008 KeyPackage offer and
13
+ * app-level decline); they are taken from one contiguous block, outside the
14
+ * Marmot 443–450 range and away from every kind the account key signs
15
+ * (`permissions`), so a future spec assignment in that range cannot collide
16
+ * with them. They travel only inside NIP-59 gift wraps and are never
17
+ * published bare.
18
+ *
19
+ * Leaf module (architecture.md `shared`): imports nothing else in-package,
20
+ * only `marmot-engine/core` for `WELCOME_EVENT_KIND`.
21
+ */
22
+ import { WELCOME_EVENT_KIND } from '@941design/marmot-engine/core';
23
+ export const RUMOR_KINDS = Object.freeze({
24
+ WELCOME: WELCOME_EVENT_KIND,
25
+ ENROLMENT_REQUEST: 4460,
26
+ KEYPACKAGE_OFFER: 4461,
27
+ DECLINE: 4462,
28
+ });
@@ -0,0 +1,26 @@
1
+ /**
2
+ * NIP-01 `OK`-response publish classification (gate-remediation R2:
3
+ * promoted from `client/transport-policy.ts` so `key-packages/` — which
4
+ * must not import `client/` — can classify a publish the same way the
5
+ * group pipeline does, instead of an ad-hoc accepted/not-accepted check.
6
+ * `client/transport-policy.ts` re-exports this unchanged (no behaviour
7
+ * change; its own tests, and `pipeline.ts`'s import of it, stay green).
8
+ */
9
+ import type { PublishResponse } from '@941design/nostr-events/transport/contract';
10
+ export type PublishOutcome = 'accepted' | 'retryable' | 'terminal';
11
+ /**
12
+ * Classifies one publish of a pre-signed event over the relay `plane`:
13
+ * - `accepted` — at least one relay answered `ok: true`, or `ok: false`
14
+ * with a `duplicate:` prefix (it already holds the event);
15
+ * - `terminal` — EVERY relay of the plane answered `ok: false` with an
16
+ * `invalid:` / `blocked:` / `restricted:` / `pow:` prefix: re-publishing
17
+ * the byte-identical envelope can never succeed;
18
+ * - `retryable` — anything else: no response from some relay (timeout,
19
+ * connection closed, missing from `responses`), `rate-limited:`,
20
+ * `error:`, or an unprefixed message.
21
+ * `accepted` lists the accepting relays in plane order.
22
+ */
23
+ export declare function classifyPublish(plane: readonly string[], responses: Readonly<Record<string, PublishResponse>>): {
24
+ readonly outcome: PublishOutcome;
25
+ readonly accepted: readonly string[];
26
+ };
@@ -0,0 +1,31 @@
1
+ /** NIP-01 `OK` message prefixes that mean the relay will never accept this event as-is. */
2
+ const TERMINAL_OK_PREFIXES = ['invalid:', 'blocked:', 'restricted:', 'pow:'];
3
+ /**
4
+ * Classifies one publish of a pre-signed event over the relay `plane`:
5
+ * - `accepted` — at least one relay answered `ok: true`, or `ok: false`
6
+ * with a `duplicate:` prefix (it already holds the event);
7
+ * - `terminal` — EVERY relay of the plane answered `ok: false` with an
8
+ * `invalid:` / `blocked:` / `restricted:` / `pow:` prefix: re-publishing
9
+ * the byte-identical envelope can never succeed;
10
+ * - `retryable` — anything else: no response from some relay (timeout,
11
+ * connection closed, missing from `responses`), `rate-limited:`,
12
+ * `error:`, or an unprefixed message.
13
+ * `accepted` lists the accepting relays in plane order.
14
+ */
15
+ export function classifyPublish(plane, responses) {
16
+ const accepted = [];
17
+ let allTerminal = plane.length > 0;
18
+ for (const relay of plane) {
19
+ const response = Object.prototype.hasOwnProperty.call(responses, relay) ? responses[relay] : undefined;
20
+ const message = response?.message ?? '';
21
+ if (response?.ok === true || message.startsWith('duplicate:')) {
22
+ accepted.push(relay);
23
+ continue;
24
+ }
25
+ if (response === undefined || !TERMINAL_OK_PREFIXES.some((prefix) => message.startsWith(prefix)))
26
+ allTerminal = false;
27
+ }
28
+ if (accepted.length > 0)
29
+ return { outcome: 'accepted', accepted };
30
+ return { outcome: allTerminal ? 'terminal' : 'retryable', accepted };
31
+ }
@@ -0,0 +1,39 @@
1
+ /** A value a store can hold. `undefined` object members are dropped, as in JSON. */
2
+ export type Storable = null | boolean | number | string | bigint | Uint8Array | readonly Storable[] | {
3
+ readonly [key: string]: Storable | undefined;
4
+ };
5
+ export declare const ENVELOPE_FORMAT = 1;
6
+ export interface Envelope {
7
+ readonly v: typeof ENVELOPE_FORMAT;
8
+ readonly engine: string;
9
+ readonly tsMls: string;
10
+ readonly payload: string;
11
+ }
12
+ /** The build stamp written into, and required of, every envelope. */
13
+ export interface CodecVersions {
14
+ readonly engine: string;
15
+ readonly tsMls: string;
16
+ }
17
+ export declare const CURRENT_CODEC_VERSIONS: CodecVersions;
18
+ /** Encodes a value to payload text. Throws `invalid-options` for a value outside {@link Storable}. */
19
+ export declare function encodePayload(value: Storable): string;
20
+ /** Decodes payload text written by {@link encodePayload}. Throws `SyntaxError` on malformed text. */
21
+ export declare function decodePayload(payload: string): Storable;
22
+ /** Wraps a value for storage, stamped with `versions` (default: this build). */
23
+ export declare function sealEnvelope(value: Storable, versions?: CodecVersions): Envelope;
24
+ /**
25
+ * Checks a stored envelope's stamp against `versions` and only then decodes
26
+ * its payload. Throws `envelope-mismatch` with `details.reason`:
27
+ * `'version'` when the stamp differs (payload never decoded), `'malformed'`
28
+ * when the record is not a well-formed envelope or its payload does not decode.
29
+ */
30
+ export declare function openEnvelope(key: string, raw: unknown, versions?: CodecVersions): Storable;
31
+ /**
32
+ * Reads an envelope WITHOUT the stamp check. Only for the wipe marker, whose
33
+ * whole purpose is to be readable by a later build (it records which build
34
+ * wiped); its payload schema is frozen at `{ at, reason }`.
35
+ */
36
+ export declare function openEnvelopeUnchecked(key: string, raw: unknown): {
37
+ readonly stamp: CodecVersions;
38
+ readonly value: Storable;
39
+ };