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.
- package/AGENTS.md +1 -1
- package/CHANGELOG.md +25 -0
- package/README.md +41 -4
- package/dist/agent/session-context.js +21 -4
- package/dist/api/cors.d.ts +21 -0
- package/dist/api/cors.js +39 -0
- package/dist/api/dream-routes.js +2 -1
- package/dist/api/errors.d.ts +22 -0
- package/dist/api/errors.js +34 -0
- package/dist/api/intentions-routes.js +27 -6
- package/dist/api/limits.d.ts +58 -0
- package/dist/api/limits.js +80 -0
- package/dist/api/memory-routes.js +82 -29
- package/dist/api/scripts-routes.js +20 -6
- package/dist/api/security-headers.d.ts +19 -0
- package/dist/api/security-headers.js +47 -0
- package/dist/api/server.d.ts +4 -1
- package/dist/api/server.js +66 -13
- package/dist/core/cues.d.ts +16 -0
- package/dist/core/cues.js +56 -3
- package/dist/mcp/server.js +13 -3
- package/dist/store/sqlite.js +1 -0
- package/package.json +6 -5
- package/public/app/{galaxy-f42190mq.js → galaxy-cgbkc6e1.js} +1 -1
- package/public/app/index-5kwkpwkp.js +2 -0
- package/public/app/index-95ffty7j.js +12 -0
- package/public/app/index-kv9v6ty0.css +1 -0
- package/public/app/index.html +1 -1
- package/public/app/{promenade-cnzzpm73.js → promenade-fa0tb6jx.js} +1 -1
- package/public/app/river-01hs4f06.js +5 -0
- package/public/app/index-2cf31xxn.css +0 -1
- package/public/app/index-f9h80bzq.js +0 -12
- package/public/app/index-kvhc17mz.js +0 -2
- package/public/app/river-tyawhh8w.js +0 -13
package/AGENTS.md
CHANGED
|
@@ -322,7 +322,7 @@ accepts a script id as the loser. API: `POST/GET /scripts`,
|
|
|
322
322
|
`tests/helpers/fixtures.ts` shipped with S5-00b. New Phase 6/7/8 suites still lean on inline
|
|
323
323
|
literals for scenario-specific content (fine per [docs/TESTING.md](./docs/TESTING.md)'s own
|
|
324
324
|
rule — a fixture is for shared corpora, not a one-off case a test is *about*).
|
|
325
|
-
-
|
|
325
|
+
- ~~`vitest.config.ts` orphaned~~ — closed: the file is gone, the suite runs under `bun test`.
|
|
326
326
|
- `tsc` global can shadow local — `pnpm build` is `tsc -p tsconfig.json`.
|
|
327
327
|
|
|
328
328
|
## 📝 Notes
|
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,30 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.2.4] - 2026-08-23
|
|
4
|
+
**Bug Fixes:**
|
|
5
|
+
- stop returning internal error detail to clients (L-01)
|
|
6
|
+
- exact-match CORS origins and add browser defence headers (M-04)
|
|
7
|
+
- bound request bodies, collections and cost parameters (M-02)
|
|
8
|
+
- bound error_pattern regex evaluation (M-01)
|
|
9
|
+
|
|
10
|
+
**Documentation:**
|
|
11
|
+
- document the API security config and correct stale status claims
|
|
12
|
+
- record the remediation status in the security audit
|
|
13
|
+
|
|
14
|
+
**Tests:**
|
|
15
|
+
- cover the full audit attack chain end to end
|
|
16
|
+
|
|
17
|
+
**CI/CD:**
|
|
18
|
+
- pin the release chain and drop unused permission (M-03)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
## [0.2.3] - 2026-08-17
|
|
23
|
+
**Features:**
|
|
24
|
+
- add Streamable HTTP transport and security hardening
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
|
|
3
28
|
## [0.2.2] - 2026-08-15
|
|
4
29
|
**Features:**
|
|
5
30
|
- add async multi-agent session capture
|
package/README.md
CHANGED
|
@@ -16,7 +16,8 @@ not when you run a full-text search for "milk".
|
|
|
16
16
|
|
|
17
17
|
## Two halves of a brain
|
|
18
18
|
|
|
19
|
-
humemory is built in two halves. The first
|
|
19
|
+
humemory is built in two halves. The first was shipped first; the second is what it
|
|
20
|
+
was always for. Both are built as of Phase 8.
|
|
20
21
|
|
|
21
22
|
### 1. Retrospective memory — *what was learned* ✅ built
|
|
22
23
|
|
|
@@ -40,7 +41,7 @@ construction.
|
|
|
40
41
|
A Claude Code `Stop` hook can queue each completed session instantly; maintenance
|
|
41
42
|
extracts and stores its learnings afterward, outside the agent's critical path.
|
|
42
43
|
|
|
43
|
-
### 2. Prospective memory — *what to resurface*
|
|
44
|
+
### 2. Prospective memory — *what to resurface* ✅ built
|
|
44
45
|
|
|
45
46
|
The second half (see `AGENTS.md` → Phase 5) is what gives humemory its life:
|
|
46
47
|
|
|
@@ -220,6 +221,41 @@ The queue directory is the whole contract, and it is inspectable at any time:
|
|
|
220
221
|
|
|
221
222
|
---
|
|
222
223
|
|
|
224
|
+
## Serving the API safely
|
|
225
|
+
|
|
226
|
+
The database holds every learning trace and open loop across all your projects,
|
|
227
|
+
and the API can read, alter and delete all of it. Treat the port as sensitive.
|
|
228
|
+
|
|
229
|
+
| Env var | Default | Effect |
|
|
230
|
+
| --- | --- | --- |
|
|
231
|
+
| `PORT` | `3456` | API/dashboard port |
|
|
232
|
+
| `HUMEMORY_HOST` | `127.0.0.1` | listen address — **loopback only unless you change it** |
|
|
233
|
+
| `HUMEMORY_API_TOKEN` | unset | when set, required on every data route (`Authorization: Bearer …` or `X-Humemory-Token`) |
|
|
234
|
+
| `CORS_ORIGINS` | `http://localhost:3456` | comma-separated exact origins, honoured when `NODE_ENV=production` |
|
|
235
|
+
| `HUMEMORY_VERBOSE_ERRORS` | unset | `1` returns real error messages instead of a correlation id — local debugging only |
|
|
236
|
+
|
|
237
|
+
**Defaults are private.** The server binds `127.0.0.1`, so nothing on your network
|
|
238
|
+
can reach it. Without `HUMEMORY_API_TOKEN` it starts anyway and warns, because on
|
|
239
|
+
loopback the OS is the boundary.
|
|
240
|
+
|
|
241
|
+
**Exposing it is deliberate.** Setting `HUMEMORY_HOST` to anything but loopback
|
|
242
|
+
*without* a token makes the server refuse to start rather than quietly publish your
|
|
243
|
+
memory to the LAN:
|
|
244
|
+
|
|
245
|
+
```bash
|
|
246
|
+
HUMEMORY_HOST=0.0.0.0 HUMEMORY_API_TOKEN="$(openssl rand -hex 32)" pnpm start:api
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
The dashboard asks for that token behind the 🔑 button in its header and keeps it
|
|
250
|
+
in `localStorage`. `/health` and the static assets stay open so a probe and the
|
|
251
|
+
page itself still load.
|
|
252
|
+
|
|
253
|
+
A token is not a substitute for the network layer: over anything but loopback, put
|
|
254
|
+
TLS and a firewall in front of it. The token travels in a header, in clear, over
|
|
255
|
+
plain HTTP.
|
|
256
|
+
|
|
257
|
+
---
|
|
258
|
+
|
|
223
259
|
## Why it exists
|
|
224
260
|
|
|
225
261
|
A log remembers everything and reminds you of nothing. A human memory forgets most
|
|
@@ -564,8 +600,9 @@ keywords >5. `photographic: true` disables decay entirely.
|
|
|
564
600
|
|
|
565
601
|
## Known issues
|
|
566
602
|
- ~~SQLite multi-process: advisory lock~~ — fixed in Sprint 5 (S5-00a): WAL + write-queue (Sprint 4) plus file-based cross-process `AdvisoryLock`.
|
|
567
|
-
-
|
|
568
|
-
|
|
603
|
+
- ~~`tests/fixtures/` missing~~ — closed (S5-00b): `tests/fixtures/*.json` + `tests/helpers/fixtures.ts`.
|
|
604
|
+
Shared corpora live there; a one-off case a test is specifically *about* stays inline.
|
|
605
|
+
- ~~`vitest.config.ts` orphaned~~ — closed: the file is gone, the suite runs under `bun test`.
|
|
569
606
|
- `tsc` global can shadow local — `pnpm build` is `tsc -p tsconfig.json`.
|
|
570
607
|
|
|
571
608
|
## Notes
|
|
@@ -154,10 +154,12 @@ function renderMarkdown(input) {
|
|
|
154
154
|
// per-step id of its own.
|
|
155
155
|
if (desc.escapedMarkers > 0)
|
|
156
156
|
escapeAttempts.push({ memoryId: script.id, count: desc.escapedMarkers });
|
|
157
|
-
lines.push(`> ${oneLine(desc.text)}`);
|
|
158
157
|
// Same injection rules as traces (6.0.3): human-authored renders bare,
|
|
159
|
-
// agent/dreamer-authored stays wrapped.
|
|
158
|
+
// agent/dreamer-authored stays wrapped. The description used to render
|
|
159
|
+
// bare unconditionally while the steps below were correctly gated
|
|
160
|
+
// (SECURITY_AUDIT.md H-03) — both now share the same `bare` check.
|
|
160
161
|
const bare = script.source === 'human';
|
|
162
|
+
lines.push(`> ${bare ? oneLine(desc.text) : wrapUntrusted(oneLine(desc.text), { source: script.source, agent: script.agent, id: script.id })}`);
|
|
161
163
|
script.steps.slice(0, SCRIPT_STEP_CAP).forEach((step, i) => {
|
|
162
164
|
const s = sanitizeTrace(step);
|
|
163
165
|
if (s.escapedMarkers > 0)
|
|
@@ -171,11 +173,24 @@ function renderMarkdown(input) {
|
|
|
171
173
|
lines.push(`_… ${script.steps.length - SCRIPT_STEP_CAP} more steps — \`pnpm cli script fire ${script.id.slice(0, 8)}\` for the full drill._`);
|
|
172
174
|
}
|
|
173
175
|
}
|
|
176
|
+
// Intentions carry the same provenance shape as memories (6.0.1) but used to
|
|
177
|
+
// render bare unconditionally regardless of it (SECURITY_AUDIT.md H-03).
|
|
178
|
+
// Only a human-verified loop skips the untrusted wrapper now.
|
|
179
|
+
const renderIntentionBody = (i, s) => {
|
|
180
|
+
const bare = i.verified === true && i.verificationReason === 'human';
|
|
181
|
+
return bare
|
|
182
|
+
? oneLine(s.text)
|
|
183
|
+
: wrapUntrusted(oneLine(s.text), { source: i.source, agent: i.agent, verified: i.verified, id: i.id });
|
|
184
|
+
};
|
|
174
185
|
if (firedNow.length) {
|
|
175
186
|
lines.push('', '### ⏰ Deadlines reached', RECALLED_NOTES_PREFACE);
|
|
176
187
|
for (const i of firedNow) {
|
|
177
188
|
const s = sanitizeTrace(i.content);
|
|
178
|
-
|
|
189
|
+
// Same reporting as scripts and traces: the content was already
|
|
190
|
+
// neutralised, but a swallowed count hides the attempt from the operator.
|
|
191
|
+
if (s.escapedMarkers > 0)
|
|
192
|
+
escapeAttempts.push({ memoryId: i.id, count: s.escapedMarkers });
|
|
193
|
+
lines.push(`- **[${loopId(i.id)}]** ${renderIntentionBody(i, s)}`);
|
|
179
194
|
}
|
|
180
195
|
}
|
|
181
196
|
if (openLoops.length) {
|
|
@@ -186,7 +201,9 @@ function renderMarkdown(input) {
|
|
|
186
201
|
? ` — due in ${humanizeAge(now, i.expiresAt).replace(' ago', '')}`
|
|
187
202
|
: '';
|
|
188
203
|
const s = sanitizeTrace(i.content);
|
|
189
|
-
|
|
204
|
+
if (s.escapedMarkers > 0)
|
|
205
|
+
escapeAttempts.push({ memoryId: i.id, count: s.escapedMarkers });
|
|
206
|
+
lines.push(`- **[${loopId(i.id)}]** ${renderIntentionBody(i, s)} (armed ${age}${deadline})`);
|
|
190
207
|
}
|
|
191
208
|
lines.push('', `_To close a loop: mention \`Closes ${loopId(openLoops[0].id)}\` in a commit message._`);
|
|
192
209
|
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CORS origin allow-list (SECURITY_AUDIT.md M-04).
|
|
3
|
+
*
|
|
4
|
+
* Extracted from `server.ts` for the same reason as the route modules: importing
|
|
5
|
+
* `server.ts` constructs the store and would open the production database, so
|
|
6
|
+
* anything that needs testing lives outside it (BUG-08).
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* Normalises an origin to its canonical `scheme://host[:port]` form, or null if
|
|
10
|
+
* it is not a parseable absolute URL.
|
|
11
|
+
*/
|
|
12
|
+
export declare function normalizeOrigin(value: string): string | null;
|
|
13
|
+
/**
|
|
14
|
+
* Builds an exact-match origin checker for hono's `cors({ origin })`.
|
|
15
|
+
*
|
|
16
|
+
* The previous check was `origin.includes(allowed)`, a substring test: with a
|
|
17
|
+
* custom CORS_ORIGINS entry, `http://localhost:3456.evil.example` contains the
|
|
18
|
+
* allowed value and passed. Both sides are now parsed and compared as whole
|
|
19
|
+
* origins, and anything unparseable is refused.
|
|
20
|
+
*/
|
|
21
|
+
export declare function makeOriginChecker(allowed: string[]): (origin: string) => string | undefined;
|
package/dist/api/cors.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CORS origin allow-list (SECURITY_AUDIT.md M-04).
|
|
3
|
+
*
|
|
4
|
+
* Extracted from `server.ts` for the same reason as the route modules: importing
|
|
5
|
+
* `server.ts` constructs the store and would open the production database, so
|
|
6
|
+
* anything that needs testing lives outside it (BUG-08).
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* Normalises an origin to its canonical `scheme://host[:port]` form, or null if
|
|
10
|
+
* it is not a parseable absolute URL.
|
|
11
|
+
*/
|
|
12
|
+
export function normalizeOrigin(value) {
|
|
13
|
+
try {
|
|
14
|
+
return new URL(value.trim()).origin;
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Builds an exact-match origin checker for hono's `cors({ origin })`.
|
|
22
|
+
*
|
|
23
|
+
* The previous check was `origin.includes(allowed)`, a substring test: with a
|
|
24
|
+
* custom CORS_ORIGINS entry, `http://localhost:3456.evil.example` contains the
|
|
25
|
+
* allowed value and passed. Both sides are now parsed and compared as whole
|
|
26
|
+
* origins, and anything unparseable is refused.
|
|
27
|
+
*/
|
|
28
|
+
export function makeOriginChecker(allowed) {
|
|
29
|
+
const normalized = new Set(allowed.map((a) => normalizeOrigin(a)).filter((a) => a !== null));
|
|
30
|
+
return (origin) => {
|
|
31
|
+
// No Origin header (curl, a native client): CORS does not apply, and
|
|
32
|
+
// answering `*` alongside `credentials: true` is a combination browsers
|
|
33
|
+
// reject anyway. Send no allow-origin at all.
|
|
34
|
+
if (!origin)
|
|
35
|
+
return undefined;
|
|
36
|
+
const candidate = normalizeOrigin(origin);
|
|
37
|
+
return candidate && normalized.has(candidate) ? candidate : undefined;
|
|
38
|
+
};
|
|
39
|
+
}
|
package/dist/api/dream-routes.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
*/
|
|
5
5
|
import { Hono } from 'hono';
|
|
6
6
|
import { runDreamer, applyDreamProposal } from '../core/dreamer.js';
|
|
7
|
+
import { serverErrorBody } from './errors.js';
|
|
7
8
|
export function createDreamRoutes(store) {
|
|
8
9
|
const app = new Hono();
|
|
9
10
|
app.get('/dreams', async (c) => {
|
|
@@ -32,7 +33,7 @@ export function createDreamRoutes(store) {
|
|
|
32
33
|
return c.json({ success: true, proposal });
|
|
33
34
|
}
|
|
34
35
|
catch (error) {
|
|
35
|
-
return c.json({
|
|
36
|
+
return c.json(serverErrorBody(`${c.req.method} ${c.req.path}`, error), 500);
|
|
36
37
|
}
|
|
37
38
|
});
|
|
38
39
|
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Uniform server-error responses (SECURITY_AUDIT.md L-01).
|
|
3
|
+
*
|
|
4
|
+
* Handlers used to return `String(error)` to the caller, so a SQLite message
|
|
5
|
+
* could hand out the schema, a constraint name or an absolute local path — free
|
|
6
|
+
* reconnaissance on an API that is meant to be reachable only from loopback but
|
|
7
|
+
* may be exposed deliberately. The full error is now logged server-side under a
|
|
8
|
+
* correlation id, and the client gets that id and nothing else.
|
|
9
|
+
*/
|
|
10
|
+
/** Body returned for any unexpected failure. */
|
|
11
|
+
export interface ServerErrorBody {
|
|
12
|
+
success: false;
|
|
13
|
+
error: string;
|
|
14
|
+
errorId: string;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Logs `error` with a fresh correlation id and builds the client-facing body.
|
|
18
|
+
*
|
|
19
|
+
* `context` should say which operation failed (e.g. `POST /memories`) so the log
|
|
20
|
+
* line is useful without the request body.
|
|
21
|
+
*/
|
|
22
|
+
export declare function serverErrorBody(context: string, error: unknown): ServerErrorBody;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Uniform server-error responses (SECURITY_AUDIT.md L-01).
|
|
3
|
+
*
|
|
4
|
+
* Handlers used to return `String(error)` to the caller, so a SQLite message
|
|
5
|
+
* could hand out the schema, a constraint name or an absolute local path — free
|
|
6
|
+
* reconnaissance on an API that is meant to be reachable only from loopback but
|
|
7
|
+
* may be exposed deliberately. The full error is now logged server-side under a
|
|
8
|
+
* correlation id, and the client gets that id and nothing else.
|
|
9
|
+
*/
|
|
10
|
+
import { randomUUID } from 'crypto';
|
|
11
|
+
/**
|
|
12
|
+
* Set HUMEMORY_VERBOSE_ERRORS=1 to echo the real message back to the caller.
|
|
13
|
+
* Intended for local debugging only — it re-enables exactly the disclosure this
|
|
14
|
+
* module exists to prevent, so it is opt-in and never the default.
|
|
15
|
+
*/
|
|
16
|
+
function verboseErrors() {
|
|
17
|
+
return process.env.HUMEMORY_VERBOSE_ERRORS === '1';
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Logs `error` with a fresh correlation id and builds the client-facing body.
|
|
21
|
+
*
|
|
22
|
+
* `context` should say which operation failed (e.g. `POST /memories`) so the log
|
|
23
|
+
* line is useful without the request body.
|
|
24
|
+
*/
|
|
25
|
+
export function serverErrorBody(context, error) {
|
|
26
|
+
const errorId = randomUUID();
|
|
27
|
+
// Full detail stays here, on the server, where it is useful and not exposed.
|
|
28
|
+
console.error(`[${errorId}] ${context}:`, error);
|
|
29
|
+
return {
|
|
30
|
+
success: false,
|
|
31
|
+
error: verboseErrors() && error instanceof Error ? error.message : 'Internal server error',
|
|
32
|
+
errorId,
|
|
33
|
+
};
|
|
34
|
+
}
|
|
@@ -6,7 +6,9 @@
|
|
|
6
6
|
* touching the production database (see docs/TESTING.md).
|
|
7
7
|
*/
|
|
8
8
|
import { Hono } from 'hono';
|
|
9
|
-
import { SqliteCueResolver, loopId } from '../core/cues.js';
|
|
9
|
+
import { SqliteCueResolver, loopId, isDangerousPattern, MAX_PATTERN_LENGTH, MAX_MATCH_TEXT_LENGTH, } from '../core/cues.js';
|
|
10
|
+
import { LimitExceeded, boundedString, MAX_CONTENT_LENGTH, MAX_SHORT_FIELD_LENGTH, MAX_COLLECTION_ITEMS, } from './limits.js';
|
|
11
|
+
import { serverErrorBody } from './errors.js';
|
|
10
12
|
const INTENTION_STATUSES = ['armed', 'fired', 'closed', 'expired'];
|
|
11
13
|
const CUE_STATUSES = ['armed', 'fired', 'cancelled'];
|
|
12
14
|
const CUE_KINDS = ['time', 'event'];
|
|
@@ -72,6 +74,14 @@ export function validateTriggerSpec(raw) {
|
|
|
72
74
|
case 'error_pattern':
|
|
73
75
|
if (typeof spec.pattern !== 'string' || !spec.pattern)
|
|
74
76
|
throw new BadRequest('"pattern" is required');
|
|
77
|
+
// SECURITY_AUDIT.md M-01: refuse oversized/backtracking-prone patterns here
|
|
78
|
+
// rather than silently degrading them to a literal search at match time.
|
|
79
|
+
if (spec.pattern.length > MAX_PATTERN_LENGTH) {
|
|
80
|
+
throw new BadRequest(`"pattern" must be at most ${MAX_PATTERN_LENGTH} characters`);
|
|
81
|
+
}
|
|
82
|
+
if (isDangerousPattern(spec.pattern)) {
|
|
83
|
+
throw new BadRequest('"pattern" contains a nested quantifier that risks catastrophic backtracking');
|
|
84
|
+
}
|
|
75
85
|
return { kind: 'event', type: 'error_pattern', pattern: spec.pattern };
|
|
76
86
|
default:
|
|
77
87
|
throw new BadRequest('unknown event type (file_open | branch_switch | error_pattern)');
|
|
@@ -101,6 +111,9 @@ export function validateAppEvent(raw) {
|
|
|
101
111
|
case 'error_pattern':
|
|
102
112
|
if (typeof e.text !== 'string' || !e.text)
|
|
103
113
|
throw new BadRequest('"text" is required');
|
|
114
|
+
if (e.text.length > MAX_MATCH_TEXT_LENGTH) {
|
|
115
|
+
throw new BadRequest(`"text" must be at most ${MAX_MATCH_TEXT_LENGTH} characters`);
|
|
116
|
+
}
|
|
104
117
|
return { type: 'error_pattern', text: e.text, directory: e.directory };
|
|
105
118
|
default:
|
|
106
119
|
if (typeof e.sha !== 'string' || !e.sha)
|
|
@@ -124,15 +137,17 @@ function serializeCue(cue) {
|
|
|
124
137
|
export function createIntentionRoutes(store, options = {}) {
|
|
125
138
|
const app = new Hono();
|
|
126
139
|
const resolver = new SqliteCueResolver(store, { clock: options.clock });
|
|
127
|
-
// Invalid input is the client's error, not the server's
|
|
140
|
+
// Invalid input is the client's error, not the server's — including a value
|
|
141
|
+
// that busts a size limit (SECURITY_AUDIT.md M-02).
|
|
128
142
|
const guard = async (c, fn) => {
|
|
129
143
|
try {
|
|
130
144
|
return await fn();
|
|
131
145
|
}
|
|
132
146
|
catch (err) {
|
|
133
|
-
if (err instanceof BadRequest)
|
|
147
|
+
if (err instanceof BadRequest || err instanceof LimitExceeded) {
|
|
134
148
|
return c.json({ error: err.message }, 400);
|
|
135
|
-
|
|
149
|
+
}
|
|
150
|
+
return c.json(serverErrorBody(`${c.req.method} ${c.req.path}`, err), 500);
|
|
136
151
|
}
|
|
137
152
|
};
|
|
138
153
|
app.post('/intentions', (c) => guard(c, async () => {
|
|
@@ -143,18 +158,24 @@ export function createIntentionRoutes(store, options = {}) {
|
|
|
143
158
|
if (typeof body.directory !== 'string' || !body.directory) {
|
|
144
159
|
throw new BadRequest('"directory" is required');
|
|
145
160
|
}
|
|
161
|
+
// SECURITY_AUDIT.md M-02: bound the stored fields and the cue collection.
|
|
162
|
+
const content = boundedString(body.content, MAX_CONTENT_LENGTH, 'content');
|
|
163
|
+
const directory = boundedString(body.directory, MAX_SHORT_FIELD_LENGTH, 'directory');
|
|
146
164
|
let expiresAt;
|
|
147
165
|
if (body.expiresAt) {
|
|
148
166
|
expiresAt = new Date(body.expiresAt);
|
|
149
167
|
if (Number.isNaN(expiresAt.getTime()))
|
|
150
168
|
throw new BadRequest('"expiresAt" is invalid');
|
|
151
169
|
}
|
|
170
|
+
if (Array.isArray(body.cues) && body.cues.length > MAX_COLLECTION_ITEMS) {
|
|
171
|
+
throw new BadRequest(`"cues" must hold at most ${MAX_COLLECTION_ITEMS} items`);
|
|
172
|
+
}
|
|
152
173
|
const cues = Array.isArray(body.cues)
|
|
153
174
|
? body.cues.map((spec) => validateTriggerSpec(spec))
|
|
154
175
|
: [];
|
|
155
176
|
const intention = await store.addIntention({
|
|
156
|
-
content:
|
|
157
|
-
directory
|
|
177
|
+
content: content.trim(),
|
|
178
|
+
directory,
|
|
158
179
|
expiresAt,
|
|
159
180
|
relatedMemoryId: typeof body.relatedMemoryId === 'string' ? body.relatedMemoryId : undefined,
|
|
160
181
|
}, cues);
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Request-size and cost limits shared by every route (SECURITY_AUDIT.md M-02).
|
|
3
|
+
*
|
|
4
|
+
* The API accepted JSON of any size and read cost parameters with a bare
|
|
5
|
+
* `parseInt`, so `?limit=999999999` or `NaN` reached the store unchecked and a
|
|
6
|
+
* single request could fill SQLite or pin the process. These caps are the
|
|
7
|
+
* business-level floor; `bodyLimit` in `server.ts` is the transport-level one.
|
|
8
|
+
*
|
|
9
|
+
* The values are deliberately generous — they exist to stop abuse, not to
|
|
10
|
+
* constrain ordinary use. A real learning trace is a few kilobytes at most.
|
|
11
|
+
*/
|
|
12
|
+
/** Longest memory/intention content accepted on a write. */
|
|
13
|
+
export declare const MAX_CONTENT_LENGTH = 100000;
|
|
14
|
+
/** Longest single keyword, and how many a memory may carry. */
|
|
15
|
+
export declare const MAX_KEYWORD_LENGTH = 200;
|
|
16
|
+
export declare const MAX_KEYWORDS = 100;
|
|
17
|
+
/** Longest short free-text field (directory, sessionId, agent, summaries…). */
|
|
18
|
+
export declare const MAX_SHORT_FIELD_LENGTH = 2000;
|
|
19
|
+
/** Longest search query string. */
|
|
20
|
+
export declare const MAX_QUERY_LENGTH = 1000;
|
|
21
|
+
/** How many steps or cues one script/intention may declare. */
|
|
22
|
+
export declare const MAX_COLLECTION_ITEMS = 100;
|
|
23
|
+
/** Ceiling for any `limit`-style pagination parameter. */
|
|
24
|
+
export declare const MAX_RESULT_LIMIT = 500;
|
|
25
|
+
/** Transport-level cap on a JSON request body, in bytes. */
|
|
26
|
+
export declare const MAX_BODY_BYTES = 1000000;
|
|
27
|
+
/** Thrown on a limit violation; routes map it to a 400. */
|
|
28
|
+
export declare class LimitExceeded extends Error {
|
|
29
|
+
constructor(message: string);
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Parses a numeric query parameter with a finite, enforced range.
|
|
33
|
+
*
|
|
34
|
+
* Unlike `parseInt`, this rejects `NaN`, `Infinity`, floats and out-of-range
|
|
35
|
+
* values instead of passing them to the store.
|
|
36
|
+
*/
|
|
37
|
+
export declare function boundedInt(raw: string | undefined, opts: {
|
|
38
|
+
fallback: number;
|
|
39
|
+
min: number;
|
|
40
|
+
max: number;
|
|
41
|
+
name: string;
|
|
42
|
+
}): number;
|
|
43
|
+
/** Same, for an optional parameter with no default. */
|
|
44
|
+
export declare function boundedOptionalInt(raw: string | undefined, opts: {
|
|
45
|
+
min: number;
|
|
46
|
+
max: number;
|
|
47
|
+
name: string;
|
|
48
|
+
}): number | undefined;
|
|
49
|
+
/** Requires a string no longer than `max`. */
|
|
50
|
+
export declare function boundedString(value: unknown, max: number, name: string): string;
|
|
51
|
+
/** Same, but tolerates an absent value. */
|
|
52
|
+
export declare function boundedOptionalString(value: unknown, max: number, name: string): string | undefined;
|
|
53
|
+
/** Requires an array of bounded strings, itself of bounded length. */
|
|
54
|
+
export declare function boundedStringArray(value: unknown, opts: {
|
|
55
|
+
maxItems: number;
|
|
56
|
+
maxItemLength: number;
|
|
57
|
+
name: string;
|
|
58
|
+
}): string[];
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Request-size and cost limits shared by every route (SECURITY_AUDIT.md M-02).
|
|
3
|
+
*
|
|
4
|
+
* The API accepted JSON of any size and read cost parameters with a bare
|
|
5
|
+
* `parseInt`, so `?limit=999999999` or `NaN` reached the store unchecked and a
|
|
6
|
+
* single request could fill SQLite or pin the process. These caps are the
|
|
7
|
+
* business-level floor; `bodyLimit` in `server.ts` is the transport-level one.
|
|
8
|
+
*
|
|
9
|
+
* The values are deliberately generous — they exist to stop abuse, not to
|
|
10
|
+
* constrain ordinary use. A real learning trace is a few kilobytes at most.
|
|
11
|
+
*/
|
|
12
|
+
/** Longest memory/intention content accepted on a write. */
|
|
13
|
+
export const MAX_CONTENT_LENGTH = 100_000;
|
|
14
|
+
/** Longest single keyword, and how many a memory may carry. */
|
|
15
|
+
export const MAX_KEYWORD_LENGTH = 200;
|
|
16
|
+
export const MAX_KEYWORDS = 100;
|
|
17
|
+
/** Longest short free-text field (directory, sessionId, agent, summaries…). */
|
|
18
|
+
export const MAX_SHORT_FIELD_LENGTH = 2_000;
|
|
19
|
+
/** Longest search query string. */
|
|
20
|
+
export const MAX_QUERY_LENGTH = 1_000;
|
|
21
|
+
/** How many steps or cues one script/intention may declare. */
|
|
22
|
+
export const MAX_COLLECTION_ITEMS = 100;
|
|
23
|
+
/** Ceiling for any `limit`-style pagination parameter. */
|
|
24
|
+
export const MAX_RESULT_LIMIT = 500;
|
|
25
|
+
/** Transport-level cap on a JSON request body, in bytes. */
|
|
26
|
+
export const MAX_BODY_BYTES = 1_000_000;
|
|
27
|
+
/** Thrown on a limit violation; routes map it to a 400. */
|
|
28
|
+
export class LimitExceeded extends Error {
|
|
29
|
+
constructor(message) {
|
|
30
|
+
super(message);
|
|
31
|
+
this.name = 'LimitExceeded';
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Parses a numeric query parameter with a finite, enforced range.
|
|
36
|
+
*
|
|
37
|
+
* Unlike `parseInt`, this rejects `NaN`, `Infinity`, floats and out-of-range
|
|
38
|
+
* values instead of passing them to the store.
|
|
39
|
+
*/
|
|
40
|
+
export function boundedInt(raw, opts) {
|
|
41
|
+
if (raw === undefined || raw === '')
|
|
42
|
+
return opts.fallback;
|
|
43
|
+
const n = Number(raw);
|
|
44
|
+
if (!Number.isInteger(n) || n < opts.min || n > opts.max) {
|
|
45
|
+
throw new LimitExceeded(`"${opts.name}" must be an integer between ${opts.min} and ${opts.max}`);
|
|
46
|
+
}
|
|
47
|
+
return n;
|
|
48
|
+
}
|
|
49
|
+
/** Same, for an optional parameter with no default. */
|
|
50
|
+
export function boundedOptionalInt(raw, opts) {
|
|
51
|
+
if (raw === undefined || raw === '')
|
|
52
|
+
return undefined;
|
|
53
|
+
return boundedInt(raw, { ...opts, fallback: 0 });
|
|
54
|
+
}
|
|
55
|
+
/** Requires a string no longer than `max`. */
|
|
56
|
+
export function boundedString(value, max, name) {
|
|
57
|
+
if (typeof value !== 'string')
|
|
58
|
+
throw new LimitExceeded(`"${name}" must be a string`);
|
|
59
|
+
if (value.length > max) {
|
|
60
|
+
throw new LimitExceeded(`"${name}" must be at most ${max} characters`);
|
|
61
|
+
}
|
|
62
|
+
return value;
|
|
63
|
+
}
|
|
64
|
+
/** Same, but tolerates an absent value. */
|
|
65
|
+
export function boundedOptionalString(value, max, name) {
|
|
66
|
+
if (value === undefined || value === null)
|
|
67
|
+
return undefined;
|
|
68
|
+
return boundedString(value, max, name);
|
|
69
|
+
}
|
|
70
|
+
/** Requires an array of bounded strings, itself of bounded length. */
|
|
71
|
+
export function boundedStringArray(value, opts) {
|
|
72
|
+
if (value === undefined || value === null)
|
|
73
|
+
return [];
|
|
74
|
+
if (!Array.isArray(value))
|
|
75
|
+
throw new LimitExceeded(`"${opts.name}" must be an array`);
|
|
76
|
+
if (value.length > opts.maxItems) {
|
|
77
|
+
throw new LimitExceeded(`"${opts.name}" must hold at most ${opts.maxItems} items`);
|
|
78
|
+
}
|
|
79
|
+
return value.map((item, i) => boundedString(item, opts.maxItemLength, `${opts.name}[${i}]`));
|
|
80
|
+
}
|