Compare commits
24 Commits
5234358cac
...
8b26919790
| Author | SHA1 | Date | |
|---|---|---|---|
| 8b26919790 | |||
| 4adb187331 | |||
| 8824e768fb | |||
| 57b53fc122 | |||
| 7cdda2e335 | |||
| b10ebc541e | |||
| 9fd9b50842 | |||
| 5fbbdd199c | |||
| 93e09875ec | |||
| 65c1f92cc1 | |||
| df14022c9a | |||
| 824019168e | |||
| 4322604f78 | |||
| ddeed9a7b7 | |||
| 07c2438fb8 | |||
| 58818e11d1 | |||
| 5ca6ec0952 | |||
| cec59784de | |||
| fc226b1f18 | |||
| fb39a17dbb | |||
| bc3e931979 | |||
| 2148027a41 | |||
| 1d751b7c55 | |||
| c2bdb2efb6 |
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`
|
||||
|
||||
1318
package-lock.json
generated
Normal file
1318
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
37
package.json
Normal file
37
package.json
Normal file
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"name": "yonexus-client",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "Yonexus.Client OpenClaw plugin scaffold",
|
||||
"type": "module",
|
||||
"main": "dist/plugin/index.js",
|
||||
"openclaw": {
|
||||
"extensions": ["./dist/Yonexus.Client/plugin/index.js"]
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"plugin",
|
||||
"scripts",
|
||||
"protocol",
|
||||
"README.md",
|
||||
"PLAN.md",
|
||||
"SCAFFOLD.md",
|
||||
"STRUCTURE.md",
|
||||
"TASKS.md"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"clean": "rm -rf dist",
|
||||
"check": "tsc -p tsconfig.json --noEmit",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest"
|
||||
},
|
||||
"dependencies": {
|
||||
"ws": "^8.18.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^25.5.2",
|
||||
"typescript": "^5.6.3",
|
||||
"vitest": "^4.1.3"
|
||||
}
|
||||
}
|
||||
0
plugin/commands/.gitkeep
Normal file
0
plugin/commands/.gitkeep
Normal file
0
plugin/core/.gitkeep
Normal file
0
plugin/core/.gitkeep
Normal file
72
plugin/core/config.ts
Normal file
72
plugin/core/config.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
export interface YonexusClientConfig {
|
||||
mainHost: string;
|
||||
identifier: string;
|
||||
notifyBotToken: string;
|
||||
adminUserId: string;
|
||||
}
|
||||
|
||||
export class YonexusClientConfigError extends Error {
|
||||
readonly issues: string[];
|
||||
|
||||
constructor(issues: string[]) {
|
||||
super(`Invalid Yonexus.Client config: ${issues.join("; ")}`);
|
||||
this.name = "YonexusClientConfigError";
|
||||
this.issues = issues;
|
||||
}
|
||||
}
|
||||
|
||||
function isNonEmptyString(value: unknown): value is string {
|
||||
return typeof value === "string" && value.trim().length > 0;
|
||||
}
|
||||
|
||||
function isValidWsUrl(value: string): boolean {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
return url.protocol === "ws:" || url.protocol === "wss:";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function validateYonexusClientConfig(raw: unknown): YonexusClientConfig {
|
||||
const source = (raw && typeof raw === "object" ? raw : {}) as Record<string, unknown>;
|
||||
const issues: string[] = [];
|
||||
|
||||
const rawMainHost = source.mainHost;
|
||||
if (!isNonEmptyString(rawMainHost)) {
|
||||
issues.push("mainHost is required");
|
||||
} else if (!isValidWsUrl(rawMainHost.trim())) {
|
||||
issues.push("mainHost must be a valid ws:// or wss:// URL");
|
||||
}
|
||||
|
||||
const rawIdentifier = source.identifier;
|
||||
if (!isNonEmptyString(rawIdentifier)) {
|
||||
issues.push("identifier is required");
|
||||
}
|
||||
|
||||
const rawNotifyBotToken = source.notifyBotToken;
|
||||
if (!isNonEmptyString(rawNotifyBotToken)) {
|
||||
issues.push("notifyBotToken is required");
|
||||
}
|
||||
|
||||
const rawAdminUserId = source.adminUserId;
|
||||
if (!isNonEmptyString(rawAdminUserId)) {
|
||||
issues.push("adminUserId is required");
|
||||
}
|
||||
|
||||
if (issues.length > 0) {
|
||||
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 {
|
||||
mainHost,
|
||||
identifier,
|
||||
notifyBotToken,
|
||||
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();
|
||||
}
|
||||
477
plugin/core/runtime.ts
Normal file
477
plugin/core/runtime.ts
Normal file
@@ -0,0 +1,477 @@
|
||||
import {
|
||||
YONEXUS_PROTOCOL_VERSION,
|
||||
buildAuthRequest,
|
||||
buildHeartbeat,
|
||||
buildHello,
|
||||
buildPairConfirm,
|
||||
CodecError,
|
||||
createAuthRequestSigningInput,
|
||||
decodeBuiltin,
|
||||
encodeBuiltin,
|
||||
encodeRuleMessage,
|
||||
isBuiltinMessage,
|
||||
type AuthFailedPayload,
|
||||
type BuiltinPayloadMap,
|
||||
type HelloAckPayload,
|
||||
type PairFailedPayload,
|
||||
type PairRequestPayload,
|
||||
type PairSuccessPayload,
|
||||
type TypedBuiltinEnvelope
|
||||
} from "../../../Yonexus.Protocol/src/index.js";
|
||||
import type { YonexusClientConfig } from "./config.js";
|
||||
import {
|
||||
ensureClientKeyPair,
|
||||
hasClientKeyPair,
|
||||
hasClientSecret,
|
||||
createInitialClientState,
|
||||
YonexusClientState,
|
||||
YonexusClientStateStore
|
||||
} from "./state.js";
|
||||
import { generateNonce, signMessage } from "../crypto/keypair.js";
|
||||
import type { ClientConnectionState, ClientTransport } from "./transport.js";
|
||||
import type { ClientRuleRegistry } from "./rules.js";
|
||||
|
||||
export type YonexusClientPhase =
|
||||
| "idle"
|
||||
| "starting"
|
||||
| "awaiting_hello_ack"
|
||||
| "pair_required"
|
||||
| "waiting_pair_confirm"
|
||||
| "auth_required"
|
||||
| "authenticated"
|
||||
| "stopped";
|
||||
|
||||
export interface YonexusClientRuntimeOptions {
|
||||
config: YonexusClientConfig;
|
||||
transport: ClientTransport;
|
||||
stateStore: YonexusClientStateStore;
|
||||
ruleRegistry?: ClientRuleRegistry;
|
||||
onAuthenticated?: () => void;
|
||||
now?: () => number;
|
||||
}
|
||||
|
||||
export interface YonexusClientRuntimeState {
|
||||
readonly phase: YonexusClientPhase;
|
||||
readonly transportState: ClientConnectionState;
|
||||
readonly clientState: YonexusClientState;
|
||||
readonly pendingPairing?: {
|
||||
expiresAt: number;
|
||||
ttlSeconds: number;
|
||||
adminNotification: "sent" | "failed";
|
||||
};
|
||||
readonly lastPairingFailure?: string;
|
||||
}
|
||||
|
||||
export class YonexusClientRuntime {
|
||||
private readonly options: YonexusClientRuntimeOptions;
|
||||
private readonly now: () => number;
|
||||
private clientState: YonexusClientState;
|
||||
private phase: YonexusClientPhase = "idle";
|
||||
private pendingPairing?: {
|
||||
expiresAt: number;
|
||||
ttlSeconds: number;
|
||||
adminNotification: "sent" | "failed";
|
||||
};
|
||||
private lastPairingFailure?: string;
|
||||
|
||||
constructor(options: YonexusClientRuntimeOptions) {
|
||||
this.options = options;
|
||||
this.now = options.now ?? (() => Math.floor(Date.now() / 1000));
|
||||
this.clientState = createInitialClientState(options.config.identifier);
|
||||
}
|
||||
|
||||
get state(): YonexusClientRuntimeState {
|
||||
return {
|
||||
phase: this.phase,
|
||||
transportState: this.options.transport.state,
|
||||
clientState: this.clientState,
|
||||
pendingPairing: this.pendingPairing,
|
||||
lastPairingFailure: this.lastPairingFailure
|
||||
};
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
if (this.phase !== "idle" && this.phase !== "stopped") {
|
||||
return;
|
||||
}
|
||||
|
||||
this.phase = "starting";
|
||||
|
||||
// Load existing state and ensure key pair exists
|
||||
let state = await this.options.stateStore.load(this.options.config.identifier);
|
||||
const keyResult = await ensureClientKeyPair(state, this.options.stateStore);
|
||||
this.clientState = keyResult.state;
|
||||
|
||||
await this.options.transport.connect();
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
await this.options.stateStore.save({
|
||||
...this.clientState,
|
||||
updatedAt: this.now()
|
||||
});
|
||||
this.options.transport.disconnect();
|
||||
this.phase = "stopped";
|
||||
}
|
||||
|
||||
async handleMessage(raw: string): Promise<void> {
|
||||
if (raw === "heartbeat_tick") {
|
||||
await this.handleHeartbeatTick();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isBuiltinMessage(raw)) {
|
||||
this.options.ruleRegistry?.dispatch(raw);
|
||||
return;
|
||||
}
|
||||
|
||||
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") {
|
||||
this.handleHelloAck(envelope as TypedBuiltinEnvelope<"hello_ack">);
|
||||
return;
|
||||
}
|
||||
|
||||
if (envelope.type === "pair_request") {
|
||||
this.handlePairRequest(envelope as TypedBuiltinEnvelope<"pair_request">);
|
||||
return;
|
||||
}
|
||||
|
||||
if (envelope.type === "pair_success") {
|
||||
await this.handlePairSuccess(envelope as TypedBuiltinEnvelope<"pair_success">);
|
||||
return;
|
||||
}
|
||||
|
||||
if (envelope.type === "pair_failed") {
|
||||
this.handlePairFailed(envelope as TypedBuiltinEnvelope<"pair_failed">);
|
||||
return;
|
||||
}
|
||||
|
||||
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.options.onAuthenticated?.();
|
||||
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 {
|
||||
if (state === "connected") {
|
||||
// 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") {
|
||||
this.phase = hasClientSecret(this.clientState) ? "auth_required" : "idle";
|
||||
this.pendingPairing = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
private sendHello(): void {
|
||||
this.phase = "awaiting_hello_ack";
|
||||
this.options.transport.send(
|
||||
encodeBuiltin(
|
||||
buildHello(
|
||||
{
|
||||
identifier: this.options.config.identifier,
|
||||
hasSecret: hasClientSecret(this.clientState),
|
||||
hasKeyPair: hasClientKeyPair(this.clientState),
|
||||
publicKey: this.clientState.publicKey,
|
||||
protocolVersion: YONEXUS_PROTOCOL_VERSION
|
||||
},
|
||||
{ timestamp: this.now() }
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
submitPairingCode(pairingCode: string, requestId?: string): boolean {
|
||||
const normalizedCode = pairingCode.trim();
|
||||
if (!normalizedCode || !this.options.transport.isConnected) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.lastPairingFailure = undefined;
|
||||
return this.options.transport.send(
|
||||
encodeBuiltin(
|
||||
buildPairConfirm(
|
||||
{
|
||||
identifier: this.options.config.identifier,
|
||||
pairingCode: normalizedCode
|
||||
},
|
||||
{ requestId, timestamp: this.now() }
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
private handleHelloAck(envelope: TypedBuiltinEnvelope<"hello_ack">): void {
|
||||
const payload = envelope.payload as HelloAckPayload | undefined;
|
||||
if (!payload) {
|
||||
return;
|
||||
}
|
||||
|
||||
switch (payload.nextAction) {
|
||||
case "pair_required":
|
||||
this.phase = "pair_required";
|
||||
break;
|
||||
case "waiting_pair_confirm":
|
||||
this.phase = "waiting_pair_confirm";
|
||||
break;
|
||||
case "auth_required":
|
||||
this.phase = "auth_required";
|
||||
void this.sendAuthRequest();
|
||||
break;
|
||||
default:
|
||||
this.phase = "idle";
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private handlePairRequest(envelope: TypedBuiltinEnvelope<"pair_request">): void {
|
||||
const payload = envelope.payload as PairRequestPayload | undefined;
|
||||
if (!payload) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.pendingPairing = {
|
||||
expiresAt: payload.expiresAt,
|
||||
ttlSeconds: payload.ttlSeconds,
|
||||
adminNotification: payload.adminNotification
|
||||
};
|
||||
this.lastPairingFailure = undefined;
|
||||
// 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> {
|
||||
const payload = envelope.payload as PairSuccessPayload | undefined;
|
||||
if (!payload) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.clientState = {
|
||||
...this.clientState,
|
||||
secret: payload.secret,
|
||||
pairedAt: payload.pairedAt,
|
||||
updatedAt: this.now()
|
||||
};
|
||||
await this.options.stateStore.save(this.clientState);
|
||||
this.pendingPairing = undefined;
|
||||
this.lastPairingFailure = undefined;
|
||||
this.phase = "auth_required";
|
||||
await this.sendAuthRequest();
|
||||
}
|
||||
|
||||
private handlePairFailed(envelope: TypedBuiltinEnvelope<"pair_failed">): void {
|
||||
const payload = envelope.payload as PairFailedPayload | undefined;
|
||||
if (!payload) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.lastPairingFailure = payload.reason;
|
||||
if (payload.reason === "expired" || payload.reason === "admin_notification_failed") {
|
||||
this.pendingPairing = undefined;
|
||||
this.phase = "pair_required";
|
||||
return;
|
||||
}
|
||||
|
||||
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(
|
||||
options: YonexusClientRuntimeOptions
|
||||
): YonexusClientRuntime {
|
||||
return new YonexusClientRuntime(options);
|
||||
}
|
||||
199
plugin/core/state.ts
Normal file
199
plugin/core/state.ts
Normal file
@@ -0,0 +1,199 @@
|
||||
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
||||
import { dirname } from "node:path";
|
||||
import { generateKeyPair, type KeyPair } from "../crypto/keypair.js";
|
||||
|
||||
export const CLIENT_STATE_VERSION = 1;
|
||||
|
||||
export interface YonexusClientState {
|
||||
identifier: string;
|
||||
privateKey?: string;
|
||||
secret?: string;
|
||||
publicKey?: string;
|
||||
pairedAt?: number;
|
||||
authenticatedAt?: number;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
export interface YonexusClientStateFile extends YonexusClientState {
|
||||
version: number;
|
||||
}
|
||||
|
||||
export class YonexusClientStateError extends Error {
|
||||
override readonly cause?: unknown;
|
||||
|
||||
constructor(message: string, cause?: unknown) {
|
||||
super(message);
|
||||
this.name = "YonexusClientStateError";
|
||||
this.cause = cause;
|
||||
}
|
||||
}
|
||||
|
||||
export class YonexusClientStateCorruptionError extends YonexusClientStateError {
|
||||
constructor(message: string, cause?: unknown) {
|
||||
super(message, cause);
|
||||
this.name = "YonexusClientStateCorruptionError";
|
||||
}
|
||||
}
|
||||
|
||||
export interface YonexusClientStateStore {
|
||||
readonly filePath: string;
|
||||
load(identifier: string): Promise<YonexusClientState>;
|
||||
save(state: YonexusClientState): Promise<void>;
|
||||
}
|
||||
|
||||
export function createYonexusClientStateStore(filePath: string): YonexusClientStateStore {
|
||||
return {
|
||||
filePath,
|
||||
load: async (identifier) => loadYonexusClientState(filePath, identifier),
|
||||
save: async (state) => saveYonexusClientState(filePath, state)
|
||||
};
|
||||
}
|
||||
|
||||
export async function loadYonexusClientState(
|
||||
filePath: string,
|
||||
identifier: string
|
||||
): Promise<YonexusClientState> {
|
||||
try {
|
||||
const raw = await readFile(filePath, "utf8");
|
||||
const parsed = JSON.parse(raw) as YonexusClientStateFile;
|
||||
assertClientStateShape(parsed, filePath);
|
||||
|
||||
return {
|
||||
identifier: parsed.identifier,
|
||||
privateKey: parsed.privateKey,
|
||||
publicKey: parsed.publicKey,
|
||||
secret: parsed.secret,
|
||||
pairedAt: parsed.pairedAt,
|
||||
authenticatedAt: parsed.authenticatedAt,
|
||||
updatedAt: parsed.updatedAt
|
||||
};
|
||||
} catch (error) {
|
||||
if (isFileNotFoundError(error)) {
|
||||
return createInitialClientState(identifier);
|
||||
}
|
||||
|
||||
if (error instanceof YonexusClientStateError) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new YonexusClientStateCorruptionError(
|
||||
`Failed to load Yonexus.Client state file: ${filePath}`,
|
||||
error
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveYonexusClientState(
|
||||
filePath: string,
|
||||
state: YonexusClientState
|
||||
): Promise<void> {
|
||||
const normalizedState = {
|
||||
...state,
|
||||
identifier: state.identifier.trim(),
|
||||
updatedAt: state.updatedAt || Math.floor(Date.now() / 1000)
|
||||
} satisfies YonexusClientState;
|
||||
|
||||
const payload: YonexusClientStateFile = {
|
||||
version: CLIENT_STATE_VERSION,
|
||||
...normalizedState
|
||||
};
|
||||
|
||||
const tempPath = `${filePath}.tmp`;
|
||||
|
||||
try {
|
||||
await mkdir(dirname(filePath), { recursive: true });
|
||||
await writeFile(tempPath, `${JSON.stringify(payload, null, 2)}\n`, "utf8");
|
||||
await rename(tempPath, filePath);
|
||||
} catch (error) {
|
||||
throw new YonexusClientStateError(
|
||||
`Failed to save Yonexus.Client state file: ${filePath}`,
|
||||
error
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function createInitialClientState(identifier: string): YonexusClientState {
|
||||
const normalizedIdentifier = identifier.trim();
|
||||
return {
|
||||
identifier: normalizedIdentifier,
|
||||
updatedAt: Math.floor(Date.now() / 1000)
|
||||
};
|
||||
}
|
||||
|
||||
export function hasClientSecret(state: YonexusClientState): boolean {
|
||||
return typeof state.secret === "string" && state.secret.length > 0;
|
||||
}
|
||||
|
||||
export function hasClientKeyPair(state: YonexusClientState): boolean {
|
||||
return (
|
||||
typeof state.privateKey === "string" &&
|
||||
state.privateKey.length > 0 &&
|
||||
typeof state.publicKey === "string" &&
|
||||
state.publicKey.length > 0
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure the client state has a valid key pair.
|
||||
* If no key pair exists, generates a new Ed25519 key pair.
|
||||
* Returns the (possibly updated) state and whether a new key was generated.
|
||||
*/
|
||||
export async function ensureClientKeyPair(
|
||||
state: YonexusClientState,
|
||||
stateStore: YonexusClientStateStore
|
||||
): Promise<{ state: YonexusClientState; generated: boolean }> {
|
||||
if (hasClientKeyPair(state)) {
|
||||
return { state, generated: false };
|
||||
}
|
||||
|
||||
const keyPair = await generateKeyPair();
|
||||
const updatedState: YonexusClientState = {
|
||||
...state,
|
||||
privateKey: keyPair.privateKey,
|
||||
publicKey: keyPair.publicKey,
|
||||
updatedAt: Math.floor(Date.now() / 1000)
|
||||
};
|
||||
|
||||
await stateStore.save(updatedState);
|
||||
return { state: updatedState, generated: true };
|
||||
}
|
||||
|
||||
function assertClientStateShape(
|
||||
value: unknown,
|
||||
filePath: string
|
||||
): asserts value is YonexusClientStateFile {
|
||||
if (!value || typeof value !== "object") {
|
||||
throw new YonexusClientStateCorruptionError(
|
||||
`State file is not a JSON object: ${filePath}`
|
||||
);
|
||||
}
|
||||
|
||||
const candidate = value as Partial<YonexusClientStateFile>;
|
||||
if (candidate.version !== CLIENT_STATE_VERSION) {
|
||||
throw new YonexusClientStateCorruptionError(
|
||||
`Unsupported client state version in ${filePath}: ${String(candidate.version)}`
|
||||
);
|
||||
}
|
||||
|
||||
if (typeof candidate.identifier !== "string" || candidate.identifier.trim().length === 0) {
|
||||
throw new YonexusClientStateCorruptionError(
|
||||
`Client state file has invalid identifier: ${filePath}`
|
||||
);
|
||||
}
|
||||
|
||||
const updatedAt = candidate.updatedAt;
|
||||
if (typeof updatedAt !== "number" || !Number.isInteger(updatedAt) || updatedAt < 0) {
|
||||
throw new YonexusClientStateCorruptionError(
|
||||
`Client state file has invalid updatedAt value: ${filePath}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function isFileNotFoundError(error: unknown): error is NodeJS.ErrnoException {
|
||||
return (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"code" in error &&
|
||||
(error as { code?: unknown }).code === "ENOENT"
|
||||
);
|
||||
}
|
||||
229
plugin/core/transport.ts
Normal file
229
plugin/core/transport.ts
Normal file
@@ -0,0 +1,229 @@
|
||||
import { WebSocket } from "ws";
|
||||
import type { YonexusClientConfig } from "./config.js";
|
||||
|
||||
export type ClientConnectionState =
|
||||
| "idle"
|
||||
| "connecting"
|
||||
| "connected"
|
||||
| "authenticating"
|
||||
| "authenticated"
|
||||
| "disconnecting"
|
||||
| "disconnected"
|
||||
| "error";
|
||||
|
||||
export interface ClientTransport {
|
||||
readonly state: ClientConnectionState;
|
||||
readonly isConnected: boolean;
|
||||
readonly isAuthenticated: boolean;
|
||||
connect(): Promise<void>;
|
||||
disconnect(): void;
|
||||
send(message: string): boolean;
|
||||
markAuthenticated(): void;
|
||||
markAuthenticating(): void;
|
||||
}
|
||||
|
||||
export type ClientMessageHandler = (message: string) => void;
|
||||
export type ClientStateChangeHandler = (state: ClientConnectionState) => void;
|
||||
export type ClientErrorHandler = (error: Error) => void;
|
||||
|
||||
export interface ClientTransportOptions {
|
||||
config: YonexusClientConfig;
|
||||
onMessage: ClientMessageHandler;
|
||||
onStateChange?: ClientStateChangeHandler;
|
||||
onError?: ClientErrorHandler;
|
||||
}
|
||||
|
||||
export class YonexusClientTransport implements ClientTransport {
|
||||
private ws: WebSocket | null = null;
|
||||
private options: ClientTransportOptions;
|
||||
private _state: ClientConnectionState = "idle";
|
||||
private reconnectAttempts = 0;
|
||||
private reconnectTimer: NodeJS.Timeout | null = null;
|
||||
private heartbeatTimer: NodeJS.Timeout | null = null;
|
||||
private shouldReconnect = false;
|
||||
|
||||
// Reconnect configuration
|
||||
private readonly maxReconnectAttempts = 10;
|
||||
private readonly baseReconnectDelayMs = 1000;
|
||||
private readonly maxReconnectDelayMs = 30000;
|
||||
|
||||
constructor(options: ClientTransportOptions) {
|
||||
this.options = options;
|
||||
}
|
||||
|
||||
get state(): ClientConnectionState {
|
||||
return this._state;
|
||||
}
|
||||
|
||||
get isConnected(): boolean {
|
||||
return this.ws !== null && this.ws.readyState === WebSocket.OPEN;
|
||||
}
|
||||
|
||||
get isAuthenticated(): boolean {
|
||||
return this._state === "authenticated";
|
||||
}
|
||||
|
||||
async connect(): Promise<void> {
|
||||
if (this.isConnected) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.shouldReconnect = true;
|
||||
this.clearReconnectTimer();
|
||||
this.setState("connecting");
|
||||
const { mainHost } = this.options.config;
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
this.ws = new WebSocket(mainHost);
|
||||
|
||||
const onOpen = () => {
|
||||
this.ws?.off("error", onInitialError);
|
||||
this.setState("connected");
|
||||
this.reconnectAttempts = 0; // Reset on successful connection
|
||||
resolve();
|
||||
};
|
||||
|
||||
const onInitialError = (error: Error) => {
|
||||
this.setState("error");
|
||||
if (this.options.onError) {
|
||||
this.options.onError(error);
|
||||
}
|
||||
reject(error);
|
||||
};
|
||||
|
||||
this.ws.once("open", onOpen);
|
||||
this.ws.once("error", onInitialError);
|
||||
|
||||
this.ws.on("message", (data) => {
|
||||
const message = data.toString("utf8");
|
||||
this.options.onMessage(message);
|
||||
});
|
||||
|
||||
this.ws.on("close", (code: number, reason: Buffer) => {
|
||||
this.handleDisconnect(code, reason.toString());
|
||||
});
|
||||
|
||||
this.ws.on("error", (error: Error) => {
|
||||
if (this.options.onError) {
|
||||
this.options.onError(error);
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
this.setState("error");
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
disconnect(): void {
|
||||
this.shouldReconnect = false;
|
||||
this.clearReconnectTimer();
|
||||
this.stopHeartbeat();
|
||||
|
||||
if (this.ws) {
|
||||
this.setState("disconnecting");
|
||||
this.ws.close(1000, "Client disconnecting");
|
||||
this.ws = null;
|
||||
}
|
||||
|
||||
this.setState("disconnected");
|
||||
}
|
||||
|
||||
send(message: string): boolean {
|
||||
if (!this.isConnected) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
this.ws!.send(message);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
markAuthenticated(): void {
|
||||
if (this._state === "connected" || this._state === "authenticating") {
|
||||
this.setState("authenticated");
|
||||
this.startHeartbeat();
|
||||
}
|
||||
}
|
||||
|
||||
markAuthenticating(): void {
|
||||
if (this._state === "connected") {
|
||||
this.setState("authenticating");
|
||||
}
|
||||
}
|
||||
|
||||
private handleDisconnect(code: number, reason: string): void {
|
||||
this.ws = null;
|
||||
this.stopHeartbeat();
|
||||
this.setState("disconnected");
|
||||
|
||||
// Don't reconnect if it was a normal close or caller explicitly stopped reconnects.
|
||||
if (code === 1000 || !this.shouldReconnect) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.reconnectAttempts < this.maxReconnectAttempts) {
|
||||
this.scheduleReconnect();
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleReconnect(): void {
|
||||
this.clearReconnectTimer();
|
||||
|
||||
const delay = Math.min(
|
||||
this.baseReconnectDelayMs * Math.pow(2, this.reconnectAttempts),
|
||||
this.maxReconnectDelayMs
|
||||
);
|
||||
|
||||
this.reconnectAttempts++;
|
||||
|
||||
this.reconnectTimer = setTimeout(() => {
|
||||
this.connect().catch(() => {
|
||||
// Error handled in connect()
|
||||
});
|
||||
}, delay);
|
||||
}
|
||||
|
||||
private clearReconnectTimer(): void {
|
||||
if (this.reconnectTimer) {
|
||||
clearTimeout(this.reconnectTimer);
|
||||
this.reconnectTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
private startHeartbeat(): void {
|
||||
this.stopHeartbeat();
|
||||
// Heartbeat every 5 minutes (300 seconds)
|
||||
this.heartbeatTimer = setInterval(() => {
|
||||
if (this.isConnected) {
|
||||
// Send heartbeat - actual message construction done by protocol layer
|
||||
this.options.onMessage("heartbeat_tick");
|
||||
}
|
||||
}, 5 * 60 * 1000);
|
||||
}
|
||||
|
||||
private stopHeartbeat(): void {
|
||||
if (this.heartbeatTimer) {
|
||||
clearInterval(this.heartbeatTimer);
|
||||
this.heartbeatTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
private setState(state: ClientConnectionState): void {
|
||||
const oldState = this._state;
|
||||
this._state = state;
|
||||
|
||||
if (oldState !== state && this.options.onStateChange) {
|
||||
this.options.onStateChange(state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function createClientTransport(options: ClientTransportOptions): ClientTransport {
|
||||
return new YonexusClientTransport(options);
|
||||
}
|
||||
119
plugin/crypto/keypair.ts
Normal file
119
plugin/crypto/keypair.ts
Normal file
@@ -0,0 +1,119 @@
|
||||
import { randomBytes, sign as signMessageRaw, verify as verifySignatureRaw } from "node:crypto";
|
||||
|
||||
/**
|
||||
* Key pair for Yonexus client authentication
|
||||
* Uses Ed25519 for digital signatures
|
||||
*/
|
||||
export interface KeyPair {
|
||||
/** Base64-encoded Ed25519 private key */
|
||||
readonly privateKey: string;
|
||||
/** Base64-encoded Ed25519 public key */
|
||||
readonly publicKey: string;
|
||||
/** Algorithm identifier for compatibility */
|
||||
readonly algorithm: "Ed25519";
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a new Ed25519 key pair for client authentication.
|
||||
*
|
||||
* In v1, we use Node.js crypto.generateKeyPairSync for Ed25519.
|
||||
* The keys are encoded as base64 for JSON serialization.
|
||||
*/
|
||||
export async function generateKeyPair(): Promise<KeyPair> {
|
||||
const { generateKeyPair } = await import("node:crypto");
|
||||
|
||||
const { publicKey, privateKey } = await new Promise<{
|
||||
publicKey: string;
|
||||
privateKey: string;
|
||||
}>((resolve, reject) => {
|
||||
generateKeyPair(
|
||||
"ed25519",
|
||||
{
|
||||
publicKeyEncoding: { type: "spki", format: "pem" },
|
||||
privateKeyEncoding: { type: "pkcs8", format: "pem" }
|
||||
},
|
||||
(err, pubKey, privKey) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
resolve({ publicKey: pubKey, privateKey: privKey });
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
privateKey,
|
||||
publicKey,
|
||||
algorithm: "Ed25519"
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Sign a message using the client's private key.
|
||||
*
|
||||
* @param privateKeyPem - PEM-encoded private key
|
||||
* @param message - Message to sign (Buffer or string)
|
||||
* @returns Base64-encoded signature
|
||||
*/
|
||||
export async function signMessage(
|
||||
privateKeyPem: string,
|
||||
message: Buffer | string
|
||||
): Promise<string> {
|
||||
const signature = signMessageRaw(null, typeof message === "string" ? Buffer.from(message) : message, privateKeyPem);
|
||||
return signature.toString("base64");
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify a signature using the client's public key.
|
||||
*
|
||||
* @param publicKeyPem - PEM-encoded public key
|
||||
* @param message - Original message (Buffer or string)
|
||||
* @param signature - Base64-encoded signature
|
||||
* @returns Whether the signature is valid
|
||||
*/
|
||||
export async function verifySignature(
|
||||
publicKeyPem: string,
|
||||
message: Buffer | string,
|
||||
signature: string
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const sigBuffer = Buffer.from(signature, "base64");
|
||||
return verifySignatureRaw(null, typeof message === "string" ? Buffer.from(message) : message, publicKeyPem, sigBuffer);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a cryptographically secure random pairing code.
|
||||
* Format: XXXX-XXXX-XXXX (12 alphanumeric characters in groups of 4)
|
||||
*/
|
||||
export function generatePairingCode(): string {
|
||||
const bytes = randomBytes(8);
|
||||
const chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; // Excludes confusing chars (0, O, 1, I)
|
||||
|
||||
let code = "";
|
||||
for (let i = 0; i < 12; i++) {
|
||||
code += chars[bytes[i % bytes.length] % chars.length];
|
||||
}
|
||||
|
||||
// Format as XXXX-XXXX-XXXX
|
||||
return `${code.slice(0, 4)}-${code.slice(4, 8)}-${code.slice(8, 12)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a shared secret for client authentication.
|
||||
* This is issued by the server after successful pairing.
|
||||
*/
|
||||
export function generateSecret(): string {
|
||||
return randomBytes(32).toString("base64url");
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a 24-character nonce for authentication.
|
||||
*/
|
||||
export function generateNonce(): string {
|
||||
const bytes = randomBytes(18);
|
||||
return bytes.toString("base64url").slice(0, 24);
|
||||
}
|
||||
0
plugin/hooks/.gitkeep
Normal file
0
plugin/hooks/.gitkeep
Normal file
134
plugin/index.ts
134
plugin/index.ts
@@ -0,0 +1,134 @@
|
||||
export { validateYonexusClientConfig, YonexusClientConfigError } from "./core/config.js";
|
||||
export type { YonexusClientConfig } from "./core/config.js";
|
||||
export {
|
||||
CLIENT_STATE_VERSION,
|
||||
YonexusClientStateError,
|
||||
YonexusClientStateCorruptionError,
|
||||
createYonexusClientStateStore,
|
||||
loadYonexusClientState,
|
||||
saveYonexusClientState,
|
||||
createInitialClientState,
|
||||
hasClientSecret,
|
||||
hasClientKeyPair,
|
||||
type YonexusClientState,
|
||||
type YonexusClientStateFile,
|
||||
type YonexusClientStateStore
|
||||
} from "./core/state.js";
|
||||
export {
|
||||
createClientTransport,
|
||||
YonexusClientTransport,
|
||||
type ClientTransport,
|
||||
type ClientTransportOptions,
|
||||
type ClientConnectionState,
|
||||
type ClientMessageHandler,
|
||||
type ClientStateChangeHandler,
|
||||
type ClientErrorHandler
|
||||
} from "./core/transport.js";
|
||||
export {
|
||||
createYonexusClientRuntime,
|
||||
YonexusClientRuntime,
|
||||
type YonexusClientRuntimeOptions,
|
||||
type YonexusClientRuntimeState,
|
||||
type YonexusClientPhase
|
||||
} 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 {
|
||||
readonly name: "Yonexus.Client";
|
||||
readonly version: string;
|
||||
readonly description: string;
|
||||
}
|
||||
|
||||
const manifest: YonexusClientPluginManifest = {
|
||||
name: "Yonexus.Client",
|
||||
version: "0.1.0",
|
||||
description: "Yonexus client plugin for cross-instance OpenClaw communication"
|
||||
};
|
||||
|
||||
export function createYonexusClientPlugin(api: { rootDir: string; pluginConfig: unknown }): void {
|
||||
// 1. Ensure shared state survives hot-reload — only initialise when absent
|
||||
if (!(_G[_REGISTRY_KEY] instanceof YonexusClientRuleRegistry)) {
|
||||
_G[_REGISTRY_KEY] = createClientRuleRegistry();
|
||||
}
|
||||
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 { manifest };
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"id": "yonexus-client",
|
||||
"name": "Yonexus.Client",
|
||||
"version": "0.1.0",
|
||||
"description": "Yonexus client plugin for cross-instance OpenClaw communication",
|
||||
"entry": "./dist/Yonexus.Client/plugin/index.js",
|
||||
"permissions": [],
|
||||
"configSchema": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"mainHost": { "type": "string" },
|
||||
"identifier": { "type": "string" },
|
||||
"notifyBotToken": { "type": "string" },
|
||||
"adminUserId": { "type": "string" }
|
||||
},
|
||||
"required": ["mainHost", "identifier", "notifyBotToken", "adminUserId"]
|
||||
}
|
||||
}
|
||||
|
||||
0
plugin/tools/.gitkeep
Normal file
0
plugin/tools/.gitkeep
Normal file
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
@@ -0,0 +1,38 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import os from "node:os";
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const mode = args.includes("--install") ? "install" : args.includes("--uninstall") ? "uninstall" : null;
|
||||
const profileIndex = args.indexOf("--openclaw-profile-path");
|
||||
const profilePath = profileIndex >= 0 ? args[profileIndex + 1] : path.join(os.homedir(), ".openclaw");
|
||||
|
||||
if (!mode) {
|
||||
console.error("Usage: node scripts/install.mjs --install|--uninstall [--openclaw-profile-path <path>]");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const repoRoot = path.resolve(import.meta.dirname, "..");
|
||||
const pluginName = "Yonexus.Client";
|
||||
const sourceDist = path.join(repoRoot, "dist");
|
||||
const targetDir = path.join(profilePath, "plugins", pluginName);
|
||||
|
||||
if (mode === "install") {
|
||||
if (!fs.existsSync(sourceDist)) {
|
||||
console.error(`Build output not found: ${sourceDist}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
fs.mkdirSync(path.dirname(targetDir), { recursive: true });
|
||||
fs.rmSync(targetDir, { recursive: true, force: 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, "package.json"), path.join(targetDir, "package.json"));
|
||||
console.log(`Installed ${pluginName} to ${targetDir}`);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
fs.rmSync(targetDir, { recursive: true, force: true });
|
||||
console.log(`Removed ${pluginName} from ${targetDir}`);
|
||||
|
||||
0
servers/.gitkeep
Normal file
0
servers/.gitkeep
Normal file
0
skills/.gitkeep
Normal file
0
skills/.gitkeep
Normal file
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");
|
||||
});
|
||||
});
|
||||
26
tsconfig.json
Normal file
26
tsconfig.json
Normal file
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"outDir": "dist",
|
||||
"rootDir": "..",
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"resolveJsonModule": true,
|
||||
"declaration": true,
|
||||
"sourceMap": true
|
||||
},
|
||||
"include": [
|
||||
"plugin/**/*.ts",
|
||||
"plugin/**/*.d.ts",
|
||||
"servers/**/*.ts",
|
||||
"../Yonexus.Protocol/src/**/*.ts"
|
||||
],
|
||||
"exclude": [
|
||||
"dist",
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
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