@rocapine/community 0.16.0 → 0.18.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/README.md CHANGED
@@ -13,7 +13,7 @@ version. The binary is named `community`.
13
13
  ## `init`
14
14
 
15
15
  ```bash
16
- npx @rocapine/community init [--modules core,push,polls,reaction,inbox,translation,images,attachments,badges,streaks] [--project-url <url>] [--anon-key <key>] [--dir supabase]
16
+ npx @rocapine/community init [--modules core,push,polls,reaction,inbox,translation,images,attachments,badges,presence,streaks] [--project-url <url>] [--anon-key <key>] [--dir supabase]
17
17
  ```
18
18
 
19
19
  Copies the migrations and Edge Functions for the requested modules into
@@ -21,10 +21,10 @@ Copies the migrations and Edge Functions for the requested modules into
21
21
  relative to the current directory), and writes a `community-sdk.json`
22
22
  manifest at the repo root recording what was installed.
23
23
 
24
- - `--modules` — comma-separated (`core,push,polls,reaction,inbox,translation,images,attachments,badges,streaks`). `core`
24
+ - `--modules` — comma-separated (`core,push,polls,reaction,inbox,translation,images,attachments,badges,presence,streaks`). `core`
25
25
  is always implied even if omitted. Omit the flag entirely to install every
26
26
  module. Regardless of the order you type them, modules are installed
27
- `core → push → polls → reaction → inbox → translation → images → attachments → badges → streaks` — this order is load-bearing:
27
+ `core → push → polls → reaction → inbox → translation → images → attachments → badges → presence → streaks` — this order is load-bearing:
28
28
  the inbox module's reaction trigger is guarded at install time and must
29
29
  find the reaction module's table already present, so reaction has to land
30
30
  first. `streaks` (deprecated: it moves an existing streak install onto badges) always brings `badges`. Requesting `inbox` without `reaction`, or `translation` without `polls`, prints a (non-fatal) warning (reactions missing from the inbox; poll labels left untranslated).
package/lib/index.js CHANGED
@@ -60,7 +60,7 @@ program
60
60
  program
61
61
  .command("init")
62
62
  .description("Copy the community backend into a Supabase project: migrations, Edge Functions, and a community-sdk.json manifest")
63
- .option("--modules <modules>", "comma-separated module list (core,push,polls,reaction,inbox,translation,images,attachments,badges,streaks) — core is always implied; defaults to all modules")
63
+ .option("--modules <modules>", "comma-separated module list (core,push,polls,reaction,inbox,translation,images,attachments,badges,presence,streaks) — core is always implied; defaults to all modules")
64
64
  .option("--project-url <url>", "Supabase project URL, e.g. https://<ref>.supabase.co — optional, only fills in the printed settings seed statement")
65
65
  .option("--anon-key <key>", "Supabase anon key — optional, only fills in the printed settings seed statement")
66
66
  .option("--dir <dir>", "target Supabase directory, relative to the current directory", "supabase")
@@ -103,7 +103,7 @@ program
103
103
  .command("adopt")
104
104
  .description("Register an already-live community backend (e.g. an app that hand-rolled its own before this SDK existed) with community-sdk.json, without copying any files")
105
105
  .requiredOption("--schema-version <n>", "the community-sdk schema version this app's live backend corresponds to")
106
- .requiredOption("--modules <modules>", "comma-separated module list (core,push,polls,reaction,inbox,translation,images,attachments,badges,streaks) — core is always implied")
106
+ .requiredOption("--modules <modules>", "comma-separated module list (core,push,polls,reaction,inbox,translation,images,attachments,badges,presence,streaks) — core is always implied")
107
107
  .option("--dir <dir>", "Supabase directory this app would use, relative to the current directory", "supabase")
108
108
  .action(async (opts) => {
109
109
  try {
@@ -10,7 +10,7 @@
10
10
  * single source of truth for module names, order, and the function sets
11
11
  * each module pulls in.
12
12
  */
13
- export declare const MODULE_ORDER: readonly ["core", "push", "polls", "reaction", "inbox", "translation", "images", "attachments", "badges", "streaks"];
13
+ export declare const MODULE_ORDER: readonly ["core", "push", "polls", "reaction", "inbox", "translation", "images", "attachments", "badges", "presence", "streaks"];
14
14
  export type Module = (typeof MODULE_ORDER)[number];
15
15
  export declare function functionsForModules(modules: readonly Module[]): string[];
16
16
  /**
@@ -75,6 +75,7 @@ exports.MODULE_ORDER = [
75
75
  "images",
76
76
  "attachments",
77
77
  "badges",
78
+ "presence",
78
79
  // Deprecated: kept to move existing streaks onto badges (streaks/002). Implies badges.
79
80
  "streaks",
80
81
  ];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rocapine/community",
3
- "version": "0.16.0",
3
+ "version": "0.18.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,139 @@
1
+ -- community-sdk presence/001_presence.sql (schema v1)
2
+ -- Presence module: a green dot on online members, a live online count, and a
3
+ -- per-member switch to hide. The app calls touch_presence() while it is open; a
4
+ -- member is online when their last touch is within the project's grace window
5
+ -- (presence_settings, default 5 minutes).
6
+ --
7
+ -- The timestamp is never readable by clients (only user_id and visible are, and
8
+ -- only for the member's own row): readers get a boolean through online_member_ids()
9
+ -- or a number through online_member_count(). Both skip banned and (for the ids)
10
+ -- hidden and mutually blocked members. The caller counts as online (whoever calls the
11
+ -- readers has the app open) even before their first touch lands, unless banned;
12
+ -- a hidden caller is counted but never listed.
13
+ -- Fully idempotent.
14
+
15
+ create table if not exists public.member_presence (
16
+ user_id uuid primary key references public.profiles(id) on delete cascade,
17
+ last_active_at timestamptz not null default now(),
18
+ visible boolean not null default true
19
+ );
20
+
21
+ create index if not exists member_presence_last_active_idx
22
+ on public.member_presence (last_active_at);
23
+
24
+ alter table public.member_presence enable row level security;
25
+
26
+ -- A member reads only their own row, and only these columns (user_id because the
27
+ -- owner filters on it: column privileges apply to WHERE columns too).
28
+ drop policy if exists "read own presence" on public.member_presence;
29
+ create policy "read own presence" on public.member_presence
30
+ for select to authenticated using (user_id = auth.uid());
31
+
32
+ revoke all on public.member_presence from public, anon, authenticated;
33
+ grant select (user_id, visible) on public.member_presence to authenticated;
34
+
35
+ create or replace function public.touch_presence()
36
+ returns void
37
+ language sql security definer set search_path = public
38
+ as $$
39
+ insert into member_presence (user_id, last_active_at)
40
+ select auth.uid(), now()
41
+ where auth.uid() is not null
42
+ on conflict (user_id) do update set last_active_at = excluded.last_active_at;
43
+ $$;
44
+
45
+ create or replace function public.set_presence_visible(p_visible boolean)
46
+ returns void
47
+ language sql security definer set search_path = public
48
+ as $$
49
+ -- A first row starts long idle: only touch_presence makes someone online.
50
+ insert into member_presence (user_id, last_active_at, visible)
51
+ select auth.uid(), 'epoch', p_visible
52
+ where auth.uid() is not null
53
+ on conflict (user_id) do update set visible = excluded.visible;
54
+ $$;
55
+
56
+ -- The grace window is a per-project setting, never a client parameter: if callers
57
+ -- chose it, sweeping 1..60 would tell them when each member was last active.
58
+ -- One row, readable only by the security definer RPCs below. Change it from the
59
+ -- SQL editor (service role): select public.presence_set_grace_minutes(10);
60
+ create table if not exists public.presence_settings (
61
+ id boolean primary key default true check (id),
62
+ grace_minutes int not null default 5 check (grace_minutes between 1 and 60)
63
+ );
64
+ insert into public.presence_settings (id) values (true) on conflict do nothing;
65
+ alter table public.presence_settings enable row level security;
66
+ revoke all on public.presence_settings from public, anon, authenticated;
67
+
68
+ -- The check constraint rejects values outside 1..60.
69
+ create or replace function public.presence_set_grace_minutes(p_minutes int)
70
+ returns void
71
+ language sql security definer set search_path = public
72
+ as $$
73
+ insert into presence_settings (id, grace_minutes) values (true, p_minutes)
74
+ on conflict (id) do update set grace_minutes = excluded.grace_minutes;
75
+ $$;
76
+
77
+ -- Earlier drafts took the grace as a parameter.
78
+ drop function if exists public.online_member_count(int);
79
+ drop function if exists public.online_member_ids(uuid[], int);
80
+
81
+ -- Members online within the grace window, hidden members included: a count
82
+ -- reveals no one. The caller counts even without a fresh row (union dedups). A banned
83
+ -- caller gets 0.
84
+ create or replace function public.online_member_count()
85
+ returns int
86
+ language sql stable security definer set search_path = public
87
+ as $$
88
+ select count(*)::int from (
89
+ select mp.user_id
90
+ from member_presence mp
91
+ join profiles p on p.id = mp.user_id
92
+ where not p.is_banned
93
+ and mp.last_active_at > now() - make_interval(
94
+ mins => coalesce((select grace_minutes from presence_settings), 5))
95
+ union
96
+ select p.id from profiles p where p.id = auth.uid() and not p.is_banned
97
+ ) online
98
+ where not exists (select 1 from profiles b where b.id = auth.uid() and b.is_banned);
99
+ $$;
100
+
101
+ -- Which of the first 200 of p_ids are online, visible, not banned and not
102
+ -- blocked either way with the caller. The caller is online when asking, unless
103
+ -- they hid themselves (a missing row means visible). A banned caller gets '{}'.
104
+ create or replace function public.online_member_ids(p_ids uuid[])
105
+ returns uuid[]
106
+ language sql stable security definer set search_path = public
107
+ as $$
108
+ select coalesce(array_agg(id), '{}') from (
109
+ select mp.user_id as id
110
+ from member_presence mp
111
+ join profiles p on p.id = mp.user_id
112
+ where mp.user_id = any (p_ids[1:200])
113
+ and mp.visible
114
+ and not p.is_banned
115
+ and mp.last_active_at > now() - make_interval(
116
+ mins => coalesce((select grace_minutes from presence_settings), 5))
117
+ and not (mp.user_id = any ((select public.blocked_member_ids())::uuid[]))
118
+ union
119
+ select p.id
120
+ from profiles p
121
+ left join member_presence mp on mp.user_id = p.id
122
+ where p.id = auth.uid()
123
+ and p.id = any (p_ids[1:200])
124
+ and not p.is_banned
125
+ and coalesce(mp.visible, true)
126
+ ) online
127
+ where not exists (select 1 from profiles b where b.id = auth.uid() and b.is_banned);
128
+ $$;
129
+
130
+ revoke execute on function public.touch_presence() from public, anon;
131
+ revoke execute on function public.set_presence_visible(boolean) from public, anon;
132
+ revoke execute on function public.online_member_count() from public, anon;
133
+ revoke execute on function public.online_member_ids(uuid[]) from public, anon;
134
+ grant execute on function public.touch_presence() to authenticated;
135
+ grant execute on function public.set_presence_visible(boolean) to authenticated;
136
+ grant execute on function public.online_member_count() to authenticated;
137
+ grant execute on function public.online_member_ids(uuid[]) to authenticated;
138
+ revoke execute on function public.presence_set_grace_minutes(int) from public, anon, authenticated;
139
+ grant execute on function public.presence_set_grace_minutes(int) to service_role;
@@ -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
- }