From 900eb90b4234e9aaa955cfbccd14f9f29d7b775f Mon Sep 17 00:00:00 2001 From: N0VAN0M4LY <224130499+N0VAN0M4LY@users.noreply.github.com> Date: Sun, 29 Nov 2026 15:30:34 +0800 Subject: [PATCH] Add explicit local account registration --- apps/server/src/accounts/account-store.ts | 30 +++++-- .../src/accounts/registration-service.ts | 75 ++++++++++++++++++ apps/server/src/index.ts | 2 + apps/server/src/server.ts | 2 + apps/server/src/web-ui/web-ui-service.ts | 2 +- apps/server/src/web-ui/web/register.css | 33 ++++++++ apps/server/src/web-ui/web/register.html | 26 +++++++ apps/server/src/web-ui/web/register.js | 78 +++++++++++++++++++ 8 files changed, 242 insertions(+), 6 deletions(-) create mode 100644 apps/server/src/accounts/registration-service.ts create mode 100644 apps/server/src/web-ui/web/register.css create mode 100644 apps/server/src/web-ui/web/register.html create mode 100644 apps/server/src/web-ui/web/register.js diff --git a/apps/server/src/accounts/account-store.ts b/apps/server/src/accounts/account-store.ts index aa128d7..ecc02d5 100644 --- a/apps/server/src/accounts/account-store.ts +++ b/apps/server/src/accounts/account-store.ts @@ -23,6 +23,10 @@ export type SignInResult = | { readonly kind: 'signed-in'; readonly account: Account; readonly registered: boolean } | { readonly kind: 'wrong-password' }; +export type RegistrationResult = + | { readonly kind: 'registered'; readonly account: Account } + | { readonly kind: 'invalid-login' | 'invalid-password' | 'invalid-nick' | 'already-registered' }; + interface AccountFile { formatVersion: 1; nextUserId: number; @@ -50,14 +54,30 @@ export class AccountStore { return { kind: 'signed-in', account: existing, registered: false }; } - const userId = String(this.#file.nextUserId); - const account: Account = { login, userId, nick: nickFromLogin(login, userId), passwordHash: hashPassword(password), created: new Date().toISOString() }; - this.#file = { ...this.#file, nextUserId: this.#file.nextUserId + 1, accounts: [...this.#file.accounts, account] }; - writeFileAtomic(this.#path, JSON.stringify(this.#file, null, 2)); - this.#lastSignedInUserId = userId; + const account = this.#create(login, password, nickFromLogin(login, String(this.#file.nextUserId))); + this.#lastSignedInUserId = account.userId; return { kind: 'signed-in', account, registered: true }; } + register(login: string, password: string, nick: string): RegistrationResult { + login = login.trim(); + nick = nick.trim(); + if (!login || /[\s\p{Cc}]/u.test(login)) return { kind: 'invalid-login' }; + if (!password) return { kind: 'invalid-password' }; + if (!nick || [...nick].length > NICK_MAX_LENGTH || /\p{Cc}/u.test(nick)) return { kind: 'invalid-nick' }; + if (this.#find(login)) return { kind: 'already-registered' }; + return { kind: 'registered', account: this.#create(login, password, nick) }; + } + + #create(login: string, password: string, nick: string): Account { + const userId = String(this.#file.nextUserId); + const account: Account = { login, userId, nick, passwordHash: hashPassword(password), created: new Date().toISOString() }; + const file = { ...this.#file, nextUserId: this.#file.nextUserId + 1, accounts: [...this.#file.accounts, account] }; + writeFileAtomic(this.#path, JSON.stringify(file, null, 2)); + this.#file = file; + return account; + } + /** * The account that most recently signed in during this service run (for defaulting the initial * read-only account dropdown in the built-in browser; never used as a fallback on mutations). diff --git a/apps/server/src/accounts/registration-service.ts b/apps/server/src/accounts/registration-service.ts new file mode 100644 index 0000000..f7d5ab6 --- /dev/null +++ b/apps/server/src/accounts/registration-service.ts @@ -0,0 +1,75 @@ +import type { Service, ServiceRequest, ServiceResponse } from '../transport/exchange.ts'; +import { createStaticWebSite, parseJsonBody } from '../web-ui/web-helpers.ts'; +import type { AccountStore } from './account-store.ts'; + +export const REGISTRATION_PATH = '/_wto/register'; +const PAGE_PATH = '/register'; +const PAGE = createStaticWebSite(new URL('../web-ui/web/', import.meta.url), ['register.html']); +const MAX_REQUEST_BYTES = 8192; + +export class RegistrationService implements Service { + readonly name = 'registration'; + readonly #accounts: AccountStore; + + constructor(accounts: AccountStore) { + this.#accounts = accounts; + } + + accepts(request: ServiceRequest): boolean { + return request.originalHost === undefined && + ((request.path === PAGE_PATH && request.method === 'GET') || request.path === REGISTRATION_PATH); + } + + handle(request: ServiceRequest): ServiceResponse { + if (request.path === PAGE_PATH) { + const page = PAGE.serve('register.html', 'local registration')!; + return { + ...page, + headers: { + ...page.headers, + 'content-security-policy': "default-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'", + 'cache-control': 'no-store', + }, + }; + } + if (request.method !== 'POST') return registrationReply(405, { error: 'method' }); + const host = request.headers.host; + const origin = request.headers.origin; + if (!host || !/^(localhost|127\.0\.0\.1)(:\d+)?$/i.test(host) || + (origin !== undefined && origin !== 'http://' + host.toLowerCase())) { + return registrationReply(403, { error: 'origin' }); + } + if (request.headers['content-type']?.split(';', 1)[0]?.trim().toLowerCase() !== 'application/json' || + request.body.length > MAX_REQUEST_BYTES) { + return registrationReply(400, { error: 'invalid-input' }); + } + const { login, password, nick } = parseJsonBody(request.body); + if (typeof login !== 'string' || typeof password !== 'string' || typeof nick !== 'string') { + return registrationReply(400, { error: 'invalid-input' }); + } + try { + const registered = this.#accounts.register(login, password, nick); + if (registered.kind !== 'registered') { + return registrationReply(registered.kind === 'already-registered' ? 409 : 400, { error: registered.kind }); + } + const { userId, nick: displayName } = registered.account; + return registrationReply(201, { userId, nick: displayName }); + } catch (error) { + console.error('[registration] saving the account failed:', error); + return registrationReply(500, { error: 'failed' }); + } + } +} + +function registrationReply(status: number, payload: object): ServiceResponse { + return { + status, + headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }, + body: JSON.stringify(payload), + logNotes: { + summary: 'local account registration', + redactedRequestBody: '[registration data redacted]', + omitResponseBody: true, + }, + }; +} diff --git a/apps/server/src/index.ts b/apps/server/src/index.ts index 0bc1a41..86a903f 100644 --- a/apps/server/src/index.ts +++ b/apps/server/src/index.ts @@ -3,5 +3,7 @@ * signs in, loads the profile and sends player actions as it would online. */ export { LOOPBACK, startServer, type ServerOptions, type RunningServer } from './server.ts'; +export { AccountStore, type RegistrationResult } from './accounts/account-store.ts'; +export { REGISTRATION_PATH } from './accounts/registration-service.ts'; export { HEALTH_PATH } from './transport/http-listener.ts'; export { multiVehiclePackIds } from './store/store-pack-ids.ts'; diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index b6bc343..a1ef35d 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -4,6 +4,7 @@ */ import type { Server } from 'node:net'; import { AccountStore } from './accounts/account-store.ts'; +import { RegistrationService } from './accounts/registration-service.ts'; import { BattleEconomy } from './battle/battle-economy.ts'; import { BattleMatchmaker } from './battle/battle-matchmaker.ts'; import { BattleSessionStore } from './battle/battle-session-store.ts'; @@ -118,6 +119,7 @@ export async function startServer(options: ServerOptions): Promise + + + + + Create a local account + + + + + +
+
+

Create a local account

+
+ + + + + +
+

+
+
+ + diff --git a/apps/server/src/web-ui/web/register.js b/apps/server/src/web-ui/web/register.js new file mode 100644 index 0000000..de79903 --- /dev/null +++ b/apps/server/src/web-ui/web/register.js @@ -0,0 +1,78 @@ +const en = { + title: 'Create a local account', + login: 'Login', + password: 'Password', + confirm: 'Confirm password', + nick: 'Nickname', + create: 'Create account', + created: 'Account created. Return to the game to sign in.', + mismatch: 'The passwords do not match.', + 'already-registered': 'An account with this login already exists.', + 'invalid-login': 'Enter a login without spaces.', + 'invalid-password': 'Enter a password.', + 'invalid-nick': 'Enter a nickname with up to 16 characters.', + failed: 'The account could not be created.', +}; + +const zh = { + title: '注册本地账号', + login: '登录账号', + password: '密码', + confirm: '确认密码', + nick: '昵称', + create: '注册', + created: '账号已注册。请返回游戏登录。', + mismatch: '两次输入的密码不一致。', + 'already-registered': '该登录账号已注册。', + 'invalid-login': '登录账号不能包含空格。', + 'invalid-password': '请输入密码。', + 'invalid-nick': '请输入最多 16 个字符的昵称。', + failed: '无法注册本地账号。', +}; + +const chinese = navigator.language.toLowerCase().startsWith('zh'); +const text = chinese ? zh : en; +document.documentElement.lang = chinese ? 'zh-CN' : 'en'; +document.title = text.title; +for (const element of document.querySelectorAll('[data-text]')) element.textContent = text[element.dataset.text]; + +const form = document.getElementById('register'); +const result = document.getElementById('result'); +const submit = form.querySelector('button[type=submit]'); + +function show(message, success) { + result.className = success ? 'notice ok' : 'notice err'; + result.textContent = message; +} + +form.addEventListener('submit', async (event) => { + event.preventDefault(); + const fields = new FormData(form); + const login = fields.get('login'); + const password = fields.get('password'); + const nick = fields.get('nick'); + if (password !== fields.get('confirmation')) { + show(text.mismatch, false); + return; + } + submit.disabled = true; + try { + const response = await fetch(form.action, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ login, password, nick }), + }); + const body = await response.json(); + if (response.ok) { + form.reset(); + form.hidden = true; + show(text.created, true); + } else { + show(text[body.error] ?? text.failed, false); + } + } catch { + show(text.failed, false); + } finally { + submit.disabled = false; + } +});