@helyx/bot 1.1.0 → 1.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 (85) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/README.md +16 -1
  3. package/dist/auto-moderation-scanner-registry.d.ts +27 -0
  4. package/dist/auto-moderation-scanner-registry.js +172 -0
  5. package/dist/cloud-connector.js +3 -0
  6. package/dist/cloud-control-dispatcher.js +32 -0
  7. package/dist/command-path-contract.js +1 -0
  8. package/dist/control-permissions.d.ts +2 -2
  9. package/dist/control-permissions.js +4 -2
  10. package/dist/control-server.d.ts +72 -16
  11. package/dist/control-server.js +150 -250
  12. package/dist/dashboard-action-control.d.ts +25 -0
  13. package/dist/dashboard-action-control.js +73 -0
  14. package/dist/dashboard-action-routes.d.ts +9 -0
  15. package/dist/dashboard-action-routes.js +36 -0
  16. package/dist/dashboard-feature-control.d.ts +37 -0
  17. package/dist/dashboard-feature-control.js +206 -0
  18. package/dist/dashboard-module-projection.d.ts +9 -0
  19. package/dist/dashboard-module-projection.js +15 -0
  20. package/dist/dashboard-preview-import-routes.d.ts +6 -0
  21. package/dist/dashboard-preview-import-routes.js +121 -0
  22. package/dist/discord-analytics.d.ts +3 -0
  23. package/dist/discord-analytics.js +49 -5
  24. package/dist/discord-auto-moderation-service.d.ts +21 -0
  25. package/dist/discord-auto-moderation-service.js +425 -0
  26. package/dist/discord-guild-health.d.ts +2 -2
  27. package/dist/discord-member-enforcement-service.d.ts +26 -0
  28. package/dist/discord-member-enforcement-service.js +590 -0
  29. package/dist/discord-message-enforcement-service.d.ts +9 -0
  30. package/dist/discord-message-enforcement-service.js +102 -0
  31. package/dist/discord-violation-thread-service.d.ts +33 -0
  32. package/dist/discord-violation-thread-service.js +789 -0
  33. package/dist/ecko-evidence-receiver.d.ts +32 -0
  34. package/dist/ecko-evidence-receiver.js +173 -0
  35. package/dist/ecko-transport-auth.d.ts +19 -0
  36. package/dist/ecko-transport-auth.js +80 -0
  37. package/dist/ecko-transport-routes.d.ts +19 -0
  38. package/dist/ecko-transport-routes.js +130 -0
  39. package/dist/embedded-auto-moderation-pool.d.ts +46 -0
  40. package/dist/embedded-auto-moderation-pool.js +324 -0
  41. package/dist/embedded-auto-moderation-scanner.d.ts +34 -0
  42. package/dist/embedded-auto-moderation-scanner.js +263 -0
  43. package/dist/embedded-auto-moderation-worker-runtime.d.ts +37 -0
  44. package/dist/embedded-auto-moderation-worker-runtime.js +37 -0
  45. package/dist/embedded-auto-moderation-worker.d.ts +2 -0
  46. package/dist/embedded-auto-moderation-worker.js +13 -0
  47. package/dist/events.d.ts +5 -1
  48. package/dist/events.js +243 -4
  49. package/dist/guilds.d.ts +2 -2
  50. package/dist/guilds.js +14 -8
  51. package/dist/hosted-server-moderation.d.ts +16 -5
  52. package/dist/hosted-server-moderation.js +32 -4
  53. package/dist/index.d.ts +1 -1
  54. package/dist/index.js +84 -14
  55. package/dist/moderation-action-registry.d.ts +11 -0
  56. package/dist/moderation-action-registry.js +375 -0
  57. package/dist/moderation-case-disassociation.d.ts +13 -0
  58. package/dist/moderation-case-disassociation.js +83 -0
  59. package/dist/moderation-platform-services.d.ts +27 -0
  60. package/dist/moderation-platform-services.js +50 -0
  61. package/dist/modules.d.ts +6 -0
  62. package/dist/modules.js +65 -3
  63. package/dist/privileged-message-metadata-cache.d.ts +35 -0
  64. package/dist/privileged-message-metadata-cache.js +70 -0
  65. package/dist/scheduled-task-runner.js +24 -1
  66. package/dist/shard-contracts.d.ts +151 -1
  67. package/dist/shard-contracts.js +142 -1
  68. package/dist/shard-coordinator.d.ts +1 -1
  69. package/dist/shard-ecko-scanner-registry.d.ts +38 -0
  70. package/dist/shard-ecko-scanner-registry.js +96 -0
  71. package/dist/shard-router.d.ts +23 -0
  72. package/dist/shard-router.js +69 -5
  73. package/dist/shard-supervisor.d.ts +11 -0
  74. package/dist/shard-supervisor.js +67 -4
  75. package/dist/shard-worker.d.ts +15 -1
  76. package/dist/shard-worker.js +95 -17
  77. package/dist/transient-violation-evidence.d.ts +39 -0
  78. package/dist/transient-violation-evidence.js +132 -0
  79. package/documentation/README.md +2 -0
  80. package/documentation/examples/.env.example +12 -0
  81. package/documentation/guides/self-hosting.md +17 -1
  82. package/documentation/modules/auto-moderation.md +51 -0
  83. package/documentation/modules/moderation.md +42 -0
  84. package/documentation/reference/environment.md +11 -0
  85. package/package.json +17 -5
@@ -0,0 +1,83 @@
1
+ import { AUTOMOD_CASE_LINK_CONTRACT_VERSION, AUTOMOD_CASE_LINK_PROVIDER_ID, HELYX_SERVICE_NAMES, } from "@helyx/sdk";
2
+ const AUTOMOD_MODULE_ID = "helyx.automod";
3
+ /** Adds Auto Moderation unlinking after the authoritative case transition. */
4
+ export function decorateModerationCaseDisassociation(input) {
5
+ const provider = caseLinkProvider(input.modules);
6
+ if (!provider)
7
+ return input.service;
8
+ const service = input.service;
9
+ return {
10
+ createPendingCase: (request) => service.createPendingCase(request),
11
+ createConfirmedAutoModerationOffenceCase: (request) => service.createConfirmedAutoModerationOffenceCase(request),
12
+ createAdditionalPendingAttempt: (request) => service.createAdditionalPendingAttempt(request),
13
+ createCorrectionCase: (request) => service.createCorrectionCase(request),
14
+ settleActionAttempt: (request) => service.settleActionAttempt(request),
15
+ recordObservedAction: (request) => service.recordObservedAction(request),
16
+ listReconciliationCandidates: (request) => service.listReconciliationCandidates(request),
17
+ async disassociateCase(request) {
18
+ const result = await service.disassociateCase(request);
19
+ if (result.outcome !== "disassociated" &&
20
+ result.outcome !== "already_disassociated")
21
+ return result;
22
+ // Deliberately pass no former subject identity across the module boundary.
23
+ await provider.disassociateCase({ services: input.services }, {
24
+ guildId: request.guildId,
25
+ moderationCaseId: result.caseId,
26
+ occurredAt: request.occurredAt,
27
+ });
28
+ if (input.services.has(HELYX_SERVICE_NAMES.memberRoleGrants)) {
29
+ const grants = input.services.get(HELYX_SERVICE_NAMES.memberRoleGrants);
30
+ let cursor;
31
+ do {
32
+ const released = await grants.releaseOwned({
33
+ sourceModuleId: "helyx.moderation",
34
+ selector: {
35
+ kind: "scope",
36
+ guildId: request.guildId,
37
+ sourceScopeId: result.caseId,
38
+ },
39
+ batchKey: `${request.operationKey}:release-access`,
40
+ occurredAt: request.occurredAt,
41
+ reason: "Moderation case disassociated",
42
+ limit: 100,
43
+ ...(cursor ? { cursor } : {}),
44
+ });
45
+ cursor = released.nextCursor;
46
+ } while (cursor);
47
+ }
48
+ return result;
49
+ },
50
+ executeRetention: (request) => service.executeRetention(request),
51
+ };
52
+ }
53
+ function caseLinkProvider(modules) {
54
+ const providers = modules.flatMap((module) => module.autoModerationCaseLinkProvider
55
+ ? [
56
+ {
57
+ moduleId: module.manifest.id,
58
+ provider: module.autoModerationCaseLinkProvider,
59
+ },
60
+ ]
61
+ : []);
62
+ if (providers.length > 1)
63
+ throw new Error("Auto Moderation case-link ownership is ambiguous");
64
+ const registered = providers[0];
65
+ if (!registered)
66
+ return null;
67
+ if (registered.moduleId !== AUTOMOD_MODULE_ID ||
68
+ registered.provider.providerId !== AUTOMOD_CASE_LINK_PROVIDER_ID ||
69
+ registered.provider.contractVersion !== AUTOMOD_CASE_LINK_CONTRACT_VERSION)
70
+ throw new Error("Auto Moderation case-link registration is invalid");
71
+ return registered.provider;
72
+ }
73
+ export function installModerationCaseDisassociation(input) {
74
+ const current = input.services.get(HELYX_SERVICE_NAMES.atomicModerationCases);
75
+ if (!current)
76
+ return;
77
+ input.services.set(HELYX_SERVICE_NAMES.atomicModerationCases, decorateModerationCaseDisassociation({
78
+ modules: input.modules,
79
+ services: input.serviceAccess,
80
+ service: current,
81
+ }));
82
+ }
83
+ //# sourceMappingURL=moderation-case-disassociation.js.map
@@ -0,0 +1,27 @@
1
+ import type { ModuleDefinition, ServiceAccess } from "@helyx/sdk";
2
+ import type { Client } from "discord.js";
3
+ import { BotAutoModerationScannerRegistry } from "./auto-moderation-scanner-registry.js";
4
+ import type { EmbeddedAutoModerationScanner } from "./embedded-auto-moderation-scanner.js";
5
+ import { TransientViolationEvidenceStore } from "./transient-violation-evidence.js";
6
+ export interface ModerationPlatformServiceHandle {
7
+ evidenceStore: TransientViolationEvidenceStore;
8
+ scannerRegistry: BotAutoModerationScannerRegistry;
9
+ embeddedScanner?: EmbeddedAutoModerationScanner;
10
+ }
11
+ /** Installs bounded moderation adapters; no module or Ecko lifecycle starts here. */
12
+ export declare function installModerationPlatformServices(input: {
13
+ services: Map<string, unknown>;
14
+ serviceAccess: ServiceAccess;
15
+ client: Client;
16
+ modules: readonly ModuleDefinition[];
17
+ runtimeProfile: "hosted" | "self-hosted";
18
+ deploymentEnvironment?: string;
19
+ embedded?: {
20
+ workers: number;
21
+ maximumItems: number;
22
+ maximumBytes: number;
23
+ maximumItemsPerGuild: number;
24
+ refreshIntervalMs: number;
25
+ };
26
+ }): Promise<ModerationPlatformServiceHandle>;
27
+ //# sourceMappingURL=moderation-platform-services.d.ts.map
@@ -0,0 +1,50 @@
1
+ import { HELYX_SERVICE_NAMES } from "@helyx/sdk";
2
+ import { BotAutoModerationScannerRegistry } from "./auto-moderation-scanner-registry.js";
3
+ import { DiscordAutoModerationAdapter } from "./discord-auto-moderation-service.js";
4
+ import { DiscordMessageEnforcementAdapter } from "./discord-message-enforcement-service.js";
5
+ import { DiscordViolationEvidenceDeliveryAdapter, DiscordViolationThreadAdapter, } from "./discord-violation-thread-service.js";
6
+ import { BotModerationActionRegistry } from "./moderation-action-registry.js";
7
+ import { TransientViolationEvidenceStore } from "./transient-violation-evidence.js";
8
+ import { installModerationCaseDisassociation } from "./moderation-case-disassociation.js";
9
+ /** Installs bounded moderation adapters; no module or Ecko lifecycle starts here. */
10
+ export async function installModerationPlatformServices(input) {
11
+ const evidenceStore = new TransientViolationEvidenceStore();
12
+ installModerationCaseDisassociation({
13
+ modules: input.modules,
14
+ services: input.services,
15
+ serviceAccess: input.serviceAccess,
16
+ });
17
+ const scannerRegistry = new BotAutoModerationScannerRegistry(input.modules, input.serviceAccess, input.runtimeProfile, evidenceStore, input.deploymentEnvironment);
18
+ const evidenceDelivery = new DiscordViolationEvidenceDeliveryAdapter(input.client, evidenceStore);
19
+ input.services.set(HELYX_SERVICE_NAMES.discordAutoModeration, new DiscordAutoModerationAdapter(input.client));
20
+ input.services.set(HELYX_SERVICE_NAMES.messageEnforcement, new DiscordMessageEnforcementAdapter(input.client));
21
+ input.services.set(HELYX_SERVICE_NAMES.violationThreads, new DiscordViolationThreadAdapter(input.client));
22
+ input.services.set(HELYX_SERVICE_NAMES.moderationActions, new BotModerationActionRegistry(input.modules, input.serviceAccess, evidenceDelivery));
23
+ input.services.set(HELYX_SERVICE_NAMES.automodScannerProvider, scannerRegistry);
24
+ let embeddedScanner;
25
+ if (input.runtimeProfile === "self-hosted" &&
26
+ input.modules.some((module) => module.autoModerationScannerProvider)) {
27
+ // The engine is an optional module peer, not a core startup dependency.
28
+ const { EmbeddedAutoModerationScanner } = await import("./embedded-auto-moderation-scanner.js");
29
+ embeddedScanner = new EmbeddedAutoModerationScanner({
30
+ registry: scannerRegistry,
31
+ evidenceStore,
32
+ environment: input.deploymentEnvironment ?? "self-hosted",
33
+ poolLimits: {
34
+ workers: input.embedded?.workers ?? 1,
35
+ maximumItems: input.embedded?.maximumItems ?? 5_000,
36
+ maximumBytes: input.embedded?.maximumBytes ?? 64 * 1_024 * 1_024,
37
+ maximumItemsPerGuild: input.embedded?.maximumItemsPerGuild ?? 100,
38
+ },
39
+ refreshIntervalMs: input.embedded?.refreshIntervalMs ?? 300_000,
40
+ });
41
+ }
42
+ if (embeddedScanner)
43
+ input.services.set(HELYX_SERVICE_NAMES.automodScannerObservations, embeddedScanner);
44
+ return {
45
+ evidenceStore,
46
+ scannerRegistry,
47
+ ...(embeddedScanner ? { embeddedScanner } : {}),
48
+ };
49
+ }
50
+ //# sourceMappingURL=moderation-platform-services.js.map
package/dist/modules.d.ts CHANGED
@@ -12,6 +12,10 @@ export interface ConfiguredModulePackage extends LoadedDefinition {
12
12
  }
13
13
  export declare const secureRandomSelectionWorkerKeyName = "HELYX_INTERNAL_SECURE_RANDOM_SELECTION_KEY";
14
14
  interface PlatformServiceEnvironment extends Pick<BotEnvironment, "HELYX_DATA_ENCRYPTION_KEY"> {
15
+ HELYX_RUNTIME_PROFILE?: BotEnvironment["HELYX_RUNTIME_PROFILE"];
16
+ HELYX_MESSAGE_CONTENT_ENABLED?: boolean;
17
+ HELYX_GUILD_MEMBERS_ENABLED?: boolean;
18
+ HELYX_ECKO_TRANSPORT_SECRET?: string | undefined;
15
19
  DISCORD_CLIENT_ID?: string;
16
20
  HELYX_DASHBOARD_PUBLIC_URL?: string;
17
21
  HELYX_INTERNAL_SECURE_RANDOM_SELECTION_KEY?: string;
@@ -22,6 +26,8 @@ export declare function platformServiceOptions(environment: PlatformServiceEnvir
22
26
  secureRandomSelectionKey?: Uint8Array;
23
27
  inviteFingerprintKey?: Uint8Array;
24
28
  dashboardBaseUrl?: string;
29
+ runtimeProfile: "hosted" | "self-hosted";
30
+ availableDiscordCapabilities: readonly ("guild-members" | "message-content")[];
25
31
  };
26
32
  export declare function deriveInviteFingerprintKey(selectionKey: Uint8Array): Uint8Array;
27
33
  export declare function loadConfiguredModules(specifiers: readonly string[], importer?: ModuleImporter): Promise<ModuleDefinition[]>;
package/dist/modules.js CHANGED
@@ -31,12 +31,28 @@ export function platformServiceOptions(environment, modules) {
31
31
  const urls = environment.HELYX_DASHBOARD_PUBLIC_URL
32
32
  ? { dashboardBaseUrl: environment.HELYX_DASHBOARD_PUBLIC_URL }
33
33
  : {};
34
+ const runtimeProfile = environment.HELYX_RUNTIME_PROFILE ?? "hosted";
35
+ const featureAccess = {
36
+ runtimeProfile,
37
+ availableDiscordCapabilities: [
38
+ ...(environment.HELYX_GUILD_MEMBERS_ENABLED
39
+ ? ["guild-members"]
40
+ : []),
41
+ ...((runtimeProfile === "hosted" &&
42
+ environment.HELYX_ECKO_TRANSPORT_SECRET !== undefined) ||
43
+ (runtimeProfile === "self-hosted" &&
44
+ environment.HELYX_MESSAGE_CONTENT_ENABLED)
45
+ ? ["message-content"]
46
+ : []),
47
+ ],
48
+ };
34
49
  const internalSelectionKey = environment.HELYX_INTERNAL_SECURE_RANDOM_SELECTION_KEY;
35
50
  if (internalSelectionKey) {
36
51
  const selectionKey = decodeSecureRandomSelectionKey(internalSelectionKey, secureRandomSelectionWorkerKeyName);
37
52
  return {
38
53
  ...application,
39
54
  ...urls,
55
+ ...featureAccess,
40
56
  secureRandomSelectionKey: selectionKey,
41
57
  inviteFingerprintKey: deriveInviteFingerprintKey(selectionKey),
42
58
  };
@@ -48,12 +64,13 @@ export function platformServiceOptions(environment, modules) {
48
64
  if (keyRequired) {
49
65
  throw new Error("HELYX_DATA_ENCRYPTION_KEY is required when Giveaways or Invite Tracking is loaded");
50
66
  }
51
- return { ...application, ...urls };
67
+ return { ...application, ...urls, ...featureAccess };
52
68
  }
53
69
  const selectionKey = deriveSecureRandomSelectionKey(encodedKey);
54
70
  return {
55
71
  ...application,
56
72
  ...urls,
73
+ ...featureAccess,
57
74
  secureRandomSelectionKey: selectionKey,
58
75
  inviteFingerprintKey: deriveInviteFingerprintKey(selectionKey),
59
76
  };
@@ -162,6 +179,11 @@ export function validateContributionParity(definition) {
162
179
  }
163
180
  const executableEvents = [
164
181
  ...(definition.events?.privilegedMessageCreate ?? []),
182
+ ...(definition.events?.privilegedMessageUpdate ?? []),
183
+ ...(definition.events?.discordAutoModerationRuleCreate ?? []),
184
+ ...(definition.events?.discordAutoModerationRuleUpdate ?? []),
185
+ ...(definition.events?.discordAutoModerationRuleDelete ?? []),
186
+ ...(definition.events?.discordAutoModerationActionExecution ?? []),
165
187
  ...(definition.events?.guildMessageCreate ?? []),
166
188
  ...(definition.events?.guildVoiceSession ?? []),
167
189
  ...(definition.events?.messageReactionAdd ?? []),
@@ -180,6 +202,20 @@ export function validateContributionParity(definition) {
180
202
  ...(definition.events?.guildEmojiDelete ?? []),
181
203
  ...(definition.events?.guildEmojiUpdate ?? []),
182
204
  ].map(({ type }) => type);
205
+ const manifestFeatureIds = new Set(definition.manifest.manifestVersion === "0.5"
206
+ ? definition.manifest.features.map(({ id }) => id)
207
+ : []);
208
+ for (const contribution of [
209
+ ...(definition.events?.privilegedMessageCreate ?? []),
210
+ ...(definition.events?.privilegedMessageUpdate ?? []),
211
+ ]) {
212
+ if (contribution.featureId &&
213
+ !manifestFeatureIds.has(contribution.featureId))
214
+ throw new Error(`Module ${definition.manifest.id} message event binds undeclared feature ${contribution.featureId}`);
215
+ if (definition.manifest.id === "helyx.automod" &&
216
+ contribution.featureId !== "automod.enhanced-scanning")
217
+ throw new Error("Auto Moderation privileged message events require the Enhanced feature binding");
218
+ }
183
219
  const executableLogs = (definition.logging?.events ?? []).map(({ id }) => id);
184
220
  const executableSchedulableActions = [
185
221
  ...new Set((definition.schedulableActions ?? []).map(({ id }) => id)),
@@ -192,9 +228,16 @@ export function validateContributionParity(definition) {
192
228
  assertSameContributionIds(definition.manifest.contributions.schedulableActions ?? [], executableSchedulableActions, "schedulable actions");
193
229
  assertSameContributionIds(definition.manifest.dashboard?.actions?.map(({ id }) => id) ?? [], executableDashboardActions, "dashboard actions");
194
230
  assertSameContributionIds(definition.manifest.dashboard?.resources?.map(({ id }) => id) ?? [], executableManagedResources, "dashboard resources");
195
- if (definition.manifest.manifestVersion === "0.4") {
231
+ if (definition.manifest.manifestVersion === "0.4" ||
232
+ definition.manifest.manifestVersion === "0.5") {
196
233
  assertCommandPathContract(definition);
197
234
  }
235
+ if (definition.manifest.manifestVersion === "0.5") {
236
+ assertSameContributionIds(definition.manifest.permissionOperations.map(({ id }) => id), (definition.permissionOperations ?? []).map(({ id }) => id), "permission operations");
237
+ }
238
+ else if ((definition.permissionOperations?.length ?? 0) > 0) {
239
+ throw new Error("Module permission operations require manifest version 0.5 or later");
240
+ }
198
241
  validatePrivacyParity(definition);
199
242
  }
200
243
  function validatePrivacyParity(definition) {
@@ -219,6 +262,7 @@ function validatePrivacyParity(definition) {
219
262
  const privacyFields = [
220
263
  collectionDeclaration.createdAtField,
221
264
  ...collectionDeclaration.subjectFields.map(({ field }) => field),
265
+ ...(collectionDeclaration.subjectRelationships ?? []).map(({ localField }) => localField),
222
266
  ...(collectionDeclaration.contentFields ?? []).map(({ field }) => field),
223
267
  ];
224
268
  for (const field of privacyFields) {
@@ -226,16 +270,34 @@ function validatePrivacyParity(definition) {
226
270
  throw new Error(`Module privacy field is not declared in record collection ${collectionDeclaration.name}: ${field}`);
227
271
  }
228
272
  }
273
+ for (const relationship of collectionDeclaration.subjectRelationships ??
274
+ []) {
275
+ const target = definition.records?.[relationship.targetCollection];
276
+ const localField = collection.fields[relationship.localField];
277
+ const targetField = target?.fields[relationship.targetField];
278
+ if (target === undefined || targetField === undefined) {
279
+ throw new Error(`Module privacy relationship target is not declared: ${relationship.targetCollection}.${relationship.targetField}`);
280
+ }
281
+ if (localField?.type !== targetField.type) {
282
+ throw new Error(`Module privacy relationship fields have incompatible types: ${collectionDeclaration.name}.${relationship.localField}`);
283
+ }
284
+ }
229
285
  }
230
286
  const subjectFieldsByCollection = new Map(definition.manifest.privacy.collections.map((collection) => [
231
287
  collection.name,
232
288
  new Set(collection.subjectFields.map(({ field }) => field)),
233
289
  ]));
290
+ const relationshipFieldsByCollection = new Map(definition.manifest.privacy.collections.map((collection) => [
291
+ collection.name,
292
+ new Set((collection.subjectRelationships ?? []).map(({ localField }) => localField)),
293
+ ]));
234
294
  for (const [collectionName, collection] of Object.entries(definition.records ?? {})) {
235
295
  const declaredSubjectFields = subjectFieldsByCollection.get(collectionName);
296
+ const relationshipFields = relationshipFieldsByCollection.get(collectionName);
236
297
  for (const field of Object.keys(collection.fields)) {
237
298
  if (isDiscordIdentityRecordField(field) &&
238
- !declaredSubjectFields?.has(field)) {
299
+ !declaredSubjectFields?.has(field) &&
300
+ !relationshipFields?.has(field)) {
239
301
  throw new Error(`Module record field containing a Discord identity is not declared for privacy access: ${collectionName}.${field}`);
240
302
  }
241
303
  }
@@ -0,0 +1,35 @@
1
+ import type { PrivilegedMessageSourceContext } from "@helyx/sdk";
2
+ /**
3
+ * Process-local, content-free metadata used only to resolve partial message edits.
4
+ * Map insertion order provides deterministic least-recently-used eviction.
5
+ */
6
+ export declare class PrivilegedMessageMetadataCache {
7
+ #private;
8
+ private readonly maximumEntries;
9
+ private readonly ttlMs;
10
+ private readonly now;
11
+ constructor(maximumEntries?: number, ttlMs?: number, now?: () => number);
12
+ remember(input: {
13
+ guildId: string;
14
+ channelId: string;
15
+ messageId: string;
16
+ source: Extract<PrivilegedMessageSourceContext, {
17
+ resolved: true;
18
+ }>;
19
+ }): void;
20
+ resolve(input: {
21
+ guildId: string;
22
+ channelId: string;
23
+ messageId: string;
24
+ }): Extract<PrivilegedMessageSourceContext, {
25
+ resolved: true;
26
+ }> | null;
27
+ delete(input: {
28
+ guildId: string;
29
+ channelId: string;
30
+ messageId: string;
31
+ }): void;
32
+ clear(): void;
33
+ size(): number;
34
+ }
35
+ //# sourceMappingURL=privileged-message-metadata-cache.d.ts.map
@@ -0,0 +1,70 @@
1
+ const DEFAULT_MAX_ENTRIES = 10_000;
2
+ const DEFAULT_TTL_MS = 10 * 60 * 1_000;
3
+ /**
4
+ * Process-local, content-free metadata used only to resolve partial message edits.
5
+ * Map insertion order provides deterministic least-recently-used eviction.
6
+ */
7
+ export class PrivilegedMessageMetadataCache {
8
+ maximumEntries;
9
+ ttlMs;
10
+ now;
11
+ #entries = new Map();
12
+ constructor(maximumEntries = DEFAULT_MAX_ENTRIES, ttlMs = DEFAULT_TTL_MS, now = Date.now) {
13
+ this.maximumEntries = maximumEntries;
14
+ this.ttlMs = ttlMs;
15
+ this.now = now;
16
+ if (!Number.isInteger(maximumEntries) || maximumEntries < 1)
17
+ throw new Error("Privileged message cache size is invalid");
18
+ if (!Number.isInteger(ttlMs) || ttlMs < 1)
19
+ throw new Error("Privileged message cache TTL is invalid");
20
+ }
21
+ remember(input) {
22
+ const key = cacheKey(input);
23
+ this.#entries.delete(key);
24
+ this.#entries.set(key, {
25
+ expiresAt: this.now() + this.ttlMs,
26
+ source: input.source,
27
+ });
28
+ this.#evictExpiredAndOverflow();
29
+ }
30
+ resolve(input) {
31
+ const key = cacheKey(input);
32
+ const entry = this.#entries.get(key);
33
+ if (!entry)
34
+ return null;
35
+ if (entry.expiresAt <= this.now()) {
36
+ this.#entries.delete(key);
37
+ return null;
38
+ }
39
+ this.#entries.delete(key);
40
+ this.#entries.set(key, entry);
41
+ return entry.source;
42
+ }
43
+ delete(input) {
44
+ this.#entries.delete(cacheKey(input));
45
+ }
46
+ clear() {
47
+ this.#entries.clear();
48
+ }
49
+ size() {
50
+ return this.#entries.size;
51
+ }
52
+ #evictExpiredAndOverflow() {
53
+ const now = this.now();
54
+ for (const [key, entry] of this.#entries) {
55
+ if (entry.expiresAt > now)
56
+ continue;
57
+ this.#entries.delete(key);
58
+ }
59
+ while (this.#entries.size > this.maximumEntries) {
60
+ const oldest = this.#entries.keys().next().value;
61
+ if (!oldest)
62
+ break;
63
+ this.#entries.delete(oldest);
64
+ }
65
+ }
66
+ }
67
+ function cacheKey(input) {
68
+ return `${input.guildId}:${input.channelId}:${input.messageId}`;
69
+ }
70
+ //# sourceMappingURL=privileged-message-metadata-cache.js.map
@@ -1,5 +1,5 @@
1
1
  import { CORE_RECORD_RETENTION_TASK, MODULE_ACTIVATION_RECOVERY_TASK, ScheduledTaskRepository, } from "@helyx/database";
2
- import { getModuleScheduledTaskContribution, HELYX_SERVICE_NAMES, } from "@helyx/sdk";
2
+ import { getModuleScheduledTaskContribution, HELYX_SERVICE_NAMES, MODERATION_CASE_RETENTION_TASK, } from "@helyx/sdk";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { canAccessModule } from "./premium-access.js";
5
5
  const DEFAULT_POLL_INTERVAL_MS = 1_000;
@@ -296,6 +296,7 @@ export function createScheduledTaskRunner(input) {
296
296
  taskVersion: contribution.version,
297
297
  delivery: contribution.delivery,
298
298
  }))),
299
+ MODERATION_CASE_RETENTION_TASK,
299
300
  ],
300
301
  ...(input.workerId === undefined ? {} : { workerId: input.workerId }),
301
302
  });
@@ -310,6 +311,28 @@ export function schedulerOperationalHealth(health) {
310
311
  export function createLocalScheduledTaskRoute(input) {
311
312
  const modules = new Map(input.modules.map((module) => [module.manifest.id, module]));
312
313
  return async (task, signal) => {
314
+ if (task.moduleId === MODERATION_CASE_RETENTION_TASK.moduleId &&
315
+ task.taskKind === MODERATION_CASE_RETENTION_TASK.taskKind &&
316
+ task.taskVersion === MODERATION_CASE_RETENTION_TASK.taskVersion &&
317
+ task.delivery === MODERATION_CASE_RETENTION_TASK.delivery) {
318
+ const { guildId, caseId } = task.payload;
319
+ if (Object.keys(task.payload).length !== 2 ||
320
+ typeof guildId !== "string" ||
321
+ !/^\d{17,20}$/u.test(guildId) ||
322
+ typeof caseId !== "string" ||
323
+ !/^[0-9a-f]{8}-[0-9a-f-]{27}$/iu.test(caseId))
324
+ return { outcome: "requires_review", safeCode: "payload_invalid" };
325
+ const result = await input.services
326
+ .get(HELYX_SERVICE_NAMES.atomicModerationCases)
327
+ .executeRetention({ guildId, caseId, occurredAt: new Date() });
328
+ return result.outcome === "deferred"
329
+ ? {
330
+ outcome: "deferred",
331
+ delayMs: Math.max(100, Math.min(86_400_000, result.deferredUntil.getTime() - Date.now())),
332
+ safeCode: `retention_${result.code}`,
333
+ }
334
+ : { outcome: "completed" };
335
+ }
313
336
  if (task.moduleId === CORE_RECORD_RETENTION_TASK.moduleId &&
314
337
  task.taskKind === CORE_RECORD_RETENTION_TASK.taskKind &&
315
338
  task.taskVersion === CORE_RECORD_RETENTION_TASK.taskVersion &&