-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfileViewAnalytics.ts
More file actions
186 lines (168 loc) · 6.92 KB
/
Copy pathfileViewAnalytics.ts
File metadata and controls
186 lines (168 loc) · 6.92 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
/**
* 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 { identityToRecipient } from 'age-encryption'
import type { Language } from '../types'
import { postJson } from '../utils/http'
/** Backend route that receives minimal file-view telemetry and forwards enriched events to PostHog. */
const FILE_VIEW_ANALYTICS_ENDPOINT = '/api/file-viewed'
/** Backend route that receives batch-download telemetry and forwards enriched events to PostHog. */
const FILES_DOWNLOADING_ANALYTICS_ENDPOINT = '/api/files-downloading'
/** Prefix used by native X25519 AGE private keys accepted by the portal login form. */
const AGE_PRIVATE_KEY_PREFIX = 'AGE-SECRET-KEY-1'
/** Cache of private-key-to-public-recipient derivations for the current browser session. */
const publicKeyCache = new Map<string, string | null>()
/**
* Minimal browser-side payload sent to the Cloudflare Pages Function.
* The backend enriches this shape with request-derived IP and Cloudflare location data before
* posting the final `File Viewed` event to PostHog.
*/
export interface FileViewAnalyticsInput {
username: string
privateKey: string
file: string
language: Language
fromCache: boolean
virtualPath: string
cryptedPath: string
}
/**
* Describes one file included in a batch-download analytics event.
* Each entry carries both the user-facing virtual path and the encrypted asset path so backend
* monitoring can correlate downloads with either the original repository hierarchy or stored ciphertext.
*/
export interface FilesDownloadingAnalyticsFile {
file: string
virtualPath: string
cryptedPath: string
}
/**
* Browser-side payload for the `Files Downloading` monitoring event.
* The payload intentionally mirrors the identity and language fields used by file-view events while moving
* per-file metadata into the `files` array required for batch downloads.
*/
export interface FilesDownloadingAnalyticsInput {
username: string
privateKey: string
language: Language
files: FilesDownloadingAnalyticsFile[]
}
/**
* Network payload posted by the browser to the Cloudflare Pages Function.
* It intentionally contains the public AGE recipient, not the private key, so analytics can
* attribute access without disclosing client-side decryption credentials to the backend.
*/
interface FileViewAnalyticsPayload {
username: string
file: string
language: Language
from_cache: boolean
user_public_key: string | null
virtual_path: string
crypted_path: string
}
/**
* Network payload posted by the browser to the batch-download Cloudflare Pages Function.
* `user_public_key` is derived client-side from the private AGE identity, while every file entry keeps
* snake_case field names to match the PostHog property contract.
*/
interface FilesDownloadingAnalyticsPayload {
username: string
language: Language
user_public_key: string | null
files: Array<{
file: string
virtual_path: string
crypted_path: string
}>
}
/**
* Derives the public AGE recipient for a private identity string.
* Invalid, empty, or unsupported identities resolve to `null` because telemetry must never block
* file viewing; the backend will still receive and forward the rest of the event.
*
* @param privateKey - AGE private identity entered by the authenticated user.
* @returns The matching public AGE recipient, or `null` when it cannot be derived.
*/
export async function deriveAgePublicKey(privateKey: string): Promise<string | null> {
const trimmedPrivateKey = privateKey.trim()
if (!trimmedPrivateKey.startsWith(AGE_PRIVATE_KEY_PREFIX)) return null
if (publicKeyCache.has(trimmedPrivateKey)) {
return publicKeyCache.get(trimmedPrivateKey) ?? null
}
try {
const publicKey = await identityToRecipient(trimmedPrivateKey)
publicKeyCache.set(trimmedPrivateKey, publicKey)
return publicKey
} catch {
publicKeyCache.set(trimmedPrivateKey, null)
return null
}
}
/**
* Sends a best-effort file-view event to the backend analytics endpoint.
* The function deliberately catches all errors because analytics failures must not interrupt the
* document viewer, decryption flow, or user navigation.
*
* @param input - Browser-side file-view details collected when a user opens a file for viewing.
*/
export async function trackFileViewed(input: FileViewAnalyticsInput): Promise<void> {
try {
const payload: FileViewAnalyticsPayload = {
username: input.username,
file: input.file,
language: input.language,
from_cache: input.fromCache,
user_public_key: await deriveAgePublicKey(input.privateKey),
virtual_path: input.virtualPath,
crypted_path: input.cryptedPath,
}
await postJson<void>(FILE_VIEW_ANALYTICS_ENDPOINT, payload, { keepalive: true })
} catch {
// Best-effort analytics only; file viewing must remain independent from monitoring delivery.
}
}
/**
* Sends a best-effort batch-download event to the backend analytics endpoint.
* The event is emitted when the user starts a ZIP download, before file decryption begins, so monitoring
* captures intent even if one selected file later fails to decrypt.
*
* @param input - Browser-side batch-download details collected from the selected file tree nodes.
*/
export async function trackFilesDownloading(input: FilesDownloadingAnalyticsInput): Promise<void> {
if (input.files.length === 0) return
try {
const payload: FilesDownloadingAnalyticsPayload = {
username: input.username,
language: input.language,
user_public_key: await deriveAgePublicKey(input.privateKey),
files: input.files.map((file) => ({
file: file.file,
virtual_path: file.virtualPath,
crypted_path: file.cryptedPath,
})),
}
await postJson<void>(FILES_DOWNLOADING_ANALYTICS_ENDPOINT, payload, { keepalive: true })
} catch {
// Best-effort analytics only; ZIP generation must not depend on monitoring delivery.
}
}