humemory 0.2.2 → 0.2.4

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.
@@ -6,41 +6,70 @@
6
6
  * production database or raising a server (BUG-08).
7
7
  */
8
8
  import { Hono } from 'hono';
9
+ import { serverErrorBody } from './errors.js';
10
+ import { LimitExceeded, boundedInt, boundedOptionalInt, boundedString, boundedOptionalString, boundedStringArray, MAX_CONTENT_LENGTH, MAX_KEYWORDS, MAX_KEYWORD_LENGTH, MAX_SHORT_FIELD_LENGTH, MAX_QUERY_LENGTH, MAX_RESULT_LIMIT, } from './limits.js';
9
11
  export function createMemoryRoutes(store) {
10
12
  const app = new Hono();
13
+ // Limit violations are the caller's fault, not ours: 400, not 500
14
+ // (SECURITY_AUDIT.md M-02).
15
+ app.onError((error, c) => {
16
+ if (error instanceof LimitExceeded) {
17
+ return c.json({ success: false, error: error.message }, 400);
18
+ }
19
+ throw error;
20
+ });
11
21
  // === MEMORIES ===
12
22
  app.post('/memories', async (c) => {
13
23
  const body = await c.req.json();
24
+ // Every user-supplied field is bounded before it reaches the store: without
25
+ // this a single request could write an arbitrarily large row (M-02).
26
+ const content = boundedString(body.content, MAX_CONTENT_LENGTH, 'content');
27
+ const keywords = boundedStringArray(body.keywords, {
28
+ maxItems: MAX_KEYWORDS,
29
+ maxItemLength: MAX_KEYWORD_LENGTH,
30
+ name: 'keywords',
31
+ });
32
+ // level3Keywords is the flat BM25 keyword line, not an array (core/types.ts).
33
+ const level3Keywords = boundedOptionalString(body.level3Keywords, MAX_CONTENT_LENGTH, 'level3Keywords');
34
+ const directory = boundedOptionalString(body.directory, MAX_SHORT_FIELD_LENGTH, 'directory');
35
+ const day = boundedOptionalString(body.day, MAX_SHORT_FIELD_LENGTH, 'day');
36
+ const sessionId = boundedOptionalString(body.sessionId, MAX_SHORT_FIELD_LENGTH, 'sessionId');
37
+ const level1Summary = boundedOptionalString(body.level1Summary, MAX_CONTENT_LENGTH, 'level1Summary');
38
+ const level2Essential = boundedOptionalString(body.level2Essential, MAX_CONTENT_LENGTH, 'level2Essential');
39
+ const agentField = boundedOptionalString(body.agent, MAX_SHORT_FIELD_LENGTH, 'agent');
40
+ const agentHeader = boundedOptionalString(c.req.header('X-Humemory-Agent'), MAX_SHORT_FIELD_LENGTH, 'X-Humemory-Agent');
14
41
  try {
15
42
  const validTypes = ['episodic', 'semantic', 'procedural'];
16
43
  const memoryType = validTypes.includes(body.memoryType) ? body.memoryType : 'semantic';
17
44
  const memory = await store.add({
18
- content: body.content,
19
- directory: body.directory || process.cwd(),
20
- day: body.day || new Date().toISOString().split('T')[0],
21
- keywords: body.keywords || [],
22
- sessionId: body.sessionId || 'default',
23
- level1Summary: body.level1Summary,
24
- level2Essential: body.level2Essential,
25
- level3Keywords: body.level3Keywords,
45
+ content,
46
+ directory: directory || process.cwd(),
47
+ day: day || new Date().toISOString().split('T')[0],
48
+ keywords,
49
+ sessionId: sessionId || 'default',
50
+ level1Summary,
51
+ level2Essential,
52
+ level3Keywords,
26
53
  memoryType: memoryType,
27
54
  // Phase 6.0.1 — attribution on every write path
28
55
  source: body.source ?? 'agent',
29
- agent: c.req.header('X-Humemory-Agent') ?? body.agent ?? 'unknown',
56
+ agent: agentHeader ?? agentField ?? 'unknown',
30
57
  });
31
58
  return c.json({ success: true, memory }, 201);
32
59
  }
33
60
  catch (error) {
34
- return c.json({ success: false, error: String(error) }, 500);
61
+ return c.json(serverErrorBody(`${c.req.method} ${c.req.path}`, error), 500);
35
62
  }
36
63
  });
37
64
  app.get('/memories', async (c) => {
38
- const limit = parseInt(c.req.query('limit') || '50');
39
- const level = c.req.query('level');
40
- const memories = await store.list({
41
- limit,
42
- level: level !== undefined ? parseInt(level) : undefined,
65
+ const limit = boundedInt(c.req.query('limit'), {
66
+ fallback: 50,
67
+ min: 1,
68
+ max: MAX_RESULT_LIMIT,
69
+ name: 'limit',
43
70
  });
71
+ const level = boundedOptionalInt(c.req.query('level'), { min: 0, max: 4, name: 'level' });
72
+ const memories = await store.list({ limit, level: level });
44
73
  return c.json({ success: true, memories });
45
74
  });
46
75
  app.get('/memories/:id', async (c) => {
@@ -62,7 +91,7 @@ export function createMemoryRoutes(store) {
62
91
  return c.json({ success: true, memory });
63
92
  }
64
93
  catch (error) {
65
- return c.json({ success: false, error: String(error) }, 500);
94
+ return c.json(serverErrorBody(`${c.req.method} ${c.req.path}`, error), 500);
66
95
  }
67
96
  });
68
97
  // Phase 6.0.1 — trust layer
@@ -82,7 +111,7 @@ export function createMemoryRoutes(store) {
82
111
  return c.json({ success: true, memory });
83
112
  }
84
113
  catch (error) {
85
- return c.json({ success: false, error: String(error) }, 500);
114
+ return c.json(serverErrorBody(`${c.req.method} ${c.req.path}`, error), 500);
86
115
  }
87
116
  });
88
117
  // Phase 6.0.2 — contradiction: this trace wins against `otherId`
@@ -98,7 +127,7 @@ export function createMemoryRoutes(store) {
98
127
  return c.json({ success: true, ...result });
99
128
  }
100
129
  catch (error) {
101
- return c.json({ success: false, error: String(error) }, 500);
130
+ return c.json(serverErrorBody(`${c.req.method} ${c.req.path}`, error), 500);
102
131
  }
103
132
  });
104
133
  app.delete('/memories/:id', async (c) => {
@@ -111,17 +140,31 @@ export function createMemoryRoutes(store) {
111
140
  if (!query) {
112
141
  return c.json({ success: false, error: 'Missing query parameter "q"' }, 400);
113
142
  }
143
+ boundedString(query, MAX_QUERY_LENGTH, 'q');
114
144
  const dateFrom = c.req.query('dateFrom') ? new Date(c.req.query('dateFrom')) : undefined;
115
145
  const dateTo = c.req.query('dateTo') ? new Date(c.req.query('dateTo')) : undefined;
116
- const minSaillance = c.req.query('minSaillance') ? parseInt(c.req.query('minSaillance')) : undefined;
117
- const minRecalls = c.req.query('minRecalls') ? parseInt(c.req.query('minRecalls')) : undefined;
146
+ const minSaillance = boundedOptionalInt(c.req.query('minSaillance'), {
147
+ min: 0,
148
+ max: 100,
149
+ name: 'minSaillance',
150
+ });
151
+ const minRecalls = boundedOptionalInt(c.req.query('minRecalls'), {
152
+ min: 0,
153
+ max: 1_000_000,
154
+ name: 'minRecalls',
155
+ });
118
156
  const memoryType = c.req.query('type');
119
157
  const results = await store.search({
120
158
  query,
121
- directory: c.req.query('directory'),
122
- sessionId: c.req.query('sessionId'),
123
- maxLevel: parseInt(c.req.query('maxLevel') || '3'),
124
- limit: parseInt(c.req.query('limit') || '10'),
159
+ directory: boundedOptionalString(c.req.query('directory'), MAX_SHORT_FIELD_LENGTH, 'directory'),
160
+ sessionId: boundedOptionalString(c.req.query('sessionId'), MAX_SHORT_FIELD_LENGTH, 'sessionId'),
161
+ maxLevel: boundedInt(c.req.query('maxLevel'), { fallback: 3, min: 0, max: 4, name: 'maxLevel' }),
162
+ limit: boundedInt(c.req.query('limit'), {
163
+ fallback: 10,
164
+ min: 1,
165
+ max: MAX_RESULT_LIMIT,
166
+ name: 'limit',
167
+ }),
125
168
  memoryType,
126
169
  dateFrom,
127
170
  dateTo,
@@ -139,19 +182,29 @@ export function createMemoryRoutes(store) {
139
182
  return c.json({ success: true, memory });
140
183
  }
141
184
  catch (error) {
142
- return c.json({ success: false, error: String(error) }, 500);
185
+ return c.json(serverErrorBody(`${c.req.method} ${c.req.path}`, error), 500);
143
186
  }
144
187
  });
145
188
  // === SIMILAR ===
146
189
  app.get('/memories/:id/similar', async (c) => {
190
+ const limit = boundedInt(c.req.query('limit'), {
191
+ fallback: 5,
192
+ min: 1,
193
+ max: MAX_RESULT_LIMIT,
194
+ name: 'limit',
195
+ });
196
+ const threshold = boundedInt(c.req.query('threshold'), {
197
+ fallback: 50,
198
+ min: 0,
199
+ max: 100,
200
+ name: 'threshold',
201
+ });
147
202
  try {
148
- const limit = parseInt(c.req.query('limit') || '5');
149
- const threshold = parseInt(c.req.query('threshold') || '50');
150
203
  const results = await store.findSimilar(c.req.param('id'), { limit, threshold });
151
204
  return c.json({ success: true, results });
152
205
  }
153
206
  catch (error) {
154
- return c.json({ success: false, error: String(error) }, 500);
207
+ return c.json(serverErrorBody(`${c.req.method} ${c.req.path}`, error), 500);
155
208
  }
156
209
  });
157
210
  // === MERGE ===
@@ -167,7 +220,7 @@ export function createMemoryRoutes(store) {
167
220
  return c.json({ success: true, result });
168
221
  }
169
222
  catch (error) {
170
- return c.json({ success: false, error: String(error) }, 500);
223
+ return c.json(serverErrorBody(`${c.req.method} ${c.req.path}`, error), 500);
171
224
  }
172
225
  });
173
226
  // === DECAY ===
@@ -10,6 +10,8 @@
10
10
  */
11
11
  import { Hono } from 'hono';
12
12
  import { validateTriggerSpec } from './intentions-routes.js';
13
+ import { serverErrorBody } from './errors.js';
14
+ import { boundedString, MAX_CONTENT_LENGTH, MAX_SHORT_FIELD_LENGTH, MAX_COLLECTION_ITEMS, } from './limits.js';
13
15
  const SCRIPT_STATUSES = ['draft', 'active', 'archived'];
14
16
  /** Input validation error — surfaced as a 400 rather than a 500. */
15
17
  class BadRequest extends Error {
@@ -24,7 +26,12 @@ function serializeScript(script) {
24
26
  function validateSteps(raw) {
25
27
  if (!Array.isArray(raw) || !raw.length)
26
28
  throw new BadRequest('"steps" must be a non-empty array');
27
- const steps = raw.map((s) => (typeof s === 'string' ? s.trim() : ''));
29
+ // SECURITY_AUDIT.md M-02: a script could otherwise declare unlimited steps,
30
+ // each of unlimited length.
31
+ if (raw.length > MAX_COLLECTION_ITEMS) {
32
+ throw new BadRequest(`"steps" must hold at most ${MAX_COLLECTION_ITEMS} items`);
33
+ }
34
+ const steps = raw.map((s, i) => typeof s === 'string' ? boundedString(s, MAX_CONTENT_LENGTH, `steps[${i}]`).trim() : '');
28
35
  if (steps.some((s) => !s))
29
36
  throw new BadRequest('every step must be a non-empty string');
30
37
  return steps;
@@ -38,10 +45,11 @@ export function createScriptRoutes(store) {
38
45
  catch (err) {
39
46
  // validateTriggerSpec throws intentions-routes' own BadRequest class —
40
47
  // instanceof would miss it across module boundaries, so match by name.
41
- if (err instanceof Error && err.name === 'BadRequest') {
48
+ // LimitExceeded (SECURITY_AUDIT.md M-02) is the caller's error too.
49
+ if (err instanceof Error && (err.name === 'BadRequest' || err.name === 'LimitExceeded')) {
42
50
  return c.json({ error: err.message }, 400);
43
51
  }
44
- return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
52
+ return c.json(serverErrorBody(`${c.req.method} ${c.req.path}`, err), 500);
45
53
  }
46
54
  };
47
55
  /** Unambiguous prefix match — humans handle short ids, like dream review. */
@@ -64,15 +72,21 @@ export function createScriptRoutes(store) {
64
72
  if (typeof body.directory !== 'string' || !body.directory) {
65
73
  throw new BadRequest('"directory" is required');
66
74
  }
75
+ const name = boundedString(body.name, MAX_SHORT_FIELD_LENGTH, 'name');
76
+ const description = boundedString(body.description, MAX_CONTENT_LENGTH, 'description');
77
+ const directory = boundedString(body.directory, MAX_SHORT_FIELD_LENGTH, 'directory');
67
78
  const steps = validateSteps(body.steps);
79
+ if (Array.isArray(body.cues) && body.cues.length > MAX_COLLECTION_ITEMS) {
80
+ throw new BadRequest(`"cues" must hold at most ${MAX_COLLECTION_ITEMS} items`);
81
+ }
68
82
  const cues = Array.isArray(body.cues)
69
83
  ? body.cues.map((spec) => validateTriggerSpec(spec))
70
84
  : [];
71
85
  const script = await store.addScript({
72
- name: body.name.trim(),
73
- description: body.description.trim(),
86
+ name: name.trim(),
87
+ description: description.trim(),
74
88
  steps,
75
- directory: body.directory,
89
+ directory,
76
90
  pinned: body.pinned === true,
77
91
  // HTTP = agent claim → draft, always (8.3). No source override.
78
92
  source: 'agent',
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Browser defence headers (SECURITY_AUDIT.md M-04).
3
+ *
4
+ * These do not replace escaping the data — H-02 is fixed at the sink — but they
5
+ * cap the blast radius of any sink we missed and stop the dashboard being framed.
6
+ *
7
+ * Extracted from `server.ts` so the policy can be tested: importing `server.ts`
8
+ * constructs the store and would open the production database (BUG-08).
9
+ */
10
+ import { secureHeaders } from 'hono/secure-headers';
11
+ type SecureHeadersOptions = NonNullable<Parameters<typeof secureHeaders>[0]>;
12
+ export declare const SECURE_HEADERS_OPTIONS: SecureHeadersOptions;
13
+ /**
14
+ * Stamps the per-request CSP nonce onto the inline <script>/<style> tags of a
15
+ * static HTML page, so they run without weakening the policy to 'unsafe-inline'.
16
+ * A tag that already carries a nonce is left as it is.
17
+ */
18
+ export declare function injectNonce(html: string, nonce: string): string;
19
+ export {};
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Browser defence headers (SECURITY_AUDIT.md M-04).
3
+ *
4
+ * These do not replace escaping the data — H-02 is fixed at the sink — but they
5
+ * cap the blast radius of any sink we missed and stop the dashboard being framed.
6
+ *
7
+ * Extracted from `server.ts` so the policy can be tested: importing `server.ts`
8
+ * constructs the store and would open the production database (BUG-08).
9
+ */
10
+ import { NONCE } from 'hono/secure-headers';
11
+ export const SECURE_HEADERS_OPTIONS = {
12
+ contentSecurityPolicy: {
13
+ defaultSrc: ["'self'"],
14
+ baseUri: ["'self'"],
15
+ objectSrc: ["'none'"],
16
+ frameAncestors: ["'none'"],
17
+ formAction: ["'self'"],
18
+ // React/d3/three are bundled to /app/*.js; the only inline script is
19
+ // session.html's, which carries the nonce.
20
+ scriptSrc: [NONCE, "'self'"],
21
+ // style-src covers <style> blocks and stylesheets. Element.style writes from
22
+ // JS go through the CSSOM and are not affected by this directive; the
23
+ // `style="…"` attributes in session.html are, hence styleSrcAttr.
24
+ styleSrc: [NONCE, "'self'"],
25
+ styleSrcAttr: ["'unsafe-inline'"],
26
+ imgSrc: ["'self'", 'data:'],
27
+ fontSrc: ["'self'", 'data:'],
28
+ connectSrc: ["'self'"],
29
+ workerSrc: ["'self'", 'blob:'],
30
+ },
31
+ // The dashboard is served over plain HTTP on loopback by default; forcing
32
+ // HSTS there would poison the browser for every other localhost service.
33
+ strictTransportSecurity: false,
34
+ xFrameOptions: 'DENY',
35
+ xContentTypeOptions: 'nosniff',
36
+ referrerPolicy: 'no-referrer',
37
+ };
38
+ /**
39
+ * Stamps the per-request CSP nonce onto the inline <script>/<style> tags of a
40
+ * static HTML page, so they run without weakening the policy to 'unsafe-inline'.
41
+ * A tag that already carries a nonce is left as it is.
42
+ */
43
+ export function injectNonce(html, nonce) {
44
+ return html
45
+ .replace(/<script(?![^>]*\bnonce=)/g, `<script nonce="${nonce}"`)
46
+ .replace(/<style(?![^>]*\bnonce=)/g, `<style nonce="${nonce}"`);
47
+ }
@@ -29,5 +29,8 @@
29
29
  * POST /cues/resolve - Sweep: expire overdue loops, fire due deadlines
30
30
  */
31
31
  import { Hono } from 'hono';
32
- declare const app: Hono<import("hono/types").BlankEnv, import("hono/types").BlankSchema, "/">;
32
+ import type { SecureHeadersVariables } from 'hono/secure-headers';
33
+ declare const app: Hono<{
34
+ Variables: SecureHeadersVariables;
35
+ }, import("hono/types").BlankSchema, "/">;
33
36
  export { app };
@@ -30,6 +30,11 @@
30
30
  */
31
31
  import { Hono } from 'hono';
32
32
  import { cors } from 'hono/cors';
33
+ import { bodyLimit } from 'hono/body-limit';
34
+ import { secureHeaders } from 'hono/secure-headers';
35
+ import { MAX_BODY_BYTES } from './limits.js';
36
+ import { makeOriginChecker } from './cors.js';
37
+ import { SECURE_HEADERS_OPTIONS, injectNonce } from './security-headers.js';
33
38
  import { serve } from '@hono/node-server';
34
39
  import { SQLiteStore } from '../store/sqlite.js';
35
40
  import { createIntentionRoutes } from './intentions-routes.js';
@@ -39,6 +44,7 @@ import { createScriptRoutes } from './scripts-routes.js';
39
44
  import { join, dirname, resolve, sep } from 'path';
40
45
  import { fileURLToPath } from 'url';
41
46
  import { readFileSync } from 'fs';
47
+ import { timingSafeEqual } from 'crypto';
42
48
  const __filename = fileURLToPath(import.meta.url);
43
49
  const __dirname = dirname(__filename);
44
50
  /**
@@ -63,15 +69,49 @@ const allowedOrigins = process.env.NODE_ENV === 'production'
63
69
  ? (process.env.CORS_ORIGINS || 'http://localhost:3456').split(',')
64
70
  : ['http://localhost:3456', 'http://localhost:3000', 'http://127.0.0.1:3456'];
65
71
  const app = new Hono();
72
+ // Transport-level cap, ahead of any route (SECURITY_AUDIT.md M-02). The
73
+ // per-field caps in `limits.ts` are the business-level floor underneath it.
74
+ app.use('*', bodyLimit({
75
+ maxSize: MAX_BODY_BYTES,
76
+ onError: (c) => c.json({ success: false, error: 'Request body too large' }, 413),
77
+ }));
66
78
  app.use('*', cors({
67
- origin: (origin) => {
68
- if (!origin)
69
- return '*'; // Allow requests without origin (like mobile apps, curl, etc)
70
- return allowedOrigins.some(allowed => origin.includes(allowed.trim())) ? origin : undefined;
71
- },
79
+ origin: makeOriginChecker(allowedOrigins),
72
80
  credentials: true,
73
81
  maxAge: 600,
74
82
  }));
83
+ // === BROWSER DEFENCE HEADERS (SECURITY_AUDIT.md M-04) ===
84
+ // Policy and nonce stamping live in ./security-headers.ts so they stay testable.
85
+ app.use('*', secureHeaders(SECURE_HEADERS_OPTIONS));
86
+ // === AUTH (SECURITY_AUDIT.md H-01) ===
87
+ // HUMEMORY_API_TOKEN, when set, is required (Bearer or x-humemory-token) on every
88
+ // data/mutation route. Static dashboard assets and /health stay open so the front
89
+ // end can load; the front end then attaches the token to its own API calls.
90
+ const API_TOKEN = process.env.HUMEMORY_API_TOKEN;
91
+ const PUBLIC_PATHS = new Set(['/health']);
92
+ function isPublicPath(path) {
93
+ return PUBLIC_PATHS.has(path) || path === '/' || path === '/app' || path === '/session' || path.startsWith('/app/');
94
+ }
95
+ function tokenMatches(supplied, expected) {
96
+ if (!supplied)
97
+ return false;
98
+ const a = Buffer.from(supplied);
99
+ const b = Buffer.from(expected);
100
+ // Constant-time compare requires equal length; a length check alone leaks
101
+ // little (token lengths aren't secret), and avoids throwing on mismatch.
102
+ return a.length === b.length && timingSafeEqual(a, b);
103
+ }
104
+ app.use('*', async (c, next) => {
105
+ if (!API_TOKEN || isPublicPath(c.req.path))
106
+ return next();
107
+ const header = c.req.header('authorization');
108
+ const bearer = header?.startsWith('Bearer ') ? header.slice(7) : undefined;
109
+ const supplied = bearer ?? c.req.header('x-humemory-token');
110
+ if (!tokenMatches(supplied, API_TOKEN)) {
111
+ return c.json({ error: 'Unauthorized' }, 401);
112
+ }
113
+ return next();
114
+ });
75
115
  // Static files (dashboard)
76
116
  const APP_DIR = join(PUBLIC_DIR, 'app');
77
117
  /**
@@ -81,13 +121,13 @@ const APP_DIR = join(PUBLIC_DIR, 'app');
81
121
  * `/app/`, the browser resolves them against the root and finds nothing — so they
82
122
  * are absolutised to `/app/`.
83
123
  */
84
- function reactAppHtml() {
124
+ function reactAppHtml(nonce) {
85
125
  const html = readFileSync(join(APP_DIR, 'index.html'), 'utf-8');
86
- return html.replace(/(src|href)="\.\//g, '$1="/app/');
126
+ return injectNonce(html.replace(/(src|href)="\.\//g, '$1="/app/'), nonce);
87
127
  }
88
128
  app.get('/', (c) => {
89
129
  try {
90
- return c.html(reactAppHtml());
130
+ return c.html(reactAppHtml(c.get('secureHeadersNonce') ?? ''));
91
131
  }
92
132
  catch {
93
133
  // Missing bundle: say what to run rather than serve a dead page.
@@ -96,7 +136,7 @@ app.get('/', (c) => {
96
136
  });
97
137
  app.get('/session', (c) => {
98
138
  const html = readFileSync(join(PUBLIC_DIR, 'session.html'), 'utf-8');
99
- return c.html(html);
139
+ return c.html(injectNonce(html, c.get('secureHeadersNonce') ?? ''));
100
140
  });
101
141
  // React front end (web/ → public/app/ through `pnpm build:web`), served at / and /app.
102
142
  const APP_MIME = {
@@ -110,7 +150,7 @@ const APP_MIME = {
110
150
  };
111
151
  app.get('/app', (c) => {
112
152
  try {
113
- return c.html(reactAppHtml());
153
+ return c.html(reactAppHtml(c.get('secureHeadersNonce') ?? ''));
114
154
  }
115
155
  catch {
116
156
  // Missing bundle: say what to run rather than a silent 404.
@@ -151,7 +191,20 @@ export { app };
151
191
  // raise a server or seize the port.
152
192
  if (import.meta.main) {
153
193
  const port = parseInt(process.env.PORT || '3456');
154
- console.log(`🧠 humemory API running on http://localhost:${port}`);
155
- console.log(`📊 Dashboard: http://localhost:${port}/`);
156
- serve({ fetch: app.fetch, port });
194
+ // Default loopback-only (SECURITY_AUDIT.md H-01): the previous code passed no
195
+ // hostname, which node-server forwards straight to server.listen(), binding
196
+ // every interface while the log line still claimed "localhost".
197
+ const hostname = process.env.HUMEMORY_HOST || '127.0.0.1';
198
+ const isLoopback = hostname === '127.0.0.1' || hostname === 'localhost' || hostname === '::1';
199
+ if (!isLoopback && !API_TOKEN) {
200
+ console.error(`Refusing to start: HUMEMORY_HOST=${hostname} exposes the API beyond loopback ` +
201
+ `without HUMEMORY_API_TOKEN set. Set a token or unset HUMEMORY_HOST.`);
202
+ process.exit(1);
203
+ }
204
+ console.log(`🧠 humemory API running on http://${hostname}:${port}`);
205
+ console.log(`📊 Dashboard: http://${hostname}:${port}/`);
206
+ if (!API_TOKEN) {
207
+ console.warn('⚠️ HUMEMORY_API_TOKEN not set — data routes are unauthenticated (loopback only).');
208
+ }
209
+ serve({ fetch: app.fetch, port, hostname });
157
210
  }
@@ -63,6 +63,22 @@ export declare function cronMatches(parsed: ParsedCron, date: Date): boolean;
63
63
  export declare const CRON_CATCHUP_MINUTES: number;
64
64
  /** True when a cron occurrence exists in the half-open interval (since, now]. */
65
65
  export declare function cronDueSince(expr: string, since: Date, now: Date): boolean;
66
+ /**
67
+ * Hard caps on regex evaluation (SECURITY_AUDIT.md M-01). The pattern and the
68
+ * event text both come from unauthenticated callers, and the native RegExp engine
69
+ * backtracks: `^(a+)+$` against a long non-matching string pins the event loop.
70
+ * The engine cannot be given a deadline, so the inputs are bounded instead and
71
+ * the shapes that make catastrophic backtracking possible are refused outright.
72
+ */
73
+ export declare const MAX_PATTERN_LENGTH = 200;
74
+ export declare const MAX_MATCH_TEXT_LENGTH = 10000;
75
+ /**
76
+ * Detects a quantifier applied to a group that itself contains a quantifier —
77
+ * the `(a+)+` / `(a*)*` / `(a+|b)*` family behind exponential backtracking.
78
+ * Conservative: it can reject a benign pattern, which only costs a fallback to
79
+ * literal search, never a hang.
80
+ */
81
+ export declare function isDangerousPattern(pattern: string): boolean;
66
82
  /** True when this event trigger matches this event. */
67
83
  export declare function eventTriggerMatches(spec: EventTriggerSpec, event: AppEvent): boolean;
68
84
  /** Length of the UUID prefix used as a readable loop identifier. */
package/dist/core/cues.js CHANGED
@@ -144,13 +144,66 @@ function directoryMatches(intentionDir, eventDir) {
144
144
  const b = normalizePath(eventDir).replace(/\/$/, '');
145
145
  return b === a || b.startsWith(`${a}/`) || a.startsWith(`${b}/`);
146
146
  }
147
- /** Tests an error pattern. An invalid regex falls back to a literal search. */
147
+ /**
148
+ * Hard caps on regex evaluation (SECURITY_AUDIT.md M-01). The pattern and the
149
+ * event text both come from unauthenticated callers, and the native RegExp engine
150
+ * backtracks: `^(a+)+$` against a long non-matching string pins the event loop.
151
+ * The engine cannot be given a deadline, so the inputs are bounded instead and
152
+ * the shapes that make catastrophic backtracking possible are refused outright.
153
+ */
154
+ export const MAX_PATTERN_LENGTH = 200;
155
+ export const MAX_MATCH_TEXT_LENGTH = 10_000;
156
+ /**
157
+ * Detects a quantifier applied to a group that itself contains a quantifier —
158
+ * the `(a+)+` / `(a*)*` / `(a+|b)*` family behind exponential backtracking.
159
+ * Conservative: it can reject a benign pattern, which only costs a fallback to
160
+ * literal search, never a hang.
161
+ */
162
+ export function isDangerousPattern(pattern) {
163
+ if (pattern.length > MAX_PATTERN_LENGTH)
164
+ return true;
165
+ // Walk the groups, tracking whether each holds an unescaped quantifier, and
166
+ // flag any group that is itself quantified on close.
167
+ const stack = [];
168
+ for (let i = 0; i < pattern.length; i++) {
169
+ const ch = pattern[i];
170
+ if (ch === '\\') {
171
+ i++; // escaped char: never a quantifier or a group delimiter
172
+ continue;
173
+ }
174
+ if (ch === '(') {
175
+ stack.push(false);
176
+ continue;
177
+ }
178
+ if (ch === ')') {
179
+ const innerHadQuantifier = stack.pop() ?? false;
180
+ const next = pattern[i + 1];
181
+ const outerQuantified = next === '+' || next === '*' || next === '{';
182
+ if (innerHadQuantifier && outerQuantified)
183
+ return true;
184
+ continue;
185
+ }
186
+ if (ch === '+' || ch === '*' || ch === '{') {
187
+ if (stack.length > 0)
188
+ stack[stack.length - 1] = true;
189
+ }
190
+ }
191
+ return false;
192
+ }
193
+ /**
194
+ * Tests an error pattern. A pattern that is invalid, oversized or shaped for
195
+ * catastrophic backtracking falls back to a literal, non-backtracking search.
196
+ */
148
197
  function errorPatternMatches(pattern, text) {
198
+ const bounded = text.length > MAX_MATCH_TEXT_LENGTH ? text.slice(0, MAX_MATCH_TEXT_LENGTH) : text;
199
+ if (isDangerousPattern(pattern)) {
200
+ return bounded.toLowerCase().includes(pattern.toLowerCase());
201
+ }
149
202
  try {
150
- return new RegExp(pattern, 'i').test(text);
203
+ return new RegExp(pattern, 'i').test(bounded);
151
204
  }
152
205
  catch {
153
- return text.toLowerCase().includes(pattern.toLowerCase());
206
+ return bounded.toLowerCase().includes(pattern.toLowerCase());
154
207
  }
155
208
  }
156
209
  /** True when this event trigger matches this event. */
@@ -24,7 +24,7 @@ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
24
24
  import { z } from 'zod';
25
25
  import { SQLiteStore } from '../store/sqlite.js';
26
26
  import { trustScore } from '../core/trust.js';
27
- import { sanitizeTrace } from '../core/sanitize.js';
27
+ import { sanitizeTrace, wrapUntrusted } from '../core/sanitize.js';
28
28
  const store = new SQLiteStore(process.env.HUMEMORY_DB);
29
29
  /**
30
30
  * This process's agent identity. Not overridable per call — see the header.
@@ -120,7 +120,11 @@ server.registerTool('humemory_intent_add', {
120
120
  source: 'agent',
121
121
  agent: callingAgent,
122
122
  }, cues);
123
- return { content: [{ type: 'text', text: `loop armed: ${i.id}\n${i.content}` }] };
123
+ // Echoes the caller's own content back into the tool result, which lands
124
+ // in the agent's context like any other tool output — sanitized the same
125
+ // way a recalled trace would be (SECURITY_AUDIT.md H-03).
126
+ const s = sanitizeTrace(i.content);
127
+ return { content: [{ type: 'text', text: `loop armed: ${i.id}\n${s.text}` }] };
124
128
  });
125
129
  server.registerTool('humemory_intent_close', {
126
130
  description: 'Close an open loop by id (or short loop-XXXX id)',
@@ -144,12 +148,18 @@ server.registerTool('humemory_dreams', {
144
148
  const pending = await store.listDreamProposals({ status: 'pending' });
145
149
  if (!pending.length)
146
150
  return { content: [{ type: 'text', text: 'no dream pending' }] };
151
+ // Dream proposals are synthesized cross-session patterns, never
152
+ // human-verified at this stage — wrapped like any other unverified
153
+ // recalled content (SECURITY_AUDIT.md H-03), not returned raw.
147
154
  return {
148
155
  content: [
149
156
  {
150
157
  type: 'text',
151
158
  text: pending
152
- .map((p) => `[${p.kind}] ${p.id} — confidence ${p.confidence}\n${p.payload.slice(0, 400)}`)
159
+ .map((p) => {
160
+ const s = sanitizeTrace(p.payload.slice(0, 400));
161
+ return `[${p.kind}] ${p.id} — confidence ${p.confidence}\n${wrapUntrusted(s.text, { id: p.id })}`;
162
+ })
153
163
  .join('\n---\n'),
154
164
  },
155
165
  ],
@@ -1276,6 +1276,7 @@ export class SQLiteStore {
1276
1276
  source: intention.source ?? 'agent',
1277
1277
  agent: intention.agent,
1278
1278
  verified: intention.verified ?? false,
1279
+ verificationReason: intention.verificationReason,
1279
1280
  device: intention.device ?? this.deviceId,
1280
1281
  };
1281
1282
  await this.enqueueWriteWithLock(async () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "humemory",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "description": "Memory for AI agents that forgets like a human — decaying traces, inverse search, and prospective loops that resurface on a cue",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -52,13 +52,13 @@
52
52
  },
53
53
  "dependencies": {
54
54
  "@anthropic-ai/sdk": "^0.92.0",
55
- "@hono/node-server": "^2.0.0",
55
+ "@hono/node-server": "^2.1.1",
56
56
  "@huggingface/transformers": "^4.2.0",
57
57
  "@modelcontextprotocol/sdk": "^1.30.0",
58
58
  "commander": "^12.0.0",
59
59
  "d3": "^7.9.0",
60
60
  "flexsearch": "^0.7.43",
61
- "hono": "^4.0.0",
61
+ "hono": "^4.13.2",
62
62
  "react": "^19.2.8",
63
63
  "react-dom": "^19.2.8",
64
64
  "three": "^0.184.0",
@@ -66,6 +66,7 @@
66
66
  },
67
67
  "devDependencies": {
68
68
  "@happy-dom/global-registrator": "^20.11.1",
69
+ "@medyll/idae-pnpm-release": "1.0.46",
69
70
  "@testing-library/dom": "^10.4.1",
70
71
  "@testing-library/react": "^16.3.2",
71
72
  "@types/d3": "^7.4.3",
@@ -74,8 +75,8 @@
74
75
  "@types/react-dom": "^19.2.4",
75
76
  "@types/three": "^0.185.3",
76
77
  "bun-types": "^1.3.13",
77
- "js-yaml": "^5.1.0",
78
- "tsx": "^4.7.0",
78
+ "js-yaml": "^5.3.0",
79
+ "tsx": "^4.23.12",
79
80
  "typescript": "^5.4.0"
80
81
  },
81
82
  "scripts": {