Embed base images into binary

Include resource directory
Ran `deno fmt` with 4 space indent, that changed every file (!!!!!)
various changes
This commit is contained in:
2025-03-24 19:11:36 -04:00
parent 2207e389c9
commit 49c481aa0e
61 changed files with 2369 additions and 2031 deletions

View File

@@ -1,6 +1,6 @@
import { APIUtils } from "../apiutils.ts";
import { route as AccountRoute } from "./account/account.ts";
export const route = APIUtils.createRouter('/accountservice');
export const route = APIUtils.createRouter("/accountservice");
route.router.use(AccountRoute.path, AccountRoute.router);
route.router.use(AccountRoute.path, AccountRoute.router);

View File

@@ -5,16 +5,23 @@ import Profile from "../../data/profiles.ts";
export const route = APIUtils.createRouter("/account");
interface CreateAccountRequestBody {
platform: string,
platformId: string,
deviceId: string
platform: string;
platformId: string;
deviceId: string;
}
route.router.post('/create',
const rateLimit = new APIUtils.RateLimiter(25, 5);
APIUtils.UserAuthentication,
route.router.post("/create",
rateLimit.middle(),
APIUtils.Authentication,
express.urlencoded({ extended: true }),
APIUtils.checkBodyTypes<CreateAccountRequestBody>({platform: "", platformId: "", deviceId: ""}),
APIUtils.checkBodyTypes<CreateAccountRequestBody>({
platform: "",
platformId: "",
deviceId: "",
}),
async (_rq, rs) => {
const newAcc = await Profile.init();
@@ -23,8 +30,43 @@ route.router.post('/create',
rs.json({
success: true,
value: await newAcc.export()
value: await newAcc.export(),
});
},
);
);
route.router.get("/bulk",
rateLimit.middle(),
async (rq: express.Request, rs: express.Response) => {
if (typeof rq.query.id == "object") {
const ids = Object.values(rq.query.id).filter((val) => typeof val == "string").map((val) => parseInt(val, 10)).filter((val) => !isNaN(val));
rs.json([...await Profile.getExportAccountsBulk(ids)]);
} else if (typeof rq.query.id == "string") {
const id = parseInt(rq.query.id, 10);
if (isNaN(id)) {
rs.json(
APIUtils.genericResponseFormat(true, "Query data error"),
);
return;
} else {
rs.json(
[await Profile.getExportAccount(id)].filter((val) =>
val !== null
),
);
return;
}
} else {
rs.json([]);
return;
}
},
);

View File

@@ -3,8 +3,8 @@ import { route as ConfigRoute } from "./api/config.ts";
import { route as GameConfig } from "./api/gameconfigs.ts";
import { APIUtils } from "../apiutils.ts";
export const route = APIUtils.createRouter('/api');
export const route = APIUtils.createRouter("/api");
route.router.use(VersionCheckRoute.path, VersionCheckRoute.router);
route.router.use(ConfigRoute.path, ConfigRoute.router);
route.router.use(GameConfig.path, GameConfig.router);
route.router.use(GameConfig.path, GameConfig.router);

View File

@@ -1,10 +1,10 @@
import { APIUtils } from "../../apiutils.ts";
import { GameConfigs } from "../../data/config.ts";
export const route = APIUtils.createRouter('/config');
export const route = APIUtils.createRouter("/config");
route.router.get('/v2', (_rq, rs) => {
route.router.get("/v2", (_rq, rs) => {
const config = GameConfigs.getConfig();
if (config == null) rs.sendStatus(500);
else rs.json(config);
});
});

View File

@@ -1,7 +1,7 @@
import { APIUtils } from "../../apiutils.ts";
export const route = APIUtils.createRouter('/gameconfigs');
export const route = APIUtils.createRouter("/gameconfigs");
route.router.get('/v1/all', (_rq, rs) => {
route.router.get("/v1/all", (_rq, rs) => {
rs.json([]);
});
});

View File

@@ -1,34 +1,35 @@
import { APIUtils } from "../../apiutils.ts";
export const route = APIUtils.createRouter('/versioncheck');
export const route = APIUtils.createRouter("/versioncheck");
const validVersion = '20191120';
const validVersion = "20191120";
enum VersionStatus {
ValidForPlay,
ValidForMenu,
UpdateRequired
UpdateRequired,
}
type ValidVersionResponse = {
VersionStatus: VersionStatus
}
VersionStatus: VersionStatus;
};
route.router.get('/v4', (rq, rs) => {
const requestedVer = rq.query['v'];
const pQuery = rq.query['p'];
if (typeof requestedVer == 'undefined' || typeof pQuery == 'undefined') {
route.router.get("/v4", (rq, rs) => {
const requestedVer = rq.query["v"];
const pQuery = rq.query["p"];
if (typeof requestedVer == "undefined" || typeof pQuery == "undefined") {
rs.statusCode = 400;
rs.json(APIUtils.genericResponseFormat(true, 'One or more query parameters were not found.'));
}
else if (requestedVer !== validVersion) {
rs.json(APIUtils.genericResponseFormat(true, "One or more query parameters were not found."));
} else if (requestedVer !== validVersion) {
const res: ValidVersionResponse = {
VersionStatus: VersionStatus.UpdateRequired
}
VersionStatus: VersionStatus.UpdateRequired,
};
rs.json(res);
} else {
const res: ValidVersionResponse = {
VersionStatus: VersionStatus.ValidForPlay
}
VersionStatus: VersionStatus.ValidForPlay,
};
rs.json(res);
}
});
});

View File

@@ -2,7 +2,7 @@ import { APIUtils } from "../apiutils.ts";
import { route as CachedLoginRoute } from "./auth/cachedlogin.ts";
import { route as ConnectRoute } from "./auth/connect.ts";
export const route = APIUtils.createRouter('/authservice');
export const route = APIUtils.createRouter("/authservice");
route.router.use(CachedLoginRoute.path, CachedLoginRoute.router);
route.router.use(ConnectRoute.path, ConnectRoute.router);
route.router.use(ConnectRoute.path, ConnectRoute.router);

View File

@@ -2,14 +2,19 @@ import { APIUtils } from "../../apiutils.ts";
export const route = APIUtils.createRouter("/cachedlogin");
route.router.get('/forplatformid/:platformtype/:platformid',
route.router.get("/forplatformid/:platformtype/:platformid",
APIUtils.UserAuthentication,
APIUtils.Authentication,
async (_rq, rs) => {
rs.json(await rs.locals.user.exportAssociatedProfiles());
const profiles = await rs.locals.user.exportAssociatedProfiles();
rs.json(profiles.map((acc) => ({
platform: 0,
platformId: rs.locals.user.getId(),
accountId: acc.accountId,
lastLoginTime: new Date().toISOString(),
requirePassword: false,
})));
},
}
);
);

View File

@@ -1,5 +1,94 @@
import { APIUtils } from "../../apiutils.ts";
import { APIUtils, NoBody } from "../../apiutils.ts";
import express from "express";
import Profile from "../../data/profiles.ts";
export const route = APIUtils.createRouter("/connect");
//route.router.post()
interface TokenRequestBody {
grant_type: string;
account_id: string;
client_id: string;
client_secret: string;
platform: string;
platform_id: string;
device_id: string;
device_class: string;
time: string;
ver: string;
asid: string;
platform_auth: string;
}
interface TokenResponseBody {
error?: string;
error_description?: string;
access_token: string;
refresh_token: string;
}
route.router.post("/token",
APIUtils.Authentication,
express.urlencoded({ extended: true }),
APIUtils.checkBodyTypes<TokenRequestBody>({
grant_type: "",
account_id: "",
client_id: "",
client_secret: "",
platform: "",
platform_id: "",
device_id: "",
device_class: "",
time: "",
ver: "",
asid: "",
platform_auth: "",
}),
async (
rq: express.Request<NoBody, NoBody, TokenRequestBody>,
rs: express.Response<TokenResponseBody>,
) => {
function requestFailed(msg: string = "invalid_request") {
rs.json({
error: msg,
access_token: "",
refresh_token: "",
});
return;
}
const conditionsMet = ![
rq.body.grant_type == "cached_login",
rq.body.client_id == "recroom",
rq.body.platform == "0",
rq.body.ver == '20191120',
!(rq.body.device_id.length > 96),
!(rq.body.client_secret.length > 96),
!(rq.body.platform_id.length > 32),
!(rq.body.time.length > 32),
!(rq.body.asid.length > 32),
].includes(false);
if (conditionsMet) {
const accounts = await rs.locals.user.getAssociatedProfiles();
const targetAccount = parseInt(rq.body.account_id);
if (isNaN(targetAccount)) requestFailed();
if (!accounts.has(targetAccount)) requestFailed("access_denied");
rs.locals.user.addAssociatedDeviceId(rq.body.device_id);
rs.locals.user.addAssociatedPlatformId(rq.body.platform_id);
const profile = new Profile(targetAccount);
if (!(await Profile.exists(profile.getId()))) requestFailed();
const token = await profile.getToken();
rs.json({
access_token: token,
refresh_token: token,
});
} else requestFailed();
},
);

106
src/routes/img.ts Normal file
View File

@@ -0,0 +1,106 @@
import { APIUtils, NoBody } from "../apiutils.ts";
import * as BaseImages from "../data/content/baseimages.ts";
import Logging from "@proxnet/undead-logging";
import express from "express";
import * as Images from "./../data/content/images.ts";
import { Image } from "https://deno.land/x/imagescript@1.3.0/mod.ts";
import { Buffer } from "node:buffer";
export const route = APIUtils.createRouter("/img");
const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890. "
.split("");
function sanitizeString(input: string) {
return input.split("").filter((char) => chars.includes(char)).join("");
}
const baseImages = BaseImages.getAllBaseImages();
interface ImageQueryOptions {
cropSquare?: string;
width?: string;
height?: string;
}
route.router.get(
"*",
async (
rq: express.Request<NoBody, NoBody, NoBody, ImageQueryOptions>,
rs: express.Response,
nxt: express.NextFunction,
) => {
const filename = sanitizeString(
rq.path.substring(1, rq.path.length).replaceAll("%20", " "),
);
// why does it think it is never reassigned? line 39
// deno-lint-ignore prefer-const
let image: Image;
const imageSource = baseImages.includes(filename)
? BaseImages.getBaseImage(filename)
: await Images.getImage(filename);
if (imageSource == null) {
nxt();
return;
}
image = await Image.decode(imageSource);
let cropSquare: boolean = false;
if (typeof rq.query.cropSquare == "string") {
const d = JSON.parse(rq.query.cropSquare);
if (typeof d == "boolean" && d) cropSquare = true;
}
let width: number | null = null;
if (typeof rq.query.width == "string") {
const num = parseInt(rq.query.width);
if (isNaN(num)) width = null;
else width = num;
}
let height: number | null = null;
if (typeof rq.query.height == "string") {
const num = parseInt(rq.query.height);
if (isNaN(num)) height = null;
else height = num;
}
if (cropSquare) {
if (image.width > image.height) {
image.crop(
Math.round(image.width / 2) - Math.round(image.height / 2),
0,
image.height,
image.height,
);
} else {image.crop(
0,
Math.round(image.height / 2) - Math.round(image.width / 2),
image.width,
image.width,
);}
}
if (width && height) {
const targetWidth = width > image.width ? image.width : width;
const targetHeight = height > image.height ? image.height : height;
if (image.width > image.height) {
image.resize(Image.RESIZE_AUTO, height);
image.crop(
Math.round(image.width / 2) - Math.round(targetWidth / 2),
0,
targetWidth,
image.height,
);
} else {
image.resize(width, Image.RESIZE_AUTO);
image.crop(
0,
Math.round(image.height / 2) - Math.round(targetHeight / 2),
image.width,
targetHeight,
);
}
} else if (width) image.resize(width, Image.RESIZE_AUTO);
else if (height) image.resize(Image.RESIZE_AUTO, height);
rs.type("png").send(Buffer.from(await image.encode()));
},
);

View File

@@ -2,38 +2,38 @@ import { APIUtils } from "../apiutils.ts";
import { Config } from "../config.ts";
const config = Config.getConfig() as Config.GalvanicConfiguration;
const protocol = config.web.securepublichost ? 'https' : 'http';
const protocol = config.web.securepublichost ? "https" : "http";
export const route = APIUtils.createRouter('/ns');
export const route = APIUtils.createRouter("/ns");
type NameserverHosts = {
Auth: string,
API: string,
WWW: string,
Notifications: string,
Images: string,
CDN: string,
Commerce: string,
Matchmaking: string,
Storage: string,
Chat: string,
Leaderboard: string
}
Auth: string;
API: string;
WWW: string;
Notifications: string;
Images: string;
CDN: string;
Commerce: string;
Matchmaking: string;
Storage: string;
Chat: string;
Leaderboard: string;
};
const nameserver: NameserverHosts = {
Auth: `${protocol}://${config.web.publichost}/auth`,
API: `${protocol}://${config.web.publichost}`,
WWW: `${protocol}://${config.web.publichost}`,
Notifications: `${protocol}://${config.web.publichost}/notify`,
Images: `${protocol}://${config.web.publichost}/img`,
CDN: `${protocol}://${config.web.publichost}/cdn`,
Commerce: `${protocol}://${config.web.publichost}/commerce`,
Matchmaking: `${protocol}://${config.web.publichost}/match`,
Storage: `${protocol}://${config.web.publichost}/storage`,
Chat: `${protocol}://${config.web.publichost}/chat`,
Leaderboard: `${protocol}://${config.web.publichost}/leaderboard`
}
Auth: `${protocol}://${config.web.publichost}/auth`,
API: `${protocol}://${config.web.publichost}`,
WWW: `${protocol}://${config.web.publichost}`,
Notifications: `${protocol}://${config.web.publichost}/notify`,
Images: `${protocol}://${config.web.publichost}/img`,
CDN: `${protocol}://${config.web.publichost}/cdn`,
Commerce: `${protocol}://${config.web.publichost}/commerce`,
Matchmaking: `${protocol}://${config.web.publichost}/match`,
Storage: `${protocol}://${config.web.publichost}/storage`,
Chat: `${protocol}://${config.web.publichost}/chat`,
Leaderboard: `${protocol}://${config.web.publichost}/leaderboard`,
};
route.router.get('*', (_rq, rs) => {
rs.json(nameserver);
route.router.get("*", (_rq, rs) => {
rs.json(nameserver);
});

View File

@@ -1,4 +1,4 @@
import { APIUtils, NoBody } from "../apiutils.ts";
import { APIUtils, getSrcIpDefault, NoBody } from "../apiutils.ts";
// @ts-types = "npm:@types/express"
import express from "express";
import { User } from "../data/users.ts";
@@ -10,25 +10,25 @@ const log = new Logging("UserRoute");
const config = Config.getConfig();
export const route = APIUtils.createRouter('/user');
export const route = APIUtils.createRouter("/user");
interface AuthRequestSec {
timestamp: number,
nonce: string,
server_id: string
timestamp: number;
nonce: string;
server_id: string;
}
interface AuthRequestRoot {
client_id: string,
message: AuthRequestSec,
signature: string,
pubkey: string
client_id: string;
message: AuthRequestSec;
signature: string;
pubkey: string;
}
const rateLimit = new APIUtils.RateLimiter(60, 1);
route.router.post('/auth',
route.router.post(
"/auth",
rateLimit.middle(),
express.json(),
APIUtils.checkBodyTypes<AuthRequestRoot>({
@@ -36,72 +36,85 @@ route.router.post('/auth',
message: {
timestamp: 0,
nonce: "asdf",
server_id: "asdf"
server_id: "asdf",
},
signature: "asdf",
pubkey: "asdf"
pubkey: "asdf",
}),
async (rq: express.Request<NoBody, NoBody, AuthRequestRoot>, rs: express.Response) => {
async (
rq: express.Request<NoBody, NoBody, AuthRequestRoot>,
rs: express.Response,
) => {
function authFailed(msg: string) {
rs.json(APIUtils.genericResponseFormat(true, msg));
}
if (rq.body.message.server_id !== config.public.serverId) {
log.w(`Auth request failed (serverId mismatch), config error?\n given ID: '${rq.body.message.server_id}'\n our ID: '${config.public.serverId}'`);
authFailed('Authentication request not intended for this server.');
log.w(
`Auth request failed (serverId mismatch), config error?\n given ID: '${rq.body.message.server_id}'\n our ID: '${config.public.serverId}'`,
);
authFailed("Authentication request not intended for this server.");
return;
}
try {
const verify = crypto.createVerify('SHA256');
const verify = crypto.createVerify("SHA256");
verify.update(JSON.stringify(rq.body.message));
verify.end();
const publicKey = await crypto.subtle.importKey(
"spki",
(Uint8Array.from(atob(rq.body.pubkey), c => c.charCodeAt(0))).buffer,
(Uint8Array.from(atob(rq.body.pubkey), (c) => c.charCodeAt(0)))
.buffer,
{ name: "ECDSA", namedCurve: "P-256" },
false,
["verify"]
["verify"],
);
const messageBytes = new TextEncoder().encode(
JSON.stringify(rq.body.message),
);
const signatureBytes = Uint8Array.from(
atob(rq.body.signature),
(c) => c.charCodeAt(0),
);
const messageBytes = new TextEncoder().encode(JSON.stringify(rq.body.message));
const signatureBytes = Uint8Array.from(atob(rq.body.signature), c => c.charCodeAt(0));
const isValid = await crypto.subtle.verify(
{ name: "ECDSA", hash: "SHA-256" },
publicKey,
signatureBytes.buffer,
messageBytes
messageBytes,
);
if (!isValid) {
log.w(`Auth failed for clientId '${rq.body.client_id}'`);
authFailed('Authentication request failed.');
authFailed("Authentication request failed.");
return;
}
} catch (err) {
log.d(`Error when verifying auth request: ${err}`);
authFailed('Authentication request failed.');
authFailed("Authentication request failed.");
return;
}
let user = new User(rq.body.client_id);
if (!(await user.exists())) {
const obj = await User.init({ client_id: rq.body.client_id, pubkey: rq.body.pubkey });
const obj = await User.init({
client_id: rq.body.client_id,
pubkey: rq.body.pubkey,
});
if (obj == null) {
rs.sendStatus(500);
return;
} else user = obj;
}
if (await user.hasNonce(rq.body.message.nonce)) {
log.w(`Client '${rq.body.client_id}' has already used nonce. Replay attack?`);
authFailed('Authentication request failed.');
if (!(await user.addNonce(rq.body.message.nonce))) {
log.w(
`Client '${rq.body.client_id}' has already used nonce. Replay attack?`,
);
authFailed("Authentication request failed.");
return;
} else user.addNonce(rq.body.message.nonce);
}
user.addAssociatedIp(getSrcIpDefault(rq));
const token = await user.getToken();
rs.json({ token: token });
}
);
},
);