@openpeepshq/core 0.12.0 → 0.14.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.
@@ -0,0 +1,151 @@
1
+ import path from 'node:path';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { mkdir, rm, stat, readdir } from 'node:fs/promises';
4
+ import { getSharedConnection } from '../redis/index.js';
5
+ import { config } from '../config/index.js';
6
+ import { logger } from '../log/index.js';
7
+ const log = logger('app:accounts:exportStore');
8
+ /** Download tokens and the assembled archives live for 7 days. */
9
+ export const EXPORT_TTL_MS = 7 * 24 * 60 * 60 * 1000;
10
+ export const EXPORT_TTL_SECONDS = Math.floor(EXPORT_TTL_MS / 1000);
11
+ const byJobKey = (jobId) => `openpeeps:account-export:${jobId}`;
12
+ const byTokenKey = (token) => `openpeeps:account-export:token:${token}`;
13
+ const readRecord = async (key) => {
14
+ const redis = await getSharedConnection();
15
+ const raw = await redis.get(key);
16
+ return raw ? JSON.parse(raw) : undefined;
17
+ };
18
+ const writeRecord = async (key, record, ttlSeconds = EXPORT_TTL_SECONDS) => {
19
+ const redis = await getSharedConnection();
20
+ await redis.set(key, JSON.stringify(record), { EX: ttlSeconds });
21
+ };
22
+ /** Resolve the directory that holds assembled export zips. */
23
+ export const exportDir = async () => {
24
+ const { media: { storage: { params }, }, } = await config();
25
+ return path.join(params.path, 'exports');
26
+ };
27
+ /**
28
+ * Mark an export job as building. Called by the worker at the start of the
29
+ * job so the status endpoint reports "building" from the first moment on.
30
+ */
31
+ export const markExportBuilding = async (jobId, accountId) => {
32
+ await writeRecord(byJobKey(jobId), {
33
+ jobId,
34
+ accountId,
35
+ state: 'building',
36
+ });
37
+ };
38
+ /**
39
+ * Mark an export as ready: mint a one-time download token and record the zip
40
+ * path + expiry under both the job and the token keys.
41
+ */
42
+ export const markExportReady = async (jobId, accountId, zipPath) => {
43
+ const token = randomUUID();
44
+ const expiresAt = new Date(Date.now() + EXPORT_TTL_MS).toISOString();
45
+ const record = {
46
+ jobId,
47
+ accountId,
48
+ state: 'ready',
49
+ token,
50
+ path: zipPath,
51
+ expiresAt,
52
+ };
53
+ await writeRecord(byJobKey(jobId), record);
54
+ await writeRecord(byTokenKey(token), record);
55
+ return { token, expiresAt };
56
+ };
57
+ /** Mark an export as failed (recorded so the status endpoint can report it). */
58
+ export const markExportError = async (jobId, accountId, error) => {
59
+ await writeRecord(byJobKey(jobId), {
60
+ jobId,
61
+ accountId,
62
+ state: 'error',
63
+ error,
64
+ });
65
+ };
66
+ /**
67
+ * Resolve the record for a job, or `null` when no record exists yet (the job
68
+ * has not started — the caller reports "not-found"). A `ready` record whose
69
+ * archive has expired or been cleaned up is reported as `expired` so the
70
+ * client stops polling and can tell the user to start a new export (instead
71
+ * of treating it as still building forever).
72
+ */
73
+ export const getExportByJob = async (jobId) => {
74
+ const record = await readRecord(byJobKey(jobId));
75
+ if (!record)
76
+ return null;
77
+ if (record.state === 'ready') {
78
+ const stillThere = record.path
79
+ ? await stat(record.path).then((s) => s.isFile(), () => false)
80
+ : false;
81
+ const expired = record.expiresAt
82
+ ? Date.parse(record.expiresAt) < Date.now()
83
+ : false;
84
+ // Past the TTL, or the archive was reclaimed by the cleanup sweep: the
85
+ // token no longer works and the user must start a new export.
86
+ if (expired || !stillThere)
87
+ return { ...record, state: 'expired' };
88
+ }
89
+ return record;
90
+ };
91
+ /**
92
+ * Resolve a download record from its one-time token. The token itself is the
93
+ * credential (random, single-use, 7-day TTL) — possession authorizes the
94
+ * download. Returns `null` when the token is unknown, expired, or its file is
95
+ * gone.
96
+ */
97
+ export const resolveDownloadByToken = async (token) => {
98
+ const record = await readRecord(byTokenKey(token));
99
+ if (!record || record.state !== 'ready')
100
+ return null;
101
+ if (record.expiresAt && Date.parse(record.expiresAt) < Date.now()) {
102
+ return null;
103
+ }
104
+ const exists = record.path
105
+ ? await stat(record.path).then((s) => s.isFile(), () => false)
106
+ : false;
107
+ if (!exists)
108
+ return null;
109
+ return record;
110
+ };
111
+ /** Invalidate a token after a successful download (one-time link). */
112
+ export const invalidateToken = async (token) => {
113
+ const redis = await getSharedConnection();
114
+ await redis.del(byTokenKey(token)).catch(() => { });
115
+ };
116
+ /**
117
+ * Delete export artifacts (zips and their staging dirs) that are past the
118
+ * TTL. An artifact whose job record is gone, no longer `ready`, or older
119
+ * than the TTL is reclaimed. Runs on a schedule.
120
+ */
121
+ export const cleanupExpiredExports = async () => {
122
+ const dir = await exportDir();
123
+ let entries = [];
124
+ try {
125
+ entries = await readdir(dir);
126
+ }
127
+ catch {
128
+ return { removed: 0 };
129
+ }
130
+ let removed = 0;
131
+ for (const entry of entries) {
132
+ const full = path.join(dir, entry);
133
+ const statMaybe = await stat(full).catch(() => undefined);
134
+ if (!statMaybe)
135
+ continue;
136
+ const age = Date.now() - statMaybe.mtimeMs;
137
+ if (age < EXPORT_TTL_MS)
138
+ continue;
139
+ await rm(full, { recursive: true, force: true }).catch(() => { });
140
+ removed += 1;
141
+ }
142
+ if (removed > 0)
143
+ log.info(`Export cleanup removed ${removed} item(s)`);
144
+ return { removed };
145
+ };
146
+ /** Ensure the exports directory exists. */
147
+ export const ensureExportDir = async () => {
148
+ const dir = await exportDir();
149
+ await mkdir(dir, { recursive: true });
150
+ return dir;
151
+ };
@@ -3,4 +3,7 @@ export { accountsMapping } from './mapping';
3
3
  export { sendEmailValidationMail } from './helpers';
4
4
  export * from './mutations';
5
5
  export * from './finders';
6
+ export * from './export';
7
+ export * from './exportStore';
8
+ export * from './exportJob';
6
9
  export declare const checkPassword: (account: Account, password: string) => Promise<boolean>;
@@ -3,4 +3,7 @@ export { accountsMapping } from './mapping.js';
3
3
  export { sendEmailValidationMail } from './helpers.js';
4
4
  export * from './mutations.js';
5
5
  export * from './finders.js';
6
+ export * from './export.js';
7
+ export * from './exportStore.js';
8
+ export * from './exportJob.js';
6
9
  export const checkPassword = async (account, password) => compare(password, account.passwordHash);
@@ -9,6 +9,7 @@ export declare const extractZipArchive: (zipPath: string, tempDir: string) => {
9
9
  promise: Promise<void>;
10
10
  kill: () => void;
11
11
  };
12
+ export declare const zipDirectory: (sourceDir: string, zipPath: string) => Promise<void>;
12
13
  export declare const createBackup: () => Promise<string | undefined>;
13
14
  export declare const downloadBackup: (name: string) => Promise<string>;
14
15
  export declare const listAllBackups: () => Promise<string[]>;
@@ -4,7 +4,7 @@ import { spawn } from 'node:child_process';
4
4
  import { emptyDir } from 'fs-extra';
5
5
  import { join, sep, isAbsolute } from 'node:path';
6
6
  import { tmpdir } from 'node:os';
7
- import archiver from 'archiver';
7
+ import { ZipArchive } from 'archiver';
8
8
  import { extractWithNodeStreamZip } from './extractWithNodeStreamZip.js';
9
9
  import { collectionInfos } from '../db/index.js';
10
10
  import { communityConfig, config, defaultConfig } from '../config/index.js';
@@ -94,9 +94,9 @@ const hostnameFromServerHost = (host) => {
94
94
  const serverUrl = host.includes('://') ? host : `http://${host}`;
95
95
  return new URL(serverUrl).hostname;
96
96
  };
97
- const zipDirectory = (sourceDir, zipPath) => new Promise((resolve, reject) => {
97
+ export const zipDirectory = (sourceDir, zipPath) => new Promise((resolve, reject) => {
98
98
  const output = createWriteStream(zipPath);
99
- const archive = archiver('zip', { zlib: { level: 9 } });
99
+ const archive = new ZipArchive({ zlib: { level: 9 } });
100
100
  output.on('close', () => resolve());
101
101
  output.on('error', reject);
102
102
  archive.on('error', reject);
@@ -67,6 +67,103 @@ export declare const communityConfig: () => Promise<{
67
67
  welcomeEmail?: string | undefined;
68
68
  pinnedPost?: string | undefined;
69
69
  autoFollow?: string[] | undefined;
70
+ allowedReactions?: string[] | undefined;
71
+ };
72
+ settings: {
73
+ openRegistrations: boolean;
74
+ defaultLanguage?: string | undefined;
75
+ defaultTimeZone?: string | undefined;
76
+ defaultFeedFormat?: "threaded" | "linear" | undefined;
77
+ indexProfiles?: boolean | undefined;
78
+ additionalForbiddenHandles?: string[] | undefined;
79
+ };
80
+ roles: {
81
+ onRegistration: {
82
+ add: string[];
83
+ remove: string[];
84
+ };
85
+ onEmailValidation: {
86
+ add: string[];
87
+ remove: string[];
88
+ };
89
+ };
90
+ profiles?: {
91
+ additionalFields?: {
92
+ key: string;
93
+ label: string;
94
+ icon?: string | undefined;
95
+ linkPattern?: string | undefined;
96
+ }[] | undefined;
97
+ } | undefined;
98
+ }>;
99
+ /**
100
+ * Reads the community config straight from the DB, bypassing the in-memory
101
+ * cache. Use for low-frequency worker-side reads where a missed pub/sub
102
+ * invalidation is not acceptable; the cached `config()` + `configUpdated`
103
+ * stays the default path.
104
+ *
105
+ * Currently used by the auto-follow designation read, which runs in the
106
+ * worker process, whose cache is only refreshed on a redis pub/sub
107
+ * `configUpdated` event that a worker connection can miss (connect timing,
108
+ * a redelivery gap, or a worker restart); a fresh read keeps the designated
109
+ * accounts on the settings the admin actually saved. Only that read is
110
+ * fresh: the same handler's `capabilitiesConfig` follow-eligibility check
111
+ * intentionally stays on the cached `config` path, so a future reader should
112
+ * not "fix" that read to be fresh without a behavior change.
113
+ */
114
+ export declare const communityConfigFresh: () => Promise<{
115
+ theme: {
116
+ base: string;
117
+ light: {
118
+ primaryHex: string;
119
+ secondaryHex?: string | undefined;
120
+ fontFamily?: string | undefined;
121
+ buttonRadius?: string | undefined;
122
+ radius?: string | undefined;
123
+ logoSmall?: string | undefined;
124
+ defaultProfileAvatar?: string | undefined;
125
+ defaultGroupAvatar?: string | undefined;
126
+ backgroundAuth?: string | undefined;
127
+ background?: string | undefined;
128
+ };
129
+ dark: {
130
+ primaryHex: string;
131
+ secondaryHex?: string | undefined;
132
+ fontFamily?: string | undefined;
133
+ buttonRadius?: string | undefined;
134
+ radius?: string | undefined;
135
+ logoSmall?: string | undefined;
136
+ defaultProfileAvatar?: string | undefined;
137
+ defaultGroupAvatar?: string | undefined;
138
+ backgroundAuth?: string | undefined;
139
+ background?: string | undefined;
140
+ };
141
+ icon?: string | undefined;
142
+ mobileIcon?: string | undefined;
143
+ primaryHex?: string | undefined;
144
+ logoFull?: string | undefined;
145
+ logoSmall?: string | undefined;
146
+ defaultProfileAvatar?: string | undefined;
147
+ defaultGroupAvatar?: string | undefined;
148
+ backgroundAuth?: string | undefined;
149
+ background?: string | undefined;
150
+ };
151
+ info: {
152
+ name: string;
153
+ tagLine: string;
154
+ contactEmail?: string | undefined;
155
+ privacyPolicy?: string | undefined;
156
+ termsAndConditions?: string | undefined;
157
+ bugReportUrl?: string | undefined;
158
+ };
159
+ content: {
160
+ aboutPage?: string | undefined;
161
+ welcomePage?: string | undefined;
162
+ codeOfConduct?: string | undefined;
163
+ welcomeEmail?: string | undefined;
164
+ pinnedPost?: string | undefined;
165
+ autoFollow?: string[] | undefined;
166
+ allowedReactions?: string[] | undefined;
70
167
  };
71
168
  settings: {
72
169
  openRegistrations: boolean;
@@ -72,6 +72,22 @@ export const config = (namespace = 'openpeeps', name = 'core') => {
72
72
  return configPromises.get(key);
73
73
  };
74
74
  export const communityConfig = () => config('openpeeps', 'community');
75
+ /**
76
+ * Reads the community config straight from the DB, bypassing the in-memory
77
+ * cache. Use for low-frequency worker-side reads where a missed pub/sub
78
+ * invalidation is not acceptable; the cached `config()` + `configUpdated`
79
+ * stays the default path.
80
+ *
81
+ * Currently used by the auto-follow designation read, which runs in the
82
+ * worker process, whose cache is only refreshed on a redis pub/sub
83
+ * `configUpdated` event that a worker connection can miss (connect timing,
84
+ * a redelivery gap, or a worker restart); a fresh read keeps the designated
85
+ * accounts on the settings the admin actually saved. Only that read is
86
+ * fresh: the same handler's `capabilitiesConfig` follow-eligibility check
87
+ * intentionally stays on the cached `config` path, so a future reader should
88
+ * not "fix" that read to be fresh without a behavior change.
89
+ */
90
+ export const communityConfigFresh = () => initConfig('openpeeps', 'community');
75
91
  export const capabilitiesConfig = () => config('openpeeps', 'capabilities').then((loaded) => ({
76
92
  ...loaded,
77
93
  accessToken: deepmerge(defaultCapabilitiesConfig.accessToken ?? {}, loaded.accessToken ?? {}),
@@ -1,4 +1,4 @@
1
- import { type AuthorizationData, type MuteParticipantRequest, type PostWithMeta, type Profile } from '@openpeepshq/common/types';
1
+ import type { AuthorizationData, MuteParticipantRequest, PostWithMeta, Profile } from '@openpeepshq/common/types';
2
2
  export { createJamToken, createJamEgressToken } from './token';
3
3
  export { diagnoseLivekit, isLivekitConnected } from './health';
4
4
  export { startRecording, stopRecording, startRtmpStream, stopRtmpStream, stopEgress, listParticipantIds, reclaimOrphanJamRoom, finishRecording, getJamRecordingUrl, getJamObserverPath, JAM_ROOM_EMPTY_TIMEOUT_SEC, JAM_ROOM_DEPARTURE_TIMEOUT_SEC, } from './livekit';
@@ -16,3 +16,16 @@ export declare const closeJam: (profile: Profile, jamEvent: PostWithMeta, recurr
16
16
  export declare const muteParticipant: (jamId: string, data: MuteParticipantRequest, recurrenceId?: string) => Promise<{
17
17
  success: boolean;
18
18
  }>;
19
+ /**
20
+ * Bans a removed profile from rejoining, evicts them now, and records the kick.
21
+ *
22
+ * (a) The ban persist happens before the eviction on purpose: the eviction is
23
+ * best-effort (its failure is swallowed below), but the ban is not — the
24
+ * profile must be locked out even if LiveKit is unreachable.
25
+ * (b) An already-banned target skips only the persist: the waiting-room
26
+ * admittance clear, the eviction attempt, and the `kicked` record still run,
27
+ * so a pending admittee is not left stranded.
28
+ */
29
+ export declare const removeParticipant: (jamEvent: PostWithMeta, profileId: string, recurrenceId?: string) => Promise<void>;
30
+ /** Lifts a ban; the profile simply becomes able to rejoin again. */
31
+ export declare const liftJamBan: (jamEvent: PostWithMeta, profileId: string) => Promise<void>;
@@ -1,10 +1,13 @@
1
- import { jamRoomName, postIdFromJamRoomName, uniquePostsById, } from '@openpeepshq/common/lib';
1
+ import { jamFromEvent, jamRoomName, postIdFromJamRoomName, uniquePostsById, } from '@openpeepshq/common/lib';
2
2
  import { listParticipantIds, reclaimOrphanJamRoom, roomService, shouldReclaimJamRoom, stopRecording, stopRtmpStream, } from './livekit.js';
3
3
  import { jamStateCache, LIVE_JAMS_CACHE_KEY, liveJamPostsCache } from './cache.js';
4
4
  import { localInstanceDomain, parseRoomInstanceDomain } from './helpers.js';
5
5
  import { findPost } from '../posts/index.js';
6
+ import { allpeepDb } from '../db/index.js';
6
7
  import { createJamEvent } from './mutations.js';
8
+ import { postsMapping } from '../posts/mapping.js';
7
9
  import { clearJamAdmittance } from './waitingRoom.js';
10
+ import { hub } from '../events/index.js';
8
11
  import { uuidv7 } from 'uuidv7';
9
12
  import { canReadPost } from '../posts/helpers/index.js';
10
13
  import { capabilitiesConfig } from '../config/index.js';
@@ -27,6 +30,29 @@ const invalidateJamCaches = async (jamId) => {
27
30
  liveJamPostsCache.del(LIVE_JAMS_CACHE_KEY).catch(() => undefined),
28
31
  ]);
29
32
  };
33
+ /**
34
+ * Shared persist-and-notify step for the two jam-config ban mutations
35
+ * ({@link removeParticipant} and {@link liftJamBan}): writes the jam's new
36
+ * `banned` list to the post, invalidates the live-jam caches, and re-broadcasts
37
+ * the fresh post to the moderators. Both paths must keep doing all three —
38
+ * dropping the cache invalidation here would be the drift this exists to
39
+ * prevent.
40
+ */
41
+ const persistJamBannedList = async (jamEvent, jam, banned) => {
42
+ const { db } = await allpeepDb();
43
+ await postsMapping.update(db, jamEvent.id, {
44
+ data: {
45
+ ...jamEvent.data,
46
+ type: 'event',
47
+ jam: { ...jam, banned },
48
+ },
49
+ });
50
+ const freshPost = await findPost(jamEvent.id);
51
+ await invalidateJamCaches(jamEvent.id);
52
+ if (freshPost) {
53
+ await hub.emit('postUpdated', freshPost, jam.moderators);
54
+ }
55
+ };
30
56
  const reclaimLocalOrphan = (post) => {
31
57
  void reclaimOrphanJamRoom(post).then(() => invalidateJamCaches(post.id));
32
58
  };
@@ -131,3 +157,51 @@ export const muteParticipant = async (jamId, data, recurrenceId) => {
131
157
  }
132
158
  return { success: result?.muted };
133
159
  };
160
+ /**
161
+ * Bans a removed profile from rejoining, evicts them now, and records the kick.
162
+ *
163
+ * (a) The ban persist happens before the eviction on purpose: the eviction is
164
+ * best-effort (its failure is swallowed below), but the ban is not — the
165
+ * profile must be locked out even if LiveKit is unreachable.
166
+ * (b) An already-banned target skips only the persist: the waiting-room
167
+ * admittance clear, the eviction attempt, and the `kicked` record still run,
168
+ * so a pending admittee is not left stranded.
169
+ */
170
+ export const removeParticipant = async (jamEvent, profileId, recurrenceId) => {
171
+ const jam = jamFromEvent(jamEvent);
172
+ if (jam && !jam.banned?.includes(profileId)) {
173
+ await persistJamBannedList(jamEvent, jam, [
174
+ ...(jam.banned ?? []),
175
+ profileId,
176
+ ]);
177
+ }
178
+ await clearJamAdmittance(jamEvent, recurrenceId, [profileId]);
179
+ const rs = await roomService();
180
+ if (rs !== undefined) {
181
+ try {
182
+ // LiveKit disconnects the participant with reason PARTICIPANT_REMOVED,
183
+ // which the client uses to show the removed-from-jam state.
184
+ await rs.removeParticipant(jamRoomName(jamEvent.id, recurrenceId), profileId);
185
+ }
186
+ catch (err) {
187
+ // The participant may already have left the room; the ban persists.
188
+ log.debug(err, 'removeParticipant: LiveKit removal failed');
189
+ }
190
+ }
191
+ await createJamEvent({
192
+ id: uuidv7(),
193
+ jamId: jamEvent.id,
194
+ type: 'kicked',
195
+ profileId,
196
+ recurrenceId,
197
+ });
198
+ };
199
+ /** Lifts a ban; the profile simply becomes able to rejoin again. */
200
+ export const liftJamBan = async (jamEvent, profileId) => {
201
+ const jam = jamFromEvent(jamEvent);
202
+ if (!jam?.banned?.includes(profileId)) {
203
+ return;
204
+ }
205
+ const banned = jam.banned.filter((id) => id !== profileId);
206
+ await persistJamBannedList(jamEvent, jam, banned);
207
+ };
@@ -7,37 +7,37 @@ type EdgeMetadata = {
7
7
  export declare const jamEventsMapping: import("../db/pg/map").Mapping<{
8
8
  id: string;
9
9
  jamId: string;
10
- type: "message" | "join" | "close" | "reaction" | "start" | "leave" | "recordStart" | "recordStop" | "streamStart" | "streamStop";
10
+ type: "message" | "join" | "close" | "reaction" | "start" | "leave" | "kicked" | "recordStart" | "recordStop" | "streamStart" | "streamStop";
11
11
  profileId: string;
12
12
  content?: string | undefined;
13
- reaction?: "👍" | "👎" | "❤️" | "😂" | "😮" | "😢" | "🎉" | undefined;
13
+ reaction?: string | undefined;
14
14
  recurrenceId?: string | undefined;
15
15
  }, JamEvent, JamEvent>;
16
16
  export declare const jamSessionStartsMapping: import("../db/pg/map").Mapping<{
17
17
  id: string;
18
18
  jamId: string;
19
- type: "message" | "join" | "close" | "reaction" | "start" | "leave" | "recordStart" | "recordStop" | "streamStart" | "streamStop";
19
+ type: "message" | "join" | "close" | "reaction" | "start" | "leave" | "kicked" | "recordStart" | "recordStop" | "streamStart" | "streamStop";
20
20
  profileId: string;
21
21
  content?: string | undefined;
22
- reaction?: "👍" | "👎" | "❤️" | "😂" | "😮" | "😢" | "🎉" | undefined;
22
+ reaction?: string | undefined;
23
23
  recurrenceId?: string | undefined;
24
24
  }, JamEvent, JamEvent>;
25
25
  export declare const jamSessionClosesMapping: import("../db/pg/map").Mapping<{
26
26
  id: string;
27
27
  jamId: string;
28
- type: "message" | "join" | "close" | "reaction" | "start" | "leave" | "recordStart" | "recordStop" | "streamStart" | "streamStop";
28
+ type: "message" | "join" | "close" | "reaction" | "start" | "leave" | "kicked" | "recordStart" | "recordStop" | "streamStart" | "streamStop";
29
29
  profileId: string;
30
30
  content?: string | undefined;
31
- reaction?: "👍" | "👎" | "❤️" | "😂" | "😮" | "😢" | "🎉" | undefined;
31
+ reaction?: string | undefined;
32
32
  recurrenceId?: string | undefined;
33
33
  }, JamEvent, JamEvent>;
34
34
  export declare const jamParticipantsMapping: import("../db/pg/map").Mapping<{
35
35
  id: string;
36
36
  jamId: string;
37
- type: "message" | "join" | "close" | "reaction" | "start" | "leave" | "recordStart" | "recordStop" | "streamStart" | "streamStop";
37
+ type: "message" | "join" | "close" | "reaction" | "start" | "leave" | "kicked" | "recordStart" | "recordStop" | "streamStart" | "streamStop";
38
38
  profileId: string;
39
39
  content?: string | undefined;
40
- reaction?: "👍" | "👎" | "❤️" | "😂" | "😮" | "😢" | "🎉" | undefined;
40
+ reaction?: string | undefined;
41
41
  recurrenceId?: string | undefined;
42
42
  }, JamEvent, JamEvent>;
43
43
  export declare const jamRecordingRelation: RelationWithMapping<PostWithMeta, JamRecording>;
@@ -71,6 +71,9 @@ export const createJamToken = async (event, profile, { external = false, recurre
71
71
  if (joiner && isBlockedPair(joiner, event.profile?.id)) {
72
72
  throw notFound({ errorKey: 'error.jamNotFound', parameters: { jamId } });
73
73
  }
74
+ if (jam?.banned?.includes(profile.id)) {
75
+ throw forbidden({ errorKey: 'error.jamBanned' });
76
+ }
74
77
  assertJamRsvpAllowed(event, profile, recurrenceId);
75
78
  const rs = await roomService();
76
79
  if (rs === undefined) {
@@ -1,6 +1,6 @@
1
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
- export declare const clearJamAdmittance: (event: PostWithMeta, recurrenceId?: string) => Promise<void>;
3
+ export declare const clearJamAdmittance: (event: PostWithMeta, recurrenceId?: string, onlyProfileIds?: string[]) => Promise<void>;
4
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>;
@@ -1,5 +1,6 @@
1
1
  import { jamRoomName } from '@openpeepshq/common/lib';
2
2
  import { jamWaitingRoomEntrySchema, } from '@openpeepshq/common/types';
3
+ import { forbidden } from '../errors/index.js';
3
4
  import { assertJamRsvpAllowed, createJamToken } from './token.js';
4
5
  import { disconnect, getConnection, getSharedConnection, } from '../redis/connection.js';
5
6
  import { getProfile } from '../profiles/index.js';
@@ -18,7 +19,17 @@ export const isAdmittedToJam = async (event, profileId, recurrenceId) => {
18
19
  const conn = await getSharedConnection();
19
20
  return Boolean(await conn.hExists(admittanceKey(event, recurrenceId), profileId));
20
21
  };
21
- export const clearJamAdmittance = async (event, recurrenceId) => {
22
+ export const clearJamAdmittance = async (event, recurrenceId, onlyProfileIds) => {
23
+ if (onlyProfileIds !== undefined) {
24
+ // Per-profile path: an explicit (possibly empty) id set must never fall
25
+ // through to the wipe-everything del() below, so `[]` is a no-op.
26
+ if (onlyProfileIds.length === 0)
27
+ return;
28
+ await getSharedConnection().then((conn) =>
29
+ // ioredis flattens an array field at the protocol level.
30
+ conn.hDel(admittanceKey(event, recurrenceId), onlyProfileIds));
31
+ return;
32
+ }
22
33
  await getSharedConnection().then((conn) => conn.del(admittanceKey(event, recurrenceId)));
23
34
  };
24
35
  export const currentWaitingRoomWatch = (jamEvent, onChange, recurrenceId) => currentWaitingRoom(jamEvent, recurrenceId)
@@ -53,6 +64,13 @@ export const admittanceWatch = (jamEvent, profileId, onToken, recurrenceId) => c
53
64
  await disconnect(conn);
54
65
  }));
55
66
  export const joinWaitingRoom = async (event, profile, recurrenceId) => {
67
+ // A removed (banned) profile must not be able to queue at all — mirroring
68
+ // the `createJamToken` gate, so the refusal happens up front instead of at
69
+ // the moderator's later "admit" click.
70
+ const jam = event.data?.type === 'event' ? event.data?.jam : undefined;
71
+ if (jam?.banned?.includes(profile.id)) {
72
+ throw forbidden({ errorKey: 'error.jamBanned' });
73
+ }
56
74
  assertJamRsvpAllowed(event, profile, recurrenceId);
57
75
  const conn = await getSharedConnection();
58
76
  const wrKey = waitingRoomKey(event, recurrenceId);
@@ -1,7 +1,7 @@
1
1
  import { createReadStream, createWriteStream } from 'node:fs';
2
2
  import { readdir, rm, stat } from 'node:fs/promises';
3
3
  import { basename, join } from 'node:path';
4
- import archiver from 'archiver';
4
+ import { ZipArchive } from 'archiver';
5
5
  const DAY_MS = 24 * 60 * 60 * 1000;
6
6
  /** Daily log file as written by the logger, e.g. `20261001.log`. */
7
7
  const RAW_LOG_FILE = /^\d{8}\.log$/;
@@ -18,7 +18,7 @@ const fileExists = async (path) => {
18
18
  };
19
19
  const zipLogFile = (file, zipPath) => new Promise((resolve, reject) => {
20
20
  const output = createWriteStream(zipPath);
21
- const archive = archiver('zip', { zlib: { level: 9 } });
21
+ const archive = new ZipArchive({ zlib: { level: 9 } });
22
22
  output.on('close', () => resolve());
23
23
  output.on('error', reject);
24
24
  archive.on('error', reject);
@@ -6,7 +6,8 @@ import { logFailure, logStep } from '../jobs/index.js';
6
6
  import { deletePushSubscription, listPushSubscriptionsByAccount, } from '../pushSubscriptions/index.js';
7
7
  import { getNotificationStats } from './finders.js';
8
8
  import { ApnsClient, Notification as IOSPushNotification } from 'apns2';
9
- import firebase from 'firebase-admin';
9
+ import { getApps } from 'firebase-admin/app';
10
+ import { getMessaging } from 'firebase-admin/messaging';
10
11
  import { jwtUtil } from '../jwt/index.js';
11
12
  import { uuidv7 } from 'uuidv7';
12
13
  const log = logger('core:notifications:push');
@@ -27,6 +28,11 @@ const describeSubscription = (subscription) => {
27
28
  return `web sub=${subscription.id} endpoint=${host}`;
28
29
  }
29
30
  case 'webhook':
31
+ // Intentionally prints the full URL: the webhook endpoint is the
32
+ // subscriber's own configured destination (their choice to expose), and
33
+ // shortening it would make delivery-failure logs impossible to
34
+ // correlate. The apn/fcm tokens below stay shortened because they are
35
+ // device credentials, not user-configured endpoints.
30
36
  return `webhook sub=${subscription.id} url=${subscription.url}`;
31
37
  case 'apn':
32
38
  return `apn sub=${subscription.id} token=${shorten(subscription.apnToken)}`;
@@ -118,7 +124,7 @@ const sendAppFCMPushNotifications = async (subscriptions, payload, notification,
118
124
  return;
119
125
  const serializedPayload = JSON.stringify(payload);
120
126
  const tokens = subscriptions.map((sub) => sub.fcmToken);
121
- if (firebase.apps.length === 0) {
127
+ if (getApps().length === 0) {
122
128
  for (const subscription of subscriptions) {
123
129
  await logFailure(jobLog, log, `FCM not initialized; skipping push to ${describeFcmTarget(account, subscription)}`);
124
130
  }
@@ -129,7 +135,7 @@ const sendAppFCMPushNotifications = async (subscriptions, payload, notification,
129
135
  }
130
136
  let result;
131
137
  try {
132
- result = await firebase.messaging().sendEachForMulticast({
138
+ result = await getMessaging().sendEachForMulticast({
133
139
  tokens,
134
140
  data: { payload: serializedPayload },
135
141
  apns: {
@@ -151,6 +157,11 @@ const sendAppFCMPushNotifications = async (subscriptions, payload, notification,
151
157
  }
152
158
  return;
153
159
  }
160
+ // v14 surfaces per-token failures as `response.error` objects (firebase#3140).
161
+ // No extra v14-specific error mapping is intentionally added here:
162
+ // `formatErrorDetail` (jobLog) already extracts `code`/`statusCode`/`reason`
163
+ // from whatever error shape arrives, so v14's error codes reach the job log
164
+ // pre-formatted.
154
165
  for (let i = 0; i < result.responses.length; i++) {
155
166
  const response = result.responses[i];
156
167
  const subscription = subscriptions[i];
@@ -145,6 +145,7 @@ export declare const baseEventsFeed: (profile?: ProfileWithMeta) => Mapping<{
145
145
  speakers?: string[] | undefined;
146
146
  presenters?: string[] | undefined;
147
147
  audience?: string[] | undefined;
148
+ banned?: string[] | undefined;
148
149
  maxSpeakers?: number | undefined;
149
150
  maxPresenters?: number | undefined;
150
151
  maxAudience?: number | undefined;