|
| 1 | +import { env, createExecutionContext, waitOnExecutionContext } from 'cloudflare:test'; |
| 2 | +import { describe, it, expect, vi } from 'vitest'; |
| 3 | +import { |
| 4 | + postMessageAsUser, |
| 5 | + type PostMessageAsUserParams, |
| 6 | + type PostMessageAsUserResult, |
| 7 | +} from '../services/post-message-as-user'; |
| 8 | + |
| 9 | +/** Map of userId → set of sandbox IDs they own. */ |
| 10 | +const ownershipMap = new Map<string, Set<string>>(); |
| 11 | + |
| 12 | +vi.mock('../services/sandbox-ownership', () => ({ |
| 13 | + userOwnsSandbox: async (_env: Env, userId: string, sandboxId: string) => |
| 14 | + ownershipMap.get(userId)?.has(sandboxId) ?? false, |
| 15 | +})); |
| 16 | + |
| 17 | +vi.mock('../services/user-lookup', () => ({ |
| 18 | + resolveUserDisplayInfo: async () => new Map(), |
| 19 | +})); |
| 20 | + |
| 21 | +function grantSandbox(userId: string, sandboxId: string) { |
| 22 | + if (!ownershipMap.has(userId)) ownershipMap.set(userId, new Set()); |
| 23 | + ownershipMap.get(userId)!.add(sandboxId); |
| 24 | +} |
| 25 | + |
| 26 | +function makeEnv(): Env { |
| 27 | + return { |
| 28 | + ...env, |
| 29 | + EVENT_SERVICE: { |
| 30 | + fetch: env.EVENT_SERVICE.fetch.bind(env.EVENT_SERVICE), |
| 31 | + connect: env.EVENT_SERVICE.connect.bind(env.EVENT_SERVICE), |
| 32 | + pushEvent: async () => true, |
| 33 | + }, |
| 34 | + } satisfies Env; |
| 35 | +} |
| 36 | + |
| 37 | +// Build a real ExecutionContext, run the callee, then drain pending |
| 38 | +// waitUntil work before asserting so isolated-storage cleanup between tests |
| 39 | +// does not race. Mirrors the pattern in helpers.ts. |
| 40 | +async function runPost( |
| 41 | + testEnv: Env, |
| 42 | + params: PostMessageAsUserParams |
| 43 | +): Promise<PostMessageAsUserResult> { |
| 44 | + const ctx = createExecutionContext(); |
| 45 | + const result = await postMessageAsUser(testEnv, { waitUntil: p => ctx.waitUntil(p) }, params); |
| 46 | + await waitOnExecutionContext(ctx); |
| 47 | + return result; |
| 48 | +} |
| 49 | + |
| 50 | +describe('postMessageAsUser', () => { |
| 51 | + it('auto-creates a conversation on first delivery and posts the message', async () => { |
| 52 | + const userId = `user-${crypto.randomUUID()}`; |
| 53 | + const sandboxId = `sandbox-${crypto.randomUUID()}`; |
| 54 | + grantSandbox(userId, sandboxId); |
| 55 | + |
| 56 | + const result = await runPost(makeEnv(), { |
| 57 | + userId, |
| 58 | + sandboxId, |
| 59 | + message: 'webhook payload arrived', |
| 60 | + source: 'webhook', |
| 61 | + autoCreateConversation: true, |
| 62 | + }); |
| 63 | + |
| 64 | + expect(result.ok).toBe(true); |
| 65 | + if (!result.ok) return; |
| 66 | + expect(result.conversationCreated).toBe(true); |
| 67 | + expect(result.conversationId).toBeTruthy(); |
| 68 | + expect(result.messageId).toBeTruthy(); |
| 69 | + }); |
| 70 | + |
| 71 | + it('reuses the existing conversation on subsequent deliveries', async () => { |
| 72 | + const userId = `user-${crypto.randomUUID()}`; |
| 73 | + const sandboxId = `sandbox-${crypto.randomUUID()}`; |
| 74 | + grantSandbox(userId, sandboxId); |
| 75 | + const testEnv = makeEnv(); |
| 76 | + |
| 77 | + const first = await runPost(testEnv, { |
| 78 | + userId, |
| 79 | + sandboxId, |
| 80 | + message: 'first', |
| 81 | + source: 'webhook', |
| 82 | + }); |
| 83 | + expect(first.ok).toBe(true); |
| 84 | + if (!first.ok) return; |
| 85 | + expect(first.conversationCreated).toBe(true); |
| 86 | + |
| 87 | + const second = await runPost(testEnv, { |
| 88 | + userId, |
| 89 | + sandboxId, |
| 90 | + message: 'second', |
| 91 | + source: 'webhook', |
| 92 | + }); |
| 93 | + expect(second.ok).toBe(true); |
| 94 | + if (!second.ok) return; |
| 95 | + expect(second.conversationCreated).toBe(false); |
| 96 | + expect(second.conversationId).toBe(first.conversationId); |
| 97 | + }); |
| 98 | + |
| 99 | + it('returns no_conversation when autoCreateConversation is false and none exists', async () => { |
| 100 | + const userId = `user-${crypto.randomUUID()}`; |
| 101 | + const sandboxId = `sandbox-${crypto.randomUUID()}`; |
| 102 | + grantSandbox(userId, sandboxId); |
| 103 | + |
| 104 | + const result = await runPost(makeEnv(), { |
| 105 | + userId, |
| 106 | + sandboxId, |
| 107 | + message: 'should fail', |
| 108 | + source: 'onboarding-warmup', |
| 109 | + autoCreateConversation: false, |
| 110 | + }); |
| 111 | + |
| 112 | + expect(result.ok).toBe(false); |
| 113 | + if (result.ok) return; |
| 114 | + expect(result.code).toBe('no_conversation'); |
| 115 | + }); |
| 116 | + |
| 117 | + it('surfaces forbidden when the user does not own the sandbox', async () => { |
| 118 | + const userId = `user-${crypto.randomUUID()}`; |
| 119 | + const sandboxId = `sandbox-${crypto.randomUUID()}`; |
| 120 | + // intentionally NOT granting ownership |
| 121 | + |
| 122 | + const result = await runPost(makeEnv(), { |
| 123 | + userId, |
| 124 | + sandboxId, |
| 125 | + message: 'should be forbidden', |
| 126 | + source: 'webhook', |
| 127 | + autoCreateConversation: true, |
| 128 | + }); |
| 129 | + |
| 130 | + expect(result.ok).toBe(false); |
| 131 | + if (result.ok) return; |
| 132 | + expect(result.code).toBe('forbidden'); |
| 133 | + }); |
| 134 | + |
| 135 | + it('rejects forbidden even when a stale conversation already exists', async () => { |
| 136 | + const userId = `user-${crypto.randomUUID()}`; |
| 137 | + const sandboxId = `sandbox-${crypto.randomUUID()}`; |
| 138 | + const testEnv = makeEnv(); |
| 139 | + |
| 140 | + // Seed: grant ownership long enough to create a conversation. |
| 141 | + grantSandbox(userId, sandboxId); |
| 142 | + const seed = await runPost(testEnv, { |
| 143 | + userId, |
| 144 | + sandboxId, |
| 145 | + message: 'seed message', |
| 146 | + source: 'webhook', |
| 147 | + }); |
| 148 | + expect(seed.ok).toBe(true); |
| 149 | + |
| 150 | + // Revoke ownership (simulates instance destroyed / reassigned). The |
| 151 | + // conversation still exists in MEMBERSHIP_DO, so the existing-conversation |
| 152 | + // path runs without the create-time ownership check. |
| 153 | + ownershipMap.get(userId)?.delete(sandboxId); |
| 154 | + |
| 155 | + const result = await runPost(testEnv, { |
| 156 | + userId, |
| 157 | + sandboxId, |
| 158 | + message: 'should now be forbidden', |
| 159 | + source: 'webhook', |
| 160 | + }); |
| 161 | + |
| 162 | + expect(result.ok).toBe(false); |
| 163 | + if (result.ok) return; |
| 164 | + expect(result.code).toBe('forbidden'); |
| 165 | + }); |
| 166 | + |
| 167 | + it('rejects empty messages with invalid_request before any side effects', async () => { |
| 168 | + const userId = `user-${crypto.randomUUID()}`; |
| 169 | + const sandboxId = `sandbox-${crypto.randomUUID()}`; |
| 170 | + grantSandbox(userId, sandboxId); |
| 171 | + |
| 172 | + const result = await runPost(makeEnv(), { |
| 173 | + userId, |
| 174 | + sandboxId, |
| 175 | + message: ' ', |
| 176 | + source: 'webhook', |
| 177 | + autoCreateConversation: true, |
| 178 | + }); |
| 179 | + |
| 180 | + expect(result.ok).toBe(false); |
| 181 | + if (result.ok) return; |
| 182 | + expect(result.code).toBe('invalid_request'); |
| 183 | + }); |
| 184 | + |
| 185 | + it('rejects messages exceeding the chat content limit with invalid_request', async () => { |
| 186 | + const userId = `user-${crypto.randomUUID()}`; |
| 187 | + const sandboxId = `sandbox-${crypto.randomUUID()}`; |
| 188 | + grantSandbox(userId, sandboxId); |
| 189 | + |
| 190 | + const result = await runPost(makeEnv(), { |
| 191 | + userId, |
| 192 | + sandboxId, |
| 193 | + // Larger than MESSAGE_TEXT_MAX_CHARS (8000) so the public schema rejects it. |
| 194 | + message: 'x'.repeat(9000), |
| 195 | + source: 'webhook', |
| 196 | + autoCreateConversation: true, |
| 197 | + }); |
| 198 | + |
| 199 | + expect(result.ok).toBe(false); |
| 200 | + if (result.ok) return; |
| 201 | + expect(result.code).toBe('invalid_request'); |
| 202 | + }); |
| 203 | + |
| 204 | + it('accepts correlation metadata without throwing', async () => { |
| 205 | + const userId = `user-${crypto.randomUUID()}`; |
| 206 | + const sandboxId = `sandbox-${crypto.randomUUID()}`; |
| 207 | + grantSandbox(userId, sandboxId); |
| 208 | + |
| 209 | + const result = await runPost(makeEnv(), { |
| 210 | + userId, |
| 211 | + sandboxId, |
| 212 | + message: 'with correlation', |
| 213 | + source: 'webhook', |
| 214 | + correlation: { triggerId: 'trig-1', webhookRequestId: 'req-1' }, |
| 215 | + }); |
| 216 | + |
| 217 | + expect(result.ok).toBe(true); |
| 218 | + }); |
| 219 | +}); |
0 commit comments