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,189 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * brain-store — self-hostable store for Brain Memory
6
+ *
7
+ * brain-store serve Run the server
8
+ * brain-store user add <name> Create a user and print their token (once)
9
+ * brain-store user list List users
10
+ * brain-store user rotate <name> Issue a new token; the old one stops working
11
+ * brain-store user remove <name> Remove a user (--purge also deletes their data)
12
+ * brain-store keygen Print a fresh encryption key
13
+ */
14
+
15
+ const crypto = require('crypto');
16
+ const os = require('os');
17
+ const path = require('path');
18
+ const { createStore, VERSION } = require('../server');
19
+ const { UserStore } = require('../lib/auth');
20
+ const { Storage, parseKey } = require('../lib/storage');
21
+
22
+ const HELP = `
23
+ brain-store ${VERSION} — self-hostable store for Brain Memory
24
+
25
+ Commands:
26
+ serve [--port N] [--host H] [--data DIR] Run the server
27
+ user add <name> [--email E] [--data DIR] Create a user; prints the token once
28
+ user list [--data DIR] List users
29
+ user rotate <name> [--data DIR] Issue a new token for a user
30
+ user remove <name> [--purge] [--data DIR] Remove a user (--purge deletes their brains)
31
+ keygen Print a fresh encryption key
32
+
33
+ Environment (flags win over environment):
34
+ STORE_DATA_DIR Data directory (default: ~/.brain-store)
35
+ STORE_PORT Port (default: 8787)
36
+ STORE_HOST Bind address (default: 127.0.0.1)
37
+ STORE_ENCRYPTION_KEY 32-byte key, hex or base64. Enables encryption at rest.
38
+ STORE_MAX_UPLOAD_MB Largest accepted archive (default: 50)
39
+ STORE_MAX_USER_MB Storage per user, 0 = unlimited (default: 0)
40
+ STORE_TRUST_PROXY "1" when behind a reverse proxy that sets X-Forwarded-For
41
+ STORE_OIDC_ISSUER Accept OpenID Connect ID tokens from this issuer ...
42
+ STORE_OIDC_AUDIENCE ... issued to this client id. Users are created on first sign-in.
43
+ STORE_OIDC_ALLOWED_DOMAINS, STORE_OIDC_ALLOWED_EMAILS
44
+ Comma-separated allow-lists. Required for a public issuer.
45
+ STORE_QUIET "1" to silence the request log
46
+
47
+ The server speaks plain HTTP. Put it behind a TLS-terminating reverse proxy
48
+ before exposing it beyond localhost. See SELF-HOSTING.md.
49
+ `.trim();
50
+
51
+ function flag(args, name) {
52
+ const i = args.indexOf(name);
53
+ if (i === -1) return undefined;
54
+ const value = args[i + 1];
55
+ args.splice(i, 2);
56
+ return value;
57
+ }
58
+
59
+ function boolFlag(args, name) {
60
+ const i = args.indexOf(name);
61
+ if (i === -1) return false;
62
+ args.splice(i, 1);
63
+ return true;
64
+ }
65
+
66
+ function dataDir(args) {
67
+ return path.resolve(
68
+ flag(args, '--data') || process.env.STORE_DATA_DIR || path.join(os.homedir(), '.brain-store')
69
+ );
70
+ }
71
+
72
+ async function serve(args) {
73
+ const dir = dataDir(args);
74
+ const port = Number(flag(args, '--port') || process.env.STORE_PORT || 8787);
75
+ const host = flag(args, '--host') || process.env.STORE_HOST || '127.0.0.1';
76
+ const quiet = process.env.STORE_QUIET === '1';
77
+ const encryptionKey = parseKey(process.env.STORE_ENCRYPTION_KEY);
78
+
79
+ const oidc = process.env.STORE_OIDC_ISSUER
80
+ ? {
81
+ issuer: process.env.STORE_OIDC_ISSUER,
82
+ audience: process.env.STORE_OIDC_AUDIENCE,
83
+ allowedDomains: process.env.STORE_OIDC_ALLOWED_DOMAINS,
84
+ allowedEmails: process.env.STORE_OIDC_ALLOWED_EMAILS,
85
+ }
86
+ : null;
87
+
88
+ const store = createStore({
89
+ dataDir: dir,
90
+ encryptionKey,
91
+ oidc,
92
+ maxUploadBytes: Number(process.env.STORE_MAX_UPLOAD_MB || 50) * 1024 * 1024,
93
+ maxUserBytes: Number(process.env.STORE_MAX_USER_MB || 0) * 1024 * 1024,
94
+ trustProxy: process.env.STORE_TRUST_PROXY === '1',
95
+ log: quiet ? null : (entry) => process.stdout.write(JSON.stringify({ ts: new Date().toISOString(), ...entry }) + '\n'),
96
+ });
97
+
98
+ const server = await store.listen(port, host);
99
+ const bound = server.address();
100
+ console.error(`brain-store ${VERSION} listening on http://${bound.address}:${bound.port}`);
101
+ console.error(` data: ${dir}`);
102
+ console.error(` encryption at rest: ${encryptionKey ? 'on' : 'off'}`);
103
+ console.error(` sign-in: static tokens${oidc ? ' + OpenID Connect (' + oidc.issuer + ')' : ''}`);
104
+ console.error(` users: ${store.users.list().length}`);
105
+ if (!['127.0.0.1', '::1', 'localhost'].includes(host)) {
106
+ console.error(' note: serving plain HTTP on a non-loopback address. Terminate TLS in front of this server.');
107
+ }
108
+
109
+ const stop = () => server.close(() => process.exit(0));
110
+ process.on('SIGINT', stop);
111
+ process.on('SIGTERM', stop);
112
+ }
113
+
114
+ function user(args) {
115
+ const sub = args.shift();
116
+ const dir = dataDir(args);
117
+ const users = new UserStore(dir);
118
+
119
+ if (sub === 'list') {
120
+ const all = users.list();
121
+ if (!all.length) return console.log('No users. Create one with: brain-store user add <name>');
122
+ for (const u of all) console.log(`${u.id}\t${u.name}\t${u.email || '-'}\t${u.created_at}`);
123
+ return;
124
+ }
125
+
126
+ if (sub === 'add') {
127
+ const email = flag(args, '--email');
128
+ const name = args.shift();
129
+ if (!name) throw new Error('usage: brain-store user add <name> [--email E]');
130
+ const created = users.add(name, email);
131
+ // A first brain, so a client that logs in has something to sync to.
132
+ new Storage(dir).createBrain(created.user.id, 'default');
133
+ printToken(created, 'created');
134
+ return;
135
+ }
136
+
137
+ if (sub === 'rotate') {
138
+ const name = args.shift();
139
+ if (!name) throw new Error('usage: brain-store user rotate <name>');
140
+ printToken(users.rotate(name), 'rotated');
141
+ return;
142
+ }
143
+
144
+ if (sub === 'remove') {
145
+ const purge = boolFlag(args, '--purge');
146
+ const name = args.shift();
147
+ if (!name) throw new Error('usage: brain-store user remove <name> [--purge]');
148
+ const removed = users.remove(name);
149
+ if (purge) new Storage(dir).deleteUser(removed.id);
150
+ console.log(`Removed ${removed.name} (${removed.id})${purge ? ' and deleted their brains' : '. Their brains were kept; add --purge to delete them'}.`);
151
+ return;
152
+ }
153
+
154
+ throw new Error('usage: brain-store user add|list|rotate|remove');
155
+ }
156
+
157
+ function printToken(result, verb) {
158
+ console.log(`User ${result.user.name} (${result.user.id}) ${verb}.`);
159
+ console.log('');
160
+ console.log('Token (shown once; the store keeps only a hash):');
161
+ console.log('');
162
+ console.log(' ' + result.token);
163
+ console.log('');
164
+ console.log('Connect a brain with:');
165
+ console.log(' brain cloud login --api-url <store URL> --token-stdin');
166
+ }
167
+
168
+ async function main() {
169
+ const args = process.argv.slice(2);
170
+ const command = args.shift();
171
+
172
+ if (!command || command === '--help' || command === '-h' || command === 'help') {
173
+ console.log(HELP);
174
+ return;
175
+ }
176
+ if (command === '--version' || command === '-v') return console.log(VERSION);
177
+ if (command === 'serve') return serve(args);
178
+ if (command === 'user') return user(args);
179
+ if (command === 'keygen') return console.log(crypto.randomBytes(32).toString('hex'));
180
+
181
+ console.error(`Unknown command: ${command}\n`);
182
+ console.error(HELP);
183
+ process.exit(1);
184
+ }
185
+
186
+ main().catch((err) => {
187
+ console.error('Error: ' + err.message);
188
+ process.exit(1);
189
+ });
@@ -0,0 +1,341 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Store contract conformance suite.
5
+ *
6
+ * Black-box: it speaks HTTP to a store and knows nothing about how the store is
7
+ * built. Point it at any implementation:
8
+ *
9
+ * STORE_URL=https://store.example STORE_TOKEN=... node --test store/conformance/
10
+ *
11
+ * STORE_TOKEN_2 a second user's token; enables the tenant-isolation tests
12
+ * STORE_BRAIN_ID use this (disposable!) brain instead of creating one, for
13
+ * accounts that cannot create another brain
14
+ * STORE_CONTRACT "1" to check only contract version 1; default "1.1"
15
+ *
16
+ * With no STORE_URL, the suite starts the reference server on a temporary
17
+ * directory and tests that.
18
+ *
19
+ * The suite overwrites the brain it works on. Never point it at a brain you care
20
+ * about.
21
+ */
22
+
23
+ const { describe, it, before, after } = require('node:test');
24
+ const assert = require('node:assert/strict');
25
+ const { sampleArchive, makeArchive, sha256, client, startReferenceStore } = require('./helpers');
26
+
27
+ const LEVEL_1_1 = (process.env.STORE_CONTRACT || '1.1') !== '1';
28
+ const UNKNOWN_BRAIN = '00000000-0000-4000-8000-000000000000';
29
+
30
+ describe('store contract', () => {
31
+ let reference = null;
32
+ let api;
33
+ let api2 = null;
34
+ let anonymous;
35
+ let brainId;
36
+ let createdBrain = false;
37
+
38
+ let first; // archives uploaded along the way
39
+ let second;
40
+
41
+ before(async () => {
42
+ let url = process.env.STORE_URL;
43
+ let token = process.env.STORE_TOKEN;
44
+ let token2 = process.env.STORE_TOKEN_2;
45
+ if (!url) {
46
+ reference = await startReferenceStore();
47
+ ({ url, token, token2 } = reference);
48
+ }
49
+ assert.ok(token, 'STORE_TOKEN is required when STORE_URL is set');
50
+ api = client(url, token);
51
+ anonymous = client(url, null);
52
+ if (token2) api2 = client(url, token2);
53
+ });
54
+
55
+ after(async () => {
56
+ if (createdBrain && brainId) await api.json('DELETE', `/api/brains/${brainId}`);
57
+ if (reference) await reference.close();
58
+ });
59
+
60
+ // -- version 1 -------------------------------------------------------------
61
+
62
+ describe('health and authentication', () => {
63
+ it('GET /health answers without credentials', async () => {
64
+ const res = await anonymous.json('GET', '/health');
65
+ assert.equal(res.status, 200);
66
+ assert.equal(res.data.status, 'ok');
67
+ });
68
+
69
+ it('rejects requests without a token', async () => {
70
+ assert.equal((await anonymous.json('GET', '/api/brains')).status, 401);
71
+ assert.equal((await anonymous.json('GET', '/auth/me')).status, 401);
72
+ });
73
+
74
+ it('rejects an unknown token', async () => {
75
+ const stranger = client(process.env.STORE_URL || reference.url, 'bst_not-a-real-token');
76
+ assert.equal((await stranger.json('GET', '/api/brains')).status, 401);
77
+ });
78
+
79
+ it('GET /auth/me describes the caller', async () => {
80
+ const res = await api.json('GET', '/auth/me');
81
+ assert.equal(res.status, 200);
82
+ assert.equal(typeof res.data.user, 'object');
83
+ assert.equal(typeof res.data.user.id, 'string');
84
+ assert.equal(typeof res.data.user.email, 'string');
85
+ });
86
+
87
+ it('errors are JSON objects with an "error" string', async () => {
88
+ const res = await anonymous.json('GET', '/api/brains');
89
+ assert.equal(typeof res.data.error, 'string');
90
+ });
91
+ });
92
+
93
+ describe('brain records', () => {
94
+ it('creates a brain, or adopts STORE_BRAIN_ID', async () => {
95
+ if (process.env.STORE_BRAIN_ID) {
96
+ brainId = process.env.STORE_BRAIN_ID;
97
+ return;
98
+ }
99
+ const name = 'conformance-' + Date.now();
100
+ const res = await api.json('POST', '/api/brains', { name });
101
+ assert.equal(res.status, 201, `could not create a brain (${res.status}); set STORE_BRAIN_ID to a disposable brain`);
102
+ assert.match(res.data.id, /^[0-9a-f-]{36}$/i);
103
+ assert.equal(res.data.name, name);
104
+ brainId = res.data.id;
105
+ createdBrain = true;
106
+ });
107
+
108
+ it('lists the brain as a bare JSON array', async () => {
109
+ const res = await api.json('GET', '/api/brains');
110
+ assert.equal(res.status, 200);
111
+ assert.ok(Array.isArray(res.data));
112
+ assert.ok(res.data.some((b) => b.id === brainId));
113
+ });
114
+
115
+ it('returns the brain record with the documented fields', async () => {
116
+ const res = await api.json('GET', `/api/brains/${brainId}`);
117
+ assert.equal(res.status, 200);
118
+ for (const field of ['id', 'name', 'size_bytes', 'file_count', 'last_synced_at', 'checksum', 'created_at']) {
119
+ assert.ok(field in res.data, `missing field ${field}`);
120
+ }
121
+ });
122
+
123
+ it('answers 404 for an unknown brain and 400 or 404 for a malformed ID', async () => {
124
+ assert.equal((await api.json('GET', `/api/brains/${UNKNOWN_BRAIN}`)).status, 404);
125
+ assert.ok([400, 404].includes((await api.json('GET', '/api/brains/not-a-uuid')).status));
126
+ });
127
+ });
128
+
129
+ describe('sync', () => {
130
+ it('downloading a brain that was never uploaded is 404', { skip: Boolean(process.env.STORE_BRAIN_ID) }, async () => {
131
+ assert.equal((await api.download(brainId)).status, 404);
132
+ });
133
+
134
+ it('accepts an upload and reports size, file count and SHA-256 of the archive', async () => {
135
+ first = sampleArchive(6, 'first'); // 6 memories + index.json
136
+ const res = await api.upload(brainId, first);
137
+ assert.equal(res.status, 200);
138
+ assert.equal(res.data.size_bytes, first.length);
139
+ assert.equal(res.data.file_count, 7);
140
+ assert.equal(res.data.checksum, sha256(first));
141
+ });
142
+
143
+ it('returns exactly the bytes that were uploaded, with X-Checksum', async () => {
144
+ const res = await api.download(brainId);
145
+ assert.equal(res.status, 200);
146
+ assert.ok(res.body.equals(first), 'downloaded archive differs from the upload');
147
+ assert.equal(res.headers.get('x-checksum'), sha256(first));
148
+ });
149
+
150
+ it('reflects the upload in the brain record', async () => {
151
+ const res = await api.json('GET', `/api/brains/${brainId}`);
152
+ assert.equal(res.data.size_bytes, first.length);
153
+ assert.equal(res.data.file_count, 7);
154
+ assert.equal(res.data.checksum, sha256(first));
155
+ assert.ok(!Number.isNaN(Date.parse(res.data.last_synced_at)));
156
+ });
157
+
158
+ it('rejects a request with no "brain" file field', async () => {
159
+ const res = await api.upload(brainId, first, { field: 'something-else' });
160
+ assert.equal(res.status, 400);
161
+ });
162
+ });
163
+
164
+ describe('snapshots', () => {
165
+ it('keeps the previous archive as a snapshot when a new one is uploaded', async () => {
166
+ second = sampleArchive(6, 'second');
167
+ assert.equal((await api.upload(brainId, second)).status, 200);
168
+
169
+ const res = await api.json('GET', `/api/brains/${brainId}/versions`);
170
+ assert.equal(res.status, 200);
171
+ assert.ok(Array.isArray(res.data.versions));
172
+ assert.ok(res.data.versions.length >= 1);
173
+ assert.equal(res.data.total, res.data.versions.length);
174
+ assert.equal(typeof res.data.versions[0].version, 'string');
175
+ });
176
+
177
+ it('lists snapshots newest first', async () => {
178
+ const { data } = await api.json('GET', `/api/brains/${brainId}/versions`);
179
+ const names = data.versions.map((v) => v.version);
180
+ assert.deepEqual(names, [...names].sort().reverse());
181
+ });
182
+
183
+ it('serves a snapshot through ?version=', async () => {
184
+ const { data } = await api.json('GET', `/api/brains/${brainId}/versions`);
185
+ const res = await api.download(brainId, { query: `?version=${encodeURIComponent(data.versions[0].version)}` });
186
+ assert.equal(res.status, 200);
187
+ assert.ok(res.body.equals(first), 'newest snapshot should be the archive that was just replaced');
188
+ });
189
+
190
+ it('refuses version names that try to leave the snapshot directory', async () => {
191
+ for (const name of ['../meta.json', '..%2F..%2Fusers.json', 'nope.tar.gz']) {
192
+ const res = await api.download(brainId, { query: `?version=${name}` });
193
+ assert.ok([400, 404].includes(res.status), `${name} -> ${res.status}`);
194
+ }
195
+ });
196
+
197
+ it('restores a snapshot as the live archive', async () => {
198
+ const { data } = await api.json('GET', `/api/brains/${brainId}/versions`);
199
+ const version = data.versions[0].version;
200
+ const res = await api.json('POST', `/api/brains/${brainId}/versions/${encodeURIComponent(version)}/restore`);
201
+ assert.equal(res.status, 200);
202
+ assert.equal(res.data.restored_version, version);
203
+ assert.ok((await api.download(brainId)).body.equals(first));
204
+ });
205
+
206
+ it('answers 404 when restoring a snapshot that does not exist', async () => {
207
+ const res = await api.json('POST', `/api/brains/${brainId}/versions/19990101T000000.000000000.tar.gz/restore`);
208
+ assert.equal(res.status, 404);
209
+ });
210
+ });
211
+
212
+ describe('the empty-push guard', () => {
213
+ it('refuses an empty archive over a brain that has memories', async () => {
214
+ const res = await api.upload(brainId, makeArchive({}));
215
+ assert.equal(res.status, 409);
216
+ assert.ok((await api.download(brainId)).body.equals(first), 'a refused push must change nothing');
217
+ });
218
+
219
+ it('accepts it with ?force=true', async () => {
220
+ const empty = makeArchive({});
221
+ const res = await api.upload(brainId, empty, { query: '?force=true' });
222
+ assert.equal(res.status, 200);
223
+ assert.equal(res.data.file_count, 0);
224
+ // Put real content back for the tests that follow.
225
+ assert.equal((await api.upload(brainId, first)).status, 200);
226
+ });
227
+ });
228
+
229
+ describe('tenant isolation', () => {
230
+ it('hides one user\'s brain from another', async (t) => {
231
+ if (!api2) return t.skip('no second token (STORE_TOKEN_2)');
232
+ assert.equal((await api2.json('GET', `/api/brains/${brainId}`)).status, 404);
233
+ assert.equal((await api2.download(brainId)).status, 404);
234
+ assert.equal((await api2.upload(brainId, sampleArchive(1, 'intruder'))).status, 404);
235
+ assert.equal((await api2.json('GET', `/api/brains/${brainId}/versions`)).status, 404);
236
+ const list = await api2.json('GET', '/api/brains');
237
+ assert.ok(!list.data.some((b) => b.id === brainId));
238
+ assert.ok((await api.download(brainId)).body.equals(first), 'the owner\'s archive must be untouched');
239
+ });
240
+ });
241
+
242
+ // -- version 1.1: conditional sync -------------------------------------------
243
+
244
+ describe('conditional sync (contract 1.1)', { skip: !LEVEL_1_1 }, () => {
245
+ it('GET /health advertises contract 1.1 or later', async () => {
246
+ const { data } = await anonymous.json('GET', '/health');
247
+ assert.ok(parseFloat(data.contract) >= 1.1, `contract is ${data.contract}`);
248
+ });
249
+
250
+ it('sends the checksum as a strong ETag on download and upload', async () => {
251
+ const down = await api.download(brainId);
252
+ assert.equal(down.headers.get('etag'), `"${sha256(first)}"`);
253
+ const up = await api.upload(brainId, first);
254
+ assert.equal(up.headers.get('etag'), `"${sha256(first)}"`);
255
+ });
256
+
257
+ it('answers 304 to If-None-Match when the client is current', async () => {
258
+ const res = await api.download(brainId, { headers: { 'If-None-Match': `"${sha256(first)}"` } });
259
+ assert.equal(res.status, 304);
260
+ assert.equal(res.body.length, 0);
261
+ });
262
+
263
+ it('sends the archive when If-None-Match is stale', async () => {
264
+ const res = await api.download(brainId, { headers: { 'If-None-Match': `"${'0'.repeat(64)}"` } });
265
+ assert.equal(res.status, 200);
266
+ assert.ok(res.body.equals(first));
267
+ });
268
+
269
+ it('accepts an upload whose If-Match names the current archive', async () => {
270
+ second = sampleArchive(6, 'second-conditional');
271
+ const res = await api.upload(brainId, second, { headers: { 'If-Match': `"${sha256(first)}"` } });
272
+ assert.equal(res.status, 200);
273
+ assert.equal(res.data.checksum, sha256(second));
274
+ });
275
+
276
+ it('refuses a stale If-Match with 412, reports the current checksum, and changes nothing', async () => {
277
+ const late = sampleArchive(6, 'late-writer');
278
+ const res = await api.upload(brainId, late, { headers: { 'If-Match': `"${sha256(first)}"` } });
279
+ assert.equal(res.status, 412);
280
+ assert.equal(res.data.current_checksum, sha256(second));
281
+ assert.ok((await api.download(brainId)).body.equals(second), 'a refused push must change nothing');
282
+ const { data } = await api.json('GET', `/api/brains/${brainId}`);
283
+ assert.equal(data.checksum, sha256(second));
284
+ });
285
+
286
+ it('lets exactly one of two racing writers win', async () => {
287
+ const base = sha256(second);
288
+ const a = sampleArchive(6, 'racer-a');
289
+ const b = sampleArchive(6, 'racer-b');
290
+ const results = await Promise.all([
291
+ api.upload(brainId, a, { headers: { 'If-Match': `"${base}"` } }),
292
+ api.upload(brainId, b, { headers: { 'If-Match': `"${base}"` } }),
293
+ ]);
294
+ const statuses = results.map((r) => r.status).sort();
295
+ assert.deepEqual(statuses, [200, 412]);
296
+ const winner = results[0].status === 200 ? a : b;
297
+ assert.ok((await api.download(brainId)).body.equals(winner));
298
+ second = winner;
299
+ });
300
+
301
+ it('treats If-None-Match: * on upload as "only if nothing is stored yet"', async () => {
302
+ const res = await api.upload(brainId, sampleArchive(6, 'first-writer'), { headers: { 'If-None-Match': '*' } });
303
+ assert.equal(res.status, 412);
304
+ assert.ok((await api.download(brainId)).body.equals(second));
305
+ });
306
+
307
+ it('still accepts an unconditional upload (version 1 clients)', async () => {
308
+ const res = await api.upload(brainId, first);
309
+ assert.equal(res.status, 200);
310
+ });
311
+
312
+ it('rejects an upload that is not a gzip-compressed tar archive', async () => {
313
+ for (const junk of [Buffer.from('this is not an archive'), require('zlib').gzipSync(Buffer.from('gzip, but not tar'.repeat(64)))]) {
314
+ const res = await api.upload(brainId, junk);
315
+ assert.equal(res.status, 400);
316
+ }
317
+ assert.ok((await api.download(brainId)).body.equals(first), 'a rejected upload must change nothing');
318
+ });
319
+
320
+ it('honours If-Match on restore', async () => {
321
+ const { data } = await api.json('GET', `/api/brains/${brainId}/versions`);
322
+ const version = data.versions[0].version;
323
+ const res = await api.json('POST', `/api/brains/${brainId}/versions/${encodeURIComponent(version)}/restore`,
324
+ null, { 'If-Match': `"${'0'.repeat(64)}"` });
325
+ assert.equal(res.status, 412);
326
+ });
327
+ });
328
+
329
+ // -- last: removal -----------------------------------------------------------
330
+
331
+ describe('removal', () => {
332
+ it('deletes a brain, after which it is gone', async (t) => {
333
+ if (!createdBrain) return t.skip('working on STORE_BRAIN_ID; not deleting it');
334
+ const res = await api.json('DELETE', `/api/brains/${brainId}`);
335
+ assert.ok([200, 204].includes(res.status));
336
+ assert.equal((await api.json('GET', `/api/brains/${brainId}`)).status, 404);
337
+ assert.equal((await api.download(brainId)).status, 404);
338
+ createdBrain = false;
339
+ });
340
+ });
341
+ });