@openpeepshq/core 0.15.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;
@@ -1,7 +1,20 @@
1
1
  import { type JamWaitingRoomEntry, type PublicProfile, type PostWithMeta } from '@openpeepshq/common/types';
2
+ /** Denials only need to outlive the current join attempt's stream. */
3
+ export declare const DENIAL_TTL_SEC: number;
2
4
  export declare const isAdmittedToJam: (event: PostWithMeta, profileId: string, recurrenceId?: string) => Promise<boolean>;
3
5
  export declare const clearJamAdmittance: (event: PostWithMeta, recurrenceId?: string, onlyProfileIds?: string[]) => Promise<void>;
4
6
  export declare const currentWaitingRoomWatch: (jamEvent: PostWithMeta, onChange: (waitingRoom: Record<string, JamWaitingRoomEntry>) => void | Promise<void>, recurrenceId?: string) => Promise<() => Promise<void>>;
5
- export declare const admittanceWatch: (jamEvent: PostWithMeta, profileId: string, onToken: (token: string) => Promise<void> | void, recurrenceId?: string) => Promise<() => Promise<void>>;
7
+ /**
8
+ * The keyspace event is the fast path for waking a queued guest, but a
9
+ * missed event (a reject that lands around the subscription window, or a
10
+ * Redis without `notify-keyspace-events`) must not strand the guest in the
11
+ * waiting room forever. As a fallback, re-check the decision keys on an
12
+ * interval for a bounded window after subscribing.
13
+ */
14
+ export declare const ADMITTANCE_FALLBACK_POLL_MS = 500;
15
+ export declare const ADMITTANCE_FALLBACK_POLLS = 40;
16
+ export declare const admittanceWatch: (jamEvent: PostWithMeta, profileId: string, onToken: (token: string) => Promise<void> | void, recurrenceId?: string, onDenied?: () => Promise<void> | void) => Promise<() => Promise<void>>;
6
17
  export declare const joinWaitingRoom: (event: PostWithMeta, profile: PublicProfile, recurrenceId?: string) => Promise<void>;
7
18
  export declare const acceptFromWaitingRoom: (event: PostWithMeta, profileId: string, recurrenceId?: string) => Promise<undefined>;
19
+ /** Remove a waiting profile and wake their join stream so they stop waiting. */
20
+ export declare const rejectFromWaitingRoom: (event: PostWithMeta, profileId: string, recurrenceId?: string) => Promise<void>;
@@ -6,15 +6,17 @@ import { disconnect, getConnection, getSharedConnection, } from '../redis/connec
6
6
  import { getProfile } from '../profiles/index.js';
7
7
  const waitingRoomKey = (event, recurrenceId) => `jams:waiting-room:${jamRoomName(event.id, recurrenceId)}`;
8
8
  const admittanceKey = (event, recurrenceId) => `jams:admitted:${jamRoomName(event.id, recurrenceId)}`;
9
+ const denialKey = (event, recurrenceId) => `jams:denied:${jamRoomName(event.id, recurrenceId)}`;
9
10
  /** Keep admissions around for the length of a long jam / mobile backgrounding. */
10
11
  const ADMITTANCE_TTL_SEC = 12 * 60 * 60;
12
+ /** Denials only need to outlive the current join attempt's stream. */
13
+ export const DENIAL_TTL_SEC = 10 * 60;
11
14
  const currentWaitingRoom = (event, recurrenceId) => getSharedConnection()
12
15
  .then((conn) => conn.hGetAll(waitingRoomKey(event, recurrenceId)))
13
16
  .then((wrRaw) => Object.entries(wrRaw))
14
17
  .then((entries) => entries.filter((e) => e[0] && e[1]))
15
18
  .then((entries) => entries.map(([key, value]) => [key, jamWaitingRoomEntrySchema.parse(JSON.parse(value))]))
16
19
  .then((entries) => Object.fromEntries(entries));
17
- const currentAdmittance = (event, recurrenceId) => getSharedConnection().then((conn) => conn.hGetAll(admittanceKey(event, recurrenceId)));
18
20
  export const isAdmittedToJam = async (event, profileId, recurrenceId) => {
19
21
  const conn = await getSharedConnection();
20
22
  return Boolean(await conn.hExists(admittanceKey(event, recurrenceId), profileId));
@@ -30,7 +32,9 @@ export const clearJamAdmittance = async (event, recurrenceId, onlyProfileIds) =>
30
32
  conn.hDel(admittanceKey(event, recurrenceId), onlyProfileIds));
31
33
  return;
32
34
  }
33
- await getSharedConnection().then((conn) => conn.del(admittanceKey(event, recurrenceId)));
35
+ const conn = await getSharedConnection();
36
+ await conn.del(admittanceKey(event, recurrenceId));
37
+ await conn.del(denialKey(event, recurrenceId));
34
38
  };
35
39
  export const currentWaitingRoomWatch = (jamEvent, onChange, recurrenceId) => currentWaitingRoom(jamEvent, recurrenceId)
36
40
  .then(onChange)
@@ -42,27 +46,100 @@ export const currentWaitingRoomWatch = (jamEvent, onChange, recurrenceId) => cur
42
46
  }
43
47
  })
44
48
  .then(() => () => disconnect(conn)));
45
- export const admittanceWatch = (jamEvent, profileId, onToken, recurrenceId) => currentAdmittance(jamEvent, recurrenceId)
46
- .then((admittance) => {
47
- if (admittance[profileId]) {
48
- return onToken(admittance[profileId]);
49
- }
50
- })
51
- .then(() => getConnection())
52
- .then((conn) => conn
53
- .subscribe(`__keyspace@0__:${admittanceKey(jamEvent, recurrenceId)}`, async (event) => {
54
- if ('hset' === event) {
55
- const token = await getSharedConnection().then((c) => c.hGet(admittanceKey(jamEvent, recurrenceId), profileId));
49
+ /**
50
+ * The keyspace event is the fast path for waking a queued guest, but a
51
+ * missed event (a reject that lands around the subscription window, or a
52
+ * Redis without `notify-keyspace-events`) must not strand the guest in the
53
+ * waiting room forever. As a fallback, re-check the decision keys on an
54
+ * interval for a bounded window after subscribing.
55
+ */
56
+ export const ADMITTANCE_FALLBACK_POLL_MS = 500;
57
+ export const ADMITTANCE_FALLBACK_POLLS = 40;
58
+ export const admittanceWatch = (jamEvent, profileId, onToken, recurrenceId, onDenied) => {
59
+ let settled = false;
60
+ let pollTimer;
61
+ const aKey = admittanceKey(jamEvent, recurrenceId);
62
+ const dKey = denialKey(jamEvent, recurrenceId);
63
+ const notifyIfDecided = async () => {
64
+ if (settled)
65
+ return true;
66
+ const shared = await getSharedConnection();
67
+ const token = await shared.hGet(aKey, profileId);
56
68
  if (token) {
57
- await disconnect(conn);
58
- return onToken(token);
69
+ // A second wake-up (keyspace event racing an in-flight fallback poll)
70
+ // can pass the guard above while these reads are awaited; re-checking
71
+ // claims the decision synchronously, so only the first caller
72
+ // delivers it.
73
+ if (settled)
74
+ return true;
75
+ settled = true;
76
+ await onToken(token);
77
+ return true;
59
78
  }
60
- }
61
- })
62
- .then(() => async () => {
63
- await getSharedConnection().then((c) => c.hDel(waitingRoomKey(jamEvent, recurrenceId), profileId));
64
- await disconnect(conn);
65
- }));
79
+ const denied = await shared.hGet(dKey, profileId);
80
+ if (denied) {
81
+ if (settled)
82
+ return true;
83
+ settled = true;
84
+ await onDenied?.();
85
+ return true;
86
+ }
87
+ return false;
88
+ };
89
+ return notifyIfDecided().then(() => getConnection().then(async (conn) => {
90
+ let connClosed = false;
91
+ const settle = async () => {
92
+ if (pollTimer) {
93
+ clearInterval(pollTimer);
94
+ pollTimer = undefined;
95
+ }
96
+ if (!connClosed) {
97
+ connClosed = true;
98
+ await disconnect(conn);
99
+ }
100
+ };
101
+ if (!settled) {
102
+ const onKeyEvent = async (event) => {
103
+ if (event !== 'hset')
104
+ return;
105
+ if (await notifyIfDecided()) {
106
+ await settle();
107
+ }
108
+ };
109
+ await conn.subscribe(`__keyspace@0__:${aKey}`, onKeyEvent);
110
+ await conn.subscribe(`__keyspace@0__:${dKey}`, onKeyEvent);
111
+ let polls = 0;
112
+ pollTimer = setInterval(() => {
113
+ void (async () => {
114
+ if (await notifyIfDecided()) {
115
+ await settle();
116
+ }
117
+ else if (++polls >= ADMITTANCE_FALLBACK_POLLS) {
118
+ // The window closed without a decision; the watch stays open
119
+ // and the keyspace events remain the wake-up path from here.
120
+ if (pollTimer) {
121
+ clearInterval(pollTimer);
122
+ pollTimer = undefined;
123
+ }
124
+ }
125
+ })();
126
+ }, ADMITTANCE_FALLBACK_POLL_MS);
127
+ if (await notifyIfDecided()) {
128
+ await settle();
129
+ }
130
+ }
131
+ return async () => {
132
+ if (pollTimer) {
133
+ clearInterval(pollTimer);
134
+ pollTimer = undefined;
135
+ }
136
+ await getSharedConnection().then((c) => c.hDel(waitingRoomKey(jamEvent, recurrenceId), profileId));
137
+ if (conn.isOpen) {
138
+ await disconnect(conn);
139
+ }
140
+ };
141
+ }));
142
+ };
66
143
  export const joinWaitingRoom = async (event, profile, recurrenceId) => {
67
144
  // A removed (banned) profile must not be able to queue at all — mirroring
68
145
  // the `createJamToken` gate, so the refusal happens up front instead of at
@@ -82,6 +159,8 @@ export const joinWaitingRoom = async (event, profile, recurrenceId) => {
82
159
  };
83
160
  // Do not clear admittance here — once admitted, the guest may reconnect
84
161
  // (mobile idle / tab freeze) without a second moderator approval.
162
+ // A new request does clear a previous rejection.
163
+ await conn.hDel(denialKey(event, recurrenceId), profile.id);
85
164
  await conn.hSet(wrKey, { [profile.id]: JSON.stringify(entry) });
86
165
  };
87
166
  export const acceptFromWaitingRoom = async (event, profileId, recurrenceId) => {
@@ -111,3 +190,13 @@ export const acceptFromWaitingRoom = async (event, profileId, recurrenceId) => {
111
190
  });
112
191
  await conn.expire(aKey, ADMITTANCE_TTL_SEC);
113
192
  };
193
+ /** Remove a waiting profile and wake their join stream so they stop waiting. */
194
+ export const rejectFromWaitingRoom = async (event, profileId, recurrenceId) => {
195
+ const conn = await getSharedConnection();
196
+ const dKey = denialKey(event, recurrenceId);
197
+ await conn.hDel(waitingRoomKey(event, recurrenceId), profileId);
198
+ await conn.hSet(dKey, { [profileId]: '1' });
199
+ // Only needs to outlive the current join attempt — the guest's join stream
200
+ // polls this key; a stale denial must not survive future join requests.
201
+ await conn.expire(dKey, DENIAL_TTL_SEC);
202
+ };
@@ -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.15.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.16.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.17.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",