Files
zeekay 19fdf55ceb feat(auth): one key scheme, minted and read in one place
A key now opens with what it is allowed to touch. `pk-` is publishable and
safe in a browser; `sk-` is secret and never leaves a server. The five marks
it replaces all began `ph` -- the upstream's initials -- and they were the
last of its brand a customer read back to us, in every SDK snippet. No word
rule could reach them, because `ph` is not a word.

The marks were also not telling the truth. The constant said `phc_` while
every live project token said `hi_`, so the middleware that routes on the
constant matched no real token at all. Two spellings existed and one was
fiction. Minting now happens in exactly one function and reading in exactly
one, so a second spelling has nowhere to live.

`phx_` (personal) and `phs_` (project secret) both become `sk-`. The mark
now says only that a value is secret; which store holds it is settled by
asking. That was already how personal keys worked -- keys minted before the
marks carry none, so the store always decided -- and both secret resolvers
already returned None on a miss and fell through, so one shared extractor
replaces the two that could drift apart.

OAuth's access and refresh tokens stay distinguishable as `at-` and `rt-`,
because the parser tells them apart before either is looked up, and the
domain-verification token becomes `vt-` rather than keeping a sixth mint of
its own.

`bin/debrand --check` now refuses the marks as a shape, so a seventh cannot
be coined. Two rules that were about to rename things that are not ours to
spell are bounded: `Lemon` no longer eats `LemonSqueezy`, and the `hog_flow`
rules no longer reach a Postgres table, a Datastore table or a route.

Keys are stored hashed, so a mark cannot be rewritten in place: the three
live project tokens have to be reminted.
2026-08-08 19:42:44 -07:00

351 lines
13 KiB
TypeScript

import { describe, expect, it } from 'vitest'
import { parseRequestProperties } from '@/lib/request-properties'
import { parseMcpMode, sanitizeHeaderValue } from '@/lib/utils'
function parseIdFromRequest(
request: { headers: { get: (name: string) => string | null } },
url: URL,
headerName: string,
paramName: string
): string | undefined {
return request.headers.get(headerName) || url.searchParams.get(paramName) || undefined
}
describe('URL Routing', () => {
const testCases = [
{ path: '/mcp', params: '', expected: { path: '/mcp', features: undefined } },
{
path: '/mcp',
params: '?features=dashboards',
expected: { path: '/mcp', features: ['dashboards'] },
},
{
path: '/mcp',
params: '?features=dashboards,insights',
expected: { path: '/mcp', features: ['dashboards', 'insights'] },
},
{ path: '/sse', params: '', expected: { path: '/sse', features: undefined } },
{
path: '/sse',
params: '?features=flags,org',
expected: { path: '/sse', features: ['flags', 'org'] },
},
{
path: '/sse/message',
params: '',
expected: { path: '/sse/message', features: undefined },
},
{
path: '/sse/message',
params: '?features=flags',
expected: { path: '/sse/message', features: ['flags'] },
},
]
describe('Query parameter parsing', () => {
it.each(testCases)('should parse $path$params correctly', ({ path, params, expected }) => {
const url = new URL(`https://example.com${path}${params}`)
expect(url.pathname).toBe(expected.path)
const featuresParam = url.searchParams.get('features')
const features = featuresParam ? featuresParam.split(',').filter(Boolean) : undefined
expect(features).toEqual(expected.features)
})
})
describe('Features string parsing', () => {
const featureTests = [
{ input: 'dashboards,insights,flags', expected: ['dashboards', 'insights', 'flags'] },
{ input: 'dashboards', expected: ['dashboards'] },
{ input: 'dashboards,,insights,', expected: ['dashboards', 'insights'] },
{ input: '', expected: [] },
]
it.each(featureTests)("should parse '$input' as $expected", ({ input, expected }) => {
const features = input.split(',').filter(Boolean)
expect(features).toEqual(expected)
})
})
describe('Organization and project ID parsing', () => {
const idParsingTests = [
{
description: 'organization ID from header',
headers: { 'x-insights-organization-id': 'org-123' },
params: '',
expectedOrgId: 'org-123',
expectedProjectId: undefined,
},
{
description: 'project ID from header',
headers: { 'x-insights-project-id': '456' },
params: '',
expectedOrgId: undefined,
expectedProjectId: '456',
},
{
description: 'both IDs from headers',
headers: { 'x-insights-organization-id': 'org-123', 'x-insights-project-id': '456' },
params: '',
expectedOrgId: 'org-123',
expectedProjectId: '456',
},
{
description: 'organization ID from query param fallback',
headers: {},
params: '?organization_id=org-789',
expectedOrgId: 'org-789',
expectedProjectId: undefined,
},
{
description: 'project ID from query param fallback',
headers: {},
params: '?project_id=101',
expectedOrgId: undefined,
expectedProjectId: '101',
},
{
description: 'both IDs from query param fallbacks',
headers: {},
params: '?organization_id=org-789&project_id=101',
expectedOrgId: 'org-789',
expectedProjectId: '101',
},
{
description: 'header takes precedence over query param',
headers: { 'x-insights-organization-id': 'header-org', 'x-insights-project-id': 'header-proj' },
params: '?organization_id=param-org&project_id=param-proj',
expectedOrgId: 'header-org',
expectedProjectId: 'header-proj',
},
{
description: 'undefined when neither header nor query param provided',
headers: {},
params: '',
expectedOrgId: undefined,
expectedProjectId: undefined,
},
]
it.each(idParsingTests)(
'should parse $description',
({ headers, params, expectedOrgId, expectedProjectId }) => {
const url = new URL(`https://example.com/mcp${params}`)
const request = {
headers: {
get: (name: string) => (headers as Record<string, string>)[name] ?? null,
},
}
const organizationId = parseIdFromRequest(request, url, 'x-insights-organization-id', 'organization_id')
const projectId = parseIdFromRequest(request, url, 'x-insights-project-id', 'project_id')
expect(organizationId).toBe(expectedOrgId)
expect(projectId).toBe(expectedProjectId)
}
)
})
describe('MCP mode parsing', () => {
const modeTests = [
{
description: 'undefined when neither header nor query param provided',
headers: {} as Record<string, string>,
params: '',
expected: undefined,
},
{
description: 'tools from header',
headers: { 'x-insights-mcp-mode': 'tools' },
params: '',
expected: 'tools' as const,
},
{
description: 'cli from header',
headers: { 'x-insights-mcp-mode': 'cli' },
params: '',
expected: 'cli' as const,
},
{
description: 'tools from query param',
headers: {},
params: '?mode=tools',
expected: 'tools' as const,
},
{
description: 'cli from query param',
headers: {},
params: '?mode=cli',
expected: 'cli' as const,
},
{
description: 'case-insensitive (CLI)',
headers: { 'x-insights-mcp-mode': 'CLI' },
params: '',
expected: 'cli' as const,
},
{
description: 'whitespace-tolerant (" tools ")',
headers: { 'x-insights-mcp-mode': ' tools ' },
params: '',
expected: 'tools' as const,
},
{
description: 'unknown value ignored',
headers: { 'x-insights-mcp-mode': 'banana' },
params: '',
expected: undefined,
},
{
description: 'legacy exec value ignored (only tools or cli accepted)',
headers: { 'x-insights-mcp-mode': 'exec' },
params: '',
expected: undefined,
},
{
description: 'header takes precedence over query param',
headers: { 'x-insights-mcp-mode': 'cli' },
params: '?mode=tools',
expected: 'cli' as const,
},
]
it.each(modeTests)('parses $description', ({ headers, params, expected }) => {
const url = new URL(`https://example.com/mcp${params}`)
const headerValue = headers['x-insights-mcp-mode'] ?? null
const queryValue = url.searchParams.get('mode')
// Mirrors the merge order in `src/index.ts` — header wins over query param.
expect(parseMcpMode(headerValue || queryValue)).toBe(expected)
})
})
describe('shared request property mode parsing', () => {
it('uses header mode before URL mode', () => {
const request = new Request('https://example.com/mcp?mode=tools', {
headers: {
Authorization: 'Bearer sk-test',
'x-insights-mcp-mode': 'cli',
},
})
expect(parseRequestProperties(request, {}).mode).toBe('cli')
})
})
describe('mcpVendorClient parsing', () => {
it('captures x-anthropic-client into mcpVendorClient', () => {
const request = new Request('https://example.com/mcp', {
headers: {
Authorization: 'Bearer sk-test',
'x-anthropic-client': 'ClaudeCode',
},
})
expect(parseRequestProperties(request, {}).mcpVendorClient).toBe('ClaudeCode')
})
it('returns undefined when x-anthropic-client is missing', () => {
const request = new Request('https://example.com/mcp', {
headers: { Authorization: 'Bearer sk-test' },
})
expect(parseRequestProperties(request, {}).mcpVendorClient).toBeUndefined()
})
it('defaults mcpClientName from x-anthropic-client when clientInfo omits a name', () => {
// Anthropic clients pool MCP transports and send no `clientInfo.name`, so
// without this fallback `$mcp_client_name` is empty and the analytics
// dashboard buckets the traffic as "Other".
const request = new Request('https://example.com/mcp', {
headers: {
Authorization: 'Bearer sk-test',
'x-anthropic-client': 'ClaudeCode',
},
})
expect(parseRequestProperties(request, {}).mcpClientName).toBe('claude-code')
})
it('keeps the self-reported clientName over the vendor header', () => {
const request = new Request('https://example.com/mcp', {
headers: {
Authorization: 'Bearer sk-test',
'x-anthropic-client': 'ClaudeCode',
},
})
expect(parseRequestProperties(request, { clientName: 'Cursor' }).mcpClientName).toBe('Cursor')
})
})
describe('MCP consumer parsing', () => {
const consumerTests = [
{
description: 'undefined when neither header nor query param provided',
headers: {} as Record<string, string>,
params: '',
expected: undefined,
},
{
description: 'plugin from header',
headers: { 'x-insights-mcp-consumer': 'plugin' },
params: '',
expected: 'plugin',
},
{
description: 'insights-code from header',
headers: { 'x-insights-mcp-consumer': 'insights-code' },
params: '',
expected: 'insights-code',
},
{
description: 'plugin from query param fallback',
headers: {},
params: '?consumer=plugin',
expected: 'plugin',
},
{
description: 'arbitrary value from query param fallback',
headers: {},
params: '?consumer=slack',
expected: 'slack',
},
{
description: 'header takes precedence over query param',
headers: { 'x-insights-mcp-consumer': 'plugin' },
params: '?consumer=other',
expected: 'plugin',
},
{
description: 'whitespace is trimmed from header value',
headers: { 'x-insights-mcp-consumer': ' plugin ' },
params: '',
expected: 'plugin',
},
{
description: 'whitespace is trimmed from query param value',
headers: {},
params: '?consumer=%20%20plugin%20%20',
expected: 'plugin',
},
{
description: 'control characters are stripped',
headers: { 'x-insights-mcp-consumer': 'plugin\x00\x1b' },
params: '',
expected: 'plugin',
},
]
it.each(consumerTests)('parses $description', ({ headers, params, expected }) => {
const url = new URL(`https://example.com/mcp${params}`)
const headerValue = headers['x-insights-mcp-consumer'] ?? null
const queryValue = url.searchParams.get('consumer')
// Mirrors the merge order in `src/index.ts` — header wins over query param,
// and both flow through `sanitizeHeaderValue` (which strips control chars,
// trims whitespace, and collapses empty results to `undefined`).
const consumer = sanitizeHeaderValue(headerValue || queryValue || undefined)
expect(consumer).toBe(expected)
})
})
})