@theholocron/holocron-plugin-discord 5.0.0-alpha.199 → 5.0.0-alpha.200

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/README.md CHANGED
@@ -72,6 +72,10 @@ methods. They use the **Holonet bot**, not a webhook URL:
72
72
  `discord.holonet` (`holocron auth set discord.holonet <token>`) — the bot token
73
73
  from the Developer Portal. Only read when a provisioning command runs, or when
74
74
  `holocron doctor` checks a provider that has a `guildId`; posting never needs it.
75
+ - `HOLOCRON_DISCORD_CLIENT_SECRET` (or `DISCORD_CLIENT_SECRET`), or the keyring entry
76
+ `discord.holonet.oauth` — the application's OAuth client secret (Developer Portal →
77
+ OAuth2 → Reset Secret). Only `holocron notifications link` reads it, to learn which
78
+ GitHub account a member owns; the API can neither create nor read it.
75
79
  - `guildId` — the server id (not a secret), set in the provider options.
76
80
  - `layout` — categories, channels (each optionally with a `webhook`) and roles.
77
81
 
package/dist/index.d.mts CHANGED
@@ -1,8 +1,9 @@
1
- import { AuthError, EnsureWebhookResult, EnsuredResource, Notifications, NotificationsAccess, NotificationsApplicationLayout, NotificationsEveryoneLayout, NotificationsLayout, NotificationsOnboardingLayout, NotificationsServerLayout, NotificationsWelcomeLayout, ResolveTokenInput, ServerInspection, VerifyTokenFailure, VerifyTokenResult, VerifyTokenResult as VerifyTokenResult$1, VerifyTokenSuccess } from "@theholocron/cli";
2
- import { DiscordBotClient, DiscordClient, DiscordClientOptions, DiscordWebhookInfo, createDiscordClient, parseWebhookUrl } from "@theholocron/discord-client";
1
+ import { AuthError, EnsureWebhookResult, EnsuredResource, Notifications, NotificationsAccess, NotificationsApplicationLayout, NotificationsEveryoneLayout, NotificationsLayout, NotificationsMember, NotificationsOnboardingLayout, NotificationsServerLayout, NotificationsSignIn, NotificationsWelcomeLayout, ResolveTokenInput, ServerInspection, VerifyTokenFailure, VerifyTokenResult, VerifyTokenResult as VerifyTokenResult$1, VerifyTokenSuccess } from "@theholocron/cli";
2
+ import { DiscordBotClient, DiscordClient, DiscordClientOptions, DiscordOAuthClient, DiscordWebhookInfo, createDiscordClient, parseWebhookUrl } from "@theholocron/discord-client";
3
3
  //#region src/auth.d.ts
4
4
  declare const resolveToken: (input?: ResolveTokenInput) => string;
5
5
  declare const resolveBotToken: (input?: ResolveTokenInput) => string;
6
+ declare const resolveClientSecret: (input?: ResolveTokenInput) => string;
6
7
  //#endregion
7
8
  //#region src/capabilities/notifications.d.ts
8
9
  interface DiscordNotificationsOptions {
@@ -28,13 +29,23 @@ declare class DiscordNotifications implements Notifications {
28
29
  private readonly defaultWebhookUrl;
29
30
  /** Memoized thunk — resolves the bot token on first provisioning call, never on `send()`. */
30
31
  private readonly bot;
32
+ /** Builds the OAuth client for one redirect URI; needs the application's client secret. */
33
+ private readonly oauth;
31
34
  readonly key: "notifications";
32
35
  readonly providerName = "discord";
33
36
  constructor(client: DiscordClient, opts: DiscordNotificationsOptions,
34
37
  /** Memoized thunk — resolves the default webhook URL on the first `send()`. */
35
38
  defaultWebhookUrl: () => string,
36
39
  /** Memoized thunk — resolves the bot token on first provisioning call, never on `send()`. */
37
- bot?: () => DiscordBotClient);
40
+ bot?: () => DiscordBotClient,
41
+ /** Builds the OAuth client for one redirect URI; needs the application's client secret. */
42
+ oauth?: (redirectUri: string) => Promise<DiscordOAuthClient>);
43
+ /**
44
+ * Sign a member in with Discord to learn which GitHub account they own. Asks only for `identify` and
45
+ * `connections`, reads the account Discord has verified, and revokes the token before returning: nothing
46
+ * about the sign-in is kept.
47
+ */
48
+ signIn(): NotificationsSignIn;
38
49
  get layout(): NotificationsLayout | undefined;
39
50
  send(channel: string, message: string): Promise<void>;
40
51
  /**
@@ -90,7 +101,10 @@ declare class DiscordNotifications implements Notifications {
90
101
  }>;
91
102
  ensureApplication(app: NotificationsApplicationLayout): Promise<{
92
103
  updated: string[];
104
+ todo?: string[];
93
105
  }>;
106
+ /** Whether the Server Members Intent is on: the unverified app's toggle, or the verified app's own bit. */
107
+ private static membersIntentOn;
94
108
  validateLayout(layout: NotificationsLayout): string | undefined;
95
109
  private botUser?;
96
110
  private botId;
@@ -159,6 +173,11 @@ declare class DiscordNotifications implements Notifications {
159
173
  category?: string;
160
174
  avatar?: string;
161
175
  }): Promise<EnsureWebhookResult>;
176
+ /** The one role with this name, or an error that says what to fix: none, or more than one. */
177
+ private roleNamed;
178
+ roleMembers(roleName: string): Promise<NotificationsMember[]>;
179
+ addRoleMember(roleName: string, memberId: string): Promise<void>;
180
+ removeRoleMember(roleName: string, memberId: string): Promise<void>;
162
181
  ensureRole(input: {
163
182
  name: string;
164
183
  mentionable?: boolean;
@@ -198,6 +217,8 @@ interface PluginContext {
198
217
  defaultWebhookUrl: () => string;
199
218
  /** Memoized — resolves the bot token on the first provisioning call, or when `holocron doctor` checks a provider that has a `guildId`; `send()` and `describe()` never touch it. */
200
219
  bot: () => DiscordBotClient;
220
+ /** Builds the OAuth client for one redirect URI; resolves the application id and the client secret on first use. */
221
+ oauth: (redirectUri: string) => Promise<DiscordOAuthClient>;
201
222
  }
202
223
  declare function createContext(options?: DiscordPluginOptions): PluginContext;
203
224
  declare function notifications(ctx: PluginContext): Notifications;
@@ -209,4 +230,4 @@ declare function createPlugin(options?: DiscordPluginOptions): {
209
230
  };
210
231
  declare const AUTH_HINT: string;
211
232
  //#endregion
212
- export { AUTH_HINT, AuthError, type DiscordClient, type DiscordClientOptions, DiscordNotifications, type DiscordNotificationsOptions, DiscordPluginOptions, type DiscordWebhookInfo, PluginContext, type ResolveTokenInput, type VerifyTokenFailure, type VerifyTokenResult, type VerifyTokenSuccess, createContext, createDiscordClient, createPlugin, notifications, parseWebhookUrl, resolveBotToken, resolveToken, verifyToken };
233
+ export { AUTH_HINT, AuthError, type DiscordClient, type DiscordClientOptions, DiscordNotifications, type DiscordNotificationsOptions, DiscordPluginOptions, type DiscordWebhookInfo, PluginContext, type ResolveTokenInput, type VerifyTokenFailure, type VerifyTokenResult, type VerifyTokenSuccess, createContext, createDiscordClient, createPlugin, notifications, parseWebhookUrl, resolveBotToken, resolveClientSecret, resolveToken, verifyToken };
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { AuthError, ProviderApiError, createResolveToken } from "@theholocron/cli";
2
2
  import { errorMessage } from "@theholocron/misc-utils";
3
- import { ChannelType, createDiscordBotClient, createDiscordClient, parseWebhookUrl, permissionNames, permissions } from "@theholocron/discord-client";
3
+ import { ApplicationFlag, ChannelType, createDiscordBotClient, createDiscordClient, createDiscordOAuthClient, findVerifiedConnection, parseWebhookUrl, permissionNames, permissions } from "@theholocron/discord-client";
4
4
  //#region src/auth.ts
5
5
  const resolveToken = createResolveToken({
6
6
  envName: "HOLOCRON_DISCORD_WEBHOOK",
@@ -14,6 +14,12 @@ const resolveBotToken = createResolveToken({
14
14
  keyringService: "discord.holonet",
15
15
  errorMessage: "no Discord bot token found. Set HOLOCRON_DISCORD_BOT_TOKEN (or DISCORD_BOT_TOKEN), or run: holocron auth set discord.holonet <token> — it is the bot token from the Discord developer portal (Bot → Reset Token), not a webhook URL."
16
16
  });
17
+ const resolveClientSecret = createResolveToken({
18
+ envName: "HOLOCRON_DISCORD_CLIENT_SECRET",
19
+ vendorEnvName: "DISCORD_CLIENT_SECRET",
20
+ keyringService: "discord.holonet.oauth",
21
+ errorMessage: "no Discord client secret found. Set HOLOCRON_DISCORD_CLIENT_SECRET (or DISCORD_CLIENT_SECRET), or run: holocron auth set discord.holonet.oauth <secret> — it is the client secret from the developer portal (OAuth2 → Reset Secret), which the API cannot create or read."
22
+ });
17
23
  //#endregion
18
24
  //#region src/capabilities/notifications.ts
19
25
  /** Discord's numeric settings, by the names the layout uses. */
@@ -198,15 +204,47 @@ var DiscordNotifications = class DiscordNotifications {
198
204
  opts;
199
205
  defaultWebhookUrl;
200
206
  bot;
207
+ oauth;
201
208
  key = "notifications";
202
209
  providerName = "discord";
203
210
  constructor(client, opts, defaultWebhookUrl, bot = () => {
204
211
  throw new Error("no Discord bot client configured");
212
+ }, oauth = () => {
213
+ throw new Error("no Discord OAuth client configured");
205
214
  }) {
206
215
  this.client = client;
207
216
  this.opts = opts;
208
217
  this.defaultWebhookUrl = defaultWebhookUrl;
209
218
  this.bot = bot;
219
+ this.oauth = oauth;
220
+ }
221
+ /**
222
+ * Sign a member in with Discord to learn which GitHub account they own. Asks only for `identify` and
223
+ * `connections`, reads the account Discord has verified, and revokes the token before returning: nothing
224
+ * about the sign-in is kept.
225
+ */
226
+ signIn() {
227
+ return {
228
+ authorizeUrl: async ({ redirectUri, state }) => (await this.oauth(redirectUri)).authorizeUrl({ state }),
229
+ complete: async ({ redirectUri, code }) => {
230
+ const client = await this.oauth(redirectUri);
231
+ const token = await client.exchangeCode(code);
232
+ try {
233
+ const [user, connections] = await Promise.all([client.user(token.access_token), client.connections(token.access_token)]);
234
+ const github = findVerifiedConnection(connections, "github");
235
+ return {
236
+ member: user.id,
237
+ name: user.global_name ?? user.username,
238
+ ...github ? { github: {
239
+ id: github.id,
240
+ login: github.name
241
+ } } : {}
242
+ };
243
+ } finally {
244
+ await client.revoke(token.access_token).catch(() => {});
245
+ }
246
+ }
247
+ };
210
248
  }
211
249
  get layout() {
212
250
  return this.opts.layout;
@@ -361,7 +399,9 @@ var DiscordNotifications = class DiscordNotifications {
361
399
  } } : {},
362
400
  ...app.terms_of_service_url ? { termsUrl: app.terms_of_service_url } : {},
363
401
  ...app.privacy_policy_url ? { privacyUrl: app.privacy_policy_url } : {},
364
- ...app.role_connections_verification_url ? { roleConnectionsUrl: app.role_connections_verification_url } : {}
402
+ ...app.role_connections_verification_url ? { roleConnectionsUrl: app.role_connections_verification_url } : {},
403
+ intents: { members: DiscordNotifications.membersIntentOn(app.flags ?? 0) },
404
+ redirectUris: app.redirect_uris ?? []
365
405
  };
366
406
  } catch (err) {
367
407
  applicationError = reason(err);
@@ -734,7 +774,17 @@ var DiscordNotifications = class DiscordNotifications {
734
774
  body[key] = app[field];
735
775
  updated.push(field);
736
776
  }
737
- if (updated.length === 0) return { updated };
777
+ const flagsNow = current.flags ?? 0;
778
+ const membersWanted = app.intents?.members;
779
+ if (membersWanted !== void 0 && membersWanted !== DiscordNotifications.membersIntentOn(flagsNow)) {
780
+ body.flags = membersWanted ? flagsNow | ApplicationFlag.GatewayGuildMembersLimited : flagsNow & ~ApplicationFlag.GatewayGuildMembersLimited;
781
+ updated.push("intents");
782
+ }
783
+ const todo = (app.redirectUris ?? []).filter((uri) => !(current.redirect_uris ?? []).includes(uri)).map((uri) => `add ${uri} under OAuth2 → Redirects in the Discord developer portal (the API does not allow setting it)`);
784
+ if (updated.length === 0) return {
785
+ updated,
786
+ ...todo.length ? { todo } : {}
787
+ };
738
788
  let after;
739
789
  try {
740
790
  after = await bot.application.modify(body);
@@ -745,12 +795,20 @@ var DiscordNotifications = class DiscordNotifications {
745
795
  const stuck = updated.filter((name) => {
746
796
  if (name === "description") return (after.description ?? "") !== app.description;
747
797
  if (name === "tags") return set(after.tags ?? []) !== set(app.tags);
798
+ if (name === "intents") return DiscordNotifications.membersIntentOn(after.flags ?? 0) !== app.intents.members;
748
799
  if (name === "install") return !after.install_params || exact(after.install_params.scopes) !== exact(install.scopes) || after.install_params.permissions !== install.permissions;
749
800
  const key = urls.find(([f]) => f === name)[1];
750
801
  return (after[key] ?? "") !== app[name];
751
802
  });
752
803
  if (stuck.length > 0) throw new Error(`sent ${stuck.join(", ")} but Discord did not keep ${stuck.length === 1 ? "it" : "them"} -- it may not accept that field from a bot, so set it in the developer portal`);
753
- return { updated };
804
+ return {
805
+ updated,
806
+ ...todo.length ? { todo } : {}
807
+ };
808
+ }
809
+ /** Whether the Server Members Intent is on: the unverified app's toggle, or the verified app's own bit. */
810
+ static membersIntentOn(flags) {
811
+ return (flags & (ApplicationFlag.GatewayGuildMembers | ApplicationFlag.GatewayGuildMembersLimited)) !== 0;
754
812
  }
755
813
  validateLayout(layout) {
756
814
  const app = layout.application;
@@ -761,6 +819,8 @@ var DiscordNotifications = class DiscordNotifications {
761
819
  const long = app.tags.find((t) => t.length > 20);
762
820
  if (long !== void 0) return `application: the tag ${JSON.stringify(long)} is over 20 characters`;
763
821
  }
822
+ const badRedirect = (app.redirectUris ?? []).find((u) => !/^https:\/\/|^http:\/\/localhost(:\d+)?\//.test(u));
823
+ if (badRedirect !== void 0) return `application: \`redirectUris\` ${JSON.stringify(badRedirect)} must start with https:// (or http://localhost for a local sign-in)`;
764
824
  for (const [field, url] of [
765
825
  ["termsUrl", app.termsUrl],
766
826
  ["privacyUrl", app.privacyUrl],
@@ -1046,6 +1106,31 @@ var DiscordNotifications = class DiscordNotifications {
1046
1106
  }
1047
1107
  return result;
1048
1108
  }
1109
+ /** The one role with this name, or an error that says what to fix: none, or more than one. */
1110
+ async roleNamed(name) {
1111
+ const matches = (await this.bot().guilds.roles(this.guild())).filter((r) => DiscordNotifications.same(r.name, name));
1112
+ if (matches.length === 0) throw new Error(`no role named \`${name}\` — run \`holocron notifications setup\` to create it`);
1113
+ if (matches.length > 1) throw new Error(`${matches.length} roles are named \`${name}\` (ids ${matches.map((r) => r.id).join(", ")}) — delete or rename the extras so it is clear which one to manage`);
1114
+ return matches[0];
1115
+ }
1116
+ async roleMembers(roleName) {
1117
+ const role = await this.roleNamed(roleName);
1118
+ try {
1119
+ return (await this.bot().guilds.membersWithRole(this.guild(), role.id)).flatMap((m) => m.user ? [{
1120
+ id: m.user.id,
1121
+ ...m.user.username ? { name: m.user.username } : {}
1122
+ }] : []);
1123
+ } catch (err) {
1124
+ if (err instanceof ProviderApiError && err.status === 403) throw new Error("Discord refused to list the server's members: switch on the **Server Members Intent** for the bot in the developer portal (Bot → Privileged Gateway Intents), then run this again", { cause: err });
1125
+ throw err;
1126
+ }
1127
+ }
1128
+ async addRoleMember(roleName, memberId) {
1129
+ await this.bot().guilds.addMemberRole(this.guild(), memberId, (await this.roleNamed(roleName)).id);
1130
+ }
1131
+ async removeRoleMember(roleName, memberId) {
1132
+ await this.bot().guilds.removeMemberRole(this.guild(), memberId, (await this.roleNamed(roleName)).id);
1133
+ }
1049
1134
  async ensureRole(input) {
1050
1135
  const bot = this.bot();
1051
1136
  const color = input.color !== void 0 ? colorToInt(input.color) : void 0;
@@ -1154,6 +1239,16 @@ async function verifyToken(webhookUrl, opts = {}) {
1154
1239
  function createContext(options = {}) {
1155
1240
  let url;
1156
1241
  let bot;
1242
+ let applicationId;
1243
+ const botClient = () => bot ??= createDiscordBotClient({
1244
+ botToken: resolveBotToken({
1245
+ env: options.env,
1246
+ keyring: options.keyring,
1247
+ org: options.org
1248
+ }),
1249
+ ...options.unsafeBotBaseUrl && options.baseUrl ? { baseUrl: options.baseUrl } : {},
1250
+ ...options.fetch ? { fetch: options.fetch } : {}
1251
+ });
1157
1252
  return {
1158
1253
  options,
1159
1254
  client: createDiscordClient({
@@ -1161,19 +1256,28 @@ function createContext(options = {}) {
1161
1256
  fetch: options.fetch
1162
1257
  }),
1163
1258
  defaultWebhookUrl: () => url ??= resolveToken(options),
1164
- bot: () => bot ??= createDiscordBotClient({
1165
- botToken: resolveBotToken({
1166
- env: options.env,
1167
- keyring: options.keyring,
1168
- org: options.org
1169
- }),
1170
- ...options.unsafeBotBaseUrl && options.baseUrl ? { baseUrl: options.baseUrl } : {},
1171
- ...options.fetch ? { fetch: options.fetch } : {}
1172
- })
1259
+ bot: botClient,
1260
+ oauth: async (redirectUri) => {
1261
+ applicationId ??= botClient().application.get().then((app) => app.id).catch((err) => {
1262
+ applicationId = void 0;
1263
+ throw err;
1264
+ });
1265
+ return createDiscordOAuthClient({
1266
+ clientId: await applicationId,
1267
+ clientSecret: resolveClientSecret({
1268
+ env: options.env,
1269
+ keyring: options.keyring,
1270
+ org: options.org
1271
+ }),
1272
+ redirectUri,
1273
+ ...options.unsafeBotBaseUrl && options.baseUrl ? { baseUrl: options.baseUrl } : {},
1274
+ ...options.fetch ? { fetch: options.fetch } : {}
1275
+ });
1276
+ }
1173
1277
  };
1174
1278
  }
1175
1279
  function notifications(ctx) {
1176
- return new DiscordNotifications(ctx.client, ctx.options, ctx.defaultWebhookUrl, ctx.bot);
1280
+ return new DiscordNotifications(ctx.client, ctx.options, ctx.defaultWebhookUrl, ctx.bot, ctx.oauth);
1177
1281
  }
1178
1282
  function createPlugin(options = {}) {
1179
1283
  const ctx = createContext(options);
@@ -1184,4 +1288,4 @@ function createPlugin(options = {}) {
1184
1288
  }
1185
1289
  const AUTH_HINT = "create a webhook in Discord: open your server → channel settings → Integrations → Webhooks → New Webhook, copy the webhook URL, then run: holocron auth set discord <https://discord.com/api/webhooks/...>";
1186
1290
  //#endregion
1187
- export { AUTH_HINT, AuthError, DiscordNotifications, createContext, createDiscordClient, createPlugin, notifications, parseWebhookUrl, resolveBotToken, resolveToken, verifyToken };
1291
+ export { AUTH_HINT, AuthError, DiscordNotifications, createContext, createDiscordClient, createPlugin, notifications, parseWebhookUrl, resolveBotToken, resolveClientSecret, resolveToken, verifyToken };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theholocron/holocron-plugin-discord",
3
- "version": "5.0.0-alpha.199",
3
+ "version": "5.0.0-alpha.200",
4
4
  "description": "Holocron plugin for Discord. Implements the notifications capability via Discord incoming webhooks.",
5
5
  "keywords": [
6
6
  "discord",
@@ -30,7 +30,7 @@
30
30
  "dist"
31
31
  ],
32
32
  "devDependencies": {
33
- "@theholocron/discord-client": "^1.45.0",
33
+ "@theholocron/discord-client": "^1.48.0",
34
34
  "@theholocron/eslint-config": "^8.8.2",
35
35
  "@theholocron/http-client": "^1.43.1",
36
36
  "@theholocron/misc-utils": "^1.16.0",
@@ -48,12 +48,12 @@
48
48
  "tsx": "4.23.15",
49
49
  "typescript": "^5.9.3",
50
50
  "vitest": "^4.1.11",
51
- "@theholocron/cli": "5.0.0-alpha.199"
51
+ "@theholocron/cli": "5.0.0-alpha.200"
52
52
  },
53
53
  "peerDependencies": {
54
- "@theholocron/discord-client": "^1.45.0",
54
+ "@theholocron/discord-client": "^1.48.0",
55
55
  "@theholocron/misc-utils": "^1.16.0",
56
- "@theholocron/cli": "5.0.0-alpha.199"
56
+ "@theholocron/cli": "5.0.0-alpha.200"
57
57
  },
58
58
  "engines": {
59
59
  "node": ">=22"