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/README.md
CHANGED
|
@@ -1,4 +1,16 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<a href="https://github.com/mrcholer/ludicord"><img src="https://raw.githubusercontent.com/mrcholer/ludicord/main/.github/assets/ludicord-banner.png" alt="Ludicord" width="900" /></a>
|
|
3
|
+
</p>
|
|
4
|
+
|
|
5
|
+
<h1 align="center">ludicord</h1>
|
|
6
|
+
|
|
7
|
+
<p align="center">
|
|
8
|
+
<a href="https://www.npmjs.com/package/ludicord"><img alt="npm version" src="https://img.shields.io/npm/v/ludicord?style=flat-square&color=5865F2" /></a>
|
|
9
|
+
<a href="https://www.npmjs.com/package/ludicord"><img alt="npm downloads" src="https://img.shields.io/npm/dm/ludicord?style=flat-square&color=00B0F4" /></a>
|
|
10
|
+
<img alt="Node.js 20.19 or newer" src="https://img.shields.io/badge/node-%3E%3D20.19-339933?style=flat-square&logo=nodedotjs&logoColor=white" />
|
|
11
|
+
<img alt="React 18.3 and 19" src="https://img.shields.io/badge/react-18.3%20%7C%2019-61DAFB?style=flat-square&logo=react&logoColor=111" />
|
|
12
|
+
<a href="https://github.com/mrcholer/ludicord/blob/main/SECURITY.md"><img alt="Security policy" src="https://img.shields.io/badge/security-policy-6D5DFC?style=flat-square" /></a>
|
|
13
|
+
</p>
|
|
2
14
|
|
|
3
15
|
The full-stack React framework and CLI for Discord Activities.
|
|
4
16
|
|
|
@@ -6,12 +18,14 @@ The full-stack React framework and CLI for Discord Activities.
|
|
|
6
18
|
ludicord dev
|
|
7
19
|
ludicord build
|
|
8
20
|
ludicord start
|
|
9
|
-
ludicord routes
|
|
10
|
-
ludicord doctor
|
|
11
|
-
ludicord info
|
|
12
|
-
ludicord clean
|
|
13
21
|
```
|
|
14
22
|
|
|
15
|
-
Public entry points include `ludicord`, `ludicord/config`, `ludicord/navigation`, `ludicord/discord`, `ludicord/auth`, `ludicord/server`, `ludicord/security`, `ludicord/ws/client`,
|
|
23
|
+
Public entry points include `ludicord`, `ludicord/config`, `ludicord/navigation`, `ludicord/discord`, `ludicord/auth`, `ludicord/server`, `ludicord/security`, `ludicord/ws/client`, `ludicord/ws/server`, `ludicord/runtime` (client status), `ludicord/runtime/server` (server tooling), and `ludicord/testing`.
|
|
24
|
+
|
|
25
|
+
See the public [documentation](https://github.com/mrcholer/ludicord/blob/main/docs/README.md), [release history](https://github.com/mrcholer/ludicord/blob/main/CHANGELOG.md), and [issue tracker](https://github.com/mrcholer/ludicord/issues). The public repository contains documentation and release information, not the framework implementation.
|
|
26
|
+
|
|
27
|
+
Automatic files: `app/layout.tsx`, `loading.tsx`, `error.tsx`, `minimize.tsx`, and `app/auth/{loading,error,denied}.tsx`. Default-export the component and the framework connects it. Embeds use `export default function embed()`.
|
|
28
|
+
|
|
29
|
+
Development includes API/WS hot updates, TypeScript diagnostics, a Ludicord browser error panel with mapped source locations, and branded compile timing. Production uses safe errors without source disclosure.
|
|
16
30
|
|
|
17
|
-
|
|
31
|
+
Discord helpers include detailed channel/guild hooks, Activity participants, voice/layout events, typed SDK commands, and permission-gated paginated guild members. Full member lists require a server-only bot token and the GUILD_MEMBERS intent.
|
package/bin/ludicord.js
CHANGED
|
File without changes
|
package/dist/api/runtime.d.ts
CHANGED
|
@@ -21,7 +21,11 @@ export interface ApiRuntimeOptions {
|
|
|
21
21
|
readonly proxyVerification?: boolean;
|
|
22
22
|
readonly discordPublicKey?: string;
|
|
23
23
|
readonly now?: () => number;
|
|
24
|
+
readonly bodyLimit?: string | number;
|
|
25
|
+
readonly allowDevelopmentSessions?: boolean;
|
|
26
|
+
readonly onError?: (error: unknown, file: string) => void;
|
|
24
27
|
}
|
|
28
|
+
export declare function parseBodyLimit(limit?: string | number): number;
|
|
25
29
|
export declare function createApiMiddleware(options: ApiRuntimeOptions): (request: ExpressRequest, response: ExpressResponse, next: NextFunction) => Promise<void>;
|
|
26
30
|
export {};
|
|
27
31
|
//# sourceMappingURL=runtime.d.ts.map
|
package/dist/api/runtime.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import path from "node:path";
|
|
2
|
+
import { Readable } from "node:stream";
|
|
3
|
+
import { pipeline } from "node:stream/promises";
|
|
2
4
|
import { pathToFileURL } from "node:url";
|
|
3
5
|
import { matchRoutePattern, routeSpecificity } from "../router/match.js";
|
|
4
6
|
import { parseSessionCookie } from "../sessions/cookies.js";
|
|
@@ -12,16 +14,42 @@ const HTTP_METHODS = [
|
|
|
12
14
|
"HEAD",
|
|
13
15
|
"OPTIONS",
|
|
14
16
|
];
|
|
15
|
-
|
|
17
|
+
export function parseBodyLimit(limit = "2mb") {
|
|
18
|
+
if (typeof limit === "number" && Number.isSafeInteger(limit) && limit > 0)
|
|
19
|
+
return limit;
|
|
20
|
+
const match = /^(\d+(?:\.\d+)?)\s*(b|kb|mb)?$/i.exec(String(limit));
|
|
21
|
+
if (match === null)
|
|
22
|
+
throw new Error("LUDICORD8002: Invalid server.limits.body.");
|
|
23
|
+
const multiplier = match[2]?.toLowerCase() === "mb" ? 1_048_576 : match[2]?.toLowerCase() === "kb" ? 1024 : 1;
|
|
24
|
+
const bytes = Number(match[1]) * multiplier;
|
|
25
|
+
if (!Number.isSafeInteger(bytes) || bytes <= 0)
|
|
26
|
+
throw new Error("LUDICORD8002: Invalid server.limits.body.");
|
|
27
|
+
return bytes;
|
|
28
|
+
}
|
|
29
|
+
class BodyLimitError extends Error {
|
|
30
|
+
}
|
|
31
|
+
class MalformedBodyError extends Error {
|
|
32
|
+
}
|
|
33
|
+
async function requestBody(request, limit) {
|
|
16
34
|
if (request.method === "GET" || request.method === "HEAD")
|
|
17
35
|
return undefined;
|
|
36
|
+
const length = Number(request.headers["content-length"]);
|
|
37
|
+
if (Number.isFinite(length) && length > limit)
|
|
38
|
+
throw new BodyLimitError();
|
|
18
39
|
const chunks = [];
|
|
19
|
-
|
|
20
|
-
|
|
40
|
+
let size = 0;
|
|
41
|
+
for await (const chunk of request.iterator({ destroyOnReturn: false })) {
|
|
42
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
43
|
+
size += buffer.length;
|
|
44
|
+
if (size > limit) {
|
|
45
|
+
request.resume();
|
|
46
|
+
throw new BodyLimitError();
|
|
47
|
+
}
|
|
48
|
+
chunks.push(buffer);
|
|
21
49
|
}
|
|
22
50
|
return Buffer.concat(chunks);
|
|
23
51
|
}
|
|
24
|
-
function webRequest(request, params, sessionSecret, body, proxyVerified) {
|
|
52
|
+
function webRequest(request, params, sessionSecret, body, proxyVerified, allowDevelopment) {
|
|
25
53
|
const origin = `${request.protocol}://${request.get("host") ?? "localhost"}`;
|
|
26
54
|
const headerEntries = [];
|
|
27
55
|
for (const [name, value] of Object.entries(request.headers)) {
|
|
@@ -37,9 +65,20 @@ function webRequest(request, params, sessionSecret, body, proxyVerified) {
|
|
|
37
65
|
headers: new Headers(headerEntries),
|
|
38
66
|
...(body === undefined ? {} : { body: body }),
|
|
39
67
|
});
|
|
68
|
+
const parseJson = web.json.bind(web);
|
|
69
|
+
Object.defineProperty(web, "json", { value: async () => {
|
|
70
|
+
try {
|
|
71
|
+
return await parseJson();
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
if (error instanceof SyntaxError)
|
|
75
|
+
throw new MalformedBodyError();
|
|
76
|
+
throw error;
|
|
77
|
+
}
|
|
78
|
+
} });
|
|
40
79
|
const session = sessionSecret === undefined
|
|
41
80
|
? null
|
|
42
|
-
: parseSessionCookie(request.headers.cookie, sessionSecret);
|
|
81
|
+
: parseSessionCookie(request.headers.cookie, sessionSecret, { allowDevelopment });
|
|
43
82
|
Object.defineProperties(web, {
|
|
44
83
|
ludicord: { value: session, enumerable: true },
|
|
45
84
|
params: { value: params, enumerable: true },
|
|
@@ -56,13 +95,19 @@ function webRequest(request, params, sessionSecret, body, proxyVerified) {
|
|
|
56
95
|
async function sendWebResponse(response, webResponse, head) {
|
|
57
96
|
response.status(webResponse.status);
|
|
58
97
|
webResponse.headers.forEach((value, name) => {
|
|
98
|
+
if (name.toLowerCase() === "set-cookie")
|
|
99
|
+
return;
|
|
59
100
|
response.setHeader(name, value);
|
|
60
101
|
});
|
|
102
|
+
const cookies = webResponse.headers.getSetCookie();
|
|
103
|
+
if (cookies.length > 0)
|
|
104
|
+
response.setHeader("Set-Cookie", cookies);
|
|
61
105
|
if (head || webResponse.body === null) {
|
|
106
|
+
await webResponse.body?.cancel();
|
|
62
107
|
response.end();
|
|
63
108
|
return;
|
|
64
109
|
}
|
|
65
|
-
|
|
110
|
+
await pipeline(Readable.fromWeb(webResponse.body), response);
|
|
66
111
|
}
|
|
67
112
|
function allowedMethods(module) {
|
|
68
113
|
const methods = HTTP_METHODS.filter((method) => typeof module[method] === "function");
|
|
@@ -77,6 +122,7 @@ async function defaultModuleLoader(absoluteFile) {
|
|
|
77
122
|
}
|
|
78
123
|
export function createApiMiddleware(options) {
|
|
79
124
|
const loadModule = options.loadModule ?? defaultModuleLoader;
|
|
125
|
+
const bodyLimit = parseBodyLimit(options.bodyLimit);
|
|
80
126
|
return async (request, response, next) => {
|
|
81
127
|
const pathname = new URL(request.originalUrl, `${request.protocol}://${request.get("host") ?? "localhost"}`).pathname;
|
|
82
128
|
if (!pathname.startsWith("/api/") && pathname !== "/api") {
|
|
@@ -99,7 +145,7 @@ export function createApiMiddleware(options) {
|
|
|
99
145
|
}
|
|
100
146
|
try {
|
|
101
147
|
const module = await loadModule(path.join(options.projectRoot, selected.route.file));
|
|
102
|
-
const body = await requestBody(request);
|
|
148
|
+
const body = await requestBody(request, bodyLimit);
|
|
103
149
|
let proxyVerified = false;
|
|
104
150
|
if (options.proxyVerification === true) {
|
|
105
151
|
const publicKey = options.discordPublicKey ?? process.env.LUDICORD_DISCORD_PUBLIC_KEY;
|
|
@@ -137,7 +183,7 @@ export function createApiMiddleware(options) {
|
|
|
137
183
|
response.status(405).json({ error: "LUDICORD_METHOD_NOT_ALLOWED" });
|
|
138
184
|
return;
|
|
139
185
|
}
|
|
140
|
-
const ludicordRequest = webRequest(request, selected.match.params, options.sessionSecret, body, proxyVerified);
|
|
186
|
+
const ludicordRequest = webRequest(request, selected.match.params, options.sessionSecret, body, proxyVerified, options.allowDevelopmentSessions === true);
|
|
141
187
|
if (module.public !== true &&
|
|
142
188
|
module.auth !== false &&
|
|
143
189
|
ludicordRequest.ludicord === null) {
|
|
@@ -153,11 +199,16 @@ export function createApiMiddleware(options) {
|
|
|
153
199
|
await sendWebResponse(response, result, method === "HEAD");
|
|
154
200
|
}
|
|
155
201
|
catch (error) {
|
|
156
|
-
if (error instanceof
|
|
157
|
-
(
|
|
202
|
+
if (error instanceof BodyLimitError) {
|
|
203
|
+
request.resume();
|
|
204
|
+
response.status(413).json({ error: "LUDICORD_BODY_TOO_LARGE" });
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
if (error instanceof MalformedBodyError) {
|
|
158
208
|
response.status(400).json({ error: "LUDICORD_MALFORMED_BODY" });
|
|
159
209
|
return;
|
|
160
210
|
}
|
|
211
|
+
options.onError?.(error, selected.route.file);
|
|
161
212
|
next(error);
|
|
162
213
|
}
|
|
163
214
|
};
|
package/dist/auth/client.d.ts
CHANGED
|
@@ -11,5 +11,15 @@ export declare function useLudicordSession(): LudicordSession | null;
|
|
|
11
11
|
export declare function useAuthStatus(): LudicordAuthStatus;
|
|
12
12
|
export declare function useAuthError(): Error | null;
|
|
13
13
|
export declare function getLudicordAuthSnapshot(): LudicordAuthSnapshot;
|
|
14
|
+
export declare function logoutLudicord(): Promise<void>;
|
|
15
|
+
export declare function useLudicordAuth(): {
|
|
16
|
+
user: import("./types.js").LudicordSessionUser | null;
|
|
17
|
+
login: typeof authenticateLudicord;
|
|
18
|
+
logout: typeof logoutLudicord;
|
|
19
|
+
status: LudicordAuthStatus;
|
|
20
|
+
session: LudicordSession | null;
|
|
21
|
+
error: Error | null;
|
|
22
|
+
};
|
|
23
|
+
export declare function setMockSessionForTesting(session: LudicordSession | null): void;
|
|
14
24
|
export declare function resetLudicordAuthForTesting(): void;
|
|
15
25
|
//# sourceMappingURL=client.d.ts.map
|
package/dist/auth/client.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { useSyncExternalStore } from "react";
|
|
1
|
+
import { useMemo, useSyncExternalStore } from "react";
|
|
2
2
|
import { getDiscordSnapshot, } from "../discord/runtime.js";
|
|
3
|
-
import { setDiscordUserFromAuth, setDiscordGuildFromAuth } from "../discord/events.js";
|
|
3
|
+
import { setDiscordUserFromAuth, setDiscordGuildFromAuth, initializeDiscordEventsFromEnvironment, enrichDiscordContext, addDiscordDiagnostic } from "../discord/events.js";
|
|
4
4
|
class LudicordAuthStore {
|
|
5
5
|
snapshot = {
|
|
6
6
|
status: "idle",
|
|
@@ -9,12 +9,21 @@ class LudicordAuthStore {
|
|
|
9
9
|
};
|
|
10
10
|
listeners = new Set();
|
|
11
11
|
authentication = null;
|
|
12
|
+
expiryTimer;
|
|
12
13
|
subscribe = (listener) => {
|
|
13
14
|
this.listeners.add(listener);
|
|
14
15
|
return () => this.listeners.delete(listener);
|
|
15
16
|
};
|
|
16
17
|
getSnapshot = () => this.snapshot;
|
|
17
18
|
update(status, session, error) {
|
|
19
|
+
clearTimeout(this.expiryTimer);
|
|
20
|
+
if (session !== null) {
|
|
21
|
+
this.expiryTimer = setTimeout(() => {
|
|
22
|
+
setDiscordUserFromAuth(null);
|
|
23
|
+
this.update("idle", null, new Error("LUDICORD6011: Session expired. Sign in again."));
|
|
24
|
+
}, Math.max(0, Math.min(session.expiresAt - Date.now(), 2_147_483_647)));
|
|
25
|
+
this.expiryTimer.unref?.();
|
|
26
|
+
}
|
|
18
27
|
this.snapshot = { status, session, error };
|
|
19
28
|
for (const listener of this.listeners)
|
|
20
29
|
listener();
|
|
@@ -22,9 +31,12 @@ class LudicordAuthStore {
|
|
|
22
31
|
run(options) {
|
|
23
32
|
if (this.authentication !== null)
|
|
24
33
|
return this.authentication;
|
|
25
|
-
this.
|
|
34
|
+
if (this.snapshot.session !== null && this.snapshot.session.expiresAt > Date.now())
|
|
35
|
+
return Promise.resolve(this.snapshot.session);
|
|
36
|
+
this.authentication = performAuthentication(options).finally(() => { this.authentication = null; });
|
|
26
37
|
return this.authentication;
|
|
27
38
|
}
|
|
39
|
+
dispose() { clearTimeout(this.expiryTimer); }
|
|
28
40
|
}
|
|
29
41
|
let authStore = new LudicordAuthStore();
|
|
30
42
|
function authCommands(sdk) {
|
|
@@ -76,7 +88,7 @@ async function performAuthentication(options) {
|
|
|
76
88
|
client_id: clientId,
|
|
77
89
|
response_type: "code",
|
|
78
90
|
state: stateBody.state,
|
|
79
|
-
scope: options.scopes ?? ["identify"],
|
|
91
|
+
scope: options.scopes ?? globalThis.__LUDICORD_PUBLIC_CONFIG__?.scopes ?? ["identify"],
|
|
80
92
|
prompt: "none",
|
|
81
93
|
});
|
|
82
94
|
}
|
|
@@ -104,22 +116,44 @@ async function performAuthentication(options) {
|
|
|
104
116
|
const exchange = (await jsonOrError(exchangeResponse));
|
|
105
117
|
if (typeof exchange.access_token !== "string" ||
|
|
106
118
|
typeof exchange.session !== "object" ||
|
|
107
|
-
exchange.session === null) {
|
|
119
|
+
exchange.session === null || typeof exchange.completionToken !== "string") {
|
|
108
120
|
throw new Error("LUDICORD6004: Invalid authentication exchange response.");
|
|
109
121
|
}
|
|
110
|
-
await commands.authenticate({ access_token: exchange.access_token });
|
|
111
|
-
const
|
|
122
|
+
const authenticated = await commands.authenticate({ access_token: exchange.access_token });
|
|
123
|
+
const expected = exchange.session;
|
|
124
|
+
if (authenticated?.user?.id !== expected.user.id) {
|
|
125
|
+
throw new Error("LUDICORD6004: Discord identity did not match the verified session.");
|
|
126
|
+
}
|
|
127
|
+
const confirmation = await fetchImplementation("/_ludicord/auth/complete", {
|
|
128
|
+
method: "POST", credentials: "include", headers: { "content-type": "application/json" },
|
|
129
|
+
body: JSON.stringify({ completionToken: exchange.completionToken }),
|
|
130
|
+
});
|
|
131
|
+
const session = await jsonOrError(confirmation);
|
|
132
|
+
if (session.authenticated !== true || session.user?.id !== expected.user.id)
|
|
133
|
+
throw new Error("LUDICORD6004: Invalid confirmed session.");
|
|
112
134
|
setDiscordUserFromAuth({
|
|
113
135
|
...session.user,
|
|
114
136
|
avatar: session.user.avatar === null || session.user.avatar.startsWith("http")
|
|
115
137
|
? session.user.avatar
|
|
116
138
|
: `https://cdn.discordapp.com/avatars/${session.user.id}/${session.user.avatar}.png`,
|
|
117
139
|
});
|
|
118
|
-
setDiscordGuildFromAuth(session.guildId, session.guildName);
|
|
140
|
+
setDiscordGuildFromAuth(session.guildId, session.guildName, session.guildIcon);
|
|
119
141
|
authStore.update("authenticated", session, null);
|
|
142
|
+
void initializeDiscordEventsFromEnvironment(discord, session.scopes).catch(() => addDiscordDiagnostic("Some Discord capabilities are unavailable."));
|
|
143
|
+
if (globalThis.__LUDICORD_PUBLIC_CONFIG__?.discordServerData) {
|
|
144
|
+
void fetchImplementation("/_ludicord/auth/context", { credentials: "include", signal: AbortSignal.timeout(10000) })
|
|
145
|
+
.then(async (response) => { if (!response.ok) {
|
|
146
|
+
addDiscordDiagnostic("Extended guild/channel data requires verified Activity membership and bot access.");
|
|
147
|
+
return;
|
|
148
|
+
} const context = await response.json(); if (authStore.getSnapshot().session === session)
|
|
149
|
+
enrichDiscordContext(context); })
|
|
150
|
+
.catch(() => addDiscordDiagnostic("Extended Discord context is temporarily unavailable."));
|
|
151
|
+
}
|
|
120
152
|
return session;
|
|
121
153
|
}
|
|
122
154
|
catch (cause) {
|
|
155
|
+
// Pending cookies cannot authorize APIs, and are cleared if SDK authentication fails.
|
|
156
|
+
await fetchImplementation("/_ludicord/auth/logout", { method: "POST", credentials: "include" }).catch(() => undefined);
|
|
123
157
|
if (authStore.getSnapshot().status === "denied")
|
|
124
158
|
throw cause;
|
|
125
159
|
const error = cause instanceof Error
|
|
@@ -176,7 +210,23 @@ export function useAuthError() {
|
|
|
176
210
|
export function getLudicordAuthSnapshot() {
|
|
177
211
|
return authStore.getSnapshot();
|
|
178
212
|
}
|
|
213
|
+
export async function logoutLudicord() {
|
|
214
|
+
const response = await fetch("/_ludicord/auth/logout", { method: "POST", credentials: "include" });
|
|
215
|
+
if (!response.ok)
|
|
216
|
+
throw new Error("LUDICORD6012: Could not sign out. Please retry.");
|
|
217
|
+
setDiscordUserFromAuth(null);
|
|
218
|
+
authStore.update("idle", null, null);
|
|
219
|
+
}
|
|
220
|
+
export function useLudicordAuth() {
|
|
221
|
+
const snapshot = useSyncExternalStore(authStore.subscribe, authStore.getSnapshot, authStore.getSnapshot);
|
|
222
|
+
return useMemo(() => ({ ...snapshot, user: snapshot.session?.user ?? null, login: authenticateLudicord, logout: logoutLudicord }), [snapshot]);
|
|
223
|
+
}
|
|
224
|
+
export function setMockSessionForTesting(session) {
|
|
225
|
+
authStore.update(session === null ? "idle" : "authenticated", session, null);
|
|
226
|
+
setDiscordUserFromAuth(session?.user ?? null);
|
|
227
|
+
}
|
|
179
228
|
export function resetLudicordAuthForTesting() {
|
|
229
|
+
authStore.dispose();
|
|
180
230
|
authStore = new LudicordAuthStore();
|
|
181
231
|
}
|
|
182
232
|
//# sourceMappingURL=client.js.map
|
package/dist/auth/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { authenticateLudicord, initializeLudicordAuthFromEnvironment, useAuthError, useAuthStatus, useLudicordSession, } from "./client.js";
|
|
1
|
+
export { authenticateLudicord, initializeLudicordAuthFromEnvironment, useAuthError, useAuthStatus, useLudicordSession, useLudicordAuth, logoutLudicord, } from "./client.js";
|
|
2
2
|
export type { LudicordAuthSnapshot, LudicordAuthStatus, LudicordSession, LudicordSessionUser, } from "./types.js";
|
|
3
3
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/auth/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export { authenticateLudicord, initializeLudicordAuthFromEnvironment, useAuthError, useAuthStatus, useLudicordSession, } from "./client.js";
|
|
1
|
+
export { authenticateLudicord, initializeLudicordAuthFromEnvironment, useAuthError, useAuthStatus, useLudicordSession, useLudicordAuth, logoutLudicord, } from "./client.js";
|
|
2
2
|
//# sourceMappingURL=index.js.map
|