brain-memory 0.3.0 → 0.5.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 (62) hide show
  1. package/CHANGELOG.md +153 -0
  2. package/README.md +4 -0
  3. package/SECURITY.md +61 -9
  4. package/bin/brain.js +24 -3
  5. package/bin/cloud-sync.js +49 -6
  6. package/bin/install.js +72 -14
  7. package/bin/memorize.js +50 -6
  8. package/bin/port.js +174 -0
  9. package/bin/recall.js +16 -6
  10. package/bin/reinforce.js +5 -0
  11. package/bin/session-start.js +30 -4
  12. package/bin/verify.js +42 -4
  13. package/commands/brain/memorize.md +8 -0
  14. package/commands/brain/sync.md +23 -0
  15. package/commands/brain/verify.md +10 -2
  16. package/hooks/citation-check.mjs +94 -0
  17. package/hooks/hooks.json +11 -0
  18. package/hooks/lib.mjs +6 -0
  19. package/hooks/prompt-recall.mjs +24 -3
  20. package/hooks/session-start.mjs +4 -2
  21. package/integrations/README.md +4 -0
  22. package/integrations/agentskills/brain-memory/SKILL.md +9 -5
  23. package/package.json +10 -5
  24. package/prompts/antigravity.md +4 -2
  25. package/prompts/claude.md +4 -2
  26. package/prompts/copilot.md +4 -2
  27. package/prompts/kilo.md +4 -2
  28. package/prompts/openai.md +4 -2
  29. package/prompts/opencode.md +4 -2
  30. package/src/adapters.js +240 -0
  31. package/src/anomaly.js +41 -1
  32. package/src/cloud-sync.js +123 -11
  33. package/src/content-lint.js +55 -2
  34. package/src/export-import.js +1 -1
  35. package/src/git-sync.js +1 -1
  36. package/src/index-manager.js +9 -5
  37. package/src/installer.js +35 -1
  38. package/src/pinning.js +20 -1
  39. package/src/provenance.js +34 -0
  40. package/src/quarantine.js +82 -5
  41. package/src/receipt.js +9 -4
  42. package/src/surfaced.js +188 -0
  43. package/store/CONTRACT.md +244 -0
  44. package/store/Dockerfile +24 -0
  45. package/store/README.md +43 -0
  46. package/store/SELF-HOSTING.md +200 -0
  47. package/store/bin/brain-store.js +189 -0
  48. package/store/conformance/conformance.test.js +341 -0
  49. package/store/conformance/helpers.js +199 -0
  50. package/store/deploy/Caddyfile +14 -0
  51. package/store/deploy/connector.Dockerfile +38 -0
  52. package/store/deploy/docker-compose.yml +83 -0
  53. package/store/deploy/env.example +19 -0
  54. package/store/lib/auth.js +174 -0
  55. package/store/lib/oidc.js +206 -0
  56. package/store/lib/storage.js +333 -0
  57. package/store/lib/tar.js +150 -0
  58. package/store/openapi.yaml +318 -0
  59. package/store/server.js +465 -0
  60. package/store/test/mock-issuer.js +104 -0
  61. package/store/test/oidc.test.js +222 -0
  62. package/store/test/store.test.js +445 -0
@@ -0,0 +1,199 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Helpers for the store conformance suite. Nothing here imports the reference
5
+ * server except startReferenceStore(), so the suite can be pointed at any
6
+ * implementation of the contract.
7
+ */
8
+
9
+ const crypto = require('crypto');
10
+ const fs = require('fs');
11
+ const http = require('http');
12
+ const https = require('https');
13
+ const os = require('os');
14
+ const path = require('path');
15
+ const zlib = require('zlib');
16
+
17
+ // -- a minimal ustar writer, so the suite needs no system `tar` ----------------
18
+
19
+ function tarHeader(name, size, typeflag) {
20
+ const header = Buffer.alloc(512);
21
+ header.write(name, 0, 100, 'utf8');
22
+ header.write('0000644\0', 100, 'latin1');
23
+ header.write('0000000\0', 108, 'latin1');
24
+ header.write('0000000\0', 116, 'latin1');
25
+ header.write(size.toString(8).padStart(11, '0') + '\0', 124, 'latin1');
26
+ header.write('00000000000\0', 136, 'latin1');
27
+ header.fill(0x20, 148, 156);
28
+ header.write(typeflag, 156, 'latin1');
29
+ header.write('ustar\0', 257, 'latin1');
30
+ header.write('00', 263, 'latin1');
31
+ let sum = 0;
32
+ for (let i = 0; i < 512; i++) sum += header[i];
33
+ header.write(sum.toString(8).padStart(6, '0') + '\0 ', 148, 'latin1');
34
+ return header;
35
+ }
36
+
37
+ /**
38
+ * Build a gzip-compressed tar archive.
39
+ * @param {Object<string,string>} files path -> content
40
+ */
41
+ function makeArchive(files) {
42
+ const blocks = [tarHeader('./', 0, '5')];
43
+ for (const [name, content] of Object.entries(files)) {
44
+ const body = Buffer.from(content, 'utf8');
45
+ blocks.push(tarHeader(name, body.length, '0'), body);
46
+ const pad = (512 - (body.length % 512)) % 512;
47
+ if (pad) blocks.push(Buffer.alloc(pad));
48
+ }
49
+ blocks.push(Buffer.alloc(1024));
50
+ return zlib.gzipSync(Buffer.concat(blocks));
51
+ }
52
+
53
+ /** An archive with `count` memory files and unique content, so its checksum is unique too. */
54
+ function sampleArchive(count, label) {
55
+ const files = {};
56
+ const nonce = crypto.randomBytes(8).toString('hex');
57
+ for (let i = 0; i < count; i++) {
58
+ files[`professional/mem_${i}.md`] = `---\nid: mem_${i}\n---\n\n${label || 'sample'} ${nonce} ${i}\n`;
59
+ }
60
+ if (count > 0) files['index.json'] = JSON.stringify({ label: label || 'sample', nonce });
61
+ return makeArchive(files);
62
+ }
63
+
64
+ function sha256(buf) {
65
+ return crypto.createHash('sha256').update(buf).digest('hex');
66
+ }
67
+
68
+ // -- a thin client -----------------------------------------------------------
69
+
70
+ /**
71
+ * One HTTP request on a socket of its own, closed when the response ends.
72
+ *
73
+ * Deliberately not `fetch`: fetch keeps connections alive in a pool, and on
74
+ * Node 18 a pooled socket to a server that has just been shut down could keep a
75
+ * finished test process from exiting, which hung CI. With `agent: false` and
76
+ * `Connection: close` nothing outlives the request, on any Node version.
77
+ *
78
+ * @returns {Promise<{status: number, headers: {get: (name: string) => string|null}, body: Buffer}>}
79
+ */
80
+ function rawRequest(method, url, { headers, body } = {}) {
81
+ return new Promise((resolve, reject) => {
82
+ const target = new URL(url);
83
+ const mod = target.protocol === 'https:' ? https : http;
84
+ const req = mod.request(target, {
85
+ method,
86
+ agent: false,
87
+ headers: {
88
+ Connection: 'close',
89
+ ...(headers || {}),
90
+ ...(body != null ? { 'Content-Length': Buffer.byteLength(body) } : {}),
91
+ },
92
+ }, (res) => {
93
+ const chunks = [];
94
+ res.on('data', (chunk) => chunks.push(chunk));
95
+ res.on('error', reject);
96
+ res.on('end', () => resolve({
97
+ status: res.statusCode,
98
+ headers: {
99
+ get(name) {
100
+ const value = res.headers[String(name).toLowerCase()];
101
+ if (value == null) return null;
102
+ return Array.isArray(value) ? value.join(', ') : value;
103
+ },
104
+ },
105
+ body: Buffer.concat(chunks),
106
+ }));
107
+ });
108
+ req.on('error', reject);
109
+ req.setTimeout(30000, () => req.destroy(new Error(`${method} ${url} timed out`)));
110
+ req.end(body != null ? body : undefined);
111
+ });
112
+ }
113
+
114
+ function parseBody(buf) {
115
+ const text = buf.toString('utf8');
116
+ try { return text ? JSON.parse(text) : null; } catch { return text; }
117
+ }
118
+
119
+ /** The subset of `fetch` the OIDC verifier uses, without a connection pool. */
120
+ async function plainFetch(url, opts = {}) {
121
+ const res = await rawRequest(opts.method || 'GET', String(url), { headers: opts.headers, body: opts.body });
122
+ return {
123
+ ok: res.status >= 200 && res.status < 300,
124
+ status: res.status,
125
+ headers: res.headers,
126
+ json: async () => JSON.parse(res.body.toString('utf8')),
127
+ text: async () => res.body.toString('utf8'),
128
+ };
129
+ }
130
+
131
+ function client(baseUrl, token) {
132
+ const base = baseUrl.replace(/\/$/, '');
133
+ const auth = token ? { Authorization: `Bearer ${token}` } : {};
134
+
135
+ async function json(method, pathname, body, headers) {
136
+ const res = await rawRequest(method, base + pathname, {
137
+ headers: { ...auth, ...(body ? { 'Content-Type': 'application/json' } : {}), ...(headers || {}) },
138
+ body: body ? JSON.stringify(body) : undefined,
139
+ });
140
+ return { status: res.status, headers: res.headers, data: parseBody(res.body) };
141
+ }
142
+
143
+ async function upload(brainId, archive, { headers, query, field } = {}) {
144
+ const boundary = '----conformance' + crypto.randomBytes(8).toString('hex');
145
+ const head = Buffer.from(
146
+ `--${boundary}\r\n` +
147
+ `Content-Disposition: form-data; name="${field || 'brain'}"; filename="brain.tar.gz"\r\n` +
148
+ 'Content-Type: application/gzip\r\n\r\n'
149
+ );
150
+ const tail = Buffer.from(`\r\n--${boundary}--\r\n`);
151
+ const res = await rawRequest('PUT', `${base}/api/brains/${brainId}/sync${query || ''}`, {
152
+ headers: { ...auth, 'Content-Type': `multipart/form-data; boundary=${boundary}`, ...(headers || {}) },
153
+ body: Buffer.concat([head, archive, tail]),
154
+ });
155
+ return { status: res.status, headers: res.headers, data: parseBody(res.body) };
156
+ }
157
+
158
+ async function download(brainId, { headers, query } = {}) {
159
+ const res = await rawRequest('GET', `${base}/api/brains/${brainId}/sync${query || ''}`, {
160
+ headers: { ...auth, ...(headers || {}) },
161
+ });
162
+ return { status: res.status, headers: res.headers, body: res.body };
163
+ }
164
+
165
+ return { json, upload, download };
166
+ }
167
+
168
+ // -- the reference store, for when no STORE_URL is given ------------------------
169
+
170
+ async function startReferenceStore(options = {}) {
171
+ const { createStore } = require('../server');
172
+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'brain-store-conformance-'));
173
+ const store = createStore({
174
+ dataDir,
175
+ requestsPerMinute: 0,
176
+ uploadsPerMinute: 0,
177
+ failedAuthPerMinute: 0,
178
+ ...options,
179
+ });
180
+ const a = store.users.add('conformance-a', 'a@example.test');
181
+ const b = store.users.add('conformance-b', 'b@example.test');
182
+ const server = await store.listen(0, '127.0.0.1');
183
+ return {
184
+ url: `http://127.0.0.1:${server.address().port}`,
185
+ token: a.token,
186
+ token2: b.token,
187
+ store,
188
+ dataDir,
189
+ close: () => new Promise((resolve) => {
190
+ server.close(() => {
191
+ fs.rmSync(dataDir, { recursive: true, force: true });
192
+ resolve();
193
+ });
194
+ if (server.closeAllConnections) server.closeAllConnections();
195
+ }),
196
+ };
197
+ }
198
+
199
+ module.exports = { makeArchive, sampleArchive, sha256, client, plainFetch, startReferenceStore };
@@ -0,0 +1,14 @@
1
+ # Caddy terminates TLS for both services and obtains certificates by itself.
2
+ # Point two DNS names at this host, put them in .env, and open ports 80 and 443.
3
+
4
+ {$STORE_DOMAIN} {
5
+ encode zstd gzip
6
+ reverse_proxy store:8787
7
+ }
8
+
9
+ {$MCP_DOMAIN} {
10
+ reverse_proxy connector:8788 {
11
+ # MCP responses can be event streams: do not buffer them.
12
+ flush_interval -1
13
+ }
14
+ }
@@ -0,0 +1,38 @@
1
+ # The MCP connector, configured for a self-hosted store.
2
+ # Build from the repository root:
3
+ # docker build -f store/deploy/connector.Dockerfile -t brain-connector .
4
+ #
5
+ # The connector runs the repository's own command-line tools (bin/, src/) against
6
+ # each user's working copy, so the image carries those alongside connector/.
7
+ FROM node:22-alpine
8
+
9
+ WORKDIR /app
10
+ COPY package.json ./
11
+ COPY bin/ ./bin/
12
+ COPY src/ ./src/
13
+ # The OpenID Connect token verifier is shared with the store.
14
+ COPY store/lib/ ./store/lib/
15
+
16
+ WORKDIR /app/connector
17
+ COPY connector/package.json connector/package-lock.json ./
18
+ # tsx runs the TypeScript sources directly and is a dev dependency.
19
+ RUN npm ci --include=dev && npm cache clean --force
20
+ COPY connector/tsconfig.json ./
21
+ COPY connector/src/ ./src/
22
+
23
+ RUN mkdir -p /var/lib/brain-connector && chown node:node /var/lib/brain-connector
24
+ USER node
25
+
26
+ ENV NODE_ENV=production \
27
+ PORT=8788 \
28
+ CONNECTOR_BIND_HOST=0.0.0.0 \
29
+ CONNECTOR_IDP=static \
30
+ CONNECTOR_BRAIN_BASE=/run/brain-connector \
31
+ CONNECTOR_STATE_DIR=/var/lib/brain-connector
32
+
33
+ EXPOSE 8788
34
+
35
+ HEALTHCHECK --interval=30s --timeout=3s --start-period=10s \
36
+ CMD wget -qO- http://127.0.0.1:8788/health >/dev/null || exit 1
37
+
38
+ CMD ["node", "--import", "tsx", "src/server.ts"]
@@ -0,0 +1,83 @@
1
+ # Self-hosted Brain: a store, a stateless MCP connector in front of it, and Caddy
2
+ # for TLS. See ../SELF-HOSTING.md.
3
+ #
4
+ # cp env.example .env # then fill it in
5
+ # docker compose up -d --build
6
+ # docker compose exec store node store/bin/brain-store.js user add <name>
7
+
8
+ name: brain
9
+
10
+ services:
11
+ store:
12
+ build:
13
+ context: ../..
14
+ dockerfile: store/Dockerfile
15
+ restart: unless-stopped
16
+ environment:
17
+ STORE_ENCRYPTION_KEY: ${STORE_ENCRYPTION_KEY:?set STORE_ENCRYPTION_KEY in .env}
18
+ STORE_MAX_UPLOAD_MB: ${STORE_MAX_UPLOAD_MB:-50}
19
+ STORE_MAX_USER_MB: ${STORE_MAX_USER_MB:-0}
20
+ STORE_TRUST_PROXY: "1"
21
+ volumes:
22
+ - store-data:/data
23
+ read_only: true
24
+ tmpfs:
25
+ - /tmp
26
+ cap_drop: [ALL]
27
+ security_opt:
28
+ - no-new-privileges:true
29
+ networks: [internal]
30
+
31
+ connector:
32
+ build:
33
+ context: ../..
34
+ dockerfile: store/deploy/connector.Dockerfile
35
+ restart: unless-stopped
36
+ depends_on:
37
+ store:
38
+ condition: service_healthy
39
+ environment:
40
+ CONNECTOR_IDP: static
41
+ # The connector talks to the store over the private network, never the internet.
42
+ BRAIN_CLOUD_API_URL: http://store:8787
43
+ CONNECTOR_STATE_KEY: ${CONNECTOR_STATE_KEY:?set CONNECTOR_STATE_KEY in .env}
44
+ # Caddy is another container on the private network, not loopback.
45
+ CONNECTOR_TRUST_PROXY: uniquelocal
46
+ volumes:
47
+ - connector-state:/var/lib/brain-connector
48
+ read_only: true
49
+ tmpfs:
50
+ - /tmp
51
+ # Users' working copies are plaintext. Keep them in memory only.
52
+ - /run/brain-connector:uid=1000,gid=1000,mode=0700
53
+ - /home/node/.npm
54
+ cap_drop: [ALL]
55
+ security_opt:
56
+ - no-new-privileges:true
57
+ networks: [internal]
58
+
59
+ caddy:
60
+ image: caddy:2-alpine
61
+ restart: unless-stopped
62
+ depends_on: [store, connector]
63
+ ports:
64
+ - "80:80"
65
+ - "443:443"
66
+ - "443:443/udp"
67
+ environment:
68
+ STORE_DOMAIN: ${STORE_DOMAIN:?set STORE_DOMAIN in .env}
69
+ MCP_DOMAIN: ${MCP_DOMAIN:?set MCP_DOMAIN in .env}
70
+ volumes:
71
+ - ./Caddyfile:/etc/caddy/Caddyfile:ro
72
+ - caddy-data:/data
73
+ - caddy-config:/config
74
+ networks: [internal]
75
+
76
+ volumes:
77
+ store-data:
78
+ connector-state:
79
+ caddy-data:
80
+ caddy-config:
81
+
82
+ networks:
83
+ internal:
@@ -0,0 +1,19 @@
1
+ # Copy to .env and fill in: cp env.example .env
2
+ # Never commit the real file.
3
+
4
+ # Two DNS names that point at this host. Caddy gets certificates for them.
5
+ STORE_DOMAIN=store.example.com
6
+ MCP_DOMAIN=mcp.example.com
7
+
8
+ # Encrypts archives at rest. Generate with:
9
+ # docker compose run --rm store keygen
10
+ # Keep a copy somewhere safe: without it the stored archives cannot be read.
11
+ STORE_ENCRYPTION_KEY=
12
+
13
+ # Encrypts the connector's saved logins (so users are not logged out on restart).
14
+ # Generate with: openssl rand -hex 32
15
+ CONNECTOR_STATE_KEY=
16
+
17
+ # Optional limits.
18
+ STORE_MAX_UPLOAD_MB=50
19
+ STORE_MAX_USER_MB=0
@@ -0,0 +1,174 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * brain-store — users and static bearer tokens
5
+ *
6
+ * Users live in `<dataDir>/users.json`. Tokens are 256 bits of randomness, shown
7
+ * once at creation and stored only as a SHA-256 hash. A fast hash is appropriate
8
+ * here because the input is high-entropy random data, not a human password.
9
+ *
10
+ * The file is re-read when it changes on disk, so `brain-store user add` takes
11
+ * effect on a running server without a restart.
12
+ */
13
+
14
+ const crypto = require('crypto');
15
+ const fs = require('fs');
16
+ const path = require('path');
17
+
18
+ const USERS_FILE = 'users.json';
19
+ const TOKEN_PREFIX = 'bst_';
20
+ const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
21
+
22
+ function sha256Hex(text) {
23
+ return crypto.createHash('sha256').update(text, 'utf8').digest('hex');
24
+ }
25
+
26
+ function newToken() {
27
+ return TOKEN_PREFIX + crypto.randomBytes(32).toString('base64url');
28
+ }
29
+
30
+ function newUserId() {
31
+ return 'usr_' + crypto.randomBytes(9).toString('base64url');
32
+ }
33
+
34
+ class UserStore {
35
+ constructor(dataDir) {
36
+ this.file = path.join(dataDir, USERS_FILE);
37
+ this.users = [];
38
+ this.loadedSig = '';
39
+ fs.mkdirSync(dataDir, { recursive: true });
40
+ }
41
+
42
+ /** Re-read users.json if it changed since the last load. */
43
+ refresh() {
44
+ let stat;
45
+ try {
46
+ stat = fs.statSync(this.file);
47
+ } catch {
48
+ this.users = [];
49
+ this.loadedSig = '';
50
+ return;
51
+ }
52
+ const sig = stat.mtimeMs + ':' + stat.size;
53
+ if (sig === this.loadedSig) return;
54
+ const parsed = JSON.parse(fs.readFileSync(this.file, 'utf8'));
55
+ this.users = Array.isArray(parsed.users) ? parsed.users : [];
56
+ this.loadedSig = sig;
57
+ }
58
+
59
+ save() {
60
+ const tmp = this.file + '.' + crypto.randomBytes(6).toString('hex') + '.tmp';
61
+ fs.writeFileSync(tmp, JSON.stringify({ users: this.users }, null, 2) + '\n', { mode: 0o600 });
62
+ fs.renameSync(tmp, this.file);
63
+ const stat = fs.statSync(this.file);
64
+ this.loadedSig = stat.mtimeMs + ':' + stat.size;
65
+ }
66
+
67
+ list() {
68
+ this.refresh();
69
+ return this.users.map(publicUser);
70
+ }
71
+
72
+ find(nameOrId) {
73
+ this.refresh();
74
+ return this.users.find((u) => u.id === nameOrId || u.name === nameOrId) || null;
75
+ }
76
+
77
+ /**
78
+ * Create a user. Returns the public record and the token, which is never
79
+ * stored and cannot be shown again.
80
+ */
81
+ add(name, email) {
82
+ this.refresh();
83
+ if (!NAME_RE.test(name || '')) {
84
+ throw new Error('user name must be 1-64 characters: letters, digits, dot, dash, underscore');
85
+ }
86
+ if (this.users.some((u) => u.name === name)) throw new Error(`user "${name}" already exists`);
87
+ const token = newToken();
88
+ const user = {
89
+ id: newUserId(),
90
+ name,
91
+ email: email || '',
92
+ token_sha256: sha256Hex(token),
93
+ created_at: new Date().toISOString(),
94
+ };
95
+ this.users.push(user);
96
+ this.save();
97
+ return { user: publicUser(user), token };
98
+ }
99
+
100
+ /** Replace a user's token. The old token stops working immediately. */
101
+ rotate(nameOrId) {
102
+ const user = this.find(nameOrId);
103
+ if (!user) throw new Error(`no such user: ${nameOrId}`);
104
+ const token = newToken();
105
+ user.token_sha256 = sha256Hex(token);
106
+ user.rotated_at = new Date().toISOString();
107
+ this.save();
108
+ return { user: publicUser(user), token };
109
+ }
110
+
111
+ /**
112
+ * Find or create the user behind a verified OpenID Connect identity. The id is
113
+ * derived from issuer and subject, so the same person always maps to the same
114
+ * user, and two issuers can never collide. OIDC users have no static token
115
+ * unless the operator issues one with `user rotate`.
116
+ *
117
+ * @returns {{user: Object, created: boolean}}
118
+ */
119
+ upsertOidc(issuer, claims) {
120
+ this.refresh();
121
+ const id = 'oidc_' + crypto.createHash('sha256')
122
+ .update(issuer + '|' + claims.sub, 'utf8').digest('base64url').slice(0, 16);
123
+ const email = typeof claims.email === 'string' ? claims.email : '';
124
+ let user = this.users.find((u) => u.id === id);
125
+ if (user) {
126
+ if (email && user.email !== email) {
127
+ user.email = email;
128
+ this.save();
129
+ }
130
+ return { user: publicUser(user), created: false };
131
+ }
132
+ user = {
133
+ id,
134
+ name: id,
135
+ email,
136
+ oidc: { iss: issuer, sub: claims.sub },
137
+ created_at: new Date().toISOString(),
138
+ };
139
+ this.users.push(user);
140
+ this.save();
141
+ return { user: publicUser(user), created: true };
142
+ }
143
+
144
+ remove(nameOrId) {
145
+ const user = this.find(nameOrId);
146
+ if (!user) throw new Error(`no such user: ${nameOrId}`);
147
+ this.users = this.users.filter((u) => u.id !== user.id);
148
+ this.save();
149
+ return publicUser(user);
150
+ }
151
+
152
+ /**
153
+ * Resolve a bearer token to a user. Every stored hash is compared in constant
154
+ * time, and the loop never exits early, so timing reveals nothing about which
155
+ * user (if any) matched.
156
+ */
157
+ authenticate(token) {
158
+ if (typeof token !== 'string' || !token.startsWith(TOKEN_PREFIX) || token.length > 200) return null;
159
+ this.refresh();
160
+ const presented = Buffer.from(sha256Hex(token), 'hex');
161
+ let match = null;
162
+ for (const user of this.users) {
163
+ const stored = Buffer.from(String(user.token_sha256 || ''), 'hex');
164
+ if (stored.length === presented.length && crypto.timingSafeEqual(stored, presented)) match = user;
165
+ }
166
+ return match ? publicUser(match) : null;
167
+ }
168
+ }
169
+
170
+ function publicUser(user) {
171
+ return { id: user.id, name: user.name, email: user.email || '', created_at: user.created_at };
172
+ }
173
+
174
+ module.exports = { UserStore, TOKEN_PREFIX };