@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,50 @@
1
+ import type { AccessGate, ExportEnricher, Limits } from '@3ngram/core';
2
+ import type { CapabilityDescriptor } from '@3ngram/schema';
3
+ import type { Express } from 'express';
4
+ export interface Extension {
5
+ /** Hosted-only surfaces advertised by the capability document when injected. */
6
+ readonly capabilities: readonly CapabilityDescriptor[];
7
+ /**
8
+ * Hosted-only limits resolver. When present, createApp threads it into the
9
+ * budget enforcement that BOTH metered transports (REST + MCP) share — so hosted
10
+ * requests resolve a real tier + window. Absent (self-host, no-op extension) the
11
+ * budget falls through to the config default cap. The private repo is the ONLY
12
+ * place a real resolver is constructed (no Apache package imports it).
13
+ */
14
+ resolveLimits?(userId: string): Promise<Limits>;
15
+ /**
16
+ * Hosted-only access gate. When present, createApp threads it into BOTH metered
17
+ * transports so hosted requests are gated by a real access policy. Absent
18
+ * (self-host) the Apache `allowAllAccess` stands, so the self-host artifact gates
19
+ * nothing on access (budget caps still apply). The private repo is the ONLY place
20
+ * a real gate is constructed (no Apache package imports it).
21
+ */
22
+ access?: AccessGate;
23
+ /**
24
+ * Hosted-only account-deletion hook. When present, createApp threads it into
25
+ * account deletion so erasing a hosted account can run platform-specific cleanup
26
+ * (e.g. external cancellation). Absent (self-host) deletion completes with no
27
+ * extra work. The private repo is the ONLY place a real hook is constructed (no
28
+ * Apache import).
29
+ */
30
+ onAccountDeletion?(userId: string): Promise<void>;
31
+ /**
32
+ * Hosted-only GDPR-export enricher. When present, createApp threads it into the
33
+ * export route so the archive includes extra platform-owned user rows. Absent
34
+ * (self-host) the export omits them. The private repo is the ONLY place a real
35
+ * enricher is constructed (no Apache import).
36
+ */
37
+ exportEnricher?: ExportEnricher;
38
+ /** Attach hosted-only routes/handlers to the server at the composition root. */
39
+ register(app: Express): void;
40
+ }
41
+ /** Apache default: advertises nothing and attaches nothing (self-host). */
42
+ export declare const noOpExtension: Extension;
43
+ /**
44
+ * Base Apache capabilities — surfaces every deployment offers (self-host and
45
+ * cloud alike), advertised in the capability document alongside any injected
46
+ * hosted-only capabilities. Kept deliberately small: the open-core memory
47
+ * surface is the one always-on capability the boundary scaffolding needs to
48
+ * prove `base ∪ extension`. NO user/tenant content.
49
+ */
50
+ export declare const baseCapabilities: readonly CapabilityDescriptor[];
@@ -0,0 +1,16 @@
1
+ /** Apache default: advertises nothing and attaches nothing (self-host). */
2
+ export const noOpExtension = {
3
+ capabilities: [],
4
+ register() { },
5
+ };
6
+ /**
7
+ * Base Apache capabilities — surfaces every deployment offers (self-host and
8
+ * cloud alike), advertised in the capability document alongside any injected
9
+ * hosted-only capabilities. Kept deliberately small: the open-core memory
10
+ * surface is the one always-on capability the boundary scaffolding needs to
11
+ * prove `base ∪ extension`. NO user/tenant content.
12
+ */
13
+ export const baseCapabilities = [
14
+ { name: 'memory.core', available: true, kind: 'rest' },
15
+ ];
16
+ //# sourceMappingURL=extension.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extension.js","sourceRoot":"","sources":["../../src/composition/extension.ts"],"names":[],"mappings":"AAqDA,2EAA2E;AAC3E,MAAM,CAAC,MAAM,aAAa,GAAc;IACtC,YAAY,EAAE,EAAE;IAChB,QAAQ,KAAI,CAAC;CACd,CAAA;AAED;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAoC;IAC/D,EAAE,IAAI,EAAE,aAAa,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE;CACvD,CAAA"}
@@ -0,0 +1 @@
1
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Apache server entrypoint — the sole side-effectful boot for self-host. Delegates
3
+ // to the shared bootstrap() (boot.ts) so the private repo's entrypoint
4
+ // runs the IDENTICAL fail-closed sequence (initObservability → loadEnv →
5
+ // metered-op check → OAuth key validation → dynamic-import createApp). No
6
+ // extension here ⇒ the no-op default ⇒ self-host runs the public build. The
7
+ // load-order contract (OTel before express) lives in bootstrap().
8
+ import { bootstrap } from './boot.js';
9
+ await bootstrap();
10
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,mFAAmF;AACnF,uEAAuE;AACvE,yEAAyE;AACzE,0EAA0E;AAC1E,4EAA4E;AAC5E,kEAAkE;AAClE,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAA;AAErC,MAAM,SAAS,EAAE,CAAA"}
@@ -0,0 +1,17 @@
1
+ /** Normalize WEB_APP_URL to an origin with no trailing slash; undefined ⇒ unset. */
2
+ export declare function webOrigin(webAppUrl: string | undefined): string | undefined;
3
+ /** `/reset-password?token=` — the set-password page reads `token` from
4
+ * searchParams. Used by password reset AND the migrated-user reconnect flow
5
+ * (see {@link buildReconnectLink}), which both set a password via this page. */
6
+ export declare function buildResetLink(webAppUrl: string | undefined, token: string): string | undefined;
7
+ /** `/verify-email?token=` — finishes signup. */
8
+ export declare function buildVerificationLink(webAppUrl: string | undefined, token: string): string | undefined;
9
+ /** Migrated-user reconnect link. A migrated account is
10
+ * pre-provisioned with no password; the user sets one via the same
11
+ * `/reset-password` set-password page and lands on their populated account. This
12
+ * is the canonical builder the launch-wave caller reuses so it never
13
+ * re-derives the WEB_APP_URL URL shape or builds a wrong-origin link. */
14
+ export declare function buildReconnectLink(webAppUrl: string | undefined, token: string): string | undefined;
15
+ /** Public self-serve signup link for waitlist re-engagement.
16
+ * No token — it points at the open `/signup` page; no account is provisioned. */
17
+ export declare function buildSignupLink(webAppUrl: string | undefined): string | undefined;
package/dist/links.js ADDED
@@ -0,0 +1,46 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Web-dashboard link builders (one home, shared by the auth routes and the
3
+ // legacy-migration launch wave). The dashboard runs on a DIFFERENT
4
+ // origin than this API server (docs/operate.mdx), so every link a
5
+ // recipient clicks MUST be built against WEB_APP_URL, never BASE_URL (the
6
+ // API/OAuth issuer, which serves none of these pages). When WEB_APP_URL is unset
7
+ // there is no web origin, so the builders return undefined and the caller skips
8
+ // the send. Tokens are credentials — callers hand these URLs to the mailer and
9
+ // never log them (hard rule 6).
10
+ /** Normalize WEB_APP_URL to an origin with no trailing slash; undefined ⇒ unset. */
11
+ export function webOrigin(webAppUrl) {
12
+ if (webAppUrl === undefined)
13
+ return undefined;
14
+ return webAppUrl.endsWith('/') ? webAppUrl.slice(0, -1) : webAppUrl;
15
+ }
16
+ /** `/reset-password?token=` — the set-password page reads `token` from
17
+ * searchParams. Used by password reset AND the migrated-user reconnect flow
18
+ * (see {@link buildReconnectLink}), which both set a password via this page. */
19
+ export function buildResetLink(webAppUrl, token) {
20
+ const origin = webOrigin(webAppUrl);
21
+ return origin === undefined
22
+ ? undefined
23
+ : `${origin}/reset-password?token=${encodeURIComponent(token)}`;
24
+ }
25
+ /** `/verify-email?token=` — finishes signup. */
26
+ export function buildVerificationLink(webAppUrl, token) {
27
+ const origin = webOrigin(webAppUrl);
28
+ return origin === undefined
29
+ ? undefined
30
+ : `${origin}/verify-email?token=${encodeURIComponent(token)}`;
31
+ }
32
+ /** Migrated-user reconnect link. A migrated account is
33
+ * pre-provisioned with no password; the user sets one via the same
34
+ * `/reset-password` set-password page and lands on their populated account. This
35
+ * is the canonical builder the launch-wave caller reuses so it never
36
+ * re-derives the WEB_APP_URL URL shape or builds a wrong-origin link. */
37
+ export function buildReconnectLink(webAppUrl, token) {
38
+ return buildResetLink(webAppUrl, token);
39
+ }
40
+ /** Public self-serve signup link for waitlist re-engagement.
41
+ * No token — it points at the open `/signup` page; no account is provisioned. */
42
+ export function buildSignupLink(webAppUrl) {
43
+ const origin = webOrigin(webAppUrl);
44
+ return origin === undefined ? undefined : `${origin}/signup`;
45
+ }
46
+ //# sourceMappingURL=links.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"links.js","sourceRoot":"","sources":["../src/links.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,2EAA2E;AAC3E,mEAAmE;AACnE,kEAAkE;AAClE,0EAA0E;AAC1E,iFAAiF;AACjF,gFAAgF;AAChF,+EAA+E;AAC/E,gCAAgC;AAEhC,oFAAoF;AACpF,MAAM,UAAU,SAAS,CAAC,SAA6B;IACrD,IAAI,SAAS,KAAK,SAAS;QAAE,OAAO,SAAS,CAAA;IAC7C,OAAO,SAAS,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAA;AACrE,CAAC;AAED;;gFAEgF;AAChF,MAAM,UAAU,cAAc,CAAC,SAA6B,EAAE,KAAa;IACzE,MAAM,MAAM,GAAG,SAAS,CAAC,SAAS,CAAC,CAAA;IACnC,OAAO,MAAM,KAAK,SAAS;QACzB,CAAC,CAAC,SAAS;QACX,CAAC,CAAC,GAAG,MAAM,yBAAyB,kBAAkB,CAAC,KAAK,CAAC,EAAE,CAAA;AACnE,CAAC;AAED,gDAAgD;AAChD,MAAM,UAAU,qBAAqB,CACnC,SAA6B,EAC7B,KAAa;IAEb,MAAM,MAAM,GAAG,SAAS,CAAC,SAAS,CAAC,CAAA;IACnC,OAAO,MAAM,KAAK,SAAS;QACzB,CAAC,CAAC,SAAS;QACX,CAAC,CAAC,GAAG,MAAM,uBAAuB,kBAAkB,CAAC,KAAK,CAAC,EAAE,CAAA;AACjE,CAAC;AAED;;;;yEAIyE;AACzE,MAAM,UAAU,kBAAkB,CAChC,SAA6B,EAC7B,KAAa;IAEb,OAAO,cAAc,CAAC,SAAS,EAAE,KAAK,CAAC,CAAA;AACzC,CAAC;AAED;iFACiF;AACjF,MAAM,UAAU,eAAe,CAAC,SAA6B;IAC3D,MAAM,MAAM,GAAG,SAAS,CAAC,SAAS,CAAC,CAAA;IACnC,OAAO,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,GAAG,MAAM,SAAS,CAAA;AAC9D,CAAC"}
@@ -0,0 +1,58 @@
1
+ import { type SmtpConfig } from '@3ngram/config';
2
+ /** The minimal transport surface the mailer needs — a seam for a mock in tests. */
3
+ export interface MailTransport {
4
+ sendMail(message: {
5
+ from: string;
6
+ to: string;
7
+ subject: string;
8
+ text: string;
9
+ }): Promise<{
10
+ messageId: string;
11
+ }>;
12
+ }
13
+ /** Builds a transport from resolved SMTP config. Default: a nodemailer transport. */
14
+ export type TransportFactory = (config: SmtpConfig) => MailTransport;
15
+ /** Outcome of an attempted reset-email send. `delivered: false` is never an error. */
16
+ export type SendResult = {
17
+ delivered: true;
18
+ messageId: string;
19
+ } | {
20
+ delivered: false;
21
+ reason: 'smtp-not-configured' | 'send-failed';
22
+ };
23
+ /** Dependencies the mailer resolves from env by default; overridable in tests. */
24
+ export interface MailerOptions {
25
+ /** Resolve SMTP config (undefined ⇒ not configured). Defaults to loadSmtpConfig. */
26
+ loadConfig?: () => SmtpConfig | undefined;
27
+ /** Build a transport from config. Defaults to the real nodemailer transport. */
28
+ transportFactory?: TransportFactory;
29
+ }
30
+ export declare function sendResetEmail(recipient: string, resetLink: string, options?: MailerOptions): Promise<SendResult>;
31
+ export declare function sendVerificationEmail(recipient: string, verificationLink: string, options?: MailerOptions): Promise<SendResult>;
32
+ /**
33
+ * Send the migrated-user reconnect email if SMTP is configured; otherwise
34
+ * degrade (same contract as sendResetEmail — never throws). `reconnectLink` is
35
+ * the existing set-password link the caller builds against WEB_APP_URL. Used by
36
+ * the legacy-migration launch wave. Logs neither recipient
37
+ * nor link (hard rule 6).
38
+ */
39
+ export declare function sendMigrationEmail(recipient: string, reconnectLink: string, options?: MailerOptions): Promise<SendResult>;
40
+ /**
41
+ * Send an arbitrary transactional email if SMTP is configured; otherwise degrade
42
+ * (same never-throw contract as the named senders above). This is the generic
43
+ * primitive a private surface reuses for its own notifications so the SMTP
44
+ * transport, degrade-to-noop policy, and hard-rule-6 logging discipline all stay
45
+ * in THIS one module — the private package never re-wires nodemailer. `logLabel`
46
+ * MUST be a bounded, content-free tag; neither the recipient nor the body is ever
47
+ * logged.
48
+ */
49
+ export declare function sendTransactionalEmail(recipient: string, subject: string, text: string, logLabel: string, options?: MailerOptions): Promise<SendResult>;
50
+ /**
51
+ * Send a re-engagement email inviting a prior waitlist signup to self-serve
52
+ * signup. `signupLink` is the public signup URL — this does
53
+ * NOT provision an account. Same degrade-never-throw contract; logs neither
54
+ * recipient nor link.
55
+ */
56
+ export declare function sendReengagementEmail(recipient: string, signupLink: string, options?: MailerOptions): Promise<SendResult>;
57
+ /** True iff SMTP is configured — lets the route pick the delivery vs degraded copy. */
58
+ export declare function isMailerConfigured(loadConfig?: () => SmtpConfig | undefined): boolean;
package/dist/mailer.js ADDED
@@ -0,0 +1,187 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Password-reset email delivery (self-host hardening). SMTP is OPTIONAL by design: a self-hosted 3ngram must boot and
3
+ // serve forgot-password with NO mail server configured. This module is the one
4
+ // place that decides "send vs degrade" so the transport (auth.ts) stays thin
5
+ // (hard rule 5) and never re-derives SMTP config.
6
+ //
7
+ // Degradation contract: when SMTP is not configured (loadSmtpConfig() returns
8
+ // undefined), sendResetEmail returns { delivered: false, reason: 'smtp-not-
9
+ // configured' } — it does NOT throw. The caller then falls back to the
10
+ // documented owner-level reset / dev-token path. A transport failure at send
11
+ // time is ALSO non-fatal here: it returns { delivered: false, reason: 'send-
12
+ // failed' } so the route can still answer a uniform 200 (no user enumeration,
13
+ // ADR-0009) instead of leaking a 500 on a flaky MTA.
14
+ //
15
+ // Hard rule 6: SMTP_PASS and the recipient address never enter a log line — the
16
+ // mailer logs host/port and (on success) the transport message id only.
17
+ import { loadSmtpConfig, log } from '@3ngram/config';
18
+ import { createTransport } from 'nodemailer';
19
+ const RESET_SUBJECT = 'Reset your 3ngram password';
20
+ const VERIFY_SUBJECT = 'Verify your 3ngram email';
21
+ const MIGRATION_SUBJECT = 'Your 3ngram memory is ready';
22
+ const REENGAGEMENT_SUBJECT = 'Reconnect with 3ngram';
23
+ /** Build the nodemailer transport. `auth` is omitted for an unauthenticated relay. */
24
+ function defaultTransportFactory(config) {
25
+ return createTransport({
26
+ host: config.host,
27
+ port: config.port,
28
+ // STARTTLS on the submission port (587); implicit TLS on 465.
29
+ secure: config.port === 465,
30
+ ...(config.auth ? { auth: config.auth } : {}),
31
+ });
32
+ }
33
+ /** The plaintext body — the reset link only, no PII beyond what the user gave us. */
34
+ function resetBody(resetLink) {
35
+ return [
36
+ 'A password reset was requested for your 3ngram account.',
37
+ '',
38
+ 'Open this link to choose a new password:',
39
+ resetLink,
40
+ '',
41
+ 'If you did not request this, you can ignore this email.',
42
+ ].join('\n');
43
+ }
44
+ function verificationBody(verificationLink) {
45
+ return [
46
+ 'Verify this email address for your 3ngram account.',
47
+ '',
48
+ 'Open this link to finish signup:',
49
+ verificationLink,
50
+ '',
51
+ 'If you did not request this, you can ignore this email.',
52
+ ].join('\n');
53
+ }
54
+ /** Migrated-user reconnect body. `reconnectLink` is the existing set-password /
55
+ * reset link (built by the caller against WEB_APP_URL) pointing at the
56
+ * pre-provisioned, already-populated account — "your memory moved with you". */
57
+ function migrationBody(reconnectLink) {
58
+ return [
59
+ 'Your memory has moved to 3ngram, and your full history came with you.',
60
+ '',
61
+ 'Open this link to set your password and reconnect to your account:',
62
+ reconnectLink,
63
+ '',
64
+ 'After signing in, repoint your client to 3ngram (the dashboard has the connection details).',
65
+ ].join('\n');
66
+ }
67
+ /** Re-engagement body for a prior waitlist signup: self-serve signup is now
68
+ * open, so `signupLink` points at the public signup page — no account is
69
+ * provisioned for them (distinct from the migrated-user reconnect flow). */
70
+ function reengagementBody(signupLink) {
71
+ return [
72
+ '3ngram is now open, so you can create your account whenever you like.',
73
+ '',
74
+ 'Sign up here:',
75
+ signupLink,
76
+ '',
77
+ 'If you are no longer interested, you can ignore this email.',
78
+ ].join('\n');
79
+ }
80
+ /**
81
+ * Send the password-reset email if SMTP is configured; otherwise degrade.
82
+ *
83
+ * Returns `{ delivered: false }` (never throws) in two non-fatal cases:
84
+ * - SMTP not configured ⇒ reason 'smtp-not-configured' (the route falls back to
85
+ * the owner-level / dev-token path).
86
+ * - transport rejects at send time ⇒ reason 'send-failed' (the route still
87
+ * answers a uniform 200 — no enumeration on a flaky MTA).
88
+ *
89
+ * `recipient` and `resetLink` are caller-supplied; this module logs neither.
90
+ */
91
+ async function sendEmail(message, options = {}) {
92
+ const loadConfig = options.loadConfig ?? loadSmtpConfig;
93
+ const config = loadConfig();
94
+ if (config === undefined) {
95
+ log().info('mailer: SMTP not configured, degrading to owner-level email path');
96
+ return { delivered: false, reason: 'smtp-not-configured' };
97
+ }
98
+ const factory = options.transportFactory ?? defaultTransportFactory;
99
+ const transport = factory(config);
100
+ try {
101
+ const { messageId } = await transport.sendMail({
102
+ from: config.from,
103
+ to: message.recipient,
104
+ subject: message.subject,
105
+ text: message.text,
106
+ });
107
+ // host/port/message-id only — never the recipient or the link (hard rule 6).
108
+ log().info({ smtpHost: config.host, smtpPort: config.port, messageId }, message.successLog);
109
+ return { delivered: true, messageId };
110
+ }
111
+ catch {
112
+ log().warn({ smtpHost: config.host, smtpPort: config.port }, message.failureLog);
113
+ return { delivered: false, reason: 'send-failed' };
114
+ }
115
+ }
116
+ export async function sendResetEmail(recipient, resetLink, options = {}) {
117
+ return sendEmail({
118
+ recipient,
119
+ subject: RESET_SUBJECT,
120
+ text: resetBody(resetLink),
121
+ successLog: 'mailer: reset email sent',
122
+ failureLog: 'mailer: reset email send failed, degrading',
123
+ }, options);
124
+ }
125
+ export async function sendVerificationEmail(recipient, verificationLink, options = {}) {
126
+ return sendEmail({
127
+ recipient,
128
+ subject: VERIFY_SUBJECT,
129
+ text: verificationBody(verificationLink),
130
+ successLog: 'mailer: verification email sent',
131
+ failureLog: 'mailer: verification email send failed, degrading',
132
+ }, options);
133
+ }
134
+ /**
135
+ * Send the migrated-user reconnect email if SMTP is configured; otherwise
136
+ * degrade (same contract as sendResetEmail — never throws). `reconnectLink` is
137
+ * the existing set-password link the caller builds against WEB_APP_URL. Used by
138
+ * the legacy-migration launch wave. Logs neither recipient
139
+ * nor link (hard rule 6).
140
+ */
141
+ export async function sendMigrationEmail(recipient, reconnectLink, options = {}) {
142
+ return sendEmail({
143
+ recipient,
144
+ subject: MIGRATION_SUBJECT,
145
+ text: migrationBody(reconnectLink),
146
+ successLog: 'mailer: migration email sent',
147
+ failureLog: 'mailer: migration email send failed, degrading',
148
+ }, options);
149
+ }
150
+ /**
151
+ * Send an arbitrary transactional email if SMTP is configured; otherwise degrade
152
+ * (same never-throw contract as the named senders above). This is the generic
153
+ * primitive a private surface reuses for its own notifications so the SMTP
154
+ * transport, degrade-to-noop policy, and hard-rule-6 logging discipline all stay
155
+ * in THIS one module — the private package never re-wires nodemailer. `logLabel`
156
+ * MUST be a bounded, content-free tag; neither the recipient nor the body is ever
157
+ * logged.
158
+ */
159
+ export async function sendTransactionalEmail(recipient, subject, text, logLabel, options = {}) {
160
+ return sendEmail({
161
+ recipient,
162
+ subject,
163
+ text,
164
+ successLog: `mailer: ${logLabel} email sent`,
165
+ failureLog: `mailer: ${logLabel} email send failed, degrading`,
166
+ }, options);
167
+ }
168
+ /**
169
+ * Send a re-engagement email inviting a prior waitlist signup to self-serve
170
+ * signup. `signupLink` is the public signup URL — this does
171
+ * NOT provision an account. Same degrade-never-throw contract; logs neither
172
+ * recipient nor link.
173
+ */
174
+ export async function sendReengagementEmail(recipient, signupLink, options = {}) {
175
+ return sendEmail({
176
+ recipient,
177
+ subject: REENGAGEMENT_SUBJECT,
178
+ text: reengagementBody(signupLink),
179
+ successLog: 'mailer: re-engagement email sent',
180
+ failureLog: 'mailer: re-engagement email send failed, degrading',
181
+ }, options);
182
+ }
183
+ /** True iff SMTP is configured — lets the route pick the delivery vs degraded copy. */
184
+ export function isMailerConfigured(loadConfig = loadSmtpConfig) {
185
+ return loadConfig() !== undefined;
186
+ }
187
+ //# sourceMappingURL=mailer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mailer.js","sourceRoot":"","sources":["../src/mailer.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,sHAAsH;AACtH,+EAA+E;AAC/E,6EAA6E;AAC7E,kDAAkD;AAClD,EAAE;AACF,8EAA8E;AAC9E,4EAA4E;AAC5E,uEAAuE;AACvE,6EAA6E;AAC7E,6EAA6E;AAC7E,8EAA8E;AAC9E,qDAAqD;AACrD,EAAE;AACF,gFAAgF;AAChF,wEAAwE;AACxE,OAAO,EAAE,cAAc,EAAE,GAAG,EAAmB,MAAM,g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KAC/D,EACD,OAAO,CACR,CAAA;AACH,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,qBAAqB,CACzC,SAAiB,EACjB,UAAkB,EAClB,UAAyB,EAAE;IAE3B,OAAO,SAAS,CACd;QACE,SAAS;QACT,OAAO,EAAE,oBAAoB;QAC7B,IAAI,EAAE,gBAAgB,CAAC,UAAU,CAAC;QAClC,UAAU,EAAE,kCAAkC;QAC9C,UAAU,EAAE,oDAAoD;KACjE,EACD,OAAO,CACR,CAAA;AACH,CAAC;AAED,uFAAuF;AACvF,MAAM,UAAU,kBAAkB,CAChC,aAA2C,cAAc;IAEzD,OAAO,UAAU,EAAE,KAAK,SAAS,CAAA;AACnC,CAAC"}
@@ -0,0 +1,14 @@
1
+ import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
2
+ /** The SDK result a tool returns: a text content mirror plus structured output. */
3
+ type ToolResult = CallToolResult;
4
+ /**
5
+ * Map a thrown error to a typed isError tool result, or return undefined when the
6
+ * error is NOT a known typed core error (the caller then treats it as an internal
7
+ * fault). This is the verbatim catch ladder from {@link runTool}: each branch
8
+ * counts a metric under its reason_code, logs at the matching level (no content),
9
+ * and returns a class-named failure. Keeping it a pure mapper (error -> result |
10
+ * undefined) lets runTool own the metrics-call/log-call sequencing only for the
11
+ * unknown-error fallthrough.
12
+ */
13
+ export declare function mapToolError(toolName: string, err: unknown): ToolResult | undefined;
14
+ export {};
@@ -0,0 +1,175 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // MCP typed-error mapping — the runTool catch ladder extracted from tools.ts (a
3
+ // mechanical split ahead of the 500-line cap; NO behaviour change). Translates a
4
+ // KNOWN typed core error into a class-named isError tool result, counts it under
5
+ // the right reason_code, and logs at the right level — all WITHOUT ever emitting
6
+ // memory content, query text, subject/value, or a credential (observability hard
7
+ // rule 6: only the error class name + bounded ids/hashes/enum states).
8
+ import { log, mcpToolErrors } from '@3ngram/config';
9
+ import { AccessDeniedError, BudgetExceededError, CommitmentExistsError, CommitmentNotFoundError, DuplicateMemoryError, EdgeConflictError, EpisodicSupersessionError, IllegalCommitmentTransitionError, InvalidCommitmentTransitionError, InvalidEmbeddingError, MissingSelectorError, NotCommitmentMemoryError, PredecessorAlreadySupersededError, PredecessorNotFoundError,
10
+ // Admin tools: scope registry + proposal review typed errors —
11
+ // appended block. ProposalNotFoundError now also covers the accept path's
12
+ // not-open / not-owned guard.
13
+ ProposalNotFoundError, ScopeNameConflictError, ScopeNotFoundError, SuccessorNotLiveError, } from '@3ngram/core';
14
+ import { ZodError } from 'zod';
15
+ import { OutputValidationError } from '../output-validation.js';
16
+ /** Wrap a typed failure as an isError result. The message names the class only. */
17
+ function fail(message) {
18
+ return { content: [{ type: 'text', text: message }], isError: true };
19
+ }
20
+ /**
21
+ * Map a thrown error to a typed isError tool result, or return undefined when the
22
+ * error is NOT a known typed core error (the caller then treats it as an internal
23
+ * fault). This is the verbatim catch ladder from {@link runTool}: each branch
24
+ * counts a metric under its reason_code, logs at the matching level (no content),
25
+ * and returns a class-named failure. Keeping it a pure mapper (error -> result |
26
+ * undefined) lets runTool own the metrics-call/log-call sequencing only for the
27
+ * unknown-error fallthrough.
28
+ */
29
+ export function mapToolError(toolName, err) {
30
+ // A result that failed its OUTPUT schema is a SERVER fault —
31
+ // never invalid_input, which would blame the caller for our bug. Handlers
32
+ // parse outputs via parseOutput(), which wraps the ZodError so this branch
33
+ // can label it honestly. Logged at error (it is our defect) with bounded
34
+ // metadata only: issue count + schema field paths, never values (rule 6).
35
+ if (err instanceof OutputValidationError) {
36
+ mcpToolErrors.add(1, { tool_name: toolName, reason_code: 'invalid_output' });
37
+ log().error({ tool_name: toolName, err: err.name, issue_count: err.issueCount, paths: err.issuePaths }, 'mcp: tool result failed output validation');
38
+ return fail(`invalid_output: the server produced a ${toolName} result that failed output validation (${err.issueCount} issue(s)) — a server-side fault, not a problem with your input`);
39
+ }
40
+ // Malformed CLIENT input — a ZodError from the boundary INPUT .parse() or a
41
+ // typed core validation error — is a 400-class caller mistake, not a server
42
+ // fault: count it as invalid_input and log at warn (no content; only the
43
+ // error class name is recorded, hard rule 6). Output parses never throw a
44
+ // bare ZodError (they are wrapped above), so this branch is input-only.
45
+ if (err instanceof ZodError ||
46
+ err instanceof InvalidEmbeddingError ||
47
+ // A missing/empty orientation selector is the no-firehose guard (mcp-design.md):
48
+ // a 400-class caller mistake, not a server fault. Counted as invalid_input.
49
+ err instanceof MissingSelectorError) {
50
+ mcpToolErrors.add(1, { tool_name: toolName, reason_code: 'invalid_input' });
51
+ log().warn({ tool_name: toolName, err: err.name }, 'mcp: tool input rejected');
52
+ return fail(`invalid input: ${err.name}`);
53
+ }
54
+ // Over the per-user budget cap. A documented domain denial,
55
+ // not a server fault: a class-named isError result counted under budget_exceeded.
56
+ // Names ONLY the bounded operation key — never the cap/consumption or any
57
+ // cost internals.
58
+ if (err instanceof BudgetExceededError) {
59
+ mcpToolErrors.add(1, { tool_name: toolName, reason_code: 'budget_exceeded' });
60
+ log().warn({ tool_name: toolName, operation: err.operation }, 'mcp: over budget cap');
61
+ return fail(`budget_exceeded: ${toolName} would exceed your usage budget`);
62
+ }
63
+ // Access policy forbids the operation. A documented domain denial, not a server
64
+ // fault: a class-named isError result counted under access_denied. Names ONLY the
65
+ // bounded access kind — never any policy internals.
66
+ if (err instanceof AccessDeniedError) {
67
+ mcpToolErrors.add(1, { tool_name: toolName, reason_code: 'access_denied' });
68
+ log().warn({ tool_name: toolName, access: err.access }, 'mcp: access denied');
69
+ return fail(`access_denied: ${err.access} access is forbidden`);
70
+ }
71
+ // Re-submitting content already live for the tenant is a documented domain
72
+ // CONFLICT, not a server fault: surface a class-named conflict result and
73
+ // count it distinctly. The message names ONLY the content_hash the error
74
+ // carries (a hash, never the content — observability hard rule 6).
75
+ if (err instanceof DuplicateMemoryError) {
76
+ mcpToolErrors.add(1, { tool_name: toolName, reason_code: 'duplicate_memory' });
77
+ log().warn({ tool_name: toolName, content_hash: err.contentHash }, 'mcp: duplicate memory rejected');
78
+ return fail(`duplicate_memory: content already exists (contentHash ${err.contentHash})`);
79
+ }
80
+ // The parent memory a commitment would ride is not a live commitment-type
81
+ // memory — a 400-class caller mistake (a fixture/edge defensive map per the
82
+ // orchestrator decision), counted as invalid_input. Names the id only.
83
+ if (err instanceof NotCommitmentMemoryError) {
84
+ mcpToolErrors.add(1, { tool_name: toolName, reason_code: 'invalid_input' });
85
+ log().warn({ tool_name: toolName, err: err.name }, 'mcp: not a commitment memory');
86
+ return fail(`invalid input: ${err.name}`);
87
+ }
88
+ // The referenced entity does not exist for the tenant (RLS hides cross-tenant
89
+ // rows, so not-found and not-owned are one mapping). Names the missing id
90
+ // only — a uuid, never content.
91
+ if (err instanceof PredecessorNotFoundError) {
92
+ mcpToolErrors.add(1, { tool_name: toolName, reason_code: 'not_found' });
93
+ log().warn({ tool_name: toolName, err: err.name }, 'mcp: predecessor not found');
94
+ return fail(`not_found: predecessor ${err.predecessorId}`);
95
+ }
96
+ if (err instanceof CommitmentNotFoundError) {
97
+ mcpToolErrors.add(1, { tool_name: toolName, reason_code: 'not_found' });
98
+ log().warn({ tool_name: toolName, err: err.name }, 'mcp: commitment not found');
99
+ // keyedBy distinguishes the id the error carries: the memory-keyed resolve
100
+ // path looks up by memory id, so a miss must read "memory <id>", never
101
+ // mislabel it a commitment id. Default ('commitment') covers id-keyed misses
102
+ // and any legacy instance lacking the discriminator.
103
+ return fail(err.keyedBy === 'memory'
104
+ ? `not_found: no commitment for memory ${err.commitmentId}`
105
+ : `not_found: commitment ${err.commitmentId}`);
106
+ }
107
+ // A documented domain CONFLICT (already superseded, edge already exists, a
108
+ // commitment already rides the memory) — not a server fault. Names the class
109
+ // and an id/hash only, never content.
110
+ if (err instanceof PredecessorAlreadySupersededError) {
111
+ mcpToolErrors.add(1, { tool_name: toolName, reason_code: 'conflict' });
112
+ log().warn({ tool_name: toolName, err: err.name }, 'mcp: predecessor already superseded');
113
+ return fail(`conflict: predecessor already superseded (${err.predecessorId})`);
114
+ }
115
+ if (err instanceof EdgeConflictError) {
116
+ mcpToolErrors.add(1, { tool_name: toolName, reason_code: 'conflict' });
117
+ log().warn({ tool_name: toolName, err: err.name }, 'mcp: edge conflict');
118
+ return fail(`conflict: ${err.name}`);
119
+ }
120
+ if (err instanceof CommitmentExistsError) {
121
+ mcpToolErrors.add(1, { tool_name: toolName, reason_code: 'conflict' });
122
+ log().warn({ tool_name: toolName, err: err.name }, 'mcp: commitment already exists');
123
+ return fail(`conflict: commitment already exists (${err.memoryId})`);
124
+ }
125
+ // An illegal FSM transition (core's primary guard or the DB backstop). Names
126
+ // the from/to states only — both are bounded enum values, never content.
127
+ if (err instanceof InvalidCommitmentTransitionError ||
128
+ err instanceof IllegalCommitmentTransitionError) {
129
+ mcpToolErrors.add(1, { tool_name: toolName, reason_code: 'invalid_transition' });
130
+ log().warn({ tool_name: toolName, err: err.name, from: err.from, to: err.to }, 'mcp: illegal commitment transition');
131
+ return fail(`invalid_transition: ${err.from} -> ${err.to}`);
132
+ }
133
+ // --- Admin tools: scope registry + proposal review — appended ---
134
+ // A scope NAME collision (create/rename) is a documented domain CONFLICT, not a
135
+ // server fault. Names the colliding scope NAME (a bounded user label, not memory
136
+ // content) only.
137
+ if (err instanceof ScopeNameConflictError) {
138
+ mcpToolErrors.add(1, { tool_name: toolName, reason_code: 'conflict' });
139
+ log().warn({ tool_name: toolName, err: err.name }, 'mcp: scope name conflict');
140
+ return fail(`conflict: scope "${err.scopeName}" already exists`);
141
+ }
142
+ // The referenced scope / proposal does not exist for the tenant (RLS hides
143
+ // cross-tenant rows, so not-found and not-owned are one mapping). Names the
144
+ // missing scope NAME / proposal id only.
145
+ if (err instanceof ScopeNotFoundError) {
146
+ mcpToolErrors.add(1, { tool_name: toolName, reason_code: 'not_found' });
147
+ log().warn({ tool_name: toolName, err: err.name }, 'mcp: scope not found');
148
+ return fail(`not_found: scope "${err.scopeName}"`);
149
+ }
150
+ if (err instanceof ProposalNotFoundError) {
151
+ mcpToolErrors.add(1, { tool_name: toolName, reason_code: 'not_found' });
152
+ log().warn({ tool_name: toolName, err: err.name }, 'mcp: proposal not open / not found');
153
+ return fail(`not_found: open proposal ${err.proposalId}`);
154
+ }
155
+ // Accepting an event-type supersedes/updates proposal is refused (ADR-0005 §3
156
+ // episodic exclusion): a documented domain CONFLICT, not a server fault. Names
157
+ // the proposal id + memory_type (a bounded enum) only, never content.
158
+ if (err instanceof EpisodicSupersessionError) {
159
+ mcpToolErrors.add(1, { tool_name: toolName, reason_code: 'conflict' });
160
+ log().warn({ tool_name: toolName, err: err.name }, 'mcp: episodic supersession refused');
161
+ return fail(`conflict: event-type proposal ${err.proposalId} cannot supersede (ADR-0005)`);
162
+ }
163
+ // A fresh apply whose proposed SUCCESSOR (from_id) is no longer live — the
164
+ // proposal went stale while queued (a later revise superseded from_id), so
165
+ // applying would leave neither side of the knowledge live. A documented
166
+ // domain CONFLICT, not a server fault; the proposal stays open for the
167
+ // existing reject path. Names the proposal + memory ids only, never content.
168
+ if (err instanceof SuccessorNotLiveError) {
169
+ mcpToolErrors.add(1, { tool_name: toolName, reason_code: 'conflict' });
170
+ log().warn({ tool_name: toolName, err: err.name }, 'mcp: proposal successor no longer live');
171
+ return fail(`conflict: proposal ${err.proposalId} successor ${err.fromId} is no longer live; re-propose against the live successor or reject this proposal`);
172
+ }
173
+ return undefined;
174
+ }
175
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/mcp/errors.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,gFAAgF;AAChF,iFAAiF;AACjF,iFAAiF;AACjF,iFAAiF;AACjF,iFAAiF;AACjF,uEAAuE;AACvE,OAAO,EAAE,GAAG,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAA;AACnD,OAAO,EACL,iBAAiB,EACjB,mBAAmB,EACnB,qBAAqB,EACrB,uBAAuB,EACvB,oBAAoB,EACpB,iBAAiB,EACjB,yBA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