iosignal 7.2.0 → 8.1.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/README.ko.md CHANGED
@@ -6,6 +6,25 @@ Node.js와 브라우저를 위한 실시간 메시징 라이브러리입니다.
6
6
  클라이언트·서버 통신, 태그 기반 발행/구독, RPC 서비스를 제공합니다.
7
7
  Node.js에서는 TCP 기반 `IOCongSocket`도 사용할 수 있습니다.
8
8
 
9
+ <p align="center">
10
+ <img src="https://raw.githubusercontent.com/remocons/iosignal/main/docs/assets/iosignal-ecosystem.png" alt="IOSignal로 연결되는 서버, CLI, Node.js, Arduino와 원격 제어 웹앱" width="720" />
11
+ </p>
12
+
13
+ ## 문서와 지원 환경
14
+
15
+ [공식 문서](https://iosignal.net/)에서 설치, 메시징 개념과 환경별 가이드를 확인할 수 있습니다.
16
+ [5분 빠른 시작](https://iosignal.net/docs/start/quickstart/)으로 전체 흐름을 익히고,
17
+ 현재 버전의 실행 예제는 아래 빠른 시작을 참고하세요.
18
+
19
+ | 환경 / 도구 | 지원 내용 | 패키지 / 예제 |
20
+ | --- | --- | --- |
21
+ | Node.js | WebSocket·TCP 서버와 클라이언트, 발행/구독, RPC | 이 저장소 · [npm](https://www.npmjs.com/package/iosignal) |
22
+ | 브라우저 | WebSocket 클라이언트, 웹앱 연동 | `iosignal/io` · [예제](https://github.com/remocons/iosignal-examples) |
23
+ | Arduino | 장치와 서버·웹앱 간 통신, 인증과 암호화 | [iosignal-arduino](https://github.com/remocons/iosignal-arduino) |
24
+ | CLI | 터미널에서 서버·클라이언트 실행과 통신 시험 | [iosignal-cli](https://github.com/remocons/iosignal-cli) |
25
+
26
+ [브라우저 통신 워크벤치](https://test.iosignal.net/)에서도 통신을 시험할 수 있습니다.
27
+
9
28
  ## 설치
10
29
 
11
30
  ```bash
@@ -88,27 +107,7 @@ process.once('SIGINT', () => io.stop());
88
107
  `signal(tag, ...args)`는 문자열, 바이너리, 객체 및 여러 인자를 지원합니다.
89
108
  `unsubscribe(tag)`로 구독을 해제할 수 있습니다.
90
109
 
91
- ### 시그널 태그 요약
92
-
93
- | 통신 방식 | 송신 | 구독 | 수신 tag |
94
- | --- | --- | --- | --- |
95
- | 채널 | `room#topic` | `room#topic` | `room#topic` |
96
- | 홈채널 | `#topic` | `#topic` | `#topic` |
97
- | B에게 직접 송신 | `B@topic` | 불필요 | `@topic` |
98
- | A의 CID 발행 | A가 `@topic` 송신 | `A@topic` | `A@topic` |
99
-
100
- 직접 시그널은 `on('message', ...)`가 아닌 `on('@', ...)`로 받습니다.
101
-
102
- ```js
103
- io.on('@', (tag, ...args) => {
104
- if (tag === '@topic') console.log(...args);
105
- });
106
- ```
107
-
108
- 리테인 발행은 `room#$state`나 `@$state`처럼 `$`를 포함한 태그를 사용합니다.
109
- 보관 정책과 제한은 서버·서비스 설정 및 인증 유형에 따라 달라집니다.
110
- 자세한 내용은 [시그널 태그](https://iosignal.net/docs/core/signal_tags)와
111
- [시그널 유형](https://iosignal.net/docs/core/signal_types)을 참고하세요.
110
+ 태그 규칙과 직접 메시지 수신 방법은 [메시징 가이드](https://github.com/remocons/iosignal/blob/main/docs/messaging.ko.md)를 참고하세요.
112
111
 
113
112
  ## 브라우저
114
113
 
@@ -129,6 +128,36 @@ io.on('ready', () => {
129
128
  브라우저 예제도 위 서버에 연결합니다. HTTPS 페이지에서는 TLS가 구성된
130
129
  `wss://` 서버 주소를 사용하세요. 사용이 끝나면 `io.stop()`으로 연결과 자동 재연결을 중단합니다.
131
130
 
131
+ ## Arduino 지원
132
+
133
+ [iosignal-arduino](https://github.com/remocons/iosignal-arduino)는 Arduino 클라이언트와
134
+ ESP32·ESP8266 등의 예제를 제공합니다. 라이브러리와 Boho·Crypto 의존성을 설치하고,
135
+ 보드에 맞는 예제에서 네트워크·서버 설정을 변경해 사용하세요.
136
+ 설치와 연결 방법은 [Arduino 공식 가이드](https://iosignal.net/docs/arduino)와
137
+ [라이브러리 README](https://github.com/remocons/iosignal-arduino#readme)를 참고하세요.
138
+
139
+ ## CLI 지원
140
+
141
+ [iosignal-cli](https://github.com/remocons/iosignal-cli)로 코드 작성 없이 서버와
142
+ 대화형 클라이언트를 실행할 수 있습니다. Node.js 22.16.0 이상이 필요합니다.
143
+
144
+ ```bash
145
+ npm install -g iosignal-cli
146
+ io-server -l 8080
147
+ ```
148
+
149
+ 다른 터미널에서 위 서버에 연결합니다. 앞의 JavaScript 서버가 실행 중이면
150
+ 서버를 추가로 실행하지 않고 클라이언트만 연결하세요.
151
+
152
+ ```bash
153
+ io-client -c ws://localhost:8080
154
+ ```
155
+
156
+ 클라이언트에서 `help`, `sub room`, `pub room hello`를 입력해 사용법과 통신을
157
+ 확인할 수 있습니다. Arduino와 TCP 통신도 함께 시험하려면 서버 실행 시
158
+ `io-server -l 8080 -L 8888`로 두 포트를 열고 장치를 TCP 포트 8888에 연결하세요.
159
+ 자세한 옵션은 [CLI README](https://github.com/remocons/iosignal-cli#readme)를 참고하세요.
160
+
132
161
  ## 주요 API
133
162
 
134
163
  | API | 용도 |
@@ -139,184 +168,41 @@ io.on('ready', () => {
139
168
  | `server.attach(name, service)` | RPC 서비스 등록 |
140
169
  | `io.call(service, command, ...args)` | RPC 요청 |
141
170
  | `io.subscribe(tag)` / `io.unsubscribe(tag)` | 태그 구독 / 해제 |
142
- | `io.signal(tag, ...args)` | 메시지 발행 |
171
+ | `io.signal(tag, ...args)` | 메시지 발행 또는 직접 송신 |
172
+ | `io.on(tag, handler)` | 이벤트 핸들러 등록 |
173
+ | `io.listen(tag, handler)` | 핸들러 등록; 직접 태그 이외에는 자동 구독 설정 |
174
+ | `io.ping()` | 서버 ping; 프로토콜 `pong` 이벤트로 응답 수신 |
143
175
  | `io.stop()` | 자동 재연결 중단 및 연결 정리 |
144
176
  | `server.close(callback)` | 서버 종료 |
145
177
  | `BohoAuth` | 서버 인증 관리자 |
146
178
  | `StringKeyProvider`, `FileKeyProvider`, `RedisKeyProvider` | 인증 키 공급자 |
179
+ | `LocalKeyProvider` | 로컬 테스트용 키 목록 없는 로그인 (`localAuth` 서버 옵션) |
147
180
 
148
- ## boho를 이용한 인증과 암호통신
149
-
150
- IOSignal은 [boho](https://github.com/remocons/boho)를 사용하여 공유 키 기반
151
- 인증과 메시지 암호화를 제공합니다. boho에는
152
- [Arduino 구현](https://github.com/remocons/boho-arduino)과 Node.js·브라우저용
153
- JavaScript 구현이 있어, 직접 만든 장치와 웹앱을 같은 방식으로 연결할 수 있습니다.
154
-
155
- ### 왜 공유 키 기반의 boho인가요?
156
-
157
- Arduino 장치와 직접 개발한 웹앱, 관리 주체가 같은 서버에서는 양쪽 코드와
158
- 최초 키 설정을 직접 관리할 수 있습니다. 제작 시 USB·직렬 연결로 장치별 키를
159
- 기록하거나, 웹앱 사용자가 별도 경로로 받은 키를 입력하거나, 서버 사이에서
160
- 기존 SSH·TLS 연결로 키를 배포할 수 있습니다.
161
-
162
- 이처럼 안전한 키 설정 경로가 이미 있다면 사전 공유 대칭키로도 인증과 암호통신을
163
- 설계할 수 있습니다. 인증기관 없이 통신할 상대를 정할 수 있으며, 이때 신뢰의
164
- 기반은 키 설정 경로와 양쪽 프로그램입니다. 장치별 키, 안전한 보관과 교체·폐기
165
- 방법은 여전히 필요합니다. 웹앱의 공개 JavaScript 번들에 공통 비밀 키를 넣는
166
- 것은 안전한 키 배포가 아닙니다.
167
-
168
- boho는 이 환경을 위해 SHA-256 기반 키스트림, XOR 암호화, 공유 키 인증과
169
- 바이너리 패킷을 묶습니다. 차별점은 암호 연산 자체의 새로움보다 **Arduino와
170
- JavaScript의 호환 구현을 IOSignal의 연결·메시지 전달에 활용할 수 있다는 점**입니다.
171
-
172
- ### XOR와 해시 기반 ‘가상 OTP’
181
+ ## 인증과 암호화
173
182
 
174
- XOR는 같은 값으로 두 번 연산하면 원래 값으로 돌아오는 단순한 연산입니다.
183
+ [Boho](https://github.com/remocons/boho)는 JavaScript와 Arduino에서 공유 키 인증과
184
+ 메시지 암호화를 제공합니다. 종단간 암호화(E2E)는 최종 송수신자만 공유하는 별도
185
+ 데이터 키로 설정합니다. 키 관리, TLS와의 관계, 세션 검증 및 구현의 적용 조건은
186
+ [Boho 기술 가이드](https://github.com/remocons/iosignal/blob/main/docs/boho.ko.md)를 참고하세요.
175
187
 
176
- ```text
177
- 암호화: 암호문 = 평문 XOR 키스트림
178
- 복호화: 평문 = 암호문 XOR 키스트림
179
- ```
180
-
181
- 진짜 일회용 패드(One-Time Pad, OTP)는 평문과 독립적인 완전한 무작위 패드를
182
- 데이터 길이만큼 준비하고, 비밀로 유지하며 한 번만 사용합니다. 이 조건에서는
183
- 완전한 비밀성을 얻지만, 1MB 데이터마다 새로운 1MB 비밀 패드를 양쪽에 공급해야
184
- 합니다. 같은 패드를 재사용하면 `C1 XOR C2 = P1 XOR P2`로 평문 사이의 관계가
185
- 노출됩니다.
186
-
187
- boho는 데이터 길이만큼 패드를 저장하는 대신, 비밀 키와 메시지별 값에서
188
- SHA-256으로 키스트림을 생성합니다. 일반적인 `set_key` 경로는 다음과 같습니다.
189
-
190
- ```text
191
- K = SHA256(입력 키)
192
- B = SHA256(K || salt12)
193
- S_i = SHA256(B || LE32(i)) // i = 1, 2, 3, …
194
- 키스트림 = S_1 || S_2 || … // 평문 길이만큼 사용
195
- ```
196
-
197
- `||`는 바이트열 연결이고, `LE32`는 4바이트 little-endian 정수입니다.
198
- 각 해시 출력은 32바이트입니다. `salt12`는 시각·카운터·nonce로 구성되며,
199
- 수신자도 같은 값과 키를 사용해 키스트림을 재현합니다.
200
-
201
- ‘가상 OTP’는 이 의사난수 키스트림을 설명하는 표현이며 진짜 OTP의 완전한
202
- 비밀성을 뜻하지 않습니다. **공개된 랜덤 값만 해시하면 누구나 같은 출력을
203
- 계산할 수 있으므로 공유 비밀 키가 필요합니다.** 같은 키와 `salt12`의 중복도
204
- 피해야 합니다. XOR만으로 변조를 검출할 수 없어 boho는 데이터 패킷에
205
- `SHA256(K || salt12 || 평문)`의 앞 8바이트로 계산한 태그도 포함합니다.
206
- 이 태그는 기존 코드의 명칭과 달리 표준 HMAC이 아닙니다.
207
-
208
- ### TLS와 함께 이해하기
209
-
210
- 일반적인 인증서 기반 TLS는 사전에 비밀을 공유하지 않은 상대와 인증·키 합의를
211
- 수행하고 실제 데이터에는 대칭키를 사용합니다. 로그인하지 않은 웹 사용자도
212
- 서버를 인증하고 암호화 연결을 만들 수 있지만, 네트워크 익명성을 제공하는 것은
213
- 아닙니다. 임베디드 환경에서는 인증서·신뢰 루트·시각·갱신 관리와 핸드셰이크
214
- 연산 및 버퍼가 부담이 될 수 있습니다. 키 설정 경로가 이미 있는 작은 시스템은
215
- 이런 구성 중 일부를 줄일 수 있습니다.
216
-
217
- 다만 TLS도 **PSK-only와 PSK+(EC)DHE**를 지원하므로 항상 제3자 인증서나 공개키
218
- 교환이 필요한 것은 아닙니다.
219
- [TLS 1.3의 PSK 방식](https://www.rfc-editor.org/rfc/rfc8446.html#section-2.2)
220
- boho가 모든 환경에서 TLS나 표준 대칭키 구현보다 빠르거나 메모리를 덜 사용한다는
221
- 뜻은 아니며 실제 비교에는 측정이 필요합니다.
222
-
223
- ### 연결 암호화와 E2E 데이터 키
224
-
225
- ```text
226
- Arduino 장치 ←→ IOSignal 서버 ←→ 브라우저 웹앱
227
- └──────── 별도 E2E 데이터 키 ────────┘
228
- ```
229
-
230
- 연결 인증용 키는 각 클라이언트의 서버 접속 자격을 확인하는 데 사용합니다.
231
- 중계 서버가 메시지 본문을 읽지 못하게 하려면 최종 송수신자만 공유하는 별도
232
- 데이터 키로 `signal_e2e`를 사용하고, 수신 측에서 `decrypt_e2e`로 검증·복호화합니다.
233
- 일반 연결 암호화만으로 종단간 암호화가 되는 것은 아닙니다. 서버는 E2E 메시지의
234
- 전달에 필요한 라우팅 정보를 처리하며 트래픽 크기 등의 메타데이터도 남습니다.
235
-
236
- 현재 JavaScript 구현의 `AUTO` 모드는 TLS를 사용하지 않고 boho 인증이 완료된
237
- 경우 boho 연결 암호화를 사용합니다. E2E 본문 암호화는 연결 보호 여부와 별도입니다.
238
- 위 빠른 시작의 인증 없는 로컬 예제는 boho 인증·암호화를 활성화한 예제가 아닙니다.
239
-
240
- 일반 웹 배포에서는 HTTPS로 웹앱을 제공하고 WSS로 연결하면서 본문에 E2E를
241
- 적용할 수 있습니다. 앱 코드가 변조되면 키와 평문도 노출될 수 있어 E2E에서도
242
- 웹앱 코드 제공자에 대한 신뢰가 필요합니다. boho는 브라우저의 mixed content
243
- 정책을 우회하지 않습니다.
244
-
245
- ### 7.0.0 세션 시간·재사용 검증
246
-
247
- 서버는 허용 시간 차이를 벗어나거나 이미 허용한 시간·카운터 조합을 다시
248
- 사용한 암호 패킷을 거부하고, 명령 실행·중계 전에 연결을 종료합니다.
249
- `ENC_488`과 `ENC_E2E` 라우팅 암호 헤더에 같은 정책을 적용하며 패킷 형식은 유지합니다.
188
+ 로컬 테스트에서는 `localAuth` 서버 옵션으로 키 목록 없이 인증을 켤 수 있습니다.
189
+ 로그인 ID가 CID가 됩니다. 규칙을 아는 누구나 임의 ID로 로그인할 수 있으므로
190
+ 신뢰하는 로컬 네트워크에서만 사용하세요. 8.1.0부터 지원합니다.
250
191
 
251
192
  ```js
252
- const server = new Server({
253
- port: 8080,
254
- security: {
255
- maxClockSkewMs: 60000,
256
- authChallengeMaxAgeMs: 60000,
257
- maxReplayEntries: 65536
258
- }
259
- }, authManager);
260
- ```
261
-
262
- 기본값은 절대 시간 차이 60초, 인증 challenge 유효기간 60초, 연결별 저장 한도
263
- 65,536개입니다. 설정은 양의 안전 정수여야 합니다. 저장 한도 초과도 연결을
264
- 종료하며 아직 유효한 재사용 기록을 임의로 지우지 않습니다.
265
- `security:mismatch(remote, reason)` 이벤트와 `remote.securityFailure`로 사유를 확인합니다.
266
-
267
- 정상 검증된 인증 증명은 challenge를 소진합니다. 재인증 또는 challenge 만료 후
268
- 수동 로그인은 재연결해야 합니다. 인증된 연결에서 다시 `login()`하면 연결이
269
- 종료됩니다. AUTH_REQ에는 현재 장치 시각이 없으므로 초기에는 challenge 경과시간을,
270
- 이후 암호 패킷에서는 장치 시각과 서버 시각의 차이를 검사합니다.
271
- 평문·TLS 전송 정책은 변경하지 않습니다.
272
-
273
- JS 클라이언트 시계는 허용 범위 안에 있어야 합니다. Boho Arduino 1.0.0은 검증된
274
- 서버 암호 헤더로 시계를 점진 보정하며 평문 PING/PONG은 시간 보정에 사용하지 않습니다.
275
- 내부 E2E 본문의 재사용 방지는 연결 암호 헤더 검증과 별도로 응용 계층에서 처리합니다.
276
-
277
- ### 현재 구현의 적용 조건
278
-
279
- - 충분히 무작위인 키를 사용하세요. `set_key`의 SHA-256 한 번은 비밀번호용 느린 KDF가 아닙니다.
280
- - JavaScript는 `crypto.getRandomValues()`를 사용하지만 현재 Arduino 구현의 독립 패킷과 인증 요청의 클라이언트 nonce는 `micros()`에 기반합니다. 이는 암호학적 난수가 아니므로 재시작·장치·통신 방향을 포함해 같은 키와 `salt12`가 반복되지 않는지 검토해야 합니다.
281
- - boho 자체는 재전송 거부나 challenge 만료를 강제하지 않습니다. 유효한 태그만으로 메시지의 신선도나 명령 실행 권한이 보장되지 않으므로 호출 측과 응용 계층의 수신 정책을 확인해야 합니다.
282
- - boho는 SHA-256을 조합한 자체 프로토콜입니다. 표준 AEAD/TLS와 동일한 보안 보장이나 장기 키 유출 후 과거 통신을 보호하는 순방향 비밀성을 제공한다고 취급해서는 안 됩니다.
283
-
284
- ## 소스 빌드 및 검증
285
-
286
- 이 저장소의 개발·검증 환경은 Node.js 22와 npm 10을 사용합니다.
287
-
288
- ```bash
289
- npm ci
290
- npm run verify
193
+ new Server({ port: 7777, localAuth: 'idKey' }) // io.auth('dev1', 'dev1')
194
+ new Server({ port: 7777, localAuth: { mode: 'sharedKey', key: 'lab2026' } }) // io.auth('dev1', 'lab2026')
291
195
  ```
292
196
 
293
- `verify`는 공개 파일 정책을 검사하고, `dist`를 삭제한 뒤 번들과 타입 선언을
294
- 재생성합니다. 이어서 자동 테스트와 npm 패키지 포함 파일 검사를 수행합니다.
295
-
296
- 빌드만 실행하려면 `npm run build`, 이미 빌드된 결과의 자동 테스트만 실행하려면
297
- `npm test`를 사용합니다.
298
-
299
- ### 통신 자동 테스트
300
-
301
- ```bash
302
- npm run build
303
- npm run test:integration
304
- ```
305
-
306
- `test/integration/`은 공개 ESM·CommonJS 빌드 각각에 대해 실제 WebSocket 통신을 검사합니다.
307
- 로컬 루프백(`127.0.0.1`)의 임시 포트를 사용하므로 외부 서버, Redis, 실제 인증키가 필요하지 않습니다.
308
-
309
- - 연결과 RPC 응답, 없는 명령 및 권한 거부
310
- - 두 클라이언트 간 문자열·객체·바이너리 발행/구독과 구독 해제
311
- - 인증 성공 및 암호화된 RPC 응답, 잘못된 인증 거부
312
- - 연결 종료 후 클라이언트 재사용과 서버 자원 정리
197
+ 익명 연결의 시그널을 막으려면 `membersOnly: true`를 함께 지정합니다.
198
+ [로컬 테스트 로그인](https://github.com/remocons/iosignal/blob/main/docs/boho.ko.md#로컬-테스트-로그인-localauth)을 참고하세요.
313
199
 
314
- `npm test`와 `npm run verify`에도 통신 검사가 포함됩니다. 테스트별 시간 제한과
315
- 전체 테스트 파일 시간 제한을 두며, 종료 시 서버와 클라이언트를 정리합니다.
316
- 실제 브라우저, TLS, TCP 전송 및 Redis 연동 검증은 이 통신 테스트 범위에 포함되지 않습니다.
200
+ ## 상세 문서
317
201
 
318
- 기존 `test/attach-services/`, `test/auth_server_client/`, `test/pubsub-counter/`,
319
- `test/subscribe-signal/`은 수동 예제입니다. 자동 실행하지 않으며, 일부는 별도 서버나 Redis가 필요합니다.
202
+ - [시그널 태그와 직접 메시지](https://github.com/remocons/iosignal/blob/main/docs/messaging.ko.md)
203
+ - [서버 ping과 peer ping](https://github.com/remocons/iosignal/blob/main/docs/ping.ko.md)
204
+ - [Boho 인증·암호화와 E2E](https://github.com/remocons/iosignal/blob/main/docs/boho.ko.md)
205
+ - [소스 빌드 및 검증](https://github.com/remocons/iosignal/blob/main/docs/development.ko.md)
320
206
 
321
207
  ## 라이선스
322
208
 
package/README.md CHANGED
@@ -6,6 +6,26 @@ A real-time messaging library for Node.js and browsers, providing WebSocket
6
6
  client–server communication, tag-based publish/subscribe and RPC services.
7
7
  Node.js also supports TCP through `IOCongSocket`.
8
8
 
9
+ <p align="center">
10
+ <img src="https://raw.githubusercontent.com/remocons/iosignal/main/docs/assets/iosignal-ecosystem.png" alt="Server, CLI, Node.js, Arduino and remote web apps connected through IOSignal" width="720" />
11
+ </p>
12
+
13
+ ## Documentation and supported environments
14
+
15
+ The [official documentation](https://iosignal.net/) covers installation, messaging
16
+ concepts and platform guides in Korean. Follow the
17
+ [five-minute quick start](https://iosignal.net/docs/start/quickstart/) for an overview,
18
+ and use the quick start below for examples targeting the current version.
19
+
20
+ | Environment / tool | Support | Package / examples |
21
+ | --- | --- | --- |
22
+ | Node.js | WebSocket/TCP servers and clients, publish/subscribe, RPC | This repository · [npm](https://www.npmjs.com/package/iosignal) |
23
+ | Browsers | WebSocket clients and web app integration | `iosignal/io` · [examples](https://github.com/remocons/iosignal-examples) |
24
+ | Arduino | Device communication with servers and web apps, authentication and encryption | [iosignal-arduino](https://github.com/remocons/iosignal-arduino) |
25
+ | CLI | Run servers and clients and test messaging in a terminal | [iosignal-cli](https://github.com/remocons/iosignal-cli) |
26
+
27
+ Try messaging in the [browser communication workbench](https://test.iosignal.net/).
28
+
9
29
  ## Installation
10
30
 
11
31
  ```bash
@@ -89,27 +109,7 @@ process.once('SIGINT', () => io.stop());
89
109
  `signal(tag, ...args)` supports strings, binary data, objects and multiple
90
110
  arguments. Use `unsubscribe(tag)` to unsubscribe.
91
111
 
92
- ### Signal tags at a glance
93
-
94
- | Communication | Send | Subscribe | Received tag |
95
- | --- | --- | --- | --- |
96
- | Channel | `room#topic` | `room#topic` | `room#topic` |
97
- | Home channel | `#topic` | `#topic` | `#topic` |
98
- | Direct to B | `B@topic` | Not required | `@topic` |
99
- | Publication by A | A sends `@topic` | `A@topic` | `A@topic` |
100
-
101
- Direct signals arrive on `on('@', ...)`, rather than `on('message', ...)`.
102
-
103
- ```js
104
- io.on('@', (tag, ...args) => {
105
- if (tag === '@topic') console.log(...args);
106
- });
107
- ```
108
-
109
- For retained publications, use a tag containing `$`, such as `room#$state` or
110
- `@$state`. Retention policies and limits depend on server/service configuration
111
- and authentication type. See [signal tags](https://iosignal.net/docs/core/signal_tags)
112
- and [signal types](https://iosignal.net/docs/core/signal_types) for details.
112
+ See the [messaging guide](https://github.com/remocons/iosignal/blob/main/docs/messaging.md) for tag rules and direct-message handling.
113
113
 
114
114
  ## Browsers
115
115
 
@@ -131,6 +131,38 @@ This browser example connects to the same server above. From an HTTPS page,
131
131
  use a `wss://` server URL with TLS configured. When finished, call `io.stop()`
132
132
  to close the connection and stop automatic reconnection.
133
133
 
134
+ ## Arduino support
135
+
136
+ [iosignal-arduino](https://github.com/remocons/iosignal-arduino) provides an Arduino
137
+ client and examples for boards including ESP32 and ESP8266. Install the library
138
+ and its Boho and Crypto dependencies, then configure the network and server in
139
+ an example for your board. See the [official Arduino guide](https://iosignal.net/docs/arduino)
140
+ and [library README](https://github.com/remocons/iosignal-arduino/blob/main/README.en.md)
141
+ for setup and connection instructions.
142
+
143
+ ## CLI support
144
+
145
+ [iosignal-cli](https://github.com/remocons/iosignal-cli) runs a server or an
146
+ interactive client without writing application code. Requires Node.js 22.16.0 or later.
147
+
148
+ ```bash
149
+ npm install -g iosignal-cli
150
+ io-server -l 8080
151
+ ```
152
+
153
+ Connect from another terminal. If the JavaScript server above is already running,
154
+ run only the client:
155
+
156
+ ```bash
157
+ io-client -c ws://localhost:8080
158
+ ```
159
+
160
+ Enter `help`, `sub room` and `pub room hello` in the client to explore messaging.
161
+ To also test Arduino over TCP, start the server with
162
+ `io-server -l 8080 -L 8888` and connect the device to TCP port 8888.
163
+ See the [CLI README](https://github.com/remocons/iosignal-cli/blob/main/README.en.md)
164
+ for more options.
165
+
134
166
  ## Main APIs
135
167
 
136
168
  | API | Purpose |
@@ -141,220 +173,43 @@ to close the connection and stop automatic reconnection.
141
173
  | `server.attach(name, service)` | Register an RPC service |
142
174
  | `io.call(service, command, ...args)` | Make an RPC request |
143
175
  | `io.subscribe(tag)` / `io.unsubscribe(tag)` | Subscribe / unsubscribe |
144
- | `io.signal(tag, ...args)` | Publish a message |
176
+ | `io.signal(tag, ...args)` | Publish or send a direct message |
177
+ | `io.on(tag, handler)` | Register an event handler |
178
+ | `io.listen(tag, handler)` | Register a handler; remember subscriptions for non-direct tags |
179
+ | `io.ping()` | Ping the server; receive the protocol `pong` event |
145
180
  | `io.stop()` | Stop automatic reconnection and clean up the connection |
146
181
  | `server.close(callback)` | Shut down the server |
147
182
  | `BohoAuth` | Server authentication manager |
148
183
  | `StringKeyProvider`, `FileKeyProvider`, `RedisKeyProvider` | Authentication key providers |
184
+ | `LocalKeyProvider` | Key-list-free logins for local tests (`localAuth` server option) |
149
185
 
150
- ## Authentication and encrypted communication with Boho
151
-
152
- IOSignal uses [Boho](https://github.com/remocons/boho) for shared-key authentication
153
- and message encryption. Boho has an
154
- [Arduino implementation](https://github.com/remocons/boho-arduino) and a JavaScript
155
- implementation for Node.js and browsers, allowing DIY devices and web apps to use
156
- the same approach.
157
-
158
- ### Why shared-key Boho?
159
-
160
- With Arduino devices, your own web apps and servers under common administration,
161
- you can control both endpoint code and initial key provisioning. Device-specific
162
- keys can be installed over USB/serial during setup, web app users can enter keys
163
- obtained through another channel, and servers can distribute keys through
164
- existing SSH/TLS connections.
165
-
166
- When a secure provisioning path already exists, pre-shared symmetric keys can
167
- support authentication and encrypted communication. You can establish peers
168
- without a certificate authority; trust rests on the provisioning path and
169
- endpoint software. Device-specific keys, secure storage, rotation and revocation
170
- are still necessary. Embedding a common secret in a public JavaScript bundle is
171
- not secure key distribution.
172
-
173
- Boho combines a SHA-256-based keystream, XOR encryption, shared-key authentication
174
- and binary packets for this environment. Its distinction is **compatible Arduino
175
- and JavaScript implementations integrated with IOSignal connections and message
176
- delivery**, rather than novelty in the cryptographic operations themselves.
177
-
178
- ### XOR and a hash-based “virtual OTP”
179
-
180
- XOR is a simple operation that restores the original value when applied twice
181
- with the same value.
182
-
183
- ```text
184
- Encryption: ciphertext = plaintext XOR keystream
185
- Decryption: plaintext = ciphertext XOR keystream
186
- ```
187
-
188
- A true one-time pad (OTP) uses a uniformly random pad independent of the
189
- plaintext, as long as the data, kept secret and used only once. This provides
190
- perfect secrecy, but requires supplying both endpoints with a new 1 MB secret
191
- pad for every 1 MB of data. Reusing a pad exposes `C1 XOR C2 = P1 XOR P2`, revealing
192
- a relationship between plaintexts.
186
+ ## Authentication and encryption
193
187
 
194
- Instead of storing a pad as large as the data, Boho generates a SHA-256 keystream
195
- from a secret key and message-specific values. The usual `set_key` path is:
188
+ [Boho](https://github.com/remocons/boho) provides shared-key authentication and
189
+ message encryption for JavaScript and Arduino. End-to-end encryption (E2E) uses
190
+ a separate data key shared only by the final endpoints. See the
191
+ [Boho technical guide](https://github.com/remocons/iosignal/blob/main/docs/boho.md) for key management, the relationship
192
+ with TLS, session validation and implementation conditions.
196
193
 
197
- ```text
198
- K = SHA256(input key)
199
- B = SHA256(K || salt12)
200
- S_i = SHA256(B || LE32(i)) // i = 1, 2, 3, …
201
- keystream = S_1 || S_2 || … // use only the plaintext length
202
- ```
203
-
204
- `||` means byte concatenation; `LE32` is a four-byte little-endian integer. Each
205
- hash output is 32 bytes. `salt12` contains time, counter and nonce values, and
206
- the receiver reproduces the stream using the same values and key.
207
-
208
- “Virtual OTP” describes this pseudorandom stream, not the perfect secrecy of a
209
- true OTP. **Public random values alone can be hashed by anyone, so a shared secret
210
- key is required.** Repeating the same key and `salt12` must also be avoided. XOR
211
- alone does not detect tampering, so Boho data packets include the first eight
212
- bytes of `SHA256(K || salt12 || plaintext)` as a tag. Despite legacy names in the
213
- code, this tag is not standard HMAC.
214
-
215
- ### Understanding the relationship with TLS
216
-
217
- Typical certificate-based TLS authenticates peers and establishes keys without a
218
- previously shared secret, then uses symmetric encryption for application data.
219
- Even web users who have not logged in can authenticate the server and establish
220
- an encrypted connection, but this does not provide network anonymity. On embedded
221
- devices, certificate, trust-root, clock and renewal management, handshake work
222
- and buffers can be burdensome. Small systems with an existing provisioning path
223
- may be able to omit some of this machinery.
224
-
225
- However, TLS supports **PSK-only and PSK with (EC)DHE**, so it does not always
226
- require third-party certificates or public-key exchange.
227
- [TLS 1.3 pre-shared keys](https://www.rfc-editor.org/rfc/rfc8446.html#section-2.2)
228
- This does not mean Boho is faster or uses less memory than every TLS or standard
229
- symmetric implementation; actual comparisons require measurement.
230
-
231
- ### Connection encryption and E2E data keys
232
-
233
- ```text
234
- Arduino device ←→ IOSignal server ←→ Browser app
235
- └──────── Separate E2E data key ────────┘
236
- ```
237
-
238
- Connection credentials establish each client's right to connect to the server.
239
- To keep a message body confidential from a relay, use `signal_e2e` with a separate
240
- data key held only by the final endpoints, then verify and decrypt it with
241
- `decrypt_e2e` at the receiver. Ordinary connection encryption is not automatically
242
- end-to-end encryption. The server processes routing information for E2E delivery,
243
- and metadata such as traffic sizes remains visible.
244
-
245
- The current JavaScript implementation's `AUTO` mode uses Boho connection
246
- encryption when TLS is not used and Boho authentication is complete. E2E body
247
- encryption is separate from connection protection. The unauthenticated local
248
- quick-start examples above do not enable Boho authentication/encryption.
249
-
250
- Normal web deployments can serve app code over HTTPS and connect over WSS while
251
- also applying E2E to message bodies. Modified app code can expose keys and
252
- plaintext, so E2E still requires trust in the app code provider. Boho does not
253
- bypass browser mixed content rules.
254
-
255
- ### Session freshness in 7.0.0
256
-
257
- The server now rejects encrypted session packets outside the configured clock
258
- window or with an already accepted time/counter pair. Both `ENC_488` and the
259
- `ENC_E2E` routing envelope share this policy. Rejection terminates the connection
260
- before executing or routing the message. Wire formats remain unchanged.
194
+ For local tests, the `localAuth` server option turns on authentication without
195
+ a key list. The login ID becomes the CID. Anyone who knows the rule can log in
196
+ under any ID, so use it only on a trusted local network. Added in 8.1.0.
261
197
 
262
198
  ```js
263
- const server = new Server({
264
- port: 8080,
265
- security: {
266
- maxClockSkewMs: 60000,
267
- authChallengeMaxAgeMs: 60000,
268
- maxReplayEntries: 65536
269
- }
270
- }, authManager);
271
- ```
272
-
273
- Defaults are a 60-second absolute clock window, a 60-second authentication
274
- challenge lifetime and at most 65,536 remembered packet tuples per connection.
275
- The limits must be positive safe integers. Cache exhaustion also terminates the
276
- connection; still-valid replay evidence is never evicted. The server emits
277
- `security:mismatch(remote, reason)` and records `remote.securityFailure`.
278
-
279
- A successfully verified authentication proof consumes its challenge. Reconnect
280
- for reauthentication or if manual login occurs after challenge expiry; calling
281
- `login()` again on an authenticated connection now closes it. AUTH_REQ has no
282
- current device timestamp, so this stage checks challenge age. Device clock skew
283
- is checked on encrypted packets. Plaintext/TLS transport policy is unchanged.
284
-
285
- JS clients must have a clock within the configured window. Boho Arduino 1.0.0
286
- adds gradual clock correction from authenticated server envelopes; plain
287
- PING/PONG provides no time sample. Inner E2E payload freshness remains an
288
- application concern, separate from the connection envelope.
289
-
290
- ### Conditions in the current implementation
291
-
292
- - Use sufficiently random keys. A single SHA-256 in `set_key` is not a slow password KDF.
293
- - JavaScript uses `crypto.getRandomValues()`, but current Arduino standalone-packet nonces and the authentication client nonce use `micros()`. This is not cryptographic randomness; consider repeated key/`salt12` combinations across restarts, devices and communication directions.
294
- - Boho itself does not enforce replay rejection or challenge expiry. A valid tag alone does not establish freshness or permission to execute a command; check receive policies in the caller and application layer.
295
- - Boho is a custom SHA-256-based protocol. Do not assume standard AEAD/TLS guarantees or forward secrecy protecting past traffic after a long-term key leak.
296
-
297
- ## Building and verification
298
-
299
- This repository uses Node.js 22 and npm 10 for development and verification.
300
-
301
- ```bash
302
- npm ci
303
- npm run verify
199
+ new Server({ port: 7777, localAuth: 'idKey' }) // io.auth('dev1', 'dev1')
200
+ new Server({ port: 7777, localAuth: { mode: 'sharedKey', key: 'lab2026' } }) // io.auth('dev1', 'lab2026')
304
201
  ```
305
202
 
306
- `verify` checks the public-file policy, removes `dist` and rebuilds bundles and
307
- type declarations. It then runs automated tests and checks the npm package file
308
- list.
309
-
310
- Use `npm run build` to build only, or `npm test` to test an existing build.
311
-
312
- ### Automated communication tests
313
-
314
- ```bash
315
- npm run build
316
- npm run test:integration
317
- ```
318
-
319
- `test/integration/` tests actual WebSocket communication for both public ESM and
320
- CommonJS builds. It uses temporary ports on local loopback (`127.0.0.1`), so it
321
- requires no external server, Redis instance or real authentication credentials.
322
-
323
- - Connections, RPC responses, unknown commands and permission denial
324
- - String, object and binary publish/subscribe between two clients, including unsubscribe
325
- - Successful authentication and encrypted RPC responses, plus rejection of invalid authentication
326
- - Client reuse and server resource cleanup after disconnection
203
+ Add `membersOnly: true` to drop signals from anonymous connections. See
204
+ [Local test logins](https://github.com/remocons/iosignal/blob/main/docs/boho.md#local-test-logins-localauth).
327
205
 
328
- These communication checks are included in `npm test` and `npm run verify`.
329
- Individual tests and test files have time limits, and connections and servers
330
- are cleaned up on completion. Actual browsers, TLS, TCP transport and Redis
331
- integration are outside their scope.
206
+ ## Detailed guides
332
207
 
333
- Existing `test/attach-services/`, `test/auth_server_client/`,
334
- `test/pubsub-counter/` and `test/subscribe-signal/` are manual examples. They are
335
- not run automatically, and some require a separate server or Redis.
208
+ - [Signal tags and direct messages](https://github.com/remocons/iosignal/blob/main/docs/messaging.md)
209
+ - [Server ping and peer ping](https://github.com/remocons/iosignal/blob/main/docs/ping.md)
210
+ - [Boho authentication, encryption and E2E](https://github.com/remocons/iosignal/blob/main/docs/boho.md)
211
+ - [Building and verification](https://github.com/remocons/iosignal/blob/main/docs/development.md)
336
212
 
337
213
  ## License
338
214
 
339
215
  Package license: MIT.
340
-
341
- ### Server ping and peer ping
342
-
343
- `io.ping()` sends a protocol PING to the server. The server replies with a
344
- protocol PONG and the client emits `io.on('pong', () => { ... })`.
345
- Native WebSocket heartbeat frames remain separate.
346
-
347
- Peer ping uses ordinary direct signals, with **one TEXT argument** carrying the
348
- sender CID. An application can opt in to replies as follows:
349
-
350
- ```js
351
- io.signal(`${targetCid}@ping`, io.cid);
352
- io.on('@', (tag, senderCid) => {
353
- if (tag === '@ping') io.signal(`${senderCid}@pong`, io.cid);
354
- if (tag === '@pong') console.log(`pong (${senderCid})`);
355
- });
356
- ```
357
-
358
- Peer responses arrive in that same `@` handler with tag `@pong`; they do not
359
- emit the protocol `pong` event. CLI clients implement replies, and Arduino's
360
- `peer_ping_pong` example implements them in user code.
@@ -178,7 +178,9 @@ declare class IOCore extends EventEmitter<string | symbol, any> {
178
178
  stop(): void;
179
179
  /**
180
180
  * Permanently destroys the instance, cleaning up all resources.
181
- * The instance will not be usable after this.
181
+ * The instance will not be usable after this. Later signal()/publish()/subscribe()
182
+ * calls are silently dropped, the same as sends while disconnected, and call()
183
+ * rejects with code 'CONNECTION_CLOSED'.
182
184
  */
183
185
  destroy(): void;
184
186
  /**
@@ -261,6 +263,7 @@ declare class IOCore extends EventEmitter<string | symbol, any> {
261
263
  getEncryptionMode(): boolean;
262
264
  /**
263
265
  * Sends data with encryption based on the encryption mode.
266
+ * Like an unconnected socket, a destroyed instance silently drops the data.
264
267
  * @param {Buffer} data - The data buffer to send.
265
268
  * @param {boolean} [useEncryption] - Optional. Force encryption or not. If undefined, uses default policy.
266
269
  */
@@ -504,7 +507,7 @@ declare class IO extends IOCore {
504
507
  */
505
508
  onWebSocketMessageBlob(event: MessageEvent): Promise<void>;
506
509
  /**
507
- * Sends data over the WebSocket.
510
+ * Sends data over the WebSocket. Data is dropped while the socket is not open.
508
511
  * @param {BufferSource} data - The data to send.
509
512
  */
510
513
  socket_send(data: BufferSource): void;