humemory 0.2.3 → 0.2.5
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 +32 -0
- package/README.md +75 -6
- package/dist/agent/claude-hook.js +8 -3
- package/dist/agent/codex-import.d.ts +40 -0
- package/dist/agent/codex-import.js +97 -0
- package/dist/agent/codex-rollout-parser.d.ts +30 -0
- package/dist/agent/codex-rollout-parser.js +111 -0
- package/dist/agent/maintenance-queue.js +2 -2
- package/dist/agent/session-context.js +6 -0
- package/dist/agent/session-parser.d.ts +17 -0
- package/dist/agent/session-parser.js +28 -0
- 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 +20 -10
- package/dist/cli/index.js +36 -0
- package/dist/core/cues.d.ts +16 -0
- package/dist/core/cues.js +56 -3
- package/dist/core/llm-cli-client.d.ts +43 -0
- package/dist/core/llm-cli-client.js +108 -0
- package/dist/store/sqlite.d.ts +9 -1
- package/dist/store/sqlite.js +9 -2
- package/package.json +2 -1
- package/public/app/index-95ffty7j.js +12 -0
- package/public/app/index.html +1 -1
- package/scripts/maintenance-worker.ts +9 -1
- package/public/app/index-nqr7bd0a.js +0 -12
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
|
+
}
|
|
@@ -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
|
|
19
|
-
directory:
|
|
20
|
-
day:
|
|
21
|
-
keywords
|
|
22
|
-
sessionId:
|
|
23
|
-
level1Summary
|
|
24
|
-
level2Essential
|
|
25
|
-
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:
|
|
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({
|
|
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 =
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
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({
|
|
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({
|
|
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({
|
|
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 =
|
|
117
|
-
|
|
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:
|
|
124
|
-
limit:
|
|
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({
|
|
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({
|
|
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({
|
|
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
|
-
|
|
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
|
-
|
|
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({
|
|
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:
|
|
73
|
-
description:
|
|
86
|
+
name: name.trim(),
|
|
87
|
+
description: description.trim(),
|
|
74
88
|
steps,
|
|
75
|
-
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
|
+
}
|