nuxt-discord 0.0.17 → 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.
Files changed (132) hide show
  1. package/README.md +249 -171
  2. package/dist/module.d.mts +146 -10
  3. package/dist/module.json +3 -3
  4. package/dist/module.mjs +1077 -348
  5. package/dist/runtime/acknowledgement.d.ts +11 -0
  6. package/dist/runtime/acknowledgement.js +156 -0
  7. package/dist/runtime/client/chat-theme.css +52 -0
  8. package/dist/runtime/client/components/ChatAvatar.d.vue.ts +6 -0
  9. package/dist/runtime/client/components/ChatAvatar.vue +11 -0
  10. package/dist/runtime/client/components/ChatAvatar.vue.d.ts +6 -0
  11. package/dist/runtime/client/components/CommandPicker.d.vue.ts +24 -0
  12. package/dist/runtime/client/components/CommandPicker.vue +67 -0
  13. package/dist/runtime/client/components/CommandPicker.vue.d.ts +24 -0
  14. package/dist/runtime/client/components/CommandReference.d.vue.ts +20 -0
  15. package/dist/runtime/client/components/CommandReference.vue +21 -0
  16. package/dist/runtime/client/components/CommandReference.vue.d.ts +20 -0
  17. package/dist/runtime/client/components/CommandTestBar.d.vue.ts +60 -0
  18. package/dist/runtime/client/components/CommandTestBar.vue +332 -0
  19. package/dist/runtime/client/components/CommandTestBar.vue.d.ts +60 -0
  20. package/dist/runtime/client/components/CommandTranscript.d.vue.ts +39 -0
  21. package/dist/runtime/client/components/CommandTranscript.vue +147 -0
  22. package/dist/runtime/client/components/CommandTranscript.vue.d.ts +39 -0
  23. package/dist/runtime/client/components/ProjectLogo.d.vue.ts +3 -0
  24. package/dist/runtime/client/components/ProjectLogo.vue +31 -0
  25. package/dist/runtime/client/components/ProjectLogo.vue.d.ts +3 -0
  26. package/dist/runtime/client/components/ReferenceContent.d.ts +26 -0
  27. package/dist/runtime/client/components/ReferenceContent.js +73 -0
  28. package/dist/runtime/client/components/TheHeader.d.vue.ts +3 -0
  29. package/dist/runtime/client/components/TheHeader.vue +53 -16
  30. package/dist/runtime/client/components/TheHeader.vue.d.ts +2 -2
  31. package/dist/runtime/client/components/appearance-select.d.ts +17 -0
  32. package/dist/runtime/client/components/appearance-select.js +15 -0
  33. package/dist/runtime/client/pages/activity.d.vue.ts +3 -0
  34. package/dist/runtime/client/pages/activity.vue +202 -0
  35. package/dist/runtime/client/pages/activity.vue.d.ts +3 -0
  36. package/dist/runtime/client/pages/context-menus.d.vue.ts +3 -0
  37. package/dist/runtime/client/pages/context-menus.vue +120 -0
  38. package/dist/runtime/client/pages/context-menus.vue.d.ts +3 -0
  39. package/dist/runtime/client/pages/listeners.d.vue.ts +3 -0
  40. package/dist/runtime/client/pages/listeners.vue +68 -0
  41. package/dist/runtime/client/pages/listeners.vue.d.ts +3 -0
  42. package/dist/runtime/client/pages/overview.d.vue.ts +3 -0
  43. package/dist/runtime/client/pages/overview.vue +280 -0
  44. package/dist/runtime/client/pages/overview.vue.d.ts +3 -0
  45. package/dist/runtime/client/pages/slash-commands.d.vue.ts +3 -0
  46. package/dist/runtime/client/pages/slash-commands.vue +185 -359
  47. package/dist/runtime/client/pages/slash-commands.vue.d.ts +2 -3
  48. package/dist/runtime/client/reference.css +46 -0
  49. package/dist/runtime/client/style.css +4 -1
  50. package/dist/runtime/client/useActivityLog.d.ts +7 -0
  51. package/dist/runtime/client/useActivityLog.js +76 -0
  52. package/dist/runtime/client/useCommandRegistry.d.ts +7 -0
  53. package/dist/runtime/client/useCommandRegistry.js +34 -0
  54. package/dist/runtime/client/useDashboardCatalog.d.ts +5 -0
  55. package/dist/runtime/client/useDashboardCatalog.js +9 -0
  56. package/dist/runtime/client/useDiscordCommandReference.d.ts +2 -0
  57. package/dist/runtime/client/useDiscordCommandReference.js +6 -0
  58. package/dist/runtime/dashboard/auth.d.ts +4 -0
  59. package/dist/runtime/dashboard/auth.js +55 -0
  60. package/dist/runtime/dashboard/oauth.d.ts +17 -0
  61. package/dist/runtime/dashboard/oauth.js +172 -0
  62. package/dist/runtime/dashboard/origin.d.ts +3 -0
  63. package/dist/runtime/dashboard/origin.js +15 -0
  64. package/dist/runtime/dashboard/permissions.d.ts +4 -0
  65. package/dist/runtime/dashboard/permissions.js +84 -0
  66. package/dist/runtime/dashboard/signin.d.ts +3 -0
  67. package/dist/runtime/dashboard/signin.js +42 -0
  68. package/dist/runtime/diagnostics.d.ts +4 -0
  69. package/dist/runtime/diagnostics.js +24 -0
  70. package/dist/runtime/discordInvocation.d.ts +14 -0
  71. package/dist/runtime/discordInvocation.js +28 -0
  72. package/dist/runtime/middleware.d.ts +1 -0
  73. package/dist/runtime/middleware.js +12 -0
  74. package/dist/runtime/reference/access.d.ts +6 -0
  75. package/dist/runtime/reference/access.js +143 -0
  76. package/dist/runtime/reference/catalog.d.ts +2 -0
  77. package/dist/runtime/reference/catalog.js +9 -0
  78. package/dist/runtime/reference/document.d.ts +2 -0
  79. package/dist/runtime/reference/document.js +22 -0
  80. package/dist/runtime/reference/hosted.d.ts +2 -0
  81. package/dist/runtime/reference/hosted.js +16 -0
  82. package/dist/runtime/reference/oauth.d.ts +2 -0
  83. package/dist/runtime/reference/oauth.js +4 -0
  84. package/dist/runtime/registration.d.ts +65 -0
  85. package/dist/runtime/registration.js +354 -0
  86. package/dist/runtime/server/api/discord/activity.get.d.ts +2 -0
  87. package/dist/runtime/server/api/discord/activity.get.js +6 -0
  88. package/dist/runtime/server/api/discord/catalog.get.d.ts +2 -0
  89. package/dist/runtime/server/api/discord/catalog.get.js +3 -0
  90. package/dist/runtime/server/api/discord/slash-command/autocomplete.post.d.ts +2 -0
  91. package/dist/runtime/server/api/discord/slash-command/autocomplete.post.js +14 -0
  92. package/dist/runtime/server/api/discord/slash-command/register.post.d.ts +1 -1
  93. package/dist/runtime/server/api/discord/slash-command/register.post.js +1 -1
  94. package/dist/runtime/server/api/discord/slash-command/remote-all.get.d.ts +1 -1
  95. package/dist/runtime/server/api/discord/slash-command/remote-diff.post.d.ts +1 -238
  96. package/dist/runtime/server/api/discord/slash-command/remote-diff.post.js +3 -1
  97. package/dist/runtime/server/api/discord/slash-command/test.post.d.ts +20 -0
  98. package/dist/runtime/server/api/discord/slash-command/test.post.js +19 -0
  99. package/dist/runtime/server/plugins/discord.js +95 -31
  100. package/dist/runtime/server/utils/client.d.ts +59 -246
  101. package/dist/runtime/server/utils/client.js +413 -451
  102. package/dist/runtime/server/utils/defineContextMenu.d.ts +49 -0
  103. package/dist/runtime/server/utils/defineContextMenu.js +12 -0
  104. package/dist/runtime/server/utils/defineListener.d.ts +24 -0
  105. package/dist/runtime/server/utils/defineListener.js +7 -0
  106. package/dist/runtime/server/utils/defineMiddleware.d.ts +29 -0
  107. package/dist/runtime/server/utils/defineMiddleware.js +24 -0
  108. package/dist/runtime/server/utils/describeCommand.d.ts +2 -0
  109. package/dist/runtime/server/utils/describeOption.d.ts +1 -1
  110. package/dist/runtime/server/utils/messageSender.d.ts +37 -0
  111. package/dist/runtime/server/utils/messageSender.js +149 -0
  112. package/dist/runtime/server/utils/middleware/cooldown.d.ts +1 -0
  113. package/dist/runtime/server/utils/middleware/cooldown.js +39 -0
  114. package/dist/runtime/server/utils/middleware/guildOnly.d.ts +1 -0
  115. package/dist/runtime/server/utils/middleware/guildOnly.js +6 -0
  116. package/dist/runtime/server/utils/middleware/ownerOnly.d.ts +1 -0
  117. package/dist/runtime/server/utils/middleware/ownerOnly.js +10 -0
  118. package/dist/runtime/server/utils/middleware/requireRole.d.ts +1 -0
  119. package/dist/runtime/server/utils/middleware/requireRole.js +15 -0
  120. package/dist/runtime/server/utils/reply.d.ts +13 -3
  121. package/dist/runtime/server/utils/reply.js +111 -162
  122. package/dist/runtime/server/utils/simulateInteraction.d.ts +20 -0
  123. package/dist/runtime/server/utils/simulateInteraction.js +127 -0
  124. package/dist/runtime/server/utils/useTextChannel.d.ts +56 -0
  125. package/dist/runtime/server/utils/useTextChannel.js +105 -0
  126. package/dist/types.d.mts +11 -1
  127. package/dist/types.d.ts +11 -1
  128. package/package.json +62 -44
  129. package/dist/runtime/client/components/TheHeader.css +0 -1
  130. package/dist/runtime/client/pages/slash-commands.css +0 -1
  131. package/dist/runtime/client/uno.config.d.ts +0 -2
  132. package/dist/runtime/client/uno.config.js +0 -10
@@ -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 +1,4 @@
1
- @import "tailwindcss";@import "@nuxt/ui";
1
+ @import "tailwindcss";
2
+ @import "@nuxt/ui";
3
+ @import "./chat-theme.css";
4
+ @source "../client";
@@ -0,0 +1,7 @@
1
+ import type { ActivityLogEntry } from '../../types.js';
2
+ export declare function useActivityLog(load: (signal: AbortSignal) => Promise<ActivityLogEntry[]>, socketUrl?: string): {
3
+ entries: import("vue").ComputedRef<ActivityLogEntry[]>;
4
+ paused: import("vue").ComputedRef<boolean>;
5
+ togglePause: () => void;
6
+ clearLog: () => void;
7
+ };
@@ -0,0 +1,76 @@
1
+ import { useDocumentVisibility, useIntervalFn, useWebSocket } from "@vueuse/core";
2
+ import { computed, onScopeDispose, ref, shallowRef, watch } from "vue";
3
+ function chronological(a, b) {
4
+ return a.timestamp - b.timestamp || a.id - b.id;
5
+ }
6
+ export function useActivityLog(load, socketUrl) {
7
+ const history = shallowRef([]);
8
+ const pausedEntries = shallowRef();
9
+ const paused = computed(() => pausedEntries.value !== void 0);
10
+ const entries = computed(() => pausedEntries.value ?? history.value);
11
+ const visibility = useDocumentVisibility();
12
+ const hasSnapshot = ref(false);
13
+ let clearedThrough;
14
+ let request;
15
+ function merge(incoming) {
16
+ const key = (entry) => `${entry.timestamp}/${entry.id}`;
17
+ const known = new Set(history.value.map(key));
18
+ const added = incoming.filter((entry) => {
19
+ if (clearedThrough && chronological(entry, clearedThrough) <= 0 || known.has(key(entry)))
20
+ return false;
21
+ known.add(key(entry));
22
+ return true;
23
+ });
24
+ if (added.length)
25
+ history.value = [...history.value, ...added].sort(chronological).slice(-500);
26
+ }
27
+ async function refresh() {
28
+ if (request || paused.value || visibility.value !== "visible")
29
+ return;
30
+ const controller = new AbortController();
31
+ request = controller;
32
+ try {
33
+ const snapshot = await load(controller.signal);
34
+ if (!controller.signal.aborted) {
35
+ merge(snapshot);
36
+ hasSnapshot.value = true;
37
+ }
38
+ } catch {
39
+ hasSnapshot.value = false;
40
+ } finally {
41
+ request = void 0;
42
+ }
43
+ }
44
+ const socket = socketUrl && typeof window !== "undefined" && "WebSocket" in window ? useWebSocket(socketUrl, {
45
+ autoReconnect: true,
46
+ onConnected: refresh,
47
+ onMessage(_, { data }) {
48
+ const update = JSON.parse(data);
49
+ if (update.event === "activity" && update.entry)
50
+ merge([update.entry]);
51
+ }
52
+ }) : void 0;
53
+ const poll = useIntervalFn(refresh, 5e3, { immediate: false });
54
+ const active = computed(() => typeof window !== "undefined" && visibility.value === "visible" && !paused.value);
55
+ watch(() => active.value && (!hasSnapshot.value || socket?.status.value !== "OPEN"), (needed) => {
56
+ if (needed)
57
+ poll.resume();
58
+ else
59
+ poll.pause();
60
+ }, { immediate: true });
61
+ watch(active, (visible) => {
62
+ if (visible)
63
+ void refresh();
64
+ }, { immediate: true });
65
+ onScopeDispose(() => request?.abort());
66
+ function togglePause() {
67
+ pausedEntries.value = paused.value ? void 0 : history.value;
68
+ }
69
+ function clearLog() {
70
+ clearedThrough = history.value.at(-1) ?? clearedThrough;
71
+ history.value = [];
72
+ if (paused.value)
73
+ pausedEntries.value = [];
74
+ }
75
+ return { entries, paused, togglePause, clearLog };
76
+ }
@@ -0,0 +1,7 @@
1
+ import type { SlashCommand } from '../../types.js';
2
+ export declare function useCommandRegistry(): {
3
+ commands: import("vue").ComputedRef<SlashCommand[]>;
4
+ diff: import("vue").ComputedRef<unknown>;
5
+ status: import("vue").Ref<import("nuxt/app").AsyncDataRequestStatus, import("nuxt/app").AsyncDataRequestStatus>;
6
+ refresh: () => Promise<void>;
7
+ };
@@ -0,0 +1,34 @@
1
+ import { useWebSocket } from "@vueuse/core";
2
+ import { computed, shallowRef, useFetch, useRuntimeConfig, watch } from "#imports";
3
+ import { useDashboardCatalog } from "./useDashboardCatalog.js";
4
+ export function useCommandRegistry() {
5
+ const catalog = useDashboardCatalog();
6
+ const updatedCommands = shallowRef();
7
+ const commands = computed(() => updatedCommands.value ?? catalog.commands.value);
8
+ const { data, status, refresh } = useFetch("/api/discord/slash-command/remote-diff", {
9
+ method: "post",
10
+ body: import.meta.dev ? computed(() => ({ commands: updatedCommands.value })) : void 0,
11
+ server: false,
12
+ watch: false
13
+ });
14
+ const diff = computed(() => status.value === "success" ? data.value : void 0);
15
+ const url = useRuntimeConfig().public.discord?.wsUrl;
16
+ if (import.meta.dev && import.meta.client && url) {
17
+ const { data: updates } = useWebSocket(url, {
18
+ autoReconnect: true,
19
+ onConnected: (socket) => socket.send(JSON.stringify({ event: "full-update" }))
20
+ });
21
+ watch(updates, (message) => {
22
+ if (!message)
23
+ return;
24
+ const update = JSON.parse(message);
25
+ if (update.event === "full-update" && Array.isArray(update.commands)) {
26
+ updatedCommands.value = update.commands;
27
+ void refresh();
28
+ } else if (update.event === "registration-updated") {
29
+ void refresh();
30
+ }
31
+ });
32
+ }
33
+ return { commands, diff, status, refresh: () => refresh() };
34
+ }
@@ -0,0 +1,5 @@
1
+ export declare function useDashboardCatalog(): {
2
+ commands: import("vue").ComputedRef<import("../../types.js").SlashCommand[]>;
3
+ menus: import("vue").ComputedRef<import("../../types.js").ContextMenu[]>;
4
+ listeners: import("vue").ComputedRef<import("../../types.js").Listener[]>;
5
+ };
@@ -0,0 +1,9 @@
1
+ import { computed, useFetch } from "#imports";
2
+ export function useDashboardCatalog() {
3
+ const { data } = useFetch("/api/discord/catalog", { server: false });
4
+ return {
5
+ commands: computed(() => data.value?.commands ?? []),
6
+ menus: computed(() => data.value?.menus ?? []),
7
+ listeners: computed(() => data.value?.listeners ?? [])
8
+ };
9
+ }
@@ -0,0 +1,2 @@
1
+ import type { DiscordCommandReference } from '../../types.js';
2
+ export declare function useDiscordCommandReference(): import("nuxt/app").AsyncData<DiscordCommandReference | undefined, import("nuxt/app").NuxtError<unknown> | undefined>;
@@ -0,0 +1,6 @@
1
+ import { useFetch, useRequestHeaders } from "#imports";
2
+ export function useDiscordCommandReference() {
3
+ return useFetch("/api/discord/reference", {
4
+ headers: import.meta.server ? useRequestHeaders(["host", "cookie"]) : void 0
5
+ });
6
+ }
@@ -0,0 +1,4 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<string | {
2
+ access: "read" | "manage";
3
+ } | undefined>>;
4
+ export default _default;
@@ -0,0 +1,55 @@
1
+ import process from "node:process";
2
+ import { defineEventHandler, getMethod, getRequestHeader, setResponseHeader, setResponseHeaders, setResponseStatus } from "h3";
3
+ import { getDashboardUserId, handleDashboardOAuth } from "./oauth.js";
4
+ import { acceptsOrigin, configuredOrigin } from "./origin.js";
5
+ import { dashboardAccessFor } from "./permissions.js";
6
+ import { renderAccessDeniedPage, renderSignInPage } from "./signin.js";
7
+ function rejectAccess(event, status, path) {
8
+ setResponseStatus(event, status);
9
+ if ((path === "/" || path === "/discord" || path.startsWith("/discord/")) && getMethod(event) === "GET" && getRequestHeader(event, "accept")?.includes("text/html")) {
10
+ setResponseHeader(event, "content-type", "text/html; charset=utf-8");
11
+ setResponseHeader(event, "content-security-policy", "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'");
12
+ return status === 401 ? renderSignInPage() : renderAccessDeniedPage();
13
+ }
14
+ return status === 401 ? "Sign in to the dashboard." : "Forbidden";
15
+ }
16
+ export default defineEventHandler(async (event) => {
17
+ setResponseHeaders(event, {
18
+ "cache-control": "private, no-store",
19
+ "cross-origin-resource-policy": "same-origin",
20
+ "referrer-policy": "no-referrer",
21
+ "x-frame-options": "DENY",
22
+ "x-content-type-options": "nosniff"
23
+ });
24
+ const url = configuredOrigin(process.env.DISCORD_DASHBOARD_ORIGIN);
25
+ const clientId = process.env.DISCORD_CLIENT_ID;
26
+ if (!url || !clientId || !/^\d+$/.test(clientId) || !process.env.DISCORD_TOKEN) {
27
+ setResponseStatus(event, 503);
28
+ return "Dashboard access is not configured.";
29
+ }
30
+ const method = getMethod(event);
31
+ const path = event.path.split("?")[0];
32
+ if (!acceptsOrigin(event, url)) {
33
+ setResponseStatus(event, 403);
34
+ return "Forbidden";
35
+ }
36
+ if (["/__discord-auth/login", "/__discord-auth/callback", "/__discord-auth/logout"].includes(path))
37
+ return handleDashboardOAuth(event, url, clientId);
38
+ const userId = getDashboardUserId(event, url);
39
+ if (!userId)
40
+ return rejectAccess(event, 401, path);
41
+ const access = await dashboardAccessFor(userId, method, path);
42
+ if (access === "unavailable") {
43
+ setResponseStatus(event, 503);
44
+ return "Discord access verification is temporarily unavailable.";
45
+ }
46
+ if (access === "forbidden")
47
+ return rejectAccess(event, 403, path);
48
+ if (path === "/__discord-auth/session") {
49
+ if (method === "GET" || method === "HEAD")
50
+ return { access };
51
+ setResponseHeader(event, "allow", "GET, HEAD");
52
+ setResponseStatus(event, 405);
53
+ return "Method not allowed";
54
+ }
55
+ });
@@ -0,0 +1,17 @@
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;
15
+ export declare function getDashboardUserId(event: H3Event, origin: URL): string | undefined;
16
+ export declare function handleDashboardOAuth(event: H3Event, origin: URL, clientId: string, options?: OAuthOptions): Promise<string | undefined>;
17
+ export {};
@@ -0,0 +1,172 @@
1
+ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
2
+ import { deleteCookie, getCookie, getMethod, getQuery, setCookie, setResponseHeader, setResponseStatus } from "h3";
3
+ const loginSeconds = 10 * 60;
4
+ const sessionSeconds = 8 * 60 * 60;
5
+ const capacity = 1024;
6
+ const tokenPattern = /^[\w-]{43}$/;
7
+ const snowflakePattern = /^[1-9]\d{0,19}$/;
8
+ function opaqueToken() {
9
+ return randomBytes(32).toString("base64url");
10
+ }
11
+ function digest(value) {
12
+ return createHash("sha256").update(value).digest();
13
+ }
14
+ class ExpiringTokens {
15
+ entries = /* @__PURE__ */ new Map();
16
+ issue(value, seconds) {
17
+ const now = Date.now();
18
+ for (const [key, entry] of this.entries) {
19
+ if (entry.expires > now && this.entries.size < capacity)
20
+ break;
21
+ this.entries.delete(key);
22
+ }
23
+ const token = opaqueToken();
24
+ this.entries.set(digest(token).toString("hex"), { expires: now + seconds * 1e3, value });
25
+ return token;
26
+ }
27
+ get(token) {
28
+ if (!token || !tokenPattern.test(token))
29
+ return;
30
+ const key = digest(token).toString("hex");
31
+ const entry = this.entries.get(key);
32
+ if (entry && entry.expires > Date.now())
33
+ return entry.value;
34
+ this.entries.delete(key);
35
+ }
36
+ revoke(token) {
37
+ if (token && tokenPattern.test(token))
38
+ this.entries.delete(digest(token).toString("hex"));
39
+ }
40
+ }
41
+ function tokenStores() {
42
+ return { logins: new ExpiringTokens(), sessions: new ExpiringTokens() };
43
+ }
44
+ const audiences = { dashboard: tokenStores(), reference: tokenStores() };
45
+ function cookies(origin, audience) {
46
+ const secure = origin.protocol === "https:";
47
+ const prefix = `${secure ? "__Host-" : ""}nuxt_discord_${audience === "reference" ? "reference_" : ""}`;
48
+ return {
49
+ session: `${prefix}session`,
50
+ login: `${prefix}login`,
51
+ options: { httpOnly: true, secure, sameSite: "lax", path: "/" }
52
+ };
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
+ }
58
+ export function getDashboardUserId(event, origin) {
59
+ return getDiscordSession(event, origin, "dashboard")?.userId;
60
+ }
61
+ function redirect(event, location) {
62
+ setResponseStatus(event, 303);
63
+ setResponseHeader(event, "location", location);
64
+ return "";
65
+ }
66
+ function reject(event, status, message) {
67
+ setResponseStatus(event, status);
68
+ return message;
69
+ }
70
+ async function identifyUser(clientId, redirectUri, verifier, code, sharedGuilds) {
71
+ const exchange = await fetch("https://discord.com/api/v10/oauth2/token", {
72
+ method: "POST",
73
+ redirect: "error",
74
+ signal: AbortSignal.timeout(8e3),
75
+ body: new URLSearchParams({ grant_type: "authorization_code", client_id: clientId, redirect_uri: redirectUri, code_verifier: verifier, code })
76
+ });
77
+ if (!exchange.ok)
78
+ return;
79
+ const token = await exchange.json();
80
+ if (typeof token.access_token !== "string" || !token.access_token || token.token_type?.toLowerCase() !== "bearer")
81
+ return;
82
+ const response = await fetch("https://discord.com/api/v10/users/@me", {
83
+ headers: { authorization: `Bearer ${token.access_token}` },
84
+ redirect: "error",
85
+ signal: AbortSignal.timeout(8e3)
86
+ });
87
+ if (!response.ok)
88
+ return;
89
+ const user = await response.json();
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)) };
105
+ }
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`;
113
+ const path = event.path.split("?")[0];
114
+ if (path !== loginPath && path !== callbackPath && path !== logoutPath)
115
+ return;
116
+ const method = path === logoutPath ? "POST" : "GET";
117
+ if (getMethod(event) !== method) {
118
+ setResponseHeader(event, "allow", method);
119
+ return reject(event, 405, "Method not allowed.");
120
+ }
121
+ const cookie = cookies(origin, audience);
122
+ const browserToken = getCookie(event, cookie.login);
123
+ if (path === logoutPath) {
124
+ sessions.revoke(getCookie(event, cookie.session));
125
+ logins.revoke(browserToken);
126
+ deleteCookie(event, cookie.session, cookie.options);
127
+ deleteCookie(event, cookie.login, cookie.options);
128
+ return redirect(event, landing);
129
+ }
130
+ if (!snowflakePattern.test(clientId))
131
+ return reject(event, 503, "Discord sign-in is not configured.");
132
+ const redirectUri = new URL(callbackPath, origin).href;
133
+ if (path === loginPath) {
134
+ const verifier = opaqueToken();
135
+ const state2 = opaqueToken();
136
+ logins.revoke(browserToken);
137
+ const token = logins.issue({ state: state2, verifier, origin: origin.origin, clientId, landing }, loginSeconds);
138
+ setCookie(event, cookie.login, token, { ...cookie.options, maxAge: loginSeconds });
139
+ const authorize = new URL("https://discord.com/oauth2/authorize");
140
+ authorize.search = new URLSearchParams({
141
+ response_type: "code",
142
+ client_id: clientId,
143
+ scope: sharedGuilds ? "identify guilds" : "identify",
144
+ prompt: "consent",
145
+ redirect_uri: redirectUri,
146
+ state: state2,
147
+ code_challenge_method: "S256",
148
+ code_challenge: digest(verifier).toString("base64url")
149
+ }).toString();
150
+ return redirect(event, authorize.href);
151
+ }
152
+ const login = logins.get(browserToken);
153
+ const { state, code, error, iss } = getQuery(event);
154
+ if (!login || login.origin !== origin.origin || login.clientId !== clientId || typeof state !== "string" || !tokenPattern.test(state) || !timingSafeEqual(digest(state), digest(login.state))) {
155
+ return reject(event, 400, "Discord sign-in expired or could not be verified.");
156
+ }
157
+ logins.revoke(browserToken);
158
+ deleteCookie(event, cookie.login, cookie.options);
159
+ if (error !== void 0 || typeof code !== "string" || !code || iss !== void 0 && iss !== "https://discord.com")
160
+ return reject(event, 400, "Discord sign-in was not completed.");
161
+ try {
162
+ const identity = await identifyUser(clientId, redirectUri, login.verifier, code, sharedGuilds);
163
+ if (identity) {
164
+ sessions.revoke(getCookie(event, cookie.session));
165
+ const token = sessions.issue({ ...identity, origin: origin.origin, audience }, sessionSeconds);
166
+ setCookie(event, cookie.session, token, { ...cookie.options, maxAge: sessionSeconds });
167
+ return redirect(event, login.landing);
168
+ }
169
+ } catch {
170
+ }
171
+ return reject(event, 502, "Discord could not verify your sign-in.");
172
+ }
@@ -0,0 +1,3 @@
1
+ import type { H3Event } from 'h3';
2
+ export declare function configuredOrigin(origin?: string): URL | undefined;
3
+ export declare function acceptsOrigin(event: H3Event, url: URL): boolean;
@@ -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
+ }
@@ -0,0 +1,4 @@
1
+ type DashboardRole = 'manage' | 'read';
2
+ type DashboardAccess = DashboardRole | 'forbidden' | 'unavailable';
3
+ export declare function dashboardAccessFor(userId: string, method: string, pathname: string): Promise<DashboardAccess>;
4
+ export {};
@@ -0,0 +1,84 @@
1
+ import process from "node:process";
2
+ const readPaths = /* @__PURE__ */ new Set([
3
+ "/",
4
+ "/favicon.ico",
5
+ "/discord",
6
+ "/discord/slash-commands",
7
+ "/discord/context-menus",
8
+ "/discord/listeners",
9
+ "/discord/activity",
10
+ "/__discord-auth/session",
11
+ "/api/discord/catalog",
12
+ "/api/discord/activity",
13
+ "/api/discord/slash-command/all",
14
+ "/api/discord/slash-command/remote-all"
15
+ ]);
16
+ function isReadRequest(method, pathname) {
17
+ if (method === "POST")
18
+ return pathname === "/api/discord/slash-command/remote-diff";
19
+ if (method !== "GET" && method !== "HEAD")
20
+ return false;
21
+ return readPaths.has(pathname) || /^\/_nuxt\/(?:[\w@-][\w.@-]*\/)*[\w@-][\w.@-]*$/.test(pathname) || /^\/api\/_nuxt_icon\/[\w-]+(?:\.json)?$/.test(pathname);
22
+ }
23
+ function isId(id) {
24
+ return typeof id === "string" && /^[1-9]\d{0,19}$/.test(id);
25
+ }
26
+ async function loadRoles(appId, token) {
27
+ try {
28
+ const response = await fetch("https://discord.com/api/v10/applications/@me", {
29
+ headers: { Authorization: `Bot ${token}` },
30
+ cache: "no-store",
31
+ redirect: "error",
32
+ signal: AbortSignal.timeout(5e3)
33
+ });
34
+ if (!response.ok)
35
+ return;
36
+ const application = await response.json();
37
+ if (application?.id !== appId)
38
+ return;
39
+ const roles = /* @__PURE__ */ new Map();
40
+ const team = application.team;
41
+ if (team === null && isId(application.owner?.id)) {
42
+ roles.set(application.owner.id, "manage");
43
+ return roles;
44
+ }
45
+ if (!isId(team?.owner_user_id) || !Array.isArray(team.members))
46
+ return;
47
+ for (const member of team.members) {
48
+ if (member?.membership_state !== 2 || !isId(member.user?.id))
49
+ continue;
50
+ if (member.role === "admin" || member.role === "developer")
51
+ roles.set(member.user.id, "manage");
52
+ else if (member.role === "read_only")
53
+ roles.set(member.user.id, "read");
54
+ }
55
+ roles.set(team.owner_user_id, "manage");
56
+ return roles;
57
+ } catch {
58
+ return void 0;
59
+ }
60
+ }
61
+ let cache;
62
+ export async function dashboardAccessFor(userId, method, pathname) {
63
+ if (!isId(userId))
64
+ return "forbidden";
65
+ const { DISCORD_CLIENT_ID: appId, DISCORD_TOKEN: token } = process.env;
66
+ if (!isId(appId) || !token) {
67
+ cache = void 0;
68
+ return "unavailable";
69
+ }
70
+ const read = isReadRequest(method, pathname);
71
+ if (!read || !cache || cache.appId !== appId || cache.token !== token || Date.now() >= cache.expires)
72
+ cache = { appId, token, expires: Date.now() + 15e3, roles: loadRoles(appId, token) };
73
+ const source = cache;
74
+ const roles = await source.roles;
75
+ if (!roles) {
76
+ if (cache === source)
77
+ cache = void 0;
78
+ return "unavailable";
79
+ }
80
+ const role = roles.get(userId);
81
+ if (role === "manage" || read && role === "read")
82
+ return role;
83
+ return "forbidden";
84
+ }
@@ -0,0 +1,3 @@
1
+ export declare function renderSignInPage(): string;
2
+ export declare function renderAccessDeniedPage(): string;
3
+ export declare function renderReferenceAccessPage(status: 401 | 403): string;
@@ -0,0 +1,42 @@
1
+ function page(heading, action) {
2
+ return `<!doctype html>
3
+ <html lang="en">
4
+ <head>
5
+ <meta charset="utf-8">
6
+ <meta name="viewport" content="width=device-width, initial-scale=1">
7
+ <meta name="color-scheme" content="light dark">
8
+ <title>${heading} \xB7 Nuxt Discord</title>
9
+ <style>
10
+ :root { color-scheme: light dark; font: 100%/1.5 system-ui, sans-serif; --bg: #f8fafc; --panel: #fff; --text: #0f172a; --muted: #475569; --line: #cbd5e1; --action: #007a47; --on-action: #fff; }
11
+ @media (prefers-color-scheme: dark) {
12
+ :root { --bg: #0f172a; --panel: #172033; --text: #f1f5f9; --muted: #cbd5e1; --line: #39465b; --action: #62e5a0; --on-action: #092518; }
13
+ }
14
+ * { box-sizing: border-box; }
15
+ body { margin: 0; min-height: 100svh; display: grid; place-items: center; padding: 1rem; color: var(--text); background: var(--bg); }
16
+ main { width: min(100%, 28rem); padding: clamp(1.25rem, 5vw, 2rem); border: 1px solid var(--line); border-radius: .75rem; background: var(--panel); }
17
+ .brand { margin: 0; color: var(--muted); font-size: .875rem; font-weight: 650; }
18
+ h1 { margin: .75rem 0 1.5rem; font-size: clamp(1.5rem, 5vw, 2rem); line-height: 1.2; letter-spacing: -.03em; }
19
+ form { margin: 0; }
20
+ .action { display: inline-flex; align-items: center; min-height: 2.75rem; padding: .55rem 1rem; border: 1px solid transparent; border-radius: .4rem; background: var(--action); color: var(--on-action); font: inherit; font-weight: 600; text-decoration: none; cursor: pointer; }
21
+ .action:hover { text-decoration: underline; text-underline-offset: .15em; }
22
+ .action:focus-visible { outline: 2px solid currentColor; outline-offset: 3px; outline-color: var(--text); }
23
+ </style>
24
+ </head>
25
+ <body>
26
+ <main>
27
+ <p class="brand">nuxt-discord</p>
28
+ <h1>${heading}</h1>
29
+ ${action}
30
+ </main>
31
+ </body>
32
+ </html>`;
33
+ }
34
+ export function renderSignInPage() {
35
+ return page("Sign in to the dashboard", '<a class="action" href="/__discord-auth/login">Sign in with Discord</a>');
36
+ }
37
+ export function renderAccessDeniedPage() {
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
+ }
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,4 @@
1
+ export declare class DiscordConfigurationError extends Error {
2
+ }
3
+ export declare function discordDiagnostic(error: unknown): string | undefined;
4
+ export declare function logDiscordFailure(context: string, error?: unknown): void;
@@ -0,0 +1,24 @@
1
+ import { constants } from "node:os";
2
+ import { DiscordjsErrorCodes } from "discord.js";
3
+ import { logger } from "./logger.js";
4
+ export class DiscordConfigurationError extends Error {
5
+ }
6
+ export function discordDiagnostic(error) {
7
+ if (error instanceof DiscordConfigurationError)
8
+ return error.message;
9
+ if (!error || typeof error !== "object")
10
+ return;
11
+ const code = Object.getOwnPropertyDescriptor(error, "code")?.value;
12
+ const status = Object.getOwnPropertyDescriptor(error, "status")?.value;
13
+ const parts = [];
14
+ if (typeof status === "number" && Number.isInteger(status) && status >= 100 && status <= 599)
15
+ parts.push(`HTTP ${status}`);
16
+ if (typeof code === "number" && Number.isSafeInteger(code) || typeof code === "string" && (Object.hasOwn(DiscordjsErrorCodes, code) || Object.hasOwn(constants.errno, code))) {
17
+ parts.push(`code ${code}`);
18
+ }
19
+ return parts.join(", ") || void 0;
20
+ }
21
+ export function logDiscordFailure(context, error) {
22
+ const diagnostic = discordDiagnostic(error);
23
+ logger.error(diagnostic ? `${context} (${diagnostic})` : context);
24
+ }