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/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 mrcholer
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -16,9 +16,7 @@ The full-stack React framework and CLI for Discord Activities.
|
|
|
16
16
|
|
|
17
17
|
```bash
|
|
18
18
|
ludicord dev
|
|
19
|
-
ludicord lint
|
|
20
19
|
ludicord build
|
|
21
|
-
ludicord analyze
|
|
22
20
|
ludicord start
|
|
23
21
|
```
|
|
24
22
|
|
|
@@ -28,8 +26,10 @@ See the public [documentation](https://github.com/mrcholer/ludicord/blob/main/do
|
|
|
28
26
|
|
|
29
27
|
Automatic files: `app/metadata.ts`, `proxy.ts`, `instrumentation.ts`, `layout.tsx`, `loading.tsx`, `error.tsx`, `global-error.tsx`, `not-found.tsx`, `minimize.tsx`, and `app/auth/{loading,error,denied}.tsx`. Embed folders may also inherit nested `layout.tsx` and nearest `loading.tsx`/`error.tsx`. Route groups such as `(games)` organize embed/API/WS source without changing URLs. Default-export the component or convention object and the framework connects it. Embeds use `export default function embed()`.
|
|
30
28
|
|
|
31
|
-
Development includes API/WS/proxy hot updates, TypeScript diagnostics, React
|
|
29
|
+
Development announces its listener before compilation, recovers from an initial compile error without losing the port, and includes API/WS/proxy hot updates, TypeScript diagnostics, React Strict Mode, a Ludicord browser error panel with mapped source locations, and branded compile timing. Production uses atomic output and safe errors without source disclosure. Advanced tooling is documented in the full guide.
|
|
32
30
|
|
|
33
31
|
Discord helpers include complete raw user/channel/guild/member/role/participant/event payloads beside convenient normalized fields, Activity participants, voice/layout events, typed SDK commands, verified permission bitfields, channel/role/member resources, and paginated guild members. Full member lists require a server-only bot token and the GUILD_MEMBERS intent.
|
|
34
32
|
|
|
35
|
-
Activity hooks add scoped persistence, cached queries, lifecycle readiness, raw Discord-event callbacks, presence summaries, animation frames, and revision-safe shared instance state. Use normal React state for local UI and these helpers where Discord Activity behavior needs a framework-owned lifecycle.
|
|
33
|
+
Activity hooks add application-, instance-, user-, guild-, and channel-scoped persistence, cached queries, lifecycle readiness, raw Discord-event callbacks, presence summaries, animation frames, and revision-safe shared instance state. Use normal React state for local UI and these helpers where Discord Activity behavior needs a framework-owned lifecycle.
|
|
34
|
+
|
|
35
|
+
Version 3.1 isolates authentication per Activity launch, renews expiring sessions without discarding a still-valid login, applies one host/origin policy to HTTP and WebSockets, adds acknowledged WebSocket events and bounded slow-client handling, and exposes adapters for multi-process sessions, one-time OAuth tokens, room delivery/counts, and shared-state revisions.
|
|
@@ -5,6 +5,7 @@ export interface LudicordSharedActivityState<T> {
|
|
|
5
5
|
readonly revision: number;
|
|
6
6
|
readonly synchronized: boolean;
|
|
7
7
|
readonly status: LudicordWSStatus;
|
|
8
|
+
readonly error: Error | null;
|
|
8
9
|
readonly setValue: Dispatch<SetStateAction<T>>;
|
|
9
10
|
}
|
|
10
11
|
export declare function useSharedActivityState<T>(route: LudicordWSRoute, key: string, initialValue: T | (() => T), options?: LudicordWSConnectionOptions): LudicordSharedActivityState<T>;
|
|
@@ -8,6 +8,7 @@ export function useSharedActivityState(route, key, initialValue, options = {}) {
|
|
|
8
8
|
const [value, setState] = useState(resolveInitial);
|
|
9
9
|
const [revision, setRevision] = useState(0);
|
|
10
10
|
const [synchronized, setSynchronized] = useState(false);
|
|
11
|
+
const [error, setError] = useState(null);
|
|
11
12
|
const valueRef = useRef(value);
|
|
12
13
|
valueRef.current = value;
|
|
13
14
|
const revisionRef = useRef(revision);
|
|
@@ -41,6 +42,7 @@ export function useSharedActivityState(route, key, initialValue, options = {}) {
|
|
|
41
42
|
setState(resolveInitial());
|
|
42
43
|
setRevision(0);
|
|
43
44
|
setSynchronized(false);
|
|
45
|
+
setError(null);
|
|
44
46
|
pendingRef.current = null;
|
|
45
47
|
inFlightRef.current = null;
|
|
46
48
|
snapshotReadyRef.current = false;
|
|
@@ -52,6 +54,7 @@ export function useSharedActivityState(route, key, initialValue, options = {}) {
|
|
|
52
54
|
if (source.key !== key || typeof source.revision !== "number")
|
|
53
55
|
return;
|
|
54
56
|
snapshotReadyRef.current = true;
|
|
57
|
+
setError(null);
|
|
55
58
|
const inFlight = inFlightRef.current;
|
|
56
59
|
if (inFlight !== null && source.revision <= inFlight.baseRevision)
|
|
57
60
|
return;
|
|
@@ -70,6 +73,23 @@ export function useSharedActivityState(route, key, initialValue, options = {}) {
|
|
|
70
73
|
setState(source.value);
|
|
71
74
|
setSynchronized(true);
|
|
72
75
|
}), [connection, flush, key]);
|
|
76
|
+
useEffect(() => connection.on("ludicord:shared:error", (payload) => {
|
|
77
|
+
if (typeof payload !== "object" || payload === null)
|
|
78
|
+
return;
|
|
79
|
+
const source = payload;
|
|
80
|
+
if (source.key !== key || typeof source.revision !== "number")
|
|
81
|
+
return;
|
|
82
|
+
inFlightRef.current = null;
|
|
83
|
+
pendingRef.current = null;
|
|
84
|
+
revisionRef.current = source.revision;
|
|
85
|
+
valueRef.current = source.value;
|
|
86
|
+
setRevision(source.revision);
|
|
87
|
+
setState(source.value);
|
|
88
|
+
setSynchronized(true);
|
|
89
|
+
const code = typeof source.code === "string" ? source.code : "LUDICORD9205";
|
|
90
|
+
const message = typeof source.message === "string" ? source.message : "Shared state update was rejected.";
|
|
91
|
+
setError(new Error(`${code}: ${message}`));
|
|
92
|
+
}), [connection, key]);
|
|
73
93
|
useEffect(() => {
|
|
74
94
|
if (connection.status === "open") {
|
|
75
95
|
snapshotReadyRef.current = false;
|
|
@@ -93,8 +113,9 @@ export function useSharedActivityState(route, key, initialValue, options = {}) {
|
|
|
93
113
|
valueRef.current = resolved;
|
|
94
114
|
setState(resolved);
|
|
95
115
|
setSynchronized(false);
|
|
116
|
+
setError(null);
|
|
96
117
|
pendingRef.current = { value: resolved };
|
|
97
118
|
flush();
|
|
98
119
|
}, [flush]);
|
|
99
|
-
return useMemo(() => ({ value, revision, synchronized, status: connection.status, setValue }), [connection.status, revision, setValue, synchronized, value]);
|
|
120
|
+
return useMemo(() => ({ value, revision, synchronized, status: connection.status, error, setValue }), [connection.status, error, revision, setValue, synchronized, value]);
|
|
100
121
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Dispatch, SetStateAction } from "react";
|
|
2
|
-
export type LudicordActivityStorageScope = "activity" | "user" | "guild" | "channel";
|
|
2
|
+
export type LudicordActivityStorageScope = "activity" | "application" | "instance" | "user" | "guild" | "channel";
|
|
3
3
|
export interface LudicordActivityStorageOptions<T> {
|
|
4
4
|
readonly scope?: LudicordActivityStorageScope;
|
|
5
5
|
readonly storage?: Storage;
|
package/dist/activity/storage.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
2
2
|
import { useDiscordChannel, useDiscordGuild, useDiscordUser } from "../discord/events.js";
|
|
3
|
+
import { useDiscord } from "../discord/runtime.js";
|
|
3
4
|
function initialValue(value) {
|
|
4
5
|
return typeof value === "function" ? value() : value;
|
|
5
6
|
}
|
|
@@ -22,9 +23,12 @@ export function useActivityStorage(key, initial, options = {}) {
|
|
|
22
23
|
const user = useDiscordUser();
|
|
23
24
|
const guild = useDiscordGuild();
|
|
24
25
|
const channel = useDiscordChannel();
|
|
26
|
+
const discord = useDiscord();
|
|
25
27
|
const scope = options.scope ?? "activity";
|
|
26
28
|
const identity = scope === "activity" ? "root" :
|
|
27
|
-
scope === "
|
|
29
|
+
scope === "application" ? discord.applicationId :
|
|
30
|
+
scope === "instance" ? (discord.applicationId === undefined || discord.instanceId === undefined ? undefined : `${discord.applicationId}:${discord.instanceId}`) :
|
|
31
|
+
scope === "user" ? user?.id : scope === "guild" ? guild?.id : channel?.id;
|
|
28
32
|
const storageKey = identity === undefined || identity === null
|
|
29
33
|
? null
|
|
30
34
|
: `ludicord:${scope}:${identity}:${key}`;
|
package/dist/api/runtime.js
CHANGED
|
@@ -4,6 +4,7 @@ import { pipeline } from "node:stream/promises";
|
|
|
4
4
|
import { pathToFileURL } from "node:url";
|
|
5
5
|
import { matchRoutePattern, routeSpecificity } from "../router/match.js";
|
|
6
6
|
import { parseSessionCookie } from "../sessions/cookies.js";
|
|
7
|
+
import { LUDICORD_LAUNCH_HEADER, normalizeLudicordLaunchId } from "../sessions/launch.js";
|
|
7
8
|
import { verifyDiscordProxyRequest } from "../security/discord.js";
|
|
8
9
|
const HTTP_METHODS = [
|
|
9
10
|
"GET",
|
|
@@ -81,7 +82,12 @@ function webRequest(request, params, sessionSecret, body, proxyVerified, allowDe
|
|
|
81
82
|
} });
|
|
82
83
|
const session = sessionSecret === undefined
|
|
83
84
|
? null
|
|
84
|
-
: parseSessionCookie(request.headers.cookie, sessionSecret, {
|
|
85
|
+
: parseSessionCookie(request.headers.cookie, sessionSecret, {
|
|
86
|
+
allowDevelopment,
|
|
87
|
+
...(normalizeLudicordLaunchId(request.get(LUDICORD_LAUNCH_HEADER)) === undefined
|
|
88
|
+
? {}
|
|
89
|
+
: { launchId: normalizeLudicordLaunchId(request.get(LUDICORD_LAUNCH_HEADER)) }),
|
|
90
|
+
});
|
|
85
91
|
Object.defineProperties(web, {
|
|
86
92
|
ludicord: { value: session, enumerable: true },
|
|
87
93
|
params: { value: params, enumerable: true },
|
package/dist/auth/client.d.ts
CHANGED
|
@@ -6,6 +6,8 @@ export interface AuthenticateLudicordOptions {
|
|
|
6
6
|
readonly discord?: DiscordRuntimeSnapshot;
|
|
7
7
|
}
|
|
8
8
|
export declare function authenticateLudicord(options?: AuthenticateLudicordOptions): Promise<LudicordSession | null>;
|
|
9
|
+
/** Refresh the Discord-backed session without unmounting the running Activity. */
|
|
10
|
+
export declare function renewLudicordSession(options?: AuthenticateLudicordOptions): Promise<LudicordSession | null>;
|
|
9
11
|
export declare function initializeLudicordAuthFromEnvironment(discord: DiscordRuntimeSnapshot): Promise<LudicordSession | null>;
|
|
10
12
|
export declare function useLudicordSession(): LudicordSession | null;
|
|
11
13
|
export declare function useAuthStatus(): LudicordAuthStatus;
|
package/dist/auth/client.js
CHANGED
|
@@ -2,6 +2,7 @@ import { useMemo, useSyncExternalStore } from "react";
|
|
|
2
2
|
import { getDiscordSnapshot, } from "../discord/runtime.js";
|
|
3
3
|
import { setDiscordUserFromAuth, setDiscordGuildFromAuth, initializeDiscordEventsFromEnvironment, enrichDiscordContext, addDiscordDiagnostic } from "../discord/events.js";
|
|
4
4
|
import { discordUserAvatarUrl } from "../discord/assets.js";
|
|
5
|
+
import { installLudicordLaunchIsolation, resetLudicordLaunchForTesting, withLudicordLaunchHeader } from "../sessions/launch.js";
|
|
5
6
|
class LudicordAuthStore {
|
|
6
7
|
snapshot = {
|
|
7
8
|
status: "idle",
|
|
@@ -11,19 +12,33 @@ class LudicordAuthStore {
|
|
|
11
12
|
listeners = new Set();
|
|
12
13
|
authentication = null;
|
|
13
14
|
expiryTimer;
|
|
15
|
+
renewalTimer;
|
|
14
16
|
subscribe = (listener) => {
|
|
15
17
|
this.listeners.add(listener);
|
|
16
18
|
return () => this.listeners.delete(listener);
|
|
17
19
|
};
|
|
18
20
|
getSnapshot = () => this.snapshot;
|
|
19
|
-
update(status, session, error) {
|
|
21
|
+
update(status, session, error, renewal = "automatic") {
|
|
20
22
|
clearTimeout(this.expiryTimer);
|
|
23
|
+
clearTimeout(this.renewalTimer);
|
|
21
24
|
if (session !== null) {
|
|
25
|
+
const remaining = session.expiresAt - Date.now();
|
|
22
26
|
this.expiryTimer = setTimeout(() => {
|
|
23
27
|
setDiscordUserFromAuth(null);
|
|
24
28
|
this.update("idle", null, new Error("LUDICORD6011: Session expired. Sign in again."));
|
|
25
|
-
}, Math.max(0, Math.min(
|
|
29
|
+
}, Math.max(0, Math.min(remaining, 2_147_483_647)));
|
|
26
30
|
this.expiryTimer.unref?.();
|
|
31
|
+
if (status === "authenticated" && session.kind !== "development" && renewal !== "none" && remaining > 1_500) {
|
|
32
|
+
const lifetime = Math.max(1, session.expiresAt - session.issuedAt);
|
|
33
|
+
const lead = Math.min(300_000, Math.max(5_000, Math.floor(lifetime * 0.1)));
|
|
34
|
+
const delay = renewal === "retry"
|
|
35
|
+
? Math.min(30_000, Math.max(1_000, Math.floor(remaining / 2)))
|
|
36
|
+
: Math.max(1_000, remaining - lead);
|
|
37
|
+
this.renewalTimer = setTimeout(() => {
|
|
38
|
+
void this.renew({}).catch(() => undefined);
|
|
39
|
+
}, Math.min(delay, 2_147_483_647));
|
|
40
|
+
this.renewalTimer.unref?.();
|
|
41
|
+
}
|
|
27
42
|
}
|
|
28
43
|
this.snapshot = { status, session, error };
|
|
29
44
|
for (const listener of this.listeners)
|
|
@@ -34,12 +49,36 @@ class LudicordAuthStore {
|
|
|
34
49
|
return this.authentication;
|
|
35
50
|
if (this.snapshot.session !== null && this.snapshot.session.expiresAt > Date.now())
|
|
36
51
|
return Promise.resolve(this.snapshot.session);
|
|
37
|
-
this.authentication = performAuthentication(options).finally(() => { this.authentication = null; });
|
|
52
|
+
this.authentication = performAuthentication(options, null).finally(() => { this.authentication = null; });
|
|
38
53
|
return this.authentication;
|
|
39
54
|
}
|
|
40
|
-
|
|
55
|
+
renew(options) {
|
|
56
|
+
if (this.authentication !== null)
|
|
57
|
+
return this.authentication;
|
|
58
|
+
const session = this.snapshot.session;
|
|
59
|
+
if (session === null || session.expiresAt <= Date.now())
|
|
60
|
+
return this.run(options);
|
|
61
|
+
this.authentication = performAuthentication(options, session).finally(() => { this.authentication = null; });
|
|
62
|
+
return this.authentication;
|
|
63
|
+
}
|
|
64
|
+
dispose() {
|
|
65
|
+
clearTimeout(this.expiryTimer);
|
|
66
|
+
clearTimeout(this.renewalTimer);
|
|
67
|
+
}
|
|
41
68
|
}
|
|
42
69
|
let authStore = new LudicordAuthStore();
|
|
70
|
+
class LudicordAuthRequestError extends Error {
|
|
71
|
+
code;
|
|
72
|
+
reason;
|
|
73
|
+
retryAfterMs;
|
|
74
|
+
constructor(message, code, reason, retryAfterMs) {
|
|
75
|
+
super(message);
|
|
76
|
+
this.code = code;
|
|
77
|
+
this.reason = reason;
|
|
78
|
+
this.retryAfterMs = retryAfterMs;
|
|
79
|
+
this.name = "LudicordAuthRequestError";
|
|
80
|
+
}
|
|
81
|
+
}
|
|
43
82
|
function authCommands(sdk) {
|
|
44
83
|
const commands = sdk.commands;
|
|
45
84
|
if (commands === undefined ||
|
|
@@ -52,17 +91,19 @@ function authCommands(sdk) {
|
|
|
52
91
|
async function jsonOrError(response) {
|
|
53
92
|
const body = (await response.json());
|
|
54
93
|
if (!response.ok) {
|
|
55
|
-
const
|
|
56
|
-
body
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
?
|
|
94
|
+
const details = typeof body === "object" && body !== null
|
|
95
|
+
? body
|
|
96
|
+
: {};
|
|
97
|
+
const message = typeof details.message === "string"
|
|
98
|
+
? details.message
|
|
60
99
|
: "Ludicord authentication request failed.";
|
|
61
|
-
throw new
|
|
100
|
+
throw new LudicordAuthRequestError(message, typeof details.error === "string" ? details.error : undefined, typeof details.reason === "string" ? details.reason : undefined, typeof details.retryAfterMs === "number" && Number.isFinite(details.retryAfterMs)
|
|
101
|
+
? Math.max(0, details.retryAfterMs)
|
|
102
|
+
: undefined);
|
|
62
103
|
}
|
|
63
104
|
return body;
|
|
64
105
|
}
|
|
65
|
-
async function performAuthentication(options) {
|
|
106
|
+
async function performAuthentication(options, retainedSession, attempt = 0) {
|
|
66
107
|
const discord = options.discord ?? getDiscordSnapshot();
|
|
67
108
|
if (discord.status !== "ready" || discord.sdk === null) {
|
|
68
109
|
return null;
|
|
@@ -72,17 +113,19 @@ async function performAuthentication(options) {
|
|
|
72
113
|
throw new Error("LUDICORD5001: Missing LUDICORD_DISCORD_CLIENT_ID.");
|
|
73
114
|
}
|
|
74
115
|
const fetchImplementation = options.fetch ?? globalThis.fetch;
|
|
116
|
+
const authFetch = (input, init) => fetchImplementation(input, withLudicordLaunchHeader(init));
|
|
75
117
|
const commands = authCommands(discord.sdk);
|
|
76
|
-
authStore.update("connecting", null,
|
|
118
|
+
authStore.update(retainedSession === null ? "connecting" : "reauthenticating", retainedSession, null, "none");
|
|
77
119
|
try {
|
|
78
|
-
const stateResponse = await
|
|
120
|
+
const stateResponse = await authFetch("/_ludicord/auth/state", {
|
|
79
121
|
credentials: "include",
|
|
80
122
|
});
|
|
81
123
|
const stateBody = (await jsonOrError(stateResponse));
|
|
82
124
|
if (typeof stateBody.state !== "string") {
|
|
83
125
|
throw new Error("LUDICORD6003: Invalid OAuth state response.");
|
|
84
126
|
}
|
|
85
|
-
|
|
127
|
+
if (retainedSession === null)
|
|
128
|
+
authStore.update("authorizing", null, null);
|
|
86
129
|
let authorization;
|
|
87
130
|
try {
|
|
88
131
|
authorization = await commands.authorize({
|
|
@@ -97,10 +140,11 @@ async function performAuthentication(options) {
|
|
|
97
140
|
const error = new Error("LUDICORD6007: Discord authorization was denied.", {
|
|
98
141
|
cause,
|
|
99
142
|
});
|
|
100
|
-
|
|
143
|
+
if (retainedSession === null)
|
|
144
|
+
authStore.update("denied", null, error);
|
|
101
145
|
throw error;
|
|
102
146
|
}
|
|
103
|
-
const exchangeResponse = await
|
|
147
|
+
const exchangeResponse = await authFetch("/_ludicord/auth/exchange", {
|
|
104
148
|
method: "POST",
|
|
105
149
|
credentials: "include",
|
|
106
150
|
headers: { "content-type": "application/json" },
|
|
@@ -125,7 +169,7 @@ async function performAuthentication(options) {
|
|
|
125
169
|
if (authenticated?.user?.id !== expected.user.id) {
|
|
126
170
|
throw new Error("LUDICORD6004: Discord identity did not match the verified session.");
|
|
127
171
|
}
|
|
128
|
-
const confirmation = await
|
|
172
|
+
const confirmation = await authFetch("/_ludicord/auth/complete", {
|
|
129
173
|
method: "POST", credentials: "include", headers: { "content-type": "application/json" },
|
|
130
174
|
body: JSON.stringify({ completionToken: exchange.completionToken }),
|
|
131
175
|
});
|
|
@@ -140,7 +184,7 @@ async function performAuthentication(options) {
|
|
|
140
184
|
authStore.update("authenticated", session, null);
|
|
141
185
|
void initializeDiscordEventsFromEnvironment(discord, session.scopes).catch(() => addDiscordDiagnostic("Some Discord capabilities are unavailable."));
|
|
142
186
|
if (globalThis.__LUDICORD_PUBLIC_CONFIG__?.discordServerData) {
|
|
143
|
-
void
|
|
187
|
+
void authFetch("/_ludicord/auth/context", { credentials: "include", signal: AbortSignal.timeout(10000) })
|
|
144
188
|
.then(async (response) => { if (!response.ok) {
|
|
145
189
|
addDiscordDiagnostic("Extended guild/channel data requires verified Activity membership and bot access.");
|
|
146
190
|
return;
|
|
@@ -151,21 +195,41 @@ async function performAuthentication(options) {
|
|
|
151
195
|
return session;
|
|
152
196
|
}
|
|
153
197
|
catch (cause) {
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
198
|
+
const retryableVerification = cause instanceof LudicordAuthRequestError &&
|
|
199
|
+
cause.code === "LUDICORD6010" &&
|
|
200
|
+
(cause.reason === "unauthorized" || cause.reason === "rate-limited");
|
|
201
|
+
if (retryableVerification && attempt < 2) {
|
|
202
|
+
await authFetch("/_ludicord/auth/cancel", { method: "POST", credentials: "include" }).catch(() => undefined);
|
|
203
|
+
const retryAfterMs = Math.min(3_000, Math.max(250, cause.retryAfterMs ?? 1_000 * (attempt + 1)));
|
|
204
|
+
await new Promise((resolve) => setTimeout(resolve, retryAfterMs));
|
|
205
|
+
return performAuthentication(options, retainedSession, attempt + 1);
|
|
206
|
+
}
|
|
207
|
+
// A failed renewal must clear only its pending OAuth state. Logging out here
|
|
208
|
+
// would destroy the still-valid session that keeps the Activity mounted.
|
|
209
|
+
await authFetch(retainedSession === null ? "/_ludicord/auth/logout" : "/_ludicord/auth/cancel", { method: "POST", credentials: "include" }).catch(() => undefined);
|
|
210
|
+
if (retainedSession === null && authStore.getSnapshot().status === "denied")
|
|
157
211
|
throw cause;
|
|
158
212
|
const error = cause instanceof Error
|
|
159
213
|
? cause
|
|
160
214
|
: new Error("LUDICORD6008: Authentication failed.");
|
|
161
|
-
|
|
215
|
+
if (retainedSession !== null && retainedSession.expiresAt > Date.now()) {
|
|
216
|
+
authStore.update("authenticated", retainedSession, error, "retry");
|
|
217
|
+
}
|
|
218
|
+
else {
|
|
219
|
+
authStore.update("error", null, error);
|
|
220
|
+
}
|
|
162
221
|
throw error;
|
|
163
222
|
}
|
|
164
223
|
}
|
|
165
224
|
export function authenticateLudicord(options = {}) {
|
|
166
225
|
return authStore.run(options);
|
|
167
226
|
}
|
|
227
|
+
/** Refresh the Discord-backed session without unmounting the running Activity. */
|
|
228
|
+
export function renewLudicordSession(options = {}) {
|
|
229
|
+
return authStore.renew(options);
|
|
230
|
+
}
|
|
168
231
|
export async function initializeLudicordAuthFromEnvironment(discord) {
|
|
232
|
+
installLudicordLaunchIsolation();
|
|
169
233
|
const config = globalThis.__LUDICORD_PUBLIC_CONFIG__;
|
|
170
234
|
if (config?.devFakeAuth === true) {
|
|
171
235
|
return authenticateDevelopmentSession();
|
|
@@ -183,7 +247,7 @@ async function authenticateDevelopmentSession() {
|
|
|
183
247
|
}
|
|
184
248
|
authStore.update("connecting", null, null);
|
|
185
249
|
try {
|
|
186
|
-
const response = await fetch("/_ludicord/auth/dev-login", { credentials: "include" });
|
|
250
|
+
const response = await fetch("/_ludicord/auth/dev-login", withLudicordLaunchHeader({ credentials: "include" }));
|
|
187
251
|
if (!response.ok)
|
|
188
252
|
throw new Error("Development fake login failed.");
|
|
189
253
|
const session = (await response.json());
|
|
@@ -210,7 +274,7 @@ export function getLudicordAuthSnapshot() {
|
|
|
210
274
|
return authStore.getSnapshot();
|
|
211
275
|
}
|
|
212
276
|
export async function logoutLudicord() {
|
|
213
|
-
const response = await fetch("/_ludicord/auth/logout", { method: "POST", credentials: "include" });
|
|
277
|
+
const response = await fetch("/_ludicord/auth/logout", withLudicordLaunchHeader({ method: "POST", credentials: "include" }));
|
|
214
278
|
if (!response.ok)
|
|
215
279
|
throw new Error("LUDICORD6012: Could not sign out. Please retry.");
|
|
216
280
|
setDiscordUserFromAuth(null);
|
|
@@ -227,4 +291,5 @@ export function setMockSessionForTesting(session) {
|
|
|
227
291
|
export function resetLudicordAuthForTesting() {
|
|
228
292
|
authStore.dispose();
|
|
229
293
|
authStore = new LudicordAuthStore();
|
|
294
|
+
resetLudicordLaunchForTesting();
|
|
230
295
|
}
|
package/dist/auth/index.d.ts
CHANGED
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
export { authenticateLudicord, initializeLudicordAuthFromEnvironment, useAuthError, useAuthStatus, useLudicordSession, useLudicordAuth, logoutLudicord, } from "./client.js";
|
|
1
|
+
export { authenticateLudicord, initializeLudicordAuthFromEnvironment, useAuthError, useAuthStatus, useLudicordSession, useLudicordAuth, logoutLudicord, renewLudicordSession, } from "./client.js";
|
|
2
|
+
export { installLudicordLaunchIsolation } from "../sessions/launch.js";
|
|
2
3
|
export type { LudicordAuthSnapshot, LudicordAuthStatus, LudicordSession, LudicordSessionUser, } from "./types.js";
|
package/dist/auth/index.js
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
export { authenticateLudicord, initializeLudicordAuthFromEnvironment, useAuthError, useAuthStatus, useLudicordSession, useLudicordAuth, logoutLudicord, } from "./client.js";
|
|
1
|
+
export { authenticateLudicord, initializeLudicordAuthFromEnvironment, useAuthError, useAuthStatus, useLudicordSession, useLudicordAuth, logoutLudicord, renewLudicordSession, } from "./client.js";
|
|
2
|
+
export { installLudicordLaunchIsolation } from "../sessions/launch.js";
|
package/dist/auth/server.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { Router } from "express";
|
|
2
2
|
import type { LudicordSessionDataStore } from "../sessions/data-store.js";
|
|
3
|
+
import type { LudicordEphemeralTokenStore } from "../sessions/ephemeral-store.js";
|
|
3
4
|
export interface LudicordAuthServerOptions {
|
|
4
5
|
readonly clientId?: string;
|
|
5
6
|
readonly clientSecret?: string;
|
|
@@ -7,9 +8,11 @@ export interface LudicordAuthServerOptions {
|
|
|
7
8
|
readonly production?: boolean;
|
|
8
9
|
readonly fetch?: typeof fetch;
|
|
9
10
|
readonly now?: () => number;
|
|
10
|
-
readonly activityInstanceVerification?: boolean;
|
|
11
|
+
readonly activityInstanceVerification?: boolean | "auto";
|
|
11
12
|
readonly botToken?: string;
|
|
12
13
|
readonly activityInstanceCacheTtlMs?: number;
|
|
13
14
|
readonly sessionDataStore?: LudicordSessionDataStore;
|
|
15
|
+
/** Shared one-time token storage for load-balanced OAuth flows. */
|
|
16
|
+
readonly ephemeralTokenStore?: LudicordEphemeralTokenStore;
|
|
14
17
|
}
|
|
15
18
|
export declare function createLudicordAuthRouter(options?: LudicordAuthServerOptions): Router;
|