@3ngram/server 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/LICENSE +202 -0
  2. package/dist/app.d.ts +72 -0
  3. package/dist/app.js +273 -0
  4. package/dist/app.js.map +1 -0
  5. package/dist/boot.d.ts +37 -0
  6. package/dist/boot.js +53 -0
  7. package/dist/boot.js.map +1 -0
  8. package/dist/composition/extension.d.ts +50 -0
  9. package/dist/composition/extension.js +16 -0
  10. package/dist/composition/extension.js.map +1 -0
  11. package/dist/index.d.ts +1 -0
  12. package/dist/index.js +10 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/links.d.ts +17 -0
  15. package/dist/links.js +46 -0
  16. package/dist/links.js.map +1 -0
  17. package/dist/mailer.d.ts +58 -0
  18. package/dist/mailer.js +187 -0
  19. package/dist/mailer.js.map +1 -0
  20. package/dist/mcp/errors.d.ts +14 -0
  21. package/dist/mcp/errors.js +175 -0
  22. package/dist/mcp/errors.js.map +1 -0
  23. package/dist/mcp/prompts.d.ts +29 -0
  24. package/dist/mcp/prompts.js +180 -0
  25. package/dist/mcp/prompts.js.map +1 -0
  26. package/dist/mcp/server.d.ts +14 -0
  27. package/dist/mcp/server.js +34 -0
  28. package/dist/mcp/server.js.map +1 -0
  29. package/dist/mcp/tools-admin.d.ts +8 -0
  30. package/dist/mcp/tools-admin.js +260 -0
  31. package/dist/mcp/tools-admin.js.map +1 -0
  32. package/dist/mcp/tools-orient.d.ts +6 -0
  33. package/dist/mcp/tools-orient.js +110 -0
  34. package/dist/mcp/tools-orient.js.map +1 -0
  35. package/dist/mcp/tools.d.ts +88 -0
  36. package/dist/mcp/tools.js +375 -0
  37. package/dist/mcp/tools.js.map +1 -0
  38. package/dist/middleware/api-key.d.ts +13 -0
  39. package/dist/middleware/api-key.js +83 -0
  40. package/dist/middleware/api-key.js.map +1 -0
  41. package/dist/middleware/api-or-session.d.ts +9 -0
  42. package/dist/middleware/api-or-session.js +22 -0
  43. package/dist/middleware/api-or-session.js.map +1 -0
  44. package/dist/middleware/authenticate.d.ts +21 -0
  45. package/dist/middleware/authenticate.js +51 -0
  46. package/dist/middleware/authenticate.js.map +1 -0
  47. package/dist/middleware/index.d.ts +1 -0
  48. package/dist/middleware/index.js +9 -0
  49. package/dist/middleware/index.js.map +1 -0
  50. package/dist/middleware/oauth-bearer.d.ts +8 -0
  51. package/dist/middleware/oauth-bearer.js +117 -0
  52. package/dist/middleware/oauth-bearer.js.map +1 -0
  53. package/dist/middleware/rate-limit.d.ts +58 -0
  54. package/dist/middleware/rate-limit.js +139 -0
  55. package/dist/middleware/rate-limit.js.map +1 -0
  56. package/dist/middleware/request-context.d.ts +7 -0
  57. package/dist/middleware/request-context.js +14 -0
  58. package/dist/middleware/request-context.js.map +1 -0
  59. package/dist/output-validation.d.ts +18 -0
  60. package/dist/output-validation.js +30 -0
  61. package/dist/output-validation.js.map +1 -0
  62. package/dist/redis.d.ts +9 -0
  63. package/dist/redis.js +37 -0
  64. package/dist/redis.js.map +1 -0
  65. package/dist/rest/cursor.d.ts +14 -0
  66. package/dist/rest/cursor.js +38 -0
  67. package/dist/rest/cursor.js.map +1 -0
  68. package/dist/rest/errors.d.ts +14 -0
  69. package/dist/rest/errors.js +119 -0
  70. package/dist/rest/errors.js.map +1 -0
  71. package/dist/rest/router.d.ts +33 -0
  72. package/dist/rest/router.js +846 -0
  73. package/dist/rest/router.js.map +1 -0
  74. package/dist/rest/scope.d.ts +14 -0
  75. package/dist/rest/scope.js +45 -0
  76. package/dist/rest/scope.js.map +1 -0
  77. package/dist/routes/api-keys.d.ts +2 -0
  78. package/dist/routes/api-keys.js +77 -0
  79. package/dist/routes/api-keys.js.map +1 -0
  80. package/dist/routes/auth.d.ts +20 -0
  81. package/dist/routes/auth.js +325 -0
  82. package/dist/routes/auth.js.map +1 -0
  83. package/dist/routes/capabilities.d.ts +10 -0
  84. package/dist/routes/capabilities.js +17 -0
  85. package/dist/routes/capabilities.js.map +1 -0
  86. package/dist/routes/health.d.ts +7 -0
  87. package/dist/routes/health.js +12 -0
  88. package/dist/routes/health.js.map +1 -0
  89. package/dist/routes/mcp.d.ts +27 -0
  90. package/dist/routes/mcp.js +81 -0
  91. package/dist/routes/mcp.js.map +1 -0
  92. package/dist/routes/oauth-authorize.d.ts +8 -0
  93. package/dist/routes/oauth-authorize.js +245 -0
  94. package/dist/routes/oauth-authorize.js.map +1 -0
  95. package/dist/routes/oauth-clients.d.ts +2 -0
  96. package/dist/routes/oauth-clients.js +59 -0
  97. package/dist/routes/oauth-clients.js.map +1 -0
  98. package/dist/routes/oauth-register.d.ts +8 -0
  99. package/dist/routes/oauth-register.js +59 -0
  100. package/dist/routes/oauth-register.js.map +1 -0
  101. package/dist/routes/oauth-token.d.ts +30 -0
  102. package/dist/routes/oauth-token.js +451 -0
  103. package/dist/routes/oauth-token.js.map +1 -0
  104. package/dist/routes/onboarding.d.ts +2 -0
  105. package/dist/routes/onboarding.js +47 -0
  106. package/dist/routes/onboarding.js.map +1 -0
  107. package/dist/routes/profile.d.ts +2 -0
  108. package/dist/routes/profile.js +35 -0
  109. package/dist/routes/profile.js.map +1 -0
  110. package/dist/routes/well-known.d.ts +2 -0
  111. package/dist/routes/well-known.js +77 -0
  112. package/dist/routes/well-known.js.map +1 -0
  113. package/dist/version.d.ts +1 -0
  114. package/dist/version.js +17 -0
  115. package/dist/version.js.map +1 -0
  116. package/package.json +67 -0
@@ -0,0 +1,30 @@
1
+ /** A tool/route RESULT failed its output schema — a server fault, not bad input. */
2
+ export class OutputValidationError extends Error {
3
+ /** The tool/route whose result failed validation. */
4
+ surface;
5
+ /** Number of schema issues (bounded metadata only). */
6
+ issueCount;
7
+ /** Issue paths — schema field names and array indices, never values. */
8
+ issuePaths;
9
+ constructor(surface, zodError) {
10
+ super(`${surface} produced a result that failed output validation`);
11
+ this.name = 'OutputValidationError';
12
+ this.surface = surface;
13
+ this.issueCount = zodError.issues.length;
14
+ this.issuePaths = zodError.issues.map((issue) => issue.path.join('.'));
15
+ }
16
+ }
17
+ /**
18
+ * Parse a handler's RESULT against its output schema, rethrowing a ZodError as
19
+ * {@link OutputValidationError} so the transport error ladder can distinguish a
20
+ * server-side result-shape fault from malformed caller input. Input `.parse()`
21
+ * calls stay bare — only OUTPUT parses go through here.
22
+ */
23
+ export function parseOutput(surface, schema, value) {
24
+ const result = schema.safeParse(value);
25
+ if (!result.success) {
26
+ throw new OutputValidationError(surface, result.error);
27
+ }
28
+ return result.data;
29
+ }
30
+ //# sourceMappingURL=output-validation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"output-validation.js","sourceRoot":"","sources":["../src/output-validation.ts"],"names":[],"mappings":"AAaA,oFAAoF;AACpF,MAAM,OAAO,qBAAsB,SAAQ,KAAK;IAC9C,qDAAqD;IAC5C,OAAO,CAAQ;IACxB,uDAAuD;IAC9C,UAAU,CAAQ;IAC3B,wEAAwE;IAC/D,UAAU,CAAU;IAE7B,YAAY,OAAe,EAAE,QAAkB;QAC7C,KAAK,CAAC,GAAG,OAAO,kDAAkD,CAAC,CAAA;QACnE,IAAI,CAAC,IAAI,GAAG,uBAAuB,CAAA;QACnC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,UAAU,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAA;QACxC,IAAI,CAAC,UAAU,GAAG,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAA;IACxE,CAAC;CACF;AAED;;;;;GAKG;AACH,MAAM,UAAU,WAAW,CACzB,OAAe,EACf,MAAS,EACT,KAAc;IAEd,MAAM,MAAM,GAAG,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,CAAA;IACtC,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;QACpB,MAAM,IAAI,qBAAqB,CAAC,OAAO,EAAE,MAAM,CAAC,KAAK,CAAC,CAAA;IACxD,CAAC;IACD,OAAO,MAAM,CAAC,IAAkB,CAAA;AAClC,CAAC"}
@@ -0,0 +1,9 @@
1
+ import { Redis } from 'ioredis';
2
+ /**
3
+ * Construct the boot Redis client iff REDIS_URL is set, else undefined ("not
4
+ * configured" — the limiters then use an in-memory store). Lazy-connect so import
5
+ * never blocks on a network dial; a redacted error is logged on connection
6
+ * failure and the limiter's fail-open path keeps the API serving. The URL is
7
+ * passed straight into ioredis and never echoed.
8
+ */
9
+ export declare function resolveRedis(): Redis | undefined;
package/dist/redis.js ADDED
@@ -0,0 +1,37 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // The single ioredis client, constructed once at boot from REDIS_URL and injected
3
+ // into the rate limiters. Mirrors the resolveGateway seam in
4
+ // app.ts: tests inject nothing (the limiters fall back to RateLimiterMemory), so
5
+ // NO real Redis is ever required in CI.
6
+ //
7
+ // The client is shared with the BullMQ workers (ioredis is
8
+ // BullMQ-compatible), so it lives at the app root rather than inside the limiter
9
+ // module. REDIS_URL is a credential — it is never logged (hard rule 6); only the
10
+ // connection lifecycle (lazy connect, retry) is observable.
11
+ import { loadEnv, log } from '@3ngram/config';
12
+ import { Redis } from 'ioredis';
13
+ /**
14
+ * Construct the boot Redis client iff REDIS_URL is set, else undefined ("not
15
+ * configured" — the limiters then use an in-memory store). Lazy-connect so import
16
+ * never blocks on a network dial; a redacted error is logged on connection
17
+ * failure and the limiter's fail-open path keeps the API serving. The URL is
18
+ * passed straight into ioredis and never echoed.
19
+ */
20
+ export function resolveRedis() {
21
+ const { REDIS_URL } = loadEnv();
22
+ if (REDIS_URL === undefined)
23
+ return undefined;
24
+ const client = new Redis(REDIS_URL, {
25
+ lazyConnect: true,
26
+ // Do not let a single command hang forever when Redis is unreachable; the
27
+ // limiter then sees a store error and fails open.
28
+ maxRetriesPerRequest: 1,
29
+ enableOfflineQueue: false,
30
+ });
31
+ client.on('error', (err) => {
32
+ // The connection string is a credential; log the error NAME only.
33
+ log().warn({ err: err.name }, 'redis: client error');
34
+ });
35
+ return client;
36
+ }
37
+ //# sourceMappingURL=redis.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redis.js","sourceRoot":"","sources":["../src/redis.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,kFAAkF;AAClF,6DAA6D;AAC7D,iFAAiF;AACjF,wCAAwC;AACxC,EAAE;AACF,2DAA2D;AAC3D,iFAAiF;AACjF,iFAAiF;AACjF,4DAA4D;AAC5D,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,gBAAgB,CAAA;AAC7C,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAE/B;;;;;;GAMG;AACH,MAAM,UAAU,YAAY;IAC1B,MAAM,EAAE,SAAS,EAAE,GAAG,OAAO,EAAE,CAAA;IAC/B,IAAI,SAAS,KAAK,SAAS;QAAE,OAAO,SAAS,CAAA;IAC7C,MAAM,MAAM,GAAG,IAAI,KAAK,CAAC,SAAS,EAAE;QAClC,WAAW,EAAE,IAAI;QACjB,0EAA0E;QAC1E,kDAAkD;QAClD,oBAAoB,EAAE,CAAC;QACvB,kBAAkB,EAAE,KAAK;KAC1B,CAAC,CAAA;IACF,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,GAAU,EAAE,EAAE;QAChC,kEAAkE;QAClE,GAAG,EAAE,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,GAAG,CAAC,IAAI,EAAE,EAAE,qBAAqB,CAAC,CAAA;IACtD,CAAC,CAAC,CAAA;IACF,OAAO,MAAM,CAAA;AACf,CAAC"}
@@ -0,0 +1,14 @@
1
+ import { type CursorPayload } from '@3ngram/schema';
2
+ /** Serialize a cursor payload to an opaque base64url token. */
3
+ export declare function encodeCursor(payload: CursorPayload): string;
4
+ /**
5
+ * Decode + validate an opaque cursor token back to its v2 payload.
6
+ *
7
+ * Returns `undefined` for a legacy v1 keyset cursor (`{ s, id }`) minted before
8
+ * the v2 deploy — the caller restarts at page 1 rather than erroring
9
+ * mid-session across the deploy boundary. A genuinely malformed token (bad
10
+ * base64/JSON, or a shape that is neither v2 nor v1) throws a ZodError, which
11
+ * mapRestError turns into a 400 — a forged or garbled cursor is client input,
12
+ * never a server crash.
13
+ */
14
+ export declare function decodeCursor(token: string): CursorPayload | undefined;
@@ -0,0 +1,38 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Node-side opaque encode/decode for the dashboard search frozen-ordering cursor.
3
+ // The payload SHAPE (cursorPayloadSchema) is the shared contract in
4
+ // @3ngram/schema; the base64url serialization lives here so the schema package
5
+ // stays dependency-light (zod only — no @types/node for Buffer). The browser
6
+ // treats the token as opaque and never decodes it (see lib/search/api.ts).
7
+ import { cursorPayloadSchema, legacyCursorPayloadSchema } from '@3ngram/schema';
8
+ /** Serialize a cursor payload to an opaque base64url token. */
9
+ export function encodeCursor(payload) {
10
+ return Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url');
11
+ }
12
+ /**
13
+ * Decode + validate an opaque cursor token back to its v2 payload.
14
+ *
15
+ * Returns `undefined` for a legacy v1 keyset cursor (`{ s, id }`) minted before
16
+ * the v2 deploy — the caller restarts at page 1 rather than erroring
17
+ * mid-session across the deploy boundary. A genuinely malformed token (bad
18
+ * base64/JSON, or a shape that is neither v2 nor v1) throws a ZodError, which
19
+ * mapRestError turns into a 400 — a forged or garbled cursor is client input,
20
+ * never a server crash.
21
+ */
22
+ export function decodeCursor(token) {
23
+ let json;
24
+ try {
25
+ json = JSON.parse(Buffer.from(token, 'base64url').toString('utf8'));
26
+ }
27
+ catch {
28
+ json = undefined;
29
+ }
30
+ const v2 = cursorPayloadSchema.safeParse(json);
31
+ if (v2.success)
32
+ return v2.data;
33
+ if (legacyCursorPayloadSchema.safeParse(json).success)
34
+ return undefined;
35
+ // Neither v2 nor a recognized legacy cursor → malformed client input (400).
36
+ return cursorPayloadSchema.parse(json);
37
+ }
38
+ //# sourceMappingURL=cursor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cursor.js","sourceRoot":"","sources":["../../src/rest/cursor.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,kFAAkF;AAClF,oEAAoE;AACpE,+EAA+E;AAC/E,6EAA6E;AAC7E,2EAA2E;AAC3E,OAAO,EAAsB,mBAAmB,EAAE,yBAAyB,EAAE,MAAM,gBAAgB,CAAA;AAEnG,+DAA+D;AAC/D,MAAM,UAAU,YAAY,CAAC,OAAsB;IACjD,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAA;AAC3E,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,YAAY,CAAC,KAAa;IACxC,IAAI,IAAa,CAAA;IACjB,IAAI,CAAC;QACH,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAA;IACrE,CAAC;IAAC,MAAM,CAAC;QACP,IAAI,GAAG,SAAS,CAAA;IAClB,CAAC;IACD,MAAM,EAAE,GAAG,mBAAmB,CAAC,SAAS,CAAC,IAAI,CAAC,CAAA;IAC9C,IAAI,EAAE,CAAC,OAAO;QAAE,OAAO,EAAE,CAAC,IAAI,CAAA;IAC9B,IAAI,yBAAyB,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,OAAO;QAAE,OAAO,SAAS,CAAA;IACvE,4EAA4E;IAC5E,OAAO,mBAAmB,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;AACxC,CAAC"}
@@ -0,0 +1,14 @@
1
+ /** A mapped HTTP failure: the status code and the stable reason_code body. */
2
+ export interface RestError {
3
+ status: number;
4
+ /** The reason_code (MCP taxonomy) — the stable machine-readable error tag. */
5
+ reason: string;
6
+ }
7
+ /**
8
+ * Map a thrown error to an HTTP status + reason_code, or undefined when the error
9
+ * is NOT a known typed core error (the caller then surfaces a generic 500). This
10
+ * mirrors the MCP catch ladder (apps/server/src/mcp/errors.ts) branch-for-branch
11
+ * — the SAME reason_code taxonomy — but emits an HTTP contract: each branch logs
12
+ * at the matching level (no content) and returns the status/reason pair.
13
+ */
14
+ export declare function mapRestError(route: string, err: unknown): RestError | undefined;
@@ -0,0 +1,119 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // REST typed-error mapping (ADR-0011 thin transport). The
3
+ // REST mirror of the core memory tools translates a KNOWN typed core error into
4
+ // an HTTP status + a stable reason_code body, REUSING the MCP reason_code
5
+ // TAXONOMY (apps/server/src/mcp/errors.ts) but mapping to HTTP codes rather than
6
+ // MCP isError results — the two transports share the taxonomy, NOT the function
7
+ // (the MCP mapper emits CallToolResult; REST emits status + JSON).
8
+ //
9
+ // REASON_CODE -> HTTP (the contract this slice ships):
10
+ // invalid_input -> 400 (ZodError / typed core validation / not-commitment)
11
+ // not_found -> 404 (predecessor / commitment / scope / proposal absent)
12
+ // conflict -> 409 (already superseded, edge conflict, commitment exists)
13
+ // duplicate_memory -> 409 (content already live for the tenant)
14
+ // invalid_transition -> 409 (illegal FSM transition)
15
+ // invalid_output -> 500 (a RESULT failed its output schema — server fault)
16
+ // auth statuses (401 unauthorized, 403 insufficient_scope, 503 resolver-or-DB)
17
+ // are emitted UPSTREAM (apiKeyAuth / scope.ts), so the mapper covers the core
18
+ // domain errors a route handler can throw. An UNKNOWN error returns undefined so
19
+ // the route surfaces a generic 500.
20
+ //
21
+ // Observability (hard rule 6): no memory content, query text, subject/value, or
22
+ // credential enters a log or a response body — only the error class name and the
23
+ // bounded ids/hashes the typed error already carries (a uuid, a content hash, an
24
+ // FSM state — never content).
25
+ import { log } from '@3ngram/config';
26
+ import { AccessDeniedError, BudgetExceededError, CommitmentExistsError, CommitmentNotFoundError, DuplicateMemoryError, EdgeConflictError, EpisodicSupersessionError, IllegalCommitmentTransitionError, InvalidCommitmentTransitionError, InvalidEmbeddingError, MemoryNotFoundError, MissingSelectorError, NotCommitmentMemoryError, PredecessorAlreadySupersededError, PredecessorNotFoundError, ProposalNotFoundError, ScopeNameConflictError, ScopeNotFoundError, SuccessorNotLiveError, } from '@3ngram/core';
27
+ import { ZodError } from 'zod';
28
+ import { OutputValidationError } from '../output-validation.js';
29
+ /**
30
+ * Map a thrown error to an HTTP status + reason_code, or undefined when the error
31
+ * is NOT a known typed core error (the caller then surfaces a generic 500). This
32
+ * mirrors the MCP catch ladder (apps/server/src/mcp/errors.ts) branch-for-branch
33
+ * — the SAME reason_code taxonomy — but emits an HTTP contract: each branch logs
34
+ * at the matching level (no content) and returns the status/reason pair.
35
+ */
36
+ export function mapRestError(route, err) {
37
+ // A result that failed an OUTPUT schema is a 500-class SERVER
38
+ // fault, never the caller's input. REST routes currently do not output-parse
39
+ // (core's read-path excerpting bounds the shapes — see the search route), so
40
+ // this branch mirrors the MCP ladder for any future output guard: same honest
41
+ // taxonomy on both transports. Bounded metadata only.
42
+ if (err instanceof OutputValidationError) {
43
+ log().error({ route, err: err.name, issue_count: err.issueCount, paths: err.issuePaths }, 'rest: result failed output validation');
44
+ return { status: 500, reason: 'invalid_output' };
45
+ }
46
+ // Malformed CLIENT input — a ZodError from a boundary INPUT .parse() or a
47
+ // typed core validation error — is a 400, not a server fault: only the error
48
+ // class name is logged.
49
+ if (err instanceof ZodError ||
50
+ err instanceof InvalidEmbeddingError ||
51
+ err instanceof MissingSelectorError ||
52
+ err instanceof NotCommitmentMemoryError) {
53
+ log().warn({ route, err: err instanceof Error ? err.name : 'unknown' }, 'rest: input rejected');
54
+ return { status: 400, reason: 'invalid_input' };
55
+ }
56
+ // Over the per-user budget cap. 402 Payment Required is the
57
+ // honest status for a spend-cap denial. The reason_code is stable and carries
58
+ // NO cost internals (no cap, no consumption) — only the bounded op name is
59
+ // logged.
60
+ if (err instanceof BudgetExceededError) {
61
+ log().warn({ route, operation: err.operation }, 'rest: over budget cap');
62
+ return { status: 402, reason: 'budget_exceeded' };
63
+ }
64
+ // Access policy forbids the operation. 403 Forbidden is the honest status — the
65
+ // request is authenticated but the access policy denies it. The reason_code
66
+ // carries ONLY the bounded access kind the error holds, never any policy
67
+ // internals.
68
+ if (err instanceof AccessDeniedError) {
69
+ log().warn({ route, access: err.access }, 'rest: access denied');
70
+ return { status: 403, reason: 'access_denied' };
71
+ }
72
+ // Re-submitting content already live for the tenant is a documented domain
73
+ // CONFLICT (409), not a server fault. Only the content_hash is logged.
74
+ if (err instanceof DuplicateMemoryError) {
75
+ log().warn({ route, content_hash: err.contentHash }, 'rest: duplicate memory rejected');
76
+ return { status: 409, reason: 'duplicate_memory' };
77
+ }
78
+ // The referenced entity does not exist for the tenant (RLS hides cross-tenant
79
+ // rows, so not-found and not-owned are one 404 mapping).
80
+ if (err instanceof PredecessorNotFoundError) {
81
+ log().warn({ route, err: err.name }, 'rest: predecessor not found');
82
+ return { status: 404, reason: 'not_found' };
83
+ }
84
+ if (err instanceof CommitmentNotFoundError) {
85
+ log().warn({ route, err: err.name }, 'rest: commitment not found');
86
+ return { status: 404, reason: 'not_found' };
87
+ }
88
+ if (err instanceof ScopeNotFoundError) {
89
+ log().warn({ route, err: err.name }, 'rest: scope not found');
90
+ return { status: 404, reason: 'not_found' };
91
+ }
92
+ if (err instanceof ProposalNotFoundError) {
93
+ log().warn({ route, err: err.name }, 'rest: proposal not found');
94
+ return { status: 404, reason: 'not_found' };
95
+ }
96
+ if (err instanceof MemoryNotFoundError) {
97
+ log().warn({ route, err: err.name }, 'rest: memory not found');
98
+ return { status: 404, reason: 'not_found' };
99
+ }
100
+ // Documented domain CONFLICTS (409): already superseded, edge conflict, a
101
+ // commitment already rides the memory, an illegal FSM transition, a scope-name
102
+ // collision. Names the class / a bounded id or enum state only, never content.
103
+ if (err instanceof PredecessorAlreadySupersededError ||
104
+ err instanceof EdgeConflictError ||
105
+ err instanceof CommitmentExistsError ||
106
+ err instanceof ScopeNameConflictError ||
107
+ err instanceof EpisodicSupersessionError ||
108
+ err instanceof SuccessorNotLiveError) {
109
+ log().warn({ route, err: err.name }, 'rest: conflict');
110
+ return { status: 409, reason: 'conflict' };
111
+ }
112
+ if (err instanceof InvalidCommitmentTransitionError ||
113
+ err instanceof IllegalCommitmentTransitionError) {
114
+ log().warn({ route, err: err.name, from: err.from, to: err.to }, 'rest: illegal commitment transition');
115
+ return { status: 409, reason: 'invalid_transition' };
116
+ }
117
+ return undefined;
118
+ }
119
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/rest/errors.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,0DAA0D;AAC1D,gFAAgF;AAChF,0EAA0E;AAC1E,iFAAiF;AACjF,gFAAgF;AAChF,mEAAmE;AACnE,EAAE;AACF,uDAAuD;AACvD,qFAAqF;AACrF,sFAAsF;AACtF,wFAAwF;AACxF,uEAAuE;AACvE,0DAA0D;AAC1D,oFAAoF;AACpF,+EAA+E;AAC/E,8EAA8E;AAC9E,iFAAiF;AACjF,oCAAoC;AACpC,EAAE;AACF,gFAAgF;AAChF,iFAAiF;AACjF,iFAAiF;AACjF,8BAA8B;AAC9B,OAAO,EAAE,GAAG,EAAE,MAAM,gBAAgB,CAAA;AACpC,OAAO,EACL,iBAAiB,EACjB,mBAAmB,EACnB,qBAAqB,EACrB,uBAAuB,EACvB,oBAAoB,EACpB,iBAAiB,EACjB,yBAAyB,EACzB,gCAAgC,EAChC,gCAAgC,EAChC,qBAAqB,EACrB,mBAAmB,EACnB,oBAAoB,EACpB,wBAAwB,EACxB,iCAAiC,EACjC,wBAAwB,EACxB,qBAAqB,EACrB,sBAAsB,EACtB,kBAAkB,EAClB,qBAAqB,GACtB,MAAM,cAAc,CAAA;AACrB,OAAO,EAAE,QAAQ,EAAE,MAAM,KAAK,CAAA;AAC9B,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAA;AAS/D;;;;;;GAMG;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,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,oBAAoB,EAAE,CAAA;IACtD,CAAC;IACD,OAAO,SAAS,CAAA;AAClB,CAAC"}
@@ -0,0 +1,33 @@
1
+ import { type AccessGate, type BudgetEnforcement, type ExportEnricher } from '@3ngram/core';
2
+ import type { Gateway } from '@3ngram/llm';
3
+ import { Router } from 'express';
4
+ import type { RateLimiterMiddleware } from '../middleware/rate-limit.js';
5
+ /** Options the boot wiring injects: the embedding gateway (undefined when not configured). */
6
+ export interface RestRouterOptions {
7
+ /** Embedding gateway threaded through createApp (same seam mcpRouter gets) — undefined when env-gated off. */
8
+ gateway: Gateway | undefined;
9
+ /** Per-API-key rate limiter for /api/v1. Mounted BEFORE apiOrSessionAuth. Session Bearer requests (no X-API-Key) skip it. */
10
+ rateLimiter?: RateLimiterMiddleware;
11
+ /** Budget enforcement — gates every metered embed on /api/v1.
12
+ * Threaded into remember/revise/import (pre-persist) and search (query embed).
13
+ * Undefined → no budget gate (test/back-compat). */
14
+ budget?: BudgetEnforcement | undefined;
15
+ /** Access gate — asserts read/write access on every /api/v1 route.
16
+ * Undefined → no access guard (test/back-compat). */
17
+ access?: AccessGate | undefined;
18
+ /** Account-deletion cleanup hook. The private repo injects platform-specific
19
+ * cleanup; undefined → self-host runs no extra work. Apache code never imports
20
+ * the private repo. */
21
+ onAccountDeletion?: ((userId: string) => Promise<void>) | undefined;
22
+ /** GDPR-export enricher. The private repo adds extra user-owned rows to the
23
+ * archive; undefined → self-host omits them. */
24
+ exportEnricher?: ExportEnricher | undefined;
25
+ }
26
+ /**
27
+ * Build the /api/v1 REST router. Every route is guarded by apiOrSessionAuth
28
+ * (applied at the router level), so the whole mirror is reachable with EITHER a
29
+ * valid X-API-Key (C3) OR a session Bearer token (C2, from POST /auth/login) —
30
+ * both bind req.userId identically. The mount stays independent of the MCP Bearer
31
+ * (OAuth) mount.
32
+ */
33
+ export declare function restRouter(options: RestRouterOptions): Router;