Files
web-terminal/control-plane/test/registry/devices.test.ts
Yaojia Wang e7f3bd05f0 feat(tunnel): zero-touch tunnel enrollment — control-plane PKI, host agent, iOS, nginx isolation
Customers install one command / log in once; hardware-generated keys never leave the
device; CSRs return certs + subdomain; frpc + base-app run as durable services. No .p12,
no manual cert import. Implements the MVP fast-path of docs/PLAN_TUNNEL_AUTOMATION.md.

Control-plane / PKI (control-plane/):
- ca/x509-assembler.ts: single KMS-signed real X.509 issuance primitive (Ed25519 + P-256)
- ca/csr-ec.ts: P-256 PKCS#10 proof-of-possession (verifyCsrPoPEc) + CSR-key routing
- ca/frpclient-issue.ts, ca/device-issue.ts: P-256 frp-client + device leaf signers
- ca/rotate.ts + api/renew.ts: real-X.509 /renew + /device/:id/renew (mTLS current cert)
- registry/devices.ts: device registry + per-account cap/rate-limit
- auth/session.ts: device:enroll capability token mint/verify
- api/device-enroll.ts: POST /device/enroll (ownership-gated, deny-by-default)
- pairing/native-redeem.ts + shared gateAndConsumePairingCode; api/provision.ts native arm
- boot/native-ca.ts + main.ts: wire two P-256 CAs + issuers + routers (dev / KMS fail-fast)

Contracts: relay-contracts enroll right; relay-auth SPIFFE /device/ arm + spiffeIdFor(kind)

Host agent (agent/):
- transport/frpcToml.ts; provision/frpcBinary.ts + untar.ts (verify-download + traversal-safe extract)
- keys P-256 keygen/CSR/loadIdentity; service two-unit install + BIND_HOST loopback S-GATE
- net/loopbackLiteral.ts strict guard; health/probe.ts + transport/frpSupervise.ts; cli pair --install

iOS (ios/Packages/ClientTLS): SecureEnclaveKey + CertificateSigningRequest + DeviceEnrollmentClient
+ Keychain enroll refactor (SecKey/Security.framework end-to-end, avoids the -25300 trap)

Isolation (deploy/nginx): njs/getCertSub.js SAN parser + zone-anchored map -> 403

Verified: 758 tests green (control-plane 246, agent 267, relay-auth 133, relay-contracts 85,
iOS ClientTLS 27), all tsc clean; real nginx+njs docker 403/200/400; Swift CSR accepted by
the real control-plane verifier; frpc extract byte-identical to `tar -xO`. Cross-validation
caught + fixed 5 real defects (1 critical, 4 high). Remaining = infra (KMS, nginx deploy,
VPS frps, physical iPhone) per PROGRESS_LOG runbook.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-10 16:11:13 +02:00

96 lines
4.2 KiB
TypeScript

/**
* A4 — device registry (mirrors registry/hosts.ts). Proves: create/get; versioned status swap
* (INV8 append-only companion rows + atomic pointer swap); per-account device CAP enforcement;
* per-account enroll RATE-LIMIT; ownership deny-by-default.
*/
import { describe, test, expect } from 'vitest'
import {
createDeviceRegistry,
createMemoryDeviceStore,
DeviceLimitError,
type RegisterDeviceInput,
} from '../../src/registry/devices.js'
const ACCOUNT_A = '11111111-1111-4111-8111-111111111111'
const ACCOUNT_B = '22222222-2222-4222-8222-222222222222'
function input(overrides: Partial<RegisterDeviceInput> = {}): RegisterDeviceInput {
return {
accountId: ACCOUNT_A,
subdomainScope: 'alice',
ecPubkeySpki: new Uint8Array([1, 2, 3, 4]),
attestationLevel: 'none',
...overrides,
}
}
describe('A4 device registry', () => {
test('registerDevice → getDevice returns the persisted record with a serial + notAfter', async () => {
const devices = createDeviceRegistry({ devices: createMemoryDeviceStore() })
const rec = await devices.registerDevice(input())
expect(rec.deviceId.length).toBeGreaterThan(0)
expect(rec.accountId).toBe(ACCOUNT_A)
expect(rec.subdomainScope).toBe('alice')
expect(rec.status).toBe('active')
expect(rec.serial.length).toBeGreaterThan(0)
expect(Date.parse(rec.notAfter)).toBeGreaterThan(Date.now())
expect(await devices.getDevice(rec.deviceId)).toEqual(rec)
})
test('ecPubkeySpki is defensively copied (public key only, immutable)', async () => {
const devices = createDeviceRegistry({ devices: createMemoryDeviceStore() })
const src = new Uint8Array([9, 9, 9])
const rec = await devices.registerDevice(input({ ecPubkeySpki: src }))
src[0] = 0 // mutate the caller's buffer
expect(Array.from(rec.ecPubkeySpki)).toEqual([9, 9, 9])
})
test('setDeviceStatus revokes with a versioned snapshot (INV8)', async () => {
const store = createMemoryDeviceStore()
const devices = createDeviceRegistry({ devices: store })
const rec = await devices.registerDevice(input())
const revoked = await devices.setDeviceStatus(rec.deviceId, 'revoked')
expect(revoked.status).toBe('revoked')
expect(revoked.revokedAt).not.toBeNull()
const versions = await store.versions(rec.deviceId)
expect(versions.length).toBe(2) // insert + revoke
expect(versions[1]?.status).toBe('revoked')
})
test('ownsDevice is deny-by-default (unknown device / foreign account ⇒ false)', async () => {
const devices = createDeviceRegistry({ devices: createMemoryDeviceStore() })
const rec = await devices.registerDevice(input())
expect(await devices.ownsDevice(ACCOUNT_A, rec.deviceId)).toBe(true)
expect(await devices.ownsDevice(ACCOUNT_B, rec.deviceId)).toBe(false)
expect(await devices.ownsDevice(ACCOUNT_A, 'nope')).toBe(false)
})
test('per-account device CAP is enforced (active count only)', async () => {
const devices = createDeviceRegistry({ devices: createMemoryDeviceStore(), deviceCap: 2 })
await devices.assertUnderCap(ACCOUNT_A) // 0 < 2
const r1 = await devices.registerDevice(input())
await devices.registerDevice(input())
await expect(devices.assertUnderCap(ACCOUNT_A)).rejects.toBeInstanceOf(DeviceLimitError)
// a different account is unaffected
await devices.assertUnderCap(ACCOUNT_B)
// revoking one frees a slot
await devices.setDeviceStatus(r1.deviceId, 'revoked')
await devices.assertUnderCap(ACCOUNT_A)
})
test('per-account enroll RATE-LIMIT throws after the window budget', () => {
const devices = createDeviceRegistry({ devices: createMemoryDeviceStore(), rateMax: 2 })
devices.checkRateLimit(ACCOUNT_A)
devices.checkRateLimit(ACCOUNT_A)
expect(() => devices.checkRateLimit(ACCOUNT_A)).toThrow(DeviceLimitError)
// a different account has its own budget
expect(() => devices.checkRateLimit(ACCOUNT_B)).not.toThrow()
})
test('DeviceLimitError carries a machine code (cap vs rate) but a uniform message', async () => {
const devices = createDeviceRegistry({ devices: createMemoryDeviceStore(), deviceCap: 0 })
await devices.registerDevice(input()).catch(() => undefined)
await expect(devices.assertUnderCap(ACCOUNT_A)).rejects.toMatchObject({ code: 'cap_exceeded' })
})
})