PlainApp
API 参考

WebSocket 加密

GraphQL 订阅通过加密二进制帧传输。

客户端
wss://<host>:<port>/graphql?cid=706c6169-3b80-8f42-9a61-4e312e54d001
服务端

客户端发送 Init

initFrame

服务端验证 Init,读取 clientNonce。

防重放

WebSocket 连接…/graphql?cid=<clientId>
↓
每次连接使用新的 Init / Ackbinding = SHA256(fields(initFrame, ackFrame))
↓
两个方向独立计数client → server: seq 1, 2, 3…server → client: seq 1, 2, 3…
↓
认证并解密seq = lastReceived + 1
✓ ↓接受lastReceived ← seq
✕ ↓拒绝close

重连:新 binding,序号归零

悬停或点按字段
1 / 5

其他 WebSocket 路由

客户端
wss://<host>:<port>/screen?cid=<clientId>
服务端

Init · clientNonce

Init

服务端验证 Init,读取 clientNonce。

XChaCha20-Poly1305 · 悬停或点按字段
1 / 5

操作

websocket

1. 建立连接

连接打开后发送 Init。cid 为客户端 ID。

typescript
const cid = '706c6169-3b80-8f42-9a61-4e312e54d001' // Your existing session's client ID
const socket = new WebSocket(
  'wss://<device-host>:<https-port>/graphql?cid=' + encodeURIComponent(cid)
)
socket.binaryType = 'arraybuffer'
let binding: Uint8Array
let lastSent = 0n
let lastReceived = 0n
protocol

2. 客户端 Init

10 秒内发送。clientNonce:32 个随机字节,编码为 64 个十六进制字符。AEAD nonce:每帧独立生成的 24 个随机字节。

typescript
// Run immediately on socket.open.
const init = {
  clientNonce: Array.from(randomBytes(32), n => n.toString(16).padStart(2, '0')).join(''),
}
const aad = fields([utf8.encode('WS_INIT'), utf8.encode('/graphql'), utf8.encode(cid)])
const initFrame = seal(key, utf8.encode(JSON.stringify(init)), aad)
socket.send(initFrame) // Retain these exact bytes for Ack.
protocol

3. 服务端 Ack

校验 Ack 并计算 binding;立即发送序号 1 的加密空明文确认,不发送业务消息。

typescript
socket.addEventListener('message', event => {
  const ackFrame = new Uint8Array(event.data)
  if (ackFrame.length < 40) throw new Error('Invalid Ack')
  const aad = fields([utf8.encode('WS_ACK'), utf8.encode('/graphql'), utf8.encode(cid), sha256(initFrame)])
  const ack: { serverNonce: string } = JSON.parse(decoder.decode(open(key, ackFrame, aad)))
  if (!/^[0-9a-f]{64}$/.test(ack.serverNonce)) throw new Error('Invalid serverNonce')
  binding = sha256(fields([initFrame, ackFrame]))
  lastSent = lastReceived = 0n
  const counter = uint64be(1n)
  const confirmationAad = fields([utf8.encode('WS_FRAME'), utf8.encode('/graphql'), utf8.encode(cid), binding, utf8.encode('client'), counter])
  const encrypted = seal(key, new Uint8Array(), confirmationAad)
  lastSent = 1n
  socket.send(concatBytes(counter, encrypted))
}, { once: true })
protocol

4. 发送加密消息

方向为 client,每帧使用新 nonce;空确认使用序号 1,业务从序号 2 起,之后严格递增。

typescript
const message = {
  type: 'subscribe', id: 'prefs',
  payload: { query: 'subscription { prefsChanged }' },
}
const next = lastSent + 1n
const counter = uint64be(next) // Reject overflow; never wrap.
const aad = fields([utf8.encode('WS_FRAME'), utf8.encode('/graphql'), utf8.encode(cid), binding, utf8.encode('client'), counter])
const encrypted = seal(key, utf8.encode(JSON.stringify(message)), aad)
lastSent = next // Advance only after successful encryption.
socket.send(concatBytes(counter, encrypted))
protocol

5. 接收加密消息

校验序列号为 lastReceived + 1,首帧为 1,方向为 server;认证解密成功后才推进计数器。

typescript
// For each binary message after Ack, in arrival order:
const frame = new Uint8Array(event.data)
if (frame.length < 48) throw new Error('Invalid frame')
const sequence = new DataView(frame.buffer).getBigUint64(0, false)
if (sequence !== lastReceived + 1n) throw new Error('Invalid sequence')
const aad = fields([utf8.encode('WS_FRAME'), utf8.encode('/graphql'), utf8.encode(cid), binding, utf8.encode('server'), frame.subarray(0, 8)])
const plaintext = open(key, frame.subarray(8), aad) // Throws on invalid tag.
lastReceived = sequence // Advance only after authentication.
const message = JSON.parse(decoder.decode(plaintext))
protocol

6. 消息类型

应用层 JSON 消息(包括 ping/pong)会加密。WebSocket 原生 Ping/Pong 控制帧不使用这层加密,但仍可由 TLS 保护。subscriptionReady 表示订阅已就绪。

typescript
const subscribe = {
  type: 'subscribe', id: 'prefs',
  payload: { query: 'subscription { prefsChanged }' },
}
const ready = {
  type: 'next', id: 'prefs',
  payload: { data: null, extensions: { subscriptionReady: true } },
}
const event = {
  type: 'next', id: 'prefs',
  payload: { data: { prefsChanged: true } },
}
const complete = { type: 'complete', id: 'prefs' }
const ping = { type: 'ping', payload: null }
const pong = { type: 'pong', payload: null }
const error = { type: 'error', id: 'prefs', payload: [{ message: '...' }] }
protocol

7. 限制与失败处理

认证或序号校验失败时关闭连接。重连后重新握手。

text
Server Init wait:     timeout(10 seconds, socket.next()), after upgrade and session-key lookup
Server confirmation:  timeout(10 seconds, socket.next()), after Ack send completes
Confirmation:         send encrypted empty payload immediately after Ack, client sequence 1
Business messages:    client starts at sequence 2; server starts at sequence 1
Init replay:          may receive a fresh Ack; old bound frames fail
Replay state:         connection counters, no timestamp or global cache
Message sequence:     last + 1, independently in each direction
Sequence overflow:    u64 max once; next frame fails, never wrap to 0
Frame size:           <= 1,048,576 bytes
Timeout/auth failure: close 1008, reason "invalid_subscription"
Reconnect:            fresh Init / Ack, new binding, last counters reset to 0; no legacy fallback