Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.
feat(mcp): add the access service for tokens and approved clients
spacesdrive752b69c5e960
diff --git a/backend/services/mcpAccessService.ts b/backend/services/mcpAccessService.tsnew file mode 100644index 0000000..05a5c98--- /dev/null+++ b/backend/services/mcpAccessService.ts@@ -0,0 +1,126 @@+import { accessTokenHint, generateAccessToken, hashAccessToken } from '../lib/mcp/accessToken.ts';+import { ConflictError, ForbiddenError, NotFoundError, UnauthorizedError } from '../lib/errors.ts';+import { newRowId } from '../lib/ids.ts';+import type { McpAccessTokenRepository } from '../repositories/mcpAccessTokenRepository.ts';+import type { McpClientGrantRepository } from '../repositories/mcpClientGrantRepository.ts';+import type { AuditRepository } from '../repositories/auditRepository.ts';+import type { RequestContext } from '../types/context.ts';+import type {+ McpAccessTokenCreateRequest, McpAccessTokenSummary, McpClientGrantSummary, McpPermission,+} from '../../shared/types/mcp.ts';++export interface McpAccessDeps {+ tokens: McpAccessTokenRepository;+ grants: McpClientGrantRepository;+ audit: AuditRepository;+ context: RequestContext;+}++// who is calling the MCP endpoint and what they may do; via names the credential for the audit log+export interface McpPrincipal {+ userId: string;+ permission: McpPermission;+ via: string;+}++export interface CreatedAccessToken {+ token: string;+ summary: McpAccessTokenSummary;+}++export interface ClientApproval {+ clientId: string;+ clientName: string;+ permission: McpPermission;+}++export interface McpAccessService {+ createToken(userId: string, request: McpAccessTokenCreateRequest): Promise<CreatedAccessToken>;+ listTokens(userId: string): Promise<McpAccessTokenSummary[]>;+ revokeToken(userId: string, id: string): Promise<void>;+ authenticateToken(token: string, now?: number): Promise<McpPrincipal>;+ approveClient(userId: string, approval: ClientApproval): Promise<McpClientGrantSummary>;+ listClients(userId: string): Promise<McpClientGrantSummary[]>;+ revokeClient(userId: string, id: string): Promise<void>;+ authorizeClient(userId: string, clientId: string, now?: number): Promise<McpPrincipal>;+}++// enough for every computer and script a person uses; a cap keeps one account from filling the table+export const MAX_ACCESS_TOKENS = 20;+const DAY_MS = 24 * 60 * 60 * 1000;+// last used is a hint for the Settings page, so one write an hour per credential is enough+const LAST_USED_RESOLUTION_MS = 60 * 60 * 1000;++function staleUse(lastUsedAt: string | null, now: number): boolean {+ return !lastUsedAt || now - Date.parse(lastUsedAt) > LAST_USED_RESOLUTION_MS;+}++export function createMcpAccessService({ tokens, grants, audit, context }: McpAccessDeps): McpAccessService {+ const { log } = context;++ // a failed last-used write never blocks the call it describes+ async function noteUse(write: () => Promise<void>): Promise<void> {+ try {+ await write();+ } catch (err) {+ log.warn('could not record when an MCP credential was used', { reason: (err as Error).message });+ }+ }++ return {+ async createToken(userId, { label, permission, expiresInDays }) {+ if ((await tokens.listForUser(userId)).length >= MAX_ACCESS_TOKENS) {+ throw new ConflictError(`You have ${MAX_ACCESS_TOKENS} access tokens. Revoke one you no longer use, then create a new one.`);+ }+ const token = generateAccessToken();+ const expiresAt = expiresInDays === null ? null : new Date(Date.now() + expiresInDays * DAY_MS).toISOString();+ const summary = await tokens.createForUser(userId, {+ id: newRowId(), label, tokenHash: await hashAccessToken(token), tokenHint: accessTokenHint(token), permission, expiresAt,+ });+ await audit.recordForUser(userId, { action: 'mcp_access_token.created', subjectType: 'mcp_access_token', subjectId: summary.id, details: { permission } });+ return { token, summary };+ },++ listTokens: userId => tokens.listForUser(userId),++ async revokeToken(userId, id) {+ if (!await tokens.revokeForUser(id, userId)) throw new NotFoundError('That access token was not found or is already revoked');+ await audit.recordForUser(userId, { action: 'mcp_access_token.revoked', subjectType: 'mcp_access_token', subjectId: id });+ },++ // the same message for an unknown, revoked or expired token, so a caller learns nothing about other tokens+ async authenticateToken(token, now = Date.now()) {+ const found = await tokens.findActiveByHash(await hashAccessToken(token));+ if (!found || (found.expiresAt && Date.parse(found.expiresAt) <= now)) {+ throw new UnauthorizedError('This access token is not valid. Create a new one in Settings, Claude.');+ }+ if (staleUse(found.lastUsedAt, now)) await noteUse(() => tokens.markUsed(found.id, new Date(now).toISOString()));+ return { userId: found.userId, permission: found.permission, via: `token:${found.id}` };+ },++ async approveClient(userId, { clientId, clientName, permission }) {+ const existing = await grants.findForUser(userId, clientId);+ const saved = existing+ ? await grants.updateForUser(existing.id, userId, { clientName, permission })+ : await grants.createForUser(userId, { clientId, clientName, permission });+ if (!saved) throw new NotFoundError('That client approval was removed while it was being saved. Approve the client again.');+ await audit.recordForUser(userId, { action: 'mcp_client.approved', subjectType: 'mcp_client', subjectId: saved.id, details: { clientId, permission } });+ return saved;+ },++ listClients: userId => grants.listForUser(userId),++ async revokeClient(userId, id) {+ if (!await grants.deleteForUser(id, userId)) throw new NotFoundError('That Claude client was not found or was already removed');+ await audit.recordForUser(userId, { action: 'mcp_client.revoked', subjectType: 'mcp_client', subjectId: id });+ },++ // an OAuth token proves who the person is; the grant says this client was approved and how far+ async authorizeClient(userId, clientId, now = Date.now()) {+ const grant = await grants.findForUser(userId, clientId);+ if (!grant) throw new ForbiddenError('This Claude client is not approved for your account. Connect it again and approve it on the Twiligent consent page.');+ if (staleUse(grant.lastUsedAt, now)) await noteUse(() => grants.markUsedForUser(grant.id, userId, new Date(now).toISOString()));+ return { userId, permission: grant.permission, via: `oauth:${clientId}` };+ },+ };+}diff --git a/backend/tests/services/mcpAccessService.test.ts b/backend/tests/services/mcpAccessService.test.tsnew file mode 100644index 0000000..6662c56--- /dev/null+++ b/backend/tests/services/mcpAccessService.test.ts@@ -0,0 +1,81 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { MAX_ACCESS_TOKENS, createMcpAccessService } from '../../services/mcpAccessService.ts';+import { createMcpAccessTokenRepository } from '../../repositories/mcpAccessTokenRepository.ts';+import { createMcpClientGrantRepository } from '../../repositories/mcpClientGrantRepository.ts';+import { createAuditRepository } from '../../repositories/auditRepository.ts';+import { createLogger } from '../../lib/logger.ts';+import { ConflictError, ForbiddenError, NotFoundError, UnauthorizedError } from '../../lib/errors.ts';+import { fakeSupabase } from '../fixtures/fakeSupabase.ts';+import type { Row } from '../fixtures/fakeSupabase.ts';++const DAY_MS = 24 * 60 * 60 * 1000;++function setup(rows: Row[] = []) {+ const db = fakeSupabase(rows);+ const service = createMcpAccessService({+ tokens: createMcpAccessTokenRepository(db),+ grants: createMcpClientGrantRepository(db),+ audit: createAuditRepository(db),+ context: { requestId: 'req-test', signal: new AbortController().signal, log: createLogger() },+ });+ const audits = () => db.table.filter(row => row._table === 'audit_events').map(row => row.action);+ return { db, service, audits };+}++test('a created token signs its owner in with its permission, and the stored row never holds the token', async () => {+ const { db, service, audits } = setup();+ const { token, summary } = await service.createToken('user-1', { label: 'Laptop', permission: 'write', expiresInDays: null });+ assert.match(token, /^twl_/);+ assert.equal(summary.hint, token.slice(-4));+ assert.ok(!JSON.stringify(db.table).includes(token));+ assert.deepEqual(await service.authenticateToken(token), { userId: 'user-1', permission: 'write', via: `token:${summary.id}` });+ assert.deepEqual(audits(), ['mcp_access_token.created']);+});++test('an unknown, revoked or expired token is refused with the same message', async () => {+ const { service } = setup();+ const { token, summary } = await service.createToken('user-1', { label: 'Script', permission: 'read', expiresInDays: 1 });+ await assert.rejects(service.authenticateToken(token, Date.now() + 2 * DAY_MS), UnauthorizedError);+ await assert.rejects(service.authenticateToken('twl_' + 'x'.repeat(43)), UnauthorizedError);+ await service.revokeToken('user-1', summary.id);+ await assert.rejects(service.authenticateToken(token), UnauthorizedError);+});++test('another person cannot revoke a token, and revoking twice says it is gone', async () => {+ const { service } = setup();+ const { summary } = await service.createToken('user-1', { label: 'Laptop', permission: 'read', expiresInDays: null });+ await assert.rejects(service.revokeToken('user-2', summary.id), NotFoundError);+ await service.revokeToken('user-1', summary.id);+ await assert.rejects(service.revokeToken('user-1', summary.id), NotFoundError);+});++test('a person can hold at most the token cap', async () => {+ const { service } = setup();+ for (let i = 0; i < MAX_ACCESS_TOKENS; i++) await service.createToken('user-1', { label: `T${i}`, permission: 'read', expiresInDays: null });+ await assert.rejects(service.createToken('user-1', { label: 'One more', permission: 'read', expiresInDays: null }), ConflictError);+});++test('an OAuth client works only after its person approved it, with the permission they chose last', async () => {+ const { service, audits } = setup();+ await assert.rejects(service.authorizeClient('user-1', 'client-a'), ForbiddenError);+ const first = await service.approveClient('user-1', { clientId: 'client-a', clientName: 'Claude', permission: 'read' });+ assert.equal((await service.authorizeClient('user-1', 'client-a')).permission, 'read');+ const again = await service.approveClient('user-1', { clientId: 'client-a', clientName: 'Claude', permission: 'write' });+ assert.equal(again.id, first.id);+ assert.deepEqual(await service.authorizeClient('user-1', 'client-a'), { userId: 'user-1', permission: 'write', via: 'oauth:client-a' });+ await assert.rejects(service.authorizeClient('user-2', 'client-a'), ForbiddenError);+ await service.revokeClient('user-1', first.id);+ await assert.rejects(service.authorizeClient('user-1', 'client-a'), ForbiddenError);+ assert.deepEqual(audits(), ['mcp_client.approved', 'mcp_client.approved', 'mcp_client.revoked']);+});++test('last used is written at most once an hour per credential', async () => {+ const { db, service } = setup();+ const { token } = await service.createToken('user-1', { label: 'Laptop', permission: 'read', expiresInDays: null });+ const now = Date.now();+ await service.authenticateToken(token, now);+ await service.authenticateToken(token, now + 60_000);+ const writes = db.calls.filter(call => call.table === 'mcp_access_tokens' && call.type === 'update' && call.values && 'last_used_at' in call.values);+ assert.equal(writes.length, 1);+});diff --git a/backend/validators/mcpValidators.ts b/backend/validators/mcpValidators.tsnew file mode 100644index 0000000..31be44c--- /dev/null+++ b/backend/validators/mcpValidators.ts@@ -0,0 +1,23 @@+import { ValidationError } from '../lib/errors.ts';+import { optionalNumber, requiredString } from './fields.ts';+import type { Fields } from './fields.ts';+import type { McpAccessTokenCreateRequest, McpPermission } from '../../shared/types/mcp.ts';++const MAX_LABEL_LENGTH = 80;+// a year at most, so a forgotten token stops working on its own+const MAX_EXPIRY_DAYS = 365;++export function parsePermission(value: unknown): McpPermission {+ if (value === 'read' || value === 'write') return value;+ throw new ValidationError('Choose what the token may do: read, or read and make changes');+}++export function parseAccessTokenCreate(body: Fields): McpAccessTokenCreateRequest {+ const label = requiredString(body, 'label', 'Give the token a name, such as the computer it is for').trim();+ if (label.length === 0 || label.length > MAX_LABEL_LENGTH) throw new ValidationError(`The name must be 1 to ${MAX_LABEL_LENGTH} characters`);+ const expiresInDays = body.expiresInDays === null ? null : optionalNumber(body, 'expiresInDays') ?? null;+ if (expiresInDays !== null && (!Number.isInteger(expiresInDays) || expiresInDays < 1 || expiresInDays > MAX_EXPIRY_DAYS)) {+ throw new ValidationError(`Expiry must be a whole number of days from 1 to ${MAX_EXPIRY_DAYS}, or never`);+ }+ return { label, permission: parsePermission(body.permission), expiresInDays };+}