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 repositories for access tokens and client grants
spacesdrive90c41a5d3935
diff --git a/backend/lib/mcp/accessToken.ts b/backend/lib/mcp/accessToken.tsindex 4c8aea8..df1b414 100644--- a/backend/lib/mcp/accessToken.ts+++ b/backend/lib/mcp/accessToken.ts@@ -1,6 +1,6 @@-// personal access tokens for Claude Code and scripts: shown once, stored only as a SHA-256 hash+import type { McpPermission } from '../../../shared/types/mcp.ts';-export type McpPermission = 'read' | 'write';+// personal access tokens for Claude Code and scripts: shown once, stored only as a SHA-256 hashconst PREFIX = 'twl_';// 32 random bytes, so guessing is hopeless and a plain hash (no salt or stretching) is enough to store itdiff --git a/backend/repositories/mcpAccessTokenRepository.ts b/backend/repositories/mcpAccessTokenRepository.tsnew file mode 100644index 0000000..2b024f0--- /dev/null+++ b/backend/repositories/mcpAccessTokenRepository.ts@@ -0,0 +1,108 @@+import { execute, maybeRow, rows } from './query.ts';+import type { SupabaseClient } from '../types/app.ts';+import type { McpAccessTokenSummary, McpPermission } from '../../shared/types/mcp.ts';++interface TokenRow {+ id: string;+ user_id: string;+ label: string;+ token_hint: string;+ permission: McpPermission;+ last_used_at: string | null;+ expires_at: string | null;+ created_at: string;+}++export interface NewAccessToken {+ id: string;+ label: string;+ tokenHash: string;+ tokenHint: string;+ permission: McpPermission;+ expiresAt: string | null;+}++// the token a request presented, as the MCP auth middleware needs it+export interface ActiveAccessToken {+ id: string;+ userId: string;+ permission: McpPermission;+ expiresAt: string | null;+ lastUsedAt: string | null;+}++const COLUMNS = 'id, user_id, label, token_hint, permission, last_used_at, expires_at, created_at';++function toSummary(row: TokenRow): McpAccessTokenSummary {+ return {+ id: row.id,+ label: row.label,+ hint: row.token_hint,+ permission: row.permission,+ lastUsedAt: row.last_used_at,+ expiresAt: row.expires_at,+ createdAt: row.created_at,+ };+}++// ...ForUser methods serve the Settings page; findActiveByHash and markUsed serve the MCP auth middleware, where the+// hash of a secret only its owner holds is what identifies the user+export interface McpAccessTokenRepository {+ createForUser(userId: string, token: NewAccessToken): Promise<McpAccessTokenSummary>;+ listForUser(userId: string): Promise<McpAccessTokenSummary[]>;+ revokeForUser(id: string, userId: string): Promise<boolean>;+ findActiveByHash(tokenHash: string): Promise<ActiveAccessToken | null>;+ markUsed(id: string, at: string): Promise<void>;+}++export function createMcpAccessTokenRepository(db: SupabaseClient): McpAccessTokenRepository {+ return {+ async createForUser(userId, token) {+ const created = await rows<TokenRow>('mcpAccessTokens.create', () => db.from('mcp_access_tokens').insert({+ id: token.id,+ user_id: userId,+ label: token.label,+ token_hash: token.tokenHash,+ token_hint: token.tokenHint,+ permission: token.permission,+ expires_at: token.expiresAt,+ }).select(COLUMNS));+ return toSummary(created[0]);+ },++ async listForUser(userId) {+ const found = await rows<TokenRow>('mcpAccessTokens.listForUser', () => db+ .from('mcp_access_tokens')+ .select(COLUMNS)+ .is('revoked_at', null)+ .eq('user_id', userId)+ .order('created_at', { ascending: false }));+ return found.map(toSummary);+ },++ async revokeForUser(id, userId) {+ const revoked = await rows<{ id: string }>('mcpAccessTokens.revoke', () => db+ .from('mcp_access_tokens')+ .update({ revoked_at: new Date().toISOString() })+ .eq('id', id)+ .is('revoked_at', null)+ .eq('user_id', userId)+ .select('id'));+ return revoked.length > 0;+ },++ async findActiveByHash(tokenHash) {+ const row = await maybeRow<TokenRow>('mcpAccessTokens.findActiveByHash', () => db+ .from('mcp_access_tokens')+ .select(COLUMNS)+ .eq('token_hash', tokenHash)+ .is('revoked_at', null)+ .maybeSingle());+ return row && { id: row.id, userId: row.user_id, permission: row.permission, expiresAt: row.expires_at, lastUsedAt: row.last_used_at };+ },++ async markUsed(id, at) {+ await execute('mcpAccessTokens.markUsed', () => db.from('mcp_access_tokens').update({ last_used_at: at }).eq('id', id));+ },+ };+}diff --git a/backend/repositories/mcpClientGrantRepository.ts b/backend/repositories/mcpClientGrantRepository.tsnew file mode 100644index 0000000..c5766fc--- /dev/null+++ b/backend/repositories/mcpClientGrantRepository.ts@@ -0,0 +1,100 @@+import { execute, maybeRow, rows } from './query.ts';+import { newRowId } from '../lib/ids.ts';+import type { SupabaseClient } from '../types/app.ts';+import type { McpClientGrantSummary, McpPermission } from '../../shared/types/mcp.ts';++interface GrantRow {+ id: string;+ client_id: string;+ client_name: string;+ permission: McpPermission;+ last_used_at: string | null;+ created_at: string;+}++export interface ClientGrantInput {+ clientId: string;+ clientName: string;+ permission: McpPermission;+}++const COLUMNS = 'id, client_id, client_name, permission, last_used_at, created_at';++function toSummary(row: GrantRow): McpClientGrantSummary {+ return {+ id: row.id,+ clientId: row.client_id,+ clientName: row.client_name,+ permission: row.permission,+ lastUsedAt: row.last_used_at,+ createdAt: row.created_at,+ };+}++// every method is scoped to the verified user: a grant only ever answers for the person who approved it+export interface McpClientGrantRepository {+ createForUser(userId: string, grant: ClientGrantInput): Promise<McpClientGrantSummary>;+ updateForUser(id: string, userId: string, changes: Omit<ClientGrantInput, 'clientId'>): Promise<McpClientGrantSummary | null>;+ findForUser(userId: string, clientId: string): Promise<McpClientGrantSummary | null>;+ listForUser(userId: string): Promise<McpClientGrantSummary[]>;+ deleteForUser(id: string, userId: string): Promise<boolean>;+ markUsedForUser(id: string, userId: string, at: string): Promise<void>;+}++export function createMcpClientGrantRepository(db: SupabaseClient): McpClientGrantRepository {+ return {+ async createForUser(userId, { clientId, clientName, permission }) {+ const created = await rows<GrantRow>('mcpClientGrants.create', () => db.from('mcp_client_grants').insert({+ id: newRowId(),+ user_id: userId,+ client_id: clientId,+ client_name: clientName,+ permission,+ }).select(COLUMNS));+ return toSummary(created[0]);+ },++ async updateForUser(id, userId, { clientName, permission }) {+ const updated = await rows<GrantRow>('mcpClientGrants.update', () => db+ .from('mcp_client_grants')+ .update({ client_name: clientName, permission })+ .eq('id', id)+ .eq('user_id', userId)+ .select(COLUMNS));+ return updated[0] ? toSummary(updated[0]) : null;+ },++ async findForUser(userId, clientId) {+ const row = await maybeRow<GrantRow>('mcpClientGrants.findForUser', () => db+ .from('mcp_client_grants')+ .select(COLUMNS)+ .eq('client_id', clientId)+ .eq('user_id', userId)+ .maybeSingle());+ return row ? toSummary(row) : null;+ },++ async listForUser(userId) {+ const found = await rows<GrantRow>('mcpClientGrants.listForUser', () => db+ .from('mcp_client_grants')+ .select(COLUMNS)+ .eq('user_id', userId)+ .order('created_at', { ascending: false }));+ return found.map(toSummary);+ },++ async deleteForUser(id, userId) {+ const deleted = await rows<{ id: string }>('mcpClientGrants.delete', () => db+ .from('mcp_client_grants')+ .delete()+ .eq('id', id)+ .eq('user_id', userId)+ .select('id'));+ return deleted.length > 0;+ },++ async markUsedForUser(id, userId, at) {+ await execute('mcpClientGrants.markUsed', () => db.from('mcp_client_grants').update({ last_used_at: at }).eq('id', id).eq('user_id', userId));+ },+ };+}diff --git a/backend/tests/fixtures/fakeSupabase.ts b/backend/tests/fixtures/fakeSupabase.tsindex 61c9550..cea7beb 100644--- a/backend/tests/fixtures/fakeSupabase.ts+++ b/backend/tests/fixtures/fakeSupabase.ts@@ -3,7 +3,7 @@ import type { SupabaseClient } from '../../types/app.ts';export type Row = Record<string, unknown>;-type Filter = [column: string, value: unknown, operator?: 'lte' | 'lt' | 'neq' | 'gte' | 'gt' | 'in' | 'or'];+type Filter = [column: string, value: unknown, operator?: 'lte' | 'lt' | 'neq' | 'gte' | 'gt' | 'in' | 'or' | 'is'];interface Action {type: 'select' | 'update' | 'insert' | 'upsert' | 'delete' | 'rpc';@@ -31,6 +31,7 @@ interface FakeQuery {gt(column: string, value: unknown): FakeQuery;in(column: string, values: unknown[]): FakeQuery;or(expression: string): FakeQuery;+ is(column: string, value: null): FakeQuery;order(): FakeQuery;limit(count: number): FakeQuery;single(): Promise<QueryResult>;@@ -89,6 +90,8 @@ function matchesFilter(row: Row, [column, value, operator]: Filter): boolean {if (operator === 'gt') return row[column] != null && (row[column] as string) > (value as string);if (operator === 'in') return (value as unknown[]).includes(row[column]);if (operator === 'or') return matchesOr(row, value as string);+ // is(column, null): a column the row never set counts as null, as in the database+ if (operator === 'is') return (row[column] ?? null) === value;return row[column] === value;}@@ -167,6 +170,10 @@ function queryBuilder(action: Action, run: Run): FakeQuery {filters.push(['', expression, 'or']);return query;},+ is(column: string, value: null) {+ filters.push([column, value, 'is']);+ return query;+ },// rows come back in the order they were stored; tests that page seed rows newest firstorder() { return query; },limit(count: number) {diff --git a/backend/tests/repositories/mcpAccessTokenRepository.test.ts b/backend/tests/repositories/mcpAccessTokenRepository.test.tsnew file mode 100644index 0000000..2a99bcc--- /dev/null+++ b/backend/tests/repositories/mcpAccessTokenRepository.test.ts@@ -0,0 +1,38 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { createMcpAccessTokenRepository } from '../../repositories/mcpAccessTokenRepository.ts';+import { fakeSupabase } from '../fixtures/fakeSupabase.ts';++const HASH = 'a'.repeat(64);+const NEW_TOKEN = { id: 't1', label: 'Laptop', tokenHash: HASH, tokenHint: 'wxyz', permission: 'read' as const, expiresAt: null };++test('a created token is listed for its owner without its hash, newest first, and never for anyone else', async () => {+ const db = fakeSupabase();+ const tokens = createMcpAccessTokenRepository(db);+ const summary = await tokens.createForUser('user-1', NEW_TOKEN);+ assert.equal(summary.hint, 'wxyz');+ assert.equal('tokenHash' in summary, false);+ assert.equal((await tokens.listForUser('user-1')).length, 1);+ assert.deepEqual(await tokens.listForUser('user-2'), []);+ assert.deepEqual(db.calls.find(call => call.table === 'mcp_access_tokens' && call.type === 'select')?.filters.find(([column]) => column === 'user_id'), ['user_id', 'user-1']);+});++test('a revoked token is no longer listed or found by its hash, and only its owner can revoke it', async () => {+ const tokens = createMcpAccessTokenRepository(fakeSupabase());+ await tokens.createForUser('user-1', NEW_TOKEN);+ assert.equal(await tokens.revokeForUser('t1', 'user-2'), false);+ assert.ok(await tokens.findActiveByHash(HASH));+ assert.equal(await tokens.revokeForUser('t1', 'user-1'), true);+ assert.equal(await tokens.findActiveByHash(HASH), null);+ assert.deepEqual(await tokens.listForUser('user-1'), []);+ assert.equal(await tokens.revokeForUser('t1', 'user-1'), false);+});++test('finding by hash returns the owner and permission the middleware needs', async () => {+ const tokens = createMcpAccessTokenRepository(fakeSupabase());+ await tokens.createForUser('user-1', { ...NEW_TOKEN, permission: 'write' });+ const found = await tokens.findActiveByHash(HASH);+ assert.equal(found?.userId, 'user-1');+ assert.equal(found?.permission, 'write');+ assert.equal(await tokens.findActiveByHash('b'.repeat(64)), null);+});diff --git a/backend/tests/repositories/mcpClientGrantRepository.test.ts b/backend/tests/repositories/mcpClientGrantRepository.test.tsnew file mode 100644index 0000000..7c4b076--- /dev/null+++ b/backend/tests/repositories/mcpClientGrantRepository.test.ts@@ -0,0 +1,26 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { createMcpClientGrantRepository } from '../../repositories/mcpClientGrantRepository.ts';+import { fakeSupabase } from '../fixtures/fakeSupabase.ts';++const GRANT = { clientId: 'client-a', clientName: 'Claude', permission: 'read' as const };++test('a grant is found only for the person who approved it', async () => {+ const grants = createMcpClientGrantRepository(fakeSupabase());+ const created = await grants.createForUser('user-1', GRANT);+ assert.equal((await grants.findForUser('user-1', 'client-a'))?.id, created.id);+ assert.equal(await grants.findForUser('user-2', 'client-a'), null);+ assert.deepEqual(await grants.listForUser('user-2'), []);+});++test('updating a grant changes its permission and keeps its id; another person cannot update or delete it', async () => {+ const grants = createMcpClientGrantRepository(fakeSupabase());+ const created = await grants.createForUser('user-1', GRANT);+ assert.equal(await grants.updateForUser(created.id, 'user-2', { clientName: 'Claude', permission: 'write' }), null);+ const updated = await grants.updateForUser(created.id, 'user-1', { clientName: 'Claude', permission: 'write' });+ assert.equal(updated?.id, created.id);+ assert.equal(updated?.permission, 'write');+ assert.equal(await grants.deleteForUser(created.id, 'user-2'), false);+ assert.equal(await grants.deleteForUser(created.id, 'user-1'), true);+ assert.equal(await grants.findForUser('user-1', 'client-a'), null);+});diff --git a/shared/types/mcp.ts b/shared/types/mcp.tsnew file mode 100644index 0000000..887cd35--- /dev/null+++ b/shared/types/mcp.ts@@ -0,0 +1,58 @@+// what a Claude client connected through the MCP server may do: read only, or also make changes+export type McpPermission = 'read' | 'write';++// a personal access token as the Settings page lists it; the token itself is never sent again after it is created+export interface McpAccessTokenSummary {+ id: string;+ label: string;+ // the last four characters, so a person can tell their tokens apart+ hint: string;+ permission: McpPermission;+ lastUsedAt: string | null;+ expiresAt: string | null;+ createdAt: string;+}++// an OAuth client a person approved on the consent page+export interface McpClientGrantSummary {+ id: string;+ clientId: string;+ clientName: string;+ permission: McpPermission;+ lastUsedAt: string | null;+ createdAt: string;+}++// GET /api/mcp/tokens+export interface McpAccessTokenListResponse {+ success: true;+ tokens: McpAccessTokenSummary[];+}++// body of POST /api/mcp/tokens; expiresInDays null means the token does not expire+export interface McpAccessTokenCreateRequest {+ label: string;+ permission: McpPermission;+ expiresInDays: number | null;+}++// POST /api/mcp/tokens: the only response that carries the token+export interface McpAccessTokenCreateResponse {+ success: true;+ token: string;+ summary: McpAccessTokenSummary;+}++// GET /api/mcp/clients+export interface McpClientGrantListResponse {+ success: true;+ clients: McpClientGrantSummary[];+}++// GET /api/mcp/info: what the Settings page needs to show how to connect+export interface McpServerInfoResponse {+ success: true;+ serverUrl: string;+ // false until the owner turns on Supabase Auth's OAuth server; tokens work either way+ oauthEnabled: boolean;+}