@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,188 @@
1
+ /** @module @category Core - Encrypted Media */
2
+ import { isLoopbackHost, rejectNonRoutableHost, } from "../components/host-safety.js";
3
+ import { canonicalizeMimeType, isValidHex } from "./canonical.js";
4
+ import { BLOSSOM_LOCATOR_KIND, ENCRYPTED_MEDIA_VERSION, } from "./types.js";
5
+ /** Single-occurrence `imeta` field names for `encrypted-media-v1`. */
6
+ const SINGLE_FIELDS = [
7
+ "v",
8
+ "ciphertext_sha256",
9
+ "plaintext_sha256",
10
+ "nonce",
11
+ "m",
12
+ "filename",
13
+ "dim",
14
+ "thumbhash",
15
+ ];
16
+ /**
17
+ * Serializes a {@link MediaAttachment} into an `encrypted-media-v1` `imeta`
18
+ * tag array (`features/encrypted-media.md` — Message Shape).
19
+ *
20
+ * Field order follows the spec: `v`, `locator`…, `ciphertext_sha256`,
21
+ * `plaintext_sha256`, `nonce`, `m`, `filename`, optional `dim`, optional
22
+ * `thumbhash`. The attachment MUST carry at least one locator.
23
+ *
24
+ * @param attachment - A populated attachment (locators filled in after upload)
25
+ * @returns A Nostr tag array beginning with `"imeta"`
26
+ */
27
+ export function encodeMediaImetaTag(attachment) {
28
+ if (attachment.locators.length === 0) {
29
+ throw new Error("encodeMediaImetaTag: attachment has no locators");
30
+ }
31
+ const parts = ["imeta", `v ${ENCRYPTED_MEDIA_VERSION}`];
32
+ for (const locator of attachment.locators) {
33
+ parts.push(`locator ${locator.kind} ${locator.value}`);
34
+ }
35
+ parts.push(`ciphertext_sha256 ${attachment.ciphertextSha256}`);
36
+ parts.push(`plaintext_sha256 ${attachment.plaintextSha256}`);
37
+ parts.push(`nonce ${attachment.nonce}`);
38
+ parts.push(`m ${attachment.mediaType}`);
39
+ parts.push(`filename ${attachment.filename}`);
40
+ if (attachment.dim !== undefined)
41
+ parts.push(`dim ${attachment.dim}`);
42
+ if (attachment.thumbhash !== undefined)
43
+ parts.push(`thumbhash ${attachment.thumbhash}`);
44
+ return parts;
45
+ }
46
+ /**
47
+ * Throws if a `blossom-v1` locator URL points at a hostile fetch target — an
48
+ * unsafe host or cleartext `http` (`features/encrypted-media.md` — Validation;
49
+ * `foundation/host-safety.md`). Unlike the policy component's dev endpoints,
50
+ * loopback is unsafe here, so the only acceptable blossom locator is `https`
51
+ * to a routable host. This is the one locator property that invalidates a
52
+ * reference, because the fetch request itself is the harm.
53
+ *
54
+ * @internal
55
+ */
56
+ function rejectUnsafeBlossomLocator(url) {
57
+ const scheme = url.protocol.replace(/:$/, "");
58
+ if (scheme !== "https") {
59
+ // Cleartext http (loopback or not) and any non-https scheme are rejected.
60
+ throw new Error("blossom-v1 locator must use https");
61
+ }
62
+ // Rejects loopback, private, CGNAT, link-local, documentation, multicast, etc.
63
+ rejectNonRoutableHost(url.hostname, "blossom-v1 locator");
64
+ // Defensive: rejectNonRoutableHost already covers loopback IPs/localhost.
65
+ if (isLoopbackHost(url.hostname)) {
66
+ throw new Error("blossom-v1 locator must not point at loopback");
67
+ }
68
+ }
69
+ /** Parses one `locator <kind> <value>` field value into a {@link MediaLocator}. */
70
+ function parseLocator(value) {
71
+ const sp = value.indexOf(" ");
72
+ if (sp <= 0)
73
+ throw new Error("locator must be '<kind> <value>'");
74
+ const kind = value.slice(0, sp);
75
+ const locValue = value.slice(sp + 1).trim();
76
+ if (kind.length === 0)
77
+ throw new Error("locator kind must not be empty");
78
+ if (locValue.length === 0)
79
+ throw new Error("locator value must not be empty");
80
+ if (!URL.canParse(locValue))
81
+ throw new Error("locator value must parse as a URL");
82
+ if (kind === BLOSSOM_LOCATOR_KIND) {
83
+ rejectUnsafeBlossomLocator(new URL(locValue));
84
+ }
85
+ return { kind, value: locValue };
86
+ }
87
+ /**
88
+ * Strictly decodes an `encrypted-media-v1` attachment from an `imeta` tag.
89
+ *
90
+ * Throws on any structural-integrity or host-safety violation
91
+ * (`features/encrypted-media.md` — Validation): wrong/legacy/missing version,
92
+ * `blurhash` present, a duplicated single-occurrence field, malformed hashes or
93
+ * nonce, missing required fields, no locator, a malformed locator, or a
94
+ * `blossom-v1` locator pointing at an unsafe host. Fetchability of a locator
95
+ * kind against group policy is NOT checked here (see `selectFetchableLocators`).
96
+ *
97
+ * @internal
98
+ */
99
+ function decodeMediaImetaTag(tag) {
100
+ if (tag[0] !== "imeta")
101
+ throw new Error("not an imeta tag");
102
+ const single = new Map();
103
+ const locators = [];
104
+ for (const part of tag.slice(1)) {
105
+ const sp = part.indexOf(" ");
106
+ const key = sp === -1 ? part : part.slice(0, sp);
107
+ const value = sp === -1 ? "" : part.slice(sp + 1);
108
+ if (key === "blurhash") {
109
+ throw new Error("blurhash is invalid in encrypted-media-v1");
110
+ }
111
+ if (key === "locator") {
112
+ locators.push(parseLocator(value));
113
+ continue;
114
+ }
115
+ if (SINGLE_FIELDS.includes(key)) {
116
+ if (single.has(key)) {
117
+ throw new Error(`duplicate single-occurrence field: ${key}`);
118
+ }
119
+ single.set(key, value);
120
+ }
121
+ // Unknown fields are ignored (only blurhash is explicitly forbidden).
122
+ }
123
+ if (single.get("v") !== ENCRYPTED_MEDIA_VERSION) {
124
+ throw new Error("missing or non-encrypted-media-v1 version");
125
+ }
126
+ if (locators.length === 0)
127
+ throw new Error("no locator present");
128
+ const ciphertextSha256 = single.get("ciphertext_sha256");
129
+ const plaintextSha256 = single.get("plaintext_sha256");
130
+ const nonce = single.get("nonce");
131
+ const mediaTypeRaw = single.get("m");
132
+ const filename = single.get("filename");
133
+ if (!ciphertextSha256 || !isValidHex(ciphertextSha256, 32))
134
+ throw new Error("ciphertext_sha256 must be a 32-byte hex value");
135
+ if (!plaintextSha256 || !isValidHex(plaintextSha256, 32))
136
+ throw new Error("plaintext_sha256 must be a 32-byte hex value");
137
+ if (!nonce || !isValidHex(nonce, 12))
138
+ throw new Error("nonce must be 24 hex characters");
139
+ if (!mediaTypeRaw)
140
+ throw new Error("m (media type) is required");
141
+ if (!filename)
142
+ throw new Error("filename is required");
143
+ // Canonicalize the media type (also rejects an empty / slash-less value).
144
+ const mediaType = canonicalizeMimeType(mediaTypeRaw);
145
+ return {
146
+ version: ENCRYPTED_MEDIA_VERSION,
147
+ locators,
148
+ ciphertextSha256,
149
+ plaintextSha256,
150
+ nonce,
151
+ mediaType,
152
+ filename,
153
+ ...(single.has("dim") ? { dim: single.get("dim") } : {}),
154
+ ...(single.has("thumbhash") ? { thumbhash: single.get("thumbhash") } : {}),
155
+ };
156
+ }
157
+ /**
158
+ * Parses an `imeta` tag into a {@link MediaAttachment}, or returns `null` if the
159
+ * tag is not a valid `encrypted-media-v1` attachment.
160
+ *
161
+ * A `null` result means the media reference is invalid and MUST be dropped (the
162
+ * containing message should be dropped too for a host-safety failure). See
163
+ * {@link decodeMediaImetaTag} for the exact conditions.
164
+ *
165
+ * @param tag - A raw `imeta` tag array from a Nostr event
166
+ */
167
+ export function parseMediaImetaTag(tag) {
168
+ try {
169
+ return decodeMediaImetaTag(tag);
170
+ }
171
+ catch {
172
+ return null;
173
+ }
174
+ }
175
+ /**
176
+ * Extracts all valid `encrypted-media-v1` attachments from a tag list.
177
+ *
178
+ * Non-`imeta` tags and `imeta` tags that fail validation are skipped.
179
+ *
180
+ * @param tags - The `tags` array from a Nostr event or rumor
181
+ * @returns Array of valid {@link MediaAttachment} objects (may be empty)
182
+ */
183
+ export function getMediaAttachments(tags) {
184
+ return tags
185
+ .filter((t) => t[0] === "imeta")
186
+ .map(parseMediaImetaTag)
187
+ .filter((a) => a !== null);
188
+ }
@@ -0,0 +1,44 @@
1
+ /** @module @category Core - Encrypted Media */
2
+ import type { EncryptedMediaPolicyV1 } from "../components/encrypted-media.js";
3
+ import { type MediaAttachment } from "./types.js";
4
+ /** Locator kinds this client knows how to fetch. */
5
+ export declare const SUPPORTED_LOCATOR_KINDS: readonly string[];
6
+ export type FetchableLocatorOptions = {
7
+ /**
8
+ * The group's `allowed_locator_kinds` (`marmot.group.encrypted-media.v1`). A
9
+ * locator whose kind is not allowed is unfetchable and skipped — but it does
10
+ * NOT invalidate the attachment or drop the message. When omitted, the policy
11
+ * gate is not applied (all structurally-valid locators are considered).
12
+ */
13
+ allowedLocatorKinds?: readonly string[];
14
+ /** Locator kinds the client supports; defaults to {@link SUPPORTED_LOCATOR_KINDS}. */
15
+ supportedLocatorKinds?: readonly string[];
16
+ };
17
+ /**
18
+ * Returns the attachment's locators that are fetchable right now: their kind is
19
+ * supported by this client and (if a policy is supplied) allowed by the group.
20
+ *
21
+ * Fetchability is judged at fetch time against the group's CURRENT policy and
22
+ * the client's current support, never against the source epoch
23
+ * (`features/encrypted-media.md` — Validation). An unsupported/out-of-policy
24
+ * locator is skipped, not treated as invalid. Order is preserved.
25
+ */
26
+ export declare function selectFetchableLocators(attachment: MediaAttachment, opts?: FetchableLocatorOptions): MediaAttachment["locators"];
27
+ /**
28
+ * Builds backend-specific fallback fetch URLs from the policy's ordered
29
+ * `default_blob_endpoints` and the attachment's `ciphertextSha256`
30
+ * (`features/encrypted-media.md` — Locator Kinds). Endpoint order is the
31
+ * fallback priority and is preserved.
32
+ *
33
+ * Only `blossom-v1` endpoints produce a URL (Blossom `GET /<sha256>`); other
34
+ * kinds need backend-specific rules and are skipped. Whether to actually fetch
35
+ * a loopback-`http` endpoint is a separate local dev/test decision.
36
+ */
37
+ export declare function buildFallbackFetchUrls(attachment: MediaAttachment, policy: EncryptedMediaPolicyV1, opts?: FetchableLocatorOptions): string[];
38
+ /**
39
+ * Resolves the ordered list of candidate fetch URLs for an attachment: explicit
40
+ * supported+allowed `blossom-v1` locator URLs first, then policy fallback URLs.
41
+ * Deduplicates while preserving order. A client tries them in order until one
42
+ * yields bytes matching `ciphertextSha256`.
43
+ */
44
+ export declare function resolveMediaFetchUrls(attachment: MediaAttachment, policy: EncryptedMediaPolicyV1, opts?: FetchableLocatorOptions): string[];
@@ -0,0 +1,69 @@
1
+ import { BLOSSOM_LOCATOR_KIND } from "./types.js";
2
+ /** Locator kinds this client knows how to fetch. */
3
+ export const SUPPORTED_LOCATOR_KINDS = [
4
+ BLOSSOM_LOCATOR_KIND,
5
+ ];
6
+ /**
7
+ * Returns the attachment's locators that are fetchable right now: their kind is
8
+ * supported by this client and (if a policy is supplied) allowed by the group.
9
+ *
10
+ * Fetchability is judged at fetch time against the group's CURRENT policy and
11
+ * the client's current support, never against the source epoch
12
+ * (`features/encrypted-media.md` — Validation). An unsupported/out-of-policy
13
+ * locator is skipped, not treated as invalid. Order is preserved.
14
+ */
15
+ export function selectFetchableLocators(attachment, opts = {}) {
16
+ const supported = opts.supportedLocatorKinds ?? SUPPORTED_LOCATOR_KINDS;
17
+ const allowed = opts.allowedLocatorKinds;
18
+ return attachment.locators.filter((l) => supported.includes(l.kind) &&
19
+ (allowed === undefined || allowed.includes(l.kind)));
20
+ }
21
+ /**
22
+ * Builds backend-specific fallback fetch URLs from the policy's ordered
23
+ * `default_blob_endpoints` and the attachment's `ciphertextSha256`
24
+ * (`features/encrypted-media.md` — Locator Kinds). Endpoint order is the
25
+ * fallback priority and is preserved.
26
+ *
27
+ * Only `blossom-v1` endpoints produce a URL (Blossom `GET /<sha256>`); other
28
+ * kinds need backend-specific rules and are skipped. Whether to actually fetch
29
+ * a loopback-`http` endpoint is a separate local dev/test decision.
30
+ */
31
+ export function buildFallbackFetchUrls(attachment, policy, opts = {}) {
32
+ const supported = opts.supportedLocatorKinds ?? SUPPORTED_LOCATOR_KINDS;
33
+ const urls = [];
34
+ for (const endpoint of policy.defaultBlobEndpoints) {
35
+ if (endpoint.locatorKind !== BLOSSOM_LOCATOR_KIND)
36
+ continue;
37
+ if (!supported.includes(endpoint.locatorKind))
38
+ continue;
39
+ // baseUrl is WHATWG-normalized (keeps a trailing `/`); join the hash.
40
+ urls.push(new URL(attachment.ciphertextSha256, endpoint.baseUrl).toString());
41
+ }
42
+ return urls;
43
+ }
44
+ /**
45
+ * Resolves the ordered list of candidate fetch URLs for an attachment: explicit
46
+ * supported+allowed `blossom-v1` locator URLs first, then policy fallback URLs.
47
+ * Deduplicates while preserving order. A client tries them in order until one
48
+ * yields bytes matching `ciphertextSha256`.
49
+ */
50
+ export function resolveMediaFetchUrls(attachment, policy, opts = {}) {
51
+ const supported = opts.supportedLocatorKinds ?? SUPPORTED_LOCATOR_KINDS;
52
+ const explicit = selectFetchableLocators(attachment, {
53
+ ...opts,
54
+ allowedLocatorKinds: opts.allowedLocatorKinds ?? policy.allowedLocatorKinds,
55
+ supportedLocatorKinds: supported,
56
+ })
57
+ .filter((l) => l.kind === BLOSSOM_LOCATOR_KIND)
58
+ .map((l) => l.value);
59
+ const fallback = buildFallbackFetchUrls(attachment, policy, opts);
60
+ const seen = new Set();
61
+ const ordered = [];
62
+ for (const url of [...explicit, ...fallback]) {
63
+ if (!seen.has(url)) {
64
+ seen.add(url);
65
+ ordered.push(url);
66
+ }
67
+ }
68
+ return ordered;
69
+ }
@@ -0,0 +1,83 @@
1
+ /** @module @category Core - Encrypted Media */
2
+ /**
3
+ * Media format / version string for the current encrypted-media scheme.
4
+ *
5
+ * Written to the `v` field of an attachment `imeta` tag and mixed into the
6
+ * key-derivation context and AEAD associated data. New media references MUST
7
+ * use this value; V1 clients MUST reject any legacy media-version string (see
8
+ * darkmatter `features/encrypted-media.md`).
9
+ */
10
+ export declare const ENCRYPTED_MEDIA_VERSION: "encrypted-media-v1";
11
+ /** The initial (and only v1) locator kind. */
12
+ export declare const BLOSSOM_LOCATOR_KIND: "blossom-v1";
13
+ /**
14
+ * A single blob locator from an attachment `imeta` tag.
15
+ *
16
+ * Serialized as `locator <kind> <value>`. For `blossom-v1` the value is an
17
+ * encrypted-blob URL; other kinds carry backend-specific values. A message MAY
18
+ * list multiple locators for the same attachment; the order is preserved.
19
+ */
20
+ export interface MediaLocator {
21
+ /** Locator kind, e.g. `"blossom-v1"`. Lowercase ASCII letters, digits, `-`. */
22
+ kind: string;
23
+ /** Locator value — a URL for `blossom-v1`. */
24
+ value: string;
25
+ }
26
+ /**
27
+ * A decoded `encrypted-media-v1` attachment (one `imeta` tag).
28
+ *
29
+ * Built by {@link encryptMediaFile} (locators are filled in by the caller after
30
+ * upload), serialized with `encodeMediaImetaTag`, and read back with
31
+ * `parseMediaImetaTag`.
32
+ */
33
+ export interface MediaAttachment {
34
+ /** Always {@link ENCRYPTED_MEDIA_VERSION}. */
35
+ version: typeof ENCRYPTED_MEDIA_VERSION;
36
+ /**
37
+ * One or more ordered locators (`locator <kind> <value>`). Empty only on the
38
+ * attachment returned by {@link encryptMediaFile} before the blob is uploaded;
39
+ * a parsed attachment always has at least one.
40
+ */
41
+ locators: MediaLocator[];
42
+ /**
43
+ * Hex-encoded SHA-256 of the **ciphertext** (64 hex chars). The preferred
44
+ * content id for blob storage; fetched bytes are verified against it.
45
+ */
46
+ ciphertextSha256: string;
47
+ /**
48
+ * Hex-encoded SHA-256 of the **plaintext** file (64 hex chars). Feeds the
49
+ * `file_key` derivation and the AEAD AAD; verified after decryption.
50
+ */
51
+ plaintextSha256: string;
52
+ /**
53
+ * Hex-encoded 12-byte ChaCha20-Poly1305 nonce (exactly 24 hex chars).
54
+ */
55
+ nonce: string;
56
+ /**
57
+ * Canonical media (MIME) type — see `canonicalizeMimeType`. Feeds the
58
+ * `file_key` derivation and the AEAD AAD.
59
+ */
60
+ mediaType: string;
61
+ /** Display filename. Feeds the `file_key` derivation and the AEAD AAD. */
62
+ filename: string;
63
+ /** Optional `<width>x<height>` render hint. */
64
+ dim?: string;
65
+ /** Optional thumbhash preview value. */
66
+ thumbhash?: string;
67
+ }
68
+ /** Result of {@link encryptMediaFile}. */
69
+ export type EncryptMediaFileResult = {
70
+ /**
71
+ * The encrypted blob. Upload this to a blob store; `SHA256(encrypted)` (also
72
+ * available as `attachment.ciphertextSha256`) is the preferred content id.
73
+ */
74
+ encrypted: Uint8Array;
75
+ /**
76
+ * A populated {@link MediaAttachment} with `ciphertextSha256`,
77
+ * `plaintextSha256`, `nonce`, `mediaType`, and `filename` set, and
78
+ * `locators` empty. The caller adds one or more {@link MediaLocator} entries
79
+ * after uploading `encrypted`, then serializes the attachment with
80
+ * `encodeMediaImetaTag`.
81
+ */
82
+ attachment: MediaAttachment;
83
+ };
@@ -0,0 +1,12 @@
1
+ /** @module @category Core - Encrypted Media */
2
+ /**
3
+ * Media format / version string for the current encrypted-media scheme.
4
+ *
5
+ * Written to the `v` field of an attachment `imeta` tag and mixed into the
6
+ * key-derivation context and AEAD associated data. New media references MUST
7
+ * use this value; V1 clients MUST reject any legacy media-version string (see
8
+ * darkmatter `features/encrypted-media.md`).
9
+ */
10
+ export const ENCRYPTED_MEDIA_VERSION = "encrypted-media-v1";
11
+ /** The initial (and only v1) locator kind. */
12
+ export const BLOSSOM_LOCATOR_KIND = "blossom-v1";
@@ -0,0 +1,6 @@
1
+ /** @module @category Core - Encrypted Media */
2
+ export { ENCRYPTED_MEDIA_VERSION, BLOSSOM_LOCATOR_KIND, type MediaAttachment, type MediaLocator, type EncryptMediaFileResult, } from "./media/types.js";
3
+ export { canonicalizeMimeType } from "./media/canonical.js";
4
+ export { deriveMediaEncryptionKey, encryptMediaFile, decryptMediaFile, decryptMediaFileWithKeys, } from "./media/crypto.js";
5
+ export { encodeMediaImetaTag, parseMediaImetaTag, getMediaAttachments, } from "./media/imeta.js";
6
+ export { SUPPORTED_LOCATOR_KINDS, selectFetchableLocators, buildFallbackFetchUrls, resolveMediaFetchUrls, type FetchableLocatorOptions, } from "./media/locator.js";
@@ -0,0 +1,12 @@
1
+ /** @module @category Core - Encrypted Media */
2
+ // Type model for encrypted-media-v1 attachments.
3
+ export { ENCRYPTED_MEDIA_VERSION, BLOSSOM_LOCATOR_KIND, } from "./media/types.js";
4
+ // MIME canonicalization (the validation helpers stay internal to media/).
5
+ export { canonicalizeMimeType } from "./media/canonical.js";
6
+ // Security-critical crypto: MLS-exporter→HKDF→ChaCha20 key derivation and the
7
+ // randomBytes/cipher AEAD site. Auditable against darkmatter media/crypto.rs.
8
+ export { deriveMediaEncryptionKey, encryptMediaFile, decryptMediaFile, decryptMediaFileWithKeys, } from "./media/crypto.js";
9
+ // imeta tag (de)serialization and strict validation.
10
+ export { encodeMediaImetaTag, parseMediaImetaTag, getMediaAttachments, } from "./media/imeta.js";
11
+ // Locator fetchability + blob-endpoint fallback resolution.
12
+ export { SUPPORTED_LOCATOR_KINDS, selectFetchableLocators, buildFallbackFetchUrls, resolveMediaFetchUrls, } from "./media/locator.js";
@@ -0,0 +1,51 @@
1
+ /**
2
+ * NIP-65 relay list event kind. Marmot uses an account's NIP-65 list to
3
+ * discover where it publishes and fetches KeyPackages; there is no dedicated
4
+ * KeyPackage relay list (transports/nostr.md "KeyPackage publication").
5
+ */
6
+ export declare const NIP65_RELAY_LIST_KIND = 10002;
7
+ /** The NIP-65 relay tag (`r`), optionally followed by a read/write marker. */
8
+ export declare const NIP65_RELAY_TAG = "r";
9
+ /**
10
+ * Marmot inbox relay list event kind (kind 10050). Welcomes are gift-wrapped to
11
+ * the recipient's inbox relay set (transports/nostr.md "Publish targets").
12
+ */
13
+ export declare const INBOX_RELAY_LIST_KIND = 10050;
14
+ /** The inbox relay-list tag (`relay`) carrying a single relay URL. */
15
+ export declare const INBOX_RELAY_TAG = "relay";
16
+ /** Event kind for addressable key package events */
17
+ export declare const ADDRESSABLE_KEY_PACKAGE_KIND = 30443;
18
+ /** The name of the tag that contains the MLS protocol version */
19
+ export declare const KEY_PACKAGE_MLS_VERSION_TAG = "mls_protocol_version";
20
+ /** The name of the tag that contains the MLS cipher suite */
21
+ export declare const KEY_PACKAGE_CIPHER_SUITE_TAG = "mls_ciphersuite";
22
+ /** The name of the tag that contains the MLS extensions */
23
+ export declare const KEY_PACKAGE_EXTENSIONS_TAG = "mls_extensions";
24
+ /** The name of the tag that contains the supported MLS proposal ids */
25
+ export declare const KEY_PACKAGE_PROPOSALS_TAG = "mls_proposals";
26
+ /** The name of the tag that contains the supported Marmot app-component ids */
27
+ export declare const KEY_PACKAGE_APP_COMPONENTS_TAG = "app_components";
28
+ /** The name of the tag that contains the relays */
29
+ export declare const KEY_PACKAGE_RELAYS_TAG = "relays";
30
+ /** The name of the tag that contains the client */
31
+ export declare const KEY_PACKAGE_CLIENT_TAG = "client";
32
+ /** The possible MLS protocol versions */
33
+ export type MLS_VERSIONS = "1.0";
34
+ /** Parsed client tag from a kind 30443 event */
35
+ export type KeyPackageClient = {
36
+ name: string;
37
+ };
38
+ /** Extended extension types that include Marmot-specific extensions */
39
+ export declare const extendedExtensionTypes: {
40
+ readonly application_id: 1;
41
+ readonly ratchet_tree: 2;
42
+ readonly required_capabilities: 3;
43
+ readonly external_pub: 4;
44
+ readonly external_senders: 5;
45
+ };
46
+ export type ExtendedExtensionTypeName = keyof typeof extendedExtensionTypes;
47
+ export type ExtendedExtensionTypeValue = (typeof extendedExtensionTypes)[ExtendedExtensionTypeName];
48
+ /** Event kind for group events (commits, proposals, application messages) */
49
+ export declare const GROUP_EVENT_KIND = 445;
50
+ /** Event kind for welcome events */
51
+ export declare const WELCOME_EVENT_KIND = 444;
@@ -0,0 +1,41 @@
1
+ /** @module @category Core - Constants */
2
+ import { defaultExtensionTypes } from "ts-mls";
3
+ /**
4
+ * NIP-65 relay list event kind. Marmot uses an account's NIP-65 list to
5
+ * discover where it publishes and fetches KeyPackages; there is no dedicated
6
+ * KeyPackage relay list (transports/nostr.md "KeyPackage publication").
7
+ */
8
+ export const NIP65_RELAY_LIST_KIND = 10002;
9
+ /** The NIP-65 relay tag (`r`), optionally followed by a read/write marker. */
10
+ export const NIP65_RELAY_TAG = "r";
11
+ /**
12
+ * Marmot inbox relay list event kind (kind 10050). Welcomes are gift-wrapped to
13
+ * the recipient's inbox relay set (transports/nostr.md "Publish targets").
14
+ */
15
+ export const INBOX_RELAY_LIST_KIND = 10050;
16
+ /** The inbox relay-list tag (`relay`) carrying a single relay URL. */
17
+ export const INBOX_RELAY_TAG = "relay";
18
+ /** Event kind for addressable key package events */
19
+ export const ADDRESSABLE_KEY_PACKAGE_KIND = 30443;
20
+ /** The name of the tag that contains the MLS protocol version */
21
+ export const KEY_PACKAGE_MLS_VERSION_TAG = "mls_protocol_version";
22
+ /** The name of the tag that contains the MLS cipher suite */
23
+ export const KEY_PACKAGE_CIPHER_SUITE_TAG = "mls_ciphersuite";
24
+ /** The name of the tag that contains the MLS extensions */
25
+ export const KEY_PACKAGE_EXTENSIONS_TAG = "mls_extensions";
26
+ /** The name of the tag that contains the supported MLS proposal ids */
27
+ export const KEY_PACKAGE_PROPOSALS_TAG = "mls_proposals";
28
+ /** The name of the tag that contains the supported Marmot app-component ids */
29
+ export const KEY_PACKAGE_APP_COMPONENTS_TAG = "app_components";
30
+ /** The name of the tag that contains the relays */
31
+ export const KEY_PACKAGE_RELAYS_TAG = "relays";
32
+ /** The name of the tag that contains the client */
33
+ export const KEY_PACKAGE_CLIENT_TAG = "client";
34
+ /** Extended extension types that include Marmot-specific extensions */
35
+ export const extendedExtensionTypes = {
36
+ ...defaultExtensionTypes,
37
+ };
38
+ /** Event kind for group events (commits, proposals, application messages) */
39
+ export const GROUP_EVENT_KIND = 445;
40
+ /** Event kind for welcome events */
41
+ export const WELCOME_EVENT_KIND = 444;
@@ -0,0 +1,52 @@
1
+ /** @module @category Core - Relay Lists */
2
+ import { NostrEvent, UnsignedEvent } from "../utils/nostr.js";
3
+ /** Optional NIP-65 read/write marker on an `r` tag. */
4
+ export type Nip65RelayUsage = "read" | "write";
5
+ /**
6
+ * Reads relay URLs from a NIP-65 (kind 10002) relay-list event.
7
+ *
8
+ * Each entry is an `r` tag: `["r", url]` (both read and write) or
9
+ * `["r", url, "read" | "write"]`. Pass `usage` to keep only relays usable for
10
+ * that direction; omit it to return every advertised relay (markerless `r`
11
+ * tags count as both directions).
12
+ *
13
+ * @param event - The kind 10002 event
14
+ * @param usage - Optional direction filter
15
+ * @returns Normalized, validated relay URLs
16
+ */
17
+ export declare function getNip65Relays(event: NostrEvent, usage?: Nip65RelayUsage): string[];
18
+ /** True for a kind 10002 event that advertises at least one valid relay. */
19
+ export declare function isValidNip65RelayListEvent(event: NostrEvent): boolean;
20
+ /** Options for {@link createNip65RelayListEvent}. */
21
+ export type CreateNip65RelayListEventOptions = {
22
+ /** The pubkey of the event author */
23
+ pubkey: string;
24
+ /** The relays the account publishes and fetches KeyPackages from */
25
+ relays: string[];
26
+ /** Optional NIP-65 marker applied to every relay (omit for read+write) */
27
+ usage?: Nip65RelayUsage;
28
+ };
29
+ /**
30
+ * Creates an unsigned NIP-65 (kind 10002) relay-list event. Marmot reads this
31
+ * list to discover an account's KeyPackage relays.
32
+ */
33
+ export declare function createNip65RelayListEvent(options: CreateNip65RelayListEventOptions): UnsignedEvent;
34
+ /**
35
+ * Reads relay URLs from an inbox (kind 10050) relay-list event. Each entry is a
36
+ * `relay` tag: `["relay", url]`.
37
+ */
38
+ export declare function getInboxRelays(event: NostrEvent): string[];
39
+ /** True for a kind 10050 event that advertises at least one valid relay. */
40
+ export declare function isValidInboxRelayListEvent(event: NostrEvent): boolean;
41
+ /** Options for {@link createInboxRelayListEvent}. */
42
+ export type CreateInboxRelayListEventOptions = {
43
+ /** The pubkey of the event author */
44
+ pubkey: string;
45
+ /** The relays where the account receives gift-wrapped welcomes */
46
+ relays: string[];
47
+ };
48
+ /**
49
+ * Creates an unsigned inbox (kind 10050) relay-list event. Marmot reads this
50
+ * list to learn where to deliver a recipient's welcomes.
51
+ */
52
+ export declare function createInboxRelayListEvent(options: CreateInboxRelayListEventOptions): UnsignedEvent;
@@ -0,0 +1,86 @@
1
+ import { isValidRelayUrl, normalizeRelayUrl } from "../utils/relay-url.js";
2
+ import { INBOX_RELAY_LIST_KIND, INBOX_RELAY_TAG, NIP65_RELAY_LIST_KIND, NIP65_RELAY_TAG, } from "./protocol.js";
3
+ import { unixNow } from "../utils/nostr.js";
4
+ /**
5
+ * Reads relay URLs from a NIP-65 (kind 10002) relay-list event.
6
+ *
7
+ * Each entry is an `r` tag: `["r", url]` (both read and write) or
8
+ * `["r", url, "read" | "write"]`. Pass `usage` to keep only relays usable for
9
+ * that direction; omit it to return every advertised relay (markerless `r`
10
+ * tags count as both directions).
11
+ *
12
+ * @param event - The kind 10002 event
13
+ * @param usage - Optional direction filter
14
+ * @returns Normalized, validated relay URLs
15
+ */
16
+ export function getNip65Relays(event, usage) {
17
+ return event.tags
18
+ .filter((tag) => tag[0] === NIP65_RELAY_TAG && tag[1])
19
+ .filter((tag) => {
20
+ if (!usage)
21
+ return true;
22
+ const marker = tag[2];
23
+ // A markerless `r` tag means the relay is used for both read and write.
24
+ return !marker || marker === usage;
25
+ })
26
+ .map((tag) => tag[1])
27
+ .filter(isValidRelayUrl)
28
+ .map(normalizeRelayUrl);
29
+ }
30
+ /** True for a kind 10002 event that advertises at least one valid relay. */
31
+ export function isValidNip65RelayListEvent(event) {
32
+ return (event.kind === NIP65_RELAY_LIST_KIND && getNip65Relays(event).length > 0);
33
+ }
34
+ /**
35
+ * Creates an unsigned NIP-65 (kind 10002) relay-list event. Marmot reads this
36
+ * list to discover an account's KeyPackage relays.
37
+ */
38
+ export function createNip65RelayListEvent(options) {
39
+ const { pubkey, relays, usage } = options;
40
+ const validRelays = relays.filter(isValidRelayUrl).map(normalizeRelayUrl);
41
+ const tags = validRelays.map((relay) => usage ? [NIP65_RELAY_TAG, relay, usage] : [NIP65_RELAY_TAG, relay]);
42
+ return {
43
+ kind: NIP65_RELAY_LIST_KIND,
44
+ created_at: unixNow(),
45
+ tags,
46
+ content: "",
47
+ pubkey,
48
+ };
49
+ }
50
+ // ---------------------------------------------------------------------------
51
+ // Inbox relay list (kind 10050) — Welcome delivery
52
+ //
53
+ // Welcomes are gift-wrapped to the recipient's inbox relay set
54
+ // (transports/nostr.md "Publish targets and acknowledgements").
55
+ // ---------------------------------------------------------------------------
56
+ /**
57
+ * Reads relay URLs from an inbox (kind 10050) relay-list event. Each entry is a
58
+ * `relay` tag: `["relay", url]`.
59
+ */
60
+ export function getInboxRelays(event) {
61
+ return event.tags
62
+ .filter((tag) => tag[0] === INBOX_RELAY_TAG && tag[1])
63
+ .map((tag) => tag[1])
64
+ .filter(isValidRelayUrl)
65
+ .map(normalizeRelayUrl);
66
+ }
67
+ /** True for a kind 10050 event that advertises at least one valid relay. */
68
+ export function isValidInboxRelayListEvent(event) {
69
+ return (event.kind === INBOX_RELAY_LIST_KIND && getInboxRelays(event).length > 0);
70
+ }
71
+ /**
72
+ * Creates an unsigned inbox (kind 10050) relay-list event. Marmot reads this
73
+ * list to learn where to deliver a recipient's welcomes.
74
+ */
75
+ export function createInboxRelayListEvent(options) {
76
+ const { pubkey, relays } = options;
77
+ const validRelays = relays.filter(isValidRelayUrl).map(normalizeRelayUrl);
78
+ const tags = validRelays.map((relay) => [INBOX_RELAY_TAG, relay]);
79
+ return {
80
+ kind: INBOX_RELAY_LIST_KIND,
81
+ created_at: unixNow(),
82
+ tags,
83
+ content: "",
84
+ pubkey,
85
+ };
86
+ }