@rocapine/community 0.11.0 → 0.13.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.11.0",
3
+ "version": "0.13.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": {
@@ -32,6 +32,7 @@ type LocaleCopy = Record<string, CopyValue>;
32
32
  export type PushCopyKey =
33
33
  | "fallbackName"
34
34
  | "comment.title"
35
+ | "reply.title"
35
36
  | "like.one"
36
37
  | "like.many"
37
38
  | "reaction.one"
@@ -43,6 +44,7 @@ const BUILTIN: Record<string, LocaleCopy> = {
43
44
  fallbackName: "Someone",
44
45
  photo: "📷 Photo",
45
46
  "comment.title": "You received a comment",
47
+ "reply.title": "You received a reply",
46
48
  "like.one": "{name} liked your post",
47
49
  "like.many": {
48
50
  one: "{name} and {count} other liked your post",
@@ -58,6 +60,7 @@ const BUILTIN: Record<string, LocaleCopy> = {
58
60
  fallbackName: "Alguém",
59
61
  photo: "📷 Foto",
60
62
  "comment.title": "Recebeste um comentário",
63
+ "reply.title": "Recebeste uma resposta",
61
64
  "like.one": "{name} gostou da tua publicação",
62
65
  "like.many": {
63
66
  one: "{name} e mais {count} pessoa gostou da tua publicação",
@@ -73,6 +76,7 @@ const BUILTIN: Record<string, LocaleCopy> = {
73
76
  fallbackName: "Alguém",
74
77
  photo: "📷 Foto",
75
78
  "comment.title": "Você recebeu um comentário",
79
+ "reply.title": "Você recebeu uma resposta",
76
80
  "like.one": "{name} curtiu seu post",
77
81
  "like.many": {
78
82
  one: "{name} e mais {count} pessoa curtiu seu post",
@@ -88,6 +92,7 @@ const BUILTIN: Record<string, LocaleCopy> = {
88
92
  fallbackName: "Alguien",
89
93
  photo: "📷 Foto",
90
94
  "comment.title": "Has recibido un comentario",
95
+ "reply.title": "Has recibido una respuesta",
91
96
  "like.one": "A {name} le ha gustado tu publicación",
92
97
  "like.many": {
93
98
  one: "A {name} y a {count} persona más les ha gustado tu publicación",
@@ -103,6 +108,7 @@ const BUILTIN: Record<string, LocaleCopy> = {
103
108
  fallbackName: "Alguien",
104
109
  photo: "📷 Foto",
105
110
  "comment.title": "Recibiste un comentario",
111
+ "reply.title": "Recibiste una respuesta",
106
112
  "like.one": "A {name} le gustó tu publicación",
107
113
  "like.many": {
108
114
  one: "A {name} y a {count} persona más les gustó tu publicación",
@@ -118,6 +124,7 @@ const BUILTIN: Record<string, LocaleCopy> = {
118
124
  fallbackName: "Qualcuno",
119
125
  photo: "📷 Foto",
120
126
  "comment.title": "Hai ricevuto un commento",
127
+ "reply.title": "Hai ricevuto una risposta",
121
128
  "like.one": "A {name} piace il tuo post",
122
129
  "like.many": {
123
130
  one: "A {name} e ad altra {count} persona piace il tuo post",
@@ -133,6 +140,7 @@ const BUILTIN: Record<string, LocaleCopy> = {
133
140
  fallbackName: "Ktoś",
134
141
  photo: "📷 Zdjęcie",
135
142
  "comment.title": "Masz nowy komentarz",
143
+ "reply.title": "Masz nową odpowiedź",
136
144
  "like.one": "{name} polubił(a) twój post",
137
145
  "like.many": {
138
146
  one: "{name} i {count} inna osoba polubiły twój post",
@@ -150,6 +158,7 @@ const BUILTIN: Record<string, LocaleCopy> = {
150
158
  fallbackName: "Quelqu'un",
151
159
  photo: "📷 Photo",
152
160
  "comment.title": "Tu as reçu un commentaire",
161
+ "reply.title": "Tu as reçu une réponse",
153
162
  "like.one": "{name} a aimé ta publication",
154
163
  "like.many": {
155
164
  one: "{name} et {count} autre personne ont aimé ta publication",
@@ -165,6 +174,7 @@ const BUILTIN: Record<string, LocaleCopy> = {
165
174
  fallbackName: "Jemand",
166
175
  photo: "📷 Foto",
167
176
  "comment.title": "Du hast einen Kommentar erhalten",
177
+ "reply.title": "Du hast eine Antwort erhalten",
168
178
  "like.one": "{name} gefällt dein Beitrag",
169
179
  "like.many": {
170
180
  one: "{name} und {count} weiterer Person gefällt dein Beitrag",
@@ -0,0 +1,53 @@
1
+ // Display name / handle rules shared by update-profile and the daily sweep:
2
+ // the app's own name is reserved (no "Unchaind Team" impersonating the app),
3
+ // a few staff-sounding handles too, and a taken handle gets a free suggestion.
4
+
5
+ const APP_NAME = Deno.env.get("COMMUNITY_APP_NAME") ?? "";
6
+
7
+ /** Lowercase, accents stripped, letters and digits only. */
8
+ function collapse(s: string): string {
9
+ return s
10
+ .normalize("NFD")
11
+ .replace(/\p{Diacritic}/gu, "")
12
+ .toLowerCase()
13
+ .replace(/[^a-z0-9]/g, "");
14
+ }
15
+
16
+ /** True when `value` contains the app's name. Short names (< 4 chars, "Eve") only match a whole word so "Steve" stays allowed. */
17
+ export function containsAppName(value: string, appName: string = APP_NAME): boolean {
18
+ const app = collapse(appName);
19
+ if (app === "") return false;
20
+ if (app.length >= 4) return collapse(value).includes(app);
21
+ return value
22
+ .normalize("NFD")
23
+ .replace(/\p{Diacritic}/gu, "")
24
+ .toLowerCase()
25
+ .split(/[^a-z0-9]+/)
26
+ .includes(app);
27
+ }
28
+
29
+ const RESERVED_HANDLES = ["admin", "support", "official", "team", "moderator"];
30
+
31
+ export function isReservedHandle(handle: string, appName: string = APP_NAME): boolean {
32
+ return RESERVED_HANDLES.includes(handle) || containsAppName(handle, appName);
33
+ }
34
+
35
+ /**
36
+ * A free handle on `handle`'s base: "superuser" -> "superuser-4821". Same
37
+ * digit widening as generate_handle (core/009). `isFree` checks the table.
38
+ */
39
+ export async function suggestHandle(
40
+ handle: string,
41
+ isFree: (candidate: string) => Promise<boolean>,
42
+ ): Promise<string | null> {
43
+ const base = handle.replace(/-[0-9]+$/, "").slice(0, 15) || "user";
44
+ for (let tries = 0; tries < 10; tries++) {
45
+ const digits =
46
+ tries < 5
47
+ ? Math.floor(Math.random() * 9000) + 1000
48
+ : Math.floor(Math.random() * 900000) + 100000;
49
+ const candidate = `${base}-${digits}`;
50
+ if (await isFree(candidate)) return candidate;
51
+ }
52
+ return null;
53
+ }
@@ -13,7 +13,8 @@ export interface ExpoPushMessage {
13
13
  badge?: number;
14
14
  }
15
15
 
16
- /** Unread inbox rows for `uid` (newer than the seen marker), at least 1 since a push
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
17
18
  * is being sent. Falls back to 1 when the inbox module is not installed. */
18
19
  export async function unreadBadge(
19
20
  supabase: { from: (table: string) => any },
@@ -25,14 +26,20 @@ export async function unreadBadge(
25
26
  .select("seen_at")
26
27
  .eq("user_id", uid)
27
28
  .maybeSingle();
28
- let query = supabase
29
- .from("notifications")
30
- .select("*", { count: "exact", head: true })
31
- .eq("user_id", uid);
29
+ let query = supabase.from("notifications").select("id").eq("user_id", uid).limit(200);
32
30
  if (seen?.seen_at) query = query.gt("created_at", seen.seen_at);
33
- const { count, error } = await query;
31
+ const { data: rows, error } = await query;
34
32
  if (error) return 1;
35
- return Math.max(1, count ?? 0);
33
+ const ids = (rows ?? []).map((r: { id: string }) => r.id);
34
+ if (ids.length === 0) return 1;
35
+ // Items marked read one by one (inbox/002_replies_and_reads.sql); a project
36
+ // without that table just counts every row past the watermark.
37
+ const { data: reads } = await supabase
38
+ .from("notification_reads")
39
+ .select("item_id")
40
+ .eq("user_id", uid)
41
+ .in("item_id", ids);
42
+ return Math.max(1, ids.length - (reads?.length ?? 0));
36
43
  } catch {
37
44
  return 1;
38
45
  }
@@ -81,7 +81,7 @@ Deno.serve(async (req) => {
81
81
  to,
82
82
  title,
83
83
  body: excerptFor(locale, profileLocale),
84
- data: { route: "/community", kind: "community_official_post" },
84
+ data: { route: "/community", kind: "community_official_post", postId: post.id },
85
85
  badge: 1,
86
86
  }));
87
87
  await sendExpoPushBatch(messages);
@@ -3,7 +3,8 @@
3
3
  // 'pending' -> promote to 'visible' (catches items whose synchronous
4
4
  // moderate-one call failed), clean 'visible' -> just stamp. Also sweeps
5
5
  // not-yet-checked usernames (profiles.username is client-writable, see
6
- // core/007_username_moderation.sql): flagged -> blanked. Posts a Slack
6
+ // core/007_username_moderation.sql): flagged or containing the app's name ->
7
+ // blanked, i.e. back to the default name (core/009). Posts a Slack
7
8
  // summary when there was something to check (no-op if SLACK_WEBHOOK_URL is
8
9
  // unset — see _shared/slack.ts). Never deletes rows. App criticism is not a
9
10
  // category (stays visible).
@@ -20,6 +21,7 @@ import {
20
21
  type ModerationResult,
21
22
  } from "../_shared/moderation.ts";
22
23
  import { fetchImagePaths, POST_IMAGES_BUCKET, postImageUrl } from "../_shared/images.ts";
24
+ import { containsAppName } from "../_shared/names.ts";
23
25
  import { postToSlack } from "../_shared/slack.ts";
24
26
 
25
27
  assertModerationConfigured();
@@ -109,6 +111,7 @@ async function sweepUsernames(): Promise<{
109
111
  }
110
112
  results.forEach((r, idx) => {
111
113
  const cats = flaggedCategories(r);
114
+ if (containsAppName(batch[idx].username)) cats.push("app_name");
112
115
  if (cats.length > 0) blanked.push({ profile: batch[idx], categories: cats });
113
116
  });
114
117
  processed.push(...batch);
@@ -0,0 +1,77 @@
1
+ {
2
+ "version": "5",
3
+ "specifiers": {
4
+ "jsr:@std/assert@1": "1.0.19",
5
+ "jsr:@std/internal@^1.0.12": "1.0.14",
6
+ "jsr:@supabase/supabase-js@2": "2.116.0",
7
+ "npm:@supabase/auth-js@2.116.0": "2.116.0",
8
+ "npm:@supabase/functions-js@2.116.0": "2.116.0",
9
+ "npm:@supabase/postgrest-js@2.116.0": "2.116.0",
10
+ "npm:@supabase/realtime-js@2.116.0": "2.116.0",
11
+ "npm:@supabase/storage-js@2.116.0": "2.116.0"
12
+ },
13
+ "jsr": {
14
+ "@std/assert@1.0.19": {
15
+ "integrity": "eaada96ee120cb980bc47e040f82814d786fe8162ecc53c91d8df60b8755991e",
16
+ "dependencies": [
17
+ "jsr:@std/internal"
18
+ ]
19
+ },
20
+ "@std/internal@1.0.14": {
21
+ "integrity": "291516b3d4c35024d6ffbc0a9df5bf4c64116e05b50012cf846710152d2ffdf7"
22
+ },
23
+ "@supabase/supabase-js@2.116.0": {
24
+ "integrity": "3005b560a70ba75504f9c11ec48cb05cec71d86d715a3c15be574394963270e0",
25
+ "dependencies": [
26
+ "npm:@supabase/auth-js",
27
+ "npm:@supabase/functions-js",
28
+ "npm:@supabase/postgrest-js",
29
+ "npm:@supabase/realtime-js",
30
+ "npm:@supabase/storage-js"
31
+ ]
32
+ }
33
+ },
34
+ "npm": {
35
+ "@supabase/auth-js@2.116.0": {
36
+ "integrity": "sha512-Cmosty12gyKGK9N3bQb+lMmuAFev5nmUzaR1AsmZHqKOAGzqX1VQzmp49CNPwOx/pw0H9Qqk4rs9yhwTlKpfDg==",
37
+ "dependencies": [
38
+ "tslib"
39
+ ]
40
+ },
41
+ "@supabase/functions-js@2.116.0": {
42
+ "integrity": "sha512-E+VOc2QDcni/fySqkBFiZhnoB3SGydEdZgFI6/dEAGAHx6yEhB46TN9qb2wXs+E+RSzOBV0R6dasiSlw4xlZAA==",
43
+ "dependencies": [
44
+ "tslib"
45
+ ]
46
+ },
47
+ "@supabase/phoenix@0.4.5": {
48
+ "integrity": "sha512-aAn9H9ovVyeApKy11OWOrrOGq8DV68yWeH4ud2lN9fzn4aO8Zb5GLL9m1pUg9nLqIcT+ZDfAcsZe0E/nqdv2lw=="
49
+ },
50
+ "@supabase/postgrest-js@2.116.0": {
51
+ "integrity": "sha512-kGpVZTDHxFTJS3tu+rU0iTAZ+4U0bcLVjxwCk8f3gRhjw3qdCZjTBlgYvc4kGH2XccmAzbkKwXL/mrNHMGSc+A==",
52
+ "dependencies": [
53
+ "tslib"
54
+ ]
55
+ },
56
+ "@supabase/realtime-js@2.116.0": {
57
+ "integrity": "sha512-MHAnlXxi2s6yiJsZsQMfs2B3RFxeVfQWxerqYhIMqcCQV/FuY3LIeouPEkXw/ah7wUWMLYwempF9MOCUScyddg==",
58
+ "dependencies": [
59
+ "@supabase/phoenix",
60
+ "tslib"
61
+ ]
62
+ },
63
+ "@supabase/storage-js@2.116.0": {
64
+ "integrity": "sha512-6/3hR6vccBP6oGM5B6RfbwZcTCKmQOodd/ZWQdsw8yJsU5zO/a//oBL6yLnmgxcjnHSrelW8rsO7hL5DPybyUQ==",
65
+ "dependencies": [
66
+ "iceberg-js",
67
+ "tslib"
68
+ ]
69
+ },
70
+ "iceberg-js@0.8.1": {
71
+ "integrity": "sha512-1dhVQZXhcHje7798IVM+xoo/1ZdVfzOMIc8/rgVSijRK38EDqOJoGula9N/8ZI5RD8QTxNQtK/Gozpr+qUqRRA=="
72
+ },
73
+ "tslib@2.8.1": {
74
+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="
75
+ }
76
+ }
77
+ }
@@ -1,6 +1,7 @@
1
1
  // Real-time comment notification: a pg_net trigger fires here when a comment
2
- // becomes visible (published). We push to the post author (unless self, opted
3
- // out, no token, or the author has blocked the commenter).
2
+ // becomes visible (published). We push to the post author, or for a reply to
3
+ // the author of the comment it answers only (unless self, opted out, no token,
4
+ // or the recipient has blocked the commenter).
4
5
  //
5
6
  // Security: this function is reachable with the public anon key (the trigger
6
7
  // calls it that way), so the body is UNTRUSTED. Only `record.id` is used; the
@@ -20,7 +21,7 @@ Deno.serve(async (req) => {
20
21
 
21
22
  const { data: comment } = await supabase
22
23
  .from("comments")
23
- .select("id, post_id, author_id, content, status")
24
+ .select("id, post_id, author_id, content, status, parent_id")
24
25
  .eq("id", record.id)
25
26
  .single();
26
27
  if (!comment || comment.status !== "visible") return new Response("skip: not visible");
@@ -30,63 +31,92 @@ Deno.serve(async (req) => {
30
31
  .select("author_id")
31
32
  .eq("id", comment.post_id)
32
33
  .single();
33
- if (!post || post.author_id === comment.author_id) return new Response("skip: self/none");
34
+ if (!post) return new Response("skip: no post");
34
35
 
35
- const { data: pref } = await supabase
36
- .from("push_tokens")
37
- .select("expo_push_token, notify_comments")
38
- .eq("user_id", post.author_id)
39
- .single();
40
- if (!pref?.expo_push_token || !pref.notify_comments) return new Response("skip: no token/pref");
41
-
42
- const { data: blocked } = await supabase
43
- .from("blocks")
44
- .select("blocker_id")
45
- .eq("blocker_id", post.author_id)
46
- .eq("blocked_id", comment.author_id)
47
- .maybeSingle();
48
- if (blocked) return new Response("skip: blocked");
49
-
50
- const { data: recipient } = await supabase
51
- .from("profiles")
52
- .select("locale")
53
- .eq("id", post.author_id)
54
- .single();
55
- const copy = pushCopy(recipient?.locale);
36
+ // A reply pushes only the author of the comment it answers; the post author
37
+ // is pushed for top-level comments (mirrors the inbox trigger,
38
+ // inbox/002_replies_and_reads.sql).
39
+ let parentAuthor: string | null = null;
40
+ if (comment.parent_id) {
41
+ const { data: parent } = await supabase
42
+ .from("comments")
43
+ .select("author_id")
44
+ .eq("id", comment.parent_id)
45
+ .maybeSingle();
46
+ parentAuthor = parent?.author_id ?? null;
47
+ }
48
+ const targets: { uid: string; title: "reply.title" | "comment.title"; kind: string }[] = [];
49
+ if (parentAuthor && parentAuthor !== comment.author_id) {
50
+ targets.push({ uid: parentAuthor, title: "reply.title", kind: "community_reply" });
51
+ }
52
+ if (!parentAuthor && post.author_id !== comment.author_id) {
53
+ targets.push({ uid: post.author_id, title: "comment.title", kind: "community_comment" });
54
+ }
55
+ if (targets.length === 0) return new Response("skip: self/none");
56
56
 
57
57
  const { data: actor } = await supabase
58
58
  .from("profiles")
59
59
  .select("username")
60
60
  .eq("id", comment.author_id)
61
61
  .single();
62
- const name = actor?.username?.trim() || copy.fallbackName;
63
- // Recipient-language excerpt when the translation module is on: translate
64
- // now (a few seconds) rather than push the source language; on failure the
65
- // original goes out and the sweep fills the rows later. translate-one fires
66
- // on the same insert, so when it holds the claim wait up to 20 s (the OpenAI
67
- // request timeout) for its rows.
68
- let excerptSource = comment.content;
69
- const targetLocale = resolveTargetLocale(recipient?.locale);
70
- if (targetLocale) {
71
- const rows = await ensureTranslations(supabase, "comment", comment.id, { waitMs: 20_000 });
72
- const match = rows?.find(
73
- (r) => r.locale === targetLocale && languageOf(r.locale) !== r.source_locale,
74
- );
75
- if (match) excerptSource = match.content;
76
- }
77
- // Title states the event; body is the commenter's name then the comment in
78
- // quotes, e.g. Marie: "So happy for you!". An image-only comment has no text:
79
- // the localized "Photo" label stands in, unquoted.
80
- const body = comment.content.trim()
81
- ? `${name}: "${excerptOrPhoto(excerptSource, "")}"`
82
- : `${name}: ${copy.text("photo")}`;
83
62
 
84
- await sendExpoPush({
85
- to: pref.expo_push_token,
86
- title: copy.text("comment.title"),
87
- body,
88
- data: { route: "/community", kind: "community_comment" },
89
- badge: await unreadBadge(supabase, post.author_id),
90
- });
63
+ const postId = comment.post_id;
64
+ for (const target of targets) await pushTo(target, actor?.username ?? null);
91
65
  return new Response("ok");
66
+
67
+ async function pushTo(
68
+ target: { uid: string; title: "reply.title" | "comment.title"; kind: string },
69
+ actorName: string | null,
70
+ ) {
71
+ const { data: pref } = await supabase
72
+ .from("push_tokens")
73
+ .select("expo_push_token, notify_comments")
74
+ .eq("user_id", target.uid)
75
+ .single();
76
+ if (!pref?.expo_push_token || !pref.notify_comments) return;
77
+
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;
85
+
86
+ const { data: recipient } = await supabase
87
+ .from("profiles")
88
+ .select("locale")
89
+ .eq("id", target.uid)
90
+ .single();
91
+ const copy = pushCopy(recipient?.locale);
92
+ const name = actorName?.trim() || copy.fallbackName;
93
+ // Recipient-language excerpt when the translation module is on: translate
94
+ // now (a few seconds) rather than push the source language; on failure the
95
+ // original goes out and the sweep fills the rows later. translate-one fires
96
+ // on the same insert, so when it holds the claim wait up to 20 s (the OpenAI
97
+ // request timeout) for its rows.
98
+ let excerptSource = comment!.content;
99
+ const targetLocale = resolveTargetLocale(recipient?.locale);
100
+ if (targetLocale) {
101
+ const rows = await ensureTranslations(supabase, "comment", comment!.id, { waitMs: 20_000 });
102
+ const match = rows?.find(
103
+ (r) => r.locale === targetLocale && languageOf(r.locale) !== r.source_locale,
104
+ );
105
+ if (match) excerptSource = match.content;
106
+ }
107
+ // Title states the event; body is the commenter's name then the comment in
108
+ // quotes, e.g. Marie: "So happy for you!". An image-only comment has no text:
109
+ // the localized "Photo" label stands in, unquoted.
110
+ const body = comment!.content.trim()
111
+ ? `${name}: "${excerptOrPhoto(excerptSource, "")}"`
112
+ : `${name}: ${copy.text("photo")}`;
113
+
114
+ await sendExpoPush({
115
+ to: pref.expo_push_token,
116
+ title: copy.text(target.title),
117
+ body,
118
+ data: { route: "/community", kind: target.kind, postId },
119
+ badge: await unreadBadge(supabase, target.uid),
120
+ });
121
+ }
92
122
  });
@@ -80,7 +80,7 @@ async function flushPost(postId: string) {
80
80
  await sendExpoPush({
81
81
  to: pref.expo_push_token,
82
82
  title,
83
- data: { route: "/community", kind: "community_like" },
83
+ data: { route: "/community", kind: "community_like", postId },
84
84
  badge: await unreadBadge(supabase, post.author_id),
85
85
  });
86
86
  }
@@ -79,7 +79,7 @@ async function flushPost(postId: string) {
79
79
  await sendExpoPush({
80
80
  to: pref.expo_push_token,
81
81
  title,
82
- data: { route: "/community", kind: "community_reaction" },
82
+ data: { route: "/community", kind: "community_reaction", postId },
83
83
  badge: await unreadBadge(supabase, post.author_id),
84
84
  });
85
85
  }
@@ -11,6 +11,7 @@
11
11
  import { createClient } from "jsr:@supabase/supabase-js@2";
12
12
  import { adminClient, json, SUPABASE_URL } from "../_shared/client.ts";
13
13
  import { assertModerationConfigured, moderateInput } from "../_shared/moderation.ts";
14
+ import { containsAppName, isReservedHandle, suggestHandle } from "../_shared/names.ts";
14
15
 
15
16
  assertModerationConfigured();
16
17
 
@@ -54,12 +55,17 @@ Deno.serve(async (req) => {
54
55
  if (u.length < 2 || u.length > 24) {
55
56
  return json({ status: "error", error: "invalid_username" }, 400);
56
57
  }
58
+ if (containsAppName(u)) return json({ status: "error", error: "reserved_name" }, 400);
57
59
  const verdict = await moderateInput(u);
58
60
  if (!verdict) return json({ status: "error", error: "moderation unavailable" }, 503);
59
61
  if (verdict.flagged) {
60
62
  return json({ status: "rejected", field: "username", reason: verdict.reason });
61
63
  }
62
- const { error } = await admin.from("profiles").update({ username: u }).eq("id", uid);
64
+ // The user's own name: the host app's sync no longer overwrites it (core/009).
65
+ const { error } = await admin
66
+ .from("profiles")
67
+ .update({ username: u, username_set_by_user: true })
68
+ .eq("id", uid);
63
69
  if (error) return json({ status: "error", error: error.message }, 500);
64
70
  }
65
71
 
@@ -69,15 +75,26 @@ Deno.serve(async (req) => {
69
75
  if (!/^[a-z0-9-]{3,20}$/.test(h)) {
70
76
  return json({ status: "error", error: "invalid_handle" }, 400);
71
77
  }
78
+ if (isReservedHandle(h)) return json({ status: "error", error: "reserved_handle" }, 400);
72
79
  const verdict = await moderateInput(h);
73
80
  if (!verdict) return json({ status: "error", error: "moderation unavailable" }, 503);
74
81
  if (verdict.flagged) {
75
82
  return json({ status: "rejected", field: "handle", reason: verdict.reason });
76
83
  }
77
- const { error } = await admin.from("profiles").update({ handle: h }).eq("id", uid);
84
+ const { error } = await admin
85
+ .from("profiles")
86
+ .update({ handle: h, handle_set_by_user: true })
87
+ .eq("id", uid);
78
88
  if (error) {
79
89
  if (error.code === "23505") {
80
- return json({ status: "error", code: "handle_taken" }, 409);
90
+ const suggestion = await suggestHandle(h, async (candidate) => {
91
+ const { count } = await admin
92
+ .from("profiles")
93
+ .select("id", { count: "exact", head: true })
94
+ .eq("handle", candidate);
95
+ return count === 0;
96
+ });
97
+ return json({ status: "error", code: "handle_taken", suggestion }, 409);
81
98
  }
82
99
  return json({ status: "error", error: error.message }, 500);
83
100
  }
@@ -0,0 +1,199 @@
1
+ -- community-sdk core/009_default_names.sql
2
+ -- Default names: every profile gets "<label> <digits>" / "<prefix>-<digits>"
3
+ -- (assign_default_profile, called by the client once per launch). The host
4
+ -- app's name seeds the profile until the user edits it through update-profile;
5
+ -- from then on a client write of `username` is ignored (the user wins). See
6
+ -- docs/superpowers/specs/2026-10-26-default-names-design.md.
7
+
8
+ alter table public.profiles
9
+ add column if not exists default_username text,
10
+ add column if not exists default_handle text,
11
+ add column if not exists username_set_by_user boolean not null default false,
12
+ add column if not exists handle_set_by_user boolean not null default false;
13
+
14
+ -- generate_handle with the slug to use when `base` has no usable letters
15
+ -- (a Korean or emoji-only name): the app's handle prefix instead of "member".
16
+ create or replace function public.generate_handle(base text, fallback text)
17
+ returns text
18
+ language plpgsql volatile security definer
19
+ set search_path = public, extensions
20
+ as $$
21
+ declare
22
+ slug text;
23
+ candidate text;
24
+ tries int := 0;
25
+ begin
26
+ slug := left(regexp_replace(lower(unaccent(coalesce(base, ''))), '[^a-z0-9]', '', 'g'), 12);
27
+ if slug = '' then
28
+ slug := left(regexp_replace(lower(coalesce(fallback, '')), '[^a-z0-9]', '', 'g'), 12);
29
+ end if;
30
+ if slug = '' then
31
+ slug := 'member';
32
+ end if;
33
+ loop
34
+ if tries < 5 then
35
+ candidate := slug || '-' || (floor(random() * 9000) + 1000)::int;
36
+ else
37
+ candidate := slug || '-' || (floor(random() * 900000) + 100000)::int;
38
+ end if;
39
+ exit when not exists (select 1 from public.profiles where handle = candidate);
40
+ tries := tries + 1;
41
+ end loop;
42
+ return candidate;
43
+ end;
44
+ $$;
45
+
46
+ create or replace function public.generate_handle(base text)
47
+ returns text
48
+ language sql volatile security definer
49
+ set search_path = public, extensions
50
+ as $$ select public.generate_handle(base, 'member') $$;
51
+
52
+ -- The default handle when it is still free, else a fresh one on its prefix.
53
+ create or replace function public.default_handle_for(p_id uuid, p_default text)
54
+ returns text
55
+ language plpgsql volatile security definer
56
+ set search_path = public, extensions
57
+ as $$
58
+ begin
59
+ if p_default is null then
60
+ return null;
61
+ end if;
62
+ if not exists (select 1 from public.profiles where handle = p_default and id <> p_id) then
63
+ return p_default;
64
+ end if;
65
+ return public.generate_handle('', regexp_replace(p_default, '-[0-9]+$', ''));
66
+ end;
67
+ $$;
68
+
69
+ -- One trigger owns username + handle consistency (replaces core/001's
70
+ -- assign_handle and core/007's profiles_username_changed, whose relative order
71
+ -- mattered). "Trusted" writes are update-profile (service role) and this
72
+ -- file's security definer functions (they set community.trusted).
73
+ create or replace function public.profiles_names()
74
+ returns trigger
75
+ language plpgsql security definer
76
+ set search_path = public, extensions
77
+ as $$
78
+ declare
79
+ trusted boolean := coalesce(auth.role(), '') = 'service_role'
80
+ or coalesce(current_setting('community.trusted', true), '') = 'on';
81
+ prefix text;
82
+ begin
83
+ if tg_op = 'UPDATE' and new.username is distinct from old.username then
84
+ if not trusted and old.username_set_by_user then
85
+ -- Host sync after the user picked their own name: the user wins.
86
+ new.username := old.username;
87
+ elsif new.username is null
88
+ or (new.username = old.username_rejected and not trusted) then
89
+ -- Blanked (moderation sweep, old clients, account scrub) or a re-sync of
90
+ -- a name the sweep already blanked: back to the default name.
91
+ new.username := old.default_username;
92
+ new.username_checked_at := now();
93
+ elsif new.username is not distinct from new.default_username then
94
+ new.username_checked_at := now();
95
+ else
96
+ -- A genuinely new name: re-check it on the next sweep.
97
+ new.username_checked_at := null;
98
+ end if;
99
+ end if;
100
+
101
+ if new.username is not null and new.handle is null then
102
+ new.handle := public.generate_handle(new.username,
103
+ regexp_replace(coalesce(new.default_handle, ''), '-[0-9]+$', ''));
104
+ elsif tg_op = 'UPDATE'
105
+ and not new.handle_set_by_user
106
+ and not new.username_set_by_user
107
+ and new.username is distinct from old.username
108
+ and new.handle is not distinct from old.handle then
109
+ -- The host's name changed (or the sweep blanked it) and the user never
110
+ -- picked a handle: follow it.
111
+ if new.username is not distinct from new.default_username then
112
+ new.handle := coalesce(public.default_handle_for(new.id, new.default_handle), new.handle);
113
+ else
114
+ prefix := regexp_replace(coalesce(new.default_handle, ''), '-[0-9]+$', '');
115
+ new.handle := public.generate_handle(new.username, prefix);
116
+ end if;
117
+ end if;
118
+ return new;
119
+ end;
120
+ $$;
121
+
122
+ drop trigger if exists profiles_assign_handle on public.profiles;
123
+ drop trigger if exists profiles_username_changed_trg on public.profiles;
124
+ drop function if exists public.assign_handle();
125
+ drop function if exists public.profiles_username_changed();
126
+
127
+ create trigger profiles_names_trg
128
+ before insert or update of username, handle on public.profiles
129
+ for each row execute function public.profiles_names();
130
+
131
+ -- Called by the client once per launch; idempotent. `p_label` is the app's
132
+ -- default name in the user's language ("Frère"), `p_handle` its ASCII handle
133
+ -- prefix ("brother"). Fills username / handle only when still null.
134
+ create or replace function public.assign_default_profile(p_label text, p_handle text)
135
+ returns void
136
+ language plpgsql volatile security definer
137
+ set search_path = public, extensions
138
+ as $$
139
+ declare
140
+ uid uuid := auth.uid();
141
+ label text := left(btrim(coalesce(p_label, '')), 17);
142
+ h text;
143
+ name text;
144
+ begin
145
+ if uid is null then
146
+ return;
147
+ end if;
148
+ if exists (select 1 from public.profiles where id = uid and default_username is not null) then
149
+ return;
150
+ end if;
151
+ if label = '' then
152
+ label := 'User';
153
+ end if;
154
+ h := public.generate_handle('', coalesce(nullif(p_handle, ''), 'user'));
155
+ name := label || ' ' || substring(h from '-([0-9]+)$');
156
+ perform set_config('community.trusted', 'on', true);
157
+ update public.profiles
158
+ set default_username = name,
159
+ default_handle = h,
160
+ username = coalesce(username, name),
161
+ handle = coalesce(handle, h)
162
+ where id = uid;
163
+ perform set_config('community.trusted', '', true);
164
+ end;
165
+ $$;
166
+
167
+ -- Account deletion: default name and handle back, bio / avatar / edits cleared.
168
+ create or replace function public.reset_profile_identity()
169
+ returns void
170
+ language plpgsql volatile security definer
171
+ set search_path = public, extensions
172
+ as $$
173
+ declare
174
+ uid uuid := auth.uid();
175
+ begin
176
+ if uid is null then
177
+ return;
178
+ end if;
179
+ perform set_config('community.trusted', 'on', true);
180
+ update public.profiles
181
+ set username = default_username,
182
+ handle = coalesce(public.default_handle_for(id, default_handle), handle),
183
+ username_set_by_user = false,
184
+ handle_set_by_user = false,
185
+ bio = null,
186
+ avatar_url = null
187
+ where id = uid;
188
+ perform set_config('community.trusted', '', true);
189
+ end;
190
+ $$;
191
+
192
+ revoke execute on function public.generate_handle(text, text) from public, anon, authenticated;
193
+ revoke execute on function public.generate_handle(text) from public, anon, authenticated;
194
+ revoke execute on function public.default_handle_for(uuid, text) from public, anon, authenticated;
195
+ revoke execute on function public.profiles_names() from public, anon, authenticated;
196
+ revoke execute on function public.assign_default_profile(text, text) from public, anon;
197
+ revoke execute on function public.reset_profile_identity() from public, anon;
198
+ grant execute on function public.assign_default_profile(text, text) to authenticated;
199
+ grant execute on function public.reset_profile_identity() to authenticated;
@@ -0,0 +1,76 @@
1
+ -- Threaded replies and comment likes (after Eve's Rhythm's community v2).
2
+ --
3
+ -- Purely additive, safe for installed app versions: older clients never send
4
+ -- parent_id (null = a top-level comment) and never read comment_likes. A reply
5
+ -- is a comment whose parent_id points at the comment it answers; the app shows
6
+ -- replies one level deep, under their root comment.
7
+
8
+ -- ============ REPLIES ============
9
+ alter table public.comments
10
+ add column if not exists parent_id uuid references public.comments(id) on delete set null;
11
+ create index if not exists comments_parent_idx
12
+ on public.comments (parent_id) where parent_id is not null;
13
+
14
+ -- Column-scoped INSERT grant (002_rls.sql): add parent_id to what a client may
15
+ -- set. GRANT is additive, the other columns stay granted.
16
+ grant insert (parent_id) on table public.comments to authenticated;
17
+
18
+ -- A reply must answer a comment of the same post that the author can see.
19
+ -- SECURITY INVOKER on purpose: RLS hides hidden comments and blocked authors,
20
+ -- so one cannot reply to what one cannot read.
21
+ create or replace function public.comments_parent_same_post()
22
+ returns trigger language plpgsql set search_path = public as $$
23
+ begin
24
+ if not exists (
25
+ select 1 from comments c where c.id = new.parent_id and c.post_id = new.post_id
26
+ ) then
27
+ raise exception 'parent comment not found on this post' using errcode = '23503';
28
+ end if;
29
+ return new;
30
+ end; $$;
31
+
32
+ drop trigger if exists comments_parent_same_post on public.comments;
33
+ create trigger comments_parent_same_post
34
+ before insert on public.comments
35
+ for each row
36
+ when (new.parent_id is not null)
37
+ execute function public.comments_parent_same_post();
38
+
39
+ -- ============ COMMENT LIKES ============
40
+ -- One row per (comment, user), readable wherever the comment is readable,
41
+ -- written only as oneself. Likes on comments notify nobody.
42
+ --
43
+ -- user_id references auth.users, NOT public.profiles, on purpose: a
44
+ -- (comment_id, user_id) key with FKs to both comments and profiles is a
45
+ -- many-to-many junction to PostgREST, which would make every existing
46
+ -- `comments?select=profiles(...)` embed ambiguous (PGRST201) and break the
47
+ -- threads of installed app versions. Same ids either way: a profile's id is
48
+ -- its auth user's id.
49
+ create table if not exists public.comment_likes (
50
+ comment_id uuid not null references public.comments(id) on delete cascade,
51
+ user_id uuid not null references auth.users(id) on delete cascade,
52
+ created_at timestamptz not null default now(),
53
+ primary key (comment_id, user_id)
54
+ );
55
+ create index if not exists comment_likes_user_idx on public.comment_likes (user_id);
56
+
57
+ alter table public.comment_likes enable row level security;
58
+
59
+ drop policy if exists "comment likes readable where comment readable" on public.comment_likes;
60
+ create policy "comment likes readable where comment readable"
61
+ on public.comment_likes for select to authenticated
62
+ using (exists (select 1 from public.comments c where c.id = comment_likes.comment_id));
63
+
64
+ drop policy if exists "like comment as self" on public.comment_likes;
65
+ create policy "like comment as self"
66
+ on public.comment_likes for insert to authenticated
67
+ with check (user_id = auth.uid() and not public.current_user_banned());
68
+
69
+ drop policy if exists "unlike comment as self" on public.comment_likes;
70
+ create policy "unlike comment as self"
71
+ on public.comment_likes for delete to authenticated
72
+ using (user_id = auth.uid());
73
+
74
+ revoke all on table public.comment_likes from anon, authenticated;
75
+ grant select, delete on table public.comment_likes to authenticated;
76
+ grant insert (comment_id, user_id) on table public.comment_likes to authenticated;
@@ -0,0 +1,91 @@
1
+ -- Reply notifications and per-item read state.
2
+ --
3
+ -- Additive: installed app versions keep reading the same RPC and the
4
+ -- `notification_seen` watermark; a new `reply` kind shows on them through their
5
+ -- custom-row fallback (or not at all), and `notification_reads` is only
6
+ -- written by apps that mark items read one by one.
7
+
8
+ -- ============ REPLIES ============
9
+ -- Replaces inbox_on_comment (001_inbox.sql), same triggers (pending -> visible,
10
+ -- and direct visible inserts). A reply notifies only the author of the comment
11
+ -- it answers ('reply'); the post author gets 'comment' for top-level comments
12
+ -- (and for a reply whose parent is gone). Self-events and blocked actors never
13
+ -- notify. Needs core/010_comment_threads.sql (comments.parent_id).
14
+ create or replace function public.inbox_on_comment()
15
+ returns trigger language plpgsql security definer set search_path = public as $$
16
+ declare
17
+ post_author uuid;
18
+ parent_author uuid;
19
+ begin
20
+ select author_id into post_author from posts where id = new.post_id;
21
+ if new.parent_id is not null then
22
+ select author_id into parent_author from comments where id = new.parent_id;
23
+ end if;
24
+
25
+ if parent_author is not null and parent_author <> new.author_id
26
+ and not exists (
27
+ select 1 from blocks where blocker_id = parent_author and blocked_id = new.author_id
28
+ ) then
29
+ begin
30
+ insert into notifications (user_id, kind, actor_id, post_id)
31
+ values (parent_author, 'reply', new.author_id, new.post_id);
32
+ exception when others then null; -- the inbox must never break a comment
33
+ end;
34
+ end if;
35
+
36
+ if post_author is not null and post_author <> new.author_id
37
+ and parent_author is null
38
+ and not exists (
39
+ select 1 from blocks where blocker_id = post_author and blocked_id = new.author_id
40
+ ) then
41
+ begin
42
+ insert into notifications (user_id, kind, actor_id, post_id)
43
+ values (post_author, 'comment', new.author_id, new.post_id);
44
+ exception when others then null;
45
+ end;
46
+ end if;
47
+ return new;
48
+ end; $$;
49
+
50
+ -- ============ PER-ITEM READS ============
51
+ -- For apps that mark an item read when it is tapped (the SDK's `readMode:
52
+ -- "tap"`): an item is read when it is older than the `notification_seen`
53
+ -- watermark ("mark all as read" moves it) or listed here. `item_id` is the id
54
+ -- `list_notifications` returns: a notification's id, or an official post's id.
55
+ create table if not exists public.notification_reads (
56
+ user_id uuid not null references public.profiles(id) on delete cascade,
57
+ item_id uuid not null,
58
+ read_at timestamptz not null default now(),
59
+ primary key (user_id, item_id)
60
+ );
61
+
62
+ alter table public.notification_reads enable row level security;
63
+
64
+ drop policy if exists "read own reads" on public.notification_reads;
65
+ create policy "read own reads" on public.notification_reads
66
+ for select to authenticated using (user_id = auth.uid());
67
+ drop policy if exists "insert own reads" on public.notification_reads;
68
+ create policy "insert own reads" on public.notification_reads
69
+ for insert to authenticated with check (user_id = auth.uid());
70
+ drop policy if exists "delete own reads" on public.notification_reads;
71
+ create policy "delete own reads" on public.notification_reads
72
+ for delete to authenticated using (user_id = auth.uid());
73
+
74
+ revoke all on table public.notification_reads from anon, authenticated;
75
+ grant select, insert, delete on table public.notification_reads to authenticated;
76
+
77
+ -- Same retention as the notifications themselves.
78
+ do $$
79
+ begin
80
+ perform cron.schedule(
81
+ 'notification-reads-purge', '20 3 * * *',
82
+ $cron$ delete from public.notification_reads where read_at < now() - interval '90 days'; $cron$
83
+ );
84
+ exception when others then
85
+ if sqlerrm like '%already exists%' then
86
+ raise notice 'cron job notification-reads-purge already scheduled, skipping';
87
+ else
88
+ raise;
89
+ end if;
90
+ end;
91
+ $$;