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는 클라이언트를 식별합니다.

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자리 hex로 표현합니다. 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을 계산한 뒤 클라이언트 sequence 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. 암호화 메시지 전송

direction client와 새로운 nonce를 사용합니다. 빈 확인은 sequence 1이며 업무 메시지는 sequence 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)과 direction 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. 메시지 타입

ping/pong을 포함한 애플리케이션 JSON 메시지는 암호화합니다. 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