Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-api): encrypted member-registration credential store
Jose Ramirez57760e058e94
diff --git a/control-api/src/services/memberRegistrationCredentialsDb.ts b/control-api/src/services/memberRegistrationCredentialsDb.tsnew file mode 100644index 000000000..46e5f4a9a--- /dev/null+++ b/control-api/src/services/memberRegistrationCredentialsDb.ts@@ -0,0 +1,80 @@+import { config } from '../config.js'+import { pool } from '../db.js'+import {+ decryptOAuthSecret,+ deriveOAuthEncryptionKey,+ encryptOAuthSecret,+} from '../oauth/encryption.js'++// Hosted-mode hub credentials (spec §8.2). Secrets are AES-256-GCM encrypted+// with the platform's existing envelope key — a Postgres dump yields nothing+// usable. Rotation is ops-level (revoke + blank); this module never deletes.+export interface MemberRegistrationCredential {+ boundDomain: string+ tenantId: string+ kid: string+ secret: string+}++interface RawRow {+ bound_domain: string+ tenant_id: string+ kid: string+ secret_encrypted: string+}++function encryptionKey(): Buffer {+ return deriveOAuthEncryptionKey(config.oauthEncryptionKey)+}++export async function getActiveMemberRegistrationCredential(+ domain: string+): Promise<MemberRegistrationCredential | null> {+ const result = await pool.query(+ `SELECT bound_domain, tenant_id, kid, secret_encrypted+ FROM member_registration_credentials+ WHERE bound_domain = $1 AND revoked_at IS NULL+ ORDER BY created_at DESC+ LIMIT 1`,+ [domain]+ )+ const row = result.rows[0] as RawRow | undefined+ if (!row) return null+ let secret: string+ try {+ secret = decryptOAuthSecret(encryptionKey(), row.secret_encrypted)+ } catch {+ // Lost/rotated envelope key = "no credential" (spec §8.2 fails soft). Revoke+ // the dead row so it frees the partial-unique slot and the re-mint INSERT+ // can succeed; keep the row (blanked) as audit trail.+ await pool.query(+ `UPDATE member_registration_credentials+ SET revoked_at = NOW(), secret_encrypted = ''+ WHERE bound_domain = $1 AND revoked_at IS NULL`,+ [domain]+ )+ return null+ }+ return {+ boundDomain: row.bound_domain,+ tenantId: row.tenant_id,+ kid: row.kid,+ secret,+ }+}++export async function insertMemberRegistrationCredential(input: {+ boundDomain: string+ tenantId: string+ kid: string+ secret: string+}): Promise<{ inserted: boolean }> {+ const encrypted = encryptOAuthSecret(encryptionKey(), input.secret)+ const result = await pool.query(+ `INSERT INTO member_registration_credentials (bound_domain, tenant_id, kid, secret_encrypted)+ VALUES ($1, $2, $3, $4)+ ON CONFLICT (bound_domain) WHERE revoked_at IS NULL DO NOTHING`,+ [input.boundDomain, input.tenantId, input.kid, encrypted]+ )+ return { inserted: (result.rowCount ?? 0) > 0 }+}diff --git a/control-api/test/services.memberRegistrationCredentialsDb.test.ts b/control-api/test/services.memberRegistrationCredentialsDb.test.tsnew file mode 100644index 000000000..069d6eddb--- /dev/null+++ b/control-api/test/services.memberRegistrationCredentialsDb.test.ts@@ -0,0 +1,105 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import {+ deriveOAuthEncryptionKey,+ encryptOAuthSecret,+} from '../src/oauth/encryption.js'++const OAUTH_KEY_HEX = 'ab'.repeat(32)++const { cfg } = vi.hoisted(() => ({+ cfg: { oauthEncryptionKey: 'ab'.repeat(32) } as Record<string, unknown>,+}))+vi.mock('../src/config.js', () => ({ config: cfg }))++const db = vi.hoisted(() => ({ pool: { query: vi.fn() } }))+vi.mock('../src/db.js', () => db)++import {+ getActiveMemberRegistrationCredential,+ insertMemberRegistrationCredential,+} from '../src/services/memberRegistrationCredentialsDb.js'++const KEY = deriveOAuthEncryptionKey(OAUTH_KEY_HEX)++describe('memberRegistrationCredentialsDb', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ it('returns the decrypted active credential', async () => {+ db.pool.query.mockResolvedValueOnce({+ rows: [+ {+ bound_domain: 'profile.acme.com',+ tenant_id: 'ext-abc123',+ kid: 'ext-abc123-deadbeef',+ secret_encrypted: encryptOAuthSecret(KEY, 'hub-secret'),+ },+ ],+ rowCount: 1,+ })+ const row = await getActiveMemberRegistrationCredential('profile.acme.com')+ expect(row).toEqual({+ boundDomain: 'profile.acme.com',+ tenantId: 'ext-abc123',+ kid: 'ext-abc123-deadbeef',+ secret: 'hub-secret',+ })+ const [sql, params] = db.pool.query.mock.calls[0]+ expect(String(sql)).toMatch(/revoked_at IS NULL/)+ expect(params).toEqual(['profile.acme.com'])+ })++ it('returns null when no active row exists', async () => {+ db.pool.query.mockResolvedValueOnce({ rows: [], rowCount: 0 })+ expect(await getActiveMemberRegistrationCredential('profile.acme.com')).toBeNull()+ })++ it('self-heals an undecryptable row: revokes it (blanking the secret) and returns null', async () => {+ db.pool.query+ .mockResolvedValueOnce({+ rows: [+ {+ bound_domain: 'profile.acme.com',+ tenant_id: 'ext-abc123',+ kid: 'ext-abc123-deadbeef',+ secret_encrypted: 'v1.not.decryptable.garbage',+ },+ ],+ rowCount: 1,+ })+ .mockResolvedValueOnce({ rows: [], rowCount: 1 }) // the revoke UPDATE+ expect(await getActiveMemberRegistrationCredential('profile.acme.com')).toBeNull()+ const [updateSql, updateParams] = db.pool.query.mock.calls[1]+ expect(String(updateSql)).toMatch(/UPDATE member_registration_credentials/)+ expect(String(updateSql)).toMatch(/revoked_at = NOW\(\)/i)+ expect(String(updateSql)).toMatch(/secret_encrypted = ''/)+ expect(updateParams).toEqual(['profile.acme.com'])+ })++ it('inserts encrypted (never the plaintext secret) with the partial-index conflict target', async () => {+ db.pool.query.mockResolvedValueOnce({ rows: [], rowCount: 1 })+ const { inserted } = await insertMemberRegistrationCredential({+ boundDomain: 'profile.acme.com',+ tenantId: 'ext-abc123',+ kid: 'ext-abc123-deadbeef',+ secret: 'hub-secret',+ })+ expect(inserted).toBe(true)+ const [sql, params] = db.pool.query.mock.calls[0]+ expect(String(sql)).toMatch(/ON CONFLICT \(bound_domain\) WHERE revoked_at IS NULL DO NOTHING/)+ expect(params?.[3]).not.toContain('hub-secret')+ expect(String(params?.[3])).toMatch(/^v1\./) // encryption.ts payload format+ })++ it('reports inserted:false when the partial unique index rejects (lost race)', async () => {+ db.pool.query.mockResolvedValueOnce({ rows: [], rowCount: 0 })+ const { inserted } = await insertMemberRegistrationCredential({+ boundDomain: 'profile.acme.com',+ tenantId: 'ext-xyz',+ kid: 'ext-xyz-1234',+ secret: 's',+ })+ expect(inserted).toBe(false)+ })+})