Skip to main content

syncular_command/
lib.rs

1//! # syncular-command — one JSON command surface over the Rust client core
2//!
3//! The command router the conformance shim proved (JSON in, JSON out, bytes
4//! as `{"$bytes": hex}`) factored into a transport-agnostic module so BOTH
5//! the stdio conformance shim AND the FFI native core dispatch through the
6//! same code. That keeps a single command surface, conformance-locked via
7//! the shim: whatever the shim exercises, the FFI core inherits.
8//!
9//! The router is generic over the `Transport` seam. The shim binds it to a
10//! stdio host (transport inverted to the harness); the FFI crate binds it to
11//! a real native HTTP+WS transport. Everything host-specific — realtime
12//! notification draining, deferred requests, event queues — stays in each
13//! host; only the pure `method → result` dispatch (and its JSON parsing) is
14//! shared here.
15
16use serde_json::{json, Value};
17use ssp2::segment::{decode_rows_segment, encode_rows_segment};
18use ssp2::{
19    decode_message, encode_message, parse_control, render_message, render_rows_segment,
20    ControlMessage,
21};
22use syncular_client::{
23    ClientDiagnosticsRequest, ClientLimits, CommandEffects, CommitOutcomeQuery,
24    LocalDataPurgeInput, LocalDataRebootstrapInput, Mutation, ResolveCommitOutcomeInput,
25    SyncClient, Transport, WindowBase, WindowCoverage,
26};
27
28// -- bytes <-> {"$bytes": hex} (the driver-protocol byte envelope) ----------
29
30pub fn bytes_to_hex(bytes: &[u8]) -> String {
31    syncular_client::values::bytes_to_hex(bytes)
32}
33
34pub fn hex_to_bytes(hex: &str) -> Result<Vec<u8>, String> {
35    syncular_client::values::hex_to_bytes(hex)
36}
37
38pub fn bytes_value(bytes: &[u8]) -> Value {
39    json!({ "$bytes": bytes_to_hex(bytes) })
40}
41
42pub fn value_bytes(value: Option<&Value>) -> Result<Vec<u8>, String> {
43    let hex = value
44        .and_then(|v| v.get("$bytes"))
45        .and_then(Value::as_str)
46        .ok_or_else(|| "expected a {\"$bytes\": hex} value".to_owned())?;
47    hex_to_bytes(hex)
48}
49
50/// The `(code, message)` pair the driver protocol carries in an `error`.
51pub type CommandError = (String, String);
52
53/// Parsed side effects of a `create` command that the host must apply to its
54/// own transport/clock (the router stays transport-agnostic). The client is
55/// already installed into the `Option<SyncClient>` slot by `dispatch`.
56#[derive(Debug, Default, Clone)]
57pub struct CreateEffects {
58    /// §5.4 capability the harness/host announced for its endpoints — the
59    /// host sets its transport's `supports_url_fetch` accordingly.
60    pub signed_urls: bool,
61    /// True while a security preflight is pending: a preflighted client was
62    /// installed (or entered preflight, or was shut down mid-preflight) and
63    /// `activateSecurity` has yet to complete. `dispatch` maintains this so a
64    /// replacement `create` without the `securityPreflight` flag is refused
65    /// across `shutdown`, where the client slot is empty, on a host that reuses
66    /// one `CreateEffects` across creates (the Tauri plugin, the conformance
67    /// shim, the bench harness).
68    ///
69    /// A host that allocates a fresh `CreateEffects` per create — the React
70    /// Native native module rebuilds its FFI handle on every `create` — starts
71    /// each create with this flag clear. For those hosts the persisted marker
72    /// in the client core carries the gate: a file-backed replica reopens in
73    /// preflight, and the `create` path refuses a plain re-create against it.
74    /// This in-memory flag covers the same-handle case where no file persists
75    /// the marker.
76    pub security_preflight_pending: bool,
77}
78
79fn client_err(message: String) -> CommandError {
80    let code = message
81        .split_once(':')
82        .map(|(candidate, _)| candidate)
83        .filter(|candidate| candidate.starts_with("client.") || candidate.starts_with("sync."))
84        .unwrap_or("client.failed");
85    (code.to_owned(), message)
86}
87
88fn need_client(client: &mut Option<SyncClient>) -> Result<&mut SyncClient, CommandError> {
89    client
90        .as_mut()
91        .ok_or_else(|| client_err("no client instance created".to_owned()))
92}
93
94pub fn parse_limits(value: Option<&Value>) -> ClientLimits {
95    let mut limits = ClientLimits::default();
96    let Some(object) = value.and_then(Value::as_object) else {
97        return limits;
98    };
99    limits.limit_commits = object
100        .get("limitCommits")
101        .and_then(Value::as_i64)
102        .map(|v| v as i32);
103    limits.limit_snapshot_rows = object
104        .get("limitSnapshotRows")
105        .and_then(Value::as_i64)
106        .map(|v| v as i32);
107    limits.max_snapshot_pages = object
108        .get("maxSnapshotPages")
109        .and_then(Value::as_i64)
110        .map(|v| v as i32);
111    limits.accept = object
112        .get("accept")
113        .and_then(Value::as_u64)
114        .map(|v| v as u8);
115    limits.blob_cache_max_bytes = object.get("blobCacheMaxBytes").and_then(Value::as_i64);
116    limits.outcome_retention_max_entries = object
117        .get("outcomeRetentionMaxEntries")
118        .and_then(Value::as_u64)
119        .map(|value| value as usize);
120    limits
121}
122
123/// §5.11: parse the `encryption` config into the client's portable keyring.
124/// Shape: `{ keys: { "<keyId>": {"$bytes": "<hex>"} },
125/// keyIdColumns: { "<table>": "<column>" } }`. Keys are 32 bytes.
126pub fn parse_encryption(
127    value: &Value,
128) -> Result<syncular_client::values::EncryptionConfig, String> {
129    let mut config = syncular_client::values::EncryptionConfig::default();
130    let Some(keys) = value.get("keys").and_then(Value::as_object) else {
131        return Ok(config);
132    };
133    for (key_id, key_val) in keys {
134        let bytes =
135            value_bytes(Some(key_val)).map_err(|e| format!("encryption key {key_id:?}: {e}"))?;
136        if bytes.len() != 32 {
137            return Err(format!(
138                "encryption key {key_id:?} must be 32 bytes, got {}",
139                bytes.len()
140            ));
141        }
142        config.keys.insert(key_id.clone(), bytes);
143    }
144    if let Some(columns) = value.get("keyIdColumns") {
145        let columns = columns
146            .as_object()
147            .ok_or_else(|| "encryption keyIdColumns must be an object".to_owned())?;
148        for (table, column) in columns {
149            let column = column.as_str().ok_or_else(|| {
150                format!("encryption keyIdColumns entry for {table:?} must be a string")
151            })?;
152            if column.is_empty() {
153                return Err(format!(
154                    "encryption keyIdColumns entry for {table:?} must not be empty"
155                ));
156            }
157            config
158                .key_id_columns
159                .insert(table.clone(), column.to_owned());
160        }
161    }
162    Ok(config)
163}
164
165/// Parse an `activateSecurity` (or rotation) `headers` param: an object of
166/// string values, replacing the transport's FULL header set.
167/// The router validates the shape at the shared chokepoint; each host applies
168/// the parsed set to its own transport (the router stays transport-agnostic).
169pub fn parse_headers(value: &Value) -> Result<Vec<(String, String)>, String> {
170    let object = value.as_object().ok_or_else(|| {
171        "sync.invalid_request: headers must be an object of string values".to_owned()
172    })?;
173    let mut headers = Vec::with_capacity(object.len());
174    for (name, value) in object {
175        let value = value
176            .as_str()
177            .ok_or_else(|| format!("sync.invalid_request: header {name:?} must be a string"))?;
178        headers.push((name.clone(), value.to_owned()));
179    }
180    Ok(headers)
181}
182
183pub fn parse_mutations(value: Option<&Value>) -> Result<Vec<Mutation>, String> {
184    let list = value
185        .and_then(Value::as_array)
186        .ok_or_else(|| "mutations must be a list".to_owned())?;
187    let mut out = Vec::with_capacity(list.len());
188    for entry in list {
189        let op = entry
190            .get("op")
191            .and_then(Value::as_str)
192            .ok_or_else(|| "mutation missing op".to_owned())?;
193        let table = entry
194            .get("table")
195            .and_then(Value::as_str)
196            .ok_or_else(|| "mutation missing table".to_owned())?
197            .to_owned();
198        let base_version = entry.get("baseVersion").and_then(Value::as_i64);
199        match op {
200            "upsert" => {
201                let mut values = entry
202                    .get("values")
203                    .and_then(Value::as_object)
204                    .cloned()
205                    .ok_or_else(|| "upsert missing values".to_owned())?;
206                decode_bigint_members(&mut values)?;
207                out.push(Mutation::Upsert {
208                    table,
209                    values,
210                    base_version,
211                });
212            }
213            "delete" => {
214                let row_id = entry
215                    .get("rowId")
216                    .and_then(Value::as_str)
217                    .ok_or_else(|| "delete missing rowId".to_owned())?
218                    .to_owned();
219                out.push(Mutation::Delete {
220                    table,
221                    row_id,
222                    base_version,
223                });
224            }
225            other => return Err(format!("unknown mutation op {other:?}")),
226        }
227    }
228    Ok(out)
229}
230
231fn decode_bigint_members(values: &mut serde_json::Map<String, Value>) -> Result<(), String> {
232    for value in values.values_mut() {
233        let Some(decimal) = value.get("$bigint").and_then(Value::as_str) else {
234            continue;
235        };
236        let integer = decimal
237            .parse::<i64>()
238            .map_err(|_| format!("bigint value {decimal:?} is outside SQLite's i64 range"))?;
239        *value = Value::from(integer);
240    }
241    Ok(())
242}
243
244fn scopes_from_params(value: Option<&Value>) -> Result<Vec<(String, Vec<String>)>, String> {
245    match value {
246        Some(v) => syncular_client::values::json_to_scope_map(v),
247        None => Ok(Vec::new()),
248    }
249}
250
251/// §4.8: parse a window base descriptor `{ table, variable, fixedScopes?,
252/// params? }` from a command's `base` param.
253fn window_base_from_params(value: Option<&Value>) -> Result<WindowBase, String> {
254    let object = value
255        .and_then(Value::as_object)
256        .ok_or_else(|| "setWindow/windowState missing base object".to_owned())?;
257    let table = object
258        .get("table")
259        .and_then(Value::as_str)
260        .ok_or_else(|| "window base missing table".to_owned())?
261        .to_owned();
262    let variable = object
263        .get("variable")
264        .and_then(Value::as_str)
265        .ok_or_else(|| "window base missing variable".to_owned())?
266        .to_owned();
267    let fixed_scopes = scopes_from_params(object.get("fixedScopes"))?;
268    let params = object
269        .get("params")
270        .and_then(Value::as_str)
271        .map(str::to_owned);
272    Ok(WindowBase {
273        table,
274        variable,
275        fixed_scopes,
276        params,
277    })
278}
279
280/// §5.10.5: parse the common `(table, rowId, column, name)` target of a crdt
281/// command. `name` selects the shared type inside the doc (default `"text"`,
282/// matching the TS `YjsColumn.text()` default).
283#[cfg(feature = "crdt-yjs")]
284fn crdt_target(params: &Value) -> Result<(String, String, String, String), CommandError> {
285    let table = params
286        .get("table")
287        .and_then(Value::as_str)
288        .ok_or_else(|| client_err("crdt command missing table".to_owned()))?
289        .to_owned();
290    let row_id = params
291        .get("rowId")
292        .and_then(Value::as_str)
293        .ok_or_else(|| client_err("crdt command missing rowId".to_owned()))?
294        .to_owned();
295    let column = params
296        .get("column")
297        .and_then(Value::as_str)
298        .ok_or_else(|| client_err("crdt command missing column".to_owned()))?
299        .to_owned();
300    let name = params
301        .get("name")
302        .and_then(Value::as_str)
303        .unwrap_or("text")
304        .to_owned();
305    Ok((table, row_id, column, name))
306}
307
308/// Dispatch one command against the client instance over `transport`.
309///
310/// The `create` command installs a fresh `SyncClient` into `client` and
311/// returns its parsed `CreateEffects` in the `Ok` result via `effects`; every
312/// other command mutates the existing instance. Errors come back as the
313/// driver-protocol `(code, message)` pair.
314///
315/// Generic over `T: Transport` so the shim (host-inverted transport) and the
316/// FFI core (native HTTP+WS transport) share this exact router.
317pub fn dispatch<T: Transport>(
318    transport: &mut T,
319    client: &mut Option<SyncClient>,
320    effects: &mut CreateEffects,
321    method: &str,
322    params: &Value,
323) -> Result<Value, CommandError> {
324    if method == "create" {
325        // Fail-closed against a compromised webview re-issuing `create` (or
326        // `shutdown` + `create`) WITHOUT the securityPreflight flag to exit
327        // the gate: while a preflight is pending — on the live client, or
328        // carried in `effects` across a `shutdown` — a replacement create must
329        // itself request securityPreflight; the gate opens only through
330        // activateSecurity.
331        let requests_preflight = params
332            .get("securityPreflight")
333            .and_then(Value::as_bool)
334            .unwrap_or(false);
335        let preflight_engaged = client.as_ref().map_or(
336            effects.security_preflight_pending,
337            SyncClient::security_preflight,
338        );
339        if preflight_engaged && !requests_preflight {
340            return Err((
341                syncular_client::SECURITY_PREFLIGHT_REQUIRED_CODE.to_owned(),
342                "the local replica is in security preflight; a replacement create must itself request securityPreflight, and protected data opens only after activateSecurity".to_owned(),
343            ));
344        }
345    } else {
346        let allowed_during_preflight = matches!(
347            method,
348            "securityLifecycle"
349                | "beginSecurityPreflight"
350                | "activateSecurity"
351                | "purgeLocalData"
352                | "localRevision"
353                | "statusSnapshot"
354                | "shutdown"
355        );
356        if client
357            .as_ref()
358            .is_some_and(|running| running.security_preflight())
359            && !allowed_during_preflight
360        {
361            return Err((
362                syncular_client::SECURITY_PREFLIGHT_REQUIRED_CODE.to_owned(),
363                "the local replica is in security preflight; complete quarantine checks and call activateSecurity before accessing protected data".to_owned(),
364            ));
365        }
366    }
367    match method {
368        "create" => {
369            let client_id = params
370                .get("clientId")
371                .and_then(Value::as_str)
372                .map(str::to_owned);
373            let schema = params
374                .get("schema")
375                .ok_or_else(|| client_err("create missing schema".to_owned()))?;
376            let limits = parse_limits(params.get("limits"));
377            // §native: a `dbPath` installs a file-backed rusqlite connection so
378            // native hosts (Tauri plugin, FFI file variant) persist across
379            // restarts; absent it, the default in-memory core (the shim's mode).
380            let mut instance = match params.get("dbPath").and_then(Value::as_str) {
381                Some(path) => SyncClient::open_path_with_identity(client_id, schema, limits, path)
382                    .map_err(client_err)?,
383                None => {
384                    SyncClient::new_with_identity(client_id, schema, limits).map_err(client_err)?
385                }
386            };
387            // Harness clock pin (§5.4 expiry runs on the virtual clock).
388            if let Some(now_ms) = params.get("nowMs").and_then(Value::as_i64) {
389                instance.set_now_ms(now_ms);
390            }
391            // §5.4 capability of the host endpoint set (accept bit 3) — the
392            // host applies it to its own transport.
393            effects.signed_urls = params
394                .get("signedUrls")
395                .and_then(Value::as_bool)
396                .unwrap_or(false);
397            // §5.11: install client-side encryption keys. Shape:
398            // { encryption: { keys: { "<keyId>": {"$bytes": "<hex>"} },
399            //                 keyIdColumns: { "<table>": "<column>" } } }.
400            let security_preflight = params
401                .get("securityPreflight")
402                .and_then(Value::as_bool)
403                .unwrap_or(false);
404            // A file-backed replica reopens in preflight when its persisted
405            // quarantine marker is set (client core restores it). Refuse a plain
406            // re-create so a rebuilt host handle — the React Native native module
407            // tears its FFI handle down on every create — cannot downgrade a
408            // quarantined replica to active. A create that itself requests
409            // securityPreflight, or an activated replica whose marker cleared,
410            // proceeds.
411            if instance.security_preflight() && !security_preflight {
412                return Err((
413                    syncular_client::SECURITY_PREFLIGHT_REQUIRED_CODE.to_owned(),
414                    "the local replica is in security preflight; a replacement create must itself request securityPreflight, and protected data opens only after activateSecurity".to_owned(),
415                ));
416            }
417            if security_preflight && params.get("encryption").is_some() {
418                return Err(client_err(
419                    "sync.invalid_request: securityPreflight and encryption are mutually exclusive; install keys with activateSecurity after preflight"
420                        .to_owned(),
421                ));
422            }
423            if let Some(enc) = params.get("encryption") {
424                let config = parse_encryption(enc).map_err(client_err)?;
425                instance.set_encryption(config);
426            }
427            if security_preflight {
428                instance.begin_security_preflight();
429            }
430            effects.security_preflight_pending = security_preflight;
431            *client = Some(instance);
432            Ok(json!({}))
433        }
434        "securityLifecycle" => Ok(json!({
435            "state": need_client(client)?.security_lifecycle()
436        })),
437        "beginSecurityPreflight" => {
438            let running = need_client(client)?;
439            running.disconnect_realtime(transport);
440            running.begin_security_preflight();
441            effects.security_preflight_pending = true;
442            Ok(json!({}))
443        }
444        "activateSecurity" => {
445            let encryption = match params.get("encryption") {
446                Some(value) => parse_encryption(value).map_err(client_err)?,
447                None => syncular_client::values::EncryptionConfig::default(),
448            };
449            // Optional fresh transport headers ride the activation atomically,
450            // so a preflight that outlives the boot token starts its first
451            // sync round with valid credentials. Validated here at the shared
452            // chokepoint (invalid input keeps the gate closed); the host
453            // applies the parsed set to its own transport.
454            if let Some(headers) = params.get("headers") {
455                parse_headers(headers).map_err(client_err)?;
456            }
457            need_client(client)?
458                .activate_security(encryption)
459                .map_err(client_err)?;
460            effects.security_preflight_pending = false;
461            Ok(json!({}))
462        }
463        "setHeaders" => {
464            let headers = params
465                .get("headers")
466                .ok_or_else(|| client_err("setHeaders missing headers".to_owned()))?;
467            parse_headers(headers).map_err(client_err)?;
468            Ok(json!({}))
469        }
470        "shutdown" => {
471            if let Some(running) = client.as_mut() {
472                // Capture the gate state BEFORE the shutdown barrier flips the
473                // client into preflight: an unactivated preflight stays
474                // pending across the shutdown, while an activated client may
475                // be recreated plainly afterwards.
476                effects.security_preflight_pending = running.security_preflight();
477                running.disconnect_realtime(transport);
478                // Teardown barrier only: an activated client that shuts down
479                // cleanly must not leave a durable quarantine mark, or its next
480                // plain create would be refused forever.
481                running.seal_security_on_teardown();
482            }
483            *client = None;
484            Ok(json!({}))
485        }
486        "subscribe" => {
487            let id = params
488                .get("id")
489                .and_then(Value::as_str)
490                .ok_or_else(|| client_err("subscribe missing id".to_owned()))?
491                .to_owned();
492            let table = params
493                .get("table")
494                .and_then(Value::as_str)
495                .ok_or_else(|| client_err("subscribe missing table".to_owned()))?
496                .to_owned();
497            let scopes = scopes_from_params(params.get("scopes")).map_err(client_err)?;
498            let sub_params = params
499                .get("params")
500                .and_then(Value::as_str)
501                .map(str::to_owned);
502            need_client(client)?
503                .subscribe(id, table, scopes, sub_params)
504                .map_err(client_err)?;
505            Ok(json!({}))
506        }
507        "unsubscribe" => {
508            let id = params
509                .get("id")
510                .and_then(Value::as_str)
511                .ok_or_else(|| client_err("unsubscribe missing id".to_owned()))?;
512            need_client(client)?.unsubscribe(id);
513            Ok(json!({}))
514        }
515        "setWindow" => {
516            let base = window_base_from_params(params.get("base")).map_err(client_err)?;
517            let units: Vec<String> = params
518                .get("units")
519                .and_then(Value::as_array)
520                .map(|arr| {
521                    arr.iter()
522                        .filter_map(|v| v.as_str().map(str::to_owned))
523                        .collect()
524                })
525                .unwrap_or_default();
526            let command_effects = need_client(client)?
527                .set_window(&base, &units)
528                .map_err(client_err)?;
529            Ok(json!({ "effects": command_effects }))
530        }
531        "windowState" => {
532            let base = window_base_from_params(params.get("base")).map_err(client_err)?;
533            let state = need_client(client)?.window_state(&base);
534            Ok(json!({ "units": state.units, "pending": state.pending }))
535        }
536        "timeWindowSugar" => {
537            let created_at_ms = params
538                .get("createdAtMs")
539                .and_then(Value::as_i64)
540                .ok_or_else(|| client_err("timeWindowSugar missing createdAtMs".to_owned()))?;
541            let count = params
542                .get("count")
543                .and_then(Value::as_u64)
544                .and_then(|value| usize::try_from(value).ok())
545                .ok_or_else(|| client_err("timeWindowSugar missing count".to_owned()))?;
546            let now_ms = params
547                .get("nowMs")
548                .and_then(Value::as_i64)
549                .ok_or_else(|| client_err("timeWindowSugar missing nowMs".to_owned()))?;
550            if params.get("unit").and_then(Value::as_str) != Some("month") {
551                return Err(client_err(
552                    "sync.invalid_request: timeWindowSugar requires the month unit".to_owned(),
553                ));
554            }
555            let unit = syncular_client::TimeBucketUnit::Month;
556            Ok(json!({
557                "bucket": syncular_client::creation_time_bucket(created_at_ms, unit)
558                    .map_err(client_err)?,
559                "units": syncular_client::last(count, unit, now_ms).map_err(client_err)?,
560            }))
561        }
562        "mutate" => {
563            let mutations = parse_mutations(params.get("mutations")).map_err(client_err)?;
564            let id = need_client(client)?.mutate(mutations).map_err(client_err)?;
565            Ok(json!({
566                "clientCommitId": id,
567                "effects": CommandEffects::interactive()
568            }))
569        }
570        "patch" => {
571            let table = params
572                .get("table")
573                .and_then(Value::as_str)
574                .ok_or_else(|| client_err("patch missing table".to_owned()))?;
575            let row_id = params
576                .get("rowId")
577                .and_then(Value::as_str)
578                .ok_or_else(|| client_err("patch missing rowId".to_owned()))?;
579            let mut partial = params
580                .get("partial")
581                .and_then(Value::as_object)
582                .cloned()
583                .ok_or_else(|| client_err("patch missing partial object".to_owned()))?;
584            decode_bigint_members(&mut partial).map_err(client_err)?;
585            let base_version = params.get("baseVersion").and_then(Value::as_i64);
586            let id = need_client(client)?
587                .patch(table, row_id, partial, base_version)
588                .map_err(client_err)?;
589            Ok(json!({
590                "clientCommitId": id,
591                "effects": CommandEffects::interactive()
592            }))
593        }
594        "purgeLocalData" => {
595            let input: LocalDataPurgeInput =
596                serde_json::from_value(params.get("input").cloned().ok_or_else(|| {
597                    client_err("sync.invalid_request: purgeLocalData missing input".to_owned())
598                })?)
599                .map_err(|error| {
600                    client_err(format!(
601                        "sync.invalid_request: invalid purgeLocalData input: {error}"
602                    ))
603                })?;
604            let result = need_client(client)?
605                .purge_local_data(&input)
606                .map_err(client_err)?;
607            serde_json::to_value(result).map_err(|error| client_err(error.to_string()))
608        }
609        "rebootstrapLocalData" => {
610            let input: LocalDataRebootstrapInput =
611                serde_json::from_value(params.get("input").cloned().ok_or_else(|| {
612                    client_err(
613                        "sync.invalid_request: rebootstrapLocalData missing input".to_owned(),
614                    )
615                })?)
616                .map_err(|error| {
617                    client_err(format!(
618                        "sync.invalid_request: invalid rebootstrapLocalData input: {error}"
619                    ))
620                })?;
621            let result = need_client(client)?
622                .rebootstrap_local_data(&input)
623                .map_err(client_err)?;
624            Ok(json!({
625                "alreadyApplied": result.already_applied,
626                "retainedCommits": result.retained_commits,
627                "resetSubscriptions": result.reset_subscriptions,
628                "effects": if result.already_applied {
629                    CommandEffects::none()
630                } else {
631                    CommandEffects::interactive()
632                }
633            }))
634        }
635        "sync" => {
636            let outcome = need_client(client)?.sync(transport);
637            Ok(outcome.to_json())
638        }
639        "syncUntilIdle" => {
640            let max_rounds = params
641                .get("maxRounds")
642                .and_then(Value::as_u64)
643                .map(|v| v as u32);
644            let outcome = need_client(client)?.sync_until_idle(transport, max_rounds);
645            Ok(outcome.to_json())
646        }
647        "readRows" => {
648            let table = params
649                .get("table")
650                .and_then(Value::as_str)
651                .ok_or_else(|| client_err("readRows missing table".to_owned()))?;
652            let rows = need_client(client)?.read_rows(table).map_err(client_err)?;
653            Ok(json!({ "rows": rows }))
654        }
655        "query" => {
656            // The React `useSyncQuery` live-query fast path: arbitrary read-only
657            // SQL over the local visible tables/views. Params ride as the driver
658            // value forms (bytes as `{"$bytes": hex}`); rows come back the same.
659            let sql = params
660                .get("sql")
661                .and_then(Value::as_str)
662                .ok_or_else(|| client_err("query missing sql".to_owned()))?;
663            let bind = match params.get("params") {
664                Some(Value::Array(list)) => list.as_slice(),
665                None | Some(Value::Null) => &[],
666                Some(_) => return Err(client_err("query params must be a list".to_owned())),
667            };
668            let rows = need_client(client)?.query(sql, bind).map_err(client_err)?;
669            Ok(Value::Object(serde_json::Map::from_iter([(
670                "rows".to_owned(),
671                Value::Array(rows.into_iter().map(Value::Object).collect()),
672            )])))
673        }
674        "querySnapshot" => {
675            let sql = params
676                .get("sql")
677                .and_then(Value::as_str)
678                .ok_or_else(|| client_err("querySnapshot missing sql".to_owned()))?;
679            let bind = match params.get("params") {
680                Some(Value::Array(list)) => list.as_slice(),
681                None | Some(Value::Null) => &[],
682                Some(_) => {
683                    return Err(client_err("querySnapshot params must be a list".to_owned()))
684                }
685            };
686            let mut coverage = Vec::new();
687            for entry in params
688                .get("coverage")
689                .and_then(Value::as_array)
690                .into_iter()
691                .flatten()
692            {
693                let base = window_base_from_params(entry.get("base")).map_err(client_err)?;
694                let units = entry
695                    .get("units")
696                    .and_then(Value::as_array)
697                    .map(|values| {
698                        values
699                            .iter()
700                            .filter_map(|value| value.as_str().map(str::to_owned))
701                            .collect()
702                    })
703                    .unwrap_or_default();
704                coverage.push(WindowCoverage { base, units });
705            }
706            let mut snapshot = need_client(client)?
707                .query_snapshot(sql, bind, &coverage)
708                .map_err(client_err)?;
709            let rows = std::mem::take(&mut snapshot.rows);
710            let mut result = serde_json::to_value(snapshot).expect("snapshot serializes");
711            result["rows"] = Value::Array(rows.into_iter().map(Value::Object).collect());
712            Ok(result)
713        }
714        "localRevision" => Ok(json!({
715            "revision": need_client(client)?.local_revision().to_string()
716        })),
717        "statusSnapshot" => Ok(serde_json::to_value(need_client(client)?.status_snapshot())
718            .expect("status serializes")),
719        "diagnosticsSnapshot" => {
720            let request = serde_json::from_value::<ClientDiagnosticsRequest>(params.clone())
721                .map_err(|error| {
722                    client_err(format!(
723                        "sync.invalid_request: invalid diagnostics request: {error}"
724                    ))
725                })?;
726            let snapshot = need_client(client)?
727                .diagnostics_snapshot(&request)
728                .map_err(client_err)?;
729            Ok(serde_json::to_value(snapshot).expect("diagnostics serialize"))
730        }
731        // Conformance/debug drains. Production hosts normally drain these
732        // immediately after every command, but exposing the exact core output
733        // here lets both client implementations consume one observation
734        // vector catalog without bridge inference.
735        "drainChangeBatches" => Ok(json!({
736            "batches": need_client(client)?.drain_change_batches()
737        })),
738        "drainSyncIntents" => Ok(json!({
739            "intents": need_client(client)?.drain_sync_intents()
740        })),
741        // -- §5.10.5 native CRDT (the `crdt-yjs` feature) -----------------------
742        // Thin forwards to the client core's yrs helpers. The command surface
743        // stays present-but-unavailable in a lean build: without the feature
744        // these fail loudly (`client.crdt_unavailable`) rather than being an
745        // unknown method, so a wrapper's typed method gives a clear error.
746        #[cfg(feature = "crdt-yjs")]
747        "crdtText" => {
748            let (table, row_id, column, name) = crdt_target(params)?;
749            let text = need_client(client)?
750                .crdt_text(&table, &row_id, &column, &name)
751                .map_err(client_err)?;
752            Ok(json!({ "text": text }))
753        }
754        #[cfg(feature = "crdt-yjs")]
755        "crdtInsertText" => {
756            let (table, row_id, column, name) = crdt_target(params)?;
757            let index = params
758                .get("index")
759                .and_then(Value::as_u64)
760                .ok_or_else(|| client_err("crdtInsertText missing index".to_owned()))?
761                as u32;
762            let value = params
763                .get("value")
764                .and_then(Value::as_str)
765                .ok_or_else(|| client_err("crdtInsertText missing value".to_owned()))?;
766            let id = need_client(client)?
767                .crdt_insert_text(&table, &row_id, &column, &name, index, value)
768                .map_err(client_err)?;
769            Ok(json!({ "clientCommitId": id }))
770        }
771        #[cfg(feature = "crdt-yjs")]
772        "crdtDeleteText" => {
773            let (table, row_id, column, name) = crdt_target(params)?;
774            let index = params
775                .get("index")
776                .and_then(Value::as_u64)
777                .ok_or_else(|| client_err("crdtDeleteText missing index".to_owned()))?
778                as u32;
779            let len = params
780                .get("len")
781                .and_then(Value::as_u64)
782                .ok_or_else(|| client_err("crdtDeleteText missing len".to_owned()))?
783                as u32;
784            let id = need_client(client)?
785                .crdt_delete_text(&table, &row_id, &column, &name, index, len)
786                .map_err(client_err)?;
787            Ok(json!({ "clientCommitId": id }))
788        }
789        #[cfg(feature = "crdt-yjs")]
790        "crdtApplyUpdate" => {
791            let (table, row_id, column, _name) = crdt_target(params)?;
792            let update = value_bytes(params.get("update")).map_err(client_err)?;
793            let id = need_client(client)?
794                .crdt_apply_update(&table, &row_id, &column, &update)
795                .map_err(client_err)?;
796            Ok(json!({ "clientCommitId": id }))
797        }
798        #[cfg(not(feature = "crdt-yjs"))]
799        "crdtText" | "crdtInsertText" | "crdtDeleteText" | "crdtApplyUpdate" => Err((
800            "client.crdt_unavailable".to_owned(),
801            "native CRDT support requires the `crdt-yjs` feature (§5.10.5)".to_owned(),
802        )),
803
804        "uploadBlob" => {
805            let bytes = value_bytes(params.get("bytes")).map_err(client_err)?;
806            let media_type = params
807                .get("mediaType")
808                .and_then(Value::as_str)
809                .map(str::to_owned);
810            let name = params
811                .get("name")
812                .and_then(Value::as_str)
813                .map(str::to_owned);
814            let reference = need_client(client)?
815                .upload_blob(&bytes, media_type, name)
816                .map_err(client_err)?;
817            Ok(json!({ "ref": reference }))
818        }
819        "fetchBlob" => {
820            let blob = params
821                .get("blob")
822                .and_then(Value::as_str)
823                .ok_or_else(|| client_err("fetchBlob missing blob".to_owned()))?
824                .to_owned();
825            // fetch_blob returns (code, message) so the server's blob.* code
826            // reaches the caller (§5.9.5 cross-scope probe).
827            let value = need_client(client)?.fetch_blob(transport, &blob)?;
828            Ok(Value::Object(serde_json::Map::from_iter([(
829                "blob".to_owned(),
830                value,
831            )])))
832        }
833        "conflicts" => {
834            let conflicts = need_client(client)?.conflicts().to_vec();
835            Ok(json!({ "conflicts": conflicts }))
836        }
837        "rejections" => {
838            let rejections = need_client(client)?.rejections().to_vec();
839            Ok(json!({ "rejections": rejections }))
840        }
841        "commitOutcome" => {
842            let client_commit_id = params
843                .get("clientCommitId")
844                .and_then(Value::as_str)
845                .ok_or_else(|| {
846                    client_err(
847                        "sync.invalid_request: commitOutcome missing clientCommitId".to_owned(),
848                    )
849                })?;
850            let outcome = need_client(client)?
851                .commit_outcome(client_commit_id)
852                .map_err(client_err)?;
853            Ok(json!({ "outcome": outcome }))
854        }
855        "commitOutcomes" => {
856            let query = serde_json::from_value::<CommitOutcomeQuery>(
857                params.get("query").cloned().unwrap_or_else(|| json!({})),
858            )
859            .map_err(|error| {
860                client_err(format!(
861                    "sync.invalid_request: invalid commit outcome query: {error}"
862                ))
863            })?;
864            let outcomes = need_client(client)?
865                .commit_outcomes(query)
866                .map_err(client_err)?;
867            Ok(json!({ "outcomes": outcomes }))
868        }
869        "resolveCommitOutcome" => {
870            let input = serde_json::from_value::<ResolveCommitOutcomeInput>(
871                params.get("input").cloned().ok_or_else(|| {
872                    client_err(
873                        "sync.invalid_request: resolveCommitOutcome missing input".to_owned(),
874                    )
875                })?,
876            )
877            .map_err(|error| {
878                client_err(format!(
879                    "sync.invalid_request: invalid outcome resolution: {error}"
880                ))
881            })?;
882            let outcome = need_client(client)?
883                .resolve_commit_outcome(input)
884                .map_err(client_err)?;
885            Ok(json!({ "outcome": outcome }))
886        }
887        "pendingCommitIds" => {
888            let ids = need_client(client)?.pending_commit_ids();
889            Ok(json!({ "ids": ids }))
890        }
891        "subscriptionState" => {
892            let id = params
893                .get("id")
894                .and_then(Value::as_str)
895                .ok_or_else(|| client_err("subscriptionState missing id".to_owned()))?;
896            let state = need_client(client)?.subscription_state(id);
897            Ok(json!({ "state": state }))
898        }
899        "recreateWithSchema" => {
900            // §7.4.2 "app ships new code": swap to the new schema on the SAME
901            // in-memory database (the Rust core has no persistent restart, so
902            // recreation IS the boot). Fires the §7.4.1 marker check.
903            let schema = params
904                .get("schema")
905                .ok_or_else(|| client_err("recreateWithSchema missing schema".to_owned()))?;
906            need_client(client)?
907                .recreate_with_schema(schema)
908                .map_err(client_err)?;
909            Ok(json!({}))
910        }
911        "connectRealtime" => {
912            need_client(client)?
913                .connect_realtime(transport)
914                .map_err(client_err)?;
915            Ok(json!({}))
916        }
917        "disconnectRealtime" => {
918            need_client(client)?.disconnect_realtime(transport);
919            Ok(json!({}))
920        }
921        "setPresence" => {
922            let scope_key = params
923                .get("scopeKey")
924                .and_then(Value::as_str)
925                .ok_or_else(|| client_err("setPresence missing scopeKey".to_owned()))?
926                .to_owned();
927            // §8.6.2: `doc` may be a JSON object or null (a leave).
928            let doc = params.get("doc");
929            let doc_ref = match doc {
930                None | Some(Value::Null) => None,
931                Some(v) => Some(v),
932            };
933            need_client(client)?
934                .set_presence(transport, &scope_key, doc_ref)
935                .map_err(client_err)?;
936            Ok(json!({}))
937        }
938        "presence" => {
939            let scope_key = params
940                .get("scopeKey")
941                .and_then(Value::as_str)
942                .ok_or_else(|| client_err("presence missing scopeKey".to_owned()))?;
943            let peers = need_client(client)?.presence(scope_key);
944            Ok(json!({ "peers": peers }))
945        }
946
947        // -- CodecDriver surface (Appendix A) — no client instance needed --
948        "messageRoundtrip" => {
949            let bytes = value_bytes(params.get("bytes")).map_err(client_err)?;
950            match decode_message(&bytes) {
951                Ok(message) => Ok(json!({
952                    "ok": true,
953                    "bytes": bytes_value(&encode_message(&message)),
954                    "renderedJson": render_message(&message).to_string(),
955                })),
956                Err(error) => Ok(json!({ "ok": false, "errorCode": error.code.as_str() })),
957            }
958        }
959        "segmentRoundtrip" => {
960            let bytes = value_bytes(params.get("bytes")).map_err(client_err)?;
961            match decode_rows_segment(&bytes) {
962                Ok(segment) => Ok(json!({
963                    "ok": true,
964                    "bytes": bytes_value(&encode_rows_segment(&segment)),
965                    "renderedJson": render_rows_segment(&segment).to_string(),
966                })),
967                Err(error) => Ok(json!({ "ok": false, "errorCode": error.code.as_str() })),
968            }
969        }
970        "realtimeKnown" => {
971            let text = params
972                .get("text")
973                .and_then(Value::as_str)
974                .ok_or_else(|| client_err("realtimeKnown missing text".to_owned()))?;
975            let known = matches!(
976                parse_control(text),
977                Ok(ControlMessage::Hello { .. })
978                    | Ok(ControlMessage::Wake { .. })
979                    | Ok(ControlMessage::Heartbeat { .. })
980                    | Ok(ControlMessage::Presence { .. })
981            );
982            Ok(json!({ "value": known }))
983        }
984
985        other => Err(client_err(format!("unknown method {other:?}"))),
986    }
987}
988
989#[cfg(test)]
990mod tests {
991    use serde_json::{json, Value};
992    use syncular_client::{
993        SegmentRequest, SyncClient, Transport, TransportError, SECURITY_PREFLIGHT_REQUIRED_CODE,
994    };
995
996    use super::{dispatch, parse_encryption, parse_headers, CreateEffects};
997
998    #[derive(Default)]
999    struct NoNetwork {
1000        realtime_connects: usize,
1001        realtime_closes: usize,
1002    }
1003
1004    impl Transport for NoNetwork {
1005        fn sync(&mut self, _request: &[u8]) -> Result<Vec<u8>, TransportError> {
1006            Err(TransportError::new("sync.transport_failed", "offline"))
1007        }
1008
1009        fn realtime_sync(&mut self, _request: &[u8]) -> Result<Vec<u8>, TransportError> {
1010            Err(TransportError::new("sync.transport_failed", "offline"))
1011        }
1012
1013        fn download_segment(
1014            &mut self,
1015            _request: &SegmentRequest,
1016        ) -> Result<Vec<u8>, TransportError> {
1017            Err(TransportError::new("sync.transport_failed", "offline"))
1018        }
1019
1020        fn realtime_connect(&mut self) -> Result<(), TransportError> {
1021            self.realtime_connects += 1;
1022            Ok(())
1023        }
1024
1025        fn realtime_send(&mut self, _text: &str) -> Result<(), TransportError> {
1026            Ok(())
1027        }
1028
1029        fn realtime_close(&mut self) -> Result<(), TransportError> {
1030            self.realtime_closes += 1;
1031            Ok(())
1032        }
1033    }
1034
1035    fn schema() -> Value {
1036        json!({
1037            "version": 1,
1038            "tables": [{
1039                "name": "todos",
1040                "columns": [
1041                    { "name": "id", "type": "string", "nullable": false },
1042                    { "name": "list_id", "type": "string", "nullable": false }
1043                ],
1044                "primaryKey": "id",
1045                "scopes": [{ "pattern": "list:{list_id}", "column": "list_id" }]
1046            }]
1047        })
1048    }
1049
1050    #[test]
1051    fn native_command_realtime_connection_is_idempotent() {
1052        let mut transport = NoNetwork::default();
1053        let mut client: Option<SyncClient> = None;
1054        let mut effects = CreateEffects::default();
1055        dispatch(
1056            &mut transport,
1057            &mut client,
1058            &mut effects,
1059            "create",
1060            &json!({ "schema": schema() }),
1061        )
1062        .expect("create client");
1063
1064        for _ in 0..2 {
1065            dispatch(
1066                &mut transport,
1067                &mut client,
1068                &mut effects,
1069                "connectRealtime",
1070                &json!({}),
1071            )
1072            .expect("idempotent connect command");
1073        }
1074        assert_eq!(transport.realtime_connects, 1);
1075
1076        dispatch(
1077            &mut transport,
1078            &mut client,
1079            &mut effects,
1080            "disconnectRealtime",
1081            &json!({}),
1082        )
1083        .expect("disconnect command");
1084        dispatch(
1085            &mut transport,
1086            &mut client,
1087            &mut effects,
1088            "disconnectRealtime",
1089            &json!({}),
1090        )
1091        .expect("idempotent disconnect command");
1092        assert_eq!(transport.realtime_closes, 1);
1093        dispatch(
1094            &mut transport,
1095            &mut client,
1096            &mut effects,
1097            "connectRealtime",
1098            &json!({}),
1099        )
1100        .expect("deliberate reconnect command");
1101        assert_eq!(transport.realtime_connects, 2);
1102    }
1103
1104    #[test]
1105    fn parses_portable_encryption_keyring_and_key_id_columns() {
1106        let key_hex = "2a".repeat(32);
1107        let config = parse_encryption(&json!({
1108            "keys": { "practice-key-v1": { "$bytes": key_hex } },
1109            "keyIdColumns": { "patients": "encryption_key_id" }
1110        }))
1111        .expect("portable keyring parses");
1112        assert_eq!(config.keys["practice-key-v1"], vec![0x2a; 32]);
1113        assert_eq!(config.key_id_columns["patients"], "encryption_key_id");
1114    }
1115
1116    #[test]
1117    fn rejects_non_string_key_id_columns() {
1118        let error = parse_encryption(&json!({
1119            "keys": {},
1120            "keyIdColumns": { "patients": 7 }
1121        }))
1122        .expect_err("invalid selector must fail");
1123        assert!(error.contains("must be a string"), "{error}");
1124    }
1125
1126    #[test]
1127    fn native_command_hosts_reject_subscription_identity_rebinds() {
1128        let mut transport = NoNetwork::default();
1129        let mut client: Option<SyncClient> = None;
1130        let mut effects = CreateEffects::default();
1131        dispatch(
1132            &mut transport,
1133            &mut client,
1134            &mut effects,
1135            "create",
1136            &json!({ "schema": schema() }),
1137        )
1138        .expect("create client");
1139
1140        let original = json!({
1141            "id": "stable-subscription",
1142            "table": "todos",
1143            "scopes": { "list_id": ["list-2", "list-1"] },
1144            "params": "{\"view\":\"v1\"}"
1145        });
1146        dispatch(
1147            &mut transport,
1148            &mut client,
1149            &mut effects,
1150            "subscribe",
1151            &original,
1152        )
1153        .expect("register subscription");
1154        dispatch(
1155            &mut transport,
1156            &mut client,
1157            &mut effects,
1158            "subscribe",
1159            &json!({
1160                "id": "stable-subscription",
1161                "table": "todos",
1162                "scopes": { "list_id": ["list-1", "list-2", "list-1"] },
1163                "params": "{\"view\":\"v1\"}"
1164            }),
1165        )
1166        .expect("canonical re-declaration is idempotent");
1167
1168        let error = dispatch(
1169            &mut transport,
1170            &mut client,
1171            &mut effects,
1172            "subscribe",
1173            &json!({
1174                "id": "stable-subscription",
1175                "table": "todos",
1176                "scopes": { "list_id": ["list-2"] },
1177                "params": "{\"view\":\"v1\"}"
1178            }),
1179        )
1180        .expect_err("changed native query identity must fail");
1181        assert_eq!(error.0, "client.subscription_intent_mismatch");
1182
1183        let state = dispatch(
1184            &mut transport,
1185            &mut client,
1186            &mut effects,
1187            "subscriptionState",
1188            &json!({ "id": "stable-subscription" }),
1189        )
1190        .expect("subscription state");
1191        assert_eq!(state["state"]["cursor"], -1);
1192        assert_eq!(state["state"]["table"], "todos");
1193    }
1194
1195    #[test]
1196    fn security_preflight_is_fail_closed_until_exact_activation() {
1197        let mut transport = NoNetwork::default();
1198        let mut client: Option<SyncClient> = None;
1199        let mut effects = CreateEffects::default();
1200        dispatch(
1201            &mut transport,
1202            &mut client,
1203            &mut effects,
1204            "create",
1205            &json!({ "schema": schema(), "securityPreflight": true }),
1206        )
1207        .expect("preflight create");
1208
1209        let lifecycle = dispatch(
1210            &mut transport,
1211            &mut client,
1212            &mut effects,
1213            "securityLifecycle",
1214            &json!({}),
1215        )
1216        .expect("lifecycle");
1217        assert_eq!(lifecycle, json!({ "state": "preflight" }));
1218
1219        let query_error = dispatch(
1220            &mut transport,
1221            &mut client,
1222            &mut effects,
1223            "query",
1224            &json!({ "sql": "SELECT id FROM todos", "params": [] }),
1225        )
1226        .expect_err("protected query must fail");
1227        assert_eq!(query_error.0, SECURITY_PREFLIGHT_REQUIRED_CODE);
1228        let diagnostics_error = dispatch(
1229            &mut transport,
1230            &mut client,
1231            &mut effects,
1232            "diagnosticsSnapshot",
1233            &json!({}),
1234        )
1235        .expect_err("diagnostics table/subscription evidence remains protected");
1236        assert_eq!(diagnostics_error.0, SECURITY_PREFLIGHT_REQUIRED_CODE);
1237
1238        dispatch(
1239            &mut transport,
1240            &mut client,
1241            &mut effects,
1242            "purgeLocalData",
1243            &json!({
1244                "input": {
1245                    "purgeId": "directive-1",
1246                    "targets": [{
1247                        "table": "todos",
1248                        "selectors": { "list_id": ["list-1"] }
1249                    }]
1250                }
1251            }),
1252        )
1253        .expect("authorized local purge remains available");
1254
1255        let repair_error = dispatch(
1256            &mut transport,
1257            &mut client,
1258            &mut effects,
1259            "rebootstrapLocalData",
1260            &json!({ "input": { "rebootstrapId": "blocked-repair" } }),
1261        )
1262        .expect_err("projection repair must remain protected during preflight");
1263        assert_eq!(repair_error.0, SECURITY_PREFLIGHT_REQUIRED_CODE);
1264
1265        dispatch(
1266            &mut transport,
1267            &mut client,
1268            &mut effects,
1269            "activateSecurity",
1270            &json!({}),
1271        )
1272        .expect("activation");
1273        let rows = dispatch(
1274            &mut transport,
1275            &mut client,
1276            &mut effects,
1277            "query",
1278            &json!({ "sql": "SELECT id FROM todos", "params": [] }),
1279        )
1280        .expect("active query");
1281        assert_eq!(rows, json!({ "rows": [] }));
1282
1283        dispatch(
1284            &mut transport,
1285            &mut client,
1286            &mut effects,
1287            "beginSecurityPreflight",
1288            &json!({}),
1289        )
1290        .expect("re-enter preflight");
1291        let blocked = dispatch(
1292            &mut transport,
1293            &mut client,
1294            &mut effects,
1295            "mutate",
1296            &json!({ "mutations": [] }),
1297        )
1298        .expect_err("mutation must be gated");
1299        assert_eq!(blocked.0, SECURITY_PREFLIGHT_REQUIRED_CODE);
1300    }
1301
1302    #[test]
1303    fn preflight_refuses_a_replacement_create_without_the_flag() {
1304        let mut transport = NoNetwork::default();
1305        let mut client: Option<SyncClient> = None;
1306        let mut effects = CreateEffects::default();
1307        dispatch(
1308            &mut transport,
1309            &mut client,
1310            &mut effects,
1311            "create",
1312            &json!({ "schema": schema(), "securityPreflight": true }),
1313        )
1314        .expect("preflight create");
1315
1316        // The escape the gate exists to prevent: a plain re-create must fail.
1317        let escape = dispatch(
1318            &mut transport,
1319            &mut client,
1320            &mut effects,
1321            "create",
1322            &json!({ "schema": schema() }),
1323        )
1324        .expect_err("plain create must be refused during preflight");
1325        assert_eq!(escape.0, SECURITY_PREFLIGHT_REQUIRED_CODE);
1326        // The refused create left the preflighted client installed and gated.
1327        let query_error = dispatch(
1328            &mut transport,
1329            &mut client,
1330            &mut effects,
1331            "query",
1332            &json!({ "sql": "SELECT id FROM todos", "params": [] }),
1333        )
1334        .expect_err("protected query stays gated");
1335        assert_eq!(query_error.0, SECURITY_PREFLIGHT_REQUIRED_CODE);
1336
1337        // A preflighted replacement is permitted and stays gated.
1338        dispatch(
1339            &mut transport,
1340            &mut client,
1341            &mut effects,
1342            "create",
1343            &json!({ "schema": schema(), "securityPreflight": true }),
1344        )
1345        .expect("preflighted replacement create");
1346        let still_gated = dispatch(
1347            &mut transport,
1348            &mut client,
1349            &mut effects,
1350            "query",
1351            &json!({ "sql": "SELECT id FROM todos", "params": [] }),
1352        )
1353        .expect_err("replacement stays gated");
1354        assert_eq!(still_gated.0, SECURITY_PREFLIGHT_REQUIRED_CODE);
1355
1356        // A legitimate activation releases the gate; creates behave as today.
1357        dispatch(
1358            &mut transport,
1359            &mut client,
1360            &mut effects,
1361            "activateSecurity",
1362            &json!({}),
1363        )
1364        .expect("activation");
1365        dispatch(
1366            &mut transport,
1367            &mut client,
1368            &mut effects,
1369            "create",
1370            &json!({ "schema": schema() }),
1371        )
1372        .expect("plain create after activation");
1373        let rows = dispatch(
1374            &mut transport,
1375            &mut client,
1376            &mut effects,
1377            "query",
1378            &json!({ "sql": "SELECT id FROM todos", "params": [] }),
1379        )
1380        .expect("active query");
1381        assert_eq!(rows, json!({ "rows": [] }));
1382    }
1383
1384    /// A file-backed replica: the persisted quarantine marker only exists here,
1385    /// which is why the in-memory tests above could not catch this.
1386    fn temp_db_path(tag: &str) -> String {
1387        std::env::temp_dir()
1388            .join(format!(
1389                "syncular-command-{tag}-{}-{:?}.db",
1390                std::process::id(),
1391                std::time::SystemTime::now()
1392                    .duration_since(std::time::UNIX_EPOCH)
1393                    .expect("clock")
1394                    .as_nanos()
1395            ))
1396            .to_string_lossy()
1397            .into_owned()
1398    }
1399
1400    #[test]
1401    fn an_activated_replica_reopens_plainly_after_shutdown() {
1402        // Shutting an ACTIVATED client down is not a quarantine event. The
1403        // teardown barrier used to call `begin_security_preflight`, which now
1404        // persists the gate, so every cleanly closed replica was marked pending
1405        // and its next plain `create` was refused forever — the reopen path
1406        // restores the flag from the marker and the create guard rejects it.
1407        let path = temp_db_path("activated-reopen");
1408        let mut transport = NoNetwork::default();
1409        let mut client: Option<SyncClient> = None;
1410        let mut effects = CreateEffects::default();
1411
1412        dispatch(
1413            &mut transport,
1414            &mut client,
1415            &mut effects,
1416            "create",
1417            &json!({ "schema": schema(), "securityPreflight": true, "dbPath": path }),
1418        )
1419        .expect("preflight create");
1420        dispatch(
1421            &mut transport,
1422            &mut client,
1423            &mut effects,
1424            "activateSecurity",
1425            &json!({}),
1426        )
1427        .expect("activation clears the gate");
1428        dispatch(
1429            &mut transport,
1430            &mut client,
1431            &mut effects,
1432            "shutdown",
1433            &json!({}),
1434        )
1435        .expect("shutdown after activation");
1436
1437        // The replica is active on disk, so a plain re-create must be admitted.
1438        dispatch(
1439            &mut transport,
1440            &mut client,
1441            &mut effects,
1442            "create",
1443            &json!({ "schema": schema(), "dbPath": path }),
1444        )
1445        .expect("an activated replica must reopen plainly after shutdown");
1446        let state = dispatch(
1447            &mut transport,
1448            &mut client,
1449            &mut effects,
1450            "securityLifecycle",
1451            &json!({}),
1452        )
1453        .expect("lifecycle");
1454        assert_eq!(state, json!({ "state": "active" }));
1455
1456        let _ = std::fs::remove_file(&path);
1457    }
1458
1459    #[test]
1460    fn an_unactivated_replica_stays_quarantined_across_shutdown_on_disk() {
1461        // The other half, and the reason the marker exists: a replica that
1462        // entered preflight and never activated must still refuse a plain
1463        // re-create after shutdown, even on a host that rebuilt its handle and
1464        // carries no in-memory flag.
1465        let path = temp_db_path("quarantined-reopen");
1466        let mut transport = NoNetwork::default();
1467        let mut client: Option<SyncClient> = None;
1468        let mut effects = CreateEffects::default();
1469
1470        dispatch(
1471            &mut transport,
1472            &mut client,
1473            &mut effects,
1474            "create",
1475            &json!({ "schema": schema(), "securityPreflight": true, "dbPath": path }),
1476        )
1477        .expect("preflight create");
1478        dispatch(
1479            &mut transport,
1480            &mut client,
1481            &mut effects,
1482            "shutdown",
1483            &json!({}),
1484        )
1485        .expect("shutdown during preflight");
1486
1487        // A fresh host handle: no in-memory pending flag survives here, so only
1488        // the persisted marker can hold the gate.
1489        let mut rebuilt = CreateEffects::default();
1490        let escape = dispatch(
1491            &mut transport,
1492            &mut client,
1493            &mut rebuilt,
1494            "create",
1495            &json!({ "schema": schema(), "dbPath": path }),
1496        )
1497        .expect_err("a quarantined replica must refuse a plain re-create");
1498        assert_eq!(escape.0, SECURITY_PREFLIGHT_REQUIRED_CODE);
1499
1500        let _ = std::fs::remove_file(&path);
1501    }
1502
1503    #[test]
1504    fn preflight_gate_survives_shutdown_before_replacement_creates() {
1505        let mut transport = NoNetwork::default();
1506        let mut client: Option<SyncClient> = None;
1507        let mut effects = CreateEffects::default();
1508        dispatch(
1509            &mut transport,
1510            &mut client,
1511            &mut effects,
1512            "create",
1513            &json!({ "schema": schema(), "securityPreflight": true }),
1514        )
1515        .expect("preflight create");
1516        dispatch(
1517            &mut transport,
1518            &mut client,
1519            &mut effects,
1520            "shutdown",
1521            &json!({}),
1522        )
1523        .expect("shutdown during preflight");
1524        assert!(client.is_none());
1525
1526        // The pending preflight rides `effects` across the empty client slot.
1527        let escape = dispatch(
1528            &mut transport,
1529            &mut client,
1530            &mut effects,
1531            "create",
1532            &json!({ "schema": schema() }),
1533        )
1534        .expect_err("shutdown + plain create must stay refused");
1535        assert_eq!(escape.0, SECURITY_PREFLIGHT_REQUIRED_CODE);
1536
1537        dispatch(
1538            &mut transport,
1539            &mut client,
1540            &mut effects,
1541            "create",
1542            &json!({ "schema": schema(), "securityPreflight": true }),
1543        )
1544        .expect("preflighted re-create");
1545        dispatch(
1546            &mut transport,
1547            &mut client,
1548            &mut effects,
1549            "activateSecurity",
1550            &json!({}),
1551        )
1552        .expect("activation");
1553
1554        // An ACTIVATED client shut down cleanly may be recreated plainly.
1555        dispatch(
1556            &mut transport,
1557            &mut client,
1558            &mut effects,
1559            "shutdown",
1560            &json!({}),
1561        )
1562        .expect("shutdown after activation");
1563        dispatch(
1564            &mut transport,
1565            &mut client,
1566            &mut effects,
1567            "create",
1568            &json!({ "schema": schema() }),
1569        )
1570        .expect("plain create after an activated shutdown");
1571    }
1572
1573    #[test]
1574    fn activate_security_validates_optional_headers_atomically() {
1575        let mut transport = NoNetwork::default();
1576        let mut client: Option<SyncClient> = None;
1577        let mut effects = CreateEffects::default();
1578        dispatch(
1579            &mut transport,
1580            &mut client,
1581            &mut effects,
1582            "create",
1583            &json!({ "schema": schema(), "securityPreflight": true }),
1584        )
1585        .expect("preflight create");
1586
1587        // Invalid header shapes fail loudly and keep the gate closed.
1588        let invalid = dispatch(
1589            &mut transport,
1590            &mut client,
1591            &mut effects,
1592            "activateSecurity",
1593            &json!({ "headers": { "authorization": 7 } }),
1594        )
1595        .expect_err("non-string header must fail");
1596        assert_eq!(invalid.0, "sync.invalid_request");
1597        let lifecycle = dispatch(
1598            &mut transport,
1599            &mut client,
1600            &mut effects,
1601            "securityLifecycle",
1602            &json!({}),
1603        )
1604        .expect("lifecycle");
1605        assert_eq!(lifecycle, json!({ "state": "preflight" }));
1606
1607        // A valid header set activates in one atomic step.
1608        dispatch(
1609            &mut transport,
1610            &mut client,
1611            &mut effects,
1612            "activateSecurity",
1613            &json!({ "headers": { "authorization": "Bearer fresh" } }),
1614        )
1615        .expect("activation with fresh headers");
1616        let lifecycle = dispatch(
1617            &mut transport,
1618            &mut client,
1619            &mut effects,
1620            "securityLifecycle",
1621            &json!({}),
1622        )
1623        .expect("lifecycle");
1624        assert_eq!(lifecycle, json!({ "state": "active" }));
1625    }
1626
1627    #[test]
1628    fn parse_headers_reads_the_full_replacement_set() {
1629        let parsed = parse_headers(&json!({
1630            "authorization": "Bearer fresh",
1631            "x-tenant": "t1"
1632        }))
1633        .expect("valid headers parse");
1634        assert_eq!(
1635            parsed,
1636            vec![
1637                ("authorization".to_owned(), "Bearer fresh".to_owned()),
1638                ("x-tenant".to_owned(), "t1".to_owned())
1639            ]
1640        );
1641        assert!(parse_headers(&json!(["authorization"])).is_err());
1642        assert!(parse_headers(&json!({ "authorization": null })).is_err());
1643    }
1644
1645    #[test]
1646    fn set_headers_validates_replacement_and_respects_preflight() {
1647        let mut transport = NoNetwork::default();
1648        let mut client: Option<SyncClient> = None;
1649        let mut effects = CreateEffects::default();
1650        dispatch(
1651            &mut transport,
1652            &mut client,
1653            &mut effects,
1654            "create",
1655            &json!({ "schema": schema() }),
1656        )
1657        .expect("create");
1658        dispatch(
1659            &mut transport,
1660            &mut client,
1661            &mut effects,
1662            "setHeaders",
1663            &json!({ "headers": { "authorization": "Bearer fresh" } }),
1664        )
1665        .expect("valid replacement");
1666        let invalid = dispatch(
1667            &mut transport,
1668            &mut client,
1669            &mut effects,
1670            "setHeaders",
1671            &json!({ "headers": { "authorization": 7 } }),
1672        )
1673        .expect_err("invalid replacement");
1674        assert_eq!(invalid.0, "sync.invalid_request");
1675
1676        dispatch(
1677            &mut transport,
1678            &mut client,
1679            &mut effects,
1680            "beginSecurityPreflight",
1681            &json!({}),
1682        )
1683        .expect("preflight");
1684        let gated = dispatch(
1685            &mut transport,
1686            &mut client,
1687            &mut effects,
1688            "setHeaders",
1689            &json!({ "headers": {} }),
1690        )
1691        .expect_err("direct rotation must respect preflight");
1692        assert_eq!(gated.0, SECURITY_PREFLIGHT_REQUIRED_CODE);
1693    }
1694}