@rocapine/community 0.15.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rocapine/community",
3
- "version": "0.15.0",
3
+ "version": "0.17.0",
4
4
  "description": "CLI to install, upgrade and adopt the Rocapine Community SDK's Supabase backend (migrations, Edge Functions) into a project.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -0,0 +1,17 @@
1
+ // Members blocked either way with `uid` (core/016_mutual_blocks.sql): a push
2
+ // never names, counts or comes from one of them. Service-role client, so both
3
+ // directions are readable.
4
+ export async function blockedWith(
5
+ supabase: { from: (table: string) => any },
6
+ uid: string,
7
+ ): Promise<Set<string>> {
8
+ const { data } = await supabase
9
+ .from("blocks")
10
+ .select("blocker_id, blocked_id")
11
+ .or(`blocker_id.eq.${uid},blocked_id.eq.${uid}`);
12
+ return new Set(
13
+ ((data ?? []) as { blocker_id: string; blocked_id: string }[]).map((b) =>
14
+ b.blocker_id === uid ? b.blocked_id : b.blocker_id,
15
+ ),
16
+ );
17
+ }
@@ -1,6 +1,7 @@
1
1
  // Shared Expo push sender. Used by notify-comment, notify-like,
2
2
  // notify-reaction and broadcast-post (push module).
3
3
 
4
+ import { blockedWith } from "./blocks.ts";
4
5
  import { runPool } from "./translation.ts";
5
6
 
6
7
  export interface ExpoPushMessage {
@@ -13,9 +14,10 @@ export interface ExpoPushMessage {
13
14
  badge?: number;
14
15
  }
15
16
 
16
- /** Unread inbox rows for `uid` (newer than the seen marker and not read one by one),
17
- * capped at 200, at least 1 since a push
18
- * is being sent. Falls back to 1 when the inbox module is not installed. */
17
+ /** Unread inbox items for `uid`, counted like the app's `unreadCount`: notification
18
+ * rows (minus those from a member blocked either way) and admin posts sent to
19
+ * everyone, newer than the seen marker and not read one by one. Capped at 200, at
20
+ * least 1 since a push is being sent. Falls back to 1 when the inbox module is not installed. */
19
21
  export async function unreadBadge(
20
22
  supabase: { from: (table: string) => any },
21
23
  uid: string,
@@ -26,11 +28,30 @@ export async function unreadBadge(
26
28
  .select("seen_at")
27
29
  .eq("user_id", uid)
28
30
  .maybeSingle();
29
- let query = supabase.from("notifications").select("id").eq("user_id", uid).limit(200);
31
+ let query = supabase.from("notifications").select("id, actor_id").eq("user_id", uid).limit(200);
30
32
  if (seen?.seen_at) query = query.gt("created_at", seen.seen_at);
31
33
  const { data: rows, error } = await query;
32
34
  if (error) return 1;
33
- const ids = (rows ?? []).map((r: { id: string }) => r.id);
35
+ // Admin posts sent to everyone are listed in the center too, for 90 days
36
+ // (inbox/003_pushed_admin_posts.sql); a broadcast counts the post it sends.
37
+ const since = Math.max(
38
+ seen?.seen_at ? Date.parse(seen.seen_at) : 0,
39
+ Date.now() - 90 * 24 * 3600 * 1000,
40
+ );
41
+ const { data: official } = await supabase
42
+ .from("posts")
43
+ .select("id")
44
+ .eq("status", "visible")
45
+ .neq("author_id", uid)
46
+ .gt("broadcast_at", new Date(since).toISOString())
47
+ .limit(200);
48
+ // Notification rows follow the same block rule as list_notifications
49
+ // (inbox/004_mutual_blocks.sql); admins are never hidden by a block.
50
+ const hidden = await blockedWith(supabase, uid);
51
+ const own = ((rows ?? []) as { id: string; actor_id: string | null }[]).filter(
52
+ (r) => !r.actor_id || !hidden.has(r.actor_id),
53
+ );
54
+ const ids = [...own, ...(official ?? [])].map((r: { id: string }) => r.id).slice(0, 200);
34
55
  if (ids.length === 0) return 1;
35
56
  // Items marked read one by one (inbox/002_replies_and_reads.sql); a project
36
57
  // without that table just counts every row past the watermark.
@@ -45,6 +66,21 @@ export async function unreadBadge(
45
66
  }
46
67
  }
47
68
 
69
+ /** `unreadBadge` for each distinct user, `concurrency` at a time (broadcast-post).
70
+ * shortcut: 4 queries per user, fine for a few thousand members; past ~20k, move
71
+ * the count into one SQL function per page. */
72
+ export async function unreadBadges(
73
+ supabase: { from: (table: string) => any },
74
+ uids: string[],
75
+ concurrency = 20,
76
+ ): Promise<Map<string, number>> {
77
+ const badges = new Map<string, number>();
78
+ await runPool([...new Set(uids)], concurrency, async (uid) => {
79
+ badges.set(uid, await unreadBadge(supabase, uid));
80
+ });
81
+ return badges;
82
+ }
83
+
48
84
  // Sends in chunks of 100 (Expo API limit), 4 requests in flight at a time, each
49
85
  // aborted after 10 s so one hung request can't stall a large broadcast past the
50
86
  // function's wall-clock limit. Best-effort: push failures must never fail the
@@ -5,11 +5,12 @@
5
5
  // read, and an anon call sends nothing unless the post's admin author asked for it
6
6
  // (core/013_post_broadcasts.sql). `broadcast_at` is claimed before sending, so a
7
7
  // post goes out once and the inbox lists exactly the posts that were sent.
8
- // Sends an Expo push to every registered token (batches of 100) but the author's.
8
+ // Sends an Expo push to every registered token (batches of 100) but the author's,
9
+ // each with its member's own unread count as the icon badge.
9
10
 
10
11
  import { adminClient, fetchAllRows, isServiceCaller } from "../_shared/client.ts";
11
12
  import { excerptOrPhoto, pushCopy } from "../_shared/copy.ts";
12
- import { sendExpoPushBatch } from "../_shared/push.ts";
13
+ import { sendExpoPushBatch, unreadBadges } from "../_shared/push.ts";
13
14
  import { BROADCAST_FALLBACK_TITLE } from "../_shared/config.ts";
14
15
  import { ensureTranslations, resolveTargetLocale, TARGET_LOCALES } from "../_shared/translation.ts";
15
16
 
@@ -75,10 +76,11 @@ Deno.serve(async (req) => {
75
76
  const seen = new Set<string>(
76
77
  rows.filter((r) => r.user_id === post.author_id).map((r) => r.expo_push_token as string),
77
78
  );
78
- const messages = rows
79
+ const recipients = rows
79
80
  .map((r) => {
80
81
  const profile = Array.isArray(r.profiles) ? r.profiles[0] : r.profiles;
81
82
  return {
83
+ uid: r.user_id as string,
82
84
  to: r.expo_push_token as string,
83
85
  profileLocale: (profile?.locale ?? null) as string | null,
84
86
  locale: resolveTargetLocale(profile?.locale ?? null),
@@ -89,14 +91,18 @@ Deno.serve(async (req) => {
89
91
  if (!m.to || seen.has(m.to)) return false;
90
92
  seen.add(m.to);
91
93
  return true;
92
- })
93
- .map(({ to, locale, profileLocale }) => ({
94
- to,
95
- title,
96
- body: excerptFor(locale, profileLocale),
97
- data: { route: "/community", kind: "community_admin_post", postId: post.id },
98
- badge: 1,
99
- }));
94
+ });
95
+ const badges = await unreadBadges(
96
+ supabase,
97
+ recipients.map((m) => m.uid),
98
+ );
99
+ const messages = recipients.map(({ uid, to, locale, profileLocale }) => ({
100
+ to,
101
+ title,
102
+ body: excerptFor(locale, profileLocale),
103
+ data: { route: "/community", kind: "community_admin_post", postId: post.id },
104
+ badge: badges.get(uid) ?? 1,
105
+ }));
100
106
  await sendExpoPushBatch(messages);
101
107
 
102
108
  return new Response(JSON.stringify({ sent: messages.length }), {
@@ -1,7 +1,7 @@
1
1
  // Real-time comment notification: a pg_net trigger fires here when a comment
2
2
  // becomes visible (published). We push to the post author, or for a reply to
3
3
  // the author of the comment it answers only (unless self, opted out, no token,
4
- // or the recipient has blocked the commenter).
4
+ // or the recipient and the commenter are blocked either way).
5
5
  //
6
6
  // Security: this function is reachable with the public anon key (the trigger
7
7
  // calls it that way), so the body is UNTRUSTED. Only `record.id` is used; the
@@ -9,6 +9,7 @@
9
9
  // push comes from the request itself.
10
10
 
11
11
  import { adminClient } from "../_shared/client.ts";
12
+ import { blockedWith } from "../_shared/blocks.ts";
12
13
  import { sendExpoPush, unreadBadge } from "../_shared/push.ts";
13
14
  import { excerptOrPhoto, pushCopy } from "../_shared/copy.ts";
14
15
  import { ensureTranslations, resolveTargetLocale, languageOf } from "../_shared/translation.ts";
@@ -75,13 +76,7 @@ Deno.serve(async (req) => {
75
76
  .single();
76
77
  if (!pref?.expo_push_token || !pref.notify_comments) return;
77
78
 
78
- const { data: blocked } = await supabase
79
- .from("blocks")
80
- .select("blocker_id")
81
- .eq("blocker_id", target.uid)
82
- .eq("blocked_id", comment!.author_id)
83
- .maybeSingle();
84
- if (blocked) return;
79
+ if ((await blockedWith(supabase, target.uid)).has(comment!.author_id)) return;
85
80
 
86
81
  const { data: recipient } = await supabase
87
82
  .from("profiles")
@@ -11,6 +11,7 @@
11
11
  // notifications early.
12
12
 
13
13
  import { adminClient } from "../_shared/client.ts";
14
+ import { blockedWith } from "../_shared/blocks.ts";
14
15
  import { sendExpoPush, unreadBadge } from "../_shared/push.ts";
15
16
  import { pushCopy } from "../_shared/copy.ts";
16
17
 
@@ -48,12 +49,8 @@ async function flushPost(postId: string) {
48
49
 
49
50
  if (!pref?.expo_push_token || !pref.notify_likes) return;
50
51
 
51
- // Contributors = likers who are not the author and not blocked by the author.
52
- const { data: blocks } = await supabase
53
- .from("blocks")
54
- .select("blocked_id")
55
- .eq("blocker_id", post.author_id);
56
- const blockedSet = new Set((blocks ?? []).map((b) => b.blocked_id as string));
52
+ // Contributors = likers who are not the author and not blocked either way.
53
+ const blockedSet = await blockedWith(supabase, post.author_id);
57
54
  const contributors = unnotified.filter(
58
55
  (l) => l.user_id !== post.author_id && !blockedSet.has(l.user_id as string),
59
56
  );
@@ -15,6 +15,7 @@
15
15
  // untrusted body; everything else comes from post_reactions.
16
16
 
17
17
  import { adminClient } from "../_shared/client.ts";
18
+ import { blockedWith } from "../_shared/blocks.ts";
18
19
  import { sendExpoPush, unreadBadge } from "../_shared/push.ts";
19
20
  import { pushCopy } from "../_shared/copy.ts";
20
21
 
@@ -55,11 +56,7 @@ async function flushPost(postId: string) {
55
56
 
56
57
  if (!pref?.expo_push_token || !pref.notify_reactions) return;
57
58
 
58
- const { data: blocks } = await supabase
59
- .from("blocks")
60
- .select("blocked_id")
61
- .eq("blocker_id", post.author_id);
62
- const blockedSet = new Set((blocks ?? []).map((b) => b.blocked_id as string));
59
+ const blockedSet = await blockedWith(supabase, post.author_id);
63
60
  const contributors = unnotified.filter(
64
61
  (l) => l.user_id !== post.author_id && !blockedSet.has(l.user_id as string),
65
62
  );
@@ -0,0 +1,116 @@
1
+ -- community-sdk core/014_post_drafts.sql (schema v1)
2
+ -- Shared post drafts for the community dashboard (service role only): the team
3
+ -- writes a post under a team account, edits it together (`version` guards
4
+ -- concurrent saves), then publishes it with publish_post_draft. Publishing skips
5
+ -- moderation (the team wrote it), applies pin and "notify everyone", copies the
6
+ -- poll, attachment or image, deletes the draft and logs `publish_post`.
7
+ -- Clients never see this table. Fully idempotent.
8
+
9
+ create table if not exists public.post_drafts (
10
+ id uuid primary key default gen_random_uuid(),
11
+ author_id uuid references public.profiles(id) on delete set null,
12
+ topic text,
13
+ content text not null default '' check (char_length(content) <= 2000),
14
+ image_path text,
15
+ image_width int,
16
+ image_height int,
17
+ poll_options text[],
18
+ attachment jsonb,
19
+ notify boolean not null default false,
20
+ pin boolean not null default false,
21
+ publish_at timestamptz,
22
+ version int not null default 1,
23
+ created_by text not null,
24
+ updated_by text not null,
25
+ created_at timestamptz not null default now(),
26
+ updated_at timestamptz not null default now()
27
+ );
28
+ alter table public.post_drafts enable row level security;
29
+ -- No policy: readable only by the service role.
30
+ revoke all on table public.post_drafts from public, anon, authenticated;
31
+
32
+ alter table public.moderation_actions drop constraint if exists moderation_actions_action_check;
33
+ alter table public.moderation_actions add constraint moderation_actions_action_check check (action in
34
+ ('hide','restore','confirm_hide','reject_report','ban','unban',
35
+ 'publish_post','create_team_account','update_team_account'));
36
+
37
+ -- Errors are raised with the code as the message (errcode P0001): draft_not_found,
38
+ -- draft_changed, not_a_team_account, author_banned, not_admin, invalid_content,
39
+ -- invalid_image, invalid_poll, invalid_attachment, one_extra_only. Columns of
40
+ -- optional modules (images, attachments) are only named when the draft uses
41
+ -- them, so a backend without those modules still publishes plain and poll drafts.
42
+ create or replace function public.publish_post_draft(p_draft_id uuid, p_version int, p_actor text)
43
+ returns uuid
44
+ language plpgsql security definer set search_path = public
45
+ as $$
46
+ declare
47
+ d post_drafts;
48
+ author profiles;
49
+ new_id uuid;
50
+ n int;
51
+ i int;
52
+ begin
53
+ select * into d from post_drafts where id = p_draft_id for update;
54
+ if not found then raise exception 'draft_not_found'; end if;
55
+ if d.version is distinct from p_version then raise exception 'draft_changed'; end if;
56
+
57
+ select * into author from profiles where id = d.author_id;
58
+ if not found or not author.is_house then raise exception 'not_a_team_account'; end if;
59
+ if author.is_banned then raise exception 'author_banned'; end if;
60
+ if (d.pin or d.notify) and not author.is_admin then raise exception 'not_admin'; end if;
61
+
62
+ -- Like posts_content_check: text is optional when there is an image.
63
+ if char_length(d.content) > 2000 or (char_length(d.content) = 0 and d.image_path is null) then
64
+ raise exception 'invalid_content';
65
+ end if;
66
+ -- Mirrors posts_image_check and posts_image_path_format (images/001). The image lives
67
+ -- in the author's storage folder; the dashboard moves it when the author changes.
68
+ if d.image_path is not null and (coalesce(d.image_width, 0) <= 0 or coalesce(d.image_height, 0) <= 0
69
+ or d.image_path !~ '^[0-9a-f-]{36}/[A-Za-z0-9_-]+\.jpg$'
70
+ or split_part(d.image_path, '/', 1) <> d.author_id::text) then
71
+ raise exception 'invalid_image';
72
+ end if;
73
+ n := coalesce(array_length(d.poll_options, 1), 0);
74
+ if d.poll_options is not null and (n not between 2 and 4
75
+ or exists (select 1 from unnest(d.poll_options) l where coalesce(char_length(l), 0) not between 1 and 60)) then
76
+ raise exception 'invalid_poll';
77
+ end if;
78
+ -- Mirrors posts_attachment_check (attachments/001); coalesce because a null check result would pass.
79
+ if d.attachment is not null and not coalesce(jsonb_typeof(d.attachment) = 'object'
80
+ and d.attachment ? 'type' and d.attachment ? 'id'
81
+ and jsonb_typeof(d.attachment -> 'type') = 'string' and jsonb_typeof(d.attachment -> 'id') = 'string'
82
+ and octet_length(d.attachment::text) <= 512, false) then
83
+ raise exception 'invalid_attachment';
84
+ end if;
85
+ if (d.image_path is not null)::int + (d.poll_options is not null)::int + (d.attachment is not null)::int > 1 then
86
+ raise exception 'one_extra_only';
87
+ end if;
88
+
89
+ -- The image goes in the insert itself: an image-only post needs it to pass posts_content_check.
90
+ if d.image_path is not null then
91
+ insert into posts (author_id, topic, content, status, moderated_at, broadcast_requested, pinned_at,
92
+ image_path, image_width, image_height)
93
+ values (d.author_id, d.topic, d.content, 'visible', now(), d.notify, case when d.pin then now() end,
94
+ d.image_path, d.image_width, d.image_height)
95
+ returning id into new_id;
96
+ else
97
+ insert into posts (author_id, topic, content, status, moderated_at, broadcast_requested, pinned_at)
98
+ values (d.author_id, d.topic, d.content, 'visible', now(), d.notify, case when d.pin then now() end)
99
+ returning id into new_id;
100
+ end if;
101
+ if d.attachment is not null then
102
+ update posts set attachment = d.attachment where id = new_id;
103
+ end if;
104
+ for i in 1..n loop
105
+ insert into poll_options (post_id, idx, label) values (new_id, i - 1, d.poll_options[i]);
106
+ end loop;
107
+
108
+ delete from post_drafts where id = d.id;
109
+ insert into moderation_actions (actor_email, action, target_post_id, target_user_id)
110
+ values (p_actor, 'publish_post', new_id, d.author_id);
111
+ return new_id;
112
+ end;
113
+ $$;
114
+
115
+ revoke execute on function public.publish_post_draft(uuid, int, text) from public, anon, authenticated;
116
+ grant execute on function public.publish_post_draft(uuid, int, text) to service_role;
@@ -0,0 +1,273 @@
1
+ -- community-sdk core/015_scheduled_posts.sql (schema v1)
2
+ -- Scheduled posts for the community dashboard (service role only): a draft gets a
3
+ -- publish_at instant (publish_tz is the zone the team picked, for display only) and
4
+ -- schedule_post_draft sets or clears it. A draft can carry a planned time without being armed:
5
+ -- armed means scheduled_by is not null, and only armed drafts are published by the cron.
6
+ -- Planning a time checks the time and the event window; arming validates the whole post.
7
+ -- check_post_draft holds the validation that publish_post_draft and the scheduler share.
8
+ -- Requires core/014. Fully idempotent.
9
+ -- topic_from / topic_until (nullable dates, until exclusive) hold the date window of an event
10
+ -- topic, which lives in the dashboard's config; the dashboard writes them with the topic.
11
+
12
+ alter table public.post_drafts add column if not exists scheduled_by text;
13
+ alter table public.post_drafts add column if not exists publish_tz text;
14
+ alter table public.post_drafts add column if not exists publish_error text;
15
+ alter table public.post_drafts add column if not exists failed_at timestamptz;
16
+ alter table public.post_drafts add column if not exists topic_from date;
17
+ alter table public.post_drafts add column if not exists topic_until date;
18
+
19
+ -- Only armed drafts are due; the predicate changed in the planned-time revision, so recreate it.
20
+ drop index if exists public.post_drafts_due_idx;
21
+ create index post_drafts_due_idx on public.post_drafts (publish_at)
22
+ where publish_at is not null and publish_error is null and scheduled_by is not null;
23
+
24
+ alter table public.moderation_actions drop constraint if exists moderation_actions_action_check;
25
+ alter table public.moderation_actions add constraint moderation_actions_action_check check (action in
26
+ ('hide','restore','confirm_hide','reject_report','ban','unban',
27
+ 'publish_post','create_team_account','update_team_account','schedule_post'));
28
+
29
+ -- The event-window part of the check, alone (it needs d.publish_tz): the local date the post goes
30
+ -- out in the draft's zone must fall in [topic_from, topic_until). A draft without a zone is guarded
31
+ -- by the dashboard only. Raises topic_closed.
32
+ create or replace function public.check_post_draft_window(d post_drafts, p_at timestamptz default null)
33
+ returns void
34
+ language plpgsql security definer set search_path = public
35
+ as $$
36
+ begin
37
+ if d.publish_tz is not null and (d.topic_from is not null or d.topic_until is not null)
38
+ and ((coalesce(p_at, now()) at time zone d.publish_tz)::date < d.topic_from
39
+ or (coalesce(p_at, now()) at time zone d.publish_tz)::date >= d.topic_until) then
40
+ raise exception 'topic_closed';
41
+ end if;
42
+ end;
43
+ $$;
44
+
45
+ revoke execute on function public.check_post_draft_window(post_drafts, timestamptz) from public, anon, authenticated;
46
+
47
+ -- Raises the publish error codes (errcode P0001, code as message): not_a_team_account,
48
+ -- author_banned, not_admin, invalid_content, invalid_image, invalid_poll,
49
+ -- invalid_attachment, one_extra_only, invalid_topic, topic_closed. Callers are security definer; nobody else may run it.
50
+ -- Takes the instant the post goes out (default now) for the event window: publishing checks it at
51
+ -- that moment, scheduling checks the chosen time. Replaces the one-argument version of earlier runs.
52
+ drop function if exists public.check_post_draft(post_drafts);
53
+ create or replace function public.check_post_draft(d post_drafts, p_at timestamptz default null)
54
+ returns void
55
+ language plpgsql security definer set search_path = public
56
+ as $$
57
+ declare
58
+ author profiles;
59
+ n int;
60
+ begin
61
+ select * into author from profiles where id = d.author_id;
62
+ if not found or not author.is_house then raise exception 'not_a_team_account'; end if;
63
+ if author.is_banned then raise exception 'author_banned'; end if;
64
+ if (d.pin or d.notify) and not author.is_admin then raise exception 'not_admin'; end if;
65
+
66
+ -- Like posts_content_check: text is optional when there is an image.
67
+ if char_length(d.content) > 2000 or (char_length(d.content) = 0 and d.image_path is null) then
68
+ raise exception 'invalid_content';
69
+ end if;
70
+ -- Mirrors posts_image_check and posts_image_path_format (images/001). The image lives
71
+ -- in the author's storage folder; the dashboard moves it when the author changes.
72
+ if d.image_path is not null and (coalesce(d.image_width, 0) <= 0 or coalesce(d.image_height, 0) <= 0
73
+ or d.image_path !~ '^[0-9a-f-]{36}/[A-Za-z0-9_-]+\.jpg$'
74
+ or split_part(d.image_path, '/', 1) <> d.author_id::text) then
75
+ raise exception 'invalid_image';
76
+ end if;
77
+ n := coalesce(array_length(d.poll_options, 1), 0);
78
+ if d.poll_options is not null and (n not between 2 and 4
79
+ or exists (select 1 from unnest(d.poll_options) l where coalesce(char_length(l), 0) not between 1 and 60)) then
80
+ raise exception 'invalid_poll';
81
+ end if;
82
+ -- Mirrors posts_attachment_check (attachments/001); coalesce because a null check result would pass.
83
+ if d.attachment is not null and not coalesce(jsonb_typeof(d.attachment) = 'object'
84
+ and d.attachment ? 'type' and d.attachment ? 'id'
85
+ and jsonb_typeof(d.attachment -> 'type') = 'string' and jsonb_typeof(d.attachment -> 'id') = 'string'
86
+ and octet_length(d.attachment::text) <= 512, false) then
87
+ raise exception 'invalid_attachment';
88
+ end if;
89
+ if (d.image_path is not null)::int + (d.poll_options is not null)::int + (d.attachment is not null)::int > 1 then
90
+ raise exception 'one_extra_only';
91
+ end if;
92
+ -- Topic rules live in the dashboard; here a draft only needs one, so the cron never posts without it.
93
+ if d.topic is null then raise exception 'invalid_topic'; end if;
94
+ perform check_post_draft_window(d, p_at);
95
+ end;
96
+ $$;
97
+
98
+ revoke execute on function public.check_post_draft(post_drafts, timestamptz) from public, anon, authenticated;
99
+
100
+ -- Same checks and codes as 014 (the validation now lives in check_post_draft, which also raises
101
+ -- invalid_topic: a draft needs a topic to go out).
102
+ create or replace function public.publish_post_draft(p_draft_id uuid, p_version int, p_actor text)
103
+ returns uuid
104
+ language plpgsql security definer set search_path = public
105
+ as $$
106
+ declare
107
+ d post_drafts;
108
+ new_id uuid;
109
+ n int;
110
+ i int;
111
+ begin
112
+ select * into d from post_drafts where id = p_draft_id for update;
113
+ if not found then raise exception 'draft_not_found'; end if;
114
+ if d.version is distinct from p_version then raise exception 'draft_changed'; end if;
115
+
116
+ perform check_post_draft(d);
117
+ n := coalesce(array_length(d.poll_options, 1), 0);
118
+
119
+ -- The image goes in the insert itself: an image-only post needs it to pass posts_content_check.
120
+ if d.image_path is not null then
121
+ insert into posts (author_id, topic, content, status, moderated_at, broadcast_requested, pinned_at,
122
+ image_path, image_width, image_height)
123
+ values (d.author_id, d.topic, d.content, 'visible', now(), d.notify, case when d.pin then now() end,
124
+ d.image_path, d.image_width, d.image_height)
125
+ returning id into new_id;
126
+ else
127
+ insert into posts (author_id, topic, content, status, moderated_at, broadcast_requested, pinned_at)
128
+ values (d.author_id, d.topic, d.content, 'visible', now(), d.notify, case when d.pin then now() end)
129
+ returning id into new_id;
130
+ end if;
131
+ if d.attachment is not null then
132
+ update posts set attachment = d.attachment where id = new_id;
133
+ end if;
134
+ for i in 1..n loop
135
+ insert into poll_options (post_id, idx, label) values (new_id, i - 1, d.poll_options[i]);
136
+ end loop;
137
+
138
+ delete from post_drafts where id = d.id;
139
+ insert into moderation_actions (actor_email, action, target_post_id, target_user_id)
140
+ values (p_actor, 'publish_post', new_id, d.author_id);
141
+ return new_id;
142
+ end;
143
+ $$;
144
+
145
+ revoke execute on function public.publish_post_draft(uuid, int, text) from public, anon, authenticated;
146
+ grant execute on function public.publish_post_draft(uuid, int, text) to service_role;
147
+
148
+ -- Plans, arms or clears the schedule of a draft and returns its new version. p_arm = false (with a
149
+ -- time) only plans it: the time, the zone and the event window are checked, not the post, and the
150
+ -- draft stays unarmed (scheduled_by null), so the cron leaves it alone; with the current time it
151
+ -- disarms a draft and keeps its time, with no check (the time may have passed); "the current
152
+ -- time" is compared at millisecond precision, since the dashboard round-trips times through JS
153
+ -- Dates, and p_tz must be the current zone. Re-sending it to an unarmed draft with no error does
154
+ -- nothing. p_arm = true (also when p_arm is null) validates the whole post (check_post_draft)
155
+ -- and arms it. A null p_publish_at clears the time and disarms. Logged (schedule_post) only when the
156
+ -- armed state changes or an armed draft's time changes.
157
+ -- Errors: draft_not_found, draft_changed, invalid_time (also a missing or unknown p_tz), plus the
158
+ -- check_post_draft codes (topic_closed for a time outside the event window). Clearing a draft with
159
+ -- no time, no error and no arming does nothing.
160
+ drop function if exists public.schedule_post_draft(uuid, int, timestamptz, text, text);
161
+ create or replace function public.schedule_post_draft(
162
+ p_draft_id uuid, p_version int, p_publish_at timestamptz, p_tz text, p_actor text, p_arm boolean default true)
163
+ returns int
164
+ language plpgsql security definer set search_path = public
165
+ as $$
166
+ declare
167
+ d post_drafts;
168
+ was_armed boolean;
169
+ now_armed boolean := p_publish_at is not null and coalesce(p_arm, true);
170
+ keep boolean; -- unschedule: disarm and keep the current time, which may be past, so nothing is re-checked
171
+ begin
172
+ select * into d from post_drafts where id = p_draft_id for update;
173
+ if not found then raise exception 'draft_not_found'; end if;
174
+ if d.version is distinct from p_version then raise exception 'draft_changed'; end if;
175
+ was_armed := d.scheduled_by is not null;
176
+ keep := p_publish_at is not null and not coalesce(p_arm, true)
177
+ and date_trunc('milliseconds', p_publish_at) = date_trunc('milliseconds', d.publish_at)
178
+ and p_tz is not distinct from d.publish_tz;
179
+
180
+ if keep then
181
+ if not was_armed and d.publish_error is null then return d.version; end if; -- nothing changes
182
+ elsif p_publish_at is not null then
183
+ if p_publish_at <= now() or p_publish_at > now() + interval '1 year 1 day' then
184
+ raise exception 'invalid_time';
185
+ end if;
186
+ -- The zone is for display only, but it must be an IANA name (not a POSIX string the dashboard can't show).
187
+ if p_tz is null or p_tz not in (select name from pg_timezone_names) then raise exception 'invalid_time'; end if;
188
+ d.publish_tz := p_tz;
189
+ if now_armed then
190
+ perform check_post_draft(d, p_publish_at); -- the whole post, event window included
191
+ else
192
+ perform check_post_draft_window(d, p_publish_at);
193
+ end if;
194
+ elsif d.publish_at is null and d.publish_error is null and not was_armed then
195
+ return d.version; -- nothing to clear
196
+ end if;
197
+
198
+ update post_drafts set
199
+ publish_at = p_publish_at,
200
+ publish_tz = case when p_publish_at is not null then p_tz end,
201
+ scheduled_by = case when now_armed then p_actor end,
202
+ publish_error = null,
203
+ failed_at = null,
204
+ version = version + 1,
205
+ updated_by = p_actor,
206
+ updated_at = now()
207
+ where id = d.id;
208
+
209
+ if was_armed <> now_armed or (now_armed and d.publish_at is distinct from p_publish_at) then
210
+ insert into moderation_actions (actor_email, action, target_user_id, note)
211
+ values (p_actor, 'schedule_post', d.author_id,
212
+ 'draft ' || d.id || case when now_armed
213
+ then ' at ' || to_char(p_publish_at at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') else ' unscheduled' end);
214
+ end if;
215
+ return d.version + 1;
216
+ end;
217
+ $$;
218
+
219
+ revoke execute on function public.schedule_post_draft(uuid, int, timestamptz, text, text, boolean) from public, anon, authenticated;
220
+ grant execute on function public.schedule_post_draft(uuid, int, timestamptz, text, text, boolean) to service_role;
221
+
222
+ -- Publishes the armed drafts (scheduled_by set) whose time has come and returns how many went out. A draft more than
223
+ -- 30 minutes late is marked 'missed' instead; a draft that fails keeps its publish_at and
224
+ -- stores the error (the code for a P0001 error, else the message; cut to 200 characters),
225
+ -- so the next run skips it until the team reschedules it. A transient error (serialization
226
+ -- failure, deadlock, lock not available) leaves the draft untouched to be retried next run;
227
+ -- the 30-minute rule bounds the retries. Run by pg_cron every minute.
228
+ create or replace function public.publish_due_post_drafts()
229
+ returns int
230
+ language plpgsql security definer set search_path = public
231
+ as $$
232
+ declare
233
+ r record;
234
+ n int := 0;
235
+ begin
236
+ for r in
237
+ select id, version, scheduled_by, publish_at from post_drafts
238
+ where publish_at <= now() and publish_error is null and scheduled_by is not null
239
+ order by publish_at for update skip locked
240
+ loop
241
+ if r.publish_at < now() - interval '30 minutes' then
242
+ update post_drafts set publish_error = 'missed', failed_at = now() where id = r.id;
243
+ else
244
+ begin
245
+ perform publish_post_draft(r.id, r.version, r.scheduled_by);
246
+ n := n + 1;
247
+ exception
248
+ when serialization_failure or deadlock_detected or lock_not_available then
249
+ raise log 'publish_due_post_drafts: transient % on draft %', sqlstate, r.id;
250
+ when others then
251
+ update post_drafts set failed_at = now(),
252
+ publish_error = left(sqlerrm, 200)
253
+ where id = r.id;
254
+ end;
255
+ end if;
256
+ end loop;
257
+ return n;
258
+ end;
259
+ $$;
260
+
261
+ revoke execute on function public.publish_due_post_drafts() from public, anon, authenticated, service_role;
262
+
263
+ do $$
264
+ begin
265
+ perform cron.schedule('post-drafts-publish', '* * * * *', $cron$ select public.publish_due_post_drafts(); $cron$);
266
+ exception when others then
267
+ if sqlerrm like '%already exists%' then
268
+ raise notice 'cron job post-drafts-publish already scheduled, skipping';
269
+ else
270
+ raise;
271
+ end if;
272
+ end;
273
+ $$;
@@ -0,0 +1,149 @@
1
+ -- community-sdk core/016_mutual_blocks.sql (schema v1)
2
+ -- A block now works both ways: once A blocks B, neither sees the other's posts,
3
+ -- comments, likes or profile, and neither can comment, reply or like on the
4
+ -- other's content. Until now only the blocker stopped seeing the blocked member,
5
+ -- who could still read the blocker and write under their posts, where everyone
6
+ -- but the blocker saw it.
7
+ --
8
+ -- Admin accounts are never hidden by a block (they are the app speaking): a block
9
+ -- toward an admin is refused, and one made before this migration is inert. A
10
+ -- member can unblock (delete their own block row) and list whom they blocked
11
+ -- (list_blocked_members()).
12
+ --
13
+ -- Additive for installed app versions: the same tables and columns, only fewer
14
+ -- rows. A blocked profile is no longer readable, so an older app shows its usual
15
+ -- error state on that profile.
16
+
17
+ create index if not exists blocks_blocked_idx on public.blocks (blocked_id, blocker_id);
18
+
19
+ -- The members hidden from the caller: the ones they blocked and the ones who
20
+ -- blocked them, admins excepted. SECURITY DEFINER because the blocks RLS only
21
+ -- shows a member their own rows, never the blocks against them. Policies call it
22
+ -- as `(select public.blocked_member_ids())::uuid[]` (one run per query; the cast keeps
23
+ -- `= any` reading an array, not a subquery). Reuse it
24
+ -- for anything that shows one member to another (online presence included).
25
+ -- A member can learn that someone blocked them by calling it; the mutual hiding
26
+ -- tells them anyway.
27
+ create or replace function public.blocked_member_ids()
28
+ returns uuid[]
29
+ language sql stable security definer set search_path = public
30
+ as $$
31
+ select coalesce(array_agg(s.other), '{}')
32
+ from (
33
+ select b.blocked_id as other from blocks b where b.blocker_id = auth.uid()
34
+ union
35
+ select b.blocker_id from blocks b where b.blocked_id = auth.uid()
36
+ ) s
37
+ join profiles p on p.id = s.other
38
+ where not p.is_admin;
39
+ $$;
40
+
41
+ revoke execute on function public.blocked_member_ids() from public, anon;
42
+ grant execute on function public.blocked_member_ids() to authenticated;
43
+
44
+ -- ============ PROFILES ============
45
+ drop policy "profiles readable by authenticated" on public.profiles;
46
+ create policy "profiles readable unless blocked"
47
+ on public.profiles for select to authenticated
48
+ using (id = auth.uid() or not (id = any ((select public.blocked_member_ids())::uuid[])));
49
+
50
+ -- ============ POSTS ============
51
+ drop policy "read visible posts, minus blocked authors" on public.posts;
52
+ create policy "read visible posts, minus blocked members"
53
+ on public.posts for select to authenticated
54
+ using (
55
+ author_id = auth.uid()
56
+ or (status = 'visible' and not (author_id = any ((select public.blocked_member_ids())::uuid[])))
57
+ );
58
+
59
+ -- ============ COMMENTS ============
60
+ drop policy "read visible comments, minus blocked authors" on public.comments;
61
+ create policy "read visible comments, minus blocked members"
62
+ on public.comments for select to authenticated
63
+ using (
64
+ author_id = auth.uid()
65
+ or (status = 'visible' and not (author_id = any ((select public.blocked_member_ids())::uuid[])))
66
+ );
67
+
68
+ -- A comment needs a post the author can read: not hidden, deleted, or by a
69
+ -- member blocked either way. A reply also needs a parent the author can read
70
+ -- (comments_parent_same_post, core/010, runs under this same RLS).
71
+ drop policy "insert own comments if not banned" on public.comments;
72
+ create policy "insert own comments if not banned"
73
+ on public.comments for insert to authenticated
74
+ with check (
75
+ author_id = auth.uid()
76
+ and not public.current_user_banned()
77
+ and status = 'pending'
78
+ and exists (select 1 from public.posts p where p.id = post_id)
79
+ );
80
+
81
+ -- ============ LIKES ============
82
+ drop policy "likes readable where post readable" on public.likes;
83
+ create policy "likes readable where post readable"
84
+ on public.likes for select to authenticated
85
+ using (
86
+ exists (select 1 from public.posts p where p.id = likes.post_id)
87
+ and not (user_id = any ((select public.blocked_member_ids())::uuid[]))
88
+ );
89
+
90
+ drop policy "like as self" on public.likes;
91
+ create policy "like as self"
92
+ on public.likes for insert to authenticated
93
+ with check (
94
+ user_id = auth.uid()
95
+ and not public.current_user_banned()
96
+ and exists (select 1 from public.posts p where p.id = post_id)
97
+ );
98
+
99
+ -- ============ COMMENT LIKES ============
100
+ drop policy "comment likes readable where comment readable" on public.comment_likes;
101
+ create policy "comment likes readable where comment readable"
102
+ on public.comment_likes for select to authenticated
103
+ using (
104
+ exists (select 1 from public.comments c where c.id = comment_likes.comment_id)
105
+ and not (user_id = any ((select public.blocked_member_ids())::uuid[]))
106
+ );
107
+
108
+ drop policy "like comment as self" on public.comment_likes;
109
+ create policy "like comment as self"
110
+ on public.comment_likes for insert to authenticated
111
+ with check (
112
+ user_id = auth.uid()
113
+ and not public.current_user_banned()
114
+ and exists (select 1 from public.comments c where c.id = comment_id)
115
+ );
116
+
117
+ -- ============ BLOCKS ============
118
+ drop policy "manage own blocks" on public.blocks;
119
+ create policy "read own blocks" on public.blocks for select to authenticated
120
+ using (blocker_id = auth.uid());
121
+ create policy "unblock own blocks" on public.blocks for delete to authenticated
122
+ using (blocker_id = auth.uid());
123
+ create policy "block a member, never an admin" on public.blocks for insert to authenticated
124
+ with check (
125
+ blocker_id = auth.uid()
126
+ and not exists (select 1 from public.profiles p where p.id = blocked_id and p.is_admin)
127
+ );
128
+
129
+ -- Whom the caller blocked, newest first, for the "Blocked members" list.
130
+ -- SECURITY DEFINER: those profiles are no longer readable through RLS.
131
+ create or replace function public.list_blocked_members()
132
+ returns table (
133
+ id uuid,
134
+ username text,
135
+ handle text,
136
+ avatar_url text,
137
+ blocked_at timestamptz
138
+ )
139
+ language sql stable security definer set search_path = public
140
+ as $$
141
+ select p.id, p.username, p.handle, p.avatar_url, b.created_at
142
+ from blocks b
143
+ join profiles p on p.id = b.blocked_id
144
+ where b.blocker_id = auth.uid()
145
+ order by b.created_at desc;
146
+ $$;
147
+
148
+ revoke execute on function public.list_blocked_members() from public, anon;
149
+ grant execute on function public.list_blocked_members() to authenticated;
@@ -0,0 +1,34 @@
1
+ -- community-sdk images/002_draft_images.sql (schema v1)
2
+ -- The nightly sweep keeps images that a shared post draft (core/014_post_drafts.sql)
3
+ -- points at, so a draft written yesterday still has its picture today.
4
+ -- Redefines post_images_unreferenced with one more reference check. Idempotent.
5
+
6
+ create or replace function public.post_images_unreferenced(p_limit int default 500)
7
+ returns setof text
8
+ language sql
9
+ stable
10
+ security definer
11
+ set search_path = ''
12
+ as $$
13
+ select o.name
14
+ from storage.objects o
15
+ where o.bucket_id = 'post-images'
16
+ and o.created_at < now() - interval '24 hours'
17
+ and not exists (
18
+ select 1 from public.posts p
19
+ where p.image_path = o.name and p.status <> 'deleted'
20
+ )
21
+ and not exists (
22
+ select 1 from public.comments c
23
+ where c.image_path = o.name and c.status <> 'deleted'
24
+ )
25
+ and not exists (
26
+ select 1 from public.post_drafts d
27
+ where d.image_path = o.name
28
+ )
29
+ order by o.created_at
30
+ limit p_limit;
31
+ $$;
32
+
33
+ revoke all on function public.post_images_unreferenced(int) from public, anon, authenticated;
34
+ grant execute on function public.post_images_unreferenced(int) to service_role;
@@ -0,0 +1,44 @@
1
+ -- community-sdk inbox/004_mutual_blocks.sql (schema v1)
2
+ -- The center follows blocks, past ones included: an item whose actor, or whose
3
+ -- post's author, is blocked either way (core/016_mutual_blocks.sql) is no longer
4
+ -- listed. Nothing is deleted, so an unblock brings the items back. Same return
5
+ -- shape as inbox/003, so installed app versions read it unchanged.
6
+
7
+ create or replace function public.list_notifications(p_limit int default 50)
8
+ returns table (
9
+ id uuid,
10
+ kind text,
11
+ actor_id uuid,
12
+ actor_username text,
13
+ post_id uuid,
14
+ post_excerpt text,
15
+ created_at timestamptz
16
+ )
17
+ language sql stable security definer set search_path = public
18
+ as $$
19
+ with hidden as (select public.blocked_member_ids() as ids)
20
+ (
21
+ select n.id, n.kind, n.actor_id, pr.username, n.post_id,
22
+ left(p.content, 140), n.created_at
23
+ from notifications n
24
+ cross join hidden h
25
+ left join profiles pr on pr.id = n.actor_id
26
+ left join posts p on p.id = n.post_id
27
+ where n.user_id = auth.uid()
28
+ and (n.post_id is null or p.status in ('visible', 'pending'))
29
+ and (n.actor_id is null or not (n.actor_id = any (h.ids)))
30
+ and (p.author_id is null or p.author_id = auth.uid() or not (p.author_id = any (h.ids)))
31
+ )
32
+ union all
33
+ (
34
+ select p.id, 'official_post', p.author_id, pr.username, p.id,
35
+ left(p.content, 140), p.broadcast_at
36
+ from posts p
37
+ join profiles pr on pr.id = p.author_id
38
+ where p.status = 'visible' and p.broadcast_at is not null
39
+ and p.author_id <> auth.uid()
40
+ and p.broadcast_at > now() - interval '90 days'
41
+ )
42
+ order by created_at desc
43
+ limit p_limit;
44
+ $$;
@@ -0,0 +1,36 @@
1
+ -- community-sdk reaction/004_mutual_blocks.sql (schema v1)
2
+ -- The reaction summary follows blocks (core/016_mutual_blocks.sql): a member
3
+ -- blocked either way is neither counted nor named as the last reactor, and only
4
+ -- posts the caller can read are summarized (the function is SECURITY DEFINER, so
5
+ -- it applies the posts rule itself). Same return shape as reaction/001.
6
+
7
+ create or replace function public.post_reaction_summary(p_post_ids uuid[])
8
+ returns table (post_id uuid, reaction_count int, last_reactor_name text, has_reacted boolean)
9
+ language sql stable security definer set search_path = public
10
+ as $$
11
+ with hidden as (select public.blocked_member_ids() as ids),
12
+ shown as (
13
+ select r.post_id, r.user_id, r.created_at
14
+ from post_reactions r
15
+ join posts p on p.id = r.post_id
16
+ cross join hidden h
17
+ where r.post_id = any (p_post_ids)
18
+ and (p.author_id = auth.uid()
19
+ or (p.status = 'visible' and not (p.author_id = any (h.ids))))
20
+ and not (r.user_id = any (h.ids))
21
+ )
22
+ select
23
+ s.post_id,
24
+ count(*)::int as reaction_count,
25
+ (
26
+ select pr.username
27
+ from shown s2
28
+ join profiles pr on pr.id = s2.user_id
29
+ where s2.post_id = s.post_id
30
+ order by s2.created_at desc
31
+ limit 1
32
+ ) as last_reactor_name,
33
+ bool_or(s.user_id = auth.uid()) as has_reacted
34
+ from shown s
35
+ group by s.post_id;
36
+ $$;
@@ -1,15 +0,0 @@
1
- /**
2
- * Replaces the `__SUPABASE_PROJECT_URL__` / `__SUPABASE_ANON_KEY__` placeholders
3
- * baked into the shipped migration SQL (see core/003, push/002, reaction/001)
4
- * with the values for the app's own Supabase project.
5
- *
6
- * Throws if any `__SUPABASE...` token remains after substitution — a guard
7
- * against a third, unhandled placeholder silently reaching the app's
8
- * migrations directory (the migration's own DO block re-checks this at
9
- * `db push` time, but failing fast here gives a clearer error before any
10
- * SQL is written to disk).
11
- */
12
- export declare function substitutePlaceholders(sql: string, values: {
13
- projectUrl: string;
14
- anonKey: string;
15
- }): string;
package/lib/substitute.js DELETED
@@ -1,25 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.substitutePlaceholders = substitutePlaceholders;
4
- /**
5
- * Replaces the `__SUPABASE_PROJECT_URL__` / `__SUPABASE_ANON_KEY__` placeholders
6
- * baked into the shipped migration SQL (see core/003, push/002, reaction/001)
7
- * with the values for the app's own Supabase project.
8
- *
9
- * Throws if any `__SUPABASE...` token remains after substitution — a guard
10
- * against a third, unhandled placeholder silently reaching the app's
11
- * migrations directory (the migration's own DO block re-checks this at
12
- * `db push` time, but failing fast here gives a clearer error before any
13
- * SQL is written to disk).
14
- */
15
- function substitutePlaceholders(sql, values) {
16
- const result = sql
17
- .split("__SUPABASE_PROJECT_URL__")
18
- .join(values.projectUrl)
19
- .split("__SUPABASE_ANON_KEY__")
20
- .join(values.anonKey);
21
- if (result.includes("__SUPABASE")) {
22
- throw new Error("community-sdk: unsubstituted __SUPABASE placeholder remains after substitution");
23
- }
24
- return result;
25
- }