@thezelijah/majik-message 1.0.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 (35) hide show
  1. package/LICENSE +67 -0
  2. package/README.md +265 -0
  3. package/dist/core/contacts/majik-contact-directory.d.ts +34 -0
  4. package/dist/core/contacts/majik-contact-directory.js +165 -0
  5. package/dist/core/contacts/majik-contact.d.ts +53 -0
  6. package/dist/core/contacts/majik-contact.js +135 -0
  7. package/dist/core/crypto/constants.d.ts +7 -0
  8. package/dist/core/crypto/constants.js +6 -0
  9. package/dist/core/crypto/crypto-provider.d.ts +20 -0
  10. package/dist/core/crypto/crypto-provider.js +70 -0
  11. package/dist/core/crypto/encryption-engine.d.ts +59 -0
  12. package/dist/core/crypto/encryption-engine.js +257 -0
  13. package/dist/core/crypto/keystore.d.ts +126 -0
  14. package/dist/core/crypto/keystore.js +575 -0
  15. package/dist/core/messages/envelope-cache.d.ts +51 -0
  16. package/dist/core/messages/envelope-cache.js +375 -0
  17. package/dist/core/messages/message-envelope.d.ts +36 -0
  18. package/dist/core/messages/message-envelope.js +161 -0
  19. package/dist/core/scanner/scanner-engine.d.ts +27 -0
  20. package/dist/core/scanner/scanner-engine.js +120 -0
  21. package/dist/core/types.d.ts +23 -0
  22. package/dist/core/types.js +1 -0
  23. package/dist/core/utils/APITranscoder.d.ts +114 -0
  24. package/dist/core/utils/APITranscoder.js +305 -0
  25. package/dist/core/utils/idb-majik-system.d.ts +15 -0
  26. package/dist/core/utils/idb-majik-system.js +37 -0
  27. package/dist/core/utils/majik-file-utils.d.ts +16 -0
  28. package/dist/core/utils/majik-file-utils.js +153 -0
  29. package/dist/core/utils/utilities.d.ts +22 -0
  30. package/dist/core/utils/utilities.js +80 -0
  31. package/dist/index.d.ts +13 -0
  32. package/dist/index.js +12 -0
  33. package/dist/majik-message.d.ts +202 -0
  34. package/dist/majik-message.js +940 -0
  35. package/package.json +97 -0
package/LICENSE ADDED
@@ -0,0 +1,67 @@
1
+ Copyright (c) 2025 Josef Elijah Delos Santos Fabian
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+
15
+ ---
16
+
17
+ Apache License
18
+ Version 2.0, January 2004
19
+ http://www.apache.org/licenses/
20
+
21
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
22
+
23
+ 1. Definitions.
24
+
25
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
26
+
27
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
28
+
29
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
30
+
31
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
32
+
33
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
34
+
35
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
36
+
37
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
40
+
41
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
42
+
43
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
44
+
45
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
46
+
47
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
48
+
49
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
50
+
51
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
52
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
53
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
54
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
55
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
56
+
57
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
58
+
59
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
60
+
61
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
62
+
63
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
64
+
65
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
66
+
67
+ END OF TERMS AND CONDITIONS
package/README.md ADDED
@@ -0,0 +1,265 @@
1
+ # Majik Message
2
+
3
+ **Majik Message** is a browser extension for **encrypting and decrypting text directly in your browser**. It is **not a chat platform** — it does not host conversations or store messages on a server. Instead, it allows you to securely encrypt text, share it with contacts, and decrypt it on any webpage, giving you full control over your data.
4
+
5
+
6
+
7
+ ---
8
+
9
+ - [Majik Message](#majik-message)
10
+ - [Features](#features)
11
+ - [Usage](#usage)
12
+ - [Encrypt Text](#encrypt-text)
13
+ - [Decrypt Text](#decrypt-text)
14
+ - [Account Management](#account-management)
15
+ - [Architecture](#architecture)
16
+ - [Browser Extension](#browser-extension)
17
+ - [Encryption](#encryption)
18
+ - [Contacts \& Accounts](#contacts--accounts)
19
+ - [Scanner](#scanner)
20
+ - [How to Use Majik Message](#how-to-use-majik-message)
21
+ - [1. Creating an Account](#1-creating-an-account)
22
+ - [2. Encrypting Messages (Manual / Side Panel)](#2-encrypting-messages-manual--side-panel)
23
+ - [3. Encrypting Text Inside a Web Page](#3-encrypting-text-inside-a-web-page)
24
+ - [4. Decrypting Messages](#4-decrypting-messages)
25
+ - [Decrypt an Entire Page](#decrypt-an-entire-page)
26
+ - [Decrypt a Selected Text](#decrypt-a-selected-text)
27
+ - [5. Automatic Scanning and Decryption](#5-automatic-scanning-and-decryption)
28
+ - [6. Sharing Your Account (Invite Key)](#6-sharing-your-account-invite-key)
29
+ - [7. Adding Contacts](#7-adding-contacts)
30
+ - [8. Importing an Existing Account](#8-importing-an-existing-account)
31
+ - [Notes and Security Reminders](#notes-and-security-reminders)
32
+ - [Contributing](#contributing)
33
+ - [License](#license)
34
+ - [Author](#author)
35
+ - [About the Developer](#about-the-developer)
36
+ - [Contact](#contact)
37
+
38
+
39
+ ---
40
+
41
+ ## Features
42
+
43
+ - **Text Encryption Anywhere**
44
+ - Highlight any text on a webpage (e.g., Gmail, Facebook), right-click, and select **Encrypt** to generate a secure string. Only authorized contacts can decrypt it.
45
+
46
+ - **Local Account with Seed Phrase**
47
+ - Accounts are derived from a **seed phrase** — no registration required.
48
+ - Add multiple contacts who can decrypt your messages.
49
+ - Share your account via **invite key** for collaborative access.
50
+ - Save, export, and import your account as a **JSON file** or **backup key**.
51
+
52
+ - **Page-Wide Decryption**
53
+ - Decrypt all valid encrypted strings on a page in a single action.
54
+
55
+ - **Automatic Scanner**
56
+ - Enable the scanner in settings to automatically detect and decrypt valid encrypted text on any webpage in real-time.
57
+
58
+ - **Privacy-First Design**
59
+ - All encryption and decryption occur locally. Messages are never stored on a server unless explicitly saved by the user.
60
+
61
+ ---
62
+
63
+ ## Usage
64
+
65
+ ### Encrypt Text
66
+
67
+ - Highlight text → right-click → Encrypt.
68
+ - Replace the text with an encrypted string or copy it.
69
+
70
+ ### Decrypt Text
71
+
72
+ - Highlight encrypted string → right-click → Decrypt
73
+ - Decrypt the entire page → right-click → Decrypt Page
74
+ - Or enable the scanner to auto-detect and decrypt strings on a page
75
+
76
+ ### Account Management
77
+
78
+ - Create an account from a seed phrase.
79
+ - Add contacts or share your account via an invite key.
80
+ - Export/import your account via JSON or backup key.
81
+
82
+ ---
83
+
84
+ ## Architecture
85
+
86
+ ### Browser Extension
87
+ Injects a content script for detecting and modifying page text.
88
+
89
+ ### Encryption
90
+ Uses standard cryptographic algorithms (AES, RSA or other implemented schemes) for end-to-end encryption.
91
+
92
+ ### Contacts & Accounts
93
+ Local storage using browser storage APIs (optional JSON backup).
94
+
95
+ ### Scanner
96
+ Observes DOM mutations to detect and auto-decrypt valid encrypted strings.
97
+
98
+ ---
99
+ ## How to Use Majik Message
100
+
101
+ ### 1. Creating an Account
102
+
103
+ Majik Message uses **seed-based accounts**. No email or registration is required.
104
+
105
+ 1. Open the **Side Panel**.
106
+ 2. A **seed phrase** will be automatically generated.
107
+ - You may regenerate a new seed phrase at any time by clicking the **dice icon**.
108
+ 3. Enter a **display name**.
109
+ - If left empty, your public key address will be used by default.
110
+ 4. Enter a **password**, then click **Apply** to create the account.
111
+ 5. Upon creation, a **JSON backup file** will be downloaded automatically.
112
+ - **Important:** Keep this file secure and private.
113
+ Anyone with access to this backup can open your account and decrypt your messages.
114
+
115
+ Once the account is created, it becomes the active account for encryption and decryption.
116
+
117
+ ---
118
+
119
+ ### 2. Encrypting Messages (Manual / Side Panel)
120
+
121
+ You can encrypt text directly from the Side Panel without interacting with a webpage.
122
+
123
+ 1. Open the **Side Panel**.
124
+ 2. Go to the **Message** tab.
125
+ 3. Toggle the mode to **Encrypt**.
126
+ 4. Choose recipients:
127
+ - Encrypt for **yourself only**, or
128
+ - Add one or more **contacts** so they can decrypt the same message.
129
+ 5. Enter your text into the input box.
130
+ 6. Choose an output option:
131
+ - Copy encrypted text to clipboard
132
+ - Download as a `.txt` file
133
+ - Download as a `.json` file
134
+
135
+ ---
136
+
137
+ ### 3. Encrypting Text Inside a Web Page
138
+
139
+ You can encrypt text directly inside any webpage (e.g., Gmail, Facebook).
140
+
141
+ 1. Open a page with a text editor (e.g., Gmail compose, Facebook post).
142
+ 2. Write or compose your message normally.
143
+ 3. Highlight the text you want to encrypt.
144
+ - You can press **Ctrl + A** to select all text.
145
+ 4. Right-click to open the context menu.
146
+ 5. Select **Majik Message → Encrypt**.
147
+ 6. Choose:
148
+ - Encrypt for yourself, or
149
+ - Encrypt for a specific contact.
150
+
151
+ The selected text will be replaced with an encrypted string.
152
+
153
+ ---
154
+
155
+ ### 4. Decrypting Messages
156
+
157
+ #### Decrypt an Entire Page
158
+
159
+ 1. Right-click anywhere on the page.
160
+ 2. Select **Majik Message → Decrypt Page**.
161
+ 3. All valid encrypted strings on the page will be decrypted.
162
+ - Decryption only works if the **active account** has access to the message.
163
+
164
+ ---
165
+
166
+ #### Decrypt a Selected Text
167
+
168
+ 1. Highlight the encrypted text.
169
+ 2. Right-click to open the context menu.
170
+ 3. Select **Majik Message → Decrypt**.
171
+
172
+ ---
173
+
174
+ ### 5. Automatic Scanning and Decryption
175
+
176
+ Majik Message can automatically detect and decrypt encrypted content on any page.
177
+
178
+ 1. Open the **Side Panel**.
179
+ 2. Go to the **Scanner** tab.
180
+ 3. Enable **Scan**.
181
+ 4. Enter your account password when prompted.
182
+
183
+ Once enabled:
184
+ - Any page you load (e.g., Gmail, Facebook) will be scanned.
185
+ - If encrypted content valid for your active account is detected, it will be decrypted automatically.
186
+
187
+ ---
188
+
189
+ ### 6. Sharing Your Account (Invite Key)
190
+
191
+ You can allow others to encrypt messages for you by sharing your invite key.
192
+
193
+ 1. Open the **Side Panel**.
194
+ 2. Go to the **Accounts** tab.
195
+ 3. Hover over your account.
196
+ 4. Click the **Share** icon.
197
+ 5. Copy and share your **invite key**.
198
+
199
+ Others can use this key to add you as a contact.
200
+
201
+ ---
202
+
203
+ ### 7. Adding Contacts
204
+
205
+ To decrypt messages from others or allow shared encryption:
206
+
207
+ 1. Open the **Side Panel**.
208
+ 2. Go to the **Contacts** tab.
209
+ 3. Click the **Add Friend** icon.
210
+ 4. Paste the other user’s **invite key**.
211
+
212
+ The contact will be added to your directory.
213
+
214
+ ---
215
+
216
+ ### 8. Importing an Existing Account
217
+
218
+ You can restore an account using a previously saved backup.
219
+
220
+ 1. Open the **Side Panel**.
221
+ 2. Go to the **Accounts** tab.
222
+ 3. Choose **Import Account**.
223
+ 4. Select your saved **JSON backup file**.
224
+ 5. Enter the associated password.
225
+
226
+ The account will be restored and can be set as active.
227
+
228
+ ---
229
+
230
+ ### Notes and Security Reminders
231
+
232
+ - All encryption and decryption are performed locally in your browser.
233
+ - Majik Message does not store messages or host conversations.
234
+ - Backup files and seed phrases grant full access to an account—store them securely.
235
+ - Decryption depends on the currently active account.
236
+
237
+ ---
238
+
239
+ ## Contributing
240
+
241
+ If you want to contribute or help extend support to more platforms, reach out via email. All contributions are welcome!
242
+
243
+ ---
244
+
245
+ ## License
246
+
247
+ [Apache-2.0](LICENSE) — free for personal and commercial use.
248
+
249
+ ---
250
+ ## Author
251
+
252
+ Made with 💙 by [@thezelijah](https://github.com/jedlsf)
253
+
254
+ ## About the Developer
255
+
256
+ - **Developer**: Josef Elijah Fabian
257
+ - **GitHub**: [https://github.com/jedlsf](https://github.com/jedlsf)
258
+ - **Project Repository**: [https://github.com/jedlsf/majik-message](https://github.com/jedlsf/majik-message)
259
+
260
+ ---
261
+
262
+ ## Contact
263
+
264
+ - **Business Email**: [business@thezelijah.world](mailto:business@thezelijah.world)
265
+ - **Official Website**: [https://www.thezelijah.world](https://www.thezelijah.world)
@@ -0,0 +1,34 @@
1
+ import { MessageEnvelope } from "../messages/message-envelope";
2
+ import { MAJIK_API_RESPONSE } from "../types";
3
+ import { MajikContact, MajikContactData, SerializedMajikContact } from "./majik-contact";
4
+ export interface MajikContactDirectoryData {
5
+ contacts: SerializedMajikContact[];
6
+ }
7
+ export declare class MajikContactDirectoryError extends Error {
8
+ cause?: unknown;
9
+ constructor(message: string, cause?: unknown);
10
+ }
11
+ export declare class MajikContactDirectory {
12
+ private contacts;
13
+ private fingerprintMap;
14
+ constructor(initialContacts?: MajikContact[]);
15
+ addContact(contact: MajikContact): this;
16
+ addContacts(contacts: MajikContact[]): this;
17
+ removeContact(id: string): MAJIK_API_RESPONSE;
18
+ updateContactMeta(id: string, meta: Partial<MajikContactData["meta"]>): MajikContact;
19
+ getContact(id: string): MajikContact | undefined;
20
+ getContactByFingerprint(fingerprint: string): MajikContact | undefined;
21
+ hasFingerprint(fingerprint: string): boolean;
22
+ listContacts(sortedByLabel?: boolean): MajikContact[];
23
+ blockContact(id: string): MajikContact;
24
+ unblockContact(id: string): MajikContact;
25
+ hasContact(id: string): boolean;
26
+ clear(): this;
27
+ /**
28
+ * Checks if a given envelope corresponds to a known contact
29
+ */
30
+ hasContactForEnvelope(envelope: MessageEnvelope): boolean;
31
+ toJSON(): Promise<MajikContactDirectoryData>;
32
+ fromJSON(data: MajikContactDirectoryData): Promise<this>;
33
+ private assertId;
34
+ }
@@ -0,0 +1,165 @@
1
+ import { KEY_ALGO } from "../crypto/constants";
2
+ import { base64ToArrayBuffer } from "../utils/utilities";
3
+ import { MajikContact, } from "./majik-contact";
4
+ /* -------------------------------
5
+ * Errors
6
+ * ------------------------------- */
7
+ export class MajikContactDirectoryError extends Error {
8
+ cause;
9
+ constructor(message, cause) {
10
+ super(message);
11
+ this.name = "MajikContactDirectoryError";
12
+ this.cause = cause;
13
+ }
14
+ }
15
+ /* -------------------------------
16
+ * MajikContactDirectory Class
17
+ * ------------------------------- */
18
+ export class MajikContactDirectory {
19
+ contacts = new Map();
20
+ fingerprintMap = new Map(); // fingerprint → contact id
21
+ constructor(initialContacts) {
22
+ if (initialContacts?.length) {
23
+ initialContacts.forEach((c) => this.addContact(c));
24
+ }
25
+ }
26
+ /* ================================
27
+ * Contact Management
28
+ * ================================ */
29
+ addContact(contact) {
30
+ if (!(contact instanceof MajikContact)) {
31
+ throw new MajikContactDirectoryError("Invalid contact instance");
32
+ }
33
+ if (this.contacts.has(contact.id)) {
34
+ throw new MajikContactDirectoryError(`Contact with id "${contact.id}" already exists`);
35
+ }
36
+ this.contacts.set(contact.id, contact);
37
+ this.fingerprintMap.set(contact.fingerprint, contact.id);
38
+ return this;
39
+ }
40
+ addContacts(contacts) {
41
+ contacts.forEach((c) => this.addContact(c));
42
+ return this;
43
+ }
44
+ removeContact(id) {
45
+ this.assertId(id);
46
+ const contact = this.contacts.get(id);
47
+ if (contact) {
48
+ this.fingerprintMap.delete(contact.fingerprint);
49
+ this.contacts.delete(id);
50
+ return {
51
+ message: "Contact removed successfully",
52
+ success: true,
53
+ };
54
+ }
55
+ else {
56
+ return {
57
+ message: "Contact not found",
58
+ success: false,
59
+ };
60
+ }
61
+ }
62
+ updateContactMeta(id, meta) {
63
+ const contact = this.getContact(id);
64
+ if (!contact)
65
+ throw new MajikContactDirectoryError("Contact not found");
66
+ if (meta) {
67
+ meta.label && contact.updateLabel(meta.label);
68
+ meta.notes && contact.updateNotes(meta.notes);
69
+ meta.blocked !== undefined && contact.setBlocked(meta.blocked);
70
+ }
71
+ return contact;
72
+ }
73
+ getContact(id) {
74
+ this.assertId(id);
75
+ return this.contacts.get(id);
76
+ }
77
+ getContactByFingerprint(fingerprint) {
78
+ if (!fingerprint) {
79
+ throw new MajikContactDirectoryError("Fingerprint must be a non-empty string");
80
+ }
81
+ const contactId = this.fingerprintMap.get(fingerprint);
82
+ return contactId ? this.contacts.get(contactId) : undefined;
83
+ }
84
+ hasFingerprint(fingerprint) {
85
+ return this.fingerprintMap.has(fingerprint);
86
+ }
87
+ listContacts(sortedByLabel = false) {
88
+ const contacts = [...this.contacts.values()];
89
+ if (sortedByLabel) {
90
+ contacts.sort((a, b) => (a.meta.label || "").localeCompare(b.meta.label || ""));
91
+ }
92
+ return contacts;
93
+ }
94
+ blockContact(id) {
95
+ const contact = this.getContact(id);
96
+ if (!contact)
97
+ throw new MajikContactDirectoryError(`Contact with id "${id}" not found for block`);
98
+ return contact.block();
99
+ }
100
+ unblockContact(id) {
101
+ const contact = this.getContact(id);
102
+ if (!contact)
103
+ throw new MajikContactDirectoryError(`Contact with id "${id}" not found for unblock`);
104
+ return contact.unblock();
105
+ }
106
+ hasContact(id) {
107
+ return this.contacts.has(id);
108
+ }
109
+ clear() {
110
+ this.contacts.clear();
111
+ this.fingerprintMap.clear();
112
+ return this;
113
+ }
114
+ /**
115
+ * Checks if a given envelope corresponds to a known contact
116
+ */
117
+ hasContactForEnvelope(envelope) {
118
+ try {
119
+ const fingerprint = envelope.extractFingerprint();
120
+ return this.hasFingerprint(fingerprint);
121
+ }
122
+ catch {
123
+ return false;
124
+ }
125
+ }
126
+ /* ================================
127
+ * Serialization / Persistence
128
+ * ================================ */
129
+ async toJSON() {
130
+ const contactsData = [];
131
+ for (const contact of this.contacts.values()) {
132
+ contactsData.push(await contact.toJSON());
133
+ }
134
+ return { contacts: contactsData };
135
+ }
136
+ async fromJSON(data) {
137
+ if (!data?.contacts) {
138
+ throw new MajikContactDirectoryError("Invalid serialized data");
139
+ }
140
+ this.clear();
141
+ for (const item of data.contacts) {
142
+ const raw = base64ToArrayBuffer(item.publicKeyBase64);
143
+ let publicKey;
144
+ try {
145
+ publicKey = await crypto.subtle.importKey("raw", raw, KEY_ALGO, true, []);
146
+ }
147
+ catch (e) {
148
+ // Fallback: create a raw-key wrapper when the browser does not support the namedCurve
149
+ publicKey = { raw: new Uint8Array(raw) };
150
+ }
151
+ const contact = MajikContact.create(item.id, publicKey, item.fingerprint, item.meta);
152
+ this.contacts.set(contact.id, contact);
153
+ this.fingerprintMap.set(contact.fingerprint, contact.id);
154
+ }
155
+ return this;
156
+ }
157
+ /* ================================
158
+ * Validation Helpers
159
+ * ================================ */
160
+ assertId(id) {
161
+ if (!id || typeof id !== "string") {
162
+ throw new MajikContactDirectoryError("Contact ID must be a non-empty string");
163
+ }
164
+ }
165
+ }
@@ -0,0 +1,53 @@
1
+ import { ISODateString } from "../types";
2
+ export type SerializedMajikContact = Omit<MajikContactData, "publicKey"> & {
3
+ publicKeyBase64: string;
4
+ };
5
+ export interface MajikContactMeta {
6
+ label?: string;
7
+ notes?: string;
8
+ blocked?: boolean;
9
+ createdAt?: ISODateString;
10
+ updatedAt?: ISODateString;
11
+ }
12
+ export interface MajikContactData {
13
+ id: string;
14
+ publicKey: CryptoKey | {
15
+ raw: Uint8Array;
16
+ };
17
+ fingerprint: string;
18
+ meta?: MajikContactMeta;
19
+ }
20
+ export interface MajikContactCard {
21
+ id: string;
22
+ publicKey: string;
23
+ fingerprint: string;
24
+ label: string;
25
+ }
26
+ export declare class MajikContactError extends Error {
27
+ cause?: unknown;
28
+ constructor(message: string, cause?: unknown);
29
+ }
30
+ export declare class MajikContact {
31
+ readonly id: string;
32
+ readonly publicKey: CryptoKey | {
33
+ raw: Uint8Array;
34
+ };
35
+ readonly fingerprint: string;
36
+ meta: MajikContactMeta;
37
+ constructor(data: MajikContactData);
38
+ static create(id: string, publicKey: CryptoKey | {
39
+ raw: Uint8Array;
40
+ }, fingerprint: string, meta?: Partial<MajikContactMeta>): MajikContact;
41
+ private assertId;
42
+ private assertPublicKey;
43
+ private assertFingerprint;
44
+ private updateTimestamp;
45
+ updateLabel(label: string): this;
46
+ updateNotes(notes: string): this;
47
+ isBlocked(): boolean;
48
+ setBlocked(blocked: boolean): this;
49
+ block(): this;
50
+ unblock(): this;
51
+ toJSON(): Promise<SerializedMajikContact>;
52
+ static isBlocked(contact: MajikContact): boolean;
53
+ }