rebreak-monorepo/backend/server/utils/device-approval-email.ts
chahinebrini 2e056c7257 feat(devices): Apple-style two-device approval flow + email fallback
iCloud-Sign-In Pattern: wenn ein neues Gerät versucht sich anzumelden
und das Plan-Limit erreicht ist, kann der User auf einem bereits
angemeldeten Gerät bestätigen — Code wird auf BEIDEN Geräten gezeigt
für visuellen Vergleich (verhindert Code-Forwarding-Attacken).

Backend:
- New table device_approval_requests + supabase_realtime + RLS
- POST   /api/devices/approvals               — create (new device)
- GET    /api/devices/approvals               — list pending (existing devices)
- GET    /api/devices/approvals/:id           — status poll (new device)
- POST   /api/devices/approvals/:id/approve   — approve + atomic evict
- POST   /api/devices/approvals/:id/reject    — reject
- POST   /api/devices/approvals/:id/email     — trigger email fallback
- POST   /api/devices/approvals/email/:token  — magic-link approve (no auth)
- Email-Template via Resend (lyra-neutral, security-formal)
- 10min TTL, 6-digit numeric codes (crypto-random)

Frontend (rebreak-native):
- DeviceApprovalIncomingSheet — existing devices: code + device-picker + Allow/Reject
- DeviceApprovalPendingSheet  — new device: code + spinner + 'Send via email'
- useDeviceApprovalRealtime   — postgres_changes subscription
- DeviceLimitReachedSheet     — neues CTA 'Auf anderem Gerät bestätigen'
- i18n DE/EN/FR/AR

Migration läuft automatisch via prisma migrate deploy bei push.
2026-06-01 02:36:28 +02:00

111 lines
4.2 KiB
TypeScript

/**
* Device-Approval Email (Fallback wenn kein anderes Device online).
*
* Sendet eine Mail an die User-Email mit:
* - 6-stelligem Code (zur Anzeige / visuellem Vergleich)
* - Magic-Link (https://app.rebreak.org/approve-device?token=XYZ) der den
* Approval direkt bestätigt — User muss nicht eingeloggt sein.
*
* Lyra-Voice: NICHT verwenden — strikt informational/sicherheitsneutral.
*/
import { Resend } from "resend";
export interface DeviceApprovalEmailOpts {
recipientNickname: string;
recipientEmail: string;
code: string;
emailToken: string;
newDeviceLabel: string; // z.B. "iPhone 15 Pro (iOS)"
expiresAt: Date;
resendApiKey: string;
appBaseUrl?: string;
}
export async function sendDeviceApprovalEmail(
opts: DeviceApprovalEmailOpts,
): Promise<void> {
if (!opts.resendApiKey) {
console.warn("[device-approval-email] resendApiKey not provided — skipping");
return;
}
const resend = new Resend(opts.resendApiKey);
const baseUrl = opts.appBaseUrl ?? "https://app.rebreak.org";
const approveUrl = `${baseUrl}/approve-device?token=${encodeURIComponent(opts.emailToken)}`;
const ttlMinutes = Math.max(
1,
Math.round((opts.expiresAt.getTime() - Date.now()) / 60_000),
);
const subject = `ReBreak: Neues Gerät bestätigen (Code ${opts.code})`;
const html = `
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${subject}</title>
<style>
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; color: #1a1a1a; background: #f5f5f7; margin: 0; padding: 0; }
.container { max-width: 560px; margin: 32px auto; background: #fff; border-radius: 12px; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,0.08); }
.header { background: #1a1a1a; padding: 24px 32px; }
.header h1 { color: #fff; font-size: 18px; font-weight: 600; margin: 0; letter-spacing: -0.3px; }
.body { padding: 28px 32px; }
.body p { font-size: 15px; line-height: 1.6; color: #3a3a3a; margin: 0 0 16px; }
.code-box { background: #f5f5f7; border-radius: 8px; padding: 20px; margin: 24px 0; text-align: center; }
.code { font-family: 'SF Mono', Monaco, monospace; font-size: 32px; font-weight: 600; letter-spacing: 8px; color: #1a1a1a; }
.btn { display: block; text-align: center; padding: 14px 20px; border-radius: 8px; font-size: 15px; font-weight: 500; text-decoration: none; background: #1a1a1a; color: #fff !important; margin: 24px 0; }
.footer { padding: 16px 32px; font-size: 12px; color: #888; border-top: 1px solid #f0f0f0; }
.warning { background: #fff8e1; border-left: 3px solid #f59e0b; padding: 12px 16px; margin: 16px 0; font-size: 13px; color: #555; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>ReBreak — Neues Gerät bestätigen</h1>
</div>
<div class="body">
<p>Hallo ${opts.recipientNickname},</p>
<p>
Es wurde versucht, sich auf <strong>${opts.newDeviceLabel}</strong> bei deinem
ReBreak-Account anzumelden. Wenn du das warst, bestätige bitte unten.
</p>
<div class="code-box">
<div style="font-size:12px;color:#888;margin-bottom:8px;">Code zum Vergleich</div>
<div class="code">${opts.code}</div>
<div style="font-size:12px;color:#888;margin-top:12px;">
Gültig für ${ttlMinutes} Minuten
</div>
</div>
<p>
Vergleiche diesen Code mit dem, der auf deinem neuen Gerät angezeigt wird.
Wenn die Codes übereinstimmen, klicke auf den Button.
</p>
<a href="${approveUrl}" class="btn">Gerät bestätigen</a>
<div class="warning">
<strong>Wenn das nicht du warst:</strong> Ignoriere diese Mail. Ohne Bestätigung
bekommt das Gerät keinen Zugang. Der Versuch läuft in ${ttlMinutes} Minuten ab.
</div>
</div>
<div class="footer">
Diese Mail wurde automatisch verschickt. Fragen? support@rebreak.org
</div>
</div>
</body>
</html>
`.trim();
try {
await resend.emails.send({
from: "ReBreak <noreply@rebreak.org>",
to: opts.recipientEmail,
subject,
html,
});
} catch (err: any) {
console.error("[device-approval-email] Failed to send:", err?.message ?? err);
}
}