@colyseus/core 0.18.5 → 0.18.6
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/build/router/index.cjs
CHANGED
|
@@ -41,6 +41,8 @@ __export(router_exports, {
|
|
|
41
41
|
toNodeHandler: () => import_node.toNodeHandler
|
|
42
42
|
});
|
|
43
43
|
module.exports = __toCommonJS(router_exports);
|
|
44
|
+
var import_promises = __toESM(require("node:fs/promises"), 1);
|
|
45
|
+
var import_node_path = __toESM(require("node:path"), 1);
|
|
44
46
|
var import_node_crypto = require("node:crypto");
|
|
45
47
|
var import_better_call = require("@colyseus/better-call");
|
|
46
48
|
var import_node = require("@colyseus/better-call/node");
|
|
@@ -179,7 +181,8 @@ function dualModeEndpoints(endpoints, opts) {
|
|
|
179
181
|
) : endpoints;
|
|
180
182
|
const specificRouter = createRouter(specificEndpoints);
|
|
181
183
|
const specificHandler = (0, import_node.toNodeHandler)(specificRouter.handler);
|
|
182
|
-
const
|
|
184
|
+
const buildMiddleware = opts.buildMiddleware ?? panelMiddleware(opts.prefix ?? "", opts.staticDir);
|
|
185
|
+
const middleware = buildMiddleware({
|
|
183
186
|
specificRouter,
|
|
184
187
|
specificHandler,
|
|
185
188
|
fullRouter,
|
|
@@ -187,6 +190,49 @@ function dualModeEndpoints(endpoints, opts) {
|
|
|
187
190
|
});
|
|
188
191
|
return Object.assign(middleware, endpoints);
|
|
189
192
|
}
|
|
193
|
+
function panelMiddleware(prefix, staticDir) {
|
|
194
|
+
const staticRoot = staticDir && import_node_path.default.resolve(staticDir);
|
|
195
|
+
return ({ specificRouter, specificHandler, fullHandler }) => (req, res, next) => {
|
|
196
|
+
const r = req;
|
|
197
|
+
const raw = r.url ?? "";
|
|
198
|
+
const q = raw.indexOf("?");
|
|
199
|
+
const url = q < 0 ? raw : raw.slice(0, q);
|
|
200
|
+
const query = q < 0 ? "" : raw.slice(q);
|
|
201
|
+
const dispatchPath = r.baseUrl ? prefix + url : url;
|
|
202
|
+
if (dispatchPath === prefix || dispatchPath === `${prefix}/`) {
|
|
203
|
+
const original = (r.originalUrl ?? raw).split("?")[0];
|
|
204
|
+
if (r.method === "GET" && !original.endsWith("/")) {
|
|
205
|
+
res.writeHead(302, { location: `${original}/${query}` });
|
|
206
|
+
res.end();
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
const dispatch = (handler) => {
|
|
211
|
+
const wrapped = Object.create(req, {
|
|
212
|
+
url: { value: dispatchPath + query, enumerable: true, configurable: true },
|
|
213
|
+
baseUrl: { value: "", enumerable: true, configurable: true },
|
|
214
|
+
originalUrl: { value: dispatchPath + query, enumerable: true, configurable: true }
|
|
215
|
+
});
|
|
216
|
+
handler(wrapped, res).catch(next);
|
|
217
|
+
};
|
|
218
|
+
const route = specificRouter.findRoute(r.method ?? "GET", dispatchPath);
|
|
219
|
+
if (route && (!route.data?.path?.endsWith("/") || dispatchPath.endsWith("/"))) {
|
|
220
|
+
return dispatch(specificHandler);
|
|
221
|
+
}
|
|
222
|
+
if (r.method !== "GET" || !staticRoot || !dispatchPath.startsWith(prefix)) {
|
|
223
|
+
return next();
|
|
224
|
+
}
|
|
225
|
+
const rel = dispatchPath.slice(prefix.length).replace(/^\/+/, "");
|
|
226
|
+
if (!rel || rel.includes("..")) {
|
|
227
|
+
return next();
|
|
228
|
+
}
|
|
229
|
+
const filePath = import_node_path.default.resolve(staticRoot, rel);
|
|
230
|
+
if (!filePath.startsWith(staticRoot + import_node_path.default.sep)) {
|
|
231
|
+
return next();
|
|
232
|
+
}
|
|
233
|
+
import_promises.default.stat(filePath).then((stat) => stat.isFile() ? dispatch(fullHandler) : next()).catch(() => next());
|
|
234
|
+
};
|
|
235
|
+
}
|
|
190
236
|
// Annotate the CommonJS export names for ESM import in node:
|
|
191
237
|
0 && (module.exports = {
|
|
192
238
|
basicAuth,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/router/index.ts"],
|
|
4
|
-
"sourcesContent": ["import type express from \"express\";\nimport type { IncomingMessage, ServerResponse } from \"http\";\nimport { createHash, timingSafeEqual } from \"node:crypto\";\nimport { type Endpoint, type Router, type RouterConfig, createRouter as createBetterCallRouter, createEndpoint, createMiddleware, APIError } from \"@colyseus/better-call\";\nimport { toNodeHandler, getRequest, setResponse } from \"@colyseus/better-call/node\";\nimport { Transport } from \"../Transport.ts\";\nimport { controller } from \"../matchmaker/controller.ts\";\nimport pkg from \"../../package.json\" with { type: \"json\" };\n\nexport {\n createEndpoint,\n createMiddleware,\n createInternalContext,\n\n // Re-export every type reachable from an inferred type below \u2014 consumers\n // depend on @colyseus/core, not @colyseus/better-call, and cannot name it\n // under pnpm's isolated node_modules (TS2742/TS2883).\n type Router,\n type RouterConfig,\n type Endpoint,\n type EndpointHandler,\n type EndpointOptions,\n type EndpointContext,\n type StrictEndpoint,\n type StandardSchemaV1,\n type MiddlewareOptions,\n type MiddlewareInputContext,\n type CookieOptions,\n type CookiePrefixOptions,\n type Status,\n} from \"@colyseus/better-call\";\n\nexport { toNodeHandler };\n\nexport function bindRouterToTransport(transport: Transport, router: Router, useExpress: boolean) {\n // add default \"/__healthcheck\" endpoint\n router.addEndpoint(createEndpoint(\"/__healthcheck\", { method: \"GET\" }, async (ctx) => {\n return new Response(\"OK\", { status: 200 });\n }));\n\n const server = transport.server;\n\n // check if the server is bound to an express app\n const expressApp: express.Application = (useExpress)\n ? transport.getExpressApp() as express.Application\n // fallback searching for express app in server listeners\n : server?.listeners('request').find((listener: Function) => listener.name === \"app\" && listener['mountpath'] === '/') as express.Application;\n\n // add default \"/\" route, if not provided.\n const hasRootRoute = (\n // check if express app has a root route\n (expressApp && hasExpressRootRoute(expressApp)) ||\n\n // check if router has a root route\n Object.values(router.endpoints).some(endpoint => endpoint.path === \"/\")\n );\n\n if (!hasRootRoute) {\n router.addEndpoint(createEndpoint(\"/\", { method: \"GET\" }, async (ctx) => {\n return new Response(`Colyseus ${pkg.version}`, { status: 200 });\n }));\n }\n\n // use custom bindRouter method if provided\n if (!server && transport.bindRouter) {\n transport.bindRouter(router);\n return;\n }\n\n // which route handler to use\n // (router + fallback to express, or just router)\n let next: any;\n\n if (expressApp) {\n server.removeListener('request', expressApp);\n\n next = async (req: IncomingMessage, res: ServerResponse) => {\n // check if the route is defined in the router\n // if so, use the router handler, otherwise fallback to express\n if (router.findRoute(req.method, req.url.split('?')[0]) !== undefined) {\n const protocol = req.headers[\"x-forwarded-proto\"] || ((req.socket as any).encrypted ? \"https\" : \"http\");\n const base = `${protocol}://${req.headers[\":authority\"] || req.headers.host}`;\n const response = await router.handler(getRequest({ base, request: req }));\n return setResponse(res, response);\n\n } else {\n return expressApp['handle'](req, res);\n }\n };\n\n } else {\n next = toNodeHandler(router.handler);\n }\n\n // handle cors headers for all requests by default\n server.prependListener('request', (req: IncomingMessage, res: ServerResponse) => {\n const corsHeaders = {\n ...controller.DEFAULT_CORS_HEADERS,\n ...controller.getCorsHeaders(new Headers(req.headers as any)),\n };\n\n if (req.method === \"OPTIONS\") {\n res.writeHead(204, corsHeaders);\n res.end();\n return;\n }\n\n Object.entries(corsHeaders).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n\n next(req, res);\n });\n}\n\n/**\n * Whether the express app already handles the root route, in which case\n * Colyseus must not register its own default \"/\" endpoint over it.\n */\nfunction hasExpressRootRoute(expressApp: express.Application) {\n return expressRouterStack(expressApp).some((layer: any) =>\n layer.match('/') && !['query', 'expressInit'].includes(layer.name));\n}\n\n/**\n * The app's router stack, or an empty stack if it has no routes yet.\n *\n * express v5 exposes the router as `app.router`; v4 exposes it as `app._router`\n * and only creates it once the first route/middleware is registered.\n */\nfunction expressRouterStack(expressApp: express.Application): any[] {\n const app = expressApp as any;\n\n if (app?._router?.stack) {\n return app._router.stack;\n }\n\n try {\n return app?.router?.stack ?? [];\n } catch (e) {\n return []; // express v4 throws on `app.router` \u2014 no routes registered\n }\n}\n\nexport function createRouter<\n E extends Record<string, Endpoint>,\n Config extends RouterConfig\n>(endpoints: E, config: Config = {} as Config) {\n const onError = config?.onError;\n return createBetterCallRouter({ ...endpoints }, {\n // better-call's /api/reference page dumps the full API surface\n // unauthenticated \u2014 opt back in by passing `openapi` explicitly.\n openapi: { disabled: true },\n ...config,\n // Otherwise a malformed body is a 500 plus a stack trace on stderr: log\n // noise any anonymous client can trigger at will. Matched on the message\n // because `onError` receives no request context to test against.\n onError: async (error: unknown) => (error instanceof SyntaxError && error.message.includes('JSON'))\n ? Response.json({ error: 'malformed request body' }, { status: 400 })\n : await onError?.(error),\n });\n}\n\nexport interface BasicAuthOptions {\n /** username \u2192 password. The common static case. */\n users?: Record<string, string>;\n /** Custom validator (e.g. DB-backed). Takes precedence over `users`. */\n validate?: (username: string, password: string) => boolean | Promise<boolean>;\n /** Realm shown in the browser prompt. Default 'Restricted'. */\n realm?: string;\n}\n\n/**\n * HTTP Basic Auth middleware. Drop into any endpoint's `use:` slot to gate\n * it behind a browser credentials prompt:\n *\n * playground({ use: [basicAuth({ users: { admin: 's3cret' } })] })\n */\nexport function basicAuth(opts: BasicAuthOptions) {\n const { users, validate } = opts;\n if (!users && !validate) {\n throw new Error('[basicAuth] provide `users` or `validate`');\n }\n // Realm is interpolated into a header \u2014 strip `\"` so it can't break out.\n const challenge = `Basic realm=\"${(opts.realm ?? 'Restricted').replace(/\"/g, '')}\", charset=\"UTF-8\"`;\n\n return createMiddleware(async (ctx) => {\n const creds = parseBasicHeader(ctx.getHeader('authorization'));\n const ok = !!creds && (validate\n ? await validate(creds.username, creds.password)\n : staticCheck(users!, creds.username, creds.password));\n if (!ok) {\n throw new APIError(401, { message: 'authentication required' }, { 'WWW-Authenticate': challenge });\n }\n });\n}\n\nfunction parseBasicHeader(header: string | null | undefined) {\n if (!header) { return null; }\n const sep = header.indexOf(' ');\n if (sep < 0 || header.slice(0, sep).toLowerCase() !== 'basic') { return null; }\n let decoded: string;\n try { decoded = Buffer.from(header.slice(sep + 1), 'base64').toString('utf8'); } catch { return null; }\n const colon = decoded.indexOf(':');\n if (colon < 0) { return null; }\n return { username: decoded.slice(0, colon), password: decoded.slice(colon + 1) };\n}\n\nfunction staticCheck(users: Record<string, string>, username: string, password: string): boolean {\n const expected = Object.prototype.hasOwnProperty.call(users, username) ? users[username] : undefined;\n // Compare even for an unknown user so reject timing doesn't reveal which\n // usernames exist.\n return safeEqual(password, expected ?? '\\0') && expected !== undefined;\n}\n\n// Hash both sides first: equalizes length (timingSafeEqual throws on a\n// length mismatch, which would itself leak the secret's length).\nfunction safeEqual(a: string, b: string): boolean {\n return timingSafeEqual(\n createHash('sha256').update(a).digest(),\n createHash('sha256').update(b).digest(),\n );\n}\n\n// ---------------------------------------------------------------------------\n// dualModeEndpoints \u2014 shared express-compat layer for @colyseus/admin,\n// @colyseus/monitor, @colyseus/playground. Builds the two local routers\n// (specific = no catch-all, full = everything) and the matching node\n// handlers, then packages the express middleware so the return value works\n// both as `{...spread}` into createRouter AND as `app.use(\"/\", x)` middleware.\n// ---------------------------------------------------------------------------\n\nexport type ExpressMiddleware = (\n req: IncomingMessage,\n res: ServerResponse,\n next: (err?: any) => void,\n) => void;\n\nexport type NodeHandler = (req: IncomingMessage, res: ServerResponse) => Promise<void>;\n\nexport interface DualModeHelpers {\n specificRouter: Router;\n specificHandler: NodeHandler;\n fullRouter: Router;\n fullHandler: NodeHandler;\n}\n\nexport function dualModeEndpoints<E extends Record<string, Endpoint>>(\n endpoints: E,\n opts: {\n /** Key in `endpoints` whose path is a catch-all. Excluded from `specificRouter` so it doesn't eat fall-through decisions. */\n catchAllKey?: keyof E;\n /** Build the express middleware given the pre-built routers + node handlers. */\n buildMiddleware: (helpers: DualModeHelpers) => ExpressMiddleware;\n },\n): ExpressMiddleware & E {\n const fullRouter = createRouter(endpoints);\n const fullHandler = toNodeHandler(fullRouter.handler) as NodeHandler;\n\n const specificEndpoints = opts.catchAllKey\n ? Object.fromEntries(\n Object.entries(endpoints).filter(([k]) => k !== opts.catchAllKey),\n ) as Partial<E>\n : endpoints;\n const specificRouter = createRouter(specificEndpoints as E);\n const specificHandler = toNodeHandler(specificRouter.handler) as NodeHandler;\n\n const middleware = opts.buildMiddleware({\n specificRouter, specificHandler, fullRouter, fullHandler,\n });\n return Object.assign(middleware, endpoints) as ExpressMiddleware & E;\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,yBAA4C;AAC5C,yBAAkJ;AAClJ,kBAAuD;AACvD,uBAA0B;AAC1B,wBAA2B;AAC3B,qBAAgB;AAEhB,IAAAA,sBAqBO;AAIA,SAAS,sBAAsB,WAAsB,QAAgB,YAAqB;AAE/F,SAAO,gBAAY,mCAAe,kBAAkB,EAAE,QAAQ,MAAM,GAAG,OAAO,QAAQ;AACpF,WAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC3C,CAAC,CAAC;AAEF,QAAM,SAAS,UAAU;AAGzB,QAAM,aAAmC,aACrC,UAAU,cAAc,IAExB,QAAQ,UAAU,SAAS,EAAE,KAAK,CAAC,aAAuB,SAAS,SAAS,SAAS,SAAS,WAAW,MAAM,GAAG;AAGtH,QAAM;AAAA;AAAA,IAEH,cAAc,oBAAoB,UAAU;AAAA,IAG7C,OAAO,OAAO,OAAO,SAAS,EAAE,KAAK,cAAY,SAAS,SAAS,GAAG;AAAA;AAGxE,MAAI,CAAC,cAAc;AACjB,WAAO,gBAAY,mCAAe,KAAK,EAAE,QAAQ,MAAM,GAAG,OAAO,QAAQ;AACvE,aAAO,IAAI,SAAS,YAAY,eAAAC,QAAI,OAAO,IAAI,EAAE,QAAQ,IAAI,CAAC;AAAA,IAChE,CAAC,CAAC;AAAA,EACJ;AAGA,MAAI,CAAC,UAAU,UAAU,YAAY;AACnC,cAAU,WAAW,MAAM;AAC3B;AAAA,EAC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M,MAAM,OAAO,QAAQ,GAAG;AAC9B,MAAI,MAAM,KAAK,OAAO,MAAM,GAAG,GAAG,EAAE,YAAY,MAAM,SAAS;AAAE,WAAO;AAAA,EAAM;AAC9E,MAAI;AACJ,MAAI;AAAE,cAAU,OAAO,KAAK,OAAO,MAAM,MAAM,CAAC,GAAG,QAAQ,EAAE,SAAS,MAAM;AAAA,EAAG,QAAQ;AAAE,WAAO;AAAA,EAAM;AACtG,QAAM,QAAQ,QAAQ,QAAQ,GAAG;AACjC,MAAI,QAAQ,GAAG;AAAE,WAAO;AAAA,EAAM;AAC9B,SAAO,EAAE,UAAU,QAAQ,MAAM,GAAG,KAAK,GAAG,UAAU,QAAQ,MAAM,QAAQ,CAAC,EAAE;AACjF;AAEA,SAAS,YAAY,OAA+B,UAAkB,UAA2B;AAC/F,QAAM,WAAW,OAAO,UAAU,eAAe,KAAK,OAAO,QAAQ,IAAI,MAAM,QAAQ,IAAI;AAG3F,SAAO,UAAU,UAAU,YAAY,IAAI,KAAK,aAAa;AAC/D;AAIA,SAAS,UAAU,GAAW,GAAoB;AAChD,aAAO;AAAA,QACL,+BAAW,QAAQ,EAAE,OAAO,CAAC,EAAE,OAAO;AAAA,QACtC,+BAAW,QAAQ,EAAE,OAAO,CAAC,EAAE,OAAO;AAAA,EACxC;AACF;AAyBO,SAAS,kBACd,WACA,
|
|
6
|
-
"names": ["import_better_call", "pkg", "createBetterCallRouter"]
|
|
4
|
+
"sourcesContent": ["import type express from \"express\";\nimport type { IncomingMessage, ServerResponse } from \"http\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createHash, timingSafeEqual } from \"node:crypto\";\nimport { type Endpoint, type Router, type RouterConfig, createRouter as createBetterCallRouter, createEndpoint, createMiddleware, APIError } from \"@colyseus/better-call\";\nimport { toNodeHandler, getRequest, setResponse } from \"@colyseus/better-call/node\";\nimport { Transport } from \"../Transport.ts\";\nimport { controller } from \"../matchmaker/controller.ts\";\nimport pkg from \"../../package.json\" with { type: \"json\" };\n\nexport {\n createEndpoint,\n createMiddleware,\n createInternalContext,\n\n // Re-export every type reachable from an inferred type below \u2014 consumers\n // depend on @colyseus/core, not @colyseus/better-call, and cannot name it\n // under pnpm's isolated node_modules (TS2742/TS2883).\n type Router,\n type RouterConfig,\n type Endpoint,\n type EndpointHandler,\n type EndpointOptions,\n type EndpointContext,\n type StrictEndpoint,\n type StandardSchemaV1,\n type MiddlewareOptions,\n type MiddlewareInputContext,\n type CookieOptions,\n type CookiePrefixOptions,\n type Status,\n} from \"@colyseus/better-call\";\n\nexport { toNodeHandler };\n\nexport function bindRouterToTransport(transport: Transport, router: Router, useExpress: boolean) {\n // add default \"/__healthcheck\" endpoint\n router.addEndpoint(createEndpoint(\"/__healthcheck\", { method: \"GET\" }, async (ctx) => {\n return new Response(\"OK\", { status: 200 });\n }));\n\n const server = transport.server;\n\n // check if the server is bound to an express app\n const expressApp: express.Application = (useExpress)\n ? transport.getExpressApp() as express.Application\n // fallback searching for express app in server listeners\n : server?.listeners('request').find((listener: Function) => listener.name === \"app\" && listener['mountpath'] === '/') as express.Application;\n\n // add default \"/\" route, if not provided.\n const hasRootRoute = (\n // check if express app has a root route\n (expressApp && hasExpressRootRoute(expressApp)) ||\n\n // check if router has a root route\n Object.values(router.endpoints).some(endpoint => endpoint.path === \"/\")\n );\n\n if (!hasRootRoute) {\n router.addEndpoint(createEndpoint(\"/\", { method: \"GET\" }, async (ctx) => {\n return new Response(`Colyseus ${pkg.version}`, { status: 200 });\n }));\n }\n\n // use custom bindRouter method if provided\n if (!server && transport.bindRouter) {\n transport.bindRouter(router);\n return;\n }\n\n // which route handler to use\n // (router + fallback to express, or just router)\n let next: any;\n\n if (expressApp) {\n server.removeListener('request', expressApp);\n\n next = async (req: IncomingMessage, res: ServerResponse) => {\n // check if the route is defined in the router\n // if so, use the router handler, otherwise fallback to express\n if (router.findRoute(req.method, req.url.split('?')[0]) !== undefined) {\n const protocol = req.headers[\"x-forwarded-proto\"] || ((req.socket as any).encrypted ? \"https\" : \"http\");\n const base = `${protocol}://${req.headers[\":authority\"] || req.headers.host}`;\n const response = await router.handler(getRequest({ base, request: req }));\n return setResponse(res, response);\n\n } else {\n return expressApp['handle'](req, res);\n }\n };\n\n } else {\n next = toNodeHandler(router.handler);\n }\n\n // handle cors headers for all requests by default\n server.prependListener('request', (req: IncomingMessage, res: ServerResponse) => {\n const corsHeaders = {\n ...controller.DEFAULT_CORS_HEADERS,\n ...controller.getCorsHeaders(new Headers(req.headers as any)),\n };\n\n if (req.method === \"OPTIONS\") {\n res.writeHead(204, corsHeaders);\n res.end();\n return;\n }\n\n Object.entries(corsHeaders).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n\n next(req, res);\n });\n}\n\n/**\n * Whether the express app already handles the root route, in which case\n * Colyseus must not register its own default \"/\" endpoint over it.\n */\nfunction hasExpressRootRoute(expressApp: express.Application) {\n return expressRouterStack(expressApp).some((layer: any) =>\n layer.match('/') && !['query', 'expressInit'].includes(layer.name));\n}\n\n/**\n * The app's router stack, or an empty stack if it has no routes yet.\n *\n * express v5 exposes the router as `app.router`; v4 exposes it as `app._router`\n * and only creates it once the first route/middleware is registered.\n */\nfunction expressRouterStack(expressApp: express.Application): any[] {\n const app = expressApp as any;\n\n if (app?._router?.stack) {\n return app._router.stack;\n }\n\n try {\n return app?.router?.stack ?? [];\n } catch (e) {\n return []; // express v4 throws on `app.router` \u2014 no routes registered\n }\n}\n\nexport function createRouter<\n E extends Record<string, Endpoint>,\n Config extends RouterConfig\n>(endpoints: E, config: Config = {} as Config) {\n const onError = config?.onError;\n return createBetterCallRouter({ ...endpoints }, {\n // better-call's /api/reference page dumps the full API surface\n // unauthenticated \u2014 opt back in by passing `openapi` explicitly.\n openapi: { disabled: true },\n ...config,\n // Otherwise a malformed body is a 500 plus a stack trace on stderr: log\n // noise any anonymous client can trigger at will. Matched on the message\n // because `onError` receives no request context to test against.\n onError: async (error: unknown) => (error instanceof SyntaxError && error.message.includes('JSON'))\n ? Response.json({ error: 'malformed request body' }, { status: 400 })\n : await onError?.(error),\n });\n}\n\nexport interface BasicAuthOptions {\n /** username \u2192 password. The common static case. */\n users?: Record<string, string>;\n /** Custom validator (e.g. DB-backed). Takes precedence over `users`. */\n validate?: (username: string, password: string) => boolean | Promise<boolean>;\n /** Realm shown in the browser prompt. Default 'Restricted'. */\n realm?: string;\n}\n\n/**\n * HTTP Basic Auth middleware. Drop into any endpoint's `use:` slot to gate\n * it behind a browser credentials prompt:\n *\n * playground({ use: [basicAuth({ users: { admin: 's3cret' } })] })\n */\nexport function basicAuth(opts: BasicAuthOptions) {\n const { users, validate } = opts;\n if (!users && !validate) {\n throw new Error('[basicAuth] provide `users` or `validate`');\n }\n // Realm is interpolated into a header \u2014 strip `\"` so it can't break out.\n const challenge = `Basic realm=\"${(opts.realm ?? 'Restricted').replace(/\"/g, '')}\", charset=\"UTF-8\"`;\n\n return createMiddleware(async (ctx) => {\n const creds = parseBasicHeader(ctx.getHeader('authorization'));\n const ok = !!creds && (validate\n ? await validate(creds.username, creds.password)\n : staticCheck(users!, creds.username, creds.password));\n if (!ok) {\n throw new APIError(401, { message: 'authentication required' }, { 'WWW-Authenticate': challenge });\n }\n });\n}\n\nfunction parseBasicHeader(header: string | null | undefined) {\n if (!header) { return null; }\n const sep = header.indexOf(' ');\n if (sep < 0 || header.slice(0, sep).toLowerCase() !== 'basic') { return null; }\n let decoded: string;\n try { decoded = Buffer.from(header.slice(sep + 1), 'base64').toString('utf8'); } catch { return null; }\n const colon = decoded.indexOf(':');\n if (colon < 0) { return null; }\n return { username: decoded.slice(0, colon), password: decoded.slice(colon + 1) };\n}\n\nfunction staticCheck(users: Record<string, string>, username: string, password: string): boolean {\n const expected = Object.prototype.hasOwnProperty.call(users, username) ? users[username] : undefined;\n // Compare even for an unknown user so reject timing doesn't reveal which\n // usernames exist.\n return safeEqual(password, expected ?? '\\0') && expected !== undefined;\n}\n\n// Hash both sides first: equalizes length (timingSafeEqual throws on a\n// length mismatch, which would itself leak the secret's length).\nfunction safeEqual(a: string, b: string): boolean {\n return timingSafeEqual(\n createHash('sha256').update(a).digest(),\n createHash('sha256').update(b).digest(),\n );\n}\n\n// ---------------------------------------------------------------------------\n// dualModeEndpoints \u2014 shared express-compat layer for @colyseus/admin,\n// @colyseus/monitor, @colyseus/playground. Builds the two local routers\n// (specific = no catch-all, full = everything) and the matching node\n// handlers, then packages the express middleware so the return value works\n// both as `{...spread}` into createRouter AND as `app.use(\"/\", x)` middleware.\n// ---------------------------------------------------------------------------\n\nexport type ExpressMiddleware = (\n req: IncomingMessage,\n res: ServerResponse,\n next: (err?: any) => void,\n) => void;\n\nexport type NodeHandler = (req: IncomingMessage, res: ServerResponse) => Promise<void>;\n\nexport interface DualModeHelpers {\n specificRouter: Router;\n specificHandler: NodeHandler;\n fullRouter: Router;\n fullHandler: NodeHandler;\n}\n\nexport function dualModeEndpoints<E extends Record<string, Endpoint>>(\n endpoints: E,\n opts: {\n /** Key in `endpoints` whose path is a catch-all. Excluded from `specificRouter` so it doesn't eat fall-through decisions. */\n catchAllKey?: keyof E;\n /** Endpoint-path prefix baked into `endpoints` (`''`, `'/monitor'`). Used by the default middleware to rebase path mounts. */\n prefix?: string;\n /** SPA dist dir \u2014 the default middleware dispatches catch-all requests only for files that exist here. */\n staticDir?: string;\n /** Build a custom express middleware given the pre-built routers + node handlers. Omit for the default SPA-panel middleware. */\n buildMiddleware?: (helpers: DualModeHelpers) => ExpressMiddleware;\n },\n): ExpressMiddleware & E {\n const fullRouter = createRouter(endpoints);\n const fullHandler = toNodeHandler(fullRouter.handler) as NodeHandler;\n\n const specificEndpoints = opts.catchAllKey\n ? Object.fromEntries(\n Object.entries(endpoints).filter(([k]) => k !== opts.catchAllKey),\n ) as Partial<E>\n : endpoints;\n const specificRouter = createRouter(specificEndpoints as E);\n const specificHandler = toNodeHandler(specificRouter.handler) as NodeHandler;\n\n const buildMiddleware = opts.buildMiddleware ?? panelMiddleware(opts.prefix ?? '', opts.staticDir);\n const middleware = buildMiddleware({\n specificRouter, specificHandler, fullRouter, fullHandler,\n });\n return Object.assign(middleware, endpoints) as ExpressMiddleware & E;\n}\n\n/**\n * Default express middleware for a single-prefix SPA panel (monitor,\n * playground). Express and the endpoint map use different coordinates: a path\n * mount strips its prefix into `req.baseUrl`, while the endpoints keep the\n * configured `prefix` baked into their paths. This rebases every request onto\n * the endpoint namespace, so the panel works at any mount path \u2014 `prefix` only\n * matters in router mode and at root mounts.\n */\nfunction panelMiddleware(prefix: string, staticDir?: string) {\n const staticRoot = staticDir && path.resolve(staticDir);\n return ({ specificRouter, specificHandler, fullHandler }: DualModeHelpers): ExpressMiddleware =>\n (req, res, next) => {\n const r = req as IncomingMessage & { baseUrl?: string; originalUrl?: string };\n const raw = r.url ?? '';\n const q = raw.indexOf('?');\n const url = q < 0 ? raw : raw.slice(0, q);\n const query = q < 0 ? '' : raw.slice(q);\n\n // Path mounts arrive stripped (`req.url` is mount-relative); root and\n // pathless mounts arrive unstripped and already match the endpoints.\n const dispatchPath = r.baseUrl ? prefix + url : url;\n\n // Canonicalize the index: the SPA references its assets relatively, so\n // they only resolve from the trailing-slash URL. The browser's address\n // is originalUrl \u2014 302 (not 301: browsers cache 301s across remounts).\n if (dispatchPath === prefix || dispatchPath === `${prefix}/`) {\n const original = (r.originalUrl ?? raw).split('?')[0]!;\n if (r.method === 'GET' && !original.endsWith('/')) {\n res.writeHead(302, { location: `${original}/${query}` });\n res.end();\n return;\n }\n }\n\n const dispatch = (handler: NodeHandler) => {\n // better-call's getRequest resolves the path as baseUrl + url\n const wrapped = Object.create(req, {\n url: { value: dispatchPath + query, enumerable: true, configurable: true },\n baseUrl: { value: '', enumerable: true, configurable: true },\n originalUrl: { value: dispatchPath + query, enumerable: true, configurable: true },\n });\n handler(wrapped as any, res).catch(next);\n };\n\n const route = specificRouter.findRoute(r.method ?? 'GET', dispatchPath);\n // rou3 normalizes trailing slashes in findRoute but processRequest\n // exact-matches \u2014 only trust the hit when the slashes agree.\n if (route && (!route.data?.path?.endsWith('/') || dispatchPath.endsWith('/'))) {\n return dispatch(specificHandler);\n }\n\n // Asset request \u2014 only delegate when the file exists on disk, so the\n // catch-all's SPA fallback can't mask sibling express routes.\n if (r.method !== 'GET' || !staticRoot || !dispatchPath.startsWith(prefix)) { return next(); }\n const rel = dispatchPath.slice(prefix.length).replace(/^\\/+/, '');\n if (!rel || rel.includes('..')) { return next(); }\n const filePath = path.resolve(staticRoot, rel);\n if (!filePath.startsWith(staticRoot + path.sep)) { return next(); }\n fs.stat(filePath).then((stat) => stat.isFile() ? dispatch(fullHandler) : next()).catch(() => next());\n };\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,sBAAe;AACf,uBAAiB;AACjB,yBAA4C;AAC5C,yBAAkJ;AAClJ,kBAAuD;AACvD,uBAA0B;AAC1B,wBAA2B;AAC3B,qBAAgB;AAEhB,IAAAA,sBAqBO;AAIA,SAAS,sBAAsB,WAAsB,QAAgB,YAAqB;AAE/F,SAAO,gBAAY,mCAAe,kBAAkB,EAAE,QAAQ,MAAM,GAAG,OAAO,QAAQ;AACpF,WAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC3C,CAAC,CAAC;AAEF,QAAM,SAAS,UAAU;AAGzB,QAAM,aAAmC,aACrC,UAAU,cAAc,IAExB,QAAQ,UAAU,SAAS,EAAE,KAAK,CAAC,aAAuB,SAAS,SAAS,SAAS,SAAS,WAAW,MAAM,GAAG;AAGtH,QAAM;AAAA;AAAA,IAEH,cAAc,oBAAoB,UAAU;AAAA,IAG7C,OAAO,OAAO,OAAO,SAAS,EAAE,KAAK,cAAY,SAAS,SAAS,GAAG;AAAA;AAGxE,MAAI,CAAC,cAAc;AACjB,WAAO,gBAAY,mCAAe,KAAK,EAAE,QAAQ,MAAM,GAAG,OAA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E,OAAO,eAAe,OAAO,YAAY,MAAM,cAAc,KAAK;AAAA,MACnF,CAAC;AACD,cAAQ,SAAgB,GAAG,EAAE,MAAM,IAAI;AAAA,IACzC;AAEA,UAAM,QAAQ,eAAe,UAAU,EAAE,UAAU,OAAO,YAAY;AAGtE,QAAI,UAAU,CAAC,MAAM,MAAM,MAAM,SAAS,GAAG,KAAK,aAAa,SAAS,GAAG,IAAI;AAC7E,aAAO,SAAS,eAAe;AAAA,IACjC;AAIA,QAAI,EAAE,WAAW,SAAS,CAAC,cAAc,CAAC,aAAa,WAAW,MAAM,GAAG;AAAE,aAAO,KAAK;AAAA,IAAG;AAC5F,UAAM,MAAM,aAAa,MAAM,OAAO,MAAM,EAAE,QAAQ,QAAQ,EAAE;AAChE,QAAI,CAAC,OAAO,IAAI,SAAS,IAAI,GAAG;AAAE,aAAO,KAAK;AAAA,IAAG;AACjD,UAAM,WAAW,iBAAAA,QAAK,QAAQ,YAAY,GAAG;AAC7C,QAAI,CAAC,SAAS,WAAW,aAAa,iBAAAA,QAAK,GAAG,GAAG;AAAE,aAAO,KAAK;AAAA,IAAG;AAClE,oBAAAC,QAAG,KAAK,QAAQ,EAAE,KAAK,CAAC,SAAS,KAAK,OAAO,IAAI,SAAS,WAAW,IAAI,KAAK,CAAC,EAAE,MAAM,MAAM,KAAK,CAAC;AAAA,EACrG;AACJ;",
|
|
6
|
+
"names": ["import_better_call", "pkg", "createBetterCallRouter", "path", "fs"]
|
|
7
7
|
}
|
package/build/router/index.d.ts
CHANGED
|
@@ -183,6 +183,10 @@ export interface DualModeHelpers {
|
|
|
183
183
|
export declare function dualModeEndpoints<E extends Record<string, Endpoint>>(endpoints: E, opts: {
|
|
184
184
|
/** Key in `endpoints` whose path is a catch-all. Excluded from `specificRouter` so it doesn't eat fall-through decisions. */
|
|
185
185
|
catchAllKey?: keyof E;
|
|
186
|
-
/**
|
|
187
|
-
|
|
186
|
+
/** Endpoint-path prefix baked into `endpoints` (`''`, `'/monitor'`). Used by the default middleware to rebase path mounts. */
|
|
187
|
+
prefix?: string;
|
|
188
|
+
/** SPA dist dir — the default middleware dispatches catch-all requests only for files that exist here. */
|
|
189
|
+
staticDir?: string;
|
|
190
|
+
/** Build a custom express middleware given the pre-built routers + node handlers. Omit for the default SPA-panel middleware. */
|
|
191
|
+
buildMiddleware?: (helpers: DualModeHelpers) => ExpressMiddleware;
|
|
188
192
|
}): ExpressMiddleware & E;
|
package/build/router/index.mjs
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
// packages/core/src/router/index.ts
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
2
4
|
import { createHash, timingSafeEqual } from "node:crypto";
|
|
3
5
|
import { createRouter as createBetterCallRouter, createEndpoint, createMiddleware, APIError } from "@colyseus/better-call";
|
|
4
6
|
import { toNodeHandler, getRequest, setResponse } from "@colyseus/better-call/node";
|
|
@@ -141,7 +143,8 @@ function dualModeEndpoints(endpoints, opts) {
|
|
|
141
143
|
) : endpoints;
|
|
142
144
|
const specificRouter = createRouter(specificEndpoints);
|
|
143
145
|
const specificHandler = toNodeHandler(specificRouter.handler);
|
|
144
|
-
const
|
|
146
|
+
const buildMiddleware = opts.buildMiddleware ?? panelMiddleware(opts.prefix ?? "", opts.staticDir);
|
|
147
|
+
const middleware = buildMiddleware({
|
|
145
148
|
specificRouter,
|
|
146
149
|
specificHandler,
|
|
147
150
|
fullRouter,
|
|
@@ -149,6 +152,49 @@ function dualModeEndpoints(endpoints, opts) {
|
|
|
149
152
|
});
|
|
150
153
|
return Object.assign(middleware, endpoints);
|
|
151
154
|
}
|
|
155
|
+
function panelMiddleware(prefix, staticDir) {
|
|
156
|
+
const staticRoot = staticDir && path.resolve(staticDir);
|
|
157
|
+
return ({ specificRouter, specificHandler, fullHandler }) => (req, res, next) => {
|
|
158
|
+
const r = req;
|
|
159
|
+
const raw = r.url ?? "";
|
|
160
|
+
const q = raw.indexOf("?");
|
|
161
|
+
const url = q < 0 ? raw : raw.slice(0, q);
|
|
162
|
+
const query = q < 0 ? "" : raw.slice(q);
|
|
163
|
+
const dispatchPath = r.baseUrl ? prefix + url : url;
|
|
164
|
+
if (dispatchPath === prefix || dispatchPath === `${prefix}/`) {
|
|
165
|
+
const original = (r.originalUrl ?? raw).split("?")[0];
|
|
166
|
+
if (r.method === "GET" && !original.endsWith("/")) {
|
|
167
|
+
res.writeHead(302, { location: `${original}/${query}` });
|
|
168
|
+
res.end();
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
const dispatch = (handler) => {
|
|
173
|
+
const wrapped = Object.create(req, {
|
|
174
|
+
url: { value: dispatchPath + query, enumerable: true, configurable: true },
|
|
175
|
+
baseUrl: { value: "", enumerable: true, configurable: true },
|
|
176
|
+
originalUrl: { value: dispatchPath + query, enumerable: true, configurable: true }
|
|
177
|
+
});
|
|
178
|
+
handler(wrapped, res).catch(next);
|
|
179
|
+
};
|
|
180
|
+
const route = specificRouter.findRoute(r.method ?? "GET", dispatchPath);
|
|
181
|
+
if (route && (!route.data?.path?.endsWith("/") || dispatchPath.endsWith("/"))) {
|
|
182
|
+
return dispatch(specificHandler);
|
|
183
|
+
}
|
|
184
|
+
if (r.method !== "GET" || !staticRoot || !dispatchPath.startsWith(prefix)) {
|
|
185
|
+
return next();
|
|
186
|
+
}
|
|
187
|
+
const rel = dispatchPath.slice(prefix.length).replace(/^\/+/, "");
|
|
188
|
+
if (!rel || rel.includes("..")) {
|
|
189
|
+
return next();
|
|
190
|
+
}
|
|
191
|
+
const filePath = path.resolve(staticRoot, rel);
|
|
192
|
+
if (!filePath.startsWith(staticRoot + path.sep)) {
|
|
193
|
+
return next();
|
|
194
|
+
}
|
|
195
|
+
fs.stat(filePath).then((stat) => stat.isFile() ? dispatch(fullHandler) : next()).catch(() => next());
|
|
196
|
+
};
|
|
197
|
+
}
|
|
152
198
|
export {
|
|
153
199
|
basicAuth,
|
|
154
200
|
bindRouterToTransport,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/router/index.ts"],
|
|
4
|
-
"sourcesContent": ["import type express from \"express\";\nimport type { IncomingMessage, ServerResponse } from \"http\";\nimport { createHash, timingSafeEqual } from \"node:crypto\";\nimport { type Endpoint, type Router, type RouterConfig, createRouter as createBetterCallRouter, createEndpoint, createMiddleware, APIError } from \"@colyseus/better-call\";\nimport { toNodeHandler, getRequest, setResponse } from \"@colyseus/better-call/node\";\nimport { Transport } from \"../Transport.ts\";\nimport { controller } from \"../matchmaker/controller.ts\";\nimport pkg from \"../../package.json\" with { type: \"json\" };\n\nexport {\n createEndpoint,\n createMiddleware,\n createInternalContext,\n\n // Re-export every type reachable from an inferred type below \u2014 consumers\n // depend on @colyseus/core, not @colyseus/better-call, and cannot name it\n // under pnpm's isolated node_modules (TS2742/TS2883).\n type Router,\n type RouterConfig,\n type Endpoint,\n type EndpointHandler,\n type EndpointOptions,\n type EndpointContext,\n type StrictEndpoint,\n type StandardSchemaV1,\n type MiddlewareOptions,\n type MiddlewareInputContext,\n type CookieOptions,\n type CookiePrefixOptions,\n type Status,\n} from \"@colyseus/better-call\";\n\nexport { toNodeHandler };\n\nexport function bindRouterToTransport(transport: Transport, router: Router, useExpress: boolean) {\n // add default \"/__healthcheck\" endpoint\n router.addEndpoint(createEndpoint(\"/__healthcheck\", { method: \"GET\" }, async (ctx) => {\n return new Response(\"OK\", { status: 200 });\n }));\n\n const server = transport.server;\n\n // check if the server is bound to an express app\n const expressApp: express.Application = (useExpress)\n ? transport.getExpressApp() as express.Application\n // fallback searching for express app in server listeners\n : server?.listeners('request').find((listener: Function) => listener.name === \"app\" && listener['mountpath'] === '/') as express.Application;\n\n // add default \"/\" route, if not provided.\n const hasRootRoute = (\n // check if express app has a root route\n (expressApp && hasExpressRootRoute(expressApp)) ||\n\n // check if router has a root route\n Object.values(router.endpoints).some(endpoint => endpoint.path === \"/\")\n );\n\n if (!hasRootRoute) {\n router.addEndpoint(createEndpoint(\"/\", { method: \"GET\" }, async (ctx) => {\n return new Response(`Colyseus ${pkg.version}`, { status: 200 });\n }));\n }\n\n // use custom bindRouter method if provided\n if (!server && transport.bindRouter) {\n transport.bindRouter(router);\n return;\n }\n\n // which route handler to use\n // (router + fallback to express, or just router)\n let next: any;\n\n if (expressApp) {\n server.removeListener('request', expressApp);\n\n next = async (req: IncomingMessage, res: ServerResponse) => {\n // check if the route is defined in the router\n // if so, use the router handler, otherwise fallback to express\n if (router.findRoute(req.method, req.url.split('?')[0]) !== undefined) {\n const protocol = req.headers[\"x-forwarded-proto\"] || ((req.socket as any).encrypted ? \"https\" : \"http\");\n const base = `${protocol}://${req.headers[\":authority\"] || req.headers.host}`;\n const response = await router.handler(getRequest({ base, request: req }));\n return setResponse(res, response);\n\n } else {\n return expressApp['handle'](req, res);\n }\n };\n\n } else {\n next = toNodeHandler(router.handler);\n }\n\n // handle cors headers for all requests by default\n server.prependListener('request', (req: IncomingMessage, res: ServerResponse) => {\n const corsHeaders = {\n ...controller.DEFAULT_CORS_HEADERS,\n ...controller.getCorsHeaders(new Headers(req.headers as any)),\n };\n\n if (req.method === \"OPTIONS\") {\n res.writeHead(204, corsHeaders);\n res.end();\n return;\n }\n\n Object.entries(corsHeaders).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n\n next(req, res);\n });\n}\n\n/**\n * Whether the express app already handles the root route, in which case\n * Colyseus must not register its own default \"/\" endpoint over it.\n */\nfunction hasExpressRootRoute(expressApp: express.Application) {\n return expressRouterStack(expressApp).some((layer: any) =>\n layer.match('/') && !['query', 'expressInit'].includes(layer.name));\n}\n\n/**\n * The app's router stack, or an empty stack if it has no routes yet.\n *\n * express v5 exposes the router as `app.router`; v4 exposes it as `app._router`\n * and only creates it once the first route/middleware is registered.\n */\nfunction expressRouterStack(expressApp: express.Application): any[] {\n const app = expressApp as any;\n\n if (app?._router?.stack) {\n return app._router.stack;\n }\n\n try {\n return app?.router?.stack ?? [];\n } catch (e) {\n return []; // express v4 throws on `app.router` \u2014 no routes registered\n }\n}\n\nexport function createRouter<\n E extends Record<string, Endpoint>,\n Config extends RouterConfig\n>(endpoints: E, config: Config = {} as Config) {\n const onError = config?.onError;\n return createBetterCallRouter({ ...endpoints }, {\n // better-call's /api/reference page dumps the full API surface\n // unauthenticated \u2014 opt back in by passing `openapi` explicitly.\n openapi: { disabled: true },\n ...config,\n // Otherwise a malformed body is a 500 plus a stack trace on stderr: log\n // noise any anonymous client can trigger at will. Matched on the message\n // because `onError` receives no request context to test against.\n onError: async (error: unknown) => (error instanceof SyntaxError && error.message.includes('JSON'))\n ? Response.json({ error: 'malformed request body' }, { status: 400 })\n : await onError?.(error),\n });\n}\n\nexport interface BasicAuthOptions {\n /** username \u2192 password. The common static case. */\n users?: Record<string, string>;\n /** Custom validator (e.g. DB-backed). Takes precedence over `users`. */\n validate?: (username: string, password: string) => boolean | Promise<boolean>;\n /** Realm shown in the browser prompt. Default 'Restricted'. */\n realm?: string;\n}\n\n/**\n * HTTP Basic Auth middleware. Drop into any endpoint's `use:` slot to gate\n * it behind a browser credentials prompt:\n *\n * playground({ use: [basicAuth({ users: { admin: 's3cret' } })] })\n */\nexport function basicAuth(opts: BasicAuthOptions) {\n const { users, validate } = opts;\n if (!users && !validate) {\n throw new Error('[basicAuth] provide `users` or `validate`');\n }\n // Realm is interpolated into a header \u2014 strip `\"` so it can't break out.\n const challenge = `Basic realm=\"${(opts.realm ?? 'Restricted').replace(/\"/g, '')}\", charset=\"UTF-8\"`;\n\n return createMiddleware(async (ctx) => {\n const creds = parseBasicHeader(ctx.getHeader('authorization'));\n const ok = !!creds && (validate\n ? await validate(creds.username, creds.password)\n : staticCheck(users!, creds.username, creds.password));\n if (!ok) {\n throw new APIError(401, { message: 'authentication required' }, { 'WWW-Authenticate': challenge });\n }\n });\n}\n\nfunction parseBasicHeader(header: string | null | undefined) {\n if (!header) { return null; }\n const sep = header.indexOf(' ');\n if (sep < 0 || header.slice(0, sep).toLowerCase() !== 'basic') { return null; }\n let decoded: string;\n try { decoded = Buffer.from(header.slice(sep + 1), 'base64').toString('utf8'); } catch { return null; }\n const colon = decoded.indexOf(':');\n if (colon < 0) { return null; }\n return { username: decoded.slice(0, colon), password: decoded.slice(colon + 1) };\n}\n\nfunction staticCheck(users: Record<string, string>, username: string, password: string): boolean {\n const expected = Object.prototype.hasOwnProperty.call(users, username) ? users[username] : undefined;\n // Compare even for an unknown user so reject timing doesn't reveal which\n // usernames exist.\n return safeEqual(password, expected ?? '\\0') && expected !== undefined;\n}\n\n// Hash both sides first: equalizes length (timingSafeEqual throws on a\n// length mismatch, which would itself leak the secret's length).\nfunction safeEqual(a: string, b: string): boolean {\n return timingSafeEqual(\n createHash('sha256').update(a).digest(),\n createHash('sha256').update(b).digest(),\n );\n}\n\n// ---------------------------------------------------------------------------\n// dualModeEndpoints \u2014 shared express-compat layer for @colyseus/admin,\n// @colyseus/monitor, @colyseus/playground. Builds the two local routers\n// (specific = no catch-all, full = everything) and the matching node\n// handlers, then packages the express middleware so the return value works\n// both as `{...spread}` into createRouter AND as `app.use(\"/\", x)` middleware.\n// ---------------------------------------------------------------------------\n\nexport type ExpressMiddleware = (\n req: IncomingMessage,\n res: ServerResponse,\n next: (err?: any) => void,\n) => void;\n\nexport type NodeHandler = (req: IncomingMessage, res: ServerResponse) => Promise<void>;\n\nexport interface DualModeHelpers {\n specificRouter: Router;\n specificHandler: NodeHandler;\n fullRouter: Router;\n fullHandler: NodeHandler;\n}\n\nexport function dualModeEndpoints<E extends Record<string, Endpoint>>(\n endpoints: E,\n opts: {\n /** Key in `endpoints` whose path is a catch-all. Excluded from `specificRouter` so it doesn't eat fall-through decisions. */\n catchAllKey?: keyof E;\n /** Build the express middleware given the pre-built routers + node handlers. */\n buildMiddleware: (helpers: DualModeHelpers) => ExpressMiddleware;\n },\n): ExpressMiddleware & E {\n const fullRouter = createRouter(endpoints);\n const fullHandler = toNodeHandler(fullRouter.handler) as NodeHandler;\n\n const specificEndpoints = opts.catchAllKey\n ? Object.fromEntries(\n Object.entries(endpoints).filter(([k]) => k !== opts.catchAllKey),\n ) as Partial<E>\n : endpoints;\n const specificRouter = createRouter(specificEndpoints as E);\n const specificHandler = toNodeHandler(specificRouter.handler) as NodeHandler;\n\n const middleware = opts.buildMiddleware({\n specificRouter, specificHandler, fullRouter, fullHandler,\n });\n return Object.assign(middleware, endpoints) as ExpressMiddleware & E;\n}\n"],
|
|
5
|
-
"mappings": ";AAEA,SAAS,YAAY,uBAAuB;AAC5C,SAAwD,gBAAgB,wBAAwB,gBAAgB,kBAAkB,gBAAgB;AAClJ,SAAS,eAAe,YAAY,mBAAmB;AACvD,OAA0B;AAC1B,SAAS,kBAAkB;AAC3B,OAAO,SAAS,qBAAqB,KAAK,EAAE,MAAM,OAAO;AAEzD;AAAA,EACE,kBAAAA;AAAA,EACA,oBAAAC;AAAA,EACA;AAAA,OAkBK;AAIA,SAAS,sBAAsB,WAAsB,QAAgB,YAAqB;AAE/F,SAAO,YAAY,eAAe,kBAAkB,EAAE,QAAQ,MAAM,GAAG,OAAO,QAAQ;AACpF,WAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC3C,CAAC,CAAC;AAEF,QAAM,SAAS,UAAU;AAGzB,QAAM,aAAmC,aACrC,UAAU,cAAc,IAExB,QAAQ,UAAU,SAAS,EAAE,KAAK,CAAC,aAAuB,SAAS,SAAS,SAAS,SAAS,WAAW,MAAM,GAAG;AAGtH,QAAM;AAAA;AAAA,IAEH,cAAc,oBAAoB,UAAU;AAAA,IAG7C,OAAO,OAAO,OAAO,SAAS,EAAE,KAAK,cAAY,SAAS,SAAS,GAAG;AAAA;AAGxE,MAAI,CAAC,cAAc;AACjB,WAAO,YAAY,eAAe,KAAK,EAAE,QAAQ,MAAM,GAAG,OAAO,QAAQ;AACvE,aAAO,IAAI,SAAS,YAAY,IAAI,OAAO,IAAI,EAAE,QAAQ,IAAI,CAAC;AAAA,IAChE,CAA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AS,iBAAiB,QAAmC;AAC3D,MAAI,CAAC,QAAQ;AAAE,WAAO;AAAA,EAAM;AAC5B,QAAM,MAAM,OAAO,QAAQ,GAAG;AAC9B,MAAI,MAAM,KAAK,OAAO,MAAM,GAAG,GAAG,EAAE,YAAY,MAAM,SAAS;AAAE,WAAO;AAAA,EAAM;AAC9E,MAAI;AACJ,MAAI;AAAE,cAAU,OAAO,KAAK,OAAO,MAAM,MAAM,CAAC,GAAG,QAAQ,EAAE,SAAS,MAAM;AAAA,EAAG,QAAQ;AAAE,WAAO;AAAA,EAAM;AACtG,QAAM,QAAQ,QAAQ,QAAQ,GAAG;AACjC,MAAI,QAAQ,GAAG;AAAE,WAAO;AAAA,EAAM;AAC9B,SAAO,EAAE,UAAU,QAAQ,MAAM,GAAG,KAAK,GAAG,UAAU,QAAQ,MAAM,QAAQ,CAAC,EAAE;AACjF;AAEA,SAAS,YAAY,OAA+B,UAAkB,UAA2B;AAC/F,QAAM,WAAW,OAAO,UAAU,eAAe,KAAK,OAAO,QAAQ,IAAI,MAAM,QAAQ,IAAI;AAG3F,SAAO,UAAU,UAAU,YAAY,IAAI,KAAK,aAAa;AAC/D;AAIA,SAAS,UAAU,GAAW,GAAoB;AAChD,SAAO;AAAA,IACL,WAAW,QAAQ,EAAE,OAAO,CAAC,EAAE,OAAO;AAAA,IACtC,WAAW,QAAQ,EAAE,OAAO,CAAC,EAAE,OAAO;AAAA,EACxC;AACF;AAyBO,SAAS,kBACd,WACA,
|
|
4
|
+
"sourcesContent": ["import type express from \"express\";\nimport type { IncomingMessage, ServerResponse } from \"http\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createHash, timingSafeEqual } from \"node:crypto\";\nimport { type Endpoint, type Router, type RouterConfig, createRouter as createBetterCallRouter, createEndpoint, createMiddleware, APIError } from \"@colyseus/better-call\";\nimport { toNodeHandler, getRequest, setResponse } from \"@colyseus/better-call/node\";\nimport { Transport } from \"../Transport.ts\";\nimport { controller } from \"../matchmaker/controller.ts\";\nimport pkg from \"../../package.json\" with { type: \"json\" };\n\nexport {\n createEndpoint,\n createMiddleware,\n createInternalContext,\n\n // Re-export every type reachable from an inferred type below \u2014 consumers\n // depend on @colyseus/core, not @colyseus/better-call, and cannot name it\n // under pnpm's isolated node_modules (TS2742/TS2883).\n type Router,\n type RouterConfig,\n type Endpoint,\n type EndpointHandler,\n type EndpointOptions,\n type EndpointContext,\n type StrictEndpoint,\n type StandardSchemaV1,\n type MiddlewareOptions,\n type MiddlewareInputContext,\n type CookieOptions,\n type CookiePrefixOptions,\n type Status,\n} from \"@colyseus/better-call\";\n\nexport { toNodeHandler };\n\nexport function bindRouterToTransport(transport: Transport, router: Router, useExpress: boolean) {\n // add default \"/__healthcheck\" endpoint\n router.addEndpoint(createEndpoint(\"/__healthcheck\", { method: \"GET\" }, async (ctx) => {\n return new Response(\"OK\", { status: 200 });\n }));\n\n const server = transport.server;\n\n // check if the server is bound to an express app\n const expressApp: express.Application = (useExpress)\n ? transport.getExpressApp() as express.Application\n // fallback searching for express app in server listeners\n : server?.listeners('request').find((listener: Function) => listener.name === \"app\" && listener['mountpath'] === '/') as express.Application;\n\n // add default \"/\" route, if not provided.\n const hasRootRoute = (\n // check if express app has a root route\n (expressApp && hasExpressRootRoute(expressApp)) ||\n\n // check if router has a root route\n Object.values(router.endpoints).some(endpoint => endpoint.path === \"/\")\n );\n\n if (!hasRootRoute) {\n router.addEndpoint(createEndpoint(\"/\", { method: \"GET\" }, async (ctx) => {\n return new Response(`Colyseus ${pkg.version}`, { status: 200 });\n }));\n }\n\n // use custom bindRouter method if provided\n if (!server && transport.bindRouter) {\n transport.bindRouter(router);\n return;\n }\n\n // which route handler to use\n // (router + fallback to express, or just router)\n let next: any;\n\n if (expressApp) {\n server.removeListener('request', expressApp);\n\n next = async (req: IncomingMessage, res: ServerResponse) => {\n // check if the route is defined in the router\n // if so, use the router handler, otherwise fallback to express\n if (router.findRoute(req.method, req.url.split('?')[0]) !== undefined) {\n const protocol = req.headers[\"x-forwarded-proto\"] || ((req.socket as any).encrypted ? \"https\" : \"http\");\n const base = `${protocol}://${req.headers[\":authority\"] || req.headers.host}`;\n const response = await router.handler(getRequest({ base, request: req }));\n return setResponse(res, response);\n\n } else {\n return expressApp['handle'](req, res);\n }\n };\n\n } else {\n next = toNodeHandler(router.handler);\n }\n\n // handle cors headers for all requests by default\n server.prependListener('request', (req: IncomingMessage, res: ServerResponse) => {\n const corsHeaders = {\n ...controller.DEFAULT_CORS_HEADERS,\n ...controller.getCorsHeaders(new Headers(req.headers as any)),\n };\n\n if (req.method === \"OPTIONS\") {\n res.writeHead(204, corsHeaders);\n res.end();\n return;\n }\n\n Object.entries(corsHeaders).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n\n next(req, res);\n });\n}\n\n/**\n * Whether the express app already handles the root route, in which case\n * Colyseus must not register its own default \"/\" endpoint over it.\n */\nfunction hasExpressRootRoute(expressApp: express.Application) {\n return expressRouterStack(expressApp).some((layer: any) =>\n layer.match('/') && !['query', 'expressInit'].includes(layer.name));\n}\n\n/**\n * The app's router stack, or an empty stack if it has no routes yet.\n *\n * express v5 exposes the router as `app.router`; v4 exposes it as `app._router`\n * and only creates it once the first route/middleware is registered.\n */\nfunction expressRouterStack(expressApp: express.Application): any[] {\n const app = expressApp as any;\n\n if (app?._router?.stack) {\n return app._router.stack;\n }\n\n try {\n return app?.router?.stack ?? [];\n } catch (e) {\n return []; // express v4 throws on `app.router` \u2014 no routes registered\n }\n}\n\nexport function createRouter<\n E extends Record<string, Endpoint>,\n Config extends RouterConfig\n>(endpoints: E, config: Config = {} as Config) {\n const onError = config?.onError;\n return createBetterCallRouter({ ...endpoints }, {\n // better-call's /api/reference page dumps the full API surface\n // unauthenticated \u2014 opt back in by passing `openapi` explicitly.\n openapi: { disabled: true },\n ...config,\n // Otherwise a malformed body is a 500 plus a stack trace on stderr: log\n // noise any anonymous client can trigger at will. Matched on the message\n // because `onError` receives no request context to test against.\n onError: async (error: unknown) => (error instanceof SyntaxError && error.message.includes('JSON'))\n ? Response.json({ error: 'malformed request body' }, { status: 400 })\n : await onError?.(error),\n });\n}\n\nexport interface BasicAuthOptions {\n /** username \u2192 password. The common static case. */\n users?: Record<string, string>;\n /** Custom validator (e.g. DB-backed). Takes precedence over `users`. */\n validate?: (username: string, password: string) => boolean | Promise<boolean>;\n /** Realm shown in the browser prompt. Default 'Restricted'. */\n realm?: string;\n}\n\n/**\n * HTTP Basic Auth middleware. Drop into any endpoint's `use:` slot to gate\n * it behind a browser credentials prompt:\n *\n * playground({ use: [basicAuth({ users: { admin: 's3cret' } })] })\n */\nexport function basicAuth(opts: BasicAuthOptions) {\n const { users, validate } = opts;\n if (!users && !validate) {\n throw new Error('[basicAuth] provide `users` or `validate`');\n }\n // Realm is interpolated into a header \u2014 strip `\"` so it can't break out.\n const challenge = `Basic realm=\"${(opts.realm ?? 'Restricted').replace(/\"/g, '')}\", charset=\"UTF-8\"`;\n\n return createMiddleware(async (ctx) => {\n const creds = parseBasicHeader(ctx.getHeader('authorization'));\n const ok = !!creds && (validate\n ? await validate(creds.username, creds.password)\n : staticCheck(users!, creds.username, creds.password));\n if (!ok) {\n throw new APIError(401, { message: 'authentication required' }, { 'WWW-Authenticate': challenge });\n }\n });\n}\n\nfunction parseBasicHeader(header: string | null | undefined) {\n if (!header) { return null; }\n const sep = header.indexOf(' ');\n if (sep < 0 || header.slice(0, sep).toLowerCase() !== 'basic') { return null; }\n let decoded: string;\n try { decoded = Buffer.from(header.slice(sep + 1), 'base64').toString('utf8'); } catch { return null; }\n const colon = decoded.indexOf(':');\n if (colon < 0) { return null; }\n return { username: decoded.slice(0, colon), password: decoded.slice(colon + 1) };\n}\n\nfunction staticCheck(users: Record<string, string>, username: string, password: string): boolean {\n const expected = Object.prototype.hasOwnProperty.call(users, username) ? users[username] : undefined;\n // Compare even for an unknown user so reject timing doesn't reveal which\n // usernames exist.\n return safeEqual(password, expected ?? '\\0') && expected !== undefined;\n}\n\n// Hash both sides first: equalizes length (timingSafeEqual throws on a\n// length mismatch, which would itself leak the secret's length).\nfunction safeEqual(a: string, b: string): boolean {\n return timingSafeEqual(\n createHash('sha256').update(a).digest(),\n createHash('sha256').update(b).digest(),\n );\n}\n\n// ---------------------------------------------------------------------------\n// dualModeEndpoints \u2014 shared express-compat layer for @colyseus/admin,\n// @colyseus/monitor, @colyseus/playground. Builds the two local routers\n// (specific = no catch-all, full = everything) and the matching node\n// handlers, then packages the express middleware so the return value works\n// both as `{...spread}` into createRouter AND as `app.use(\"/\", x)` middleware.\n// ---------------------------------------------------------------------------\n\nexport type ExpressMiddleware = (\n req: IncomingMessage,\n res: ServerResponse,\n next: (err?: any) => void,\n) => void;\n\nexport type NodeHandler = (req: IncomingMessage, res: ServerResponse) => Promise<void>;\n\nexport interface DualModeHelpers {\n specificRouter: Router;\n specificHandler: NodeHandler;\n fullRouter: Router;\n fullHandler: NodeHandler;\n}\n\nexport function dualModeEndpoints<E extends Record<string, Endpoint>>(\n endpoints: E,\n opts: {\n /** Key in `endpoints` whose path is a catch-all. Excluded from `specificRouter` so it doesn't eat fall-through decisions. */\n catchAllKey?: keyof E;\n /** Endpoint-path prefix baked into `endpoints` (`''`, `'/monitor'`). Used by the default middleware to rebase path mounts. */\n prefix?: string;\n /** SPA dist dir \u2014 the default middleware dispatches catch-all requests only for files that exist here. */\n staticDir?: string;\n /** Build a custom express middleware given the pre-built routers + node handlers. Omit for the default SPA-panel middleware. */\n buildMiddleware?: (helpers: DualModeHelpers) => ExpressMiddleware;\n },\n): ExpressMiddleware & E {\n const fullRouter = createRouter(endpoints);\n const fullHandler = toNodeHandler(fullRouter.handler) as NodeHandler;\n\n const specificEndpoints = opts.catchAllKey\n ? Object.fromEntries(\n Object.entries(endpoints).filter(([k]) => k !== opts.catchAllKey),\n ) as Partial<E>\n : endpoints;\n const specificRouter = createRouter(specificEndpoints as E);\n const specificHandler = toNodeHandler(specificRouter.handler) as NodeHandler;\n\n const buildMiddleware = opts.buildMiddleware ?? panelMiddleware(opts.prefix ?? '', opts.staticDir);\n const middleware = buildMiddleware({\n specificRouter, specificHandler, fullRouter, fullHandler,\n });\n return Object.assign(middleware, endpoints) as ExpressMiddleware & E;\n}\n\n/**\n * Default express middleware for a single-prefix SPA panel (monitor,\n * playground). Express and the endpoint map use different coordinates: a path\n * mount strips its prefix into `req.baseUrl`, while the endpoints keep the\n * configured `prefix` baked into their paths. This rebases every request onto\n * the endpoint namespace, so the panel works at any mount path \u2014 `prefix` only\n * matters in router mode and at root mounts.\n */\nfunction panelMiddleware(prefix: string, staticDir?: string) {\n const staticRoot = staticDir && path.resolve(staticDir);\n return ({ specificRouter, specificHandler, fullHandler }: DualModeHelpers): ExpressMiddleware =>\n (req, res, next) => {\n const r = req as IncomingMessage & { baseUrl?: string; originalUrl?: string };\n const raw = r.url ?? '';\n const q = raw.indexOf('?');\n const url = q < 0 ? raw : raw.slice(0, q);\n const query = q < 0 ? '' : raw.slice(q);\n\n // Path mounts arrive stripped (`req.url` is mount-relative); root and\n // pathless mounts arrive unstripped and already match the endpoints.\n const dispatchPath = r.baseUrl ? prefix + url : url;\n\n // Canonicalize the index: the SPA references its assets relatively, so\n // they only resolve from the trailing-slash URL. The browser's address\n // is originalUrl \u2014 302 (not 301: browsers cache 301s across remounts).\n if (dispatchPath === prefix || dispatchPath === `${prefix}/`) {\n const original = (r.originalUrl ?? raw).split('?')[0]!;\n if (r.method === 'GET' && !original.endsWith('/')) {\n res.writeHead(302, { location: `${original}/${query}` });\n res.end();\n return;\n }\n }\n\n const dispatch = (handler: NodeHandler) => {\n // better-call's getRequest resolves the path as baseUrl + url\n const wrapped = Object.create(req, {\n url: { value: dispatchPath + query, enumerable: true, configurable: true },\n baseUrl: { value: '', enumerable: true, configurable: true },\n originalUrl: { value: dispatchPath + query, enumerable: true, configurable: true },\n });\n handler(wrapped as any, res).catch(next);\n };\n\n const route = specificRouter.findRoute(r.method ?? 'GET', dispatchPath);\n // rou3 normalizes trailing slashes in findRoute but processRequest\n // exact-matches \u2014 only trust the hit when the slashes agree.\n if (route && (!route.data?.path?.endsWith('/') || dispatchPath.endsWith('/'))) {\n return dispatch(specificHandler);\n }\n\n // Asset request \u2014 only delegate when the file exists on disk, so the\n // catch-all's SPA fallback can't mask sibling express routes.\n if (r.method !== 'GET' || !staticRoot || !dispatchPath.startsWith(prefix)) { return next(); }\n const rel = dispatchPath.slice(prefix.length).replace(/^\\/+/, '');\n if (!rel || rel.includes('..')) { return next(); }\n const filePath = path.resolve(staticRoot, rel);\n if (!filePath.startsWith(staticRoot + path.sep)) { return next(); }\n fs.stat(filePath).then((stat) => stat.isFile() ? dispatch(fullHandler) : next()).catch(() => next());\n };\n}\n"],
|
|
5
|
+
"mappings": ";AAEA,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS,YAAY,uBAAuB;AAC5C,SAAwD,gBAAgB,wBAAwB,gBAAgB,kBAAkB,gBAAgB;AAClJ,SAAS,eAAe,YAAY,mBAAmB;AACvD,OAA0B;AAC1B,SAAS,kBAAkB;AAC3B,OAAO,SAAS,qBAAqB,KAAK,EAAE,MAAM,OAAO;AAEzD;AAAA,EACE,kBAAAA;AAAA,EACA,oBAAAC;AAAA,EACA;AAAA,OAkBK;AAIA,SAAS,sBAAsB,WAAsB,QAAgB,YAAqB;AAE/F,SAAO,YAAY,eAAe,kBAAkB,EAAE,QAAQ,MAAM,GAAG,OAAO,QAAQ;AACpF,WAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC3C,CAAC,CAAC;AAEF,QAAM,SAAS,UAAU;AAGzB,QAAM,aAAmC,aACrC,UAAU,cAAc,IAExB,QAAQ,UAAU,SAAS,EAAE,KAAK,CAAC,aAAuB,SAAS,SAAS,SAAS,SAAS,WAAW,MAAM,GAAG;AAGtH,QAAM;AAAA;AAAA,IAEH,cAAc,oBAAoB,UAAU;AAAA,IAG7C,OAAO,OAAO,OAAO,SAAS,EAAE,KAAK,cAAY,SAAS,SAAS,GAAG;AAAA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,YAAY,MAAM,cAAc,KAAK;AAAA,QAC3D,aAAa,EAAE,OAAO,eAAe,OAAO,YAAY,MAAM,cAAc,KAAK;AAAA,MACnF,CAAC;AACD,cAAQ,SAAgB,GAAG,EAAE,MAAM,IAAI;AAAA,IACzC;AAEA,UAAM,QAAQ,eAAe,UAAU,EAAE,UAAU,OAAO,YAAY;AAGtE,QAAI,UAAU,CAAC,MAAM,MAAM,MAAM,SAAS,GAAG,KAAK,aAAa,SAAS,GAAG,IAAI;AAC7E,aAAO,SAAS,eAAe;AAAA,IACjC;AAIA,QAAI,EAAE,WAAW,SAAS,CAAC,cAAc,CAAC,aAAa,WAAW,MAAM,GAAG;AAAE,aAAO,KAAK;AAAA,IAAG;AAC5F,UAAM,MAAM,aAAa,MAAM,OAAO,MAAM,EAAE,QAAQ,QAAQ,EAAE;AAChE,QAAI,CAAC,OAAO,IAAI,SAAS,IAAI,GAAG;AAAE,aAAO,KAAK;AAAA,IAAG;AACjD,UAAM,WAAW,KAAK,QAAQ,YAAY,GAAG;AAC7C,QAAI,CAAC,SAAS,WAAW,aAAa,KAAK,GAAG,GAAG;AAAE,aAAO,KAAK;AAAA,IAAG;AAClE,OAAG,KAAK,QAAQ,EAAE,KAAK,CAAC,SAAS,KAAK,OAAO,IAAI,SAAS,WAAW,IAAI,KAAK,CAAC,EAAE,MAAM,MAAM,KAAK,CAAC;AAAA,EACrG;AACJ;",
|
|
6
6
|
"names": ["createEndpoint", "createMiddleware"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@colyseus/core",
|
|
3
|
-
"version": "0.18.
|
|
3
|
+
"version": "0.18.6",
|
|
4
4
|
"description": "Multiplayer Framework for Node.js.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"input": "./src/index.ts",
|
|
@@ -52,25 +52,25 @@
|
|
|
52
52
|
"msgpackr": "^2.0.1",
|
|
53
53
|
"nanoid": "^3.3.11",
|
|
54
54
|
"@colyseus/better-call": "^1.3.1",
|
|
55
|
-
"@colyseus/
|
|
56
|
-
"@colyseus/
|
|
55
|
+
"@colyseus/greeting-banner": "^4.0.1",
|
|
56
|
+
"@colyseus/shared-types": "^0.18.1"
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
|
59
59
|
"@colyseus/schema": "^5.0.8",
|
|
60
60
|
"express": "^5.0.0",
|
|
61
61
|
"vitest": "^3.1.1",
|
|
62
62
|
"@colyseus/redis-driver": "^0.18.2",
|
|
63
|
-
"@colyseus/
|
|
64
|
-
"@colyseus/
|
|
63
|
+
"@colyseus/tools": "^0.18.2",
|
|
64
|
+
"@colyseus/redis-presence": "^0.18.2"
|
|
65
65
|
},
|
|
66
66
|
"peerDependencies": {
|
|
67
67
|
"@colyseus/schema": "^5.0.8",
|
|
68
68
|
"@pm2/io": "^6.1.0",
|
|
69
69
|
"express": "^4.16.0 || ^5.0.0",
|
|
70
70
|
"zod": "^4.1.12",
|
|
71
|
-
"@colyseus/
|
|
71
|
+
"@colyseus/better-call": "^1.3.1",
|
|
72
72
|
"@colyseus/auth": "^0.18.1",
|
|
73
|
-
"@colyseus/
|
|
73
|
+
"@colyseus/ws-transport": "^0.18.1"
|
|
74
74
|
},
|
|
75
75
|
"peerDependenciesMeta": {
|
|
76
76
|
"@colyseus/auth": {
|
package/src/router/index.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import type express from "express";
|
|
2
2
|
import type { IncomingMessage, ServerResponse } from "http";
|
|
3
|
+
import fs from "node:fs/promises";
|
|
4
|
+
import path from "node:path";
|
|
3
5
|
import { createHash, timingSafeEqual } from "node:crypto";
|
|
4
6
|
import { type Endpoint, type Router, type RouterConfig, createRouter as createBetterCallRouter, createEndpoint, createMiddleware, APIError } from "@colyseus/better-call";
|
|
5
7
|
import { toNodeHandler, getRequest, setResponse } from "@colyseus/better-call/node";
|
|
@@ -250,8 +252,12 @@ export function dualModeEndpoints<E extends Record<string, Endpoint>>(
|
|
|
250
252
|
opts: {
|
|
251
253
|
/** Key in `endpoints` whose path is a catch-all. Excluded from `specificRouter` so it doesn't eat fall-through decisions. */
|
|
252
254
|
catchAllKey?: keyof E;
|
|
253
|
-
/**
|
|
254
|
-
|
|
255
|
+
/** Endpoint-path prefix baked into `endpoints` (`''`, `'/monitor'`). Used by the default middleware to rebase path mounts. */
|
|
256
|
+
prefix?: string;
|
|
257
|
+
/** SPA dist dir — the default middleware dispatches catch-all requests only for files that exist here. */
|
|
258
|
+
staticDir?: string;
|
|
259
|
+
/** Build a custom express middleware given the pre-built routers + node handlers. Omit for the default SPA-panel middleware. */
|
|
260
|
+
buildMiddleware?: (helpers: DualModeHelpers) => ExpressMiddleware;
|
|
255
261
|
},
|
|
256
262
|
): ExpressMiddleware & E {
|
|
257
263
|
const fullRouter = createRouter(endpoints);
|
|
@@ -265,8 +271,71 @@ export function dualModeEndpoints<E extends Record<string, Endpoint>>(
|
|
|
265
271
|
const specificRouter = createRouter(specificEndpoints as E);
|
|
266
272
|
const specificHandler = toNodeHandler(specificRouter.handler) as NodeHandler;
|
|
267
273
|
|
|
268
|
-
const
|
|
274
|
+
const buildMiddleware = opts.buildMiddleware ?? panelMiddleware(opts.prefix ?? '', opts.staticDir);
|
|
275
|
+
const middleware = buildMiddleware({
|
|
269
276
|
specificRouter, specificHandler, fullRouter, fullHandler,
|
|
270
277
|
});
|
|
271
278
|
return Object.assign(middleware, endpoints) as ExpressMiddleware & E;
|
|
272
279
|
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Default express middleware for a single-prefix SPA panel (monitor,
|
|
283
|
+
* playground). Express and the endpoint map use different coordinates: a path
|
|
284
|
+
* mount strips its prefix into `req.baseUrl`, while the endpoints keep the
|
|
285
|
+
* configured `prefix` baked into their paths. This rebases every request onto
|
|
286
|
+
* the endpoint namespace, so the panel works at any mount path — `prefix` only
|
|
287
|
+
* matters in router mode and at root mounts.
|
|
288
|
+
*/
|
|
289
|
+
function panelMiddleware(prefix: string, staticDir?: string) {
|
|
290
|
+
const staticRoot = staticDir && path.resolve(staticDir);
|
|
291
|
+
return ({ specificRouter, specificHandler, fullHandler }: DualModeHelpers): ExpressMiddleware =>
|
|
292
|
+
(req, res, next) => {
|
|
293
|
+
const r = req as IncomingMessage & { baseUrl?: string; originalUrl?: string };
|
|
294
|
+
const raw = r.url ?? '';
|
|
295
|
+
const q = raw.indexOf('?');
|
|
296
|
+
const url = q < 0 ? raw : raw.slice(0, q);
|
|
297
|
+
const query = q < 0 ? '' : raw.slice(q);
|
|
298
|
+
|
|
299
|
+
// Path mounts arrive stripped (`req.url` is mount-relative); root and
|
|
300
|
+
// pathless mounts arrive unstripped and already match the endpoints.
|
|
301
|
+
const dispatchPath = r.baseUrl ? prefix + url : url;
|
|
302
|
+
|
|
303
|
+
// Canonicalize the index: the SPA references its assets relatively, so
|
|
304
|
+
// they only resolve from the trailing-slash URL. The browser's address
|
|
305
|
+
// is originalUrl — 302 (not 301: browsers cache 301s across remounts).
|
|
306
|
+
if (dispatchPath === prefix || dispatchPath === `${prefix}/`) {
|
|
307
|
+
const original = (r.originalUrl ?? raw).split('?')[0]!;
|
|
308
|
+
if (r.method === 'GET' && !original.endsWith('/')) {
|
|
309
|
+
res.writeHead(302, { location: `${original}/${query}` });
|
|
310
|
+
res.end();
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
const dispatch = (handler: NodeHandler) => {
|
|
316
|
+
// better-call's getRequest resolves the path as baseUrl + url
|
|
317
|
+
const wrapped = Object.create(req, {
|
|
318
|
+
url: { value: dispatchPath + query, enumerable: true, configurable: true },
|
|
319
|
+
baseUrl: { value: '', enumerable: true, configurable: true },
|
|
320
|
+
originalUrl: { value: dispatchPath + query, enumerable: true, configurable: true },
|
|
321
|
+
});
|
|
322
|
+
handler(wrapped as any, res).catch(next);
|
|
323
|
+
};
|
|
324
|
+
|
|
325
|
+
const route = specificRouter.findRoute(r.method ?? 'GET', dispatchPath);
|
|
326
|
+
// rou3 normalizes trailing slashes in findRoute but processRequest
|
|
327
|
+
// exact-matches — only trust the hit when the slashes agree.
|
|
328
|
+
if (route && (!route.data?.path?.endsWith('/') || dispatchPath.endsWith('/'))) {
|
|
329
|
+
return dispatch(specificHandler);
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// Asset request — only delegate when the file exists on disk, so the
|
|
333
|
+
// catch-all's SPA fallback can't mask sibling express routes.
|
|
334
|
+
if (r.method !== 'GET' || !staticRoot || !dispatchPath.startsWith(prefix)) { return next(); }
|
|
335
|
+
const rel = dispatchPath.slice(prefix.length).replace(/^\/+/, '');
|
|
336
|
+
if (!rel || rel.includes('..')) { return next(); }
|
|
337
|
+
const filePath = path.resolve(staticRoot, rel);
|
|
338
|
+
if (!filePath.startsWith(staticRoot + path.sep)) { return next(); }
|
|
339
|
+
fs.stat(filePath).then((stat) => stat.isFile() ? dispatch(fullHandler) : next()).catch(() => next());
|
|
340
|
+
};
|
|
341
|
+
}
|