👥 Let each person sign in with an account of their own
Everyone used the one local administrator, so the system could not tell who asked for a change, and anyone could approve anything. Owners and admins now create accounts on a members page: a login name, a display name and a role, with a password shown once. The control plane keeps only its scrypt hash, and account creation is deliberately not replayable by idempotency key, so the password is stored nowhere a replay could return it. The console checks a password through a control plane route its proxy never forwards from a browser, then calls the control plane with its local credential plus the person's account and password version; those headers count only together with that credential. Disabling an account stops it at once, and resetting a password ends its existing sessions. A session that is neither the administrator nor a valid account gets no credential at all. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
40a20f5dfb
commit
e8f99f4b24
@ -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<Actor, 'displayName' | 'email'> {
|
||||
};
|
||||
}
|
||||
|
||||
/** 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<Actor> {
|
||||
/**
|
||||
* `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<Actor> {
|
||||
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',
|
||||
|
||||
228
apps/api/src/domain/local-accounts.ts
Normal file
228
apps/api/src/domain/local-accounts.ts
Normal file
@ -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<LocalAccountView[]> {
|
||||
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<LocalAccount>('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<LocalAccount>('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>('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<LocalAccount>(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<LocalAccount>(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<LocalAccount>('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<Actor> {
|
||||
const account = await tx.get<LocalAccount>('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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@ -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,
|
||||
|
||||
@ -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);
|
||||
|
||||
4
apps/web/src/app/(console)/members/page.tsx
Normal file
4
apps/web/src/app/(console)/members/page.tsx
Normal file
@ -0,0 +1,4 @@
|
||||
import { MembersView } from '@/features/members';
|
||||
export default function Page() {
|
||||
return <MembersView />;
|
||||
}
|
||||
@ -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);
|
||||
|
||||
@ -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;
|
||||
}
|
||||
|
||||
@ -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',
|
||||
|
||||
@ -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(
|
||||
`<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>登录 · WishForge</title><style>
|
||||
*{box-sizing:border-box}body{margin:0;background:#f7f9fc;color:#172a3a;font:16px/1.6 system-ui,-apple-system,sans-serif;min-height:100vh;display:grid;place-items:center;padding:28px}main{width:100%;max-width:460px;background:#fff;border:1px solid #e3e9ed;border-radius:20px;padding:36px;box-shadow:0 16px 60px #172a3a09}.brand{font-weight:750;color:#087d70;letter-spacing:.03em}h1{font-size:28px;line-height:1.3;margin:24px 0 12px}p{color:#526474;margin:0 0 24px}label{display:block;font-size:14px;font-weight:600;margin:18px 0 7px}input{font:inherit;width:100%;padding:11px 12px;border:1px solid #cbd6dd;border-radius:9px}input:focus{outline:3px solid #c7eee6;border-color:#087d70}button{border:0;border-radius:9px;width:100%;padding:13px;background:#087d70;color:white;font:600 16px system-ui;cursor:pointer;margin-top:24px}button:focus-visible{outline:3px solid #91d9cc;outline-offset:3px}.error{color:#9b2828;background:#fff0f0;border-radius:8px;padding:10px 12px;margin:18px 0 0}.note{font-size:12px;margin:20px 0 0;color:#768593}@media(max-width:480px){main{padding:24px}h1{font-size:25px}}
|
||||
</style></head><body><main><div class="brand">✦ WishForge</div><h1>让愿望成为现实</h1><p>登录本机工作空间,提交愿望并查看实现与交付进度。</p>${message ? `<p class="error" role="alert">${escapeHtml(message)}</p>` : ''}<form action="/login?returnTo=${escapeHtml(encodeURIComponent(returnTo))}" method="post"><label for="username">管理员账号</label><input id="username" name="username" autocomplete="username" required maxlength="64" autofocus><label for="password">访问密码</label><input id="password" name="password" type="password" autocomplete="current-password" required maxlength="256"><button type="submit">进入工作空间</button></form><p class="note">仅向获准的协作者提供访问密码。登录会话在 1 小时后失效。</p></main></body></html>`,
|
||||
</style></head><body><main><div class="brand">✦ WishForge</div><h1>让愿望成为现实</h1><p>登录本机工作空间,提交愿望并查看实现与交付进度。</p>${message ? `<p class="error" role="alert">${escapeHtml(message)}</p>` : ''}<form action="/login?returnTo=${escapeHtml(encodeURIComponent(returnTo))}" method="post"><label for="username">账号</label><input id="username" name="username" autocomplete="username" required maxlength="64" autofocus><label for="password">密码</label><input id="password" name="password" type="password" autocomplete="current-password" required maxlength="256"><button type="submit">进入工作空间</button></form><p class="note">账号由管理员在「成员」页创建。登录会话在 1 小时后失效。</p></main></body></html>`,
|
||||
{
|
||||
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,
|
||||
);
|
||||
|
||||
@ -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 }) {
|
||||
本地模式
|
||||
</span>
|
||||
) : session.data?.authenticated ? (
|
||||
<form action="/logout" method="post">
|
||||
<form action="/logout" method="post" className="signed-in">
|
||||
{session.data.name ? <span className="muted">{session.data.name}</span> : null}
|
||||
<button className="subtle-link">退出登录</button>
|
||||
</form>
|
||||
) : (
|
||||
|
||||
337
apps/web/src/features/members.tsx
Normal file
337
apps/web/src/features/members.tsx
Normal file
@ -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<Role, string> = {
|
||||
owner: '所有者',
|
||||
admin: '管理员',
|
||||
developer: '开发者',
|
||||
deployer: '部署者',
|
||||
viewer: '只读',
|
||||
};
|
||||
const assignable: Role[] = ['admin', 'developer', 'deployer', 'viewer'];
|
||||
const roleHints: Record<Role, string> = {
|
||||
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 (
|
||||
<Modal title={title} description="密码只显示这一次。请复制后通过可信的渠道交给对方。" onClose={onClose}>
|
||||
<div className="form-stack">
|
||||
<code className="password-once">{password}</code>
|
||||
<div className="modal-actions">
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
onClick={() =>
|
||||
void navigator.clipboard?.writeText(password).then(
|
||||
() => setCopied(true),
|
||||
() => setCopied(false),
|
||||
)
|
||||
}
|
||||
>
|
||||
<Copy size={15} />
|
||||
{copied ? '已复制' : '复制密码'}
|
||||
</Button>
|
||||
<Button type="button" onClick={onClose}>
|
||||
我已保存
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
/** Everyone signs in with an account of their own, so the system knows who did what. */
|
||||
export function MembersView() {
|
||||
const identity = useResource<Identity>('/identity');
|
||||
const manager = identity.data && ['owner', 'admin'].includes(identity.data.role);
|
||||
const accounts = useResource<LocalAccount[]>(manager ? '/local-accounts' : null, 30000);
|
||||
const projects = useResource<Project[]>(manager ? '/projects' : null);
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [form, setForm] = useState({ username: '', displayName: '', role: 'developer' as Role });
|
||||
const [projectIds, setProjectIds] = useState<string[] | undefined>();
|
||||
const [password, setPassword] = useState<{ title: string; value: string }>();
|
||||
const [resetting, setResetting] = useState<LocalAccount>();
|
||||
const [busy, setBusy] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
async function act<T>(key: string, action: () => Promise<T>) {
|
||||
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 (
|
||||
<>
|
||||
<PageHeader
|
||||
title="成员"
|
||||
description="每个人用自己的账号登录,系统才知道愿望是谁提的、改动由谁审核、发布由谁批准。"
|
||||
action={
|
||||
manager ? (
|
||||
<Button onClick={() => setAdding(true)}>
|
||||
<Plus size={16} />
|
||||
添加成员
|
||||
</Button>
|
||||
) : undefined
|
||||
}
|
||||
/>
|
||||
{identity.error ? (
|
||||
<ErrorNotice error={identity.error} retry={() => void identity.mutate()} />
|
||||
) : identity.isLoading ? (
|
||||
<Loading />
|
||||
) : !manager ? (
|
||||
<Notice>只有所有者或管理员可以管理成员。你的角色是「{roleLabels[identity.data!.role]}」。</Notice>
|
||||
) : (
|
||||
<Panel title="账号">
|
||||
<p className="panel-intro">
|
||||
本机管理员(凭据文件里的账号)是所有者,不在下面的列表里。停用的账号立即无法再操作;重置密码会让对方已登录的会话失效。
|
||||
</p>
|
||||
{accounts.error ? (
|
||||
<ErrorNotice error={accounts.error} retry={() => void accounts.mutate()} />
|
||||
) : accounts.isLoading ? (
|
||||
<Loading />
|
||||
) : accounts.data?.length ? (
|
||||
<div className="table-scroll">
|
||||
<table className="data-table" aria-label="成员账号">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>成员</th>
|
||||
<th>角色</th>
|
||||
<th>状态</th>
|
||||
<th>创建</th>
|
||||
<th>
|
||||
<span className="sr-only">操作</span>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{accounts.data.map(account => (
|
||||
<tr key={account.id}>
|
||||
<td>
|
||||
<strong>{account.displayName}</strong>
|
||||
<div className="muted text-small">{account.username}</div>
|
||||
</td>
|
||||
<td>
|
||||
<select
|
||||
aria-label={`${account.displayName} 的角色`}
|
||||
value={account.role}
|
||||
disabled={!account.active || busy === `role:${account.id}`}
|
||||
onChange={event =>
|
||||
void act(`role:${account.id}`, () =>
|
||||
mutateApi(
|
||||
`/local-accounts/${encodeURIComponent(account.id)}`,
|
||||
{ role: event.target.value },
|
||||
'PATCH',
|
||||
),
|
||||
)
|
||||
}
|
||||
>
|
||||
{assignable.map(role => (
|
||||
<option key={role} value={role}>
|
||||
{roleLabels[role]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</td>
|
||||
<td>
|
||||
<Status
|
||||
value={account.active ? 'ready' : 'disabled'}
|
||||
label={account.active ? '可用' : '已停用'}
|
||||
/>
|
||||
</td>
|
||||
<td className="muted text-small">{formatTime(account.createdAt)}</td>
|
||||
<td>
|
||||
<div className="button-group">
|
||||
<Button variant="ghost" onClick={() => setResetting(account)}>
|
||||
<KeyRound size={15} />
|
||||
重置密码
|
||||
</Button>
|
||||
<Button
|
||||
variant={account.active ? 'danger' : 'secondary'}
|
||||
busy={busy === `active:${account.id}`}
|
||||
onClick={() =>
|
||||
void act(`active:${account.id}`, () =>
|
||||
mutateApi(
|
||||
`/local-accounts/${encodeURIComponent(account.id)}`,
|
||||
{ active: !account.active },
|
||||
'PATCH',
|
||||
),
|
||||
)
|
||||
}
|
||||
>
|
||||
{account.active ? '停用' : '启用'}
|
||||
</Button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : (
|
||||
<EmptyState
|
||||
compact
|
||||
icon={<UserRound size={34} strokeWidth={1.35} />}
|
||||
title="还没有成员账号"
|
||||
description="添加成员后,把生成的密码交给对方,对方就能用自己的账号登录。"
|
||||
/>
|
||||
)}
|
||||
{!adding && !resetting ? <FormError message={error} /> : null}
|
||||
<dl className="role-legend">
|
||||
{(Object.keys(roleLabels) as Role[]).map(role => (
|
||||
<div key={role}>
|
||||
<dt>{roleLabels[role]}</dt>
|
||||
<dd>{roleHints[role]}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</Panel>
|
||||
)}
|
||||
{adding ? (
|
||||
<Modal title="添加成员" description="创建后会生成一个初始密码。" onClose={() => setAdding(false)}>
|
||||
<form
|
||||
className="form-stack"
|
||||
onSubmit={event => {
|
||||
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 });
|
||||
});
|
||||
}}
|
||||
>
|
||||
<Field label="登录名" hint="2–32 位小写字母、数字、点、横线或下划线,例如 zhanghm。">
|
||||
<input
|
||||
required
|
||||
pattern="[a-z0-9][a-z0-9_.\-]{1,31}"
|
||||
value={form.username}
|
||||
onChange={event => setForm({ ...form, username: event.target.value.toLowerCase() })}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="显示名" hint="在运行记录、审核和审批里显示,例如真实姓名。">
|
||||
<input
|
||||
required
|
||||
maxLength={60}
|
||||
value={form.displayName}
|
||||
onChange={event => setForm({ ...form, displayName: event.target.value })}
|
||||
/>
|
||||
</Field>
|
||||
<Field label="角色" hint={roleHints[form.role]}>
|
||||
<select value={form.role} onChange={event => setForm({ ...form, role: event.target.value as Role })}>
|
||||
{assignable.map(role => (
|
||||
<option key={role} value={role}>
|
||||
{roleLabels[role]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
{projects.data?.length ? (
|
||||
<fieldset className="checkbox-list">
|
||||
<legend>可以进入的项目</legend>
|
||||
{projects.data.map(project => (
|
||||
<label key={project.id}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={chosen.includes(project.id)}
|
||||
onChange={event =>
|
||||
setProjectIds(
|
||||
event.target.checked ? [...chosen, project.id] : chosen.filter(id => id !== project.id),
|
||||
)
|
||||
}
|
||||
/>
|
||||
{project.name}
|
||||
</label>
|
||||
))}
|
||||
</fieldset>
|
||||
) : null}
|
||||
<FormError message={error} />
|
||||
<div className="modal-actions">
|
||||
<Button type="button" variant="secondary" onClick={() => setAdding(false)}>
|
||||
取消
|
||||
</Button>
|
||||
<Button busy={busy === 'create'} disabled={!form.username.trim() || !form.displayName.trim()}>
|
||||
创建账号
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
) : null}
|
||||
{resetting ? (
|
||||
<Modal
|
||||
title={`重置 ${resetting.displayName} 的密码`}
|
||||
description="会生成新密码,对方已登录的会话会立即失效。"
|
||||
onClose={() => setResetting(undefined)}
|
||||
>
|
||||
<div className="form-stack">
|
||||
<FormError message={error} />
|
||||
<div className="modal-actions">
|
||||
<Button type="button" variant="secondary" onClick={() => setResetting(undefined)}>
|
||||
保留原密码
|
||||
</Button>
|
||||
<Button
|
||||
variant="danger"
|
||||
busy={busy === 'reset'}
|
||||
onClick={() =>
|
||||
void act('reset', () =>
|
||||
mutateApi<{ password: string }>(
|
||||
`/local-accounts/${encodeURIComponent(resetting.id)}/password`,
|
||||
undefined,
|
||||
),
|
||||
).then(result => {
|
||||
if (!result) return;
|
||||
setPassword({ title: `${resetting.displayName} 的新密码`, value: result.password });
|
||||
setResetting(undefined);
|
||||
})
|
||||
}
|
||||
>
|
||||
重置密码
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
) : null}
|
||||
{password ? (
|
||||
<PasswordOnce title={password.title} password={password.value} onClose={() => setPassword(undefined)} />
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@ -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<Session | null> {
|
||||
*/
|
||||
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<string, string> {
|
||||
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);
|
||||
}
|
||||
|
||||
@ -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();
|
||||
|
||||
@ -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<LocalAccountLogin | undefined> {
|
||||
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<LocalAccountLogin> };
|
||||
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);
|
||||
|
||||
@ -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;
|
||||
};
|
||||
|
||||
@ -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(),
|
||||
|
||||
107
tests/local-accounts.test.ts
Normal file
107
tests/local-accounts.test.ts
Normal file
@ -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', 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' });
|
||||
});
|
||||
});
|
||||
Loading…
x
Reference in New Issue
Block a user