@open-mercato/core 0.7.1-develop.7131.1.20abf9e885 → 0.7.1-develop.7135.1.19bf969756
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.map +2 -2
- package/dist/modules/communication_channels/api/post/test-seed/route.js +40 -2
- package/dist/modules/communication_channels/api/post/test-seed/route.js.map +2 -2
- package/dist/modules/communication_channels/lib/access-control.js +6 -1
- package/dist/modules/communication_channels/lib/access-control.js.map +2 -2
- package/dist/modules/communication_channels/lib/system-user.js +8 -3
- package/dist/modules/communication_channels/lib/system-user.js.map +2 -2
- package/dist/modules/warranty_claims/api/ai/assess/route.js +20 -18
- package/dist/modules/warranty_claims/api/ai/assess/route.js.map +2 -2
- package/dist/modules/warranty_claims/api/credit-memo/route.js +11 -12
- package/dist/modules/warranty_claims/api/credit-memo/route.js.map +2 -2
- package/dist/modules/warranty_claims/api/events/route.js +1 -1
- package/dist/modules/warranty_claims/api/events/route.js.map +2 -2
- package/dist/modules/warranty_claims/api/portal/attachments/route.js +24 -27
- package/dist/modules/warranty_claims/api/portal/attachments/route.js.map +2 -2
- package/dist/modules/warranty_claims/api/portal/claims/[id]/route.js +8 -10
- package/dist/modules/warranty_claims/api/portal/claims/[id]/route.js.map +2 -2
- package/dist/modules/warranty_claims/api/portal/claims/[id]/shared.js +4 -9
- package/dist/modules/warranty_claims/api/portal/claims/[id]/shared.js.map +2 -2
- package/dist/modules/warranty_claims/api/portal/claims/[id]/submit/route.js +3 -3
- package/dist/modules/warranty_claims/api/portal/claims/[id]/submit/route.js.map +2 -2
- package/dist/modules/warranty_claims/api/portal/claims/[id]/withdraw/route.js +3 -3
- package/dist/modules/warranty_claims/api/portal/claims/[id]/withdraw/route.js.map +2 -2
- package/dist/modules/warranty_claims/api/portal/claims/route.js +4 -9
- package/dist/modules/warranty_claims/api/portal/claims/route.js.map +2 -2
- package/dist/modules/warranty_claims/api/portal/events/route.js +12 -13
- package/dist/modules/warranty_claims/api/portal/events/route.js.map +2 -2
- package/dist/modules/warranty_claims/api/receiving/route.js +14 -15
- package/dist/modules/warranty_claims/api/receiving/route.js.map +2 -2
- package/dist/modules/warranty_claims/api/registrations/route.js +9 -4
- package/dist/modules/warranty_claims/api/registrations/route.js.map +2 -2
- package/dist/modules/warranty_claims/api/replacement-order/route.js +11 -12
- package/dist/modules/warranty_claims/api/replacement-order/route.js.map +2 -2
- package/dist/modules/warranty_claims/api/return-label/route.js +20 -19
- package/dist/modules/warranty_claims/api/return-label/route.js.map +2 -2
- package/dist/modules/warranty_claims/api/risk/route.js +2 -1
- package/dist/modules/warranty_claims/api/risk/route.js.map +2 -2
- package/dist/modules/warranty_claims/api/sales-return/route.js +11 -12
- package/dist/modules/warranty_claims/api/sales-return/route.js.map +2 -2
- package/dist/modules/warranty_claims/api/troubleshooting-guides/route.js +22 -1
- package/dist/modules/warranty_claims/api/troubleshooting-guides/route.js.map +2 -2
- package/dist/modules/warranty_claims/api/vendor-recovery-suggestions/route.js +2 -1
- package/dist/modules/warranty_claims/api/vendor-recovery-suggestions/route.js.map +2 -2
- package/dist/modules/warranty_claims/commands/shared.js +2 -2
- package/dist/modules/warranty_claims/commands/shared.js.map +2 -2
- package/dist/modules/warranty_claims/lib/portalAuthGuard.js +31 -0
- package/dist/modules/warranty_claims/lib/portalAuthGuard.js.map +7 -0
- package/package.json +7 -7
- package/src/helpers/integration/communicationChannelsFixtures.ts +13 -0
- package/src/modules/communication_channels/api/post/test-seed/route.ts +47 -2
- package/src/modules/communication_channels/lib/access-control.ts +28 -0
- package/src/modules/communication_channels/lib/system-user.ts +40 -22
- package/src/modules/warranty_claims/api/ai/assess/route.ts +23 -17
- package/src/modules/warranty_claims/api/credit-memo/route.ts +14 -13
- package/src/modules/warranty_claims/api/events/route.ts +1 -1
- package/src/modules/warranty_claims/api/portal/attachments/route.ts +29 -27
- package/src/modules/warranty_claims/api/portal/claims/[id]/route.ts +9 -10
- package/src/modules/warranty_claims/api/portal/claims/[id]/shared.ts +5 -9
- package/src/modules/warranty_claims/api/portal/claims/[id]/submit/route.ts +3 -3
- package/src/modules/warranty_claims/api/portal/claims/[id]/withdraw/route.ts +3 -3
- package/src/modules/warranty_claims/api/portal/claims/route.ts +5 -9
- package/src/modules/warranty_claims/api/portal/events/route.ts +13 -13
- package/src/modules/warranty_claims/api/receiving/route.ts +17 -15
- package/src/modules/warranty_claims/api/registrations/route.ts +9 -3
- package/src/modules/warranty_claims/api/replacement-order/route.ts +14 -13
- package/src/modules/warranty_claims/api/return-label/route.ts +21 -17
- package/src/modules/warranty_claims/api/risk/route.ts +3 -1
- package/src/modules/warranty_claims/api/sales-return/route.ts +14 -13
- package/src/modules/warranty_claims/api/troubleshooting-guides/route.ts +23 -1
- package/src/modules/warranty_claims/api/vendor-recovery-suggestions/route.ts +3 -1
- package/src/modules/warranty_claims/commands/shared.ts +7 -1
- package/src/modules/warranty_claims/lib/portalAuthGuard.ts +30 -0
package/.turbo/turbo-build.log
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/helpers/integration/communicationChannelsFixtures.ts"],
|
|
4
|
-
"sourcesContent": ["import { expect, type APIRequestContext } from '@playwright/test';\nimport { apiRequest } from './api';\nimport { expectId, readJsonSafe } from './generalFixtures';\n\n/**\n * Communication-channels integration fixtures.\n *\n * These drive the TEST-ONLY seed endpoint `POST /api/communication_channels/test-seed`,\n * which is gated by `OM_ENABLE_TEST_CHANNEL_SEEDING` (inert/404 in production). Use\n * {@link isChannelSeedingAvailable} to skip tests when the gate is off rather than\n * failing them.\n */\n\nexport type SeedAddressField =\n | string\n | { address: string; name?: string }\n | Array<string | { address: string; name?: string }>;\n\nconst TEST_SEED_PATH = '/api/communication_channels/test-seed';\n\n/**\n * Probe whether the env-gated test-seed endpoint is enabled in the target app.\n * Returns false when the route answers 404 (flag off) so callers can `test.skip`.\n * The caller's token must hold `communication_channels.connect_user_channel`.\n */\nexport async function isChannelSeedingAvailable(\n request: APIRequestContext,\n token: string,\n): Promise<boolean> {\n // A malformed body returns 422 when the gate is ON and 404 when it is OFF.\n const response = await apiRequest(request, 'POST', TEST_SEED_PATH, {\n token,\n data: { action: '__probe__' },\n });\n return response.status() !== 404;\n}\n\n/**\n * Seed a connected, network-free `__test_seed__` channel owned by the caller.\n * Returns the new channel id. Tear down with {@link deleteChannelIfExists}.\n */\nexport async function seedConnectedChannel(\n request: APIRequestContext,\n token: string,\n input: {\n displayName?: string;\n externalIdentifier?: string;\n /**\n * `chat` connects the non-email stub instead: a channel whose senders carry\n * an opaque handle and no address, and whose `externalIdentifier` is NULL \u2014\n * the shape a real Discord/Slack channel has. Use it for anything asserting\n * the hub's sender-identity contract (#4975); the default `email` flavor\n * cannot prove it, because it can only ever supply email-shaped data.\n */\n providerFlavor?: 'email' | 'chat';\n } = {},\n): Promise<string> {\n const response = await apiRequest(request, 'POST', TEST_SEED_PATH, {\n token,\n data: { action: 'connect-channel', ...input },\n });\n expect(\n response.status(),\n 'POST /api/communication_channels/test-seed (connect-channel) should return 201',\n ).toBe(201);\n const body = await readJsonSafe<{ channelId?: string }>(response);\n return expectId(body?.channelId, 'connect-channel response should include channelId');\n}\n\n/**\n * Seed an inbound `MessageChannelLink` for `channelId` and emit\n * `communication_channels.message.received` through the real event bus. The\n * persistent customers link-channel-message-received subscriber is enqueued to\n * the `events` queue \u2014 drain it with `drainIntegrationQueue('events')`.\n *\n * Returns the created link + message ids (the message id is the platform\n * `messages.message` id, usable as `messageThreadId` to thread a follow-up).\n *\n * Pass `createThreadMapping: true` to also seed a `ChannelThreadMapping` for the\n * thread \u2014 required before exercising the reaction (`/messages/[id]/reactions`)\n * and thread-assign (`/threads/[id]/assign`) routes, which resolve the owning\n * channel through that mapping.\n */\nexport async function seedInboundMessage(\n request: APIRequestContext,\n token: string,\n input: {\n channelId: string;\n from?: SeedAddressField;\n to?: SeedAddressField;\n cc?: SeedAddressField;\n subject?: string;\n bodyText?: string;\n messageId?: string;\n inReplyTo?: string;\n references?: string[];\n messageThreadId?: string;\n providerKey?: string;\n createThreadMapping?: boolean;\n },\n): Promise<{ channelLinkId: string; messageId: string; conversationId: string }> {\n const response = await apiRequest(request, 'POST', TEST_SEED_PATH, {\n token,\n data: { action: 'emit-inbound', ...input },\n });\n expect(\n response.status(),\n 'POST /api/communication_channels/test-seed (emit-inbound) should return 201',\n ).toBe(201);\n const body = await readJsonSafe<{\n channelLinkId?: string;\n messageId?: string;\n conversationId?: string;\n }>(response);\n return {\n channelLinkId: expectId(body?.channelLinkId, 'emit-inbound response should include channelLinkId'),\n messageId: expectId(body?.messageId, 'emit-inbound response should include messageId'),\n conversationId: expectId(\n body?.conversationId,\n 'emit-inbound response should include conversationId',\n ),\n };\n}\n\n/**\n * Best-effort delete of a seeded channel via the owner-scoped DELETE route.\n * Safe to call with a null id in `finally`.\n */\n/**\n * Ingest an inbound chat message through the REAL `ingest_inbound_message`\n * command: the stub adapter normalizes the frame and the hub composes the\n * platform message via `messages.messages.compose`.\n *\n * Unlike {@link seedInboundMessage}, nothing here is short-circuited \u2014 no row is\n * inserted behind the compose path \u2014 so a hub contract the provider cannot\n * satisfy fails the test instead of hiding behind seeded data. That bypass is\n * exactly why CI was green while every real inbound Discord message was rejected\n * (#4975).\n *\n * The sender is identified only by `senderIdentifier` (a Discord snowflake, a\n * Slack member id, \u2026). There is deliberately no way to pass an address.\n */\nexport async function ingestInboundChatMessage(\n request: APIRequestContext,\n token: string,\n input: {\n channelId: string;\n senderIdentifier: string;\n senderDisplayName?: string;\n body?: string;\n externalMessageId: string;\n externalConversationId: string;\n },\n): Promise<{\n status: string;\n messageId: string | null;\n conversationId: string | null;\n channelLinkId: string | null;\n channelType: string | null;\n}> {\n const response = await apiRequest(request, 'POST', TEST_SEED_PATH, {\n token,\n data: { action: 'ingest-inbound', ...input },\n });\n expect(\n response.status(),\n 'POST /api/communication_channels/test-seed (ingest-inbound) should return 201 \u2014 ' +\n 'a non-201 here means the hub rejected a sender with no email address',\n ).toBe(201);\n const body = await readJsonSafe<{\n status?: string;\n messageId?: string | null;\n conversationId?: string | null;\n channelLinkId?: string | null;\n channelType?: string | null;\n }>(response);\n return {\n status: body?.status ?? 'unknown',\n messageId: body?.messageId ?? null,\n conversationId: body?.conversationId ?? null,\n channelLinkId: body?.channelLinkId ?? null,\n channelType: body?.channelType ?? null,\n };\n}\n\nexport async function deleteChannelIfExists(\n request: APIRequestContext,\n token: string | null,\n channelId: string | null,\n): Promise<void> {\n if (!token || !channelId) return;\n await apiRequest(\n request,\n 'DELETE',\n `/api/communication_channels/channels/${encodeURIComponent(channelId)}`,\n { token },\n ).catch(() => undefined);\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,cAAsC;AAC/C,SAAS,kBAAkB;AAC3B,SAAS,UAAU,oBAAoB;AAgBvC,MAAM,iBAAiB;AAOvB,eAAsB,0BACpB,SACA,OACkB;AAElB,QAAM,WAAW,MAAM,WAAW,SAAS,QAAQ,gBAAgB;AAAA,IACjE;AAAA,IACA,MAAM,EAAE,QAAQ,YAAY;AAAA,EAC9B,CAAC;AACD,SAAO,SAAS,OAAO,MAAM;AAC/B;AAMA,eAAsB,qBACpB,SACA,OACA,
|
|
4
|
+
"sourcesContent": ["import { expect, type APIRequestContext } from '@playwright/test';\nimport { apiRequest } from './api';\nimport { expectId, readJsonSafe } from './generalFixtures';\n\n/**\n * Communication-channels integration fixtures.\n *\n * These drive the TEST-ONLY seed endpoint `POST /api/communication_channels/test-seed`,\n * which is gated by `OM_ENABLE_TEST_CHANNEL_SEEDING` (inert/404 in production). Use\n * {@link isChannelSeedingAvailable} to skip tests when the gate is off rather than\n * failing them.\n */\n\nexport type SeedAddressField =\n | string\n | { address: string; name?: string }\n | Array<string | { address: string; name?: string }>;\n\nconst TEST_SEED_PATH = '/api/communication_channels/test-seed';\n\n/**\n * Probe whether the env-gated test-seed endpoint is enabled in the target app.\n * Returns false when the route answers 404 (flag off) so callers can `test.skip`.\n * The caller's token must hold `communication_channels.connect_user_channel`.\n */\nexport async function isChannelSeedingAvailable(\n request: APIRequestContext,\n token: string,\n): Promise<boolean> {\n // A malformed body returns 422 when the gate is ON and 404 when it is OFF.\n const response = await apiRequest(request, 'POST', TEST_SEED_PATH, {\n token,\n data: { action: '__probe__' },\n });\n return response.status() !== 404;\n}\n\n/**\n * Seed a connected, network-free `__test_seed__` channel owned by the caller.\n * Returns the new channel id. Tear down with {@link deleteChannelIfExists}.\n */\nexport async function seedConnectedChannel(\n request: APIRequestContext,\n token: string,\n input: {\n displayName?: string;\n externalIdentifier?: string;\n /**\n * `chat` connects the non-email stub instead: a channel whose senders carry\n * an opaque handle and no address, and whose `externalIdentifier` is NULL \u2014\n * the shape a real Discord/Slack channel has. Use it for anything asserting\n * the hub's sender-identity contract (#4975); the default `email` flavor\n * cannot prove it, because it can only ever supply email-shaped data.\n */\n providerFlavor?: 'email' | 'chat';\n /**\n * Relabel the connected stub channel's `provider_key`. Provider packages own\n * routes that filter on their own key, and a real channel for those providers\n * cannot be connected in CI (the Discord adapter validates its bot token\n * against the live API), so without this a provider-scoped listing can only\n * be asserted against an empty result \u2014 the assertion that stayed green\n * through #5602.\n *\n * The row is relabelled, nothing is registered: do not drive an outbound send\n * through a relabelled channel, because delivery would resolve the real\n * provider's adapter.\n */\n labelAsProviderKey?: string;\n } = {},\n): Promise<string> {\n const response = await apiRequest(request, 'POST', TEST_SEED_PATH, {\n token,\n data: { action: 'connect-channel', ...input },\n });\n expect(\n response.status(),\n 'POST /api/communication_channels/test-seed (connect-channel) should return 201',\n ).toBe(201);\n const body = await readJsonSafe<{ channelId?: string }>(response);\n return expectId(body?.channelId, 'connect-channel response should include channelId');\n}\n\n/**\n * Seed an inbound `MessageChannelLink` for `channelId` and emit\n * `communication_channels.message.received` through the real event bus. The\n * persistent customers link-channel-message-received subscriber is enqueued to\n * the `events` queue \u2014 drain it with `drainIntegrationQueue('events')`.\n *\n * Returns the created link + message ids (the message id is the platform\n * `messages.message` id, usable as `messageThreadId` to thread a follow-up).\n *\n * Pass `createThreadMapping: true` to also seed a `ChannelThreadMapping` for the\n * thread \u2014 required before exercising the reaction (`/messages/[id]/reactions`)\n * and thread-assign (`/threads/[id]/assign`) routes, which resolve the owning\n * channel through that mapping.\n */\nexport async function seedInboundMessage(\n request: APIRequestContext,\n token: string,\n input: {\n channelId: string;\n from?: SeedAddressField;\n to?: SeedAddressField;\n cc?: SeedAddressField;\n subject?: string;\n bodyText?: string;\n messageId?: string;\n inReplyTo?: string;\n references?: string[];\n messageThreadId?: string;\n providerKey?: string;\n createThreadMapping?: boolean;\n },\n): Promise<{ channelLinkId: string; messageId: string; conversationId: string }> {\n const response = await apiRequest(request, 'POST', TEST_SEED_PATH, {\n token,\n data: { action: 'emit-inbound', ...input },\n });\n expect(\n response.status(),\n 'POST /api/communication_channels/test-seed (emit-inbound) should return 201',\n ).toBe(201);\n const body = await readJsonSafe<{\n channelLinkId?: string;\n messageId?: string;\n conversationId?: string;\n }>(response);\n return {\n channelLinkId: expectId(body?.channelLinkId, 'emit-inbound response should include channelLinkId'),\n messageId: expectId(body?.messageId, 'emit-inbound response should include messageId'),\n conversationId: expectId(\n body?.conversationId,\n 'emit-inbound response should include conversationId',\n ),\n };\n}\n\n/**\n * Best-effort delete of a seeded channel via the owner-scoped DELETE route.\n * Safe to call with a null id in `finally`.\n */\n/**\n * Ingest an inbound chat message through the REAL `ingest_inbound_message`\n * command: the stub adapter normalizes the frame and the hub composes the\n * platform message via `messages.messages.compose`.\n *\n * Unlike {@link seedInboundMessage}, nothing here is short-circuited \u2014 no row is\n * inserted behind the compose path \u2014 so a hub contract the provider cannot\n * satisfy fails the test instead of hiding behind seeded data. That bypass is\n * exactly why CI was green while every real inbound Discord message was rejected\n * (#4975).\n *\n * The sender is identified only by `senderIdentifier` (a Discord snowflake, a\n * Slack member id, \u2026). There is deliberately no way to pass an address.\n */\nexport async function ingestInboundChatMessage(\n request: APIRequestContext,\n token: string,\n input: {\n channelId: string;\n senderIdentifier: string;\n senderDisplayName?: string;\n body?: string;\n externalMessageId: string;\n externalConversationId: string;\n },\n): Promise<{\n status: string;\n messageId: string | null;\n conversationId: string | null;\n channelLinkId: string | null;\n channelType: string | null;\n}> {\n const response = await apiRequest(request, 'POST', TEST_SEED_PATH, {\n token,\n data: { action: 'ingest-inbound', ...input },\n });\n expect(\n response.status(),\n 'POST /api/communication_channels/test-seed (ingest-inbound) should return 201 \u2014 ' +\n 'a non-201 here means the hub rejected a sender with no email address',\n ).toBe(201);\n const body = await readJsonSafe<{\n status?: string;\n messageId?: string | null;\n conversationId?: string | null;\n channelLinkId?: string | null;\n channelType?: string | null;\n }>(response);\n return {\n status: body?.status ?? 'unknown',\n messageId: body?.messageId ?? null,\n conversationId: body?.conversationId ?? null,\n channelLinkId: body?.channelLinkId ?? null,\n channelType: body?.channelType ?? null,\n };\n}\n\nexport async function deleteChannelIfExists(\n request: APIRequestContext,\n token: string | null,\n channelId: string | null,\n): Promise<void> {\n if (!token || !channelId) return;\n await apiRequest(\n request,\n 'DELETE',\n `/api/communication_channels/channels/${encodeURIComponent(channelId)}`,\n { token },\n ).catch(() => undefined);\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,cAAsC;AAC/C,SAAS,kBAAkB;AAC3B,SAAS,UAAU,oBAAoB;AAgBvC,MAAM,iBAAiB;AAOvB,eAAsB,0BACpB,SACA,OACkB;AAElB,QAAM,WAAW,MAAM,WAAW,SAAS,QAAQ,gBAAgB;AAAA,IACjE;AAAA,IACA,MAAM,EAAE,QAAQ,YAAY;AAAA,EAC9B,CAAC;AACD,SAAO,SAAS,OAAO,MAAM;AAC/B;AAMA,eAAsB,qBACpB,SACA,OACA,QAwBI,CAAC,GACY;AACjB,QAAM,WAAW,MAAM,WAAW,SAAS,QAAQ,gBAAgB;AAAA,IACjE;AAAA,IACA,MAAM,EAAE,QAAQ,mBAAmB,GAAG,MAAM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AAAA,IACrE,EAAE,MAAM;AAAA,EACV,EAAE,MAAM,MAAM,MAAS;AACzB;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -47,7 +47,23 @@ const connectChannelSchema = z.object({
|
|
|
47
47
|
* address, so a test can exercise the hub's non-email identity contract
|
|
48
48
|
* without inventing one (#4975).
|
|
49
49
|
*/
|
|
50
|
-
providerFlavor: z.enum(["email", "chat"]).optional()
|
|
50
|
+
providerFlavor: z.enum(["email", "chat"]).optional(),
|
|
51
|
+
/**
|
|
52
|
+
* TEST-ONLY: rewrite the connected stub channel's `provider_key` to this value.
|
|
53
|
+
*
|
|
54
|
+
* Routes that a provider package owns filter on their own `provider_key`, and
|
|
55
|
+
* a real channel for those providers cannot be connected in CI — the Discord
|
|
56
|
+
* adapter's `validateCredentials` performs a live API call against a bot token
|
|
57
|
+
* no test environment has. Without this, a provider-scoped listing has nothing
|
|
58
|
+
* to list and can only be asserted against an empty result, which is exactly
|
|
59
|
+
* the assertion that would have stayed green through #5602.
|
|
60
|
+
*
|
|
61
|
+
* It relabels a row; it registers nothing. The stub adapter is still the only
|
|
62
|
+
* adapter present, so the channel remains network-free — but no test should
|
|
63
|
+
* drive an outbound send through a relabelled channel, because delivery would
|
|
64
|
+
* then resolve the real provider's adapter.
|
|
65
|
+
*/
|
|
66
|
+
labelAsProviderKey: z.string().min(1).max(64).regex(/^[a-z0-9_-]+$/).optional()
|
|
51
67
|
});
|
|
52
68
|
const ingestInboundSchema = z.object({
|
|
53
69
|
action: z.literal("ingest-inbound"),
|
|
@@ -149,8 +165,30 @@ async function POST(req) {
|
|
|
149
165
|
{ status: 500 }
|
|
150
166
|
);
|
|
151
167
|
}
|
|
168
|
+
if (body.labelAsProviderKey && body.labelAsProviderKey !== input.providerKey) {
|
|
169
|
+
const seedEm = container.resolve("em").fork();
|
|
170
|
+
const connected = await findOneWithDecryption(
|
|
171
|
+
seedEm,
|
|
172
|
+
CommunicationChannel,
|
|
173
|
+
{ id: result.channelId, tenantId },
|
|
174
|
+
void 0,
|
|
175
|
+
{ tenantId, organizationId }
|
|
176
|
+
);
|
|
177
|
+
if (!connected) {
|
|
178
|
+
return NextResponse.json(
|
|
179
|
+
{ error: "[internal] test-seed could not reload the channel it just connected" },
|
|
180
|
+
{ status: 500 }
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
connected.providerKey = body.labelAsProviderKey;
|
|
184
|
+
await seedEm.flush();
|
|
185
|
+
}
|
|
152
186
|
return NextResponse.json(
|
|
153
|
-
{
|
|
187
|
+
{
|
|
188
|
+
channelId: result.channelId,
|
|
189
|
+
externalIdentifier: result.externalIdentifier,
|
|
190
|
+
providerKey: body.labelAsProviderKey ?? input.providerKey
|
|
191
|
+
},
|
|
154
192
|
{ status: 201 }
|
|
155
193
|
);
|
|
156
194
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/modules/communication_channels/api/post/test-seed/route.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { CommandBus } from '@open-mercato/shared/lib/commands'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n ChannelThreadMapping,\n CommunicationChannel,\n ExternalConversation,\n MessageChannelLink,\n} from '../../../data/entities'\nimport { ChannelAccessDeniedError, assertCanManageChannel } from '../../../lib/access-control'\nimport {\n COMMUNICATION_CHANNELS_CONNECT_CREDENTIAL_CHANNEL_COMMAND_ID,\n type ConnectCredentialChannelInput,\n type ConnectCredentialChannelResult,\n} from '../../../commands/connect-credential-channel'\nimport { emitCommunicationChannelsEvent } from '../../../events'\nimport {\n TEST_SEED_CHAT_PROVIDER_KEY,\n TEST_SEED_PROVIDER_KEY,\n ensureTestSeedAdapterRegistered,\n isTestChannelSeedingEnabled,\n} from '../../../lib/test-seed'\nimport {\n COMMUNICATION_CHANNELS_INGEST_INBOUND_COMMAND_ID,\n type IngestInboundMessageInput,\n type IngestInboundMessageResult,\n} from '../../../commands/ingest-inbound-message'\n\n/**\n * TEST-ONLY channel seeding endpoint.\n *\n * Gated by `OM_ENABLE_TEST_CHANNEL_SEEDING` \u2014 when the flag is unset (the\n * production default) every request returns 404, so this route is invisible and\n * inert in production. See `lib/test-seed.ts` for the full rationale.\n *\n * Three actions, all scoped to the caller's tenant/org:\n * - `connect-channel`: connect a network-free stub channel owned by the caller\n * (delegates to the real connect-credential command so the channel persists\n * credentials + lands in `status='connected'`). Enables the outbound\n * compose \u2192 deliver \u2192 `.sent` chain to complete in CI. `providerFlavor: 'chat'`\n * connects the non-email stub instead, for tests about sender identity.\n * - `ingest-inbound`: run the REAL `ingest_inbound_message` command over an\n * adapter-normalized chat frame, so the platform compose path \u2014 and every\n * validation rule on it \u2014 actually executes. Use this for anything that\n * claims inbound works.\n * - `emit-inbound`: insert an inbound `MessageChannelLink` (+ a `messages.message`\n * row for threading) and emit `communication_channels.message.received` so the\n * customers link-channel-message subscriber runs against real Postgres. Enables\n * the inbound auto-link tests (TC-CRM-EMAIL-002..005). NOTE: this action\n * deliberately bypasses `messages.messages.compose` \u2014 it can never prove that\n * the hub accepts a message, only that downstream subscribers fire.\n */\ntype RbacServiceLike = {\n loadAcl: (\n userId: string,\n scope: { tenantId: string | null; organizationId: string | null },\n ) => Promise<{ isSuperAdmin: boolean; features: string[]; organizations: string[] | null }>\n}\n\nexport const metadata = {\n path: '/communication_channels/test-seed',\n POST: {\n requireAuth: true,\n requireFeatures: ['communication_channels.connect_user_channel'],\n },\n}\n\nconst addressObjectSchema = z.object({ address: z.string(), name: z.string().optional() })\nconst addressFieldSchema = z.union([\n z.string(),\n addressObjectSchema,\n z.array(z.union([z.string(), addressObjectSchema])),\n])\n\nconst connectChannelSchema = z.object({\n action: z.literal('connect-channel'),\n displayName: z.string().min(1).max(255).optional(),\n externalIdentifier: z.string().min(1).max(255).optional(),\n /**\n * Which stub provider to connect. `email` (default) keeps the historical\n * email-shaped channel; `chat` connects a channel whose senders have no\n * address, so a test can exercise the hub's non-email identity contract\n * without inventing one (#4975).\n */\n providerFlavor: z.enum(['email', 'chat']).optional(),\n})\n\n/**\n * Drive the REAL `ingest_inbound_message` command with a chat-shaped frame.\n *\n * `emit-inbound` below deliberately bypasses the platform compose path (it\n * inserts the `messages` row with raw SQL) because it only ever needed a\n * landing zone for the CRM-link subscribers. That bypass is why an inbound test\n * could pass while `composeMessageSchema` rejected every real message (#4975).\n * This action takes the opposite approach: it hands the frame to the adapter and\n * the ingest command and asserts nothing on the way, so whatever the hub's\n * contract really is, the test feels it.\n */\nconst ingestInboundSchema = z.object({\n action: z.literal('ingest-inbound'),\n channelId: z.string().uuid(),\n /** Opaque sender handle \u2014 a Discord snowflake, a Slack member id, etc. */\n senderIdentifier: z.string().min(1).max(255),\n senderDisplayName: z.string().max(255).optional(),\n body: z.string().max(50_000).optional(),\n externalMessageId: z.string().min(1).max(255),\n externalConversationId: z.string().min(1).max(255),\n})\n\nconst emitInboundSchema = z.object({\n action: z.literal('emit-inbound'),\n /** Channel that owns the inbound message; controls authorUserId + default visibility. */\n channelId: z.string().uuid(),\n /** Provider key persisted on the link (defaults to the stub provider). */\n providerKey: z.string().min(1).max(64).optional(),\n /** Normalized inbound addresses (stored under channelPayload). */\n from: addressFieldSchema.optional(),\n to: addressFieldSchema.optional(),\n cc: addressFieldSchema.optional(),\n subject: z.string().max(500).optional(),\n bodyText: z.string().max(200_000).optional(),\n /** RFC2822 Message-ID of this inbound message (for In-Reply-To matching). */\n messageId: z.string().max(500).optional(),\n /** RFC2822 In-Reply-To header (threading-inheritance fallback). */\n inReplyTo: z.string().max(500).optional(),\n references: z.array(z.string().max(500)).max(50).optional(),\n /**\n * Open Mercato `messages.message` thread id this inbound message belongs to.\n * When set, a `messages.message` row is created with this `threadId` so the\n * hub-thread inheritance join can resolve a Person from a sibling message.\n */\n messageThreadId: z.string().uuid().optional(),\n /**\n * Test-only: also create a `ChannelThreadMapping` for the seeded thread. The\n * reaction (`/messages/[id]/reactions`) and thread-assign\n * (`/threads/[id]/assign`) routes resolve the owning channel through this\n * mapping and return 409/404 without it. Opt-in so the existing CRM-link\n * seeds (which don't need a mapping) keep their current mapping-free shape.\n */\n createThreadMapping: z.boolean().optional(),\n})\n\nconst bodySchema = z.discriminatedUnion('action', [\n connectChannelSchema,\n ingestInboundSchema,\n emitInboundSchema,\n])\n\nexport async function POST(req: Request): Promise<Response> {\n // Fail-closed: invisible in production. Mirrors an unknown route (404) rather\n // than 403 so the surface leaks nothing when the flag is off.\n if (!isTestChannelSeedingEnabled()) {\n return NextResponse.json({ error: 'Not found' }, { status: 404 })\n }\n\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub || !auth?.tenantId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n let body: z.infer<typeof bodySchema>\n try {\n body = bodySchema.parse(await readJsonSafe(req, null))\n } catch (err) {\n return NextResponse.json(\n { error: err instanceof Error ? err.message : 'Invalid request body' },\n { status: 422 },\n )\n }\n\n const container = await createRequestContainer()\n // Defensive: make sure the stub adapter is registered for this process even if\n // a worker-only node skipped module di registration.\n ensureTestSeedAdapterRegistered()\n\n const tenantId = auth.tenantId as string\n const organizationId = (auth as { orgId?: string | null }).orgId ?? null\n const userId = auth.sub as string\n\n if (body.action === 'connect-channel') {\n const stamp = Date.now()\n const commandBus = container.resolve('commandBus') as CommandBus\n const isChatFlavor = body.providerFlavor === 'chat'\n // A chat channel is deliberately connected WITHOUT an email-ish credential\n // key, so `connect-credential-channel` derives no `externalIdentifier` and\n // the row is shaped exactly like a real Discord channel (identifier NULL \u2014\n // the condition #4977 describes). Inventing one here would recreate the\n // fixture dishonesty that hid #4975.\n const credentials = isChatFlavor\n ? { handle: body.externalIdentifier ?? `test-seed-chat-${stamp}` }\n : {\n username: body.externalIdentifier ?? `test-seed-${stamp}@test-seed.local`,\n fromAddress: body.externalIdentifier ?? `test-seed-${stamp}@test-seed.local`,\n }\n const input: ConnectCredentialChannelInput = {\n providerKey: isChatFlavor ? TEST_SEED_CHAT_PROVIDER_KEY : TEST_SEED_PROVIDER_KEY,\n displayName:\n body.displayName ?? `Test Seed ${isChatFlavor ? 'Chat ' : ''}Channel ${stamp}`,\n credentials,\n userId,\n scope: { tenantId, organizationId },\n }\n const { result } = await commandBus.execute<\n ConnectCredentialChannelInput,\n ConnectCredentialChannelResult\n >(COMMUNICATION_CHANNELS_CONNECT_CREDENTIAL_CHANNEL_COMMAND_ID, {\n input,\n ctx: {\n container,\n auth: auth as never,\n organizationScope: null,\n selectedOrganizationId: organizationId,\n organizationIds: organizationId ? [organizationId] : null,\n },\n })\n if (result.status !== 'connected') {\n return NextResponse.json(\n { error: '[internal] test-seed connect failed', detail: result },\n { status: 500 },\n )\n }\n return NextResponse.json(\n { channelId: result.channelId, externalIdentifier: result.externalIdentifier },\n { status: 201 },\n )\n }\n\n // action === 'ingest-inbound' | 'emit-inbound' \u2014 both address an existing channel.\n const em = (container.resolve('em') as EntityManager).fork()\n // Only the `emit-inbound` branch stamps a caller-chosen provider key onto the\n // rows it seeds; `ingest-inbound` takes the channel's own (see below).\n const providerKey =\n body.action === 'emit-inbound' ? body.providerKey ?? TEST_SEED_PROVIDER_KEY : TEST_SEED_PROVIDER_KEY\n\n // `channelId` is caller-supplied, so confirm it names a channel this tenant/org\n // actually owns before seeding rows that reference it. Mirrors the ownership\n // lookup every other per-channel route performs (see channels/[id]/test-send).\n const ownedChannel = await findOneWithDecryption(\n em,\n CommunicationChannel,\n {\n id: body.channelId,\n tenantId,\n organizationId,\n deletedAt: null,\n },\n undefined,\n { tenantId, organizationId },\n )\n if (!ownedChannel) {\n return NextResponse.json({ error: 'Channel not found' }, { status: 404 })\n }\n\n // Tenant/org scope alone does not authorize: `connect_user_channel` is granted\n // broadly, so a same-tenant caller could otherwise seed against a colleague's\n // personal mailbox. Enforce the module's owner-only contract \u2014 personal\n // channels are owner-restricted, shared channels need `manage`.\n let userFeatures: string[] = []\n try {\n const rbac = container.resolve('rbacService') as RbacServiceLike\n const acl = await rbac.loadAcl(userId, { tenantId, organizationId })\n userFeatures = acl?.isSuperAdmin ? ['*'] : Array.isArray(acl?.features) ? acl.features : []\n } catch {\n userFeatures = []\n }\n try {\n assertCanManageChannel(\n { userId: ownedChannel.userId },\n userId,\n userFeatures,\n 'communication_channels.manage',\n )\n } catch (err) {\n if (err instanceof ChannelAccessDeniedError) {\n return NextResponse.json({ error: 'Channel not found' }, { status: 404 })\n }\n const status = (err as { statusCode?: number }).statusCode ?? 403\n return NextResponse.json(\n { error: err instanceof Error ? err.message : 'Access denied' },\n { status },\n )\n }\n\n if (body.action === 'ingest-inbound') {\n // Everything below this point is the real path: the adapter normalizes the\n // frame and `ingest_inbound_message` composes the platform message through\n // `messages.messages.compose`. Nothing is short-circuited, so a hub contract\n // the provider cannot satisfy surfaces here as a failure instead of hiding\n // behind seeded rows (#4975).\n // The channel's own provider key, never a hardcoded one: ingest does not\n // check that `providerKey` matches the channel it names, so passing a\n // different one would silently stamp the wrong provider onto the link.\n const channelProviderKey = ownedChannel.providerKey\n if (channelProviderKey !== TEST_SEED_CHAT_PROVIDER_KEY) {\n return NextResponse.json(\n {\n error:\n 'ingest-inbound requires a channel connected with providerFlavor: \"chat\"; ' +\n `channel ${body.channelId} is '${channelProviderKey}'`,\n },\n { status: 422 },\n )\n }\n\n const commandBus = container.resolve('commandBus') as CommandBus\n const adapterRegistry = container.resolve('channelAdapterRegistry') as {\n get: (key: string) => { normalizeInbound: (raw: unknown) => Promise<unknown> } | undefined\n }\n const adapter = adapterRegistry.get(channelProviderKey)\n if (!adapter) {\n return NextResponse.json(\n { error: '[internal] test-seed chat adapter is not registered' },\n { status: 500 },\n )\n }\n\n const normalized = await adapter.normalizeInbound({\n raw: {\n externalMessageId: body.externalMessageId,\n externalConversationId: body.externalConversationId,\n senderIdentifier: body.senderIdentifier,\n senderDisplayName: body.senderDisplayName,\n body: body.body ?? '',\n },\n eventType: 'message',\n metadata: {},\n })\n\n const ingestInput = {\n channelId: body.channelId,\n providerKey: channelProviderKey,\n channelType: ownedChannel.channelType,\n scope: { tenantId, organizationId },\n message: normalized,\n } as IngestInboundMessageInput\n\n const { result } = await commandBus.execute<\n IngestInboundMessageInput,\n IngestInboundMessageResult\n >(COMMUNICATION_CHANNELS_INGEST_INBOUND_COMMAND_ID, {\n input: ingestInput,\n ctx: {\n container,\n auth: auth as never,\n organizationScope: null,\n selectedOrganizationId: organizationId,\n organizationIds: organizationId ? [organizationId] : null,\n },\n })\n\n return NextResponse.json(\n {\n status: result.status,\n messageId: result.messageId ?? null,\n conversationId: result.externalConversationId ?? null,\n channelLinkId: result.channelLinkId ?? null,\n channelType: ownedChannel.channelType,\n },\n { status: 201 },\n )\n }\n\n // A MessageChannelLink requires a non-null external_conversation_id (FK) and\n // message_id. Create a synthetic conversation + (optionally threaded) message\n // so the link is shaped like a real inbound row the subscriber can consume.\n const conversation = em.create(ExternalConversation, {\n channelId: body.channelId,\n externalConversationId: `inbound-seed:${Date.now()}:${Math.random().toString(16).slice(2, 8)}`,\n subject: body.subject ?? null,\n tenantId,\n organizationId,\n lastMessageAt: new Date(),\n })\n em.persist(conversation)\n await em.flush()\n\n // Insert the platform `messages.message` row via raw SQL rather than importing\n // the messages module's entity class (cross-module ORM coupling rule). Only\n // `thread_id` matters for the hub-thread inheritance join (TC-CRM-EMAIL-005);\n // the rest satisfy NOT NULL constraints.\n const messageRows = (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.${providerKey}`,\n body.messageThreadId ?? null,\n userId,\n body.subject ?? '(no subject)',\n body.bodyText ?? '',\n body.channelId,\n tenantId,\n organizationId,\n ],\n )) as Array<{ id: string }>\n const messageId = messageRows[0]?.id\n if (!messageId) {\n return NextResponse.json({ error: '[internal] failed to seed message row' }, { status: 500 })\n }\n\n const link = em.create(MessageChannelLink, {\n messageId,\n externalConversationId: conversation.id,\n providerKey,\n channelType: 'email',\n direction: 'inbound',\n deliveryStatus: 'delivered',\n channelPayload: {\n ...(body.from !== undefined ? { from: body.from } : {}),\n ...(body.to !== undefined ? { to: body.to } : {}),\n ...(body.cc !== undefined ? { cc: body.cc } : {}),\n ...(body.subject !== undefined ? { subject: body.subject } : {}),\n ...(body.bodyText !== undefined ? { text: body.bodyText } : {}),\n ...(body.inReplyTo !== undefined ? { inReplyTo: body.inReplyTo } : {}),\n ...(body.references !== undefined ? { references: body.references } : {}),\n },\n channelContentType: 'text/plain',\n channelMetadata: {\n ...(body.messageId !== undefined ? { messageId: body.messageId } : {}),\n },\n tenantId,\n organizationId,\n })\n em.persist(link)\n await em.flush()\n\n // Optionally mirror `ingest-inbound-message`: a real inbound message always\n // lands a ChannelThreadMapping that the reaction + thread-assign routes use to\n // resolve the owning channel. Seeded inbound messages skip it by default; opt\n // in for tests that exercise those routes. Keyed by `messageThreadId ?? messageId`\n // to match how those commands resolve the mapping (`message.threadId ?? message.id`).\n if (body.createThreadMapping) {\n const mapping = em.create(ChannelThreadMapping, {\n externalConversationId: conversation.id,\n messageThreadId: body.messageThreadId ?? messageId,\n channelId: body.channelId,\n providerKey,\n externalThreadRef: conversation.externalConversationId,\n tenantId,\n organizationId,\n })\n em.persist(mapping)\n await em.flush()\n }\n\n // Emit the hub event through the real event bus so the persistent customers\n // link-channel-message-received subscriber is enqueued to the `events` queue.\n await emitCommunicationChannelsEvent(\n 'communication_channels.message.received',\n {\n channelLinkId: link.id,\n channelId: body.channelId,\n providerKey,\n direction: 'inbound',\n tenantId,\n organizationId,\n },\n { persistent: true },\n )\n\n return NextResponse.json(\n { channelLinkId: link.id, messageId, conversationId: conversation.id },\n { status: 201 },\n )\n}\n\nexport const openApi = {\n tags: ['CommunicationChannels'],\n methods: {\n POST: {\n summary:\n 'Test-only: seed a connected channel, ingest a real inbound message, or emit a seeded inbound link (env-gated)',\n tags: ['CommunicationChannels'],\n responses: [\n { status: 201, description: 'Channel seeded / inbound message emitted' },\n { status: 401, description: 'Unauthorized' },\n {\n status: 404,\n description:\n 'Test channel seeding disabled (production default), or the requested channel does not belong to the caller',\n },\n { status: 422, description: 'Invalid request body' },\n { status: 500, description: 'Seed failed' },\n ],\n },\n },\n}\n\nexport default POST\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAEvC,SAAS,oBAAoB;AAC7B,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,0BAA0B,8BAA8B;AACjE;AAAA,EACE;AAAA,OAGK;AACP,SAAS,sCAAsC;AAC/C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,OAGK;
|
|
4
|
+
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { CommandBus } from '@open-mercato/shared/lib/commands'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n ChannelThreadMapping,\n CommunicationChannel,\n ExternalConversation,\n MessageChannelLink,\n} from '../../../data/entities'\nimport { ChannelAccessDeniedError, assertCanManageChannel } from '../../../lib/access-control'\nimport {\n COMMUNICATION_CHANNELS_CONNECT_CREDENTIAL_CHANNEL_COMMAND_ID,\n type ConnectCredentialChannelInput,\n type ConnectCredentialChannelResult,\n} from '../../../commands/connect-credential-channel'\nimport { emitCommunicationChannelsEvent } from '../../../events'\nimport {\n TEST_SEED_CHAT_PROVIDER_KEY,\n TEST_SEED_PROVIDER_KEY,\n ensureTestSeedAdapterRegistered,\n isTestChannelSeedingEnabled,\n} from '../../../lib/test-seed'\nimport {\n COMMUNICATION_CHANNELS_INGEST_INBOUND_COMMAND_ID,\n type IngestInboundMessageInput,\n type IngestInboundMessageResult,\n} from '../../../commands/ingest-inbound-message'\n\n/**\n * TEST-ONLY channel seeding endpoint.\n *\n * Gated by `OM_ENABLE_TEST_CHANNEL_SEEDING` \u2014 when the flag is unset (the\n * production default) every request returns 404, so this route is invisible and\n * inert in production. See `lib/test-seed.ts` for the full rationale.\n *\n * Three actions, all scoped to the caller's tenant/org:\n * - `connect-channel`: connect a network-free stub channel owned by the caller\n * (delegates to the real connect-credential command so the channel persists\n * credentials + lands in `status='connected'`). Enables the outbound\n * compose \u2192 deliver \u2192 `.sent` chain to complete in CI. `providerFlavor: 'chat'`\n * connects the non-email stub instead, for tests about sender identity, and\n * `labelAsProviderKey` relabels the connected row so a provider-scoped\n * listing has something to list without a live credential probe.\n * - `ingest-inbound`: run the REAL `ingest_inbound_message` command over an\n * adapter-normalized chat frame, so the platform compose path \u2014 and every\n * validation rule on it \u2014 actually executes. Use this for anything that\n * claims inbound works.\n * - `emit-inbound`: insert an inbound `MessageChannelLink` (+ a `messages.message`\n * row for threading) and emit `communication_channels.message.received` so the\n * customers link-channel-message subscriber runs against real Postgres. Enables\n * the inbound auto-link tests (TC-CRM-EMAIL-002..005). NOTE: this action\n * deliberately bypasses `messages.messages.compose` \u2014 it can never prove that\n * the hub accepts a message, only that downstream subscribers fire.\n */\ntype RbacServiceLike = {\n loadAcl: (\n userId: string,\n scope: { tenantId: string | null; organizationId: string | null },\n ) => Promise<{ isSuperAdmin: boolean; features: string[]; organizations: string[] | null }>\n}\n\nexport const metadata = {\n path: '/communication_channels/test-seed',\n POST: {\n requireAuth: true,\n requireFeatures: ['communication_channels.connect_user_channel'],\n },\n}\n\nconst addressObjectSchema = z.object({ address: z.string(), name: z.string().optional() })\nconst addressFieldSchema = z.union([\n z.string(),\n addressObjectSchema,\n z.array(z.union([z.string(), addressObjectSchema])),\n])\n\nconst connectChannelSchema = z.object({\n action: z.literal('connect-channel'),\n displayName: z.string().min(1).max(255).optional(),\n externalIdentifier: z.string().min(1).max(255).optional(),\n /**\n * Which stub provider to connect. `email` (default) keeps the historical\n * email-shaped channel; `chat` connects a channel whose senders have no\n * address, so a test can exercise the hub's non-email identity contract\n * without inventing one (#4975).\n */\n providerFlavor: z.enum(['email', 'chat']).optional(),\n /**\n * TEST-ONLY: rewrite the connected stub channel's `provider_key` to this value.\n *\n * Routes that a provider package owns filter on their own `provider_key`, and\n * a real channel for those providers cannot be connected in CI \u2014 the Discord\n * adapter's `validateCredentials` performs a live API call against a bot token\n * no test environment has. Without this, a provider-scoped listing has nothing\n * to list and can only be asserted against an empty result, which is exactly\n * the assertion that would have stayed green through #5602.\n *\n * It relabels a row; it registers nothing. The stub adapter is still the only\n * adapter present, so the channel remains network-free \u2014 but no test should\n * drive an outbound send through a relabelled channel, because delivery would\n * then resolve the real provider's adapter.\n */\n labelAsProviderKey: z\n .string()\n .min(1)\n .max(64)\n .regex(/^[a-z0-9_-]+$/)\n .optional(),\n})\n\n/**\n * Drive the REAL `ingest_inbound_message` command with a chat-shaped frame.\n *\n * `emit-inbound` below deliberately bypasses the platform compose path (it\n * inserts the `messages` row with raw SQL) because it only ever needed a\n * landing zone for the CRM-link subscribers. That bypass is why an inbound test\n * could pass while `composeMessageSchema` rejected every real message (#4975).\n * This action takes the opposite approach: it hands the frame to the adapter and\n * the ingest command and asserts nothing on the way, so whatever the hub's\n * contract really is, the test feels it.\n */\nconst ingestInboundSchema = z.object({\n action: z.literal('ingest-inbound'),\n channelId: z.string().uuid(),\n /** Opaque sender handle \u2014 a Discord snowflake, a Slack member id, etc. */\n senderIdentifier: z.string().min(1).max(255),\n senderDisplayName: z.string().max(255).optional(),\n body: z.string().max(50_000).optional(),\n externalMessageId: z.string().min(1).max(255),\n externalConversationId: z.string().min(1).max(255),\n})\n\nconst emitInboundSchema = z.object({\n action: z.literal('emit-inbound'),\n /** Channel that owns the inbound message; controls authorUserId + default visibility. */\n channelId: z.string().uuid(),\n /** Provider key persisted on the link (defaults to the stub provider). */\n providerKey: z.string().min(1).max(64).optional(),\n /** Normalized inbound addresses (stored under channelPayload). */\n from: addressFieldSchema.optional(),\n to: addressFieldSchema.optional(),\n cc: addressFieldSchema.optional(),\n subject: z.string().max(500).optional(),\n bodyText: z.string().max(200_000).optional(),\n /** RFC2822 Message-ID of this inbound message (for In-Reply-To matching). */\n messageId: z.string().max(500).optional(),\n /** RFC2822 In-Reply-To header (threading-inheritance fallback). */\n inReplyTo: z.string().max(500).optional(),\n references: z.array(z.string().max(500)).max(50).optional(),\n /**\n * Open Mercato `messages.message` thread id this inbound message belongs to.\n * When set, a `messages.message` row is created with this `threadId` so the\n * hub-thread inheritance join can resolve a Person from a sibling message.\n */\n messageThreadId: z.string().uuid().optional(),\n /**\n * Test-only: also create a `ChannelThreadMapping` for the seeded thread. The\n * reaction (`/messages/[id]/reactions`) and thread-assign\n * (`/threads/[id]/assign`) routes resolve the owning channel through this\n * mapping and return 409/404 without it. Opt-in so the existing CRM-link\n * seeds (which don't need a mapping) keep their current mapping-free shape.\n */\n createThreadMapping: z.boolean().optional(),\n})\n\nconst bodySchema = z.discriminatedUnion('action', [\n connectChannelSchema,\n ingestInboundSchema,\n emitInboundSchema,\n])\n\nexport async function POST(req: Request): Promise<Response> {\n // Fail-closed: invisible in production. Mirrors an unknown route (404) rather\n // than 403 so the surface leaks nothing when the flag is off.\n if (!isTestChannelSeedingEnabled()) {\n return NextResponse.json({ error: 'Not found' }, { status: 404 })\n }\n\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub || !auth?.tenantId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n let body: z.infer<typeof bodySchema>\n try {\n body = bodySchema.parse(await readJsonSafe(req, null))\n } catch (err) {\n return NextResponse.json(\n { error: err instanceof Error ? err.message : 'Invalid request body' },\n { status: 422 },\n )\n }\n\n const container = await createRequestContainer()\n // Defensive: make sure the stub adapter is registered for this process even if\n // a worker-only node skipped module di registration.\n ensureTestSeedAdapterRegistered()\n\n const tenantId = auth.tenantId as string\n const organizationId = (auth as { orgId?: string | null }).orgId ?? null\n const userId = auth.sub as string\n\n if (body.action === 'connect-channel') {\n const stamp = Date.now()\n const commandBus = container.resolve('commandBus') as CommandBus\n const isChatFlavor = body.providerFlavor === 'chat'\n // A chat channel is deliberately connected WITHOUT an email-ish credential\n // key, so `connect-credential-channel` derives no `externalIdentifier` and\n // the row is shaped exactly like a real Discord channel (identifier NULL \u2014\n // the condition #4977 describes). Inventing one here would recreate the\n // fixture dishonesty that hid #4975.\n const credentials = isChatFlavor\n ? { handle: body.externalIdentifier ?? `test-seed-chat-${stamp}` }\n : {\n username: body.externalIdentifier ?? `test-seed-${stamp}@test-seed.local`,\n fromAddress: body.externalIdentifier ?? `test-seed-${stamp}@test-seed.local`,\n }\n const input: ConnectCredentialChannelInput = {\n providerKey: isChatFlavor ? TEST_SEED_CHAT_PROVIDER_KEY : TEST_SEED_PROVIDER_KEY,\n displayName:\n body.displayName ?? `Test Seed ${isChatFlavor ? 'Chat ' : ''}Channel ${stamp}`,\n credentials,\n userId,\n scope: { tenantId, organizationId },\n }\n const { result } = await commandBus.execute<\n ConnectCredentialChannelInput,\n ConnectCredentialChannelResult\n >(COMMUNICATION_CHANNELS_CONNECT_CREDENTIAL_CHANNEL_COMMAND_ID, {\n input,\n ctx: {\n container,\n auth: auth as never,\n organizationScope: null,\n selectedOrganizationId: organizationId,\n organizationIds: organizationId ? [organizationId] : null,\n },\n })\n if (result.status !== 'connected') {\n return NextResponse.json(\n { error: '[internal] test-seed connect failed', detail: result },\n { status: 500 },\n )\n }\n if (body.labelAsProviderKey && body.labelAsProviderKey !== input.providerKey) {\n const seedEm = (container.resolve('em') as EntityManager).fork()\n const connected = await findOneWithDecryption(\n seedEm,\n CommunicationChannel,\n { id: result.channelId, tenantId },\n undefined,\n { tenantId, organizationId },\n )\n if (!connected) {\n return NextResponse.json(\n { error: '[internal] test-seed could not reload the channel it just connected' },\n { status: 500 },\n )\n }\n connected.providerKey = body.labelAsProviderKey\n await seedEm.flush()\n }\n return NextResponse.json(\n {\n channelId: result.channelId,\n externalIdentifier: result.externalIdentifier,\n providerKey: body.labelAsProviderKey ?? input.providerKey,\n },\n { status: 201 },\n )\n }\n\n // action === 'ingest-inbound' | 'emit-inbound' \u2014 both address an existing channel.\n const em = (container.resolve('em') as EntityManager).fork()\n // Only the `emit-inbound` branch stamps a caller-chosen provider key onto the\n // rows it seeds; `ingest-inbound` takes the channel's own (see below).\n const providerKey =\n body.action === 'emit-inbound' ? body.providerKey ?? TEST_SEED_PROVIDER_KEY : TEST_SEED_PROVIDER_KEY\n\n // `channelId` is caller-supplied, so confirm it names a channel this tenant/org\n // actually owns before seeding rows that reference it. Mirrors the ownership\n // lookup every other per-channel route performs (see channels/[id]/test-send).\n const ownedChannel = await findOneWithDecryption(\n em,\n CommunicationChannel,\n {\n id: body.channelId,\n tenantId,\n organizationId,\n deletedAt: null,\n },\n undefined,\n { tenantId, organizationId },\n )\n if (!ownedChannel) {\n return NextResponse.json({ error: 'Channel not found' }, { status: 404 })\n }\n\n // Tenant/org scope alone does not authorize: `connect_user_channel` is granted\n // broadly, so a same-tenant caller could otherwise seed against a colleague's\n // personal mailbox. Enforce the module's owner-only contract \u2014 personal\n // channels are owner-restricted, shared channels need `manage`.\n let userFeatures: string[] = []\n try {\n const rbac = container.resolve('rbacService') as RbacServiceLike\n const acl = await rbac.loadAcl(userId, { tenantId, organizationId })\n userFeatures = acl?.isSuperAdmin ? ['*'] : Array.isArray(acl?.features) ? acl.features : []\n } catch {\n userFeatures = []\n }\n try {\n assertCanManageChannel(\n { userId: ownedChannel.userId },\n userId,\n userFeatures,\n 'communication_channels.manage',\n )\n } catch (err) {\n if (err instanceof ChannelAccessDeniedError) {\n return NextResponse.json({ error: 'Channel not found' }, { status: 404 })\n }\n const status = (err as { statusCode?: number }).statusCode ?? 403\n return NextResponse.json(\n { error: err instanceof Error ? err.message : 'Access denied' },\n { status },\n )\n }\n\n if (body.action === 'ingest-inbound') {\n // Everything below this point is the real path: the adapter normalizes the\n // frame and `ingest_inbound_message` composes the platform message through\n // `messages.messages.compose`. Nothing is short-circuited, so a hub contract\n // the provider cannot satisfy surfaces here as a failure instead of hiding\n // behind seeded rows (#4975).\n // The channel's own provider key, never a hardcoded one: ingest does not\n // check that `providerKey` matches the channel it names, so passing a\n // different one would silently stamp the wrong provider onto the link.\n const channelProviderKey = ownedChannel.providerKey\n if (channelProviderKey !== TEST_SEED_CHAT_PROVIDER_KEY) {\n return NextResponse.json(\n {\n error:\n 'ingest-inbound requires a channel connected with providerFlavor: \"chat\"; ' +\n `channel ${body.channelId} is '${channelProviderKey}'`,\n },\n { status: 422 },\n )\n }\n\n const commandBus = container.resolve('commandBus') as CommandBus\n const adapterRegistry = container.resolve('channelAdapterRegistry') as {\n get: (key: string) => { normalizeInbound: (raw: unknown) => Promise<unknown> } | undefined\n }\n const adapter = adapterRegistry.get(channelProviderKey)\n if (!adapter) {\n return NextResponse.json(\n { error: '[internal] test-seed chat adapter is not registered' },\n { status: 500 },\n )\n }\n\n const normalized = await adapter.normalizeInbound({\n raw: {\n externalMessageId: body.externalMessageId,\n externalConversationId: body.externalConversationId,\n senderIdentifier: body.senderIdentifier,\n senderDisplayName: body.senderDisplayName,\n body: body.body ?? '',\n },\n eventType: 'message',\n metadata: {},\n })\n\n const ingestInput = {\n channelId: body.channelId,\n providerKey: channelProviderKey,\n channelType: ownedChannel.channelType,\n scope: { tenantId, organizationId },\n message: normalized,\n } as IngestInboundMessageInput\n\n const { result } = await commandBus.execute<\n IngestInboundMessageInput,\n IngestInboundMessageResult\n >(COMMUNICATION_CHANNELS_INGEST_INBOUND_COMMAND_ID, {\n input: ingestInput,\n ctx: {\n container,\n auth: auth as never,\n organizationScope: null,\n selectedOrganizationId: organizationId,\n organizationIds: organizationId ? [organizationId] : null,\n },\n })\n\n return NextResponse.json(\n {\n status: result.status,\n messageId: result.messageId ?? null,\n conversationId: result.externalConversationId ?? null,\n channelLinkId: result.channelLinkId ?? null,\n channelType: ownedChannel.channelType,\n },\n { status: 201 },\n )\n }\n\n // A MessageChannelLink requires a non-null external_conversation_id (FK) and\n // message_id. Create a synthetic conversation + (optionally threaded) message\n // so the link is shaped like a real inbound row the subscriber can consume.\n const conversation = em.create(ExternalConversation, {\n channelId: body.channelId,\n externalConversationId: `inbound-seed:${Date.now()}:${Math.random().toString(16).slice(2, 8)}`,\n subject: body.subject ?? null,\n tenantId,\n organizationId,\n lastMessageAt: new Date(),\n })\n em.persist(conversation)\n await em.flush()\n\n // Insert the platform `messages.message` row via raw SQL rather than importing\n // the messages module's entity class (cross-module ORM coupling rule). Only\n // `thread_id` matters for the hub-thread inheritance join (TC-CRM-EMAIL-005);\n // the rest satisfy NOT NULL constraints.\n const messageRows = (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.${providerKey}`,\n body.messageThreadId ?? null,\n userId,\n body.subject ?? '(no subject)',\n body.bodyText ?? '',\n body.channelId,\n tenantId,\n organizationId,\n ],\n )) as Array<{ id: string }>\n const messageId = messageRows[0]?.id\n if (!messageId) {\n return NextResponse.json({ error: '[internal] failed to seed message row' }, { status: 500 })\n }\n\n const link = em.create(MessageChannelLink, {\n messageId,\n externalConversationId: conversation.id,\n providerKey,\n channelType: 'email',\n direction: 'inbound',\n deliveryStatus: 'delivered',\n channelPayload: {\n ...(body.from !== undefined ? { from: body.from } : {}),\n ...(body.to !== undefined ? { to: body.to } : {}),\n ...(body.cc !== undefined ? { cc: body.cc } : {}),\n ...(body.subject !== undefined ? { subject: body.subject } : {}),\n ...(body.bodyText !== undefined ? { text: body.bodyText } : {}),\n ...(body.inReplyTo !== undefined ? { inReplyTo: body.inReplyTo } : {}),\n ...(body.references !== undefined ? { references: body.references } : {}),\n },\n channelContentType: 'text/plain',\n channelMetadata: {\n ...(body.messageId !== undefined ? { messageId: body.messageId } : {}),\n },\n tenantId,\n organizationId,\n })\n em.persist(link)\n await em.flush()\n\n // Optionally mirror `ingest-inbound-message`: a real inbound message always\n // lands a ChannelThreadMapping that the reaction + thread-assign routes use to\n // resolve the owning channel. Seeded inbound messages skip it by default; opt\n // in for tests that exercise those routes. Keyed by `messageThreadId ?? messageId`\n // to match how those commands resolve the mapping (`message.threadId ?? message.id`).\n if (body.createThreadMapping) {\n const mapping = em.create(ChannelThreadMapping, {\n externalConversationId: conversation.id,\n messageThreadId: body.messageThreadId ?? messageId,\n channelId: body.channelId,\n providerKey,\n externalThreadRef: conversation.externalConversationId,\n tenantId,\n organizationId,\n })\n em.persist(mapping)\n await em.flush()\n }\n\n // Emit the hub event through the real event bus so the persistent customers\n // link-channel-message-received subscriber is enqueued to the `events` queue.\n await emitCommunicationChannelsEvent(\n 'communication_channels.message.received',\n {\n channelLinkId: link.id,\n channelId: body.channelId,\n providerKey,\n direction: 'inbound',\n tenantId,\n organizationId,\n },\n { persistent: true },\n )\n\n return NextResponse.json(\n { channelLinkId: link.id, messageId, conversationId: conversation.id },\n { status: 201 },\n )\n}\n\nexport const openApi = {\n tags: ['CommunicationChannels'],\n methods: {\n POST: {\n summary:\n 'Test-only: seed a connected channel, ingest a real inbound message, or emit a seeded inbound link (env-gated)',\n tags: ['CommunicationChannels'],\n responses: [\n { status: 201, description: 'Channel seeded / inbound message emitted' },\n { status: 401, description: 'Unauthorized' },\n {\n status: 404,\n description:\n 'Test channel seeding disabled (production default), or the requested channel does not belong to the caller',\n },\n { status: 422, description: 'Invalid request body' },\n { status: 500, description: 'Seed failed' },\n ],\n },\n },\n}\n\nexport default POST\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAEvC,SAAS,oBAAoB;AAC7B,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,0BAA0B,8BAA8B;AACjE;AAAA,EACE;AAAA,OAGK;AACP,SAAS,sCAAsC;AAC/C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,OAGK;AAmCA,MAAM,WAAW;AAAA,EACtB,MAAM;AAAA,EACN,MAAM;AAAA,IACJ,aAAa;AAAA,IACb,iBAAiB,CAAC,6CAA6C;AAAA,EACjE;AACF;AAEA,MAAM,sBAAsB,EAAE,OAAO,EAAE,SAAS,EAAE,OAAO,GAAG,MAAM,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC;AACzF,MAAM,qBAAqB,EAAE,MAAM;AAAA,EACjC,EAAE,OAAO;AAAA,EACT;AAAA,EACA,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,mBAAmB,CAAC,CAAC;AACpD,CAAC;AAED,MAAM,uBAAuB,EAAE,OAAO;AAAA,EACpC,QAAQ,EAAE,QAAQ,iBAAiB;AAAA,EACnC,aAAa,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,EAAE,SAAS;AAAA,EACjD,oBAAoB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAA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A,EACrB,MAAM,CAAC,uBAAuB;AAAA,EAC9B,SAAS;AAAA,IACP,MAAM;AAAA,MACJ,SACE;AAAA,MACF,MAAM,CAAC,uBAAuB;AAAA,MAC9B,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,2CAA2C;AAAA,QACvE,EAAE,QAAQ,KAAK,aAAa,eAAe;AAAA,QAC3C;AAAA,UACE,QAAQ;AAAA,UACR,aACE;AAAA,QACJ;AAAA,QACA,EAAE,QAAQ,KAAK,aAAa,uBAAuB;AAAA,QACnD,EAAE,QAAQ,KAAK,aAAa,cAAc;AAAA,MAC5C;AAAA,IACF;AAAA,EACF;AACF;AAEA,IAAO,gBAAQ;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -8,6 +8,10 @@ function channelOrgScopeWhereFromFilter(filter) {
|
|
|
8
8
|
if (!organizationIds || organizationIds.length === 0) return {};
|
|
9
9
|
return { $or: [{ organizationId: { $in: organizationIds } }, { organizationId: null }] };
|
|
10
10
|
}
|
|
11
|
+
function channelOwnerScopeWhere(currentUserId) {
|
|
12
|
+
if (!currentUserId) return { userId: null };
|
|
13
|
+
return { $or: [{ userId: null }, { userId: currentUserId }] };
|
|
14
|
+
}
|
|
11
15
|
function assertCanAccessChannel(channel, currentUserId, userFeatures) {
|
|
12
16
|
if (!channel) {
|
|
13
17
|
throw new ChannelAccessDeniedError("Channel not found");
|
|
@@ -48,6 +52,7 @@ export {
|
|
|
48
52
|
assertCanAccessChannel,
|
|
49
53
|
assertCanManageChannel,
|
|
50
54
|
channelOrgScopeWhere,
|
|
51
|
-
channelOrgScopeWhereFromFilter
|
|
55
|
+
channelOrgScopeWhereFromFilter,
|
|
56
|
+
channelOwnerScopeWhere
|
|
52
57
|
};
|
|
53
58
|
//# sourceMappingURL=access-control.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/communication_channels/lib/access-control.ts"],
|
|
4
|
-
"sourcesContent": ["import { authorizeFeatures } from '@open-mercato/shared/security/featurePolicy'\n\n/**\n * Per-user channel access control \u2014 service-layer authorization helpers.\n *\n * Personal mailbox privacy (v1: strict owner-only). A per-user channel\n * (`userId` set) may be read or managed ONLY by its owner \u2014 not even an admin\n * or superadmin can act on another user's personal mailbox. Tenant-wide /\n * shared channels (`userId == null`, e.g. WhatsApp Business / Slack workspaces)\n * remain accessible to any caller the route already feature-gated.\n *\n * Routes also narrow at the SQL layer (the admin channel list returns\n * `user_id IS NULL` rows only; the profile list filters `user_id =\n * currentUser.id`); these helpers are the per-channel authorization backstop a\n * route calls once it has loaded the row.\n */\n\nexport const ADMIN_FEATURE = 'communication_channels.admin'\n\n/**\n * Org-scoping fragment for reading/managing channels.\n *\n * Tenant-wide channels are stored with `organization_id IS NULL` (the\n * tenant-scoped push providers FCM/APNs/Expo do this deliberately \u2014 see\n * `connect-credential-channel.ts`). They are visible and manageable from ANY\n * org in the tenant, so a read scoped to the caller's selected org must also\n * match the NULL rows; otherwise a channel connected while an admin had a\n * non-null org would be invisible to every listing/detail query (and vice\n * versa). Org-scoped channels (`organization_id = <org>`) stay scoped to their\n * org.\n *\n * Spread the result into a MikroORM `where` object alongside `tenantId` etc.\n */\nexport function channelOrgScopeWhere(\n orgId: string | null | undefined,\n): Record<string, unknown> {\n return orgId\n ? { $or: [{ organizationId: orgId }, { organizationId: null }] }\n : { organizationId: null }\n}\n\n/**\n * Same NULL-inclusive org scoping, expressed over a resolved\n * `OrganizationScopeFilter` (`resolveOrganizationScopeFilter`) rather than a\n * single org id.\n *\n * Read routes scope on the caller's *selected* organization (the\n * `om_selected_org` cookie the top-bar switcher writes), not on the org baked\n * into the session token (#5012) \u2014 that resolution yields a list of org ids, or\n * `undefined` when the caller is unrestricted (super-admin viewing all orgs).\n * An unrestricted caller sees every channel in the tenant, so the fragment is\n * empty; a restricted one gets their orgs plus the tenant-wide (`NULL`) rows.\n */\nexport function channelOrgScopeWhereFromFilter(\n filter: { organizationIds: string[] | undefined } | null | undefined,\n): Record<string, unknown> {\n const organizationIds = filter?.organizationIds\n if (!organizationIds || organizationIds.length === 0) return {}\n return { $or: [{ organizationId: { $in: organizationIds } }, { organizationId: null }] }\n}\n\n/**\n * Throws when the caller may not access a specific channel. Returns silently\n * when access is allowed.\n *\n * Personal mailbox privacy (v1: strict owner-only). A per-user channel\n * (`userId` set) may be acted on ONLY by its owner \u2014 not even an admin /\n * superadmin can poll, test-send, import history from, register push on, or\n * delete another user's personal mailbox. Tenant-wide channels\n * (`userId == null`, e.g. WhatsApp Business / Slack workspaces) remain\n * accessible to any caller the route already feature-gated.\n *\n * `userFeatures` is retained on the signature (callers pass it) but no longer\n * grants a bypass; it is reserved for the v2 admin-oversight feature.\n *\n * Callers MUST pass the fully decrypted channel row \u2014 we read `userId` directly.\n */\nexport function assertCanAccessChannel(\n channel: { userId?: string | null } | null | undefined,\n currentUserId: string | null | undefined,\n userFeatures: string[] | null | undefined,\n): void {\n if (!channel) {\n // Defensive: callers pre-check existence and return 404, so this is\n // unreachable in practice. Throw the typed access error (route-mapped to a\n // masked 404) rather than a bare Error that would surface as a 500.\n throw new ChannelAccessDeniedError('Channel not found')\n }\n void userFeatures\n // Tenant-wide / shared channel \u2014 accessible to all callers.\n if (channel.userId == null) return\n // Personal mailbox \u2014 owner only, regardless of admin grants (v1).\n if (channel.userId !== currentUserId) {\n throw new ChannelAccessDeniedError(\n 'Channel is a personal mailbox owned by another user',\n )\n }\n}\n\n/**\n * Authorization for MANAGING (mutating) a channel \u2014 disconnect, poll, set\n * primary, import history, register push. Encodes the per-user ownership rule:\n *\n * - **Personal mailbox** (`userId` set): the **owner has full control** of\n * their own account; any other caller \u2014 admin included \u2014 is denied (v1\n * strict owner-only, no bypass). Routes gate these on\n * `communication_channels.connect_user_channel` so every email user reaches\n * this check for their own channels.\n * - **Tenant-wide / shared channel** (`userId == null`, e.g. WhatsApp\n * Business / Slack workspaces): requires the route's `elevatedFeature`\n * (`communication_channels.manage`, `\u2026channel.push.manage`, or\n * `\u2026channel.import_history`). Evaluated by the shared feature policy.\n *\n * Throws `ChannelAccessDeniedError` (route handlers map it to 404, masking\n * existence) when the caller may not manage the channel.\n */\nexport function assertCanManageChannel(\n channel: { userId?: string | null } | null | undefined,\n currentUserId: string | null | undefined,\n userFeatures: string[] | null | undefined,\n elevatedFeature: string,\n): void {\n if (!channel) {\n // Defensive: callers pre-check existence and return 404, so this is\n // unreachable in practice. Throw the typed access error (route-mapped to a\n // masked 404) rather than a bare Error that would surface as a 500.\n throw new ChannelAccessDeniedError('Channel not found')\n }\n // Personal mailbox \u2014 owner only. The owner manages their own account fully\n // (gated by connect_user_channel at the route); no admin bypass in v1.\n if (channel.userId != null) {\n if (channel.userId !== currentUserId) {\n throw new ChannelAccessDeniedError('Channel is a personal mailbox owned by another user')\n }\n return\n }\n // Tenant-wide / shared channel \u2014 requires the elevated management feature.\n const grantedFeatures = Array.isArray(userFeatures) ? userFeatures : []\n if (!authorizeFeatures([elevatedFeature], { grantedFeatures })) {\n throw new ChannelAccessDeniedError(`Managing a shared channel requires '${elevatedFeature}'`)\n }\n}\n\n/**\n * Stable error class so route handlers can map to a 403 instead of leaking the\n * underlying message verbatim. Subclasses `Error` for compatibility with the\n * platform's error logging helpers.\n */\nexport class ChannelAccessDeniedError extends Error {\n override name = 'ChannelAccessDeniedError'\n readonly statusCode = 403\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,yBAAyB;AAiB3B,MAAM,gBAAgB;AAgBtB,SAAS,qBACd,OACyB;AACzB,SAAO,QACH,EAAE,KAAK,CAAC,EAAE,gBAAgB,MAAM,GAAG,EAAE,gBAAgB,KAAK,CAAC,EAAE,IAC7D,EAAE,gBAAgB,KAAK;AAC7B;AAcO,SAAS,+BACd,QACyB;AACzB,QAAM,kBAAkB,QAAQ;AAChC,MAAI,CAAC,mBAAmB,gBAAgB,WAAW,EAAG,QAAO,CAAC;AAC9D,SAAO,EAAE,KAAK,CAAC,EAAE,gBAAgB,EAAE,KAAK,gBAAgB,EAAE,GAAG,EAAE,gBAAgB,KAAK,CAAC,EAAE;AACzF;AAkBO,SAAS,uBACd,SACA,eACA,cACM;AACN,MAAI,CAAC,SAAS;AAIZ,UAAM,IAAI,yBAAyB,mBAAmB;AAAA,EACxD;AACA,OAAK;AAEL,MAAI,QAAQ,UAAU,KAAM;AAE5B,MAAI,QAAQ,WAAW,eAAe;AACpC,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACF;AAmBO,SAAS,uBACd,SACA,eACA,cACA,iBACM;AACN,MAAI,CAAC,SAAS;AAIZ,UAAM,IAAI,yBAAyB,mBAAmB;AAAA,EACxD;AAGA,MAAI,QAAQ,UAAU,MAAM;AAC1B,QAAI,QAAQ,WAAW,eAAe;AACpC,YAAM,IAAI,yBAAyB,qDAAqD;AAAA,IAC1F;AACA;AAAA,EACF;AAEA,QAAM,kBAAkB,MAAM,QAAQ,YAAY,IAAI,eAAe,CAAC;AACtE,MAAI,CAAC,kBAAkB,CAAC,eAAe,GAAG,EAAE,gBAAgB,CAAC,GAAG;AAC9D,UAAM,IAAI,yBAAyB,uCAAuC,eAAe,GAAG;AAAA,EAC9F;AACF;AAOO,MAAM,iCAAiC,MAAM;AAAA,EAA7C;AAAA;AACL,SAAS,OAAO;AAChB,SAAS,aAAa;AAAA;AACxB;",
|
|
4
|
+
"sourcesContent": ["import { authorizeFeatures } from '@open-mercato/shared/security/featurePolicy'\n\n/**\n * Per-user channel access control \u2014 service-layer authorization helpers.\n *\n * Personal mailbox privacy (v1: strict owner-only). A per-user channel\n * (`userId` set) may be read or managed ONLY by its owner \u2014 not even an admin\n * or superadmin can act on another user's personal mailbox. Tenant-wide /\n * shared channels (`userId == null`, e.g. WhatsApp Business / Slack workspaces)\n * remain accessible to any caller the route already feature-gated.\n *\n * Routes also narrow at the SQL layer (the admin channel list returns\n * `user_id IS NULL` rows only; the profile list filters `user_id =\n * currentUser.id`); these helpers are the per-channel authorization backstop a\n * route calls once it has loaded the row.\n */\n\nexport const ADMIN_FEATURE = 'communication_channels.admin'\n\n/**\n * Org-scoping fragment for reading/managing channels.\n *\n * Tenant-wide channels are stored with `organization_id IS NULL` (the\n * tenant-scoped push providers FCM/APNs/Expo do this deliberately \u2014 see\n * `connect-credential-channel.ts`). They are visible and manageable from ANY\n * org in the tenant, so a read scoped to the caller's selected org must also\n * match the NULL rows; otherwise a channel connected while an admin had a\n * non-null org would be invisible to every listing/detail query (and vice\n * versa). Org-scoped channels (`organization_id = <org>`) stay scoped to their\n * org.\n *\n * Spread the result into a MikroORM `where` object alongside `tenantId` etc.\n */\nexport function channelOrgScopeWhere(\n orgId: string | null | undefined,\n): Record<string, unknown> {\n return orgId\n ? { $or: [{ organizationId: orgId }, { organizationId: null }] }\n : { organizationId: null }\n}\n\n/**\n * Same NULL-inclusive org scoping, expressed over a resolved\n * `OrganizationScopeFilter` (`resolveOrganizationScopeFilter`) rather than a\n * single org id.\n *\n * Read routes scope on the caller's *selected* organization (the\n * `om_selected_org` cookie the top-bar switcher writes), not on the org baked\n * into the session token (#5012) \u2014 that resolution yields a list of org ids, or\n * `undefined` when the caller is unrestricted (super-admin viewing all orgs).\n * An unrestricted caller sees every channel in the tenant, so the fragment is\n * empty; a restricted one gets their orgs plus the tenant-wide (`NULL`) rows.\n */\nexport function channelOrgScopeWhereFromFilter(\n filter: { organizationIds: string[] | undefined } | null | undefined,\n): Record<string, unknown> {\n const organizationIds = filter?.organizationIds\n if (!organizationIds || organizationIds.length === 0) return {}\n return { $or: [{ organizationId: { $in: organizationIds } }, { organizationId: null }] }\n}\n\n/**\n * Ownership fragment for LISTING channels \u2014 the SQL-layer twin of\n * {@link assertCanAccessChannel}.\n *\n * Routes have historically hardcoded one of the two halves of the rule: the\n * admin channel list narrows to `user_id IS NULL`, the profile list narrows to\n * `user_id = <caller>`. A provider-scoped listing needs both, because which half\n * a channel falls into is decided by the connect flow the provider offers, not\n * by the listing. Hardcoding `userId: null` is what made the Discord AI\n * auto-reply panel structurally empty (#5602): every route the product exposes\n * for connecting a Discord bot writes `user_id = auth.sub`, so the filter\n * excluded the only channels that can exist.\n *\n * The clause admits exactly what the assert allows and nothing more \u2014 shared\n * channels, plus the caller's own personal ones. It grants no admin bypass, in\n * line with v1 strict owner-only: a personal mailbox stays invisible to everyone\n * but its owner. An anonymous caller (no user id) sees shared channels only.\n *\n * Spread into a MikroORM `where`, or nest under `$and` when another fragment in\n * the same query already claims `$or` (`channelOrgScopeWhereFromFilter` does).\n */\nexport function channelOwnerScopeWhere(\n currentUserId: string | null | undefined,\n): Record<string, unknown> {\n if (!currentUserId) return { userId: null }\n return { $or: [{ userId: null }, { userId: currentUserId }] }\n}\n\n/**\n * Throws when the caller may not access a specific channel. Returns silently\n * when access is allowed.\n *\n * Personal mailbox privacy (v1: strict owner-only). A per-user channel\n * (`userId` set) may be acted on ONLY by its owner \u2014 not even an admin /\n * superadmin can poll, test-send, import history from, register push on, or\n * delete another user's personal mailbox. Tenant-wide channels\n * (`userId == null`, e.g. WhatsApp Business / Slack workspaces) remain\n * accessible to any caller the route already feature-gated.\n *\n * `userFeatures` is retained on the signature (callers pass it) but no longer\n * grants a bypass; it is reserved for the v2 admin-oversight feature.\n *\n * Callers MUST pass the fully decrypted channel row \u2014 we read `userId` directly.\n */\nexport function assertCanAccessChannel(\n channel: { userId?: string | null } | null | undefined,\n currentUserId: string | null | undefined,\n userFeatures: string[] | null | undefined,\n): void {\n if (!channel) {\n // Defensive: callers pre-check existence and return 404, so this is\n // unreachable in practice. Throw the typed access error (route-mapped to a\n // masked 404) rather than a bare Error that would surface as a 500.\n throw new ChannelAccessDeniedError('Channel not found')\n }\n void userFeatures\n // Tenant-wide / shared channel \u2014 accessible to all callers.\n if (channel.userId == null) return\n // Personal mailbox \u2014 owner only, regardless of admin grants (v1).\n if (channel.userId !== currentUserId) {\n throw new ChannelAccessDeniedError(\n 'Channel is a personal mailbox owned by another user',\n )\n }\n}\n\n/**\n * Authorization for MANAGING (mutating) a channel \u2014 disconnect, poll, set\n * primary, import history, register push. Encodes the per-user ownership rule:\n *\n * - **Personal mailbox** (`userId` set): the **owner has full control** of\n * their own account; any other caller \u2014 admin included \u2014 is denied (v1\n * strict owner-only, no bypass). Routes gate these on\n * `communication_channels.connect_user_channel` so every email user reaches\n * this check for their own channels.\n * - **Tenant-wide / shared channel** (`userId == null`, e.g. WhatsApp\n * Business / Slack workspaces): requires the route's `elevatedFeature`\n * (`communication_channels.manage`, `\u2026channel.push.manage`, or\n * `\u2026channel.import_history`). Evaluated by the shared feature policy.\n *\n * Throws `ChannelAccessDeniedError` (route handlers map it to 404, masking\n * existence) when the caller may not manage the channel.\n */\nexport function assertCanManageChannel(\n channel: { userId?: string | null } | null | undefined,\n currentUserId: string | null | undefined,\n userFeatures: string[] | null | undefined,\n elevatedFeature: string,\n): void {\n if (!channel) {\n // Defensive: callers pre-check existence and return 404, so this is\n // unreachable in practice. Throw the typed access error (route-mapped to a\n // masked 404) rather than a bare Error that would surface as a 500.\n throw new ChannelAccessDeniedError('Channel not found')\n }\n // Personal mailbox \u2014 owner only. The owner manages their own account fully\n // (gated by connect_user_channel at the route); no admin bypass in v1.\n if (channel.userId != null) {\n if (channel.userId !== currentUserId) {\n throw new ChannelAccessDeniedError('Channel is a personal mailbox owned by another user')\n }\n return\n }\n // Tenant-wide / shared channel \u2014 requires the elevated management feature.\n const grantedFeatures = Array.isArray(userFeatures) ? userFeatures : []\n if (!authorizeFeatures([elevatedFeature], { grantedFeatures })) {\n throw new ChannelAccessDeniedError(`Managing a shared channel requires '${elevatedFeature}'`)\n }\n}\n\n/**\n * Stable error class so route handlers can map to a 403 instead of leaking the\n * underlying message verbatim. Subclasses `Error` for compatibility with the\n * platform's error logging helpers.\n */\nexport class ChannelAccessDeniedError extends Error {\n override name = 'ChannelAccessDeniedError'\n readonly statusCode = 403\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,yBAAyB;AAiB3B,MAAM,gBAAgB;AAgBtB,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MAAM;AAAA,EAA7C;AAAA;AACL,SAAS,OAAO;AAChB,SAAS,aAAa;AAAA;AACxB;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { lookupHashCandidates } from "@open-mercato/shared/lib/encryption/aes";
|
|
1
2
|
const COMMUNICATION_CHANNELS_SYSTEM_USER_ID = "00000000-0000-0000-0000-000000000000";
|
|
2
3
|
function systemUserEmail(tenantId) {
|
|
3
4
|
return `system+communication_channels@${tenantId}.local`;
|
|
@@ -5,9 +6,13 @@ function systemUserEmail(tenantId) {
|
|
|
5
6
|
async function resolveCommunicationChannelsSystemUserId(em, tenantId, fallbackId) {
|
|
6
7
|
try {
|
|
7
8
|
const expectedEmail = systemUserEmail(tenantId);
|
|
8
|
-
const
|
|
9
|
-
const
|
|
10
|
-
const
|
|
9
|
+
const emailHashes = lookupHashCandidates(expectedEmail);
|
|
10
|
+
const placeholders = emailHashes.map(() => "?").join(", ");
|
|
11
|
+
const rows = await em.getConnection().execute(
|
|
12
|
+
`SELECT id FROM users WHERE email_hash IN (${placeholders}) AND tenant_id = ? AND deleted_at IS NULL LIMIT 1`,
|
|
13
|
+
[...emailHashes, tenantId]
|
|
14
|
+
);
|
|
15
|
+
const id = Array.isArray(rows) ? rows[0]?.id : void 0;
|
|
11
16
|
if (typeof id === "string" && id.length > 0) return id;
|
|
12
17
|
} catch {
|
|
13
18
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/communication_channels/lib/system-user.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\n\n/**\n * Sentinel UUID \u2014 used as a last-resort `senderUserId` for inbound channel\n * messages when no per-tenant system user is available. Matches the pattern\n * in `inbox_ops/lib/messagesIntegration.ts`.\n */\nexport const COMMUNICATION_CHANNELS_SYSTEM_USER_ID = '00000000-0000-0000-0000-000000000000'\n\n/**\n * Configurable email pattern for per-tenant channel-bot users. Implementations\n * (provider packages, onboarding scripts) may create a real `auth.user` row\n * matching this convention so inbound channel messages get a meaningful sender\n * display name in the unified inbox.\n *\n * Format: `system+communication_channels@<tenantId>.local`\n */\nexport function systemUserEmail(tenantId: string): string {\n return `system+communication_channels@${tenantId}.local`\n}\n\n/**\n * Resolve a tenant-scoped system user id to attribute inbound channel messages to.\n *\n * Lookup order:\n * 1. Per-tenant channel-bot user (by convention email \u2014 see `systemUserEmail`).\n * 2. (Optional, caller-supplied) seed fallback \u2014 a specific override id.\n * 3. Sentinel UUID (`00000000-...`) \u2014 backward-compatible default.\n *\n * The function is fail-soft: when the lookup throws, it falls back to the\n * sentinel. The inbound-processor must never refuse to ingest a message\n * because the channel-bot user doesn't exist.\n *\n * @param em EntityManager scoped to the tenant.\n * @param tenantId Tenant id for which to resolve the system user.\n * @param fallbackId Optional caller-supplied fallback (e.g., the channel's\n * assigned user) used when the channel-bot lookup misses.\n */\nexport async function resolveCommunicationChannelsSystemUserId(\n em: EntityManager,\n tenantId: string,\n fallbackId?: string | null,\n): Promise<string> {\n try {\n const expectedEmail = systemUserEmail(tenantId)\n //
|
|
5
|
-
"mappings": "
|
|
4
|
+
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { lookupHashCandidates } from '@open-mercato/shared/lib/encryption/aes'\n\n/**\n * Sentinel UUID \u2014 used as a last-resort `senderUserId` for inbound channel\n * messages when no per-tenant system user is available. Matches the pattern\n * in `inbox_ops/lib/messagesIntegration.ts`.\n */\nexport const COMMUNICATION_CHANNELS_SYSTEM_USER_ID = '00000000-0000-0000-0000-000000000000'\n\n/**\n * Configurable email pattern for per-tenant channel-bot users. Implementations\n * (provider packages, onboarding scripts) may create a real `auth.user` row\n * matching this convention so inbound channel messages get a meaningful sender\n * display name in the unified inbox.\n *\n * Format: `system+communication_channels@<tenantId>.local`\n */\nexport function systemUserEmail(tenantId: string): string {\n return `system+communication_channels@${tenantId}.local`\n}\n\n/**\n * Resolve a tenant-scoped system user id to attribute inbound channel messages to.\n *\n * Lookup order:\n * 1. Per-tenant channel-bot user (by convention email \u2014 see `systemUserEmail`).\n * 2. (Optional, caller-supplied) seed fallback \u2014 a specific override id.\n * 3. Sentinel UUID (`00000000-...`) \u2014 backward-compatible default.\n *\n * The function is fail-soft: when the lookup throws, it falls back to the\n * sentinel. The inbound-processor must never refuse to ingest a message\n * because the channel-bot user doesn't exist.\n *\n * That fail-soft design is also what hid #5599 for as long as it did \u2014 a broken\n * lookup and an absent user produce the identical outcome \u2014 so the two\n * properties the lookup depends on (the column it matches and the table it\n * names) are pinned by `__tests__/system-user.test.ts` rather than left to the\n * next reader to notice.\n *\n * @param em EntityManager scoped to the tenant.\n * @param tenantId Tenant id for which to resolve the system user.\n * @param fallbackId Optional caller-supplied fallback (e.g., the channel's\n * assigned user) used when the channel-bot lookup misses.\n */\nexport async function resolveCommunicationChannelsSystemUserId(\n em: EntityManager,\n tenantId: string,\n fallbackId?: string | null,\n): Promise<string> {\n try {\n const expectedEmail = systemUserEmail(tenantId)\n // Match on `email_hash`, never on `email` (#5599). `users.email` is\n // encrypted at rest with a per-row IV, so its ciphertext is\n // non-deterministic and an equality filter against the plaintext can never\n // hit \u2014 which is exactly why the tenant uniqueness index keys on\n // `email_hash` instead (see `auth/data/entities.ts`). The candidate list\n // covers both the keyed `v2:` digest and the legacy unkeyed one, so a\n // deployment that has not yet backfilled still matches.\n //\n // The digests must be computed the same way `auth` writes them\n // (`auth/lib/emailHash.ts` \u2192 `hashForLookup(email)`), i.e. with NO hash\n // context. Reusing the shared primitive rather than importing the auth\n // helper keeps this module free of a cross-module code dependency; the two\n // must stay aligned if `auth` ever adopts a context.\n const emailHashes = lookupHashCandidates(expectedEmail)\n\n // Raw SQL against the table, not `createQueryBuilder('auth.users')`. That\n // call names no registered entity \u2014 entities are discovered under their\n // class names \u2014 so MikroORM reads the dot as a schema qualifier and looks\n // for `users` in a schema named `auth`, which this project never creates\n // (`Migration20251030150038` puts `users` in the default schema). The helper\n // swallows every error by design, so the miss was indistinguishable from\n // \"no channel-bot user exists\" and hid behind the same fallback as the\n // plaintext-vs-ciphertext defect above. A parameterized statement names the\n // table unambiguously and still pulls in no cross-module entity class,\n // keeping the decoupling this helper was written for.\n const placeholders = emailHashes.map(() => '?').join(', ')\n const rows = await em\n .getConnection()\n .execute<Array<{ id?: string }>>(\n `SELECT id FROM users WHERE email_hash IN (${placeholders}) AND tenant_id = ? AND deleted_at IS NULL LIMIT 1`,\n [...emailHashes, tenantId],\n )\n const id = Array.isArray(rows) ? rows[0]?.id : undefined\n if (typeof id === 'string' && id.length > 0) return id\n } catch {\n // ignore \u2014 fall through to fallback\n }\n if (typeof fallbackId === 'string' && fallbackId.length > 0) return fallbackId\n return COMMUNICATION_CHANNELS_SYSTEM_USER_ID\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,4BAA4B;AAO9B,MAAM,wCAAwC;AAU9C,SAAS,gBAAgB,UAA0B;AACxD,SAAO,iCAAiC,QAAQ;AAClD;AAyBA,eAAsB,yCACpB,IACA,UACA,YACiB;AACjB,MAAI;AACF,UAAM,gBAAgB,gBAAgB,QAAQ;AAc9C,UAAM,cAAc,qBAAqB,aAAa;AAYtD,UAAM,eAAe,YAAY,IAAI,MAAM,GAAG,EAAE,KAAK,IAAI;AACzD,UAAM,OAAO,MAAM,GAChB,cAAc,EACd;AAAA,MACC,6CAA6C,YAAY;AAAA,MACzD,CAAC,GAAG,aAAa,QAAQ;AAAA,IAC3B;AACF,UAAM,KAAK,MAAM,QAAQ,IAAI,IAAI,KAAK,CAAC,GAAG,KAAK;AAC/C,QAAI,OAAO,OAAO,YAAY,GAAG,SAAS,EAAG,QAAO;AAAA,EACtD,QAAQ;AAAA,EAER;AACA,MAAI,OAAO,eAAe,YAAY,WAAW,SAAS,EAAG,QAAO;AACpE,SAAO;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -6,6 +6,7 @@ import { resolveOrganizationScopeForRequest } from "@open-mercato/core/modules/d
|
|
|
6
6
|
import { CrudHttpError, isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
|
|
7
7
|
import { getCommandInterceptorHttpRejection } from "@open-mercato/shared/lib/commands/errors";
|
|
8
8
|
import { readJsonSafe } from "@open-mercato/shared/lib/http/readJsonSafe";
|
|
9
|
+
import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
|
|
9
10
|
import { runRouteMutationGuards } from "@open-mercato/shared/lib/crud/route-mutation-guard";
|
|
10
11
|
import { withScopedPayload } from "@open-mercato/shared/lib/api/scoped";
|
|
11
12
|
import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
|
|
@@ -72,7 +73,7 @@ function isSuperAdmin(auth) {
|
|
|
72
73
|
function buildAuthContext(context) {
|
|
73
74
|
const userId = context.ctx.auth?.sub;
|
|
74
75
|
if (!userId) {
|
|
75
|
-
throw new CrudHttpError(401, { error: "warranty_claims.errors.unauthorized" });
|
|
76
|
+
throw new CrudHttpError(401, { error: context.translate("warranty_claims.errors.unauthorized", "Unauthorized") });
|
|
76
77
|
}
|
|
77
78
|
return {
|
|
78
79
|
tenantId: context.tenantId,
|
|
@@ -85,7 +86,7 @@ function buildAuthContext(context) {
|
|
|
85
86
|
function buildAttachmentAuthContext(context) {
|
|
86
87
|
const auth = context.ctx.auth;
|
|
87
88
|
if (!auth?.sub) {
|
|
88
|
-
throw new CrudHttpError(401, { error: "warranty_claims.errors.unauthorized" });
|
|
89
|
+
throw new CrudHttpError(401, { error: context.translate("warranty_claims.errors.unauthorized", "Unauthorized") });
|
|
89
90
|
}
|
|
90
91
|
return {
|
|
91
92
|
...auth,
|
|
@@ -94,16 +95,16 @@ function buildAttachmentAuthContext(context) {
|
|
|
94
95
|
orgId: context.organizationId
|
|
95
96
|
};
|
|
96
97
|
}
|
|
97
|
-
async function resolveAssessContext(req) {
|
|
98
|
+
async function resolveAssessContext(req, translate) {
|
|
98
99
|
const container = await createRequestContainer();
|
|
99
100
|
const auth = await getAuthFromRequest(req);
|
|
100
101
|
if (!auth || !auth.tenantId) {
|
|
101
|
-
throw new CrudHttpError(401, { error: "warranty_claims.errors.unauthorized" });
|
|
102
|
+
throw new CrudHttpError(401, { error: translate("warranty_claims.errors.unauthorized", "Unauthorized") });
|
|
102
103
|
}
|
|
103
104
|
const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req });
|
|
104
105
|
const organizationId = scope?.selectedId ?? auth.orgId ?? null;
|
|
105
106
|
if (!organizationId) {
|
|
106
|
-
throw new CrudHttpError(400, { error: "warranty_claims.errors.organization_required" });
|
|
107
|
+
throw new CrudHttpError(400, { error: translate("warranty_claims.errors.organization_required", "Organization context is required.") });
|
|
107
108
|
}
|
|
108
109
|
return {
|
|
109
110
|
ctx: {
|
|
@@ -118,7 +119,7 @@ async function resolveAssessContext(req) {
|
|
|
118
119
|
organizationId,
|
|
119
120
|
container,
|
|
120
121
|
em: container.resolve("em").fork(),
|
|
121
|
-
translate
|
|
122
|
+
translate
|
|
122
123
|
};
|
|
123
124
|
}
|
|
124
125
|
function toAssessInput(payload, context) {
|
|
@@ -127,7 +128,7 @@ function toAssessInput(payload, context) {
|
|
|
127
128
|
async function runGuard(req, context, input) {
|
|
128
129
|
const userId = context.ctx.auth?.sub;
|
|
129
130
|
if (!userId) {
|
|
130
|
-
throw new CrudHttpError(401, { error: "warranty_claims.errors.unauthorized" });
|
|
131
|
+
throw new CrudHttpError(401, { error: context.translate("warranty_claims.errors.unauthorized", "Unauthorized") });
|
|
131
132
|
}
|
|
132
133
|
return runRouteMutationGuards({
|
|
133
134
|
container: context.ctx.container,
|
|
@@ -145,7 +146,7 @@ async function runGuard(req, context, input) {
|
|
|
145
146
|
}
|
|
146
147
|
});
|
|
147
148
|
}
|
|
148
|
-
async function loadScopedLine(em, scope, claimId, lineId) {
|
|
149
|
+
async function loadScopedLine(em, scope, claimId, lineId, translate) {
|
|
149
150
|
const line = await findOneWithDecryption(
|
|
150
151
|
em,
|
|
151
152
|
WarrantyClaimLine,
|
|
@@ -160,7 +161,7 @@ async function loadScopedLine(em, scope, claimId, lineId) {
|
|
|
160
161
|
scope
|
|
161
162
|
);
|
|
162
163
|
if (!line) {
|
|
163
|
-
throw new CrudHttpError(404, { error: "warranty_claims.errors.notFound" });
|
|
164
|
+
throw new CrudHttpError(404, { error: translate("warranty_claims.errors.notFound", "Claim not found.") });
|
|
164
165
|
}
|
|
165
166
|
return line;
|
|
166
167
|
}
|
|
@@ -182,7 +183,7 @@ async function verifyAttachmentLinkedToTarget(context, input) {
|
|
|
182
183
|
]
|
|
183
184
|
}) : false;
|
|
184
185
|
if (!linked) {
|
|
185
|
-
throw new CrudHttpError(400, { error: "warranty_claims.errors.attachmentNotLinked" });
|
|
186
|
+
throw new CrudHttpError(400, { error: context.translate("warranty_claims.errors.attachmentNotLinked", "The attachment is not linked to this claim.") });
|
|
186
187
|
}
|
|
187
188
|
}
|
|
188
189
|
function mergeAssessmentPayload(current, key, value) {
|
|
@@ -210,12 +211,13 @@ async function persistAssessmentPayload(context, line, key, value, updatedAt) {
|
|
|
210
211
|
);
|
|
211
212
|
}
|
|
212
213
|
async function POST(req) {
|
|
214
|
+
const { translate } = await resolveTranslations();
|
|
213
215
|
try {
|
|
214
|
-
const context = await resolveAssessContext(req);
|
|
216
|
+
const context = await resolveAssessContext(req, translate);
|
|
215
217
|
const payload = toRecord(await readJsonSafe(req, {}));
|
|
216
218
|
const parsed = toAssessInput(payload, context);
|
|
217
219
|
if (parsed.kind === "damage" && !parsed.lineId) {
|
|
218
|
-
throw new CrudHttpError(400, { error: "warranty_claims.errors.invalidInput" });
|
|
220
|
+
throw new CrudHttpError(400, { error: translate("warranty_claims.errors.invalidInput", "Invalid input") });
|
|
219
221
|
}
|
|
220
222
|
const guarded = parsed.lineId ? await runGuard(req, context, parsed) : null;
|
|
221
223
|
if (guarded && !guarded.ok) {
|
|
@@ -225,9 +227,9 @@ async function POST(req) {
|
|
|
225
227
|
const scope = { tenantId: context.tenantId, organizationId: context.organizationId };
|
|
226
228
|
if (input.kind === "damage") {
|
|
227
229
|
if (!input.lineId) {
|
|
228
|
-
throw new CrudHttpError(400, { error: "warranty_claims.errors.invalidInput" });
|
|
230
|
+
throw new CrudHttpError(400, { error: translate("warranty_claims.errors.invalidInput", "Invalid input") });
|
|
229
231
|
}
|
|
230
|
-
const line2 = await loadScopedLine(context.em, scope, input.claimId, input.lineId);
|
|
232
|
+
const line2 = await loadScopedLine(context.em, scope, input.claimId, input.lineId, translate);
|
|
231
233
|
await verifyAttachmentLinkedToTarget(context, {
|
|
232
234
|
attachmentId: input.attachmentId,
|
|
233
235
|
claimId: input.claimId,
|
|
@@ -246,8 +248,8 @@ async function POST(req) {
|
|
|
246
248
|
await guarded?.runAfterSuccess();
|
|
247
249
|
return NextResponse.json({ status: "ok", assessment });
|
|
248
250
|
}
|
|
249
|
-
await requireScopedClaim(context.em, input.claimId, scope);
|
|
250
|
-
const line = input.lineId ? await loadScopedLine(context.em, scope, input.claimId, input.lineId) : null;
|
|
251
|
+
await requireScopedClaim(context.em, input.claimId, scope, {}, translate("warranty_claims.errors.notFound", "Claim not found."));
|
|
252
|
+
const line = input.lineId ? await loadScopedLine(context.em, scope, input.claimId, input.lineId, translate) : null;
|
|
251
253
|
await verifyAttachmentLinkedToTarget(context, {
|
|
252
254
|
attachmentId: input.attachmentId,
|
|
253
255
|
claimId: input.claimId,
|
|
@@ -278,10 +280,10 @@ async function POST(req) {
|
|
|
278
280
|
return NextResponse.json({ status: "aiUnavailable" });
|
|
279
281
|
}
|
|
280
282
|
if (err instanceof z.ZodError) {
|
|
281
|
-
return NextResponse.json({ error: "warranty_claims.errors.invalidInput" }, { status: 400 });
|
|
283
|
+
return NextResponse.json({ error: translate("warranty_claims.errors.invalidInput", "Invalid input") }, { status: 400 });
|
|
282
284
|
}
|
|
283
285
|
logger.error("warranty_claims.ai.assess.post failed", { err });
|
|
284
|
-
return NextResponse.json({ error: "warranty_claims.errors.save_failed" }, { status: 500 });
|
|
286
|
+
return NextResponse.json({ error: translate("warranty_claims.errors.save_failed", "Failed to save warranty claim.") }, { status: 500 });
|
|
285
287
|
}
|
|
286
288
|
}
|
|
287
289
|
const openApi = {
|