@helyx/bot 0.3.0 → 0.4.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.
@@ -1,5 +1,5 @@
1
1
  import type { CommandContribution, MessageResponse, ModalDefinition, ModuleDefinition, ServiceAccess } from "@helyx/sdk";
2
- import { ModalBuilder, type Client, type InteractionReplyOptions, type InteractionUpdateOptions } from "discord.js";
2
+ import { ModalBuilder, type ChatInputCommandInteraction, type Client, type InteractionReplyOptions, type InteractionUpdateOptions } from "discord.js";
3
3
  export interface InteractionLogger {
4
4
  info(fields: Record<string, unknown>, message: string): void;
5
5
  warn(fields: Record<string, unknown>, message: string): void;
@@ -8,8 +8,14 @@ export interface InteractionLogger {
8
8
  export interface CommandRegistration {
9
9
  internalGuildId?: string;
10
10
  prepare?(client: Client<true>): Promise<void>;
11
+ synchronise?: boolean;
12
+ selfAuthorizingGuildModuleIds?: ReadonlySet<string>;
11
13
  }
12
14
  export declare function installInteractions(client: Client, modules: readonly ModuleDefinition[], registration: CommandRegistration, logger: InteractionLogger, services: ServiceAccess): Promise<void>;
15
+ export declare function buildApplicationCommandDefinitions(modules: readonly ModuleDefinition[], internalGuildId?: string): {
16
+ global: ReturnType<typeof toCommandDefinition>[];
17
+ guild: ReturnType<typeof toCommandDefinition>[];
18
+ };
13
19
  export declare function resolveCommandExecutor(command: CommandContribution, subcommandName: string | null): CommandContribution["execute"];
14
20
  export declare function toCommandDefinition(registered: {
15
21
  contribution: CommandContribution;
@@ -20,6 +26,7 @@ export declare function sendToChannel(client: Client, channelId: string, respons
20
26
  }>;
21
27
  export declare function deleteChannelMessage(client: Client, channelId: string, messageId: string): Promise<void>;
22
28
  export declare function editChannelMessage(client: Client, channelId: string, messageId: string, response: MessageResponse): Promise<void>;
29
+ export declare function authorizeCommand(interaction: ChatInputCommandInteraction, moduleId: string, commandId: string, rateLimit: CommandContribution["rateLimit"], services: ServiceAccess, selfAuthorizingGuildCommand: boolean): Promise<boolean>;
23
30
  export declare function normalizeDiscordPermission(permission: string): string;
24
31
  export declare function toReplyOptions(response: MessageResponse): InteractionReplyOptions;
25
32
  export declare function toUpdateOptions(response: MessageResponse): InteractionUpdateOptions;
@@ -42,6 +42,10 @@ export function installInteractions(client, modules, registration, logger, servi
42
42
  });
43
43
  async function registerCommands() {
44
44
  await registration.prepare?.(readyClient);
45
+ if (registration.synchronise === false) {
46
+ logger.info({ event: "commands.registration_delegated" }, "Application command registration is owned by the supervisor");
47
+ return;
48
+ }
45
49
  const globalDefinitions = globalCommands.map(toCommandDefinition);
46
50
  await readyClient.application.commands.set(globalDefinitions);
47
51
  if (registration.internalGuildId) {
@@ -94,7 +98,8 @@ export function installInteractions(client, modules, registration, logger, servi
94
98
  const commandId = subcommandName
95
99
  ? `${command.name}.${subcommandName}`
96
100
  : command.name;
97
- if (await authorizeCommand(interaction, moduleId, commandId, subcommand?.rateLimit ?? command.rateLimit, services)) {
101
+ if (await authorizeCommand(interaction, moduleId, commandId, subcommand?.rateLimit ?? command.rateLimit, services, registration.selfAuthorizingGuildModuleIds?.has(moduleId) ??
102
+ false)) {
98
103
  const context = createCommandContext(interaction, services);
99
104
  await execute(context);
100
105
  }
@@ -143,6 +148,21 @@ export function installInteractions(client, modules, registration, logger, servi
143
148
  }
144
149
  return registrationReady;
145
150
  }
151
+ export function buildApplicationCommandDefinitions(modules, internalGuildId) {
152
+ const commands = uniqueMap(modules.flatMap((module) => (module.interactions?.commands ?? []).map((contribution) => ({
153
+ moduleId: module.manifest.id,
154
+ contribution,
155
+ }))), ({ contribution }) => contribution.name, "command name");
156
+ const global = [...commands.values()]
157
+ .filter(({ contribution }) => contribution.registration === "global")
158
+ .map(toCommandDefinition);
159
+ const guild = [...commands.values()]
160
+ .filter(({ contribution }) => contribution.registration === "guild")
161
+ .map(toCommandDefinition);
162
+ if (guild.length > 0 && !internalGuildId)
163
+ throw new Error("DISCORD_INTERNAL_GUILD_ID is required when guild commands are loaded");
164
+ return { global, guild };
165
+ }
146
166
  export function resolveCommandExecutor(command, subcommandName) {
147
167
  if (command.subcommands?.length) {
148
168
  if (!subcommandName)
@@ -249,6 +269,8 @@ function createContext(interaction, services) {
249
269
  userRoleIds: interaction.member instanceof GuildMember
250
270
  ? [...interaction.member.roles.cache.keys()]
251
271
  : (interaction.member?.roles ?? []),
272
+ isAdministrator: interaction.memberPermissions?.has(PermissionFlagsBits.Administrator) ??
273
+ false,
252
274
  ...(interaction.guildId ? { serverId: interaction.guildId } : {}),
253
275
  ...(interaction.channelId ? { channelId: interaction.channelId } : {}),
254
276
  ...(interaction.isButton() ? { messageId: interaction.message.id } : {}),
@@ -309,6 +331,8 @@ function createModalContext(interaction, services) {
309
331
  userRoleIds: interaction.member instanceof GuildMember
310
332
  ? [...interaction.member.roles.cache.keys()]
311
333
  : (interaction.member?.roles ?? []),
334
+ isAdministrator: interaction.memberPermissions?.has(PermissionFlagsBits.Administrator) ??
335
+ false,
312
336
  ...(interaction.guildId ? { serverId: interaction.guildId } : {}),
313
337
  ...(interaction.channelId ? { channelId: interaction.channelId } : {}),
314
338
  services,
@@ -407,31 +431,33 @@ async function replyEphemeralText(interaction, content) {
407
431
  }
408
432
  await interaction.reply({ content, flags: MessageFlags.Ephemeral });
409
433
  }
410
- async function authorizeCommand(interaction, moduleId, commandId, rateLimit, services) {
434
+ export async function authorizeCommand(interaction, moduleId, commandId, rateLimit, services, selfAuthorizingGuildCommand) {
411
435
  if (!interaction.guildId)
412
436
  return true;
413
- if (!(await authorizeComponent(interaction, moduleId, services)))
414
- return false;
415
- const permissions = services.get(HELYX_SERVICE_NAMES.permissions);
416
- const policy = await permissions.getEffectivePolicy(interaction.guildId, moduleId, commandId);
417
- const actor = {
418
- userId: interaction.user.id,
419
- roleIds: interaction.member instanceof GuildMember
420
- ? [...interaction.member.roles.cache.keys()]
421
- : (interaction.member?.roles ?? []),
422
- permissions: interaction.memberPermissions
423
- ?.toArray()
424
- .map(normalizeDiscordPermission) ?? [],
425
- isServerOwner: interaction.guild?.ownerId === interaction.user.id,
426
- isAdministrator: interaction.memberPermissions?.has(PermissionFlagsBits.Administrator) ??
427
- false,
428
- };
429
- if (!canUseCommand(actor, policy)) {
430
- await interaction.reply({
431
- content: "You do not have permission to use this command.",
432
- flags: MessageFlags.Ephemeral,
433
- });
434
- return false;
437
+ if (!selfAuthorizingGuildCommand) {
438
+ if (!(await authorizeComponent(interaction, moduleId, services)))
439
+ return false;
440
+ const permissions = services.get(HELYX_SERVICE_NAMES.permissions);
441
+ const policy = await permissions.getEffectivePolicy(interaction.guildId, moduleId, commandId);
442
+ const actor = {
443
+ userId: interaction.user.id,
444
+ roleIds: interaction.member instanceof GuildMember
445
+ ? [...interaction.member.roles.cache.keys()]
446
+ : (interaction.member?.roles ?? []),
447
+ permissions: interaction.memberPermissions
448
+ ?.toArray()
449
+ .map(normalizeDiscordPermission) ?? [],
450
+ isServerOwner: interaction.guild?.ownerId === interaction.user.id,
451
+ isAdministrator: interaction.memberPermissions?.has(PermissionFlagsBits.Administrator) ??
452
+ false,
453
+ };
454
+ if (!canUseCommand(actor, policy)) {
455
+ await interaction.reply({
456
+ content: "You do not have permission to use this command.",
457
+ flags: MessageFlags.Ephemeral,
458
+ });
459
+ return false;
460
+ }
435
461
  }
436
462
  if (rateLimit) {
437
463
  const limits = services.get(HELYX_SERVICE_NAMES.rateLimits);
@@ -0,0 +1,21 @@
1
+ import type { CloudConnectorConsentRecord } from "@helyx/database";
2
+ import type { CloudConnector, CloudConnectorStatus } from "./cloud-connector.js";
3
+ import { type ShardCloudResponse } from "./shard-contracts.js";
4
+ export declare class WorkerCloudConnectorProxy implements CloudConnector {
5
+ #private;
6
+ setControlHandler(): void;
7
+ start(): Promise<void>;
8
+ status(): CloudConnectorStatus;
9
+ getSupportConsent(): Promise<CloudConnectorConsentRecord>;
10
+ updateSupportConsent(input: {
11
+ supportInspectionEnabled: boolean;
12
+ supportDataClasses: string[];
13
+ diagnosticsEnabled: boolean;
14
+ }): Promise<CloudConnectorConsentRecord>;
15
+ enrol(token: string, source: "startup" | "discord" | "file"): Promise<CloudConnectorStatus>;
16
+ disconnect(): Promise<void>;
17
+ rotate(): Promise<CloudConnectorStatus>;
18
+ stop(): Promise<void>;
19
+ accept(response: ShardCloudResponse): void;
20
+ }
21
+ //# sourceMappingURL=shard-cloud-proxy.d.ts.map
@@ -0,0 +1,94 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { SHARD_CONTROL_TIMEOUT_MS, assertShardMessageSize, shardCloudResponseSchema, } from "./shard-contracts.js";
3
+ export class WorkerCloudConnectorProxy {
4
+ #pending = new Map();
5
+ #status = { state: "offline" };
6
+ setControlHandler() { }
7
+ async start() {
8
+ this.#status = parseStatus(await this.#request({ kind: "cloud.status" }));
9
+ }
10
+ status() {
11
+ return this.#status;
12
+ }
13
+ async getSupportConsent() {
14
+ return parseConsent(await this.#request({ kind: "cloud.consent.get" }));
15
+ }
16
+ async updateSupportConsent(input) {
17
+ return parseConsent(await this.#request({ kind: "cloud.consent.update", ...input }));
18
+ }
19
+ async enrol(token, source) {
20
+ this.#status = parseStatus(await this.#request({ kind: "cloud.enrol", token, source }));
21
+ return this.#status;
22
+ }
23
+ async disconnect() {
24
+ await this.#request({ kind: "cloud.disconnect" });
25
+ this.#status = { state: "unpaired" };
26
+ }
27
+ async rotate() {
28
+ this.#status = parseStatus(await this.#request({ kind: "cloud.rotate" }));
29
+ return this.#status;
30
+ }
31
+ stop() {
32
+ for (const pending of this.#pending.values()) {
33
+ clearTimeout(pending.timer);
34
+ pending.reject(new Error("Shard worker is stopping"));
35
+ }
36
+ this.#pending.clear();
37
+ return Promise.resolve();
38
+ }
39
+ accept(response) {
40
+ const accepted = shardCloudResponseSchema.parse(response);
41
+ const pending = this.#pending.get(accepted.requestId);
42
+ if (!pending)
43
+ return;
44
+ this.#pending.delete(accepted.requestId);
45
+ clearTimeout(pending.timer);
46
+ if (accepted.ok)
47
+ pending.resolve(accepted.result);
48
+ else
49
+ pending.reject(new Error(accepted.message));
50
+ }
51
+ async #request(operation) {
52
+ if (!process.send)
53
+ throw new Error("Shard supervisor IPC is unavailable");
54
+ const requestId = randomUUID();
55
+ const message = {
56
+ version: 1,
57
+ type: "helyx.cloud.request",
58
+ requestId,
59
+ deadlineAt: new Date(Date.now() + SHARD_CONTROL_TIMEOUT_MS).toISOString(),
60
+ operation,
61
+ };
62
+ assertShardMessageSize(message);
63
+ const response = new Promise((resolve, reject) => {
64
+ const timer = setTimeout(() => {
65
+ this.#pending.delete(requestId);
66
+ reject(new Error("Cloud supervisor request timed out"));
67
+ }, SHARD_CONTROL_TIMEOUT_MS);
68
+ timer.unref();
69
+ this.#pending.set(requestId, { resolve, reject, timer });
70
+ });
71
+ process.send(message);
72
+ return response;
73
+ }
74
+ }
75
+ function parseStatus(value) {
76
+ if (typeof value !== "object" || value === null || !("state" in value))
77
+ throw new Error("Cloud supervisor returned an invalid status");
78
+ const raw = value;
79
+ return {
80
+ state: raw.state,
81
+ ...(raw.installationId ? { installationId: raw.installationId } : {}),
82
+ ...(raw.lastConnectedAt
83
+ ? { lastConnectedAt: new Date(raw.lastConnectedAt) }
84
+ : {}),
85
+ ...(raw.lastErrorCode ? { lastErrorCode: raw.lastErrorCode } : {}),
86
+ };
87
+ }
88
+ function parseConsent(value) {
89
+ if (typeof value !== "object" || value === null || !("updatedAt" in value))
90
+ throw new Error("Cloud supervisor returned invalid consent");
91
+ const consent = value;
92
+ return { ...consent, updatedAt: new Date(consent.updatedAt) };
93
+ }
94
+ //# sourceMappingURL=shard-cloud-proxy.js.map