All files / src/sessionkey wallet.ts

22.85% Statements 24/105
30.23% Branches 13/43
20% Functions 5/25
23.52% Lines 24/102

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 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 36438x               1x       1x                     1x 1x                                                                                                 1x                 1x 9x 9x       9x                 9x     9x   9x 7x 7x 7x 7x 7x 2x 2x                                                                                                 4x                 2x                 2x                                                                                                                                                                                                                                                                                                                                                                                   1x  
import {
    AnyAction,
    Checksum256,
    Name,
    NameType,
    PrivateKey,
    PublicKey,
    Transaction,
} from '@wharfkit/antelope'
 
import {LogoutContext} from '../kit'
import {LoginContext} from '../login'
import {Session} from '../session'
import {TransactContext} from '../transact'
import {
    AbstractWalletPlugin,
    SerializedWalletPlugin,
    WalletPlugin,
    WalletPluginConfig,
    WalletPluginData,
    WalletPluginLoginResponse,
    WalletPluginMetadata,
    WalletPluginSignResponse,
} from '../wallet'
import {Contract as SystemContract} from './systemcontract'
import {SessionKeyWalletInterface, SessionKeyWhitelistEntry} from './types'
 
/**
 * Options for creating a new [[SessionKeyWalletPlugin]] instance.
 */
export interface SessionKeyWalletPluginOptions {
    /** The user's primary wallet that will be used for non-whitelisted actions. */
    primaryWallet: WalletPlugin
    /** The private key for the session key. */
    privateKey: PrivateKey
    /** The permission name the session key operates under. */
    permission: NameType
    /** The whitelist of contracts and actions this session key can sign. */
    whitelist: SessionKeyWhitelistEntry[]
}
 
/**
 * Options for restoring a [[SessionKeyWalletPlugin]] from serialized data.
 */
export interface SessionKeyWalletPluginRestoreOptions {
    /** Available wallet plugins for restoring the primary wallet. */
    walletPlugins: WalletPlugin[]
}
 
/**
 * Serialized form of a whitelist entry.
 */
export interface SerializedSessionKeyWalletEntry {
    /** Contract account name. */
    contract: string
    /** Optional array of action names. If omitted, all actions on the contract are allowed. */
    actions?: string[]
}
 
/**
 * The serialized form of a [[SessionKeyWalletPlugin]].
 */
export interface SerializedSessionKeyWallet {
    /** Serialized primary wallet plugin. */
    primaryWallet: SerializedWalletPlugin
    /** Private key as a string. */
    privateKey: string
    /** Permission name as a string. */
    permission: string
    /** Serialized whitelist entries. */
    whitelist: SerializedSessionKeyWalletEntry[]
}
 
let sessionKeyLogoutInProgress = false
 
/**
 * Wallet plugin that wraps a primary wallet and routes transactions based on whitelist.
 * Whitelisted actions are signed with the session key, others fall back to primary wallet.
 */
export class SessionKeyWalletPlugin
    extends AbstractWalletPlugin
    implements SessionKeyWalletInterface
{
    public readonly id = 'session-key-wallet'
    readonly config: WalletPluginConfig = {
        requiresChainSelect: false,
        requiresPermissionSelect: false,
    }
    readonly metadata: WalletPluginMetadata = WalletPluginMetadata.from({
        name: 'Session Key Wallet',
        description: 'A wrapper wallet that routes transactions based on whitelist',
    })
 
    private primaryWallet!: WalletPlugin
    private privateKey!: PrivateKey
    private permission!: Name
    private whitelist!: SessionKeyWhitelistEntry[]
    private walletPlugins: WalletPlugin[] = []
 
    constructor(options?: SessionKeyWalletPluginOptions | SessionKeyWalletPluginRestoreOptions) {
        super()
 
        if (options && 'primaryWallet' in options) {
            this.primaryWallet = options.primaryWallet
            this.privateKey = PrivateKey.from(options.privateKey)
            this.permission = Name.from(options.permission)
            this.whitelist = options.whitelist
            this.metadata.publicKey = String(this.privateKey.toPublic())
        } else if (options && 'walletPlugins' in options) {
            this.walletPlugins = options.walletPlugins
        }
    }
 
    get data(): WalletPluginData {
        return {
            primaryWallet: this.primaryWallet.serialize(),
            privateKey: String(this.privateKey),
            permission: String(this.permission),
            whitelist: this.whitelist.map((entry) => ({
                contract: String(entry.contract),
                actions: entry.actions?.map((a) => String(a)),
            })),
        }
    }
 
    set data(data: WalletPluginData) {
        const serialized = data as SerializedSessionKeyWallet
        this.privateKey = PrivateKey.from(serialized.privateKey)
        this.permission = Name.from(serialized.permission)
        this.whitelist = serialized.whitelist.map((entry) => ({
            contract: Name.from(entry.contract),
            actions: entry.actions?.map((a) => Name.from(a)),
        }))
        this.metadata.publicKey = String(this.privateKey.toPublic())
 
        Iif (serialized.primaryWallet) {
            const primaryPlugin = this.walletPlugins.find(
                (p) => p.id === serialized.primaryWallet.id
            )
            if (primaryPlugin) {
                Iif (serialized.primaryWallet.data) {
                    primaryPlugin.data = serialized.primaryWallet.data
                }
                this.primaryWallet = primaryPlugin
            } else {
                throw new Error(
                    `Cannot restore session key: primary wallet plugin '${serialized.primaryWallet.id}' not found`
                )
            }
        }
    }
 
    /**
     * Get the primary wallet that this session key wallet wraps.
     *
     * @returns The primary wallet plugin
     */
    getPrimaryWallet(): WalletPlugin {
        return this.primaryWallet
    }
 
    /**
     * Get the permission name the session key operates under.
     *
     * @returns The permission name
     */
    getPermission(): Name {
        return this.permission
    }
 
    /**
     * Get the public key of the session key.
     *
     * @returns The public key as a string
     */
    getPublicKey(): string {
        return String(this.privateKey.toPublic())
    }
 
    /**
     * Get the whitelist of contracts and actions this session key can sign.
     *
     * @returns Array of whitelist entries
     */
    getWhitelist(): SessionKeyWhitelistEntry[] {
        return this.whitelist
    }
 
    /**
     * Check if an action is whitelisted for signing with the session key.
     *
     * @param action The action to check
     * @returns True if the action is whitelisted
     */
    isWhitelisted(action: AnyAction): boolean {
        const actionContract = Name.from(action.account)
        const actionName = Name.from(action.name)
 
        for (const entry of this.whitelist) {
            Iif (Name.from(entry.contract).equals(actionContract)) {
                Iif (!entry.actions || entry.actions.length === 0) {
                    return true
                }
                for (const allowedAction of entry.actions) {
                    Iif (actionName.equals(allowedAction)) {
                        return true
                    }
                }
            }
        }
        return false
    }
 
    /**
     * Check if all actions in a transaction are whitelisted.
     *
     * @param actions Array of actions to check
     * @returns True if all actions are whitelisted
     */
    allActionsWhitelisted(actions: AnyAction[]): boolean {
        return actions.every((action) => this.isWhitelisted(action))
    }
 
    login(context: LoginContext): Promise<WalletPluginLoginResponse> {
        return this.primaryWallet.login(context)
    }
 
    async logout(context: LogoutContext): Promise<void> {
        Iif (!this.privateKey || !context.ui?.onSessionKeyRemove || sessionKeyLogoutInProgress) {
            return
        }
 
        sessionKeyLogoutInProgress = true
        try {
            const shouldRemove = await context.ui.onSessionKeyRemove({appName: context.appName})
            Iif (!shouldRemove) {
                return
            }
 
            const session = context.session
            const actor = session.actor
            const client = session.client
            const publicKey = this.privateKey.toPublic()
 
            const accountData = await client.v1.chain.get_account(actor)
            const permData = accountData.permissions.find((p) =>
                this.permission.equals(p.perm_name)
            )
 
            Iif (!permData) {
                return
            }
 
            const ourKeyIndex = permData.required_auth.keys.findIndex((k) =>
                PublicKey.from(k.key).equals(publicKey)
            )
 
            Iif (ourKeyIndex === -1) {
                return
            }
 
            const remainingKeys = permData.required_auth.keys.filter((_, i) => i !== ourKeyIndex)
            const systemContract = new SystemContract({client})
            const actions: AnyAction[] = []
 
            const primarySession = new Session(
                {
                    chain: session.chain,
                    permissionLevel: session.permissionLevel,
                    walletPlugin: this.primaryWallet,
                },
                {
                    fetch: session.fetch,
                    ui: context.ui,
                }
            )
 
            if (remainingKeys.length > 0) {
                actions.push(
                    systemContract.action(
                        'updateauth',
                        {
                            account: actor,
                            permission: this.permission,
                            parent: 'active',
                            auth: {
                                ...permData.required_auth,
                                keys: remainingKeys,
                            },
                        },
                        {authorization: [session.permissionLevel]}
                    )
                )
            } else {
                const linkedActions = permData.linked_actions || []
                for (const link of linkedActions) {
                    actions.push(
                        systemContract.action(
                            'unlinkauth',
                            {
                                account: actor,
                                code: link.account,
                                type: link.action || '',
                            },
                            {authorization: [session.permissionLevel]}
                        )
                    )
                }
 
                actions.push(
                    systemContract.action(
                        'deleteauth',
                        {
                            account: actor,
                            permission: this.permission,
                        },
                        {authorization: [session.permissionLevel]}
                    )
                )
            }
 
            await primarySession.transact({actions})
 
            Iif (this.primaryWallet?.logout) {
                await this.primaryWallet.logout(context)
            }
        } catch (error) {
            sessionKeyLogoutInProgress = false
            throw error
        } finally {
            sessionKeyLogoutInProgress = false
        }
    }
 
    async sign(resolved: any, context: TransactContext): Promise<WalletPluginSignResponse> {
        const transaction = resolved.transaction
        const actions = transaction.actions || []
 
        const hasSessionKeyAuth = actions.some((action: any) =>
            action.authorization.some((auth: any) =>
                this.permission.equals(auth.permission || auth.permission_name)
            )
        )
 
        Iif (hasSessionKeyAuth) {
            const txn = Transaction.from(transaction)
            const digest = txn.signingDigest(Checksum256.from(context.chain.id))
            const signature = this.privateKey.signDigest(digest)
            return {
                signatures: [signature],
            }
        }
 
        return this.primaryWallet.sign(resolved, context)
    }
 
    serialize(): SerializedWalletPlugin {
        return {
            id: this.id,
            data: this.data,
        }
    }
}