applesauce-common 7.0.0 → 7.1.1

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 (46) hide show
  1. package/dist/casts/index.d.ts +1 -0
  2. package/dist/casts/index.js +1 -0
  3. package/dist/casts/napplet-handlers.d.ts +39 -0
  4. package/dist/casts/napplet-handlers.js +91 -0
  5. package/dist/factories/file-message.d.ts +24 -0
  6. package/dist/factories/file-message.js +37 -0
  7. package/dist/factories/index.d.ts +2 -0
  8. package/dist/factories/index.js +2 -0
  9. package/dist/factories/legacy-message.d.ts +8 -2
  10. package/dist/factories/legacy-message.js +11 -6
  11. package/dist/factories/napplet-handlers.d.ts +34 -0
  12. package/dist/factories/napplet-handlers.js +77 -0
  13. package/dist/factories/wrapped-message.js +10 -4
  14. package/dist/helpers/encrypted-content-cache.d.ts +2 -11
  15. package/dist/helpers/encrypted-content-cache.js +6 -31
  16. package/dist/helpers/encrypted-file.d.ts +41 -0
  17. package/dist/helpers/encrypted-file.js +64 -0
  18. package/dist/helpers/file-message.d.ts +18 -0
  19. package/dist/helpers/file-message.js +44 -0
  20. package/dist/helpers/file-metadata.d.ts +9 -4
  21. package/dist/helpers/file-metadata.js +16 -0
  22. package/dist/helpers/index.d.ts +3 -0
  23. package/dist/helpers/index.js +3 -0
  24. package/dist/helpers/messages.js +3 -2
  25. package/dist/helpers/mute.js +2 -2
  26. package/dist/helpers/napplet-handlers.d.ts +79 -0
  27. package/dist/helpers/napplet-handlers.js +187 -0
  28. package/dist/helpers/napplet.d.ts +18 -0
  29. package/dist/helpers/napplet.js +33 -0
  30. package/dist/helpers/wrapped-messages.d.ts +2 -0
  31. package/dist/helpers/wrapped-messages.js +6 -1
  32. package/dist/models/index.d.ts +1 -0
  33. package/dist/models/index.js +1 -0
  34. package/dist/models/legacy-messages.js +6 -1
  35. package/dist/models/napplet-handlers.d.ts +16 -0
  36. package/dist/models/napplet-handlers.js +45 -0
  37. package/dist/models/wrapped-messages.js +9 -7
  38. package/dist/observable/filter-timeline-by-mutes.js +1 -1
  39. package/dist/operations/file-message.d.ts +7 -0
  40. package/dist/operations/file-message.js +34 -0
  41. package/dist/operations/index.d.ts +2 -0
  42. package/dist/operations/index.js +2 -0
  43. package/dist/operations/napplet-handlers.d.ts +47 -0
  44. package/dist/operations/napplet-handlers.js +161 -0
  45. package/dist/operations/wrapped-message.js +2 -2
  46. package/package.json +12 -16
@@ -0,0 +1,64 @@
1
+ import { bytesToHex, hexToBytes } from "@noble/hashes/utils.js";
2
+ import { sha256 } from "@noble/hashes/sha2.js";
3
+ /** The file encryption algorithm used by NIP-17 file messages */
4
+ export const ENCRYPTED_FILE_ALGORITHM = "aes-gcm";
5
+ async function toBytes(data) {
6
+ if (data instanceof Uint8Array)
7
+ return data;
8
+ if (data instanceof ArrayBuffer)
9
+ return new Uint8Array(data);
10
+ return new Uint8Array(await data.arrayBuffer());
11
+ }
12
+ /** Returns the hex encoded sha256 of some bytes */
13
+ function hashHex(bytes) {
14
+ return bytesToHex(sha256(bytes));
15
+ }
16
+ /** Copies bytes into a fresh ArrayBuffer, which Web Crypto requires */
17
+ function buffer(bytes) {
18
+ return bytes.slice().buffer;
19
+ }
20
+ /** Encrypts a file with a random AES-GCM key and nonce for upload to a public file server */
21
+ export async function encryptFile(data) {
22
+ const plaintext = await toBytes(data);
23
+ const key = crypto.getRandomValues(new Uint8Array(32));
24
+ const nonce = crypto.getRandomValues(new Uint8Array(12));
25
+ const cryptoKey = await crypto.subtle.importKey("raw", buffer(key), "AES-GCM", false, ["encrypt"]);
26
+ const encrypted = await crypto.subtle.encrypt({ name: "AES-GCM", iv: buffer(nonce) }, cryptoKey, buffer(plaintext));
27
+ const ciphertext = new Uint8Array(encrypted);
28
+ return {
29
+ ciphertext,
30
+ algorithm: ENCRYPTED_FILE_ALGORITHM,
31
+ key: bytesToHex(key),
32
+ nonce: bytesToHex(nonce),
33
+ sha256: hashHex(ciphertext),
34
+ originalSha256: hashHex(plaintext),
35
+ size: ciphertext.length,
36
+ };
37
+ }
38
+ /**
39
+ * Decrypts a file encrypted with {@link encryptFile} or another NIP-17 client
40
+ * @throws if the algorithm is unsupported, the key or nonce is missing, a hash does not match, or decryption fails
41
+ */
42
+ export async function decryptFile(data, fields) {
43
+ const algorithm = fields.encryptionAlgorithm ?? ENCRYPTED_FILE_ALGORITHM;
44
+ if (algorithm.toLowerCase() !== ENCRYPTED_FILE_ALGORITHM)
45
+ throw new Error(`Unsupported encryption algorithm ${algorithm}`);
46
+ if (!fields.decryptionKey || !fields.decryptionNonce)
47
+ throw new Error("Missing decryption key or nonce");
48
+ const ciphertext = await toBytes(data);
49
+ if (fields.sha256 && hashHex(ciphertext) !== fields.sha256.toLowerCase())
50
+ throw new Error("Encrypted file hash does not match");
51
+ // Clients disagree on the nonce length (12 or 16 bytes), and AES-GCM accepts both.
52
+ const key = hexToBytes(fields.decryptionKey);
53
+ const nonce = hexToBytes(fields.decryptionNonce);
54
+ const cryptoKey = await crypto.subtle.importKey("raw", buffer(key), "AES-GCM", false, ["decrypt"]);
55
+ const decrypted = await crypto.subtle
56
+ .decrypt({ name: "AES-GCM", iv: buffer(nonce) }, cryptoKey, buffer(ciphertext))
57
+ .catch(() => {
58
+ throw new Error("Failed to decrypt file");
59
+ });
60
+ const plaintext = new Uint8Array(decrypted);
61
+ if (fields.originalSha256 && hashHex(plaintext) !== fields.originalSha256.toLowerCase())
62
+ throw new Error("Decrypted file hash does not match");
63
+ return plaintext;
64
+ }
@@ -0,0 +1,18 @@
1
+ import { NostrEvent, Rumor } from "applesauce-core/helpers/event";
2
+ import { FileMetadataFields } from "./file-metadata.js";
3
+ /** The NIP-17 file message kind */
4
+ export declare const FILE_MESSAGE_KIND = 15;
5
+ /** A NIP-17 kind 15 file message rumor */
6
+ export type FileMessage = Rumor & {
7
+ kind: typeof FILE_MESSAGE_KIND;
8
+ };
9
+ /**
10
+ * Checks if a rumor is a valid NIP-17 kind 15 file message
11
+ * @note requires a file-type or decryption-key tag, which also tells a file apart from a double-ratchet kind 15 receipt
12
+ */
13
+ export declare function isValidFileMessage(rumor?: Rumor | NostrEvent): rumor is FileMessage;
14
+ /** Gets the file URL, type, hashes, and decryption fields of a kind 15 file message */
15
+ export declare function getFileMessageMetadata(message: FileMessage): FileMetadataFields;
16
+ export declare function getFileMessageMetadata(message?: Rumor | NostrEvent): FileMetadataFields | undefined;
17
+ /** Gets the attachments of a message, from a kind 15 file message or the imeta tags of any other message */
18
+ export declare function getMessageAttachments(message: Rumor | NostrEvent): FileMetadataFields[];
@@ -0,0 +1,44 @@
1
+ import { getOrComputeCachedValue } from "applesauce-core/helpers/cache";
2
+ import { kinds } from "applesauce-core/helpers/event";
3
+ import { getMediaAttachments, parseFileMetadataTags } from "./file-metadata.js";
4
+ /** The NIP-17 file message kind */
5
+ export const FILE_MESSAGE_KIND = kinds.FileMessage;
6
+ const FileMessageMetadataSymbol = Symbol.for("file-message-metadata");
7
+ const MessageAttachmentsSymbol = Symbol.for("message-attachments");
8
+ function isURL(content) {
9
+ try {
10
+ const url = new URL(content.trim());
11
+ return url.protocol === "https:" || url.protocol === "http:";
12
+ }
13
+ catch {
14
+ return false;
15
+ }
16
+ }
17
+ /**
18
+ * Checks if a rumor is a valid NIP-17 kind 15 file message
19
+ * @note requires a file-type or decryption-key tag, which also tells a file apart from a double-ratchet kind 15 receipt
20
+ */
21
+ export function isValidFileMessage(rumor) {
22
+ if (!rumor || rumor.kind !== FILE_MESSAGE_KIND || !isURL(rumor.content))
23
+ return false;
24
+ return rumor.tags.some((tag) => (tag[0] === "file-type" || tag[0] === "decryption-key") && !!tag[1]);
25
+ }
26
+ export function getFileMessageMetadata(message) {
27
+ if (!isValidFileMessage(message))
28
+ return undefined;
29
+ return getOrComputeCachedValue(message, FileMessageMetadataSymbol, () => {
30
+ // Kind 15 names the MIME type "file-type" where NIP-94 uses "m".
31
+ const tags = message.tags.map((tag) => (tag[0] === "file-type" ? ["m", tag[1]] : tag));
32
+ return { ...parseFileMetadataTags(tags), url: message.content.trim() };
33
+ });
34
+ }
35
+ /** Gets the attachments of a message, from a kind 15 file message or the imeta tags of any other message */
36
+ export function getMessageAttachments(message) {
37
+ return getOrComputeCachedValue(message, MessageAttachmentsSymbol, () => {
38
+ if (message.kind === FILE_MESSAGE_KIND) {
39
+ const file = getFileMessageMetadata(message);
40
+ return file ? [file] : [];
41
+ }
42
+ return getMediaAttachments(message).filter((attachment) => !!attachment.url);
43
+ });
44
+ }
@@ -7,10 +7,7 @@ export type FileMetadataFields = {
7
7
  type?: string;
8
8
  /** sha256 hash of the file */
9
9
  sha256?: string;
10
- /**
11
- * The original sha256 hash before the file was transformed
12
- * @deprecated
13
- */
10
+ /** The sha256 hash of the original file before it was transformed or encrypted */
14
11
  originalSha256?: string;
15
12
  /** size of the file in bytes */
16
13
  size?: number;
@@ -32,11 +29,19 @@ export type FileMetadataFields = {
32
29
  blurhash?: string;
33
30
  /** fallback URLs */
34
31
  fallback?: string[];
32
+ /** The algorithm the file is encrypted with, usually "aes-gcm" */
33
+ encryptionAlgorithm?: string;
34
+ /** The hex encoded key to decrypt the file */
35
+ decryptionKey?: string;
36
+ /** The hex encoded nonce to decrypt the file */
37
+ decryptionNonce?: string;
35
38
  };
36
39
  /** A kind 1063 file metadata event */
37
40
  export type FileMetadataEvent = KnownEvent<1063>;
38
41
  /** Alias for {@link FileMetadataFields} */
39
42
  export type MediaAttachment = FileMetadataFields;
43
+ /** Checks if a file is encrypted and carries the key and nonce to decrypt it */
44
+ export declare function isEncryptedFile(file: FileMetadataFields): boolean;
40
45
  /** Type guard for a valid kind 1063 file metadata event */
41
46
  export declare function isValidFileMetadata(event?: NostrEvent): event is FileMetadataEvent;
42
47
  /** Parses file metadata tags into {@link FileMetadataFields} */
@@ -1,6 +1,10 @@
1
1
  import { getURLPathname } from "applesauce-core/helpers/url";
2
2
  import { getTagValue } from "applesauce-core/helpers/event";
3
3
  import { getOrComputeCachedValue } from "applesauce-core/helpers/cache";
4
+ /** Checks if a file is encrypted and carries the key and nonce to decrypt it */
5
+ export function isEncryptedFile(file) {
6
+ return !!file.decryptionKey && !!file.decryptionNonce;
7
+ }
4
8
  /** Type guard for a valid kind 1063 file metadata event */
5
9
  export function isValidFileMetadata(event) {
6
10
  return !!event && event.kind === 1063 && !!getTagValue(event, "url");
@@ -46,6 +50,12 @@ export function parseFileMetadataTags(tags) {
46
50
  metadata.alt = fields.alt;
47
51
  if (fields.blurhash)
48
52
  metadata.blurhash = fields.blurhash;
53
+ if (fields["encryption-algorithm"])
54
+ metadata.encryptionAlgorithm = fields["encryption-algorithm"];
55
+ if (fields["decryption-key"])
56
+ metadata.decryptionKey = fields["decryption-key"];
57
+ if (fields["decryption-nonce"])
58
+ metadata.decryptionNonce = fields["decryption-nonce"];
49
59
  return metadata;
50
60
  }
51
61
  /** Parses a imeta tag into a {@link FileMetadataFields} */
@@ -124,6 +134,12 @@ export function createFileMetadataTags(attachment) {
124
134
  if (attachment.fallback && attachment.fallback?.length > 0)
125
135
  for (const url of attachment.fallback)
126
136
  add("fallback", url);
137
+ if (attachment.encryptionAlgorithm)
138
+ add("encryption-algorithm", attachment.encryptionAlgorithm);
139
+ if (attachment.decryptionKey)
140
+ add("decryption-key", attachment.decryptionKey);
141
+ if (attachment.decryptionNonce)
142
+ add("decryption-nonce", attachment.decryptionNonce);
127
143
  return tags;
128
144
  }
129
145
  /** Creates an imeta tag for a media attachment */
@@ -17,6 +17,8 @@ export * from "./emoji.js";
17
17
  export * from "./emoji-pack.js";
18
18
  export * from "./encrypted-content-cache.js";
19
19
  export * from "./external-identities.js";
20
+ export * from "./encrypted-file.js";
21
+ export * from "./file-message.js";
20
22
  export * from "./file-metadata.js";
21
23
  export * from "./gift-wrap.js";
22
24
  export * from "./git-grasp-list.js";
@@ -36,6 +38,7 @@ export * from "./lnurl.js";
36
38
  export * from "./messages.js";
37
39
  export * from "./mute.js";
38
40
  export * from "./napplet.js";
41
+ export * from "./napplet-handlers.js";
39
42
  export * from "./nostr-web-token.js";
40
43
  export * from "./picture-post.js";
41
44
  export * from "./poll.js";
@@ -17,6 +17,8 @@ export * from "./emoji.js";
17
17
  export * from "./emoji-pack.js";
18
18
  export * from "./encrypted-content-cache.js";
19
19
  export * from "./external-identities.js";
20
+ export * from "./encrypted-file.js";
21
+ export * from "./file-message.js";
20
22
  export * from "./file-metadata.js";
21
23
  export * from "./gift-wrap.js";
22
24
  export * from "./git-grasp-list.js";
@@ -36,6 +38,7 @@ export * from "./lnurl.js";
36
38
  export * from "./messages.js";
37
39
  export * from "./mute.js";
38
40
  export * from "./napplet.js";
41
+ export * from "./napplet-handlers.js";
39
42
  export * from "./nostr-web-token.js";
40
43
  export * from "./picture-post.js";
41
44
  export * from "./poll.js";
@@ -33,8 +33,9 @@ export function getConversationParticipants(participants) {
33
33
  participantList = participants;
34
34
  }
35
35
  else {
36
- if (participants.kind !== kinds.EncryptedDirectMessage && participants.kind !== kinds.PrivateDirectMessage)
37
- throw new Error("Can only get participants from direct message event (4, 14)");
36
+ const kind = participants.kind;
37
+ if (kind !== kinds.EncryptedDirectMessage && kind !== kinds.PrivateDirectMessage && kind !== kinds.FileMessage)
38
+ throw new Error("Can only get participants from direct message event (4, 14, 15)");
38
39
  participantList = [participants.pubkey, ...participants.tags.filter(isPTag).map((t) => t[1])];
39
40
  }
40
41
  return Array.from(new Set(participantList));
@@ -82,8 +82,8 @@ export async function unlockHiddenMutes(mute, signer) {
82
82
  export function createMutedWordsRegExp(mutedWords) {
83
83
  // Escape special characters and join with |
84
84
  const escapedWords = mutedWords.map((word) => word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
85
- // Create the RegExp with word boundaries and case insensitive flag
86
- return new RegExp(`\\b(${escapedWords.join("|")})\\b`, "gi");
85
+ // Keep matches outside Unicode words, including combining marks and underscores
86
+ return new RegExp(`(?<![\\p{L}\\p{M}\\p{N}_])(${escapedWords.join("|")})(?![\\p{L}\\p{M}\\p{N}_])`, "giu");
87
87
  }
88
88
  // Compiled muted word RegExps, keyed by the words set so matchMutes doesn't rebuild one per event
89
89
  const mutedWordsRegExpCache = new WeakMap();
@@ -0,0 +1,79 @@
1
+ import { KnownEvent, NostrEvent } from "applesauce-core/helpers/event";
2
+ import { Filter } from "applesauce-core/helpers/filter";
3
+ import { HiddenContentSigner } from "applesauce-core/helpers/hidden-content";
4
+ import { AddressPointer, EventPointer } from "applesauce-core/helpers/pointers";
5
+ /**
6
+ * The event kind for napplet handler preferences (addressable events)
7
+ * @see https://github.com/napplet/naps/blob/master/naps/NAP-INTENT.md
8
+ */
9
+ export declare const NAPPLET_HANDLERS_KIND = 31129;
10
+ /** A validated napplet handler preferences event */
11
+ export type NappletHandlersEvent = KnownEvent<typeof NAPPLET_HANDLERS_KIND>;
12
+ /** A reference to a napplet that follows its latest manifest, or to a pinned snapshot */
13
+ export type NappletHandlerRef = {
14
+ type: "address";
15
+ pointer: AddressPointer;
16
+ } | {
17
+ type: "snapshot";
18
+ pointer: EventPointer;
19
+ };
20
+ /** The handler entries of one tag set (public or private), in preference order */
21
+ export type NappletHandlerEntries = {
22
+ /** Archetype-wide handlers from the `a` and `e` tags */
23
+ handlers: NappletHandlerRef[];
24
+ /** Intent-specific handlers from the `i` tags, keyed by convention identity */
25
+ intents: Map<string, NappletHandlerRef[]>;
26
+ };
27
+ /** A handler considered when resolving an intent */
28
+ export type NappletHandlerCandidate = {
29
+ /** The referenced napplet */
30
+ ref: NappletHandlerRef;
31
+ /** Whether the entry came from the private tags */
32
+ hidden: boolean;
33
+ /** Whether the entry is intent-specific (`i` tag) rather than archetype-wide */
34
+ intent: boolean;
35
+ };
36
+ /** Type for events with unlocked private handler entries */
37
+ export type UnlockedNappletHandlers = {
38
+ [NappletHandlersHiddenSymbol]: NappletHandlerEntries;
39
+ };
40
+ export declare const NappletHandlersPublicSymbol: unique symbol;
41
+ export declare const NappletHandlersHiddenSymbol: unique symbol;
42
+ /** Checks if an event is a valid napplet handler preferences event (kind 31129) */
43
+ export declare function isValidNappletHandlers(event?: NostrEvent): event is NappletHandlersEvent;
44
+ /** Returns the archetype from the `d` tag */
45
+ export declare function getNappletHandlersArchetype(event: NostrEvent): string;
46
+ /** Returns a relay filter for handler preferences of an archetype, optionally from a set of authors */
47
+ export declare function getNappletHandlersFilter(archetype: string, authors?: string[]): Filter;
48
+ /** Checks if an address points to a named (with an identifier) or root (without one) napplet manifest */
49
+ export declare function isNappletHandlerAddress(pointer: AddressPointer): boolean;
50
+ /** Returns the coordinate or snapshot id that identifies a handler reference, ignoring relay hints */
51
+ export declare function getNappletHandlerRefKey(ref: NappletHandlerRef): string;
52
+ /** Checks if two handler references name the same napplet or the same pinned snapshot */
53
+ export declare function isSameNappletHandlerRef(a: NappletHandlerRef, b: NappletHandlerRef): boolean;
54
+ /** Parses an `i` tag `<ref>`: a napplet coordinate or a snapshot id */
55
+ export declare function parseNappletHandlerRef(value: string): NappletHandlerRef | undefined;
56
+ /**
57
+ * Parses the handler entries from a set of tags, skipping malformed entries and unknown tags
58
+ * @param tags The public or private tags of the event
59
+ * @param archetype The archetype from the event's `d` tag
60
+ * @param hintTags Extra tags whose `a` and `e` entries provide relay hints and authors for `i` references
61
+ */
62
+ export declare function parseNappletHandlerTags(tags: string[][], archetype: string, hintTags?: string[][]): NappletHandlerEntries;
63
+ /** Returns the public handler entries, which other users read as recommendations */
64
+ export declare function getPublicNappletHandlers(event: NostrEvent): NappletHandlerEntries;
65
+ /** Returns the private handler entries if the event is unlocked */
66
+ export declare function getHiddenNappletHandlers<T extends NostrEvent & UnlockedNappletHandlers>(event: T): NappletHandlerEntries;
67
+ export declare function getHiddenNappletHandlers<T extends NostrEvent>(event: T): NappletHandlerEntries | undefined;
68
+ /** Checks if the private handler entries are unlocked */
69
+ export declare function isHiddenNappletHandlersUnlocked<T extends NostrEvent>(event: T): event is T & UnlockedNappletHandlers;
70
+ /**
71
+ * Decrypts the private handler entries
72
+ * @throws if the content cannot be decrypted into a list of tags
73
+ */
74
+ export declare function unlockHiddenNappletHandlers(event: NostrEvent, signer: HiddenContentSigner): Promise<NappletHandlerEntries>;
75
+ /**
76
+ * Returns the handlers to try for a convention identity, in resolution order
77
+ * @note Private entries are only included once unlocked, and a shell must still check each candidate is usable
78
+ */
79
+ export declare function getNappletHandlerCandidates(event: NostrEvent, identity: string): NappletHandlerCandidate[];
@@ -0,0 +1,187 @@
1
+ import { getOrComputeCachedValue, setCachedValue } from "applesauce-core/helpers/cache";
2
+ import { getReplaceableIdentifier, notifyEventUpdate } from "applesauce-core/helpers/event";
3
+ import { getHiddenTags, isHiddenTagsUnlocked, setHiddenTagsEncryptionMethod, unlockHiddenTags, } from "applesauce-core/helpers/hidden-tags";
4
+ import { getAddressPointerFromATag, getEventPointerFromETag, getReplaceableAddressFromPointer, parseReplaceableAddress, } from "applesauce-core/helpers/pointers";
5
+ import { isHexKey } from "applesauce-core/helpers/string";
6
+ import { NAPPLET_KIND, NAPPLET_ROOT_KIND, NAPPLET_SNAPSHOT_KIND, parseNappletConvention } from "./napplet.js";
7
+ /**
8
+ * The event kind for napplet handler preferences (addressable events)
9
+ * @see https://github.com/napplet/naps/blob/master/naps/NAP-INTENT.md
10
+ */
11
+ export const NAPPLET_HANDLERS_KIND = 31129;
12
+ // Private entries are NIP-44 encrypted to the author, as in NIP-51
13
+ setHiddenTagsEncryptionMethod(NAPPLET_HANDLERS_KIND, "nip44");
14
+ export const NappletHandlersPublicSymbol = Symbol.for("napplet-handlers-public");
15
+ export const NappletHandlersHiddenSymbol = Symbol.for("napplet-handlers-hidden");
16
+ /** Checks if an event is a valid napplet handler preferences event (kind 31129) */
17
+ export function isValidNappletHandlers(event) {
18
+ return !!event && event.kind === NAPPLET_HANDLERS_KIND && getReplaceableIdentifier(event) !== "";
19
+ }
20
+ /** Returns the archetype from the `d` tag */
21
+ export function getNappletHandlersArchetype(event) {
22
+ return getReplaceableIdentifier(event);
23
+ }
24
+ /** Returns a relay filter for handler preferences of an archetype, optionally from a set of authors */
25
+ export function getNappletHandlersFilter(archetype, authors) {
26
+ return { kinds: [NAPPLET_HANDLERS_KIND], "#d": [archetype], ...(authors ? { authors } : {}) };
27
+ }
28
+ /** Checks if an address points to a named (with an identifier) or root (without one) napplet manifest */
29
+ export function isNappletHandlerAddress(pointer) {
30
+ if (pointer.kind === NAPPLET_KIND)
31
+ return pointer.identifier !== "";
32
+ if (pointer.kind === NAPPLET_ROOT_KIND)
33
+ return pointer.identifier === "";
34
+ return false;
35
+ }
36
+ /** Returns the coordinate or snapshot id that identifies a handler reference, ignoring relay hints */
37
+ export function getNappletHandlerRefKey(ref) {
38
+ return ref.type === "address" ? getReplaceableAddressFromPointer(ref.pointer) : ref.pointer.id;
39
+ }
40
+ /** Checks if two handler references name the same napplet or the same pinned snapshot */
41
+ export function isSameNappletHandlerRef(a, b) {
42
+ return getNappletHandlerRefKey(a) === getNappletHandlerRefKey(b);
43
+ }
44
+ /** Parses an `i` tag `<ref>`: a napplet coordinate or a snapshot id */
45
+ export function parseNappletHandlerRef(value) {
46
+ if (isHexKey(value))
47
+ return { type: "snapshot", pointer: { id: value.toLowerCase(), kind: NAPPLET_SNAPSHOT_KIND } };
48
+ const pointer = parseReplaceableAddress(value);
49
+ if (!pointer || !isNappletHandlerAddress(pointer))
50
+ return undefined;
51
+ return { type: "address", pointer };
52
+ }
53
+ /** Parses an archetype-wide `a` or `e` handler tag */
54
+ function parseHandlerTag(tag) {
55
+ if (tag[0] === "a") {
56
+ const pointer = getAddressPointerFromATag(tag);
57
+ if (!pointer || !isNappletHandlerAddress(pointer))
58
+ return undefined;
59
+ return { type: "address", pointer };
60
+ }
61
+ if (tag[0] === "e") {
62
+ const pointer = getEventPointerFromETag(tag);
63
+ if (!pointer)
64
+ return undefined;
65
+ // The author is in the fourth position, after the optional relay hint
66
+ const snapshot = { ...pointer, kind: NAPPLET_SNAPSHOT_KIND };
67
+ if (isHexKey(tag[3]))
68
+ snapshot.author = tag[3];
69
+ return { type: "snapshot", pointer: snapshot };
70
+ }
71
+ return undefined;
72
+ }
73
+ /** Parses the archetype-wide `a` and `e` handlers from a set of tags, keeping the first of any repeats */
74
+ function parseHandlerTags(tags) {
75
+ const handlers = [];
76
+ const seen = new Set();
77
+ for (const tag of tags) {
78
+ const ref = parseHandlerTag(tag);
79
+ if (!ref)
80
+ continue;
81
+ const key = getNappletHandlerRefKey(ref);
82
+ if (seen.has(key))
83
+ continue;
84
+ seen.add(key);
85
+ handlers.push(ref);
86
+ }
87
+ return handlers;
88
+ }
89
+ /**
90
+ * Parses the handler entries from a set of tags, skipping malformed entries and unknown tags
91
+ * @param tags The public or private tags of the event
92
+ * @param archetype The archetype from the event's `d` tag
93
+ * @param hintTags Extra tags whose `a` and `e` entries provide relay hints and authors for `i` references
94
+ */
95
+ export function parseNappletHandlerTags(tags, archetype, hintTags = []) {
96
+ const handlers = parseHandlerTags(tags);
97
+ // An `i` tag has no relay hint, so borrow one from an `a` or `e` tag with the same reference
98
+ const hints = new Map();
99
+ for (const ref of [...handlers, ...parseHandlerTags(hintTags)]) {
100
+ const key = getNappletHandlerRefKey(ref);
101
+ if (!hints.has(key))
102
+ hints.set(key, ref);
103
+ }
104
+ const intents = new Map();
105
+ for (const tag of tags) {
106
+ if (tag[0] !== "i" || !tag[1] || !tag[2])
107
+ continue;
108
+ // Ignore identities with a query or fragment, or for another archetype
109
+ const convention = parseNappletConvention(tag[1]);
110
+ if (convention?.archetype !== archetype)
111
+ continue;
112
+ const parsed = parseNappletHandlerRef(tag[2]);
113
+ if (!parsed)
114
+ continue;
115
+ const ref = hints.get(getNappletHandlerRefKey(parsed)) ?? parsed;
116
+ const refs = intents.get(tag[1]) ?? [];
117
+ if (refs.some((existing) => isSameNappletHandlerRef(existing, ref)))
118
+ continue;
119
+ refs.push(ref);
120
+ intents.set(tag[1], refs);
121
+ }
122
+ return { handlers, intents };
123
+ }
124
+ /** Returns the public handler entries, which other users read as recommendations */
125
+ export function getPublicNappletHandlers(event) {
126
+ return getOrComputeCachedValue(event, NappletHandlersPublicSymbol, () => parseNappletHandlerTags(event.tags, getNappletHandlersArchetype(event)));
127
+ }
128
+ export function getHiddenNappletHandlers(event) {
129
+ if (NappletHandlersHiddenSymbol in event)
130
+ return event[NappletHandlersHiddenSymbol];
131
+ const tags = getHiddenTags(event);
132
+ if (!tags)
133
+ return undefined;
134
+ // Private `i` entries may reference a publicly listed napplet, so public tags also provide hints
135
+ const entries = parseNappletHandlerTags(tags, getNappletHandlersArchetype(event), event.tags);
136
+ // Derived from the event's own hidden tags, so it is memoized on the event non-enumerably
137
+ setCachedValue(event, NappletHandlersHiddenSymbol, entries);
138
+ return entries;
139
+ }
140
+ /** Checks if the private handler entries are unlocked */
141
+ export function isHiddenNappletHandlersUnlocked(event) {
142
+ return (isHiddenTagsUnlocked(event) &&
143
+ (NappletHandlersHiddenSymbol in event || getHiddenNappletHandlers(event) !== undefined));
144
+ }
145
+ /**
146
+ * Decrypts the private handler entries
147
+ * @throws if the content cannot be decrypted into a list of tags
148
+ */
149
+ export async function unlockHiddenNappletHandlers(event, signer) {
150
+ if (NappletHandlersHiddenSymbol in event)
151
+ return event[NappletHandlersHiddenSymbol];
152
+ await unlockHiddenTags(event, signer);
153
+ const entries = getHiddenNappletHandlers(event);
154
+ if (!entries)
155
+ throw new Error("Failed to unlock hidden napplet handlers");
156
+ notifyEventUpdate(event);
157
+ return entries;
158
+ }
159
+ /**
160
+ * Returns the handlers to try for a convention identity, in resolution order
161
+ * @note Private entries are only included once unlocked, and a shell must still check each candidate is usable
162
+ */
163
+ export function getNappletHandlerCandidates(event, identity) {
164
+ const publicEntries = getPublicNappletHandlers(event);
165
+ const hiddenEntries = getHiddenNappletHandlers(event);
166
+ // Private intent entries, then public intent entries, then private and public archetype-wide entries
167
+ const groups = [
168
+ [hiddenEntries?.intents.get(identity), true, true],
169
+ [publicEntries.intents.get(identity), false, true],
170
+ [hiddenEntries?.handlers, true, false],
171
+ [publicEntries.handlers, false, false],
172
+ ];
173
+ const candidates = [];
174
+ const seen = new Set();
175
+ for (const [refs, hidden, intent] of groups) {
176
+ if (!refs)
177
+ continue;
178
+ for (const ref of refs) {
179
+ const key = getNappletHandlerRefKey(ref);
180
+ if (seen.has(key))
181
+ continue;
182
+ seen.add(key);
183
+ candidates.push({ ref, hidden, intent });
184
+ }
185
+ }
186
+ return candidates;
187
+ }
@@ -87,3 +87,21 @@ export declare function getNappletIcon(event: NostrEvent): NappletIcon | undefin
87
87
  export declare function getNappletParentPointer(event: NostrEvent): AddressPointer | undefined;
88
88
  /** Returns the address of the root napplet a snapshot's lineage originates from (`A` tag) */
89
89
  export declare function getNappletRootPointer(event: NostrEvent): AddressPointer | undefined;
90
+ /** A NAP-INTENT convention identity split into its archetype and intent */
91
+ export type NappletConvention = {
92
+ archetype: string;
93
+ intent: string;
94
+ };
95
+ /**
96
+ * Parses a `napplet:<archetype>/<intent>` convention identity
97
+ * @returns undefined if the identity is malformed or has a query or fragment
98
+ * @see https://github.com/napplet/naps/blob/master/naps/NAP-INTENT.md
99
+ */
100
+ export declare function parseNappletConvention(identity: string): NappletConvention | undefined;
101
+ /**
102
+ * Creates a `napplet:<archetype>/<intent>` convention identity
103
+ * @throws if the resulting identity is malformed or has a query or fragment
104
+ */
105
+ export declare function createNappletConvention(archetype: string, intent: string): string;
106
+ /** Checks if a manifest advertises a convention identity for its archetype */
107
+ export declare function nappletSupportsConvention(manifest: NostrEvent, identity: string): boolean;
@@ -142,3 +142,36 @@ export function getNappletRootPointer(event) {
142
142
  const tag = event.tags.find((t) => t[0] === "A" && t[1]);
143
143
  return (tag && getAddressPointerFromATag(tag)) || undefined;
144
144
  }
145
+ /**
146
+ * Parses a `napplet:<archetype>/<intent>` convention identity
147
+ * @returns undefined if the identity is malformed or has a query or fragment
148
+ * @see https://github.com/napplet/naps/blob/master/naps/NAP-INTENT.md
149
+ */
150
+ export function parseNappletConvention(identity) {
151
+ if (identity.includes("?") || identity.includes("#"))
152
+ return undefined;
153
+ const match = identity.match(/^napplet:([^/]+)\/(.+)$/);
154
+ if (!match)
155
+ return undefined;
156
+ return { archetype: match[1], intent: match[2] };
157
+ }
158
+ /**
159
+ * Creates a `napplet:<archetype>/<intent>` convention identity
160
+ * @throws if the resulting identity is malformed or has a query or fragment
161
+ */
162
+ export function createNappletConvention(archetype, intent) {
163
+ const identity = `napplet:${archetype}/${intent}`;
164
+ const parsed = parseNappletConvention(identity);
165
+ if (parsed?.archetype !== archetype)
166
+ throw new Error(`Invalid napplet convention identity: ${identity}`);
167
+ return identity;
168
+ }
169
+ /** Checks if a manifest advertises a convention identity for its archetype */
170
+ export function nappletSupportsConvention(manifest, identity) {
171
+ const convention = parseNappletConvention(identity);
172
+ if (!convention)
173
+ return false;
174
+ if (!getNappletArchetypes(manifest).includes(convention.archetype))
175
+ return false;
176
+ return getNappletIntents(manifest).some((entry) => entry.intent === identity);
177
+ }
@@ -1,4 +1,6 @@
1
1
  import { Rumor } from "./gift-wrap.js";
2
+ /** Checks if a rumor is a NIP-17 chat message (kind 14) or a valid file message (kind 15) */
3
+ export declare function isWrappedMessage(rumor: Rumor): boolean;
2
4
  /** Returns the subject of a wrapped direct message */
3
5
  export declare function getWrappedMessageSubject(message: Rumor): string | undefined;
4
6
  /** Returns the parent id of a wrapped direct message */
@@ -1,5 +1,10 @@
1
- import { getTagValue } from "applesauce-core/helpers/event";
1
+ import { getTagValue, kinds } from "applesauce-core/helpers/event";
2
+ import { isValidFileMessage } from "./file-message.js";
2
3
  import { getConversationParticipants } from "./messages.js";
4
+ /** Checks if a rumor is a NIP-17 chat message (kind 14) or a valid file message (kind 15) */
5
+ export function isWrappedMessage(rumor) {
6
+ return rumor.kind === kinds.PrivateDirectMessage || isValidFileMessage(rumor);
7
+ }
3
8
  /** Returns the subject of a wrapped direct message */
4
9
  export function getWrappedMessageSubject(message) {
5
10
  return getTagValue(message, "subject");
@@ -21,3 +21,4 @@ export * from "./zap-goals.js";
21
21
  export * from "applesauce-core/models";
22
22
  import "./__register__.js";
23
23
  export * from "./nsite.js";
24
+ export * from "./napplet-handlers.js";
@@ -23,3 +23,4 @@ export * from "applesauce-core/models";
23
23
  // Register the common models with the event store
24
24
  import "./__register__.js";
25
25
  export * from "./nsite.js";
26
+ export * from "./napplet-handlers.js";
@@ -5,7 +5,12 @@ import { getLegacyMessageCorrespondent, getLegacyMessageParent } from "../helper
5
5
  import { getConversationIdentifierFromMessage, getConversationParticipants } from "../helpers/messages.js";
6
6
  /** A model that returns all legacy message groups (1-1) that a pubkey is participating in */
7
7
  export function LegacyMessagesGroups(self) {
8
- return (store) => store.timeline({ kinds: [kinds.EncryptedDirectMessage], "#p": [self] }).pipe(map((messages) => {
8
+ return (store) => store
9
+ .timeline([
10
+ { kinds: [kinds.EncryptedDirectMessage], "#p": [self] },
11
+ { kinds: [kinds.EncryptedDirectMessage], authors: [self] },
12
+ ])
13
+ .pipe(map((messages) => {
9
14
  const groups = {};
10
15
  for (const message of messages) {
11
16
  const id = getConversationIdentifierFromMessage(message);
@@ -0,0 +1,16 @@
1
+ import { Model } from "applesauce-core/event-store";
2
+ import { NappletHandlerRef, NappletHandlersEvent } from "../helpers/napplet-handlers.js";
3
+ import { NappletEvent } from "../helpers/napplet.js";
4
+ /** A napplet recommended as a handler, with the authors recommending it */
5
+ export interface RecommendedNappletHandler {
6
+ /** The napplet manifest or pinned snapshot */
7
+ napplet: NappletEvent;
8
+ /** The reference the recommenders used */
9
+ ref: NappletHandlerRef;
10
+ /** The pubkeys of the authors recommending the napplet */
11
+ recommenders: string[];
12
+ }
13
+ /** A model that returns handler preferences for an archetype, optionally from a set of authors */
14
+ export declare function NappletHandlersModel(archetype: string, authors?: string[]): Model<NappletHandlersEvent[]>;
15
+ /** A model that returns the napplets others publicly recommend for an archetype or intent, ranked by recommender count */
16
+ export declare function RecommendedNappletHandlersModel(archetype: string, authors?: string[], identity?: string): Model<RecommendedNappletHandler[]>;