|
| 1 | +import type { Collection } from '@tanstack/react-db' |
| 2 | +import { isLocalhostConnectionString } from '@conar/connection/utils' |
| 3 | +import { decryptWithKey, encryptWithKey } from '@conar/shared/utils/crypto-web' |
| 4 | +import { decryptWithPrivateKey, generateEncryptionKeyPair } from '@conar/shared/utils/pair-keys' |
| 5 | +import { SafeURL } from '@conar/shared/utils/safe-url' |
| 6 | +import { persistedCollectionOptions } from '@tanstack/browser-db-sqlite-persistence' |
| 7 | +import { BasicIndex, createCollection } from '@tanstack/react-db' |
| 8 | +import { encryptionKeyStorage, getEncryptionKey, resetEncryptionKey } from '~/lib/encryption-key-storage' |
| 9 | +import { orpc } from '~/lib/orpc' |
| 10 | +import { persistence } from '~/lib/sync' |
| 11 | + |
| 12 | +interface StoredConnectionString { |
| 13 | + id: string |
| 14 | + encrypted: string |
| 15 | + updatedAt: Date |
| 16 | + metadata: { |
| 17 | + isPasswordPopulated: boolean |
| 18 | + isLocalhost: boolean |
| 19 | + displayUrl: string |
| 20 | + defaultResourceName: string | null |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +const resolvePromises = new Map<string, Promise<void>>() |
| 25 | + |
| 26 | +async function encryptValue(connectionString: string) { |
| 27 | + return encryptWithKey(await getEncryptionKey(), connectionString) |
| 28 | +} |
| 29 | + |
| 30 | +async function decryptValue(encryptedConnectionString: string) { |
| 31 | + return decryptWithKey(await getEncryptionKey(), encryptedConnectionString) |
| 32 | +} |
| 33 | + |
| 34 | +function buildRecord(id: string, connectionString: string, encrypted: string, updatedAt: Date): StoredConnectionString { |
| 35 | + const url = new SafeURL(connectionString) |
| 36 | + |
| 37 | + return { |
| 38 | + id, |
| 39 | + encrypted, |
| 40 | + updatedAt, |
| 41 | + metadata: { |
| 42 | + isPasswordPopulated: !!url.password, |
| 43 | + isLocalhost: isLocalhostConnectionString(connectionString), |
| 44 | + displayUrl: `${url.hostname}${url.port ? `:${url.port}` : ''}`, |
| 45 | + defaultResourceName: url.pathname && url.pathname !== '/' ? url.pathname.slice(1) : null, |
| 46 | + }, |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +// eslint-disable-next-line ts/consistent-type-definitions |
| 51 | +type ConnectionStringsUtils = { |
| 52 | + decrypt: (id: string) => Promise<string> |
| 53 | + upsert: (id: string, connectionString: string, updatedAt: Date) => Promise<void> |
| 54 | + ready: () => Promise<void> |
| 55 | + resolve: (id: string) => Promise<void> |
| 56 | +} |
| 57 | + |
| 58 | +type ConnectionStringsCollection = Collection<StoredConnectionString, string, ConnectionStringsUtils> |
| 59 | + |
| 60 | +export function createConnectionStringsCollection() { |
| 61 | + const connectionStringsCollection: ConnectionStringsCollection = createCollection(persistedCollectionOptions<StoredConnectionString, string, never, ConnectionStringsUtils>({ |
| 62 | + id: 'connection-strings', |
| 63 | + persistence, |
| 64 | + autoIndex: 'eager', |
| 65 | + gcTime: 1, |
| 66 | + defaultIndexType: BasicIndex, |
| 67 | + schemaVersion: 1, |
| 68 | + getKey: item => item.id, |
| 69 | + utils: { |
| 70 | + async decrypt(id: string): Promise<string> { |
| 71 | + const record = connectionStringsCollection.get(id) |
| 72 | + if (!record) |
| 73 | + throw new Error(`No connection string found for connection "${id}"`) |
| 74 | + |
| 75 | + try { |
| 76 | + return await decryptValue(record.encrypted) |
| 77 | + } |
| 78 | + catch (error) { |
| 79 | + await resetEncryptionKey() |
| 80 | + throw error |
| 81 | + } |
| 82 | + }, |
| 83 | + async upsert(id: string, connectionString: string, updatedAt: Date): Promise<void> { |
| 84 | + const encrypted = await encryptValue(connectionString) |
| 85 | + const record = buildRecord(id, connectionString, encrypted, updatedAt) |
| 86 | + |
| 87 | + if (connectionStringsCollection.has(id)) { |
| 88 | + connectionStringsCollection.update(id, draft => Object.assign(draft, record)) |
| 89 | + } |
| 90 | + else { |
| 91 | + connectionStringsCollection.insert(record) |
| 92 | + } |
| 93 | + }, |
| 94 | + async ready() { |
| 95 | + await Promise.all([ |
| 96 | + encryptionKeyStorage.ready, |
| 97 | + connectionStringsCollection.stateWhenReady(), |
| 98 | + Promise.allSettled(resolvePromises.values()), |
| 99 | + ]) |
| 100 | + }, |
| 101 | + async resolve(id: string) { |
| 102 | + // await connectionStringsCollection.waitFor('index:added') |
| 103 | + const existing = resolvePromises.get(id) |
| 104 | + if (existing) |
| 105 | + return existing |
| 106 | + |
| 107 | + const local = connectionStringsCollection.get(id) |
| 108 | + |
| 109 | + const promise = (async () => { |
| 110 | + const { publicKey, privateKey } = await generateEncryptionKeyPair() |
| 111 | + const result = await orpc.connections.resolve.call({ id, publicKey, updatedAt: local?.updatedAt }) |
| 112 | + |
| 113 | + if (result.status === 'unchanged') |
| 114 | + return |
| 115 | + |
| 116 | + const connectionString = await decryptWithPrivateKey(privateKey, result.connectionString) |
| 117 | + await connectionStringsCollection.utils.upsert(id, await preserveLocalPassword(id, connectionString), result.updatedAt) |
| 118 | + })().finally(() => { |
| 119 | + resolvePromises.delete(id) |
| 120 | + }) |
| 121 | + |
| 122 | + resolvePromises.set(id, promise) |
| 123 | + return promise |
| 124 | + }, |
| 125 | + }, |
| 126 | + })) |
| 127 | + |
| 128 | + async function preserveLocalPassword(id: string, connectionString: string) { |
| 129 | + const url = new SafeURL(connectionString) |
| 130 | + const local = connectionStringsCollection.get(id) |
| 131 | + |
| 132 | + if (!url.password && local?.metadata.isPasswordPopulated) { |
| 133 | + url.password = new SafeURL(await connectionStringsCollection.utils.decrypt(id)).password |
| 134 | + } |
| 135 | + |
| 136 | + return url.toString() |
| 137 | + } |
| 138 | + |
| 139 | + return { |
| 140 | + connectionStringsCollection, |
| 141 | + } |
| 142 | +} |
0 commit comments