diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.ts index 970a4f0..4294fbe 100644 --- a/apps/api/src/auth.ts +++ b/apps/api/src/auth.ts @@ -2,6 +2,7 @@ import { resolveGatewayTarget } from './domain/gateway-target.js'; import { createRemoteJWKSet, jwtVerify, type JWTPayload } from 'jose'; import { DomainError, type Actor, isProduction, type Run, type RunnerRegistration } from '@wishforge/contracts'; import { currentGeneration, sameSecret } from './domain/policy.js'; +import { LOCAL_TENANT, LocalAccounts } from './domain/local-accounts.js'; import type { Store } from './db/store.js'; import { ServiceTokens } from './service-tokens.js'; import { dispatchTenants } from './tenants.js'; @@ -19,6 +20,11 @@ function profile(payload: JWTPayload): Pick { }; } +/** The person a local web console signed in, from its request headers; see Authenticator.authenticate. */ +export function localUser(header: (name: string) => string | undefined) { + return { user: header('X-WishForge-Local-User'), version: header('X-WishForge-Local-Version') }; +} + export class Authenticator { private jwks; constructor( @@ -46,10 +52,18 @@ export class Authenticator { if (isProduction(env) && env.WF_DEV_AUTH_TOKEN) throw new Error('Development authentication cannot be configured in production'); } - async authenticate(authorization?: string): Promise { + /** + * `local` names the person a local deployment's web console signed in, with their password + * version; it counts only together with the console's local credential. + */ + async authenticate(authorization?: string, local?: { user?: string; version?: string }): Promise { if (!authorization?.startsWith('Bearer ')) throw new DomainError('UNAUTHENTICATED', 'Sign in to continue', 401); const token = authorization.slice(7); if (!isProduction(this.env) && this.env.WF_DEV_AUTH_TOKEN && sameSecret(token, this.env.WF_DEV_AUTH_TOKEN)) { + if (local?.user) + return this.store.read(LOCAL_TENANT, tx => + new LocalAccounts(this.store, this.env).actor(tx, local.user!, local.version), + ); return { ...(await this.member('demo', '11111111-1111-4111-8111-111111111111', 'human', 'wishforge-web')), displayName: 'Local Developer', diff --git a/apps/api/src/domain/local-accounts.ts b/apps/api/src/domain/local-accounts.ts new file mode 100644 index 0000000..79f0090 --- /dev/null +++ b/apps/api/src/domain/local-accounts.ts @@ -0,0 +1,228 @@ +import { randomBytes, randomInt, scryptSync, timingSafeEqual } from 'node:crypto'; +import { + DomainError, + isProduction, + localAccountInput, + localAccountPatch, + localLoginInput, + type Actor, + type Entity, + type LocalAccountView, + type Project, + type Role, +} from '@wishforge/contracts'; +import type { Store, Transaction } from '../db/store.js'; +import { must, record, touch } from './control-plane.js'; +import { effectiveEntitlements } from './entitlements.js'; +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. + */ +interface LocalAccount extends Entity { + username: string; + displayName: string; + passwordHash: string; + salt: string; + /** Changes when the password is reset, which ends the person's existing sessions. */ + passwordVersion: number; + createdBy: string; +} + +/** The deployment's tenant for the local credential; see Authenticator.authenticate. */ +export const LOCAL_TENANT = 'demo'; +export const localAccountId = (username: string) => `local:${username}`; +/** Without look-alike characters, so a password can be read out or typed from a screen. */ +const ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789'; +const hash = (password: string, salt: string) => scryptSync(password, salt, 64); + +/** Local accounts exist only where the web console signs people in with the local credential. */ +export function localAccountsEnabled(env: NodeJS.ProcessEnv) { + return !isProduction(env) && Boolean(env.WF_DEV_AUTH_TOKEN); +} + +function newPassword() { + return Array.from({ length: 16 }, () => ALPHABET[randomInt(ALPHABET.length)]).join(''); +} +function credential(password: string) { + const salt = randomBytes(32).toString('hex'); + return { salt, passwordHash: hash(password, salt).toString('hex') }; +} +function view(account: LocalAccount, role: Role | undefined): LocalAccountView { + return { + id: account.id, + username: account.username, + displayName: account.displayName, + role: role ?? 'viewer', + active: Boolean(role), + createdAt: account.createdAt, + createdBy: account.createdBy, + }; +} + +export class LocalAccounts { + constructor( + private store: Store, + private env = process.env, + ) {} + private enabled(actor?: Actor) { + if (!localAccountsEnabled(this.env)) + throw new DomainError( + 'LOCAL_ACCOUNTS_UNAVAILABLE', + 'Local accounts are only available in local deployments', + 404, + ); + if (actor && actor.tenantId !== LOCAL_TENANT) + throw new DomainError('LOCAL_ACCOUNTS_UNAVAILABLE', 'Local accounts belong to the local deployment', 404); + } + private manage(actor: Actor) { + this.enabled(actor); + requireHuman(actor); + requireRole(actor, ['owner', 'admin']); + } + async list(actor: Actor): Promise { + this.manage(actor); + return this.store.read(actor.tenantId, async tx => { + const roles = new Map((await tx.members()).filter(m => m.active).map(m => [m.userId, m.role])); + return (await tx.list('local_account')).map(account => view(account, roles.get(account.id))); + }); + } + /** + * Not idempotent by key on purpose: a replayed response would have to keep the password. The + * username is unique, so a retried request fails instead, and a password can be reset. + */ + async create(actor: Actor, input: unknown) { + this.manage(actor); + const data = localAccountInput.parse(input); + return this.store.transaction(actor.tenantId, async tx => { + const id = localAccountId(data.username); + if (await tx.get('local_account', id)) + throw new DomainError('ACCOUNT_EXISTS', 'This username is already taken', 409); + const members = (await tx.members()).filter(member => member.active); + 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 account: LocalAccount = { + ...record(actor.tenantId), + id, + username: data.username, + displayName: data.displayName, + ...credential(password), + passwordVersion: 1, + createdBy: actor.userId, + }; + await tx.put('local_account', account); + await tx.putMembership({ userId: id, role: data.role, active: true }); + const projects = await tx.list('project'); + for (const project of projects) { + if (data.projectIds && !data.projectIds.includes(project.id)) continue; + if (!project.memberIds.includes(id)) + await tx.put('project', { ...touch(project), memberIds: [...project.memberIds, id] }); + } + await tx.put('entitlement_event', { + ...record(actor.tenantId), + action: 'member.invited', + actorId: actor.userId, + targetSubject: id, + role: data.role, + }); + // The password is shown this once; only its hash is kept. + return { account: view(account, data.role), password }; + }); + } + async update(actor: Actor, id: string, input: unknown) { + this.manage(actor); + const data = localAccountPatch.parse(input); + 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 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; + if (next !== account) await tx.put('local_account', next); + if (active !== Boolean(current) || role !== current?.role) { + if (active && !current) { + const members = (await tx.members()).filter(member => member.active); + if (members.length >= effectiveEntitlements(await tx.tenant()).limits.maxMembers) + throw new DomainError('MEMBER_LIMIT', 'Tenant active-member allowance is exhausted', 429); + } + await tx.putMembership({ userId: id, role, active }); + await tx.put('entitlement_event', { + ...record(actor.tenantId), + action: active ? 'member.role_changed' : 'member.disabled', + actorId: actor.userId, + targetSubject: id, + role, + }); + } + return view(next, active ? role : undefined); + }); + } + /** A new password, shown once; sessions signed in with the old one end. */ + async resetPassword(actor: Actor, id: string) { + this.manage(actor); + return this.store.transaction(actor.tenantId, async tx => { + const account = await must(tx, 'local_account', id); + const password = newPassword(); + await tx.put('local_account', { + ...touch(account), + ...credential(password), + passwordVersion: account.passwordVersion + 1, + }); + await tx.put('entitlement_event', { + ...record(actor.tenantId), + action: 'member.password_reset', + actorId: actor.userId, + targetSubject: id, + }); + return { password }; + }); + } + /** + * The web console's check of a person's password. Only the console calls this: its proxy never + * forwards a browser request here. Unknown usernames cost the same work as known ones. + */ + async verify(actor: Actor, input: unknown) { + this.enabled(actor); + if (actor.kind !== 'human' || actor.clientId !== 'wishforge-web' || actor.userId.startsWith('local:')) + throw new DomainError('FORBIDDEN', 'Only the web console verifies passwords', 403); + const { username, password } = localLoginInput.parse(input); + return this.store.read(actor.tenantId, async tx => { + const account = /^[a-z0-9][a-z0-9_.-]{1,31}$/.test(username) + ? await tx.get('local_account', localAccountId(username)) + : undefined; + const salt = account?.salt ?? '0'.repeat(64); + const expected = Buffer.from(account?.passwordHash ?? '0'.repeat(128), 'hex'); + const matches = timingSafeEqual(hash(password, salt), expected) && Boolean(account); + const role = account ? await tx.membership(account.id) : undefined; + if (!matches || !account || !role) return { verified: false as const }; + return { + verified: true as const, + userId: account.id, + displayName: account.displayName, + role, + passwordVersion: account.passwordVersion, + }; + }); + } + /** The person behind a console request: the account must still be active, with the same password. */ + async actor(tx: Transaction, userId: string, version: string | undefined): Promise { + const account = await tx.get('local_account', userId); + if (!account || String(account.passwordVersion) !== version) + throw new DomainError('UNAUTHENTICATED', 'Your sign-in ended; sign in again', 401); + const role = await tx.membership(userId); + if (!role) throw new DomainError('FORBIDDEN', 'Your account is disabled', 403); + return { + tenantId: account.tenantId, + userId, + role, + kind: 'human', + clientId: 'wishforge-web', + displayName: account.displayName, + }; + } +} diff --git a/apps/api/src/http.ts b/apps/api/src/http.ts index 23dfdba..87a9678 100644 --- a/apps/api/src/http.ts +++ b/apps/api/src/http.ts @@ -27,7 +27,7 @@ import { isProduction, type Workspace, } from '@wishforge/contracts'; -import { Authenticator } from './auth.js'; +import { Authenticator, localUser } from './auth.js'; import { ControlPlane, must, projectAccess, record, touch } from './domain/control-plane.js'; import { Releases } from './domain/releases.js'; import { AgentBundles } from './domain/agent-bundles.js'; @@ -42,6 +42,7 @@ import { ProviderProxy } from './domain/provider-proxy.js'; import { Entitlements, requireCapacity } from './domain/entitlements.js'; import { requireRole, requireHuman } from './domain/policy.js'; import { configuredVerificationProfiles, selectVerificationProfile } from './domain/verification-policy.js'; +import { LocalAccounts } from './domain/local-accounts.js'; export class Services { auth: Authenticator; @@ -51,6 +52,7 @@ export class Services { connections: Connections; runners: RunnerBroker; github: GitHubIntegration; + accounts: LocalAccounts; constructor(readonly control: ControlPlane) { this.auth = new Authenticator(control.store, control.env); this.releases = new Releases(control.store, control.env); @@ -59,6 +61,7 @@ export class Services { this.connections = new Connections(control.store, control.env); this.runners = new RunnerBroker(control.store, this.releases, control.env); this.github = new GitHubIntegration(control.store, control.env); + this.accounts = new LocalAccounts(control.store, control.env); } } type AuthRequest = Request & { actor: Actor }; @@ -173,8 +176,8 @@ export class Errors implements ExceptionFilter { export class ApiController { constructor(@Inject(Services) private s: Services) {} @Get('identity') identity(@Req() req: AuthRequest) { - const { userId, role, kind } = req.actor; - return ok({ userId, role, kind }); + const { userId, role, kind, displayName } = req.actor; + return ok({ userId, role, kind, ...(displayName ? { displayName } : {}) }); } @Get('dashboard') async dashboard(@Req() req: AuthRequest) { const a = req.actor; @@ -362,7 +365,10 @@ export class ApiController { if (busy || res.writableEnded) return; busy = true; try { - const actor = await this.s.auth.authenticate(r.header('Authorization')); + const actor = await this.s.auth.authenticate( + r.header('Authorization'), + localUser(name => r.header(name)), + ); for (const e of await this.s.control.events(actor, id, cursor)) { res.write(`id: ${e.seq}\nevent: run\ndata: ${JSON.stringify(e)}\n\n`); cursor = e.seq; @@ -515,6 +521,26 @@ export class ApiController { @Post('admin/members') async admitMember(@Req() r: AuthRequest, @Body() b: unknown) { return ok(await new Entitlements(this.s.control.store, this.s.control.env).inviteMember(r.actor, b, key(r))); } + @Get('local-accounts') async localAccounts(@Req() r: AuthRequest) { + return ok(await this.s.accounts.list(r.actor)); + } + @Post('local-accounts') async createLocalAccount(@Req() r: AuthRequest, @Body() b: unknown) { + return ok(await this.s.accounts.create(r.actor, b)); + } + @Patch('local-accounts/:id') async updateLocalAccount( + @Req() r: AuthRequest, + @Param('id') id: string, + @Body() b: unknown, + ) { + return ok(await this.s.accounts.update(r.actor, id, b)); + } + @Post('local-accounts/:id/password') async resetLocalPassword(@Req() r: AuthRequest, @Param('id') id: string) { + return ok(await this.s.accounts.resetPassword(r.actor, id)); + } + /** Only the web console's own sign-in calls this; its proxy never forwards a browser here. */ + @Post('local-access/login') @HttpCode(200) async localLogin(@Req() r: AuthRequest, @Body() b: unknown) { + return ok(await this.s.accounts.verify(r.actor, b)); + } @Post('admin/executions/:id/reconcile') async reconcileResources( @Req() r: AuthRequest, @Param('id') id: string, diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts index 1955135..6540319 100644 --- a/apps/api/src/main.ts +++ b/apps/api/src/main.ts @@ -12,6 +12,7 @@ import { handleMcp } from './mcp.js'; import { Dispatcher } from './dispatcher.js'; import { auditContext } from './audit-context.js'; import { internalActor } from './internal-auth.js'; +import { localUser } from './auth.js'; import { observability } from './telemetry.js'; import { ProviderProxy } from './domain/provider-proxy.js'; import { once } from 'node:events'; @@ -135,7 +136,10 @@ export async function bootstrap() { }); raw.use('/v1', async (req: express.Request, res: express.Response, next: express.NextFunction) => { try { - const actor = await service.auth.authenticate(req.header('Authorization')); + const actor = await service.auth.authenticate( + req.header('Authorization'), + localUser(name => req.header(name)), + ); (req as express.Request & { actor: unknown }).actor = actor; res.setHeader('Cache-Control', 'no-store'); auditContext.run({ actorId: actor.userId }, next); diff --git a/apps/web/src/app/(console)/members/page.tsx b/apps/web/src/app/(console)/members/page.tsx new file mode 100644 index 0000000..203f8a0 --- /dev/null +++ b/apps/web/src/app/(console)/members/page.tsx @@ -0,0 +1,4 @@ +import { MembersView } from '@/features/members'; +export default function Page() { + return ; +} diff --git a/apps/web/src/app/api/[...path]/route.ts b/apps/web/src/app/api/[...path]/route.ts index 7c9e78b..86226f3 100644 --- a/apps/web/src/app/api/[...path]/route.ts +++ b/apps/web/src/app/api/[...path]/route.ts @@ -1,5 +1,12 @@ import { NextRequest, NextResponse } from 'next/server'; -import { authorizationFor, cookieOptions, publicOrigin, SESSION_COOKIE } from '@/lib/auth'; +import { + authorizationFor, + browserMayCall, + cookieOptions, + identityHeaders, + publicOrigin, + SESSION_COOKIE, +} from '@/lib/auth'; export const runtime = 'nodejs'; export const dynamic = 'force-dynamic'; type Context = { params: Promise<{ path: string[] }> }; @@ -7,12 +14,15 @@ async function proxy(request: NextRequest, context: Context) { const { path } = await context.params; if (path.some(part => !part || part === '..' || part === '.' || part.includes('/') || part.includes('\\'))) return NextResponse.json({ error: { code: 'INVALID_PATH', message: '无效的 API 路径。' } }, { status: 400 }); + // Password checks are the console's own sign-in, never a browser's request. + if (!browserMayCall(path)) + return NextResponse.json({ error: { code: 'NOT_FOUND', message: '无效的 API 路径。' } }, { status: 404 }); if (!['GET', 'HEAD'].includes(request.method)) { const origin = request.headers.get('origin'); if ((origin && origin !== publicOrigin(request)) || request.headers.get('sec-fetch-site') === 'cross-site') return NextResponse.json({ error: { code: 'ORIGIN_DENIED', message: '请求来源不被允许。' } }, { status: 403 }); } - const { token, cookie } = await authorizationFor(request); + const { token, cookie, localUser } = await authorizationFor(request); if (!token) return NextResponse.json( { @@ -25,7 +35,7 @@ async function proxy(request: NextRequest, context: Context) { ); const base = (process.env.WF_API_URL ?? 'http://127.0.0.1:4000').replace(/\/$/, ''); const url = `${base}/v1/${path.map(encodeURIComponent).join('/')}${request.nextUrl.search}`; - const headers = new Headers({ Authorization: `Bearer ${token}` }); + const headers = new Headers(identityHeaders(token, localUser)); for (const key of ['content-type', 'accept', 'idempotency-key', 'last-event-id']) { const value = request.headers.get(key); if (value) headers.set(key, value); diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.css index d10cbbc..e5a0c22 100644 --- a/apps/web/src/app/globals.css +++ b/apps/web/src/app/globals.css @@ -2736,3 +2736,59 @@ button { color: var(--teal); margin-top: 3px; } +.checkbox-list { + border: 1px solid var(--border); + border-radius: var(--radius); + padding: 10px 14px 12px; + margin: 0; + display: grid; + gap: 6px; +} +.checkbox-list legend { + font-weight: 600; + padding: 0 4px; +} +.checkbox-list label { + display: flex; + align-items: center; + gap: 8px; +} +.checkbox-list input { + appearance: auto; + min-height: auto; + margin: 0; + accent-color: var(--teal); + width: 15px; + height: 15px; +} +.role-legend { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); + gap: 10px 18px; + margin: 18px 0 0; + padding-top: 14px; + border-top: 1px solid var(--border); +} +.role-legend dt { + font-weight: 600; +} +.role-legend dd { + margin: 2px 0 0; + color: var(--muted); + font-size: 12px; +} +.password-once { + display: block; + font-size: 20px; + letter-spacing: 0.08em; + padding: 14px 16px; + border-radius: var(--radius); + background: var(--teal-pale); + user-select: all; + word-break: break-all; +} +.signed-in { + display: flex; + align-items: center; + gap: 10px; +} diff --git a/apps/web/src/app/ide/[id]/launch/route.ts b/apps/web/src/app/ide/[id]/launch/route.ts index 9ee7be3..a052622 100644 --- a/apps/web/src/app/ide/[id]/launch/route.ts +++ b/apps/web/src/app/ide/[id]/launch/route.ts @@ -1,9 +1,9 @@ import { NextRequest, NextResponse } from 'next/server'; -import { isDevelopment, tokenFor } from '@/lib/auth'; +import { authorizationFor, identityHeaders, isDevelopment } from '@/lib/auth'; export const runtime = 'nodejs'; export const dynamic = 'force-dynamic'; export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) { - const token = await tokenFor(request); + const { token, localUser } = await authorizationFor(request); if (!token) return NextResponse.redirect( new URL(`/login?returnTo=${encodeURIComponent(request.nextUrl.pathname)}`, request.nextUrl.origin), @@ -13,10 +13,7 @@ export async function GET(request: NextRequest, { params }: { params: Promise<{ try { const response = await fetch(`${api}/v1/workspaces/${encodeURIComponent(id)}/launch`, { method: 'POST', - headers: { - Authorization: `Bearer ${token}`, - 'Content-Type': 'application/json', - }, + headers: { ...identityHeaders(token, localUser), 'Content-Type': 'application/json' }, body: JSON.stringify({}), cache: 'no-store', redirect: 'error', diff --git a/apps/web/src/app/login/route.ts b/apps/web/src/app/login/route.ts index 233fe8a..3fe5055 100644 --- a/apps/web/src/app/login/route.ts +++ b/apps/web/src/app/login/route.ts @@ -22,7 +22,9 @@ import { localRequestAllowed, loginRateLimit, recordLoginFailure, + verifyLocalAccount, verifyLocalPassword, + type LocalAccountLogin, } from '@/lib/local-access'; const escapeHtml = (value: string) => @@ -33,7 +35,7 @@ function localLoginPage(request: NextRequest, message = '', status = 200) { return new Response( `登录 · WishForge
✦ WishForge

让愿望成为现实

登录本机工作空间,提交愿望并查看实现与交付进度。

${message ? `` : ''}

仅向获准的协作者提供访问密码。登录会话在 1 小时后失效。

`, +
✦ WishForge

让愿望成为现实

登录本机工作空间,提交愿望并查看实现与交付进度。

${message ? `` : ''}

账号由管理员在「成员」页创建。登录会话在 1 小时后失效。

`, { status, headers: { @@ -152,9 +154,19 @@ export async function POST(request: NextRequest) { return response; } try { - if (username.length > 64 || password.length > 256 || !verifyLocalPassword(username, password)) { + const oversized = username.length > 64 || password.length > 256; + const administrator = !oversized && verifyLocalPassword(username, password); + let account: LocalAccountLogin | undefined; + if (!oversized && !administrator) { + try { + account = await verifyLocalAccount(username, password); + } catch { + return localLoginPage(request, '暂时无法核对账号,请稍后重试。', 503); + } + } + if (!administrator && !account) { recordLoginFailure(); - return localLoginPage(request, '账号或访问密码不正确。', 401); + return localLoginPage(request, '账号或密码不正确。', 401); } const expiresAt = Math.floor(Date.now() / 1000) + LOCAL_SESSION_SECONDS; const cookie = await seal( @@ -164,8 +176,9 @@ export async function POST(request: NextRequest) { accessToken: '', expiresAt, sessionExpiresAt: expiresAt, - sub: 'local-administrator', - name: '本机管理员', + ...(account + ? { sub: account.userId, name: account.displayName, accountVersion: account.passwordVersion } + : { sub: 'local-administrator', name: '本机管理员' }), }, LOCAL_SESSION_SECONDS, ); diff --git a/apps/web/src/components/console-shell.tsx b/apps/web/src/components/console-shell.tsx index b83ea87..c02edf1 100644 --- a/apps/web/src/components/console-shell.tsx +++ b/apps/web/src/components/console-shell.tsx @@ -13,6 +13,7 @@ import { RefreshCw, Settings2, Sparkle, + Users, X, } from 'lucide-react'; import Link from 'next/link'; @@ -30,6 +31,7 @@ const navigation = [ ['/providers', '执行器', Settings2], ['/agent', 'Agent 配置', Bot], ['/usage', '用量', BarChart3], + ['/members', '成员', Users], ] as const; export function ConsoleShell({ children }: { children: ReactNode }) { const pathname = usePathname(); @@ -115,7 +117,8 @@ export function ConsoleShell({ children }: { children: ReactNode }) { 本地模式 ) : session.data?.authenticated ? ( -
+ + {session.data.name ? {session.data.name} : null}
) : ( diff --git a/apps/web/src/features/members.tsx b/apps/web/src/features/members.tsx new file mode 100644 index 0000000..81943cc --- /dev/null +++ b/apps/web/src/features/members.tsx @@ -0,0 +1,337 @@ +'use client'; +import { useState } from 'react'; +import { Copy, KeyRound, Plus, UserRound } from 'lucide-react'; +import { formatTime, messageOf, mutateApi, useResource } from '@/lib/api'; +import type { Identity, LocalAccount, Project, Role } from '@/lib/types'; +import { + Button, + EmptyState, + ErrorNotice, + Field, + FormError, + Loading, + Modal, + Notice, + PageHeader, + Panel, + Status, +} from '@/components/ui'; + +export const roleLabels: Record = { + owner: '所有者', + admin: '管理员', + developer: '开发者', + deployer: '部署者', + viewer: '只读', +}; +const assignable: Role[] = ['admin', 'developer', 'deployer', 'viewer']; +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); + return ( + +
+ {password} +
+ + +
+
+
+ ); +} + +/** Everyone signs in with an account of their own, so the system knows who did what. */ +export function MembersView() { + const identity = useResource('/identity'); + const manager = identity.data && ['owner', 'admin'].includes(identity.data.role); + 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 }); + const [projectIds, setProjectIds] = useState(); + const [password, setPassword] = useState<{ title: string; value: string }>(); + const [resetting, setResetting] = useState(); + const [busy, setBusy] = useState(''); + const [error, setError] = useState(''); + async function act(key: string, action: () => Promise) { + setBusy(key); + setError(''); + try { + const result = await action(); + await accounts.mutate(); + return result; + } catch (failure) { + setError(messageOf(failure)); + return undefined; + } finally { + setBusy(''); + } + } + const chosen = projectIds ?? projects.data?.map(project => project.id) ?? []; + return ( + <> + setAdding(true)}> + + 添加成员 + + ) : undefined + } + /> + {identity.error ? ( + void identity.mutate()} /> + ) : identity.isLoading ? ( + + ) : !manager ? ( + 只有所有者或管理员可以管理成员。你的角色是「{roleLabels[identity.data!.role]}」。 + ) : ( + +

+ 本机管理员(凭据文件里的账号)是所有者,不在下面的列表里。停用的账号立即无法再操作;重置密码会让对方已登录的会话失效。 +

+ {accounts.error ? ( + void accounts.mutate()} /> + ) : accounts.isLoading ? ( + + ) : accounts.data?.length ? ( +
+ + + + + + + + + + + + {accounts.data.map(account => ( + + + + + + + + ))} + +
成员角色状态创建 + 操作 +
+ {account.displayName} +
{account.username}
+
+ + + + {formatTime(account.createdAt)} +
+ + +
+
+
+ ) : ( + } + title="还没有成员账号" + description="添加成员后,把生成的密码交给对方,对方就能用自己的账号登录。" + /> + )} + {!adding && !resetting ? : null} +
+ {(Object.keys(roleLabels) as Role[]).map(role => ( +
+
{roleLabels[role]}
+
{roleHints[role]}
+
+ ))} +
+
+ )} + {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, + }), + ).then(created => { + if (!created) return; + setAdding(false); + setForm({ username: '', displayName: '', role: 'developer' }); + 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} + +
+ + +
+ +
+ ) : null} + {resetting ? ( + setResetting(undefined)} + > +
+ +
+ + +
+
+
+ ) : null} + {password ? ( + setPassword(undefined)} /> + ) : null} + + ); +} diff --git a/apps/web/src/lib/auth.ts b/apps/web/src/lib/auth.ts index 45c23de..4e17795 100644 --- a/apps/web/src/lib/auth.ts +++ b/apps/web/src/lib/auth.ts @@ -23,7 +23,11 @@ type Session = { sub: string; authMode?: 'local'; credentialId?: string; + /** A local account's password version; the control plane ends sessions of an older one. */ + accountVersion?: number; }; +/** A local account the console signed in, as the control plane identifies it. */ +export type LocalUser = { id: string; version: string }; /** A signed-in browser stays signed in this long while it keeps being used (requirements FR-A5). */ const SESSION_SECONDS = 12 * 60 * 60; /** Refresh an access token this long before it expires. */ @@ -142,14 +146,20 @@ async function refresh(session: Session): Promise { */ export async function authorizationFor( request: NextRequest, -): Promise<{ token?: string; cookie?: { value: string; maxAge: number } }> { +): Promise<{ token?: string; cookie?: { value: string; maxAge: number }; localUser?: LocalUser }> { if (isDevelopmentAuth()) return developmentHostAllowed(request) ? { token: process.env.WF_DEV_AUTH_TOKEN } : {}; const session = await getSession(request); if (!session) return {}; - if (localAccessEnabled()) - return localRequestAllowed(request) - ? { token: process.env.WF_LOCAL_API_TOKEN || process.env.WF_DEV_AUTH_TOKEN } - : {}; + if (localAccessEnabled()) { + if (!localRequestAllowed(request)) return {}; + const token = process.env.WF_LOCAL_API_TOKEN || process.env.WF_DEV_AUTH_TOKEN; + // The administrator from the credential file is the deployment's owner; anyone else signed in + // with an account of their own, and the control plane acts as them. Nothing else gets a token. + if (session.sub === 'local-administrator') return { token }; + if (session.sub.startsWith('local:') && Number.isSafeInteger(session.accountVersion)) + return { token, localUser: { id: session.sub, version: String(session.accountVersion) } }; + return {}; + } const now = nowSeconds(); if (session.expiresAt - REFRESH_MARGIN_SECONDS > now || !session.refreshToken) return session.expiresAt > now ? { token: session.accessToken } : {}; @@ -161,6 +171,17 @@ export async function authorizationFor( export async function tokenFor(request: NextRequest) { return (await authorizationFor(request)).token; } +/** Control plane routes the console calls for itself only, never on a browser's behalf. */ +export function browserMayCall(path: string[]) { + return path[0] !== 'local-access'; +} +/** The headers that make the control plane act for this request's signed-in person. */ +export function identityHeaders(token: string, localUser?: LocalUser): Record { + return { + Authorization: `Bearer ${token}`, + ...(localUser ? { 'X-WishForge-Local-User': localUser.id, 'X-WishForge-Local-Version': localUser.version } : {}), + }; +} export function oidcConfigured() { return Boolean(process.env.OIDC_ISSUER && process.env.OIDC_CLIENT_ID && process.env.WF_SESSION_SECRET); } diff --git a/apps/web/src/lib/local-access.test.ts b/apps/web/src/lib/local-access.test.ts index 7fe43d2..196e49c 100644 --- a/apps/web/src/lib/local-access.test.ts +++ b/apps/web/src/lib/local-access.test.ts @@ -6,7 +6,15 @@ import { scryptSync } from 'node:crypto'; import { NextRequest } from 'next/server'; vi.mock('server-only', () => ({})); -import { authorizationFor, getSession, isDevelopmentAuth, seal, SESSION_COOKIE } from './auth'; +import { + authorizationFor, + browserMayCall, + getSession, + identityHeaders, + isDevelopmentAuth, + seal, + SESSION_COOKIE, +} from './auth'; import { beginLoginAttempt, clearLoginFailures, @@ -15,6 +23,7 @@ import { localRequestAllowed, loginRateLimit, recordLoginFailure, + verifyLocalAccount, verifyLocalPassword, } from './local-access'; import { proxy } from '../proxy'; @@ -91,6 +100,50 @@ describe('local operator browser boundary', () => { token: 'private-control-api-token', }); }); + it('makes the control plane act as the person a session signed in with their own account', async () => { + expect( + await authorizationFor( + await authenticated('/api/projects', { sub: 'local:zhanghm', name: '章鸿铭', accountVersion: 3 }), + ), + ).toEqual({ token: 'private-control-api-token', localUser: { id: 'local:zhanghm', version: '3' } }); + // The administrator from the credential file is the deployment's owner, with no account. + expect((await authorizationFor(await authenticated('/api/projects'))).localUser).toBeUndefined(); + // A session claiming an account without its password version, or anyone else, gets nothing. + expect(await authorizationFor(await authenticated('/api/projects', { sub: 'local:zhanghm' }))).toEqual({}); + expect(await authorizationFor(await authenticated('/api/projects', { sub: 'someone' }))).toEqual({}); + expect(identityHeaders('token', { id: 'local:zhanghm', version: '3' })).toEqual({ + Authorization: 'Bearer token', + 'X-WishForge-Local-User': 'local:zhanghm', + 'X-WishForge-Local-Version': '3', + }); + }); + it('checks an account’s password with the control plane, never through the browser proxy', async () => { + const calls: Array<{ url: string; init?: RequestInit }> = []; + vi.stubGlobal('fetch', async (url: string, init?: RequestInit) => { + calls.push({ url, init }); + const { password } = JSON.parse(String(init?.body)); + return Response.json({ + data: + password === 'right' + ? { verified: true, userId: 'local:zhanghm', displayName: '章鸿铭', role: 'developer', passwordVersion: 2 } + : { verified: false }, + }); + }); + try { + expect(await verifyLocalAccount('zhanghm', 'right')).toEqual({ + userId: 'local:zhanghm', + displayName: '章鸿铭', + passwordVersion: 2, + }); + expect(await verifyLocalAccount('zhanghm', 'wrong')).toBeUndefined(); + expect(calls[0]!.url).toBe('http://127.0.0.1:4000/v1/local-access/login'); + expect(new Headers(calls[0]!.init?.headers).get('authorization')).toBe('Bearer private-control-api-token'); + } finally { + vi.unstubAllGlobals(); + } + expect(browserMayCall(['local-access', 'login'])).toBe(false); + expect(browserMayCall(['local-accounts'])).toBe(true); + }); it('rejects OIDC, expired, and credential-rotated sessions in local mode', async () => { expect(await getSession(await authenticated('/', { authMode: undefined }))).toBeNull(); expect(await getSession(await authenticated('/', { expiresAt: 1 }))).toBeNull(); diff --git a/apps/web/src/lib/local-access.ts b/apps/web/src/lib/local-access.ts index 34512e4..3fa6196 100644 --- a/apps/web/src/lib/local-access.ts +++ b/apps/web/src/lib/local-access.ts @@ -37,6 +37,43 @@ export function localCredentialId() { return createHash('sha256').update(localCredentials().passwordHash).digest('hex'); } +export interface LocalAccountLogin { + userId: string; + displayName: string; + passwordVersion: number; +} +/** + * A person's own account, which the control plane checks; undefined when the username or password + * is wrong. Throws when the control plane cannot answer. + */ +export async function verifyLocalAccount(username: string, password: string): Promise { + const token = process.env.WF_LOCAL_API_TOKEN || process.env.WF_DEV_AUTH_TOKEN; + if (!token) return undefined; + const base = (process.env.WF_API_URL ?? 'http://127.0.0.1:4000').replace(/\/$/, ''); + const response = await fetch(`${base}/v1/local-access/login`, { + method: 'POST', + headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }, + body: JSON.stringify({ username, password }), + cache: 'no-store', + redirect: 'error', + signal: AbortSignal.timeout(10000), + }); + // Local accounts are not available here: only the administrator can sign in. + if (response.status === 404) return undefined; + if (!response.ok) throw new Error('The control plane could not check the account'); + const payload = (await response.json()) as { data?: { verified?: boolean } & Partial }; + const data = payload.data; + if ( + !data?.verified || + typeof data.userId !== 'string' || + !data.userId.startsWith('local:') || + typeof data.displayName !== 'string' || + !Number.isSafeInteger(data.passwordVersion) + ) + return undefined; + return { userId: data.userId, displayName: data.displayName, passwordVersion: data.passwordVersion! }; +} + export function verifyLocalPassword(username: string, password: string) { const credentials = localCredentials(); const actual = scryptSync(password, credentials.salt, 64); diff --git a/apps/web/src/lib/types.ts b/apps/web/src/lib/types.ts index 34a304d..307f13f 100644 --- a/apps/web/src/lib/types.ts +++ b/apps/web/src/lib/types.ts @@ -224,3 +224,16 @@ export type Environment = { deploymentSecretPolicyDigest?: string; [key: string]: unknown; }; +/** Who the console acts as. */ +export type Identity = { userId: string; role: Role; kind: string; displayName?: string }; +export type Role = 'owner' | 'admin' | 'developer' | 'deployer' | 'viewer'; +/** A person with an account of their own on a local deployment. */ +export type LocalAccount = { + id: string; + username: string; + displayName: string; + role: Role; + active: boolean; + createdAt: string; + createdBy: string; +}; diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index df737fe..b03e846 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -54,7 +54,8 @@ export type EntityKind = | 'artifact' | 'github_operation' | 'provider_proxy_request' - | 'entitlement_event'; + | 'entitlement_event' + | 'local_account'; export interface Entity { id: string; tenantId: string; @@ -101,6 +102,16 @@ export interface Project extends Entity { integrationLease?: IntegrationLease; integrationFence?: number; } +/** A person who signs in to a local deployment with a password of their own. */ +export interface LocalAccountView { + id: string; + username: string; + displayName: string; + role: Role; + active: boolean; + createdAt: string; + createdBy: string; +} export interface Budget { maxTokens: number; maxMinutes: number; @@ -398,6 +409,29 @@ export const environmentInput = z secretVersionRefs: z.array(text.max(256)).max(32).default([]), }) .strict(); +/** Roles a local account can hold; the owner is the deployment's operator. */ +export const localAccountRoles = ['admin', 'developer', 'deployer', 'viewer'] as const; +export const localAccountInput = z + .object({ + username: z + .string() + .trim() + .regex(/^[a-z0-9][a-z0-9_.-]{1,31}$/, 'Use 2–32 lowercase letters, digits, dots, dashes or underscores'), + displayName: text.max(60), + role: z.enum(localAccountRoles), + /** Projects the person may work in; all projects when omitted. */ + projectIds: z.array(text.max(200)).max(200).optional(), + }) + .strict(); +export const localAccountPatch = z + .object({ + displayName: text.max(60).optional(), + role: z.enum(localAccountRoles).optional(), + active: z.boolean().optional(), + }) + .strict() + .refine(value => Object.values(value).some(field => field !== undefined), 'Change at least one field'); +export const localLoginInput = z.object({ username: z.string().max(64), password: z.string().max(256) }).strict(); export const releaseInput = z .object({ generation: text.optional(), diff --git a/tests/local-accounts.test.ts b/tests/local-accounts.test.ts new file mode 100644 index 0000000..40cbd60 --- /dev/null +++ b/tests/local-accounts.test.ts @@ -0,0 +1,107 @@ +/** + * People of a local deployment sign in with accounts of their own, so each acts with their own + * role (requirements FR-A1): the console checks passwords through the control plane, then calls + * it with the local credential and the person's account. + */ +import { beforeEach, describe, expect, it } from 'vitest'; +import type { Actor, Project } from '@wishforge/contracts'; +import { Authenticator } from '../apps/api/src/auth.js'; +import { ControlPlane } from '../apps/api/src/domain/control-plane.js'; +import { LocalAccounts } from '../apps/api/src/domain/local-accounts.js'; +import { MemoryStore } from './helpers/memory-store.js'; + +const devToken = 'local-console-credential-0123456789'; +const env = { NODE_ENV: 'test', WF_DEPLOYMENT_MODE: 'development', WF_DEV_AUTH_TOKEN: devToken }; +const operator = '11111111-1111-4111-8111-111111111111'; +let db: MemoryStore, accounts: LocalAccounts, auth: Authenticator, console_: Actor, project: Project; + +beforeEach(async () => { + db = new MemoryStore(); + db.seed('demo'); + await db.transaction('demo', tx => tx.putMembership({ userId: operator, role: 'owner', active: true })); + accounts = new LocalAccounts(db, env); + auth = new Authenticator(db, env); + console_ = await auth.authenticate(`Bearer ${devToken}`); + project = await new ControlPlane(db, env).createProject(console_, { + name: 'Pilot', + repositoryUrl: 'https://example.org/pilot.git', + }); +}); +const create = (username: string, role = 'developer') => + accounts.create(console_, { username, displayName: `${username} 名`, role }); + +describe('local accounts', () => { + it('creates an account with a one-time password and lets it into the projects', async () => { + const { account, password } = await create('zhanghm'); + expect(account).toMatchObject({ id: 'local:zhanghm', role: 'developer', active: true }); + expect(password).toMatch(/^[A-Za-z0-9]{16}$/); + expect(await accounts.list(console_)).toEqual([expect.objectContaining({ username: 'zhanghm' })]); + const stored = await db.read('demo', tx => tx.get('project', project.id)); + expect(stored?.memberIds).toContain('local:zhanghm'); + // Only the hash is kept, nowhere a replay could return the password. + expect( + JSON.stringify(db.state.get('demo'), (_, value) => (value instanceof Map ? [...value] : value)), + ).not.toContain(password); + await expect(create('zhanghm')).rejects.toMatchObject({ code: 'ACCOUNT_EXISTS' }); + }); + + it('checks passwords for the console, and acts as the person it signed in', async () => { + const { password } = await create('zhanghm'); + const verified = await accounts.verify(console_, { username: 'zhanghm', password }); + expect(verified).toMatchObject({ verified: true, userId: 'local:zhanghm', role: 'developer', passwordVersion: 1 }); + expect(await accounts.verify(console_, { username: 'zhanghm', password: 'wrong' })).toEqual({ verified: false }); + expect(await accounts.verify(console_, { username: 'nobody', password })).toEqual({ verified: false }); + const person = await auth.authenticate(`Bearer ${devToken}`, { user: 'local:zhanghm', version: '1' }); + expect(person).toMatchObject({ + userId: 'local:zhanghm', + role: 'developer', + kind: 'human', + displayName: 'zhanghm 名', + }); + // The account header counts only with the console's credential. + await expect(auth.authenticate('Bearer something-else', { user: 'local:zhanghm', version: '1' })).rejects.toThrow(); + // A signed-in person cannot use the console's password check. + await expect(accounts.verify(person, { username: 'zhanghm', password })).rejects.toMatchObject({ + code: 'FORBIDDEN', + }); + }); + + it('ends sessions on a password reset and stops a disabled account at once', async () => { + const { password } = await create('zhanghm'); + const { password: next } = await accounts.resetPassword(console_, 'local:zhanghm'); + expect(next).not.toBe(password); + await expect( + auth.authenticate(`Bearer ${devToken}`, { user: 'local:zhanghm', version: '1' }), + ).rejects.toMatchObject({ code: 'UNAUTHENTICATED' }); + expect(await accounts.verify(console_, { username: 'zhanghm', password })).toEqual({ verified: false }); + expect(await accounts.verify(console_, { username: 'zhanghm', password: next })).toMatchObject({ + verified: true, + passwordVersion: 2, + }); + await accounts.update(console_, 'local:zhanghm', { active: false }); + await expect( + auth.authenticate(`Bearer ${devToken}`, { user: 'local:zhanghm', version: '2' }), + ).rejects.toMatchObject({ code: 'FORBIDDEN' }); + expect(await accounts.verify(console_, { username: 'zhanghm', password: next })).toEqual({ verified: false }); + expect(await accounts.list(console_)).toEqual([expect.objectContaining({ active: false })]); + }); + + it('leaves managing accounts to owners and administrators', async () => { + await create('zhanghm'); + const developer = await auth.authenticate(`Bearer ${devToken}`, { user: 'local:zhanghm', version: '1' }); + await expect(accounts.list(developer)).rejects.toMatchObject({ code: 'FORBIDDEN' }); + await expect( + accounts.create(developer, { username: 'other', displayName: 'Other', role: 'admin' }), + ).rejects.toMatchObject({ code: 'FORBIDDEN' }); + await accounts.update(console_, 'local:zhanghm', { role: 'admin' }); + const admin = await auth.authenticate(`Bearer ${devToken}`, { user: 'local:zhanghm', version: '1' }); + await expect(accounts.update(admin, 'local:zhanghm', { active: false })).rejects.toMatchObject({ + code: 'SELF_ACCOUNT_CHANGE', + }); + }); + + it('exists only in local deployments', async () => { + const production = new LocalAccounts(db, { NODE_ENV: 'production', WF_DEPLOYMENT_MODE: 'production' }); + await expect(production.list(console_)).rejects.toMatchObject({ code: 'LOCAL_ACCOUNTS_UNAVAILABLE' }); + }); +});