ludicord 2.2.1 → 2.2.5

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 +21 -7
  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 +298 -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
@@ -0,0 +1,17 @@
1
+ export interface LudicordDiagnostic {
2
+ readonly message: string;
3
+ readonly file?: string;
4
+ readonly line?: number;
5
+ readonly column?: number;
6
+ readonly frame?: string;
7
+ readonly stack?: string;
8
+ readonly kind: "compile" | "type" | "runtime";
9
+ }
10
+ export declare function redact(message: string): string;
11
+ export declare function sourceFrame(root: string, file: string, line: number, column: number): string | undefined;
12
+ export declare function diagnostic(error: unknown, root: string, file?: string, kind?: LudicordDiagnostic["kind"]): LudicordDiagnostic;
13
+ export declare function checkProjectTypes(root: string): readonly LudicordDiagnostic[];
14
+ export declare function watchProjectTypes(root: string, publish: (items: readonly LudicordDiagnostic[]) => void): {
15
+ close(): void;
16
+ } | undefined;
17
+ //# sourceMappingURL=diagnostics.d.ts.map
@@ -0,0 +1,87 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import ts from "typescript";
5
+ export function redact(message) {
6
+ let text = message;
7
+ for (const key of ["LUDICORD_DISCORD_CLIENT_SECRET", "LUDICORD_SESSION_SECRET", "LUDICORD_DISCORD_BOT_TOKEN"]) {
8
+ const value = process.env[key];
9
+ if (value)
10
+ text = text.split(value).join("[redacted]");
11
+ }
12
+ return text;
13
+ }
14
+ export function sourceFrame(root, file, line, column) {
15
+ const absolute = path.resolve(root, file);
16
+ const relative = path.relative(root, absolute);
17
+ if (relative.startsWith("..") || path.isAbsolute(relative) || !/\.[cm]?[jt]sx?$/.test(file) || !existsSync(absolute))
18
+ return undefined;
19
+ const lines = readFileSync(absolute, "utf8").split(/\r?\n/);
20
+ return redact(lines.slice(Math.max(0, line - 3), line + 2).map((source, index) => {
21
+ const number = Math.max(1, line - 2) + index;
22
+ return `${number === line ? ">" : " "} ${String(number).padStart(4)} | ${source}${number === line ? `\n | ${" ".repeat(Math.max(0, Math.min(column - 1, 300)))}^` : ""}`;
23
+ }).join("\n"));
24
+ }
25
+ export function diagnostic(error, root, file, kind = "runtime") {
26
+ const value = error;
27
+ const first = value?.errors?.[0];
28
+ let location = first?.location ?? value?.loc;
29
+ if (!location && value?.stack) {
30
+ for (const match of value.stack.matchAll(/(?:\(|at\s+)((?:file:\/\/\/|[A-Za-z]:[\\/]|\/)[^\n]+?):(\d+):(\d+)\)?/g)) {
31
+ try {
32
+ const source = match[1]?.startsWith("file:") ? fileURLToPath(match[1]) : match[1];
33
+ if (source && sourceFrame(root, source, Number(match[2]), Number(match[3]))) {
34
+ location = { file: source, line: Number(match[2]), column: Number(match[3]) - 1 };
35
+ break;
36
+ }
37
+ }
38
+ catch { /* Not a local source frame. */ }
39
+ }
40
+ }
41
+ const target = (location?.file ?? value?.id ?? file)?.split("?", 1)[0];
42
+ const relative = target === undefined ? undefined : path.relative(root, path.resolve(root, target)).split(path.sep).join("/");
43
+ const line = location?.line;
44
+ const column = location?.column === undefined ? undefined : location.column + 1;
45
+ const frame = target !== undefined && line !== undefined ? sourceFrame(root, target, line, column ?? 1) : value?.frame;
46
+ let message = first?.text ?? value?.message ?? String(error);
47
+ if (kind === "compile") {
48
+ message = message.split("\n")[0] ?? message;
49
+ if (target && message.includes(target))
50
+ message = message.slice(message.indexOf(target) + target.length).replace(/^:\s*/, "");
51
+ }
52
+ return {
53
+ kind, message: redact(message),
54
+ ...(relative === undefined ? {} : { file: relative }),
55
+ ...(line === undefined ? {} : { line }), ...(column === undefined ? {} : { column }),
56
+ ...(frame === undefined ? {} : { frame: redact(frame) }),
57
+ ...(value?.stack === undefined ? {} : { stack: redact(value.stack) }),
58
+ };
59
+ }
60
+ function tsDiagnostic(item, root) {
61
+ const position = item.file?.getLineAndCharacterOfPosition(item.start ?? 0);
62
+ return diagnostic({ message: `TS${item.code}: ${ts.flattenDiagnosticMessageText(item.messageText, "\n")}`,
63
+ ...(item.file === undefined ? {} : { loc: { file: item.file.fileName, line: (position?.line ?? 0) + 1, column: position?.character ?? 0 } }),
64
+ }, root, undefined, "type");
65
+ }
66
+ export function checkProjectTypes(root) {
67
+ const config = path.join(root, "tsconfig.json");
68
+ if (!existsSync(config))
69
+ return [];
70
+ const raw = ts.readConfigFile(config, ts.sys.readFile);
71
+ if (raw.error)
72
+ return [tsDiagnostic(raw.error, root)];
73
+ const parsed = ts.parseJsonConfigFileContent(raw.config, ts.sys, root, { noEmit: true }, config);
74
+ const program = ts.createProgram(parsed.fileNames, parsed.options);
75
+ return [...parsed.errors, ...ts.getPreEmitDiagnostics(program)].map((item) => tsDiagnostic(item, root));
76
+ }
77
+ export function watchProjectTypes(root, publish) {
78
+ const config = path.join(root, "tsconfig.json");
79
+ if (!existsSync(config))
80
+ return undefined;
81
+ const host = ts.createWatchCompilerHost(config, { noEmit: true }, ts.sys, ts.createSemanticDiagnosticsBuilderProgram, () => { }, () => { });
82
+ host.afterProgramCreate = (program) => {
83
+ publish(ts.getPreEmitDiagnostics(program.getProgram()).map((item) => tsDiagnostic(item, root)));
84
+ };
85
+ return ts.createWatchProgram(host);
86
+ }
87
+ //# sourceMappingURL=diagnostics.js.map
@@ -0,0 +1,5 @@
1
+ export { createLudicordDevServer } from "./dev-server.js";
2
+ export { createLudicordProductionServer } from "./production-server.js";
3
+ export type { LudicordDevServer, LudicordDevServerOptions } from "./dev-server.js";
4
+ export type { LudicordProductionServer, LudicordProductionServerOptions } from "./production-server.js";
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,3 @@
1
+ export { createLudicordDevServer } from "./dev-server.js";
2
+ export { createLudicordProductionServer } from "./production-server.js";
3
+ //# sourceMappingURL=index.js.map
@@ -7,6 +7,8 @@ import { createApiMiddleware } from "../../api/runtime.js";
7
7
  import { createLudicordAuthRouter } from "../../auth/server.js";
8
8
  import { attachWebSocketRuntime, } from "../../ws/server.js";
9
9
  import { LUDICORD_VERSION } from "../../version.js";
10
+ import { loadProjectEnvironment } from "../../config/environment.js";
11
+ import { redact } from "./diagnostics.js";
10
12
  function readJson(file) {
11
13
  return JSON.parse(readFileSync(file, "utf8"));
12
14
  }
@@ -47,8 +49,10 @@ function bundleLoader(output, bundles) {
47
49
  }
48
50
  export async function createLudicordProductionServer(options) {
49
51
  const projectRoot = path.resolve(options.projectRoot);
52
+ loadProjectEnvironment(projectRoot, "production");
50
53
  const { output, metadata, manifests } = loadProductionBuild(projectRoot);
51
54
  const app = express();
55
+ app.set("env", "production");
52
56
  const httpServer = createServer(app);
53
57
  const apiLoader = bundleLoader(output, metadata.api);
54
58
  const wsLoader = bundleLoader(output, metadata.websocket);
@@ -70,6 +74,8 @@ export async function createLudicordProductionServer(options) {
70
74
  ? {}
71
75
  : { sessionSecret: process.env.LUDICORD_SESSION_SECRET }),
72
76
  proxyVerification: metadata.config.discord.proxyVerification,
77
+ bodyLimit: metadata.config.server.limits.body,
78
+ allowDevelopmentSessions: false,
73
79
  ...(process.env.LUDICORD_DISCORD_PUBLIC_KEY === undefined
74
80
  ? {}
75
81
  : { discordPublicKey: process.env.LUDICORD_DISCORD_PUBLIC_KEY }),
@@ -84,6 +90,9 @@ export async function createLudicordProductionServer(options) {
84
90
  heartbeatInterval: metadata.config.websocket.heartbeatInterval,
85
91
  maxPayload: metadata.config.websocket.maxPayload,
86
92
  compression: metadata.config.websocket.compression,
93
+ enabled: metadata.config.websocket.enabled,
94
+ allowDevelopmentSessions: false,
95
+ onError: (error) => console.error(redact(error instanceof Error ? error.stack ?? error.message : String(error))),
87
96
  });
88
97
  const clientDirectory = path.join(output, "client");
89
98
  const indexHtml = readFileSync(path.join(clientDirectory, "index.html"), "utf8");
@@ -91,6 +100,11 @@ export async function createLudicordProductionServer(options) {
91
100
  app.get("/", (_request, response) => {
92
101
  response.status(200).type("html").send(indexHtml);
93
102
  });
103
+ app.use((error, _request, response, _next) => {
104
+ console.error(redact(error instanceof Error ? error.stack ?? error.message : String(error)));
105
+ if (!response.headersSent)
106
+ response.status(500).json({ error: "LUDICORD_INTERNAL_ERROR", message: "An internal error occurred. Please try again." });
107
+ });
94
108
  const portOption = options.port ?? metadata.config.server.port;
95
109
  const host = options.host ?? metadata.config.server.host;
96
110
  await new Promise((resolve, reject) => {
@@ -17,6 +17,7 @@ export declare function verifyDiscordProxyRequest(options: VerifyDiscordProxyReq
17
17
  export type DiscordActivityInstanceVerificationResult = {
18
18
  readonly verified: true;
19
19
  readonly cached: boolean;
20
+ readonly instance: DiscordActivityInstance;
20
21
  } | {
21
22
  readonly verified: false;
22
23
  readonly reason: "missing" | "unauthorized" | "rate-limited" | "unavailable";
@@ -29,6 +30,14 @@ export interface VerifyDiscordActivityInstanceOptions {
29
30
  readonly fetch?: typeof fetch;
30
31
  readonly now?: number;
31
32
  readonly cacheTtlMs?: number;
33
+ readonly userId?: string;
34
+ }
35
+ export interface DiscordActivityInstance {
36
+ readonly applicationId: string;
37
+ readonly instanceId: string;
38
+ readonly userIds: readonly string[];
39
+ readonly guildId?: string;
40
+ readonly channelId?: string;
32
41
  }
33
42
  export declare function verifyDiscordActivityInstance(options: VerifyDiscordActivityInstanceOptions): Promise<DiscordActivityInstanceVerificationResult>;
34
43
  export declare function resetDiscordSecurityCacheForTesting(): void;
@@ -1,4 +1,4 @@
1
- import { createPublicKey, verify as verifySignature, } from "node:crypto";
1
+ import { createPublicKey, createHash, verify as verifySignature, } from "node:crypto";
2
2
  const ED25519_SPKI_PREFIX = Buffer.from("302a300506032b6570032100", "hex");
3
3
  const DEFAULT_MAX_AGE_MS = 5 * 60 * 1_000;
4
4
  const DEFAULT_INSTANCE_CACHE_MS = 30_000;
@@ -51,6 +51,7 @@ export function verifyDiscordProxyRequest(options) {
51
51
  }
52
52
  const instanceCache = new Map();
53
53
  const pendingInstanceChecks = new Map();
54
+ const rateLimits = new Map();
54
55
  function retryAfter(response) {
55
56
  const value = response.headers.get("retry-after");
56
57
  if (value === null)
@@ -79,21 +80,36 @@ export async function verifyDiscordActivityInstance(options) {
79
80
  return { verified: false, reason: "missing" };
80
81
  }
81
82
  const now = options.now ?? Date.now();
82
- const key = `${options.applicationId}:${options.instanceId}`;
83
+ const credential = createHash("sha256").update(options.botToken).digest("hex");
84
+ const key = `${options.applicationId}:${options.instanceId}:${credential}`;
85
+ const membership = (result) => {
86
+ if (result.verified && options.userId !== undefined && !result.instance.userIds.includes(options.userId)) {
87
+ return { verified: false, reason: "unauthorized" };
88
+ }
89
+ return result;
90
+ };
91
+ const limitedUntil = rateLimits.get(credential) ?? 0;
92
+ if (limitedUntil > now)
93
+ return { verified: false, reason: "rate-limited", retryAfterMs: limitedUntil - now };
94
+ rateLimits.delete(credential);
83
95
  const cached = instanceCache.get(key);
84
96
  if (cached !== undefined && cached.expiresAt > now) {
85
- return { verified: true, cached: true };
97
+ return membership({ verified: true, cached: true, instance: cached.instance });
86
98
  }
87
99
  const pending = pendingInstanceChecks.get(key);
88
100
  if (pending !== undefined)
89
- return pending;
101
+ return membership(await pending);
90
102
  const request = (async () => {
91
103
  try {
92
104
  const response = await (options.fetch ?? globalThis.fetch)(`https://discord.com/api/v10/applications/${encodeURIComponent(options.applicationId)}/activity-instances/${encodeURIComponent(options.instanceId)}`, {
93
105
  headers: { authorization: `Bot ${options.botToken}` },
106
+ signal: AbortSignal.timeout(10_000),
94
107
  });
95
108
  if (response.status === 429) {
96
109
  const delay = retryAfter(response);
110
+ if (rateLimits.size >= MAX_INSTANCE_CACHE_ENTRIES)
111
+ rateLimits.clear();
112
+ rateLimits.set(credential, now + (delay ?? 1000));
97
113
  return {
98
114
  verified: false,
99
115
  reason: "rate-limited",
@@ -106,11 +122,24 @@ export async function verifyDiscordActivityInstance(options) {
106
122
  if (!response.ok) {
107
123
  return { verified: false, reason: "unavailable" };
108
124
  }
125
+ const body = await response.json();
126
+ if (body.application_id !== options.applicationId || body.instance_id !== options.instanceId ||
127
+ !Array.isArray(body.users) || !body.users.every((id) => typeof id === "string")) {
128
+ return { verified: false, reason: "unavailable" };
129
+ }
130
+ const instance = {
131
+ applicationId: options.applicationId,
132
+ instanceId: options.instanceId,
133
+ userIds: body.users,
134
+ ...(typeof body.location?.guild_id === "string" ? { guildId: body.location.guild_id } : {}),
135
+ ...(typeof body.location?.channel_id === "string" ? { channelId: body.location.channel_id } : {}),
136
+ };
109
137
  pruneInstanceCache(now);
110
138
  instanceCache.set(key, {
111
- expiresAt: now + (options.cacheTtlMs ?? DEFAULT_INSTANCE_CACHE_MS),
139
+ expiresAt: now + Math.min(Math.max(options.cacheTtlMs ?? DEFAULT_INSTANCE_CACHE_MS, 0), DEFAULT_INSTANCE_CACHE_MS),
140
+ instance,
112
141
  });
113
- return { verified: true, cached: false };
142
+ return { verified: true, cached: false, instance };
114
143
  }
115
144
  catch {
116
145
  return { verified: false, reason: "unavailable" };
@@ -120,10 +149,11 @@ export async function verifyDiscordActivityInstance(options) {
120
149
  }
121
150
  })();
122
151
  pendingInstanceChecks.set(key, request);
123
- return request;
152
+ return membership(await request);
124
153
  }
125
154
  export function resetDiscordSecurityCacheForTesting() {
126
155
  instanceCache.clear();
127
156
  pendingInstanceChecks.clear();
157
+ rateLimits.clear();
128
158
  }
129
159
  //# sourceMappingURL=discord.js.map
@@ -0,0 +1,3 @@
1
+ /** Streaming scan, including binary/large public assets and chunk-boundary matches. Never reports a secret value. */
2
+ export declare function clientContainsSecret(directory: string): boolean;
3
+ //# sourceMappingURL=secret-scan.d.ts.map
@@ -0,0 +1,40 @@
1
+ import { existsSync, readdirSync, openSync, readSync, closeSync } from "node:fs";
2
+ import path from "node:path";
3
+ /** Streaming scan, including binary/large public assets and chunk-boundary matches. Never reports a secret value. */
4
+ export function clientContainsSecret(directory) {
5
+ const secrets = ["LUDICORD_DISCORD_CLIENT_SECRET", "LUDICORD_SESSION_SECRET", "LUDICORD_DISCORD_BOT_TOKEN"]
6
+ .map((key) => process.env[key]).filter((value) => Boolean(value)).map((value) => Buffer.from(value));
7
+ if (!secrets.length || !existsSync(directory))
8
+ return false;
9
+ const overlap = Math.max(...secrets.map((secret) => secret.length)) - 1;
10
+ const scan = (folder) => {
11
+ for (const entry of readdirSync(folder, { withFileTypes: true })) {
12
+ const file = path.join(folder, entry.name);
13
+ if (entry.isDirectory()) {
14
+ if (scan(file))
15
+ return true;
16
+ continue;
17
+ }
18
+ if (!entry.isFile())
19
+ continue;
20
+ const descriptor = openSync(file, "r");
21
+ try {
22
+ const chunk = Buffer.alloc(64 * 1024);
23
+ let tail = Buffer.alloc(0);
24
+ let size;
25
+ while ((size = readSync(descriptor, chunk, 0, chunk.length, null)) > 0) {
26
+ const contents = Buffer.concat([tail, chunk.subarray(0, size)]);
27
+ if (secrets.some((secret) => contents.includes(secret)))
28
+ return true;
29
+ tail = Buffer.from(contents.subarray(Math.max(0, contents.length - overlap)));
30
+ }
31
+ }
32
+ finally {
33
+ closeSync(descriptor);
34
+ }
35
+ }
36
+ return false;
37
+ };
38
+ return scan(directory);
39
+ }
40
+ //# sourceMappingURL=secret-scan.js.map
@@ -0,0 +1,45 @@
1
+ export declare class LudicordDiscordRestError extends Error {
2
+ readonly status: number;
3
+ readonly retryAfterMs?: number | undefined;
4
+ constructor(status: number, message: string, retryAfterMs?: number | undefined);
5
+ }
6
+ export interface DiscordRestMember {
7
+ readonly user: {
8
+ readonly id: string;
9
+ readonly username: string;
10
+ readonly global_name?: string | null;
11
+ readonly avatar?: string | null;
12
+ };
13
+ readonly nick?: string | null;
14
+ readonly avatar?: string | null;
15
+ readonly roles: readonly string[];
16
+ readonly joined_at?: string;
17
+ }
18
+ export interface DiscordRestGuild {
19
+ readonly id: string;
20
+ readonly name: string;
21
+ readonly icon?: string | null;
22
+ readonly description?: string | null;
23
+ readonly approximate_member_count?: number;
24
+ readonly features?: readonly string[];
25
+ }
26
+ export interface DiscordRestChannel {
27
+ readonly id: string;
28
+ readonly type: number;
29
+ readonly name?: string;
30
+ readonly guild_id?: string;
31
+ readonly topic?: string | null;
32
+ }
33
+ /** REST only: no Gateway connection, bot runtime, or client-side token exposure. */
34
+ export declare function createDiscordRest(options?: {
35
+ readonly botToken?: string;
36
+ readonly fetch?: typeof fetch;
37
+ }): {
38
+ getGuild: (guildId: string) => Promise<DiscordRestGuild>;
39
+ getChannel: (channelId: string) => Promise<DiscordRestChannel>;
40
+ listGuildMembers(guildId: string, pagination?: {
41
+ readonly limit?: number;
42
+ readonly after?: string;
43
+ }): Promise<DiscordRestMember[]>;
44
+ };
45
+ //# sourceMappingURL=discord-rest.d.ts.map
@@ -0,0 +1,46 @@
1
+ export class LudicordDiscordRestError extends Error {
2
+ status;
3
+ retryAfterMs;
4
+ constructor(status, message, retryAfterMs) {
5
+ super(message);
6
+ this.status = status;
7
+ this.retryAfterMs = retryAfterMs;
8
+ this.name = "LudicordDiscordRestError";
9
+ }
10
+ }
11
+ /** REST only: no Gateway connection, bot runtime, or client-side token exposure. */
12
+ export function createDiscordRest(options = {}) {
13
+ const token = options.botToken ?? process.env.LUDICORD_DISCORD_BOT_TOKEN;
14
+ const fetchImplementation = options.fetch ?? globalThis.fetch;
15
+ let limitedUntil = 0;
16
+ async function get(resource) {
17
+ if (!token)
18
+ throw new LudicordDiscordRestError(501, "Discord server data requires LUDICORD_DISCORD_BOT_TOKEN. The token stays server-only.");
19
+ if (limitedUntil > Date.now())
20
+ throw new LudicordDiscordRestError(429, "Discord rate limit reached. Please retry later.", limitedUntil - Date.now());
21
+ const response = await fetchImplementation("https://discord.com/api/v10" + resource, { headers: { authorization: "Bot " + token }, signal: AbortSignal.timeout(10_000) });
22
+ if (response.status === 429) {
23
+ const data = await response.json().catch(() => ({}));
24
+ const delay = Number(response.headers.get("retry-after") ?? data.retry_after ?? 1);
25
+ const retryAfterMs = Math.max(1000, Number.isFinite(delay) ? delay * 1000 : 1000);
26
+ limitedUntil = Date.now() + retryAfterMs;
27
+ throw new LudicordDiscordRestError(429, "Discord rate limit reached. Please retry later.", retryAfterMs);
28
+ }
29
+ if (!response.ok)
30
+ throw new LudicordDiscordRestError(response.status, response.status === 403 ? "Discord denied access. Check the application's guild access, permissions, and the GUILD_MEMBERS privileged intent for member lists." : "Discord could not provide the requested server data.");
31
+ return response.json();
32
+ }
33
+ const id = (value) => { if (!/^\d+$/.test(value))
34
+ throw new LudicordDiscordRestError(400, "Invalid Discord ID."); return encodeURIComponent(value); };
35
+ return {
36
+ getGuild: (guildId) => get(`/guilds/${id(guildId)}?with_counts=true`),
37
+ getChannel: (channelId) => get(`/channels/${id(channelId)}`),
38
+ listGuildMembers(guildId, pagination = {}) {
39
+ const limit = Math.min(1000, Math.max(1, Math.floor(pagination.limit ?? 100)));
40
+ if (!Number.isFinite(limit))
41
+ throw new LudicordDiscordRestError(400, "Invalid member page size.");
42
+ return get(`/guilds/${id(guildId)}/members?limit=${limit}${pagination.after ? `&after=${id(pagination.after)}` : ""}`);
43
+ },
44
+ };
45
+ }
46
+ //# sourceMappingURL=discord-rest.js.map
@@ -1,3 +1,5 @@
1
1
  export { getLudicordSession, requireLudicordSession, } from "./session.js";
2
2
  export type { LudicordRequest, LudicordRequestVerification, RouteContext, } from "./types.js";
3
+ export { createDiscordRest, LudicordDiscordRestError } from "./discord-rest.js";
4
+ export type { DiscordRestGuild, DiscordRestChannel, DiscordRestMember } from "./discord-rest.js";
3
5
  //# sourceMappingURL=index.d.ts.map
@@ -1,2 +1,3 @@
1
1
  export { getLudicordSession, requireLudicordSession, } from "./session.js";
2
+ export { createDiscordRest, LudicordDiscordRestError } from "./discord-rest.js";
2
3
  //# sourceMappingURL=index.js.map
@@ -1,6 +1,7 @@
1
1
  import type { LudicordSession } from "../auth/types.js";
2
2
  export declare const SESSION_COOKIE = "ludicord_session";
3
3
  export declare const OAUTH_STATE_COOKIE = "ludicord_oauth_state";
4
+ export declare const PENDING_SESSION_COOKIE = "ludicord_pending_session";
4
5
  export interface CookieOptions {
5
6
  readonly production: boolean;
6
7
  readonly maxAgeSeconds?: number;
@@ -9,5 +10,7 @@ export declare function serializeSessionCookie(value: string, options: CookieOpt
9
10
  export declare function serializeStateCookie(value: string, options: CookieOptions): string;
10
11
  export declare function clearCookie(name: string, production: boolean): string;
11
12
  export declare function parseCookies(cookieHeader: string | undefined): Readonly<Record<string, string>>;
12
- export declare function parseSessionCookie(cookieHeader: string | undefined, secret: string): LudicordSession | null;
13
+ export declare function parseSessionCookie(cookieHeader: string | undefined, secret: string, options?: {
14
+ readonly allowDevelopment?: boolean;
15
+ }): LudicordSession | null;
13
16
  //# sourceMappingURL=cookies.d.ts.map
@@ -1,6 +1,7 @@
1
1
  import { unsealLudicordSession } from "./crypto.js";
2
2
  export const SESSION_COOKIE = "ludicord_session";
3
3
  export const OAUTH_STATE_COOKIE = "ludicord_oauth_state";
4
+ export const PENDING_SESSION_COOKIE = "ludicord_pending_session";
4
5
  function baseCookie(name, value, options) {
5
6
  const parts = [
6
7
  `${name}=${encodeURIComponent(value)}`,
@@ -41,13 +42,25 @@ export function parseCookies(cookieHeader) {
41
42
  continue;
42
43
  const name = pair.slice(0, separator).trim();
43
44
  const value = pair.slice(separator + 1).trim();
44
- if (name !== "")
45
- cookies[name] = decodeURIComponent(value);
45
+ if (name !== "") {
46
+ try {
47
+ cookies[name] = decodeURIComponent(value);
48
+ }
49
+ catch {
50
+ // A malformed, untrusted cookie must never escape into an upgrade handler.
51
+ return {};
52
+ }
53
+ }
46
54
  }
47
55
  return cookies;
48
56
  }
49
- export function parseSessionCookie(cookieHeader, secret) {
57
+ export function parseSessionCookie(cookieHeader, secret, options = {}) {
50
58
  const value = parseCookies(cookieHeader)[SESSION_COOKIE];
51
- return value === undefined ? null : unsealLudicordSession(value, secret);
59
+ const session = value === undefined ? null : unsealLudicordSession(value, secret);
60
+ if (session?.kind === "pending")
61
+ return null;
62
+ if (session?.kind === "development" && options.allowDevelopment !== true)
63
+ return null;
64
+ return session;
52
65
  }
53
66
  //# sourceMappingURL=cookies.js.map
@@ -42,7 +42,13 @@ export function unsealLudicordSession(value, secret) {
42
42
  ]);
43
43
  const session = JSON.parse(decrypted.toString("utf8"));
44
44
  if (session.authenticated !== true ||
45
+ typeof session.user?.id !== "string" ||
46
+ typeof session.user?.username !== "string" ||
47
+ typeof session.applicationId !== "string" ||
48
+ !Array.isArray(session.scopes) ||
49
+ !session.scopes.every((scope) => typeof scope === "string") ||
45
50
  typeof session.expiresAt !== "number" ||
51
+ !Number.isFinite(session.expiresAt) ||
46
52
  session.expiresAt <= Date.now()) {
47
53
  return null;
48
54
  }
@@ -2,4 +2,17 @@ export { createMockDiscord, resetDiscordRuntimeForTesting, } from "../discord/te
2
2
  export { resetLudicordAuthForTesting } from "../auth/client.js";
3
3
  export type { MockDiscordController } from "../discord/testing.js";
4
4
  export { resetDiscordEventStoreForTesting } from "../discord/events.js";
5
+ import type { ReactNode } from "react";
6
+ import type { LudicordSession } from "../auth/types.js";
7
+ import type { LudicordFileComponents } from "../runtime/client/files.js";
8
+ export declare function createMockSession(overrides?: Partial<LudicordSession>): LudicordSession;
9
+ export declare function renderLudicordActivity(children: ReactNode, options?: {
10
+ readonly container?: HTMLElement;
11
+ readonly session?: LudicordSession | null;
12
+ readonly files?: LudicordFileComponents;
13
+ }): Promise<{
14
+ container: HTMLElement;
15
+ rerender: (node: ReactNode) => Promise<void>;
16
+ unmount(): Promise<void>;
17
+ }>;
5
18
  //# sourceMappingURL=index.d.ts.map
@@ -1,4 +1,28 @@
1
1
  export { createMockDiscord, resetDiscordRuntimeForTesting, } from "../discord/testing.js";
2
2
  export { resetLudicordAuthForTesting } from "../auth/client.js";
3
3
  export { resetDiscordEventStoreForTesting } from "../discord/events.js";
4
+ import { createElement, act } from "react";
5
+ import { createRoot } from "react-dom/client";
6
+ import { setMockSessionForTesting } from "../auth/client.js";
7
+ import { LudicordRoot } from "../runtime/client/root.js";
8
+ export function createMockSession(overrides = {}) {
9
+ return { authenticated: true, user: { id: "mock-user", username: "mock_user", displayName: "Mock User", avatar: null },
10
+ applicationId: "mock-application", instanceId: "mock-instance", guildId: "mock-guild", channelId: "mock-channel",
11
+ scopes: ["identify", "guilds"], issuedAt: Date.now(), expiresAt: Date.now() + 3_600_000, ...overrides };
12
+ }
13
+ export async function renderLudicordActivity(children, options = {}) {
14
+ if (typeof document === "undefined")
15
+ throw new Error("LUDICORD_TEST1001: renderLudicordActivity requires a DOM environment such as jsdom.");
16
+ const container = options.container ?? document.createElement("div");
17
+ if (!container.isConnected)
18
+ document.body.append(container);
19
+ if (options.session !== undefined)
20
+ setMockSessionForTesting(options.session);
21
+ const root = createRoot(container);
22
+ const render = async (node) => { await act(async () => root.render(createElement(LudicordRoot, { files: options.files ?? {}, children: node }))); };
23
+ await render(children);
24
+ return { container, rerender: render, async unmount() { await act(async () => root.unmount()); if (options.container === undefined)
25
+ container.remove(); if (options.session !== undefined)
26
+ setMockSessionForTesting(null); } };
27
+ }
4
28
  //# sourceMappingURL=index.js.map
package/dist/version.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export declare const LUDICORD_VERSION: "2.1.0";
1
+ export declare const LUDICORD_VERSION: "2.2.5";
2
2
  //# sourceMappingURL=version.d.ts.map
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
- export const LUDICORD_VERSION = "2.1.0";
1
+ export const LUDICORD_VERSION = "2.2.5";
2
2
  //# sourceMappingURL=version.js.map
@@ -10,7 +10,11 @@ interface BrowserSocket {
10
10
  send(data: string): void;
11
11
  close(code?: number, reason?: string): void;
12
12
  }
13
+ export declare const subscribeWebSocketRuntime: (listener: () => void) => () => void;
14
+ export declare const isWebSocketRuntimeReady: () => boolean;
13
15
  export interface LudicordWSConnectionOptions {
16
+ readonly enabled?: boolean;
17
+ readonly autoConnect?: boolean;
14
18
  readonly reconnect?: {
15
19
  readonly enabled?: boolean;
16
20
  readonly attempts?: number;
@@ -38,6 +42,7 @@ export declare class LudicordWebSocketConnection {
38
42
  private manuallyClosed;
39
43
  private readonly reconnectOptions;
40
44
  private readonly factory;
45
+ private readonly enabled;
41
46
  constructor(route: LudicordWSRoute, options?: LudicordWSConnectionOptions);
42
47
  readonly subscribe: (listener: () => void) => (() => void);
43
48
  readonly getStatus: () => LudicordWSStatus;
@@ -50,6 +55,7 @@ export declare class LudicordWebSocketConnection {
50
55
  off(event: string, listener: (data: unknown) => void): void;
51
56
  close(): void;
52
57
  reconnect(): void;
58
+ start(): void;
53
59
  }
54
60
  export declare function useWS(route: LudicordWSRoute, options?: LudicordWSConnectionOptions): LudicordWSConnection;
55
61
  export {};