-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseAgeDecrypt.ts
More file actions
272 lines (246 loc) · 9.48 KB
/
Copy pathuseAgeDecrypt.ts
File metadata and controls
272 lines (246 loc) · 9.48 KB
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
/**
* Copyright (c) Ronan Le Meillat - SCTG Development 2008-2026
* Licensed under the MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import { useState, useCallback, useRef, useEffect } from 'react'
import { Decrypter } from 'age-encryption'
import type { DecryptState } from '../types'
import { encryptedFileCache, type EncryptedCacheStats } from '../services/encryptedFileCache'
import { fetchArrayBuffer } from '../utils/http'
import { safeGetItem, safeSetItem } from '../utils/storage'
/** localStorage key storing whether persistent encrypted caching is enabled. */
const PERSISTENT_CACHE_ENABLED_KEY = 'techno_viewer_persistent_encrypted_cache_enabled'
/** Returns `true` when persistent encrypted caching should be enabled by default. */
function loadPersistentCacheEnabled(): boolean {
const raw = safeGetItem(PERSISTENT_CACHE_ENABLED_KEY)
if (raw === null) return true
return raw !== '0'
}
/** Stores the persistent encrypted cache preference in localStorage. */
function savePersistentCacheEnabled(enabled: boolean): void {
safeSetItem(PERSISTENT_CACHE_ENABLED_KEY, enabled ? '1' : '0')
}
/** Runtime metrics exposed to the UI for persistent encrypted cache observability. */
interface PersistentCacheMetrics extends EncryptedCacheStats {
hits: number
misses: number
enabled: boolean
}
/**
* Describes the source used to satisfy an encrypted file read before decrypting it.
* `memory` means the already decrypted bytes were reused from the in-memory session cache,
* `persistent` means encrypted bytes were read from IndexedDB, and `network` means encrypted
* bytes had to be fetched from the deployed asset URL.
*/
type DecryptSource = 'memory' | 'persistent' | 'network'
/**
* Wraps decrypted bytes with telemetry metadata that callers can use for analytics.
* The bytes remain the same value returned by {@link UseAgeDecryptReturn.decrypt}; the
* extra fields only describe whether the user-visible view was backed by any cache layer.
*/
interface DecryptResult {
data: Uint8Array
fromCache: boolean
source: DecryptSource
}
const EMPTY_CACHE_STATS: EncryptedCacheStats = {
entries: 0,
sizeBytes: 0,
usageBytes: null,
quotaBytes: null,
persisted: null,
limitBytes: 0,
}
/** Return value of the {@link useAgeDecrypt} hook. */
interface UseAgeDecryptReturn {
decrypt: (url: string) => Promise<Uint8Array | null>
decryptWithMetadata: (url: string) => Promise<DecryptResult | null>
decryptBytes: (bytes: Uint8Array) => Promise<Uint8Array | null>
state: DecryptState
error: string | null
reset: () => void
persistentCacheMetrics: PersistentCacheMetrics
setPersistentCacheEnabled: (enabled: boolean) => void
clearPersistentCache: () => Promise<void>
refreshPersistentCacheMetrics: () => Promise<void>
}
/**
* Provides AGE decryption utilities with an in-memory URL-keyed cache.
* @param privateKey - The AGE secret key (must start with `AGE-SECRET-KEY-1`).
* @returns Decryption functions, the current decryption state, any error message, and a reset helper.
*/
export function useAgeDecrypt(privateKey: string): UseAgeDecryptReturn {
const [state, setState] = useState<DecryptState>('idle')
const [error, setError] = useState<string | null>(null)
const [persistentCacheEnabled, setPersistentCacheEnabledState] = useState<boolean>(loadPersistentCacheEnabled)
const [persistentCacheStats, setPersistentCacheStats] = useState<EncryptedCacheStats>(EMPTY_CACHE_STATS)
const persistentCacheHitsRef = useRef(0)
const persistentCacheMissesRef = useRef(0)
// Cache decrypted files in memory by URL to avoid repeated decryption in the same session.
const cache = useRef<Map<string, Uint8Array>>(new Map())
const refreshPersistentCacheMetrics = useCallback(async (): Promise<void> => {
const stats = await encryptedFileCache.getStats()
setPersistentCacheStats(stats)
}, [])
useEffect(() => {
void refreshPersistentCacheMetrics()
}, [refreshPersistentCacheMetrics])
const setPersistentCacheEnabled = useCallback((enabled: boolean) => {
setPersistentCacheEnabledState(enabled)
savePersistentCacheEnabled(enabled)
}, [])
const clearPersistentCache = useCallback(async (): Promise<void> => {
await encryptedFileCache.clear()
await refreshPersistentCacheMetrics()
}, [refreshPersistentCacheMetrics])
const decryptBytes = useCallback(
async (bytes: Uint8Array): Promise<Uint8Array | null> => {
if (!privateKey.trim()) {
setError('No private key provided')
setState('error')
return null
}
setState('loading')
setError(null)
try {
const decrypter = new Decrypter()
decrypter.addIdentity(privateKey.trim())
const result = await decrypter.decrypt(bytes, 'uint8array')
setState('success')
return result
} catch (err) {
const msg = err instanceof Error ? err.message : 'Decryption failed'
setError(msg)
setState('error')
return null
}
},
[privateKey]
)
const getUrl = (url: string) => {
// Keep absolute URLs untouched; normalize relative paths against BASE_URL.
if (/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(url)) return url
const base = import.meta.env.BASE_URL || '/'
const basePath = base
.replace(/\/+$/, '')
.replace(/^([^/])/, '/$1')
const normalizedPath = url.startsWith('/') ? url : `/${url}`
if (!basePath || basePath === '/') return normalizedPath
if (normalizedPath === basePath || normalizedPath.startsWith(`${basePath}/`)) {
return normalizedPath
}
// If the input path already starts with the app basename segment
// (e.g. "/techno-viewer/..."), do not prepend BASE_URL again.
const baseSegment = basePath.split('/').filter(Boolean).pop()
if (baseSegment && (normalizedPath === `/${baseSegment}` || normalizedPath.startsWith(`/${baseSegment}/`))) {
return normalizedPath
}
return `${basePath}${normalizedPath}`
}
const decryptWithMetadata = useCallback(
async (url: string): Promise<DecryptResult | null> => {
const resolvedUrl = getUrl(url)
if (cache.current.has(resolvedUrl)) {
setState('success')
return {
data: cache.current.get(resolvedUrl)!,
fromCache: true,
source: 'memory',
}
}
if (!privateKey.trim()) {
setError('No private key provided')
setState('error')
return null
}
setState('loading')
setError(null)
try {
let encryptedBytes: Uint8Array | null = null
let source: DecryptSource = 'network'
if (persistentCacheEnabled) {
encryptedBytes = await encryptedFileCache.get(resolvedUrl)
if (encryptedBytes) {
persistentCacheHitsRef.current += 1
source = 'persistent'
}
}
if (!encryptedBytes) {
if (persistentCacheEnabled) {
persistentCacheMissesRef.current += 1
}
const bytes = await fetchArrayBuffer(resolvedUrl)
encryptedBytes = new Uint8Array(bytes)
if (persistentCacheEnabled) {
await encryptedFileCache.set(resolvedUrl, encryptedBytes)
}
}
const decrypter = new Decrypter()
decrypter.addIdentity(privateKey.trim())
const result = await decrypter.decrypt(encryptedBytes, 'uint8array')
cache.current.set(resolvedUrl, result)
if (persistentCacheEnabled) {
void refreshPersistentCacheMetrics()
}
setState('success')
return {
data: result,
fromCache: source !== 'network',
source,
}
} catch (err) {
const msg = err instanceof Error ? err.message : 'Decryption failed'
setError(msg)
setState('error')
return null
}
},
[privateKey, persistentCacheEnabled, refreshPersistentCacheMetrics]
)
const decrypt = useCallback(
async (url: string): Promise<Uint8Array | null> => {
const result = await decryptWithMetadata(url)
return result?.data ?? null
},
[decryptWithMetadata]
)
const reset = useCallback(() => {
setState('idle')
setError(null)
}, [])
return {
decrypt,
decryptWithMetadata,
decryptBytes,
state,
error,
reset,
persistentCacheMetrics: {
...persistentCacheStats,
enabled: persistentCacheEnabled,
hits: persistentCacheHitsRef.current,
misses: persistentCacheMissesRef.current,
},
setPersistentCacheEnabled,
clearPersistentCache,
refreshPersistentCacheMetrics,
}
}