server be & fe

This commit is contained in:
azykov@mail.ru
2026-09-29 13:50:01 +03:00
commit 657009bd6c
56 changed files with 6162 additions and 0 deletions
+12
View File
@@ -0,0 +1,12 @@
# Copy to .env and fill in.
# Public host names the dev/preview server answers to (comma-separated).
ALLOWED_HOSTS=dev.aggtaa.com
# ---- Local development without the reverse proxy only ----
# The admin UI calls /api/admin/*. Behind the real proxy these requests never reach this server.
# Locally, Vite emulates the proxy: forwards /api/* to server-be with /api stripped.
# BACKEND_URL=http://127.0.0.1:10002
# ADMIN_PROXY_SECRET=
# Fakes the Remote-Email header set by Authelia. NEVER set it behind the real proxy.
# DEV_REMOTE_EMAIL=
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="color-scheme" content="dark" />
<title>Cardy Admin</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+28
View File
@@ -0,0 +1,28 @@
{
"name": "@cardy/server-fe",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"start": "vite build && vite preview",
"typecheck": "tsc -p tsconfig.json"
},
"dependencies": {
"@cardy/shared": "workspace:*",
"bwip-js": "^4.11.4",
"qrcode": "^1.5.4",
"react": "^19.3.0",
"react-dom": "^19.3.0"
},
"devDependencies": {
"@types/qrcode": "^1.5.6",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"@vitejs/plugin-react": "^6.1.1",
"typescript": "^7.0.2",
"vite": "^8.3.1"
}
}
+102
View File
@@ -0,0 +1,102 @@
import { useEffect, useState } from 'react';
import type { MeResponse } from '@cardy/shared';
import { api, ApiError } from './api.js';
import { ErrorText, useLoad } from './components.js';
import { CardEditorPage } from './pages/CardEditor.js';
import { CardsPage } from './pages/Cards.js';
import { GroupsPage } from './pages/Groups.js';
import { MyKeysPage } from './pages/MyKeys.js';
import { UsersPage } from './pages/Users.js';
import { linkClick, navigate, usePath } from './router.js';
export function App() {
const me = useLoad(api.me);
// Bumped when the superadmin switches groups so pages reload their data.
const [groupEpoch, setGroupEpoch] = useState(0);
if (me.loading && !me.data) return <div className="center muted">Loading…</div>;
if (!me.data) {
return (
<div className="center">
<h1>Cardy</h1>
<p className="error">{me.error}</p>
</div>
);
}
return <Shell me={me.data} groupEpoch={groupEpoch} onGroupChanged={async () => { await me.reload(); setGroupEpoch((e) => e + 1); }} />;
}
function Shell({ me, groupEpoch, onGroupChanged }: { me: MeResponse; groupEpoch: number; onGroupChanged: () => Promise<void> }) {
const path = usePath();
const isAdmin = me.role !== 'user';
const isSuper = me.role === 'superadmin';
const tabs = [
...(isAdmin ? [{ path: '/cards', label: 'Cards' }, { path: '/users', label: 'Users' }] : []),
...(isSuper ? [{ path: '/groups', label: 'Groups' }] : []),
{ path: '/keys', label: 'My keys' },
];
let page = null;
const cardMatch = /^\/cards\/([^/]+)$/.exec(path);
if (isAdmin && cardMatch) page = <CardEditorPage cardId={cardMatch[1]!} />;
else if (isAdmin && path === '/cards') page = <CardsPage />;
else if (isAdmin && path === '/users') page = <UsersPage me={me} />;
else if (isSuper && path === '/groups') page = <GroupsPage me={me} onGroupsChanged={onGroupChanged} />;
else if (path === '/keys') page = <MyKeysPage me={me} />;
useEffect(() => {
if (!page) navigate(isAdmin ? '/cards' : '/keys', { replace: true });
});
return (
<div className="app">
<header className="topbar">
<div className="brand">Cardy</div>
<nav>
{tabs.map((t) => (
<a key={t.path} href={t.path} onClick={linkClick} className={path.startsWith(t.path) ? 'active' : ''}>
{t.label}
</a>
))}
</nav>
<div className="topbar-right">
{isSuper ? <GroupSwitcher me={me} onChanged={onGroupChanged} epoch={groupEpoch} /> : <span className="pill">{me.currentGroup.name}</span>}
<span className="muted small" title={me.role}>
{me.email} · {me.role}
</span>
</div>
</header>
<main key={groupEpoch}>{page}</main>
</div>
);
}
function GroupSwitcher({ me, onChanged, epoch }: { me: MeResponse; onChanged: () => Promise<void>; epoch: number }) {
const groups = useLoad(api.groups, [epoch]);
const [error, setError] = useState<string>();
return (
<label className="group-switcher">
<span className="muted small">Group</span>
<select
value={me.currentGroup.id}
onChange={async (e) => {
try {
await api.setCurrentGroup(e.target.value);
setError(undefined);
await onChanged();
} catch (err) {
setError(err instanceof ApiError ? err.message : String(err));
}
}}
>
{(groups.data ?? [me.currentGroup]).map((g) => (
<option key={g.id} value={g.id}>
{g.name}
</option>
))}
</select>
<ErrorText error={error ?? groups.error} />
</label>
);
}
+97
View File
@@ -0,0 +1,97 @@
import type { AccessKeyView, Card, CardFields, CardPatch, Group, MeResponse, Role, UserView } from '@cardy/shared';
// Reverse proxy: /api/admin/* goes through Authelia to server-be.
const BASE = '/api/admin';
const RELOAD_MARK = 'cardy:auth-reload';
export class ApiError extends Error {
constructor(
readonly status: number,
message: string,
) {
super(message);
}
}
/**
* A 401 without Cardy's JSON body comes from Authelia (session expired): reload the page so
* Authelia shows its login form. Guarded against reload loops.
*/
function reloadForLogin(): boolean {
let last = 0;
try {
last = Number(sessionStorage.getItem(RELOAD_MARK) ?? 0);
if (Date.now() - last < 15_000) return false;
sessionStorage.setItem(RELOAD_MARK, String(Date.now()));
} catch {
return false;
}
location.reload();
return true;
}
async function request<T>(method: string, path: string, body?: unknown): Promise<T> {
// Accept/X-Requested-With make Authelia answer 401 instead of redirecting to its login page.
const headers: Record<string, string> = { Accept: 'application/json', 'X-Requested-With': 'XMLHttpRequest' };
if (method !== 'GET') headers['X-Cardy-Admin'] = '1';
let payload: BodyInit | undefined;
if (body instanceof FormData) payload = body;
else if (body !== undefined) {
headers['Content-Type'] = 'application/json';
payload = JSON.stringify(body);
}
const res = await fetch(BASE + path, { method, headers, body: payload, credentials: 'same-origin' });
if (!res.ok) {
let cardyError: string | undefined;
try {
cardyError = ((await res.json()) as { error?: string }).error;
} catch {
// not JSON: the response came from the proxy or Authelia
}
if (res.status === 401 && cardyError === undefined && reloadForLogin()) {
await new Promise(() => undefined); // page is reloading
}
throw new ApiError(res.status, cardyError ?? `${res.status} ${res.statusText}`);
}
return (res.status === 204 ? undefined : await res.json()) as T;
}
const enc = encodeURIComponent;
function files(list: File[]): FormData {
const form = new FormData();
for (const f of list) form.append('file', f, f.name);
return form;
}
export const api = {
me: () => request<MeResponse>('GET', '/me'),
myKeys: () => request<AccessKeyView[]>('GET', '/my-keys'),
groups: () => request<Group[]>('GET', '/groups'),
createGroup: (name: string) => request<Group>('POST', '/groups', { name }),
renameGroup: (id: string, name: string) => request<Group>('PATCH', `/groups/${enc(id)}`, { name }),
deleteGroup: (id: string) => request<void>('DELETE', `/groups/${enc(id)}`),
setCurrentGroup: (groupId: string) => request<Group>('PUT', '/current-group', { groupId }),
users: () => request<UserView[]>('GET', '/users'),
createUser: (email: string, role: Role) => request<UserView>('POST', '/users', { email, role }),
updateUser: (email: string, patch: { role?: Role; groupId?: string }) =>
request<UserView>('PATCH', `/users/${enc(email)}`, patch),
deleteUser: (email: string) => request<void>('DELETE', `/users/${enc(email)}`),
createKey: (email: string, label: string) => request<AccessKeyView>('POST', `/users/${enc(email)}/keys`, { label }),
deleteKey: (email: string, keyId: string) => request<void>('DELETE', `/users/${enc(email)}/keys/${enc(keyId)}`),
cards: () => request<Card[]>('GET', '/cards'),
createCard: (fields: CardFields) => request<Card>('POST', '/cards', fields),
updateCard: (id: string, patch: CardPatch) => request<Card>('PATCH', `/cards/${enc(id)}`, patch),
/** Marks as deleted; for an already deleted card removes it permanently (returns undefined). */
deleteCard: (id: string) => request<Card | undefined>('DELETE', `/cards/${enc(id)}`),
setLogo: (id: string, file: File) => request<Card>('PUT', `/cards/${enc(id)}/logo`, files([file])),
removeLogo: (id: string) => request<Card>('DELETE', `/cards/${enc(id)}/logo`),
addImages: (id: string, list: File[]) => request<Card>('POST', `/cards/${enc(id)}/images`, files(list)),
removeImage: (id: string, imageId: string) => request<Card>('DELETE', `/cards/${enc(id)}/images/${enc(imageId)}`),
logoUrl: (card: Card) => `${BASE}/cards/${enc(card.id)}/logo?v=${card.imagesVersion}`,
imageUrl: (card: Card, imageId: string) => `${BASE}/cards/${enc(card.id)}/images/${enc(imageId)}`,
};
+214
View File
@@ -0,0 +1,214 @@
import QRCode from 'qrcode';
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import {
BWIP_BCID,
TWO_DIMENSIONAL_CODE_TYPES,
cardAbbreviation,
textColorOn,
type AccessKeyView,
type Card,
type CodeType,
} from '@cardy/shared';
import { api } from './api.js';
/** Loads data and exposes a reload function; errors are reported via `error`. */
export function useLoad<T>(load: () => Promise<T>, deps: unknown[] = []) {
const [data, setData] = useState<T>();
const [error, setError] = useState<string>();
const [loading, setLoading] = useState(true);
// eslint-disable-next-line react-hooks/exhaustive-deps
const run = useCallback(load, deps);
const reload = useCallback(async () => {
setLoading(true);
try {
setData(await run());
setError(undefined);
} catch (e) {
setError((e as Error).message);
} finally {
setLoading(false);
}
}, [run]);
useEffect(() => {
void reload();
}, [reload]);
return { data, setData, error, loading, reload };
}
/** Wraps an async action with a busy flag and error message. */
export function useAction() {
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string>();
const run = useCallback(async <T,>(fn: () => Promise<T>): Promise<T | undefined> => {
setBusy(true);
setError(undefined);
try {
return await fn();
} catch (e) {
setError((e as Error).message);
return undefined;
} finally {
setBusy(false);
}
}, []);
return { busy, error, setError, run };
}
export function ErrorText({ error }: { error?: string }) {
return error ? <p className="error">{error}</p> : null;
}
export function Modal({ title, onClose, children }: { title: string; onClose: () => void; children: ReactNode }) {
useEffect(() => {
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose();
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [onClose]);
return (
<div className="modal-backdrop" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
<div className="modal" role="dialog" aria-modal="true" aria-label={title}>
<header className="modal-header">
<h2>{title}</h2>
<button className="ghost" onClick={onClose} aria-label="Close">
✕
</button>
</header>
{children}
</div>
</div>
);
}
export function CopyButton({ text, label = 'Copy' }: { text: string; label?: string }) {
const [copied, setCopied] = useState(false);
return (
<button
className="secondary"
onClick={async () => {
await navigator.clipboard.writeText(text);
setCopied(true);
setTimeout(() => setCopied(false), 1500);
}}
>
{copied ? 'Copied' : label}
</button>
);
}
export function KeyQrModal({ keyView, owner, onClose }: { keyView: AccessKeyView; owner: string; onClose: () => void }) {
const [svg, setSvg] = useState('');
useEffect(() => {
QRCode.toString(keyView.deepLink, { type: 'svg', margin: 2, errorCorrectionLevel: 'M' }).then(setSvg);
}, [keyView.deepLink]);
return (
<Modal title={keyView.label ? `Key “${keyView.label}”` : 'Access key'} onClose={onClose}>
<p className="muted">
{owner} · created {formatDate(keyView.createdAt)}
</p>
<div className="qr" dangerouslySetInnerHTML={{ __html: svg }} />
<p className="muted small">Scan with the Cardy app or the phone camera.</p>
<div className="field">
<label>Key</label>
<div className="row nowrap">
<code className="mono grow break">{keyView.key}</code>
<CopyButton text={keyView.key} />
</div>
</div>
<div className="field">
<label>Login link</label>
<div className="row nowrap">
<a className="mono grow break link-box" href={keyView.deepLink} title="Open in the Cardy app">
{keyView.deepLink}
</a>
<CopyButton text={keyView.deepLink} />
</div>
</div>
</Modal>
);
}
type Bwip = typeof import('bwip-js/browser');
let bwipPromise: Promise<Bwip> | undefined;
export function CodePreview({ code, codeType }: { code: string; codeType: CodeType }) {
// bwip-js is ~1 MB, load it only when a code is shown.
const [bwipjs, setBwipjs] = useState<Bwip>();
useEffect(() => {
bwipPromise ??= import('bwip-js/browser').then((m) => (m as { default?: Bwip }).default ?? m);
void bwipPromise.then((b) => setBwipjs(() => b));
}, []);
const result = useMemo(() => {
if (!code) return { error: 'Enter a code to see the preview' };
if (!bwipjs) return { error: 'Loading…' };
try {
const svg = bwipjs.toSVG({
bcid: BWIP_BCID[codeType],
text: code,
scale: 3,
...(TWO_DIMENSIONAL_CODE_TYPES.has(codeType) ? {} : { height: 14, includetext: true, textxalign: 'center' as const }),
paddingwidth: 4,
paddingheight: 4,
backgroundcolor: 'FFFFFF',
});
return { svg };
} catch (e) {
return { error: String((e as Error).message ?? e).replace(/^Error:\s*/, '') };
}
}, [bwipjs, code, codeType]);
if ('error' in result) return <p className="code-preview-error">{result.error}</p>;
return <div className="code-preview" dangerouslySetInnerHTML={{ __html: result.svg }} />;
}
export function CardBadge({ card, size = 56 }: { card: Pick<Card, 'id' | 'name' | 'color' | 'logo' | 'imagesVersion'>; size?: number }) {
const style = { width: size, height: size, background: card.color, color: textColorOn(card.color) };
if (card.logo) {
return (
<span className="badge" style={style}>
<img src={api.logoUrl(card as Card)} alt="" />
</span>
);
}
return (
<span className="badge" style={{ ...style, fontSize: size * 0.36 }}>
{cardAbbreviation(card.name)}
</span>
);
}
export function FilePicker({
label,
multiple,
disabled,
onFiles,
}: {
label: string;
multiple?: boolean;
disabled?: boolean;
onFiles: (files: File[]) => void;
}) {
const ref = useRef<HTMLInputElement>(null);
return (
<>
<button className="secondary" disabled={disabled} onClick={() => ref.current?.click()}>
{label}
</button>
<input
ref={ref}
type="file"
accept="image/*"
multiple={multiple}
hidden
onChange={(e) => {
const list = [...(e.target.files ?? [])];
e.target.value = '';
if (list.length) onFiles(list);
}}
/>
</>
);
}
export function formatDate(iso: string): string {
return new Date(iso).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' });
}
+10
View File
@@ -0,0 +1,10 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { App } from './App.js';
import './styles.css';
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
);
+211
View File
@@ -0,0 +1,211 @@
import { useEffect, useState } from 'react';
import { CODE_TYPES, CODE_TYPE_LABELS, cardFieldsSchema, randomCardColor, type Card, type CardFields } from '@cardy/shared';
import { api } from '../api.js';
import { CardBadge, CodePreview, ErrorText, FilePicker, formatDate, useAction, useLoad } from '../components.js';
import { linkClick, navigate } from '../router.js';
export function CardEditorPage({ cardId }: { cardId: string }) {
const isNew = cardId === 'new';
const loaded = useLoad(async () => (isNew ? undefined : (await api.cards()).find((c) => c.id === cardId) ?? null), [cardId]);
if (loaded.loading && loaded.data === undefined && !isNew) return <p className="muted">Loading…</p>;
if (loaded.error) return <ErrorText error={loaded.error} />;
if (loaded.data === null) {
return (
<section>
<p className="empty">Card not found.</p>
<a href="/cards" onClick={linkClick}>
Back to cards
</a>
</section>
);
}
return <Editor key={cardId} initial={loaded.data} />;
}
function Editor({ initial }: { initial?: Card }) {
const [card, setCard] = useState<Card | undefined>(initial);
const [fields, setFields] = useState<CardFields>(
initial
? { name: initial.name, color: initial.color, code: initial.code, codeType: initial.codeType }
: { name: '', color: randomCardColor(), code: '', codeType: 'EAN13' },
);
const action = useAction();
const [saved, setSaved] = useState(false);
useEffect(() => setSaved(false), [fields]);
const dirty = !card || card.name !== fields.name || card.color !== fields.color || card.code !== fields.code || card.codeType !== fields.codeType;
const set = <K extends keyof CardFields>(key: K, value: CardFields[K]) => setFields((f) => ({ ...f, [key]: value }));
const save = async (e: React.FormEvent) => {
e.preventDefault();
const parsed = cardFieldsSchema.safeParse(fields);
if (!parsed.success) {
action.setError(parsed.error.issues.map((i) => i.message).join('; '));
return;
}
const result = await action.run(() => (card ? api.updateCard(card.id, parsed.data) : api.createCard(parsed.data)));
if (!result) return;
setCard(result);
setSaved(true);
if (!card) navigate(`/cards/${result.id}`, { replace: true });
};
return (
<section className="editor">
<div className="row page-head">
<a href="/cards" onClick={linkClick} className="ghost-link">
← Cards
</a>
<h1 className="grow">{card ? card.name : 'New card'}</h1>
{card && <CardBadge card={{ ...card, ...fields }} size={48} />}
</div>
{card?.deleted && (
<div className="banner danger row">
<span className="grow">This card is deleted. Apps don't see it.</span>
<button
className="secondary"
disabled={action.busy}
onClick={async () => {
const restored = await action.run(() => api.updateCard(card.id, { deleted: false }));
if (restored) setCard(restored);
}}
>
Restore
</button>
</div>
)}
<div className="editor-grid">
<form className="panel" onSubmit={save}>
<div className="field">
<label htmlFor="name">Name</label>
<input id="name" value={fields.name} onChange={(e) => set('name', e.target.value)} maxLength={200} required />
</div>
<div className="field">
<label htmlFor="color">Color</label>
<div className="row">
<input id="color" type="color" value={fields.color} onChange={(e) => set('color', e.target.value.toUpperCase())} />
<input
className="mono"
value={fields.color}
onChange={(e) => set('color', e.target.value)}
pattern="#[0-9a-fA-F]{6}"
size={8}
aria-label="Color hex"
/>
<button type="button" className="secondary" onClick={() => set('color', randomCardColor())}>
Random
</button>
</div>
</div>
<div className="field">
<label htmlFor="codeType">Code type</label>
<select id="codeType" value={fields.codeType} onChange={(e) => set('codeType', e.target.value as CardFields['codeType'])}>
{CODE_TYPES.map((t) => (
<option key={t} value={t}>
{CODE_TYPE_LABELS[t]}
</option>
))}
</select>
</div>
<div className="field">
<label htmlFor="code">Code</label>
<textarea id="code" className="mono" rows={2} value={fields.code} onChange={(e) => set('code', e.target.value)} required />
</div>
<CodePreview code={fields.code} codeType={fields.codeType} />
<div className="row">
<button type="submit" disabled={action.busy || (!dirty && !!card)}>
{card ? 'Save' : 'Create card'}
</button>
{saved && <span className="muted small">Saved</span>}
<span className="grow" />
{card && <DeleteButtons card={card} onChange={setCard} />}
</div>
<ErrorText error={action.error} />
{card && (
<p className="muted small">
Created {formatDate(card.createdAt)} · updated {formatDate(card.updatedAt)} · images version {card.imagesVersion}
</p>
)}
</form>
{card ? <ImagesPanel card={card} onChange={setCard} /> : <div className="panel muted">Create the card to add a logo and images.</div>}
</div>
</section>
);
}
function DeleteButtons({ card, onChange }: { card: Card; onChange: (card: Card) => void }) {
const action = useAction();
return (
<>
<button
type="button"
className="danger"
disabled={action.busy}
onClick={async () => {
if (card.deleted) {
if (!confirm(`Permanently delete "${card.name}" with all its images? This cannot be undone.`)) return;
if ((await action.run(async () => (await api.deleteCard(card.id), true))) !== undefined) navigate('/cards');
} else {
if (!confirm(`Delete "${card.name}"? It can be restored later.`)) return;
const deleted = await action.run(() => api.deleteCard(card.id));
if (deleted) onChange(deleted);
}
}}
>
{card.deleted ? 'Delete permanently' : 'Delete'}
</button>
<ErrorText error={action.error} />
</>
);
}
function ImagesPanel({ card, onChange }: { card: Card; onChange: (card: Card) => void }) {
const action = useAction();
const apply = async (fn: () => Promise<Card>) => {
const updated = await action.run(fn);
if (updated) onChange(updated);
};
return (
<div className="panel">
<h2>Logo</h2>
<div className="row">
{card.logo ? <img className="logo-preview" src={api.logoUrl(card)} alt="Logo" /> : <span className="muted">No logo</span>}
<span className="grow" />
<FilePicker label={card.logo ? 'Replace' : 'Upload'} disabled={action.busy} onFiles={([f]) => f && apply(() => api.setLogo(card.id, f))} />
{card.logo && (
<button className="danger" disabled={action.busy} onClick={() => apply(() => api.removeLogo(card.id))}>
Remove
</button>
)}
</div>
<h2>Images</h2>
<div className="thumbs">
{card.images.map((img) => (
<figure key={img.id} className="thumb">
<a href={api.imageUrl(card, img.id)} target="_blank" rel="noreferrer">
<img src={api.imageUrl(card, img.id)} alt="" loading="lazy" />
</a>
<button
className="danger small"
disabled={action.busy}
onClick={() => confirm('Delete this image?') && apply(() => api.removeImage(card.id, img.id))}
>
Delete
</button>
</figure>
))}
{card.images.length === 0 && <span className="muted">No images</span>}
</div>
<FilePicker label="Add images" multiple disabled={action.busy} onFiles={(files) => apply(() => api.addImages(card.id, files))} />
{action.busy && <span className="muted small"> Uploading…</span>}
<ErrorText error={action.error} />
</div>
);
}
+55
View File
@@ -0,0 +1,55 @@
import { useMemo, useState } from 'react';
import { CODE_TYPE_LABELS } from '@cardy/shared';
import { api } from '../api.js';
import { CardBadge, ErrorText, useLoad } from '../components.js';
import { linkClick } from '../router.js';
export function CardsPage() {
const cards = useLoad(api.cards);
const [filter, setFilter] = useState('');
const [showDeleted, setShowDeleted] = useState(false);
const visible = useMemo(() => {
const q = filter.trim().toLowerCase();
return (cards.data ?? [])
.filter((c) => showDeleted || !c.deleted)
.filter((c) => !q || c.name.toLowerCase().includes(q))
.sort((a, b) => a.name.localeCompare(b.name));
}, [cards.data, filter, showDeleted]);
const deletedCount = cards.data?.filter((c) => c.deleted).length ?? 0;
return (
<section>
<div className="row page-head">
<h1 className="grow">Cards</h1>
<a className="button" href="/cards/new" onClick={linkClick}>
New card
</a>
</div>
<div className="row">
<input className="grow" type="search" placeholder="Filter by name" value={filter} onChange={(e) => setFilter(e.target.value)} />
<label className="checkbox">
<input type="checkbox" checked={showDeleted} onChange={(e) => setShowDeleted(e.target.checked)} />
Show deleted ({deletedCount})
</label>
</div>
<ErrorText error={cards.error} />
{cards.data && visible.length === 0 && <p className="empty">{cards.data.length ? 'No matching cards.' : 'No cards yet.'}</p>}
<div className="card-grid">
{visible.map((c) => (
<a key={c.id} href={`/cards/${c.id}`} onClick={linkClick} className={`card-tile${c.deleted ? ' deleted' : ''}`}>
<CardBadge card={c} />
<div className="grow">
<div className="card-name">{c.name}</div>
<div className="muted small">
{CODE_TYPE_LABELS[c.codeType]}
{c.images.length > 0 && ` · ${c.images.length} image${c.images.length === 1 ? '' : 's'}`}
</div>
</div>
{c.deleted && <span className="pill danger">deleted</span>}
</a>
))}
</div>
</section>
);
}
+98
View File
@@ -0,0 +1,98 @@
import { useState } from 'react';
import type { Group, MeResponse } from '@cardy/shared';
import { api } from '../api.js';
import { ErrorText, useAction, useLoad } from '../components.js';
export function GroupsPage({ me, onGroupsChanged }: { me: MeResponse; onGroupsChanged: () => Promise<void> }) {
const groups = useLoad(api.groups);
const action = useAction();
const [name, setName] = useState('');
const changed = async () => {
await groups.reload();
await onGroupsChanged();
};
return (
<section>
<h1>Groups</h1>
<form
className="row"
onSubmit={async (e) => {
e.preventDefault();
if (await action.run(() => api.createGroup(name.trim()))) {
setName('');
await changed();
}
}}
>
<input placeholder="New group name" value={name} onChange={(e) => setName(e.target.value)} required />
<button type="submit" disabled={action.busy || !name.trim()}>
Add group
</button>
</form>
<ErrorText error={action.error ?? groups.error} />
<ul className="list">
{groups.data?.map((g) => (
<GroupRow key={g.id} group={g} isCurrent={g.id === me.currentGroup.id} isOwn={g.id === me.group.id} onChanged={changed} />
))}
</ul>
</section>
);
}
function GroupRow({ group, isCurrent, isOwn, onChanged }: { group: Group; isCurrent: boolean; isOwn: boolean; onChanged: () => Promise<void> }) {
const [editing, setEditing] = useState(false);
const [name, setName] = useState(group.name);
const action = useAction();
return (
<li className="list-item">
{editing ? (
<form
className="row grow"
onSubmit={async (e) => {
e.preventDefault();
if (await action.run(() => api.renameGroup(group.id, name.trim()))) {
setEditing(false);
await onChanged();
}
}}
>
<input className="grow" value={name} onChange={(e) => setName(e.target.value)} autoFocus required />
<button type="submit" disabled={action.busy}>
Save
</button>
<button type="button" className="secondary" onClick={() => { setEditing(false); setName(group.name); }}>
Cancel
</button>
</form>
) : (
<>
<div className="grow">
{group.name}
{isCurrent && <span className="pill accent">current</span>}
{isOwn && <span className="pill">yours</span>}
</div>
<button className="secondary" onClick={() => api.setCurrentGroup(group.id).then(onChanged)} disabled={isCurrent}>
Select
</button>
<button className="secondary" onClick={() => setEditing(true)}>
Rename
</button>
<button
className="danger"
disabled={action.busy}
onClick={async () => {
const ok = confirm(`Delete group "${group.name}"?\n\nAll its users, their keys and all cards with images will be deleted permanently.`);
if (ok && (await action.run(async () => (await api.deleteGroup(group.id), true)))) await onChanged();
}}
>
Delete
</button>
</>
)}
<ErrorText error={action.error} />
</li>
);
}
+32
View File
@@ -0,0 +1,32 @@
import { useState } from 'react';
import type { AccessKeyView, MeResponse } from '@cardy/shared';
import { api } from '../api.js';
import { ErrorText, KeyQrModal, formatDate, useLoad } from '../components.js';
export function MyKeysPage({ me }: { me: MeResponse }) {
const keys = useLoad(api.myKeys);
const [shown, setShown] = useState<AccessKeyView>();
return (
<section>
<h1>My keys</h1>
<p className="muted">Scan a key's QR code with the Cardy app to sign in. Keys are issued by your group administrator.</p>
<ErrorText error={keys.error} />
{keys.data?.length === 0 && <p className="empty">You have no keys yet.</p>}
<ul className="list">
{keys.data?.map((k) => (
<li key={k.id} className="list-item">
<div className="grow">
<div>{k.label || 'Unnamed key'}</div>
<div className="muted small">
Created {formatDate(k.createdAt)} · <span className="mono">{k.key.slice(0, 4)}…{k.key.slice(-4)}</span>
</div>
</div>
<button onClick={() => setShown(k)}>Show QR</button>
</li>
))}
</ul>
{shown && <KeyQrModal keyView={shown} owner={me.email} onClose={() => setShown(undefined)} />}
</section>
);
}
+195
View File
@@ -0,0 +1,195 @@
import { useState } from 'react';
import { ROLES, type AccessKeyView, type Group, type MeResponse, type Role, type UserView } from '@cardy/shared';
import { api } from '../api.js';
import { ErrorText, KeyQrModal, formatDate, useAction, useLoad } from '../components.js';
export function UsersPage({ me }: { me: MeResponse }) {
const users = useLoad(api.users);
const isSuper = me.role === 'superadmin';
const groups = useLoad(() => (isSuper ? api.groups() : Promise.resolve([] as Group[])));
const assignableRoles: Role[] = isSuper ? [...ROLES] : ['user', 'admin'];
return (
<section>
<h1>Users</h1>
<p className="muted">Users of group “{me.currentGroup.name}”. Users sign in to this site through Authelia with the same email.</p>
<AddUser roles={assignableRoles} onAdded={users.reload} />
<ErrorText error={users.error} />
{users.data?.length === 0 && <p className="empty">No users in this group.</p>}
<ul className="list">
{users.data?.map((u) => (
<UserRow key={u.email} user={u} me={me} roles={assignableRoles} groups={groups.data ?? []} onChanged={users.reload} />
))}
</ul>
</section>
);
}
function AddUser({ roles, onAdded }: { roles: Role[]; onAdded: () => Promise<void> }) {
const [email, setEmail] = useState('');
const [role, setRole] = useState<Role>('user');
const action = useAction();
return (
<>
<form
className="row"
onSubmit={async (e) => {
e.preventDefault();
if (await action.run(() => api.createUser(email.trim(), role))) {
setEmail('');
setRole('user');
await onAdded();
}
}}
>
<input type="email" placeholder="email@example.com" value={email} onChange={(e) => setEmail(e.target.value)} required />
<select value={role} onChange={(e) => setRole(e.target.value as Role)}>
{roles.map((r) => (
<option key={r}>{r}</option>
))}
</select>
<button type="submit" disabled={action.busy}>
Add user
</button>
</form>
<ErrorText error={action.error} />
</>
);
}
function UserRow({
user,
me,
roles,
groups,
onChanged,
}: {
user: UserView;
me: MeResponse;
roles: Role[];
groups: Group[];
onChanged: () => Promise<void>;
}) {
const [expanded, setExpanded] = useState(false);
const action = useAction();
const isSelf = user.email === me.email;
const canManage = me.role === 'superadmin' || user.role !== 'superadmin';
const update = async (patch: { role?: Role; groupId?: string }) => {
if (await action.run(() => api.updateUser(user.email, patch))) await onChanged();
};
return (
<li className="list-item column">
<div className="row">
<div className="grow">
<div>
{user.email}
{isSelf && <span className="pill">you</span>}
</div>
<div className="muted small">
{user.keys.length} key{user.keys.length === 1 ? '' : 's'}
</div>
</div>
<select
value={user.role}
disabled={!canManage || isSelf || action.busy}
onChange={(e) => update({ role: e.target.value as Role })}
aria-label="Role"
>
{(roles.includes(user.role) ? roles : [...roles, user.role]).map((r) => (
<option key={r}>{r}</option>
))}
</select>
{me.role === 'superadmin' && groups.length > 0 && (
<select
value={user.groupId}
disabled={action.busy}
onChange={(e) => {
const target = groups.find((g) => g.id === e.target.value);
if (confirm(`Move ${user.email} to group "${target?.name}"?`)) void update({ groupId: e.target.value });
}}
aria-label="Group"
>
{groups.map((g) => (
<option key={g.id} value={g.id}>
{g.name}
</option>
))}
</select>
)}
<button className="secondary" onClick={() => setExpanded((x) => !x)} disabled={!canManage}>
{expanded ? 'Hide keys' : 'Keys'}
</button>
<button
className="danger"
disabled={!canManage || isSelf || action.busy}
onClick={async () => {
if (!confirm(`Delete user ${user.email} and all their keys?`)) return;
if (await action.run(async () => (await api.deleteUser(user.email), true))) await onChanged();
}}
>
Delete
</button>
</div>
<ErrorText error={action.error} />
{expanded && <UserKeys user={user} onChanged={onChanged} />}
</li>
);
}
function UserKeys({ user, onChanged }: { user: UserView; onChanged: () => Promise<void> }) {
const [label, setLabel] = useState('');
const [shown, setShown] = useState<AccessKeyView>();
const action = useAction();
return (
<div className="subpanel">
{user.keys.length === 0 && <p className="muted small">No keys.</p>}
<ul className="list compact">
{user.keys.map((k) => (
<li key={k.id} className="list-item">
<div className="grow">
<div>{k.label || 'Unnamed key'}</div>
<div className="muted small">
Created {formatDate(k.createdAt)} · <span className="mono">{k.key.slice(0, 4)}…{k.key.slice(-4)}</span>
</div>
</div>
<button className="secondary" onClick={() => setShown(k)}>
Show QR
</button>
<button
className="danger"
disabled={action.busy}
onClick={async () => {
if (!confirm('Delete this key? Apps signed in with it stop working immediately.')) return;
if (await action.run(async () => (await api.deleteKey(user.email, k.id), true))) await onChanged();
}}
>
Delete
</button>
</li>
))}
</ul>
<form
className="row"
onSubmit={async (e) => {
e.preventDefault();
const created = await action.run(() => api.createKey(user.email, label.trim()));
if (created) {
setLabel('');
setShown(created);
await onChanged();
}
}}
>
<input placeholder="Label (optional), e.g. Pixel 8" value={label} onChange={(e) => setLabel(e.target.value)} maxLength={100} />
<button type="submit" disabled={action.busy}>
Generate key
</button>
</form>
<ErrorText error={action.error} />
{shown && <KeyQrModal keyView={shown} owner={user.email} onClose={() => setShown(undefined)} />}
</div>
);
}
+30
View File
@@ -0,0 +1,30 @@
import { useEffect, useState } from 'react';
const listeners = new Set<() => void>();
export function navigate(path: string, { replace = false } = {}): void {
if (path === location.pathname) return;
if (replace) history.replaceState(null, '', path);
else history.pushState(null, '', path);
listeners.forEach((l) => l());
}
window.addEventListener('popstate', () => listeners.forEach((l) => l()));
export function usePath(): string {
const [path, setPath] = useState(location.pathname);
useEffect(() => {
const listener = () => setPath(location.pathname);
listeners.add(listener);
listener(); // catch navigations that happened before subscribing
return () => void listeners.delete(listener);
}, []);
return path;
}
/** Click handler for <a href> that navigates without a reload (keeps ctrl/middle-click working). */
export function linkClick(e: React.MouseEvent<HTMLAnchorElement>): void {
if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
e.preventDefault();
navigate(e.currentTarget.getAttribute('href') ?? '/');
}
+585
View File
@@ -0,0 +1,585 @@
/* Dark theme only. */
:root {
color-scheme: dark;
--bg: #0f1115;
--surface: #171a21;
--surface-2: #1f232c;
--border: #2c313c;
--text: #e6e8ec;
--muted: #8b93a3;
--accent: #5b9dff;
--accent-strong: #3d86f5;
--accent-text: #0b1220;
--danger: #ff6b6b;
--danger-bg: #3a1b1f;
--radius: 10px;
--font: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
--mono: ui-monospace, 'Cascadia Code', Consolas, monospace;
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
background: var(--bg);
color: var(--text);
font: 15px/1.45 var(--font);
}
h1 {
font-size: 1.5rem;
margin: 0 0 12px;
}
h2 {
font-size: 1.05rem;
margin: 16px 0 8px;
}
h2:first-child {
margin-top: 0;
}
a {
color: var(--accent);
}
p {
margin: 8px 0;
}
.muted {
color: var(--muted);
}
.small {
font-size: 0.85em;
}
.mono {
font-family: var(--mono);
}
.break {
word-break: break-all;
}
.error {
color: var(--danger);
}
.empty {
color: var(--muted);
padding: 24px 0;
}
.center {
max-width: 480px;
margin: 15vh auto;
padding: 0 16px;
text-align: center;
}
/* ---- controls ---- */
input,
select,
textarea,
button,
.button {
font: inherit;
color: var(--text);
border-radius: 8px;
}
input,
select,
textarea {
background: var(--surface-2);
border: 1px solid var(--border);
padding: 7px 10px;
min-width: 0;
}
input:focus,
select:focus,
textarea:focus {
outline: 2px solid var(--accent);
outline-offset: -1px;
}
input[type='color'] {
width: 44px;
height: 36px;
padding: 2px;
}
input[type='checkbox'] {
accent-color: var(--accent);
}
textarea {
width: 100%;
resize: vertical;
}
button,
.button {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 6px;
padding: 7px 14px;
border: 1px solid transparent;
background: var(--accent);
color: var(--accent-text);
font-weight: 600;
cursor: pointer;
text-decoration: none;
white-space: nowrap;
}
button:hover:not(:disabled),
.button:hover {
background: var(--accent-strong);
}
button:disabled {
opacity: 0.45;
cursor: default;
}
button.secondary {
background: var(--surface-2);
border-color: var(--border);
color: var(--text);
}
button.secondary:hover:not(:disabled) {
background: var(--border);
}
button.danger {
background: transparent;
border-color: var(--danger-bg);
color: var(--danger);
}
button.danger:hover:not(:disabled) {
background: var(--danger-bg);
}
button.ghost {
background: transparent;
color: var(--muted);
padding: 4px 8px;
}
button.ghost:hover:not(:disabled) {
background: var(--surface-2);
color: var(--text);
}
button.small {
padding: 3px 8px;
font-size: 0.85em;
}
.ghost-link {
color: var(--muted);
text-decoration: none;
}
.ghost-link:hover {
color: var(--text);
}
.checkbox {
display: inline-flex;
align-items: center;
gap: 6px;
white-space: nowrap;
}
.field {
display: flex;
flex-direction: column;
gap: 4px;
margin-bottom: 12px;
}
.field label {
color: var(--muted);
font-size: 0.85em;
}
.row {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.row.nowrap {
flex-wrap: nowrap;
}
.row.nowrap > button {
flex: none;
}
.grow {
flex: 1 1 auto;
min-width: 0;
}
.pill {
display: inline-block;
margin-left: 8px;
padding: 1px 8px;
border-radius: 999px;
background: var(--surface-2);
border: 1px solid var(--border);
color: var(--muted);
font-size: 0.78em;
vertical-align: middle;
}
.pill.accent {
color: var(--accent);
border-color: color-mix(in srgb, var(--accent) 40%, transparent);
}
.pill.danger {
color: var(--danger);
border-color: var(--danger-bg);
background: var(--danger-bg);
}
/* ---- layout ---- */
.topbar {
display: flex;
align-items: center;
gap: 20px;
flex-wrap: wrap;
padding: 10px 24px;
background: var(--surface);
border-bottom: 1px solid var(--border);
position: sticky;
top: 0;
z-index: 10;
}
.brand {
font-weight: 700;
font-size: 1.1rem;
letter-spacing: 0.02em;
}
.topbar nav {
display: flex;
gap: 4px;
}
.topbar nav a {
padding: 6px 12px;
border-radius: 8px;
color: var(--muted);
text-decoration: none;
}
.topbar nav a:hover {
color: var(--text);
background: var(--surface-2);
}
.topbar nav a.active {
color: var(--text);
background: var(--surface-2);
}
.topbar-right {
margin-left: auto;
display: flex;
align-items: center;
gap: 16px;
flex-wrap: wrap;
}
.group-switcher {
display: flex;
align-items: center;
gap: 6px;
}
main {
max-width: 1100px;
margin: 0 auto;
padding: 24px;
}
section > .row {
margin-bottom: 12px;
}
.page-head h1 {
margin: 0;
}
.panel {
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 16px;
}
.subpanel {
margin-top: 10px;
padding: 12px;
border-radius: 8px;
background: var(--bg);
border: 1px solid var(--border);
}
.banner {
padding: 10px 14px;
border-radius: var(--radius);
margin-bottom: 12px;
}
.banner.danger {
background: var(--danger-bg);
color: var(--danger);
}
/* ---- lists ---- */
.list {
list-style: none;
margin: 12px 0 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 8px;
}
.list.compact {
margin: 0 0 10px;
}
.list-item {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
padding: 12px 14px;
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
}
.list-item.column {
flex-direction: column;
align-items: stretch;
}
.subpanel .list-item {
background: var(--surface-2);
}
/* ---- cards ---- */
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
gap: 10px;
margin-top: 12px;
}
.card-tile {
display: flex;
align-items: center;
gap: 12px;
padding: 12px;
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
color: var(--text);
text-decoration: none;
}
.card-tile:hover {
border-color: var(--accent);
}
.card-tile.deleted {
opacity: 0.55;
}
.card-name {
font-weight: 600;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.badge {
flex: none;
display: inline-flex;
align-items: center;
justify-content: center;
border-radius: 12px;
font-weight: 700;
overflow: hidden;
}
.badge img {
width: 100%;
height: 100%;
object-fit: contain;
}
.editor-grid {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
gap: 16px;
align-items: start;
}
@media (max-width: 800px) {
.editor-grid {
grid-template-columns: 1fr;
}
main {
padding: 16px;
}
.topbar {
padding: 10px 16px;
}
}
/* Codes stay black on white so they remain scannable. */
.code-preview {
background: #fff;
border-radius: 8px;
padding: 8px;
margin-bottom: 12px;
display: flex;
justify-content: center;
}
.code-preview svg {
max-width: 100%;
max-height: 220px;
height: auto;
}
.code-preview-error {
color: var(--muted);
font-size: 0.85em;
border: 1px dashed var(--border);
border-radius: 8px;
padding: 16px;
margin: 0 0 12px;
text-align: center;
}
.logo-preview {
width: 72px;
height: 72px;
object-fit: contain;
background: var(--surface-2);
border-radius: 8px;
}
.thumbs {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(110px, 1fr));
gap: 10px;
margin-bottom: 12px;
}
.thumb {
margin: 0;
display: flex;
flex-direction: column;
gap: 6px;
}
.thumb img {
width: 100%;
aspect-ratio: 1;
object-fit: cover;
border-radius: 8px;
background: var(--surface-2);
display: block;
}
/* ---- modal ---- */
.modal-backdrop {
position: fixed;
inset: 0;
background: rgb(0 0 0 / 0.65);
display: flex;
align-items: center;
justify-content: center;
padding: 16px;
z-index: 100;
}
.modal {
width: min(480px, 100%);
max-height: 100%;
overflow: auto;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 14px;
padding: 18px 20px;
}
.modal-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 4px;
}
.modal-header h2 {
margin: 0;
}
.qr {
background: #fff;
border-radius: 10px;
padding: 8px;
width: min(280px, 100%);
margin: 12px auto 4px;
}
.qr svg {
display: block;
width: 100%;
height: auto;
}
.modal code,
.modal .link-box {
background: var(--surface-2);
border: 1px solid var(--border);
padding: 6px 8px;
border-radius: 6px;
}
.modal .link-box {
text-decoration: none;
}
.modal .link-box:hover {
border-color: var(--accent);
text-decoration: underline;
}
+9
View File
@@ -0,0 +1,9 @@
{
"extends": "../tsconfig.base.json",
"compilerOptions": {
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"jsx": "react-jsx",
"types": ["vite/client"]
},
"include": ["src", "vite.config.ts"]
}
+43
View File
@@ -0,0 +1,43 @@
import react from '@vitejs/plugin-react';
import { defineConfig, loadEnv, type ProxyOptions } from 'vite';
// Behind the real reverse proxy /api never reaches this server. The /api proxy below only emulates
// that reverse proxy for local development without it (strips /api, sets X-Forwarded-Prefix).
//
// Env (server-fe/.env or process env):
// ALLOWED_HOSTS comma-separated public host names (default dev.aggtaa.com)
// BACKEND_URL local dev: server-be address (default http://127.0.0.1:10002)
// ADMIN_PROXY_SECRET local dev: sent as X-Cardy-Proxy-Secret, must match server-be
// DEV_REMOTE_EMAIL local dev: fakes the Remote-Email header normally set by Authelia
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), '');
const headers: Record<string, string> = { 'X-Forwarded-Prefix': '/api' };
if (env.ADMIN_PROXY_SECRET) headers['X-Cardy-Proxy-Secret'] = env.ADMIN_PROXY_SECRET;
if (env.DEV_REMOTE_EMAIL) {
headers['Remote-Email'] = env.DEV_REMOTE_EMAIL;
console.warn(`\n⚠ DEV_REMOTE_EMAIL is set: every request acts as ${env.DEV_REMOTE_EMAIL}. Never use it behind the real proxy.\n`);
}
const proxy: Record<string, ProxyOptions> = {
'/api': {
target: env.BACKEND_URL || 'http://127.0.0.1:10002',
rewrite: (path) => path.replace(/^\/api/, '') || '/',
headers,
},
};
const server = {
host: true,
port: 10001,
strictPort: true,
allowedHosts: (env.ALLOWED_HOSTS || 'dev.aggtaa.com').split(',').map((h) => h.trim()),
proxy,
};
return {
plugins: [react()],
// bwip-js alone is ~1 MB; it is lazy-loaded.
build: { chunkSizeWarningLimit: 1100 },
server,
preview: server,
};
});