@openpeepshq/core 0.30.0 → 0.31.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.
@@ -3,6 +3,8 @@ import type { Profile, EntryData, PostWithMeta, Notification, ReactionData, JamR
3
3
  export type CoreEvents = {
4
4
  profileCreated: (profile: Profile) => void;
5
5
  postCreated: (post: PostWithMeta) => void;
6
+ postUpdated: (post: PostWithMeta, previousJamModerators: string[]) => void;
7
+ postDeleted: (post: PostWithMeta) => void;
6
8
  jamRecordingCompleted: (recording: JamRecordingWithMeta) => void;
7
9
  followCreated: (follower: Profile, followed: Profile) => void;
8
10
  /** Follow edge removed (unfollow). Federation reacts by sending Undo(Follow) for outbound follows only. */
@@ -34,5 +36,20 @@ export declare const hub: {
34
36
  emit: (eventType: string, ...eventArgs: unknown[]) => Promise<void>;
35
37
  on: <T extends unknown[]>(eventType: string, handler: (...args: T) => unknown) => Unsubscribe;
36
38
  once: (eventType: string, handler: (...args: unknown[]) => unknown) => void;
39
+ /**
40
+ * Resolves once every `on` subscription registered so far has finished its
41
+ * asynchronous Redis connect + SUBSCRIBE. Await this before relying on
42
+ * pub/sub delivery: an `emit` published while a subscription is still
43
+ * pending is lost (Redis has no subscriber to deliver to). Federation
44
+ * attaches correctness-critical handlers (`postDeleted` tombstones), so
45
+ * `installFederation` awaits this before the server accepts writes.
46
+ *
47
+ * Bounded by `SUBSCRIBE_READY_TIMEOUT_MS`: node-redis retries `connect()`
48
+ * forever, so an unavailable Redis would otherwise hold server startup
49
+ * hostage. On timeout we proceed with a warning — a down Redis already
50
+ * degrades every hub consumer (emits fail too), so waiting longer buys
51
+ * nothing.
52
+ */
53
+ ready: () => Promise<void>;
37
54
  };
38
55
  export { onceWorker, onceQueue } from './once';
@@ -2,11 +2,15 @@ import { getConnection } from '../redis/connection.js';
2
2
  import { logger } from '../log/index.js';
3
3
  import { onceQueue, registerOnceHandler } from './once.js';
4
4
  const log = logger('app:events');
5
+ /** Upper bound on `hub.ready()`'s wait for in-flight `on` subscriptions. */
6
+ const SUBSCRIBE_READY_TIMEOUT_MS = 10_000;
5
7
  // `satisfies Record<CoreEventKey, true>` guarantees at compile time that every
6
8
  // event key is present and that no unexpected keys can slip in.
7
9
  const validEventKeyMap = {
8
10
  profileCreated: true,
9
11
  postCreated: true,
12
+ postUpdated: true,
13
+ postDeleted: true,
10
14
  jamRecordingCompleted: true,
11
15
  followCreated: true,
12
16
  followDeleted: true,
@@ -33,6 +37,11 @@ const publishConnection = async () => {
33
37
  };
34
38
  const baseHub = (prefix) => {
35
39
  const subscriptions = new Map();
40
+ // Subscribe promises in flight. `on` registers a handler and then subscribes
41
+ // asynchronously (Redis connect + SUBSCRIBE), so there is a window in which an
42
+ // `emit` publishes to a channel that has no subscriber yet. `ready()` lets a
43
+ // caller await that window closing before relying on delivery.
44
+ const pendingSubscriptions = new Set();
36
45
  return {
37
46
  /**
38
47
  * Fan-out must not fail the caller (register/react/etc.). Redis publish and
@@ -57,7 +66,8 @@ const baseHub = (prefix) => {
57
66
  },
58
67
  on: (eventType, handler) => {
59
68
  const channel = `${prefix}:${eventType}`;
60
- getConnection().then((conn) => {
69
+ const sub = getConnection()
70
+ .then((conn) => {
61
71
  conn.subscribe(channel, (message) => {
62
72
  const args = JSON.parse(message);
63
73
  handler(...args);
@@ -68,7 +78,15 @@ const baseHub = (prefix) => {
68
78
  subscriptions.set(channel, entry);
69
79
  }
70
80
  entry.channels.push(channel);
81
+ })
82
+ .catch((err) => {
83
+ // Subscribe is best-effort like emit, but a permanently failed
84
+ // subscription means this handler is dead — log it rather than
85
+ // leaving a floating rejected promise.
86
+ log.error({ channel, err }, 'hub subscribe failed');
71
87
  });
88
+ pendingSubscriptions.add(sub);
89
+ void sub.finally(() => pendingSubscriptions.delete(sub));
72
90
  return () => {
73
91
  getConnection().then((conn) => conn.unsubscribe(channel));
74
92
  const entry = subscriptions.get(channel);
@@ -83,6 +101,37 @@ const baseHub = (prefix) => {
83
101
  once: (eventType, handler) => {
84
102
  registerOnceHandler(`${prefix}:${eventType}`, handler);
85
103
  },
104
+ /**
105
+ * Resolves once every `on` subscription registered so far has finished its
106
+ * asynchronous Redis connect + SUBSCRIBE. Await this before relying on
107
+ * pub/sub delivery: an `emit` published while a subscription is still
108
+ * pending is lost (Redis has no subscriber to deliver to). Federation
109
+ * attaches correctness-critical handlers (`postDeleted` tombstones), so
110
+ * `installFederation` awaits this before the server accepts writes.
111
+ *
112
+ * Bounded by `SUBSCRIBE_READY_TIMEOUT_MS`: node-redis retries `connect()`
113
+ * forever, so an unavailable Redis would otherwise hold server startup
114
+ * hostage. On timeout we proceed with a warning — a down Redis already
115
+ * degrades every hub consumer (emits fail too), so waiting longer buys
116
+ * nothing.
117
+ */
118
+ ready: async () => {
119
+ const start = Date.now();
120
+ while (pendingSubscriptions.size > 0) {
121
+ const remaining = SUBSCRIBE_READY_TIMEOUT_MS - (Date.now() - start);
122
+ const settled = await Promise.race([
123
+ Promise.allSettled([...pendingSubscriptions]).then(() => 'settled'),
124
+ new Promise((resolve) => setTimeout(() => resolve('timeout'), Math.max(0, remaining)).unref()),
125
+ ]);
126
+ if (settled === 'timeout' && pendingSubscriptions.size > 0) {
127
+ log.warn({
128
+ pending: pendingSubscriptions.size,
129
+ elapsedMs: Date.now() - start,
130
+ }, 'hub subscriptions still pending; continuing without them');
131
+ return;
132
+ }
133
+ }
134
+ },
86
135
  };
87
136
  };
88
137
  export const hub = baseHub('allpeep:core');
@@ -26,6 +26,23 @@ export type RemoteActorInput = {
26
26
  bio?: string;
27
27
  avatar?: string | null;
28
28
  };
29
+ /**
30
+ * Derive a local `profiles.handle` for a federated actor from its
31
+ * `preferredUsername` (falling back to the actor URI).
32
+ *
33
+ * The handle is **lowercased** because the federated identity key
34
+ * `(handle, domain)` is case-insensitive: mention extraction
35
+ * (`matchFederatedMentionTokens`) already lowercases both halves, so
36
+ * `@Bob@Mastodon.Social` looks up `('bob', 'mastodon.social')`. Storing the
37
+ * raw `preferredUsername` verbatim (`Bob`) would make that exact-match lookup
38
+ * miss. Lowercasing at the single ingest source (both `upsertRemoteActor`
39
+ * callers) keeps the stored key and the lookup key in the same shape.
40
+ *
41
+ * Migration note: rows ingested before this normalisation keep their original
42
+ * case, so a mixed-case `(handle, domain)` may not resolve until backfilled —
43
+ * and the `(handle, domain)` uniqueness is now effectively case-insensitive,
44
+ * so `Bob`/`bob` on the same domain must be treated as one actor, not two.
45
+ */
29
46
  export declare const federatedHandleFrom: (preferred: string | null | undefined, uri: string) => string;
30
47
  export declare const loadLocalActor: (profileId: string) => Promise<LocalActor | null>;
31
48
  export declare const findLocalActorIdByHandle: (handle: string) => Promise<string | null>;
@@ -6,13 +6,34 @@ import { nowIso } from '../db/pg/mappers.js';
6
6
  import { profiles } from '../db/pg/schema/documents.js';
7
7
  import { profilesMapping } from '../profiles/mapping.js';
8
8
  import { findProfileByHandleAndDomain, findProfileByUri } from './profiles.js';
9
+ /**
10
+ * Derive a local `profiles.handle` for a federated actor from its
11
+ * `preferredUsername` (falling back to the actor URI).
12
+ *
13
+ * The handle is **lowercased** because the federated identity key
14
+ * `(handle, domain)` is case-insensitive: mention extraction
15
+ * (`matchFederatedMentionTokens`) already lowercases both halves, so
16
+ * `@Bob@Mastodon.Social` looks up `('bob', 'mastodon.social')`. Storing the
17
+ * raw `preferredUsername` verbatim (`Bob`) would make that exact-match lookup
18
+ * miss. Lowercasing at the single ingest source (both `upsertRemoteActor`
19
+ * callers) keeps the stored key and the lookup key in the same shape.
20
+ *
21
+ * Migration note: rows ingested before this normalisation keep their original
22
+ * case, so a mixed-case `(handle, domain)` may not resolve until backfilled —
23
+ * and the `(handle, domain)` uniqueness is now effectively case-insensitive,
24
+ * so `Bob`/`bob` on the same domain must be treated as one actor, not two.
25
+ */
9
26
  export const federatedHandleFrom = (preferred, uri) => {
10
27
  const fromName = (preferred ?? '')
11
28
  .replace(/[^a-zA-Z0-9_.-]/g, '')
29
+ .toLowerCase()
12
30
  .slice(0, 64);
13
31
  if (fromName.length >= 1)
14
32
  return fromName;
15
- const fromUri = uri.replace(/[^a-zA-Z0-9]/g, '').slice(-16);
33
+ const fromUri = uri
34
+ .replace(/[^a-zA-Z0-9]/g, '')
35
+ .toLowerCase()
36
+ .slice(-16);
16
37
  return `actor-${fromUri || 'remote'}`;
17
38
  };
18
39
  const clipDisplayName = (name) => name ? name.slice(0, 30) : undefined;
@@ -6,6 +6,8 @@ export declare const FOLLOWERS_PATH: "/ap/users/{identifier}/followers";
6
6
  export declare const NOTE_PATH: "/ap/objects/{id}";
7
7
  export declare const CREATE_PATH: "/ap/create/{id}";
8
8
  export declare const ACCEPT_PATH: "/ap/accept/{id}";
9
+ export declare const UPDATE_PATH: "/ap/update/{id}";
10
+ export declare const DELETE_PATH: "/ap/delete/{id}";
9
11
  export declare const federationOrigin: (domain: string) => string;
10
12
  export declare const actorUri: (domain: string, profileId: string) => string;
11
13
  export declare const objectUri: (domain: string, postId: string) => string;
@@ -10,6 +10,8 @@ export const FOLLOWERS_PATH = '/ap/users/{identifier}/followers';
10
10
  export const NOTE_PATH = '/ap/objects/{id}';
11
11
  export const CREATE_PATH = '/ap/create/{id}';
12
12
  export const ACCEPT_PATH = '/ap/accept/{id}';
13
+ export const UPDATE_PATH = '/ap/update/{id}';
14
+ export const DELETE_PATH = '/ap/delete/{id}';
13
15
  export const federationOrigin = (domain) => `https://${domain}`;
14
16
  export const actorUri = (domain, profileId) => `https://${domain}/ap/users/${profileId}`;
15
17
  export const objectUri = (domain, postId) => `https://${domain}/ap/objects/${postId}`;
@@ -2,7 +2,7 @@ export { deleteOutboundFollow, findApActivityByUri, findOutboundFollow, recordAp
2
2
  export type { ApActivity, ApActivityDirection } from './activities';
3
3
  export { federatedHandleFrom, findLocalActorIdByHandle, loadLocalActor, loadLocalActorKeys, upsertRemoteActor, } from './actors';
4
4
  export type { LocalActor, LocalActorKeys, RemoteActorInput } from './actors';
5
- export { ACCEPT_PATH, ACTOR_INBOX_PATH, ACTOR_PATH, CREATE_PATH, FOLLOWERS_PATH, NOTE_PATH, SHARED_INBOX_PATH, acceptActivityUri, actorUri, backfillLocalFederationIdentities, createActivityUri, federationOrigin, generateActorKeyPair, localActorScalars, localObjectScalars, objectUri, } from './identity';
5
+ export { ACCEPT_PATH, ACTOR_INBOX_PATH, ACTOR_PATH, CREATE_PATH, DELETE_PATH, FOLLOWERS_PATH, NOTE_PATH, SHARED_INBOX_PATH, UPDATE_PATH, acceptActivityUri, actorUri, backfillLocalFederationIdentities, createActivityUri, federationOrigin, generateActorKeyPair, localActorScalars, localObjectScalars, objectUri, } from './identity';
6
6
  export { ingestIncomingFollow, ingestIncomingUnfollow, listFederatedFollowerRecipients, withoutBlockedRecipients, } from './ingest';
7
7
  export type { FollowerRecipient } from './ingest';
8
8
  export { loadPublicNote } from './notes';
@@ -1,6 +1,6 @@
1
1
  export { deleteOutboundFollow, findApActivityByUri, findOutboundFollow, recordApActivity, } from './activities.js';
2
2
  export { federatedHandleFrom, findLocalActorIdByHandle, loadLocalActor, loadLocalActorKeys, upsertRemoteActor, } from './actors.js';
3
- export { ACCEPT_PATH, ACTOR_INBOX_PATH, ACTOR_PATH, CREATE_PATH, FOLLOWERS_PATH, NOTE_PATH, SHARED_INBOX_PATH, acceptActivityUri, actorUri, backfillLocalFederationIdentities, createActivityUri, federationOrigin, generateActorKeyPair, localActorScalars, localObjectScalars, objectUri, } from './identity.js';
3
+ export { ACCEPT_PATH, ACTOR_INBOX_PATH, ACTOR_PATH, CREATE_PATH, DELETE_PATH, FOLLOWERS_PATH, NOTE_PATH, SHARED_INBOX_PATH, UPDATE_PATH, acceptActivityUri, actorUri, backfillLocalFederationIdentities, createActivityUri, federationOrigin, generateActorKeyPair, localActorScalars, localObjectScalars, objectUri, } from './identity.js';
4
4
  export { ingestIncomingFollow, ingestIncomingUnfollow, listFederatedFollowerRecipients, withoutBlockedRecipients, } from './ingest.js';
5
5
  export { loadPublicNote } from './notes.js';
6
6
  export { federationIsActive, hostnameOf, peerHostAllowed } from './peers.js';
@@ -4,5 +4,23 @@ export type PublicNote = {
4
4
  content: string;
5
5
  published: string;
6
6
  inReplyToUri: string | null;
7
+ /**
8
+ * Actor URIs of remote (federated) profiles mentioned in the note.
9
+ * Populated only by `loadPublicNote`'s mention-join and consumed only by the
10
+ * server's Fedify Note dispatcher (which CCs the mentionees); there is no
11
+ * other consumer today. Keep any new consumer server-dispatcher-side so the
12
+ * join stays scoped to federation delivery.
13
+ *
14
+ * Deliberately **create-time-frozen**: `updatePost` re-links hashtags but
15
+ * does not re-resolve/re-connect mention edges (the pre-existing local
16
+ * semantic — a local edit has never changed who is mentioned, and
17
+ * notification re-fan-out on edit is not in scope). Every subsequent
18
+ * `Update(Note)` therefore CCs the *original* mention set: a mention added
19
+ * on an edit is not CC'd remotely, and a removed one stays CC'd until the
20
+ * note is deleted. That is a documented decision (Phase R review round 4,
21
+ * item 2), not an accident — if remote edit-time mention changes become
22
+ * required, re-link the mention edges in `updatePost` first.
23
+ */
24
+ mentionUris: string[];
7
25
  };
8
26
  export declare const loadPublicNote: (postId: string) => Promise<PublicNote | null>;
@@ -1,6 +1,8 @@
1
1
  import { and, eq, isNotNull, isNull } from 'drizzle-orm';
2
2
  import { pgDb } from '../db/pg/client.js';
3
3
  import { posts } from '../db/pg/schema/documents.js';
4
+ import { profiles } from '../db/pg/schema/documents.js';
5
+ import { mentions } from '../db/pg/schema/edges.js';
4
6
  export const loadPublicNote = async (postId) => {
5
7
  const db = pgDb();
6
8
  const [row] = await db
@@ -20,11 +22,20 @@ export const loadPublicNote = async (postId) => {
20
22
  if (!row || row.type !== 'note' || row.visibility !== 'public')
21
23
  return null;
22
24
  const body = (row.body ?? {});
25
+ const mentionRows = await db
26
+ .select({ uri: profiles.uri })
27
+ .from(mentions)
28
+ .innerJoin(profiles, eq(mentions.toId, profiles.id))
29
+ .where(and(eq(mentions.fromId, postId), isNull(profiles.deletedAt), eq(profiles.type, 'federated')));
30
+ const mentionUris = mentionRows
31
+ .map((m) => m.uri)
32
+ .filter((uri) => Boolean(uri));
23
33
  return {
24
34
  id: row.id,
25
35
  creatorId: row.creatorId,
26
36
  content: body.content ?? '',
27
37
  published: row.createdAt,
28
38
  inReplyToUri: row.inReplyToUri,
39
+ mentionUris,
29
40
  };
30
41
  };
@@ -1,7 +1,8 @@
1
1
  import { notificationAll, } from '@openpeepshq/common/types';
2
- import { extractMentionHandles } from '@openpeepshq/core/posts';
2
+ import { extractFederatedMentionTokens } from '@openpeepshq/core/posts';
3
3
  import { findPost } from '@openpeepshq/core/posts';
4
4
  import { findProfile, findProfileByHandle } from '@openpeepshq/core/profiles';
5
+ import { findProfileByHandleAndDomain } from '@openpeepshq/core/federation';
5
6
  import { maybeCreateNotification } from '@openpeepshq/core/notifications';
6
7
  import { getProfileAvatar, profileName } from '@openpeepshq/common/lib';
7
8
  import { communityConfig } from '../../../config/index.js';
@@ -15,8 +16,13 @@ const getMentionedProfiles = async (post) => {
15
16
  }
16
17
  }
17
18
  if (byId.size === 0) {
18
- for (const handle of extractMentionHandles(post.data?.content)) {
19
- const profile = await findProfileByHandle(handle);
19
+ for (const token of extractFederatedMentionTokens(post.data?.content)) {
20
+ const [handle, domain] = token.includes('@')
21
+ ? token.split('@')
22
+ : [token, undefined];
23
+ const profile = domain
24
+ ? await findProfileByHandleAndDomain(handle, domain)
25
+ : await findProfileByHandle(handle);
20
26
  if (profile) {
21
27
  byId.set(profile.id, profile);
22
28
  }
@@ -10,6 +10,11 @@ export declare const isLocal: (post: PostWithMeta) => boolean;
10
10
  export * from './filters';
11
11
  export declare const extractHashtags: (data: PostDataUnion) => string[];
12
12
  export declare const extractMentionHandles: (text?: string) => string[];
13
+ /**
14
+ * Every mention token in the text: local `@handle` plus remote
15
+ * `handle@domain` (domain lowercased).
16
+ */
17
+ export declare const extractFederatedMentionTokens: (text?: string) => string[];
13
18
  export declare const resolveMentionsForPost: (data: PostDataUnion) => Promise<MentionWithPublicProfile[]>;
14
19
  export declare const entryConnector: (db: import("../../db").PgDb, from: Profile, to: Post, data?: ({
15
20
  type: "create";
@@ -5,7 +5,8 @@ import { composeFilters, connectionFinder, connector, disconnector, filterAndTra
5
5
  import { allpeepDb, collectionInfos } from '../../db/index.js';
6
6
  import { capabilitiesConfig } from '../../config/index.js';
7
7
  import { canReadPost } from './filters.js';
8
- import { currentReactionsFromEntries, isBlockedPair, isReactionHistoryEntry, isReactionType, matchMentionHandles, normalizePostDataFromDb, toHiddenPost, tombstoneProfileWithMetaIfDeleted, } from '@openpeepshq/common/lib';
8
+ import { currentReactionsFromEntries, isBlockedPair, isReactionHistoryEntry, isReactionType, matchFederatedMentionTokens, matchMentionHandles, normalizePostDataFromDb, toHiddenPost, tombstoneProfileWithMetaIfDeleted, } from '@openpeepshq/common/lib';
9
+ import { findProfileByHandleAndDomain } from '../../federation/profiles.js';
9
10
  import { EMBEDDED_REPOSTS_LIMIT } from '../mapping.js';
10
11
  import { loadThreadPreviewReplies } from '../threadPreview.js';
11
12
  export const isDirect = (post) => post.visibility === 'direct';
@@ -28,12 +29,37 @@ export const extractHashtags = (data) => {
28
29
  return [...new Set([...fromContent, ...fromTags])];
29
30
  };
30
31
  export const extractMentionHandles = (text) => matchMentionHandles(text);
32
+ /**
33
+ * Every mention token in the text: local `@handle` plus remote
34
+ * `handle@domain` (domain lowercased).
35
+ */
36
+ export const extractFederatedMentionTokens = (text) => matchFederatedMentionTokens(text);
31
37
  export const resolveMentionsForPost = async (data) => {
32
38
  const byProfileId = new Map();
33
- for (const handle of extractMentionHandles(data.content)) {
34
- const profile = await findProfileByHandle(handle);
39
+ for (const token of extractFederatedMentionTokens(data.content)) {
40
+ const [handle, domain] = token.includes('@')
41
+ ? token.split('@')
42
+ : [token, undefined];
43
+ // Local remains the fast path; a remote `handle@domain` token resolves
44
+ // through the federated finder first, then falls back to a local profile
45
+ // with the same handle (keeps behavior for ambiguous local handles).
46
+ // Fallback side effect: when the federated finder misses and a *local*
47
+ // profile matches, the stored `MentionData.text` keeps the `@domain`
48
+ // suffix (`@bob@mastodon.social` against local bob). Consumers of
49
+ // `MentionData.text` must therefore handle both the bare local-handle
50
+ // shape and the `handle@domain` shape for the same profile.
51
+ const profile = domain
52
+ ? ((await findProfileByHandleAndDomain(handle, domain)) ??
53
+ (await findProfileByHandle(handle)))
54
+ : await findProfileByHandle(handle);
35
55
  if (profile) {
36
- byProfileId.set(profile.id, { profile, text: `@${handle}` });
56
+ // Handles are case-insensitive identity keys, so the stored mention text
57
+ // is normalised to lowercase on both branches (remote tokens are already
58
+ // lowercased at extraction) to keep `MentionData.text` a consistent shape.
59
+ byProfileId.set(profile.id, {
60
+ profile,
61
+ text: `@${handle.toLowerCase()}${domain ? `@${domain}` : ''}`,
62
+ });
37
63
  }
38
64
  }
39
65
  return [...byProfileId.values()];
@@ -316,6 +316,9 @@ export const deletePost = async (post, profile) => {
316
316
  if (post.type === 'question') {
317
317
  await cancelPollEnd(post.id);
318
318
  }
319
+ // Fires after the post row is gone from the DB, so federation handlers
320
+ // cannot re-load the note and must rely on the pre-delete `post.uri`.
321
+ hub.emit('postDeleted', post);
319
322
  return postsMapping.find(db, post.id);
320
323
  };
321
324
  export const validatePollVote = (post, data) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openpeepshq/core",
3
- "version": "0.30.0",
3
+ "version": "0.31.0",
4
4
  "type": "module",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "dependencies": {
@@ -37,8 +37,8 @@
37
37
  "type-fest": "^4.31.0",
38
38
  "uuidv7": "^1.0.2",
39
39
  "web-push": "^3.6.7",
40
- "@openpeepshq/common": "0.32.0",
41
40
  "@openpeepshq/fetch-client": "^0.3.0",
41
+ "@openpeepshq/common": "0.33.0",
42
42
  "@openpeepshq/geocoder": "^0.1.2",
43
43
  "@openpeepshq/i18n": "^0.33.0"
44
44
  },