-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathschema.sql
More file actions
3264 lines (2596 loc) · 95.6 KB
/
Copy pathschema.sql
File metadata and controls
3264 lines (2596 loc) · 95.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
--
-- PostgreSQL database dump
--
\restrict f9UfSPE6AEQGyeIWT74rUgsmzrFnn15mG9BMzdPh4QLH686eitlPz7DImIrK4CO
-- Dumped from database version 17.6
-- Dumped by pg_dump version 18.4
SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET transaction_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET check_function_bodies = false;
SET xmloption = content;
SET client_min_messages = warning;
SET row_security = off;
--
-- Name: public; Type: SCHEMA; Schema: -; Owner: -
--
CREATE SCHEMA public;
--
-- Name: SCHEMA public; Type: COMMENT; Schema: -; Owner: -
--
COMMENT ON SCHEMA public IS 'standard public schema';
--
-- Name: activate_gated_storage_subs(text); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.activate_gated_storage_subs(p_pubkey text) RETURNS integer
LANGUAGE plpgsql SECURITY DEFINER
SET search_path TO ''
AS $$
DECLARE
v_count integer;
BEGIN
UPDATE public.paddle_storage_subs
SET gated = false,
updated_at = now()
WHERE pubkey = p_pubkey
AND gated = true;
GET DIAGNOSTICS v_count = ROW_COUNT;
RETURN v_count;
END;
$$;
--
-- Name: adjust_blob_bytes(bigint); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.adjust_blob_bytes(delta bigint) RETURNS void
LANGUAGE plpgsql SECURITY DEFINER
SET search_path TO ''
AS $$
begin
perform public.adjust_image_bytes(delta);
end;
$$;
--
-- Name: adjust_image_bytes(bigint); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.adjust_image_bytes(delta bigint) RETURNS void
LANGUAGE plpgsql SECURITY DEFINER
SET search_path TO ''
AS $$
DECLARE
v_pubkey text;
v_max_total_bytes bigint;
v_max_image_bytes bigint;
v_total_bytes bigint;
v_image_bytes bigint;
BEGIN
v_pubkey := auth.jwt() -> 'app_metadata' ->> 'pubkey';
IF v_pubkey IS NULL THEN
RAISE EXCEPTION 'pubkey not linked';
END IF;
INSERT INTO public.pubkey_quotas (user_pubkey, note_count, total_bytes, image_bytes, updated_at)
VALUES (v_pubkey, 0, 0, greatest(delta, 0), now())
ON CONFLICT (user_pubkey) DO UPDATE
SET image_bytes = greatest(public.pubkey_quotas.image_bytes + delta, 0),
updated_at = now()
RETURNING total_bytes, image_bytes INTO v_total_bytes, v_image_bytes;
-- Enforce on growth only. Deletes always succeed.
IF delta > 0 THEN
SELECT max_total_bytes, max_image_bytes
INTO v_max_total_bytes, v_max_image_bytes
FROM public.quota_limits_for_pubkey(v_pubkey);
-- Gate 1: per-type image cap.
IF v_image_bytes > v_max_image_bytes THEN
UPDATE public.pubkey_quotas
SET image_bytes = greatest(image_bytes - delta, 0),
updated_at = now()
WHERE user_pubkey = v_pubkey;
RAISE EXCEPTION 'Quota exceeded: image storage % bytes > limit % bytes',
v_image_bytes, v_max_image_bytes
USING errcode = 'check_violation';
END IF;
-- Gate 2: combined storage cap (notes + images).
IF (v_total_bytes + v_image_bytes) > v_max_total_bytes THEN
UPDATE public.pubkey_quotas
SET image_bytes = greatest(image_bytes - delta, 0),
updated_at = now()
WHERE user_pubkey = v_pubkey;
RAISE EXCEPTION 'Quota exceeded: combined storage % bytes > limit % bytes',
(v_total_bytes + v_image_bytes), v_max_total_bytes
USING errcode = 'check_violation';
END IF;
END IF;
END;
$$;
--
-- Name: admin_abuse_allowlist_add(text, text); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.admin_abuse_allowlist_add(target_pubkey text, p_reason text DEFAULT NULL::text) RETURNS void
LANGUAGE plpgsql SECURITY DEFINER
SET search_path TO 'public'
AS $$
DECLARE
v_caller text;
BEGIN
IF NOT public.is_admin() THEN
RAISE EXCEPTION 'not authorized' USING errcode = '42501';
END IF;
v_caller := (auth.jwt() -> 'user_metadata' ->> 'pubkey');
INSERT INTO public.abuse_allowlist (pubkey, added_by_pubkey, reason)
VALUES (target_pubkey, v_caller, p_reason)
ON CONFLICT (pubkey) DO UPDATE
SET added_at = now(),
added_by_pubkey = EXCLUDED.added_by_pubkey,
reason = EXCLUDED.reason;
END;
$$;
--
-- Name: admin_abuse_allowlist_list(); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.admin_abuse_allowlist_list() RETURNS TABLE(pubkey text, added_at timestamp with time zone, added_by_pubkey text, reason text)
LANGUAGE plpgsql STABLE SECURITY DEFINER
SET search_path TO 'public'
AS $$
BEGIN
IF NOT public.is_admin() THEN
RAISE EXCEPTION 'not authorized' USING errcode = '42501';
END IF;
RETURN QUERY
SELECT a.pubkey, a.added_at, a.added_by_pubkey, a.reason
FROM public.abuse_allowlist a
ORDER BY a.added_at DESC;
END;
$$;
--
-- Name: admin_abuse_allowlist_remove(text); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.admin_abuse_allowlist_remove(target_pubkey text) RETURNS void
LANGUAGE plpgsql SECURITY DEFINER
SET search_path TO 'public'
AS $$
BEGIN
IF NOT public.is_admin() THEN
RAISE EXCEPTION 'not authorized' USING errcode = '42501';
END IF;
DELETE FROM public.abuse_allowlist WHERE pubkey = target_pubkey;
END;
$$;
--
-- Name: admin_abuse_device_cycling(); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.admin_abuse_device_cycling() RETURNS TABLE(pubkey text, devices_7d bigint, total_devices bigint, is_pro boolean)
LANGUAGE plpgsql STABLE SECURITY DEFINER
SET search_path TO 'public'
AS $$
BEGIN
IF NOT public.is_admin() THEN
RAISE EXCEPTION 'not authorized' USING errcode = '42501';
END IF;
RETURN QUERY
SELECT
d.pubkey,
count(*) FILTER (WHERE d.created_at > now() - interval '7 days')::bigint AS devices_7d,
count(*)::bigint AS total_devices,
(EXISTS (SELECT 1 FROM public.pro_pubkeys pp WHERE pp.pubkey = d.pubkey)) AS is_pro
FROM public.devices d
WHERE NOT EXISTS (SELECT 1 FROM public.abuse_allowlist a WHERE a.pubkey = d.pubkey)
GROUP BY d.pubkey
HAVING count(*) FILTER (WHERE d.created_at > now() - interval '7 days') > 3
ORDER BY devices_7d DESC
LIMIT 50;
END;
$$;
--
-- Name: admin_abuse_device_farms(); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.admin_abuse_device_farms() RETURNS TABLE(pubkey text, device_count bigint, active_count bigint, is_pro boolean, note_count bigint)
LANGUAGE plpgsql STABLE SECURITY DEFINER
SET search_path TO 'public'
AS $$
BEGIN
IF NOT public.is_admin() THEN
RAISE EXCEPTION 'not authorized' USING errcode = '42501';
END IF;
RETURN QUERY
SELECT
d.pubkey,
count(*)::bigint AS device_count,
count(*) FILTER (WHERE d.last_seen_at > now() - interval '30 days')::bigint AS active_count,
(EXISTS (SELECT 1 FROM public.pro_pubkeys pp WHERE pp.pubkey = d.pubkey)) AS is_pro,
coalesce(q.note_count, 0)::bigint AS note_count
FROM public.devices d
LEFT JOIN public.pubkey_quotas q ON q.user_pubkey = d.pubkey
WHERE NOT EXISTS (SELECT 1 FROM public.abuse_allowlist a WHERE a.pubkey = d.pubkey)
GROUP BY d.pubkey, q.note_count
HAVING count(*) > 5
ORDER BY device_count DESC
LIMIT 50;
END;
$$;
--
-- Name: admin_abuse_ghost_writers(); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.admin_abuse_ghost_writers() RETURNS TABLE(pubkey text, note_count bigint, total_bytes bigint, last_seen_at timestamp with time zone, days_silent bigint)
LANGUAGE plpgsql STABLE SECURITY DEFINER
SET search_path TO 'public'
AS $$
BEGIN
IF NOT public.is_admin() THEN
RAISE EXCEPTION 'not authorized' USING errcode = '42501';
END IF;
RETURN QUERY
SELECT
q.user_pubkey AS pubkey,
q.note_count,
q.total_bytes,
latest.last_seen AS last_seen_at,
extract(day FROM now() - latest.last_seen)::bigint AS days_silent
FROM public.pubkey_quotas q
LEFT JOIN LATERAL (
SELECT max(d.last_seen_at) AS last_seen
FROM public.devices d
WHERE d.pubkey = q.user_pubkey
) latest ON true
WHERE q.note_count > 0
AND (latest.last_seen IS NULL OR latest.last_seen < now() - interval '90 days')
AND NOT EXISTS (SELECT 1 FROM public.abuse_allowlist a WHERE a.pubkey = q.user_pubkey)
ORDER BY q.note_count DESC
LIMIT 50;
END;
$$;
--
-- Name: admin_abuse_note_hoarders(); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.admin_abuse_note_hoarders() RETURNS TABLE(pubkey text, note_count bigint, total_bytes bigint, is_pro boolean, last_seen_at timestamp with time zone)
LANGUAGE plpgsql STABLE SECURITY DEFINER
SET search_path TO 'public'
AS $$
BEGIN
IF NOT public.is_admin() THEN
RAISE EXCEPTION 'not authorized' USING errcode = '42501';
END IF;
RETURN QUERY
SELECT
q.user_pubkey AS pubkey,
q.note_count,
q.total_bytes,
(EXISTS (SELECT 1 FROM public.pro_pubkeys pp WHERE pp.pubkey = q.user_pubkey)) AS is_pro,
(SELECT max(d.last_seen_at) FROM public.devices d WHERE d.pubkey = q.user_pubkey) AS last_seen_at
FROM public.pubkey_quotas q
WHERE q.note_count > 1000
AND NOT EXISTS (SELECT 1 FROM public.abuse_allowlist a WHERE a.pubkey = q.user_pubkey)
ORDER BY q.note_count DESC
LIMIT 50;
END;
$$;
--
-- Name: admin_abuse_oversized_notes(); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.admin_abuse_oversized_notes() RETURNS TABLE(pubkey text, note_id uuid, ciphertext_bytes bigint, created_at timestamp with time zone, updated_at timestamp with time zone)
LANGUAGE plpgsql STABLE SECURITY DEFINER
SET search_path TO 'public'
AS $$
BEGIN
IF NOT public.is_admin() THEN
RAISE EXCEPTION 'not authorized' USING errcode = '42501';
END IF;
RETURN QUERY
SELECT
n.user_pubkey AS pubkey,
n.id AS note_id,
octet_length(n.ciphertext)::bigint AS ciphertext_bytes,
n.created_at,
n.updated_at
FROM public.notes n
WHERE octet_length(n.ciphertext) > 512000
AND NOT EXISTS (SELECT 1 FROM public.abuse_allowlist a WHERE a.pubkey = n.user_pubkey)
ORDER BY ciphertext_bytes DESC
LIMIT 50;
END;
$$;
--
-- Name: admin_abuse_storage_hogs(); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.admin_abuse_storage_hogs() RETURNS TABLE(pubkey text, total_bytes bigint, max_bytes bigint, pct numeric, is_pro boolean, note_count bigint)
LANGUAGE plpgsql STABLE SECURITY DEFINER
SET search_path TO 'public'
AS $$
BEGIN
IF NOT public.is_admin() THEN
RAISE EXCEPTION 'not authorized' USING errcode = '42501';
END IF;
RETURN QUERY
SELECT
q.user_pubkey AS pubkey,
q.total_bytes,
lim.max_total_bytes AS max_bytes,
round(q.total_bytes::numeric / nullif(lim.max_total_bytes, 0) * 100, 1) AS pct,
(EXISTS (SELECT 1 FROM public.pro_pubkeys pp WHERE pp.pubkey = q.user_pubkey)) AS is_pro,
q.note_count
FROM public.pubkey_quotas q
CROSS JOIN LATERAL public.quota_limits_for_pubkey(q.user_pubkey) lim
WHERE q.total_bytes > lim.max_total_bytes * 0.8
AND NOT EXISTS (SELECT 1 FROM public.abuse_allowlist a WHERE a.pubkey = q.user_pubkey)
ORDER BY pct DESC
LIMIT 50;
END;
$$;
--
-- Name: admin_activation_funnel(); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.admin_activation_funnel() RETURNS jsonb
LANGUAGE plpgsql STABLE SECURITY DEFINER
SET search_path TO 'public'
AS $$
DECLARE
result jsonb;
v_total bigint;
v_linked bigint;
v_has_notes bigint;
v_has_device bigint;
v_active_7d bigint;
BEGIN
IF NOT public.is_admin() THEN
RAISE EXCEPTION 'not authorized' USING errcode = '42501';
END IF;
SELECT count(*) INTO v_total
FROM auth.users
WHERE (raw_app_meta_data ->> 'pubkey') IS NOT NULL;
SELECT count(*) INTO v_linked
FROM auth.users
WHERE (raw_app_meta_data ->> 'pubkey') IS NOT NULL;
SELECT count(DISTINCT user_pubkey) INTO v_has_notes FROM public.notes;
SELECT count(DISTINCT pubkey) INTO v_has_device FROM public.devices;
SELECT count(DISTINCT pubkey) INTO v_active_7d
FROM public.devices
WHERE last_seen_at > now() - interval '7 days';
SELECT jsonb_build_object(
'signed_up', v_total,
'linked_pubkey', v_linked,
'wrote_note', v_has_notes,
'registered_device', v_has_device,
'active_7d', v_active_7d
) INTO result;
RETURN result;
END;
$$;
--
-- Name: admin_activity_breakdown(); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.admin_activity_breakdown() RETURNS jsonb
LANGUAGE plpgsql STABLE SECURITY DEFINER
SET search_path TO 'public'
AS $$
DECLARE
result jsonb;
BEGIN
IF NOT public.is_admin() THEN
RAISE EXCEPTION 'not authorized' USING errcode = '42501';
END IF;
WITH pubkeys AS (
SELECT DISTINCT (raw_app_meta_data ->> 'pubkey') AS pk
FROM auth.users
WHERE (raw_app_meta_data ->> 'pubkey') IS NOT NULL
),
latest_device AS (
SELECT pubkey AS pk, max(last_seen_at) AS last_active
FROM public.devices
GROUP BY pubkey
)
SELECT jsonb_build_object(
'active_7d', count(*) FILTER (WHERE ld.last_active > now() - interval '7 days'),
'warm_30d', count(*) FILTER (WHERE ld.last_active BETWEEN now() - interval '30 days' AND now() - interval '7 days'),
'dormant', count(*) FILTER (WHERE ld.last_active < now() - interval '30 days'),
'ghost', count(*) FILTER (WHERE ld.last_active IS NULL),
'total', count(*)
) INTO result
FROM pubkeys p
LEFT JOIN latest_device ld ON ld.pk = p.pk;
RETURN result;
END;
$$;
--
-- Name: admin_add_timeline_event(timestamp with time zone, text, text, text); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.admin_add_timeline_event(occurred_at timestamp with time zone, label text, description text DEFAULT NULL::text, url text DEFAULT NULL::text) RETURNS uuid
LANGUAGE plpgsql SECURITY DEFINER
SET search_path TO ''
AS $$
declare
caller_pubkey text;
new_id uuid;
begin
-- Require the caller to be an admin.
if not exists (
select 1 from public.admin_pubkeys
where pubkey = (auth.jwt() -> 'app_metadata' ->> 'pubkey')
) then
raise exception 'forbidden' using errcode = '42501';
end if;
if label is null or length(trim(label)) = 0 then
raise exception 'label required' using errcode = '22023';
end if;
-- Use app_metadata (not user_metadata) - app_metadata is server-writable only.
caller_pubkey := nullif(
(auth.jwt() -> 'app_metadata' ->> 'pubkey'),
''
);
insert into public.timeline_events (occurred_at, label, description, url, created_by)
values (
occurred_at,
trim(label),
nullif(trim(description), ''),
nullif(trim(url), ''),
caller_pubkey
)
returning id into new_id;
return new_id;
end;
$$;
--
-- Name: admin_adjust_storage(text, bigint); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.admin_adjust_storage(target_pubkey text, delta_bytes bigint) RETURNS void
LANGUAGE plpgsql SECURITY DEFINER
SET search_path TO 'public'
AS $$
BEGIN
IF NOT public.is_admin() THEN
RAISE EXCEPTION 'not authorized' USING errcode = '42501';
END IF;
INSERT INTO public.pubkey_quotas (user_pubkey, note_count, total_bytes, image_bytes, extra_storage_bytes, updated_at)
VALUES (target_pubkey, 0, 0, 0, greatest(delta_bytes, 0), now())
ON CONFLICT (user_pubkey) DO UPDATE
SET extra_storage_bytes = greatest(public.pubkey_quotas.extra_storage_bytes + delta_bytes, 0),
updated_at = now();
END;
$$;
--
-- Name: admin_ban_pubkey(text, text); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.admin_ban_pubkey(target_pubkey text, p_reason text DEFAULT NULL::text) RETURNS void
LANGUAGE plpgsql SECURITY DEFINER
SET search_path TO 'public'
AS $$
DECLARE
v_admin_pubkey text;
BEGIN
IF NOT public.is_admin() THEN
RAISE EXCEPTION 'not authorized' USING errcode = '42501';
END IF;
v_admin_pubkey := auth.jwt() -> 'app_metadata' ->> 'pubkey';
INSERT INTO public.banned_pubkeys (pubkey, reason, banned_by)
VALUES (target_pubkey, p_reason, v_admin_pubkey)
ON CONFLICT (pubkey) DO UPDATE
SET reason = EXCLUDED.reason, banned_at = now(), banned_by = EXCLUDED.banned_by;
END;
$$;
--
-- Name: admin_cohort_retention(integer); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.admin_cohort_retention(p_weeks integer DEFAULT 12) RETURNS TABLE(cohort_week date, cohort_size integer, w0 integer, w1 integer, w2 integer, w3 integer, w4 integer, w5 integer, w6 integer, w7 integer, w8 integer)
LANGUAGE plpgsql STABLE SECURITY DEFINER
SET search_path TO 'public'
AS $$
BEGIN
IF NOT public.is_admin() THEN
RAISE EXCEPTION 'not authorized' USING errcode = '42501';
END IF;
IF p_weeks < 1 THEN p_weeks := 1; END IF;
IF p_weeks > 52 THEN p_weeks := 52; END IF;
RETURN QUERY
WITH cohorts AS (
SELECT
date_trunc('week', u.created_at)::date AS cw,
(u.raw_app_meta_data ->> 'pubkey') AS pk
FROM auth.users u
WHERE (u.raw_app_meta_data ->> 'pubkey') IS NOT NULL
AND u.created_at >= now() - (p_weeks * interval '1 week')
),
activity AS (
SELECT DISTINCT pubkey AS pk, date_trunc('week', last_seen_at)::date AS aw
FROM public.devices
WHERE last_seen_at >= now() - ((p_weeks + 9) * interval '1 week')
)
SELECT
c.cw AS cohort_week,
count(DISTINCT c.pk)::int AS cohort_size,
count(DISTINCT CASE WHEN a.aw = c.cw THEN c.pk END)::int AS w0,
count(DISTINCT CASE WHEN a.aw = (c.cw + interval '1 week')::date THEN c.pk END)::int AS w1,
count(DISTINCT CASE WHEN a.aw = (c.cw + interval '2 weeks')::date THEN c.pk END)::int AS w2,
count(DISTINCT CASE WHEN a.aw = (c.cw + interval '3 weeks')::date THEN c.pk END)::int AS w3,
count(DISTINCT CASE WHEN a.aw = (c.cw + interval '4 weeks')::date THEN c.pk END)::int AS w4,
count(DISTINCT CASE WHEN a.aw = (c.cw + interval '5 weeks')::date THEN c.pk END)::int AS w5,
count(DISTINCT CASE WHEN a.aw = (c.cw + interval '6 weeks')::date THEN c.pk END)::int AS w6,
count(DISTINCT CASE WHEN a.aw = (c.cw + interval '7 weeks')::date THEN c.pk END)::int AS w7,
count(DISTINCT CASE WHEN a.aw = (c.cw + interval '8 weeks')::date THEN c.pk END)::int AS w8
FROM cohorts c
LEFT JOIN activity a ON a.pk = c.pk
GROUP BY c.cw
ORDER BY c.cw DESC;
END;
$$;
--
-- Name: admin_db_health(); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.admin_db_health() RETURNS jsonb
LANGUAGE plpgsql STABLE SECURITY DEFINER
SET search_path TO 'public'
AS $$
DECLARE
result jsonb;
BEGIN
IF NOT public.is_admin() THEN
RAISE EXCEPTION 'not authorized' USING errcode = '42501';
END IF;
SELECT jsonb_build_object(
'db_size', pg_database_size(current_database()),
'notes_table_size', pg_total_relation_size('public.notes'),
'notes_index_size', pg_indexes_size('public.notes'),
'devices_table_size', pg_total_relation_size('public.devices'),
'quotas_table_size', pg_total_relation_size('public.pubkey_quotas'),
'versions_table_size', CASE
WHEN to_regclass('public.note_versions') IS NOT NULL
THEN pg_total_relation_size('public.note_versions')
ELSE 0
END,
'cache_table_size', pg_total_relation_size('public.admin_cache'),
'auth_users_count', (SELECT count(*) FROM auth.users)
) INTO result;
RETURN result;
END;
$$;
--
-- Name: admin_delete_timeline_event(uuid); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.admin_delete_timeline_event(target_id uuid) RETURNS void
LANGUAGE plpgsql SECURITY DEFINER
SET search_path TO 'public'
AS $$
begin
if not public.is_admin() then
raise exception 'not authorized' using errcode = '42501';
end if;
delete from public.timeline_events where id = target_id;
end;
$$;
--
-- Name: admin_device_names_breakdown(); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.admin_device_names_breakdown() RETURNS TABLE(device_name text, total bigint, active_30d bigint)
LANGUAGE plpgsql STABLE SECURITY DEFINER
SET search_path TO 'public'
AS $$
BEGIN
IF NOT public.is_admin() THEN
RAISE EXCEPTION 'not authorized' USING errcode = '42501';
END IF;
RETURN QUERY
SELECT
d.device_name,
count(*)::bigint AS total,
count(*) FILTER (WHERE d.last_seen_at > now() - interval '30 days')::bigint AS active_30d
FROM public.devices d
GROUP BY d.device_name
ORDER BY total DESC;
END;
$$;
--
-- Name: admin_events_summary(); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.admin_events_summary() RETURNS TABLE(type text, source text, count bigint)
LANGUAGE plpgsql STABLE SECURITY DEFINER
SET search_path TO 'public'
AS $$
begin
if not public.is_admin() then
raise exception 'not authorized' using errcode = '42501';
end if;
return query
select e.type, e.source, count(*)::bigint
from public.admin_events e
group by e.type, e.source
order by e.type, count(*) desc;
end;
$$;
--
-- Name: admin_feature_adoption(); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.admin_feature_adoption() RETURNS jsonb
LANGUAGE plpgsql STABLE SECURITY DEFINER
SET search_path TO 'public'
AS $$
DECLARE
result jsonb;
v_multi_device bigint := 0;
v_history_users bigint := 0;
v_image_users bigint := 0;
v_burn_users bigint := 0;
v_total_users bigint := 0;
BEGIN
IF NOT public.is_admin() THEN
RAISE EXCEPTION 'not authorized' USING errcode = '42501';
END IF;
SELECT count(DISTINCT (raw_app_meta_data ->> 'pubkey'))
INTO v_total_users
FROM auth.users
WHERE (raw_app_meta_data ->> 'pubkey') IS NOT NULL;
-- Multi-device users
SELECT count(*) INTO v_multi_device
FROM (SELECT pubkey FROM public.devices GROUP BY pubkey HAVING count(*) > 1) sub;
-- Note history users (Pro feature)
IF to_regclass('public.note_versions') IS NOT NULL THEN
EXECUTE 'SELECT count(DISTINCT n.user_pubkey) FROM public.note_versions nv JOIN public.notes n ON n.id = nv.note_id'
INTO v_history_users;
END IF;
-- Image users
SELECT count(*) INTO v_image_users
FROM public.pubkey_quotas WHERE image_bytes > 0;
-- Burn note users
IF to_regclass('public.burn_notes') IS NOT NULL THEN
EXECUTE 'SELECT count(DISTINCT user_pubkey) FROM public.burn_notes'
INTO v_burn_users;
END IF;
SELECT jsonb_build_object(
'total_users', v_total_users,
'multi_device', v_multi_device,
'note_history', v_history_users,
'images', v_image_users,
'burn_notes', v_burn_users
) INTO result;
RETURN result;
END;
$$;
--
-- Name: admin_force_refresh_cache(); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.admin_force_refresh_cache() RETURNS void
LANGUAGE plpgsql SECURITY DEFINER
SET search_path TO 'public'
AS $$
BEGIN
IF NOT public.is_admin() THEN
RAISE EXCEPTION 'not authorized' USING errcode = '42501';
END IF;
PERFORM public.admin_refresh_cache();
END;
$$;
--
-- Name: admin_fp_anomalies(); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.admin_fp_anomalies() RETURNS TABLE(pubkey text, anomaly_type text, device_count bigint, detail text, is_pro boolean)
LANGUAGE plpgsql STABLE SECURITY DEFINER
SET search_path TO 'public'
AS $$
BEGIN
IF NOT public.is_admin() THEN
RAISE EXCEPTION 'not authorized' USING errcode = '42501';
END IF;
-- Duplicate fingerprints: multiple active devices with identical
-- (platform, gpu, cores) hashes for the same pubkey. Should not
-- happen after dedup - indicates a bug or manipulation.
RETURN QUERY
SELECT
d.pubkey,
'duplicate_fingerprint'::text AS anomaly_type,
count(*)::bigint AS device_count,
'duplicate device fingerprint detected'::text AS detail,
EXISTS(SELECT 1 FROM pro_pubkeys pp WHERE pp.pubkey = d.pubkey) AS is_pro
FROM public.devices d
WHERE d.revoked_at IS NULL
AND d.fp_platform_hash IS NOT NULL
GROUP BY d.pubkey, d.fp_platform_hash, d.fp_gpu_hash, d.fp_cores_hash
HAVING count(*) > 1;
-- Null GPU hash: WebGL blocked (Brave, restricted modes) or bot.
-- Only flag if multiple devices on the same pubkey lack GPU data.
RETURN QUERY
SELECT
d.pubkey,
'null_gpu'::text AS anomaly_type,
count(*)::bigint AS device_count,
'GPU unavailable on ' || count(*)::text || ' device(s)' AS detail,
EXISTS(SELECT 1 FROM pro_pubkeys pp WHERE pp.pubkey = d.pubkey) AS is_pro
FROM public.devices d
WHERE d.revoked_at IS NULL
AND d.fp_platform_hash IS NOT NULL
AND d.fp_gpu_hash IS NULL
GROUP BY d.pubkey
HAVING count(*) >= 2;
END;
$$;
--
-- Name: admin_get_cached(text); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.admin_get_cached(p_key text) RETURNS jsonb
LANGUAGE plpgsql STABLE SECURITY DEFINER
SET search_path TO 'public'
AS $$
DECLARE
v_result jsonb;
v_age interval;
BEGIN
IF NOT public.is_admin() THEN
RAISE EXCEPTION 'not authorized' USING errcode = '42501';
END IF;
SELECT payload, now() - computed_at
INTO v_result, v_age
FROM public.admin_cache
WHERE key = p_key;
-- Return null if missing or older than 12 hours (2x the refresh interval).
IF v_result IS NULL OR v_age > interval '12 hours' THEN
RETURN NULL;
END IF;
RETURN v_result;
END;
$$;
--
-- Name: admin_list_admins(); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.admin_list_admins() RETURNS TABLE(pubkey text, label text, created_at timestamp with time zone)
LANGUAGE plpgsql STABLE SECURITY DEFINER
SET search_path TO 'public'
AS $$
begin
if not public.is_admin() then
raise exception 'not authorized' using errcode = '42501';
end if;
return query
select a.pubkey, a.label, a.created_at
from public.admin_pubkeys a
order by a.created_at asc;
end;
$$;
--
-- Name: admin_list_banned(); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.admin_list_banned() RETURNS TABLE(pubkey text, reason text, banned_at timestamp with time zone, banned_by text)
LANGUAGE plpgsql STABLE SECURITY DEFINER
SET search_path TO 'public'
AS $$
BEGIN
IF NOT public.is_admin() THEN
RAISE EXCEPTION 'not authorized' USING errcode = '42501';
END IF;
RETURN QUERY
SELECT bp.pubkey, bp.reason, bp.banned_at, bp.banned_by
FROM public.banned_pubkeys bp
ORDER BY bp.banned_at DESC;
END;
$$;
SET default_tablespace = '';
SET default_table_access_method = heap;
--
-- Name: devices; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.devices (
pubkey text NOT NULL,
device_id text NOT NULL,
device_name text DEFAULT 'Unknown device'::text NOT NULL,
platform text DEFAULT 'web'::text NOT NULL,
created_at timestamp with time zone DEFAULT now() NOT NULL,
last_seen_at timestamp with time zone DEFAULT now() NOT NULL,
revoked_at timestamp with time zone,
device_group text,
fp_platform_hash text,
fp_gpu_hash text,
fp_cores_hash text,
fp_language_hash text
);
--
-- Name: COLUMN devices.device_group; Type: COMMENT; Schema: public; Owner: -
--
COMMENT ON COLUMN public.devices.device_group IS 'Groups browser installs on the same physical device. Limit check counts DISTINCT device_group values. NULL = own slot.';
--
-- Name: COLUMN devices.fp_platform_hash; Type: COMMENT; Schema: public; Owner: -
--
COMMENT ON COLUMN public.devices.fp_platform_hash IS 'HMAC-SHA256(fp_pepper, "platform:" || normalized_os). Pepper is per-user, derived from the BIP-39 seed. Server cannot reverse or cross-user-correlate.';
--
-- Name: COLUMN devices.fp_gpu_hash; Type: COMMENT; Schema: public; Owner: -
--
COMMENT ON COLUMN public.devices.fp_gpu_hash IS 'HMAC-SHA256(fp_pepper, "gpu:" || webgl_renderer). NULL when GPU is unavailable (Brave, restricted contexts) so the server can apply the degraded matching threshold.';
--
-- Name: COLUMN devices.fp_cores_hash; Type: COMMENT; Schema: public; Owner: -
--
COMMENT ON COLUMN public.devices.fp_cores_hash IS 'HMAC-SHA256(fp_pepper, "cores:" || navigator.hardwareConcurrency).';
--
-- Name: COLUMN devices.fp_language_hash; Type: COMMENT; Schema: public; Owner: -
--
COMMENT ON COLUMN public.devices.fp_language_hash IS 'HMAC-SHA256(fp_pepper, "language:" || navigator.language).';
--
-- Name: admin_list_devices_for_pubkey(text); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.admin_list_devices_for_pubkey(target_pubkey text) RETURNS SETOF public.devices
LANGUAGE plpgsql STABLE SECURITY DEFINER
SET search_path TO 'public'
AS $$
begin
if not public.is_admin() then
raise exception 'not authorized' using errcode = '42501';
end if;
return query
select *
from public.devices
where pubkey = target_pubkey
order by last_seen_at desc;
end;
$$;
--
-- Name: admin_list_pro_users(integer, integer); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.admin_list_pro_users(p_page integer DEFAULT 0, p_per_page integer DEFAULT 20) RETURNS TABLE(pubkey text, source text, amount_cents integer, created_at timestamp with time zone)
LANGUAGE plpgsql STABLE SECURITY DEFINER
SET search_path TO 'public'
AS $$
BEGIN
IF NOT public.is_admin() THEN