Merge S10 (a1): public ledger profiles v1

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

# Conflicts:
#	BUILD-STATE.md
#	CLAUDE.md
This commit is contained in:
Kev
2026-07-11 19:40:43 -04:00
19 changed files with 1224 additions and 6 deletions
+219
View File
@@ -0,0 +1,219 @@
// A1 Session 10 — /api/profiles: claim handle + publish toggle (auth) and the
// public record read. Supabase + auth are mocked (ledgerRoutes.test.js
// pattern); under test: handle validation, 409 on a taken handle,
// private-by-default writes, and the no-existence-leak 404 (unknown and
// unpublished handles are byte-identical).
const express = require('express');
const request = require('supertest');
jest.mock('../../src/middleware/auth', () => ({
requireAuth: (req, res, next) => {
if (!req.headers.authorization) return res.status(401).json({ error: 'auth required' });
req.user = { id: 'u1', tier: 'analyst' };
return next();
},
}));
// Table-aware Supabase stub. Configure via mockState; every query records
// its filters so scoping is assertable.
const mockState = {
profileRow: null, // what public_profiles maybeSingle resolves to
upsertError: null,
upserts: [],
ledgerRows: [],
filters: [], // [table, filters[]]
};
function mockChain(table) {
const b = { _filters: [] };
const rec = (op) => (...args) => { b._filters.push([op, ...args]); return b; };
b.select = () => b;
b.eq = rec('eq');
b.is = rec('is');
b.not = rec('not');
b.gte = rec('gte');
b.order = () => b;
b.maybeSingle = () => {
mockState.filters.push([table, b._filters]);
return Promise.resolve({ data: mockState.profileRow, error: null });
};
b.limit = () => {
mockState.filters.push([table, b._filters]);
return Promise.resolve({ data: mockState.ledgerRows, error: null, count: 0 });
};
b.then = (resolve, reject) => {
mockState.filters.push([table, b._filters]);
return Promise.resolve({ data: mockState.ledgerRows, error: null, count: 0 }).then(resolve, reject);
};
b.upsert = (row, opts) => {
mockState.upserts.push({ table, row, opts });
return Promise.resolve({ error: mockState.upsertError });
};
return b;
}
jest.mock('../../src/utils/supabase', () => ({
getSupabaseServiceClient: () => ({ from: (table) => mockChain(table) }),
}));
process.env.SUPABASE_URL = 'https://test.supabase.co';
process.env.SUPABASE_SERVICE_ROLE_KEY = 'test-key';
function mountApp() {
delete require.cache[require.resolve('../../src/routes/profiles')];
const routes = require('../../src/routes/profiles');
const app = express();
app.use(express.json());
app.use('/api/profiles', routes);
return app;
}
beforeEach(() => {
mockState.profileRow = null;
mockState.upsertError = null;
mockState.upserts.length = 0;
mockState.ledgerRows.length = 0;
mockState.filters.length = 0;
});
describe('GET /api/profiles/me', () => {
test('401 without auth', async () => {
const res = await request(mountApp()).get('/api/profiles/me');
expect(res.status).toBe(401);
});
test('returns the own row scoped to the authenticated user', async () => {
mockState.profileRow = { handle: 'kev', published: false, created_at: '2026-07-10' };
const res = await request(mountApp())
.get('/api/profiles/me')
.set('Authorization', 'Bearer t');
expect(res.status).toBe(200);
expect(res.body.profile).toEqual({ handle: 'kev', published: false, created_at: '2026-07-10' });
const [table, filters] = mockState.filters[0];
expect(table).toBe('public_profiles');
expect(filters).toContainEqual(['eq', 'user_id', 'u1']);
});
test('no row yet → profile null (not an error)', async () => {
const res = await request(mountApp())
.get('/api/profiles/me')
.set('Authorization', 'Bearer t');
expect(res.status).toBe(200);
expect(res.body.profile).toBeNull();
});
});
describe('POST /api/profiles/me', () => {
test('401 without auth', async () => {
const res = await request(mountApp()).post('/api/profiles/me').send({ handle: 'kev' });
expect(res.status).toBe(401);
});
test.each(['ab', 'way_too_long_for_a_handle', 'has space', 'bad-dash', 'dot.dot', ''])(
'rejects invalid handle %j with 400 and writes nothing',
async (handle) => {
const res = await request(mountApp())
.post('/api/profiles/me')
.set('Authorization', 'Bearer t')
.send({ handle });
expect(res.status).toBe(400);
expect(mockState.upserts).toHaveLength(0);
},
);
test('upserts own row; PRIVATE BY DEFAULT — published false unless explicitly true', async () => {
const res = await request(mountApp())
.post('/api/profiles/me')
.set('Authorization', 'Bearer t')
.send({ handle: 'Kev_2026' }); // no published flag at all
expect(res.status).toBe(200);
expect(res.body.profile).toEqual({ handle: 'kev_2026', published: false });
expect(mockState.upserts).toHaveLength(1);
expect(mockState.upserts[0].table).toBe('public_profiles');
expect(mockState.upserts[0].row).toEqual({ user_id: 'u1', handle: 'kev_2026', published: false });
expect(mockState.upserts[0].opts).toEqual({ onConflict: 'user_id' });
});
test('published only flips on an explicit boolean true', async () => {
const res = await request(mountApp())
.post('/api/profiles/me')
.set('Authorization', 'Bearer t')
.send({ handle: 'kev', published: true });
expect(res.status).toBe(200);
expect(mockState.upserts[0].row.published).toBe(true);
// truthy-but-not-true must NOT publish
const res2 = await request(mountApp())
.post('/api/profiles/me')
.set('Authorization', 'Bearer t')
.send({ handle: 'kev', published: 'yes' });
expect(res2.status).toBe(200);
expect(mockState.upserts[1].row.published).toBe(false);
});
test('handle owned by another user → 409', async () => {
mockState.upsertError = { code: '23505', message: 'duplicate key value violates unique constraint "public_profiles_handle_key"' };
const res = await request(mountApp())
.post('/api/profiles/me')
.set('Authorization', 'Bearer t')
.send({ handle: 'taken_one' });
expect(res.status).toBe(409);
});
});
describe('GET /api/profiles/:handle (public)', () => {
test('published profile → handle + user-scoped aggregate + settled entries', async () => {
mockState.profileRow = { user_id: 'u2', handle: 'kev', published: true };
mockState.ledgerRows.push({ id: 'r1', player_name: 'Judge', outcome: 'hit', grade: 'A' });
const res = await request(mountApp()).get('/api/profiles/kev');
expect(res.status).toBe(200);
expect(res.body.handle).toBe('kev');
expect(res.body.min_sample).toBe(20);
expect(res.body.aggregate).toBeTruthy();
expect(res.body.aggregate.hit_pct).not.toBeUndefined();
expect(Array.isArray(res.body.entries)).toBe(true);
// Every ledger query is scoped to THAT user, never the public record.
const ledgerQueries = mockState.filters.filter(([t]) => t === 'ledger_entries');
expect(ledgerQueries.length).toBeGreaterThan(0);
for (const [, filters] of ledgerQueries) {
expect(filters).toContainEqual(['eq', 'user_id', 'u2']);
expect(filters.some((f) => f[0] === 'is' && f[1] === 'user_id')).toBe(false);
}
// The entries list is settled rows only.
const entriesQ = ledgerQueries.find(([, f]) => f.some((x) => x[0] === 'not' && x[1] === 'outcome'));
expect(entriesQ).toBeTruthy();
});
test('NO EXISTENCE LEAK — unknown and unpublished return the identical 404', async () => {
// Unknown handle: no row at all.
mockState.profileRow = null;
const unknown = await request(mountApp()).get('/api/profiles/ghost_handle');
// Unpublished handle: row exists, published false.
mockState.profileRow = { user_id: 'u3', handle: 'private_kev', published: false };
const unpublished = await request(mountApp()).get('/api/profiles/private_kev');
expect(unknown.status).toBe(404);
expect(unpublished.status).toBe(404);
expect(unknown.body).toEqual(unpublished.body);
});
test('an unpublished profile leaks NO ledger data', async () => {
mockState.profileRow = { user_id: 'u3', handle: 'private_kev', published: false };
mockState.ledgerRows.push({ id: 'r1', player_name: 'Judge', outcome: 'hit', grade: 'A' });
const res = await request(mountApp()).get('/api/profiles/private_kev');
expect(res.status).toBe(404);
expect(res.body.entries).toBeUndefined();
expect(res.body.aggregate).toBeUndefined();
// The ledger table was never even queried.
expect(mockState.filters.filter(([t]) => t === 'ledger_entries')).toHaveLength(0);
});
test('a malformed handle shape gets the same 404 without touching the database', async () => {
const res = await request(mountApp()).get('/api/profiles/NOT%20A%20HANDLE');
expect(res.status).toBe(404);
expect(mockState.filters).toHaveLength(0);
});
});
+70
View File
@@ -0,0 +1,70 @@
// A1 Session 10 — getModelAggregate scoping. The public default MUST stay
// `.is('user_id', null)` (the model record); the new `userId` option swaps
// it for `.eq('user_id', uid)` (a user's own public-profile aggregate).
// Same window, same n≥20 gate in both scopes.
const ledgerService = require('../../src/services/ledgerService');
function makeSb(captured, rows) {
return {
from() {
const b = { _filters: [] };
const rec = (op) => (...args) => { b._filters.push([op, ...args]); return b; };
b.select = () => b;
b.eq = rec('eq');
b.is = rec('is');
b.not = rec('not');
b.gte = rec('gte');
b.order = () => b;
b.limit = () => { captured.push(b._filters); return Promise.resolve({ data: rows, error: null, count: 0 }); };
b.then = (resolve, reject) => {
captured.push(b._filters);
return Promise.resolve({ data: rows, error: null, count: 2 }).then(resolve, reject);
};
return b;
},
};
}
describe('getModelAggregate scoping', () => {
test('default (no userId) scopes BOTH queries to the public record (user_id IS NULL)', async () => {
const captured = [];
const agg = await ledgerService.getModelAggregate({ sb: makeSb(captured, []) });
expect(captured.length).toBe(2); // settled + pending
for (const filters of captured) {
expect(filters).toContainEqual(['is', 'user_id', null]);
expect(filters.some((f) => f[0] === 'eq' && f[1] === 'user_id')).toBe(false);
}
expect(agg.hit_pct).toBeNull();
expect(agg.min_sample).toBe(ledgerService.MIN_AGG_SAMPLE);
});
test('userId scopes BOTH queries to that user and never touches the public scope', async () => {
const captured = [];
await ledgerService.getModelAggregate({ sb: makeSb(captured, []), userId: 'u-42' });
expect(captured.length).toBe(2);
for (const filters of captured) {
expect(filters).toContainEqual(['eq', 'user_id', 'u-42']);
expect(filters.some((f) => f[0] === 'is' && f[1] === 'user_id')).toBe(false);
}
});
test('user scope keeps the n≥20 gate — no percentage on a small sample', async () => {
const rows = Array.from({ length: 5 }, () => ({ outcome: 'hit', clv_result: 'beat', grade: 'A' }));
const agg = await ledgerService.getModelAggregate({ sb: makeSb([], rows), userId: 'u-42' });
expect(agg.settled).toBe(5);
expect(agg.hit_pct).toBeNull();
expect(agg.beat_close_pct).toBeNull();
});
test('user scope renders percentages at n≥20 like the public record', async () => {
const rows = [
...Array.from({ length: 14 }, () => ({ outcome: 'hit', clv_result: 'beat', grade: 'A' })),
...Array.from({ length: 7 }, () => ({ outcome: 'miss', clv_result: 'faded', grade: 'B' })),
];
const agg = await ledgerService.getModelAggregate({ sb: makeSb([], rows), userId: 'u-42' });
expect(agg.settled).toBe(21);
expect(agg.hit_pct).toBe(Math.round((14 / 21) * 100));
expect(agg.beat_close_pct).toBe(Math.round((14 / 21) * 100));
});
});
+118
View File
@@ -0,0 +1,118 @@
// A1 Session 10 — public ledger profiles: /u/[handle] page + OG card +
// settings claim/publish UI + proxies + migration. The .tsx surfaces are
// asserted against source (plain-JS Jest, no TS transform) — same pattern as
// vyndrAppShell/socialPreview.
const fs = require('fs');
const path = require('path');
const ROOT = path.join(__dirname, '..', '..');
const WEB = path.join(ROOT, 'web', 'src');
const read = (rel) => fs.readFileSync(path.join(WEB, rel), 'utf8');
const exists = (rel) => fs.existsSync(path.join(WEB, rel));
const routes = require('../../web/src/lib/routes');
describe('/u routing — the share surface stays public', () => {
it('never gates /u (a public record must load anonymous)', () => {
expect(routes.isGatedRoute('/u')).toBe(false);
expect(routes.isGatedRoute('/u/kev')).toBe(false);
});
it('declares /u in OPEN_ROUTES', () => {
expect(routes.OPEN_ROUTES).toContain('/u');
});
});
describe('/u/[handle] server shell', () => {
const src = read('app/u/[handle]/page.tsx');
it('carries the CLV-verified metadata title', () => {
expect(src).toContain('CLV-verified record — @');
expect(src).toContain('· VYNDR');
});
it('renders the client record component', () => {
expect(src).toContain('PublicProfile');
expect(exists('app/u/[handle]/PublicProfile.tsx')).toBe(true);
});
});
describe('/u/[handle] client record', () => {
const src = read('app/u/[handle]/PublicProfile.tsx');
it('honors the n-gate: RECORD BUILDING under min_sample, never a small-sample %', () => {
expect(src).toContain('RECORD BUILDING');
expect(src).toMatch(/settled >= minSample/);
});
it('shows outcome + CLV chips on settled rows (ledger card patterns)', () => {
expect(src).toContain('✓ HIT');
expect(src).toContain('✕ MISS');
expect(src).toContain('BEAT CLOSE');
expect(src).toContain('clv_result');
});
it('states the uncurated contract and one not-found state for unknown AND unpublished', () => {
expect(src).toContain('Nothing curated');
expect(src).toContain('private by default');
expect(src).toMatch(/notfound/);
});
it('fetches through the Next proxy (S25 rule)', () => {
expect(src).toContain('/api/profiles/');
});
});
describe('/u/[handle] OG image', () => {
const og = read('app/u/[handle]/opengraph-image.tsx');
it('is a 1200x630 PNG record card', () => {
expect(og).toContain('width: 1200, height: 630');
expect(og).toContain("contentType = 'image/png'");
expect(og).toContain('PUBLIC LEDGER');
expect(og).toContain('misses included');
});
it('does NOT use the edge runtime (self-hosted standalone, S53 rule)', () => {
expect(og).not.toContain("runtime = 'edge'");
});
});
describe('settings — claim handle + publish toggle', () => {
const src = read('app/settings/page.tsx');
it('carries the explicit private-by-default publish copy verbatim', () => {
expect(src).toContain('Publishing puts your ENTIRE settled record on a public page — wins and misses. Private by default.');
});
it('reads and writes /api/profiles/me with the bearer token', () => {
expect(src).toContain("fetch('/api/profiles/me'");
expect(src).toMatch(/method: 'POST'[\s\S]*?\/api\/profiles\/me|\/api\/profiles\/me[\s\S]*?method: 'POST'/);
});
it('sanitizes the handle input to the API shape (a-z 0-9 _ , max 20)', () => {
expect(src).toContain("replace(/[^a-z0-9_]/g, '')");
expect(src).toContain('.slice(0, 20)');
});
});
describe('Next proxies (S25 rule — Express is not browser-reachable)', () => {
it('me proxy forwards GET/POST with Authorization', () => {
const src = read('app/api/profiles/me/route.ts');
expect(src).toContain('BACKEND_URL');
expect(src).toContain('/api/profiles/me');
expect(src).toContain('authorization');
expect(src).toContain('export async function POST');
});
it('handle proxy forwards the public read and passes the 404 through untouched', () => {
const src = read('app/api/profiles/[handle]/route.ts');
expect(src).toContain('BACKEND_URL');
expect(src).toContain('/api/profiles/');
expect(src).toContain('status: upstream.status');
});
});
describe('migration 022 — public_profiles (committed, applied by the founder)', () => {
const sql = fs.readFileSync(path.join(ROOT, 'supabase', 'migrations', '022_public_profiles.sql'), 'utf8');
it('creates the table with the handle CHECK + private-by-default published', () => {
expect(sql).toContain('public.public_profiles');
expect(sql).toContain("handle ~ '^[a-z0-9_]{3,20}$'");
expect(sql).toMatch(/published\s+boolean NOT NULL DEFAULT false/);
expect(sql).toContain('REFERENCES auth.users');
});
it('RLS: published rows readable by anyone, own row by owner, writes service-role only', () => {
expect(sql).toContain('ENABLE ROW LEVEL SECURITY');
expect(sql).toContain('USING (published = true)');
expect(sql).toContain('USING (user_id = auth.uid())');
expect(sql).not.toMatch(/FOR (INSERT|UPDATE|DELETE)/);
});
});