@open-mercato/channel-smtp 0.0.0-stage → 0.10.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 (62) hide show
  1. package/.turbo/turbo-build.log +2 -0
  2. package/build.mjs +7 -0
  3. package/dist/index.js +5 -0
  4. package/dist/index.js.map +7 -0
  5. package/dist/modules/channel_smtp/__integration__/TC-CHANNEL-SMTP-001.spec.js +97 -0
  6. package/dist/modules/channel_smtp/__integration__/TC-CHANNEL-SMTP-001.spec.js.map +7 -0
  7. package/dist/modules/channel_smtp/__integration__/meta.js +10 -0
  8. package/dist/modules/channel_smtp/__integration__/meta.js.map +7 -0
  9. package/dist/modules/channel_smtp/acl.js +10 -0
  10. package/dist/modules/channel_smtp/acl.js.map +7 -0
  11. package/dist/modules/channel_smtp/capabilities.js +10 -0
  12. package/dist/modules/channel_smtp/capabilities.js.map +7 -0
  13. package/dist/modules/channel_smtp/di.js +22 -0
  14. package/dist/modules/channel_smtp/di.js.map +7 -0
  15. package/dist/modules/channel_smtp/index.js +13 -0
  16. package/dist/modules/channel_smtp/index.js.map +7 -0
  17. package/dist/modules/channel_smtp/integration.js +96 -0
  18. package/dist/modules/channel_smtp/integration.js.map +7 -0
  19. package/dist/modules/channel_smtp/lib/adapter.js +127 -0
  20. package/dist/modules/channel_smtp/lib/adapter.js.map +7 -0
  21. package/dist/modules/channel_smtp/lib/credentials.js +44 -0
  22. package/dist/modules/channel_smtp/lib/credentials.js.map +7 -0
  23. package/dist/modules/channel_smtp/lib/health.js +35 -0
  24. package/dist/modules/channel_smtp/lib/health.js.map +7 -0
  25. package/dist/modules/channel_smtp/lib/preset.js +91 -0
  26. package/dist/modules/channel_smtp/lib/preset.js.map +7 -0
  27. package/dist/modules/channel_smtp/lib/system-email-config.js +13 -0
  28. package/dist/modules/channel_smtp/lib/system-email-config.js.map +7 -0
  29. package/dist/modules/channel_smtp/lib/transport.js +100 -0
  30. package/dist/modules/channel_smtp/lib/transport.js.map +7 -0
  31. package/dist/modules/channel_smtp/lib/validate-credentials.js +39 -0
  32. package/dist/modules/channel_smtp/lib/validate-credentials.js.map +7 -0
  33. package/dist/modules/channel_smtp/setup.js +30 -0
  34. package/dist/modules/channel_smtp/setup.js.map +7 -0
  35. package/jest.config.cjs +33 -0
  36. package/package.json +85 -3
  37. package/src/index.ts +1 -0
  38. package/src/modules/channel_smtp/__integration__/TC-CHANNEL-SMTP-001.spec.ts +133 -0
  39. package/src/modules/channel_smtp/__integration__/meta.ts +6 -0
  40. package/src/modules/channel_smtp/__tests__/contracts.test.ts +39 -0
  41. package/src/modules/channel_smtp/acl.ts +6 -0
  42. package/src/modules/channel_smtp/capabilities.ts +8 -0
  43. package/src/modules/channel_smtp/di.ts +20 -0
  44. package/src/modules/channel_smtp/index.ts +9 -0
  45. package/src/modules/channel_smtp/integration.ts +91 -0
  46. package/src/modules/channel_smtp/lib/__tests__/adapter.test.ts +250 -0
  47. package/src/modules/channel_smtp/lib/__tests__/credentials.test.ts +69 -0
  48. package/src/modules/channel_smtp/lib/__tests__/health.test.ts +67 -0
  49. package/src/modules/channel_smtp/lib/__tests__/preset.test.ts +156 -0
  50. package/src/modules/channel_smtp/lib/__tests__/transport.test.ts +20 -0
  51. package/src/modules/channel_smtp/lib/__tests__/validate-credentials.test.ts +100 -0
  52. package/src/modules/channel_smtp/lib/adapter.ts +155 -0
  53. package/src/modules/channel_smtp/lib/credentials.ts +77 -0
  54. package/src/modules/channel_smtp/lib/health.ts +47 -0
  55. package/src/modules/channel_smtp/lib/preset.ts +138 -0
  56. package/src/modules/channel_smtp/lib/system-email-config.ts +10 -0
  57. package/src/modules/channel_smtp/lib/transport.ts +166 -0
  58. package/src/modules/channel_smtp/lib/validate-credentials.ts +60 -0
  59. package/src/modules/channel_smtp/setup.ts +30 -0
  60. package/tsconfig.json +9 -0
  61. package/watch.mjs +7 -0
  62. package/README.md +0 -3
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/channel_smtp/lib/health.ts"],
4
+ "sourcesContent": ["import type { IntegrationScope } from '@open-mercato/shared/modules/integrations/types'\nimport { smtpCredentialsSchema } from './credentials'\nimport { credentialsToConnection, getSmtpTransport } from './transport'\n\ntype HealthCheckResult = {\n status: 'healthy' | 'unhealthy'\n message: string\n details: Record<string, unknown>\n}\n\nconst PROBE_TIMEOUT_MS = 8_000\n\nexport const channelSmtpHealthCheck = {\n async check(\n credentials: Record<string, unknown> | null,\n _scope: IntegrationScope,\n ): Promise<HealthCheckResult> {\n const parsed = smtpCredentialsSchema.safeParse(credentials ?? {})\n if (!parsed.success) {\n return {\n status: 'unhealthy',\n message: `SMTP credentials invalid: ${parsed.error.issues[0]?.message ?? 'unknown validation error'}`,\n details: { reason: 'invalid_credentials' },\n }\n }\n\n // `verify()` opens the connection, negotiates TLS and runs SMTP AUTH, so it\n // proves the same things a send needs without putting a message on the wire.\n // Kept inside the hub's 10s health budget via the transport's own timeouts.\n const connection = { ...credentialsToConnection(parsed.data), timeoutMs: PROBE_TIMEOUT_MS }\n try {\n await getSmtpTransport().verify(connection)\n return {\n status: 'healthy',\n message: 'SMTP relay accepted the credentials',\n details: { host: connection.host, port: connection.port, tls: connection.tls },\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : 'SMTP connection failed'\n return {\n status: 'unhealthy',\n message: `SMTP health check failed: ${message}`,\n details: { reason: 'connection_failed', host: connection.host, port: connection.port },\n }\n }\n },\n}\n"],
5
+ "mappings": "AACA,SAAS,6BAA6B;AACtC,SAAS,yBAAyB,wBAAwB;AAQ1D,MAAM,mBAAmB;AAElB,MAAM,yBAAyB;AAAA,EACpC,MAAM,MACJ,aACA,QAC4B;AAC5B,UAAM,SAAS,sBAAsB,UAAU,eAAe,CAAC,CAAC;AAChE,QAAI,CAAC,OAAO,SAAS;AACnB,aAAO;AAAA,QACL,QAAQ;AAAA,QACR,SAAS,6BAA6B,OAAO,MAAM,OAAO,CAAC,GAAG,WAAW,0BAA0B;AAAA,QACnG,SAAS,EAAE,QAAQ,sBAAsB;AAAA,MAC3C;AAAA,IACF;AAKA,UAAM,aAAa,EAAE,GAAG,wBAAwB,OAAO,IAAI,GAAG,WAAW,iBAAiB;AAC1F,QAAI;AACF,YAAM,iBAAiB,EAAE,OAAO,UAAU;AAC1C,aAAO;AAAA,QACL,QAAQ;AAAA,QACR,SAAS;AAAA,QACT,SAAS,EAAE,MAAM,WAAW,MAAM,MAAM,WAAW,MAAM,KAAK,WAAW,IAAI;AAAA,MAC/E;AAAA,IACF,SAAS,OAAO;AACd,YAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU;AACzD,aAAO;AAAA,QACL,QAAQ;AAAA,QACR,SAAS,6BAA6B,OAAO;AAAA,QAC7C,SAAS,EAAE,QAAQ,qBAAqB,MAAM,WAAW,MAAM,MAAM,WAAW,KAAK;AAAA,MACvF;AAAA,IACF;AAAA,EACF;AACF;",
6
+ "names": []
7
+ }
@@ -0,0 +1,91 @@
1
+ import { normalizeEnvString, resolveDefaultEmailFromAddress } from "@open-mercato/shared/lib/email/config";
2
+ import { createLogger } from "@open-mercato/shared/lib/logger";
3
+ import { getTelemetryRuntime } from "@open-mercato/shared/lib/telemetry/runtime";
4
+ import { ensureSystemEmailChannel } from "@open-mercato/core/modules/communication_channels/lib/ensure-system-email-channel";
5
+ import { isSelectedSystemEmailProvider } from "@open-mercato/core/modules/communication_channels/lib/system-email-provider-config";
6
+ import { smtpCapabilities } from "../capabilities.js";
7
+ import { SMTP_TLS_MODES } from "./credentials.js";
8
+ const logger = createLogger("channel_smtp");
9
+ const DEFAULT_PORT = 587;
10
+ const IMPLICIT_TLS_PORT = 465;
11
+ function resolvePort() {
12
+ const raw = normalizeEnvString(process.env.SMTP_PORT);
13
+ if (!raw) return DEFAULT_PORT;
14
+ const parsed = Number(raw);
15
+ return Number.isInteger(parsed) && parsed > 0 && parsed <= 65535 ? parsed : DEFAULT_PORT;
16
+ }
17
+ function resolveTlsMode(port) {
18
+ const raw = normalizeEnvString(process.env.SMTP_TLS)?.toLowerCase();
19
+ if (raw && SMTP_TLS_MODES.includes(raw)) return raw;
20
+ return port === IMPLICIT_TLS_PORT ? "tls" : "starttls";
21
+ }
22
+ function readSmtpEnvPreset() {
23
+ const host = normalizeEnvString(process.env.SMTP_HOST);
24
+ const user = normalizeEnvString(process.env.SMTP_USER);
25
+ const password = normalizeEnvString(process.env.SMTP_PASSWORD);
26
+ const fromAddress = resolveDefaultEmailFromAddress();
27
+ if (!host || !user || !password || !fromAddress) {
28
+ if (host && !(user && password && fromAddress)) {
29
+ logger.warn("SMTP_HOST is set but the SMTP preset is incomplete; skipping SMTP preset", {
30
+ missing: [
31
+ ...user ? [] : ["SMTP_USER"],
32
+ ...password ? [] : ["SMTP_PASSWORD"],
33
+ ...fromAddress ? [] : ["NOTIFICATIONS_EMAIL_FROM, EMAIL_FROM, or ADMIN_EMAIL"]
34
+ ]
35
+ });
36
+ }
37
+ return null;
38
+ }
39
+ const port = resolvePort();
40
+ return { host, port, tls: resolveTlsMode(port), user, password, fromAddress };
41
+ }
42
+ async function applySmtpEnvPreset(ctx) {
43
+ if (!isSelectedSystemEmailProvider("smtp")) return;
44
+ const preset = readSmtpEnvPreset();
45
+ if (!preset) return;
46
+ let credentialsService;
47
+ try {
48
+ credentialsService = ctx.container.resolve("integrationCredentialsService");
49
+ } catch {
50
+ return;
51
+ }
52
+ await credentialsService.save("channel_smtp", preset, {
53
+ tenantId: ctx.tenantId,
54
+ organizationId: ctx.organizationId,
55
+ userId: null
56
+ });
57
+ try {
58
+ const integrationStateService = ctx.container.resolve("integrationStateService");
59
+ await integrationStateService.upsert("channel_smtp", { isEnabled: true }, {
60
+ tenantId: ctx.tenantId,
61
+ organizationId: ctx.organizationId
62
+ });
63
+ } catch (err) {
64
+ logger.warn("Failed to enable the SMTP integration state; Integrations will read Disabled while email is live", {
65
+ err,
66
+ tenantId: ctx.tenantId,
67
+ organizationId: ctx.organizationId
68
+ });
69
+ getTelemetryRuntime()?.reportError(err, {
70
+ module: "channel_smtp",
71
+ code: "channel_smtp.preset_state_upsert_failed",
72
+ attributes: {
73
+ tenantId: ctx.tenantId,
74
+ organizationId: ctx.organizationId
75
+ }
76
+ });
77
+ }
78
+ await ensureSystemEmailChannel(ctx.em, {
79
+ tenantId: ctx.tenantId,
80
+ organizationId: ctx.organizationId,
81
+ providerKey: "smtp",
82
+ externalIdentifier: preset.fromAddress,
83
+ displayName: "SMTP system email",
84
+ capabilities: { ...smtpCapabilities }
85
+ });
86
+ }
87
+ export {
88
+ applySmtpEnvPreset,
89
+ readSmtpEnvPreset
90
+ };
91
+ //# sourceMappingURL=preset.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/channel_smtp/lib/preset.ts"],
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { AppContainer } from '@open-mercato/shared/lib/di/container'\nimport { normalizeEnvString, resolveDefaultEmailFromAddress } from '@open-mercato/shared/lib/email/config'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\nimport { ensureSystemEmailChannel } from '@open-mercato/core/modules/communication_channels/lib/ensure-system-email-channel'\nimport { isSelectedSystemEmailProvider } from '@open-mercato/core/modules/communication_channels/lib/system-email-provider-config'\nimport { smtpCapabilities } from '../capabilities'\nimport { SMTP_TLS_MODES, type SmtpTlsMode } from './credentials'\n\nconst logger = createLogger('channel_smtp')\n\nconst DEFAULT_PORT = 587\nconst IMPLICIT_TLS_PORT = 465\n\ntype PresetScope = {\n em: EntityManager\n container: AppContainer\n tenantId: string\n organizationId: string\n}\n\ntype CredentialsServiceLike = {\n save: (\n integrationId: string,\n credentials: Record<string, unknown>,\n scope: { organizationId: string; tenantId: string; userId?: string | null },\n ) => Promise<void>\n}\n\ntype IntegrationStateServiceLike = {\n upsert: (\n integrationId: string,\n input: { isEnabled: boolean },\n scope: { organizationId: string; tenantId: string },\n ) => Promise<unknown>\n}\n\nexport type SmtpEnvPreset = {\n host: string\n port: number\n tls: SmtpTlsMode\n user: string\n password: string\n fromAddress: string\n}\n\nfunction resolvePort(): number {\n const raw = normalizeEnvString(process.env.SMTP_PORT)\n if (!raw) return DEFAULT_PORT\n const parsed = Number(raw)\n return Number.isInteger(parsed) && parsed > 0 && parsed <= 65535 ? parsed : DEFAULT_PORT\n}\n\nfunction resolveTlsMode(port: number): SmtpTlsMode {\n const raw = normalizeEnvString(process.env.SMTP_TLS)?.toLowerCase()\n if (raw && (SMTP_TLS_MODES as readonly string[]).includes(raw)) return raw as SmtpTlsMode\n // Port 465 is implicit TLS by convention and speaks no STARTTLS, so defaulting\n // it to `starttls` would hand every operator who only set SMTP_PORT=465 a\n // connection that hangs on the greeting.\n return port === IMPLICIT_TLS_PORT ? 'tls' : 'starttls'\n}\n\nexport function readSmtpEnvPreset(): SmtpEnvPreset | null {\n const host = normalizeEnvString(process.env.SMTP_HOST)\n const user = normalizeEnvString(process.env.SMTP_USER)\n const password = normalizeEnvString(process.env.SMTP_PASSWORD)\n const fromAddress = resolveDefaultEmailFromAddress()\n if (!host || !user || !password || !fromAddress) {\n // A partially-filled SMTP block looks configured and seeds nothing, so name\n // what is missing instead of returning null in silence.\n if (host && !(user && password && fromAddress)) {\n logger.warn('SMTP_HOST is set but the SMTP preset is incomplete; skipping SMTP preset', {\n missing: [\n ...(user ? [] : ['SMTP_USER']),\n ...(password ? [] : ['SMTP_PASSWORD']),\n ...(fromAddress ? [] : ['NOTIFICATIONS_EMAIL_FROM, EMAIL_FROM, or ADMIN_EMAIL']),\n ],\n })\n }\n return null\n }\n const port = resolvePort()\n return { host, port, tls: resolveTlsMode(port), user, password, fromAddress }\n}\n\nexport async function applySmtpEnvPreset(ctx: PresetScope): Promise<void> {\n // Only the provider this instance actually selected seeds anything, so a leftover\n // SMTP_HOST on an instance that moved to `SYSTEM_EMAIL_PROVIDER=resend` no longer\n // advertises an Enabled SMTP integration and a connected channel nothing sends through.\n if (!isSelectedSystemEmailProvider('smtp')) return\n const preset = readSmtpEnvPreset()\n if (!preset) return\n\n let credentialsService: CredentialsServiceLike\n try {\n credentialsService = ctx.container.resolve('integrationCredentialsService') as CredentialsServiceLike\n } catch {\n return\n }\n\n await credentialsService.save('channel_smtp', preset, {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n userId: null,\n })\n\n try {\n const integrationStateService = ctx.container.resolve('integrationStateService') as IntegrationStateServiceLike\n await integrationStateService.upsert('channel_smtp', { isEnabled: true }, {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n })\n } catch (err) {\n logger.warn('Failed to enable the SMTP integration state; Integrations will read Disabled while email is live', {\n err,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n })\n getTelemetryRuntime()?.reportError(err, {\n module: 'channel_smtp',\n code: 'channel_smtp.preset_state_upsert_failed',\n attributes: {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n },\n })\n }\n\n await ensureSystemEmailChannel(ctx.em, {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n providerKey: 'smtp',\n externalIdentifier: preset.fromAddress,\n displayName: 'SMTP system email',\n capabilities: { ...smtpCapabilities },\n })\n}\n"],
5
+ "mappings": "AAEA,SAAS,oBAAoB,sCAAsC;AACnE,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AACpC,SAAS,gCAAgC;AACzC,SAAS,qCAAqC;AAC9C,SAAS,wBAAwB;AACjC,SAAS,sBAAwC;AAEjD,MAAM,SAAS,aAAa,cAAc;AAE1C,MAAM,eAAe;AACrB,MAAM,oBAAoB;AAkC1B,SAAS,cAAsB;AAC7B,QAAM,MAAM,mBAAmB,QAAQ,IAAI,SAAS;AACpD,MAAI,CAAC,IAAK,QAAO;AACjB,QAAM,SAAS,OAAO,GAAG;AACzB,SAAO,OAAO,UAAU,MAAM,KAAK,SAAS,KAAK,UAAU,QAAQ,SAAS;AAC9E;AAEA,SAAS,eAAe,MAA2B;AACjD,QAAM,MAAM,mBAAmB,QAAQ,IAAI,QAAQ,GAAG,YAAY;AAClE,MAAI,OAAQ,eAAqC,SAAS,GAAG,EAAG,QAAO;AAIvE,SAAO,SAAS,oBAAoB,QAAQ;AAC9C;AAEO,SAAS,oBAA0C;AACxD,QAAM,OAAO,mBAAmB,QAAQ,IAAI,SAAS;AACrD,QAAM,OAAO,mBAAmB,QAAQ,IAAI,SAAS;AACrD,QAAM,WAAW,mBAAmB,QAAQ,IAAI,aAAa;AAC7D,QAAM,cAAc,+BAA+B;AACnD,MAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,YAAY,CAAC,aAAa;AAG/C,QAAI,QAAQ,EAAE,QAAQ,YAAY,cAAc;AAC9C,aAAO,KAAK,4EAA4E;AAAA,QACtF,SAAS;AAAA,UACP,GAAI,OAAO,CAAC,IAAI,CAAC,WAAW;AAAA,UAC5B,GAAI,WAAW,CAAC,IAAI,CAAC,eAAe;AAAA,UACpC,GAAI,cAAc,CAAC,IAAI,CAAC,sDAAsD;AAAA,QAChF;AAAA,MACF,CAAC;AAAA,IACH;AACA,WAAO;AAAA,EACT;AACA,QAAM,OAAO,YAAY;AACzB,SAAO,EAAE,MAAM,MAAM,KAAK,eAAe,IAAI,GAAG,MAAM,UAAU,YAAY;AAC9E;AAEA,eAAsB,mBAAmB,KAAiC;AAIxE,MAAI,CAAC,8BAA8B,MAAM,EAAG;AAC5C,QAAM,SAAS,kBAAkB;AACjC,MAAI,CAAC,OAAQ;AAEb,MAAI;AACJ,MAAI;AACF,yBAAqB,IAAI,UAAU,QAAQ,+BAA+B;AAAA,EAC5E,QAAQ;AACN;AAAA,EACF;AAEA,QAAM,mBAAmB,KAAK,gBAAgB,QAAQ;AAAA,IACpD,UAAU,IAAI;AAAA,IACd,gBAAgB,IAAI;AAAA,IACpB,QAAQ;AAAA,EACV,CAAC;AAED,MAAI;AACF,UAAM,0BAA0B,IAAI,UAAU,QAAQ,yBAAyB;AAC/E,UAAM,wBAAwB,OAAO,gBAAgB,EAAE,WAAW,KAAK,GAAG;AAAA,MACxE,UAAU,IAAI;AAAA,MACd,gBAAgB,IAAI;AAAA,IACtB,CAAC;AAAA,EACH,SAAS,KAAK;AACZ,WAAO,KAAK,oGAAoG;AAAA,MAC9G;AAAA,MACA,UAAU,IAAI;AAAA,MACd,gBAAgB,IAAI;AAAA,IACtB,CAAC;AACD,wBAAoB,GAAG,YAAY,KAAK;AAAA,MACtC,QAAQ;AAAA,MACR,MAAM;AAAA,MACN,YAAY;AAAA,QACV,UAAU,IAAI;AAAA,QACd,gBAAgB,IAAI;AAAA,MACtB;AAAA,IACF,CAAC;AAAA,EACH;AAEA,QAAM,yBAAyB,IAAI,IAAI;AAAA,IACrC,UAAU,IAAI;AAAA,IACd,gBAAgB,IAAI;AAAA,IACpB,aAAa;AAAA,IACb,oBAAoB,OAAO;AAAA,IAC3B,aAAa;AAAA,IACb,cAAc,EAAE,GAAG,iBAAiB;AAAA,EACtC,CAAC;AACH;",
6
+ "names": []
7
+ }
@@ -0,0 +1,13 @@
1
+ import { registerSystemEmailProviderConfigResolver } from "@open-mercato/core/modules/communication_channels/lib/system-email-provider-config";
2
+ import { readSmtpEnvPreset } from "./preset.js";
3
+ function registerSmtpSystemEmailConfigResolver() {
4
+ registerSystemEmailProviderConfigResolver({
5
+ providerKey: "smtp",
6
+ isConfigured: () => Boolean(readSmtpEnvPreset()),
7
+ resolveCredentials: ({ fromAddress }) => readSmtpEnvPreset() ?? { fromAddress }
8
+ });
9
+ }
10
+ export {
11
+ registerSmtpSystemEmailConfigResolver
12
+ };
13
+ //# sourceMappingURL=system-email-config.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/channel_smtp/lib/system-email-config.ts"],
4
+ "sourcesContent": ["import { registerSystemEmailProviderConfigResolver } from '@open-mercato/core/modules/communication_channels/lib/system-email-provider-config'\nimport { readSmtpEnvPreset } from './preset'\n\nexport function registerSmtpSystemEmailConfigResolver(): void {\n registerSystemEmailProviderConfigResolver({\n providerKey: 'smtp',\n isConfigured: () => Boolean(readSmtpEnvPreset()),\n resolveCredentials: ({ fromAddress }) => readSmtpEnvPreset() ?? { fromAddress },\n })\n}\n"],
5
+ "mappings": "AAAA,SAAS,iDAAiD;AAC1D,SAAS,yBAAyB;AAE3B,SAAS,wCAA8C;AAC5D,4CAA0C;AAAA,IACxC,aAAa;AAAA,IACb,cAAc,MAAM,QAAQ,kBAAkB,CAAC;AAAA,IAC/C,oBAAoB,CAAC,EAAE,YAAY,MAAM,kBAAkB,KAAK,EAAE,YAAY;AAAA,EAChF,CAAC;AACH;",
6
+ "names": []
7
+ }
@@ -0,0 +1,100 @@
1
+ import nodemailer from "nodemailer";
2
+ import { resolveSafeHostAddress } from "@open-mercato/shared/lib/host-pinning";
3
+ import {
4
+ allowsInsecureTransport,
5
+ allowsInternalHosts,
6
+ INSECURE_TRANSPORT_MESSAGE,
7
+ INTERNAL_HOST_MESSAGE,
8
+ UNRESOLVABLE_HOST_MESSAGE
9
+ } from "./credentials.js";
10
+ const DEFAULT_TIMEOUT_MS = 1e4;
11
+ async function createTransporter(connection) {
12
+ if (connection.tls === "none" && !allowsInsecureTransport()) {
13
+ throw new Error(`[internal] ${INSECURE_TRANSPORT_MESSAGE}`);
14
+ }
15
+ const pinned = await resolveSafeHostAddress(connection.host, {
16
+ allowInternal: allowsInternalHosts(),
17
+ internalMessage: INTERNAL_HOST_MESSAGE,
18
+ unresolvableMessage: UNRESOLVABLE_HOST_MESSAGE
19
+ });
20
+ const timeout = connection.timeoutMs ?? DEFAULT_TIMEOUT_MS;
21
+ return nodemailer.createTransport({
22
+ host: pinned.host,
23
+ port: connection.port,
24
+ secure: connection.tls === "tls",
25
+ requireTLS: connection.tls === "starttls",
26
+ auth: { user: connection.user, pass: connection.password },
27
+ connectionTimeout: timeout,
28
+ greetingTimeout: timeout,
29
+ socketTimeout: timeout,
30
+ // Certificate verification stays on for every encrypted mode; only an
31
+ // explicit `'none'` (already gated above) talks cleartext. A relay with a
32
+ // self-signed certificate is a misconfiguration to fix at the relay, not
33
+ // something to silently accept here.
34
+ tls: connection.tls === "none" ? void 0 : { rejectUnauthorized: true, ...pinned.servername ? { servername: pinned.servername } : {} }
35
+ });
36
+ }
37
+ function toAddressStrings(value) {
38
+ if (!Array.isArray(value)) return void 0;
39
+ return value.map((entry) => {
40
+ if (typeof entry === "string") return entry;
41
+ if (entry && typeof entry === "object" && "address" in entry) {
42
+ return String(entry.address);
43
+ }
44
+ return String(entry);
45
+ });
46
+ }
47
+ class NodemailerTransport {
48
+ async send(connection, message) {
49
+ const transporter = await createTransporter(connection);
50
+ try {
51
+ const info = await transporter.sendMail({
52
+ from: message.from,
53
+ to: message.to,
54
+ subject: message.subject,
55
+ ...message.text ? { text: message.text } : {},
56
+ ...message.html ? { html: message.html } : {},
57
+ ...message.replyTo ? { replyTo: message.replyTo } : {},
58
+ ...message.attachments?.length ? { attachments: message.attachments } : {}
59
+ });
60
+ return {
61
+ ...info,
62
+ ...toAddressStrings(info.accepted) ? { accepted: toAddressStrings(info.accepted) } : {},
63
+ ...toAddressStrings(info.rejected) ? { rejected: toAddressStrings(info.rejected) } : {}
64
+ };
65
+ } finally {
66
+ transporter.close();
67
+ }
68
+ }
69
+ async verify(connection) {
70
+ const transporter = await createTransporter(connection);
71
+ try {
72
+ await transporter.verify();
73
+ } finally {
74
+ transporter.close();
75
+ }
76
+ }
77
+ }
78
+ let cachedTransport = null;
79
+ function getSmtpTransport() {
80
+ if (!cachedTransport) cachedTransport = new NodemailerTransport();
81
+ return cachedTransport;
82
+ }
83
+ function setSmtpTransport(transport) {
84
+ cachedTransport = transport;
85
+ }
86
+ function credentialsToConnection(credentials) {
87
+ return {
88
+ host: credentials.host,
89
+ port: Number(credentials.port),
90
+ tls: credentials.tls,
91
+ user: credentials.user,
92
+ password: credentials.password
93
+ };
94
+ }
95
+ export {
96
+ credentialsToConnection,
97
+ getSmtpTransport,
98
+ setSmtpTransport
99
+ };
100
+ //# sourceMappingURL=transport.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/channel_smtp/lib/transport.ts"],
4
+ "sourcesContent": ["import nodemailer from 'nodemailer'\nimport { resolveSafeHostAddress } from '@open-mercato/shared/lib/host-pinning'\nimport {\n allowsInsecureTransport,\n allowsInternalHosts,\n INSECURE_TRANSPORT_MESSAGE,\n INTERNAL_HOST_MESSAGE,\n UNRESOLVABLE_HOST_MESSAGE,\n type SmtpCredentials,\n type SmtpTlsMode,\n} from './credentials'\n\nexport interface SmtpConnection {\n host: string\n port: number\n tls: SmtpTlsMode\n user: string\n password: string\n timeoutMs?: number\n}\n\nexport interface SmtpAttachment {\n filename: string\n content: string\n encoding: 'base64'\n contentType?: string\n}\n\nexport interface SmtpMessage {\n from: string\n to: string[]\n subject: string\n text?: string\n html?: string\n replyTo?: string\n attachments?: SmtpAttachment[]\n}\n\nexport interface SmtpSendInfo {\n messageId?: string\n response?: string\n /**\n * Nodemailer resolves the send as soon as the relay accepts *at least one*\n * recipient, reporting the split in `accepted`/`rejected`. Both are carried\n * through so the adapter can qualify a partial delivery instead of reporting\n * an unqualified success.\n */\n accepted?: string[]\n rejected?: string[]\n}\n\n/**\n * Thin seam over `nodemailer` so the adapter and the health check share one\n * connect path and tests can swap in a fake without reaching for module mocks.\n */\nexport interface SmtpTransport {\n send(connection: SmtpConnection, message: SmtpMessage): Promise<SmtpSendInfo>\n verify(connection: SmtpConnection): Promise<void>\n}\n\nconst DEFAULT_TIMEOUT_MS = 10_000\n\ntype Transporter = ReturnType<typeof nodemailer.createTransport>\n\nasync function createTransporter(connection: SmtpConnection): Promise<Transporter> {\n if (connection.tls === 'none' && !allowsInsecureTransport()) {\n throw new Error(`[internal] ${INSECURE_TRANSPORT_MESSAGE}`)\n }\n const pinned = await resolveSafeHostAddress(connection.host, {\n allowInternal: allowsInternalHosts(),\n internalMessage: INTERNAL_HOST_MESSAGE,\n unresolvableMessage: UNRESOLVABLE_HOST_MESSAGE,\n })\n const timeout = connection.timeoutMs ?? DEFAULT_TIMEOUT_MS\n return nodemailer.createTransport({\n host: pinned.host,\n port: connection.port,\n secure: connection.tls === 'tls',\n requireTLS: connection.tls === 'starttls',\n auth: { user: connection.user, pass: connection.password },\n connectionTimeout: timeout,\n greetingTimeout: timeout,\n socketTimeout: timeout,\n // Certificate verification stays on for every encrypted mode; only an\n // explicit `'none'` (already gated above) talks cleartext. A relay with a\n // self-signed certificate is a misconfiguration to fix at the relay, not\n // something to silently accept here.\n tls:\n connection.tls === 'none'\n ? undefined\n : { rejectUnauthorized: true, ...(pinned.servername ? { servername: pinned.servername } : {}) },\n })\n}\n\n/**\n * Nodemailer reports `accepted`/`rejected` as addresses or `{ address }`\n * objects depending on how the envelope was built; flatten both to plain\n * strings so the adapter has one shape to reason about.\n */\nfunction toAddressStrings(value: unknown): string[] | undefined {\n if (!Array.isArray(value)) return undefined\n return value.map((entry) => {\n if (typeof entry === 'string') return entry\n if (entry && typeof entry === 'object' && 'address' in entry) {\n return String((entry as { address: unknown }).address)\n }\n return String(entry)\n })\n}\n\nclass NodemailerTransport implements SmtpTransport {\n async send(connection: SmtpConnection, message: SmtpMessage): Promise<SmtpSendInfo> {\n const transporter = await createTransporter(connection)\n try {\n const info = (await transporter.sendMail({\n from: message.from,\n to: message.to,\n subject: message.subject,\n ...(message.text ? { text: message.text } : {}),\n ...(message.html ? { html: message.html } : {}),\n ...(message.replyTo ? { replyTo: message.replyTo } : {}),\n ...(message.attachments?.length ? { attachments: message.attachments } : {}),\n })) as SmtpSendInfo\n return {\n ...info,\n ...(toAddressStrings(info.accepted) ? { accepted: toAddressStrings(info.accepted) } : {}),\n ...(toAddressStrings(info.rejected) ? { rejected: toAddressStrings(info.rejected) } : {}),\n }\n } finally {\n // Close on every path: a failed send (bad password, unreachable relay \u2014\n // the common case) would otherwise leak the socket pool.\n transporter.close()\n }\n }\n\n async verify(connection: SmtpConnection): Promise<void> {\n const transporter = await createTransporter(connection)\n try {\n await transporter.verify()\n } finally {\n transporter.close()\n }\n }\n}\n\nlet cachedTransport: SmtpTransport | null = null\n\nexport function getSmtpTransport(): SmtpTransport {\n if (!cachedTransport) cachedTransport = new NodemailerTransport()\n return cachedTransport\n}\n\n/** Test-only hook; pass `null` to restore the real nodemailer transport. */\nexport function setSmtpTransport(transport: SmtpTransport | null): void {\n cachedTransport = transport\n}\n\nexport function credentialsToConnection(credentials: SmtpCredentials): SmtpConnection {\n return {\n host: credentials.host,\n port: Number(credentials.port),\n tls: credentials.tls,\n user: credentials.user,\n password: credentials.password,\n }\n}\n"],
5
+ "mappings": "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",
6
+ "names": []
7
+ }
@@ -0,0 +1,39 @@
1
+ import { createLogger } from "@open-mercato/shared/lib/logger";
2
+ import { smtpCredentialsSchema } from "./credentials.js";
3
+ import { credentialsToConnection, getSmtpTransport } from "./transport.js";
4
+ const logger = createLogger("channel_smtp");
5
+ const PROBE_TIMEOUT_MS = 8e3;
6
+ async function validateSmtpCredentials(rawCredentials) {
7
+ const parsed = smtpCredentialsSchema.safeParse(rawCredentials ?? {});
8
+ if (!parsed.success) {
9
+ const errors = {};
10
+ for (const issue of parsed.error.issues) {
11
+ const path = issue.path[0];
12
+ if (typeof path !== "string") continue;
13
+ if (!errors[path]) errors[path] = issue.message;
14
+ }
15
+ return { ok: false, errors };
16
+ }
17
+ const connection = { ...credentialsToConnection(parsed.data), timeoutMs: PROBE_TIMEOUT_MS };
18
+ try {
19
+ await getSmtpTransport().verify(connection);
20
+ } catch (error) {
21
+ return { ok: false, errors: { password: classifyAuthError(error) } };
22
+ }
23
+ return { ok: true };
24
+ }
25
+ function classifyAuthError(error) {
26
+ const message = error instanceof Error ? error.message : String(error ?? "");
27
+ logger.warn("SMTP credential validation failed", { message });
28
+ if (/auth|login|credentials|535|454|530/i.test(message)) {
29
+ return "Authentication rejected by the relay. Check the username and password.";
30
+ }
31
+ if (/timeout|ETIMEDOUT|ECONNREFUSED|ENOTFOUND|EAI_AGAIN/i.test(message)) {
32
+ return "Could not reach the relay. Check the host and port.";
33
+ }
34
+ return "SMTP relay refused the credentials.";
35
+ }
36
+ export {
37
+ validateSmtpCredentials
38
+ };
39
+ //# sourceMappingURL=validate-credentials.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/channel_smtp/lib/validate-credentials.ts"],
4
+ "sourcesContent": ["import type { ValidateCredentialsResult } from '@open-mercato/core/modules/communication_channels/lib/adapter'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { smtpCredentialsSchema } from './credentials'\nimport { credentialsToConnection, getSmtpTransport } from './transport'\n\nconst logger = createLogger('channel_smtp')\n\nconst PROBE_TIMEOUT_MS = 8_000\n\n/**\n * Validate SMTP relay credentials before the hub persists them.\n *\n * The connect command accepts adapters without this method optimistically, which\n * for a provider whose host is operator-supplied would mean a loopback relay or a\n * cleartext transport is saved and only refused later, at send time. The schema\n * already encodes both refusals, so surfacing them here turns them into\n * field-level errors the connect form can inline-highlight \u2014 the same two-layer\n * treatment `channel-imap` gives the identical surface.\n *\n * Then `verify()` runs a real handshake plus AUTH, so a typo'd host or a rejected\n * password fails at setup rather than on the first transactional email.\n */\nexport async function validateSmtpCredentials(\n rawCredentials: unknown,\n): Promise<ValidateCredentialsResult> {\n const parsed = smtpCredentialsSchema.safeParse(rawCredentials ?? {})\n if (!parsed.success) {\n const errors: Record<string, string> = {}\n for (const issue of parsed.error.issues) {\n const path = issue.path[0]\n if (typeof path !== 'string') continue\n // First error wins per field \u2014 CrudForm only renders one per field anyway.\n if (!errors[path]) errors[path] = issue.message\n }\n return { ok: false, errors }\n }\n\n const connection = { ...credentialsToConnection(parsed.data), timeoutMs: PROBE_TIMEOUT_MS }\n try {\n await getSmtpTransport().verify(connection)\n } catch (error) {\n return { ok: false, errors: { password: classifyAuthError(error) } }\n }\n\n return { ok: true }\n}\n\nfunction classifyAuthError(error: unknown): string {\n // Never echo raw relay text (banners, internal hostnames) back to the client;\n // keep the full message server-side for diagnostics.\n const message = error instanceof Error ? error.message : String(error ?? '')\n logger.warn('SMTP credential validation failed', { message })\n if (/auth|login|credentials|535|454|530/i.test(message)) {\n return 'Authentication rejected by the relay. Check the username and password.'\n }\n if (/timeout|ETIMEDOUT|ECONNREFUSED|ENOTFOUND|EAI_AGAIN/i.test(message)) {\n return 'Could not reach the relay. Check the host and port.'\n }\n return 'SMTP relay refused the credentials.'\n}\n"],
5
+ "mappings": "AACA,SAAS,oBAAoB;AAC7B,SAAS,6BAA6B;AACtC,SAAS,yBAAyB,wBAAwB;AAE1D,MAAM,SAAS,aAAa,cAAc;AAE1C,MAAM,mBAAmB;AAezB,eAAsB,wBACpB,gBACoC;AACpC,QAAM,SAAS,sBAAsB,UAAU,kBAAkB,CAAC,CAAC;AACnE,MAAI,CAAC,OAAO,SAAS;AACnB,UAAM,SAAiC,CAAC;AACxC,eAAW,SAAS,OAAO,MAAM,QAAQ;AACvC,YAAM,OAAO,MAAM,KAAK,CAAC;AACzB,UAAI,OAAO,SAAS,SAAU;AAE9B,UAAI,CAAC,OAAO,IAAI,EAAG,QAAO,IAAI,IAAI,MAAM;AAAA,IAC1C;AACA,WAAO,EAAE,IAAI,OAAO,OAAO;AAAA,EAC7B;AAEA,QAAM,aAAa,EAAE,GAAG,wBAAwB,OAAO,IAAI,GAAG,WAAW,iBAAiB;AAC1F,MAAI;AACF,UAAM,iBAAiB,EAAE,OAAO,UAAU;AAAA,EAC5C,SAAS,OAAO;AACd,WAAO,EAAE,IAAI,OAAO,QAAQ,EAAE,UAAU,kBAAkB,KAAK,EAAE,EAAE;AAAA,EACrE;AAEA,SAAO,EAAE,IAAI,KAAK;AACpB;AAEA,SAAS,kBAAkB,OAAwB;AAGjD,QAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,SAAS,EAAE;AAC3E,SAAO,KAAK,qCAAqC,EAAE,QAAQ,CAAC;AAC5D,MAAI,sCAAsC,KAAK,OAAO,GAAG;AACvD,WAAO;AAAA,EACT;AACA,MAAI,sDAAsD,KAAK,OAAO,GAAG;AACvE,WAAO;AAAA,EACT;AACA,SAAO;AACT;",
6
+ "names": []
7
+ }
@@ -0,0 +1,30 @@
1
+ import {
2
+ hasChannelAdapter,
3
+ registerChannelAdapter
4
+ } from "@open-mercato/core/modules/communication_channels/lib/adapter-registry-singleton";
5
+ import { getSmtpChannelAdapter } from "./lib/adapter.js";
6
+ import { applySmtpEnvPreset } from "./lib/preset.js";
7
+ import { registerSmtpSystemEmailConfigResolver } from "./lib/system-email-config.js";
8
+ function ensureSmtpAdapterRegistered() {
9
+ if (hasChannelAdapter("smtp")) return;
10
+ registerChannelAdapter(getSmtpChannelAdapter());
11
+ }
12
+ ensureSmtpAdapterRegistered();
13
+ registerSmtpSystemEmailConfigResolver();
14
+ const setup = {
15
+ defaultRoleFeatures: {
16
+ superadmin: ["channel_smtp.view", "channel_smtp.configure"],
17
+ admin: ["channel_smtp.view", "channel_smtp.configure"]
18
+ },
19
+ async seedDefaults(ctx) {
20
+ ensureSmtpAdapterRegistered();
21
+ registerSmtpSystemEmailConfigResolver();
22
+ await applySmtpEnvPreset(ctx);
23
+ }
24
+ };
25
+ var setup_default = setup;
26
+ export {
27
+ setup_default as default,
28
+ setup
29
+ };
30
+ //# sourceMappingURL=setup.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/modules/channel_smtp/setup.ts"],
4
+ "sourcesContent": ["import type { ModuleSetupConfig } from '@open-mercato/shared/modules/setup'\nimport {\n hasChannelAdapter,\n registerChannelAdapter,\n} from '@open-mercato/core/modules/communication_channels/lib/adapter-registry-singleton'\nimport { getSmtpChannelAdapter } from './lib/adapter'\nimport { applySmtpEnvPreset } from './lib/preset'\nimport { registerSmtpSystemEmailConfigResolver } from './lib/system-email-config'\n\nfunction ensureSmtpAdapterRegistered(): void {\n if (hasChannelAdapter('smtp')) return\n registerChannelAdapter(getSmtpChannelAdapter())\n}\n\nensureSmtpAdapterRegistered()\nregisterSmtpSystemEmailConfigResolver()\n\nexport const setup: ModuleSetupConfig = {\n defaultRoleFeatures: {\n superadmin: ['channel_smtp.view', 'channel_smtp.configure'],\n admin: ['channel_smtp.view', 'channel_smtp.configure'],\n },\n async seedDefaults(ctx) {\n ensureSmtpAdapterRegistered()\n registerSmtpSystemEmailConfigResolver()\n await applySmtpEnvPreset(ctx)\n },\n}\n\nexport default setup\n"],
5
+ "mappings": "AACA;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,6BAA6B;AACtC,SAAS,0BAA0B;AACnC,SAAS,6CAA6C;AAEtD,SAAS,8BAAoC;AAC3C,MAAI,kBAAkB,MAAM,EAAG;AAC/B,yBAAuB,sBAAsB,CAAC;AAChD;AAEA,4BAA4B;AAC5B,sCAAsC;AAE/B,MAAM,QAA2B;AAAA,EACtC,qBAAqB;AAAA,IACnB,YAAY,CAAC,qBAAqB,wBAAwB;AAAA,IAC1D,OAAO,CAAC,qBAAqB,wBAAwB;AAAA,EACvD;AAAA,EACA,MAAM,aAAa,KAAK;AACtB,gCAA4B;AAC5B,0CAAsC;AACtC,UAAM,mBAAmB,GAAG;AAAA,EAC9B;AACF;AAEA,IAAO,gBAAQ;",
6
+ "names": []
7
+ }
@@ -0,0 +1,33 @@
1
+ /** @type {import('jest').Config} */
2
+ const base = require('../../jest.config.base.cjs')
3
+
4
+ module.exports = {
5
+ ...base,
6
+ testEnvironment: 'node',
7
+ watchman: false,
8
+ rootDir: '.',
9
+ moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json'],
10
+ moduleNameMapper: {
11
+ '^@open-mercato/channel-smtp/(.*)$': '<rootDir>/src/$1',
12
+ '^@open-mercato/core/(.*)$': '<rootDir>/../core/src/$1',
13
+ '^@open-mercato/shared/(.*)$': '<rootDir>/../shared/src/$1',
14
+ '^@open-mercato/ui/(.*)$': '<rootDir>/../ui/src/$1',
15
+ },
16
+ transform: {
17
+ '^.+\\.(t|j)sx?$': [
18
+ '<rootDir>/../../scripts/jest-mikroorm-transformer.cjs',
19
+ {
20
+ tsconfig: {
21
+ jsx: 'react-jsx',
22
+ rootDir: '.',
23
+ ignoreDeprecations: '6.0',
24
+ },
25
+ },
26
+ ],
27
+ },
28
+ transformIgnorePatterns: [
29
+ 'node_modules/(?!(sanitize-html|htmlparser2|domhandler|domutils|dom-serializer|domelementtype|entities|@mikro-orm|kysely)/)',
30
+ ],
31
+ testMatch: ['<rootDir>/src/**/__tests__/**/*.test.(ts|tsx)'],
32
+ passWithNoTests: true,
33
+ }
package/package.json CHANGED
@@ -1,6 +1,88 @@
1
1
  {
2
2
  "name": "@open-mercato/channel-smtp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.10.0",
4
+ "license": "MIT",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "scripts": {
8
+ "build": "node build.mjs",
9
+ "watch": "node watch.mjs",
10
+ "test": "jest --config jest.config.cjs",
11
+ "typecheck": "tsc --noEmit"
12
+ },
13
+ "exports": {
14
+ ".": "./dist/index.js",
15
+ "./*.ts": {
16
+ "types": "./src/*.ts",
17
+ "default": "./dist/*.js"
18
+ },
19
+ "./*.tsx": {
20
+ "types": "./src/*.tsx",
21
+ "default": "./dist/*.js"
22
+ },
23
+ "./*": {
24
+ "types": [
25
+ "./src/*.ts",
26
+ "./src/*.tsx"
27
+ ],
28
+ "default": "./dist/*.js"
29
+ },
30
+ "./*/*": {
31
+ "types": [
32
+ "./src/*/*.ts",
33
+ "./src/*/*.tsx"
34
+ ],
35
+ "default": "./dist/*/*.js"
36
+ },
37
+ "./*/*/*": {
38
+ "types": [
39
+ "./src/*/*/*.ts",
40
+ "./src/*/*/*.tsx"
41
+ ],
42
+ "default": "./dist/*/*/*.js"
43
+ },
44
+ "./*/*/*/*": {
45
+ "types": [
46
+ "./src/*/*/*/*.ts",
47
+ "./src/*/*/*/*.tsx"
48
+ ],
49
+ "default": "./dist/*/*/*/*.js"
50
+ }
51
+ },
52
+ "dependencies": {
53
+ "@open-mercato/core": "0.10.0",
54
+ "@types/nodemailer": "^8.0.1",
55
+ "nodemailer": "^10.0.10"
56
+ },
57
+ "peerDependencies": {
58
+ "@mikro-orm/postgresql": "^7.0.14",
59
+ "@open-mercato/ai-assistant": "0.10.0",
60
+ "@open-mercato/shared": "0.10.0",
61
+ "@open-mercato/ui": "0.10.0",
62
+ "react": "^19.0.0",
63
+ "react-dom": "^19.0.0"
64
+ },
65
+ "devDependencies": {
66
+ "@open-mercato/ai-assistant": "0.10.0",
67
+ "@open-mercato/shared": "0.10.0",
68
+ "@open-mercato/ui": "0.10.0",
69
+ "@types/jest": "^30.0.0",
70
+ "@types/react": "^19.2.18",
71
+ "@types/react-dom": "^19.2.5",
72
+ "esbuild": "^0.28.2",
73
+ "glob": "^14.0.6",
74
+ "jest": "^30.4.2",
75
+ "react": "19.2.8",
76
+ "react-dom": "19.2.8",
77
+ "ts-jest": "^29.4.11",
78
+ "typescript": "7.0.2"
79
+ },
80
+ "publishConfig": {
81
+ "access": "public"
82
+ },
83
+ "repository": {
84
+ "type": "git",
85
+ "url": "https://github.com/open-mercato/open-mercato",
86
+ "directory": "packages/channel-smtp"
87
+ }
6
88
  }
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export { metadata } from './modules/channel_smtp/index'
@@ -0,0 +1,133 @@
1
+ import { expect, test } from '@playwright/test'
2
+ import { getAuthToken } from '@open-mercato/core/helpers/integration/authFixtures'
3
+ import { apiRequest } from '@open-mercato/core/helpers/integration/api'
4
+ import { readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures'
5
+
6
+ /**
7
+ * TC-CHANNEL-SMTP-001 — SMTP provider registration, tenant scope and the
8
+ * save-time safety refusals.
9
+ *
10
+ * `@open-mercato/channel-smtp` registers the `smtp` email `ChannelAdapter` with
11
+ * `channelScope: 'tenant'`. That declaration is load-bearing: `sendSystemEmail`
12
+ * only ever resolves tenant-wide rows, so a per-user SMTP channel would be
13
+ * invisible to system email. The credential-connect routes are where both the
14
+ * registration and the scope become observable:
15
+ *
16
+ * - the **per-user** route short-circuits tenant-scoped providers with 403
17
+ * (`provider_is_tenant_scoped`) before touching credentials — 403 rather than
18
+ * 404 (`no_adapter`) proves the adapter is registered, and it stops a
19
+ * non-admin minting a tenant-wide relay;
20
+ * - the **tenant** route runs the adapter's own `validateCredentials`, so the
21
+ * relay host is an operator-supplied SSRF surface that must be refused at
22
+ * save time, not merely at send time.
23
+ *
24
+ * Every case here fails validation, so no channel is created and there is
25
+ * nothing to clean up. The relay round-trip (rendering, replyTo, attachments,
26
+ * the raw-string recipient the hub test-send route passes, and partial
27
+ * recipient rejection) is covered network-free in
28
+ * `lib/__tests__/adapter.test.ts` and `lib/__tests__/validate-credentials.test.ts`.
29
+ */
30
+ const TENANT_CONNECT = '/api/communication_channels/channels/connect/tenant-credentials'
31
+ const PER_USER_CONNECT = '/api/communication_channels/channels/connect/credentials'
32
+
33
+ const validRelay = {
34
+ host: 'smtp.example.com',
35
+ port: 587,
36
+ tls: 'starttls',
37
+ user: 'mailer',
38
+ password: 'not-a-real-password',
39
+ fromAddress: 'no-reply@example.com',
40
+ }
41
+
42
+ test.describe('TC-CHANNEL-SMTP-001: SMTP provider registration and safety refusals', () => {
43
+ test('per-user connect with providerKey=smtp is refused (403, tenant-scoped)', async ({
44
+ request,
45
+ }) => {
46
+ const token = await getAuthToken(request)
47
+ const response = await apiRequest(request, 'POST', PER_USER_CONNECT, {
48
+ token,
49
+ data: {
50
+ providerKey: 'smtp',
51
+ displayName: 'SMTP — per-user (should be refused)',
52
+ credentials: validRelay,
53
+ },
54
+ })
55
+
56
+ expect(response.status(), 'route should not 5xx').toBeLessThan(500)
57
+ expect(response.status(), 'authenticated request should not 401').not.toBe(401)
58
+ expect(response.status()).toBe(403)
59
+ const body = await readJsonSafe<{ code?: string }>(response)
60
+ expect(body?.code).toBe('provider_is_tenant_scoped')
61
+ })
62
+
63
+ test('tenant connect with empty credentials reaches validateCredentials (422)', async ({
64
+ request,
65
+ }) => {
66
+ const token = await getAuthToken(request)
67
+ const response = await apiRequest(request, 'POST', TENANT_CONNECT, {
68
+ token,
69
+ data: { providerKey: 'smtp', displayName: 'SMTP — tenant connect', credentials: {} },
70
+ })
71
+
72
+ expect(response.status(), 'route should not 5xx').toBeLessThan(500)
73
+ // Asserting 422 (not merely "not 404") proves the request authenticated AND
74
+ // reached the adapter — a 401 auth misconfig would let this pass vacuously.
75
+ expect(response.status(), 'authenticated request should not 401').not.toBe(401)
76
+ expect(response.status(), 'registered adapter should reject empty credentials').toBe(422)
77
+ const body = await readJsonSafe<{ fieldErrors?: Record<string, string> }>(response)
78
+ expect(Object.keys(body?.fieldErrors ?? {})).toEqual(
79
+ expect.arrayContaining(['host', 'user', 'password', 'fromAddress']),
80
+ )
81
+ })
82
+
83
+ test('tenant connect refuses a loopback relay host before persisting anything', async ({
84
+ request,
85
+ }) => {
86
+ const token = await getAuthToken(request)
87
+ const response = await apiRequest(request, 'POST', TENANT_CONNECT, {
88
+ token,
89
+ data: {
90
+ providerKey: 'smtp',
91
+ displayName: 'SMTP — loopback relay (should be refused)',
92
+ credentials: { ...validRelay, host: '127.0.0.1' },
93
+ },
94
+ })
95
+
96
+ expect(response.status(), 'route should not 5xx').toBeLessThan(500)
97
+ expect(response.status(), 'a loopback relay host must be refused at save time').toBe(422)
98
+ const body = await readJsonSafe<{ fieldErrors?: Record<string, string> }>(response)
99
+ expect(body?.fieldErrors?.host, 'the refusal must name the host field').toMatch(
100
+ /private or loopback/i,
101
+ )
102
+ })
103
+
104
+ test('tenant connect refuses cleartext transport without the operator opt-in', async ({
105
+ request,
106
+ }) => {
107
+ const token = await getAuthToken(request)
108
+ const response = await apiRequest(request, 'POST', TENANT_CONNECT, {
109
+ token,
110
+ data: {
111
+ providerKey: 'smtp',
112
+ displayName: 'SMTP — cleartext (should be refused)',
113
+ credentials: { ...validRelay, tls: 'none', port: 25 },
114
+ },
115
+ })
116
+
117
+ expect(response.status(), 'route should not 5xx').toBeLessThan(500)
118
+ expect(response.status(), 'cleartext must be refused unless opted in').toBe(422)
119
+ const body = await readJsonSafe<{ fieldErrors?: Record<string, string> }>(response)
120
+ expect(body?.fieldErrors?.tls).toMatch(/OM_CHANNEL_SMTP_ALLOW_INSECURE_TRANSPORT/)
121
+ })
122
+
123
+ test('both connect routes reject unauthenticated callers', async ({ request }) => {
124
+ for (const url of [PER_USER_CONNECT, TENANT_CONNECT]) {
125
+ const response = await apiRequest(request, 'POST', url, {
126
+ // Intentionally empty token — this asserts the 401 unauth path.
127
+ token: '',
128
+ data: { providerKey: 'smtp', displayName: 'SMTP', credentials: validRelay },
129
+ })
130
+ expect(response.status(), `${url} must require authentication`).toBe(401)
131
+ }
132
+ })
133
+ })
@@ -0,0 +1,6 @@
1
+ export const integrationMeta = {
2
+ description: 'SMTP outbound email provider integration coverage (TC-CHANNEL-SMTP-001)',
3
+ dependsOnModules: ['communication_channels', 'channel_smtp'],
4
+ }
5
+
6
+ export default integrationMeta