Othavio Quiliao commited on
Commit
04b82f8
Β·
unverified Β·
1 Parent(s): 4690be8

fix: align Mission Control device auth handshake with OpenClaw protocol

Browse files
Files changed (2) hide show
  1. src/lib/device-identity.ts +26 -19
  2. src/lib/websocket.ts +30 -11
src/lib/device-identity.ts CHANGED
@@ -24,17 +24,19 @@ export interface DeviceIdentity {
24
 
25
  // ── Helpers ──────────────────────────────────────────────────────
26
 
27
- function toBase64(buffer: ArrayBuffer): string {
28
  const bytes = new Uint8Array(buffer)
29
  let binary = ''
30
  for (let i = 0; i < bytes.byteLength; i++) {
31
  binary += String.fromCharCode(bytes[i])
32
  }
33
- return btoa(binary)
34
  }
35
 
36
- function fromBase64(b64: string): Uint8Array {
37
- const binary = atob(b64)
 
 
38
  const bytes = new Uint8Array(binary.length)
39
  for (let i = 0; i < binary.length; i++) {
40
  bytes[i] = binary.charCodeAt(i)
@@ -42,14 +44,18 @@ function fromBase64(b64: string): Uint8Array {
42
  return bytes
43
  }
44
 
45
- function generateUUID(): string {
46
- return crypto.randomUUID()
 
 
 
 
47
  }
48
 
49
  // ── Key management ───────────────────────────────────────────────
50
 
51
  async function importPrivateKey(pkcs8Bytes: Uint8Array): Promise<CryptoKey> {
52
- return crypto.subtle.importKey('pkcs8', pkcs8Bytes.buffer as ArrayBuffer, 'Ed25519', false, ['sign'])
53
  }
54
 
55
  async function createNewIdentity(): Promise<DeviceIdentity> {
@@ -58,9 +64,10 @@ async function createNewIdentity(): Promise<DeviceIdentity> {
58
  const pubRaw = await crypto.subtle.exportKey('raw', keyPair.publicKey)
59
  const privPkcs8 = await crypto.subtle.exportKey('pkcs8', keyPair.privateKey)
60
 
61
- const deviceId = generateUUID()
62
- const publicKeyBase64 = toBase64(pubRaw)
63
- const privateKeyBase64 = toBase64(privPkcs8)
 
64
 
65
  localStorage.setItem(STORAGE_DEVICE_ID, deviceId)
66
  localStorage.setItem(STORAGE_PUBKEY, publicKeyBase64)
@@ -86,7 +93,7 @@ export async function getOrCreateDeviceIdentity(): Promise<DeviceIdentity> {
86
 
87
  if (storedId && storedPub && storedPriv) {
88
  try {
89
- const privateKey = await importPrivateKey(fromBase64(storedPriv))
90
  return {
91
  deviceId: storedId,
92
  publicKeyBase64: storedPub,
@@ -102,19 +109,19 @@ export async function getOrCreateDeviceIdentity(): Promise<DeviceIdentity> {
102
  }
103
 
104
  /**
105
- * Signs a server nonce with the Ed25519 private key.
106
- * Returns base64-encoded signature and signing timestamp.
107
  */
108
- export async function signChallenge(
109
  privateKey: CryptoKey,
110
- nonce: string
 
111
  ): Promise<{ signature: string; signedAt: number }> {
112
  const encoder = new TextEncoder()
113
- const nonceBytes = encoder.encode(nonce)
114
- const signedAt = Date.now()
115
- const signatureBuffer = await crypto.subtle.sign('Ed25519', privateKey, nonceBytes)
116
  return {
117
- signature: toBase64(signatureBuffer),
118
  signedAt,
119
  }
120
  }
 
24
 
25
  // ── Helpers ──────────────────────────────────────────────────────
26
 
27
+ function toBase64Url(buffer: ArrayBuffer): string {
28
  const bytes = new Uint8Array(buffer)
29
  let binary = ''
30
  for (let i = 0; i < bytes.byteLength; i++) {
31
  binary += String.fromCharCode(bytes[i])
32
  }
33
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '')
34
  }
35
 
36
+ function fromBase64Url(value: string): Uint8Array {
37
+ const normalized = value.replace(/-/g, '+').replace(/_/g, '/')
38
+ const padded = normalized + '='.repeat((4 - (normalized.length % 4)) % 4)
39
+ const binary = atob(padded)
40
  const bytes = new Uint8Array(binary.length)
41
  for (let i = 0; i < binary.length; i++) {
42
  bytes[i] = binary.charCodeAt(i)
 
44
  return bytes
45
  }
46
 
47
+ async function sha256Hex(buffer: ArrayBuffer): Promise<string> {
48
+ const digest = await crypto.subtle.digest('SHA-256', new Uint8Array(buffer))
49
+ const bytes = new Uint8Array(digest)
50
+ return Array.from(bytes)
51
+ .map((b) => b.toString(16).padStart(2, '0'))
52
+ .join('')
53
  }
54
 
55
  // ── Key management ───────────────────────────────────────────────
56
 
57
  async function importPrivateKey(pkcs8Bytes: Uint8Array): Promise<CryptoKey> {
58
+ return crypto.subtle.importKey('pkcs8', pkcs8Bytes as unknown as BufferSource, 'Ed25519', false, ['sign'])
59
  }
60
 
61
  async function createNewIdentity(): Promise<DeviceIdentity> {
 
64
  const pubRaw = await crypto.subtle.exportKey('raw', keyPair.publicKey)
65
  const privPkcs8 = await crypto.subtle.exportKey('pkcs8', keyPair.privateKey)
66
 
67
+ // OpenClaw expects device.id = sha256(rawPublicKey) in lowercase hex.
68
+ const deviceId = await sha256Hex(pubRaw)
69
+ const publicKeyBase64 = toBase64Url(pubRaw)
70
+ const privateKeyBase64 = toBase64Url(privPkcs8)
71
 
72
  localStorage.setItem(STORAGE_DEVICE_ID, deviceId)
73
  localStorage.setItem(STORAGE_PUBKEY, publicKeyBase64)
 
93
 
94
  if (storedId && storedPub && storedPriv) {
95
  try {
96
+ const privateKey = await importPrivateKey(fromBase64Url(storedPriv))
97
  return {
98
  deviceId: storedId,
99
  publicKeyBase64: storedPub,
 
109
  }
110
 
111
  /**
112
+ * Signs an auth payload with the Ed25519 private key.
113
+ * Returns base64url signature and signing timestamp.
114
  */
115
+ export async function signPayload(
116
  privateKey: CryptoKey,
117
+ payload: string,
118
+ signedAt = Date.now()
119
  ): Promise<{ signature: string; signedAt: number }> {
120
  const encoder = new TextEncoder()
121
+ const payloadBytes = encoder.encode(payload)
122
+ const signatureBuffer = await crypto.subtle.sign('Ed25519', privateKey, payloadBytes)
 
123
  return {
124
+ signature: toBase64Url(signatureBuffer),
125
  signedAt,
126
  }
127
  }
src/lib/websocket.ts CHANGED
@@ -5,7 +5,7 @@ import { useMissionControl } from '@/store'
5
  import { normalizeModel } from '@/lib/utils'
6
  import {
7
  getOrCreateDeviceIdentity,
8
- signChallenge,
9
  getCachedDeviceToken,
10
  cacheDeviceToken,
11
  } from '@/lib/device-identity'
@@ -147,10 +147,33 @@ export function useWebSocket() {
147
  nonce: string
148
  } | undefined
149
 
 
 
 
 
 
 
 
 
 
150
  if (nonce) {
151
  try {
152
  const identity = await getOrCreateDeviceIdentity()
153
- const { signature, signedAt } = await signChallenge(identity.privateKey, nonce)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  device = {
155
  id: identity.deviceId,
156
  publicKey: identity.publicKeyBase64,
@@ -163,8 +186,6 @@ export function useWebSocket() {
163
  }
164
  }
165
 
166
- const cachedToken = getCachedDeviceToken()
167
-
168
  const connectRequest = {
169
  type: 'req',
170
  method: 'connect',
@@ -173,18 +194,16 @@ export function useWebSocket() {
173
  minProtocol: PROTOCOL_VERSION,
174
  maxProtocol: PROTOCOL_VERSION,
175
  client: {
176
- id: 'gateway-client',
177
  displayName: 'Mission Control',
178
  version: APP_VERSION,
179
  platform: 'web',
180
- mode: 'ui',
181
  instanceId: `mc-${Date.now()}`
182
  },
183
- role: 'operator',
184
- scopes: ['operator.admin'],
185
- auth: authTokenRef.current
186
- ? { token: authTokenRef.current }
187
- : undefined,
188
  device,
189
  deviceToken: cachedToken || undefined,
190
  }
 
5
  import { normalizeModel } from '@/lib/utils'
6
  import {
7
  getOrCreateDeviceIdentity,
8
+ signPayload,
9
  getCachedDeviceToken,
10
  cacheDeviceToken,
11
  } from '@/lib/device-identity'
 
147
  nonce: string
148
  } | undefined
149
 
150
+ const cachedToken = getCachedDeviceToken()
151
+
152
+ const clientId = 'gateway-client'
153
+ const clientMode = 'ui'
154
+ const role = 'operator'
155
+ const scopes = ['operator.admin']
156
+ const authToken = authTokenRef.current || undefined
157
+ const tokenForSignature = authToken ?? cachedToken ?? ''
158
+
159
  if (nonce) {
160
  try {
161
  const identity = await getOrCreateDeviceIdentity()
162
+ const signedAt = Date.now()
163
+ // Sign OpenClaw v2 device-auth payload (gateway accepts v2 and v3).
164
+ const payload = [
165
+ 'v2',
166
+ identity.deviceId,
167
+ clientId,
168
+ clientMode,
169
+ role,
170
+ scopes.join(','),
171
+ String(signedAt),
172
+ tokenForSignature,
173
+ nonce,
174
+ ].join('|')
175
+
176
+ const { signature } = await signPayload(identity.privateKey, payload, signedAt)
177
  device = {
178
  id: identity.deviceId,
179
  publicKey: identity.publicKeyBase64,
 
186
  }
187
  }
188
 
 
 
189
  const connectRequest = {
190
  type: 'req',
191
  method: 'connect',
 
194
  minProtocol: PROTOCOL_VERSION,
195
  maxProtocol: PROTOCOL_VERSION,
196
  client: {
197
+ id: clientId,
198
  displayName: 'Mission Control',
199
  version: APP_VERSION,
200
  platform: 'web',
201
+ mode: clientMode,
202
  instanceId: `mc-${Date.now()}`
203
  },
204
+ role,
205
+ scopes,
206
+ auth: authToken ? { token: authToken } : undefined,
 
 
207
  device,
208
  deviceToken: cachedToken || undefined,
209
  }