@remit/backend 0.0.128 → 0.0.130

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@remit/backend",
3
- "version": "0.0.128",
3
+ "version": "0.0.130",
4
4
  "description": "Remit Mail Inspector API backend",
5
5
  "license": "MIT",
6
6
  "author": "",
@@ -36,6 +36,8 @@ const listEvents =
36
36
  CalendarEventOperations.CalendarEventOperations_listCalendarEvents as Handler;
37
37
  const createEvent =
38
38
  CalendarEventOperations.CalendarEventOperations_createCalendarEvent as Handler;
39
+ const getEvent =
40
+ CalendarEventDetailOperations.CalendarEventDetailOperations_getCalendarEvent as Handler;
39
41
  const updateEvent =
40
42
  CalendarEventDetailOperations.CalendarEventDetailOperations_updateCalendarEvent as Handler;
41
43
  const deleteEvent =
@@ -264,6 +266,118 @@ describe("GET /calendar-events", () => {
264
266
  });
265
267
  });
266
268
 
269
+ describe("GET /calendar-events?calendarObjectId", () => {
270
+ it("lists the occurrences of that one resource, across the caller's calendars", async () => {
271
+ const { event } = anAccount();
272
+ const defaultId = await defaultCalendarId(event);
273
+ const work = (await createCalendar(
274
+ contextOf({ requestBody: { urlSegment: "work", displayName: "Work" } }),
275
+ event,
276
+ )) as unknown as { calendarId: string };
277
+ const series = await seedEvent(event, {
278
+ calendarId: work.calendarId,
279
+ summary: "Stand-up",
280
+ start: "2026-09-07T09:00:00Z",
281
+ end: "2026-09-07T09:15:00Z",
282
+ recurrenceRule: "FREQ=WEEKLY;COUNT=3",
283
+ });
284
+ await seedEvent(event, {
285
+ calendarId: defaultId,
286
+ summary: "Dentist",
287
+ start: "2026-09-08T09:00:00Z",
288
+ end: "2026-09-08T10:00:00Z",
289
+ });
290
+
291
+ const listed = (await listEvents(
292
+ contextOf({
293
+ query: { ...WINDOW, calendarObjectId: series.calendarObjectId },
294
+ }),
295
+ event,
296
+ )) as unknown as { items: Instance[] };
297
+
298
+ assert.deepEqual(
299
+ listed.items.map((instance) => [
300
+ instance.calendarId,
301
+ instance.start.slice(0, 10),
302
+ ]),
303
+ [
304
+ [work.calendarId, "2026-09-07"],
305
+ [work.calendarId, "2026-09-14"],
306
+ [work.calendarId, "2026-09-21"],
307
+ ],
308
+ );
309
+ });
310
+
311
+ it("lists nothing for a resource on another account", async () => {
312
+ const stranger = anAccount();
313
+ const theirs = await seedEvent(stranger.event, {
314
+ calendarId: await defaultCalendarId(stranger.event),
315
+ summary: "Private",
316
+ start: "2026-09-07T09:00:00Z",
317
+ end: "2026-09-07T10:00:00Z",
318
+ });
319
+ const { event } = anAccount();
320
+
321
+ const listed = (await listEvents(
322
+ contextOf({
323
+ query: { ...WINDOW, calendarObjectId: theirs.calendarObjectId },
324
+ }),
325
+ event,
326
+ )) as unknown as { items: Instance[] };
327
+
328
+ assert.deepEqual(listed.items, []);
329
+ });
330
+ });
331
+
332
+ describe("GET /calendar-events/{calendarObjectId} without a calendar", () => {
333
+ it("finds the resource among the caller's calendars", async () => {
334
+ const { event } = anAccount();
335
+ await defaultCalendarId(event);
336
+ const work = (await createCalendar(
337
+ contextOf({ requestBody: { urlSegment: "work", displayName: "Work" } }),
338
+ event,
339
+ )) as unknown as { calendarId: string };
340
+ const seeded = await seedEvent(event, {
341
+ calendarId: work.calendarId,
342
+ summary: "Stand-up",
343
+ start: "2026-09-07T09:00:00Z",
344
+ end: "2026-09-07T09:15:00Z",
345
+ });
346
+
347
+ const found = (await getEvent(
348
+ contextOf({
349
+ params: { calendarObjectId: seeded.calendarObjectId },
350
+ query: {},
351
+ }),
352
+ event,
353
+ )) as unknown as { calendarId: string; dtStart: string };
354
+
355
+ assert.equal(found.calendarId, work.calendarId);
356
+ assert.match(found.dtStart, /^2026-09-07/);
357
+ });
358
+
359
+ it("answers not-found for a resource on another account", async () => {
360
+ const stranger = anAccount();
361
+ const theirs = await seedEvent(stranger.event, {
362
+ calendarId: await defaultCalendarId(stranger.event),
363
+ summary: "Private",
364
+ start: "2026-09-07T09:00:00Z",
365
+ end: "2026-09-07T10:00:00Z",
366
+ });
367
+ const { event } = anAccount();
368
+
369
+ const found = await getEvent(
370
+ contextOf({
371
+ params: { calendarObjectId: theirs.calendarObjectId },
372
+ query: {},
373
+ }),
374
+ event,
375
+ );
376
+
377
+ assert.equal(found.statusCode, 404);
378
+ });
379
+ });
380
+
267
381
  describe("POST /calendar-events", () => {
268
382
  it("refuses a recurrence rule it cannot read and writes nothing", async () => {
269
383
  const { event } = anAccount();
@@ -15,6 +15,7 @@ import {
15
15
  deleteCalendarObject,
16
16
  listBusySpans,
17
17
  listCalendarInstances,
18
+ listObjectInstances,
18
19
  OFFSET_BEARING,
19
20
  parseCalendar,
20
21
  projectCalendar,
@@ -490,6 +491,22 @@ export const deleteCalendarEventFor = async (
490
491
  );
491
492
  };
492
493
 
494
+ /** The collection holding a resource, found among the ones given. */
495
+ const locateResource = async (
496
+ deps: CalendarDeps,
497
+ collections: CalendarCollectionItem[],
498
+ calendarObjectId: string,
499
+ ): Promise<ResolvedResource | undefined> => {
500
+ for (const collection of collections) {
501
+ const object = await deps.calendarObject.find(
502
+ collection.calendarId,
503
+ calendarObjectId,
504
+ );
505
+ if (object) return { collection, object };
506
+ }
507
+ return undefined;
508
+ };
509
+
493
510
  const readCalendarIds = (value: unknown): string[] => {
494
511
  if (typeof value === "string") return value === "" ? [] : [value];
495
512
  if (Array.isArray(value)) return value.filter((id) => typeof id === "string");
@@ -545,6 +562,7 @@ export const CalendarEventOperations: Record<
545
562
  from?: string;
546
563
  to?: string;
547
564
  calendarId?: string | string[];
565
+ calendarObjectId?: string;
548
566
  };
549
567
  const window = readWindow(query.from, query.to);
550
568
  if (!window.ok) return badRequest(window.error);
@@ -557,6 +575,22 @@ export const CalendarEventOperations: Record<
557
575
  );
558
576
  if (!collections.ok) return answerRefusal(collections.error);
559
577
 
578
+ if (query.calendarObjectId) {
579
+ const located = await locateResource(
580
+ deps,
581
+ collections.value,
582
+ query.calendarObjectId,
583
+ );
584
+ if (!located) return { items: [] };
585
+ const own = await listObjectInstances(
586
+ deps,
587
+ located.collection,
588
+ located.object,
589
+ window.value,
590
+ );
591
+ return { items: own.map(toInstanceResponse) };
592
+ }
593
+
560
594
  const instances = await listCalendarInstances(
561
595
  deps,
562
596
  collections.value,
@@ -594,6 +628,20 @@ export const CalendarEventDetailOperations: Record<
594
628
  if (!request.ok) return badRequest(request.error);
595
629
  const deps = calendarEventDepsOf(calendarDepsOf(await getClient()));
596
630
 
631
+ if (request.value.calendarId === "") {
632
+ const located = await locateResource(
633
+ deps,
634
+ await listCalendarsFor(deps, accountConfigId),
635
+ request.value.calendarObjectId,
636
+ );
637
+ if (!located) {
638
+ return notFound(
639
+ `no event ${request.value.calendarObjectId} on this account`,
640
+ );
641
+ }
642
+ return toEventResponse(located.object);
643
+ }
644
+
597
645
  const resolved = await resolveResource(
598
646
  deps,
599
647
  accountConfigId,
@@ -168,11 +168,14 @@ const refusingSqsClient = (): { client: SQSClient; accept: () => void } => {
168
168
  };
169
169
  };
170
170
 
171
+ let accountSyncedServices: string[] = ["Mail"];
172
+
171
173
  const accountRepository = {
172
174
  get: async () => ({
173
175
  accountId: ACCOUNT_ID,
174
176
  accountConfigId: ACCOUNT_CONFIG_ID,
175
177
  email: ACCOUNT_EMAIL,
178
+ syncedServices: accountSyncedServices,
176
179
  }),
177
180
  } as unknown as IAccountRepository;
178
181
 
@@ -327,6 +330,7 @@ const sentOutboxMessageId = async (): Promise<string> => {
327
330
 
328
331
  afterEach(() => {
329
332
  _resetForTest();
333
+ accountSyncedServices = ["Mail"];
330
334
  });
331
335
 
332
336
  describe("an outbox entry that has left draft (#604)", () => {
@@ -674,3 +678,67 @@ describe("attachmentIds on a draft update (#679)", () => {
674
678
  assert.equal(attachmentRows.size, 2);
675
679
  });
676
680
  });
681
+
682
+ describe("sending from an account with mail off (#1181)", () => {
683
+ const assertRefusal = (response: APIGatewayProxyResult): void => {
684
+ assert.equal(response.statusCode, 400);
685
+ const body = JSON.parse(response.body) as {
686
+ code?: string;
687
+ message?: string;
688
+ details?: Record<string, string>;
689
+ };
690
+ assert.equal(body.code, "mail_sync_off");
691
+ assert.match(String(body.message), /Turn Mail back on .* in Settings/);
692
+ assert.deepEqual(body.details, { accountId: ACCOUNT_ID });
693
+ };
694
+
695
+ it("answers a send of a saved draft with a 400 naming the fix", async () => {
696
+ installClient();
697
+ const draft = await createDraft(
698
+ requestContext({}),
699
+ authorizedEvent({
700
+ accountId: ACCOUNT_ID,
701
+ toAddresses: ["recipient@example.com"],
702
+ subject: "hello",
703
+ }),
704
+ );
705
+ accountSyncedServices = ["Calendar"];
706
+
707
+ const response = await respond(() =>
708
+ sendMessage(
709
+ requestContext({
710
+ params: { outboxMessageId: String(draft.outboxMessageId) },
711
+ }),
712
+ authorizedEvent(),
713
+ ),
714
+ );
715
+
716
+ assertRefusal(response);
717
+ const kept = await getMessage(
718
+ requestContext({
719
+ params: { outboxMessageId: String(draft.outboxMessageId) },
720
+ }),
721
+ authorizedEvent(),
722
+ );
723
+ assert.equal(kept.status, "draft");
724
+ });
725
+
726
+ it("answers a send-immediately create with the same 400", async () => {
727
+ installClient();
728
+ accountSyncedServices = ["Calendar"];
729
+
730
+ const response = await respond(() =>
731
+ createDraft(
732
+ requestContext({}),
733
+ authorizedEvent({
734
+ accountId: ACCOUNT_ID,
735
+ toAddresses: ["recipient@example.com"],
736
+ subject: "hello",
737
+ sendImmediately: true,
738
+ }),
739
+ ),
740
+ );
741
+
742
+ assertRefusal(response);
743
+ });
744
+ });
@@ -0,0 +1,197 @@
1
+ import assert from "node:assert/strict";
2
+ import { randomUUID } from "node:crypto";
3
+ import { readFileSync } from "node:fs";
4
+ import { afterEach, beforeEach, describe, it } from "node:test";
5
+ import type { AccountItem } from "@remit/data-ports";
6
+ import {
7
+ AccountAuthType,
8
+ AccountService,
9
+ ConnectionState,
10
+ MailboxCursorState,
11
+ } from "@remit/domain-enums";
12
+ import {
13
+ AccountRepo,
14
+ AccountSettingRepo,
15
+ AddressRepo,
16
+ DrizzleMessageRepository,
17
+ DrizzleThreadMessageRepository,
18
+ LabelRepo,
19
+ MailboxRepo,
20
+ MessageLabelRepo,
21
+ } from "@remit/drizzle-service";
22
+ import { createShippedSqliteDb } from "@remit/drizzle-service/test-sqlite";
23
+ import type { APIGatewayProxyEvent } from "aws-lambda";
24
+ import type { Context } from "openapi-backend";
25
+ import { deriveAccountConfigId } from "../auth.js";
26
+ import {
27
+ _resetForTest,
28
+ type RemitClient,
29
+ setClient,
30
+ } from "../service/data-client.js";
31
+ import { ThreadOperations } from "./thread.js";
32
+ import {
33
+ buildInboxMailboxMap,
34
+ executeUnifiedThreadListing,
35
+ type UnifiedThreadClient,
36
+ } from "./unified-threads.js";
37
+
38
+ const SUB = "cognito-sub-1181";
39
+ const ACCOUNT_CONFIG_ID = deriveAccountConfigId(SUB);
40
+ const NOW = 1_700_000_000_000;
41
+
42
+ let client: UnifiedThreadClient & RemitClient;
43
+ let close: () => void;
44
+
45
+ beforeEach(() => {
46
+ const store = createShippedSqliteDb();
47
+ store.sqlite.exec(
48
+ readFileSync(
49
+ new URL(
50
+ "../../../../npm-scripts/sqlite-search-index.sql",
51
+ import.meta.url,
52
+ ),
53
+ "utf8",
54
+ ),
55
+ );
56
+ close = store.close;
57
+ const db = store.db as never;
58
+ client = {
59
+ account: new AccountRepo(store.db),
60
+ accountSetting: new AccountSettingRepo(store.db),
61
+ mailbox: new MailboxRepo(store.db),
62
+ address: new AddressRepo(store.db),
63
+ message: new DrizzleMessageRepository(db),
64
+ threadMessage: new DrizzleThreadMessageRepository(db),
65
+ label: new LabelRepo(store.db),
66
+ messageLabel: new MessageLabelRepo(store.db),
67
+ } as unknown as UnifiedThreadClient & RemitClient;
68
+ setClient(client);
69
+ });
70
+
71
+ afterEach(() => {
72
+ _resetForTest();
73
+ close();
74
+ });
75
+
76
+ const seedAccountWithInboxThread = async (
77
+ syncedServices: AccountItem["syncedServices"],
78
+ ): Promise<{ accountId: string; mailboxId: string; threadId: string }> => {
79
+ const label = syncedServices.join("-");
80
+ const account = await client.account.create({
81
+ accountConfigId: ACCOUNT_CONFIG_ID,
82
+ username: `${label}@example.com`,
83
+ email: `${label}@example.com`,
84
+ authType: AccountAuthType.OauthMicrosoft,
85
+ syncedServices,
86
+ imapHost: "outlook.office365.com",
87
+ imapPort: 993,
88
+ imapTls: true,
89
+ imapStartTls: false,
90
+ isActive: true,
91
+ connectionState: ConnectionState.Authenticated,
92
+ });
93
+ const created = await client.mailbox.create({
94
+ accountId: account.accountId,
95
+ namespacePrefix: "",
96
+ hierarchyDelimiter: "/",
97
+ fullPath: "INBOX",
98
+ uidValidity: 1,
99
+ uidNext: 2,
100
+ highestModseq: "0",
101
+ messageCount: 1,
102
+ unseenCount: 1,
103
+ deletedCount: 0,
104
+ totalSize: 10,
105
+ lastSyncUid: 1,
106
+ highWaterMarkUid: 1,
107
+ lastMessageSyncAt: NOW,
108
+ cursorState: MailboxCursorState.normal,
109
+ } as Parameters<MailboxRepo["create"]>[0]);
110
+ if (created.outcome !== "Created") throw new Error("INBOX path taken");
111
+ const mailbox = created.mailbox;
112
+ const messageId = randomUUID();
113
+ await client.message.create({
114
+ messageId,
115
+ mailboxId: mailbox.mailboxId,
116
+ uid: 1,
117
+ sequenceNumber: 1,
118
+ rfc822Size: 10,
119
+ internalDate: NOW,
120
+ envelopeId: randomUUID(),
121
+ rootBodyPartId: randomUUID(),
122
+ status: "active",
123
+ syncStatus: "synced",
124
+ });
125
+ const threadId = randomUUID();
126
+ await client.threadMessage.create({
127
+ accountConfigId: ACCOUNT_CONFIG_ID,
128
+ threadId,
129
+ messageId,
130
+ mailboxId: mailbox.mailboxId,
131
+ uid: 1,
132
+ referenceOrder: 0,
133
+ internalDate: NOW,
134
+ sentDate: NOW,
135
+ subject: `hello from ${label}`,
136
+ isRead: false,
137
+ isDeleted: false,
138
+ hasAttachment: false,
139
+ hasStars: false,
140
+ });
141
+ return {
142
+ accountId: account.accountId,
143
+ mailboxId: mailbox.mailboxId,
144
+ threadId,
145
+ };
146
+ };
147
+
148
+ const unifiedThreadIds = async (searchText?: string): Promise<string[]> => {
149
+ const response = await executeUnifiedThreadListing(
150
+ client,
151
+ ACCOUNT_CONFIG_ID,
152
+ {
153
+ starredOnly: false,
154
+ searchText,
155
+ count: false,
156
+ results: true,
157
+ },
158
+ );
159
+ return (response.items ?? []).map((item) => item.threadId).sort();
160
+ };
161
+
162
+ describe("a mail-off account in the unified surfaces (#1181)", () => {
163
+ it("leaves the unified list and search, and its mailbox still opens directly", async () => {
164
+ const mailOnly = await seedAccountWithInboxThread([AccountService.Mail]);
165
+ const both = await seedAccountWithInboxThread([
166
+ AccountService.Mail,
167
+ AccountService.Calendar,
168
+ ]);
169
+ const calendarOnly = await seedAccountWithInboxThread([
170
+ AccountService.Calendar,
171
+ ]);
172
+ const mailSources = [mailOnly.threadId, both.threadId].sort();
173
+
174
+ assert.deepEqual(await unifiedThreadIds(), mailSources);
175
+ assert.deepEqual(await unifiedThreadIds("hello"), mailSources);
176
+
177
+ const scope = await buildInboxMailboxMap(ACCOUNT_CONFIG_ID, client);
178
+ assert.equal(scope.starredMailboxIds.has(calendarOnly.mailboxId), false);
179
+
180
+ const listThreads = ThreadOperations.ThreadOperations_listThreads as (
181
+ context: Context,
182
+ event: APIGatewayProxyEvent,
183
+ ) => Promise<unknown>;
184
+ const opened = (await listThreads(
185
+ {
186
+ request: { params: { mailboxId: calendarOnly.mailboxId }, query: {} },
187
+ } as unknown as Context,
188
+ {
189
+ requestContext: { authorizer: { claims: { sub: SUB } } },
190
+ } as unknown as APIGatewayProxyEvent,
191
+ )) as { items: { threadId: string }[] };
192
+ assert.deepEqual(
193
+ opened.items.map((item) => item.threadId),
194
+ [calendarOnly.threadId],
195
+ );
196
+ });
197
+ });
@@ -52,7 +52,7 @@ const buildClient = (
52
52
  settings: AccountSettingItem[] = [],
53
53
  ): InboxMapClient =>
54
54
  ({
55
- account: { listAllByAccountConfig: async () => accounts },
55
+ account: { listMailSourcesByAccountConfig: async () => accounts },
56
56
  mailbox: {
57
57
  listAllByAccount: async (accountId: string) =>
58
58
  mailboxesByAccount[accountId] ?? [],
@@ -455,7 +455,10 @@ describe("executeUnifiedThreadListing", () => {
455
455
  const buildListingClient = (calls: Call[], count = 0) =>
456
456
  ({
457
457
  account: {
458
- listAllByAccountConfig: async () => [account("a1"), account("a2")],
458
+ listMailSourcesByAccountConfig: async () => [
459
+ account("a1"),
460
+ account("a2"),
461
+ ],
459
462
  },
460
463
  mailbox: {
461
464
  listAllByAccount: async (accountId: string) =>
@@ -37,7 +37,9 @@ const MAILBOX_LIST_CONCURRENCY = 5;
37
37
  */
38
38
  export interface InboxMapClient {
39
39
  account: {
40
- listAllByAccountConfig(accountConfigId: string): Promise<AccountItem[]>;
40
+ listMailSourcesByAccountConfig(
41
+ accountConfigId: string,
42
+ ): Promise<AccountItem[]>;
41
43
  };
42
44
  mailbox: {
43
45
  listAllByAccount(accountId: string): Promise<MailboxItem[]>;
@@ -125,7 +127,7 @@ const isExcludedFromSearch = (mailbox: MailboxItem): boolean =>
125
127
  * keyed by accountId/mailboxId; a target counts as muted only when its MutedFlag
126
128
  * exists AND `value === true`.
127
129
  *
128
- * NOTE (read cost / mute drift): this fan-out (one listAllByAccountConfig + N
130
+ * NOTE (read cost / mute drift): this fan-out (one listMailSourcesByAccountConfig + N
129
131
  * per-account mailbox listings) runs on *every* page request and is not cached
130
132
  * across a pagination session. Acceptable for v1 — mailbox lists are small —
131
133
  * but it means the inbox/mute filter set is rebuilt per page from live state,
@@ -146,7 +148,7 @@ export const buildInboxMailboxMap = async (
146
148
  virtualCopyMailboxIds: Set<string>;
147
149
  }> => {
148
150
  const [accounts, settings] = await Promise.all([
149
- client.account.listAllByAccountConfig(accountConfigId),
151
+ client.account.listMailSourcesByAccountConfig(accountConfigId),
150
152
  client.accountSetting.listByAccountConfig(accountConfigId),
151
153
  ]);
152
154