Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add signing to mobile login flow
Leendert de Borst177cbefd22b2
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.ktindex 86e91354d..c7ccd2160 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt@@ -38,6 +38,7 @@ class VaultSync("lookupAccountFingerprint","acceptSharedManifestInvitation","transferEmailClaim",+ "approveMobileLogin",)}diff --git a/apps/mobile-app/app/(tabs)/settings/mobile-unlock/confirm.tsx b/apps/mobile-app/app/(tabs)/settings/mobile-unlock/confirm.tsxindex d36f7e7bd..074384734 100644--- a/apps/mobile-app/app/(tabs)/settings/mobile-unlock/confirm.tsx+++ b/apps/mobile-app/app/(tabs)/settings/mobile-unlock/confirm.tsx@@ -1,6 +1,6 @@import { ApiRequestError } from '@aliasvault/client/api/errors/ApiRequestError';import { MobileLoginProtocol } from '@aliasvault/client/auth/MobileLoginProtocol';-import { VaultKeyAlgorithm, type MobileLoginDetailsResponse, type MobileLoginRequestReference, type MobileLoginSubmitRequest } from '@aliasvault/models/webapi';+import { VaultKeyAlgorithm, type MobileLoginDetailsResponse, type MobileLoginRequestReference } from '@aliasvault/models/webapi';import { Ionicons } from '@expo/vector-icons';import { router } from 'expo-router';import { useState, useEffect, useRef } from 'react';@@ -188,8 +188,13 @@ export default function MobileUnlockConfirmScreen() : React.ReactNode {// Encrypt with the public key that was verified against the QR code.const encryptedAccountKey = await NativeVaultManager.encryptAccountKeyForMobileLogin(request.details.clientPublicKey);- const submitRequest: MobileLoginSubmitRequest = { requestId: scan.requestId, encryptedAccountKey, algorithm: request.details.algorithm };- await webApi.post<MobileLoginSubmitRequest, void>('auth/mobile-login/submit', submitRequest, false);+ const approval = { requestId: scan.requestId, encryptedAccountKey, algorithm: request.details.algorithm };+ const result = await NativeVaultManager.runSharingOperation('approveMobileLogin', JSON.stringify(approval));+ if (!result.success) {+ console.error('Mobile login approval failed:', result.apiErrorCode ?? result.error);+ showResult(false);+ return;+ }showResult(true);} catch (error) {diff --git a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swiftindex 154db9266..002f7eb88 100644--- a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift+++ b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift@@ -237,7 +237,7 @@ internal final class VaultSync {}/// The engine operations the sharing screen may ask for.- private static let sharingOperations: Set<String> = ["createSharedManifest", "inviteToSharedManifest", "updateSharedManifest", "lookupAccountFingerprint", "acceptSharedManifestInvitation", "transferEmailClaim"]+ private static let sharingOperations: Set<String> = ["createSharedManifest", "inviteToSharedManifest", "updateSharedManifest", "lookupAccountFingerprint", "acceptSharedManifestInvitation", "transferEmailClaim", "approveMobileLogin"]/// The forced logouts by the engine's reason.private static let logoutErrors: [String: AppError] = [diff --git a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs b/apps/server/AliasVault.Api/Controllers/V2/AuthController.csindex ebfd39606..6a1e872d1 100644--- a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs@@ -1076,6 +1076,14 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMreturn ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);}+ // An approval creates a new session, so the approving session must still exist: a leftover access token of a revoked+ // session cannot be used to log in again.+ var sessionId = Guid.TryParse(User.FindFirstValue(TokenService.RefreshTokenIdClaim), out var refreshTokenId) ? refreshTokenId : Guid.Empty;+ if (!await context.AliasVaultUserRefreshTokens.AnyAsync(t => t.Id == sessionId && t.UserId == user.Id))+ {+ return ApiError.Result(ApiErrorCode.NOT_AUTHENTICATED, 401);+ }+var loginRequest = await context.MobileLoginRequests.FirstOrDefaultAsync(r => r.Id == model.RequestId);if (loginRequest == null || !MobileLoginRequestHelper.IsAwaitingApproval(loginRequest, timeProvider.GetUtcNow().UtcDateTime)){@@ -1088,6 +1096,17 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserMreturn ApiError.Result(ApiErrorCode.INVALID_ALGORITHM, 400);}+ // A signed approval proves the signing key, which a session token alone does not. Unsigned approvals from older app+ // versions are still accepted; make the signature required once those versions are no longer supported.+ if (model.Signature is not null)+ {+ var signingKey = await GrantHelper.GetPrimarySigningKeyAsync(context, user.Id);+ if (signingKey is null || !Signing.Verify(signingKey, Signing.MobileLoginApprovalMessage(model.RequestId, model.Algorithm, model.EncryptedAccountKey), model.Signature))+ {+ return ApiError.Result(ApiErrorCode.SIGNATURE_INVALID, 400);+ }+ }+// Store the answer in one transaction.var fulfilledAt = timeProvider.GetUtcNow().UtcDateTime;var mobileIpAddress = IpAddressUtility.GetAnonymizedIpFromContext(HttpContext, config.IpLoggingEnabled);diff --git a/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs b/apps/server/AliasVault.Api/Controllers/V2/GroupsController.csindex 3b6df901e..4dae875d4 100644--- a/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs@@ -237,33 +237,34 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Usereturn ApiError.Result(ApiErrorCode.ACCOUNT_FINGERPRINT_NOT_FOUND, 404);}- var signerPublicKey = await GrantHelper.GetPrimarySigningKeyAsync(context, me.Id);- if (!Signing.Verify(signerPublicKey, Signing.KeyCertificationMessage(me.Id, model.SubjectUserId, model.SubjectSigningPublicKey), model.Signature))- {- return ApiError.Result(ApiErrorCode.SIGNATURE_INVALID, 400);- }-- var now = timeProvider.GetUtcNow().UtcDateTime;- Task<int> ReplaceAsync() => context.UserKeyCertifications- .Where(c => c.CertifierUserId == me.Id && c.SubjectUserId == model.SubjectUserId)- .ExecuteUpdateAsync(c => c.SetProperty(x => x.SubjectSigningPublicKey, model.SubjectSigningPublicKey).SetProperty(x => x.Signature, model.Signature).SetProperty(x => x.UpdatedAt, now));-- if (await ReplaceAsync() == 0)+ var strategy = context.Database.CreateExecutionStrategy();+ return await strategy.ExecuteAsync<IActionResult>(async () =>{- context.UserKeyCertifications.Add(new UserKeyCertification { Id = Guid.NewGuid(), CertifierUserId = me.Id, SubjectUserId = model.SubjectUserId, SubjectSigningPublicKey = model.SubjectSigningPublicKey, Signature = model.Signature, CreatedAt = now, UpdatedAt = now });+ await using var writeContext = await dbContextFactory.CreateDbContextAsync();+ await using var tx = await writeContext.Database.BeginTransactionAsync();- try+ // The signature is checked against the signing key under the lock a key rotation takes, so it cannot be replaced in between.+ await GrantHelper.LockUserCertificationsAsync(writeContext, me.Id);+ var signerPublicKey = await GrantHelper.GetPrimarySigningKeyAsync(writeContext, me.Id);+ if (!Signing.Verify(signerPublicKey, Signing.KeyCertificationMessage(me.Id, model.SubjectUserId, model.SubjectSigningPublicKey), model.Signature)){- await context.SaveChangesAsync();+ return ApiError.Result(ApiErrorCode.SIGNATURE_INVALID, 400);}- catch (DbUpdateException)++ var now = timeProvider.GetUtcNow().UtcDateTime;+ var replaced = await writeContext.UserKeyCertifications+ .Where(c => c.CertifierUserId == me.Id && c.SubjectUserId == model.SubjectUserId)+ .ExecuteUpdateAsync(c => c.SetProperty(x => x.SubjectSigningPublicKey, model.SubjectSigningPublicKey).SetProperty(x => x.Signature, model.Signature).SetProperty(x => x.UpdatedAt, now));+ if (replaced == 0){- // A concurrent request stored a certification for the same pair first; this one replaces it.- await ReplaceAsync();+ writeContext.UserKeyCertifications.Add(new UserKeyCertification { Id = Guid.NewGuid(), CertifierUserId = me.Id, SubjectUserId = model.SubjectUserId, SubjectSigningPublicKey = model.SubjectSigningPublicKey, Signature = model.Signature, CreatedAt = now, UpdatedAt = now });+ await writeContext.SaveChangesAsync();}- }- return Ok();+ await tx.CommitAsync();+ await authLoggingService.LogAuthEventSuccessAsync(me.UserName!, AuthEventType.KeyCertification);+ return Ok();+ });}/// <summary>@@ -488,6 +489,7 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use}await transaction.CommitAsync();+ await authLoggingService.LogAuthEventSuccessAsync(me.UserName!, AuthEventType.SharedVaultInvitation);return Ok(new GrantManifestAccessResponse { InvitationId = invitation.Id });});}@@ -908,6 +910,7 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Useawait context.SaveChangesAsync();await transaction.CommitAsync();+ await authLoggingService.LogAuthEventSuccessAsync(me.UserName!, AuthEventType.SharedVaultJoin);return Ok();});}diff --git a/apps/server/AliasVault.Api/Controllers/V2/KeyRotationController.cs b/apps/server/AliasVault.Api/Controllers/V2/KeyRotationController.csindex 01f01d11d..0747aa518 100644--- a/apps/server/AliasVault.Api/Controllers/V2/KeyRotationController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/KeyRotationController.cs@@ -132,6 +132,7 @@ public class KeyRotationController(ILogger<KeyRotationController> logger, IAlias{await using var writeContext = await dbContextFactory.CreateDbContextAsync();await using var tx = await writeContext.Database.BeginTransactionAsync();+ await GrantHelper.LockUserCertificationsAsync(writeContext, user.Id);var manifest = await writeContext.VaultManifests.FirstOrDefaultAsync(x => x.ManifestId == model.Expected.PersonalManifestId && x.OwnerGroupId == user.PersonalGroupId);if (manifest == null)diff --git a/apps/server/AliasVault.Api/Helpers/GrantHelper.cs b/apps/server/AliasVault.Api/Helpers/GrantHelper.csindex daf5cd213..ff5e4ea55 100644--- a/apps/server/AliasVault.Api/Helpers/GrantHelper.cs+++ b/apps/server/AliasVault.Api/Helpers/GrantHelper.cs@@ -101,6 +101,18 @@ public static class GrantHelperreturn await context.UserSigningKeys.Where(k => k.UserId == userId && k.IsPrimary).Select(k => k.PublicKey).FirstOrDefaultAsync();}+ /// <summary>+ /// Take a transaction-scoped lock on the key certifications a user made, so a certification and a key rotation of that+ /// user never interleave (a certification signed with the old key after the rotation re-signed the others).+ /// </summary>+ /// <param name="context">Database context, inside an open transaction.</param>+ /// <param name="userId">The certifying user.</param>+ /// <returns>Task.</returns>+ public static async Task LockUserCertificationsAsync(AliasServerDbContext context, string userId)+ {+ await context.Database.ExecuteSqlInterpolatedAsync($"SELECT pg_advisory_xact_lock(hashtextextended({"user-certifications:" + userId}, 0))");+ }+/// <summary>/// Take a user's access to a shared manifest away./// </summary>diff --git a/apps/server/Shared/AliasVault.Shared/Models/Enums/AuthEventType.cs b/apps/server/Shared/AliasVault.Shared/Models/Enums/AuthEventType.csindex af5c3c2c5..c5873b727 100644--- a/apps/server/Shared/AliasVault.Shared/Models/Enums/AuthEventType.cs+++ b/apps/server/Shared/AliasVault.Shared/Models/Enums/AuthEventType.cs@@ -88,19 +88,24 @@ public enum AuthEventTypeSharedVaultAccessRevocation = 52,/// <summary>- /// Represents an admin removing a member from a family, confirmed with the master password.+ /// Represents a member giving up their own access to a shared manifest, confirmed with the master password./// </summary>- FamilyMemberRemoval = 53,+ SharedVaultLeave = 54,/// <summary>- /// Represents a member giving up their own access to a shared manifest, confirmed with the master password.+ /// Represents an admin inviting an account to a shared manifest./// </summary>- SharedVaultLeave = 54,+ SharedVaultInvitation = 56,++ /// <summary>+ /// Represents accepting an invitation to a shared manifest, which gives the account its own grant.+ /// </summary>+ SharedVaultJoin = 57,/// <summary>- /// Represents a member leaving a family, confirmed with the master password.+ /// Represents certifying another account's signing key after checking its account fingerprint./// </summary>- FamilyLeave = 55,+ KeyCertification = 58,/// <summary>/// Represents a user account deletion event.diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/MobileLoginSubmitRequest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/MobileLoginSubmitRequest.csindex b1255d985..9c140b252 100644--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/MobileLoginSubmitRequest.cs+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/MobileLoginSubmitRequest.cs@@ -33,4 +33,10 @@ public class MobileLoginSubmitRequest/// </summary>[Required]public required string Algorithm { get; set; }++ /// <summary>+ /// Gets or sets the approving user's Ed25519 signature over the approval (see <c>Signing.MobileLoginApprovalMessage</c>).+ /// Optional while app versions that do not sign are supported.+ /// </summary>+ public string? Signature { get; set; }}diff --git a/apps/server/Tests/AliasVault.UnitTests/Utilities/SigningTests.cs b/apps/server/Tests/AliasVault.UnitTests/Utilities/SigningTests.csindex c7ef5bfa4..200c738df 100644--- a/apps/server/Tests/AliasVault.UnitTests/Utilities/SigningTests.cs+++ b/apps/server/Tests/AliasVault.UnitTests/Utilities/SigningTests.cs@@ -49,4 +49,14 @@ public class SigningTestsvar message = Signing.EmailClaimTransferMessage("[email protected]", Guid.Parse("0A1B2C3D-0000-0000-0000-000000000001"), Guid.Parse("0A1B2C3D-0000-0000-0000-000000000002"), 1767225600000);Assert.That(Convert.ToHexStringLower(message), Is.EqualTo("00000026616c6961737661756c742f76312f7369672f656d61696c2d636c61696d2d7472616e7366657200000011616c696173406578616d706c652e636f6d0000002430613162326333642d303030302d303030302d303030302d3030303030303030303030310000002430613162326333642d303030302d303030302d303030302d3030303030303030303030320000000d31373637323235363030303030"));}++ /// <summary>+ /// The Login with Mobile approval message equals the Rust core's MOBILE_LOGIN_APPROVAL_MESSAGE_VECTOR.+ /// </summary>+ [Test]+ public void MobileLoginApprovalMessageKnownAnswer()+ {+ var message = Signing.MobileLoginApprovalMessage("0123456789abcdef0123456789abcdef", "rsa-oaep-sha256", "YWs=");+ Assert.That(Convert.ToHexStringLower(message), Is.EqualTo("00000027616c6961737661756c742f76312f7369672f6d6f62696c652d6c6f67696e2d617070726f76616c0000002030313233343536373839616263646566303132333435363738396162636465660000000f7273612d6f6165702d736861323536000000045957733d"));+ }}diff --git a/apps/server/Utilities/AliasVault.Cryptography/Signing.cs b/apps/server/Utilities/AliasVault.Cryptography/Signing.csindex d3cbea07f..6e9d0f87c 100644--- a/apps/server/Utilities/AliasVault.Cryptography/Signing.cs+++ b/apps/server/Utilities/AliasVault.Cryptography/Signing.cs@@ -42,6 +42,11 @@ public static class Signing/// </summary>public const string EmailClaimTransferLabel = "aliasvault/v1/sig/email-claim-transfer";+ /// <summary>+ /// The label of a Login with Mobile approval, signed by the approving user.+ /// </summary>+ public const string MobileLoginApprovalLabel = "aliasvault/v1/sig/mobile-login-approval";+/// <summary>/// The label of a new signing public key, signed by the signing key it replaces./// </summary>@@ -137,6 +142,18 @@ public static class Signingreturn SignedMessage(EmailClaimTransferLabel, Utf8(address), Utf8(sourceManifestId.ToString()), Utf8(targetManifestId.ToString()), Utf8(claimVersion.ToString(System.Globalization.CultureInfo.InvariantCulture)));}+ /// <summary>+ /// Builds the signed message of a Login with Mobile approval: the Account Key encrypted for the requesting client.+ /// </summary>+ /// <param name="requestId">The Login with Mobile request.</param>+ /// <param name="algorithm">The algorithm of the encrypted Account Key.</param>+ /// <param name="encryptedAccountKey">The encrypted Account Key.</param>+ /// <returns>The message bytes.</returns>+ public static byte[] MobileLoginApprovalMessage(string requestId, string algorithm, string encryptedAccountKey)+ {+ return SignedMessage(MobileLoginApprovalLabel, Utf8(requestId), Utf8(algorithm), Utf8(encryptedAccountKey));+ }+/// <summary>/// Builds the signed message of a signing key rotation: the account's new signing public key, signed by the previous one./// </summary>diff --git a/core/client/src/sync/VaultSyncEngine.ts b/core/client/src/sync/VaultSyncEngine.tsindex b145e4de4..d9d43e39a 100644--- a/core/client/src/sync/VaultSyncEngine.ts+++ b/core/client/src/sync/VaultSyncEngine.ts@@ -21,7 +21,7 @@ import type { ISqliteDatabase, SqliteValue } from '../platform/SqliteEngine';/** The operations the engine runs. *//** The sharing operations, which take `VaultSyncSharingParams`. */-export type VaultSyncSharingOperation = 'createSharedManifest' | 'inviteToSharedManifest' | 'updateSharedManifest' | 'lookupAccountFingerprint' | 'acceptSharedManifestInvitation' | 'transferEmailClaim';+export type VaultSyncSharingOperation = 'createSharedManifest' | 'inviteToSharedManifest' | 'updateSharedManifest' | 'lookupAccountFingerprint' | 'acceptSharedManifestInvitation' | 'transferEmailClaim' | 'approveMobileLogin';export type VaultSyncOperation = 'fullSync' | 'migrationStatus' | 'migrateManifest' | 'statusCheck' | 'resolveVaultKey' | VaultSyncSharingOperation | 'rotateAccountKeys';@@ -52,6 +52,9 @@ export type VaultSyncSharingParams = {address?: string;sourceManifestId?: string;claimVersion?: number;+ requestId?: string;+ encryptedAccountKey?: string;+ algorithm?: string;};/** Moving an email alias from `sourceManifestId` to `manifestId`, signed over the claim version the server reported. */diff --git a/core/models/src/webapi/AuthEventType.ts b/core/models/src/webapi/AuthEventType.tsindex 4b696d195..470797283 100644--- a/core/models/src/webapi/AuthEventType.ts+++ b/core/models/src/webapi/AuthEventType.ts@@ -72,6 +72,31 @@ export enum AuthEventType {*/SharedVaultDeletion = 'shared-vault-deletion',+ /**+ * Represents an admin taking a member's access to a shared manifest away, confirmed with the master password.+ */+ SharedVaultAccessRevocation = 'shared-vault-access-revocation',++ /**+ * Represents a member giving up their own access to a shared manifest, confirmed with the master password.+ */+ SharedVaultLeave = 'shared-vault-leave',++ /**+ * Represents an admin inviting an account to a shared manifest.+ */+ SharedVaultInvitation = 'shared-vault-invitation',++ /**+ * Represents accepting an invitation to a shared manifest, which gives the account its own grant.+ */+ SharedVaultJoin = 'shared-vault-join',++ /**+ * Represents certifying another account's signing key after checking its account fingerprint.+ */+ KeyCertification = 'key-certification',+/*** Represents a user account deletion event.*/diff --git a/core/models/src/webapi/MobileLogin.ts b/core/models/src/webapi/MobileLogin.tsindex 09b316e38..ee6268c6a 100644--- a/core/models/src/webapi/MobileLogin.ts+++ b/core/models/src/webapi/MobileLogin.ts@@ -70,12 +70,3 @@ export type MobileLoginDetailsResponse = {operatingSystem: string | null;createdAt: string;}--/**- * Mobile login submit request type.- */-export type MobileLoginSubmitRequest = {- requestId: string;- encryptedAccountKey: string;- algorithm: string;-}diff --git a/core/rust/src/crypto/signing.rs b/core/rust/src/crypto/signing.rsindex 1d702e08c..88c271979 100644--- a/core/rust/src/crypto/signing.rs+++ b/core/rust/src/crypto/signing.rs@@ -29,6 +29,9 @@ pub const INVITATION_NAME_LABEL: &str = "aliasvault/v1/sig/invitation-name";/// The label of moving an email alias to another manifest, signed by the user who moves it.pub const EMAIL_CLAIM_TRANSFER_LABEL: &str = "aliasvault/v1/sig/email-claim-transfer";+/// The label of a Login with Mobile approval: the Account Key encrypted for the requesting client, signed by the approving user.+pub const MOBILE_LOGIN_APPROVAL_LABEL: &str = "aliasvault/v1/sig/mobile-login-approval";+/// The label of a new signing public key, signed by the signing key it replaces.pub const SIGNING_KEY_ROTATION_LABEL: &str = "aliasvault/v1/sig/signing-key-rotation";@@ -107,6 +110,11 @@ pub fn email_claim_transfer_message(address: &str, source_manifest_id: &str, tarsigned_message(EMAIL_CLAIM_TRANSFER_LABEL, &[address.as_bytes(), normalize(source_manifest_id).as_bytes(), normalize(target_manifest_id).as_bytes(), claim_version.as_bytes()])}+/// The signed message of approving Login with Mobile request `request_id` with `encrypted_account_key`.+pub fn mobile_login_approval_message(request_id: &str, algorithm: &str, encrypted_account_key: &str) -> Vec<u8> {+ signed_message(MOBILE_LOGIN_APPROVAL_LABEL, &[request_id.as_bytes(), algorithm.as_bytes(), encrypted_account_key.as_bytes()])+}+/// The signed message of a signing key rotation: the account's new signing public key, vouched for by the previous one.pub fn signing_key_rotation_message(user_id: &str, new_signing_public_key: &str) -> Vec<u8> {signed_message(SIGNING_KEY_ROTATION_LABEL, &[user_id.as_bytes(), new_signing_public_key.as_bytes()])@@ -217,6 +225,15 @@ mod tests {assert_eq!(crate::common::encoding::hex_encode_lower(&message), EMAIL_CLAIM_TRANSFER_MESSAGE_VECTOR);}+ /// Known-answer vector for the Login with Mobile approval message, which `Signing.cs` builds too. Never regenerate it.+ #[test]+ fn mobile_login_approval_message_known_answer() {+ let message = mobile_login_approval_message("0123456789abcdef0123456789abcdef", "rsa-oaep-sha256", "YWs=");+ assert_eq!(crate::common::encoding::hex_encode_lower(&message), MOBILE_LOGIN_APPROVAL_MESSAGE_VECTOR);+ }++ const MOBILE_LOGIN_APPROVAL_MESSAGE_VECTOR: &str = "00000027616c6961737661756c742f76312f7369672f6d6f62696c652d6c6f67696e2d617070726f76616c0000002030313233343536373839616263646566303132333435363738396162636465660000000f7273612d6f6165702d736861323536000000045957733d";+const EMAIL_CLAIM_TRANSFER_MESSAGE_VECTOR: &str = "00000026616c6961737661756c742f76312f7369672f656d61696c2d636c61696d2d7472616e7366657200000011616c696173406578616d706c652e636f6d0000002430613162326333642d303030302d303030302d303030302d3030303030303030303030310000002430613162326333642d303030302d303030302d303030302d3030303030303030303030320000000d31373637323235363030303030";const KEY_CERTIFICATION_MESSAGE_VECTOR: &str = "00000023616c6961737661756c742f76312f7369672f6b65792d63657274696669636174696f6e00000006757365722d3100000006757365722d320000002c41364548762f504f454c3464634e3059353076416d57666b316a436270513166486479475a424a564d62673d";diff --git a/core/rust/src/vault_sync/engine.rs b/core/rust/src/vault_sync/engine.rsindex 84ba16ec9..77ba2e630 100644--- a/core/rust/src/vault_sync/engine.rs+++ b/core/rust/src/vault_sync/engine.rs@@ -35,6 +35,7 @@ pub(crate) async fn run(host: Host, request: SyncRequest) -> Value {SyncOperation::AcceptSharedManifestInvitation => serde_json::to_value(sharing::accept_shared_manifest_invitation_operation(&mut ctx).await),SyncOperation::RotateAccountKeys => serde_json::to_value(rotation::rotate_account_keys_operation(&mut ctx).await),SyncOperation::TransferEmailClaim => serde_json::to_value(sharing::transfer_email_claim_operation(&mut ctx).await),+ SyncOperation::ApproveMobileLogin => serde_json::to_value(sharing::approve_mobile_login_operation(&mut ctx).await),};finish(&ctx, result.unwrap_or(Value::Null))}diff --git a/core/rust/src/vault_sync/sharing.rs b/core/rust/src/vault_sync/sharing.rsindex 2c8bef59c..483226de0 100644--- a/core/rust/src/vault_sync/sharing.rs+++ b/core/rust/src/vault_sync/sharing.rs@@ -1,5 +1,6 @@//! The sharing operations that take vault keys or sign something: creating a group's shared manifest, updating one,-//! inviting to a group or a shared manifest, accepting those invitations, and moving an email alias to another manifest.+//! inviting to a group or a shared manifest, accepting those invitations, moving an email alias to another manifest, and+//! approving a Login with Mobile request.//!//! Trust between two accounts rests on key certifications: once a user has checked another account's signing key (outside//! AliasVault) against that account's account fingerprint (the key's fingerprint), a client signs a@@ -133,6 +134,16 @@ struct EmailClaimTransferRequest<'a> {signature: &'a str,}+#[derive(Debug, Serialize)]+#[serde(rename_all = "camelCase")]+struct MobileLoginSubmitRequest<'a> {+ request_id: &'a str,+ encrypted_account_key: &'a str,+ algorithm: &'a str,+ #[serde(skip_serializing_if = "Option::is_none")]+ signature: Option<String>,+}+#[derive(Debug, Serialize)]#[serde(rename_all = "camelCase")]struct AcceptInvitationRequest<'a> {@@ -285,6 +296,12 @@ pub(crate) async fn transfer_email_claim_operation(ctx: &mut Ctx) -> SharingOperfinish(ctx, "move email alias", outcome).await}+/// Approve a Login with Mobile request.+pub(crate) async fn approve_mobile_login_operation(ctx: &mut Ctx) -> SharingOperationResult {+ let outcome = approve_mobile_login(ctx).await;+ finish(ctx, "approve mobile login", outcome).await+}+/// Turn an operation's outcome into the result the host acts on.async fn finish(ctx: &Ctx, what: &str, outcome: Outcome) -> SharingOperationResult {match outcome {@@ -645,6 +662,22 @@ async fn transfer_email_claim(ctx: &mut Ctx) -> Outcome {Ok(Ok(Done { manifest_id: Some(target_manifest_id), ..Default::default() }))}+/// Hand the Account Key, encrypted for the requesting client, to a Login with Mobile request, signed with this account's+/// own key so a stolen session token alone cannot approve a request. An account without a signing key yet sends it unsigned.+async fn approve_mobile_login(ctx: &mut Ctx) -> Outcome {+ let target = params(ctx)?;+ let request_id = target.request_id.as_deref().ok_or_else(|| SyncError::Other("The approval names no request".to_string()))?;+ let encrypted_account_key = target.encrypted_account_key.as_deref().ok_or_else(|| SyncError::Other("The approval carries no Account Key".to_string()))?;+ let algorithm = target.algorithm.as_deref().ok_or_else(|| SyncError::Other("The approval names no algorithm".to_string()))?;+ let signature = match keys::signing_private_key(ctx).await? {+ Some(signing_key) => Some(crypto::signing::sign(signing_key.expose_secret(), &crypto::signing::mobile_login_approval_message(request_id, algorithm, encrypted_account_key))?),+ None => None,+ };+ http::post_no_content(&ctx.host, "Auth/mobile-login/submit", &MobileLoginSubmitRequest { request_id, encrypted_account_key, algorithm, signature }).await?;+ ctx.log("[Sharing] Approved a Login with Mobile request.").await;+ Ok(Ok(Done::default()))+}+/// Accept an invitation to a shared manifest: check the certified inviter signed it and the key inside opens for this/// account, then sign the grant as this account's own.async fn accept_shared_manifest_invitation(ctx: &mut Ctx) -> Outcome {diff --git a/core/rust/src/vault_sync/types.rs b/core/rust/src/vault_sync/types.rsindex 98dc7427a..5a403f17e 100644--- a/core/rust/src/vault_sync/types.rs+++ b/core/rust/src/vault_sync/types.rs@@ -40,6 +40,8 @@ pub enum SyncOperation {RotateAccountKeys,/// Move an email alias to another manifest (`SharingParams.manifest_id`), signed with this account's own key.TransferEmailClaim,+ /// Approve a Login with Mobile request with the Account Key encrypted for the requesting client, signed with this account's own key.+ ApproveMobileLogin,}/// What a key rotation needs from the host: the proof of the current password and the new unlock method, both@@ -88,6 +90,15 @@ pub struct SharingParams {/// The claim version the server reported for the alias, which an alias transfer signs.#[serde(default)]pub claim_version: Option<i64>,+ /// The Login with Mobile request a mobile login approval answers.+ #[serde(default)]+ pub request_id: Option<String>,+ /// The Account Key encrypted for the requesting client, for a mobile login approval.+ #[serde(default)]+ pub encrypted_account_key: Option<String>,+ /// The algorithm of `encrypted_account_key`.+ #[serde(default)]+ pub algorithm: Option<String>,}/// Sync request.