|
1 | 1 | import { produce } from 'immer'; |
2 | 2 | import { PersistentStore } from 'src/modules/persistent-store'; |
3 | | -import type { Credentials } from '../account/Credentials'; |
| 3 | +import { invariant } from 'src/shared/invariant'; |
| 4 | +import { getError } from 'src/shared/errors/getError'; |
| 5 | +import { ErrorWithEnumerableMessage } from 'src/shared/errors/errors'; |
| 6 | +import type { User } from 'src/shared/types/User'; |
| 7 | +import type { Credentials, SessionCredentials } from '../account/Credentials'; |
| 8 | +import { emitter } from '../events'; |
| 9 | +import { Account } from '../account/Account'; |
4 | 10 | import type { WalletRecord } from './model/types'; |
5 | 11 | import { WalletRecordModel as Model } from './WalletRecord'; |
6 | 12 |
|
7 | 13 | type EncryptedWalletRecord = string; |
8 | 14 |
|
9 | 15 | type WalletStoreState = Record<string, EncryptedWalletRecord | undefined>; |
10 | 16 |
|
| 17 | +export class InternalBackupError extends ErrorWithEnumerableMessage { |
| 18 | + didRestore: boolean; |
| 19 | + constructor(error: Error, { didRestore }: { didRestore: boolean }) { |
| 20 | + super(error.message); |
| 21 | + this.name = error.name !== 'Error' ? error.name : 'InternalBackupError'; |
| 22 | + this.didRestore = didRestore; |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +type RecordBackup = { user: User; record: string }; |
| 27 | +function stringifyBackup({ user, record }: RecordBackup): string { |
| 28 | + return JSON.stringify({ user, record }); |
| 29 | +} |
| 30 | + |
| 31 | +function parseBackup(value: string): RecordBackup { |
| 32 | + const parsed = JSON.parse(value) as RecordBackup; |
| 33 | + invariant(parsed.user, 'User not found in backup'); |
| 34 | + invariant(parsed.record, 'Record not found in backup'); |
| 35 | + return parsed; |
| 36 | +} |
| 37 | + |
11 | 38 | export class WalletStore extends PersistentStore<WalletStoreState> { |
12 | 39 | static key = 'wallet'; |
13 | 40 | /** Store unencrypted "lastRecord" to avoid unnecessary stringifications */ |
@@ -42,25 +69,130 @@ export class WalletStore extends PersistentStore<WalletStoreState> { |
42 | 69 | } |
43 | 70 |
|
44 | 71 | /** Prefer WalletStore['save'] unless necessary */ |
45 | | - async encryptAndSave( |
| 72 | + private async encryptAndSave( |
46 | 73 | id: string, |
47 | | - encryptionKey: string, |
| 74 | + credentials: Credentials, |
48 | 75 | record: WalletRecord |
49 | 76 | ) { |
50 | | - const encryptedRecord = await Model.encryptRecord(encryptionKey, record); |
51 | | - this.setState((state) => |
| 77 | + const encryptedRecord = await Model.encryptRecord( |
| 78 | + credentials.encryptionKey, |
| 79 | + record |
| 80 | + ); |
| 81 | + await this.setState((state) => |
52 | 82 | produce(state, (draft) => { |
53 | 83 | draft[id] = encryptedRecord; |
54 | 84 | }) |
55 | 85 | ); |
56 | 86 | this.lastRecord = record; |
57 | 87 | } |
58 | 88 |
|
59 | | - async save(id: string, encryptionKey: string, record: WalletRecord) { |
| 89 | + async save(id: string, credentials: Credentials, record: WalletRecord) { |
60 | 90 | if (this.lastRecord === record) { |
61 | 91 | return; |
62 | 92 | } |
63 | | - await this.encryptAndSave(id, encryptionKey, record); |
| 93 | + await this.encryptAndSave(id, credentials, record); |
| 94 | + } |
| 95 | + |
| 96 | + async createBackup(id: string) { |
| 97 | + /** |
| 98 | + * Accessing user is a cross-concern, but this is the only way |
| 99 | + * to make our backup truly atomic and independent: |
| 100 | + * encrypted record relies on `salt` stored in the user object, |
| 101 | + * and for a robust backup recovery it's best to store this object |
| 102 | + * together with the encrypted record |
| 103 | + */ |
| 104 | + const user = await Account.readCurrentUser(); |
| 105 | + const record = (await this.getSavedState())[id]; |
| 106 | + invariant(record, `Record not found for id: ${id}`); |
| 107 | + invariant(user && user.id === id, `User not found for id: ${id}`); |
| 108 | + return this.setState({ |
| 109 | + ...this.state, |
| 110 | + [`backup:${id}`]: stringifyBackup({ user, record }), |
| 111 | + }); |
| 112 | + } |
| 113 | + |
| 114 | + async restoreFromBackup(id: string) { |
| 115 | + const key = `backup:${id}`; |
| 116 | + const state = await this.getSavedState(); |
| 117 | + const saved = state[key]; |
| 118 | + invariant(saved, `Backup not found for id: ${id}`); |
| 119 | + const { user, record } = parseBackup(saved); |
| 120 | + await Promise.all([ |
| 121 | + this.setState((state) => |
| 122 | + produce(state, (draft) => { |
| 123 | + draft[id] = record; |
| 124 | + delete draft[key]; |
| 125 | + }) |
| 126 | + ), |
| 127 | + Account.writeCurrentUser(user), |
| 128 | + ]); |
| 129 | + } |
| 130 | + |
| 131 | + async restoreFromAnyBackup() { |
| 132 | + const state = await this.getSavedState(); |
| 133 | + const key = Object.keys(state).find((key) => key.startsWith('backup:')); |
| 134 | + if (key) { |
| 135 | + await this.restoreFromBackup(key.split(':')[1]); |
| 136 | + } else { |
| 137 | + throw new Error('No backups found'); |
| 138 | + } |
| 139 | + } |
| 140 | + |
| 141 | + async clearBackup(id: string) { |
| 142 | + return this.setState((state) => |
| 143 | + produce(state, (draft) => { |
| 144 | + const key = `backup:${id}`; |
| 145 | + delete draft[key]; |
| 146 | + }) |
| 147 | + ); |
| 148 | + } |
| 149 | + |
| 150 | + /** |
| 151 | + * Executes an operation with a backup and an automatic recovery. |
| 152 | + * Guarantees atomicity by restoring to the previous state if the operation fails. |
| 153 | + */ |
| 154 | + async withBackup(id: string, operation: () => Promise<unknown>) { |
| 155 | + await this.createBackup(id); |
| 156 | + try { |
| 157 | + await operation(); |
| 158 | + await this.clearBackup(id); |
| 159 | + } catch (error) { |
| 160 | + try { |
| 161 | + await this.restoreFromBackup(id); |
| 162 | + emitter.emit('globalError', { |
| 163 | + name: 'internal_error', |
| 164 | + message: 'Atomic wallet update failed. Restored from backup.', |
| 165 | + }); |
| 166 | + console.log('Successfully restored wallet record from backup'); // eslint-disable-line no-console |
| 167 | + } catch { |
| 168 | + emitter.emit('globalError', { |
| 169 | + name: 'internal_error', |
| 170 | + message: 'Atomic wallet update failed. Restore from backup failed.', |
| 171 | + }); |
| 172 | + throw new InternalBackupError(getError(error), { didRestore: false }); |
| 173 | + } |
| 174 | + throw error; |
| 175 | + } |
| 176 | + } |
| 177 | + |
| 178 | + async reEncrypt({ |
| 179 | + id, |
| 180 | + credentials, |
| 181 | + newCredentials, |
| 182 | + }: { |
| 183 | + id: string; |
| 184 | + credentials: SessionCredentials; |
| 185 | + newCredentials: SessionCredentials; |
| 186 | + }) { |
| 187 | + await this.ready(); |
| 188 | + console.log('reading', { id, credentials, state: this.getState() }); |
| 189 | + const currentRecord = await this.read(id, credentials); |
| 190 | + invariant(currentRecord, `Record not found for ${id}`); |
| 191 | + const newRecord = await Model.reEncryptRecord(currentRecord, { |
| 192 | + credentials, |
| 193 | + newCredentials, |
| 194 | + }); |
| 195 | + await this.encryptAndSave(id, newCredentials, newRecord); |
64 | 196 | } |
65 | 197 |
|
66 | 198 | deleteMany(keys: string[]) { |
|
0 commit comments