WebSocket の暗号化
GraphQL サブスクリプションは暗号化されたバイナリフレームを使用します。
このページは WSS /graphql を示します。セッションキーは XChaCha20-Poly1305 タグで init、ack、メッセージフレームを認証します。これらのフレームには Ed25519 署名や SignaturePurpose は含まれません。パスワードなしのログインは WSS /auth の ServerHello に署名します。認証を参照してください。
wss://<host>:<port>/graphql?cid=706c6169-3b80-8f42-9a61-4e312e54d001Init を送信
サーバーが Init を検証し、clientNonce を読み取ります。
リプレイ防止
…/graphql?cid=<clientId>binding = SHA256(fields(initFrame, ackFrame))client → server: seq 1, 2, 3…server → client: seq 1, 2, 3…seq = lastReceived + 1lastReceived ← seqclose再接続:新しい binding、カウンターをリセット
その他の WebSocket ルート
key: 既存セッションのトークン
wss://<host>:<port>/screen?cid=<clientId>Init · clientNonce
サーバーが Init を検証し、clientNonce を読み取ります。
操作
1. 接続
ソケットを開いた後に Init を送信します。cid はクライアントを識別します。
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 = 0n2. クライアント Init
10 秒以内に送信します。clientNonce はランダムな 32 バイトを 64 桁の hex で表したものです。AEAD nonce はフレームごとにランダムな 24 バイトです。
// 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.3. サーバー Ack
Ack を検証して binding を計算し、クライアントの sequence 1 で暗号化した空の確認を直ちに送信します。
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 })4. 暗号化メッセージの送信
direction に client を使用し、新しい nonce を使います。空の確認は sequence 1、業務メッセージは sequence 2 から厳密に増加します。
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))5. 暗号化メッセージの受信
lastReceived + 1(初回は 1)と direction server を必須とします。認証付き復号が成功した後にのみ進めます。
// 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))6. メッセージの種類
ping/pong を含むアプリケーションの JSON メッセージは暗号化します。WebSocket 固有の Ping/Pong 制御フレームはこの暗号化の対象外ですが、TLS で保護できます。subscriptionReady は準備完了を示します。
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: '...' }] }7. 制限と失敗
認証またはシーケンスの失敗時は切断します。新しいハンドシェイクで再接続してください。
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