feat: implement JMAP push notification handling and subscription management

This commit is contained in:
Linus Rath
2026-04-20 08:26:09 +02:00
parent bc3b923945
commit 15006086d2
8 changed files with 415 additions and 0 deletions
+91
View File
@@ -0,0 +1,91 @@
import { NextRequest, NextResponse } from 'next/server';
import { logger } from '@/lib/logger';
import { subscriptionStore } from '@/lib/push/store';
import { sendExpoPush } from '@/lib/push/expo';
import { isValidSubscriptionId } from '@/lib/push/validation';
import type { JmapPushBody } from '@/lib/push/types';
/**
* POST /api/push/jmap/:id
*
* Destination configured on JMAP PushSubscription. Spec (RFC 8620 §7.2)
* allows two body shapes:
*
* { "@type": "PushVerification", pushSubscriptionId, verificationCode }
* { "@type": "StateChange", changed: { [accountId]: { [type]: state } } }
*
* PushVerification is terminated here — cached against the subscription so
* the client can poll it. StateChange is fanned out as an Expo push so the
* mobile app wakes and re-fetches with its own credentials.
*/
function getAllowedOrigin(): string | null {
const raw = process.env.PUSH_ALLOWED_JMAP_ORIGIN?.trim();
return raw ? raw : null;
}
function getSharedSecret(): string | null {
const raw = process.env.PUSH_SHARED_SECRET?.trim();
return raw ? raw : null;
}
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
try {
const { id } = await params;
if (!isValidSubscriptionId(id)) {
return NextResponse.json({ error: 'Invalid subscriptionId' }, { status: 400 });
}
const allowedOrigin = getAllowedOrigin();
if (allowedOrigin) {
const origin = request.headers.get('origin') ?? '';
if (origin && origin !== allowedOrigin) {
return NextResponse.json({ error: 'Origin not allowed' }, { status: 403 });
}
}
const sharedSecret = getSharedSecret();
if (sharedSecret) {
// Stalwart supports a custom `Authorization` header on the push URL via
// PushSubscription.keys/headers — a shared secret is the strongest
// authentication a stateless relay can enforce.
const presented = request.headers.get('x-push-secret') ?? '';
if (presented !== sharedSecret) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
}
const record = await subscriptionStore.get(id);
if (!record) {
return NextResponse.json({ error: 'Unknown subscription' }, { status: 404 });
}
const body = (await request.json().catch(() => null)) as JmapPushBody | null;
if (!body || typeof body['@type'] !== 'string') {
return NextResponse.json({ error: 'Invalid JMAP push body' }, { status: 400 });
}
if (body['@type'] === 'PushVerification') {
record.verificationCode = body.verificationCode;
await subscriptionStore.put(id, record);
return NextResponse.json({ ok: true });
}
if (body['@type'] === 'StateChange') {
const ok = await sendExpoPush(record, body);
record.lastPushAt = Date.now();
await subscriptionStore.put(id, record);
return NextResponse.json({ ok });
}
return NextResponse.json({ error: 'Unsupported JMAP push type' }, { status: 400 });
} catch (error) {
logger.error('push: jmap handler failed', {
error: error instanceof Error ? error.message : 'Unknown error',
});
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
+29
View File
@@ -0,0 +1,29 @@
import { NextRequest, NextResponse } from 'next/server';
import { logger } from '@/lib/logger';
import { subscriptionStore } from '@/lib/push/store';
import { isValidSubscriptionId } from '@/lib/push/validation';
/**
* DELETE /api/push/register/:id
*
* Client tears down its relay mapping on logout / uninstall. Idempotent —
* deleting a non-existent id still returns ok.
*/
export async function DELETE(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
try {
const { id } = await params;
if (!isValidSubscriptionId(id)) {
return NextResponse.json({ error: 'Invalid subscriptionId' }, { status: 400 });
}
await subscriptionStore.delete(id);
return NextResponse.json({ ok: true });
} catch (error) {
logger.error('push: unregister failed', {
error: error instanceof Error ? error.message : 'Unknown error',
});
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
+52
View File
@@ -0,0 +1,52 @@
import { NextRequest, NextResponse } from 'next/server';
import { logger } from '@/lib/logger';
import { subscriptionStore } from '@/lib/push/store';
import {
isValidExpoPushToken,
isValidSubscriptionId,
} from '@/lib/push/validation';
import type { SubscriptionRecord } from '@/lib/push/types';
/**
* POST /api/push/register
* Body: { subscriptionId, expoPushToken, accountLabel? }
*
* Called by the mobile app once it has created a JMAP PushSubscription and
* received the subscriptionId it plans to use. We hold only the device's
* Expo push token + that id — no user credentials pass through the relay.
*/
export async function POST(request: NextRequest) {
try {
const body = (await request.json().catch(() => null)) as {
subscriptionId?: unknown;
expoPushToken?: unknown;
accountLabel?: unknown;
} | null;
if (!body) return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
const { subscriptionId, expoPushToken, accountLabel } = body;
if (!isValidSubscriptionId(subscriptionId)) {
return NextResponse.json({ error: 'Invalid subscriptionId' }, { status: 400 });
}
if (!isValidExpoPushToken(expoPushToken)) {
return NextResponse.json({ error: 'Invalid expoPushToken' }, { status: 400 });
}
const record: SubscriptionRecord = {
expoPushToken,
verificationCode: null,
createdAt: Date.now(),
lastPushAt: null,
accountLabel:
typeof accountLabel === 'string' ? accountLabel.slice(0, 120) : undefined,
};
await subscriptionStore.put(subscriptionId, record);
return NextResponse.json({ ok: true });
} catch (error) {
logger.error('push: register failed', {
error: error instanceof Error ? error.message : 'Unknown error',
});
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
+34
View File
@@ -0,0 +1,34 @@
import { NextRequest, NextResponse } from 'next/server';
import { logger } from '@/lib/logger';
import { subscriptionStore } from '@/lib/push/store';
import { isValidSubscriptionId } from '@/lib/push/validation';
/**
* GET /api/push/verify/:id
*
* Mobile app polls this after creating a JMAP PushSubscription. When the
* JMAP server POSTs a PushVerification to /api/push/jmap/:id we stash the
* code on the record; the client then PATCHes the subscription with it and
* activation completes (RFC 8620 §7.2.2).
*/
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) {
try {
const { id } = await params;
if (!isValidSubscriptionId(id)) {
return NextResponse.json({ error: 'Invalid subscriptionId' }, { status: 400 });
}
const record = await subscriptionStore.get(id);
if (!record) {
return NextResponse.json({ error: 'Unknown subscription' }, { status: 404 });
}
return NextResponse.json({ verificationCode: record.verificationCode ?? null });
} catch (error) {
logger.error('push: verify poll failed', {
error: error instanceof Error ? error.message : 'Unknown error',
});
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}