NodePairingDialog.vue 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. <script setup lang="ts">
  2. import { computed, onBeforeUnmount, ref, watch } from 'vue'
  3. import QRCode from 'qrcode'
  4. import AppIcon from '@/components/common/AppIcon.vue'
  5. import { accountPairingStatus, createAccountPairing, type AccountPairingSession } from '@/api/accountPairing'
  6. import {
  7. createPairing,
  8. pairChildNode,
  9. pairedDevices,
  10. pairingStatus,
  11. revokePairedDevice,
  12. type NodeScope,
  13. type PairedDevice,
  14. type PairingSession,
  15. } from '@/api/pairing'
  16. const props = withDefaults(defineProps<{ open: boolean; insecureTransport?: boolean; userName?: string; isAdmin?: boolean }>(), {
  17. insecureTransport: false,
  18. userName: '',
  19. isAdmin: false,
  20. })
  21. const emit = defineEmits<{ close: [] }>()
  22. const ALL_SCOPES: NodeScope[] = [
  23. 'agents.read', 'history.read', 'sessions.execute', 'groups.read', 'groups.execute',
  24. ]
  25. const pairing = ref<PairingSession>()
  26. const accountPairing = ref<AccountPairingSession>()
  27. const qrImage = ref('')
  28. const accountQrImage = ref('')
  29. const accountPairingComplete = ref(false)
  30. const devices = ref<PairedDevice[]>([])
  31. const nodeID = ref('')
  32. const busy = ref(false)
  33. const error = ref('')
  34. const childCode = ref('')
  35. const childName = ref('')
  36. const scanVideo = ref<HTMLVideoElement>()
  37. const scanning = ref(false)
  38. const now = ref(Date.now())
  39. let timer: number | undefined
  40. let accountTimer: number | undefined
  41. let scanTimer: number | undefined
  42. let scanStream: MediaStream | undefined
  43. type BarcodeDetectorLike = { detect(source: ImageBitmapSource): Promise<Array<{ rawValue?: string }>> }
  44. type BarcodeDetectorConstructor = new (options: { formats: string[] }) => BarcodeDetectorLike
  45. const secondsRemaining = computed(() => pairing.value
  46. ? Math.max(0, Math.ceil((pairing.value.expiresAt - now.value) / 1_000))
  47. : 0)
  48. const accountSecondsRemaining = computed(() => accountPairing.value
  49. ? Math.max(0, Math.ceil((accountPairing.value.expiresAt - now.value) / 1_000))
  50. : 0)
  51. function stopPolling() {
  52. if (timer !== undefined) window.clearInterval(timer)
  53. timer = undefined
  54. }
  55. function stopAccountPolling() {
  56. if (accountTimer !== undefined) window.clearInterval(accountTimer)
  57. accountTimer = undefined
  58. }
  59. async function pollAccountPairing() {
  60. now.value = Date.now()
  61. const current = accountPairing.value
  62. if (!current || accountSecondsRemaining.value <= 0) { stopAccountPolling(); return }
  63. try {
  64. const status = await accountPairingStatus(current.pairingId)
  65. if (status.state === 'claimed') {
  66. accountPairingComplete.value = true
  67. stopAccountPolling()
  68. } else if (status.state === 'expired') stopAccountPolling()
  69. } catch { /* Keep a still-valid QR code during transient polling failures. */ }
  70. }
  71. async function beginAccountPairing() {
  72. busy.value = true; error.value = ''; accountPairingComplete.value = false; stopAccountPolling()
  73. try {
  74. const created = await createAccountPairing()
  75. accountPairing.value = created
  76. now.value = Date.now()
  77. accountQrImage.value = await QRCode.toDataURL(created.qrPayload, {
  78. width: 296, margin: 2, errorCorrectionLevel: 'M', color: { dark: '#191918', light: '#ffffff' },
  79. })
  80. accountTimer = window.setInterval(() => { void pollAccountPairing() }, 1_000)
  81. } catch (cause) { error.value = cause instanceof Error ? cause.message : '无法创建手机登录二维码' }
  82. finally { busy.value = false }
  83. }
  84. function stopScanning() {
  85. if (scanTimer !== undefined) window.clearInterval(scanTimer)
  86. scanTimer = undefined
  87. scanStream?.getTracks().forEach(track => track.stop())
  88. scanStream = undefined
  89. scanning.value = false
  90. }
  91. async function startScanning() {
  92. const Detector = (window as unknown as { BarcodeDetector?: BarcodeDetectorConstructor }).BarcodeDetector
  93. if (!Detector || !navigator.mediaDevices?.getUserMedia) {
  94. error.value = '当前浏览器不支持直接扫码,请粘贴配对码。'
  95. return
  96. }
  97. stopScanning(); error.value = ''
  98. try {
  99. scanStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' }, audio: false })
  100. scanning.value = true
  101. await new Promise(resolve => window.setTimeout(resolve, 0))
  102. if (scanVideo.value) { scanVideo.value.srcObject = scanStream; await scanVideo.value.play() }
  103. const detector = new Detector({ formats: ['qr_code'] })
  104. scanTimer = window.setInterval(() => {
  105. const video = scanVideo.value
  106. if (!video || video.readyState < 2) return
  107. void detector.detect(video).then(values => {
  108. const payload = values.find(value => value.rawValue?.startsWith('yaoyao://pair'))?.rawValue
  109. if (payload) { childCode.value = payload; stopScanning() }
  110. }).catch(() => undefined)
  111. }, 350)
  112. } catch { error.value = '无法使用摄像头,请检查权限或直接粘贴配对码。'; stopScanning() }
  113. }
  114. async function refreshDevices() {
  115. const response = await pairedDevices()
  116. devices.value = response.devices
  117. nodeID.value = response.nodeId
  118. }
  119. async function poll() {
  120. now.value = Date.now()
  121. const current = pairing.value
  122. if (!current || secondsRemaining.value <= 0) {
  123. stopPolling()
  124. return
  125. }
  126. try {
  127. const status = await pairingStatus(current.pairingId)
  128. if (status.state === 'claimed') {
  129. pairing.value = undefined
  130. qrImage.value = ''
  131. stopPolling()
  132. await refreshDevices()
  133. } else if (status.state === 'expired') {
  134. stopPolling()
  135. }
  136. } catch {
  137. // A transient poll failure must not discard a still-valid QR code.
  138. }
  139. }
  140. async function beginPairing() {
  141. busy.value = true
  142. error.value = ''
  143. stopPolling()
  144. stopAccountPolling()
  145. try {
  146. const created = await createPairing(ALL_SCOPES)
  147. pairing.value = created
  148. now.value = Date.now()
  149. qrImage.value = await QRCode.toDataURL(created.qrPayload, {
  150. width: 296,
  151. margin: 2,
  152. errorCorrectionLevel: 'M',
  153. color: { dark: '#191918', light: '#ffffff' },
  154. })
  155. timer = window.setInterval(() => { void poll() }, 1_000)
  156. } catch (cause) {
  157. error.value = cause instanceof Error ? cause.message : '无法创建配对二维码'
  158. } finally {
  159. busy.value = false
  160. }
  161. }
  162. async function addChild() {
  163. busy.value = true
  164. error.value = ''
  165. try {
  166. await pairChildNode(childCode.value.trim(), childName.value.trim() || undefined)
  167. childCode.value = ''
  168. childName.value = ''
  169. } catch (cause) {
  170. error.value = cause instanceof Error ? cause.message : '添加子节点失败'
  171. } finally {
  172. busy.value = false
  173. }
  174. }
  175. async function revoke(device: PairedDevice) {
  176. if (!window.confirm(`撤销“${device.name}”的 Hermes 访问权限?`)) return
  177. busy.value = true
  178. error.value = ''
  179. try {
  180. await revokePairedDevice(device.id)
  181. await refreshDevices()
  182. } catch (cause) {
  183. error.value = cause instanceof Error ? cause.message : '撤销设备失败'
  184. } finally {
  185. busy.value = false
  186. }
  187. }
  188. watch(() => props.open, open => {
  189. stopPolling()
  190. stopScanning()
  191. pairing.value = undefined
  192. accountPairing.value = undefined
  193. qrImage.value = ''
  194. accountQrImage.value = ''
  195. accountPairingComplete.value = false
  196. error.value = ''
  197. if (open) {
  198. void beginAccountPairing()
  199. if (!props.isAdmin) return
  200. busy.value = true
  201. void refreshDevices()
  202. .catch(cause => { error.value = cause instanceof Error ? cause.message : '读取配对设备失败' })
  203. .finally(() => { busy.value = false })
  204. }
  205. })
  206. onBeforeUnmount(() => { stopPolling(); stopAccountPolling(); stopScanning() })
  207. </script>
  208. <template>
  209. <Teleport to="body">
  210. <Transition name="pairing-fade">
  211. <div v-if="open" class="pairing-layer" role="presentation" @mousedown.self="emit('close')">
  212. <section class="pairing-dialog" role="dialog" aria-modal="true" aria-labelledby="pairing-title">
  213. <header>
  214. <div><small>YAOYAO MOBILE</small><h2 id="pairing-title">手机登录与节点</h2></div>
  215. <button class="icon-button" type="button" aria-label="关闭手机与节点" @click="emit('close')"><AppIcon name="close" /></button>
  216. </header>
  217. <p class="pairing-intro">手机扫描登录二维码后,会把这台 15300 保存为普通服务器账号;不会添加成子节点。</p>
  218. <p v-if="insecureTransport" class="pairing-warning"><AppIcon name="alert" :size="15" />当前是局域网 HTTP,二维码免密配对仅适用于可信网络。正式使用请配置 HTTPS/WSS 或 Tailscale。</p>
  219. <p v-if="error" class="pairing-error">{{ error }}</p>
  220. <section class="account-login-section">
  221. <div class="device-heading"><strong>扫码登录并添加服务器</strong><small>{{ userName }}</small></div>
  222. <section v-if="accountPairing" class="qr-card">
  223. <img v-if="accountQrImage" :src="accountQrImage" alt="手机扫码登录并添加服务器" />
  224. <strong>{{ accountPairingComplete ? '手机已添加此服务器' : '在 iOS 登录页选择扫码' }}</strong>
  225. <span v-if="accountPairingComplete">该二维码已经失效</span>
  226. <span v-else-if="accountSecondsRemaining">二维码将在 {{ accountSecondsRemaining }} 秒后失效</span>
  227. <span v-else>二维码已失效</span>
  228. <button v-if="accountPairingComplete || !accountSecondsRemaining" class="quiet-button" type="button" @click="beginAccountPairing">重新生成</button>
  229. </section>
  230. </section>
  231. <section v-if="isAdmin" class="device-section">
  232. <div class="device-heading"><strong>授权为 15300 子节点</strong><small>管理员</small></div>
  233. <section v-if="pairing" class="qr-card">
  234. <img v-if="qrImage" :src="qrImage" alt="添加此 Hermes 节点的二维码" />
  235. <strong>仅用于子节点配对</strong>
  236. <span v-if="secondsRemaining">二维码将在 {{ secondsRemaining }} 秒后失效</span>
  237. <span v-else>二维码已失效</span>
  238. <button v-if="!secondsRemaining" class="quiet-button" type="button" @click="beginPairing">重新生成</button>
  239. </section>
  240. <button v-else class="solid-button create-pairing" type="button" :disabled="busy" @click="beginPairing">
  241. <AppIcon name="users" :size="17" />{{ busy ? '正在准备…' : '生成子节点配对二维码' }}
  242. </button>
  243. </section>
  244. <section v-if="isAdmin" class="device-section">
  245. <div class="device-heading"><strong>已授权设备</strong><small v-if="nodeID">节点 {{ nodeID.slice(0, 8) }}</small></div>
  246. <p v-if="!busy && !devices.length" class="device-empty">还没有已授权设备。</p>
  247. <div v-for="device in devices" :key="device.id" class="device-row">
  248. <span><b>{{ device.name }}</b><small>{{ device.scopes.includes('history.read') ? 'Bots、历史与团队' : '受限访问' }}</small></span>
  249. <button type="button" :disabled="busy" @click="revoke(device)">撤销</button>
  250. </div>
  251. </section>
  252. <section v-if="isAdmin" class="device-section child-section">
  253. <div class="device-heading"><strong>添加 15300 子节点</strong><small>只管理直接子节点</small></div>
  254. <label><span>节点名称(可选)</span><input v-model="childName" placeholder="例如:办公室 Mac" /></label>
  255. <label><span>子节点配对码</span><textarea v-model="childCode" rows="3" placeholder="粘贴子节点生成的 yaoyao://pair…" /></label>
  256. <video v-if="scanning" ref="scanVideo" class="scanner-video" muted playsinline />
  257. <button class="quiet-button" type="button" @click="scanning ? stopScanning() : startScanning()">{{ scanning ? '停止扫码' : '使用摄像头扫码' }}</button>
  258. <button class="solid-button create-pairing" type="button" :disabled="busy || !childCode.trim()" @click="addChild">验证并添加子节点</button>
  259. </section>
  260. </section>
  261. </div>
  262. </Transition>
  263. </Teleport>
  264. </template>
  265. <style scoped>
  266. .pairing-layer { position: fixed; z-index: 260; inset: 0; display: grid; place-items: center; padding: 18px; background: var(--scrim); backdrop-filter: blur(6px); }
  267. .pairing-dialog { width: min(470px, 100%); max-height: min(760px, calc(100vh - 36px)); overflow-y: auto; padding: 18px; border: 1px solid var(--line); border-radius: 18px; background: var(--surface-raised); box-shadow: var(--shadow-float); }
  268. header { display: flex; align-items: flex-start; justify-content: space-between; } header small { color: var(--text-muted); font-size: 9px; letter-spacing: .08em; } h2 { margin: 3px 0 0; font-size: 19px; letter-spacing: -.03em; }
  269. .pairing-intro { margin: 17px 0 14px; color: var(--text-secondary); font-size: 11px; line-height: 1.65; }
  270. .pairing-warning, .pairing-error { margin: 0 0 13px; padding: 10px; border-radius: 10px; font-size: 10px; line-height: 1.55; }.pairing-warning { display: flex; gap: 7px; background: color-mix(in srgb, var(--warning, #bd7611) 10%, transparent); color: var(--text-secondary); }.pairing-error { background: color-mix(in srgb, var(--danger) 9%, transparent); color: var(--danger); }
  271. .create-pairing { width: 100%; min-height: 43px; gap: 8px; }
  272. .account-login-section { display: grid; gap: 8px; margin-top: 14px; }.account-login-section > .device-heading { margin-bottom: 0; }
  273. .pairing-credentials { display: grid; gap: 10px; margin-bottom: 13px; }.pairing-credentials label { display: grid; gap: 5px; color: var(--text-secondary); font-size: 10px; }.pairing-credentials input { min-height: 38px; padding: 0 10px; border: 1px solid var(--line); border-radius: 10px; outline: 0; background: var(--surface-soft); color: var(--text-primary); }.pairing-credentials input:focus { border-color: var(--line-strong); box-shadow: 0 0 0 3px var(--focus-ring); }.pairing-credentials small { color: var(--text-muted); font-size: 9px; line-height: 1.5; }
  274. .qr-card { display: grid; justify-items: center; gap: 7px; padding: 14px; border: 1px solid var(--line); border-radius: 14px; background: #fff; color: #191918; }.qr-card img { width: min(296px, 100%); aspect-ratio: 1; }.qr-card strong { font-size: 12px; }.qr-card span { color: #686865; font-size: 10px; }.qr-card .quiet-button { color: #191918; }
  275. .device-section { margin-top: 19px; padding-top: 15px; border-top: 1px solid var(--line); }.device-heading { display: flex; justify-content: space-between; margin-bottom: 8px; }.device-heading strong { font-size: 11px; }.device-heading small, .device-empty { color: var(--text-muted); font-size: 9px; }.device-empty { margin: 12px 1px; }
  276. .device-row { display: flex; align-items: center; gap: 12px; min-height: 47px; padding: 6px 2px; border-bottom: 1px solid var(--line); }.device-row span { display: flex; min-width: 0; flex: 1; flex-direction: column; gap: 3px; }.device-row b { overflow: hidden; font-size: 11px; text-overflow: ellipsis; white-space: nowrap; }.device-row small { color: var(--text-muted); font-size: 9px; }.device-row button { border: 0; background: transparent; color: var(--danger); font-size: 10px; cursor: pointer; }
  277. .child-section { display: grid; gap: 9px; }.child-section label { display: grid; gap: 5px; color: var(--text-secondary); font-size: 10px; }.child-section input,.child-section textarea { padding: 9px 10px; border: 1px solid var(--line); border-radius: 9px; background: var(--surface-soft); color: var(--text-primary); font: inherit; resize: vertical; }
  278. .scanner-video { width: 100%; max-height: 260px; border-radius: 11px; background: #111; object-fit: cover; }
  279. .pairing-fade-enter-active, .pairing-fade-leave-active { transition: opacity 140ms ease; }.pairing-fade-enter-active .pairing-dialog, .pairing-fade-leave-active .pairing-dialog { transition: transform 170ms var(--ease-out); }.pairing-fade-enter-from, .pairing-fade-leave-to { opacity: 0; }.pairing-fade-enter-from .pairing-dialog, .pairing-fade-leave-to .pairing-dialog { transform: translateY(8px) scale(.985); }
  280. @media (max-width: 540px) { .pairing-layer { place-items: end center; padding: 0; }.pairing-dialog { width: 100%; max-height: calc(100vh - 12px); border-radius: 19px 19px 0 0; padding-bottom: max(18px, env(safe-area-inset-bottom)); } }
  281. </style>