-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathgoogle.test.ts
More file actions
1155 lines (1032 loc) · 41.5 KB
/
Copy pathgoogle.test.ts
File metadata and controls
1155 lines (1032 loc) · 41.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { beforeEach, describe, expect, it } from "vitest";
import { Hono } from "@emulators/core";
import { decodeJwt, createLocalJWKSet, jwtVerify } from "jose";
import {
Store,
WebhookDispatcher,
authMiddleware,
createApiErrorHandler,
createErrorHandler,
type TokenMap,
} from "@emulators/core";
import { googlePlugin, seedFromConfig } from "../index.js";
import { buildRawMessage } from "../helpers.js";
const base = "http://localhost:4000";
function createTestApp() {
const store = new Store();
const webhooks = new WebhookDispatcher();
const tokenMap: TokenMap = new Map();
tokenMap.set("test-token", {
login: "testuser@example.com",
id: 1,
scopes: ["openid", "email", "profile"],
});
const app = new Hono();
app.onError(createApiErrorHandler());
app.use("*", createErrorHandler());
app.use("*", authMiddleware(tokenMap));
googlePlugin.register(app as any, store, webhooks, base, tokenMap);
googlePlugin.seed?.(store, base);
seedFromConfig(store, base, {
users: [
{ email: "testuser@example.com", name: "Test User" },
{ email: "consumer@gmail.com", name: "Consumer User" },
{ email: "workspaceuser@example.com", name: "Workspace User", hd: "override.io" },
],
oauth_clients: [
{
client_id: "emu_google_client_id",
client_secret: "emu_google_client_secret",
name: "Inbox Zero",
redirect_uris: ["http://localhost:3000/api/auth/callback/google"],
},
],
labels: [
{
id: "Label_ops",
user_email: "testuser@example.com",
name: "Ops/Review",
color_background: "#DDEEFF",
color_text: "#111111",
},
],
messages: [
{
id: "msg_support_1",
thread_id: "thread_support",
user_email: "testuser@example.com",
from: "Support <support@example.com>",
to: "testuser@example.com",
subject: "Your support ticket has been updated",
body_text: "We have an update on your ticket.",
label_ids: ["INBOX", "UNREAD", "Label_ops"],
date: "2025-01-04T10:00:00.000Z",
},
{
id: "msg_support_2",
thread_id: "thread_support",
user_email: "testuser@example.com",
from: "testuser@example.com",
to: "Support <support@example.com>",
subject: "Re: Your support ticket has been updated",
body_text: "Thanks for the update.",
label_ids: ["SENT"],
date: "2025-01-04T11:00:00.000Z",
references: "<msg_support_1@emulate.google.local>",
in_reply_to: "<msg_support_1@emulate.google.local>",
},
{
id: "msg_invoice",
thread_id: "thread_billing",
user_email: "testuser@example.com",
from: "Billing <billing@example.com>",
to: "testuser@example.com",
subject: "Invoice ready for review",
body_text: "Your January invoice is ready to review.",
label_ids: ["INBOX", "CATEGORY_UPDATES"],
date: "2025-01-03T10:00:00.000Z",
},
{
id: "msg_release",
thread_id: "thread_release",
user_email: "testuser@example.com",
from: "Releases <release@example.com>",
to: "testuser@example.com",
subject: "Release notes available",
body_html: "<p>The latest release is ready.</p>",
label_ids: ["INBOX", "UNREAD", "CATEGORY_UPDATES"],
date: "2025-01-02T10:00:00.000Z",
},
{
id: "msg_draft",
thread_id: "thread_draft",
user_email: "testuser@example.com",
from: "testuser@example.com",
to: "partner@example.com",
subject: "Draft follow-up",
body_text: "This draft should only appear when not filtered.",
label_ids: ["DRAFT"],
date: "2025-01-01T10:00:00.000Z",
},
],
calendars: [
{
id: "primary",
user_email: "testuser@example.com",
summary: "testuser@example.com",
primary: true,
selected: true,
time_zone: "UTC",
},
{
id: "cal_team",
user_email: "testuser@example.com",
summary: "Team Calendar",
description: "Shared engineering schedule",
selected: true,
time_zone: "UTC",
},
],
calendar_events: [
{
id: "evt_kickoff",
user_email: "testuser@example.com",
calendar_id: "primary",
summary: "Project Kickoff",
description: "Align on the Q1 plan.",
start_date_time: "2025-01-10T09:00:00.000Z",
end_date_time: "2025-01-10T09:30:00.000Z",
attendees: [
{ email: "testuser@example.com", display_name: "Test User" },
{ email: "teammate@example.com", display_name: "Teammate" },
],
conference_entry_points: [
{
entry_point_type: "video",
uri: "https://meet.google.com/project-kickoff",
label: "Google Meet",
},
],
hangout_link: "https://meet.google.com/project-kickoff",
},
],
drive_items: [
{
id: "drv_docs",
user_email: "testuser@example.com",
name: "Docs",
mime_type: "application/vnd.google-apps.folder",
parent_ids: ["root"],
},
{
id: "drv_handbook",
user_email: "testuser@example.com",
name: "Handbook.pdf",
mime_type: "application/pdf",
parent_ids: ["drv_docs"],
data: "pdf-handbook-data",
},
],
});
return { app };
}
function authHeaders(extra?: Record<string, string>): Record<string, string> {
return { Authorization: "Bearer test-token", ...extra };
}
async function jsonRequest(
app: Hono,
path: string,
init?: Omit<RequestInit, "body" | "headers"> & { body?: unknown; headers?: Record<string, string> },
) {
const headers = authHeaders({ "Content-Type": "application/json", ...(init?.headers ?? {}) });
const body =
init?.body === undefined || typeof init.body === "string"
? (init?.body as string | undefined)
: JSON.stringify(init.body);
return app.request(`${base}${path}`, {
...init,
headers,
body,
});
}
async function formRequest(app: Hono, path: string, body: Record<string, string>, init?: RequestInit) {
return app.request(`${base}${path}`, {
...init,
method: init?.method ?? "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
...(init?.headers ?? {}),
},
body: new URLSearchParams(body).toString(),
});
}
describe("Google plugin integration", () => {
let app: Hono;
beforeEach(() => {
app = createTestApp().app;
});
it("returns user info for a valid token", async () => {
const res = await app.request(`${base}/oauth2/v2/userinfo`, { headers: authHeaders() });
expect(res.status).toBe(200);
const body = (await res.json()) as {
sub: string;
email: string;
email_verified: boolean;
name: string;
};
expect(body.sub).toBeDefined();
expect(body.email).toBe("testuser@example.com");
expect(body.email_verified).toBe(true);
expect(body.name).toBe("Test User");
});
it("lists paginated messages with Gmail-style filters", async () => {
const res = await app.request(
`${base}/gmail/v1/users/me/messages?maxResults=2&q=${encodeURIComponent("-label:DRAFT in:inbox")}`,
{ headers: authHeaders() },
);
expect(res.status).toBe(200);
const body = (await res.json()) as {
messages: Array<{ id: string; threadId: string }>;
nextPageToken?: string;
resultSizeEstimate: number;
};
expect(body.messages).toEqual([
{ id: "msg_support_1", threadId: "thread_support" },
{ id: "msg_invoice", threadId: "thread_billing" },
]);
expect(body.nextPageToken).toBe("2");
expect(body.resultSizeEstimate).toBe(3);
});
it("returns message payloads in metadata and raw formats", async () => {
const metadataRes = await app.request(
`${base}/gmail/v1/users/me/messages/msg_release?format=metadata&metadataHeaders=Subject&metadataHeaders=From`,
{ headers: authHeaders() },
);
expect(metadataRes.status).toBe(200);
const metadataBody = (await metadataRes.json()) as {
payload: { headers: Array<{ name: string; value: string }>; body: { size: number } };
};
expect(metadataBody.payload.headers).toEqual([
{ name: "From", value: "Releases <release@example.com>" },
{ name: "Subject", value: "Release notes available" },
]);
expect(metadataBody.payload.body.size).toBe(0);
const rawRes = await app.request(`${base}/gmail/v1/users/me/messages/msg_release?format=raw`, {
headers: authHeaders(),
});
const rawBody = (await rawRes.json()) as { raw?: string };
expect(rawBody.raw).toBeDefined();
});
it("returns attachment parts and serves attachment bodies", async () => {
const raw = buildRawMessage({
from: "Contracts <contracts@example.com>",
to: "testuser@example.com",
subject: "Signed contract attached",
body_text: "Please review the attached contract.",
body_html: "<p>Please review the attached contract.</p>",
attachments: [
{
filename: "contract.pdf",
mime_type: "application/pdf",
content: "fake-pdf-data",
},
],
});
const importRes = await jsonRequest(app, "/gmail/v1/users/me/messages/import", {
method: "POST",
body: {
raw,
labelIds: ["INBOX"],
},
});
expect(importRes.status).toBe(200);
const imported = (await importRes.json()) as { id: string };
const messageRes = await app.request(`${base}/gmail/v1/users/me/messages/${imported.id}`, {
headers: authHeaders(),
});
expect(messageRes.status).toBe(200);
const message = (await messageRes.json()) as {
payload: {
mimeType: string;
parts?: Array<{
filename?: string;
body?: { attachmentId?: string; size?: number };
}>;
};
};
expect(message.payload.mimeType).toBe("multipart/mixed");
const attachmentPart = message.payload.parts?.find((part) => part.filename === "contract.pdf");
expect(attachmentPart?.body?.attachmentId).toBeDefined();
expect(attachmentPart?.body?.size).toBe(Buffer.byteLength("fake-pdf-data", "utf8"));
const attachmentRes = await app.request(
`${base}/gmail/v1/users/me/messages/${imported.id}/attachments/${attachmentPart!.body!.attachmentId}`,
{ headers: authHeaders() },
);
expect(attachmentRes.status).toBe(200);
const attachment = (await attachmentRes.json()) as { data: string; size: number };
expect(Buffer.from(attachment.data, "base64url").toString("utf8")).toBe("fake-pdf-data");
expect(attachment.size).toBe(Buffer.byteLength("fake-pdf-data", "utf8"));
const listRes = await app.request(`${base}/gmail/v1/users/me/messages?q=${encodeURIComponent("has:attachment")}`, {
headers: authHeaders(),
});
expect(listRes.status).toBe(200);
const listBody = (await listRes.json()) as {
messages: Array<{ id: string }>;
};
expect(listBody.messages.some((entry) => entry.id === imported.id)).toBe(true);
});
it("creates, updates, lists, sends, and deletes drafts", async () => {
const createRaw = buildRawMessage({
from: "testuser@example.com",
to: "partner@example.com",
subject: "Draft review",
body_html: "<p>First draft body</p>",
});
const createRes = await jsonRequest(app, "/gmail/v1/users/me/drafts", {
method: "POST",
body: {
message: {
threadId: "thread_support",
raw: createRaw,
},
},
});
expect(createRes.status).toBe(200);
const created = (await createRes.json()) as {
id: string;
message: {
id: string;
threadId: string;
labelIds: string[];
payload: { headers: Array<{ name: string; value: string }> };
};
};
expect(created.id).toMatch(/^r-\d+$/);
expect(created.message.threadId).toBe("thread_support");
expect(created.message.labelIds).toContain("DRAFT");
expect(created.message.payload.headers.find((header) => header.name === "Subject")?.value).toBe("Draft review");
const listRes = await app.request(`${base}/gmail/v1/users/me/drafts?maxResults=20`, {
headers: authHeaders(),
});
expect(listRes.status).toBe(200);
const listBody = (await listRes.json()) as {
drafts: Array<{ id: string; message?: { id: string; threadId: string } }>;
};
expect(listBody.drafts.some((draft) => draft.id === created.id && draft.message?.id === created.message.id)).toBe(
true,
);
const getRes = await app.request(`${base}/gmail/v1/users/me/drafts/${created.id}?format=full`, {
headers: authHeaders(),
});
expect(getRes.status).toBe(200);
const updateRaw = buildRawMessage({
from: "testuser@example.com",
to: "partner@example.com",
subject: "Draft review updated",
body_html: "<p>Updated draft body</p>",
});
const updateRes = await jsonRequest(app, `/gmail/v1/users/me/drafts/${created.id}`, {
method: "PUT",
body: {
message: {
raw: updateRaw,
},
},
});
expect(updateRes.status).toBe(200);
const updated = (await updateRes.json()) as {
id: string;
message: { id: string; labelIds: string[]; payload: { headers: Array<{ name: string; value: string }> } };
};
expect(updated.id).toBe(created.id);
expect(updated.message.id).toBe(created.message.id);
expect(updated.message.labelIds).toContain("DRAFT");
expect(updated.message.payload.headers.find((header) => header.name === "Subject")?.value).toBe(
"Draft review updated",
);
const sendRes = await jsonRequest(app, "/gmail/v1/users/me/drafts/send", {
method: "POST",
body: { id: created.id },
});
expect(sendRes.status).toBe(200);
const sent = (await sendRes.json()) as { id: string; threadId: string; labelIds: string[] };
expect(sent.id).toBe(created.message.id);
expect(sent.threadId).toBe("thread_support");
expect(sent.labelIds).toContain("SENT");
expect(sent.labelIds).not.toContain("DRAFT");
const missingDraftRes = await app.request(`${base}/gmail/v1/users/me/drafts/${created.id}`, {
headers: authHeaders(),
});
expect(missingDraftRes.status).toBe(404);
const deleteRaw = buildRawMessage({
from: "testuser@example.com",
to: "delete@example.com",
subject: "Delete me",
body_text: "Disposable draft",
});
const secondCreateRes = await jsonRequest(app, "/gmail/v1/users/me/drafts", {
method: "POST",
body: {
message: { raw: deleteRaw },
},
});
const secondDraft = (await secondCreateRes.json()) as { id: string; message: { id: string } };
const deleteRes = await app.request(`${base}/gmail/v1/users/me/drafts/${secondDraft.id}`, {
method: "DELETE",
headers: authHeaders(),
});
expect(deleteRes.status).toBe(204);
const deletedMessageRes = await app.request(`${base}/gmail/v1/users/me/messages/${secondDraft.message.id}`, {
headers: authHeaders(),
});
expect(deletedMessageRes.status).toBe(404);
});
it("tracks history entries after watch registration", async () => {
const watchRes = await jsonRequest(app, "/gmail/v1/users/me/watch", {
method: "POST",
body: {
topicName: "projects/emulate-local/topics/gmail",
labelIds: ["INBOX", "SENT"],
labelFilterBehavior: "include",
},
});
expect(watchRes.status).toBe(200);
const watch = (await watchRes.json()) as { historyId: string; expiration: string };
expect(BigInt(watch.historyId)).toBeGreaterThan(0n);
expect(BigInt(watch.expiration)).toBeGreaterThan(BigInt(Date.now()));
const importRaw = buildRawMessage({
from: "Alerts <alerts@example.com>",
to: "testuser@example.com",
subject: "Deployment notification",
body_text: "A deployment has finished successfully.",
});
const importRes = await jsonRequest(app, "/gmail/v1/users/me/messages/import", {
method: "POST",
body: {
raw: importRaw,
labelIds: ["INBOX", "UNREAD"],
},
});
expect(importRes.status).toBe(200);
const imported = (await importRes.json()) as { id: string };
const modifyRes = await jsonRequest(app, `/gmail/v1/users/me/messages/${imported.id}/modify`, {
method: "POST",
body: {
addLabelIds: ["STARRED"],
removeLabelIds: ["UNREAD"],
},
});
expect(modifyRes.status).toBe(200);
const historyRes = await app.request(
`${base}/gmail/v1/users/me/history?startHistoryId=${watch.historyId}&historyTypes=messageAdded&historyTypes=labelAdded&historyTypes=labelRemoved`,
{ headers: authHeaders() },
);
expect(historyRes.status).toBe(200);
const historyBody = (await historyRes.json()) as {
historyId: string;
history: Array<{
id: string;
messagesAdded?: Array<{ message: { id: string; threadId: string } }>;
labelsAdded?: Array<{ message: { id: string; threadId: string }; labelIds: string[] }>;
labelsRemoved?: Array<{ message: { id: string; threadId: string }; labelIds: string[] }>;
}>;
};
expect(BigInt(historyBody.historyId)).toBeGreaterThan(BigInt(watch.historyId));
expect(
historyBody.history.some((entry) => entry.messagesAdded?.some((item) => item.message.id === imported.id)),
).toBe(true);
expect(
historyBody.history.some((entry) =>
entry.labelsAdded?.some((item) => item.message.id === imported.id && item.labelIds.includes("STARRED")),
),
).toBe(true);
expect(
historyBody.history.some((entry) =>
entry.labelsRemoved?.some((item) => item.message.id === imported.id && item.labelIds.includes("UNREAD")),
),
).toBe(true);
const stopRes = await app.request(`${base}/gmail/v1/users/me/stop`, {
method: "POST",
headers: authHeaders(),
});
expect(stopRes.status).toBe(200);
});
it("lists settings resources and applies Gmail filters to matching messages", async () => {
const sendAsRes = await app.request(`${base}/gmail/v1/users/me/settings/sendAs`, {
headers: authHeaders(),
});
expect(sendAsRes.status).toBe(200);
const sendAsBody = (await sendAsRes.json()) as {
sendAs: Array<{ sendAsEmail: string; displayName?: string; isDefault: boolean }>;
};
expect(sendAsBody.sendAs).toEqual(
expect.arrayContaining([
expect.objectContaining({
sendAsEmail: "testuser@example.com",
displayName: "Test User",
isDefault: true,
}),
]),
);
const forwardingRes = await app.request(`${base}/gmail/v1/users/me/settings/forwardingAddresses`, {
headers: authHeaders(),
});
expect(forwardingRes.status).toBe(200);
const forwardingBody = (await forwardingRes.json()) as {
forwardingAddresses: Array<{ forwardingEmail: string }>;
};
expect(forwardingBody.forwardingAddresses).toEqual([]);
const createFilterRes = await jsonRequest(app, "/gmail/v1/users/me/settings/filters", {
method: "POST",
body: {
criteria: { from: "billing@example.com" },
action: { addLabelIds: ["Label_ops"], removeLabelIds: ["INBOX"] },
},
});
expect(createFilterRes.status).toBe(200);
const filter = (await createFilterRes.json()) as {
id: string;
criteria: { from: string };
action: { addLabelIds: string[]; removeLabelIds: string[] };
};
expect(filter.criteria.from).toBe("billing@example.com");
expect(filter.action.addLabelIds).toContain("Label_ops");
expect(filter.action.removeLabelIds).toContain("INBOX");
const duplicateFilterRes = await jsonRequest(app, "/gmail/v1/users/me/settings/filters", {
method: "POST",
body: {
criteria: { from: "billing@example.com" },
action: { addLabelIds: ["Label_ops"], removeLabelIds: ["INBOX"] },
},
});
expect(duplicateFilterRes.status).toBe(400);
const duplicateError = (await duplicateFilterRes.json()) as { error: { message: string } };
expect(duplicateError.error.message).toBe("Filter already exists");
const listFiltersRes = await app.request(`${base}/gmail/v1/users/me/settings/filters`, {
headers: authHeaders(),
});
expect(listFiltersRes.status).toBe(200);
const listedFilters = (await listFiltersRes.json()) as {
filter: Array<{ id: string }>;
};
expect(listedFilters.filter).toEqual(expect.arrayContaining([expect.objectContaining({ id: filter.id })]));
const filteredRaw = buildRawMessage({
from: "Billing <billing@example.com>",
to: "testuser@example.com",
subject: "Filtered invoice",
body_text: "This should be relabeled by the emulator filter.",
});
const filteredImportRes = await jsonRequest(app, "/gmail/v1/users/me/messages/import", {
method: "POST",
body: {
raw: filteredRaw,
labelIds: ["INBOX", "UNREAD"],
},
});
expect(filteredImportRes.status).toBe(200);
const filteredMessage = (await filteredImportRes.json()) as { id: string };
const filteredMessageRes = await app.request(`${base}/gmail/v1/users/me/messages/${filteredMessage.id}`, {
headers: authHeaders(),
});
expect(filteredMessageRes.status).toBe(200);
const filteredBody = (await filteredMessageRes.json()) as { labelIds: string[] };
expect(filteredBody.labelIds).toContain("Label_ops");
expect(filteredBody.labelIds).toContain("UNREAD");
expect(filteredBody.labelIds).not.toContain("INBOX");
const deleteFilterRes = await app.request(`${base}/gmail/v1/users/me/settings/filters/${filter.id}`, {
method: "DELETE",
headers: authHeaders(),
});
expect(deleteFilterRes.status).toBe(204);
const afterDeleteRes = await app.request(`${base}/gmail/v1/users/me/settings/filters`, {
headers: authHeaders(),
});
expect(afterDeleteRes.status).toBe(200);
const afterDelete = (await afterDeleteRes.json()) as {
filter: Array<{ id: string }>;
};
expect(afterDelete.filter).toEqual([]);
});
it("creates sent messages and appends them to existing threads", async () => {
const raw = buildRawMessage({
from: "testuser@example.com",
to: "Support <support@example.com>",
subject: "Re: Your support ticket has been updated",
body_text: "Closing the loop from the emulator.",
message_id: "<outbound-1@example.com>",
in_reply_to: "<msg_support_1@emulate.google.local>",
references: "<msg_support_1@emulate.google.local>",
});
const sendRes = await jsonRequest(app, "/gmail/v1/users/me/messages/send", {
method: "POST",
body: {
threadId: "thread_support",
raw,
},
});
expect(sendRes.status).toBe(200);
const sent = (await sendRes.json()) as {
id: string;
threadId: string;
labelIds: string[];
};
expect(sent.threadId).toBe("thread_support");
expect(sent.labelIds).toContain("SENT");
const threadRes = await app.request(`${base}/gmail/v1/users/me/threads/thread_support`, {
headers: authHeaders(),
});
expect(threadRes.status).toBe(200);
const thread = (await threadRes.json()) as {
messages: Array<{ id: string }>;
};
expect(thread.messages).toHaveLength(3);
});
it("modifies, batches, trashes, and deletes messages", async () => {
const labelRes = await jsonRequest(app, "/gmail/v1/users/me/labels", {
method: "POST",
body: { name: "Projects/Alpha" },
});
const label = (await labelRes.json()) as { id: string };
const modifyRes = await jsonRequest(app, "/gmail/v1/users/me/messages/msg_invoice/modify", {
method: "POST",
body: { addLabelIds: [label.id], removeLabelIds: ["INBOX"] },
});
expect(modifyRes.status).toBe(200);
const modified = (await modifyRes.json()) as { labelIds: string[] };
expect(modified.labelIds).toContain(label.id);
expect(modified.labelIds).not.toContain("INBOX");
const batchModifyRes = await jsonRequest(app, "/gmail/v1/users/me/messages/batchModify", {
method: "POST",
body: { ids: ["msg_support_1", "msg_release"], addLabelIds: ["STARRED"], removeLabelIds: ["UNREAD"] },
});
expect(batchModifyRes.status).toBe(204);
const supportRes = await app.request(`${base}/gmail/v1/users/me/messages/msg_support_1`, {
headers: authHeaders(),
});
const support = (await supportRes.json()) as { labelIds: string[] };
expect(support.labelIds).toContain("STARRED");
expect(support.labelIds).not.toContain("UNREAD");
const trashRes = await jsonRequest(app, "/gmail/v1/users/me/messages/msg_release/trash", {
method: "POST",
});
const trashed = (await trashRes.json()) as { labelIds: string[] };
expect(trashed.labelIds).toContain("TRASH");
expect(trashed.labelIds).not.toContain("INBOX");
const untrashRes = await jsonRequest(app, "/gmail/v1/users/me/messages/msg_release/untrash", {
method: "POST",
});
const untrashed = (await untrashRes.json()) as { labelIds: string[] };
expect(untrashed.labelIds).toContain("INBOX");
expect(untrashed.labelIds).not.toContain("TRASH");
const batchDeleteRes = await jsonRequest(app, "/gmail/v1/users/me/messages/batchDelete", {
method: "POST",
body: { ids: ["msg_draft"] },
});
expect(batchDeleteRes.status).toBe(204);
const deletedRes = await app.request(`${base}/gmail/v1/users/me/messages/msg_draft`, {
headers: authHeaders(),
});
expect(deletedRes.status).toBe(404);
});
it("lists, gets, and mutates threads", async () => {
const listRes = await app.request(
`${base}/gmail/v1/users/me/threads?maxResults=10&q=${encodeURIComponent("-label:DRAFT")}`,
{ headers: authHeaders() },
);
expect(listRes.status).toBe(200);
const listBody = (await listRes.json()) as {
threads: Array<{ id: string; snippet: string; historyId: string }>;
};
expect(listBody.threads.map((thread) => thread.id)).toEqual(["thread_support", "thread_billing", "thread_release"]);
const modifyRes = await jsonRequest(app, "/gmail/v1/users/me/threads/thread_support/modify", {
method: "POST",
body: { addLabelIds: ["IMPORTANT"], removeLabelIds: ["UNREAD"] },
});
expect(modifyRes.status).toBe(200);
const thread = (await modifyRes.json()) as {
messages: Array<{ labelIds: string[] }>;
};
expect(thread.messages.every((message) => message.labelIds.includes("IMPORTANT"))).toBe(true);
expect(thread.messages.some((message) => message.labelIds.includes("UNREAD"))).toBe(false);
const trashRes = await jsonRequest(app, "/gmail/v1/users/me/threads/thread_support/trash", {
method: "POST",
});
expect(trashRes.status).toBe(200);
const hiddenListRes = await app.request(`${base}/gmail/v1/users/me/threads`, {
headers: authHeaders(),
});
const hiddenList = (await hiddenListRes.json()) as { threads: Array<{ id: string }> };
expect(hiddenList.threads.some((threadItem) => threadItem.id === "thread_support")).toBe(false);
const untrashRes = await jsonRequest(app, "/gmail/v1/users/me/threads/thread_support/untrash", {
method: "POST",
});
expect(untrashRes.status).toBe(200);
const deleteRes = await app.request(`${base}/gmail/v1/users/me/threads/thread_billing`, {
method: "DELETE",
headers: authHeaders(),
});
expect(deleteRes.status).toBe(204);
});
it("creates, updates, and deletes user labels", async () => {
const createRes = await jsonRequest(app, "/gmail/v1/users/me/labels", {
method: "POST",
body: {
name: "Inbox Zero/Follow Up",
messageListVisibility: "show",
labelListVisibility: "labelShow",
color: {
backgroundColor: "#ABCDEF",
textColor: "#123456",
},
},
});
expect(createRes.status).toBe(200);
const created = (await createRes.json()) as { id: string; name: string; color?: { backgroundColor?: string } };
expect(created.name).toBe("Inbox Zero/Follow Up");
expect(created.color?.backgroundColor).toBe("#ABCDEF");
await jsonRequest(app, "/gmail/v1/users/me/messages/msg_invoice/modify", {
method: "POST",
body: { addLabelIds: [created.id] },
});
const patchRes = await jsonRequest(app, `/gmail/v1/users/me/labels/${created.id}`, {
method: "PATCH",
body: {
name: "Inbox Zero/Done",
color: {
backgroundColor: "#FEDCBA",
textColor: "#654321",
},
},
});
expect(patchRes.status).toBe(200);
const patched = (await patchRes.json()) as { name: string; color?: { backgroundColor?: string } };
expect(patched.name).toBe("Inbox Zero/Done");
expect(patched.color?.backgroundColor).toBe("#FEDCBA");
const getRes = await app.request(`${base}/gmail/v1/users/me/labels/${created.id}`, {
headers: authHeaders(),
});
const fetched = (await getRes.json()) as { messagesTotal: number };
expect(fetched.messagesTotal).toBe(1);
const deleteRes = await app.request(`${base}/gmail/v1/users/me/labels/${created.id}`, {
method: "DELETE",
headers: authHeaders(),
});
expect(deleteRes.status).toBe(204);
const messageRes = await app.request(`${base}/gmail/v1/users/me/messages/msg_invoice`, {
headers: authHeaders(),
});
const message = (await messageRes.json()) as { labelIds: string[] };
expect(message.labelIds).not.toContain(created.id);
});
it("exchanges auth codes for refresh tokens and refreshes access tokens", async () => {
const authorizeRes = await formRequest(app, "/o/oauth2/v2/auth/callback", {
email: "testuser@example.com",
redirect_uri: "http://localhost:3000/api/auth/callback/google",
scope: "openid email profile https://www.googleapis.com/auth/calendar.readonly",
client_id: "emu_google_client_id",
});
expect(authorizeRes.status).toBe(302);
const redirectLocation = authorizeRes.headers.get("Location");
expect(redirectLocation).toBeTruthy();
const redirectUrl = new URL(redirectLocation!);
const code = redirectUrl.searchParams.get("code");
expect(code).toBeTruthy();
const tokenRes = await formRequest(app, "/oauth2/token", {
code: code!,
grant_type: "authorization_code",
redirect_uri: "http://localhost:3000/api/auth/callback/google",
client_id: "emu_google_client_id",
client_secret: "emu_google_client_secret",
});
expect(tokenRes.status).toBe(200);
const tokenBody = (await tokenRes.json()) as {
access_token: string;
refresh_token: string;
id_token: string;
scope: string;
};
expect(tokenBody.access_token).toMatch(/^google_/);
expect(tokenBody.refresh_token).toMatch(/^google_refresh_/);
expect(tokenBody.id_token).toBeDefined();
const claims = decodeJwt(tokenBody.id_token);
expect(claims.iss).toBe(base);
expect(claims.aud).toBe("emu_google_client_id");
expect(claims.sub).toBeDefined();
expect(claims.email).toBe("testuser@example.com");
expect(claims.email_verified).toBe(true);
expect(claims.name).toBe("Test User");
const refreshRes = await formRequest(app, "/oauth2/token", {
grant_type: "refresh_token",
refresh_token: tokenBody.refresh_token,
client_id: "emu_google_client_id",
client_secret: "emu_google_client_secret",
});
expect(refreshRes.status).toBe(200);
const refreshBody = (await refreshRes.json()) as {
access_token: string;
scope: string;
};
expect(refreshBody.access_token).toMatch(/^google_/);
expect(refreshBody.access_token).not.toBe(tokenBody.access_token);
expect(refreshBody.scope).toBe(tokenBody.scope);
});
it("GET /oauth2/v3/certs returns JWKS with RSA public key", async () => {
const res = await app.request(`${base}/oauth2/v3/certs`);
expect(res.status).toBe(200);
const body = (await res.json()) as { keys: Array<Record<string, unknown>> };
expect(body.keys).toHaveLength(1);
const key = body.keys[0];
expect(key.kty).toBe("RSA");
expect(key.kid).toBe("emulate-google-1");
expect(key.use).toBe("sig");
expect(key.alg).toBe("RS256");
});
it("id_token signature can be verified against the JWKS endpoint", async () => {
const authorizeRes = await formRequest(app, "/o/oauth2/v2/auth/callback", {
email: "testuser@example.com",
redirect_uri: "http://localhost:3000/api/auth/callback/google",
scope: "openid email profile",
client_id: "emu_google_client_id",
});
const code = new URL(authorizeRes.headers.get("Location")!).searchParams.get("code")!;
const tokenRes = await formRequest(app, "/oauth2/token", {
code,
grant_type: "authorization_code",
redirect_uri: "http://localhost:3000/api/auth/callback/google",
client_id: "emu_google_client_id",
client_secret: "emu_google_client_secret",
});
const { id_token } = (await tokenRes.json()) as { id_token: string };
const certsRes = await app.request(`${base}/oauth2/v3/certs`);
const jwksJson = (await certsRes.json()) as { keys: object[] };
const JWKS = createLocalJWKSet(jwksJson);
const { payload } = await jwtVerify(id_token, JWKS, {
issuer: base,
audience: "emu_google_client_id",
});
expect(payload.email).toBe("testuser@example.com");
});
it("derives, overrides, and omits the hd claim based on user config", async () => {
async function getIdTokenClaims(email: string) {
const authorize = await formRequest(app, "/o/oauth2/v2/auth/callback", {
email,
redirect_uri: "http://localhost:3000/api/auth/callback/google",
scope: "openid email profile",
client_id: "emu_google_client_id",
});
const code = new URL(authorize.headers.get("Location")!).searchParams.get("code")!;
const tokenRes = await formRequest(app, "/oauth2/token", {
code,
grant_type: "authorization_code",
redirect_uri: "http://localhost:3000/api/auth/callback/google",
client_id: "emu_google_client_id",
client_secret: "emu_google_client_secret",
});
const body = (await tokenRes.json()) as { id_token: string; access_token: string };
return { claims: decodeJwt(body.id_token) as { hd?: string }, accessToken: body.access_token };
}
const derived = await getIdTokenClaims("testuser@example.com");
expect(derived.claims.hd).toBe("example.com");
const overridden = await getIdTokenClaims("workspaceuser@example.com");
expect(overridden.claims.hd).toBe("override.io");
const consumer = await getIdTokenClaims("consumer@gmail.com");
expect(consumer.claims.hd).toBeUndefined();
const userinfoRes = await app.request(`${base}/oauth2/v2/userinfo`, {
headers: { Authorization: `Bearer ${overridden.accessToken}` },
});
expect(userinfoRes.status).toBe(200);
expect(((await userinfoRes.json()) as { hd?: string }).hd).toBe("override.io");
});
it("lists calendar resources, creates events, queries freebusy, and deletes events", async () => {
const calendarListRes = await app.request(`${base}/calendar/v3/users/me/calendarList`, {
headers: authHeaders(),
});
expect(calendarListRes.status).toBe(200);
const calendarList = (await calendarListRes.json()) as {
items: Array<{ id: string; summary: string; primary?: boolean }>;
};
expect(calendarList.items.map((calendar) => calendar.id)).toEqual(["primary", "cal_team"]);
const eventListRes = await app.request(
`${base}/calendar/v3/calendars/primary/events?timeMin=2025-01-10T08:00:00.000Z&timeMax=2025-01-10T10:00:00.000Z&singleEvents=true&orderBy=startTime&q=${encodeURIComponent("kickoff")}`,
{ headers: authHeaders() },