@rocapine/community 0.16.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.16.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,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,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
- }