@openpeepshq/core 0.1.32 → 0.1.34

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 (261) hide show
  1. package/dist/accessTokens/helpers.d.ts +2 -2
  2. package/dist/accessTokens/tokens.js +14 -7
  3. package/dist/accounts/mutations.d.ts +2 -2
  4. package/dist/accounts/mutations.js +33 -35
  5. package/dist/analytics/cache.js +12 -7
  6. package/dist/analytics/compile.js +16 -10
  7. package/dist/analytics/pdfReport.d.ts +1 -0
  8. package/dist/analytics/pdfReport.js +5 -4
  9. package/dist/analytics/privacy.d.ts +18 -0
  10. package/dist/analytics/privacy.js +10 -0
  11. package/dist/analytics/read.js +75 -19
  12. package/dist/analytics/report.d.ts +21 -1
  13. package/dist/analytics/report.js +9 -2
  14. package/dist/backups/index.js +78 -15
  15. package/dist/backups/metadata.d.ts +8 -2
  16. package/dist/backups/metadata.js +6 -2
  17. package/dist/config/defaults/capabilities.js +13 -2
  18. package/dist/config/defaults/community.js +7 -9
  19. package/dist/config/defaults/core.d.ts +1 -1
  20. package/dist/config/defaults/core.js +3 -0
  21. package/dist/config/defaults/db.d.ts +0 -2
  22. package/dist/config/defaults/db.js +0 -2
  23. package/dist/config/index.d.ts +25 -3
  24. package/dist/config/index.js +7 -1
  25. package/dist/db/helpers.d.ts +7 -28
  26. package/dist/db/helpers.js +30 -152
  27. package/dist/db/index.d.ts +3 -1
  28. package/dist/db/index.js +5 -0
  29. package/dist/db/init.js +2 -2
  30. package/dist/db/migration/importCollections.d.ts +15 -10
  31. package/dist/db/migration/importCollections.js +121 -155
  32. package/dist/db/migration/shared.d.ts +2 -37
  33. package/dist/db/migration/shared.js +2 -59
  34. package/dist/db/pg/client.js +4 -0
  35. package/dist/db/pg/collections.d.ts +2 -2
  36. package/dist/db/pg/collections.js +2 -2
  37. package/dist/db/pg/filters/edges.d.ts +1 -1
  38. package/dist/db/pg/filters/edges.js +1 -1
  39. package/dist/db/pg/filters/posts.d.ts +11 -0
  40. package/dist/db/pg/filters/posts.js +37 -3
  41. package/dist/db/pg/filters/profiles.d.ts +1 -0
  42. package/dist/db/pg/filters/profiles.js +2 -1
  43. package/dist/db/pg/map/filters.js +37 -2
  44. package/dist/db/pg/map/mutations.js +13 -8
  45. package/dist/db/pg/map/registry.d.ts +5 -0
  46. package/dist/db/pg/map/registry.js +64 -24
  47. package/dist/db/pg/map/relations.d.ts +1 -1
  48. package/dist/db/pg/map/relations.js +98 -46
  49. package/dist/db/pg/migrate.d.ts +22 -0
  50. package/dist/db/pg/migrate.js +88 -2
  51. package/dist/db/pg/queries/activity.js +3 -3
  52. package/dist/db/pg/queries/sorts.d.ts +1 -0
  53. package/dist/db/pg/queries/sorts.js +4 -0
  54. package/dist/db/pg/schema/documents.d.ts +422 -41
  55. package/dist/db/pg/schema/documents.js +43 -9
  56. package/dist/db/pg/schema/edges.d.ts +117 -7
  57. package/dist/db/pg/schema/edges.js +4 -2
  58. package/dist/db/pg/schema/index.d.ts +505 -15
  59. package/dist/db/pg/sql/0007_shallow_oracle.sql +3 -0
  60. package/dist/db/pg/sql/0008_group_owner_roles.sql +31 -0
  61. package/dist/db/pg/sql/0009_event_occurrences.sql +26 -0
  62. package/dist/db/pg/sql/0010_user_group_membership_roles.sql +16 -0
  63. package/dist/db/pg/sql/0011_drop_data_migrations.sql +1 -0
  64. package/dist/db/pg/sql/0012_posts_last_activity_at.sql +5 -0
  65. package/dist/db/pg/sql/0013_add_blocks_edge.sql +12 -0
  66. package/dist/db/pg/sql/0014_federation_datamodel.sql +59 -0
  67. package/dist/db/pg/sql/0015_profile_hashtags.sql +12 -0
  68. package/dist/db/pg/sql/meta/{0006_snapshot.json → 0015_snapshot.json} +393 -39
  69. package/dist/db/pg/sql/meta/_journal.json +64 -1
  70. package/dist/db/replaceOrigin.js +6 -0
  71. package/dist/db/types.d.ts +0 -4
  72. package/dist/email/render.js +11 -3
  73. package/dist/events/index.d.ts +6 -1
  74. package/dist/events/index.js +55 -33
  75. package/dist/federation/activities.d.ts +17 -0
  76. package/dist/federation/activities.js +26 -0
  77. package/dist/federation/identity.d.ts +16 -0
  78. package/dist/federation/identity.js +52 -0
  79. package/dist/federation/index.d.ts +4 -0
  80. package/dist/federation/index.js +3 -0
  81. package/dist/federation/profiles.d.ts +3 -0
  82. package/dist/federation/profiles.js +14 -0
  83. package/dist/groups/finders.d.ts +3 -2
  84. package/dist/groups/helpers.d.ts +24 -6
  85. package/dist/groups/mapping.d.ts +6 -4
  86. package/dist/groups/mapping.js +2 -2
  87. package/dist/groups/mutations.js +1 -1
  88. package/dist/hashtags/finders.d.ts +6 -3
  89. package/dist/hashtags/finders.js +2 -0
  90. package/dist/hashtags/helpers.d.ts +8 -0
  91. package/dist/hashtags/helpers.js +4 -0
  92. package/dist/hashtags/index.d.ts +2 -0
  93. package/dist/hashtags/index.js +2 -0
  94. package/dist/hashtags/mutations.d.ts +3 -0
  95. package/dist/hashtags/mutations.js +13 -1
  96. package/dist/i18n/index.d.ts +1 -1
  97. package/dist/i18n/index.js +3 -1
  98. package/dist/i18n/pluginLocales.d.ts +6 -0
  99. package/dist/i18n/pluginLocales.js +15 -0
  100. package/dist/inviteLinks/helpers.d.ts +4 -4
  101. package/dist/jams/cache.d.ts +1 -1
  102. package/dist/jams/cache.js +2 -1
  103. package/dist/jams/export.d.ts +19 -0
  104. package/dist/jams/export.js +60 -0
  105. package/dist/jams/finders.d.ts +2 -1
  106. package/dist/jams/finders.js +18 -7
  107. package/dist/jams/health.d.ts +8 -0
  108. package/dist/jams/health.js +46 -0
  109. package/dist/jams/helpers.d.ts +6 -2
  110. package/dist/jams/index.d.ts +6 -3
  111. package/dist/jams/index.js +41 -27
  112. package/dist/jams/jobs.js +1 -1
  113. package/dist/jams/livekit.d.ts +93 -10
  114. package/dist/jams/livekit.js +151 -52
  115. package/dist/jams/mapping.d.ts +17 -7
  116. package/dist/jams/mutations.d.ts +3 -1
  117. package/dist/jams/recording.d.ts +10 -0
  118. package/dist/jams/recording.js +32 -0
  119. package/dist/jams/rtmp.d.ts +5 -0
  120. package/dist/jams/rtmp.js +8 -0
  121. package/dist/jams/token.d.ts +15 -3
  122. package/dist/jams/token.js +30 -16
  123. package/dist/jams/waitingRoom.d.ts +6 -6
  124. package/dist/jams/waitingRoom.js +24 -23
  125. package/dist/jobs/index.d.ts +1 -0
  126. package/dist/jobs/index.js +6 -1
  127. package/dist/jobs/jobDetail.js +1 -6
  128. package/dist/media/index.d.ts +1 -1
  129. package/dist/media/index.js +23 -8
  130. package/dist/media/processing.js +18 -7
  131. package/dist/notifications/defaultNotifications/follow/index.js +2 -2
  132. package/dist/notifications/defaultNotifications/groupMemberJoined/index.js +3 -1
  133. package/dist/notifications/defaultNotifications/groupMemberLeft/index.js +3 -1
  134. package/dist/notifications/defaultNotifications/index.js +4 -0
  135. package/dist/notifications/defaultNotifications/newGroupPost/index.js +12 -6
  136. package/dist/notifications/defaultNotifications/pollEnded/index.d.ts +19 -0
  137. package/dist/notifications/defaultNotifications/pollEnded/index.js +39 -0
  138. package/dist/notifications/defaultNotifications/pollEnded/recipients.d.ts +3 -0
  139. package/dist/notifications/defaultNotifications/pollEnded/recipients.js +18 -0
  140. package/dist/notifications/defaultNotifications/rsvp/index.d.ts +6 -1
  141. package/dist/notifications/defaultNotifications/rsvp/index.js +7 -0
  142. package/dist/notifications/defaultNotifications/rsvpCanceled/index.d.ts +24 -0
  143. package/dist/notifications/defaultNotifications/rsvpCanceled/index.js +75 -0
  144. package/dist/notifications/defaultNotifications/rsvpCanceled/recipients.d.ts +4 -0
  145. package/dist/notifications/defaultNotifications/rsvpCanceled/recipients.js +11 -0
  146. package/dist/notifications/helpers.js +6 -2
  147. package/dist/notifications/jobs.js +3 -1
  148. package/dist/notifications/mutations.js +4 -0
  149. package/dist/notifications/push.js +11 -4
  150. package/dist/plugins/helpers.d.ts +1 -0
  151. package/dist/plugins/helpers.js +1 -8
  152. package/dist/plugins/index.d.ts +5 -0
  153. package/dist/plugins/index.js +78 -5
  154. package/dist/plugins/install.d.ts +39 -0
  155. package/dist/plugins/install.js +455 -0
  156. package/dist/plugins/pluginAuth.d.ts +1 -1
  157. package/dist/plugins/pluginAuth.js +10 -6
  158. package/dist/plugins/state.d.ts +4 -0
  159. package/dist/plugins/state.js +29 -0
  160. package/dist/posts/activity.d.ts +9 -0
  161. package/dist/posts/activity.js +35 -0
  162. package/dist/posts/contextClosure.d.ts +1 -9
  163. package/dist/posts/contextClosure.js +15 -44
  164. package/dist/posts/conversationQueries.d.ts +7 -0
  165. package/dist/posts/conversationQueries.js +76 -2
  166. package/dist/posts/eventAgenda.d.ts +166 -0
  167. package/dist/posts/eventAgenda.js +126 -0
  168. package/dist/posts/eventOccurrenceJobs.d.ts +4 -0
  169. package/dist/posts/eventOccurrenceJobs.js +28 -0
  170. package/dist/posts/eventOccurrences.d.ts +10 -0
  171. package/dist/posts/eventOccurrences.js +61 -0
  172. package/dist/posts/finders.d.ts +47 -16
  173. package/dist/posts/finders.js +93 -62
  174. package/dist/posts/helpers/filters.js +14 -9
  175. package/dist/posts/helpers/index.d.ts +129 -30
  176. package/dist/posts/helpers/index.js +66 -33
  177. package/dist/posts/index.d.ts +7 -1
  178. package/dist/posts/index.js +7 -1
  179. package/dist/posts/mapping.d.ts +491 -13
  180. package/dist/posts/mapping.js +45 -10
  181. package/dist/posts/mutations.d.ts +441 -4
  182. package/dist/posts/mutations.js +177 -43
  183. package/dist/posts/pollEnd.d.ts +3 -0
  184. package/dist/posts/pollEnd.js +7 -0
  185. package/dist/posts/pollEndJobs.d.ts +8 -0
  186. package/dist/posts/pollEndJobs.js +49 -0
  187. package/dist/posts/replyClosure.d.ts +10 -0
  188. package/dist/posts/replyClosure.js +43 -0
  189. package/dist/posts/rsvpConfirmationEmail.js +14 -15
  190. package/dist/posts/threadPreview.d.ts +8 -0
  191. package/dist/posts/threadPreview.js +44 -0
  192. package/dist/posts/unseenCounts.d.ts +2 -0
  193. package/dist/posts/unseenCounts.js +28 -8
  194. package/dist/profileSettings/cache.js +22 -5
  195. package/dist/profileSettings/mapping.d.ts +2 -0
  196. package/dist/profiles/activityQueries.d.ts +5 -0
  197. package/dist/profiles/activityQueries.js +85 -0
  198. package/dist/profiles/activitySummary.d.ts +3 -0
  199. package/dist/profiles/activitySummary.js +87 -0
  200. package/dist/profiles/blocks.d.ts +12 -0
  201. package/dist/profiles/blocks.js +73 -0
  202. package/dist/profiles/cache.d.ts +4 -1
  203. package/dist/profiles/cache.js +28 -7
  204. package/dist/profiles/finders.d.ts +2 -1
  205. package/dist/profiles/finders.js +8 -3
  206. package/dist/profiles/helpers.d.ts +7 -5
  207. package/dist/profiles/index.d.ts +3 -1
  208. package/dist/profiles/index.js +3 -1
  209. package/dist/profiles/mapping.d.ts +10 -5
  210. package/dist/profiles/mapping.js +13 -1
  211. package/dist/profiles/mutations.d.ts +8 -4
  212. package/dist/profiles/mutations.js +42 -15
  213. package/dist/pushSubscriptions/helpers.d.ts +2 -2
  214. package/dist/pushSubscriptions/mutations.js +13 -1
  215. package/dist/redis/connection.d.ts +2 -0
  216. package/dist/redis/connection.js +25 -6
  217. package/dist/reports/helpers.d.ts +6 -6
  218. package/dist/roles/index.d.ts +1 -1
  219. package/dist/roles/index.js +1 -1
  220. package/dist/roles/mapping.d.ts +1 -0
  221. package/dist/roles/mutations.js +86 -3
  222. package/dist/search/mapping.d.ts +1 -1
  223. package/dist/search/mapping.js +6 -2
  224. package/dist/server/index.d.ts +19 -1
  225. package/dist/server/index.js +37 -18
  226. package/dist/server/stablePublicServerInfo.d.ts +17 -0
  227. package/dist/server/stablePublicServerInfo.js +37 -0
  228. package/dist/server/status.d.ts +25 -0
  229. package/dist/server/status.js +98 -0
  230. package/dist/stats/finders.d.ts +1 -16131
  231. package/dist/stats/finders.js +9 -5
  232. package/dist/stats/mapping.d.ts +21 -1
  233. package/dist/stats/mapping.js +0 -3
  234. package/package.json +6 -12
  235. package/dist/db/arango.d.ts +0 -2
  236. package/dist/db/arango.js +0 -110
  237. package/dist/db/migration/autoMigrate.d.ts +0 -2
  238. package/dist/db/migration/autoMigrate.js +0 -111
  239. package/dist/db/migration/cli.d.ts +0 -1
  240. package/dist/db/migration/cli.js +0 -56
  241. package/dist/db/migration/detect.d.ts +0 -6
  242. package/dist/db/migration/detect.js +0 -87
  243. package/dist/db/migration/exportArango.d.ts +0 -4
  244. package/dist/db/migration/exportArango.js +0 -80
  245. package/dist/db/migration/importPostgres.d.ts +0 -3
  246. package/dist/db/migration/importPostgres.js +0 -18
  247. package/dist/db/migration/transform.d.ts +0 -18
  248. package/dist/db/migration/transform.js +0 -209
  249. package/dist/db/migration/validate.d.ts +0 -18
  250. package/dist/db/migration/validate.js +0 -69
  251. package/dist/db/pg/sql/meta/0000_snapshot.json +0 -3380
  252. package/dist/db/pg/sql/meta/0004_snapshot.json +0 -4114
  253. package/dist/db/pg/sql/meta/0005_snapshot.json +0 -4179
  254. package/dist/mastodon/index.d.ts +0 -4
  255. package/dist/mastodon/index.js +0 -51
  256. package/dist/mastodon/types.d.ts +0 -7579
  257. package/dist/mastodon/types.js +0 -523
  258. package/dist/mastodon/typescript.d.ts +0 -1578
  259. package/dist/mastodon/typescript.js +0 -1
  260. package/dist/roles/defaults.d.ts +0 -2
  261. package/dist/roles/defaults.js +0 -94
@@ -0,0 +1,455 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createRequire } from 'node:module';
3
+ import fs from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import { defaultConfig } from '../config/index.js';
6
+ import { logger } from '../log/index.js';
7
+ import { allpeepDb } from '../db/index.js';
8
+ import { configs } from '../db/pg/schema/documents.js';
9
+ import { nowIso } from '../db/pg/mappers.js';
10
+ import { eq } from 'drizzle-orm';
11
+ import { setPluginEnabledOverride } from './state.js';
12
+ const log = logger('core:plugins:install');
13
+ const requireFromHost = createRequire(new URL('../../package.json', import.meta.url));
14
+ const MAX_COMMAND_OUTPUT = 16000;
15
+ const INSTALLED_PLUGINS_KEY = 'openpeeps-installed-plugins';
16
+ export const getInstalledPlugins = async () => {
17
+ var _a, _b;
18
+ const { db } = await allpeepDb();
19
+ const rows = await db
20
+ .select()
21
+ .from(configs)
22
+ .where(eq(configs.key, INSTALLED_PLUGINS_KEY))
23
+ .limit(1);
24
+ return (_b = (_a = rows[0]) === null || _a === void 0 ? void 0 : _a.body) !== null && _b !== void 0 ? _b : {};
25
+ };
26
+ const setInstalledPlugin = async (pluginKey, source, requiresAuth, installedBy) => {
27
+ const installed = await getInstalledPlugins();
28
+ const body = Object.assign(Object.assign({}, installed), { [pluginKey]: { source, requiresAuth, installedAt: nowIso(), installedBy } });
29
+ const ts = nowIso();
30
+ const { db } = await allpeepDb();
31
+ await db
32
+ .insert(configs)
33
+ .values({ key: INSTALLED_PLUGINS_KEY, body, createdAt: ts, updatedAt: ts })
34
+ .onConflictDoUpdate({
35
+ target: configs.key,
36
+ set: { body, updatedAt: ts },
37
+ });
38
+ };
39
+ const removeInstalledPlugin = async (pluginKey) => {
40
+ const installed = await getInstalledPlugins();
41
+ const rest = Object.fromEntries(Object.entries(installed).filter(([key]) => key !== pluginKey));
42
+ const ts = nowIso();
43
+ const { db } = await allpeepDb();
44
+ await db
45
+ .insert(configs)
46
+ .values({
47
+ key: INSTALLED_PLUGINS_KEY,
48
+ body: rest,
49
+ createdAt: ts,
50
+ updatedAt: ts,
51
+ })
52
+ .onConflictDoUpdate({
53
+ target: configs.key,
54
+ set: { body: rest, updatedAt: ts },
55
+ });
56
+ };
57
+ const runCommand = (command, args, cwd, environment = {}) => new Promise((resolve) => {
58
+ const child = spawn(command, args, {
59
+ cwd,
60
+ env: Object.assign({ HOME: process.env.HOME, LANG: process.env.LANG, LC_ALL: process.env.LC_ALL, NODE_EXTRA_CA_CERTS: process.env.NODE_EXTRA_CA_CERTS, PATH: process.env.PATH, SSL_CERT_DIR: process.env.SSL_CERT_DIR, SSL_CERT_FILE: process.env.SSL_CERT_FILE, TMPDIR: process.env.TMPDIR }, environment),
61
+ shell: false,
62
+ });
63
+ let stdout = '';
64
+ let stderr = '';
65
+ child.stdout.on('data', (chunk) => {
66
+ stdout += chunk.toString();
67
+ });
68
+ child.stderr.on('data', (chunk) => {
69
+ stderr += chunk.toString();
70
+ });
71
+ child.on('close', (exitCode) => {
72
+ resolve({ exitCode: exitCode !== null && exitCode !== void 0 ? exitCode : 1, stdout, stderr });
73
+ });
74
+ child.on('error', (err) => {
75
+ resolve({ exitCode: 1, stdout, stderr: String(err) });
76
+ });
77
+ });
78
+ const getPluginDir = async () => {
79
+ const { plugins } = await defaultConfig;
80
+ return plugins.path;
81
+ };
82
+ const redactUrl = (url) => {
83
+ const parsed = new URL(url);
84
+ if (parsed.protocol !== 'ssh:') {
85
+ parsed.username = '';
86
+ }
87
+ parsed.password = '';
88
+ return parsed.toString();
89
+ };
90
+ const sourceLabel = (source) => source.type === 'npm'
91
+ ? `npm:${source.package}${source.version ? `@${source.version}` : ''}`
92
+ : `git:${redactUrl(source.url)}${source.ref ? `#${source.ref}` : ''}`;
93
+ /**
94
+ * Inverse of sourceLabel for credentials-free sources; undefined when the
95
+ * stored label is not a label this version produced.
96
+ */
97
+ const parseInstallSource = (label) => {
98
+ if (label.startsWith('npm:')) {
99
+ const spec = label.slice('npm:'.length);
100
+ const at = spec.lastIndexOf('@');
101
+ // A leading '@' is the scope prefix, not a version separator.
102
+ if (at <= 0) {
103
+ return { type: 'npm', package: spec };
104
+ }
105
+ return {
106
+ type: 'npm',
107
+ package: spec.slice(0, at),
108
+ version: spec.slice(at + 1),
109
+ };
110
+ }
111
+ if (label.startsWith('git:')) {
112
+ const spec = label.slice('git:'.length);
113
+ const hash = spec.indexOf('#');
114
+ if (hash === -1) {
115
+ return { type: 'git', url: spec };
116
+ }
117
+ return { type: 'git', url: spec.slice(0, hash), ref: spec.slice(hash + 1) };
118
+ }
119
+ return undefined;
120
+ };
121
+ const sourceSecrets = (source) => {
122
+ if (source.type === 'npm') {
123
+ return source.auth ? [source.auth.token] : [];
124
+ }
125
+ if (!source.auth) {
126
+ return [];
127
+ }
128
+ if (source.auth.type === 'token') {
129
+ return [source.auth.token];
130
+ }
131
+ return [source.auth.privateKey];
132
+ };
133
+ const redactSecrets = (value, secrets) => secrets.reduce((redacted, secret) => redacted.split(secret).join('[REDACTED]'), value);
134
+ const trimCommandOutput = (value) => value.length <= MAX_COMMAND_OUTPUT
135
+ ? value
136
+ : `${value.slice(0, MAX_COMMAND_OUTPUT)}\n… truncated`;
137
+ const commandFailure = (operation, result, secrets) => {
138
+ const output = [result.stderr, result.stdout]
139
+ .map((part) => part.trim())
140
+ .filter(Boolean)
141
+ .join('\n');
142
+ return redactSecrets(`${operation} failed: ${trimCommandOutput(output)}`, secrets).trim();
143
+ };
144
+ const peerDependencyNames = (pkgJson) => {
145
+ const peers = pkgJson.peerDependencies;
146
+ if (!peers || typeof peers !== 'object' || Array.isArray(peers)) {
147
+ return [];
148
+ }
149
+ return Object.keys(peers);
150
+ };
151
+ const resolveHostPackage = async (name) => {
152
+ let current = path.dirname(requireFromHost.resolve(name));
153
+ while (true) {
154
+ try {
155
+ const pkg = JSON.parse(await fs.readFile(path.join(current, 'package.json'), 'utf8'));
156
+ if (pkg.name === name) {
157
+ return current;
158
+ }
159
+ }
160
+ catch (_a) {
161
+ // Keep walking toward the filesystem root.
162
+ }
163
+ const parent = path.dirname(current);
164
+ if (parent === current) {
165
+ throw new Error(`Could not locate package root for "${name}".`);
166
+ }
167
+ current = parent;
168
+ }
169
+ };
170
+ export const linkHostPeerDependencies = async (installDir, names) => {
171
+ for (const name of names) {
172
+ let resolved;
173
+ try {
174
+ resolved = await resolveHostPackage(name);
175
+ }
176
+ catch (_a) {
177
+ return {
178
+ success: false,
179
+ error: `Host does not provide peer dependency "${name}".`,
180
+ };
181
+ }
182
+ const destination = path.join(installDir, 'node_modules', name);
183
+ await fs.mkdir(path.dirname(destination), { recursive: true });
184
+ await fs.rm(destination, { recursive: true, force: true });
185
+ await fs.symlink(resolved, destination);
186
+ }
187
+ return { success: true };
188
+ };
189
+ const writeNpmConfig = async (tempDir, auth) => {
190
+ var _a;
191
+ if (!auth) {
192
+ return {};
193
+ }
194
+ const registry = new URL((_a = auth.registry) !== null && _a !== void 0 ? _a : 'https://registry.npmjs.org/');
195
+ const registryUrl = registry.toString().replace(/\/?$/, '/');
196
+ const authPath = registry.pathname.replace(/\/?$/, '/');
197
+ const configPath = path.join(tempDir, '.npmrc');
198
+ await fs.writeFile(configPath, [
199
+ `registry=${registryUrl}`,
200
+ `//${registry.host}${authPath}:_authToken=${auth.token}`,
201
+ 'always-auth=true',
202
+ '',
203
+ ].join('\n'), { mode: 0o600 });
204
+ return { NPM_CONFIG_USERCONFIG: configPath };
205
+ };
206
+ const removeNpmConfig = (tempDir) => fs.rm(path.join(tempDir, '.npmrc'), { force: true });
207
+ const writeGitAuth = async (tempDir, auth) => {
208
+ if (!auth) {
209
+ return { GIT_TERMINAL_PROMPT: '0' };
210
+ }
211
+ if (auth.type === 'token') {
212
+ const askpassPath = path.join(tempDir, 'git-askpass');
213
+ await fs.writeFile(askpassPath, [
214
+ '#!/bin/sh',
215
+ 'case "$1" in',
216
+ ' *Username*) printf "%s\\n" "$OPENPEEPS_GIT_USERNAME" ;;',
217
+ ' *) printf "%s\\n" "$OPENPEEPS_GIT_TOKEN" ;;',
218
+ 'esac',
219
+ '',
220
+ ].join('\n'), { mode: 0o700 });
221
+ return {
222
+ GIT_ASKPASS: askpassPath,
223
+ GIT_ASKPASS_REQUIRE: 'force',
224
+ GIT_TERMINAL_PROMPT: '0',
225
+ OPENPEEPS_GIT_TOKEN: auth.token,
226
+ OPENPEEPS_GIT_USERNAME: auth.username,
227
+ };
228
+ }
229
+ const keyPath = path.join(tempDir, 'git-deploy-key');
230
+ const knownHostsPath = path.join(tempDir, 'known_hosts');
231
+ await fs.writeFile(keyPath, `${auth.privateKey.trim()}\n`, { mode: 0o600 });
232
+ await fs.writeFile(knownHostsPath, '', { mode: 0o600 });
233
+ return {
234
+ GIT_SSH_COMMAND: [
235
+ 'ssh',
236
+ '-F /dev/null',
237
+ `-i "${keyPath}"`,
238
+ '-o BatchMode=yes',
239
+ '-o IdentitiesOnly=yes',
240
+ '-o StrictHostKeyChecking=accept-new',
241
+ `-o UserKnownHostsFile="${knownHostsPath}"`,
242
+ ].join(' '),
243
+ GIT_SSH_VARIANT: 'ssh',
244
+ GIT_TERMINAL_PROMPT: '0',
245
+ };
246
+ };
247
+ export const installPlugin = async (source, installedBy, options) => {
248
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
249
+ const pluginsDir = await getPluginDir();
250
+ const label = sourceLabel(source);
251
+ const secrets = sourceSecrets(source);
252
+ let tempDir;
253
+ try {
254
+ tempDir = await fs.mkdtemp(path.join(pluginsDir, '.install-'));
255
+ }
256
+ catch (e) {
257
+ log.error(e, `Failed to create temp dir in ${pluginsDir}`);
258
+ return { success: false, error: `Cannot write to plugins directory: ${e}` };
259
+ }
260
+ try {
261
+ let installDir;
262
+ let npmEnvironment;
263
+ if (source.type === 'npm') {
264
+ const pkg = source.version
265
+ ? `${source.package}@${source.version}`
266
+ : source.package;
267
+ log.info(`Installing npm package ${pkg} to temp dir ${tempDir}`);
268
+ const init = await runCommand('npm', ['init', '-y'], tempDir);
269
+ if (init.exitCode !== 0) {
270
+ const error = commandFailure('npm init', init, secrets);
271
+ log.error(new Error(error), `npm init failed for ${label}.`);
272
+ return { success: false, error };
273
+ }
274
+ npmEnvironment = await writeNpmConfig(tempDir, source.auth);
275
+ const install = await runCommand('npm', ['install', '--omit=peer', pkg], tempDir, npmEnvironment);
276
+ if (install.exitCode !== 0) {
277
+ const error = commandFailure('npm install', install, secrets);
278
+ log.error(new Error(error), `npm install failed for ${label}.`);
279
+ return { success: false, error };
280
+ }
281
+ installDir = path.join(tempDir, 'node_modules', source.package);
282
+ }
283
+ else {
284
+ const repositoryUrl = redactUrl(source.url);
285
+ log.info(`Cloning git repo ${repositoryUrl} to temp dir ${tempDir}`);
286
+ const cloneArgs = ['clone', '--depth', '1'];
287
+ if (source.ref) {
288
+ cloneArgs.push('--branch', source.ref);
289
+ }
290
+ cloneArgs.push(repositoryUrl, path.join(tempDir, 'repo'));
291
+ const gitEnvironment = await writeGitAuth(tempDir, source.auth);
292
+ const clone = await runCommand('git', cloneArgs, tempDir, gitEnvironment);
293
+ if (clone.exitCode !== 0) {
294
+ const error = commandFailure('git clone', clone, secrets);
295
+ log.error(new Error(error), `git clone failed for ${label}.`);
296
+ return { success: false, error };
297
+ }
298
+ installDir = path.join(tempDir, 'repo');
299
+ }
300
+ // Read package.json to determine namespace/name
301
+ const pkgJsonRaw = await fs.readFile(path.join(installDir, 'package.json'), 'utf-8');
302
+ const pkgJson = JSON.parse(pkgJsonRaw);
303
+ const namespace = (_e = (_b = (_a = pkgJson.openpeeps) === null || _a === void 0 ? void 0 : _a.namespace) !== null && _b !== void 0 ? _b : (_d = (_c = pkgJson.name) === null || _c === void 0 ? void 0 : _c.split('/')[0]) === null || _d === void 0 ? void 0 : _d.replace(/^@/, '')) !== null && _e !== void 0 ? _e : 'custom';
304
+ const name = (_l = (_j = (_g = (_f = pkgJson.openpeeps) === null || _f === void 0 ? void 0 : _f.name) !== null && _g !== void 0 ? _g : (_h = pkgJson.name) === null || _h === void 0 ? void 0 : _h.split('/')[1]) !== null && _j !== void 0 ? _j : (_k = pkgJson.name) === null || _k === void 0 ? void 0 : _k.replace(/^@[^/]+\//, '')) !== null && _l !== void 0 ? _l : 'plugin';
305
+ const pluginKey = `${namespace}/${name}`;
306
+ const destDir = path.join(pluginsDir, namespace, name);
307
+ // Check if already exists in the plugins dir (built-in)
308
+ const existingEntries = await fs
309
+ .readdir(pluginsDir)
310
+ .catch(() => []);
311
+ const nsEntries = existingEntries.includes(namespace)
312
+ ? await fs
313
+ .readdir(path.join(pluginsDir, namespace))
314
+ .catch(() => [])
315
+ : [];
316
+ if (nsEntries.includes(name)) {
317
+ // Check if this is a built-in plugin (not in installed list)
318
+ const installed = await getInstalledPlugins();
319
+ if (!installed[pluginKey]) {
320
+ return {
321
+ success: false,
322
+ error: `Plugin "${pluginKey}" is a built-in plugin and cannot be overwritten.`,
323
+ };
324
+ }
325
+ }
326
+ // Build the plugin if it has a build script
327
+ if ((_m = pkgJson.scripts) === null || _m === void 0 ? void 0 : _m.build) {
328
+ log.info(`Building plugin ${pluginKey}...`);
329
+ const buildDeps = await runCommand('npm', ['install', '--omit=peer'], installDir, npmEnvironment);
330
+ if (buildDeps.exitCode !== 0) {
331
+ const error = commandFailure('Dependency install', buildDeps, secrets);
332
+ log.error(new Error(error), `Plugin ${pluginKey} dependency install failed.`);
333
+ return { success: false, error };
334
+ }
335
+ const linked = await linkHostPeerDependencies(installDir, peerDependencyNames(pkgJson));
336
+ if (!linked.success) {
337
+ log.error(new Error(linked.error), `Plugin ${pluginKey} peer link failed.`);
338
+ return linked;
339
+ }
340
+ // The plugin temp dir sits under the host tree. A plugin script that
341
+ // invokes pnpm would otherwise adopt the host workspace.
342
+ await fs.writeFile(path.join(installDir, 'pnpm-workspace.yaml'), "packages:\n - '.'\n");
343
+ await removeNpmConfig(tempDir);
344
+ const build = await runCommand('npm', ['run', 'build'], installDir, {
345
+ CI: 'true',
346
+ });
347
+ if (build.exitCode !== 0) {
348
+ const error = commandFailure('Build', build, secrets);
349
+ log.error(new Error(error), `Plugin ${pluginKey} build failed.`);
350
+ return { success: false, error };
351
+ }
352
+ }
353
+ // Move to final location
354
+ await removeNpmConfig(tempDir);
355
+ await fs.mkdir(path.join(pluginsDir, namespace), { recursive: true });
356
+ await fs.rm(destDir, { recursive: true, force: true });
357
+ await fs.cp(installDir, destDir, { recursive: true });
358
+ await setInstalledPlugin(pluginKey, label, secrets.length > 0, installedBy);
359
+ if (options === null || options === void 0 ? void 0 : options.selfHeal) {
360
+ // Re-downloading an already-reviewed plugin keeps its enabled state.
361
+ log.info(`Self-healed plugin ${pluginKey} (re-downloaded from ${label}).`);
362
+ }
363
+ else {
364
+ // Installed plugins never auto-enable — an admin must explicitly
365
+ // activate them via the enable toggle (Phase B) after reviewing them.
366
+ await setPluginEnabledOverride(pluginKey, false);
367
+ log.info(`Plugin ${pluginKey} installed successfully from ${label}${installedBy ? ` by ${installedBy}` : ''}. Disabled by default — activate it explicitly to load it.`);
368
+ }
369
+ return { success: true, pluginKey };
370
+ }
371
+ catch (e) {
372
+ const rawMessage = e instanceof Error ? e.message : String(e);
373
+ const message = redactSecrets(rawMessage, secrets);
374
+ log.error(new Error(message), `Failed to install plugin from ${label}.`);
375
+ return { success: false, error: message };
376
+ }
377
+ finally {
378
+ await fs.rm(tempDir, { recursive: true, force: true }).catch(() => { });
379
+ }
380
+ };
381
+ export const uninstallPlugin = async (pluginKey, uninstalledBy) => {
382
+ const installed = await getInstalledPlugins();
383
+ if (!installed[pluginKey]) {
384
+ return {
385
+ success: false,
386
+ error: `Plugin "${pluginKey}" was not installed via the admin UI.`,
387
+ };
388
+ }
389
+ const pluginsDir = await getPluginDir();
390
+ const pluginDir = path.join(pluginsDir, pluginKey);
391
+ try {
392
+ await fs.rm(pluginDir, { recursive: true, force: true });
393
+ await removeInstalledPlugin(pluginKey);
394
+ log.info(`Plugin ${pluginKey} uninstalled${uninstalledBy ? ` by ${uninstalledBy}` : ''}.`);
395
+ return { success: true };
396
+ }
397
+ catch (e) {
398
+ const message = e instanceof Error ? e.message : String(e);
399
+ log.error(e, `Failed to uninstall plugin ${pluginKey}.`);
400
+ return { success: false, error: message };
401
+ }
402
+ };
403
+ /**
404
+ * Re-downloads admin-installed plugins whose files are missing from the
405
+ * plugins directory (e.g. after a container recreate whose plugins path was
406
+ * not a persistent volume). Credentials are not stored, so plugins installed
407
+ * from private sources cannot be re-fetched — they are reported for manual
408
+ * re-install instead. Returns pluginKey -> reason for every plugin that is
409
+ * still unavailable after the attempt.
410
+ */
411
+ export const selfHealInstalledPlugins = async () => {
412
+ var _a;
413
+ const installed = await getInstalledPlugins();
414
+ const pluginsDir = await getPluginDir();
415
+ const failures = {};
416
+ for (const [pluginKey, record] of Object.entries(installed)) {
417
+ const healthy = await fs
418
+ .access(path.join(pluginsDir, pluginKey, 'package.json'))
419
+ .then(() => true)
420
+ .catch(() => false);
421
+ if (healthy)
422
+ continue;
423
+ if (record.requiresAuth) {
424
+ log.error(`Plugin ${pluginKey} files are missing and it was installed from a private source; re-install it with credentials.`);
425
+ failures[pluginKey] =
426
+ 'Plugin files are missing. It was installed from a private source, which cannot be re-downloaded automatically — reinstall it with its credentials.';
427
+ continue;
428
+ }
429
+ const source = parseInstallSource(record.source);
430
+ if (!source) {
431
+ log.error(`Plugin ${pluginKey} files are missing and its recorded source "${record.source}" could not be parsed.`);
432
+ failures[pluginKey] =
433
+ 'Plugin files are missing and its recorded install source is no longer recognizable — reinstall it.';
434
+ continue;
435
+ }
436
+ try {
437
+ const result = await installPlugin(source, record.installedBy, {
438
+ selfHeal: true,
439
+ });
440
+ if (!result.success) {
441
+ log.error(new Error((_a = result.error) !== null && _a !== void 0 ? _a : 'unknown error'), `Self-heal failed for plugin ${pluginKey}.`);
442
+ failures[pluginKey] = `Automatic re-download failed: ${result.error}`;
443
+ }
444
+ }
445
+ catch (e) {
446
+ log.error(e, `Self-heal failed for plugin ${pluginKey}.`);
447
+ failures[pluginKey] = `Automatic re-download failed: ${e instanceof Error ? e.message : String(e)}`;
448
+ }
449
+ }
450
+ return failures;
451
+ };
452
+ export const getInstalledPluginKeys = async () => {
453
+ const installed = await getInstalledPlugins();
454
+ return Object.keys(installed);
455
+ };
@@ -26,5 +26,5 @@ declare global {
26
26
  * or verify whether the profile/account still exists. Plugin authors that need
27
27
  * stronger guarantees or the handle should perform their own lookup.
28
28
  */
29
- export declare const ensurePluginAuth: () => (req: Request, res: Response, next: NextFunction) => Promise<Response<any, Record<string, any>> | undefined>;
29
+ export declare const ensurePluginAuth: () => (req: Request, res: Response, next: NextFunction) => Promise<void>;
30
30
  export {};
@@ -18,27 +18,31 @@ import { jwtUtil } from '../jwt/index.js';
18
18
  */
19
19
  export const ensurePluginAuth = () => async (req, res, next) => {
20
20
  var _a;
21
+ // Express 5's RequestHandler type requires `void | Promise<void>` — never
22
+ // `return res...`, which types as `Promise<Response>` and fails overload
23
+ // resolution wherever this middleware is passed to router.post/get/etc.
21
24
  const authHeader = req.headers.authorization;
22
25
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
23
- return res.status(401).json({ success: false, message: 'Unauthorized' });
26
+ res.status(401).json({ success: false, message: 'Unauthorized' });
27
+ return;
24
28
  }
25
29
  const token = authHeader.slice(7);
26
30
  if (!token) {
27
- return res.status(401).json({ success: false, message: 'Unauthorized' });
31
+ res.status(401).json({ success: false, message: 'Unauthorized' });
32
+ return;
28
33
  }
29
34
  try {
30
35
  const jwt = await jwtUtil();
31
36
  const verified = await jwt.verify(token);
32
37
  const payload = verified === null || verified === void 0 ? void 0 : verified.payload;
33
38
  if (!((_a = payload === null || payload === void 0 ? void 0 : payload.identities) === null || _a === void 0 ? void 0 : _a.profile)) {
34
- return res
35
- .status(401)
36
- .json({ success: false, message: 'Invalid token' });
39
+ res.status(401).json({ success: false, message: 'Invalid token' });
40
+ return;
37
41
  }
38
42
  req.pluginProfile = { id: payload.identities.profile };
39
43
  next();
40
44
  }
41
45
  catch (_b) {
42
- return res.status(401).json({ success: false, message: 'Unauthorized' });
46
+ res.status(401).json({ success: false, message: 'Unauthorized' });
43
47
  }
44
48
  };
@@ -0,0 +1,4 @@
1
+ type PluginStateBody = Record<string, boolean>;
2
+ export declare const getPluginStateOverrides: () => Promise<PluginStateBody>;
3
+ export declare const setPluginEnabledOverride: (pluginKey: string, enabled: boolean) => Promise<import("pg").QueryResult<never>>;
4
+ export {};
@@ -0,0 +1,29 @@
1
+ import { eq } from 'drizzle-orm';
2
+ import { allpeepDb } from '../db/index.js';
3
+ import { configs } from '../db/pg/schema/documents.js';
4
+ import { nowIso } from '../db/pg/mappers.js';
5
+ // Single JSONB row keyed by plugin key -> desired enabled state. A missing
6
+ // entry means "no override"; the static `openpeeps.enabled` package.json
7
+ // gate decides. Reuses the generic `configs` table rather than a dedicated
8
+ // one — this is a small, boot-time-read key/value document, not a relation.
9
+ const PLUGIN_STATE_KEY = 'openpeeps-plugin-state';
10
+ export const getPluginStateOverrides = () => allpeepDb().then(async ({ db }) => {
11
+ var _a, _b;
12
+ const rows = await db
13
+ .select()
14
+ .from(configs)
15
+ .where(eq(configs.key, PLUGIN_STATE_KEY))
16
+ .limit(1);
17
+ return (_b = (_a = rows[0]) === null || _a === void 0 ? void 0 : _a.body) !== null && _b !== void 0 ? _b : {};
18
+ });
19
+ export const setPluginEnabledOverride = (pluginKey, enabled) => getPluginStateOverrides().then((overrides) => {
20
+ const body = Object.assign(Object.assign({}, overrides), { [pluginKey]: enabled });
21
+ const ts = nowIso();
22
+ return allpeepDb().then(({ db }) => db
23
+ .insert(configs)
24
+ .values({ key: PLUGIN_STATE_KEY, body, createdAt: ts, updatedAt: ts })
25
+ .onConflictDoUpdate({
26
+ target: configs.key,
27
+ set: { body, updatedAt: ts },
28
+ }));
29
+ });
@@ -0,0 +1,9 @@
1
+ import type { PgDb } from '../db/pg/client';
2
+ /**
3
+ * Walk outbound `reply_to` until there is no parent. A root post is itself.
4
+ */
5
+ export declare const findReplyRootId: (db: PgDb, postId: string) => Promise<string>;
6
+ /** Bump conversation ordering without changing `created_at` or `updated_at`. */
7
+ export declare const touchPostActivity: (db: PgDb, postId: string) => Promise<void>;
8
+ /** Replies and reactions on any descendant bump the original/root post. */
9
+ export declare const bumpConversationActivity: (db: PgDb, postId: string) => Promise<void>;
@@ -0,0 +1,35 @@
1
+ import { sql } from 'drizzle-orm';
2
+ /**
3
+ * Walk outbound `reply_to` until there is no parent. A root post is itself.
4
+ */
5
+ export const findReplyRootId = async (db, postId) => {
6
+ var _a, _b;
7
+ const result = (await db.execute(sql `
8
+ WITH RECURSIVE walk AS (
9
+ SELECT ${postId}::text AS node_id, 0 AS depth
10
+ UNION ALL
11
+ SELECT rt.to_id, walk.depth + 1
12
+ FROM reply_to rt
13
+ INNER JOIN walk ON rt.from_id = walk.node_id
14
+ WHERE walk.depth < 64
15
+ )
16
+ SELECT node_id
17
+ FROM walk
18
+ ORDER BY depth DESC
19
+ LIMIT 1
20
+ `));
21
+ return (_b = (_a = result.rows[0]) === null || _a === void 0 ? void 0 : _a.node_id) !== null && _b !== void 0 ? _b : postId;
22
+ };
23
+ /** Bump conversation ordering without changing `created_at` or `updated_at`. */
24
+ export const touchPostActivity = async (db, postId) => {
25
+ await db.execute(sql `
26
+ UPDATE posts
27
+ SET last_activity_at = now()
28
+ WHERE id = ${postId}::uuid
29
+ `);
30
+ };
31
+ /** Replies and reactions on any descendant bump the original/root post. */
32
+ export const bumpConversationActivity = async (db, postId) => {
33
+ const rootId = await findReplyRootId(db, postId);
34
+ await touchPostActivity(db, rootId);
35
+ };
@@ -1,17 +1,9 @@
1
1
  import type { AuthorizationData, DbPost, PostWithMeta } from '@openpeepshq/common/types';
2
- import type { PgDb } from '../db/pg/client';
3
2
  import type { Mapping } from '../db/pg/map';
4
- export declare const CONTEXT_NODE_CAP = 100;
5
3
  type ClosureDirection = 'ancestors' | 'descendents';
6
- /** Collect reply-graph ids via one recursive CTE (capped). */
7
- export declare const collectReplyClosureIds: (db: PgDb, startId: string, direction: ClosureDirection, { maxDepth, limit, newestFirst, }?: {
8
- maxDepth?: number;
9
- limit?: number;
10
- newestFirst?: boolean;
11
- }) => Promise<string[]>;
4
+ export { CONTEXT_NODE_CAP, collectReplyClosureIds } from './replyClosure';
12
5
  /** Load and hydrate posts in a reply closure, then ACL-filter + transform. */
13
6
  export declare const loadReplyContextPosts: (authData: AuthorizationData, startId: string, direction: ClosureDirection, mapping: Mapping<DbPost>, { maxDepth, limit, }?: {
14
7
  maxDepth?: number;
15
8
  limit?: number;
16
9
  }) => Promise<PostWithMeta[]>;
17
- export {};