ludicord 3.0.0 → 3.1.0
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/LICENSE +21 -0
- package/README.md +4 -4
- package/dist/activity/shared-state.d.ts +1 -0
- package/dist/activity/shared-state.js +22 -1
- package/dist/activity/storage.d.ts +1 -1
- package/dist/activity/storage.js +5 -1
- package/dist/api/runtime.js +7 -1
- package/dist/auth/client.d.ts +2 -0
- package/dist/auth/client.js +89 -24
- package/dist/auth/index.d.ts +2 -1
- package/dist/auth/index.js +2 -1
- package/dist/auth/server.d.ts +4 -1
- package/dist/auth/server.js +123 -63
- package/dist/auth/types.d.ts +1 -1
- package/dist/cli/index.js +3 -0
- package/dist/compiler/build.d.ts +4 -2
- package/dist/compiler/build.js +23 -2
- package/dist/compiler/client-entry.js +2 -1
- package/dist/config/defaults.js +19 -3
- package/dist/config/types.d.ts +21 -2
- package/dist/discord/events.js +9 -4
- package/dist/lint/index.js +1 -1
- package/dist/runtime/client/dev-panel.js +28 -11
- package/dist/runtime/client/embed-router.js +1 -1
- package/dist/runtime/index.d.ts +1 -1
- package/dist/runtime/server/dev-server.d.ts +18 -0
- package/dist/runtime/server/dev-server.js +165 -21
- package/dist/runtime/server/index.d.ts +1 -1
- package/dist/runtime/server/production-server.d.ts +4 -0
- package/dist/runtime/server/production-server.js +29 -0
- package/dist/security/discord.js +8 -1
- package/dist/server/index.d.ts +2 -0
- package/dist/server/index.js +1 -0
- package/dist/server/request-security.d.ts +5 -0
- package/dist/server/request-security.js +81 -0
- package/dist/server/session.js +3 -1
- package/dist/sessions/cookies.d.ts +5 -1
- package/dist/sessions/cookies.js +13 -5
- package/dist/sessions/ephemeral-store.d.ts +15 -0
- package/dist/sessions/ephemeral-store.js +39 -0
- package/dist/sessions/launch.d.ts +7 -0
- package/dist/sessions/launch.js +68 -0
- package/dist/testing/index.d.ts +1 -1
- package/dist/testing/index.js +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/ws/adapter.d.ts +23 -0
- package/dist/ws/adapter.js +1 -0
- package/dist/ws/client.d.ts +13 -1
- package/dist/ws/client.js +105 -6
- package/dist/ws/index.d.ts +5 -4
- package/dist/ws/index.js +1 -1
- package/dist/ws/server.d.ts +36 -3
- package/dist/ws/server.js +287 -41
- package/dist/ws/shared-state.d.ts +17 -0
- package/dist/ws/shared-state.js +72 -35
- package/package.json +1 -6
package/dist/auth/server.js
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import { randomBytes } from "node:crypto";
|
|
2
2
|
import express from "express";
|
|
3
|
-
import { OAUTH_STATE_COOKIE, PENDING_SESSION_COOKIE, SESSION_COOKIE, clearCookie, parseCookies, parseSessionCookie, serializeSessionCookie, serializeStateCookie, } from "../sessions/cookies.js";
|
|
3
|
+
import { OAUTH_STATE_COOKIE, PENDING_SESSION_COOKIE, SESSION_COOKIE, clearCookie, parseCookies, parseSessionCookie, scopedCookieName, serializePendingSessionCookie, serializeSessionCookie, serializeStateCookie, } from "../sessions/cookies.js";
|
|
4
|
+
import { LUDICORD_LAUNCH_HEADER, normalizeLudicordLaunchId } from "../sessions/launch.js";
|
|
4
5
|
import { safeEqual, sealLudicordSession, unsealLudicordSession } from "../sessions/crypto.js";
|
|
5
6
|
import { verifyDiscordActivityInstance } from "../security/discord.js";
|
|
6
7
|
import { createDiscordRest, LudicordDiscordRestError } from "../server/discord-rest.js";
|
|
7
8
|
import { createMemorySessionDataStore } from "../sessions/data-store.js";
|
|
9
|
+
import { createMemoryEphemeralTokenStore } from "../sessions/ephemeral-store.js";
|
|
8
10
|
import { discordGuildIconUrl, discordUserAvatarUrl } from "../discord/assets.js";
|
|
9
11
|
function compactSession(session, dataId) {
|
|
10
12
|
const { raw: _userRaw, ...user } = session.user;
|
|
@@ -63,6 +65,13 @@ function secureRequest(request) {
|
|
|
63
65
|
: forwardedProtocol?.split(",", 1)[0]?.trim();
|
|
64
66
|
return protocol === "https" || request.protocol === "https";
|
|
65
67
|
}
|
|
68
|
+
function requestLaunchId(request) {
|
|
69
|
+
return normalizeLudicordLaunchId(request.get(LUDICORD_LAUNCH_HEADER));
|
|
70
|
+
}
|
|
71
|
+
function requestLaunchOptions(request) {
|
|
72
|
+
const launchId = requestLaunchId(request);
|
|
73
|
+
return launchId === undefined ? {} : { launchId };
|
|
74
|
+
}
|
|
66
75
|
export function createLudicordAuthRouter(options = {}) {
|
|
67
76
|
const router = express.Router();
|
|
68
77
|
const production = options.production ?? process.env.NODE_ENV === "production";
|
|
@@ -71,20 +80,37 @@ export function createLudicordAuthRouter(options = {}) {
|
|
|
71
80
|
const sessionSecret = options.sessionSecret ?? process.env.LUDICORD_SESSION_SECRET;
|
|
72
81
|
const fetchImplementation = options.fetch ?? globalThis.fetch;
|
|
73
82
|
const now = options.now ?? Date.now;
|
|
74
|
-
const verifyActivityInstance = options.activityInstanceVerification ?? false;
|
|
75
83
|
const botToken = options.botToken ?? process.env.LUDICORD_DISCORD_BOT_TOKEN;
|
|
84
|
+
const verificationMode = options.activityInstanceVerification ?? "auto";
|
|
85
|
+
const verifyActivityInstance = verificationMode === "auto"
|
|
86
|
+
? botToken !== undefined && botToken !== ""
|
|
87
|
+
: verificationMode;
|
|
76
88
|
const rest = createDiscordRest({ ...(botToken === undefined ? {} : { botToken }), fetch: fetchImplementation });
|
|
77
89
|
const sessionDataStore = options.sessionDataStore ?? createMemorySessionDataStore({ now });
|
|
78
|
-
const
|
|
79
|
-
const
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
90
|
+
const ephemeralTokenStore = options.ephemeralTokenStore ?? createMemoryEphemeralTokenStore({ now });
|
|
91
|
+
const clearEphemeralTokens = async (request) => {
|
|
92
|
+
const launchId = requestLaunchId(request);
|
|
93
|
+
const cookies = parseCookies(request.headers.cookie);
|
|
94
|
+
const state = cookies[scopedCookieName(OAUTH_STATE_COOKIE, launchId)];
|
|
95
|
+
if (state !== undefined)
|
|
96
|
+
await ephemeralTokenStore.delete(`oauth-state:${state}`);
|
|
97
|
+
const pendingValue = cookies[scopedCookieName(PENDING_SESSION_COOKIE, launchId)];
|
|
98
|
+
const pending = pendingValue === undefined || sessionSecret === undefined
|
|
99
|
+
? null
|
|
100
|
+
: unsealLudicordSession(pendingValue, sessionSecret);
|
|
101
|
+
if (pending?.completionToken !== undefined) {
|
|
102
|
+
await ephemeralTokenStore.delete(`oauth-completion:${pending.completionToken}`);
|
|
103
|
+
}
|
|
87
104
|
};
|
|
105
|
+
const verifyInstance = (applicationId, instanceId, token, userId) => verifyDiscordActivityInstance({
|
|
106
|
+
applicationId,
|
|
107
|
+
instanceId,
|
|
108
|
+
botToken: token,
|
|
109
|
+
...(userId === undefined ? {} : { userId }),
|
|
110
|
+
fetch: fetchImplementation,
|
|
111
|
+
now: now(),
|
|
112
|
+
...(options.activityInstanceCacheTtlMs === undefined ? {} : { cacheTtlMs: options.activityInstanceCacheTtlMs }),
|
|
113
|
+
});
|
|
88
114
|
router.use(express.json({ limit: "64kb" }));
|
|
89
115
|
router.get("/dev-login", async (request, response) => {
|
|
90
116
|
const address = request.socket.remoteAddress;
|
|
@@ -94,36 +120,59 @@ export function createLudicordAuthRouter(options = {}) {
|
|
|
94
120
|
response.status(404).json({ authenticated: false });
|
|
95
121
|
return;
|
|
96
122
|
}
|
|
97
|
-
const
|
|
123
|
+
const developmentValue = (name, fallback) => {
|
|
124
|
+
const value = process.env[name]?.trim();
|
|
125
|
+
return value === undefined || value === "" ? fallback : value.slice(0, 128);
|
|
126
|
+
};
|
|
127
|
+
const optionalDevelopmentValue = (name) => {
|
|
128
|
+
const value = process.env[name]?.trim();
|
|
129
|
+
return value === undefined || value === "" ? undefined : value.slice(0, 128);
|
|
130
|
+
};
|
|
131
|
+
const issuedAt = now();
|
|
132
|
+
const userId = developmentValue("LUDICORD_DEV_USER_ID", "local-development-user");
|
|
133
|
+
const username = developmentValue("LUDICORD_DEV_USERNAME", "local_player");
|
|
134
|
+
const displayName = developmentValue("LUDICORD_DEV_DISPLAY_NAME", "Local Player");
|
|
135
|
+
const instanceId = developmentValue("LUDICORD_DEV_INSTANCE_ID", "local-development-instance");
|
|
136
|
+
const guildId = optionalDevelopmentValue("LUDICORD_DEV_GUILD_ID");
|
|
137
|
+
const channelId = optionalDevelopmentValue("LUDICORD_DEV_CHANNEL_ID");
|
|
138
|
+
const scopes = (process.env.LUDICORD_DEV_SCOPES ?? "identify")
|
|
139
|
+
.split(/[\s,]+/)
|
|
140
|
+
.map((scope) => scope.trim())
|
|
141
|
+
.filter((scope, index, values) => scope !== "" && values.indexOf(scope) === index)
|
|
142
|
+
.slice(0, 64);
|
|
98
143
|
const session = {
|
|
99
144
|
authenticated: true,
|
|
100
145
|
kind: "development",
|
|
101
146
|
user: {
|
|
102
|
-
id:
|
|
103
|
-
username
|
|
104
|
-
displayName
|
|
147
|
+
id: userId,
|
|
148
|
+
username,
|
|
149
|
+
displayName,
|
|
105
150
|
avatar: null,
|
|
106
|
-
raw: { id:
|
|
151
|
+
raw: { id: userId, username, global_name: displayName, avatar: null },
|
|
107
152
|
},
|
|
108
153
|
applicationId: clientId,
|
|
109
|
-
instanceId
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
154
|
+
instanceId,
|
|
155
|
+
...(guildId === undefined ? {} : { guildId }),
|
|
156
|
+
...(channelId === undefined ? {} : { channelId }),
|
|
157
|
+
scopes: scopes.length === 0 ? ["identify"] : scopes,
|
|
158
|
+
issuedAt,
|
|
159
|
+
expiresAt: issuedAt + 3_600_000,
|
|
113
160
|
};
|
|
114
161
|
const dataId = randomBytes(24).toString("base64url");
|
|
115
162
|
await sessionDataStore.set(dataId, extendedSessionData(session), session.expiresAt);
|
|
116
|
-
|
|
163
|
+
const launchId = requestLaunchId(request);
|
|
164
|
+
response.setHeader("Set-Cookie", serializeSessionCookie(sealLudicordSession(compactSession(session, dataId), sessionSecret), { production: false, maxAgeSeconds: 3600, ...(launchId === undefined ? {} : { launchId }) }));
|
|
117
165
|
response.json(session);
|
|
118
166
|
});
|
|
119
|
-
router.get("/state", (request, response) => {
|
|
167
|
+
router.get("/state", async (request, response) => {
|
|
120
168
|
if (clientId === undefined || clientSecret === undefined || sessionSecret === undefined) {
|
|
121
169
|
unavailable(response);
|
|
122
170
|
return;
|
|
123
171
|
}
|
|
124
172
|
const state = randomBytes(32).toString("base64url");
|
|
125
|
-
|
|
126
|
-
|
|
173
|
+
const launchId = requestLaunchId(request);
|
|
174
|
+
await ephemeralTokenStore.set(`oauth-state:${state}`, now() + 300_000);
|
|
175
|
+
response.setHeader("Set-Cookie", serializeStateCookie(state, { production: production || secureRequest(request), ...(launchId === undefined ? {} : { launchId }) }));
|
|
127
176
|
response.json({ state });
|
|
128
177
|
});
|
|
129
178
|
router.post("/exchange", async (request, response) => {
|
|
@@ -134,18 +183,25 @@ export function createLudicordAuthRouter(options = {}) {
|
|
|
134
183
|
const body = (request.body ?? {});
|
|
135
184
|
const code = optionalString(body.code);
|
|
136
185
|
const state = optionalString(body.state);
|
|
137
|
-
const
|
|
186
|
+
const launchId = requestLaunchId(request);
|
|
187
|
+
const stateCookie = parseCookies(request.headers.cookie)[scopedCookieName(OAUTH_STATE_COOKIE, launchId)];
|
|
138
188
|
if (code === undefined ||
|
|
139
189
|
state === undefined ||
|
|
140
190
|
stateCookie === undefined ||
|
|
141
|
-
!safeEqual(state, stateCookie)
|
|
191
|
+
!safeEqual(state, stateCookie)) {
|
|
192
|
+
response.status(400).json({
|
|
193
|
+
error: "LUDICORD6003",
|
|
194
|
+
message: "Invalid OAuth code or state.",
|
|
195
|
+
});
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
if (!await ephemeralTokenStore.consume(`oauth-state:${state}`)) {
|
|
142
199
|
response.status(400).json({
|
|
143
200
|
error: "LUDICORD6003",
|
|
144
201
|
message: "Invalid OAuth code or state.",
|
|
145
202
|
});
|
|
146
203
|
return;
|
|
147
204
|
}
|
|
148
|
-
states.delete(state);
|
|
149
205
|
try {
|
|
150
206
|
const tokenResponse = await fetchImplementation("https://discord.com/api/oauth2/token", {
|
|
151
207
|
method: "POST",
|
|
@@ -215,25 +271,16 @@ export function createLudicordAuthRouter(options = {}) {
|
|
|
215
271
|
});
|
|
216
272
|
return;
|
|
217
273
|
}
|
|
218
|
-
const verification = await
|
|
219
|
-
applicationId: clientId,
|
|
220
|
-
instanceId,
|
|
221
|
-
botToken,
|
|
222
|
-
userId: user.id,
|
|
223
|
-
fetch: fetchImplementation,
|
|
224
|
-
now: now(),
|
|
225
|
-
...(options.activityInstanceCacheTtlMs === undefined
|
|
226
|
-
? {}
|
|
227
|
-
: { cacheTtlMs: options.activityInstanceCacheTtlMs }),
|
|
228
|
-
});
|
|
274
|
+
const verification = await verifyInstance(clientId, instanceId, botToken, user.id);
|
|
229
275
|
if (!verification.verified) {
|
|
276
|
+
if (verification.reason === "rate-limited") {
|
|
277
|
+
response.setHeader("Retry-After", String(Math.max(1, Math.ceil((verification.retryAfterMs ?? 1_000) / 1_000))));
|
|
278
|
+
}
|
|
230
279
|
response.status(verification.reason === "rate-limited" ? 429 : 401).json({
|
|
231
280
|
error: "LUDICORD6010",
|
|
232
281
|
message: "Discord Activity instance verification failed.",
|
|
233
282
|
reason: verification.reason,
|
|
234
|
-
|
|
235
|
-
? {}
|
|
236
|
-
: { retryAfterMs: verification.retryAfterMs }),
|
|
283
|
+
retryAfterMs: verification.retryAfterMs ?? (verification.reason === "unauthorized" ? 1_000 : 0),
|
|
237
284
|
});
|
|
238
285
|
return;
|
|
239
286
|
}
|
|
@@ -296,13 +343,14 @@ export function createLudicordAuthRouter(options = {}) {
|
|
|
296
343
|
const completionToken = randomBytes(32).toString("base64url");
|
|
297
344
|
const dataId = randomBytes(24).toString("base64url");
|
|
298
345
|
await sessionDataStore.set(dataId, extendedSessionData(session), issuedAt + 120_000);
|
|
299
|
-
|
|
346
|
+
await ephemeralTokenStore.set(`oauth-completion:${completionToken}`, now() + 120_000);
|
|
300
347
|
const sealed = sealLudicordSession({ ...compactSession(session, dataId), kind: "pending", completionToken, sessionExpiresAt: session.expiresAt, expiresAt: issuedAt + 120_000 }, sessionSecret);
|
|
301
|
-
response.append("Set-Cookie",
|
|
348
|
+
response.append("Set-Cookie", serializePendingSessionCookie(sealed, {
|
|
302
349
|
production: production || secureRequest(request),
|
|
303
350
|
maxAgeSeconds: 120,
|
|
304
|
-
|
|
305
|
-
|
|
351
|
+
...(launchId === undefined ? {} : { launchId }),
|
|
352
|
+
}));
|
|
353
|
+
response.append("Set-Cookie", clearCookie(OAUTH_STATE_COOKIE, production || secureRequest(request), launchId));
|
|
306
354
|
response.json({
|
|
307
355
|
access_token: token.access_token,
|
|
308
356
|
session,
|
|
@@ -318,15 +366,19 @@ export function createLudicordAuthRouter(options = {}) {
|
|
|
318
366
|
}
|
|
319
367
|
});
|
|
320
368
|
router.post("/complete", async (request, response) => {
|
|
321
|
-
const
|
|
369
|
+
const launchId = requestLaunchId(request);
|
|
370
|
+
const value = parseCookies(request.headers.cookie)[scopedCookieName(PENDING_SESSION_COOKIE, launchId)];
|
|
322
371
|
const token = optionalString(request.body?.completionToken);
|
|
323
372
|
const pending = value === undefined || sessionSecret === undefined ? null : unsealLudicordSession(value, sessionSecret);
|
|
324
373
|
if (pending?.kind !== "pending" || token === undefined || pending.completionToken === undefined ||
|
|
325
|
-
!safeEqual(token, pending.completionToken)
|
|
374
|
+
!safeEqual(token, pending.completionToken)) {
|
|
375
|
+
response.status(401).json({ error: "LUDICORD6009", message: "Login confirmation expired. Please retry." });
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
if (!await ephemeralTokenStore.consume(`oauth-completion:${token}`)) {
|
|
326
379
|
response.status(401).json({ error: "LUDICORD6009", message: "Login confirmation expired. Please retry." });
|
|
327
380
|
return;
|
|
328
381
|
}
|
|
329
|
-
completions.delete(token);
|
|
330
382
|
const { kind: _kind, completionToken: _token, sessionExpiresAt, ...identity } = pending;
|
|
331
383
|
const expiresAt = Math.min(now() + 3_600_000, sessionExpiresAt ?? pending.expiresAt);
|
|
332
384
|
const compact = { ...identity, expiresAt };
|
|
@@ -336,9 +388,9 @@ export function createLudicordAuthRouter(options = {}) {
|
|
|
336
388
|
await sessionDataStore.set(dataId, extendedSessionData(session), expiresAt);
|
|
337
389
|
}
|
|
338
390
|
response.append("Set-Cookie", serializeSessionCookie(sealLudicordSession(compact, sessionSecret), {
|
|
339
|
-
production: production || secureRequest(request), maxAgeSeconds: Math.max(0, Math.floor((expiresAt - now()) / 1000)),
|
|
391
|
+
production: production || secureRequest(request), maxAgeSeconds: Math.max(0, Math.floor((expiresAt - now()) / 1000)), ...(launchId === undefined ? {} : { launchId }),
|
|
340
392
|
}));
|
|
341
|
-
response.append("Set-Cookie", clearCookie(PENDING_SESSION_COOKIE, production || secureRequest(request)));
|
|
393
|
+
response.append("Set-Cookie", clearCookie(PENDING_SESSION_COOKIE, production || secureRequest(request), launchId));
|
|
342
394
|
response.json(session);
|
|
343
395
|
});
|
|
344
396
|
router.get("/session", async (request, response) => {
|
|
@@ -346,7 +398,7 @@ export function createLudicordAuthRouter(options = {}) {
|
|
|
346
398
|
unavailable(response);
|
|
347
399
|
return;
|
|
348
400
|
}
|
|
349
|
-
const session = parseSessionCookie(request.headers.cookie, sessionSecret, { allowDevelopment: !production });
|
|
401
|
+
const session = parseSessionCookie(request.headers.cookie, sessionSecret, { allowDevelopment: !production, ...requestLaunchOptions(request) });
|
|
350
402
|
if (session === null) {
|
|
351
403
|
response.status(401).json({ authenticated: false });
|
|
352
404
|
return;
|
|
@@ -354,17 +406,25 @@ export function createLudicordAuthRouter(options = {}) {
|
|
|
354
406
|
response.json(await hydrateSession(session, sessionDataStore));
|
|
355
407
|
});
|
|
356
408
|
router.post("/logout", async (request, response) => {
|
|
409
|
+
await clearEphemeralTokens(request);
|
|
357
410
|
if (sessionSecret !== undefined) {
|
|
358
|
-
const session = parseSessionCookie(request.headers.cookie, sessionSecret, { allowDevelopment: !production });
|
|
411
|
+
const session = parseSessionCookie(request.headers.cookie, sessionSecret, { allowDevelopment: !production, ...requestLaunchOptions(request) });
|
|
359
412
|
const id = session === null ? undefined : sessionDataId(session);
|
|
360
413
|
if (id !== undefined)
|
|
361
414
|
await sessionDataStore.delete(id);
|
|
362
415
|
}
|
|
363
|
-
|
|
416
|
+
const launchId = requestLaunchId(request);
|
|
417
|
+
response.setHeader("Set-Cookie", [SESSION_COOKIE, PENDING_SESSION_COOKIE, OAUTH_STATE_COOKIE].map((name) => clearCookie(name, production || secureRequest(request), launchId)));
|
|
418
|
+
response.status(204).end();
|
|
419
|
+
});
|
|
420
|
+
router.post("/cancel", async (request, response) => {
|
|
421
|
+
await clearEphemeralTokens(request);
|
|
422
|
+
const launchId = requestLaunchId(request);
|
|
423
|
+
response.setHeader("Set-Cookie", [PENDING_SESSION_COOKIE, OAUTH_STATE_COOKIE].map((name) => clearCookie(name, production || secureRequest(request), launchId)));
|
|
364
424
|
response.status(204).end();
|
|
365
425
|
});
|
|
366
426
|
router.get("/context", async (request, response) => {
|
|
367
|
-
const compact = sessionSecret === undefined ? null : parseSessionCookie(request.headers.cookie, sessionSecret);
|
|
427
|
+
const compact = sessionSecret === undefined ? null : parseSessionCookie(request.headers.cookie, sessionSecret, requestLaunchOptions(request));
|
|
368
428
|
if (!compact) {
|
|
369
429
|
response.status(401).json({ message: "Discord login is required." });
|
|
370
430
|
return;
|
|
@@ -375,7 +435,7 @@ export function createLudicordAuthRouter(options = {}) {
|
|
|
375
435
|
return;
|
|
376
436
|
}
|
|
377
437
|
try {
|
|
378
|
-
const verification = await
|
|
438
|
+
const verification = await verifyInstance(session.applicationId, session.instanceId, botToken, session.user.id);
|
|
379
439
|
if (!verification.verified) {
|
|
380
440
|
response.status(403).json({ message: "Activity membership could not be verified." });
|
|
381
441
|
return;
|
|
@@ -402,7 +462,7 @@ export function createLudicordAuthRouter(options = {}) {
|
|
|
402
462
|
}
|
|
403
463
|
});
|
|
404
464
|
router.get("/guild-channels", async (request, response) => {
|
|
405
|
-
const session = sessionSecret === undefined ? null : parseSessionCookie(request.headers.cookie, sessionSecret);
|
|
465
|
+
const session = sessionSecret === undefined ? null : parseSessionCookie(request.headers.cookie, sessionSecret, requestLaunchOptions(request));
|
|
406
466
|
if (!session) {
|
|
407
467
|
response.status(401).json({ message: "Discord login is required." });
|
|
408
468
|
return;
|
|
@@ -412,7 +472,7 @@ export function createLudicordAuthRouter(options = {}) {
|
|
|
412
472
|
return;
|
|
413
473
|
}
|
|
414
474
|
try {
|
|
415
|
-
const verified = await
|
|
475
|
+
const verified = await verifyInstance(session.applicationId, session.instanceId, botToken, session.user.id);
|
|
416
476
|
if (!verified.verified || !verified.instance.guildId) {
|
|
417
477
|
response.status(!verified.verified && verified.reason === "rate-limited" ? 429 : 403).json({ message: "The current user could not be verified in this guild Activity." });
|
|
418
478
|
return;
|
|
@@ -426,7 +486,7 @@ export function createLudicordAuthRouter(options = {}) {
|
|
|
426
486
|
}
|
|
427
487
|
});
|
|
428
488
|
router.get("/guild-roles", async (request, response) => {
|
|
429
|
-
const session = sessionSecret === undefined ? null : parseSessionCookie(request.headers.cookie, sessionSecret);
|
|
489
|
+
const session = sessionSecret === undefined ? null : parseSessionCookie(request.headers.cookie, sessionSecret, requestLaunchOptions(request));
|
|
430
490
|
if (!session) {
|
|
431
491
|
response.status(401).json({ message: "Discord login is required." });
|
|
432
492
|
return;
|
|
@@ -436,7 +496,7 @@ export function createLudicordAuthRouter(options = {}) {
|
|
|
436
496
|
return;
|
|
437
497
|
}
|
|
438
498
|
try {
|
|
439
|
-
const verified = await
|
|
499
|
+
const verified = await verifyInstance(session.applicationId, session.instanceId, botToken, session.user.id);
|
|
440
500
|
if (!verified.verified || !verified.instance.guildId) {
|
|
441
501
|
response.status(!verified.verified && verified.reason === "rate-limited" ? 429 : 403).json({ message: "The current user could not be verified in this guild Activity." });
|
|
442
502
|
return;
|
|
@@ -450,7 +510,7 @@ export function createLudicordAuthRouter(options = {}) {
|
|
|
450
510
|
}
|
|
451
511
|
});
|
|
452
512
|
router.get("/guild-member/:userId", async (request, response) => {
|
|
453
|
-
const session = sessionSecret === undefined ? null : parseSessionCookie(request.headers.cookie, sessionSecret);
|
|
513
|
+
const session = sessionSecret === undefined ? null : parseSessionCookie(request.headers.cookie, sessionSecret, requestLaunchOptions(request));
|
|
454
514
|
if (!session) {
|
|
455
515
|
response.status(401).json({ message: "Discord login is required." });
|
|
456
516
|
return;
|
|
@@ -465,7 +525,7 @@ export function createLudicordAuthRouter(options = {}) {
|
|
|
465
525
|
return;
|
|
466
526
|
}
|
|
467
527
|
try {
|
|
468
|
-
const verified = await
|
|
528
|
+
const verified = await verifyInstance(session.applicationId, session.instanceId, botToken, session.user.id);
|
|
469
529
|
if (!verified.verified || !verified.instance.guildId) {
|
|
470
530
|
response.status(!verified.verified && verified.reason === "rate-limited" ? 429 : 403).json({ message: "The current user could not be verified in this guild Activity." });
|
|
471
531
|
return;
|
|
@@ -479,7 +539,7 @@ export function createLudicordAuthRouter(options = {}) {
|
|
|
479
539
|
}
|
|
480
540
|
});
|
|
481
541
|
router.get("/guild-members", async (request, response) => {
|
|
482
|
-
const session = sessionSecret === undefined ? null : parseSessionCookie(request.headers.cookie, sessionSecret);
|
|
542
|
+
const session = sessionSecret === undefined ? null : parseSessionCookie(request.headers.cookie, sessionSecret, requestLaunchOptions(request));
|
|
483
543
|
if (session === null) {
|
|
484
544
|
response.status(401).json({ message: "Discord login is required." });
|
|
485
545
|
return;
|
|
@@ -493,7 +553,7 @@ export function createLudicordAuthRouter(options = {}) {
|
|
|
493
553
|
return;
|
|
494
554
|
}
|
|
495
555
|
try {
|
|
496
|
-
const verified = await
|
|
556
|
+
const verified = await verifyInstance(session.applicationId, session.instanceId, botToken, session.user.id);
|
|
497
557
|
if (!verified.verified || !verified.instance.guildId) {
|
|
498
558
|
response.status(!verified.verified && verified.reason === "rate-limited" ? 429 : 403).json({ message: "The current user could not be verified in this guild Activity." });
|
|
499
559
|
return;
|
package/dist/auth/types.d.ts
CHANGED
|
@@ -27,7 +27,7 @@ export interface LudicordSession {
|
|
|
27
27
|
readonly issuedAt: number;
|
|
28
28
|
readonly expiresAt: number;
|
|
29
29
|
}
|
|
30
|
-
export type LudicordAuthStatus = "idle" | "connecting" | "authorizing" | "authenticated" | "denied" | "error";
|
|
30
|
+
export type LudicordAuthStatus = "idle" | "connecting" | "authorizing" | "reauthenticating" | "authenticated" | "denied" | "error";
|
|
31
31
|
export interface LudicordAuthSnapshot {
|
|
32
32
|
readonly status: LudicordAuthStatus;
|
|
33
33
|
readonly session: LudicordSession | null;
|
package/dist/cli/index.js
CHANGED
package/dist/compiler/build.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { ResolvedLudicordConfig } from "../config/types.js";
|
|
2
2
|
import type { LudicordManifests } from "../manifests/types.js";
|
|
3
3
|
import type { LudicordBundleReport } from "./bundle-report.js";
|
|
4
|
-
export declare const LUDICORD_BUILD_SCHEMA_VERSION:
|
|
4
|
+
export declare const LUDICORD_BUILD_SCHEMA_VERSION: 3;
|
|
5
5
|
export interface RouteBundle {
|
|
6
6
|
readonly source: string;
|
|
7
7
|
readonly bundle: string;
|
|
@@ -22,7 +22,8 @@ export interface LudicordBuildMetadata {
|
|
|
22
22
|
readonly scopes: readonly string[];
|
|
23
23
|
readonly authRequired: boolean;
|
|
24
24
|
readonly proxyVerification: boolean;
|
|
25
|
-
readonly activityInstanceVerification: boolean;
|
|
25
|
+
readonly activityInstanceVerification: boolean | "auto";
|
|
26
|
+
readonly activityInstanceCacheTtlMs: number;
|
|
26
27
|
};
|
|
27
28
|
readonly activity: {
|
|
28
29
|
readonly defaultEmbed: string;
|
|
@@ -39,6 +40,7 @@ export interface LudicordBuildResult {
|
|
|
39
40
|
readonly manifests: LudicordManifests;
|
|
40
41
|
readonly metadata: LudicordBuildMetadata;
|
|
41
42
|
readonly bundleReport: LudicordBundleReport;
|
|
43
|
+
readonly warnings: readonly string[];
|
|
42
44
|
formatSummary(): string;
|
|
43
45
|
}
|
|
44
46
|
export declare function cleanupStaleBuildDirectories(projectRoot: string, now?: number): string[];
|
package/dist/compiler/build.js
CHANGED
|
@@ -17,9 +17,27 @@ import { checkProjectTypes } from "../runtime/server/diagnostics.js";
|
|
|
17
17
|
import { createBundleReport } from "./bundle-report.js";
|
|
18
18
|
const VIRTUAL_BUILD_ENTRY = "virtual:ludicord-production-entry";
|
|
19
19
|
const RESOLVED_BUILD_ENTRY = "\0virtual:ludicord-production-entry";
|
|
20
|
-
export const LUDICORD_BUILD_SCHEMA_VERSION =
|
|
20
|
+
export const LUDICORD_BUILD_SCHEMA_VERSION = 3;
|
|
21
21
|
const STALE_BUILD_DIRECTORY = /^\.ludicord-(?:build|previous)-\d+-[0-9a-f-]+$/i;
|
|
22
22
|
const STALE_BUILD_AGE_MS = 24 * 60 * 60 * 1_000;
|
|
23
|
+
function frameworkWarnings(config, manifests) {
|
|
24
|
+
const warnings = [];
|
|
25
|
+
if (config.discord.auth.required) {
|
|
26
|
+
if (config.discord.auth.activityInstanceVerification === false) {
|
|
27
|
+
warnings.push("Discord Activity instance verification is disabled. Browser-provided guild, channel, and instance identity is not authoritative.");
|
|
28
|
+
}
|
|
29
|
+
else if (config.discord.auth.activityInstanceVerification === "auto" && !process.env.LUDICORD_DISCORD_BOT_TOKEN) {
|
|
30
|
+
warnings.push("Discord Activity instance verification is inactive because LUDICORD_DISCORD_BOT_TOKEN is missing.");
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
if (config.server.allowedHosts === true) {
|
|
34
|
+
warnings.push("server.allowedHosts accepts every Host header. Configure the production Activity and tunnel hostnames explicitly.");
|
|
35
|
+
}
|
|
36
|
+
if (manifests.activity.proxy !== undefined && !config.discord.auth.proxyVerification) {
|
|
37
|
+
warnings.push("app/proxy.ts is enabled without Discord request-signature verification.");
|
|
38
|
+
}
|
|
39
|
+
return warnings;
|
|
40
|
+
}
|
|
23
41
|
function safeOutputDirectory(projectRoot) {
|
|
24
42
|
const output = path.resolve(projectRoot, ".ludicord");
|
|
25
43
|
if (path.dirname(output) !== path.resolve(projectRoot) || path.basename(output) !== ".ludicord") {
|
|
@@ -202,6 +220,7 @@ function buildMetadata(clientEntry, api, websocket, instrumentation, proxy, bund
|
|
|
202
220
|
authRequired: config.discord.auth.required,
|
|
203
221
|
proxyVerification: config.discord.auth.proxyVerification,
|
|
204
222
|
activityInstanceVerification: config.discord.auth.activityInstanceVerification,
|
|
223
|
+
activityInstanceCacheTtlMs: config.discord.auth.activityInstanceCacheTtlMs,
|
|
205
224
|
},
|
|
206
225
|
activity: {
|
|
207
226
|
defaultEmbed: config.activity.defaultEmbed,
|
|
@@ -222,6 +241,7 @@ export async function buildLudicordProject(projectRoot) {
|
|
|
222
241
|
const temporaryDirectory = temporaryBuildDirectory(root);
|
|
223
242
|
const manifests = generateManifests(root);
|
|
224
243
|
const { config } = await loadLudicordConfig(root);
|
|
244
|
+
const warnings = frameworkWarnings(config, manifests);
|
|
225
245
|
mkdirSync(temporaryDirectory, { recursive: true });
|
|
226
246
|
try {
|
|
227
247
|
generateLudicordTypes(root, manifests, config);
|
|
@@ -253,6 +273,7 @@ export async function buildLudicordProject(projectRoot) {
|
|
|
253
273
|
manifests,
|
|
254
274
|
metadata,
|
|
255
275
|
bundleReport,
|
|
276
|
+
warnings,
|
|
256
277
|
formatSummary() {
|
|
257
278
|
const routes = [
|
|
258
279
|
"/ Activity",
|
|
@@ -282,7 +303,7 @@ Route Type
|
|
|
282
303
|
────────────────────────────────────────
|
|
283
304
|
${routes.join("\n")}
|
|
284
305
|
|
|
285
|
-
✓ Build completed${bundleReport.warnings.length === 0 ? "" : `\n\nBundle warnings\n${bundleReport.warnings.map((warning) => `! ${warning}`).join("\n")}`}`;
|
|
306
|
+
✓ Build completed${warnings.length === 0 ? "" : `\n\nFramework warnings\n${warnings.map((warning) => `! ${warning}`).join("\n")}`}${bundleReport.warnings.length === 0 ? "" : `\n\nBundle warnings\n${bundleReport.warnings.map((warning) => `! ${warning}`).join("\n")}`}`;
|
|
286
307
|
},
|
|
287
308
|
};
|
|
288
309
|
}
|
|
@@ -4,7 +4,7 @@ import { LUDICORD_VERSION } from "../version.js";
|
|
|
4
4
|
export function clientEntry(root, manifests, config, development) {
|
|
5
5
|
const file = (relative) => `${development ? "/@fs/" : ""}${normalizePath(path.join(root, relative))}`;
|
|
6
6
|
const imports = [`import React from "react";`, `import { createRoot } from "react-dom/client";`,
|
|
7
|
-
`import { LudicordRoot } from "ludicord/internal";`, `import Pages from ${JSON.stringify(file(manifests.activity.root))};`];
|
|
7
|
+
`import { LudicordRoot } from "ludicord/internal";`, `import { installLudicordLaunchIsolation } from "ludicord/auth";`, `import Pages from ${JSON.stringify(file(manifests.activity.root))};`];
|
|
8
8
|
const components = [];
|
|
9
9
|
let metadata = "";
|
|
10
10
|
if (manifests.activity.metadata !== undefined) {
|
|
@@ -50,6 +50,7 @@ export function clientEntry(root, manifests, config, development) {
|
|
|
50
50
|
return `${imports.join("\n")}
|
|
51
51
|
globalThis.__LUDICORD_PUBLIC_CONFIG__ = ${JSON.stringify(publicConfig)};
|
|
52
52
|
globalThis.__LUDICORD_EMBEDS__ = {${embedDefinitions.join(",\n")}};
|
|
53
|
+
installLudicordLaunchIsolation();
|
|
53
54
|
const container = document.getElementById("ludicord-root");
|
|
54
55
|
if (!container) throw new Error("LUDICORD2003: Missing #ludicord-root container.");
|
|
55
56
|
const root = createRoot(container);
|
package/dist/config/defaults.js
CHANGED
|
@@ -8,7 +8,8 @@ export function resolveConfig(config = {}) {
|
|
|
8
8
|
required: config.discord?.auth?.required ?? true,
|
|
9
9
|
session: config.discord?.auth?.session ?? "encrypted-cookie",
|
|
10
10
|
proxyVerification: config.discord?.auth?.proxyVerification ?? false,
|
|
11
|
-
activityInstanceVerification: config.discord?.auth?.activityInstanceVerification ??
|
|
11
|
+
activityInstanceVerification: config.discord?.auth?.activityInstanceVerification ?? "auto",
|
|
12
|
+
activityInstanceCacheTtlMs: config.discord?.auth?.activityInstanceCacheTtlMs ?? 30_000,
|
|
12
13
|
},
|
|
13
14
|
},
|
|
14
15
|
activity: {
|
|
@@ -25,6 +26,7 @@ export function resolveConfig(config = {}) {
|
|
|
25
26
|
port: config.server?.port ?? 3000,
|
|
26
27
|
host: config.server?.host ?? "0.0.0.0",
|
|
27
28
|
allowedHosts: config.server?.allowedHosts ?? true,
|
|
29
|
+
allowedOrigins: config.server?.allowedOrigins ?? "same-origin",
|
|
28
30
|
limits: {
|
|
29
31
|
body: config.server?.limits?.body ?? "2mb",
|
|
30
32
|
},
|
|
@@ -34,9 +36,13 @@ export function resolveConfig(config = {}) {
|
|
|
34
36
|
websocket: {
|
|
35
37
|
enabled: config.websocket?.enabled ?? true,
|
|
36
38
|
heartbeatInterval: config.websocket?.heartbeatInterval ?? 30_000,
|
|
37
|
-
maxPayload: config.websocket?.maxPayload ??
|
|
39
|
+
maxPayload: config.websocket?.maxPayload ?? 262_144,
|
|
38
40
|
compression: config.websocket?.compression ?? false,
|
|
39
41
|
maxMessagesPerSecond: config.websocket?.maxMessagesPerSecond ?? 120,
|
|
42
|
+
maxBytesPerSecond: config.websocket?.maxBytesPerSecond ?? 524_288,
|
|
43
|
+
backpressureLimit: config.websocket?.backpressureLimit ?? 524_288,
|
|
44
|
+
backpressureStrategy: config.websocket?.backpressureStrategy ?? "queue-latest",
|
|
45
|
+
maxQueuedMessages: config.websocket?.maxQueuedMessages ?? 64,
|
|
40
46
|
reconnect: {
|
|
41
47
|
enabled: config.websocket?.reconnect?.enabled ?? true,
|
|
42
48
|
attempts: config.websocket?.reconnect?.attempts ?? 10,
|
|
@@ -54,7 +60,11 @@ export function resolveConfig(config = {}) {
|
|
|
54
60
|
integer(resolved.server.requestTimeout, 1, 900_000, "server.requestTimeout");
|
|
55
61
|
integer(resolved.server.shutdownTimeout, 100, 120_000, "server.shutdownTimeout");
|
|
56
62
|
integer(resolved.build.clientAssetWarningLimit, 1_024, 100_000_000, "build.clientAssetWarningLimit");
|
|
63
|
+
integer(resolved.discord.auth.activityInstanceCacheTtlMs, 0, 30_000, "discord.auth.activityInstanceCacheTtlMs");
|
|
57
64
|
integer(resolved.websocket.maxMessagesPerSecond, 1, 10_000, "websocket.maxMessagesPerSecond");
|
|
65
|
+
integer(resolved.websocket.maxBytesPerSecond, 1_024, 1_073_741_824, "websocket.maxBytesPerSecond");
|
|
66
|
+
integer(resolved.websocket.backpressureLimit, 1_024, 1_073_741_824, "websocket.backpressureLimit");
|
|
67
|
+
integer(resolved.websocket.maxQueuedMessages, 1, 10_000, "websocket.maxQueuedMessages");
|
|
58
68
|
integer(resolved.websocket.reconnect.attempts, 0, 10000, "websocket.reconnect.attempts");
|
|
59
69
|
integer(resolved.websocket.reconnect.initialDelay, 0, 2_147_483_647, "websocket.reconnect.initialDelay");
|
|
60
70
|
integer(resolved.websocket.reconnect.maxDelay, resolved.websocket.reconnect.initialDelay, 2_147_483_647, "websocket.reconnect.maxDelay");
|
|
@@ -66,11 +76,17 @@ export function resolveConfig(config = {}) {
|
|
|
66
76
|
fail("server.host");
|
|
67
77
|
if (resolved.server.allowedHosts !== true && (!Array.isArray(resolved.server.allowedHosts) || resolved.server.allowedHosts.some((host) => typeof host !== "string" || !host.trim())))
|
|
68
78
|
fail("server.allowedHosts");
|
|
79
|
+
if (resolved.server.allowedOrigins !== true && resolved.server.allowedOrigins !== "same-origin" && (!Array.isArray(resolved.server.allowedOrigins) || resolved.server.allowedOrigins.some((origin) => typeof origin !== "string" || !/^https?:\/\//.test(origin))))
|
|
80
|
+
fail("server.allowedOrigins");
|
|
69
81
|
if (resolved.discord.auth.session !== "encrypted-cookie")
|
|
70
82
|
fail("discord.auth.session");
|
|
83
|
+
if (!["queue-latest", "close"].includes(resolved.websocket.backpressureStrategy))
|
|
84
|
+
fail("websocket.backpressureStrategy");
|
|
71
85
|
if (!Array.isArray(resolved.discord.scopes) || resolved.discord.scopes.some((scope) => typeof scope !== "string" || !scope.trim()))
|
|
72
86
|
fail("discord.scopes");
|
|
73
|
-
|
|
87
|
+
if (resolved.discord.auth.activityInstanceVerification !== "auto" && typeof resolved.discord.auth.activityInstanceVerification !== "boolean")
|
|
88
|
+
fail("discord.auth.activityInstanceVerification");
|
|
89
|
+
for (const [field, value] of Object.entries({ "discord.auth.required": resolved.discord.auth.required, "discord.auth.proxyVerification": resolved.discord.auth.proxyVerification, "react.strictMode": resolved.react.strictMode, "websocket.enabled": resolved.websocket.enabled, "websocket.compression": resolved.websocket.compression, "websocket.reconnect.enabled": resolved.websocket.reconnect.enabled })) {
|
|
74
90
|
if (typeof value !== "boolean")
|
|
75
91
|
fail(field);
|
|
76
92
|
}
|
package/dist/config/types.d.ts
CHANGED
|
@@ -3,7 +3,10 @@ export interface LudicordAuthConfig {
|
|
|
3
3
|
required?: boolean;
|
|
4
4
|
session?: "encrypted-cookie";
|
|
5
5
|
proxyVerification?: boolean;
|
|
6
|
-
|
|
6
|
+
/** `auto` verifies Activity identity whenever a server bot token is available. */
|
|
7
|
+
activityInstanceVerification?: boolean | "auto";
|
|
8
|
+
/** Success-cache lifetime for Discord Activity Instance lookups. */
|
|
9
|
+
activityInstanceCacheTtlMs?: number;
|
|
7
10
|
}
|
|
8
11
|
export interface LudicordDiscordConfig {
|
|
9
12
|
clientId?: string;
|
|
@@ -29,6 +32,8 @@ export interface LudicordServerConfig {
|
|
|
29
32
|
port?: number;
|
|
30
33
|
host?: string;
|
|
31
34
|
allowedHosts?: true | readonly string[];
|
|
35
|
+
/** Browser origins allowed to call framework routes. Defaults to same-origin. */
|
|
36
|
+
allowedOrigins?: true | "same-origin" | readonly string[];
|
|
32
37
|
limits?: LudicordServerLimits;
|
|
33
38
|
/** Maximum duration of an API route handler in milliseconds. */
|
|
34
39
|
requestTimeout?: number;
|
|
@@ -48,6 +53,14 @@ export interface LudicordWebSocketConfig {
|
|
|
48
53
|
compression?: boolean;
|
|
49
54
|
/** Per-client inbound event limit for each one-second window. */
|
|
50
55
|
maxMessagesPerSecond?: number;
|
|
56
|
+
/** Per-client inbound byte limit for each one-second window. */
|
|
57
|
+
maxBytesPerSecond?: number;
|
|
58
|
+
/** Buffered bytes allowed before outbound messages are queued. */
|
|
59
|
+
backpressureLimit?: number;
|
|
60
|
+
/** Behavior when an outbound socket is temporarily slow. */
|
|
61
|
+
backpressureStrategy?: "queue-latest" | "close";
|
|
62
|
+
/** Maximum coalesced outbound messages retained for a slow client. */
|
|
63
|
+
maxQueuedMessages?: number;
|
|
51
64
|
reconnect?: LudicordReconnectConfig;
|
|
52
65
|
}
|
|
53
66
|
export interface LudicordConfig {
|
|
@@ -66,7 +79,8 @@ export interface ResolvedLudicordConfig {
|
|
|
66
79
|
required: boolean;
|
|
67
80
|
session: "encrypted-cookie";
|
|
68
81
|
proxyVerification: boolean;
|
|
69
|
-
activityInstanceVerification: boolean;
|
|
82
|
+
activityInstanceVerification: boolean | "auto";
|
|
83
|
+
activityInstanceCacheTtlMs: number;
|
|
70
84
|
};
|
|
71
85
|
};
|
|
72
86
|
activity: {
|
|
@@ -83,6 +97,7 @@ export interface ResolvedLudicordConfig {
|
|
|
83
97
|
port: number;
|
|
84
98
|
host: string;
|
|
85
99
|
allowedHosts: true | readonly string[];
|
|
100
|
+
allowedOrigins: true | "same-origin" | readonly string[];
|
|
86
101
|
limits: {
|
|
87
102
|
body: string;
|
|
88
103
|
};
|
|
@@ -95,6 +110,10 @@ export interface ResolvedLudicordConfig {
|
|
|
95
110
|
maxPayload: number;
|
|
96
111
|
compression: boolean;
|
|
97
112
|
maxMessagesPerSecond: number;
|
|
113
|
+
maxBytesPerSecond: number;
|
|
114
|
+
backpressureLimit: number;
|
|
115
|
+
backpressureStrategy: "queue-latest" | "close";
|
|
116
|
+
maxQueuedMessages: number;
|
|
98
117
|
reconnect: {
|
|
99
118
|
enabled: boolean;
|
|
100
119
|
attempts: number;
|