Files
puter/src/backend/util/username.test.ts
Daniel Salazar d162549c1d refactor(controllers): one signup, login, confirm and window.user path; userProtected/internalAuth route options (#4189)
* refactor(auth): one signup path for form, temp, OIDC and team accounts

Signup steps (validate hook, phone/card forcing, bonus verdict, provisioning,
signup events) move from AuthController and OIDCService into SignupService.
Username rules, availability and generation move to util/username.ts, and
user-row + group + default-folder creation to provisionUser, which
TeamService and DefaultUserService now share.

Behaviour fixes: a provisioned team seat joins default_user_group like every
other account, and generated temp usernames skip names whose home path is
occupied.

* refactor(auth): one web-session start for password and OIDC sign-in

startWebSession creates the session with the request's IP, user agent, origin
and host and sets the session cookie. OIDC sign-ins used to create their
session without that metadata, so they showed up blank in the session list.

* refactor(auth): one confirmEmail for the code and link confirmation routes

Both routes now re-run the email checks, refuse an address another account
confirmed, strip it from other rows, promote the group and push
user.email_confirmed to the account's sockets (with the originating socket id
on the code route). The link route's full-table UPDATE clearing other
accounts' pending change-email requests is dropped: /change_email/confirm
already refuses an address a confirmed account owns.

* refactor(auth): build window.user once for whoami and sign-in

buildUserDetails and scrubSensitive move from the whoami extension into
util/userDetails.ts. /whoami calls them; sign-in responses now return the same
user-actor payload, scrubbed, so the login copy no longer ships the phone
number and a no-reload login gets oidc_only/otp/directories up front. Taskbar
resolution is best-effort on both.

* refactor(http): userProtected route option replaces AuthController's route walker copy

The user-protected gate is materialized from a userProtected RouteOption
(implies requireUserActor), so AuthController no longer re-implements the
decorator walker to wire it per instance; those routes and the session
routes are plain decorators now. AuthRequired also counts requireVerified
and userProtected.

* refactor(http): internalAuth route option and a shared bodyRecord

EventsController and PeerController each checked x-puter-internal-auth by
hand with different compares; an internalAuth RouteOption now picks the
secret from config and one constant-time gate checks it. ShareController and
EventsController share bodyRecord instead of private copies.

* fix(fs): cap legacy /delete at 500 paths per request

The bulk form resolved, ACL-checked and removed an unbounded paths[] list one
by one. It now refuses more than FS_BATCH_WRITE_MAX_ITEMS (500), the cap the
batch write routes already use, before touching any entry.

* refactor(controllers): user and subdomain writes and reads through their stores

AuthController's 2FA setup/enable/disable and recovery-code writes go through
UserStore.update instead of raw UPDATEs plus a manual invalidate, and
/readdir-subdomains pages SubdomainStore.listByUserId instead of an unbounded
SELECT; the response shape is unchanged.

* refactor(auth): note SignupService's call-time peers

* fix(auth): type userDetails' taskbar deps independently of TaskbarDeps.clients
2026-10-11 22:00:53 -07:00

194 lines
6.1 KiB
TypeScript

/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { v4 as uuidv4 } from 'uuid';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import { PuterServer } from '../server.js';
import { setupTestServer } from '../testUtil.js';
import * as identifier from './identifier.js';
import {
assertValidUsername,
generateUsername,
isUsernameTaken,
USERNAME_MAX_LENGTH,
usernameConflict,
usernameRejection,
} from './username.js';
import { generateDefaultFsentries } from './userProvisioning.js';
let server: PuterServer;
beforeAll(async () => {
server = await setupTestServer();
});
afterAll(async () => {
await server?.shutdown();
});
const freeName = () => `un_${Math.random().toString(36).slice(2, 10)}`;
const makeUser = async (username = freeName()) => {
const user = await server.stores.user.create({
username,
uuid: uuidv4(),
password: null,
email: `${username}@test.local`,
});
await generateDefaultFsentries(server.clients.db, server.stores.user, user);
return user;
};
/**
* Moves `owner`'s Documents folder under `/<name>`, so only the home path is
* taken.
*/
const parkUnder = async (name: string) => {
const owner = await makeUser();
const docs = await server.stores.fsEntry.getEntryByPath(
`/${owner.username}/Documents`,
);
await server.clients.db.write(
'UPDATE fsentries SET path = ? WHERE id = ?',
[`/${name}/Documents`, docs!.id],
);
};
describe('usernameRejection', () => {
it('names the first rule a name breaks', () => {
expect(usernameRejection('ok_name1')).toBeNull();
expect(usernameRejection('bad-name')).toBe('format');
expect(usernameRejection('')).toBe('format');
expect(usernameRejection('a'.repeat(USERNAME_MAX_LENGTH + 1))).toBe(
'length',
);
expect(usernameRejection('admin')).toBe('reserved');
});
});
describe('assertValidUsername', () => {
it('throws the signup answer for each rule', () => {
expect(() => assertValidUsername('fine_name')).not.toThrow();
expect(() => assertValidUsername('no spaces')).toThrow(
expect.objectContaining({
statusCode: 400,
legacyCode: 'bad_request',
message:
'Username can only contain letters, numbers and underscore (_).',
}),
);
expect(() => assertValidUsername('a'.repeat(46))).toThrow(
expect.objectContaining({
statusCode: 400,
message: 'Username cannot be longer than 45 characters.',
}),
);
expect(() => assertValidUsername('admin')).toThrow(
expect.objectContaining({
statusCode: 400,
legacyCode: 'username_already_in_use',
}),
);
});
});
describe('usernameConflict', () => {
it('is null for a free name', async () => {
expect(await usernameConflict(server.stores, freeName())).toBeNull();
});
it('reports an account holding the name, unless it is the caller', async () => {
const user = await makeUser();
expect(await usernameConflict(server.stores, user.username)).toBe(
'account',
);
expect(
await usernameConflict(server.stores, user.username, user.id),
).toBeNull();
});
it('reports a name that is free but whose home path holds rows', async () => {
const name = freeName();
await parkUnder(name);
expect(await usernameConflict(server.stores, name)).toBe('home');
});
});
describe('generateUsername', () => {
it('skips a candidate whose home path is occupied', async () => {
const parked = freeName();
const free = freeName();
await parkUnder(parked);
const spy = vi
.spyOn(identifier, 'generate_identifier')
.mockReturnValueOnce(parked)
.mockReturnValueOnce(free);
try {
expect(await generateUsername(server.stores)).toBe(free);
} finally {
spy.mockRestore();
}
});
it('gives up after a bounded number of taken candidates', async () => {
const taken = await makeUser();
const spy = vi
.spyOn(identifier, 'generate_identifier')
.mockReturnValue(taken.username);
try {
expect(await generateUsername(server.stores)).toBeNull();
expect(spy).toHaveBeenCalledTimes(20);
} finally {
spy.mockRestore();
}
});
});
describe('isUsernameTaken', () => {
const duplicate = Object.assign(new Error('dup'), {
code: 'SQLITE_CONSTRAINT_UNIQUE',
});
it('is true only for a unique violation on a name another account holds', async () => {
const holder = await makeUser();
expect(
await isUsernameTaken(
server.stores.user,
duplicate,
holder.username,
),
).toBe(true);
expect(
await isUsernameTaken(
server.stores.user,
duplicate,
holder.username,
holder.id,
),
).toBe(false);
expect(
await isUsernameTaken(
server.stores.user,
new Error('other'),
holder.username,
),
).toBe(false);
});
});