mirror of
https://github.com/storytold/discord-github-ticket-relay.git
synced 2026-11-26 01:11:23 +01:00
Apps & repositories access for moderators: No access, View or Edit, set in a combined Page access card
This commit is contained in:
1 parent
8d445de583
commit
cda4d5d0de
13 files changed
+277
-63
No files matched your search
+1
-1
@@ -24,7 +24,7 @@ export interface Queryable {
|
||||
}
|
||||
|
||||
const DATE_COLUMN = /(^|_)at$/;
|
||||
const JSON_COLUMNS = new Set(['labels', 'warnings', 'data', 'detail', 'triage_config', 'verdict', 'applied_actions', 'suggestions', 'form', 'last_run_summary', 'stats', 'auto_actions', 'before', 'scope', 'config_used', 'filter', 'triage_access']);
|
||||
const JSON_COLUMNS = new Set(['labels', 'warnings', 'data', 'detail', 'triage_config', 'verdict', 'applied_actions', 'suggestions', 'form', 'last_run_summary', 'stats', 'auto_actions', 'before', 'scope', 'config_used', 'filter', 'triage_access', 'page_access']);
|
||||
const BOOLEAN_COLUMNS = new Set(['enabled', 'repo_private', 'contributor_enabled', 'can_act_tickets', 'can_view_contributors', 'auto_cleanup', 'closed_enabled', 'spam_enabled', 'age_enabled', 'can_search_issues', 'can_manage_files', 'can_view_health', 'apply_suggestions', 'apply_inbox_only', 'github_enabled']);
|
||||
|
||||
function toParam(value: unknown): unknown {
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
-- What a moderator can do on setup pages an admin opens to them (for now Apps & repositories):
|
||||
-- no access, view, or edit (JSON, keyed by page). Moderators start with no access.
|
||||
ALTER TABLE workspace_members ADD COLUMN page_access TEXT NOT NULL DEFAULT '{}';
|
||||
@@ -8,6 +8,17 @@ export type AccessLevel = 'none' | 'view' | 'edit';
|
||||
export const VIEW_ONLY_AREAS: ReadonlySet<TriageArea> = new Set(['activity']);
|
||||
export const TRIAGE_AREA_NAMES: Record<TriageArea, string> = { actions: 'Actions', labels: 'Label groups', prompt: 'Prompt', runs: 'Re-run', activity: 'Activity' };
|
||||
|
||||
/** Setup pages an admin can open to moderators, each with no access, view or edit. */
|
||||
export const PAGE_AREAS = ['apps'] as const;
|
||||
export type PageArea = (typeof PAGE_AREAS)[number];
|
||||
export const PAGE_AREA_NAMES: Record<PageArea, string> = { apps: 'Apps & repositories' };
|
||||
|
||||
/** A moderator's level on a setup page (none when unset or unknown). */
|
||||
export function pageLevel(access: Partial<Record<string, unknown>> | null | undefined, area: PageArea): AccessLevel {
|
||||
const v = access?.[area];
|
||||
return v === 'edit' || v === 'view' ? v : 'none';
|
||||
}
|
||||
|
||||
/** A moderator's level on a Triage page (none when unset or unknown). */
|
||||
export function triageLevel(access: Partial<Record<string, unknown>> | null | undefined, area: TriageArea): AccessLevel {
|
||||
const v = access?.[area];
|
||||
@@ -18,7 +29,8 @@ export function triageLevel(access: Partial<Record<string, unknown>> | null | un
|
||||
/**
|
||||
* What a workspace member may do. Owners and admins can do everything except that only
|
||||
* owners manage people; moderators can always see tickets and, if an admin allows it, act on
|
||||
* them and see contributor verifications. Moderators never change setup, panels or settings.
|
||||
* them, see contributor verifications, and see or change Apps & repositories and the Triage
|
||||
* pages. GitHub, Discord, panels and settings stay with admins.
|
||||
*/
|
||||
export type Permission =
|
||||
| 'view' // overview
|
||||
@@ -30,7 +42,8 @@ export type Permission =
|
||||
| 'health.view' // the Server health page
|
||||
| 'manage' // setup, apps, panels, ticket types, contributor roles, settings, moderator permissions
|
||||
| 'members' // invite people, change roles, remove people
|
||||
| `triage.${TriageArea}.${'view' | 'edit'}`; // a Triage page: see it, or change it
|
||||
| `triage.${TriageArea}.${'view' | 'edit'}` // a Triage page: see it, or change it
|
||||
| `${PageArea}.${'view' | 'edit'}`; // a setup page opened to moderators: see it, or change it
|
||||
|
||||
export interface MemberAccess {
|
||||
role: Role;
|
||||
@@ -41,6 +54,8 @@ export interface MemberAccess {
|
||||
can_view_health: boolean;
|
||||
/** Per Triage page: none, view or edit. */
|
||||
triage_access: Partial<Record<TriageArea, AccessLevel>>;
|
||||
/** Per setup page (Apps & repositories): none, view or edit. */
|
||||
page_access: Partial<Record<PageArea, AccessLevel>>;
|
||||
}
|
||||
|
||||
export function can(m: MemberAccess, p: Permission): boolean {
|
||||
@@ -61,6 +76,11 @@ export function can(m: MemberAccess, p: Permission): boolean {
|
||||
case 'health.view':
|
||||
return m.can_view_health;
|
||||
default: {
|
||||
const page = /^(\w+)\.(view|edit)$/.exec(p);
|
||||
if (page && (PAGE_AREAS as readonly string[]).includes(page[1]!)) {
|
||||
const level = pageLevel(m.page_access, page[1] as PageArea);
|
||||
return page[2] === 'view' ? level !== 'none' : level === 'edit';
|
||||
}
|
||||
const t = /^triage\.(\w+)\.(view|edit)$/.exec(p);
|
||||
if (!t || !(TRIAGE_AREAS as readonly string[]).includes(t[1]!)) return false;
|
||||
const level = triageLevel(m.triage_access, t[1] as TriageArea);
|
||||
|
||||
@@ -2,7 +2,7 @@ import { withTransaction, type Db, type Queryable } from '../db/database.js';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { randomToken, sha256 } from '../lib/crypto.js';
|
||||
import type { Config } from '../config.js';
|
||||
import { TRIAGE_AREAS, triageLevel, type MemberAccess } from './permissions.js';
|
||||
import { PAGE_AREAS, pageLevel, TRIAGE_AREAS, triageLevel, type MemberAccess } from './permissions.js';
|
||||
import { UserFacingError, type Role, type UserRow, type WorkspaceRow } from './types.js';
|
||||
|
||||
export async function upsertUser(
|
||||
@@ -25,10 +25,10 @@ export interface Membership extends MemberAccess {
|
||||
workspace: WorkspaceRow;
|
||||
}
|
||||
|
||||
const MEMBER_COLUMNS = 'm.role, m.can_act_tickets, m.can_view_contributors, m.can_search_issues, m.can_manage_files, m.can_view_health, m.triage_access';
|
||||
const MEMBER_COLUMNS = 'm.role, m.can_act_tickets, m.can_view_contributors, m.can_search_issues, m.can_manage_files, m.can_view_health, m.triage_access, m.page_access';
|
||||
|
||||
function toMembership(row: Record<string, unknown>): Membership {
|
||||
const { role, can_act_tickets, can_view_contributors, can_search_issues, can_manage_files, can_view_health, triage_access, ...workspace } = row;
|
||||
const { role, can_act_tickets, can_view_contributors, can_search_issues, can_manage_files, can_view_health, triage_access, page_access, ...workspace } = row;
|
||||
return {
|
||||
workspace: workspace as unknown as WorkspaceRow,
|
||||
role: role as Role,
|
||||
@@ -38,6 +38,7 @@ function toMembership(row: Record<string, unknown>): Membership {
|
||||
can_manage_files: Boolean(can_manage_files),
|
||||
can_view_health: Boolean(can_view_health),
|
||||
triage_access: (triage_access && typeof triage_access === 'object' ? triage_access : {}) as MemberAccess['triage_access'],
|
||||
page_access: (page_access && typeof page_access === 'object' ? page_access : {}) as MemberAccess['page_access'],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -216,6 +217,21 @@ export async function setModeratorTriageAccess(q: Queryable, workspaceId: string
|
||||
return clean;
|
||||
}
|
||||
|
||||
/** Changes a moderator's level on the setup pages given; the others keep theirs. */
|
||||
export async function setModeratorPageAccess(q: Queryable, workspaceId: string, userId: string, access: Partial<Record<string, string>>): Promise<MemberAccess['page_access']> {
|
||||
const { rows } = await q.query<{ page_access: MemberAccess['page_access'] }>(`SELECT page_access FROM workspace_members WHERE workspace_id = $1 AND user_id = $2 AND role = 'moderator'`, [workspaceId, userId]);
|
||||
if (!rows[0]) throw new UserFacingError('Only moderators have adjustable permissions.', 404);
|
||||
const next = { ...rows[0].page_access };
|
||||
for (const a of PAGE_AREAS) {
|
||||
if (access[a] === undefined) continue;
|
||||
const level = pageLevel(access, a);
|
||||
if (level === 'none') delete next[a];
|
||||
else next[a] = level;
|
||||
}
|
||||
await q.query(`UPDATE workspace_members SET page_access = $3 WHERE workspace_id = $1 AND user_id = $2 AND role = 'moderator'`, [workspaceId, userId, next]);
|
||||
return next;
|
||||
}
|
||||
|
||||
export async function setModeratorPermissions(
|
||||
q: Queryable,
|
||||
workspaceId: string,
|
||||
|
||||
+9
-6
@@ -4,7 +4,7 @@ import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { html, raw, type SafeHtml } from '../lib/html.js';
|
||||
import type { Membership } from '../domain/workspaces.js';
|
||||
import { can, ROLE_LABELS, TRIAGE_AREAS, type MemberAccess } from '../domain/permissions.js';
|
||||
import { can, PAGE_AREAS, ROLE_LABELS, TRIAGE_AREAS, type MemberAccess } from '../domain/permissions.js';
|
||||
import type { Role, UserRow, WorkspaceRow } from '../domain/types.js';
|
||||
import { avatar, csrfField, discordAvatar, icon, iconBtn, initials, menu, notice, type IconName } from './ui.js';
|
||||
|
||||
@@ -72,8 +72,10 @@ function navItem(href: string, label: string, name: IconName, active: boolean, t
|
||||
}
|
||||
|
||||
/** A page this person can't open: shown greyed out with a lock, so they know it exists. */
|
||||
function lockedNavItem(label: string, name: IconName): SafeHtml {
|
||||
return html`<span class="nav-item locked" aria-disabled="true" title="Only admins can open ${label}. Ask an admin if you need access.">${icon(name)}<span>${label}</span><span class="trail">${icon('lock', 14)}<span class="sr-only"> (admins only)</span></span></span>`;
|
||||
/** A page this person can't open: greyed out with a lock. `grantable` pages can be opened to moderators by an admin. */
|
||||
function lockedNavItem(label: string, name: IconName, o: { grantable?: boolean } = {}): SafeHtml {
|
||||
const why = o.grantable ? `You don’t have access to ${label}. Ask an admin if you need it.` : `Only admins can open ${label}. Ask an admin if you need access.`;
|
||||
return html`<span class="nav-item locked" aria-disabled="true" title="${why}">${icon(name)}<span>${label}</span><span class="trail">${icon('lock', 14)}<span class="sr-only"> (${o.grantable ? 'no access' : 'admins only'})</span></span></span>`;
|
||||
}
|
||||
|
||||
function stepMark(state: StepState): SafeHtml {
|
||||
@@ -83,8 +85,9 @@ function stepMark(state: StepState): SafeHtml {
|
||||
}
|
||||
|
||||
export function roleLabel(access: MemberAccess): string {
|
||||
// View only: can't act on tickets or change any Triage page.
|
||||
if (access.role === 'moderator' && !access.can_act_tickets && !TRIAGE_AREAS.some((a) => can(access, `triage.${a}.edit`))) return 'Moderator · View only';
|
||||
// View only: can't act on tickets or change any page.
|
||||
const changes = access.can_act_tickets || TRIAGE_AREAS.some((a) => can(access, `triage.${a}.edit`)) || PAGE_AREAS.some((a) => can(access, `${a}.edit`));
|
||||
if (access.role === 'moderator' && !changes) return 'Moderator · View only';
|
||||
return ROLE_LABELS[access.role];
|
||||
}
|
||||
|
||||
@@ -110,7 +113,7 @@ export function layout(ctx: PageContext, opts: { title: string; active: string;
|
||||
<div class="nav-label">General setup</div>
|
||||
${manage ? navItem(`${base}/setup/github`, 'GitHub', 'github', a === 'github', stepMark(p?.github ?? 'todo')) : lockedNavItem('GitHub', 'github')}
|
||||
${manage ? navItem(`${base}/setup/discord`, 'Discord', 'message-circle', a === 'discord', stepMark(p?.discord ?? 'todo')) : lockedNavItem('Discord', 'message-circle')}
|
||||
${manage ? navItem(`${base}/apps`, 'Apps & repositories', 'boxes', a === 'apps', stepMark(p?.apps ?? 'todo')) : lockedNavItem('Apps & repositories', 'boxes')}
|
||||
${can(access, 'apps.view') ? navItem(`${base}/apps`, 'Apps & repositories', 'boxes', a === 'apps', stepMark(p?.apps ?? 'todo')) : lockedNavItem('Apps & repositories', 'boxes', { grantable: true })}
|
||||
<div class="nav-label">Utilities</div>
|
||||
${navItem(`${base}/tickets`, 'Tickets', 'ticket', a === 'tickets', attention)}
|
||||
${can(access, 'contrib.view') ? navItem(`${base}/contributors`, 'Contributor Roles', 'award', a === 'contributors') : lockedNavItem('Contributor Roles', 'award')}
|
||||
|
||||
+10
-2
@@ -1052,9 +1052,17 @@ progress.bar.wide { max-width: none; }
|
||||
/* Members › Triage access */
|
||||
.level-select[data-level="none"] { color: var(--muted); }
|
||||
.level-select[data-level="edit"] { color: var(--accent-text); font-weight: 500; }
|
||||
/* Room for the longest choice (“No access”) next to the chevron. */
|
||||
.access-table .select { min-width: 112px; }
|
||||
/* Room for the longest choice (“No access”) next to the chevron; tighter cells so every page fits the card. */
|
||||
.access-table .select { min-width: 100px; }
|
||||
.access-table th.th-perm, .access-table td.perm { padding-left: 8px; padding-right: 8px; }
|
||||
.access-table th.th-perm:first-child, .access-table td.perm:first-child { padding-left: 20px; }
|
||||
.access-table th.th-perm:last-child, .access-table td.perm:last-child { padding-right: 20px; }
|
||||
.access-table td.all-col { border-right: 1px solid var(--border); }
|
||||
/* Page access: a heading row naming each group of pages, with a line where a group starts. */
|
||||
.access-table tr.group-h th.grp { padding-top: 10px; padding-bottom: 0; border-bottom: 0; vertical-align: bottom; }
|
||||
.access-table tr.group-h .g { display: inline-flex; align-items: center; gap: 6px; font: 500 12px/16px var(--font); color: var(--muted); }
|
||||
.access-table tr.group-h th[rowspan] { vertical-align: bottom; }
|
||||
.access-table .group-start, .access-table tr.group-h th.grp + th.grp { border-left: 1px solid var(--border); }
|
||||
.seg-item.locked { opacity: 0.6; cursor: not-allowed; }
|
||||
.seg-item.locked:hover { color: var(--muted); }
|
||||
.seg-item.locked svg { flex: none; }
|
||||
|
||||
+31
-22
@@ -3,10 +3,11 @@ import { z } from 'zod';
|
||||
import type { RepoInfo } from '../../github/client.js';
|
||||
import { getInstallationRepos } from '../../domain/repos.js';
|
||||
import { checkPanel } from '../../domain/panel.js';
|
||||
import { can } from '../../domain/permissions.js';
|
||||
import { createApp, deleteApp, getApp, getGitHubConnection, listApps, moveApp, setAppEnabled, updateApp } from '../../domain/store.js';
|
||||
import { UserFacingError, type AppRow, type Deps } from '../../domain/types.js';
|
||||
import { html, raw } from '../../lib/html.js';
|
||||
import { avatar, badge, csrfField, empty, icon, iconBtn, labelTag, linkBtn, menu, notice, pageHeader, pill, plural, selectWrap, submitBtn, tag } from '../ui.js';
|
||||
import { avatar, badge, csrfField, empty, icon, iconBtn, labelTag, linkBtn, menu, notice, pageHeader, pill, plural, selectWrap, submitBtn, tag, viewOnlyTag } from '../ui.js';
|
||||
import { setFlash } from '../session.js';
|
||||
import type { Web, WorkspaceRequestContext } from '../server.js';
|
||||
|
||||
@@ -58,11 +59,16 @@ async function validateAppInput(deps: Deps, installationId: number, body: unknow
|
||||
return { values, errors, repo };
|
||||
}
|
||||
|
||||
/** How to get a change into Discord: update the panel, or ask an admin to (moderators can't open it). */
|
||||
function panelStep(ctx: WorkspaceRequestContext, what: string): string {
|
||||
return can(ctx.membership, 'manage') ? `Update the panel to ${what}.` : `An admin needs to update the panel to ${what}.`;
|
||||
}
|
||||
|
||||
export function registerAppRoutes(app: FastifyInstance, web: Web): void {
|
||||
const { deps } = web;
|
||||
|
||||
app.get('/w/:wid/apps', async (req, reply) => {
|
||||
const ctx = await web.requireWorkspace(req, reply);
|
||||
const ctx = await web.requireWorkspace(req, reply, { permission: 'apps.view' });
|
||||
if (!ctx) return reply;
|
||||
const apps = await listApps(deps.db, ctx.workspace.id);
|
||||
const panel = await checkPanel(deps, ctx.workspace.id, { live: false });
|
||||
@@ -85,26 +91,27 @@ export function registerAppRoutes(app: FastifyInstance, web: Web): void {
|
||||
return html`<span class="inline" aria-label="Files tickets" title="Files tickets">${icon('circle-check', 16, 'ok')}</span>`;
|
||||
};
|
||||
const b = ctx.base;
|
||||
const edit = can(ctx.membership, 'apps.edit');
|
||||
const repoUse = new Map<number, number>();
|
||||
for (const a of apps) repoUse.set(a.repo_id, (repoUse.get(a.repo_id) ?? 0) + 1);
|
||||
const addApp = linkBtn(`${b}/apps/new`, 'Add app', { variant: 'primary', icon: 'plus' });
|
||||
const addApp = edit ? linkBtn(`${b}/apps/new`, 'Add app', { variant: 'primary', icon: 'plus' }) : null;
|
||||
|
||||
const body = html`
|
||||
${pageHeader({
|
||||
eyebrow: 'General setup · Step 3 of 3',
|
||||
title: 'Apps & repositories',
|
||||
after: apps.length ? badge(apps.length) : '',
|
||||
after: [apps.length ? badge(apps.length) : '', edit ? '' : viewOnlyTag('You can see the apps and their repositories. Ask an admin if you need to change them.')],
|
||||
description: 'The apps members pick in Discord, each mapped to a GitHub repository. Tickets and Contributor Roles both use this list.',
|
||||
actions: addApp,
|
||||
actions: addApp ?? undefined,
|
||||
})}
|
||||
${panel.state === 'published' && panel.outdated
|
||||
? notice('info', 'The ticket panel in Discord doesn’t show your latest changes yet', 'Members still see the old list of apps.', { action: linkBtn(`${b}/tickets/panel`, 'Update panel', { size: 'sm' }) })
|
||||
? notice('info', 'The ticket panel in Discord doesn’t show your latest changes yet', can(ctx.membership, 'manage') ? 'Members still see the old list of apps.' : 'Members still see the old list of apps until an admin updates the panel.', { action: can(ctx.membership, 'manage') ? linkBtn(`${b}/tickets/panel`, 'Update panel', { size: 'sm' }) : undefined })
|
||||
: ''}
|
||||
<div class="card">
|
||||
${apps.length === 0
|
||||
? empty('boxes', 'No apps yet', 'Add the first app members can file tickets for, for example “Mobile app” or “Billing portal”.', addApp)
|
||||
? empty('boxes', 'No apps yet', edit ? 'Add the first app members can file tickets for, for example “Mobile app” or “Billing portal”.' : 'An admin can add the apps members file tickets for.', addApp)
|
||||
: html`<div class="card-b flush"><div class="table-wrap wide"><table>
|
||||
<thead><tr><th>App</th><th>Repository</th><th class="center">Tickets</th><th class="center">Contributor Roles</th><th>Extra labels</th><th class="actions"><span class="sr-only">Actions</span></th></tr></thead>
|
||||
<thead><tr><th>App</th><th>Repository</th><th class="center">Tickets</th><th class="center">Contributor Roles</th><th>Extra labels</th>${edit ? html`<th class="actions"><span class="sr-only">Actions</span></th>` : ''}</tr></thead>
|
||||
<tbody>${apps.map((a, i) => {
|
||||
const shared = repoUse.get(a.repo_id)! - 1;
|
||||
return html`<tr class="${a.enabled ? '' : 'off'}">
|
||||
@@ -113,7 +120,7 @@ export function registerAppRoutes(app: FastifyInstance, web: Web): void {
|
||||
<td class="center">${ticketState(a)}</td>
|
||||
<td class="center">${a.contributor_enabled ? html`<span class="inline" aria-label="Counts for Contributor Roles" title="Counts for Contributor Roles">${icon('circle-check', 16, 'ok')}</span>` : html`<span class="em" aria-label="Not counted">—</span>`}</td>
|
||||
<td>${a.labels.length ? html`<div class="tags">${a.labels.map((l) => labelTag(l))}</div>` : html`<span class="em">—</span>`}</td>
|
||||
<td class="actions"><div class="row">
|
||||
${edit ? html`<td class="actions"><div class="row">
|
||||
${iconBtn('pencil', `Edit ${a.name}`, { size: 'sm', href: `${b}/apps/${a.id}/edit` })}
|
||||
${menu([
|
||||
i > 0 ? { post: `${b}/apps/${a.id}/move`, label: 'Move up', icon: 'arrow-up', fields: { direction: 'up' } } : null,
|
||||
@@ -122,7 +129,7 @@ export function registerAppRoutes(app: FastifyInstance, web: Web): void {
|
||||
'sep',
|
||||
{ post: `${b}/apps/${a.id}/delete`, label: 'Remove app…', icon: 'trash-2', danger: true, confirm: { title: `Remove “${a.name}”?`, body: 'Members can’t pick it after you update the panel. Past tickets are kept.', label: 'Remove app', danger: true } },
|
||||
], { csrf: ctx.csrf, label: `More actions for ${a.name}` })}
|
||||
</div></td></tr>`;
|
||||
</div></td>` : ''}</tr>`;
|
||||
})}
|
||||
</tbody></table></div></div>
|
||||
<div class="card-note">Hidden apps don’t appear on the panel. With more than 25 apps, the panel shows 24 and a “More apps…” option that opens a page-by-page list.</div>`}
|
||||
@@ -140,7 +147,8 @@ export function registerAppRoutes(app: FastifyInstance, web: Web): void {
|
||||
description: 'Members only see the name and description. The repository stays behind the scenes.',
|
||||
});
|
||||
if (!gh || !deps.github) {
|
||||
return web.render(reply, ctx, title, 'apps', html`${header}${notice('warn', 'Connect GitHub first', 'You need a connected GitHub account to choose a repository.', { action: linkBtn(`${b}/setup/github`, 'Connect GitHub', { size: 'sm' }) })}`);
|
||||
const admin = can(ctx.membership, 'manage');
|
||||
return web.render(reply, ctx, title, 'apps', html`${header}${notice('warn', 'Connect GitHub first', admin ? 'You need a connected GitHub account to choose a repository.' : 'An admin needs to connect GitHub before apps can be added.', { action: admin ? linkBtn(`${b}/setup/github`, 'Connect GitHub', { size: 'sm' }) : undefined })}`);
|
||||
}
|
||||
let repos: RepoInfo[] = [];
|
||||
let repoError = '';
|
||||
@@ -162,6 +170,7 @@ export function registerAppRoutes(app: FastifyInstance, web: Web): void {
|
||||
<div class="field"><label for="description">Short description <span class="opt">(optional)</span></label><input id="description" type="text" name="description" value="${values.description}" maxlength="100" placeholder="iOS and Android"><div class="hint">Helps members pick the right app. Up to 100 characters.</div></div>
|
||||
</div>
|
||||
<div class="field"><label for="repo">GitHub repository</label>
|
||||
${can(ctx.membership, 'manage') ? '' : html`<div class="hint">Repositories the GitHub App can access. Ask an admin if one is missing.</div>`}
|
||||
${selectWrap(html`<select id="repo" name="repo_id" required>
|
||||
<option value="">Choose a repository…</option>
|
||||
${repos.map((r) => {
|
||||
@@ -170,7 +179,7 @@ export function registerAppRoutes(app: FastifyInstance, web: Web): void {
|
||||
})}
|
||||
</select>`)}
|
||||
<div class="hint" id="repo-visibility"></div>
|
||||
${repos.length === 0 && !repoError ? html`<div class="hint">No repositories are shared with the GitHub App yet. <a href="${b}/setup/github">Manage repository access</a>.</div>` : ''}
|
||||
${repos.length === 0 && !repoError ? html`<div class="hint">No repositories are shared with the GitHub App yet. ${can(ctx.membership, 'manage') ? html`<a href="${b}/setup/github">Manage repository access</a>.` : 'Ask an admin to share them in GitHub setup.'}</div>` : ''}
|
||||
</div>
|
||||
<div class="field"><span class="label">Labels <span class="opt">(optional)</span></span>
|
||||
<div class="hint">Existing labels from the repository, added to every ticket for this app.</div>
|
||||
@@ -188,13 +197,13 @@ export function registerAppRoutes(app: FastifyInstance, web: Web): void {
|
||||
}
|
||||
|
||||
app.get('/w/:wid/apps/new', async (req, reply) => {
|
||||
const ctx = await web.requireWorkspace(req, reply);
|
||||
const ctx = await web.requireWorkspace(req, reply, { permission: 'apps.edit' });
|
||||
if (!ctx) return reply;
|
||||
return renderForm(ctx, reply, null, { name: '', description: '', repoId: null, labels: [], enabled: true });
|
||||
});
|
||||
|
||||
app.get('/w/:wid/apps/:appId/edit', async (req, reply) => {
|
||||
const ctx = await web.requireWorkspace(req, reply);
|
||||
const ctx = await web.requireWorkspace(req, reply, { permission: 'apps.edit' });
|
||||
if (!ctx) return reply;
|
||||
const existing = await getApp(deps.db, ctx.workspace.id, (req.params as { appId: string }).appId);
|
||||
if (!existing) return reply.callNotFound();
|
||||
@@ -202,7 +211,7 @@ export function registerAppRoutes(app: FastifyInstance, web: Web): void {
|
||||
});
|
||||
|
||||
async function save(req: FastifyRequest, reply: FastifyReply, appId: string | null) {
|
||||
const ctx = await web.requireWorkspace(req, reply);
|
||||
const ctx = await web.requireWorkspace(req, reply, { permission: 'apps.edit' });
|
||||
if (!ctx) return reply;
|
||||
const existing = appId ? await getApp(deps.db, ctx.workspace.id, appId) : null;
|
||||
if (appId && !existing) return reply.callNotFound();
|
||||
@@ -229,7 +238,7 @@ export function registerAppRoutes(app: FastifyInstance, web: Web): void {
|
||||
if (err instanceof UserFacingError) return renderForm(ctx, reply.code(400), existing, result.values, [err.message]);
|
||||
throw err;
|
||||
}
|
||||
setFlash(reply, 'success', existing ? `Saved “${input.name}”` : `Added “${input.name}”. Update the panel to show it in Discord.`);
|
||||
setFlash(reply, 'success', existing ? `Saved “${input.name}”` : `Added “${input.name}”. ${panelStep(ctx, 'show it in Discord')}`);
|
||||
return reply.redirect(`${ctx.base}/apps`);
|
||||
}
|
||||
|
||||
@@ -237,17 +246,17 @@ export function registerAppRoutes(app: FastifyInstance, web: Web): void {
|
||||
app.post('/w/:wid/apps/:appId', (req, reply) => save(req, reply, (req.params as { appId: string }).appId));
|
||||
|
||||
app.post('/w/:wid/apps/:appId/toggle', async (req, reply) => {
|
||||
const ctx = await web.requireWorkspace(req, reply);
|
||||
const ctx = await web.requireWorkspace(req, reply, { permission: 'apps.edit' });
|
||||
if (!ctx) return reply;
|
||||
const existing = await getApp(deps.db, ctx.workspace.id, (req.params as { appId: string }).appId);
|
||||
if (!existing) return reply.callNotFound();
|
||||
await setAppEnabled(deps.db, ctx.workspace.id, existing.id, !existing.enabled);
|
||||
setFlash(reply, 'success', `“${existing.name}” ${existing.enabled ? 'hidden from' : 'shown on'} the panel. Update the panel to reflect this in Discord.`);
|
||||
setFlash(reply, 'success', `“${existing.name}” ${existing.enabled ? 'hidden from' : 'shown on'} the panel. ${panelStep(ctx, 'reflect this in Discord')}`);
|
||||
return reply.redirect(`${ctx.base}/apps`);
|
||||
});
|
||||
|
||||
app.post('/w/:wid/apps/:appId/move', async (req, reply) => {
|
||||
const ctx = await web.requireWorkspace(req, reply);
|
||||
const ctx = await web.requireWorkspace(req, reply, { permission: 'apps.edit' });
|
||||
if (!ctx) return reply;
|
||||
const direction = (req.body as { direction?: string }).direction === 'up' ? 'up' : 'down';
|
||||
await moveApp(deps.db, ctx.workspace.id, (req.params as { appId: string }).appId, direction);
|
||||
@@ -255,18 +264,18 @@ export function registerAppRoutes(app: FastifyInstance, web: Web): void {
|
||||
});
|
||||
|
||||
app.post('/w/:wid/apps/:appId/delete', async (req, reply) => {
|
||||
const ctx = await web.requireWorkspace(req, reply);
|
||||
const ctx = await web.requireWorkspace(req, reply, { permission: 'apps.edit' });
|
||||
if (!ctx) return reply;
|
||||
const existing = await getApp(deps.db, ctx.workspace.id, (req.params as { appId: string }).appId);
|
||||
if (!existing) return reply.callNotFound();
|
||||
await deleteApp(deps.db, ctx.workspace.id, existing.id);
|
||||
setFlash(reply, 'success', `Removed “${existing.name}”. Update the panel to remove it from Discord.`);
|
||||
setFlash(reply, 'success', `Removed “${existing.name}”. ${panelStep(ctx, 'remove it from Discord')}`);
|
||||
return reply.redirect(`${ctx.base}/apps`);
|
||||
});
|
||||
|
||||
/** JSON: labels of a repository, restricted to repositories the installation can access. */
|
||||
app.get('/w/:wid/apps/labels', async (req, reply) => {
|
||||
const ctx = await web.requireWorkspace(req, reply);
|
||||
const ctx = await web.requireWorkspace(req, reply, { permission: 'apps.edit' });
|
||||
if (!ctx) return reply;
|
||||
const gh = await getGitHubConnection(deps.db, ctx.workspace.id);
|
||||
if (!gh || !deps.github) return reply.code(400).send({ error: 'Connect GitHub first.' });
|
||||
|
||||
+58
-16
@@ -1,7 +1,7 @@
|
||||
import type { FastifyInstance, FastifyReply } from 'fastify';
|
||||
import { can, ROLE_LABELS, TRIAGE_AREA_NAMES, TRIAGE_AREAS, triageLevel, VIEW_ONLY_AREAS, type AccessLevel, type MemberAccess, type TriageArea } from '../../domain/permissions.js';
|
||||
import { can, PAGE_AREA_NAMES, PAGE_AREAS, pageLevel, ROLE_LABELS, TRIAGE_AREA_NAMES, TRIAGE_AREAS, triageLevel, VIEW_ONLY_AREAS, type AccessLevel, type MemberAccess, type PageArea, type TriageArea } from '../../domain/permissions.js';
|
||||
import { UserFacingError, type Role } from '../../domain/types.js';
|
||||
import { createInvite, listInvites, listMembers, removeMember, revokeInvite, setMemberRole, setModeratorPermissions, setModeratorTriageAccess } from '../../domain/workspaces.js';
|
||||
import { createInvite, listInvites, listMembers, removeMember, revokeInvite, setMemberRole, setModeratorPageAccess, setModeratorPermissions, setModeratorTriageAccess } from '../../domain/workspaces.js';
|
||||
import { html, raw, type SafeHtml } from '../../lib/html.js';
|
||||
import { setFlash } from '../session.js';
|
||||
import type { Web, WorkspaceRequestContext } from '../server.js';
|
||||
@@ -51,7 +51,8 @@ const MOD_SWITCHES = [
|
||||
type ModField = (typeof MOD_SWITCHES)[number]['field'];
|
||||
|
||||
const CAPABILITIES: [string, string, string, string][] = [
|
||||
['Setup, panels and settings', 'yes', 'yes', 'no'],
|
||||
['GitHub, Discord, panels and settings', 'yes', 'yes', 'no'],
|
||||
['Apps & repositories (view or edit)', 'yes', 'yes', 'maybe'],
|
||||
['Ticket forms and file rules', 'yes', 'yes', 'no'],
|
||||
['Triage pages (view or edit, page by page)', 'yes', 'yes', 'maybe'],
|
||||
['Tickets inbox', 'yes', 'yes', 'yes'],
|
||||
@@ -64,6 +65,11 @@ const CAPABILITIES: [string, string, string, string][] = [
|
||||
['Invite people and change roles', 'yes', 'no', 'no'],
|
||||
];
|
||||
|
||||
/** What each setup page covers, for the access table. */
|
||||
const PAGE_AREA_DESC: Record<PageArea, string> = {
|
||||
apps: 'Apps and their repositories.',
|
||||
};
|
||||
|
||||
/** What each Triage page covers, for the access table. */
|
||||
const TRIAGE_AREA_DESC: Record<TriageArea, string> = {
|
||||
actions: 'Switches, actions, rules and limits.',
|
||||
@@ -89,7 +95,8 @@ function accessTags(m: MemberAccess): SafeHtml {
|
||||
if (m.role === 'owner') return html`${tag('Full access')}${tag('Invites & roles')}`;
|
||||
if (m.role === 'admin') return tag('Full access');
|
||||
const triage = triageSummary(m);
|
||||
return html`${tag(m.can_act_tickets ? 'Act on tickets' : 'View tickets')}${m.can_view_contributors ? tag('Verifications') : ''}${m.can_search_issues ? tag('Issue search') : ''}${m.can_manage_files ? tag('Files') : ''}${m.can_view_health ? tag('Server health') : ''}${triage ? tag(triage) : ''}`;
|
||||
const pages = PAGE_AREAS.filter((a) => pageLevel(m.page_access, a) !== 'none').map((a) => tag(`${a === 'apps' ? 'Apps' : PAGE_AREA_NAMES[a]}: ${pageLevel(m.page_access, a)}`));
|
||||
return html`${pages}${tag(m.can_act_tickets ? 'Act on tickets' : 'View tickets')}${m.can_view_contributors ? tag('Verifications') : ''}${m.can_search_issues ? tag('Issue search') : ''}${m.can_manage_files ? tag('Files') : ''}${m.can_view_health ? tag('Server health') : ''}${triage ? tag(triage) : ''}`;
|
||||
}
|
||||
|
||||
export function registerMemberRoutes(app: FastifyInstance, web: Web): void {
|
||||
@@ -155,7 +162,7 @@ export function registerMemberRoutes(app: FastifyInstance, web: Web): void {
|
||||
switchInput({ name: field, checked: m[field], label: `${nameOf(m)}: ${label}`, attrs: html`form="perm-${suffix}${m.id}"` });
|
||||
|
||||
const modAccess = html`<div class="card" id="moderator-access">
|
||||
<div class="card-h"><div><h2>Moderator access</h2><div class="desc">New moderators start view-only. Moderators never see setup, panels or settings. Triage pages are set below.</div></div></div>
|
||||
<div class="card-h"><div><h2>Moderator access</h2><div class="desc">New moderators start view-only. The pages they can open, like Apps & repositories and Triage, are set below in Page access. GitHub, Discord, panels and settings stay with admins.</div></div></div>
|
||||
${mods.length
|
||||
? html`${mods.map((m) => html`${permForm(m, '')}${permForm(m, 'm-')}`)}
|
||||
<div class="table-wrap only-desktop"><table>
|
||||
@@ -175,32 +182,46 @@ export function registerMemberRoutes(app: FastifyInstance, web: Web): void {
|
||||
: empty('users', 'No moderators yet', 'Moderators can read the tickets inbox. Invite someone as a moderator, then choose what else they can do here.', owner ? linkBtn(`${b}/members?invite=1#invite`, 'Invite', { icon: 'user-plus' }) : null)}
|
||||
</div>`;
|
||||
|
||||
const levelOptions = (levels: AccessLevel[], level: AccessLevel) => levels.map((l) => html`<option value="${l}" ${l === level ? raw('selected') : ''}>${LEVEL_NAMES[l]}</option>`);
|
||||
const levelSelect = (m: (typeof members)[number], area: TriageArea, suffix: string) => {
|
||||
const level = triageLevel(m.triage_access, area);
|
||||
const levels: AccessLevel[] = VIEW_ONLY_AREAS.has(area) ? ['none', 'view'] : ['none', 'view', 'edit'];
|
||||
return selectWrap(html`<select name="${area}" form="tri-${suffix}${m.id}" class="level-select" data-level="${level}" aria-label="${nameOf(m)}: ${TRIAGE_AREA_NAMES[area]}">${levels.map((l) => html`<option value="${l}" ${l === level ? raw('selected') : ''}>${LEVEL_NAMES[l]}</option>`)}</select>`, { sm: true });
|
||||
return selectWrap(html`<select name="${area}" form="tri-${suffix}${m.id}" class="level-select" data-level="${level}" aria-label="${nameOf(m)}: ${TRIAGE_AREA_NAMES[area]}">${levelOptions(levels, level)}</select>`, { sm: true });
|
||||
};
|
||||
// "All pages" sets every page at once (Activity goes up to View); it shows Custom when they differ.
|
||||
const pageSelect = (m: (typeof members)[number], area: PageArea, suffix: string) => {
|
||||
const level = pageLevel(m.page_access, area);
|
||||
return selectWrap(html`<select name="${area}" form="pg-${suffix}${m.id}" class="level-select" data-level="${level}" aria-label="${nameOf(m)}: ${PAGE_AREA_NAMES[area]}">${levelOptions(['none', 'view', 'edit'], level)}</select>`, { sm: true });
|
||||
};
|
||||
// "All Triage pages" sets every Triage page at once (Activity goes up to View); it shows Custom when they differ.
|
||||
const allSelect = (m: (typeof members)[number], suffix: string) => {
|
||||
const levels = TRIAGE_AREAS.map((a) => triageLevel(m.triage_access, a));
|
||||
const same = (l: AccessLevel) => TRIAGE_AREAS.every((a, i) => levels[i] === (l === 'edit' && VIEW_ONLY_AREAS.has(a) ? 'view' : l));
|
||||
const current = (['none', 'view', 'edit'] as const).find(same) ?? '';
|
||||
return selectWrap(html`<select data-set-levels="tri-${suffix}${m.id}" aria-label="${nameOf(m)}: every Triage page"><option value="" ${current ? '' : raw('selected')} disabled hidden>Custom</option>${(['none', 'view', 'edit'] as const).map((l) => html`<option value="${l}" ${l === current ? raw('selected') : ''}>${l === 'none' ? 'No access' : l === 'view' ? 'View all' : 'Edit all'}</option>`)}</select>`, { sm: true });
|
||||
};
|
||||
const triageAccess = mods.length ? html`<div class="card" id="triage-access">
|
||||
<div class="card-h"><div><h2>Triage access</h2><div class="desc">What each moderator can do in Tickets › Triage, page by page. <strong>View</strong> shows the page with every control turned off; <strong>Edit</strong> lets them change it. Moderators start with no access.</div></div></div>
|
||||
${mods.map((m) => html`<form id="tri-${m.id}" method="post" action="${b}/members/${m.id}/triage-access" data-async hidden>${csrfField(ctx.csrf)}</form><form id="tri-m-${m.id}" method="post" action="${b}/members/${m.id}/triage-access" data-async hidden>${csrfField(ctx.csrf)}</form>`)}
|
||||
const accessForms = (m: (typeof members)[number]) => html`${['', 'm-'].map((suffix) => html`<form id="pg-${suffix}${m.id}" method="post" action="${b}/members/${m.id}/page-access" data-async hidden>${csrfField(ctx.csrf)}</form><form id="tri-${suffix}${m.id}" method="post" action="${b}/members/${m.id}/triage-access" data-async hidden>${csrfField(ctx.csrf)}</form>`)}`;
|
||||
const pageAccess = mods.length ? html`<div class="card" id="page-access">
|
||||
<div class="card-h"><div><h2>Page access</h2><div class="desc">Pages each moderator can open, and whether they can change them. <strong>View</strong> shows the page with every control turned off; <strong>Edit</strong> lets them change it. Moderators start with no access.</div></div></div>
|
||||
${mods.map(accessForms)}
|
||||
<div class="table-wrap only-desktop"><table class="access-table">
|
||||
<thead><tr><th class="th-perm"><div class="l">Moderator</div></th><th class="th-perm"><div class="l">All pages</div><div class="d">Set every page at once.</div></th>${TRIAGE_AREAS.map((a) => html`<th class="th-perm"><div class="l">${TRIAGE_AREA_NAMES[a]}</div><div class="d">${TRIAGE_AREA_DESC[a]}</div></th>`)}</tr></thead>
|
||||
<thead>
|
||||
<tr class="group-h"><th class="th-perm" rowspan="2"><div class="l">Moderator</div></th><th class="th-perm grp" colspan="${String(PAGE_AREAS.length)}"><div class="g">${icon('boxes', 14)}General setup</div></th><th class="th-perm grp" colspan="${String(TRIAGE_AREAS.length + 1)}"><div class="g">${icon('ticket', 14)}Tickets › Triage</div></th></tr>
|
||||
<tr>${PAGE_AREAS.map((a) => html`<th class="th-perm"><div class="l">${PAGE_AREA_NAMES[a]}</div><div class="d">${PAGE_AREA_DESC[a]}</div></th>`)}<th class="th-perm group-start"><div class="l">All Triage pages</div><div class="d">Set them all at once.</div></th>${TRIAGE_AREAS.map((a) => html`<th class="th-perm"><div class="l">${TRIAGE_AREA_NAMES[a]}</div><div class="d">${TRIAGE_AREA_DESC[a]}</div></th>`)}</tr>
|
||||
</thead>
|
||||
<tbody>${mods.map((m) => html`<tr>
|
||||
<td class="perm"><span class="who-cell">${avatar(nameOf(m), 24, { src: discordAvatar(m) })}<span class="name">${nameOf(m)}</span></span></td>
|
||||
<td class="perm all-col">${allSelect(m, '')}</td>
|
||||
${PAGE_AREAS.map((a) => html`<td class="perm">${pageSelect(m, a, '')}</td>`)}
|
||||
<td class="perm group-start all-col">${allSelect(m, '')}</td>
|
||||
${TRIAGE_AREAS.map((a) => html`<td class="perm">${levelSelect(m, a, '')}</td>`)}
|
||||
</tr>`)}</tbody></table></div>
|
||||
<div class="only-mobile">${mods.map((m) => html`<div class="mod-block">
|
||||
<div class="line"><span class="who-cell">${avatar(nameOf(m), 24, { src: discordAvatar(m) })}<span class="name">${nameOf(m)}</span></span>${allSelect(m, 'm-')}</div>
|
||||
<div class="line"><span class="who-cell">${avatar(nameOf(m), 24, { src: discordAvatar(m) })}<span class="name">${nameOf(m)}</span></span></div>
|
||||
<div class="sub-h">General setup</div>
|
||||
${PAGE_AREAS.map((a) => setting(PAGE_AREA_NAMES[a], PAGE_AREA_DESC[a], pageSelect(m, a, 'm-')))}
|
||||
<div class="sub-h">Tickets › Triage</div>
|
||||
${setting('All Triage pages', 'Set them all at once.', allSelect(m, 'm-'))}
|
||||
${TRIAGE_AREAS.map((a) => setting(TRIAGE_AREA_NAMES[a], TRIAGE_AREA_DESC[a], levelSelect(m, a, 'm-')))}</div>`)}</div>
|
||||
<div class="card-note">Changes apply right away. “Use these settings” on a re-run also needs Edit on Actions, Label groups and Prompt. Applying suggestions on tickets is set by “Act on tickets” above.</div>
|
||||
<div class="card-note">Changes apply right away. Edit on Apps & repositories lets them add, change and remove apps, and pick any repository the GitHub App can access; updating the panel in Discord stays with admins. “Use these settings” on a re-run also needs Edit on Actions, Label groups and Prompt. Applying suggestions on tickets is set by “Act on tickets” above.</div>
|
||||
</div>` : '';
|
||||
|
||||
const mark = (v: string) => (v === 'yes' ? html`${icon('circle-check', 16, 'ok')}<span class="sr-only">Yes</span>` : v === 'maybe' ? html`<span class="xs muted">If allowed</span>` : html`<span class="em" aria-label="No">—</span>`);
|
||||
@@ -217,7 +238,7 @@ export function registerMemberRoutes(app: FastifyInstance, web: Web): void {
|
||||
${pending}
|
||||
</div>
|
||||
${modAccess}
|
||||
${triageAccess}
|
||||
${pageAccess}
|
||||
<details class="card">
|
||||
<summary>${icon('info')}<span>What each role can do</span>${icon('chevron-down', 16, 'chev')}</summary>
|
||||
<div class="table-wrap"><table>
|
||||
@@ -304,6 +325,27 @@ export function registerMemberRoutes(app: FastifyInstance, web: Web): void {
|
||||
return reply.redirect(`${ctx.base}/members`);
|
||||
});
|
||||
|
||||
/** Owners and admins set a moderator's access to setup pages such as Apps & repositories (JSON from the selects, or a form). */
|
||||
app.post('/w/:wid/members/:userId/page-access', async (req, reply) => {
|
||||
const ctx = await web.requireWorkspace(req, reply, { permission: 'manage' });
|
||||
if (!ctx) return reply;
|
||||
const userId = (req.params as { userId: string }).userId;
|
||||
try {
|
||||
const before = (await listMembers(deps.db, ctx.workspace.id)).find((m) => m.id === userId);
|
||||
const next = await setModeratorPageAccess(deps.db, ctx.workspace.id, userId, req.body as Record<string, string>);
|
||||
const name = before ? before.display_name ?? before.username : 'Moderator';
|
||||
const changes = PAGE_AREAS.filter((a) => pageLevel(before?.page_access, a) !== pageLevel(next, a)).map((a) => `${PAGE_AREA_NAMES[a]} → ${LEVEL_NAMES[pageLevel(next, a)]}`);
|
||||
const message = `${name}: ${changes.length ? changes.join(', ') : 'Access saved'}`;
|
||||
if (web.wantsJson(req)) return reply.send({ ok: true, message });
|
||||
setFlash(reply, 'success', message);
|
||||
} catch (err) {
|
||||
if (!(err instanceof UserFacingError)) throw err;
|
||||
if (web.wantsJson(req)) return reply.code(err.status).send({ ok: false, error: err.message });
|
||||
setFlash(reply, 'error', err.message);
|
||||
}
|
||||
return reply.redirect(`${ctx.base}/members#page-access`);
|
||||
});
|
||||
|
||||
/** Owners and admins set a moderator's access to each Triage page (JSON from the selects, or a form). */
|
||||
app.post('/w/:wid/members/:userId/triage-access', async (req, reply) => {
|
||||
const ctx = await web.requireWorkspace(req, reply, { permission: 'manage' });
|
||||
@@ -322,7 +364,7 @@ export function registerMemberRoutes(app: FastifyInstance, web: Web): void {
|
||||
if (web.wantsJson(req)) return reply.code(err.status).send({ ok: false, error: err.message });
|
||||
setFlash(reply, 'error', err.message);
|
||||
}
|
||||
return reply.redirect(`${ctx.base}/members#triage-access`);
|
||||
return reply.redirect(`${ctx.base}/members#page-access`);
|
||||
});
|
||||
|
||||
app.post('/w/:wid/members/:userId/remove', async (req, reply) => {
|
||||
|
||||
@@ -216,7 +216,7 @@ export function registerTriageConfigRoutes(app: FastifyInstance, web: Web): void
|
||||
${csrfField(ctx.csrf)}
|
||||
<fieldset class="plain stack${edit ? '' : ' view-only'}" ${edit ? '' : raw('disabled')}>
|
||||
<div class="card">
|
||||
<div class="card-h"><div><h2>About your products</h2><div class="desc">Claude reads this with every ticket. It already gets each app’s name, repository and description.</div></div>${can(ctx.membership, 'manage') ? linkBtn(`${ctx.base}/apps`, 'Edit apps', { size: 'sm', variant: 'ghost', trail: 'arrow-right' }) : ''}</div>
|
||||
<div class="card-h"><div><h2>About your products</h2><div class="desc">Claude reads this with every ticket. It already gets each app’s name, repository and description.</div></div>${can(ctx.membership, 'apps.view') ? linkBtn(`${ctx.base}/apps`, can(ctx.membership, 'apps.edit') ? 'Edit apps' : 'See apps', { size: 'sm', variant: 'ghost', trail: 'arrow-right' }) : ''}</div>
|
||||
<div class="card-b tight">${apps.length
|
||||
? html`<ul class="tri-effects">${apps.map((a) => html`<li><span><strong>${a.name}</strong> <span class="muted mono xs">${a.repo_owner}/${a.repo_name}</span>${a.description ? html`<span class="muted"> · ${a.description}</span>` : html`<span class="em"> · no description</span>`}</span></li>`)}</ul>`
|
||||
: html`<p class="small muted">No apps yet.</p>`}</div>
|
||||
|
||||
@@ -3,7 +3,7 @@ import { z } from 'zod';
|
||||
import { checkContributorPanel, contributorApps, getContributorSettings, listManualRoles, listTiers, verificationStats } from '../../domain/contributors.js';
|
||||
import { checkDiscordCredentials, checkGitHubCredentials, type CredentialCheck } from '../../domain/credentials.js';
|
||||
import { checkPanel } from '../../domain/panel.js';
|
||||
import { can } from '../../domain/permissions.js';
|
||||
import { can, firstTriageArea, TRIAGE_AREAS, VIEW_ONLY_AREAS } from '../../domain/permissions.js';
|
||||
import { getDiscordConnection, getGitHubConnection, listApps } from '../../domain/store.js';
|
||||
import { countByStatus, decryptPayload, filedThisWeek, listSubmissions } from '../../domain/submissions.js';
|
||||
import { enabledTicketTypes } from '../../domain/ticket-types.js';
|
||||
@@ -117,9 +117,17 @@ export function registerWorkspaceRoutes(app: FastifyInstance, web: Web): void {
|
||||
|
||||
if (!manage) {
|
||||
// Moderators: what needs attention, the latest tickets and what they're allowed to do.
|
||||
const accessRow = (label: string, allowed: boolean, always = false) => html`<div class="line sm"><span class="grow small">${label}</span>${allowed
|
||||
? html`<span class="locked">${icon('circle-check', 14, 'ok')}${always ? 'Always' : 'Allowed'}</span>`
|
||||
const accessRow = (label: string, allowed: boolean | string, always = false) => html`<div class="line sm"><span class="grow small">${label}</span>${allowed
|
||||
? html`<span class="locked">${icon('circle-check', 14, 'ok')}${typeof allowed === 'string' ? allowed : always ? 'Always' : 'Allowed'}</span>`
|
||||
: locked('Not allowed')}</div>`;
|
||||
const m = ctx.membership;
|
||||
const level = (view: boolean, edit: boolean) => (edit ? 'Edit' : view ? 'View' : false);
|
||||
// Triage: "Edit", "View", "View · 2 of 5 pages" or "3 of 5 pages · 1 editable".
|
||||
const viewN = TRIAGE_AREAS.filter((a) => can(m, `triage.${a}.view`)).length;
|
||||
const editN = TRIAGE_AREAS.filter((a) => can(m, `triage.${a}.edit`)).length;
|
||||
const editable = TRIAGE_AREAS.filter((a) => !VIEW_ONLY_AREAS.has(a)).length;
|
||||
const pagesOf = `${viewN} of ${TRIAGE_AREAS.length} pages`;
|
||||
const triage = !firstTriageArea(m) ? false : editN === editable && viewN === TRIAGE_AREAS.length ? 'Edit' : !editN ? (viewN === TRIAGE_AREAS.length ? 'View' : `View · ${pagesOf}`) : `${pagesOf} · ${editN} editable`;
|
||||
const body = html`
|
||||
${pageHeader({ title: 'Overview', description: `${ctx.workspace.name} · You're a moderator` })}
|
||||
${attentionNotice}
|
||||
@@ -130,7 +138,9 @@ export function registerWorkspaceRoutes(app: FastifyInstance, web: Web): void {
|
||||
<div class="g-2-1">
|
||||
${latest}
|
||||
<div class="card"><div class="card-h"><div><h2>Your access</h2><div class="desc">Set by admins in Members & permissions.</div></div></div>
|
||||
<div>${accessRow('View tickets', true, true)}${accessRow('Act on tickets', act)}${accessRow('Contributor verifications', contribView)}</div></div>
|
||||
<div>${accessRow('View tickets', true, true)}${accessRow('Act on tickets', act)}${accessRow('Contributor verifications', contribView)}${accessRow('Search all issues', can(m, 'issues.view'))}${accessRow('Clean up files', can(m, 'files.manage'))}${accessRow('Server health', can(m, 'health.view'))}
|
||||
${accessRow('Apps & repositories', level(can(m, 'apps.view'), can(m, 'apps.edit')))}
|
||||
${accessRow('Triage', triage)}</div></div>
|
||||
</div>`;
|
||||
return web.render(reply, ctx, 'Overview', 'overview', body);
|
||||
}
|
||||
|
||||
+6
-5
@@ -13,7 +13,7 @@ import type { TriageEngine } from '../triage/engine.js';
|
||||
import { getDiscordConnection, getGitHubConnection, getPanel, listApps } from '../domain/store.js';
|
||||
import { UserFacingError, type Deps, type Role } from '../domain/types.js';
|
||||
import { getMembership, listMemberships, type Membership } from '../domain/workspaces.js';
|
||||
import { can, TRIAGE_AREA_NAMES, type Permission, type TriageArea } from '../domain/permissions.js';
|
||||
import { can, PAGE_AREA_NAMES, PAGE_AREAS, TRIAGE_AREA_NAMES, type PageArea, type Permission, type TriageArea } from '../domain/permissions.js';
|
||||
import { layout, simplePage, type PageContext, type SetupProgress } from './layout.js';
|
||||
import { loadSession, SESSION_COOKIE, takeFlash, type AuthContext } from './session.js';
|
||||
import { registerAuthRoutes } from './routes/auth.js';
|
||||
@@ -197,11 +197,12 @@ export async function buildServer(deps: Deps, processor: Processor, opts: { logg
|
||||
}
|
||||
const ctx = { ...web.pageContext(req, reply), workspace: membership.workspace, role: membership.role, membership, base: `/w/${membership.workspace.id}`, memberships: await listMemberships(deps.db, auth.user.id), progress: await computeProgress(deps, wid) };
|
||||
const scope = can(membership, 'contrib.view') ? 'the tickets inbox and contributor verifications' : 'the tickets inbox';
|
||||
// A Triage page: say which one, and what access it needs.
|
||||
const triage = /^triage\.(\w+)\.(view|edit)$/.exec(o.permission ?? '');
|
||||
const area = triage ? TRIAGE_AREA_NAMES[triage[1] as TriageArea] : null;
|
||||
// A page admins can open to moderators: say which one, and what access it needs.
|
||||
const grant = /^(?:(triage)\.)?(\w+)\.(view|edit)$/.exec(o.permission ?? '');
|
||||
const area = !grant ? null : grant[1] ? `Triage › ${TRIAGE_AREA_NAMES[grant[2] as TriageArea] ?? grant[2]}` : (PAGE_AREAS as readonly string[]).includes(grant[2]!) ? PAGE_AREA_NAMES[grant[2] as PageArea] : null;
|
||||
const viewPerm = grant ? (o.permission!.replace(/\.edit$/, '.view') as Permission) : null;
|
||||
const text = area
|
||||
? triage![2] === 'edit' && can(membership, `triage.${triage![1] as TriageArea}.view`) ? `You can see Triage › ${area}, but not change it. Ask an admin if you need Edit.` : `You don’t have access to Triage › ${area}. Ask an admin if you need it.`
|
||||
? grant![3] === 'edit' && can(membership, viewPerm!) ? `You can see ${area}, but not change it. Ask an admin if you need Edit.` : `You don’t have access to ${area}. Ask an admin if you need it.`
|
||||
: `Your role can see ${scope}. Ask an admin or the owner if you need more access.`;
|
||||
web.render(reply, ctx, 'No access', '', html`${pageHeader({ title: 'No access' })}
|
||||
<div class="card">${empty('lock', 'You don’t have access to this page', text, linkBtn(`/w/${membership.workspace.id}`, 'Go to overview'))}</div>`);
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import { afterAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { listApps } from '../src/domain/store.js';
|
||||
import { createInvite, setModeratorPageAccess, setModeratorTriageAccess } from '../src/domain/workspaces.js';
|
||||
import { form, get, makeAdmin, makeApp, makeWorkspace, resetDb, testDb, type Admin, type ConfiguredWorkspace, type TestEnv } from './helpers.js';
|
||||
|
||||
let env: TestEnv;
|
||||
let ws: ConfiguredWorkspace;
|
||||
let mod: Admin;
|
||||
const wid = () => ws.workspace.id;
|
||||
const w = () => `/w/${ws.workspace.id}`;
|
||||
const page = (url: string, who: Admin = mod) => env.server.inject({ method: 'GET', url: `${w()}${url}`, ...get(who) });
|
||||
const post = (url: string, fields: Record<string, string> = {}, who: Admin = mod) => env.server.inject({ method: 'POST', url: `${w()}${url}`, ...form(who, fields) });
|
||||
const pageAccess = async () => (await env.db.query('SELECT page_access, triage_access FROM workspace_members WHERE user_id = $1', [mod.user.id])).rows[0];
|
||||
|
||||
beforeEach(async () => {
|
||||
await resetDb();
|
||||
env = await makeApp();
|
||||
ws = await makeWorkspace(env);
|
||||
mod = await makeAdmin(env, 'mia');
|
||||
await env.server.inject({ method: 'POST', url: `/invite/${await createInvite(env.db, wid(), ws.owner.user.id, 'moderator')}`, ...form(mod) });
|
||||
});
|
||||
afterAll(async () => {
|
||||
await testDb().end();
|
||||
});
|
||||
|
||||
describe('Apps & repositories access for moderators', () => {
|
||||
it('starts with no access: locked in the sidebar, and the page says why', async () => {
|
||||
const overview = await page('');
|
||||
expect(overview.body).toContain('title="You don’t have access to Apps & repositories. Ask an admin if you need it."');
|
||||
expect(overview.body).not.toContain(`href="${w()}/apps"`);
|
||||
const res = await page('/apps');
|
||||
expect(res.statusCode).toBe(403);
|
||||
expect(res.body).toContain('You don’t have access to Apps & repositories. Ask an admin if you need it.');
|
||||
expect((await post('/apps', { name: 'Sneaky', repo_id: String(ws.repoIds[0]), enabled: '1' })).statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it('is set on the Members page next to the Triage pages, without touching them', async () => {
|
||||
await setModeratorTriageAccess(env.db, wid(), mod.user.id, { actions: 'view' });
|
||||
const members = await page('/members', ws.owner);
|
||||
expect(members.body).toContain('id="page-access"');
|
||||
expect(members.body).toContain(`name="apps" form="pg-${mod.user.id}"`);
|
||||
expect(members.body).toContain('Tickets › Triage');
|
||||
|
||||
const res = await env.server.inject({
|
||||
method: 'POST', url: `${w()}/members/${mod.user.id}/page-access`,
|
||||
headers: { ...form(ws.owner).headers, accept: 'application/json' },
|
||||
payload: new URLSearchParams({ _csrf: ws.owner.csrf, apps: 'view' }).toString(),
|
||||
});
|
||||
expect(res.json()).toEqual({ ok: true, message: 'mia: Apps & repositories → View' });
|
||||
expect(await pageAccess()).toEqual({ page_access: { apps: 'view' }, triage_access: { actions: 'view' } });
|
||||
expect((await page('/members', ws.owner)).body).toContain('Apps: view');
|
||||
// Only admins set it.
|
||||
expect((await post(`/members/${mod.user.id}/page-access`, { apps: 'edit' })).statusCode).toBe(403);
|
||||
await expect(setModeratorPageAccess(env.db, wid(), ws.owner.user.id, { apps: 'view' })).rejects.toThrow();
|
||||
});
|
||||
|
||||
it('View shows the apps without any way to change them', async () => {
|
||||
await setModeratorPageAccess(env.db, wid(), mod.user.id, { apps: 'view' });
|
||||
const app = ws.apps[0]!;
|
||||
const list = await page('/apps');
|
||||
expect(list.statusCode).toBe(200);
|
||||
expect(list.body).toContain(app.name);
|
||||
expect(list.body).toContain('View only');
|
||||
expect(list.body).toContain(`href="${w()}/apps" class="nav-item" aria-current="page"`);
|
||||
expect(list.body).not.toContain('Add app');
|
||||
expect(list.body).not.toContain(`/apps/${app.id}/edit`);
|
||||
expect(list.body).not.toContain('Remove app');
|
||||
|
||||
const edit = await page(`/apps/${app.id}/edit`);
|
||||
expect(edit.statusCode).toBe(403);
|
||||
expect(edit.body).toContain('You can see Apps & repositories, but not change it. Ask an admin if you need Edit.');
|
||||
for (const url of ['/apps/new', `/apps/labels?repo=${ws.repoIds[0]}`]) expect((await page(url)).statusCode, url).toBe(403);
|
||||
for (const url of [`/apps/${app.id}/toggle`, `/apps/${app.id}/delete`, `/apps/${app.id}/move`]) expect((await post(url)).statusCode, url).toBe(403);
|
||||
expect((await listApps(env.db, wid())).map((a) => [a.name, a.enabled])).toEqual(ws.apps.map((a) => [a.name, true]));
|
||||
});
|
||||
|
||||
it('Edit lets them add, change, hide and remove apps; GitHub, Discord and the panel stay with admins', async () => {
|
||||
await setModeratorPageAccess(env.db, wid(), mod.user.id, { apps: 'edit' });
|
||||
const list = await page('/apps');
|
||||
expect(list.body).toContain('Add app');
|
||||
expect(list.body).not.toContain('View only');
|
||||
expect(list.body).toContain('<div class="who-role">Moderator</div>');
|
||||
|
||||
expect((await page('/apps/new')).statusCode).toBe(200);
|
||||
const added = await post('/apps', { name: 'Tablet', repo_id: String(ws.repoIds[0]), enabled: '1' });
|
||||
expect(added.statusCode).toBe(302);
|
||||
const tablet = (await listApps(env.db, wid())).find((a) => a.name === 'Tablet')!;
|
||||
expect(tablet).toBeTruthy();
|
||||
// A repository outside the GitHub App is still refused.
|
||||
env.github.addInstallation(9999, 'someone-else', [{ id: 4242, name: 'secret-repo' }]);
|
||||
expect((await post('/apps', { name: 'Sneaky', repo_id: '4242', enabled: '1' })).statusCode).toBe(400);
|
||||
|
||||
await post(`/apps/${tablet.id}/toggle`);
|
||||
expect((await listApps(env.db, wid())).find((a) => a.id === tablet.id)!.enabled).toBe(false);
|
||||
await post(`/apps/${tablet.id}/delete`);
|
||||
expect((await listApps(env.db, wid())).some((a) => a.id === tablet.id)).toBe(false);
|
||||
|
||||
for (const url of ['/setup/github', '/setup/discord', '/tickets/panel', '/settings']) expect((await page(url)).statusCode, url).toBe(403);
|
||||
const overview = await page('');
|
||||
expect(overview.body).toMatch(/Apps & repositories<\/span><span class="locked">.*?Edit<\/span>/);
|
||||
});
|
||||
});
|
||||
@@ -40,7 +40,7 @@ describe('Triage access for moderators', () => {
|
||||
|
||||
it('is set page by page on the Members page, and saved right away', async () => {
|
||||
const members = await page('/members', ws.owner);
|
||||
expect(members.body).toContain('id="triage-access"');
|
||||
expect(members.body).toContain('id="page-access"');
|
||||
expect(members.body).toContain(`name="labels" form="tri-${mod.user.id}"`);
|
||||
|
||||
const res = await env.server.inject({
|
||||
|
||||
Reference in new issue
Block a user