@theholocron/holocron-plugin-discord 5.0.0-alpha.435 → 5.0.0-alpha.437

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.
package/dist/index.d.mts CHANGED
@@ -9,7 +9,8 @@ export declare const resolveClientSecret: import("@theholocron/cli").TokenResolv
9
9
  /**
10
10
  * Every token this plugin takes, for `holocron doctor secrets --verify`. `verifyToken` checks a webhook URL, so the bot token has
11
11
  * its own `verify` (it asks for the bot's application) and the OAuth client secret, which cannot be checked without a
12
- * sign-in, is listed but not handed to it. The webhook is the last resort for a post that names no
12
+ * sign-in, is listed but not handed to it. The bot's `expect` is what each
13
+ * layer's token must carry (membership of the server and the permissions `setup` needs). The webhook is the last resort for a post that names no
13
14
  * channel, alias or `defaultChannel`, so nothing needs it by default (`optional`).
14
15
  */
15
16
  export declare const tokens: PluginToken[];
@@ -381,13 +382,14 @@ export declare function createContext(options?: DiscordPluginOptions): PluginCon
381
382
  /** Builds the `notifications` capability for a context. */
382
383
  export declare function notifications(ctx: PluginContext): Notifications;
383
384
  /**
384
- * Creates the Discord plugin: its `notifications` capability and its `connection` probe. The probe checks the webhook
385
+ * Creates the Discord plugin: its `notifications` capability and its `connection` and `token` probes. The probe checks the webhook
385
386
  * when there is one, and the bot token when there is not: the webhook is only a last resort for a post that names no
386
387
  * channel, so a missing one is not a failed connection when the bot can be reached.
387
388
  */
388
389
  export declare function createPlugin(options?: DiscordPluginOptions): {
389
390
  name: string;
390
391
  probes: {
392
+ token: import("@theholocron/cli").Probe;
391
393
  connection: import("@theholocron/cli").Probe;
392
394
  };
393
395
  capabilities: {
package/dist/index.mjs CHANGED
@@ -1,6 +1,59 @@
1
- import { AuthError, ElevationRequiredError, ProviderApiError, connectionProbe, createResolveToken } from "@theholocron/cli";
1
+ import { AuthError, ElevationRequiredError, ProviderApiError, connectionProbe, createResolveToken, tokenExpectations } from "@theholocron/cli";
2
2
  import { errorMessage } from "@theholocron/misc-utils";
3
3
  import { ApplicationFlag, ChannelType, MessageFlag, createDiscordBotClient, createDiscordClient, createDiscordOAuthClient, findVerifiedConnection, parseWebhookUrl, permissionNames, permissions } from "@theholocron/discord-client";
4
+ // src/bot-needs.ts
5
+ /** What the bot needs in the server to do everything `setup` does. The invite link asks for exactly these. */
6
+ const BOT_NEEDS = [
7
+ "ViewChannel",
8
+ "SendMessages",
9
+ "ReadMessageHistory",
10
+ "ManageChannels",
11
+ "ManageRoles",
12
+ "ManageWebhooks",
13
+ "ManageGuild",
14
+ "CreatePublicThreads",
15
+ "CreatePrivateThreads",
16
+ "SendMessagesInThreads"
17
+ ];
18
+ /**
19
+ * What the bot keeps for a layout: the usual set, Pin Messages when the layout pins messages, Manage Threads when it
20
+ * declares a forum (a post's tags are applied by the bot, and a moderated tag only by someone who can manage threads),
21
+ * and Add Reactions when a forum has `starterReactions` (without it the bot skips them and the post still gets made).
22
+ * The one list `setup`'s invite link, `doctor notifications` and `probe discord token` all read.
23
+ */
24
+ function botNeeds(layout) {
25
+ const channels = (layout?.categories ?? []).flatMap((c) => c.channels ?? []);
26
+ const forum = channels.some((ch) => ch.kind === "forum");
27
+ const reacts = channels.some((ch) => (ch.starterReactions ?? []).length > 0);
28
+ return [
29
+ ...BOT_NEEDS,
30
+ ...layout?.pinned?.length ? ["PinMessages"] : [],
31
+ ...forum ? ["ManageThreads"] : [],
32
+ ...reacts ? ["AddReactions"] : []
33
+ ];
34
+ }
35
+ // src/probes/token/expectations.ts
36
+ /** The name the probe's row uses for being a member of the configured server, beside the permission names. */
37
+ const GUILD = "guild";
38
+ /** What the bot token must do in a layer: be in the server and hold every permission `setup` needs. */
39
+ const EVERYTHING = {
40
+ [GUILD]: "required",
41
+ ...Object.fromEntries(BOT_NEEDS.map((name) => [name, "required"]))
42
+ };
43
+ /**
44
+ * What each layer's bot token is meant to carry. It is one bot, so every layer that holds the token (a laptop, CI,
45
+ * Sentinel in `prod`) needs the same: to be a member of the configured server with the permissions of `BOT_NEEDS`,
46
+ * the list `setup`'s invite link and `doctor notifications` use. Permissions only a layout asks for (Pin Messages,
47
+ * Manage Threads, Add Reactions) are added by the probe from the same `botNeeds()`. This is the plugin's `tokens`
48
+ * declaration, read through `tokenExpectations()`; change it and the Discord section of
49
+ * `docs/src/content/docs/tokens.mdx` together.
50
+ */
51
+ const EXPECTED = { permissions: {
52
+ local: EVERYTHING,
53
+ dev: EVERYTHING,
54
+ ci: EVERYTHING,
55
+ prod: EVERYTHING
56
+ } };
4
57
  // src/verify-bot-token.ts
5
58
  /** Checks a Discord bot token by asking for the bot's own application; resolves to its name and id, or the failure message. */
6
59
  async function verifyBotToken(botToken, opts = {}) {
@@ -46,7 +99,8 @@ const resolveClientSecret = createResolveToken({
46
99
  /**
47
100
  * Every token this plugin takes, for `holocron doctor secrets --verify`. `verifyToken` checks a webhook URL, so the bot token has
48
101
  * its own `verify` (it asks for the bot's application) and the OAuth client secret, which cannot be checked without a
49
- * sign-in, is listed but not handed to it. The webhook is the last resort for a post that names no
102
+ * sign-in, is listed but not handed to it. The bot's `expect` is what each
103
+ * layer's token must carry (membership of the server and the permissions `setup` needs). The webhook is the last resort for a post that names no
50
104
  * channel, alias or `defaultChannel`, so nothing needs it by default (`optional`).
51
105
  */
52
106
  const tokens = [
@@ -56,7 +110,8 @@ const tokens = [
56
110
  },
57
111
  {
58
112
  ...resolveBotToken.token,
59
- verify: (token) => verifyBotToken(token)
113
+ verify: (token) => verifyBotToken(token),
114
+ expect: EXPECTED
60
115
  },
61
116
  {
62
117
  ...resolveClientSecret.token,
@@ -398,19 +453,6 @@ const FILTER = {
398
453
  all: 2
399
454
  };
400
455
  const nameOf = (map, value) => Object.keys(map).find((k) => map[k] === value);
401
- /** What the bot needs in the server to do everything `setup` does. The invite link asks for exactly these. */
402
- const BOT_NEEDS = [
403
- "ViewChannel",
404
- "SendMessages",
405
- "ReadMessageHistory",
406
- "ManageChannels",
407
- "ManageRoles",
408
- "ManageWebhooks",
409
- "ManageGuild",
410
- "CreatePublicThreads",
411
- "CreatePrivateThreads",
412
- "SendMessagesInThreads"
413
- ];
414
456
  /** The OAuth2 scopes Discord offers an application, as its own application page lists them. Exact, lower-case. */
415
457
  const SCOPES = /* @__PURE__ */ new Set([
416
458
  "applications.builds.read",
@@ -842,15 +884,7 @@ var DiscordNotifications = class DiscordNotifications {
842
884
  * and Add Reactions when a forum has `starterReactions` (without it the bot skips them and the post still gets made).
843
885
  */
844
886
  needs() {
845
- const channels = (this.opts.layout?.categories ?? []).flatMap((c) => c.channels ?? []);
846
- const forum = channels.some((ch) => ch.kind === "forum");
847
- const reacts = channels.some((ch) => (ch.starterReactions ?? []).length > 0);
848
- return [
849
- ...BOT_NEEDS,
850
- ...this.opts.layout?.pinned?.length ? ["PinMessages"] : [],
851
- ...forum ? ["ManageThreads"] : [],
852
- ...reacts ? ["AddReactions"] : []
853
- ];
887
+ return botNeeds(this.opts.layout);
854
888
  }
855
889
  /** Where to re-invite the bot so its role holds what `setup` needs. Re-authorising updates the role in place. */
856
890
  async inviteUrl(names = this.needs()) {
@@ -2141,6 +2175,212 @@ var DiscordNotifications = class DiscordNotifications {
2141
2175
  return this.defaultWebhookUrl();
2142
2176
  }
2143
2177
  };
2178
+ // src/probes/token/parse-token-args.ts
2179
+ /** Reads `--layer <word>` and `--token-name <VAR>` (or the `=` forms) from the words after `probe discord token`; the CLI passes them with `--environment`: the layer, and which declared token is being checked. */
2180
+ function parseTokenArgs(args) {
2181
+ let layer;
2182
+ let tokenName;
2183
+ for (let i = 0; i < args.length; i++) {
2184
+ const arg = args[i];
2185
+ if (arg === "--layer") layer = args[++i];
2186
+ else if (arg.startsWith("--layer=")) layer = arg.slice(8);
2187
+ else if (arg === "--token-name") tokenName = args[++i];
2188
+ else if (arg.startsWith("--token-name=")) tokenName = arg.slice(13);
2189
+ }
2190
+ return {
2191
+ ...layer ? { layer } : {},
2192
+ ...tokenName ? { tokenName } : {}
2193
+ };
2194
+ }
2195
+ // src/probes/token/token.ts
2196
+ /** The bot token's variable in the plugin's `tokens`, which is where the layers' expectations are read from and the only token this probe checks. */
2197
+ const BOT_TOKEN = "HOLOCRON_DISCORD_BOT_TOKEN";
2198
+ /** The rules the plugin's `tokens` declare for a layer's bot token, read through `tokenExpectations()`. */
2199
+ const declared = (layer, envName) => tokenExpectations(tokens, {
2200
+ layer,
2201
+ envName
2202
+ })[0]?.rules;
2203
+ /** `ManageChannels` as `Manage Channels`, the way the permission is named in Discord's own screens. */
2204
+ const words = (name) => name.replace(/([a-z])([A-Z])/g, "$1 $2");
2205
+ /**
2206
+ * One row for what was tried. With no rule it only describes (`ok` for a held permission, `info` for one it lacks).
2207
+ * Under a layer's rule it judges: a required permission the bot lacks fails, and one the layer must not have fails when
2208
+ * the bot has it; a permission rightly absent is a bare `ok`.
2209
+ */
2210
+ function rowFor({ label, outcome }, rule) {
2211
+ const detail = outcome.detail ? { detail: outcome.detail } : {};
2212
+ if (outcome.kind === "error") return {
2213
+ status: "fail",
2214
+ label,
2215
+ ...detail
2216
+ };
2217
+ const has = outcome.kind === "has";
2218
+ if (rule === "required") return {
2219
+ status: has ? "ok" : "fail",
2220
+ label,
2221
+ ...detail
2222
+ };
2223
+ if (rule === "absent") return has ? {
2224
+ status: "fail",
2225
+ label,
2226
+ ...detail
2227
+ } : {
2228
+ status: "ok",
2229
+ label
2230
+ };
2231
+ return {
2232
+ status: has ? "ok" : "info",
2233
+ label,
2234
+ ...detail
2235
+ };
2236
+ }
2237
+ /**
2238
+ * What the bot holds in the server: everything for the owner or an Administrator, else the permissions of its roles
2239
+ * (@everyone and the ones it has). Channel overwrites are not looked at; `doctor notifications` does that per forum.
2240
+ */
2241
+ async function heldPermissions(ctx, guildId, ownerId, me) {
2242
+ if (ownerId === me) return () => true;
2243
+ const bot = ctx.bot();
2244
+ const [member, roles] = await Promise.all([bot.guilds.member(guildId, me), bot.guilds.roles(guildId)]);
2245
+ const held = /* @__PURE__ */ new Set([guildId, ...member.roles]);
2246
+ const bits = roles.filter((r) => held.has(r.id)).reduce((all, r) => all | BigInt(r.permissions ?? "0"), 0n);
2247
+ const has = (name) => {
2248
+ const bit = BigInt(permissions([name]));
2249
+ return (bits & bit) === bit;
2250
+ };
2251
+ const admin = has("Administrator");
2252
+ return (name) => admin || has(name);
2253
+ }
2254
+ /**
2255
+ * The `token` probe: checks the Discord bot token against the configured server. It asks for the bot's application (is
2256
+ * the token good), whether the bot is a member of the `guildId` server, and which of the permissions Holocron needs
2257
+ * (`botNeeds()`, the same list `setup`'s invite link and `doctor notifications` use) its roles give it. It only reads,
2258
+ * so it changes nothing. The token is the one the plugin resolves, so `--token discord=<token>` or `--environment
2259
+ * <layer>` checks another one.
2260
+ *
2261
+ * A token with no layer is only described. When the CLI passes `--layer` (because `--environment` named a layer), the
2262
+ * results are judged against what that layer's token is meant to carry (the plugin's `tokens` declaration, read with
2263
+ * `tokenExpectations()`) and shown in two groups, what it should have and what it should not.
2264
+ */
2265
+ function tokenProbe(ctx) {
2266
+ return {
2267
+ summary: "Check the Discord bot token: that it is valid, that the bot is in the configured server, and which of the permissions Holocron needs its roles give it; for a layer's Environment, check it against what that layer should carry. Read-only.",
2268
+ writes: false,
2269
+ acceptsToken: true,
2270
+ async run(probe) {
2271
+ const { layer, tokenName } = parseTokenArgs(probe.args ?? []);
2272
+ if (tokenName !== void 0 && tokenName !== BOT_TOKEN) {
2273
+ probe.say({
2274
+ status: "info",
2275
+ label: tokenName,
2276
+ detail: "not a bot token, so this probe does not check it"
2277
+ });
2278
+ return;
2279
+ }
2280
+ const token = ctx.token();
2281
+ probe.secret(token);
2282
+ if (/^https?:\/\//i.test(token)) {
2283
+ probe.say({
2284
+ status: "fail",
2285
+ label: "token",
2286
+ detail: "that is a webhook URL, not a bot token (HOLOCRON_DISCORD_BOT_TOKEN)"
2287
+ });
2288
+ return;
2289
+ }
2290
+ const bot = ctx.bot();
2291
+ const rules = layer ? (ctx.rules ?? declared)(layer, BOT_TOKEN) : void 0;
2292
+ if (layer && !rules) probe.say({
2293
+ status: "info",
2294
+ label: layer,
2295
+ detail: "no expectations are declared for it, so the token is only described"
2296
+ });
2297
+ let me;
2298
+ try {
2299
+ const app = await bot.application.get();
2300
+ probe.say({
2301
+ status: "ok",
2302
+ label: "token",
2303
+ detail: `bot: ${app.name} (id: ${app.id})`
2304
+ });
2305
+ me = (await bot.users.me()).id;
2306
+ } catch (err) {
2307
+ probe.say({
2308
+ status: "fail",
2309
+ label: "token",
2310
+ detail: errorMessage(err)
2311
+ });
2312
+ return;
2313
+ }
2314
+ const guildId = ctx.options.guildId;
2315
+ if (!guildId) {
2316
+ probe.say({
2317
+ status: rules ? "fail" : "info",
2318
+ label: "server",
2319
+ detail: "no guildId in the discord provider options, so membership and permissions cannot be checked"
2320
+ });
2321
+ return;
2322
+ }
2323
+ const keys = [...new Set(botNeeds(ctx.options.layout))];
2324
+ const tried = [];
2325
+ let held;
2326
+ try {
2327
+ const guild = await bot.guilds.get(guildId);
2328
+ held = await heldPermissions(ctx, guildId, guild.owner_id, me);
2329
+ tried.push({
2330
+ key: GUILD,
2331
+ label: "Server membership",
2332
+ outcome: {
2333
+ kind: "has",
2334
+ detail: guild.name ?? guildId
2335
+ }
2336
+ });
2337
+ } catch (err) {
2338
+ if (err instanceof ProviderApiError && (err.status === 403 || err.status === 404)) {
2339
+ tried.push({
2340
+ key: GUILD,
2341
+ label: "Server membership",
2342
+ outcome: {
2343
+ kind: "none",
2344
+ detail: `the bot is not in server ${guildId} (${err.status})`
2345
+ }
2346
+ });
2347
+ held = () => false;
2348
+ } else tried.push({
2349
+ key: GUILD,
2350
+ label: "Server membership",
2351
+ outcome: {
2352
+ kind: "error",
2353
+ detail: errorMessage(err)
2354
+ }
2355
+ });
2356
+ }
2357
+ if (held) for (const key of keys) {
2358
+ const has = held(key);
2359
+ tried.push({
2360
+ key,
2361
+ label: words(key),
2362
+ outcome: has ? { kind: "has" } : {
2363
+ kind: "none",
2364
+ detail: "not held"
2365
+ }
2366
+ });
2367
+ }
2368
+ if (!rules) {
2369
+ for (const t of tried) probe.say(rowFor(t, void 0));
2370
+ return;
2371
+ }
2372
+ for (const [heading, rule] of [["Should have", "required"], ["Should not have", "absent"]]) {
2373
+ const inGroup = tried.filter((t) => (rules[t.key] ?? "required") === rule);
2374
+ if (inGroup.length === 0) continue;
2375
+ probe.say({
2376
+ status: "heading",
2377
+ label: heading
2378
+ });
2379
+ for (const t of inGroup) probe.say(rowFor(t, rule));
2380
+ }
2381
+ }
2382
+ };
2383
+ }
2144
2384
  // src/verify-token.ts
2145
2385
  /** Checks a Discord webhook URL by fetching the webhook; resolves to its name and id, or the failure message. */
2146
2386
  async function verifyToken(webhookUrl, opts = {}) {
@@ -2208,7 +2448,7 @@ function notifications(ctx) {
2208
2448
  return new DiscordNotifications(ctx.client, ctx.options, ctx.defaultWebhookUrl, ctx.bot, ctx.oauth);
2209
2449
  }
2210
2450
  /**
2211
- * Creates the Discord plugin: its `notifications` capability and its `connection` probe. The probe checks the webhook
2451
+ * Creates the Discord plugin: its `notifications` capability and its `connection` and `token` probes. The probe checks the webhook
2212
2452
  * when there is one, and the bot token when there is not: the webhook is only a last resort for a post that names no
2213
2453
  * channel, so a missing one is not a failed connection when the bot can be reached.
2214
2454
  */
@@ -2217,36 +2457,58 @@ function createPlugin(options = {}) {
2217
2457
  let found = "webhook";
2218
2458
  return {
2219
2459
  name: "@theholocron/holocron-plugin-discord",
2220
- probes: { connection: connectionProbe({
2221
- provider: "Discord",
2222
- url: options.baseUrl ?? "https://discord.com",
2223
- fetch: options.fetch,
2224
- token: () => {
2225
- try {
2226
- found = "webhook";
2227
- return resolveToken(options);
2228
- } catch (noWebhook) {
2229
- found = "bot";
2460
+ probes: {
2461
+ token: tokenProbe({
2462
+ options: {
2463
+ guildId: options.guildId,
2464
+ layout: options.layout
2465
+ },
2466
+ token: () => options.cliToken ?? resolveBotToken({
2467
+ env: options.env,
2468
+ keyring: options.keyring,
2469
+ org: options.org
2470
+ }),
2471
+ bot: () => createDiscordBotClient({
2472
+ botToken: options.cliToken ?? resolveBotToken({
2473
+ env: options.env,
2474
+ keyring: options.keyring,
2475
+ org: options.org
2476
+ }),
2477
+ ...options.unsafeBotBaseUrl && options.baseUrl ? { baseUrl: options.baseUrl } : {},
2478
+ ...options.fetch ? { fetch: options.fetch } : {}
2479
+ })
2480
+ }),
2481
+ connection: connectionProbe({
2482
+ provider: "Discord",
2483
+ url: options.baseUrl ?? "https://discord.com",
2484
+ fetch: options.fetch,
2485
+ token: () => {
2230
2486
  try {
2231
- return resolveBotToken({
2232
- env: options.env,
2233
- keyring: options.keyring,
2234
- org: options.org
2235
- });
2236
- } catch {
2237
- throw noWebhook;
2487
+ found = "webhook";
2488
+ return resolveToken(options);
2489
+ } catch (noWebhook) {
2490
+ found = "bot";
2491
+ try {
2492
+ return resolveBotToken({
2493
+ env: options.env,
2494
+ keyring: options.keyring,
2495
+ org: options.org
2496
+ });
2497
+ } catch {
2498
+ throw noWebhook;
2499
+ }
2238
2500
  }
2239
- }
2240
- },
2241
- verify: (token) => found === "webhook" ? verifyToken(token, {
2242
- baseUrl: options.baseUrl,
2243
- fetch: options.fetch
2244
- }) : verifyBotToken(token, {
2245
- baseUrl: options.baseUrl,
2246
- fetch: options.fetch,
2247
- unsafeBotBaseUrl: options.unsafeBotBaseUrl
2501
+ },
2502
+ verify: (token) => found === "webhook" ? verifyToken(token, {
2503
+ baseUrl: options.baseUrl,
2504
+ fetch: options.fetch
2505
+ }) : verifyBotToken(token, {
2506
+ baseUrl: options.baseUrl,
2507
+ fetch: options.fetch,
2508
+ unsafeBotBaseUrl: options.unsafeBotBaseUrl
2509
+ })
2248
2510
  })
2249
- }) },
2511
+ },
2250
2512
  capabilities: { notifications: () => notifications(ctx) }
2251
2513
  };
2252
2514
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theholocron/holocron-plugin-discord",
3
- "version": "5.0.0-alpha.435",
3
+ "version": "5.0.0-alpha.437",
4
4
  "description": "Holocron plugin for Discord. Implements the notifications capability via Discord incoming webhooks.",
5
5
  "keywords": [
6
6
  "discord",
@@ -41,19 +41,19 @@
41
41
  "tsx": "4.23.15",
42
42
  "typescript": "^5.9.3",
43
43
  "vitest": "^5.1.0",
44
- "@theholocron/cli": "5.0.0-alpha.435",
44
+ "@theholocron/cli": "5.0.0-alpha.437",
45
+ "@theholocron/eslint-config": "^8.9.0-alpha.17",
46
+ "@theholocron/discord-client": "^1.58.0-alpha.32",
47
+ "@theholocron/http-client": "^1.58.0-alpha.32",
45
48
  "@theholocron/misc-utils": "^1.17.0-alpha.4",
46
- "@theholocron/tsconfig": "^8.9.0-alpha.17",
47
- "@theholocron/discord-client": "^1.58.0-alpha.31",
48
- "@theholocron/http-client": "^1.58.0-alpha.31",
49
49
  "@theholocron/tsdown-config": "^8.9.0-alpha.17",
50
- "@theholocron/eslint-config": "^8.9.0-alpha.17",
50
+ "@theholocron/tsconfig": "^8.9.0-alpha.17",
51
51
  "@theholocron/vitest-config": "^8.9.0-alpha.17"
52
52
  },
53
53
  "peerDependencies": {
54
54
  "@theholocron/discord-client": "^1.50.0",
55
55
  "@theholocron/misc-utils": "^1.16.0",
56
- "@theholocron/cli": "5.0.0-alpha.435"
56
+ "@theholocron/cli": "5.0.0-alpha.437"
57
57
  },
58
58
  "engines": {
59
59
  "node": ">=22"