Compare commits
18 Commits
cec59784de
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| b270649f21 | |||
| 8b26919790 | |||
| 4adb187331 | |||
| 8824e768fb | |||
| 57b53fc122 | |||
| 7cdda2e335 | |||
| b10ebc541e | |||
| 9fd9b50842 | |||
| 5fbbdd199c | |||
| 93e09875ec | |||
| 65c1f92cc1 | |||
| df14022c9a | |||
| 824019168e | |||
| 4322604f78 | |||
| ddeed9a7b7 | |||
| 07c2438fb8 | |||
| 58818e11d1 | |||
| 5ca6ec0952 |
4
.gitignore
vendored
Normal file
4
.gitignore
vendored
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
node_modules/
|
||||||
|
dist/
|
||||||
|
coverage/
|
||||||
|
*.log
|
||||||
134
README.md
134
README.md
@@ -0,0 +1,134 @@
|
|||||||
|
# Yonexus.Client
|
||||||
|
|
||||||
|
Yonexus.Client is the follower-side plugin for a Yonexus network.
|
||||||
|
|
||||||
|
It runs on non-central OpenClaw instances and is responsible for:
|
||||||
|
|
||||||
|
- connecting outbound to `Yonexus.Server`
|
||||||
|
- managing local identifier + trust material
|
||||||
|
- generating a local Ed25519 keypair on first run
|
||||||
|
- completing out-of-band pairing
|
||||||
|
- authenticating on reconnect with signed proof
|
||||||
|
- sending periodic heartbeats
|
||||||
|
- dispatching inbound rule messages to locally registered handlers
|
||||||
|
|
||||||
|
## Status
|
||||||
|
|
||||||
|
Current state: **scaffold + core runtime MVP**
|
||||||
|
|
||||||
|
Implemented in this repository today:
|
||||||
|
|
||||||
|
- config validation
|
||||||
|
- local state store for identifier / keypair / secret
|
||||||
|
- automatic first-run keypair generation
|
||||||
|
- WebSocket client transport with reconnect backoff
|
||||||
|
- hello / hello_ack handling
|
||||||
|
- pairing pending flow + pairing code submission
|
||||||
|
- auth_request generation and auth state transitions
|
||||||
|
- heartbeat loop
|
||||||
|
- rule registry + send-to-server APIs
|
||||||
|
|
||||||
|
Still pending before production use:
|
||||||
|
|
||||||
|
- automated Client unit/integration tests
|
||||||
|
- richer operator UX for entering pairing codes
|
||||||
|
- final OpenClaw lifecycle hook integration
|
||||||
|
- deployment/troubleshooting docs specific to follower instances
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
Required config shape:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"mainHost": "wss://example.com/yonexus",
|
||||||
|
"identifier": "client-a",
|
||||||
|
"notifyBotToken": "<discord-bot-token>",
|
||||||
|
"adminUserId": "123456789012345678"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Field notes
|
||||||
|
|
||||||
|
- `mainHost`: WebSocket URL of the Yonexus server (`ws://` or `wss://`)
|
||||||
|
- `identifier`: unique client identity inside the Yonexus network
|
||||||
|
- `notifyBotToken`: currently kept aligned with system-level config expectations
|
||||||
|
- `adminUserId`: admin reference used by the broader Yonexus pairing model
|
||||||
|
|
||||||
|
## Runtime Overview
|
||||||
|
|
||||||
|
Startup flow:
|
||||||
|
|
||||||
|
1. validate config
|
||||||
|
2. load local state
|
||||||
|
3. generate keypair if missing
|
||||||
|
4. connect to `mainHost`
|
||||||
|
5. send `hello`
|
||||||
|
6. continue into pairing or auth depending on server response
|
||||||
|
|
||||||
|
Authentication flow:
|
||||||
|
|
||||||
|
1. receive `hello_ack(auth_required)` or `pair_success`
|
||||||
|
2. build proof from `secret + nonce + timestamp` using canonical JSON bytes
|
||||||
|
3. sign with local Ed25519 private key
|
||||||
|
4. send `auth_request`
|
||||||
|
5. on success, enter authenticated state and start heartbeat loop
|
||||||
|
|
||||||
|
Pairing flow:
|
||||||
|
|
||||||
|
1. receive `pair_request` metadata from server
|
||||||
|
2. obtain pairing code from the human-admin out-of-band channel
|
||||||
|
3. submit pairing code through `submitPairingCode()`
|
||||||
|
4. persist returned secret after `pair_success`
|
||||||
|
|
||||||
|
## Public API Surface
|
||||||
|
|
||||||
|
Exported runtime helpers currently include:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
sendMessageToServer(message: string): Promise<boolean>
|
||||||
|
sendRuleMessage(ruleIdentifier: string, content: string): Promise<boolean>
|
||||||
|
registerRule(rule: string, processor: (message: string) => unknown): void
|
||||||
|
submitPairingCode(pairingCode: string): Promise<boolean>
|
||||||
|
```
|
||||||
|
|
||||||
|
Rules:
|
||||||
|
|
||||||
|
- application messages must use `${rule_identifier}::${message_content}`
|
||||||
|
- `builtin` is reserved and cannot be registered as an application rule
|
||||||
|
|
||||||
|
## Local State
|
||||||
|
|
||||||
|
The client persists at least:
|
||||||
|
|
||||||
|
- `identifier`
|
||||||
|
- `privateKey`
|
||||||
|
- `publicKey`
|
||||||
|
- `secret`
|
||||||
|
- key/auth/pair timestamps
|
||||||
|
|
||||||
|
This is enough to survive restarts and perform authenticated reconnects.
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
Install dependencies and run type checks:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install
|
||||||
|
npm run check
|
||||||
|
```
|
||||||
|
|
||||||
|
## Limitations
|
||||||
|
|
||||||
|
Current known limitations:
|
||||||
|
|
||||||
|
- no polished end-user pairing code entry UX yet
|
||||||
|
- no client unit/integration test suite yet
|
||||||
|
- no offline buffering/queueing
|
||||||
|
- no end-to-end encrypted payload channel beyond current pairing/auth model
|
||||||
|
|
||||||
|
## Related Repos
|
||||||
|
|
||||||
|
- Umbrella: `../`
|
||||||
|
- Shared protocol: `../Yonexus.Protocol`
|
||||||
|
- Server plugin: `../Yonexus.Server`
|
||||||
|
|||||||
1267
package-lock.json
generated
1267
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
11
package.json
11
package.json
@@ -5,6 +5,9 @@
|
|||||||
"description": "Yonexus.Client OpenClaw plugin scaffold",
|
"description": "Yonexus.Client OpenClaw plugin scaffold",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "dist/plugin/index.js",
|
"main": "dist/plugin/index.js",
|
||||||
|
"openclaw": {
|
||||||
|
"extensions": ["./dist/Yonexus.Client/plugin/index.js"]
|
||||||
|
},
|
||||||
"files": [
|
"files": [
|
||||||
"dist",
|
"dist",
|
||||||
"plugin",
|
"plugin",
|
||||||
@@ -19,12 +22,16 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "tsc -p tsconfig.json",
|
"build": "tsc -p tsconfig.json",
|
||||||
"clean": "rm -rf dist",
|
"clean": "rm -rf dist",
|
||||||
"check": "tsc -p tsconfig.json --noEmit"
|
"check": "tsc -p tsconfig.json --noEmit",
|
||||||
|
"test": "vitest run",
|
||||||
|
"test:watch": "vitest"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"ws": "^8.18.0"
|
"ws": "^8.18.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"typescript": "^5.6.3"
|
"@types/node": "^25.5.2",
|
||||||
|
"typescript": "^5.6.3",
|
||||||
|
"vitest": "^4.1.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,25 +32,25 @@ export function validateYonexusClientConfig(raw: unknown): YonexusClientConfig {
|
|||||||
const source = (raw && typeof raw === "object" ? raw : {}) as Record<string, unknown>;
|
const source = (raw && typeof raw === "object" ? raw : {}) as Record<string, unknown>;
|
||||||
const issues: string[] = [];
|
const issues: string[] = [];
|
||||||
|
|
||||||
const mainHost = source.mainHost;
|
const rawMainHost = source.mainHost;
|
||||||
if (!isNonEmptyString(mainHost)) {
|
if (!isNonEmptyString(rawMainHost)) {
|
||||||
issues.push("mainHost is required");
|
issues.push("mainHost is required");
|
||||||
} else if (!isValidWsUrl(mainHost.trim())) {
|
} else if (!isValidWsUrl(rawMainHost.trim())) {
|
||||||
issues.push("mainHost must be a valid ws:// or wss:// URL");
|
issues.push("mainHost must be a valid ws:// or wss:// URL");
|
||||||
}
|
}
|
||||||
|
|
||||||
const identifier = source.identifier;
|
const rawIdentifier = source.identifier;
|
||||||
if (!isNonEmptyString(identifier)) {
|
if (!isNonEmptyString(rawIdentifier)) {
|
||||||
issues.push("identifier is required");
|
issues.push("identifier is required");
|
||||||
}
|
}
|
||||||
|
|
||||||
const notifyBotToken = source.notifyBotToken;
|
const rawNotifyBotToken = source.notifyBotToken;
|
||||||
if (!isNonEmptyString(notifyBotToken)) {
|
if (!isNonEmptyString(rawNotifyBotToken)) {
|
||||||
issues.push("notifyBotToken is required");
|
issues.push("notifyBotToken is required");
|
||||||
}
|
}
|
||||||
|
|
||||||
const adminUserId = source.adminUserId;
|
const rawAdminUserId = source.adminUserId;
|
||||||
if (!isNonEmptyString(adminUserId)) {
|
if (!isNonEmptyString(rawAdminUserId)) {
|
||||||
issues.push("adminUserId is required");
|
issues.push("adminUserId is required");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -58,10 +58,15 @@ export function validateYonexusClientConfig(raw: unknown): YonexusClientConfig {
|
|||||||
throw new YonexusClientConfigError(issues);
|
throw new YonexusClientConfigError(issues);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const mainHost = (rawMainHost as string).trim();
|
||||||
|
const identifier = (rawIdentifier as string).trim();
|
||||||
|
const notifyBotToken = (rawNotifyBotToken as string).trim();
|
||||||
|
const adminUserId = (rawAdminUserId as string).trim();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
mainHost: mainHost.trim(),
|
mainHost,
|
||||||
identifier: identifier.trim(),
|
identifier,
|
||||||
notifyBotToken: notifyBotToken.trim(),
|
notifyBotToken,
|
||||||
adminUserId: adminUserId.trim()
|
adminUserId
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
85
plugin/core/rules.ts
Normal file
85
plugin/core/rules.ts
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
import { BUILTIN_RULE, CodecError, parseRuleMessage } from "../../../Yonexus.Protocol/src/index.js";
|
||||||
|
|
||||||
|
export type ClientRuleProcessor = (message: string) => unknown;
|
||||||
|
|
||||||
|
export class ClientRuleRegistryError extends Error {
|
||||||
|
constructor(message: string) {
|
||||||
|
super(message);
|
||||||
|
this.name = "ClientRuleRegistryError";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ClientRuleRegistry {
|
||||||
|
readonly size: number;
|
||||||
|
registerRule(rule: string, processor: ClientRuleProcessor): void;
|
||||||
|
hasRule(rule: string): boolean;
|
||||||
|
dispatch(raw: string): boolean;
|
||||||
|
getRules(): readonly string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export class YonexusClientRuleRegistry implements ClientRuleRegistry {
|
||||||
|
private readonly rules = new Map<string, ClientRuleProcessor>();
|
||||||
|
|
||||||
|
get size(): number {
|
||||||
|
return this.rules.size;
|
||||||
|
}
|
||||||
|
|
||||||
|
registerRule(rule: string, processor: ClientRuleProcessor): void {
|
||||||
|
const normalizedRule = this.normalizeRule(rule);
|
||||||
|
if (this.rules.has(normalizedRule)) {
|
||||||
|
throw new ClientRuleRegistryError(
|
||||||
|
`Rule '${normalizedRule}' is already registered`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.rules.set(normalizedRule, processor);
|
||||||
|
}
|
||||||
|
|
||||||
|
hasRule(rule: string): boolean {
|
||||||
|
return this.rules.has(rule.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
dispatch(raw: string): boolean {
|
||||||
|
const parsed = parseRuleMessage(raw);
|
||||||
|
const processor = this.rules.get(parsed.ruleIdentifier);
|
||||||
|
if (!processor) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
processor(raw);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
getRules(): readonly string[] {
|
||||||
|
return [...this.rules.keys()];
|
||||||
|
}
|
||||||
|
|
||||||
|
private normalizeRule(rule: string): string {
|
||||||
|
const normalizedRule = rule.trim();
|
||||||
|
if (!normalizedRule) {
|
||||||
|
throw new ClientRuleRegistryError("Rule identifier must be a non-empty string");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (normalizedRule === BUILTIN_RULE) {
|
||||||
|
throw new ClientRuleRegistryError(
|
||||||
|
`Rule identifier '${BUILTIN_RULE}' is reserved`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
parseRuleMessage(`${normalizedRule}::probe`);
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof CodecError) {
|
||||||
|
throw new ClientRuleRegistryError(error.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
return normalizedRule;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createClientRuleRegistry(): ClientRuleRegistry {
|
||||||
|
return new YonexusClientRuleRegistry();
|
||||||
|
}
|
||||||
@@ -1,10 +1,17 @@
|
|||||||
import {
|
import {
|
||||||
YONEXUS_PROTOCOL_VERSION,
|
YONEXUS_PROTOCOL_VERSION,
|
||||||
|
buildAuthRequest,
|
||||||
|
buildHeartbeat,
|
||||||
buildHello,
|
buildHello,
|
||||||
buildPairConfirm,
|
buildPairConfirm,
|
||||||
|
CodecError,
|
||||||
|
createAuthRequestSigningInput,
|
||||||
decodeBuiltin,
|
decodeBuiltin,
|
||||||
encodeBuiltin,
|
encodeBuiltin,
|
||||||
|
encodeRuleMessage,
|
||||||
isBuiltinMessage,
|
isBuiltinMessage,
|
||||||
|
type AuthFailedPayload,
|
||||||
|
type BuiltinPayloadMap,
|
||||||
type HelloAckPayload,
|
type HelloAckPayload,
|
||||||
type PairFailedPayload,
|
type PairFailedPayload,
|
||||||
type PairRequestPayload,
|
type PairRequestPayload,
|
||||||
@@ -20,7 +27,9 @@ import {
|
|||||||
YonexusClientState,
|
YonexusClientState,
|
||||||
YonexusClientStateStore
|
YonexusClientStateStore
|
||||||
} from "./state.js";
|
} from "./state.js";
|
||||||
|
import { generateNonce, signMessage } from "../crypto/keypair.js";
|
||||||
import type { ClientConnectionState, ClientTransport } from "./transport.js";
|
import type { ClientConnectionState, ClientTransport } from "./transport.js";
|
||||||
|
import type { ClientRuleRegistry } from "./rules.js";
|
||||||
|
|
||||||
export type YonexusClientPhase =
|
export type YonexusClientPhase =
|
||||||
| "idle"
|
| "idle"
|
||||||
@@ -36,6 +45,8 @@ export interface YonexusClientRuntimeOptions {
|
|||||||
config: YonexusClientConfig;
|
config: YonexusClientConfig;
|
||||||
transport: ClientTransport;
|
transport: ClientTransport;
|
||||||
stateStore: YonexusClientStateStore;
|
stateStore: YonexusClientStateStore;
|
||||||
|
ruleRegistry?: ClientRuleRegistry;
|
||||||
|
onAuthenticated?: () => void;
|
||||||
now?: () => number;
|
now?: () => number;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -105,14 +116,24 @@ export class YonexusClientRuntime {
|
|||||||
|
|
||||||
async handleMessage(raw: string): Promise<void> {
|
async handleMessage(raw: string): Promise<void> {
|
||||||
if (raw === "heartbeat_tick") {
|
if (raw === "heartbeat_tick") {
|
||||||
|
await this.handleHeartbeatTick();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!isBuiltinMessage(raw)) {
|
if (!isBuiltinMessage(raw)) {
|
||||||
|
this.options.ruleRegistry?.dispatch(raw);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const envelope = decodeBuiltin(raw);
|
let envelope: TypedBuiltinEnvelope<keyof BuiltinPayloadMap>;
|
||||||
|
try {
|
||||||
|
envelope = decodeBuiltin(raw) as TypedBuiltinEnvelope<keyof BuiltinPayloadMap>;
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof CodecError) {
|
||||||
|
this.lastPairingFailure = error.message;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (envelope.type === "hello_ack") {
|
if (envelope.type === "hello_ack") {
|
||||||
this.handleHelloAck(envelope as TypedBuiltinEnvelope<"hello_ack">);
|
this.handleHelloAck(envelope as TypedBuiltinEnvelope<"hello_ack">);
|
||||||
return;
|
return;
|
||||||
@@ -134,18 +155,49 @@ export class YonexusClientRuntime {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (envelope.type === "auth_success") {
|
if (envelope.type === "auth_success") {
|
||||||
|
this.options.transport.markAuthenticated();
|
||||||
|
this.clientState = {
|
||||||
|
...this.clientState,
|
||||||
|
authenticatedAt: this.now(),
|
||||||
|
updatedAt: this.now()
|
||||||
|
};
|
||||||
|
await this.options.stateStore.save(this.clientState);
|
||||||
this.phase = "authenticated";
|
this.phase = "authenticated";
|
||||||
|
this.options.onAuthenticated?.();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (envelope.type === "auth_failed") {
|
||||||
|
await this.handleAuthFailed(envelope as TypedBuiltinEnvelope<"auth_failed">);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (envelope.type === "re_pair_required") {
|
||||||
|
await this.handleRePairRequired();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.lastPairingFailure = `unsupported_builtin:${String(envelope.type)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
handleTransportStateChange(state: ClientConnectionState): void {
|
handleTransportStateChange(state: ClientConnectionState): void {
|
||||||
if (state === "connected") {
|
if (state === "connected") {
|
||||||
this.sendHello();
|
// Reload state from disk before hello so that any secret written by an
|
||||||
|
// external process (e.g. a pairing script) is picked up on reconnect.
|
||||||
|
this.options.stateStore.load(this.options.config.identifier).then((fresh) => {
|
||||||
|
if (fresh) {
|
||||||
|
this.clientState = { ...this.clientState, ...fresh };
|
||||||
|
}
|
||||||
|
this.sendHello();
|
||||||
|
}).catch(() => {
|
||||||
|
// If reload fails, proceed with in-memory state
|
||||||
|
this.sendHello();
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (state === "disconnected") {
|
if (state === "disconnected") {
|
||||||
this.phase = "idle";
|
this.phase = hasClientSecret(this.clientState) ? "auth_required" : "idle";
|
||||||
|
this.pendingPairing = undefined;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -202,6 +254,7 @@ export class YonexusClientRuntime {
|
|||||||
break;
|
break;
|
||||||
case "auth_required":
|
case "auth_required":
|
||||||
this.phase = "auth_required";
|
this.phase = "auth_required";
|
||||||
|
void this.sendAuthRequest();
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
this.phase = "idle";
|
this.phase = "idle";
|
||||||
@@ -221,7 +274,10 @@ export class YonexusClientRuntime {
|
|||||||
adminNotification: payload.adminNotification
|
adminNotification: payload.adminNotification
|
||||||
};
|
};
|
||||||
this.lastPairingFailure = undefined;
|
this.lastPairingFailure = undefined;
|
||||||
this.phase = payload.adminNotification === "sent" ? "waiting_pair_confirm" : "pair_required";
|
// Always wait for the pairing code regardless of notification status.
|
||||||
|
// When adminNotification is "failed", the admin can retrieve the code
|
||||||
|
// via the server CLI command and deliver it through an alternate channel.
|
||||||
|
this.phase = "waiting_pair_confirm";
|
||||||
}
|
}
|
||||||
|
|
||||||
private async handlePairSuccess(envelope: TypedBuiltinEnvelope<"pair_success">): Promise<void> {
|
private async handlePairSuccess(envelope: TypedBuiltinEnvelope<"pair_success">): Promise<void> {
|
||||||
@@ -240,6 +296,7 @@ export class YonexusClientRuntime {
|
|||||||
this.pendingPairing = undefined;
|
this.pendingPairing = undefined;
|
||||||
this.lastPairingFailure = undefined;
|
this.lastPairingFailure = undefined;
|
||||||
this.phase = "auth_required";
|
this.phase = "auth_required";
|
||||||
|
await this.sendAuthRequest();
|
||||||
}
|
}
|
||||||
|
|
||||||
private handlePairFailed(envelope: TypedBuiltinEnvelope<"pair_failed">): void {
|
private handlePairFailed(envelope: TypedBuiltinEnvelope<"pair_failed">): void {
|
||||||
@@ -257,6 +314,160 @@ export class YonexusClientRuntime {
|
|||||||
|
|
||||||
this.phase = "waiting_pair_confirm";
|
this.phase = "waiting_pair_confirm";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async handleAuthFailed(
|
||||||
|
envelope: TypedBuiltinEnvelope<"auth_failed">
|
||||||
|
): Promise<void> {
|
||||||
|
const payload = envelope.payload as AuthFailedPayload | undefined;
|
||||||
|
if (!payload) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
payload.reason === "re_pair_required" ||
|
||||||
|
payload.reason === "nonce_collision" ||
|
||||||
|
payload.reason === "rate_limited"
|
||||||
|
) {
|
||||||
|
this.lastPairingFailure = payload.reason;
|
||||||
|
await this.resetTrustState();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.lastPairingFailure = payload.reason;
|
||||||
|
// If the server lost our session (race condition), re-announce via hello
|
||||||
|
// so the server creates a new session and we can retry auth.
|
||||||
|
if (payload.reason === "not_paired" && hasClientSecret(this.clientState)) {
|
||||||
|
this.sendHello();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.phase = "auth_required";
|
||||||
|
}
|
||||||
|
|
||||||
|
private async sendAuthRequest(): Promise<void> {
|
||||||
|
if (!this.options.transport.isConnected) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!this.clientState.secret || !this.clientState.privateKey) {
|
||||||
|
this.phase = "pair_required";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const proofTimestamp = this.now();
|
||||||
|
const nonce = generateNonce();
|
||||||
|
const signature = await signMessage(
|
||||||
|
this.clientState.privateKey,
|
||||||
|
createAuthRequestSigningInput({
|
||||||
|
secret: this.clientState.secret,
|
||||||
|
nonce,
|
||||||
|
proofTimestamp
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
this.options.transport.markAuthenticating();
|
||||||
|
this.options.transport.send(
|
||||||
|
encodeBuiltin(
|
||||||
|
buildAuthRequest(
|
||||||
|
{
|
||||||
|
identifier: this.options.config.identifier,
|
||||||
|
nonce,
|
||||||
|
proofTimestamp,
|
||||||
|
signature,
|
||||||
|
publicKey: this.clientState.publicKey
|
||||||
|
},
|
||||||
|
{ requestId: `auth_${proofTimestamp}_${nonce}`, timestamp: proofTimestamp }
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handleHeartbeatTick(): Promise<void> {
|
||||||
|
if (this.phase !== "authenticated" || !this.options.transport.isConnected) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.options.transport.send(
|
||||||
|
encodeBuiltin(
|
||||||
|
buildHeartbeat(
|
||||||
|
{
|
||||||
|
identifier: this.options.config.identifier,
|
||||||
|
status: "alive"
|
||||||
|
},
|
||||||
|
{ timestamp: this.now() }
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handleRePairRequired(): Promise<void> {
|
||||||
|
this.pendingPairing = undefined;
|
||||||
|
this.lastPairingFailure = "re_pair_required";
|
||||||
|
await this.resetTrustState();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async resetTrustState(): Promise<void> {
|
||||||
|
this.clientState = {
|
||||||
|
...this.clientState,
|
||||||
|
secret: undefined,
|
||||||
|
pairedAt: undefined,
|
||||||
|
authenticatedAt: undefined,
|
||||||
|
updatedAt: this.now()
|
||||||
|
};
|
||||||
|
|
||||||
|
await this.options.stateStore.save(this.clientState);
|
||||||
|
this.phase = "pair_required";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send a rule message to the server.
|
||||||
|
* Message must already conform to `${rule_identifier}::${message_content}`.
|
||||||
|
*
|
||||||
|
* @param message - The complete rule message with identifier and content
|
||||||
|
* @returns True if message was sent, false if not connected or not authenticated
|
||||||
|
*/
|
||||||
|
sendMessageToServer(message: string): boolean {
|
||||||
|
if (!this.options.transport.isConnected || !this.options.transport.isAuthenticated) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate the message is a properly formatted rule message
|
||||||
|
try {
|
||||||
|
if (message.startsWith("builtin::")) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const delimiterIndex = message.indexOf("::");
|
||||||
|
if (delimiterIndex === -1) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const ruleIdentifier = message.slice(0, delimiterIndex);
|
||||||
|
const content = message.slice(delimiterIndex + 2);
|
||||||
|
encodeRuleMessage(ruleIdentifier, content);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.options.transport.send(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send a rule message to the server using separate rule identifier and content.
|
||||||
|
*
|
||||||
|
* @param ruleIdentifier - The rule identifier (alphanumeric with underscores/hyphens)
|
||||||
|
* @param content - The message content
|
||||||
|
* @returns True if message was sent, false if not connected/authenticated or invalid format
|
||||||
|
*/
|
||||||
|
sendRuleMessage(ruleIdentifier: string, content: string): boolean {
|
||||||
|
if (!this.options.transport.isConnected || !this.options.transport.isAuthenticated) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const encoded = encodeRuleMessage(ruleIdentifier, content);
|
||||||
|
return this.options.transport.send(encoded);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createYonexusClientRuntime(
|
export function createYonexusClientRuntime(
|
||||||
|
|||||||
@@ -181,7 +181,8 @@ function assertClientStateShape(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!Number.isInteger(candidate.updatedAt) || candidate.updatedAt < 0) {
|
const updatedAt = candidate.updatedAt;
|
||||||
|
if (typeof updatedAt !== "number" || !Number.isInteger(updatedAt) || updatedAt < 0) {
|
||||||
throw new YonexusClientStateCorruptionError(
|
throw new YonexusClientStateCorruptionError(
|
||||||
`Client state file has invalid updatedAt value: ${filePath}`
|
`Client state file has invalid updatedAt value: ${filePath}`
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -18,6 +18,8 @@ export interface ClientTransport {
|
|||||||
connect(): Promise<void>;
|
connect(): Promise<void>;
|
||||||
disconnect(): void;
|
disconnect(): void;
|
||||||
send(message: string): boolean;
|
send(message: string): boolean;
|
||||||
|
markAuthenticated(): void;
|
||||||
|
markAuthenticating(): void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ClientMessageHandler = (message: string) => void;
|
export type ClientMessageHandler = (message: string) => void;
|
||||||
@@ -38,6 +40,7 @@ export class YonexusClientTransport implements ClientTransport {
|
|||||||
private reconnectAttempts = 0;
|
private reconnectAttempts = 0;
|
||||||
private reconnectTimer: NodeJS.Timeout | null = null;
|
private reconnectTimer: NodeJS.Timeout | null = null;
|
||||||
private heartbeatTimer: NodeJS.Timeout | null = null;
|
private heartbeatTimer: NodeJS.Timeout | null = null;
|
||||||
|
private shouldReconnect = false;
|
||||||
|
|
||||||
// Reconnect configuration
|
// Reconnect configuration
|
||||||
private readonly maxReconnectAttempts = 10;
|
private readonly maxReconnectAttempts = 10;
|
||||||
@@ -65,6 +68,8 @@ export class YonexusClientTransport implements ClientTransport {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this.shouldReconnect = true;
|
||||||
|
this.clearReconnectTimer();
|
||||||
this.setState("connecting");
|
this.setState("connecting");
|
||||||
const { mainHost } = this.options.config;
|
const { mainHost } = this.options.config;
|
||||||
|
|
||||||
@@ -73,12 +78,13 @@ export class YonexusClientTransport implements ClientTransport {
|
|||||||
this.ws = new WebSocket(mainHost);
|
this.ws = new WebSocket(mainHost);
|
||||||
|
|
||||||
const onOpen = () => {
|
const onOpen = () => {
|
||||||
|
this.ws?.off("error", onInitialError);
|
||||||
this.setState("connected");
|
this.setState("connected");
|
||||||
this.reconnectAttempts = 0; // Reset on successful connection
|
this.reconnectAttempts = 0; // Reset on successful connection
|
||||||
resolve();
|
resolve();
|
||||||
};
|
};
|
||||||
|
|
||||||
const onError = (error: Error) => {
|
const onInitialError = (error: Error) => {
|
||||||
this.setState("error");
|
this.setState("error");
|
||||||
if (this.options.onError) {
|
if (this.options.onError) {
|
||||||
this.options.onError(error);
|
this.options.onError(error);
|
||||||
@@ -87,7 +93,7 @@ export class YonexusClientTransport implements ClientTransport {
|
|||||||
};
|
};
|
||||||
|
|
||||||
this.ws.once("open", onOpen);
|
this.ws.once("open", onOpen);
|
||||||
this.ws.once("error", onError);
|
this.ws.once("error", onInitialError);
|
||||||
|
|
||||||
this.ws.on("message", (data) => {
|
this.ws.on("message", (data) => {
|
||||||
const message = data.toString("utf8");
|
const message = data.toString("utf8");
|
||||||
@@ -112,6 +118,7 @@ export class YonexusClientTransport implements ClientTransport {
|
|||||||
}
|
}
|
||||||
|
|
||||||
disconnect(): void {
|
disconnect(): void {
|
||||||
|
this.shouldReconnect = false;
|
||||||
this.clearReconnectTimer();
|
this.clearReconnectTimer();
|
||||||
this.stopHeartbeat();
|
this.stopHeartbeat();
|
||||||
|
|
||||||
@@ -151,18 +158,16 @@ export class YonexusClientTransport implements ClientTransport {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private handleDisconnect(code: number, reason: string): void {
|
private handleDisconnect(code: number, reason: string): void {
|
||||||
const wasAuthenticated = this._state === "authenticated";
|
|
||||||
this.ws = null;
|
this.ws = null;
|
||||||
this.stopHeartbeat();
|
this.stopHeartbeat();
|
||||||
this.setState("disconnected");
|
this.setState("disconnected");
|
||||||
|
|
||||||
// Don't reconnect if it was a normal close
|
// Don't reconnect if it was a normal close or caller explicitly stopped reconnects.
|
||||||
if (code === 1000) {
|
if (code === 1000 || !this.shouldReconnect) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Attempt reconnect if we were previously authenticated
|
if (this.reconnectAttempts < this.maxReconnectAttempts) {
|
||||||
if (wasAuthenticated && this.reconnectAttempts < this.maxReconnectAttempts) {
|
|
||||||
this.scheduleReconnect();
|
this.scheduleReconnect();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,6 +31,26 @@ export {
|
|||||||
type YonexusClientRuntimeState,
|
type YonexusClientRuntimeState,
|
||||||
type YonexusClientPhase
|
type YonexusClientPhase
|
||||||
} from "./core/runtime.js";
|
} from "./core/runtime.js";
|
||||||
|
export {
|
||||||
|
createClientRuleRegistry,
|
||||||
|
YonexusClientRuleRegistry,
|
||||||
|
ClientRuleRegistryError,
|
||||||
|
type ClientRuleRegistry,
|
||||||
|
type ClientRuleProcessor
|
||||||
|
} from "./core/rules.js";
|
||||||
|
|
||||||
|
import path from "node:path";
|
||||||
|
import { validateYonexusClientConfig } from "./core/config.js";
|
||||||
|
import { createYonexusClientStateStore } from "./core/state.js";
|
||||||
|
import { createClientTransport } from "./core/transport.js";
|
||||||
|
import { createYonexusClientRuntime, type YonexusClientRuntime } from "./core/runtime.js";
|
||||||
|
import { createClientRuleRegistry, YonexusClientRuleRegistry } from "./core/rules.js";
|
||||||
|
|
||||||
|
const _G = globalThis as Record<string, unknown>;
|
||||||
|
const _STARTED_KEY = "_yonexusClientStarted";
|
||||||
|
const _RUNTIME_KEY = "_yonexusClientRuntime";
|
||||||
|
const _REGISTRY_KEY = "_yonexusClientRegistry";
|
||||||
|
const _CALLBACKS_KEY = "_yonexusClientOnAuthCallbacks";
|
||||||
|
|
||||||
export interface YonexusClientPluginManifest {
|
export interface YonexusClientPluginManifest {
|
||||||
readonly name: "Yonexus.Client";
|
readonly name: "Yonexus.Client";
|
||||||
@@ -38,24 +58,76 @@ export interface YonexusClientPluginManifest {
|
|||||||
readonly description: string;
|
readonly description: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface YonexusClientPluginRuntime {
|
|
||||||
readonly hooks: readonly [];
|
|
||||||
readonly commands: readonly [];
|
|
||||||
readonly tools: readonly [];
|
|
||||||
}
|
|
||||||
|
|
||||||
const manifest: YonexusClientPluginManifest = {
|
const manifest: YonexusClientPluginManifest = {
|
||||||
name: "Yonexus.Client",
|
name: "Yonexus.Client",
|
||||||
version: "0.1.0",
|
version: "0.1.0",
|
||||||
description: "Yonexus client plugin for cross-instance OpenClaw communication"
|
description: "Yonexus client plugin for cross-instance OpenClaw communication"
|
||||||
};
|
};
|
||||||
|
|
||||||
export function createYonexusClientPlugin(): YonexusClientPluginRuntime {
|
export function createYonexusClientPlugin(api: { rootDir: string; pluginConfig: unknown }): void {
|
||||||
return {
|
// 1. Ensure shared state survives hot-reload — only initialise when absent
|
||||||
hooks: [],
|
if (!(_G[_REGISTRY_KEY] instanceof YonexusClientRuleRegistry)) {
|
||||||
commands: [],
|
_G[_REGISTRY_KEY] = createClientRuleRegistry();
|
||||||
tools: []
|
}
|
||||||
|
if (!Array.isArray(_G[_CALLBACKS_KEY])) {
|
||||||
|
_G[_CALLBACKS_KEY] = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const ruleRegistry = _G[_REGISTRY_KEY] as YonexusClientRuleRegistry;
|
||||||
|
const onAuthenticatedCallbacks = _G[_CALLBACKS_KEY] as Array<() => void>;
|
||||||
|
|
||||||
|
// 2. Refresh the cross-plugin API object every call so that sendRule / submitPairingCode
|
||||||
|
// closures always read the live runtime from globalThis.
|
||||||
|
_G["__yonexusClient"] = {
|
||||||
|
ruleRegistry,
|
||||||
|
sendRule: (ruleId: string, content: string): boolean =>
|
||||||
|
(_G[_RUNTIME_KEY] as YonexusClientRuntime | undefined)?.sendRuleMessage(ruleId, content) ?? false,
|
||||||
|
submitPairingCode: (code: string): boolean =>
|
||||||
|
(_G[_RUNTIME_KEY] as YonexusClientRuntime | undefined)?.submitPairingCode(code) ?? false,
|
||||||
|
onAuthenticated: onAuthenticatedCallbacks
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 3. Start the runtime only once — the globalThis flag survives hot-reload
|
||||||
|
if (_G[_STARTED_KEY]) return;
|
||||||
|
_G[_STARTED_KEY] = true;
|
||||||
|
|
||||||
|
const config = validateYonexusClientConfig(api.pluginConfig);
|
||||||
|
const stateStore = createYonexusClientStateStore(path.join(api.rootDir, "state.json"));
|
||||||
|
|
||||||
|
const transport = createClientTransport({
|
||||||
|
config,
|
||||||
|
onMessage: (msg) => {
|
||||||
|
(_G[_RUNTIME_KEY] as YonexusClientRuntime | undefined)?.handleMessage(msg).catch((err: unknown) => {
|
||||||
|
console.error("[yonexus-client] message handler error:", err);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onStateChange: (state) => {
|
||||||
|
(_G[_RUNTIME_KEY] as YonexusClientRuntime | undefined)?.handleTransportStateChange(state);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const runtime = createYonexusClientRuntime({
|
||||||
|
config,
|
||||||
|
transport,
|
||||||
|
stateStore,
|
||||||
|
ruleRegistry,
|
||||||
|
onAuthenticated: () => {
|
||||||
|
for (const cb of onAuthenticatedCallbacks) cb();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
_G[_RUNTIME_KEY] = runtime;
|
||||||
|
|
||||||
|
const shutdown = (): void => {
|
||||||
|
runtime.stop().catch((err: unknown) => {
|
||||||
|
console.error("[yonexus-client] shutdown error:", err);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
process.once("SIGTERM", shutdown);
|
||||||
|
process.once("SIGINT", shutdown);
|
||||||
|
|
||||||
|
runtime.start().catch((err: unknown) => {
|
||||||
|
console.error("[yonexus-client] failed to start:", err);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export default createYonexusClientPlugin;
|
export default createYonexusClientPlugin;
|
||||||
|
|||||||
@@ -1,13 +1,19 @@
|
|||||||
{
|
{
|
||||||
|
"id": "yonexus-client",
|
||||||
"name": "Yonexus.Client",
|
"name": "Yonexus.Client",
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"description": "Yonexus client plugin for cross-instance OpenClaw communication",
|
"description": "Yonexus client plugin for cross-instance OpenClaw communication",
|
||||||
"entry": "dist/plugin/index.js",
|
"entry": "./dist/Yonexus.Client/plugin/index.js",
|
||||||
"permissions": [],
|
"permissions": [],
|
||||||
"config": {
|
"configSchema": {
|
||||||
"mainHost": "",
|
"type": "object",
|
||||||
"identifier": "",
|
"additionalProperties": false,
|
||||||
"notifyBotToken": "",
|
"properties": {
|
||||||
"adminUserId": ""
|
"mainHost": { "type": "string" },
|
||||||
|
"identifier": { "type": "string" },
|
||||||
|
"notifyBotToken": { "type": "string" },
|
||||||
|
"adminUserId": { "type": "string" }
|
||||||
|
},
|
||||||
|
"required": ["mainHost", "identifier", "notifyBotToken", "adminUserId"]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
24
plugin/types/ws.d.ts
vendored
Normal file
24
plugin/types/ws.d.ts
vendored
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
declare module "ws" {
|
||||||
|
export type RawData = Buffer | ArrayBuffer | Buffer[] | string;
|
||||||
|
|
||||||
|
export class WebSocket {
|
||||||
|
static readonly OPEN: number;
|
||||||
|
constructor(url: string);
|
||||||
|
readonly readyState: number;
|
||||||
|
send(data: string): void;
|
||||||
|
close(code?: number, reason?: string): void;
|
||||||
|
terminate(): void;
|
||||||
|
on(event: "open", listener: () => void): this;
|
||||||
|
on(event: "message", listener: (data: RawData) => void): this;
|
||||||
|
on(event: "close", listener: (code: number, reason: Buffer) => void): this;
|
||||||
|
on(event: "error", listener: (error: Error) => void): this;
|
||||||
|
once(event: "open", listener: () => void): this;
|
||||||
|
once(event: "error", listener: (error: Error) => void): this;
|
||||||
|
off(event: "error", listener: (error: Error) => void): this;
|
||||||
|
removeAllListeners?(event?: string): this;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class WebSocketServer {
|
||||||
|
constructor(options: { host?: string; port: number });
|
||||||
|
}
|
||||||
|
}
|
||||||
2
protocol
2
protocol
Submodule protocol updated: 9232aa7c17...2611304084
@@ -29,6 +29,7 @@ if (mode === "install") {
|
|||||||
fs.rmSync(targetDir, { recursive: true, force: true });
|
fs.rmSync(targetDir, { recursive: true, force: true });
|
||||||
fs.cpSync(sourceDist, path.join(targetDir, "dist"), { recursive: true });
|
fs.cpSync(sourceDist, path.join(targetDir, "dist"), { recursive: true });
|
||||||
fs.copyFileSync(path.join(repoRoot, "plugin", "openclaw.plugin.json"), path.join(targetDir, "openclaw.plugin.json"));
|
fs.copyFileSync(path.join(repoRoot, "plugin", "openclaw.plugin.json"), path.join(targetDir, "openclaw.plugin.json"));
|
||||||
|
fs.copyFileSync(path.join(repoRoot, "package.json"), path.join(targetDir, "package.json"));
|
||||||
console.log(`Installed ${pluginName} to ${targetDir}`);
|
console.log(`Installed ${pluginName} to ${targetDir}`);
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
}
|
}
|
||||||
|
|||||||
592
tests/runtime-flow.test.ts
Normal file
592
tests/runtime-flow.test.ts
Normal file
@@ -0,0 +1,592 @@
|
|||||||
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
import {
|
||||||
|
buildAuthFailed,
|
||||||
|
buildAuthSuccess,
|
||||||
|
buildHelloAck,
|
||||||
|
buildPairFailed,
|
||||||
|
buildPairRequest,
|
||||||
|
buildPairSuccess,
|
||||||
|
buildRePairRequired,
|
||||||
|
decodeBuiltin,
|
||||||
|
encodeBuiltin,
|
||||||
|
type HelloEnvelopePayloadMap,
|
||||||
|
type PairConfirmPayload,
|
||||||
|
type TypedBuiltinEnvelope
|
||||||
|
} from "../../Yonexus.Protocol/src/index.js";
|
||||||
|
import { createYonexusClientRuntime } from "../plugin/core/runtime.js";
|
||||||
|
import type { YonexusClientState, YonexusClientStateStore } from "../plugin/core/state.js";
|
||||||
|
import type { ClientConnectionState, ClientTransport } from "../plugin/core/transport.js";
|
||||||
|
|
||||||
|
type SavedState = YonexusClientState;
|
||||||
|
|
||||||
|
function createInitialState(): YonexusClientState {
|
||||||
|
return {
|
||||||
|
identifier: "client-a",
|
||||||
|
updatedAt: 1_710_000_000
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createMockStateStore(initialState: YonexusClientState = createInitialState()) {
|
||||||
|
let state = { ...initialState };
|
||||||
|
const saved: SavedState[] = [];
|
||||||
|
|
||||||
|
const store: YonexusClientStateStore = {
|
||||||
|
filePath: "/tmp/yonexus-client-test.json",
|
||||||
|
load: vi.fn(async () => ({ ...state })),
|
||||||
|
save: vi.fn(async (next) => {
|
||||||
|
state = { ...next };
|
||||||
|
saved.push({ ...next });
|
||||||
|
})
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
store,
|
||||||
|
saved,
|
||||||
|
getState: () => ({ ...state })
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createMockTransport() {
|
||||||
|
let currentState: ClientConnectionState = "idle";
|
||||||
|
const sent: string[] = [];
|
||||||
|
|
||||||
|
const transport: ClientTransport = {
|
||||||
|
get state() {
|
||||||
|
return currentState;
|
||||||
|
},
|
||||||
|
get isConnected() {
|
||||||
|
return currentState !== "idle" && currentState !== "disconnected" && currentState !== "error";
|
||||||
|
},
|
||||||
|
get isAuthenticated() {
|
||||||
|
return currentState === "authenticated";
|
||||||
|
},
|
||||||
|
connect: vi.fn(async () => {
|
||||||
|
currentState = "connected";
|
||||||
|
}),
|
||||||
|
disconnect: vi.fn(() => {
|
||||||
|
currentState = "disconnected";
|
||||||
|
}),
|
||||||
|
send: vi.fn((message: string) => {
|
||||||
|
sent.push(message);
|
||||||
|
return true;
|
||||||
|
}),
|
||||||
|
markAuthenticated: vi.fn(() => {
|
||||||
|
currentState = "authenticated";
|
||||||
|
}),
|
||||||
|
markAuthenticating: vi.fn(() => {
|
||||||
|
currentState = "authenticating";
|
||||||
|
})
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
transport,
|
||||||
|
sent,
|
||||||
|
setState: (state: ClientConnectionState) => {
|
||||||
|
currentState = state;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("Yonexus.Client runtime flow", () => {
|
||||||
|
it("starts by loading state, ensuring keypair, and sending hello on connect", async () => {
|
||||||
|
const storeState = createMockStateStore();
|
||||||
|
const transportState = createMockTransport();
|
||||||
|
const runtime = createYonexusClientRuntime({
|
||||||
|
config: {
|
||||||
|
mainHost: "ws://localhost:8787",
|
||||||
|
identifier: "client-a",
|
||||||
|
notifyBotToken: "stub-token",
|
||||||
|
adminUserId: "admin-user"
|
||||||
|
},
|
||||||
|
transport: transportState.transport,
|
||||||
|
stateStore: storeState.store,
|
||||||
|
now: () => 1_710_000_000
|
||||||
|
});
|
||||||
|
|
||||||
|
await runtime.start();
|
||||||
|
runtime.handleTransportStateChange("connected");
|
||||||
|
|
||||||
|
expect(transportState.transport.connect).toHaveBeenCalled();
|
||||||
|
expect(storeState.saved.length).toBeGreaterThan(0);
|
||||||
|
expect(runtime.state.clientState.publicKey).toBeTypeOf("string");
|
||||||
|
expect(runtime.state.phase).toBe("awaiting_hello_ack");
|
||||||
|
|
||||||
|
const hello = decodeBuiltin(transportState.sent[0]);
|
||||||
|
expect(hello.type).toBe("hello");
|
||||||
|
expect(hello.payload).toMatchObject({
|
||||||
|
identifier: "client-a",
|
||||||
|
hasSecret: false,
|
||||||
|
hasKeyPair: true
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("SR-04: first run without credentials enters pair flow and does not require manual state bootstrap", async () => {
|
||||||
|
const storeState = createMockStateStore({
|
||||||
|
identifier: "client-a",
|
||||||
|
updatedAt: 1_710_000_000
|
||||||
|
});
|
||||||
|
const transportState = createMockTransport();
|
||||||
|
const runtime = createYonexusClientRuntime({
|
||||||
|
config: {
|
||||||
|
mainHost: "ws://localhost:8787",
|
||||||
|
identifier: "client-a",
|
||||||
|
notifyBotToken: "stub-token",
|
||||||
|
adminUserId: "admin-user"
|
||||||
|
},
|
||||||
|
transport: transportState.transport,
|
||||||
|
stateStore: storeState.store,
|
||||||
|
now: () => 1_710_000_000
|
||||||
|
});
|
||||||
|
|
||||||
|
await runtime.start();
|
||||||
|
runtime.handleTransportStateChange("connected");
|
||||||
|
|
||||||
|
const hello = decodeBuiltin(transportState.sent[0]);
|
||||||
|
expect(hello.type).toBe("hello");
|
||||||
|
expect(hello.payload).toMatchObject({
|
||||||
|
identifier: "client-a",
|
||||||
|
hasSecret: false,
|
||||||
|
hasKeyPair: true
|
||||||
|
});
|
||||||
|
|
||||||
|
await runtime.handleMessage(
|
||||||
|
encodeBuiltin(
|
||||||
|
buildHelloAck(
|
||||||
|
{
|
||||||
|
identifier: "client-a",
|
||||||
|
nextAction: "pair_required"
|
||||||
|
},
|
||||||
|
{ requestId: "req-first-run", timestamp: 1_710_000_000 }
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(runtime.state.phase).toBe("pair_required");
|
||||||
|
expect(runtime.state.clientState.secret).toBeUndefined();
|
||||||
|
expect(runtime.state.clientState.privateKey).toBeTypeOf("string");
|
||||||
|
expect(runtime.state.clientState.publicKey).toBeTypeOf("string");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("handles pair request, submits code, stores secret, and authenticates", async () => {
|
||||||
|
let now = 1_710_000_000;
|
||||||
|
const storeState = createMockStateStore();
|
||||||
|
const transportState = createMockTransport();
|
||||||
|
const runtime = createYonexusClientRuntime({
|
||||||
|
config: {
|
||||||
|
mainHost: "ws://localhost:8787",
|
||||||
|
identifier: "client-a",
|
||||||
|
notifyBotToken: "stub-token",
|
||||||
|
adminUserId: "admin-user"
|
||||||
|
},
|
||||||
|
transport: transportState.transport,
|
||||||
|
stateStore: storeState.store,
|
||||||
|
now: () => now
|
||||||
|
});
|
||||||
|
|
||||||
|
await runtime.start();
|
||||||
|
runtime.handleTransportStateChange("connected");
|
||||||
|
await runtime.handleMessage(
|
||||||
|
encodeBuiltin(
|
||||||
|
buildHelloAck(
|
||||||
|
{
|
||||||
|
identifier: "client-a",
|
||||||
|
nextAction: "pair_required"
|
||||||
|
},
|
||||||
|
{ requestId: "req-hello", timestamp: now }
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(runtime.state.phase).toBe("pair_required");
|
||||||
|
|
||||||
|
await runtime.handleMessage(
|
||||||
|
encodeBuiltin(
|
||||||
|
buildPairRequest(
|
||||||
|
{
|
||||||
|
identifier: "client-a",
|
||||||
|
expiresAt: now + 300,
|
||||||
|
ttlSeconds: 300,
|
||||||
|
adminNotification: "sent",
|
||||||
|
codeDelivery: "out_of_band"
|
||||||
|
},
|
||||||
|
{ requestId: "req-pair", timestamp: now }
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(runtime.state.phase).toBe("waiting_pair_confirm");
|
||||||
|
expect(runtime.state.pendingPairing).toMatchObject({
|
||||||
|
ttlSeconds: 300,
|
||||||
|
adminNotification: "sent"
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(runtime.submitPairingCode("PAIR-CODE-123", "req-pair-confirm")).toBe(true);
|
||||||
|
const pairConfirm = decodeBuiltin(transportState.sent.at(-1)!);
|
||||||
|
expect(pairConfirm.type).toBe("pair_confirm");
|
||||||
|
expect((pairConfirm.payload as PairConfirmPayload).pairingCode).toBe("PAIR-CODE-123");
|
||||||
|
|
||||||
|
now += 1;
|
||||||
|
await runtime.handleMessage(
|
||||||
|
encodeBuiltin(
|
||||||
|
buildPairSuccess(
|
||||||
|
{
|
||||||
|
identifier: "client-a",
|
||||||
|
secret: "issued-secret",
|
||||||
|
pairedAt: now
|
||||||
|
},
|
||||||
|
{ requestId: "req-pair-confirm", timestamp: now }
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(runtime.state.clientState.secret).toBe("issued-secret");
|
||||||
|
expect(runtime.state.phase).toBe("auth_required");
|
||||||
|
expect(transportState.transport.markAuthenticating).toHaveBeenCalled();
|
||||||
|
|
||||||
|
const authRequest = decodeBuiltin(transportState.sent.at(-1)!);
|
||||||
|
expect(authRequest.type).toBe("auth_request");
|
||||||
|
expect(authRequest.payload).toMatchObject({ identifier: "client-a" });
|
||||||
|
|
||||||
|
now += 1;
|
||||||
|
await runtime.handleMessage(
|
||||||
|
encodeBuiltin(
|
||||||
|
buildAuthSuccess(
|
||||||
|
{
|
||||||
|
identifier: "client-a",
|
||||||
|
authenticatedAt: now,
|
||||||
|
status: "online"
|
||||||
|
},
|
||||||
|
{ requestId: "req-auth", timestamp: now }
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(runtime.state.phase).toBe("authenticated");
|
||||||
|
expect(transportState.transport.markAuthenticated).toHaveBeenCalled();
|
||||||
|
expect(runtime.state.clientState.authenticatedAt).toBe(now);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("resets trust state on re-pair-required auth failures", async () => {
|
||||||
|
let now = 1_710_000_000;
|
||||||
|
const storeState = createMockStateStore({
|
||||||
|
identifier: "client-a",
|
||||||
|
publicKey: "pubkey",
|
||||||
|
privateKey: "privkey",
|
||||||
|
secret: "old-secret",
|
||||||
|
pairedAt: now - 10,
|
||||||
|
authenticatedAt: now - 5,
|
||||||
|
updatedAt: now - 5
|
||||||
|
});
|
||||||
|
const transportState = createMockTransport();
|
||||||
|
transportState.setState("connected");
|
||||||
|
const runtime = createYonexusClientRuntime({
|
||||||
|
config: {
|
||||||
|
mainHost: "ws://localhost:8787",
|
||||||
|
identifier: "client-a",
|
||||||
|
notifyBotToken: "stub-token",
|
||||||
|
adminUserId: "admin-user"
|
||||||
|
},
|
||||||
|
transport: transportState.transport,
|
||||||
|
stateStore: storeState.store,
|
||||||
|
now: () => now
|
||||||
|
});
|
||||||
|
|
||||||
|
await runtime.start();
|
||||||
|
await runtime.handleMessage(
|
||||||
|
encodeBuiltin(
|
||||||
|
buildAuthFailed(
|
||||||
|
{
|
||||||
|
identifier: "client-a",
|
||||||
|
reason: "nonce_collision"
|
||||||
|
},
|
||||||
|
{ requestId: "req-auth", timestamp: now }
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(runtime.state.phase).toBe("pair_required");
|
||||||
|
expect(runtime.state.lastPairingFailure).toBe("nonce_collision");
|
||||||
|
expect(runtime.state.clientState.secret).toBeUndefined();
|
||||||
|
|
||||||
|
now += 1;
|
||||||
|
await runtime.handleMessage(
|
||||||
|
encodeBuiltin(
|
||||||
|
buildRePairRequired(
|
||||||
|
{
|
||||||
|
identifier: "client-a",
|
||||||
|
reason: "rate_limited"
|
||||||
|
},
|
||||||
|
{ requestId: "req-repair", timestamp: now }
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(runtime.state.phase).toBe("pair_required");
|
||||||
|
expect(runtime.state.lastPairingFailure).toBe("re_pair_required");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("SR-03: restarts with stored credentials and resumes at auth flow without re-pairing", async () => {
|
||||||
|
const now = 1_710_000_000;
|
||||||
|
const { generateKeyPair } = await import("../plugin/crypto/keypair.js");
|
||||||
|
const keyPair = await generateKeyPair();
|
||||||
|
const storeState = createMockStateStore({
|
||||||
|
identifier: "client-a",
|
||||||
|
publicKey: keyPair.publicKey,
|
||||||
|
privateKey: keyPair.privateKey,
|
||||||
|
secret: "stored-secret",
|
||||||
|
pairedAt: now - 20,
|
||||||
|
authenticatedAt: now - 10,
|
||||||
|
updatedAt: now - 10
|
||||||
|
});
|
||||||
|
const transportState = createMockTransport();
|
||||||
|
const runtime = createYonexusClientRuntime({
|
||||||
|
config: {
|
||||||
|
mainHost: "ws://localhost:8787",
|
||||||
|
identifier: "client-a",
|
||||||
|
notifyBotToken: "stub-token",
|
||||||
|
adminUserId: "admin-user"
|
||||||
|
},
|
||||||
|
transport: transportState.transport,
|
||||||
|
stateStore: storeState.store,
|
||||||
|
now: () => now
|
||||||
|
});
|
||||||
|
|
||||||
|
await runtime.start();
|
||||||
|
runtime.handleTransportStateChange("connected");
|
||||||
|
|
||||||
|
const hello = decodeBuiltin(transportState.sent[0]);
|
||||||
|
expect(hello.type).toBe("hello");
|
||||||
|
expect(hello.payload).toMatchObject({
|
||||||
|
identifier: "client-a",
|
||||||
|
hasSecret: true,
|
||||||
|
hasKeyPair: true,
|
||||||
|
publicKey: keyPair.publicKey
|
||||||
|
});
|
||||||
|
|
||||||
|
await runtime.handleMessage(
|
||||||
|
encodeBuiltin(
|
||||||
|
buildHelloAck(
|
||||||
|
{
|
||||||
|
identifier: "client-a",
|
||||||
|
nextAction: "auth_required"
|
||||||
|
},
|
||||||
|
{ requestId: "req-restart-hello", timestamp: now }
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(runtime.state.phase).toBe("auth_required");
|
||||||
|
|
||||||
|
const authRequest = decodeBuiltin(transportState.sent.at(-1)!);
|
||||||
|
expect(authRequest.type).toBe("auth_request");
|
||||||
|
expect(authRequest.payload).toMatchObject({ identifier: "client-a" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sends heartbeat only when authenticated and connected", async () => {
|
||||||
|
const storeState = createMockStateStore({
|
||||||
|
identifier: "client-a",
|
||||||
|
publicKey: "pubkey",
|
||||||
|
privateKey: "privkey",
|
||||||
|
secret: "secret",
|
||||||
|
pairedAt: 1_709_999_990,
|
||||||
|
authenticatedAt: 1_709_999_995,
|
||||||
|
updatedAt: 1_709_999_995
|
||||||
|
});
|
||||||
|
const transportState = createMockTransport();
|
||||||
|
transportState.setState("authenticated");
|
||||||
|
const runtime = createYonexusClientRuntime({
|
||||||
|
config: {
|
||||||
|
mainHost: "ws://localhost:8787",
|
||||||
|
identifier: "client-a",
|
||||||
|
notifyBotToken: "stub-token",
|
||||||
|
adminUserId: "admin-user"
|
||||||
|
},
|
||||||
|
transport: transportState.transport,
|
||||||
|
stateStore: storeState.store,
|
||||||
|
now: () => 1_710_000_000
|
||||||
|
});
|
||||||
|
|
||||||
|
await runtime.start();
|
||||||
|
|
||||||
|
await runtime.handleMessage("heartbeat_tick");
|
||||||
|
expect(transportState.sent).toHaveLength(0);
|
||||||
|
|
||||||
|
await runtime.handleMessage(
|
||||||
|
encodeBuiltin(
|
||||||
|
buildAuthSuccess(
|
||||||
|
{
|
||||||
|
identifier: "client-a",
|
||||||
|
authenticatedAt: 1_710_000_000,
|
||||||
|
status: "online"
|
||||||
|
},
|
||||||
|
{ timestamp: 1_710_000_000 }
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
await runtime.handleMessage("heartbeat_tick");
|
||||||
|
const heartbeat = decodeBuiltin(transportState.sent.at(-1)!);
|
||||||
|
expect(heartbeat.type).toBe("heartbeat");
|
||||||
|
expect(heartbeat.payload).toMatchObject({ identifier: "client-a", status: "alive" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("tracks pairing failures without wiping pending session for retryable reasons", async () => {
|
||||||
|
const storeState = createMockStateStore();
|
||||||
|
const transportState = createMockTransport();
|
||||||
|
const runtime = createYonexusClientRuntime({
|
||||||
|
config: {
|
||||||
|
mainHost: "ws://localhost:8787",
|
||||||
|
identifier: "client-a",
|
||||||
|
notifyBotToken: "stub-token",
|
||||||
|
adminUserId: "admin-user"
|
||||||
|
},
|
||||||
|
transport: transportState.transport,
|
||||||
|
stateStore: storeState.store,
|
||||||
|
now: () => 1_710_000_000
|
||||||
|
});
|
||||||
|
|
||||||
|
await runtime.start();
|
||||||
|
runtime.handleTransportStateChange("connected");
|
||||||
|
await runtime.handleMessage(
|
||||||
|
encodeBuiltin(
|
||||||
|
buildPairRequest(
|
||||||
|
{
|
||||||
|
identifier: "client-a",
|
||||||
|
expiresAt: 1_710_000_300,
|
||||||
|
ttlSeconds: 300,
|
||||||
|
adminNotification: "sent",
|
||||||
|
codeDelivery: "out_of_band"
|
||||||
|
},
|
||||||
|
{ timestamp: 1_710_000_000 }
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
await runtime.handleMessage(
|
||||||
|
encodeBuiltin(
|
||||||
|
buildPairFailed(
|
||||||
|
{
|
||||||
|
identifier: "client-a",
|
||||||
|
reason: "invalid_code"
|
||||||
|
},
|
||||||
|
{ timestamp: 1_710_000_001 }
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(runtime.state.phase).toBe("waiting_pair_confirm");
|
||||||
|
expect(runtime.state.pendingPairing).toBeDefined();
|
||||||
|
expect(runtime.state.lastPairingFailure).toBe("invalid_code");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("PF-10: restart during pending pairing resumes waiting for out-of-band code", async () => {
|
||||||
|
const now = 1_710_000_000;
|
||||||
|
const storeState = createMockStateStore({
|
||||||
|
identifier: "client-a",
|
||||||
|
updatedAt: now
|
||||||
|
});
|
||||||
|
|
||||||
|
const firstTransportState = createMockTransport();
|
||||||
|
const firstRuntime = createYonexusClientRuntime({
|
||||||
|
config: {
|
||||||
|
mainHost: "ws://localhost:8787",
|
||||||
|
identifier: "client-a",
|
||||||
|
notifyBotToken: "stub-token",
|
||||||
|
adminUserId: "admin-user"
|
||||||
|
},
|
||||||
|
transport: firstTransportState.transport,
|
||||||
|
stateStore: storeState.store,
|
||||||
|
now: () => now
|
||||||
|
});
|
||||||
|
|
||||||
|
await firstRuntime.start();
|
||||||
|
firstRuntime.handleTransportStateChange("connected");
|
||||||
|
await firstRuntime.handleMessage(
|
||||||
|
encodeBuiltin(
|
||||||
|
buildPairRequest(
|
||||||
|
{
|
||||||
|
identifier: "client-a",
|
||||||
|
expiresAt: now + 300,
|
||||||
|
ttlSeconds: 300,
|
||||||
|
adminNotification: "sent",
|
||||||
|
codeDelivery: "out_of_band"
|
||||||
|
},
|
||||||
|
{ requestId: "req-pair", timestamp: now }
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(firstRuntime.state.phase).toBe("waiting_pair_confirm");
|
||||||
|
expect(firstRuntime.state.pendingPairing).toMatchObject({
|
||||||
|
expiresAt: now + 300,
|
||||||
|
ttlSeconds: 300,
|
||||||
|
adminNotification: "sent"
|
||||||
|
});
|
||||||
|
|
||||||
|
await firstRuntime.stop();
|
||||||
|
|
||||||
|
const secondTransportState = createMockTransport();
|
||||||
|
const secondRuntime = createYonexusClientRuntime({
|
||||||
|
config: {
|
||||||
|
mainHost: "ws://localhost:8787",
|
||||||
|
identifier: "client-a",
|
||||||
|
notifyBotToken: "stub-token",
|
||||||
|
adminUserId: "admin-user"
|
||||||
|
},
|
||||||
|
transport: secondTransportState.transport,
|
||||||
|
stateStore: storeState.store,
|
||||||
|
now: () => now + 5
|
||||||
|
});
|
||||||
|
|
||||||
|
await secondRuntime.start();
|
||||||
|
secondRuntime.handleTransportStateChange("connected");
|
||||||
|
|
||||||
|
const hello = decodeBuiltin(secondTransportState.sent[0]);
|
||||||
|
expect(hello.type).toBe("hello");
|
||||||
|
expect(hello.payload).toMatchObject({
|
||||||
|
identifier: "client-a",
|
||||||
|
hasSecret: false,
|
||||||
|
hasKeyPair: true
|
||||||
|
});
|
||||||
|
|
||||||
|
await secondRuntime.handleMessage(
|
||||||
|
encodeBuiltin(
|
||||||
|
buildHelloAck(
|
||||||
|
{
|
||||||
|
identifier: "client-a",
|
||||||
|
nextAction: "waiting_pair_confirm"
|
||||||
|
},
|
||||||
|
{ requestId: "req-hello-resume", timestamp: now + 5 }
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
await secondRuntime.handleMessage(
|
||||||
|
encodeBuiltin(
|
||||||
|
buildPairRequest(
|
||||||
|
{
|
||||||
|
identifier: "client-a",
|
||||||
|
expiresAt: now + 300,
|
||||||
|
ttlSeconds: 295,
|
||||||
|
adminNotification: "sent",
|
||||||
|
codeDelivery: "out_of_band"
|
||||||
|
},
|
||||||
|
{ requestId: "req-pair-resume", timestamp: now + 5 }
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(secondRuntime.state.phase).toBe("waiting_pair_confirm");
|
||||||
|
expect(secondRuntime.state.pendingPairing).toMatchObject({
|
||||||
|
expiresAt: now + 300,
|
||||||
|
ttlSeconds: 295,
|
||||||
|
adminNotification: "sent"
|
||||||
|
});
|
||||||
|
expect(secondRuntime.submitPairingCode("PAIR-CODE-123", "req-pair-resume")).toBe(true);
|
||||||
|
|
||||||
|
const pairConfirm = decodeBuiltin(secondTransportState.sent.at(-1)!);
|
||||||
|
expect(pairConfirm.type).toBe("pair_confirm");
|
||||||
|
expect((pairConfirm.payload as PairConfirmPayload).pairingCode).toBe("PAIR-CODE-123");
|
||||||
|
});
|
||||||
|
});
|
||||||
132
tests/state-and-rules.test.ts
Normal file
132
tests/state-and-rules.test.ts
Normal file
@@ -0,0 +1,132 @@
|
|||||||
|
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
|
||||||
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
import { createClientRuleRegistry, ClientRuleRegistryError } from "../plugin/core/rules.js";
|
||||||
|
import {
|
||||||
|
createInitialClientState,
|
||||||
|
createYonexusClientStateStore,
|
||||||
|
ensureClientKeyPair,
|
||||||
|
hasClientKeyPair,
|
||||||
|
hasClientSecret,
|
||||||
|
loadYonexusClientState,
|
||||||
|
saveYonexusClientState,
|
||||||
|
YonexusClientStateCorruptionError,
|
||||||
|
type YonexusClientState
|
||||||
|
} from "../plugin/core/state.js";
|
||||||
|
import { signMessage, verifySignature } from "../plugin/crypto/keypair.js";
|
||||||
|
|
||||||
|
const tempDirs: string[] = [];
|
||||||
|
|
||||||
|
afterEach(async () => {
|
||||||
|
await Promise.all(
|
||||||
|
tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true }))
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
async function createTempStatePath(): Promise<string> {
|
||||||
|
const dir = await mkdtemp(join(tmpdir(), "yonexus-client-test-"));
|
||||||
|
tempDirs.push(dir);
|
||||||
|
return join(dir, "state.json");
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("Yonexus.Client state store", () => {
|
||||||
|
it("creates minimal initial state when the file does not exist", async () => {
|
||||||
|
const filePath = await createTempStatePath();
|
||||||
|
|
||||||
|
const state = await loadYonexusClientState(filePath, "client-a");
|
||||||
|
|
||||||
|
expect(state.identifier).toBe("client-a");
|
||||||
|
expect(hasClientSecret(state)).toBe(false);
|
||||||
|
expect(hasClientKeyPair(state)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("persists and reloads local trust material", async () => {
|
||||||
|
const filePath = await createTempStatePath();
|
||||||
|
const state: YonexusClientState = {
|
||||||
|
...createInitialClientState("client-a"),
|
||||||
|
publicKey: "pubkey",
|
||||||
|
privateKey: "privkey",
|
||||||
|
secret: "secret-value",
|
||||||
|
pairedAt: 1_710_000_000,
|
||||||
|
authenticatedAt: 1_710_000_100,
|
||||||
|
updatedAt: 1_710_000_101
|
||||||
|
};
|
||||||
|
|
||||||
|
await saveYonexusClientState(filePath, state);
|
||||||
|
const reloaded = await loadYonexusClientState(filePath, "client-a");
|
||||||
|
|
||||||
|
expect(reloaded).toEqual(state);
|
||||||
|
const raw = JSON.parse(await readFile(filePath, "utf8")) as { version: number };
|
||||||
|
expect(raw.version).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("generates and persists an Ed25519 keypair only once", async () => {
|
||||||
|
const filePath = await createTempStatePath();
|
||||||
|
const store = createYonexusClientStateStore(filePath);
|
||||||
|
const initial = createInitialClientState("client-a");
|
||||||
|
|
||||||
|
const first = await ensureClientKeyPair(initial, store);
|
||||||
|
expect(first.generated).toBe(true);
|
||||||
|
expect(hasClientKeyPair(first.state)).toBe(true);
|
||||||
|
|
||||||
|
const signature = await signMessage(first.state.privateKey!, "hello yonexus");
|
||||||
|
await expect(
|
||||||
|
verifySignature(first.state.publicKey!, "hello yonexus", signature)
|
||||||
|
).resolves.toBe(true);
|
||||||
|
|
||||||
|
const second = await ensureClientKeyPair(first.state, store);
|
||||||
|
expect(second.generated).toBe(false);
|
||||||
|
expect(second.state.privateKey).toBe(first.state.privateKey);
|
||||||
|
expect(second.state.publicKey).toBe(first.state.publicKey);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("SR-06: raises a corruption error for malformed client state files", async () => {
|
||||||
|
const filePath = await createTempStatePath();
|
||||||
|
await saveYonexusClientState(filePath, {
|
||||||
|
...createInitialClientState("client-a"),
|
||||||
|
updatedAt: 1_710_000_000
|
||||||
|
});
|
||||||
|
|
||||||
|
await writeFile(filePath, '{"version":1,"identifier":"client-a","updatedAt":"bad"}\n', "utf8");
|
||||||
|
|
||||||
|
await expect(loadYonexusClientState(filePath, "client-a")).rejects.toBeInstanceOf(
|
||||||
|
YonexusClientStateCorruptionError
|
||||||
|
);
|
||||||
|
await expect(loadYonexusClientState(filePath, "client-a")).rejects.toThrow(
|
||||||
|
"invalid updatedAt"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Yonexus.Client rule registry", () => {
|
||||||
|
it("dispatches exact-match rule messages to the registered processor", () => {
|
||||||
|
const registry = createClientRuleRegistry();
|
||||||
|
const processor = vi.fn();
|
||||||
|
registry.registerRule("chat_sync", processor);
|
||||||
|
|
||||||
|
const handled = registry.dispatch("chat_sync::{\"body\":\"hello\"}");
|
||||||
|
|
||||||
|
expect(handled).toBe(true);
|
||||||
|
expect(processor).toHaveBeenCalledWith("chat_sync::{\"body\":\"hello\"}");
|
||||||
|
expect(registry.getRules()).toEqual(["chat_sync"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects reserved and duplicate registrations", () => {
|
||||||
|
const registry = createClientRuleRegistry();
|
||||||
|
registry.registerRule("chat_sync", () => undefined);
|
||||||
|
|
||||||
|
expect(() => registry.registerRule("builtin", () => undefined)).toThrow(ClientRuleRegistryError);
|
||||||
|
expect(() => registry.registerRule("chat_sync", () => undefined)).toThrow(
|
||||||
|
"Rule 'chat_sync' is already registered"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns false when no processor matches a message", () => {
|
||||||
|
const registry = createClientRuleRegistry();
|
||||||
|
|
||||||
|
expect(registry.dispatch("chat_sync::{\"body\":\"hello\"}")).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
412
tests/state-auth-heartbeat.test.ts
Normal file
412
tests/state-auth-heartbeat.test.ts
Normal file
@@ -0,0 +1,412 @@
|
|||||||
|
import { mkdtemp, readFile, rm } from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
|
||||||
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
import { createClientRuleRegistry, ClientRuleRegistryError } from "../plugin/core/rules.js";
|
||||||
|
import {
|
||||||
|
createInitialClientState,
|
||||||
|
createYonexusClientStateStore,
|
||||||
|
ensureClientKeyPair,
|
||||||
|
hasClientKeyPair,
|
||||||
|
hasClientSecret,
|
||||||
|
loadYonexusClientState,
|
||||||
|
saveYonexusClientState,
|
||||||
|
type YonexusClientState
|
||||||
|
} from "../plugin/core/state.js";
|
||||||
|
import { signMessage, verifySignature } from "../plugin/crypto/keypair.js";
|
||||||
|
|
||||||
|
// Inline protocol helpers (to avoid submodule dependency in tests)
|
||||||
|
function createAuthRequestSigningInput(input: {
|
||||||
|
secret: string;
|
||||||
|
nonce: string;
|
||||||
|
proofTimestamp: number;
|
||||||
|
}): string {
|
||||||
|
return JSON.stringify({
|
||||||
|
secret: input.secret,
|
||||||
|
nonce: input.nonce,
|
||||||
|
timestamp: input.proofTimestamp
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function isValidAuthNonce(nonce: string): boolean {
|
||||||
|
return /^[A-Za-z0-9_-]{24}$/.test(nonce);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isTimestampFresh(
|
||||||
|
proofTimestamp: number,
|
||||||
|
now: number,
|
||||||
|
maxDriftSeconds: number = 10
|
||||||
|
): { ok: true } | { ok: false; reason: "stale_timestamp" | "future_timestamp" } {
|
||||||
|
const drift = proofTimestamp - now;
|
||||||
|
if (Math.abs(drift) < maxDriftSeconds) {
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
reason: drift < 0 ? "stale_timestamp" : "future_timestamp"
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const tempDirs: string[] = [];
|
||||||
|
|
||||||
|
afterEach(async () => {
|
||||||
|
await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
|
||||||
|
});
|
||||||
|
|
||||||
|
async function createTempStatePath(): Promise<string> {
|
||||||
|
const dir = await mkdtemp(join(tmpdir(), "yonexus-client-test-"));
|
||||||
|
tempDirs.push(dir);
|
||||||
|
return join(dir, "state.json");
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("Yonexus.Client state store", () => {
|
||||||
|
it("creates minimal initial state when the file does not exist", async () => {
|
||||||
|
const filePath = await createTempStatePath();
|
||||||
|
|
||||||
|
const state = await loadYonexusClientState(filePath, "client-a");
|
||||||
|
|
||||||
|
expect(state.identifier).toBe("client-a");
|
||||||
|
expect(hasClientSecret(state)).toBe(false);
|
||||||
|
expect(hasClientKeyPair(state)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("persists and reloads local trust material", async () => {
|
||||||
|
const filePath = await createTempStatePath();
|
||||||
|
const state: YonexusClientState = {
|
||||||
|
...createInitialClientState("client-a"),
|
||||||
|
publicKey: "pubkey",
|
||||||
|
privateKey: "privkey",
|
||||||
|
secret: "secret-value",
|
||||||
|
pairedAt: 1_710_000_000,
|
||||||
|
authenticatedAt: 1_710_000_100,
|
||||||
|
updatedAt: 1_710_000_101
|
||||||
|
};
|
||||||
|
|
||||||
|
await saveYonexusClientState(filePath, state);
|
||||||
|
const reloaded = await loadYonexusClientState(filePath, "client-a");
|
||||||
|
|
||||||
|
expect(reloaded).toEqual(state);
|
||||||
|
const raw = JSON.parse(await readFile(filePath, "utf8")) as { version: number };
|
||||||
|
expect(raw.version).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("generates and persists an Ed25519 keypair only once", async () => {
|
||||||
|
const filePath = await createTempStatePath();
|
||||||
|
const store = createYonexusClientStateStore(filePath);
|
||||||
|
const initial = createInitialClientState("client-a");
|
||||||
|
|
||||||
|
const first = await ensureClientKeyPair(initial, store);
|
||||||
|
expect(first.generated).toBe(true);
|
||||||
|
expect(hasClientKeyPair(first.state)).toBe(true);
|
||||||
|
|
||||||
|
const signature = await signMessage(first.state.privateKey!, "hello yonexus");
|
||||||
|
await expect(verifySignature(first.state.publicKey!, "hello yonexus", signature)).resolves.toBe(
|
||||||
|
true
|
||||||
|
);
|
||||||
|
|
||||||
|
const second = await ensureClientKeyPair(first.state, store);
|
||||||
|
expect(second.generated).toBe(false);
|
||||||
|
expect(second.state.privateKey).toBe(first.state.privateKey);
|
||||||
|
expect(second.state.publicKey).toBe(first.state.publicKey);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Yonexus.Client rule registry", () => {
|
||||||
|
it("dispatches exact-match rule messages to the registered processor", () => {
|
||||||
|
const registry = createClientRuleRegistry();
|
||||||
|
const processor = vi.fn();
|
||||||
|
registry.registerRule("chat_sync", processor);
|
||||||
|
|
||||||
|
const handled = registry.dispatch("chat_sync::{\"body\":\"hello\"}");
|
||||||
|
|
||||||
|
expect(handled).toBe(true);
|
||||||
|
expect(processor).toHaveBeenCalledWith("chat_sync::{\"body\":\"hello\"}");
|
||||||
|
expect(registry.getRules()).toEqual(["chat_sync"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects reserved and duplicate registrations", () => {
|
||||||
|
const registry = createClientRuleRegistry();
|
||||||
|
registry.registerRule("chat_sync", () => undefined);
|
||||||
|
|
||||||
|
expect(() => registry.registerRule("builtin", () => undefined)).toThrow(ClientRuleRegistryError);
|
||||||
|
expect(() => registry.registerRule("chat_sync", () => undefined)).toThrow(
|
||||||
|
"Rule 'chat_sync' is already registered"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns false when no processor matches a message", () => {
|
||||||
|
const registry = createClientRuleRegistry();
|
||||||
|
|
||||||
|
expect(registry.dispatch("chat_sync::{\"body\":\"hello\"}")).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Yonexus.Client auth flow", () => {
|
||||||
|
it("constructs valid auth request signing input", () => {
|
||||||
|
const input = createAuthRequestSigningInput({
|
||||||
|
secret: "my-secret",
|
||||||
|
nonce: "RANDOM24CHARSTRINGX001",
|
||||||
|
proofTimestamp: 1_710_000_000
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(input).toBe(
|
||||||
|
'{"secret":"my-secret","nonce":"RANDOM24CHARSTRINGX001","timestamp":1710000000}'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("validates nonce format correctly", () => {
|
||||||
|
expect(isValidAuthNonce("RANDOM24CHARSTRINGX00001")).toBe(true);
|
||||||
|
expect(isValidAuthNonce("RANDOM24CHARSTRINGX00")).toBe(false);
|
||||||
|
expect(isValidAuthNonce("RANDOM24CHARSTRINGX0001")).toBe(false);
|
||||||
|
expect(isValidAuthNonce("invalid_nonce_with_!@#")).toBe(false);
|
||||||
|
expect(isValidAuthNonce("")).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("validates timestamp freshness", () => {
|
||||||
|
const now = 1_710_000_000;
|
||||||
|
|
||||||
|
expect(isTimestampFresh(now, now)).toEqual({ ok: true });
|
||||||
|
expect(isTimestampFresh(now - 5, now)).toEqual({ ok: true });
|
||||||
|
expect(isTimestampFresh(now + 5, now)).toEqual({ ok: true });
|
||||||
|
|
||||||
|
expect(isTimestampFresh(now - 15, now)).toEqual({ ok: false, reason: "stale_timestamp" });
|
||||||
|
expect(isTimestampFresh(now + 15, now)).toEqual({ ok: false, reason: "future_timestamp" });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Yonexus.Client phase state machine", () => {
|
||||||
|
it("transitions from idle to connecting to connected", () => {
|
||||||
|
const sm = createClientStateMachine();
|
||||||
|
|
||||||
|
expect(sm.getState()).toBe("idle");
|
||||||
|
|
||||||
|
sm.transition("connect");
|
||||||
|
expect(sm.getState()).toBe("connecting");
|
||||||
|
|
||||||
|
sm.transition("connected");
|
||||||
|
expect(sm.getState()).toBe("connected");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("handles pairing required flow", () => {
|
||||||
|
const sm = createClientStateMachine();
|
||||||
|
|
||||||
|
sm.transition("connect");
|
||||||
|
sm.transition("connected");
|
||||||
|
sm.transition("pair_required");
|
||||||
|
expect(sm.getState()).toBe("pairing_required");
|
||||||
|
|
||||||
|
sm.transition("pairing_started");
|
||||||
|
expect(sm.getState()).toBe("pairing_pending");
|
||||||
|
|
||||||
|
sm.transition("pair_success");
|
||||||
|
expect(sm.getState()).toBe("authenticating");
|
||||||
|
|
||||||
|
sm.transition("auth_success");
|
||||||
|
expect(sm.getState()).toBe("authenticated");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("handles re-pair required from authenticated", () => {
|
||||||
|
const sm = createClientStateMachine();
|
||||||
|
|
||||||
|
sm.transition("connect");
|
||||||
|
sm.transition("connected");
|
||||||
|
sm.transition("pair_required");
|
||||||
|
sm.transition("pairing_started");
|
||||||
|
sm.transition("pair_success");
|
||||||
|
sm.transition("auth_success");
|
||||||
|
expect(sm.getState()).toBe("authenticated");
|
||||||
|
|
||||||
|
sm.transition("re_pair_required");
|
||||||
|
expect(sm.getState()).toBe("pairing_required");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("handles disconnect and reconnect", () => {
|
||||||
|
const sm = createClientStateMachine();
|
||||||
|
|
||||||
|
sm.transition("connect");
|
||||||
|
sm.transition("connected");
|
||||||
|
sm.transition("auth_required");
|
||||||
|
sm.transition("auth_success");
|
||||||
|
expect(sm.getState()).toBe("authenticated");
|
||||||
|
|
||||||
|
sm.transition("disconnect");
|
||||||
|
expect(sm.getState()).toBe("reconnecting");
|
||||||
|
|
||||||
|
sm.transition("connect");
|
||||||
|
expect(sm.getState()).toBe("connecting");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("emits state change events", () => {
|
||||||
|
const sm = createClientStateMachine();
|
||||||
|
const listener = vi.fn();
|
||||||
|
|
||||||
|
sm.on("stateChange", listener);
|
||||||
|
sm.transition("connect");
|
||||||
|
|
||||||
|
expect(listener).toHaveBeenCalledWith({ from: "idle", to: "connecting" });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("Yonexus.Client heartbeat scheduling", () => {
|
||||||
|
it("schedules heartbeat only when authenticated", () => {
|
||||||
|
const heartbeat = createHeartbeatScheduler({ intervalMs: 300_000 });
|
||||||
|
|
||||||
|
expect(heartbeat.isRunning()).toBe(false);
|
||||||
|
|
||||||
|
heartbeat.start();
|
||||||
|
expect(heartbeat.isRunning()).toBe(true);
|
||||||
|
|
||||||
|
heartbeat.stop();
|
||||||
|
expect(heartbeat.isRunning()).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("emits heartbeat tick at configured interval", () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
const onTick = vi.fn();
|
||||||
|
const heartbeat = createHeartbeatScheduler({ intervalMs: 300_000, onTick });
|
||||||
|
|
||||||
|
heartbeat.start();
|
||||||
|
expect(onTick).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
vi.advanceTimersByTime(300_000);
|
||||||
|
expect(onTick).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
|
vi.advanceTimersByTime(300_000);
|
||||||
|
expect(onTick).toHaveBeenCalledTimes(2);
|
||||||
|
|
||||||
|
heartbeat.stop();
|
||||||
|
vi.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("resets interval on restart", () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
const onTick = vi.fn();
|
||||||
|
const heartbeat = createHeartbeatScheduler({ intervalMs: 300_000, onTick });
|
||||||
|
|
||||||
|
heartbeat.start();
|
||||||
|
vi.advanceTimersByTime(150_000);
|
||||||
|
|
||||||
|
heartbeat.stop();
|
||||||
|
heartbeat.start();
|
||||||
|
|
||||||
|
vi.advanceTimersByTime(150_000);
|
||||||
|
expect(onTick).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
vi.advanceTimersByTime(150_000);
|
||||||
|
expect(onTick).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
|
heartbeat.stop();
|
||||||
|
vi.useRealTimers();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
type ClientState =
|
||||||
|
| "idle"
|
||||||
|
| "connecting"
|
||||||
|
| "connected"
|
||||||
|
| "pairing_required"
|
||||||
|
| "pairing_pending"
|
||||||
|
| "authenticating"
|
||||||
|
| "authenticated"
|
||||||
|
| "reconnecting"
|
||||||
|
| "error";
|
||||||
|
|
||||||
|
type ClientEvent =
|
||||||
|
| "connect"
|
||||||
|
| "connected"
|
||||||
|
| "disconnected"
|
||||||
|
| "disconnect"
|
||||||
|
| "pair_required"
|
||||||
|
| "pairing_started"
|
||||||
|
| "pair_success"
|
||||||
|
| "pair_failed"
|
||||||
|
| "auth_required"
|
||||||
|
| "auth_success"
|
||||||
|
| "auth_failed"
|
||||||
|
| "re_pair_required"
|
||||||
|
| "error";
|
||||||
|
|
||||||
|
interface StateMachine {
|
||||||
|
getState(): ClientState;
|
||||||
|
transition(event: ClientEvent): void;
|
||||||
|
on(event: "stateChange", handler: (change: { from: ClientState; to: ClientState }) => void): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createClientStateMachine(): StateMachine {
|
||||||
|
let state: ClientState = "idle";
|
||||||
|
const listeners: Array<(change: { from: ClientState; to: ClientState }) => void> = [];
|
||||||
|
|
||||||
|
const transitions: Record<ClientState, Partial<Record<ClientEvent, ClientState>>> = {
|
||||||
|
idle: { connect: "connecting" },
|
||||||
|
connecting: { connected: "connected", error: "error", disconnect: "reconnecting" },
|
||||||
|
connected: {
|
||||||
|
pair_required: "pairing_required",
|
||||||
|
auth_required: "authenticating",
|
||||||
|
disconnect: "reconnecting"
|
||||||
|
},
|
||||||
|
pairing_required: { pairing_started: "pairing_pending", disconnect: "reconnecting" },
|
||||||
|
pairing_pending: {
|
||||||
|
pair_success: "authenticating",
|
||||||
|
pair_failed: "pairing_required",
|
||||||
|
disconnect: "reconnecting"
|
||||||
|
},
|
||||||
|
authenticating: {
|
||||||
|
auth_success: "authenticated",
|
||||||
|
auth_failed: "pairing_required",
|
||||||
|
re_pair_required: "pairing_required",
|
||||||
|
disconnect: "reconnecting"
|
||||||
|
},
|
||||||
|
authenticated: { re_pair_required: "pairing_required", disconnect: "reconnecting" },
|
||||||
|
reconnecting: { connect: "connecting" },
|
||||||
|
error: { connect: "connecting" }
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
getState: () => state,
|
||||||
|
transition: (event: ClientEvent) => {
|
||||||
|
const nextState = transitions[state]?.[event];
|
||||||
|
if (nextState) {
|
||||||
|
const from = state;
|
||||||
|
state = nextState;
|
||||||
|
listeners.forEach((l) => l({ from, to: nextState }));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
on: (event, handler) => {
|
||||||
|
if (event === "stateChange") {
|
||||||
|
listeners.push(handler);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface HeartbeatScheduler {
|
||||||
|
start(): void;
|
||||||
|
stop(): void;
|
||||||
|
isRunning(): boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createHeartbeatScheduler(options: {
|
||||||
|
intervalMs: number;
|
||||||
|
onTick?: () => void;
|
||||||
|
}): HeartbeatScheduler {
|
||||||
|
let timer: ReturnType<typeof setInterval> | null = null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
start: () => {
|
||||||
|
if (timer) clearInterval(timer);
|
||||||
|
timer = setInterval(() => {
|
||||||
|
options.onTick?.();
|
||||||
|
}, options.intervalMs);
|
||||||
|
},
|
||||||
|
stop: () => {
|
||||||
|
if (timer) {
|
||||||
|
clearInterval(timer);
|
||||||
|
timer = null;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
isRunning: () => timer !== null
|
||||||
|
};
|
||||||
|
}
|
||||||
163
tests/transport-reconnect.test.ts
Normal file
163
tests/transport-reconnect.test.ts
Normal file
@@ -0,0 +1,163 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
type EventName = "open" | "close" | "error" | "message";
|
||||||
|
type EventHandler = (...args: any[]) => void;
|
||||||
|
|
||||||
|
const socketInstances: MockWebSocket[] = [];
|
||||||
|
const pendingBehaviors: Array<"open" | "error"> = [];
|
||||||
|
|
||||||
|
class MockWebSocket {
|
||||||
|
static readonly OPEN = 1;
|
||||||
|
static readonly CLOSED = 3;
|
||||||
|
|
||||||
|
readyState = 0;
|
||||||
|
sent: string[] = [];
|
||||||
|
private readonly handlers = new Map<EventName, EventHandler[]>();
|
||||||
|
|
||||||
|
constructor(public readonly url: string) {
|
||||||
|
socketInstances.push(this);
|
||||||
|
const behavior = pendingBehaviors.shift() ?? "open";
|
||||||
|
|
||||||
|
queueMicrotask(() => {
|
||||||
|
if (behavior === "open") {
|
||||||
|
this.readyState = MockWebSocket.OPEN;
|
||||||
|
this.emit("open");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const error = new Error(`mock connect failure for ${url}`);
|
||||||
|
this.emit("error", error);
|
||||||
|
this.emit("close", 1006, Buffer.from("connect failed"));
|
||||||
|
this.readyState = MockWebSocket.CLOSED;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
once(event: EventName, handler: EventHandler): this {
|
||||||
|
const onceHandler: EventHandler = (...args: any[]) => {
|
||||||
|
this.off(event, onceHandler);
|
||||||
|
handler(...args);
|
||||||
|
};
|
||||||
|
return this.on(event, onceHandler);
|
||||||
|
}
|
||||||
|
|
||||||
|
on(event: EventName, handler: EventHandler): this {
|
||||||
|
const existing = this.handlers.get(event) ?? [];
|
||||||
|
existing.push(handler);
|
||||||
|
this.handlers.set(event, existing);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
off(event: EventName, handler: EventHandler): this {
|
||||||
|
const existing = this.handlers.get(event) ?? [];
|
||||||
|
this.handlers.set(
|
||||||
|
event,
|
||||||
|
existing.filter((candidate) => candidate !== handler)
|
||||||
|
);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
send(message: string): void {
|
||||||
|
this.sent.push(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
close(code = 1000, reason = ""):
|
||||||
|
void {
|
||||||
|
this.readyState = MockWebSocket.CLOSED;
|
||||||
|
this.emit("close", code, Buffer.from(reason));
|
||||||
|
}
|
||||||
|
|
||||||
|
emit(event: EventName, ...args: any[]): void {
|
||||||
|
for (const handler of [...(this.handlers.get(event) ?? [])]) {
|
||||||
|
handler(...args);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
vi.mock("ws", () => ({
|
||||||
|
WebSocket: MockWebSocket
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe("Yonexus.Client transport reconnect behavior", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
socketInstances.length = 0;
|
||||||
|
pendingBehaviors.length = 0;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.useRealTimers();
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("CF-02: retries initial connect with exponential backoff when server is unreachable", async () => {
|
||||||
|
const { createClientTransport } = await import("../plugin/core/transport.js");
|
||||||
|
const onStateChange = vi.fn();
|
||||||
|
const onError = vi.fn();
|
||||||
|
|
||||||
|
pendingBehaviors.push("error", "error", "open");
|
||||||
|
|
||||||
|
const transport = createClientTransport({
|
||||||
|
config: {
|
||||||
|
mainHost: "ws://localhost:8787",
|
||||||
|
identifier: "client-a",
|
||||||
|
notifyBotToken: "stub-token",
|
||||||
|
adminUserId: "admin-user"
|
||||||
|
},
|
||||||
|
onMessage: vi.fn(),
|
||||||
|
onStateChange,
|
||||||
|
onError
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(transport.connect()).rejects.toThrow("mock connect failure");
|
||||||
|
expect(socketInstances).toHaveLength(1);
|
||||||
|
expect(transport.state).toBe("disconnected");
|
||||||
|
|
||||||
|
await vi.advanceTimersByTimeAsync(999);
|
||||||
|
expect(socketInstances).toHaveLength(1);
|
||||||
|
|
||||||
|
await vi.advanceTimersByTimeAsync(1);
|
||||||
|
expect(socketInstances).toHaveLength(2);
|
||||||
|
|
||||||
|
await vi.advanceTimersByTimeAsync(1_999);
|
||||||
|
expect(socketInstances).toHaveLength(2);
|
||||||
|
|
||||||
|
await vi.advanceTimersByTimeAsync(1);
|
||||||
|
expect(socketInstances).toHaveLength(3);
|
||||||
|
expect(transport.state).toBe("connected");
|
||||||
|
expect(onError.mock.calls.length).toBeGreaterThanOrEqual(2);
|
||||||
|
expect(onStateChange).toHaveBeenCalledWith("connecting");
|
||||||
|
expect(onStateChange).toHaveBeenCalledWith("connected");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("CF-01: reconnects with backoff after network partition closes an established connection", async () => {
|
||||||
|
const { createClientTransport } = await import("../plugin/core/transport.js");
|
||||||
|
|
||||||
|
pendingBehaviors.push("open", "open");
|
||||||
|
|
||||||
|
const transport = createClientTransport({
|
||||||
|
config: {
|
||||||
|
mainHost: "ws://localhost:8787",
|
||||||
|
identifier: "client-a",
|
||||||
|
notifyBotToken: "stub-token",
|
||||||
|
adminUserId: "admin-user"
|
||||||
|
},
|
||||||
|
onMessage: vi.fn(),
|
||||||
|
onStateChange: vi.fn(),
|
||||||
|
onError: vi.fn()
|
||||||
|
});
|
||||||
|
|
||||||
|
await transport.connect();
|
||||||
|
expect(socketInstances).toHaveLength(1);
|
||||||
|
expect(transport.state).toBe("connected");
|
||||||
|
|
||||||
|
socketInstances[0].emit("close", 1006, Buffer.from("network partition"));
|
||||||
|
expect(transport.state).toBe("disconnected");
|
||||||
|
|
||||||
|
await vi.advanceTimersByTimeAsync(999);
|
||||||
|
expect(socketInstances).toHaveLength(1);
|
||||||
|
|
||||||
|
await vi.advanceTimersByTimeAsync(1);
|
||||||
|
expect(socketInstances).toHaveLength(2);
|
||||||
|
expect(transport.state).toBe("connected");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -4,7 +4,7 @@
|
|||||||
"module": "NodeNext",
|
"module": "NodeNext",
|
||||||
"moduleResolution": "NodeNext",
|
"moduleResolution": "NodeNext",
|
||||||
"outDir": "dist",
|
"outDir": "dist",
|
||||||
"rootDir": ".",
|
"rootDir": "..",
|
||||||
"strict": true,
|
"strict": true,
|
||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
"esModuleInterop": true,
|
"esModuleInterop": true,
|
||||||
@@ -15,7 +15,9 @@
|
|||||||
},
|
},
|
||||||
"include": [
|
"include": [
|
||||||
"plugin/**/*.ts",
|
"plugin/**/*.ts",
|
||||||
"servers/**/*.ts"
|
"plugin/**/*.d.ts",
|
||||||
|
"servers/**/*.ts",
|
||||||
|
"../Yonexus.Protocol/src/**/*.ts"
|
||||||
],
|
],
|
||||||
"exclude": [
|
"exclude": [
|
||||||
"dist",
|
"dist",
|
||||||
|
|||||||
8
vitest.config.ts
Normal file
8
vitest.config.ts
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
import { defineConfig } from "vitest/config";
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
globals: true,
|
||||||
|
environment: "node"
|
||||||
|
}
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user