Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions bun.lock

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

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
"homepage": "https://github.com/FROSTR-ORG/igloo-cli#readme",
"dependencies": {
"@frostr/bifrost": "^1.0.7",
"@frostr/igloo-core": "^0.2.4",
"@frostr/igloo-core": "0.2.4",
"@noble/ciphers": "^2.0.1",
"@noble/curves": "^2.0.1",
"@noble/hashes": "^2.0.1",
Expand Down
4 changes: 2 additions & 2 deletions src/components/keyset/useShareEchoListener.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {useCallback, useEffect, useMemo, useRef, useState} from 'react';
import {awaitShareEcho} from '@frostr/igloo-core';
import {computeEchoRelays} from '../../keyset/echoRelays.js';
import {awaitShareEchoCompat} from '../../keyset/awaitShareEchoCompat.js';

export type EchoStatus = 'idle' | 'listening' | 'success';

Expand Down Expand Up @@ -131,7 +131,7 @@ export function useShareEchoListener(
console.log('[echo-listen] INFO using relays', relays ?? 'default');
} catch {}
}
const result = await awaitShareEcho(
const result = await awaitShareEchoCompat(
groupCredential,
shareCredential,
{ relays, timeout: timeoutMs, eventConfig: { enableLogging: debugEnabled, customLogger: debugLogger } }
Expand Down
156 changes: 156 additions & 0 deletions src/keyset/awaitShareEchoCompat.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import {
createBifrostNode,
connectNode,
cleanupBifrostNode,
decodeShare,
decodeGroup,
DEFAULT_ECHO_RELAYS,
type NodeEventConfig
} from '@frostr/igloo-core';

export type AwaitShareEchoOptions = {
relays?: string[];
timeout?: number;
eventConfig?: NodeEventConfig;
};

const HEX_CHALLENGE_REGEX = /^[0-9a-f]+$/i;

function resolveEchoRelays(groupCredential: string, explicitRelays?: string[]): string[] {
if (Array.isArray(explicitRelays) && explicitRelays.length > 0) {
return explicitRelays;
}
try {
const decoded: any = decodeGroup(groupCredential);
const relays: unknown = decoded?.relays ?? decoded?.relayUrls ?? decoded?.relay_urls;
if (Array.isArray(relays) && relays.length > 0) {
return relays.filter((relay): relay is string => typeof relay === 'string' && relay.length > 0);
}
} catch {
// If group decoding fails we fall back to defaults.
}
return DEFAULT_ECHO_RELAYS;
}

function isHexChallenge(input: unknown): boolean {
if (typeof input !== 'string') return false;
const trimmed = input.trim();
if (trimmed.length === 0 || trimmed.length % 2 !== 0) {
return false;
}
return HEX_CHALLENGE_REGEX.test(trimmed);
}

export function isEchoConfirmationPayload(data: unknown): boolean {
if (typeof data !== 'string') return false;
const trimmed = data.trim();
if (trimmed.length === 0) return false;
if (trimmed.toLowerCase() === 'echo') return true;
return isHexChallenge(trimmed);
}

export async function awaitShareEchoCompat(
groupCredential: string,
shareCredential: string,
{relays, timeout = 30_000, eventConfig = {}}: AwaitShareEchoOptions = {}
): Promise<boolean> {
const shareDetails = decodeShare(shareCredential);
const resolvedRelays = resolveEchoRelays(groupCredential, relays);

let node: any | null = null;
let timeoutId: NodeJS.Timeout | null = null;
let settled = false;

const cleanup = () => {
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = null;
}
if (node) {
cleanupBifrostNode(node);
node = null;
}
};

const prefixLogger = (level: string, message: string, payload?: unknown) => {
const prefix = `[awaitShareEcho:${shareDetails.idx}] ${message}`;
if (eventConfig.customLogger) {
eventConfig.customLogger(level, prefix, payload);
} else if (eventConfig.enableLogging) {
// eslint-disable-next-line no-console
console.log(prefix, payload ?? '');
}
};

return new Promise<boolean>((resolve, reject) => {
const safeResolve = (value: boolean) => {
if (settled) return;
settled = true;
cleanup();
resolve(value);
};

const safeReject = (error: unknown) => {
if (settled) return;
settled = true;
cleanup();
const err = error instanceof Error ? error : new Error(String(error));
reject(err);
};

try {
const mergedEventConfig: NodeEventConfig = {
...eventConfig,
customLogger: prefixLogger
};

node = createBifrostNode(
{group: groupCredential, share: shareCredential, relays: resolvedRelays},
mergedEventConfig
);

const onMessage = (payload: any) => {
if (!payload || payload.tag !== '/echo/req') {
return;
}
if (!isEchoConfirmationPayload(payload.data)) {
return;
}
prefixLogger('info', 'Echo confirmation received', payload);
safeResolve(true);
};

const onError = (error: unknown) => {
prefixLogger('error', 'Node error while waiting for echo', error);
safeReject(error);
};

const onClosed = () => {
if (settled) return;
prefixLogger('warn', 'Connection closed before echo arrived');
safeReject(new Error('Connection closed before echo confirmation was received.'));
};

node.on('message', onMessage);
node.on('error', onError);
node.on('closed', onClosed);

timeoutId = setTimeout(() => {
safeReject(new Error(`No echo confirmation within ${timeout / 1000}s.`));
}, timeout);

void connectNode(node)
.then(() => {
if (settled) {
return;
}
prefixLogger('info', 'Listening for echo confirmation');
})
.catch(error => {
safeReject(error);
});
} catch (error) {
safeReject(error);
}
});
}
25 changes: 25 additions & 0 deletions tests/awaitShareEchoCompat.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {isEchoConfirmationPayload} from '../src/keyset/awaitShareEchoCompat.js';

test('isEchoConfirmationPayload accepts legacy "echo" token', () => {
assert.equal(isEchoConfirmationPayload('echo'), true);
assert.equal(isEchoConfirmationPayload(' ECHO '), true);
});

test('isEchoConfirmationPayload accepts even-length hex challenges', () => {
assert.equal(
isEchoConfirmationPayload('810907ac3915c5d4f50e6751ea476b708fe7178f53711d1a185bb3d49987b3d4'),
true
);
assert.equal(isEchoConfirmationPayload('aaff00cc'), true);
});

test('isEchoConfirmationPayload rejects invalid payloads', () => {
assert.equal(isEchoConfirmationPayload(''), false);
assert.equal(isEchoConfirmationPayload(' '), false);
assert.equal(isEchoConfirmationPayload('abc'), false); // odd length
assert.equal(isEchoConfirmationPayload('xyz123'), false); // non-hex
assert.equal(isEchoConfirmationPayload(undefined), false);
assert.equal(isEchoConfirmationPayload(null), false);
});