Fix #55: Split character sheet in tabs #62

Merged
Syndria98 merged 2 commits from ai/issue-55 into master 2026-10-15 13:33:28 +00:00
16 changed files with 1284 additions and 27 deletions
Showing only changes of commit d901385900 - Show all commits

View File

@@ -193,4 +193,113 @@ router.get('/get-settings', passport.authenticate('jwt', {session: false}), asyn
}
});
// -- Account management (the "Manage accounts" window of the site settings) ----
// /api/user is mounted before the JWT guard, so every route below authenticates
// inline; and only an administrator gets past isAdmin (services/middleware.js).
router.get('/list', passport.authenticate('jwt', {session: false}), isAdmin, async (req, res) => {
try {
// No account gets out with its password or an unfinished setup code.
const users = await User.find().select('-password -setupCode').sort({ date: 1 });
res.json({ status: "ok", users });
} catch (err) {
console.error(err);
res.json({ status: "error", msg: "errors.internal" });
}
});
// The admin creates the account with the password its user logs in with; the
// setupCode flow above stays as it is, nothing on the frontend completes it.
router.post('/create', passport.authenticate('jwt', {session: false}), isAdmin, async (req, res) => {
try {
const { name, username, email, password } = req.body;
if (!(name && username && email && password)) {
return res.json({ status: "error", msg: "errors.missing-data" });
}
const existingUser = await User.findOne({
$or: [
{ email: email },
{ username: username }
]
});
if (existingUser) {
return res.json({
status: "error",
msg: "register.errors.email-username-exists"
});
}
const salt = await bcrypt.genSalt(10);
let user = new User({
name: name,
username: username,
email: email,
password: await bcrypt.hash(password, salt)
});
await user.save();
res.json({
status: "ok",
user: {
_id: user._id,
name: user.name,
username: user.username,
email: user.email,
admin: user.admin,
date: user.date
}
});
} catch (err) {
console.error(err);
res.json({ status: "error", msg: "errors.internal" });
}
});
router.post('/set-admin', passport.authenticate('jwt', {session: false}), isAdmin, async (req, res) => {
try {
const { id, admin } = req.body;
if (!id || typeof admin !== 'boolean') {
return res.json({ status: "error", msg: "errors.missing-data" });
}
// Switching one's own rights off could leave an instance with nobody who
// can manage accounts at all, so the row for yourself stays closed.
if (String(req.user._id) === String(id)) {
return res.json({ status: "error", msg: "settings.site-administration.accounts.errors.self-admin" });
}
const user = await User.findOne({ _id: id });
if (!user) return res.json({ status: "error", msg: "errors.notfound" });
user.admin = admin;
await user.save();
res.json({ status: "ok", user: { _id: user._id, admin: user.admin } });
} catch (err) {
console.error(err);
res.json({ status: "error", msg: "errors.internal" });
}
});
// Only the account itself goes; what it created stays as it is.
router.post('/delete', passport.authenticate('jwt', {session: false}), isAdmin, async (req, res) => {
try {
const { id } = req.body;
if (!id) return res.json({ status: "error", msg: "errors.missing-data" });
// Same guard as the admin switch: nobody locks themselves out on the way out.
if (String(req.user._id) === String(id)) {
return res.json({ status: "error", msg: "settings.site-administration.accounts.errors.self-delete" });
}
const user = await User.findOne({ _id: id });
if (!user) return res.json({ status: "error", msg: "errors.notfound" });
await user.deleteOne();
res.json({ status: "ok" });
} catch (err) {
console.error(err);
res.json({ status: "error", msg: "errors.internal" });
}
});
module.exports = router;

View File

@@ -1,5 +1,28 @@
const { numberOr, asText, plainText, stringList } = require('./foundry-fields');
// D&D 5e keeps an actor's background, species, class and subclass as a reference to an
// embedded item: `system.details.background` and friends hold that item's id, and the
// field's `fallback` option hands back the bare id when the item is gone. Dragonroll
// holds names, so a reference is read through the actor's items and an id that resolves
// to nothing is dropped. An id travelling back as a name is how Foundry ends up with a
// background item — and a details reference — that does not exist (Syndria98/dragonroll#54).
const FOUNDRY_DOCUMENT_ID = /^[A-Za-z0-9_-]{16}$/;
function looksLikeFoundryId(value) {
// Sixteen plain letters is a name; the ids Foundry generates carry a digit.
return FOUNDRY_DOCUMENT_ID.test(value) && /[0-9]/.test(value) && /[A-Za-z]/.test(value);
}
// The name a `system.details` entry stands for: an embedded item's id resolves to that
// item's name, and plain text (older system releases store the name here) is the name.
function detailsName(value, items) {
const text = asText(value).trim();
if (!text) return '';
const referenced = items.find((item) => asText(item?._id ?? item?.id).trim() === text);
if (referenced) return asText(referenced.name).trim();
return looksLikeFoundryId(text) ? '' : text;
}
function foundryActorToCharacter(foundryActor) {
const system = foundryActor.system || {};
const details = system.details || {};
@@ -25,11 +48,11 @@ function foundryActorToCharacter(foundryActor) {
type: ['character', 'npc', 'creature'].includes(savedDragonrollType)
? savedDragonrollType
: (['character', 'npc', 'creature'].includes(foundryActor.type) ? foundryActor.type : 'character'),
species: asText(details.race || details.species),
className: asText(details.class || classItem?.name),
subclass: asText(details.subclass || subclassItem?.name),
species: detailsName(details.race || details.species, items),
className: detailsName(details.class, items) || asText(classItem?.name),
subclass: detailsName(details.subclass, items) || asText(subclassItem?.name),
level: numberOr(details.level ?? classItem?.system?.levels, 1),
background: asText(details.background || backgroundItem?.name),
background: detailsName(details.background, items) || asText(backgroundItem?.name),
challengeRating: String(details.cr ?? ''),
description: plainText(details.biography?.value || details.biography),
image: asText(foundryActor.img || foundryActor.image),

View File

@@ -1000,10 +1000,10 @@ function makeFoundryCharacterData(entry) {
type: entry.type === "character" ? "character" : "npc",
img: getDragonrollImageUrl(entry.image) || undefined,
system: {
// `details.race` and `details.background` are left out on purpose: they reference
// embedded items and are linked once the actor stands with its items made.
details: {
race: entry.species || "",
level: Number(entry.level) || 1,
background: entry.background || "",
biography: { value: entry.description || "" },
cr: entry.challengeRating || "",
},
@@ -1036,9 +1036,7 @@ function characterUpdateData(entry) {
const updates = {
name: entry.name,
img: getDragonrollImageUrl(entry.image) || "icons/svg/mystery-man.svg",
"system.details.race": entry.species || "",
"system.details.level": Number(entry.level) || 1,
"system.details.background": entry.background || "",
"system.details.biography.value": entry.description || "",
"system.details.cr": entry.challengeRating || "",
[`flags.${MODULE_ID}.traits`]: entry.traits || "",
@@ -1052,6 +1050,40 @@ function characterUpdateData(entry) {
return updates;
}
// `system.details.background` and `system.details.race` are LocalDocumentFields in
// D&D 5e: they hold the id of an item embedded in the actor, never its name. A name
// written into one is a reference that resolves to nothing, and adding that item in
// Foundry then fails, so each of these follows the actor's own item for it instead.
const EMBEDDED_DETAILS = [
// Dragonroll owns the background item it lists, so its reference follows it always and
// a background taken off in the campaign leaves no reference behind.
{ field: "background", path: "system.details.background", types: ["background"], clearWhenMissing: true },
// The species item belongs to the world: point at it when it carries the name, and
// leave the reference to the GM when it does not.
{ field: "species", path: "system.details.race", types: ["race", "species"] },
];
function localDocumentId(value) {
// The field resolves to the referenced document when it can and to the stored id
// when the document is gone (its `fallback` option).
if (typeof value === "string") return value;
return value?._id || "";
}
function embeddedDetailReferenceData(actor, entry) {
const updates = {};
for (const detail of EMBEDDED_DETAILS) {
const wanted = String(entry[detail.field] || "").trim();
const item = wanted
? actor.items?.contents?.find((candidate) => detail.types.includes(candidate.type) && candidate.name === wanted)
: null;
const reference = item?.id || "";
if (!reference && !detail.clearWhenMissing) continue;
if (localDocumentId(documentValue(actor, detail.path)) !== reference) updates[detail.path] = reference;
}
return updates;
}
async function reconcileEmbeddedItems(actor, entry) {
const desired = [];
if (entry.className) desired.push({ type: "class", name: entry.className, system: { levels: Number(entry.level) || 1 } });
@@ -1110,6 +1142,9 @@ async function applyDragonrollCharacter(actor, entry) {
await withActorSyncSuppressed(actor, async () => {
if (changed) await actor.update(updates);
await reconcileEmbeddedItems(actor, entry);
// The item references are written after the reconcile that makes the items they point at.
const references = embeddedDetailReferenceData(actor, entry);
if (Object.keys(references).length) await actor.update(references);
if (dragonrollActorId(actor) !== String(entry._id)
|| actor.getFlag?.(MODULE_ID, "actorType") !== entry.type) {
await actor.update({
@@ -1137,7 +1172,12 @@ async function createFoundryCharacter(entry) {
if (!actor) return;
await withActorSyncSuppressed(actor, async () => {
await actor.update({ [`flags.${MODULE_ID}.syncMutation`]: false });
await actor.update({
// The actor was made with its items, so its background and species references
// can point at them right away.
...embeddedDetailReferenceData(actor, entry),
[`flags.${MODULE_ID}.syncMutation`]: false,
});
});
await mapDragonrollActor(entry._id, actor.id);
}

View File

@@ -7,7 +7,7 @@ import { AnchorMap, AnchoredMap, ClearAnchoredMap, SetActivePane } from '~/servi
import { emitter } from '~/services/Emitter';
import { BuildColorMenu } from '~/services/EntryColors';
import { BuildItemRows } from '~/services/ItemFolders';
import Server from '~/services/Server';
import Server, { getBaseUrl } from '~/services/Server';
import { ClearWindow, CreateWindow, GetFirstWindowId } from '~/services/Windows';
import { HideContextMenu, ShowContextMenu } from '~/services/ContextMenu';
import { ACTOR_DRAG_TYPE } from '~/services/MapTokens';
@@ -283,6 +283,13 @@ function itemSummary(item) {
return `${t(`campaigns.item.categories.${item.category}`)} · ${t(`campaigns.item.rarities.${item.rarity}`)} · ${t('campaigns.item.quantity-short')} ${item.quantity}`;
}
// An item's icon in the sidebar: an uploaded filename served from /api/public, or a full URL
// (Foundry sends its own icon as one) — the same rule the item window uses.
function itemImageUrl(image) {
if (!image) return '';
return /^(https?:|data:|\/\/)/i.test(image) ? image : `${getBaseUrl()}/public/${image}`;
}
function mapSummary(map) {
return t('campaigns.map.summary', { size: map.gridSize, scale: map.scale });
}
@@ -670,9 +677,11 @@ onBeforeUnmount(() => {
@toggle="toggleFolder(row.folder._id)"
/>
<div v-else class="entity-entry" :style="rowIndent(row.depth)" role="button" tabindex="0" @click="openItemSheet(row.item)" @keydown.enter="openItemSheet(row.item)" @keydown.space.prevent="openItemSheet(row.item)" @contextmenu.prevent="showEntryMenu(row.item, 'item')">
<span class="entity-entry-name-row">
<span class="entity-entry-title">
<span v-if="row.item.image" class="entity-entry-image" aria-hidden="true">
<img :src="itemImageUrl(row.item.image)" alt="">
</span>
<span class="entity-entry-name">{{ row.item.name }}</span>
<span v-if="row.item.foundryItemId" class="entity-entry-sync">{{ t('campaigns.synced') }}</span>
</span>
<span class="entity-entry-meta">{{ itemSummary(row.item) }}</span>
</div>
@@ -865,6 +874,15 @@ onBeforeUnmount(() => {
}
.entity-entry-meta, .entity-entry-description { font-size: 12px; opacity: 0.72; }
.entity-entry-description { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; }
/* An item row leads with the item's own icon on the left of its name, standing in for the
"SYNCED" text it used to show (Syndria98/dragonroll#53). */
.entity-entry-title { display: flex; align-items: center; gap: 9px; min-width: 0; }
.entity-entry-image {
flex: 0 0 30px; width: 30px; height: 30px; box-sizing: border-box;
display: grid; place-items: center; overflow: hidden;
border: 1px solid var(--color-border); border-radius: 6px; background: var(--color-background-soft);
}
.entity-entry-image img { width: 100%; height: 100%; object-fit: contain; }
@media (max-width: 900px) {
.notes-sidebar {

View File

@@ -0,0 +1,289 @@
<script setup>
import { onMounted, ref } from 'vue';
import WindowHandle from './partials/WindowHandle.vue';
import Server from '~/services/Server';
import { DisplayToast } from '~/services/Toaster';
import { GetUser } from '@/services/User';
import { SetupHandle, SetSize, ResetPosition, Top, SetResizable, SetMinSize } from '@/services/Windows';
const handle = ref(null);
const wrapper = ref(null);
const props = defineProps(['data']);
const data = props.data;
const id = data.id;
// The admin standing in front of the window: their own row keeps the switches closed,
// the server answers the same to anybody who still tries (routes/user.js).
const currentUserId = GetUser()?._id;
const users = ref([]);
const busy = ref("");
const creating = ref(false);
const name = ref("");
const username = ref("");
const email = ref("");
const password = ref("");
onMounted(() => {
Top(wrapper);
SetupHandle(id, handle);
SetSize(id, {width: 620, height: 520});
ResetPosition(id, "center");
SetResizable(id, true);
SetMinSize(id, {width: 460, height: 360});
LoadUsers();
});
async function LoadUsers(){
try {
const response = await Server().get('/user/list');
if(response.data.status !== 'ok') return;
users.value = response.data.users || [];
} catch {
DisplayToast('red', $t('errors.internal'), 3000);
}
}
function ClearForm(){
name.value = "";
username.value = "";
email.value = "";
password.value = "";
}
async function CreateAccount(){
// The checks the register window makes before it asks the server for an account
if(username.value.length < 3){
DisplayToast('red', $t('settings.site-administration.accounts.errors.username-empty'), 3000);
return;
}
if(email.value.length < 5 || !email.value.includes('@')){
DisplayToast('red', $t('settings.site-administration.accounts.errors.email-empty'), 3000);
return;
}
if(name.value.length == 0){
DisplayToast('red', $t('settings.site-administration.accounts.errors.name-empty'), 3000);
return;
}
if(password.value.length == 0){
DisplayToast('red', $t('settings.site-administration.accounts.errors.password-empty'), 3000);
return;
}
creating.value = true;
try {
const response = await Server().post('/user/create', {
name: name.value,
username: username.value,
email: email.value,
password: password.value
});
if(response.data.status !== 'ok'){
DisplayToast('red', $t(response.data.msg || 'errors.internal'), 3000);
return;
}
users.value.push(response.data.user);
ClearForm();
DisplayToast('green', $t('settings.site-administration.accounts.created'), 3000);
} catch {
DisplayToast('red', $t('errors.internal'), 3000);
} finally {
creating.value = false;
}
}
async function ToggleAdmin(user){
busy.value = user._id;
try {
const response = await Server().post('/user/set-admin', { id: user._id, admin: !user.admin });
if(response.data.status !== 'ok'){
DisplayToast('red', $t(response.data.msg || 'errors.internal'), 3000);
return;
}
user.admin = response.data.user.admin;
DisplayToast('green', $t('settings.site-administration.accounts.updated'), 3000);
} catch {
DisplayToast('red', $t('errors.internal'), 3000);
} finally {
busy.value = "";
}
}
async function DeleteAccount(user){
busy.value = user._id;
try {
const response = await Server().post('/user/delete', { id: user._id });
if(response.data.status !== 'ok'){
DisplayToast('red', $t(response.data.msg || 'errors.internal'), 3000);
return;
}
users.value = users.value.filter((account) => account._id !== user._id);
DisplayToast('green', $t('settings.site-administration.accounts.deleted'), 3000);
} catch {
DisplayToast('red', $t('errors.internal'), 3000);
} finally {
busy.value = "";
}
}
function IsSelf(user){
return user._id === currentUserId;
}
</script>
<template>
<div class="window-wrapper" :id="'window-wrapper-' + id" ref="wrapper">
<WindowHandle :window="id" ref="handle"></WindowHandle>
<!-- Body -->
<div class="accounts-body">
<div class="accounts-list">
<div v-for="user in users" :key="user._id" class="account-row">
<div class="account-info">
<span class="account-name">{{ user.name }} <span v-if="IsSelf(user)" class="account-self">({{ $t('settings.site-administration.accounts.you') }})</span></span>
<span class="account-line">@{{ user.username }}</span>
<span class="account-line">{{ user.email }}</span>
<span v-if="user.admin" class="account-admin">{{ $t('settings.site-administration.accounts.admin') }}</span>
</div>
<div class="account-actions" v-if="!IsSelf(user)">
<button class="btn-primary button-small sound-click" type="button" :disabled="busy !== ''" v-on:click.prevent="ToggleAdmin(user)">
{{ user.admin ? $t('settings.site-administration.accounts.remove-admin') : $t('settings.site-administration.accounts.make-admin') }}
</button>
<button class="btn-primary button-small danger sound-click" type="button" :disabled="busy !== ''" v-on:click.prevent="DeleteAccount(user)">
{{ $t('settings.site-administration.accounts.delete') }}
</button>
</div>
</div>
</div>
<form class="new-account" v-on:submit.prevent="CreateAccount">
<h3>{{ $t('settings.site-administration.accounts.new-account') }}</h3>
<div class="form-field">
<label for="account-name-field">{{$t('settings.site-administration.accounts.name')}}</label>
<input id="account-name-field" type="text" name="name" v-model="name" autocomplete="off">
</div>
<div class="form-field">
<label for="account-username-field">{{$t('settings.site-administration.accounts.username')}}</label>
<input id="account-username-field" type="text" name="username" v-model="username" autocomplete="off">
</div>
<div class="form-field">
<label for="account-email-field">{{$t('settings.site-administration.accounts.email')}}</label>
<input id="account-email-field" type="email" name="email" v-model="email" autocomplete="off">
</div>
<div class="form-field">
<label for="account-password-field">{{$t('settings.site-administration.accounts.password')}}</label>
<input id="account-password-field" type="password" name="password" v-model="password" autocomplete="off">
</div>
<div class="form-field">
<button class="btn-primary sound-click" type="submit" :disabled="creating">
{{ $t('settings.site-administration.accounts.create') }}
</button>
</div>
</form>
</div>
</div>
</template>
<style scoped>
.window-wrapper {
display: flex;
flex-direction: column;
align-items: center;
user-select: none;
}
.accounts-body {
display: flex;
flex-direction: column;
flex: 1;
width: 100%;
min-height: 0;
}
.accounts-list {
flex: 1;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 8px;
padding: 16px;
}
.account-row {
display: flex;
justify-content: space-between;
align-items: center;
gap: 10px;
padding: 10px 12px;
border: 1px solid var(--color-border);
border-radius: 6px;
background-color: var(--color-background-soft);
}
.account-info {
display: flex;
flex-direction: column;
min-width: 0;
}
.account-name {
font-weight: bold;
}
.account-line {
font-size: 13px;
opacity: 0.75;
overflow-wrap: anywhere;
}
.account-self {
font-weight: normal;
opacity: 0.75;
}
.account-admin {
color: var(--color-green);
font-size: 13px;
}
.account-actions {
display: flex;
gap: 8px;
}
.danger {
color: var(--color-red);
}
.new-account {
padding: 0 16px 16px 16px;
border-top: 1px solid var(--color-border);
}
.new-account h3 {
font-family: MrEavesRemake;
}
.form-field {
display: flex;
flex-direction: column;
gap: 4px;
margin-bottom: 10px;
}
.form-field input {
width: 100%;
box-sizing: border-box;
}
label {
text-align: left;
}
</style>

View File

@@ -80,21 +80,15 @@ onMounted(() => {
});
function OpenManageAccounts(){
ClearWindow('settings');
ClearWindow({ type: 'settings' });
CreateWindow('account_management', {
type: 'account_management',
title: 'settings.site-administration.manage-accounts.title',
id: 'account-management',
// Back returns to the settings tab this button sits on; CreateWindow leaves
// a window that is already open alone.
back: () => {
ClearWindow('account-management')
CreateWindow('settings', {
id: 'settings',
type: 'settings',
title: 'settings.title',
back: () => { ClearWindow('settings'); CreateWindow('main_menu'); }
});
ClearWindow({ type: 'account_management' });
CreateWindow('settings');
}
})
});
}
const getLocaleName = (locale) => {

View File

@@ -34,6 +34,12 @@ const defWindows = {
},
movable: true
},
account_management: {
title: 'windows.account-management',
component: () => import('~/components/windows/AccountManagementWindow.vue'),
close: () => ClearWindow({type: 'account_management'}),
movable: true
},
create_campaign: {
title: "windows.create-campaign",
component: () => import('~/components/windows/CreateCampaignWindow.vue'),

View File

@@ -8,6 +8,30 @@
"language": "Idioma"
},
"site-administration": {
"manage-accounts": "Gestiona els comptes"
"manage-accounts": "Gestiona els comptes",
"accounts": {
"you": "tu",
"admin": "Administrador",
"make-admin": "Fes-lo administrador",
"remove-admin": "Treu-li l'administrador",
"delete": "Elimina",
"new-account": "Nou compte",
"name": "Nom",
"username": "Nom d'usuari",
"email": "Correu electrònic",
"password": "Contrasenya",
"create": "Crea el compte",
"created": "Compte creat",
"updated": "Compte actualitzat",
"deleted": "Compte eliminat",
"errors": {
"name-empty": "Si us plau, introdueix un nom.",
"username-empty": "Si us plau, introdueix un nom d'usuari.",
"email-empty": "Si us plau, introdueix un correu electrònic vàlid.",
"password-empty": "Si us plau, introdueix una contrasenya.",
"self-admin": "No pots canviar els teus propis privilegis d'administrador.",
"self-delete": "No pots eliminar el teu propi compte."
}
}
}
}

View File

@@ -5,6 +5,7 @@
"example": "Finestra d'exemple",
"edit-profile": "Editar perfil",
"settings": "Configuració",
"account-management": "Gestió dels comptes",
"create-campaign": "Crear campanya",
"create-map": "Crear mapa",
"map-viewer": "Mapa",

View File

@@ -8,6 +8,30 @@
"language": "Language"
},
"site-administration": {
"manage-accounts": "Manage accounts"
"manage-accounts": "Manage accounts",
"accounts": {
"you": "you",
"admin": "Administrator",
"make-admin": "Make administrator",
"remove-admin": "Remove administrator",
"delete": "Delete",
"new-account": "New account",
"name": "Name",
"username": "Username",
"email": "Email",
"password": "Password",
"create": "Create account",
"created": "Account created",
"updated": "Account updated",
"deleted": "Account deleted",
"errors": {
"name-empty": "Please enter a name.",
"username-empty": "Please enter a username.",
"email-empty": "Please enter a valid email address.",
"password-empty": "Please enter a password.",
"self-admin": "You cannot change your own administrator rights.",
"self-delete": "You cannot delete your own account."
}
}
}
}

View File

@@ -5,6 +5,7 @@
"example": "Example Window",
"edit-profile": "Edit Profile",
"settings": "Settings",
"account-management": "Manage accounts",
"create-campaign": "Create Campaign",
"create-map": "Create Map",
"map-viewer": "Map",

View File

@@ -8,6 +8,30 @@
"language": "Idioma"
},
"site-administration": {
"manage-accounts": "Gestionar cuentas"
"manage-accounts": "Gestionar cuentas",
"accounts": {
"you": "tú",
"admin": "Administrador",
"make-admin": "Nombrar administrador",
"remove-admin": "Quitar administrador",
"delete": "Eliminar",
"new-account": "Nueva cuenta",
"name": "Nombre",
"username": "Nombre de usuario",
"email": "Correo electrónico",
"password": "Contraseña",
"create": "Crear cuenta",
"created": "Cuenta creada",
"updated": "Cuenta actualizada",
"deleted": "Cuenta eliminada",
"errors": {
"name-empty": "Por favor, introduce un nombre.",
"username-empty": "Por favor, introduce un nombre de usuario.",
"email-empty": "Por favor, introduce un correo electrónico válido.",
"password-empty": "Por favor, introduce una contraseña.",
"self-admin": "No puedes cambiar tus propios privilegios de administrador.",
"self-delete": "No puedes eliminar tu propia cuenta."
}
}
}
}

View File

@@ -5,6 +5,7 @@
"example": "Ventana de ejemplo",
"edit-profile": "Editar perfil",
"settings": "Configuración",
"account-management": "Gestionar cuentas",
"create-campaign": "Crear campanya",
"create-map": "Crear mapa",
"map-viewer": "Mapa",

View File

@@ -0,0 +1,417 @@
// Tests for the D&D 5e details the system keeps as a reference to an embedded item
// (Syndria98/dragonroll#54). `system.details.background` and `system.details.race` are
// LocalDocumentFields: they hold the id of the actor's background / race item and never
// its name, and their `fallback` option hands the bare id back when that item is gone.
// Dragonroll holds names, so reading the id as a name and writing it back gave Foundry a
// background item that does not exist and a details reference resolving to nothing —
// adding a background in Foundry then failed.
//
// The backend mapper is plain CommonJS and is required directly. The Foundry module is
// loaded into a `node:vm` context holding stubbed Foundry globals with fake timers, like
// tests/foundry-sync-toggle.test.js: the characters Dragonroll answers with are applied
// to a stubbed actor, so the references it writes are observable.
//
// Run with `npm test` from the repository root, or `node --test tests/`.
const { test } = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const MODULE_ID = "dragonroll-foundry";
const read = (...parts) => fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8");
const { foundryActorToCharacter } = require(path.join(__dirname, "..", "backend", "src", "services", "actor-foundry.js"));
// Foundry generates document ids as sixteen characters of its alphabet, digits included.
const ID_GONE = "aB3cD9eF1gH2iJ4k";
const ID_SOLDIER = "Kx7pQ2mR9vT4wZ8n";
const ID_HUMAN = "7QcL2fYh5Bd0Mn3s";
function foundryActor(details = {}, items = []) {
return { _id: "actor-1", name: "Thalia", type: "character", system: { details }, items };
}
test("a background carried as an item arrives by its name, not its id", () => {
const character = foundryActor(
{ background: ID_SOLDIER },
[{ _id: ID_SOLDIER, name: "Soldier", type: "background" }],
);
assert.equal(foundryActorToCharacter(character).background, "Soldier");
});
test("a background reference whose item is gone does not become a background", () => {
// The item was deleted, and `fallback: true` gives the id back instead.
const character = foundryActor({ background: ID_GONE }, []);
assert.equal(foundryActorToCharacter(character).background, "");
});
test("a background item takes the place of a reference that resolves to nothing", () => {
const character = foundryActor(
{ background: ID_GONE },
[{ _id: ID_SOLDIER, name: "Soldier", type: "background" }],
);
assert.equal(foundryActorToCharacter(character).background, "Soldier");
});
test("a plain-text background from an older system release is still a name", () => {
const character = foundryActor({ background: "Sailor" }, []);
assert.equal(foundryActorToCharacter(character).background, "Sailor");
});
test("the class, subclass and species references resolve the same way", () => {
const items = [
{ _id: ID_HUMAN, name: "Human", type: "race" },
{ _id: "cls1Id00000000", name: "Fighter", type: "class" },
{ _id: "sub1Id00000000", name: "Oracle", type: "subclass" },
];
const character = foundryActor(
{ race: ID_HUMAN, class: "cls1Id00000000", subclass: "sub1Id00000000" },
items,
);
const fields = foundryActorToCharacter(character);
assert.equal(fields.species, "Human");
assert.equal(fields.className, "Fighter");
assert.equal(fields.subclass, "Oracle");
});
test("a class reference that resolves to nothing falls back to the class item", () => {
const character = foundryActor(
{ class: ID_GONE, race: ID_GONE },
[{ _id: "cls1Id00000000", name: "Fighter", type: "class" }],
);
const fields = foundryActorToCharacter(character);
assert.equal(fields.className, "Fighter", "the class the actor carries, not the id");
assert.equal(fields.species, "", "and nothing to name the species from");
});
// --- The Foundry module applies Dragonroll's character --------------------------
// A reference is either the id this sync wrote or the document the field resolves to.
function referenceId(actor, field) {
const value = actor.system.details?.[field];
return typeof value === "string" ? value : value?._id || "";
}
function makeStubItem(id, { name, type, system = {}, flags = {} }) {
return {
_id: id,
id,
name,
type,
system,
flags,
parent: { documentName: "Actor" },
getFlag(module, key) { return this.flags?.[module]?.[key]; },
toObject() {
return { _id: this.id, name: this.name, type: this.type, system: this.system, flags: this.flags };
},
};
}
function writeDotted(target, data) {
for (const [key, value] of Object.entries(data)) {
const parts = key.split(".");
const last = parts.pop();
let node = target;
for (const part of parts) node = node[part] ??= {};
node[last] = value;
}
}
let stubCounter = 0;
function makeStubActor(name, { type = "character", system = {}, flags = {}, items = [] } = {}) {
stubCounter += 1;
const id = `actor-${stubCounter}`;
const contents = items.map((item, index) => makeStubItem(item._id || `embedded-${stubCounter}-${index}`, item));
const actor = {
id,
name,
type,
documentName: "Actor",
img: "icons/svg/mystery-man.svg",
system,
flags,
items: { contents },
getFlag(module, key) { return this.flags?.[module]?.[key]; },
async update(data) {
writeDotted(this, data);
return this;
},
async updateEmbeddedDocuments(documentName, updates) {
for (const update of updates) {
const item = contents.find((candidate) => candidate.id === update._id);
if (item) writeDotted(item, update);
}
return updates.map((update) => contents.find((candidate) => candidate.id === update._id));
},
async createEmbeddedDocuments(documentName, datas) {
const created = datas.map((data) => {
const item = makeStubItem(`embedded-${stubCounter}-${contents.length}`, data);
item.name = data.name;
item.type = data.type;
contents.push(item);
return item;
});
return created;
},
async deleteEmbeddedDocuments(documentName, ids) {
for (const id of ids) {
const index = contents.findIndex((item) => item.id === id);
if (index >= 0) contents.splice(index, 1);
}
return ids;
},
toObject() {
return {
_id: this.id,
name: this.name,
type: this.type,
img: this.img,
flags: this.flags,
system: this.system,
};
},
};
return actor;
}
// A linked world with the actors it holds, answering `foundry/sync/characters` with the
// campaign's characters. Each one is applied to its Foundry actor on the next reconcile.
function makeWorld({ actors = [], remoteActors = [] } = {}) {
const state = {
hooks: new Map(),
registered: new Map(),
requests: [],
timers: new Map(),
nextTimerId: 1,
logs: [],
};
const settingsStore = { autoSync: true, syncToken: "sync-token-1", dragonrollApiUrl: "http://backend.test:5000" };
const sandbox = {
console: {
log() {},
info() {},
warn: (...args) => state.logs.push(args.map(String).join(" ")),
error: (...args) => state.logs.push(args.map(String).join(" ")),
},
URL,
CONFIG: {},
window: { location: { origin: "http://vtt.test" } },
ui: { notifications: { info() {}, warn() {}, error() {} } },
Hooks: {
once(name, fn) { state.hooks.set(name, [fn]); },
on(name, fn) { state.hooks.set(name, [...(state.hooks.get(name) || []), fn]); },
},
setTimeout: (fn, delay = 0) => {
const timerId = state.nextTimerId++;
state.timers.set(timerId, { fn, delay });
return timerId;
},
clearTimeout: (timerId) => state.timers.delete(timerId),
setInterval: () => 0,
clearInterval: () => {},
fetch: async (url, options = {}) => {
const href = String(url);
state.requests.push({ href, method: options.method, body: options.body ? JSON.parse(options.body) : null });
if (href.includes("foundry/sync/characters")) return { ok: true, status: 200, json: async () => ({ status: "ok", actors: remoteActors }) };
if (href.includes("foundry/sync/items")) return { ok: true, status: 200, json: async () => ({ status: "ok", items: [] }) };
return { ok: true, status: 200, json: async () => ({ status: "ok", actors: [], items: [] }) };
},
Item: { async create() { return null; } },
Actor: {
async create(data) {
const actor = makeStubActor(data.name, {
type: data.type,
system: structuredClone(data.system || {}),
flags: structuredClone(data.flags || {}),
items: (data.items || []).map((item) => ({ name: item.name, type: item.type, system: item.system })),
});
actors.push(actor);
return actor;
},
},
};
sandbox.game = {
user: { isGM: true },
world: { id: "world-1", title: "Test World" },
system: { id: "dnd5e" },
modules: { get: () => ({}) },
actors: { contents: actors, get: (actorId) => actors.find((actor) => actor.id === actorId) },
items: { contents: [], get: () => null },
folders: { contents: [], get: () => null },
settings: {
register(module, key, definition) {
state.registered.set(key, definition);
if (!(key in settingsStore)) settingsStore[key] = definition.default;
},
get(module, key) { return settingsStore[key]; },
async set(module, key, value) {
settingsStore[key] = value;
await state.registered.get(key)?.onChange?.(value);
},
},
};
vm.createContext(sandbox);
vm.runInContext(read("dragonroll-foundry", "scripts", "api.js"), sandbox);
state.game = sandbox.game;
state.actor = (actorId) => actors.find((actor) => actor.id === actorId);
const drain = async () => { await new Promise((resolve) => setImmediate(resolve)); };
// World start: the actors are pushed, then the campaign's characters are applied.
state.start = async () => {
await state.fire("init");
await state.fire("ready");
await state.runTimers();
return state;
};
state.fire = async (name, ...args) => {
for (const handler of state.hooks.get(name) || []) await handler(...args);
await drain();
};
state.runTimers = async () => {
for (let round = 0; round < 6; round += 1) {
if (!state.timers.size && round > 2) break;
const due = [...state.timers.values()];
state.timers.clear();
for (const timer of due) await timer.fn();
await drain();
}
};
state.itemNames = (actor) => actor.items.contents.map((item) => [item.type, item.name]);
return state;
}
// The campaign's character for `actor`, holding what Dragonroll keeps for it.
function campaignCharacter(actor, over = {}) {
return {
_id: "dr-actor-1",
name: "Thalia",
type: "character",
species: "",
className: "",
subclass: "",
level: 1,
background: "",
challengeRating: "",
description: "",
image: "",
abilityScores: {},
armorClass: 10,
speed: 30,
traits: "",
proficiencies: "",
spells: "",
inventory: [],
foundryActorId: actor?.id ?? null,
...over,
};
}
test("Dragonroll's background becomes the actor's background item, referenced by id", async () => {
const actor = makeStubActor("Thalia", {
system: { details: { background: "" } },
flags: { [MODULE_ID]: { actorId: "dr-actor-1" } },
});
const world = await makeWorld({
actors: [actor],
remoteActors: [campaignCharacter(actor, { background: "Soldier" })],
}).start();
const background = actor.items.contents.find((item) => item.type === "background");
assert.ok(background, "the character's background stands in Foundry as an item");
assert.equal(background.name, "Soldier");
assert.equal(referenceId(actor, "background"), background.id, "its details reference points at the item");
assert.equal(actor.system.details.background, background.id);
assert.deepEqual(world.logs, [], "applying the character did not warn");
});
test("the background an earlier sync invented is taken back out", async () => {
// What the bug left behind: an item named after the id the details field held, next to
// the real background, and a reference the old sync overwrote with that id.
const actor = makeStubActor("Thalia", {
system: { details: { background: ID_GONE } },
flags: { [MODULE_ID]: { actorId: "dr-actor-1" } },
items: [
{ _id: ID_SOLDIER, name: "Soldier", type: "background", flags: { [MODULE_ID]: { syncedItem: true } } },
{ _id: "item-bogus", name: ID_GONE, type: "background", flags: { [MODULE_ID]: { syncedItem: true } } },
],
});
const world = await makeWorld({
actors: [actor],
remoteActors: [campaignCharacter(actor, { background: "Soldier" })],
}).start();
assert.deepEqual(world.itemNames(actor), [["background", "Soldier"]], "only the real background is left");
assert.equal(referenceId(actor, "background"), ID_SOLDIER, "and the reference resolves to it");
});
test("a background taken off in Dragonroll clears the reference", async () => {
const actor = makeStubActor("Thalia", {
system: { details: { background: ID_SOLDIER } },
flags: { [MODULE_ID]: { actorId: "dr-actor-1" } },
items: [
{ _id: ID_SOLDIER, name: "Soldier", type: "background", flags: { [MODULE_ID]: { syncedItem: true } } },
],
});
const world = await makeWorld({ actors: [actor], remoteActors: [campaignCharacter(actor)] }).start();
assert.deepEqual(world.itemNames(actor), [], "the background item went with it");
assert.equal(referenceId(actor, "background"), "", "and no reference is left pointing at nothing");
});
test("a species never lands in the details reference as a name", async () => {
const actor = makeStubActor("Thalia", {
// A species picked in the sheet: dnd5e made the race item and referenced it by id.
system: { details: { race: ID_HUMAN } },
flags: { [MODULE_ID]: { actorId: "dr-actor-1" } },
items: [{ _id: ID_HUMAN, name: "Human", type: "race", flags: { [MODULE_ID]: { syncedItem: true } } }],
});
await makeWorld({
actors: [actor],
remoteActors: [campaignCharacter(actor, { species: "Human", background: "Soldier" })],
}).start();
assert.equal(referenceId(actor, "race"), ID_HUMAN, "the species reference still points at the race item");
assert.notEqual(actor.system.details.race, "Human", "a name in it would resolve to nothing");
});
test("a species the world keeps as plain text is left to the world", async () => {
// An actor migrated from an older system release: no race item, the name is what the
// field holds, and Dragonroll has nothing to reference.
const actor = makeStubActor("Thalia", {
system: { details: { race: "Human" } },
flags: { [MODULE_ID]: { actorId: "dr-actor-1" } },
});
await makeWorld({
actors: [actor],
remoteActors: [campaignCharacter(actor, { species: "Human" })],
}).start();
assert.equal(actor.system.details.race, "Human", "the text the sheet reads is kept as it was");
});
test("a character made in Dragonroll references the background it is created with", async () => {
const world = await makeWorld({ actors: [], remoteActors: [campaignCharacter(null, { background: "Soldier" })] }).start();
const [actor] = world.game.actors.contents;
assert.ok(actor, "the campaign's character was made in this world");
const background = actor.items.contents.find((item) => item.type === "background");
assert.ok(background, "created together with its background item");
assert.equal(background.name, "Soldier");
assert.equal(referenceId(actor, "background"), background.id, "referenced by that item's id, never its name");
});

View File

@@ -0,0 +1,69 @@
// Tests for Syndria98/dragonroll#53: the item row in the campaign sidebar dropped its "SYNCED"
// text badge and now leads with the item's own icon on the left of the entry.
//
// The repository root installs no dependencies, so these read the sidebar component the way
// tests/sidebar-entity-entry.test.js does — the checks are about the markup and style of the row.
//
// Run with `npm test` from the repository root, or `node --test tests/`.
const { test } = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const source = fs.readFileSync(
path.join(__dirname, "..", "frontend", "app", "components", "partials", "ContentSidebar.vue"),
"utf8"
);
// The block that renders the item rows, from the items section down to its closing template. The
// items section is followed by the maps section (`v-else`), so the first `</template>` that leads
// there ends it; the inner `v-for` close is followed by another close, not by `v-else`.
const itemSection =
/<template v-else-if="activeSection === 'items'">([\s\S]*?)<\/template>\s*\n\s*<template v-else>/.exec(source)?.[1] ?? "";
// `selector` is inserted verbatim, so escape the `.` of a class combination. Comments are dropped:
// they explain a rule, they are not part of it.
function ruleFor(selector) {
const rule = new RegExp(`\\.${selector}\\s*\\{([^}]*)\\}`).exec(source)?.[0];
return rule?.replace(/\/\*[\s\S]*?\*\//g, "");
}
test("the item entry no longer shows the SYNCED text", () => {
assert.ok(itemSection, "expected to find the items section of the sidebar");
assert.doesNotMatch(itemSection, /campaigns\.synced/, "the item row must not render the synced text");
assert.doesNotMatch(itemSection, /entity-entry-sync/, "the item row must not render the synced badge");
});
test("the item entry shows the item's image on the left when it has one", () => {
// the icon renders only for an item that carries an image, resolved through the helper...
assert.match(
itemSection,
/<span v-if="row\.item\.image" class="entity-entry-image"[\s\S]*?<img :src="itemImageUrl\(row\.item\.image\)"/
);
// ...and on the left: it stands before the name in the row markup.
assert.ok(
itemSection.indexOf("entity-entry-image") < itemSection.indexOf("entity-entry-name"),
"the item image must stand to the left of the name"
);
});
test("the item entry lays the icon out beside the name", () => {
const title = ruleFor("entity-entry-title");
assert.ok(title, "expected a .entity-entry-title style rule");
assert.match(title, /display:\s*flex/, "the icon and the name sit side by side");
const image = ruleFor("entity-entry-image");
assert.ok(image, "expected a .entity-entry-image style rule");
assert.match(image, /overflow:\s*hidden/, "the icon is clipped to its box");
});
test("an item image resolves like the item window: uploads from /public, full URLs as they are", () => {
assert.match(source, /import Server, \{ getBaseUrl \} from ['"]~\/services\/Server['"]/);
const resolver = /function itemImageUrl\(image\)\s*\{[\s\S]*?\n\}/.exec(source)?.[0] ?? "";
assert.ok(resolver, "expected an itemImageUrl helper");
assert.match(resolver, /https\?:/, "a full http(s) URL loads as it is");
assert.match(resolver, /data:/, "a data URI loads as it is");
assert.match(resolver, /\$\{getBaseUrl\(\)\}\/public\//, "an uploaded filename resolves as a /public file");
});

View File

@@ -0,0 +1,217 @@
// Tests for "Manage accounts" of Syndria98/dragonroll#51: the button on the settings window's site
// administration tab opened a window type (`account_management`) that was never registered in
// `WindowDefinitions.js`, so `getComponent` dereferenced `defWindows[type].component` on `undefined` —
// `can't access property "component", (intermediate value)[type] is undefined` — instead of opening
// anything. The window is the site administration screen now (list accounts, create one, grant or
// take administrator rights, delete one), guarded on the backend by the `isAdmin` middleware.
//
// Like tests/settings-window.test.js, the window wiring is read from the sources; the window registry
// is also checked against every window type the frontend opens, which is what catches this class of
// bug before the click does.
//
// Run with `npm test` from the repository root, or `node --test tests/`.
const { test } = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const read = (...parts) => fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8");
const frontendApp = path.join(__dirname, "..", "frontend", "app");
const windowDefsSource = read("frontend", "app", "services", "WindowDefinitions.js");
const settingsWindowSource = read("frontend", "app", "components", "windows", "SettingsWindow.vue");
const accountsWindowSource = read("frontend", "app", "components", "windows", "AccountManagementWindow.vue");
const userRouteSource = read("backend", "src", "routes", "user.js");
// -- the window registry -------------------------------------------------------
// Top-level entries of `defWindows`: every entry sits at 2 spaces, its contents at 4+.
function registryEntries() {
const header = /^ {2}([A-Za-z_]\w*):\s*\{/gm;
const marks = [];
let match;
while ((match = header.exec(windowDefsSource))) marks.push({ type: match[1], index: match.index });
assert.ok(marks.length > 0, "expected window definitions to register windows");
const entries = {};
marks.forEach((mark, i) => {
const end = i + 1 < marks.length ? marks[i + 1].index : windowDefsSource.length;
entries[mark.type] = windowDefsSource.slice(mark.index, end);
});
return entries;
}
function* sourceFiles(dir) {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) yield* sourceFiles(full);
else if (/\.(vue|js|ts)$/.test(entry.name)) yield full;
}
}
test("account_management is a registered window with a component on disk", () => {
const entries = registryEntries();
const definition = entries["account_management"];
assert.ok(definition, "account_management must be registered or getComponent opens undefined");
assert.match(definition, /AccountManagementWindow\.vue/);
const component = path.join(frontendApp, "components", "windows", "AccountManagementWindow.vue");
assert.ok(fs.existsSync(component), "the window component file must exist");
});
test("no window is opened with a type that is not registered", () => {
const registered = registryEntries();
// The type is the first string argument of CreateWindow; CreateChildWindow takes a parent
// (GetFirstWindowId('main_menu')-style, a registered type itself) before the type. Data
// objects after it hold strings that mean nothing to the registry, so they stay unmatched.
const createWindow = /CreateWindow\(\s*['"]([a-z_]+)['"]/g;
const createChildWindow = /CreateChildWindow\(\s*(?:GetFirstWindowId\(\s*['"]([a-z_]+)['"]\s*\)|[a-z_]+)\s*,\s*['"]([a-z_]+)['"]/g;
for (const file of sourceFiles(frontendApp)) {
const source = fs.readFileSync(file, "utf8");
const found = [...source.matchAll(createWindow), ...source.matchAll(createChildWindow)];
for (const match of found) {
for (const type of match.slice(1)) {
if (!type) continue;
assert.ok(
registered[type],
`${path.relative(frontendApp, file)} opens '${type}', which WindowDefinitions.js does not define`
);
}
}
}
});
test("every registered window points at a component file that exists", () => {
for (const [type, definition] of Object.entries(registryEntries())) {
const imported = /import\(['"]([^'"]+)['"]\)/.exec(definition)?.[1];
assert.ok(imported, `${type} must import a component`);
const file = path.join(frontendApp, imported.replace(/^~\//, ""));
assert.ok(fs.existsSync(file), `${type} points at ${imported}, which is not there`);
}
});
// -- opening it from the settings window ----------------------------------------
const openManageAccounts = /function OpenManageAccounts\(\)\s*\{[\s\S]*?\n\}/.exec(settingsWindowSource)?.[0];
test("the settings tab opens the account window and can come back", () => {
assert.ok(openManageAccounts, "expected an OpenManageAccounts in the settings window");
assert.match(openManageAccounts, /CreateWindow\(\s*'account_management'/);
// ClearWindow takes a selector object; a bare string matched neither `selector.type` nor
// `selector.id` and closed nothing, leaving both windows stacked.
assert.match(openManageAccounts, /ClearWindow\(\s*\{\s*type:\s*'settings'\s*\}\s*\)/);
assert.match(openManageAccounts, /ClearWindow\(\s*\{\s*type:\s*'account_management'\s*\}\s*\)/);
assert.match(openManageAccounts, /CreateWindow\(\s*'settings'/, "back returns to the settings window");
assert.doesNotMatch(settingsWindowSource, /ClearWindow\(\s*['"]/g, "no ClearWindow call may pass a bare string");
});
// -- the account management window ------------------------------------------------
test("the account window talks to the account management endpoints", () => {
assert.match(accountsWindowSource, /Server\(\)\.get\(['"]\/user\/list['"]/);
assert.match(accountsWindowSource, /Server\(\)\.post\(['"]\/user\/create['"]/);
assert.match(accountsWindowSource, /Server\(\)\.post\(['"]\/user\/set-admin['"]/);
assert.match(accountsWindowSource, /Server\(\)\.post\(['"]\/user\/delete['"]/);
});
test("the window closes the switches on the row of the admin using it", () => {
// The server answers the same way to anybody who still posts it (see below); the row just
// does not invite the attempt.
assert.match(accountsWindowSource, /v-if="!IsSelf\(user\)"/);
assert.match(accountsWindowSource, /GetUser\(\)\?\._id/);
});
// -- the backend routes -----------------------------------------------------------
function routeDeclaration(method, route) {
const declaration = new RegExp(`router\\.${method}\\(['"]${route}['"][^\\n]*`).exec(userRouteSource)?.[0];
assert.ok(declaration, `expected a ${method.toUpperCase()} ${route} route`);
// /api/user is mounted before the JWT guard: without inline authentication the route would
// be public to any request (landmine 5 of AGENTS.md), and only an admin may manage accounts.
assert.match(declaration, /passport\.authenticate\(['"]jwt['"]/);
assert.match(declaration, /isAdmin/, `${route} may only be answered for an administrator`);
return declaration;
}
function routeBlock(method, route) {
const start = userRouteSource.indexOf(`router.${method}('${route}'`);
assert.ok(start !== -1, `expected a ${method.toUpperCase()} ${route} route`);
const next = userRouteSource.indexOf(`\nrouter.`, start + 1);
return userRouteSource.slice(start, next === -1 ? userRouteSource.length : next);
}
test("GET /user/list answers the accounts without passwords or setup codes", () => {
routeDeclaration("get", "/list");
assert.match(routeBlock("get", "/list"), /select\(['"]-password -setupCode['"]\)/);
});
test("POST /user/create stores a hashed password and refuses duplicates", () => {
const block = routeBlock("post", "/create");
assert.match(block, /bcrypt\.hash\(password/, "the password must not go in as it came");
assert.match(block, /register\.errors\.email-username-exists/, "duplicates answer with the register message");
assert.doesNotMatch(block, /setupCode/, "no half-finished setup account is invented here");
});
for (const route of ["/set-admin", "/delete"]) {
test(`POST /user${route} refuses to act on the admin that is asking`, () => {
routeDeclaration("post", route);
const block = routeBlock("post", route);
assert.match(block, /String\(req\.user\._id\) === String\(id\)/, "an admin keeps their own account closed");
assert.match(block, /errors\.internal/);
});
}
// -- i18n --------------------------------------------------------------------------
test("every locale titles the account window and names its strings", () => {
const required = [
"accounts.you",
"accounts.admin",
"accounts.make-admin",
"accounts.remove-admin",
"accounts.delete",
"accounts.new-account",
"accounts.name",
"accounts.username",
"accounts.email",
"accounts.password",
"accounts.create",
"accounts.created",
"accounts.updated",
"accounts.deleted",
"accounts.errors.self-admin",
"accounts.errors.self-delete",
];
for (const locale of ["en", "es", "ca"]) {
const windows = JSON.parse(read("frontend", "i18n", "locales", locale, "windows.json"));
assert.ok(windows["account-management"]?.trim(), `${locale} is missing the account window title`);
const settings = JSON.parse(read("frontend", "i18n", "locales", locale, "settings.json"));
assert.ok(settings["site-administration"]?.["manage-accounts"]?.trim(), `${locale} is missing manage accounts`);
for (const key of required) {
const value = key.split(".").reduce((node, part) => node?.[part], settings["site-administration"]);
assert.ok(value?.trim(), `${locale} is missing settings.site-administration.${key}`);
}
}
});
test("every accounts string the window translates exists in every locale", () => {
// $t keys with nothing to translate fall back to the key itself, so every accounts key the
// window uses has to be carried by every locale. (`errors.internal` is the envelope fallback
// every window toasts the same way and stays out of it.)
const used = [...new Set(
[...accountsWindowSource.matchAll(/\$t\(\s*['"](settings\.site-administration\.accounts\.[\w.-]+)['"]/g)]
.map((key) => key[1])
)];
assert.ok(used.length >= 14, `expected the window's translated strings, found ${used.length}`);
for (const locale of ["en", "es", "ca"]) {
const settings = JSON.parse(read("frontend", "i18n", "locales", locale, "settings.json"));
for (const key of used) {
const value = key.split(".").slice(1).reduce((node, part) => node?.[part], settings);
assert.ok(typeof value === "string" && value.trim(), `${locale} is missing ${key}`);
}
}
});