feat: improve account deletion and Agent authorization review
This commit is contained in:
1 parent
5ad64460f7
commit
91365ee315
21 files changed
+2276
-713
No files matched your search
@@ -5,13 +5,13 @@
|
||||
"dev": "node scripts/dev.cjs",
|
||||
"build": "tsc",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "tsx --test --test-concurrency=1 test/calculation.test.ts test/update.test.ts test/zip.test.ts test/metals.test.ts ../web/test/i18n.test.ts",
|
||||
"test": "tsx --test --test-concurrency=1 test/calculation.test.ts test/update.test.ts test/zip.test.ts test/metals.test.ts ../web/test/i18n.test.ts test/account-deletion.test.ts",
|
||||
"db:generate": "prisma generate",
|
||||
"db:migrate": "node scripts/database.cjs deploy",
|
||||
"db:status": "node scripts/database.cjs status",
|
||||
"test:integration": "tsx --test --test-concurrency=1 test/integration.test.ts test/privacy.test.ts test/icons.test.ts test/transfers.test.ts test/queries.test.ts test/debts.test.ts test/update-integration.test.ts test/record-edit.test.ts test/security-backup.test.ts test/credit-balance.test.ts test/group-order.test.ts test/settings-plans.test.ts test/inclusion-metals.test.ts",
|
||||
"test:integration": "tsx --test --test-concurrency=1 test/integration.test.ts test/privacy.test.ts test/icons.test.ts test/transfers.test.ts test/queries.test.ts test/debts.test.ts test/update-integration.test.ts test/record-edit.test.ts test/security-backup.test.ts test/credit-balance.test.ts test/group-order.test.ts test/settings-plans.test.ts test/inclusion-metals.test.ts test/account-deletion-integration.test.ts",
|
||||
"test:performance": "tsx scripts/performance.ts after",
|
||||
"test:mcp": "tsx --test --test-concurrency=1 test/mcp.test.ts",
|
||||
"test:mcp": "tsx --test --test-concurrency=1 test/mcp.test.ts test/oauth-duration.test.ts",
|
||||
"mcp:probe": "tsx scripts/mcp-probe.ts",
|
||||
"icons:seed": "node scripts/seed-icons.cjs",
|
||||
"test:mcp:codex": "tsx --test --test-concurrency=1 test/codex-oauth.test.ts"
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE `AgentGrant` MODIFY `refreshExpiresAt` DATETIME(3) NULL COMMENT '刷新授权到期时间,UTC;空表示永久 OAuth 授权或个人令牌不适用';
|
||||
@@ -127,7 +127,7 @@ model AgentGrant {
|
||||
refreshDigest String? @unique @db.Char(64)
|
||||
/// 访问令牌到期时间,UTC;空表示可撤销的永久个人令牌
|
||||
expiresAt DateTime?
|
||||
/// 刷新授权到期时间,UTC
|
||||
/// 刷新授权到期时间,UTC;空表示永久 OAuth 授权或个人令牌不适用
|
||||
refreshExpiresAt DateTime?
|
||||
/// 撤销时间,UTC;空表示未撤销
|
||||
revokedAt DateTime?
|
||||
|
||||
@@ -15,7 +15,7 @@ import { Response } from 'express';
|
||||
import { z } from 'zod';
|
||||
import { Database } from '../database';
|
||||
import { AuthService, UserRequest } from '../auth';
|
||||
import { AgentOAuth, urls, scopeInput } from './oauth';
|
||||
import { AgentOAuth, urls, scopeInput, oauthDays } from './oauth';
|
||||
import { AgentOperations } from './operations';
|
||||
import { protocolTools, tokenDays } from './information';
|
||||
@Controller('api/agent')
|
||||
@@ -34,6 +34,7 @@ export class AgentManagementController {
|
||||
name: true,
|
||||
scopes: true,
|
||||
expiresAt: true,
|
||||
refreshExpiresAt: true,
|
||||
createdAt: true,
|
||||
revokedAt: true,
|
||||
clientId: true,
|
||||
@@ -110,11 +111,11 @@ export class AgentManagementController {
|
||||
@Param('id') id: string,
|
||||
@Body() raw: unknown,
|
||||
) {
|
||||
const { approve, scopes } = z
|
||||
.object({ approve: z.boolean(), scopes: scopeInput.optional() })
|
||||
const { approve, scopes, days } = z
|
||||
.object({ approve: z.boolean(), scopes: scopeInput.optional(), days: oauthDays.default(30) })
|
||||
.strict()
|
||||
.parse(raw);
|
||||
return this.oauth.consent(r.userId, z.string().uuid().parse(id), approve, scopes);
|
||||
return this.oauth.consent(r.userId, z.string().uuid().parse(id), approve, scopes, days);
|
||||
}
|
||||
@Get('operations/:id') preview(@Req() r: UserRequest, @Param('id') id: string) {
|
||||
return this.operations.preview(r.userId, z.string().uuid().parse(id));
|
||||
|
||||
@@ -33,6 +33,14 @@ export const scopeInput = z
|
||||
(!v.includes('hidden_write') ||
|
||||
(v.includes('hidden_read') && (v.includes('draft') || v.includes('write')))),
|
||||
);
|
||||
export const oauthDays = z.union([
|
||||
z.literal(1),
|
||||
z.literal(3),
|
||||
z.literal(7),
|
||||
z.literal(30),
|
||||
z.literal(365),
|
||||
z.literal(null),
|
||||
]);
|
||||
export const digest = (s: string) => createHash('sha256').update(s).digest('hex');
|
||||
const secret = () => randomBytes(32).toString('base64url');
|
||||
export function urls() {
|
||||
@@ -63,6 +71,9 @@ export function urls() {
|
||||
}
|
||||
export function webLink(key: string, id: string) {
|
||||
const u = new URL(urls().web);
|
||||
u.pathname =
|
||||
u.pathname.replace(/\/$/, '') +
|
||||
(key === 'agent_authorization' ? '/agent/authorize' : '/agent/operation');
|
||||
u.searchParams.set(key, id);
|
||||
return u.toString();
|
||||
}
|
||||
@@ -156,11 +167,18 @@ export class AgentOAuth implements OAuthServerProvider {
|
||||
resource: p.resource,
|
||||
};
|
||||
}
|
||||
async consent(userId: string, id: string, approved: boolean, selected?: string[]) {
|
||||
async consent(
|
||||
userId: string,
|
||||
id: string,
|
||||
approved: boolean,
|
||||
selected?: string[],
|
||||
days: number | null = 30,
|
||||
) {
|
||||
return this.db.atomic(async () => {
|
||||
await this.pending(id);
|
||||
const row = await this.db.agentAuthorization.findUniqueOrThrow({ where: { id } });
|
||||
const parameters = row.parameters as any;
|
||||
const authorizationDays = oauthDays.parse(days);
|
||||
const allowed = selected || ['read'];
|
||||
scopeInput.parse(allowed);
|
||||
if (allowed.some((scope: string) => !parameters.scopes.includes(scope)))
|
||||
@@ -172,7 +190,7 @@ export class AgentOAuth implements OAuthServerProvider {
|
||||
userId,
|
||||
status: approved ? 'approved' : 'denied',
|
||||
codeDigest: approved ? digest(code) : null,
|
||||
parameters: { ...parameters, scopes: allowed },
|
||||
parameters: { ...parameters, scopes: allowed, authorizationDays },
|
||||
},
|
||||
});
|
||||
if (!changed.count) throw new BadRequestException('授权请求已处理');
|
||||
@@ -202,18 +220,23 @@ export class AgentOAuth implements OAuthServerProvider {
|
||||
selected: string[],
|
||||
days: number | null,
|
||||
clientId?: string,
|
||||
authorizationDays: number | null = 30,
|
||||
) {
|
||||
if (clientId && days === null) throw new BadRequestException('OAuth 连接必须有期限');
|
||||
const access = secret(),
|
||||
refresh = clientId ? secret() : undefined,
|
||||
sessionId = digest(secret());
|
||||
const expiresAt = days === null ? null : new Date(Date.now() + days * 86400000),
|
||||
refreshExpiresAt = clientId ? new Date(Date.now() + 30 * 86400000) : null;
|
||||
const expiresAt = days === null ? null : new Date(Date.now() + days * 86400000);
|
||||
const lifetime = oauthDays.parse(authorizationDays);
|
||||
const refreshExpiresAt =
|
||||
clientId && lifetime !== null ? new Date(Date.now() + lifetime * 86400000) : null;
|
||||
await this.db.session.create({
|
||||
data: {
|
||||
id: sessionId,
|
||||
userId,
|
||||
expiresAt: refreshExpiresAt || expiresAt || new Date(Date.now() + 86400000),
|
||||
expiresAt: clientId
|
||||
? refreshExpiresAt || new Date(Date.now() + 30 * 86400000)
|
||||
: expiresAt || new Date(Date.now() + 86400000),
|
||||
},
|
||||
});
|
||||
const grant = await this.db.agentGrant.create({
|
||||
@@ -274,6 +297,7 @@ export class AgentOAuth implements OAuthServerProvider {
|
||||
p.scopes,
|
||||
1 / 24,
|
||||
client.client_id,
|
||||
p.authorizationDays === undefined ? 30 : p.authorizationDays,
|
||||
)
|
||||
).tokens;
|
||||
});
|
||||
@@ -291,8 +315,7 @@ export class AgentOAuth implements OAuthServerProvider {
|
||||
!row ||
|
||||
row.clientId !== client.client_id ||
|
||||
row.revokedAt ||
|
||||
!row.refreshExpiresAt ||
|
||||
row.refreshExpiresAt <= new Date()
|
||||
(row.refreshExpiresAt && row.refreshExpiresAt <= new Date())
|
||||
)
|
||||
throw new InvalidGrantError('Invalid refresh token');
|
||||
const current = row.scopes as string[];
|
||||
@@ -303,21 +326,36 @@ export class AgentOAuth implements OAuthServerProvider {
|
||||
throw new InvalidScopeError('Scope escalation rejected');
|
||||
const access = secret(),
|
||||
refresh = secret();
|
||||
const accessExpiresAt = new Date(
|
||||
Math.min(Date.now() + 3600000, row.refreshExpiresAt ? +row.refreshExpiresAt : Infinity),
|
||||
);
|
||||
const changed = await this.db.agentGrant.updateMany({
|
||||
where: { id: row.id, refreshDigest: digest(token), revokedAt: null },
|
||||
data: {
|
||||
accessDigest: digest(access),
|
||||
refreshDigest: digest(refresh),
|
||||
expiresAt: new Date(Date.now() + 3600000),
|
||||
expiresAt: accessExpiresAt,
|
||||
scopes: selected || current,
|
||||
},
|
||||
});
|
||||
if (!changed.count) throw new InvalidGrantError('Refresh token already used');
|
||||
// Permanent OAuth keeps a bounded business session, renewed only after a valid refresh.
|
||||
const sessionExpiresAt = row.refreshExpiresAt || new Date(Date.now() + 30 * 86400000);
|
||||
await this.db.session.upsert({
|
||||
where: { id: row.sessionId },
|
||||
create: { id: row.sessionId, userId: row.userId, expiresAt: sessionExpiresAt },
|
||||
update: {
|
||||
expiresAt: sessionExpiresAt,
|
||||
revealUntil: null,
|
||||
backupDigest: null,
|
||||
backupExpiresAt: null,
|
||||
},
|
||||
});
|
||||
return {
|
||||
access_token: access,
|
||||
refresh_token: refresh,
|
||||
token_type: 'Bearer',
|
||||
expires_in: 3600,
|
||||
expires_in: Math.max(0, Math.floor((+accessExpiresAt - Date.now()) / 1000)),
|
||||
scope: (selected || current).join(' '),
|
||||
};
|
||||
});
|
||||
@@ -328,6 +366,7 @@ export class AgentOAuth implements OAuthServerProvider {
|
||||
if (
|
||||
!row ||
|
||||
row.revokedAt ||
|
||||
(row.clientId && row.refreshExpiresAt && row.refreshExpiresAt <= new Date()) ||
|
||||
(row.expiresAt ? row.expiresAt <= new Date() : !!row.clientId) ||
|
||||
row.resource !== urls().resource.toString()
|
||||
)
|
||||
@@ -358,6 +397,15 @@ export class AgentOAuth implements OAuthServerProvider {
|
||||
id,
|
||||
...(userId ? { userId } : {}),
|
||||
revokedAt: null,
|
||||
AND: [
|
||||
{
|
||||
OR: [
|
||||
{ clientId: null },
|
||||
{ refreshExpiresAt: null },
|
||||
{ refreshExpiresAt: { gt: new Date() } },
|
||||
],
|
||||
},
|
||||
],
|
||||
OR: [{ expiresAt: { gt: new Date() } }, { expiresAt: null, clientId: null }],
|
||||
},
|
||||
});
|
||||
|
||||
@@ -219,10 +219,94 @@ export class AgentOperations {
|
||||
if (!row) throw new NotFoundException('操作不存在');
|
||||
const t = this.get(row.tool),
|
||||
grant = await this.oauth.grant(row.grantId, userId);
|
||||
let impact: unknown = { parameters: row.parameters, message: t.description };
|
||||
const selected = grant.scopes as string[];
|
||||
const ids = new Set<string>();
|
||||
const collect = (value: unknown) => {
|
||||
if (typeof value === 'string' && /^[a-f0-9-]{36}$/i.test(value)) ids.add(value);
|
||||
else if (Array.isArray(value)) value.forEach(collect);
|
||||
else if (value && typeof value === 'object') Object.values(value).forEach(collect);
|
||||
};
|
||||
collect(row.parameters);
|
||||
const visible = { userId, ...(selected.includes('hidden_read') ? {} : { hidden: false }) };
|
||||
const positions = await this.db.position.findMany({
|
||||
where: { ...visible, id: { in: [...ids] } },
|
||||
select: { id: true, name: true, currency: true, side: true, kind: true },
|
||||
});
|
||||
const schedules = await this.db.schedule.findMany({
|
||||
where: { userId, id: { in: [...ids] } },
|
||||
select: { id: true, name: true, sourceId: true, targetId: true },
|
||||
});
|
||||
const visibleScheduleIds = new Set(
|
||||
(
|
||||
await this.db.position.findMany({
|
||||
where: {
|
||||
...visible,
|
||||
id: { in: schedules.flatMap((s) => [s.sourceId, ...(s.targetId ? [s.targetId] : [])]) },
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
).map((p) => p.id),
|
||||
);
|
||||
const references = Object.fromEntries([
|
||||
...positions.map((p) => [p.id, p]),
|
||||
...schedules
|
||||
.filter(
|
||||
(s) =>
|
||||
visibleScheduleIds.has(s.sourceId) &&
|
||||
(!s.targetId || visibleScheduleIds.has(s.targetId)),
|
||||
)
|
||||
.map((s) => [s.id, { name: s.name, kind: 'schedule' }]),
|
||||
]);
|
||||
const p = row.parameters as Record<string, any>;
|
||||
let current: Record<string, unknown> | undefined;
|
||||
if (['movement_update', 'movement_delete'].includes(row.tool)) {
|
||||
const movement = await this.db.transfer.findFirst({
|
||||
where: { id: p.id, userId, source: visible, target: visible },
|
||||
include: { source: true, target: true },
|
||||
});
|
||||
if (movement) {
|
||||
references[movement.sourceId] = {
|
||||
name: movement.source.name,
|
||||
currency: movement.source.currency,
|
||||
};
|
||||
references[movement.targetId] = {
|
||||
name: movement.target.name,
|
||||
currency: movement.target.currency,
|
||||
};
|
||||
current = {
|
||||
operation: movement.operation,
|
||||
sourceId: movement.sourceId,
|
||||
targetId: movement.targetId,
|
||||
amount: movement.amount.toString(),
|
||||
received: movement.received.toString(),
|
||||
fee: movement.fee.toString(),
|
||||
date: new Date(+movement.effectiveDate + 8 * 3600000).toISOString().slice(0, 16),
|
||||
notes: movement.notes,
|
||||
};
|
||||
}
|
||||
} else if (['history_update', 'history_delete', 'balance_record'].includes(row.tool)) {
|
||||
const revision = await this.db.revision.findFirst({
|
||||
where: {
|
||||
positionId: p.id,
|
||||
position: visible,
|
||||
...(p.revisionId ? { id: p.revisionId } : {}),
|
||||
},
|
||||
orderBy: [{ effectiveDate: 'desc' }, { sequence: 'desc' }],
|
||||
});
|
||||
if (revision)
|
||||
current = {
|
||||
id: p.id,
|
||||
amount: revision.amount.toString(),
|
||||
date: new Date(+revision.effectiveDate + 8 * 3600000).toISOString().slice(0, 16),
|
||||
notes: revision.notes,
|
||||
};
|
||||
}
|
||||
const impact = { parameters: row.parameters, references, current };
|
||||
return {
|
||||
...this.view(row),
|
||||
impact,
|
||||
connectionName: grant.name,
|
||||
destructive: !!t.destructive,
|
||||
description: t.description,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -209,6 +209,7 @@ export class AgentTransport {
|
||||
name: g.name,
|
||||
scopes: g.scopes,
|
||||
expiresAt: g.expiresAt,
|
||||
authorizationExpiresAt: g.clientId ? g.refreshExpiresAt : g.expiresAt,
|
||||
resource: g.resource,
|
||||
permission: (g.scopes as string[]).includes('write')
|
||||
? 'write'
|
||||
|
||||
@@ -158,6 +158,63 @@ export class PortfolioBusinessService {
|
||||
});
|
||||
return { ok: true };
|
||||
}
|
||||
async deletion(r: UserRequest, id: string) {
|
||||
const p = await this.own(r.userId, id, r.revealed);
|
||||
if (p.kind !== 'account') throw new BadRequestException('此功能仅用于删除账户');
|
||||
const [historyCount, movementCount, scheduleCount, linkCount] = await Promise.all([
|
||||
this.db.revision.count({ where: { positionId: id } }),
|
||||
this.db.transfer.count({
|
||||
where: { userId: r.userId, OR: [{ sourceId: id }, { targetId: id }] },
|
||||
}),
|
||||
this.db.schedule.count({
|
||||
where: { userId: r.userId, OR: [{ sourceId: id }, { targetId: id }] },
|
||||
}),
|
||||
this.db.positionLink.count({ where: { OR: [{ sourceId: id }, { targetId: id }] } }),
|
||||
]);
|
||||
return {
|
||||
name: p.name,
|
||||
historyCount,
|
||||
movementCount,
|
||||
scheduleCount,
|
||||
linkCount,
|
||||
canDelete: movementCount === 0 && scheduleCount === 0,
|
||||
};
|
||||
}
|
||||
async remove(r: UserRequest, id: string, raw: unknown) {
|
||||
const input = z
|
||||
.object({ confirmation: z.string().min(1).max(100) })
|
||||
.strict()
|
||||
.parse(raw);
|
||||
const result = await this.db.serial(async (tx) => {
|
||||
await tx.$queryRaw(
|
||||
Prisma.sql`SELECT id FROM Position WHERE id = ${id} AND userId = ${r.userId} FOR UPDATE`,
|
||||
);
|
||||
const p = await tx.position.findFirst({
|
||||
where: { id, userId: r.userId, ...(r.revealed ? {} : { hidden: false }) },
|
||||
});
|
||||
if (!p) throw new NotFoundException('账户不存在');
|
||||
if (p.kind !== 'account') throw new BadRequestException('此功能仅用于删除账户');
|
||||
if (input.confirmation !== p.name)
|
||||
throw new BadRequestException('请输入完整账户名称确认删除');
|
||||
// Paired movements must be removed through replay, never via cascade.
|
||||
if (
|
||||
await tx.transfer.count({
|
||||
where: { userId: r.userId, OR: [{ sourceId: id }, { targetId: id }] },
|
||||
})
|
||||
)
|
||||
throw new ConflictException('账户存在资金往来,请先撤销相关记录,或选择归档保留历史');
|
||||
if (
|
||||
await tx.schedule.count({
|
||||
where: { userId: r.userId, OR: [{ sourceId: id }, { targetId: id }] },
|
||||
})
|
||||
)
|
||||
throw new ConflictException('账户被定时计划使用,请先删除相关计划,或选择归档');
|
||||
await tx.position.delete({ where: { id } });
|
||||
return { ok: true };
|
||||
});
|
||||
this.fx.invalidate(r.userId);
|
||||
return result;
|
||||
}
|
||||
async revise(r: UserRequest, id: string, b: unknown) {
|
||||
const v = revisionInput.parse(b);
|
||||
if (pairedReasons.includes(v.reason)) throw new BadRequestException('请使用账户转账接口');
|
||||
@@ -351,6 +408,16 @@ export class PortfolioController {
|
||||
) {
|
||||
return this.service.edit(r, id, b);
|
||||
}
|
||||
@Get('positions/:id/deletion') async deletion(@Req() r: UserRequest, @Param('id') id: string) {
|
||||
return this.service.deletion(r, id);
|
||||
}
|
||||
@Delete('positions/:id') async remove(
|
||||
@Req() r: UserRequest,
|
||||
@Param('id') id: string,
|
||||
@Body() b: unknown,
|
||||
) {
|
||||
return this.service.remove(r, id, b);
|
||||
}
|
||||
@Post('positions/:id/revisions') async revise(
|
||||
@Req() r: UserRequest,
|
||||
@Param('id') id: string,
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
import 'dotenv/config';
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { randomUUID, randomBytes, createHash } from 'node:crypto';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { today } from '../src/validation';
|
||||
const base = process.env.TEST_API_URL || 'http://127.0.0.1:3100/api';
|
||||
const origin = process.env.WEB_ORIGIN === '*' ? 'http://localhost:5173' : process.env.WEB_ORIGIN!;
|
||||
test('real REST account deletion preserves paired balances, blocks schedules, cascades own history and isolates users', async () => {
|
||||
const db = new PrismaClient(),
|
||||
users: string[] = [];
|
||||
async function fixture() {
|
||||
const u = await db.user.create({
|
||||
data: { username: 'delete_' + randomUUID(), passwordHash: 'unused', idleMinutes: 0 },
|
||||
});
|
||||
users.push(u.id);
|
||||
const token = randomBytes(32).toString('hex');
|
||||
const sessionId = createHash('sha256').update(token).digest('hex');
|
||||
await db.session.create({
|
||||
data: { id: sessionId, userId: u.id, expiresAt: new Date(Date.now() + 3600000) },
|
||||
});
|
||||
return { id: u.id, cookie: 'wp_session=' + token, sessionId };
|
||||
}
|
||||
async function call(u: any, path: string, method = 'GET', data?: unknown) {
|
||||
const r = await fetch(base + path, {
|
||||
method,
|
||||
headers: {
|
||||
Cookie: u.cookie,
|
||||
Origin: origin,
|
||||
...(data ? { 'Content-Type': 'application/json' } : {}),
|
||||
},
|
||||
body: data ? JSON.stringify(data) : undefined,
|
||||
});
|
||||
return { status: r.status, data: await r.json() };
|
||||
}
|
||||
try {
|
||||
const a = await fixture(),
|
||||
b = await fixture();
|
||||
const input = {
|
||||
kind: 'account',
|
||||
side: 'asset',
|
||||
category: 'cash',
|
||||
name: '删除测试账户',
|
||||
currency: 'CNY',
|
||||
amount: '100',
|
||||
date: today(),
|
||||
};
|
||||
const first = await call(a, '/positions', 'POST', input);
|
||||
assert.equal(first.status, 201);
|
||||
const id = first.data.id;
|
||||
assert.equal((await call(b, '/positions/' + id + '/deletion')).status, 404);
|
||||
assert.equal(
|
||||
(await call(b, '/positions/' + id, 'DELETE', { confirmation: input.name })).status,
|
||||
404,
|
||||
);
|
||||
assert.equal(
|
||||
(await call(a, '/positions/' + id, 'DELETE', { confirmation: '错误名称' })).status,
|
||||
400,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await call(a, '/positions/' + id + '/revisions', 'POST', {
|
||||
amount: '125.87654321',
|
||||
date: today(),
|
||||
})
|
||||
).status,
|
||||
201,
|
||||
);
|
||||
const debt = await call(a, '/positions', 'POST', {
|
||||
...input,
|
||||
kind: 'debt',
|
||||
side: 'liability',
|
||||
name: '关联债务',
|
||||
amount: '10',
|
||||
});
|
||||
assert.equal(debt.status, 201);
|
||||
assert.equal(
|
||||
(await call(a, '/positions/' + debt.data.id + '/links', 'PUT', { targetIds: [id] })).status,
|
||||
200,
|
||||
);
|
||||
const impact = await call(a, '/positions/' + id + '/deletion');
|
||||
assert.equal(impact.data.historyCount, 2);
|
||||
assert.equal(impact.data.linkCount, 1);
|
||||
assert.equal(impact.data.canDelete, true);
|
||||
assert.equal(
|
||||
(await call(a, '/positions/' + id, 'DELETE', { confirmation: input.name })).status,
|
||||
200,
|
||||
);
|
||||
assert.equal((await call(a, '/positions/' + id)).status, 404);
|
||||
assert.equal(await db.revision.count({ where: { positionId: id } }), 0);
|
||||
assert.equal(await db.positionLink.count({ where: { targetId: id } }), 0);
|
||||
const overview = await call(a, '/overview');
|
||||
assert.equal(overview.data.assets, '0.00');
|
||||
assert.equal(overview.data.liabilities, '10.00');
|
||||
assert.ok(!(await call(a, '/history')).data.items.some((h: any) => h.positionId === id));
|
||||
assert.ok(
|
||||
!(await call(a, '/calendar/day?date=' + today())).data.items.some(
|
||||
(h: any) => h.positionId === id,
|
||||
),
|
||||
);
|
||||
|
||||
const source = (await call(a, '/positions', 'POST', input)).data.id;
|
||||
const target = (
|
||||
await call(a, '/positions', 'POST', { ...input, name: '收款测试账户', amount: '0' })
|
||||
).data.id;
|
||||
const movement = await call(a, '/transfers', 'POST', {
|
||||
sourceId: source,
|
||||
targetId: target,
|
||||
amount: '20',
|
||||
received: '20',
|
||||
date: today(),
|
||||
});
|
||||
assert.equal(movement.status, 201);
|
||||
assert.equal((await call(a, '/positions/' + source + '/deletion')).data.canDelete, false);
|
||||
assert.equal(
|
||||
(await call(a, '/positions/' + source, 'DELETE', { confirmation: input.name })).status,
|
||||
409,
|
||||
);
|
||||
assert.equal((await call(a, '/positions/' + target)).data.amount, '20');
|
||||
assert.equal((await call(a, '/transfers/' + movement.data.id, 'DELETE')).status, 200);
|
||||
assert.equal((await call(a, '/positions/' + target)).data.amount, '0');
|
||||
const schedule = await call(a, '/schedules', 'POST', {
|
||||
name: '未来计划',
|
||||
operation: 'expense',
|
||||
sourceId: source,
|
||||
amount: '5',
|
||||
nextAt: '2099-01-01T10:00',
|
||||
intervalDays: 0,
|
||||
});
|
||||
assert.equal(schedule.status, 201);
|
||||
assert.equal((await call(a, '/positions/' + source + '/deletion')).data.scheduleCount, 1);
|
||||
assert.equal(
|
||||
(await call(a, '/positions/' + source, 'DELETE', { confirmation: input.name })).status,
|
||||
409,
|
||||
);
|
||||
assert.equal((await call(a, '/schedules/' + schedule.data.id, 'DELETE')).status, 200);
|
||||
assert.equal(
|
||||
(await call(a, '/positions/' + source, 'DELETE', { confirmation: input.name })).status,
|
||||
200,
|
||||
);
|
||||
|
||||
const hidden = (await call(a, '/positions', 'POST', { ...input, hidden: true })).data.id;
|
||||
assert.equal((await call(a, '/positions/' + hidden + '/deletion')).status, 404);
|
||||
assert.equal(
|
||||
(await call(a, '/positions/' + hidden, 'DELETE', { confirmation: input.name })).status,
|
||||
404,
|
||||
);
|
||||
await db.session.update({
|
||||
where: { id: a.sessionId },
|
||||
data: { revealUntil: new Date(Date.now() + 600000) },
|
||||
});
|
||||
assert.equal(
|
||||
(await call(a, '/positions/' + hidden, 'DELETE', { confirmation: input.name })).status,
|
||||
200,
|
||||
);
|
||||
assert.equal(
|
||||
(await call(a, '/positions/' + debt.data.id, 'DELETE', { confirmation: '关联债务' })).status,
|
||||
400,
|
||||
);
|
||||
} finally {
|
||||
await db.user.deleteMany({ where: { id: { in: users } } });
|
||||
await db.$disconnect();
|
||||
}
|
||||
});
|
||||
test('draft review resolves only referenced visible names and canonical standalone confirmation URL', async () => {
|
||||
const db = new PrismaClient();
|
||||
let userId = '';
|
||||
try {
|
||||
const u = await db.user.create({
|
||||
data: { username: 'review_' + randomUUID(), passwordHash: 'unused', idleMinutes: 0 },
|
||||
});
|
||||
userId = u.id;
|
||||
const token = randomBytes(32).toString('hex'),
|
||||
sid = createHash('sha256').update(token).digest('hex');
|
||||
await db.session.create({
|
||||
data: { id: sid, userId, expiresAt: new Date(Date.now() + 3600000) },
|
||||
});
|
||||
const grant = await db.agentGrant.create({
|
||||
data: {
|
||||
userId,
|
||||
name: '草稿审阅测试',
|
||||
scopes: ['read', 'draft'],
|
||||
resource: process.env.MCP_PUBLIC_URL || 'http://localhost:3100/mcp',
|
||||
sessionId: sid,
|
||||
accessDigest: createHash('sha256').update(randomUUID()).digest('hex'),
|
||||
expiresAt: new Date(Date.now() + 3600000),
|
||||
},
|
||||
});
|
||||
const visible = await db.position.create({
|
||||
data: {
|
||||
userId,
|
||||
name: '可见账户',
|
||||
kind: 'account',
|
||||
side: 'asset',
|
||||
category: 'cash',
|
||||
currency: 'CNY',
|
||||
notes: '',
|
||||
},
|
||||
});
|
||||
const hidden = await db.position.create({
|
||||
data: {
|
||||
userId,
|
||||
name: '隐藏名称不能泄露',
|
||||
hidden: true,
|
||||
kind: 'account',
|
||||
side: 'asset',
|
||||
category: 'cash',
|
||||
currency: 'CNY',
|
||||
notes: '',
|
||||
},
|
||||
});
|
||||
const unrelated = await db.position.create({
|
||||
data: {
|
||||
userId,
|
||||
name: '无关账户',
|
||||
kind: 'account',
|
||||
side: 'asset',
|
||||
category: 'cash',
|
||||
currency: 'CNY',
|
||||
notes: '',
|
||||
},
|
||||
});
|
||||
const op = await db.agentOperation.create({
|
||||
data: {
|
||||
userId,
|
||||
grantId: grant.id,
|
||||
key: randomUUID(),
|
||||
hash: '0'.repeat(64),
|
||||
snapshot: '0'.repeat(64),
|
||||
tool: 'debt_links_set',
|
||||
parameters: { id: visible.id, targetIds: [hidden.id] },
|
||||
expiresAt: new Date(Date.now() + 600000),
|
||||
},
|
||||
});
|
||||
const res = await fetch(base + '/agent/operations/' + op.id, {
|
||||
headers: { Cookie: 'wp_session=' + token },
|
||||
});
|
||||
assert.equal(res.status, 200);
|
||||
const preview = await res.json();
|
||||
assert.equal(preview.connectionName, '草稿审阅测试');
|
||||
assert.equal(preview.impact.references[visible.id].name, '可见账户');
|
||||
assert.ok(!preview.impact.references[hidden.id]);
|
||||
assert.ok(!preview.impact.references[unrelated.id]);
|
||||
assert.equal(new URL(preview.confirmationUrl).pathname, '/agent/operation');
|
||||
} finally {
|
||||
if (userId) await db.user.deleteMany({ where: { id: userId } });
|
||||
await db.$disconnect();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,97 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { PortfolioBusinessService } from '../src/portfolio';
|
||||
import { NotFoundException, ConflictException, BadRequestException } from '@nestjs/common';
|
||||
function fixture() {
|
||||
const row = { id: 'account', userId: 'owner', name: '测试账户', kind: 'account', hidden: false };
|
||||
let movements = 0,
|
||||
schedules = 0,
|
||||
deleted = false,
|
||||
invalidated = false;
|
||||
const db: any = {
|
||||
serial: async (fn: any) => fn(db),
|
||||
$queryRaw: async () => [],
|
||||
position: {
|
||||
findFirst: async ({ where }: any) =>
|
||||
where.id === row.id &&
|
||||
where.userId === row.userId &&
|
||||
!(where.hidden === false && row.hidden) &&
|
||||
!deleted
|
||||
? row
|
||||
: null,
|
||||
delete: async () => {
|
||||
deleted = true;
|
||||
return row;
|
||||
},
|
||||
},
|
||||
transfer: { count: async () => movements },
|
||||
schedule: { count: async () => schedules },
|
||||
};
|
||||
const service = new PortfolioBusinessService(
|
||||
db,
|
||||
{
|
||||
invalidate: () => {
|
||||
invalidated = true;
|
||||
},
|
||||
} as any,
|
||||
{} as any,
|
||||
{} as any,
|
||||
);
|
||||
return {
|
||||
service,
|
||||
row,
|
||||
setMovements: (v: number) => {
|
||||
movements = v;
|
||||
},
|
||||
setSchedules: (v: number) => {
|
||||
schedules = v;
|
||||
},
|
||||
state: () => ({ deleted, invalidated }),
|
||||
};
|
||||
}
|
||||
const owner = { userId: 'owner', revealed: false } as any;
|
||||
test('account deletion checks ownership and hidden visibility before deleting or invalidating', async () => {
|
||||
const f = fixture();
|
||||
await assert.rejects(
|
||||
() => f.service.remove({ ...owner, userId: 'other' }, 'account', { confirmation: '测试账户' }),
|
||||
NotFoundException,
|
||||
);
|
||||
f.row.hidden = true;
|
||||
await assert.rejects(
|
||||
() => f.service.remove(owner, 'account', { confirmation: '测试账户' }),
|
||||
NotFoundException,
|
||||
);
|
||||
assert.deepEqual(f.state(), { deleted: false, invalidated: false });
|
||||
await f.service.remove({ ...owner, revealed: true }, 'account', { confirmation: '测试账户' });
|
||||
assert.deepEqual(f.state(), { deleted: true, invalidated: true });
|
||||
});
|
||||
test('wrong confirmation, non-accounts, paired movements and schedules cannot cascade', async () => {
|
||||
const f = fixture();
|
||||
await assert.rejects(
|
||||
() => f.service.remove(owner, 'account', { confirmation: '错误名称' }),
|
||||
BadRequestException,
|
||||
);
|
||||
f.row.kind = 'asset';
|
||||
await assert.rejects(
|
||||
() => f.service.remove(owner, 'account', { confirmation: '测试账户' }),
|
||||
BadRequestException,
|
||||
);
|
||||
f.row.kind = 'account';
|
||||
f.setMovements(1);
|
||||
await assert.rejects(
|
||||
() => f.service.remove(owner, 'account', { confirmation: '测试账户' }),
|
||||
ConflictException,
|
||||
);
|
||||
f.setMovements(0);
|
||||
f.setSchedules(1);
|
||||
await assert.rejects(
|
||||
() => f.service.remove(owner, 'account', { confirmation: '测试账户' }),
|
||||
ConflictException,
|
||||
);
|
||||
assert.deepEqual(f.state(), { deleted: false, invalidated: false });
|
||||
f.setSchedules(0);
|
||||
assert.deepEqual(await f.service.remove(owner, 'account', { confirmation: '测试账户' }), {
|
||||
ok: true,
|
||||
});
|
||||
assert.deepEqual(f.state(), { deleted: true, invalidated: true });
|
||||
});
|
||||
@@ -0,0 +1,282 @@
|
||||
import 'dotenv/config';
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { randomUUID, randomBytes, createHash } from 'node:crypto';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
const root = process.env.TEST_API_URL?.replace(/\/api$/, '') || 'http://127.0.0.1:3100';
|
||||
const resource = process.env.MCP_PUBLIC_URL || 'http://localhost:3100/mcp';
|
||||
const origin = process.env.WEB_ORIGIN === '*' ? 'http://localhost:5173' : process.env.WEB_ORIGIN!;
|
||||
test('OAuth consent persists selected lifetime; refresh rotates and cannot extend authorization or access past its end', async () => {
|
||||
const db = new PrismaClient();
|
||||
let userId = '',
|
||||
clientId = '';
|
||||
try {
|
||||
const u = await db.user.create({
|
||||
data: { username: 'oauth_days_' + randomUUID(), passwordHash: 'unused', idleMinutes: 0 },
|
||||
});
|
||||
userId = u.id;
|
||||
const session = randomBytes(32).toString('hex'),
|
||||
sid = createHash('sha256').update(session).digest('hex');
|
||||
await db.session.create({
|
||||
data: { id: sid, userId, expiresAt: new Date(Date.now() + 3600000) },
|
||||
});
|
||||
const cookie = 'wp_session=' + session;
|
||||
clientId = randomUUID();
|
||||
const callback = 'http://127.0.0.1:47891/callback';
|
||||
await db.agentClient.create({
|
||||
data: {
|
||||
id: clientId,
|
||||
metadata: {
|
||||
client_id: clientId,
|
||||
client_name: '期限测试',
|
||||
redirect_uris: [callback],
|
||||
token_endpoint_auth_method: 'none',
|
||||
grant_types: ['authorization_code', 'refresh_token'],
|
||||
response_types: ['code'],
|
||||
},
|
||||
},
|
||||
});
|
||||
async function authorization() {
|
||||
const verifier = randomBytes(32).toString('base64url'),
|
||||
id = randomUUID();
|
||||
await db.agentAuthorization.create({
|
||||
data: {
|
||||
id,
|
||||
clientId,
|
||||
expiresAt: new Date(Date.now() + 600000),
|
||||
parameters: {
|
||||
redirectUri: callback,
|
||||
resource,
|
||||
scopes: ['read', 'draft'],
|
||||
codeChallenge: createHash('sha256').update(verifier).digest('base64url'),
|
||||
},
|
||||
},
|
||||
});
|
||||
return { id, verifier };
|
||||
}
|
||||
async function consent(id: string, days?: number) {
|
||||
const r = await fetch(root + '/api/agent/authorizations/' + id, {
|
||||
method: 'POST',
|
||||
headers: { Cookie: cookie, Origin: origin, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
approve: true,
|
||||
scopes: ['read', 'draft'],
|
||||
...(days === undefined ? {} : { days }),
|
||||
}),
|
||||
});
|
||||
return { status: r.status, data: await r.json() };
|
||||
}
|
||||
async function token(data: Record<string, string>) {
|
||||
const r = await fetch(root + '/token', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({ client_id: clientId, resource, ...data }),
|
||||
});
|
||||
return { status: r.status, data: await r.json() };
|
||||
}
|
||||
for (const days of [1, 3, 7, 30, 365, undefined]) {
|
||||
const a = await authorization(),
|
||||
approved = await consent(a.id, days);
|
||||
assert.equal(approved.status, 201);
|
||||
const code = new URL(approved.data.redirect).searchParams.get('code')!;
|
||||
const issued = await token({
|
||||
grant_type: 'authorization_code',
|
||||
code,
|
||||
code_verifier: a.verifier,
|
||||
redirect_uri: callback,
|
||||
});
|
||||
assert.equal(issued.status, 200);
|
||||
assert.equal(issued.data.expires_in, 3600);
|
||||
let grant = await db.agentGrant.findUniqueOrThrow({
|
||||
where: {
|
||||
accessDigest: createHash('sha256').update(issued.data.access_token).digest('hex'),
|
||||
},
|
||||
});
|
||||
const ending = +grant.refreshExpiresAt!;
|
||||
assert.ok(Math.abs(ending - Date.now() - (days ?? 30) * 86400000) < 5000);
|
||||
const sessionRow = await db.session.findUniqueOrThrow({ where: { id: grant.sessionId } });
|
||||
assert.equal(+sessionRow.expiresAt, ending);
|
||||
const refreshed = await token({
|
||||
grant_type: 'refresh_token',
|
||||
refresh_token: issued.data.refresh_token,
|
||||
});
|
||||
assert.equal(refreshed.status, 200);
|
||||
grant = await db.agentGrant.findUniqueOrThrow({ where: { id: grant.id } });
|
||||
assert.equal(+grant.refreshExpiresAt!, ending);
|
||||
const nearEnd = new Date(Date.now() + 50000);
|
||||
await db.agentGrant.update({ where: { id: grant.id }, data: { refreshExpiresAt: nearEnd } });
|
||||
const finalRefresh = await token({
|
||||
grant_type: 'refresh_token',
|
||||
refresh_token: refreshed.data.refresh_token,
|
||||
});
|
||||
assert.equal(finalRefresh.status, 200);
|
||||
assert.ok(finalRefresh.data.expires_in <= 50);
|
||||
grant = await db.agentGrant.findUniqueOrThrow({ where: { id: grant.id } });
|
||||
assert.equal(+grant.expiresAt!, +nearEnd);
|
||||
await db.agentGrant.update({
|
||||
where: { id: grant.id },
|
||||
data: { refreshExpiresAt: new Date(0) },
|
||||
});
|
||||
assert.equal(
|
||||
(
|
||||
await token({
|
||||
grant_type: 'refresh_token',
|
||||
refresh_token: finalRefresh.data.refresh_token,
|
||||
})
|
||||
).status,
|
||||
400,
|
||||
);
|
||||
const request = await fetch(resource, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: 'Bearer ' + finalRefresh.data.access_token,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: '{}',
|
||||
});
|
||||
assert.equal(request.status, 401);
|
||||
}
|
||||
for (const days of [0, 2, 366]) {
|
||||
const a = await authorization();
|
||||
assert.equal((await consent(a.id, days)).status, 400);
|
||||
assert.equal(
|
||||
(await db.agentAuthorization.findUniqueOrThrow({ where: { id: a.id } })).status,
|
||||
'pending',
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (userId) await db.user.deleteMany({ where: { id: userId } });
|
||||
if (clientId) {
|
||||
await db.agentAuthorization.deleteMany({ where: { clientId } });
|
||||
await db.agentClient.deleteMany({ where: { id: clientId } });
|
||||
}
|
||||
await db.$disconnect();
|
||||
}
|
||||
});
|
||||
test('permanent OAuth rotates credentials, renews deleted business session and remains revocable', async () => {
|
||||
const db = new PrismaClient();
|
||||
let userId = '',
|
||||
clientId = '';
|
||||
try {
|
||||
const u = await db.user.create({
|
||||
data: { username: 'oauth_permanent_' + randomUUID(), passwordHash: 'unused', idleMinutes: 0 },
|
||||
});
|
||||
userId = u.id;
|
||||
const cookieToken = randomBytes(32).toString('hex'),
|
||||
sid = createHash('sha256').update(cookieToken).digest('hex');
|
||||
await db.session.create({
|
||||
data: { id: sid, userId, expiresAt: new Date(Date.now() + 3600000) },
|
||||
});
|
||||
clientId = randomUUID();
|
||||
const redirectUri = 'http://127.0.0.1:47891/callback';
|
||||
await db.agentClient.create({
|
||||
data: {
|
||||
id: clientId,
|
||||
metadata: {
|
||||
client_id: clientId,
|
||||
client_name: '永久授权测试',
|
||||
redirect_uris: [redirectUri],
|
||||
token_endpoint_auth_method: 'none',
|
||||
grant_types: ['authorization_code', 'refresh_token'],
|
||||
response_types: ['code'],
|
||||
},
|
||||
},
|
||||
});
|
||||
const id = randomUUID(),
|
||||
verifier = randomBytes(32).toString('base64url');
|
||||
await db.agentAuthorization.create({
|
||||
data: {
|
||||
id,
|
||||
clientId,
|
||||
parameters: {
|
||||
redirectUri,
|
||||
resource,
|
||||
scopes: ['read'],
|
||||
codeChallenge: createHash('sha256').update(verifier).digest('base64url'),
|
||||
},
|
||||
expiresAt: new Date(Date.now() + 600000),
|
||||
},
|
||||
});
|
||||
const res = await fetch(root + '/api/agent/authorizations/' + id, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Cookie: 'wp_session=' + cookieToken,
|
||||
Origin: origin,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ approve: true, scopes: ['read'], days: null }),
|
||||
});
|
||||
assert.equal(res.status, 201);
|
||||
const consent = await res.json();
|
||||
async function token(data: Record<string, string>) {
|
||||
const r = await fetch(root + '/token', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({ client_id: clientId, resource, ...data }),
|
||||
});
|
||||
return { status: r.status, data: await r.json() };
|
||||
}
|
||||
const issued = await token({
|
||||
grant_type: 'authorization_code',
|
||||
code: new URL(consent.redirect).searchParams.get('code')!,
|
||||
code_verifier: verifier,
|
||||
redirect_uri: redirectUri,
|
||||
});
|
||||
assert.equal(issued.status, 200);
|
||||
assert.equal(issued.data.expires_in, 3600);
|
||||
const grant = await db.agentGrant.findUniqueOrThrow({
|
||||
where: { accessDigest: createHash('sha256').update(issued.data.access_token).digest('hex') },
|
||||
});
|
||||
assert.equal(grant.refreshExpiresAt, null);
|
||||
assert.ok(grant.expiresAt);
|
||||
assert.equal(
|
||||
((await db.agentAuthorization.findUniqueOrThrow({ where: { id } })).parameters as any)
|
||||
.authorizationDays,
|
||||
null,
|
||||
);
|
||||
await db.session.delete({ where: { id: grant.sessionId } });
|
||||
const refreshed = await token({
|
||||
grant_type: 'refresh_token',
|
||||
refresh_token: issued.data.refresh_token,
|
||||
});
|
||||
assert.equal(refreshed.status, 200);
|
||||
const renewed = await db.session.findUniqueOrThrow({ where: { id: grant.sessionId } });
|
||||
assert.ok(+renewed.expiresAt > Date.now() + 29 * 86400000);
|
||||
assert.equal(
|
||||
(await db.agentGrant.findUniqueOrThrow({ where: { id: grant.id } })).refreshExpiresAt,
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
(await token({ grant_type: 'refresh_token', refresh_token: issued.data.refresh_token }))
|
||||
.status,
|
||||
400,
|
||||
);
|
||||
const revoke = await fetch(root + '/revoke', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({ client_id: clientId, token: refreshed.data.access_token }),
|
||||
});
|
||||
assert.equal(revoke.status, 200);
|
||||
assert.equal(
|
||||
(await token({ grant_type: 'refresh_token', refresh_token: refreshed.data.refresh_token }))
|
||||
.status,
|
||||
400,
|
||||
);
|
||||
const denied = await fetch(resource, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: 'Bearer ' + refreshed.data.access_token,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: '{}',
|
||||
});
|
||||
assert.equal(denied.status, 401);
|
||||
} finally {
|
||||
if (userId) await db.user.deleteMany({ where: { id: userId } });
|
||||
if (clientId) {
|
||||
await db.agentAuthorization.deleteMany({ where: { clientId } });
|
||||
await db.agentClient.deleteMany({ where: { id: clientId } });
|
||||
}
|
||||
await db.$disconnect();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { api, type Position } from './api';
|
||||
import { showToast } from './Toast';
|
||||
type Impact = {
|
||||
name: string;
|
||||
historyCount: number;
|
||||
movementCount: number;
|
||||
scheduleCount: number;
|
||||
linkCount: number;
|
||||
canDelete: boolean;
|
||||
};
|
||||
export function AccountDeletion({
|
||||
position,
|
||||
busy,
|
||||
cancel,
|
||||
remove,
|
||||
}: {
|
||||
position: Position;
|
||||
busy: boolean;
|
||||
cancel: () => void;
|
||||
remove: (name: string) => void;
|
||||
}) {
|
||||
const [impact, setImpact] = useState<Impact | null>(null),
|
||||
[name, setName] = useState('');
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
void api<Impact>('/positions/' + position.id + '/deletion')
|
||||
.then((v) => {
|
||||
if (active) setImpact(v);
|
||||
})
|
||||
.catch((e) => {
|
||||
if (active) showToast(e.message, 'error');
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [position.id]);
|
||||
return (
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (impact?.canDelete && name === impact.name && !busy) remove(name);
|
||||
}}
|
||||
>
|
||||
<h3>删除账户「{position.name}」</h3>
|
||||
{!impact ? (
|
||||
<p>正在检查关联记录…</p>
|
||||
) : (
|
||||
<>
|
||||
<p>
|
||||
删除后将移除该账户、{impact.historyCount} 条余额历史及 {impact.linkCount}{' '}
|
||||
个债务关联。资产总览、趋势和收支日历将同步更新,无法撤销。
|
||||
</p>
|
||||
{!impact.canDelete ? (
|
||||
<div className="agent-warning" role="status">
|
||||
<strong>请先处理账户引用</strong>
|
||||
<p>
|
||||
还有 {impact.movementCount} 条资金往来、{impact.scheduleCount}{' '}
|
||||
个定时计划。请先撤销相关资金往来并删除相关计划,再删除账户。若需要保留历史,可改用归档。
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<label>
|
||||
输入完整账户名称确认删除
|
||||
<input
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
autoComplete="off"
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<div className="modal-actions">
|
||||
<button type="button" className="secondary" disabled={busy} onClick={cancel}>
|
||||
返回
|
||||
</button>
|
||||
<button
|
||||
className="primary danger"
|
||||
disabled={busy || !impact?.canDelete || name !== impact.name}
|
||||
>
|
||||
删除账户
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
+434
-654
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,416 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { api, money } from './api';
|
||||
import { showToast } from './Toast';
|
||||
import {
|
||||
displayValue,
|
||||
fieldLabels,
|
||||
permissionLabel,
|
||||
statusLabel,
|
||||
toolLabel,
|
||||
type Reference,
|
||||
} from './agent-display';
|
||||
type Consent = {
|
||||
id: string;
|
||||
name: string;
|
||||
scopes: string[];
|
||||
redirectUri: string;
|
||||
resource: string;
|
||||
};
|
||||
type Preview = {
|
||||
operationId: string;
|
||||
tool: string;
|
||||
status: string;
|
||||
description: string;
|
||||
expiresAt: string;
|
||||
connectionName: string;
|
||||
destructive: boolean;
|
||||
impact: {
|
||||
parameters: Record<string, unknown>;
|
||||
references: Record<string, Reference>;
|
||||
current?: Record<string, unknown>;
|
||||
};
|
||||
result?: unknown;
|
||||
};
|
||||
function ReviewError({ message, retry }: { message: string; retry: () => void }) {
|
||||
return (
|
||||
<section className="panel">
|
||||
<h2>暂时无法加载</h2>
|
||||
<p>{message}</p>
|
||||
<button className="secondary" onClick={retry}>
|
||||
重新加载
|
||||
</button>{' '}
|
||||
<a href="/">返回资产空间</a>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
export function AgentAuthorization({ id }: { id: string | null }) {
|
||||
const [consent, setConsent] = useState<Consent | null>(null),
|
||||
[level, setLevel] = useState('read'),
|
||||
[days, setDays] = useState('30'),
|
||||
[hiddenRead, setHiddenRead] = useState(false),
|
||||
[hiddenWrite, setHiddenWrite] = useState(false),
|
||||
[busy, setBusy] = useState(false),
|
||||
[error, setError] = useState(''),
|
||||
[reload, setReload] = useState(0);
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
setConsent(null);
|
||||
setError('');
|
||||
setLevel('read');
|
||||
setDays('30');
|
||||
setHiddenRead(false);
|
||||
setHiddenWrite(false);
|
||||
if (!id) {
|
||||
setError('授权链接缺少请求编号,请从客户端重新发起连接。');
|
||||
return;
|
||||
}
|
||||
void api<Consent>('/agent/authorizations/' + id)
|
||||
.then((v) => {
|
||||
if (active) setConsent(v);
|
||||
})
|
||||
.catch((e) => {
|
||||
if (active) setError(e.message);
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [id, reload]);
|
||||
const selected =
|
||||
consent?.scopes.filter(
|
||||
(s) =>
|
||||
s === 'read' ||
|
||||
s === level ||
|
||||
(s === 'hidden_read' && hiddenRead) ||
|
||||
(s === 'hidden_write' && hiddenWrite && hiddenRead && level !== 'read'),
|
||||
) || [];
|
||||
async function decide(approve: boolean) {
|
||||
if (!consent || busy) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const v = await api<{ redirect: string }>('/agent/authorizations/' + consent.id, 'POST', {
|
||||
approve,
|
||||
scopes: selected,
|
||||
days: days === 'permanent' ? null : Number(days),
|
||||
});
|
||||
location.assign(v.redirect);
|
||||
} catch (e) {
|
||||
showToast(e instanceof Error ? e.message : '授权失败', 'error');
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
if (error) return <ReviewError message={error} retry={() => setReload((v) => v + 1)} />;
|
||||
if (!consent)
|
||||
return (
|
||||
<section className="panel">
|
||||
<p>正在读取连接请求…</p>
|
||||
</section>
|
||||
);
|
||||
return (
|
||||
<section className="panel agent-consent-card">
|
||||
<span className="badge">连接授权</span>
|
||||
<h1>允许「{consent.name}」连接 WorthPath?</h1>
|
||||
<p className="muted">选择它可以访问的范围。你可以随时在连接管理中撤销授权。</p>
|
||||
<div className="agent-permission-choices" role="group" aria-label="连接权限">
|
||||
{[
|
||||
['read', '只读查询', '查看账户和统计,无法修改账目。'],
|
||||
['draft', '草稿修改', '提出修改,由你逐项确认后执行。'],
|
||||
['write', '直接写入', '普通账目修改立即执行,无需逐次确认。'],
|
||||
]
|
||||
.filter(([key]) => consent.scopes.includes(key))
|
||||
.map(([key, title, detail]) => (
|
||||
<button
|
||||
key={key}
|
||||
className={level === key ? 'permission-choice selected' : 'permission-choice'}
|
||||
disabled={busy}
|
||||
aria-pressed={level === key}
|
||||
onClick={() => {
|
||||
setLevel(key);
|
||||
if (key === 'read') setHiddenWrite(false);
|
||||
}}
|
||||
>
|
||||
<strong>{title}</strong>
|
||||
<span>{detail}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<label className="agent-duration">
|
||||
授权有效期
|
||||
<select value={days} disabled={busy} onChange={(e) => setDays(e.target.value)}>
|
||||
{[
|
||||
['1', '1 天'],
|
||||
['3', '3 天'],
|
||||
['7', '7 天'],
|
||||
['30', '30 天'],
|
||||
['365', '1 年(365 天)'],
|
||||
['permanent', '永久(可撤销)'],
|
||||
].map(([value, label]) => (
|
||||
<option key={value} value={value}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<small>有限期限到期后重新授权;永久授权仍可随时撤销。</small>
|
||||
</label>
|
||||
{consent.scopes.includes('hidden_read') && (
|
||||
<fieldset className="agent-scope-options">
|
||||
<legend>隐藏账户(默认不授权)</legend>
|
||||
<label className="check-line">
|
||||
<input
|
||||
type="checkbox"
|
||||
disabled={busy}
|
||||
checked={hiddenRead}
|
||||
onChange={(e) => {
|
||||
setHiddenRead(e.target.checked);
|
||||
if (!e.target.checked) setHiddenWrite(false);
|
||||
}}
|
||||
/>
|
||||
允许读取隐藏账户
|
||||
</label>
|
||||
{consent.scopes.includes('hidden_write') && (
|
||||
<label className="check-line">
|
||||
<input
|
||||
type="checkbox"
|
||||
disabled={busy || !hiddenRead || level === 'read'}
|
||||
checked={hiddenWrite}
|
||||
onChange={(e) => setHiddenWrite(e.target.checked)}
|
||||
/>
|
||||
允许修改隐藏账户
|
||||
</label>
|
||||
)}
|
||||
</fieldset>
|
||||
)}
|
||||
<div className="agent-final-permission" role="status">
|
||||
<strong>最终授权:{permissionLabel(selected)}</strong>
|
||||
<span>
|
||||
授权期限:
|
||||
{days === 'permanent'
|
||||
? '永久(可撤销)'
|
||||
: days === '365'
|
||||
? '1 年(365 天)'
|
||||
: days + ' 天'}
|
||||
</span>
|
||||
<span>
|
||||
隐藏账户:{hiddenRead ? (hiddenWrite ? '可读取和修改' : '仅可读取') : '不可访问'}
|
||||
</span>
|
||||
</div>
|
||||
<details className="agent-details">
|
||||
<summary>核对客户端与授权地址</summary>
|
||||
<dl className="agent-fields">
|
||||
<dt>服务地址</dt>
|
||||
<dd>{consent.resource}</dd>
|
||||
<dt>回调地址</dt>
|
||||
<dd>{consent.redirectUri}</dd>
|
||||
<dt>候选权限</dt>
|
||||
<dd>{consent.scopes.join(', ')}</dd>
|
||||
<dt>最终权限代码</dt>
|
||||
<dd>{selected.join(', ')}</dd>
|
||||
</dl>
|
||||
<p>客户端请求的是候选范围;最终仅授予上方选中的权限。只批准你正在连接的客户端。</p>
|
||||
</details>
|
||||
<div className="modal-actions">
|
||||
<button className="secondary" disabled={busy} onClick={() => void decide(false)}>
|
||||
拒绝授权
|
||||
</button>
|
||||
<button
|
||||
className="primary"
|
||||
disabled={busy || !selected.includes('read')}
|
||||
onClick={() => void decide(true)}
|
||||
>
|
||||
{busy ? '正在处理…' : '授权此连接'}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
function Fields({
|
||||
data,
|
||||
references,
|
||||
currency,
|
||||
receivedCurrency,
|
||||
liability = false,
|
||||
}: {
|
||||
data: unknown;
|
||||
references: Record<string, Reference>;
|
||||
currency?: string;
|
||||
receivedCurrency?: string;
|
||||
liability?: boolean;
|
||||
}) {
|
||||
if (data === null || typeof data !== 'object' || Array.isArray(data))
|
||||
return <p>{displayValue(data, references)}</p>;
|
||||
const entries = Object.entries(data as Record<string, unknown>);
|
||||
const object = data as Record<string, unknown>;
|
||||
const localCurrency =
|
||||
typeof object.currency === 'string'
|
||||
? object.currency
|
||||
: references[String(object.sourceId || object.id || '')]?.currency || currency;
|
||||
const targetCurrency =
|
||||
references[String(object.targetId || '')]?.currency || receivedCurrency || localCurrency;
|
||||
return (
|
||||
<dl className="agent-fields">
|
||||
{entries.map(([key, value]) => {
|
||||
if (value && typeof value === 'object' && !Array.isArray(value))
|
||||
return (
|
||||
<div className="agent-field-section" key={key}>
|
||||
<h3>{key === 'data' ? '修改内容' : fieldLabels[key] || key}</h3>
|
||||
<Fields
|
||||
data={value}
|
||||
references={references}
|
||||
currency={localCurrency}
|
||||
receivedCurrency={targetCurrency}
|
||||
liability={liability}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
const amount =
|
||||
['amount', 'received', 'fee', 'metalCostPerGram', 'costPerGram'].includes(key) &&
|
||||
typeof value === 'string' &&
|
||||
/^-?\d+(\.\d+)?$/.test(value);
|
||||
let shown = displayValue(value, references);
|
||||
const fieldCurrency = key === 'received' ? targetCurrency : localCurrency;
|
||||
if (amount && fieldCurrency) {
|
||||
let v = String(value);
|
||||
if (key === 'amount' && liability && !/^-?0(\.0+)?$/.test(v))
|
||||
v = v.startsWith('-') ? v.slice(1) : '-' + v;
|
||||
shown = money(v, fieldCurrency);
|
||||
}
|
||||
return (
|
||||
<div className="agent-field" key={key}>
|
||||
<dt>{fieldLabels[key] || key}</dt>
|
||||
<dd>{shown}</dd>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</dl>
|
||||
);
|
||||
}
|
||||
export function AgentOperation({ id }: { id: string | null }) {
|
||||
const [preview, setPreview] = useState<Preview | null>(null),
|
||||
[error, setError] = useState(''),
|
||||
[busy, setBusy] = useState(false),
|
||||
[reload, setReload] = useState(0),
|
||||
[now, setNow] = useState(Date.now());
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
setPreview(null);
|
||||
setError('');
|
||||
if (!id) {
|
||||
setError('草稿链接缺少操作编号,请从操作记录重新打开。');
|
||||
return;
|
||||
}
|
||||
void api<Preview>('/agent/operations/' + id)
|
||||
.then((v) => {
|
||||
if (active) setPreview(v);
|
||||
})
|
||||
.catch((e) => {
|
||||
if (active) setError(e.message);
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [id, reload]);
|
||||
useEffect(() => {
|
||||
const timer = setInterval(() => setNow(Date.now()), 1000);
|
||||
return () => clearInterval(timer);
|
||||
}, []);
|
||||
async function decide(approve: boolean) {
|
||||
if (!preview || busy) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
await api('/agent/operations/' + preview.operationId, 'POST', { approve });
|
||||
setPreview(await api<Preview>('/agent/operations/' + preview.operationId));
|
||||
showToast(approve ? '修改已完成,Agent 可以查询结果' : '草稿已取消', 'success');
|
||||
} catch (e) {
|
||||
showToast(e instanceof Error ? e.message : '操作失败', 'error');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
if (error) return <ReviewError message={error} retry={() => setReload((v) => v + 1)} />;
|
||||
if (!preview)
|
||||
return (
|
||||
<section className="panel">
|
||||
<p>正在读取草稿…</p>
|
||||
</section>
|
||||
);
|
||||
const expired = preview.status === 'pending' && new Date(preview.expiresAt).getTime() <= now;
|
||||
const pending = preview.status === 'pending' && !expired;
|
||||
const params = preview.impact.parameters,
|
||||
refs = preview.impact.references || {};
|
||||
const ref = refs[String(params.id || params.sourceId || '')];
|
||||
const absolute = ['balance_record', 'history_update', 'position_create'].includes(preview.tool);
|
||||
const currency =
|
||||
ref?.currency ||
|
||||
refs[String(preview.impact.current?.sourceId || '')]?.currency ||
|
||||
(typeof params.currency === 'string' ? params.currency : undefined);
|
||||
const receivedCurrency =
|
||||
refs[String(params.targetId || preview.impact.current?.targetId || '')]?.currency;
|
||||
return (
|
||||
<section className="panel agent-consent-card">
|
||||
<span className="badge">{statusLabel(expired ? 'expired' : preview.status)}</span>
|
||||
<h1>{toolLabel(preview.tool)}</h1>
|
||||
<p className="muted">来自连接:{preview.connectionName}</p>
|
||||
{pending && <p>请核对下方内容。确认后修改才会写入账目。</p>}
|
||||
{absolute && (
|
||||
<p className="agent-final-permission">金额为变更后的余额或估值;负债按欠款显示为负数。</p>
|
||||
)}
|
||||
{preview.destructive && (
|
||||
<div className="agent-warning">这项操作会删除记录并重算相关余额,请核对后再确认。</div>
|
||||
)}
|
||||
{preview.impact.current && (
|
||||
<section className="agent-existing">
|
||||
<h3>当前记录</h3>
|
||||
<Fields
|
||||
data={preview.impact.current}
|
||||
references={refs}
|
||||
currency={currency}
|
||||
liability={
|
||||
['balance_record', 'history_update', 'history_delete'].includes(preview.tool) &&
|
||||
ref?.side === 'liability'
|
||||
}
|
||||
/>
|
||||
</section>
|
||||
)}
|
||||
<h3>{preview.destructive ? '操作对象' : '提交的修改'}</h3>
|
||||
<Fields
|
||||
data={params}
|
||||
references={refs}
|
||||
currency={currency}
|
||||
receivedCurrency={receivedCurrency}
|
||||
liability={absolute && (ref?.side === 'liability' || params.side === 'liability')}
|
||||
/>
|
||||
{pending && (
|
||||
<p className="muted">
|
||||
有效至{' '}
|
||||
{new Date(preview.expiresAt).toLocaleString('zh-CN', { timeZone: 'Asia/Hong_Kong' })}
|
||||
(UTC+8)。账目发生变化时,需要 Agent 重新创建草稿。
|
||||
</p>
|
||||
)}
|
||||
{expired && <p className="agent-warning">草稿已过期,请让 Agent 重新创建。</p>}
|
||||
{preview.status === 'completed' && <p role="status">这项修改已经执行完成。</p>}
|
||||
{preview.result !== undefined && preview.result !== null && (
|
||||
<details className="agent-details">
|
||||
<summary>查看执行结果</summary>
|
||||
<Fields data={preview.result} references={refs} />
|
||||
</details>
|
||||
)}
|
||||
<details className="agent-details">
|
||||
<summary>查看工具说明</summary>
|
||||
<code>{preview.tool}</code>
|
||||
<p>{preview.description}</p>
|
||||
</details>
|
||||
<div className="modal-actions">
|
||||
<a href="/">返回资产空间</a>
|
||||
{pending && (
|
||||
<>
|
||||
<button className="secondary" disabled={busy} onClick={() => void decide(false)}>
|
||||
取消草稿
|
||||
</button>
|
||||
<button className="primary" disabled={busy} onClick={() => void decide(true)}>
|
||||
{busy ? '正在处理…' : '确认执行'}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
+65
-16
@@ -54,6 +54,8 @@ import { orderedGroups, mergeGroupOrder } from './group-order';
|
||||
import { Calendar } from './Calendar';
|
||||
import { SchedulePanel } from './SchedulePanel';
|
||||
import { AgentConnections } from './AgentConnections';
|
||||
import { AgentAuthorization, AgentOperation } from './AgentReview';
|
||||
import { AccountDeletion } from './AccountDeletion';
|
||||
import { IconPicker } from './IconPicker';
|
||||
import { MetalPanel } from './MetalPanel';
|
||||
import { QuickTransfer } from './QuickTransfer';
|
||||
@@ -233,7 +235,7 @@ export default function App() {
|
||||
[page, setPage] = useState(
|
||||
new URLSearchParams(location.search).has('agent_authorization') ||
|
||||
new URLSearchParams(location.search).has('agent_operation')
|
||||
? 'settings'
|
||||
? 'agent-review'
|
||||
: 'overview',
|
||||
),
|
||||
[positions, setPositions] = useState<Position[]>([]),
|
||||
@@ -693,7 +695,7 @@ export default function App() {
|
||||
const agentReturn =
|
||||
new URLSearchParams(location.search).has('agent_authorization') ||
|
||||
new URLSearchParams(location.search).has('agent_operation');
|
||||
setPage(agentReturn ? 'settings' : 'overview');
|
||||
setPage(agentReturn ? 'agent-review' : 'overview');
|
||||
if (agentReturn) setSettingsSection('agent');
|
||||
setSelected(null);
|
||||
setModal(null);
|
||||
@@ -878,6 +880,30 @@ export default function App() {
|
||||
if (session === sessionGeneration.current) setBusy(false);
|
||||
}
|
||||
}
|
||||
const agentParams = new URLSearchParams(location.search);
|
||||
if (
|
||||
agentParams.has('agent_authorization') ||
|
||||
agentParams.has('agent_operation') ||
|
||||
location.pathname === '/agent/authorize' ||
|
||||
location.pathname === '/agent/operation'
|
||||
) {
|
||||
return (
|
||||
<main className="agent-review-page">
|
||||
<header className="agent-review-header">
|
||||
<a href="/">WorthPath</a>
|
||||
<span>{user.username}</span>
|
||||
<button className="text" disabled={busy} onClick={() => void logout()}>
|
||||
退出登录
|
||||
</button>
|
||||
</header>
|
||||
{agentParams.has('agent_authorization') || location.pathname === '/agent/authorize' ? (
|
||||
<AgentAuthorization id={agentParams.get('agent_authorization')} />
|
||||
) : (
|
||||
<AgentOperation id={agentParams.get('agent_operation')} />
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
const nav = [
|
||||
['overview', LayoutDashboard],
|
||||
['account', Wallet],
|
||||
@@ -1341,6 +1367,15 @@ export default function App() {
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{p.kind === 'account' && (
|
||||
<button
|
||||
className="secondary danger-text"
|
||||
disabled={busy}
|
||||
onClick={() => setModal({ kind: 'delete-account', p })}
|
||||
>
|
||||
删除账户
|
||||
</button>
|
||||
)}
|
||||
<button className="secondary" onClick={() => setModal({ kind: 'edit', p })}>
|
||||
{tr('编辑资料')}
|
||||
</button>
|
||||
@@ -2572,25 +2607,39 @@ export default function App() {
|
||||
? modal.p?.kind === 'debt'
|
||||
? operationLabel(modal.p.side === 'asset' ? 'collect' : 'repay')
|
||||
: tr('收款 / 还款')
|
||||
: modal.kind === 'transfer'
|
||||
? tr('转账')
|
||||
: modal.kind === 'reveal'
|
||||
? tr('验证密码以显示隐藏资产')
|
||||
: modal.kind === 'edit'
|
||||
? tr('编辑项目')
|
||||
: modal.kind === 'revision'
|
||||
? tr('更新余额 / 估值')
|
||||
: modal.kind === 'correction'
|
||||
? tr('更正历史记录')
|
||||
: modal.kind === 'links'
|
||||
? tr('管理债务关联')
|
||||
: tr('新增') + tr(labels[modal.kind])
|
||||
: modal.kind === 'delete-account'
|
||||
? '删除账户'
|
||||
: modal.kind === 'transfer'
|
||||
? tr('转账')
|
||||
: modal.kind === 'reveal'
|
||||
? tr('验证密码以显示隐藏资产')
|
||||
: modal.kind === 'edit'
|
||||
? tr('编辑项目')
|
||||
: modal.kind === 'revision'
|
||||
? tr('更新余额 / 估值')
|
||||
: modal.kind === 'correction'
|
||||
? tr('更正历史记录')
|
||||
: modal.kind === 'links'
|
||||
? tr('管理债务关联')
|
||||
: tr('新增') + tr(labels[modal.kind])
|
||||
}
|
||||
close={() => {
|
||||
if (!busy) setModal(null);
|
||||
}}
|
||||
>
|
||||
{['transfer', 'debt-payment'].includes(modal.kind) ? (
|
||||
{modal.kind === 'delete-account' && modal.p ? (
|
||||
<AccountDeletion
|
||||
position={modal.p}
|
||||
busy={busy}
|
||||
cancel={() => setModal(null)}
|
||||
remove={(confirmation) =>
|
||||
void act(async () => {
|
||||
await api('/positions/' + modal.p!.id, 'DELETE', { confirmation });
|
||||
setSelected(null);
|
||||
}, '账户已删除')
|
||||
}
|
||||
/>
|
||||
) : ['transfer', 'debt-payment'].includes(modal.kind) ? (
|
||||
movementLoading ? (
|
||||
<p>{tr('正在刷新数据…')}</p>
|
||||
) : modal.kind === 'transfer' ? (
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
export const toolLabels: Record<string, string> = {
|
||||
schedule_toggle: '启用或暂停计划',
|
||||
metal_holding_create: '新增贵金属持仓',
|
||||
metal_value: '按参考价更新贵金属估值',
|
||||
metals_prices: '查询贵金属参考价',
|
||||
connection_revoke: '撤销当前连接',
|
||||
position_create: '新增账户、资产或债务',
|
||||
position_update: '修改项目资料',
|
||||
balance_record: '更新余额或估值',
|
||||
history_update: '更正余额历史',
|
||||
history_delete: '删除余额历史',
|
||||
debt_links_set: '更新债务关联',
|
||||
movement_create: '记录资金往来',
|
||||
movement_update: '修改资金往来',
|
||||
movement_delete: '撤销资金往来',
|
||||
schedule_create: '新增定时计划',
|
||||
schedule_update: '修改定时计划',
|
||||
schedule_delete: '删除定时计划',
|
||||
schedules_run: '执行到期计划',
|
||||
schedule_run: '执行到期计划',
|
||||
settings_update: '更新偏好设置',
|
||||
account_groups_order: '调整账户分组顺序',
|
||||
icon_publish: '保存私有图标',
|
||||
metal_configure: '设置贵金属持仓',
|
||||
metal_holding_update: '更新贵金属克数',
|
||||
positions_list: '查询账户、资产和债务',
|
||||
position_get: '查看项目详情',
|
||||
history_list: '查询余额历史',
|
||||
overview_get: '查看资产总览',
|
||||
trend_get: '查看净资产趋势',
|
||||
movements_list: '查询资金往来',
|
||||
movement_by_revision: '查看关联资金往来',
|
||||
calendar_month: '查看月度收支',
|
||||
calendar_day: '查看每日收支',
|
||||
schedules_list: '查看定时计划',
|
||||
schedule_runs: '查看计划执行记录',
|
||||
settings_get: '读取偏好设置',
|
||||
rates_list: '查询汇率',
|
||||
metals_list: '查询贵金属参考价',
|
||||
icons_list: '查询图标库',
|
||||
connection_info: '查看连接权限',
|
||||
state_get: '核对账目状态',
|
||||
operation_get: '查询草稿结果',
|
||||
file_upload_request: '上传私有图标',
|
||||
file_status: '查询上传状态',
|
||||
icon_image: '读取图标',
|
||||
};
|
||||
export const statusLabels: Record<string, string> = {
|
||||
pending: '待确认',
|
||||
completed: '已完成',
|
||||
cancelled: '已取消',
|
||||
expired: '已过期',
|
||||
failed: '失败',
|
||||
success: '成功',
|
||||
error: '失败',
|
||||
denied: '已拒绝',
|
||||
};
|
||||
export function toolLabel(name: string) {
|
||||
return toolLabels[name] || '账目操作';
|
||||
}
|
||||
export function statusLabel(status: string) {
|
||||
return statusLabels[status] || status;
|
||||
}
|
||||
export function permissionLabel(scopes: string[]) {
|
||||
return scopes.includes('write') ? '直接写入' : scopes.includes('draft') ? '草稿修改' : '只读查询';
|
||||
}
|
||||
export const fieldLabels: Record<string, string> = {
|
||||
status: '状态',
|
||||
message: '处理说明',
|
||||
createdAt: '创建时间',
|
||||
updatedAt: '更新时间',
|
||||
effectiveDate: '业务时间',
|
||||
data: '修改内容',
|
||||
nextAt: '下次执行时间',
|
||||
intervalDays: '间隔天数(0 为一次)',
|
||||
scheduled_expense: '计划支出',
|
||||
maxRuns: '最多执行次数',
|
||||
repeat: '重复规则',
|
||||
nextRunAt: '下次执行时间',
|
||||
id: '项目',
|
||||
positionId: '项目',
|
||||
sourceId: '转出账户',
|
||||
targetId: '转入项目',
|
||||
revisionId: '历史记录',
|
||||
name: '名称',
|
||||
kind: '类型',
|
||||
side: '资产属性',
|
||||
category: '分类',
|
||||
groupName: '账户分组',
|
||||
currency: '币种',
|
||||
amount: '金额',
|
||||
received: '到账金额',
|
||||
fee: '手续费',
|
||||
date: '业务时间',
|
||||
notes: '备注',
|
||||
reason: '变更原因',
|
||||
operation: '操作类型',
|
||||
archived: '归档',
|
||||
hidden: '隐藏',
|
||||
included: '计入总览',
|
||||
iconId: '图标',
|
||||
targetIds: '关联项目',
|
||||
groups: '分组顺序',
|
||||
metalType: '贵金属品种',
|
||||
grams: '重量(克)',
|
||||
metalGrams: '重量(克)',
|
||||
costPerGram: '每克买入成本',
|
||||
metalCostPerGram: '每克买入成本',
|
||||
enabled: '启用计划',
|
||||
frequency: '执行频率',
|
||||
interval: '间隔',
|
||||
nextDate: '下次执行时间',
|
||||
startDate: '开始时间',
|
||||
endDate: '结束时间',
|
||||
dayOfMonth: '每月执行日',
|
||||
baseCurrency: '本位币',
|
||||
showNotes: '显示备注',
|
||||
hiddenMenus: '隐藏菜单',
|
||||
overviewCards: '总览卡片',
|
||||
includeIndependentAssets: '独立资产计入总览',
|
||||
accountGroupOrder: '分组顺序',
|
||||
ok: '执行成功',
|
||||
executed: '已执行次数',
|
||||
errors: '执行异常',
|
||||
hasMore: '仍有待执行计划',
|
||||
};
|
||||
export const valueLabels: Record<string, string> = {
|
||||
account: '账户',
|
||||
asset: '资产',
|
||||
liability: '负债',
|
||||
debt: '债务',
|
||||
bank: '银行账户',
|
||||
cash: '现金',
|
||||
investment: '投资账户',
|
||||
credit_card: '信用卡',
|
||||
loan: '贷款账户',
|
||||
other: '其他',
|
||||
gold: '黄金',
|
||||
silver: '白银',
|
||||
property: '房产',
|
||||
vehicle: '车辆',
|
||||
personal: '个人借款',
|
||||
transfer: '转账',
|
||||
borrow: '借入',
|
||||
lend: '借出',
|
||||
repay: '还款',
|
||||
collect: '收款',
|
||||
expense: '支出',
|
||||
initial: '初始余额',
|
||||
balance: '余额更新',
|
||||
valuation: '估值更新',
|
||||
correction: '历史更正',
|
||||
repayment: '还款',
|
||||
daily: '每天',
|
||||
weekly: '每周',
|
||||
monthly: '每月',
|
||||
};
|
||||
export type Reference = { name: string; currency: string; side: string; kind: string };
|
||||
export function displayValue(value: unknown, references: Record<string, Reference> = {}): string {
|
||||
if (value === null || value === undefined || value === '') return '未设置';
|
||||
if (typeof value === 'boolean') return value ? '是' : '否';
|
||||
if (Array.isArray(value))
|
||||
return value.length ? value.map((v) => displayValue(v, references)).join('、') : '无';
|
||||
const s = String(value);
|
||||
return references[s]?.name || valueLabels[s] || s;
|
||||
}
|
||||
@@ -2042,3 +2042,229 @@ textarea,
|
||||
.agent-tabs button {
|
||||
min-height: 40px;
|
||||
}
|
||||
|
||||
/* Agent setup and standalone review pages */
|
||||
.agent-review-page {
|
||||
max-width: 880px;
|
||||
margin: 0 auto;
|
||||
padding: 32px 24px 64px;
|
||||
}
|
||||
.agent-review-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 20px;
|
||||
margin-bottom: 32px;
|
||||
}
|
||||
.agent-review-header a {
|
||||
font-size: 22px;
|
||||
font-weight: 800;
|
||||
margin-right: auto;
|
||||
text-decoration: none;
|
||||
color: inherit;
|
||||
}
|
||||
.agent-consent-card h1 {
|
||||
font-size: clamp(24px, 4vw, 32px);
|
||||
line-height: 1.35;
|
||||
margin: 18px 0 12px;
|
||||
}
|
||||
.agent-consent-card > p {
|
||||
line-height: 1.7;
|
||||
}
|
||||
.agent-tabs {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
margin: 24px 0;
|
||||
}
|
||||
.agent-connect-layout {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 2fr) minmax(240px, 1fr);
|
||||
gap: 24px;
|
||||
align-items: start;
|
||||
}
|
||||
.agent-step-number {
|
||||
display: inline-grid;
|
||||
place-items: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 50%;
|
||||
background: #e8f3ef;
|
||||
color: #246952;
|
||||
font-weight: 700;
|
||||
margin-top: 20px;
|
||||
}
|
||||
.agent-setup h3 {
|
||||
margin: 10px 0;
|
||||
}
|
||||
.agent-help {
|
||||
position: sticky;
|
||||
top: 24px;
|
||||
}
|
||||
.agent-permission-choices {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 12px;
|
||||
margin: 20px 0;
|
||||
}
|
||||
.permission-choice {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
text-align: left;
|
||||
gap: 8px;
|
||||
padding: 18px;
|
||||
height: 100%;
|
||||
border: 1px solid #dde4df;
|
||||
border-radius: 14px;
|
||||
background: #fff;
|
||||
color: #24392f;
|
||||
white-space: normal;
|
||||
}
|
||||
.permission-choice span {
|
||||
font-size: 13px;
|
||||
line-height: 1.6;
|
||||
color: #617068;
|
||||
}
|
||||
.permission-choice.selected {
|
||||
border-color: #327d60;
|
||||
background: #f0f8f3;
|
||||
box-shadow: inset 0 0 0 1px #327d60;
|
||||
}
|
||||
.agent-final-permission {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
padding: 18px;
|
||||
margin: 24px 0;
|
||||
border-radius: 12px;
|
||||
background: #f0f8f3;
|
||||
color: #2c5d48;
|
||||
}
|
||||
.agent-warning {
|
||||
padding: 16px;
|
||||
border-radius: 12px;
|
||||
background: #fff4e7;
|
||||
color: #8b5013;
|
||||
line-height: 1.6;
|
||||
margin: 20px 0;
|
||||
}
|
||||
.agent-fields {
|
||||
margin: 20px 0;
|
||||
}
|
||||
.agent-field {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(110px, 1fr) minmax(0, 3fr);
|
||||
gap: 20px;
|
||||
padding: 13px 0;
|
||||
border-bottom: 1px solid #e8ece9;
|
||||
}
|
||||
.agent-fields dt {
|
||||
color: #617068;
|
||||
font-size: 14px;
|
||||
}
|
||||
.agent-fields dd {
|
||||
margin: 0;
|
||||
overflow-wrap: anywhere;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
.agent-field-section {
|
||||
padding: 12px 0;
|
||||
}
|
||||
.agent-field-section h3 {
|
||||
font-size: 16px;
|
||||
}
|
||||
.agent-tool-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 14px;
|
||||
margin-top: 20px;
|
||||
}
|
||||
.agent-tool-card {
|
||||
border: 1px solid #e3e9e5;
|
||||
border-radius: 12px;
|
||||
padding: 18px;
|
||||
}
|
||||
.agent-tool-card h4 {
|
||||
margin: 0 0 12px;
|
||||
}
|
||||
.agent-tool-card code {
|
||||
font-size: 12px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.agent-review-link {
|
||||
background: #246952;
|
||||
color: #fff;
|
||||
padding: 10px 16px;
|
||||
border-radius: 10px;
|
||||
text-decoration: none;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.agent-empty {
|
||||
text-align: center;
|
||||
padding: 28px 16px;
|
||||
color: #617068;
|
||||
}
|
||||
.agent-card + .agent-card {
|
||||
margin-top: 20px;
|
||||
}
|
||||
.agent-form .check-line {
|
||||
display: flex;
|
||||
}
|
||||
.agent-consent-card .modal-actions {
|
||||
flex-wrap: wrap;
|
||||
margin-top: 28px;
|
||||
}
|
||||
.agent-secret {
|
||||
user-select: text;
|
||||
}
|
||||
@media (max-width: 760px) {
|
||||
.agent-connect-layout,
|
||||
.agent-permission-choices,
|
||||
.agent-tool-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
.agent-help {
|
||||
position: static;
|
||||
}
|
||||
.agent-review-page {
|
||||
padding: 20px 14px 40px;
|
||||
}
|
||||
.agent-row {
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
}
|
||||
.agent-field {
|
||||
grid-template-columns: minmax(90px, 1fr) minmax(0, 2fr);
|
||||
gap: 12px;
|
||||
}
|
||||
}
|
||||
|
||||
.agent-consent-card .agent-scope-options .check-line {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
.agent-consent-card .check-line input[type='checkbox'],
|
||||
.agent-form .check-line input[type='checkbox'] {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
min-height: 18px;
|
||||
padding: 0;
|
||||
flex: 0 0 18px;
|
||||
}
|
||||
.agent-existing {
|
||||
padding: 16px;
|
||||
background: #f8faf8;
|
||||
border-radius: 12px;
|
||||
margin: 20px 0;
|
||||
}
|
||||
|
||||
.agent-setup .agent-scope-options .check-line {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.agent-setup .check-line input[type='checkbox'] {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
flex: 0 0 18px;
|
||||
}
|
||||
@@ -240,7 +240,7 @@
|
||||
{
|
||||
"TABLE_NAME": "agentgrant",
|
||||
"COLUMN_NAME": "refreshExpiresAt",
|
||||
"COLUMN_COMMENT": "刷新授权到期时间,UTC"
|
||||
"COLUMN_COMMENT": "刷新授权到期时间,UTC;空表示永久 OAuth 授权或个人令牌不适用"
|
||||
},
|
||||
{
|
||||
"TABLE_NAME": "agentgrant",
|
||||
|
||||
+6
-2
@@ -22,13 +22,13 @@ OAuth 使用发现元数据、动态注册的公开客户端、授权码、S256
|
||||
|
||||
敏感操作(密码/账号修改、清空、备份导出恢复、公开图标发布、安全设置变更)仅在网站进行,不存在 sensitive scope。汇率和参考报价可以查询,MCP 不能修改或主动刷新。贵金属仍可按克数创建、设置成本和重量,并用已有报价更新资产估值;估值历史与报价是不同业务。
|
||||
|
||||
个人访问令牌仅作为支持自定义 Bearer 头客户端的补充。在网站验证当前密码,选择权限和 1、3、7、30 天、365 天或永久。完整值仅创建时展示,数据库只存 SHA-256 摘要。永久令牌数据库到期日为空,每个请求仍重新检查撤销和资源;为兼容 SDK 中间件,每次认证上下文有有限期验证断言,不改变令牌期限。永久令牌内部业务会话按天续期。OAuth 访问令牌一小时、刷新授权三十天,刷新时轮换摘要;不支持永久 OAuth。
|
||||
个人访问令牌仅作为支持自定义 Bearer 头客户端的补充。在网站验证当前密码,选择权限和 1、3、7、30 天、365 天或永久。完整值仅创建时展示,数据库只存 SHA-256 摘要。永久令牌数据库到期日为空,每个请求仍重新检查撤销和资源;为兼容 SDK 中间件,每次认证上下文有有限期验证断言,不改变令牌期限。永久令牌内部业务会话按天续期。OAuth 授权页可选择 1、3、7、30、365 天或永久,默认 30 天。访问令牌最长一小时且不超过有限授权期限;刷新时轮换摘要,不延长原授权期限。永久授权仍可撤销,内部业务会话有界并在刷新时重建。
|
||||
|
||||
旧连接有 write 时,现在直接执行普通修改;旧全局策略不再阻止它。只想创建草稿时,撤销旧连接并重新授权 read draft。历史策略行保留但不参与任何权限判断;旧敏感工具草稿不可提交。
|
||||
|
||||
## 页面复制提示词配置
|
||||
|
||||
在「设置与备份 → 连接 Agent → 开始连接」选择申请权限(默认 read,draft),点击「复制 Codex 配置提示词」,发送给运行在本机、能够执行命令的 Codex。提示词明确授权它仅配置 worthpath 连接、使用 OAuth、保留其他配置并核对实际工具加载;命令由 Codex 执行,用户无需手动输入。用户仍须完成 WorthPath 网页登录和权限确认,当前会话无法加载新增工具时须重启客户端或新建会话。提示词不包含个人令牌,也不会修改账目。
|
||||
在「设置与备份 → 连接 Agent」复制实际 MCP 地址和“Agent 使用教程”。支持远程 OAuth 的客户端填写此地址,选择 Streamable HTTP;在 WorthPath 网页登录,审核客户端名称、回调地址、资源,并选择连接权限。网页会回到已注册的精确回调地址并保留 state。客户端自行验证 state。
|
||||
|
||||
权限选择只改变申请内容,不会立即改变现有连接授权;最终以网页确认和 connection_info 为准。这是可执行的配置指令,不是浏览器一键注册客户端;客户端缺少本机执行能力时需如实说明限制。
|
||||
|
||||
@@ -128,3 +128,7 @@ cd E:\WorthPath
|
||||
申请草稿模式时选择“草稿修改(网页确认)”,不勾选隐藏账户;最终将授予应显示 read,draft。授权后用 connection_info 核对实际 scopes 仅有两项、readHidden/writeHidden 均 false。不要仅因默认请求包含全部候选权限就停止登录,最终批准仍由用户完成。
|
||||
|
||||
新增可选真实客户端回归:apps/api/test/codex-oauth.test.ts。设置 CODEX_CLI 为本机官方 Codex 可执行文件路径,然后运行 pnpm --filter @worthpath/api test:mcp:codex。前置为可访问的开发 API/MySQL,支持 TEST_API_URL/MCP_PUBLIC_URL/WEB_ORIGIN。测试使用独立临时 CODEX_HOME 与账号,不使用真实客户端凭据;两个测试分别覆盖显式和默认请求,最终 grant 仅 read,draft、39 工具发现、隐藏权限关闭和普通修改返回 pending 且没有 position 入账。自动清理临时凭据、账号与注册。两项实际通过;没有验证用户真实桌面聊天内工具调用。
|
||||
|
||||
### 独立审核页面与草稿预览
|
||||
|
||||
OAuth 审核使用 /agent/authorize,草稿确认使用 /agent/operation;旧查询参数链接仍兼容。审核页显示申请范围、最终权限与授权期限。草稿按中文字段展示账户名称、金额、日期、备注及已有记录,用户确认后执行;过期或状态发生变化时不能提交。能力页面支持搜索,技术说明默认折叠。
|
||||
@@ -0,0 +1,20 @@
|
||||
# 账户删除与 Agent 连接更新(2026-10-04)
|
||||
|
||||
- 账户详情新增删除入口,先展示将删除的余额历史、资产关联数量,输入完整账户名称才允许删除。关联转账或计划时先处理关联记录,避免影响其他账户余额。删除校验用户归属和隐藏账户权限;独立资产、负债使用各自已有流程。
|
||||
- OAuth 授权与草稿确认使用独立页面,登录后保持待审核链接,旧链接继续兼容。
|
||||
- 草稿改为中文字段及账户名称,显示原记录与修改内容,保留金额精度、负债符号和跨币种单位;显示过期、取消、确认和执行结果。
|
||||
- Agent 页面分为连接助手、我的连接、草稿记录、能力权限;连接采用步骤向导,能力可搜索,技术内容折叠展示。
|
||||
- OAuth 期限支持 1、3、7、30、365 天和永久,默认 30 天。访问令牌最长一小时,有限授权到期后无法刷新或访问,刷新不延长授权。永久授权可撤销,刷新时重建有界业务会话。
|
||||
- 连接助手可申请隐藏账户读取、修改权限,默认关闭;修改必须同时允许读取,且不能用于只读模式。配置提示词携带申请范围,最终以网页审核及 connection_info 为准。
|
||||
|
||||
## 数据库
|
||||
|
||||
应用 20261004110000_oauth_duration_comment 迁移,更新 AgentGrant.refreshExpiresAt 注释;空值表示永久 OAuth 授权或个人令牌不适用。无需新增表和字段。
|
||||
|
||||
## 验证
|
||||
|
||||
完成类型检查、生产构建、单元测试、真实 MySQL 业务集成测试及 OAuth/MCP 测试。覆盖账户删除级联和关联保护、跨用户与隐藏权限、草稿引用隔离、所有固定期限、永久授权、刷新轮换、到期和撤销。浏览器验证独立审核、可读草稿确认、删除确认输入和隐藏权限配置;测试使用临时账户,未修改真实用户账目。
|
||||
|
||||
最终验证:39 项单元测试(含工作区已有的 Host 配置测试)、20 项真实 MySQL 集成测试、6 项 OAuth/MCP 测试通过;生产构建与类型检查通过,25 项数据库迁移全部应用。
|
||||
|
||||
复验时当前环境的非本机 HTTP MCP 地址触发既有 HTTPS 校验。验证临时使用 localhost,未修改 .env;使用该非本机地址前仍须配置 HTTPS。
|
||||
@@ -7,8 +7,6 @@
|
||||
> * 数据库的表和字段需要有注释
|
||||
> * 在docs目录不要保存任何图片
|
||||
|
||||
文档图片清理已完成并验证:2026-10-03 21:24(UTC+8)。已删除 `docs` 目录内全部 14 张图片,移除相关 Markdown 图片引用,并在 README 中注明文档保存约定。
|
||||
|
||||
更新要求:
|
||||
|
||||
- ~~转出账户余额不足时直接变成负的而不是拒绝转账~~ — 已完成代码更新:2026-10-02 17:37
|
||||
@@ -68,28 +66,14 @@
|
||||
- ~~在账号页的账号卡片中,不需要显示这个卡片的分组~~ — 已完成并验证:2026-10-04 01:43(UTC+8)
|
||||
- ~~删除所有旧备份兼容,仅支持当前 ZIP v9~~ — 已完成并验证:2026-10-04 01:43(UTC+8)
|
||||
- ~~删除单文件 JSON 备份支持,包括 JSON v3~~ — 已完成并验证:2026-10-04 01:43(UTC+8)
|
||||
|
||||
验证与部署边界见 [更新说明](docs/update-2026-10-02.md)。
|
||||
|
||||
数据库验收完成:2026-10-02 17:54。12 个迁移状态最新,31 个内置图标已初始化;28 项单元测试、9 项真实数据库集成检查通过。
|
||||
|
||||
本轮补充验收完成:2026-10-02 18:44。13 个迁移状态最新,34 个内置图标已初始化;28 项单元测试、10 项真实数据库集成检查通过,9 张表与 88 个字段注释已核验。重新检查文档,无新增未完成要求。
|
||||
|
||||
本轮验收完成:2026-10-03 11:22。28 项单元测试、11 项真实 MySQL 集成检查、前后端类型检查与生产构建通过;未新增数据库表或字段。账号、删除与备份更新详情见 [更新说明](docs/update-2026-10-03.md)。重新检查文档,无新增未完成要求。
|
||||
|
||||
负债账户溢缴验收完成:2026-10-03 12:05。30 项单元测试、12 项真实 MySQL 集成检查、类型检查和构建通过;支持信用卡等负债账户正数存款显示及总资产分类,已有数据符号保留。详见 [更新说明](docs/update-credit-balance-2026-10-03.md)。复查发现新增“分组可以排序”,继续处理。
|
||||
|
||||
分组排序验收完成:2026-10-03 12:27。32 项单元测试、13 项真实 MySQL 集成检查、类型检查与构建通过;14 个迁移已应用,9 张表与 89 个字段注释已核验。账户页、筛选与选择弹窗顺序同步并持久化,备份恢复包含分组顺序。详见 [更新说明](docs/update-group-order-2026-10-03.md)。
|
||||
|
||||
图库补充验收完成:2026-10-03 12:36。新增“抖音月付”和“东方财富”图标,36 项内置图库已初始化,两个图标的已认证搜索和图片读取通过。详见 [更新说明](docs/update-icons-2026-10-03.md)。
|
||||
|
||||
分组界面验收完成:2026-10-03 17:04。支持拖拽与键盘调整顺序,全部账户按分组顺序分行显示;33 项单元测试、前端类型检查、生产构建和真实数据库分组排序专项检查通过。详见 [更新说明](docs/update-group-drag-2026-10-03.md)。
|
||||
|
||||
设置与交互验收完成:2026-10-03 17:54。33 项单元检查、15 项真实 MySQL 集成检查、前后端类型检查和生产构建通过;京东金融图标修正后另通过 4 项图标与转账专项回归。15 个迁移已应用,9 张表与 92 个字段注释齐全。登录与隐私、总览卡片、计划弹窗、右上角提示、京东金融 App 图标和快速转账详情见 [更新说明](docs/update-settings-interaction-2026-10-03.md)。复查未发现新增未完成要求。
|
||||
|
||||
账户转账与估价验收完成:2026-10-03 18:56。35 项单元检查、17 项真实 MySQL 集成检查、类型检查和生产构建通过;最终估值去重另通过 4 项专项回归。17 个迁移已应用,10 张表与 106 个字段注释完整。计入开关、黄金/白银估价、ZIP v8 和第三方接口清单详见 [更新说明](docs/update-inclusion-metals-2026-10-03.md) 与 [README](README.md#第三方接口与外部素材来源)。复查未发现新增未完成要求。
|
||||
- ~~修改提示框,全部提示直接在右上角出现弹出提示框~~ — 已完成并通过浏览器成功/认证错误反馈验证:2026-10-04 02:23(UTC+8)
|
||||
- ~~修正 MCP 接入教程误导,补充已验证的 Codex OAuth 配置和 localhost 限制~~ — 已完成:2026-10-04 02:23(UTC+8);CLI 0.160.0 OAuth/DCR 登录及官方 SDK 39 工具发现通过,桌面会话内调用尚未验证。
|
||||
- ~~在连接 Agent 页面提供可直接发送给 Codex 执行配置的提示词,无需用户输入命令~~ — 已完成并通过三档权限复制、前端类型检查与构建:2026-10-04 02:32(UTC+8);网页登录授权由用户完成。
|
||||
- ~~Codex 配置提示词补充 Windows PowerShell 挂起排查与正常权限申请流程~~ — 已完成:2026-10-04 02:42(UTC+8);本机提升权限及无 profile 的 CLI 版本检查通过,前端构建通过。
|
||||
- ~~明确 OAuth 候选与最终授权范围,验证 Codex 请求全部权限时可收窄为 read,draft~~ — 已完成:2026-10-04 02:56(UTC+8);两项真实 CLI OAuth/草稿隔离测试及浏览器权限选择验证通过。
|
||||
- ~~账号添加删除功能~~ — 已完成并验证:2026-10-04 11:03(UTC+8),见 docs/update-agent-accounts-2026-10-04.md
|
||||
- ~~MCP授权页使用单独的一个页面,不用在原来的设置页面~~ — 已完成并验证:2026-10-04 11:03(UTC+8),见 docs/update-agent-accounts-2026-10-04.md
|
||||
- ~~优化MCP草稿确认页面,当前显示的内容是json,不好看~~ — 已完成并验证:2026-10-04 11:03(UTC+8),见 docs/update-agent-accounts-2026-10-04.md
|
||||
- ~~优化MCP页面。当前的有点混乱,技能描述也是,进行大的修改~~ — 已完成并验证:2026-10-04 11:03(UTC+8),见 docs/update-agent-accounts-2026-10-04.md
|
||||
- ~~使用OAuth也要可以设置授权的时间(有固定的选项1 3 7 30day 1yaer 永久)~~ — 已完成并验证:2026-10-04 11:03(UTC+8),见 docs/update-agent-accounts-2026-10-04.md
|
||||
- ~~连接助手可以设置申请隐藏账号权限~~ — 已完成并验证:2026-10-04 11:03(UTC+8),见 docs/update-agent-accounts-2026-10-04.md
|
||||
Reference in new issue
Block a user