humemory 0.2.3 → 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';
@@ -64,15 +69,20 @@ const allowedOrigins = process.env.NODE_ENV === 'production'
64
69
  ? (process.env.CORS_ORIGINS || 'http://localhost:3456').split(',')
65
70
  : ['http://localhost:3456', 'http://localhost:3000', 'http://127.0.0.1:3456'];
66
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
+ }));
67
78
  app.use('*', cors({
68
- origin: (origin) => {
69
- if (!origin)
70
- return '*'; // Allow requests without origin (like mobile apps, curl, etc)
71
- return allowedOrigins.some(allowed => origin.includes(allowed.trim())) ? origin : undefined;
72
- },
79
+ origin: makeOriginChecker(allowedOrigins),
73
80
  credentials: true,
74
81
  maxAge: 600,
75
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));
76
86
  // === AUTH (SECURITY_AUDIT.md H-01) ===
77
87
  // HUMEMORY_API_TOKEN, when set, is required (Bearer or x-humemory-token) on every
78
88
  // data/mutation route. Static dashboard assets and /health stay open so the front
@@ -111,13 +121,13 @@ const APP_DIR = join(PUBLIC_DIR, 'app');
111
121
  * `/app/`, the browser resolves them against the root and finds nothing — so they
112
122
  * are absolutised to `/app/`.
113
123
  */
114
- function reactAppHtml() {
124
+ function reactAppHtml(nonce) {
115
125
  const html = readFileSync(join(APP_DIR, 'index.html'), 'utf-8');
116
- return html.replace(/(src|href)="\.\//g, '$1="/app/');
126
+ return injectNonce(html.replace(/(src|href)="\.\//g, '$1="/app/'), nonce);
117
127
  }
118
128
  app.get('/', (c) => {
119
129
  try {
120
- return c.html(reactAppHtml());
130
+ return c.html(reactAppHtml(c.get('secureHeadersNonce') ?? ''));
121
131
  }
122
132
  catch {
123
133
  // Missing bundle: say what to run rather than serve a dead page.
@@ -126,7 +136,7 @@ app.get('/', (c) => {
126
136
  });
127
137
  app.get('/session', (c) => {
128
138
  const html = readFileSync(join(PUBLIC_DIR, 'session.html'), 'utf-8');
129
- return c.html(html);
139
+ return c.html(injectNonce(html, c.get('secureHeadersNonce') ?? ''));
130
140
  });
131
141
  // React front end (web/ → public/app/ through `pnpm build:web`), served at / and /app.
132
142
  const APP_MIME = {
@@ -140,7 +150,7 @@ const APP_MIME = {
140
150
  };
141
151
  app.get('/app', (c) => {
142
152
  try {
143
- return c.html(reactAppHtml());
153
+ return c.html(reactAppHtml(c.get('secureHeadersNonce') ?? ''));
144
154
  }
145
155
  catch {
146
156
  // Missing bundle: say what to run rather than a silent 404.
@@ -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. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "humemory",
3
- "version": "0.2.3",
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",
@@ -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",