feat: profile sharing via X25519 envelope (Phase B, #3)
An owner can now share a profile with another account; the recipient
reads the profile's metadata AND its data (medications, appointments,
health stats) under their own login. The server stays a blind store:
sharing uses an X25519 envelope — the owner wraps the profile DEK to
the recipient's identity public key via ECDH (fresh ephemeral key per
share), the recipient unwraps it with their identity private key.
Backend:
- models/profile_share.rs: ProfileShare + ProfileShareRepository
(find_for_recipient, find_for_profile, find_active [checks active +
expiry], delete, upsert). Indexed on (profileId, recipientUserId) and
recipientUserId.
- handlers/profile_share.rs: POST/GET /profiles/:id/shares,
DELETE /profiles/:id/shares/:recipient, GET /profiles/shared-with-me,
GET /users/public-key (public), and authorize_profile_read — the
share-gate that admits owner OR active-share recipient.
- The share-gate is wired into list/get for medications, appointments,
and health stats: when profile_id is specified, resolve the owner via
the gate and query as them. Data repos stay ownership-scoped.
- Removed the legacy Share system (ADR Open Q5): models/{share,
permission}.rs, handlers/{shares,permissions}.rs, middleware/
permission.rs (dead), the shares collection field + methods in
mongodb_impl.rs, the shares index, and the 5 /api/shares +
/api/permissions routes.
- share_tests.rs: full owner→recipient→revoke flow, ownership
isolation, share-to-self/nonexistent/keyless rejections, expired
share treated as absent.
Frontend:
- crypto/keys.ts: wrapProfileDekToRecipient /
unwrapProfileDekFromShare (ECDH envelope, ephemeral key per share).
- useProfileStore: loadSharedWithMe (unwrap each share's DEK with the
identity private key), shareProfile, revokeShare, loadProfileShares.
Shared profiles merge into the list with is_shared=true.
- ProfileSwitcher: shows shared profiles with a 'shared' chip.
- ProfileSharing (new) + ProfileEditor: owner UI to add a recipient by
email and revoke; shared profiles render read-only with owner info.
- ECDH round-trip test (owner wraps, recipient unwraps, stranger can't).
Verification: backend cargo build/clippy (-D warnings)/fmt clean, tests
compile (integration tests run in CI — Mongo is fixed there). Frontend
tsc clean, 31/31 tests pass.
⚠️ Backend integration tests not run locally (no Mongo/Docker in this
sandbox); CI will run them — I'll fix any failures immediately.
Phases C (hard revoke / re-key) and D (graduation) remain. Refs #3.
This commit is contained in:
parent
015a99a7fe
commit
04520539aa
25 changed files with 1875 additions and 953 deletions
|
|
@ -12,6 +12,8 @@ import {
|
|||
generateProfileDek,
|
||||
wrapProfileDek,
|
||||
unwrapProfileDek,
|
||||
wrapProfileDekToRecipient,
|
||||
unwrapProfileDekFromShare,
|
||||
encrypt as encryptRaw,
|
||||
decrypt as decryptRaw,
|
||||
setEncKey,
|
||||
|
|
@ -19,6 +21,7 @@ import {
|
|||
clearIdentityPrivate,
|
||||
clearProfileDeks,
|
||||
setIdentityPrivate,
|
||||
getIdentityPrivate,
|
||||
getEncKey,
|
||||
getActiveProfileDek,
|
||||
getActiveProfileId,
|
||||
|
|
@ -37,6 +40,7 @@ import {
|
|||
DrugInteraction,
|
||||
AdherenceStats,
|
||||
Profile,
|
||||
ProfileShareListing,
|
||||
Appointment,
|
||||
CreateAppointmentRequest,
|
||||
UpdateAppointmentRequest,
|
||||
|
|
@ -137,6 +141,18 @@ interface ProfileState {
|
|||
relationship?: string;
|
||||
}) => Promise<void>;
|
||||
deleteProfile: (profileId: string) => Promise<void>;
|
||||
/** Fetch profiles shared TO the current user and merge them into `profiles`,
|
||||
* unwrapping each share's profile DEK via the recipient's identity private
|
||||
* key. Called after loadProfiles on login/unlock. */
|
||||
loadSharedWithMe: () => Promise<void>;
|
||||
/** Owner: share a profile to a recipient by email. Fetches the recipient's
|
||||
* identity public key, wraps the profile DEK to it via ECDH, and POSTs. */
|
||||
shareProfile: (profileId: string, recipientEmail: string) => Promise<void>;
|
||||
/** Owner: revoke a share (delete the share record server-side). */
|
||||
revokeShare: (profileId: string, recipientUserId: string) => Promise<void>;
|
||||
/** Shares the current user has created for a profile (for the owner UI). */
|
||||
profileShares: Record<string, ProfileShareListing[]>;
|
||||
loadProfileShares: (profileId: string) => Promise<void>;
|
||||
clearError: () => void;
|
||||
}
|
||||
|
||||
|
|
@ -805,6 +821,7 @@ export const useProfileStore = create<ProfileState>()(
|
|||
activeProfileId: null,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
profileShares: {},
|
||||
|
||||
loadProfiles: async () => {
|
||||
const accountDek = getEncKey();
|
||||
|
|
@ -980,6 +997,130 @@ export const useProfileStore = create<ProfileState>()(
|
|||
}
|
||||
},
|
||||
|
||||
loadSharedWithMe: async () => {
|
||||
// Recipient path: profiles shared TO the current user. Each share's
|
||||
// profile DEK is wrapped under an ECDH-derived key; unwrap it with the
|
||||
// identity private key, then decrypt the display name under the profile
|
||||
// DEK. Merge into the profiles list with is_shared = true.
|
||||
const myIdentityPrivate = getIdentityPrivate();
|
||||
if (!myIdentityPrivate) {
|
||||
// No identity key unlocked — can't unwrap shared profile DEKs. Silently
|
||||
// skip; the owned-profile list still loads.
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const shared = await apiService.listSharedWithMe();
|
||||
const sharedProfiles: Profile[] = [];
|
||||
for (const s of shared) {
|
||||
// Skip if we already have the DEK in memory (avoid re-unwrapping).
|
||||
let profileDek = getProfileDek(s.profile_id);
|
||||
if (!profileDek) {
|
||||
try {
|
||||
profileDek = await unwrapProfileDekFromShare(
|
||||
{ data: s.wrapped_profile_dek, iv: s.wrapped_profile_dek_iv },
|
||||
s.ephemeral_public_key,
|
||||
myIdentityPrivate,
|
||||
);
|
||||
setProfileDek(s.profile_id, profileDek);
|
||||
} catch {
|
||||
continue; // couldn't unwrap — skip this share
|
||||
}
|
||||
}
|
||||
let name = '';
|
||||
if (s.name_data && s.name_iv && profileDek) {
|
||||
try {
|
||||
name = await decryptRaw({ data: s.name_data, iv: s.name_iv }, profileDek);
|
||||
} catch { name = ''; }
|
||||
}
|
||||
sharedProfiles.push({
|
||||
profile_id: s.profile_id,
|
||||
owner_account_id: s.owner_account_id,
|
||||
name,
|
||||
kind: s.kind,
|
||||
relationship: s.relationship,
|
||||
role: 'patient',
|
||||
permissions: s.permissions,
|
||||
created_at: s.created_at,
|
||||
updated_at: s.created_at,
|
||||
is_shared: true,
|
||||
});
|
||||
}
|
||||
// Merge: replace any prior shared entries, keep owned ones intact.
|
||||
const owned = get().profiles.filter((p) => !p.is_shared);
|
||||
const merged = [...owned, ...sharedProfiles];
|
||||
set({ profiles: merged });
|
||||
} catch (error: any) {
|
||||
// Non-fatal: owned profiles still work.
|
||||
set({ error: error.message || 'Failed to load shared profiles' });
|
||||
}
|
||||
},
|
||||
|
||||
shareProfile: async (profileId, recipientEmail) => {
|
||||
// Owner path: fetch recipient pubkey, wrap the profile DEK to it, POST.
|
||||
const myIdentityPrivate = getIdentityPrivate();
|
||||
const profileDek = getProfileDek(profileId);
|
||||
if (!myIdentityPrivate) {
|
||||
set({ error: 'No identity key unlocked — cannot share' });
|
||||
throw new Error('No identity key');
|
||||
}
|
||||
if (!profileDek) {
|
||||
set({ error: 'No profile key — switch to the profile first' });
|
||||
throw new Error('No profile key');
|
||||
}
|
||||
set({ isLoading: true, error: null });
|
||||
try {
|
||||
const { identity_public_key: recipientPub } =
|
||||
await apiService.getUserPublicKey(recipientEmail);
|
||||
const envelope = await wrapProfileDekToRecipient(
|
||||
profileDek,
|
||||
recipientPub,
|
||||
myIdentityPrivate,
|
||||
);
|
||||
await apiService.createProfileShare(profileId, {
|
||||
recipient_email: recipientEmail,
|
||||
ephemeral_public_key: envelope.ephemeralPublicKey,
|
||||
wrapped_profile_dek: envelope.wrappedProfileDek.data,
|
||||
wrapped_profile_dek_iv: envelope.wrappedProfileDek.iv,
|
||||
permissions: ['read'],
|
||||
});
|
||||
// Refresh the share listing for this profile.
|
||||
await get().loadProfileShares(profileId);
|
||||
set({ isLoading: false });
|
||||
} catch (error: any) {
|
||||
set({
|
||||
error: error.message || 'Failed to share profile',
|
||||
isLoading: false,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
revokeShare: async (profileId, recipientUserId) => {
|
||||
set({ isLoading: true, error: null });
|
||||
try {
|
||||
await apiService.deleteProfileShare(profileId, recipientUserId);
|
||||
await get().loadProfileShares(profileId);
|
||||
set({ isLoading: false });
|
||||
} catch (error: any) {
|
||||
set({
|
||||
error: error.message || 'Failed to revoke share',
|
||||
isLoading: false,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
loadProfileShares: async (profileId) => {
|
||||
try {
|
||||
const shares = await apiService.listProfileShares(profileId);
|
||||
set((state) => ({
|
||||
profileShares: { ...state.profileShares, [profileId]: shares },
|
||||
}));
|
||||
} catch (error: any) {
|
||||
set({ error: error.message || 'Failed to load shares' });
|
||||
}
|
||||
},
|
||||
|
||||
clearError: () => set({ error: null }),
|
||||
})),
|
||||
);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue