diff --git a/src/db/database.ts b/src/db/database.ts index e79809e..2ab756f 100644 --- a/src/db/database.ts +++ b/src/db/database.ts @@ -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 { diff --git a/src/db/migrations/022_page_access.sql b/src/db/migrations/022_page_access.sql new file mode 100644 index 0000000..6d1480d --- /dev/null +++ b/src/db/migrations/022_page_access.sql @@ -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 '{}'; diff --git a/src/domain/permissions.ts b/src/domain/permissions.ts index 699aa77..8fbd1c1 100644 --- a/src/domain/permissions.ts +++ b/src/domain/permissions.ts @@ -8,6 +8,17 @@ export type AccessLevel = 'none' | 'view' | 'edit'; export const VIEW_ONLY_AREAS: ReadonlySet = new Set(['activity']); export const TRIAGE_AREA_NAMES: Record = { 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 = { apps: 'Apps & repositories' }; + +/** A moderator's level on a setup page (none when unset or unknown). */ +export function pageLevel(access: Partial> | 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> | null | undefined, area: TriageArea): AccessLevel { const v = access?.[area]; @@ -18,7 +29,8 @@ export function triageLevel(access: Partial> | 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>; + /** Per setup page (Apps & repositories): none, view or edit. */ + page_access: Partial>; } 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); diff --git a/src/domain/workspaces.ts b/src/domain/workspaces.ts index 2f007d8..91aa33c 100644 --- a/src/domain/workspaces.ts +++ b/src/domain/workspaces.ts @@ -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): 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): 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>): Promise { + 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, diff --git a/src/web/layout.ts b/src/web/layout.ts index 765f6dd..ccbeb46 100644 --- a/src/web/layout.ts +++ b/src/web/layout.ts @@ -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`${icon(name)}${label}${icon('lock', 14)} (admins only)`; +/** 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`${icon(name)}${label}${icon('lock', 14)} (${o.grantable ? 'no access' : 'admins only'})`; } 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; ${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 })} ${navItem(`${base}/tickets`, 'Tickets', 'ticket', a === 'tickets', attention)} ${can(access, 'contrib.view') ? navItem(`${base}/contributors`, 'Contributor Roles', 'award', a === 'contributors') : lockedNavItem('Contributor Roles', 'award')} diff --git a/src/web/public/app.css b/src/web/public/app.css index 36f98a3..2ea507c 100644 --- a/src/web/public/app.css +++ b/src/web/public/app.css @@ -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; } diff --git a/src/web/routes/apps.ts b/src/web/routes/apps.ts index c423c42..a19d323 100644 --- a/src/web/routes/apps.ts +++ b/src/web/routes/apps.ts @@ -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`${icon('circle-check', 16, 'ok')}`; }; const b = ctx.base; + const edit = can(ctx.membership, 'apps.edit'); const repoUse = new Map(); 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 }) : ''}
${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`
- + ${edit ? html`` : ''}${apps.map((a, i) => { const shared = repoUse.get(a.repo_id)! - 1; return html` @@ -113,7 +120,7 @@ export function registerAppRoutes(app: FastifyInstance, web: Web): void { - `; + ` : ''}`; })}
AppRepositoryTicketsContributor RolesExtra labelsActions
AppRepositoryTicketsContributor RolesExtra labelsActions
${ticketState(a)} ${a.contributor_enabled ? html`${icon('circle-check', 16, 'ok')}` : html`—`} ${a.labels.length ? html`
${a.labels.map((l) => labelTag(l))}
` : html`—`}
+ ${edit ? html`
${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}` })} -
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.
`} @@ -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 {
Helps members pick the right app. Up to 100 characters.
+ ${can(ctx.membership, 'manage') ? '' : html`
Repositories the GitHub App can access. Ask an admin if one is missing.
`} ${selectWrap(html``)}
- ${repos.length === 0 && !repoError ? html`
No repositories are shared with the GitHub App yet. Manage repository access.
` : ''} + ${repos.length === 0 && !repoError ? html`
No repositories are shared with the GitHub App yet. ${can(ctx.membership, 'manage') ? html`Manage repository access.` : 'Ask an admin to share them in GitHub setup.'}
` : ''}
Labels (optional)
Existing labels from the repository, added to every ticket for this app.
@@ -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.' }); diff --git a/src/web/routes/members.ts b/src/web/routes/members.ts index 04d848b..fe33372 100644 --- a/src/web/routes/members.ts +++ b/src/web/routes/members.ts @@ -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 = { + apps: 'Apps and their repositories.', +}; + /** What each Triage page covers, for the access table. */ const TRIAGE_AREA_DESC: Record = { 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`
-

Moderator access

New moderators start view-only. Moderators never see setup, panels or settings. Triage pages are set below.
+

Moderator access

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.
${mods.length ? html`${mods.map((m) => html`${permForm(m, '')}${permForm(m, 'm-')}`)}
@@ -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)} `; + const levelOptions = (levels: AccessLevel[], level: AccessLevel) => levels.map((l) => html``); 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``, { sm: true }); + return selectWrap(html``, { 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``, { 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``, { sm: true }); }; - const triageAccess = mods.length ? html`
-

Triage access

What each moderator can do in Tickets › Triage, page by page. View shows the page with every control turned off; Edit lets them change it. Moderators start with no access.
- ${mods.map((m) => html`${csrfField(ctx.csrf)}${csrfField(ctx.csrf)}`)} + const accessForms = (m: (typeof members)[number]) => html`${['', 'm-'].map((suffix) => html`${csrfField(ctx.csrf)}${csrfField(ctx.csrf)}`)}`; + const pageAccess = mods.length ? html`
+

Page access

Pages each moderator can open, and whether they can change them. View shows the page with every control turned off; Edit lets them change it. Moderators start with no access.
+ ${mods.map(accessForms)}
- ${TRIAGE_AREAS.map((a) => html``)} + + + ${PAGE_AREAS.map((a) => html``)}${TRIAGE_AREAS.map((a) => html``)} + ${mods.map((m) => html` - + ${PAGE_AREAS.map((a) => html``)} + ${TRIAGE_AREAS.map((a) => html``)} `)}
Moderator
All pages
Set every page at once.
${TRIAGE_AREA_NAMES[a]}
${TRIAGE_AREA_DESC[a]}
Moderator
${icon('boxes', 14)}General setup
${icon('ticket', 14)}Tickets › Triage
${PAGE_AREA_NAMES[a]}
${PAGE_AREA_DESC[a]}
All Triage pages
Set them all at once.
${TRIAGE_AREA_NAMES[a]}
${TRIAGE_AREA_DESC[a]}
${avatar(nameOf(m), 24, { src: discordAvatar(m) })}${nameOf(m)}${allSelect(m, '')}${pageSelect(m, a, '')}${allSelect(m, '')}${levelSelect(m, a, '')}
${mods.map((m) => html`
-
${avatar(nameOf(m), 24, { src: discordAvatar(m) })}${nameOf(m)}${allSelect(m, 'm-')}
+
${avatar(nameOf(m), 24, { src: discordAvatar(m) })}${nameOf(m)}
+
General setup
+ ${PAGE_AREAS.map((a) => setting(PAGE_AREA_NAMES[a], PAGE_AREA_DESC[a], pageSelect(m, a, 'm-')))} +
Tickets › Triage
+ ${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-')))}
`)}
-
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.
+
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.
` : ''; const mark = (v: string) => (v === 'yes' ? html`${icon('circle-check', 16, 'ok')}Yes` : v === 'maybe' ? html`If allowed` : html`—`); @@ -217,7 +238,7 @@ export function registerMemberRoutes(app: FastifyInstance, web: Web): void { ${pending}
${modAccess} - ${triageAccess} + ${pageAccess}
${icon('info')}What each role can do${icon('chevron-down', 16, 'chev')}
@@ -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); + 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) => { diff --git a/src/web/routes/triage-config.ts b/src/web/routes/triage-config.ts index 18acc6c..97e85f7 100644 --- a/src/web/routes/triage-config.ts +++ b/src/web/routes/triage-config.ts @@ -216,7 +216,7 @@ export function registerTriageConfigRoutes(app: FastifyInstance, web: Web): void ${csrfField(ctx.csrf)}
-

About your products

Claude reads this with every ticket. It already gets each app’s name, repository and description.
${can(ctx.membership, 'manage') ? linkBtn(`${ctx.base}/apps`, 'Edit apps', { size: 'sm', variant: 'ghost', trail: 'arrow-right' }) : ''}
+

About your products

Claude reads this with every ticket. It already gets each app’s name, repository and description.
${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' }) : ''}
${apps.length ? html`
    ${apps.map((a) => html`
  • ${a.name} ${a.repo_owner}/${a.repo_name}${a.description ? html` · ${a.description}` : html` · no description`}
  • `)}
` : html`

No apps yet.

`}
diff --git a/src/web/routes/workspace.ts b/src/web/routes/workspace.ts index 3c588f1..f9f7bed 100644 --- a/src/web/routes/workspace.ts +++ b/src/web/routes/workspace.ts @@ -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`
${label}${allowed - ? html`${icon('circle-check', 14, 'ok')}${always ? 'Always' : 'Allowed'}` + const accessRow = (label: string, allowed: boolean | string, always = false) => html`
${label}${allowed + ? html`${icon('circle-check', 14, 'ok')}${typeof allowed === 'string' ? allowed : always ? 'Always' : 'Allowed'}` : locked('Not allowed')}
`; + 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 {
${latest}

Your access

Set by admins in Members & permissions.
-
${accessRow('View tickets', true, true)}${accessRow('Act on tickets', act)}${accessRow('Contributor verifications', contribView)}
+
${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)}
`; return web.render(reply, ctx, 'Overview', 'overview', body); } diff --git a/src/web/server.ts b/src/web/server.ts index abf7a49..21fc870 100644 --- a/src/web/server.ts +++ b/src/web/server.ts @@ -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' })}
${empty('lock', 'You don’t have access to this page', text, linkBtn(`/w/${membership.workspace.id}`, 'Go to overview'))}
`); diff --git a/test/apps-access.test.ts b/test/apps-access.test.ts new file mode 100644 index 0000000..e164cb5 --- /dev/null +++ b/test/apps-access.test.ts @@ -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 = {}, 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('
Moderator
'); + + 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>.*?Edit<\/span>/); + }); +}); diff --git a/test/triage-access.test.ts b/test/triage-access.test.ts index da341d9..af2aedb 100644 --- a/test/triage-access.test.ts +++ b/test/triage-access.test.ts @@ -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({