feat(v1.1.8): dashboard Users tab + Invitations sub-tab

apps/[slug]/users/+page.svelte: list, create form, edit modal,
revoke-sessions, reset-password (returns one-shot token in a copy
modal so the admin can paste it into a manual reset link), delete.

apps/[slug]/users/invitations/+page.svelte: pending list, create
form (with optional inline email template — off by default for
out-of-band delivery), revoke.

Tab strip in apps/[slug]/+page.svelte gets a Users entry above
Files, matching the external-route pattern files/ and dead-letters/
already use. Sub-tab navigation from Users -> Invitations and back.

api.ts gains AppUser / Invitation / ResetPasswordResponse /
CreateAppUserInput / PatchAppUserInput / InvitationTemplate /
CreateInvitationInput types and `users` + `appInvitations`
namespaces mirroring the appMembers shape.

svelte-check is green on every file under src/. The 150 errors
the runner reports are all pre-existing in tests/e2e/ (missing
@playwright/test install — unrelated to v1.1.8 changes).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
MechaCat02
2026-06-06 14:54:20 +02:00
parent aa2631ff61
commit 6449cb6f6a
4 changed files with 918 additions and 0 deletions

View File

@@ -238,6 +238,68 @@ export interface CreateEmailTriggerInput {
inbound_secret?: string | null;
}
/// v1.1.8 per-app end-user record returned by the admin users API.
/// Never carries the password hash or session tokens.
export interface AppUser {
id: string;
app_id: string;
email: string;
display_name: string | null;
email_verified_at: string | null;
last_login_at: string | null;
created_at: string;
updated_at: string;
roles: string[];
}
export interface CreateAppUserInput {
email: string;
password: string;
display_name?: string | null;
}
export interface PatchAppUserInput {
/// Triple-state: present-with-string sets, present-with-null clears,
/// absent leaves alone. The serde shape on the server is the same.
display_name?: string | null;
}
export interface ResetPasswordResponse {
token: string;
expires_in_seconds: number;
}
export interface RevokeSessionsResponse {
revoked: number;
}
/// v1.1.8 pending-invitation row.
export interface Invitation {
id: string;
app_id: string;
email: string;
display_name: string | null;
roles: string[];
created_at: string;
expires_at: string;
}
export interface InvitationTemplate {
link_base: string;
from: string;
subject: string;
body_template: string;
}
export interface CreateInvitationInput {
email: string;
display_name?: string | null;
roles?: string[];
/// Optional. Omit to issue an invitation without sending an email
/// (the admin delivers the token out-of-band).
template?: InvitationTemplate;
}
/// v1.1.5 file metadata as the admin files endpoint returns it.
export interface FileMeta {
id: string;
@@ -760,6 +822,64 @@ export const api = {
)
},
users: {
list: (idOrSlug: string, opts: { cursor?: string; limit?: number } = {}) => {
const params = new URLSearchParams();
if (opts.cursor) params.set('cursor', opts.cursor);
if (opts.limit !== undefined) params.set('limit', String(opts.limit));
const qs = params.toString();
return adminRequest<{ users: AppUser[]; next_cursor: string | null }>(
`/api/v1/admin/apps/${encodeURIComponent(idOrSlug)}/users${qs ? `?${qs}` : ''}`
);
},
get: (idOrSlug: string, userId: string) =>
adminRequest<AppUser>(
`/api/v1/admin/apps/${encodeURIComponent(idOrSlug)}/users/${userId}`
),
create: (idOrSlug: string, input: CreateAppUserInput) =>
adminRequest<AppUser>(`/api/v1/admin/apps/${encodeURIComponent(idOrSlug)}/users`, {
method: 'POST',
body: JSON.stringify(input)
}),
patch: (idOrSlug: string, userId: string, input: PatchAppUserInput) =>
adminRequest<AppUser>(
`/api/v1/admin/apps/${encodeURIComponent(idOrSlug)}/users/${userId}`,
{ method: 'PATCH', body: JSON.stringify(input) }
),
remove: (idOrSlug: string, userId: string) =>
adminRequest<null>(
`/api/v1/admin/apps/${encodeURIComponent(idOrSlug)}/users/${userId}`,
{ method: 'DELETE' }
),
resetPassword: (idOrSlug: string, userId: string) =>
adminRequest<ResetPasswordResponse>(
`/api/v1/admin/apps/${encodeURIComponent(idOrSlug)}/users/${userId}/reset-password`,
{ method: 'POST' }
),
revokeSessions: (idOrSlug: string, userId: string) =>
adminRequest<RevokeSessionsResponse>(
`/api/v1/admin/apps/${encodeURIComponent(idOrSlug)}/users/${userId}/revoke-sessions`,
{ method: 'POST' }
)
},
appInvitations: {
list: (idOrSlug: string) =>
adminRequest<{ invitations: Invitation[] }>(
`/api/v1/admin/apps/${encodeURIComponent(idOrSlug)}/invitations`
),
create: (idOrSlug: string, input: CreateInvitationInput) =>
adminRequest<Invitation>(
`/api/v1/admin/apps/${encodeURIComponent(idOrSlug)}/invitations`,
{ method: 'POST', body: JSON.stringify(input) }
),
remove: (idOrSlug: string, inviteId: string) =>
adminRequest<null>(
`/api/v1/admin/apps/${encodeURIComponent(idOrSlug)}/invitations/${inviteId}`,
{ method: 'DELETE' }
)
},
execute: async (
id: string,
body: unknown,

View File

@@ -783,6 +783,13 @@
class:active={activeTab === 'settings'}
onclick={() => (activeTab = 'settings')}>Settings</button
>
<a
class="tab-link"
href="{base}/apps/{slug}/users"
title="Users — per-app end users managed by the users::* SDK"
>
Users
</a>
<a
class="tab-link"
href="{base}/apps/{slug}/files"

View File

@@ -0,0 +1,466 @@
<script lang="ts">
import { base } from '$app/paths';
import { page } from '$app/state';
import {
api,
ApiError,
type App,
type AppUser,
type ResetPasswordResponse
} from '$lib/api';
import ConfirmModal from '$lib/ConfirmModal.svelte';
let slug = $derived(page.params.slug ?? '');
let app = $state<App | null>(null);
let users = $state<AppUser[]>([]);
let nextCursor = $state<string | null>(null);
let loading = $state(false);
let error = $state<string | null>(null);
let showCreate = $state(false);
let createEmail = $state('');
let createPassword = $state('');
let createDisplayName = $state('');
let creating = $state(false);
let editing = $state<AppUser | null>(null);
let editDisplayName = $state('');
let editRolesText = $state('');
let savingEdit = $state(false);
let toRemove = $state<AppUser | null>(null);
let removing = $state(false);
let toRevoke = $state<AppUser | null>(null);
let revoking = $state(false);
let toReset = $state<AppUser | null>(null);
let resetToken = $state<ResetPasswordResponse | null>(null);
let resetting = $state(false);
async function loadApp() {
try {
app = await api.apps.get(slug);
} catch (e) {
error = e instanceof ApiError ? e.message : String(e);
}
}
async function loadUsers(cursor?: string) {
loading = true;
error = null;
try {
const res = await api.users.list(slug, { cursor, limit: 100 });
if (cursor) {
users = [...users, ...res.users];
} else {
users = res.users;
}
nextCursor = res.next_cursor;
} catch (e) {
error = e instanceof ApiError ? e.message : String(e);
} finally {
loading = false;
}
}
$effect(() => {
void slug;
void loadApp();
void loadUsers();
});
async function submitCreate() {
creating = true;
error = null;
try {
const created = await api.users.create(slug, {
email: createEmail.trim(),
password: createPassword,
display_name: createDisplayName.trim() || null
});
users = [created, ...users];
createEmail = '';
createPassword = '';
createDisplayName = '';
showCreate = false;
} catch (e) {
error = e instanceof ApiError ? e.message : String(e);
} finally {
creating = false;
}
}
function openEdit(u: AppUser) {
editing = u;
editDisplayName = u.display_name ?? '';
// Roles are managed via SDK / cron / admin-issued invitations
// only for v1.1.8; the dashboard renders them read-only here.
editRolesText = u.roles.join(', ');
}
async function submitEdit() {
if (!editing) return;
savingEdit = true;
try {
const trimmed = editDisplayName.trim();
const updated = await api.users.patch(slug, editing.id, {
display_name: trimmed.length ? trimmed : null
});
users = users.map((u) => (u.id === updated.id ? updated : u));
editing = null;
} catch (e) {
error = e instanceof ApiError ? e.message : String(e);
} finally {
savingEdit = false;
}
}
async function confirmRemove() {
if (!toRemove) return;
removing = true;
try {
await api.users.remove(slug, toRemove.id);
users = users.filter((u) => u.id !== toRemove!.id);
toRemove = null;
} catch (e) {
error = e instanceof ApiError ? e.message : String(e);
} finally {
removing = false;
}
}
async function confirmRevoke() {
if (!toRevoke) return;
revoking = true;
try {
await api.users.revokeSessions(slug, toRevoke.id);
toRevoke = null;
} catch (e) {
error = e instanceof ApiError ? e.message : String(e);
} finally {
revoking = false;
}
}
async function confirmReset() {
if (!toReset) return;
resetting = true;
try {
resetToken = await api.users.resetPassword(slug, toReset.id);
} catch (e) {
error = e instanceof ApiError ? e.message : String(e);
} finally {
resetting = false;
}
}
function closeResetTokenModal() {
toReset = null;
resetToken = null;
}
function fmtTime(iso: string | null): string {
return iso ? new Date(iso).toLocaleString() : '—';
}
</script>
<svelte:head>
<title>Users · {slug} · PiCloud</title>
</svelte:head>
<div class="container">
<header>
<div>
<a href="{base}/apps/{slug}" class="back">&larr; back to {app?.name ?? slug}</a>
<h1>Users</h1>
<p class="subtitle">
End-users of this app, managed by the <code>users::*</code> SDK. Distinct
from instance operators (Admins tab).
</p>
</div>
<div>
<a class="tab-link" href="{base}/apps/{slug}/users/invitations">Invitations</a>
<button type="button" onclick={() => (showCreate = !showCreate)}>
{showCreate ? 'Cancel' : 'New user'}
</button>
</div>
</header>
{#if showCreate}
<form
class="create-form"
onsubmit={(e) => {
e.preventDefault();
void submitCreate();
}}
>
<label>
<span>Email</span>
<input type="email" required bind:value={createEmail} />
</label>
<label>
<span>Password</span>
<input type="password" required minlength={8} bind:value={createPassword} />
</label>
<label>
<span>Display name (optional)</span>
<input type="text" bind:value={createDisplayName} />
</label>
<button type="submit" disabled={creating}>
{creating ? 'Creating…' : 'Create user'}
</button>
</form>
{/if}
{#if error}
<div class="error">{error}</div>
{/if}
{#if users.length === 0 && !loading}
<p class="muted">No users yet. Create one above or wait for them to sign up.</p>
{:else}
<table>
<thead>
<tr>
<th>Email</th>
<th>Display name</th>
<th>Verified</th>
<th>Roles</th>
<th>Last login</th>
<th></th>
</tr>
</thead>
<tbody>
{#each users as u (u.id)}
<tr>
<td>{u.email}</td>
<td>{u.display_name ?? '—'}</td>
<td>
{#if u.email_verified_at}
<span class="badge badge-ok" title={u.email_verified_at}>yes</span>
{:else}
<span class="badge badge-pending">pending</span>
{/if}
</td>
<td>
{#each u.roles as r}
<span class="chip">{r}</span>
{/each}
</td>
<td>{fmtTime(u.last_login_at)}</td>
<td class="row-actions">
<button type="button" onclick={() => openEdit(u)}>Edit</button>
<button type="button" onclick={() => (toReset = u)}>Reset pw</button>
<button type="button" onclick={() => (toRevoke = u)}>Revoke sessions</button>
<button type="button" class="danger" onclick={() => (toRemove = u)}>
Delete
</button>
</td>
</tr>
{/each}
</tbody>
</table>
{#if nextCursor}
<button
type="button"
class="secondary"
onclick={() => loadUsers(nextCursor ?? undefined)}
>
Load more
</button>
{/if}
{/if}
</div>
{#if editing}
<ConfirmModal
title="Edit user"
confirmLabel="Save"
busy={savingEdit}
onConfirm={submitEdit}
onCancel={() => (editing = null)}
>
<label class="modal-label">
<span>Email (immutable)</span>
<input type="email" value={editing.email} disabled />
</label>
<label class="modal-label">
<span>Display name</span>
<input type="text" bind:value={editDisplayName} />
</label>
<label class="modal-label">
<span>Roles</span>
<input type="text" value={editRolesText} disabled />
<small class="muted">
Manage via <code>users::add_role</code> / <code>users::remove_role</code> in
scripts; v1.1.8 does not edit roles from the dashboard.
</small>
</label>
</ConfirmModal>
{/if}
{#if toRemove}
<ConfirmModal
title="Delete user"
variant="danger"
confirmLabel="Delete user"
busy={removing}
onConfirm={confirmRemove}
onCancel={() => (toRemove = null)}
>
<p>
Delete <strong>{toRemove.email}</strong>? This removes their record, sessions, roles,
and pending reset / verification tokens. Cannot be undone.
</p>
</ConfirmModal>
{/if}
{#if toRevoke}
<ConfirmModal
title="Revoke all sessions"
confirmLabel="Revoke sessions"
busy={revoking}
onConfirm={confirmRevoke}
onCancel={() => (toRevoke = null)}
>
<p>
Revoke every active session for <strong>{toRevoke.email}</strong>? They will be
signed out everywhere immediately; the next request requires a fresh login.
</p>
</ConfirmModal>
{/if}
{#if toReset && !resetToken}
<ConfirmModal
title="Generate password-reset token"
confirmLabel="Generate token"
busy={resetting}
onConfirm={confirmReset}
onCancel={() => (toReset = null)}
>
<p>
Generate a one-shot password-reset token for <strong>{toReset.email}</strong>?
The token is returned exactly once — paste it into a manual reset link.
</p>
</ConfirmModal>
{/if}
{#if resetToken}
<ConfirmModal
title="Reset token"
confirmLabel="Done"
onConfirm={closeResetTokenModal}
onCancel={closeResetTokenModal}
>
<p>
Copy this token now — it won't be shown again. It expires in
{Math.round(resetToken.expires_in_seconds / 60)} minutes.
</p>
<pre class="token">{resetToken.token}</pre>
</ConfirmModal>
{/if}
<style>
.container {
max-width: 70rem;
margin: 0 auto;
padding: 1.5rem;
}
header {
display: flex;
justify-content: space-between;
align-items: flex-end;
gap: 1rem;
margin-bottom: 1rem;
}
.back {
font-size: 0.85rem;
}
.subtitle {
color: var(--muted, #666);
font-size: 0.9rem;
}
.tab-link {
margin-right: 0.5rem;
}
.create-form {
display: grid;
grid-template-columns: 1fr 1fr 1fr auto;
gap: 0.75rem;
align-items: end;
margin-bottom: 1rem;
}
.create-form label {
display: flex;
flex-direction: column;
gap: 0.25rem;
font-size: 0.85rem;
}
.modal-label {
display: flex;
flex-direction: column;
gap: 0.25rem;
font-size: 0.85rem;
margin-bottom: 0.75rem;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 0.9rem;
}
th,
td {
text-align: left;
padding: 0.4rem 0.6rem;
border-bottom: 1px solid var(--border, #e2e2e2);
}
.row-actions {
display: flex;
gap: 0.25rem;
flex-wrap: wrap;
}
.row-actions button {
font-size: 0.78rem;
padding: 0.2rem 0.5rem;
}
.muted {
color: var(--muted, #666);
}
.error {
color: #b00020;
margin: 0.5rem 0;
}
button.danger {
color: #b00020;
}
.chip {
display: inline-block;
padding: 0.1rem 0.4rem;
border-radius: 0.3rem;
background: var(--chip-bg, #eef);
font-size: 0.75rem;
margin-right: 0.25rem;
}
.badge {
display: inline-block;
padding: 0.1rem 0.4rem;
border-radius: 0.3rem;
font-size: 0.72rem;
}
.badge-ok {
background: #d8f5d8;
color: #2a6a2a;
}
.badge-pending {
background: #fff3cd;
color: #856404;
}
.token {
background: var(--code-bg, #f5f5f7);
padding: 0.5rem;
font-size: 0.85rem;
overflow-wrap: anywhere;
white-space: pre-wrap;
}
</style>

View File

@@ -0,0 +1,325 @@
<script lang="ts">
import { base } from '$app/paths';
import { page } from '$app/state';
import { api, ApiError, type App, type Invitation } from '$lib/api';
import ConfirmModal from '$lib/ConfirmModal.svelte';
let slug = $derived(page.params.slug ?? '');
let app = $state<App | null>(null);
let invitations = $state<Invitation[]>([]);
let loading = $state(false);
let error = $state<string | null>(null);
let showCreate = $state(false);
let createEmail = $state('');
let createDisplayName = $state('');
let createRoles = $state('');
let sendEmail = $state(false);
let templateLinkBase = $state('');
let templateFrom = $state('');
let templateSubject = $state('You have been invited');
let templateBody = $state(
"Welcome — click the link below to set up your account.\n\n{link}"
);
let creating = $state(false);
let toRevoke = $state<Invitation | null>(null);
let revoking = $state(false);
async function loadApp() {
try {
app = await api.apps.get(slug);
} catch (e) {
error = e instanceof ApiError ? e.message : String(e);
}
}
async function loadInvitations() {
loading = true;
error = null;
try {
const res = await api.appInvitations.list(slug);
invitations = res.invitations;
} catch (e) {
error = e instanceof ApiError ? e.message : String(e);
} finally {
loading = false;
}
}
$effect(() => {
void slug;
void loadApp();
void loadInvitations();
});
async function submitCreate() {
creating = true;
error = null;
try {
const roles = createRoles
.split(',')
.map((s) => s.trim())
.filter((s) => s.length > 0);
const template = sendEmail
? {
link_base: templateLinkBase.trim(),
from: templateFrom.trim(),
subject: templateSubject,
body_template: templateBody
}
: undefined;
const created = await api.appInvitations.create(slug, {
email: createEmail.trim(),
display_name: createDisplayName.trim() || null,
roles,
template
});
invitations = [created, ...invitations];
createEmail = '';
createDisplayName = '';
createRoles = '';
showCreate = false;
} catch (e) {
error = e instanceof ApiError ? e.message : String(e);
} finally {
creating = false;
}
}
async function confirmRevoke() {
if (!toRevoke) return;
revoking = true;
try {
await api.appInvitations.remove(slug, toRevoke.id);
invitations = invitations.filter((i) => i.id !== toRevoke!.id);
toRevoke = null;
} catch (e) {
error = e instanceof ApiError ? e.message : String(e);
} finally {
revoking = false;
}
}
function fmtTime(iso: string): string {
return new Date(iso).toLocaleString();
}
</script>
<svelte:head>
<title>Invitations · {slug} · PiCloud</title>
</svelte:head>
<div class="container">
<header>
<div>
<a href="{base}/apps/{slug}/users" class="back">&larr; back to Users</a>
<h1>Invitations</h1>
<p class="subtitle">
Pending invitations. Accepting an invitation creates the user and signs them in
with a fresh session token; pre-staged roles are applied atomically.
</p>
</div>
<div>
<button type="button" onclick={() => (showCreate = !showCreate)}>
{showCreate ? 'Cancel' : 'New invitation'}
</button>
</div>
</header>
{#if showCreate}
<form
class="create-form"
onsubmit={(e) => {
e.preventDefault();
void submitCreate();
}}
>
<label>
<span>Email</span>
<input type="email" required bind:value={createEmail} />
</label>
<label>
<span>Display name (optional)</span>
<input type="text" bind:value={createDisplayName} />
</label>
<label>
<span>Roles (comma-separated, optional)</span>
<input type="text" bind:value={createRoles} placeholder="editor, admin" />
</label>
<label class="checkbox-row">
<input type="checkbox" bind:checked={sendEmail} />
<span>Send invitation email</span>
<small class="muted">
Off = generate token only (out-of-band delivery). Requires SMTP configured.
</small>
</label>
{#if sendEmail}
<label>
<span>Link base</span>
<input
type="url"
required
bind:value={templateLinkBase}
placeholder="https://app.example.com/accept-invite"
/>
</label>
<label>
<span>From</span>
<input
type="email"
required
bind:value={templateFrom}
placeholder="invites@app.example.com"
/>
</label>
<label>
<span>Subject</span>
<input type="text" required bind:value={templateSubject} />
</label>
<label class="full-row">
<span>Body template (use <code>{'{link}'}</code> placeholder)</span>
<textarea rows={5} bind:value={templateBody}></textarea>
</label>
{/if}
<button type="submit" disabled={creating} class="full-row">
{creating ? 'Creating…' : 'Create invitation'}
</button>
</form>
{/if}
{#if error}
<div class="error">{error}</div>
{/if}
{#if loading}
<p class="muted">Loading…</p>
{:else if invitations.length === 0}
<p class="muted">No pending invitations.</p>
{:else}
<table>
<thead>
<tr>
<th>Email</th>
<th>Display name</th>
<th>Roles</th>
<th>Created</th>
<th>Expires</th>
<th></th>
</tr>
</thead>
<tbody>
{#each invitations as inv (inv.id)}
<tr>
<td>{inv.email}</td>
<td>{inv.display_name ?? '—'}</td>
<td>
{#each inv.roles as r}
<span class="chip">{r}</span>
{/each}
</td>
<td>{fmtTime(inv.created_at)}</td>
<td>{fmtTime(inv.expires_at)}</td>
<td>
<button type="button" class="danger" onclick={() => (toRevoke = inv)}>
Revoke
</button>
</td>
</tr>
{/each}
</tbody>
</table>
{/if}
</div>
{#if toRevoke}
<ConfirmModal
title="Revoke invitation"
variant="danger"
confirmLabel="Revoke"
busy={revoking}
onConfirm={confirmRevoke}
onCancel={() => (toRevoke = null)}
>
<p>
Revoke pending invitation for <strong>{toRevoke.email}</strong>? The token sent
to them becomes inert immediately.
</p>
</ConfirmModal>
{/if}
<style>
.container {
max-width: 70rem;
margin: 0 auto;
padding: 1.5rem;
}
header {
display: flex;
justify-content: space-between;
align-items: flex-end;
gap: 1rem;
margin-bottom: 1rem;
}
.back {
font-size: 0.85rem;
}
.subtitle {
color: var(--muted, #666);
font-size: 0.9rem;
}
.create-form {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 0.75rem;
align-items: end;
margin-bottom: 1rem;
}
.create-form label {
display: flex;
flex-direction: column;
gap: 0.25rem;
font-size: 0.85rem;
}
.create-form .full-row {
grid-column: span 2;
}
.checkbox-row {
grid-column: span 2;
flex-direction: row;
align-items: center;
gap: 0.5rem;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 0.9rem;
}
th,
td {
text-align: left;
padding: 0.4rem 0.6rem;
border-bottom: 1px solid var(--border, #e2e2e2);
}
.muted {
color: var(--muted, #666);
}
.error {
color: #b00020;
margin: 0.5rem 0;
}
button.danger {
color: #b00020;
}
.chip {
display: inline-block;
padding: 0.1rem 0.4rem;
border-radius: 0.3rem;
background: var(--chip-bg, #eef);
font-size: 0.75rem;
margin-right: 0.25rem;
}
</style>