feat(accounts): add explicit local account registration

This commit is contained in:
N0VAN0M4LY committed 2026-11-29 15:30:34 +08:00
1 parent ef3648cb13
commit 2b1da24263
8 files changed
+242 -6

No files matched your search

+25 -5
View File
@@ -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).
@@ -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,
},
};
}