diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 656ef75b..7f663112 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -88,7 +88,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S
| `Server/Api`, `Server/Events` | Endpoint groups (`XxxEndpoints.Map`; `ScheduleEndpoints`: `/api/v1/schedules`; `LibraryEndpoints`: the Library filters' facets, sequence thumbnail, photo delete, bulk delete/retag/jobs; `TrashEndpoints`: list, restore, empty), API errors, the WebSocket `EventHub` |
| `Server/Security` | Accounts, password hashing, tokens, session cookies, login guard, access rules, audit log |
| `Server/Storage`, `Server/Jobs` | Archive and processing modules, uploads (`UploadMaintenance`: recovery at start, and the sweep that is the `uploads` clean-up step), render store; `JobEngineHost`, `SchedulerHost` (the `Scheduler` on the engine, started after it; archive.json read every 10 minutes whatever the scan schedule does; every schedule change and run published as a `scheduleChanged` event) and `ServerScheduleHost` (time zone, archive refreshed from archive.json, system schedules), render node service, monitor and availability |
-| `Server/Hosting`, `Server/Admin/web` | `ServerHost`, `ServerLogging` (console and file levels the logging filters read at every line, the file sink's limits, the engine's level; applied again when Settings › Logs is saved), certificates, discovery beacon, embedded static files, Windows service (start and stop failures in the Application event log); the admin panel (ES modules, one per page; `schedules.js` is the Jobs page's Scheduled tab; the Library's views in `pages/library/`: `sequence.js` a sequence and its photo viewer, `trash.js` the archive's trash, `shared.js` cards, selection and grid keyboard; the web upload `upload.js` is imported on demand) |
+| `Server/Hosting`, `Server/Admin/web` | `ServerHost`, `ServerLogging` (console and file levels the logging filters read at every line, the file sink's limits, the engine's level; applied again when Settings › Logs is saved), certificates, discovery beacon, embedded static files, Windows service (start and stop failures in the Application event log); the admin panel (ES modules, one per page; `schedules.js` is the Jobs page's Scheduled tab; the Library's views in `pages/library/`: `sequence.js` a sequence and its photo viewer, `trash.js` the archive's trash, `shared.js` cards, selection and grid keyboard; `upload.js` the upload dialog the Library opens on demand, hashing in the module worker `hash-worker.js` with the in-house incremental SHA-256 of `sha256.js`, self-tested before its first use) |
### 2.5 Hosts
diff --git a/i18n/en/Admin.resx b/i18n/en/Admin.resx
index 36352a24..338df811 100644
--- a/i18n/en/Admin.resx
+++ b/i18n/en/Admin.resx
@@ -778,6 +778,61 @@
SequenceSizeTrash
+ Add photos
+ Choose photos on this computer; you can also drop them on this dialog
+ {0} of {1}
+ Cancel
+ Stop now: the photos not finished yet are discarded on the server
+ Close
+ Close the upload dialog
+ Photos: {0} of {1}
+ Drop photos here
+ Existing sequence
+ Add the photos to a sequence already on the server
+ Failed: {0}
+ Photos cannot be hashed in this browser, so nothing was uploaded.long
+ New sequence
+ Create a sequence on the server for these photos
+ Title
+ Name of the new sequence; left empty, it is named after the date and camera of its photos
+ No sequence found
+ {0} photo
+ {0} photos
+ Photos
+ Choose a sequence first.
+ The file could not be read.
+ Remove {0}
+ Take this photo off the list
+ Search sequences
+ Find a sequence by title, camera or tag
+ This browser computed a test SHA-256 wrongly, so nothing is uploaded from it.long
+ Sequences
+ The sequence the photos go into
+ Folders skipped: {0}
+ Folders are imported with the desktop app; here only photos are uploaded
+ Not photos: {0}
+ Files in a format the server does not read as photos were left out
+ Too large: {0}
+ Files larger than the server's upload limit ({0}) were left out
+ Upload
+ Send the photos not on the server yet; the server checks each one against its SHA-256
+ Cancelled
+ Deleted before
+ Deleted from this sequence earlier: restore it from the trash to bring it back
+ Uploaded
+ On the server and verified against its SHA-256
+ Already there
+ The server already has this photo
+ Failed
+ Hashing {0}
+ Not sent
+ Not sent: the upload stopped before this photo
+ Starting
+ Uploading {0}
+ Verifying
+ Waiting
+ Sequence
+ Upload photos{0} account{0} accountsActive
diff --git a/i18n/it/Admin.it.resx b/i18n/it/Admin.it.resx
index e00c17f8..54c95ad3 100644
--- a/i18n/it/Admin.it.resx
+++ b/i18n/it/Admin.it.resx
@@ -775,6 +775,61 @@
SequenzaDimensioneCestino
+ Aggiungi foto
+ Scegli le foto su questo computer; puoi anche trascinarle in questa finestra
+ {0} di {1}
+ Annulla
+ Ferma ora: le foto non ancora finite vengono scartate sul server
+ Chiudi
+ Chiudi la finestra di caricamento
+ Foto: {0} di {1}
+ Trascina qui le foto
+ Sequenza esistente
+ Aggiungi le foto a una sequenza già presente sul server
+ Non riuscite: {0}
+ In questo browser non si può calcolare l'hash delle foto, quindi non è stato caricato nulla.
+ Nuova sequenza
+ Crea sul server una sequenza per queste foto
+ Titolo
+ Nome della nuova sequenza; se resta vuoto, prende data e fotocamera delle sue foto
+ Nessuna sequenza trovata
+ {0} foto
+ {0} foto
+ Foto
+ Scegli prima una sequenza.
+ Impossibile leggere il file.
+ Togli {0}
+ Togli questa foto dall'elenco
+ Cerca sequenze
+ Trova una sequenza per titolo, fotocamera o tag
+ Questo browser ha calcolato male uno SHA-256 di prova, quindi non carica nulla.
+ Sequenze
+ La sequenza in cui vanno le foto
+ Cartelle saltate: {0}
+ Le cartelle si importano con l'app desktop; qui si caricano solo foto
+ Non foto: {0}
+ Esclusi i file in un formato che il server non legge come foto
+ Troppo grandi: {0}
+ Esclusi i file oltre il limite di caricamento del server ({0})
+ Carica
+ Invia le foto non ancora sul server; il server controlla ognuna con il suo SHA-256
+ Annullata
+ Eliminata prima
+ Eliminata in precedenza da questa sequenza: ripristinala dal cestino per riaverla
+ Caricata
+ Sul server e verificata con il suo SHA-256
+ Già presente
+ Il server ha già questa foto
+ Non riuscita
+ Calcolo hash {0}
+ Non inviata
+ Non inviata: il caricamento si è fermato prima di questa foto
+ Avvio
+ Invio {0}
+ Verifica
+ In attesa
+ Sequenza
+ Carica foto{0} account{0} accountAttivo
diff --git a/src/Chronos.Protocol/Dtos.cs b/src/Chronos.Protocol/Dtos.cs
index 45d59111..c53de5ed 100644
--- a/src/Chronos.Protocol/Dtos.cs
+++ b/src/Chronos.Protocol/Dtos.cs
@@ -9,6 +9,10 @@ public sealed record ApiError(string Code, string Message, string? Details = nul
public sealed record ServerLimits(long MaxUploadBytes, int ChunkSizeBytes, int PasswordMinLength = 10);
/// GET /api/v1/server/info.
+///
+/// File extensions the archive files as photos (lower case, no dot): the admin panel's upload dialog offers and sends only
+/// these (owner review 2, R3). Null from servers that do not announce them.
+///
public sealed record ServerInfo(
string Name,
string Version,
@@ -16,7 +20,8 @@ public sealed record ServerInfo(
IReadOnlyList Capabilities,
string? TlsFingerprint,
IReadOnlyList Formats,
- ServerLimits Limits);
+ ServerLimits Limits,
+ IReadOnlyList? Extensions = null);
/// GET /health.
public sealed record HealthStatus(string Status, string Version, IReadOnlyDictionary Checks);
diff --git a/src/Chronos.Server/Admin/web/admin.css b/src/Chronos.Server/Admin/web/admin.css
index 3cfe4e52..e23338a1 100644
--- a/src/Chronos.Server/Admin/web/admin.css
+++ b/src/Chronos.Server/Admin/web/admin.css
@@ -404,6 +404,24 @@ dialog.viewer .buttons { grid-column: 1 / -1; }
.seq-card[aria-selected="true"], .frame[aria-selected="true"], .seq-row[aria-selected="true"] { outline: 3px solid Highlight; }
}
+/* Upload dialog (owner review 2, R3, upload.js): the target, a drop zone, the photos with their state, the total. */
+dialog.dialog.upload { width: 640px; }
+.upload-choice { border: 0; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 8px 20px; }
+.upload-choice legend { color: var(--text-muted); padding: 0; margin-block-end: 8px; }
+.upload-existing { display: grid; gap: 8px; margin-block-start: 10px; }
+.upload-new { display: grid; gap: 6px; margin-block-start: 10px; color: var(--text-muted); }
+.input.list { height: auto; padding: 4px 0; }
+.input.list option { padding: 3px 10px; }
+.drop { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; padding: 14px; border: 1px dashed var(--stroke-strong); border-radius: var(--radius-card); color: var(--text-muted); }
+dialog.upload.dragging .drop { border-color: var(--accent); background: var(--accent-selected); color: var(--text); }
+.upload-files { list-style: none; margin: 0; padding: 0; max-height: 40vh; overflow-y: auto; display: grid; grid-template-columns: minmax(0, 1fr) max-content minmax(110px, 170px) 28px; column-gap: 12px; align-content: start; }
+.upload-file { grid-column: 1 / -1; display: grid; grid-template-columns: subgrid; align-items: center; min-height: 36px; border-bottom: 1px solid var(--stroke); }
+.upload-file .status { display: flex; align-items: center; gap: 8px; min-width: 0; font-size: 12px; }
+.upload-file .status svg.bar { flex: 1 1 0; min-width: 24px; }
+.upload-file .btn.icon.small { width: 28px; min-width: 28px; }
+.upload-total { display: flex; align-items: center; gap: 12px; font-size: 12px; }
+.upload-total .progress-cell { flex: 1 1 0; }
+
/* About: the last group of Settings (owner review 2); #/about scrolls to it below the sticky header and focuses its heading. */
.about { scroll-margin-block-start: 84px; }
.about h2:focus { outline: none; }
diff --git a/src/Chronos.Server/Admin/web/api.js b/src/Chronos.Server/Admin/web/api.js
index 1a72f455..de496323 100644
--- a/src/Chronos.Server/Admin/web/api.js
+++ b/src/Chronos.Server/Admin/web/api.js
@@ -18,19 +18,18 @@ function csrfToken() {
}
/**
- * One API call. The body is JSON (any value), raw bytes (a Blob, sent as application/octet-stream) or nothing. A call
- * aborted through signal rejects with the browser's AbortError, which callers tell apart from an ApiFailure.
+ * One API call: a JSON body, or with raw the bytes of a Blob (upload chunks, sent as octet-stream). An abort through
+ * signal rejects with the browser's AbortError; any other failure to reach the server with ApiFailure status 0.
*/
-async function request(method, url, body, signal) {
+async function request(method, url, body, { raw = false, signal } = {}) {
const headers = { Accept: "application/json", "Accept-Language": culture() };
- const raw = body instanceof Blob;
if (body !== undefined) headers["Content-Type"] = raw ? "application/octet-stream" : "application/json";
if (method !== "GET") headers["X-CSRF-Token"] = csrfToken();
let res;
try {
res = await fetch(url, { method, headers, credentials: "same-origin", signal, body: body === undefined ? undefined : raw ? body : JSON.stringify(body) });
} catch (err) {
- if (err?.name === "AbortError") throw err;
+ if (signal?.aborted) throw err;
throw new ApiFailure(0, "unreachable", "");
}
if (res.status === 401 && url !== "/api/v1/auth/login") {
@@ -55,8 +54,8 @@ export const api = {
put: (url, body) => request("PUT", url, body),
patch: (url, body) => request("PATCH", url, body),
del: (url) => request("DELETE", url),
- /** PUT of raw bytes (an upload chunk) with the session's CSRF header, like every other call; abortable through signal. */
- putBytes: (url, blob, signal) => request("PUT", url, blob, signal),
+ /** PUT of a Blob's bytes (an upload chunk) with the session's headers: the parsed JSON answer; failures as the calls above. */
+ putBytes: (url, blob, signal) => request("PUT", url, blob, { raw: true, signal }),
user: () => currentUser,
/** Restores the session from the cookie; null when signed out. */
diff --git a/src/Chronos.Server/Admin/web/hash-worker.js b/src/Chronos.Server/Admin/web/hash-worker.js
new file mode 100644
index 00000000..390a7c0a
--- /dev/null
+++ b/src/Chronos.Server/Admin/web/hash-worker.js
@@ -0,0 +1,42 @@
+// Module worker of the upload dialog (owner review 2, R3): hashes a picked photo off the page's thread, reading it in
+// 8 MiB blocks so a large RAW never sits in memory whole. Before its first hash it runs the SHA-256 self-test and, if
+// any check fails, refuses every request (fail closed): the dialog then uploads nothing.
+//
+// Messages in: { id, file } a File or Blob to hash; requests are answered one after the other
+// Messages out: { id, type: "progress", done, total }
+// { id, type: "done", sha256 } lower-case hex
+// { id, type: "error", reason: "self_test" | "read", detail }
+import { Sha256, toHex, selfTest } from "./sha256.js";
+
+const BLOCK = 8 * 1024 * 1024;
+let verdict = null;
+let queue = Promise.resolve();
+
+self.addEventListener("message", (e) => {
+ const { id, file } = e.data ?? {};
+ queue = queue.then(() => hash(id, file));
+});
+
+async function hash(id, file) {
+ try {
+ verdict ??= selfTest().catch(() => "self_test_error");
+ const failed = await verdict;
+ if (failed) {
+ self.postMessage({ id, type: "error", reason: "self_test", detail: failed });
+ return;
+ }
+ const sha = new Sha256();
+ const total = file.size;
+ for (let done = 0; done < total;) {
+ const bytes = new Uint8Array(await file.slice(done, Math.min(done + BLOCK, total)).arrayBuffer());
+ // A file that shrank while it was read must not end with a digest of part of it.
+ if (bytes.length === 0) throw new Error("short read");
+ sha.update(bytes);
+ done += bytes.length;
+ self.postMessage({ id, type: "progress", done, total });
+ }
+ self.postMessage({ id, type: "done", sha256: toHex(sha.digest()) });
+ } catch (err) {
+ self.postMessage({ id, type: "error", reason: "read", detail: String(err?.name ?? err) });
+ }
+}
diff --git a/src/Chronos.Server/Admin/web/sha256.js b/src/Chronos.Server/Admin/web/sha256.js
new file mode 100644
index 00000000..fa0f77ba
--- /dev/null
+++ b/src/Chronos.Server/Admin/web/sha256.js
@@ -0,0 +1,185 @@
+// Incremental SHA-256 (FIPS 180-4) for the upload dialog (owner review 2, R3): photos are hashed while they are read in
+// blocks, which crypto.subtle cannot do (it digests one buffer). In-house like everything else; the hash worker checks it
+// against known answers and crypto.subtle before using it (selfTest), and the server verifies every upload again.
+
+const K = new Int32Array([
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
+]);
+
+const INITIAL = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];
+
+/** Hashes the whole 64-byte blocks of bytes[pos, end) into state h; returns where the first unprocessed byte is. */
+function blocks(h, w, bytes, pos, end) {
+ let h0 = h[0], h1 = h[1], h2 = h[2], h3 = h[3], h4 = h[4], h5 = h[5], h6 = h[6], h7 = h[7];
+ while (end - pos >= 64) {
+ for (let i = 0; i < 16; i++, pos += 4) w[i] = (bytes[pos] << 24) | (bytes[pos + 1] << 16) | (bytes[pos + 2] << 8) | bytes[pos + 3];
+ for (let i = 16; i < 64; i++) {
+ const x = w[i - 15];
+ const y = w[i - 2];
+ const s0 = ((x >>> 7) | (x << 25)) ^ ((x >>> 18) | (x << 14)) ^ (x >>> 3);
+ const s1 = ((y >>> 17) | (y << 15)) ^ ((y >>> 19) | (y << 13)) ^ (y >>> 10);
+ w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0;
+ }
+ let a = h0, b = h1, c = h2, d = h3, e = h4, f = h5, g = h6, k = h7;
+ for (let i = 0; i < 64; i++) {
+ const s1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7));
+ const t1 = (k + s1 + ((e & f) ^ (~e & g)) + K[i] + w[i]) | 0;
+ const s0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10));
+ const t2 = (s0 + ((a & b) ^ (a & c) ^ (b & c))) | 0;
+ k = g;
+ g = f;
+ f = e;
+ e = (d + t1) | 0;
+ d = c;
+ c = b;
+ b = a;
+ a = (t1 + t2) | 0;
+ }
+ h0 = (h0 + a) | 0;
+ h1 = (h1 + b) | 0;
+ h2 = (h2 + c) | 0;
+ h3 = (h3 + d) | 0;
+ h4 = (h4 + e) | 0;
+ h5 = (h5 + f) | 0;
+ h6 = (h6 + g) | 0;
+ h7 = (h7 + k) | 0;
+ }
+ h[0] = h0; h[1] = h1; h[2] = h2; h[3] = h3; h[4] = h4; h[5] = h5; h[6] = h6; h[7] = h7;
+ return pos;
+}
+
+function asBytes(data) {
+ if (data instanceof Uint8Array) return data;
+ if (data instanceof ArrayBuffer) return new Uint8Array(data);
+ if (ArrayBuffer.isView(data)) return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
+ throw new TypeError("SHA-256 hashes bytes");
+}
+
+/** SHA-256 fed in pieces of any size: update(bytes) as often as needed, then digest() once. */
+export class Sha256 {
+ constructor() {
+ this.h = new Int32Array(INITIAL);
+ this.w = new Int32Array(64);
+ this.buffer = new Uint8Array(64);
+ this.buffered = 0;
+ this.length = 0;
+ this.finished = false;
+ }
+
+ /** Adds bytes (Uint8Array, another typed array or an ArrayBuffer) to the message. */
+ update(data) {
+ if (this.finished) throw new Error("SHA-256 already digested");
+ const bytes = asBytes(data);
+ this.length += bytes.length;
+ let pos = 0;
+ if (this.buffered > 0) {
+ const take = Math.min(64 - this.buffered, bytes.length);
+ this.buffer.set(bytes.subarray(0, take), this.buffered);
+ this.buffered += take;
+ pos = take;
+ if (this.buffered < 64) return this;
+ blocks(this.h, this.w, this.buffer, 0, 64);
+ this.buffered = 0;
+ }
+ pos = blocks(this.h, this.w, bytes, pos, bytes.length);
+ if (pos < bytes.length) {
+ this.buffer.set(bytes.subarray(pos), 0);
+ this.buffered = bytes.length - pos;
+ }
+ return this;
+ }
+
+ /** The 32-byte digest; the hash takes no more input afterwards. */
+ digest() {
+ if (this.finished) throw new Error("SHA-256 already digested");
+ this.finished = true;
+ const tail = new Uint8Array(this.buffered < 56 ? 64 : 128);
+ tail.set(this.buffer.subarray(0, this.buffered));
+ tail[this.buffered] = 0x80;
+ // The message length in bits as a 64-bit big-endian number, split without losing precision above 2^32.
+ const high = Math.floor(this.length / 0x20000000);
+ const low = (this.length % 0x20000000) * 8;
+ const view = new DataView(tail.buffer);
+ view.setUint32(tail.length - 8, high);
+ view.setUint32(tail.length - 4, low);
+ blocks(this.h, this.w, tail, 0, tail.length);
+ const out = new Uint8Array(32);
+ const result = new DataView(out.buffer);
+ for (let i = 0; i < 8; i++) result.setUint32(i * 4, this.h[i] >>> 0);
+ return out;
+ }
+}
+
+/** Lower-case hexadecimal, as the upload API takes a SHA-256. */
+export function toHex(bytes) {
+ let hex = "";
+ for (const b of bytes) hex += (b < 16 ? "0" : "") + b.toString(16);
+ return hex;
+}
+
+/** The hex SHA-256 of one buffer. */
+export function sha256Hex(data) {
+ return toHex(new Sha256().update(data).digest());
+}
+
+const ascii = (text) => new TextEncoder().encode(text);
+
+/** FIPS 180-4 examples (and the NIST long-message test): message and expected digest. */
+const KNOWN_ANSWERS = [
+ ["", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"],
+ ["abc", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"],
+ ["abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"],
+ [
+ "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
+ "cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1",
+ ],
+];
+const MILLION_A = "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0";
+
+/** Feeds bytes in pieces of uneven sizes, so the partial-block buffer is exercised at every offset. */
+function piecewise(bytes) {
+ const hash = new Sha256();
+ const sizes = [1, 63, 64, 65, 0, 127, 128, 129, 1000, 4096, 55, 56, 57];
+ let pos = 0;
+ for (let i = 0; pos < bytes.length; i++) {
+ const size = Math.min(sizes[i % sizes.length], bytes.length - pos);
+ hash.update(bytes.subarray(pos, pos + size));
+ pos += size;
+ }
+ return toHex(hash.digest());
+}
+
+/**
+ * Runs the known-answer tests (whole and piece by piece) and, where crypto.subtle exists (secure pages), compares a 1 MiB
+ * random buffer with it. Resolves to null when every check passes, else to the name of the first one that failed: the
+ * caller refuses to hash then (fail closed).
+ */
+export async function selfTest() {
+ for (const [message, expected] of KNOWN_ANSWERS) {
+ const bytes = ascii(message);
+ if (sha256Hex(bytes) !== expected || piecewise(bytes) !== expected) return `kat:${message.length}`;
+ }
+ const million = new Uint8Array(1_000_000).fill(0x61);
+ if (sha256Hex(million) !== MILLION_A || piecewise(million) !== MILLION_A) return "kat:million";
+ const subtle = globalThis.crypto?.subtle;
+ if (subtle) {
+ const random = new Uint8Array(1 << 20);
+ // getRandomValues fills at most 64 KiB per call.
+ for (let pos = 0; pos < random.length; pos += 65536) globalThis.crypto.getRandomValues(random.subarray(pos, pos + 65536));
+ let reference;
+ try {
+ reference = toHex(new Uint8Array(await subtle.digest("SHA-256", random)));
+ } catch {
+ reference = null;
+ }
+ if (reference !== null && (sha256Hex(random) !== reference || piecewise(random) !== reference)) return "subtle";
+ }
+ return null;
+}
diff --git a/src/Chronos.Server/Admin/web/upload.js b/src/Chronos.Server/Admin/web/upload.js
new file mode 100644
index 00000000..7e78d045
--- /dev/null
+++ b/src/Chronos.Server/Admin/web/upload.js
@@ -0,0 +1,693 @@
+// Upload dialog of the admin panel (owner review 2, R3; BRIEF §14.4, §14.8): photos from this computer into an existing
+// or a new sequence, chosen with the file picker or dropped on the dialog. Folders are not taken: importing a whole folder
+// stays a feature of the desktop app. Each photo is hashed in a module worker (hash-worker.js, which self-tests its
+// SHA-256 first and refuses to hash when a check fails), started, sent in the chunks the server does not have yet and
+// completed; the server verifies the hash again before it files the photo.
+import { ApiFailure } from "./api.js";
+import { t, plural, applyStrings, culture } from "./i18n.js";
+import { escapeHtml, attr, bar, formatBytes, formatNumber, errorText } from "./ui.js";
+import { icons } from "./icons.js";
+
+/** Photos sent at once, and chunks in flight for each: four requests, half of what the server takes from one account. */
+const FILES_AT_ONCE = 2;
+const CHUNKS_AT_ONCE = 2;
+/** Retries of a call that failed for a passing reason (no answer, 429, 503), after 1, 2 and 4 seconds. */
+const RETRIES = 3;
+const SEARCH_DELAY = 250;
+const LIST_LIMIT = 50;
+/** States of a photo already on the server: a later run leaves it alone. */
+const FINISHED = new Set(["done", "exists", "deleted"]);
+/** States of a photo a run is sending. */
+const ACTIVE = new Set(["hashing", "starting", "uploading", "verifying"]);
+
+/** A failure of the hash worker: kind self_test (its SHA-256 failed a check), worker (it did not run), read or stopped. */
+class HashError extends Error {
+ constructor(kind, detail = "") {
+ super(`${kind} ${detail}`.trim());
+ this.kind = kind;
+ }
+}
+
+let dialogs = 0;
+
+/**
+ * Opens the upload dialog. With sequence ({ id, title } or a SequenceDto) the photos go into it; without, the dialog
+ * lets the user pick an existing sequence or name a new one. onDone() runs after every run that changed the library
+ * (photos uploaded or a sequence created), so the page can refresh. Resolves when the dialog closes.
+ */
+export function openUpload({ api, sequence, onDone } = {}) {
+ return new Promise((resolve) => {
+ const id = `upload-${++dialogs}`;
+ let target = sequence?.id ? { id: sequence.id, title: sequence.displayTitle ?? sequence.title ?? "" } : null;
+ let extensions = null;
+ let maxBytes = 0;
+ let running = false;
+ let controller = null;
+ let broken = null;
+ let hasher = null;
+ let searchTimer = null;
+ let searchToken = 0;
+ let frame = 0;
+ const items = [];
+ const skipped = { folders: 0, formats: 0, size: 0 };
+ const titles = new Map();
+
+ const dialog = document.createElement("dialog");
+ dialog.className = "dialog upload";
+ dialog.setAttribute("aria-labelledby", `${id}-title`);
+ dialog.innerHTML = `
+ `;
+ document.body.appendChild(dialog);
+ applyStrings(dialog);
+ const form = dialog.querySelector("form");
+ const targetHost = dialog.querySelector(`#${id}-target`);
+ const input = dialog.querySelector('input[type="file"]');
+ const addButton = dialog.querySelector('[data-act="add"]');
+ const closeButton = dialog.querySelector('[data-act="close"]');
+ const startButton = dialog.querySelector('[data-act="start"]');
+ const notes = dialog.querySelector(".upload-notes");
+ const list = dialog.querySelector(".upload-files");
+ const total = dialog.querySelector(".upload-total");
+ const errorLine = dialog.querySelector(".error");
+
+ drawTarget();
+ drawButtons();
+
+ addButton.addEventListener("click", () => input.click());
+ input.addEventListener("change", () => {
+ take([...input.files], 0);
+ input.value = "";
+ });
+ form.addEventListener("submit", (e) => {
+ e.preventDefault();
+ run();
+ });
+ closeButton.addEventListener("click", () => {
+ if (running) cancel();
+ else dialog.close();
+ });
+ list.addEventListener("click", (e) => {
+ const button = e.target.closest('[data-act="remove"]');
+ if (!button || running) return;
+ const index = items.findIndex((i) => i.key === button.closest("[data-key]").dataset.key);
+ if (index < 0) return;
+ const [item] = items.splice(index, 1);
+ const next = item.row.nextElementSibling ?? item.row.previousElementSibling;
+ item.row.remove();
+ (next?.querySelector('[data-act="remove"]:not([hidden])') ?? addButton).focus();
+ drawList();
+ });
+
+ // Drops: photos are taken, folders only counted (BRIEF §14.8: no folder upload on the web).
+ const hasFiles = (e) => [...(e.dataTransfer?.types ?? [])].includes("Files");
+ dialog.addEventListener("dragover", (e) => {
+ if (!hasFiles(e)) return;
+ e.preventDefault();
+ e.dataTransfer.dropEffect = running || extensions === null ? "none" : "copy";
+ dialog.classList.add("dragging");
+ });
+ dialog.addEventListener("dragleave", (e) => {
+ if (!dialog.contains(e.relatedTarget)) dialog.classList.remove("dragging");
+ });
+ dialog.addEventListener("drop", (e) => {
+ if (!hasFiles(e)) return;
+ e.preventDefault();
+ dialog.classList.remove("dragging");
+ if (running || extensions === null) return;
+ const { files, folders } = dropped(e.dataTransfer);
+ take(files, folders);
+ });
+
+ // Esc closes only while nothing is being sent; Cancel stops a run.
+ dialog.addEventListener("cancel", (e) => {
+ if (running) e.preventDefault();
+ });
+ // Leaving the page while photos are sent asks first (returnValue for browsers before preventDefault counted).
+ const guard = (e) => {
+ e.preventDefault();
+ e.returnValue = true;
+ };
+ const signedOut = () => {
+ controller?.abort();
+ dialog.close();
+ };
+ window.addEventListener("chronos:signed-out", signedOut);
+ dialog.addEventListener("close", () => {
+ controller?.abort();
+ hasher?.stop();
+ clearTimeout(searchTimer);
+ cancelAnimationFrame(frame);
+ window.removeEventListener("beforeunload", guard);
+ window.removeEventListener("chronos:signed-out", signedOut);
+ dialog.remove();
+ resolve();
+ });
+ dialog.showModal();
+ targetHost.querySelector('input[type="search"]')?.focus();
+ const firstFocus = document.activeElement;
+
+ // The photo extensions and the size limit the server announces: only those are offered and sent.
+ api.get("/api/v1/server/info").then((info) => {
+ extensions = new Set((info?.extensions ?? []).map((e) => String(e).toLowerCase()));
+ maxBytes = info?.limits?.maxUploadBytes ?? 0;
+ input.accept = [...extensions].map((e) => `.${e}`).join(",");
+ drawButtons();
+ // Into a given sequence the first step is adding photos, once the button can be used.
+ if (target && document.activeElement === firstFocus) addButton.focus();
+ }).catch((err) => showError(errorText(err)));
+
+ /** The target: fixed (given, or chosen when the first run started), else the choice of an existing or a new sequence. */
+ function drawTarget() {
+ if (target) {
+ targetHost.innerHTML = `