ihasmail could hand a file to the share sheet as of #306, and was still not in it. Share a photo from the gallery, a link from the browser or a document from a file manager and ihasmail was not among the places it could go, which is the one piece of operating-system integration a mail app is expected to have. A share is a POST that navigates, and there is nothing on this side that can answer one: the app is a client-side router with no endpoint at that address, and the server behind it would need a route that understood the composer. So the service worker intercepts it, takes the form body, puts the files and text in its cache, and redirects to the app -- which finds them on start and opens a draft holding them. The subject is the shared title, the text and the link become the body, and files are attached and begin uploading. Nothing is addressed: a share says what to send, never who to. The body is pushed in above the signature rather than passed to open(), because open() only fits a signature when it is given no body at all -- the obvious version drops the signature from every message that started as a share, and nothing about the draft looks wrong afterwards. Collected on every start rather than when the launch URL says so. A share to a signed-out ihasmail lands on the sign-in page, and there is no account to attach to until it is done, so the payload has to outlive a redirect and a login -- which the query string does not. What that costs is a stash nobody came back for, so it carries a timestamp and expires after ten minutes. `accept` names wildcard families and explicit types and extensions both. A mail client attaches anything, but wildcards are not in the specification and operating systems differ over which form they match on, so the explicit list is what holds if the families are ignored. The cache name the worker and the app have to agree on now has one home on the app side. It was written out twice, and a drift would not fail -- a push verification would simply never complete and a share would arrive at an empty composer. One case is deliberately left to fail loudly: an app still installed whose worker has been cleared away POSTs to the server, which answers 405. A server route would trade a plain error for a silent nothing, and the payload is gone in both -- it only ever existed in that request body. Verified by test, not on a device: Android is the only place this exists at all, and the extension driving Chrome is not connected here. The handoff is pinned from the tab's side against a cache shaped exactly as the worker leaves it, since the two files never see each other.
175 lines
6.9 KiB
TypeScript
175 lines
6.9 KiB
TypeScript
/**
|
|
* Turning Web Push on and off, and completing the handshake it needs.
|
|
*
|
|
* Kept apart from `webpush.ts` so that module stays pure JMAP and stays
|
|
* testable: everything here touches the browser's service worker and
|
|
* permission prompt, none of which exists under a test runner.
|
|
*/
|
|
import { CAP } from "@/jmap/client";
|
|
import { withBase } from "./basePath";
|
|
import { SW_CACHE_NAME } from "./swCache";
|
|
import { isDeviceTrusted } from "@/lib/storage";
|
|
import { useSession } from "@/store/session";
|
|
import { useMail } from "@/store/mail";
|
|
import {
|
|
applicationServerKey,
|
|
createSubscription,
|
|
decodeApplicationServerKey,
|
|
deviceClientId,
|
|
findSubscription,
|
|
listSubscriptions,
|
|
needsRenewal,
|
|
pushEnabledHere,
|
|
setPushEnabledHere,
|
|
subscriptionPayload,
|
|
unsubscribeThisDevice,
|
|
verifySubscription,
|
|
webPushAvailable,
|
|
} from "@/lib/webpush";
|
|
|
|
let listening = false;
|
|
|
|
/**
|
|
* Watch for the verification code the server pushes.
|
|
*
|
|
* The service worker cannot answer it — a JMAP call needs the session cookie
|
|
* and this is a background context — so it forwards the code here, or leaves it
|
|
* in the cache when no tab was open to forward it to.
|
|
*/
|
|
export function listenForVerification(): void {
|
|
if (listening || typeof navigator === "undefined" || !("serviceWorker" in navigator)) return;
|
|
listening = true;
|
|
navigator.serviceWorker.addEventListener("message", (e: MessageEvent) => {
|
|
const d = e.data as { type?: string; id?: string; code?: string } | undefined;
|
|
if (d?.type === "push-verification" && d.id && d.code) void verifySubscription(d.id, d.code).catch(() => {});
|
|
});
|
|
void collectStoredVerification();
|
|
}
|
|
|
|
/** Pick up a code that arrived while no tab was open. */
|
|
async function collectStoredVerification(): Promise<void> {
|
|
try {
|
|
const cache = await caches.open(SW_CACHE_NAME);
|
|
// The same absolute key the worker writes. Relative would be resolved
|
|
// against this document's URL, which is a different place on every route.
|
|
const key = withBase("/ihasmail-push-verification");
|
|
const hit = await cache.match(key);
|
|
if (!hit) return;
|
|
const { id, code } = (await hit.json()) as { id?: string; code?: string };
|
|
await cache.delete(key);
|
|
if (id && code) await verifySubscription(id, code);
|
|
} catch {
|
|
/* nothing waiting, or no cache: not a failure */
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Subscribe this browser. Safe to call again — the deviceClientId makes a
|
|
* repeat replace rather than accumulate.
|
|
*
|
|
* Returns why it could not, rather than throwing, because every reason is
|
|
* something to tell the user plainly: an old server, a browser without push, a
|
|
* permission they declined.
|
|
*/
|
|
export async function enableWebPush(): Promise<{ ok: true } | { ok: false; reason: string }> {
|
|
if (!webPushAvailable()) {
|
|
return { ok: false, reason: "This browser or mail server does not support background notifications." };
|
|
}
|
|
if (Notification.permission === "denied") {
|
|
return { ok: false, reason: "Notifications are blocked for this site in your browser's settings." };
|
|
}
|
|
// A subscription outlives the tab and belongs to the account, not the
|
|
// session -- so on a machine the user has told us is not theirs, it would go
|
|
// on delivering their mail to it long after they had gone.
|
|
if (!isDeviceTrusted()) {
|
|
return { ok: false, reason: "Background notifications need a device you have marked as your own. Sign in again with \u201CThis is my own device\u201D ticked." };
|
|
}
|
|
const key = applicationServerKey();
|
|
if (!key) return { ok: false, reason: "This mail server does not publish a push key." };
|
|
|
|
try {
|
|
await registerThisBrowser(key);
|
|
setPushEnabledHere(true);
|
|
listenForVerification();
|
|
return { ok: true };
|
|
} catch (err) {
|
|
return { ok: false, reason: (err as Error).message || "Could not subscribe to notifications." };
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get this browser subscribed at the push service and registered at Stalwart.
|
|
*
|
|
* Shared by turning push on and by renewing it, because they are the same
|
|
* call: `deviceClientId` makes a repeat registration replace rather than
|
|
* accumulate, so there is no separate "update" path to get wrong.
|
|
*
|
|
* The local subscription is created when it is missing rather than only reused.
|
|
* A browser may drop or rotate one on its own -- a `pushsubscriptionchange`
|
|
* nobody was open to hear -- and the version that only reused an existing one
|
|
* gave up there, leaving push off for good with the switch still saying it was
|
|
* on.
|
|
*/
|
|
async function registerThisBrowser(key: string): Promise<void> {
|
|
const reg = await navigator.serviceWorker.ready;
|
|
const sub = (await reg.pushManager.getSubscription()) ?? (await reg.pushManager.subscribe({
|
|
// Web Push requires it, and Chrome refuses a subscription without it.
|
|
userVisibleOnly: true,
|
|
applicationServerKey: decodeApplicationServerKey(key),
|
|
}));
|
|
const accountId = useSession.getState().ownAccountFor(CAP.mail);
|
|
const inboxId = useMail.getState().roleId("inbox");
|
|
await createSubscription(subscriptionPayload(sub, accountId, inboxId));
|
|
}
|
|
|
|
/**
|
|
* Keep a subscription alive, from app start.
|
|
*
|
|
* Renewal has to happen here rather than in the service worker: registering
|
|
* with Stalwart is a JMAP call, and a JMAP call needs the session cookie that
|
|
* only a page has. So the guarantee is "push keeps working as long as ihasmail
|
|
* is opened now and again", and the renewal window is wide enough that once a
|
|
* week is enough.
|
|
*
|
|
* Silent by design. Every reason to stop is a normal state -- push was never
|
|
* turned on here, the permission is gone, the device is not trusted any more --
|
|
* and none of them is news to deliver on a cold start.
|
|
*/
|
|
export async function renewWebPush(): Promise<void> {
|
|
if (!pushEnabledHere() || !webPushAvailable()) return;
|
|
if (typeof Notification === "undefined" || Notification.permission !== "granted") return;
|
|
const key = applicationServerKey();
|
|
if (!key) return;
|
|
try {
|
|
if (!needsRenewal(await listSubscriptions(), deviceClientId())) return;
|
|
await registerThisBrowser(key);
|
|
listenForVerification();
|
|
} catch {
|
|
/* offline, or the server said no: the next start tries again */
|
|
}
|
|
}
|
|
|
|
/** Remove this browser's subscription, at the browser and at the server. */
|
|
export async function disableWebPush(): Promise<void> {
|
|
await unsubscribeThisDevice();
|
|
}
|
|
|
|
/**
|
|
* Whether *this browser* has a subscription registered at the server.
|
|
*
|
|
* The device has to match. This used to answer "does the account have any
|
|
* subscription at all", which is true the moment one other device has one --
|
|
* so a phone that had never successfully registered, or whose registration had
|
|
* since expired, showed the switch already on and delivered nothing. The
|
|
* account-wide question is not one this switch is asking.
|
|
*/
|
|
export async function webPushActive(): Promise<boolean> {
|
|
try {
|
|
const reg = await navigator.serviceWorker?.getRegistration();
|
|
if (!(await reg?.pushManager.getSubscription())) return false;
|
|
return Boolean(findSubscription(await listSubscriptions(), deviceClientId()));
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|