desktop: Add an actor profile editor behind the actorRepos lab

Co-authored-by: Brandon Oxendine <brandon.oxendine@gmail.com>
This commit is contained in:
Ioannis T.
2026-11-20 17:33:55 +01:00
co-authored by Brandon Oxendine
parent 442e58780f
commit bc2914f06b
74 changed files with 15563 additions and 35 deletions
+2
View File
@@ -4825,6 +4825,7 @@ dependencies = [
"infer",
"log",
"mime-infer",
"multibase",
"radicle",
"radicle-artifact",
"radicle-artifact-client",
@@ -4842,6 +4843,7 @@ dependencies = [
"tempfile",
"thiserror 2.0.19",
"ts-rs",
"unicode-normalization",
"url",
"which",
]
@@ -1,3 +1,4 @@
pub mod actor;
pub mod auth;
pub mod cob;
pub mod diff;
@@ -0,0 +1,157 @@
use radicle::git;
use radicle::identity::{Did, RepoId};
use radicle_types::actor::{
ActorInfo, ActorProfile, ActorRevision, EnrollmentPreview, ProfileEdit, ProfileImages,
};
use radicle_types::cobs::{CobOptions, PaginatedQuery};
use radicle_types::error::Error;
use radicle_types::traits::actor::Actor;
use crate::AppState;
use crate::commands::blocking;
#[tauri::command]
pub async fn actor(ctx: tauri::State<'_, AppState>) -> Result<Option<ActorInfo>, Error> {
blocking(ctx, move |ctx| ctx.actor()).await
}
#[tauri::command]
pub async fn create_actor(
ctx: tauri::State<'_, AppState>,
profile: ActorProfile,
images: ProfileImages,
opts: CobOptions,
) -> Result<ActorInfo, Error> {
blocking(ctx, move |ctx| ctx.create_actor(profile, images, opts)).await
}
#[tauri::command]
pub async fn update_actor_profile(
ctx: tauri::State<'_, AppState>,
profile: ActorProfile,
images: ProfileImages,
opts: CobOptions,
) -> Result<ActorInfo, Error> {
blocking(ctx, move |ctx| {
ctx.update_actor_profile(profile, images, opts)
})
.await
}
#[tauri::command]
pub async fn joinable_actor(
ctx: tauri::State<'_, AppState>,
rid: RepoId,
) -> Result<ActorInfo, Error> {
blocking(ctx, move |ctx| ctx.joinable_actor(rid)).await
}
#[tauri::command]
pub async fn join_actor(ctx: tauri::State<'_, AppState>, rid: RepoId) -> Result<String, Error> {
blocking(ctx, move |ctx| ctx.join_actor(rid)).await
}
#[tauri::command]
pub async fn decode_enrollment(
ctx: tauri::State<'_, AppState>,
code: String,
) -> Result<EnrollmentPreview, Error> {
blocking(ctx, move |ctx| ctx.decode_enrollment(code)).await
}
#[tauri::command]
pub async fn approve_enrollment(
ctx: tauri::State<'_, AppState>,
code: String,
controller: bool,
opts: CobOptions,
) -> Result<ActorInfo, Error> {
blocking(ctx, move |ctx| {
ctx.approve_enrollment(code, controller, opts)
})
.await
}
#[tauri::command]
pub async fn approve_actor_revision(
ctx: tauri::State<'_, AppState>,
id: git::Oid,
opts: CobOptions,
) -> Result<ActorInfo, Error> {
blocking(ctx, move |ctx| ctx.approve_actor_revision(id, opts)).await
}
#[tauri::command]
pub async fn withdraw_actor_revision(
ctx: tauri::State<'_, AppState>,
id: git::Oid,
opts: CobOptions,
) -> Result<ActorInfo, Error> {
blocking(ctx, move |ctx| ctx.withdraw_actor_revision(id, opts)).await
}
#[tauri::command]
pub async fn reject_actor_revision(
ctx: tauri::State<'_, AppState>,
id: git::Oid,
opts: CobOptions,
) -> Result<ActorInfo, Error> {
blocking(ctx, move |ctx| ctx.reject_actor_revision(id, opts)).await
}
#[tauri::command]
pub async fn remove_actor_key(
ctx: tauri::State<'_, AppState>,
did: Did,
opts: CobOptions,
) -> Result<ActorInfo, Error> {
blocking(ctx, move |ctx| ctx.remove_actor_key(did, opts)).await
}
#[tauri::command]
pub async fn actors_of_key(ctx: tauri::State<'_, AppState>) -> Result<Vec<ActorInfo>, Error> {
blocking(ctx, move |ctx| ctx.actors_of_key()).await
}
#[tauri::command]
pub async fn closed_actor_revisions(
ctx: tauri::State<'_, AppState>,
) -> Result<Vec<ActorRevision>, Error> {
blocking(ctx, move |ctx| ctx.closed_actor_revisions()).await
}
#[tauri::command]
pub async fn actor_profile_history(
ctx: tauri::State<'_, AppState>,
skip: Option<usize>,
take: Option<usize>,
) -> Result<PaginatedQuery<Vec<ProfileEdit>>, Error> {
blocking(ctx, move |ctx| ctx.actor_profile_history(skip, take)).await
}
#[tauri::command]
pub async fn leave_actor(
ctx: tauri::State<'_, AppState>,
rid: RepoId,
opts: CobOptions,
) -> Result<ActorInfo, Error> {
blocking(ctx, move |ctx| ctx.leave_actor(rid, opts)).await
}
#[tauri::command]
pub async fn cancel_leave(
ctx: tauri::State<'_, AppState>,
rid: RepoId,
opts: CobOptions,
) -> Result<ActorInfo, Error> {
blocking(ctx, move |ctx| ctx.cancel_leave(rid, opts)).await
}
#[tauri::command]
pub async fn retire_actor(
ctx: tauri::State<'_, AppState>,
rid: RepoId,
opts: CobOptions,
) -> Result<ActorInfo, Error> {
blocking(ctx, move |ctx| ctx.retire_actor(rid, opts)).await
}
+18 -1
View File
@@ -9,7 +9,7 @@ use tauri::menu::{Menu, MenuItem, MenuItemKind};
use tauri::{Emitter, Manager};
use tauri_plugin_log::{Target, TargetKind};
use commands::{auth, cob, diff, identity, inbox, profile, repo, startup, thread};
use commands::{actor, auth, cob, diff, identity, inbox, profile, repo, startup, thread};
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
@@ -135,6 +135,23 @@ pub fn run() {
diff::save_diff_to_disk,
repo::get_commit_diff,
identity::identity_by_repo,
actor::actor,
actor::create_actor,
actor::update_actor_profile,
actor::joinable_actor,
actor::join_actor,
actor::decode_enrollment,
actor::approve_enrollment,
actor::approve_actor_revision,
actor::withdraw_actor_revision,
actor::reject_actor_revision,
actor::remove_actor_key,
actor::actors_of_key,
actor::closed_actor_revisions,
actor::actor_profile_history,
actor::leave_actor,
actor::cancel_leave,
actor::retire_actor,
inbox::clear_notifications,
inbox::notification_count,
inbox::list_notifications,
+2
View File
@@ -14,6 +14,7 @@ git2 = { version = "0.21", default-features = false, features = ["vendored-libgi
log = { version = "0.4.22" }
infer = { version = "0.19.0" }
mime-infer = { version = "3.0.0" }
multibase = { version = "0.9.3" }
radicle = { version = "0.25", features = ["tor", "i2p"] }
radicle-artifact = { version = "0.23" }
radicle-artifact-client = { version = "0.23" }
@@ -35,6 +36,7 @@ ts-rs = { version = "12.0.1", features = [
"no-serde-warnings",
"format",
] }
unicode-normalization = { version = "0.1.25" }
url = { version = "2.5.4", features = ["serde"] }
which = { version = "8.0.5" }
@@ -0,0 +1,40 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { ActorProfile } from "./ActorProfile";
/**
* Another controller's version of the profile, on a branch that is not
* behind the one this key reads.
*/
export type ActorFork = {
did: string;
/**
* The commit that controller's branch is on.
*/
head: string;
/**
* Unset when that version holds no profile this Desktop can read.
*/
profile?: ActorProfile;
/**
* The profile as it was where the two versions split. Unset when they
* split at no one commit, or that commit holds no profile this Desktop
* can read in full.
*/
base?: ActorProfile;
/**
* What that version changed since the two split, as a unified diff of
* the profile cleaned as it is for display. Unset when `base` is, or
* that version holds no profile this Desktop can read.
*/
changes?: string;
/**
* That version changed files other than the profile since the two
* split or, when they split at no one commit, holds other files that
* differ from the version shown. A save here leaves those changes out.
*/
otherFiles: boolean;
/**
* That version is from a newer client, so Desktop must not replace it.
*/
profileNewer: boolean;
};
@@ -0,0 +1,57 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { ActorFork } from "./ActorFork";
import type { ActorKey } from "./ActorKey";
import type { ActorKind } from "./ActorKind";
import type { ActorProfile } from "./ActorProfile";
import type { ActorRevision } from "./ActorRevision";
/**
* An actor as Desktop shows it: the local one, or one the local key may
* join.
*/
export type ActorInfo = {
rid: string;
kind: ActorKind;
/**
* The founding key first, then the other bound keys, then the
* controllers that are not bound.
*/
keys: Array<ActorKey>;
/**
* How many controllers must agree on a profile edit.
*/
threshold: number;
/**
* How many controllers must accept an identity change.
*/
majority: number;
/**
* The payload is from a newer client, so Desktop must not change it.
*/
payloadNewer: boolean;
/**
* Unset when the default branch has no readable profile yet.
*/
profile?: ActorProfile;
/**
* The profile is from a newer client, so Desktop must not rewrite it.
*/
profileNewer: boolean;
/**
* The profile file cannot be read; a save replaces it.
*/
profileUnreadable: boolean;
/**
* The commit the profile was read from.
*/
head?: string;
/**
* Identity changes open for the controllers' votes.
*/
pending: Array<ActorRevision>;
/**
* The other controllers' versions of the profile that are not behind
* the one shown, when this key publishes alone; a save replaces them.
*/
forks: Array<ActorFork>;
};
@@ -0,0 +1,18 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* A key of the actor as Desktop shows it.
*/
export type ActorKey = {
did: string;
/**
* The node alias, local to this machine and no part of the profile.
*/
alias?: string;
bound: boolean;
controller: boolean;
/**
* Seconds since the epoch.
*/
addedAt: number;
};
@@ -0,0 +1,7 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* What the actor repository describes; any other value makes the payload
* invalid.
*/
export type ActorKind = "person" | "agent" | "org";
@@ -0,0 +1,19 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { ProfileLink } from "./ProfileLink";
/**
* The contents of `.radicle/profile.json`. A file of `PROFILE_VERSION` must
* match the schema exactly; a newer one is read for its known fields.
*/
export type ActorProfile = {
version: number;
displayName: string;
fullName?: string;
pronouns?: string;
bio?: string;
location?: string;
timezone?: string;
avatar?: string;
banner?: string;
links?: Array<ProfileLink>;
};
@@ -0,0 +1,41 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { ActorKey } from "./ActorKey";
import type { RevisionState } from "./RevisionState";
/**
* A change to the actor's identity. One open for votes applies once a
* majority of the controllers accept it. What it adds, removes and lowers is
* told against the identity it was proposed on.
*/
export type ActorRevision = {
id: string;
author: string;
/**
* Seconds since the epoch.
*/
createdAt: number;
/**
* The keys it adds or gives another role, with the roles they get.
*/
added: Array<ActorKey>;
removed: Array<string>;
/**
* How many controllers a profile edit needs after the change, if it
* lowers that.
*/
threshold?: number;
/**
* The controllers that accepted it, the author among them.
*/
accepted: Array<string>;
/**
* The controllers that rejected it. The change stays open until it can no
* longer reach a majority.
*/
rejected: Array<string>;
/**
* It changes more than Desktop can show, so Desktop must not sign it.
*/
unreadable: boolean;
state: RevisionState;
};
@@ -0,0 +1,18 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* The key an enrollment code would bind, shown before a controller approves
* it.
*/
export type EnrollmentPreview = {
did: string;
/**
* The key's node alias, when this machine knows it.
*/
alias?: string;
/**
* The key already controls the actor, as a recovery key does, and keeps
* that role.
*/
controller: boolean;
};
@@ -0,0 +1,35 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* One version of the profile in the history of the one shown.
*/
export type ProfileEdit = {
commit: string;
/**
* The versions it was saved over: none for the first version, several
* for a save that joined versions that had split.
*/
parents: Array<string>;
/**
* Seconds since the epoch, by the clock of the device that saved it.
*/
savedAt: number;
/**
* The key of the device that saved it, as the commit records it, which
* nothing verifies. Unset when the commit names no key.
*/
author?: string;
/**
* The fields of the profile, by their names in the file, that differ
* from the first of `parents`, or that the first version sets; `avatar`
* and `banner` also when the picture they name changed. Unset when this
* version or that parent holds a profile this Desktop cannot read in
* full.
*/
fields?: Array<string>;
/**
* It is in the history of the profile `actor` shows. Otherwise it is on
* this key's own branch, and waits for the other controllers.
*/
live: boolean;
};
@@ -0,0 +1,9 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* The pictures to save in the repository with a profile, each the base64 of
* an image file: a PNG, JPEG, WebP or GIF of at most 1 MiB for the avatar
* and 2 MiB for the banner. The kind is told from the first bytes of the
* file, and the rest is not decoded: what is saved may not show.
*/
export type ProfileImages = { avatar?: string; banner?: string };
@@ -0,0 +1,3 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type ProfileLink = { url: string; label?: string };
@@ -0,0 +1,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* Where a change to the actor's identity stands.
*/
export type RevisionState = "open" | "accepted" | "rejected" | "lapsed";
@@ -9,4 +9,8 @@ export type RepoSummary = {
* `rad ls --all` shows as "local".
*/
seeding: boolean;
/**
* The repository is an actor's, a profile and not a project.
*/
actor: boolean;
};
+414
View File
@@ -0,0 +1,414 @@
//! Actor repositories: what an actor is and what Desktop shows of one.
//! Nothing here signs or talks to a node; `traits::actor` does.
use serde::Serialize;
use ts_rs::TS;
use radicle::git;
use radicle::identity::{Did, RepoId};
use radicle::node::Alias;
mod identity;
mod profile;
// The public interface of the actor rules.
pub use identity::{
ActorKind, ActorPayload, ClosedIdentityRevision, Enrollment, EnrollmentError,
IdentityDocRevision, OpenIdentityRevision, ResolvedActor, ResolvedKey, RevisionState,
changed_key_entries, changes_only_keys, closed_revisions, enrolled_doc, identity_history,
initial_doc, open_revisions, removed_doc, repo_name, resolve, retired_doc,
};
pub use profile::{
ActorProfile, PROFILE_PATH, ProfileFile, ProfileImage, ProfileImages, ProfileLink,
changed_fields, profile_changes, profile_tree, profile_tree_with, read_profile,
};
/// Drops the entries of `object` that `fields` does not name, and says whether
/// there were any.
fn retain_fields(object: &mut serde_json::Map<String, serde_json::Value>, fields: &[&str]) -> bool {
let before = object.len();
object.retain(|key, _| fields.contains(&key.as_str()));
object.len() != before
}
/// Every way an actor operation can fail. Desktop shows the messages to the
/// user as they are.
#[derive(Debug, thiserror::Error)]
pub enum Error {
/// The profile fails `ActorProfile::validate`; the message names the field.
#[error("Invalid profile: {0}.")]
Profile(String),
/// The local key is already bound to an actor repository.
#[error("This key already has a profile, {0}.")]
Exists(RepoId),
/// The key had an actor of that name, retired or left over.
#[error("A profile named {0} is already in storage. Pick another display name.")]
NameTaken(String),
/// No actor repository binds the local key.
#[error("The profile is no longer in storage.")]
NotFound,
/// More than one actor binds the local key.
#[error("This key belongs to more than one profile: {}.", .0.iter().map(ToString::to_string).collect::<Vec<_>>().join(", "))]
Ambiguous(Vec<RepoId>),
/// The profile is from a newer client; rewriting it would drop fields.
#[error("A newer version of Desktop has written this profile since the page loaded.")]
ProfileNewer,
/// The enrollment code cannot be read, or its signature is not the
/// joining key's consent.
#[error("That is not a valid code.")]
InvalidCode,
/// The enrollment code is for another actor.
#[error("That code is for another profile, {0}.")]
WrongActor(RepoId),
/// An actor binds the key, and what it is cannot be read.
#[error(
"This key belongs to a profile, {0}, written by a newer app that this version of Desktop cannot read. Update Desktop."
)]
ActorNewer(RepoId),
/// The identity changed while a change to it was being prepared.
#[error("Your keys changed just now. Check them and try again.")]
Moved,
/// The identity changed after the joining key consented.
#[error("Your keys changed after that code was created. Create a new one on the other device.")]
Stale,
/// The key is already bound to the actor.
#[error("That key is already yours.")]
AlreadyBound,
/// The payload lists as many keys as it can hold.
#[error("You have the most keys a profile can list.")]
Full,
/// Only a controller can change the identity.
#[error("This device's key cannot change which keys are yours. Use a key that can.")]
NotController,
/// The actor payload holds more than this client knows; a change would
/// sign what it cannot read.
#[error(
"Your keys hold fields this version of Desktop does not know, so it cannot change them."
)]
PayloadNewer,
/// The repository is not in storage.
#[error("The profile {0} is not on this device.")]
NotFetched(RepoId),
/// The copy in storage has no head and none can be computed, so the node
/// fetches nothing more into it.
#[error(
"This device fetched the profile while two of its devices had saved different versions, and it cannot update that copy. Save the profile on a device that controls it, then fetch it again here."
)]
CopyStuck(RepoId),
/// The user blocked the repository, so nothing here seeds it.
#[error("You blocked {0}. Unblock it first, then add this device.")]
Blocked(RepoId),
/// The repository is not an individual actor that a key can join.
#[error("{0} is not a profile a device can be added to.")]
NotJoinable(RepoId),
/// Only the key that proposed an identity change can withdraw it.
#[error("Only the key that proposed this change can withdraw it.")]
NotAuthor,
/// No open identity change has this id.
#[error("The change {0} is no longer open.")]
RevisionNotFound(git::Oid),
/// A key cannot remove itself from the actor.
#[error("This device cannot revoke its own key. Revoke it from another controller.")]
RemoveSelf,
/// The actor has no such key.
#[error("The key {0} is no longer part of your profile.")]
KeyNotFound(Did),
/// No live individual actor of that id binds the local key.
#[error("This device's key is not in the profile {0}.")]
NotBound(RepoId),
/// The local key is the actor's only controller, so its removal would
/// leave the actor without one.
#[error("This device's key is the only controller of {0}. That profile can only be retired.")]
OnlyController(RepoId),
/// The local key does not control the actor, so it has no vote on its own
/// removal; the controllers are the keys that have.
#[error("This device's key cannot approve changes in {rid}. A device that controls that profile has to revoke it: {}.", .controllers.iter().map(ToString::to_string).collect::<Vec<_>>().join(", "))]
LeaveNeedsController { rid: RepoId, controllers: Vec<Did> },
/// The local key has voted to leave another actor, and that change is
/// still open.
#[error(
"This device is already leaving {0}. Cancel that leave first, or wait until it is approved or rejected."
)]
Leaving(RepoId),
/// No open change by which the local key leaves the actor holds its vote.
#[error("This device is not leaving {0}.")]
NotLeaving(RepoId),
/// Another key proposed the removal the local key accepted, and only the
/// proposer withdraws a change.
#[error(
"Another device proposed removing this one from {0}, so only that device can withdraw it."
)]
LeaveNotOwn(RepoId),
/// Retiring the actor would leave the local key with none.
#[error("{0} is the only profile this device is in, so it is not retired from here.")]
LastActor(RepoId),
/// Other keys control the actor too, and Desktop has no way for them to
/// sign a retirement.
#[error(
"Other devices control {0} too, so this device cannot retire it alone. Leave it instead."
)]
RetireShared(RepoId),
/// This key already voted on the identity change.
#[error("This key already voted on that change.")]
AlreadyVoted,
/// This key already accepted another change at the same identity version.
#[error("This key already approved another change; that one has to be settled first.")]
VotedElsewhere,
/// The change does more than Desktop can show, so the user cannot vote on it.
#[error("This change does more than Desktop can show, so it cannot be signed here.")]
RevisionUnreadable,
/// The edit is on this key's branch, signed, and announced if the node
/// runs, but the controllers' branches have split.
#[error(
"Saved under this key only. The profile did not update because its controllers' copies have diverged. Open the profile on another device that controls it, once it has synced, and save there."
)]
Diverged,
#[error(transparent)]
Repository(#[from] radicle::storage::RepositoryError),
#[error("the identity revision {0} is missing")]
Missing(git::Oid),
#[error("the identity document has no actor payload with keys")]
Payload,
#[error(transparent)]
Doc(#[from] radicle::identity::doc::DocError),
#[error(transparent)]
Project(#[from] radicle::identity::project::ProjectError),
#[error(transparent)]
Branch(#[from] git::fmt::Error),
#[error(transparent)]
Json(#[from] serde_json::Error),
#[error(transparent)]
Git(#[from] git::raw::Error),
}
impl Error {
/// The code the frontend branches on; every other error shows its message.
pub const fn code(&self) -> &'static str {
match self {
Self::Exists(_) => "ActorError.Exists",
Self::Ambiguous(_) => "ActorError.Ambiguous",
Self::NotController => "ActorError.NotController",
Self::PayloadNewer => "ActorError.PayloadNewer",
Self::NotFetched(_) => "ActorError.NotFetched",
Self::CopyStuck(_) => "ActorError.CopyStuck",
_ => "UnknownError",
}
}
}
/// A key of the actor as Desktop shows it.
#[derive(Clone, Debug, Serialize, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export)]
#[ts(export_to = "actor/")]
pub struct ActorKey {
#[ts(as = "String")]
pub did: Did,
/// The node alias, local to this machine and no part of the profile.
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(as = "Option<String>", optional)]
pub alias: Option<Alias>,
pub bound: bool,
pub controller: bool,
/// Seconds since the epoch.
#[ts(type = "number")]
pub added_at: i64,
}
/// An actor as Desktop shows it: the local one, or one the local key may
/// join.
#[derive(Clone, Debug, Serialize, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export)]
#[ts(export_to = "actor/")]
pub struct ActorInfo {
#[ts(as = "String")]
pub rid: RepoId,
pub kind: ActorKind,
/// The founding key first, then the other bound keys, then the
/// controllers that are not bound.
pub keys: Vec<ActorKey>,
/// How many controllers must agree on a profile edit.
pub threshold: usize,
/// How many controllers must accept an identity change.
pub majority: usize,
/// The payload is from a newer client, so Desktop must not change it.
pub payload_newer: bool,
/// Unset when the default branch has no readable profile yet.
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub profile: Option<ActorProfile>,
/// The profile is from a newer client, so Desktop must not rewrite it.
pub profile_newer: bool,
/// The profile file cannot be read; a save replaces it.
pub profile_unreadable: bool,
/// The commit the profile was read from.
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(as = "Option<String>", optional)]
pub head: Option<git::Oid>,
/// Identity changes open for the controllers' votes.
pub pending: Vec<ActorRevision>,
/// The other controllers' versions of the profile that are not behind
/// the one shown, when this key publishes alone; a save replaces them.
pub forks: Vec<ActorFork>,
}
/// Another controller's version of the profile, on a branch that is not
/// behind the one this key reads.
#[derive(Clone, Debug, Serialize, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export)]
#[ts(export_to = "actor/")]
pub struct ActorFork {
#[ts(as = "String")]
pub did: Did,
/// The commit that controller's branch is on.
#[ts(as = "String")]
pub head: git::Oid,
/// Unset when that version holds no profile this Desktop can read.
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub profile: Option<ActorProfile>,
/// The profile as it was where the two versions split. Unset when they
/// split at no one commit, or that commit holds no profile this Desktop
/// can read in full.
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub base: Option<ActorProfile>,
/// What that version changed since the two split, as a unified diff of
/// the profile cleaned as it is for display. Unset when `base` is, or
/// that version holds no profile this Desktop can read.
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub changes: Option<String>,
/// That version changed files other than the profile since the two
/// split or, when they split at no one commit, holds other files that
/// differ from the version shown. A save here leaves those changes out.
pub other_files: bool,
/// That version is from a newer client, so Desktop must not replace it.
pub profile_newer: bool,
}
/// A change to the actor's identity. One open for votes applies once a
/// majority of the controllers accept it. What it adds, removes and lowers is
/// told against the identity it was proposed on.
#[derive(Clone, Debug, Serialize, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export)]
#[ts(export_to = "actor/")]
pub struct ActorRevision {
#[ts(as = "String")]
pub id: git::Oid,
#[ts(as = "String")]
pub author: Did,
/// Seconds since the epoch.
#[ts(type = "number")]
pub created_at: i64,
/// The keys it adds or gives another role, with the roles they get.
pub added: Vec<ActorKey>,
#[ts(as = "Vec<String>")]
pub removed: Vec<Did>,
/// How many controllers a profile edit needs after the change, if it
/// lowers that.
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub threshold: Option<usize>,
/// The controllers that accepted it, the author among them.
#[ts(as = "Vec<String>")]
pub accepted: Vec<Did>,
/// The controllers that rejected it. The change stays open until it can no
/// longer reach a majority.
#[ts(as = "Vec<String>")]
pub rejected: Vec<Did>,
/// It changes more than Desktop can show, so Desktop must not sign it.
pub unreadable: bool,
pub state: RevisionState,
}
/// One version of the profile in the history of the one shown.
#[derive(Clone, Debug, Serialize, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export)]
#[ts(export_to = "actor/")]
pub struct ProfileEdit {
#[ts(as = "String")]
pub commit: git::Oid,
/// The versions it was saved over: none for the first version, several
/// for a save that joined versions that had split.
#[ts(as = "Vec<String>")]
pub parents: Vec<git::Oid>,
/// Seconds since the epoch, by the clock of the device that saved it.
#[ts(type = "number")]
pub saved_at: i64,
/// The key of the device that saved it, as the commit records it, which
/// nothing verifies. Unset when the commit names no key.
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(as = "Option<String>")]
#[ts(optional)]
pub author: Option<Did>,
/// The fields of the profile, by their names in the file, that differ
/// from the first of `parents`, or that the first version sets; `avatar`
/// and `banner` also when the picture they name changed. Unset when this
/// version or that parent holds a profile this Desktop cannot read in
/// full.
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub fields: Option<Vec<String>>,
/// It is in the history of the profile `actor` shows. Otherwise it is on
/// this key's own branch, and waits for the other controllers.
pub live: bool,
}
/// The key an enrollment code would bind, shown before a controller approves
/// it.
#[derive(Clone, Debug, Serialize, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export)]
#[ts(export_to = "actor/")]
pub struct EnrollmentPreview {
#[ts(as = "String")]
pub did: Did,
/// The key's node alias, when this machine knows it.
#[serde(skip_serializing_if = "Option::is_none")]
#[ts(as = "Option<String>", optional)]
pub alias: Option<Alias>,
/// The key already controls the actor, as a recovery key does, and keeps
/// that role.
pub controller: bool,
}
@@ -0,0 +1,820 @@
//! The identity side of an actor repository: its payload, how a key consents
//! to join, and how the identity history resolves to an actor.
use std::collections::BTreeMap;
use std::str::FromStr;
use serde::{Deserialize, Serialize};
use radicle::cob;
use radicle::crypto::Signature;
use radicle::crypto::signature::Verifier as _;
use radicle::git;
use radicle::identity::doc::{Payload, PayloadId};
use radicle::identity::project::ProjectName;
use radicle::identity::{Did, Doc, Project, RepoId, Visibility};
use radicle::storage::ReadRepository;
use super::{Error, retain_fields};
/// The identity payload that marks a repository as an actor repository.
const PAYLOAD_ID: &str = "dev.radicle.actor";
/// The value in the payload's `keys` map that marks the founding key.
const ROOT_KEY: &str = "root";
/// The prefix of the statement a key signs to consent to joining an actor.
const CONSENT_PREFIX: &str = "rad-actor-consent-v1";
const PAYLOAD_VERSION: u32 = 1;
/// The most keys a payload may bind.
const MAX_KEYS: usize = 255;
/// The most actor repositories a payload may say it replaces.
const MAX_SUPERSEDES: usize = 16;
/// The fields of a payload of `PAYLOAD_VERSION`.
const PAYLOAD_FIELDS: &[&str] = &[
"version",
"type",
"keys",
"migrations",
"supersededBy",
"retired",
"supersedes",
];
/// The fields of a migration in such a payload.
const MIGRATION_FIELDS: &[&str] = &["from", "signature"];
/// The longest project name, in bytes.
const MAX_REPO_NAME: usize = 255;
fn payload_id() -> PayloadId {
PayloadId::from_str(PAYLOAD_ID).expect("PAYLOAD_ID is a valid payload id")
}
/// What the actor repository describes; any other value makes the payload
/// invalid.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "actor/")]
pub enum ActorKind {
#[default]
Person,
Agent,
Org,
}
impl ActorKind {
pub fn is_individual(self) -> bool {
matches!(self, Self::Person | Self::Agent)
}
}
/// A key's signed claim that it moved here from another actor.
/// Desktop copies it into every new revision as it is and never checks or acts on it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Migration {
from: String,
signature: String,
}
/// The `dev.radicle.actor` payload, read for the fields of `PAYLOAD_VERSION`.
/// A payload of that version must match its schema in them. What else a
/// payload holds, at any version, is left out, and such a payload is never
/// written back, see `is_newer`.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ActorPayload {
pub version: u32,
#[serde(rename = "type", default)]
pub kind: ActorKind,
/// Bound keys: the founding key maps to `root`, every other key to its
/// consent signature.
#[serde(default)]
pub keys: BTreeMap<Did, String>,
/// By the DID of the key that moved.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
migrations: BTreeMap<String, Migration>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub superseded_by: Option<RepoId>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub retired: bool,
/// The actor repositories this one replaces; a move counts only if the old
/// one names this one in `superseded_by`.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub supersedes: Vec<RepoId>,
/// The document held fields `PAYLOAD_VERSION` does not define.
#[serde(skip)]
undefined_fields: bool,
/// The payload is of a newer version and gives its kind, its keys, or
/// whether it has ended, in a form this version cannot read.
#[serde(skip)]
unsure: bool,
}
impl ActorPayload {
/// The payload an actor is created with.
fn founding(did: Did) -> Self {
Self {
version: PAYLOAD_VERSION,
kind: ActorKind::Person,
keys: BTreeMap::from([(did, ROOT_KEY.to_string())]),
migrations: BTreeMap::new(),
superseded_by: None,
retired: false,
supersedes: Vec::new(),
undefined_fields: false,
unsure: false,
}
}
/// Whether `doc` carries the payload at all, valid or not.
pub fn marks(doc: &Doc) -> bool {
doc.payload().contains_key(&payload_id())
}
/// The valid payload of `doc`, if any, see `ActorPayload`. A payload of a
/// newer version is always one.
pub fn of(doc: &Doc) -> Option<Self> {
let payload = doc.payload().get(&payload_id())?;
let version = payload.get("version")?.as_u64()?;
if version > u64::from(PAYLOAD_VERSION) {
return Some(Self::of_newer(version, payload.as_object()?));
}
let mut value = (**payload).clone();
let object = value.as_object_mut()?;
if object.get("supersededBy").is_some_and(|rid| rid.is_null()) {
return None;
}
let mut undefined_fields = retain_fields(object, PAYLOAD_FIELDS);
if let Some(migrations) = object.get_mut("migrations").and_then(|m| m.as_object_mut()) {
for migration in migrations.values_mut().filter_map(|m| m.as_object_mut()) {
undefined_fields |= retain_fields(migration, MIGRATION_FIELDS);
}
}
let mut payload: Self = serde_json::from_value(value).ok()?;
payload.undefined_fields = undefined_fields;
// The limits are those of `PAYLOAD_VERSION`'s schema.
let valid = payload.version >= 1
&& payload.keys.len() <= MAX_KEYS
&& payload.supersedes.len() <= MAX_SUPERSEDES
&& payload
.migrations
.keys()
.all(|did| did.starts_with("did:key:"));
valid.then_some(payload)
}
/// A payload of a newer `version`, read for what this version knows of
/// it. It is an actor's whatever it holds, and it is never written back.
/// A value this version cannot read counts as absent; where that leaves
/// the actor's kind, its ending or its keys open, the payload is `unsure`.
fn of_newer(version: u64, object: &serde_json::Map<String, serde_json::Value>) -> Self {
let kind = object
.get("type")
.map(|kind| serde_json::from_value(kind.clone()).ok());
let retired = object.get("retired").map(|retired| retired.as_bool());
let superseded_by = object
.get("supersededBy")
.filter(|rid| !rid.is_null())
.map(|rid| rid.as_str().and_then(|rid| rid.parse().ok()));
// Entry by entry: the keys this version reads keep their binding. One
// it cannot read still leaves the payload `unsure`, so the actor is
// shown to none of them as theirs.
let entries = object.get("keys").and_then(|keys| keys.as_object());
let keys = entries
.into_iter()
.flatten()
.filter_map(|(did, binding)| Some((did.parse().ok()?, binding.as_str()?.to_string())))
.collect::<BTreeMap<Did, String>>();
let keys_read = entries.is_some_and(|entries| entries.len() == keys.len());
let supersedes = object
.get("supersedes")
.and_then(|rids| rids.as_array())
.into_iter()
.flatten()
.filter_map(|rid| rid.as_str()?.parse().ok())
.collect();
Self {
version: u32::try_from(version).unwrap_or(u32::MAX),
unsure: kind == Some(None)
|| retired == Some(None)
|| superseded_by == Some(None)
|| !keys_read,
kind: kind.flatten().unwrap_or_default(),
keys,
// Nothing here acts on the migrations.
migrations: BTreeMap::new(),
superseded_by: superseded_by.flatten(),
retired: retired.flatten().unwrap_or_default(),
supersedes,
undefined_fields: false,
}
}
/// Whether the payload holds more than this version knows: it is of a
/// newer version, or holds fields `PAYLOAD_VERSION` does not define. Such
/// a payload must not be written back.
pub(super) fn is_newer(&self) -> bool {
self.version > PAYLOAD_VERSION || self.undefined_fields
}
}
/// One version of a repository's identity document.
#[derive(Clone, Debug)]
pub struct IdentityDocRevision {
pub commit: git::Oid,
/// When the revision was committed, in seconds since the epoch.
pub time: i64,
pub doc: Doc,
}
impl From<&cob::identity::Revision> for IdentityDocRevision {
fn from(revision: &cob::identity::Revision) -> Self {
Self {
commit: revision.id,
time: revision.timestamp.as_secs() as i64,
doc: revision.doc.clone(),
}
}
}
/// What the identity history of an actor repository establishes.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ResolvedActor {
pub kind: ActorKind,
/// Every key of the actor: the founding key first, then the other bound
/// keys, then the controllers that are not bound.
pub keys: Vec<ResolvedKey>,
/// The payload is newer than `PAYLOAD_VERSION`, so it must not be written
/// back.
pub payload_newer: bool,
/// The payload gives the actor's kind, its keys, or whether it has ended,
/// in a form this version cannot read, so it is not known to be live.
pub unsure: bool,
/// The actor has ended with no successor.
pub retired: bool,
/// The actor repository that replaces this one, as this actor claims it.
pub superseded_by: Option<RepoId>,
}
impl ResolvedActor {
/// The keys that act as the actor: their activity shows as the actor's.
pub fn bound_keys(&self) -> impl Iterator<Item = Did> + '_ {
self.keys.iter().filter(|k| k.bound).map(|k| k.did)
}
/// Whether the actor is known to be a person or an agent, neither
/// retired nor superseded; only such an actor can be joined or acted as.
pub fn is_live_individual(&self) -> bool {
self.kind.is_individual() && !self.retired && self.superseded_by.is_none() && !self.unsure
}
}
/// A key of the actor and its roles. A key can be bound, a controller, or both.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ResolvedKey {
pub did: Did,
/// Listed under `keys` with a valid consent, or the founding key.
pub bound: bool,
/// A delegate of the identity document.
pub controller: bool,
/// When the revision that gave the key its current role was committed.
pub added_at: i64,
}
/// The message a key signs to consent to joining the actor at `rid`. `parent`
/// ties it to one identity revision, so it cannot be reused.
fn consent_message(rid: RepoId, did: Did, parent: git::Oid) -> String {
format!("{CONSENT_PREFIX} {rid} {did} {parent}")
}
/// The actor that `rid`'s identity history describes, or `None` if it is not
/// an actor's.
pub fn resolve(rid: RepoId, history: &[IdentityDocRevision]) -> Option<ResolvedActor> {
let root = history.first()?;
let current = history.last()?;
ActorPayload::of(&root.doc)?;
let mut delegates = root.doc.delegates().iter();
let founding_key = match (delegates.next(), delegates.next()) {
(Some(founding_key), None) => *founding_key,
_ => return None,
};
let current_payload = ActorPayload::of(&current.doc)?;
// Each revision's raw `keys`, indexed like `history`, read even where the
// payload is not. A consent from before a key's removal does not count
// once the key comes back.
let keys_by_revision = history
.iter()
.map(|revision| raw_keys(revision.doc.payload()))
.collect::<Vec<_>>();
let mut keys = Vec::new();
for (did, binding) in &current_payload.keys {
// The revision that introduced the entry: the latest one where it is
// present and differs from its parent's.
let mut introduced = history.len() - 1;
while introduced > 0
&& keys_by_revision[introduced - 1]
.and_then(|keys| keys.get(&did.to_string()))
.and_then(serde_json::Value::as_str)
.is_some_and(|previous| previous == binding)
{
introduced -= 1;
}
let bound = if introduced == 0 {
binding == ROOT_KEY && *did == founding_key
} else {
let parent = history[introduced - 1].commit;
consent_signature(binding)
.is_some_and(|signature| consents(rid, *did, parent, &signature))
};
if bound {
keys.push(ResolvedKey {
did: *did,
bound: true,
controller: current.doc.is_delegate(did),
added_at: history[introduced].time,
});
}
}
keys.sort_by_key(|key| (key.did != founding_key, key.did));
for did in current.doc.delegates().iter() {
if keys.iter().any(|key| key.did == *did) {
continue;
}
// The revision that last made the key a delegate; if it was removed
// and added back, the one that added it back.
let mut introduced = history.len() - 1;
while introduced > 0 && history[introduced - 1].doc.is_delegate(did) {
introduced -= 1;
}
keys.push(ResolvedKey {
did: *did,
bound: false,
controller: true,
added_at: history[introduced].time,
});
}
Some(ResolvedActor {
kind: current_payload.kind,
keys,
payload_newer: current_payload.is_newer(),
unsure: current_payload.unsure,
retired: current_payload.retired,
superseded_by: current_payload.superseded_by,
})
}
/// Every accepted version of `repo`'s identity document, oldest first, each
/// built on the one before it.
pub fn identity_history<R: ReadRepository + cob::Store>(
repo: &R,
) -> Result<Vec<IdentityDocRevision>, Error> {
let identity = cob::identity::Identity::load(repo)?;
let mut history = Vec::new();
let mut next = Some(identity.current);
while let Some(id) = next {
let revision = identity.revision(&id).ok_or(Error::Missing(id))?;
history.push(IdentityDocRevision::from(revision));
next = revision.parent;
}
history.reverse();
Ok(history)
}
/// A proposed change to the actor's identity that controllers are still
/// voting on.
#[derive(Clone, Debug)]
pub struct OpenIdentityRevision {
pub id: git::Oid,
pub author: Did,
/// When it was proposed, in seconds since the epoch.
pub time: i64,
/// The identity document it proposes.
pub doc: Doc,
/// The controllers that accepted it, the author included.
pub accepted: Vec<Did>,
/// The controllers that rejected it.
pub rejected: Vec<Did>,
/// The actor if the change is accepted; `None` if it would no longer be
/// one.
pub resolved: Option<ResolvedActor>,
}
/// The changes to `repo`'s identity still open for votes, given its `history`.
pub fn open_revisions<R: ReadRepository + cob::Store>(
repo: &R,
rid: RepoId,
history: &[IdentityDocRevision],
) -> Result<Vec<OpenIdentityRevision>, Error> {
let identity = cob::identity::Identity::load(repo)?;
let open = identity
.revisions()
.filter(|revision| revision.is_active() && revision.parent == Some(identity.current))
.map(|revision| {
let mut proposed = history.to_vec();
proposed.push(IdentityDocRevision::from(revision));
OpenIdentityRevision {
id: revision.id,
author: *revision.author.id(),
time: revision.timestamp.as_secs() as i64,
doc: revision.doc.clone(),
accepted: revision.accepted().collect(),
rejected: revision.rejected().collect(),
resolved: resolve(rid, &proposed),
}
})
.collect();
Ok(open)
}
/// Where a change to the actor's identity stands.
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, ts_rs::TS)]
#[serde(rename_all = "camelCase")]
#[ts(export)]
#[ts(export_to = "actor/")]
pub enum RevisionState {
/// The controllers are still voting on it.
Open,
/// A majority of the controllers accepted it, and it applied.
Accepted,
/// A majority of the controllers rejected it.
Rejected,
/// It can no longer apply: another change was accepted first, or the
/// change it was built on was rejected.
Lapsed,
}
/// A change to the actor's identity that `open_revisions` does not give, or
/// the identity's first version.
#[derive(Clone, Debug)]
pub struct ClosedIdentityRevision {
pub id: git::Oid,
pub author: Did,
/// When it was proposed, in seconds since the epoch.
pub time: i64,
/// The identity document it proposed.
pub doc: Doc,
pub accepted: Vec<Did>,
pub rejected: Vec<Did>,
pub state: RevisionState,
/// The document it was proposed on, with the actor that one gave if it
/// gave one; `None` for the first version.
pub before: Option<(Doc, Option<ResolvedActor>)>,
/// The actor with the change applied; `None` if it would not be one.
pub after: Option<ResolvedActor>,
}
/// Every change to `repo`'s identity but those `open_revisions` gives, newest
/// first, the first version last: the ones that ended, and one still open
/// that waits on another open change. A change its author withdrew is not
/// among them: the identity keeps none it can list. Resolves the actor once
/// for each change and once for the version it was proposed on.
pub fn closed_revisions<R: ReadRepository + cob::Store>(
repo: &R,
rid: RepoId,
) -> Result<Vec<ClosedIdentityRevision>, Error> {
use cob::identity::{RejectedBy, State};
let identity = cob::identity::Identity::load(repo)?;
// The versions a change builds on, root first, whether or not they were
// accepted.
let line = |from: Option<git::Oid>| {
let mut line = Vec::new();
let mut next = from;
while let Some(id) = next {
let revision = identity.revision(&id).ok_or(Error::Missing(id))?;
line.push(IdentityDocRevision::from(revision));
next = revision.parent;
}
line.reverse();
Ok::<_, Error>(line)
};
let mut closed = Vec::new();
for revision in identity.revisions() {
let state = match revision.state {
State::Active if revision.parent == Some(identity.current) => continue,
State::Active => RevisionState::Open,
State::Accepted => RevisionState::Accepted,
State::Rejected(RejectedBy::Vote) => RevisionState::Rejected,
State::Rejected(RejectedBy::Sibling(_) | RejectedBy::Parent) => RevisionState::Lapsed,
State::Redacted(_) => continue,
};
let mut proposed = line(revision.parent)?;
let before = proposed
.last()
.map(|parent| (parent.doc.clone(), resolve(rid, &proposed)));
proposed.push(IdentityDocRevision::from(revision));
closed.push(ClosedIdentityRevision {
id: revision.id,
author: *revision.author.id(),
time: revision.timestamp.as_secs() as i64,
doc: revision.doc.clone(),
accepted: revision.accepted().collect(),
rejected: revision.rejected().collect(),
state,
before,
after: resolve(rid, &proposed),
});
}
closed.reverse();
Ok(closed)
}
const ENROLLMENT_PREFIX: &str = "rad-enroll:";
/// The code's version, which is the consent statement's.
const ENROLLMENT_VERSION: u8 = 0x01;
const ENROLLMENT_LEN: usize = 1 + 20 + 32 + 20 + 64;
/// A key's consent to joining an actor, as the joining key hands it to a
/// controller.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Enrollment {
pub rid: RepoId,
pub did: Did,
/// The identity revision the consent is anchored to.
pub parent: git::Oid,
pub signature: Signature,
}
impl Enrollment {
/// The consent of `signer`'s key to joining `rid` on top of `parent`.
pub fn sign(rid: RepoId, parent: git::Oid, signer: &impl radicle::crypto::Signer) -> Self {
let did = Did::from(*signer.public_key());
let signature = signer.sign(consent_message(rid, did, parent).as_bytes());
Self {
rid,
did,
parent,
signature,
}
}
/// The value of the key's entry under the payload's `keys`.
pub fn consent(&self) -> String {
multibase::encode(multibase::Base::Base58Btc, self.signature.to_bytes())
}
/// Whether the signature is the key's consent.
pub fn verifies(&self) -> bool {
consents(self.rid, self.did, self.parent, &self.signature)
}
/// The code the joining key shows: `rad-enroll:` and the enrollment in
/// base58.
pub fn encode(&self) -> String {
let mut bytes = Vec::with_capacity(ENROLLMENT_LEN);
bytes.push(ENROLLMENT_VERSION);
bytes.extend_from_slice(&sha1(&self.rid));
bytes.extend_from_slice(self.did.as_ref());
bytes.extend_from_slice(&sha1(&self.parent));
bytes.extend_from_slice(&self.signature.to_bytes());
format!(
"{ENROLLMENT_PREFIX}{}",
multibase::encode(multibase::Base::Base58Btc, bytes)
)
}
/// The enrollment in a code from `encode`, ignoring whitespace. It does not
/// check the signature; see `verifies`.
pub fn decode(code: &str) -> Result<Self, EnrollmentError> {
let code = code.split_whitespace().collect::<String>();
let encoded = code
.strip_prefix(ENROLLMENT_PREFIX)
.ok_or(EnrollmentError::Prefix)?;
let (base, bytes) = multibase::decode(encoded).map_err(|_| EnrollmentError::Encoding)?;
if base != multibase::Base::Base58Btc {
return Err(EnrollmentError::Encoding);
}
let Some((&version, rest)) = bytes.split_first() else {
return Err(EnrollmentError::Length);
};
if version != ENROLLMENT_VERSION {
return Err(EnrollmentError::Version(version));
}
if bytes.len() != ENROLLMENT_LEN {
return Err(EnrollmentError::Length);
}
let (rid, rest) = rest.split_at(20);
let (key, rest) = rest.split_at(32);
let (parent, signature) = rest.split_at(20);
let oid =
|bytes: &[u8]| git::Oid::from_sha1(bytes.try_into().expect("the slice is 20 bytes"));
let key: [u8; 32] = key.try_into().expect("the slice is 32 bytes");
Ok(Self {
rid: RepoId::from(oid(rid)),
did: Did::from(radicle::crypto::PublicKey::from(key)),
parent: oid(parent),
signature: Signature::from_slice(signature).map_err(|_| EnrollmentError::Encoding)?,
})
}
}
fn sha1(oid: &git::Oid) -> [u8; 20] {
oid.into_sha1()
.expect("version 1 codes carry SHA-1 object ids")
}
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
pub enum EnrollmentError {
#[error("an enrollment code starts with {ENROLLMENT_PREFIX}")]
Prefix,
#[error("the enrollment code is not valid base58")]
Encoding,
#[error("the enrollment code has the wrong length")]
Length,
#[error("the enrollment code has version {0}, which this version does not know")]
Version(u8),
}
/// The actor payload's `keys` as raw JSON, so an edit changes those entries
/// and leaves the rest of the payload as it is.
fn raw_keys(
payloads: &BTreeMap<PayloadId, Payload>,
) -> Option<&serde_json::Map<String, serde_json::Value>> {
payloads
.get(&payload_id())
.and_then(|payload| payload.as_object())
.and_then(|payload| payload.get("keys"))
.and_then(|keys| keys.as_object())
}
/// `raw_keys`, for editing.
fn raw_keys_mut(
payloads: &mut BTreeMap<PayloadId, Payload>,
) -> Option<&mut serde_json::Map<String, serde_json::Value>> {
payloads
.get_mut(&payload_id())
.and_then(|payload| payload.as_object_mut())
.and_then(|payload| payload.get_mut("keys"))
.and_then(|keys| keys.as_object_mut())
}
/// `doc` with the enrolling key added to the payload's `keys`, and to the
/// delegates if `controller` is set. A delegate stays one. `Full` if the
/// payload has the most keys it can.
pub fn enrolled_doc(doc: &Doc, enrollment: &Enrollment, controller: bool) -> Result<Doc, Error> {
let mut raw = doc.clone().edit();
let keys = raw_keys_mut(&mut raw.payload).ok_or(Error::Payload)?;
keys.insert(
enrollment.did.to_string(),
serde_json::Value::String(enrollment.consent()),
);
if keys.len() > MAX_KEYS {
return Err(Error::Full);
}
if controller && !raw.delegates.contains(&enrollment.did) {
raw.delegates.push(enrollment.did);
}
Ok(Doc::try_from(raw)?)
}
/// `doc` without `did` in the payload's `keys` or the delegates, with the
/// threshold lowered to fit the delegates left.
pub fn removed_doc(doc: &Doc, did: &Did) -> Result<Doc, Error> {
let mut raw = doc.clone().edit();
raw_keys_mut(&mut raw.payload)
.ok_or(Error::Payload)?
.remove(&did.to_string());
raw.delegates.retain(|delegate| delegate != did);
raw.threshold = raw.threshold.min(raw.delegates.len());
Ok(Doc::try_from(raw)?)
}
/// `doc` with `retired` set in the actor payload and nothing else changed.
pub fn retired_doc(doc: &Doc) -> Result<Doc, Error> {
let mut raw = doc.clone().edit();
raw.payload
.get_mut(&payload_id())
.and_then(|payload| payload.as_object_mut())
.ok_or(Error::Payload)?
.insert("retired".into(), true.into());
Ok(Doc::try_from(raw)?)
}
/// Whether `proposed` changes only the actor's keys and the delegates, which
/// is all Desktop shows of a change. The threshold may only drop to fit the
/// delegates left.
pub fn changes_only_keys(doc: &Doc, proposed: &Doc) -> bool {
let fitted = doc.threshold().min(proposed.delegates().len());
let without_keys = |doc: &Doc| {
let mut raw = doc.clone().edit();
// The field goes whole, so an empty map and a missing one read alike.
if let Some(payload) = raw
.payload
.get_mut(&payload_id())
.and_then(|payload| payload.as_object_mut())
{
payload.remove("keys");
}
raw.delegates.clear();
raw.threshold = 0;
raw
};
proposed.threshold() == fitted && without_keys(doc) == without_keys(proposed)
}
/// The keys whose entry under the payload's `keys` differs between `doc` and
/// `proposed`.
pub fn changed_key_entries(doc: &Doc, proposed: &Doc) -> Vec<String> {
let entries = |doc: &Doc| raw_keys(doc.payload()).cloned().unwrap_or_default();
let (before, after) = (entries(doc), entries(proposed));
let mut changed = before
.keys()
.chain(after.keys())
.filter(|key| before.get(*key) != after.get(*key))
.cloned()
.collect::<Vec<_>>();
changed.sort();
changed.dedup();
changed
}
/// The signature in a `keys` entry, which must be multibase base58btc.
fn consent_signature(value: &str) -> Option<Signature> {
let (multibase::Base::Base58Btc, bytes) = multibase::decode(value).ok()? else {
return None;
};
Signature::from_slice(&bytes).ok()
}
/// Whether `signature` is `did`'s consent to joining `rid` on top of `parent`.
fn consents(rid: RepoId, did: Did, parent: git::Oid, signature: &Signature) -> bool {
let Ok(key) = radicle::crypto::VerifyingKey::try_from(&*did) else {
return false;
};
key.verify(consent_message(rid, did, parent).as_bytes(), signature)
.is_ok()
}
/// The repository name for a display name: the characters a project name
/// allows, any other run as one dash, at most 255 bytes. Falls back to
/// `fallback`, then to "actor". Dots alone count as empty, since a clone would
/// land in `.` or `..`.
pub fn repo_name(display_name: &str, fallback: &str) -> String {
fn clean(value: &str) -> String {
let name = value
.chars()
.map(|c| {
if c.is_alphanumeric() || ProjectName::ALLOWED_CHARS.contains(&c) {
c
} else {
'-'
}
})
.fold(String::new(), |mut name, c| {
if !(c == '-' && name.ends_with('-')) {
name.push(c);
}
name
});
let mut name = name.trim_matches('-').to_string();
while name.len() > MAX_REPO_NAME {
name.pop();
}
let name = name.trim_end_matches('-');
if name.chars().all(|c| c == '.') {
return String::new();
}
name.to_string()
}
[clean(display_name), clean(fallback)]
.into_iter()
.find(|name| !name.is_empty())
.unwrap_or_else(|| "actor".to_string())
}
/// The identity document of a new actor: a project payload, which a default
/// branch needs, and an actor payload with `did` as the only key.
pub fn initial_doc(name: &str, default_branch: &str, did: Did) -> Result<Doc, Error> {
let name = ProjectName::try_from(name.to_string())?;
let branch = git::fmt::RefString::try_from(default_branch)?;
let project = Project::new(name, "Actor repository".to_string(), branch).map_err(|errs| {
errs.into_iter()
.next()
.expect("a failed Project::new returns at least one error")
})?;
let payload = serde_json::to_value(ActorPayload::founding(did))?;
let doc = Doc::initial(project, did, Visibility::Public).with_edits(|raw| {
raw.payload.insert(payload_id(), Payload::from(payload));
})?;
Ok(doc)
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,692 @@
use std::str::FromStr;
use radicle::crypto::{Seed, Signer as _, SigningKey};
use radicle::git;
use radicle::identity::doc::{Payload, PayloadId};
use radicle::identity::project::ProjectName;
use radicle::identity::{Did, Doc, Project, RepoId, Visibility};
use super::*;
fn key(seed: u8) -> SigningKey {
SigningKey::from_seed(Seed::new([seed; 32]))
}
fn did_of(key: &SigningKey) -> Did {
Did::from(*key.public_key())
}
fn did() -> Did {
did_of(&key(7))
}
fn oid(byte: u8) -> git::Oid {
git::raw::Oid::from_bytes(&[byte; 20]).unwrap().into()
}
fn rid() -> RepoId {
RepoId::from(oid(42))
}
fn payload_id() -> PayloadId {
PayloadId::from_str("dev.radicle.actor").unwrap()
}
/// The payload an actor is created with, as `initial_doc` writes it.
fn founding_payload(did: Did) -> ActorPayload {
ActorPayload::of(&initial_doc("alice", "master", did).unwrap()).unwrap()
}
fn root() -> IdentityDocRevision {
IdentityDocRevision {
commit: oid(1),
time: 1,
doc: initial_doc("alice", "master", did()).unwrap(),
}
}
fn copy(revision: &IdentityDocRevision) -> IdentityDocRevision {
IdentityDocRevision {
commit: revision.commit,
time: revision.time,
doc: revision.doc.clone(),
}
}
fn bound(resolved: &ResolvedActor) -> Vec<Did> {
resolved.bound_keys().collect()
}
fn recovery(resolved: &ResolvedActor) -> Vec<Did> {
resolved
.keys
.iter()
.filter(|k| !k.bound && k.controller)
.map(|k| k.did)
.collect()
}
/// `previous` edited: `payload` replaces the actor payload and
/// `delegates`, when given, the delegate list.
fn revision(
previous: &IdentityDocRevision,
commit: u8,
payload: &ActorPayload,
delegates: Option<Vec<Did>>,
) -> IdentityDocRevision {
let value = serde_json::to_value(payload).unwrap();
let doc = previous
.doc
.clone()
.with_edits(|raw| {
raw.payload.insert(payload_id(), Payload::from(value));
if let Some(delegates) = delegates {
raw.delegates = delegates;
}
})
.unwrap();
IdentityDocRevision {
commit: oid(commit),
time: i64::from(commit),
doc,
}
}
fn with_payload(revision: &IdentityDocRevision, payload: serde_json::Value) -> IdentityDocRevision {
IdentityDocRevision {
commit: revision.commit,
time: revision.time,
doc: revision
.doc
.clone()
.with_edits(|raw| {
raw.payload.insert(payload_id(), Payload::from(payload));
})
.unwrap(),
}
}
fn consent(key: &SigningKey, parent: git::Oid) -> String {
Enrollment::sign(rid(), parent, key).consent()
}
#[test]
fn initial_doc_marks_the_actor() {
let did = did();
let doc = initial_doc("alice", "master", did).unwrap();
let payload = ActorPayload::of(&doc).unwrap();
assert_eq!(payload.version, 1);
assert_eq!(payload.kind, ActorKind::Person);
assert_eq!(payload.keys.get(&did).map(String::as_str), Some("root"));
assert_eq!(doc.delegates().iter().collect::<Vec<_>>(), vec![&did]);
assert_eq!(doc.project().unwrap().default_branch().as_str(), "master");
}
#[test]
fn a_plain_project_is_not_an_actor() {
let project = Project::new(
"alice".to_string().try_into().unwrap(),
String::new(),
git::fmt::RefString::try_from("master").unwrap(),
)
.unwrap();
let doc = Doc::initial(project, did(), Visibility::Public);
assert!(ActorPayload::of(&doc).is_none());
let plain = IdentityDocRevision {
commit: oid(1),
time: 1,
doc,
};
assert!(resolve(rid(), &[copy(&plain)]).is_none());
// The payload arriving in a later revision does not make an actor.
let later = revision(&plain, 2, &founding_payload(did()), None);
assert!(resolve(rid(), &[plain, later]).is_none());
}
#[test]
fn a_payload_of_this_version_is_held_to_its_schema() {
let root = root();
let moved = did_of(&key(9)).to_string();
let read =
|payload: &serde_json::Value| ActorPayload::of(&with_payload(&root, payload.clone()).doc);
use serde_json::json;
// Every field of the version survives a read and a write.
let whole = json!({
"version": 1,
"type": "person",
"keys": {},
"migrations": { moved.clone(): { "from": rid().to_string(), "signature": "z4jHmar" } },
"supersededBy": rid().to_string(),
"retired": true,
"supersedes": vec![rid().to_string(); 16],
});
let payload = read(&whole).unwrap();
assert!(!payload.is_newer());
assert_eq!(serde_json::to_value(&payload).unwrap(), whole);
// A migration is keyed by any `did:key`, not only one of a key this
// version can verify with.
let other_curve = json!({
"version": 1,
"migrations": {
"did:key:zQ3s":
{ "from": "a", "signature": "b" },
},
});
assert!(read(&other_curve).is_some());
for invalid in [
json!({ "version": 1, "migrations": [{ "from": "a", "signature": "b" }] }),
json!({ "version": 1, "migrations": { moved.clone(): { "from": "a" } } }),
json!({ "version": 1, "migrations": { "alice": { "from": "a", "signature": "b" } } }),
json!({ "version": 1, "supersededBy": null }),
json!({ "version": 1, "supersedes": vec![rid().to_string(); 17] }),
] {
assert!(read(&invalid).is_none(), "{invalid}");
}
}
#[test]
fn a_payload_with_fields_its_version_does_not_define_is_read_but_not_written() {
let root = root();
let did = did();
use serde_json::json;
for beyond in [
json!({ "version": 1, "keys": { did.to_string(): "root" }, "mood": "unknown" }),
json!({
"version": 1,
"keys": { did.to_string(): "root" },
"names": [{ "source": "dns", "name": "example.org" }],
}),
json!({
"version": 1,
"keys": { did.to_string(): "root" },
"migrations": { did.to_string(): { "from": "a", "signature": "b", "to": "c" } },
}),
] {
let revision = with_payload(&root, beyond.clone());
let payload = ActorPayload::of(&revision.doc).unwrap();
assert!(payload.is_newer(), "{beyond}");
let resolved = resolve(rid(), &[revision]).unwrap();
assert!(resolved.payload_newer, "{beyond}");
assert_eq!(bound(&resolved), vec![did], "{beyond}");
}
}
#[test]
fn the_payload_is_validated() {
let root = root();
let did = did();
use serde_json::json;
let plain = ActorPayload::of(&with_payload(&root, json!({ "version": 1 })).doc).unwrap();
assert_eq!(plain.kind, ActorKind::Person);
assert!(plain.keys.is_empty());
for invalid in [
json!({ "type": "person" }),
json!({ "version": 0 }),
json!({ "version": 1, "type": "robot" }),
json!({ "version": 1, "keys": { "alice": "root" } }),
] {
assert!(
ActorPayload::of(&with_payload(&root, invalid.clone()).doc).is_none(),
"{invalid}"
);
}
// A newer payload is read for every field this version acts on, whatever
// else it holds and whatever limits its own version sets.
let newer = with_payload(
&root,
json!({
"version": 2,
"type": "agent",
"keys": { did.to_string(): "root" },
"migrations": ["reshaped"],
"supersededBy": rid().to_string(),
"retired": true,
"supersedes": vec![rid().to_string(); 17],
"mood": "new",
}),
);
let payload = ActorPayload::of(&newer.doc).unwrap();
assert_eq!(payload.kind, ActorKind::Agent);
assert_eq!(payload.superseded_by, Some(rid()));
assert!(payload.retired);
assert_eq!(payload.supersedes.len(), 17);
let resolved = resolve(rid(), &[newer]).unwrap();
assert!(resolved.payload_newer);
assert_eq!(bound(&resolved), vec![did]);
}
#[test]
fn a_newer_payload_stays_an_actor_whatever_its_fields_hold() {
use serde_json::json;
let did = did();
let root = root();
let read = |payload: serde_json::Value| ActorPayload::of(&with_payload(&root, payload).doc);
// What cannot be read costs nothing else its reading: the key keeps its
// binding and the list its other entries.
let partly = with_payload(
&root,
json!({
"version": 2,
"keys": { did.to_string(): "root", "not a key": "root", did_of(&key(8)).to_string(): 7 },
"supersedes": [rid().to_string(), 7, "not an id"],
}),
);
let payload = ActorPayload::of(&partly.doc).unwrap();
assert_eq!(payload.keys.keys().collect::<Vec<_>>(), vec![&did]);
assert_eq!(payload.supersedes, vec![rid()]);
let resolved = resolve(rid(), &[partly]).unwrap();
assert!(resolved.payload_newer);
assert_eq!(bound(&resolved), vec![did]);
// Where the kind or the ending cannot be read, the actor is not known to
// be live, and says so.
for unread in [
json!({ "type": "team" }),
json!({ "type": 7 }),
json!({ "retired": "no" }),
json!({ "supersededBy": 7 }),
] {
let mut payload = json!({ "version": 2, "keys": { did.to_string(): "root" } });
payload
.as_object_mut()
.unwrap()
.extend(unread.as_object().unwrap().clone());
let resolved = resolve(rid(), &[with_payload(&root, payload)]).unwrap();
assert!(resolved.unsure, "{unread}");
assert!(!resolved.is_live_individual(), "{unread}");
assert_eq!(bound(&resolved), vec![did], "{unread}");
}
// Nor is it known whose it is where the keys cannot all be read.
for keys in [
json!({ "version": 2 }),
json!({ "version": 2, "keys": [did.to_string()] }),
json!({ "version": 2, "keys": { did.to_string(): { "role": "root" } } }),
] {
let resolved = resolve(rid(), &[with_payload(&root, keys.clone())]).unwrap();
assert!(resolved.unsure, "{keys}");
assert!(bound(&resolved).is_empty(), "{keys}");
}
// In a payload of this version, a kind it does not define is invalid.
assert!(read(json!({ "version": 1, "type": "team" })).is_none());
}
#[test]
fn the_root_decides_what_is_an_actor() {
let did = did();
let other = did_of(&key(8));
let root = root();
// Two delegates in the root do not make an actor.
let two = IdentityDocRevision {
commit: oid(1),
time: 1,
doc: root
.doc
.clone()
.with_edits(|raw| raw.delegates.push(other))
.unwrap(),
};
assert!(resolve(rid(), &[two]).is_none());
// A root entry for a key other than the founding one is ignored.
let mut payload = founding_payload(did);
payload.keys.insert(other, "root".to_string());
let claimed = with_payload(&root, serde_json::to_value(&payload).unwrap());
let resolved = resolve(rid(), &[claimed]).unwrap();
assert_eq!(bound(&resolved), vec![did]);
assert!(recovery(&resolved).is_empty());
// A current document that dropped the payload is not an actor.
let dropped = IdentityDocRevision {
commit: oid(2),
time: 2,
doc: root
.doc
.clone()
.with_edits(|raw| {
raw.payload.remove(&payload_id());
})
.unwrap(),
};
assert!(resolve(rid(), &[root, dropped]).is_none());
}
#[test]
fn a_key_is_bound_only_with_its_consent() {
let founding = key(7);
let joining = key(9);
let root = root();
let mut payload = founding_payload(did_of(&founding));
// Claimed without consent: a controller, not a bound key.
payload
.keys
.insert(did_of(&joining), "zinvalid".to_string());
let claimed = revision(
&root,
2,
&payload,
Some(vec![did_of(&founding), did_of(&joining)]),
);
let resolved = resolve(rid(), &[copy(&root), claimed]).unwrap();
assert_eq!(bound(&resolved), vec![did_of(&founding)]);
assert_eq!(recovery(&resolved), vec![did_of(&joining)]);
assert_eq!(
resolved.keys[1].added_at, 2,
"added when it became a delegate"
);
// Consent anchored to another revision does not count.
payload
.keys
.insert(did_of(&joining), consent(&joining, oid(3)));
let elsewhere = revision(&root, 2, &payload, None);
let resolved = resolve(rid(), &[copy(&root), elsewhere]).unwrap();
assert_eq!(bound(&resolved), vec![did_of(&founding)]);
// Consent by another key does not count.
payload
.keys
.insert(did_of(&joining), consent(&founding, root.commit));
let forged = revision(&root, 2, &payload, None);
let resolved = resolve(rid(), &[copy(&root), forged]).unwrap();
assert_eq!(bound(&resolved), vec![did_of(&founding)]);
// Consent to joining another actor does not count.
let elsewhere = Enrollment::sign(RepoId::from(oid(43)), root.commit, &joining).consent();
payload.keys.insert(did_of(&joining), elsewhere);
let replayed = revision(&root, 2, &payload, None);
let resolved = resolve(rid(), &[copy(&root), replayed]).unwrap();
assert_eq!(bound(&resolved), vec![did_of(&founding)]);
// The right signature in another multibase does not count either.
let signature = Enrollment::sign(rid(), root.commit, &joining)
.signature
.to_bytes();
payload.keys.insert(
did_of(&joining),
multibase::encode(multibase::Base::Base64, signature),
);
let base64 = revision(&root, 2, &payload, None);
let resolved = resolve(rid(), &[copy(&root), base64]).unwrap();
assert_eq!(bound(&resolved), vec![did_of(&founding)]);
// Consent anchored to the head it extends binds the key, and stays
// bound through later revisions that carry the entry forward.
payload
.keys
.insert(did_of(&joining), consent(&joining, root.commit));
let enrolled = revision(&root, 2, &payload, None);
let mut later_payload = payload.clone();
later_payload.kind = ActorKind::Agent;
let later = revision(&enrolled, 3, &later_payload, None);
let resolved = resolve(rid(), &[copy(&root), copy(&enrolled), later]).unwrap();
assert_eq!(bound(&resolved), vec![did_of(&founding), did_of(&joining)]);
assert_eq!(resolved.kind, ActorKind::Agent);
assert!(recovery(&resolved).is_empty());
assert_eq!(resolved.keys[0].added_at, 1);
assert_eq!(
resolved.keys[1].added_at, 2,
"added when enrolled, not when carried forward"
);
assert!(!resolved.keys[1].controller);
// Removing the entry and restating the old statement later does not
// bind the key again: the anchor has moved.
let mut removed_payload = later_payload.clone();
removed_payload.keys.remove(&did_of(&joining));
let removed = revision(&enrolled, 3, &removed_payload, None);
let restated = revision(&removed, 4, &later_payload, None);
let resolved = resolve(rid(), &[root, enrolled, removed, restated]).unwrap();
assert_eq!(bound(&resolved), vec![did_of(&founding)]);
}
#[test]
fn a_revision_that_cannot_be_read_is_stepped_over() {
let did = did();
let root = root();
let unreadable = with_payload(
&root,
serde_json::json!({ "version": 1, "type": "weather", "keys": { did.to_string(): "root" } }),
);
assert!(ActorPayload::of(&unreadable.doc).is_none());
let repaired = revision(&unreadable, 3, &founding_payload(did), None);
// The founding key stays bound: its entry is unchanged since the root,
// and the bad revision in between is no introduction.
let resolved = resolve(rid(), &[copy(&root), unreadable, repaired]).unwrap();
assert_eq!(bound(&resolved), vec![did]);
}
#[test]
fn a_consent_is_not_replayed_through_an_unreadable_revision() {
let founding = key(7);
let joining = key(9);
let root = root();
let mut payload = founding_payload(did_of(&founding));
payload
.keys
.insert(did_of(&joining), consent(&joining, root.commit));
let joined = revision(&root, 2, &payload, None);
assert_eq!(
bound(&resolve(rid(), &[copy(&root), copy(&joined)]).unwrap()),
vec![did_of(&founding), did_of(&joining)]
);
// A revision that cannot be read drops the key, and the next one adds it
// back with the consent from before: that consent names the root as its
// parent, which the revision adding it back does not extend.
let dropped = with_payload(
&joined,
serde_json::json!({
"version": 1, "type": "weather", "keys": { did_of(&founding).to_string(): "root" },
}),
);
let replayed = revision(&dropped, 4, &payload, None);
let resolved = resolve(rid(), &[copy(&root), joined, dropped, replayed]).unwrap();
assert_eq!(bound(&resolved), vec![did_of(&founding)]);
}
#[test]
fn lifecycle_flags_are_read() {
let root = root();
let mut payload = founding_payload(did());
payload.retired = true;
let retired = revision(&root, 2, &payload, None);
assert!(resolve(rid(), &[copy(&root), retired]).unwrap().retired);
payload.retired = false;
payload.superseded_by = Some(RepoId::from(oid(9)));
let superseded = revision(&root, 2, &payload, None);
assert_eq!(
resolve(rid(), &[root, superseded]).unwrap().superseded_by,
Some(RepoId::from(oid(9)))
);
}
#[test]
fn the_repo_name_derives_from_the_display_name() {
assert_eq!(repo_name("Alice Liddell", "alice"), "Alice-Liddell");
assert_eq!(repo_name("cloudhead", "alice"), "cloudhead");
assert_eq!(repo_name("日本", "alice"), "日本");
assert_eq!(repo_name("!!!", "alice"), "alice");
assert_eq!(repo_name("!!!", "j@t"), "j-t");
assert_eq!(repo_name("", ""), "actor");
assert_eq!(repo_name("John Doe", "alice"), "John-Doe");
// A clone of `.` or `..` would land in the current or the parent directory.
assert_eq!(repo_name("..", "alice"), "alice");
assert_eq!(repo_name(".", "."), "actor");
let long = repo_name(&"日".repeat(255), "alice");
assert!(long.len() <= 255 && long.starts_with("日"));
assert!(ProjectName::try_from(long).is_ok(), "fits a project name");
}
fn code_bytes(code: &str) -> Vec<u8> {
multibase::decode(code.strip_prefix("rad-enroll:").unwrap())
.unwrap()
.1
}
fn code_of(bytes: &[u8]) -> String {
format!(
"rad-enroll:{}",
multibase::encode(multibase::Base::Base58Btc, bytes)
)
}
#[test]
fn an_enrollment_code_carries_the_consent_whole() {
let joining = key(9);
let enrollment = Enrollment::sign(rid(), oid(3), &joining);
let code = enrollment.encode();
// A paste that wrapped the code still reads.
let wrapped = format!("{}\n {}", &code[..40], &code[40..]);
assert_eq!(Enrollment::decode(&wrapped).unwrap(), enrollment);
assert_eq!(code_bytes(&code).len(), 137);
let decoded = Enrollment::decode(&code).unwrap();
assert_eq!(decoded, enrollment);
assert_eq!(decoded.did, did_of(&joining));
assert!(decoded.verifies());
}
#[test]
fn an_enrollment_code_that_is_not_one_is_refused() {
let code = Enrollment::sign(rid(), oid(3), &key(9)).encode();
let bytes = code_bytes(&code);
// The version byte decides first, whatever follows it.
let mut newer = bytes.clone();
newer[0] = 0x02;
newer.truncate(40);
assert_eq!(
Enrollment::decode(&code_of(&newer)),
Err(EnrollmentError::Version(2))
);
assert_eq!(
Enrollment::decode(&code_of(&bytes[..100])),
Err(EnrollmentError::Length)
);
assert_eq!(
Enrollment::decode(code.strip_prefix("rad-enroll:").unwrap()),
Err(EnrollmentError::Prefix)
);
// A code for another anchor carries a signature that is not the
// key's consent to it.
let mut moved = bytes;
moved[1 + 20 + 32] ^= 0xff;
let moved = Enrollment::decode(&code_of(&moved)).unwrap();
assert!(!moved.verifies());
}
#[test]
fn an_approval_binds_the_key_and_keeps_the_rest_of_the_payload() {
let migrations = serde_json::json!({
did().to_string(): { "from": rid().to_string(), "signature": "z4jHmar" },
});
let root = with_payload(
&root(),
serde_json::json!({
"version": 1,
"type": "person",
"keys": { did().to_string(): "root" },
"migrations": migrations.clone(),
}),
);
let joining = key(9);
let enrollment = Enrollment::sign(rid(), root.commit, &joining);
for controller in [true, false] {
let doc = enrolled_doc(&root.doc, &enrollment, controller).unwrap();
let id = PayloadId::from_str("dev.radicle.actor").unwrap();
let payload = &**doc.payload().get(&id).unwrap();
assert_eq!(payload["migrations"], migrations);
let next = IdentityDocRevision {
commit: oid(2),
time: 2,
doc,
};
let resolved = resolve(rid(), &[root.clone(), next]).unwrap();
let key = resolved
.keys
.iter()
.find(|key| key.did == did_of(&joining))
.unwrap();
assert!(key.bound);
assert_eq!(key.controller, controller);
}
}
#[test]
fn a_removal_needs_the_keys_it_removes_from() {
let root = with_payload(
&root(),
serde_json::json!({ "version": 1, "type": "person" }),
);
assert!(matches!(
removed_doc(&root.doc, &did_of(&key(9))),
Err(Error::Payload)
));
// An empty map of keys and none at all are the same to a vote.
let empty = with_payload(
&root,
serde_json::json!({ "version": 1, "type": "person", "keys": {} }),
);
assert!(changes_only_keys(&root.doc, &empty.doc));
}
/// What another client has to produce from the same inputs: the key of seed 9
/// joining `rid()` on top of `oid(3)`.
#[test]
fn the_consent_and_the_code_are_fixed_to_the_byte() {
use radicle::crypto::signature::Verifier as _;
const SIGNED: &str =
"zp3FoCpC5kviWaZojkW9C4oktXW253yuxfcsQwaFKkKy8LEBZgTxucUTCfDCropNBKqokohCTZEqCQoGWHad4U2k";
const CODE: &str = "rad-enroll:zPXUVBCd7FA4epFwD8Das7hXuxxTXVHBBKxV3qsjBkBTCzp96L5U49q9mvikdWz69LAHWFGmJ2HR7rUzPyFUMsyzPaNRcBpZhaFCFD6Q7hGWwbm5BPiNhMTCMi6qRFebGqiwGrX5aTG5Hk3BajC4DAdr6R7VbgUowtFKs5sWmo3okrYfnj1DJ6jhh1i";
let joining = did_of(&key(9));
let enrollment = Enrollment::sign(rid(), oid(3), &key(9));
// The statement: the prefix, then the actor, the joining key and the
// anchor in their textual forms, one space apart.
let statement = format!(
"rad-actor-consent-v1 rad:zb56iBSEKUikofQ1eb4cGFfpsstM {joining} 0303030303030303030303030303030303030303"
);
let verifier = radicle::crypto::VerifyingKey::try_from(&*joining).unwrap();
assert!(
verifier
.verify(statement.as_bytes(), &enrollment.signature)
.is_ok()
);
assert_eq!(enrollment.consent(), SIGNED);
// The code: the version, the actor, the joining key, the anchor and the
// signature, raw and with nothing between them.
let mut bytes = vec![0x01];
bytes.extend([42; 20]);
bytes.extend_from_slice(joining.as_ref());
bytes.extend([3; 20]);
bytes.extend(enrollment.signature.to_bytes());
assert_eq!(code_bytes(CODE), bytes);
assert_eq!(enrollment.encode(), CODE);
}
@@ -0,0 +1,583 @@
//! The profile file of an actor repository: its limits, how its text is
//! cleaned, and how it is read and written.
use serde::{Deserialize, Serialize};
use unicode_normalization::UnicodeNormalization as _;
use radicle::git;
use super::{Error, retain_fields};
/// Where the profile lives, relative to the root of the default branch.
pub const PROFILE_PATH: &str = ".radicle/profile.json";
const PROFILE_VERSION: u32 = 1;
/// The limits on the profile file's strings, in characters, and on its links.
const MAX_STRING: usize = 255;
const MAX_LABEL: usize = 64;
const MAX_LINKS: usize = 16;
/// The most bytes a profile file is read with; a valid one is a few hundred.
const MAX_PROFILE_BYTES: usize = 64 * 1024;
/// The most bytes a picture saved with the profile may have. Every node that
/// has the profile copies its pictures and keeps the earlier ones.
const MAX_AVATAR_BYTES: usize = 1024 * 1024;
const MAX_BANNER_BYTES: usize = 2 * 1024 * 1024;
/// The pictures a save takes, by what their content is, and the extension
/// each is saved under.
const IMAGE_TYPES: &[(&str, &str)] = &[
("image/png", "png"),
("image/jpeg", "jpg"),
("image/webp", "webp"),
("image/gif", "gif"),
];
/// The pictures to save in the repository with a profile, each the base64 of
/// an image file: a PNG, JPEG, WebP or GIF of at most 1 MiB for the avatar
/// and 2 MiB for the banner. The kind is told from the first bytes of the
/// file, and the rest is not decoded: what is saved may not show.
#[derive(Clone, Debug, Default, Deserialize, ts_rs::TS)]
#[ts(export)]
#[ts(export_to = "actor/")]
pub struct ProfileImages {
#[serde(default)]
#[ts(optional)]
pub avatar: Option<String>,
#[serde(default)]
#[ts(optional)]
pub banner: Option<String>,
}
/// A picture that passed the checks of `ProfileImages::place`.
#[derive(Debug)]
pub struct ProfileImage {
/// The file's name without its extension, which says what it is for.
stem: &'static str,
/// Where it is saved, relative to the root of the default branch.
path: String,
bytes: Vec<u8>,
}
impl ProfileImages {
/// `profile` with the field of each picture naming the file it is saved
/// as, and the pictures to save. The error names the field and what is
/// wrong with its picture: not base64, too large, or not an image of a
/// kind that is taken.
pub fn place(
self,
mut profile: ActorProfile,
) -> Result<(ActorProfile, Vec<ProfileImage>), String> {
use base64::Engine as _;
let fields = [
("avatar", self.avatar, MAX_AVATAR_BYTES, &mut profile.avatar),
("banner", self.banner, MAX_BANNER_BYTES, &mut profile.banner),
];
let mut images = Vec::new();
for (stem, encoded, limit, field) in fields {
let Some(encoded) = encoded else { continue };
let bytes = base64::engine::general_purpose::STANDARD
.decode(encoded)
.map_err(|_| format!("the {stem} picture is not base64"))?;
if bytes.len() > limit {
return Err(format!(
"the {stem} picture is {} KiB, and the limit is {} KiB",
bytes.len().div_ceil(1024),
limit / 1024
));
}
let kind = infer::get(&bytes).map(|kind| kind.mime_type());
let Some((_, extension)) = IMAGE_TYPES.iter().find(|(mime, _)| Some(*mime) == kind)
else {
return Err(format!(
"the {stem} picture must be a PNG, JPEG, WebP or GIF image, and this is {}",
kind.unwrap_or("none of them")
));
};
let path = format!("{stem}.{extension}");
*field = Some(path.clone());
images.push(ProfileImage { stem, path, bytes });
}
Ok((profile, images))
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
#[serde(deny_unknown_fields)]
#[ts(export_to = "actor/")]
pub struct ProfileLink {
pub url: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub label: Option<String>,
}
/// The contents of `.radicle/profile.json`. A file of `PROFILE_VERSION` must
/// match the schema exactly; a newer one is read for its known fields.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[ts(export_to = "actor/")]
pub struct ActorProfile {
pub version: u32,
pub display_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub full_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub pronouns: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub bio: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub location: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub timezone: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub avatar: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub banner: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub links: Vec<ProfileLink>,
}
const PROFILE_FIELDS: &[&str] = &[
"version",
"displayName",
"fullName",
"pronouns",
"bio",
"location",
"timezone",
"avatar",
"banner",
"links",
];
const LINK_FIELDS: &[&str] = &["url", "label"];
/// Text as it is displayed or compared: one line, without control or
/// invisible characters, then NFC, so that what is left composes; trimmed.
/// A line break or a tab stands between words, so a space takes its place.
fn clean_text(value: &str) -> String {
// The character before, of those that stay.
let mut before = None;
value
.chars()
.filter_map(|c| {
let is_break = c.is_control() && c.is_whitespace();
let c = if is_break { ' ' } else { c };
// A break after a space adds nothing to it.
let dropped = is_hidden(c)
|| (is_emoji_selector(c) && !before.is_some_and(takes_selector))
|| (is_break && before == Some(' '));
if dropped {
return None;
}
before = Some(c);
Some(c)
})
.nfc()
.collect::<String>()
.trim()
.to_string()
}
fn is_hidden(c: char) -> bool {
c.is_control() || is_invisible(c)
}
/// The two variation selectors that pick an emoji's text or picture form.
fn is_emoji_selector(c: char) -> bool {
matches!(c, '\u{FE0E}' | '\u{FE0F}')
}
/// Whether a selector after `c` can change what shows: after a symbol or a
/// digit it can, after a letter or a space it only hides in the text.
fn takes_selector(c: char) -> bool {
!(c.is_alphabetic() || c.is_whitespace() || is_emoji_selector(c))
}
/// Characters that do not show and can make one name look like another: the
/// line separators, and what Unicode says to ignore when text is drawn. Those
/// are the bidirectional marks, the zero-width characters, the fillers, the
/// tags and the variation selectors, but for the two of `is_emoji_selector`.
/// What is drawn with one of them loses its form: a joined emoji, the flag
/// of a region, the variant of an ideograph.
fn is_invisible(c: char) -> bool {
matches!(
c,
'\u{00AD}'
| '\u{034F}'
| '\u{061C}'
| '\u{115F}'..='\u{1160}'
| '\u{17B4}'..='\u{17B5}'
| '\u{180B}'..='\u{180F}'
| '\u{200B}'..='\u{200F}'
| '\u{2028}'..='\u{202E}'
| '\u{2060}'..='\u{206F}'
| '\u{3164}'
| '\u{FE00}'..='\u{FE0D}'
| '\u{FEFF}'
| '\u{FFA0}'
| '\u{FFF0}'..='\u{FFF8}'
| '\u{1BCA0}'..='\u{1BCA3}'
| '\u{1D173}'..='\u{1D17A}'
| '\u{E0000}'..='\u{E0FFF}'
)
}
/// Whether `name` shows nothing once cleaned; the braille blank is a
/// character that draws as a space.
fn is_blank(name: &str) -> bool {
clean_text(name)
.chars()
.all(|c| c.is_whitespace() || c == '\u{2800}' || is_emoji_selector(c))
}
const LINK_SCHEMES: &[&str] = &["https", "http", "mailto", "rad"];
const IMAGE_SCHEMES: &[&str] = &["https", "http"];
/// A web URL, or a path relative to the repository root. A path may not hold
/// `%`, since a browser decodes `%2e%2e` to `..`.
fn is_image_ref(value: &str) -> bool {
if value.contains(':') {
return has_scheme(value, IMAGE_SCHEMES);
}
!value.contains('\\')
&& !value.contains('%')
&& !value.starts_with('/')
&& !value.split('/').any(|part| part == "..")
}
fn has_scheme(url: &str, schemes: &[&str]) -> bool {
url.split_once(':').is_some_and(|(scheme, _)| {
schemes
.iter()
.any(|allowed| scheme.eq_ignore_ascii_case(allowed))
})
}
impl ActorProfile {
/// The first field that breaks a limit, as a message for the form.
pub fn validate(&self) -> Result<(), String> {
if is_blank(&self.display_name) {
return Err("display name is required".to_string());
}
let strings = [
("display name", Some(&self.display_name)),
("full name", self.full_name.as_ref()),
("pronouns", self.pronouns.as_ref()),
("bio", self.bio.as_ref()),
("location", self.location.as_ref()),
("time zone", self.timezone.as_ref()),
("avatar", self.avatar.as_ref()),
("banner", self.banner.as_ref()),
];
for (field, value) in strings {
if value.is_some_and(|v| v.chars().count() > MAX_STRING) {
return Err(format!("{field} cannot exceed {MAX_STRING} characters"));
}
}
// Other clients render these as links and images, so a scheme that
// runs code or reads local files never gets signed. Nor does an
// address with characters that do not show: cleaning it would point
// it somewhere else.
for (field, value) in [("avatar", &self.avatar), ("banner", &self.banner)] {
let Some(image) = value else { continue };
if image.chars().any(is_hidden) {
return Err(format!("{field} cannot hold characters that do not show"));
}
if !is_image_ref(image) {
return Err(format!(
"{field} must be a path in the repository or a web URL"
));
}
}
if self.links.len() > MAX_LINKS {
return Err(format!("at most {MAX_LINKS} links are allowed"));
}
for link in &self.links {
let length = link.url.chars().count();
if length == 0 || length > MAX_STRING {
return Err(format!("a link must be 1 to {MAX_STRING} characters"));
}
if link.url.chars().any(is_hidden) {
return Err("a link cannot hold characters that do not show".to_string());
}
if !has_scheme(&link.url, LINK_SCHEMES) {
return Err("a link must be a web URL, a mailto: address or a rad: URI".to_string());
}
if link
.label
.as_ref()
.is_some_and(|l| l.chars().count() > MAX_LABEL)
{
return Err(format!("a link label cannot exceed {MAX_LABEL} characters"));
}
}
Ok(())
}
/// The file as written to the repository: its text cleaned, its addresses
/// only trimmed, empty fields dropped. `validate` refuses an address with
/// characters that do not show.
pub fn normalized(mut self) -> Self {
self.version = PROFILE_VERSION;
self.rewritten(|address| address.trim().to_string())
}
/// The profile as it is displayed: every string cleaned, addresses too,
/// and a name that shows nothing left empty.
fn cleaned(self) -> Self {
let mut cleaned = self.rewritten(clean_text);
if is_blank(&cleaned.display_name) {
cleaned.display_name.clear();
}
cleaned
}
/// Every text cleaned with `clean_text`, the image and link addresses
/// passed through `address`, empty optional fields dropped.
fn rewritten(mut self, address: impl Fn(&str) -> String) -> Self {
fn kept(value: Option<String>, rewrite: impl Fn(&str) -> String) -> Option<String> {
value.map(|v| rewrite(&v)).filter(|v| !v.is_empty())
}
self.display_name = clean_text(&self.display_name);
self.full_name = kept(self.full_name, clean_text);
self.pronouns = kept(self.pronouns, clean_text);
self.bio = kept(self.bio, clean_text);
self.location = kept(self.location, clean_text);
self.timezone = kept(self.timezone, clean_text);
self.avatar = kept(self.avatar, &address);
self.banner = kept(self.banner, &address);
self.links = self
.links
.into_iter()
.map(|link| ProfileLink {
url: address(&link.url),
label: kept(link.label, clean_text),
})
.filter(|link| !link.url.is_empty())
.collect();
self
}
/// The profile in a file of any version, see `ActorProfile`.
fn from_json(bytes: &[u8]) -> Option<ReadProfile> {
let mut value: serde_json::Value = serde_json::from_slice(bytes).ok()?;
let version = value.get("version")?.as_u64()?;
if version == 0 {
return None;
}
let newer = version > u64::from(PROFILE_VERSION);
if newer {
let object = value.as_object_mut()?;
retain_fields(object, PROFILE_FIELDS);
if let Some(links) = object.get_mut("links").and_then(|l| l.as_array_mut()) {
for link in links.iter_mut().filter_map(|l| l.as_object_mut()) {
retain_fields(link, LINK_FIELDS);
}
}
}
let profile: Self = serde_json::from_value(value).ok()?;
Some(ReadProfile {
profile: profile.cleaned(),
newer,
})
}
fn to_json(&self) -> Result<Vec<u8>, serde_json::Error> {
let mut bytes = serde_json::to_vec_pretty(self)?;
bytes.push(b'\n');
Ok(bytes)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ReadProfile {
pub profile: ActorProfile,
/// The file is newer than `PROFILE_VERSION`; writing it back would drop
/// fields.
pub newer: bool,
}
/// What a commit's tree holds at `PROFILE_PATH`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ProfileFile {
/// No file there.
Missing,
/// A file this version cannot read: not JSON, not its version's schema, or
/// over `MAX_PROFILE_BYTES`. A save replaces it, so the user is told.
Unreadable,
Read(Box<ReadProfile>),
}
/// `parent`'s tree, or an empty one, with `profile` at `PROFILE_PATH`.
pub fn profile_tree<'a>(
repo: &'a git::raw::Repository,
parent: Option<&git::raw::Tree<'a>>,
profile: &ActorProfile,
) -> Result<git::raw::Tree<'a>, Error> {
profile_tree_with(repo, parent, profile, &[], &[])
}
/// As `profile_tree`, with `images` saved at the root. An `avatar` or `banner`
/// picture at the root that the profile no longer names is left out of the
/// tree. One the profile names that `parent` lacks is taken from the first of
/// `others` that has it, so a version merged in keeps its picture; where
/// `parent` has a file of that name, that one stays. `Profile` if a folder is
/// where a picture would be saved.
pub fn profile_tree_with<'a>(
repo: &'a git::raw::Repository,
parent: Option<&git::raw::Tree<'a>>,
profile: &ActorProfile,
images: &[ProfileImage],
others: &[git::raw::Tree<'a>],
) -> Result<git::raw::Tree<'a>, Error> {
let blob = repo.blob(&profile.to_json()?)?;
let empty;
let baseline = match parent {
Some(tree) => tree,
None => {
empty = repo.find_tree(repo.treebuilder(None)?.write()?)?;
&empty
}
};
let is_file = |entry: &git2::TreeEntry| entry.kind() == Some(git2::ObjectType::Blob);
let mut update = git2::build::TreeUpdateBuilder::new();
update.upsert(PROFILE_PATH, blob, git::raw::FileMode::Blob);
for (stem, named) in [("avatar", &profile.avatar), ("banner", &profile.banner)] {
let named = named.as_deref();
let earlier = IMAGE_TYPES
.iter()
.map(|(_, extension)| format!("{stem}.{extension}"))
.filter(|path| Some(path.as_str()) != named)
.filter(|path| baseline.get_name(path).is_some_and(|entry| is_file(&entry)));
for path in earlier {
update.remove(path);
}
if let Some(image) = images.iter().find(|image| image.stem == stem) {
if baseline
.get_name(&image.path)
.is_some_and(|entry| !is_file(&entry))
{
return Err(Error::Profile(format!(
"the repository has a folder named {}, where the {stem} picture is saved",
image.path
)));
}
update.upsert(
image.path.as_str(),
repo.blob(&image.bytes)?,
git::raw::FileMode::Blob,
);
} else if let Some(path) = named.filter(|path| !path.contains(':')) {
let path = std::path::Path::new(path);
let theirs = || {
others
.iter()
.find_map(|tree| tree.get_path(path).ok().filter(is_file))
};
if baseline.get_path(path).is_err()
&& let Some(entry) = theirs()
{
update.upsert(path, entry.id(), git::raw::FileMode::Blob);
}
}
}
let tree = update.create_updated(repo, baseline)?;
Ok(repo.find_tree(tree)?)
}
/// The fields in which `to` differs from `from`, by their names in the file.
/// `None` is a version with no profile file, which sets no field.
pub fn changed_fields(from: Option<&ActorProfile>, to: Option<&ActorProfile>) -> Vec<&'static str> {
let unset = ActorProfile {
version: PROFILE_VERSION,
display_name: String::new(),
full_name: None,
pronouns: None,
bio: None,
location: None,
timezone: None,
avatar: None,
banner: None,
links: Vec::new(),
};
let (from, to) = (from.unwrap_or(&unset), to.unwrap_or(&unset));
let fields = [
("displayName", from.display_name != to.display_name),
("fullName", from.full_name != to.full_name),
("pronouns", from.pronouns != to.pronouns),
("bio", from.bio != to.bio),
("location", from.location != to.location),
("timezone", from.timezone != to.timezone),
("avatar", from.avatar != to.avatar),
("banner", from.banner != to.banner),
("links", from.links != to.links),
];
fields
.into_iter()
.filter_map(|(field, changed)| changed.then_some(field))
.collect()
}
/// What turns the profile `from` into `to`, as a unified diff of the file
/// each would be saved as.
pub fn profile_changes(from: &ActorProfile, to: &ActorProfile) -> Result<String, Error> {
let path = std::path::Path::new(PROFILE_PATH);
let (from, to) = (from.to_json()?, to.to_json()?);
let mut patch = git2::Patch::from_buffers(&from, Some(path), &to, Some(path), None)?;
Ok(String::from_utf8_lossy(&patch.to_buf()?).into_owned())
}
/// The profile in `commit`'s tree. A directory or a submodule at the path
/// counts as no file.
pub fn read_profile(
repo: &git::raw::Repository,
commit: git::Oid,
) -> Result<ProfileFile, git::raw::Error> {
let tree = repo.find_commit(commit.into())?.tree()?;
let Ok(entry) = tree.get_path(std::path::Path::new(PROFILE_PATH)) else {
return Ok(ProfileFile::Missing);
};
if entry.kind() != Some(git::raw::ObjectType::Blob) {
return Ok(ProfileFile::Missing);
}
// The size comes from the object's header, so a file over the limit is
// never loaded.
let (size, _) = repo.odb()?.read_header(entry.id())?;
if size > MAX_PROFILE_BYTES {
return Ok(ProfileFile::Unreadable);
}
let object = entry.to_object(repo)?;
let Some(blob) = object.as_blob() else {
return Ok(ProfileFile::Missing);
};
Ok(
ActorProfile::from_json(blob.content()).map_or(ProfileFile::Unreadable, |read| {
ProfileFile::Read(Box::new(read))
}),
)
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,550 @@
use super::*;
fn profile(display_name: &str) -> ActorProfile {
ActorProfile {
version: 1,
display_name: display_name.to_string(),
full_name: None,
pronouns: None,
bio: None,
location: None,
timezone: None,
avatar: None,
banner: None,
links: vec![],
}
}
#[test]
fn profile_validation_follows_the_schema() {
assert!(profile(" ").validate().is_err());
let long = ActorProfile {
bio: Some("é".repeat(255)),
..profile("alice")
};
assert!(
long.validate().is_ok(),
"limits count characters, not bytes"
);
let too_long = ActorProfile {
bio: Some("é".repeat(256)),
..profile("alice")
};
assert!(too_long.validate().unwrap_err().starts_with("bio"));
let many = ActorProfile {
links: (0..17)
.map(|i| ProfileLink {
url: format!("https://example.com/{i}"),
label: None,
})
.collect(),
..profile("alice")
};
assert!(many.validate().unwrap_err().contains("16 links"));
let link = |url: &str| ActorProfile {
links: vec![ProfileLink {
url: url.to_string(),
label: None,
}],
..profile("alice")
};
for url in [
"HTTPS://example.com",
"mailto:a@b.c",
"rad:z3gqcJUoA1n9HaHKufZs5FCSGazv5",
] {
assert!(link(url).validate().is_ok(), "{url}");
}
for url in ["javascript:alert(1)", "file:///etc/passwd", "example.com"] {
assert!(link(url).validate().is_err(), "{url}");
}
let avatar = |value: &str| ActorProfile {
avatar: Some(value.to_string()),
..profile("alice")
};
for value in ["images/avatar.png", "https://example.com/a.png"] {
assert!(avatar(value).validate().is_ok(), "{value}");
}
for value in [
"javascript:alert(1)",
"/etc/passwd",
"//evil.example/a.png",
"../a.png",
// A browser folds a percent-encoded dot into `..`.
"%2e%2e/%2e%2e/a.png",
] {
assert!(
avatar(value).validate().unwrap_err().starts_with("avatar"),
"{value}"
);
}
}
#[test]
fn profile_text_is_cleaned_for_display() {
// A decomposed "é", a bidirectional override and a control character.
let cleaned = ActorProfile {
full_name: Some(" Ali\u{202E}ce\u{0} ".to_string()),
..profile("Zoe\u{301}")
}
.normalized();
assert_eq!(cleaned.display_name, "Zo\u{e9}");
assert_eq!(cleaned.full_name.as_deref(), Some("Alice"));
// Zero-width characters, direction marks and line separators hide in a
// name and go the same way.
let hidden = profile("\u{FEFF}al\u{200B}i\u{200E}c\u{2028}e\u{061C}").normalized();
assert_eq!(hidden.display_name, "alice");
}
#[test]
fn a_line_break_becomes_a_space() {
let cleaned = ActorProfile {
bio: Some(" Rust dev\r\n\u{0}Berlin\n".to_string()),
location: Some("Ber\tlin".to_string()),
..profile("Al\nice")
}
.normalized();
// No string keeps a control character, and no two words run together.
assert_eq!(cleaned.bio.as_deref(), Some("Rust dev Berlin"));
assert_eq!(cleaned.display_name, "Al ice");
assert_eq!(cleaned.location.as_deref(), Some("Ber lin"));
}
/// A tree with `json` as its only file, at the profile path, whatever it
/// holds.
fn profile_file_tree<'r>(repo: &'r git::raw::Repository, json: &[u8]) -> git::raw::Tree<'r> {
let empty = repo
.find_tree(repo.treebuilder(None).unwrap().write().unwrap())
.unwrap();
let tree = git2::build::TreeUpdateBuilder::new()
.upsert(
PROFILE_PATH,
repo.blob(json).unwrap(),
git::raw::FileMode::Blob,
)
.create_updated(repo, &empty)
.unwrap();
repo.find_tree(tree).unwrap()
}
/// Reads `json` as the profile file of a commit, as Desktop does.
fn read_file(json: &[u8]) -> ProfileFile {
let tmp = tempfile::tempdir().unwrap();
let repo = git::raw::Repository::init_bare(tmp.path()).unwrap();
let tree = profile_file_tree(&repo, json);
let signature = git::raw::Signature::now("alice", "alice@example.com").unwrap();
let commit = repo
.commit(None, &signature, &signature, "Profile", &tree, &[])
.unwrap();
read_profile(&repo, commit.into()).unwrap()
}
/// The profile `json` reads as, which the case expects to be one.
fn read_back(json: &[u8]) -> ReadProfile {
match read_file(json) {
ProfileFile::Read(read) => *read,
other => panic!("expected a profile, got {other:?}"),
}
}
#[test]
fn profile_files_are_read_by_version() {
let known = br#"{ "version": 1, "displayName": "alice" }"#;
let read = read_back(known);
assert_eq!(read.profile.display_name, "alice");
assert!(!read.newer);
// A file this version cannot read is told apart from no file, so a save
// does not replace it unannounced.
let unknown_field = br#"{ "version": 1, "displayName": "alice", "mood": "sunny" }"#;
assert_eq!(read_file(unknown_field), ProfileFile::Unreadable);
let unknown_link_field =
br#"{ "version": 1, "displayName": "alice", "links": [{ "url": "x", "icon": "y" }] }"#;
assert_eq!(read_file(unknown_link_field), ProfileFile::Unreadable);
assert_eq!(
read_file(br#"{ "displayName": "alice" }"#),
ProfileFile::Unreadable
);
assert_eq!(
read_file(br#"{ "version": 0, "displayName": "alice" }"#),
ProfileFile::Unreadable
);
assert_eq!(read_file(b"not json"), ProfileFile::Unreadable);
// A file over the size limit is not read at all, whatever it holds.
let mut padded = br#"{"version":1,"displayName":"Alice"}"#.to_vec();
assert!(matches!(read_file(&padded), ProfileFile::Read(_)));
padded.resize(MAX_PROFILE_BYTES + 1, b' ');
assert_eq!(read_file(&padded), ProfileFile::Unreadable);
let newer = br#"{ "version": 2, "displayName": "alice", "mood": "sunny", "links": [{ "url": "https://x", "icon": "y" }] }"#;
let read = read_back(newer);
assert!(read.newer);
assert_eq!(read.profile.display_name, "alice");
assert_eq!(read.profile.links[0].url, "https://x");
}
#[test]
fn links_and_images_another_client_wrote_are_read_whole() {
// The editor gets the file as it is, so the user sees what to fix.
let file = br#"{ "version": 1, "displayName": "alice", "avatar": "javascript:alert(1)",
"banner": "..\\..\\etc\\passwd", "links": [{ "url": "x" }, { "url": "javascript:alert(1)" },
{ "url": "https://x" }] }"#;
let read = read_back(file);
assert_eq!(read.profile.links.len(), 3);
assert_eq!(read.profile.avatar.as_deref(), Some("javascript:alert(1)"));
assert!(read.profile.validate().is_err());
}
#[test]
fn profile_round_trips_through_a_tree() {
let tmp = tempfile::tempdir().unwrap();
let repo = git::raw::Repository::init_bare(tmp.path()).unwrap();
let profile = ActorProfile {
full_name: Some("Alice Liddell".to_string()),
bio: Some(" Curiouser. ".to_string()),
links: vec![ProfileLink {
url: "https://example.com".to_string(),
label: Some("".to_string()),
}],
..profile("alice")
}
.normalized();
let signature = git::raw::Signature::now("alice", "alice@example.com").unwrap();
let tree = profile_tree(&repo, None, &profile).unwrap();
let commit = repo
.commit(None, &signature, &signature, "Create profile", &tree, &[])
.unwrap();
let ProfileFile::Read(read) = read_profile(&repo, commit.into()).unwrap() else {
panic!("the profile is read back");
};
let read = read.profile.clone();
assert_eq!(read.bio.as_deref(), Some("Curiouser."));
assert_eq!(read.links[0].label, None);
// A second write replaces the file and keeps the rest of the tree.
let updated = ActorProfile { bio: None, ..read };
let parent = repo.find_commit(commit).unwrap();
let tree = profile_tree(&repo, Some(&parent.tree().unwrap()), &updated).unwrap();
let commit = repo
.commit(
None,
&signature,
&signature,
"Edit profile",
&tree,
&[&parent],
)
.unwrap();
let ProfileFile::Read(read) = read_profile(&repo, commit.into()).unwrap() else {
panic!("the profile is read back");
};
let read = read.profile.clone();
assert_eq!(read.bio, None);
assert_eq!(read.full_name.as_deref(), Some("Alice Liddell"));
}
#[test]
fn characters_that_do_not_show_are_stripped() {
let hidden = [
'\u{00AD}',
'\u{034F}',
'\u{180E}',
'\u{2061}',
'\u{3164}',
'\u{FE00}',
'\u{FFA0}',
'\u{E0041}',
'\u{E0100}',
];
for c in hidden {
let cleaned = profile(&format!("al{c}ice")).normalized();
assert_eq!(cleaned.display_name, "alice", "U+{:04X}", u32::from(c));
}
// What is left composes, so cleaning twice changes nothing more.
let joined = profile("Zoe\u{034F}\u{301}").normalized();
assert_eq!(joined.display_name, "Zo\u{e9}");
// A selector that picks an emoji's form changes what shows, so it stays
// after a symbol or a digit. After a letter it shows nothing.
for emoji in ["\u{2764}\u{FE0F}", "1\u{FE0F}\u{20E3}"] {
assert_eq!(profile(emoji).normalized().display_name, emoji);
}
let lookalike = profile("al\u{FE0F}ice \u{FE0E}").normalized();
assert_eq!(lookalike.display_name, "alice");
}
#[test]
fn a_name_that_shows_nothing_is_no_name() {
let blanks = [
"\u{3164}",
"\u{2800}",
" \u{2800} \u{200B}",
"\u{FE0F}",
"\u{2800}\u{FE0F}",
];
for blank in blanks {
assert!(profile(blank).normalized().validate().is_err(), "{blank:?}");
assert!(profile(blank).validate().is_err(), "{blank:?} as given");
}
// Read from a file, such a name is empty, so that what shows the profile
// can tell there is none.
let read = read_back(br#"{ "version": 1, "displayName": "\u2800" }"#);
assert_eq!(read.profile.display_name, "");
}
#[test]
fn an_address_is_refused_not_rewritten() {
let hidden = "https://exa\u{00AD}mple.com";
let written = ActorProfile {
avatar: Some(format!(" {hidden} ")),
links: vec![ProfileLink {
url: hidden.to_string(),
label: None,
}],
..profile("alice")
}
.normalized();
assert_eq!(written.avatar.as_deref(), Some(hidden), "only trimmed");
assert_eq!(written.links[0].url, hidden);
assert!(written.validate().unwrap_err().starts_with("avatar"));
let link_only = ActorProfile {
avatar: None,
..written
};
assert!(link_only.validate().unwrap_err().starts_with("a link"));
// Read for display, it is cleaned like any other string.
let file = format!(r#"{{ "version": 1, "displayName": "alice", "avatar": "{hidden}" }}"#);
let read = read_back(file.as_bytes());
assert_eq!(read.profile.avatar.as_deref(), Some("https://example.com"));
}
/// The first bytes of a file of each kind, which is all that tells them apart.
const PNG: &[u8] = b"\x89PNG\r\n\x1a\na picture";
const JPEG: &[u8] = b"\xff\xd8\xff\xe0a picture";
const PDF: &[u8] = b"%PDF-1.4 a document";
fn encoded(bytes: &[u8]) -> Option<String> {
use base64::Engine as _;
Some(base64::engine::general_purpose::STANDARD.encode(bytes))
}
fn avatar(bytes: &[u8]) -> ProfileImages {
ProfileImages {
avatar: encoded(bytes),
banner: None,
}
}
/// The tree of `profile` saved over `parent` with `images`, next to `others`.
fn saved<'r>(
repo: &'r git::raw::Repository,
parent: Option<&git::raw::Tree<'r>>,
profile: ActorProfile,
images: ProfileImages,
others: &[git::raw::Tree<'r>],
) -> Result<git::raw::Tree<'r>, Error> {
let (profile, images) = images.place(profile).map_err(Error::Profile)?;
profile_tree_with(repo, parent, &profile, &images, others)
}
fn files(tree: &git::raw::Tree) -> Vec<String> {
tree.iter()
.map(|entry| entry.name().unwrap().to_owned())
.collect()
}
fn file(repo: &git::raw::Repository, tree: &git::raw::Tree, name: &str) -> Vec<u8> {
let entry = tree.get_name(name).unwrap();
repo.find_blob(entry.id()).unwrap().content().to_vec()
}
#[test]
fn a_picture_is_named_by_what_its_content_is() {
let images = ProfileImages {
avatar: encoded(JPEG),
banner: encoded(PNG),
};
let typed = ActorProfile {
avatar: Some("https://example.com/me.png".to_string()),
..profile("alice")
};
let (placed, pictures) = images.place(typed).unwrap();
assert_eq!(placed.avatar.as_deref(), Some("avatar.jpg"));
assert_eq!(placed.banner.as_deref(), Some("banner.png"));
assert_eq!(pictures.len(), 2);
// Without a picture the fields are the form's.
let (kept, pictures) = ProfileImages::default().place(profile("alice")).unwrap();
assert_eq!(kept, profile("alice"));
assert!(pictures.is_empty());
}
#[test]
fn a_picture_over_its_limit_or_of_no_taken_kind_is_refused() {
let sized = |bytes: usize| {
let mut picture = PNG.to_vec();
picture.resize(bytes, 0);
picture
};
let banner = |bytes: &[u8]| ProfileImages {
avatar: None,
banner: encoded(bytes),
};
assert!(
avatar(&sized(MAX_AVATAR_BYTES))
.place(profile("alice"))
.is_ok()
);
let refused = avatar(&sized(MAX_AVATAR_BYTES + 1))
.place(profile("alice"))
.unwrap_err();
assert!(refused.contains("avatar"));
// The banner has its own limit.
assert!(
banner(&sized(MAX_AVATAR_BYTES + 1))
.place(profile("alice"))
.is_ok()
);
let refused = banner(&sized(MAX_BANNER_BYTES + 1))
.place(profile("alice"))
.unwrap_err();
assert!(refused.contains("banner"));
let refused = banner(PDF).place(profile("alice")).unwrap_err();
assert!(refused.contains("banner") && refused.contains("application/pdf"));
assert!(avatar(b"").place(profile("alice")).is_err());
let not_base64 = ProfileImages {
avatar: Some("not base64!".to_string()),
banner: None,
};
assert!(not_base64.place(profile("alice")).is_err());
}
#[test]
fn a_picture_the_profile_stops_naming_leaves_the_tree() {
let tmp = tempfile::tempdir().unwrap();
let repo = git::raw::Repository::init_bare(tmp.path()).unwrap();
let none = ProfileImages::default;
let with_png = saved(&repo, None, profile("alice"), avatar(PNG), &[]).unwrap();
assert_eq!(files(&with_png), [".radicle", "avatar.png"]);
assert_eq!(file(&repo, &with_png, "avatar.png"), PNG);
let named = || ActorProfile {
avatar: Some("avatar.png".to_string()),
..profile("alice")
};
// A save that still names it keeps it.
let kept = saved(&repo, Some(&with_png), named(), none(), &[]).unwrap();
assert_eq!(files(&kept), [".radicle", "avatar.png"]);
// One of another kind takes its place.
let replaced = saved(&repo, Some(&with_png), named(), avatar(JPEG), &[]).unwrap();
assert_eq!(files(&replaced), [".radicle", "avatar.jpg"]);
// A cleared field, or one that names an address, has no file.
let cleared = saved(&repo, Some(&with_png), profile("alice"), none(), &[]).unwrap();
assert_eq!(files(&cleared), [".radicle"]);
let linked = ActorProfile {
avatar: Some("https://example.com/me.png".to_string()),
..profile("alice")
};
let linked = saved(&repo, Some(&with_png), linked, none(), &[]).unwrap();
assert_eq!(files(&linked), [".radicle"]);
}
#[test]
fn a_folder_where_a_picture_goes_is_not_replaced() {
let tmp = tempfile::tempdir().unwrap();
let repo = git::raw::Repository::init_bare(tmp.path()).unwrap();
let empty = saved(&repo, None, profile("alice"), ProfileImages::default(), &[]).unwrap();
let with_folder = git2::build::TreeUpdateBuilder::new()
.upsert(
"avatar.png/inside.txt",
repo.blob(b"kept").unwrap(),
git::raw::FileMode::Blob,
)
.create_updated(&repo, &empty)
.unwrap();
let with_folder = repo.find_tree(with_folder).unwrap();
let refused = saved(
&repo,
Some(&with_folder),
profile("alice"),
avatar(PNG),
&[],
);
assert!(matches!(refused, Err(Error::Profile(_))));
// Nor does a save that names no picture take it away.
let kept = saved(
&repo,
Some(&with_folder),
profile("alice"),
ProfileImages::default(),
&[],
)
.unwrap();
assert_eq!(files(&kept), [".radicle", "avatar.png"]);
}
#[test]
fn a_picture_only_a_merged_version_has_comes_along() {
let tmp = tempfile::tempdir().unwrap();
let repo = git::raw::Repository::init_bare(tmp.path()).unwrap();
let none = ProfileImages::default;
let mine = saved(&repo, None, profile("alice"), none(), &[]).unwrap();
let theirs = saved(&repo, None, profile("alice"), avatar(PNG), &[]).unwrap();
let named = || ActorProfile {
avatar: Some("avatar.png".to_string()),
..profile("alice")
};
let merged = saved(
&repo,
Some(&mine),
named(),
none(),
std::slice::from_ref(&theirs),
)
.unwrap();
assert_eq!(file(&repo, &merged, "avatar.png"), PNG);
// A profile that does not name it leaves it behind.
let without = saved(
&repo,
Some(&mine),
profile("alice"),
none(),
std::slice::from_ref(&theirs),
)
.unwrap();
assert_eq!(files(&without), [".radicle"]);
// Where both have a file of that name, the one saved over stays.
let other_bytes = b"\x89PNG\r\n\x1a\nanother picture";
let mine = saved(&repo, None, profile("alice"), avatar(other_bytes), &[]).unwrap();
let merged = saved(&repo, Some(&mine), named(), none(), &[theirs]).unwrap();
assert_eq!(file(&repo, &merged, "avatar.png"), other_bytes);
}
+12
View File
@@ -154,6 +154,17 @@ pub enum Error {
#[error("revision not found: {0}")]
RevisionNotFound(String),
/// Reading or writing an actor repository.
#[error(transparent)]
Actor(#[from] crate::actor::Error),
/// Reading a payload of an identity document.
#[error(transparent)]
Payload(#[from] radicle::identity::doc::PayloadError),
/// Changing an identity.
#[error(transparent)]
Identity(#[from] radicle::cob::identity::Error),
/// Commit not found in the repository.
#[error("commit not found: {0}")]
CommitNotFound(radicle::git::Oid),
@@ -271,6 +282,7 @@ impl Error {
"AliasError.InvalidAlias"
}
Error::FileTooLarge(_) => "PayloadError.TooLarge",
Error::Actor(error) => error.code(),
Error::ReviewExists => "PatchError.ReviewExists",
Error::CommitNotFound(_) => "RepoError.CommitNotFound",
Error::InvalidLocation(_) => "ArtifactError.InvalidLocation",
+3
View File
@@ -1,4 +1,5 @@
use traits::Profile;
use traits::actor::Actor;
use traits::artifact_node::ArtifactNode;
use traits::board::Boards;
use traits::cobs::Cobs;
@@ -12,6 +13,7 @@ use traits::release_mut::ReleasesMut;
use traits::repo::Repo;
use traits::thread::Thread;
pub mod actor;
pub mod artifact;
pub mod auth;
pub mod binaries;
@@ -34,6 +36,7 @@ pub struct AppState {
impl Boards for AppState {}
impl Repo for AppState {}
impl Actor for AppState {}
impl Thread for AppState {}
impl Cobs for AppState {}
impl Identity for AppState {}
+2
View File
@@ -31,6 +31,8 @@ pub struct RepoSummary {
/// False for a repository that is in storage but not seeded, which
/// `rad ls --all` shows as "local".
pub seeding: bool,
/// The repository is an actor's, a profile and not a project.
pub actor: bool,
}
#[derive(Serialize, TS)]
@@ -10,6 +10,7 @@ use crate::error::Error;
const ALIAS_SEARCH_LIMIT: usize = 50;
pub mod actor;
pub mod artifact_node;
pub mod board;
pub mod cobs;
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -13,6 +13,7 @@ use radicle::storage;
use radicle::storage::{ReadRepository, ReadStorage, RepositoryInfo, WriteStorage};
use radicle::{git, identity, node};
use crate::actor;
use crate::cobs;
use crate::diff;
use crate::diff::Diff;
@@ -426,6 +427,7 @@ pub trait Repo: Profile {
name: data.name,
private: doc.is_private(),
seeding,
actor: is_actor(storage, rid, &doc),
});
}
@@ -1096,7 +1098,15 @@ pub trait Repo: Profile {
let profile = self.profile();
let mut node = radicle::Node::new(profile.home().socket_from_env());
profile.seed(rid, node::policy::Scope::All, &mut node)?;
// A scope the user already set for the repository stays as it is.
let scope = match (*profile.policies()?).seed_policy(&rid)? {
Some(node::policy::SeedPolicy {
policy: node::policy::SeedingPolicy::Allow { scope },
..
}) => scope,
_ => node::policy::Scope::All,
};
profile.seed(rid, scope, &mut node)?;
// The policy alone only fetches once a seed next announces the repo,
// which a quiet one may not do for a long time. Fetch now, like
@@ -1209,6 +1219,28 @@ fn seed_candidates(
.collect()
}
/// Whether `rid`, with `doc` as its current document, is an actor's
/// repository: both its first document and `doc` hold a valid actor payload.
/// Reads the first document of a repository whose current one holds such a
/// payload, and of no other.
fn is_actor(storage: &storage::git::Storage, rid: identity::RepoId, doc: &Doc) -> bool {
if actor::ActorPayload::of(doc).is_none() {
return false;
}
let root = storage
.repository(rid)
.and_then(|repo| Ok(repo.identity_doc_at(repo.identity_root()?)?));
match root {
Ok(root) => actor::ActorPayload::of(&root.doc).is_some(),
Err(e) => {
log::warn!("Not able to tell whether {rid} is an actor's: {e}");
false
}
}
}
fn is_radicle_metadata(repo: &git2::Repository, oid: git::Oid) -> bool {
repo.find_commit(oid.into())
.and_then(|commit| commit.tree())
+212 -1
View File
@@ -4,7 +4,7 @@ use std::sync::Arc;
use axum::Router;
use axum::body::Bytes;
use axum::extract::{FromRequestParts, Request, State};
use axum::extract::{DefaultBodyLimit, FromRequestParts, Request, State};
use axum::middleware::{self, Next};
use axum::response::{IntoResponse, Json, Response};
use axum::routing::post;
@@ -22,6 +22,7 @@ use radicle::node::{NOTIFICATIONS_DB_FILE, NodeId};
use radicle::storage::{ReadRepository as _, ReadStorage as _};
use radicle::{git, identity};
use radicle_types as types;
use radicle_types::actor::ActorProfile;
use radicle_types::cobs::CobOptions;
use radicle_types::cobs::FromRadicleAction;
use radicle_types::cobs::issue;
@@ -37,6 +38,7 @@ use radicle_types::domain::patch::traits::PatchService;
use radicle_types::error::Error;
use radicle_types::outbound::sqlite::Sqlite;
use radicle_types::traits::Profile;
use radicle_types::traits::actor::Actor;
use radicle_types::traits::artifact_node::ArtifactNode;
use radicle_types::traits::board::Boards;
use radicle_types::traits::cobs::Cobs;
@@ -62,6 +64,7 @@ impl Boards for Context {}
impl Repo for Context {}
impl Cobs for Context {}
impl Identity for Context {}
impl Actor for Context {}
impl Inbox for Context {}
impl Thread for Context {}
impl Issues for Context {}
@@ -177,6 +180,43 @@ pub fn router(shared: Shared) -> Router {
.route("/update_board", post(update_board_handler))
.route("/rename_board", post(rename_board_handler))
.route("/set_board_columns", post(set_board_columns_handler))
// A save carries its pictures in the body.
.route(
"/create_actor",
post(create_actor_handler).layer(DefaultBodyLimit::max(PROFILE_BODY_BYTES)),
)
.route(
"/update_actor_profile",
post(update_actor_profile_handler).layer(DefaultBodyLimit::max(PROFILE_BODY_BYTES)),
)
.route("/joinable_actor", post(joinable_actor_handler))
.route("/join_actor", post(join_actor_handler))
.route("/approve_enrollment", post(approve_enrollment_handler))
.route(
"/approve_actor_revision",
post(approve_actor_revision_handler),
)
.route(
"/withdraw_actor_revision",
post(withdraw_actor_revision_handler),
)
.route(
"/reject_actor_revision",
post(reject_actor_revision_handler),
)
.route("/remove_actor_key", post(remove_actor_key_handler))
.route("/actors_of_key", post(actors_of_key_handler))
.route(
"/closed_actor_revisions",
post(closed_actor_revisions_handler),
)
.route(
"/actor_profile_history",
post(actor_profile_history_handler),
)
.route("/leave_actor", post(leave_actor_handler))
.route("/cancel_leave", post(cancel_leave_handler))
.route("/retire_actor", post(retire_actor_handler))
.route_layer(middleware::from_fn_with_state(
Arc::new(Mutex::new(())),
serialize_writes,
@@ -201,6 +241,8 @@ pub fn router(shared: Shared) -> Router {
.route("/list_repo_refs", post(list_repo_refs_handler))
.route("/list_canonical_tags", post(list_canonical_tags_handler))
.route("/identity_by_repo", post(identity_handler))
.route("/actor", post(actor_handler))
.route("/decode_enrollment", post(decode_enrollment_handler))
.route("/version", post(version_handler))
.route("/git_info", post(git_info_handler))
.route("/diff_stats", post(diff_stats_handler))
@@ -468,6 +510,175 @@ async fn identity_handler(
Ok::<_, Error>(Json(identity))
}
async fn actor_handler(Ctx(ctx): Ctx) -> impl IntoResponse {
Ok::<_, Error>(Json(ctx.actor()?))
}
/// Room for an avatar and a banner at their limits, as base64.
const PROFILE_BODY_BYTES: usize = 8 * 1024 * 1024;
#[derive(Deserialize)]
struct ActorProfileBody {
pub profile: ActorProfile,
#[serde(default)]
pub images: types::actor::ProfileImages,
pub opts: types::cobs::CobOptions,
}
async fn create_actor_handler(
Ctx(ctx): Ctx,
Json(ActorProfileBody {
profile,
images,
opts,
}): Json<ActorProfileBody>,
) -> impl IntoResponse {
Ok::<_, Error>(Json(ctx.create_actor(profile, images, opts)?))
}
async fn update_actor_profile_handler(
Ctx(ctx): Ctx,
Json(ActorProfileBody {
profile,
images,
opts,
}): Json<ActorProfileBody>,
) -> impl IntoResponse {
Ok::<_, Error>(Json(ctx.update_actor_profile(profile, images, opts)?))
}
async fn joinable_actor_handler(
Ctx(ctx): Ctx,
Json(RepoBody { rid }): Json<RepoBody>,
) -> impl IntoResponse {
Ok::<_, Error>(Json(ctx.joinable_actor(rid)?))
}
async fn join_actor_handler(
Ctx(ctx): Ctx,
Json(RepoBody { rid }): Json<RepoBody>,
) -> impl IntoResponse {
Ok::<_, Error>(Json(ctx.join_actor(rid)?))
}
#[derive(Deserialize)]
struct CodeBody {
pub code: String,
}
async fn decode_enrollment_handler(
Ctx(ctx): Ctx,
Json(CodeBody { code }): Json<CodeBody>,
) -> impl IntoResponse {
Ok::<_, Error>(Json(ctx.decode_enrollment(code)?))
}
#[derive(Deserialize)]
struct EnrollmentBody {
pub code: String,
pub controller: bool,
pub opts: types::cobs::CobOptions,
}
async fn approve_enrollment_handler(
Ctx(ctx): Ctx,
Json(EnrollmentBody {
code,
controller,
opts,
}): Json<EnrollmentBody>,
) -> impl IntoResponse {
Ok::<_, Error>(Json(ctx.approve_enrollment(code, controller, opts)?))
}
#[derive(Deserialize)]
struct RevisionBody {
pub id: radicle::git::Oid,
pub opts: types::cobs::CobOptions,
}
async fn approve_actor_revision_handler(
Ctx(ctx): Ctx,
Json(RevisionBody { id, opts }): Json<RevisionBody>,
) -> impl IntoResponse {
Ok::<_, Error>(Json(ctx.approve_actor_revision(id, opts)?))
}
async fn withdraw_actor_revision_handler(
Ctx(ctx): Ctx,
Json(RevisionBody { id, opts }): Json<RevisionBody>,
) -> impl IntoResponse {
Ok::<_, Error>(Json(ctx.withdraw_actor_revision(id, opts)?))
}
async fn reject_actor_revision_handler(
Ctx(ctx): Ctx,
Json(RevisionBody { id, opts }): Json<RevisionBody>,
) -> impl IntoResponse {
Ok::<_, Error>(Json(ctx.reject_actor_revision(id, opts)?))
}
#[derive(Deserialize)]
struct KeyBody {
pub did: identity::Did,
pub opts: types::cobs::CobOptions,
}
async fn remove_actor_key_handler(
Ctx(ctx): Ctx,
Json(KeyBody { did, opts }): Json<KeyBody>,
) -> impl IntoResponse {
Ok::<_, Error>(Json(ctx.remove_actor_key(did, opts)?))
}
async fn actors_of_key_handler(Ctx(ctx): Ctx) -> impl IntoResponse {
Ok::<_, Error>(Json(ctx.actors_of_key()?))
}
async fn closed_actor_revisions_handler(Ctx(ctx): Ctx) -> impl IntoResponse {
Ok::<_, Error>(Json(ctx.closed_actor_revisions()?))
}
#[derive(Deserialize)]
struct PageBody {
pub skip: Option<usize>,
pub take: Option<usize>,
}
async fn actor_profile_history_handler(
Ctx(ctx): Ctx,
Json(PageBody { skip, take }): Json<PageBody>,
) -> impl IntoResponse {
Ok::<_, Error>(Json(ctx.actor_profile_history(skip, take)?))
}
#[derive(Deserialize)]
struct RepoWriteBody {
pub rid: identity::RepoId,
pub opts: types::cobs::CobOptions,
}
async fn leave_actor_handler(
Ctx(ctx): Ctx,
Json(RepoWriteBody { rid, opts }): Json<RepoWriteBody>,
) -> impl IntoResponse {
Ok::<_, Error>(Json(ctx.leave_actor(rid, opts)?))
}
async fn cancel_leave_handler(
Ctx(ctx): Ctx,
Json(RepoWriteBody { rid, opts }): Json<RepoWriteBody>,
) -> impl IntoResponse {
Ok::<_, Error>(Json(ctx.cancel_leave(rid, opts)?))
}
async fn retire_actor_handler(
Ctx(ctx): Ctx,
Json(RepoWriteBody { rid, opts }): Json<RepoWriteBody>,
) -> impl IntoResponse {
Ok::<_, Error>(Json(ctx.retire_actor(rid, opts)?))
}
async fn list_repo_refs_handler(
Ctx(ctx): Ctx,
Json(RepoBody { rid }): Json<RepoBody>,
+3
View File
@@ -42,6 +42,7 @@
import Auth from "@app/views/auth/Auth.svelte";
import CreateIdentity from "@app/views/auth/CreateIdentity.svelte";
import InboxView from "@app/views/Inbox.svelte";
import ProfileView from "@app/views/profile/Profile.svelte";
import Board from "@app/views/repo/Board.svelte";
import Identity from "@app/views/repo/Identity.svelte";
import Issue from "@app/views/repo/Issue.svelte";
@@ -272,6 +273,8 @@
<GuideView {...$activeRouteStore.params} />
{:else if $activeRouteStore.resource === "repo.board"}
<Board {...$activeRouteStore.params} />
{:else if $activeRouteStore.resource === "profile"}
<ProfileView {...$activeRouteStore.params} />
{:else if $activeRouteStore.resource === "repo.home"}
<RepoHome {...$activeRouteStore.params} />
{:else if $activeRouteStore.resource === "repo.commits"}
+97
View File
@@ -0,0 +1,97 @@
<script lang="ts">
import type { ActorInfo } from "@bindings/actor/ActorInfo";
import UserAvatar from "@radicle-gui/ui/components/UserAvatar.svelte";
import { onDestroy } from "svelte";
import { RepoImages } from "@app/lib/repoImages";
interface Props {
// The profile whose picture is shown. Without a profile, or without a
// picture that can be shown, the pattern generated from an ID stands in:
// the profile's, or `fallbackId` when there is no profile.
actor: Pick<ActorInfo, "rid" | "head" | "profile"> | null;
fallbackId?: string;
styleWidth: string;
}
const { actor, fallbackId, styleWidth }: Props = $props();
const images = new RepoImages();
onDestroy(() => images.dispose());
const rid = $derived(actor?.rid);
const head = $derived(actor?.head);
// A value with a colon is a web address. It is not fetched: that would
// tell its host who is looking, each time the picture is shown.
const path = $derived.by(() => {
const named = actor?.profile?.avatar?.trim();
return named && !named.includes(":") ? named : undefined;
});
// The picture shown and the profile it belongs to. A save moves `head`
// whether or not it changed the picture, so the one shown stays until the
// next has loaded.
let src = $state<string>();
let shownOf: string | undefined;
let broken = $state(false);
// The profile names a picture, so the pattern stands in only once that
// picture has failed to load: it must not show for a moment before it.
const named = $derived(Boolean(rid && head && path));
let failed = $state(false);
function showPicture(url: string | undefined) {
src = url;
broken = false;
failed = url === undefined;
// Releases the pictures loaded before this one.
images.sweep();
}
$effect(() => {
if (rid !== shownOf) {
shownOf = rid;
src = undefined;
}
if (!rid || !head || !path) {
showPicture(undefined);
return;
}
let gone = false;
void images
.load(rid, head, path)
.then(image => {
if (!gone) showPicture(image?.url);
})
.catch((e: unknown) => {
console.warn("Could not load the profile's avatar", e);
if (!gone) showPicture(undefined);
});
return () => {
gone = true;
};
});
const patternId = $derived(actor?.rid ?? fallbackId);
</script>
<style>
img {
display: block;
object-fit: cover;
}
</style>
{#if src && !broken}
<img
style:width={styleWidth}
style:height={styleWidth}
{src}
alt="Avatar"
onerror={() => (broken = true)} />
{:else if patternId && (!named || failed || broken)}
<UserAvatar nodeId={patternId} {styleWidth} />
{/if}
+7 -6
View File
@@ -3,12 +3,11 @@
</script>
<script lang="ts">
import type { RepoSummary } from "@bindings/repo/RepoSummary";
import { z } from "zod";
import { nodeRunning } from "@app/lib/events";
import { invoke } from "@app/lib/invoke";
import { cachedListReposWithActors, invoke } from "@app/lib/invoke";
import { repoListScope } from "@app/lib/repoListScope";
import { seedTarget } from "@app/lib/seedRepo";
import useLocalStorage from "@app/lib/useLocalStorage.svelte";
import { twemoji } from "@app/lib/utils";
@@ -24,11 +23,10 @@
interface Props {
reload: () => Promise<void>;
repos: RepoSummary[];
seededNotReplicated: string[];
}
const { reload, repos, seededNotReplicated }: Props = $props();
const { reload, seededNotReplicated }: Props = $props();
let popoverExpanded: boolean = $state(false);
let rid = $state("");
@@ -61,10 +59,13 @@
return;
}
// The project list hides actor repositories, so this check uses the full
// list.
const stored = await cachedListReposWithActors(repoListScope.value);
const target = seedTarget(
rid,
seededNotReplicated,
repos.map(r => r.rid),
stored.map(r => r.rid),
);
if ("error" in target) {
validationMessage = target.error;
+3 -1
View File
@@ -634,7 +634,9 @@
<div class="body">
<div class="nav">
{#if !mini}
<IdentityButton config={sidebarData.config} />
<IdentityButton
config={sidebarData.config}
actor={sidebarData.actor} />
{/if}
<a
+7 -2
View File
@@ -210,8 +210,13 @@
<path
d="M7.89634 2.39647C9.0581 1.23471 10.9416 1.23471 12.1034 2.39647C13.2651 3.55823 13.2651 5.44174 12.1034 6.6035L7.35337 11.3535C6.60582 12.101 5.39388 12.101 4.64634 11.3535C3.89879 10.606 3.89879 9.39401 4.64634 8.64647L8.64634 4.64647L9.35337 5.3535L5.35337 9.3535C4.99634 9.71052 4.99634 10.2894 5.35337 10.6465C5.71039 11.0035 6.28931 11.0035 6.64634 10.6465L11.3963 5.89647C12.1676 5.12523 12.1676 3.87473 11.3963 3.1035C10.6251 2.33226 9.3746 2.33226 8.60337 3.1035L3.85337 7.8535C2.66792 9.03895 2.66792 10.961 3.85337 12.1465C5.03882 13.3319 6.96089 13.3319 8.14634 12.1465L12.6463 7.64647L13.3534 8.3535L8.85337 12.8535C7.27739 14.4295 4.72231 14.4295 3.14634 12.8535C1.57036 11.2775 1.57036 8.72244 3.14634 7.14647L7.89634 2.39647Z" />
{:else if name === "avatar-incognito"}
<path
d="M13.5 8C13.5 4.96243 11.0376 2.5 8 2.5C4.96243 2.5 2.5 4.96243 2.5 8C2.5 9.74051 3.3094 11.291 4.57129 12.2988C4.61586 12.0809 4.68106 11.8667 4.7666 11.6602C4.94249 11.2357 5.2005 10.8503 5.52539 10.5254C5.85028 10.2005 6.23569 9.94249 6.66016 9.7666C7.0848 9.59071 7.54037 9.5 8 9.5C8.45963 9.5 8.9152 9.59071 9.33984 9.7666C9.76431 9.94249 10.1497 10.2005 10.4746 10.5254C10.7995 10.8503 11.0575 11.2357 11.2334 11.6602C11.3189 11.8666 11.3832 12.081 11.4277 12.2988C12.69 11.291 13.5 9.74078 13.5 8ZM8 10.5C7.6717 10.5 7.34628 10.5648 7.04297 10.6904C6.73978 10.8161 6.46449 11.0004 6.23242 11.2324C6.00036 11.4645 5.81606 11.7398 5.69043 12.043C5.57752 12.3155 5.51565 12.6061 5.50391 12.9004C6.25321 13.2828 7.10103 13.5 8 13.5C8.89866 13.5 9.74601 13.2826 10.4951 12.9004C10.4834 12.6061 10.4225 12.3155 10.3096 12.043C10.1839 11.7398 9.99964 11.4645 9.76758 11.2324C9.53551 11.0004 9.26022 10.8161 8.95703 10.6904C8.65372 10.5648 8.32831 10.5 8 10.5ZM9 6.5C9 5.94772 8.55228 5.5 8 5.5C7.44772 5.5 7 5.94772 7 6.5C7 7.05228 7.44772 7.5 8 7.5C8.55228 7.5 9 7.05228 9 6.5ZM14.5 8C14.5 10.3005 13.3033 12.3194 11.5 13.4746V13.5H11.4619C10.4593 14.1324 9.27294 14.5 8 14.5C6.72706 14.5 5.54065 14.1324 4.53809 13.5H4.5V13.4746C2.69675 12.3194 1.5 10.3005 1.5 8C1.5 4.41015 4.41015 1.5 8 1.5C11.5899 1.5 14.5 4.41015 14.5 8ZM10 6.5C10 7.60457 9.10457 8.5 8 8.5C6.89543 8.5 6 7.60457 6 6.5C6 5.39543 6.89543 4.5 8 4.5C9.10457 4.5 10 5.39543 10 6.5Z" />
<g fill="none" stroke="currentColor">
<circle cx="8" cy="8" r="6" />
<circle cx="8" cy="6.5" r="1.5" />
<path
d="M5 13L5.87868 9.87868L10.1213 9.87868L11 13"
stroke-linecap="square" />
</g>
{:else if name === "badge"}
<path
d="M4.64602 8.34829L5.35313 7.64118L7.00488 9.29294L10.6613 5.63656L11.3684 6.34367L7.00488 10.7072L4.64602 8.34829Z" />
+22 -4
View File
@@ -1,13 +1,16 @@
<script lang="ts">
import type { ActorInfo } from "@bindings/actor/ActorInfo";
import type { Config } from "@bindings/config/Config";
import UserAvatar from "@radicle-gui/ui/components/UserAvatar.svelte";
import debounce from "lodash/debounce";
import { writeToClipboard } from "@app/lib/invoke";
import { labs } from "@app/lib/labs";
import { entityUrl } from "@app/lib/mentions";
import * as router from "@app/lib/router";
import { didFromPublicKey, explorerHost, truncateDid } from "@app/lib/utils";
import ActorAvatar from "@app/components/ActorAvatar.svelte";
import Button from "@app/components/Button.svelte";
import DropdownListItem from "@app/components/DropdownListItem.svelte";
import Icon from "@app/components/Icon.svelte";
@@ -16,9 +19,10 @@
interface Props {
config: Config;
actor: ActorInfo | null;
}
const { config }: Props = $props();
const { config, actor }: Props = $props();
let popoverExpanded: boolean = $state(false);
let copyIcon: "copy" | "checkmark" = $state("copy");
@@ -35,8 +39,9 @@
styleJustifyContent="flex-start"
active={popoverExpanded}
{onclick}>
<UserAvatar nodeId={config.publicKey} styleWidth="1rem" />
<span class="label">{config.alias}</span>
<!-- A profile looks the same on each of its devices. -->
<ActorAvatar {actor} fallbackId={config.publicKey} styleWidth="1rem" />
<span class="label">{actor?.profile?.displayName || config.alias}</span>
<span class="label" style:color="var(--color-text-tertiary)">
<Icon name={popoverExpanded ? "chevron-up" : "chevron-down"} />
</span>
@@ -48,6 +53,19 @@
style:border-radius="var(--border-radius-md)"
style:background-color="var(--color-surface-canvas)"
style:padding="0.25rem">
{#if labs.actorRepos}
<DropdownListItem
styleGap="0.5rem"
styleWidth="100%"
selected={false}
onclick={async () => {
closeFocused();
await router.push({ resource: "profile", tab: "profile" });
}}>
<Icon name="avatar-incognito" />
{actor ? "Profile" : "Set up profile"}
</DropdownListItem>
{/if}
<DropdownListItem
styleGap="0.5rem"
styleWidth="100%"
@@ -390,10 +390,12 @@
async function reloadRepos() {
invalidateReposSummary();
[repos, seededNotReplicated] = await Promise.all([
const [reloaded, fetching] = await Promise.all([
cachedListReposSummary(repoListScope.value),
invoke<string[]>("seeded_not_replicated"),
]);
repos = reloaded;
seededNotReplicated = fetching;
}
// The route loader already fetched the list for the scope in force, so the
@@ -1127,7 +1129,7 @@
data-flip
onclick={e => e.stopPropagation()}
role="none">
<AddRepoButton reload={reloadRepos} {repos} {seededNotReplicated} />
<AddRepoButton reload={reloadRepos} {seededNotReplicated} />
</span>
</div>
+6 -1
View File
@@ -4,7 +4,12 @@ import useLocalStorage from "@app/lib/useLocalStorage.svelte";
// One-off tips that can be dismissed permanently. Kept in a single list so
// settings can offer to bring all of them back.
export type HintId = "markdown" | "guide";
export type HintId =
| "markdown"
| "guide"
| "profile.permanence"
// One for each profile and number of its controllers.
| `profile.controllers:${string}`;
const storage = useLocalStorage("dismissedHints", z.array(z.string()), []);
+29 -2
View File
@@ -1,3 +1,4 @@
import type { ActorInfo } from "@bindings/actor/ActorInfo";
import type { AliasSuggestion } from "@bindings/cob/AliasSuggestion";
import type { DiffOptions } from "@bindings/cob/DiffOptions";
import type { Issue } from "@bindings/cob/issue/Issue";
@@ -17,6 +18,8 @@ import type { TreePath } from "@bindings/repo/TreePath";
import { cached } from "@radicle-gui/ui/lib/cached";
import * as tauri from "@tauri-apps/api/core";
import { labs } from "@app/lib/labs";
import { projectsOf } from "@app/lib/projects";
import type { RepoListScope } from "@app/lib/repoListScope";
export async function invoke<T = null>(
@@ -416,15 +419,39 @@ export const cachedGetCommitDiff = cached(
* is cached with a short TTL; mutations that change it (adding, seeding,
* unseeding) go through invalidateReposSummary().
*/
export const cachedListReposSummary = cached(
export const cachedListReposWithActors = cached(
(show: RepoListScope) =>
invoke<RepoSummary[]>("list_repos_summary", { show }),
show => `list_repos_summary:${show}`,
{ max: 2, ttl: 30_000 },
);
/**
* The repositories to list as projects, see `projectsOf`. Whatever lists
* repositories calls this; `cachedListReposWithActors` is for telling what is
* in storage.
*/
export async function cachedListReposSummary(
show: RepoListScope,
): Promise<RepoSummary[]> {
return projectsOf(await cachedListReposWithActors(show), labs.actorRepos);
}
/**
* Finding the local actor scans storage like the repo list does, and every
* route loads it while the lab is on, so it shares the list's caching and
* invalidation; a save or create clears it as well.
*/
export const cachedActor = cached(
() => invoke<ActorInfo | null>("actor"),
() => "actor",
{ max: 1, ttl: 30_000 },
);
// The sidebar loads the repositories and the actor together, so both go.
export function invalidateReposSummary(): void {
cachedListReposSummary.clear();
cachedListReposWithActors.clear();
cachedActor.clear();
}
export async function writeToClipboard(
+9
View File
@@ -3,6 +3,7 @@ import { z } from "zod";
import useLocalStorage from "@app/lib/useLocalStorage.svelte";
const boards = useLocalStorage("labs.boards", z.boolean(), false);
const actorRepos = useLocalStorage("labs.actorRepos", z.boolean(), false);
// Experimental features, off until turned on in Settings.
export const labs = {
@@ -13,4 +14,12 @@ export const labs = {
set boards(value: boolean) {
boards.value = value;
},
get actorRepos(): boolean {
return actorRepos.value;
},
set actorRepos(value: boolean) {
actorRepos.value = value;
},
};
+10
View File
@@ -0,0 +1,10 @@
import type { RepoSummary } from "@bindings/repo/RepoSummary";
// The repositories to show as projects: with the actor lab on, an actor
// repository is a profile and is never listed as one.
export function projectsOf(
repos: RepoSummary[],
actorLab: boolean,
): RepoSummary[] {
return actorLab ? repos.filter(repo => !repo.actor) : repos;
}
+24 -6
View File
@@ -130,12 +130,16 @@ async function navigate(
route: Route,
fragment?: string,
): Promise<void> {
// Boards are a Labs feature; while it's off a board link shows the
// repository instead, and the address says so.
const hidden = route.resource === "repo.board" && !labs.boards;
const newRoute: Route = hidden
? { resource: "repo.home", rid: route.rid }
: route;
// Boards and the profile are Labs features; while one is off its link
// shows the repository, or the inbox, instead, and the address says so.
const hidden =
(route.resource === "repo.board" && !labs.boards) ||
(route.resource === "profile" && !labs.actorRepos);
const newRoute: Route = !hidden
? route
: route.resource === "repo.board"
? { resource: "repo.home", rid: route.rid }
: { resource: "inbox" };
const historyNav = pendingHistoryNavigation;
pendingHistoryNavigation = false;
isLoading.set(true);
@@ -209,6 +213,13 @@ function guideUrlToRoute(url: URL): { resource: "guide" } | undefined {
}
}
function profileUrlToRoute(url: URL): Route | undefined {
if (url.pathname === "/profile") {
const tab = url.searchParams.get("tab");
return { resource: "profile", tab: tab === "keys" ? "keys" : "profile" };
}
}
function urlToRoute(url: URL): Route | null {
const segments = url.pathname.substring(1).split("/");
const resource = segments.shift();
@@ -227,6 +238,11 @@ function urlToRoute(url: URL): Route | null {
return guideRoute;
}
const profileRoute = profileUrlToRoute(url);
if (profileRoute) {
return profileRoute;
}
switch (resource) {
case "repos": {
return repoUrlToRoute(segments, url.searchParams);
@@ -242,6 +258,8 @@ export function routeToPath(route: Route): string {
return "/inbox";
} else if (route.resource === "guide") {
return "/guide";
} else if (route.resource === "profile") {
return `/profile?tab=${route.tab}`;
} else if (
route.resource === "repo.board" ||
route.resource === "repo.home" ||
+58 -5
View File
@@ -1,4 +1,5 @@
import type { LoadedRepoRoute, RepoRoute } from "@app/views/repo/router";
import type { ActorInfo } from "@bindings/actor/ActorInfo";
import type { NotificationsByRepo } from "@bindings/cob/inbox/NotificationsByRepo";
import type { Config } from "@bindings/config/Config";
import type { RepoSummary } from "@bindings/repo/RepoSummary";
@@ -17,7 +18,13 @@ import {
loadRepoHome,
} from "@app/views/repo/router";
import { cachedListReposSummary, invoke } from "@app/lib/invoke";
import {
cachedActor,
cachedListReposSummary,
invoke,
InvokeError,
} from "@app/lib/invoke";
import { labs } from "@app/lib/labs";
import { repoListScope } from "@app/lib/repoListScope";
interface BootingRoute {
@@ -32,11 +39,21 @@ interface GuideRoute {
resource: "guide";
}
export type ProfileTab = "profile" | "keys";
interface ProfileRoute {
resource: "profile";
tab: ProfileTab;
}
export interface SidebarData {
config: Config;
repos: RepoSummary[];
notificationCount: number;
seededNotReplicated: string[];
actor: ActorInfo | null;
/** Why the actor could not be loaded, with the backend's error code. */
actorError?: { code: string; message: string };
}
export interface LoadedInboxRoute {
@@ -52,9 +69,19 @@ export interface LoadedGuideRoute {
params: { sidebarData: SidebarData };
}
export type Route = BootingRoute | RepoRoute | InboxRoute | GuideRoute;
export interface LoadedProfileRoute {
resource: "profile";
params: { sidebarData: SidebarData; tab: ProfileTab };
}
export type Route =
BootingRoute | RepoRoute | InboxRoute | GuideRoute | ProfileRoute;
export type LoadedRoute =
BootingRoute | LoadedRepoRoute | LoadedInboxRoute | LoadedGuideRoute;
| BootingRoute
| LoadedRepoRoute
| LoadedInboxRoute
| LoadedGuideRoute
| LoadedProfileRoute;
export function isLoadedRepoRoute(
route: LoadedRoute,
@@ -75,14 +102,31 @@ export function isLoadedRepoRoute(
}
export async function loadSidebarData(): Promise<SidebarData> {
const [config, repos, notificationCount, seededNotReplicated] =
const [config, repos, notificationCount, seededNotReplicated, lookup] =
await Promise.all([
invoke<Config>("config"),
cachedListReposSummary(repoListScope.value),
invoke<number>("notification_count"),
invoke<string[]>("seeded_not_replicated"),
labs.actorRepos ? loadActor() : { actor: null },
]);
return { config, repos, notificationCount, seededNotReplicated };
return { config, repos, notificationCount, seededNotReplicated, ...lookup };
}
// Whatever goes wrong with the actor is shown on the profile page, never
// allowed to stop a route from loading.
async function loadActor(): Promise<Pick<SidebarData, "actor" | "actorError">> {
try {
return { actor: await cachedActor() };
} catch (error) {
if (error instanceof InvokeError) {
return {
actor: null,
actorError: { code: error.code, message: error.message },
};
}
throw error;
}
}
export async function loadGuide(): Promise<LoadedGuideRoute> {
@@ -90,6 +134,13 @@ export async function loadGuide(): Promise<LoadedGuideRoute> {
return { resource: "guide", params: { sidebarData } };
}
export async function loadProfile(
route: ProfileRoute,
): Promise<LoadedProfileRoute> {
const sidebarData = await loadSidebarData();
return { resource: "profile", params: { sidebarData, tab: route.tab } };
}
export async function loadInbox(): Promise<LoadedInboxRoute> {
const [sidebarData, notificationsByRepo] = await Promise.all([
loadSidebarData(),
@@ -113,6 +164,8 @@ export async function loadRoute(
return loadGuide();
} else if (route.resource === "repo.board") {
return loadBoard(route);
} else if (route.resource === "profile") {
return loadProfile(route);
} else if (route.resource === "repo.home") {
return loadRepoHome(route);
} else if (route.resource === "repo.commits") {
+9 -3
View File
@@ -9,7 +9,10 @@
interface Props {
title: string;
width: string;
icon: ComponentProps<typeof Icon>["name"];
icon?: ComponentProps<typeof Icon>["name"];
// The confirm button's style: ghost for a destructive step, secondary
// for the step the dialog is there to take.
variant?: "ghost" | "secondary";
label: string;
busyLabel: string;
failure?: string;
@@ -24,6 +27,7 @@
title,
width,
icon,
variant = "ghost",
label,
busyLabel,
failure = "Something went wrong.",
@@ -123,11 +127,13 @@
{#if canConfirm}
<Button variant="outline" onclick={hide}>Cancel</Button>
<Button
variant="ghost"
{variant}
disabled={working || disabled}
onclick={() => void run()}>
<span class="confirm-label">
<Icon name={icon} />
{#if icon}
<Icon name={icon} />
{/if}
{working ? busyLabel : label}
</span>
</Button>
+246
View File
@@ -0,0 +1,246 @@
<script lang="ts">
import type { ActorInfo } from "@bindings/actor/ActorInfo";
import type { ProfileEdit } from "@bindings/actor/ProfileEdit";
import type { PaginatedQuery } from "@bindings/cob/PaginatedQuery";
import {
ago,
describeActorError,
keyName,
PROFILE_PATH,
} from "@app/views/profile/actor";
import { invoke } from "@app/lib/invoke";
import { hide } from "@app/lib/modal";
import Button from "@app/components/Button.svelte";
import CopyableId from "@app/components/CopyableId.svelte";
import Icon from "@app/components/Icon.svelte";
import ScrollArea from "@app/components/ScrollArea.svelte";
interface Props {
// The profile whose versions are listed, for its ID and its keys' names.
actor: ActorInfo;
}
const { actor }: Props = $props();
const PAGE = 20;
// The profile's fields as the form labels them.
const LABELS: Record<string, string> = {
displayName: "display name",
fullName: "full name",
pronouns: "pronouns",
bio: "bio",
location: "location",
timezone: "time zone",
avatar: "avatar",
banner: "banner",
links: "links",
};
const edits = $state<ProfileEdit[]>([]);
// How many versions the pages so far covered, which is more than `edits`
// holds once a page has repeated some.
let fetched = 0;
let more = $state(false);
let loading = $state(true);
let error = $state<string>();
async function load() {
loading = true;
error = undefined;
try {
const page = await invoke<PaginatedQuery<ProfileEdit[]>>(
"actor_profile_history",
{ skip: fetched, take: PAGE },
);
// A profile that moved since the last page shifts the next one back
// over versions already here.
fetched += page.content.length;
const held = new Set(edits.map(edit => edit.commit));
edits.push(...page.content.filter(edit => !held.has(edit.commit)));
more = page.more;
} catch (e) {
error = describeActorError(e, "Could not load the history.");
} finally {
loading = false;
}
}
void load();
function list(fields: string[]): string {
const names = fields.map(field => LABELS[field] ?? field);
if (names.length === 1) return names[0];
return `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;
}
// What a version did, told against the one it was saved over. A version
// that changed no field shown here changed something else: another file,
// or a part of the profile this version of Desktop does not read.
function summary(edit: ProfileEdit): string {
if (edit.parents.length === 0) return "Created the profile";
const changed = edit.fields?.length ? list(edit.fields) : undefined;
if (edit.parents.length > 1) {
const joined = "Joined versions saved on different devices";
return changed ? `${joined} and changed ${changed}` : joined;
}
return changed
? `Changed ${changed}`
: "Changed in a way this version of Desktop cannot show";
}
</script>
<style>
.modal {
width: 36rem;
max-width: 92vw;
display: flex;
flex-direction: column;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-lg);
background-color: var(--color-surface-canvas);
overflow: hidden;
}
.header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 1.25rem;
height: 3.25rem;
flex-shrink: 0;
border-bottom: 1px solid var(--color-border-subtle);
}
.title {
font: var(--txt-heading-s);
color: var(--color-text-primary);
}
.source {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.625rem 1.25rem;
border-bottom: 1px solid var(--color-border-subtle);
background-color: var(--color-surface-subtle);
color: var(--color-text-secondary);
}
.path {
font: var(--txt-code-regular);
color: var(--color-text-tertiary);
}
.entries {
display: flex;
flex-direction: column;
}
.entry {
display: flex;
align-items: flex-start;
gap: 0.75rem;
padding: 0.875rem 1.25rem;
}
.entry + .entry {
border-top: 1px solid var(--color-border-subtle);
}
.entry-icon {
display: flex;
flex-shrink: 0;
padding-top: 0.125rem;
color: var(--color-text-tertiary);
}
.entry-text {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.changed {
color: var(--color-text-primary);
}
.byline {
color: var(--color-text-tertiary);
}
.more {
display: flex;
justify-content: center;
padding: 0.75rem 1.25rem;
border-top: 1px solid var(--color-border-subtle);
}
.empty {
padding: 2.5rem 1.25rem;
text-align: center;
}
.error {
color: var(--color-feedback-error-text);
}
</style>
<div class="modal">
<div class="header">
<span class="title">Published history</span>
<Button variant="naked" onclick={hide}>
<span style:color="var(--color-text-tertiary)">
<Icon name="close" />
</span>
</Button>
</div>
<div class="source txt-body-m-regular">
<Icon name="repository" />
<CopyableId id={actor.rid} styleFont="var(--txt-body-m-regular)">
{actor.rid}
</CopyableId>
<span class="path">{PROFILE_PATH}</span>
</div>
{#if edits.length > 0}
<ScrollArea style="max-height: 24rem;">
<div class="entries">
{#each edits as edit (edit.commit)}
<div class="entry">
<span class="entry-icon"><Icon name="commit" /></span>
<div class="entry-text">
<span class="changed txt-body-m-regular">{summary(edit)}</span>
<span class="byline txt-body-m-regular">
{edit.author
? keyName(actor, edit.author)
: "A device that left no name"} · {ago(edit.savedAt)} ·
<span class="path">{edit.commit.slice(0, 7)}</span>
{#if !edit.live}
· Not the profile yet
{/if}
</span>
</div>
</div>
{/each}
{#if more}
<div class="more">
<Button
variant="outline"
bordered
disabled={loading}
onclick={load}>
Show more
</Button>
</div>
{/if}
</div>
</ScrollArea>
{:else if !loading && !error}
<div class="empty">
<span class="txt-missing txt-body-m-regular">Nothing published yet</span>
</div>
{/if}
{#if error}
<div class="empty">
<span class="error txt-body-m-regular">{error}</span>
</div>
{/if}
</div>
+136
View File
@@ -0,0 +1,136 @@
<script lang="ts">
import type { ActorProfile } from "@bindings/actor/ActorProfile";
import { PROFILE_PATH } from "@app/views/profile/actor";
import debounce from "lodash/debounce";
import { writeToClipboard } from "@app/lib/invoke";
import { hide } from "@app/lib/modal";
import Button from "@app/components/Button.svelte";
import Icon from "@app/components/Icon.svelte";
import PierreFile from "@app/components/PierreFile.svelte";
import PierreSnippet from "@app/components/PierreSnippet.svelte";
import ScrollArea from "@app/components/ScrollArea.svelte";
import SegmentedSwitch from "@app/components/SegmentedSwitch.svelte";
interface Props {
// Whose version this is, as the keys list names it.
name: string;
// The commit of the version.
head: string;
// Unset when the version holds no profile this Desktop can read.
profile?: ActorProfile;
// What the version changed since it split from the one shown here, as a
// unified diff. Unset when that cannot be told.
changes?: string;
}
const { name, head, profile, changes }: Props = $props();
let chosen = $state<"document" | "changes">("changes");
const view = $derived(changes === undefined ? "document" : chosen);
const raw = $derived(profile ? JSON.stringify(profile, null, 2) : undefined);
const copied = $derived(view === "changes" ? changes : raw);
let copyIcon: "copy" | "checkmark" = $state("copy");
const restoreIcon = debounce(() => (copyIcon = "copy"), 1000);
async function copy() {
if (copied === undefined) return;
await writeToClipboard(copied);
copyIcon = "checkmark";
restoreIcon();
}
</script>
<style>
.modal {
width: min(46rem, 92vw);
height: min(38rem, 85vh);
display: flex;
flex-direction: column;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-lg);
background-color: var(--color-surface-canvas);
overflow: hidden;
}
.header {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0 0.75rem 0 1.5rem;
height: 3.25rem;
flex-shrink: 0;
border-bottom: 1px solid var(--color-border-subtle);
}
.title {
font: var(--txt-heading-s);
color: var(--color-text-primary);
}
.actions {
display: flex;
align-items: center;
gap: 0.25rem;
margin-left: auto;
}
.code {
padding: 0.75rem 0;
}
.note {
padding: 0 1.5rem;
color: var(--color-text-secondary);
}
</style>
<div class="modal">
<div class="header">
<span class="title">Profile on {name}</span>
<div class="actions">
{#if raw !== undefined && changes !== undefined}
<SegmentedSwitch
options={[
{ value: "document", label: "Document" },
{ value: "changes", label: "Changes" },
]}
value={view}
onchange={value => (chosen = value)} />
{/if}
{#if copied !== undefined}
<Button variant="outline" styleHeight="2rem" onclick={copy}>
<Icon name={copyIcon} />
{view === "changes" ? "Copy diff" : "Copy JSON"}
</Button>
{/if}
<Button variant="naked" onclick={hide}>
<span style:color="var(--color-text-tertiary)">
<Icon name="close" />
</span>
</Button>
</div>
</div>
<ScrollArea style="flex: 1; min-height: 0;">
<div class="code">
{#if raw === undefined}
<span class="note txt-body-m-regular">
That version holds no profile this Desktop can read.
</span>
{:else if view === "document" || changes === undefined}
<PierreFile
contents={raw}
path={PROFILE_PATH}
cacheKey={`profile-version:${head}`} />
{:else if changes.trim() === ""}
<span class="note txt-body-m-regular">
The profile was not changed there.
</span>
{:else}
<PierreSnippet
patch={changes}
path={PROFILE_PATH}
cacheKey={`profile-split:${head}:${changes.length}`} />
{/if}
</div>
</ScrollArea>
</div>
+21
View File
@@ -7,6 +7,7 @@
import { hints } from "@app/lib/hints";
import { invoke } from "@app/lib/invoke";
import { labs } from "@app/lib/labs";
import * as router from "@app/lib/router";
import { updateChecker } from "@app/lib/updateChecker.svelte";
import { pluralize } from "@app/lib/utils";
@@ -34,6 +35,7 @@
// Shown so that a user seeing the slower fallback can tell which git, if
// any, was picked.
const gitInfo = invoke<GitInfo>("git_info");
const activeRoute = router.activeUnloadedRouteStore;
const diffStyleOptions: Option<DiffOptions["diffStyle"]>[] = [
{ value: "unified", icon: "diff-unified", title: "Unified" },
@@ -302,6 +304,25 @@
value={labs.boards ? "on" : "off"}
onchange={value => (labs.boards = value === "on")} />
</div>
<div class="row">
<div class="row-label">
<span class="row-title">Rich profiles</span>
<span class="row-description">
Link the keys on your devices into one profile. Experimental: the
profile format may still change.
</span>
</div>
<SegmentedSwitch
options={labsOptions}
value={labs.actorRepos ? "on" : "off"}
onchange={value => {
labs.actorRepos = value === "on";
// The sidebar is loaded with the route, so the page loads again
// for it to follow; the router leaves a page that needs this
// experiment.
void router.replace($activeRoute);
}} />
</div>
</div>
<div class="footer">
{#if updateChecker.currentVersion}
@@ -0,0 +1,107 @@
<script lang="ts">
import type { ActorInfo } from "@bindings/actor/ActorInfo";
import type { ActorRevision } from "@bindings/actor/ActorRevision";
import Icon from "@app/components/Icon.svelte";
import { ago, keyName, revisionTitle } from "./actor";
interface Props {
actor: ActorInfo;
// A change to the keys that ended, or one that waits on another.
revision: ActorRevision;
localDid: string;
// The change the profile began with.
first?: boolean;
}
const { actor, revision, localDid, first = false }: Props = $props();
const STATES = {
accepted: "Applied",
rejected: "Rejected",
lapsed: "Lapsed",
open: "Waiting",
} as const;
const name = (did: string) =>
did === localDid ? "this device" : keyName(actor, did);
const list = (dids: string[]) =>
new Intl.ListFormat("en", { type: "conjunction" }).format(dids.map(name));
</script>
<style>
.change {
display: flex;
align-items: flex-start;
gap: 0.75rem;
padding: 0.75rem;
}
.change-icon {
display: flex;
align-items: center;
justify-content: center;
width: 2rem;
height: 2rem;
flex-shrink: 0;
border-radius: var(--border-radius-md);
background-color: var(--color-surface-subtle);
color: var(--color-text-secondary);
}
.text {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.25rem;
color: var(--color-text-primary);
}
.byline {
color: var(--color-text-tertiary);
}
.state {
flex-shrink: 0;
padding: 0.125rem 0.5rem;
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-subtle);
color: var(--color-text-secondary);
}
.state.accepted {
background-color: var(--color-feedback-success-bg);
color: var(--color-feedback-success-text);
}
.state.rejected {
background-color: var(--color-feedback-error-bg);
color: var(--color-feedback-error-text);
}
.state.open {
background-color: var(--color-feedback-warning-bg);
color: var(--color-feedback-warning-text);
}
</style>
<div class="change">
<span class="change-icon">
<Icon name={revision.removed.length > 0 ? "trash" : "key"} />
</span>
<div class="text">
<span class="txt-body-m-medium">
{first ? "Created the profile" : revisionTitle(actor, revision, true)}
</span>
<span class="byline txt-body-m-regular">
Proposed by {name(revision.author)}
{ago(revision.createdAt)}
{#if revision.accepted.length > 0}
· approved by {list(revision.accepted)}
{/if}
{#if revision.rejected.length > 0}
· rejected by {list(revision.rejected)}
{/if}
</span>
</div>
<span class="state {revision.state} txt-body-m-medium">
{STATES[revision.state]}
</span>
</div>
+235
View File
@@ -0,0 +1,235 @@
<script lang="ts">
import type { EnrollmentPreview } from "@bindings/actor/EnrollmentPreview";
import { invoke } from "@app/lib/invoke";
import { publicKeyFromDid } from "@app/lib/utils";
import Checkbox from "@app/components/Checkbox.svelte";
import CopyableId from "@app/components/CopyableId.svelte";
import Icon from "@app/components/Icon.svelte";
import TextInput from "@app/components/TextInput.svelte";
import ConfirmModal from "@app/modals/ConfirmModal.svelte";
import { describeActorError } from "./actor";
import KeyChunks from "./KeyChunks.svelte";
interface Props {
rid: string;
majority: number;
confirm: (code: string, controller: boolean) => Promise<void>;
}
const { rid, majority, confirm }: Props = $props();
// The joining key makes the code, so it consents before anything changes;
// this key only checks and signs it.
let code = $state("");
// Tooling defaults to enrolling a key as both, with an opt-out.
let controller = $state(true);
const ENROLL_PREFIX = "rad-enroll:";
const looksLikeCode = $derived(code.trim().startsWith(ENROLL_PREFIX));
// The code is checked as it is pasted, and the key it binds shown, so the
// user can tell it is the machine they are adding before anything is
// signed.
type Check =
| { status: "none" }
| { status: "checking" }
| { status: "ok"; preview: EnrollmentPreview }
| { status: "failed"; message: string };
let check = $state<Check>({ status: "none" });
// A key that already controls the actor keeps that role whatever the box
// says, so the box says so.
const controls = $derived(check.status === "ok" && check.preview.controller);
$effect(() => {
if (controls) controller = true;
});
// A check scans every repository, so it waits for the typing to stop.
const CHECK_DELAY_MS = 300;
$effect(() => {
const pasted = code.trim();
check = { status: "none" };
if (!looksLikeCode) return;
let current = true;
const timer = setTimeout(() => {
check = { status: "checking" };
invoke<EnrollmentPreview>("decode_enrollment", { code: pasted })
.then(preview => {
if (current) check = { status: "ok", preview };
})
.catch((error: unknown) => {
if (current) check = { status: "failed", message: describe(error) };
});
}, CHECK_DELAY_MS);
return () => {
current = false;
clearTimeout(timer);
};
});
function describe(error: unknown): string {
return describeActorError(error, "Could not add the key.", {
"ActorError.NotController":
"This device's key cannot add keys. Approve from a key that can.",
});
}
</script>
<style>
.step {
display: flex;
gap: 0.75rem;
}
.step-number {
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
width: 1.5rem;
height: 1.5rem;
border-radius: 50%;
background-color: var(--color-surface-subtle);
color: var(--color-text-secondary);
font: var(--txt-body-m-medium);
}
.step-body {
display: flex;
flex-direction: column;
gap: 0.5rem;
min-width: 0;
flex: 1;
}
.lead,
.step-text {
color: var(--color-text-secondary);
}
.check-label {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.hint {
color: var(--color-text-tertiary);
}
.error {
color: var(--color-feedback-error-text);
}
.verified {
display: flex;
gap: 0.5rem;
padding: 0.875rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
background-color: var(--color-surface-subtle);
}
.verified-rows {
display: flex;
flex-direction: column;
gap: 0.5rem;
min-width: 0;
}
.verified-row {
color: var(--color-text-secondary);
}
.verified .ok {
display: flex;
flex-shrink: 0;
padding-top: 0.125rem;
color: var(--color-feedback-success-text);
}
</style>
<ConfirmModal
title="Add a key"
width="34rem"
icon="key"
variant="secondary"
label={majority > 1 ? "Sign and propose" : "Add key"}
busyLabel="Signing…"
disabled={check.status !== "ok"}
confirm={() => confirm(code.trim(), controller)}
describeError={describe}>
{#snippet body()}
<span class="lead txt-body-m-regular">
Add another device's key so that your work on both devices appears under
the same profile. Start on that device, then approve it here.
</span>
<div class="step">
<span class="step-number">1</span>
<div class="step-body">
<span class="step-text txt-body-m-regular">
On the device you are adding, open Profile, choose Join existing
profile, and enter this Profile ID:
</span>
<CopyableId id={rid} styleFont="var(--txt-code-regular)">
{rid}
</CopyableId>
</div>
</div>
<div class="step">
<span class="step-number">2</span>
<div class="step-body">
<span class="step-text txt-body-m-regular">
Create a code there, then paste it here.
</span>
<TextInput bind:value={code} placeholder="{ENROLL_PREFIX}…" autofocus />
{#if code.trim() && !looksLikeCode}
<span class="hint txt-body-s-regular">
A code starts with {ENROLL_PREFIX}
</span>
{:else if check.status === "checking"}
<span class="hint txt-body-s-regular">Checking the code…</span>
{:else if check.status === "failed"}
<span class="error txt-body-s-regular">{check.message}</span>
{:else if check.status === "ok"}
<div class="verified">
<span class="ok"><Icon name="checkmark" /></span>
<div class="verified-rows txt-body-m-regular">
<div class="verified-row">
Valid code. It adds the key below. Make sure the device you are
adding shows the same key.
</div>
<!-- Whole, since a look-alike only has to match what is shown. -->
<KeyChunks
publicKey={publicKeyFromDid(check.preview.did)}
name={check.preview.alias} />
{#if check.preview.controller}
<div class="verified-row">
Already a controller, as a recovery key. Adding it makes it a
full key.
</div>
{/if}
</div>
</div>
{/if}
</div>
</div>
<Checkbox bind:checked={controller} disabled={controls}>
<span class="check-label">
<span class="txt-body-m-regular">Also make it a controller</span>
<span class="hint txt-body-s-regular">
Recommended. Controllers are the keys that can add and remove other
keys. Keep at least three, so losing one is not permanent. Turn this
off for a device you do not fully trust. Its work still appears under
your profile, but it cannot change which keys are yours or edit the
profile.
</span>
</span>
</Checkbox>
{/snippet}
</ConfirmModal>
@@ -0,0 +1,264 @@
<script lang="ts">
import type { Form } from "./form";
import UserAvatar from "@radicle-gui/ui/components/UserAvatar.svelte";
import { publicKeyFromDid, truncateId } from "@app/lib/utils";
import Icon from "@app/components/Icon.svelte";
interface Props {
form: Form;
avatar: string | undefined;
banner: string | undefined;
// What the generated avatar is drawn from when there is no picture.
avatarId: string;
// The keys whose work Explorer credits to the profile.
keys: { did: string; alias?: string }[];
url: string | undefined;
}
const { form, avatar, banner, avatarId, keys, url }: Props = $props();
let avatarBroken = $state(false);
let bannerBroken = $state(false);
$effect(() => {
void avatar;
avatarBroken = false;
});
$effect(() => {
void banner;
bannerBroken = false;
});
const facts = $derived(
[form.pronouns, form.location, form.timezone]
.map(fact => fact.trim())
.filter(Boolean),
);
const links = $derived(form.links.filter(link => link.url.trim()));
function linkLabel(link: { url: string; label?: string }): string {
if (link.label?.trim()) return link.label.trim();
const value = link.url.trim();
if (value.startsWith("mailto:")) return "Email";
try {
return new URL(value).host || value;
} catch {
return value;
}
}
function linkValue(url: string): string {
const value = url.trim();
return value.startsWith("mailto:") ? value.slice("mailto:".length) : value;
}
</script>
<style>
.browser {
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
background-color: var(--color-surface-canvas);
overflow: hidden;
}
.chrome {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.5rem 0.75rem;
border-bottom: 1px solid var(--color-border-subtle);
background-color: var(--color-surface-subtle);
color: var(--color-text-tertiary);
}
.url {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font: var(--txt-code-regular);
}
/* Across the top, as profile pages usually have one. */
.banner {
height: 5rem;
overflow: hidden;
background-color: var(--color-surface-subtle);
}
.banner img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
.head {
display: flex;
align-items: flex-end;
justify-content: space-between;
padding: 0.875rem 0.875rem 0;
}
/* With a banner, the avatar overlaps its bottom-left edge. */
.banner + .head {
margin-top: -2rem;
padding-top: 0;
}
.avatar {
width: 4rem;
height: 4rem;
overflow: hidden;
border: 3px solid var(--color-surface-canvas);
border-radius: var(--border-radius-md);
background-color: var(--color-surface-subtle);
}
.avatar :global(img) {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
.body {
display: flex;
flex-direction: column;
gap: 0.625rem;
padding: 0.5rem 0.875rem 0.875rem;
}
.name {
font: var(--txt-heading-s);
color: var(--color-text-primary);
min-width: 0;
overflow-wrap: anywhere;
}
.name.empty {
color: var(--color-text-tertiary);
}
.follow {
display: inline-flex;
align-items: center;
gap: 0.25rem;
flex-shrink: 0;
padding: 0.25rem 0.5rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-sm);
color: var(--color-text-secondary);
}
.full-name,
.facts {
color: var(--color-text-secondary);
}
.facts {
display: flex;
align-items: center;
gap: 0.375rem;
flex-wrap: wrap;
}
.separator {
color: var(--color-text-quaternary);
}
.bio {
color: var(--color-text-primary);
overflow-wrap: anywhere;
}
/* The page lists keys this way already, so links share the shape. */
.rows {
display: flex;
flex-direction: column;
gap: 0.375rem;
}
.row {
display: flex;
align-items: center;
gap: 0.5rem;
min-width: 0;
}
.chip {
display: inline-flex;
align-items: center;
gap: 0.25rem;
flex-shrink: 0;
padding: 0.125rem 0.375rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-sm);
color: var(--color-text-secondary);
}
.value {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--color-text-tertiary);
font: var(--txt-code-regular);
}
</style>
<div class="browser">
<div class="chrome">
<Icon name="globe" />
<span class="url">{url ?? "Explorer"}</span>
</div>
{#if banner && !bannerBroken}
<div class="banner">
<img src={banner} alt="" onerror={() => (bannerBroken = true)} />
</div>
{/if}
<div class="head">
<div class="avatar">
{#if avatar && !avatarBroken}
<img src={avatar} alt="" onerror={() => (avatarBroken = true)} />
{:else}
<UserAvatar nodeId={avatarId} styleWidth="100%" />
{/if}
</div>
<span class="follow txt-body-m-regular">
<Icon name="plus" />
Follow
</span>
</div>
<div class="body">
<span class="name" class:empty={!form.displayName.trim()}>
{form.displayName.trim() || "Display name"}
</span>
{#if form.fullName.trim()}
<span class="full-name txt-body-m-regular">{form.fullName}</span>
{/if}
{#if facts.length > 0}
<div class="facts txt-body-m-regular">
{#each facts as fact, index (index)}
{#if index > 0}
<span class="separator">·</span>
{/if}
<span>{fact}</span>
{/each}
</div>
{/if}
{#if form.bio.trim()}
<span class="bio txt-body-m-regular">{form.bio}</span>
{/if}
<div class="rows">
{#each links as link (link.id)}
<div class="row txt-body-m-regular">
<span class="chip">
<Icon name="link" />
{linkLabel(link)}
</span>
<span class="value">{linkValue(link.url)}</span>
</div>
{/each}
{#each keys as key (key.did)}
<div class="row txt-body-m-regular">
<span class="chip">
<Icon name="key" />
{key.alias ?? "Unnamed"}
</span>
<span class="value">{truncateId(publicKeyFromDid(key.did))}</span>
</div>
{/each}
</div>
</div>
</div>
+163
View File
@@ -0,0 +1,163 @@
<script lang="ts">
import type { Form } from "./form";
import UserAvatar from "@radicle-gui/ui/components/UserAvatar.svelte";
import { truncateId } from "@app/lib/utils";
import Icon from "@app/components/Icon.svelte";
interface Props {
form: Form;
avatar: string | undefined;
banner: string | undefined;
// What the generated avatar is drawn from when there is no picture.
avatarId: string;
// The Profile ID, or this device's key before there is a profile.
did: string;
}
const { form, avatar, banner, avatarId, did }: Props = $props();
let broken = $state(false);
let bannerBroken = $state(false);
$effect(() => {
void avatar;
broken = false;
});
$effect(() => {
void banner;
bannerBroken = false;
});
</script>
<style>
/* Inert: the shape of the card other people see, not a working one. */
.card {
display: flex;
flex-direction: column;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
background-color: var(--color-surface-canvas);
box-shadow: var(--elevation-low);
overflow: hidden;
}
.banner {
height: 3.5rem;
background-color: var(--color-surface-subtle);
}
.banner img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
.avatar {
width: 3rem;
height: 3rem;
margin: 0.875rem 0 0 0.875rem;
overflow: hidden;
border: 3px solid var(--color-surface-canvas);
border-radius: var(--border-radius-md);
background-color: var(--color-surface-subtle);
}
/* With a banner, the avatar overlaps its bottom-left edge. */
.banner + .avatar {
margin-top: -1.5rem;
}
.avatar :global(img) {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
.body {
display: flex;
flex-direction: column;
gap: 0.75rem;
padding: 0.5rem 0.875rem 0.875rem;
}
.text {
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.125rem;
}
.name,
.full-name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.name {
color: var(--color-text-primary);
}
.name.empty {
color: var(--color-text-tertiary);
}
.full-name,
.bio {
color: var(--color-text-secondary);
}
.bio {
display: -webkit-box;
-webkit-line-clamp: 3;
line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}
.did {
color: var(--color-text-tertiary);
font: var(--txt-code-regular);
}
.action {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.375rem;
padding: 0.375rem 0.5rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-sm);
color: var(--color-text-secondary);
}
</style>
<div class="card">
{#if banner && !bannerBroken}
<div class="banner">
<img src={banner} alt="" onerror={() => (bannerBroken = true)} />
</div>
{/if}
<span class="avatar">
{#if avatar && !broken}
<img src={avatar} alt="" onerror={() => (broken = true)} />
{:else}
<UserAvatar nodeId={avatarId} styleWidth="100%" />
{/if}
</span>
<div class="body">
<span class="text">
<span
class="name txt-body-m-medium"
class:empty={!form.displayName.trim()}>
{form.displayName.trim() || "Display name"}
</span>
{#if form.fullName.trim()}
<span class="full-name txt-body-m-regular">{form.fullName}</span>
{/if}
</span>
{#if form.bio.trim()}
<span class="bio txt-body-m-regular">{form.bio}</span>
{/if}
<span class="did">{truncateId(did)}</span>
<span class="action txt-body-m-medium">
View profile
<Icon name="open-external" />
</span>
</div>
</div>
@@ -0,0 +1,289 @@
<script lang="ts" module>
// A picture chosen for the profile and not saved yet. The backend names
// the file it is saved as, by what its content is.
export interface PickedImage {
base64: string;
// An object URL to show it by.
url: string;
}
</script>
<script lang="ts">
import UserAvatar from "@radicle-gui/ui/components/UserAvatar.svelte";
import Button from "@app/components/Button.svelte";
import Icon from "@app/components/Icon.svelte";
interface Props {
kind: "avatar" | "banner";
// What the profile field holds: a path in the repository, or a web URL
// that another tool wrote.
value: string;
// The picture to show for it, if there is one to show.
src: string | undefined;
picked: PickedImage | undefined;
// An empty avatar falls back to the pattern generated from this ID,
// since that is what people see.
fallbackId?: string;
disabled: boolean;
// What the backend would refuse in the field.
error: string | undefined;
onpick: (image: PickedImage | undefined) => void;
}
/* eslint-disable prefer-const */
let {
kind,
value = $bindable(""),
src,
picked,
fallbackId,
disabled,
error,
onpick,
}: Props = $props();
/* eslint-enable prefer-const */
// The backend's limits, checked here so the answer comes at once. Which
// kinds of picture it takes is the backend's to say.
const LIMIT_KIB = { avatar: 1024, banner: 2048 } as const;
const label = $derived(kind === "avatar" ? "Avatar" : "Banner");
let input = $state<HTMLInputElement>();
let pickError = $state<string>();
let broken = $state(false);
$effect(() => {
void src;
broken = false;
});
$effect(() => {
const url = picked?.url;
return () => {
if (url) URL.revokeObjectURL(url);
};
});
function base64(bytes: Uint8Array): string {
let binary = "";
const step = 0x8000;
for (let at = 0; at < bytes.length; at += step) {
binary += String.fromCharCode(...bytes.subarray(at, at + step));
}
return btoa(binary);
}
async function pick(file: File | undefined) {
pickError = undefined;
if (!file) return;
const kib = Math.ceil(file.size / 1024);
if (kib > LIMIT_KIB[kind]) {
pickError = `This picture is ${kib} KiB, and the limit is ${LIMIT_KIB[kind]} KiB.`;
return;
}
// A file that does not decode is no picture, whatever its name says.
try {
(await createImageBitmap(file)).close();
} catch {
pickError = "This file is not a picture that can be shown.";
return;
}
onpick({
base64: base64(new Uint8Array(await file.arrayBuffer())),
url: URL.createObjectURL(file),
});
}
// A picture picked and not saved goes back to what the field held;
// otherwise the field is emptied.
function remove() {
if (picked) onpick(undefined);
else value = "";
pickError = undefined;
}
</script>
<style>
.field {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.label {
color: var(--color-text-primary);
}
.row {
display: flex;
align-items: center;
gap: 0.875rem;
}
.preview {
position: relative;
flex-shrink: 0;
padding: 0;
cursor: pointer;
overflow: hidden;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-subtle);
}
.preview[disabled] {
cursor: not-allowed;
}
.preview.avatar {
width: 4rem;
height: 4rem;
}
.preview.banner {
width: 12rem;
height: 4rem;
}
.preview img,
.preview :global(img) {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
.preview:hover:not([disabled]) {
border-color: var(--color-border-mid);
}
/* Sits on the picture, so the picker has no button of its own. */
.pick {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: flex;
align-items: center;
justify-content: center;
width: 1.75rem;
height: 1.75rem;
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-canvas);
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
color: var(--color-text-primary);
}
.preview:hover .pick {
background-color: var(--color-surface-base);
}
.placeholder {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
color: var(--color-text-quaternary);
}
.details {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.375rem;
}
.source {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--color-text-primary);
font: var(--txt-code-regular);
}
.unsaved {
color: var(--color-text-secondary);
}
.actions {
display: flex;
align-items: center;
gap: 0.5rem;
}
.actions :global(.button.outline) {
color: var(--color-text-secondary);
}
.limits {
color: var(--color-text-tertiary);
}
.error {
display: flex;
align-items: center;
gap: 0.375rem;
color: var(--color-feedback-error-text);
}
input[type="file"] {
display: none;
}
</style>
<div class="field">
<span class="label txt-body-m-medium">{label}</span>
<input
bind:this={input}
type="file"
accept="image/png,image/jpeg,image/webp,image/gif"
aria-label="{kind} picture"
onchange={() => {
void pick(input?.files?.[0]);
if (input) input.value = "";
}} />
<div class="row">
<button
type="button"
class="preview {kind}"
title={disabled ? undefined : src ? `Replace ${kind}` : `Choose ${kind}`}
{disabled}
onclick={() => input?.click()}>
{#if src && !broken}
<img {src} alt="" onerror={() => (broken = true)} />
{:else if fallbackId}
<UserAvatar nodeId={fallbackId} styleWidth="100%" />
{:else}
<span class="placeholder"><Icon name="placeholder" /></span>
{/if}
{#if !disabled}
<span class="pick"><Icon name={src ? "edit" : "plus"} /></span>
{/if}
</button>
<div class="details">
{#if picked || value}
{#if picked}
<span class="unsaved txt-body-m-regular">
New picture, not saved yet
</span>
{:else}
<span class="source">{value}</span>
{#if value.includes(":")}
<span class="limits txt-body-s-regular">
A web address. Desktop does not load pictures from the web.
</span>
{/if}
{/if}
<!-- A picture that cannot be changed is only shown. -->
{#if !disabled}
<div class="actions">
<Button variant="outline" bordered onclick={remove}>Remove</Button>
</div>
{/if}
{:else if !disabled}
<span class="limits txt-body-s-regular">
Up to {LIMIT_KIB[kind] / 1024} MiB.
</span>
{/if}
</div>
</div>
{#if pickError ?? error}
<span class="error txt-body-m-regular">
<Icon name="warning" />
{pickError ?? error}
</span>
{/if}
</div>
+597
View File
@@ -0,0 +1,597 @@
<script lang="ts">
import type { ActorInfo } from "@bindings/actor/ActorInfo";
import { untrack } from "svelte";
import { nodeRunning } from "@app/lib/events";
import { poll } from "@app/lib/interval";
import { invoke, InvokeError } from "@app/lib/invoke";
import { fetchingRepos, seededRepos, seedRepo } from "@app/lib/seedRepo";
import { parseRepositoryId, publicKeyFromDid } from "@app/lib/utils";
import ActorAvatar from "@app/components/ActorAvatar.svelte";
import Button from "@app/components/Button.svelte";
import Clipboard from "@app/components/Clipboard.svelte";
import Icon from "@app/components/Icon.svelte";
import Spinner from "@app/components/Spinner.svelte";
import TextInput from "@app/components/TextInput.svelte";
import {
describeActorError,
keyKind,
profileName,
reload,
roleText,
} from "./actor";
import KeyChunks from "./KeyChunks.svelte";
import Notice from "./Notice.svelte";
interface Props {
// This device's key, which the approving device shows from the code.
publicKey: string;
// This device's name, shown with its key.
alias: string;
oncancel: () => void;
}
const { publicKey, alias, oncancel }: Props = $props();
let rid = $state("");
let working = $state(false);
let error = $state<string>();
let code = $state<string>();
const EXAMPLE_ID = "rad:z3gqcJUoA1n9HaHKufZs5FCSGazv5";
// The ID as the lists of repositories write it, however it was entered.
const target = $derived.by(() => {
const parsed = parseRepositoryId(rid.trim());
return parsed && `${parsed.prefix}${parsed.pubkey}`;
});
// The profile is looked up as its ID is entered and shown, so the user
// sees whose it is before this device's key consents to anything.
type Check =
| { status: "none" }
| { status: "checking" }
| { status: "ok"; actor: ActorInfo }
| { status: "missing"; rid: string }
// The copy here has no head, so the node fetches nothing more into it.
| { status: "stuck"; rid: string; message: string }
| { status: "failed"; message: string };
let check = $state<Check>({ status: "none" });
// Only the answer to the latest lookup counts.
let latest = 0;
async function lookup(id: string): Promise<void> {
const mine = ++latest;
check = { status: "checking" };
let found: Check;
try {
const actor = await invoke<ActorInfo>("joinable_actor", { rid: id });
found = { status: "ok", actor };
} catch (e) {
found = refusal(id, e);
}
if (mine === latest) check = found;
}
function refusal(id: string, e: unknown): Check {
if (e instanceof InvokeError && e.code === "ActorError.NotFetched") {
return { status: "missing", rid: id };
}
if (e instanceof InvokeError && e.code === "ActorError.CopyStuck") {
return { status: "stuck", rid: id, message: e.message };
}
return {
status: "failed",
message: describeActorError(e, "Could not look up the profile."),
};
}
// A lookup scans every repository, so it waits for the typing to stop.
const CHECK_DELAY_MS = 300;
$effect(() => {
const id = target;
latest += 1;
check = { status: "none" };
error = undefined;
if (id === undefined) return;
const timer = setTimeout(() => void lookup(id), CHECK_DELAY_MS);
return () => clearTimeout(timer);
});
const fetching = $derived(
check.status === "missing" && $fetchingRepos.includes(check.rid),
);
// A look at a profile that is still awaited: one at a time, and only an
// answer changes the page, so a lookup that fails leaves it waiting.
let lookingAgain = false;
async function lookAgain(id: string): Promise<void> {
if (lookingAgain) return;
lookingAgain = true;
const mine = latest;
let found: Check;
try {
const actor = await invoke<ActorInfo>("joinable_actor", { rid: id });
found = { status: "ok", actor };
} catch (e) {
found = refusal(id, e);
} finally {
lookingAgain = false;
}
if (
mine === latest &&
(found.status === "ok" || found.status === "stuck")
) {
check = found;
}
}
// The missing profile whose fetch was asked for or seen on its way.
let awaited: string | undefined;
$effect(() => {
if ($seededRepos === 0) return;
untrack(() => {
if (check.status === "missing") awaited = check.rid;
});
});
// The sidebar looks at what is being fetched once a repository is asked
// for, and every few seconds while any is on its way. An awaited profile
// that is not among them when it has looked may have arrived, however
// quickly the fetch went. One that stays among them is looked up at each
// look, since a copy the node cannot update never leaves them.
$effect(() => {
const underway = $fetchingRepos;
untrack(() => {
if (check.status !== "missing") return;
if (underway.includes(check.rid)) {
if (awaited === check.rid) void lookAgain(check.rid);
awaited = check.rid;
} else if (awaited === check.rid) {
awaited = undefined;
void lookup(check.rid);
}
});
});
// The user asked for this profile by its ID, so fetching it seeds it
// without asking again.
async function fetchProfile(target: string) {
working = true;
error = undefined;
try {
await seedRepo(target);
} catch (e) {
error = describeActorError(e, "Could not fetch the profile.");
} finally {
working = false;
}
}
async function join(target: string) {
working = true;
error = undefined;
try {
code = await invoke<string>("join_actor", { rid: target });
} catch (e) {
error = describeActorError(e, "Could not create a code.");
} finally {
working = false;
}
}
async function submit() {
if (check.status === "ok") {
await join(check.actor.rid);
} else if (check.status === "missing" && !fetching && $nodeRunning) {
// It may have arrived since the last look.
const id = check.rid;
await lookup(id);
if (check.status === "missing") await fetchProfile(id);
}
}
// Storage drops a copy this device never wrote to, so the fetch that
// follows starts from nothing. The user asked for this profile, so it is
// seeded again without asking.
async function fetchAgain(id: string) {
working = true;
error = undefined;
try {
await invoke<null>("clean", { rid: id });
await lookup(id);
if (check.status === "stuck") {
error = "Could not remove this device's copy of the profile.";
} else if (check.status === "missing" && $nodeRunning) {
await seedRepo(id);
}
} catch (e) {
error = describeActorError(e, "Could not fetch the profile again.");
} finally {
working = false;
}
}
function back() {
code = undefined;
if (target !== undefined) void lookup(target);
}
async function done() {
await reload("profile");
oncancel();
}
// While the code waits to be approved, the page looks every few seconds
// for this key in a profile and moves on once it is.
const APPROVAL_POLL_MS = 5000;
$effect(() => {
if (code === undefined) return;
return poll(async active => {
try {
const actor = await invoke<ActorInfo | null>("actor");
if (active() && actor) void reload("profile");
} catch (e) {
console.warn("Could not look for the approval", e);
}
}, APPROVAL_POLL_MS);
});
</script>
<style>
.join {
display: flex;
flex-direction: column;
gap: 1rem;
width: 100%;
max-width: 40rem;
}
.title {
font: var(--txt-body-l-medium);
color: var(--color-text-primary);
}
.text {
color: var(--color-text-secondary);
}
.hint {
color: var(--color-text-tertiary);
}
.error {
color: var(--color-feedback-error-text);
}
.status {
display: flex;
align-items: center;
gap: 0.5rem;
color: var(--color-text-secondary);
}
.step {
display: flex;
gap: 0.75rem;
}
.step-number {
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
width: 1.5rem;
height: 1.5rem;
border-radius: 50%;
background-color: var(--color-surface-subtle);
color: var(--color-text-secondary);
font: var(--txt-body-m-medium);
}
.step-body {
display: flex;
flex-direction: column;
gap: 0.5rem;
min-width: 0;
flex: 1;
}
.found {
display: flex;
flex-direction: column;
gap: 0.75rem;
margin-top: 0.5rem;
}
.found-title {
font: var(--txt-body-l-medium);
color: var(--color-text-primary);
}
.card {
display: flex;
flex-direction: column;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
background-color: var(--color-surface-canvas);
overflow: hidden;
}
.card-head {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 1rem;
color: var(--color-text-primary);
}
.card-head :global(img) {
border-radius: var(--border-radius-md);
}
.card-name {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.card-rid {
color: var(--color-text-tertiary);
word-break: break-all;
}
.devices {
display: flex;
flex-direction: column;
gap: 0.75rem;
padding: 1rem;
border-top: 1px solid var(--color-border-subtle);
}
.device {
display: flex;
align-items: center;
gap: 0.75rem;
}
.device-icon {
display: flex;
align-items: center;
justify-content: center;
width: 2rem;
height: 2rem;
flex-shrink: 0;
border-radius: var(--border-radius-md);
background-color: var(--color-surface-subtle);
color: var(--color-text-secondary);
}
.device-text {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.125rem;
color: var(--color-text-primary);
}
.device-name {
display: flex;
align-items: center;
gap: 0.5rem;
}
.chip {
padding: 0.125rem 0.375rem;
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-subtle);
color: var(--color-text-secondary);
}
.did {
font: var(--txt-code-small);
color: var(--color-text-tertiary);
word-break: break-all;
}
.code {
display: flex;
align-items: flex-start;
gap: 0.5rem;
padding: 0.75rem;
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-subtle);
font: var(--txt-code-regular);
color: var(--color-text-primary);
word-break: break-all;
}
.actions {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 0.5rem;
}
.waiting {
margin-right: auto;
}
</style>
{#snippet copyable(text: string)}
<div class="code">
<span style:flex="1">{text}</span>
<Clipboard {text} />
</div>
{/snippet}
{#snippet found(actor: ActorInfo)}
<div class="found">
<span class="found-title">Is this your profile?</span>
<div class="card">
<div class="card-head">
<ActorAvatar {actor} styleWidth="2.5rem" />
<div class="card-name">
{#if actor.profileUnreadable}
<span class="text txt-body-m-regular">
Its profile file is not one this version of Desktop can read.
</span>
{:else}
<span class="txt-heading-s">{profileName(actor)}</span>
{#if actor.profile?.fullName}
<span class="text txt-body-m-regular">
{actor.profile.fullName}
</span>
{/if}
{/if}
<span class="card-rid txt-body-s-regular">{actor.rid}</span>
</div>
{#if actor.kind === "agent"}
<span class="chip txt-body-s-regular">Automated agent</span>
{/if}
</div>
<div class="devices">
{#each actor.keys as key (key.did)}
{@const role = roleText[keyKind(key)]}
<div class="device">
<span class="device-icon"><Icon name="key" /></span>
<div class="device-text">
<div class="device-name">
<!-- Only a label: a look-alike can copy it. -->
<span class="txt-body-m-medium">{key.alias ?? "Unnamed"}</span>
{#if role}
<span class="chip txt-body-s-regular">{role}</span>
{/if}
</div>
<!-- Whole, since a look-alike only has to match what is shown. -->
<span class="did">{publicKeyFromDid(key.did)}</span>
</div>
</div>
{/each}
</div>
</div>
{#if actor.payloadNewer}
<Notice icon="warning" tone="warning">
<span class="txt-body-s-regular">
Written by a newer Desktop or another app. It may hold keys this
version does not show.
</span>
</Notice>
{/if}
<span class="hint txt-body-s-regular">
Nothing changes until your other devices approve this one.
</span>
</div>
{/snippet}
<div class="join">
<span class="title">Join existing profile</span>
{#if code}
<span class="text txt-body-m-regular">
Paste this code on a device that has your profile, under Keys → Add key.
</span>
{@render copyable(code)}
<span class="text txt-body-m-regular">
It will show this device's key. Check that it matches.
</span>
<KeyChunks {publicKey} name={alias} />
<div class="actions">
<span class="status waiting txt-body-m-regular">
<Spinner />
Waiting for approval…
</span>
<!-- Creating a code writes nothing, so the profile can be looked at again. -->
<Button variant="outline" bordered onclick={back}>Back</Button>
<Button variant="secondary" onclick={() => void done()}>Done</Button>
</div>
{:else}
<div class="step">
<span class="step-number">1</span>
<span class="text txt-body-m-regular">
On a device that already has your profile, open Profile and copy the
Profile ID.
</span>
</div>
<div class="step">
<span class="step-number">2</span>
<div class="step-body">
<span class="text txt-body-m-regular">Paste it here.</span>
<TextInput
bind:value={rid}
placeholder="Profile ID, e.g. {EXAMPLE_ID}"
disabled={working || fetching}
autofocus
onSubmit={() => void submit()} />
{#if rid.trim() && target === undefined}
<span class="hint txt-body-s-regular">
That is not a Profile ID. One looks like {EXAMPLE_ID}.
</span>
{:else if check.status === "missing" && !$nodeRunning}
<!-- The code signs the profile's current state, which only a copy
of it gives, and a stopped node fetches none. -->
<Notice icon="warning" tone="warning">
<span class="txt-body-m-regular">
Your node is offline. Start it to fetch this profile.
</span>
</Notice>
{:else if fetching}
<span class="status txt-body-m-regular">
<Spinner />
Fetching the profile from the network…
</span>
{:else if check.status === "checking"}
<span class="status txt-body-m-regular">Looking up the profile…</span>
{:else if check.status === "missing"}
<span class="status txt-body-m-regular">
This profile is not on this device yet. Fetch it to see whose it is.
</span>
{:else if check.status === "stuck"}
<Notice icon="warning" tone="warning">
<span class="txt-body-m-regular">{check.message}</span>
</Notice>
{:else if check.status === "failed"}
<span class="error txt-body-m-regular">{check.message}</span>
{:else if check.status === "ok"}
{@render found(check.actor)}
{/if}
{#if error}
<span class="error txt-body-m-regular">{error}</span>
{/if}
</div>
</div>
<div class="actions">
<Button variant="outline" bordered onclick={oncancel}>Cancel</Button>
{#if check.status === "missing"}
<Button
variant="secondary"
disabled={fetching || working || !$nodeRunning}
onclick={submit}>
Fetch the profile
</Button>
{:else if check.status === "stuck"}
{@const id = check.rid}
<Button
variant="secondary"
disabled={working}
onclick={() => fetchAgain(id)}>
Fetch again
</Button>
{:else}
<Button
variant="secondary"
disabled={check.status !== "ok" || working}
onclick={submit}>
Create code
</Button>
{/if}
</div>
{/if}
</div>
@@ -0,0 +1,56 @@
<script lang="ts">
interface Props {
// A public key, without the `did:key:` prefix.
publicKey: string;
// The device name the key's node goes by. It only labels the key: a
// look-alike can copy it.
name?: string;
}
const { publicKey, name }: Props = $props();
// Large and in two even lines, so two screens can be compared a line at a
// time.
const LINES = 2;
const lines = $derived.by(() => {
const length = Math.ceil(publicKey.length / LINES);
return Array.from({ length: LINES }, (_, i) =>
publicKey.slice(i * length, (i + 1) * length),
);
});
</script>
<style>
.key {
display: flex;
flex-direction: column;
align-items: center;
padding: 0.75rem 1rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
background-color: var(--color-surface-canvas);
color: var(--color-text-primary);
font: var(--txt-code-regular);
font-size: 1.125rem;
line-height: 1.75rem;
letter-spacing: 0.2em;
}
.name {
margin-top: 0.5rem;
padding: 0 0.375rem;
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-brand-subtle);
color: var(--color-text-brand);
letter-spacing: normal;
}
</style>
<div class="key" aria-label={publicKey}>
{#each lines as line, index (index)}
<span>{line}</span>
{/each}
{#if name}
<span class="name txt-body-m-medium">{name}</span>
{/if}
</div>
+511
View File
@@ -0,0 +1,511 @@
<script lang="ts">
import type { ActorInfo } from "@bindings/actor/ActorInfo";
import type { ActorRevision } from "@bindings/actor/ActorRevision";
import type { HintId } from "@app/lib/hints";
import { hints } from "@app/lib/hints";
import { invoke } from "@app/lib/invoke";
import { show } from "@app/lib/modal";
import { publicKeyFromDid, truncateId } from "@app/lib/utils";
import Button from "@app/components/Button.svelte";
import CopyableId from "@app/components/CopyableId.svelte";
import Icon from "@app/components/Icon.svelte";
import {
type ActorWrite,
ago,
change,
controllersOf,
describeActorError,
keyKind,
keyName,
mayChangeKeys,
roleText,
votedRemoval,
} from "./actor";
import ClosedRevision from "./ClosedRevision.svelte";
import EnrollKey from "./EnrollKey.svelte";
import Notice from "./Notice.svelte";
import PendingRevision from "./PendingRevision.svelte";
interface Props {
actor: ActorInfo;
localDid: string;
}
const { actor, localDid }: Props = $props();
const controllers = $derived(controllersOf(actor));
// The warnings about too few controllers that the user has read and closed,
// by profile. Fewer controllers is a choice, so neither comes back for the
// same count.
const warning = $derived<HintId>(
`profile.controllers:${actor.rid}:${controllers.length}`,
);
const dismiss = () => hints.dismiss(warning);
const canChangeKeys = $derived(mayChangeKeys(actor, localDid));
// What an identity change shows in: the open changes and their votes, the
// keys and what each may do, and the two counts of approvals.
const moved = $derived(
JSON.stringify([
actor.rid,
actor.pending,
actor.keys,
actor.threshold,
actor.majority,
]),
);
// The changes to the keys that ended, newest first, loaded again whenever
// the identity moves.
let closed = $state<ActorRevision[]>([]);
$effect(() => {
void moved;
let gone = false;
invoke<ActorRevision[]>("closed_actor_revisions")
.then(revisions => {
if (!gone) closed = revisions;
})
.catch((e: unknown) =>
console.warn("Could not load the past changes to the keys", e),
);
return () => {
gone = true;
};
});
let acting = $state(false);
let actionError = $state<string>();
let confirmingRevoke = $state<string>();
let revokeError = $state<{ did: string; message: string }>();
// The error goes to the page's own place, or to `onerror` when the caller
// shows it next to what was clicked.
async function act(
write: ActorWrite,
onerror?: (error: unknown) => void,
): Promise<void> {
acting = true;
actionError = undefined;
revokeError = undefined;
try {
await change(write, "keys");
} catch (error) {
if (onerror) onerror(error);
else
actionError = describeActorError(error, "Could not make the change.");
} finally {
acting = false;
}
}
function revoke(did: string) {
confirmingRevoke = undefined;
void act({ command: "remove_actor_key", args: { did } }, error => {
revokeError = {
did,
message: describeActorError(error, "Could not revoke the key.", {
"ActorError.NotController":
"This device's key cannot revoke keys. Revoke from a key that can.",
}),
};
});
}
// A key whose removal has this machine's vote and waits for the others.
function revokePending(did: string): boolean {
return votedRemoval(actor, did, localDid) !== undefined;
}
// A confirmation for a key that left the list must not reopen when it
// comes back.
$effect(() => {
if (
confirmingRevoke &&
!actor.keys.some(key => key.did === confirmingRevoke)
)
confirmingRevoke = undefined;
});
function openEnroll() {
show({
component: EnrollKey,
props: {
rid: actor.rid,
majority: actor.majority,
confirm: (code: string, controller: boolean) =>
change(
{ command: "approve_enrollment", args: { code, controller } },
"keys",
),
},
});
}
</script>
<style>
.quorums {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 0.75rem;
}
.quorum {
display: flex;
flex-direction: column;
gap: 0.375rem;
padding: 0.875rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
background-color: var(--color-surface-canvas);
}
.quorum-title {
display: flex;
align-items: center;
gap: 0.375rem;
color: var(--color-text-secondary);
}
.quorum-value {
color: var(--color-text-primary);
}
.quorum-note {
color: var(--color-text-tertiary);
}
/* Past changes in one box, each below the last. */
.closed {
display: flex;
flex-direction: column;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
background-color: var(--color-surface-canvas);
}
.closed > :global(* + *) {
border-top: 1px solid var(--color-border-subtle);
}
.approvals {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.footer-note {
color: var(--color-text-tertiary);
}
.error {
color: var(--color-feedback-error-text);
}
.section-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
margin-bottom: 0.625rem;
}
/* As tall as its title, so the taller button beside it does not push the
first line lower than on the Profile tab. */
.section-header.with-action {
height: 1.25rem;
margin-bottom: 1rem;
}
.section-title {
display: inline-flex;
align-items: center;
gap: 0.375rem;
color: var(--color-text-secondary);
}
.keys {
display: flex;
flex-direction: column;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
overflow: hidden;
}
.key {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.75rem;
background-color: var(--color-surface-canvas);
}
.key + .key {
border-top: 1px solid var(--color-border-subtle);
}
.key-icon {
display: flex;
align-items: center;
justify-content: center;
width: 2rem;
height: 2rem;
flex-shrink: 0;
border-radius: var(--border-radius-md);
background-color: var(--color-surface-subtle);
color: var(--color-text-secondary);
}
.key-actions {
flex-shrink: 0;
}
.confirm {
display: flex;
align-items: center;
gap: 0.375rem;
}
.confirm-text {
color: var(--color-text-secondary);
}
.key-text {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.key-name-row {
display: flex;
align-items: center;
gap: 0.5rem;
flex-wrap: wrap;
}
.key-name {
color: var(--color-text-primary);
}
.chip {
padding: 0.125rem 0.375rem;
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-subtle);
color: var(--color-text-secondary);
}
.chip.brand {
background-color: var(--color-surface-brand-subtle);
color: var(--color-text-brand);
}
.key-facts {
display: flex;
align-items: center;
gap: 0.5rem;
flex-wrap: wrap;
color: var(--color-text-tertiary);
}
.separator {
color: var(--color-text-quaternary);
}
</style>
{#if actor.payloadNewer}
<Notice
icon="warning"
title="Written by a newer Desktop or another app"
tone="warning">
<span class="txt-body-m-regular">
This profile holds fields this version of Desktop does not know, so the
keys cannot be changed here. It may also hold keys this version does not
show.
</span>
</Notice>
{/if}
<div>
<div class="section-header with-action">
<span class="section-title txt-body-m-medium">
Keys
<span class="global-counter-badge">{actor.keys.length}</span>
</span>
{#if canChangeKeys}
<Button variant="secondary" onclick={openEnroll}>
<Icon name="plus" />
Add key
</Button>
{/if}
</div>
<div class="keys">
{#each actor.keys as key (key.did)}
{@const kind = keyKind(key)}
{@const role = roleText[kind]}
<div class="key">
<span class="key-icon">
<Icon name={kind === "recovery" ? "lock" : "key"} />
</span>
<div class="key-text">
<div class="key-name-row">
<span class="key-name txt-body-m-medium">
{keyName(actor, key.did)}
</span>
{#if key.did === localDid}
<span class="chip brand txt-body-m-medium">This device</span>
{/if}
{#if role}
<span class="chip txt-body-m-medium">{role}</span>
{/if}
</div>
<div class="key-facts txt-body-m-regular">
<CopyableId id={key.did} styleFont="var(--txt-body-m-regular)">
{truncateId(publicKeyFromDid(key.did))}
</CopyableId>
<span class="separator">·</span>
<span>added {ago(key.addedAt)}</span>
{#if key.did === localDid}
<span class="separator">·</span>
<span>active now</span>
{:else if !key.bound}
<span class="separator">·</span>
<span>kept offline</span>
{/if}
</div>
{#if revokeError?.did === key.did}
<span class="error txt-body-m-regular">{revokeError.message}</span>
{/if}
</div>
<!-- Revoking the key this machine signs with would lock it out. -->
{#if canChangeKeys && key.did !== localDid}
<div class="key-actions">
{#if confirmingRevoke === key.did}
<div class="confirm">
<span class="confirm-text txt-body-m-regular">
{#if key.controller && controllers.length - 1 < actor.majority}
This needs its own approval too. Propose anyway?
{:else}
{actor.majority > 1 ? "Propose revoking?" : "Revoke?"}
{/if}
</span>
<Button
variant="ghost"
styleHeight="1.75rem"
disabled={acting}
onclick={() => revoke(key.did)}>
Yes
</Button>
<Button
variant="outline"
styleHeight="1.75rem"
disabled={acting}
onclick={() => (confirmingRevoke = undefined)}>
Cancel
</Button>
</div>
{:else if revokePending(key.did)}
<span class="chip txt-body-m-medium">Revoke pending</span>
{:else}
<Button
variant="naked"
title="Revoke key"
disabled={acting}
onclick={() => (confirmingRevoke = key.did)}>
<Icon name="trash" />
</Button>
{/if}
</div>
{/if}
</div>
{/each}
</div>
<!-- The key the error is about can be gone after the reload. -->
{#if revokeError && !actor.keys.some(key => key.did === revokeError?.did)}
<span class="footer-note error txt-body-m-regular">
{revokeError.message}
</span>
{/if}
</div>
<!-- Below three controllers, losing one can freeze the keys for good. -->
{#if controllers.length === 2 && !hints.isDismissed(warning)}
<Notice
icon="warning"
title="Don't get locked out"
tone="warning"
ondismiss={dismiss}>
<span class="txt-body-m-regular">
With two controllers, both have to approve every change to your keys. If
you lose one, you can never remove it or add a replacement. With three
controllers, any two can approve, so losing one does not lock you out.
</span>
</Notice>
{:else if controllers.length === 1 && !hints.isDismissed(warning)}
<Notice
icon="warning"
title="Only one controller"
tone="warning"
ondismiss={dismiss}>
<span class="txt-body-m-regular">
Lose this key and you lose control of the profile, with no way to get it
back. Three controllers is the recommended minimum.
</span>
</Notice>
{/if}
<div>
<div class="section-header">
<span class="section-title txt-body-m-medium">Approvals needed</span>
</div>
<div class="quorums">
<div class="quorum">
<span class="quorum-title txt-body-m-medium">
<Icon name="key" />
Adding or removing a key
</span>
<span class="quorum-value txt-heading-s">
{actor.majority} of {controllers.length}
</span>
<span class="quorum-note txt-body-m-regular">
How many of your controllers have to approve. Always a majority, so it
rises as you add keys.
</span>
</div>
<div class="quorum">
<span class="quorum-title txt-body-m-medium">
<Icon name="edit" />
Editing your profile
</span>
<span class="quorum-value txt-heading-s">
{actor.threshold} of {controllers.length}
</span>
<span class="quorum-note txt-body-m-regular">
How many controllers have to agree on an edit. With one, your edits show
up straight away.
</span>
</div>
</div>
</div>
{#if actor.pending.length > 0 || closed.length > 0}
<div>
<div class="section-header">
<span class="section-title txt-body-m-medium">Changes</span>
</div>
<div class="approvals">
{#each actor.pending as revision (revision.id)}
<PendingRevision {actor} {revision} {localDid} {acting} {act} />
{/each}
{#if closed.length > 0}
<div class="closed">
{#each closed as revision, index (revision.id)}
<ClosedRevision
{actor}
{revision}
{localDid}
first={index === closed.length - 1} />
{/each}
</div>
{/if}
</div>
</div>
{/if}
{#if actionError}
<span class="footer-note error txt-body-m-regular">{actionError}</span>
{/if}
+132
View File
@@ -0,0 +1,132 @@
<script lang="ts">
import type { ComponentProps, Snippet } from "svelte";
import Icon from "@app/components/Icon.svelte";
interface Props {
icon: ComponentProps<typeof Icon>["name"];
// With a title, the icon heads the box and the children follow below;
// without one, the icon sits beside the text.
title?: string;
tone?: "error" | "warning";
// Ends the notice with a button the user acknowledges it with.
ondismiss?: () => void;
children: Snippet;
}
const { icon, title, tone, ondismiss, children }: Props = $props();
</script>
<style>
.notice {
display: flex;
flex-direction: column;
gap: 0.375rem;
padding: 0.75rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
background-color: var(--color-surface-subtle);
color: var(--color-text-secondary);
}
.notice.inline {
flex-direction: row;
gap: 0.5rem;
}
.notice.error {
border-color: var(--color-feedback-error-border);
background-color: var(--color-feedback-error-bg);
color: var(--color-feedback-error-text);
}
.notice.warning {
border-color: var(--color-feedback-warning-border);
background-color: var(--color-feedback-warning-bg);
color: var(--color-text-primary);
}
.heading {
display: flex;
align-items: center;
gap: 0.375rem;
color: var(--color-text-primary);
}
.content {
display: flex;
flex-direction: column;
gap: 0.375rem;
min-width: 0;
}
.dismiss {
display: flex;
margin-top: 0.375rem;
}
/* The app's filled primary button, in the notice's color. */
.acknowledge {
height: 1.75rem;
padding: 0 0.5rem;
border: 0;
border-radius: var(--border-radius-sm);
background-color: var(--tone-fill, var(--color-surface-brand-secondary));
color: var(--color-text-on-brand);
cursor: pointer;
}
.acknowledge:hover {
background-color: var(
--tone-fill-hover,
var(--color-surface-brand-primary)
);
}
.notice.warning {
--tone-fill: var(--color-feedback-warning-border);
--tone-fill-hover: color-mix(
in srgb,
var(--color-feedback-warning-border) 85%,
black
);
}
.notice.error {
--tone-fill: var(--color-feedback-error-fill);
--tone-fill-hover: var(--color-feedback-error-fill-hover);
}
.notice.error .heading {
color: inherit;
}
.icon {
display: flex;
flex-shrink: 0;
color: var(--color-text-tertiary);
padding-top: 0.0625rem;
}
.notice.warning .icon {
color: inherit;
}
</style>
<div
class="notice"
class:inline={!title}
class:error={tone === "error"}
class:warning={tone === "warning"}>
{#if title}
<div class="heading txt-body-m-medium">
<Icon name={icon} />
{title}
</div>
{:else}
<span class="icon">
<Icon name={icon} />
</span>
{/if}
<!-- Beside the icon in an inline notice, so the button goes under the
text rather than next to it. -->
<div class="content">
{@render children()}
{#if ondismiss}
<div class="dismiss">
<button class="acknowledge txt-body-m-medium" onclick={ondismiss}>
I understand
</button>
</div>
{/if}
</div>
</div>
@@ -0,0 +1,332 @@
<script lang="ts">
import type { ActorInfo } from "@bindings/actor/ActorInfo";
import type { ActorRevision } from "@bindings/actor/ActorRevision";
import { publicKeyFromDid } from "@app/lib/utils";
import Button from "@app/components/Button.svelte";
import Clipboard from "@app/components/Clipboard.svelte";
import Icon from "@app/components/Icon.svelte";
import {
type ActorWrite,
ago,
controllersOf,
describeActorError,
isController,
keyName,
mayChangeKeys,
revisionTitle,
type Vote,
votesText,
} from "./actor";
interface Props {
actor: ActorInfo;
revision: ActorRevision;
localDid: string;
acting: boolean;
act: (
write: ActorWrite,
onerror?: (error: unknown) => void,
) => Promise<void>;
}
const { actor, revision, localDid, acting, act }: Props = $props();
// A vote's error stays on the card it was cast from.
let error = $state<string>();
const vote = (command: Vote) => {
error = undefined;
void act({ command, args: { id: revision.id } }, e => {
error = describeActorError(e, "Could not make the change.");
});
};
const controllers = $derived(controllersOf(actor));
const controls = $derived(isController(actor, localDid));
const canChangeKeys = $derived(mayChangeKeys(actor, localDid));
const mine = $derived(revision.author === localDid);
const signed = $derived(revision.accepted.includes(localDid));
const rejected = $derived(revision.rejected.includes(localDid));
const removesMe = $derived(revision.removed.includes(localDid));
const hinted = $derived(revision.unreadable || removesMe);
const votes = $derived(mine || (controls && !signed && !rejected));
const title = $derived(revisionTitle(actor, revision));
</script>
<style>
.approval {
display: flex;
flex-direction: column;
gap: 0.875rem;
padding: 0.875rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
background-color: var(--color-surface-canvas);
}
.approval-head {
display: flex;
align-items: flex-start;
gap: 0.75rem;
}
.approval-icon {
display: flex;
align-items: center;
justify-content: center;
width: 2rem;
height: 2rem;
flex-shrink: 0;
border-radius: var(--border-radius-md);
background-color: var(--color-surface-subtle);
color: var(--color-text-secondary);
}
.approval-text {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.25rem;
color: var(--color-text-primary);
}
.byline,
.actions-hint {
color: var(--color-text-tertiary);
}
/* The buttons line up with the bottom of a hint that holds a command. */
.actions.tall {
align-items: flex-end;
}
.status {
flex-shrink: 0;
padding: 0.125rem 0.5rem;
border-radius: var(--border-radius-sm);
background-color: var(--color-feedback-warning-bg);
color: var(--color-feedback-warning-text);
}
.status.rejected {
background-color: var(--color-feedback-error-bg);
color: var(--color-feedback-error-text);
}
.actions {
display: flex;
align-items: center;
gap: 0.5rem;
}
.actions-hint {
margin-right: auto;
}
.command {
display: flex;
align-items: flex-start;
gap: 0.5rem;
padding: 0.75rem;
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-subtle);
font: var(--txt-code-regular);
color: var(--color-text-primary);
}
.unsupported {
display: flex;
flex-direction: column;
gap: 0.5rem;
min-width: 0;
word-break: break-all;
}
.signatures {
display: flex;
flex-direction: column;
gap: 0.5rem;
padding-top: 0.875rem;
border-top: 1px solid var(--color-border-subtle);
}
.progress-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.75rem;
color: var(--color-text-secondary);
}
.track {
display: flex;
gap: 0.1875rem;
flex: 1;
max-width: 12rem;
}
.segment {
flex: 1;
height: 0.25rem;
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-mid);
}
.segment.filled {
background-color: var(--color-feedback-success-fill);
}
.signer {
display: flex;
align-items: center;
gap: 0.5rem;
color: var(--color-text-primary);
}
.signer-icon {
display: flex;
flex-shrink: 0;
color: var(--color-text-quaternary);
}
.signer-icon.signed {
color: var(--color-feedback-success-text);
}
.signer-icon.rejected {
color: var(--color-feedback-error-text);
}
.added-key {
display: flex;
flex-direction: column;
gap: 0.25rem;
padding: 0.5rem 0;
border-top: 1px solid var(--color-border-hint);
}
.mono {
font: var(--txt-code-regular);
color: var(--color-text-primary);
word-break: break-all;
}
.card-error {
color: var(--color-feedback-error-text);
}
.chip.brand {
padding: 0 0.375rem;
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-brand-subtle);
color: var(--color-text-brand);
}
.signer-when {
margin-left: auto;
color: var(--color-text-tertiary);
}
</style>
<div class="approval">
<div class="approval-head">
<span class="approval-icon"><Icon name="key" /></span>
<div class="approval-text">
<span class="txt-body-m-medium">{title}</span>
<span class="byline txt-body-m-regular">
Proposed by {mine ? "this device" : keyName(actor, revision.author)}
{ago(revision.createdAt)}
</span>
</div>
{#if revision.rejected.length > 0}
<span class="status rejected txt-body-m-medium">Rejected</span>
{:else}
<span class="status txt-body-m-medium">Awaiting signatures</span>
{/if}
</div>
<!-- Approving is a decision about a key, so each key added is shown
whole; the alias only labels it. -->
{#each revision.added as key (key.did)}
<div class="added-key txt-body-m-regular">
{#if key.alias}
<span class="txt-body-m-medium">{key.alias}</span>
{/if}
<span class="mono">{publicKeyFromDid(key.did)}</span>
</div>
{/each}
<div class="signatures">
<div class="progress-row">
<span class="txt-body-m-medium">
{votesText(actor, revision)}
</span>
<div class="track">
{#each Array.from({ length: actor.majority }, (_, i) => i) as slot (slot)}
<span class="segment" class:filled={slot < revision.accepted.length}>
</span>
{/each}
</div>
</div>
{#each controllers as key (key.did)}
{@const verdict = revision.accepted.includes(key.did)
? "signed"
: revision.rejected.includes(key.did)
? "rejected"
: "waiting"}
<div class="signer txt-body-m-regular">
<span
class="signer-icon"
class:signed={verdict === "signed"}
class:rejected={verdict === "rejected"}>
<Icon
name={verdict === "signed"
? "checkmark"
: verdict === "rejected"
? "close"
: "clock"} />
</span>
<span>{keyName(actor, key.did)}</span>
{#if key.did === localDid}
<span class="chip brand txt-body-s-regular">This device</span>
{/if}
<span class="signer-when">{verdict}</span>
</div>
{/each}
</div>
{#if hinted || votes}
<div class="actions" class:tall={revision.unreadable}>
<span class="actions-hint txt-body-m-regular">
{#if revision.unreadable}
{@const command = `rad id show ${revision.id} --repo ${actor.rid}`}
<span class="unsupported">
This change edits more than this version of Desktop supports. Review
it with this command.
<span class="command">
<span style:flex="1">{command}</span>
<Clipboard text={command} />
</span>
</span>
{:else if removesMe}
Approving removes this device from your profile.
{/if}
</span>
{#if mine}
<Button
variant="outline"
bordered
disabled={acting}
onclick={() => vote("withdraw_actor_revision")}>
Withdraw
</Button>
{:else if controls && !signed && !rejected}
<Button
variant="outline"
bordered
disabled={acting}
onclick={() => vote("reject_actor_revision")}>
Reject
</Button>
{#if canChangeKeys && !revision.unreadable}
<Button
variant="secondary"
disabled={acting}
onclick={() => vote("approve_actor_revision")}>
Approve
</Button>
{/if}
{/if}
</div>
{/if}
{#if error}
<span class="card-error txt-body-m-regular">{error}</span>
{/if}
</div>
+272
View File
@@ -0,0 +1,272 @@
<script lang="ts">
import type { ComponentProps } from "svelte";
import * as router from "@app/lib/router";
import type { ProfileTab, SidebarData } from "@app/lib/router/definitions";
import { didFromPublicKey } from "@app/lib/utils";
import Button from "@app/components/Button.svelte";
import CopyableId from "@app/components/CopyableId.svelte";
import Icon from "@app/components/Icon.svelte";
import ScrollArea from "@app/components/ScrollArea.svelte";
import Topbar from "@app/components/Topbar.svelte";
import Layout from "@app/views/repo/Layout.svelte";
import JoinActor from "./JoinActor.svelte";
import Keys from "./Keys.svelte";
import Notice from "./Notice.svelte";
import ProfileForm from "./ProfileForm.svelte";
import SeveralProfiles from "./SeveralProfiles.svelte";
interface Props {
sidebarData: SidebarData;
tab: ProfileTab;
}
const { sidebarData, tab }: Props = $props();
const actor = $derived(sidebarData.actor);
const localDid = $derived(didFromPublicKey(sidebarData.config.publicKey));
const tabs = $derived<
{
value: ProfileTab;
label: string;
icon: ComponentProps<typeof Icon>["name"];
count?: number;
}[]
>([
{ value: "profile", label: "Profile", icon: "avatar-incognito" },
{ value: "keys", label: "Keys", icon: "key", count: actor?.keys.length },
]);
// The user may well have a profile on another device, so this speaks only
// of this one.
const NO_PROFILE = "This device has no profile yet.";
let editing = $state(false);
let joining = $state(false);
// A profile that arrives while the form is up, as after a create, ends the
// choice.
$effect(() => {
if (actor) {
editing = false;
joining = false;
}
});
</script>
<style>
.page {
display: flex;
flex-direction: column;
height: 100%;
}
.tabs {
display: flex;
align-items: center;
gap: 0.25rem;
}
.tab {
display: flex;
align-items: center;
gap: 0.25rem;
font: var(--txt-body-m-regular);
color: var(--color-text-secondary);
padding: 0.25rem 0.5rem;
border-radius: var(--border-radius-sm);
text-decoration: none;
cursor: pointer;
white-space: nowrap;
}
.tab:hover {
background-color: var(--color-surface-subtle);
color: var(--color-text-primary);
}
.tab.active {
background-color: var(--color-surface-subtle);
color: var(--color-text-primary);
}
.topbar-end {
margin-left: auto;
display: flex;
align-items: center;
gap: 0.5rem;
}
.actor-label {
color: var(--color-text-tertiary);
}
.chip {
padding: 0.125rem 0.375rem;
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-subtle);
color: var(--color-text-secondary);
}
.body {
flex: 1;
min-height: 0;
}
.inner {
width: min(100%, 52rem);
margin: 0 auto;
padding: 1.5rem 1.5rem 7rem;
display: flex;
flex-direction: column;
gap: 1.5rem;
}
/* Room for the preview beside the form. */
.inner.wide {
width: min(100%, 68rem);
}
.missing {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.5rem;
text-align: center;
color: var(--color-text-secondary);
}
.missing-icon {
display: flex;
margin-bottom: 0.5rem;
color: var(--color-text-tertiary);
}
.missing-title {
color: var(--color-text-primary);
}
.empty {
display: flex;
height: 100%;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 1rem;
}
</style>
{#snippet failed(error: { code: string; message: string })}
{#if error.code === "ActorError.Ambiguous"}
<ScrollArea style="height: 100%; min-width: 0;">
<div class="inner">
<SeveralProfiles {localDid} {tab} message={error.message} />
</div>
</ScrollArea>
{:else}
<div class="empty">
<div class="inner">
<Notice icon="warning" tone="error" title="Could not load the profile">
<span class="txt-body-m-regular">{error.message}</span>
</Notice>
</div>
</div>
{/if}
{/snippet}
{#snippet missing(text: string)}
<div class="missing">
<span class="missing-icon"><Icon name="avatar-incognito" size="32" /></span>
<span class="missing-title txt-body-l-medium">{text}</span>
<span class="txt-body-m-regular">
A profile ties your devices together under one name.
</span>
</div>
{/snippet}
<Layout selfScroll>
<div class="page">
<Topbar>
<div class="tabs">
{#each tabs as t (t.value)}
<a
class="tab"
class:active={tab === t.value}
href={router.routeToPath({ resource: "profile", tab: t.value })}>
<Icon name={t.icon} />
{t.label}
{#if t.count}
<span class="global-counter-badge">{t.count}</span>
{/if}
</a>
{/each}
</div>
{#if actor}
<div class="topbar-end">
{#if actor.kind === "agent"}
<span class="chip txt-body-m-regular">Automated agent</span>
{/if}
<span class="actor-label txt-body-m-regular">Profile ID</span>
<CopyableId id={actor.rid} styleFont="var(--txt-body-m-regular)">
{actor.rid}
</CopyableId>
<Button
variant="ghost"
title="The identity document of this profile"
onclick={() =>
router.push({ resource: "repo.identity", rid: actor.rid })}>
<Icon name="code" />
Identity
</Button>
</div>
{/if}
</Topbar>
<div class="body">
{#if sidebarData.actorError}
{@render failed(sidebarData.actorError)}
{:else if tab === "profile"}
{#if actor || editing}
<ScrollArea style="height: 100%; min-width: 0;">
<div class="inner wide">
<ProfileForm
{actor}
{localDid}
config={sidebarData.config}
oncancel={() => (editing = false)} />
</div>
</ScrollArea>
{:else if joining}
<div class="empty">
<JoinActor
publicKey={sidebarData.config.publicKey}
alias={sidebarData.config.alias}
oncancel={() => (joining = false)} />
</div>
{:else}
<div class="empty">
{@render missing(NO_PROFILE)}
<div
class="global-flex"
style:gap="0.5rem"
style:margin-top="0.5rem">
<Button
variant="outline"
bordered
onclick={() => (joining = true)}>
Join existing profile
</Button>
<Button variant="secondary" onclick={() => (editing = true)}>
Create a new profile
</Button>
</div>
</div>
{/if}
{:else if actor}
<ScrollArea style="height: 100%; min-width: 0;">
<div class="inner">
<Keys {actor} {localDid} />
</div>
</ScrollArea>
{:else}
<div class="empty">
{@render missing(NO_PROFILE)}
</div>
{/if}
</div>
</div>
</Layout>
@@ -0,0 +1,179 @@
<script lang="ts">
import type { ActorInfo } from "@bindings/actor/ActorInfo";
import { hide } from "@app/lib/modal";
import * as router from "@app/lib/router";
import ActorAvatar from "@app/components/ActorAvatar.svelte";
import Button from "@app/components/Button.svelte";
import Clipboard from "@app/components/Clipboard.svelte";
import Icon from "@app/components/Icon.svelte";
import { profileName } from "./actor";
interface Props {
actor: ActorInfo;
}
const { actor }: Props = $props();
const rid = $derived(actor.rid);
async function toKeys() {
hide();
await router.push({ resource: "profile", tab: "keys" });
}
</script>
<style>
.modal {
width: 30rem;
max-width: 92vw;
display: flex;
flex-direction: column;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-lg);
background-color: var(--color-surface-canvas);
overflow: hidden;
}
.header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 1.5rem;
height: 3.25rem;
border-bottom: 1px solid var(--color-border-subtle);
}
.title {
font: var(--txt-heading-s);
color: var(--color-text-primary);
}
.body {
display: flex;
flex-direction: column;
gap: 1.25rem;
padding: 1.5rem;
}
.profile {
display: flex;
align-items: center;
gap: 0.75rem;
}
.avatar {
width: 2.5rem;
height: 2.5rem;
flex-shrink: 0;
overflow: hidden;
border-radius: var(--border-radius-md);
}
.name {
min-width: 0;
overflow-wrap: anywhere;
color: var(--color-text-primary);
}
.next {
display: flex;
flex-direction: column;
gap: 0.75rem;
padding-top: 1.25rem;
border-top: 1px solid var(--color-border-subtle);
}
.next-title {
color: var(--color-text-primary);
}
.step {
display: flex;
gap: 0.75rem;
color: var(--color-text-secondary);
}
.step-number {
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
width: 1.5rem;
height: 1.5rem;
border-radius: 50%;
background-color: var(--color-surface-subtle);
color: var(--color-text-secondary);
font: var(--txt-body-m-medium);
}
.step-body {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.5rem;
padding-top: 0.125rem;
}
.id {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.625rem 0.75rem;
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-subtle);
font: var(--txt-code-regular);
color: var(--color-text-primary);
word-break: break-all;
}
.actions {
display: flex;
justify-content: flex-end;
gap: 0.5rem;
padding: 0 1.5rem 1.5rem;
}
</style>
<div class="modal">
<div class="header">
<span class="title">Profile created</span>
<Button variant="naked" onclick={hide}>
<span style:color="var(--color-text-tertiary)">
<Icon name="close" />
</span>
</Button>
</div>
<div class="body">
<div class="profile">
<span class="avatar">
<ActorAvatar {actor} styleWidth="100%" />
</span>
<span class="name txt-body-m-medium">{profileName(actor)}</span>
</div>
<div class="next">
<span class="next-title txt-body-m-medium">Add your other devices</span>
<div class="step txt-body-m-regular">
<span class="step-number">1</span>
<span class="step-body">
On another device, open Profile and choose Join existing profile.
</span>
</div>
<div class="step txt-body-m-regular">
<span class="step-number">2</span>
<div class="step-body">
Paste this Profile ID.
<div class="id">
<span style:flex="1">{rid}</span>
<Clipboard text={rid} />
</div>
</div>
</div>
<div class="step txt-body-m-regular">
<span class="step-number">3</span>
<span class="step-body">Approve the device here, under Keys.</span>
</div>
</div>
</div>
<div class="actions">
<Button variant="outline" bordered onclick={hide}>Done</Button>
<Button variant="secondary" onclick={() => void toKeys()}>
Go to Keys
</Button>
</div>
</div>
@@ -0,0 +1,965 @@
<script lang="ts">
import type { ActorFork } from "@bindings/actor/ActorFork";
import type { ActorInfo } from "@bindings/actor/ActorInfo";
import type { ActorProfile } from "@bindings/actor/ActorProfile";
import type { ProfileLink } from "@bindings/actor/ProfileLink";
import type { Config } from "@bindings/config/Config";
import { onDestroy, untrack } from "svelte";
import { hints } from "@app/lib/hints";
import { entityUrl } from "@app/lib/mentions";
import { show } from "@app/lib/modal";
import { RepoImages } from "@app/lib/repoImages";
import Button from "@app/components/Button.svelte";
import Icon from "@app/components/Icon.svelte";
import TextInput from "@app/components/TextInput.svelte";
import ProfileHistory from "@app/modals/ProfileHistory.svelte";
import { change, describeActorError, isController } from "./actor";
import ExplorerPreview from "./ExplorerPreview.svelte";
import {
compareVersions,
fieldValue,
type Form,
laidOver,
type MergeField,
TEXT_FIELDS,
type TextField,
} from "./form";
import HoverCard from "./HoverCard.svelte";
import ImagePicker, { type PickedImage } from "./ImagePicker.svelte";
import Notice from "./Notice.svelte";
import ProfileCreated from "./ProfileCreated.svelte";
import PronounsPicker from "./PronounsPicker.svelte";
import SplitNotice from "./SplitNotice.svelte";
import TimezonePicker from "./TimezonePicker.svelte";
interface Props {
actor: ActorInfo | null;
localDid: string;
config: Config;
// Leaves the form of a profile not created yet.
oncancel: () => void;
}
const { actor, localDid, config, oncancel }: Props = $props();
// The limits of the profile file, as the backend checks them.
const LIMITS = { string: 255, label: 64, links: 16 } as const;
const LINK_SCHEMES = ["https", "http", "mailto", "rad"];
const IMAGE_SCHEMES = ["https", "http"];
let nextLinkId = 0;
const linkRow = (link: ProfileLink) => ({ ...link, id: nextLinkId++ });
// What a text field shows besides its label: a description above the
// input, a hint below it.
type TextOptions = {
required?: boolean;
description?: string;
hint?: string;
placeholder?: string;
autofocus?: boolean;
};
function formFrom(profile: ActorProfile | undefined): Form {
return {
displayName: profile?.displayName ?? "",
fullName: profile?.fullName ?? "",
pronouns: profile?.pronouns ?? "",
bio: profile?.bio ?? "",
location: profile?.location ?? "",
timezone: profile?.timezone ?? "",
avatar: profile?.avatar ?? "",
banner: profile?.banner ?? "",
links: (profile?.links ?? []).map(linkRow),
};
}
function profileFrom(form: Form): ActorProfile {
const field = (value: string) => value.trim() || undefined;
return {
version: 1,
displayName: form.displayName.trim(),
fullName: field(form.fullName),
pronouns: field(form.pronouns),
bio: field(form.bio),
location: field(form.location),
timezone: field(form.timezone),
avatar: field(form.avatar),
banner: field(form.banner),
links: form.links
.filter(link => link.url.trim() !== "")
.map(({ url, label }) => ({
url: url.trim(),
label: field(label ?? ""),
})),
};
}
// An edit is the profile only once enough controllers carry it, and a
// save here is carried by this key alone. Where that is not enough, there
// is no step for the others to take it over, so the profile is only shown.
const cannotEdit = $derived.by(() => {
if (actor === null) return undefined;
if (!isController(actor, localDid)) {
return "Only a device that controls this profile can edit it. Keys lists which devices do.";
}
if (actor.threshold > 1) {
return `Edits to this profile need ${actor.threshold} controllers to agree, so it is shown here read-only.`;
}
return undefined;
});
const shown = $derived(actor?.profile);
const shownHead = $derived(actor?.head);
// The parent reuses this component across routes, so the form is rebuilt
// when the route brings a different profile, as after a save.
// svelte-ignore state_referenced_locally
let form = $state<Form>(formFrom(actor?.profile));
// svelte-ignore state_referenced_locally
let lastHead = actor?.head;
// The profile the form was built from, to tell edits from a clean form.
// svelte-ignore state_referenced_locally
let base = actor?.profile;
$effect(() => {
if (shownHead !== lastHead) {
lastHead = shownHead;
// A create form whose key turned out to have a profile, made elsewhere
// or just now: what was typed goes over it, so a save does not blank
// its other fields. Otherwise edits survive a head that moved under
// them; a save then extends the new head.
if (base === undefined && shown !== undefined) {
form = laidOver(form, formFrom(shown), formFrom(undefined));
} else if (same(form, formFrom(base)) && !anyPicked) {
form = formFrom(shown);
submitted = false;
}
base = shown;
}
});
// The pictures chosen since the last save. Each replaces what its field
// holds when the profile is saved.
type ImageField = "avatar" | "banner";
let picked = $state<Partial<Record<ImageField, PickedImage>>>({});
const anyPicked = $derived(
picked.avatar !== undefined || picked.banner !== undefined,
);
const images = new RepoImages();
onDestroy(() => images.dispose());
// The file in the profile's repository that the saved profile names and
// the form still does.
function savedImage(field: ImageField) {
const path = shown?.[field];
if (!actor?.head || !path || path.includes(":")) return undefined;
if (picked[field] || form[field].trim() !== path) return undefined;
return { rid: actor.rid, head: actor.head, path };
}
// The saved pictures the form still names, loaded to show them.
const savedUrls = $state<Partial<Record<ImageField, string>>>({});
for (const field of ["avatar", "banner"] as const) {
$effect(() => {
const ref = savedImage(field);
if (!ref) {
savedUrls[field] = undefined;
return;
}
let gone = false;
void images
.load(ref.rid, ref.head, ref.path)
.then(image => {
if (!gone) savedUrls[field] = image?.url;
})
.catch((e: unknown) => {
console.warn(`Could not load the ${field} picture`, e);
if (!gone) savedUrls[field] = undefined;
});
return () => {
gone = true;
};
});
}
// The picture a field shows: one picked and not saved, or the saved file.
// One kept at a web address is not fetched, since that would tell its host
// who is looking.
function imageSrc(field: ImageField): string | undefined {
return picked[field]?.url ?? savedUrls[field];
}
// The previews show the form as typed, where the profile is seen.
type Surface = "card" | "explorer";
let surface = $state<Surface>("card");
const avatarId = $derived(actor?.rid ?? config.publicKey);
const previewKeys = $derived(
actor
? actor.keys
.filter(key => key.bound)
.map(key => ({ did: key.did, alias: key.alias ?? undefined }))
: [{ did: localDid, alias: config.alias }],
);
const explorerUrl = $derived(
entityUrl({ type: "node", nid: config.publicKey }, config),
);
// Puts another version's value of a field into the form.
function pickFrom(field: MergeField, from: ActorProfile | undefined) {
const picked = formFrom(from);
if (field === "links") form.links = picked.links;
else form[field] = picked[field];
}
// Takes from another version each field only its device changed since
// the versions split, where the form still holds the profile's value.
function takeTheirs(fork: ActorFork) {
if (!actor) return;
const current = profileFrom(form);
for (const { field, changedOn } of compareVersions(
actor.profile,
fork.profile,
fork.base,
)) {
if (
changedOn === "theirs" &&
fieldValue(current, field) === fieldValue(actor.profile, field)
) {
pickFrom(field, fork.profile);
}
}
}
// A version is taken from once, when the split first shows; the user
// picks the rest.
const merged: string[] = [];
$effect(() => {
if (!actor) return;
for (const fork of actor.forks) {
if (merged.includes(fork.head) || fork.profileNewer) continue;
merged.push(fork.head);
untrack(() => takeTheirs(fork));
}
});
let submitting = $state(false);
let submitted = $state(false);
let submitError = $state<string>();
// What the last save did, shown briefly beside the button: a message that
// stays could outlast what it was said of.
let saved = $state(false);
// A profile just created is announced once it has loaded, with what to do
// next.
let created = $state(false);
$effect(() => {
if (!created || !actor) return;
created = false;
show({
component: ProfileCreated,
props: { actor },
});
});
const SAVED_MS = 4000;
let savedTimer: ReturnType<typeof setTimeout> | undefined;
// Nothing is saved from here when this device cannot edit the profile, or
// when a newer app wrote the file: it has fields this one would drop, here
// or on another controller's version that a save would replace.
const readOnly = $derived(
actor !== null &&
(cannotEdit !== undefined ||
actor.profileNewer ||
actor.forks.some(fork => fork.profileNewer)),
);
// A form that turns read-only under an edit goes back to the profile: the
// edit has nowhere to be saved from, and the notice says why.
$effect(() => {
if (!readOnly) return;
untrack(() => {
form = formFrom(shown);
picked = {};
confirmingRemove = undefined;
submitted = false;
});
});
const changed = $derived(
actor !== null && (!same(form, formFrom(shown)) || anyPicked),
);
$effect(() => {
if (changed) saved = false;
});
// Another controller's version makes the form as it is worth saving: the
// save is what replaces that version.
const dirty = $derived(
actor === null ||
actor.profile === undefined ||
changed ||
actor.forks.length > 0,
);
// Lengths count code points of the trimmed text in NFC, as the limits do.
const length = (value: string) =>
Array.from(value.trim().normalize("NFC")).length;
const tooLong = (value: string, limit: number) => {
const over = length(value) - limit;
return over > 0 ? `Too long by ${over} characters.` : undefined;
};
const hasScheme = (value: string, schemes: string[]) => {
const scheme = value.split(":", 1)[0];
return value.includes(":") && schemes.includes(scheme.toLowerCase());
};
// Other clients render these as links and images, so what the backend
// refuses is refused here too.
const isImageRef = (value: string) =>
value.includes(":")
? hasScheme(value, IMAGE_SCHEMES)
: !value.includes("\\") &&
!value.includes("%") &&
!value.startsWith("/") &&
!value.split("/").includes("..");
// What the backend would refuse, by field; a link's errors by its index.
const errors = $derived.by(() => {
const text: Partial<Record<TextField, string>> = {};
if (form.displayName.trim().length === 0) {
text.displayName = "Enter a display name.";
}
for (const field of TEXT_FIELDS) {
text[field] ??= tooLong(form[field], LIMITS.string);
}
for (const field of ["avatar", "banner"] as const) {
const image = form[field].trim();
if (image && !isImageRef(image)) {
text[field] ??=
"Desktop cannot save this picture. Remove it to save the profile.";
}
}
const links = form.links.map(link => {
const url = link.url.trim();
if (!url) return undefined;
return (
tooLong(url, LIMITS.string) ??
(hasScheme(url, LINK_SCHEMES)
? tooLong(link.label ?? "", LIMITS.label)
: "A web URL, a mailto: address or a rad: URI.")
);
});
const any = Object.values(text).some(Boolean) || links.some(error => error);
return { text, links, any };
});
const errorOf = (field: TextField) =>
submitted ? errors.text[field] : undefined;
const bioLeft = $derived(LIMITS.string - length(form.bio));
const canAddLink = $derived(form.links.length < LIMITS.links);
const canSubmit = $derived(
dirty && !readOnly && !submitting && !(submitted && errors.any),
);
async function submit() {
submitted = true;
if (errors.any) return;
submitting = true;
submitError = undefined;
saved = false;
const updating = actor !== null;
try {
await change(
{
command: updating ? "update_actor_profile" : "create_actor",
args: {
profile: profileFrom(form),
images: {
avatar: picked.avatar?.base64,
banner: picked.banner?.base64,
},
},
},
"profile",
);
} catch (error) {
submitError = describeActorError(
error,
updating
? "Could not save the profile."
: "Could not create the profile.",
{
"ActorError.Exists":
"This key already has a profile, made elsewhere. It is shown here with your edits over it; save again to apply them.",
},
);
return;
} finally {
submitting = false;
}
form = formFrom(shown);
base = shown;
picked = {};
submitted = false;
if (!updating) {
created = true;
return;
}
saved = true;
clearTimeout(savedTimer);
savedTimer = setTimeout(() => (saved = false), SAVED_MS);
}
function same(a: Form, b: Form): boolean {
return JSON.stringify(profileFrom(a)) === JSON.stringify(profileFrom(b));
}
// Back to the form as it opened, which holds what only another device
// changed: a save without it would undo that device's edit.
function discard() {
picked = {};
form = formFrom(shown);
for (const fork of actor?.forks ?? []) {
if (!fork.profileNewer) takeTheirs(fork);
}
submitted = false;
submitError = undefined;
}
// The row just added, whose URL takes the focus.
let focusedLink = $state<number>();
let confirmingRemove = $state<number>();
function addLink() {
if (!canAddLink) return;
const row = linkRow({ url: "", label: undefined });
focusedLink = row.id;
form.links.push(row);
}
// A row with nothing typed in it goes without asking.
function askRemoveLink(index: number) {
const link = form.links[index];
if (link.url.trim() || link.label?.trim()) confirmingRemove = link.id;
else removeLink(index);
}
function removeLink(index: number) {
confirmingRemove = undefined;
form.links.splice(index, 1);
}
// The bio grows with what is typed instead of scrolling.
let bioElement = $state<HTMLTextAreaElement>();
$effect(() => {
void form.bio;
if (bioElement) {
bioElement.style.height = "0px";
bioElement.style.height = `${bioElement.scrollHeight + 2}px`;
}
});
</script>
<style>
.columns {
display: flex;
align-items: flex-start;
gap: 2rem;
}
.preview-column {
position: sticky;
top: 0;
width: 19rem;
flex-shrink: 0;
display: flex;
flex-direction: column;
gap: 0.625rem;
}
/* Below this the preview stops earning its column. */
@media (max-width: 66rem) {
.columns {
flex-direction: column;
}
.preview-column {
position: static;
width: 100%;
max-width: 22rem;
}
}
.surface-switch {
display: flex;
align-items: center;
}
.surface-note {
color: var(--color-text-secondary);
}
.form {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 1.25rem;
}
.field {
display: flex;
flex-direction: column;
gap: 0.375rem;
}
.picker {
min-width: 0;
}
.field-label {
display: flex;
align-items: baseline;
gap: 0.375rem;
color: var(--color-text-primary);
}
/* Drawn rather than marked up, so reformatting cannot put a space between
the asterisk and the word it marks. */
.required::after {
content: "*";
color: var(--color-text-quaternary);
}
.field-note {
color: var(--color-text-secondary);
}
.field-error {
display: flex;
align-items: center;
gap: 0.375rem;
color: var(--color-feedback-error-text);
}
.counter {
margin-left: auto;
color: var(--color-text-tertiary);
}
.counter.over {
color: var(--color-feedback-error-text);
}
.row {
display: flex;
gap: 0.75rem;
}
.row > :global(*) {
flex: 1;
min-width: 0;
}
.links {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.link-row {
display: flex;
align-items: center;
gap: 0.5rem;
}
.link-url-field {
flex: 1;
min-width: 0;
}
.link-label-field {
width: 9rem;
flex-shrink: 0;
}
.confirm {
display: flex;
align-items: center;
gap: 0.375rem;
flex-shrink: 0;
}
.confirm-text {
color: var(--color-text-secondary);
}
/* Drawn as the app's text inputs are. */
.bio {
width: 100%;
min-height: 2rem;
padding: 0.25rem 0.75rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-base);
color: var(--color-text-primary);
line-height: 1.6;
resize: none;
overflow: hidden;
outline: none;
}
.bio:focus {
border-color: var(--color-border-brand);
}
.bio.invalid {
border-color: var(--color-feedback-error-border);
}
.bio[disabled] {
cursor: not-allowed;
}
.footer {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 0.5rem;
padding-top: 0.25rem;
}
.footer-note {
margin-right: auto;
color: var(--color-text-tertiary);
}
.error {
color: var(--color-feedback-error-text);
}
.success {
display: flex;
align-items: center;
gap: 0.25rem;
color: var(--color-foreground-success);
}
</style>
{#snippet fieldError(message: string | undefined)}
{#if message}
<span class="field-error txt-body-m-regular">
<Icon name="warning" />
{message}
</span>
{/if}
{/snippet}
{#snippet text(field: TextField, label: string, options: TextOptions = {})}
<div class="field">
<span class="field-label txt-body-m-medium">
{#if options.required}
<span class="required">{label}</span>
{:else}
{label}
{/if}
</span>
{#if options.description}
<span class="field-note txt-body-m-regular">{options.description}</span>
{/if}
<TextInput
bind:value={form[field]}
valid={errorOf(field) === undefined}
placeholder={options.placeholder}
autofocus={options.autofocus}
disabled={readOnly} />
{@render fieldError(errorOf(field))}
{#if options.hint}
<span class="field-note txt-body-s-regular">{options.hint}</span>
{/if}
</div>
{/snippet}
<div class="columns">
<aside class="preview-column">
<div class="surface-switch">
<Button
variant="ghost"
flatRight
active={surface === "card"}
onclick={() => (surface = "card")}>
Hover card
</Button>
<Button
variant="ghost"
flatLeft
active={surface === "explorer"}
onclick={() => (surface = "explorer")}>
Explorer
</Button>
</div>
{#if surface === "card"}
<span class="surface-note txt-body-m-regular">
Shown when someone hovers your name in the app.
</span>
<HoverCard
{form}
avatar={imageSrc("avatar")}
banner={imageSrc("banner")}
{avatarId}
did={actor?.rid ?? config.publicKey} />
{:else}
<span class="surface-note txt-body-m-regular">
Your profile on Explorer.
</span>
<ExplorerPreview
{form}
avatar={imageSrc("avatar")}
banner={imageSrc("banner")}
{avatarId}
keys={previewKeys}
url={explorerUrl} />
{/if}
</aside>
<div class="form">
{#if actor?.profileNewer}
<Notice icon="warning" title="Written by a newer Desktop" tone="warning">
<span class="txt-body-m-regular">
This profile was written by a newer version of Desktop. Editing it
here would drop the fields this version does not know, so it is shown
as is.
</span>
</Notice>
{:else if actor?.profileUnreadable}
<Notice icon="warning" title="Profile file not readable" tone="warning">
<span class="txt-body-m-regular">
The profile file in the repository is not one this version of Desktop
can read.
{#if !cannotEdit}Saving replaces it.{/if}
</span>
</Notice>
{/if}
{#if actor && actor.forks.length > 0}
<SplitNotice {actor} current={profileFrom(form)} onpick={pickFrom} />
{/if}
{#if cannotEdit}
<Notice icon="lock" title="Read-only">
<span class="txt-body-m-regular">{cannotEdit}</span>
</Notice>
{/if}
<ImagePicker
kind="avatar"
bind:value={form.avatar}
src={imageSrc("avatar")}
picked={picked.avatar}
fallbackId={avatarId}
disabled={readOnly}
error={errorOf("avatar")}
onpick={image => (picked.avatar = image)} />
<ImagePicker
kind="banner"
bind:value={form.banner}
src={imageSrc("banner")}
picked={picked.banner}
disabled={readOnly}
error={errorOf("banner")}
onpick={image => (picked.banner = image)} />
<div class="row">
{@render text("displayName", "Display name", {
required: true,
// The first thing to type on a new profile; a saved one is read first.
autofocus: actor === null,
hint: "This is not unique.",
})}
{@render text("fullName", "Full name")}
<div class="field">
<span class="field-label txt-body-m-medium">Pronouns</span>
<div class="picker">
<PronounsPicker bind:value={form.pronouns} disabled={readOnly} />
</div>
{@render fieldError(errorOf("pronouns"))}
</div>
</div>
<div class="row">
{@render text("location", "Location")}
<div class="field">
<span class="field-label txt-body-m-medium">Time zone</span>
<div class="picker">
<TimezonePicker bind:value={form.timezone} disabled={readOnly} />
</div>
{@render fieldError(errorOf("timezone"))}
</div>
</div>
<div class="field">
<span class="field-label txt-body-m-medium">
Bio
<span class="counter" class:over={bioLeft < 0}>
{bioLeft < 0 ? `${-bioLeft} over` : `${bioLeft} left`}
</span>
</span>
<textarea
class="bio txt-body-m-regular"
class:invalid={errorOf("bio") !== undefined}
rows="1"
bind:this={bioElement}
bind:value={form.bio}
disabled={readOnly}>
</textarea>
<span class="field-note txt-body-s-regular">
Saved as one paragraph. Line breaks become spaces.
</span>
{@render fieldError(errorOf("bio"))}
</div>
<div class="field">
<span class="field-label txt-body-m-medium">
Links
<span class="counter">
{form.links.length} of {LIMITS.links}
</span>
</span>
<span class="field-note txt-body-m-regular">
Web URLs, mailto: addresses and rad: URIs.
</span>
<div class="links">
{#each form.links as link, index (link.id)}
{@const linkError = submitted ? errors.links[index] : undefined}
<div class="link-row">
<div class="link-url-field">
<TextInput
bind:value={link.url}
valid={linkError === undefined}
placeholder="https://example.com"
autofocus={link.id === focusedLink}
disabled={readOnly}
onSubmit={addLink} />
</div>
<div class="link-label-field">
<TextInput
bind:value={link.label}
placeholder="Label"
disabled={readOnly}
onSubmit={addLink} />
</div>
{#if confirmingRemove === link.id && !readOnly}
<div class="confirm">
<span class="confirm-text txt-body-m-regular">Remove?</span>
<Button
variant="ghost"
styleHeight="1.75rem"
onclick={() => removeLink(index)}>
Yes
</Button>
<Button
variant="outline"
styleHeight="1.75rem"
onclick={() => (confirmingRemove = undefined)}>
Cancel
</Button>
</div>
{:else}
<Button
variant="naked"
title="Remove link"
disabled={readOnly}
onclick={() => askRemoveLink(index)}>
<Icon name="trash" />
</Button>
{/if}
</div>
{@render fieldError(linkError)}
{/each}
<div>
<Button
variant="outline"
bordered
disabled={!canAddLink || readOnly}
onclick={addLink}>
<Icon name="plus" />
Add link
</Button>
</div>
</div>
</div>
<!-- It says the same for every profile, so once read it stays closed. -->
{#if !hints.isDismissed("profile.permanence") && !readOnly}
<Notice
icon="warning"
tone="warning"
ondismiss={() => hints.dismiss("profile.permanence")}>
<span class="txt-body-m-regular">
Everything you save here is permanent. Every node that has your
profile copies it and keeps its earlier versions, even after you
change or remove something.
</span>
</Notice>
{/if}
<div class="footer">
{#if submitError}
<span class="footer-note error txt-body-m-regular">
{submitError}
</span>
{:else if saved}
<span class="footer-note success txt-body-m-regular">
<Icon name="checkmark" />
Saved.
</span>
{:else if changed}
<span class="footer-note txt-body-m-regular">Unsaved changes</span>
{/if}
{#if changed}
<Button variant="outline" bordered onclick={discard}>Discard</Button>
{:else if !actor}
<Button
variant="outline"
bordered
disabled={submitting}
onclick={oncancel}>
Cancel
</Button>
{/if}
{#if actor}
<Button
variant="ghost"
onclick={() => show({ component: ProfileHistory, props: { actor } })}>
View history
</Button>
{/if}
<Button variant="secondary" disabled={!canSubmit} onclick={submit}>
{#if !actor}
Create profile
{:else}
Save profile
{/if}
</Button>
</div>
</div>
</div>
@@ -0,0 +1,152 @@
<script lang="ts">
import Button from "@app/components/Button.svelte";
import DropdownListItem from "@app/components/DropdownListItem.svelte";
import Icon from "@app/components/Icon.svelte";
import Popover, { closeFocused } from "@app/components/Popover.svelte";
import TextInput from "@app/components/TextInput.svelte";
interface Props {
value: string;
disabled?: boolean;
}
/* eslint-disable prefer-const */
let { value = $bindable(""), disabled = false }: Props = $props();
/* eslint-enable prefer-const */
// The field is free text, so these are a shortcut past typing rather than
// the answers allowed.
const common = [
"he/him",
"she/her",
"they/them",
"he/they",
"she/they",
"any pronouns",
];
let expanded = $state(false);
let custom = $state("");
// A value typed before is offered for editing, not retyped.
$effect(() => {
if (expanded) custom = common.includes(value) ? "" : value;
});
function pick(pronouns: string) {
value = pronouns;
closeFocused();
}
</script>
<style>
.control {
display: flex;
align-items: center;
gap: 0.25rem;
min-width: 0;
}
.control > :global(:first-child) {
flex: 1;
min-width: 0;
}
.clear-icon {
display: flex;
color: var(--color-text-tertiary);
}
.trigger {
display: flex;
align-items: center;
gap: 0.5rem;
width: 100%;
min-width: 0;
}
.trigger-value {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.placeholder {
flex: 1;
color: var(--color-text-tertiary);
}
.panel {
display: flex;
flex-direction: column;
width: 14rem;
padding-top: 0.25rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
background-color: var(--color-surface-canvas);
overflow: hidden;
}
.custom {
display: flex;
flex-direction: column;
gap: 0.375rem;
margin-top: 0.25rem;
padding: 0.5rem;
border-top: 1px solid var(--color-border-subtle);
}
.custom-label {
color: var(--color-text-tertiary);
}
</style>
<div class="control">
<Popover
popoverPadding="0"
placement="bottom-start"
styleDisplay="flex"
bind:expanded>
{#snippet toggle(onclick)}
<Button
variant="outline"
bordered
{onclick}
{disabled}
styleWidth="100%"
styleJustifyContent="flex-start">
<span class="trigger">
{#if value}
<span class="trigger-value">{value}</span>
{:else}
<span class="placeholder">Not set</span>
{/if}
<Icon name={expanded ? "chevron-up" : "chevron-down"} />
</span>
</Button>
{/snippet}
{#snippet popover()}
<div class="panel">
{#each common as pronouns (pronouns)}
<DropdownListItem
styleWidth="100%"
selected={value === pronouns}
onclick={() => pick(pronouns)}>
<span class="txt-body-m-regular">{pronouns}</span>
</DropdownListItem>
{/each}
<div class="custom">
<span class="custom-label txt-body-s-regular">Something else</span>
<TextInput
bind:value={custom}
placeholder="Write your own"
styleHeight="1.75rem"
onSubmit={() => {
if (custom.trim()) pick(custom.trim());
}} />
</div>
</div>
{/snippet}
</Popover>
{#if value && !disabled}
<Button variant="naked" title="Clear pronouns" onclick={() => (value = "")}>
<span class="clear-icon"><Icon name="close" /></span>
</Button>
{/if}
</div>
@@ -0,0 +1,88 @@
<script lang="ts">
import ConfirmModal from "@app/modals/ConfirmModal.svelte";
import { describeActorError } from "./actor";
import Notice from "./Notice.svelte";
interface Props {
name: string;
rid: string;
// The profiles shown that this device is in besides the one retired, by
// name; empty if none can be shown.
staysIn: string;
// The devices the profile has besides this one.
others: number;
confirm: () => Promise<void>;
}
const { name, rid, staysIn, others, confirm }: Props = $props();
</script>
<style>
.profile {
display: flex;
flex-direction: column;
gap: 0.25rem;
color: var(--color-text-primary);
}
.rid {
word-break: break-all;
}
.caution {
display: flex;
flex-direction: column;
gap: 0.5rem;
min-width: 0;
}
</style>
<ConfirmModal
title="Retire profile"
width="28rem"
label="Retire"
busyLabel="Retiring…"
describeError={e =>
describeActorError(e, "Could not retire the profile.", {
"ActorError.NotController":
"This device's key does not control this profile, so it cannot retire it.",
"ActorError.PayloadNewer":
"This profile holds fields this version of Desktop does not know, so it cannot retire it.",
})}
{confirm}>
{#snippet body()}
<div class="profile">
<span class="txt-body-m-medium">{name}</span>
<span class="rid">{rid}</span>
</div>
<span>
This ends the profile.
{#if staysIn}
This device stays in {staysIn}.
{/if}
</span>
<Notice icon="warning" tone="warning">
<div class="caution">
{#if others === 1}
<span>
This profile has 1 other device. It loses the profile too, without
being asked.
</span>
{:else if others > 1}
<span>
This profile has {others} other devices. They lose the profile too, without
being asked.
</span>
{/if}
<span>
Nothing is deleted. The profile stays on the network with everything
saved in it.
</span>
<span>This cannot be undone.</span>
</div>
</Notice>
{/snippet}
</ConfirmModal>
@@ -0,0 +1,308 @@
<script lang="ts">
import type { ActorInfo } from "@bindings/actor/ActorInfo";
import { invoke } from "@app/lib/invoke";
import { show } from "@app/lib/modal";
import type { ProfileTab } from "@app/lib/router/definitions";
import Button from "@app/components/Button.svelte";
import CopyableId from "@app/components/CopyableId.svelte";
import {
change,
controllersOf,
describeActorError,
isController,
mayChangeKeys,
profileName,
votedRemoval,
votesText,
} from "./actor";
import Notice from "./Notice.svelte";
import RetireProfile from "./RetireProfile.svelte";
interface Props {
localDid: string;
tab: ProfileTab;
// What the backend said when it found the key in several profiles.
message: string;
}
const { localDid, tab, message }: Props = $props();
let actors = $state<ActorInfo[]>();
let loadError = $state<string>();
let acting = $state(false);
let confirming = $state<string>();
let actionError = $state<{ rid: string; message: string }>();
// A load of the page builds this anew, so another device's vote shows
// then, as on every profile page.
async function load() {
try {
actors = await invoke<ActorInfo[]>("actors_of_key");
loadError = undefined;
} catch (e) {
loadError = describeActorError(e, message);
}
}
void load();
const nameOf = (actor: ActorInfo) =>
actor.profile?.displayName || "the profile with no name";
// The open change by which this device leaves `actor`, once it has voted.
// The backend also counts a change from another tool that unbinds the key
// without removing it; that one shows only as its refusal of a leave.
const leaveOf = (actor: ActorInfo) => votedRemoval(actor, localDid, localDid);
// One leave at a time: two that both went through would leave this device
// in no profile.
const leaving = $derived(actors?.find(actor => leaveOf(actor)));
const several = $derived(actors !== undefined && actors.length > 2);
function staysIn(left: ActorInfo): string {
return (actors ?? [])
.filter(actor => actor.rid !== left.rid)
.map(nameOf)
.join(" and ");
}
// Retiring is permanent and applies at once, so it is confirmed in a
// dialog, which shows a failure itself.
function openRetire(actor: ActorInfo) {
show({
component: RetireProfile,
props: {
name: profileName(actor),
rid: actor.rid,
staysIn: staysIn(actor),
others: actor.keys.length - 1,
confirm: async () => {
try {
await change(
{ command: "retire_actor", args: { rid: actor.rid } },
tab,
);
} finally {
// Not waited for: the page has reloaded by now, and this only
// refreshes the list where the device is still in several.
void load();
}
},
},
});
}
async function act(
command: "leave_actor" | "cancel_leave",
actor: ActorInfo,
fallback: string,
) {
confirming = undefined;
actionError = undefined;
acting = true;
try {
await change({ command, args: { rid: actor.rid } }, tab);
} catch (e) {
actionError = {
rid: actor.rid,
message: describeActorError(e, fallback),
};
} finally {
await load();
acting = false;
}
}
</script>
<style>
.profiles {
display: flex;
flex-direction: column;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
overflow: hidden;
}
.profile {
display: flex;
flex-direction: column;
gap: 0.5rem;
padding: 0.75rem;
background-color: var(--color-surface-canvas);
}
.profile + .profile {
border-top: 1px solid var(--color-border-subtle);
}
.head {
display: flex;
align-items: center;
gap: 0.75rem;
}
.name {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.25rem;
color: var(--color-text-primary);
}
.text {
color: var(--color-text-secondary);
}
.confirm {
display: flex;
align-items: center;
gap: 0.375rem;
flex-wrap: wrap;
color: var(--color-text-secondary);
}
.did {
color: var(--color-text-primary);
word-break: break-all;
}
.error {
color: var(--color-feedback-error-text);
}
</style>
<Notice
icon="warning"
tone="error"
title={several
? "This device is in several profiles"
: "This device is in two profiles"}>
<span class="txt-body-m-regular">
{#if several}
A device belongs to one profile. Until this one is in one only, its work
is credited to none of them and it cannot change any.
{:else}
A device belongs to one profile. Until this one leaves the other, its work
is credited to neither and it cannot change either.
{/if}
</span>
</Notice>
{#if loadError}
<span class="error txt-body-m-regular">{loadError}</span>
{:else if actors}
<div class="profiles">
{#each actors as actor (actor.rid)}
{@const controllers = controllersOf(actor)}
{@const open = leaveOf(actor)}
<div class="profile txt-body-m-regular">
<div class="head">
<div class="name">
<span class="txt-body-m-medium">
{profileName(actor)}
</span>
<CopyableId id={actor.rid} styleFont="var(--txt-body-m-regular)">
{actor.rid}
</CopyableId>
</div>
{#if open?.author === localDid}
<Button
variant="outline"
bordered
disabled={acting}
onclick={() =>
act("cancel_leave", actor, "Could not cancel the leave.")}>
Cancel leave
</Button>
{:else if !leaving && mayChangeKeys(actor, localDid) && controllers.length > 1 && confirming !== actor.rid}
<Button
variant="outline"
bordered
disabled={acting}
onclick={() => (confirming = actor.rid)}>
Leave
</Button>
{:else if !leaving && mayChangeKeys(actor, localDid) && controllers.length === 1}
<Button
variant="outline"
bordered
disabled={acting}
onclick={() => openRetire(actor)}>
Retire
</Button>
{/if}
</div>
{#if open?.author === localDid}
<span class="text">
You asked to leave. Open Keys on a device that controls this profile
and approve the change. {votesText(actor, open)}.
</span>
{:else if open}
<!-- Only the key that proposed a change withdraws it. -->
<span class="text">
Another device proposed removing this one, and you approved.
{votesText(actor, open)}. Only that device can withdraw it.
</span>
{:else if leaving}
<span class="text">
You are already leaving {nameOf(leaving)}. Cancel that leave first,
or wait until it is approved or rejected.
</span>
{:else if !isController(actor, localDid)}
<span class="text">
Only a controller can remove this device. Open Keys on one of these
and revoke this device's key:
</span>
{#each controllers as key (key.did)}
<span class="txt-body-s-regular">
{#if key.alias}
<span class="txt-body-s-medium">{key.alias}</span>
{/if}
<span class="did">{key.did}</span>
</span>
{/each}
{:else if actor.payloadNewer}
<span class="text">
Written by a newer Desktop or another app, so this device cannot
leave it from here.
</span>
{:else if controllers.length === 1}
<span class="text">
This device is the only controller here, so it cannot leave. This
profile can only be retired.
</span>
{:else if confirming === actor.rid}
<div class="confirm">
<span>
Leave {nameOf(actor)}? This device stays in {staysIn(actor)} and cannot
be added to {nameOf(actor)} again while {staysIn(actor)} exists.
</span>
<Button
variant="ghost"
styleHeight="1.75rem"
disabled={acting}
onclick={() =>
act("leave_actor", actor, "Could not leave the profile.")}>
Yes
</Button>
<Button
variant="outline"
styleHeight="1.75rem"
disabled={acting}
onclick={() => (confirming = undefined)}>
Cancel
</Button>
</div>
{/if}
{#if actionError?.rid === actor.rid}
<span class="error">{actionError.message}</span>
{/if}
</div>
{/each}
</div>
{/if}
@@ -0,0 +1,214 @@
<script lang="ts">
import type { ActorInfo } from "@bindings/actor/ActorInfo";
import type { ActorProfile } from "@bindings/actor/ActorProfile";
import { show } from "@app/lib/modal";
import Button from "@app/components/Button.svelte";
import Icon from "@app/components/Icon.svelte";
import ProfileVersionModal from "@app/modals/ProfileVersion.svelte";
import { keyName } from "./actor";
import { compareVersions, fieldValue, type MergeField } from "./form";
import Notice from "./Notice.svelte";
interface Props {
// An actor with versions of the profile on other controllers' branches.
actor: ActorInfo;
// The profile as the form holds it now.
current: ActorProfile;
// Puts a version's value of a field into the form.
onpick: (field: MergeField, from: ActorProfile | undefined) => void;
}
const { actor, current, onpick }: Props = $props();
const LABELS: Record<MergeField, string> = {
displayName: "Display name",
fullName: "Full name",
pronouns: "Pronouns",
bio: "Bio",
location: "Location",
timezone: "Time zone",
avatar: "Avatar",
banner: "Banner",
links: "Links",
};
const forks = $derived(
actor.forks.map(fork => ({
...fork,
name: keyName(actor, fork.did),
differences: compareVersions(actor.profile, fork.profile, fork.base),
})),
);
const picked = (field: MergeField, from: ActorProfile | undefined) =>
fieldValue(current, field) === fieldValue(from, field);
</script>
<style>
.lead {
color: var(--color-text-primary);
}
.compare {
display: grid;
grid-template-columns: 7rem 1fr 1fr;
gap: 0.375rem 0.5rem;
margin-top: 0.375rem;
padding: 0.75rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
background-color: var(--color-surface-canvas);
}
.column {
color: var(--color-text-tertiary);
}
.field {
display: flex;
flex-direction: column;
gap: 0.125rem;
padding-top: 0.5rem;
color: var(--color-text-primary);
}
.note {
color: var(--color-text-tertiary);
}
.option {
align-self: start;
display: flex;
align-items: flex-start;
gap: 0.5rem;
padding: 0.5rem 0.625rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-canvas);
color: var(--color-text-primary);
font: var(--txt-body-m-regular);
text-align: left;
cursor: pointer;
min-width: 0;
}
.option:hover {
border-color: var(--color-border-mid);
}
.option.picked {
border-color: var(--color-border-brand);
background-color: var(--color-surface-brand-subtle);
}
.value {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 0.125rem;
overflow-wrap: anywhere;
}
.empty {
color: var(--color-text-tertiary);
}
.check {
display: flex;
flex-shrink: 0;
color: var(--color-text-brand);
visibility: hidden;
}
.picked .check {
visibility: visible;
}
.raw {
display: flex;
padding-top: 0.25rem;
}
</style>
{#snippet value(field: MergeField, from: ActorProfile | undefined)}
{#if field === "links"}
{#each from?.links ?? [] as link (link.url)}
<span>{link.label ? `${link.label}: ` : ""}{link.url}</span>
{:else}
<span class="empty">No links</span>
{/each}
{:else if fieldValue(from, field)}
<span>{fieldValue(from, field)}</span>
{:else}
<span class="empty">Empty</span>
{/if}
{/snippet}
{#snippet option(field: MergeField, from: ActorProfile | undefined)}
<button
type="button"
class="option"
class:picked={picked(field, from)}
onclick={() => onpick(field, from)}>
<span class="value">{@render value(field, from)}</span>
<span class="check"><Icon name="checkmark" /></span>
</button>
{/snippet}
{#each forks as fork (fork.did)}
<Notice icon="warning" title={`Also edited on ${fork.name}`} tone="warning">
{#if fork.profileNewer}
<span class="txt-body-m-regular">
The version on {fork.name} was written by a newer Desktop, so this one cannot
replace it. Save the profile from {fork.name}.
</span>
{:else}
<span class="lead txt-body-m-regular">
{#if fork.differences.some(d => d.changedOn === "both")}
Pick which version to keep where both devices changed something, then
save.
{:else}
Its changes are filled in below. Save to publish them.
{/if}
</span>
{#if fork.differences.length > 0}
<div class="compare txt-body-m-regular">
<span></span>
<span class="column txt-body-s-regular">This device</span>
<span class="column txt-body-s-regular">{fork.name}</span>
{#each fork.differences as { field, changedOn } (field)}
<span class="field txt-body-m-medium">
{LABELS[field]}
{#if changedOn === "theirs"}
<span class="note txt-body-s-regular">
Only changed on {fork.name}
</span>
{/if}
</span>
{@render option(field, actor.profile)}
{@render option(field, fork.profile)}
{/each}
</div>
{/if}
{#if fork.otherFiles}
<span class="txt-body-m-regular">
The version on {fork.name} also changed other files in the repository. Saving
here leaves them out; they stay in the history.
</span>
{/if}
{/if}
<div class="raw">
<Button
variant="naked"
styleHeight="1.75rem"
onclick={() =>
show({
component: ProfileVersionModal,
props: {
name: fork.name,
head: fork.head,
profile: fork.profile,
changes: fork.changes,
},
})}>
<Icon name="code" />View raw changes
</Button>
</div>
</Notice>
{/each}
@@ -0,0 +1,257 @@
<script lang="ts">
import fuzzysort from "fuzzysort";
import Button from "@app/components/Button.svelte";
import DropdownListItem from "@app/components/DropdownListItem.svelte";
import Icon from "@app/components/Icon.svelte";
import Popover, { closeFocused } from "@app/components/Popover.svelte";
import ScrollArea from "@app/components/ScrollArea.svelte";
import TextInput from "@app/components/TextInput.svelte";
interface Props {
value: string;
disabled?: boolean;
}
/* eslint-disable prefer-const */
let { value = $bindable(""), disabled = false }: Props = $props();
/* eslint-enable prefer-const */
const supported: string[] = (() => {
try {
return Intl.supportedValuesOf("timeZone");
} catch {
return ["UTC"];
}
})();
const detected: string | undefined = (() => {
try {
return Intl.DateTimeFormat().resolvedOptions().timeZone;
} catch {
return undefined;
}
})();
// Every IANA zone, so the answer is never "none of these six". The list
// leaves out UTC and aliases such as Asia/Calcutta, which the system or a
// stored profile can still name.
const zones = $derived([
...new Set(
[...supported, detected, value].filter(
(zone): zone is string => typeof zone === "string" && zone !== "",
),
),
]);
let filter = $state("");
let expanded = $state(false);
// The Etc/GMT zones are fixed offsets rather than places, so they sit after
// the real ones instead of interleaving with them.
function isOffset(zone: string): boolean {
return zone.startsWith("Etc/");
}
// Shown without the "Etc/" prefix, which means nothing to anyone.
function label(zone: string): string {
return isOffset(zone) ? zone.slice("Etc/".length) : zone;
}
function offsetsLast(list: string[]): string[] {
return [...list.filter(z => !isOffset(z)), ...list.filter(isOffset)];
}
// Every zone, with the detected one first so it is one click away.
const results = $derived.by(() => {
const matched = filter.trim()
? fuzzysort.go(filter, zones, { all: false }).map(r => r.target)
: [...zones].sort((a, b) => a.localeCompare(b));
const ordered = offsetsLast(matched);
return detected && ordered.includes(detected)
? [detected, ...ordered.filter(zone => zone !== detected)]
: ordered;
});
// The moment the picker opened, so every row shows the same minute.
const now = $derived.by(() => {
void expanded;
return new Date();
});
function localTime(zone: string): string | undefined {
try {
return new Intl.DateTimeFormat(undefined, {
timeStyle: "short",
timeZone: zone,
}).format(now);
} catch {
return undefined;
}
}
function pick(zone: string) {
value = zone;
filter = "";
closeFocused();
}
</script>
<style>
.control {
display: flex;
align-items: center;
gap: 0.25rem;
min-width: 0;
}
.control > :global(:first-child) {
flex: 1;
min-width: 0;
}
.clear-icon {
display: flex;
color: var(--color-text-tertiary);
}
.trigger {
display: flex;
align-items: center;
gap: 0.5rem;
width: 100%;
min-width: 0;
}
.trigger-value {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.trigger-time {
flex-shrink: 0;
color: var(--color-text-tertiary);
}
.chip {
flex-shrink: 0;
padding: 0.125rem 0.375rem;
border-radius: var(--border-radius-sm);
background-color: var(--color-surface-subtle);
color: var(--color-text-secondary);
}
.placeholder {
flex: 1;
color: var(--color-text-tertiary);
}
.panel {
display: flex;
flex-direction: column;
width: 20rem;
border: 1px solid var(--color-border-subtle);
border-radius: var(--border-radius-md);
background-color: var(--color-surface-canvas);
overflow: hidden;
}
.search {
padding: 0.5rem;
border-bottom: 1px solid var(--color-border-subtle);
}
.list {
max-height: 16rem;
}
.row {
display: flex;
align-items: center;
gap: 0.5rem;
width: 100%;
min-width: 0;
}
.zone {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.time {
margin-left: auto;
flex-shrink: 0;
color: var(--color-text-tertiary);
}
.empty {
padding: 0.75rem;
color: var(--color-text-tertiary);
}
</style>
<div class="control">
<Popover
popoverPadding="0"
placement="bottom-start"
styleDisplay="flex"
bind:expanded>
{#snippet toggle(onclick)}
<Button
variant="outline"
bordered
{onclick}
{disabled}
styleWidth="100%"
styleJustifyContent="flex-start">
<span class="trigger">
<Icon name="clock" />
{#if value}
<span class="trigger-value">{label(value)}</span>
{#if localTime(value)}
<span class="trigger-time">{localTime(value)}</span>
{/if}
{:else}
<span class="placeholder">Not set</span>
{/if}
<Icon name={expanded ? "chevron-up" : "chevron-down"} />
</span>
</Button>
{/snippet}
{#snippet popover()}
<div class="panel">
<div class="search">
<TextInput
autofocus
bind:value={filter}
placeholder="Search time zones"
styleHeight="1.75rem" />
</div>
{#if results.length > 0}
<ScrollArea style="max-height: 16rem;">
<div class="list">
{#each results as zone (zone)}
<DropdownListItem
styleWidth="100%"
selected={value === zone}
onclick={() => pick(zone)}>
<span class="row txt-body-m-regular">
<span class="zone">{label(zone)}</span>
{#if zone === detected}
<span class="chip txt-body-m-medium">Detected</span>
{/if}
<span class="time">{localTime(zone)}</span>
</span>
</DropdownListItem>
{/each}
</div>
</ScrollArea>
{:else}
<div class="empty txt-body-m-regular">No matching time zones</div>
{/if}
</div>
{/snippet}
</Popover>
{#if value && !disabled}
<Button
variant="naked"
title="Clear time zone"
onclick={() => (value = "")}>
<span class="clear-icon"><Icon name="close" /></span>
</Button>
{/if}
</div>
+199
View File
@@ -0,0 +1,199 @@
import type { ActorInfo } from "@bindings/actor/ActorInfo";
import type { ActorKey } from "@bindings/actor/ActorKey";
import type { ActorProfile } from "@bindings/actor/ActorProfile";
import type { ActorRevision } from "@bindings/actor/ActorRevision";
import type { ProfileImages } from "@bindings/actor/ProfileImages";
import { get } from "svelte/store";
import { nodeRunning } from "@app/lib/events";
import { invalidateReposSummary, invoke, InvokeError } from "@app/lib/invoke";
import * as router from "@app/lib/router";
import type { ProfileTab } from "@app/lib/router/definitions";
import { formatTimestamp, publicKeyFromDid, truncateId } from "@app/lib/utils";
import { announce } from "@app/components/AnnounceSwitch.svelte";
// Where the profile is kept in the actor's repository.
export const PROFILE_PATH = ".radicle/profile.json";
// The text for `error`: `overrides` first, where a place needs other words
// than the backend's for a code, then the backend's own message, then
// `fallback`.
export function describeActorError(
error: unknown,
fallback: string,
overrides: Record<string, string> = {},
): string {
if (error instanceof InvokeError && error.code in overrides) {
return overrides[error.code];
}
return error instanceof Error ? error.message : fallback;
}
// Reloads the profile page on `tab` from storage, so it shows what was
// written.
export async function reload(tab: ProfileTab): Promise<void> {
invalidateReposSummary();
await router.replace({ resource: "profile", tab });
}
// The actor writes and what each takes; the options are added by `change`.
export type ActorWrite =
| {
command: "create_actor" | "update_actor_profile";
args: { profile: ActorProfile; images: ProfileImages };
}
| {
command: "approve_enrollment";
args: { code: string; controller: boolean };
}
| { command: "remove_actor_key"; args: { did: string } }
| { command: "leave_actor"; args: { rid: string } }
| { command: "cancel_leave"; args: { rid: string } }
| { command: "retire_actor"; args: { rid: string } }
| { command: "approve_actor_revision"; args: { id: string } }
| { command: "withdraw_actor_revision"; args: { id: string } }
| { command: "reject_actor_revision"; args: { id: string } };
// The votes on an open identity change.
export type Vote = Extract<ActorWrite, { args: { id: string } }>["command"];
// Runs an actor write, then reloads `tab` whether or not it went through: a
// failure may come from state the page has not seen, and a write that went
// through is not undone by a reload that did not. The write announces when
// the node runs and the user has not turned announcing off.
export async function change(
{ command, args }: ActorWrite,
tab: ProfileTab,
): Promise<void> {
const opts = { announce: get(nodeRunning) && get(announce) };
const reloadQuietly = () =>
reload(tab).catch((e: unknown) =>
console.warn("Could not reload the profile", e),
);
try {
await invoke<ActorInfo>(command, { ...args, opts });
} catch (error) {
await reloadQuietly();
throw error;
}
await reloadQuietly();
}
// The keys that govern the actor's identity.
export function controllersOf(actor: ActorInfo): ActorKey[] {
return actor.keys.filter(key => key.controller);
}
// Whether `did` governs the actor's identity. A rejection signs a verdict,
// not the document, so a controller rejects a change this version of the
// app cannot write back whole.
export function isController(actor: ActorInfo, did: string): boolean {
return actor.keys.some(key => key.did === did && key.controller);
}
// Whether `did` may change the actor's keys: it governs the identity, and
// the payload is one this version of Desktop can write back whole.
export function mayChangeKeys(actor: ActorInfo, did: string): boolean {
return isController(actor, did) && !actor.payloadNewer;
}
// The open change that removes `did` from `actor` and has `voter`'s vote.
export function votedRemoval(
actor: ActorInfo,
did: string,
voter: string,
): ActorRevision | undefined {
return actor.pending.find(
revision =>
revision.removed.includes(did) && revision.accepted.includes(voter),
);
}
// What a change to `actor`'s keys does, in a line. A change that ended is
// told in the past tense, and since the keys have moved on since, every key
// it lists is told as added.
export function revisionTitle(
actor: ActorInfo,
revision: ActorRevision,
past = false,
): string {
const parts = [
...revision.added.map(key => {
const known = !past && actor.keys.some(k => k.did === key.did);
const role = {
full: "",
recovery: " as a recovery key",
bound: " (not a controller)",
}[keyKind(key)];
const verb = past ? "Added" : known ? "Change" : "Add";
return `${verb} ${keyName(actor, key.did)}${role}`;
}),
...revision.removed.map(
did => `${past ? "Removed" : "Remove"} ${keyName(actor, did)}`,
),
];
// A lower quorum on profile edits is a change of its own; it must not
// pass unseen inside a removal or a role change.
if (revision.threshold !== undefined) {
const approvals = revision.threshold === 1 ? "approval" : "approvals";
const quorum = past
? `needed ${revision.threshold} ${approvals}`
: `need ${revision.threshold} ${approvals} instead of ${actor.threshold}`;
return parts.length > 0
? `${parts.join(", ")}; profile edits ${quorum}`
: `Profile edits ${quorum}`;
}
if (parts.length > 0) return parts.join(", ");
return past ? "Changed the identity" : "Change the identity";
}
// How the votes on an open change of `actor` stand.
export function votesText(actor: ActorInfo, revision: ActorRevision): string {
const approved = Math.min(revision.accepted.length, actor.majority);
const rejected =
revision.rejected.length > 0
? `, ${revision.rejected.length} rejected`
: "";
return `${approved} of ${actor.majority} approved${rejected}`;
}
// What a key does for the actor: a full key acts as it and approves
// changes, a recovery key only approves, a bound key only acts.
export function keyKind(key: ActorKey): "full" | "recovery" | "bound" {
if (key.bound && key.controller) return "full";
return key.controller ? "recovery" : "bound";
}
// The label of each kind of key. Both roles are the default, so a key that
// has them needs none.
export const roleText = {
full: undefined,
recovery: "Recovery key",
bound: "Not a controller",
};
// What a profile is called where its name is shown.
export function profileName(actor: ActorInfo): string {
return actor.profile?.displayName || "A profile with no name";
}
// The alias of a key of `actor`, or of one an open change adds, and the
// shortened key otherwise.
export function keyName(actor: ActorInfo, did: string): string {
const key =
actor.keys.find(key => key.did === did) ??
actor.pending.flatMap(r => r.added).find(key => key.did === did);
return key?.alias ?? truncateId(publicKeyFromDid(did));
}
export function ago(seconds: number): string {
const elapsed = formatTimestamp(seconds * 1000);
return elapsed === "now" ? "just now" : `${elapsed} ago`;
}
+88
View File
@@ -0,0 +1,88 @@
import type { ActorProfile } from "@bindings/actor/ActorProfile";
import type { ProfileLink } from "@bindings/actor/ProfileLink";
// The form holds every field as a string, so an empty one reads as unset
// when the profile is sent. A link row has an id of its own, so a removed
// row above it does not take its values and focus.
export interface Form {
displayName: string;
fullName: string;
pronouns: string;
bio: string;
location: string;
timezone: string;
avatar: string;
banner: string;
links: (ProfileLink & { id: number })[];
}
export type TextField = Exclude<keyof Form, "links">;
export const TEXT_FIELDS: TextField[] = [
"displayName",
"fullName",
"pronouns",
"bio",
"location",
"timezone",
"avatar",
"banner",
];
// `loaded` with the fields typed into `typed` over it, for a form that
// turned out to edit a profile made elsewhere. A field the user left as
// `empty` keeps the loaded value; so do the links while no link was typed.
export function laidOver(typed: Form, loaded: Form, empty: Form): Form {
const merged = { ...loaded };
for (const field of TEXT_FIELDS) {
if (typed[field] !== empty[field]) merged[field] = typed[field];
}
if (typed.links.length > 0) merged.links = typed.links;
return merged;
}
// What can differ between two versions of the profile, field by field.
export type MergeField = TextField | "links";
export const MERGE_FIELDS: MergeField[] = [...TEXT_FIELDS, "links"];
// A field as the profile file holds it, for comparing two versions.
export function fieldValue(
profile: ActorProfile | undefined,
field: MergeField,
): string {
if (field === "links") {
return JSON.stringify(
(profile?.links ?? []).map(({ url, label }) => ({ url, label })),
);
}
return (profile?.[field] ?? "").trim();
}
// A field that differs between this device's version and another's: one
// only the other device changed since the two split is taken from there;
// one both changed is for the user to pick. A field only this device
// changed keeps its value, so it is left out.
export interface FieldDifference {
field: MergeField;
changedOn: "theirs" | "both";
}
export function compareVersions(
mine: ActorProfile | undefined,
theirs: ActorProfile | undefined,
base: ActorProfile | undefined,
): FieldDifference[] {
return MERGE_FIELDS.flatMap(field => {
const ours = fieldValue(mine, field);
const other = fieldValue(theirs, field);
if (ours === other) return [];
// Without the version both started from, every difference is a choice.
if (base === undefined) return [{ field, changedOn: "both" as const }];
const before = fieldValue(base, field);
if (other === before) return [];
return [
{ field, changedOn: ours === before ? ("theirs" as const) : "both" },
];
});
}
+109
View File
@@ -0,0 +1,109 @@
import type { Page } from "@playwright/test";
import type { RadiclePeer } from "@tests/support/peerManager.js";
import { api } from "@tests/support/api.js";
import { createProject } from "@tests/support/collaboration.js";
import { expect, test } from "@tests/support/fixtures.js";
// A project and an actor in the peer's storage, with names that share a
// start so one query finds both.
async function projectAndActor(page: Page, peer: RadiclePeer) {
const project = await createProject(peer, "tulips");
const actor = (await api(page, peer, "create_actor", {
profile: { version: 1, displayName: "tulips-keeper" },
opts: { announce: false },
})) as { rid: string };
return { project, actorRid: actor.rid };
}
async function turnLabOn(page: Page) {
await page.addInitScript(() =>
localStorage.setItem("labs.actorRepos", "true"),
);
}
function projectLink(page: Page) {
return page.getByRole("link", { name: /tulips(?!-keeper)/ });
}
function actorLink(page: Page) {
return page.getByRole("link", { name: /tulips-keeper/ });
}
test("an actor's repository is not listed while the lab is on", async ({
page,
peer,
}) => {
await projectAndActor(page, peer);
await turnLabOn(page);
await page.goto("/inbox");
await expect(projectLink(page)).toBeVisible();
await expect(actorLink(page)).toBeHidden();
});
test("an actor's repository is listed while the lab is off", async ({
page,
peer,
}) => {
await projectAndActor(page, peer);
await page.goto("/inbox");
await expect(projectLink(page)).toBeVisible();
await expect(actorLink(page)).toBeVisible();
});
test("an actor's repository is not offered as a mention", async ({
page,
peer,
}) => {
const { project } = await projectAndActor(page, peer);
await turnLabOn(page);
await page.goto(`/repos/${project.rid}/issues/${project.issueId}`);
await page.getByPlaceholder("Leave a comment").click();
await page.keyboard.insertText("@tulips");
const suggestions = page.locator(".suggestion");
await expect(suggestions.filter({ hasText: "tulips" })).toHaveCount(1);
await expect(suggestions.filter({ hasText: "tulips-keeper" })).toHaveCount(0);
});
test("adding an actor's repository says it is here already", async ({
page,
peer,
}) => {
const { actorRid } = await projectAndActor(page, peer);
await turnLabOn(page);
await page.goto("/inbox");
await page.getByRole("button", { name: "icon-plus", exact: true }).click();
const input = page.getByPlaceholder(/^RID, e\.g\./);
await input.fill(actorRid);
await input.press("Enter");
await expect(page.getByText("This repo is already seeded")).toBeVisible();
});
test("turning the lab on hides an actor's repository at once", async ({
page,
peer,
}) => {
await projectAndActor(page, peer);
await page.goto("/inbox");
await expect(actorLink(page)).toBeVisible();
await page.getByRole("button", { name: "Settings" }).click();
await page
.locator(".row", { hasText: "Rich profiles" })
.getByRole("button", { name: "On", exact: true })
.click();
await page.keyboard.press("Escape");
await expect(projectLink(page)).toBeVisible();
await expect(actorLink(page)).toBeHidden();
});
+294
View File
@@ -0,0 +1,294 @@
import type { Page } from "@playwright/test";
import {
aliceRemote,
expect,
gitOptions,
test,
useBackend,
} from "@tests/support/fixtures.js";
// A repository ID of the right shape that no peer holds.
const profileRid = "rad:z3gqcJUoA1n9HaHKufZs5FCSGazv5";
// The backend's answer about a profile that lives on another device.
function profileAnswer(overrides: object = {}) {
return {
rid: profileRid,
kind: "person",
keys: [
{
did: aliceRemote,
alias: "laptop",
bound: true,
controller: true,
addedAt: 0,
},
],
threshold: 1,
majority: 1,
payloadNewer: false,
profile: { version: 1, displayName: "Alice Liddell" },
profileNewer: false,
profileUnreadable: false,
pending: [],
forks: [],
...overrides,
};
}
async function openJoinForm(page: Page) {
await page.addInitScript(() =>
localStorage.setItem("labs.actorRepos", "true"),
);
await page.goto("/profile");
await page.getByRole("button", { name: "Join existing profile" }).click();
}
test("the profile to join is shown before a code is made", async ({
page,
peer: _peer,
}) => {
let lookups = 0;
await page.route(/\/joinable_actor$/, route => {
lookups += 1;
return route.fulfill({ json: profileAnswer() });
});
let signed = 0;
await page.route(/\/join_actor$/, route => {
signed += 1;
return route.fulfill({ json: "rad-enroll:made-for-the-test" });
});
await openJoinForm(page);
await page.getByPlaceholder(/^Profile ID/).fill(profileRid);
await expect(page.getByText("Is this your profile?")).toBeVisible();
await expect(page.getByText("Alice Liddell")).toBeVisible();
await expect(page.getByText("laptop", { exact: true })).toBeVisible();
await expect(
page.getByText(aliceRemote.slice("did:key:".length)),
).toBeVisible();
expect(signed).toBe(0);
await page.getByRole("button", { name: "Create code" }).click();
await expect(page.getByText("rad-enroll:made-for-the-test")).toBeVisible();
expect(signed).toBe(1);
// Going back looks the profile up afresh: its keys may have changed.
const before = lookups;
// The header's history arrow is named "Back" too, and holds no text.
await page.getByRole("button").filter({ hasText: "Back" }).click();
await expect(page.getByText("Is this your profile?")).toBeVisible();
await expect(page.getByPlaceholder(/^Profile ID/)).toHaveValue(profileRid);
expect(lookups).toBe(before + 1);
});
test("an ID entered without its prefix is the same profile", async ({
page,
peer: _peer,
}) => {
const asked: string[] = [];
await page.route(/\/joinable_actor$/, route => {
asked.push((route.request().postDataJSON() as { rid: string }).rid);
return route.fulfill({ json: profileAnswer() });
});
await openJoinForm(page);
await page
.getByPlaceholder(/^Profile ID/)
.fill(profileRid.replace(/^rad:/, ""));
await expect(page.getByText("Is this your profile?")).toBeVisible();
expect(asked).toEqual([profileRid]);
});
test("what this version cannot read of the profile is said", async ({
page,
peer: _peer,
}) => {
await page.route(/\/joinable_actor$/, route =>
route.fulfill({
json: profileAnswer({
payloadNewer: true,
profile: undefined,
profileUnreadable: true,
}),
}),
);
await openJoinForm(page);
await page.getByPlaceholder(/^Profile ID/).fill(profileRid);
await expect(
page.getByText("It may hold keys this version does not show"),
).toBeVisible();
await expect(
page.getByText("Its profile file is not one this version of Desktop"),
).toBeVisible();
await expect(page.getByText("A profile with no name")).toBeHidden();
});
test("a profile that is not on this device gets no code", async ({
page,
peer: _peer,
}) => {
await openJoinForm(page);
await page.getByPlaceholder(/^Profile ID/).fill(profileRid);
await expect(
page.getByText(/This profile is not on this device yet/),
).toBeVisible();
await expect(
page.getByRole("button", { name: "Fetch the profile" }),
).toBeVisible();
await expect(page.getByRole("button", { name: "Create code" })).toBeHidden();
});
test("a profile fetched before anyone looked is still found", async ({
page,
peer: _peer,
}) => {
// The fetch ends at once: from the moment it is asked for, the profile is
// here, and it never shows up as being fetched.
let arrived = false;
await page.route(/\/joinable_actor$/, route =>
arrived ? route.fulfill({ json: profileAnswer() }) : route.continue(),
);
await page.route(/\/seed$/, route => {
arrived = true;
return route.fulfill({ json: null });
});
await openJoinForm(page);
await page.getByPlaceholder(/^Profile ID/).fill(profileRid);
await page.getByRole("button", { name: "Fetch the profile" }).click();
await expect(page.getByText("Is this your profile?")).toBeVisible();
});
test("a copy the node cannot update is fetched again", async ({
page,
peer: _peer,
}) => {
// The copy arrives without a head while the profile is split: it stays
// listed as being fetched, and no later fetch reaches it.
let copy: "none" | "stuck" | "whole" = "none";
const calls: string[] = [];
await page.route(/\/seeded_not_replicated$/, route =>
// Removing the copy leaves the policy, so it is awaited again at once.
route.fulfill({
json: calls.length > 0 && copy !== "whole" ? [profileRid] : [],
}),
);
// One lookup during the wait fails for a reason of its own.
let failures = 1;
await page.route(/\/joinable_actor$/, route => {
if (copy === "none") return route.continue();
if (copy === "whole") return route.fulfill({ json: profileAnswer() });
if (failures-- > 0) {
return route.fulfill({
status: 500,
json: { code: "UnknownError", message: "The disk was busy." },
});
}
return route.fulfill({
status: 500,
json: {
code: "ActorError.CopyStuck",
message: "This device cannot update that copy.",
},
});
});
await page.route(/\/seed$/, route => {
calls.push("seed");
// By the second fetch a controller has saved, and the split is closed.
copy = calls.includes("clean") ? "whole" : "stuck";
return route.fulfill({ json: null });
});
await page.route(/\/clean$/, route => {
calls.push("clean");
copy = "none";
return route.fulfill({ json: null });
});
await openJoinForm(page);
await page.getByPlaceholder(/^Profile ID/).fill(profileRid);
await page.getByRole("button", { name: "Fetch the profile" }).click();
await expect(
page.getByText("This device cannot update that copy."),
).toBeVisible({
timeout: 20_000,
});
await expect(page.getByText("The disk was busy.")).toBeHidden();
await expect(page.getByRole("button", { name: "Create code" })).toBeHidden();
// Fetching again seeds without a dialog too.
await page.getByRole("button", { name: "Fetch again" }).click();
await expect(page.getByText("Is this your profile?")).toBeVisible();
expect(calls).toEqual(["seed", "clean", "seed"]);
});
test("another repository being fetched does not set off lookups", async ({
page,
peer: _peer,
}) => {
// The sidebar looks every few seconds while anything is on its way.
await page.route(/\/seeded_not_replicated$/, route =>
route.fulfill({ json: ["rad:z3fpY7nttPPa6MBnAv2DccHzQJnqe"] }),
);
let lookups = 0;
await page.route(/\/joinable_actor$/, route => {
lookups += 1;
return route.continue();
});
await openJoinForm(page);
await page.getByPlaceholder(/^Profile ID/).fill(profileRid);
await expect(
page.getByText(/This profile is not on this device yet/),
).toBeVisible();
await page.waitForTimeout(11_000);
expect(lookups).toBe(1);
});
test("text that is no profile ID says so", async ({ page, peer: _peer }) => {
await openJoinForm(page);
await page.getByPlaceholder(/^Profile ID/).fill("not an id");
await expect(page.getByText(/That is not a Profile ID/)).toBeVisible();
await expect(
page.getByRole("button", { name: "Create code" }),
).toBeDisabled();
});
test("a profile that cannot be fetched while the node is offline says so", async ({
page,
peerManager,
}) => {
const peer = await peerManager.createPeer({
name: "offline",
gitOptions: gitOptions["bob"],
});
await peer.startHttpd();
await useBackend(page, peer);
await openJoinForm(page);
await page.getByPlaceholder(/^Profile ID/).fill(profileRid);
await expect(page.getByText(/Your node is offline/)).toBeVisible();
await expect(
page.getByRole("button", { name: "Fetch the profile" }),
).toBeDisabled();
await expect(page.getByRole("button", { name: "Create code" })).toBeHidden();
});
+194
View File
@@ -0,0 +1,194 @@
import type { Page } from "@playwright/test";
import { aliceRemote, expect, test } from "@tests/support/fixtures.js";
// Two repository IDs of the right shape that no peer holds.
const joinedRid = "rad:z3gqcJUoA1n9HaHKufZs5FCSGazv5";
const createdRid = "rad:z4V1sjrXqjvFdnCUbxPFqd5p4DtH5";
const key = (did: string, controller = true) => ({
did,
bound: true,
controller,
addedAt: 0,
});
const profile = (
rid: string,
displayName: string,
keys: ReturnType<typeof key>[],
) => ({
rid,
kind: "person",
keys,
threshold: 1,
majority: Math.floor(keys.filter(k => k.controller).length / 2) + 1,
payloadNewer: false,
profile: { version: 1, displayName },
profileNewer: false,
profileUnreadable: false,
pending: [] as object[],
forks: [],
});
// The backend's answers about a key that two profiles bind, which takes a
// second device to bring about: one the device joined and shares, and one it
// created and alone controls. Once `created` is retired, the device is in
// `joined` only.
async function twoProfiles(page: Page, local: string) {
const joined = profile(joinedRid, "Alice Liddell", [
key(aliceRemote),
key(local),
]);
const created = profile(createdRid, "Bob Belcher", [
key(local),
key(aliceRemote, false),
]);
const state = { joined, created, retired: false };
await page.addInitScript(() =>
localStorage.setItem("labs.actorRepos", "true"),
);
await page.route(/\/actor$/, route =>
state.retired
? route.fulfill({ json: joined })
: route.fulfill({
status: 500,
json: {
code: "ActorError.Ambiguous",
message: "This key belongs to more than one profile.",
},
}),
);
await page.route(/\/actors_of_key$/, route =>
route.fulfill({ json: state.retired ? [joined] : [joined, created] }),
);
return state;
}
// By its ID, since one row can name the other profile.
const rowOf = (page: Page, rid: string) =>
page.locator(".profile", { hasText: rid });
test("a device in two profiles leaves one and waits for the approval", async ({
page,
peer,
}) => {
const local = `did:key:${peer.nodeId}`;
const { joined } = await twoProfiles(page, local);
let left: unknown;
await page.route(/\/leave_actor$/, route => {
left = route.request().postDataJSON();
joined.pending = [
{
id: "0000000000000000000000000000000000000001",
author: local,
createdAt: 0,
added: [],
removed: [local],
accepted: [local],
rejected: [] as string[],
unreadable: false,
},
];
return route.fulfill({ json: joined });
});
await page.route(/\/cancel_leave$/, route => {
joined.pending = [];
return route.fulfill({ json: joined });
});
await page.goto("/profile?tab=keys");
await expect(page.getByText("This device is in two profiles")).toBeVisible();
const row = (rid: string) => rowOf(page, rid);
const leave = row(joinedRid).getByRole("button", {
name: "Leave",
exact: true,
});
// Nothing but a retirement ends a profile this device alone controls.
await expect(row(createdRid)).toContainText("can only be retired");
await expect(
row(createdRid).getByRole("button", { name: "Leave", exact: true }),
).toHaveCount(0);
await leave.click();
await expect(row(joinedRid)).toContainText(
"This device stays in Bob Belcher",
);
await row(joinedRid).getByRole("button", { name: "Yes" }).click();
await expect(row(joinedRid)).toContainText("You asked to leave.");
await expect(row(joinedRid)).toContainText("1 of 2 approved.");
await expect(leave).toHaveCount(0);
await expect(row(createdRid)).toContainText(
"You are already leaving Alice Liddell",
);
expect(left).toMatchObject({ rid: joinedRid });
// The leave was asked for on the Keys tab, and the page stays on it.
await expect(page.locator(".tab.active")).toContainText("Keys");
// The wait is read from the profile, so another device's vote shows when
// the page loads again.
(joined.pending[0] as { rejected: string[] }).rejected = [aliceRemote];
await page.getByRole("button", { name: "Reload" }).click();
await expect(row(joinedRid)).toContainText("1 of 2 approved, 1 rejected.");
// The other device may never answer, so the leave can be taken back.
await row(joinedRid).getByRole("button", { name: "Cancel leave" }).click();
await expect(leave).toBeVisible();
await expect(row(joinedRid)).not.toContainText("You asked to leave.");
});
test("a device retires the profile it alone controls and is left in the other", async ({
page,
peer,
}) => {
const state = await twoProfiles(page, `did:key:${peer.nodeId}`);
let retired: unknown;
let refuse = true;
await page.route(/\/retire_actor$/, route => {
if (refuse) {
return route.fulfill({
status: 500,
json: { code: "UnknownError", message: "Your keys changed just now." },
});
}
retired = route.request().postDataJSON();
state.retired = true;
return route.fulfill({ json: state.created });
});
await page.goto("/profile");
await rowOf(page, createdRid).getByRole("button", { name: "Retire" }).click();
// Nothing is signed until the dialog is confirmed, and it says what ends.
const dialog = page.locator(".modal");
await expect(dialog).toContainText("Bob Belcher");
await expect(dialog).toContainText(createdRid);
await expect(dialog).toContainText("This device stays in Alice Liddell.");
await expect(dialog).toContainText(
"This profile has 1 other device. It loses the profile too",
);
await expect(dialog).toContainText("This cannot be undone.");
expect(retired).toBeUndefined();
// A refused retirement is said in the dialog, which stays for another try.
await dialog.getByRole("button", { name: "Retire" }).click();
await expect(dialog).toContainText("Your keys changed just now.");
await expect(page.getByText("This device is in two profiles")).toBeVisible();
refuse = false;
await dialog.getByRole("button", { name: "Retire" }).click();
await expect(page.getByText("This device is in two profiles")).toBeHidden();
await expect(page.getByText("Profile ID")).toBeVisible();
await expect(page.getByText(joinedRid)).toBeVisible();
expect(retired).toMatchObject({ rid: createdRid });
});
+253
View File
@@ -0,0 +1,253 @@
import { api } from "@tests/support/api.js";
import { expect, test, waitForCommand } from "@tests/support/fixtures.js";
test("creating a profile shows what to do next, saving one is confirmed briefly", async ({
page,
peer: _peer,
}) => {
await page.addInitScript(() =>
localStorage.setItem("labs.actorRepos", "true"),
);
await page.goto("/profile");
await page.getByRole("button", { name: "Create a new profile" }).click();
const field = (label: string) =>
page.locator(".field", { hasText: label }).getByRole("textbox");
await field("Display name").fill("Alice Liddell");
await waitForCommand(page, "create_actor", () =>
page.getByRole("button", { name: "Create profile" }).click(),
);
// A new profile is announced with how to add the other devices.
const created = page.locator(".modal", { hasText: "Profile created" });
await expect(created).toContainText("Alice Liddell");
await expect(created).toContainText("Add your other devices");
await created.getByRole("button", { name: "Go to Keys" }).click();
await expect(page).toHaveURL(/\/profile\?tab=keys$/);
await page.getByRole("link", { name: "Profile" }).first().click();
await field("Full name").fill("Alice Pleasance Liddell");
await waitForCommand(page, "update_actor_profile", () =>
page.getByRole("button", { name: "Save profile" }).click(),
);
await expect(page.getByText("Saved.")).toBeVisible();
// A save is routine, so its confirmation goes by itself.
await expect(page.getByText("Saved.")).toBeHidden();
});
// A picture of one pixel.
const png = Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==",
"base64",
);
test("a picture chosen for the profile is saved with it and shown from then on", async ({
page,
peer: _peer,
}) => {
await page.addInitScript(() =>
localStorage.setItem("labs.actorRepos", "true"),
);
await page.goto("/profile");
await page.getByRole("button", { name: "Create a new profile" }).click();
const field = (label: string) =>
page.locator(".field", { hasText: label }).getByRole("textbox");
const avatar = page.getByLabel("avatar picture");
// The picture itself, not the pattern shown while there is none.
const shown = page.locator(".preview.avatar img[alt='']");
const remove = page.getByRole("button", { name: "Remove", exact: true });
const source = page.locator(".source");
const unsaved = page.getByText("New picture, not saved yet");
await field("Display name").fill("Alice Liddell");
// A file that is no picture is not taken, whatever it is called.
await avatar.setInputFiles({
name: "me.png",
mimeType: "image/png",
buffer: Buffer.from("not a picture"),
});
await expect(
page.getByText("This file is not a picture that can be shown."),
).toBeVisible();
await expect(remove).toBeHidden();
await expect(shown).toBeHidden();
// The name it was given says nothing of what it is saved as.
await avatar.setInputFiles({
name: "me.jpg",
mimeType: "image/jpeg",
buffer: png,
});
await expect(shown).toBeVisible();
await expect(remove).toBeVisible();
await expect(unsaved).toBeVisible();
await waitForCommand(page, "create_actor", () =>
page.getByRole("button", { name: "Create profile" }).click(),
);
await page.getByRole("button", { name: "Done" }).click();
await expect(source).toHaveText("avatar.png");
await expect(shown).toBeVisible();
await expect(unsaved).toBeHidden();
// It is read back from the profile, not kept by the page.
await page.reload();
await expect(source).toHaveText("avatar.png");
await expect(shown).toBeVisible();
// A picture taken back before the save changes nothing.
await avatar.setInputFiles({
name: "me.png",
mimeType: "image/png",
buffer: png,
});
await remove.click();
await expect(
page.getByRole("button", { name: "Save profile" }),
).toBeDisabled();
});
test("the published history lists every version once, however its pages overlap", async ({
page,
peer,
}) => {
const version = (index: number, overrides: object = {}) => ({
commit: index.toString(16).padStart(40, "0"),
parents: [(index + 1).toString(16).padStart(40, "0")],
savedAt: 0,
author: `did:key:${peer.nodeId}`,
fields: ["bio"],
live: true,
...overrides,
});
const versions = (from: number, to: number) =>
Array.from({ length: to - from }, (_, at) => version(from + at));
// The profile moves by a whole page while the list is read, so the second
// page holds nothing new.
const pages: Record<number, object> = {
0: {
cursor: 0,
more: true,
content: [version(0, { live: false }), ...versions(1, 20)],
},
20: { cursor: 20, more: true, content: versions(0, 20) },
40: {
cursor: 40,
more: false,
content: [...versions(20, 22), version(22, { parents: [] })],
},
};
const asked: number[] = [];
await page.route(/\/actor_profile_history$/, route => {
const { skip } = route.request().postDataJSON() as { skip: number };
asked.push(skip);
return route.fulfill({ json: pages[skip] });
});
await page.addInitScript(() =>
localStorage.setItem("labs.actorRepos", "true"),
);
await page.goto("/profile");
await page.getByRole("button", { name: "Create a new profile" }).click();
await page
.locator(".field", { hasText: "Display name" })
.getByRole("textbox")
.fill("Alice Liddell");
await waitForCommand(page, "create_actor", () =>
page.getByRole("button", { name: "Create profile" }).click(),
);
await page.getByRole("button", { name: "Done" }).click();
await page.getByRole("button", { name: "View history" }).click();
const rows = page.locator(".modal .entry");
const more = page.getByRole("button", { name: "Show more" });
await expect(rows).toHaveCount(20);
// Only the version that waits for a controller is marked.
await expect(page.getByText("Not the profile yet")).toHaveCount(1);
await expect(rows.first()).toContainText("Not the profile yet");
await more.click();
await expect.poll(() => asked).toEqual([0, 20]);
await expect(rows).toHaveCount(20);
await more.click();
await expect(rows).toHaveCount(23);
await expect(rows.last()).toContainText("Created the profile");
await expect(more).toBeHidden();
expect(asked).toEqual([0, 20, 40]);
});
test("a profile this device cannot publish alone is only shown", async ({
page,
peer,
}) => {
await api(page, peer, "create_actor", {
profile: { version: 1, displayName: "alice", bio: "published" },
opts: { announce: false },
});
await page.addInitScript(() =>
localStorage.setItem("labs.actorRepos", "true"),
);
// A profile that takes two controllers needs a second one, so the
// backend's answer is told to need them.
await page.route(/\/actor$/, async route => {
const response = await route.fetch();
await route.fulfill({
response,
json: { ...(await response.json()), threshold: 2 },
});
});
await page.goto("/profile");
await expect(
page.getByText(/need 2 controllers to agree, so it is shown here/),
).toBeVisible();
await expect(page.locator("textarea.bio")).toHaveValue("published");
await expect(page.locator("textarea.bio")).toBeDisabled();
await expect(
page.getByRole("button", { name: "Save profile" }),
).toBeDisabled();
});
test("a device that does not control the profile is offered no edit", async ({
page,
peer,
}) => {
await api(page, peer, "create_actor", {
profile: { version: 1, displayName: "alice" },
opts: { announce: false },
});
await page.addInitScript(() =>
localStorage.setItem("labs.actorRepos", "true"),
);
// A key without control joins from a second device, so the backend's
// answer is told this one has none, and that the profile names a picture.
await page.route(/\/actor$/, async route => {
const response = await route.fetch();
const actor = await response.json();
await route.fulfill({
response,
json: {
...actor,
keys: actor.keys.map((key: object) => ({ ...key, controller: false })),
profile: { ...actor.profile, avatar: "https://example.com/me.png" },
},
});
});
await page.goto("/profile");
await expect(
page.getByText(/Only a device that controls this profile can edit it/),
).toBeVisible();
await expect(page.getByText("https://example.com/me.png")).toBeVisible();
await expect(page.getByRole("button", { name: "Remove" })).toBeHidden();
await expect(page.getByText(/Everything you save here/)).toBeHidden();
await expect(
page.getByRole("button", { name: "Save profile" }),
).toBeDisabled();
});
+121
View File
@@ -0,0 +1,121 @@
import type { Page } from "@playwright/test";
import type { RadiclePeer } from "@tests/support/peerManager.js";
import { api } from "@tests/support/api.js";
import {
aliceRemote,
expect,
test,
waitForCommand,
} from "@tests/support/fixtures.js";
// A profile on the peer that the page is told another controller has edited
// too. A real second version needs a second device, so the backend's answer
// gets one added on its way to the page.
async function splitProfile(
page: Page,
peer: RadiclePeer,
fork: { profileNewer: boolean; otherFiles: boolean; base?: object },
) {
await api(page, peer, "create_actor", {
profile: { version: 1, displayName: "alice" },
opts: { announce: false },
});
await page.addInitScript(() =>
localStorage.setItem("labs.actorRepos", "true"),
);
await page.route(/\/actor$/, async route => {
const response = await route.fetch();
const actor = await response.json();
await route.fulfill({
response,
json: {
...actor,
forks: [
{
did: aliceRemote,
head: actor.head,
profile: { version: 1, displayName: "alice", bio: "from phone" },
changes: [
"--- a/.radicle/profile.json",
"+++ b/.radicle/profile.json",
"@@ -1,4 +1,5 @@",
" {",
' "version": 1,',
'- "displayName": "alice"',
'+ "displayName": "alice",',
'+ "bio": "from phone"',
" }",
"",
].join("\n"),
...fork,
},
],
},
});
});
await page.goto("/profile");
await expect(page.getByText(/Also edited on/)).toBeVisible();
}
test("a split is closed by saving the profile as it is", async ({
page,
peer,
}) => {
await splitProfile(page, peer, {
profileNewer: false,
otherFiles: true,
});
await expect(
page.getByText(/also changed other files in the repository/),
).toBeVisible();
await page.getByRole("button", { name: /View raw changes/ }).click();
await expect(page.getByText('"bio": "from phone"')).toBeVisible();
await page.keyboard.press("Escape");
await page.unroute(/\/actor$/);
await waitForCommand(page, "update_actor_profile", () =>
page.getByRole("button", { name: "Save profile" }).click(),
);
await expect(page.getByText(/Also edited on/)).toBeHidden();
});
test("a newer version elsewhere cannot be saved over", async ({
page,
peer,
}) => {
await splitProfile(page, peer, { profileNewer: true, otherFiles: false });
await expect(
page.getByText(/also changed other files in the repository/),
).toBeHidden();
await expect(
page.getByText(/was written by a newer Desktop, so this one cannot/),
).toBeVisible();
await expect(
page.getByText("Written by a newer Desktop", { exact: true }),
).toBeHidden();
await expect(
page.getByRole("button", { name: "Save profile" }),
).toBeDisabled();
});
test("discarding keeps what only the other device changed", async ({
page,
peer,
}) => {
await splitProfile(page, peer, {
profileNewer: false,
otherFiles: false,
base: { version: 1, displayName: "alice" },
});
const bio = page.locator("textarea.bio");
await expect(bio).toHaveValue("from phone");
await page.getByRole("button", { name: "Discard" }).click();
await expect(bio).toHaveValue("from phone");
});
+65
View File
@@ -0,0 +1,65 @@
import { compareVersions, type Form, laidOver } from "@app/views/profile/form";
import { expect, test } from "vitest";
const empty: Form = {
displayName: "",
fullName: "",
pronouns: "",
bio: "",
location: "",
timezone: "",
avatar: "",
banner: "",
links: [],
};
const loaded: Form = {
...empty,
displayName: "Alice",
bio: "Curiouser.",
links: [{ id: 0, url: "https://alice.example", label: "Website" }],
};
test("a create form laid over an existing profile keeps what was not typed", () => {
// Its own empty list, as a form built on its own has.
const typed: Form = { ...empty, pronouns: "she/her", links: [] };
const merged = laidOver(typed, loaded, empty);
expect(merged.pronouns).toBe("she/her");
expect(merged.displayName).toBe("Alice");
expect(merged.bio).toBe("Curiouser.");
expect(merged.links).toEqual(loaded.links);
});
test("typed links replace the loaded ones", () => {
const typed: Form = {
...empty,
links: [{ id: 1, url: "mailto:alice@example.com" }],
};
expect(laidOver(typed, loaded, empty).links).toEqual(typed.links);
});
test("a split takes one-sided changes and leaves both-sided ones to pick", () => {
const base = { version: 1, displayName: "Alice", bio: "Curiouser." };
const mine = { ...base, bio: "Curiouser and curiouser." };
const theirs = {
...base,
bio: "Down the rabbit hole.",
location: "Wonderland",
};
expect(compareVersions(mine, theirs, base)).toEqual([
{ field: "bio", changedOn: "both" },
{ field: "location", changedOn: "theirs" },
]);
});
test("a split with no common version leaves every difference to pick", () => {
const mine = { version: 1, displayName: "Alice" };
const theirs = { version: 1, displayName: "Alice", location: "Wonderland" };
expect(compareVersions(mine, theirs, undefined)).toEqual([
{ field: "location", changedOn: "both" },
]);
});
+23
View File
@@ -0,0 +1,23 @@
import type { RepoSummary } from "@bindings/repo/RepoSummary";
import { expect, test } from "vitest";
import { projectsOf } from "@app/lib/projects";
function repo(name: string, actor: boolean): RepoSummary {
return { rid: `rad:${name}`, name, private: false, seeding: true, actor };
}
const repos = [repo("alice", true), repo("heartwood", false)];
test("an actor repository is no project while the lab is on", () => {
expect(projectsOf(repos, true).map(r => r.name)).toEqual(["heartwood"]);
});
test("every repository is listed while the lab is off", () => {
expect(projectsOf(repos, false)).toEqual(repos);
});
test("no repositories give no projects", () => {
expect(projectsOf([], true)).toEqual([]);
});