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
@@ -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();
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user