brain-memory 0.1.0-beta.1 → 0.1.0-beta.10

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brain-memory",
3
- "version": "0.1.0-beta.1",
3
+ "version": "0.1.0-beta.10",
4
4
  "description": "A brain-inspired hierarchical memory system for AI coding agents. Deep nested file structure that mimics human memory with time-decay and strength-based recall.",
5
5
  "keywords": [
6
6
  "claude-code",
@@ -9,7 +9,11 @@
9
9
  "memory",
10
10
  "ai-agent",
11
11
  "context-engineering",
12
- "hierarchical-memory"
12
+ "hierarchical-memory",
13
+ "neuroscience",
14
+ "spaced-repetition",
15
+ "file-based",
16
+ "slash-commands"
13
17
  ],
14
18
  "author": {
15
19
  "name": "Onur Karali",
@@ -20,14 +24,16 @@
20
24
  "url": "https://github.com/onurkarali/brain/issues"
21
25
  },
22
26
  "bin": {
23
- "brain-memory": "bin/install.js"
27
+ "brain-memory": "bin/install.js",
28
+ "brain-recall": "bin/recall.js",
29
+ "brain-reinforce": "bin/reinforce.js"
24
30
  },
25
31
  "files": [
32
+ "assets/",
26
33
  "bin/",
27
34
  "commands/",
28
35
  "prompts/",
29
36
  "templates/",
30
- "hooks/",
31
37
  "src/",
32
38
  "README.md",
33
39
  "LICENSE"
@@ -37,7 +43,12 @@
37
43
  "url": "git+https://github.com/onurkarali/brain.git"
38
44
  },
39
45
  "scripts": {
40
- "test": "node --test 'test/*.test.js'"
46
+ "test": "node --test test/index-manager.test.js test/scorer.test.js test/tfidf.test.js test/recall.test.js test/functional.test.js test/sunshine.test.js test/stress.test.js test/crypto.test.js test/git-sync.test.js test/export-import.test.js test/install.test.js test/prompts.test.js",
47
+ "prerelease": "npm test",
48
+ "release:beta": "npm version prerelease --preid beta && npm publish --tag beta && npm dist-tag add brain-memory@$(node -p \"require('./package.json').version\") latest",
49
+ "release:patch": "npm version patch && npm publish",
50
+ "release:minor": "npm version minor && npm publish",
51
+ "release:major": "npm version major && npm publish"
41
52
  },
42
53
  "license": "MIT",
43
54
  "engines": {
package/prompts/claude.md CHANGED
@@ -4,7 +4,7 @@ This project uses the **Brain Memory** plugin — a hierarchical, file-system-ba
4
4
 
5
5
  ## Memory Location
6
6
 
7
- All memories are stored in `.brain/` with a deep nested directory structure organized by life domains (professional, personal, social, family) with on-demand subcategories.
7
+ All memories are stored in a single global `~/.brain/` directory in the user's home folder, shared across all projects and all supported AI agents. The directory uses a deep nested structure organized by life domains (professional, personal, social, family) with on-demand subcategories.
8
8
 
9
9
  ## How It Works
10
10
 
@@ -37,7 +37,7 @@ Each memory is a Markdown file with YAML frontmatter containing: `id`, `type`, `
37
37
  | observation | 0.40 | 0.950 | Casual facts or notices |
38
38
 
39
39
  ### Associative Network
40
- Memories are connected via weighted edges in `.brain/associations.json`. When you recall memory A, **spreading activation** automatically surfaces related memories B and C — just like how the brain activates linked neurons. Links are strengthened through **Hebbian learning**: memories recalled together become more tightly connected over time.
40
+ Memories are connected via weighted edges in `~/.brain/associations.json`. When you recall memory A, **spreading activation** automatically surfaces related memories B and C — just like how the brain activates linked neurons. Links are strengthened through **Hebbian learning**: memories recalled together become more tightly connected over time.
41
41
 
42
42
  ### Context-Dependent Recall
43
43
  Memories store their encoding context (project, topics, task type). During recall, memories encoded in a similar context to the current session are scored higher — matching how human memory works better when recall context matches encoding context.
@@ -58,18 +58,80 @@ Memories store their encoding context (project, topics, task type). During recal
58
58
  - `/brain:sunshine [target]` — Deep forensic erasure — trace and remove all references to a memory
59
59
  - `/brain:sleep [scope]` — Full maintenance cycle: replay, synaptic homeostasis, knowledge propagation, semantic crystallization, reorganize, consolidate, prune, REM dreaming, and expertise detection
60
60
  - `/brain:status` — Dashboard with brain health overview
61
+ - `/brain:sync [subcommand]` — Sync memories via Git remote or export/import for portability
62
+
63
+ ## Session Start Behavior
64
+
65
+ **IMPORTANT: Perform these steps automatically at the beginning of every session.**
66
+
67
+ If `~/.brain/index.json` exists:
68
+
69
+ 1. **Read the index** to understand the current brain state (memory count, categories)
70
+ 2. **Run the recall engine** to deterministically identify relevant memories for the current project:
71
+ ```bash
72
+ brain-recall --context --project "<current project>" --top 5
73
+ ```
74
+ This uses TF-IDF + the v4 scoring formula to find the most relevant memories — no guessing.
75
+ 3. **Silently internalize** the returned memories so you can reference them naturally during the session — do NOT dump memory contents
76
+ 4. **Check review queue** — read `~/.brain/review-queue.json` if it exists for memories due for review
77
+ 5. **Output a brief status** (1-3 lines):
78
+
79
+ If memories are due for review:
80
+ ```
81
+ 🧠 Brain active — <N> memories loaded (<M> in current project context)
82
+ 📋 <X> memories due for review — run /brain:review
83
+ ```
84
+
85
+ Otherwise:
86
+ ```
87
+ 🧠 Brain active — <N> memories loaded (<M> in current project context)
88
+ ```
89
+
90
+ If any frequently-used memories (access_count >= 3) have confidence < 0.5:
91
+ ```
92
+ ⚠️ <N> frequently-used memories have low confidence — consider verifying
93
+ ```
94
+
95
+ **The goal is ambient awareness** — know about past decisions, learnings, and preferences without reciting them. When a situation arises where a past memory is relevant, naturally reference it.
96
+
97
+ ## Session End Behavior
98
+
99
+ When a session is ending or the user signals they are done, evaluate whether the session contained:
100
+ - **Decisions** — Architecture choices, technology selections, trade-off resolutions
101
+ - **Learnings** — New patterns, debugging insights, API discoveries
102
+ - **Insights** — Realizations about the codebase, project, or process
103
+ - **Experiences** — Significant events like incidents, deployments, milestones
104
+ - **Goals** — New objectives discussed or planned
105
+
106
+ If the session contained meaningful content in any of these categories, suggest:
107
+ ```
108
+ 💡 This session contained notable <type(s)>. Would you like to store them as brain memories?
109
+ Run /brain:memorize to capture them before this context is lost.
110
+ ```
111
+
112
+ **Rules:**
113
+ - Do NOT auto-memorize without user consent
114
+ - Do NOT prompt for trivial sessions (quick fixes, typo corrections, simple questions)
115
+ - Only suggest when there is genuinely valuable context worth preserving
116
+ - Always save session context to `~/.brain/contexts.json` regardless (append a session summary, keep last 20 entries)
61
117
 
62
- ## Auto-Memorize Guidance
118
+ ## When Recalling Memories
63
119
 
64
- At the end of significant sessions, consider suggesting `/brain:memorize` to the user if important decisions, learnings, or insights occurred during the conversation. Do NOT automatically memorize without the user's awareness.
120
+ When the user asks you to "remember" something, or when context from past sessions would be helpful, use the **deterministic recall engine** instead of manually computing scores:
65
121
 
66
- ## When Recalling Memories
122
+ 1. Run `brain-recall "<query>" --project <project> --task <task_type> --top 10` (or `node <install-path>/bin/recall.js`)
123
+ 2. The engine computes TF-IDF relevance, decayed strength, spreading activation, context match, and salience — all deterministically
124
+ 3. Read the top-scoring memory files and present results
125
+ 4. Run `brain-reinforce <mem_id1> <mem_id2> ...` to apply spaced reinforcement and Hebbian co-retrieval strengthening
126
+ 5. If no matches, search the archive (`~/.brain/_archived/`)
127
+
128
+ The recall engine ensures **identical scoring across all agents** — Claude, Gemini, and Codex all get the same rankings for the same query.
129
+
130
+ ## Portable Sync
131
+
132
+ Brain memories can be synced across devices in two ways:
133
+
134
+ 1. **Git remote** — Push/pull `~/.brain/` to any private Git repository (GitHub, GitLab, Codeberg, self-hosted). Run `/brain:sync setup <url>` to configure, then use `/brain:sync push` and `/brain:sync pull`.
135
+ 2. **Export/Import** — Pack the entire `~/.brain/` into a single portable file for manual transfer. Run `/brain:sync export` and `/brain:sync import <path>`.
67
136
 
68
- When the user asks you to "remember" something, or when context from past sessions would be helpful:
69
- 1. Check `.brain/index.json` for relevant memories
70
- 2. Load `.brain/associations.json` for spreading activation
71
- 3. Score by v4 formula: `0.38*relevance + 0.18*decayed_strength + 0.08*recency + 0.14*spreading_bonus + 0.14*context_match + 0.08*salience`
72
- 4. Return strong individual matches or synthesize from multiple related memories
73
- 5. Apply spaced reinforcement (spacing-aware boost) and improve decay rate
74
- 6. Strengthen Hebbian links between co-retrieved memories
75
- 7. If no active matches, search the archive (`.brain/_archived/`)
137
+ Both methods support optional AES-256-GCM encryption. Sync is always manual — never automatic.
package/prompts/gemini.md CHANGED
@@ -4,7 +4,7 @@ This project uses the **Brain Memory** plugin — a hierarchical, file-system-ba
4
4
 
5
5
  ## Memory Location
6
6
 
7
- All memories are stored in `.brain/` with a deep nested directory structure organized by life domains (professional, personal, social, family) with on-demand subcategories.
7
+ All memories are stored in a single global `~/.brain/` directory in the user's home folder, shared across all projects and all supported AI agents. The directory uses a deep nested structure organized by life domains (professional, personal, social, family) with on-demand subcategories.
8
8
 
9
9
  ## How It Works
10
10
 
@@ -37,7 +37,7 @@ Each memory is a Markdown file with YAML frontmatter containing: `id`, `type`, `
37
37
  | observation | 0.40 | 0.950 | Casual facts or notices |
38
38
 
39
39
  ### Associative Network
40
- Memories are connected via weighted edges in `.brain/associations.json`. When you recall memory A, **spreading activation** automatically surfaces related memories B and C — just like how the brain activates linked neurons. Links are strengthened through **Hebbian learning**: memories recalled together become more tightly connected over time.
40
+ Memories are connected via weighted edges in `~/.brain/associations.json`. When you recall memory A, **spreading activation** automatically surfaces related memories B and C — just like how the brain activates linked neurons. Links are strengthened through **Hebbian learning**: memories recalled together become more tightly connected over time.
41
41
 
42
42
  ### Context-Dependent Recall
43
43
  Memories store their encoding context (project, topics, task type). During recall, memories encoded in a similar context to the current session are scored higher — matching how human memory works better when recall context matches encoding context.
@@ -59,18 +59,80 @@ Commands are available via `/brain:` prefix:
59
59
  - `/brain:sunshine [target]` — Deep forensic erasure — trace and remove all references to a memory
60
60
  - `/brain:sleep [scope]` — Full maintenance cycle: replay, synaptic homeostasis, knowledge propagation, semantic crystallization, reorganize, consolidate, prune, REM dreaming, and expertise detection
61
61
  - `/brain:status` — Dashboard with brain health overview
62
+ - `/brain:sync [subcommand]` — Sync memories via Git remote or export/import for portability
63
+
64
+ ## Session Start Behavior
65
+
66
+ **IMPORTANT: Perform these steps automatically at the beginning of every session.**
67
+
68
+ If `~/.brain/index.json` exists:
69
+
70
+ 1. **Read the index** to understand the current brain state (memory count, categories)
71
+ 2. **Run the recall engine** to deterministically identify relevant memories for the current project:
72
+ ```bash
73
+ brain-recall --context --project "<current project>" --top 5
74
+ ```
75
+ This uses TF-IDF + the v4 scoring formula to find the most relevant memories — no guessing.
76
+ 3. **Silently internalize** the returned memories so you can reference them naturally during the session — do NOT dump memory contents
77
+ 4. **Check review queue** — read `~/.brain/review-queue.json` if it exists for memories due for review
78
+ 5. **Output a brief status** (1-3 lines):
79
+
80
+ If memories are due for review:
81
+ ```
82
+ 🧠 Brain active — <N> memories loaded (<M> in current project context)
83
+ 📋 <X> memories due for review — run /brain:review
84
+ ```
85
+
86
+ Otherwise:
87
+ ```
88
+ 🧠 Brain active — <N> memories loaded (<M> in current project context)
89
+ ```
90
+
91
+ If any frequently-used memories (access_count >= 3) have confidence < 0.5:
92
+ ```
93
+ ⚠️ <N> frequently-used memories have low confidence — consider verifying
94
+ ```
95
+
96
+ **The goal is ambient awareness** — know about past decisions, learnings, and preferences without reciting them. When a situation arises where a past memory is relevant, naturally reference it.
97
+
98
+ ## Session End Behavior
99
+
100
+ When a session is ending or the user signals they are done, evaluate whether the session contained:
101
+ - **Decisions** — Architecture choices, technology selections, trade-off resolutions
102
+ - **Learnings** — New patterns, debugging insights, API discoveries
103
+ - **Insights** — Realizations about the codebase, project, or process
104
+ - **Experiences** — Significant events like incidents, deployments, milestones
105
+ - **Goals** — New objectives discussed or planned
106
+
107
+ If the session contained meaningful content in any of these categories, suggest:
108
+ ```
109
+ 💡 This session contained notable <type(s)>. Would you like to store them as brain memories?
110
+ Run /brain:memorize to capture them before this context is lost.
111
+ ```
112
+
113
+ **Rules:**
114
+ - Do NOT auto-memorize without user consent
115
+ - Do NOT prompt for trivial sessions (quick fixes, typo corrections, simple questions)
116
+ - Only suggest when there is genuinely valuable context worth preserving
117
+ - Always save session context to `~/.brain/contexts.json` regardless (append a session summary, keep last 20 entries)
62
118
 
63
- ## Auto-Memorize Guidance
119
+ ## When Recalling Memories
64
120
 
65
- At the end of significant sessions, consider suggesting `/brain:memorize` to the user if important decisions, learnings, or insights occurred during the conversation. Do NOT automatically memorize without the user's awareness.
121
+ When the user asks you to "remember" something, or when context from past sessions would be helpful, use the **deterministic recall engine** instead of manually computing scores:
66
122
 
67
- ## When Recalling Memories
123
+ 1. Run `brain-recall "<query>" --project <project> --task <task_type> --top 10` (or `node <install-path>/bin/recall.js`)
124
+ 2. The engine computes TF-IDF relevance, decayed strength, spreading activation, context match, and salience — all deterministically
125
+ 3. Read the top-scoring memory files and present results
126
+ 4. Run `brain-reinforce <mem_id1> <mem_id2> ...` to apply spaced reinforcement and Hebbian co-retrieval strengthening
127
+ 5. If no matches, search the archive (`~/.brain/_archived/`)
128
+
129
+ The recall engine ensures **identical scoring across all agents** — Claude, Gemini, and Codex all get the same rankings for the same query.
130
+
131
+ ## Portable Sync
132
+
133
+ Brain memories can be synced across devices in two ways:
134
+
135
+ 1. **Git remote** — Push/pull `~/.brain/` to any private Git repository (GitHub, GitLab, Codeberg, self-hosted). Run `/brain:sync setup <url>` to configure, then use `/brain:sync push` and `/brain:sync pull`.
136
+ 2. **Export/Import** — Pack the entire `~/.brain/` into a single portable file for manual transfer. Run `/brain:sync export` and `/brain:sync import <path>`.
68
137
 
69
- When the user asks you to "remember" something, or when context from past sessions would be helpful:
70
- 1. Check `.brain/index.json` for relevant memories
71
- 2. Load `.brain/associations.json` for spreading activation
72
- 3. Score by v4 formula: `0.38*relevance + 0.18*decayed_strength + 0.08*recency + 0.14*spreading_bonus + 0.14*context_match + 0.08*salience`
73
- 4. Return strong individual matches or synthesize from multiple related memories
74
- 5. Apply spaced reinforcement (spacing-aware boost) and improve decay rate
75
- 6. Strengthen Hebbian links between co-retrieved memories
76
- 7. If no active matches, search the archive (`.brain/_archived/`)
138
+ Both methods support optional AES-256-GCM encryption. Sync is always manual — never automatic.
package/prompts/openai.md CHANGED
@@ -59,18 +59,80 @@ Brain skills are available via `/brain-` prefix:
59
59
  - `/brain-sunshine [target]` — Deep forensic erasure — trace and remove all references to a memory
60
60
  - `/brain-sleep [scope]` — Full maintenance cycle: replay, synaptic homeostasis, knowledge propagation, semantic crystallization, reorganize, consolidate, prune, REM dreaming, and expertise detection
61
61
  - `/brain-status` — Dashboard with brain health overview
62
+ - `/brain-sync [subcommand]` — Sync memories via Git remote or export/import for portability
63
+
64
+ ## Session Start Behavior
65
+
66
+ **IMPORTANT: Perform these steps automatically at the beginning of every session.**
67
+
68
+ If `.brain/index.json` exists in the current project:
69
+
70
+ 1. **Read the index** to understand the current brain state (memory count, categories)
71
+ 2. **Run the recall engine** to deterministically identify relevant memories for the current project:
72
+ ```bash
73
+ brain-recall --context --project "<current project>" --top 5
74
+ ```
75
+ This uses TF-IDF + the v4 scoring formula to find the most relevant memories — no guessing.
76
+ 3. **Silently internalize** the returned memories so you can reference them naturally during the session — do NOT dump memory contents
77
+ 4. **Check review queue** — read `.brain/review-queue.json` if it exists for memories due for review
78
+ 5. **Output a brief status** (1-3 lines):
79
+
80
+ If memories are due for review:
81
+ ```
82
+ 🧠 Brain active — <N> memories loaded (<M> in current project context)
83
+ 📋 <X> memories due for review — run /brain-review
84
+ ```
85
+
86
+ Otherwise:
87
+ ```
88
+ 🧠 Brain active — <N> memories loaded (<M> in current project context)
89
+ ```
90
+
91
+ If any frequently-used memories (access_count >= 3) have confidence < 0.5:
92
+ ```
93
+ ⚠️ <N> frequently-used memories have low confidence — consider verifying
94
+ ```
95
+
96
+ **The goal is ambient awareness** — know about past decisions, learnings, and preferences without reciting them. When a situation arises where a past memory is relevant, naturally reference it.
97
+
98
+ ## Session End Behavior
99
+
100
+ When a session is ending or the user signals they are done, evaluate whether the session contained:
101
+ - **Decisions** — Architecture choices, technology selections, trade-off resolutions
102
+ - **Learnings** — New patterns, debugging insights, API discoveries
103
+ - **Insights** — Realizations about the codebase, project, or process
104
+ - **Experiences** — Significant events like incidents, deployments, milestones
105
+ - **Goals** — New objectives discussed or planned
106
+
107
+ If the session contained meaningful content in any of these categories, suggest:
108
+ ```
109
+ 💡 This session contained notable <type(s)>. Would you like to store them as brain memories?
110
+ Run /brain-memorize to capture them before this context is lost.
111
+ ```
112
+
113
+ **Rules:**
114
+ - Do NOT auto-memorize without user consent
115
+ - Do NOT prompt for trivial sessions (quick fixes, typo corrections, simple questions)
116
+ - Only suggest when there is genuinely valuable context worth preserving
117
+ - Always save session context to `.brain/contexts.json` regardless (append a session summary, keep last 20 entries)
62
118
 
63
- ## Auto-Memorize Guidance
119
+ ## When Recalling Memories
64
120
 
65
- At the end of significant sessions, consider suggesting `/brain-memorize` to the user if important decisions, learnings, or insights occurred during the conversation. Do NOT automatically memorize without the user's awareness.
121
+ When the user asks you to "remember" something, or when context from past sessions would be helpful, use the **deterministic recall engine** instead of manually computing scores:
66
122
 
67
- ## When Recalling Memories
123
+ 1. Run `brain-recall "<query>" --project <project> --task <task_type> --top 10` (or `node <install-path>/bin/recall.js`)
124
+ 2. The engine computes TF-IDF relevance, decayed strength, spreading activation, context match, and salience — all deterministically
125
+ 3. Read the top-scoring memory files and present results
126
+ 4. Run `brain-reinforce <mem_id1> <mem_id2> ...` to apply spaced reinforcement and Hebbian co-retrieval strengthening
127
+ 5. If no matches, search the archive (`.brain/_archived/`)
128
+
129
+ The recall engine ensures **identical scoring across all agents** — Claude, Gemini, and Codex all get the same rankings for the same query.
130
+
131
+ ## Portable Sync
132
+
133
+ Brain memories can be synced across devices in two ways:
134
+
135
+ 1. **Git remote** — Push/pull `.brain/` to any private Git repository (GitHub, GitLab, Codeberg, self-hosted). Run `/brain-sync setup <url>` to configure, then use `/brain-sync push` and `/brain-sync pull`.
136
+ 2. **Export/Import** — Pack the entire `.brain/` into a single portable file for manual transfer. Run `/brain-sync export` and `/brain-sync import <path>`.
68
137
 
69
- When the user asks you to "remember" something, or when context from past sessions would be helpful:
70
- 1. Check `.brain/index.json` for relevant memories
71
- 2. Load `.brain/associations.json` for spreading activation
72
- 3. Score by v4 formula: `0.38*relevance + 0.18*decayed_strength + 0.08*recency + 0.14*spreading_bonus + 0.14*context_match + 0.08*salience`
73
- 4. Return strong individual matches or synthesize from multiple related memories
74
- 5. Apply spaced reinforcement (spacing-aware boost) and improve decay rate
75
- 6. Strengthen Hebbian links between co-retrieved memories
76
- 7. If no active matches, search the archive (`.brain/_archived/`)
138
+ Both methods support optional AES-256-GCM encryption. Sync is always manual — never automatic.
package/src/crypto.js ADDED
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Brain Memory — Crypto Utilities
3
+ *
4
+ * AES-256-GCM encryption for memory export/import and encrypted sync.
5
+ * Zero external dependencies — uses only Node.js built-in crypto.
6
+ */
7
+
8
+ const crypto = require('crypto');
9
+
10
+ const PBKDF2_ITERATIONS = 100000;
11
+ const PBKDF2_DIGEST = 'sha512';
12
+ const KEY_LENGTH = 32; // 256 bits
13
+ const IV_LENGTH = 12; // 96 bits for GCM
14
+ const SALT_LENGTH = 32;
15
+ const AUTH_TAG_LENGTH = 16;
16
+
17
+ /**
18
+ * Derive an AES-256 key from a passphrase using PBKDF2.
19
+ *
20
+ * @param {string} passphrase - User-provided passphrase
21
+ * @param {Buffer} salt - 32-byte salt
22
+ * @returns {Buffer} 32-byte derived key
23
+ */
24
+ function deriveKey(passphrase, salt) {
25
+ return crypto.pbkdf2Sync(passphrase, salt, PBKDF2_ITERATIONS, KEY_LENGTH, PBKDF2_DIGEST);
26
+ }
27
+
28
+ /**
29
+ * Encrypt a UTF-8 string with AES-256-GCM.
30
+ *
31
+ * Output format: salt (32) + iv (12) + authTag (16) + ciphertext
32
+ *
33
+ * @param {string} plaintext - UTF-8 string to encrypt
34
+ * @param {string} passphrase - Passphrase (key derived via PBKDF2)
35
+ * @returns {Buffer} Encrypted buffer
36
+ */
37
+ function encrypt(plaintext, passphrase) {
38
+ const salt = crypto.randomBytes(SALT_LENGTH);
39
+ const key = deriveKey(passphrase, salt);
40
+ const iv = crypto.randomBytes(IV_LENGTH);
41
+
42
+ const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
43
+ const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
44
+ const authTag = cipher.getAuthTag();
45
+
46
+ return Buffer.concat([salt, iv, authTag, encrypted]);
47
+ }
48
+
49
+ /**
50
+ * Decrypt an AES-256-GCM encrypted buffer back to a UTF-8 string.
51
+ *
52
+ * @param {Buffer} encrypted - Buffer produced by encrypt()
53
+ * @param {string} passphrase - Same passphrase used for encryption
54
+ * @returns {string} Decrypted UTF-8 string
55
+ * @throws {Error} If passphrase is wrong or data is tampered
56
+ */
57
+ function decrypt(encrypted, passphrase) {
58
+ if (encrypted.length < SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH) {
59
+ throw new Error('Invalid encrypted data: too short');
60
+ }
61
+
62
+ const salt = encrypted.subarray(0, SALT_LENGTH);
63
+ const iv = encrypted.subarray(SALT_LENGTH, SALT_LENGTH + IV_LENGTH);
64
+ const authTag = encrypted.subarray(SALT_LENGTH + IV_LENGTH, SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH);
65
+ const ciphertext = encrypted.subarray(SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH);
66
+
67
+ const key = deriveKey(passphrase, salt);
68
+ const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
69
+ decipher.setAuthTag(authTag);
70
+
71
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8');
72
+ }
73
+
74
+ /**
75
+ * Encrypt a Buffer with AES-256-GCM.
76
+ *
77
+ * Output format: salt (32) + iv (12) + authTag (16) + ciphertext
78
+ *
79
+ * @param {Buffer} buffer - Raw buffer to encrypt
80
+ * @param {string} passphrase - Passphrase
81
+ * @returns {Buffer} Encrypted buffer
82
+ */
83
+ function encryptBuffer(buffer, passphrase) {
84
+ const salt = crypto.randomBytes(SALT_LENGTH);
85
+ const key = deriveKey(passphrase, salt);
86
+ const iv = crypto.randomBytes(IV_LENGTH);
87
+
88
+ const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
89
+ const encrypted = Buffer.concat([cipher.update(buffer), cipher.final()]);
90
+ const authTag = cipher.getAuthTag();
91
+
92
+ return Buffer.concat([salt, iv, authTag, encrypted]);
93
+ }
94
+
95
+ /**
96
+ * Decrypt a Buffer encrypted with encryptBuffer().
97
+ *
98
+ * @param {Buffer} encrypted - Buffer produced by encryptBuffer()
99
+ * @param {string} passphrase - Same passphrase used for encryption
100
+ * @returns {Buffer} Decrypted buffer
101
+ * @throws {Error} If passphrase is wrong or data is tampered
102
+ */
103
+ function decryptBuffer(encrypted, passphrase) {
104
+ if (encrypted.length < SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH) {
105
+ throw new Error('Invalid encrypted data: too short');
106
+ }
107
+
108
+ const salt = encrypted.subarray(0, SALT_LENGTH);
109
+ const iv = encrypted.subarray(SALT_LENGTH, SALT_LENGTH + IV_LENGTH);
110
+ const authTag = encrypted.subarray(SALT_LENGTH + IV_LENGTH, SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH);
111
+ const ciphertext = encrypted.subarray(SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH);
112
+
113
+ const key = deriveKey(passphrase, salt);
114
+ const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
115
+ decipher.setAuthTag(authTag);
116
+
117
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
118
+ }
119
+
120
+ module.exports = {
121
+ deriveKey,
122
+ encrypt,
123
+ decrypt,
124
+ encryptBuffer,
125
+ decryptBuffer,
126
+ PBKDF2_ITERATIONS,
127
+ SALT_LENGTH,
128
+ IV_LENGTH,
129
+ AUTH_TAG_LENGTH,
130
+ };