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.
- package/README.md +21 -7
- package/bin/ludicord.js +0 -0
- package/dist/api/runtime.d.ts +4 -0
- package/dist/api/runtime.js +61 -10
- package/dist/auth/client.d.ts +10 -0
- package/dist/auth/client.js +58 -8
- package/dist/auth/index.d.ts +1 -1
- package/dist/auth/index.js +1 -1
- package/dist/auth/server.js +154 -34
- package/dist/auth/types.d.ts +5 -0
- package/dist/cli/index.js +14 -13
- package/dist/cli/project-commands.js +49 -34
- package/dist/compiler/build.js +37 -128
- package/dist/compiler/client-entry.d.ts +4 -0
- package/dist/compiler/client-entry.js +35 -0
- package/dist/compiler/client-tooling.d.ts +5 -0
- package/dist/compiler/client-tooling.js +97 -0
- package/dist/compiler/scanner.js +8 -0
- package/dist/compiler/server-bundle.d.ts +11 -0
- package/dist/compiler/server-bundle.js +31 -0
- package/dist/compiler/type-generation.js +11 -2
- package/dist/config/defaults.js +28 -2
- package/dist/config/environment.d.ts +2 -0
- package/dist/config/environment.js +18 -0
- package/dist/discord/data.d.ts +21 -0
- package/dist/discord/data.js +91 -0
- package/dist/discord/events.d.ts +42 -4
- package/dist/discord/events.js +120 -41
- package/dist/discord/index.d.ts +4 -2
- package/dist/discord/index.js +2 -1
- package/dist/discord/runtime.d.ts +2 -2
- package/dist/discord/runtime.js +9 -13
- package/dist/discord/testing.d.ts +1 -0
- package/dist/discord/testing.js +10 -0
- package/dist/manifests/types.d.ts +4 -0
- package/dist/navigation/index.d.ts +2 -0
- package/dist/runtime/client/dev-panel.d.ts +2 -0
- package/dist/runtime/client/dev-panel.js +63 -0
- package/dist/runtime/client/embed-router.d.ts +4 -1
- package/dist/runtime/client/embed-router.js +69 -17
- package/dist/runtime/client/files.d.ts +23 -0
- package/dist/runtime/client/files.js +12 -0
- package/dist/runtime/client/minimize-card.js +4 -4
- package/dist/runtime/client/minimize.d.ts +1 -0
- package/dist/runtime/client/minimize.js +1 -0
- package/dist/runtime/client/root.d.ts +7 -0
- package/dist/runtime/client/root.js +19 -0
- package/dist/runtime/index.d.ts +8 -4
- package/dist/runtime/index.js +14 -2
- package/dist/runtime/server/dev-server.d.ts +1 -0
- package/dist/runtime/server/dev-server.js +298 -319
- package/dist/runtime/server/diagnostics.d.ts +17 -0
- package/dist/runtime/server/diagnostics.js +87 -0
- package/dist/runtime/server/index.d.ts +5 -0
- package/dist/runtime/server/index.js +3 -0
- package/dist/runtime/server/production-server.js +14 -0
- package/dist/security/discord.d.ts +9 -0
- package/dist/security/discord.js +37 -7
- package/dist/security/secret-scan.d.ts +3 -0
- package/dist/security/secret-scan.js +40 -0
- package/dist/server/discord-rest.d.ts +45 -0
- package/dist/server/discord-rest.js +46 -0
- package/dist/server/index.d.ts +2 -0
- package/dist/server/index.js +1 -0
- package/dist/sessions/cookies.d.ts +4 -1
- package/dist/sessions/cookies.js +17 -4
- package/dist/sessions/crypto.js +6 -0
- package/dist/testing/index.d.ts +13 -0
- package/dist/testing/index.js +24 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/ws/client.d.ts +6 -0
- package/dist/ws/client.js +46 -10
- package/dist/ws/server.d.ts +4 -0
- package/dist/ws/server.js +35 -14
- package/package.json +31 -4
- package/dist/api/runtime.d.ts.map +0 -1
- package/dist/api/runtime.js.map +0 -1
- package/dist/auth/client.d.ts.map +0 -1
- package/dist/auth/client.js.map +0 -1
- package/dist/auth/index.d.ts.map +0 -1
- package/dist/auth/index.js.map +0 -1
- package/dist/auth/server.d.ts.map +0 -1
- package/dist/auth/server.js.map +0 -1
- package/dist/auth/types.d.ts.map +0 -1
- package/dist/auth/types.js.map +0 -1
- package/dist/cli/index.d.ts.map +0 -1
- package/dist/cli/index.js.map +0 -1
- package/dist/cli/project-commands.d.ts.map +0 -1
- package/dist/cli/project-commands.js.map +0 -1
- package/dist/compiler/build.d.ts.map +0 -1
- package/dist/compiler/build.js.map +0 -1
- package/dist/compiler/index.d.ts.map +0 -1
- package/dist/compiler/index.js.map +0 -1
- package/dist/compiler/scanner.d.ts.map +0 -1
- package/dist/compiler/scanner.js.map +0 -1
- package/dist/compiler/type-generation.d.ts.map +0 -1
- package/dist/compiler/type-generation.js.map +0 -1
- package/dist/compiler/write-manifests.d.ts.map +0 -1
- package/dist/compiler/write-manifests.js.map +0 -1
- package/dist/config/defaults.d.ts.map +0 -1
- package/dist/config/defaults.js.map +0 -1
- package/dist/config/index.d.ts.map +0 -1
- package/dist/config/index.js.map +0 -1
- package/dist/config/loader.d.ts.map +0 -1
- package/dist/config/loader.js.map +0 -1
- package/dist/config/project-root.d.ts.map +0 -1
- package/dist/config/project-root.js.map +0 -1
- package/dist/config/types.d.ts.map +0 -1
- package/dist/config/types.js.map +0 -1
- package/dist/discord/events.d.ts.map +0 -1
- package/dist/discord/events.js.map +0 -1
- package/dist/discord/index.d.ts.map +0 -1
- package/dist/discord/index.js.map +0 -1
- package/dist/discord/runtime.d.ts.map +0 -1
- package/dist/discord/runtime.js.map +0 -1
- package/dist/discord/safe-area.d.ts.map +0 -1
- package/dist/discord/safe-area.js.map +0 -1
- package/dist/discord/testing.d.ts.map +0 -1
- package/dist/discord/testing.js.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/manifests/types.d.ts.map +0 -1
- package/dist/manifests/types.js.map +0 -1
- package/dist/navigation/index.d.ts.map +0 -1
- package/dist/navigation/index.js.map +0 -1
- package/dist/router/match.d.ts.map +0 -1
- package/dist/router/match.js.map +0 -1
- package/dist/runtime/client/embed-router.d.ts.map +0 -1
- package/dist/runtime/client/embed-router.js.map +0 -1
- package/dist/runtime/client/minimize-card.d.ts.map +0 -1
- package/dist/runtime/client/minimize-card.js.map +0 -1
- package/dist/runtime/client/minimize.d.ts.map +0 -1
- package/dist/runtime/client/minimize.js.map +0 -1
- package/dist/runtime/index.d.ts.map +0 -1
- package/dist/runtime/index.js.map +0 -1
- package/dist/runtime/server/dev-server.d.ts.map +0 -1
- package/dist/runtime/server/dev-server.js.map +0 -1
- package/dist/runtime/server/production-server.d.ts.map +0 -1
- package/dist/runtime/server/production-server.js.map +0 -1
- package/dist/security/discord.d.ts.map +0 -1
- package/dist/security/discord.js.map +0 -1
- package/dist/security/index.d.ts.map +0 -1
- package/dist/security/index.js.map +0 -1
- package/dist/server/index.d.ts.map +0 -1
- package/dist/server/index.js.map +0 -1
- package/dist/server/session.d.ts.map +0 -1
- package/dist/server/session.js.map +0 -1
- package/dist/server/types.d.ts.map +0 -1
- package/dist/server/types.js.map +0 -1
- package/dist/sessions/cookies.d.ts.map +0 -1
- package/dist/sessions/cookies.js.map +0 -1
- package/dist/sessions/crypto.d.ts.map +0 -1
- package/dist/sessions/crypto.js.map +0 -1
- package/dist/shared/errors.d.ts.map +0 -1
- package/dist/shared/errors.js.map +0 -1
- package/dist/testing/index.d.ts.map +0 -1
- package/dist/testing/index.js.map +0 -1
- package/dist/version.d.ts.map +0 -1
- package/dist/version.js.map +0 -1
- package/dist/ws/client.d.ts.map +0 -1
- package/dist/ws/client.js.map +0 -1
- package/dist/ws/index.d.ts.map +0 -1
- package/dist/ws/index.js.map +0 -1
- package/dist/ws/server.d.ts.map +0 -1
- package/dist/ws/server.js.map +0 -1
package/dist/auth/server.js
CHANGED
|
@@ -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", (
|
|
42
|
-
|
|
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
|
-
|
|
141
|
-
|
|
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
|
-
|
|
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"
|
|
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
|
|
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:
|
|
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", (
|
|
247
|
-
response.setHeader("Set-Cookie", clearCookie(
|
|
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
|
package/dist/auth/types.d.ts
CHANGED
|
@@ -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 {
|
|
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
|
-
|
|
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
|
-
|
|
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,
|
|
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 =
|
|
53
|
+
const [nodeMajor = 0, nodeMinor = 0] = process.versions.node.split(".").map(Number);
|
|
73
54
|
diagnostics.push({
|
|
74
|
-
level: nodeMajor
|
|
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
|
|
103
|
+
level: !process.env.LUDICORD_DISCORD_CLIENT_SECRET?.trim() ? "error" : "ok",
|
|
123
104
|
message: "Discord Client Secret",
|
|
124
|
-
...(process.env.LUDICORD_DISCORD_CLIENT_SECRET
|
|
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
|
|
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
|
|
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:
|
|
174
|
-
message:
|
|
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
|
-
|
|
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) {
|