Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions apps/mobile/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,13 @@ Camera app offers to open them directly in Mold; cold-launch and already-open
links share the same claim, instance-verification, and Keychain path as Mold's
in-app scanner.

An authenticated claim receives a distinct `mold_pair_...` credential, not the
host's operator key. The host stores only its digest in `mold.db`; web and
desktop Settings list grants with `GET /api/pairing/clients` and revoke one
with `DELETE /api/pairing/clients/:id`. Paired credentials can use normal APIs
but cannot create or manage other grants. When host authentication is disabled,
pairing remains credential-free and there is no grant to revoke.

Authenticated gallery media uses `POST /api/gallery/media-token` to exchange
the normal `X-Api-Key` request for a short-lived, read-only URL scoped to one
`/api/gallery/image/:filename` path. This allows native video Range requests and
Expand Down
2 changes: 1 addition & 1 deletion bun.nix
Original file line number Diff line number Diff line change
Expand Up @@ -1377,4 +1377,4 @@
url = "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz";
hash = "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==";
};
}
}
1 change: 1 addition & 0 deletions crates/mold-db/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ mod device_preferences;
pub mod metadata_io;
pub mod migrations;
mod model_prefs;
pub mod paired_clients;
mod path;
pub mod persist;
mod prompt_history;
Expand Down
33 changes: 28 additions & 5 deletions crates/mold-db/src/migrations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,25 @@ const V15_SCHEDULER_ESTIMATE_RUNTIME: &str = r#"
ALTER TABLE scheduler_estimates ADD COLUMN ewma_runtime_ms REAL;
"#;

/// v16 → individually revocable credentials created by mobile pairing.
///
/// Only SHA-256 digests of the high-entropy bearer credentials are retained.
/// Revocation deletes the row, so a copied client credential stops working
/// immediately and stays revoked across server restarts.
const V16_PAIRED_CLIENTS: &str = r#"
CREATE TABLE paired_clients (
id TEXT PRIMARY KEY,
server_instance_id TEXT NOT NULL,
name TEXT NOT NULL,
client_kind TEXT NOT NULL,
credential_hash BLOB NOT NULL UNIQUE CHECK (length(credential_hash) = 32),
created_at_ms INTEGER NOT NULL,
last_used_at_ms INTEGER
);
CREATE INDEX idx_paired_clients_instance_created_at
ON paired_clients(server_instance_id, created_at_ms DESC);
"#;

/// Ordered list of schema migrations. Version numbers must be strictly
/// increasing — [`apply_pending`] validates this at startup.
pub(crate) const MIGRATIONS: &[Migration] = &[
Expand Down Expand Up @@ -441,11 +460,15 @@ pub(crate) const MIGRATIONS: &[Migration] = &[
version: 15,
kind: MigrationKind::Sql(V15_SCHEDULER_ESTIMATE_RUNTIME),
},
Migration {
version: 16,
kind: MigrationKind::Sql(V16_PAIRED_CLIENTS),
},
];

/// The highest migration version this build ships. Exposed publicly so
/// operators / tests can assert what schema level they're running against.
pub const SCHEMA_VERSION: i64 = 15;
pub const SCHEMA_VERSION: i64 = 16;

/// v1 → v2: rewrite every `output_dir` value to its canonical form so
/// rows written by the v0.8.x release (which keyed on raw paths) keep
Expand Down Expand Up @@ -821,7 +844,7 @@ mod tests {
SCHEMA_VERSION,
"fresh DB must end at the latest SCHEMA_VERSION",
);
assert_eq!(SCHEMA_VERSION, 15);
assert_eq!(SCHEMA_VERSION, 16);
assert!(table_exists(&conn, "device_preferences"));
assert_eq!(
column_names(&conn, "device_preferences"),
Expand Down Expand Up @@ -1152,8 +1175,8 @@ mod v9_tests {
use rusqlite::Connection;

#[test]
fn schema_version_is_thirteen() {
assert_eq!(SCHEMA_VERSION, 15);
fn schema_version_is_current() {
assert_eq!(SCHEMA_VERSION, 16);
}

#[test]
Expand Down Expand Up @@ -1234,7 +1257,7 @@ mod v15_tests {

apply_pending(&mut conn).unwrap();

assert_eq!(current_version(&conn).unwrap(), 15);
assert_eq!(current_version(&conn).unwrap(), SCHEMA_VERSION);
let runtime: Option<f64> = conn
.query_row(
"SELECT ewma_runtime_ms FROM scheduler_estimates WHERE estimate_key = 'legacy'",
Expand Down
132 changes: 132 additions & 0 deletions crates/mold-db/src/paired_clients.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
//! Durable, individually revocable credentials issued by the pairing API.

use anyhow::{Context, Result};
use rusqlite::params;

use crate::MetadataDb;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PairedClient {
pub id: String,
pub server_instance_id: String,
pub name: String,
pub client_kind: String,
pub credential_hash: [u8; 32],
pub created_at_ms: i64,
pub last_used_at_ms: Option<i64>,
}

pub struct PairedClients<'a> {
db: &'a MetadataDb,
}

impl<'a> PairedClients<'a> {
pub fn new(db: &'a MetadataDb) -> Self {
Self { db }
}

pub fn list(&self, server_instance_id: &str) -> Result<Vec<PairedClient>> {
self.db.with_conn(|conn| {
let mut statement = conn.prepare(
"SELECT id, server_instance_id, name, client_kind, credential_hash, created_at_ms, last_used_at_ms
FROM paired_clients
WHERE server_instance_id = ?1
ORDER BY created_at_ms DESC, id ASC",
)?;
let rows = statement.query_map([server_instance_id], |row| {
let hash: Vec<u8> = row.get(4)?;
let credential_hash: [u8; 32] = hash.try_into().map_err(|value: Vec<u8>| {
rusqlite::Error::FromSqlConversionFailure(
value.len(),
rusqlite::types::Type::Blob,
"paired credential hash must be 32 bytes".into(),
)
})?;
Comment thread
jamesbrink marked this conversation as resolved.
Ok(PairedClient {
id: row.get(0)?,
server_instance_id: row.get(1)?,
name: row.get(2)?,
client_kind: row.get(3)?,
credential_hash,
created_at_ms: row.get(5)?,
last_used_at_ms: row.get(6)?,
})
})?;
rows.collect::<rusqlite::Result<Vec<_>>>()
.map_err(Into::into)
})
}

pub fn insert(&self, client: &PairedClient) -> Result<()> {
self.db.with_conn(|conn| {
conn.execute(
"INSERT INTO paired_clients (
id, server_instance_id, name, client_kind, credential_hash, created_at_ms, last_used_at_ms
) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
params![
client.id,
client.server_instance_id,
client.name,
client.client_kind,
client.credential_hash.as_slice(),
client.created_at_ms,
client.last_used_at_ms,
],
)
.context("inserting paired client")?;
Ok(())
})
}

pub fn touch(&self, server_instance_id: &str, id: &str, last_used_at_ms: i64) -> Result<()> {
self.db.with_conn(|conn| {
conn.execute(
"UPDATE paired_clients SET last_used_at_ms = ?3 WHERE server_instance_id = ?1 AND id = ?2",
params![server_instance_id, id, last_used_at_ms],
)?;
Ok(())
})
}

pub fn revoke(&self, server_instance_id: &str, id: &str) -> Result<bool> {
self.db.with_conn(|conn| {
Ok(conn.execute(
"DELETE FROM paired_clients WHERE server_instance_id = ?1 AND id = ?2",
params![server_instance_id, id],
)? > 0)
})
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn grants_round_trip_touch_and_revoke() {
let db = MetadataDb::open_in_memory().unwrap();
let clients = PairedClients::new(&db);
let client = PairedClient {
id: "phone-1".into(),
server_instance_id: "server-a".into(),
name: "James's iPhone".into(),
client_kind: "mobile".into(),
credential_hash: [7; 32],
created_at_ms: 100,
last_used_at_ms: None,
};

clients.insert(&client).unwrap();
assert_eq!(clients.list("server-a").unwrap(), vec![client.clone()]);
assert!(clients.list("server-b").unwrap().is_empty());
clients.touch("server-a", &client.id, 250).unwrap();
assert_eq!(
clients.list("server-a").unwrap()[0].last_used_at_ms,
Some(250)
);
assert!(!clients.revoke("server-b", &client.id).unwrap());
assert!(clients.revoke("server-a", &client.id).unwrap());
assert!(!clients.revoke("server-a", &client.id).unwrap());
assert!(clients.list("server-a").unwrap().is_empty());
}
}
Loading
Loading