@open-mercato/core 0.7.1-develop.7150.1.c1941e0c22 → 0.7.1-develop.7151.1.00d0391847
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +1 -1
- package/dist/helpers/integration/communicationChannelsFixtures.js +77 -1
- package/dist/helpers/integration/communicationChannelsFixtures.js.map +2 -2
- package/dist/helpers/integration/crmFixtures.js +3 -0
- package/dist/helpers/integration/crmFixtures.js.map +2 -2
- package/dist/modules/auth/api/reset.js +7 -1
- package/dist/modules/auth/api/reset.js.map +2 -2
- package/dist/modules/auth/api/users/resend-invite/route.js +7 -1
- package/dist/modules/auth/api/users/resend-invite/route.js.map +2 -2
- package/dist/modules/auth/commands/users.js +7 -1
- package/dist/modules/auth/commands/users.js.map +2 -2
- package/dist/modules/communication_channels/api/post/test-seed/route.js +101 -26
- package/dist/modules/communication_channels/api/post/test-seed/route.js.map +3 -3
- package/dist/modules/communication_channels/di.js +8 -0
- package/dist/modules/communication_channels/di.js.map +2 -2
- package/dist/modules/communication_channels/lib/ensure-system-email-channel.js +57 -0
- package/dist/modules/communication_channels/lib/ensure-system-email-channel.js.map +7 -0
- package/dist/modules/communication_channels/lib/system-email-provider-config.js +32 -0
- package/dist/modules/communication_channels/lib/system-email-provider-config.js.map +7 -0
- package/dist/modules/communication_channels/lib/system-email.js +190 -0
- package/dist/modules/communication_channels/lib/system-email.js.map +7 -0
- package/dist/modules/communication_channels/lib/test-seed.js +130 -1
- package/dist/modules/communication_channels/lib/test-seed.js.map +2 -2
- package/dist/modules/communication_channels/setup.js +56 -1
- package/dist/modules/communication_channels/setup.js.map +2 -2
- package/dist/modules/customer_accounts/api/admin/users-invite.js +1 -0
- package/dist/modules/customer_accounts/api/admin/users-invite.js.map +2 -2
- package/dist/modules/customer_accounts/api/portal/users-invite.js +1 -0
- package/dist/modules/customer_accounts/api/portal/users-invite.js.map +2 -2
- package/dist/modules/customer_accounts/api/signup.js +8 -4
- package/dist/modules/customer_accounts/api/signup.js.map +2 -2
- package/dist/modules/customer_accounts/lib/invitationEmail.js +3 -1
- package/dist/modules/customer_accounts/lib/invitationEmail.js.map +2 -2
- package/dist/modules/customers/api/interactions/route.js +3 -0
- package/dist/modules/customers/api/interactions/route.js.map +2 -2
- package/dist/modules/messages/lib/email-sender.js +16 -14
- package/dist/modules/messages/lib/email-sender.js.map +2 -2
- package/dist/modules/notifications/lib/strategies/email-delivery-strategy.js +3 -1
- package/dist/modules/notifications/lib/strategies/email-delivery-strategy.js.map +2 -2
- package/dist/modules/sales/api/quotes/accept/route.js +3 -1
- package/dist/modules/sales/api/quotes/accept/route.js.map +2 -2
- package/dist/modules/sales/api/quotes/send/route.js +13 -4
- package/dist/modules/sales/api/quotes/send/route.js.map +3 -3
- package/package.json +7 -7
- package/src/helpers/integration/communicationChannelsFixtures.ts +129 -0
- package/src/helpers/integration/crmFixtures.ts +4 -1
- package/src/modules/auth/api/reset.ts +7 -1
- package/src/modules/auth/api/users/resend-invite/route.ts +7 -1
- package/src/modules/auth/commands/users.ts +7 -1
- package/src/modules/auth/i18n/de.json +4 -0
- package/src/modules/auth/i18n/en.json +4 -0
- package/src/modules/auth/i18n/es.json +4 -0
- package/src/modules/auth/i18n/ko.json +4 -0
- package/src/modules/auth/i18n/pl.json +4 -0
- package/src/modules/communication_channels/api/post/test-seed/route.ts +121 -29
- package/src/modules/communication_channels/di.ts +8 -0
- package/src/modules/communication_channels/lib/ensure-system-email-channel.ts +85 -0
- package/src/modules/communication_channels/lib/system-email-provider-config.ts +62 -0
- package/src/modules/communication_channels/lib/system-email.ts +316 -0
- package/src/modules/communication_channels/lib/test-seed.ts +198 -0
- package/src/modules/communication_channels/setup.ts +91 -1
- package/src/modules/customer_accounts/api/admin/users-invite.ts +1 -0
- package/src/modules/customer_accounts/api/portal/users-invite.ts +1 -0
- package/src/modules/customer_accounts/api/signup.ts +6 -2
- package/src/modules/customer_accounts/lib/invitationEmail.ts +3 -0
- package/src/modules/customers/api/interactions/route.ts +4 -0
- package/src/modules/messages/lib/email-sender.ts +18 -16
- package/src/modules/notifications/lib/strategies/email-delivery-strategy.ts +3 -1
- package/src/modules/sales/api/quotes/accept/route.ts +2 -0
- package/src/modules/sales/api/quotes/send/route.ts +16 -3
|
@@ -1,13 +1,120 @@
|
|
|
1
|
+
import { appendFile, mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
2
|
+
import { timingSafeEqual } from "node:crypto";
|
|
3
|
+
import path from "node:path";
|
|
1
4
|
import { baseEmailCapabilities } from "./email-capabilities.js";
|
|
2
5
|
import { hasChannelAdapter, registerChannelAdapter } from "./adapter-registry-singleton.js";
|
|
6
|
+
import { registerSystemEmailProviderConfigResolver } from "./system-email-provider-config.js";
|
|
3
7
|
const TEST_SEED_PROVIDER_KEY = "__test_seed__";
|
|
4
8
|
const TEST_SEED_CHAT_PROVIDER_KEY = "__test_seed_chat__";
|
|
5
9
|
const TEST_CHANNEL_SEEDING_ENV = "OM_ENABLE_TEST_CHANNEL_SEEDING";
|
|
10
|
+
const TEST_EMAIL_CAPTURE_ACCESS_TOKEN_ENV = "OM_TEST_EMAIL_CAPTURE_ACCESS_TOKEN";
|
|
11
|
+
const TEST_EMAIL_CAPTURE_CORRELATION_TOKEN_ENV = "OM_TEST_EMAIL_CAPTURE_CORRELATION_TOKEN";
|
|
12
|
+
const TEST_SYSTEM_EMAIL_CAPTURE_PATH_ENV = "OM_TEST_SYSTEM_EMAIL_CAPTURE_PATH";
|
|
6
13
|
function isTestChannelSeedingEnabled() {
|
|
7
14
|
const raw = process.env[TEST_CHANNEL_SEEDING_ENV];
|
|
8
15
|
if (typeof raw !== "string") return false;
|
|
9
16
|
return ["1", "true", "yes", "on"].includes(raw.trim().toLowerCase());
|
|
10
17
|
}
|
|
18
|
+
async function createTestSeedPlatformMessage(em, input) {
|
|
19
|
+
const rows = await em.getConnection().execute(
|
|
20
|
+
`INSERT INTO messages
|
|
21
|
+
(type, thread_id, sender_user_id, subject, body, body_format, priority, status,
|
|
22
|
+
is_draft, sent_at, visibility, source_entity_type, source_entity_id,
|
|
23
|
+
tenant_id, organization_id, created_at, updated_at)
|
|
24
|
+
VALUES
|
|
25
|
+
(?, ?, ?, ?, ?, 'text', 'normal', 'sent',
|
|
26
|
+
false, now(), 'public', 'communication_channels.test_seed_inbound', ?,
|
|
27
|
+
?, ?, now(), now())
|
|
28
|
+
RETURNING id`,
|
|
29
|
+
[
|
|
30
|
+
`channel.${input.providerKey}`,
|
|
31
|
+
input.threadId ?? null,
|
|
32
|
+
input.senderUserId,
|
|
33
|
+
input.subject ?? "(no subject)",
|
|
34
|
+
input.bodyText ?? "",
|
|
35
|
+
input.channelId,
|
|
36
|
+
input.tenantId,
|
|
37
|
+
input.organizationId
|
|
38
|
+
]
|
|
39
|
+
);
|
|
40
|
+
return rows[0]?.id ?? null;
|
|
41
|
+
}
|
|
42
|
+
function normalizeToken(value) {
|
|
43
|
+
if (typeof value !== "string") return null;
|
|
44
|
+
const normalized = value.trim();
|
|
45
|
+
return normalized.length >= 32 ? normalized : null;
|
|
46
|
+
}
|
|
47
|
+
function isTestEmailCaptureAccessAuthorized(providedToken) {
|
|
48
|
+
const expectedToken = normalizeToken(process.env[TEST_EMAIL_CAPTURE_ACCESS_TOKEN_ENV]);
|
|
49
|
+
const normalizedProvidedToken = normalizeToken(providedToken);
|
|
50
|
+
if (!expectedToken || !normalizedProvidedToken) return false;
|
|
51
|
+
const expected = Buffer.from(expectedToken);
|
|
52
|
+
const provided = Buffer.from(normalizedProvidedToken);
|
|
53
|
+
return expected.length === provided.length && timingSafeEqual(expected, provided);
|
|
54
|
+
}
|
|
55
|
+
function resolveTestEmailCaptureCorrelationToken() {
|
|
56
|
+
return normalizeToken(process.env[TEST_EMAIL_CAPTURE_CORRELATION_TOKEN_ENV]);
|
|
57
|
+
}
|
|
58
|
+
function resolveCapturePath() {
|
|
59
|
+
const explicit = process.env[TEST_SYSTEM_EMAIL_CAPTURE_PATH_ENV]?.trim();
|
|
60
|
+
if (explicit) return path.resolve(explicit);
|
|
61
|
+
const queueBaseDir = process.env.QUEUE_BASE_DIR?.trim();
|
|
62
|
+
if (queueBaseDir) return path.resolve(queueBaseDir, "..", "test-email-capture.jsonl");
|
|
63
|
+
return path.resolve(process.cwd(), ".mercato", "test-email-capture.jsonl");
|
|
64
|
+
}
|
|
65
|
+
function matchesCaptureScope(message, scope, options = {}) {
|
|
66
|
+
if (message.scope.tenantId === scope.tenantId) {
|
|
67
|
+
const messageOrganizationId = message.scope.organizationId ?? null;
|
|
68
|
+
return messageOrganizationId === scope.organizationId || messageOrganizationId === scope.tenantId;
|
|
69
|
+
}
|
|
70
|
+
if (message.scope.tenantId !== "system" || message.scope.organizationId !== "system" || !options.systemRecipient || !options.captureCorrelationToken || message.captureCorrelationToken !== options.captureCorrelationToken) {
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
const expectedRecipient = options.systemRecipient.trim().toLowerCase();
|
|
74
|
+
const matchesRecipient = (value) => {
|
|
75
|
+
if (typeof value === "string") return value.trim().toLowerCase() === expectedRecipient;
|
|
76
|
+
if (Array.isArray(value)) return value.some(matchesRecipient);
|
|
77
|
+
if (!value || typeof value !== "object") return false;
|
|
78
|
+
return matchesRecipient(value.address);
|
|
79
|
+
};
|
|
80
|
+
return matchesRecipient(message.metadata?.to);
|
|
81
|
+
}
|
|
82
|
+
async function readTestSeedCapturedMessages() {
|
|
83
|
+
const capturePath = resolveCapturePath();
|
|
84
|
+
const text = await readFile(capturePath, "utf8").catch(() => "");
|
|
85
|
+
return text.split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0).map((line) => {
|
|
86
|
+
try {
|
|
87
|
+
return JSON.parse(line);
|
|
88
|
+
} catch {
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
}).filter((message) => Boolean(message?.scope));
|
|
92
|
+
}
|
|
93
|
+
async function clearTestSeedCapturedMessages(scope, options = {}) {
|
|
94
|
+
const capturePath = resolveCapturePath();
|
|
95
|
+
const retained = (await readTestSeedCapturedMessages()).filter((message) => !matchesCaptureScope(message, scope, options));
|
|
96
|
+
if (retained.length === 0) {
|
|
97
|
+
await rm(capturePath, { force: true });
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
await writeFile(
|
|
101
|
+
capturePath,
|
|
102
|
+
`${retained.map((message) => JSON.stringify(message)).join("\n")}
|
|
103
|
+
`,
|
|
104
|
+
"utf8"
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
async function listTestSeedCapturedMessages(scope, options = {}) {
|
|
108
|
+
return (await readTestSeedCapturedMessages()).filter(
|
|
109
|
+
(message) => matchesCaptureScope(message, scope, options)
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
async function captureTestSeedMessage(record) {
|
|
113
|
+
const capturePath = resolveCapturePath();
|
|
114
|
+
await mkdir(path.dirname(capturePath), { recursive: true });
|
|
115
|
+
await appendFile(capturePath, `${JSON.stringify(record)}
|
|
116
|
+
`, "utf8");
|
|
117
|
+
}
|
|
11
118
|
const testSeedCapabilities = {
|
|
12
119
|
...baseEmailCapabilities,
|
|
13
120
|
conversationHistory: false,
|
|
@@ -23,6 +130,15 @@ class TestSeedChannelAdapter {
|
|
|
23
130
|
}
|
|
24
131
|
async sendMessage(input) {
|
|
25
132
|
const externalMessageId = `test-seed-${Date.now()}-${Math.random().toString(16).slice(2, 10)}@test-seed.local`;
|
|
133
|
+
await captureTestSeedMessage({
|
|
134
|
+
capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
135
|
+
externalMessageId,
|
|
136
|
+
conversationId: input.conversationId,
|
|
137
|
+
content: input.content,
|
|
138
|
+
scope: input.scope,
|
|
139
|
+
metadata: input.metadata,
|
|
140
|
+
captureCorrelationToken: resolveTestEmailCaptureCorrelationToken() ?? void 0
|
|
141
|
+
});
|
|
26
142
|
return {
|
|
27
143
|
externalMessageId,
|
|
28
144
|
conversationId: input.conversationId,
|
|
@@ -95,6 +211,11 @@ function getTestSeedChatChannelAdapter() {
|
|
|
95
211
|
}
|
|
96
212
|
function ensureTestSeedAdapterRegistered() {
|
|
97
213
|
if (!isTestChannelSeedingEnabled()) return;
|
|
214
|
+
registerSystemEmailProviderConfigResolver({
|
|
215
|
+
providerKey: TEST_SEED_PROVIDER_KEY,
|
|
216
|
+
isConfigured: isTestChannelSeedingEnabled,
|
|
217
|
+
resolveCredentials: ({ fromAddress }) => ({ testSeed: true, fromAddress })
|
|
218
|
+
});
|
|
98
219
|
if (!hasChannelAdapter(TEST_SEED_PROVIDER_KEY)) {
|
|
99
220
|
registerChannelAdapter(getTestSeedChannelAdapter());
|
|
100
221
|
}
|
|
@@ -104,9 +225,17 @@ function ensureTestSeedAdapterRegistered() {
|
|
|
104
225
|
}
|
|
105
226
|
export {
|
|
106
227
|
TEST_CHANNEL_SEEDING_ENV,
|
|
228
|
+
TEST_EMAIL_CAPTURE_ACCESS_TOKEN_ENV,
|
|
229
|
+
TEST_EMAIL_CAPTURE_CORRELATION_TOKEN_ENV,
|
|
107
230
|
TEST_SEED_CHAT_PROVIDER_KEY,
|
|
108
231
|
TEST_SEED_PROVIDER_KEY,
|
|
232
|
+
TEST_SYSTEM_EMAIL_CAPTURE_PATH_ENV,
|
|
233
|
+
clearTestSeedCapturedMessages,
|
|
234
|
+
createTestSeedPlatformMessage,
|
|
109
235
|
ensureTestSeedAdapterRegistered,
|
|
110
|
-
isTestChannelSeedingEnabled
|
|
236
|
+
isTestChannelSeedingEnabled,
|
|
237
|
+
isTestEmailCaptureAccessAuthorized,
|
|
238
|
+
listTestSeedCapturedMessages,
|
|
239
|
+
resolveTestEmailCaptureCorrelationToken
|
|
111
240
|
};
|
|
112
241
|
//# sourceMappingURL=test-seed.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/communication_channels/lib/test-seed.ts"],
|
|
4
|
-
"sourcesContent": ["import type {\n ChannelAdapter,\n ChannelCapabilities,\n ChannelNativeContent,\n ConvertOutboundInput,\n GetMessageStatusInput,\n InboundMessage,\n MessageStatus,\n NormalizedInboundMessage,\n SendMessageInput,\n SendMessageResult,\n ValidateCredentialsInput,\n ValidateCredentialsResult,\n VerifyWebhookInput,\n} from './adapter'\nimport { baseEmailCapabilities } from './email-capabilities'\nimport { hasChannelAdapter, registerChannelAdapter } from './adapter-registry-singleton'\n\n/**\n * Test-only channel seeding support.\n *\n * The ephemeral integration harness cannot connect a REAL email channel:\n * - IMAP/SMTP `validateCredentials` performs a live LOGIN against a mail server\n * (none exists in CI), so `POST /channels/connect/credentials` returns 422.\n * - Even with a connected channel, the outbound delivery worker calls the real\n * SMTP adapter, which fails with no server \u2014 so `communication_channels.message.sent`\n * never fires and the customers link subscriber never runs.\n *\n * To make the compose \u2192 deliver \u2192 `.sent` \u2192 CRM-link \u2192 cross-user-visibility chain\n * (TC-CRM-EMAIL-001) and the inbound auto-link chain (TC-CRM-EMAIL-002..005) runnable\n * end-to-end against real Postgres, this module provides a network-free stub adapter\n * that is registered ONLY when `OM_ENABLE_TEST_CHANNEL_SEEDING` is set.\n *\n * Production safety: the registration is gated by {@link isTestChannelSeedingEnabled};\n * when the env flag is unset (the production default) the adapter is never registered\n * and the `__test_seed__` provider key resolves to no adapter \u2014 so the connect route\n * returns 404 `no_adapter` exactly as it would for any unknown provider. The dedicated\n * test-seed API route enforces the same gate independently (fail-closed 404 in prod).\n */\n\n/** Provider key for the network-free test stub adapter. */\nexport const TEST_SEED_PROVIDER_KEY = '__test_seed__'\n\n/**\n * Provider key for the network-free stub adapter that stands in for a CHAT\n * provider \u2014 one whose senders are identified by an opaque handle and have no\n * email address at all (Discord, Slack, Telegram\u2026).\n *\n * It exists because the email-shaped stub above can only ever prove the hub\n * accepts email-shaped data. That is precisely how CI stayed green while every\n * real inbound Discord message was rejected (#4975): the fixture invented an\n * address the provider can never produce. Tests that need to prove the hub's\n * non-email identity contract MUST drive this provider instead.\n */\nexport const TEST_SEED_CHAT_PROVIDER_KEY = '__test_seed_chat__'\n\n/** Env flag that unlocks test-only channel seeding. Off in production. */\nexport const TEST_CHANNEL_SEEDING_ENV = 'OM_ENABLE_TEST_CHANNEL_SEEDING'\n\n/**\n * True only when the test-seeding env flag is explicitly enabled. Accepts the\n * usual truthy tokens (`1`, `true`, `yes`, `on`) so the harness can opt in via a\n * plain `=true`. Any other value (including unset) is treated as disabled.\n */\nexport function isTestChannelSeedingEnabled(): boolean {\n const raw = process.env[TEST_CHANNEL_SEEDING_ENV]\n if (typeof raw !== 'string') return false\n return ['1', 'true', 'yes', 'on'].includes(raw.trim().toLowerCase())\n}\n\n/**\n * Capabilities for the stub: an email channel that supports neither reactions,\n * edit/delete, nor conversation history \u2014 so the strict registry validator\n * (`validateAdapterCapabilities`) requires only the core method surface.\n */\nconst testSeedCapabilities: ChannelCapabilities = {\n ...baseEmailCapabilities,\n conversationHistory: false,\n realtimePush: false,\n}\n\n/**\n * A `ChannelAdapter` whose `sendMessage` reports a successful send WITHOUT any\n * network I/O. Used exclusively by the integration harness to let the outbound\n * delivery worker reach its success path and emit `communication_channels.message.sent`.\n */\nclass TestSeedChannelAdapter implements ChannelAdapter {\n // Widened to `string` rather than inferred as a literal so the chat-flavoured\n // subclass below can override both with its own provider key / channel type.\n readonly providerKey: string = TEST_SEED_PROVIDER_KEY\n readonly channelType: string = 'email'\n readonly capabilities = testSeedCapabilities\n\n async sendMessage(input: SendMessageInput): Promise<SendMessageResult> {\n // Synthesize a deterministic-looking RFC2822-style message id; never touches\n // the network. The delivery worker persists this as the external message id.\n const externalMessageId = `test-seed-${Date.now()}-${Math.random().toString(16).slice(2, 10)}@test-seed.local`\n return {\n externalMessageId,\n conversationId: input.conversationId,\n status: 'sent',\n metadata: { testSeed: true },\n }\n }\n\n async verifyWebhook(_input: VerifyWebhookInput): Promise<InboundMessage> {\n // No real webhook \u2014 return the inert event so the generic webhook route 202s\n // without enqueuing tenant-scoped work (mirrors the IMAP adapter contract).\n return { raw: {}, eventType: 'other', metadata: { reason: 'test-seed-no-webhook' } }\n }\n\n async getStatus(_input: GetMessageStatusInput): Promise<MessageStatus> {\n return { status: 'sent' }\n }\n\n async convertOutbound(input: ConvertOutboundInput): Promise<ChannelNativeContent> {\n return {\n content: {\n text: input.body,\n bodyFormat: input.bodyFormat,\n },\n metadata: input.channelMetadata ?? {},\n }\n }\n\n async normalizeInbound(_raw: InboundMessage): Promise<NormalizedInboundMessage> {\n // The test-seed inbound path seeds MessageChannelLink rows directly and emits\n // the hub event, so this adapter never normalizes a raw inbound payload.\n throw new Error('[internal] TestSeedChannelAdapter.normalizeInbound is not used by the seed harness')\n }\n\n async validateCredentials(_input: ValidateCredentialsInput): Promise<ValidateCredentialsResult> {\n // No real server to authenticate against \u2014 accept any credentials so the\n // connect command persists a connected channel.\n return { ok: true }\n }\n}\n\n/**\n * Capabilities for the chat stub. Identical to the email stub's except for the\n * recipient shape: a chat channel is addressed by a provider-issued identifier\n * (a Discord snowflake), not an email address.\n *\n * Without this override the chat stub inherited `baseEmailCapabilities`, so it\n * claimed `channelType: 'discord'` while validating recipients as email\n * addresses \u2014 a channel that could not be addressed the way the provider it\n * imitates actually is. That left the hub's `'provider-native'` branch\n * (#4976: per-provider recipient validation, and the omitted recipient that\n * falls back to the adapter's own target) reachable only with a live Discord\n * bot, so no integration test could cover it and CI never exercised it.\n */\nconst testSeedChatCapabilities: ChannelCapabilities = {\n ...testSeedCapabilities,\n recipientFormat: 'provider-native',\n}\n\n/**\n * Chat-flavoured twin of {@link TestSeedChannelAdapter}: same network-free\n * behaviour, but it declares a non-email `channelType`, so a channel connected\n * through it is shaped like a real chat channel \u2014 including an\n * `externalIdentifier` of NULL when no email-ish credential key is supplied.\n */\nclass TestSeedChatChannelAdapter extends TestSeedChannelAdapter {\n readonly providerKey: string = TEST_SEED_CHAT_PROVIDER_KEY\n readonly channelType: string = 'discord'\n readonly capabilities = testSeedChatCapabilities\n\n async normalizeInbound(raw: InboundMessage): Promise<NormalizedInboundMessage> {\n // Unlike the email stub, this one is reachable: the test-seed ingest action\n // feeds it a chat-shaped frame so the message travels the real ingest path\n // (and therefore the real compose validation) rather than a SQL shortcut.\n const frame = (raw.raw ?? {}) as Record<string, unknown>\n const senderIdentifier = String(frame.senderIdentifier ?? '')\n if (!senderIdentifier) {\n throw new Error('[internal] TestSeedChatChannelAdapter requires a senderIdentifier')\n }\n return {\n externalMessageId: String(frame.externalMessageId ?? ''),\n externalConversationId: String(frame.externalConversationId ?? ''),\n senderIdentifier,\n senderDisplayName:\n typeof frame.senderDisplayName === 'string' ? frame.senderDisplayName : undefined,\n body: typeof frame.body === 'string' ? frame.body : '',\n bodyFormat: 'text',\n timestamp: new Date(),\n channelPayload: {},\n channelContentType: 'text/plain',\n channelMetadata: {},\n }\n }\n}\n\nlet cachedTestSeedAdapter: TestSeedChannelAdapter | null = null\nlet cachedTestSeedChatAdapter: TestSeedChatChannelAdapter | null = null\n\nfunction getTestSeedChannelAdapter(): TestSeedChannelAdapter {\n if (!cachedTestSeedAdapter) cachedTestSeedAdapter = new TestSeedChannelAdapter()\n return cachedTestSeedAdapter\n}\n\nfunction getTestSeedChatChannelAdapter(): TestSeedChatChannelAdapter {\n if (!cachedTestSeedChatAdapter) cachedTestSeedChatAdapter = new TestSeedChatChannelAdapter()\n return cachedTestSeedChatAdapter\n}\n\n/**\n * Register the test-seed adapter exactly once, but ONLY when the env flag is set.\n * Idempotent and safe to call from every container creation (`di.register`) \u2014 a\n * no-op when seeding is disabled or the adapter is already registered.\n */\nexport function ensureTestSeedAdapterRegistered(): void {\n if (!isTestChannelSeedingEnabled()) return\n if (!hasChannelAdapter(TEST_SEED_PROVIDER_KEY)) {\n registerChannelAdapter(getTestSeedChannelAdapter())\n }\n if (!hasChannelAdapter(TEST_SEED_CHAT_PROVIDER_KEY)) {\n registerChannelAdapter(getTestSeedChatChannelAdapter())\n }\n}\n"],
|
|
5
|
-
"mappings": "
|
|
4
|
+
"sourcesContent": ["import { appendFile, mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { timingSafeEqual } from 'node:crypto'\nimport path from 'node:path'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type {\n ChannelAdapter,\n ChannelCapabilities,\n ChannelNativeContent,\n ConvertOutboundInput,\n GetMessageStatusInput,\n InboundMessage,\n MessageStatus,\n NormalizedInboundMessage,\n SendMessageInput,\n SendMessageResult,\n ValidateCredentialsInput,\n ValidateCredentialsResult,\n VerifyWebhookInput,\n} from './adapter'\nimport { baseEmailCapabilities } from './email-capabilities'\nimport { hasChannelAdapter, registerChannelAdapter } from './adapter-registry-singleton'\nimport { registerSystemEmailProviderConfigResolver } from './system-email-provider-config'\n\n/**\n * Test-only channel seeding support.\n *\n * The ephemeral integration harness cannot connect a REAL email channel:\n * - IMAP/SMTP `validateCredentials` performs a live LOGIN against a mail server\n * (none exists in CI), so `POST /channels/connect/credentials` returns 422.\n * - Even with a connected channel, the outbound delivery worker calls the real\n * SMTP adapter, which fails with no server \u2014 so `communication_channels.message.sent`\n * never fires and the customers link subscriber never runs.\n *\n * To make the compose \u2192 deliver \u2192 `.sent` \u2192 CRM-link \u2192 cross-user-visibility chain\n * (TC-CRM-EMAIL-001) and the inbound auto-link chain (TC-CRM-EMAIL-002..005) runnable\n * end-to-end against real Postgres, this module provides a network-free stub adapter\n * that is registered ONLY when `OM_ENABLE_TEST_CHANNEL_SEEDING` is set.\n *\n * Production safety: the registration is gated by {@link isTestChannelSeedingEnabled};\n * when the env flag is unset (the production default) the adapter is never registered\n * and the `__test_seed__` provider key resolves to no adapter \u2014 so the connect route\n * returns 404 `no_adapter` exactly as it would for any unknown provider. The dedicated\n * test-seed API route enforces the same gate independently (fail-closed 404 in prod).\n */\n\n/** Provider key for the network-free test stub adapter. */\nexport const TEST_SEED_PROVIDER_KEY = '__test_seed__'\n\n/**\n * Provider key for the network-free stub adapter that stands in for a CHAT\n * provider \u2014 one whose senders are identified by an opaque handle and have no\n * email address at all (Discord, Slack, Telegram\u2026).\n *\n * It exists because the email-shaped stub above can only ever prove the hub\n * accepts email-shaped data. That is precisely how CI stayed green while every\n * real inbound Discord message was rejected (#4975): the fixture invented an\n * address the provider can never produce. Tests that need to prove the hub's\n * non-email identity contract MUST drive this provider instead.\n */\nexport const TEST_SEED_CHAT_PROVIDER_KEY = '__test_seed_chat__'\n\n/** Env flag that unlocks test-only channel seeding. Off in production. */\nexport const TEST_CHANNEL_SEEDING_ENV = 'OM_ENABLE_TEST_CHANNEL_SEEDING'\nexport const TEST_EMAIL_CAPTURE_ACCESS_TOKEN_ENV = 'OM_TEST_EMAIL_CAPTURE_ACCESS_TOKEN'\nexport const TEST_EMAIL_CAPTURE_CORRELATION_TOKEN_ENV = 'OM_TEST_EMAIL_CAPTURE_CORRELATION_TOKEN'\n/**\n * Where the Hub's tenant-scoped capture is written.\n *\n * Deliberately not `OM_TEST_EMAIL_CAPTURE_PATH`: that one belongs to the unscoped capture in\n * `@open-mercato/shared/lib/email/send`, which writes a different record shape to a path the repo\n * also ships a committed fixture for. Pointing both mechanisms at one file made this module parse\n * foreign records and let `clear-capture` rewrite the other mechanism's fixtures. Two mechanisms,\n * two files.\n */\nexport const TEST_SYSTEM_EMAIL_CAPTURE_PATH_ENV = 'OM_TEST_SYSTEM_EMAIL_CAPTURE_PATH'\n\n/**\n * True only when the test-seeding env flag is explicitly enabled. Accepts the\n * usual truthy tokens (`1`, `true`, `yes`, `on`) so the harness can opt in via a\n * plain `=true`. Any other value (including unset) is treated as disabled.\n */\nexport function isTestChannelSeedingEnabled(): boolean {\n const raw = process.env[TEST_CHANNEL_SEEDING_ENV]\n if (typeof raw !== 'string') return false\n return ['1', 'true', 'yes', 'on'].includes(raw.trim().toLowerCase())\n}\n\nexport type TestSeedCapturedMessage = {\n capturedAt: string\n externalMessageId: string\n conversationId?: string\n content: SendMessageInput['content']\n scope: SendMessageInput['scope']\n metadata?: SendMessageInput['metadata']\n captureCorrelationToken?: string\n}\n\ntype TestSeedCaptureScope = {\n tenantId: string\n organizationId: string | null\n}\n\nexport type TestSeedCaptureOptions = {\n systemRecipient?: string\n captureCorrelationToken?: string\n}\n\nexport async function createTestSeedPlatformMessage(\n em: EntityManager,\n input: {\n providerKey: string\n threadId?: string\n senderUserId: string\n subject?: string\n bodyText?: string\n channelId: string\n tenantId: string\n organizationId: string | null\n },\n): Promise<string | null> {\n const rows = (await em.getConnection().execute(\n `INSERT INTO messages\n (type, thread_id, sender_user_id, subject, body, body_format, priority, status,\n is_draft, sent_at, visibility, source_entity_type, source_entity_id,\n tenant_id, organization_id, created_at, updated_at)\n VALUES\n (?, ?, ?, ?, ?, 'text', 'normal', 'sent',\n false, now(), 'public', 'communication_channels.test_seed_inbound', ?,\n ?, ?, now(), now())\n RETURNING id`,\n [\n `channel.${input.providerKey}`,\n input.threadId ?? null,\n input.senderUserId,\n input.subject ?? '(no subject)',\n input.bodyText ?? '',\n input.channelId,\n input.tenantId,\n input.organizationId,\n ],\n )) as Array<{ id: string }>\n return rows[0]?.id ?? null\n}\n\nfunction normalizeToken(value: string | null | undefined): string | null {\n if (typeof value !== 'string') return null\n const normalized = value.trim()\n return normalized.length >= 32 ? normalized : null\n}\n\nexport function isTestEmailCaptureAccessAuthorized(providedToken: string | null): boolean {\n const expectedToken = normalizeToken(process.env[TEST_EMAIL_CAPTURE_ACCESS_TOKEN_ENV])\n const normalizedProvidedToken = normalizeToken(providedToken)\n if (!expectedToken || !normalizedProvidedToken) return false\n const expected = Buffer.from(expectedToken)\n const provided = Buffer.from(normalizedProvidedToken)\n return expected.length === provided.length && timingSafeEqual(expected, provided)\n}\n\nexport function resolveTestEmailCaptureCorrelationToken(): string | null {\n return normalizeToken(process.env[TEST_EMAIL_CAPTURE_CORRELATION_TOKEN_ENV])\n}\n\nfunction resolveCapturePath(): string {\n const explicit = process.env[TEST_SYSTEM_EMAIL_CAPTURE_PATH_ENV]?.trim()\n if (explicit) return path.resolve(explicit)\n const queueBaseDir = process.env.QUEUE_BASE_DIR?.trim()\n if (queueBaseDir) return path.resolve(queueBaseDir, '..', 'test-email-capture.jsonl')\n return path.resolve(process.cwd(), '.mercato', 'test-email-capture.jsonl')\n}\n\nfunction matchesCaptureScope(\n message: TestSeedCapturedMessage,\n scope: TestSeedCaptureScope,\n options: TestSeedCaptureOptions = {},\n): boolean {\n if (message.scope.tenantId === scope.tenantId) {\n const messageOrganizationId = message.scope.organizationId ?? null\n return messageOrganizationId === scope.organizationId || messageOrganizationId === scope.tenantId\n }\n\n if (\n message.scope.tenantId !== 'system' ||\n message.scope.organizationId !== 'system' ||\n !options.systemRecipient ||\n !options.captureCorrelationToken ||\n message.captureCorrelationToken !== options.captureCorrelationToken\n ) {\n return false\n }\n\n const expectedRecipient = options.systemRecipient.trim().toLowerCase()\n const matchesRecipient = (value: unknown): boolean => {\n if (typeof value === 'string') return value.trim().toLowerCase() === expectedRecipient\n if (Array.isArray(value)) return value.some(matchesRecipient)\n if (!value || typeof value !== 'object') return false\n return matchesRecipient((value as Record<string, unknown>).address)\n }\n\n return matchesRecipient(message.metadata?.to)\n}\n\nasync function readTestSeedCapturedMessages(): Promise<TestSeedCapturedMessage[]> {\n const capturePath = resolveCapturePath()\n const text = await readFile(capturePath, 'utf8').catch(() => '')\n return text\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .map((line) => {\n try {\n return JSON.parse(line) as TestSeedCapturedMessage\n } catch {\n return null\n }\n })\n // A record without a scope is not ours. Skipping instead of throwing keeps a stray or\n // foreign-shaped line from turning every capture read into a 500.\n .filter((message): message is TestSeedCapturedMessage => Boolean(message?.scope))\n}\n\nexport async function clearTestSeedCapturedMessages(\n scope: TestSeedCaptureScope,\n options: TestSeedCaptureOptions = {},\n): Promise<void> {\n const capturePath = resolveCapturePath()\n const retained = (await readTestSeedCapturedMessages())\n .filter((message) => !matchesCaptureScope(message, scope, options))\n if (retained.length === 0) {\n await rm(capturePath, { force: true })\n return\n }\n await writeFile(\n capturePath,\n `${retained.map((message) => JSON.stringify(message)).join('\\n')}\\n`,\n 'utf8',\n )\n}\n\nexport async function listTestSeedCapturedMessages(\n scope: TestSeedCaptureScope,\n options: TestSeedCaptureOptions = {},\n): Promise<TestSeedCapturedMessage[]> {\n return (await readTestSeedCapturedMessages()).filter((message) =>\n matchesCaptureScope(message, scope, options),\n )\n}\n\nasync function captureTestSeedMessage(record: TestSeedCapturedMessage): Promise<void> {\n const capturePath = resolveCapturePath()\n await mkdir(path.dirname(capturePath), { recursive: true })\n await appendFile(capturePath, `${JSON.stringify(record)}\\n`, 'utf8')\n}\n\n/**\n * Capabilities for the stub: an email channel that supports neither reactions,\n * edit/delete, nor conversation history \u2014 so the strict registry validator\n * (`validateAdapterCapabilities`) requires only the core method surface.\n */\nconst testSeedCapabilities: ChannelCapabilities = {\n ...baseEmailCapabilities,\n conversationHistory: false,\n realtimePush: false,\n}\n\n/**\n * A `ChannelAdapter` whose `sendMessage` reports a successful send WITHOUT any\n * network I/O. Used exclusively by the integration harness to let the outbound\n * delivery worker reach its success path and emit `communication_channels.message.sent`.\n */\nclass TestSeedChannelAdapter implements ChannelAdapter {\n // Widened to `string` rather than inferred as a literal so the chat-flavoured\n // subclass below can override both with its own provider key / channel type.\n readonly providerKey: string = TEST_SEED_PROVIDER_KEY\n readonly channelType: string = 'email'\n readonly capabilities = testSeedCapabilities\n\n async sendMessage(input: SendMessageInput): Promise<SendMessageResult> {\n // Synthesize a deterministic-looking RFC2822-style message id; never touches\n // the network. The delivery worker persists this as the external message id.\n const externalMessageId = `test-seed-${Date.now()}-${Math.random().toString(16).slice(2, 10)}@test-seed.local`\n await captureTestSeedMessage({\n capturedAt: new Date().toISOString(),\n externalMessageId,\n conversationId: input.conversationId,\n content: input.content,\n scope: input.scope,\n metadata: input.metadata,\n captureCorrelationToken: resolveTestEmailCaptureCorrelationToken() ?? undefined,\n })\n return {\n externalMessageId,\n conversationId: input.conversationId,\n status: 'sent',\n metadata: { testSeed: true },\n }\n }\n\n async verifyWebhook(_input: VerifyWebhookInput): Promise<InboundMessage> {\n // No real webhook \u2014 return the inert event so the generic webhook route 202s\n // without enqueuing tenant-scoped work (mirrors the IMAP adapter contract).\n return { raw: {}, eventType: 'other', metadata: { reason: 'test-seed-no-webhook' } }\n }\n\n async getStatus(_input: GetMessageStatusInput): Promise<MessageStatus> {\n return { status: 'sent' }\n }\n\n async convertOutbound(input: ConvertOutboundInput): Promise<ChannelNativeContent> {\n return {\n content: {\n text: input.body,\n bodyFormat: input.bodyFormat,\n },\n metadata: input.channelMetadata ?? {},\n }\n }\n\n async normalizeInbound(_raw: InboundMessage): Promise<NormalizedInboundMessage> {\n // The test-seed inbound path seeds MessageChannelLink rows directly and emits\n // the hub event, so this adapter never normalizes a raw inbound payload.\n throw new Error('[internal] TestSeedChannelAdapter.normalizeInbound is not used by the seed harness')\n }\n\n async validateCredentials(_input: ValidateCredentialsInput): Promise<ValidateCredentialsResult> {\n // No real server to authenticate against \u2014 accept any credentials so the\n // connect command persists a connected channel.\n return { ok: true }\n }\n}\n\n/**\n * Capabilities for the chat stub. Identical to the email stub's except for the\n * recipient shape: a chat channel is addressed by a provider-issued identifier\n * (a Discord snowflake), not an email address.\n *\n * Without this override the chat stub inherited `baseEmailCapabilities`, so it\n * claimed `channelType: 'discord'` while validating recipients as email\n * addresses \u2014 a channel that could not be addressed the way the provider it\n * imitates actually is. That left the hub's `'provider-native'` branch\n * (#4976: per-provider recipient validation, and the omitted recipient that\n * falls back to the adapter's own target) reachable only with a live Discord\n * bot, so no integration test could cover it and CI never exercised it.\n */\nconst testSeedChatCapabilities: ChannelCapabilities = {\n ...testSeedCapabilities,\n recipientFormat: 'provider-native',\n}\n\n/**\n * Chat-flavoured twin of {@link TestSeedChannelAdapter}: same network-free\n * behaviour, but it declares a non-email `channelType`, so a channel connected\n * through it is shaped like a real chat channel \u2014 including an\n * `externalIdentifier` of NULL when no email-ish credential key is supplied.\n */\nclass TestSeedChatChannelAdapter extends TestSeedChannelAdapter {\n readonly providerKey: string = TEST_SEED_CHAT_PROVIDER_KEY\n readonly channelType: string = 'discord'\n readonly capabilities = testSeedChatCapabilities\n\n async normalizeInbound(raw: InboundMessage): Promise<NormalizedInboundMessage> {\n // Unlike the email stub, this one is reachable: the test-seed ingest action\n // feeds it a chat-shaped frame so the message travels the real ingest path\n // (and therefore the real compose validation) rather than a SQL shortcut.\n const frame = (raw.raw ?? {}) as Record<string, unknown>\n const senderIdentifier = String(frame.senderIdentifier ?? '')\n if (!senderIdentifier) {\n throw new Error('[internal] TestSeedChatChannelAdapter requires a senderIdentifier')\n }\n return {\n externalMessageId: String(frame.externalMessageId ?? ''),\n externalConversationId: String(frame.externalConversationId ?? ''),\n senderIdentifier,\n senderDisplayName:\n typeof frame.senderDisplayName === 'string' ? frame.senderDisplayName : undefined,\n body: typeof frame.body === 'string' ? frame.body : '',\n bodyFormat: 'text',\n timestamp: new Date(),\n channelPayload: {},\n channelContentType: 'text/plain',\n channelMetadata: {},\n }\n }\n}\n\nlet cachedTestSeedAdapter: TestSeedChannelAdapter | null = null\nlet cachedTestSeedChatAdapter: TestSeedChatChannelAdapter | null = null\n\nfunction getTestSeedChannelAdapter(): TestSeedChannelAdapter {\n if (!cachedTestSeedAdapter) cachedTestSeedAdapter = new TestSeedChannelAdapter()\n return cachedTestSeedAdapter\n}\n\nfunction getTestSeedChatChannelAdapter(): TestSeedChatChannelAdapter {\n if (!cachedTestSeedChatAdapter) cachedTestSeedChatAdapter = new TestSeedChatChannelAdapter()\n return cachedTestSeedChatAdapter\n}\n\n/**\n * Register the test-seed adapter exactly once, but ONLY when the env flag is set.\n * Idempotent and safe to call from every container creation (`di.register`) \u2014 a\n * no-op when seeding is disabled or the adapter is already registered.\n */\nexport function ensureTestSeedAdapterRegistered(): void {\n if (!isTestChannelSeedingEnabled()) return\n registerSystemEmailProviderConfigResolver({\n providerKey: TEST_SEED_PROVIDER_KEY,\n isConfigured: isTestChannelSeedingEnabled,\n resolveCredentials: ({ fromAddress }) => ({ testSeed: true, fromAddress }),\n })\n if (!hasChannelAdapter(TEST_SEED_PROVIDER_KEY)) {\n registerChannelAdapter(getTestSeedChannelAdapter())\n }\n if (!hasChannelAdapter(TEST_SEED_CHAT_PROVIDER_KEY)) {\n registerChannelAdapter(getTestSeedChatChannelAdapter())\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,YAAY,OAAO,UAAU,IAAI,iBAAiB;AAC3D,SAAS,uBAAuB;AAChC,OAAO,UAAU;AAiBjB,SAAS,6BAA6B;AACtC,SAAS,mBAAmB,8BAA8B;AAC1D,SAAS,iDAAiD;AAyBnD,MAAM,yBAAyB;AAa/B,MAAM,8BAA8B;AAGpC,MAAM,2BAA2B;AACjC,MAAM,sCAAsC;AAC5C,MAAM,2CAA2C;AAUjD,MAAM,qCAAqC;AAO3C,SAAS,8BAAuC;AACrD,QAAM,MAAM,QAAQ,IAAI,wBAAwB;AAChD,MAAI,OAAO,QAAQ,SAAU,QAAO;AACpC,SAAO,CAAC,KAAK,QAAQ,OAAO,IAAI,EAAE,SAAS,IAAI,KAAK,EAAE,YAAY,CAAC;AACrE;AAsBA,eAAsB,8BACpB,IACA,OAUwB;AACxB,QAAM,OAAQ,MAAM,GAAG,cAAc,EAAE;AAAA,IACrC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASA;AAAA,MACE,WAAW,MAAM,WAAW;AAAA,MAC5B,MAAM,YAAY;AAAA,MAClB,MAAM;AAAA,MACN,MAAM,WAAW;AAAA,MACjB,MAAM,YAAY;AAAA,MAClB,MAAM;AAAA,MACN,MAAM;AAAA,MACN,MAAM;AAAA,IACR;AAAA,EACF;AACA,SAAO,KAAK,CAAC,GAAG,MAAM;AACxB;AAEA,SAAS,eAAe,OAAiD;AACvE,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,QAAM,aAAa,MAAM,KAAK;AAC9B,SAAO,WAAW,UAAU,KAAK,aAAa;AAChD;AAEO,SAAS,mCAAmC,eAAuC;AACxF,QAA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C,2BAAuB,0BAA0B,CAAC;AAAA,EACpD;AACA,MAAI,CAAC,kBAAkB,2BAA2B,GAAG;AACnD,2BAAuB,8BAA8B,CAAC;AAAA,EACxD;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
|
-
import {
|
|
2
|
+
import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
|
|
3
3
|
import { createLogger } from "@open-mercato/shared/lib/logger";
|
|
4
|
+
import { CommunicationChannel } from "./data/entities.js";
|
|
5
|
+
import { COMMUNICATION_CHANNELS_QUEUES } from "./lib/queue.js";
|
|
6
|
+
import { isTestChannelSeedingEnabled, TEST_SEED_PROVIDER_KEY } from "./lib/test-seed.js";
|
|
4
7
|
const logger = createLogger("communication_channels");
|
|
8
|
+
const TEST_SEED_FROM_ADDRESS = "system@test-seed.local";
|
|
5
9
|
const POLL_TICK_INTERVAL_SECONDS = Math.max(
|
|
6
10
|
10,
|
|
7
11
|
Number.parseInt(process.env.OM_HUB_POLL_SCHEDULER_TICK_SECONDS ?? "60", 10) || 60
|
|
@@ -51,6 +55,57 @@ const setup = {
|
|
|
51
55
|
]
|
|
52
56
|
},
|
|
53
57
|
async seedDefaults({ container, organizationId, tenantId }) {
|
|
58
|
+
if (isTestChannelSeedingEnabled() && process.env.SYSTEM_EMAIL_PROVIDER === TEST_SEED_PROVIDER_KEY) {
|
|
59
|
+
const em = container.resolve("em").fork();
|
|
60
|
+
const existing = await findOneWithDecryption(
|
|
61
|
+
em,
|
|
62
|
+
CommunicationChannel,
|
|
63
|
+
{
|
|
64
|
+
providerKey: TEST_SEED_PROVIDER_KEY,
|
|
65
|
+
channelType: "email",
|
|
66
|
+
tenantId,
|
|
67
|
+
organizationId,
|
|
68
|
+
userId: null,
|
|
69
|
+
deletedAt: null
|
|
70
|
+
},
|
|
71
|
+
void 0,
|
|
72
|
+
{ tenantId, organizationId }
|
|
73
|
+
);
|
|
74
|
+
if (!existing) {
|
|
75
|
+
em.persist(em.create(CommunicationChannel, {
|
|
76
|
+
providerKey: TEST_SEED_PROVIDER_KEY,
|
|
77
|
+
channelType: "email",
|
|
78
|
+
displayName: "Test Seed System Email",
|
|
79
|
+
externalIdentifier: TEST_SEED_FROM_ADDRESS,
|
|
80
|
+
userId: null,
|
|
81
|
+
isPrimary: false,
|
|
82
|
+
isActive: true,
|
|
83
|
+
status: "connected",
|
|
84
|
+
tenantId,
|
|
85
|
+
organizationId
|
|
86
|
+
}));
|
|
87
|
+
await em.flush();
|
|
88
|
+
}
|
|
89
|
+
try {
|
|
90
|
+
const credentialsService = container.resolve("integrationCredentialsService");
|
|
91
|
+
const testSeedIntegrationId = `channel_${TEST_SEED_PROVIDER_KEY}`;
|
|
92
|
+
const credentialScope = { tenantId, organizationId, userId: null };
|
|
93
|
+
const existingCredentials = await credentialsService.resolve(testSeedIntegrationId, credentialScope);
|
|
94
|
+
if (!existingCredentials) {
|
|
95
|
+
await credentialsService.save(
|
|
96
|
+
testSeedIntegrationId,
|
|
97
|
+
{ testSeed: true, fromAddress: TEST_SEED_FROM_ADDRESS },
|
|
98
|
+
credentialScope
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
} catch (error) {
|
|
102
|
+
logger.warn("Test-seed email credentials could not be stored; tenant-scoped sends will fail closed", {
|
|
103
|
+
err: error,
|
|
104
|
+
tenantId,
|
|
105
|
+
organizationId
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
}
|
|
54
109
|
const cradle = container;
|
|
55
110
|
if (typeof cradle.hasRegistration !== "function" || !cradle.hasRegistration("schedulerService")) {
|
|
56
111
|
return;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/modules/communication_channels/setup.ts"],
|
|
4
|
-
"sourcesContent": ["import { createHash } from 'node:crypto'\nimport type { ModuleSetupConfig } from '@open-mercato/shared/modules/setup'\nimport { COMMUNICATION_CHANNELS_QUEUES } from './lib/queue'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('communication_channels')\n\ntype SchedulerServiceLike = {\n register: (registration: {\n id: string\n name: string\n scopeType: 'system' | 'organization' | 'tenant'\n organizationId?: string\n tenantId?: string\n scheduleType: 'cron' | 'interval'\n scheduleValue: string\n timezone?: string\n targetType: 'queue' | 'command'\n targetQueue?: string\n targetPayload?: unknown\n sourceType?: 'user' | 'module'\n sourceModule?: string\n isEnabled?: boolean\n description?: string\n }) => Promise<void>\n}\n\n/**\n * Tick interval in seconds. Default 60s per email integration spec\n * \u00A7 Hub Deltas \u2192 Delta 6 (scheduler mechanism).\n */\nconst POLL_TICK_INTERVAL_SECONDS = Math.max(\n 10,\n Number.parseInt(process.env.OM_HUB_POLL_SCHEDULER_TICK_SECONDS ?? '60', 10) || 60,\n)\n\n/**\n * `scheduled_jobs.id` is a uuid column, so a module-owned schedule's stable\n * registration key must be hashed into a uuid rather than used verbatim \u2014 this\n * keeps `schedulerService.register()` an idempotent upsert across re-runs of\n * seedDefaults instead of trying to insert a raw string into the uuid PK.\n */\nfunction stableScheduleUuid(stableKey: string): string {\n const hex = createHash('sha256').update(stableKey).digest('hex')\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`\n}\n\nfunction stablePollTickScheduleId(organizationId: string): string {\n return stableScheduleUuid(`communication_channels:poll-tick:${organizationId}`)\n}\n\nexport const setup: ModuleSetupConfig = {\n defaultRoleFeatures: {\n superadmin: [\n 'communication_channels.view',\n 'communication_channels.manage',\n 'communication_channels.react',\n 'communication_channels.assign',\n 'communication_channels.connect_user_channel',\n 'communication_channels.connect_tenant_channel',\n 'communication_channels.admin',\n 'communication_channels.channel.import_history',\n 'communication_channels.channel.push.manage',\n ],\n admin: [\n 'communication_channels.view',\n 'communication_channels.manage',\n 'communication_channels.react',\n 'communication_channels.assign',\n 'communication_channels.connect_user_channel',\n 'communication_channels.connect_tenant_channel',\n 'communication_channels.admin',\n 'communication_channels.channel.import_history',\n 'communication_channels.channel.push.manage',\n ],\n manager: [\n 'communication_channels.view',\n 'communication_channels.manage',\n 'communication_channels.react',\n 'communication_channels.assign',\n 'communication_channels.connect_user_channel',\n ],\n employee: [\n 'communication_channels.view',\n 'communication_channels.react',\n 'communication_channels.connect_user_channel',\n ],\n },\n\n async seedDefaults({ container, organizationId, tenantId }) {\n /**\n * Register the per-channel polling tick with `@open-mercato/scheduler`.\n *\n * Per email integration spec \u00A7 Hub Deltas \u2192 Delta 6: every\n * `POLL_TICK_INTERVAL_SECONDS` (default 60s), enqueue a single\n * `communication-channels-poll-tick` job that enumerates due channels and\n * fans out to the `communication-channels-poll` queue.\n *\n * The registration is per-organization (one tick row per org/tenant pair)\n * so multi-tenant deploys schedule independently. Skipped silently when the\n * scheduler module isn't enabled \u2014 keeps the hub usable in scheduler-less\n * test harnesses.\n */\n const cradle = container as { hasRegistration?: (name: string) => boolean }\n if (typeof cradle.hasRegistration !== 'function' || !cradle.hasRegistration('schedulerService')) {\n return\n }\n const schedulerService = container.resolve('schedulerService') as SchedulerServiceLike\n // Best-effort: a scheduler failure must not abort tenant initialization for\n // every other module (mirrors the ai_assistant setup pattern). The schedule\n // ids are deterministic uuids so re-runs upsert idempotently.\n try {\n await schedulerService.register({\n id: stablePollTickScheduleId(organizationId),\n name: 'Communication channels poll tick',\n description:\n `Enumerates active polling channels every ${POLL_TICK_INTERVAL_SECONDS}s and enqueues per-channel poll jobs.`,\n scopeType: 'organization',\n organizationId,\n tenantId,\n scheduleType: 'interval',\n scheduleValue: `${POLL_TICK_INTERVAL_SECONDS}s`,\n timezone: 'UTC',\n targetType: 'queue',\n targetQueue: COMMUNICATION_CHANNELS_QUEUES.pollTick,\n targetPayload: {\n scope: { tenantId, organizationId },\n },\n sourceType: 'module',\n sourceModule: 'communication_channels',\n isEnabled: true,\n })\n\n // Spec C \u00A7 Phase C4 \u2014 Gmail watch renewal cron, per-org so multi-tenant\n // deploys schedule independently.\n await schedulerService.register({\n id: stableScheduleUuid(`communication_channels:gmail-renew-watch:${organizationId}`),\n name: 'Gmail watch renewal',\n description:\n 'Daily 04:00 UTC. Re-issues gmail.users.watch for channels within OM_PUSH_RENEWAL_GMAIL_LEAD_HOURS of expiry.',\n scopeType: 'organization',\n organizationId,\n tenantId,\n scheduleType: 'cron',\n scheduleValue: '0 4 * * *',\n timezone: 'UTC',\n targetType: 'queue',\n targetQueue: COMMUNICATION_CHANNELS_QUEUES.gmailRenewWatch,\n targetPayload: { scope: { tenantId, organizationId } },\n sourceType: 'module',\n sourceModule: 'communication_channels',\n isEnabled: true,\n })\n } catch (error) {\n logger.warn('Failed to register module schedules', { err: error })\n }\n },\n}\n\nexport default setup\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,kBAAkB;AAE3B,SAAS,
|
|
4
|
+
"sourcesContent": ["import { createHash } from 'node:crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport type { ModuleSetupConfig } from '@open-mercato/shared/modules/setup'\nimport { CommunicationChannel } from './data/entities'\nimport { COMMUNICATION_CHANNELS_QUEUES } from './lib/queue'\nimport { isTestChannelSeedingEnabled, TEST_SEED_PROVIDER_KEY } from './lib/test-seed'\n\nconst logger = createLogger('communication_channels')\n\ntype SchedulerServiceLike = {\n register: (registration: {\n id: string\n name: string\n scopeType: 'system' | 'organization' | 'tenant'\n organizationId?: string\n tenantId?: string\n scheduleType: 'cron' | 'interval'\n scheduleValue: string\n timezone?: string\n targetType: 'queue' | 'command'\n targetQueue?: string\n targetPayload?: unknown\n sourceType?: 'user' | 'module'\n sourceModule?: string\n isEnabled?: boolean\n description?: string\n }) => Promise<void>\n}\n\ntype CredentialsServiceLike = {\n resolve: (\n integrationId: string,\n scope: { organizationId: string; tenantId: string; userId?: string | null },\n ) => Promise<Record<string, unknown> | null>\n save: (\n integrationId: string,\n credentials: Record<string, unknown>,\n scope: { organizationId: string; tenantId: string; userId?: string | null },\n ) => Promise<void>\n}\n\n/**\n * Sender the test-seed channel presents. Shared by the channel row's\n * `externalIdentifier` and its seeded credentials so both describe one address.\n */\nconst TEST_SEED_FROM_ADDRESS = 'system@test-seed.local'\n\n/**\n * Tick interval in seconds. Default 60s per email integration spec\n * \u00A7 Hub Deltas \u2192 Delta 6 (scheduler mechanism).\n */\nconst POLL_TICK_INTERVAL_SECONDS = Math.max(\n 10,\n Number.parseInt(process.env.OM_HUB_POLL_SCHEDULER_TICK_SECONDS ?? '60', 10) || 60,\n)\n\n/**\n * `scheduled_jobs.id` is a uuid column, so a module-owned schedule's stable\n * registration key must be hashed into a uuid rather than used verbatim \u2014 this\n * keeps `schedulerService.register()` an idempotent upsert across re-runs of\n * seedDefaults instead of trying to insert a raw string into the uuid PK.\n */\nfunction stableScheduleUuid(stableKey: string): string {\n const hex = createHash('sha256').update(stableKey).digest('hex')\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`\n}\n\nfunction stablePollTickScheduleId(organizationId: string): string {\n return stableScheduleUuid(`communication_channels:poll-tick:${organizationId}`)\n}\n\nexport const setup: ModuleSetupConfig = {\n defaultRoleFeatures: {\n superadmin: [\n 'communication_channels.view',\n 'communication_channels.manage',\n 'communication_channels.react',\n 'communication_channels.assign',\n 'communication_channels.connect_user_channel',\n 'communication_channels.connect_tenant_channel',\n 'communication_channels.admin',\n 'communication_channels.channel.import_history',\n 'communication_channels.channel.push.manage',\n ],\n admin: [\n 'communication_channels.view',\n 'communication_channels.manage',\n 'communication_channels.react',\n 'communication_channels.assign',\n 'communication_channels.connect_user_channel',\n 'communication_channels.connect_tenant_channel',\n 'communication_channels.admin',\n 'communication_channels.channel.import_history',\n 'communication_channels.channel.push.manage',\n ],\n manager: [\n 'communication_channels.view',\n 'communication_channels.manage',\n 'communication_channels.react',\n 'communication_channels.assign',\n 'communication_channels.connect_user_channel',\n ],\n employee: [\n 'communication_channels.view',\n 'communication_channels.react',\n 'communication_channels.connect_user_channel',\n ],\n },\n\n async seedDefaults({ container, organizationId, tenantId }) {\n if (isTestChannelSeedingEnabled() && process.env.SYSTEM_EMAIL_PROVIDER === TEST_SEED_PROVIDER_KEY) {\n const em = (container.resolve('em') as EntityManager).fork()\n const existing = await findOneWithDecryption(\n em,\n CommunicationChannel,\n {\n providerKey: TEST_SEED_PROVIDER_KEY,\n channelType: 'email',\n tenantId,\n organizationId,\n userId: null,\n deletedAt: null,\n },\n undefined,\n { tenantId, organizationId },\n )\n if (!existing) {\n em.persist(em.create(CommunicationChannel, {\n providerKey: TEST_SEED_PROVIDER_KEY,\n channelType: 'email',\n displayName: 'Test Seed System Email',\n externalIdentifier: TEST_SEED_FROM_ADDRESS,\n userId: null,\n isPrimary: false,\n isActive: true,\n status: 'connected',\n tenantId,\n organizationId,\n }))\n await em.flush()\n }\n\n /**\n * Seeding the channel row without credentials is not a neutral state \u2014 it is a\n * fail-closed one. Once a tenant owns a Hub channel, `resolveTenantCredentials`\n * deliberately refuses to fall back to instance-wide env credentials, so every\n * tenant-scoped send throws `SYSTEM_EMAIL_CREDENTIALS_NOT_CONFIGURED`. Callers that\n * treat a failed send as a failed write (customer invitations roll back and return\n * 502) then fail outright rather than merely losing the email.\n *\n * Seeding credentials alongside the row makes the harness model a tenant that\n * finished configuring its provider, which is also the only one of the three\n * credential cases the integration suite would otherwise never exercise.\n */\n // Best-effort, like the scheduler registration below: credential storage needs the\n // integrations module and a usable encryption key, and neither is guaranteed in every\n // harness. A failure here must not abort tenant initialization for every other module.\n try {\n const credentialsService = container.resolve('integrationCredentialsService') as CredentialsServiceLike\n const testSeedIntegrationId = `channel_${TEST_SEED_PROVIDER_KEY}`\n const credentialScope = { tenantId, organizationId, userId: null }\n const existingCredentials = await credentialsService.resolve(testSeedIntegrationId, credentialScope)\n if (!existingCredentials) {\n await credentialsService.save(\n testSeedIntegrationId,\n { testSeed: true, fromAddress: TEST_SEED_FROM_ADDRESS },\n credentialScope,\n )\n }\n } catch (error) {\n logger.warn('Test-seed email credentials could not be stored; tenant-scoped sends will fail closed', {\n err: error,\n tenantId,\n organizationId,\n })\n }\n }\n\n /**\n * Register the per-channel polling tick with `@open-mercato/scheduler`.\n *\n * Per email integration spec \u00A7 Hub Deltas \u2192 Delta 6: every\n * `POLL_TICK_INTERVAL_SECONDS` (default 60s), enqueue a single\n * `communication-channels-poll-tick` job that enumerates due channels and\n * fans out to the `communication-channels-poll` queue.\n *\n * The registration is per-organization (one tick row per org/tenant pair)\n * so multi-tenant deploys schedule independently. Skipped silently when the\n * scheduler module isn't enabled \u2014 keeps the hub usable in scheduler-less\n * test harnesses.\n */\n const cradle = container as { hasRegistration?: (name: string) => boolean }\n if (typeof cradle.hasRegistration !== 'function' || !cradle.hasRegistration('schedulerService')) {\n return\n }\n const schedulerService = container.resolve('schedulerService') as SchedulerServiceLike\n // Best-effort: a scheduler failure must not abort tenant initialization for\n // every other module (mirrors the ai_assistant setup pattern). The schedule\n // ids are deterministic uuids so re-runs upsert idempotently.\n try {\n await schedulerService.register({\n id: stablePollTickScheduleId(organizationId),\n name: 'Communication channels poll tick',\n description:\n `Enumerates active polling channels every ${POLL_TICK_INTERVAL_SECONDS}s and enqueues per-channel poll jobs.`,\n scopeType: 'organization',\n organizationId,\n tenantId,\n scheduleType: 'interval',\n scheduleValue: `${POLL_TICK_INTERVAL_SECONDS}s`,\n timezone: 'UTC',\n targetType: 'queue',\n targetQueue: COMMUNICATION_CHANNELS_QUEUES.pollTick,\n targetPayload: {\n scope: { tenantId, organizationId },\n },\n sourceType: 'module',\n sourceModule: 'communication_channels',\n isEnabled: true,\n })\n\n // Spec C \u00A7 Phase C4 \u2014 Gmail watch renewal cron, per-org so multi-tenant\n // deploys schedule independently.\n await schedulerService.register({\n id: stableScheduleUuid(`communication_channels:gmail-renew-watch:${organizationId}`),\n name: 'Gmail watch renewal',\n description:\n 'Daily 04:00 UTC. Re-issues gmail.users.watch for channels within OM_PUSH_RENEWAL_GMAIL_LEAD_HOURS of expiry.',\n scopeType: 'organization',\n organizationId,\n tenantId,\n scheduleType: 'cron',\n scheduleValue: '0 4 * * *',\n timezone: 'UTC',\n targetType: 'queue',\n targetQueue: COMMUNICATION_CHANNELS_QUEUES.gmailRenewWatch,\n targetPayload: { scope: { tenantId, organizationId } },\n sourceType: 'module',\n sourceModule: 'communication_channels',\n isEnabled: true,\n })\n } catch (error) {\n logger.warn('Failed to register module schedules', { err: error })\n }\n },\n}\n\nexport default setup\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,kBAAkB;AAE3B,SAAS,6BAA6B;AACtC,SAAS,oBAAoB;AAE7B,SAAS,4BAA4B;AACrC,SAAS,qCAAqC;AAC9C,SAAS,6BAA6B,8BAA8B;AAEpE,MAAM,SAAS,aAAa,wBAAwB;AAsCpD,MAAM,yBAAyB;AAM/B,MAAM,6BAA6B,KAAK;AAAA,EACtC;AAAA,EACA,OAAO,SAAS,QAAQ,IAAI,sCAAsC,MAAM,EAAE,KAAK;AACjF;AAQA,SAAS,mBAAmB,WAA2B;AACrD,QAAM,MAAM,WAAW,QAAQ,EAAE,OAAO,SAAS,EAAE,OAAO,KAAK;AAC/D,SAAO,GAAG,IAAI,MAAM,GAAG,CAAC,CAAC,IAAI,IAAI,MAAM,GAAG,EAAE,CAAC,IAAI,IAAI,MAAM,IAAI,EAAE,CAAC,IAAI,IAAI,MAAM,IAAI,EAAE,CAAC,IAAI,IAAI,MAAM,IAAI,EAAE,CAAC;AAC9G;AAEA,SAAS,yBAAyB,gBAAgC;AAChE,SAAO,mBAAmB,oCAAoC,cAAc,EAAE;AAChF;AAEO,MAAM,QAA2B;AAAA,EACtC,qBAAqB;AAAA,IACnB,YAAY;AAAA,MACV;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,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AAEA,IAAO,gBAAQ;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/modules/customer_accounts/api/admin/users-invite.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport { CustomerInvitationService } from '@open-mercato/core/modules/customer_accounts/services/customerInvitationService'\nimport { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'\nimport { inviteUserSchema } from '@open-mercato/core/modules/customer_accounts/data/validators'\nimport { isOwnedCompanyEntity, isOwnedPersonEntity, resolveOwnedCompanyForPerson } from '@open-mercato/core/modules/customer_accounts/lib/customerEntityOwnership'\nimport { rateLimitErrorSchema } from '@open-mercato/shared/lib/ratelimit/helpers'\nimport {\n checkAuthRateLimit,\n customerInviteRateLimitConfig,\n customerInviteIpRateLimitConfig,\n} from '@open-mercato/core/modules/customer_accounts/lib/rateLimiter'\nimport { readNormalizedEmailFromJsonRequest } from '@open-mercato/core/modules/customer_accounts/lib/rateLimitIdentifier'\nimport { sendCustomerInvitationEmail } from '@open-mercato/core/modules/customer_accounts/lib/invitationEmail'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { CustomerUserInvitation } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { findAndCountWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { lookupHashCandidates } from '@open-mercato/shared/lib/encryption/aes'\n\nconst logger = createLogger('customer_accounts').child({ component: 'admin-users-invite' })\n\nconst UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\nexport const metadata = {}\n\nfunction resolveInvitedByUserId(auth: NonNullable<Awaited<ReturnType<typeof getAuthFromRequest>>>): string | null {\n if (auth.isApiKey) return auth.userId ?? null\n return auth.sub\n}\n\nfunction parsePositiveInt(value: string | null, fallback: number): number {\n const parsed = Number.parseInt(value ?? '', 10)\n return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback\n}\n\n// Pending invitations are the only trace a not-yet-accepted invite leaves: the\n// customer user row is created on accept, so every users-backed surface (admin\n// users list, the CRM person \"account status\" widget) shows the same empty\n// state right after a successful invite (#4950). This read surface makes that\n// pending state queryable. The one-time token stays server-side.\nexport async function GET(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const rbacService = container.resolve('rbacService') as RbacService\n const hasAccess = await rbacService.userHasAllFeatures(auth.sub, ['customer_accounts.view'], { tenantId: auth.tenantId, organizationId: auth.orgId })\n if (!hasAccess) {\n return NextResponse.json({ ok: false, error: 'Insufficient permissions' }, { status: 403 })\n }\n\n const url = new URL(req.url)\n // A non-numeric page/pageSize must not reach the query as NaN.\n const page = Math.max(1, parsePositiveInt(url.searchParams.get('page'), 1))\n const pageSize = Math.min(100, Math.max(1, parsePositiveInt(url.searchParams.get('pageSize'), 25)))\n const personEntityId = url.searchParams.get('personEntityId')\n const customerEntityId = url.searchParams.get('customerEntityId')\n const email = url.searchParams.get('email')\n\n for (const value of [personEntityId, customerEntityId]) {\n if (value && !UUID_PATTERN.test(value)) {\n return NextResponse.json({ ok: false, error: 'Validation failed' }, { status: 400 })\n }\n }\n\n // Pending means: still open (not accepted, not cancelled) and not expired.\n const where: Record<string, unknown> = {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n acceptedAt: null,\n cancelledAt: null,\n expiresAt: { $gt: new Date() },\n }\n if (personEntityId) where.personEntityId = personEntityId\n if (customerEntityId) where.customerEntityId = customerEntityId\n // email is stored encrypted, so match on the deterministic lookup hash.\n if (email) where.emailHash = { $in: lookupHashCandidates(email) }\n\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n const [invitations, total] = await findAndCountWithDecryption(\n em,\n CustomerUserInvitation,\n where as any,\n {\n orderBy: { createdAt: 'DESC' },\n limit: pageSize,\n offset: (page - 1) * pageSize,\n },\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n\n const items = invitations.map((invitation) => ({\n id: invitation.id,\n email: invitation.email,\n displayName: invitation.displayName || null,\n customerEntityId: invitation.customerEntityId || null,\n personEntityId: invitation.personEntityId || null,\n roleIds: Array.isArray(invitation.roleIdsJson) ? invitation.roleIdsJson : [],\n invitedByUserId: invitation.invitedByUserId || null,\n expiresAt: invitation.expiresAt,\n createdAt: invitation.createdAt,\n }))\n\n return NextResponse.json({\n ok: true,\n items,\n total,\n totalPages: Math.max(1, Math.ceil(total / pageSize)),\n page,\n })\n}\n\nexport async function POST(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const rateLimitEmail = await readNormalizedEmailFromJsonRequest(req)\n const { error: rateLimitError } = await checkAuthRateLimit({\n req,\n ipConfig: customerInviteIpRateLimitConfig,\n compoundConfig: customerInviteRateLimitConfig,\n compoundIdentifier: rateLimitEmail,\n })\n if (rateLimitError) return rateLimitError\n\n const container = await createRequestContainer()\n const rbacService = container.resolve('rbacService') as RbacService\n const hasAccess = await rbacService.userHasAllFeatures(auth.sub, ['customer_accounts.invite'], { tenantId: auth.tenantId, organizationId: auth.orgId })\n if (!hasAccess) {\n return NextResponse.json({ ok: false, error: 'Insufficient permissions' }, { status: 403 })\n }\n\n let body: unknown\n try {\n body = await req.json()\n } catch {\n return NextResponse.json({ ok: false, error: 'Invalid request body' }, { status: 400 })\n }\n\n const parsed = inviteUserSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ ok: false, error: 'Validation failed', details: parsed.error.flatten().fieldErrors }, { status: 400 })\n }\n\n // Reject a customerEntityId the caller does not own. customerEntityId is the\n // CRM company FK; without this check a non-company (e.g. a person) entity id\n // or a company from another org poisons the invitation and every later user\n // edit fails with \"Company not found\" (#4362, #2693).\n if (parsed.data.customerEntityId) {\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n const owned = await isOwnedCompanyEntity(em, parsed.data.customerEntityId, {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n })\n if (!owned) {\n return NextResponse.json({ ok: false, error: 'Company not found' }, { status: 400 })\n }\n }\n\n // Same guard for the person FK: it is copied onto the customer user on accept\n // and makes `autoLinkCrm` short-circuit, so an unowned id would permanently\n // cross-link the portal user to another org's CRM person.\n let resolvedCustomerEntityId = parsed.data.customerEntityId || null\n if (parsed.data.personEntityId) {\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n const owned = await isOwnedPersonEntity(em, parsed.data.personEntityId, {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n })\n if (!owned) {\n return NextResponse.json({ ok: false, error: 'Person not found' }, { status: 400 })\n }\n\n // An invitation raised from a person card carries only the person FK, and the\n // accepted user then short-circuits `autoLinkCrm`. Resolve the person's company\n // here so the user lands with a company scope key: the portal Users page, portal\n // invitations, and the company detail \"Portal users\" group all filter on it.\n if (!resolvedCustomerEntityId) {\n resolvedCustomerEntityId = await resolveOwnedCompanyForPerson(em, parsed.data.personEntityId, {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n })\n }\n }\n\n const customerInvitationService = container.resolve('customerInvitationService') as CustomerInvitationService\n\n const { invitation, rawToken, rollbackState } = await customerInvitationService.createInvitation(\n parsed.data.email,\n { tenantId: auth.tenantId!, organizationId: auth.orgId! },\n {\n customerEntityId: resolvedCustomerEntityId,\n personEntityId: parsed.data.personEntityId || null,\n roleIds: parsed.data.roleIds,\n invitedByUserId: resolveInvitedByUserId(auth),\n displayName: parsed.data.displayName || null,\n },\n )\n\n try {\n await sendCustomerInvitationEmail({\n container,\n organizationId: auth.orgId!,\n email: invitation.email,\n rawToken,\n })\n } catch (error) {\n logger.error('Invitation email failed', { err: error })\n try {\n await customerInvitationService.rollbackInvitation(invitation, rollbackState)\n } catch (rollbackError) {\n logger.error('Invitation rollback failed', { err: rollbackError })\n }\n return NextResponse.json({ ok: false, error: 'Invitation email could not be sent' }, { status: 502 })\n }\n\n // Emit only after the email is sent, so a subscriber observing \"invited\" can\n // assume the recipient was actually notified (no event fires on the 502 path).\n void emitCustomerAccountsEvent('customer_accounts.user.invited', {\n invitationId: invitation.id,\n email: invitation.email,\n customerEntityId: invitation.customerEntityId || null,\n invitedByType: 'staff',\n tenantId: auth.tenantId!,\n organizationId: auth.orgId!,\n }).catch(() => undefined)\n\n return NextResponse.json({\n ok: true,\n invitation: {\n id: invitation.id,\n email: invitation.email,\n // Echo the stored CRM links so the caller can see which company the person\n // invite resolved to. The token stays unexposed.\n customerEntityId: invitation.customerEntityId || null,\n personEntityId: invitation.personEntityId || null,\n expiresAt: invitation.expiresAt,\n },\n }, { status: 201 })\n}\n\nconst successSchema = z.object({\n ok: z.literal(true),\n invitation: z.object({\n id: z.string().uuid(),\n email: z.string(),\n customerEntityId: z.string().uuid().nullable(),\n personEntityId: z.string().uuid().nullable(),\n expiresAt: z.string().datetime(),\n }),\n})\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Invite customer user (admin)',\n description: 'Creates a staff-initiated invitation for a new customer user. The invitedByUserId is set from the staff auth context.',\n tags: ['Customer Accounts Admin'],\n requestBody: { schema: inviteUserSchema },\n responses: [{ status: 201, description: 'Invitation created', schema: successSchema }],\n errors: [\n { status: 400, description: 'Validation failed', schema: errorSchema },\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 403, description: 'Insufficient permissions', schema: errorSchema },\n { status: 429, description: 'Too many invitation requests', schema: rateLimitErrorSchema },\n { status: 502, description: 'Invitation email could not be sent', schema: errorSchema },\n ],\n}\n\nconst listQuerySchema = z.object({\n page: z.coerce.number().int().min(1).optional(),\n pageSize: z.coerce.number().int().min(1).max(100).optional(),\n personEntityId: z.string().uuid().optional(),\n customerEntityId: z.string().uuid().optional(),\n email: z.string().optional(),\n})\n\nconst listSuccessSchema = z.object({\n ok: z.literal(true),\n items: z.array(z.object({\n id: z.string().uuid(),\n email: z.string(),\n displayName: z.string().nullable(),\n customerEntityId: z.string().uuid().nullable(),\n personEntityId: z.string().uuid().nullable(),\n roleIds: z.array(z.string().uuid()),\n invitedByUserId: z.string().uuid().nullable(),\n expiresAt: z.string().datetime(),\n createdAt: z.string().datetime(),\n })),\n total: z.number(),\n totalPages: z.number(),\n page: z.number(),\n})\n\nconst listMethodDoc: OpenApiMethodDoc = {\n summary: 'List pending customer invitations (admin)',\n description: 'Lists invitations that are still pending \u2014 not accepted, not cancelled, and not expired \u2014 for the caller\\'s tenant and organization. The invitation token is never returned.',\n tags: ['Customer Accounts Admin'],\n query: listQuerySchema,\n responses: [{ status: 200, description: 'Pending invitations', schema: listSuccessSchema }],\n errors: [\n { status: 400, description: 'Validation failed', schema: errorSchema },\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 403, description: 'Insufficient permissions', schema: errorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Invite customer user (admin)',\n methods: { GET: listMethodDoc, POST: methodDoc },\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAGvC,SAAS,iCAAiC;AAC1C,SAAS,wBAAwB;AACjC,SAAS,sBAAsB,qBAAqB,oCAAoC;AACxF,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,0CAA0C;AACnD,SAAS,mCAAmC;AAC5C,SAAS,oBAAoB;AAC7B,SAAS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AE,KAAK;AAAA,IACpB,OAAO,EAAE,OAAO;AAAA,IAChB,aAAa,EAAE,OAAO,EAAE,SAAS;AAAA,IACjC,kBAAkB,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AAAA,IAC7C,gBAAgB,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AAAA,IAC3C,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC;AAAA,IAClC,iBAAiB,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AAAA,IAC5C,WAAW,EAAE,OAAO,EAAE,SAAS;AAAA,IAC/B,WAAW,EAAE,OAAO,EAAE,SAAS;AAAA,EACjC,CAAC,CAAC;AAAA,EACF,OAAO,EAAE,OAAO;AAAA,EAChB,YAAY,EAAE,OAAO;AAAA,EACrB,MAAM,EAAE,OAAO;AACjB,CAAC;AAED,MAAM,gBAAkC;AAAA,EACtC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,yBAAyB;AAAA,EAChC,OAAO;AAAA,EACP,WAAW,CAAC,EAAE,QAAQ,KAAK,aAAa,uBAAuB,QAAQ,kBAAkB,CAAC;AAAA,EAC1F,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,YAAY;AAAA,IACrE,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,YAAY;AAAA,IACrE,EAAE,QAAQ,KAAK,aAAa,4BAA4B,QAAQ,YAAY;AAAA,EAC9E;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,SAAS,EAAE,KAAK,eAAe,MAAM,UAAU;AACjD;",
|
|
4
|
+
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport { CustomerInvitationService } from '@open-mercato/core/modules/customer_accounts/services/customerInvitationService'\nimport { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'\nimport { inviteUserSchema } from '@open-mercato/core/modules/customer_accounts/data/validators'\nimport { isOwnedCompanyEntity, isOwnedPersonEntity, resolveOwnedCompanyForPerson } from '@open-mercato/core/modules/customer_accounts/lib/customerEntityOwnership'\nimport { rateLimitErrorSchema } from '@open-mercato/shared/lib/ratelimit/helpers'\nimport {\n checkAuthRateLimit,\n customerInviteRateLimitConfig,\n customerInviteIpRateLimitConfig,\n} from '@open-mercato/core/modules/customer_accounts/lib/rateLimiter'\nimport { readNormalizedEmailFromJsonRequest } from '@open-mercato/core/modules/customer_accounts/lib/rateLimitIdentifier'\nimport { sendCustomerInvitationEmail } from '@open-mercato/core/modules/customer_accounts/lib/invitationEmail'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { CustomerUserInvitation } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { findAndCountWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { lookupHashCandidates } from '@open-mercato/shared/lib/encryption/aes'\n\nconst logger = createLogger('customer_accounts').child({ component: 'admin-users-invite' })\n\nconst UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\nexport const metadata = {}\n\nfunction resolveInvitedByUserId(auth: NonNullable<Awaited<ReturnType<typeof getAuthFromRequest>>>): string | null {\n if (auth.isApiKey) return auth.userId ?? null\n return auth.sub\n}\n\nfunction parsePositiveInt(value: string | null, fallback: number): number {\n const parsed = Number.parseInt(value ?? '', 10)\n return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback\n}\n\n// Pending invitations are the only trace a not-yet-accepted invite leaves: the\n// customer user row is created on accept, so every users-backed surface (admin\n// users list, the CRM person \"account status\" widget) shows the same empty\n// state right after a successful invite (#4950). This read surface makes that\n// pending state queryable. The one-time token stays server-side.\nexport async function GET(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const rbacService = container.resolve('rbacService') as RbacService\n const hasAccess = await rbacService.userHasAllFeatures(auth.sub, ['customer_accounts.view'], { tenantId: auth.tenantId, organizationId: auth.orgId })\n if (!hasAccess) {\n return NextResponse.json({ ok: false, error: 'Insufficient permissions' }, { status: 403 })\n }\n\n const url = new URL(req.url)\n // A non-numeric page/pageSize must not reach the query as NaN.\n const page = Math.max(1, parsePositiveInt(url.searchParams.get('page'), 1))\n const pageSize = Math.min(100, Math.max(1, parsePositiveInt(url.searchParams.get('pageSize'), 25)))\n const personEntityId = url.searchParams.get('personEntityId')\n const customerEntityId = url.searchParams.get('customerEntityId')\n const email = url.searchParams.get('email')\n\n for (const value of [personEntityId, customerEntityId]) {\n if (value && !UUID_PATTERN.test(value)) {\n return NextResponse.json({ ok: false, error: 'Validation failed' }, { status: 400 })\n }\n }\n\n // Pending means: still open (not accepted, not cancelled) and not expired.\n const where: Record<string, unknown> = {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n acceptedAt: null,\n cancelledAt: null,\n expiresAt: { $gt: new Date() },\n }\n if (personEntityId) where.personEntityId = personEntityId\n if (customerEntityId) where.customerEntityId = customerEntityId\n // email is stored encrypted, so match on the deterministic lookup hash.\n if (email) where.emailHash = { $in: lookupHashCandidates(email) }\n\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n const [invitations, total] = await findAndCountWithDecryption(\n em,\n CustomerUserInvitation,\n where as any,\n {\n orderBy: { createdAt: 'DESC' },\n limit: pageSize,\n offset: (page - 1) * pageSize,\n },\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n\n const items = invitations.map((invitation) => ({\n id: invitation.id,\n email: invitation.email,\n displayName: invitation.displayName || null,\n customerEntityId: invitation.customerEntityId || null,\n personEntityId: invitation.personEntityId || null,\n roleIds: Array.isArray(invitation.roleIdsJson) ? invitation.roleIdsJson : [],\n invitedByUserId: invitation.invitedByUserId || null,\n expiresAt: invitation.expiresAt,\n createdAt: invitation.createdAt,\n }))\n\n return NextResponse.json({\n ok: true,\n items,\n total,\n totalPages: Math.max(1, Math.ceil(total / pageSize)),\n page,\n })\n}\n\nexport async function POST(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const rateLimitEmail = await readNormalizedEmailFromJsonRequest(req)\n const { error: rateLimitError } = await checkAuthRateLimit({\n req,\n ipConfig: customerInviteIpRateLimitConfig,\n compoundConfig: customerInviteRateLimitConfig,\n compoundIdentifier: rateLimitEmail,\n })\n if (rateLimitError) return rateLimitError\n\n const container = await createRequestContainer()\n const rbacService = container.resolve('rbacService') as RbacService\n const hasAccess = await rbacService.userHasAllFeatures(auth.sub, ['customer_accounts.invite'], { tenantId: auth.tenantId, organizationId: auth.orgId })\n if (!hasAccess) {\n return NextResponse.json({ ok: false, error: 'Insufficient permissions' }, { status: 403 })\n }\n\n let body: unknown\n try {\n body = await req.json()\n } catch {\n return NextResponse.json({ ok: false, error: 'Invalid request body' }, { status: 400 })\n }\n\n const parsed = inviteUserSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ ok: false, error: 'Validation failed', details: parsed.error.flatten().fieldErrors }, { status: 400 })\n }\n\n // Reject a customerEntityId the caller does not own. customerEntityId is the\n // CRM company FK; without this check a non-company (e.g. a person) entity id\n // or a company from another org poisons the invitation and every later user\n // edit fails with \"Company not found\" (#4362, #2693).\n if (parsed.data.customerEntityId) {\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n const owned = await isOwnedCompanyEntity(em, parsed.data.customerEntityId, {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n })\n if (!owned) {\n return NextResponse.json({ ok: false, error: 'Company not found' }, { status: 400 })\n }\n }\n\n // Same guard for the person FK: it is copied onto the customer user on accept\n // and makes `autoLinkCrm` short-circuit, so an unowned id would permanently\n // cross-link the portal user to another org's CRM person.\n let resolvedCustomerEntityId = parsed.data.customerEntityId || null\n if (parsed.data.personEntityId) {\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n const owned = await isOwnedPersonEntity(em, parsed.data.personEntityId, {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n })\n if (!owned) {\n return NextResponse.json({ ok: false, error: 'Person not found' }, { status: 400 })\n }\n\n // An invitation raised from a person card carries only the person FK, and the\n // accepted user then short-circuits `autoLinkCrm`. Resolve the person's company\n // here so the user lands with a company scope key: the portal Users page, portal\n // invitations, and the company detail \"Portal users\" group all filter on it.\n if (!resolvedCustomerEntityId) {\n resolvedCustomerEntityId = await resolveOwnedCompanyForPerson(em, parsed.data.personEntityId, {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n })\n }\n }\n\n const customerInvitationService = container.resolve('customerInvitationService') as CustomerInvitationService\n\n const { invitation, rawToken, rollbackState } = await customerInvitationService.createInvitation(\n parsed.data.email,\n { tenantId: auth.tenantId!, organizationId: auth.orgId! },\n {\n customerEntityId: resolvedCustomerEntityId,\n personEntityId: parsed.data.personEntityId || null,\n roleIds: parsed.data.roleIds,\n invitedByUserId: resolveInvitedByUserId(auth),\n displayName: parsed.data.displayName || null,\n },\n )\n\n try {\n await sendCustomerInvitationEmail({\n container,\n tenantId: auth.tenantId!,\n organizationId: auth.orgId!,\n email: invitation.email,\n rawToken,\n })\n } catch (error) {\n logger.error('Invitation email failed', { err: error })\n try {\n await customerInvitationService.rollbackInvitation(invitation, rollbackState)\n } catch (rollbackError) {\n logger.error('Invitation rollback failed', { err: rollbackError })\n }\n return NextResponse.json({ ok: false, error: 'Invitation email could not be sent' }, { status: 502 })\n }\n\n // Emit only after the email is sent, so a subscriber observing \"invited\" can\n // assume the recipient was actually notified (no event fires on the 502 path).\n void emitCustomerAccountsEvent('customer_accounts.user.invited', {\n invitationId: invitation.id,\n email: invitation.email,\n customerEntityId: invitation.customerEntityId || null,\n invitedByType: 'staff',\n tenantId: auth.tenantId!,\n organizationId: auth.orgId!,\n }).catch(() => undefined)\n\n return NextResponse.json({\n ok: true,\n invitation: {\n id: invitation.id,\n email: invitation.email,\n // Echo the stored CRM links so the caller can see which company the person\n // invite resolved to. The token stays unexposed.\n customerEntityId: invitation.customerEntityId || null,\n personEntityId: invitation.personEntityId || null,\n expiresAt: invitation.expiresAt,\n },\n }, { status: 201 })\n}\n\nconst successSchema = z.object({\n ok: z.literal(true),\n invitation: z.object({\n id: z.string().uuid(),\n email: z.string(),\n customerEntityId: z.string().uuid().nullable(),\n personEntityId: z.string().uuid().nullable(),\n expiresAt: z.string().datetime(),\n }),\n})\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Invite customer user (admin)',\n description: 'Creates a staff-initiated invitation for a new customer user. The invitedByUserId is set from the staff auth context.',\n tags: ['Customer Accounts Admin'],\n requestBody: { schema: inviteUserSchema },\n responses: [{ status: 201, description: 'Invitation created', schema: successSchema }],\n errors: [\n { status: 400, description: 'Validation failed', schema: errorSchema },\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 403, description: 'Insufficient permissions', schema: errorSchema },\n { status: 429, description: 'Too many invitation requests', schema: rateLimitErrorSchema },\n { status: 502, description: 'Invitation email could not be sent', schema: errorSchema },\n ],\n}\n\nconst listQuerySchema = z.object({\n page: z.coerce.number().int().min(1).optional(),\n pageSize: z.coerce.number().int().min(1).max(100).optional(),\n personEntityId: z.string().uuid().optional(),\n customerEntityId: z.string().uuid().optional(),\n email: z.string().optional(),\n})\n\nconst listSuccessSchema = z.object({\n ok: z.literal(true),\n items: z.array(z.object({\n id: z.string().uuid(),\n email: z.string(),\n displayName: z.string().nullable(),\n customerEntityId: z.string().uuid().nullable(),\n personEntityId: z.string().uuid().nullable(),\n roleIds: z.array(z.string().uuid()),\n invitedByUserId: z.string().uuid().nullable(),\n expiresAt: z.string().datetime(),\n createdAt: z.string().datetime(),\n })),\n total: z.number(),\n totalPages: z.number(),\n page: z.number(),\n})\n\nconst listMethodDoc: OpenApiMethodDoc = {\n summary: 'List pending customer invitations (admin)',\n description: 'Lists invitations that are still pending \u2014 not accepted, not cancelled, and not expired \u2014 for the caller\\'s tenant and organization. The invitation token is never returned.',\n tags: ['Customer Accounts Admin'],\n query: listQuerySchema,\n responses: [{ status: 200, description: 'Pending invitations', schema: listSuccessSchema }],\n errors: [\n { status: 400, description: 'Validation failed', schema: errorSchema },\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 403, description: 'Insufficient permissions', schema: errorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Invite customer user (admin)',\n methods: { GET: listMethodDoc, POST: methodDoc },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAGvC,SAAS,iCAAiC;AAC1C,SAAS,wBAAwB;AACjC,SAAS,sBAAsB,qBAAqB,oCAAoC;AACxF,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,0CAA0C;AACnD,SAAS,mCAAmC;AAC5C,SAAS,oBAAoB;AAC7B,SAAS,8BAA8B;AACvC,SAAS,kCAAkC;AAC3C,SAAS,4BAA4B;AAErC,MAAM,SAAS,aAAa,mBAAmB,EAAE,MAAM,EAAE,WAAW,qBAAqB,CAAC;AAE1F,MAAM,eAAe;AAEd,MAAM,WAAW,CAAC;AAEzB,SAAS,uBAAuB,MAAkF;AAChH,MAAI,KAAK,SAAU,QAAO,KAAK,UAAU;AACzC,SAAO,KAAK;AACd;AAEA,SAAS,iBAAiB,OAAsB,UAA0B;AACxE,QAAM,SAAS,OAAO,SAAS,SAAS,IAAI,EAAE;AAC9C,SAAO,OAAO,SAAS,MAAM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,SAAS;AAAA,IAC/B,WAAW,EAAE,OAAO,EAAE,SAAS;AAAA,EACjC,CAAC,CAAC;AAAA,EACF,OAAO,EAAE,OAAO;AAAA,EAChB,YAAY,EAAE,OAAO;AAAA,EACrB,MAAM,EAAE,OAAO;AACjB,CAAC;AAED,MAAM,gBAAkC;AAAA,EACtC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,yBAAyB;AAAA,EAChC,OAAO;AAAA,EACP,WAAW,CAAC,EAAE,QAAQ,KAAK,aAAa,uBAAuB,QAAQ,kBAAkB,CAAC;AAAA,EAC1F,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,YAAY;AAAA,IACrE,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,YAAY;AAAA,IACrE,EAAE,QAAQ,KAAK,aAAa,4BAA4B,QAAQ,YAAY;AAAA,EAC9E;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,SAAS,EAAE,KAAK,eAAe,MAAM,UAAU;AACjD;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/modules/customer_accounts/api/portal/users-invite.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { getCustomerAuthFromRequest, requireCustomerFeature } from '@open-mercato/core/modules/customer_accounts/lib/customerAuth'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { CustomerInvitationService } from '@open-mercato/core/modules/customer_accounts/services/customerInvitationService'\nimport { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'\nimport { CustomerRbacService } from '@open-mercato/core/modules/customer_accounts/services/customerRbacService'\nimport { CustomerRole } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { inviteUserSchema } from '@open-mercato/core/modules/customer_accounts/data/validators'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { rateLimitErrorSchema } from '@open-mercato/shared/lib/ratelimit/helpers'\nimport {\n checkAuthRateLimit,\n customerInviteRateLimitConfig,\n customerInviteIpRateLimitConfig,\n} from '@open-mercato/core/modules/customer_accounts/lib/rateLimiter'\nimport { readNormalizedEmailFromJsonRequest } from '@open-mercato/core/modules/customer_accounts/lib/rateLimitIdentifier'\nimport { sendCustomerInvitationEmail } from '@open-mercato/core/modules/customer_accounts/lib/invitationEmail'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('customer_accounts').child({ component: 'portal-users-invite' })\n\nexport const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }\n\nexport async function POST(req: Request) {\n const auth = await getCustomerAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const rateLimitEmail = await readNormalizedEmailFromJsonRequest(req)\n const { error: rateLimitError } = await checkAuthRateLimit({\n req,\n ipConfig: customerInviteIpRateLimitConfig,\n compoundConfig: customerInviteRateLimitConfig,\n compoundIdentifier: rateLimitEmail,\n })\n if (rateLimitError) return rateLimitError\n\n const container = await createRequestContainer()\n const customerRbacService = container.resolve('customerRbacService') as CustomerRbacService\n\n try {\n await requireCustomerFeature(auth, ['portal.users.manage'], customerRbacService)\n } catch (response) {\n return response as NextResponse\n }\n\n if (!auth.customerEntityId) {\n return NextResponse.json({ ok: false, error: 'No company association' }, { status: 403 })\n }\n\n let body: unknown\n try {\n body = await req.json()\n } catch {\n return NextResponse.json({ ok: false, error: 'Invalid request body' }, { status: 400 })\n }\n\n const parsed = inviteUserSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ ok: false, error: 'Validation failed', details: parsed.error.flatten().fieldErrors }, { status: 400 })\n }\n\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n // Validate all roles are customer_assignable\n const requestedRoleIds = parsed.data.roleIds\n const roles = requestedRoleIds.length > 0\n ? await findWithDecryption(\n em,\n CustomerRole,\n {\n id: { $in: requestedRoleIds },\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n deletedAt: null,\n } as any,\n undefined,\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n : []\n const rolesById = new Map(roles.map((role) => [role.id, role]))\n for (const roleId of requestedRoleIds) {\n const role = rolesById.get(roleId)\n if (!role) {\n return NextResponse.json({ ok: false, error: `Role ${roleId} not found` }, { status: 400 })\n }\n if (!role.customerAssignable) {\n return NextResponse.json({ ok: false, error: `Role \"${role.name}\" cannot be assigned by portal users` }, { status: 403 })\n }\n }\n\n const customerInvitationService = container.resolve('customerInvitationService') as CustomerInvitationService\n\n const { invitation, rawToken, rollbackState } = await customerInvitationService.createInvitation(\n parsed.data.email,\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n {\n customerEntityId: auth.customerEntityId,\n roleIds: parsed.data.roleIds,\n invitedByCustomerUserId: auth.sub,\n displayName: parsed.data.displayName || null,\n },\n )\n\n try {\n await sendCustomerInvitationEmail({\n container,\n organizationId: auth.orgId,\n email: invitation.email,\n rawToken,\n })\n } catch (error) {\n logger.error('Invitation email failed', { err: error })\n try {\n await customerInvitationService.rollbackInvitation(invitation, rollbackState)\n } catch (rollbackError) {\n logger.error('Invitation rollback failed', { err: rollbackError })\n }\n return NextResponse.json({ ok: false, error: 'Invitation email could not be sent' }, { status: 502 })\n }\n\n // Emit only after the email is sent, so a subscriber observing \"invited\" can\n // assume the recipient was actually notified (no event fires on the 502 path).\n void emitCustomerAccountsEvent('customer_accounts.user.invited', {\n invitationId: invitation.id,\n email: invitation.email,\n customerEntityId: invitation.customerEntityId || null,\n invitedByType: 'portal',\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n }).catch(() => undefined)\n\n return NextResponse.json({\n ok: true,\n invitation: {\n id: invitation.id,\n email: invitation.email,\n expiresAt: invitation.expiresAt,\n },\n }, { status: 201 })\n}\n\nconst successSchema = z.object({\n ok: z.literal(true),\n invitation: z.object({\n id: z.string().uuid(),\n email: z.string(),\n expiresAt: z.string().datetime(),\n }),\n})\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Invite a user to the company portal',\n description: 'Creates an invitation for a new user to join the company portal.',\n tags: ['Customer Portal'],\n requestBody: { schema: inviteUserSchema },\n responses: [{ status: 201, description: 'Invitation created', schema: successSchema }],\n errors: [\n { status: 400, description: 'Validation failed', schema: errorSchema },\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 403, description: 'Insufficient permissions or non-assignable role', schema: errorSchema },\n { status: 429, description: 'Too many invitation requests', schema: rateLimitErrorSchema },\n { status: 502, description: 'Invitation email could not be sent', schema: errorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Invite portal user',\n methods: { POST: methodDoc },\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,4BAA4B,8BAA8B;AACnE,SAAS,8BAA8B;AAEvC,SAAS,iCAAiC;AAE1C,SAAS,oBAAoB;AAC7B,SAAS,wBAAwB;AACjC,SAAS,0BAA0B;AACnC,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,0CAA0C;AACnD,SAAS,mCAAmC;AAC5C,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,mBAAmB,EAAE,MAAM,EAAE,WAAW,sBAAsB,CAAC;AAEpF,MAAM,WAAqD,EAAE,aAAa,MAAM;AAEvF,eAAsB,KAAK,KAAc;AACvC,QAAM,OAAO,MAAM,2BAA2B,GAAG;AACjD,MAAI,CAAC,MAAM;AACT,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,0BAA0B,GAAG,EAAE,QAAQ,IAAI,CA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Q,qBAAqB;AAAA,IACzF,EAAE,QAAQ,KAAK,aAAa,sCAAsC,QAAQ,YAAY;AAAA,EACxF;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,SAAS,EAAE,MAAM,UAAU;AAC7B;",
|
|
4
|
+
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { getCustomerAuthFromRequest, requireCustomerFeature } from '@open-mercato/core/modules/customer_accounts/lib/customerAuth'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { CustomerInvitationService } from '@open-mercato/core/modules/customer_accounts/services/customerInvitationService'\nimport { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'\nimport { CustomerRbacService } from '@open-mercato/core/modules/customer_accounts/services/customerRbacService'\nimport { CustomerRole } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { inviteUserSchema } from '@open-mercato/core/modules/customer_accounts/data/validators'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { rateLimitErrorSchema } from '@open-mercato/shared/lib/ratelimit/helpers'\nimport {\n checkAuthRateLimit,\n customerInviteRateLimitConfig,\n customerInviteIpRateLimitConfig,\n} from '@open-mercato/core/modules/customer_accounts/lib/rateLimiter'\nimport { readNormalizedEmailFromJsonRequest } from '@open-mercato/core/modules/customer_accounts/lib/rateLimitIdentifier'\nimport { sendCustomerInvitationEmail } from '@open-mercato/core/modules/customer_accounts/lib/invitationEmail'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('customer_accounts').child({ component: 'portal-users-invite' })\n\nexport const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }\n\nexport async function POST(req: Request) {\n const auth = await getCustomerAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const rateLimitEmail = await readNormalizedEmailFromJsonRequest(req)\n const { error: rateLimitError } = await checkAuthRateLimit({\n req,\n ipConfig: customerInviteIpRateLimitConfig,\n compoundConfig: customerInviteRateLimitConfig,\n compoundIdentifier: rateLimitEmail,\n })\n if (rateLimitError) return rateLimitError\n\n const container = await createRequestContainer()\n const customerRbacService = container.resolve('customerRbacService') as CustomerRbacService\n\n try {\n await requireCustomerFeature(auth, ['portal.users.manage'], customerRbacService)\n } catch (response) {\n return response as NextResponse\n }\n\n if (!auth.customerEntityId) {\n return NextResponse.json({ ok: false, error: 'No company association' }, { status: 403 })\n }\n\n let body: unknown\n try {\n body = await req.json()\n } catch {\n return NextResponse.json({ ok: false, error: 'Invalid request body' }, { status: 400 })\n }\n\n const parsed = inviteUserSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ ok: false, error: 'Validation failed', details: parsed.error.flatten().fieldErrors }, { status: 400 })\n }\n\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n // Validate all roles are customer_assignable\n const requestedRoleIds = parsed.data.roleIds\n const roles = requestedRoleIds.length > 0\n ? await findWithDecryption(\n em,\n CustomerRole,\n {\n id: { $in: requestedRoleIds },\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n deletedAt: null,\n } as any,\n undefined,\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n : []\n const rolesById = new Map(roles.map((role) => [role.id, role]))\n for (const roleId of requestedRoleIds) {\n const role = rolesById.get(roleId)\n if (!role) {\n return NextResponse.json({ ok: false, error: `Role ${roleId} not found` }, { status: 400 })\n }\n if (!role.customerAssignable) {\n return NextResponse.json({ ok: false, error: `Role \"${role.name}\" cannot be assigned by portal users` }, { status: 403 })\n }\n }\n\n const customerInvitationService = container.resolve('customerInvitationService') as CustomerInvitationService\n\n const { invitation, rawToken, rollbackState } = await customerInvitationService.createInvitation(\n parsed.data.email,\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n {\n customerEntityId: auth.customerEntityId,\n roleIds: parsed.data.roleIds,\n invitedByCustomerUserId: auth.sub,\n displayName: parsed.data.displayName || null,\n },\n )\n\n try {\n await sendCustomerInvitationEmail({\n container,\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n email: invitation.email,\n rawToken,\n })\n } catch (error) {\n logger.error('Invitation email failed', { err: error })\n try {\n await customerInvitationService.rollbackInvitation(invitation, rollbackState)\n } catch (rollbackError) {\n logger.error('Invitation rollback failed', { err: rollbackError })\n }\n return NextResponse.json({ ok: false, error: 'Invitation email could not be sent' }, { status: 502 })\n }\n\n // Emit only after the email is sent, so a subscriber observing \"invited\" can\n // assume the recipient was actually notified (no event fires on the 502 path).\n void emitCustomerAccountsEvent('customer_accounts.user.invited', {\n invitationId: invitation.id,\n email: invitation.email,\n customerEntityId: invitation.customerEntityId || null,\n invitedByType: 'portal',\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n }).catch(() => undefined)\n\n return NextResponse.json({\n ok: true,\n invitation: {\n id: invitation.id,\n email: invitation.email,\n expiresAt: invitation.expiresAt,\n },\n }, { status: 201 })\n}\n\nconst successSchema = z.object({\n ok: z.literal(true),\n invitation: z.object({\n id: z.string().uuid(),\n email: z.string(),\n expiresAt: z.string().datetime(),\n }),\n})\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Invite a user to the company portal',\n description: 'Creates an invitation for a new user to join the company portal.',\n tags: ['Customer Portal'],\n requestBody: { schema: inviteUserSchema },\n responses: [{ status: 201, description: 'Invitation created', schema: successSchema }],\n errors: [\n { status: 400, description: 'Validation failed', schema: errorSchema },\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 403, description: 'Insufficient permissions or non-assignable role', schema: errorSchema },\n { status: 429, description: 'Too many invitation requests', schema: rateLimitErrorSchema },\n { status: 502, description: 'Invitation email could not be sent', schema: errorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Invite portal user',\n methods: { POST: methodDoc },\n}\n"],
|
|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,EAAE,OAAO;AAAA,IAChB,WAAW,EAAE,OAAO,EAAE,SAAS;AAAA,EACjC,CAAC;AACH,CAAC;AACD,MAAM,cAAc,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,KAAK,GAAG,OAAO,EAAE,OAAO,EAAE,CAAC;AAExE,MAAM,YAA8B;AAAA,EAClC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,iBAAiB;AAAA,EACxB,aAAa,EAAE,QAAQ,iBAAiB;AAAA,EACxC,WAAW,CAAC,EAAE,QAAQ,KAAK,aAAa,sBAAsB,QAAQ,cAAc,CAAC;AAAA,EACrF,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,YAAY;AAAA,IACrE,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,YAAY;AAAA,IACrE,EAAE,QAAQ,KAAK,aAAa,mDAAmD,QAAQ,YAAY;AAAA,IACnG,EAAE,QAAQ,KAAK,aAAa,gCAAgC,QAAQ,qBAAqB;AAAA,IACzF,EAAE,QAAQ,KAAK,aAAa,sCAAsC,QAAQ,YAAY;AAAA,EACxF;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,SAAS,EAAE,MAAM,UAAU;AAC7B;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -114,10 +114,12 @@ async function POST(req) {
|
|
|
114
114
|
"If this was not you, you can ignore this message. No new portal account was created."
|
|
115
115
|
)
|
|
116
116
|
};
|
|
117
|
-
|
|
117
|
+
await sendEmail({
|
|
118
118
|
to: existing.email,
|
|
119
119
|
subject: subject2,
|
|
120
|
-
react: CustomerExistingAccountEmail({ loginUrl, copy: copy2 })
|
|
120
|
+
react: CustomerExistingAccountEmail({ loginUrl, copy: copy2 }),
|
|
121
|
+
tenantId,
|
|
122
|
+
organizationId
|
|
121
123
|
}).catch((error) => {
|
|
122
124
|
logger.error("Existing-account email failed", { err: error });
|
|
123
125
|
});
|
|
@@ -160,10 +162,12 @@ async function POST(req) {
|
|
|
160
162
|
"This verification link expires in 24 hours. If you did not request this, you can ignore this email."
|
|
161
163
|
)
|
|
162
164
|
};
|
|
163
|
-
|
|
165
|
+
await sendEmail({
|
|
164
166
|
to: user.email,
|
|
165
167
|
subject,
|
|
166
|
-
react: CustomerSignupVerificationEmail({ verifyUrl, copy })
|
|
168
|
+
react: CustomerSignupVerificationEmail({ verifyUrl, copy }),
|
|
169
|
+
tenantId,
|
|
170
|
+
organizationId
|
|
167
171
|
}).catch((error) => {
|
|
168
172
|
logger.error("Verification email failed", { err: error });
|
|
169
173
|
});
|