@openpeepshq/core 0.16.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -73,6 +73,7 @@ export const defaultConfig = {
73
73
  federation: {
74
74
  active: false,
75
75
  allowedHosts: [],
76
+ blockedHosts: [],
76
77
  },
77
78
  activityPub: {
78
79
  defaultDomain: process.env.ACTIVITY_PUB_DEFAULT_DOMAIN || 'localhost',
@@ -3,7 +3,7 @@ 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
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';
6
- export { ingestIncomingFollow, ingestIncomingUnfollow, listFederatedFollowerRecipients, } from './ingest';
6
+ export { ingestIncomingFollow, ingestIncomingUnfollow, listFederatedFollowerRecipients, withoutBlockedRecipients, } from './ingest';
7
7
  export type { FollowerRecipient } from './ingest';
8
8
  export { loadPublicNote } from './notes';
9
9
  export type { PublicNote } from './notes';
@@ -1,7 +1,7 @@
1
1
  export { findApActivityByUri, recordApActivity } from './activities.js';
2
2
  export { federatedHandleFrom, findLocalActorIdByHandle, loadLocalActor, loadLocalActorKeys, upsertRemoteActor, } from './actors.js';
3
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';
4
- export { ingestIncomingFollow, ingestIncomingUnfollow, listFederatedFollowerRecipients, } from './ingest.js';
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';
7
7
  export { findProfileByHandleAndDomain, findProfileByUri } from './profiles.js';
@@ -6,4 +6,6 @@ export type FollowerRecipient = {
6
6
  inboxUrl: string;
7
7
  sharedInboxUrl: string | null;
8
8
  };
9
+ /** Drop recipients whose host is on the federation blocklist. */
10
+ export declare const withoutBlockedRecipients: (recipients: FollowerRecipient[], blockedHosts: readonly string[]) => FollowerRecipient[];
9
11
  export declare const listFederatedFollowerRecipients: (followedId: string) => Promise<FollowerRecipient[]>;
@@ -1,10 +1,13 @@
1
1
  import { and, eq, isNull, sql } from 'drizzle-orm';
2
+ import { hostIsBlocked } from '@openpeepshq/common/lib';
2
3
  import { pgDb } from '../db/pg/client.js';
3
4
  import { follows } from '../db/pg/schema/edges.js';
4
5
  import { profiles } from '../db/pg/schema/documents.js';
6
+ import { config } from '../config/index.js';
5
7
  import { follow, unfollow } from '../profiles/mutations.js';
6
8
  import { follows as hasFollow } from '../profiles/finders.js';
7
9
  import { recordApActivity } from './activities.js';
10
+ import { hostnameOf } from './peers.js';
8
11
  export const ingestIncomingFollow = async (follower, followed, activityUri) => {
9
12
  if (!(await hasFollow(follower, followed))) {
10
13
  await follow(follower, followed, {
@@ -37,6 +40,11 @@ const followerUri = (profile) => {
37
40
  const uri = profile.uri;
38
41
  return uri ?? `profile:${profile.id}`;
39
42
  };
43
+ /** Drop recipients whose host is on the federation blocklist. */
44
+ export const withoutBlockedRecipients = (recipients, blockedHosts) => recipients.filter((recipient) => {
45
+ const host = hostnameOf(recipient.uri);
46
+ return !host || !hostIsBlocked(host, blockedHosts);
47
+ });
40
48
  export const listFederatedFollowerRecipients = async (followedId) => {
41
49
  const db = pgDb();
42
50
  const rows = await db
@@ -48,7 +56,7 @@ export const listFederatedFollowerRecipients = async (followedId) => {
48
56
  .from(follows)
49
57
  .innerJoin(profiles, sql `${follows.fromId} = ${profiles.id}::text`)
50
58
  .where(and(eq(follows.toId, followedId), eq(profiles.type, 'federated'), isNull(profiles.deletedAt)));
51
- return rows.flatMap((row) => row.uri && row.inboxUrl
59
+ const recipients = rows.flatMap((row) => row.uri && row.inboxUrl
52
60
  ? [
53
61
  {
54
62
  uri: row.uri,
@@ -57,4 +65,6 @@ export const listFederatedFollowerRecipients = async (followedId) => {
57
65
  },
58
66
  ]
59
67
  : []);
68
+ const { blockedHosts } = (await config()).federation;
69
+ return withoutBlockedRecipients(recipients, blockedHosts);
60
70
  };
@@ -1,4 +1,4 @@
1
- import { hostIsAllowed } from '@openpeepshq/common/lib';
1
+ import { hostFederationAllowed } from '@openpeepshq/common/lib';
2
2
  import { config } from '../config/index.js';
3
3
  export const hostnameOf = (value) => {
4
4
  try {
@@ -19,6 +19,6 @@ export const peerHostAllowed = async (value) => {
19
19
  if (!host)
20
20
  return false;
21
21
  const cfg = await config();
22
- return hostIsAllowed(host, cfg.federation.allowedHosts);
22
+ return hostFederationAllowed(host, cfg.federation.allowedHosts, cfg.federation.blockedHosts);
23
23
  };
24
24
  export const federationIsActive = async () => (await config()).federation.active;
@@ -60,6 +60,20 @@ const sendWebPushNotification = (subscription, payload) => config().then(async (
60
60
  },
61
61
  contentEncoding: 'aes128gcm',
62
62
  }));
63
+ /**
64
+ * Carries the webhook target's HTTP status so callers can tell a gone/dead
65
+ * endpoint (404/410) apart from a transient failure (timeout, 5xx, …) —
66
+ * the web path rejects with `{ statusCode }` for the same reason, and only a
67
+ * gone endpoint justifies deleting the subscription.
68
+ */
69
+ class WebhookPushError extends Error {
70
+ statusCode;
71
+ constructor(statusCode) {
72
+ super(`Webhook push failed with status ${statusCode}`);
73
+ this.name = 'WebhookPushError';
74
+ this.statusCode = statusCode;
75
+ }
76
+ }
63
77
  const sendWebhookPushNotification = async (subscription, payload) => {
64
78
  const jwt = await jwtUtil();
65
79
  const token = await jwt.sign({
@@ -80,7 +94,7 @@ const sendWebhookPushNotification = async (subscription, payload) => {
80
94
  }),
81
95
  });
82
96
  if (!response.ok) {
83
- throw new Error(`Webhook push failed with status ${response.status}`);
97
+ throw new WebhookPushError(response.status);
84
98
  }
85
99
  };
86
100
  const sendAppIOSPushNotifications = async (subscriptions, payload, notification, jobLog) => {
@@ -172,6 +186,18 @@ const sendAppFCMPushNotifications = async (subscriptions, payload, notification,
172
186
  }
173
187
  else {
174
188
  await logFailure(jobLog, log, `FCM push to ${describeFcmTarget(account, subscription)} failed`, response.error);
189
+ // registration-token-not-registered is the only reliable dead-token
190
+ // signal: INVALID_ARGUMENT also fires for request-level problems (bad
191
+ // payload keys, size limits), where the token is still live. FCM v1
192
+ // codes are normalized to UPPERCASE client codes, so match the suffix
193
+ // case-insensitively.
194
+ const errorCode = response.error?.code;
195
+ if (typeof errorCode === 'string' &&
196
+ /registration-token-not-registered/i.test(errorCode)) {
197
+ await deletePushSubscription(subscription.id)
198
+ .then(() => logStep(jobLog, log, `Removed dead FCM subscription ${subscription.id} (${errorCode})`))
199
+ .catch((deleteError) => logFailure(jobLog, log, `failed to remove FCM subscription ${subscription.id}`, deleteError));
200
+ }
175
201
  }
176
202
  }
177
203
  await logStep(jobLog, log, `FCM push complete: ${result.successCount} delivered, ${result.failureCount} failed`);
@@ -214,7 +240,17 @@ export const doPush = async (notification, notificationStats, account, jobLog) =
214
240
  await logStep(jobLog, log, `Web push delivered to ${describeSubscription(subscription)} (status ${result?.statusCode ?? 'n/a'})`);
215
241
  })
216
242
  .catch(async (error) => {
217
- await logFailure(jobLog, log, `web push to ${describeSubscription(subscription)} failed; removing dead subscription`, error);
243
+ // web-push rejects with { statusCode } for >= 400 and resolves for
244
+ // 2xx/3xx. Only 404/410 mean the endpoint is gone; deleting on
245
+ // anything else (403 VAPID misconfig, 429 rate limit, transient
246
+ // network errors with no status) would wipe live subscriptions.
247
+ const statusCode = error
248
+ ?.statusCode;
249
+ if (statusCode !== 404 && statusCode !== 410) {
250
+ await logFailure(jobLog, log, `web push to ${describeSubscription(subscription)} failed; keeping subscription`, error);
251
+ return;
252
+ }
253
+ await logFailure(jobLog, log, `web push to ${describeSubscription(subscription)} gone (${statusCode}); removing dead subscription`, error);
218
254
  await deletePushSubscription(subscription.id)
219
255
  .then(() => logStep(jobLog, log, `Removed dead web subscription ${subscription.id}`))
220
256
  .catch((deleteError) => logFailure(jobLog, log, `failed to remove web subscription ${subscription.id}`, deleteError));
@@ -224,7 +260,13 @@ export const doPush = async (notification, notificationStats, account, jobLog) =
224
260
  await logStep(jobLog, log, `Sending webhook push to ${describeSubscription(subscription)}`);
225
261
  await sendWebhookPushNotification(subscription, payloadData)
226
262
  .then(() => logStep(jobLog, log, `Webhook push delivered to ${describeSubscription(subscription)}`))
227
- .catch((error) => logFailure(jobLog, log, `webhook push to ${describeSubscription(subscription)} failed`, error));
263
+ .catch((error) => {
264
+ // Webhook delivery failures never auto-delete the subscription:
265
+ // unlike web (404/410) and FCM (registration-token-not-registered),
266
+ // a webhook has no reliable dead-endpoint signal, so a transient
267
+ // outage must not wipe a live one.
268
+ logFailure(jobLog, log, `webhook push to ${describeSubscription(subscription)} failed`, error);
269
+ });
228
270
  }
229
271
  await sendAppIOSPushNotifications(apnSubscriptions, payloadData, notification, jobLog);
230
272
  await sendAppFCMPushNotifications(fcmSubscriptions, payloadData, notification, account, jobLog);
@@ -250,7 +292,14 @@ export const sendTestPushNotification = async (account, profile, subscriptionKey
250
292
  await sendWebPushNotification(webSubscription, payload)
251
293
  .catch(async (error) => {
252
294
  log.error(error);
253
- await deletePushSubscription(webSubscription.id);
295
+ // web-push rejects with { statusCode } for >= 400. Only 404/410 mean
296
+ // the endpoint is gone; a transient 403/429 or status-less network
297
+ // error must not delete a live subscription (mirrors doPush).
298
+ const statusCode = error
299
+ ?.statusCode;
300
+ if (statusCode === 404 || statusCode === 410) {
301
+ await deletePushSubscription(webSubscription.id).catch((deleteError) => log.error(`failed to remove dead test-push subscription`, deleteError));
302
+ }
254
303
  throw error;
255
304
  })
256
305
  .then((r) => {
@@ -265,7 +314,13 @@ export const sendTestPushNotification = async (account, profile, subscriptionKey
265
314
  if (webhookSubscription) {
266
315
  await sendWebhookPushNotification(webhookSubscription, payload).catch(async (error) => {
267
316
  log.error(error);
268
- await deletePushSubscription(webhookSubscription.id);
317
+ // Only a gone webhook endpoint (404/410) justifies deleting the
318
+ // subscription — a transient 5xx/timeout must not wipe a live one
319
+ // (mirrors the web-path guard above).
320
+ const statusCode = error instanceof WebhookPushError ? error.statusCode : undefined;
321
+ if (statusCode === 404 || statusCode === 410) {
322
+ await deletePushSubscription(webhookSubscription.id).catch((deleteError) => log.error(`failed to remove dead test-push webhook subscription`, deleteError));
323
+ }
269
324
  throw error;
270
325
  });
271
326
  return;
@@ -1,4 +1,4 @@
1
- import { Account } from '@openpeepshq/common/types';
1
+ import { Account, PushSubscription } from '@openpeepshq/common/types';
2
2
  export declare const findPushSubscription: (id: string) => Promise<{
3
3
  type: "web";
4
4
  endpoint: string;
@@ -92,6 +92,8 @@ export declare const findPushSubscription: (id: string) => Promise<{
92
92
  } | undefined;
93
93
  deletedAt?: string | null | undefined;
94
94
  } | undefined>;
95
+ /** Owner of a subscription's account edge, if one is linked. */
96
+ export declare const findAccountForPushSubscription: (subscription: PushSubscription) => Promise<import("@openpeepshq/common").AccountWithMeta | undefined>;
95
97
  export declare const listPushSubscriptionsByAccount: (account: Account) => Promise<({
96
98
  type: "web";
97
99
  endpoint: string;
@@ -1,6 +1,16 @@
1
- import { pushSubscriptionsRelation } from '../accounts/mapping.js';
2
- import { accountsMapping } from '../accounts/mapping.js';
1
+ import { accountsMapping, pushSubscriptionsRelation, } from '../accounts/mapping.js';
3
2
  import { allpeepDb } from '../db/index.js';
4
3
  import { pushSubscriptionsMapping } from './mapping.js';
5
4
  export const findPushSubscription = (id) => allpeepDb().then((db) => pushSubscriptionsMapping.find(db.db, id));
5
+ /** Owner of a subscription's account edge, if one is linked. */
6
+ export const findAccountForPushSubscription = (subscription) => allpeepDb().then(({ db }) => pushSubscriptionsMapping
7
+ .relationsFrom(subscription, {
8
+ alias: 'account',
9
+ edgeCollection: 'accountToPushSubscription',
10
+ direction: 'INBOUND',
11
+ skipEdge: true,
12
+ mapping: accountsMapping.data(),
13
+ cardinality: 'many',
14
+ })
15
+ .first(db));
6
16
  export const listPushSubscriptionsByAccount = (account) => allpeepDb().then(({ db }) => accountsMapping.relationsFrom(account, pushSubscriptionsRelation).all(db));
@@ -97,3 +97,96 @@ export declare const pushSubscriptionAccountConnector: (db: import("../db").PgDb
97
97
  _from: string;
98
98
  _to: string;
99
99
  }>>;
100
+ export declare const pushSubscriptionAccountDisconnector: (db: import("../db").PgDb, from: Account, to: {
101
+ type: "web";
102
+ endpoint: string;
103
+ keys: {
104
+ auth: string;
105
+ p256dh: string;
106
+ };
107
+ id: string;
108
+ createdAt: string;
109
+ updatedAt: string;
110
+ deviceName?: string | undefined;
111
+ alerts?: {
112
+ poll: boolean;
113
+ followRequest: boolean;
114
+ status: boolean;
115
+ favorite: boolean;
116
+ follow: boolean;
117
+ repost: boolean;
118
+ mention: boolean;
119
+ update: boolean;
120
+ admin: {
121
+ signUp: boolean;
122
+ report: boolean;
123
+ };
124
+ } | undefined;
125
+ deletedAt?: string | null | undefined;
126
+ } | {
127
+ type: "apn";
128
+ apnToken: string;
129
+ id: string;
130
+ createdAt: string;
131
+ updatedAt: string;
132
+ deviceName?: string | undefined;
133
+ alerts?: {
134
+ poll: boolean;
135
+ followRequest: boolean;
136
+ status: boolean;
137
+ favorite: boolean;
138
+ follow: boolean;
139
+ repost: boolean;
140
+ mention: boolean;
141
+ update: boolean;
142
+ admin: {
143
+ signUp: boolean;
144
+ report: boolean;
145
+ };
146
+ } | undefined;
147
+ deletedAt?: string | null | undefined;
148
+ } | {
149
+ type: "fcm";
150
+ fcmToken: string;
151
+ id: string;
152
+ createdAt: string;
153
+ updatedAt: string;
154
+ deviceName?: string | undefined;
155
+ alerts?: {
156
+ poll: boolean;
157
+ followRequest: boolean;
158
+ status: boolean;
159
+ favorite: boolean;
160
+ follow: boolean;
161
+ repost: boolean;
162
+ mention: boolean;
163
+ update: boolean;
164
+ admin: {
165
+ signUp: boolean;
166
+ report: boolean;
167
+ };
168
+ } | undefined;
169
+ deletedAt?: string | null | undefined;
170
+ } | {
171
+ type: "webhook";
172
+ url: string;
173
+ publicKey: string;
174
+ id: string;
175
+ createdAt: string;
176
+ updatedAt: string;
177
+ alerts?: {
178
+ poll: boolean;
179
+ followRequest: boolean;
180
+ status: boolean;
181
+ favorite: boolean;
182
+ follow: boolean;
183
+ repost: boolean;
184
+ mention: boolean;
185
+ update: boolean;
186
+ admin: {
187
+ signUp: boolean;
188
+ report: boolean;
189
+ };
190
+ } | undefined;
191
+ deletedAt?: string | null | undefined;
192
+ }) => Promise<void>;
@@ -1,3 +1,4 @@
1
- import { connector } from '../db/helpers.js';
1
+ import { connector, disconnector } from '../db/helpers.js';
2
2
  import { collectionInfos } from '../db/index.js';
3
3
  export const pushSubscriptionAccountConnector = connector(collectionInfos.accountsCollection, collectionInfos.pushSubscriptionsCollection, collectionInfos.accountToPushSubscriptionCollection);
4
+ export const pushSubscriptionAccountDisconnector = disconnector(collectionInfos.accountsCollection, collectionInfos.pushSubscriptionsCollection, collectionInfos.accountToPushSubscriptionCollection);
@@ -1,6 +1,7 @@
1
1
  import { pushSubscriptionsMapping } from './mapping.js';
2
2
  import { allpeepDb } from '../db/index.js';
3
- import { pushSubscriptionAccountConnector } from './helpers.js';
3
+ import { pushSubscriptionAccountConnector, pushSubscriptionAccountDisconnector, } from './helpers.js';
4
+ import { findAccountForPushSubscription } from './finders.js';
4
5
  const uniqueCredential = (data) => {
5
6
  switch (data.type) {
6
7
  case 'web':
@@ -21,6 +22,20 @@ export const createPushSubscription = async (account, data) => {
21
22
  })
22
23
  .first(db);
23
24
  if (existingPushSubscription) {
25
+ // Re-linking to a different account must switch the edge, not add one:
26
+ // account_to_push_subscription allows parallel edges, and a stale second
27
+ // edge makes doPush treat the shared token as a duplicate and delete it.
28
+ const previousAccount = await findAccountForPushSubscription(existingPushSubscription);
29
+ if (previousAccount && previousAccount.id !== account.id) {
30
+ await pushSubscriptionAccountDisconnector(db, previousAccount, existingPushSubscription);
31
+ // The new account may already hold a (stale) edge to this subscription —
32
+ // the parallel-edge state created before the relink guard existed. Drop
33
+ // it first so the connect below is the only edge for the new account,
34
+ // keeping the single-edge invariant airtight (doPush would otherwise
35
+ // collapse the duplicate only later).
36
+ await pushSubscriptionAccountDisconnector(db, account, existingPushSubscription);
37
+ await pushSubscriptionAccountConnector(db, account, existingPushSubscription);
38
+ }
24
39
  return existingPushSubscription;
25
40
  }
26
41
  const pushSubscription = await pushSubscriptionsMapping.create(db, data);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openpeepshq/core",
3
- "version": "0.16.0",
3
+ "version": "0.17.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.17.0",
40
+ "@openpeepshq/common": "0.18.0",
41
41
  "@openpeepshq/fetch-client": "^0.2.1",
42
42
  "@openpeepshq/geocoder": "^0.1.2",
43
- "@openpeepshq/i18n": "^0.19.0"
43
+ "@openpeepshq/i18n": "^0.20.0"
44
44
  },
45
45
  "main": "dist/index.js",
46
46
  "types": "dist/index.d.ts",
@@ -70,7 +70,7 @@
70
70
  "eslint": "^10.14.0",
71
71
  "eslint-config-prettier": "^9.1.0",
72
72
  "google-auth-library": "^10.7.0",
73
- "i18next": "^24.2.3",
73
+ "i18next": "^26.3.4",
74
74
  "prettier": "^3.4.2",
75
75
  "tsc-alias": "^1.8.10",
76
76
  "typescript": "^6.0.2",