@openpeepshq/core 0.7.0 → 0.8.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.
@@ -1,5 +1,5 @@
1
1
  import { getSharedConnection } from '../redis/index.js';
2
- const KEY_PREFIX = 'analytics:v5:';
2
+ const KEY_PREFIX = 'analytics:v6:';
3
3
  const OPEN_DAY_TTL_SEC = 60 * 60;
4
4
  const CLOSED_RANGE_TTL_SEC = 60 * 60 * 6;
5
5
  export const analyticsCacheKey = (section, from, to) => `${KEY_PREFIX}${section}:${from}:${to}`;
@@ -4,6 +4,7 @@ import { database } from '../db/index.js';
4
4
  import { analyticsDailyTotals } from '../db/pg/schema/analytics.js';
5
5
  import { logger } from '../log/index.js';
6
6
  import { invalidateAnalyticsCache } from './cache.js';
7
+ import { localMemberScope } from './memberScope.js';
7
8
  const log = logger('app:analytics:compile');
8
9
  const dayString = (d) => formatISO(startOfDay(d), { representation: 'date' });
9
10
  const dayBounds = (day) => {
@@ -51,23 +52,32 @@ export const compileAnalyticsDay = async (day) => {
51
52
  const jamParticipants = await countScalar(db, sql `select count(*)::int as c from jam_events
52
53
  where deleted_at is null and body->>'type' = 'join'
53
54
  and created_at >= ${start} and created_at < ${end}`);
55
+ // Scope to the same population as newMembers/totalMembersAt (local,
56
+ // non-deleted profiles) so the daily active_members rollup — and hence the
57
+ // overview series/chart — cannot exceed the member series. Composes from
58
+ // the shared localMemberScope fragment so a future query edit cannot
59
+ // silently drop it.
54
60
  const activeMembers = await countScalar(db, sql `select count(*)::int as c from (
55
- select creator_id as profile_id from posts
56
- where deleted_at is null
57
- and created_at >= ${start} and created_at < ${end}
58
- union
59
- select from_id from entries
60
- where body->>'type' in ('reaction', 'unreaction')
61
- and created_at >= ${start} and created_at < ${end}
62
- union
63
- select from_id from repost
64
- where created_at >= ${start} and created_at < ${end}
65
- union
66
- select from_id from reply_to
67
- where created_at >= ${start} and created_at < ${end}
68
- union
69
- select from_id from bookmarks
70
- where created_at >= ${start} and created_at < ${end}
61
+ select a.actor_id as profile_id
62
+ from (
63
+ select creator_id as actor_id from posts
64
+ where deleted_at is null
65
+ and created_at >= ${start} and created_at < ${end}
66
+ union
67
+ select from_id from entries
68
+ where body->>'type' in ('reaction', 'unreaction')
69
+ and created_at >= ${start} and created_at < ${end}
70
+ union
71
+ select from_id from repost
72
+ where created_at >= ${start} and created_at < ${end}
73
+ union
74
+ select from_id from reply_to
75
+ where created_at >= ${start} and created_at < ${end}
76
+ union
77
+ select from_id from bookmarks
78
+ where created_at >= ${start} and created_at < ${end}
79
+ ) a
80
+ ${localMemberScope(sql `a.actor_id`)}
71
81
  ) active`);
72
82
  await db
73
83
  .insert(analyticsDailyTotals)
@@ -210,6 +220,16 @@ export const compileAnalyticsDay = async (day) => {
210
220
  where created_at >= ${start} and created_at < ${end}
211
221
  group by to_id
212
222
  `);
223
+ // Cheap self-check that a future query edit cannot silently reintroduce the
224
+ // active-members > total-members bug this module once had. The rollup is
225
+ // scoped through localMemberScope, so this only trips on a real regression.
226
+ const memberPopulation = await countScalar(db, sql `select count(*)::int as c from profiles
227
+ where deleted_at is null and type = 'local'
228
+ and created_at < ${end}`);
229
+ if (activeMembers > memberPopulation) {
230
+ log.error(`active_members (${activeMembers}) exceeds the member population (${memberPopulation}) for ${day}; ` +
231
+ `the active-members scope join is likely broken`);
232
+ }
213
233
  log.info(`Compiled analytics for ${day}`);
214
234
  };
215
235
  export const compileRetentionCohorts = async () => {
@@ -0,0 +1,12 @@
1
+ import { type SQL } from 'drizzle-orm';
2
+ /**
3
+ * The member population the active-member metrics are measured against:
4
+ * local, non-deleted profiles (the same predicate as totalMembersAt and the
5
+ * newMembers rollup). The activeMembers card/MAU (via countDistinctActives)
6
+ * and the daily active_members rollup compose from this fragment so the
7
+ * active <= total invariant cannot regress through divergent copies of the
8
+ * scope. Retention cohorts and topMembers intentionally do NOT compose from
9
+ * it — they measure raw actor activity (whether the same profile acted, who
10
+ * contributed most), not member-population actives.
11
+ */
12
+ export declare const localMemberScope: (actorIdColumn: SQL) => SQL;
@@ -0,0 +1,13 @@
1
+ import { sql } from 'drizzle-orm';
2
+ /**
3
+ * The member population the active-member metrics are measured against:
4
+ * local, non-deleted profiles (the same predicate as totalMembersAt and the
5
+ * newMembers rollup). The activeMembers card/MAU (via countDistinctActives)
6
+ * and the daily active_members rollup compose from this fragment so the
7
+ * active <= total invariant cannot regress through divergent copies of the
8
+ * scope. Retention cohorts and topMembers intentionally do NOT compose from
9
+ * it — they measure raw actor activity (whether the same profile acted, who
10
+ * contributed most), not member-population actives.
11
+ */
12
+ export const localMemberScope = (actorIdColumn) => sql `join profiles p on p.id::text = ${actorIdColumn}
13
+ where p.type = 'local' and p.deleted_at is null`;
@@ -7,6 +7,7 @@ import { analyticsCacheKey, getAnalyticsCache, setAnalyticsCache, } from './cach
7
7
  import { aggregateSeriesIntoBuckets, eachUtcDay, resolveAnalyticsRange, selectChartBuckets, } from './dateRange.js';
8
8
  import { metricCard, sumSeries, averageSeries } from './metrics.js';
9
9
  import { isPublicAnalyticsGroup } from './privacy.js';
10
+ import { localMemberScope } from './memberScope.js';
10
11
  const POST_TYPE_KEYS = [
11
12
  'jam',
12
13
  'article',
@@ -24,24 +25,32 @@ const countDistinctActives = async (from, to) => {
24
25
  const db = await database();
25
26
  const start = utcDayStart(from);
26
27
  const end = exclusiveEnd(to);
28
+ // Scope actors to the same population as totalMembersAt (local,
29
+ // non-deleted profiles) so federated or deleted actors cannot make
30
+ // active members exceed total members. The scope composes from the shared
31
+ // localMemberScope fragment so a future query edit cannot silently drop it.
27
32
  const result = await db.execute(sql `
28
33
  select count(*)::int as c from (
29
- select creator_id as profile_id from posts
30
- where deleted_at is null
31
- and created_at >= ${start} and created_at < ${end}
32
- union
33
- select from_id from entries
34
- where body->>'type' in ('reaction', 'unreaction')
35
- and created_at >= ${start} and created_at < ${end}
36
- union
37
- select from_id from repost
38
- where created_at >= ${start} and created_at < ${end}
39
- union
40
- select from_id from reply_to
41
- where created_at >= ${start} and created_at < ${end}
42
- union
43
- select from_id from bookmarks
44
- where created_at >= ${start} and created_at < ${end}
34
+ select a.actor_id as profile_id
35
+ from (
36
+ select creator_id as actor_id from posts
37
+ where deleted_at is null
38
+ and created_at >= ${start} and created_at < ${end}
39
+ union
40
+ select from_id from entries
41
+ where body->>'type' in ('reaction', 'unreaction')
42
+ and created_at >= ${start} and created_at < ${end}
43
+ union
44
+ select from_id from repost
45
+ where created_at >= ${start} and created_at < ${end}
46
+ union
47
+ select from_id from reply_to
48
+ where created_at >= ${start} and created_at < ${end}
49
+ union
50
+ select from_id from bookmarks
51
+ where created_at >= ${start} and created_at < ${end}
52
+ ) a
53
+ ${localMemberScope(sql `a.actor_id`)}
45
54
  ) active
46
55
  `);
47
56
  const rows = result.rows;
@@ -85,18 +94,24 @@ const loadTotalsSeries = async (from, to, column) => {
85
94
  const sumColumn = async (from, to, column) => sumSeries(await loadTotalsSeries(from, to, column));
86
95
  const totalMembersAt = async (day) => {
87
96
  const db = await database();
88
- const end = `${day}T23:59:59.999Z`;
97
+ // Exclusive next-day boundary, matching the active-members rollup
98
+ // (compile.ts) and the self-check guard. `<= 23:59:59.999` missed
99
+ // microsecond-precision timestamps in the last millisecond of the day, so a
100
+ // profile created at range end would fall on one side of the
101
+ // active <= total invariant but not the other.
89
102
  const result = await db.execute(sql `
90
103
  select count(*)::int as c from profiles
91
104
  where deleted_at is null and type = 'local'
92
- and created_at <= ${end}
105
+ and created_at < ${exclusiveEnd(day)}
93
106
  `);
94
107
  const rows = result.rows;
95
108
  return Number(rows[0]?.c ?? 0);
96
109
  };
97
110
  const verifiedMembersAt = async (day) => {
98
111
  const db = await database();
99
- const end = `${day}T23:59:59.999Z`;
112
+ // Exclusive next-day boundary (see totalMembersAt) so a profile created in
113
+ // the day's final millisecond is counted like the active-members metrics.
114
+ const end = exclusiveEnd(day);
100
115
  const result = await db.execute(sql `
101
116
  select count(*)::int as c from profiles p
102
117
  join controls c on c.to_id = p.id::text
@@ -104,14 +119,16 @@ const verifiedMembersAt = async (day) => {
104
119
  where p.deleted_at is null and p.type = 'local'
105
120
  and a.deleted_at is null
106
121
  and a.email_validated = true
107
- and p.created_at <= ${end}
122
+ and p.created_at < ${end}
108
123
  `);
109
124
  const rows = result.rows;
110
125
  return Number(rows[0]?.c ?? 0);
111
126
  };
112
127
  const unverifiedMembersAt = async (day) => {
113
128
  const db = await database();
114
- const end = `${day}T23:59:59.999Z`;
129
+ // Exclusive next-day boundary (see totalMembersAt) so a profile created in
130
+ // the day's final millisecond is counted like the active-members metrics.
131
+ const end = exclusiveEnd(day);
115
132
  const result = await db.execute(sql `
116
133
  select count(*)::int as c from profiles p
117
134
  join controls c on c.to_id = p.id::text
@@ -119,7 +136,7 @@ const unverifiedMembersAt = async (day) => {
119
136
  where p.deleted_at is null and p.type = 'local'
120
137
  and a.deleted_at is null
121
138
  and a.email_validated = false
122
- and p.created_at <= ${end}
139
+ and p.created_at < ${end}
123
140
  `);
124
141
  const rows = result.rows;
125
142
  return Number(rows[0]?.c ?? 0);
@@ -621,7 +638,7 @@ export const getAnalyticsGrowth = async (query = {}) => {
621
638
  where p.deleted_at is null
622
639
  and p.type <> 'guest'
623
640
  and p.created_at >= ${`${range.from}T00:00:00.000Z`}
624
- and p.created_at <= ${`${range.to}T23:59:59.999Z`}
641
+ and p.created_at < ${exclusiveEnd(range.to)}
625
642
  order by p.created_at desc
626
643
  limit 25
627
644
  `),
@@ -66,6 +66,7 @@ export declare const communityConfig: () => Promise<{
66
66
  codeOfConduct?: string | undefined;
67
67
  welcomeEmail?: string | undefined;
68
68
  pinnedPost?: string | undefined;
69
+ autoFollow?: string[] | undefined;
69
70
  };
70
71
  settings: {
71
72
  openRegistrations: boolean;
@@ -1,7 +1,7 @@
1
- import { type PublicProfile, type PostWithMeta } from '@openpeepshq/common/types';
1
+ import { type JamWaitingRoomEntry, type PublicProfile, type PostWithMeta } from '@openpeepshq/common/types';
2
2
  export declare const isAdmittedToJam: (event: PostWithMeta, profileId: string, recurrenceId?: string) => Promise<boolean>;
3
3
  export declare const clearJamAdmittance: (event: PostWithMeta, recurrenceId?: string) => Promise<void>;
4
- export declare const currentWaitingRoomWatch: (jamEvent: PostWithMeta, onChange: (waitingRoom: Record<string, PublicProfile>) => void | Promise<void>, recurrenceId?: string) => Promise<() => Promise<void>>;
4
+ export declare const currentWaitingRoomWatch: (jamEvent: PostWithMeta, onChange: (waitingRoom: Record<string, JamWaitingRoomEntry>) => void | Promise<void>, recurrenceId?: string) => Promise<() => Promise<void>>;
5
5
  export declare const admittanceWatch: (jamEvent: PostWithMeta, profileId: string, onToken: (token: string) => Promise<void> | void, recurrenceId?: string) => Promise<() => Promise<void>>;
6
6
  export declare const joinWaitingRoom: (event: PostWithMeta, profile: PublicProfile, recurrenceId?: string) => Promise<void>;
7
7
  export declare const acceptFromWaitingRoom: (event: PostWithMeta, profileId: string, recurrenceId?: string) => Promise<undefined>;
@@ -1,7 +1,8 @@
1
1
  import { jamRoomName } from '@openpeepshq/common/lib';
2
- import { publicProfileSchema, } from '@openpeepshq/common/types';
2
+ import { jamWaitingRoomEntrySchema, } from '@openpeepshq/common/types';
3
3
  import { assertJamRsvpAllowed, createJamToken } from './token.js';
4
4
  import { disconnect, getConnection, getSharedConnection, } from '../redis/connection.js';
5
+ import { getProfile } from '../profiles/index.js';
5
6
  const waitingRoomKey = (event, recurrenceId) => `jams:waiting-room:${jamRoomName(event.id, recurrenceId)}`;
6
7
  const admittanceKey = (event, recurrenceId) => `jams:admitted:${jamRoomName(event.id, recurrenceId)}`;
7
8
  /** Keep admissions around for the length of a long jam / mobile backgrounding. */
@@ -10,12 +11,7 @@ const currentWaitingRoom = (event, recurrenceId) => getSharedConnection()
10
11
  .then((conn) => conn.hGetAll(waitingRoomKey(event, recurrenceId)))
11
12
  .then((wrRaw) => Object.entries(wrRaw))
12
13
  .then((entries) => entries.filter((e) => e[0] && e[1]))
13
- .then((entries) => entries.map(([key, value]) => [
14
- key,
15
- publicProfileSchema
16
- .partial()
17
- .parse(JSON.parse(value)),
18
- ]))
14
+ .then((entries) => entries.map(([key, value]) => [key, jamWaitingRoomEntrySchema.parse(JSON.parse(value))]))
19
15
  .then((entries) => Object.fromEntries(entries));
20
16
  const currentAdmittance = (event, recurrenceId) => getSharedConnection().then((conn) => conn.hGetAll(admittanceKey(event, recurrenceId)));
21
17
  export const isAdmittedToJam = async (event, profileId, recurrenceId) => {
@@ -60,18 +56,35 @@ export const joinWaitingRoom = async (event, profile, recurrenceId) => {
60
56
  assertJamRsvpAllowed(event, profile, recurrenceId);
61
57
  const conn = await getSharedConnection();
62
58
  const wrKey = waitingRoomKey(event, recurrenceId);
59
+ // Store only the display name keyed by profile id — the full object
60
+ // (incl. guestData) does not round-trip through the moderation stream.
61
+ // The admission path re-fetches the profile by id.
62
+ const entry = {
63
+ displayName: profile.displayName ?? profile.handle,
64
+ };
63
65
  // Do not clear admittance here — once admitted, the guest may reconnect
64
66
  // (mobile idle / tab freeze) without a second moderator approval.
65
- await conn.hSet(wrKey, { [profile.id]: JSON.stringify(profile) });
67
+ await conn.hSet(wrKey, { [profile.id]: JSON.stringify(entry) });
66
68
  };
67
69
  export const acceptFromWaitingRoom = async (event, profileId, recurrenceId) => {
68
70
  const conn = await getSharedConnection();
69
71
  const wrKey = waitingRoomKey(event, recurrenceId);
70
- const profile = await publicProfileSchema
71
- .parseAsync(JSON.parse((await conn.hGet(wrKey, profileId)) || 'undefined'))
72
- .catch(() => undefined);
72
+ const entryRaw = await conn.hGet(wrKey, profileId);
73
73
  await conn.hDel(wrKey, profileId);
74
- if (!event || !profile) {
74
+ if (!event || !entryRaw) {
75
+ return undefined;
76
+ }
77
+ const entry = jamWaitingRoomEntrySchema.safeParse(JSON.parse(entryRaw)).data;
78
+ if (!entry) {
79
+ return undefined;
80
+ }
81
+ // Re-fetch the full profile by id so token generation never depends on the
82
+ // streamed queue shape. A profile that can no longer be fetched (deleted
83
+ // while queued) is refused: the queue entry is already consumed above, so
84
+ // returning undefined is enough — never mint a token for a shapeless
85
+ // fabricated profile.
86
+ const profile = await getProfile(profileId, true);
87
+ if (!profile) {
75
88
  return undefined;
76
89
  }
77
90
  const aKey = admittanceKey(event, recurrenceId);
@@ -26,6 +26,27 @@ export declare const mergeOneToOnePreviews: (conversations: PostWithMeta[][]) =>
26
26
  * they authored but are no longer in the audience of. Returns
27
27
  * [root, lastReadablePost] per conversation so the user can still find and
28
28
  * view the conversation history after leaving.
29
+ *
30
+ * Leaf semantics: the leaf is the newest post above the leave chain that is
31
+ * not itself a leave note (i.e. the newest message the leaver can still read).
32
+ * Root is the deepest ancestor in the walk (thread start). The walk starts at
33
+ * the leave note and follows `reply_to` edges only, so the root is the
34
+ * reply-chain ancestor — for a thread whose newest post was deleted it still
35
+ * resolves through `reply_to` edges; posts linked only via a mention or uri
36
+ * (e.g. `in_reply_to_uri` federation rows) are not ancestors of the walk.
37
+ *
38
+ * Deleted posts: follows the active-inbox deletion semantics —
39
+ * postContextMappingForProfile uses softDelete: false, so deleted posts
40
+ * surface as tombstones in hydrateLeanPostsByIds. A deleted root or deleted
41
+ * intermediate node still produces a root/leaf pair; if hydrateLeanPostsByIds
42
+ * cannot resolve it, the preview is silently dropped (identical to the
43
+ * active inbox).
44
+ *
45
+ * The visibility = 'direct' filter on left_posts exists because public and
46
+ * group replies never carry an audience edge back to their creator, so without
47
+ * it every public reply would register as the leaver "leaving" the conversation.
48
+ * Leave notes are always created with visibility = 'direct' (see
49
+ * leaveConversation), making the filter exact.
29
50
  */
30
51
  export declare const listLeftConversations: (authData: AuthorizationData) => Promise<PostWithMeta[][]>;
31
52
  /**
@@ -34,6 +34,8 @@ export const listConversationRootLeafPairs = async (db, profileId) => {
34
34
  SELECT walk.leaf_id, rt.to_id, walk.depth + 1
35
35
  FROM reply_to rt
36
36
  INNER JOIN walk ON rt.from_id = walk.node_id
37
+ -- Unreachable for a well-formed reply tree; caps pathological data only.
38
+ WHERE walk.depth < 9999
37
39
  ),
38
40
  roots AS (
39
41
  SELECT DISTINCT ON (leaf_id) leaf_id, node_id AS root_id
@@ -167,6 +169,27 @@ export const mergeOneToOnePreviews = (conversations) => {
167
169
  * they authored but are no longer in the audience of. Returns
168
170
  * [root, lastReadablePost] per conversation so the user can still find and
169
171
  * view the conversation history after leaving.
172
+ *
173
+ * Leaf semantics: the leaf is the newest post above the leave chain that is
174
+ * not itself a leave note (i.e. the newest message the leaver can still read).
175
+ * Root is the deepest ancestor in the walk (thread start). The walk starts at
176
+ * the leave note and follows `reply_to` edges only, so the root is the
177
+ * reply-chain ancestor — for a thread whose newest post was deleted it still
178
+ * resolves through `reply_to` edges; posts linked only via a mention or uri
179
+ * (e.g. `in_reply_to_uri` federation rows) are not ancestors of the walk.
180
+ *
181
+ * Deleted posts: follows the active-inbox deletion semantics —
182
+ * postContextMappingForProfile uses softDelete: false, so deleted posts
183
+ * surface as tombstones in hydrateLeanPostsByIds. A deleted root or deleted
184
+ * intermediate node still produces a root/leaf pair; if hydrateLeanPostsByIds
185
+ * cannot resolve it, the preview is silently dropped (identical to the
186
+ * active inbox).
187
+ *
188
+ * The visibility = 'direct' filter on left_posts exists because public and
189
+ * group replies never carry an audience edge back to their creator, so without
190
+ * it every public reply would register as the leaver "leaving" the conversation.
191
+ * Leave notes are always created with visibility = 'direct' (see
192
+ * leaveConversation), making the filter exact.
170
193
  */
171
194
  export const listLeftConversations = async (authData) => {
172
195
  const profile = authData.profile;
@@ -175,33 +198,58 @@ export const listLeftConversations = async (authData) => {
175
198
  }
176
199
  const { db } = await allpeepDb();
177
200
  const result = (await db.execute(sql `
178
- WITH left_posts AS (
179
- SELECT p.id AS left_id, rt.to_id AS parent_id
201
+ WITH RECURSIVE left_posts AS (
202
+ SELECT p.id AS left_id
180
203
  FROM posts p
181
- INNER JOIN reply_to rt ON rt.from_id = p.id
204
+ INNER JOIN reply_to rt ON rt.from_id = p.id::text
182
205
  WHERE p.creator_id = ${profile.id}
206
+ AND p.visibility = 'direct'
183
207
  AND p.deleted_at IS NULL
184
208
  AND NOT EXISTS (
185
209
  SELECT 1 FROM audience a
186
- WHERE a.from_id = p.id AND a.to_id = p.creator_id
210
+ WHERE a.from_id = p.id::text AND a.to_id = p.creator_id
187
211
  )
188
212
  ),
189
213
  walk AS (
190
- SELECT lp.left_id AS conv_id, lp.parent_id AS leaf_id,
191
- lp.parent_id AS node_id, 0 AS depth
214
+ -- node_id is the reply-graph cursor: text, to match rt.from_id/to_id.
215
+ -- (posts.id is uuid, so the leave id must be cast to keep the
216
+ -- UNION ALL and the recursive join on one type.)
217
+ SELECT lp.left_id::text AS conv_id, lp.left_id::text AS node_id,
218
+ 0 AS depth
192
219
  FROM left_posts lp
193
220
  UNION ALL
194
- SELECT walk.conv_id, walk.leaf_id, rt.to_id, walk.depth + 1
221
+ SELECT walk.conv_id, rt.to_id, walk.depth + 1
195
222
  FROM reply_to rt
196
223
  INNER JOIN walk ON rt.from_id = walk.node_id
197
224
  WHERE walk.depth < 9999
198
225
  ),
199
226
  roots AS (
200
- SELECT DISTINCT ON (conv_id) conv_id, node_id AS root_id, leaf_id
227
+ SELECT DISTINCT ON (conv_id) conv_id, node_id AS root_id
201
228
  FROM walk
202
229
  ORDER BY conv_id, depth DESC
230
+ ),
231
+ leaves AS (
232
+ -- Leave notes are excluded from leaf candidacy so the leaf is the
233
+ -- newest *readable* post (the newest message the leaver can still
234
+ -- read), not the leave note itself.
235
+ SELECT DISTINCT ON (conv_id) conv_id, node_id AS leaf_id
236
+ FROM walk
237
+ WHERE NOT EXISTS (
238
+ SELECT 1 FROM left_posts lp WHERE lp.left_id::text = walk.node_id
239
+ )
240
+ ORDER BY conv_id, depth ASC
241
+ ),
242
+ combined AS (
243
+ SELECT r.root_id, l.leaf_id
244
+ FROM roots r
245
+ JOIN leaves l ON r.conv_id = l.conv_id
246
+ ),
247
+ best AS (
248
+ SELECT DISTINCT ON (root_id) root_id, leaf_id
249
+ FROM combined
250
+ ORDER BY root_id, leaf_id DESC
203
251
  )
204
- SELECT root_id, leaf_id FROM roots ORDER BY leaf_id DESC
252
+ SELECT root_id, leaf_id FROM best ORDER BY leaf_id DESC
205
253
  `));
206
254
  const pairs = result.rows.map((row) => ({
207
255
  rootId: row.root_id,
@@ -0,0 +1,9 @@
1
+ /** Subscribes the designated-account follows to profileCreated (once queue). */
2
+ export declare const registerAutoFollowHandler: () => void;
3
+ /**
4
+ * Test-only: clear the module-local registration flag so a fresh
5
+ * `registerAutoFollowHandler()` call re-subscribes. Without it, the
6
+ * once-per-process guard makes the handler un-reachable from a second test
7
+ * file (and the already-registered subscription is never re-created).
8
+ */
9
+ export declare const resetAutoFollowHandlerRegistration: () => void;
@@ -0,0 +1,35 @@
1
+ import { communityConfig } from '../config/index.js';
2
+ import { hub } from '../events/index.js';
3
+ import { getProfile } from './cache.js';
4
+ import { followDesignatedProfiles } from './mutations.js';
5
+ const handleProfileCreated = async (profileArg) => {
6
+ const profile = profileArg;
7
+ if (!profile?.id)
8
+ return;
9
+ // Event payload predates applyCommunityRoleChanges; re-read for final
10
+ // roles (and to skip profiles deleted before the job runs)
11
+ const fresh = await getProfile(profile.id);
12
+ if (!fresh)
13
+ return;
14
+ const autoFollow = (await communityConfig()).content.autoFollow;
15
+ if (!autoFollow?.length)
16
+ return;
17
+ await followDesignatedProfiles(fresh, autoFollow);
18
+ };
19
+ let registered = false;
20
+ /** Subscribes the designated-account follows to profileCreated (once queue). */
21
+ export const registerAutoFollowHandler = () => {
22
+ if (registered)
23
+ return;
24
+ registered = true;
25
+ hub.once('profileCreated', handleProfileCreated);
26
+ };
27
+ /**
28
+ * Test-only: clear the module-local registration flag so a fresh
29
+ * `registerAutoFollowHandler()` call re-subscribes. Without it, the
30
+ * once-per-process guard makes the handler un-reachable from a second test
31
+ * file (and the already-registered subscription is never re-created).
32
+ */
33
+ export const resetAutoFollowHandlerRegistration = () => {
34
+ registered = false;
35
+ };
@@ -7,4 +7,6 @@ export declare const getProfile: (id: string, ignoreSoftDelete?: boolean) => Pro
7
7
  export declare const getPublicProfile: (id: string, ignoreSoftDelete?: boolean) => Promise<ProfileWithMeta | undefined>;
8
8
  /** Local handle lookup only — federated paths must use uri or (handle, domain). */
9
9
  export declare const getProfileByHandle: (handle: string, ignoreSoftDelete?: boolean) => Promise<ProfileWithMeta | undefined>;
10
+ /** Local handle lookup scoped to the instance's default domain. */
11
+ export declare const getLocalProfileByHandle: (handle: string) => Promise<ProfileWithMeta | undefined>;
10
12
  export declare const getProfiles: (ids: string[]) => Promise<ProfileWithMeta[]>;
@@ -1,5 +1,6 @@
1
1
  import { createCache } from 'cache-manager';
2
2
  import { allpeepDb } from '../db/index.js';
3
+ import { config } from '../config/index.js';
3
4
  import { profilesMapping, publicProfilesMapping } from './mapping.js';
4
5
  import { loadBlockIds } from './blocks.js';
5
6
  export const profilesCache = createCache({
@@ -59,6 +60,19 @@ export const getProfileByHandle = async (handle, ignoreSoftDelete = false) => pr
59
60
  .findOneBy(db, { matches: { handle } })
60
61
  : profilesMapping.findOneBy(db, { matches: { handle } }))
61
62
  .then(withBlockIds));
63
+ /** Local handle lookup scoped to the instance's default domain. */
64
+ export const getLocalProfileByHandle = async (handle) => {
65
+ const { activityPub } = await config();
66
+ return allpeepDb()
67
+ .then(({ db }) => profilesMapping.findOneBy(db, {
68
+ matches: {
69
+ handle,
70
+ type: 'local',
71
+ activityPub: { domain: activityPub.defaultDomain },
72
+ },
73
+ }))
74
+ .then(withBlockIds);
75
+ };
62
76
  export const getProfiles = async (ids) => profilesCache
63
77
  .mget(ids)
64
78
  .then((profiles) => Promise.all(profiles.map(async (p, index) => p || (await getProfile(ids[index])))))
@@ -3,6 +3,7 @@ export * from './mutations';
3
3
  export * from './finders';
4
4
  export * from './export';
5
5
  export { getProfileActivitySummary, getAdminProfileSummary, } from './activitySummary';
6
- export { getProfile, getPublicProfile, getProfiles, clearProfileCache, } from './cache';
6
+ export { getProfile, getPublicProfile, getProfiles, getLocalProfileByHandle, clearProfileCache, } from './cache';
7
+ export { registerAutoFollowHandler } from './autoFollow';
7
8
  export { areBlocked, hasBlockAmong, loadBlockIds, listBlockingIds, } from './blocks';
8
9
  export declare const findNewFreeHandle: (seed: string) => Promise<string>;
@@ -6,7 +6,8 @@ export * from './mutations.js';
6
6
  export * from './finders.js';
7
7
  export * from './export.js';
8
8
  export { getProfileActivitySummary, getAdminProfileSummary, } from './activitySummary.js';
9
- export { getProfile, getPublicProfile, getProfiles, clearProfileCache, } from './cache.js';
9
+ export { getProfile, getPublicProfile, getProfiles, getLocalProfileByHandle, clearProfileCache, } from './cache.js';
10
+ export { registerAutoFollowHandler } from './autoFollow.js';
10
11
  export { areBlocked, hasBlockAmong, loadBlockIds, listBlockingIds, } from './blocks.js';
11
12
  const sanitizeHandle = (name) => name.replace(/[^a-zA-Z0-9]/g, '-');
12
13
  export const findNewFreeHandle = async (seed) => {
@@ -1,10 +1,38 @@
1
- import { Account, FollowData, GuestPassRequest, Profile, ProfileData, ProfileWithMeta, Role } from '@openpeepshq/common/types';
1
+ import { Account, AuthorizationData, FollowData, GuestPassRequest, Profile, ProfileData, ProfileWithMeta, Role } from '@openpeepshq/common/types';
2
2
  export declare const createProfile: (data: ProfileData, controllingAccount?: Account) => Promise<ProfileWithMeta>;
3
3
  export declare const createGuestProfile: (guestPassRequest: GuestPassRequest) => Promise<ProfileWithMeta>;
4
4
  export declare const updateProfile: (profileId: string, data: Partial<ProfileData>) => Promise<ProfileWithMeta>;
5
5
  export declare const pinPostOnProfile: (profile: Pick<Profile, "id" | "handle">, pinnedPostId: string) => Promise<ProfileWithMeta>;
6
6
  export declare const deleteProfile: (profileId: string) => Promise<void>;
7
7
  export declare const follow: (follower: Profile, followed: Profile, followData: FollowData) => Promise<void>;
8
+ /**
9
+ * Normalizes a configured auto-follow handle: strips a leading `@` and
10
+ * surrounding whitespace. Both the save-time validation (server PATCH
11
+ * backstop) and the follow resolution (auto-follow queue) must use this
12
+ * shared form so the two paths cannot drift apart.
13
+ */
14
+ export declare const normalizeAutoFollowHandle: (rawHandle: string) => string;
15
+ /**
16
+ * Whether `follower` may follow `target` under the same rules as
17
+ * `followProfileHandler`. Callers acting on behalf of a request pass the
18
+ * request's `authData` so its scopes are honored; queue callers omit it and
19
+ * are treated like in-app web session tokens (which always carry the
20
+ * `admin * *` scope). Restricted access tokens never reach this path — only
21
+ * `followProfileHandler` carries a token, and it passes the request's
22
+ * `authData` through — so the synthesized-scope shortcut must not be copied
23
+ * onto a token-bearing caller.
24
+ */
25
+ export declare const canFollowProfile: (follower: ProfileWithMeta, target: ProfileWithMeta, authData?: AuthorizationData) => Promise<{
26
+ success: boolean;
27
+ missingCapabilities: string[];
28
+ }>;
29
+ /**
30
+ * Makes a profile follow the community's designated accounts (community
31
+ * config `content.autoFollow`, by handle). Local, resolvable handles only.
32
+ * Skips the profile itself, blocked pairs, and profiles the follower may
33
+ * not follow; one failing follow never blocks the rest.
34
+ */
35
+ export declare const followDesignatedProfiles: (profile: ProfileWithMeta, handles: string[]) => Promise<void>;
8
36
  export declare const unfollow: (follower: Profile, followed: Profile) => Promise<void>;
9
37
  export declare const blockProfile: (blocker: Profile, blocked: Profile) => Promise<void>;
10
38
  export declare const unblockProfile: (blocker: Profile, blocked: Profile) => Promise<void>;
@@ -2,9 +2,11 @@ import { profilesMapping } from './mapping.js';
2
2
  import { allpeepDb } from '../db/index.js';
3
3
  import { followConnector, followDisconnector, followFinder, giveControl, roleAssigner, roleUnassigner, } from './helpers.js';
4
4
  import { hub } from '../events/index.js';
5
- import { randomString } from '@openpeepshq/common/lib';
5
+ import { checkProfileCapabilities, isBlockedPair, randomString, } from '@openpeepshq/common/lib';
6
+ import { capabilitiesConfig } from '../config/index.js';
6
7
  import { deleteAccessTokensForProfile } from '../accessTokens/helpers.js';
7
- import { profilesCache, getProfile, getPublicProfile, clearProfileCache, } from './cache.js';
8
+ import { profilesCache, getProfile, getPublicProfile, getLocalProfileByHandle, clearProfileCache, } from './cache.js';
9
+ import { logger } from '../log/index.js';
8
10
  import { accountsCache } from '../accounts/cache.js';
9
11
  import { assertProfileCapacity } from './capacity.js';
10
12
  import { deleteBlock, dropFollowsBetween, insertBlock, listBlockingIds, } from './blocks.js';
@@ -73,6 +75,68 @@ export const follow = async (follower, followed, followData) => {
73
75
  }
74
76
  await Promise.all([clearProfileCache(follower), clearProfileCache(followed)]);
75
77
  };
78
+ const log = logger('openpeeps:auto-follow');
79
+ const adminAllScope = {
80
+ scopeLevel: 'admin',
81
+ resource: { type: '*', id: '*' },
82
+ };
83
+ /**
84
+ * Normalizes a configured auto-follow handle: strips a leading `@` and
85
+ * surrounding whitespace. Both the save-time validation (server PATCH
86
+ * backstop) and the follow resolution (auto-follow queue) must use this
87
+ * shared form so the two paths cannot drift apart.
88
+ */
89
+ export const normalizeAutoFollowHandle = (rawHandle) => rawHandle.replace(/^@/, '').trim();
90
+ /**
91
+ * Whether `follower` may follow `target` under the same rules as
92
+ * `followProfileHandler`. Callers acting on behalf of a request pass the
93
+ * request's `authData` so its scopes are honored; queue callers omit it and
94
+ * are treated like in-app web session tokens (which always carry the
95
+ * `admin * *` scope). Restricted access tokens never reach this path — only
96
+ * `followProfileHandler` carries a token, and it passes the request's
97
+ * `authData` through — so the synthesized-scope shortcut must not be copied
98
+ * onto a token-bearing caller.
99
+ */
100
+ export const canFollowProfile = async (follower, target, authData) => {
101
+ const { success, missingCapabilities } = checkProfileCapabilities({
102
+ profile: follower,
103
+ scopes: authData?.scopes ?? [adminAllScope],
104
+ }, ['core-profiles-follow'], target, await capabilitiesConfig());
105
+ return { success, missingCapabilities };
106
+ };
107
+ /**
108
+ * Makes a profile follow the community's designated accounts (community
109
+ * config `content.autoFollow`, by handle). Local, resolvable handles only.
110
+ * Skips the profile itself, blocked pairs, and profiles the follower may
111
+ * not follow; one failing follow never blocks the rest.
112
+ */
113
+ export const followDesignatedProfiles = async (profile, handles) => {
114
+ for (const rawHandle of handles) {
115
+ const handle = normalizeAutoFollowHandle(rawHandle);
116
+ if (!handle || handle === profile.handle)
117
+ continue;
118
+ try {
119
+ const target = await getLocalProfileByHandle(handle);
120
+ if (!target) {
121
+ log.warn(`auto-follow target not found on this instance: ${handle}`);
122
+ continue;
123
+ }
124
+ if (isBlockedPair(profile, target.id)) {
125
+ log.warn(`auto-follow skipped, blocked pair: ${profile.handle} <-> ${handle}`);
126
+ continue;
127
+ }
128
+ const { success, missingCapabilities } = await canFollowProfile(profile, target);
129
+ if (!success) {
130
+ log.warn(`auto-follow skipped, missing capabilities ${missingCapabilities.join(', ')}: ${profile.handle} -> ${handle}`);
131
+ continue;
132
+ }
133
+ await follow(profile, target, { reblogs: true, notify: false });
134
+ }
135
+ catch (error) {
136
+ log.error(`auto-follow failed for ${handle}`, error);
137
+ }
138
+ }
139
+ };
76
140
  export const unfollow = async (follower, followed) => {
77
141
  const { db } = await allpeepDb();
78
142
  await followDisconnector(db, follower, followed);
@@ -67,6 +67,7 @@ export declare const serverInfo: () => Promise<{
67
67
  codeOfConduct?: string | undefined;
68
68
  welcomeEmail?: string | undefined;
69
69
  pinnedPost?: string | undefined;
70
+ autoFollow?: string[] | undefined;
70
71
  };
71
72
  settings: {
72
73
  openRegistrations: boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openpeepshq/core",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "type": "module",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "dependencies": {
@@ -37,10 +37,10 @@
37
37
  "type-fest": "^4.31.0",
38
38
  "uuidv7": "^1.0.2",
39
39
  "web-push": "^3.6.7",
40
- "@openpeepshq/common": "0.9.0",
40
+ "@openpeepshq/common": "0.10.0",
41
+ "@openpeepshq/fetch-client": "^0.2.1",
41
42
  "@openpeepshq/geocoder": "^0.1.2",
42
- "@openpeepshq/i18n": "^0.10.0",
43
- "@openpeepshq/fetch-client": "^0.2.1"
43
+ "@openpeepshq/i18n": "^0.11.0"
44
44
  },
45
45
  "main": "dist/index.js",
46
46
  "types": "dist/index.d.ts",