|
| 1 | +/** |
| 2 | + * Singleton encryption service using Web Worker. |
| 3 | + * This offloads CPU-intensive AES encryption operations to a separate thread. |
| 4 | + * Works in both browser and Node.js environments via platform-specific config. |
| 5 | + * |
| 6 | + * The worker is lazily initialized on first use and shared across all consumers. |
| 7 | + */ |
| 8 | +import { wrap, releaseProxy, transfer, type Remote } from 'comlink' |
| 9 | +import { Lifecycle, scoped } from 'tsyringe' |
| 10 | +import { EncryptedGroupKey } from '@streamr/trackerless-network' |
| 11 | +import { createEncryptionWorker } from '@/createEncryptionWorker' |
| 12 | +import type { EncryptionWorkerApi } from './EncryptionWorker' |
| 13 | +import { DestroySignal } from '../DestroySignal' |
| 14 | +import { StreamrClientError } from '../StreamrClientError' |
| 15 | +import { GroupKey } from './GroupKey' |
| 16 | + |
| 17 | +@scoped(Lifecycle.ContainerScoped) |
| 18 | +export class EncryptionService { |
| 19 | + private worker: ReturnType<typeof createEncryptionWorker> | undefined |
| 20 | + private workerApi: Remote<EncryptionWorkerApi> | undefined |
| 21 | + |
| 22 | + constructor(destroySignal: DestroySignal) { |
| 23 | + destroySignal.onDestroy.listen(() => this.destroy()) |
| 24 | + } |
| 25 | + |
| 26 | + private getWorkerApi(): Remote<EncryptionWorkerApi> { |
| 27 | + if (this.workerApi === undefined) { |
| 28 | + this.worker = createEncryptionWorker() |
| 29 | + this.workerApi = wrap<EncryptionWorkerApi>(this.worker) |
| 30 | + } |
| 31 | + return this.workerApi |
| 32 | + } |
| 33 | + |
| 34 | + /** |
| 35 | + * Encrypt data using AES-256-CTR. |
| 36 | + * Note: The input data buffer is transferred to the worker and becomes unusable after this call. |
| 37 | + */ |
| 38 | + async encryptWithAES(data: Uint8Array, cipherKey: Uint8Array): Promise<Uint8Array> { |
| 39 | + const result = await this.getWorkerApi().encrypt( |
| 40 | + transfer({ data, cipherKey }, [data.buffer]) |
| 41 | + ) |
| 42 | + if (result.type === 'error') { |
| 43 | + throw new Error(`AES encryption failed: ${result.message}`) |
| 44 | + } |
| 45 | + return result.data |
| 46 | + } |
| 47 | + |
| 48 | + /** |
| 49 | + * Decrypt AES-256-CTR encrypted data. |
| 50 | + * Note: The input cipher buffer is transferred to the worker and becomes unusable after this call. |
| 51 | + */ |
| 52 | + async decryptWithAES(cipher: Uint8Array, cipherKey: Uint8Array): Promise<Uint8Array> { |
| 53 | + const result = await this.getWorkerApi().decrypt( |
| 54 | + transfer({ cipher, cipherKey }, [cipher.buffer]) |
| 55 | + ) |
| 56 | + if (result.type === 'error') { |
| 57 | + throw new Error(`AES decryption failed: ${result.message}`) |
| 58 | + } |
| 59 | + return result.data |
| 60 | + } |
| 61 | + |
| 62 | + /** |
| 63 | + * Encrypt the next group key using the current group key. |
| 64 | + */ |
| 65 | + async encryptNextGroupKey(currentKey: GroupKey, nextKey: GroupKey): Promise<EncryptedGroupKey> { |
| 66 | + const result = await this.getWorkerApi().encryptGroupKey({ |
| 67 | + nextGroupKeyId: nextKey.id, |
| 68 | + nextGroupKeyData: nextKey.data, |
| 69 | + currentGroupKeyData: currentKey.data |
| 70 | + }) |
| 71 | + if (result.type === 'error') { |
| 72 | + throw new Error(`Group key encryption failed: ${result.message}`) |
| 73 | + } |
| 74 | + return { |
| 75 | + id: result.id, |
| 76 | + data: result.data |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + /** |
| 81 | + * Decrypt an encrypted group key using the current group key. |
| 82 | + */ |
| 83 | + async decryptNextGroupKey(currentKey: GroupKey, encryptedKey: EncryptedGroupKey): Promise<GroupKey> { |
| 84 | + const result = await this.getWorkerApi().decryptGroupKey({ |
| 85 | + encryptedGroupKeyId: encryptedKey.id, |
| 86 | + encryptedGroupKeyData: encryptedKey.data, |
| 87 | + currentGroupKeyData: currentKey.data |
| 88 | + }) |
| 89 | + if (result.type === 'error') { |
| 90 | + throw new Error(`Group key decryption failed: ${result.message}`) |
| 91 | + } |
| 92 | + return new GroupKey(result.id, Buffer.from(result.data)) |
| 93 | + } |
| 94 | + |
| 95 | + /** |
| 96 | + * Decrypt a stream message's content and optionally the new group key. |
| 97 | + * This combines both operations for efficiency when processing messages. |
| 98 | + * Note: The input content buffer is transferred to the worker and becomes unusable after this call. |
| 99 | + */ |
| 100 | + async decryptStreamMessage( |
| 101 | + content: Uint8Array, |
| 102 | + groupKey: GroupKey, |
| 103 | + encryptedNewGroupKey?: EncryptedGroupKey |
| 104 | + ): Promise<[Uint8Array, GroupKey?]> { |
| 105 | + const request = { |
| 106 | + content, |
| 107 | + groupKeyData: groupKey.data, |
| 108 | + newGroupKey: encryptedNewGroupKey ? { |
| 109 | + id: encryptedNewGroupKey.id, |
| 110 | + data: encryptedNewGroupKey.data |
| 111 | + } : undefined |
| 112 | + } |
| 113 | + const result = await this.getWorkerApi().decryptStreamMessage( |
| 114 | + transfer(request, [content.buffer]) |
| 115 | + ) |
| 116 | + if (result.type === 'error') { |
| 117 | + throw new StreamrClientError(`AES decryption failed: ${result.message}`, 'DECRYPT_ERROR') |
| 118 | + } |
| 119 | + |
| 120 | + let newGroupKey: GroupKey | undefined |
| 121 | + if (result.newGroupKey) { |
| 122 | + newGroupKey = new GroupKey(result.newGroupKey.id, Buffer.from(result.newGroupKey.data)) |
| 123 | + } |
| 124 | + |
| 125 | + return [result.content, newGroupKey] |
| 126 | + } |
| 127 | + |
| 128 | + destroy(): void { |
| 129 | + if (this.workerApi !== undefined) { |
| 130 | + this.workerApi[releaseProxy]() |
| 131 | + this.workerApi = undefined |
| 132 | + } |
| 133 | + if (this.worker !== undefined) { |
| 134 | + this.worker.terminate() |
| 135 | + this.worker = undefined |
| 136 | + } |
| 137 | + } |
| 138 | +} |
0 commit comments