From addf330b10210500a4c4fa42449c9686f7452e5d Mon Sep 17 00:00:00 2001 From: eust-w Date: Wed, 28 Oct 2026 12:07:08 +0800 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Add=20account=20types=20and=20enfor?= =?UTF-8?q?ce=20per-user=20wish=20permissions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Provide six account types and custom combinations of wish, code review, release and management permissions, applied on each authenticated request. - Enforce frontend-only accounts when submitting, answering, widening and reverting wishes; require every contributor to have full access before skipping backend code review. - Gate code review and release decisions by their specific permissions. - Rework member management to create and edit account types, permissions and project access, and reflect those permissions throughout the console. - Update the manual and architecture docs with permission tests and end-to-end coverage. Co-Authored-By: Claude Fable 5 --- apps/api/src/domain/control-plane.ts | 79 +++- apps/api/src/domain/github.ts | 5 +- apps/api/src/domain/local-accounts.ts | 131 ++++-- apps/api/src/domain/permissions.ts | 46 ++ apps/api/src/domain/releases.ts | 7 +- apps/api/src/http.ts | 11 +- apps/web/src/app/globals.css | 38 ++ apps/web/src/components/console-shell.tsx | 2 +- apps/web/src/features/dashboard.tsx | 12 +- apps/web/src/features/members.tsx | 511 +++++++++++++-------- apps/web/src/features/project-settings.tsx | 29 +- apps/web/src/features/projects.tsx | 38 +- apps/web/src/features/releases.tsx | 63 ++- apps/web/src/features/runs.tsx | 120 +++-- apps/web/src/lib/events.ts | 2 +- apps/web/src/lib/permissions.ts | 55 +++ apps/web/src/lib/types.ts | 18 +- apps/web/src/lib/waiting.ts | 2 +- docs/architecture.md | 10 +- docs/reference/repository-contract.md | 2 +- docs/user-manual.md | 107 +++-- packages/contracts/package.json | 1 + packages/contracts/src/index.ts | 48 +- packages/contracts/src/permissions.ts | 88 ++++ tests/console-bundle.test.ts | 4 +- tests/local-accounts.test.ts | 149 ++++-- tests/local-loop.test.ts | 180 +++++++- tests/permissions.test.ts | 38 ++ 28 files changed, 1350 insertions(+), 446 deletions(-) create mode 100644 apps/api/src/domain/permissions.ts create mode 100644 apps/web/src/lib/permissions.ts create mode 100644 packages/contracts/src/permissions.ts create mode 100644 tests/permissions.test.ts diff --git a/apps/api/src/domain/control-plane.ts b/apps/api/src/domain/control-plane.ts index 0bfdf1e..701738c 100644 --- a/apps/api/src/domain/control-plane.ts +++ b/apps/api/src/domain/control-plane.ts @@ -53,6 +53,7 @@ import { assertVerificationProfile, verificationPolicyDigest } from './verificat import { IntegrationLeases } from './integration-lease.js'; import { captureLesson, projectLessons } from './lessons.js'; import { describeProviderEvent } from './provider-events.js'; +import { backendDefined, personWishScope, requirePermission, wishScopeOf } from './permissions.js'; export const now = () => new Date().toISOString(); export function record(tenantId: string): Entity { @@ -364,6 +365,16 @@ export class ControlPlane { this.validateKey(key); return this.store.transaction(actor.tenantId, async tx => { const project = await projectAccess(tx, actor, projectId); + const scope = wishScopeOf(actor, project); + if (scope === 'none') throw new DomainError('WISH_FORBIDDEN', 'Your account cannot submit wishes', 403); + // Whoever may only wish for frontend changes gets frontend-only wishes. + const frontendOnly = backendDefined(project) && scope === 'frontend' ? true : data.frontendOnly; + if (frontendOnly && data.frontendOnly === false) + throw new DomainError( + 'FRONTEND_ONLY_ACCOUNT', + 'Your account may only wish for frontend changes; ask someone who may change backend code', + 403, + ); const localPoc = boundPocProject(project, this.env); if (localPoc && (data.sourceBranch || data.provider !== 'claude-code')) throw new DomainError( @@ -418,6 +429,7 @@ export class ControlPlane { reservedTokens: data.budget.maxTokens, usedTokens: 0, activeMilliseconds: 0, + ...(frontendOnly !== undefined ? { frontendOnly } : {}), ...(extras.revertOf ? { revertOf: extras.revertOf } : {}), } as Run; const blocked = startBlocker(provider, project); @@ -472,8 +484,22 @@ export class ControlPlane { return this.store.transaction(actor.tenantId, async tx => { const run = await must(tx, 'run', id); const project = await projectAccess(tx, actor, run.projectId); + // Adding to a requirement is wishing: not beyond what the person may wish for themselves. + if ( + data.action === 'answer' && + backendDefined(project) && + wishScopeOf(actor, project) === 'frontend' && + (!run.frontendOnly || data.allowBackend) + ) + throw new DomainError( + 'FRONTEND_ONLY_ACCOUNT', + data.allowBackend + ? 'Your account may only wish for frontend changes; someone who may change backend code widens the wish' + : 'This run may change backend code, and your account may only wish for frontend changes', + 403, + ); return idempotent(tx, `command:${actor.userId}:${id}:${key}`, data, async () => { - const result = await this.applyCommand(tx, run, project, data); + const result = await this.applyCommand(tx, run, project, data, actor.userId); if (data.allowBackend) await tx.event(id, 'run.scope', 'The wish may change backend code from now on.', { frontendOnly: false, @@ -497,6 +523,8 @@ export class ControlPlane { acceptanceCriteria?: string[]; allowBackend?: true; }, + /** Who adds to the requirement with an answer. */ + by?: string, ): Promise { const id = run.id; if (terminal(run)) throw new DomainError('TERMINAL_RUN', 'Submit a new wish to change a completed task'); @@ -550,6 +578,8 @@ export class ControlPlane { wish.revision += 1; wish.goal = `${wish.goal}\n\n${answer}`; if (data.allowBackend) run.frontendOnly = false; + if (by && by !== run.requestedBy && !run.contributors?.includes(by)) + run.contributors = [...(run.contributors ?? []), by]; if (data.acceptanceCriteria) wish.acceptanceCriteria = data.acceptanceCriteria; await tx.put('wish', wish); run.revision = wish.revision; @@ -615,9 +645,9 @@ export class ControlPlane { requireHuman(actor); requireRole(actor, ['owner', 'admin', 'developer']); this.validateKey(key); - const { original, integration, existing } = await this.store.read(actor.tenantId, async tx => { + const { original, integration, existing, project } = await this.store.read(actor.tenantId, async tx => { const original = await must(tx, 'run', id); - await projectAccess(tx, actor, original.projectId); + const project = await projectAccess(tx, actor, original.projectId); const integration = original.integratedCommit ? (await tx.list('evidence', { runId: id })).find( evidence => @@ -630,7 +660,7 @@ export class ControlPlane { const existing = (await tx.list('run', { projectId: original.projectId })).find( run => run.revertOf?.runId === id && !terminal(run), ); - return { original, integration, existing }; + return { original, integration, existing, project }; }); if (existing) return { wish_id: existing.wishId, run_id: existing.id, status_url: `/runs/${existing.id}` }; if (!original.integratedCommit) @@ -640,6 +670,13 @@ export class ControlPlane { 'REVERT_UNAVAILABLE', 'Where the target branch stood before this run integrated is not recorded; submit a wish that undoes the change instead', ); + // Only a frontend-only run is known to have left backend code alone. + if (backendDefined(project) && !original.frontendOnly && wishScopeOf(actor, project) === 'frontend') + throw new DomainError( + 'FRONTEND_ONLY_ACCOUNT', + 'This run may have changed backend code; ask someone who may change backend code to take it back', + 403, + ); const commit = original.integratedCommit.slice(0, 12); return this.submit( actor, @@ -653,6 +690,7 @@ export class ControlPlane { ], provider: original.provider, budget: { maxTokens: Math.min(original.budget.maxTokens, 300_000), maxMinutes: 60, maxRepairRounds: 3 }, + ...(backendDefined(project) ? { frontendOnly: Boolean(original.frontendOnly) } : {}), }, key, { @@ -690,8 +728,12 @@ export class ControlPlane { // A run from another branch also brings that branch's commits, which the change does not show. const touches = paths.length > 0 || (Boolean(run.sourceBranch) && Boolean(project.codeReview?.paths.length)); if (!touches) return { required: false as const }; - // Whoever may change backend code directly needs no review of their own change. - if (run.requestedBy && project.codeReview?.trustedMembers?.includes(run.requestedBy)) { + // A backend change needs no review when everyone who asked for it may merge backend code directly. + const people = [run.requestedBy, ...(run.contributors ?? [])].filter((person): person is string => + Boolean(person), + ); + const scopes = await Promise.all(people.map(person => personWishScope(tx, person, project))); + if (people.length && scopes.every(scope => scope === 'full')) { const recorded = (await tx.events(id)).some( event => event.type === 'code_review.skipped' && event.data?.sourceCommit === input.sourceCommit, ); @@ -699,8 +741,13 @@ export class ControlPlane { await tx.event( id, 'code_review.skipped', - `The change touches ${paths.length} backend path(s); whoever asked for it may change backend code directly, so it needs no review.`, - { sourceCommit: input.sourceCommit, requestedBy: run.requestedBy, paths: paths.slice(0, 50) }, + `The change touches ${paths.length} backend path(s); everyone who asked for it may change backend code directly, so it needs no review.`, + { + sourceCommit: input.sourceCommit, + requestedBy: run.requestedBy, + ...(run.contributors?.length ? { contributors: run.contributors } : {}), + paths: paths.slice(0, 50), + }, ); return { required: false as const }; } @@ -753,7 +800,7 @@ export class ControlPlane { */ async decideCodeReview(actor: Actor, id: string, input: unknown, key?: string) { requireHuman(actor); - requireRole(actor, ['owner', 'admin']); + requirePermission(actor, 'reviewCode'); const data = codeReviewDecisionInput.parse(input); this.validateKey(key); return this.store.transaction(actor.tenantId, async tx => { @@ -765,7 +812,8 @@ export class ControlPlane { ); if (!review || review.sourceCommit !== data.sourceCommit) throw new DomainError('REVIEW_STALE', 'The change under review changed; reload it and review again'); - if (isProduction(this.env) && review.requestedBy === actor.userId) + // Only someone who could have merged the change directly may approve their own, and nobody in production. + if (review.requestedBy === actor.userId && (isProduction(this.env) || wishScopeOf(actor, project) !== 'full')) throw new DomainError('SELF_REVIEW', 'Someone other than the requester reviews the change', 403); const who = actor.displayName ?? actor.userId; await tx.put('code_review', { @@ -786,10 +834,13 @@ export class ControlPlane { const waiting = run.status === 'waiting' && run.waitingReason === 'code_review'; if (data.decision === 'approve') return waiting ? this.applyCommand(tx, run, project, { action: 'resume' }) : run; - return this.applyCommand(tx, run, project, { - action: 'answer', - message: `代码审核未通过(${who}):${data.comment}`, - }); + return this.applyCommand( + tx, + run, + project, + { action: 'answer', message: `代码审核未通过(${who}):${data.comment}` }, + actor.userId, + ); }); }); } diff --git a/apps/api/src/domain/github.ts b/apps/api/src/domain/github.ts index 559c576..6c5170d 100644 --- a/apps/api/src/domain/github.ts +++ b/apps/api/src/domain/github.ts @@ -23,6 +23,7 @@ import { import type { Store, Transaction } from '../db/store.js'; import { executionLease, executionScope, must, projectAccess, record, setWaiting, touch } from './control-plane.js'; import { digest, requireHuman, requireRole } from './policy.js'; +import { requirePermission } from './permissions.js'; const createInput = z .object({ @@ -375,7 +376,7 @@ export class GitHubIntegration { } } async authorizeMerge(actor: Actor, id: string, input: { expectedHeadSha: string; expectedBaseSha: string }) { - requireRole(actor, ['owner', 'admin', 'deployer']); + requirePermission(actor, 'releases'); requireHuman(actor); const observed = await this.reconcilePullRequest(actor, id); return this.store.transaction(actor.tenantId, async tx => { @@ -407,7 +408,7 @@ export class GitHubIntegration { } async merge(actor: Actor, id: string) { if (actor.kind !== 'verifier') { - requireRole(actor, ['owner', 'admin', 'deployer']); + requirePermission(actor, 'releases'); requireHuman(actor); } const observed = await this.reconcilePullRequest(actor, id); diff --git a/apps/api/src/domain/local-accounts.ts b/apps/api/src/domain/local-accounts.ts index 92304b3..96ef8e7 100644 --- a/apps/api/src/domain/local-accounts.ts +++ b/apps/api/src/domain/local-accounts.ts @@ -1,13 +1,20 @@ import { randomBytes, randomInt, scryptSync, timingSafeEqual } from 'node:crypto'; import { + accountTypeOf, + accountTypes, DomainError, isProduction, localAccountInput, localAccountPatch, localLoginInput, + normalizePermissions, + roleFor, + rolePermissions, + type AccountType, type Actor, type Entity, type LocalAccountView, + type Permissions, type Project, type Role, } from '@wishforge/contracts'; @@ -19,7 +26,7 @@ import { requireHuman, requireRole } from './policy.js'; /** * A person of a local deployment, signing in with a password of their own. The web console * checks the password here and then calls the API with its local credential plus the person's - * account ID and password version, so each person acts with their own role. + * account ID and password version, so each person acts with their own permissions. */ interface LocalAccount extends Entity { username: string; @@ -29,6 +36,11 @@ interface LocalAccount extends Entity { /** Changes when the password is reset, which ends the person's existing sessions. */ passwordVersion: number; createdBy: string; + /** + * What the person may do; their role follows from it. Absent on accounts from before + * permissions, where the role alone decides. + */ + permissions?: Permissions; } /** The deployment's tenant for the local credential; see Authenticator.authenticate. */ @@ -51,32 +63,50 @@ function credential(password: string) { return { salt, passwordHash: hash(password, salt).toString('hex') }; } function view(account: LocalAccount, role: Role | undefined, projects: Project[]): LocalAccountView { - const own = projects.filter(project => project.memberIds.includes(account.id)); + const permissions = account.permissions + ? normalizePermissions(account.permissions) + : rolePermissions(role ?? 'viewer'); + const type = accountTypeOf(permissions); return { id: account.id, username: account.username, displayName: account.displayName, - role: role ?? 'viewer', + role: role ?? roleFor(permissions), active: Boolean(role), createdAt: account.createdAt, createdBy: account.createdBy, - projectIds: own.map(project => project.id), - backendProjectIds: own - .filter(project => project.codeReview?.trustedMembers?.includes(account.id)) - .map(project => project.id), + projectIds: projects.filter(project => project.memberIds.includes(account.id)).map(project => project.id), + permissions, + ...(type ? { type } : {}), }; } -/** A project where `userId` may, or may no longer, change backend code without a review. */ -function withBackend(project: Project, userId: string, backend: boolean): Project | undefined { - const policy = project.codeReview ?? { paths: [], exceptPaths: [] }; - const trusted = policy.trustedMembers ?? []; - if (trusted.includes(userId) === backend) return undefined; +/** An account type's permissions, or the ones given, as kept: managing includes everything else. */ +function granted(data: { type?: AccountType; permissions?: Permissions }): Permissions | undefined { + if (data.permissions) return normalizePermissions(data.permissions); + return data.type ? { ...accountTypes[data.type] } : undefined; +} +const samePermissions = (a: Permissions, b: Permissions) => + a.wish === b.wish && a.reviewCode === b.reviewCode && a.releases === b.releases && a.manage === b.manage; +/** + * The project with `userId` in it or not, as `member` says. A person with permissions of their own + * is no longer one of the project's trusted members: their account decides what they may change. + */ +function withMember(project: Project, userId: string, member: boolean): Project | undefined { + const present = project.memberIds.includes(userId); + const trusted = project.codeReview?.trustedMembers ?? []; + const wasTrusted = trusted.includes(userId); + if (present === member && !wasTrusted) return undefined; return { ...touch(project), - codeReview: { - ...policy, - trustedMembers: backend ? [...trusted, userId] : trusted.filter(member => member !== userId), - }, + memberIds: + present === member + ? project.memberIds + : member + ? [...project.memberIds, userId] + : project.memberIds.filter(id => id !== userId), + ...(wasTrusted + ? { codeReview: { ...project.codeReview!, trustedMembers: trusted.filter(id => id !== userId) } } + : {}), }; } @@ -125,6 +155,8 @@ export class LocalAccounts { if (members.length >= effectiveEntitlements(await tx.tenant()).limits.maxMembers) throw new DomainError('MEMBER_LIMIT', 'Tenant active-member allowance is exhausted', 429); const password = newPassword(); + const permissions = granted(data)!; + const role = roleFor(permissions); const account: LocalAccount = { ...record(actor.tenantId), id, @@ -133,31 +165,26 @@ export class LocalAccounts { ...credential(password), passwordVersion: 1, createdBy: actor.userId, + permissions, }; await tx.put('local_account', account); - await tx.putMembership({ userId: id, role: data.role, active: true }); + await tx.putMembership({ userId: id, role, active: true }); const projects: Project[] = []; for (const project of await tx.list('project')) { - if (data.projectIds && !data.projectIds.includes(project.id)) { - projects.push(project); - continue; - } - let next = project.memberIds.includes(id) - ? project - : { ...touch(project), memberIds: [...project.memberIds, id] }; - next = withBackend(next, id, data.backend) ?? next; - if (next !== project) await tx.put('project', next); - projects.push(next); + const next = withMember(project, id, !data.projectIds || data.projectIds.includes(project.id)); + if (next) await tx.put('project', next); + projects.push(next ?? project); } await tx.put('entitlement_event', { ...record(actor.tenantId), action: 'member.invited', actorId: actor.userId, targetSubject: id, - role: data.role, + role, + permissions, }); // The password is shown this once; only its hash is kept. - return { account: view(account, data.role, projects), password }; + return { account: view(account, role, projects), password }; }); } async update(actor: Actor, id: string, input: unknown) { @@ -166,22 +193,40 @@ export class LocalAccounts { return this.store.transaction(actor.tenantId, async tx => { const account = await must(tx, 'local_account', id); const current = (await tx.members()).find(member => member.userId === id && member.active); - const role = data.role ?? current?.role ?? 'viewer'; + const before = account.permissions + ? normalizePermissions(account.permissions) + : rolePermissions(current?.role ?? 'viewer'); + const permissions = granted(data); + const changed = Boolean(permissions && (!account.permissions || !samePermissions(permissions, before))); + const role = permissions ? roleFor(permissions) : (current?.role ?? roleFor(before)); const active = data.active ?? Boolean(current); - if (id === actor.userId && (!active || role !== current?.role)) - throw new DomainError('SELF_ACCOUNT_CHANGE', 'Ask another administrator to change your own role or access'); - const next = data.displayName ? { ...touch(account), displayName: data.displayName } : account; + const all = await tx.list('project'); + const moved = all.some( + project => data.projectIds && data.projectIds.includes(project.id) !== project.memberIds.includes(id), + ); + if (id === actor.userId && (!active || changed || moved)) + throw new DomainError( + 'SELF_ACCOUNT_CHANGE', + 'Ask another administrator to change your own permissions, projects or access', + ); + const next = + data.displayName || changed + ? { + ...touch(account), + ...(data.displayName ? { displayName: data.displayName } : {}), + ...(changed ? { permissions } : {}), + } + : account; if (next !== account) await tx.put('local_account', next); const projects: Project[] = []; - for (const project of await tx.list('project')) { - const changed = - data.backend !== undefined && project.memberIds.includes(id) - ? withBackend(project, id, data.backend) - : undefined; - if (changed) await tx.put('project', changed); - projects.push(changed ?? project); + for (const project of all) { + const member = data.projectIds ? data.projectIds.includes(project.id) : project.memberIds.includes(id); + // A project of theirs can still count them as trusted from before they had permissions. + const updated = data.projectIds || next.permissions ? withMember(project, id, member) : undefined; + if (updated) await tx.put('project', updated); + projects.push(updated ?? project); } - if (active !== Boolean(current) || role !== current?.role) { + if (active !== Boolean(current) || role !== current?.role || changed) { if (active && !current) { const members = (await tx.members()).filter(member => member.active); if (members.length >= effectiveEntitlements(await tx.tenant()).limits.maxMembers) @@ -190,10 +235,11 @@ export class LocalAccounts { await tx.putMembership({ userId: id, role, active }); await tx.put('entitlement_event', { ...record(actor.tenantId), - action: active ? 'member.role_changed' : 'member.disabled', + action: active ? (changed ? 'member.permissions_changed' : 'member.role_changed') : 'member.disabled', actorId: actor.userId, targetSubject: id, role, + ...(changed ? { permissions } : {}), }); } return view(next, active ? role : undefined, projects); @@ -260,6 +306,7 @@ export class LocalAccounts { kind: 'human', clientId: 'wishforge-web', displayName: account.displayName, + ...(account.permissions ? { permissions: normalizePermissions(account.permissions) } : {}), }; } } diff --git a/apps/api/src/domain/permissions.ts b/apps/api/src/domain/permissions.ts new file mode 100644 index 0000000..51175b6 --- /dev/null +++ b/apps/api/src/domain/permissions.ts @@ -0,0 +1,46 @@ +import { + DomainError, + normalizePermissions, + rolePermissions, + wishScopeIn, + type Actor, + type Entity, + type Permissions, + type Project, + type WishScope, +} from '@wishforge/contracts'; +import type { Transaction } from '../db/store.js'; + +const actions: Record<'reviewCode' | 'releases' | 'manage', string> = { + reviewCode: 'review code changes', + releases: 'approve, reject or roll back releases', + manage: 'manage this deployment', +}; +const trusted = (project: Project, userId: string) => Boolean(project.codeReview?.trustedMembers?.includes(userId)); +/** Whether the project says which code is backend; without that, every change is frontend code. */ +export const backendDefined = (project: Project) => Boolean(project.codeReview?.paths.length); + +/** What the actor may do: the permissions of their own account, or else what their role allows. */ +export function permissionsOf(actor: Actor): Permissions { + return actor.permissions ? normalizePermissions(actor.permissions) : rolePermissions(actor.role); +} +export function requirePermission(actor: Actor, permission: keyof typeof actions) { + if (!permissionsOf(actor)[permission]) + throw new DomainError('FORBIDDEN', `Your account cannot ${actions[permission]}`, 403); +} +/** What the actor may wish for in the project. */ +export function wishScopeOf(actor: Actor, project: Project): WishScope { + return wishScopeIn(permissionsOf(actor), Boolean(actor.permissions), trusted(project, actor.userId)); +} +/** + * What a person may wish for in the project now, for a decision made on their behalf (whether + * their change needs a review): nothing once they no longer belong to the deployment. + */ +export async function personWishScope(tx: Transaction, userId: string, project: Project): Promise { + const role = await tx.membership(userId); + if (!role) return 'none'; + const own = userId.startsWith('local:') + ? (await tx.get('local_account', userId))?.permissions + : undefined; + return wishScopeIn(own ?? rolePermissions(role), Boolean(own), trusted(project, userId)); +} diff --git a/apps/api/src/domain/releases.ts b/apps/api/src/domain/releases.ts index 7658bc9..eeb9269 100644 --- a/apps/api/src/domain/releases.ts +++ b/apps/api/src/domain/releases.ts @@ -33,6 +33,7 @@ import { } from './control-plane.js'; import { captureLesson } from './lessons.js'; import { digest, releaseRisk, requireRole, requireHuman } from './policy.js'; +import { requirePermission } from './permissions.js'; import { applicationUrlFor, assertApplicationConfigured, assertApplicationAccepted } from './application-access.js'; import { assertVerificationProfile, verificationPolicyDigest } from './verification-policy.js'; @@ -276,7 +277,7 @@ export class Releases { } async request(actor: Actor, input: unknown, key?: string) { - requireRole(actor, ['owner', 'admin', 'deployer']); + requirePermission(actor, 'releases'); const data = releaseInput.parse(input); return this.store.transaction(actor.tenantId, async tx => { const run = await must(tx, 'run', data.runId); @@ -431,7 +432,7 @@ export class Releases { return { run, environment, project }; } async decide(actor: Actor, id: string, input: { decision: string; bindingDigest: string }) { - requireRole(actor, ['owner', 'admin', 'deployer']); + requirePermission(actor, 'releases'); requireHuman(actor); if (!['approve', 'reject'].includes(input.decision)) throw new DomainError('INVALID_DECISION', 'Choose approve or reject', 400); @@ -657,7 +658,7 @@ export class Releases { }; } async rollback(actor: Actor, id: string, key?: string) { - requireRole(actor, ['owner', 'admin', 'deployer']); + requirePermission(actor, 'releases'); requireHuman(actor); return this.store.transaction(actor.tenantId, async tx => { const release = await must(tx, 'release', id); diff --git a/apps/api/src/http.ts b/apps/api/src/http.ts index 1d318cf..1d5484f 100644 --- a/apps/api/src/http.ts +++ b/apps/api/src/http.ts @@ -45,6 +45,7 @@ import { Entitlements, requireCapacity } from './domain/entitlements.js'; import { requireRole, requireHuman } from './domain/policy.js'; import { configuredVerificationProfiles, selectVerificationProfile } from './domain/verification-policy.js'; import { LocalAccounts, localAccountsEnabled } from './domain/local-accounts.js'; +import { permissionsOf } from './domain/permissions.js'; import { WishRefiner } from './domain/wish-refiner.js'; import { notificationsConfigured } from './domain/notifications.js'; @@ -183,7 +184,15 @@ export class ApiController { constructor(@Inject(Services) private s: Services) {} @Get('identity') identity(@Req() req: AuthRequest) { const { userId, role, kind, displayName } = req.actor; - return ok({ userId, role, kind, ...(displayName ? { displayName } : {}) }); + return ok({ + userId, + role, + kind, + ...(displayName ? { displayName } : {}), + permissions: permissionsOf(req.actor), + // Permissions of one's own account apply as they are; a role's can be raised by a project. + permissionSource: req.actor.permissions ? 'account' : 'role', + }); } /** What this deployment offers, so the console shows only what works here. */ @Get('capabilities') capabilities(@Req() req: AuthRequest) { diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.css index 721cc8b..401f5af 100644 --- a/apps/web/src/app/globals.css +++ b/apps/web/src/app/globals.css @@ -2995,3 +2995,41 @@ ul.criteria-choices { line-height: 1.7; color: var(--muted); } +.type-options { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); + gap: 8px; +} +.permission-tags { + display: flex; + flex-wrap: wrap; + gap: 5px; +} +.permission-details .permission-wish { + display: flex; + align-items: center; + gap: 10px; +} +.permission-details .permission-wish select { + min-height: 34px; + padding: 5px 10px; + font-size: 13px; + width: auto; +} +.permission-matrix td, +.permission-matrix th { + vertical-align: top; +} +.permission-matrix td:nth-child(n + 3), +.permission-matrix th:nth-child(n + 3) { + text-align: center; + white-space: nowrap; +} +fieldset:disabled .scope-option, +fieldset:disabled label { + cursor: not-allowed; + opacity: 0.65; +} +.member-scopes { + font-size: 13px; +} diff --git a/apps/web/src/components/console-shell.tsx b/apps/web/src/components/console-shell.tsx index c02edf1..6f7b8ba 100644 --- a/apps/web/src/components/console-shell.tsx +++ b/apps/web/src/components/console-shell.tsx @@ -31,7 +31,7 @@ const navigation = [ ['/providers', '执行器', Settings2], ['/agent', 'Agent 配置', Bot], ['/usage', '用量', BarChart3], - ['/members', '成员', Users], + ['/members', '成员与权限', Users], ] as const; export function ConsoleShell({ children }: { children: ReactNode }) { const pathname = usePathname(); diff --git a/apps/web/src/features/dashboard.tsx b/apps/web/src/features/dashboard.tsx index 1bd7195..54c3b5b 100644 --- a/apps/web/src/features/dashboard.tsx +++ b/apps/web/src/features/dashboard.tsx @@ -6,6 +6,7 @@ import { resourceState } from '@/lib/readiness'; import type { Dashboard } from '@/lib/types'; import { ButtonLink, EmptyState, ErrorNotice, Loading, PageHeader, Panel } from '@/components/ui'; import { RunTable } from '@/components/run-table'; +import { useMayWish } from '@/lib/permissions'; const journey = [ ['许愿与澄清', '将想法转化为可执行的任务,与 Agent 一起澄清细节。'], ['独立工作区', '在独立任务分支实现代码,按环境配置完成构建与验证。'], @@ -14,6 +15,7 @@ const journey = [ ['部署与观察', '部署到目标环境,并持续观察运行状态。'], ]; export function DashboardView() { + const mayWish = useMayWish(); const { data: cachedData, error, isLoading, isValidating, mutate } = useResource('/dashboard', 10000); const data = error && [401, 403].includes(error.status) ? undefined : cachedData; const connectionState = resourceState(Boolean(data), Boolean(error), isValidating); @@ -53,10 +55,12 @@ export function DashboardView() { title="工作概览" description="从一句愿望,到有证据的交付。" action={ - - - 提交愿望 - + mayWish ? ( + + + 提交愿望 + + ) : undefined } /> {error ? ( diff --git a/apps/web/src/features/members.tsx b/apps/web/src/features/members.tsx index 4eea3aa..e6ab229 100644 --- a/apps/web/src/features/members.tsx +++ b/apps/web/src/features/members.tsx @@ -1,8 +1,17 @@ 'use client'; import { useState } from 'react'; -import { Copy, KeyRound, Plus, UserRound } from 'lucide-react'; +import { Copy, KeyRound, Pencil, Plus, UserRound } from 'lucide-react'; +import { + accountTypeNames, + accountTypeOf, + accountTypes, + normalizePermissions, + wishScopes, + type Permissions, +} from '@wishforge/contracts/permissions'; import { formatTime, messageOf, mutateApi, useResource } from '@/lib/api'; -import type { Identity, LocalAccount, Project, Role } from '@/lib/types'; +import type { Identity, LocalAccount, Project } from '@/lib/types'; +import { accountTypeLabels, permissionPhrases, typeName, wishScopeLabels } from '@/lib/permissions'; import { Button, EmptyState, @@ -17,32 +26,6 @@ import { Status, } from '@/components/ui'; -export const roleLabels: Record = { - owner: '所有者', - admin: '管理员', - developer: '开发者', - deployer: '部署者', - viewer: '只读', -}; -const assignable: Role[] = ['admin', 'developer', 'deployer', 'viewer']; -/** What code a person may change directly; which paths are backend code is each project's setting. */ -const codeScopes = { - frontend: '仅前端(改后端要审核)', - backend: '前端和后端', -} as const; -function codeScope(account: LocalAccount): keyof typeof codeScopes | 'mixed' | undefined { - if (!account.projectIds.length) return undefined; - if (!account.backendProjectIds.length) return 'frontend'; - return account.backendProjectIds.length === account.projectIds.length ? 'backend' : 'mixed'; -} -const roleHints: Record = { - owner: '本机服务的维护者,拥有全部权限', - admin: '管理成员、项目设置、预算;可以审核代码、审批发布', - developer: '提交愿望、继续或暂停运行、补充需求、撤销改动', - deployer: '审批和回滚发布', - viewer: '只能查看', -}; - /** Shows a password once, for the administrator to hand over; it is not kept anywhere readable. */ function PasswordOnce({ title, password, onClose }: { title: string; password: string; onClose: () => void }) { const [copied, setCopied] = useState(false); @@ -73,15 +56,244 @@ function PasswordOnce({ title, password, onClose }: { title: string; password: s ); } -/** Everyone signs in with an account of their own, so the system knows who did what. */ +/** Every account type next to what it may do. */ +function PermissionMatrix() { + const mark = (allowed: boolean) => (allowed ? '✓' : '—'); + return ( +
+ + + + + + + + + + + + {accountTypeNames.map(type => { + const permissions = accountTypes[type]; + return ( + + + + + + + + ); + })} + +
账户类型许愿审核代码审批发布管理
+ {accountTypeLabels[type].name} +
{accountTypeLabels[type].hint}
+
{wishScopeLabels[permissions.wish]}{mark(permissions.reviewCode)}{mark(permissions.releases)}{mark(permissions.manage)}
+
+ ); +} +function Phrases({ permissions }: { permissions: Permissions }) { + return ( +
+ {permissionPhrases(permissions).map(phrase => ( + + {phrase} + + ))} +
+ ); +} +const sameSet = (a: string[], b: string[]) => a.length === b.length && a.every(item => b.includes(item)); +const samePermissions = (a: Permissions, b: Permissions) => + a.wish === b.wish && a.reviewCode === b.reviewCode && a.releases === b.releases && a.manage === b.manage; + +/** + * Adding an account, or changing one: an account type fills in the permissions, which can then be + * adjusted one by one. Administrators cannot change their own permissions or projects. + */ +function AccountForm({ + account, + projects, + self, + onClose, + onSaved, +}: { + account?: LocalAccount; + projects: Project[]; + self: boolean; + onClose: () => void; + onSaved: (created?: { account: LocalAccount; password: string }) => Promise; +}) { + const [username, setUsername] = useState(''); + const [displayName, setDisplayName] = useState(account?.displayName ?? ''); + const [permissions, setPermissions] = useState(account?.permissions ?? { ...accountTypes.frontend }); + const [projectIds, setProjectIds] = useState(account?.projectIds ?? projects.map(project => project.id)); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(''); + const shown = normalizePermissions(permissions); + const type = accountTypeOf(shown); + const change = (next: Partial) => setPermissions(normalizePermissions({ ...permissions, ...next })); + async function save(event: React.FormEvent) { + event.preventDefault(); + setBusy(true); + setError(''); + try { + if (!account) { + const created = await mutateApi<{ account: LocalAccount; password: string }>('/local-accounts', { + username: username.trim(), + displayName: displayName.trim(), + permissions: shown, + projectIds, + }); + await onSaved(created); + } else { + // Only what changed: an administrator may rename themselves, nothing more. + const patch = { + ...(displayName.trim() !== account.displayName ? { displayName: displayName.trim() } : {}), + ...(!samePermissions(shown, account.permissions) ? { permissions: shown } : {}), + ...(!sameSet(projectIds, account.projectIds) ? { projectIds } : {}), + }; + if (Object.keys(patch).length) + await mutateApi(`/local-accounts/${encodeURIComponent(account.id)}`, patch, 'PATCH'); + await onSaved(); + } + } catch (failure) { + setError(messageOf(failure)); + } finally { + setBusy(false); + } + } + return ( + +
+ {account ? null : ( + + setUsername(event.target.value.toLowerCase())} + /> + + )} + + setDisplayName(event.target.value)} /> + + {self ? 不能修改自己的权限和项目,请让另一位管理员修改。 : null} +
+ 账户类型 +
+ {accountTypeNames.map(name => ( + + ))} +
+
+
+ 具体权限{type ? '' : '(自定义)'} + + + + +
+ {projects.length ? ( +
+ 可以进入的项目 + {projects.map(project => ( + + ))} +
+ ) : null} +

+ 哪些代码算后端,在各项目的「项目设置 · 代码权限」里定义;项目没有定义时,所有代码都算前端。 +

+ +
+ + +
+ +
+ ); +} + +/** Everyone signs in with an account of their own; its type says what they may do. */ export function MembersView() { const identity = useResource('/identity'); - const manager = identity.data && ['owner', 'admin'].includes(identity.data.role); + const manager = Boolean(identity.data?.permissions?.manage); const accounts = useResource(manager ? '/local-accounts' : null, 30000); const projects = useResource(manager ? '/projects' : null); - const [adding, setAdding] = useState(false); - const [form, setForm] = useState({ username: '', displayName: '', role: 'developer' as Role, backend: false }); - const [projectIds, setProjectIds] = useState(); + const [editing, setEditing] = useState(); const [password, setPassword] = useState<{ title: string; value: string }>(); const [resetting, setResetting] = useState(); const [busy, setBusy] = useState(''); @@ -100,15 +312,16 @@ export function MembersView() { setBusy(''); } } - const chosen = projectIds ?? projects.data?.map(project => project.id) ?? []; + const projectNames = (ids: string[]) => + ids.map(id => projects.data?.find(project => project.id === id)?.name ?? id.slice(0, 8)).join('、'); return ( <> setAdding(true)}> + @@ -117,89 +330,72 @@ export function MembersView() { /> {identity.error ? ( void identity.mutate()} /> - ) : identity.isLoading ? ( + ) : identity.isLoading || !identity.data ? ( ) : !manager ? ( - 只有所有者或管理员可以管理成员。你的角色是「{roleLabels[identity.data!.role]}」。 + +

+ 你的账户类型是「{typeName(identity.data.permissions)}」。只有管理员可以添加成员和分配权限。 +

+ +
) : (

- 本机管理员(凭据文件里的账号)是所有者,不在下面的列表里。停用的账号立即无法再操作;重置密码会让对方已登录的会话失效。「代码权限」为「仅前端」的人改到后端代码时,改动要先经所有者或管理员审核才能合入;哪些路径算后端代码,在项目设置的「代码权限」里定义。 + 停用的账号立即无法再操作;重置密码会让对方已登录的会话失效。改了账户类型或权限,对方的下一个操作就按新权限执行。

{accounts.error ? ( void accounts.mutate()} /> ) : accounts.isLoading ? ( - ) : accounts.data?.length ? ( + ) : (
- - + + + - - {accounts.data.map(account => ( + + + + + + + + + {accounts.data?.map(account => ( + - -
成员角色代码权限账户类型能做什么项目 状态创建 操作
+ 本机管理员 +
凭据文件里的账号
+
管理员 + + 全部项目 + + 不能在这里修改
{account.displayName} -
{account.username}
+
+ {account.username} · {formatTime(account.createdAt)} 创建 +
{typeName(account.permissions)} - + - {codeScope(account) ? ( - + + {account.projectIds.length ? ( + projectNames(account.projectIds) ) : ( - 没有项目 + 无 )} @@ -208,9 +404,12 @@ export function MembersView() { label={account.active ? '可用' : '已停用'} /> {formatTime(account.createdAt)}
+
- ) : ( + )} + {accounts.data && !accounts.data.length ? ( } title="还没有成员账号" - description="添加成员后,把生成的密码交给对方,对方就能用自己的账号登录。" + description="添加成员并选好账户类型,把生成的密码交给对方,对方就能用自己的账号登录。" /> - )} - {!adding && !resetting ? : null} -
- {(Object.keys(roleLabels) as Role[]).map(role => ( -
-
{roleLabels[role]}
-
{roleHints[role]}
-
- ))} -
+ ) : null} + {!editing && !resetting ? : null}
)} - {adding ? ( - setAdding(false)}> -
{ - event.preventDefault(); - void act('create', () => - mutateApi<{ account: LocalAccount; password: string }>('/local-accounts', { - username: form.username.trim(), - displayName: form.displayName.trim(), - role: form.role, - projectIds: chosen, - backend: form.backend, - }), - ).then(created => { - if (!created) return; - setAdding(false); - setForm({ username: '', displayName: '', role: 'developer', backend: false }); - setProjectIds(undefined); - setPassword({ title: `${created.account.displayName} 的初始密码`, value: created.password }); - }); - }} - > - - setForm({ ...form, username: event.target.value.toLowerCase() })} - /> - - - setForm({ ...form, displayName: event.target.value })} - /> - - - - - - - - {projects.data?.length ? ( -
- 可以进入的项目 - {projects.data.map(project => ( - - ))} -
- ) : null} - -
- - -
- -
+ {identity.data ? ( + +

+ 添加或编辑成员时选一个类型,再按需要单独调整某项权限(调整后显示为「自定义」)。许愿能不能改后端,只看「许愿」这一项;哪些代码算后端,在各项目的「项目设置 + · 代码权限」里定义。 +

+ +
+ ) : null} + {editing && projects.data ? ( + setEditing(undefined)} + onSaved={async created => { + setEditing(undefined); + await accounts.mutate(); + if (created) setPassword({ title: `${created.account.displayName} 的初始密码`, value: created.password }); + }} + /> ) : null} {resetting ? ( ('/local-accounts'); + // Where people have accounts of their own, their accounts say what they may change; elsewhere + // the project lets people merge backend changes directly. + const capabilities = useResource<{ localAccounts: boolean }>('/capabilities'); + const accounts = useResource(capabilities.data?.localAccounts ? '/local-accounts' : null); const nameOf = (userId: string) => accounts.data?.find(account => account.id === userId)?.displayName ?? personName(userId); const [wishRules, setWishRules] = useState(project.wishRules ?? ''); @@ -233,7 +236,7 @@ export function ProjectSettings({

代码权限

- 改到「后端代码」的运行,验证通过后先停在「等待代码审核」,所有者或管理员批准后才合入;提交人在下面「可以直接改后端代码的人」里时不用审核。前端与其他放行的代码,验证通过就合入。 + 在这里划出哪些代码算后端。只能改前端的人碰不到它;其他人改到它时,有「直接合入」权限的验证通过就合入,没有的先停在「等待代码审核」,由有「审核代码」权限的人批准。前端与其他放行的代码,验证通过就合入。

- {project.memberIds?.length ? ( + {capabilities.data?.localAccounts ? ( +
+ 谁能改什么 + {(project.memberIds ?? []).map(userId => { + const account = accounts.data?.find(candidate => candidate.id === userId); + return ( + + {account?.displayName ?? personName(userId)}: + {account + ? `${typeName(account.permissions)} · ${wishScopeLabels[account.permissions.wish]}${account.active ? '' : '(已停用)'}` + : userId === '11111111-1111-4111-8111-111111111111' + ? `管理员 · ${wishScopeLabels.full}` + : '按角色'} + + ); + })} + 每个人能许愿改什么,在「成员与权限」页按人设置。 +
+ ) : project.memberIds?.length ? (
可以直接改后端代码的人 {project.memberIds.map(userId => ( diff --git a/apps/web/src/features/projects.tsx b/apps/web/src/features/projects.tsx index 0142132..6423cd3 100644 --- a/apps/web/src/features/projects.tsx +++ b/apps/web/src/features/projects.tsx @@ -4,7 +4,7 @@ import Link from 'next/link'; import { useRouter } from 'next/navigation'; import { ArrowRight, ArrowUpRight, FolderGit2, GitBranch, Laptop, Plus, Search, Settings2 } from 'lucide-react'; import { formatTime, messageOf, mutateApi, safeUrl, useResource } from '@/lib/api'; -import type { IdeBranch, Project, Run, Workspace } from '@/lib/types'; +import type { IdeBranch, Identity, Project, Run, Workspace } from '@/lib/types'; import { Button, ButtonLink, @@ -166,6 +166,8 @@ function CreateProject({ onClose, onCreated }: { onClose: () => void; onCreated: ); } export function ProjectView({ id }: { id: string }) { + const identity = useResource('/identity'); + const mayWish = identity.data?.permissions?.wish !== 'none'; const projects = useResource('/projects'); const runs = useResource(`/runs?project=${id}`, 10000); const workspaces = useResource(`/projects/${id}/workspaces`, 10000); @@ -221,14 +223,18 @@ export function ProjectView({ id }: { id: string }) { back={{ href: '/projects', label: '项目空间' }} action={
- - - - 提交愿望 - + {identity.data?.permissions?.manage ? ( + + ) : null} + {mayWish ? ( + + + 提交愿望 + + ) : null}
} /> @@ -279,7 +285,11 @@ export function ProjectView({ id }: { id: string }) { (放行 {project.codeReview.exceptPaths.join('、')}) ) : null} - 的改动先审核再合入;{project.codeReview.trustedMembers?.length ?? 0} 人可以直接改后端 + 算后端代码:只能改前端的人碰不到它,其他人改到它时按各自的权限直接合入或先审核(见 + + 成员与权限 + + ) ) : ( '不区分前后端,验证通过后直接合入' @@ -317,9 +327,11 @@ export function ProjectView({ id }: { id: string }) { {branch.commit.slice(0, 7)} · {formatTime(branch.updatedAt)} - - 提交愿望合入 - + {mayWish ? ( + + 提交愿望合入 + + ) : null} ))} diff --git a/apps/web/src/features/releases.tsx b/apps/web/src/features/releases.tsx index f634efd..58cd04a 100644 --- a/apps/web/src/features/releases.tsx +++ b/apps/web/src/features/releases.tsx @@ -3,7 +3,7 @@ import Link from 'next/link'; import { useState } from 'react'; import { ArrowRight, ArrowUpRight, Box, Check, ChevronDown, RotateCcw, ShieldCheck, X } from 'lucide-react'; import { formatTime, messageOf, mutateApi, shortId, safeUrl, useResource } from '@/lib/api'; -import type { Environment, Release } from '@/lib/types'; +import type { Environment, Identity, Release } from '@/lib/types'; import { browserId } from '@/lib/browser-id'; import { riskReasonLabel } from '@/lib/risk'; import { personName } from '@/lib/people'; @@ -45,6 +45,9 @@ function releaseAccessUrl(release: Release) { return release.status === 'healthy' ? safeUrl(release.deliveryUrl) : undefined; } export function ReleasesView() { + const identity = useResource('/identity'); + // Approving, rejecting and rolling back is for whoever may decide on releases; anyone may read a review. + const decider = Boolean(identity.data?.permissions?.releases); const { data, error, isLoading, mutate } = useResource('/releases', 7000); const environments = useResource('/environments'); const environmentName = (id: string) => environments.data?.find(environment => environment.id === id)?.name ?? id; @@ -106,7 +109,7 @@ export function ReleasesView() { ) : null} - {rollbackable(release) ? ( + {decider && rollbackable(release) ? ( - - + {decider ? ( + <> + + +
+ + +
+ + ) : ( + 等待有「审批发布」权限的人批准或拒绝。 + )} ); diff --git a/apps/web/src/features/runs.tsx b/apps/web/src/features/runs.tsx index cfad482..38b9873 100644 --- a/apps/web/src/features/runs.tsx +++ b/apps/web/src/features/runs.tsx @@ -59,9 +59,11 @@ import { eventLabel } from '@/lib/events'; import { browserId } from '@/lib/browser-id'; import { credentialSourceLabel, initialWishProvider, wishProviderReady } from '@/lib/readiness'; import { personName } from '@/lib/people'; +import { mayWishBackend, useMayWish, wishScopeFor } from '@/lib/permissions'; import type { CodeReview } from '@/lib/types'; export function RunsView() { + const mayWish = useMayWish(); const runs = useResource('/runs', 5000); const projects = useResource('/projects'); const [search, setSearch] = useState(''); @@ -83,10 +85,12 @@ export function RunsView() { title="运行记录" description="从意图到验收,查看每一次执行的完整轨迹。" action={ - - - 提交愿望 - + mayWish ? ( + + + 提交愿望 + + ) : undefined } /> {runs.error ? void runs.mutate()} /> : null} @@ -326,12 +330,13 @@ function frontendArea(policy: { paths: string[]; exceptPaths: string[] }) { /** Whether a wish may change backend code, where the project says which code that is. */ function ScopeChoice({ policy, - backendAllowed, + scope, frontendOnly, onChange, }: { policy: { paths: string[]; exceptPaths: string[] }; - backendAllowed: boolean; + /** What the person may wish for: only frontend changes leaves them nothing to choose. */ + scope: 'frontend' | 'review' | 'full'; frontendOnly: boolean; onChange: (frontendOnly: boolean) => void; }) { @@ -341,17 +346,27 @@ function ScopeChoice({ title: '只改前端', detail: `${frontendArea(policy)}。改到后端代码时,平台会把这些改动恢复原样,让 Agent 只改前端重做。`, }, - { - value: false, - title: '前端和后端', - detail: backendAllowed - ? '可以改后端代码。你有这个项目的后端权限,验证通过就直接合入。' - : '可以改后端代码。你没有这个项目的后端权限,改到后端代码时,验证通过后要所有者或管理员审核才合入。', - }, + ...(scope === 'frontend' + ? [] + : [ + { + value: false, + title: '前端和后端', + detail: + scope === 'full' + ? '可以改后端代码。你的账户可以直接合入,验证通过就合入。' + : '可以改后端代码。你的账户改到后端时,验证通过后要有「审核代码」权限的人批准才合入。', + }, + ]), ]; return (
代码范围 + {scope === 'frontend' ? ( + + 你的账户只能许愿改前端;需要改后端时,请有后端权限的人提交,或让管理员调整你的账户类型。 + + ) : null} {options.map(option => (