nuxt-discord 0.1.0 → 0.2.1

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 (52) hide show
  1. package/dist/module.d.mts +41 -1
  2. package/dist/module.json +1 -1
  3. package/dist/module.mjs +131 -11
  4. package/dist/runtime/acknowledgement.d.ts +2 -1
  5. package/dist/runtime/acknowledgement.js +44 -12
  6. package/dist/runtime/client/components/CommandCard.d.ts +29 -0
  7. package/dist/runtime/client/components/CommandCard.js +75 -0
  8. package/dist/runtime/client/components/CommandReference.d.vue.ts +20 -0
  9. package/dist/runtime/client/components/CommandReference.vue +21 -0
  10. package/dist/runtime/client/components/CommandReference.vue.d.ts +20 -0
  11. package/dist/runtime/client/components/CommandTestBar.vue +0 -3
  12. package/dist/runtime/client/components/CommandsHeading.d.ts +24 -0
  13. package/dist/runtime/client/components/CommandsHeading.js +17 -0
  14. package/dist/runtime/client/components/DashboardHeader.d.ts +32 -0
  15. package/dist/runtime/client/components/DashboardHeader.js +32 -0
  16. package/dist/runtime/client/components/ProjectLogo.d.ts +4 -0
  17. package/dist/runtime/client/components/ProjectLogo.js +31 -0
  18. package/dist/runtime/client/components/ReferenceContent.d.ts +22 -0
  19. package/dist/runtime/client/components/ReferenceContent.js +45 -0
  20. package/dist/runtime/client/components/TheHeader.vue +33 -52
  21. package/dist/runtime/client/components/appearance-select.d.ts +1 -1
  22. package/dist/runtime/client/components/appearance-select.js +1 -1
  23. package/dist/runtime/client/pages/slash-commands.vue +28 -110
  24. package/dist/runtime/client/reference.css +133 -0
  25. package/dist/runtime/client/useDiscordCommandReference.d.ts +2 -0
  26. package/dist/runtime/client/useDiscordCommandReference.js +6 -0
  27. package/dist/runtime/dashboard/auth.js +10 -17
  28. package/dist/runtime/dashboard/oauth.d.ts +15 -1
  29. package/dist/runtime/dashboard/oauth.js +42 -21
  30. package/dist/runtime/dashboard/origin.d.ts +2 -0
  31. package/dist/runtime/dashboard/origin.js +8 -0
  32. package/dist/runtime/dashboard/signin.d.ts +2 -1
  33. package/dist/runtime/dashboard/signin.js +7 -2
  34. package/dist/runtime/dashboard/urls.d.ts +2 -0
  35. package/dist/runtime/dashboard/urls.js +8 -0
  36. package/dist/runtime/reference/access.d.ts +6 -0
  37. package/dist/runtime/reference/access.js +144 -0
  38. package/dist/runtime/reference/catalog.d.ts +2 -0
  39. package/dist/runtime/reference/catalog.js +9 -0
  40. package/dist/runtime/reference/document.d.ts +2 -0
  41. package/dist/runtime/reference/document.js +25 -0
  42. package/dist/runtime/reference/hosted.d.ts +2 -0
  43. package/dist/runtime/reference/hosted.js +16 -0
  44. package/dist/runtime/reference/oauth.d.ts +2 -0
  45. package/dist/runtime/reference/oauth.js +4 -0
  46. package/dist/runtime/server/plugins/discord.js +2 -0
  47. package/dist/types.d.mts +1 -1
  48. package/dist/types.d.ts +1 -1
  49. package/package.json +1 -1
  50. package/dist/runtime/client/components/ProjectLogo.d.vue.ts +0 -3
  51. package/dist/runtime/client/components/ProjectLogo.vue +0 -31
  52. package/dist/runtime/client/components/ProjectLogo.vue.d.ts +0 -3
@@ -0,0 +1,133 @@
1
+ /* Both the dashboard and the script-free reference use the same command view. */
2
+ :where(.nd-header, .discord-reference, .nd-command-card, .nd-commands-heading, .nd-reference-page) {
3
+ --nd-bg: var(--ui-bg, light-dark(#fff, #0f172b));
4
+ --nd-elevated: var(--ui-bg-elevated, light-dark(#f1f5f9, #1d293d));
5
+ --nd-border: var(--ui-border, light-dark(#e2e8f0, #1d293d));
6
+ --nd-text: var(--ui-text, light-dark(#314158, #e2e8f0));
7
+ --nd-strong: var(--ui-text-highlighted, light-dark(#0f172b, #fff));
8
+ --nd-muted: var(--ui-text-muted, light-dark(#45556c, #90a1b9));
9
+ }
10
+ html:has(.nd-reference-page) { color-scheme: light dark; background: light-dark(#fff, #0f172b); }
11
+ body:has(.nd-reference-page) { margin: 0; }
12
+ .nd-reference-page, .discord-reference {
13
+ color: var(--nd-text);
14
+ background: var(--nd-bg);
15
+ font: 1rem/1.5 ui-sans-serif, system-ui, sans-serif;
16
+ }
17
+ .nd-reference-page { min-height: 100vh; }
18
+ .discord-reference { overflow-wrap: anywhere; }
19
+ .nd-reference-page *, .discord-reference * { box-sizing: border-box; }
20
+ .discord-reference { box-sizing: border-box; max-width: 72rem; margin: auto; padding: 2rem 1.5rem 4rem; }
21
+ .discord-reference :where(p, h1, h2, dl, dd) { margin: 0; }
22
+ .nd-reference-page :where(a, button, summary):focus-visible, .discord-reference :where(a, summary):focus-visible,
23
+ .nd-command-card summary:focus-visible { outline: 2px solid currentColor; outline-offset: 3px; }
24
+ .nd-header {
25
+ position: sticky; inset-block-start: 0; z-index: 50;
26
+ border-bottom: 1px solid var(--nd-border);
27
+ background: color-mix(in srgb, var(--nd-bg) 80%, transparent);
28
+ backdrop-filter: blur(24px);
29
+ }
30
+ .nd-header-row {
31
+ box-sizing: border-box; display: flex; align-items: center; justify-content: space-between;
32
+ height: 3.5rem; max-width: 72rem; padding-inline: 1.5rem; margin-inline: auto;
33
+ }
34
+ .nd-header-start, .nd-brand, .nd-header-actions, .nd-desktop-nav { display: flex; align-items: center; }
35
+ .nd-header-start { gap: 1.5rem; }
36
+ .nd-brand { gap: .625rem; font-size: .875rem; font-weight: 600; letter-spacing: -.025em; white-space: nowrap; }
37
+ .nd-header :where(.nd-brand, nav a, .ref-admin-entry) { color: inherit; text-decoration: none; }
38
+ .nd-brand svg { flex: none; }
39
+ .nd-header-actions, .nd-desktop-nav { gap: .25rem; }
40
+ .nd-skip:not(:focus) { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }
41
+ .nd-skip:focus { position: absolute; z-index: 1; padding: .5rem; background: var(--nd-bg); color: var(--nd-strong); }
42
+ .nd-desktop-nav a {
43
+ padding: .25rem .625rem; border-radius: .375rem; color: var(--nd-muted);
44
+ font-size: .75rem; line-height: 1rem; font-weight: 500;
45
+ }
46
+ .nd-desktop-nav a:is(:hover, [aria-current=page]), .nd-header-actions :is(.ref-admin-entry, form button):hover {
47
+ color: var(--nd-strong); background: var(--nd-elevated);
48
+ }
49
+ .nd-mobile-nav { display: none; }
50
+ .nd-mobile-nav a { flex: none; }
51
+ .nd-mobile-nav a[aria-current=page] { font-weight: 700; }
52
+ .nd-header-actions :where(.ref-admin-entry, form button) {
53
+ display: inline-flex; align-items: center; min-height: 2.75rem; padding: .25rem .5rem;
54
+ color: var(--nd-muted); background: none; border: 0; border-radius: .375rem; cursor: pointer;
55
+ font: inherit; font-size: .875rem; font-weight: 500; white-space: nowrap;
56
+ }
57
+ @media (max-width: 22.5rem) {
58
+ .nd-header-row { padding-inline: .75rem; }
59
+ .nd-header-actions :where(.ref-admin-entry, form button) { padding-inline: .25rem; }
60
+ }
61
+ @media (max-width: 39.999rem) {
62
+ .nd-header { --nd-desktop-display: none; --nd-mobile-display: flex; }
63
+ }
64
+ @media (max-width: 47.999rem) {
65
+ .nd-header-hosted { --nd-desktop-display: none; --nd-mobile-display: flex; }
66
+ }
67
+ .nd-desktop-nav { display: var(--nd-desktop-display, flex); }
68
+ .nd-mobile-nav {
69
+ display: var(--nd-mobile-display, none); gap: .75rem; overflow-x: auto; padding: .5rem 1rem;
70
+ border-top: 1px solid var(--nd-border); font-size: .875rem; line-height: 1.25rem;
71
+ }
72
+
73
+ .nd-commands-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 1rem; margin-bottom: 2rem; }
74
+ .nd-commands-heading h1 { margin: 0; font-size: 1.5rem; line-height: 2rem; font-weight: 700; letter-spacing: -.025em; }
75
+ .nd-commands-heading p, .nd-description, .nd-menu dd { margin: .25rem 0 0; color: var(--nd-muted); font-size: .875rem; line-height: 1.25rem; }
76
+ .nd-divider { border: 0; border-top: 1px solid var(--nd-border); margin: 0 0 2rem; }
77
+ :where(.nd-command-card) {
78
+ color: var(--nd-text); background: var(--nd-bg); border: 1px solid var(--nd-border); border-radius: .5rem;
79
+ }
80
+ .nd-command-card, .nd-menus, .nd-reference-page main { scroll-margin-top: 7rem; }
81
+ .discord-reference .nd-command-card + .nd-command-card { margin-top: .75rem; }
82
+ .nd-card-header { display: flex; justify-content: space-between; align-items: flex-start; gap: 1rem; }
83
+ .nd-card-header, .nd-card-footer, .nd-menu { padding: 1rem; }
84
+ .nd-card-options, .nd-card-footer { border-top: 1px solid var(--nd-border); }
85
+ .nd-card-options { display: flex; align-items: flex-start; flex-wrap: wrap; gap: .5rem; padding: 1rem; }
86
+ .nd-card-intro { min-width: 0; flex: 1; overflow-wrap: anywhere; }
87
+ .nd-card-title { display: flex; align-items: center; flex-wrap: wrap; gap: .5rem; }
88
+ .nd-card-title h2 {
89
+ margin: 0; color: var(--nd-strong); font-size: 1rem; line-height: 1.5rem; font-weight: 600;
90
+ }
91
+ .nd-card-title code { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; font-size: inherit; }
92
+ .nd-card-title a { color: inherit; text-decoration: none; }
93
+ .nd-card-title a:hover { text-decoration: underline; text-underline-offset: .18em; }
94
+ .nd-option {
95
+ min-width: 0; max-width: 100%; font-size: .75rem; line-height: 1rem;
96
+ border: 1px solid var(--nd-border); border-radius: .375rem; background: var(--nd-elevated);
97
+ }
98
+ .nd-option > summary {
99
+ display: flex; align-items: center; flex-wrap: wrap; gap: .375rem; cursor: pointer;
100
+ padding: .375rem .625rem; border-radius: inherit; overflow-wrap: anywhere; list-style: none;
101
+ }
102
+ .nd-option > summary::-webkit-details-marker { display: none; }
103
+ .nd-option > summary::after {
104
+ content: ''; width: .3rem; height: .3rem; margin: 0 .125rem .15rem .125rem;
105
+ border: solid var(--nd-muted); border-width: 0 1px 1px 0; transform: rotate(45deg);
106
+ }
107
+ .nd-option[open] > summary::after { transform: rotate(225deg); margin-bottom: -.15rem; }
108
+ .nd-option-name { font-weight: 500; }
109
+ .nd-optional { color: var(--nd-muted); }
110
+ .nd-badge {
111
+ display: inline-flex; align-items: center; border-radius: .25rem; padding: .125rem .25rem;
112
+ color: var(--nd-text); font-size: .625rem; line-height: .75rem; font-weight: 500;
113
+ box-shadow: inset 0 0 0 1px var(--nd-border);
114
+ }
115
+ .nd-primary, .nd-success { --nd-tint: light-dark(#007a45, #7bf1a8); }
116
+ .nd-info, .nd-auto { --nd-tint: light-dark(#1447e6, #8ec5ff); }
117
+ .nd-secondary { --nd-tint: light-dark(#7008e7, #dab2ff); }
118
+ .nd-warning { --nd-tint: light-dark(#894b00, #ffd230); }
119
+ .nd-neutral { --nd-tint: var(--nd-text); }
120
+ .nd-type, .nd-auto { color: var(--nd-tint); box-shadow: inset 0 0 0 1px color-mix(in srgb, currentColor 25%, transparent); }
121
+ .nd-type { background: color-mix(in srgb, currentColor 9%, transparent); }
122
+ .nd-option-detail { max-width: 30rem; padding: 0 .625rem .5rem; color: var(--nd-muted); overflow-wrap: anywhere; }
123
+ .nd-option-detail p { margin: .25rem 0 0; }
124
+ .nd-option-detail p:first-child { color: var(--nd-text); }
125
+ .nd-empty { padding: 4rem 1rem; text-align: center; }
126
+ .nd-menus { margin-top: 2.5rem; }
127
+ .nd-menus h2 { margin: 0 0 1rem; font-size: 1.25rem; line-height: 1.75rem; }
128
+ .nd-menu dt { font-weight: 600; }
129
+ @media (min-width: 40rem) {
130
+ .nd-card-header, .nd-card-footer, .nd-menu { padding-inline: 1.5rem; }
131
+ .nd-card-options { padding: 1.5rem; }
132
+ .nd-command-card, .nd-menus, .nd-reference-page main { scroll-margin-top: 4.5rem; }
133
+ }
@@ -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
+ }
@@ -1,22 +1,16 @@
1
1
  import process from "node:process";
2
- import { defineEventHandler, getMethod, getRequestHeader, setResponseHeader, setResponseHeaders, setResponseStatus } from "h3";
2
+ import { defineEventHandler, getMethod, getQuery, getRequestHeader, setResponseHeader, setResponseHeaders, setResponseStatus } from "h3";
3
3
  import { getDashboardUserId, handleDashboardOAuth } from "./oauth.js";
4
+ import { acceptsOrigin } 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
- }
7
+ import { configuredOrigin, dashboardCommandsPath } from "./urls.js";
14
8
  function rejectAccess(event, status, path) {
15
9
  setResponseStatus(event, status);
16
10
  if ((path === "/" || path === "/discord" || path.startsWith("/discord/")) && getMethod(event) === "GET" && getRequestHeader(event, "accept")?.includes("text/html")) {
17
11
  setResponseHeader(event, "content-type", "text/html; charset=utf-8");
18
12
  setResponseHeader(event, "content-security-policy", "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'");
19
- return status === 401 ? renderSignInPage() : renderAccessDeniedPage();
13
+ return status === 401 ? renderSignInPage(path) : renderAccessDeniedPage();
20
14
  }
21
15
  return status === 401 ? "Sign in to the dashboard." : "Forbidden";
22
16
  }
@@ -28,7 +22,7 @@ export default defineEventHandler(async (event) => {
28
22
  "x-frame-options": "DENY",
29
23
  "x-content-type-options": "nosniff"
30
24
  });
31
- const url = privateOrigin();
25
+ const url = configuredOrigin(process.env.DISCORD_DASHBOARD_ORIGIN);
32
26
  const clientId = process.env.DISCORD_CLIENT_ID;
33
27
  if (!url || !clientId || !/^\d+$/.test(clientId) || !process.env.DISCORD_TOKEN) {
34
28
  setResponseStatus(event, 503);
@@ -36,15 +30,14 @@ export default defineEventHandler(async (event) => {
36
30
  }
37
31
  const method = getMethod(event);
38
32
  const path = event.path.split("?")[0];
39
- const requestOrigin = getRequestHeader(event, "origin");
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) {
33
+ if (!acceptsOrigin(event, url)) {
43
34
  setResponseStatus(event, 403);
44
35
  return "Forbidden";
45
36
  }
46
- if (["/__discord-auth/login", "/__discord-auth/callback", "/__discord-auth/logout"].includes(path))
47
- return handleDashboardOAuth(event, url, clientId);
37
+ if (["/__discord-auth/login", "/__discord-auth/callback", "/__discord-auth/logout"].includes(path)) {
38
+ const landing = path === "/__discord-auth/login" && getQuery(event).view === "commands" ? dashboardCommandsPath : "/discord";
39
+ return handleDashboardOAuth(event, url, clientId, { audience: "dashboard", landing });
40
+ }
48
41
  const userId = getDashboardUserId(event, url);
49
42
  if (!userId)
50
43
  return rejectAccess(event, 401, path);
@@ -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
- const logins = new ExpiringTokens();
45
- const sessions = new ExpiringTokens();
46
- function cookies(origin) {
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-nuxt_discord_" : "nuxt_discord_";
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
- const session = sessions.get(getCookie(event, cookies(origin).session));
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 === "string" && snowflakePattern.test(user.id) && !user.bot)
89
- return user.id;
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, "/discord");
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 userId = await identifyUser(clientId, redirectUri, login.verifier, code);
142
- if (userId) {
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({ userId, origin: origin.origin }, sessionSeconds);
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, "/discord");
167
+ return redirect(event, login.landing);
147
168
  }
148
169
  } catch {
149
170
  }
@@ -0,0 +1,2 @@
1
+ import type { H3Event } from 'h3';
2
+ export declare function acceptsOrigin(event: H3Event, url: URL): boolean;
@@ -0,0 +1,8 @@
1
+ import { getMethod, getRequestHeader } from "h3";
2
+ export function acceptsOrigin(event, url) {
3
+ const method = getMethod(event);
4
+ const requestOrigin = getRequestHeader(event, "origin");
5
+ const write = !["GET", "HEAD"].includes(method);
6
+ const navigation = getRequestHeader(event, "sec-fetch-mode") === "navigate" && getRequestHeader(event, "sec-fetch-dest") === "document";
7
+ return !(getRequestHeader(event, "host")?.toLowerCase() !== url.host || getRequestHeader(event, "sec-fetch-site") === "cross-site" && (write || !navigation) || (write || requestOrigin !== void 0) && requestOrigin !== url.origin);
8
+ }
@@ -1,2 +1,3 @@
1
- export declare function renderSignInPage(): string;
1
+ export declare function renderSignInPage(path: string): string;
2
2
  export declare function renderAccessDeniedPage(): string;
3
+ export declare function renderReferenceAccessPage(status: 401 | 403): string;
@@ -1,3 +1,4 @@
1
+ import { dashboardCommandsPath } from "./urls.js";
1
2
  function page(heading, action) {
2
3
  return `<!doctype html>
3
4
  <html lang="en">
@@ -31,9 +32,13 @@ function page(heading, action) {
31
32
  </body>
32
33
  </html>`;
33
34
  }
34
- export function renderSignInPage() {
35
- return page("Sign in to the dashboard", '<a class="action" href="/__discord-auth/login">Sign in with Discord</a>');
35
+ export function renderSignInPage(path) {
36
+ const login = path === dashboardCommandsPath ? "/__discord-auth/login?view=commands" : "/__discord-auth/login";
37
+ return page("Sign in to the dashboard", `<a class="action" href="${login}">Sign in with Discord</a>`);
36
38
  }
37
39
  export function renderAccessDeniedPage() {
38
40
  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
41
  }
42
+ export function renderReferenceAccessPage(status) {
43
+ 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>');
44
+ }
@@ -0,0 +1,2 @@
1
+ export declare const dashboardCommandsPath = "/discord/slash-commands";
2
+ export declare function configuredOrigin(origin?: string): URL | undefined;
@@ -0,0 +1,8 @@
1
+ export const dashboardCommandsPath = "/discord/slash-commands";
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
+ }
@@ -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,144 @@
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 } from "../dashboard/origin.js";
5
+ import { dashboardAccessFor } from "../dashboard/permissions.js";
6
+ import { renderReferenceAccessPage } from "../dashboard/signin.js";
7
+ import { configuredOrigin } from "../dashboard/urls.js";
8
+ import { useDiscordClient } from "../server/utils/useDiscordClient.js";
9
+ const authPaths = ["/__discord-reference/login", "/__discord-reference/callback", "/__discord-reference/logout"];
10
+ export function referenceRequest(path, method, options) {
11
+ if (method === "GET" || method === "HEAD") {
12
+ if (path === "/api/discord/reference" || options.page !== false && path === "/commands")
13
+ return true;
14
+ if (method === "GET" && options.access !== "public" && authPaths.slice(0, 2).includes(path))
15
+ return true;
16
+ }
17
+ return method === "POST" && options.access !== "public" && path === authPaths[2];
18
+ }
19
+ function referenceHeaders(event) {
20
+ setResponseHeaders(event, {
21
+ "cache-control": "private, no-store",
22
+ "cross-origin-resource-policy": "same-origin",
23
+ "referrer-policy": "no-referrer",
24
+ "x-content-type-options": "nosniff",
25
+ "x-frame-options": "DENY"
26
+ });
27
+ }
28
+ function signInConfig(event, policy) {
29
+ const url = configuredOrigin(process.env.DISCORD_REFERENCE_ORIGIN ?? process.env.DISCORD_DASHBOARD_ORIGIN);
30
+ const clientId = process.env.DISCORD_CLIENT_ID;
31
+ if (!url || !clientId || !/^[1-9]\d{0,19}$/.test(clientId) || policy.access !== "authenticated" && !process.env.DISCORD_TOKEN)
32
+ throw createError({ statusCode: 503, statusMessage: "Command reference sign-in is not configured." });
33
+ if (!acceptsOrigin(event, url))
34
+ throw createError({ statusCode: 403, statusMessage: "Forbidden" });
35
+ return { url, clientId };
36
+ }
37
+ let verifiedBot;
38
+ async function botIdentityMatches(clientId, token) {
39
+ if (verifiedBot?.token === token && verifiedBot.clientId === clientId)
40
+ return true;
41
+ try {
42
+ const response = await fetch("https://discord.com/api/v10/users/@me", {
43
+ headers: { Authorization: `Bot ${token}` },
44
+ redirect: "error",
45
+ signal: AbortSignal.timeout(5e3)
46
+ });
47
+ const user = response.ok && await response.json();
48
+ if (user?.id === clientId && user.bot === true) {
49
+ verifiedBot = { token, clientId };
50
+ return true;
51
+ }
52
+ } catch {
53
+ }
54
+ return false;
55
+ }
56
+ export async function memberAccessFor(userId, guilds) {
57
+ let unavailable = false;
58
+ const deadline = Date.now() + 5e3;
59
+ for (const guild of guilds) {
60
+ const remaining = deadline - Date.now();
61
+ if (remaining <= 0)
62
+ return "unavailable";
63
+ try {
64
+ const response = await fetch(`https://discord.com/api/v10/guilds/${guild}/members/${userId}`, {
65
+ headers: { Authorization: `Bot ${process.env.DISCORD_TOKEN}` },
66
+ cache: "no-store",
67
+ redirect: "error",
68
+ signal: AbortSignal.timeout(remaining)
69
+ });
70
+ if (response.status === 404)
71
+ continue;
72
+ if (response.ok && (await response.json())?.user?.id === userId)
73
+ return "read";
74
+ } catch {
75
+ }
76
+ unavailable = true;
77
+ }
78
+ return unavailable ? "unavailable" : "forbidden";
79
+ }
80
+ export async function authorizeReference(event, policy, document = false) {
81
+ referenceHeaders(event);
82
+ if (policy.access === "public")
83
+ return;
84
+ const { url, clientId } = signInConfig(event, policy);
85
+ const session = getDiscordSession(event, url, "reference");
86
+ let access = "anonymous";
87
+ if (session) {
88
+ if (policy.access === "private") {
89
+ access = await dashboardAccessFor(session.userId, "GET", "/__discord-auth/session");
90
+ } else if (policy.access === "members") {
91
+ access = policy.guilds && !await botIdentityMatches(clientId, process.env.DISCORD_TOKEN) ? "unavailable" : await memberAccessFor(session.userId, policy.guilds ?? session.guilds ?? []);
92
+ } else {
93
+ access = "read";
94
+ }
95
+ }
96
+ if (access === "unavailable")
97
+ throw createError({ statusCode: 503, statusMessage: "Discord access verification is temporarily unavailable." });
98
+ if (access === "anonymous" || access === "forbidden") {
99
+ const status = access === "anonymous" ? 401 : 403;
100
+ if (document) {
101
+ setResponseStatus(event, status);
102
+ return renderReferenceAccessPage(status);
103
+ }
104
+ throw createError({ statusCode: status, statusMessage: access === "anonymous" ? "Sign in to the command reference." : "Forbidden" });
105
+ }
106
+ }
107
+ function returnPath(value, origin, fallback) {
108
+ if (value === void 0)
109
+ return fallback;
110
+ let path = "";
111
+ if (typeof value === "string" && value.length <= 2048 && !/%(?:2f|5c|25)/i.test(value)) {
112
+ try {
113
+ path = decodeURIComponent(value);
114
+ } catch {
115
+ }
116
+ }
117
+ if (!/^\/[\p{L}\p{N}._~/-]*$/u.test(path) || path.includes("//") || path.split("/").some((part) => part === "." || part === ".."))
118
+ throw createError({ statusCode: 400, statusMessage: "Invalid return path." });
119
+ return new URL(path, origin).pathname;
120
+ }
121
+ export function referenceOAuth(event, policy) {
122
+ referenceHeaders(event);
123
+ const path = event.path.split("?")[0];
124
+ if (!referenceRequest(path, getMethod(event), policy) || !authPaths.includes(path))
125
+ throw createError({ statusCode: 404 });
126
+ const { url, clientId } = signInConfig(event, policy);
127
+ let sharedGuilds;
128
+ if (policy.access === "members" && !policy.guilds && !path.endsWith("/logout")) {
129
+ let client;
130
+ try {
131
+ client = useDiscordClient().internalClient;
132
+ } catch {
133
+ }
134
+ if (!client?.isReady() || client.user.id !== clientId)
135
+ throw createError({ statusCode: 503, statusMessage: "The bot is unavailable for shared server verification." });
136
+ const guilds = client.guilds.cache;
137
+ sharedGuilds = (ids) => ids.filter((id) => guilds.has(id));
138
+ }
139
+ return handleDashboardOAuth(event, url, clientId, {
140
+ audience: "reference",
141
+ landing: returnPath(getQuery(event).returnTo, url, policy.page === false ? "/" : "/commands"),
142
+ sharedGuilds
143
+ });
144
+ }
@@ -0,0 +1,2 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<any>>;
2
+ export default _default;
@@ -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,2 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<string>>;
2
+ export default _default;
@@ -0,0 +1,25 @@
1
+ import { dashboardHref, 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 = {
18
+ ...dashboardHref && { "admin-entry": () => h("a", { href: dashboardHref, class: "ref-admin-entry", rel: "noreferrer" }, "Admin sign-in") },
19
+ ...policy.access !== "public" && {
20
+ default: () => h("form", { method: "post", action: "/__discord-reference/logout" }, h("button", { type: "submit" }, "Sign out"))
21
+ }
22
+ };
23
+ const body = await renderToString(h(ReferenceContent, { catalog: await getCatalog(), standalone: true }, slots));
24
+ 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>${body}</body></html>`;
25
+ });
@@ -0,0 +1,2 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<any>>;
2
+ export default _default;
@@ -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
+ });
@@ -0,0 +1,2 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<string | undefined>>;
2
+ export default _default;
@@ -0,0 +1,4 @@
1
+ import { policy } from "discord/reference";
2
+ import { defineEventHandler } from "h3";
3
+ import { referenceOAuth } from "./access.js";
4
+ export default defineEventHandler((event) => referenceOAuth(event, policy));