@open-workspace/email 0.5.2 → 0.6.1

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.
Files changed (50) hide show
  1. package/README.md +1 -2
  2. package/alchemy/index.ts +0 -16
  3. package/migrations/0003_after_0_5_2.sql +1 -0
  4. package/migrations/meta/0003_snapshot.json +703 -0
  5. package/migrations/meta/_journal.json +7 -0
  6. package/package.json +6 -5
  7. package/shared/mail.ts +3 -2
  8. package/shared/module.ts +1 -1
  9. package/src/client.tsx +20 -30
  10. package/src/extensions.ts +176 -0
  11. package/src/mail/compose-window-chrome.tsx +5 -10
  12. package/src/mail/compose-window.tsx +13 -2
  13. package/src/mail/composer-attach-button.tsx +106 -0
  14. package/src/mail/composer-editor.tsx +17 -0
  15. package/src/mail/composer-inserts.tsx +186 -0
  16. package/src/mail/composer-toolbar.tsx +3 -0
  17. package/src/mail/conversation-message.tsx +37 -1
  18. package/src/mail/conversation-reply.tsx +5 -10
  19. package/src/mail/message-actions.tsx +30 -0
  20. package/src/mail/message-attachments.tsx +62 -0
  21. package/src/mail/message-panels.tsx +206 -0
  22. package/src/mail/module-extensions.ts +87 -0
  23. package/src/mail/reader-pane.tsx +75 -47
  24. package/src/mail/recipient-combobox.tsx +32 -12
  25. package/src/mail/shared-compose.ts +45 -0
  26. package/src/settings/mail-notifications.tsx +119 -0
  27. package/src/settings/settings-queries.ts +0 -7
  28. package/worker/backups/file-parts.ts +9 -6
  29. package/worker/backups/mail-backup.ts +21 -4
  30. package/worker/backups/settings-backup.ts +56 -24
  31. package/worker/db/schema.ts +0 -36
  32. package/worker/jmap/method-core.ts +2 -3
  33. package/worker/jmap/push-subscription-methods.ts +5 -2
  34. package/worker/jmap/push.ts +10 -11
  35. package/worker/jmap/routes.ts +10 -49
  36. package/worker/mail/bimi.ts +2 -3
  37. package/worker/mail/person-erasure.ts +58 -0
  38. package/worker/mail/push-notifications.ts +59 -419
  39. package/worker/mail/remote-proxy.ts +3 -206
  40. package/worker/mail/remote-routes.ts +2 -2
  41. package/worker/mail/uploads.ts +14 -6
  42. package/worker/mail/webhook-source.ts +13 -1
  43. package/worker/mailbox/index.ts +27 -0
  44. package/worker/mailbox/mailbox-drafts.ts +5 -0
  45. package/worker/module-api.ts +239 -0
  46. package/worker/module.ts +11 -7
  47. package/src/pwa/push-key.ts +0 -18
  48. package/src/pwa/push-subscription.ts +0 -213
  49. package/src/settings/notifications-page.tsx +0 -306
  50. package/worker/mail/push-endpoint.ts +0 -17
@@ -1,213 +0,0 @@
1
- import type { PushSubscriptionData } from "@mmmike/web-push/client";
2
- import { responseJson } from "@open-workspace/core/ui";
3
-
4
- import { mailApi } from "../lib/mail-api";
5
- import { pushKeyMatches } from "./push-key";
6
-
7
- const SERVICE_WORKER_READY_TIMEOUT_MS = 10_000;
8
-
9
- function pushIsSupported() {
10
- return (
11
- "serviceWorker" in navigator &&
12
- "PushManager" in window &&
13
- "Notification" in window
14
- );
15
- }
16
-
17
- async function activeServiceWorkerRegistration() {
18
- const current = await navigator.serviceWorker.getRegistration();
19
-
20
- if (current?.active) return current;
21
-
22
- let timeout: ReturnType<typeof setTimeout> | undefined;
23
-
24
- try {
25
- return await Promise.race([
26
- navigator.serviceWorker.ready,
27
- new Promise<never>((_resolve, reject) => {
28
- timeout = setTimeout(() => {
29
- reject(new Error("The notification service is unavailable"));
30
- }, SERVICE_WORKER_READY_TIMEOUT_MS);
31
- }),
32
- ]);
33
- } finally {
34
- if (timeout) clearTimeout(timeout);
35
- }
36
- }
37
-
38
- async function currentBrowserPushSubscription() {
39
- if (!pushIsSupported()) return null;
40
- const registration = await navigator.serviceWorker.getRegistration();
41
-
42
- return registration?.pushManager.getSubscription() ?? null;
43
- }
44
-
45
- async function serializedSubscription(subscription: PushSubscription) {
46
- const client = await import("@mmmike/web-push/client");
47
-
48
- return client.serializeSubscription(subscription);
49
- }
50
-
51
- async function bindPushSubscription(subscription: PushSubscriptionData) {
52
- await responseJson(
53
- await mailApi.api.notifications.subscriptions.$put({ json: subscription })
54
- );
55
- }
56
-
57
- async function removeServerPushSubscription(endpoint: string) {
58
- await responseJson(
59
- await mailApi.api.notifications.subscriptions.$delete({
60
- json: { endpoint },
61
- })
62
- );
63
- }
64
-
65
- /**
66
- * This browser's subscription for the server's current VAPID key: `current`
67
- * when it was made with that key, else a new one in its place. A stage that
68
- * is recreated has new keys, and the push service refuses what the server
69
- * signs for a subscription made with the old ones.
70
- */
71
- async function subscriptionForKey(
72
- registration: ServiceWorkerRegistration,
73
- current: PushSubscription | null,
74
- publicKey: string
75
- ) {
76
- const { urlBase64ToUint8Array } = await import("@mmmike/web-push/vapid");
77
- const serverKey = urlBase64ToUint8Array(publicKey);
78
-
79
- if (
80
- current &&
81
- pushKeyMatches(current.options.applicationServerKey, serverKey)
82
- ) {
83
- return current;
84
- }
85
-
86
- if (current) {
87
- await removeServerPushSubscription(current.endpoint);
88
- // The browser has one subscription per service worker; another key needs it gone first.
89
- await current.unsubscribe();
90
- }
91
-
92
- return registration.pushManager.subscribe({
93
- userVisibleOnly: true,
94
- applicationServerKey: serverKey,
95
- });
96
- }
97
-
98
- /**
99
- * Before sign-out, stops this device getting the account's notifications.
100
- * The browser keeps its subscription, so the next person to sign in on this
101
- * device can claim it.
102
- */
103
- export async function removePushSubscriptionForSignOut() {
104
- let endpoint: string | undefined;
105
-
106
- try {
107
- endpoint = (await currentBrowserPushSubscription())?.endpoint;
108
- } catch {
109
- // Sign-out must not depend on browser push APIs being healthy; the
110
- // session is revoked even when this device cannot identify itself.
111
- return;
112
- }
113
-
114
- if (endpoint) await removeServerPushSubscription(endpoint);
115
- }
116
-
117
- /** On sign-in or reconnect, claim this browser's subscription for the current session. */
118
- export async function syncCurrentPushSubscription() {
119
- if (!pushIsSupported()) return;
120
- const registration = await navigator.serviceWorker.getRegistration();
121
- const current = await registration?.pushManager.getSubscription();
122
-
123
- if (!registration || !current) return;
124
-
125
- if (Notification.permission === "denied") {
126
- await removeServerPushSubscription(current.endpoint);
127
-
128
- return;
129
- }
130
-
131
- if (Notification.permission !== "granted") return;
132
-
133
- const config = await responseJson(
134
- await mailApi.api.notifications.config.$get()
135
- );
136
-
137
- if (!config.publicKey) return;
138
-
139
- const subscription = await subscriptionForKey(
140
- registration,
141
- current,
142
- config.publicKey
143
- );
144
-
145
- await bindPushSubscription(await serializedSubscription(subscription));
146
- }
147
-
148
- /** Inspect this browser without registering it again just to display the settings. */
149
- export async function currentPushRegistrationStatus(publicKey: string) {
150
- if (!pushIsSupported()) return "unsupported" as const;
151
-
152
- if (Notification.permission === "denied") return "denied" as const;
153
-
154
- if (Notification.permission !== "granted") return "prompt" as const;
155
-
156
- const subscription = await currentBrowserPushSubscription();
157
-
158
- if (!subscription) return "prompt" as const;
159
-
160
- const { urlBase64ToUint8Array } = await import("@mmmike/web-push/vapid");
161
-
162
- return pushKeyMatches(
163
- subscription.options.applicationServerKey,
164
- urlBase64ToUint8Array(publicKey)
165
- )
166
- ? ("enabled" as const)
167
- : ("prompt" as const);
168
- }
169
-
170
- export async function enableCurrentPushSubscription(publicKey: string) {
171
- if (!pushIsSupported()) {
172
- throw new Error("Push is not supported on this device");
173
- }
174
-
175
- if ((await Notification.requestPermission()) !== "granted") {
176
- throw new Error("Notification permission was denied");
177
- }
178
-
179
- const registration = await activeServiceWorkerRegistration();
180
-
181
- const current = await registration.pushManager.getSubscription();
182
-
183
- const subscription = await subscriptionForKey(
184
- registration,
185
- current,
186
- publicKey
187
- );
188
-
189
- try {
190
- await bindPushSubscription(await serializedSubscription(subscription));
191
- } catch (error) {
192
- // Settings reads browser state. Roll back a new subscription if the server never confirmed it.
193
- if (subscription !== current) await subscription.unsubscribe();
194
- throw error;
195
- }
196
- }
197
-
198
- export async function disableCurrentPushSubscription() {
199
- const subscription = await currentBrowserPushSubscription();
200
-
201
- if (!subscription) return { browserUnsubscribed: true };
202
-
203
- await removeServerPushSubscription(subscription.endpoint);
204
- let browserUnsubscribed = false;
205
-
206
- try {
207
- browserUnsubscribed = await subscription.unsubscribe();
208
- } catch {
209
- // The account mapping is already gone, which is the security boundary.
210
- }
211
-
212
- return { browserUnsubscribed };
213
- }
@@ -1,306 +0,0 @@
1
- import {
2
- adminPanelClass,
3
- AdminPanelBody,
4
- AdminPanelFooter,
5
- AdminPanelHeader,
6
- Button,
7
- DelayedFallback,
8
- Switch,
9
- useAuth,
10
- useDelayedPending,
11
- responseJson,
12
- } from "@open-workspace/core/ui";
13
- import {
14
- skipToken,
15
- useMutation,
16
- useQuery,
17
- useQueryClient,
18
- } from "@tanstack/react-query";
19
- import { Bell, BellOff, LoaderCircle, Smartphone } from "lucide-react";
20
- import { toast } from "sonner";
21
-
22
- import { mailApi } from "../lib/mail-api";
23
- import {
24
- currentPushRegistrationStatus,
25
- disableCurrentPushSubscription,
26
- enableCurrentPushSubscription,
27
- } from "../pwa/push-subscription";
28
- import {
29
- notificationPreferencesQuery,
30
- pushConfigQuery,
31
- } from "./settings-queries";
32
-
33
- type DeviceStatus =
34
- | "loading"
35
- | "error"
36
- | "unsupported"
37
- | "prompt"
38
- | "denied"
39
- | "enabled";
40
-
41
- function deviceStatusCopy(
42
- status: DeviceStatus,
43
- configured: boolean,
44
- configurationError: string | null
45
- ) {
46
- if (status === "error") return "Could not check this device. Try again.";
47
-
48
- if (configurationError) return configurationError;
49
-
50
- if (!configured) return "Web Push is not configured on this server.";
51
-
52
- if (status === "unsupported") {
53
- return "Push is unavailable in this browser. On iPhone or iPad, add the app to the Home Screen first.";
54
- }
55
-
56
- if (status === "denied") {
57
- return "Notifications are blocked in this browser's site settings.";
58
- }
59
-
60
- if (status === "enabled") {
61
- return "This device can notify you when OpenWorkspace is closed.";
62
- }
63
-
64
- if (status === "prompt") {
65
- return "Enable notifications for this browser and device.";
66
- }
67
-
68
- return "Checking this device…";
69
- }
70
-
71
- export function NotificationsSettings() {
72
- const client = useQueryClient();
73
- const userId = useAuth().user?.id;
74
-
75
- const config = useQuery(pushConfigQuery);
76
- const preferences = useQuery(notificationPreferencesQuery);
77
-
78
- const publicKey = config.data?.publicKey ?? null;
79
- const deviceStatusKey = ["push-device-status", userId, publicKey] as const;
80
-
81
- const device = useQuery({
82
- queryKey: deviceStatusKey,
83
- enabled: Boolean(config.data?.enabled && publicKey && userId),
84
- queryFn: publicKey
85
- ? () => currentPushRegistrationStatus(publicKey)
86
- : skipToken,
87
- });
88
-
89
- const enable = useMutation({
90
- mutationFn: async () => {
91
- if (!publicKey) throw new Error("Web Push is not configured");
92
-
93
- if (!userId) throw new Error("Sign in is required");
94
- await enableCurrentPushSubscription(publicKey);
95
- },
96
- onSuccess: () => {
97
- client.setQueryData(deviceStatusKey, "enabled" satisfies DeviceStatus);
98
- toast.success("Notifications enabled on this device");
99
- },
100
- onError: (error) => {
101
- void client.invalidateQueries({ queryKey: deviceStatusKey });
102
- toast.error(error.message);
103
- },
104
- });
105
-
106
- const disable = useMutation({
107
- mutationFn: disableCurrentPushSubscription,
108
- onSuccess: (removal) => {
109
- client.setQueryData(deviceStatusKey, "prompt" satisfies DeviceStatus);
110
-
111
- if (removal.browserUnsubscribed) {
112
- toast.success("Notifications disabled on this device");
113
- } else {
114
- toast.warning(
115
- "Notifications are disabled; this browser kept an unused subscription."
116
- );
117
- }
118
- },
119
- onError: (error) => toast.error(error.message),
120
- });
121
-
122
- const updatePreference = useMutation({
123
- mutationFn: async ({
124
- mailboxId,
125
- enabled,
126
- }: {
127
- mailboxId: string;
128
- enabled: boolean;
129
- }) =>
130
- responseJson(
131
- await mailApi.api.notifications.preferences[":mailboxId"].$put({
132
- param: { mailboxId },
133
- json: { enabled },
134
- })
135
- ),
136
- onSuccess: async () => {
137
- await client.invalidateQueries({
138
- queryKey: ["notification-preferences"],
139
- });
140
- },
141
- onError: (error) => toast.error(error.message),
142
- });
143
-
144
- const configured = config.data?.enabled ?? false;
145
-
146
- const deviceStatus: DeviceStatus =
147
- config.isError || device.isError
148
- ? "error"
149
- : config.isLoading || (configured && device.isLoading)
150
- ? "loading"
151
- : configured
152
- ? (device.data ?? "loading")
153
- : "unsupported";
154
-
155
- // Checking the device is mostly quick: its spinner only shows if it isn't.
156
- const deviceChecking = useDelayedPending(
157
- config.isLoading || device.isFetching
158
- );
159
-
160
- const devicePending =
161
- config.isLoading ||
162
- device.isFetching ||
163
- enable.isPending ||
164
- disable.isPending;
165
-
166
- const deviceSpinner = deviceChecking || enable.isPending || disable.isPending;
167
-
168
- function handleDeviceAction() {
169
- if (deviceStatus === "error") {
170
- void (config.isError ? config.refetch() : device.refetch());
171
-
172
- return;
173
- }
174
-
175
- enable.mutate();
176
- }
177
-
178
- return (
179
- <div className={adminPanelClass}>
180
- <AdminPanelHeader
181
- Icon={Bell}
182
- title="Mail notifications"
183
- description="Alerts for new mail, set for you on this device."
184
- />
185
- <AdminPanelBody className="space-y-6">
186
- <div className="flex flex-col gap-4 sm:flex-row sm:items-center">
187
- <span className="bg-primary/12 text-primary grid size-11 shrink-0 place-items-center rounded-lg">
188
- <Smartphone className="size-5" />
189
- </span>
190
- <div className="min-w-0 flex-1">
191
- <p className="text-sm font-semibold">This device</p>
192
- <p className="text-muted-foreground mt-1 text-xs leading-relaxed">
193
- {deviceStatusCopy(
194
- deviceStatus,
195
- configured,
196
- config.data?.error ?? null
197
- )}
198
- </p>
199
- </div>
200
- {deviceStatus === "enabled" ? (
201
- <Button
202
- variant="outline"
203
- disabled={devicePending}
204
- onClick={() => disable.mutate()}
205
- >
206
- {disable.isPending ? (
207
- <LoaderCircle className="animate-spin" />
208
- ) : (
209
- <BellOff />
210
- )}
211
- Disable
212
- </Button>
213
- ) : (
214
- <Button
215
- disabled={
216
- (deviceStatus !== "error" && !configured) ||
217
- deviceStatus === "unsupported" ||
218
- deviceStatus === "denied" ||
219
- deviceStatus === "loading" ||
220
- devicePending
221
- }
222
- onClick={handleDeviceAction}
223
- >
224
- {deviceSpinner ? (
225
- <LoaderCircle className="animate-spin" />
226
- ) : (
227
- <Bell />
228
- )}
229
- {deviceStatus === "error" ? "Retry" : "Enable"}
230
- </Button>
231
- )}
232
- </div>
233
-
234
- <div className="border-border/70 border-t pt-5">
235
- <p className="text-sm font-semibold">Mailboxes</p>
236
- <p className="text-muted-foreground mt-1 text-xs">
237
- Choose which mailboxes may send you new-message notifications.
238
- </p>
239
- <div className="divide-border/70 mt-4 divide-y">
240
- <DelayedFallback
241
- pending={preferences.isLoading}
242
- fallback={
243
- <div className="text-muted-foreground flex items-center gap-2 py-4 text-xs">
244
- <LoaderCircle className="size-4 animate-spin" /> Loading
245
- mailboxes…
246
- </div>
247
- }
248
- >
249
- {preferences.isError ? (
250
- <div className="flex items-center justify-between gap-4 py-4">
251
- <p className="text-destructive text-xs">
252
- Could not load mailbox preferences.
253
- </p>
254
- <Button
255
- size="sm"
256
- variant="outline"
257
- disabled={preferences.isFetching}
258
- onClick={() => void preferences.refetch()}
259
- >
260
- {preferences.isFetching && (
261
- <LoaderCircle className="animate-spin" />
262
- )}
263
- Retry
264
- </Button>
265
- </div>
266
- ) : preferences.data?.preferences.length ? (
267
- preferences.data.preferences.map((preference) => (
268
- <label
269
- key={preference.mailboxId}
270
- className="flex items-center gap-4 py-3"
271
- >
272
- <span className="min-w-0 flex-1">
273
- <span className="block truncate text-sm font-medium">
274
- {preference.displayName}
275
- </span>
276
- <span className="text-muted-foreground block truncate text-xs">
277
- {preference.address}
278
- </span>
279
- </span>
280
- <Switch
281
- checked={preference.enabled}
282
- disabled={updatePreference.isPending}
283
- onCheckedChange={(enabled) =>
284
- updatePreference.mutate({
285
- mailboxId: preference.mailboxId,
286
- enabled,
287
- })
288
- }
289
- />
290
- </label>
291
- ))
292
- ) : (
293
- <p className="text-muted-foreground py-4 text-xs">
294
- No mailboxes are available for notifications.
295
- </p>
296
- )}
297
- </DelayedFallback>
298
- </div>
299
- </div>
300
- </AdminPanelBody>
301
- <AdminPanelFooter className="text-muted-foreground justify-start text-xs">
302
- You won't be notified about a mailbox while it's open in a tab.
303
- </AdminPanelFooter>
304
- </div>
305
- );
306
- }
@@ -1,17 +0,0 @@
1
- import { assertProxyableRemoteUrl } from "./remote-proxy";
2
-
3
- /**
4
- * The one rule for where the Worker POSTs pushes, the app's Web Push and
5
- * JMAP's alike. Push goes to whatever push service the subscriber uses, so
6
- * any public HTTPS host is accepted (a self-hosted Mozilla autopush
7
- * included). What is refused is what the image proxy refuses: credentials
8
- * in the URL, localhost, private and internal addresses, and internal-only
9
- * names. Checked when it is registered and again before each delivery.
10
- */
11
- export function isPublicPushEndpoint(endpoint: string) {
12
- try {
13
- return assertProxyableRemoteUrl(endpoint).protocol === "https:";
14
- } catch {
15
- return false;
16
- }
17
- }