-
Notifications
You must be signed in to change notification settings - Fork 0
clean up echo flow once more #9
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| } | ||
| }); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| }); |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.