ludicord 2.2.1 → 2.2.4

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 (166) hide show
  1. package/README.md +8 -6
  2. package/bin/ludicord.js +0 -0
  3. package/dist/api/runtime.d.ts +4 -0
  4. package/dist/api/runtime.js +61 -10
  5. package/dist/auth/client.d.ts +10 -0
  6. package/dist/auth/client.js +58 -8
  7. package/dist/auth/index.d.ts +1 -1
  8. package/dist/auth/index.js +1 -1
  9. package/dist/auth/server.js +154 -34
  10. package/dist/auth/types.d.ts +5 -0
  11. package/dist/cli/index.js +14 -13
  12. package/dist/cli/project-commands.js +49 -34
  13. package/dist/compiler/build.js +37 -128
  14. package/dist/compiler/client-entry.d.ts +4 -0
  15. package/dist/compiler/client-entry.js +35 -0
  16. package/dist/compiler/client-tooling.d.ts +5 -0
  17. package/dist/compiler/client-tooling.js +97 -0
  18. package/dist/compiler/scanner.js +8 -0
  19. package/dist/compiler/server-bundle.d.ts +11 -0
  20. package/dist/compiler/server-bundle.js +31 -0
  21. package/dist/compiler/type-generation.js +11 -2
  22. package/dist/config/defaults.js +28 -2
  23. package/dist/config/environment.d.ts +2 -0
  24. package/dist/config/environment.js +18 -0
  25. package/dist/discord/data.d.ts +21 -0
  26. package/dist/discord/data.js +91 -0
  27. package/dist/discord/events.d.ts +42 -4
  28. package/dist/discord/events.js +120 -41
  29. package/dist/discord/index.d.ts +4 -2
  30. package/dist/discord/index.js +2 -1
  31. package/dist/discord/runtime.d.ts +2 -2
  32. package/dist/discord/runtime.js +9 -13
  33. package/dist/discord/testing.d.ts +1 -0
  34. package/dist/discord/testing.js +10 -0
  35. package/dist/manifests/types.d.ts +4 -0
  36. package/dist/navigation/index.d.ts +2 -0
  37. package/dist/runtime/client/dev-panel.d.ts +2 -0
  38. package/dist/runtime/client/dev-panel.js +63 -0
  39. package/dist/runtime/client/embed-router.d.ts +4 -1
  40. package/dist/runtime/client/embed-router.js +69 -17
  41. package/dist/runtime/client/files.d.ts +23 -0
  42. package/dist/runtime/client/files.js +12 -0
  43. package/dist/runtime/client/minimize-card.js +4 -4
  44. package/dist/runtime/client/minimize.d.ts +1 -0
  45. package/dist/runtime/client/minimize.js +1 -0
  46. package/dist/runtime/client/root.d.ts +7 -0
  47. package/dist/runtime/client/root.js +19 -0
  48. package/dist/runtime/index.d.ts +8 -4
  49. package/dist/runtime/index.js +14 -2
  50. package/dist/runtime/server/dev-server.d.ts +1 -0
  51. package/dist/runtime/server/dev-server.js +294 -319
  52. package/dist/runtime/server/diagnostics.d.ts +17 -0
  53. package/dist/runtime/server/diagnostics.js +87 -0
  54. package/dist/runtime/server/index.d.ts +5 -0
  55. package/dist/runtime/server/index.js +3 -0
  56. package/dist/runtime/server/production-server.js +14 -0
  57. package/dist/security/discord.d.ts +9 -0
  58. package/dist/security/discord.js +37 -7
  59. package/dist/security/secret-scan.d.ts +3 -0
  60. package/dist/security/secret-scan.js +40 -0
  61. package/dist/server/discord-rest.d.ts +45 -0
  62. package/dist/server/discord-rest.js +46 -0
  63. package/dist/server/index.d.ts +2 -0
  64. package/dist/server/index.js +1 -0
  65. package/dist/sessions/cookies.d.ts +4 -1
  66. package/dist/sessions/cookies.js +17 -4
  67. package/dist/sessions/crypto.js +6 -0
  68. package/dist/testing/index.d.ts +13 -0
  69. package/dist/testing/index.js +24 -0
  70. package/dist/version.d.ts +1 -1
  71. package/dist/version.js +1 -1
  72. package/dist/ws/client.d.ts +6 -0
  73. package/dist/ws/client.js +46 -10
  74. package/dist/ws/server.d.ts +4 -0
  75. package/dist/ws/server.js +35 -14
  76. package/package.json +31 -4
  77. package/dist/api/runtime.d.ts.map +0 -1
  78. package/dist/api/runtime.js.map +0 -1
  79. package/dist/auth/client.d.ts.map +0 -1
  80. package/dist/auth/client.js.map +0 -1
  81. package/dist/auth/index.d.ts.map +0 -1
  82. package/dist/auth/index.js.map +0 -1
  83. package/dist/auth/server.d.ts.map +0 -1
  84. package/dist/auth/server.js.map +0 -1
  85. package/dist/auth/types.d.ts.map +0 -1
  86. package/dist/auth/types.js.map +0 -1
  87. package/dist/cli/index.d.ts.map +0 -1
  88. package/dist/cli/index.js.map +0 -1
  89. package/dist/cli/project-commands.d.ts.map +0 -1
  90. package/dist/cli/project-commands.js.map +0 -1
  91. package/dist/compiler/build.d.ts.map +0 -1
  92. package/dist/compiler/build.js.map +0 -1
  93. package/dist/compiler/index.d.ts.map +0 -1
  94. package/dist/compiler/index.js.map +0 -1
  95. package/dist/compiler/scanner.d.ts.map +0 -1
  96. package/dist/compiler/scanner.js.map +0 -1
  97. package/dist/compiler/type-generation.d.ts.map +0 -1
  98. package/dist/compiler/type-generation.js.map +0 -1
  99. package/dist/compiler/write-manifests.d.ts.map +0 -1
  100. package/dist/compiler/write-manifests.js.map +0 -1
  101. package/dist/config/defaults.d.ts.map +0 -1
  102. package/dist/config/defaults.js.map +0 -1
  103. package/dist/config/index.d.ts.map +0 -1
  104. package/dist/config/index.js.map +0 -1
  105. package/dist/config/loader.d.ts.map +0 -1
  106. package/dist/config/loader.js.map +0 -1
  107. package/dist/config/project-root.d.ts.map +0 -1
  108. package/dist/config/project-root.js.map +0 -1
  109. package/dist/config/types.d.ts.map +0 -1
  110. package/dist/config/types.js.map +0 -1
  111. package/dist/discord/events.d.ts.map +0 -1
  112. package/dist/discord/events.js.map +0 -1
  113. package/dist/discord/index.d.ts.map +0 -1
  114. package/dist/discord/index.js.map +0 -1
  115. package/dist/discord/runtime.d.ts.map +0 -1
  116. package/dist/discord/runtime.js.map +0 -1
  117. package/dist/discord/safe-area.d.ts.map +0 -1
  118. package/dist/discord/safe-area.js.map +0 -1
  119. package/dist/discord/testing.d.ts.map +0 -1
  120. package/dist/discord/testing.js.map +0 -1
  121. package/dist/index.d.ts.map +0 -1
  122. package/dist/index.js.map +0 -1
  123. package/dist/manifests/types.d.ts.map +0 -1
  124. package/dist/manifests/types.js.map +0 -1
  125. package/dist/navigation/index.d.ts.map +0 -1
  126. package/dist/navigation/index.js.map +0 -1
  127. package/dist/router/match.d.ts.map +0 -1
  128. package/dist/router/match.js.map +0 -1
  129. package/dist/runtime/client/embed-router.d.ts.map +0 -1
  130. package/dist/runtime/client/embed-router.js.map +0 -1
  131. package/dist/runtime/client/minimize-card.d.ts.map +0 -1
  132. package/dist/runtime/client/minimize-card.js.map +0 -1
  133. package/dist/runtime/client/minimize.d.ts.map +0 -1
  134. package/dist/runtime/client/minimize.js.map +0 -1
  135. package/dist/runtime/index.d.ts.map +0 -1
  136. package/dist/runtime/index.js.map +0 -1
  137. package/dist/runtime/server/dev-server.d.ts.map +0 -1
  138. package/dist/runtime/server/dev-server.js.map +0 -1
  139. package/dist/runtime/server/production-server.d.ts.map +0 -1
  140. package/dist/runtime/server/production-server.js.map +0 -1
  141. package/dist/security/discord.d.ts.map +0 -1
  142. package/dist/security/discord.js.map +0 -1
  143. package/dist/security/index.d.ts.map +0 -1
  144. package/dist/security/index.js.map +0 -1
  145. package/dist/server/index.d.ts.map +0 -1
  146. package/dist/server/index.js.map +0 -1
  147. package/dist/server/session.d.ts.map +0 -1
  148. package/dist/server/session.js.map +0 -1
  149. package/dist/server/types.d.ts.map +0 -1
  150. package/dist/server/types.js.map +0 -1
  151. package/dist/sessions/cookies.d.ts.map +0 -1
  152. package/dist/sessions/cookies.js.map +0 -1
  153. package/dist/sessions/crypto.d.ts.map +0 -1
  154. package/dist/sessions/crypto.js.map +0 -1
  155. package/dist/shared/errors.d.ts.map +0 -1
  156. package/dist/shared/errors.js.map +0 -1
  157. package/dist/testing/index.d.ts.map +0 -1
  158. package/dist/testing/index.js.map +0 -1
  159. package/dist/version.d.ts.map +0 -1
  160. package/dist/version.js.map +0 -1
  161. package/dist/ws/client.d.ts.map +0 -1
  162. package/dist/ws/client.js.map +0 -1
  163. package/dist/ws/index.d.ts.map +0 -1
  164. package/dist/ws/index.js.map +0 -1
  165. package/dist/ws/server.d.ts.map +0 -1
  166. package/dist/ws/server.js.map +0 -1
package/README.md CHANGED
@@ -6,12 +6,14 @@ The full-stack React framework and CLI for Discord Activities.
6
6
  ludicord dev
7
7
  ludicord build
8
8
  ludicord start
9
- ludicord routes
10
- ludicord doctor
11
- ludicord info
12
- ludicord clean
13
9
  ```
14
10
 
15
- Public entry points include `ludicord`, `ludicord/config`, `ludicord/navigation`, `ludicord/discord`, `ludicord/auth`, `ludicord/server`, `ludicord/security`, `ludicord/ws/client`, and `ludicord/ws/server`.
11
+ Public entry points include `ludicord`, `ludicord/config`, `ludicord/navigation`, `ludicord/discord`, `ludicord/auth`, `ludicord/server`, `ludicord/security`, `ludicord/ws/client`, `ludicord/ws/server`, `ludicord/runtime` (client status), `ludicord/runtime/server` (server tooling), and `ludicord/testing`.
16
12
 
17
- See the repository [documentation](../../docs/README.md) for routing, Discord authentication, APIs, WebSockets, production deployment, and security.
13
+ See the public [documentation](https://github.com/mrcholer/ludicord/blob/main/docs/README.md), [release history](https://github.com/mrcholer/ludicord/blob/main/CHANGELOG.md), and [issue tracker](https://github.com/mrcholer/ludicord/issues). The public repository contains documentation and release information, not the framework implementation.
14
+
15
+ Automatic files: `app/layout.tsx`, `loading.tsx`, `error.tsx`, `minimize.tsx`, and `app/auth/{loading,error,denied}.tsx`. Default-export the component and the framework connects it. Embeds use `export default function embed()`.
16
+
17
+ Development includes API/WS hot updates, TypeScript diagnostics, a Ludicord browser error panel with mapped source locations, and branded compile timing. Production uses safe errors without source disclosure.
18
+
19
+ Discord helpers include detailed channel/guild hooks, Activity participants, voice/layout events, typed SDK commands, and permission-gated paginated guild members. Full member lists require a server-only bot token and the GUILD_MEMBERS intent.
package/bin/ludicord.js CHANGED
File without changes
@@ -21,7 +21,11 @@ export interface ApiRuntimeOptions {
21
21
  readonly proxyVerification?: boolean;
22
22
  readonly discordPublicKey?: string;
23
23
  readonly now?: () => number;
24
+ readonly bodyLimit?: string | number;
25
+ readonly allowDevelopmentSessions?: boolean;
26
+ readonly onError?: (error: unknown, file: string) => void;
24
27
  }
28
+ export declare function parseBodyLimit(limit?: string | number): number;
25
29
  export declare function createApiMiddleware(options: ApiRuntimeOptions): (request: ExpressRequest, response: ExpressResponse, next: NextFunction) => Promise<void>;
26
30
  export {};
27
31
  //# sourceMappingURL=runtime.d.ts.map
@@ -1,4 +1,6 @@
1
1
  import path from "node:path";
2
+ import { Readable } from "node:stream";
3
+ import { pipeline } from "node:stream/promises";
2
4
  import { pathToFileURL } from "node:url";
3
5
  import { matchRoutePattern, routeSpecificity } from "../router/match.js";
4
6
  import { parseSessionCookie } from "../sessions/cookies.js";
@@ -12,16 +14,42 @@ const HTTP_METHODS = [
12
14
  "HEAD",
13
15
  "OPTIONS",
14
16
  ];
15
- async function requestBody(request) {
17
+ export function parseBodyLimit(limit = "2mb") {
18
+ if (typeof limit === "number" && Number.isSafeInteger(limit) && limit > 0)
19
+ return limit;
20
+ const match = /^(\d+(?:\.\d+)?)\s*(b|kb|mb)?$/i.exec(String(limit));
21
+ if (match === null)
22
+ throw new Error("LUDICORD8002: Invalid server.limits.body.");
23
+ const multiplier = match[2]?.toLowerCase() === "mb" ? 1_048_576 : match[2]?.toLowerCase() === "kb" ? 1024 : 1;
24
+ const bytes = Number(match[1]) * multiplier;
25
+ if (!Number.isSafeInteger(bytes) || bytes <= 0)
26
+ throw new Error("LUDICORD8002: Invalid server.limits.body.");
27
+ return bytes;
28
+ }
29
+ class BodyLimitError extends Error {
30
+ }
31
+ class MalformedBodyError extends Error {
32
+ }
33
+ async function requestBody(request, limit) {
16
34
  if (request.method === "GET" || request.method === "HEAD")
17
35
  return undefined;
36
+ const length = Number(request.headers["content-length"]);
37
+ if (Number.isFinite(length) && length > limit)
38
+ throw new BodyLimitError();
18
39
  const chunks = [];
19
- for await (const chunk of request) {
20
- chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
40
+ let size = 0;
41
+ for await (const chunk of request.iterator({ destroyOnReturn: false })) {
42
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
43
+ size += buffer.length;
44
+ if (size > limit) {
45
+ request.resume();
46
+ throw new BodyLimitError();
47
+ }
48
+ chunks.push(buffer);
21
49
  }
22
50
  return Buffer.concat(chunks);
23
51
  }
24
- function webRequest(request, params, sessionSecret, body, proxyVerified) {
52
+ function webRequest(request, params, sessionSecret, body, proxyVerified, allowDevelopment) {
25
53
  const origin = `${request.protocol}://${request.get("host") ?? "localhost"}`;
26
54
  const headerEntries = [];
27
55
  for (const [name, value] of Object.entries(request.headers)) {
@@ -37,9 +65,20 @@ function webRequest(request, params, sessionSecret, body, proxyVerified) {
37
65
  headers: new Headers(headerEntries),
38
66
  ...(body === undefined ? {} : { body: body }),
39
67
  });
68
+ const parseJson = web.json.bind(web);
69
+ Object.defineProperty(web, "json", { value: async () => {
70
+ try {
71
+ return await parseJson();
72
+ }
73
+ catch (error) {
74
+ if (error instanceof SyntaxError)
75
+ throw new MalformedBodyError();
76
+ throw error;
77
+ }
78
+ } });
40
79
  const session = sessionSecret === undefined
41
80
  ? null
42
- : parseSessionCookie(request.headers.cookie, sessionSecret);
81
+ : parseSessionCookie(request.headers.cookie, sessionSecret, { allowDevelopment });
43
82
  Object.defineProperties(web, {
44
83
  ludicord: { value: session, enumerable: true },
45
84
  params: { value: params, enumerable: true },
@@ -56,13 +95,19 @@ function webRequest(request, params, sessionSecret, body, proxyVerified) {
56
95
  async function sendWebResponse(response, webResponse, head) {
57
96
  response.status(webResponse.status);
58
97
  webResponse.headers.forEach((value, name) => {
98
+ if (name.toLowerCase() === "set-cookie")
99
+ return;
59
100
  response.setHeader(name, value);
60
101
  });
102
+ const cookies = webResponse.headers.getSetCookie();
103
+ if (cookies.length > 0)
104
+ response.setHeader("Set-Cookie", cookies);
61
105
  if (head || webResponse.body === null) {
106
+ await webResponse.body?.cancel();
62
107
  response.end();
63
108
  return;
64
109
  }
65
- response.send(Buffer.from(await webResponse.arrayBuffer()));
110
+ await pipeline(Readable.fromWeb(webResponse.body), response);
66
111
  }
67
112
  function allowedMethods(module) {
68
113
  const methods = HTTP_METHODS.filter((method) => typeof module[method] === "function");
@@ -77,6 +122,7 @@ async function defaultModuleLoader(absoluteFile) {
77
122
  }
78
123
  export function createApiMiddleware(options) {
79
124
  const loadModule = options.loadModule ?? defaultModuleLoader;
125
+ const bodyLimit = parseBodyLimit(options.bodyLimit);
80
126
  return async (request, response, next) => {
81
127
  const pathname = new URL(request.originalUrl, `${request.protocol}://${request.get("host") ?? "localhost"}`).pathname;
82
128
  if (!pathname.startsWith("/api/") && pathname !== "/api") {
@@ -99,7 +145,7 @@ export function createApiMiddleware(options) {
99
145
  }
100
146
  try {
101
147
  const module = await loadModule(path.join(options.projectRoot, selected.route.file));
102
- const body = await requestBody(request);
148
+ const body = await requestBody(request, bodyLimit);
103
149
  let proxyVerified = false;
104
150
  if (options.proxyVerification === true) {
105
151
  const publicKey = options.discordPublicKey ?? process.env.LUDICORD_DISCORD_PUBLIC_KEY;
@@ -137,7 +183,7 @@ export function createApiMiddleware(options) {
137
183
  response.status(405).json({ error: "LUDICORD_METHOD_NOT_ALLOWED" });
138
184
  return;
139
185
  }
140
- const ludicordRequest = webRequest(request, selected.match.params, options.sessionSecret, body, proxyVerified);
186
+ const ludicordRequest = webRequest(request, selected.match.params, options.sessionSecret, body, proxyVerified, options.allowDevelopmentSessions === true);
141
187
  if (module.public !== true &&
142
188
  module.auth !== false &&
143
189
  ludicordRequest.ludicord === null) {
@@ -153,11 +199,16 @@ export function createApiMiddleware(options) {
153
199
  await sendWebResponse(response, result, method === "HEAD");
154
200
  }
155
201
  catch (error) {
156
- if (error instanceof SyntaxError ||
157
- (error instanceof TypeError && /JSON/.test(error.message))) {
202
+ if (error instanceof BodyLimitError) {
203
+ request.resume();
204
+ response.status(413).json({ error: "LUDICORD_BODY_TOO_LARGE" });
205
+ return;
206
+ }
207
+ if (error instanceof MalformedBodyError) {
158
208
  response.status(400).json({ error: "LUDICORD_MALFORMED_BODY" });
159
209
  return;
160
210
  }
211
+ options.onError?.(error, selected.route.file);
161
212
  next(error);
162
213
  }
163
214
  };
@@ -11,5 +11,15 @@ export declare function useLudicordSession(): LudicordSession | null;
11
11
  export declare function useAuthStatus(): LudicordAuthStatus;
12
12
  export declare function useAuthError(): Error | null;
13
13
  export declare function getLudicordAuthSnapshot(): LudicordAuthSnapshot;
14
+ export declare function logoutLudicord(): Promise<void>;
15
+ export declare function useLudicordAuth(): {
16
+ user: import("./types.js").LudicordSessionUser | null;
17
+ login: typeof authenticateLudicord;
18
+ logout: typeof logoutLudicord;
19
+ status: LudicordAuthStatus;
20
+ session: LudicordSession | null;
21
+ error: Error | null;
22
+ };
23
+ export declare function setMockSessionForTesting(session: LudicordSession | null): void;
14
24
  export declare function resetLudicordAuthForTesting(): void;
15
25
  //# sourceMappingURL=client.d.ts.map
@@ -1,6 +1,6 @@
1
- import { useSyncExternalStore } from "react";
1
+ import { useMemo, useSyncExternalStore } from "react";
2
2
  import { getDiscordSnapshot, } from "../discord/runtime.js";
3
- import { setDiscordUserFromAuth, setDiscordGuildFromAuth } from "../discord/events.js";
3
+ import { setDiscordUserFromAuth, setDiscordGuildFromAuth, initializeDiscordEventsFromEnvironment, enrichDiscordContext, addDiscordDiagnostic } from "../discord/events.js";
4
4
  class LudicordAuthStore {
5
5
  snapshot = {
6
6
  status: "idle",
@@ -9,12 +9,21 @@ class LudicordAuthStore {
9
9
  };
10
10
  listeners = new Set();
11
11
  authentication = null;
12
+ expiryTimer;
12
13
  subscribe = (listener) => {
13
14
  this.listeners.add(listener);
14
15
  return () => this.listeners.delete(listener);
15
16
  };
16
17
  getSnapshot = () => this.snapshot;
17
18
  update(status, session, error) {
19
+ clearTimeout(this.expiryTimer);
20
+ if (session !== null) {
21
+ this.expiryTimer = setTimeout(() => {
22
+ setDiscordUserFromAuth(null);
23
+ this.update("idle", null, new Error("LUDICORD6011: Session expired. Sign in again."));
24
+ }, Math.max(0, Math.min(session.expiresAt - Date.now(), 2_147_483_647)));
25
+ this.expiryTimer.unref?.();
26
+ }
18
27
  this.snapshot = { status, session, error };
19
28
  for (const listener of this.listeners)
20
29
  listener();
@@ -22,9 +31,12 @@ class LudicordAuthStore {
22
31
  run(options) {
23
32
  if (this.authentication !== null)
24
33
  return this.authentication;
25
- this.authentication = performAuthentication(options);
34
+ if (this.snapshot.session !== null && this.snapshot.session.expiresAt > Date.now())
35
+ return Promise.resolve(this.snapshot.session);
36
+ this.authentication = performAuthentication(options).finally(() => { this.authentication = null; });
26
37
  return this.authentication;
27
38
  }
39
+ dispose() { clearTimeout(this.expiryTimer); }
28
40
  }
29
41
  let authStore = new LudicordAuthStore();
30
42
  function authCommands(sdk) {
@@ -76,7 +88,7 @@ async function performAuthentication(options) {
76
88
  client_id: clientId,
77
89
  response_type: "code",
78
90
  state: stateBody.state,
79
- scope: options.scopes ?? ["identify"],
91
+ scope: options.scopes ?? globalThis.__LUDICORD_PUBLIC_CONFIG__?.scopes ?? ["identify"],
80
92
  prompt: "none",
81
93
  });
82
94
  }
@@ -104,22 +116,44 @@ async function performAuthentication(options) {
104
116
  const exchange = (await jsonOrError(exchangeResponse));
105
117
  if (typeof exchange.access_token !== "string" ||
106
118
  typeof exchange.session !== "object" ||
107
- exchange.session === null) {
119
+ exchange.session === null || typeof exchange.completionToken !== "string") {
108
120
  throw new Error("LUDICORD6004: Invalid authentication exchange response.");
109
121
  }
110
- await commands.authenticate({ access_token: exchange.access_token });
111
- const session = exchange.session;
122
+ const authenticated = await commands.authenticate({ access_token: exchange.access_token });
123
+ const expected = exchange.session;
124
+ if (authenticated?.user?.id !== expected.user.id) {
125
+ throw new Error("LUDICORD6004: Discord identity did not match the verified session.");
126
+ }
127
+ const confirmation = await fetchImplementation("/_ludicord/auth/complete", {
128
+ method: "POST", credentials: "include", headers: { "content-type": "application/json" },
129
+ body: JSON.stringify({ completionToken: exchange.completionToken }),
130
+ });
131
+ const session = await jsonOrError(confirmation);
132
+ if (session.authenticated !== true || session.user?.id !== expected.user.id)
133
+ throw new Error("LUDICORD6004: Invalid confirmed session.");
112
134
  setDiscordUserFromAuth({
113
135
  ...session.user,
114
136
  avatar: session.user.avatar === null || session.user.avatar.startsWith("http")
115
137
  ? session.user.avatar
116
138
  : `https://cdn.discordapp.com/avatars/${session.user.id}/${session.user.avatar}.png`,
117
139
  });
118
- setDiscordGuildFromAuth(session.guildId, session.guildName);
140
+ setDiscordGuildFromAuth(session.guildId, session.guildName, session.guildIcon);
119
141
  authStore.update("authenticated", session, null);
142
+ void initializeDiscordEventsFromEnvironment(discord, session.scopes).catch(() => addDiscordDiagnostic("Some Discord capabilities are unavailable."));
143
+ if (globalThis.__LUDICORD_PUBLIC_CONFIG__?.discordServerData) {
144
+ void fetchImplementation("/_ludicord/auth/context", { credentials: "include", signal: AbortSignal.timeout(10000) })
145
+ .then(async (response) => { if (!response.ok) {
146
+ addDiscordDiagnostic("Extended guild/channel data requires verified Activity membership and bot access.");
147
+ return;
148
+ } const context = await response.json(); if (authStore.getSnapshot().session === session)
149
+ enrichDiscordContext(context); })
150
+ .catch(() => addDiscordDiagnostic("Extended Discord context is temporarily unavailable."));
151
+ }
120
152
  return session;
121
153
  }
122
154
  catch (cause) {
155
+ // Pending cookies cannot authorize APIs, and are cleared if SDK authentication fails.
156
+ await fetchImplementation("/_ludicord/auth/logout", { method: "POST", credentials: "include" }).catch(() => undefined);
123
157
  if (authStore.getSnapshot().status === "denied")
124
158
  throw cause;
125
159
  const error = cause instanceof Error
@@ -176,7 +210,23 @@ export function useAuthError() {
176
210
  export function getLudicordAuthSnapshot() {
177
211
  return authStore.getSnapshot();
178
212
  }
213
+ export async function logoutLudicord() {
214
+ const response = await fetch("/_ludicord/auth/logout", { method: "POST", credentials: "include" });
215
+ if (!response.ok)
216
+ throw new Error("LUDICORD6012: Could not sign out. Please retry.");
217
+ setDiscordUserFromAuth(null);
218
+ authStore.update("idle", null, null);
219
+ }
220
+ export function useLudicordAuth() {
221
+ const snapshot = useSyncExternalStore(authStore.subscribe, authStore.getSnapshot, authStore.getSnapshot);
222
+ return useMemo(() => ({ ...snapshot, user: snapshot.session?.user ?? null, login: authenticateLudicord, logout: logoutLudicord }), [snapshot]);
223
+ }
224
+ export function setMockSessionForTesting(session) {
225
+ authStore.update(session === null ? "idle" : "authenticated", session, null);
226
+ setDiscordUserFromAuth(session?.user ?? null);
227
+ }
179
228
  export function resetLudicordAuthForTesting() {
229
+ authStore.dispose();
180
230
  authStore = new LudicordAuthStore();
181
231
  }
182
232
  //# sourceMappingURL=client.js.map
@@ -1,3 +1,3 @@
1
- export { authenticateLudicord, initializeLudicordAuthFromEnvironment, useAuthError, useAuthStatus, useLudicordSession, } from "./client.js";
1
+ export { authenticateLudicord, initializeLudicordAuthFromEnvironment, useAuthError, useAuthStatus, useLudicordSession, useLudicordAuth, logoutLudicord, } from "./client.js";
2
2
  export type { LudicordAuthSnapshot, LudicordAuthStatus, LudicordSession, LudicordSessionUser, } from "./types.js";
3
3
  //# sourceMappingURL=index.d.ts.map
@@ -1,2 +1,2 @@
1
- export { authenticateLudicord, initializeLudicordAuthFromEnvironment, useAuthError, useAuthStatus, useLudicordSession, } from "./client.js";
1
+ export { authenticateLudicord, initializeLudicordAuthFromEnvironment, useAuthError, useAuthStatus, useLudicordSession, useLudicordAuth, logoutLudicord, } from "./client.js";
2
2
  //# sourceMappingURL=index.js.map
@@ -1,8 +1,9 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
  import express from "express";
3
- import { OAUTH_STATE_COOKIE, SESSION_COOKIE, clearCookie, parseCookies, parseSessionCookie, serializeSessionCookie, serializeStateCookie, } from "../sessions/cookies.js";
4
- import { safeEqual, sealLudicordSession } from "../sessions/crypto.js";
3
+ import { OAUTH_STATE_COOKIE, PENDING_SESSION_COOKIE, SESSION_COOKIE, clearCookie, parseCookies, parseSessionCookie, serializeSessionCookie, serializeStateCookie, } from "../sessions/cookies.js";
4
+ import { safeEqual, sealLudicordSession, unsealLudicordSession } from "../sessions/crypto.js";
5
5
  import { verifyDiscordActivityInstance } from "../security/discord.js";
6
+ import { createDiscordRest, LudicordDiscordRestError } from "../server/discord-rest.js";
6
7
  function optionalString(value) {
7
8
  return typeof value === "string" && value !== "" ? value : undefined;
8
9
  }
@@ -37,15 +38,30 @@ export function createLudicordAuthRouter(options = {}) {
37
38
  const now = options.now ?? Date.now;
38
39
  const verifyActivityInstance = options.activityInstanceVerification ?? false;
39
40
  const botToken = options.botToken ?? process.env.LUDICORD_DISCORD_BOT_TOKEN;
41
+ const rest = createDiscordRest({ ...(botToken === undefined ? {} : { botToken }), fetch: fetchImplementation });
42
+ const states = new Map();
43
+ const completions = new Map();
44
+ const remember = (entries, token, ttl) => {
45
+ for (const [key, expiry] of entries)
46
+ if (expiry <= now())
47
+ entries.delete(key);
48
+ if (entries.size >= 1000)
49
+ entries.delete(entries.keys().next().value);
50
+ entries.set(token, now() + ttl);
51
+ };
40
52
  router.use(express.json({ limit: "64kb" }));
41
- router.get("/dev-login", (_request, response) => {
42
- if (production || process.env.LUDICORD_DEV_FAKE_AUTH !== "true" || sessionSecret === undefined || clientId === undefined) {
53
+ router.get("/dev-login", (request, response) => {
54
+ const address = request.socket.remoteAddress;
55
+ const loopback = address === "127.0.0.1" || address === "::1" || address === "::ffff:127.0.0.1";
56
+ if (production || !loopback || request.headers["x-forwarded-for"] !== undefined ||
57
+ process.env.LUDICORD_DEV_FAKE_AUTH !== "true" || sessionSecret === undefined || clientId === undefined) {
43
58
  response.status(404).json({ authenticated: false });
44
59
  return;
45
60
  }
46
61
  const now = Date.now();
47
62
  const session = {
48
63
  authenticated: true,
64
+ kind: "development",
49
65
  user: {
50
66
  id: "local-development-user",
51
67
  username: "local_player",
@@ -67,6 +83,7 @@ export function createLudicordAuthRouter(options = {}) {
67
83
  return;
68
84
  }
69
85
  const state = randomBytes(32).toString("base64url");
86
+ remember(states, state, 300_000);
70
87
  response.setHeader("Set-Cookie", serializeStateCookie(state, { production: production || secureRequest(request) }));
71
88
  response.json({ state });
72
89
  });
@@ -75,20 +92,21 @@ export function createLudicordAuthRouter(options = {}) {
75
92
  unavailable(response);
76
93
  return;
77
94
  }
78
- const body = request.body;
95
+ const body = (request.body ?? {});
79
96
  const code = optionalString(body.code);
80
97
  const state = optionalString(body.state);
81
98
  const stateCookie = parseCookies(request.headers.cookie)[OAUTH_STATE_COOKIE];
82
99
  if (code === undefined ||
83
100
  state === undefined ||
84
101
  stateCookie === undefined ||
85
- !safeEqual(state, stateCookie)) {
102
+ !safeEqual(state, stateCookie) || (states.get(state) ?? 0) <= now()) {
86
103
  response.status(400).json({
87
104
  error: "LUDICORD6003",
88
105
  message: "Invalid OAuth code or state.",
89
106
  });
90
107
  return;
91
108
  }
109
+ states.delete(state);
92
110
  try {
93
111
  const tokenResponse = await fetchImplementation("https://discord.com/api/oauth2/token", {
94
112
  method: "POST",
@@ -101,6 +119,7 @@ export function createLudicordAuthRouter(options = {}) {
101
119
  grant_type: "authorization_code",
102
120
  code,
103
121
  }),
122
+ signal: AbortSignal.timeout(10_000),
104
123
  });
105
124
  if (!tokenResponse.ok) {
106
125
  response.status(502).json({
@@ -121,6 +140,7 @@ export function createLudicordAuthRouter(options = {}) {
121
140
  headers: {
122
141
  authorization: `Bearer ${token.access_token}`,
123
142
  },
143
+ signal: AbortSignal.timeout(10_000),
124
144
  });
125
145
  if (!userResponse.ok) {
126
146
  response.status(502).json({
@@ -137,30 +157,12 @@ export function createLudicordAuthRouter(options = {}) {
137
157
  });
138
158
  return;
139
159
  }
140
- const guildId = optionalString(body.context?.guildId);
141
- const channelId = optionalString(body.context?.channelId);
160
+ let guildId = optionalString(body.context?.guildId);
161
+ let channelId = optionalString(body.context?.channelId);
142
162
  const instanceId = optionalString(body.context?.instanceId);
143
163
  let activityInstanceVerified = false;
144
164
  let guildName;
145
- if (guildId !== undefined && typeof token.scope === "string" && token.scope.includes("guilds")) {
146
- try {
147
- const guildsResponse = await fetchImplementation("https://discord.com/api/users/@me/guilds", {
148
- headers: { authorization: `Bearer ${token.access_token}` },
149
- });
150
- if (guildsResponse.ok) {
151
- const userGuilds = (await guildsResponse.json());
152
- if (Array.isArray(userGuilds)) {
153
- const currentGuild = userGuilds.find((g) => g.id === guildId);
154
- if (typeof currentGuild?.name === "string") {
155
- guildName = currentGuild.name;
156
- }
157
- }
158
- }
159
- }
160
- catch {
161
- // Optional guild details fetch fallback
162
- }
163
- }
165
+ let guildIcon;
164
166
  if (verifyActivityInstance) {
165
167
  if (botToken === undefined || botToken === "") {
166
168
  unavailable(response);
@@ -177,6 +179,7 @@ export function createLudicordAuthRouter(options = {}) {
177
179
  applicationId: clientId,
178
180
  instanceId,
179
181
  botToken,
182
+ userId: user.id,
180
183
  fetch: fetchImplementation,
181
184
  now: now(),
182
185
  ...(options.activityInstanceCacheTtlMs === undefined
@@ -195,15 +198,50 @@ export function createLudicordAuthRouter(options = {}) {
195
198
  return;
196
199
  }
197
200
  activityInstanceVerified = true;
201
+ guildId = verification.instance.guildId;
202
+ channelId = verification.instance.channelId;
203
+ }
204
+ if (guildId !== undefined && token.scope?.split(/\s+/).includes("guilds")) {
205
+ try {
206
+ // Guild lists are paginated; stop as soon as the current guild is found.
207
+ let after = "";
208
+ for (let page = 0; page < 10; page += 1) {
209
+ const guildsResponse = await fetchImplementation(`https://discord.com/api/users/@me/guilds?limit=200${after === "" ? "" : `&after=${encodeURIComponent(after)}`}`, {
210
+ headers: { authorization: `Bearer ${token.access_token}` },
211
+ signal: AbortSignal.timeout(10_000),
212
+ });
213
+ if (!guildsResponse.ok)
214
+ break;
215
+ const userGuilds = await guildsResponse.json();
216
+ if (!Array.isArray(userGuilds))
217
+ break;
218
+ const guild = userGuilds.find((item) => item.id === guildId);
219
+ if (guild !== undefined) {
220
+ guildName = guild.name;
221
+ guildIcon = typeof guild.icon === "string" ? `https://cdn.discordapp.com/icons/${guildId}/${guild.icon}.png` : null;
222
+ break;
223
+ }
224
+ if (userGuilds.length < 200)
225
+ break;
226
+ after = userGuilds.at(-1)?.id ?? "";
227
+ if (after === "")
228
+ break;
229
+ }
230
+ }
231
+ catch {
232
+ // Optional presentation metadata must not prevent login.
233
+ }
198
234
  }
199
235
  const issuedAt = now();
200
- const expiresInSeconds = typeof token.expires_in === "number" ? token.expires_in : 604_800;
236
+ const expiresInSeconds = typeof token.expires_in === "number" && Number.isFinite(token.expires_in)
237
+ ? Math.max(1, Math.min(Math.floor(token.expires_in), 604_800)) : 604_800;
201
238
  const session = {
202
239
  authenticated: true,
203
240
  user: safeUser(user),
204
241
  applicationId: clientId,
205
242
  ...(guildId === undefined ? {} : { guildId }),
206
243
  ...(guildName === undefined ? {} : { guildName }),
244
+ ...(guildIcon === undefined ? {} : { guildIcon }),
207
245
  ...(channelId === undefined ? {} : { channelId }),
208
246
  ...(instanceId === undefined ? {} : { instanceId }),
209
247
  ...(activityInstanceVerified ? { activityInstanceVerified: true } : {}),
@@ -213,15 +251,19 @@ export function createLudicordAuthRouter(options = {}) {
213
251
  issuedAt,
214
252
  expiresAt: issuedAt + expiresInSeconds * 1_000,
215
253
  };
216
- const sealed = sealLudicordSession(session, sessionSecret);
254
+ const completionToken = randomBytes(32).toString("base64url");
255
+ remember(completions, completionToken, 120_000);
256
+ const sealed = sealLudicordSession({ ...session, kind: "pending", completionToken, sessionExpiresAt: session.expiresAt, expiresAt: issuedAt + 120_000 }, sessionSecret);
217
257
  response.append("Set-Cookie", serializeSessionCookie(sealed, {
218
258
  production: production || secureRequest(request),
219
- maxAgeSeconds: expiresInSeconds,
220
- }));
259
+ maxAgeSeconds: 120,
260
+ }).replace(`${SESSION_COOKIE}=`, `${PENDING_SESSION_COOKIE}=`));
221
261
  response.append("Set-Cookie", clearCookie(OAUTH_STATE_COOKIE, production || secureRequest(request)));
222
262
  response.json({
223
263
  access_token: token.access_token,
224
264
  session,
265
+ completionToken,
266
+ expiresInSeconds,
225
267
  });
226
268
  }
227
269
  catch {
@@ -231,22 +273,100 @@ export function createLudicordAuthRouter(options = {}) {
231
273
  });
232
274
  }
233
275
  });
276
+ router.post("/complete", (request, response) => {
277
+ const value = parseCookies(request.headers.cookie)[PENDING_SESSION_COOKIE];
278
+ const token = optionalString(request.body?.completionToken);
279
+ const pending = value === undefined || sessionSecret === undefined ? null : unsealLudicordSession(value, sessionSecret);
280
+ if (pending?.kind !== "pending" || token === undefined || pending.completionToken === undefined ||
281
+ !safeEqual(token, pending.completionToken) || (completions.get(token) ?? 0) <= now()) {
282
+ response.status(401).json({ error: "LUDICORD6009", message: "Login confirmation expired. Please retry." });
283
+ return;
284
+ }
285
+ completions.delete(token);
286
+ const { kind: _kind, completionToken: _token, sessionExpiresAt, ...identity } = pending;
287
+ const expiresAt = Math.min(now() + 3_600_000, sessionExpiresAt ?? pending.expiresAt);
288
+ const session = { ...identity, expiresAt };
289
+ response.append("Set-Cookie", serializeSessionCookie(sealLudicordSession(session, sessionSecret), {
290
+ production: production || secureRequest(request), maxAgeSeconds: Math.max(0, Math.floor((expiresAt - now()) / 1000)),
291
+ }));
292
+ response.append("Set-Cookie", clearCookie(PENDING_SESSION_COOKIE, production || secureRequest(request)));
293
+ response.json(session);
294
+ });
234
295
  router.get("/session", (request, response) => {
235
296
  if (sessionSecret === undefined) {
236
297
  unavailable(response);
237
298
  return;
238
299
  }
239
- const session = parseSessionCookie(request.headers.cookie, sessionSecret);
300
+ const session = parseSessionCookie(request.headers.cookie, sessionSecret, { allowDevelopment: !production });
240
301
  if (session === null) {
241
302
  response.status(401).json({ authenticated: false });
242
303
  return;
243
304
  }
244
305
  response.json(session);
245
306
  });
246
- router.post("/logout", (_request, response) => {
247
- response.setHeader("Set-Cookie", clearCookie(SESSION_COOKIE, production));
307
+ router.post("/logout", (request, response) => {
308
+ response.setHeader("Set-Cookie", [SESSION_COOKIE, PENDING_SESSION_COOKIE, OAUTH_STATE_COOKIE].map((name) => clearCookie(name, production || secureRequest(request))));
248
309
  response.status(204).end();
249
310
  });
311
+ router.get("/context", async (request, response) => {
312
+ const session = sessionSecret === undefined ? null : parseSessionCookie(request.headers.cookie, sessionSecret);
313
+ if (!session) {
314
+ response.status(401).json({ message: "Discord login is required." });
315
+ return;
316
+ }
317
+ if (!botToken || !session.instanceId) {
318
+ response.status(501).json({ message: "Extended Discord context requires a bot token and verified Activity membership." });
319
+ return;
320
+ }
321
+ try {
322
+ const verification = await verifyDiscordActivityInstance({ applicationId: session.applicationId, instanceId: session.instanceId, userId: session.user.id, botToken, fetch: fetchImplementation });
323
+ if (!verification.verified) {
324
+ response.status(403).json({ message: "Activity membership could not be verified." });
325
+ return;
326
+ }
327
+ const { guildId, channelId } = verification.instance;
328
+ const [guild, channel] = await Promise.all([guildId ? rest.getGuild(guildId) : undefined, channelId ? rest.getChannel(channelId) : undefined]);
329
+ response.json({ guild, channel });
330
+ }
331
+ catch (error) {
332
+ response.status(error instanceof LudicordDiscordRestError ? error.status : 502).json({ message: "Discord context is unavailable. Check the bot's access to this guild and channel." });
333
+ }
334
+ });
335
+ router.get("/guild-members", async (request, response) => {
336
+ const session = sessionSecret === undefined ? null : parseSessionCookie(request.headers.cookie, sessionSecret);
337
+ if (session === null) {
338
+ response.status(401).json({ message: "Discord login is required." });
339
+ return;
340
+ }
341
+ if (!botToken) {
342
+ response.status(501).json({ message: "Full guild member lists require a server-only bot token and the GUILD_MEMBERS privileged intent. useParticipants() provides Activity members without this permission." });
343
+ return;
344
+ }
345
+ if (!session.instanceId) {
346
+ response.status(403).json({ message: "A verified Activity instance is required to read guild members." });
347
+ return;
348
+ }
349
+ try {
350
+ const verified = await verifyDiscordActivityInstance({ applicationId: session.applicationId, instanceId: session.instanceId, userId: session.user.id, botToken, fetch: fetchImplementation });
351
+ if (!verified.verified || !verified.instance.guildId) {
352
+ response.status(!verified.verified && verified.reason === "rate-limited" ? 429 : 403).json({ message: "The current user could not be verified in this guild Activity." });
353
+ return;
354
+ }
355
+ const limit = request.query.limit === undefined ? 100 : Number(request.query.limit);
356
+ const after = typeof request.query.after === "string" ? request.query.after : undefined;
357
+ const members = await rest.listGuildMembers(verified.instance.guildId, { limit, ...(after === undefined ? {} : { after }) });
358
+ response.json({ members, next: members.length === Math.min(1000, Math.max(1, Math.floor(limit))) ? members.at(-1)?.user.id ?? null : null });
359
+ }
360
+ catch (error) {
361
+ if (error instanceof LudicordDiscordRestError) {
362
+ if (error.retryAfterMs !== undefined)
363
+ response.setHeader("Retry-After", String(Math.ceil(error.retryAfterMs / 1000)));
364
+ response.status(error.status).json({ message: error.message });
365
+ }
366
+ else
367
+ response.status(502).json({ message: "Discord member information is temporarily unavailable." });
368
+ }
369
+ });
250
370
  return router;
251
371
  }
252
372
  //# sourceMappingURL=server.js.map