@dokebi/websocket 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AI.md CHANGED
@@ -1,4 +1,4 @@
1
- # AI 작업 안내 — @dokebi/websocket 0.2.0
1
+ # AI 작업 안내 — @dokebi/websocket 0.3.0
2
2
 
3
3
  dokebi-web(Fastify) 위에 WebSocket 라우트를 열고 @dokebi/websocket-hub로 서버·워커 사이 방송·접속자 목록을 잇는다. 방송은 **많아야 한 번(at-most-once)** 이다: 허브가 내보내면 끝나고 클라이언트 ACK·재전송이 없다([D-0057](../../docs/decisions/D-0057-websocket-broadcast-without-ack.md)). 뷰·DB를 강제하지 않는다. Node >=24, core ^0.2.0, peer: @dokebi/web·@dokebi/websocket-hub. 세부는 [README](README.md)다.
4
4
 
@@ -27,6 +27,7 @@ npx dokebi add @dokebi/websocket-hub --set mode=cluster --set namespace=shop --s
27
27
  | `heartbeatMs` | 10000 | ping/pong |
28
28
  | `idleTimeoutMs` | 0(끔) | 클라이언트가 이 시간 동안 아무것도 안 보내면 4408 `Idle`. 페이지가 `{"$dokebi":"ping-v1"}`을 주기적으로 보낸다 |
29
29
  | `hubWaitMs` | 5000 | 허브가 recovering일 때 업그레이드가 기다리는 시간(0이면 바로 503) |
30
+ | `sealDriftMs` | 60000 | 봉인 연결(§4a): 프레임 ts가 서버 시계와 이만큼(1000~600000) 넘게 다르면 4400. nonce는 두 배 동안 기억 |
30
31
 
31
32
  ## 3. 라우트 — defineSocket(권장)
32
33
 
@@ -56,8 +57,29 @@ export const chatSocket = (app: AppContext) => defineSocket({
56
57
 
57
58
  - 메시지 형식: JSON `{ type, data?, id? }`. `reply`·`error`는 예약 type. 모르는 type은 `UNKNOWN_TYPE`, 잘못된 형식은 `INVALID_MESSAGE`, handler 오류는 오류의 `code`(대문자 형식) 또는 `HANDLER_FAILED`로 `{ type: 'error', id?, code }`(message·stack은 보내지 않고 서버 로그에 남김, §7).
58
59
  - `socket`: `session`·`identity`·`send(type, data)`(이 연결)·`broadcast(type, data, { room?, member? })`(허브로, tenant 고정 → receipt `{ id, recipients }`). 받는 소켓에는 `send`와 같은 `{ type, data }` 텍스트 프레임으로 간다.
59
- - 멀티 앱: @dokebi/app의 `sockets: (app) => [chatSocket(app)]`. 앱마다 같은 경로가 따로 등록되고 허브 tenant는 `<앱>:<tenant>`.
60
- - 저수준: `context.get(ws).route({ path, origins?, constraints?, version?, authenticate, authorizeRoom?, message(data, session), presence? })`. session: `id`·`identity`·`send`·`broadcast(bytes, target?)`·`join(room)`·`leave(room)`·`close(code?, reason?)`·`reportError?(error, details)`(§7).
60
+ - 멀티 앱: @dokebi/app의 `sockets: (app) => [chatSocket(app)]`. 앱마다 같은 경로가 따로 등록되고 허브 tenant는 `<네임스페이스>:<tenant>`(기본 네임스페이스는 앱 이름, D-0061). `authenticate`가 돌려주는 `namespace`는 @dokebi/app이 읽고 지운다. 이 패키지는 허브에 등록할 때 `namespace`를 빼고 넘긴다.
61
+ - 저수준: `context.get(ws).route({ path, origins?, constraints?, version?, seal?, authenticate, authorizeRoom?, message(data, session), presence? })`. session: `id`·`identity`·`send`·`broadcast(bytes, target?)`·`join(room)`·`leave(room)`·`close(code?, reason?)`·`reportError?(error, details)`(§7).
62
+
63
+ ## 3a. 서버 코드에서 보내기·조회 (0.3.0, [D-0061](../../docs/decisions/D-0061-realtime-namespaces.md))
64
+
65
+ 연결 밖(서버 코드·작업·관리자 앱)에서 tenant를 지정해 쓰는 API. @dokebi/app 앱은 보통 이것을 감싼 `app.realtime(namespace)`를 쓴다.
66
+
67
+ ```ts
68
+ const ws = context.get(websocket);
69
+ await ws.list({ tenant: 'shop:t1' }); // 허브에 묻는다(클러스터 전체, 허브 code로 실패)
70
+ await ws.list({ tenantPrefix: 'shop:', room: 'vip' }); // 이 서버가 받은 presence(모든 서버, 조금 늦을 수 있음)
71
+ await ws.send({ tenant: 'shop:t1', member: 'u42' }, 'chat.message', { text: 'hi' }); // { type, data } 텍스트
72
+ await ws.broadcast({ tenantPrefix: 'shop:' }, bytesOrText); // 원시 바이트(UTF-8이면 텍스트 프레임)
73
+ await ws.kick({ tenant: 'shop:t1', member: 'u42' }, 4403, 'Removed');
74
+ const stop = ws.onPresence(({ tenant, joined, left }) => {});
75
+ ```
76
+
77
+ - 필터: `tenant`와 `tenantPrefix` 중 **정확히 하나**, 더해 `room?`·`member?`(둘 다면 그 방의 그 사람). 문자열 1~256바이트. 어기면 `INVALID_FILTER`. `send`의 type은 handler type 규칙(`INVALID_TYPE`), JSON이 안 되는 data는 `INVALID_DATA`.
78
+ - `tenant`: 허브 호출 하나. 실패는 허브 code 그대로(`RECOVERING`·`BUSY`·`OUTCOME_UNKNOWN`). `tenantPrefix`: 허브에는 tenant를 넘는 조회가 없으므로 이 서버의 presence 거울에서 접두가 맞는 tenant를 모아 tenant마다 호출한다(16개씩 동시). 일부가 실패하면 첫 실패의 code로 거부하고 오류에 `receipt`(성공한 tenant 몫)와 `cause`(AggregateError)를 단다. 아는 tenant가 없으면 아무것도 보내지 않고 `{ ids: [], recipients: [] }`.
79
+ - 영수증 `{ ids, recipients }`: tenant마다 허브 방송 id, 그때 조건에 맞은 연결. 받았다는 확인이 아니다(D-0057). kick은 `{ ids }`.
80
+ - 봉인: 방송 전달 경로 그대로라 봉인 소켓은 소켓마다 봉인된 사본을, 평문 소켓은 같은 버퍼를 받는다. 바이너리는 봉인 소켓에 가지 않는다(§4a).
81
+ - `onPresence`: 모든 서버의 입·퇴장을 tenant마다(route `presence`와 같은 의미, 처음 보는 서버는 이미 있던 연결을 joined로 담을 수 있음). 던지거나 거부한 listener는 error `PRESENCE_LISTENER_FAILED`(10초당 한 줄)로 남고 다른 listener는 계속 돈다.
82
+ - debug: `WebSocket connections listed`(source `hub`·`presence`, 수, ms), `WebSocket server broadcast sent`(tenant 수·실패 수·recipients·bytes), `WebSocket server kick sent`, `WebSocket presence listener added/removed`, presence 변화 로그의 `listeners`.
61
83
 
62
84
  ## 4. 클라이언트가 할 일
63
85
 
@@ -72,7 +94,19 @@ setInterval(() => socket.send('{"$dokebi":"ping-v1"}'), 15000); // idleT
72
94
 
73
95
  - 방송은 서버가 보낸 바이트 그대로 온다: UTF-8이면 텍스트 프레임(`defineSocket`의 `{ type, data }` JSON), 아니면 바이너리 프레임. 풀 봉투(`delivery-v1`)도 보낼 ACK도 없다. 브라우저 진입점 `@dokebi/websocket/client`(`DeliveryReceiver`)는 0.2.0에서 없어졌다(import하면 모듈을 찾지 못함). 표준 `WebSocket` API만 쓴다. 옛 페이지가 보내는 `{"$dokebi":"ack-v1"}`은 닫지 않고 무시한다(debug `ACK_IGNORED`).
74
96
  - 연결이 끊긴 사이·느린 소비자로 닫힌 사이의 방송은 다시 오지 않는다. 화면은 다시 연결되면 서버에서 최신 상태를 읽는다.
75
- - 닫힘 코드: 4426 새로고침, 4409 같은 clientId 중복(`Duplicate client`), 4408 idle, 1013 허브 불가·느린 소비자, 1012 서버 종료, 1011 handler 미처리 오류.
97
+ - 닫힘 코드: 4426 새로고침, 4409 같은 clientId 중복(`Duplicate client`), 4408 idle, 1013 허브 불가·느린 소비자, 1012 서버 종료, 1011 handler 미처리 오류, 4415 봉인 호스트인데 `dokebi.seal` 제안 없음, 4400 봉인 프레임 거절(§4a). 4400·4415는 다시 붙어도 같으므로 재접속하지 않는다.
98
+
99
+ ## 4a. 봉인 연결 (0.3.0, [D-0059](../../docs/decisions/D-0059-seal-and-websocket-client.md) §4)
100
+
101
+ 호스트(또는 라우트)마다 모든 프레임을 봉인한다. **이 패키지는 봉인을 모른다**: 이름 `dokebi-seal`로 찾는 코덱 제공자(@dokebi/seal 플러그인)가 연결마다 프레임을 바꾼다. 공개 패키지는 @dokebi/seal을 import하지 않는다.
102
+
103
+ - 켜기: @dokebi/app이면 `options.dokebi-app.domains.<host>.seal: true`(앱이 route.seal을 채운다). 앱 없이: `route({ seal: true | (request) => boolean })`·`defineSocket({ seal })`. 봉인 라우트가 있는데 `dokebi-seal` 플러그인이 등록돼 있지 않으면 setup이 `SEAL_PROVIDER_MISSING`으로 실패한다(fail closed). `api.sealing`은 제공자가 있으면 true.
104
+ - 계약(구조만): `SocketCodecProvider { forConnection({ host, path, userAgent, nonces, driftMs }): SocketCodec }`, `SocketCodec { decode(frame): Promise<string>; encode(text): string; hello(): string }`. `host`는 web `requestHost`(trustProxy 반영)에서 포트를 뺀 소문자, `path`는 업그레이드 경로(질의 제외), `nonces`는 `hub.nonces()`(cluster = Redis 공유, local = 프로세스), `driftMs`는 `sealDriftMs`.
105
+ - 협상: 봉인 다리가 있는 클라이언트는 서브프로토콜 `['dokebi.seal', 'dokebi.plain']`(상수 `SEAL_PROTOCOL`·`PLAIN_PROTOCOL`)을 제안한다. 봉인 연결은 `dokebi.seal`만 고른다(plain은 절대 고르지 않음). 그것이 제안에 없으면 업그레이드 뒤 **4415** `Seal required`(재접속 안 함). 평문 연결은 `dokebi.plain`이 제안됐으면 그것을, 아니면 아무것도 고르지 않는다(옛 클라이언트). 클라이언트는 `ws.protocol === 'dokebi.seal'`로만 봉인을 판단하므로 같은 페이지 코드가 평문 호스트에서는 평문으로 돈다.
106
+ - 흐름: 서버가 맨 먼저 봉인된 `{"$dokebi":"hello-v1"}`을 보낸다(클라이언트는 그 ts로 시계 차이를 잡는다). 들어오는 프레임은 연결의 순서 사슬 안에서 열린 뒤 제어 프레임(`$dokebi` ping·ack)·라우트로 간다(대기 메시지 수에 포함). 라우트·handler는 평문 텍스트를 본다.
107
+ - 거절: 봉인 안 된 프레임·바이너리 프레임·열지 못함·drift·재전송은 **4400** `Bad frame`. 이유(`no-prefix`·`plain-rejected`·`drift`·`replay`·`open-failed`·`binary`)는 warn 로그에만 남고 클라이언트에는 가지 않는다(재전송 성공 여부를 엿보지 못하게). 거절 뒤 그 연결의 프레임은 읽지 않는다.
108
+ - 내보내기: 응답·`send`·presence·방송 모두 봉인. 평문 소켓은 방송 버퍼 하나를 나눠 쓰고 봉인 소켓만 수신자마다 봉인한다. UTF-8 바이트는 텍스트로 봉인해 보내고, UTF-8이 아닌 바이트를 `send`하면 `SEAL_BINARY_UNSUPPORTED`로 거절(`defineSocket`에서는 그 code의 오류 응답). 바이너리 방송은 봉인 소켓에 보내지 않고 센다(warn `SEAL_BINARY_UNSUPPORTED`, `dropped`).
109
+ - 비용(2026-10-15, `benchmarks/results/2026-10-15-websocket-seal.json`): 봉인·해제 1회 약 15~17µs(1KB), 수신자 500 방송 p50 약 14.5ms(평문 1.6ms), Redis nonce 붙은 요청 왕복 p50 0.38ms(평문 0.04ms).
76
110
 
77
111
  ## 5. 응답 코드와 전달 의미
78
112
 
@@ -91,6 +125,7 @@ stop: 새 업무 차단 → 받은 handler·송신 중 방송 대기 → 1012로
91
125
 
92
126
  - 예외를 조용히 버리지 않는다. 닫힘 코드·오류 응답으로 바꾸는 것 외의 실패는 `error`: 고정 영어 메시지 + `code` + `error`(원본 오류 전문: 이름·메시지 전체·스택과 cause마다 `Caused by: …`, 주소·포트·errno 메시지도 그대로, URL 자격 증명만 `//***@`로 가림, 16KB 초과분만 잘라 표시). 예: handler 실패 `WebSocket message handler failed`(code는 오류의 code 또는 `HANDLER_FAILED`, 1011로 닫음), 소켓 오류 `SOCKET_ERROR`, 방송 쓰기 실패 `BROADCAST_WRITE_FAILED`, presence handler `PRESENCE_HANDLER_FAILED`, 허브 이벤트 끊김 `HUB_EVENTS_FAILED`(모든 소켓 1013), 정리 지연 `PRESENCE_CLEANUP_DEFERRED`. 등록 실패는 warn(4409·1013로 닫음), 느린 소비자는 warn `SLOW_CONSUMER`. 이미 닫힌 소켓에 못 쓴 응답·presence는 warn `REPLY_DROPPED`(클라이언트가 떠났을 뿐 서버 실패가 아님, 10초에 한 번 + `repeated`).
93
127
  - 메시지·소켓마다 도는 자리는 같은 메시지·code를 10초당 한 줄로 쓰고 나머지는 `repeated` 개수로 묶는다(drain 끝에 남은 개수도 씀). 본문·토큰은 쓰지 않는다.
128
+ - 봉인(§4a): 프레임 거절은 warn `WebSocket sealed frame refused; closed`(code `SEAL_FRAME_REFUSED`, `reason`, `error`, 이유마다 10초당 한 줄 + `repeated`), 코덱 생성 실패 error `SEAL_CODEC_FAILED`(1011), 방송 봉인 실패 error `SEAL_ENCODE_FAILED`(1011), hello 송신 실패 warn `SEAL_HELLO_FAILED`. debug: 제공자 유무(`WebSocket seal provider`), 업그레이드마다 결정(`WebSocket seal decision`: path·sealed·offered), `WebSocket seal hello sent`, 4415(`WebSocket seal required; closed`), 연결 로그의 `sealed`, 방송 로그의 `sealed` 개수.
94
129
  - debug: 연결·닫힘·업그레이드 거절, 허브 등록 ms, 방 입장·퇴장·거절, presence 변화(개수), kick, 방송 전달(ID·연결 수·`binary`, `isEnabled` 확인 뒤), 옛 클라이언트의 `ack-v1` 무시(`ACK_IGNORED`, 10초당 한 줄 + `repeated`), idle·heartbeat 종료, drain 시작·끝. 대기 메시지 초과(1013 `Too many messages`)는 warn `TOO_MANY_MESSAGES`.
95
130
  - `defineSocket`의 handler 오류: 클라이언트에는 지금처럼 `{ type: 'error', id?, code }`만 가고(message·stack 없음, 소켓은 열린 채), 서버 로그에는 error `WebSocket handler failed.`(code `SOCKET_HANDLER_FAILED`, `type`=메시지 type, `reply`=클라이언트에 보낸 code, `connection`, `error`=전문)가 남는다. 반복은 type+reply code마다 10초당 한 줄. 잘못된 형식·모르는 type(클라이언트 잘못)은 debug `WebSocket client message refused`(code `INVALID_MESSAGE`·`UNKNOWN_TYPE`, code마다 세어 묶음).
96
131
  - 이 보고는 `session.reportError?(error, { source: 'handler' | 'client', code, type? })`로 간다. 게이트웨이가 만든 session에만 있고, 직접 만든 session(시험 등)에 없으면 `defineSocket`은 응답만 보낸다. 저수준 `route.message`도 같은 메서드로 보고할 수 있다.
@@ -103,4 +138,4 @@ stop: 새 업무 차단 → 받은 handler·송신 중 방송 대기 → 1012로
103
138
  - 방송은 많아야 한 번이다. 재접속·리더 교체·느린 소비자에서는 빠질 수 있고, `OUTCOME_UNKNOWN` 뒤에 다시 보내면 두 번 받을 수 있다.
104
139
  - 실제 두 컨테이너·네 워커 교차 전달, 허브 SIGKILL, NATS 장애 검증은 했지만 두 물리 장비·WAN 검증은 아니다(OPS-002).
105
140
 
106
- 근거: `examples/23-websocket`(두 Docker 서버·네 워커), `examples/25-playground`(앱별 소켓·presence·부하 시험), D-0024·D-0033·D-0034·D-0057(D-0025의 ACK를 대체).
141
+ 근거: `examples/23-websocket`(두 Docker 서버·네 워커), `examples/25-playground`(앱별 소켓·presence·부하 시험), D-0024·D-0033·D-0034·D-0057(D-0025의 ACK를 대체), D-0059 §4(봉인 — 실제 서버 시험과 Chromium 검사는 @dokebi/seal에 있다: `npm run seal:test`·`seal:browser-check`).
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @dokebi/websocket
2
2
 
3
- Node >=24, 0.2.0. Dokebi Fastify 웹과 websocket-hub를 연결하는 선택 플러그인. API 서버에 템플릿/뷰를 강제하지 않는다.
3
+ Node >=24, 0.3.0. Dokebi Fastify 웹과 websocket-hub를 연결하는 선택 플러그인. API 서버에 템플릿/뷰를 강제하지 않는다.
4
4
 
5
5
  ```ts
6
6
  import { Application, dependencyOf, loadConfig } from '@dokebi/core';
@@ -91,3 +91,31 @@ socket.onopen = () => reloadState(); // 끊긴 사이의 방송은 다
91
91
  - `route({ constraints })`: 업그레이드 라우트에 Fastify 라우트 제약을 붙인다. @dokebi/app이 `{ dokebiApp: '<앱>' }`으로 앱마다 같은 경로(`/ws`)를 따로 등록한다.
92
92
  - `defineSocket({ path, authenticate, on: { '<type>': handler } })`는 메시지 라우터가 붙은 라우트를 만든다. 메시지는 JSON `{ type, data?, id? }`다. 핸들러 `(data, socket)`의 반환값은 `id`가 있으면 `{ type: 'reply', id, data }`로 간다. `socket.send(type, data)`는 이 연결에, `socket.broadcast(type, data, target?)`는 허브로 보낸다. 모르는 type은 `UNKNOWN_TYPE`, 잘못된 메시지는 `INVALID_MESSAGE`, 핸들러 오류는 오류의 `code`(대문자 형식일 때) 또는 `HANDLER_FAILED`로 `{ type: 'error', id?, code }` 응답한다. 오류 메시지·stack은 보내지 않고, 게이트웨이가 서버 로그에 error `WebSocket handler failed.`(code `SOCKET_HANDLER_FAILED`, 오류 전문)로 남긴다(세션의 `reportError`, D-0047). `reply`·`error`는 예약 type이다.
93
93
  - 2026-10-14 수정([ISSUE-0005](../../docs/issues/ISSUE-0005-playground-findings.md) PG-14): WebSocket 라우트가 없는 경로로 온 업그레이드 요청이 404 뒤에도 원시 소켓을 열어 둬 앱 종료가 정리 시한까지 멈췄다. @fastify/websocket을 캡슐화 없이 등록해 그 훅이 모든 업그레이드에 적용되게 했다.
94
+
95
+ ## 서버 코드의 조회·전송 (0.3.0, [D-0061](../../docs/decisions/D-0061-realtime-namespaces.md))
96
+
97
+ 연결 밖의 서버 코드가 tenant를 지정해 접속자를 읽고 보낼 수 있다. 허브의 `list`·`broadcast`·`kick`을 감싼 것이다(@dokebi/app의 `app.realtime(namespace)`가 이것을 쓴다).
98
+
99
+ - `list({ tenant | tenantPrefix, room?, member? })`: `tenant`면 허브에 묻고, `tenantPrefix`면 이 서버가 받은 presence(모든 서버)에서 읽는다(허브에는 tenant를 넘는 조회가 없다).
100
+ - `send(filter, type, data?)`: defineSocket 방송과 같은 `{ type, data }` 텍스트 프레임. `broadcast(filter, bytes | text)`: 원시 바이트. 둘 다 많아야 한 번이고, 봉인 소켓에는 소켓마다 봉인되어 간다. `tenantPrefix`는 아는 tenant마다 허브 방송 하나를 보낸다. 영수증 `{ ids, recipients }`.
101
+ - `kick(filter, code?, reason?)`, `onPresence(listener)`(모든 tenant의 입·퇴장, 실패는 error `PRESENCE_LISTENER_FAILED`).
102
+ - 인증 결과의 `namespace` 필드는 @dokebi/app 몫이라 허브 등록 때 뺀다.
103
+ - 자세한 규칙은 [AI.md](AI.md) §3a.
104
+
105
+ ## 호스트별 봉인 (0.3.0, [D-0059](../../docs/decisions/D-0059-seal-and-websocket-client.md) §4)
106
+
107
+ 연결마다 모든 프레임을 봉인할 수 있다. 이 패키지는 알고리즘을 모르고, 이름 `dokebi-seal`로 찾는 코덱 제공자(@dokebi/seal 플러그인)가 연결별로 프레임을 바꾼다. 이 공개 패키지는 @dokebi/seal을 import하지 않는다(`optionalDependency({ name: 'dokebi-seal' })`로 구조적 계약 `SocketCodecProvider`만 찾는다).
108
+
109
+ ```ts
110
+ context.get(ws).route({
111
+ path: '/ws',
112
+ seal: (request) => request.headers.host === 'secure.example.com', // 또는 true. @dokebi/app은 domains.<host>.seal로 채운다
113
+ authenticate, message,
114
+ });
115
+ ```
116
+
117
+ - 봉인 라우트가 있는데 `dokebi-seal` 플러그인이 없으면 setup이 `SEAL_PROVIDER_MISSING`으로 실패한다.
118
+ - 봉인 연결: 클라이언트가 서브프로토콜 `dokebi.seal`을 제안해야 한다(없으면 4415 `Seal required`). 서버는 봉인된 `{"$dokebi":"hello-v1"}`을 먼저 보내고, 들어오는 프레임을 연결의 순서 사슬 안에서 연 뒤 제어 프레임·라우트로 넘긴다. 열리지 않는 프레임(평문·바이너리·drift·재전송)은 4400 `Bad frame`이며 이유는 서버 warn 로그에만 남는다. 응답·presence·방송은 봉인되어 나가고, 방송은 평문 소켓이 버퍼 하나를 나눠 쓰는 그대로이며 봉인 소켓만 수신자마다 봉인한다. 바이너리는 보내지 않는다(`SEAL_BINARY_UNSUPPORTED`).
119
+ - 협상: 봉인 다리가 있는 클라이언트는 `dokebi.seal`과 `dokebi.plain`(`PLAIN_PROTOCOL`)을 함께 제안한다. 봉인 연결은 `dokebi.seal`만 고르고(plain은 고르지 않음), 평문 연결은 `dokebi.plain`이 제안됐으면 그것을, 아니면 아무것도 고르지 않는다(옛 클라이언트 그대로). 그래서 다리를 준 페이지도 평문 호스트에서는 평문으로 돈다.
120
+ - `sealDriftMs`(기본 60000): 프레임 시각 허용 차이. 재전송 nonce는 `hub.nonces()`(cluster면 Redis 공유)에 두 배 동안 남는다.
121
+ - 자세한 규칙·로그·비용은 [AI.md](AI.md) §4a.
package/dist/gateway.d.ts CHANGED
@@ -2,15 +2,16 @@ import type { PluginContext } from '@dokebi/core';
2
2
  import type { WebApi } from '@dokebi/web';
3
3
  import type { HubApi } from '@dokebi/websocket-hub';
4
4
  import type { Options } from './options.js';
5
- import type { WebsocketApi } from './types.js';
5
+ import { type SocketCodecProvider, type WebsocketApi } from './types.js';
6
6
  export declare class Gateway {
7
7
  #private;
8
8
  readonly context: PluginContext;
9
9
  readonly web: WebApi;
10
10
  readonly hub: HubApi;
11
11
  readonly settings: Options;
12
+ readonly codecs: SocketCodecProvider | undefined;
12
13
  readonly api: WebsocketApi;
13
- constructor(context: PluginContext, web: WebApi, hub: HubApi, settings: Options);
14
+ constructor(context: PluginContext, web: WebApi, hub: HubApi, settings: Options, codecs?: SocketCodecProvider | undefined);
14
15
  start(): void;
15
16
  /** Stops waiting as soon as `signal` (the core drain deadline) aborts; sockets are then cut. */
16
17
  drain(signal: AbortSignal): Promise<void>;
package/dist/gateway.js CHANGED
@@ -4,8 +4,64 @@ import { setTimeout as delay, setImmediate as immediate } from 'node:timers/prom
4
4
  import fastifyWebsocket from '@fastify/websocket';
5
5
  import { WebSocket } from 'ws';
6
6
  import { errorCode, errorText, LogThrottle } from './log.js';
7
+ import { PLAIN_PROTOCOL, SEAL_PROTOCOL, } from './types.js';
7
8
  const TEXT = Object.freeze({ binary: false });
8
9
  const BINARY = Object.freeze({ binary: true });
10
+ /** Close codes of sealed connections (D-0059 §4); the client does not reconnect after them. */
11
+ const BAD_FRAME = 4400;
12
+ const SEAL_REQUIRED = 4415;
13
+ /** Why a sealed frame was refused, as a bounded log group (codec reasons look like `replay`). */
14
+ const REASON = /^[a-z][a-z-]{0,31}$/;
15
+ /** Message types of `api.send`, as defineSocket handler types. */
16
+ const TYPE = /^[A-Za-z][A-Za-z0-9._:-]{0,63}$/;
17
+ /** Hub calls a `tenantPrefix` broadcast or kick runs at once. */
18
+ const FAN_OUT = 16;
19
+ const encoder = new TextEncoder();
20
+ function coded(message, code) {
21
+ return Object.assign(new Error(message), { code });
22
+ }
23
+ /** A host without its port, lower case; IPv6 literals keep their brackets (like the browser). */
24
+ function withoutPort(host) {
25
+ const raw = host.toLowerCase();
26
+ if (raw.startsWith('['))
27
+ return raw.slice(0, raw.indexOf(']') + 1);
28
+ const colon = raw.lastIndexOf(':');
29
+ return colon === -1 ? raw : raw.slice(0, colon);
30
+ }
31
+ /** A filter string: 1 to 256 bytes (the hub's identifier limit). */
32
+ function filterText(value) {
33
+ return typeof value === 'string' && value.length > 0 && Buffer.byteLength(value) <= 256;
34
+ }
35
+ /** Checks a server-side filter (D-0061): exactly one of tenant and tenantPrefix. */
36
+ function checkFilter(filter) {
37
+ const value = filter;
38
+ if (!value ||
39
+ typeof value !== 'object' ||
40
+ (value.tenant === undefined) === (value.tenantPrefix === undefined) ||
41
+ (value.tenant !== undefined && !filterText(value.tenant)) ||
42
+ (value.tenantPrefix !== undefined && !filterText(value.tenantPrefix)) ||
43
+ (value.room !== undefined && !filterText(value.room)) ||
44
+ (value.member !== undefined && !filterText(value.member)))
45
+ throw coded('A websocket filter is { tenant } or { tenantPrefix }, with room? and member?, strings of 1 to 256 bytes', 'INVALID_FILTER');
46
+ return value;
47
+ }
48
+ function connectionInfo(record) {
49
+ return Object.freeze({
50
+ tenant: record.tenant,
51
+ member: record.member,
52
+ connection: record.connection,
53
+ ownerEpoch: record.ownerEpoch,
54
+ ...(record.clientId === undefined ? {} : { clientId: record.clientId }),
55
+ rooms: record.rooms,
56
+ metadata: record.metadata,
57
+ });
58
+ }
59
+ function sealOf(route) {
60
+ const value = route.seal;
61
+ if (value !== undefined && typeof value !== 'boolean' && typeof value !== 'function')
62
+ throw new Error('Invalid websocket route');
63
+ return value;
64
+ }
9
65
  /** Allow-list entries must be exact http(s) origins such as `https://app.example.com`. */
10
66
  function parseOrigins(value) {
11
67
  if (value === undefined)
@@ -71,6 +127,7 @@ export class Gateway {
71
127
  web;
72
128
  hub;
73
129
  settings;
130
+ codecs;
74
131
  api;
75
132
  #routes = [];
76
133
  #clients = new Map();
@@ -81,23 +138,29 @@ export class Gateway {
81
138
  #sends = 0;
82
139
  #sendsIdle;
83
140
  #identities = new WeakMap();
141
+ /** `api.onPresence` listeners (D-0061). */
142
+ #listeners = new Set();
143
+ /** Upgrades decided as sealed in preValidation, read by handleProtocols and the wsHandler. */
144
+ #sealed = new WeakSet();
84
145
  #frozen = false;
85
146
  #closing = false;
86
147
  #loop;
87
148
  #timer;
88
149
  /** Failures on per-message and per-socket paths, logged once per interval with a count. */
89
150
  #throttle;
90
- constructor(context, web, hub, settings) {
151
+ constructor(context, web, hub, settings, codecs = undefined) {
91
152
  this.context = context;
92
153
  this.web = web;
93
154
  this.hub = hub;
94
155
  this.settings = settings;
156
+ this.codecs = codecs;
95
157
  const self = this;
96
158
  this.#throttle = new LogThrottle(context.logger);
97
159
  this.api = Object.freeze({
98
160
  get connections() {
99
161
  return self.#clients.size;
100
162
  },
163
+ sealing: codecs !== undefined,
101
164
  route: (route) => {
102
165
  if (this.#frozen || context.app.state !== 'starting')
103
166
  throw new Error('Register websocket routes during setup');
@@ -106,8 +169,43 @@ export class Gateway {
106
169
  typeof route.message !== 'function')
107
170
  throw new Error('Invalid websocket route');
108
171
  const origins = parseOrigins(route.origins);
172
+ const seal = sealOf(route);
173
+ // Fail closed: a route that may seal must not quietly run in plain text.
174
+ if (seal && !codecs)
175
+ throw coded(`WebSocket route ${route.path} is sealed; register the dokebi-seal plugin`, 'SEAL_PROVIDER_MISSING');
109
176
  this.#routes.push({ route: { ...route }, origins });
110
177
  },
178
+ list: (filter) => this.#list(filter),
179
+ broadcast: (filter, data) => this.#broadcast(filter, data),
180
+ send: (filter, type, data) => {
181
+ if (typeof type !== 'string' || !TYPE.test(type))
182
+ return Promise.reject(coded('Message types match ' + TYPE.source, 'INVALID_TYPE'));
183
+ let text;
184
+ try {
185
+ text = JSON.stringify(data === undefined ? { type } : { type, data });
186
+ }
187
+ catch (error) {
188
+ return Promise.reject(Object.assign(new Error('Message data is not JSON', { cause: error }), {
189
+ code: 'INVALID_DATA',
190
+ }));
191
+ }
192
+ return this.#broadcast(filter, text);
193
+ },
194
+ kick: (filter, code, reason) => this.#kick(filter, code, reason),
195
+ onPresence: (listener) => {
196
+ if (typeof listener !== 'function')
197
+ throw new TypeError('Invalid presence listener');
198
+ this.#listeners.add(listener);
199
+ context.logger.log('debug', 'WebSocket presence listener added', {
200
+ listeners: this.#listeners.size,
201
+ });
202
+ return () => {
203
+ if (this.#listeners.delete(listener))
204
+ context.logger.log('debug', 'WebSocket presence listener removed', {
205
+ listeners: this.#listeners.size,
206
+ });
207
+ };
208
+ },
111
209
  });
112
210
  // Registered without encapsulation (skip-override) so @fastify/websocket's hooks run for
113
211
  // every upgrade, including ones that match no websocket route: its onResponse hook then
@@ -115,7 +213,19 @@ export class Gateway {
115
213
  const gateway = async (scope) => {
116
214
  this.#frozen = true;
117
215
  await scope.register(fastifyWebsocket, {
118
- options: { maxPayload: settings.maxPayload, perMessageDeflate: false },
216
+ options: {
217
+ maxPayload: settings.maxPayload,
218
+ perMessageDeflate: false,
219
+ // D-0059 §4: a client with a seal bridge offers `dokebi.seal` and `dokebi.plain`.
220
+ // A sealed upgrade selects `dokebi.seal` only (never plain; not offered: 4415 after the
221
+ // upgrade). A plain upgrade selects `dokebi.plain` when offered (browsers fail a handshake
222
+ // that selects none of the offered protocols), otherwise nothing, as for old clients.
223
+ handleProtocols: (protocols, request) => {
224
+ if (this.#sealed.has(request))
225
+ return protocols.has(SEAL_PROTOCOL) ? SEAL_PROTOCOL : false;
226
+ return protocols.has(PLAIN_PROTOCOL) ? PLAIN_PROTOCOL : false;
227
+ },
228
+ },
119
229
  // A wsHandler that threw: the client gets 1011, the cause goes to the log (D-0047).
120
230
  errorHandler: (error, socket) => {
121
231
  this.#throttle.report('error', 'WebSocket handler failed', 'SOCKET_FAILURE', error);
@@ -150,6 +260,20 @@ export class Gateway {
150
260
  if (!identity)
151
261
  return reply.code(401).send({ error: 'UNAUTHORIZED' });
152
262
  this.#identities.set(request, identity);
263
+ const seal = route.seal;
264
+ if (seal === undefined || seal === false)
265
+ return;
266
+ const sealed = seal === true || seal(request) === true;
267
+ if (sealed)
268
+ this.#sealed.add(request.raw);
269
+ if (this.context.logger.isEnabled('debug'))
270
+ this.context.logger.log('debug', 'WebSocket seal decision', {
271
+ path: route.path,
272
+ sealed,
273
+ offered: String(request.headers['sec-websocket-protocol'] ?? '')
274
+ .split(',')
275
+ .some((value) => value.trim() === SEAL_PROTOCOL),
276
+ });
153
277
  },
154
278
  handler: (_request, reply) => reply.code(426).send({ error: 'WEBSOCKET_REQUIRED' }),
155
279
  wsHandler: (socket, request) => this.#attach(socket, request, route),
@@ -164,10 +288,31 @@ export class Gateway {
164
288
  void task.then(() => this.#tasks.delete(task), () => this.#tasks.delete(task));
165
289
  return task;
166
290
  }
167
- #send(socket, data) {
168
- const bytes = typeof data === 'string' ? Buffer.byteLength(data) : data.byteLength;
291
+ #send(value, data) {
292
+ const socket = value.socket;
169
293
  if (socket.readyState !== WebSocket.OPEN)
170
294
  return Promise.reject(Object.assign(new Error('Socket closed'), { code: 'SOCKET_CLOSED' }));
295
+ if (value.codec) {
296
+ // Sealed connections carry text only: UTF-8 bytes are sent as text, other bytes refused.
297
+ let text;
298
+ if (typeof data === 'string')
299
+ text = data;
300
+ else {
301
+ const buffer = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
302
+ if (!isUtf8(buffer))
303
+ return Promise.reject(coded('Binary data cannot be sent on a sealed socket', 'SEAL_BINARY_UNSUPPORTED'));
304
+ text = buffer.toString();
305
+ }
306
+ try {
307
+ data = value.codec.encode(text);
308
+ }
309
+ catch (error) {
310
+ return Promise.reject(Object.assign(new Error('Sealing a frame failed', { cause: error }), {
311
+ code: 'SEAL_ENCODE_FAILED',
312
+ }));
313
+ }
314
+ }
315
+ const bytes = typeof data === 'string' ? Buffer.byteLength(data) : data.byteLength;
171
316
  if (socket.bufferedAmount + bytes > this.settings.maxBufferedBytes) {
172
317
  this.#slow(socket);
173
318
  return Promise.reject(Object.assign(new Error('Socket backpressure'), { code: 'SLOW_CONSUMER' }));
@@ -188,7 +333,8 @@ export class Gateway {
188
333
  #deliver(socket, frame, kind) {
189
334
  if (socket.readyState !== WebSocket.OPEN)
190
335
  return;
191
- if (socket.bufferedAmount + frame.byteLength > this.settings.maxBufferedBytes) {
336
+ const bytes = typeof frame === 'string' ? Buffer.byteLength(frame) : frame.byteLength;
337
+ if (socket.bufferedAmount + bytes > this.settings.maxBufferedBytes) {
192
338
  this.#slow(socket);
193
339
  return;
194
340
  }
@@ -233,14 +379,52 @@ export class Gateway {
233
379
  return;
234
380
  }
235
381
  }
382
+ const sealed = this.#sealed.has(request.raw);
383
+ // A sealed host never talks plain text: a client that cannot seal is told so (no reconnect).
384
+ if (sealed && socket.protocol !== SEAL_PROTOCOL) {
385
+ this.context.logger.log('debug', 'WebSocket seal required; closed', {
386
+ path: route.path,
387
+ code: 'SEAL_REQUIRED',
388
+ });
389
+ socket.close(SEAL_REQUIRED, 'Seal required');
390
+ return;
391
+ }
236
392
  const identity = this.#identities.get(request);
237
393
  if (!identity || this.#closing || this.#clients.size >= this.settings.maxConnections) {
238
394
  socket.close(1013, 'Unavailable');
239
395
  return;
240
396
  }
241
397
  const id = randomUUID();
398
+ let codec;
399
+ if (sealed) {
400
+ let hello;
401
+ try {
402
+ codec = this.codecs.forConnection({
403
+ host: withoutPort(this.web.requestHost(request)),
404
+ path: request.url.split('?', 1)[0] ?? route.path,
405
+ userAgent: String(request.headers['user-agent'] ?? ''),
406
+ nonces: this.hub.nonces(),
407
+ driftMs: this.settings.sealDriftMs,
408
+ });
409
+ hello = codec.hello();
410
+ }
411
+ catch (error) {
412
+ this.#throttle.report('error', 'WebSocket seal codec failed; closed', 'SEAL_CODEC_FAILED', error, { connection: id });
413
+ socket.close(1011, 'Socket failure');
414
+ return;
415
+ }
416
+ // The first frame of a sealed connection: the client takes its clock offset from it and
417
+ // reports 'open' only after it (D-0059 §4).
418
+ socket.send(hello, TEXT, (error) => {
419
+ if (error)
420
+ this.#throttle.report('warn', 'WebSocket seal hello not sent', 'SEAL_HELLO_FAILED', error, { connection: id });
421
+ });
422
+ if (this.context.logger.isEnabled('debug'))
423
+ this.context.logger.log('debug', 'WebSocket seal hello sent', { connection: id });
424
+ }
242
425
  const value = {
243
426
  socket,
427
+ codec,
244
428
  route,
245
429
  session: undefined,
246
430
  tail: Promise.resolve(),
@@ -259,6 +443,7 @@ export class Gateway {
259
443
  member: identity.member,
260
444
  clientId: identity.clientId ?? null,
261
445
  path: route.path,
446
+ sealed: codec !== undefined,
262
447
  remote: `${request.socket.remoteAddress ?? '?'}:${request.socket.remotePort ?? '?'}`,
263
448
  userAgent: String(request.headers['user-agent'] ?? '').slice(0, 160),
264
449
  // Browser context of the upgrade: a prerendered or prefetched page says so here.
@@ -269,7 +454,7 @@ export class Gateway {
269
454
  const session = Object.freeze({
270
455
  id,
271
456
  identity,
272
- send: (data) => this.#send(socket, data),
457
+ send: (data) => this.#send(value, data),
273
458
  broadcast: async (data, target) => {
274
459
  return this.hub.broadcast({ ...target, tenant: identity.tenant }, data);
275
460
  },
@@ -310,7 +495,9 @@ export class Gateway {
310
495
  },
311
496
  });
312
497
  value.session = session;
313
- const registration = { ...identity, connection: id };
498
+ // `namespace` belongs to @dokebi/app (D-0061); the hub registers known fields only.
499
+ const { namespace: _namespace, ...fields } = identity;
500
+ const registration = { ...fields, connection: id };
314
501
  value.tail = this.#watch(this.hub.register(registration).then((handle) => {
315
502
  value.registration = handle;
316
503
  if (this.context.logger.isEnabled('debug'))
@@ -343,74 +530,47 @@ export class Gateway {
343
530
  });
344
531
  });
345
532
  // Attach synchronously, before awaiting Redis/TCP registration, so early frames are queued.
346
- socket.on('message', (raw) => {
533
+ socket.on('message', (raw, isBinary) => {
347
534
  value.seen = performance.now();
348
- // Control frames are answered here, outside the route's message queue.
349
535
  const bytes = Array.isArray(raw)
350
536
  ? Buffer.concat(raw)
351
537
  : Buffer.from(raw instanceof ArrayBuffer ? new Uint8Array(raw) : raw);
352
- if (bytes[0] === 123) {
353
- let control;
354
- try {
355
- control = JSON.parse(bytes.toString());
356
- }
357
- catch {
358
- /* The route owns non-control payload parsing. */
359
- }
360
- // The page is alive (idleTimeoutMs): nothing else to do.
361
- if (control?.$dokebi === 'ping-v1')
538
+ if (codec) {
539
+ // Sealed: the frame is opened in this connection's order chain, then handled like a
540
+ // plain one (control frames, then the route). Nothing is read before it opens.
541
+ if (this.#closing)
362
542
  return;
363
- // A page loaded before D-0057 still acknowledges broadcasts: nothing to do, and no
364
- // reason to close it. Counted at debug until it reloads.
365
- if (control?.$dokebi === 'ack-v1') {
366
- this.#throttle.report('debug', 'WebSocket ACK from an old client ignored', 'ACK_IGNORED', undefined, { connection: id });
367
- return;
368
- }
369
- }
370
- if (this.#closing)
371
- return;
372
- if (++value.pending > this.settings.maxPendingMessages) {
373
- value.pending--;
374
- // The server closing a client is worth seeing (like SLOW_CONSUMER): usually a handler
375
- // that waits long (a slow database call) while the client keeps sending.
376
- this.#throttle.report('warn', 'WebSocket message queue full; closed', 'TOO_MANY_MESSAGES', undefined, {
377
- connection: id,
378
- pending: value.pending,
543
+ this.#enqueue(value, id, async () => {
544
+ if (value.failed)
545
+ return; // refused earlier (4400) or not registered: take nothing
546
+ let text;
547
+ try {
548
+ if (isBinary)
549
+ throw Object.assign(new Error('Binary frame'), { reason: 'binary' });
550
+ text = await codec.decode(bytes.toString());
551
+ }
552
+ catch (error) {
553
+ this.#refuse(value, id, error);
554
+ return;
555
+ }
556
+ if (text.charCodeAt(0) === 123 && this.#control(text, id))
557
+ return;
558
+ if (value.failed || !value.registration)
559
+ return;
560
+ return route.message(Buffer.from(text), session);
379
561
  });
380
- socket.close(1013, 'Too many messages');
381
562
  return;
382
563
  }
383
- const data = Array.isArray(raw)
384
- ? Buffer.concat(raw)
385
- : raw instanceof ArrayBuffer
386
- ? Buffer.from(raw)
387
- : Buffer.from(raw);
388
- const work = value.tail.then(() => {
564
+ // Control frames are answered here, outside the route's message queue.
565
+ if (bytes[0] === 123 && this.#control(bytes.toString(), id))
566
+ return;
567
+ if (this.#closing)
568
+ return;
569
+ this.#enqueue(value, id, () => {
389
570
  if (value.failed || !value.registration)
390
571
  return;
391
- return route.message(data, session);
572
+ return route.message(bytes, session);
392
573
  });
393
- value.tail = work
394
- .then(() => { }, (error) => {
395
- value.failed = true;
396
- // A reply that cannot be written because the socket is closing is not a handler
397
- // failure. A slow consumer was logged where it was closed; a client that left is
398
- // counted here as warn, once per interval: the client is gone, nothing on this
399
- // server failed (OPS-002 soak: thousands of these hid the real cause at error).
400
- const code = error?.code;
401
- if (code === 'SLOW_CONSUMER')
402
- return;
403
- if (code === 'SOCKET_CLOSED') {
404
- this.#throttle.report('warn', 'WebSocket reply dropped; socket closed', 'REPLY_DROPPED', error, { connection: id });
405
- return;
406
- }
407
- this.#throttle.report('error', 'WebSocket message handler failed', errorCode(error, 'HANDLER_FAILED'), error, { connection: id });
408
- socket.close(1011, 'Message failed');
409
- })
410
- .finally(() => {
411
- value.pending--;
412
- });
413
- this.#watch(value.tail);
414
574
  });
415
575
  socket.once('close', (code, reason) => {
416
576
  this.context.logger.log('debug', 'WebSocket closed', {
@@ -434,6 +594,78 @@ export class Gateway {
434
594
  });
435
595
  });
436
596
  }
597
+ /**
598
+ * Answers a `$dokebi` control frame (ping-v1, ack-v1); false when `text` is not one, so the
599
+ * route gets it.
600
+ */
601
+ #control(text, id) {
602
+ let control;
603
+ try {
604
+ control = JSON.parse(text);
605
+ }
606
+ catch {
607
+ /* The route owns non-control payload parsing. */
608
+ }
609
+ // The page is alive (idleTimeoutMs): nothing else to do.
610
+ if (control?.$dokebi === 'ping-v1')
611
+ return true;
612
+ // A page loaded before D-0057 still acknowledges broadcasts: nothing to do, and no
613
+ // reason to close it. Counted at debug until it reloads.
614
+ if (control?.$dokebi === 'ack-v1') {
615
+ this.#throttle.report('debug', 'WebSocket ACK from an old client ignored', 'ACK_IGNORED', undefined, { connection: id });
616
+ return true;
617
+ }
618
+ return false;
619
+ }
620
+ /**
621
+ * A sealed frame that did not open (plain text, binary, drift, replay, bad seal): 4400 and the
622
+ * connection takes nothing more. The reason goes to the log only, never to the client: telling
623
+ * `replay` from `drift` would let an attacker probe the defence (D-0059 §4).
624
+ */
625
+ #refuse(value, id, error) {
626
+ const given = error?.reason;
627
+ const reason = typeof given === 'string' && REASON.test(given) ? given : 'unknown';
628
+ value.failed = true;
629
+ this.#throttle.report('warn', 'WebSocket sealed frame refused; closed', 'SEAL_FRAME_REFUSED', error, { connection: id, reason }, reason);
630
+ value.socket.close(BAD_FRAME, 'Bad frame');
631
+ }
632
+ /** Runs `work` after this connection's earlier messages and presence calls, in order. */
633
+ #enqueue(value, id, work) {
634
+ const socket = value.socket;
635
+ if (++value.pending > this.settings.maxPendingMessages) {
636
+ value.pending--;
637
+ // The server closing a client is worth seeing (like SLOW_CONSUMER): usually a handler
638
+ // that waits long (a slow database call) while the client keeps sending.
639
+ this.#throttle.report('warn', 'WebSocket message queue full; closed', 'TOO_MANY_MESSAGES', undefined, {
640
+ connection: id,
641
+ pending: value.pending,
642
+ });
643
+ socket.close(1013, 'Too many messages');
644
+ return;
645
+ }
646
+ value.tail = value.tail
647
+ .then(work)
648
+ .then(() => { }, (error) => {
649
+ value.failed = true;
650
+ // A reply that cannot be written because the socket is closing is not a handler
651
+ // failure. A slow consumer was logged where it was closed; a client that left is
652
+ // counted here as warn, once per interval: the client is gone, nothing on this
653
+ // server failed (OPS-002 soak: thousands of these hid the real cause at error).
654
+ const code = error?.code;
655
+ if (code === 'SLOW_CONSUMER')
656
+ return;
657
+ if (code === 'SOCKET_CLOSED') {
658
+ this.#throttle.report('warn', 'WebSocket reply dropped; socket closed', 'REPLY_DROPPED', error, { connection: id });
659
+ return;
660
+ }
661
+ this.#throttle.report('error', 'WebSocket message handler failed', errorCode(error, 'HANDLER_FAILED'), error, { connection: id });
662
+ socket.close(1011, 'Message failed');
663
+ })
664
+ .finally(() => {
665
+ value.pending--;
666
+ });
667
+ this.#watch(value.tail);
668
+ }
437
669
  /** Turns one server's new connection list into joins and leaves per tenant, for local routes. */
438
670
  #presence(owner, connections) {
439
671
  const before = this.#owners.get(owner) ?? [];
@@ -475,8 +707,11 @@ export class Gateway {
475
707
  tenants: changes.size,
476
708
  joined,
477
709
  left,
710
+ listeners: this.#listeners.size,
478
711
  });
479
712
  }
713
+ if (this.#listeners.size)
714
+ this.#notify(changes);
480
715
  for (const value of this.#clients.values()) {
481
716
  const { route, session } = value;
482
717
  const change = session && changes.get(session.identity.tenant);
@@ -507,6 +742,144 @@ export class Gateway {
507
742
  this.#watch(value.tail);
508
743
  }
509
744
  }
745
+ /** Records of the presence mirror (every server, as the hub reported them) that match. */
746
+ #mirror(filter) {
747
+ const result = [];
748
+ for (const records of this.#owners.values())
749
+ for (const record of records)
750
+ if ((filter.tenant === undefined
751
+ ? record.tenant.startsWith(filter.tenantPrefix)
752
+ : record.tenant === filter.tenant) &&
753
+ (filter.room === undefined || record.rooms.includes(filter.room)) &&
754
+ (filter.member === undefined || record.member === filter.member))
755
+ result.push(record);
756
+ return result;
757
+ }
758
+ /** One hub query per tenant the filter names: its own, or each known one under the prefix. */
759
+ #queries(filter) {
760
+ const narrow = {
761
+ ...(filter.room === undefined ? {} : { room: filter.room }),
762
+ ...(filter.member === undefined ? {} : { member: filter.member }),
763
+ };
764
+ if (filter.tenant !== undefined)
765
+ return [{ tenant: filter.tenant, ...narrow }];
766
+ const tenants = new Set(this.#mirror(filter).map((record) => record.tenant));
767
+ return [...tenants].map((tenant) => ({ tenant, ...narrow }));
768
+ }
769
+ /** Runs `call` for every query, FAN_OUT at a time; the results and failures in query order. */
770
+ async #fanOut(queries, call) {
771
+ const results = [];
772
+ const failures = [];
773
+ for (let index = 0; index < queries.length; index += FAN_OUT) {
774
+ const settled = await Promise.allSettled(queries.slice(index, index + FAN_OUT).map((query) => call(query)));
775
+ for (const outcome of settled)
776
+ if (outcome.status === 'fulfilled')
777
+ results.push(outcome.value);
778
+ else
779
+ failures.push(outcome.reason);
780
+ }
781
+ return { results, failures };
782
+ }
783
+ async #list(input) {
784
+ const filter = checkFilter(input);
785
+ const started = performance.now();
786
+ let records;
787
+ if (filter.tenant !== undefined) {
788
+ const [query] = this.#queries(filter);
789
+ records = (await this.hub.list(query)).connections;
790
+ }
791
+ else
792
+ records = this.#mirror(filter);
793
+ if (this.context.logger.isEnabled('debug'))
794
+ this.context.logger.log('debug', 'WebSocket connections listed', {
795
+ source: filter.tenant === undefined ? 'presence' : 'hub',
796
+ tenant: filter.tenant?.slice(0, 64) ?? null,
797
+ tenantPrefix: filter.tenantPrefix?.slice(0, 64) ?? null,
798
+ connections: records.length,
799
+ ms: Math.round((performance.now() - started) * 1000) / 1000,
800
+ });
801
+ return Object.freeze(records.map(connectionInfo));
802
+ }
803
+ async #broadcast(input, data) {
804
+ const filter = checkFilter(input);
805
+ if (typeof data !== 'string' && !(data instanceof Uint8Array))
806
+ throw coded('Broadcast data is a string or a Uint8Array', 'INVALID_DATA');
807
+ const bytes = typeof data === 'string' ? encoder.encode(data) : data;
808
+ const queries = this.#queries(filter);
809
+ // A single tenant keeps the hub's own error (RECOVERING, BUSY, OUTCOME_UNKNOWN).
810
+ if (filter.tenant !== undefined) {
811
+ const receipt = await this.hub.broadcast(queries[0], bytes);
812
+ if (this.context.logger.isEnabled('debug'))
813
+ this.context.logger.log('debug', 'WebSocket server broadcast sent', {
814
+ id: receipt.id,
815
+ tenants: 1,
816
+ recipients: receipt.recipients.length,
817
+ bytes: bytes.byteLength,
818
+ });
819
+ return Object.freeze({ ids: Object.freeze([receipt.id]), recipients: receipt.recipients });
820
+ }
821
+ const { results, failures } = await this.#fanOut(queries, (query) => this.hub.broadcast(query, bytes));
822
+ const receipt = Object.freeze({
823
+ ids: Object.freeze(results.map((result) => result.id)),
824
+ recipients: Object.freeze(results.flatMap((result) => result.recipients)),
825
+ });
826
+ if (this.context.logger.isEnabled('debug'))
827
+ this.context.logger.log('debug', 'WebSocket server broadcast sent', {
828
+ tenantPrefix: filter.tenantPrefix?.slice(0, 64) ?? null,
829
+ tenants: queries.length,
830
+ failed: failures.length,
831
+ recipients: receipt.recipients.length,
832
+ bytes: bytes.byteLength,
833
+ });
834
+ if (failures.length)
835
+ throw Object.assign(new Error(`WebSocket broadcast failed for ${failures.length} of ${queries.length} tenants`, {
836
+ cause: new AggregateError(failures, 'Hub broadcast failures'),
837
+ }), { code: errorCode(failures[0], 'BROADCAST_FAILED'), receipt });
838
+ return receipt;
839
+ }
840
+ async #kick(input, code, reason) {
841
+ const filter = checkFilter(input);
842
+ const queries = this.#queries(filter);
843
+ const { results, failures } = await this.#fanOut(queries, (query) => this.hub.kick(query, code, reason));
844
+ const receipt = Object.freeze({
845
+ ids: Object.freeze(results.map((result) => result.id)),
846
+ });
847
+ this.context.logger.log('debug', 'WebSocket server kick sent', {
848
+ tenant: filter.tenant?.slice(0, 64) ?? null,
849
+ tenantPrefix: filter.tenantPrefix?.slice(0, 64) ?? null,
850
+ tenants: queries.length,
851
+ failed: failures.length,
852
+ code: code ?? null,
853
+ });
854
+ if (failures.length === 1 && queries.length === 1)
855
+ throw failures[0];
856
+ if (failures.length)
857
+ throw Object.assign(new Error(`WebSocket kick failed for ${failures.length} of ${queries.length} tenants`, {
858
+ cause: new AggregateError(failures, 'Hub kick failures'),
859
+ }), { code: errorCode(failures[0], 'KICK_FAILED'), receipt });
860
+ return receipt;
861
+ }
862
+ /** Hands each tenant's change to the `api.onPresence` listeners; their failures are logged. */
863
+ #notify(changes) {
864
+ for (const [tenant, change] of changes) {
865
+ const presence = Object.freeze({
866
+ tenant,
867
+ joined: Object.freeze([...change.joined]),
868
+ left: Object.freeze([...change.left]),
869
+ });
870
+ for (const listener of this.#listeners) {
871
+ const failed = (error) => this.#throttle.report('error', 'WebSocket presence listener failed', 'PRESENCE_LISTENER_FAILED', error);
872
+ try {
873
+ const result = listener(presence);
874
+ if (result && typeof result.then === 'function')
875
+ result.then(undefined, failed);
876
+ }
877
+ catch (error) {
878
+ failed(error);
879
+ }
880
+ }
881
+ }
882
+ }
510
883
  start() {
511
884
  const events = this.hub.events();
512
885
  this.#loop = (async () => {
@@ -527,22 +900,49 @@ export class Gateway {
527
900
  }
528
901
  // The broadcast bytes as they are (D-0057): a text frame when they are UTF-8 (the
529
902
  // `{ type, data }` JSON of defineSocket), a binary frame otherwise. One buffer shared
530
- // by every recipient; ws keeps per-socket order in its queue.
903
+ // by every plain recipient; ws keeps per-socket order in its queue. Sealed sockets get
904
+ // their own sealed copy of the text (each key and nonce is per connection and frame).
531
905
  const frame = Buffer.from(event.data.buffer, event.data.byteOffset, event.data.byteLength);
532
906
  const kind = isUtf8(frame) ? TEXT : BINARY;
533
907
  let local = 0;
908
+ let sealed = 0;
909
+ let dropped = 0;
910
+ let text;
534
911
  for (const id of event.connections) {
535
912
  const value = this.#clients.get(id);
536
- if (value) {
537
- local++;
913
+ if (!value)
914
+ continue;
915
+ local++;
916
+ if (!value.codec) {
538
917
  this.#deliver(value.socket, frame, kind);
918
+ continue;
919
+ }
920
+ // A sealed connection carries text only: a binary broadcast is not sent to it.
921
+ if (kind === BINARY) {
922
+ dropped++;
923
+ continue;
924
+ }
925
+ text ??= frame.toString();
926
+ let sealedFrame;
927
+ try {
928
+ sealedFrame = value.codec.encode(text);
929
+ }
930
+ catch (error) {
931
+ this.#throttle.report('error', 'WebSocket broadcast not sealed; socket closed', 'SEAL_ENCODE_FAILED', error, { connection: id });
932
+ value.socket.close(1011, 'Socket failure');
933
+ continue;
539
934
  }
935
+ sealed++;
936
+ this.#deliver(value.socket, sealedFrame, TEXT);
540
937
  }
938
+ if (dropped)
939
+ this.#throttle.report('warn', 'WebSocket binary broadcast not sent to sealed sockets', 'SEAL_BINARY_UNSUPPORTED', undefined, { id: event.id, dropped });
541
940
  if (this.context.logger.isEnabled('debug'))
542
941
  this.context.logger.log('debug', 'WebSocket broadcast delivered', {
543
942
  id: event.id,
544
943
  connections: event.connections.length,
545
944
  local,
945
+ sealed,
546
946
  binary: kind === BINARY,
547
947
  });
548
948
  // Queued events would otherwise be fanned out in one tick, before any socket can flush,
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { definePlugin, providerDependency } from '@dokebi/core';
1
+ import { definePlugin, optionalDependency, providerDependency, } from '@dokebi/core';
2
2
  import { Gateway } from './gateway.js';
3
3
  import { parseOptions } from './options.js';
4
4
  export * from './router.js';
@@ -9,9 +9,14 @@ const hub = providerDependency({
9
9
  packageName: '@dokebi/websocket-hub',
10
10
  load: () => import('@dokebi/websocket-hub'),
11
11
  });
12
+ /**
13
+ * The socket codec provider (D-0059 §4): the private dokebi-seal plugin when it is registered.
14
+ * Looked up by name only; this package never imports @dokebi/seal.
15
+ */
16
+ const seal = optionalDependency({ name: 'dokebi-seal', version: '^0.1.0' });
12
17
  const web = providerDependency({
13
18
  name: 'dokebi-web',
14
- version: '^0.1.0',
19
+ version: '^0.1.0 || ^0.2.0',
15
20
  packageName: '@dokebi/web',
16
21
  load: () => import('@dokebi/web'),
17
22
  });
@@ -22,7 +27,16 @@ class WebsocketRuntime {
22
27
  this.#options = options;
23
28
  }
24
29
  setup(context) {
25
- this.#gateway = new Gateway(context, context.getDependency(web), context.getDependency(hub), this.#options);
30
+ const codecs = context.getOptionalDependency(seal);
31
+ if (codecs !== undefined && typeof codecs?.forConnection !== 'function')
32
+ throw Object.assign(new Error('dokebi-seal does not provide forConnection'), {
33
+ code: 'SEAL_PROVIDER_INVALID',
34
+ });
35
+ context.logger.log('debug', 'WebSocket seal provider', {
36
+ present: codecs !== undefined,
37
+ sealDriftMs: this.#options.sealDriftMs,
38
+ });
39
+ this.#gateway = new Gateway(context, context.getDependency(web), context.getDependency(hub), this.#options, codecs);
26
40
  return this.#gateway.api;
27
41
  }
28
42
  start() {
@@ -35,9 +49,9 @@ class WebsocketRuntime {
35
49
  /** Factory input: `{ app, options? }`. Options default to `app.config['dokebi-websocket']`. */
36
50
  export const createPlugin = definePlugin({
37
51
  name: 'dokebi-websocket',
38
- version: '0.2.0',
52
+ version: '0.3.0',
39
53
  core: '^0.2.0',
40
54
  options: parseOptions,
41
- dependencies: () => [hub, web],
55
+ dependencies: () => [hub, web, seal],
42
56
  instance: ({ options }) => new WebsocketRuntime(options),
43
57
  });
package/dist/options.d.ts CHANGED
@@ -17,5 +17,10 @@ export interface Options {
17
17
  * restart) before it is refused with 503 HUB_RECOVERING. 0 refuses at once.
18
18
  */
19
19
  hubWaitMs: number;
20
+ /**
21
+ * How far the timestamp of a sealed frame may differ from this server's clock (D-0059 §4):
22
+ * older or newer frames are refused (4400). Replay nonces are kept twice as long.
23
+ */
24
+ sealDriftMs: number;
20
25
  }
21
26
  export declare function parseOptions(input: unknown): Options;
package/dist/options.js CHANGED
@@ -23,6 +23,7 @@ export function parseOptions(input) {
23
23
  heartbeatMs: 10000,
24
24
  idleTimeoutMs: 0,
25
25
  hubWaitMs: 5000,
26
+ sealDriftMs: 60000,
26
27
  };
27
28
  if (Object.keys(v).some((k) => !Object.hasOwn(defaults, k)))
28
29
  throw new Error('Unknown websocket option');
@@ -30,8 +31,9 @@ export function parseOptions(input) {
30
31
  for (const key of Object.keys(defaults)) {
31
32
  if (v[key] !== undefined) {
32
33
  const x = v[key];
33
- const min = key === 'idleTimeoutMs' || key === 'hubWaitMs' ? 0 : 1;
34
- if (typeof x !== 'number' || !Number.isSafeInteger(x) || x < min || x > 67108864)
34
+ const min = key === 'idleTimeoutMs' || key === 'hubWaitMs' ? 0 : key === 'sealDriftMs' ? 1000 : 1;
35
+ const max = key === 'sealDriftMs' ? 600000 : 67108864;
36
+ if (typeof x !== 'number' || !Number.isSafeInteger(x) || x < min || x > max)
35
37
  throw new Error('Invalid websocket limit');
36
38
  result[key] = x;
37
39
  }
package/dist/router.d.ts CHANGED
@@ -28,6 +28,8 @@ export interface SocketDefinition {
28
28
  readonly constraints?: WebsocketRoute['constraints'];
29
29
  /** Client code version this route accepts; others are closed with 4426 (D-0033). */
30
30
  readonly version?: string;
31
+ /** Seals this route's frames (D-0059 §4; needs the dokebi-seal plugin). See `WebsocketRoute.seal`. */
32
+ readonly seal?: WebsocketRoute['seal'];
31
33
  authenticate(request: FastifyRequest): Awaitable<WebsocketIdentity | undefined>;
32
34
  authorizeRoom?(identity: WebsocketIdentity, room: string): Awaitable<boolean>;
33
35
  /** Handlers by message type, e.g. `{ 'chat.send': (data, socket) => ... }`. */
package/dist/router.js CHANGED
@@ -42,6 +42,7 @@ export function defineSocket(definition) {
42
42
  ...(definition.origins === undefined ? {} : { origins: definition.origins }),
43
43
  ...(definition.constraints === undefined ? {} : { constraints: definition.constraints }),
44
44
  ...(definition.version === undefined ? {} : { version: definition.version }),
45
+ ...(definition.seal === undefined ? {} : { seal: definition.seal }),
45
46
  authenticate: (request) => definition.authenticate(request),
46
47
  ...(definition.authorizeRoom
47
48
  ? {
package/dist/types.d.ts CHANGED
@@ -7,6 +7,11 @@ export interface WebsocketIdentity {
7
7
  readonly clientId?: string;
8
8
  readonly rooms?: readonly string[];
9
9
  readonly metadata?: Readonly<Record<string, string>>;
10
+ /**
11
+ * Which realtime namespace of the app the connection joins (D-0061). Read and removed by
12
+ * @dokebi/app; this package never sends it to the hub.
13
+ */
14
+ readonly namespace?: string;
10
15
  }
11
16
  /** A connection of the hub as presence changes report it (any server of the cluster). */
12
17
  export interface WebsocketPeer {
@@ -84,6 +89,15 @@ export interface WebsocketRoute {
84
89
  * instead of joining with an old protocol.
85
90
  */
86
91
  readonly version?: string;
92
+ /**
93
+ * Seals every frame of the connections this decides for (D-0059 §4): `true`, or a function of
94
+ * the upgrade request (dokebi-app sets one from `domains.<host>.seal`). A sealed connection
95
+ * needs a codec provider (the dokebi-seal plugin; without it setup fails with
96
+ * SEAL_PROVIDER_MISSING), must offer the `dokebi.seal` subprotocol (otherwise 4415
97
+ * `Seal required`), gets a sealed `{"$dokebi":"hello-v1"}` first, and is closed with 4400
98
+ * `Bad frame` on a frame that does not open. Routes and handlers see plain text either way.
99
+ */
100
+ readonly seal?: boolean | ((request: FastifyRequest) => boolean);
87
101
  authenticate(request: FastifyRequest): Awaitable<WebsocketIdentity | undefined>;
88
102
  authorizeRoom?(identity: WebsocketIdentity, room: string): Awaitable<boolean>;
89
103
  message(data: Uint8Array, session: WebsocketSession): Awaitable<void>;
@@ -93,7 +107,101 @@ export interface WebsocketRoute {
93
107
  */
94
108
  presence?(change: WebsocketPresence, session: WebsocketSession): Awaitable<void>;
95
109
  }
110
+ /** A connection as the hub lists it (any server of the cluster). */
111
+ export interface WebsocketConnectionInfo extends WebsocketPeer {
112
+ readonly tenant: string;
113
+ readonly rooms: readonly string[];
114
+ }
115
+ /**
116
+ * Which connections a server-side call is about (D-0061): one tenant (`tenant`) or every tenant
117
+ * whose name starts with `tenantPrefix` (exactly one of the two), optionally narrowed to a room,
118
+ * a member, or a member in a room. Strings are 1 to 256 bytes.
119
+ */
120
+ export interface WebsocketFilter {
121
+ readonly tenant?: string;
122
+ readonly tenantPrefix?: string;
123
+ readonly room?: string;
124
+ readonly member?: string;
125
+ }
126
+ /** What a server-side broadcast resolves with: one hub broadcast per tenant it went to. */
127
+ export interface WebsocketReceipt {
128
+ /** The hub broadcast ids (one per tenant); empty when no tenant matched (nothing was sent). */
129
+ readonly ids: readonly string[];
130
+ /** The connections the hub matched when it was sent (not a confirmation, D-0057). */
131
+ readonly recipients: readonly string[];
132
+ }
133
+ /** What a server-side kick resolves with: one hub kick per tenant. */
134
+ export interface WebsocketKickReceipt {
135
+ readonly ids: readonly string[];
136
+ }
96
137
  export interface WebsocketApi {
97
138
  route(definition: WebsocketRoute): void;
98
139
  readonly connections: number;
140
+ /** True when a socket codec provider (the dokebi-seal plugin) is registered: sealed routes work. */
141
+ readonly sealing: boolean;
142
+ /**
143
+ * Connections of the cluster that match (D-0061). With `tenant`: asked from the hub (the
144
+ * leader in cluster mode; fails with the hub's code, e.g. RECOVERING). With `tenantPrefix`: read
145
+ * from the presence the hub reported to this server (every server, eventually consistent;
146
+ * empty before start), since the hub has no query across tenants.
147
+ */
148
+ list(filter: WebsocketFilter): Promise<readonly WebsocketConnectionInfo[]>;
149
+ /**
150
+ * Hands `data` through the hub to the matching connections, like `session.broadcast` but from
151
+ * server code (D-0061): at most once, text frames for UTF-8 and binary otherwise, sealed per
152
+ * sealed socket (binary is not sent to sealed sockets). `tenantPrefix` sends one hub broadcast
153
+ * per tenant this server knows from presence. Fails with the hub's code (RECOVERING, BUSY,
154
+ * OUTCOME_UNKNOWN); with `tenantPrefix` the error has `receipt` for the tenants that worked.
155
+ */
156
+ broadcast(filter: WebsocketFilter, data: string | Uint8Array): Promise<WebsocketReceipt>;
157
+ /** `broadcast` of the `{ type, data }` text frame `defineSocket` handlers send. */
158
+ send(filter: WebsocketFilter, type: string, data?: unknown): Promise<WebsocketReceipt>;
159
+ /** Closes the matching connections on every server (hub kick; code 4000-4999, default 4403). */
160
+ kick(filter: WebsocketFilter, code?: number, reason?: string): Promise<WebsocketKickReceipt>;
161
+ /**
162
+ * Calls `listener` with each tenant's joins and leaves (every server, as routes' `presence`
163
+ * gets them) until the returned function is called. A listener that throws or rejects is
164
+ * logged at error (PRESENCE_LISTENER_FAILED); the others still run.
165
+ */
166
+ onPresence(listener: (change: WebsocketPresence) => unknown): () => void;
167
+ }
168
+ /** The subprotocol a client offers when it can seal frames; a sealed connection selects it. */
169
+ export declare const SEAL_PROTOCOL = "dokebi.seal";
170
+ /**
171
+ * Offered together with `dokebi.seal` by a client that can seal; a plain connection selects it,
172
+ * so the same client runs plain there (a sealed connection never selects it).
173
+ */
174
+ export declare const PLAIN_PROTOCOL = "dokebi.plain";
175
+ /** One-time nonce store for sealed frames: the hub's `nonces()` (D-0038). */
176
+ export interface SocketNonceStore {
177
+ setIfNotExists(key: string, ttlSeconds: number): Promise<boolean>;
178
+ readonly shared: boolean;
179
+ }
180
+ /** What a codec provider is told about one sealed connection (D-0059 §4). */
181
+ export interface SocketCodecConnection {
182
+ /** The request host without port, lower case (dokebi-web `requestHost`, honours trustProxy). */
183
+ readonly host: string;
184
+ /** The upgrade request path without the query. */
185
+ readonly path: string;
186
+ readonly userAgent: string;
187
+ /** Replay nonces: Redis shared in cluster mode, this process in local mode. */
188
+ readonly nonces: SocketNonceStore;
189
+ /** Accepted clock difference of a frame (`sealDriftMs`). */
190
+ readonly driftMs: number;
191
+ }
192
+ /** Turns the frames of one connection into text and back. Its errors never reach the client. */
193
+ export interface SocketCodec {
194
+ /** Opens one incoming text frame; rejects (with a `reason` such as `drift` or `replay`) to refuse it. */
195
+ decode(frame: string): Promise<string>;
196
+ /** Seals one outgoing text message. */
197
+ encode(text: string): string;
198
+ /** The sealed `{"$dokebi":"hello-v1"}` frame sent first on the connection. */
199
+ hello(): string;
200
+ }
201
+ /**
202
+ * The shape the dokebi-seal plugin provides (looked up by name, never imported: this public
203
+ * package does not depend on @dokebi/seal).
204
+ */
205
+ export interface SocketCodecProvider {
206
+ forConnection(connection: SocketCodecConnection): SocketCodec;
99
207
  }
package/dist/types.js CHANGED
@@ -1 +1,7 @@
1
- export {};
1
+ /** The subprotocol a client offers when it can seal frames; a sealed connection selects it. */
2
+ export const SEAL_PROTOCOL = 'dokebi.seal';
3
+ /**
4
+ * Offered together with `dokebi.seal` by a client that can seal; a plain connection selects it,
5
+ * so the same client runs plain there (a sealed connection never selects it).
6
+ */
7
+ export const PLAIN_PROTOCOL = 'dokebi.plain';
@@ -52,6 +52,13 @@
52
52
  "maximum": 67108864,
53
53
  "default": 5000,
54
54
  "description": "How long an upgrade waits for a reconnecting hub (leader change, rolling restart) before 503 HUB_RECOVERING; 0 refuses at once."
55
+ },
56
+ "sealDriftMs": {
57
+ "type": "integer",
58
+ "minimum": 1000,
59
+ "maximum": 600000,
60
+ "default": 60000,
61
+ "description": "Sealed connections (route.seal, dokebi-app domains.<host>.seal): how far a frame timestamp may differ from the server clock before the frame is refused (4400). Needs the dokebi-seal plugin."
55
62
  }
56
63
  }
57
64
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dokebi/websocket",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -33,11 +33,11 @@
33
33
  },
34
34
  "peerDependencies": {
35
35
  "@dokebi/core": "^0.2.0",
36
- "@dokebi/web": "^0.1.0",
36
+ "@dokebi/web": "^0.1.0 || ^0.2.0",
37
37
  "@dokebi/websocket-hub": "^0.3.0"
38
38
  },
39
39
  "devDependencies": {
40
- "@dokebi/web": "0.1.2",
40
+ "@dokebi/web": "0.2.0",
41
41
  "@dokebi/websocket-hub": "0.3.0"
42
42
  },
43
43
  "dokebi": {
@@ -51,7 +51,12 @@
51
51
  },
52
52
  {
53
53
  "name": "dokebi-web",
54
- "version": "^0.1.0"
54
+ "version": "^0.1.0 || ^0.2.0"
55
+ },
56
+ {
57
+ "name": "dokebi-seal",
58
+ "version": "^0.1.0",
59
+ "optional": true
55
60
  }
56
61
  ],
57
62
  "optionsSchema": "options.schema.json",