nuxt-discord 0.1.0 → 0.2.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/dist/module.d.mts +39 -1
- package/dist/module.json +1 -1
- package/dist/module.mjs +119 -11
- package/dist/runtime/acknowledgement.d.ts +2 -1
- package/dist/runtime/acknowledgement.js +44 -12
- package/dist/runtime/client/components/CommandPicker.d.vue.ts +2 -2
- package/dist/runtime/client/components/CommandPicker.vue.d.ts +2 -2
- package/dist/runtime/client/components/CommandReference.d.vue.ts +20 -0
- package/dist/runtime/client/components/CommandReference.vue +21 -0
- package/dist/runtime/client/components/CommandReference.vue.d.ts +20 -0
- package/dist/runtime/client/components/CommandTestBar.vue +0 -3
- package/dist/runtime/client/components/ReferenceContent.d.ts +26 -0
- package/dist/runtime/client/components/ReferenceContent.js +73 -0
- package/dist/runtime/client/components/appearance-select.d.ts +1 -1
- package/dist/runtime/client/components/appearance-select.js +1 -1
- package/dist/runtime/client/reference.css +46 -0
- package/dist/runtime/client/useDiscordCommandReference.d.ts +2 -0
- package/dist/runtime/client/useDiscordCommandReference.js +6 -0
- package/dist/runtime/dashboard/auth.js +3 -13
- package/dist/runtime/dashboard/oauth.d.ts +15 -1
- package/dist/runtime/dashboard/oauth.js +42 -21
- package/dist/runtime/dashboard/origin.d.ts +3 -0
- package/dist/runtime/dashboard/origin.js +15 -0
- package/dist/runtime/dashboard/signin.d.ts +1 -0
- package/dist/runtime/dashboard/signin.js +3 -0
- package/dist/runtime/reference/access.d.ts +6 -0
- package/dist/runtime/reference/access.js +143 -0
- package/dist/runtime/reference/catalog.d.ts +2 -0
- package/dist/runtime/reference/catalog.js +9 -0
- package/dist/runtime/reference/document.d.ts +2 -0
- package/dist/runtime/reference/document.js +22 -0
- package/dist/runtime/reference/hosted.d.ts +2 -0
- package/dist/runtime/reference/hosted.js +16 -0
- package/dist/runtime/reference/oauth.d.ts +2 -0
- package/dist/runtime/reference/oauth.js +4 -0
- package/dist/runtime/server/plugins/discord.js +2 -0
- package/dist/types.d.mts +1 -1
- package/dist/types.d.ts +1 -1
- package/package.json +1 -1
package/dist/module.d.mts
CHANGED
|
@@ -47,6 +47,8 @@ interface NuxtDiscordOptions {
|
|
|
47
47
|
autoStart: boolean;
|
|
48
48
|
/** Build the authenticated dashboard into the production Node server. */
|
|
49
49
|
dashboard?: boolean;
|
|
50
|
+
/** Publish the generated command reference. Disabled by default. */
|
|
51
|
+
reference?: false | DiscordReferenceOptions;
|
|
50
52
|
/**
|
|
51
53
|
* Timeout in milliseconds before an interaction's reactive scope is disposed.
|
|
52
54
|
* This cleans up watchers (reactive replies) and component collectors (buttons).
|
|
@@ -174,6 +176,7 @@ interface SlashCommand {
|
|
|
174
176
|
nsfw?: boolean;
|
|
175
177
|
/** Middleware names from @middleware JSDoc tags */
|
|
176
178
|
middleware?: string[];
|
|
179
|
+
hasRuntimeMiddleware?: boolean;
|
|
177
180
|
/** Interaction contexts where this command is available (Guild=0, BotDM=1, PrivateChannel=2) */
|
|
178
181
|
contexts?: number[];
|
|
179
182
|
defaultMemberPermissions?: string | null;
|
|
@@ -233,8 +236,43 @@ interface ContextMenu {
|
|
|
233
236
|
guilds?: true | string[];
|
|
234
237
|
/** Middleware names from @middleware JSDoc tags */
|
|
235
238
|
middleware?: string[];
|
|
239
|
+
hasRuntimeMiddleware?: boolean;
|
|
236
240
|
nameLocalizations?: LocalizationMap;
|
|
237
241
|
}
|
|
242
|
+
type DiscordReferenceOptions = {
|
|
243
|
+
page?: boolean;
|
|
244
|
+
} & ({
|
|
245
|
+
access: 'public' | 'private' | 'authenticated';
|
|
246
|
+
} | {
|
|
247
|
+
access: 'members';
|
|
248
|
+
guilds?: string[];
|
|
249
|
+
});
|
|
250
|
+
interface DiscordReferenceOption {
|
|
251
|
+
name: string;
|
|
252
|
+
description: string;
|
|
253
|
+
type: 'string' | 'integer' | 'number' | 'boolean' | 'user' | 'channel' | 'role' | 'mentionable' | 'attachment';
|
|
254
|
+
required: boolean;
|
|
255
|
+
hasAutocomplete: boolean;
|
|
256
|
+
choices?: {
|
|
257
|
+
name: string;
|
|
258
|
+
value: string | number;
|
|
259
|
+
}[];
|
|
260
|
+
min?: number;
|
|
261
|
+
max?: number;
|
|
262
|
+
minLength?: number;
|
|
263
|
+
maxLength?: number;
|
|
264
|
+
}
|
|
265
|
+
interface DiscordCommandReference {
|
|
266
|
+
commands: {
|
|
267
|
+
name: string;
|
|
268
|
+
description: string;
|
|
269
|
+
options: DiscordReferenceOption[];
|
|
270
|
+
}[];
|
|
271
|
+
menus: {
|
|
272
|
+
name: string;
|
|
273
|
+
type: 'user' | 'message';
|
|
274
|
+
}[];
|
|
275
|
+
}
|
|
238
276
|
interface DashboardCatalog {
|
|
239
277
|
commands: SlashCommand[];
|
|
240
278
|
menus: ContextMenu[];
|
|
@@ -256,4 +294,4 @@ interface NuxtDiscordContext {
|
|
|
256
294
|
declare const _default: _nuxt_schema.NuxtModule<NuxtDiscordOptions, NuxtDiscordOptions, false>;
|
|
257
295
|
|
|
258
296
|
export { _default as default, slashCommandOptionTypeIdentifiers, typeIdentifierToEnum };
|
|
259
|
-
export type { ContextMenu, DashboardCatalog, DiscordRuntimeConfig, Listener, Mentionable, MiddlewareEntry, NuxtDiscordContext, NuxtDiscordOptions, SlashCommand, SlashCommandAttachmentOption, SlashCommandBooleanOption, SlashCommandChannelOption, SlashCommandCustomReturnHandler, SlashCommandIntegerOption, SlashCommandMentionableOption, SlashCommandNumberOption, SlashCommandOption, SlashCommandOptionBase, SlashCommandOptionType, SlashCommandOptionTypeIdentifier, SlashCommandReturnType, SlashCommandRoleOption, SlashCommandRuntime, SlashCommandStringOption, SlashCommandSubcommand, SlashCommandSubcommandGroup, SlashCommandSubcommandGroupRuntime, SlashCommandSubcommandRuntime, SlashCommandUserOption, integer };
|
|
297
|
+
export type { ContextMenu, DashboardCatalog, DiscordCommandReference, DiscordReferenceOption, DiscordReferenceOptions, DiscordRuntimeConfig, Listener, Mentionable, MiddlewareEntry, NuxtDiscordContext, NuxtDiscordOptions, SlashCommand, SlashCommandAttachmentOption, SlashCommandBooleanOption, SlashCommandChannelOption, SlashCommandCustomReturnHandler, SlashCommandIntegerOption, SlashCommandMentionableOption, SlashCommandNumberOption, SlashCommandOption, SlashCommandOptionBase, SlashCommandOptionType, SlashCommandOptionTypeIdentifier, SlashCommandReturnType, SlashCommandRoleOption, SlashCommandRuntime, SlashCommandStringOption, SlashCommandSubcommand, SlashCommandSubcommandGroup, SlashCommandSubcommandGroupRuntime, SlashCommandSubcommandRuntime, SlashCommandUserOption, integer };
|
package/dist/module.json
CHANGED
package/dist/module.mjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import
|
|
1
|
+
import fs, { globSync, readFileSync, writeFileSync, renameSync } from 'node:fs';
|
|
2
|
+
import path, { relative, sep, join } from 'node:path';
|
|
3
|
+
import { createResolver, extendPages, addServerTemplate, addTemplate, addTypeTemplate, updateTemplates, isIgnored, defineNuxtModule, addImports, addComponent, addServerHandler, extendRouteRules, addServerScanDir, addServerPlugin, addServerImportsDir, loadNuxtModuleInstance } from '@nuxt/kit';
|
|
2
4
|
import { ApplicationCommandOptionType, Locale, GatewayIntentBits } from 'discord.js';
|
|
3
5
|
import { logger } from '../dist/runtime/logger.js';
|
|
4
|
-
import fs, { globSync, readFileSync } from 'node:fs';
|
|
5
|
-
import path, { relative, sep } from 'node:path';
|
|
6
6
|
import ts from 'typescript';
|
|
7
7
|
import '../dist/runtime/server/utils/defineMiddleware.js';
|
|
8
8
|
import { resolveMiddlewareTags } from '../dist/runtime/middleware.js';
|
|
9
|
-
import { rm } from 'node:fs/promises';
|
|
9
|
+
import { rm, mkdir } from 'node:fs/promises';
|
|
10
10
|
import { pathToFileURL } from 'node:url';
|
|
11
11
|
import chokidar from 'chokidar';
|
|
12
12
|
import { listen } from 'listhen';
|
|
@@ -35,13 +35,11 @@ function prepareClient(ctx) {
|
|
|
35
35
|
"lucide:blocks",
|
|
36
36
|
"lucide:circle-x",
|
|
37
37
|
"lucide:eye",
|
|
38
|
-
"lucide:gift",
|
|
39
38
|
"lucide:pin",
|
|
40
39
|
"lucide:plus",
|
|
41
40
|
"lucide:send-horizontal",
|
|
42
41
|
"lucide:shapes",
|
|
43
42
|
"lucide:smile",
|
|
44
|
-
"lucide:sticker",
|
|
45
43
|
"simple-icons:discord",
|
|
46
44
|
"simple-icons:github"
|
|
47
45
|
]) icons.add(name);
|
|
@@ -166,6 +164,7 @@ const macros = {
|
|
|
166
164
|
}
|
|
167
165
|
},
|
|
168
166
|
useMiddleware(_ctx, _node, command) {
|
|
167
|
+
command.hasRuntimeMiddleware = true;
|
|
169
168
|
command.middleware ??= [];
|
|
170
169
|
}
|
|
171
170
|
};
|
|
@@ -632,6 +631,7 @@ function processContextMenuFile(ctx, file) {
|
|
|
632
631
|
const sourceFile = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true);
|
|
633
632
|
let type;
|
|
634
633
|
let nameFromDefine;
|
|
634
|
+
let hasRuntimeMiddleware = false;
|
|
635
635
|
ts.forEachChild(sourceFile, (node) => {
|
|
636
636
|
if (ts.isExportAssignment(node) && ts.isCallExpression(node.expression)) {
|
|
637
637
|
const call = node.expression;
|
|
@@ -643,6 +643,7 @@ function processContextMenuFile(ctx, file) {
|
|
|
643
643
|
type = "message";
|
|
644
644
|
}
|
|
645
645
|
if (type && call.arguments.length > 0) {
|
|
646
|
+
hasRuntimeMiddleware = call.arguments.length >= 3;
|
|
646
647
|
const firstArg = call.arguments[0];
|
|
647
648
|
if (ts.isStringLiteral(firstArg)) {
|
|
648
649
|
nameFromDefine = firstArg.text;
|
|
@@ -668,7 +669,7 @@ function processContextMenuFile(ctx, file) {
|
|
|
668
669
|
const middleware = readMiddlewareTags(sourceFile);
|
|
669
670
|
const definition = sourceFile.statements.find(ts.isExportAssignment);
|
|
670
671
|
const guilds = readGuildTags(ts.getJSDocTags(definition));
|
|
671
|
-
return { name, type, path: file, ...guilds && { guilds }, ...middleware.length > 0 ? { middleware } : {} };
|
|
672
|
+
return { name, type, path: file, ...hasRuntimeMiddleware ? { hasRuntimeMiddleware: true } : {}, ...guilds && { guilds }, ...middleware.length > 0 ? { middleware } : {} };
|
|
672
673
|
}
|
|
673
674
|
function getJSDocTag(sourceFile, tagName) {
|
|
674
675
|
let result;
|
|
@@ -815,6 +816,58 @@ function reuseCommandDependencies(entries, updated, changed) {
|
|
|
815
816
|
};
|
|
816
817
|
}
|
|
817
818
|
|
|
819
|
+
function resolveReference(options) {
|
|
820
|
+
if (options === void 0 || options === false)
|
|
821
|
+
return;
|
|
822
|
+
if (!options || !["public", "private", "authenticated", "members"].includes(options.access) || options.page !== void 0 && typeof options.page !== "boolean") {
|
|
823
|
+
throw new Error("discord.reference requires a valid access mode and an optional boolean page setting.");
|
|
824
|
+
}
|
|
825
|
+
if (Object.keys(options).some((key) => !["access", "page", "guilds"].includes(key)))
|
|
826
|
+
throw new Error("discord.reference accepts access, page and guilds.");
|
|
827
|
+
if (options.access === "members") {
|
|
828
|
+
if (options.guilds === void 0)
|
|
829
|
+
return { access: options.access, page: options.page ?? true };
|
|
830
|
+
if (!Array.isArray(options.guilds) || !options.guilds.length || options.guilds.some((id) => typeof id !== "string" || !/^[1-9]\d{0,19}$/.test(id)))
|
|
831
|
+
throw new Error("discord.reference.guilds requires Discord server IDs for members access.");
|
|
832
|
+
return { access: options.access, page: options.page ?? true, guilds: [...new Set(options.guilds)] };
|
|
833
|
+
}
|
|
834
|
+
if ("guilds" in options)
|
|
835
|
+
throw new Error("discord.reference.guilds is used only with members access.");
|
|
836
|
+
return { access: options.access, page: options.page ?? true };
|
|
837
|
+
}
|
|
838
|
+
function restricted(item) {
|
|
839
|
+
return Boolean(item.guilds || item.hasRuntimeMiddleware || item.middleware?.some((name) => name !== "cooldown" && name !== "guildOnly") || "nsfw" in item && item.nsfw || "defaultMemberPermissions" in item && item.defaultMemberPermissions != null);
|
|
840
|
+
}
|
|
841
|
+
function projectOption(option) {
|
|
842
|
+
const type = ApplicationCommandOptionType[option.type].toLowerCase();
|
|
843
|
+
return {
|
|
844
|
+
name: option.name,
|
|
845
|
+
description: option.description,
|
|
846
|
+
type,
|
|
847
|
+
required: option.required,
|
|
848
|
+
hasAutocomplete: option.hasAutocomplete,
|
|
849
|
+
..."min" in option && { min: option.min },
|
|
850
|
+
..."max" in option && { max: option.max },
|
|
851
|
+
..."minLength" in option && { minLength: option.minLength },
|
|
852
|
+
..."maxLength" in option && { maxLength: option.maxLength },
|
|
853
|
+
..."choices" in option && { choices: option.choices?.map(({ name, value }) => ({ name, value })) }
|
|
854
|
+
};
|
|
855
|
+
}
|
|
856
|
+
function projectReference(commands, menus, access) {
|
|
857
|
+
function leaves(tree, prefix = "") {
|
|
858
|
+
return tree.flatMap((command) => {
|
|
859
|
+
if (access !== "private" && restricted(command))
|
|
860
|
+
return [];
|
|
861
|
+
const name = prefix + command.name;
|
|
862
|
+
return command.subcommands.length ? leaves(command.subcommands, `${name} `) : [{ name, description: command.description, options: command.options.map(projectOption) }];
|
|
863
|
+
});
|
|
864
|
+
}
|
|
865
|
+
return {
|
|
866
|
+
commands: leaves(commands).sort((a, b) => a.name.localeCompare(b.name)),
|
|
867
|
+
menus: menus.filter((menu) => access === "private" || !restricted(menu)).map(({ name, type }) => ({ name, type })).sort((a, b) => a.name.localeCompare(b.name))
|
|
868
|
+
};
|
|
869
|
+
}
|
|
870
|
+
|
|
818
871
|
function prepareTemplates(ctx) {
|
|
819
872
|
addServerTemplate({
|
|
820
873
|
filename: "discord/catalog",
|
|
@@ -898,6 +951,11 @@ function prepareTemplates(ctx) {
|
|
|
898
951
|
addTypeTemplate({
|
|
899
952
|
filename: "discord/types.d.ts",
|
|
900
953
|
getContents: () => `
|
|
954
|
+
declare module 'discord/reference' {
|
|
955
|
+
export function getCatalog(): import('nuxt-discord').DiscordCommandReference | Promise<import('nuxt-discord').DiscordCommandReference>
|
|
956
|
+
export const policy: import('nuxt-discord').DiscordReferenceOptions
|
|
957
|
+
export const styles: string
|
|
958
|
+
}
|
|
901
959
|
declare module 'discord/catalog' {
|
|
902
960
|
const catalog: import('nuxt-discord').DashboardCatalog
|
|
903
961
|
export default catalog
|
|
@@ -1061,10 +1119,11 @@ function createRuntimeExport(handler, originalBody) {
|
|
|
1061
1119
|
);
|
|
1062
1120
|
}
|
|
1063
1121
|
|
|
1064
|
-
function prepareHMR(ctx) {
|
|
1122
|
+
function prepareHMR(ctx, liveReferenceFile) {
|
|
1065
1123
|
const { nuxt, options } = ctx;
|
|
1066
1124
|
const watching = nuxt.options.dev && options.watch.enabled;
|
|
1067
1125
|
const commandsDir = ctx.resolve.root(options.dir, "commands") + path.sep;
|
|
1126
|
+
const commandIdPrefix = commandsDir.split(path.sep).join("/");
|
|
1068
1127
|
const hotDir = path.join(nuxt.options.buildDir, "discord", "hmr");
|
|
1069
1128
|
let dependencies = /* @__PURE__ */ new Set();
|
|
1070
1129
|
const updated = /* @__PURE__ */ new Map();
|
|
@@ -1085,6 +1144,13 @@ function prepareHMR(ctx) {
|
|
|
1085
1144
|
});
|
|
1086
1145
|
});
|
|
1087
1146
|
if (watching) {
|
|
1147
|
+
let publishReference = function(snapshot) {
|
|
1148
|
+
if (liveReferenceFile && options.reference) {
|
|
1149
|
+
const catalog = projectReference(snapshot.slashCommands, snapshot.contextMenus, options.reference.access);
|
|
1150
|
+
writeFileSync(`${liveReferenceFile}.tmp`, JSON.stringify(catalog));
|
|
1151
|
+
renameSync(`${liveReferenceFile}.tmp`, liveReferenceFile);
|
|
1152
|
+
}
|
|
1153
|
+
};
|
|
1088
1154
|
const ignoreCommandsDir = (file) => {
|
|
1089
1155
|
if (file === commandsDir.slice(0, -1) || file.startsWith(commandsDir)) {
|
|
1090
1156
|
return true;
|
|
@@ -1121,6 +1187,10 @@ function prepareHMR(ctx) {
|
|
|
1121
1187
|
nuxt.hook("nitro:init", async (nitro) => {
|
|
1122
1188
|
websocket = createWebSocket();
|
|
1123
1189
|
await rm(hotDir, { recursive: true, force: true });
|
|
1190
|
+
if (liveReferenceFile) {
|
|
1191
|
+
await mkdir(hotDir, { recursive: true });
|
|
1192
|
+
publishReference(ctx);
|
|
1193
|
+
}
|
|
1124
1194
|
listener = await listen(() => "Nuxt Discord", websocketOptions);
|
|
1125
1195
|
nitro.options.runtimeConfig.public.discord = {
|
|
1126
1196
|
wsUrl: listener.url.replace("http", "ws")
|
|
@@ -1169,6 +1239,14 @@ function prepareHMR(ctx) {
|
|
|
1169
1239
|
const outputDir = path.join(hotDir, String(version));
|
|
1170
1240
|
try {
|
|
1171
1241
|
const snapshot = { ...ctx };
|
|
1242
|
+
if (liveReferenceFile) {
|
|
1243
|
+
collectContextMenus(snapshot);
|
|
1244
|
+
if (![...changed].some((file) => file.startsWith(commandIdPrefix))) {
|
|
1245
|
+
publishReference(snapshot);
|
|
1246
|
+
ctx.contextMenus = snapshot.contextMenus;
|
|
1247
|
+
continue;
|
|
1248
|
+
}
|
|
1249
|
+
}
|
|
1172
1250
|
collectSlashCommands(snapshot, changed);
|
|
1173
1251
|
const source = getSlashCommandTemplateContent(snapshot, true);
|
|
1174
1252
|
const additions = await buildCommandUpdate(rollupConfig, source, outputDir, initial, updated, changed);
|
|
@@ -1176,6 +1254,10 @@ function prepareHMR(ctx) {
|
|
|
1176
1254
|
changed.forEach((file) => dirty.add(file));
|
|
1177
1255
|
continue;
|
|
1178
1256
|
}
|
|
1257
|
+
if (liveReferenceFile) {
|
|
1258
|
+
publishReference(snapshot);
|
|
1259
|
+
ctx.contextMenus = snapshot.contextMenus;
|
|
1260
|
+
}
|
|
1179
1261
|
ctx.slashCommands = snapshot.slashCommands;
|
|
1180
1262
|
for (const id of changed)
|
|
1181
1263
|
updated.delete(id);
|
|
@@ -1196,7 +1278,8 @@ function prepareHMR(ctx) {
|
|
|
1196
1278
|
building = false;
|
|
1197
1279
|
}
|
|
1198
1280
|
}
|
|
1199
|
-
const
|
|
1281
|
+
const watched = liveReferenceFile ? [commandsDir, ctx.resolve.root(options.dir, "context-menus")] : [commandsDir];
|
|
1282
|
+
const watcher = chokidar.watch(watched, { ignoreInitial: true }).on("all", (event, file) => {
|
|
1200
1283
|
if (["add", "change", "unlink"].includes(event) && file.endsWith(".ts")) {
|
|
1201
1284
|
const id = path.resolve(file).split(path.sep).join("/");
|
|
1202
1285
|
dirty.add(id);
|
|
@@ -1349,8 +1432,33 @@ const module$1 = defineNuxtModule({
|
|
|
1349
1432
|
const ctx = createContext(discordOptions, nuxt);
|
|
1350
1433
|
const development = nuxt.options.dev || nuxt.options._prepare;
|
|
1351
1434
|
const hostedDashboard = !development && discordOptions.dashboard === true;
|
|
1435
|
+
const reference = resolveReference(discordOptions.reference);
|
|
1436
|
+
const liveReferenceFile = reference && nuxt.options.dev && discordOptions.watch.enabled ? join(nuxt.options.buildDir, "discord", "hmr", "reference.json") : void 0;
|
|
1437
|
+
if (reference) {
|
|
1438
|
+
addImports({ name: "useDiscordCommandReference", from: ctx.resolve.module("runtime/client/useDiscordCommandReference") });
|
|
1439
|
+
addComponent({ name: "DiscordCommandReference", filePath: ctx.resolve.module("runtime/client/components/CommandReference.vue") });
|
|
1440
|
+
addServerTemplate({
|
|
1441
|
+
filename: "discord/reference",
|
|
1442
|
+
getContents: () => [
|
|
1443
|
+
liveReferenceFile ? `import { readFile } from 'node:fs/promises'; export async function getCatalog() { return JSON.parse(await readFile(${JSON.stringify(liveReferenceFile)}, 'utf8')) }` : `const catalog = ${JSON.stringify(projectReference(ctx.slashCommands, ctx.contextMenus, reference.access))}; export const getCatalog = () => catalog`,
|
|
1444
|
+
`export const policy = ${JSON.stringify(reference)}`,
|
|
1445
|
+
`export const styles = ${JSON.stringify(readFileSync(ctx.resolve.module("runtime/client/reference.css"), "utf8"))}`
|
|
1446
|
+
].join("\n")
|
|
1447
|
+
});
|
|
1448
|
+
const routes = [{ route: "/api/discord/reference", handler: "catalog" }];
|
|
1449
|
+
if (reference.page)
|
|
1450
|
+
routes.push({ route: "/commands", handler: "document" });
|
|
1451
|
+
if (reference.access !== "public") {
|
|
1452
|
+
for (const action of ["login", "callback", "logout"])
|
|
1453
|
+
routes.push({ route: `/__discord-reference/${action}`, handler: "oauth" });
|
|
1454
|
+
}
|
|
1455
|
+
for (const { route, handler } of routes) {
|
|
1456
|
+
addServerHandler({ route, method: route.endsWith("/logout") ? "post" : "get", handler: ctx.resolve.module(`runtime/reference/${handler}`) });
|
|
1457
|
+
extendRouteRules(route, { prerender: false, cache: false, isr: false, swr: false }, { override: true });
|
|
1458
|
+
}
|
|
1459
|
+
}
|
|
1352
1460
|
if (hostedDashboard) {
|
|
1353
|
-
addServerHandler({ middleware: true, handler: ctx.resolve.module("runtime/dashboard/auth") });
|
|
1461
|
+
addServerHandler({ middleware: true, handler: ctx.resolve.module(reference ? "runtime/reference/hosted" : "runtime/dashboard/auth") });
|
|
1354
1462
|
for (const route of ["/discord", "/discord/**", "/api/discord", "/api/discord/**"])
|
|
1355
1463
|
extendRouteRules(route, { prerender: false, cache: false }, { override: true });
|
|
1356
1464
|
for (const [path, method] of [
|
|
@@ -1460,7 +1568,7 @@ const module$1 = defineNuxtModule({
|
|
|
1460
1568
|
collectContextMenus(ctx);
|
|
1461
1569
|
collectListeners(ctx);
|
|
1462
1570
|
prepareTemplates(ctx);
|
|
1463
|
-
prepareHMR(ctx);
|
|
1571
|
+
prepareHMR(ctx, liveReferenceFile);
|
|
1464
1572
|
}
|
|
1465
1573
|
});
|
|
1466
1574
|
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import type { CommandInteraction, InteractionReplyOptions, MessageCreateOptions, ModalSubmitInteraction } from 'discord.js';
|
|
2
2
|
import type { MessageSenderConfig, SentMessage } from './server/utils/messageSender.js';
|
|
3
|
+
import { MessagePayload } from 'discord.js';
|
|
3
4
|
type ReplyInteraction = CommandInteraction | ModalSubmitInteraction;
|
|
4
5
|
export type DeferPolicy = 'public' | 'private' | 'manual';
|
|
5
6
|
export declare function scheduleAcknowledgement(interaction: ReplyInteraction, policy?: DeferPolicy, allowTimer?: boolean): () => void;
|
|
6
7
|
export declare function wasAutomaticallyDeferred(interaction: ReplyInteraction): boolean;
|
|
7
|
-
export declare function interactionSender(interaction: ReplyInteraction): Omit<MessageSenderConfig, 'send'> & {
|
|
8
|
+
export declare function interactionSender(interaction: ReplyInteraction, source?: MessagePayload): Omit<MessageSenderConfig, 'send'> & {
|
|
8
9
|
send: (opts: InteractionReplyOptions | MessageCreateOptions) => Promise<SentMessage>;
|
|
9
10
|
};
|
|
10
11
|
export {};
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { MessageFlags, MessageFlagsBitField, MessagePayload } from "discord.js";
|
|
2
2
|
import { logDiscordFailure } from "./diagnostics.js";
|
|
3
|
-
const
|
|
3
|
+
const policies = /* @__PURE__ */ new WeakMap();
|
|
4
4
|
const automatic = /* @__PURE__ */ new WeakMap();
|
|
5
5
|
export function scheduleAcknowledgement(interaction, policy, allowTimer = true) {
|
|
6
|
+
if (policy)
|
|
7
|
+
policies.set(interaction, policy);
|
|
6
8
|
if (policy === "manual")
|
|
7
9
|
return () => {
|
|
8
10
|
};
|
|
9
|
-
if (policy === "private")
|
|
10
|
-
privateByDefault.add(interaction);
|
|
11
11
|
const elapsed = Date.now() - (interaction.createdTimestamp ?? Date.now());
|
|
12
12
|
const originalDefer = interaction.deferReply;
|
|
13
13
|
const restoreMethods = [];
|
|
@@ -35,13 +35,18 @@ export function scheduleAcknowledgement(interaction, policy, allowTimer = true)
|
|
|
35
35
|
value(...args) {
|
|
36
36
|
cancel();
|
|
37
37
|
const ack = automatic.get(this);
|
|
38
|
-
if (method === "reply"
|
|
38
|
+
if (method === "reply") {
|
|
39
39
|
const payload = args[0];
|
|
40
40
|
const options = typeof payload === "string" ? { content: payload } : payload instanceof MessagePayload ? payload.options : payload;
|
|
41
|
-
const opts = options;
|
|
41
|
+
const opts = policy === "private" ? withPrivateFlag(options) : options;
|
|
42
|
+
const source = payload instanceof MessagePayload ? payload : void 0;
|
|
42
43
|
if (ack)
|
|
43
|
-
return interactionSender(this).send(opts);
|
|
44
|
-
|
|
44
|
+
return interactionSender(this, source).send(opts);
|
|
45
|
+
if (!this.deferred && !this.replied && canDeferFiles(opts)) {
|
|
46
|
+
return sendInitialFiles(this, opts, source).then(({ response, message }) => opts.fetchReply ? message : response);
|
|
47
|
+
}
|
|
48
|
+
if (policy === "private")
|
|
49
|
+
return Reflect.apply(original, this, [opts]);
|
|
45
50
|
}
|
|
46
51
|
if (method === "deferReply") {
|
|
47
52
|
const opts = args[0] ?? {};
|
|
@@ -84,33 +89,60 @@ function editOptions(options) {
|
|
|
84
89
|
const writable = bits & (MessageFlags.SuppressEmbeds | MessageFlags.IsComponentsV2);
|
|
85
90
|
return { ...editable, flags: writable };
|
|
86
91
|
}
|
|
92
|
+
function canDeferFiles(opts) {
|
|
93
|
+
return opts.files?.length && !opts.withResponse && !opts.tts && !new MessageFlagsBitField(opts.flags).any(MessageFlags.SuppressNotifications | MessageFlags.IsVoiceMessage);
|
|
94
|
+
}
|
|
95
|
+
function withResolvedFiles(interaction, opts, source) {
|
|
96
|
+
if (!source?.files && !source?.body)
|
|
97
|
+
return opts;
|
|
98
|
+
const payload = MessagePayload.create(interaction.webhook, opts);
|
|
99
|
+
payload.files = source.files;
|
|
100
|
+
if (source.body) {
|
|
101
|
+
payload.body = {
|
|
102
|
+
...source.body,
|
|
103
|
+
flags: opts.flags == null ? void 0 : new MessageFlagsBitField(opts.flags).bitfield,
|
|
104
|
+
tts: "tts" in opts ? opts.tts : void 0
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
return payload;
|
|
108
|
+
}
|
|
109
|
+
async function sendInitialFiles(interaction, opts, source) {
|
|
110
|
+
const response = await interaction.deferReply(isPrivate(opts) ? { flags: MessageFlags.Ephemeral } : {});
|
|
111
|
+
const message = await interaction.editReply(withResolvedFiles(interaction, editOptions(opts), source));
|
|
112
|
+
return { response, message };
|
|
113
|
+
}
|
|
87
114
|
export function wasAutomaticallyDeferred(interaction) {
|
|
88
115
|
return automatic.has(interaction);
|
|
89
116
|
}
|
|
90
|
-
export function interactionSender(interaction) {
|
|
117
|
+
export function interactionSender(interaction, source) {
|
|
91
118
|
let method;
|
|
92
119
|
return {
|
|
93
120
|
async send(options) {
|
|
94
121
|
let opts = options;
|
|
95
|
-
|
|
122
|
+
const policy = policies.get(interaction);
|
|
123
|
+
if (!interaction.replied && policy === "private" && !isPrivate(opts))
|
|
96
124
|
opts = withPrivateFlag(opts);
|
|
97
125
|
const ack = automatic.get(interaction);
|
|
98
126
|
if (ack)
|
|
99
127
|
await ack.pending;
|
|
100
128
|
method = interaction.replied ? "followUp" : interaction.deferred ? "editReply" : "reply";
|
|
129
|
+
if (method === "reply" && policy !== "manual" && canDeferFiles(opts)) {
|
|
130
|
+
method = "editReply";
|
|
131
|
+
return (await sendInitialFiles(interaction, opts)).message;
|
|
132
|
+
}
|
|
101
133
|
if (method === "editReply") {
|
|
102
134
|
const explicitlyPrivate = isPrivate(opts);
|
|
103
135
|
const originalPrivate = ack ? ack.policy !== "public" : interaction.ephemeral;
|
|
104
136
|
if (explicitlyPrivate && originalPrivate === false || ack && explicitlyPrivate !== originalPrivate) {
|
|
105
137
|
await interaction.editReply({ content: "Preparing reply\u2026" });
|
|
106
138
|
method = "followUp";
|
|
107
|
-
const message = await interaction.followUp(opts);
|
|
139
|
+
const message = await interaction.followUp(withResolvedFiles(interaction, opts, source));
|
|
108
140
|
await interaction.deleteReply().catch((error) => logDiscordFailure("Could not remove acknowledgement:", error));
|
|
109
141
|
return message;
|
|
110
142
|
}
|
|
111
|
-
return interaction.editReply(editOptions(opts));
|
|
143
|
+
return interaction.editReply(withResolvedFiles(interaction, editOptions(opts), source));
|
|
112
144
|
}
|
|
113
|
-
return interaction[method](opts);
|
|
145
|
+
return interaction[method](withResolvedFiles(interaction, opts, source));
|
|
114
146
|
},
|
|
115
147
|
edit(msg, options) {
|
|
116
148
|
const opts = editOptions(options);
|
|
@@ -14,11 +14,11 @@ type __VLS_Props = {
|
|
|
14
14
|
searching?: boolean;
|
|
15
15
|
};
|
|
16
16
|
declare const __VLS_export: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {
|
|
17
|
-
highlight: (index: number) => any;
|
|
18
17
|
choose: (item: PickerItem) => any;
|
|
18
|
+
highlight: (index: number) => any;
|
|
19
19
|
}, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{
|
|
20
|
-
onHighlight?: ((index: number) => any) | undefined;
|
|
21
20
|
onChoose?: ((item: PickerItem) => any) | undefined;
|
|
21
|
+
onHighlight?: ((index: number) => any) | undefined;
|
|
22
22
|
}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
|
|
23
23
|
declare const _default: typeof __VLS_export;
|
|
24
24
|
export default _default;
|
|
@@ -14,11 +14,11 @@ type __VLS_Props = {
|
|
|
14
14
|
searching?: boolean;
|
|
15
15
|
};
|
|
16
16
|
declare const __VLS_export: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {
|
|
17
|
-
highlight: (index: number) => any;
|
|
18
17
|
choose: (item: PickerItem) => any;
|
|
18
|
+
highlight: (index: number) => any;
|
|
19
19
|
}, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{
|
|
20
|
-
onHighlight?: ((index: number) => any) | undefined;
|
|
21
20
|
onChoose?: ((item: PickerItem) => any) | undefined;
|
|
21
|
+
onHighlight?: ((index: number) => any) | undefined;
|
|
22
22
|
}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
|
|
23
23
|
declare const _default: typeof __VLS_export;
|
|
24
24
|
export default _default;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { DiscordCommandReference } from '../../../types.js';
|
|
2
|
+
type __VLS_Props = {
|
|
3
|
+
catalog: DiscordCommandReference;
|
|
4
|
+
title?: string;
|
|
5
|
+
};
|
|
6
|
+
type __VLS_Slots = {
|
|
7
|
+
'default'?: () => unknown;
|
|
8
|
+
'command-footer'?: (props: {
|
|
9
|
+
command: DiscordCommandReference['commands'][number];
|
|
10
|
+
}) => unknown;
|
|
11
|
+
};
|
|
12
|
+
declare const __VLS_base: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
|
|
13
|
+
declare const __VLS_export: __VLS_WithSlots<typeof __VLS_base, __VLS_Slots>;
|
|
14
|
+
declare const _default: typeof __VLS_export;
|
|
15
|
+
export default _default;
|
|
16
|
+
type __VLS_WithSlots<T, S> = T & {
|
|
17
|
+
new (): {
|
|
18
|
+
$slots: S;
|
|
19
|
+
};
|
|
20
|
+
};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
<script setup>
|
|
2
|
+
import ReferenceContent from "./ReferenceContent";
|
|
3
|
+
defineProps({
|
|
4
|
+
catalog: { type: Object, required: true },
|
|
5
|
+
title: { type: String, required: false }
|
|
6
|
+
});
|
|
7
|
+
defineSlots();
|
|
8
|
+
</script>
|
|
9
|
+
|
|
10
|
+
<template>
|
|
11
|
+
<ReferenceContent :catalog="catalog" :title="title">
|
|
12
|
+
<slot />
|
|
13
|
+
<template #command-footer="{ command }">
|
|
14
|
+
<slot name="command-footer" :command="command" />
|
|
15
|
+
</template>
|
|
16
|
+
</ReferenceContent>
|
|
17
|
+
</template>
|
|
18
|
+
|
|
19
|
+
<style src="../reference.css">
|
|
20
|
+
|
|
21
|
+
</style>
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { DiscordCommandReference } from '../../../types.js';
|
|
2
|
+
type __VLS_Props = {
|
|
3
|
+
catalog: DiscordCommandReference;
|
|
4
|
+
title?: string;
|
|
5
|
+
};
|
|
6
|
+
type __VLS_Slots = {
|
|
7
|
+
'default'?: () => unknown;
|
|
8
|
+
'command-footer'?: (props: {
|
|
9
|
+
command: DiscordCommandReference['commands'][number];
|
|
10
|
+
}) => unknown;
|
|
11
|
+
};
|
|
12
|
+
declare const __VLS_base: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
|
|
13
|
+
declare const __VLS_export: __VLS_WithSlots<typeof __VLS_base, __VLS_Slots>;
|
|
14
|
+
declare const _default: typeof __VLS_export;
|
|
15
|
+
export default _default;
|
|
16
|
+
type __VLS_WithSlots<T, S> = T & {
|
|
17
|
+
new (): {
|
|
18
|
+
$slots: S;
|
|
19
|
+
};
|
|
20
|
+
};
|
|
@@ -303,9 +303,6 @@ function setField(name, el) {
|
|
|
303
303
|
</button>
|
|
304
304
|
</div>
|
|
305
305
|
<div class="flex shrink-0 items-center gap-3 text-chat-muted sm:gap-4">
|
|
306
|
-
<div v-if="!command" aria-hidden="true" class="hidden items-center gap-4 sm:flex" title="Discord media controls">
|
|
307
|
-
<UIcon name="i-lucide-gift" class="size-5" /><span class="rounded-[3px] border-2 px-px text-[.625rem] leading-[1.1] font-extrabold">GIF</span><UIcon name="i-lucide-sticker" class="size-5" />
|
|
308
|
-
</div>
|
|
309
306
|
<UPopover v-if="!command || option" v-model:open="emojis" :content="{ side: 'top', align: 'end' }" :ui="{ content: 'grid grid-cols-4 gap-1 rounded-lg bg-chat-panel p-2 ring-chat-line' }">
|
|
310
307
|
<button type="button" aria-label="Add emoji" class="grid size-6 cursor-pointer place-items-center hover:text-chat-text">
|
|
311
308
|
<UIcon name="i-lucide-smile" class="size-5" />
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { PropType } from 'vue';
|
|
2
|
+
import type { DiscordCommandReference } from '../../../types.js';
|
|
3
|
+
declare const _default: import("vue").DefineComponent<import("vue").ExtractPropTypes<{
|
|
4
|
+
catalog: {
|
|
5
|
+
type: PropType<DiscordCommandReference>;
|
|
6
|
+
required: true;
|
|
7
|
+
};
|
|
8
|
+
title: {
|
|
9
|
+
type: StringConstructor;
|
|
10
|
+
default: string;
|
|
11
|
+
};
|
|
12
|
+
}>, () => import("vue").VNode<import("vue").RendererNode, import("vue").RendererElement, {
|
|
13
|
+
[key: string]: any;
|
|
14
|
+
}>, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<import("vue").ExtractPropTypes<{
|
|
15
|
+
catalog: {
|
|
16
|
+
type: PropType<DiscordCommandReference>;
|
|
17
|
+
required: true;
|
|
18
|
+
};
|
|
19
|
+
title: {
|
|
20
|
+
type: StringConstructor;
|
|
21
|
+
default: string;
|
|
22
|
+
};
|
|
23
|
+
}>> & Readonly<{}>, {
|
|
24
|
+
title: string;
|
|
25
|
+
}, {}, {}, {}, string, import("vue").ComponentProvideOptions, true, {}, any>;
|
|
26
|
+
export default _default;
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { defineComponent, h } from "vue";
|
|
2
|
+
function commandId(name) {
|
|
3
|
+
return `command-${name.replaceAll(" ", "/")}`;
|
|
4
|
+
}
|
|
5
|
+
function optionRow(option) {
|
|
6
|
+
const limits = [];
|
|
7
|
+
if (option.min !== void 0)
|
|
8
|
+
limits.push(`Minimum ${option.min}`);
|
|
9
|
+
if (option.max !== void 0)
|
|
10
|
+
limits.push(`Maximum ${option.max}`);
|
|
11
|
+
if (option.minLength !== void 0)
|
|
12
|
+
limits.push(`Minimum length ${option.minLength}`);
|
|
13
|
+
if (option.maxLength !== void 0)
|
|
14
|
+
limits.push(`Maximum length ${option.maxLength}`);
|
|
15
|
+
if (option.hasAutocomplete)
|
|
16
|
+
limits.push("Autocomplete");
|
|
17
|
+
return h("div", { key: option.name, class: "ref-option" }, [
|
|
18
|
+
h("dt", [
|
|
19
|
+
h("code", option.name),
|
|
20
|
+
" ",
|
|
21
|
+
h("small", `${option.type} \xB7 ${option.required ? "Required" : "Optional"}`)
|
|
22
|
+
]),
|
|
23
|
+
h("dd", [
|
|
24
|
+
option.description,
|
|
25
|
+
limits.length ? h("span", { class: "ref-meta" }, limits.join(" \xB7 ")) : null,
|
|
26
|
+
option.choices?.length ? h("span", { class: "ref-meta" }, `Choices \xB7 ${option.choices.map((choice) => choice.name).join(", ")}`) : null
|
|
27
|
+
])
|
|
28
|
+
]);
|
|
29
|
+
}
|
|
30
|
+
export default defineComponent({
|
|
31
|
+
name: "DiscordReferenceContent",
|
|
32
|
+
props: {
|
|
33
|
+
catalog: { type: Object, required: true },
|
|
34
|
+
title: { type: String, default: "Command reference" }
|
|
35
|
+
},
|
|
36
|
+
setup(props, { slots }) {
|
|
37
|
+
function navigation() {
|
|
38
|
+
const links = props.catalog.commands.map(
|
|
39
|
+
(cmd) => h("li", { key: cmd.name }, [h("a", { href: `#${encodeURIComponent(commandId(cmd.name))}` }, [h("code", `/${cmd.name}`)])])
|
|
40
|
+
);
|
|
41
|
+
if (props.catalog.menus.length)
|
|
42
|
+
links.push(h("li", { key: "context-menus-link" }, [h("a", { href: "#context-menus" }, "Context menus")]));
|
|
43
|
+
return h("nav", { "class": "ref-nav", "aria-label": "On this page" }, [h("p", "On this page"), h("ul", links)]);
|
|
44
|
+
}
|
|
45
|
+
function commandSection(cmd) {
|
|
46
|
+
return h("section", { key: cmd.name, class: "ref-command" }, [
|
|
47
|
+
h("h3", { id: commandId(cmd.name) }, [h("code", `/${cmd.name}`)]),
|
|
48
|
+
h("p", cmd.description),
|
|
49
|
+
cmd.options.length ? h("dl", cmd.options.map(optionRow)) : null,
|
|
50
|
+
slots["command-footer"]?.({ command: cmd })
|
|
51
|
+
]);
|
|
52
|
+
}
|
|
53
|
+
function menuSection() {
|
|
54
|
+
return h("section", [
|
|
55
|
+
h("h2", { id: "context-menus" }, "Context menus"),
|
|
56
|
+
h("dl", props.catalog.menus.map((menu) => h("div", { key: `${menu.type}:${menu.name}`, class: "ref-option" }, [
|
|
57
|
+
h("dt", menu.name),
|
|
58
|
+
h("dd", `Open the Apps menu on a ${menu.type}.`)
|
|
59
|
+
])))
|
|
60
|
+
]);
|
|
61
|
+
}
|
|
62
|
+
return () => h("article", { class: "discord-reference" }, [
|
|
63
|
+
h("header", { class: "ref-header" }, [h("h1", props.title), slots.default?.()]),
|
|
64
|
+
props.catalog.commands.length || props.catalog.menus.length ? h("div", { class: "ref-layout" }, [
|
|
65
|
+
navigation(),
|
|
66
|
+
h("div", { class: "ref-content" }, [
|
|
67
|
+
props.catalog.commands.length ? h("section", [h("h2", "Slash commands"), ...props.catalog.commands.map(commandSection)]) : null,
|
|
68
|
+
props.catalog.menus.length ? menuSection() : null
|
|
69
|
+
])
|
|
70
|
+
]) : h("p", "No commands or context menus are listed.")
|
|
71
|
+
]);
|
|
72
|
+
}
|
|
73
|
+
});
|
|
@@ -7,7 +7,7 @@ export declare const appearanceSelect: {
|
|
|
7
7
|
readonly align: "end";
|
|
8
8
|
};
|
|
9
9
|
readonly ui: {
|
|
10
|
-
readonly base: "size-11 shrink-0 justify-center p-0";
|
|
10
|
+
readonly base: "size-11 shrink-0 cursor-pointer justify-center p-0";
|
|
11
11
|
readonly leading: "static p-0";
|
|
12
12
|
readonly leadingIcon: "size-[1.125rem] text-current";
|
|
13
13
|
readonly value: "sr-only";
|
|
@@ -5,7 +5,7 @@ export const appearanceSelect = {
|
|
|
5
5
|
"color": "neutral",
|
|
6
6
|
"content": { align: "end" },
|
|
7
7
|
"ui": {
|
|
8
|
-
base: "size-11 shrink-0 justify-center p-0",
|
|
8
|
+
base: "size-11 shrink-0 cursor-pointer justify-center p-0",
|
|
9
9
|
leading: "static p-0",
|
|
10
10
|
leadingIcon: "size-[1.125rem] text-current",
|
|
11
11
|
value: "sr-only",
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
.discord-reference {
|
|
2
|
+
color-scheme: light dark;
|
|
3
|
+
--ref-ink: light-dark(#202527, #e7edeb);
|
|
4
|
+
--ref-muted: light-dark(#515e5a, #b0bcb7);
|
|
5
|
+
--ref-border: light-dark(#d6dfdb, #35423c);
|
|
6
|
+
--ref-accent: light-dark(#087451, #79deba);
|
|
7
|
+
color: var(--ref-ink);
|
|
8
|
+
background-color: light-dark(#fff, #141a18);
|
|
9
|
+
font: 1rem/1.55 system-ui, sans-serif;
|
|
10
|
+
max-width: 70rem;
|
|
11
|
+
margin-inline: auto;
|
|
12
|
+
padding: clamp(1.25rem, 5vw, 4rem);
|
|
13
|
+
overflow-wrap: anywhere;
|
|
14
|
+
}
|
|
15
|
+
.light .discord-reference { color-scheme: light; }
|
|
16
|
+
.dark .discord-reference { color-scheme: dark; }
|
|
17
|
+
.discord-reference h1, .discord-reference h2, .discord-reference h3, .discord-reference p,
|
|
18
|
+
.discord-reference dl, .discord-reference dd, .discord-reference ul { margin: 0; }
|
|
19
|
+
.discord-reference .ref-header { border-bottom: 1px solid var(--ref-border); padding-bottom: 1.5rem; margin-bottom: 2rem; }
|
|
20
|
+
.discord-reference h1 { font-size: clamp(2rem, 4vw, 3rem); letter-spacing: -.045em; line-height: 1.12; font-weight: 650; }
|
|
21
|
+
.discord-reference h2 { font-size: 1.25rem; font-weight: 650; letter-spacing: -.025em; }
|
|
22
|
+
.discord-reference h3 { font-size: 1.15rem; font-weight: 600; }
|
|
23
|
+
.discord-reference :is(h2, h3) { scroll-margin-top: 5rem; }
|
|
24
|
+
.discord-reference code { font: inherit; font-family: ui-monospace, monospace; }
|
|
25
|
+
.discord-reference a { color: var(--ref-accent); text-underline-offset: .18em; }
|
|
26
|
+
.discord-reference a:focus-visible { outline: 2px solid currentColor; outline-offset: 3px; }
|
|
27
|
+
.discord-reference .ref-header > :not(h1) { margin-top: .85rem; }
|
|
28
|
+
.discord-reference .ref-layout { display: grid; grid-template-columns: minmax(0, 13rem) minmax(0, 1fr); gap: clamp(1.5rem, 5vw, 4rem); }
|
|
29
|
+
.discord-reference .ref-nav p { font-size: .875rem; font-weight: 650; }
|
|
30
|
+
.discord-reference .ref-nav ul { display: grid; gap: .15rem; list-style: none; padding: .65rem 0 0; }
|
|
31
|
+
.discord-reference .ref-nav a { display: inline-block; padding-block: .25rem; min-height: 1.5rem; font-size: .875rem; text-decoration: none; }
|
|
32
|
+
.discord-reference .ref-nav a:hover, .discord-reference .ref-nav a:focus-visible { text-decoration: underline; }
|
|
33
|
+
.discord-reference .ref-content > section + section { margin-top: 2rem; }
|
|
34
|
+
.discord-reference .ref-command { padding-block: 1.25rem; border-bottom: 1px solid var(--ref-border); }
|
|
35
|
+
.discord-reference .ref-command > p { margin-top: .25rem; }
|
|
36
|
+
.discord-reference dl { margin-top: 1rem; }
|
|
37
|
+
.discord-reference .ref-option { border-inline-start: 2px solid var(--ref-border); padding-inline-start: 1rem; }
|
|
38
|
+
.discord-reference .ref-option + .ref-option { margin-top: .85rem; }
|
|
39
|
+
.discord-reference dt { font-weight: 600; }
|
|
40
|
+
.discord-reference small, .discord-reference .ref-meta, .discord-reference dd { color: var(--ref-muted); }
|
|
41
|
+
.discord-reference small { font: 400 .875rem/1.5 system-ui, sans-serif; margin-inline-start: .4rem; }
|
|
42
|
+
.discord-reference .ref-meta { display: block; font-size: .875rem; }
|
|
43
|
+
@media (max-width: 42rem) {
|
|
44
|
+
.discord-reference .ref-layout { grid-template-columns: minmax(0, 1fr); }
|
|
45
|
+
.discord-reference .ref-nav ul { display: flex; flex-wrap: wrap; gap: .15rem .9rem; }
|
|
46
|
+
}
|
|
@@ -1,16 +1,9 @@
|
|
|
1
1
|
import process from "node:process";
|
|
2
2
|
import { defineEventHandler, getMethod, getRequestHeader, setResponseHeader, setResponseHeaders, setResponseStatus } from "h3";
|
|
3
3
|
import { getDashboardUserId, handleDashboardOAuth } from "./oauth.js";
|
|
4
|
+
import { acceptsOrigin, configuredOrigin } from "./origin.js";
|
|
4
5
|
import { dashboardAccessFor } from "./permissions.js";
|
|
5
6
|
import { renderAccessDeniedPage, renderSignInPage } from "./signin.js";
|
|
6
|
-
function privateOrigin() {
|
|
7
|
-
const origin = process.env.DISCORD_DASHBOARD_ORIGIN;
|
|
8
|
-
const url = origin && URL.canParse(origin) ? new URL(origin) : void 0;
|
|
9
|
-
if (!url || url.origin !== origin)
|
|
10
|
-
return;
|
|
11
|
-
if (url.protocol === "https:" || url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))
|
|
12
|
-
return url;
|
|
13
|
-
}
|
|
14
7
|
function rejectAccess(event, status, path) {
|
|
15
8
|
setResponseStatus(event, status);
|
|
16
9
|
if ((path === "/" || path === "/discord" || path.startsWith("/discord/")) && getMethod(event) === "GET" && getRequestHeader(event, "accept")?.includes("text/html")) {
|
|
@@ -28,7 +21,7 @@ export default defineEventHandler(async (event) => {
|
|
|
28
21
|
"x-frame-options": "DENY",
|
|
29
22
|
"x-content-type-options": "nosniff"
|
|
30
23
|
});
|
|
31
|
-
const url =
|
|
24
|
+
const url = configuredOrigin(process.env.DISCORD_DASHBOARD_ORIGIN);
|
|
32
25
|
const clientId = process.env.DISCORD_CLIENT_ID;
|
|
33
26
|
if (!url || !clientId || !/^\d+$/.test(clientId) || !process.env.DISCORD_TOKEN) {
|
|
34
27
|
setResponseStatus(event, 503);
|
|
@@ -36,10 +29,7 @@ export default defineEventHandler(async (event) => {
|
|
|
36
29
|
}
|
|
37
30
|
const method = getMethod(event);
|
|
38
31
|
const path = event.path.split("?")[0];
|
|
39
|
-
|
|
40
|
-
const write = !["GET", "HEAD"].includes(method);
|
|
41
|
-
const navigation = getRequestHeader(event, "sec-fetch-mode") === "navigate" && getRequestHeader(event, "sec-fetch-dest") === "document";
|
|
42
|
-
if (getRequestHeader(event, "host")?.toLowerCase() !== url.host || getRequestHeader(event, "sec-fetch-site") === "cross-site" && (write || !navigation) || (write || requestOrigin !== void 0) && requestOrigin !== url.origin) {
|
|
32
|
+
if (!acceptsOrigin(event, url)) {
|
|
43
33
|
setResponseStatus(event, 403);
|
|
44
34
|
return "Forbidden";
|
|
45
35
|
}
|
|
@@ -1,3 +1,17 @@
|
|
|
1
1
|
import type { H3Event } from 'h3';
|
|
2
|
+
type Audience = 'dashboard' | 'reference';
|
|
3
|
+
interface OAuthOptions {
|
|
4
|
+
audience: Audience;
|
|
5
|
+
landing: string;
|
|
6
|
+
sharedGuilds?: (guildIds: string[]) => string[];
|
|
7
|
+
}
|
|
8
|
+
interface Session {
|
|
9
|
+
userId: string;
|
|
10
|
+
origin: string;
|
|
11
|
+
audience: Audience;
|
|
12
|
+
guilds?: string[];
|
|
13
|
+
}
|
|
14
|
+
export declare function getDiscordSession(event: H3Event, origin: URL, audience: Audience): Session | undefined;
|
|
2
15
|
export declare function getDashboardUserId(event: H3Event, origin: URL): string | undefined;
|
|
3
|
-
export declare function handleDashboardOAuth(event: H3Event, origin: URL, clientId: string): Promise<string | undefined>;
|
|
16
|
+
export declare function handleDashboardOAuth(event: H3Event, origin: URL, clientId: string, options?: OAuthOptions): Promise<string | undefined>;
|
|
17
|
+
export {};
|
|
@@ -1,8 +1,5 @@
|
|
|
1
1
|
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
2
|
import { deleteCookie, getCookie, getMethod, getQuery, setCookie, setResponseHeader, setResponseStatus } from "h3";
|
|
3
|
-
const loginPath = "/__discord-auth/login";
|
|
4
|
-
const callbackPath = "/__discord-auth/callback";
|
|
5
|
-
const logoutPath = "/__discord-auth/logout";
|
|
6
3
|
const loginSeconds = 10 * 60;
|
|
7
4
|
const sessionSeconds = 8 * 60 * 60;
|
|
8
5
|
const capacity = 1024;
|
|
@@ -41,20 +38,25 @@ class ExpiringTokens {
|
|
|
41
38
|
this.entries.delete(digest(token).toString("hex"));
|
|
42
39
|
}
|
|
43
40
|
}
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
41
|
+
function tokenStores() {
|
|
42
|
+
return { logins: new ExpiringTokens(), sessions: new ExpiringTokens() };
|
|
43
|
+
}
|
|
44
|
+
const audiences = { dashboard: tokenStores(), reference: tokenStores() };
|
|
45
|
+
function cookies(origin, audience) {
|
|
47
46
|
const secure = origin.protocol === "https:";
|
|
48
|
-
const prefix = secure ? "__Host-
|
|
47
|
+
const prefix = `${secure ? "__Host-" : ""}nuxt_discord_${audience === "reference" ? "reference_" : ""}`;
|
|
49
48
|
return {
|
|
50
49
|
session: `${prefix}session`,
|
|
51
50
|
login: `${prefix}login`,
|
|
52
51
|
options: { httpOnly: true, secure, sameSite: "lax", path: "/" }
|
|
53
52
|
};
|
|
54
53
|
}
|
|
54
|
+
export function getDiscordSession(event, origin, audience) {
|
|
55
|
+
const session = audiences[audience].sessions.get(getCookie(event, cookies(origin, audience).session));
|
|
56
|
+
return session?.origin === origin.origin && session.audience === audience ? session : void 0;
|
|
57
|
+
}
|
|
55
58
|
export function getDashboardUserId(event, origin) {
|
|
56
|
-
|
|
57
|
-
return session?.origin === origin.origin ? session.userId : void 0;
|
|
59
|
+
return getDiscordSession(event, origin, "dashboard")?.userId;
|
|
58
60
|
}
|
|
59
61
|
function redirect(event, location) {
|
|
60
62
|
setResponseStatus(event, 303);
|
|
@@ -65,7 +67,7 @@ function reject(event, status, message) {
|
|
|
65
67
|
setResponseStatus(event, status);
|
|
66
68
|
return message;
|
|
67
69
|
}
|
|
68
|
-
async function identifyUser(clientId, redirectUri, verifier, code) {
|
|
70
|
+
async function identifyUser(clientId, redirectUri, verifier, code, sharedGuilds) {
|
|
69
71
|
const exchange = await fetch("https://discord.com/api/v10/oauth2/token", {
|
|
70
72
|
method: "POST",
|
|
71
73
|
redirect: "error",
|
|
@@ -85,10 +87,29 @@ async function identifyUser(clientId, redirectUri, verifier, code) {
|
|
|
85
87
|
if (!response.ok)
|
|
86
88
|
return;
|
|
87
89
|
const user = await response.json();
|
|
88
|
-
if (typeof user.id
|
|
89
|
-
return
|
|
90
|
+
if (typeof user.id !== "string" || !snowflakePattern.test(user.id) || user.bot)
|
|
91
|
+
return;
|
|
92
|
+
if (!sharedGuilds)
|
|
93
|
+
return { userId: user.id };
|
|
94
|
+
const guildResponse = await fetch("https://discord.com/api/v10/users/@me/guilds?limit=200", {
|
|
95
|
+
headers: { authorization: `Bearer ${token.access_token}` },
|
|
96
|
+
redirect: "error",
|
|
97
|
+
signal: AbortSignal.timeout(8e3)
|
|
98
|
+
});
|
|
99
|
+
if (!guildResponse.ok)
|
|
100
|
+
return;
|
|
101
|
+
const guilds = await guildResponse.json();
|
|
102
|
+
if (!Array.isArray(guilds) || guilds.length > 200 || !guilds.every((guild) => typeof guild?.id === "string" && snowflakePattern.test(guild.id)))
|
|
103
|
+
return;
|
|
104
|
+
return { userId: user.id, guilds: sharedGuilds(guilds.map((guild) => guild.id)) };
|
|
90
105
|
}
|
|
91
|
-
export async function handleDashboardOAuth(event, origin, clientId) {
|
|
106
|
+
export async function handleDashboardOAuth(event, origin, clientId, options = { audience: "dashboard", landing: "/discord" }) {
|
|
107
|
+
const { audience, landing, sharedGuilds } = options;
|
|
108
|
+
const { logins, sessions } = audiences[audience];
|
|
109
|
+
const prefix = audience === "reference" ? "/__discord-reference" : "/__discord-auth";
|
|
110
|
+
const loginPath = `${prefix}/login`;
|
|
111
|
+
const callbackPath = `${prefix}/callback`;
|
|
112
|
+
const logoutPath = `${prefix}/logout`;
|
|
92
113
|
const path = event.path.split("?")[0];
|
|
93
114
|
if (path !== loginPath && path !== callbackPath && path !== logoutPath)
|
|
94
115
|
return;
|
|
@@ -97,14 +118,14 @@ export async function handleDashboardOAuth(event, origin, clientId) {
|
|
|
97
118
|
setResponseHeader(event, "allow", method);
|
|
98
119
|
return reject(event, 405, "Method not allowed.");
|
|
99
120
|
}
|
|
100
|
-
const cookie = cookies(origin);
|
|
121
|
+
const cookie = cookies(origin, audience);
|
|
101
122
|
const browserToken = getCookie(event, cookie.login);
|
|
102
123
|
if (path === logoutPath) {
|
|
103
124
|
sessions.revoke(getCookie(event, cookie.session));
|
|
104
125
|
logins.revoke(browserToken);
|
|
105
126
|
deleteCookie(event, cookie.session, cookie.options);
|
|
106
127
|
deleteCookie(event, cookie.login, cookie.options);
|
|
107
|
-
return redirect(event,
|
|
128
|
+
return redirect(event, landing);
|
|
108
129
|
}
|
|
109
130
|
if (!snowflakePattern.test(clientId))
|
|
110
131
|
return reject(event, 503, "Discord sign-in is not configured.");
|
|
@@ -113,13 +134,13 @@ export async function handleDashboardOAuth(event, origin, clientId) {
|
|
|
113
134
|
const verifier = opaqueToken();
|
|
114
135
|
const state2 = opaqueToken();
|
|
115
136
|
logins.revoke(browserToken);
|
|
116
|
-
const token = logins.issue({ state: state2, verifier, origin: origin.origin, clientId }, loginSeconds);
|
|
137
|
+
const token = logins.issue({ state: state2, verifier, origin: origin.origin, clientId, landing }, loginSeconds);
|
|
117
138
|
setCookie(event, cookie.login, token, { ...cookie.options, maxAge: loginSeconds });
|
|
118
139
|
const authorize = new URL("https://discord.com/oauth2/authorize");
|
|
119
140
|
authorize.search = new URLSearchParams({
|
|
120
141
|
response_type: "code",
|
|
121
142
|
client_id: clientId,
|
|
122
|
-
scope: "identify",
|
|
143
|
+
scope: sharedGuilds ? "identify guilds" : "identify",
|
|
123
144
|
prompt: "consent",
|
|
124
145
|
redirect_uri: redirectUri,
|
|
125
146
|
state: state2,
|
|
@@ -138,12 +159,12 @@ export async function handleDashboardOAuth(event, origin, clientId) {
|
|
|
138
159
|
if (error !== void 0 || typeof code !== "string" || !code || iss !== void 0 && iss !== "https://discord.com")
|
|
139
160
|
return reject(event, 400, "Discord sign-in was not completed.");
|
|
140
161
|
try {
|
|
141
|
-
const
|
|
142
|
-
if (
|
|
162
|
+
const identity = await identifyUser(clientId, redirectUri, login.verifier, code, sharedGuilds);
|
|
163
|
+
if (identity) {
|
|
143
164
|
sessions.revoke(getCookie(event, cookie.session));
|
|
144
|
-
const token = sessions.issue({
|
|
165
|
+
const token = sessions.issue({ ...identity, origin: origin.origin, audience }, sessionSeconds);
|
|
145
166
|
setCookie(event, cookie.session, token, { ...cookie.options, maxAge: sessionSeconds });
|
|
146
|
-
return redirect(event,
|
|
167
|
+
return redirect(event, login.landing);
|
|
147
168
|
}
|
|
148
169
|
} catch {
|
|
149
170
|
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { getMethod, getRequestHeader } from "h3";
|
|
2
|
+
export function configuredOrigin(origin) {
|
|
3
|
+
const url = origin && URL.canParse(origin) ? new URL(origin) : void 0;
|
|
4
|
+
if (!url || url.origin !== origin)
|
|
5
|
+
return;
|
|
6
|
+
if (url.protocol === "https:" || url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))
|
|
7
|
+
return url;
|
|
8
|
+
}
|
|
9
|
+
export function acceptsOrigin(event, url) {
|
|
10
|
+
const method = getMethod(event);
|
|
11
|
+
const requestOrigin = getRequestHeader(event, "origin");
|
|
12
|
+
const write = !["GET", "HEAD"].includes(method);
|
|
13
|
+
const navigation = getRequestHeader(event, "sec-fetch-mode") === "navigate" && getRequestHeader(event, "sec-fetch-dest") === "document";
|
|
14
|
+
return !(getRequestHeader(event, "host")?.toLowerCase() !== url.host || getRequestHeader(event, "sec-fetch-site") === "cross-site" && (write || !navigation) || (write || requestOrigin !== void 0) && requestOrigin !== url.origin);
|
|
15
|
+
}
|
|
@@ -37,3 +37,6 @@ export function renderSignInPage() {
|
|
|
37
37
|
export function renderAccessDeniedPage() {
|
|
38
38
|
return page("This account doesn\u2019t have dashboard access", '<form method="post" action="/__discord-auth/logout"><button class="action" type="submit">Use another Discord account</button></form>');
|
|
39
39
|
}
|
|
40
|
+
export function renderReferenceAccessPage(status) {
|
|
41
|
+
return status === 401 ? page("Sign in to the command reference", '<a class="action" href="/__discord-reference/login">Sign in with Discord</a>') : page("This account doesn\u2019t have access to the command reference", '<form method="post" action="/__discord-reference/logout"><button class="action" type="submit">Use another Discord account</button></form>');
|
|
42
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { H3Event } from 'h3';
|
|
2
|
+
import type { DiscordReferenceOptions } from '../../types.js';
|
|
3
|
+
export declare function referenceRequest(path: string, method: string, options: DiscordReferenceOptions): boolean;
|
|
4
|
+
export declare function memberAccessFor(userId: string, guilds: string[]): Promise<"read" | "forbidden" | "unavailable">;
|
|
5
|
+
export declare function authorizeReference(event: H3Event, policy: DiscordReferenceOptions, document?: boolean): Promise<string | undefined>;
|
|
6
|
+
export declare function referenceOAuth(event: H3Event, policy: DiscordReferenceOptions): Promise<string | undefined>;
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import process from "node:process";
|
|
2
|
+
import { createError, getMethod, getQuery, setResponseHeaders, setResponseStatus } from "h3";
|
|
3
|
+
import { getDiscordSession, handleDashboardOAuth } from "../dashboard/oauth.js";
|
|
4
|
+
import { acceptsOrigin, configuredOrigin } from "../dashboard/origin.js";
|
|
5
|
+
import { dashboardAccessFor } from "../dashboard/permissions.js";
|
|
6
|
+
import { renderReferenceAccessPage } from "../dashboard/signin.js";
|
|
7
|
+
import { useDiscordClient } from "../server/utils/useDiscordClient.js";
|
|
8
|
+
const authPaths = ["/__discord-reference/login", "/__discord-reference/callback", "/__discord-reference/logout"];
|
|
9
|
+
export function referenceRequest(path, method, options) {
|
|
10
|
+
if (method === "GET" || method === "HEAD") {
|
|
11
|
+
if (path === "/api/discord/reference" || options.page !== false && path === "/commands")
|
|
12
|
+
return true;
|
|
13
|
+
if (method === "GET" && options.access !== "public" && authPaths.slice(0, 2).includes(path))
|
|
14
|
+
return true;
|
|
15
|
+
}
|
|
16
|
+
return method === "POST" && options.access !== "public" && path === authPaths[2];
|
|
17
|
+
}
|
|
18
|
+
function referenceHeaders(event) {
|
|
19
|
+
setResponseHeaders(event, {
|
|
20
|
+
"cache-control": "private, no-store",
|
|
21
|
+
"cross-origin-resource-policy": "same-origin",
|
|
22
|
+
"referrer-policy": "no-referrer",
|
|
23
|
+
"x-content-type-options": "nosniff",
|
|
24
|
+
"x-frame-options": "DENY"
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
function signInConfig(event, policy) {
|
|
28
|
+
const url = configuredOrigin(process.env.DISCORD_REFERENCE_ORIGIN ?? process.env.DISCORD_DASHBOARD_ORIGIN);
|
|
29
|
+
const clientId = process.env.DISCORD_CLIENT_ID;
|
|
30
|
+
if (!url || !clientId || !/^[1-9]\d{0,19}$/.test(clientId) || policy.access !== "authenticated" && !process.env.DISCORD_TOKEN)
|
|
31
|
+
throw createError({ statusCode: 503, statusMessage: "Command reference sign-in is not configured." });
|
|
32
|
+
if (!acceptsOrigin(event, url))
|
|
33
|
+
throw createError({ statusCode: 403, statusMessage: "Forbidden" });
|
|
34
|
+
return { url, clientId };
|
|
35
|
+
}
|
|
36
|
+
let verifiedBot;
|
|
37
|
+
async function botIdentityMatches(clientId, token) {
|
|
38
|
+
if (verifiedBot?.token === token && verifiedBot.clientId === clientId)
|
|
39
|
+
return true;
|
|
40
|
+
try {
|
|
41
|
+
const response = await fetch("https://discord.com/api/v10/users/@me", {
|
|
42
|
+
headers: { Authorization: `Bot ${token}` },
|
|
43
|
+
redirect: "error",
|
|
44
|
+
signal: AbortSignal.timeout(5e3)
|
|
45
|
+
});
|
|
46
|
+
const user = response.ok && await response.json();
|
|
47
|
+
if (user?.id === clientId && user.bot === true) {
|
|
48
|
+
verifiedBot = { token, clientId };
|
|
49
|
+
return true;
|
|
50
|
+
}
|
|
51
|
+
} catch {
|
|
52
|
+
}
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
export async function memberAccessFor(userId, guilds) {
|
|
56
|
+
let unavailable = false;
|
|
57
|
+
const deadline = Date.now() + 5e3;
|
|
58
|
+
for (const guild of guilds) {
|
|
59
|
+
const remaining = deadline - Date.now();
|
|
60
|
+
if (remaining <= 0)
|
|
61
|
+
return "unavailable";
|
|
62
|
+
try {
|
|
63
|
+
const response = await fetch(`https://discord.com/api/v10/guilds/${guild}/members/${userId}`, {
|
|
64
|
+
headers: { Authorization: `Bot ${process.env.DISCORD_TOKEN}` },
|
|
65
|
+
cache: "no-store",
|
|
66
|
+
redirect: "error",
|
|
67
|
+
signal: AbortSignal.timeout(remaining)
|
|
68
|
+
});
|
|
69
|
+
if (response.status === 404)
|
|
70
|
+
continue;
|
|
71
|
+
if (response.ok && (await response.json())?.user?.id === userId)
|
|
72
|
+
return "read";
|
|
73
|
+
} catch {
|
|
74
|
+
}
|
|
75
|
+
unavailable = true;
|
|
76
|
+
}
|
|
77
|
+
return unavailable ? "unavailable" : "forbidden";
|
|
78
|
+
}
|
|
79
|
+
export async function authorizeReference(event, policy, document = false) {
|
|
80
|
+
referenceHeaders(event);
|
|
81
|
+
if (policy.access === "public")
|
|
82
|
+
return;
|
|
83
|
+
const { url, clientId } = signInConfig(event, policy);
|
|
84
|
+
const session = getDiscordSession(event, url, "reference");
|
|
85
|
+
let access = "anonymous";
|
|
86
|
+
if (session) {
|
|
87
|
+
if (policy.access === "private") {
|
|
88
|
+
access = await dashboardAccessFor(session.userId, "GET", "/__discord-auth/session");
|
|
89
|
+
} else if (policy.access === "members") {
|
|
90
|
+
access = policy.guilds && !await botIdentityMatches(clientId, process.env.DISCORD_TOKEN) ? "unavailable" : await memberAccessFor(session.userId, policy.guilds ?? session.guilds ?? []);
|
|
91
|
+
} else {
|
|
92
|
+
access = "read";
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
if (access === "unavailable")
|
|
96
|
+
throw createError({ statusCode: 503, statusMessage: "Discord access verification is temporarily unavailable." });
|
|
97
|
+
if (access === "anonymous" || access === "forbidden") {
|
|
98
|
+
const status = access === "anonymous" ? 401 : 403;
|
|
99
|
+
if (document) {
|
|
100
|
+
setResponseStatus(event, status);
|
|
101
|
+
return renderReferenceAccessPage(status);
|
|
102
|
+
}
|
|
103
|
+
throw createError({ statusCode: status, statusMessage: access === "anonymous" ? "Sign in to the command reference." : "Forbidden" });
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
function returnPath(value, origin, fallback) {
|
|
107
|
+
if (value === void 0)
|
|
108
|
+
return fallback;
|
|
109
|
+
let path = "";
|
|
110
|
+
if (typeof value === "string" && value.length <= 2048 && !/%(?:2f|5c|25)/i.test(value)) {
|
|
111
|
+
try {
|
|
112
|
+
path = decodeURIComponent(value);
|
|
113
|
+
} catch {
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
if (!/^\/[\p{L}\p{N}._~/-]*$/u.test(path) || path.includes("//") || path.split("/").some((part) => part === "." || part === ".."))
|
|
117
|
+
throw createError({ statusCode: 400, statusMessage: "Invalid return path." });
|
|
118
|
+
return new URL(path, origin).pathname;
|
|
119
|
+
}
|
|
120
|
+
export function referenceOAuth(event, policy) {
|
|
121
|
+
referenceHeaders(event);
|
|
122
|
+
const path = event.path.split("?")[0];
|
|
123
|
+
if (!referenceRequest(path, getMethod(event), policy) || !authPaths.includes(path))
|
|
124
|
+
throw createError({ statusCode: 404 });
|
|
125
|
+
const { url, clientId } = signInConfig(event, policy);
|
|
126
|
+
let sharedGuilds;
|
|
127
|
+
if (policy.access === "members" && !policy.guilds && !path.endsWith("/logout")) {
|
|
128
|
+
let client;
|
|
129
|
+
try {
|
|
130
|
+
client = useDiscordClient().internalClient;
|
|
131
|
+
} catch {
|
|
132
|
+
}
|
|
133
|
+
if (!client?.isReady() || client.user.id !== clientId)
|
|
134
|
+
throw createError({ statusCode: 503, statusMessage: "The bot is unavailable for shared server verification." });
|
|
135
|
+
const guilds = client.guilds.cache;
|
|
136
|
+
sharedGuilds = (ids) => ids.filter((id) => guilds.has(id));
|
|
137
|
+
}
|
|
138
|
+
return handleDashboardOAuth(event, url, clientId, {
|
|
139
|
+
audience: "reference",
|
|
140
|
+
landing: returnPath(getQuery(event).returnTo, url, policy.page === false ? "/" : "/commands"),
|
|
141
|
+
sharedGuilds
|
|
142
|
+
});
|
|
143
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { getCatalog, policy } from "discord/reference";
|
|
2
|
+
import { createError, defineEventHandler } from "h3";
|
|
3
|
+
import { authorizeReference } from "./access.js";
|
|
4
|
+
export default defineEventHandler(async (event) => {
|
|
5
|
+
if (event.path.split("?")[0] !== "/api/discord/reference")
|
|
6
|
+
throw createError({ statusCode: 404 });
|
|
7
|
+
await authorizeReference(event, policy);
|
|
8
|
+
return getCatalog();
|
|
9
|
+
});
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { getCatalog, policy, styles } from "discord/reference";
|
|
2
|
+
import { createError, defineEventHandler, setResponseHeaders } from "h3";
|
|
3
|
+
import { h } from "vue";
|
|
4
|
+
import { renderToString } from "vue/server-renderer";
|
|
5
|
+
import ReferenceContent from "../client/components/ReferenceContent.js";
|
|
6
|
+
import { authorizeReference } from "./access.js";
|
|
7
|
+
export default defineEventHandler(async (event) => {
|
|
8
|
+
if (policy.page === false || event.path.split("?")[0] !== "/commands")
|
|
9
|
+
throw createError({ statusCode: 404 });
|
|
10
|
+
setResponseHeaders(event, {
|
|
11
|
+
"content-type": "text/html; charset=utf-8",
|
|
12
|
+
"content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'"
|
|
13
|
+
});
|
|
14
|
+
const denied = await authorizeReference(event, policy, true);
|
|
15
|
+
if (denied)
|
|
16
|
+
return denied;
|
|
17
|
+
const slots = policy.access === "public" ? void 0 : {
|
|
18
|
+
default: () => h("form", { method: "post", action: "/__discord-reference/logout" }, h("button", { type: "submit" }, "Sign out"))
|
|
19
|
+
};
|
|
20
|
+
const body = await renderToString(h(ReferenceContent, { catalog: await getCatalog() }, slots));
|
|
21
|
+
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="color-scheme" content="light dark"><title>Command reference</title><style>${styles}</style></head><body><main>${body}</main></body></html>`;
|
|
22
|
+
});
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { policy } from "discord/reference";
|
|
2
|
+
import { defineEventHandler, getMethod } from "h3";
|
|
3
|
+
import dashboardAuth from "../dashboard/auth.js";
|
|
4
|
+
import { referenceOAuth, referenceRequest } from "./access.js";
|
|
5
|
+
import catalog from "./catalog.js";
|
|
6
|
+
import document from "./document.js";
|
|
7
|
+
export default defineEventHandler((event) => {
|
|
8
|
+
const path = event.path.split("?")[0];
|
|
9
|
+
if (!referenceRequest(path, getMethod(event), policy))
|
|
10
|
+
return dashboardAuth(event);
|
|
11
|
+
if (path === "/api/discord/reference")
|
|
12
|
+
return catalog(event);
|
|
13
|
+
if (path === "/commands")
|
|
14
|
+
return document(event);
|
|
15
|
+
return referenceOAuth(event, policy);
|
|
16
|
+
});
|
|
@@ -12,6 +12,8 @@ export default defineNitroPlugin(async (nitro) => {
|
|
|
12
12
|
if (import.meta.prerender)
|
|
13
13
|
return;
|
|
14
14
|
const runtimeConfig = useRuntimeConfig();
|
|
15
|
+
if (!runtimeConfig.discord.autoStart && (!process.env.DISCORD_TOKEN || !process.env.DISCORD_CLIENT_ID))
|
|
16
|
+
return;
|
|
15
17
|
let closed = false;
|
|
16
18
|
function fail(message, error) {
|
|
17
19
|
logDiscordFailure(message, error);
|
package/dist/types.d.mts
CHANGED
|
@@ -16,4 +16,4 @@ export { type SendHandle, type UseTextChannelReturn } from '../dist/runtime/serv
|
|
|
16
16
|
|
|
17
17
|
export { default, type slashCommandOptionTypeIdentifiers, type typeIdentifierToEnum } from './module.mjs'
|
|
18
18
|
|
|
19
|
-
export { type ContextMenu, type DashboardCatalog, type DiscordRuntimeConfig, type Listener, type Mentionable, type MiddlewareEntry, type NuxtDiscordContext, type NuxtDiscordOptions, type SlashCommand, type SlashCommandAttachmentOption, type SlashCommandBooleanOption, type SlashCommandChannelOption, type SlashCommandCustomReturnHandler, type SlashCommandIntegerOption, type SlashCommandMentionableOption, type SlashCommandNumberOption, type SlashCommandOption, type SlashCommandOptionBase, type SlashCommandOptionType, type SlashCommandOptionTypeIdentifier, type SlashCommandReturnType, type SlashCommandRoleOption, type SlashCommandRuntime, type SlashCommandStringOption, type SlashCommandSubcommand, type SlashCommandSubcommandGroup, type SlashCommandSubcommandGroupRuntime, type SlashCommandSubcommandRuntime, type SlashCommandUserOption, type integer } from './module.mjs'
|
|
19
|
+
export { type ContextMenu, type DashboardCatalog, type DiscordCommandReference, type DiscordReferenceOption, type DiscordReferenceOptions, type DiscordRuntimeConfig, type Listener, type Mentionable, type MiddlewareEntry, type NuxtDiscordContext, type NuxtDiscordOptions, type SlashCommand, type SlashCommandAttachmentOption, type SlashCommandBooleanOption, type SlashCommandChannelOption, type SlashCommandCustomReturnHandler, type SlashCommandIntegerOption, type SlashCommandMentionableOption, type SlashCommandNumberOption, type SlashCommandOption, type SlashCommandOptionBase, type SlashCommandOptionType, type SlashCommandOptionTypeIdentifier, type SlashCommandReturnType, type SlashCommandRoleOption, type SlashCommandRuntime, type SlashCommandStringOption, type SlashCommandSubcommand, type SlashCommandSubcommandGroup, type SlashCommandSubcommandGroupRuntime, type SlashCommandSubcommandRuntime, type SlashCommandUserOption, type integer } from './module.mjs'
|
package/dist/types.d.ts
CHANGED
|
@@ -16,4 +16,4 @@ export { type SendHandle, type UseTextChannelReturn } from '../dist/runtime/serv
|
|
|
16
16
|
|
|
17
17
|
export { default, type slashCommandOptionTypeIdentifiers, type typeIdentifierToEnum } from './module.mjs'
|
|
18
18
|
|
|
19
|
-
export { type ContextMenu, type DashboardCatalog, type DiscordRuntimeConfig, type Listener, type Mentionable, type MiddlewareEntry, type NuxtDiscordContext, type NuxtDiscordOptions, type SlashCommand, type SlashCommandAttachmentOption, type SlashCommandBooleanOption, type SlashCommandChannelOption, type SlashCommandCustomReturnHandler, type SlashCommandIntegerOption, type SlashCommandMentionableOption, type SlashCommandNumberOption, type SlashCommandOption, type SlashCommandOptionBase, type SlashCommandOptionType, type SlashCommandOptionTypeIdentifier, type SlashCommandReturnType, type SlashCommandRoleOption, type SlashCommandRuntime, type SlashCommandStringOption, type SlashCommandSubcommand, type SlashCommandSubcommandGroup, type SlashCommandSubcommandGroupRuntime, type SlashCommandSubcommandRuntime, type SlashCommandUserOption, type integer } from './module.mjs'
|
|
19
|
+
export { type ContextMenu, type DashboardCatalog, type DiscordCommandReference, type DiscordReferenceOption, type DiscordReferenceOptions, type DiscordRuntimeConfig, type Listener, type Mentionable, type MiddlewareEntry, type NuxtDiscordContext, type NuxtDiscordOptions, type SlashCommand, type SlashCommandAttachmentOption, type SlashCommandBooleanOption, type SlashCommandChannelOption, type SlashCommandCustomReturnHandler, type SlashCommandIntegerOption, type SlashCommandMentionableOption, type SlashCommandNumberOption, type SlashCommandOption, type SlashCommandOptionBase, type SlashCommandOptionType, type SlashCommandOptionTypeIdentifier, type SlashCommandReturnType, type SlashCommandRoleOption, type SlashCommandRuntime, type SlashCommandStringOption, type SlashCommandSubcommand, type SlashCommandSubcommandGroup, type SlashCommandSubcommandGroupRuntime, type SlashCommandSubcommandRuntime, type SlashCommandUserOption, type integer } from './module.mjs'
|
package/package.json
CHANGED