@openpeepshq/core 0.2.0 → 0.2.1

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.
Files changed (58) hide show
  1. package/LICENSE +674 -0
  2. package/dist/accounts/mutations.js +9 -0
  3. package/dist/config/index.d.ts +3 -336
  4. package/dist/db/explorer/index.d.ts +1 -1
  5. package/dist/db/explorer/index.js +1 -1
  6. package/dist/db/pg/map/registry.js +3 -2
  7. package/dist/jams/export.d.ts +2 -0
  8. package/dist/jams/export.js +5 -0
  9. package/dist/jams/finders.d.ts +1 -0
  10. package/dist/jams/finders.js +1 -0
  11. package/dist/jams/health.d.ts +23 -0
  12. package/dist/jams/health.js +79 -7
  13. package/dist/jams/index.d.ts +1 -1
  14. package/dist/jams/index.js +10 -3
  15. package/dist/jams/token.js +6 -2
  16. package/dist/jams/waitingRoom.js +3 -1
  17. package/dist/media/garbageCollection.d.ts +109 -0
  18. package/dist/media/garbageCollection.js +603 -0
  19. package/dist/media/garbageCollectionJobs.d.ts +14 -0
  20. package/dist/media/garbageCollectionJobs.js +55 -0
  21. package/dist/media/index.d.ts +2 -0
  22. package/dist/media/index.js +4 -2
  23. package/dist/media/streaming.d.ts +2 -0
  24. package/dist/media/streaming.js +8 -0
  25. package/dist/notifications/defaultNotifications/index.js +2 -0
  26. package/dist/notifications/defaultNotifications/jamStarted/index.d.ts +1 -0
  27. package/dist/notifications/defaultNotifications/jamStarted/index.js +61 -13
  28. package/dist/notifications/defaultNotifications/waitlistOffer/index.d.ts +24 -0
  29. package/dist/notifications/defaultNotifications/waitlistOffer/index.js +40 -0
  30. package/dist/notifications/index.d.ts +1 -1
  31. package/dist/notifications/index.js +1 -1
  32. package/dist/plugins/pluginAuth.js +1 -0
  33. package/dist/posts/conversationQueries.d.ts +31 -0
  34. package/dist/posts/conversationQueries.js +150 -24
  35. package/dist/posts/finders.d.ts +9 -0
  36. package/dist/posts/finders.js +23 -3
  37. package/dist/posts/helpers/index.d.ts +10 -2
  38. package/dist/posts/helpers/index.js +6 -0
  39. package/dist/posts/index.d.ts +3 -1
  40. package/dist/posts/index.js +3 -1
  41. package/dist/posts/mapping.d.ts +14 -0
  42. package/dist/posts/mutations.d.ts +12 -6
  43. package/dist/posts/mutations.js +220 -68
  44. package/dist/posts/rsvpExport.d.ts +47 -0
  45. package/dist/posts/rsvpExport.js +178 -0
  46. package/dist/posts/unseenCounts.d.ts +6 -0
  47. package/dist/posts/unseenCounts.js +51 -1
  48. package/dist/posts/waitlist.d.ts +13 -0
  49. package/dist/posts/waitlist.js +75 -0
  50. package/dist/posts/waitlistOfferJobs.d.ts +10 -0
  51. package/dist/posts/waitlistOfferJobs.js +91 -0
  52. package/dist/profiles/index.js +6 -1
  53. package/dist/reports/mapping.d.ts +1 -1
  54. package/dist/server/index.d.ts +1 -0
  55. package/dist/stats/mapping.d.ts +1 -0
  56. package/dist/stripe/connection.js +1 -1
  57. package/dist/stripe/helpers.js +7 -3
  58. package/package.json +10 -9
@@ -140,6 +140,15 @@ export const updateAccount = async (accountData) => {
140
140
  }
141
141
  const previousEmail = accountData.account.email;
142
142
  const updatedEmail = normalizeEmailAddress(accountData.email);
143
+ if (updatedEmail && updatedEmail !== previousEmail) {
144
+ const existing = await findAccountByEmail(updatedEmail);
145
+ if (existing && existing.id !== accountData.account.id) {
146
+ throw conflict({
147
+ errorKey: 'emailAlreadyTaken',
148
+ parameters: { email: updatedEmail },
149
+ });
150
+ }
151
+ }
143
152
  const account = await accountsMapping.update(db, accountData.account.id, {
144
153
  email: updatedEmail,
145
154
  passwordHash: accountData.password
@@ -14,174 +14,7 @@ export declare const refreshConfig: (namespace?: string, name?: string) => void;
14
14
  * admin UI forms and pin/unpin all send partial trees.
15
15
  */
16
16
  export declare const updateConfigValues: (configValues: unknown, namespace?: string, name?: string) => Promise<void>;
17
- export declare const config: <T = {
18
- version: string;
19
- environment: string;
20
- server: {
21
- host: string;
22
- signUpsOpen: boolean;
23
- publicContent: boolean;
24
- maxProfiles?: number | undefined;
25
- };
26
- db: {
27
- databaseUrl: string;
28
- url?: string | undefined;
29
- databaseName?: string | undefined;
30
- };
31
- redis: {
32
- host: string;
33
- };
34
- email: {
35
- service: string;
36
- defaultTemplatePath: string;
37
- transportConfig: {
38
- host: string;
39
- port: number;
40
- secure: boolean;
41
- auth?: {
42
- user?: string | undefined;
43
- pass?: string | undefined;
44
- } | undefined;
45
- };
46
- defaultFrom?: string | undefined;
47
- };
48
- logs: {
49
- local: {
50
- path: string;
51
- };
52
- retention: {
53
- zipAfterDays: number;
54
- deleteAfterDays: number;
55
- };
56
- };
57
- media: {
58
- maxUploadMb: number;
59
- storage: {
60
- driver: "openpeeps";
61
- params: {
62
- path: string;
63
- prefix: string;
64
- host?: string | undefined;
65
- };
66
- };
67
- };
68
- network: {
69
- port: number;
70
- };
71
- plugins: {
72
- path: string;
73
- rootPackageJsonPath: string;
74
- };
75
- secrets: {
76
- jwt: string;
77
- };
78
- jams: {
79
- livekit: {
80
- url: string;
81
- apiKey?: string | undefined;
82
- apiSecret?: string | undefined;
83
- recordingEnabled?: boolean | undefined;
84
- };
85
- };
86
- vapid: {
87
- privateKey?: string | undefined;
88
- publicKey?: string | undefined;
89
- };
90
- federation: {
91
- active: boolean;
92
- allowedHosts: string[];
93
- };
94
- activityPub: {
95
- defaultDomain: string;
96
- itemsPerPage: number;
97
- threadDepth: number;
98
- federation: {
99
- requestTimeout: number;
100
- };
101
- };
102
- sso: {
103
- generic: {
104
- id: string;
105
- name: string;
106
- userProfileRequest: {
107
- url: string;
108
- authHeader?: string | undefined;
109
- };
110
- userProfilePaths: {
111
- email: string;
112
- handle?: string | undefined;
113
- avatar?: string | undefined;
114
- displayName?: string | undefined;
115
- };
116
- loginLink?: string | undefined;
117
- createAccounts?: boolean | undefined;
118
- createProfiles?: boolean | undefined;
119
- }[];
120
- oidc: {
121
- id: string;
122
- name: string;
123
- authorizationUrl: string;
124
- tokenUrl: string;
125
- userinfoUrl: string;
126
- clientId: string;
127
- kind?: "oidc" | "github" | "gitlab" | "gitlab-selfhosted" | "google" | "entra" | "auth0" | "keycloak" | "authentik" | "okta" | "discord" | "pocketid" | undefined;
128
- instanceUrl?: string | undefined;
129
- tenant?: string | undefined;
130
- emailsUrl?: string | undefined;
131
- jwksUri?: string | undefined;
132
- clientSecret?: string | undefined;
133
- scope?: string | undefined;
134
- claimMapping?: {
135
- email?: string | undefined;
136
- handle?: string | undefined;
137
- displayName?: string | undefined;
138
- avatar?: string | undefined;
139
- } | undefined;
140
- approvalRequired?: boolean | undefined;
141
- }[];
142
- onlySSO?: boolean | undefined;
143
- };
144
- services: {
145
- sentry: {
146
- enabled: boolean;
147
- dsn?: string | undefined;
148
- replayEnabled?: boolean | undefined;
149
- };
150
- location: {
151
- type: string;
152
- url: string;
153
- apiKey?: string | undefined;
154
- };
155
- };
156
- apps: {
157
- ios: {
158
- url?: string | undefined;
159
- bundleIdentifier?: string | undefined;
160
- teamId?: string | undefined;
161
- appId?: string | undefined;
162
- apnKeyId?: string | undefined;
163
- apnSigningKey?: string | undefined;
164
- };
165
- android: {
166
- url?: string | undefined;
167
- packageName?: string | undefined;
168
- appId?: string | undefined;
169
- fcmCredentials?: string | undefined;
170
- };
171
- };
172
- payments: {
173
- stripe: {
174
- paidMembership?: {
175
- enabled: boolean;
176
- productId?: string | undefined;
177
- trialPeriodDays?: number | undefined;
178
- } | undefined;
179
- publishableKey?: string | undefined;
180
- secretKey?: string | undefined;
181
- webhookSecret?: string | undefined;
182
- };
183
- };
184
- }>(namespace?: string, name?: string) => Promise<T>;
17
+ export declare const config: <T = CoreConfig>(namespace?: string, name?: string) => Promise<T>;
185
18
  export declare const communityConfig: () => Promise<{
186
19
  theme: {
187
20
  base: string;
@@ -239,6 +72,7 @@ export declare const communityConfig: () => Promise<{
239
72
  defaultTimeZone?: string | undefined;
240
73
  defaultFeedFormat?: "threaded" | "linear" | undefined;
241
74
  indexProfiles?: boolean | undefined;
75
+ additionalForbiddenHandles?: string[] | undefined;
242
76
  };
243
77
  roles: {
244
78
  onRegistration: {
@@ -260,174 +94,7 @@ export declare const communityConfig: () => Promise<{
260
94
  } | undefined;
261
95
  }>;
262
96
  export declare const capabilitiesConfig: () => Promise<CapabilitiesConfig>;
263
- export declare const sanitizedConfigWithDefaults: <T = {
264
- version: string;
265
- environment: string;
266
- server: {
267
- host: string;
268
- signUpsOpen: boolean;
269
- publicContent: boolean;
270
- maxProfiles?: number | undefined;
271
- };
272
- db: {
273
- databaseUrl: string;
274
- url?: string | undefined;
275
- databaseName?: string | undefined;
276
- };
277
- redis: {
278
- host: string;
279
- };
280
- email: {
281
- service: string;
282
- defaultTemplatePath: string;
283
- transportConfig: {
284
- host: string;
285
- port: number;
286
- secure: boolean;
287
- auth?: {
288
- user?: string | undefined;
289
- pass?: string | undefined;
290
- } | undefined;
291
- };
292
- defaultFrom?: string | undefined;
293
- };
294
- logs: {
295
- local: {
296
- path: string;
297
- };
298
- retention: {
299
- zipAfterDays: number;
300
- deleteAfterDays: number;
301
- };
302
- };
303
- media: {
304
- maxUploadMb: number;
305
- storage: {
306
- driver: "openpeeps";
307
- params: {
308
- path: string;
309
- prefix: string;
310
- host?: string | undefined;
311
- };
312
- };
313
- };
314
- network: {
315
- port: number;
316
- };
317
- plugins: {
318
- path: string;
319
- rootPackageJsonPath: string;
320
- };
321
- secrets: {
322
- jwt: string;
323
- };
324
- jams: {
325
- livekit: {
326
- url: string;
327
- apiKey?: string | undefined;
328
- apiSecret?: string | undefined;
329
- recordingEnabled?: boolean | undefined;
330
- };
331
- };
332
- vapid: {
333
- privateKey?: string | undefined;
334
- publicKey?: string | undefined;
335
- };
336
- federation: {
337
- active: boolean;
338
- allowedHosts: string[];
339
- };
340
- activityPub: {
341
- defaultDomain: string;
342
- itemsPerPage: number;
343
- threadDepth: number;
344
- federation: {
345
- requestTimeout: number;
346
- };
347
- };
348
- sso: {
349
- generic: {
350
- id: string;
351
- name: string;
352
- userProfileRequest: {
353
- url: string;
354
- authHeader?: string | undefined;
355
- };
356
- userProfilePaths: {
357
- email: string;
358
- handle?: string | undefined;
359
- avatar?: string | undefined;
360
- displayName?: string | undefined;
361
- };
362
- loginLink?: string | undefined;
363
- createAccounts?: boolean | undefined;
364
- createProfiles?: boolean | undefined;
365
- }[];
366
- oidc: {
367
- id: string;
368
- name: string;
369
- authorizationUrl: string;
370
- tokenUrl: string;
371
- userinfoUrl: string;
372
- clientId: string;
373
- kind?: "oidc" | "github" | "gitlab" | "gitlab-selfhosted" | "google" | "entra" | "auth0" | "keycloak" | "authentik" | "okta" | "discord" | "pocketid" | undefined;
374
- instanceUrl?: string | undefined;
375
- tenant?: string | undefined;
376
- emailsUrl?: string | undefined;
377
- jwksUri?: string | undefined;
378
- clientSecret?: string | undefined;
379
- scope?: string | undefined;
380
- claimMapping?: {
381
- email?: string | undefined;
382
- handle?: string | undefined;
383
- displayName?: string | undefined;
384
- avatar?: string | undefined;
385
- } | undefined;
386
- approvalRequired?: boolean | undefined;
387
- }[];
388
- onlySSO?: boolean | undefined;
389
- };
390
- services: {
391
- sentry: {
392
- enabled: boolean;
393
- dsn?: string | undefined;
394
- replayEnabled?: boolean | undefined;
395
- };
396
- location: {
397
- type: string;
398
- url: string;
399
- apiKey?: string | undefined;
400
- };
401
- };
402
- apps: {
403
- ios: {
404
- url?: string | undefined;
405
- bundleIdentifier?: string | undefined;
406
- teamId?: string | undefined;
407
- appId?: string | undefined;
408
- apnKeyId?: string | undefined;
409
- apnSigningKey?: string | undefined;
410
- };
411
- android: {
412
- url?: string | undefined;
413
- packageName?: string | undefined;
414
- appId?: string | undefined;
415
- fcmCredentials?: string | undefined;
416
- };
417
- };
418
- payments: {
419
- stripe: {
420
- paidMembership?: {
421
- enabled: boolean;
422
- productId?: string | undefined;
423
- trialPeriodDays?: number | undefined;
424
- } | undefined;
425
- publishableKey?: string | undefined;
426
- secretKey?: string | undefined;
427
- webhookSecret?: string | undefined;
428
- };
429
- };
430
- }>(namespace?: string, name?: string) => Promise<{
97
+ export declare const sanitizedConfigWithDefaults: <T = CoreConfig>(namespace?: string, name?: string) => Promise<{
431
98
  config: unknown;
432
99
  defaults: unknown;
433
100
  }>;
@@ -2,5 +2,5 @@ export { listExplorerTables, getExplorerTable, describeExplorerTable, quoteIdent
2
2
  export { listExplorerRows, DEFAULT_ROW_LIMIT, MAX_ROW_LIMIT, MAX_EXPORT_LIMIT, clampLimit, buildFilterClause, } from './query';
3
3
  export type { ListRowsInput } from './query';
4
4
  export { updateExplorerRow } from './mutate';
5
- export { runExplorerSql, SQL_STATEMENT_TIMEOUT_MS, SQL_MAX_ROWS, SQL_HARD_MAX_ROWS, SQL_DEFAULT_MAX_ROWS } from './sql';
5
+ export { runExplorerSql, SQL_STATEMENT_TIMEOUT_MS, SQL_MAX_ROWS, SQL_HARD_MAX_ROWS, SQL_DEFAULT_MAX_ROWS, } from './sql';
6
6
  export { rowsToCsv } from './csv';
@@ -1,5 +1,5 @@
1
1
  export { listExplorerTables, getExplorerTable, describeExplorerTable, quoteIdent, assertKnownColumns, primaryKeyColumns, } from './tables.js';
2
2
  export { listExplorerRows, DEFAULT_ROW_LIMIT, MAX_ROW_LIMIT, MAX_EXPORT_LIMIT, clampLimit, buildFilterClause, } from './query.js';
3
3
  export { updateExplorerRow } from './mutate.js';
4
- export { runExplorerSql, SQL_STATEMENT_TIMEOUT_MS, SQL_MAX_ROWS, SQL_HARD_MAX_ROWS, SQL_DEFAULT_MAX_ROWS } from './sql.js';
4
+ export { runExplorerSql, SQL_STATEMENT_TIMEOUT_MS, SQL_MAX_ROWS, SQL_HARD_MAX_ROWS, SQL_DEFAULT_MAX_ROWS, } from './sql.js';
5
5
  export { rowsToCsv } from './csv.js';
@@ -1,3 +1,4 @@
1
+ import { withDeletedProfileIdentity } from '@openpeepshq/common/lib';
1
2
  import * as documents from '../schema/documents.js';
2
3
  import * as edges from '../schema/edges.js';
3
4
  import { modelTimestampsFromRow, normalizeIsoDatetime, rowToModel, } from '../mappers.js';
@@ -402,7 +403,7 @@ export const rowToDocument = (collection, row, keepMetadata = false) => {
402
403
  guest: row.guest ?? undefined,
403
404
  }, timestamps);
404
405
  case 'profiles':
405
- return rowToModel(row.id, {
406
+ return withDeletedProfileIdentity(rowToModel(row.id, {
406
407
  handle: row.handle,
407
408
  type: row.type,
408
409
  ...(row.activityPubDomain
@@ -424,7 +425,7 @@ export const rowToDocument = (collection, row, keepMetadata = false) => {
424
425
  ...(typeof row.fetchedAt === 'string'
425
426
  ? { fetchedAt: normalizeIsoDatetime(row.fetchedAt) }
426
427
  : {}),
427
- }, timestamps);
428
+ }, timestamps));
428
429
  case 'posts': {
429
430
  const lastActivityAt = row.lastActivityAt
430
431
  ? normalizeIsoDatetime(row.lastActivityAt)
@@ -15,5 +15,7 @@ type AttendanceProfile = Pick<Profile, 'type' | 'displayName' | 'handle' | 'gues
15
15
  export declare const jamAttendanceExportHeaders: readonly ["Type", "Name", "Email", "Handle", "Joined At"];
16
16
  export declare const jamAttendanceRowFromJoin: (join: JoinRecord, profile: AttendanceProfile | undefined) => JamAttendanceExportRow;
17
17
  export declare const jamAttendanceExportCsv: (rows: JamAttendanceExportRow[]) => string;
18
+ /** Profiles that joined the jam room. Recurring jams share one room. */
19
+ export declare const listJamAttendeeProfileIds: (jamId: string) => Promise<string[]>;
18
20
  export declare const exportJamAttendanceCsv: (jamId: string) => Promise<string>;
19
21
  export {};
@@ -49,6 +49,11 @@ const listJamJoinEvents = async (jamId) => {
49
49
  ];
50
50
  });
51
51
  };
52
+ /** Profiles that joined the jam room. Recurring jams share one room. */
53
+ export const listJamAttendeeProfileIds = async (jamId) => {
54
+ const joins = await listJamJoinEvents(jamId);
55
+ return [...new Set(joins.map((join) => join.profileId))];
56
+ };
52
57
  export const exportJamAttendanceCsv = async (jamId) => {
53
58
  const joins = await listJamJoinEvents(jamId);
54
59
  const profileIds = [...new Set(joins.map((join) => join.profileId))];
@@ -10,6 +10,7 @@ export declare const listJamEvents: (jamId: string, { start, limit }?: {
10
10
  start?: string;
11
11
  limit?: number;
12
12
  }) => Promise<import("../db/pg/map").WithId<JamEvent>[]>;
13
+ export declare const listJamStarts: (jamId: string) => Promise<import("../db/pg/map").WithId<JamEvent>[]>;
13
14
  export declare const listAttendance: (jamId: string, { start, limit }?: {
14
15
  start?: string;
15
16
  limit?: number;
@@ -7,6 +7,7 @@ import { getJamState } from './cache.js';
7
7
  import { transformJamRecordingData } from './helpers.js';
8
8
  export const baseListJam = (props, { start, limit = 100 }) => addStartLimit(jamEventsMapping.filter({ matches: props }), start, limit);
9
9
  export const listJamEvents = (jamId, { start, limit } = {}) => allpeepDb().then(({ db }) => baseListJam({ jamId }, { start, limit }).all(db));
10
+ export const listJamStarts = (jamId) => allpeepDb().then(({ db }) => baseListJam({ jamId, type: 'start' }, { limit: 200 }).all(db));
10
11
  export const listAttendance = (jamId, { start, limit } = {}) => allpeepDb().then(({ db }) => baseListJam({ jamId, type: 'join' }, { start, limit }).all(db));
11
12
  export const findJamState = async (jam, hideParticipants, recurrenceId) => {
12
13
  const state = await getJamState(jam, recurrenceId);
@@ -1,10 +1,33 @@
1
+ import { type LivekitDiagnosis } from '@openpeepshq/common/types';
1
2
  export declare const LIVEKIT_HEALTH_TIMEOUT_MS = 5000;
2
3
  export declare const LIVEKIT_HEALTH_MAX_ATTEMPTS = 3;
4
+ /** Drop credential material if a client library echoes it in an error. */
5
+ export declare const redactSecrets: (message: string, secrets: Array<string | undefined>) => string;
6
+ export type LivekitProbeResult = {
7
+ ok: boolean;
8
+ error?: string;
9
+ };
3
10
  /**
4
11
  * True when a LiveKit RoomService call succeeds within maxAttempts. Retries so a
5
12
  * single transient failure does not disable jams for a full /server/info bucket.
6
13
  * Credentials in config are not enough — invalid keys fail on first RPC.
7
14
  */
15
+ export declare const probeLivekitConnectionResult: (listRooms: () => Promise<unknown>, timeoutMs?: number, maxAttempts?: number) => Promise<LivekitProbeResult>;
8
16
  export declare const probeLivekitConnection: (listRooms: () => Promise<unknown>, timeoutMs?: number, maxAttempts?: number) => Promise<boolean>;
9
17
  /** Cached LiveKit reachability. False when unset, unauthorized, or unreachable. */
10
18
  export declare const isLivekitConnected: () => Promise<boolean>;
19
+ export type LivekitDiagnosisInput = {
20
+ url?: string;
21
+ hasApiKey: boolean;
22
+ hasApiSecret: boolean;
23
+ recordingEnabled: boolean;
24
+ reachable: boolean;
25
+ error?: string;
26
+ };
27
+ /** Checklist the admin diagnosis page renders. Secrets never leave this shape. */
28
+ export declare const buildLivekitDiagnosis: (input: LivekitDiagnosisInput) => LivekitDiagnosis;
29
+ /**
30
+ * Fresh LiveKit check for admins. Bypasses the short health cache so Refresh
31
+ * reports the current credentials and the last probe error.
32
+ */
33
+ export declare const diagnoseLivekit: () => Promise<LivekitDiagnosis>;
@@ -1,4 +1,6 @@
1
1
  import { createCache } from 'cache-manager';
2
+ import { livekitDiagnosisSchema, } from '@openpeepshq/common/types';
3
+ import { config } from '../config/index.js';
2
4
  import { logger } from '../log/index.js';
3
5
  import { roomService } from './livekit.js';
4
6
  const log = logger('app:jams:livekit');
@@ -23,28 +25,98 @@ const withTimeout = (promise, timeoutMs) => new Promise((resolve, reject) => {
23
25
  reject(err);
24
26
  });
25
27
  });
28
+ const errorMessage = (e) => e instanceof Error && e.message ? e.message : 'LiveKit health check failed';
29
+ /** Drop credential material if a client library echoes it in an error. */
30
+ export const redactSecrets = (message, secrets) => secrets.reduce((text, secret) => {
31
+ if (!secret || secret.length < 8)
32
+ return text;
33
+ return text.split(secret).join('[redacted]');
34
+ }, message);
26
35
  /**
27
36
  * True when a LiveKit RoomService call succeeds within maxAttempts. Retries so a
28
37
  * single transient failure does not disable jams for a full /server/info bucket.
29
38
  * Credentials in config are not enough — invalid keys fail on first RPC.
30
39
  */
31
- export const probeLivekitConnection = async (listRooms, timeoutMs = LIVEKIT_HEALTH_TIMEOUT_MS, maxAttempts = LIVEKIT_HEALTH_MAX_ATTEMPTS) => {
40
+ export const probeLivekitConnectionResult = async (listRooms, timeoutMs = LIVEKIT_HEALTH_TIMEOUT_MS, maxAttempts = LIVEKIT_HEALTH_MAX_ATTEMPTS) => {
41
+ let lastError = 'LiveKit health check failed';
32
42
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
33
43
  try {
34
44
  await withTimeout(listRooms(), timeoutMs);
35
- return true;
45
+ return { ok: true };
36
46
  }
37
47
  catch (e) {
38
- log.warn(`LiveKit health check failed (attempt ${attempt}/${maxAttempts}): ${e.message}`);
48
+ lastError = errorMessage(e);
49
+ log.warn(`LiveKit health check failed (attempt ${attempt}/${maxAttempts}): ${lastError}`);
39
50
  }
40
51
  }
41
- return false;
52
+ return { ok: false, error: lastError };
42
53
  };
54
+ export const probeLivekitConnection = async (listRooms, timeoutMs = LIVEKIT_HEALTH_TIMEOUT_MS, maxAttempts = LIVEKIT_HEALTH_MAX_ATTEMPTS) => (await probeLivekitConnectionResult(listRooms, timeoutMs, maxAttempts)).ok;
43
55
  /** Cached LiveKit reachability. False when unset, unauthorized, or unreachable. */
44
56
  export const isLivekitConnected = () => livekitHealthCache.wrap(LIVEKIT_HEALTH_CACHE_KEY, async () => {
45
- const rs = await roomService();
46
- if (rs === undefined) {
57
+ try {
58
+ const rs = await roomService();
59
+ if (rs === undefined) {
60
+ return false;
61
+ }
62
+ return probeLivekitConnection(() => rs.listRooms([LIVEKIT_HEALTH_ROOM]));
63
+ }
64
+ catch (e) {
65
+ log.warn(`LiveKit health check failed: ${errorMessage(e)}`);
47
66
  return false;
48
67
  }
49
- return probeLivekitConnection(() => rs.listRooms([LIVEKIT_HEALTH_ROOM]));
50
68
  });
69
+ /** Checklist the admin diagnosis page renders. Secrets never leave this shape. */
70
+ export const buildLivekitDiagnosis = (input) => {
71
+ const configured = Boolean(input.url) && input.hasApiKey && input.hasApiSecret;
72
+ return {
73
+ connected: configured && input.reachable,
74
+ recordingEnabled: input.recordingEnabled,
75
+ ...(input.url ? { url: input.url } : {}),
76
+ ...(configured && !input.reachable && input.error
77
+ ? { error: input.error }
78
+ : {}),
79
+ checks: [
80
+ { id: 'url', ok: Boolean(input.url) },
81
+ { id: 'apiKey', ok: input.hasApiKey },
82
+ { id: 'apiSecret', ok: input.hasApiSecret },
83
+ { id: 'reachable', ok: configured && input.reachable },
84
+ ],
85
+ };
86
+ };
87
+ /**
88
+ * Fresh LiveKit check for admins. Bypasses the short health cache so Refresh
89
+ * reports the current credentials and the last probe error.
90
+ */
91
+ export const diagnoseLivekit = async () => {
92
+ const { url, apiKey, apiSecret, recordingEnabled } = (await config()).jams
93
+ .livekit;
94
+ const base = {
95
+ url,
96
+ hasApiKey: Boolean(apiKey),
97
+ hasApiSecret: Boolean(apiSecret),
98
+ recordingEnabled: !!recordingEnabled,
99
+ };
100
+ // Only probe when all credentials are present: a partial config can't tell
101
+ // "missing secret" apart from "auth rejected" and would surface errors that
102
+ // don't reflect the real problem.
103
+ let reachable = false;
104
+ let error;
105
+ if (url && apiKey && apiSecret) {
106
+ try {
107
+ const rs = await roomService();
108
+ if (rs) {
109
+ const probe = await probeLivekitConnectionResult(() => rs.listRooms([LIVEKIT_HEALTH_ROOM]));
110
+ reachable = probe.ok;
111
+ error = probe.error
112
+ ? redactSecrets(probe.error, [apiKey, apiSecret])
113
+ : undefined;
114
+ }
115
+ }
116
+ catch (e) {
117
+ error = redactSecrets(errorMessage(e), [apiKey, apiSecret]);
118
+ log.warn(`LiveKit diagnosis failed: ${error}`);
119
+ }
120
+ }
121
+ return livekitDiagnosisSchema.parse(buildLivekitDiagnosis({ ...base, reachable, error }));
122
+ };
@@ -1,6 +1,6 @@
1
1
  import { type AuthorizationData, type MuteParticipantRequest, type PostWithMeta, type Profile } from '@openpeepshq/common/types';
2
2
  export { createJamToken, createJamEgressToken } from './token';
3
- export { isLivekitConnected } from './health';
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';
5
5
  export { rtmpStreamOutput } from './rtmp';
6
6
  export { jamRecordingStopQueue, jamRecordingStopWorker, scheduleRecordingAutoStop, cancelRecordingAutoStop, JAM_RECORDING_MAX_DURATION_MS, } from './jobs';
@@ -10,7 +10,7 @@ import { canReadPost } from '../posts/helpers/index.js';
10
10
  import { capabilitiesConfig } from '../config/index.js';
11
11
  import { logger } from '../log/index.js';
12
12
  export { createJamToken, createJamEgressToken } from './token.js';
13
- export { isLivekitConnected } from './health.js';
13
+ export { diagnoseLivekit, isLivekitConnected } from './health.js';
14
14
  export { startRecording, stopRecording, startRtmpStream, stopRtmpStream, stopEgress, listParticipantIds, reclaimOrphanJamRoom, finishRecording, getJamRecordingUrl, getJamObserverPath, JAM_ROOM_EMPTY_TIMEOUT_SEC, JAM_ROOM_DEPARTURE_TIMEOUT_SEC, } from './livekit.js';
15
15
  export { rtmpStreamOutput } from './rtmp.js';
16
16
  export { jamRecordingStopQueue, jamRecordingStopWorker, scheduleRecordingAutoStop, cancelRecordingAutoStop, JAM_RECORDING_MAX_DURATION_MS, } from './jobs.js';
@@ -35,7 +35,14 @@ const reclaimLocalOrphan = (post) => {
35
35
  * Auth filtering happens in {@link listLiveJams} so the cache is not per-user.
36
36
  */
37
37
  const fetchLiveJamPosts = async () => {
38
- const rs = await roomService();
38
+ let rs;
39
+ try {
40
+ rs = await roomService();
41
+ }
42
+ catch (e) {
43
+ log.warn(`Failed to reach LiveKit (${e.message}). Admins can diagnose this at /admin/diagnostics/livekit.`);
44
+ return [];
45
+ }
39
46
  if (rs === undefined) {
40
47
  return [];
41
48
  }
@@ -48,7 +55,7 @@ const fetchLiveJamPosts = async () => {
48
55
  ]);
49
56
  }
50
57
  catch (e) {
51
- log.warn(`Failed to list live jam rooms: ${e.message}`);
58
+ log.warn(`Failed to list live jam rooms (${e.message}). Admins can diagnose this at /admin/diagnostics/livekit.`);
52
59
  return [];
53
60
  }
54
61
  const posts = await Promise.all(rooms.map(async (room) => {
@@ -1,5 +1,5 @@
1
1
  import { publicProfileSchema, } from '@openpeepshq/common/types';
2
- import { canModerateJam, countYesRsvps, getEffectiveRsvp, isBlockedPair, jamRoomName, } from '@openpeepshq/common/lib';
2
+ import { canModerateJam, countYesRsvps, getEffectiveRsvp, isBlockedPair, jamRoomName, occurrenceForJamStart, } from '@openpeepshq/common/lib';
3
3
  import { authNeeded, forbidden, notFound } from '../errors/index.js';
4
4
  import { config } from '../config/index.js';
5
5
  import { AccessToken, TrackSource } from 'livekit-server-sdk';
@@ -133,7 +133,11 @@ export const createJamToken = async (event, profile, { external = false, recurre
133
133
  canUpdateOwnMetadata: true,
134
134
  });
135
135
  if (!jamOpen) {
136
- hub.emit('jamStarted', profile, event);
136
+ const eventData = event.data?.type === 'event' ? event.data : undefined;
137
+ const startedOccurrenceId = eventData
138
+ ? occurrenceForJamStart(eventData, { recurrenceId })?.recurrenceId
139
+ : undefined;
140
+ hub.emit('jamStarted', profile, event, startedOccurrenceId);
137
141
  }
138
142
  return accessToken.toJwt();
139
143
  };
@@ -12,7 +12,9 @@ const currentWaitingRoom = (event, recurrenceId) => getSharedConnection()
12
12
  .then((entries) => entries.filter((e) => e[0] && e[1]))
13
13
  .then((entries) => entries.map(([key, value]) => [
14
14
  key,
15
- publicProfileSchema.partial().parse(JSON.parse(value)),
15
+ publicProfileSchema
16
+ .partial()
17
+ .parse(JSON.parse(value)),
16
18
  ]))
17
19
  .then((entries) => Object.fromEntries(entries));
18
20
  const currentAdmittance = (event, recurrenceId) => getSharedConnection().then((conn) => conn.hGetAll(admittanceKey(event, recurrenceId)));