-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Expand file tree
/
Copy pathapp.ts
More file actions
262 lines (234 loc) · 7.38 KB
/
app.ts
File metadata and controls
262 lines (234 loc) · 7.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
import crypto from "node:crypto";
import {
ChannelType,
type Content,
createMessageMemory,
type IAgentRuntime,
type Memory,
type MessageProcessingResult,
type Service,
stringToUuid,
type UUID,
} from "@elizaos/core";
import express, { type Express, type Request, type Response } from "express";
import { v4 as uuidv4 } from "uuid";
const ROBLOX_SERVICE_NAME = "roblox";
type RobloxMessageService = Service & {
sendMessage: (agentId: UUID, message: string) => Promise<unknown>;
};
type RobloxChatRequestBody = {
playerId: number;
playerName: string;
text: string;
placeId?: string;
jobId?: string;
};
type RobloxChatResponseBody = {
reply: string;
agentName: string;
};
type RequestWithRawBody = Request<object, object, RobloxChatRequestBody> & {
rawBody?: string;
};
type HeaderReader = {
header: (name: string) => string | undefined;
rawBody?: string;
};
export type RuntimeLike = {
agentId: UUID;
character: { name?: string };
ensureConnection: (args: {
entityId: UUID;
roomId: UUID;
worldId: UUID;
userName: string;
source: string;
channelId: string;
type: ChannelType;
}) => Promise<void>;
messageService: {
handleMessage: (
runtime: IAgentRuntime,
message: Memory,
callback?: (content: Content) => Promise<Memory[]>,
) => Promise<MessageProcessingResult>;
} | null;
getService: <T extends Service>(serviceName: string) => T | null;
};
function timingSafeEqual(a: string, b: string): boolean {
const aBuf = Buffer.from(a);
const bBuf = Buffer.from(b);
if (aBuf.length !== bBuf.length) return false;
return crypto.timingSafeEqual(aBuf, bBuf);
}
function verifySharedSecret(req: HeaderReader, sharedSecret: string): boolean {
if (!sharedSecret) return true;
const headerSecret = req.header("x-eliza-secret") ?? "";
if (headerSecret && timingSafeEqual(headerSecret, sharedSecret)) return true;
// Optional HMAC mode:
// x-eliza-signature: sha256=<hex(hmac_sha256(secret, rawBody))>
const sig = req.header("x-eliza-signature") ?? "";
if (!sig.startsWith("sha256=")) return false;
const rawBody = req.rawBody ?? "";
const expected =
"sha256=" +
crypto.createHmac("sha256", sharedSecret).update(rawBody).digest("hex");
return timingSafeEqual(sig, expected);
}
function assertValidChatBody(body: RobloxChatRequestBody): void {
if (!Number.isFinite(body.playerId))
throw new Error("playerId must be a number");
if (!body.playerName || typeof body.playerName !== "string")
throw new Error("playerName must be a string");
if (!body.text || typeof body.text !== "string")
throw new Error("text must be a string");
}
const RATE_LIMIT_WINDOW_MS = 60_000;
const RATE_LIMIT_MAX_REQUESTS = 60;
function createRateLimiter() {
const buckets = new Map<string, { count: number; resetAt: number }>();
return function rateLimit(ip: string): boolean {
const now = Date.now();
const bucket = buckets.get(ip);
if (!bucket || bucket.resetAt <= now) {
buckets.set(ip, { count: 1, resetAt: now + RATE_LIMIT_WINDOW_MS });
return true;
}
if (bucket.count >= RATE_LIMIT_MAX_REQUESTS) {
return false;
}
bucket.count += 1;
return true;
};
}
export function createRobloxBridgeApp(
runtime: RuntimeLike,
sharedSecret: string,
): Express {
const app = express();
app.use(
express.json({
verify: (req, _res, buf) => {
(req as RequestWithRawBody).rawBody = buf.toString("utf8");
},
}),
);
const checkChatRateLimit = createRateLimiter();
app.get("/health", (_req: Request, res: Response) => {
res.json({ status: "ok" });
});
const debugEnabled =
process.env.DEBUG_ROBLOX_BRIDGE?.toLowerCase() === "true";
if (debugEnabled) {
app.get("/debug-env", (_req: Request, res: Response) => {
res.json({
DEBUG_ROBLOX_BRIDGE: process.env.DEBUG_ROBLOX_BRIDGE ?? null,
ROBLOX_ECHO_TO_GAME: process.env.ROBLOX_ECHO_TO_GAME ?? null,
});
});
}
app.post(
"/roblox/chat",
async (
req: Request<object, object, RobloxChatRequestBody>,
res: Response,
) => {
try {
const clientIp = req.ip ?? req.socket.remoteAddress ?? "unknown";
if (!checkChatRateLimit(clientIp)) {
res.status(429).json({ error: "Too Many Requests" });
return;
}
const rawReq = req as RequestWithRawBody;
if (!verifySharedSecret(rawReq, sharedSecret)) {
res.status(401).json({ error: "Unauthorized" });
return;
}
const body = req.body;
assertValidChatBody(body);
const userId = stringToUuid(`roblox:user:${body.playerId}`);
const roomId = stringToUuid(`roblox:job:${body.jobId ?? "unknown"}`);
const worldId = stringToUuid(
`roblox:universe:${process.env.ROBLOX_UNIVERSE_ID ?? "unknown"}`,
);
await runtime.ensureConnection({
entityId: userId,
roomId,
worldId,
userName: body.playerName,
source: "roblox",
channelId: "roblox_chat",
type: ChannelType.DM,
});
const message = createMessageMemory({
id: uuidv4() as UUID,
entityId: userId,
roomId,
content: {
text: body.text,
source: "roblox_chat",
channelType: ChannelType.DM,
},
});
if (!runtime.messageService) {
res.status(500).json({
error:
"Runtime message service not initialized. Ensure runtime.initialize() was called.",
});
return;
}
let reply = "";
const result = await runtime.messageService.handleMessage(
runtime as IAgentRuntime,
message,
async (content) => {
if (content?.text) reply += content.text;
return [];
},
);
if (!reply.trim() && result.responseContent?.text) {
reply = result.responseContent.text;
}
// Optional: echo the agent reply back into Roblox via Open Cloud publish
// (Roblox servers subscribe and display it).
if (process.env.ROBLOX_ECHO_TO_GAME?.toLowerCase() === "true") {
const svc =
runtime.getService<RobloxMessageService>(ROBLOX_SERVICE_NAME);
if (svc) {
await svc.sendMessage(
runtime.agentId,
reply.trim() || "(no response)",
);
}
}
const response: RobloxChatResponseBody = {
reply: reply.trim() || "(no response)",
agentName: runtime.character.name ?? "Agent",
};
if (debugEnabled) {
res.json({
...response,
debug: {
didRespond: result.didRespond,
mode: result.mode ?? "none",
hasResponseContent: result.responseContent !== null,
responseContentText:
typeof result.responseContent?.text === "string"
? result.responseContent.text
: null,
actions: Array.isArray(result.responseContent?.actions)
? result.responseContent.actions
: null,
},
});
} else {
res.json(response);
}
} catch (error) {
const msg = error instanceof Error ? error.message : "Unknown error";
res.status(400).json({ error: msg });
}
},
);
return app;
}