diff --git a/.github/workflows/electron-tests.yaml b/.github/workflows/electron-tests.yaml index 485a030e3..86083cd56 100644 --- a/.github/workflows/electron-tests.yaml +++ b/.github/workflows/electron-tests.yaml @@ -11,6 +11,9 @@ on: - "testing-view/**" paths: - "electron-app/**" + - "frontend/frontend-kit/**" + - "pnpm-lock.yaml" + - "pnpm-workspace.yaml" - ".github/workflows/electron-tests.yaml" jobs: diff --git a/e2e/scripts/build-renderers.mjs b/e2e/scripts/build-renderers.mjs index e9873d3c3..ad5ac4733 100644 --- a/e2e/scripts/build-renderers.mjs +++ b/e2e/scripts/build-renderers.mjs @@ -10,10 +10,11 @@ if (!pnpmCli) throw new Error("Run this build through pnpm --dir e2e build"); for (const view of ["testing", "competition", "logging", "adj"]) { // Preserve Testing's E2E build; do not rebuild it in normal mode afterwards. + const isJs = /\.(c|m)?js$/i.test(pnpmCli); execFileSync( - process.execPath, + isJs ? process.execPath : pnpmCli, [ - pnpmCli, + ...(isJs ? [pnpmCli] : []), "--filter", `${view}-view`, view === "testing" ? "build:e2e" : "build", diff --git a/electron-app/README.md b/electron-app/README.md index a2b9d108e..cb663a559 100644 --- a/electron-app/README.md +++ b/electron-app/README.md @@ -108,6 +108,66 @@ sudo ifconfig lo0 alias 127.0.0.9 up - **Mode Selector**: html5 file to chose the mode of the app: testing, competition or flashing. Placed at `renderer/mode-selector` +## Cloud Logs + +Cloud Logs is a desktop capability shared by Logging View and Testing View. The +renderer calls the narrow `window.electronAPI.cloudLogs` interface exposed from +`preload.js`; it does not access the filesystem, ZIP library, credentials, or +remote API directly. The IPC handlers in `src/cloudLogs/handlers.js` validate +that requests come from the local Logging or Testing window and keep local paths +inside the Electron main process. + +The local folder format is `/logger///`. +Cloud uploads operate on one recording at a time. All regular session files +(configuration, CSVs, and metadata) are packaged and preserved in the recording +ZIP, including the root `logger_settings.json` and all current or future telemetry +subfolders. Launcher traces, symlinks, and directory traversal paths are excluded. +The date attached to a cloud record comes from the recording's +`logger_settings.json`, not from the time it was uploaded. Users must confirm +that recording has stopped; Electron checks that its files did not change while +it compressed the ZIP and reports compression progress to the requesting view. + +Downloaded archives are checked and extracted into +`/logger/cloud-logs/-/`. Extraction uses a staging +directory and rejects unsafe paths, links, duplicate entries, unsupported files, +encrypted ZIPs, and archives over the configured file and byte limits. Logging +View opens a downloaded recording through the same loader it uses for local +folders, so analysis works offline after download. `cloud-logs/` is created on +first use, even when the Go backend is not running. + +The shared typed renderer contract is exported as `CloudLogsAPI` from +`@hyperloopupv/frontend-kit/core`. Testing View already has that type on its +Electron bridge, so it can call the same service without implementing another +network or filesystem client. The React implementation currently lives in +`frontend/logging-view/src/components/cloudLogs/CloudLogsDialog.tsx`. + +Credentials are entered in the Cloud Logs dialog and managed by Electron in +`src/cloudLogs/credentials.js`. The user name and encrypted key are stored in +`/cloud-logs.json` when OS secure storage is available. If +secure storage is unavailable, Electron keeps the key in memory until exit. The +key is never sent back to the renderer; the renderer only receives the user, +whether a key is configured, and whether storage is persistent. + +### Cloud Logs API Integration + +The remote HTTP adapter in `src/cloudLogs/client.js` is fully connected to the +Cloud Logs API (`https://cloud-logs.hyperloopupv.com/api/v1`, configurable via +`CLOUD_LOGS_API_URL` or `config.toml`) and supports direct-to-storage uploads +and downloads: + +- **Catalog & Tags**: Lists paginated recordings (`listLogs`) and retrieves tag + suggestions for autocomplete (`autocompleteTags`). +- **Direct-to-Storage Uploads**: Uploads use a two-phase protocol where session + metadata is registered with the API (`POST /logs/initiate`) and the ZIP archive + is streamed directly to Google Drive via a pre-authenticated resumable upload URL, + followed by confirmation (`POST /logs/{id}/complete`). +- **Direct-to-Storage Downloads**: Downloads stream the ZIP archive directly from + storage to disk with size limit enforcement and error sanitization. + +All requests are authenticated via `Bearer` token or `X-API-Key`. Detailed API +specifications, data mappings, and error formats are documented in +`src/cloudLogs/README.md`. + ## Dependencies - `electron` - Desktop application framework diff --git a/electron-app/package.json b/electron-app/package.json index 2549992da..09e5f17d4 100644 --- a/electron-app/package.json +++ b/electron-app/package.json @@ -6,7 +6,7 @@ "type": "module", "author": { "name": "Hyperloop UPV", - "email": "partners@hyperloopupv.com" + "email": "software@hyperloopupv.com" }, "contributors": [ { @@ -66,9 +66,11 @@ "dependencies": { "@iarna/toml": "^2.2.5", "ansi-to-html": "^0.7.2", + "archiver": "5.3.2", "electron-store": "^11.0.2", "electron-updater": "^6.7.3", - "picocolors": "^1.1.1" + "picocolors": "^1.1.1", + "yauzl": "2.10.0" }, "devDependencies": { "@vitest/coverage-v8": "^4.0.18", diff --git a/electron-app/preload.js b/electron-app/preload.js index a4d5debf6..9d74a19f1 100644 --- a/electron-app/preload.js +++ b/electron-app/preload.js @@ -6,24 +6,28 @@ const { contextBridge, ipcRenderer } = require("electron"); -/** - * Exposes Electron APIs to the renderer process via contextBridge. - * All methods use ipcRenderer.invoke for secure two-way communication with the main process. - * @type {Object} - * @property {function(): Promise} getCurrentView - Gets the name of the currently loaded view. - * @property {function(string): Promise} switchView - Switches to a different view. - * @property {function(Object): Promise} saveConfig - Saves the configuration object. - * @property {function(): Promise} getConfig - Gets the current configuration object. - * @property {function(): Promise} importConfig - Imports configuration from a file dialog. - * @property {function(): Promise} selectFolder - Opens a folder selection dialog. - * @example - * // In renderer process: - * const view = await window.electronAPI.getCurrentView(); - * await window.electronAPI.switchView("control-station"); - * const config = await window.electronAPI.getConfig(); - * await window.electronAPI.saveConfig({ database: { host: "localhost" } }); - */ contextBridge.exposeInMainWorld("electronAPI", { + // Cloud Logs API: credentials, sync, and transfer progress + cloudLogs: { + getCredentialsStatus: () => + ipcRenderer.invoke("cloud-logs:credentials-status"), + setCredentials: (input) => + ipcRenderer.invoke("cloud-logs:credentials-save", input), + clearCredentials: () => ipcRenderer.invoke("cloud-logs:credentials-clear"), + getLocalSessions: () => ipcRenderer.invoke("cloud-logs:local-sessions"), + selectSession: () => ipcRenderer.invoke("cloud-logs:select-session"), + list: (cursor) => ipcRenderer.invoke("cloud-logs:list", cursor), + autocompleteTags: (query) => ipcRenderer.invoke("cloud-logs:tags", query), + upload: (input) => ipcRenderer.invoke("cloud-logs:upload", input), + download: (input) => ipcRenderer.invoke("cloud-logs:download", input), + getDownloads: () => ipcRenderer.invoke("cloud-logs:downloads"), + // Subscribe to transfer progress; returns an unsubscribe callback + onProgress: (callback) => { + const listener = (_event, progress) => callback(progress); + ipcRenderer.on("cloud-logs:progress", listener); + return () => ipcRenderer.removeListener("cloud-logs:progress", listener); + }, + }, // Get the currently loaded view name getCurrentView: () => ipcRenderer.invoke("get-current-view"), // Switch to a different view by name, optionally passing query params @@ -61,7 +65,7 @@ contextBridge.exposeInMainWorld("electronAPI", { ipcRenderer.send("mode-selected", mode); return Promise.resolve(); }, - // Receive log message from backend + // Subscribes to backend log messages; returns an unsubscribe callback. onLog: (callback) => { const listener = (_event, value) => callback(value); ipcRenderer.removeAllListeners("log"); diff --git a/electron-app/src/cloudLogs/README.md b/electron-app/src/cloudLogs/README.md new file mode 100644 index 000000000..7f02dd2be --- /dev/null +++ b/electron-app/src/cloudLogs/README.md @@ -0,0 +1,347 @@ +# Cloud Logs integration + +Desktop service shared by Logging View and Testing View via +`window.electronAPI.cloudLogs`. The typed contract is exported from +`@hyperloopupv/frontend-kit/core` (`CloudLogsAPI`). React never imports Node code. + +## File map + +| File | Responsibility | Change it when… | +| ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | +| `client.js` | The remote HTTP adapter. Implements `listLogs`, `autocompleteTags`, two-phase `uploadLog`, direct streaming `downloadLog`, and error sanitization. | Modifying API endpoints, authentication headers, error serialization, or upload/download flows. | +| `credentials.js` | Reads, writes, encrypts, and clears the Cloud Logs user and API key. Only credential status is returned to the renderer. | Changing credential persistence, secure-storage policy, or validation. | +| `sessions.js` | Resolves the configured `logger/` root, creates `cloud-logs/`, scans local launch folders, and validates a recording using its `logger_settings.json`. Formats archive filenames by title/standard date. | Changing how backend recordings are laid out, session validation, or archive naming rules. | +| `archive.js` | Zips every regular file inside one recording and safely extracts downloaded archives with cross-platform attribute handling. Reports compression and extraction progress. | Changing archive layout, ZIP safety checks, limits, or progress. | +| `handlers.js` | Connects renderer IPC calls to credentials, session discovery, archive operations, and the remote adapter. Checks the calling window, owns local path grants, scopes progress, and removes temporary files. | Adding renderer operations, changing authorization, or coordinating uploads and downloads. | +| `__tests__/client.test.js` | Unit tests for the HTTP client adapter (URL parsing, authentication, upload phases, download streaming, Pydantic error formatting, sanitization). | Adding regression tests for remote API interactions. | +| `__tests__/handlers.test.js` | Unit tests for the Cloud Logs IPC handlers (authentication guards, upload/download input validation, title propagation, and error redaction). | Adding regression tests for IPC bridge logic. | +| `__tests__/storage.test.js` | Tests local session discovery, ZIP round trips and safety, archive naming, arbitrary logger subfolders, and credential storage using temporary files. | Adding regression coverage for session storage, ZIP handling, or credentials. | +| `README.md` | This module guide and API handoff contract. | Updating module behavior or integration instructions. | + +Related bridge files live outside this directory: `electron-app/preload.js` +exposes `window.electronAPI.cloudLogs`; `frontend/frontend-kit/kit/src/core/cloudLogs.ts` +defines the shared TypeScript contract; and +`frontend/logging-view/src/components/cloudLogs/CloudLogsDialog.tsx` implements +the Logging View dialog. Testing View can use the same preload bridge and types. + +## Remote API: Architecture & Endpoints + +The remote telemetry storage service is implemented in [`Hyperloop-UPV/cloud-logs`](https://github.com/Hyperloop-UPV/cloud-logs). +All client methods in `client.js` are fully connected and tested: + +| Function | Input | Result | +| ------------------ | ------------------------------------------- | ---------------------------------------------- | +| `listLogs` | credentials, optional cursor | `{ items: CloudLog[], nextCursor?: string }` | +| `autocompleteTags` | credentials, query (including empty string) | `string[]` | +| `uploadLog` | credentials, archivePath, metadata | confirmed `CloudLog` | +| `downloadLog` | credentials, id, destination, maxBytes | resolves after ZIP is fully written and closed | + +The desktop application contract defines: + +- `CloudLog`: `{ id: string, user: string, notes: string, tags: string[], date: string, title?: string, fileName?: string }`. +- `DownloadedLog`: `{ id: string, path: string, date: string, title?: string, fileName?: string }`. + +### Configuration & Base URL + +- **Production Base URL**: `https://cloud-logs.hyperloopupv.com/api/v1` +- **Configuration**: Overridable via `CLOUD_LOGS_API_URL` environment variable or `config.toml` (e.g. `[cloud_logs] api_url = "https://..."`). + +### Authentication + +Every authenticated request to the Cloud Logs API must provide the user's API key using either: + +- `Authorization: Bearer ` (standard HTTP bearer token), or +- `X-API-Key: ` (machine/automated header). + +Both header formats are accepted interchangeably by the API server. + +### Date Format Mapping + +- **Local Logger format**: `YYYY-MM-DDTHH-mm-ss` (e.g., `2026-11-15T12-30-00`, read from `logger_settings.json.date`). +- **Cloud Logs API format**: ISO-8601 UTC string `YYYY-MM-DDTHH:mm:ssZ` (e.g., `2026-11-15T12:30:00Z`). +- **Conversion rule**: + - Convert from local logger to API when uploading: + ```js + const isoDate = date.replace( + /^(\d{4}-\d{2}-\d{2}T\d{2})-(\d{2})-(\d{2})$/, + "$1:$2:$3Z", + ); + ``` + - Convert from API back to local logger format when listing/downloading: + ```js + const loggerDate = isoDate.replace( + /^(\d{4}-\d{2}-\d{2}T\d{2}):(\d{2}):(\d{2})(?:\.\d+)?Z?$/, + "$1-$2-$3", + ); + ``` + - **Important**: Do **NOT** use `new Date(...)` or `.toISOString()` for this transformation. Local dates must not have timezones or local daylight-saving offsets invented for them; the nominal recorded time is converted directly. + +--- + +### Real Endpoints Specification + +#### 1. Catalog Search & Pagination + +- **Method**: `GET /logs` (or `GET /api/v1/logs`) +- **Query Parameters**: + - `page`: Page index (integer, default: `1`). + - `pageSize`: Items per page (integer, default: `50`, max: `100`). + - `sortBy`: Field to order by (`uploadDate`, `logDate`, `fileName`, `fileSize`, default: `uploadDate`). + - `sortOrder`: Sort direction (`asc` or `desc`, default: `desc`). + - `fromDate`: (Optional) Filter logs from this ISO date. + - `toDate`: (Optional) Filter logs up to this ISO date. + - `tags`: Comma-separated list of required tags (e.g. `pod,propulsion`). + - `status`: Filter by state (`ready`, `pending_upload`, `aborted`, `failed`, default: `ready`). + - `textQuery`: (Optional) Substring search in filenames and notes. +- **Response Schema (`200 OK`)**: + ```json + { + "total": 42, + "page": 1, + "pageSize": 20, + "items": [ + { + "id": "c8b321a0-3841-4cf1-a472-8d76a26d7f01", + "fileName": "run_42_telemetry.zip", + "status": "ready", + "driveFolder": "2026_10", + "driveFileId": "1aB2cD3e...", + "driveUrl": "https://drive.google.com/file/d/1aB2cD3e.../view", + "fileSize": 104857600, + "fileHash": "a1b2c3d4...", + "tags": ["pod", "propulsion"], + "note": "Track run with inverter at 80% throttle", + "clientMetadata": { + "hostname": "pod-orin-master-01", + "clientUser": "operator_john" + }, + "logDate": "2026-10-23T10:00:00Z", + "createdBy": "a3b1c2d3-...", + "creator": "john_eng", + "uploadDate": "2026-10-23T10:00:02Z", + "completedAt": "2026-10-23T10:01:10Z" + } + ] + } + ``` +- **Mapping to `CloudLog`**: + Map each item in `items` to: + ```js + { + id: item.id, + fileName: item.fileName || item.file_name || "", + title: + item.title || + item.clientMetadata?.title || + (item.fileName ? item.fileName.replace(/\.zip$/i, "") : ""), + user: item.creator || item.user || item.clientMetadata?.clientUser || credentials.user, + notes: item.note || item.notes || "", + tags: item.tags || [], + date: item.logDate || item.uploadDate || item.fileDate || item.date || item.createdAt || "", + } + ``` + Set `nextCursor` to `page < Math.ceil(total / pageSize) ? String(page + 1) : undefined`. + +#### 2. Tag Autocomplete + +- **Method**: `GET /logs/tags` +- **Query Parameters**: + - `detailed`: Boolean (default: `false`). +- **Response Schema (`200 OK`)**: + ```json + ["bms", "brakes", "inverter", "motor", "pod", "propulsion", "telemetry"] + ``` + If `query` is provided in `autocompleteTags`, filter suggestions locally or pass query parameter if supported. + +#### 3. Two-Phase Resumable Upload to Google Drive + +Telemetry binaries stream directly to Google Drive via pre-authenticated resumable upload sessions. They are **never sent directly through the Cloud-Logs API server**. + +```mermaid +sequenceDiagram + participant CS as Control Station (Electron) + participant API as Cloud Logs API + participant Drive as Google Drive + + CS->>API: POST /logs/initiate (metadata) + API-->>CS: { id, uploadUrl, driveFolder, status } + CS->>Drive: PUT (binary stream, NO API auth headers) + Drive-->>CS: 200/201 OK { id: driveFileId } + alt Upload Succeeded + CS->>API: POST /logs/{id}/complete { fileHash, driveFileId } + API-->>CS: 200 OK { id, status: "ready", ... } + else Upload Cancelled / Failed + CS->>API: POST /logs/{id}/abort { reason } + API-->>CS: 200 OK { id, status: "aborted", ... } + end +``` + +##### Step 3.1: Request Upload Session & Register Metadata + +- **Method**: `POST /logs/initiate` (or `POST /api/v1/logs/initiate`) +- **Request Fields**: + - `fileName`: string (required) - Name of the ZIP archive (`.zip` or `<standard-date>.zip`). + - `fileSize`: integer (required) - Archive size in bytes. + - `logDate`: ISO datetime string (`YYYY-MM-DDTHH:mm:ssZ`) - Creation/recording date from `logger_settings.json`. + - `tags`: string array (optional) - Tags associated with the recording. + - `note`: string (optional) - User description or notes. + - `clientMetadata`: object (optional) - Client environment details (e.g., `hostname`, `clientUser`, `title`, `appVersion`). +- **Request Body**: + ```json + { + "fileName": "run_42_telemetry.zip", + "fileSize": 104857600, + "logDate": "2026-10-23T10:00:00Z", + "tags": ["pod", "propulsion"], + "note": "Track run with inverter at 80% throttle", + "clientMetadata": { + "hostname": "pod-orin-master-01", + "clientUser": "operator_john", + "title": "Run 42 Telemetry", + "appVersion": "1.0.0" + } + } + ``` +- **Response Schema (`200 OK`)**: + ```json + { + "id": "c8b321a0-3841-4cf1-a472-8d76a26d7f01", + "uploadUrl": "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&upload_id=...", + "driveFolder": "2026_10", + "status": "pending_upload", + "expiresInSeconds": 86400 + } + ``` + +##### Step 3.2: Direct Binary Stream to Google Drive + +- **Method**: `PUT <uploadUrl>` +- **Headers**: Standard HTTP body stream headers (`Content-Length: <fileSize>`, `Content-Type: application/zip`). +- **CRITICAL**: Do **NOT** send `Authorization` or `X-API-Key` headers to `uploadUrl`. The Google Drive upload URL is already signed/pre-authenticated. Forwarding API keys to Google will cause request failure or credential leakage. +- Stream the ZIP archive directly from `archivePath` using Node streams. + +##### Step 3.3: Complete & Verify Upload + +- **Method**: `POST /logs/{id}/complete` +- **Request Body**: + ```json + { + "fileHash": "optional_client_calculated_sha256", + "driveFileId": "optional_google_drive_file_id" + } + ``` +- **Response Schema (`200 OK`)**: + ```json + { + "id": "c8b321a0-3841-4cf1-a472-8d76a26d7f01", + "status": "ready", + "driveUrl": "https://drive.google.com/file/d/.../view", + "driveFolder": "2026_10", + "fileName": "run_42_telemetry.zip", + "fileSize": 104857600, + "message": "Upload verified and completed successfully" + } + ``` +- Maps to confirmed `CloudLog` on resolution. + +##### Step 3.4: Abort Upload (Cancellation) + +- **Method**: `POST /logs/{id}/abort` +- **When to call**: If transfer is cancelled or an unrecoverable network failure occurs after initiate. +- **Request Body**: + ```json + { + "reason": "Cancelled by user" + } + ``` +- **Response Schema (`200 OK`)**: + ```json + { + "id": "c8b321a0-3841-4cf1-a472-8d76a26d7f01", + "status": "aborted", + "message": "Upload aborted successfully", + "abortedAt": "2026-10-24T08:30:00Z" + } + ``` + +#### 4. File Download (Direct Streaming / 307 Fallback) + +- **Method**: `GET /logs/{id}/download` (or `GET /api/v1/logs/{id}/download`) +- **Behavior**: + - Validates authentication (`Authorization: Bearer <apiKey>` or `X-API-Key: <apiKey>`). + - Streams the binary ZIP content directly with `200 OK` (via backend Google Drive streaming). + - Also handles HTTP redirect responses (`301`, `302`, `307`, `308`) by following `Location` headers (resolved with `new URL(location, downloadEndpoint)`). + - **CRITICAL Security**: Never forward authorization headers (`Authorization` or `X-API-Key`) to external redirects or third-party hosts. + - Enforces `maxBytes` (default 2–4 GiB) while streaming the response into the destination file. + - If the log is not in `ready` state, the endpoint returns `400 Bad Request`; if nonexistent, `404 Not Found`. + +--- + +### Adapter Guidelines & Error Handling in `client.js` + +- Stream files directly via Node streams instead of buffering entire archives in memory. +- Enforce `maxBytes` byte limits during streaming downloads to prevent disk saturation. +- Never forward authentication headers to third-party domains or external redirects (such as Google Drive). +- Sanitize error messages: redact API keys (`Bearer [REDACTED]`, `x-api-key: [REDACTED]`), strip raw HTML dumps, and serialize FastAPI/Pydantic 422 validation detail arrays/objects into readable JSON instead of `[object Object]`. + +## Local service (implemented) + +- Local discovery: `<logging_path>/logger/<app-launch>/<recording>/`. +- Native folder selection also permits recordings outside that root. The main + process gives the renderer an opaque token scoped to its window, not a generic + "upload any path" API. +- One recording per ZIP. `logger_settings.json` stays at the ZIP root, and every + regular file inside that recording is included, even in unrecognized or future + subfolders such as `orders/`, `protections/`, and `other/`. The parent app + launch folder is never archived. The local `cloud-log.json` download marker is + excluded. Upload only stopped recordings; compression rejects files whose + size/mtime or membership changes during archiving. +- **Upload Archive Naming**: + Upload ZIPs are created inside an OS temporary directory named `cloud-logs-upload-*` + (under Node's `os.tmpdir()`). If the user specifies a custom title, it is sanitized + and formatted as `<clean_title>.zip`. If no title is given, it defaults to the nominal + recording date in standard format (`YYYY-MM-DDTHH-mm-ss.zip`). The archive is never + named generic `session.zip`. Electron deletes the temporary directory and ZIP after + the upload completes or fails. +- `logger/cloud-logs/` is created on first use, also with the Go backend stopped. + Paths resolve against the same backend working directory and `logging_path`. + `others/` remains inside each app launch, not beside the launch folders. +- **Downloaded Session Naming & Metadata**: + Downloads extract into a private `.download-*` staging directory. The staging ZIP + is named using the log's remote `fileName` or sanitized `title.zip` (fallback `${id}.zip`), + avoiding generic names like `session.zip`. + After validation, the directory is renamed into `cloud-logs/<sanitized fileName or title>-<hh-mm-ss>/`. + `cloud-log.json` stores `{ id, date, title, fileName }` beside the extracted session. + When opening a downloaded session in Logging View (`list-session-files`), the application + reads `cloud-log.json` and presents the session with its real title or filename. Repeated downloads reuse the valid local copy. +- Extraction rejects traversal, symlinks, encrypted archives, duplicate file + entries and oversized archives. It accepts arbitrary regular files in a + downloaded recording so future logger subfolders remain usable. Limits: 4 GiB + and 10,000 entries. +- Progress is scoped by requestId and sent only to the requesting window. + Compression and extraction report file progress; network phases are + indeterminate. One transfer at a time across the desktop app. The dialog stays + open during transfers; closing the application still interrupts them. + +## Credentials + +`<Electron userData>/cloud-logs.json` holds the user and encrypted API key. With +no secure OS storage (including Linux `basic_text`/`unknown`), only the user is +persisted; the key stays in process memory. No key is returned to React. Blank +key on save preserves the current key; removing credentials requires the +explicit Remove action. Credentials updates are serialized across windows. + +## UI and future consumers + +Logging View's sidebar opens Library / Upload / Credentials. Tags are fetched +with a debounced API search. Recording date is read-only and comes from the +selected recording. Downloads open through the existing session-folder loader, +so CSV parsing, charts and recent sessions keep the same behavior. In a browser +without Electron the dialog explains that desktop integration is required. + +Testing View can call the same bridge; its global interface already includes +`cloudLogs`. No backend lifecycle changes are required for cloud operations. + +Run `pnpm --dir electron-app test -- src/cloudLogs/__tests__` and the Logging +View build/lint. The tests use real temporary files and ZIPs, mocked credentials +storage and no remote network. diff --git a/electron-app/src/cloudLogs/__tests__/client.test.js b/electron-app/src/cloudLogs/__tests__/client.test.js new file mode 100644 index 000000000..58f6eb440 --- /dev/null +++ b/electron-app/src/cloudLogs/__tests__/client.test.js @@ -0,0 +1,1287 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { ReadableStream } from "node:stream/web"; + +const mockConfig = vi.hoisted(() => ({ value: {} })); +vi.mock("../../config/configInstance.js", () => ({ + readConfig: vi.fn(async () => mockConfig.value), +})); + +import { + autocompleteTags, + clearTagCache, + convertDateToIso, + downloadLog, + getAuthHeaders, + getBaseUrl, + handleResponseError, + listLogs, + normalizeApiUrl, + sanitizeError, + sanitizeMessage, + uploadLog, +} from "../client.js"; + +describe("Cloud Logs Client", () => { + let tempDir; + let originalFetch; + let originalEnvUrl; + + beforeEach(async () => { + tempDir = await mkdtemp(path.join(tmpdir(), "cloud-logs-client-test-")); + mockConfig.value = {}; + clearTagCache(); + originalEnvUrl = process.env.CLOUD_LOGS_API_URL; + delete process.env.CLOUD_LOGS_API_URL; + originalFetch = globalThis.fetch; + }); + + afterEach(async () => { + globalThis.fetch = originalFetch; + if (originalEnvUrl !== undefined) { + process.env.CLOUD_LOGS_API_URL = originalEnvUrl; + } else { + delete process.env.CLOUD_LOGS_API_URL; + } + vi.restoreAllMocks(); + await rm(tempDir, { recursive: true, force: true }); + }); + + describe("Base URL & Auth Headers", () => { + it("falls back to default base URL when not configured", async () => { + const url = await getBaseUrl(); + expect(url).toBe("https://cloud-logs.hyperloopupv.com/api/v1"); + }); + + it("uses config cloud_logs.api_url and normalizes cleanly", async () => { + mockConfig.value = { + cloud_logs: { api_url: "https://custom.logs.org/api/v1" }, + }; + expect(await getBaseUrl()).toBe("https://custom.logs.org/api/v1"); + + mockConfig.value = { + cloud_logs: { api_url: "https://custom.logs.org/api/v1/" }, + }; + expect(await getBaseUrl()).toBe("https://custom.logs.org/api/v1"); + + mockConfig.value = { cloud_logs: { api_url: "https://custom.logs.org" } }; + expect(await getBaseUrl()).toBe("https://custom.logs.org"); + }); + + it("prefers process.env.CLOUD_LOGS_API_URL over config and normalizes", async () => { + mockConfig.value = { + cloud_logs: { api_url: "https://custom.logs.org/api/v1" }, + }; + process.env.CLOUD_LOGS_API_URL = "http://localhost:8000"; + expect(await getBaseUrl()).toBe("http://localhost:8000"); + + process.env.CLOUD_LOGS_API_URL = "http://localhost:8000/api/v1/"; + expect(await getBaseUrl()).toBe("http://localhost:8000/api/v1"); + }); + + it("falls back to default base URL when empty, undefined, or null", () => { + expect(normalizeApiUrl()).toBe( + "https://cloud-logs.hyperloopupv.com/api/v1", + ); + expect(normalizeApiUrl(undefined)).toBe( + "https://cloud-logs.hyperloopupv.com/api/v1", + ); + expect(normalizeApiUrl(null)).toBe( + "https://cloud-logs.hyperloopupv.com/api/v1", + ); + expect(normalizeApiUrl("")).toBe( + "https://cloud-logs.hyperloopupv.com/api/v1", + ); + expect(normalizeApiUrl(" ")).toBe( + "https://cloud-logs.hyperloopupv.com/api/v1", + ); + }); + + it("preserves /api/v1, /api/v2, and custom paths without mangling them", () => { + expect(normalizeApiUrl("https://example.com/api/v1")).toBe( + "https://example.com/api/v1", + ); + expect(normalizeApiUrl("https://example.com/api/v2")).toBe( + "https://example.com/api/v2", + ); + expect(normalizeApiUrl("http://localhost:8000")).toBe( + "http://localhost:8000", + ); + expect(normalizeApiUrl("https://example.com/proxy/subpath")).toBe( + "https://example.com/proxy/subpath", + ); + }); + + it("removes trailing slashes and collapses multiple slashes", () => { + expect(normalizeApiUrl("https://example.com/")).toBe( + "https://example.com", + ); + expect(normalizeApiUrl("https://example.com/api/v1/")).toBe( + "https://example.com/api/v1", + ); + expect(normalizeApiUrl("https://example.com/api/v2///")).toBe( + "https://example.com/api/v2", + ); + expect(normalizeApiUrl("https://example.com///proxy///subpath///")).toBe( + "https://example.com/proxy/subpath", + ); + expect(normalizeApiUrl("http://localhost:8000//api//v1//")).toBe( + "http://localhost:8000/api/v1", + ); + }); + + it("throws on non-http/https protocols", () => { + expect(() => normalizeApiUrl("ftp://foo.bar")).toThrow( + 'Invalid Cloud Logs API URL protocol: "ftp:". Only http: and https: are allowed.', + ); + expect(() => normalizeApiUrl("ws://localhost:8080")).toThrow( + 'Invalid Cloud Logs API URL protocol: "ws:". Only http: and https: are allowed.', + ); + expect(() => normalizeApiUrl("file:///path/to/api")).toThrow( + 'Invalid Cloud Logs API URL protocol: "file:". Only http: and https: are allowed.', + ); + }); + + it("throws on malformed strings", () => { + expect(() => normalizeApiUrl("not-a-url")).toThrow( + 'Invalid Cloud Logs API URL: "not-a-url". Must be a valid absolute HTTP or HTTPS URL.', + ); + expect(() => normalizeApiUrl("://invalid")).toThrow( + 'Invalid Cloud Logs API URL: "://invalid". Must be a valid absolute HTTP or HTTPS URL.', + ); + }); + + it("throws on non-string inputs", () => { + expect(() => normalizeApiUrl(123)).toThrow( + "Invalid Cloud Logs API URL: Expected string but received number", + ); + expect(() => normalizeApiUrl({})).toThrow( + "Invalid Cloud Logs API URL: Expected string but received object", + ); + }); + + it("builds auth headers correctly with apiKey and optional user", () => { + expect(getAuthHeaders()).toEqual({}); + expect(getAuthHeaders({ apiKey: "secret123" })).toEqual({ + Authorization: "Bearer secret123", + "X-API-Key": "secret123", + }); + expect( + getAuthHeaders({ apiKey: "secret123", user: "operator_john" }), + ).toEqual({ + Authorization: "Bearer secret123", + "X-API-Key": "secret123", + "X-User": "operator_john", + }); + }); + }); + + describe("Date conversion", () => { + it("converts YYYY-MM-DDTHH-mm-ss to ISO 8601 YYYY-MM-DDTHH:mm:ssZ", () => { + expect(convertDateToIso("2026-11-15T12-30-00")).toBe( + "2026-11-15T12:30:00Z", + ); + expect(convertDateToIso("2026-01-01T00-00-00")).toBe( + "2026-01-01T00:00:00Z", + ); + }); + + it("handles already ISO-formatted dates", () => { + expect(convertDateToIso("2026-11-15T12:30:00Z")).toBe( + "2026-11-15T12:30:00Z", + ); + expect(convertDateToIso("2026-11-15T12:30:00")).toBe( + "2026-11-15T12:30:00Z", + ); + }); + + it("converts single-digit date strings by padding with leading zeroes", () => { + expect(convertDateToIso("2026-2-12T17-01-46")).toBe( + "2026-02-12T17:01:46Z", + ); + expect(convertDateToIso("2026-2-5 9:8:7")).toBe("2026-02-05T09:08:07Z"); + }); + + it("returns undefined for missing or empty input", () => { + expect(convertDateToIso(undefined)).toBeUndefined(); + expect(convertDateToIso("")).toBeUndefined(); + }); + }); + + describe("Error sanitization", () => { + it("sanitizes API keys and tokens from strings", () => { + const apiKey = "super-secret-key-999"; + const dirty = `Error connecting with key ${apiKey} and header Bearer abc123def456`; + const clean = sanitizeMessage(dirty, apiKey); + expect(clean).not.toContain(apiKey); + expect(clean).toContain("[REDACTED]"); + expect(clean).toContain("Bearer [REDACTED]"); + }); + + it("sanitizes Error instances preserving status and code", () => { + const apiKey = "key_xyz_789"; + const err = new Error(`Failed with API key ${apiKey}`); + err.status = 401; + err.code = "ERR_AUTH"; + const cleanErr = sanitizeError(err, apiKey); + expect(cleanErr.message).not.toContain(apiKey); + expect(cleanErr.message).toContain("[REDACTED]"); + expect(cleanErr.status).toBe(401); + expect(cleanErr.code).toBe("ERR_AUTH"); + }); + + it("sanitizes query parameters containing tokens", () => { + const msg = + "GET /api/v1/download?token=secretToken123&apiKey=anotherSecret"; + const clean = sanitizeMessage(msg); + expect(clean).not.toContain("secretToken123"); + expect(clean).not.toContain("anotherSecret"); + expect(clean).toContain("?token=[REDACTED]"); + expect(clean).toContain("&apiKey=[REDACTED]"); + }); + + it("avoids replacing short API keys under 4 characters to protect normal words", () => { + const shortKey = "cat"; + const msg = "The catalog category indicates concat was successful"; + const clean = sanitizeMessage(msg, shortKey); + expect(clean).toBe(msg); + }); + + it("sanitizes headers, JSON fields, and various query parameters", () => { + const jsonPayload = + '{"x-api-key": "secret-json-123", "apiKey": "json-key-456", "note": "ok"}'; + const cleanJson = sanitizeMessage(jsonPayload); + expect(cleanJson).toContain('"x-api-key": "[REDACTED]"'); + expect(cleanJson).toContain('"apiKey": "[REDACTED]"'); + expect(cleanJson).not.toContain("secret-json-123"); + expect(cleanJson).not.toContain("json-key-456"); + + const headerText = "api-key: my-secret-val; Bearer my-token-val;"; + const cleanHeader = sanitizeMessage(headerText); + expect(cleanHeader).toBe("api-key: [REDACTED]; Bearer [REDACTED];"); + + const queryUrl = + "https://example.com/api?token=t1&api_key=k1&key=k2&secret=s1"; + const cleanQuery = sanitizeMessage(queryUrl); + expect(cleanQuery).toBe( + "https://example.com/api?token=[REDACTED]&api_key=[REDACTED]&key=[REDACTED]&secret=[REDACTED]", + ); + }); + }); + + describe("handleResponseError", () => { + it("properly formats 422 validation error arrays without producing [object Object]", async () => { + const validationErrors = [ + { + loc: ["body", "logDate"], + msg: "field required", + type: "value_error.missing", + }, + { + loc: ["body", "fileSize"], + msg: "ensure this value is greater than 0", + type: "value_error.number.not_gt", + }, + ]; + const mockResponse = { + status: 422, + json: async () => ({ detail: validationErrors }), + }; + + await expect(handleResponseError(mockResponse)).rejects.toThrow( + `Request failed with status 422: ${JSON.stringify(validationErrors)}`, + ); + + try { + await handleResponseError(mockResponse); + } catch (err) { + expect(err.message).not.toContain("[object Object]"); + expect(err.message).toContain("field required"); + expect(err.message).toContain("value_error.missing"); + expect(err.status).toBe(422); + } + }); + + it("formats object detail without producing [object Object]", async () => { + const errorObj = { error: "Unprocessable", code: 42201 }; + const mockResponse = { + status: 422, + json: async () => ({ detail: errorObj }), + }; + + try { + await handleResponseError(mockResponse); + } catch (err) { + expect(err.message).not.toContain("[object Object]"); + expect(err.message).toContain(JSON.stringify(errorObj)); + } + }); + + it("uses string detail when detail is a string", async () => { + const mockResponse = { + status: 400, + json: async () => ({ detail: "Invalid request payload" }), + }; + + try { + await handleResponseError(mockResponse); + } catch (err) { + expect(err.message).toContain("Invalid request payload"); + } + }); + + it("falls back to message or JSON string when detail is absent", async () => { + const mockResponseMsg = { + status: 500, + json: async () => ({ message: "Internal server error" }), + }; + + try { + await handleResponseError(mockResponseMsg); + } catch (err) { + expect(err.message).toContain("Internal server error"); + } + + const mockResponseJson = { + status: 500, + json: async () => ({ code: "UNKNOWN_ERR" }), + }; + + try { + await handleResponseError(mockResponseJson); + } catch (err) { + expect(err.message).toContain('{"code":"UNKNOWN_ERR"}'); + } + }); + + it("strips HTML tags and trims to 300 characters when proxy returns 502 HTML", async () => { + const htmlBody = ` + <!DOCTYPE html> + <html> + <head><title>502 Bad Gateway + +

502 Bad Gateway

+

The upstream server failed to respond in time.

+ + + `; + const mockResponse = { + status: 502, + statusText: "Bad Gateway", + text: async () => htmlBody, + }; + + try { + await handleResponseError(mockResponse); + expect.unreachable(); + } catch (err) { + expect(err.status).toBe(502); + expect(err.message).not.toContain(""); + expect(err.message).not.toContain(""); + expect(err.message).not.toContain("

"); + expect(err.message).toContain("502 Bad Gateway"); + expect(err.message).toContain( + "The upstream server failed to respond in time.", + ); + } + }); + + it("extracts error or message fields when detail is absent in JSON", async () => { + const mockResponseError = { + status: 403, + text: async () => JSON.stringify({ error: "Access denied by policy" }), + }; + + try { + await handleResponseError(mockResponseError); + expect.unreachable(); + } catch (err) { + expect(err.status).toBe(403); + expect(err.message).toContain("Access denied by policy"); + } + }); + }); + + describe("listLogs", () => { + it("calls GET /logs with pagination parameters and auth headers", async () => { + const mockItems = [ + { + id: "uuid-1", + fileName: "run_1.zip", + creator: "alice", + note: "Run 1 notes", + tags: ["pod", "test"], + logDate: "2026-10-23T10:00:00Z", + }, + ]; + + const fetchMock = vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ + total: 105, + page: 1, + pageSize: 50, + items: mockItems, + }), + }); + globalThis.fetch = fetchMock; + + const result = await listLogs({ + credentials: { apiKey: "key-123", user: "alice" }, + cursor: "1", + }); + + expect(fetchMock).toHaveBeenCalledTimes(1); + const [url, options] = fetchMock.mock.calls[0]; + expect(url).toBe( + "https://cloud-logs.hyperloopupv.com/api/v1/logs?page=1&pageSize=50&sortBy=uploadDate&sortOrder=desc", + ); + expect(options.method).toBe("GET"); + expect(options.headers).toMatchObject({ + Authorization: "Bearer key-123", + "X-API-Key": "key-123", + "X-User": "alice", + }); + + expect(result.items).toHaveLength(1); + expect(result.items[0]).toEqual({ + id: "uuid-1", + user: "alice", + notes: "Run 1 notes", + tags: ["pod", "test"], + date: "2026-10-23T10:00:00Z", + logDate: "2026-10-23T10:00:00Z", + uploadDate: "", + fileName: "run_1.zip", + title: "run_1", + }); + expect(result.nextCursor).toBe("2"); + }); + + it("normalizes various backend field shapes (description, notes, creator, clientUser)", async () => { + const mockItems = [ + { + id: "uuid-2", + clientMetadata: { clientUser: "bob" }, + description: "Description mapped to notes", + tags: ["sensors"], + uploadDate: "2026-11-01T08:00:00Z", + }, + { + id: "uuid-3", + user: "carol", + notes: "Already notes", + tags: null, + date: "2026-11-02T09:00:00", + }, + ]; + + globalThis.fetch = vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ + total: 2, + page: 1, + pageSize: 50, + items: mockItems, + }), + }); + + const result = await listLogs({ credentials: { apiKey: "key-123" } }); + expect(result.items).toEqual([ + { + id: "uuid-2", + user: "bob", + notes: "Description mapped to notes", + tags: ["sensors"], + date: "2026-11-01T08:00:00Z", + logDate: "", + uploadDate: "2026-11-01T08:00:00Z", + fileName: "", + title: "", + }, + { + id: "uuid-3", + user: "carol", + notes: "Already notes", + tags: [], + date: "2026-11-02T09:00:00", + logDate: "2026-11-02T09:00:00", + uploadDate: "", + fileName: "", + title: "", + }, + ]); + expect(result.nextCursor).toBeUndefined(); + }); + + it("maps title and fileName following priority: item.title > clientMetadata.title > fileName without .zip", async () => { + const mockItems = [ + { + id: "item-1", + title: "Explicit Title", + clientMetadata: { title: "Ignored Meta" }, + fileName: "file_1.zip", + }, + { + id: "item-2", + clientMetadata: { title: "Metadata Title" }, + fileName: "file_2.zip", + }, + { + id: "item-3", + fileName: "run_recording_42.zip", + }, + { + id: "item-4", + file_name: "fallback_snake_case.zip", + }, + { + id: "item-5", + }, + ]; + + globalThis.fetch = vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ + total: 5, + items: mockItems, + }), + }); + + const result = await listLogs({ credentials: { apiKey: "key-123" } }); + expect(result.items).toHaveLength(5); + expect(result.items[0].title).toBe("Explicit Title"); + expect(result.items[0].fileName).toBe("file_1.zip"); + expect(result.items[1].title).toBe("Metadata Title"); + expect(result.items[1].fileName).toBe("file_2.zip"); + expect(result.items[2].title).toBe("run_recording_42"); + expect(result.items[2].fileName).toBe("run_recording_42.zip"); + expect(result.items[3].title).toBe("fallback_snake_case"); + expect(result.items[3].fileName).toBe("fallback_snake_case.zip"); + expect(result.items[4].title).toBe(""); + expect(result.items[4].fileName).toBe(""); + }); + + it("throws sanitized error when list request fails", async () => { + const apiKey = "secret-leak-key"; + globalThis.fetch = vi.fn().mockResolvedValue({ + ok: false, + status: 401, + json: async () => ({ detail: `Invalid credentials: ${apiKey}` }), + }); + + await expect(listLogs({ credentials: { apiKey } })).rejects.toThrow(); + try { + await listLogs({ credentials: { apiKey } }); + } catch (err) { + expect(err.message).not.toContain(apiKey); + expect(err.message).toContain("[REDACTED]"); + } + }); + }); + + describe("autocompleteTags", () => { + it("calls GET /logs/tags and returns all tags when query is absent", async () => { + const tags = ["bms", "inverter", "motor", "pod", "propulsion"]; + globalThis.fetch = vi.fn().mockResolvedValue({ + ok: true, + json: async () => tags, + }); + + const result = await autocompleteTags({ + credentials: { apiKey: "key-1" }, + }); + expect(result).toEqual(tags); + }); + + it("filters tags case-insensitively when query is provided", async () => { + const tags = ["BMS", "Brakes", "Inverter", "Motor", "Pod", "Propulsion"]; + globalThis.fetch = vi.fn().mockResolvedValue({ + ok: true, + json: async () => tags, + }); + + const result = await autocompleteTags({ + credentials: { apiKey: "key-1" }, + query: "pr", + }); + expect(result).toEqual(["Propulsion"]); + + const resultP = await autocompleteTags({ + credentials: { apiKey: "key-1" }, + query: "p", + }); + expect(resultP).toEqual(["Pod", "Propulsion"]); + + const resultUpper = await autocompleteTags({ + credentials: { apiKey: "key-1" }, + query: "BRAK", + }); + expect(resultUpper).toEqual(["Brakes"]); + }); + + it("sanitizes error if autocomplete tags request fails", async () => { + const apiKey = "secret-tag-key"; + globalThis.fetch = vi.fn().mockResolvedValue({ + ok: false, + status: 500, + text: async () => `Database error occurred with key ${apiKey}`, + }); + + try { + await autocompleteTags({ credentials: { apiKey } }); + expect.unreachable(); + } catch (err) { + expect(err.message).not.toContain(apiKey); + expect(err.message).toContain("[REDACTED]"); + } + }); + }); + + describe("uploadLog", () => { + let archiveFile; + + beforeEach(async () => { + archiveFile = path.join(tempDir, "session.zip"); + await writeFile(archiveFile, Buffer.from("dummy zip data")); + }); + + it("executes two-phase upload: initiate -> PUT stream -> complete", async () => { + const calls = []; + globalThis.fetch = vi.fn(async (url, options) => { + calls.push({ url, options }); + if (url.endsWith("/logs/initiate")) { + return { + ok: true, + json: async () => ({ + id: "session-uuid-1", + uploadUrl: + "https://www.googleapis.com/upload/drive/v3/files?upload_id=abc", + driveFolder: "2026_11", + status: "pending_upload", + }), + }; + } + if (url.startsWith("https://www.googleapis.com/upload")) { + return { + ok: true, + status: 200, + json: async () => ({ id: "drive-file-id-456" }), + }; + } + if (url.endsWith("/logs/session-uuid-1/complete")) { + return { + ok: true, + json: async () => ({ + id: "session-uuid-1", + status: "ready", + driveUrl: + "https://drive.google.com/file/d/drive-file-id-456/view", + fileName: "session.zip", + }), + }; + } + return { ok: false, status: 404 }; + }); + + const metadata = { + user: "operator_manel", + notes: "Track run test", + tags: ["pod", "speed"], + date: "2026-11-15T12-30-00", + }; + + const result = await uploadLog({ + credentials: { apiKey: "upload-key", user: "operator_manel" }, + archivePath: archiveFile, + metadata, + }); + + expect(calls).toHaveLength(3); + + // 1. Initiate call + const [initiateCall, putCall, completeCall] = calls; + expect(initiateCall.url).toBe( + "https://cloud-logs.hyperloopupv.com/api/v1/logs/initiate", + ); + expect(initiateCall.options.headers).toMatchObject({ + Authorization: "Bearer upload-key", + "X-API-Key": "upload-key", + "X-User": "operator_manel", + }); + const initiateBody = JSON.parse(initiateCall.options.body); + expect(initiateBody).toEqual({ + fileName: "session.zip", + fileSize: 14, + logDate: "2026-11-15T12:30:00Z", + tags: ["pod", "speed"], + note: "Track run test", + user: "operator_manel", + clientMetadata: { + clientUser: "operator_manel", + }, + }); + + // 2. PUT to uploadUrl: MUST NOT leak Authorization or X-API-Key headers + expect(putCall.url).toContain( + "https://www.googleapis.com/upload/drive/v3/files", + ); + expect(putCall.options.method).toBe("PUT"); + expect(putCall.options.headers.Authorization).toBeUndefined(); + expect(putCall.options.headers["X-API-Key"]).toBeUndefined(); + expect(putCall.options.headers["X-User"]).toBeUndefined(); + + // 3. Complete call + expect(completeCall.url).toBe( + "https://cloud-logs.hyperloopupv.com/api/v1/logs/session-uuid-1/complete", + ); + expect(completeCall.options.headers).toMatchObject({ + Authorization: "Bearer upload-key", + "X-API-Key": "upload-key", + }); + expect(JSON.parse(completeCall.options.body)).toEqual({ + driveFileId: "drive-file-id-456", + }); + + // Return value: confirmed CloudLog + expect(result).toEqual({ + id: "session-uuid-1", + user: "operator_manel", + notes: "Track run test", + tags: ["pod", "speed"], + date: "2026-11-15T12-30-00", + fileName: "session.zip", + title: undefined, + }); + }); + + it("respects metadata.fileName if provided, otherwise falling back to path.basename(archivePath)", async () => { + const calls = []; + globalThis.fetch = vi.fn(async (url, options) => { + calls.push({ url, options }); + if (url.endsWith("/logs/initiate")) { + return { + ok: true, + json: async () => ({ + id: "session-uuid-custom-name", + uploadUrl: + "https://www.googleapis.com/upload/drive/v3/files?upload_id=name123", + status: "pending_upload", + }), + }; + } + if (url.startsWith("https://www.googleapis.com/upload")) { + return { + ok: true, + status: 200, + json: async () => ({ id: "drive-custom-name" }), + }; + } + if (url.endsWith("/complete")) { + return { + ok: true, + json: async () => ({ + id: "session-uuid-custom-name", + status: "ready", + }), + }; + } + return { ok: false, status: 404 }; + }); + + await uploadLog({ + credentials: { apiKey: "upload-key", user: "operator_manel" }, + archivePath: archiveFile, + metadata: { + fileName: "2026-02-12T17-01-46.zip", + date: "2026-2-12T17-01-46", + }, + }); + + const initiateCall = calls.find((c) => c.url.endsWith("/logs/initiate")); + expect(initiateCall).toBeDefined(); + const initiateBody = JSON.parse(initiateCall.options.body); + expect(initiateBody.fileName).toBe("2026-02-12T17-01-46.zip"); + expect(initiateBody.logDate).toBe("2026-02-12T17:01:46Z"); + }); + + it("uses metadata.logDate when provided with precedence over metadata.date", async () => { + const calls = []; + globalThis.fetch = vi.fn(async (url, options) => { + calls.push({ url, options }); + if (url.endsWith("/logs/initiate")) { + return { + ok: true, + json: async () => ({ + id: "session-uuid-logdate", + uploadUrl: + "https://www.googleapis.com/upload/drive/v3/files?upload_id=logdate123", + status: "pending_upload", + }), + }; + } + if (url.startsWith("https://www.googleapis.com/upload")) { + return { + ok: true, + status: 200, + json: async () => ({ id: "drive-logdate" }), + }; + } + if (url.endsWith("/complete")) { + return { + ok: true, + json: async () => ({ + id: "session-uuid-logdate", + status: "ready", + }), + }; + } + return { ok: false, status: 404 }; + }); + + await uploadLog({ + credentials: { apiKey: "upload-key", user: "operator_manel" }, + archivePath: archiveFile, + metadata: { + logDate: "2026-11-20T10:00:00Z", + date: "2026-11-19T09:00:00Z", + }, + }); + + const initiateCall = calls.find((c) => c.url.endsWith("/logs/initiate")); + expect(initiateCall).toBeDefined(); + const initiateBody = JSON.parse(initiateCall.options.body); + expect(initiateBody.logDate).toBe("2026-11-20T10:00:00Z"); + }); + + it("aborts upload via POST /logs/{id}/abort if PUT to uploadUrl fails", async () => { + const calls = []; + globalThis.fetch = vi.fn(async (url, options) => { + calls.push({ url, options }); + if (url.endsWith("/logs/initiate")) { + return { + ok: true, + json: async () => ({ + id: "session-uuid-abort", + uploadUrl: "https://storage.googleapis.com/resumable-upload", + status: "pending_upload", + }), + }; + } + if (url.startsWith("https://storage.googleapis.com")) { + return { + ok: false, + status: 503, + statusText: "Service Unavailable", + text: async () => "Google storage connection refused", + }; + } + if (url.endsWith("/logs/session-uuid-abort/abort")) { + return { + ok: true, + json: async () => ({ id: "session-uuid-abort", status: "aborted" }), + }; + } + return { ok: false, status: 404 }; + }); + + const apiKey = "abort-test-key"; + await expect( + uploadLog({ + credentials: { apiKey, user: "operator_test" }, + archivePath: archiveFile, + metadata: { notes: "test", tags: [] }, + }), + ).rejects.toThrow(); + + // Verify abort was called + const abortCall = calls.find((c) => + c.url.endsWith("/logs/session-uuid-abort/abort"), + ); + expect(abortCall).toBeDefined(); + expect(abortCall.options.method).toBe("POST"); + expect(abortCall.options.headers).toMatchObject({ + Authorization: `Bearer ${apiKey}`, + "X-API-Key": apiKey, + }); + const abortBody = JSON.parse(abortCall.options.body); + expect(abortBody.reason).toMatch(/failed with status 503/i); + }); + + it("aborts upload via POST /logs/{id}/abort if complete request fails", async () => { + const calls = []; + globalThis.fetch = vi.fn(async (url, options) => { + calls.push({ url, options }); + if (url.endsWith("/logs/initiate")) { + return { + ok: true, + json: async () => ({ + id: "session-uuid-complete-fail", + uploadUrl: "https://storage.googleapis.com/resumable-upload", + status: "pending_upload", + }), + }; + } + if (url.startsWith("https://storage.googleapis.com")) { + return { + ok: true, + status: 200, + json: async () => ({ id: "drive-file-999" }), + }; + } + if (url.endsWith("/complete")) { + return { + ok: false, + status: 400, + json: async () => ({ + detail: "File verification failed in Google Drive", + }), + }; + } + if (url.endsWith("/abort")) { + return { + ok: true, + json: async () => ({ status: "aborted" }), + }; + } + return { ok: false, status: 404 }; + }); + + await expect( + uploadLog({ + credentials: { apiKey: "key-123" }, + archivePath: archiveFile, + metadata: { notes: "test", tags: [] }, + }), + ).rejects.toThrow(/File verification failed/); + + const abortCall = calls.find((c) => c.url.endsWith("/abort")); + expect(abortCall).toBeDefined(); + }); + + it("returns credentials.user if metadata.user is omitted", async () => { + globalThis.fetch = vi.fn(async (url) => { + if (url.endsWith("/logs/initiate")) { + return { + ok: true, + json: async () => ({ + id: "session-uuid-no-user", + uploadUrl: + "https://www.googleapis.com/upload/drive/v3/files?upload_id=user1", + status: "pending_upload", + }), + }; + } + if (url.startsWith("https://www.googleapis.com/upload")) { + return { + ok: true, + status: 200, + json: async () => ({ id: "drive-file-id-user1" }), + }; + } + if (url.endsWith("/complete")) { + return { + ok: true, + json: async () => ({ id: "session-uuid-no-user", status: "ready" }), + }; + } + return { ok: false, status: 404 }; + }); + + const metadata = { + notes: "Omitted user metadata", + tags: ["test"], + date: "2026-11-15T12-30-00", + }; + + const result = await uploadLog({ + credentials: { apiKey: "upload-key", user: "cred_operator_user" }, + archivePath: archiveFile, + metadata, + }); + + expect(result.user).toBe("cred_operator_user"); + expect(result).toEqual({ + id: "session-uuid-no-user", + user: "cred_operator_user", + notes: "Omitted user metadata", + tags: ["test"], + date: "2026-11-15T12-30-00", + fileName: "session.zip", + title: undefined, + }); + }); + + it("includes title inside clientMetadata when metadata.title is provided, and returns fileName and title in confirmed log", async () => { + const calls = []; + globalThis.fetch = vi.fn(async (url, options) => { + calls.push({ url, options }); + if (url.endsWith("/logs/initiate")) { + return { + ok: true, + json: async () => ({ + id: "session-uuid-title-1", + uploadUrl: + "https://www.googleapis.com/upload/drive/v3/files?upload_id=title1", + status: "pending_upload", + }), + }; + } + if (url.startsWith("https://www.googleapis.com/upload")) { + return { + ok: true, + status: 200, + json: async () => ({ id: "drive-file-id-title1" }), + }; + } + if (url.endsWith("/complete")) { + return { + ok: true, + json: async () => ({ + id: "session-uuid-title-1", + status: "ready", + }), + }; + } + return { ok: false, status: 404 }; + }); + + const metadata = { + title: "BMS Track Run", + fileName: "BMS Track Run.zip", + user: "operator_manel", + notes: "Run notes", + tags: ["bms"], + date: "2026-11-15T12-30-00", + }; + + const result = await uploadLog({ + credentials: { apiKey: "upload-key", user: "operator_manel" }, + archivePath: archiveFile, + metadata, + }); + + const initiateCall = calls.find((c) => c.url.endsWith("/logs/initiate")); + expect(initiateCall).toBeDefined(); + const initiateBody = JSON.parse(initiateCall.options.body); + + expect(initiateBody.clientMetadata).toEqual({ + clientUser: "operator_manel", + title: "BMS Track Run", + }); + expect(initiateBody.fileName).toBe("BMS Track Run.zip"); + + expect(result).toEqual({ + id: "session-uuid-title-1", + user: "operator_manel", + notes: "Run notes", + tags: ["bms"], + date: "2026-11-15T12-30-00", + fileName: "BMS Track Run.zip", + title: "BMS Track Run", + }); + }); + }); + + describe("downloadLog", () => { + it("handles 307 temporary redirect, strips auth headers, and streams to file", async () => { + const destination = path.join(tempDir, "downloaded.zip"); + const fakeBinaryContent = Buffer.from( + "ZIP FILE BYTES CONTENT 1234567890", + ); + + const calls = []; + globalThis.fetch = vi.fn(async (url, options) => { + calls.push({ url, options }); + if (url.endsWith("/logs/log-123/download")) { + return { + status: 307, + headers: new Headers({ + location: + "https://drive.google.com/uc?export=download&id=abc1234", + }), + }; + } + if (url.startsWith("https://drive.google.com")) { + return { + ok: true, + status: 200, + body: new ReadableStream({ + start(controller) { + controller.enqueue(fakeBinaryContent.subarray(0, 10)); + controller.enqueue(fakeBinaryContent.subarray(10)); + controller.close(); + }, + }), + }; + } + return { ok: false, status: 404 }; + }); + + const apiKey = "download-secret-key"; + await downloadLog({ + credentials: { apiKey, user: "user-1" }, + id: "log-123", + destination, + }); + + expect(calls).toHaveLength(2); + + // Call 1: trusted API with auth headers and redirect: 'manual' + const [initialCall, redirectCall] = calls; + expect(initialCall.url).toBe( + "https://cloud-logs.hyperloopupv.com/api/v1/logs/log-123/download", + ); + expect(initialCall.options.redirect).toBe("manual"); + expect(initialCall.options.headers).toMatchObject({ + Authorization: `Bearer ${apiKey}`, + "X-API-Key": apiKey, + "X-User": "user-1", + }); + + // Call 2: Google Drive redirect target WITHOUT auth headers + expect(redirectCall.url).toBe( + "https://drive.google.com/uc?export=download&id=abc1234", + ); + expect(redirectCall.options.headers).toBeUndefined(); + + // Verify file written and closed + const written = await readFile(destination); + expect(written).toEqual(fakeBinaryContent); + }); + + it("handles direct 200 response and streams to destination", async () => { + const destination = path.join(tempDir, "direct.zip"); + const content = Buffer.from("Direct 200 stream payload"); + + globalThis.fetch = vi.fn().mockResolvedValue({ + status: 200, + ok: true, + body: new ReadableStream({ + start(controller) { + controller.enqueue(content); + controller.close(); + }, + }), + }); + + await downloadLog({ + credentials: { apiKey: "key-1" }, + id: "log-direct", + destination, + }); + + const written = await readFile(destination); + expect(written).toEqual(content); + }); + + it("enforces maxBytes limit: aborts stream, unlinks destination, and throws error", async () => { + const destination = path.join(tempDir, "oversized.zip"); + const chunk1 = Buffer.alloc(500, "a"); + const chunk2 = Buffer.alloc(600, "b"); + + globalThis.fetch = vi.fn().mockResolvedValue({ + status: 200, + ok: true, + body: new ReadableStream({ + start(controller) { + controller.enqueue(chunk1); + controller.enqueue(chunk2); + controller.close(); + }, + }), + }); + + await expect( + downloadLog({ + credentials: { apiKey: "key-1" }, + id: "log-oversized", + destination, + maxBytes: 800, // smaller than 500 + 600 = 1100 + }), + ).rejects.toThrow(/Download exceeded maximum allowed size/); + + // Verify file was unlinked and does not exist + await expect(stat(destination)).rejects.toThrow(); + }); + + it("sanitizes error if download response returns error with API key", async () => { + const destination = path.join(tempDir, "error.zip"); + const apiKey = "download-fail-key"; + + globalThis.fetch = vi.fn().mockResolvedValue({ + status: 404, + ok: false, + json: async () => ({ detail: `Log not found for apiKey ${apiKey}` }), + }); + + try { + await downloadLog({ + credentials: { apiKey }, + id: "log-missing", + destination, + }); + expect.unreachable(); + } catch (err) { + expect(err.message).not.toContain(apiKey); + expect(err.message).toContain("[REDACTED]"); + } + }); + + it("handles relative redirect paths using new URL(location, downloadEndpoint)", async () => { + const destination = path.join(tempDir, "relative-redirect.zip"); + const fakeBinaryContent = Buffer.from("RELATIVE REDIRECT STREAM CONTENT"); + + const calls = []; + globalThis.fetch = vi.fn(async (url, options) => { + calls.push({ url, options }); + if (url.endsWith("/logs/log-rel-1/download")) { + return { + status: 302, + headers: new Headers({ + location: "/storage/archives/log-rel-1.zip", + }), + }; + } + if ( + url === + "https://cloud-logs.hyperloopupv.com/storage/archives/log-rel-1.zip" + ) { + return { + ok: true, + status: 200, + body: new ReadableStream({ + start(controller) { + controller.enqueue(fakeBinaryContent); + controller.close(); + }, + }), + }; + } + return { ok: false, status: 404 }; + }); + + await downloadLog({ + credentials: { apiKey: "key-1", user: "rel_user" }, + id: "log-rel-1", + destination, + }); + + expect(calls).toHaveLength(2); + const [initialCall, redirectCall] = calls; + expect(initialCall.url).toBe( + "https://cloud-logs.hyperloopupv.com/api/v1/logs/log-rel-1/download", + ); + // Resolved target URL must match the expected URL resolved against downloadEndpoint + expect(redirectCall.url).toBe( + "https://cloud-logs.hyperloopupv.com/storage/archives/log-rel-1.zip", + ); + expect(redirectCall.options.headers).toBeUndefined(); + + const written = await readFile(destination); + expect(written).toEqual(fakeBinaryContent); + }); + }); +}); diff --git a/electron-app/src/cloudLogs/__tests__/handlers.test.js b/electron-app/src/cloudLogs/__tests__/handlers.test.js new file mode 100644 index 000000000..f8d784787 --- /dev/null +++ b/electron-app/src/cloudLogs/__tests__/handlers.test.js @@ -0,0 +1,866 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +const { handlers, mockIpcMain } = vi.hoisted(() => { + const map = new Map(); + return { + handlers: map, + mockIpcMain: { + handle: vi.fn((channel, fn) => { + map.set(channel, fn); + }), + }, + }; +}); + +vi.mock("electron", () => ({ + BrowserWindow: { + fromWebContents: vi.fn(), + }, + dialog: { + showOpenDialog: vi.fn(), + }, + ipcMain: mockIpcMain, +})); + +vi.mock("../../utils/paths.js", () => ({ + getAppPath: () => "/app", + getBackendWorkingDir: () => "/app", +})); + +vi.mock("../credentials.js", () => ({ + getCredentials: vi + .fn() + .mockResolvedValue({ user: "testuser", apiKey: "secret-key-123" }), + getCredentialsStatus: vi + .fn() + .mockResolvedValue({ user: "testuser", hasApiKey: true, persistent: true }), + setCredentials: vi.fn(), + clearCredentials: vi.fn(), +})); + +vi.mock("../client.js", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + listLogs: vi.fn(), + autocompleteTags: vi.fn(), + uploadLog: vi.fn(), + downloadLog: vi.fn(), + }; +}); + +vi.mock("../archive.js", () => ({ + compressSession: vi.fn(), + extractSession: vi.fn(), +})); + +vi.mock("../sessions.js", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + findLocalSessions: vi.fn(), + formatSessionZipName: vi.fn((date, title) => { + if (typeof title === "string" && title.trim()) { + return `${title.trim()}.zip`; + } + return date ? `${date}.zip` : "2026-01-01T00-00-00.zip"; + }), + getCloudRoot: vi.fn(), + getLogsRoot: vi.fn().mockResolvedValue("/app/logger"), + inspectSession: vi.fn(), + }; +}); + +import { dialog } from "electron"; +import * as archive from "../archive.js"; +import * as sessions from "../sessions.js"; +import * as client from "../client.js"; +import { setupCloudLogsHandlers } from "../handlers.js"; + +describe("Cloud Logs IPC handlers", () => { + beforeEach(() => { + handlers.clear(); + vi.clearAllMocks(); + setupCloudLogsHandlers(); + }); + + const createEvent = () => { + const mainFrame = { + url: "file:///app/renderer/logging-view/index.html", + }; + return { + sender: { + id: 1, + mainFrame, + isDestroyed: () => false, + send: vi.fn(), + }, + senderFrame: mainFrame, + }; + }; + + describe("assertSender validation", () => { + it("rejects calls from unauthorized URLs or views", async () => { + const listHandler = handlers.get("cloud-logs:list"); + const evilEvent = { + sender: { + id: 2, + mainFrame: { url: "file:///other-app/index.html" }, + isDestroyed: () => false, + }, + senderFrame: { url: "file:///other-app/index.html" }, + }; + await expect(listHandler(evilEvent)).rejects.toThrow( + "Cloud Logs is only available to local Logging and Testing views.", + ); + }); + + it("rejects calls from child frames even with allowed URL", async () => { + const listHandler = handlers.get("cloud-logs:list"); + const mainFrame = { url: "file:///app/renderer/logging-view/index.html" }; + const childFrame = { + url: "file:///app/renderer/logging-view/index.html", + }; + const iframeEvent = { + sender: { id: 1, mainFrame, isDestroyed: () => false }, + senderFrame: childFrame, + }; + await expect(listHandler(iframeEvent)).rejects.toThrow( + "Cloud Logs is only available to local Logging and Testing views.", + ); + }); + }); + + describe("list handler", () => { + it("handles undefined, null, empty, and whitespace cursors gracefully", async () => { + const listHandler = handlers.get("cloud-logs:list"); + expect(listHandler).toBeDefined(); + + client.listLogs.mockResolvedValueOnce({ items: [], nextCursor: "2" }); + const resUndef = await listHandler(createEvent(), undefined); + expect(client.listLogs).toHaveBeenCalledWith({ + credentials: { user: "testuser", apiKey: "secret-key-123" }, + cursor: undefined, + }); + expect(resUndef).toEqual({ items: [], nextCursor: "2" }); + + client.listLogs.mockResolvedValueOnce({ items: [] }); + await listHandler(createEvent(), null); + expect(client.listLogs).toHaveBeenCalledWith({ + credentials: { user: "testuser", apiKey: "secret-key-123" }, + cursor: undefined, + }); + + client.listLogs.mockResolvedValueOnce({ items: [] }); + await listHandler(createEvent(), ""); + expect(client.listLogs).toHaveBeenCalledWith({ + credentials: { user: "testuser", apiKey: "secret-key-123" }, + cursor: undefined, + }); + + client.listLogs.mockResolvedValueOnce({ items: [] }); + await listHandler(createEvent(), " "); + expect(client.listLogs).toHaveBeenCalledWith({ + credentials: { user: "testuser", apiKey: "secret-key-123" }, + cursor: undefined, + }); + }); + + it("passes valid trimmed cursor string to client", async () => { + const listHandler = handlers.get("cloud-logs:list"); + client.listLogs.mockResolvedValueOnce({ items: [] }); + + await listHandler(createEvent(), "page-2"); + expect(client.listLogs).toHaveBeenCalledWith({ + credentials: { user: "testuser", apiKey: "secret-key-123" }, + cursor: "page-2", + }); + + client.listLogs.mockResolvedValueOnce({ items: [] }); + await listHandler(createEvent(), " cursor-token-42 "); + expect(client.listLogs).toHaveBeenCalledWith({ + credentials: { user: "testuser", apiKey: "secret-key-123" }, + cursor: "cursor-token-42", + }); + }); + + it("rejects non-string cursor types", async () => { + const listHandler = handlers.get("cloud-logs:list"); + await expect(listHandler(createEvent(), 123)).rejects.toThrow( + "Invalid Cloud Logs request.", + ); + await expect(listHandler(createEvent(), {})).rejects.toThrow( + "Invalid Cloud Logs request.", + ); + }); + + it("cleans and redacts error messages from client", async () => { + const listHandler = handlers.get("cloud-logs:list"); + client.listLogs.mockRejectedValueOnce( + new Error( + "Request failed with Bearer secret-token-xyz and x-api-key: master-key-999", + ), + ); + + await expect(listHandler(createEvent(), undefined)).rejects.toThrow( + "Request failed with Bearer [REDACTED] and x-api-key: [REDACTED]", + ); + }); + }); + + describe("tags handler", () => { + it("handles tag queries and sanitizes errors", async () => { + const tagsHandler = handlers.get("cloud-logs:tags"); + expect(tagsHandler).toBeDefined(); + + client.autocompleteTags.mockResolvedValueOnce(["bms", "motor"]); + const tags = await tagsHandler(createEvent(), "bm"); + expect(tags).toEqual(["bms", "motor"]); + expect(client.autocompleteTags).toHaveBeenCalledWith({ + credentials: { user: "testuser", apiKey: "secret-key-123" }, + query: "bm", + }); + + client.autocompleteTags.mockRejectedValueOnce( + new Error("API failure: Authorization: Bearer secret-token-123"), + ); + await expect(tagsHandler(createEvent(), "pod")).rejects.toThrow( + "API failure: Authorization: Bearer [REDACTED]", + ); + }); + + it("rejects invalid queries", async () => { + const tagsHandler = handlers.get("cloud-logs:tags"); + await expect(tagsHandler(createEvent(), 123)).rejects.toThrow( + "Invalid tag query.", + ); + await expect(tagsHandler(createEvent(), "a".repeat(201))).rejects.toThrow( + "Invalid tag query.", + ); + }); + }); + + describe("upload handler", () => { + it("compresses and forwards upload metadata to client.uploadLog", async () => { + const uploadHandler = handlers.get("cloud-logs:upload"); + const selectHandler = handlers.get("cloud-logs:select-session"); + expect(uploadHandler).toBeDefined(); + expect(selectHandler).toBeDefined(); + + const event = createEvent(); + dialog.showOpenDialog.mockResolvedValueOnce({ + canceled: false, + filePaths: ["/app/logger/2026-11-15T12-00-00/2026-11-15T12-30-00"], + }); + + sessions.inspectSession.mockResolvedValueOnce({ + name: "2026-11-15T12-30-00", + launch: "2026-11-15T12-00-00", + date: "2026-11-15T12-30-00", + bytes: 100, + fileCount: 2, + files: [], + }); + + archive.compressSession.mockResolvedValueOnce({ + name: "2026-11-15T12-30-00", + date: "2026-11-15T12-30-00", + }); + + client.uploadLog.mockResolvedValueOnce({ + id: "upload-1", + user: "testuser", + notes: "Test notes", + tags: ["pod"], + date: "2026-11-15T12-30-00", + }); + + const selected = await selectHandler(event); + expect(selected).toBeDefined(); + + const result = await uploadHandler(event, { + sessionId: selected.id, + notes: "Test notes", + tags: ["pod"], + requestId: "req-upload-1", + }); + + expect(client.uploadLog).toHaveBeenCalledWith({ + credentials: { user: "testuser", apiKey: "secret-key-123" }, + archivePath: expect.stringContaining("2026-11-15T12-30-00.zip"), + metadata: { + fileName: "2026-11-15T12-30-00.zip", + title: undefined, + user: "testuser", + notes: "Test notes", + tags: ["pod"], + date: "2026-11-15T12-30-00", + }, + }); + expect(result).toEqual({ + id: "upload-1", + user: "testuser", + notes: "Test notes", + tags: ["pod"], + date: "2026-11-15T12-30-00", + }); + }); + + it("extracts custom title and passes archiveName and title to client.uploadLog", async () => { + const uploadHandler = handlers.get("cloud-logs:upload"); + const selectHandler = handlers.get("cloud-logs:select-session"); + + const event = createEvent(); + dialog.showOpenDialog.mockResolvedValueOnce({ + canceled: false, + filePaths: ["/app/logger/2026-11-15T12-00-00/2026-11-15T12-30-00"], + }); + + sessions.inspectSession.mockResolvedValueOnce({ + name: "2026-11-15T12-30-00", + launch: "2026-11-15T12-00-00", + date: "2026-11-15T12-30-00", + bytes: 100, + fileCount: 2, + files: [], + }); + + archive.compressSession.mockResolvedValueOnce({ + name: "2026-11-15T12-30-00", + date: "2026-11-15T12-30-00", + }); + + client.uploadLog.mockResolvedValueOnce({ + id: "upload-title-1", + user: "testuser", + notes: "Notes with title", + tags: ["run"], + date: "2026-11-15T12-30-00", + fileName: "High Speed Run.zip", + title: "High Speed Run", + }); + + const selected = await selectHandler(event); + expect(selected).toBeDefined(); + + const result = await uploadHandler(event, { + sessionId: selected.id, + title: "High Speed Run", + notes: "Notes with title", + tags: ["run"], + requestId: "req-upload-title-1", + }); + + expect(sessions.formatSessionZipName).toHaveBeenCalledWith( + "2026-11-15T12-30-00", + "High Speed Run", + ); + expect(client.uploadLog).toHaveBeenCalledWith({ + credentials: { user: "testuser", apiKey: "secret-key-123" }, + archivePath: expect.stringContaining("High Speed Run.zip"), + metadata: { + fileName: "High Speed Run.zip", + title: "High Speed Run", + user: "testuser", + notes: "Notes with title", + tags: ["run"], + date: "2026-11-15T12-30-00", + }, + }); + expect(result).toEqual({ + id: "upload-title-1", + user: "testuser", + notes: "Notes with title", + tags: ["run"], + date: "2026-11-15T12-30-00", + fileName: "High Speed Run.zip", + title: "High Speed Run", + }); + }); + + it("rejects upload when title exceeds 200 characters", async () => { + const uploadHandler = handlers.get("cloud-logs:upload"); + const selectHandler = handlers.get("cloud-logs:select-session"); + + const event = createEvent(); + dialog.showOpenDialog.mockResolvedValueOnce({ + canceled: false, + filePaths: ["/app/logger/2026-11-15T12-00-00/2026-11-15T12-30-00"], + }); + + sessions.inspectSession.mockResolvedValueOnce({ + name: "2026-11-15T12-30-00", + launch: "2026-11-15T12-00-00", + date: "2026-11-15T12-30-00", + bytes: 100, + fileCount: 2, + files: [], + }); + + const selected = await selectHandler(event); + + await expect( + uploadHandler(event, { + sessionId: selected.id, + title: "a".repeat(201), + notes: "Notes", + tags: [], + requestId: "req-upload-too-long", + }), + ).rejects.toThrow("Invalid Cloud Logs request."); + }); + + it("allows upload with empty title without throwing Invalid Cloud Logs request", async () => { + const uploadHandler = handlers.get("cloud-logs:upload"); + const selectHandler = handlers.get("cloud-logs:select-session"); + + const event = createEvent(); + dialog.showOpenDialog.mockResolvedValueOnce({ + canceled: false, + filePaths: ["/app/logger/2026-11-15T12-00-00/2026-11-15T12-30-00"], + }); + + sessions.inspectSession.mockResolvedValueOnce({ + name: "2026-11-15T12-30-00", + launch: "2026-11-15T12-00-00", + date: "2026-11-15T12-30-00", + bytes: 100, + fileCount: 2, + files: [], + }); + + archive.compressSession.mockResolvedValueOnce({ + name: "2026-11-15T12-30-00", + date: "2026-11-15T12-30-00", + }); + + client.uploadLog.mockResolvedValueOnce({ + id: "upload-empty-title", + user: "testuser", + notes: "Notes with empty title", + tags: [], + date: "2026-11-15T12-30-00", + fileName: "2026-11-15T12-30-00.zip", + title: undefined, + }); + + const selected = await selectHandler(event); + + const result = await uploadHandler(event, { + sessionId: selected.id, + title: "", + notes: "Notes with empty title", + tags: [], + requestId: "req-upload-empty-title", + }); + + expect(sessions.formatSessionZipName).toHaveBeenCalledWith( + "2026-11-15T12-30-00", + "", + ); + expect(client.uploadLog).toHaveBeenCalledWith({ + credentials: { user: "testuser", apiKey: "secret-key-123" }, + archivePath: expect.stringContaining("2026-11-15T12-30-00.zip"), + metadata: { + fileName: "2026-11-15T12-30-00.zip", + title: undefined, + user: "testuser", + notes: "Notes with empty title", + tags: [], + date: "2026-11-15T12-30-00", + }, + }); + expect(result.id).toBe("upload-empty-title"); + }); + }); + + describe("download handler", () => { + let testCloudRoot; + + beforeEach(async () => { + testCloudRoot = await mkdtemp(path.join(tmpdir(), "cloud-logs-dl-test-")); + sessions.getCloudRoot.mockResolvedValue(testCloudRoot); + sessions.inspectSession.mockResolvedValue({ + date: "2026-11-15T12-30-00", + fileCount: 3, + bytes: 1024, + }); + client.downloadLog.mockImplementation(async ({ destination }) => { + await writeFile(destination, "mock zip content"); + }); + archive.extractSession.mockImplementation(async (_zip, dest) => { + await mkdir(dest, { recursive: true }); + return { date: "2026-11-15T12-30-00" }; + }); + }); + + afterEach(async () => { + await rm(testCloudRoot, { recursive: true, force: true }); + }); + + it("downloads and names archive using fileName when provided", async () => { + const downloadHandler = handlers.get("cloud-logs:download"); + const event = createEvent(); + + const result = await downloadHandler(event, { + id: "session-1", + title: "Test Run Title", + fileName: "custom-run-1.zip", + requestId: "req-dl-1", + }); + + expect(client.downloadLog).toHaveBeenCalledWith({ + credentials: { user: "testuser", apiKey: "secret-key-123" }, + id: "session-1", + destination: expect.stringMatching(/[/\\]custom-run-1\.zip$/), + maxBytes: 4 * 1024 ** 3, + }); + + const expectedDir = path.join(testCloudRoot, "custom-run-1-12-30-00"); + expect(result).toEqual({ + id: "session-1", + path: expectedDir, + date: "2026-11-15T12-30-00", + title: "Test Run Title", + fileName: "custom-run-1.zip", + }); + + const savedInfo = JSON.parse( + await readFile(path.join(expectedDir, "cloud-log.json"), "utf8"), + ); + expect(savedInfo).toEqual({ + id: "session-1", + date: "2026-11-15T12-30-00", + title: "Test Run Title", + fileName: "custom-run-1.zip", + }); + }); + + it("appends .zip to fileName if missing", async () => { + const downloadHandler = handlers.get("cloud-logs:download"); + const event = createEvent(); + + const result = await downloadHandler(event, { + id: "session-2", + fileName: "session-no-ext", + requestId: "req-dl-2", + }); + + expect(client.downloadLog).toHaveBeenCalledWith( + expect.objectContaining({ + destination: expect.stringMatching(/[/\\]session-no-ext\.zip$/), + }), + ); + expect(result.title).toBe("session-no-ext"); + expect(result.fileName).toBe("session-no-ext"); + }); + + it("derives archiveName from title with sanitized characters when fileName is omitted", async () => { + const downloadHandler = handlers.get("cloud-logs:download"); + const event = createEvent(); + + const result = await downloadHandler(event, { + id: "session-3", + title: "Test/Run:1*Speed?2", + requestId: "req-dl-3", + }); + + expect(client.downloadLog).toHaveBeenCalledWith( + expect.objectContaining({ + destination: expect.stringMatching(/[/\\]Test_Run_1_Speed_2\.zip$/), + }), + ); + expect(result.title).toBe("Test/Run:1*Speed?2"); + expect(result.fileName).toBe("Test_Run_1_Speed_2.zip"); + }); + + it("falls back to id.zip when neither fileName nor title is provided", async () => { + const downloadHandler = handlers.get("cloud-logs:download"); + const event = createEvent(); + + const result = await downloadHandler(event, { + id: "session-4", + requestId: "req-dl-4", + }); + + expect(client.downloadLog).toHaveBeenCalledWith( + expect.objectContaining({ + destination: expect.stringMatching(/[/\\]session-4\.zip$/), + }), + ); + expect(result.title).toBe(""); + expect(result.fileName).toBe("session-4.zip"); + }); + + it("returns cached session data with title and fileName on cache hit", async () => { + const downloadHandler = handlers.get("cloud-logs:download"); + const event = createEvent(); + + // First download + await downloadHandler(event, { + id: "session-cache", + title: "Original Title", + fileName: "cached-session.zip", + requestId: "req-cache-1", + }); + expect(client.downloadLog).toHaveBeenCalledTimes(1); + + // Second download with same id (cache hit) + const cached = await downloadHandler(event, { + id: "session-cache", + requestId: "req-cache-2", + }); + + expect(client.downloadLog).toHaveBeenCalledTimes(1); + expect(cached).toEqual({ + id: "session-cache", + path: path.join(testCloudRoot, "cached-session-12-30-00"), + date: "2026-11-15T12-30-00", + title: "Original Title", + fileName: "cached-session.zip", + }); + }); + + it("derives title from fileName on cache hit if info.title is missing", async () => { + const downloadHandler = handlers.get("cloud-logs:download"); + const event = createEvent(); + const id = "session-cache-no-title"; + const dir = path.join(testCloudRoot, "legacy-run-12-30-00"); + await mkdir(dir, { recursive: true }); + await writeFile( + path.join(dir, "cloud-log.json"), + JSON.stringify({ + id, + date: "2026-11-15T12-30-00", + fileName: "legacy-run.zip", + }), + ); + + const cached = await downloadHandler(event, { + id, + requestId: "req-cache-3", + }); + expect(client.downloadLog).not.toHaveBeenCalled(); + expect(cached.title).toBe("legacy-run"); + expect(cached.fileName).toBe("legacy-run.zip"); + }); + + it("handles download with empty title and empty fileName without throwing", async () => { + const downloadHandler = handlers.get("cloud-logs:download"); + const event = createEvent(); + + const result = await downloadHandler(event, { + id: "session-empty-props", + title: "", + fileName: "", + requestId: "req-dl-empty", + }); + + expect(client.downloadLog).toHaveBeenCalledWith( + expect.objectContaining({ + destination: expect.stringMatching(/[/\\]session-empty-props\.zip$/), + }), + ); + expect(result.title).toBe(""); + expect(result.fileName).toBe("session-empty-props.zip"); + }); + + it("sanitizes fileName with special characters and path subdirectories", async () => { + const downloadHandler = handlers.get("cloud-logs:download"); + const event = createEvent(); + + const result = await downloadHandler(event, { + id: "session-sanitize", + fileName: "../../nested/bad:file*name?.zip", + requestId: "req-dl-sanitize", + }); + + expect(client.downloadLog).toHaveBeenCalledWith( + expect.objectContaining({ + destination: expect.stringMatching(/[/\\]bad_file_name_\.zip$/), + }), + ); + expect(result.fileName).toBe("bad_file_name_.zip"); + }); + + it("cleans up corrupt cache directory and redownloads when cloud-log.json is invalid", async () => { + const downloadHandler = handlers.get("cloud-logs:download"); + const event = createEvent(); + const id = "session-corrupt-cache"; + const dir = path.join(testCloudRoot, "corrupt-cache-dir"); + await mkdir(dir, { recursive: true }); + await writeFile( + path.join(dir, "cloud-log.json"), + `{"id":"${id}", invalid:`, + ); + + const result = await downloadHandler(event, { + id, + title: "Recovered Title", + requestId: "req-dl-corrupt", + }); + + expect(client.downloadLog).toHaveBeenCalledTimes(1); + expect(result.id).toBe(id); + expect(result.title).toBe("Recovered Title"); + }); + + it("disambiguates destination folder name when destination exists for a different session", async () => { + const downloadHandler = handlers.get("cloud-logs:download"); + const event = createEvent(); + + const existingDir = path.join(testCloudRoot, "custom-run-12-30-00"); + await mkdir(existingDir, { recursive: true }); + await writeFile( + path.join(existingDir, "cloud-log.json"), + JSON.stringify({ + id: "other-id", + date: "2026-11-15T12-30-00", + fileName: "custom-run.zip", + }), + ); + + const result = await downloadHandler(event, { + id: "new-id", + fileName: "custom-run.zip", + requestId: "req-dl-disambiguate", + }); + + const disambiguatedDir = path.join( + testCloudRoot, + "custom-run-12-30-00_2", + ); + expect(result.path).toBe(disambiguatedDir); + + const existingContent = JSON.parse( + await readFile(path.join(existingDir, "cloud-log.json"), "utf8"), + ); + expect(existingContent.id).toBe("other-id"); + + const newContent = JSON.parse( + await readFile(path.join(disambiguatedDir, "cloud-log.json"), "utf8"), + ); + expect(newContent.id).toBe("new-id"); + }); + + it("rejects download with invalid id, title > 200, or fileName > 255", async () => { + const downloadHandler = handlers.get("cloud-logs:download"); + const event = createEvent(); + + await expect( + downloadHandler(event, { id: "", requestId: "req-err-1" }), + ).rejects.toThrow("Invalid Cloud Logs request."); + + await expect( + downloadHandler(event, { + id: "session-err", + title: "a".repeat(201), + requestId: "req-err-2", + }), + ).rejects.toThrow("Invalid Cloud Logs request."); + + await expect( + downloadHandler(event, { + id: "session-err", + fileName: "a".repeat(256), + requestId: "req-err-3", + }), + ).rejects.toThrow("Invalid Cloud Logs request."); + }); + }); + + describe("downloads handler", () => { + let testCloudRoot; + + beforeEach(async () => { + testCloudRoot = await mkdtemp( + path.join(tmpdir(), "cloud-logs-dls-test-"), + ); + sessions.getCloudRoot.mockResolvedValue(testCloudRoot); + }); + + afterEach(async () => { + await rm(testCloudRoot, { recursive: true, force: true }); + }); + + it("returns list of downloaded sessions including title and fileName sorted by date descending", async () => { + const downloadsHandler = handlers.get("cloud-logs:downloads"); + expect(downloadsHandler).toBeDefined(); + + const item1Id = "session-1"; + const item1Dir = path.join(testCloudRoot, "Run A - 12-00-00"); + await mkdir(item1Dir, { recursive: true }); + await writeFile( + path.join(item1Dir, "cloud-log.json"), + JSON.stringify({ + id: item1Id, + date: "2026-11-15T12-00-00", + title: "Run A", + fileName: "run-a.zip", + }), + ); + + const item2Id = "session-2"; + const item2Dir = path.join(testCloudRoot, "run-b - 14-00-00"); + await mkdir(item2Dir, { recursive: true }); + await writeFile( + path.join(item2Dir, "cloud-log.json"), + JSON.stringify({ + id: item2Id, + date: "2026-11-15T14-00-00", + fileName: "run-b.zip", + }), + ); + + const item3Id = "session-3"; + const item3Dir = path.join(testCloudRoot, "session-3 - 10-00-00"); + await mkdir(item3Dir, { recursive: true }); + await writeFile( + path.join(item3Dir, "cloud-log.json"), + JSON.stringify({ + id: item3Id, + date: "2026-11-15T10-00-00", + }), + ); + + // Directory without cloud-log.json should be skipped + const nonSessionDir = path.join(testCloudRoot, "unrelated-dir"); + await mkdir(nonSessionDir, { recursive: true }); + + sessions.inspectSession.mockImplementation(async (dir) => { + if (dir === item1Dir) return { date: "2026-11-15T12-00-00" }; + if (dir === item2Dir) return { date: "2026-11-15T14-00-00" }; + if (dir === item3Dir) return { date: "2026-11-15T10-00-00" }; + return { date: "2026-11-15T00-00-00" }; + }); + + const list = await downloadsHandler(createEvent()); + + expect(list).toHaveLength(3); + expect(list[0]).toEqual({ + id: "session-2", + date: "2026-11-15T14-00-00", + path: item2Dir, + title: "run-b", + fileName: "run-b.zip", + }); + expect(list[1]).toEqual({ + id: "session-1", + date: "2026-11-15T12-00-00", + path: item1Dir, + title: "Run A", + fileName: "run-a.zip", + }); + expect(list[2]).toEqual({ + id: "session-3", + date: "2026-11-15T10-00-00", + path: item3Dir, + title: "", + fileName: "", + }); + }); + }); +}); diff --git a/electron-app/src/cloudLogs/__tests__/storage.test.js b/electron-app/src/cloudLogs/__tests__/storage.test.js new file mode 100644 index 000000000..1e74c1a17 --- /dev/null +++ b/electron-app/src/cloudLogs/__tests__/storage.test.js @@ -0,0 +1,364 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + mkdtemp, + mkdir, + readFile, + writeFile, + rm, + symlink, +} from "node:fs/promises"; +import { createWriteStream } from "node:fs"; +import { pipeline } from "node:stream/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import archiver from "archiver"; + +const env = vi.hoisted(() => ({ root: "", secure: true, locked: false })); +vi.mock("electron", () => ({ + app: { getPath: () => env.root }, + safeStorage: { + isEncryptionAvailable: () => env.secure, + getSelectedStorageBackend: () => + env.secure ? "gnome_libsecret" : "basic_text", + encryptString: (value) => Buffer.from(`encrypted:${value}`), + decryptString: (value) => { + if (env.locked) throw new Error("locked"); + return value.toString().slice(10); + }, + }, +})); +vi.mock("../../utils/paths.js", () => ({ + getBackendWorkingDir: () => env.root, +})); +vi.mock("../../config/configInstance.js", () => ({ + readConfig: async () => ({ logging: { logging_path: "." } }), +})); + +import { compressSession, extractSession } from "../archive.js"; +import { + findLocalSessions, + formatDownloadedFolderName, + formatSessionZipName, + getCloudRoot, + inspectSession, +} from "../sessions.js"; +import { + clearCredentials, + getCredentials, + getCredentialsStatus, + setCredentials, +} from "../credentials.js"; + +let session; +const settings = { + date: "2026-11-15T12-30-00", + time_unit: "us", + adj_commit_hash: "abc123", +}; +beforeEach(async () => { + env.root = await mkdtemp(path.join(tmpdir(), "cloud-logs-test-")); + env.secure = true; + env.locked = false; + session = path.join(env.root, "logger", "2026-11-15T12-00-00", settings.date); + await mkdir(path.join(session, "data", "BCU"), { recursive: true }); + await mkdir(path.join(session, "protections")); + await writeFile( + path.join(session, "logger_settings.json"), + JSON.stringify(settings), + ); + await writeFile( + path.join(session, "data", "BCU", "speed.csv"), + "0,BCU,backend,4\n1000,BCU,backend,5\n", + ); + await writeFile( + path.join(session, "protections", "BCU.csv"), + "0,BCU,backend,FAULT\n", + ); +}); +afterEach(async () => { + await clearCredentials(); + await rm(env.root, { recursive: true, force: true }); +}); + +async function zipEntries(entries, name = "input.zip") { + const dest = path.join(env.root, name); + const archive = archiver("zip"); + const output = pipeline(archive, createWriteStream(dest)); + for (const [file, content] of entries) + archive.append(content, { name: file }); + await Promise.all([archive.finalize(), output]); + return dest; +} + +describe("session archives", () => { + it("round-trips every session file, including unfamiliar subfolders", async () => { + await writeFile(path.join(session, "config.toml"), 'api_key="private"'); + await mkdir(path.join(session, "other", "metadata"), { recursive: true }); + await writeFile( + path.join(session, "other", "metadata", "notes.txt"), + "reserved logger data", + ); + const zip = path.join(env.root, "session.zip"); + const progress = vi.fn(); + const original = await compressSession(session, zip, progress); + const extracted = path.join(env.root, "extracted"); + const result = await extractSession(zip, extracted, vi.fn()); + expect(result.date).toBe(settings.date); + expect(result.fileCount).toBe(5); + expect(result.bytes).toBe(original.bytes); + expect(progress).toHaveBeenCalledWith(5, 5); + expect( + await readFile(path.join(extracted, "data/BCU/speed.csv"), "utf8"), + ).toContain("1000,BCU,backend,5"); + expect( + await readFile(path.join(extracted, "other/metadata/notes.txt"), "utf8"), + ).toBe("reserved logger data"); + expect( + await readFile(path.join(extracted, "config.toml"), "utf8"), + ).toContain("private"); + }); + it("discovers recordings underneath launches, excluding cloud downloads", async () => { + const cloud = await getCloudRoot(); + await mkdir(path.join(cloud, "cached")); + const sessions = await findLocalSessions(); + expect(sessions).toHaveLength(1); + expect(sessions[0].date).toBe(settings.date); + await expect(inspectSession(path.dirname(session))).rejects.toThrow( + "Select a recording", + ); + }); + it("refuses symbolic links in a local recording", async () => { + await symlink( + path.join(session, "logger_settings.json"), + path.join(session, "data", "link"), + ); + await expect(inspectSession(session)).rejects.toThrow("symbolic links"); + }); + it("refuses a recording that changes while compressing", async () => { + let changed = false; + const { appendFileSync } = await import("node:fs"); + await expect( + compressSession(session, path.join(env.root, "changing.zip"), () => { + if (!changed) { + changed = true; + appendFileSync( + path.join(session, "data/BCU/speed.csv"), + "2000,BCU,backend,6\n", + ); + } + }), + ).rejects.toThrow("changed during compression"); + }); + it("rejects zip traversal without creating files outside the target", async () => { + const zip = await zipEntries([["aa/escape.csv", "bad"]]); + const bytes = await readFile(zip); + const from = Buffer.from("aa/escape.csv"); + let index = bytes.indexOf(from); + while (index !== -1) { + bytes.set(Buffer.from("../escape.csv"), index); + index = bytes.indexOf(from, index + from.length); + } + await writeFile(zip, bytes); + await expect( + extractSession(zip, path.join(env.root, "out"), vi.fn()), + ).rejects.toThrow(); + await expect(readFile(path.join(env.root, "escape.csv"))).rejects.toThrow(); + }); + it("rejects duplicate entries instead of overwriting", async () => { + const zip = await zipEntries([ + ["logger_settings.json", "{}"], + ["logger_settings.json", "{}"], + ]); + await expect( + extractSession(zip, path.join(env.root, "out"), vi.fn()), + ).rejects.toThrow(); + }); + it("normalizes single-digit month and day when inspecting a session", async () => { + const singleDigitDir = path.join( + env.root, + "logger", + "2026-02-12T17-00-00", + "2026-2-12T17-01-46", + ); + await mkdir(singleDigitDir, { recursive: true }); + await writeFile( + path.join(singleDigitDir, "logger_settings.json"), + JSON.stringify({ date: "2026-2-12T17-01-46", time_unit: "us" }), + ); + const inspected = await inspectSession(singleDigitDir); + expect(inspected.date).toBe("2026-02-12T17-01-46"); + }); +}); + +describe("formatSessionZipName", () => { + it("formats standard recording dates", () => { + expect(formatSessionZipName("2026-11-15T12-30-00")).toBe( + "2026-11-15T12-30-00.zip", + ); + }); + + it("pads single-digit months, days, and times with leading zero", () => { + expect(formatSessionZipName("2026-2-12T17-01-46")).toBe( + "2026-02-12T17-01-46.zip", + ); + expect(formatSessionZipName("2026-2-5T9-8-7")).toBe( + "2026-02-05T09-08-07.zip", + ); + }); + + it("handles colons in timestamps and replaces colons/illegal chars in safe strings", () => { + expect(formatSessionZipName("2026-11-15T12:30:00")).toBe( + "2026-11-15T12-30-00.zip", + ); + expect(formatSessionZipName("session:custom:name")).toBe( + "session-custom-name.zip", + ); + expect(formatSessionZipName("session/path:name.zip")).toBe( + "session-path-name.zip", + ); + }); + + it("falls back to current UTC timestamp when dateStr is null or undefined", () => { + const nullResult = formatSessionZipName(null); + expect(nullResult).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}\.zip$/); + expect(nullResult).not.toBe("session.zip"); + const undefinedResult = formatSessionZipName(undefined); + expect(undefinedResult).toMatch( + /^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}\.zip$/, + ); + expect(undefinedResult).not.toBe("session.zip"); + const emptyResult = formatSessionZipName(""); + expect(emptyResult).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}\.zip$/); + expect(emptyResult).not.toBe("session.zip"); + }); + + it("names the archive after title when non-empty title is provided", () => { + expect(formatSessionZipName("2026-11-15T12-30-00", "High Speed Test")).toBe( + "High Speed Test.zip", + ); + expect( + formatSessionZipName("2026-11-15T12-30-00", "High Speed Test.zip"), + ).toBe("High Speed Test.zip"); + expect( + formatSessionZipName("2026-11-15T12-30-00", " Trimmed Title "), + ).toBe("Trimmed Title.zip"); + }); + + it("cleans illegal characters in title by replacing them with underscores", () => { + expect( + formatSessionZipName( + "2026-11-15T12-30-00", + 'Run/1:Test*2?3<4>5|6\\7"8.zip', + ), + ).toBe("Run_1_Test_2_3_4_5_6_7_8.zip"); + }); + + it("falls back to standard date formatting when title is omitted or empty", () => { + expect(formatSessionZipName("2026-11-15T12-30-00", "")).toBe( + "2026-11-15T12-30-00.zip", + ); + expect(formatSessionZipName("2026-11-15T12-30-00", " ")).toBe( + "2026-11-15T12-30-00.zip", + ); + expect(formatSessionZipName("2026-11-15T12-30-00", null)).toBe( + "2026-11-15T12-30-00.zip", + ); + expect(formatSessionZipName("2026-11-15T12-30-00", undefined)).toBe( + "2026-11-15T12-30-00.zip", + ); + const emptyBoth = formatSessionZipName(null, ""); + expect(emptyBoth).not.toBe("session.zip"); + expect(emptyBoth).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}\.zip$/); + }); +}); + +describe("formatDownloadedFolderName", () => { + it("formats folder name using fileName with hh-mm-ss", () => { + expect( + formatDownloadedFolderName("2026-11-15T12-30-00", { + fileName: "custom-run-1.zip", + title: "Test Run Title", + id: "session-1", + }), + ).toBe("custom-run-1-12-30-00"); + }); + + it("strips .zip from fileName and sanitizes illegal characters", () => { + expect( + formatDownloadedFolderName("2026-11-15T12-30-00", { + fileName: "../../nested/bad:file*name?.zip", + }), + ).toBe("bad_file_name_-12-30-00"); + }); + + it("falls back to title when fileName is omitted or empty", () => { + expect( + formatDownloadedFolderName("2026-11-15T12-30-00", { + title: "High Speed Test", + }), + ).toBe("High_Speed_Test-12-30-00"); + + expect( + formatDownloadedFolderName("2026-11-15T12-30-00", { + fileName: " ", + title: "Run/1:Test", + }), + ).toBe("Run_1_Test-12-30-00"); + }); + + it("falls back to id when both fileName and title are omitted", () => { + expect( + formatDownloadedFolderName("2026-11-15T12-30-00", { + id: "session-4", + }), + ).toBe("session-4-12-30-00"); + }); + + it("falls back to 'session' when no identifiers are provided", () => { + expect(formatDownloadedFolderName("2026-11-15T12-30-00")).toBe( + "session-12-30-00", + ); + }); + + it("falls back to current time when dateStr is missing or invalid", () => { + const result = formatDownloadedFolderName(null, { fileName: "run-1" }); + expect(result).toMatch(/^run-1-\d{2}-\d{2}-\d{2}$/); + }); +}); + +describe("credentials", () => { + it("returns only credential status to the UI and preserves a blank replacement", async () => { + expect(await setCredentials({ user: "alice", apiKey: "secret" })).toEqual({ + user: "alice", + hasApiKey: true, + persistent: true, + }); + expect( + await readFile(path.join(env.root, "cloud-logs.json"), "utf8"), + ).not.toContain("secret"); + await setCredentials({ user: "bob", apiKey: "" }); + expect(await getCredentials()).toEqual({ user: "bob", apiKey: "secret" }); + await clearCredentials(); + expect((await getCredentialsStatus()).hasApiKey).toBe(false); + }); + it("keeps the key only in memory when secure storage is unavailable", async () => { + env.secure = false; + expect( + (await setCredentials({ user: "alice", apiKey: "memory-only" })) + .persistent, + ).toBe(false); + expect(await readFile(path.join(env.root, "cloud-logs.json"), "utf8")).toBe( + '{"user":"alice"}', + ); + expect((await getCredentials()).apiKey).toBe("memory-only"); + }); + it("allows replacing an old key that cannot be decrypted", async () => { + await setCredentials({ user: "alice", apiKey: "old" }); + env.locked = true; + await expect( + setCredentials({ user: "alice", apiKey: "new" }), + ).resolves.toMatchObject({ hasApiKey: true }); + env.locked = false; + expect((await getCredentials()).apiKey).toBe("new"); + }); +}); diff --git a/electron-app/src/cloudLogs/archive.js b/electron-app/src/cloudLogs/archive.js new file mode 100644 index 000000000..aafa276be --- /dev/null +++ b/electron-app/src/cloudLogs/archive.js @@ -0,0 +1,186 @@ +/** + * @module cloudLogs + * @description Archive compression and safe extraction utilities for recording sessions. + * Handles ZIP archive creation and extraction with protection against zip slips, zip bombs, and traversal attacks. + */ + +import archiver from "archiver"; +import yauzl from "yauzl"; +import { createWriteStream } from "node:fs"; +import { mkdir } from "node:fs/promises"; +import { pipeline } from "node:stream/promises"; +import { Transform } from "node:stream"; +import path from "node:path"; +import { + inspectSession, + isSessionFile, + MAX_BYTES, + MAX_FILES, +} from "./sessions.js"; + +/** + * Compresses a completed recording session folder into a ZIP archive. + * @param {string} dir - Directory path of the recording session to compress. + * @param {string} destination - Destination file path for the ZIP archive. + * @param {function(number, number): void} onProgress - Callback invoked with processed entry count and total file count. + * @returns {Promise} Session metadata of the compressed archive. + * @throws {Error} If destination file already exists, compression fails, or files change during compression. + */ +export async function compressSession(dir, destination, onProgress) { + const before = await inspectSession(dir); + const archive = archiver("zip", { zlib: { level: 6 } }); + archive.on("progress", ({ entries }) => + onProgress(entries.processed, before.fileCount), + ); + archive.on("warning", (error) => archive.destroy(error)); + + // Flag 'wx' ensures failure if the destination already exists + const output = pipeline( + archive, + createWriteStream(destination, { flags: "wx" }), + ); + + for (const file of before.files) + archive.file(path.join(dir, file.name), { name: file.name }); + + try { + await Promise.all([archive.finalize(), output]); + } catch (error) { + archive.abort(); + throw error; + } + + // Verify files did not change while compressing (e.g. logger was still running) + const after = await inspectSession(dir); + if (JSON.stringify(before.files) !== JSON.stringify(after.files)) { + throw new Error( + "The recording changed during compression. Stop logging before uploading.", + ); + } + return before; +} + +/** + * Extracts session files into a private directory, rejecting traversal, symlinks, and zip bombs. + * @param {string} archivePath - Path to the ZIP archive file. + * @param {string} destination - Destination directory path for extracted files. + * @param {function(number, number): void} onProgress - Callback invoked with processed entry count and total entry count. + * @returns {Promise} Inspected session metadata of the extracted files. + * @throws {Error} If archive contains unsafe entries, exceeds limits, or extraction fails. + */ +export async function extractSession(archivePath, destination, onProgress) { + await mkdir(destination, { recursive: true }); + await new Promise((resolve, reject) => { + yauzl.open( + archivePath, + { lazyEntries: true, autoClose: true }, + (error, zip) => { + if (error) return reject(error); + let entries = 0; + let bytes = 0; + let declaredBytes = 0; + const seen = new Set(); + const fail = (err) => { + zip.close(); + reject(err); + }; + zip.on("error", fail); + zip.on("end", resolve); + zip.on("entry", (entry) => { + void (async () => { + // Normalize path separators to POSIX slashes for consistent validation + const name = entry.fileName.replace(/\\/g, "/"); + + // Extract host OS and POSIX mode from entry attributes + const madeBy = entry.versionMadeBy >> 8; + const mode = + madeBy === 3 + ? (entry.externalFileAttributes >>> 16) & 0o170000 + : 0; + + // Reject zip bombs, absolute paths, traversal, symlinks, and encryption + if ( + ++entries > MAX_FILES || + name.startsWith("/") || + name.includes(":") || + name.split("/").some((p) => p === ".." || p === ".") || + (mode != 0 && mode !== 0o100000 && mode !== 0o040000) || + entry.generalPurposeBitFlag & 1 + ) { + throw new Error( + "Archive contains an unsafe or unsupported entry.", + ); + } + + // Skip directory entries since directories are created on demand + if (name.endsWith("/")) { + zip.readEntry(); + return; + } + + if (!isSessionFile(name)) + throw new Error( + "Archive contains files outside a logging session.", + ); + + // Validate total declared uncompressed size from headers + declaredBytes += entry.uncompressedSize; + if (declaredBytes > MAX_BYTES) + throw new Error("Extracted session exceeds 4 GiB."); + + const target = path.resolve(destination, name); + + // Lowercase paths on Windows to prevent case-collision attacks + const key = + process.platform === "win32" ? target.toLowerCase() : target; + if (seen.has(key)) + throw new Error("Archive contains duplicate file entries."); + seen.add(key); + + // Ensure the target path is strictly contained within destination + if (!target.startsWith(path.resolve(destination) + path.sep)) + throw new Error("Unsafe archive path."); + + await mkdir(path.dirname(target), { recursive: true }); + + const input = await new Promise((res, rej) => + zip.openReadStream(entry, (err, stream) => + err ? rej(err) : res(stream), + ), + ); + + // Track decompressed bytes in real-time to guard against forged headers + const limit = new Transform({ + transform(chunk, _encoding, done) { + bytes += chunk.length; + done( + bytes > MAX_BYTES + ? new Error("Extracted session exceeds 4 GiB.") + : null, + chunk, + ); + }, + }); + + // Prevent overwriting existing files and symlink race conditions + const output = createWriteStream(target, { flags: "wx" }); + + input.once("error", fail); + limit.once("error", fail); + output.once("error", fail); + + await pipeline(input, limit, output); + + onProgress(entries, zip.entryCount); + + zip.readEntry(); + })().catch(fail); + }); + + zip.readEntry(); + }, + ); + }); + + return inspectSession(destination); +} diff --git a/electron-app/src/cloudLogs/client.js b/electron-app/src/cloudLogs/client.js new file mode 100644 index 000000000..8120d4548 --- /dev/null +++ b/electron-app/src/cloudLogs/client.js @@ -0,0 +1,713 @@ +/** + * @module cloudLogs + * @description HTTP client and network transfer operations for the Cloud Logs service. + * Handles authentication, listing, tag autocomplete, and upload/download streams. + */ + +import { createReadStream, createWriteStream, openAsBlob } from "node:fs"; +import { stat, unlink } from "node:fs/promises"; +import path from "node:path"; +import { Readable, Transform } from "node:stream"; +import { pipeline } from "node:stream/promises"; +import { readConfig } from "../config/configInstance.js"; + +const DEFAULT_BASE_URL = "https://cloud-logs.hyperloopupv.com/api/v1"; +const DEFAULT_MAX_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB +const TAG_CACHE_TTL_MS = 60 * 1000; // 60 seconds + +let tagCache = { + timestamp: 0, + tags: [], + key: "", +}; + +/** + * Clears the in-memory cache for tag suggestions. + */ +export function clearTagCache() { + tagCache = { + timestamp: 0, + tags: [], + key: "", + }; +} + +/** + * Merges an optional caller AbortSignal with a timeout signal (default 15,000 ms). + * @param {AbortSignal} [callerSignal] - Optional caller-provided signal. + * @param {number} [timeoutMs=15000] - Timeout duration in milliseconds. + * @returns {AbortSignal} Merged abort signal that aborts when either the timeout fires or the caller aborts. + */ +function createTimeoutSignal(callerSignal, timeoutMs = 15000) { + const timeoutSignal = AbortSignal.timeout(timeoutMs); + if (!callerSignal) return timeoutSignal; + if (typeof AbortSignal.any === "function") { + return AbortSignal.any([callerSignal, timeoutSignal]); + } + const controller = new AbortController(); + const onAbort = () => + controller.abort(callerSignal.reason || timeoutSignal.reason); + if (callerSignal.aborted || timeoutSignal.aborted) { + controller.abort( + callerSignal.aborted ? callerSignal.reason : timeoutSignal.reason, + ); + return controller.signal; + } + callerSignal.addEventListener("abort", onAbort, { once: true }); + timeoutSignal.addEventListener("abort", onAbort, { once: true }); + return controller.signal; +} + +/** + * Normalizes the Cloud Logs API base URL (HTTP/HTTPS only, no trailing or duplicate path slashes). + * @param {string} [raw] - The raw URL string to normalize. + * @returns {string} The normalized base URL. + * @throws {Error} If the URL is invalid or uses an unsupported protocol. + */ +export function normalizeApiUrl(raw) { + if ( + raw === null || + raw === undefined || + (typeof raw === "string" && raw.trim() === "") + ) { + return DEFAULT_BASE_URL; + } + if (typeof raw !== "string") { + throw new Error( + `Invalid Cloud Logs API URL: Expected string but received ${typeof raw}`, + ); + } + const trimmed = raw.trim(); + let parsed; + try { + parsed = new URL(trimmed); + } catch { + throw new Error( + `Invalid Cloud Logs API URL: "${trimmed}". Must be a valid absolute HTTP or HTTPS URL.`, + ); + } + if (parsed.protocol !== "http:" && parsed.protocol !== "https:") { + throw new Error( + `Invalid Cloud Logs API URL protocol: "${parsed.protocol}". Only http: and https: are allowed.`, + ); + } + const cleanPathname = parsed.pathname + .replace(/\/+/g, "/") + .replace(/\/+$/, ""); + return `${parsed.origin}${cleanPathname}`; +} + +/** + * Resolves the Cloud Logs API base URL from environment, configuration, or default fallback. + * Precedence: env var CLOUD_LOGS_API_URL > config file > DEFAULT_BASE_URL. + * @returns {Promise} The resolved and normalized API base URL. + */ +export async function getBaseUrl() { + let raw = process.env.CLOUD_LOGS_API_URL; + if (!raw) { + try { + const config = await readConfig(); + raw = config?.cloud_logs?.api_url; + } catch { + // Ignore readConfig failures (e.g. missing files or test environments) + } + } + return normalizeApiUrl(raw); +} + +/** + * Converts filesystem-safe date strings (e.g. YYYY-MM-DDTHH-mm-ss) to ISO 8601 UTC. + * @param {string} [dateStr] - The raw date string to convert. + * @returns {string | undefined} The formatted ISO 8601 string, or undefined if input is invalid. + */ +export function convertDateToIso(dateStr) { + if (!dateStr || typeof dateStr !== "string") return undefined; + const match = dateStr.match( + /^(\d{4})-(\d{1,2})-(\d{1,2})[T_ ](\d{1,2})[-:](\d{1,2})[-:](\d{1,2})(?:\.\d+)?/, + ); + if (match) { + const [, y, m, d, h, min, s] = match; + const pad = (v) => String(v).padStart(2, "0"); + return `${y}-${pad(m)}-${pad(d)}T${pad(h)}:${pad(min)}:${pad(s)}Z`; + } + // Assume UTC if timezone is omitted + if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z?$/.test(dateStr)) { + return dateStr.endsWith("Z") ? dateStr : `${dateStr}Z`; + } + return dateStr; +} + +/** + * Constructs authentication headers (Bearer token, X-API-Key, and optional X-User). + * @param {Object} [credentials] - Credentials object. + * @param {string} [credentials.apiKey] - The API key / bearer token. + * @param {string} [credentials.user] - Optional username. + * @returns {Record} Headers object for HTTP requests. + */ +export function getAuthHeaders(credentials) { + const headers = {}; + if (credentials?.apiKey) { + headers["Authorization"] = `Bearer ${credentials.apiKey}`; + headers["X-API-Key"] = credentials.apiKey; + } + if (credentials?.user) { + headers["X-User"] = credentials.user; + } + return headers; +} + +/** + * Redacts secrets (API keys, Bearer tokens, query parameters) from a string + * to prevent leaking credentials in UI messages or logs. + * @param {string} text - The input string to sanitize. + * @param {string} [apiKey] - The active API key to specifically redact. + * @returns {string} The sanitized text with sensitive tokens replaced. + */ +export function sanitizeMessage(text, apiKey) { + if (typeof text !== "string") return String(text); + let result = text; + // Only redact keys >= 4 chars to prevent replacing trivial substrings + if (typeof apiKey === "string" && apiKey.trim().length >= 4) { + result = result.replaceAll(apiKey, "[REDACTED]"); + if (apiKey.trim() !== apiKey) { + result = result.replaceAll(apiKey.trim(), "[REDACTED]"); + } + } + result = result.replace(/Bearer\s+[^\s"'>;&]+/gi, "Bearer [REDACTED]"); + result = result.replace( + /(["']?(?:x-)?api[_-]?key["']?\s*[:=]\s*["']?)[^\s"'>;&,]+/gi, + "$1[REDACTED]", + ); + result = result.replace( + /([?&](?:token|api[_-]?key|key|secret)=)[^&\s"'>]+/gi, + "$1[REDACTED]", + ); + return result; +} + +/** + * Redacts secrets from an Error message and stack trace, preserving error code and HTTP status. + * @param {Error | unknown} err - The error object to sanitize. + * @param {string} [apiKey] - The active API key to redact. + * @returns {Error} A new sanitized Error instance. + */ +export function sanitizeError(err, apiKey) { + if (!err) return new Error("Unknown error"); + const origMessage = err.message || String(err); + const cleanMessage = sanitizeMessage(origMessage, apiKey); + const sanitized = new Error(cleanMessage); + if (err.code) sanitized.code = err.code; + if (err.status) sanitized.status = err.status; + if (err.stack) { + sanitized.stack = sanitizeMessage(err.stack, apiKey); + } + return sanitized; +} + +/** + * Extracts error details from an HTTP error response and throws a sanitized Error. + * @param {Response} response - The Fetch Response object. + * @param {Object} [credentials] - Credentials containing the apiKey to redact. + * @param {string} [credentials.apiKey] - The API key. + * @returns {Promise} + * @throws {Error} Sanitized error with HTTP status and detail message. + */ +export async function handleResponseError(response, credentials) { + let raw = ""; + try { + if (typeof response.text === "function") { + raw = await response.text(); + } else if (typeof response.json === "function") { + const parsed = await response.json(); + raw = typeof parsed === "string" ? parsed : JSON.stringify(parsed); + } + } catch { + // If reading body fails, fall back to statusText + } + + let detail = ""; + if (typeof raw === "string" && raw.trim().length > 0) { + try { + const data = JSON.parse(raw); + if (typeof data?.detail === "string" && data.detail.trim().length > 0) { + detail = data.detail; + } else if (data?.detail != null) { + detail = JSON.stringify(data.detail); + } else if ( + typeof data?.message === "string" && + data.message.trim().length > 0 + ) { + detail = data.message; + } else if ( + typeof data?.error === "string" && + data.error.trim().length > 0 + ) { + detail = data.error; + } else if (data != null && typeof data === "object") { + detail = JSON.stringify(data); + } + } catch { + detail = raw + .replace(/<[^>]*>/g, " ") + .replace(/\s+/g, " ") + .trim() + .slice(0, 300); + } + } + + if (!detail) { + detail = response.statusText || ""; + } + + const err = new Error( + `Request failed with status ${response.status}: ${detail}`, + ); + err.status = response.status; + throw sanitizeError(err, credentials?.apiKey); +} + +/** + * Fetches paginated log records from the Cloud Logs API and normalizes schema fields for the UI. + * @param {Object} [options] - Request options. + * @param {Object} [options.credentials] - User credentials. + * @param {string} [options.credentials.apiKey] - The API key. + * @param {string} [options.credentials.user] - The username. + * @param {string} [options.cursor] - Pagination cursor or page number. + * @returns {Promise<{items: Array, nextCursor?: string}>} Paginated log items and next cursor if available. + * @throws {Error} If the request fails or returns an error status. + */ +export async function listLogs({ credentials, cursor, signal } = {}) { + try { + const baseUrl = await getBaseUrl(); + const page = Math.max(1, parseInt(cursor, 10) || 1); + const pageSize = 50; + const url = `${baseUrl}/logs?page=${page}&pageSize=${pageSize}&sortBy=uploadDate&sortOrder=desc`; + const res = await fetch(url, { + method: "GET", + headers: { + ...getAuthHeaders(credentials), + Accept: "application/json", + }, + signal: createTimeoutSignal(signal), + }); + + if (!res.ok) { + await handleResponseError(res, credentials); + } + + const data = await res.json(); + const rawItems = Array.isArray(data?.items) ? data.items : []; + // Normalize heterogeneous schema fields from different backend service versions + const items = rawItems.map((item) => ({ + id: String(item.id), + user: item.creator || item.user || item.clientMetadata?.clientUser || "", + notes: item.note ?? item.notes ?? item.description ?? "", + tags: Array.isArray(item.tags) ? item.tags : [], + date: + item.logDate || + item.uploadDate || + item.fileDate || + item.date || + item.createdAt || + "", + logDate: item.logDate || item.fileDate || item.date || "", + uploadDate: item.uploadDate || item.createdAt || "", + fileName: item.fileName || item.file_name || "", + title: + item.title || + item.clientMetadata?.title || + (item.fileName + ? item.fileName.replace(/\.zip$/i, "") + : item.file_name + ? item.file_name.replace(/\.zip$/i, "") + : ""), + })); + + const total = + typeof data?.total === "number" ? data.total : rawItems.length; + const result = { items }; + const effectivePageSize = Number(data?.pageSize) || pageSize; + if (page * effectivePageSize < total) { + result.nextCursor = String(page + 1); + } + return result; + } catch (err) { + throw sanitizeError(err, credentials?.apiKey); + } +} + +/** + * Retrieves tag suggestions from the Cloud Logs API, optionally filtered by a search query. + * @param {Object} [options] - Request options. + * @param {Object} [options.credentials] - User credentials. + * @param {string} [options.credentials.apiKey] - The API key. + * @param {string} [options.credentials.user] - The username. + * @param {string} [options.query] - Optional query substring to filter tags. + * @param {AbortSignal} [options.signal] - Optional caller AbortSignal. + * @returns {Promise} List of matching tag names. + * @throws {Error} If the request fails. + */ +export async function autocompleteTags({ credentials, query, signal } = {}) { + try { + const baseUrl = await getBaseUrl(); + const cacheKey = `${baseUrl}:${credentials?.apiKey || ""}`; + const now = Date.now(); + let allTags; + + if ( + tagCache.key === cacheKey && + now - tagCache.timestamp < TAG_CACHE_TTL_MS && + Array.isArray(tagCache.tags) + ) { + allTags = tagCache.tags; + } else { + const url = `${baseUrl}/logs/tags`; + const res = await fetch(url, { + method: "GET", + headers: { + ...getAuthHeaders(credentials), + Accept: "application/json", + }, + signal: createTimeoutSignal(signal), + }); + + if (!res.ok) { + await handleResponseError(res, credentials); + } + + const data = await res.json(); + allTags = Array.isArray(data) ? data : []; + tagCache = { + timestamp: now, + tags: allTags, + key: cacheKey, + }; + } + + let tags = allTags; + if (typeof query === "string" && query.trim()) { + const q = query.trim().toLowerCase(); + tags = tags.filter( + (t) => typeof t === "string" && t.toLowerCase().includes(q), + ); + } + return tags; + } catch (err) { + throw sanitizeError(err, credentials?.apiKey); + } +} + +/** + * Uploads a log archive directly to cloud storage using the initiate -> upload -> complete workflow. + * @param {Object} [options] - Upload options. + * @param {Object} [options.credentials] - User credentials. + * @param {string} [options.credentials.apiKey] - The API key. + * @param {string} [options.credentials.user] - The username. + * @param {string} options.archivePath - Absolute path to the zip archive file. + * @param {Object} [options.metadata] - Optional session metadata. + * @param {string} [options.metadata.fileName] - Name of the archive file. + * @param {string} [options.metadata.title] - Human-readable session title. + * @param {string} [options.metadata.logDate] - Session date string. + * @param {string} [options.metadata.date] - Alternate session date string. + * @param {string} [options.metadata.user] - Owner username. + * @param {string} [options.metadata.notes] - Notes or description. + * @param {string[]} [options.metadata.tags] - Array of tags. + * @returns {Promise} Upload summary containing session ID and metadata. + * @throws {Error} If initiation, upload stream, or completion fails. + */ +export async function uploadLog({ + credentials, + archivePath, + metadata = {}, + signal, +} = {}) { + let sessionId = null; + let baseUrl; + try { + baseUrl = await getBaseUrl(); + const stats = await stat(archivePath); + const fileSize = stats.size; + const fileName = metadata.fileName || path.basename(archivePath); + const logDate = convertDateToIso(metadata.logDate || metadata.date); + const user = metadata.user || credentials?.user; + + const clientMetadata = { + clientUser: user, + }; + if (metadata.title) { + clientMetadata.title = metadata.title; + } + + const note = + typeof metadata.notes === "string" && metadata.notes.trim() + ? metadata.notes.trim() + : null; + + const tags = Array.isArray(metadata.tags) + ? metadata.tags + .filter((t) => typeof t === "string" && t.trim().length > 0) + .map((t) => t.trim()) + : []; + + const initiateBody = { + fileName, + fileSize, + logDate, + tags, + note, + user, + clientMetadata, + }; + + const initiateRes = await fetch(`${baseUrl}/logs/initiate`, { + method: "POST", + headers: { + ...getAuthHeaders(credentials), + "Content-Type": "application/json", + Accept: "application/json", + }, + body: JSON.stringify(initiateBody), + signal: createTimeoutSignal(signal), + }); + + if (!initiateRes.ok) { + await handleResponseError(initiateRes, credentials); + } + + const session = await initiateRes.json(); + sessionId = session?.id; + + if (!session?.uploadUrl) { + throw new Error( + "Cloud Logs upload initiate response did not contain uploadUrl", + ); + } + + let driveFileId; + try { + // Stream binary directly to storage; omit auth headers to avoid credential leakage and signature errors + let body; + if (typeof openAsBlob === "function") { + body = await openAsBlob(archivePath); + } else { + body = Readable.toWeb(createReadStream(archivePath)); + } + + const putRes = await fetch(session.uploadUrl, { + method: "PUT", + headers: { + "Content-Type": "application/zip", + }, + body, + duplex: "half", // Required by Fetch API for streaming request bodies + signal, + }); + + if (!putRes.ok) { + let errDetail = ""; + try { + errDetail = await putRes.text(); + } catch { + errDetail = putRes.statusText; + } + throw new Error( + `Upload to storage URL failed with status ${putRes.status}: ${errDetail}`, + ); + } + + try { + const putData = await putRes.json(); + if (putData?.id) { + driveFileId = putData.id; + } + } catch { + // Storage responses are not guaranteed to be JSON (e.g. empty 200 OK) + } + } catch (putErr) { + await attemptAbort(baseUrl, sessionId, credentials, putErr.message); + throw putErr; + } + + try { + const completeBody = driveFileId ? { driveFileId } : {}; + const completeRes = await fetch( + `${baseUrl}/logs/${encodeURIComponent(sessionId)}/complete`, + { + method: "POST", + headers: { + ...getAuthHeaders(credentials), + "Content-Type": "application/json", + Accept: "application/json", + }, + body: JSON.stringify(completeBody), + signal: createTimeoutSignal(signal), + }, + ); + + if (!completeRes.ok) { + await handleResponseError(completeRes, credentials); + } + } catch (completeErr) { + await attemptAbort(baseUrl, sessionId, credentials, completeErr.message); + throw completeErr; + } + + return { + id: String(session.id), + user: user || metadata.user || "", + notes: metadata.notes, + tags: metadata.tags, + date: metadata.date, + fileName, + title: metadata.title, + }; + } catch (err) { + throw sanitizeError(err, credentials?.apiKey); + } +} + +/** + * Sends a best-effort abort request to the API server; suppresses errors to preserve the root cause. + * @param {string} baseUrl - The API base URL. + * @param {string} sessionId - The upload session identifier. + * @param {Object} credentials - User credentials for authentication. + * @param {string} [reason] - Abort reason description. + * @returns {Promise} + */ +async function attemptAbort(baseUrl, sessionId, credentials, reason) { + if (!sessionId || !baseUrl) return; + try { + await fetch(`${baseUrl}/logs/${encodeURIComponent(sessionId)}/abort`, { + method: "POST", + headers: { + ...getAuthHeaders(credentials), + "Content-Type": "application/json", + }, + body: JSON.stringify({ reason: reason || "Upload failed" }), + signal: createTimeoutSignal(undefined, 5000), + }); + } catch { + // Suppress abort failures to preserve the primary error + } +} + +/** + * Downloads a log archive, streaming directly to disk while handling redirects and size limits. + * @param {Object} [options] - Download options. + * @param {Object} [options.credentials] - User credentials. + * @param {string} [options.credentials.apiKey] - The API key. + * @param {string} [options.credentials.user] - The username. + * @param {string} options.id - The Cloud Log ID to download. + * @param {string} options.destination - Absolute destination file path for the archive. + * @param {number} [options.maxBytes] - Maximum allowed byte size (defaults to 4 GiB). + * @param {AbortSignal} [options.signal] - Optional caller AbortSignal. + * @returns {Promise} + * @throws {Error} If the download fails, redirect is invalid, or size limit is exceeded. + */ +export async function downloadLog({ + credentials, + id, + destination, + maxBytes, + signal, +} = {}) { + const limit = typeof maxBytes === "number" ? maxBytes : DEFAULT_MAX_BYTES; + const abortController = new AbortController(); + + if (signal) { + if (signal.aborted) { + abortController.abort(signal.reason); + } else { + signal.addEventListener( + "abort", + () => abortController.abort(signal.reason), + { once: true }, + ); + } + } + + try { + const baseUrl = await getBaseUrl(); + const downloadEndpoint = `${baseUrl}/logs/${encodeURIComponent(id)}/download`; + + const initialRes = await fetch(downloadEndpoint, { + method: "GET", + headers: getAuthHeaders(credentials), + redirect: "manual", + signal: abortController.signal, + }); + + let downloadRes; + const status = initialRes.status; + + // Strip auth headers before redirect to external storage to prevent token leakage + if ([301, 302, 303, 307, 308].includes(status)) { + const location = initialRes.headers.get("location"); + if (!location) { + throw new Error( + `Redirect response (${status}) missing Location header`, + ); + } + const targetUrl = new URL(location, downloadEndpoint).href; + downloadRes = await fetch(targetUrl, { + method: "GET", + signal: abortController.signal, + }); + + if (!downloadRes.ok) { + await handleResponseError(downloadRes, credentials); + } + } else if (status === 200) { + downloadRes = initialRes; + } else { + await handleResponseError(initialRes, credentials); + } + + if (!downloadRes.body) { + throw new Error("Download response body is empty"); + } + + let totalBytes = 0; + const limitTransform = new Transform({ + transform(chunk, _encoding, callback) { + const chunkLength = chunk.byteLength ?? chunk.length ?? 0; + totalBytes += chunkLength; + if (totalBytes > limit) { + try { + abortController.abort(); + } catch { + // Ignore abort error + } + callback( + new Error( + `Download exceeded maximum allowed size of ${limit} bytes`, + ), + ); + return; + } + callback(null, chunk); + }, + }); + + const readable = + typeof downloadRes.body.pipe === "function" + ? downloadRes.body + : Readable.fromWeb(downloadRes.body); + + const fileStream = createWriteStream(destination); + + await pipeline(readable, limitTransform, fileStream); + } catch (err) { + try { + abortController.abort(); + } catch { + // Ignore abort errors + } + try { + await unlink(destination); + } catch { + // Best-effort cleanup + } + throw sanitizeError(err, credentials?.apiKey); + } +} diff --git a/electron-app/src/cloudLogs/credentials.js b/electron-app/src/cloudLogs/credentials.js new file mode 100644 index 000000000..a5deb6358 --- /dev/null +++ b/electron-app/src/cloudLogs/credentials.js @@ -0,0 +1,137 @@ +/** + * @module cloudLogs + * @description Cloud Logs credential storage and encryption management. + * Handles reading, writing, and safe storage of user credentials and API keys. + */ + +import { app, safeStorage } from "electron"; +import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; +import path from "node:path"; + +// In-memory fallback when OS-level persistent encryption is unavailable +let memoryKey = ""; + +/** + * Checks whether OS-level persistent encryption is available and secure. + * Avoids persisting to disk on Linux if safeStorage uses an unencrypted backend. + * @returns {boolean} True if encryption can be persisted securely to disk. + */ +function canPersist() { + return ( + safeStorage.isEncryptionAvailable() && + (process.platform !== "linux" || + !["basic_text", "unknown"].includes( + safeStorage.getSelectedStorageBackend(), + )) + ); +} + +/** + * Resolves the path to the credentials configuration file. + * @returns {string} Absolute path to cloud-logs.json in userData. + */ +const configPath = () => path.join(app.getPath("userData"), "cloud-logs.json"); + +/** + * Reads stored settings from the configuration file. + * @returns {Promise} Stored settings object or empty object if file does not exist. + * @throws {Error} If reading or parsing fails for reasons other than missing file. + */ +async function readSettings() { + try { + return JSON.parse(await readFile(configPath(), "utf8")); + } catch (error) { + if (error.code === "ENOENT") return {}; + throw new Error("Could not read Cloud Logs credentials."); + } +} + +/** + * Atomically writes settings with owner-only (0o600) permissions. + * @param {Object} value - Settings object to write. + * @returns {Promise} + */ +async function writeSettings(value) { + await mkdir(path.dirname(configPath()), { recursive: true }); + const temporary = `${configPath()}.tmp`; + await writeFile(temporary, JSON.stringify(value), { mode: 0o600 }); + await rename(temporary, configPath()); +} + +/** + * Retrieves the active user and decrypted API key from memory or OS keychain. + * @returns {Promise<{ user: string, apiKey: string }>} Active credentials object. + * @throws {Error} If the saved API key cannot be decrypted. + */ +export async function getCredentials() { + const stored = await readSettings(); + let apiKey = memoryKey; + if (!apiKey && stored.encryptedKey && canPersist()) { + try { + apiKey = safeStorage.decryptString( + Buffer.from(stored.encryptedKey, "base64"), + ); + } catch { + throw new Error( + "The saved API key cannot be unlocked. Replace it in Credentials.", + ); + } + } + return { user: stored.user || "", apiKey }; +} + +/** + * Returns credential status for UI badges without exposing the raw API key. + * @returns {Promise<{ user: string, hasApiKey: boolean, persistent: boolean }>} Credential status. + */ +export async function getCredentialsStatus() { + const stored = await readSettings(); + return { + user: stored.user || "", + hasApiKey: !!(memoryKey || (stored.encryptedKey && canPersist())), + persistent: canPersist(), + }; +} + +/** + * Updates stored credentials with optional API key encryption. + * Omitting apiKey preserves the existing key. + * @param {Object} credentials - Credential parameters. + * @param {string} credentials.user - Username. + * @param {string} [credentials.apiKey] - Optional API key. + * @returns {Promise<{ user: string, hasApiKey: boolean, persistent: boolean }>} Updated credential status. + * @throws {Error} If user or apiKey validation fails. + */ +export async function setCredentials({ user, apiKey }) { + if ( + typeof user !== "string" || + !user.trim() || + user.length > 200 || + (apiKey !== undefined && + (typeof apiKey !== "string" || apiKey.length > 8192)) + ) { + throw new Error("Enter a valid user and API key."); + } + // Blank API key preserves existing key or recovers previous key + const key = apiKey?.trim() || (await getCredentials()).apiKey; + if (!key) throw new Error("Enter an API key."); + const persistent = canPersist(); + await writeSettings({ + user: user.trim(), + encryptedKey: persistent + ? safeStorage.encryptString(key).toString("base64") + : undefined, + }); + memoryKey = persistent ? "" : key; + return getCredentialsStatus(); +} + +/** + * Clears stored credentials and resets in-memory API key. + * @returns {Promise<{ user: string, hasApiKey: boolean, persistent: boolean }>} Cleared credential status. + */ +export async function clearCredentials() { + await writeSettings({}); + memoryKey = ""; + return getCredentialsStatus(); +} diff --git a/electron-app/src/cloudLogs/handlers.js b/electron-app/src/cloudLogs/handlers.js new file mode 100644 index 000000000..27e776a9e --- /dev/null +++ b/electron-app/src/cloudLogs/handlers.js @@ -0,0 +1,548 @@ +/** + * @module cloudLogs + * @description IPC handlers for Cloud Logs operations between the main process and renderer. + * Registers handlers for: + * - Credential management + * - Session discovery and selection + * - Cloud log listing and tag autocomplete + * - Archive compression, upload, download, and extraction + */ + +import { BrowserWindow, dialog, ipcMain } from "electron"; +import { randomUUID } from "node:crypto"; +import { + mkdtemp, + readdir, + readFile, + writeFile, + rename, + rm, + stat, +} from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { getAppPath } from "../utils/paths.js"; +import * as credentials from "./credentials.js"; +import * as client from "./client.js"; +import { compressSession, extractSession } from "./archive.js"; +import { + findLocalSessions, + formatDownloadedFolderName, + formatSessionZipName, + getCloudRoot, + getLogsRoot, + inspectSession, + MAX_BYTES, +} from "./sessions.js"; + +/** + * Restricts IPC access to top-level main frames of authorized local views. + * @param {import("electron").IpcMainInvokeEvent} event - The IPC event object. + * @throws {Error} If the sender frame is not an authorized local view main frame. + * @returns {void} + */ +export function assertSender(event) { + if ( + !event?.sender || + !event?.senderFrame || + event.senderFrame !== event.sender.mainFrame + ) { + throw new Error( + "Cloud Logs is only available to local Logging and Testing views.", + ); + } + const rawUrl = event.senderFrame?.url?.split(/[?#]/)[0]; + if (!rawUrl) { + throw new Error( + "Cloud Logs is only available to local Logging and Testing views.", + ); + } + try { + const pathModule = process.platform === "win32" ? path.win32 : path; + let filePath; + try { + filePath = rawUrl.startsWith("file:") + ? fileURLToPath(rawUrl, { windows: process.platform === "win32" }) + : pathModule.resolve(rawUrl); + } catch { + filePath = pathModule.resolve(rawUrl); + } + const resolvedPath = pathModule.resolve(filePath); + const allowedPaths = ["logging-view", "testing-view"].map((view) => + pathModule.resolve(getAppPath(), "renderer", view, "index.html"), + ); + const isAllowed = allowedPaths.some((target) => + process.platform === "win32" + ? target.toLowerCase() === resolvedPath.toLowerCase() + : target === resolvedPath, + ); + if (!isAllowed) { + throw new Error( + "Cloud Logs is only available to local Logging and Testing views.", + ); + } + } catch (error) { + if ( + error.message === + "Cloud Logs is only available to local Logging and Testing views." + ) { + throw error; + } + throw new Error( + "Cloud Logs is only available to local Logging and Testing views.", + ); + } +} + +/** + * Validates a non-empty string and enforces a maximum character limit. + * @param {unknown} value - Value to validate. + * @param {number} [max=500] - Maximum allowed character length. + * @returns {string} The validated string. + * @throws {Error} If the value is not a string, is empty, or exceeds the limit. + */ +function text(value, max = 500) { + if (typeof value !== "string" || !value.trim() || value.length > max) + throw new Error("Invalid Cloud Logs request."); + return value; +} + +/** + * Sanitizes client errors to prevent credential or URL leakage in UI alerts. + * @param {Error | unknown} error - The error to sanitize. + * @returns {Error} A sanitized Error object safe for display in the UI. + */ +function cleanClientError(error) { + if (!error) return new Error("Cloud Logs operation failed."); + const raw = + error instanceof Error + ? error.message + : typeof error === "string" + ? error + : String(error); + const sanitized = client.sanitizeMessage(raw).trim(); + return new Error(sanitized || "Cloud Logs operation failed."); +} + +/** + * Finds an already-downloaded valid session by cloud log ID. + * @param {string} root - The cloud logs root directory path. + * @param {string} id - The cloud log ID to search for. + * @returns {Promise<{dir: string, info: Object, session: Object} | null>} Existing download info, or null if not found. + */ +async function findExistingDownload(root, id) { + try { + for (const entry of await readdir(root, { withFileTypes: true })) { + if (!entry.isDirectory() || entry.name.startsWith(".")) continue; + const dir = path.join(root, entry.name); + try { + const info = JSON.parse( + await readFile(path.join(dir, "cloud-log.json"), "utf8"), + ); + if (info.id === id) { + const session = await inspectSession(dir); + return { dir, info, session }; + } + } catch (err) { + // If the directory was specifically for this ID but is corrupt, clean it up + if (err.code !== "ENOENT") { + try { + const raw = await readFile( + path.join(dir, "cloud-log.json"), + "utf8", + ); + const escapedId = id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const idPattern = new RegExp(`"id"\\s*:\\s*"${escapedId}"`); + if (idPattern.test(raw)) { + await rm(dir, { recursive: true, force: true }); + } + } catch { + /* ignore */ + } + } + } + } + } catch { + /* root may not exist yet */ + } + return null; +} + +/** + * Registers all IPC handlers for Cloud Logs management, listing, uploads, and downloads. + * Should be called once during main process IPC initialization. + * @returns {void} + */ +export function setupCloudLogsHandlers() { + const selected = new Map(); + let transferRunning = false; + let credentialsQueue = Promise.resolve(); + + /** + * Helper to register an IPC handler with sender verification. + * @param {string} name - Handler channel name suffix (prefixed with "cloud-logs:"). + * @param {function(import("electron").IpcMainInvokeEvent, any): Promise | any} fn - The handler implementation. + * @returns {void} + */ + const handle = (name, fn) => + ipcMain.handle(`cloud-logs:${name}`, async (event, input) => { + assertSender(event); + return fn(event, input); + }); + + /** + * Registers a session folder grant for the requesting sender webContents. + * @param {import("electron").IpcMainInvokeEvent} event - The IPC event object. + * @param {Object} session - The inspected session data. + * @param {string} dir - Directory path of the session. + * @returns {Object} Session summary with generated session grant ID. + */ + const register = (event, session, dir) => { + const id = randomUUID(); + selected.set(id, { owner: event.sender.id, dir, date: session.date }); + // Bound stale folder grants from repeated discovery/pickers. + if (selected.size > 2000) selected.delete(selected.keys().next().value); + const { files, ...summary } = session; + void files; + return { ...summary, id }; + }; + + /** + * Reads and verifies stored credentials, throwing if unconfigured. + * @returns {Promise<{user: string, apiKey: string}>} Valid credentials object. + * @throws {Error} If credentials are not configured. + */ + const auth = async () => { + await credentialsQueue; + const value = await credentials.getCredentials(); + if (!value.user || !value.apiKey) + throw new Error("Configure your user and API key in Credentials first."); + return value; + }; + + /** + * Queues a credential mutation operation to prevent concurrent writes. + * @param {function(): Promise} fn - The operation to execute. + * @returns {Promise} The result of the mutation operation. + */ + const changeCredentials = (fn) => { + const result = credentialsQueue.then(fn); + credentialsQueue = result.catch(() => {}); + return result; + }; + + /** + * Locks transfer execution and sets up progress reporting for uploads and downloads. + * @param {import("electron").IpcMainInvokeEvent} event - The IPC event object. + * @param {Object} input - Transfer input containing requestId. + * @param {function(function(string, number=, number=): void): Promise} fn - Transfer worker callback. + * @returns {Promise} Result returned by the transfer worker callback. + * @throws {Error} If another transfer is currently active. + */ + const transfer = async (event, input, fn) => { + text(input?.requestId, 100); + if (transferRunning) + throw new Error("Another Cloud Logs transfer is in progress."); + transferRunning = true; + const report = (phase, completed, total) => { + if (!event.sender.isDestroyed()) + event.sender.send("cloud-logs:progress", { + requestId: input.requestId, + phase, + completed, + total, + }); + }; + try { + return await fn(report); + } finally { + transferRunning = false; + } + }; + + handle("credentials-status", () => + credentialsQueue.then(() => credentials.getCredentialsStatus()), + ); + handle("credentials-save", (_event, input) => + changeCredentials(() => credentials.setCredentials(input)), + ); + handle("credentials-clear", () => + changeCredentials(() => credentials.clearCredentials()), + ); + handle("local-sessions", async (event) => { + await getCloudRoot(); + const sessions = await findLocalSessions(); + return sessions.map(({ dir, ...session }) => register(event, session, dir)); + }); + handle("select-session", async (event) => { + const result = await dialog.showOpenDialog( + BrowserWindow.fromWebContents(event.sender), + { + title: "Select a completed logging session", + defaultPath: await getLogsRoot(), + properties: ["openDirectory"], + }, + ); + if (result.canceled) return null; + const dir = result.filePaths[0]; + return register(event, await inspectSession(dir), dir); + }); + handle("list", async (_event, cursor) => { + let sanitizedCursor; + if (cursor !== undefined && cursor !== null) { + if (typeof cursor !== "string") { + throw new Error("Invalid Cloud Logs request."); + } + const trimmed = cursor.trim(); + if (trimmed.length > 0) { + sanitizedCursor = text(trimmed); + } + } + try { + return await client.listLogs({ + credentials: await auth(), + cursor: sanitizedCursor, + }); + } catch (error) { + throw cleanClientError(error); + } + }); + handle("tags", async (_event, query) => { + if (typeof query !== "string" || query.length > 200) + throw new Error("Invalid tag query."); + try { + return await client.autocompleteTags({ + credentials: await auth(), + query, + }); + } catch (error) { + throw cleanClientError(error); + } + }); + handle("upload", (event, input) => + transfer(event, input, async (report) => { + const grant = selected.get(input?.sessionId); + if (!grant || grant.owner !== event.sender.id) + throw new Error("Select the session again before uploading."); + if ( + typeof input?.notes !== "string" || + input.notes.length > 10000 || + !Array.isArray(input.tags) || + input.tags.length > 30 + ) + throw new Error("Invalid notes or tags."); + const title = + typeof input?.title === "string" && input.title.trim() + ? text(input.title.trim(), 200) + : ""; + const tags = [...new Set(input.tags.map((tag) => text(tag, 100)))]; + const account = await auth(); + const temp = await mkdtemp(path.join(tmpdir(), "cloud-logs-upload-")); + try { + report("compressing", 0); + const archiveName = formatSessionZipName(grant.date, title); + const archivePath = path.join(temp, archiveName); + const session = await compressSession( + grant.dir, + archivePath, + (n, total) => report("compressing", n, total), + ); + report("uploading"); + try { + return await client.uploadLog({ + credentials: account, + archivePath, + metadata: { + fileName: archiveName, + title: title || undefined, + user: account.user, + notes: input.notes.trim(), + tags, + date: session.date, + }, + }); + } catch (error) { + throw cleanClientError(error); + } + } finally { + await rm(temp, { recursive: true, force: true }); + } + }), + ); + handle("download", (event, input) => + transfer(event, input, async (report) => { + const id = text(input?.id); + const title = + typeof input?.title === "string" && input.title.trim() + ? text(input.title.trim(), 200) + : ""; + const rawFileName = + typeof input?.fileName === "string" && input.fileName.trim() + ? text(input.fileName.trim(), 255) + : ""; + const fileName = rawFileName + ? path.basename(rawFileName).replace(/[/\\?%*:|"<>]/g, "_") + : ""; + const archiveName = fileName + ? fileName.endsWith(".zip") + ? fileName + : `${fileName}.zip` + : title + ? `${title.replace(/[/\\?%*:|"<>]/g, "_")}.zip` + : `${id}.zip`; + const derivedTitle = + title || (fileName ? fileName.replace(/\.zip$/i, "") : ""); + const account = await auth(); + const root = await getCloudRoot(); + // Return cached copy if already downloaded and valid + const existing = await findExistingDownload(root, id); + if (existing) { + return { + id, + path: existing.dir, + date: existing.session.date, + title: + existing.info.title || + (existing.info.fileName + ? existing.info.fileName.replace(/\.zip$/i, "") + : ""), + fileName: existing.info.fileName || "", + }; + } + + // Staging on the destination filesystem makes the final rename atomic. + const temp = await mkdtemp(path.join(root, ".download-")); + try { + const archivePath = path.join(temp, archiveName); + report("downloading"); + try { + await client.downloadLog({ + credentials: account, + id, + destination: archivePath, + maxBytes: MAX_BYTES, + }); + } catch (error) { + throw cleanClientError(error); + } + if ((await stat(archivePath)).size > MAX_BYTES) + throw new Error("Downloaded archive exceeds 4 GiB."); + report("extracting", 0); + const extracted = path.join(temp, "session"); + const session = await extractSession( + archivePath, + extracted, + (n, total) => report("extracting", n, total), + ); + await writeFile( + path.join(extracted, "cloud-log.json"), + JSON.stringify({ + id, + date: session.date, + title: derivedTitle, + fileName: fileName || archiveName, + }), + ); + + // Destination folder format: - + const folderName = formatDownloadedFolderName(session.date, { + fileName, + title, + id, + }); + + // Disambiguate folder name if destination already exists for a different session + let targetName = folderName; + let destination = path.join(root, targetName); + let counter = 1; + while (true) { + try { + await stat(destination); + let matchesCurrentId = false; + try { + const existingRaw = await readFile( + path.join(destination, "cloud-log.json"), + "utf8", + ); + const existingInfo = JSON.parse(existingRaw); + if (existingInfo.id === id) { + matchesCurrentId = true; + } + } catch { + matchesCurrentId = false; + } + + if (matchesCurrentId) { + break; + } + + counter++; + targetName = `${folderName}_${counter}`; + destination = path.join(root, targetName); + } catch (err) { + if (err.code === "ENOENT") break; + throw err; + } + } + + // Remove stale directories matching this cloud log ID + try { + for (const entry of await readdir(root, { withFileTypes: true })) { + if (!entry.isDirectory() || entry.name.startsWith(".")) continue; + const dir = path.join(root, entry.name); + if (dir === destination) continue; + try { + const info = JSON.parse( + await readFile(path.join(dir, "cloud-log.json"), "utf8"), + ); + if (info.id === id) { + await rm(dir, { recursive: true, force: true }); + } + } catch { + /* skip */ + } + } + } catch {} + + await rm(destination, { recursive: true, force: true }); + await rename(extracted, destination); + return { + id, + path: destination, + date: session.date, + title: derivedTitle, + fileName: fileName || archiveName, + }; + } finally { + await rm(temp, { recursive: true, force: true }); + } + }), + ); + handle("downloads", async () => { + const root = await getCloudRoot(); + const items = []; + for (const entry of await readdir(root, { withFileTypes: true })) { + if (!entry.isDirectory() || entry.name.startsWith(".")) continue; + const dir = path.join(root, entry.name); + try { + const info = JSON.parse( + await readFile(path.join(dir, "cloud-log.json"), "utf8"), + ); + const session = await inspectSession(dir); + items.push({ + id: text(info.id), + date: session.date, + path: dir, + title: + info.title || + (info.fileName ? info.fileName.replace(/\.zip$/i, "") : ""), + fileName: info.fileName || "", + }); + } catch { + /* Do not expose partial or invalid downloads. */ + } + } + return items.sort((a, b) => b.date.localeCompare(a.date)); + }); +} diff --git a/electron-app/src/cloudLogs/sessions.js b/electron-app/src/cloudLogs/sessions.js new file mode 100644 index 000000000..4f94888ec --- /dev/null +++ b/electron-app/src/cloudLogs/sessions.js @@ -0,0 +1,258 @@ +/** + * @module cloudLogs + * @description Session discovery, inspection, and path formatting utilities for Cloud Logs. + * Handles locating local recording sessions, validating session contents, and resolving paths. + */ + +import { lstat, readdir, readFile, mkdir } from "node:fs/promises"; +import path from "node:path"; +import { readConfig } from "../config/configInstance.js"; +import { getBackendWorkingDir } from "../utils/paths.js"; + +/** + * Hard limit of 4 GiB per session archive to guard against memory and disk exhaustion. + * @constant {number} + */ +export const MAX_BYTES = 4 * 1024 ** 3; + +/** + * Limit of 10,000 files per session to mitigate zip bomb attacks and inode exhaustion. + * @constant {number} + */ +export const MAX_FILES = 10000; + +/** + * Determines whether a file path belongs to a regular session recording. + * Excludes internal descriptor and traversal paths. + * @param {string} name - Relative file name or path. + * @returns {boolean} True if the file belongs to a session recording. + */ +export const isSessionFile = (name) => + name === "logger_settings.json" || + (!name.startsWith("cloud-log.json") && !name.startsWith("../")); + +/** + * Resolves the telemetry logs root directory (`/logger`). + * @returns {Promise} Absolute path to the logger directory. + */ +export async function getLogsRoot() { + const config = await readConfig(); + return path.resolve( + getBackendWorkingDir(), + config.logging?.logging_path || ".", + "logger", + ); +} + +/** + * Resolves `logger/cloud-logs`, rejecting symlinks to prevent directory traversal. + * @returns {Promise} Absolute path to the cloud-logs directory. + * @throws {Error} If the cloud logs directory is a symbolic link. + */ +export async function getCloudRoot() { + const root = path.join(await getLogsRoot(), "cloud-logs"); + await mkdir(root, { recursive: true }); + if ((await lstat(root)).isSymbolicLink()) + throw new Error("Cloud Logs folder cannot be a symbolic link."); + return root; +} + +/** + * Formats upload ZIP filename from recording date and optional sanitized title. + * @param {string} [dateStr] - ISO or formatted recording date string. + * @param {string} [title] - Optional human-readable session title. + * @returns {string} Sanitized ZIP filename ending in .zip. + */ +export function formatSessionZipName(dateStr, title) { + if (typeof title === "string" && title.trim()) { + const cleaned = title + .trim() + .replace(/\.zip$/i, "") + .replace(/[/\\?%*:|"<>]/g, "_"); + if (cleaned) { + return `${cleaned}.zip`; + } + } + + const pad = (v) => String(v).padStart(2, "0"); + if (!dateStr || typeof dateStr !== "string" || !dateStr.trim()) { + const now = new Date(); + const y = now.getUTCFullYear(); + const m = pad(now.getUTCMonth() + 1); + const d = pad(now.getUTCDate()); + const h = pad(now.getUTCHours()); + const min = pad(now.getUTCMinutes()); + const s = pad(now.getUTCSeconds()); + return `${y}-${m}-${d}T${h}-${min}-${s}.zip`; + } + + const match = dateStr.match( + /^(\d{4})-(\d{1,2})-(\d{1,2})[T_ ](\d{1,2})[-:](\d{1,2})[-:](\d{1,2})/, + ); + if (match) { + const [, y, m, d, h, min, s] = match; + return `${y}-${pad(m)}-${pad(d)}T${pad(h)}-${pad(min)}-${pad(s)}.zip`; + } + + const cleaned = dateStr + .trim() + .replace(/\.zip$/i, "") + .replace(/[/\\?%*:|"<>]/g, "-"); + return `${cleaned}.zip`; +} + +/** + * Formats destination directory name: `-`. + * @param {string} [dateStr] - Optional recording date string containing time components. + * @param {Object} [metadata={}] - Session metadata options. + * @param {string} [metadata.fileName] - Original archive filename. + * @param {string} [metadata.title] - Human-readable session title. + * @param {string} [metadata.id] - Remote session identifier. + * @returns {string} Formatted directory name. + */ +export function formatDownloadedFolderName( + dateStr, + { fileName, title, id } = {}, +) { + let base = ""; + if (typeof fileName === "string" && fileName.trim()) { + base = path + .basename(fileName.trim()) + .replace(/\.zip$/i, "") + .replace(/[/\\?%*:|"<>]/g, "_") + .replace(/\s+/g, "_") + .trim(); + } + if (!base && typeof title === "string" && title.trim()) { + base = title + .trim() + .replace(/\.zip$/i, "") + .replace(/[/\\?%*:|"<>]/g, "_") + .replace(/\s+/g, "_") + .trim(); + } + if (!base && typeof id === "string" && id.trim()) { + base = id + .trim() + .replace(/[/\\?%*:|"<>]/g, "_") + .replace(/\s+/g, "_") + .trim(); + } + if (!base) { + base = "session"; + } + + const pad = (v) => String(v).padStart(2, "0"); + let timePart = ""; + if (typeof dateStr === "string" && dateStr.trim()) { + const match = dateStr.match(/[T_ ](\d{1,2})[-:](\d{1,2})[-:](\d{1,2})/); + if (match) { + const [, h, min, s] = match; + timePart = `${pad(h)}-${pad(min)}-${pad(s)}`; + } + } + + if (!timePart) { + const now = new Date(); + timePart = `${pad(now.getHours())}-${pad(now.getMinutes())}-${pad(now.getSeconds())}`; + } + + return `${base}-${timePart}`; +} + +/** + * Validates a recording directory and extracts session metadata from logger_settings.json. + * Enforces depth limit, file count limit, byte size limit, and symlink prohibition. + * @param {string} dir - Absolute path to the session folder to inspect. + * @returns {Promise<{ name: string, launch: string, date: string, bytes: number, fileCount: number, files: Array<{ name: string, size: number, mtimeMs: number }> }>} Session metadata. + * @throws {Error} If directory is invalid, limits are exceeded, or logger_settings.json is missing or malformed. + */ +export async function inspectSession(dir) { + if (!(await lstat(dir)).isDirectory()) + throw new Error("Select a logging session folder."); + const files = []; + let bytes = 0; + + // Recursively traverse directory up to depth limit + async function walk(relative = "", depth = 0) { + if (depth > 8) throw new Error("Session directory is too deeply nested."); + for (const entry of await readdir(path.join(dir, relative), { + withFileTypes: true, + })) { + if (entry.isSymbolicLink()) + throw new Error("Session folders cannot contain symbolic links."); + const name = relative ? `${relative}/${entry.name}` : entry.name; + if (entry.isDirectory()) { + await walk(name, depth + 1); + } else if (entry.isFile() && name !== "cloud-log.json") { + const stats = await lstat(path.join(dir, name)); + bytes += stats.size; + files.push({ name, size: stats.size, mtimeMs: stats.mtimeMs }); + if (bytes > MAX_BYTES || files.length > MAX_FILES) + throw new Error("Session exceeds the 4 GiB / 10,000 file limit."); + } + } + } + await walk(); + + // Validate that logger_settings.json is present + if (!files.some((f) => f.name === "logger_settings.json")) + throw new Error( + "Select a recording containing logger_settings.json, not the app launch folder.", + ); + + // Parse session date from logger_settings.json + const settings = JSON.parse( + await readFile(path.join(dir, "logger_settings.json"), "utf8"), + ); + const dateMatch = + typeof settings.date === "string" && + settings.date.match( + /^(\d{4})-(\d{1,2})-(\d{1,2})[T_ ](\d{1,2})[-:](\d{1,2})[-:](\d{1,2})/, + ); + if (!dateMatch) throw new Error("Session has no valid recording date."); + const [, y, m, d, h, min, s] = dateMatch; + const pad = (v) => v.padStart(2, "0"); + const normalizedDate = `${y}-${pad(m)}-${pad(d)}T${pad(h)}-${pad(min)}-${pad(s)}`; + return { + name: path.basename(dir), + launch: path.basename(path.dirname(dir)), + date: normalizedDate, + bytes, + fileCount: files.length, + files: files.sort((a, b) => a.name.localeCompare(b.name)), + }; +} + +/** + * Discovers completed local sessions across launch directories, sorted descending by date. + * @returns {Promise>} List of discovered session metadata objects. + * @throws {Error} If reading the root log directory fails. + */ +export async function findLocalSessions() { + const root = await getLogsRoot(); + let launches; + try { + launches = await readdir(root, { withFileTypes: true }); + } catch (error) { + if (error.code === "ENOENT") return []; + throw error; + } + const sessions = []; + for (const launch of launches) { + if (!launch.isDirectory() || !/^\d{4}-\d{2}-\d{2}T/.test(launch.name)) + continue; + for (const entry of await readdir(path.join(root, launch.name), { + withFileTypes: true, + })) { + if (!entry.isDirectory() || entry.name === "others") continue; + const dir = path.join(root, launch.name, entry.name); + try { + sessions.push({ dir, ...(await inspectSession(dir)) }); + } catch { + // Incomplete or empty recordings are not upload candidates + } + } + } + return sessions.sort((a, b) => b.date.localeCompare(a.date)); +} diff --git a/electron-app/src/ipc/__tests__/handlers.test.js b/electron-app/src/ipc/__tests__/handlers.test.js new file mode 100644 index 000000000..372da431f --- /dev/null +++ b/electron-app/src/ipc/__tests__/handlers.test.js @@ -0,0 +1,146 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +const { handlers, mockIpcMain, mockWebContents } = vi.hoisted(() => { + const map = new Map(); + const webContents = { id: 1 }; + return { + handlers: map, + mockIpcMain: { + handle: vi.fn((channel, fn) => { + map.set(channel, fn); + }), + }, + mockWebContents: webContents, + }; +}); + +vi.mock("electron", () => ({ + app: { + getVersion: () => "1.0.0", + emit: vi.fn(), + }, + dialog: { + showOpenDialog: vi.fn(), + showMessageBox: vi.fn(), + showErrorBox: vi.fn(), + }, + ipcMain: mockIpcMain, + shell: { + openPath: vi.fn(), + }, +})); + +vi.mock("../../utils/paths.js", () => ({ + getAppPath: () => "/app", +})); + +vi.mock("../../utils/logger.js", () => ({ + logger: { + electron: { + info: vi.fn(), + error: vi.fn(), + }, + }, +})); + +vi.mock("../../windows/mainWindow.js", () => ({ + getMainWindow: () => ({ webContents: mockWebContents }), + getCurrentView: vi.fn(), + loadView: vi.fn(), +})); + +vi.mock("../../processes/backend.js", () => ({ + getBackendWorkingDir: () => "/app", + restartBackend: vi.fn(), +})); + +vi.mock("../../config/configInstance.js", () => ({ + importConfig: vi.fn(), + readConfig: vi.fn(), + writeConfig: vi.fn(), +})); + +vi.mock("../../cloudLogs/handlers.js", () => ({ + setupCloudLogsHandlers: vi.fn(), +})); + +vi.mock("../../cloudLogs/sessions.js", () => ({ + getLogsRoot: vi.fn().mockResolvedValue("/app/logger"), +})); + +import { setupIpcHandlers } from "../handlers.js"; + +describe("IPC handlers - list-session-files", () => { + let tempDir; + + beforeEach(async () => { + handlers.clear(); + vi.clearAllMocks(); + setupIpcHandlers(); + tempDir = await mkdtemp(path.join(tmpdir(), "ipc-session-test-")); + }); + + afterEach(async () => { + await rm(tempDir, { recursive: true, force: true }); + }); + + const createSenderEvent = () => ({ + sender: mockWebContents, + }); + + it("uses basename of directory when cloud-log.json is absent", async () => { + const handler = handlers.get("list-session-files"); + expect(handler).toBeDefined(); + + await writeFile(path.join(tempDir, "data.csv"), "1,2,3"); + + const result = await handler(createSenderEvent(), tempDir); + expect(result.folderName).toBe(path.basename(tempDir)); + expect(result.entries).toContain("data.csv"); + }); + + it("uses info.title from cloud-log.json as folderName when present", async () => { + const handler = handlers.get("list-session-files"); + + await writeFile( + path.join(tempDir, "cloud-log.json"), + JSON.stringify({ title: "Custom Session Title", fileName: "custom.zip" }), + ); + await writeFile(path.join(tempDir, "logger_settings.json"), "{}"); + + const result = await handler(createSenderEvent(), tempDir); + expect(result.folderName).toBe("Custom Session Title"); + expect(result.entries).toContain("logger_settings.json"); + expect(result.entries).not.toContain("cloud-log.json"); + }); + + it("uses info.fileName without .zip from cloud-log.json when title is absent", async () => { + const handler = handlers.get("list-session-files"); + + await writeFile( + path.join(tempDir, "cloud-log.json"), + JSON.stringify({ fileName: "Run_2026-11-15.zip" }), + ); + await writeFile(path.join(tempDir, "logger_settings.json"), "{}"); + + const result = await handler(createSenderEvent(), tempDir); + expect(result.folderName).toBe("Run_2026-11-15"); + expect(result.entries).toContain("logger_settings.json"); + expect(result.entries).not.toContain("cloud-log.json"); + }); + + it("falls back to basename when cloud-log.json has neither title nor fileName", async () => { + const handler = handlers.get("list-session-files"); + + await writeFile( + path.join(tempDir, "cloud-log.json"), + JSON.stringify({ id: "session-123" }), + ); + + const result = await handler(createSenderEvent(), tempDir); + expect(result.folderName).toBe(path.basename(tempDir)); + }); +}); diff --git a/electron-app/src/ipc/handlers.js b/electron-app/src/ipc/handlers.js index f16fce3f7..293f2cd62 100644 --- a/electron-app/src/ipc/handlers.js +++ b/electron-app/src/ipc/handlers.js @@ -5,6 +5,8 @@ * - View management * - Configuration management * - Folder selection dialogs + * - Session file management + * - Cloud logs integration */ import { app, dialog, ipcMain, shell } from "electron"; @@ -18,12 +20,11 @@ import { readConfig, writeConfig, } from "../config/configInstance.js"; -import { - getBackendWorkingDir, - restartBackend, -} from "../processes/backend.js"; +import { getBackendWorkingDir, restartBackend } from "../processes/backend.js"; import { logger } from "../utils/logger.js"; import { getAppPath } from "../utils/paths.js"; +import { setupCloudLogsHandlers } from "../cloudLogs/handlers.js"; +import { getLogsRoot } from "../cloudLogs/sessions.js"; import { getCurrentView, getMainWindow, @@ -39,6 +40,8 @@ import { * setupIpcHandlers(); */ function setupIpcHandlers() { + setupCloudLogsHandlers(); + /** * @event get-current-view * @description Returns the identifier of the currently loaded view. @@ -56,12 +59,20 @@ function setupIpcHandlers() { await restartBackend(); } catch (error) { logger.electron.error("Failed to restart backend:", error); - dialog.showErrorBox("Restart Failed", `Could not restart backend:\n\n${error.message}`); + dialog.showErrorBox( + "Restart Failed", + `Could not restart backend:\n\n${error.message}`, + ); } finally { loadView("testing-view"); } }); + /** + * @event get-app-version + * @description Returns the application version string from package metadata. + * @returns {string} The application version. + */ ipcMain.handle("get-app-version", () => app.getVersion()); /** @@ -99,6 +110,11 @@ function setupIpcHandlers() { } }); + /** + * @event get-available-views + * @description Returns the list of views available in the current build. + * @returns {Array<{mode: string, label: string}>} Available views list. + */ ipcMain.handle("get-available-views", () => { const ALL_VIEWS = [ { mode: "testing", label: "Testing View" }, @@ -109,15 +125,15 @@ function setupIpcHandlers() { ]; const rendererDir = join(getAppPath(), "renderer"); return ALL_VIEWS.filter(({ mode }) => - fs.existsSync(join(rendererDir, `${mode}-view`)) + fs.existsSync(join(rendererDir, `${mode}-view`)), ); }); /** * @event switch-view - * @description Switches the main window to the specified view. + * @description Switches to the specified view. * @param {import("electron").IpcMainInvokeEvent} event - The IPC event object. - * @param {string} view - The name of the view to switch to (e.g., "ethernet-view", "control-station"). + * @param {string} view - The name of the view to switch to. * @param {Record} [query] - Optional query params passed through to the * loaded view's URL (e.g. `{ commit: hash }` so adj-view can auto-load a commit). * @returns {string} The view name that was loaded. @@ -127,8 +143,6 @@ function setupIpcHandlers() { return view; }); - - /** * @event save-config * @async @@ -196,6 +210,7 @@ function setupIpcHandlers() { const mainWindow = getMainWindow(); const result = await dialog.showOpenDialog(mainWindow, { title: "Select Logging Folder", + defaultPath: await getLogsRoot(), properties: ["openDirectory"], }); @@ -238,8 +253,12 @@ function setupIpcHandlers() { // browser File objects, so reopening a recent session from its path needs // the main process to list and read it. - // Guard: these two read arbitrary paths, so only the window that actually - // hosts the views may call them (same spirit as the About window's check). + /** + * Restricts session file IPC access strictly to the main window webContents. + * @param {import("electron").IpcMainInvokeEvent} event - The IPC event object. + * @throws {Error} If the sender is not the main window. + * @returns {void} + */ const assertSessionSender = (event) => { const mainWindow = getMainWindow(); if (!mainWindow || event.sender !== mainWindow.webContents) { @@ -247,36 +266,36 @@ function setupIpcHandlers() { } }; - // A session is /logger_settings.json, /data//*.csv and - // /order/order.csv — exactly what the renderer's openSession reads. - // Walking only those three shapes keeps a huge parent folder from being - // scanned, and Dirent.isDirectory()/isFile() skip symlinks. - const SESSION_FILE_LIMIT = 4000; + // A recording is identified by logger_settings.json. Walk its contents up to 10,000 files + // and depth 8, matching cloud-logs session limits, so future logger subfolders can be read. + const SESSION_FILE_LIMIT = 10000; + const MAX_SESSION_DEPTH = 8; + /** + * Recursively collects file entries within a session directory up to SESSION_FILE_LIMIT and MAX_SESSION_DEPTH. + * @param {string} dir - The session root directory path. + * @returns {Promise} Array of slash-separated relative file paths. + */ const listSessionEntries = async (dir) => { const entries = []; - if (fs.existsSync(join(dir, "logger_settings.json"))) { - entries.push("logger_settings.json"); - } - if (fs.existsSync(join(dir, "order", "order.csv"))) { - entries.push("order/order.csv"); - } - let boards = []; - try { - boards = await readdir(join(dir, "data"), { withFileTypes: true }); - } catch { - return entries; - } - for (const board of boards) { - if (!board.isDirectory()) continue; - const files = await readdir(join(dir, "data", board.name), { + const walk = async (relative = "", depth = 0) => { + if (depth > MAX_SESSION_DEPTH) return; + const children = await readdir(join(dir, relative), { withFileTypes: true, }); - for (const file of files) { - if (!file.isFile() || !file.name.endsWith(".csv")) continue; - entries.push(`data/${board.name}/${file.name}`); - if (entries.length >= SESSION_FILE_LIMIT) return entries; + for (const child of children) { + if (child.isSymbolicLink()) continue; + const name = relative ? join(relative, child.name) : child.name; + if (child.isDirectory()) await walk(name, depth + 1); + else if (child.isFile() && name !== "cloud-log.json") + entries.push(name.split(sep).join("/")); + if (entries.length >= SESSION_FILE_LIMIT) return; } + }; + try { + await walk(); + } catch (error) { + if (error.code !== "ENOENT") throw error; } return entries; }; @@ -300,8 +319,22 @@ function setupIpcHandlers() { if (!stats.isDirectory()) { throw new Error(`Not a folder: ${dir}`); } + let folderName = basename(dir) || "Session"; + try { + // If cloud-log.json is present, use its title or archive filename instead of the raw directory name. + const info = JSON.parse( + await readFile(join(dir, "cloud-log.json"), "utf8"), + ); + if (info.title) { + folderName = info.title; + } else if (info.fileName) { + folderName = info.fileName.replace(/\.zip$/i, ""); + } + } catch { + // Not a cloud log folder + } return { - folderName: basename(dir) || "Session", + folderName, entries: await listSessionEntries(dir), }; }); @@ -329,6 +362,12 @@ function setupIpcHandlers() { // BLCU — only the file picker runs through IPC; all API calls go directly // from the renderer to http://localhost:8000. + /** + * @event blcu-select-file + * @async + * @description Opens a native file dialog to select a firmware file (.bin, .hex, .elf). + * @returns {Promise} The selected file path, or null if canceled. + */ ipcMain.handle("blcu-select-file", async () => { try { const mainWindow = getMainWindow(); @@ -344,6 +383,14 @@ function setupIpcHandlers() { } }); + /** + * @event blcu-read-file + * @async + * @description Reads a firmware file from disk into a buffer. + * @param {import("electron").IpcMainInvokeEvent} _event - The IPC event object. + * @param {string} filePath - Absolute path to the firmware file. + * @returns {Promise} The file contents buffer. + */ ipcMain.handle("blcu-read-file", async (_event, filePath) => { return await readFile(filePath); }); diff --git a/frontend/frontend-kit/kit/src/core/cloudLogs.ts b/frontend/frontend-kit/kit/src/core/cloudLogs.ts new file mode 100644 index 000000000..d6e095e2e --- /dev/null +++ b/frontend/frontend-kit/kit/src/core/cloudLogs.ts @@ -0,0 +1,73 @@ +/** Shared desktop IPC contract for Cloud Logs management (`window.electronAPI.cloudLogs`). */ + +export interface CloudLog { + id: string; + user: string; + notes: string; + tags: string[]; + date: string; + title?: string; + fileName?: string; + logDate?: string; + uploadDate?: string; +} + +export interface LocalLogSession { + id: string; + name: string; + launch: string; + date: string; + fileCount: number; + bytes: number; +} + +export interface DownloadedLog { + id: string; + path: string; + date: string; + title?: string; + fileName?: string; +} + +export interface CloudCredentialsStatus { + user: string; + hasApiKey: boolean; + persistent: boolean; +} + +export interface CloudLogProgress { + requestId: string; + phase: "compressing" | "uploading" | "downloading" | "extracting"; + completed?: number; + total?: number; +} + +export interface CloudLogsAPI { + getCredentialsStatus(): Promise; + setCredentials(input: { + user: string; + apiKey?: string; + }): Promise; + clearCredentials(): Promise; + getLocalSessions(): Promise; + selectSession(): Promise; + list( + cursor?: string | null, + ): Promise<{ items: CloudLog[]; nextCursor?: string }>; + autocompleteTags(query: string): Promise; + upload(input: { + sessionId: string; + title?: string; + notes: string; + tags: string[]; + requestId: string; + }): Promise; + download(input: { + id: string; + title?: string; + fileName?: string; + requestId: string; + }): Promise; + getDownloads(): Promise; + onProgress(callback: (progress: CloudLogProgress) => void): () => void; +} diff --git a/frontend/frontend-kit/kit/src/core/index.ts b/frontend/frontend-kit/kit/src/core/index.ts index 005c4cefa..4315aca3e 100644 --- a/frontend/frontend-kit/kit/src/core/index.ts +++ b/frontend/frontend-kit/kit/src/core/index.ts @@ -3,3 +3,4 @@ export * from "./loggerColors"; export * from "./minMaxDownsample"; export * from "./types"; export * from "./websocket"; +export type * from "./cloudLogs"; diff --git a/frontend/logging-view/src/components/cloudLogs/CloudLogsDialog.tsx b/frontend/logging-view/src/components/cloudLogs/CloudLogsDialog.tsx new file mode 100644 index 000000000..64a8c7a8d --- /dev/null +++ b/frontend/logging-view/src/components/cloudLogs/CloudLogsDialog.tsx @@ -0,0 +1,969 @@ +// Cloud Logs management dialog (Credentials, Upload, and Catalog Library). +// Provides an interface to sync, upload local sessions to the cloud, +// and download remote sessions directly into the local logging directory. + +import { useEffect, useRef, useState } from "react"; +import { + Button, + Checkbox, + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, + Input, + Label, + SidebarMenuButton, + Tabs, + TabsContent, + TabsList, + TabsTrigger, + Textarea, +} from "@hyperloopupv/frontend-kit/components"; +import { + AlertCircle, + CheckCircle2, + Database, + FileDown, + FolderOpen, + RefreshCw, + Upload, + X, +} from "@hyperloopupv/frontend-kit/icons"; +import type { + CloudCredentialsStatus, + CloudLog, + CloudLogProgress, + CloudLogsAPI, + DownloadedLog, + LocalLogSession, +} from "@hyperloopupv/frontend-kit/core"; +import { useSessionFolder } from "../../hooks/useSessionFolder"; + +const failureMessage = (error: unknown) => + (error instanceof Error ? error.message : String(error)).replace( + /^Error invoking remote method '[^']+': (?:Error: )?/, + "", + ); + +const dateLabel = (date: string) => { + if (!date) return ""; + const clean = date.replace(/\.\d+Z?$/, "").replace(/Z$/, ""); + return clean + .replace("T", " · ") + .replace(/(\d{2})[-:](\d{2})[-:](\d{2})$/, "$1:$2:$3"); +}; + +const sizeLabel = (bytes: number) => `${(bytes / 1024 ** 2).toFixed(1)} MB`; + +const phases = { + compressing: "Compressing session…", + uploading: "Uploading ZIP…", + downloading: "Downloading ZIP…", + extracting: "Extracting session…", +}; + +const noticeTones = { + info: "bg-muted/40 text-muted-foreground", + success: + "border-green-600/30 bg-green-600/10 text-green-700 dark:text-green-400", + // The theme's dark `--destructive` is too dim for text on a dark background. + error: "border-red-600/30 bg-red-600/10 text-red-700 dark:text-red-400", +}; + +/** Inline feedback: grey for hints, green when an operation worked, red when it failed. */ +function Notice({ + children, + error = false, + success = false, +}: { + children: React.ReactNode; + error?: boolean; + success?: boolean; +}) { + const tone = error ? "error" : success ? "success" : "info"; + const Icon = error ? AlertCircle : success ? CheckCircle2 : null; + return ( +
+ {Icon && } +

{children}

+
+ ); +} + +function CredentialsPanel({ + api, + status, + onSaved, +}: { + api: CloudLogsAPI; + status: CloudCredentialsStatus | null; + onSaved: (status: CloudCredentialsStatus) => void; +}) { + const [user, setUser] = useState(status?.user ?? ""); + const [key, setKey] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + const [message, setMessage] = useState(""); + const [confirmClear, setConfirmClear] = useState(false); + + useEffect(() => setUser(status?.user ?? ""), [status?.user]); + + const save = async (clear = false) => { + setBusy(true); + setError(""); + setMessage(""); + try { + const next = clear + ? await api.clearCredentials() + : await api.setCredentials({ user, apiKey: key }); + setKey(""); + setConfirmClear(false); + onSaved(next); + setMessage( + clear + ? "Credentials removed." + : "Credentials saved. They are shared by Logging View and Testing View.", + ); + } catch (err) { + setError(failureMessage(err)); + } finally { + setBusy(false); + } + }; + + return ( +
{ + event.preventDefault(); + void save(); + }} + > +

+ Set the account used to access Cloud Logs and identify your uploads. +

+
+ + setUser(e.target.value)} + placeholder="Your user name" + /> +
+
+ + setKey(e.target.value)} + placeholder={ + status?.hasApiKey + ? "Key configured — leave blank to keep it" + : "Enter your API key" + } + /> +

+ {status?.persistent + ? "Stored encrypted on this computer. The saved key is never displayed." + : "Secure storage is unavailable. Your API key will only be kept until the app closes."} +

+
+ {error && {error}} + {message && {message}} +
+ + {status?.hasApiKey && ( + + )} +
+ {confirmClear && ( +
+ Remove the saved user and API key from this computer? + +
+ )} +
+ ); +} + +function UploadPanel({ + api, + ready, + busy, + onUpload, +}: { + api: CloudLogsAPI; + ready: boolean; + busy: boolean; + onUpload: ( + session: LocalLogSession, + notes: string, + tags: string[], + title?: string, + ) => Promise; +}) { + const [sessions, setSessions] = useState([]); + const [selected, setSelected] = useState(null); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(""); + const [title, setTitle] = useState(""); + const [notes, setNotes] = useState(""); + const [tags, setTags] = useState([]); + const [query, setQuery] = useState(""); + const [suggestions, setSuggestions] = useState([]); + const [tagError, setTagError] = useState(""); + const [tagBusy, setTagBusy] = useState(false); + const [stopped, setStopped] = useState(false); + + const refresh = async () => { + setLoading(true); + setError(""); + try { + setSessions(await api.getLocalSessions()); + } catch (err) { + setError(failureMessage(err)); + } finally { + setLoading(false); + } + }; + + useEffect(() => { + void refresh(); + }, [api]); // eslint-disable-line react-hooks/exhaustive-deps + + // Debounce tag autocomplete (300ms) with a cancellation guard for out-of-order responses. + useEffect(() => { + if (!ready) return; + let current = true; + setTagBusy(true); + setTagError(""); + setSuggestions([]); + const timer = setTimeout(() => { + api + .autocompleteTags(query) + .then((items) => { + if (current) setSuggestions([...new Set(items)]); + }) + .catch((err) => { + if (current) setTagError(failureMessage(err)); + }) + .finally(() => { + if (current) setTagBusy(false); + }); + }, 300); + return () => { + current = false; + clearTimeout(timer); + }; + }, [api, query, ready]); + + const choose = (session: LocalLogSession | null) => { + setSelected(session); + setStopped(false); + }; + + const browse = async () => { + setLoading(true); + setError(""); + try { + const picked = await api.selectSession(); + if (picked) choose(picked); + } catch (err) { + setError(failureMessage(err)); + } finally { + setLoading(false); + } + }; + + const handleAddTag = (rawTag?: string) => { + const candidate = (rawTag ?? query).trim(); + if (!candidate || tags.includes(candidate) || tags.length >= 30) return; + setTags((prev) => [...prev, candidate]); + setQuery(""); + }; + + return ( +
{ + // Prevent Enter inside text inputs from accidentally submitting the upload form. + if ( + e.key === "Enter" && + (e.target as HTMLElement)?.tagName === "INPUT" + ) { + e.preventDefault(); + } + }} + onSubmit={async (e) => { + e.preventDefault(); + if (selected) { + const ok = await onUpload( + selected, + notes, + tags, + title.trim() || undefined, + ); + if (ok) { + setSelected(null); + setTitle(""); + setNotes(""); + setTags([]); + setStopped(false); + } + } + }} + > +

+ Share one completed recording. Its CSV files and session settings are + compressed into a ZIP before upload. +

+
+
+ + +
+ + + {!loading && !sessions.length && ( +

+ No completed recordings found in the configured logger folder. You + can browse to another session. +

+ )} +
+ {selected && ( +
+

{selected.name}

+

Launch: {selected.launch}

+

Log date: {dateLabel(selected.date)}

+

+ {selected.fileCount} files · {sizeLabel(selected.bytes)} before + compression +

+
+ )} +
+
+ + setTitle(e.target.value)} + /> +
+
+ +