All files handoff.ts

93.51% Statements 101/108
73.52% Branches 50/68
100% Functions 20/20
96% Lines 96/100

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218213x             1x 1x   1x   1x                                   1x 12x 12x 12x     1x 13x 13x 13x                         1x 3x 3x 3x 3x 3x 3x       1x           4x 4x 4x 4x 4x 4x 4x 4x 4x   4x 3x 3x   4x 1x   4x 1x   4x 1x   4x 2x 1x 1x 1x     4x 1x 1x     4x 4x 4x 4x 4x 4x       1x       7x     1x         15x 15x   14x 14x   1x 1x   13x 1x 1x   12x 12x 1x 1x   11x 11x             1x       5x 5x 4x         2x                 4x 4x 4x 4x 3x 3x               3x   2x     2x 2x 2x     2x       2x           1x   1x         3x 3x 1x 1x   3x    
import {receive, ReceiveContext} from '@greymass/buoy'
import {
    AbiProvider,
    CallbackPayload,
    Cancelable,
    ResolvedSigningRequest,
    SignedTransaction,
} from '@wharfkit/session'
import * as zlib from 'pako'
 
import {extractSignaturesFromCallback, isCallback} from './esr'
 
const TRANSACTION_HANDOFF_KEY = 'wharfkit:anchor-transaction-handoff'
 
interface CallbackChannel {
    channel: string
    service: string
}
 
export interface TransactionHandoff {
    version: 1
    returnUrl: string
    callback: CallbackChannel
    transactionId: string
    chainId: string
    actor: string
    permission: string
    expiresAt: string
}
 
function isCallbackChannel(value: unknown): value is CallbackChannel {
    Iif (!value || typeof value !== 'object') return false
    const candidate = value as Record<string, unknown>
    return typeof candidate.channel === 'string' && typeof candidate.service === 'string'
}
 
function isTransactionHandoff(value: unknown): value is TransactionHandoff {
    Iif (!value || typeof value !== 'object') return false
    const candidate = value as Record<string, unknown>
    return (
        candidate.version === 1 &&
        typeof candidate.returnUrl === 'string' &&
        isCallbackChannel(candidate.callback) &&
        typeof candidate.transactionId === 'string' &&
        typeof candidate.chainId === 'string' &&
        typeof candidate.actor === 'string' &&
        typeof candidate.permission === 'string' &&
        typeof candidate.expiresAt === 'string'
    )
}
 
/** Check whether returnUrl differs from currentUrl only by a non-empty fragment. */
export function isSamePageReturn(returnUrl: string, currentUrl = window.location.href): boolean {
    const current = new URL(currentUrl)
    const target = new URL(returnUrl, current)
    const targetHash = target.hash
    current.hash = ''
    target.hash = ''
    return targetHash.length > 1 && current.href === target.href
}
 
/** Resolve once the page returns from an app handoff: the return hash arrives or the page is re-shown. */
export function waitForPageReturn(
    returnUrl: string,
    signal?: AbortSignal,
    pageWindow: Window = window,
    pageDocument: Document = document
): Promise<void> {
    const expectedHash = new URL(returnUrl, pageWindow.location.href).hash
    let departed = pageDocument.visibilityState === 'hidden'
    return new Promise<void>((resolve, reject) => {
        const cleanup = () => {
            pageWindow.removeEventListener('hashchange', onHashChange)
            pageWindow.removeEventListener('pagehide', onPageHide)
            pageWindow.removeEventListener('pageshow', onPageShow)
            pageDocument.removeEventListener('visibilitychange', onVisibilityChange)
            signal?.removeEventListener('abort', onAbort)
        }
        const finish = () => {
            cleanup()
            resolve()
        }
        const onHashChange = () => {
            if (expectedHash && pageWindow.location.hash === expectedHash) finish()
        }
        const onPageHide = () => {
            departed = true
        }
        const onPageShow = () => {
            if (departed) finish()
        }
        const onVisibilityChange = () => {
            if (pageDocument.visibilityState === 'hidden') {
                departed = true
            } else if (departed) {
                finish()
            }
        }
        const onAbort = () => {
            cleanup()
            reject(new Error('Transaction callback wait cancelled'))
        }
 
        pageWindow.addEventListener('hashchange', onHashChange)
        pageWindow.addEventListener('pagehide', onPageHide)
        pageWindow.addEventListener('pageshow', onPageShow)
        pageDocument.addEventListener('visibilitychange', onVisibilityChange)
        signal?.addEventListener('abort', onAbort, {once: true})
        Iif (signal?.aborted) onAbort()
    })
}
 
export function storeTransactionHandoff(
    handoff: TransactionHandoff,
    storage: Storage = window.localStorage
): void {
    storage.setItem(TRANSACTION_HANDOFF_KEY, JSON.stringify(handoff))
}
 
export function findReturnedTransactionHandoff(
    currentUrl = window.location.href,
    now = Date.now(),
    storage: Storage = window.localStorage
): TransactionHandoff | null {
    const encoded = storage.getItem(TRANSACTION_HANDOFF_KEY)
    if (!encoded) return null
    let handoff: unknown
    try {
        handoff = JSON.parse(encoded)
    } catch {
        storage.removeItem(TRANSACTION_HANDOFF_KEY)
        return null
    }
    if (!isTransactionHandoff(handoff)) {
        storage.removeItem(TRANSACTION_HANDOFF_KEY)
        return null
    }
    const expiresAt = Date.parse(handoff.expiresAt)
    if (!Number.isFinite(expiresAt) || expiresAt <= now) {
        storage.removeItem(TRANSACTION_HANDOFF_KEY)
        return null
    }
    try {
        return new URL(currentUrl).href === new URL(handoff.returnUrl).href ? handoff : null
    } catch {
        storage.removeItem(TRANSACTION_HANDOFF_KEY)
        return null
    }
}
 
export function clearTransactionHandoff(
    handoff: TransactionHandoff,
    storage: Storage = window.localStorage
): void {
    const current = findReturnedTransactionHandoff(handoff.returnUrl, 0, storage)
    if (current?.returnUrl === handoff.returnUrl) {
        storage.removeItem(TRANSACTION_HANDOFF_KEY)
    }
}
 
/** Receive the buffered signed transaction for a stored handoff, or null when none matches the current URL. */
export function receiveReturnedTransaction(options: {
    currentUrl?: string
    now?: number
    storage?: Storage
    WebSocket?: typeof WebSocket
    /** @internal */
    receive?: typeof receive
    abiProvider: AbiProvider
}): Cancelable<SignedTransaction> | null {
    const storage = options.storage ?? window.localStorage
    const now = options.now ?? Date.now()
    const handoff = findReturnedTransactionHandoff(options.currentUrl, now, storage)
    if (!handoff) return null
    const ctx: ReceiveContext = {}
    const pending = (options.receive ?? receive)(
        {
            ...handoff.callback,
            WebSocket: options.WebSocket ?? WebSocket,
            timeout: Math.max(1, Date.parse(handoff.expiresAt) - now),
        },
        ctx
    )
    const transaction = pending
        .then(async (response) => {
            Iif (typeof response !== 'string') {
                throw new Error('Anchor did not return a signed transaction')
            }
            const payload: CallbackPayload = JSON.parse(response)
            const signatures = extractSignaturesFromCallback(payload)
            Iif (!isCallback(payload) || signatures.length === 0) {
                throw new Error('Anchor did not return a signed transaction')
            }
            const resolved = await ResolvedSigningRequest.fromPayload(payload, {
                zlib,
                abiProvider: options.abiProvider,
            })
            if (
                String(resolved.transaction.id) !== handoff.transactionId ||
                String(resolved.chainId) !== handoff.chainId ||
                String(resolved.signer.actor) !== handoff.actor ||
                String(resolved.signer.permission) !== handoff.permission
            ) {
                throw new Error('Anchor returned a different transaction')
            }
            return SignedTransaction.from({
                ...resolved.transaction,
                signatures,
            })
        })
        .finally(() => clearTransactionHandoff(handoff, storage)) as Cancelable<SignedTransaction>
    transaction.cancel = () => {
        ctx.cancel?.()
        return transaction
    }
    return transaction
}