mini-interactions 0.0.0-stage → 0.16.0
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/LICENSE +21 -0
- package/MIGRATION.md +126 -0
- package/README.md +303 -2
- package/dist/bot.d.ts +113 -0
- package/dist/bot.js +293 -0
- package/dist/builders/ActionRowBuilder.d.ts +22 -0
- package/dist/builders/ActionRowBuilder.js +33 -0
- package/dist/builders/AutomodRuleBuilder.d.ts +45 -0
- package/dist/builders/AutomodRuleBuilder.js +151 -0
- package/dist/builders/ButtonBuilder.d.ts +53 -0
- package/dist/builders/ButtonBuilder.js +124 -0
- package/dist/builders/ChannelSelectMenuBuilder.d.ts +53 -0
- package/dist/builders/ChannelSelectMenuBuilder.js +105 -0
- package/dist/builders/CheckboxBuilder.d.ts +20 -0
- package/dist/builders/CheckboxBuilder.js +20 -0
- package/dist/builders/CheckboxGroupBuilder.d.ts +25 -0
- package/dist/builders/CheckboxGroupBuilder.js +48 -0
- package/dist/builders/EmbedBuilder.d.ts +33 -0
- package/dist/builders/EmbedBuilder.js +103 -0
- package/dist/builders/FileUploadBuilder.d.ts +17 -0
- package/dist/builders/FileUploadBuilder.js +22 -0
- package/dist/builders/LabelBuilder.d.ts +16 -0
- package/dist/builders/LabelBuilder.js +21 -0
- package/dist/builders/MiniContainerBuilder.d.ts +131 -0
- package/dist/builders/MiniContainerBuilder.js +347 -0
- package/dist/builders/ModalBuilder.d.ts +16 -0
- package/dist/builders/ModalBuilder.js +36 -0
- package/dist/builders/ModalChannelSelectMenuBuilder.d.ts +29 -0
- package/dist/builders/ModalChannelSelectMenuBuilder.js +25 -0
- package/dist/builders/ModalMentionableSelectMenuBuilder.d.ts +53 -0
- package/dist/builders/ModalMentionableSelectMenuBuilder.js +87 -0
- package/dist/builders/ModalRoleSelectMenuBuilder.d.ts +27 -0
- package/dist/builders/ModalRoleSelectMenuBuilder.js +24 -0
- package/dist/builders/ModalStringSelectMenuBuilder.d.ts +62 -0
- package/dist/builders/ModalStringSelectMenuBuilder.js +120 -0
- package/dist/builders/ModalUserSelectMenuBuilder.d.ts +53 -0
- package/dist/builders/ModalUserSelectMenuBuilder.js +96 -0
- package/dist/builders/RadioBuilder.d.ts +22 -0
- package/dist/builders/RadioBuilder.js +36 -0
- package/dist/builders/RoleSelectMenuBuilder.d.ts +47 -0
- package/dist/builders/RoleSelectMenuBuilder.js +92 -0
- package/dist/builders/StringSelectMenuBuilder.d.ts +52 -0
- package/dist/builders/StringSelectMenuBuilder.js +104 -0
- package/dist/builders/StringSelectMenuOptionBuilder.d.ts +46 -0
- package/dist/builders/StringSelectMenuOptionBuilder.js +106 -0
- package/dist/builders/TextInputBuilder.d.ts +23 -0
- package/dist/builders/TextInputBuilder.js +26 -0
- package/dist/builders/index.d.ts +44 -0
- package/dist/builders/index.js +22 -0
- package/dist/builders/shared.d.ts +8 -0
- package/dist/builders/shared.js +11 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +71 -0
- package/dist/commands/CommandBuilder.d.ts +278 -0
- package/dist/commands/CommandBuilder.js +687 -0
- package/dist/commands/ContextMenuCommandBuilder.d.ts +94 -0
- package/dist/commands/ContextMenuCommandBuilder.js +145 -0
- package/dist/core/http/DiscordRestClient.d.ts +400 -0
- package/dist/core/http/DiscordRestClient.js +988 -0
- package/dist/core/interactions/InteractionContext.d.ts +33 -0
- package/dist/core/interactions/InteractionContext.js +61 -0
- package/dist/core/interactions/InteractionVerifier.d.ts +8 -0
- package/dist/core/interactions/InteractionVerifier.js +9 -0
- package/dist/core/messages/DiscordSentMessage.d.ts +32 -0
- package/dist/core/messages/DiscordSentMessage.js +64 -0
- package/dist/core/messages/message-payloads.d.ts +94 -0
- package/dist/core/messages/message-payloads.js +99 -0
- package/dist/core/webhooks/DiscordWebhook.d.ts +14 -0
- package/dist/core/webhooks/DiscordWebhook.js +69 -0
- package/dist/database/MiniDataBuilder.d.ts +61 -0
- package/dist/database/MiniDataBuilder.js +98 -0
- package/dist/database/MiniDatabase.d.ts +67 -0
- package/dist/database/MiniDatabase.js +222 -0
- package/dist/database/MiniDatabaseBuilder.d.ts +58 -0
- package/dist/database/MiniDatabaseBuilder.js +84 -0
- package/dist/database/index.d.ts +5 -0
- package/dist/database/index.js +3 -0
- package/dist/identity/ApplicationIdentityProfile.d.ts +188 -0
- package/dist/identity/ApplicationIdentityProfile.js +207 -0
- package/dist/index.d.ts +54 -0
- package/dist/index.js +34 -0
- package/dist/lobby/Lobby.d.ts +150 -0
- package/dist/lobby/Lobby.js +90 -0
- package/dist/node/MiniInteraction.d.ts +199 -0
- package/dist/node/MiniInteraction.js +861 -0
- package/dist/node/index.d.ts +2 -0
- package/dist/node/index.js +1 -0
- package/dist/oauth2/DiscordOAuth.d.ts +49 -0
- package/dist/oauth2/DiscordOAuth.js +113 -0
- package/dist/oauth2/OAuth2Builder.d.ts +296 -0
- package/dist/oauth2/OAuth2Builder.js +435 -0
- package/dist/oauth2/OAuth2Scopes.d.ts +285 -0
- package/dist/oauth2/OAuth2Scopes.js +438 -0
- package/dist/oauth2/OAuthTokenStorage.d.ts +37 -0
- package/dist/oauth2/OAuthTokenStorage.js +109 -0
- package/dist/oauth2/index.d.ts +8 -0
- package/dist/oauth2/index.js +4 -0
- package/dist/router/AutocompleteContext.d.ts +36 -0
- package/dist/router/AutocompleteContext.js +82 -0
- package/dist/router/InteractionRouter.d.ts +82 -0
- package/dist/router/InteractionRouter.js +225 -0
- package/dist/types/ButtonStyle.d.ts +16 -0
- package/dist/types/ButtonStyle.js +17 -0
- package/dist/types/ChannelType.d.ts +2 -0
- package/dist/types/ChannelType.js +2 -0
- package/dist/types/Commands.d.ts +35 -0
- package/dist/types/Commands.js +1 -0
- package/dist/types/ComponentTypes.d.ts +19 -0
- package/dist/types/ComponentTypes.js +1 -0
- package/dist/types/InteractionFlags.d.ts +5 -0
- package/dist/types/InteractionFlags.js +6 -0
- package/dist/types/PermissionFlags.d.ts +56 -0
- package/dist/types/PermissionFlags.js +5 -0
- package/dist/types/RoleConnectionMetadata.d.ts +14 -0
- package/dist/types/RoleConnectionMetadata.js +1 -0
- package/dist/types/RoleConnectionMetadataTypes.d.ts +11 -0
- package/dist/types/RoleConnectionMetadataTypes.js +12 -0
- package/dist/types/SeparatorSpacingSize.d.ts +2 -0
- package/dist/types/SeparatorSpacingSize.js +2 -0
- package/dist/types/checkbox.d.ts +16 -0
- package/dist/types/checkbox.js +12 -0
- package/dist/types/discord.d.ts +2 -0
- package/dist/types/discord.js +1 -0
- package/dist/types/radio.d.ts +12 -0
- package/dist/types/radio.js +10 -0
- package/dist/types/validation.d.ts +14 -0
- package/dist/types/validation.js +40 -0
- package/dist/utils/CommandInteractionOptions.d.ts +66 -0
- package/dist/utils/CommandInteractionOptions.js +364 -0
- package/dist/utils/ContextMenuInteraction.d.ts +76 -0
- package/dist/utils/ContextMenuInteraction.js +152 -0
- package/dist/utils/MessageComponentInteraction.d.ts +148 -0
- package/dist/utils/MessageComponentInteraction.js +259 -0
- package/dist/utils/ModalSubmitInteraction.d.ts +86 -0
- package/dist/utils/ModalSubmitInteraction.js +267 -0
- package/dist/utils/cdn.d.ts +30 -0
- package/dist/utils/cdn.js +60 -0
- package/dist/utils/formatting.d.ts +76 -0
- package/dist/utils/formatting.js +132 -0
- package/dist/utils/interactionMessageHelpers.d.ts +40 -0
- package/dist/utils/interactionMessageHelpers.js +118 -0
- package/dist/utils/localization.d.ts +25 -0
- package/dist/utils/localization.js +38 -0
- package/dist/utils/snowflake.d.ts +19 -0
- package/dist/utils/snowflake.js +32 -0
- package/dist/webhooks/WebhookEvent.d.ts +229 -0
- package/dist/webhooks/WebhookEvent.js +59 -0
- package/dist/webhooks/WebhookEventRouter.d.ts +123 -0
- package/dist/webhooks/WebhookEventRouter.js +160 -0
- package/dist/webhooks/WebhookEventVerifier.d.ts +33 -0
- package/dist/webhooks/WebhookEventVerifier.js +37 -0
- package/dist/webhooks/index.d.ts +6 -0
- package/dist/webhooks/index.js +3 -0
- package/package.json +93 -4
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
import { OAUTH2_AUTHORIZE_URL, OAUTH2_ME_URL, OAUTH2_REVOKE_URL, OAUTH2_TOKEN_URL, OAuth2Scope, OAuth2ScopeMetadata, OAuth2ScopePresets, describeOAuth2Scopes, isOAuth2Scope, requiresOAuth2ScopeApproval, } from "./OAuth2Scopes.js";
|
|
2
|
+
/**
|
|
3
|
+
* A fluent builder for Discord's OAuth2 flows, plus typed clients for the token
|
|
4
|
+
* endpoints.
|
|
5
|
+
*
|
|
6
|
+
* ```ts
|
|
7
|
+
* const oauth = new OAuth2Builder({
|
|
8
|
+
* clientId: process.env.DISCORD_CLIENT_ID!,
|
|
9
|
+
* clientSecret: process.env.DISCORD_CLIENT_SECRET!,
|
|
10
|
+
* redirectUri: "https://example.com/api/discord-oauth-callback",
|
|
11
|
+
* }).addScopes(...OAuth2ScopePresets.SignIn);
|
|
12
|
+
*
|
|
13
|
+
* const { url, state } = oauth.build(); // send the user here
|
|
14
|
+
* const tokens = await oauth.exchangeCode(code); // in the callback
|
|
15
|
+
* ```
|
|
16
|
+
*
|
|
17
|
+
* Everything here is Fetch-API only — no Node built-ins — so the same instance
|
|
18
|
+
* works in a Vercel function, a Cloudflare Worker or a long-lived server.
|
|
19
|
+
*
|
|
20
|
+
* @see {@link https://docs.discord.com/developers/topics/oauth2}
|
|
21
|
+
*/
|
|
22
|
+
export class OAuth2Builder {
|
|
23
|
+
clientId;
|
|
24
|
+
clientSecret;
|
|
25
|
+
fetchImpl;
|
|
26
|
+
scopes;
|
|
27
|
+
redirectUri;
|
|
28
|
+
state;
|
|
29
|
+
responseType = "code";
|
|
30
|
+
prompt = "consent";
|
|
31
|
+
permissions;
|
|
32
|
+
guildId;
|
|
33
|
+
disableGuildSelect = false;
|
|
34
|
+
integrationType;
|
|
35
|
+
teamApplication = false;
|
|
36
|
+
constructor(options) {
|
|
37
|
+
if (!options.clientId)
|
|
38
|
+
throw new TypeError("[OAuth2Builder] clientId is required.");
|
|
39
|
+
this.clientId = options.clientId;
|
|
40
|
+
this.clientSecret = options.clientSecret;
|
|
41
|
+
this.fetchImpl = options.fetch ?? fetch;
|
|
42
|
+
this.redirectUri = options.redirectUri;
|
|
43
|
+
this.scopes = options.scopes ? normalizeScopes(options.scopes) : [];
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Starts from the Social SDK's `GetDefaultCommunicationScopes`, i.e. the set
|
|
47
|
+
* **Linked Channels** requires: `openid sdk.social_layer`.
|
|
48
|
+
*
|
|
49
|
+
* ```ts
|
|
50
|
+
* OAuth2Builder.communication({ clientId, clientSecret, redirectUri })
|
|
51
|
+
* ```
|
|
52
|
+
*/
|
|
53
|
+
static communication(options) {
|
|
54
|
+
return new OAuth2Builder({
|
|
55
|
+
...options,
|
|
56
|
+
scopes: [...OAuth2ScopePresets.SocialCommunication],
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Starts from the Social SDK's `GetDefaultPresenceScopes`
|
|
61
|
+
* (`openid sdk.social_layer_presence`) — account linking, friends and rich
|
|
62
|
+
* presence, but no messaging or Linked Channels.
|
|
63
|
+
*/
|
|
64
|
+
static presence(options) {
|
|
65
|
+
return new OAuth2Builder({ ...options, scopes: [...OAuth2ScopePresets.SocialPresence] });
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Starts from the plain user-install sign-in set (`identify email`), the
|
|
69
|
+
* usual starting point for a dashboard that reads `/users/@me`.
|
|
70
|
+
*/
|
|
71
|
+
static signIn(options) {
|
|
72
|
+
return new OAuth2Builder({ ...options, scopes: [...OAuth2ScopePresets.SignIn] });
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* A bot-invite URL: no `response_type`, no `redirect_uri` — Discord adds the
|
|
76
|
+
* bot to the selected server and redirects nowhere.
|
|
77
|
+
*
|
|
78
|
+
* Pass `permissions` for the bot's permission integer and `guildId` to
|
|
79
|
+
* preselect a server, optionally locking the picker with
|
|
80
|
+
* `disableGuildSelect`.
|
|
81
|
+
*/
|
|
82
|
+
static bot(options) {
|
|
83
|
+
const builder = new OAuth2Builder({
|
|
84
|
+
...options,
|
|
85
|
+
scopes: [OAuth2Scope.Bot, OAuth2Scope.ApplicationsCommands],
|
|
86
|
+
}).setResponseType(undefined);
|
|
87
|
+
if (options.permissions !== undefined)
|
|
88
|
+
builder.setPermissions(options.permissions);
|
|
89
|
+
if (options.guildId)
|
|
90
|
+
builder.setGuildId(options.guildId);
|
|
91
|
+
if (options.disableGuildSelect)
|
|
92
|
+
builder.setDisableGuildSelect(true);
|
|
93
|
+
if (options.integrationType !== undefined) {
|
|
94
|
+
builder.setIntegrationType(options.integrationType);
|
|
95
|
+
}
|
|
96
|
+
return builder;
|
|
97
|
+
}
|
|
98
|
+
/** Replaces the requested scopes. Duplicates and blanks are dropped; order is preserved. */
|
|
99
|
+
setScopes(scopes) {
|
|
100
|
+
this.scopes = normalizeScopes(scopes);
|
|
101
|
+
return this;
|
|
102
|
+
}
|
|
103
|
+
/** Appends scopes, ignoring ones already requested. */
|
|
104
|
+
addScopes(...scopes) {
|
|
105
|
+
return this.setScopes([...this.scopes, ...scopes]);
|
|
106
|
+
}
|
|
107
|
+
/** Removes scopes; names that are not currently requested are ignored. */
|
|
108
|
+
removeScopes(...scopes) {
|
|
109
|
+
const drop = new Set(scopes);
|
|
110
|
+
return this.setScopes(this.scopes.filter((scope) => !drop.has(scope)));
|
|
111
|
+
}
|
|
112
|
+
/** The scopes requested so far, in request order. */
|
|
113
|
+
getScopes() {
|
|
114
|
+
return [...this.scopes];
|
|
115
|
+
}
|
|
116
|
+
/** Where Discord sends the user after they approve. */
|
|
117
|
+
setRedirectUri(redirectUri) {
|
|
118
|
+
this.redirectUri = redirectUri ?? undefined;
|
|
119
|
+
return this;
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Pins the CSRF `state`. Discord returns it untouched on the redirect and you
|
|
123
|
+
* **must** compare it against the value bound to the user's session.
|
|
124
|
+
*
|
|
125
|
+
* When unset, {@link build} generates a cryptographically random one.
|
|
126
|
+
*/
|
|
127
|
+
setState(state) {
|
|
128
|
+
this.state = state ?? undefined;
|
|
129
|
+
return this;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* `code` (authorization code grant, the default) or `token` (implicit grant,
|
|
133
|
+
* for browser-only clients that cannot keep a secret).
|
|
134
|
+
*
|
|
135
|
+
* Pass `undefined` for the bot flow, which has no response type at all.
|
|
136
|
+
*/
|
|
137
|
+
setResponseType(responseType) {
|
|
138
|
+
this.responseType = responseType;
|
|
139
|
+
return this;
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* `consent` forces the approval screen even for an existing authorization;
|
|
143
|
+
* `none` skips it. Passthrough scopes (`bot`, `webhook.incoming`) always ask.
|
|
144
|
+
*/
|
|
145
|
+
setPrompt(prompt) {
|
|
146
|
+
this.prompt = prompt;
|
|
147
|
+
return this;
|
|
148
|
+
}
|
|
149
|
+
/** Bot permissions as an integer; bigints are serialised exactly. */
|
|
150
|
+
setPermissions(permissions) {
|
|
151
|
+
this.permissions =
|
|
152
|
+
typeof permissions === "bigint" ? permissions.toString() : String(permissions);
|
|
153
|
+
return this;
|
|
154
|
+
}
|
|
155
|
+
/** Preselects a server in the bot-invite picker. */
|
|
156
|
+
setGuildId(guildId) {
|
|
157
|
+
this.guildId = guildId ?? undefined;
|
|
158
|
+
return this;
|
|
159
|
+
}
|
|
160
|
+
/** Locks the bot-invite picker to {@link setGuildId}'s server. */
|
|
161
|
+
setDisableGuildSelect(disableGuildSelect = true) {
|
|
162
|
+
this.disableGuildSelect = disableGuildSelect;
|
|
163
|
+
return this;
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Where the app installs: `0` for a server, `1` for the user's account.
|
|
167
|
+
*
|
|
168
|
+
* Only meaningful when the scopes include `applications.commands`, and the app
|
|
169
|
+
* must be configured in the Developer Portal to support the context.
|
|
170
|
+
*/
|
|
171
|
+
setIntegrationType(integrationType) {
|
|
172
|
+
this.integrationType = integrationType ?? undefined;
|
|
173
|
+
return this;
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Marks the application as team-owned, which restricts the client credentials
|
|
177
|
+
* grant to `identify` and `applications.commands.update`.
|
|
178
|
+
*/
|
|
179
|
+
setTeamApplication(teamApplication = true) {
|
|
180
|
+
this.teamApplication = teamApplication;
|
|
181
|
+
return this;
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Builds the authorization URL. Generates a `state` when none was set, and
|
|
185
|
+
* validates the scope/grant combination first — see {@link OAuth2BuilderError}.
|
|
186
|
+
*/
|
|
187
|
+
build() {
|
|
188
|
+
this.validate();
|
|
189
|
+
const url = new URL(OAUTH2_AUTHORIZE_URL);
|
|
190
|
+
url.searchParams.set("client_id", this.clientId);
|
|
191
|
+
if (this.responseType) {
|
|
192
|
+
url.searchParams.set("response_type", this.responseType);
|
|
193
|
+
url.searchParams.set("prompt", this.prompt);
|
|
194
|
+
}
|
|
195
|
+
url.searchParams.set("scope", this.scopes.join(" "));
|
|
196
|
+
if (this.redirectUri)
|
|
197
|
+
url.searchParams.set("redirect_uri", this.redirectUri);
|
|
198
|
+
if (this.permissions)
|
|
199
|
+
url.searchParams.set("permissions", this.permissions);
|
|
200
|
+
if (this.guildId)
|
|
201
|
+
url.searchParams.set("guild_id", this.guildId);
|
|
202
|
+
if (this.disableGuildSelect)
|
|
203
|
+
url.searchParams.set("disable_guild_select", "true");
|
|
204
|
+
if (this.integrationType !== undefined) {
|
|
205
|
+
url.searchParams.set("integration_type", String(this.integrationType));
|
|
206
|
+
}
|
|
207
|
+
const state = this.state ?? randomState();
|
|
208
|
+
this.state = state;
|
|
209
|
+
url.searchParams.set("state", state);
|
|
210
|
+
return {
|
|
211
|
+
url: url.toString(),
|
|
212
|
+
state,
|
|
213
|
+
scopes: [...this.scopes],
|
|
214
|
+
responseType: this.responseType,
|
|
215
|
+
/** Scopes that need Discord's approval before this flow will work. */
|
|
216
|
+
requiresApproval: requiresOAuth2ScopeApproval(this.scopes),
|
|
217
|
+
/** Ready-to-render consent copy for the requested scopes. */
|
|
218
|
+
consent: describeOAuth2Scopes(this.scopes),
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
/** The authorization URL from {@link build}, for callers that ignore the rest. */
|
|
222
|
+
toURL() {
|
|
223
|
+
return this.build().url;
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* The requested scopes grouped for a consent screen, with the copy from
|
|
227
|
+
* `OAuth2ScopeMetadata`.
|
|
228
|
+
*
|
|
229
|
+
* ```ts
|
|
230
|
+
* oauth.describeScopes();
|
|
231
|
+
* // [{ category: "identity", scopes: [{ scope: "identify", description: "…" }] }]
|
|
232
|
+
* ```
|
|
233
|
+
*/
|
|
234
|
+
describeScopes() {
|
|
235
|
+
const grouped = new Map();
|
|
236
|
+
for (const entry of describeOAuth2Scopes(this.scopes)) {
|
|
237
|
+
const category = isOAuth2Scope(entry.scope)
|
|
238
|
+
? OAuth2ScopeMetadata[entry.scope].category
|
|
239
|
+
: "identity";
|
|
240
|
+
const bucket = grouped.get(category) ?? [];
|
|
241
|
+
bucket.push(entry);
|
|
242
|
+
grouped.set(category, bucket);
|
|
243
|
+
}
|
|
244
|
+
return Array.from(grouped, ([category, scopes]) => ({ category, scopes }));
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Exchanges the `code` from the redirect for tokens — the authorization code
|
|
248
|
+
* grant. Needs `clientSecret` and the same `redirect_uri` used in the
|
|
249
|
+
* authorization request.
|
|
250
|
+
*
|
|
251
|
+
* On a `webhook.incoming` flow the response also carries `webhook`; store its
|
|
252
|
+
* `id` and `token` immediately, they are the only copy you get.
|
|
253
|
+
*/
|
|
254
|
+
async exchangeCode(code, options = {}) {
|
|
255
|
+
const body = new URLSearchParams({ grant_type: "authorization_code", code });
|
|
256
|
+
if (this.redirectUri)
|
|
257
|
+
body.set("redirect_uri", this.redirectUri);
|
|
258
|
+
return this.tokenRequest(body, options);
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* Exchanges a refresh token for a fresh access token. Discord may rotate the
|
|
262
|
+
* refresh token, so always persist the one in the response.
|
|
263
|
+
*/
|
|
264
|
+
async refresh(refreshToken, options = {}) {
|
|
265
|
+
return this.tokenRequest(new URLSearchParams({ grant_type: "refresh_token", refresh_token: refreshToken }), options);
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Requests an application-level Bearer token with no user context, for testing
|
|
269
|
+
* or for the `applications.commands.update` route.
|
|
270
|
+
*
|
|
271
|
+
* Team-owned applications may only ask for `identify` and
|
|
272
|
+
* `applications.commands.update`; mark the client with
|
|
273
|
+
* {@link setTeamApplication} to have that enforced locally instead of by a
|
|
274
|
+
* confusing API error.
|
|
275
|
+
*/
|
|
276
|
+
async clientCredentials(scopes = this.scopes, options = {}) {
|
|
277
|
+
const requested = normalizeScopes(scopes);
|
|
278
|
+
if (this.teamApplication) {
|
|
279
|
+
const allowed = new Set([
|
|
280
|
+
OAuth2Scope.Identify,
|
|
281
|
+
OAuth2Scope.ApplicationsCommandsUpdate,
|
|
282
|
+
]);
|
|
283
|
+
const unexpected = requested.filter((scope) => !allowed.has(scope));
|
|
284
|
+
if (unexpected.length > 0) {
|
|
285
|
+
throw new OAuth2BuilderError(`Team applications may only request ${[...allowed].join(", ")} with the client credentials grant; got ${unexpected.join(", ")}.`, "team_scopes_restricted");
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
return this.tokenRequest(new URLSearchParams({ grant_type: "client_credentials", scope: requested.join(" ") }), options);
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* Revokes an access **or** refresh token.
|
|
292
|
+
*
|
|
293
|
+
* Revocation is authorization-wide: every token issued from the same
|
|
294
|
+
* authorization dies, whichever token you pass and whatever hint you give.
|
|
295
|
+
* For a Social SDK game this is what triggers `APPLICATION_DEAUTHORIZED`.
|
|
296
|
+
*/
|
|
297
|
+
async revokeToken(token, tokenTypeHint, options = {}) {
|
|
298
|
+
await this.requireClientSecret();
|
|
299
|
+
const body = new URLSearchParams({ token });
|
|
300
|
+
if (tokenTypeHint)
|
|
301
|
+
body.set("token_type_hint", tokenTypeHint);
|
|
302
|
+
await this.formRequest(OAUTH2_REVOKE_URL, body, options);
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* Reads what the current Bearer token is actually allowed to do
|
|
306
|
+
* (`GET /oauth2/@me`) — the only reliable way to learn the granted scopes,
|
|
307
|
+
* since users may decline individual ones.
|
|
308
|
+
*/
|
|
309
|
+
async getAuthorizationInfo(accessToken) {
|
|
310
|
+
const response = await this.request(OAUTH2_ME_URL, {
|
|
311
|
+
headers: { Authorization: `Bearer ${accessToken}` },
|
|
312
|
+
});
|
|
313
|
+
const body = (await response.json());
|
|
314
|
+
return { ...body, scopes: (body.scopes ?? []).map((scope) => scope) };
|
|
315
|
+
}
|
|
316
|
+
/** Resolves the current user from a Bearer token. Requires the `identify` scope. */
|
|
317
|
+
async getUser(accessToken) {
|
|
318
|
+
return (await this.getAuthorizationInfo(accessToken)).user;
|
|
319
|
+
}
|
|
320
|
+
validate() {
|
|
321
|
+
if (this.scopes.length === 0) {
|
|
322
|
+
throw new OAuth2BuilderError("At least one scope is required.", "missing_scope");
|
|
323
|
+
}
|
|
324
|
+
if (this.responseType && !this.redirectUri) {
|
|
325
|
+
throw new OAuth2BuilderError(`The ${this.responseType === "code" ? "authorization code" : "implicit"} grant requires a redirectUri.`, "missing_redirect_uri");
|
|
326
|
+
}
|
|
327
|
+
if (this.responseType === "token" && this.scopes.includes(OAuth2Scope.RoleConnectionsWrite)) {
|
|
328
|
+
// Documented restriction: Discord rejects role_connections.write on implicit.
|
|
329
|
+
throw new OAuth2BuilderError("role_connections.write cannot be used with the implicit grant; use the authorization code grant.", "implicit_grant_unsupported_scope");
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
async requireClientSecret() {
|
|
333
|
+
if (!this.clientSecret) {
|
|
334
|
+
throw new OAuth2BuilderError("This flow needs clientSecret for HTTP Basic authentication.", "missing_client_secret");
|
|
335
|
+
}
|
|
336
|
+
return this.clientSecret;
|
|
337
|
+
}
|
|
338
|
+
async tokenRequest(body, options) {
|
|
339
|
+
if (!options.clientCredentialsInBody)
|
|
340
|
+
await this.requireClientSecret();
|
|
341
|
+
const response = await this.formRequest(OAUTH2_TOKEN_URL, body, options);
|
|
342
|
+
return (await response.json());
|
|
343
|
+
}
|
|
344
|
+
async formRequest(url, body, options) {
|
|
345
|
+
if (options.clientCredentialsInBody) {
|
|
346
|
+
body.set("client_id", this.clientId);
|
|
347
|
+
if (this.clientSecret)
|
|
348
|
+
body.set("client_secret", this.clientSecret);
|
|
349
|
+
}
|
|
350
|
+
return this.request(url, {
|
|
351
|
+
method: "POST",
|
|
352
|
+
body,
|
|
353
|
+
headers: {
|
|
354
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
355
|
+
...this.basicAuthHeader(options.clientCredentialsInBody),
|
|
356
|
+
},
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
basicAuthHeader(credentialsInBody) {
|
|
360
|
+
if (credentialsInBody || !this.clientSecret)
|
|
361
|
+
return {};
|
|
362
|
+
return { Authorization: `Basic ${base64(`${this.clientId}:${this.clientSecret}`)}` };
|
|
363
|
+
}
|
|
364
|
+
async request(url, init) {
|
|
365
|
+
const response = await this.fetchImpl(url, init);
|
|
366
|
+
if (!response.ok) {
|
|
367
|
+
const text = await response.text();
|
|
368
|
+
throw new OAuth2RequestError(response.status, text, url);
|
|
369
|
+
}
|
|
370
|
+
return response;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
/**
|
|
374
|
+
* Thrown when an authorization request is contradictory — a combination Discord
|
|
375
|
+
* would reject, caught before the user ever sees a broken consent screen.
|
|
376
|
+
*/
|
|
377
|
+
export class OAuth2BuilderError extends Error {
|
|
378
|
+
code;
|
|
379
|
+
constructor(message, code) {
|
|
380
|
+
super(`[OAuth2Builder] ${message}`);
|
|
381
|
+
this.code = code;
|
|
382
|
+
this.name = "OAuth2BuilderError";
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
/**
|
|
386
|
+
* Thrown when Discord rejects a token or revocation request. The request bodies
|
|
387
|
+
* are form-encoded but the error payload is JSON, so `error` and
|
|
388
|
+
* `errorDescription` are parsed out of `body` when possible.
|
|
389
|
+
*/
|
|
390
|
+
export class OAuth2RequestError extends Error {
|
|
391
|
+
status;
|
|
392
|
+
body;
|
|
393
|
+
url;
|
|
394
|
+
/** Discord's `error` code, e.g. `invalid_grant` or `invalid_client`. */
|
|
395
|
+
error;
|
|
396
|
+
/** Discord's human-readable `error_description`, when present. */
|
|
397
|
+
errorDescription;
|
|
398
|
+
constructor(status, body, url) {
|
|
399
|
+
let parsed = {};
|
|
400
|
+
try {
|
|
401
|
+
parsed = JSON.parse(body);
|
|
402
|
+
}
|
|
403
|
+
catch {
|
|
404
|
+
// A non-JSON body (an HTML error page, a proxy) is kept verbatim in `body`.
|
|
405
|
+
}
|
|
406
|
+
super(`[OAuth2Builder] POST ${url} failed: ${status}${parsed.error ? ` ${parsed.error}` : ""}${parsed.error_description ? ` (${parsed.error_description})` : ""}`);
|
|
407
|
+
this.status = status;
|
|
408
|
+
this.body = body;
|
|
409
|
+
this.url = url;
|
|
410
|
+
this.name = "OAuth2RequestError";
|
|
411
|
+
this.error = parsed.error;
|
|
412
|
+
this.errorDescription = parsed.error_description;
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
function normalizeScopes(scopes) {
|
|
416
|
+
return Array.from(new Set(Array.from(scopes, (scope) => String(scope).trim()).filter(Boolean)));
|
|
417
|
+
}
|
|
418
|
+
function randomState() {
|
|
419
|
+
const cryptoApi = globalThis.crypto;
|
|
420
|
+
if (cryptoApi?.randomUUID)
|
|
421
|
+
return cryptoApi.randomUUID();
|
|
422
|
+
if (cryptoApi?.getRandomValues) {
|
|
423
|
+
const bytes = cryptoApi.getRandomValues(new Uint8Array(16));
|
|
424
|
+
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
425
|
+
}
|
|
426
|
+
throw new OAuth2BuilderError("No Web Crypto implementation available to generate a state nonce; pass one with setState().", "missing_crypto");
|
|
427
|
+
}
|
|
428
|
+
/** UTF-8 safe base64, without depending on Node's Buffer. */
|
|
429
|
+
function base64(input) {
|
|
430
|
+
const bytes = new TextEncoder().encode(input);
|
|
431
|
+
let binary = "";
|
|
432
|
+
for (const byte of bytes)
|
|
433
|
+
binary += String.fromCharCode(byte);
|
|
434
|
+
return btoa(binary);
|
|
435
|
+
}
|