pairing.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. import {
  2. createCipheriv,
  3. createDecipheriv,
  4. createHash,
  5. randomBytes,
  6. randomUUID,
  7. timingSafeEqual,
  8. } from 'node:crypto'
  9. import {
  10. mkdirSync,
  11. readFileSync,
  12. renameSync,
  13. writeFileSync,
  14. } from 'node:fs'
  15. import { join } from 'node:path'
  16. import { HttpError } from './errors.js'
  17. const PAIRING_TTL_MS = 2 * 60 * 1_000
  18. const MAX_PENDING_PAIRINGS = 32
  19. const MAX_PAIRED_DEVICES = 64
  20. const TOKEN_BYTES = 32
  21. export const NODE_PAIRING_PROTOCOL_VERSION = 1
  22. export const DEFAULT_NODE_SCOPES = [
  23. 'agents.read',
  24. 'history.read',
  25. 'sessions.execute',
  26. 'groups.read',
  27. 'groups.execute',
  28. ] as const
  29. export type NodeScope = typeof DEFAULT_NODE_SCOPES[number]
  30. interface PersistedDevice {
  31. id: string
  32. name: string
  33. tokenHash: string
  34. encryptedCookie: string
  35. scopes: NodeScope[]
  36. createdAt: number
  37. lastUsedAt: number
  38. }
  39. interface PersistedPairingState {
  40. version: 1
  41. nodeID: string
  42. devices: PersistedDevice[]
  43. }
  44. interface PendingPairing {
  45. id: string
  46. secretHash: Buffer
  47. cookieHeader: string
  48. scopes: NodeScope[]
  49. createdAt: number
  50. expiresAt: number
  51. claimedDeviceID?: string
  52. }
  53. export interface PairingSession {
  54. id: string
  55. secret: string
  56. nodeID: string
  57. fingerprint: string
  58. scopes: NodeScope[]
  59. createdAt: number
  60. expiresAt: number
  61. }
  62. export interface PairedDeviceSummary {
  63. id: string
  64. name: string
  65. scopes: NodeScope[]
  66. createdAt: number
  67. lastUsedAt: number
  68. }
  69. export interface PairingClaim {
  70. pairingID: string
  71. secret: string
  72. deviceName: string
  73. }
  74. export interface PairingClaimResult {
  75. device: PairedDeviceSummary
  76. token: string
  77. nodeID: string
  78. fingerprint: string
  79. scopes: NodeScope[]
  80. }
  81. function hashSecret(value: string): Buffer {
  82. return createHash('sha256').update(value, 'utf8').digest()
  83. }
  84. function canonicalDeviceName(value: string): string {
  85. const normalized = value.trim().replace(/\s+/g, ' ')
  86. if (!normalized || normalized.length > 100 || /[\u0000-\u001f\u007f]/.test(normalized)) {
  87. throw new HttpError(400, 'Device name is invalid', 'invalid_device_name')
  88. }
  89. return normalized
  90. }
  91. function canonicalPairingID(value: string): string {
  92. const normalized = value.trim().toLowerCase()
  93. if (!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(normalized)) {
  94. throw new HttpError(400, 'Pairing ID is invalid', 'invalid_pairing')
  95. }
  96. return normalized
  97. }
  98. function canonicalDeviceID(value: string): string {
  99. const normalized = value.trim().toLowerCase()
  100. if (!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(normalized)) {
  101. throw new HttpError(400, 'Device ID is invalid', 'invalid_device')
  102. }
  103. return normalized
  104. }
  105. function parseScopes(value: readonly string[] | undefined): NodeScope[] {
  106. const requested = value ?? [...DEFAULT_NODE_SCOPES]
  107. const allowed = new Set<string>(DEFAULT_NODE_SCOPES)
  108. const result: NodeScope[] = []
  109. for (const scope of requested) {
  110. if (!allowed.has(scope)) {
  111. throw new HttpError(400, `Unsupported node scope: ${scope}`, 'invalid_scope')
  112. }
  113. if (!result.includes(scope as NodeScope)) result.push(scope as NodeScope)
  114. }
  115. if (result.length === 0) throw new HttpError(400, 'At least one node scope is required', 'invalid_scope')
  116. return result
  117. }
  118. function persistentSecret(home: string): Buffer {
  119. mkdirSync(home, { recursive: true, mode: 0o700 })
  120. const path = join(home, 'node-pairing-secret.bin')
  121. try {
  122. const existing = readFileSync(path)
  123. if (existing.byteLength !== 32) throw new Error('Node pairing secret has an invalid length')
  124. return existing
  125. } catch (error) {
  126. if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
  127. }
  128. const generated = randomBytes(32)
  129. try {
  130. writeFileSync(path, generated, { mode: 0o600, flag: 'wx' })
  131. return generated
  132. } catch (error) {
  133. if ((error as NodeJS.ErrnoException).code === 'EEXIST') return readFileSync(path)
  134. throw error
  135. }
  136. }
  137. export class NodePairingStore {
  138. readonly #home: string
  139. readonly #secret: Buffer
  140. readonly #statePath: string
  141. readonly #clock: () => number
  142. readonly #pending = new Map<string, PendingPairing>()
  143. #state: PersistedPairingState
  144. constructor(home: string, clock: () => number = Date.now) {
  145. this.#home = home
  146. this.#secret = persistentSecret(home)
  147. this.#statePath = join(home, 'paired-devices.json')
  148. this.#clock = clock
  149. this.#state = this.#load()
  150. }
  151. get nodeID(): string { return this.#state.nodeID }
  152. get fingerprint(): string {
  153. return createHash('sha256')
  154. .update(this.#state.nodeID, 'utf8')
  155. .update(this.#secret)
  156. .digest('base64url')
  157. }
  158. create(cookieHeader: string | undefined, requestedScopes?: readonly string[]): PairingSession {
  159. const cookies = cookieHeader?.trim() ?? ''
  160. if (!cookies) {
  161. throw new HttpError(401, 'An authenticated Hermes session is required', 'authentication_required')
  162. }
  163. this.#prunePending()
  164. while (this.#pending.size >= MAX_PENDING_PAIRINGS) {
  165. const oldest = this.#pending.keys().next().value as string | undefined
  166. if (!oldest) break
  167. this.#pending.delete(oldest)
  168. }
  169. const id = randomUUID().toLowerCase()
  170. const secret = randomBytes(TOKEN_BYTES).toString('base64url')
  171. const now = this.#clock()
  172. const pending: PendingPairing = {
  173. id,
  174. secretHash: hashSecret(`${id}:${secret}`),
  175. cookieHeader: cookies,
  176. scopes: parseScopes(requestedScopes),
  177. createdAt: now,
  178. expiresAt: now + PAIRING_TTL_MS,
  179. }
  180. this.#pending.set(id, pending)
  181. return {
  182. id,
  183. secret,
  184. nodeID: this.nodeID,
  185. fingerprint: this.fingerprint,
  186. scopes: [...pending.scopes],
  187. createdAt: now,
  188. expiresAt: pending.expiresAt,
  189. }
  190. }
  191. status(pairingID: string): { state: 'pending' | 'claimed' | 'expired'; deviceID?: string } {
  192. const id = canonicalPairingID(pairingID)
  193. const pending = this.#pending.get(id)
  194. if (!pending || pending.expiresAt <= this.#clock()) {
  195. this.#pending.delete(id)
  196. return { state: 'expired' }
  197. }
  198. return pending.claimedDeviceID
  199. ? { state: 'claimed', deviceID: pending.claimedDeviceID }
  200. : { state: 'pending' }
  201. }
  202. claim(input: PairingClaim): PairingClaimResult {
  203. this.#prunePending()
  204. const id = canonicalPairingID(input.pairingID)
  205. const pending = this.#pending.get(id)
  206. if (!pending || pending.expiresAt <= this.#clock()) {
  207. this.#pending.delete(id)
  208. throw new HttpError(410, 'Pairing code expired', 'pairing_expired')
  209. }
  210. if (pending.claimedDeviceID) {
  211. throw new HttpError(409, 'Pairing code was already used', 'pairing_already_used')
  212. }
  213. const supplied = hashSecret(`${id}:${input.secret}`)
  214. if (supplied.byteLength !== pending.secretHash.byteLength
  215. || !timingSafeEqual(supplied, pending.secretHash)) {
  216. throw new HttpError(401, 'Pairing secret is invalid', 'invalid_pairing_secret')
  217. }
  218. if (this.#state.devices.length >= MAX_PAIRED_DEVICES) {
  219. throw new HttpError(409, 'Paired device limit reached', 'paired_device_limit')
  220. }
  221. const now = this.#clock()
  222. const token = randomBytes(TOKEN_BYTES).toString('base64url')
  223. const device: PersistedDevice = {
  224. id: randomUUID().toLowerCase(),
  225. name: canonicalDeviceName(input.deviceName),
  226. tokenHash: hashSecret(token).toString('base64url'),
  227. encryptedCookie: this.#encrypt(pending.cookieHeader),
  228. scopes: [...pending.scopes],
  229. createdAt: now,
  230. lastUsedAt: now,
  231. }
  232. this.#state.devices.push(device)
  233. pending.claimedDeviceID = device.id
  234. pending.cookieHeader = ''
  235. this.#save()
  236. return {
  237. device: this.#summary(device),
  238. token,
  239. nodeID: this.nodeID,
  240. fingerprint: this.fingerprint,
  241. scopes: [...device.scopes],
  242. }
  243. }
  244. list(): PairedDeviceSummary[] {
  245. return this.#state.devices
  246. .map((device) => this.#summary(device))
  247. .sort((left, right) => right.lastUsedAt - left.lastUsedAt)
  248. }
  249. hasDevice(deviceID: string): boolean {
  250. try {
  251. const id = canonicalDeviceID(deviceID)
  252. return this.#state.devices.some((device) => device.id === id)
  253. } catch {
  254. return false
  255. }
  256. }
  257. delegatedCookies(deviceID: string): string {
  258. const id = canonicalDeviceID(deviceID)
  259. const device = this.#state.devices.find((candidate) => candidate.id === id)
  260. if (!device) throw new HttpError(404, 'Paired device was not found', 'paired_device_not_found')
  261. return this.#decrypt(device.encryptedCookie)
  262. }
  263. revoke(deviceID: string): boolean {
  264. const id = canonicalDeviceID(deviceID)
  265. const before = this.#state.devices.length
  266. this.#state.devices = this.#state.devices.filter((device) => device.id !== id)
  267. if (this.#state.devices.length === before) return false
  268. this.#save()
  269. return true
  270. }
  271. authorize(deviceID: string, token: string, requiredScope?: NodeScope): string {
  272. const id = canonicalDeviceID(deviceID)
  273. const normalizedToken = token.trim()
  274. if (!normalizedToken || normalizedToken.length > 512) {
  275. throw new HttpError(401, 'Paired device token is missing', 'paired_device_unauthorized')
  276. }
  277. const device = this.#state.devices.find((candidate) => candidate.id === id)
  278. if (!device) throw new HttpError(401, 'Paired device is not recognized', 'paired_device_unauthorized')
  279. const expected = Buffer.from(device.tokenHash, 'base64url')
  280. const supplied = hashSecret(normalizedToken)
  281. if (expected.byteLength !== supplied.byteLength || !timingSafeEqual(expected, supplied)) {
  282. throw new HttpError(401, 'Paired device token is invalid', 'paired_device_unauthorized')
  283. }
  284. if (requiredScope && !device.scopes.includes(requiredScope)) {
  285. throw new HttpError(403, `Paired device lacks ${requiredScope}`, 'paired_device_forbidden')
  286. }
  287. device.lastUsedAt = this.#clock()
  288. this.#save()
  289. return this.#decrypt(device.encryptedCookie)
  290. }
  291. updateCookies(deviceID: string, cookieHeader: string | undefined): void {
  292. const id = canonicalDeviceID(deviceID)
  293. const device = this.#state.devices.find((candidate) => candidate.id === id)
  294. if (!device || !cookieHeader?.trim()) return
  295. device.encryptedCookie = this.#encrypt(cookieHeader.trim())
  296. device.lastUsedAt = this.#clock()
  297. this.#save()
  298. }
  299. #summary(device: PersistedDevice): PairedDeviceSummary {
  300. return {
  301. id: device.id,
  302. name: device.name,
  303. scopes: [...device.scopes],
  304. createdAt: device.createdAt,
  305. lastUsedAt: device.lastUsedAt,
  306. }
  307. }
  308. #prunePending(): void {
  309. const now = this.#clock()
  310. for (const [id, pending] of this.#pending) {
  311. if (pending.expiresAt <= now) this.#pending.delete(id)
  312. }
  313. }
  314. #encrypt(value: string): string {
  315. const iv = randomBytes(12)
  316. const cipher = createCipheriv('aes-256-gcm', this.#secret, iv)
  317. const ciphertext = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()])
  318. return Buffer.concat([iv, cipher.getAuthTag(), ciphertext]).toString('base64url')
  319. }
  320. #decrypt(value: string): string {
  321. try {
  322. const encoded = Buffer.from(value, 'base64url')
  323. if (encoded.byteLength < 29) throw new Error('encrypted cookie is truncated')
  324. const iv = encoded.subarray(0, 12)
  325. const tag = encoded.subarray(12, 28)
  326. const ciphertext = encoded.subarray(28)
  327. const decipher = createDecipheriv('aes-256-gcm', this.#secret, iv)
  328. decipher.setAuthTag(tag)
  329. return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8')
  330. } catch {
  331. throw new HttpError(401, 'Paired device credentials are unavailable', 'paired_device_credentials_invalid')
  332. }
  333. }
  334. #load(): PersistedPairingState {
  335. try {
  336. const parsed = JSON.parse(readFileSync(this.#statePath, 'utf8')) as Partial<PersistedPairingState>
  337. if (parsed.version !== 1
  338. || typeof parsed.nodeID !== 'string'
  339. || !Array.isArray(parsed.devices)) {
  340. throw new Error('paired device state is invalid')
  341. }
  342. return {
  343. version: 1,
  344. nodeID: canonicalDeviceID(parsed.nodeID),
  345. devices: parsed.devices as PersistedDevice[],
  346. }
  347. } catch (error) {
  348. if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
  349. const state: PersistedPairingState = {
  350. version: 1,
  351. nodeID: randomUUID().toLowerCase(),
  352. devices: [],
  353. }
  354. this.#state = state
  355. this.#save()
  356. return state
  357. }
  358. }
  359. #save(): void {
  360. mkdirSync(this.#home, { recursive: true, mode: 0o700 })
  361. const temporary = `${this.#statePath}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`
  362. writeFileSync(temporary, `${JSON.stringify(this.#state, null, 2)}\n`, {
  363. mode: 0o600,
  364. flag: 'wx',
  365. })
  366. renameSync(temporary, this.#statePath)
  367. }
  368. }
  369. export function bearerToken(value: string | undefined): string {
  370. const match = value?.match(/^Bearer ([A-Za-z0-9_-]{20,512})$/)
  371. if (!match) throw new HttpError(401, 'Paired device bearer token is required', 'paired_device_unauthorized')
  372. return match[1]!
  373. }