Skip to content

Commit e229799

Browse files
committed
FEAT: Add self-hosted Hub passkey foundation
- Add hub-server.ts to handle HTTP server logic for CrewCode Hub. - Introduce hub-store.ts for managing user, credential, session, and machine data with SQLite. - Create hub.ts for CLI options parsing and server initialization. - Implement remote-access-security.ts for rate limiting and origin validation. - Add tests for hub functionality, remote access authentication, and security features. - Ensure secure handling of sessions and credentials with appropriate error handling and validation.
1 parent 9c84037 commit e229799

18 files changed

Lines changed: 1588 additions & 29 deletions

‎.gitignore‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,3 +43,7 @@ docs-website/.astro/
4343
social-media-post.md
4444
Work/
4545
promo-video
46+
packaging/arch/pkg/
47+
packaging/arch/src/
48+
packaging/arch/*.deb
49+
packaging/arch/*.pkg.tar.*

‎bin/crewcode-server.mjs‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,21 @@ import { fileURLToPath } from 'url'
66
import { spawnSync } from 'child_process'
77

88
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..')
9-
const entry = join(root, 'out', 'main', 'headless.js')
9+
const args = process.argv.slice(2)
10+
const command = args[0] === 'hub' ? 'hub' : 'serve'
11+
const entry = join(root, 'out', 'main', command === 'hub' ? 'hub.js' : 'headless.js')
1012
if (!existsSync(entry)) {
11-
console.error('CrewCode server build is missing. Run `npm run build` before starting from this checkout.')
13+
console.error(`CrewCode ${command} build is missing. Run \`npm run build\` before starting from this checkout.`)
1214
process.exit(1)
1315
}
1416

1517
// The Electron package sets ELECTRON_RUN_AS_NODE in some development shells.
16-
// A headless server must always execute in ordinary Node.js.
18+
// Headless services must always execute in ordinary Node.js.
1719
delete process.env.ELECTRON_RUN_AS_NODE
1820
const require = createRequire(import.meta.url)
1921
const module = require(entry)
20-
module.runHeadless(process.argv.slice(2)).catch(error => {
22+
const run = command === 'hub' ? module.runHub : module.runHeadless
23+
run(command === 'hub' || args[0] === 'serve' ? args.slice(1) : args).catch(error => {
2124
console.error(error?.message || String(error))
2225
process.exitCode = 1
2326
})

‎docs/web-remote-access.md‎

Lines changed: 268 additions & 6 deletions
Large diffs are not rendered by default.

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,7 @@
149149
"fix-node-pty-permissions": "node scripts/fix-node-pty-permissions.mjs",
150150
"postinstall": "npm run fix-node-pty-permissions",
151151
"install-electron": "node node_modules/electron/install.js",
152-
"sync-plugin-api": "node scripts/sync-plugin-api-helper.mjs",
152+
"sync-plugin-api": "node packages/crewcode-plugin-api/scripts/sync-vendored.mjs",
153153
"crewcode": "node packages/crewcode-plugin-cli/bin/crewcode.mjs",
154154
"codemirror:install": "node packages/crew-codemirror/bin/cm.js install",
155155
"codemirror:build": "node packages/crew-codemirror/bin/cm.js build",

‎src/main/headless.test.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,13 @@ describe('headless CLI options', () => {
88
})
99

1010
it('parses serve network and data options', () => {
11-
expect(parseServeOptions(['serve', '--host', '0.0.0.0', '--port', '4000', '--data-dir', 'state', '--workspace-root', 'projects'], '/tmp')).toEqual({ host: '0.0.0.0', port: 4000, dataDir: resolve('/tmp', 'state'), webRoot: undefined, allowedWorkspaceRoots: [resolve('/tmp', 'projects')] })
11+
expect(parseServeOptions(['serve', '--host', '0.0.0.0', '--port', '4000', '--data-dir', 'state', '--workspace-root', 'projects', '--public-origin', 'https://crewcode.example'], '/tmp')).toEqual({ host: '0.0.0.0', port: 4000, dataDir: resolve('/tmp', 'state'), webRoot: undefined, allowedWorkspaceRoots: [resolve('/tmp', 'projects')], publicOrigins: ['https://crewcode.example'] })
1212
})
1313

14-
it('rejects invalid ports and unknown options', () => {
14+
it('rejects invalid ports, public origins, and unknown options', () => {
1515
expect(() => parseServeOptions(['--port', '70000'])).toThrow('invalid port')
16+
expect(() => parseServeOptions(['--public-origin', 'https://crewcode.example/path'])).toThrow('invalid public origin')
17+
expect(() => parseServeOptions(['--public-origin', 'file:///tmp/hub'])).toThrow('invalid public origin')
1618
expect(() => parseServeOptions(['--public'])).toThrow('unknown option')
1719
})
1820
})

‎src/main/headless.ts‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ interface ServeOptions {
1010
dataDir: string
1111
webRoot?: string
1212
allowedWorkspaceRoots?: string[]
13+
publicOrigins?: string[]
1314
}
1415

1516
function usage(): string {
@@ -24,6 +25,7 @@ Options:
2425
--data-dir <path> Server state directory (default: ~/.crewcode)
2526
--web-root <path> Built renderer directory
2627
--workspace-root <path> Allow browser projects under this host directory (repeatable; default: home)
28+
--public-origin <url> Allow an exact browser origin behind a reverse proxy (repeatable)
2729
--help Show this help
2830
2931
Examples:
@@ -41,6 +43,15 @@ function valueAfter(argv: string[], index: number, flag: string): string {
4143
return value
4244
}
4345

46+
function exactPublicOrigin(value: string): string {
47+
let url: URL
48+
try { url = new URL(value) } catch { throw new Error(`invalid public origin: ${value}`) }
49+
if ((url.protocol !== 'http:' && url.protocol !== 'https:') || url.username || url.password || url.pathname !== '/' || url.search || url.hash) {
50+
throw new Error(`invalid public origin: ${value}`)
51+
}
52+
return url.origin
53+
}
54+
4455
export function parseServeOptions(argv: string[], cwd = process.cwd()): ServeOptions | { help: true } {
4556
const args = argv[0] === 'serve' ? argv.slice(1) : argv
4657
if (args.includes('--help') || args.includes('-h')) return { help: true }
@@ -49,6 +60,7 @@ export function parseServeOptions(argv: string[], cwd = process.cwd()): ServeOpt
4960
let dataDir = join(homedir(), '.crewcode')
5061
let webRoot: string | undefined
5162
const allowedWorkspaceRoots: string[] = []
63+
const publicOrigins: string[] = []
5264
for (let index = 0; index < args.length; index += 1) {
5365
const arg = args[index]
5466
if (arg === '--host') host = valueAfter(args, index++, arg)
@@ -59,9 +71,17 @@ export function parseServeOptions(argv: string[], cwd = process.cwd()): ServeOpt
5971
} else if (arg === '--data-dir') dataDir = resolve(cwd, valueAfter(args, index++, arg))
6072
else if (arg === '--web-root') webRoot = resolve(cwd, valueAfter(args, index++, arg))
6173
else if (arg === '--workspace-root') allowedWorkspaceRoots.push(resolve(cwd, valueAfter(args, index++, arg)))
74+
else if (arg === '--public-origin') publicOrigins.push(exactPublicOrigin(valueAfter(args, index++, arg)))
6275
else throw new Error(`unknown option: ${arg}`)
6376
}
64-
return { host, port, dataDir, webRoot, allowedWorkspaceRoots: allowedWorkspaceRoots.length ? allowedWorkspaceRoots : undefined }
77+
return {
78+
host,
79+
port,
80+
dataDir,
81+
webRoot,
82+
allowedWorkspaceRoots: allowedWorkspaceRoots.length ? allowedWorkspaceRoots : undefined,
83+
publicOrigins: publicOrigins.length ? publicOrigins : undefined,
84+
}
6585
}
6686

6787
function defaultWebRoot(): string | undefined {

‎src/main/hub-auth.ts‎

Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
import { createHash, randomBytes, timingSafeEqual } from 'crypto'
2+
import {
3+
generateAuthenticationOptions,
4+
generateRegistrationOptions,
5+
verifyAuthenticationResponse,
6+
verifyRegistrationResponse,
7+
type AuthenticationResponseJSON,
8+
type PublicKeyCredentialCreationOptionsJSON,
9+
type PublicKeyCredentialRequestOptionsJSON,
10+
type RegistrationResponseJSON,
11+
} from '@simplewebauthn/server'
12+
import { HubStore, type HubUser } from './hub-store'
13+
14+
const CHALLENGE_TTL_MS = 5 * 60_000
15+
export const HUB_BOOTSTRAP_TTL_MS = 10 * 60_000
16+
export const HUB_SESSION_TTL_MS = 12 * 60 * 60_000
17+
18+
interface PendingChallenge {
19+
challenge: string
20+
expiresAt: number
21+
bootstrapDigest?: Buffer
22+
}
23+
24+
function digest(value: string): Buffer {
25+
return createHash('sha256').update(value).digest()
26+
}
27+
28+
function matches(value: string, expected: Buffer): boolean {
29+
const actual = digest(value)
30+
return actual.length === expected.length && timingSafeEqual(actual, expected)
31+
}
32+
33+
export class HubAuth {
34+
private readonly registrationChallenges = new Map<string, PendingChallenge>()
35+
private readonly authenticationChallenges = new Map<string, PendingChallenge>()
36+
private bootstrapDigest: Buffer | null = null
37+
private bootstrapExpiresAt = 0
38+
private bootstrapUsed = false
39+
40+
constructor(
41+
private readonly store: HubStore,
42+
readonly publicOrigin: string,
43+
private readonly now: () => number = Date.now,
44+
) {}
45+
46+
get rpId(): string { return new URL(this.publicOrigin).hostname }
47+
48+
issueBootstrap(): { token: string; expiresAt: number } | null {
49+
if (this.store.owner()) return null
50+
const token = randomBytes(32).toString('base64url')
51+
this.bootstrapDigest = digest(token)
52+
this.bootstrapExpiresAt = this.now() + HUB_BOOTSTRAP_TTL_MS
53+
this.bootstrapUsed = false
54+
return { token, expiresAt: this.bootstrapExpiresAt }
55+
}
56+
57+
async registrationOptions(token: string, username: string): Promise<{ flowId: string; options: PublicKeyCredentialCreationOptionsJSON }> {
58+
this.requireBootstrap(token)
59+
const normalized = username.trim()
60+
if (!/^[\p{L}\p{N}_. -]{1,64}$/u.test(normalized)) throw new Error('owner name must be 1-64 letters, numbers, spaces, dots, underscores, or hyphens')
61+
const options = await generateRegistrationOptions({
62+
rpName: 'CrewCode Hub',
63+
rpID: this.rpId,
64+
userName: normalized,
65+
userDisplayName: normalized,
66+
attestationType: 'none',
67+
authenticatorSelection: { residentKey: 'preferred', userVerification: 'required' },
68+
})
69+
const flowId = randomBytes(16).toString('hex')
70+
this.registrationChallenges.set(flowId, { challenge: options.challenge, expiresAt: this.now() + CHALLENGE_TTL_MS, bootstrapDigest: digest(token) })
71+
return { flowId, options }
72+
}
73+
74+
async verifyRegistration(input: { token: string; flowId: string; username: string; response: RegistrationResponseJSON }): Promise<{ user: HubUser; token: string; csrf: string }> {
75+
this.requireBootstrap(input.token)
76+
const pending = this.registrationChallenges.get(input.flowId)
77+
this.registrationChallenges.delete(input.flowId)
78+
if (!pending || pending.expiresAt <= this.now() || !pending.bootstrapDigest || !matches(input.token, pending.bootstrapDigest)) throw new Error('registration challenge is invalid or expired')
79+
const verification = await verifyRegistrationResponse({
80+
response: input.response,
81+
expectedChallenge: pending.challenge,
82+
expectedOrigin: this.publicOrigin,
83+
expectedRPID: this.rpId,
84+
requireUserVerification: true,
85+
})
86+
if (!verification.verified || !verification.registrationInfo) throw new Error('passkey registration could not be verified')
87+
const username = input.username.trim()
88+
const user = this.store.createOwnerWithCredential({
89+
username,
90+
credential: verification.registrationInfo.credential,
91+
deviceType: verification.registrationInfo.credentialDeviceType,
92+
backedUp: verification.registrationInfo.credentialBackedUp,
93+
now: this.now(),
94+
})
95+
this.bootstrapUsed = true
96+
this.bootstrapDigest = null
97+
const session = this.store.createSession(user.id, this.now(), HUB_SESSION_TTL_MS)
98+
return { user, token: session.token, csrf: session.csrf }
99+
}
100+
101+
async authenticationOptions(): Promise<{ flowId: string; options: PublicKeyCredentialRequestOptionsJSON }> {
102+
const owner = this.store.owner()
103+
if (!owner) throw new Error('Hub owner setup is incomplete')
104+
const credentials = this.store.credentialsForUser(owner.id)
105+
const options = await generateAuthenticationOptions({
106+
rpID: this.rpId,
107+
allowCredentials: credentials.map(credential => ({ id: credential.id, transports: credential.transports })),
108+
userVerification: 'required',
109+
})
110+
const flowId = randomBytes(16).toString('hex')
111+
this.authenticationChallenges.set(flowId, { challenge: options.challenge, expiresAt: this.now() + CHALLENGE_TTL_MS })
112+
return { flowId, options }
113+
}
114+
115+
async verifyAuthentication(input: { flowId: string; response: AuthenticationResponseJSON }): Promise<{ user: HubUser; token: string; csrf: string }> {
116+
const pending = this.authenticationChallenges.get(input.flowId)
117+
this.authenticationChallenges.delete(input.flowId)
118+
if (!pending || pending.expiresAt <= this.now()) throw new Error('authentication challenge is invalid or expired')
119+
const credential = this.store.credential(input.response.id)
120+
if (!credential) throw new Error('passkey is not registered with this Hub')
121+
const verification = await verifyAuthenticationResponse({
122+
response: input.response,
123+
expectedChallenge: pending.challenge,
124+
expectedOrigin: this.publicOrigin,
125+
expectedRPID: this.rpId,
126+
credential: { id: credential.id, publicKey: new Uint8Array(credential.publicKey), counter: credential.counter, transports: credential.transports },
127+
requireUserVerification: true,
128+
})
129+
if (!verification.verified) throw new Error('passkey authentication could not be verified')
130+
this.store.updateCredentialCounter(credential.id, verification.authenticationInfo.newCounter)
131+
const owner = this.store.owner()
132+
if (!owner || owner.id !== credential.userId) throw new Error('passkey owner is unavailable')
133+
const session = this.store.createSession(owner.id, this.now(), HUB_SESSION_TTL_MS)
134+
return { user: owner, token: session.token, csrf: session.csrf }
135+
}
136+
137+
private requireBootstrap(token: string): void {
138+
if (this.store.owner()) throw new Error('Hub owner already exists')
139+
if (this.bootstrapUsed || !this.bootstrapDigest || this.bootstrapExpiresAt <= this.now() || !matches(token, this.bootstrapDigest)) {
140+
throw new Error('bootstrap token is invalid, expired, or already used')
141+
}
142+
}
143+
}

‎src/main/hub-server.test.ts‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import { mkdtempSync, rmSync } from 'fs'
2+
import { tmpdir } from 'os'
3+
import { join } from 'path'
4+
import { afterEach, describe, expect, it } from 'vitest'
5+
import { startHubServer, type RunningHubServer } from './hub-server'
6+
import { HubStore } from './hub-store'
7+
8+
const cleanups: Array<() => void | Promise<void>> = []
9+
afterEach(async () => {
10+
while (cleanups.length) await cleanups.pop()?.()
11+
})
12+
13+
function temporaryDirectory(): string {
14+
const directory = mkdtempSync(join(tmpdir(), 'crewcode-hub-test-'))
15+
cleanups.push(() => rmSync(directory, { recursive: true, force: true }))
16+
return directory
17+
}
18+
19+
async function server(): Promise<RunningHubServer> {
20+
const running = await startHubServer({ dataDir: temporaryDirectory(), port: 0 })
21+
cleanups.push(() => running.close())
22+
return running
23+
}
24+
25+
describe('Hub store', () => {
26+
it('persists an owner credential and protects session secrets with digests', () => {
27+
const directory = temporaryDirectory()
28+
const path = join(directory, 'hub.sqlite')
29+
const store = new HubStore(path)
30+
const owner = store.createOwnerWithCredential({
31+
username: 'Owner',
32+
credential: { id: 'credential-id', publicKey: new Uint8Array([1, 2, 3]), counter: 0, transports: ['internal'] },
33+
deviceType: 'singleDevice',
34+
backedUp: false,
35+
now: 1_000,
36+
})
37+
const created = store.createSession(owner.id, 2_000, 10_000)
38+
expect(store.authenticateSession(created.token, 3_000)?.userId).toBe(owner.id)
39+
expect(store.authenticateSession(`${created.session.id}.wrong`, 3_000)).toBeNull()
40+
expect(store.validateCsrf(created.session.id, created.csrf)).toBe(true)
41+
expect(store.revokeSession(created.session.id, 4_000)).toBe(true)
42+
expect(store.authenticateSession(created.token, 5_000)).toBeNull()
43+
store.close()
44+
45+
const reopened = new HubStore(path)
46+
expect(reopened.owner()?.username).toBe('Owner')
47+
expect(reopened.credentialsForUser(owner.id)[0]?.publicKey).toEqual(new Uint8Array([1, 2, 3]))
48+
reopened.close()
49+
})
50+
})
51+
52+
describe('Hub HTTP security boundary', () => {
53+
it('does not disclose the one-time bootstrap token through status', async () => {
54+
const running = await server()
55+
expect(running.bootstrapToken).toBeTruthy()
56+
const response = await fetch(`${running.url}/api/v1/hub/status`)
57+
const body = await response.text()
58+
expect(response.status).toBe(200)
59+
expect(body).not.toContain(running.bootstrapToken as string)
60+
expect(JSON.parse(body)).toEqual({ service: 'crewcode-hub', protocolVersion: 1, ownerConfigured: false })
61+
})
62+
63+
it('rejects foreign browser origins and unauthenticated machine access', async () => {
64+
const running = await server()
65+
const foreign = await fetch(`${running.url}/api/v1/hub/status`, { headers: { origin: 'https://evil.example' } })
66+
expect(foreign.status).toBe(403)
67+
const machines = await fetch(`${running.url}/api/v1/hub/machines`)
68+
expect(machines.status).toBe(401)
69+
})
70+
71+
it('trusts only the configured HTTPS RP origin, not the internal listener host', async () => {
72+
const running = await startHubServer({ dataDir: temporaryDirectory(), port: 0, publicOrigin: 'https://crewcode.example' })
73+
cleanups.push(() => running.close())
74+
const internal = await fetch(`${running.url}/api/v1/hub/status`, { headers: { origin: running.url } })
75+
expect(internal.status).toBe(403)
76+
const configured = await fetch(`${running.url}/api/v1/hub/status`, { headers: { origin: 'https://crewcode.example' } })
77+
expect(configured.status).toBe(200)
78+
})
79+
80+
it('serves the standalone setup screen with a restrictive CSP', async () => {
81+
const running = await server()
82+
const response = await fetch(running.url)
83+
expect(response.status).toBe(200)
84+
expect(response.headers.get('content-security-policy')).toContain("script-src 'self'")
85+
expect(response.headers.get('content-security-policy')).toContain("frame-ancestors 'none'")
86+
expect(await response.text()).not.toContain('<script>')
87+
})
88+
})

0 commit comments

Comments
 (0)