ludicord 2.2.0 → 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 +81 -8
  7. package/dist/auth/index.d.ts +1 -1
  8. package/dist/auth/index.js +1 -1
  9. package/dist/auth/server.js +175 -32
  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 -127
  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 -282
  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 -1
  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 +36 -15
  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
@@ -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,13 +38,52 @@ 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" }));
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) {
58
+ response.status(404).json({ authenticated: false });
59
+ return;
60
+ }
61
+ const now = Date.now();
62
+ const session = {
63
+ authenticated: true,
64
+ kind: "development",
65
+ user: {
66
+ id: "local-development-user",
67
+ username: "local_player",
68
+ displayName: "Local Player",
69
+ avatar: null,
70
+ },
71
+ applicationId: clientId,
72
+ instanceId: "local-development-instance",
73
+ scopes: ["identify"],
74
+ issuedAt: now,
75
+ expiresAt: now + 3_600_000,
76
+ };
77
+ response.setHeader("Set-Cookie", serializeSessionCookie(sealLudicordSession(session, sessionSecret), { production: false, maxAgeSeconds: 3600 }));
78
+ response.json(session);
79
+ });
41
80
  router.get("/state", (request, response) => {
42
81
  if (clientId === undefined || clientSecret === undefined || sessionSecret === undefined) {
43
82
  unavailable(response);
44
83
  return;
45
84
  }
46
85
  const state = randomBytes(32).toString("base64url");
86
+ remember(states, state, 300_000);
47
87
  response.setHeader("Set-Cookie", serializeStateCookie(state, { production: production || secureRequest(request) }));
48
88
  response.json({ state });
49
89
  });
@@ -52,20 +92,21 @@ export function createLudicordAuthRouter(options = {}) {
52
92
  unavailable(response);
53
93
  return;
54
94
  }
55
- const body = request.body;
95
+ const body = (request.body ?? {});
56
96
  const code = optionalString(body.code);
57
97
  const state = optionalString(body.state);
58
98
  const stateCookie = parseCookies(request.headers.cookie)[OAUTH_STATE_COOKIE];
59
99
  if (code === undefined ||
60
100
  state === undefined ||
61
101
  stateCookie === undefined ||
62
- !safeEqual(state, stateCookie)) {
102
+ !safeEqual(state, stateCookie) || (states.get(state) ?? 0) <= now()) {
63
103
  response.status(400).json({
64
104
  error: "LUDICORD6003",
65
105
  message: "Invalid OAuth code or state.",
66
106
  });
67
107
  return;
68
108
  }
109
+ states.delete(state);
69
110
  try {
70
111
  const tokenResponse = await fetchImplementation("https://discord.com/api/oauth2/token", {
71
112
  method: "POST",
@@ -78,6 +119,7 @@ export function createLudicordAuthRouter(options = {}) {
78
119
  grant_type: "authorization_code",
79
120
  code,
80
121
  }),
122
+ signal: AbortSignal.timeout(10_000),
81
123
  });
82
124
  if (!tokenResponse.ok) {
83
125
  response.status(502).json({
@@ -98,6 +140,7 @@ export function createLudicordAuthRouter(options = {}) {
98
140
  headers: {
99
141
  authorization: `Bearer ${token.access_token}`,
100
142
  },
143
+ signal: AbortSignal.timeout(10_000),
101
144
  });
102
145
  if (!userResponse.ok) {
103
146
  response.status(502).json({
@@ -114,30 +157,12 @@ export function createLudicordAuthRouter(options = {}) {
114
157
  });
115
158
  return;
116
159
  }
117
- const guildId = optionalString(body.context?.guildId);
118
- const channelId = optionalString(body.context?.channelId);
160
+ let guildId = optionalString(body.context?.guildId);
161
+ let channelId = optionalString(body.context?.channelId);
119
162
  const instanceId = optionalString(body.context?.instanceId);
120
163
  let activityInstanceVerified = false;
121
164
  let guildName;
122
- if (guildId !== undefined && typeof token.scope === "string" && token.scope.includes("guilds")) {
123
- try {
124
- const guildsResponse = await fetchImplementation("https://discord.com/api/users/@me/guilds", {
125
- headers: { authorization: `Bearer ${token.access_token}` },
126
- });
127
- if (guildsResponse.ok) {
128
- const userGuilds = (await guildsResponse.json());
129
- if (Array.isArray(userGuilds)) {
130
- const currentGuild = userGuilds.find((g) => g.id === guildId);
131
- if (typeof currentGuild?.name === "string") {
132
- guildName = currentGuild.name;
133
- }
134
- }
135
- }
136
- }
137
- catch {
138
- // Optional guild details fetch fallback
139
- }
140
- }
165
+ let guildIcon;
141
166
  if (verifyActivityInstance) {
142
167
  if (botToken === undefined || botToken === "") {
143
168
  unavailable(response);
@@ -154,6 +179,7 @@ export function createLudicordAuthRouter(options = {}) {
154
179
  applicationId: clientId,
155
180
  instanceId,
156
181
  botToken,
182
+ userId: user.id,
157
183
  fetch: fetchImplementation,
158
184
  now: now(),
159
185
  ...(options.activityInstanceCacheTtlMs === undefined
@@ -172,15 +198,50 @@ export function createLudicordAuthRouter(options = {}) {
172
198
  return;
173
199
  }
174
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
+ }
175
234
  }
176
235
  const issuedAt = now();
177
- 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;
178
238
  const session = {
179
239
  authenticated: true,
180
240
  user: safeUser(user),
181
241
  applicationId: clientId,
182
242
  ...(guildId === undefined ? {} : { guildId }),
183
243
  ...(guildName === undefined ? {} : { guildName }),
244
+ ...(guildIcon === undefined ? {} : { guildIcon }),
184
245
  ...(channelId === undefined ? {} : { channelId }),
185
246
  ...(instanceId === undefined ? {} : { instanceId }),
186
247
  ...(activityInstanceVerified ? { activityInstanceVerified: true } : {}),
@@ -190,15 +251,19 @@ export function createLudicordAuthRouter(options = {}) {
190
251
  issuedAt,
191
252
  expiresAt: issuedAt + expiresInSeconds * 1_000,
192
253
  };
193
- 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);
194
257
  response.append("Set-Cookie", serializeSessionCookie(sealed, {
195
258
  production: production || secureRequest(request),
196
- maxAgeSeconds: expiresInSeconds,
197
- }));
259
+ maxAgeSeconds: 120,
260
+ }).replace(`${SESSION_COOKIE}=`, `${PENDING_SESSION_COOKIE}=`));
198
261
  response.append("Set-Cookie", clearCookie(OAUTH_STATE_COOKIE, production || secureRequest(request)));
199
262
  response.json({
200
263
  access_token: token.access_token,
201
264
  session,
265
+ completionToken,
266
+ expiresInSeconds,
202
267
  });
203
268
  }
204
269
  catch {
@@ -208,22 +273,100 @@ export function createLudicordAuthRouter(options = {}) {
208
273
  });
209
274
  }
210
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
+ });
211
295
  router.get("/session", (request, response) => {
212
296
  if (sessionSecret === undefined) {
213
297
  unavailable(response);
214
298
  return;
215
299
  }
216
- const session = parseSessionCookie(request.headers.cookie, sessionSecret);
300
+ const session = parseSessionCookie(request.headers.cookie, sessionSecret, { allowDevelopment: !production });
217
301
  if (session === null) {
218
302
  response.status(401).json({ authenticated: false });
219
303
  return;
220
304
  }
221
305
  response.json(session);
222
306
  });
223
- router.post("/logout", (_request, response) => {
224
- 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))));
225
309
  response.status(204).end();
226
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
+ });
227
370
  return router;
228
371
  }
229
372
  //# sourceMappingURL=server.js.map
@@ -5,11 +5,16 @@ export interface LudicordSessionUser {
5
5
  readonly avatar: string | null;
6
6
  }
7
7
  export interface LudicordSession {
8
+ /** Development and pending credentials are never accepted as production sessions. */
9
+ readonly kind?: "development" | "pending";
10
+ readonly completionToken?: string;
11
+ readonly sessionExpiresAt?: number;
8
12
  readonly authenticated: true;
9
13
  readonly user: LudicordSessionUser;
10
14
  readonly applicationId: string;
11
15
  readonly guildId?: string;
12
16
  readonly guildName?: string;
17
+ readonly guildIcon?: string | null;
13
18
  readonly channelId?: string;
14
19
  readonly instanceId?: string;
15
20
  readonly activityInstanceVerified?: true;
package/dist/cli/index.js CHANGED
@@ -1,6 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import { pathToFileURL } from "node:url";
3
- import { loadEnv } from "vite";
3
+ import { spawn } from "node:child_process";
4
+ import { redact } from "../runtime/server/diagnostics.js";
5
+ import { loadProjectEnvironment } from "../config/environment.js";
4
6
  import { loadLudicordConfig } from "../config/loader.js";
5
7
  import { resolveProjectRoot } from "../config/project-root.js";
6
8
  import { buildLudicordProject } from "../compiler/build.js";
@@ -42,6 +44,7 @@ function parseDevArguments(args) {
42
44
  let host;
43
45
  let hmr = true;
44
46
  let open = false;
47
+ let debug = false;
45
48
  for (let index = 0; index < args.length; index += 1) {
46
49
  const argument = args[index];
47
50
  if (argument === "--port" || argument === "-p") {
@@ -67,7 +70,7 @@ function parseDevArguments(args) {
67
70
  open = true;
68
71
  }
69
72
  else if (argument === "--debug") {
70
- // Debug output is consumed by later command phases.
73
+ debug = true;
71
74
  }
72
75
  else {
73
76
  throw new Error(`LUDICORD0002: Unknown dev option "${argument}".`);
@@ -78,6 +81,7 @@ function parseDevArguments(args) {
78
81
  ...(host === undefined ? {} : { host }),
79
82
  hmr,
80
83
  open,
84
+ debug,
81
85
  };
82
86
  }
83
87
  function environmentPort() {
@@ -89,13 +93,6 @@ function environmentPort() {
89
93
  }
90
94
  return Number(value);
91
95
  }
92
- function loadProjectEnvironment(projectRoot, mode) {
93
- const environment = loadEnv(mode, projectRoot, "");
94
- for (const [name, value] of Object.entries(environment)) {
95
- if (process.env[name] === undefined)
96
- process.env[name] = value;
97
- }
98
- }
99
96
  async function runDevCommand(args, output) {
100
97
  const parsed = parseDevArguments(args);
101
98
  const projectRoot = resolveProjectRoot();
@@ -108,10 +105,14 @@ async function runDevCommand(args, output) {
108
105
  port,
109
106
  host,
110
107
  hmr: parsed.hmr,
108
+ debug: parsed.debug,
111
109
  });
112
110
  output.stdout(server.formatReadyMessage());
113
111
  if (parsed.open) {
114
- output.stdout("Open the Local URL above in your browser.");
112
+ const command = process.platform === "win32" ? "rundll32.exe" : process.platform === "darwin" ? "open" : "xdg-open";
113
+ const child = spawn(command, process.platform === "win32" ? ["url.dll,FileProtocolHandler", server.url] : [server.url], { detached: true, stdio: "ignore", windowsHide: true });
114
+ child.on("error", () => output.stderr("Ludicord could not open a browser. Open the Local URL above."));
115
+ child.unref();
115
116
  }
116
117
  const shutdown = async () => {
117
118
  await server.close();
@@ -187,7 +188,7 @@ export async function runLudicordCli(args = process.argv.slice(2), output = defa
187
188
  return await runDevCommand(args.slice(1), output);
188
189
  }
189
190
  catch (error) {
190
- output.stderr(error instanceof Error ? error.message : String(error));
191
+ output.stderr(redact(error instanceof Error ? error.message : String(error)));
191
192
  return 1;
192
193
  }
193
194
  }
@@ -198,7 +199,7 @@ export async function runLudicordCli(args = process.argv.slice(2), output = defa
198
199
  : await runStartCommand(args.slice(1), output);
199
200
  }
200
201
  catch (error) {
201
- output.stderr(error instanceof Error ? error.message : String(error));
202
+ output.stderr(redact(error instanceof Error ? error.message : String(error)));
202
203
  return 1;
203
204
  }
204
205
  }
@@ -210,7 +211,7 @@ export async function runLudicordCli(args = process.argv.slice(2), output = defa
210
211
  return await runProjectCommand(command, args.slice(1), output);
211
212
  }
212
213
  catch (error) {
213
- output.stderr(error instanceof Error ? error.message : String(error));
214
+ output.stderr(redact(error instanceof Error ? error.message : String(error)));
214
215
  return 1;
215
216
  }
216
217
  }
@@ -1,5 +1,9 @@
1
- import { existsSync, readFileSync, readdirSync, rmSync, statSync, } from "node:fs";
1
+ import { existsSync, readFileSync, rmSync, } from "node:fs";
2
2
  import path from "node:path";
3
+ import { createRequire } from "node:module";
4
+ import { createServer } from "node:net";
5
+ import { loadProjectEnvironment } from "../config/environment.js";
6
+ import { clientContainsSecret } from "../security/secret-scan.js";
3
7
  import { loadLudicordConfig } from "../config/loader.js";
4
8
  import { generateManifests } from "../compiler/scanner.js";
5
9
  import { LUDICORD_VERSION } from "../version.js";
@@ -43,35 +47,12 @@ function diagnosticLine(diagnostic) {
43
47
  : "✗";
44
48
  return `${icon} ${diagnostic.message}${diagnostic.detail === undefined ? "" : `\n ${diagnostic.detail}`}`;
45
49
  }
46
- function walkFiles(directory) {
47
- if (!existsSync(directory))
48
- return [];
49
- return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
50
- const file = path.join(directory, entry.name);
51
- return entry.isDirectory() ? walkFiles(file) : [file];
52
- });
53
- }
54
- function clientContainsSecret(projectRoot) {
55
- const client = path.join(projectRoot, ".ludicord", "client");
56
- const secrets = [
57
- process.env.LUDICORD_DISCORD_CLIENT_SECRET,
58
- process.env.LUDICORD_SESSION_SECRET,
59
- process.env.LUDICORD_DISCORD_BOT_TOKEN,
60
- ].filter((value) => value !== undefined && value !== "");
61
- if (secrets.length === 0 || !existsSync(client))
62
- return false;
63
- return walkFiles(client).some((file) => {
64
- if (statSync(file).size > 10_000_000)
65
- return false;
66
- const contents = readFileSync(file);
67
- return secrets.some((secret) => contents.includes(Buffer.from(secret)));
68
- });
69
- }
70
50
  export async function runDoctor(projectRoot) {
51
+ loadProjectEnvironment(projectRoot, "production");
71
52
  const diagnostics = [];
72
- const nodeMajor = Number(process.versions.node.split(".")[0]);
53
+ const [nodeMajor = 0, nodeMinor = 0] = process.versions.node.split(".").map(Number);
73
54
  diagnostics.push({
74
- level: nodeMajor >= 20 ? "ok" : "error",
55
+ level: nodeMajor > 20 || (nodeMajor === 20 && nodeMinor >= 19) ? "ok" : "error",
75
56
  message: `Node.js ${process.versions.node}`,
76
57
  });
77
58
  let manifests;
@@ -119,9 +100,9 @@ export async function runDoctor(projectRoot) {
119
100
  : {}),
120
101
  });
121
102
  diagnostics.push({
122
- level: process.env.LUDICORD_DISCORD_CLIENT_SECRET === undefined ? "error" : "ok",
103
+ level: !process.env.LUDICORD_DISCORD_CLIENT_SECRET?.trim() ? "error" : "ok",
123
104
  message: "Discord Client Secret",
124
- ...(process.env.LUDICORD_DISCORD_CLIENT_SECRET === undefined
105
+ ...(!process.env.LUDICORD_DISCORD_CLIENT_SECRET?.trim()
125
106
  ? { detail: "Set LUDICORD_DISCORD_CLIENT_SECRET." }
126
107
  : {}),
127
108
  });
@@ -136,7 +117,7 @@ export async function runDoctor(projectRoot) {
136
117
  : { detail: "LUDICORD_SESSION_SECRET must contain at least 32 characters." }),
137
118
  });
138
119
  if (config.discord.auth.proxyVerification &&
139
- process.env.LUDICORD_DISCORD_PUBLIC_KEY === undefined) {
120
+ !process.env.LUDICORD_DISCORD_PUBLIC_KEY?.trim()) {
140
121
  diagnostics.push({
141
122
  level: "error",
142
123
  message: "Discord Public Key",
@@ -150,7 +131,7 @@ export async function runDoctor(projectRoot) {
150
131
  });
151
132
  }
152
133
  if (config.discord.auth.activityInstanceVerification &&
153
- process.env.LUDICORD_DISCORD_BOT_TOKEN === undefined) {
134
+ !process.env.LUDICORD_DISCORD_BOT_TOKEN?.trim()) {
154
135
  diagnostics.push({
155
136
  level: "error",
156
137
  message: "Activity Instance verification token",
@@ -158,6 +139,33 @@ export async function runDoctor(projectRoot) {
158
139
  });
159
140
  }
160
141
  }
142
+ if (config) {
143
+ if (!config.discord.scopes.includes("guilds"))
144
+ diagnostics.push({ level: "warning", message: 'Add the "guilds" scope for guild and channel details.' });
145
+ if (config.discord.auth.required && !config.discord.auth.activityInstanceVerification)
146
+ diagnostics.push({ level: "warning", message: "Activity Instance verification is disabled; client-provided guild/channel/instance IDs are unverified." });
147
+ if (process.env.LUDICORD_DEV_FAKE_AUTH === "true")
148
+ diagnostics.push({ level: "warning", message: "Development fake authentication is enabled locally; never use fake sessions in production." });
149
+ if (config.server.port !== 0) {
150
+ const available = await new Promise((resolve) => {
151
+ const probe = createServer();
152
+ probe.once("error", () => resolve(false));
153
+ probe.listen(config.server.port, "127.0.0.1", () => probe.close(() => resolve(true)));
154
+ });
155
+ diagnostics.push({ level: available ? "ok" : "warning", message: available ? `Port ${config.server.port} is available` : `Port ${config.server.port} is occupied or unavailable; stop the existing server or select --port.` });
156
+ }
157
+ }
158
+ const metadataFile = path.join(projectRoot, ".ludicord", "build.json");
159
+ if (existsSync(metadataFile)) {
160
+ try {
161
+ const metadata = JSON.parse(readFileSync(metadataFile, "utf8"));
162
+ if (metadata.frameworkVersion !== LUDICORD_VERSION)
163
+ diagnostics.push({ level: "warning", message: "Production output was built with a different framework version. Run ludicord build." });
164
+ }
165
+ catch {
166
+ diagnostics.push({ level: "error", message: "Invalid production build metadata. Run ludicord build." });
167
+ }
168
+ }
161
169
  diagnostics.push({
162
170
  level: existsSync(path.join(projectRoot, ".ludicord", "build.json"))
163
171
  ? "ok"
@@ -169,9 +177,10 @@ export async function runDoctor(projectRoot) {
169
177
  ? {}
170
178
  : { detail: "Run ludicord build before ludicord start." }),
171
179
  });
180
+ const leaked = clientContainsSecret(path.join(projectRoot, ".ludicord", "client"));
172
181
  diagnostics.push({
173
- level: clientContainsSecret(projectRoot) ? "error" : "ok",
174
- message: clientContainsSecret(projectRoot)
182
+ level: leaked ? "error" : "ok",
183
+ message: leaked
175
184
  ? "Server secret detected in client output"
176
185
  : "No server secret leakage detected",
177
186
  });
@@ -193,7 +202,13 @@ function dependencyVersion(projectRoot, packageName) {
193
202
  .version;
194
203
  }
195
204
  catch {
196
- return "not installed";
205
+ try {
206
+ const require = createRequire(import.meta.url);
207
+ return JSON.parse(readFileSync(require.resolve(packageName + "/package.json"), "utf8")).version;
208
+ }
209
+ catch {
210
+ return "not installed";
211
+ }
197
212
  }
198
213
  }
199
214
  export function formatInfo(projectRoot) {