feat: voice messages, offline queue, delivery ticks, volume slider, admin + scaling

- Voice messages: MediaRecorder → encrypted attachment, custom waveform
  player via OfflineAudioContext, 60s limit + live mic-level meter
- Offline message queue: localStorage outbox, exponential backoff retries,
  optimistic pending bubble with retry/discard
- Delivery indicator: message_deliveries table + RLS (reciprocal receipts),
  ✓ / ✓✓ / ✓✓-blue tick states, group-aware (all members must ack)
- Per-participant volume slider in calls via right-click tile menu,
  persisted to localStorage, applied to attached audio elements
- Group call scaling: grid up to 12 tiles with pagination,
  active-speaker auto-promotion in fullscreen
- Push notifications scaffolding: service worker, VAPID subscription
  registration, notify-push edge function skeleton
- Backup recovery code: 24-char base32 code (~120 bits entropy) as
  alternative decrypt path, restore UI with mode toggle
- Admin panel: conversations list, audit log (admin_audit_log table +
  admin_log_action RPC), audit entry on user flag toggle
- Search v2: sender filter, attachment-only toggle, date range
- Reactions pop animation (scale 0.4→1.15→1 on count change)
- Message list windowing (150 default, expand via IntersectionObserver)
- Stub cleanup: removed dead ScreenshareStub from CallParticipantTile

Fixes:
- Focus-triggered flicker: dropped window.focus listeners in three spots,
  throttled visibilitychange/online wake-refreshes to 30s, keep existing
  data visible during background re-syncs (no more spinner on every click)
- Voice attachment audio element collapsed to 0px on peer side — now
  forces 280px min-width on bubble

Migrations (push required):
  20260421000001_message_deliveries.sql
  20260421000002_admin_audit_log.sql

Server TODO:
  VAPID keys + notify-push edge function deploy
This commit is contained in:
2026-04-21 01:14:16 +02:00
parent da85f0ba54
commit a04ecf7a19
40 changed files with 4286 additions and 430 deletions
+102
View File
@@ -0,0 +1,102 @@
// Supabase Edge Function — fan-out push notifications via Web Push (VAPID).
//
// Trigger: server-side (e.g. database trigger on messages INSERT calling
// pg_net.http_post → this function), or app-level after sendEncryptedMessage
// resolves successfully.
//
// Required environment variables (set via supabase secrets):
// VAPID_PUBLIC_KEY
// VAPID_PRIVATE_KEY
// VAPID_SUBJECT e.g. "mailto:admin@example.com"
// PUSH_FANOUT_SHARED_SECRET shared header secret to authenticate caller
//
// Request body:
// { conversationId: string, senderUserId: string, senderName: string, kind?: "message" | "call" }
//
// The function:
// 1. Looks up conversation_members minus sender.
// 2. Joins to push_tokens via devices.
// 3. Sends a Web Push to each token using web-push npm via npm: specifier.
//
// Note: this is a skeleton — wire web-push library and verify against the
// chosen Deno deploy runtime.
// deno-lint-ignore-file no-explicit-any
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
import webPush from 'npm:web-push@3.6.7';
const SUPABASE_URL = Deno.env.get('SUPABASE_URL') ?? '';
const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? '';
const VAPID_PUBLIC_KEY = Deno.env.get('VAPID_PUBLIC_KEY') ?? '';
const VAPID_PRIVATE_KEY = Deno.env.get('VAPID_PRIVATE_KEY') ?? '';
const VAPID_SUBJECT = Deno.env.get('VAPID_SUBJECT') ?? 'mailto:admin@example.com';
const SHARED_SECRET = Deno.env.get('PUSH_FANOUT_SHARED_SECRET') ?? '';
if (VAPID_PUBLIC_KEY && VAPID_PRIVATE_KEY) {
webPush.setVapidDetails(VAPID_SUBJECT, VAPID_PUBLIC_KEY, VAPID_PRIVATE_KEY);
}
interface Payload {
conversationId: string;
senderUserId: string;
senderName: string;
kind?: 'message' | 'call';
}
Deno.serve(async (req) => {
if (req.method !== 'POST') return new Response('method', { status: 405 });
// Shared-secret gate. Cheap, replaces user JWT here because the trigger has
// no authenticated session.
const auth = req.headers.get('x-shared-secret');
if (!SHARED_SECRET || auth !== SHARED_SECRET) {
return new Response('unauthorized', { status: 401 });
}
let body: Payload;
try {
body = await req.json();
} catch {
return new Response('bad json', { status: 400 });
}
const client = createClient(SUPABASE_URL, SERVICE_ROLE_KEY);
const { data: members, error: mErr } = await client
.from('conversation_members')
.select('user_id')
.eq('conversation_id', body.conversationId);
if (mErr) return new Response('members lookup failed', { status: 500 });
const recipientIds = (members ?? [])
.map((m: any) => m.user_id as string)
.filter((id: string) => id !== body.senderUserId);
if (recipientIds.length === 0) return new Response('no recipients', { status: 200 });
const { data: tokens, error: tErr } = await client
.from('push_tokens')
.select('token, devices!inner(user_id)')
.in('devices.user_id', recipientIds);
if (tErr) return new Response('tokens lookup failed', { status: 500 });
const payload = JSON.stringify({
title: body.senderName,
body: body.kind === 'call' ? 'Eingehender Anruf' : 'Neue Nachricht',
conversationId: body.conversationId,
kind: body.kind ?? 'message',
});
const results = await Promise.allSettled(
(tokens ?? []).map(async (row: any) => {
try {
const sub = JSON.parse(row.token);
await webPush.sendNotification(sub, payload);
} catch (err) {
console.warn('push send failed', err);
}
}),
);
return new Response(JSON.stringify({ sent: results.length }), {
headers: { 'content-type': 'application/json' },
});
});
@@ -0,0 +1,54 @@
-- ============================================================================
-- Delivery receipts — "✓✓" tick in WhatsApp/Telegram parlance: the recipient's
-- device has fetched the message from the server, regardless of whether they
-- have actually opened the conversation yet. `message_reads` already covers
-- the "read" step; this table fills the gap between "sent" and "read".
--
-- A row exists iff the recipient user has acknowledged receiving the message
-- on at least one device. Writes are triggered client-side after successful
-- message fetch/decrypt. Select policy mirrors read receipts (opt-out via
-- profiles.show_read_receipts on BOTH ends).
-- ============================================================================
create table public.message_deliveries (
message_id uuid not null references public.messages(id) on delete cascade,
user_id uuid not null references auth.users(id) on delete cascade,
delivered_at timestamptz not null default now(),
primary key (message_id, user_id)
);
alter table public.message_deliveries enable row level security;
create policy deliveries_select_reciprocal on public.message_deliveries
for select to authenticated
using (
user_id = auth.uid()
or (
coalesce(
(select show_read_receipts from public.profiles where profiles.user_id = auth.uid()),
true
)
and coalesce(
(select show_read_receipts from public.profiles where profiles.user_id = message_deliveries.user_id),
true
)
and exists (
select 1 from public.messages m
where m.id = message_id and public.is_conversation_member(m.conversation_id)
)
)
);
create policy deliveries_insert_own on public.message_deliveries
for insert to authenticated
with check (
user_id = auth.uid()
and exists (
select 1 from public.messages m
where m.id = message_id and public.is_conversation_member(m.conversation_id)
)
);
create index message_deliveries_message_id_idx on public.message_deliveries (message_id);
create index message_deliveries_user_id_idx on public.message_deliveries (user_id);
alter publication supabase_realtime add table public.message_deliveries;
@@ -0,0 +1,63 @@
-- ============================================================================
-- Admin audit log — append-only journal of administrative actions. Writes
-- go through an RPC so the insert path is a single choke-point with input
-- validation; reads are admin-only via RLS.
-- ============================================================================
create table public.admin_audit_log (
id uuid primary key default gen_random_uuid(),
actor_id uuid not null references auth.users(id) on delete set null,
action text not null,
target_type text,
target_id text,
metadata jsonb not null default '{}'::jsonb,
created_at timestamptz not null default now()
);
create index admin_audit_log_created_at_idx on public.admin_audit_log (created_at desc);
create index admin_audit_log_actor_idx on public.admin_audit_log (actor_id);
alter table public.admin_audit_log enable row level security;
create policy audit_log_select_admin on public.admin_audit_log
for select to authenticated
using (public.current_user_is_admin());
-- Insert via RPC only — no direct insert policy, so clients can't forge rows
-- with a different actor_id.
create or replace function public.admin_log_action(
p_action text,
p_target_type text default null,
p_target_id text default null,
p_metadata jsonb default '{}'::jsonb
) returns uuid
language plpgsql
security definer
set search_path = public
as $$
declare
new_id uuid;
begin
if not public.current_user_is_admin() then
raise exception 'not an admin';
end if;
insert into public.admin_audit_log (actor_id, action, target_type, target_id, metadata)
values (auth.uid(), p_action, p_target_type, p_target_id, coalesce(p_metadata, '{}'::jsonb))
returning id into new_id;
return new_id;
end;
$$;
revoke all on function public.admin_log_action(text, text, text, jsonb) from public;
grant execute on function public.admin_log_action(text, text, text, jsonb) to authenticated;
-- ============================================================================
-- Admin conversations view — lets admins list every conversation (bypassing
-- is_conversation_member). Read-only: no writes flow through the view.
-- ============================================================================
create policy conversations_select_admin on public.conversations
for select to authenticated
using (public.current_user_is_admin());
create policy conversation_members_select_admin on public.conversation_members
for select to authenticated
using (public.current_user_is_admin());