Add explicit local account registration
This commit is contained in:
1 parent
2246e3f68e
commit
900eb90b42
8 files changed
+242
-6
No files matched your search
@@ -23,6 +23,10 @@ export type SignInResult =
|
|||||||
| { readonly kind: 'signed-in'; readonly account: Account; readonly registered: boolean }
|
| { readonly kind: 'signed-in'; readonly account: Account; readonly registered: boolean }
|
||||||
| { readonly kind: 'wrong-password' };
|
| { 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 {
|
interface AccountFile {
|
||||||
formatVersion: 1;
|
formatVersion: 1;
|
||||||
nextUserId: number;
|
nextUserId: number;
|
||||||
@@ -50,14 +54,30 @@ export class AccountStore {
|
|||||||
return { kind: 'signed-in', account: existing, registered: false };
|
return { kind: 'signed-in', account: existing, registered: false };
|
||||||
}
|
}
|
||||||
|
|
||||||
const userId = String(this.#file.nextUserId);
|
const account = this.#create(login, password, nickFromLogin(login, String(this.#file.nextUserId)));
|
||||||
const account: Account = { login, userId, nick: nickFromLogin(login, userId), passwordHash: hashPassword(password), created: new Date().toISOString() };
|
this.#lastSignedInUserId = account.userId;
|
||||||
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;
|
|
||||||
return { kind: 'signed-in', account, registered: true };
|
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
|
* 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).
|
* read-only account dropdown in the built-in browser; never used as a fallback on mutations).
|
||||||
|
|||||||
@@ -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,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -3,5 +3,7 @@
|
|||||||
* signs in, loads the profile and sends player actions as it would online.
|
* signs in, loads the profile and sends player actions as it would online.
|
||||||
*/
|
*/
|
||||||
export { LOOPBACK, startServer, type ServerOptions, type RunningServer } from './server.ts';
|
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 { HEALTH_PATH } from './transport/http-listener.ts';
|
||||||
export { multiVehiclePackIds } from './store/store-pack-ids.ts';
|
export { multiVehiclePackIds } from './store/store-pack-ids.ts';
|
||||||
@@ -4,6 +4,7 @@
|
|||||||
*/
|
*/
|
||||||
import type { Server } from 'node:net';
|
import type { Server } from 'node:net';
|
||||||
import { AccountStore } from './accounts/account-store.ts';
|
import { AccountStore } from './accounts/account-store.ts';
|
||||||
|
import { RegistrationService } from './accounts/registration-service.ts';
|
||||||
import { BattleEconomy } from './battle/battle-economy.ts';
|
import { BattleEconomy } from './battle/battle-economy.ts';
|
||||||
import { BattleMatchmaker } from './battle/battle-matchmaker.ts';
|
import { BattleMatchmaker } from './battle/battle-matchmaker.ts';
|
||||||
import { BattleSessionStore } from './battle/battle-session-store.ts';
|
import { BattleSessionStore } from './battle/battle-session-store.ts';
|
||||||
@@ -118,6 +119,7 @@ export async function startServer(options: ServerOptions): Promise<RunningServer
|
|||||||
|
|
||||||
const router = new Router([
|
const router = new Router([
|
||||||
webUi,
|
webUi,
|
||||||
|
new RegistrationService(accounts),
|
||||||
new StoreService(accounts, profiles, catalogues.store, tuning.redeemCodes, options.port),
|
new StoreService(accounts, profiles, catalogues.store, tuning.redeemCodes, options.port),
|
||||||
new MarketplaceService(accounts, profiles, catalogues.inventory, notifyInventoryChanged, tuning.marketplace),
|
new MarketplaceService(accounts, profiles, catalogues.inventory, notifyInventoryChanged, tuning.marketplace),
|
||||||
new InventoryService(accounts, profiles, catalogues.inventory),
|
new InventoryService(accounts, profiles, catalogues.inventory),
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ import { StoreMediaCache, STORE_MEDIA_PREFIX } from './store-media-cache.ts';
|
|||||||
import { contentResponse, createStaticWebSite, notFound } from './web-helpers.ts';
|
import { contentResponse, createStaticWebSite, notFound } from './web-helpers.ts';
|
||||||
|
|
||||||
const PREFIX = '/_wto/ui/';
|
const PREFIX = '/_wto/ui/';
|
||||||
const SHARED_FILES = createStaticWebSite(new URL('./web/', import.meta.url), ['common.css', 'common.js', 'official-images.json', 'official-store-media.json']);
|
const SHARED_FILES = createStaticWebSite(new URL('./web/', import.meta.url), ['common.css', 'common.js', 'register.css', 'register.js', 'official-images.json', 'official-store-media.json']);
|
||||||
const ICON_PATH = /^(vehicle|flag)\/([^/]+)\.svg$/;
|
const ICON_PATH = /^(vehicle|flag)\/([^/]+)\.svg$/;
|
||||||
const ART_PATH = /^art\/(vehicle|group|product|skin|decal|attachable|unlock)\/([^/]+)$/;
|
const ART_PATH = /^art\/(vehicle|group|product|skin|decal|attachable|unlock)\/([^/]+)$/;
|
||||||
const PACK_PREFIX = 'asset-pack/';
|
const PACK_PREFIX = 'asset-pack/';
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
.registration {
|
||||||
|
width: 100%;
|
||||||
|
max-width: 480px;
|
||||||
|
margin: 24px auto;
|
||||||
|
padding: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.registration h1 {
|
||||||
|
margin: 0 0 6px;
|
||||||
|
font-size: 22px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.registration form,
|
||||||
|
.registration label {
|
||||||
|
display: grid;
|
||||||
|
gap: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.registration form {
|
||||||
|
gap: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.registration input {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.registration button {
|
||||||
|
justify-self: start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.registration .notice {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Create a local account</title>
|
||||||
|
<link rel="stylesheet" href="/_wto/ui/common.css">
|
||||||
|
<link rel="stylesheet" href="/_wto/ui/register.css">
|
||||||
|
<script src="/_wto/ui/register.js" defer></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main>
|
||||||
|
<section class="card registration">
|
||||||
|
<h1 data-text="title">Create a local account</h1>
|
||||||
|
<form id="register" method="post" action="/_wto/register">
|
||||||
|
<label><span data-text="login">Login</span><input name="login" autocomplete="username" required></label>
|
||||||
|
<label><span data-text="password">Password</span><input name="password" type="password" autocomplete="new-password" required></label>
|
||||||
|
<label><span data-text="confirm">Confirm password</span><input name="confirmation" type="password" autocomplete="new-password" required></label>
|
||||||
|
<label><span data-text="nick">Nickname</span><input name="nick" autocomplete="nickname" required></label>
|
||||||
|
<button class="buy" type="submit" data-text="create">Create account</button>
|
||||||
|
</form>
|
||||||
|
<p id="result" class="notice" role="status"></p>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
});
|
||||||
Reference in new issue
Block a user