Skip to content

Commit

Permalink
fix nocap regression, echo.websocket.org false positive
Browse files Browse the repository at this point in the history
  • Loading branch information
dskvr committed Jan 16, 2025
1 parent d34f74f commit c7ea2f4
Show file tree
Hide file tree
Showing 9 changed files with 86 additions and 40 deletions.
2 changes: 1 addition & 1 deletion apps/gui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@
"@careswitch/svelte-data-table": "^0.6.3",
"@nostrwatch/auditor": "workspace:*",
"@nostrwatch/nocap": "workspace:^",
"@nostrwatch/nocap-websocket-adapter-default": "workspace:^",
"@nostrwatch/nocap-every-adapter-default": "workspace:^",
"@nostrwatch/route66": "workspace:^",
"@nostrwatch/route66-cacheadapter-nostrsqlite": "workspace:^",
"@nostrwatch/route66-wsadapter-nostrtools": "workspace:^",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
const busy: Writable<boolean> = writable(false);
const speed: Writable<number | null> = writable(null);
const success: Writable<boolean | null> = writable(null);
// const success: Writable<boolean | null> = writable(null);
const result: Writable<any | null> = writable(null);
const speedometerWidth: Writable<number> = writable(400);
let nocap: Nocap | null ;
Expand All @@ -23,15 +24,14 @@
nocap.on('change', (value: any) => {
//console.log('onchange value', value);
});
nocap.useAdapters([WebsocketAdapter]);
const result = await nocap.check('open' as CheckKey);
//console.log('speedcard result', result)
nocap.useAdapter(WebsocketAdapter);
const res = await nocap.check(['open', 'read']);
//console.log('speedcard result', res)
busy.set(false);
speed.set(result.open.duration);
success.set(result.open.data)
speed.set(res.open.duration);
// success.set(res.open.data)
result.set(res);
nocap = null;
if (container) {
resizeObserver = new ResizeObserver(entries => {
for (let entry of entries) {
Expand All @@ -53,6 +53,8 @@
nocap = null;
});
$: error = $result?.open?.message ?? false;
$: success = $result?.open?.data ?? false
$: value = $speed ? Math.round($speed) : null;
$: isMaximum = (value || 0) > 3000;
$: width = $speedometerWidth;
Expand All @@ -69,7 +71,9 @@
<Card.Title>Speed</Card.Title>
</Card.Header>
<Card.Content class="speedometer-container">
{#if $success === true && $busy === false}
<!-- <pre>{JSON.stringify($result, null, 2)}</pre> -->

{#if success === true && $busy === false}
<div bind:this={container} class="text-center">
{#if value}
<Speedometer
Expand Down Expand Up @@ -122,7 +126,11 @@
{#if $busy}
<div>Speed test commencing...</div>
{:else}
<div>Could not connect.</div>
{#if error}
<div>{error}</div>
{:else}
<div>Could not connect.</div>
{/if}
{/if}
{/if}
</Card.Content>
Expand Down
4 changes: 2 additions & 2 deletions apps/gui/src/lib/stores/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ export const updateLastSync = () => {
}

export const shouldSync = () => {
// const threshold = 60*30
const threshold = 15*1
const threshold = 60*30
// const threshold = 15*60
const timestamp = get(lastCompleteSync)
const now = Math.round(Date.now()/1000)
console.log('should sync?', threshold<(now-timestamp), formatSeconds(threshold), timeAgo(now*1000), timeAgo(timestamp*1000))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,15 @@
"test-ui": "vitest --ui --testTimeout=15000"
},
"dependencies": {
"@nostrwatch/nocap": "workspace:*",
"@nostrwatch/nocap-dns-adapter-default": "workspace:*",
"@nostrwatch/nocap-geo-adapter-default": "workspace:*",
"@nostrwatch/nocap-info-adapter-default": "workspace:*",
"@nostrwatch/nocap-ssl-adapter-default": "workspace:*",
"@nostrwatch/nocap-websocket-adapter-default": "workspace:*",
"buffer": "^6.0.3",
"websocket-polyfill": "^0.0.3",
"ws": "8.18.0",
"@nostrwatch/nocap": "workspace:*"
"ws": "8.18.0"
},
"peerDependencies": {
"@nostrwatch/websocket": "workspace:^"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ export default [
strict: false,
},
plugins: [
nodePolyfills(),
resolve({
browser: true,
extensions: ['.js'],
Expand All @@ -82,7 +83,7 @@ export default [
json({
sourceMap: true,
}),
nodePolyfills(),

// terser(),
],
onwarn
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { TorWebSocket } from './tor';
import { Buffer } from 'buffer';

import {
AbstractAdapter,
Expand All @@ -23,19 +24,20 @@ class WebsocketAdapterDefault extends AbstractAdapter implements IAdapter {
initialize(): void {}

async check_open(): Promise<void> {
console.log('WebsocketAdapterDefault.check_open()', 'open');
this.base?.logger?.debug(`${this.base.url}: WebsocketAdapterDefault.check_open()`);
try {
if (this.base.network === 'clearnet') {
this.base.ws = new CompatibleWebSocket(this.base.url);
await this.base.ws.ready();
} else if (this.base.network === 'tor') {
const torSocksProxy = 'socks5h://127.0.0.1:9050';
const agent = new (require('socks-proxy-agent')).SocksProxyAgent(torSocksProxy);
this.base.ws = new CompatibleWebSocket(this.base.url, { agent });
await this.base.ws.ready();
} else {
throw new Error('Unsupported network');
}
await this.base.ws.ready();
console.log('WebsocketAdapterDefault.check_open()', 'connected');
this.bind_events();
} catch (error) {
console.error('Error in check_open:', error);
Expand Down Expand Up @@ -64,11 +66,13 @@ class WebsocketAdapterDefault extends AbstractAdapter implements IAdapter {
bind_events(): void {
this.base?.logger?.debug(`${this.base.url}: WebsocketAdapterDefault.bind_events()`);
try {
this.base.ws?.on('open', (e: Event) => {
this.base.ws?.on('open', async (e: Event) => {
console.log('WebsocketAdapterDefault.check_open()', 'complete', this.base.subid('open'));
this.base.on_open(e);
this.count.event++;
});
this.base.ws?.on('message', (data: any) => {
this.base.ws?.on('message', (message: any) => {
const { data } = message;
this.handle_nostr_event(data);
});
this.base.ws?.on('close', (e: Event) => {
Expand All @@ -86,24 +90,23 @@ class WebsocketAdapterDefault extends AbstractAdapter implements IAdapter {
this.base?.logger?.debug(`${this.base.url}: WebsocketAdapterDefault.handle_nostr_event()`);
let ev: any;
try{
console.log('MESSAGE', message)
const messageType = (message instanceof Buffer)? 'buffer': typeof message;
if(messageType === 'string') {
ev = JSON.parse(message as string)
ev = JSON.parse(message as string);
}
else if(messageType === 'buffer') {
ev = JSON.parse((message as Buffer).toString())
ev = JSON.parse((message as Buffer).toString());
}
} catch (e) {
const err = `${this.base.url} is not NIP-01 compatible, responded with invalid JSON: ${e}`;
this.base?.logger?.err(err);
this.base.auditor.fail('INVALID_JSON', {
description: 'Relay responded to subscription with invalid JSON.',
severity: 'high',
impact: ['reliability'],
domain: 'NIP-01',
});
return this.base.websocket_hard_fail(err);
console.error('json parsing failed')
return this.base.websocket_hard_fail(this.notNip01Compat(e));
}

const validEventTypes = ['EVENT', 'EOSE', 'OK', 'NOTICE', 'LIMITS', 'AUTH'];

if(!validEventTypes.includes(ev?.[0])) {
console.error('event type failed', typeof ev, ev?.[0])
return this.base.websocket_hard_fail(this.notNip01Compat(ev));
}

if (!ev || !(ev instanceof Array) || !ev.length) return;
Expand Down Expand Up @@ -168,6 +171,18 @@ class WebsocketAdapterDefault extends AbstractAdapter implements IAdapter {
this.base?.logger?.debug('WebsocketAdapterDefault.close()');
this.base?.ws?.close();
}

notNip01Compat(e?: any): string {
const err = `${this.base.url} is not NIP-01 compatible, responded with invalid JSON: ${e}`;
this.base?.logger?.err(err);
this.base.auditor.fail('INVALID_JSON', {
description: 'Relay responded to subscription with invalid JSON.',
severity: 'high',
impact: ['reliability'],
domain: 'NIP-01',
});
return err
}
}

export default WebsocketAdapterDefault;
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@
"types": "./dist/server/types/index.d.ts"
},
"./web": {
"import": "./dist/web/index.esm.js",
"types": "./dist/web/types/index.d.ts"
"import": "./dist/web/index.js",
"types": "./dist/server/types/index.d.ts"
}
},
"scripts": {
Expand Down
26 changes: 22 additions & 4 deletions libraries/nocap/src/classes/Base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -985,7 +985,7 @@ on_event(subid: string, ev: any): void {
return this.maybeExecuteAdapterMethod(
'websocket',
'isConnecting',
() => this.ws?.readyState && (this.ws?.readyState as number) === WebSocket.CONNECTING ? true : false
() => this.ws?.readyState && (this.ws?.readyState as number) === 0 ? true : false
)
}

Expand All @@ -1000,7 +1000,10 @@ on_event(subid: string, ev: any): void {
return this.maybeExecuteAdapterMethod(
'websocket',
'isConnected',
() => this.ws?.readyState && this.ws.readyState === WebSocket.OPEN ? true : false
() => {
console.log('isConnected', this.ws?.readyState && this.ws.readyState === 1 ? true : false, this?.ws?.readyState)
return this.ws?.readyState && this.ws.readyState === 1 ? true : false
}
)
}

Expand All @@ -1017,7 +1020,7 @@ on_event(subid: string, ev: any): void {
return this.maybeExecuteAdapterMethod(
'websocket',
'isClosing',
() => this.ws?.readyState && this.ws.readyState === WebSocket.CLOSING ? true : false
() => this.ws?.readyState && this.ws.readyState === 2 ? true : false
)
}

Expand All @@ -1032,7 +1035,22 @@ on_event(subid: string, ev: any): void {
return this.maybeExecuteAdapterMethod(
'websocket',
'isClosed',
() => this.ws?.readyState && this.ws.readyState === WebSocket.CLOSED ? true : false
() => this.ws?.readyState && this.ws.readyState === 3 ? true : false
)
}

/**
* isBusy
* Checks if the websocket is busy (connecting or closing)
*
* @private
* @returns {boolean} - True if closed, false otherwise
*/
isBusy(): boolean {
return this.maybeExecuteAdapterMethod(
'websocket',
'isBusy',
() => this.isConnecting() || this.isClosing()
)
}

Expand Down
7 changes: 5 additions & 2 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit c7ea2f4

Please sign in to comment.