Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Update mobile login models and API methods (#2159)

Leendert de Borstd68c674664b7
diff --git a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs b/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs
index 18ae06312..b6d1d8373 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs
@@ -57,12 +57,6 @@ using V2Auth = AliasVault.Shared.Models.WebApi.V2.Auth;
[ApiVersion("2")]
public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, IConfiguration configuration, IMemoryCache cache, ITimeProvider timeProvider, AuthLoggingService authLoggingService, Config config, ServerSettingsService settingsService, RegistrationRateLimitService registrationRateLimitService, IpBlockListService ipBlockListService, MobileLoginRateLimitService mobileLoginRateLimitService) : ControllerBase
{
- /// <summary>
- /// Timeout in minutes for mobile login requests. Clients use 2 minutes for countdown, we use 3 here to give a bit of extra buffer time.
- /// Requests older than this will be automatically expired and removed.
- /// </summary>
- private const int MobileLoginTimeoutMinutes = 10;
-
/// <summary>
/// Access token validity in minutes.
/// </summary>
@@ -747,13 +741,13 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
}
/// <summary>
- /// Initiates a mobile login request by creating a QR code challenge.
+ /// Initiates a mobile login request. The client shows the returned request id as a QR code and keeps the poll secret to itself.
/// </summary>
/// <param name="model">The mobile login initiate request model.</param>
/// <returns>IActionResult.</returns>
[HttpPost("mobile-login/initiate")]
[AllowAnonymous]
- public async Task<IActionResult> InitiateMobileLogin([FromBody] MobileLoginInitiateRequest model)
+ public async Task<IActionResult> InitiateMobileLogin([FromBody] V2Auth.MobileLoginInitiateRequest model)
{
// Reject invalid public key structure.
if (!MobileLoginPublicKeyValidator.IsValid(model.ClientPublicKey))
@@ -779,62 +773,68 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
await using var context = await dbContextFactory.CreateDbContextAsync();
- // Generate a unique request ID
+ // The request id travels through the QR code, the poll secret stays with the initiating client. Only its hash is stored.
var requestId = Guid.NewGuid().ToString("N");
+ var pollSecret = Base64UrlEncoder.Encode(RandomNumberGenerator.GetBytes(32));
- // Create the login request
var loginRequest = new MobileLoginRequest
{
Id = requestId,
ClientPublicKey = model.ClientPublicKey,
+ PollSecretHash = MobileLoginRequestHelper.HashPollSecret(pollSecret),
CreatedAt = timeProvider.UtcNow,
ClientIpAddress = ipAddress,
+ ClientName = MobileLoginRequestHelper.SanitizeClientName(ClientHeaderInfo.GetRawValue(Request)),
+ ClientBrowser = RequestClientInfo.DetermineBrowser(HttpContext),
+ ClientOperatingSystem = RequestClientInfo.DetermineOperatingSystem(HttpContext),
};
context.MobileLoginRequests.Add(loginRequest);
await context.SaveChangesAsync();
- return Ok(new MobileLoginInitiateResponse
+ return Ok(new V2Auth.MobileLoginInitiateResponse
{
RequestId = requestId,
+ PollSecret = pollSecret,
});
}
/// <summary>
- /// Polls the status of a mobile login request.
+ /// Polls the status of a mobile login request. Only the client that initiated the request holds the poll secret.
/// </summary>
- /// <param name="requestId">The unique identifier for the login request.</param>
+ /// <param name="model">The mobile login poll request model.</param>
/// <returns>IActionResult.</returns>
- [HttpGet("mobile-login/poll/{requestId}")]
+ [HttpPost("mobile-login/poll")]
[AllowAnonymous]
- public async Task<IActionResult> PollMobileLogin(string requestId)
+ public async Task<IActionResult> PollMobileLogin([FromBody] V2Auth.MobileLoginPollRequest model)
{
await using var context = await dbContextFactory.CreateDbContextAsync();
- var loginRequest = await context.MobileLoginRequests.FirstOrDefaultAsync(r => r.Id == requestId);
+ var loginRequest = await context.MobileLoginRequests.FirstOrDefaultAsync(r => r.Id == model.RequestId);
- // Check if request exists and hasn't expired
- if (loginRequest == null || loginRequest.CreatedAt.AddMinutes(MobileLoginTimeoutMinutes) < timeProvider.UtcNow)
+ // An unknown request and a wrong poll secret get the same answer.
+ if (loginRequest == null || !MobileLoginRequestHelper.IsPollSecretValid(loginRequest, model.PollSecret))
{
return NotFound(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 404));
}
- // If not fulfilled, return pending status
+ if (loginRequest.DeclinedAt != null)
+ {
+ return Ok(new V2Auth.MobileLoginPollResponse { Status = V2Auth.MobileLoginStatus.Declined });
+ }
+
if (loginRequest.FulfilledAt == null)
{
- return Ok(new MobileLoginPollResponse
+ if (MobileLoginRequestHelper.IsApprovalWindowClosed(loginRequest, timeProvider.UtcNow))
{
- Fulfilled = false,
- EncryptedSymmetricKey = null,
- EncryptedToken = null,
- EncryptedRefreshToken = null,
- EncryptedDecryptionKey = null,
- EncryptedUsername = null,
- });
+ return NotFound(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 404));
+ }
+
+ return Ok(new V2Auth.MobileLoginPollResponse { Status = V2Auth.MobileLoginStatus.Pending });
}
- // Check if already retrieved (one-time use protection)
- if (loginRequest.RetrievedAt != null)
+ // One-time use: an approved request is handed out once, and only shortly after the approval.
+ if (loginRequest.RetrievedAt != null || loginRequest.EncryptedUnlockKey == null || MobileLoginRequestHelper.IsRetrievalWindowClosed(loginRequest, timeProvider.UtcNow))
{
return NotFound(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 404));
}
@@ -861,76 +861,84 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.ACCOUNT_LOCKED, 400));
}
- // Generate token for the user
- var tokenModel = await GenerateNewTokensForUser(user, extendedLifetime: true);
+ // Claim the request and clear its key material in one transaction.
+ var clientPublicKey = loginRequest.ClientPublicKey;
+ var encryptedUnlockKey = loginRequest.EncryptedUnlockKey;
+ var retrievedAt = timeProvider.UtcNow;
+ var claimed = await context.MobileLoginRequests
+ .Where(r => r.Id == loginRequest.Id && r.RetrievedAt == null)
+ .ExecuteUpdateAsync(u => u.SetProperty(r => r.RetrievedAt, retrievedAt).SetProperty(r => r.ClientPublicKey, string.Empty).SetProperty(r => r.EncryptedUnlockKey, (string?)null));
+ if (claimed != 1)
+ {
+ return NotFound(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 404));
+ }
- // Get encrypted decryption key from the login request and put it in memory
- var encryptedDecryptionKey = loginRequest.EncryptedDecryptionKey!;
+ // The client needs the key derivation parameters next to the unlock key to be able to unlock offline later.
+ var tokenModel = await GenerateNewTokensForUser(user, extendedLifetime: true);
+ var encryptionSettings = await AuthHelper.GetUserLatestVaultEncryptionSettingsAsync(context, user);
+ var payload = new V2Auth.MobileLoginPayload
+ {
+ Username = user.UserName!,
+ Token = tokenModel.Token,
+ RefreshToken = tokenModel.RefreshToken,
+ Salt = encryptionSettings.Salt,
+ EncryptionType = encryptionSettings.EncryptionType,
+ EncryptionSettings = encryptionSettings.EncryptionSettings,
+ };
- // Generate a single symmetric key for encrypting all fields
+ // The payload is encrypted with a one-off symmetric key, which in turn is encrypted with the client's RSA public key.
var symmetricKey = Cryptography.Server.Encryption.GenerateRandomSymmetricKey();
+ var encryptedPayload = Cryptography.Server.Encryption.SymmetricEncrypt(JsonSerializer.Serialize(payload, MobileLoginRequestHelper.PayloadJsonOptions), symmetricKey);
+ var encryptedSymmetricKey = Cryptography.Server.Encryption.EncryptSymmetricKeyWithRsa(symmetricKey, clientPublicKey);
- // Encrypt each field with the symmetric key (returns base64)
- var encryptedToken = Cryptography.Server.Encryption.SymmetricEncrypt(tokenModel.Token, symmetricKey);
- var encryptedRefreshToken = Cryptography.Server.Encryption.SymmetricEncrypt(tokenModel.RefreshToken, symmetricKey);
- var encryptedUsername = Cryptography.Server.Encryption.SymmetricEncrypt(user.UserName!, symmetricKey);
-
- // Encrypt the symmetric key with the client's RSA public key (returns base64)
- var encryptedSymmetricKey = Cryptography.Server.Encryption.EncryptSymmetricKeyWithRsa(symmetricKey, loginRequest.ClientPublicKey);
-
- // Log successful mobile login authentication
await authLoggingService.LogAuthEventSuccessAsync(user.UserName!, AuthEventType.MobileLogin);
- // Mark as retrieved and clear sensitive data from database
- loginRequest.ClientPublicKey = string.Empty;
- loginRequest.EncryptedDecryptionKey = null;
- loginRequest.RetrievedAt = timeProvider.UtcNow;
- await context.SaveChangesAsync();
-
- // Return response with encrypted symmetric key and encrypted fields
- // Client will decrypt username to call /login endpoint for salt and encryption settings
- return Ok(new MobileLoginPollResponse
+ return Ok(new V2Auth.MobileLoginPollResponse
{
- Fulfilled = true,
+ Status = V2Auth.MobileLoginStatus.Approved,
EncryptedSymmetricKey = encryptedSymmetricKey,
- EncryptedToken = encryptedToken,
- EncryptedRefreshToken = encryptedRefreshToken,
- EncryptedDecryptionKey = encryptedDecryptionKey,
- EncryptedUsername = encryptedUsername,
+ EncryptedPayload = encryptedPayload,
+ EncryptedUnlockKey = encryptedUnlockKey,
});
}
/// <summary>
- /// Gets the public key for a mobile login request (for mobile app to encrypt).
+ /// Gets details about a mobile login request that the mobile app shows to the user before they approve.
/// </summary>
- /// <param name="requestId">The unique identifier for the login request.</param>
+ /// <param name="model">The request to describe.</param>
/// <returns>IActionResult.</returns>
- [HttpGet("mobile-login/request/{requestId}")]
+ [HttpPost("mobile-login/details")]
[Authorize]
- public async Task<IActionResult> GetMobileLoginRequest(string requestId)
+ public async Task<IActionResult> GetMobileLoginDetails([FromBody] V2Auth.MobileLoginRequestReference model)
{
await using var context = await dbContextFactory.CreateDbContextAsync();
- var loginRequest = await context.MobileLoginRequests.FirstOrDefaultAsync(r => r.Id == requestId);
-
- // Check if request exists and hasn't expired
- if (loginRequest == null || loginRequest.CreatedAt.AddMinutes(MobileLoginTimeoutMinutes) < timeProvider.UtcNow)
+ var loginRequest = await context.MobileLoginRequests.FirstOrDefaultAsync(r => r.Id == model.RequestId);
+ if (loginRequest == null || !MobileLoginRequestHelper.IsAwaitingApproval(loginRequest, timeProvider.UtcNow))
{
return NotFound(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 404));
}
- // Return only the public key
- return Ok(new { clientPublicKey = loginRequest.ClientPublicKey });
+ return Ok(new V2Auth.MobileLoginDetailsResponse
+ {
+ ClientPublicKey = loginRequest.ClientPublicKey,
+ IpAddress = loginRequest.ClientIpAddress,
+ Location = RequestClientInfo.DetermineCountry(),
+ ClientName = loginRequest.ClientName,
+ Browser = loginRequest.ClientBrowser,
+ OperatingSystem = loginRequest.ClientOperatingSystem,
+ CreatedAt = loginRequest.CreatedAt,
+ });
}
/// <summary>
- /// Submits a mobile login response from the mobile app.
+ /// Approves a mobile login request: the mobile app hands in the account unlock key, encrypted with the client's public key.
/// </summary>
/// <param name="model">The mobile login submit request model.</param>
/// <returns>IActionResult.</returns>
[HttpPost("mobile-login/submit")]
[Authorize]
- public async Task<IActionResult> SubmitMobileLogin([FromBody] MobileLoginSubmitRequest model)
+ public async Task<IActionResult> SubmitMobileLogin([FromBody] V2Auth.MobileLoginSubmitRequest model)
{
await using var context = await dbContextFactory.CreateDbContextAsync();
@@ -942,9 +950,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
}
var loginRequest = await context.MobileLoginRequests.FirstOrDefaultAsync(r => r.Id == model.RequestId);
-
- // Check if request exists and hasn't expired
- if (loginRequest == null || loginRequest.CreatedAt.AddMinutes(MobileLoginTimeoutMinutes) < timeProvider.UtcNow)
+ if (loginRequest == null || loginRequest.DeclinedAt != null || MobileLoginRequestHelper.IsApprovalWindowClosed(loginRequest, timeProvider.UtcNow))
{
return NotFound(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 404));
}
@@ -955,14 +961,51 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM
return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_ALREADY_FULFILLED, 400));
}
- // Update the login request with the encrypted key and user ID
- loginRequest.EncryptedDecryptionKey = model.EncryptedDecryptionKey;
+ // Store the answer in one transaction.
+ var fulfilledAt = timeProvider.UtcNow;
+ var mobileIpAddress = IpAddressUtility.GetAnonymizedIpFromContext(HttpContext, config.IpLoggingEnabled);
+ var updated = await context.MobileLoginRequests
+ .Where(r => r.Id == loginRequest.Id && r.FulfilledAt == null && r.DeclinedAt == null)
+ .ExecuteUpdateAsync(u => u.SetProperty(r => r.EncryptedUnlockKey, model.EncryptedUnlockKey).SetProperty(r => r.UserId, user.Id).SetProperty(r => r.FulfilledAt, fulfilledAt).SetProperty(r => r.MobileIpAddress, mobileIpAddress));
+ if (updated != 1)
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_ALREADY_FULFILLED, 400));
+ }
+
+ return Ok();
+ }
+
+ /// <summary>
+ /// Declines a mobile login request.
+ /// </summary>
+ /// <param name="model">The request to decline.</param>
+ /// <returns>IActionResult.</returns>
+ [HttpPost("mobile-login/decline")]
+ [Authorize]
+ public async Task<IActionResult> DeclineMobileLogin([FromBody] V2Auth.MobileLoginRequestReference model)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+
+ var user = await userManager.GetUserAsync(User);
+ if (user == null)
+ {
+ return Unauthorized(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.USER_NOT_FOUND, 401));
+ }
+
+ var loginRequest = await context.MobileLoginRequests.FirstOrDefaultAsync(r => r.Id == model.RequestId);
+ if (loginRequest == null || !MobileLoginRequestHelper.IsAwaitingApproval(loginRequest, timeProvider.UtcNow))
+ {
+ return NotFound(ApiErrorCodeHelper.CreateErrorResponse(ApiErrorCode.MOBILE_LOGIN_REQUEST_NOT_FOUND, 404));
+ }
+
+ loginRequest.ClientPublicKey = string.Empty;
loginRequest.UserId = user.Id;
- loginRequest.FulfilledAt = timeProvider.UtcNow;
+ loginRequest.DeclinedAt = timeProvider.UtcNow;
loginRequest.MobileIpAddress = IpAddressUtility.GetAnonymizedIpFromContext(HttpContext, config.IpLoggingEnabled);
-
await context.SaveChangesAsync();
+ await authLoggingService.LogAuthEventFailAsync(user.UserName!, AuthEventType.MobileLogin, AuthFailureReason.MobileLoginDeclined);
+
return Ok();
}
diff --git a/apps/server/AliasVault.Api/Helpers/MobileLoginRequestHelper.cs b/apps/server/AliasVault.Api/Helpers/MobileLoginRequestHelper.cs
new file mode 100644
index 000000000..bc4c0142b
--- /dev/null
+++ b/apps/server/AliasVault.Api/Helpers/MobileLoginRequestHelper.cs
@@ -0,0 +1,92 @@
+//-----------------------------------------------------------------------
+// <copyright file="MobileLoginRequestHelper.cs" company="aliasvault">
+// Copyright (c) aliasvault. All rights reserved.
+// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace AliasVault.Api.Helpers;
+
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using System.Text.RegularExpressions;
+using AliasServerDb;
+
+/// <summary>
+/// Rules of the mobile login handshake that the endpoints share: the time windows, the poll secret and the client name.
+/// </summary>
+public static partial class MobileLoginRequestHelper
+{
+ /// <summary>
+ /// How long the mobile app may approve or decline a request after it was created. Clients show a 2 minute countdown.
+ /// </summary>
+ public static readonly TimeSpan ApprovalWindow = TimeSpan.FromMinutes(3);
+
+ /// <summary>
+ /// How long the initiating client may collect an approved request after the approval.
+ /// </summary>
+ public static readonly TimeSpan RetrievalWindow = TimeSpan.FromMinutes(1);
+
+ /// <summary>
+ /// JSON options the encrypted poll payload is written with.
+ /// </summary>
+ public static readonly JsonSerializerOptions PayloadJsonOptions = new(JsonSerializerDefaults.Web);
+
+ /// <summary>
+ /// Hashes a poll secret for storage.
+ /// </summary>
+ /// <param name="pollSecret">The poll secret as handed to the initiating client.</param>
+ /// <returns>Base64 SHA-256 hash of the secret.</returns>
+ public static string HashPollSecret(string pollSecret) => Convert.ToBase64String(SHA256.HashData(Encoding.UTF8.GetBytes(pollSecret)));
+
+ /// <summary>
+ /// Checks a presented poll secret against the stored hash in constant time.
+ /// </summary>
+ /// <param name="request">The mobile login request.</param>
+ /// <param name="pollSecret">The poll secret the caller presented.</param>
+ /// <returns>True when the secret belongs to the request.</returns>
+ public static bool IsPollSecretValid(MobileLoginRequest request, string? pollSecret)
+ {
+ if (string.IsNullOrEmpty(pollSecret) || string.IsNullOrEmpty(request.PollSecretHash))
+ {
+ return false;
+ }
+
+ return CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(HashPollSecret(pollSecret)), Encoding.UTF8.GetBytes(request.PollSecretHash));
+ }
+
+ /// <summary>
+ /// Whether the time to approve or decline the request has passed.
+ /// </summary>
+ /// <param name="request">The mobile login request.</param>
+ /// <param name="now">The current UTC time.</param>
+ /// <returns>True when the request can no longer be answered.</returns>
+ public static bool IsApprovalWindowClosed(MobileLoginRequest request, DateTime now) => request.CreatedAt.Add(ApprovalWindow) < now;
+
+ /// <summary>
+ /// Whether the time to collect an approved request has passed.
+ /// </summary>
+ /// <param name="request">The mobile login request.</param>
+ /// <param name="now">The current UTC time.</param>
+ /// <returns>True when the approval can no longer be collected.</returns>
+ public static bool IsRetrievalWindowClosed(MobileLoginRequest request, DateTime now) => request.FulfilledAt == null || request.FulfilledAt.Value.Add(RetrievalWindow) < now;
+
+ /// <summary>
+ /// Whether the request still waits for the mobile app: not answered yet and not expired.
+ /// </summary>
+ /// <param name="request">The mobile login request.</param>
+ /// <param name="now">The current UTC time.</param>
+ /// <returns>True when the mobile app may still approve or decline.</returns>
+ public static bool IsAwaitingApproval(MobileLoginRequest request, DateTime now) => request.FulfilledAt == null && request.DeclinedAt == null && !IsApprovalWindowClosed(request, now);
+
+ /// <summary>
+ /// Reduces the client header to something safe to show on the approval screen. The header is attacker-controlled free text.
+ /// </summary>
+ /// <param name="clientHeader">The raw X-AliasVault-Client header value.</param>
+ /// <returns>The header when it has the expected "{client}-{version}" shape, otherwise null.</returns>
+ public static string? SanitizeClientName(string? clientHeader) => clientHeader is not null && ClientNameRegex().IsMatch(clientHeader) ? clientHeader : null;
+
+ [GeneratedRegex(@"^[A-Za-z0-9][A-Za-z0-9._-]{0,49}$")]
+ private static partial Regex ClientNameRegex();
+}
diff --git a/core/client/src/auth/MobileLoginProtocol.ts b/core/client/src/auth/MobileLoginProtocol.ts
new file mode 100644
index 000000000..cbbdb1ce1
--- /dev/null
+++ b/core/client/src/auth/MobileLoginProtocol.ts
@@ -0,0 +1,89 @@
+import { bytesToBase64 } from '../utilities/Base64';
+
+/**
+ * What the QR code of a mobile login request carries.
+ */
+export type MobileLoginQrPayload = {
+ requestId: string;
+ publicKeyHash: string;
+}
+
+/**
+ * Client-side rules of the mobile login (QR unlock) handshake, shared by the client that shows the QR code and the
+ * mobile app that scans it.
+ */
+export class MobileLoginProtocol {
+ public static readonly QR_PREFIX = 'aliasvault://open/mobile-unlock/';
+
+ public static readonly VERIFICATION_CODE_LENGTH = 2;
+
+ private static readonly VERIFICATION_CODE_CONTEXT = 'AliasVault.MobileLogin.VerificationCode.v1:';
+
+ private static readonly REQUEST_ID_PATTERN = /^[0-9a-f]{32}$/;
+
+ private static readonly PUBLIC_KEY_HASH_PATTERN = /^[A-Za-z0-9_-]{43}$/;
+
+ /**
+ * SHA-256 hash of the public key JWK string, base64url encoded without padding (43 characters).
+ */
+ public static async computePublicKeyHash(publicKeyJwk: string): Promise<string> {
+ const digest = await MobileLoginProtocol.sha256(publicKeyJwk);
+ return bytesToBase64(digest).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
+ }
+
+ /**
+ * The verification code for a public key: a fixed number of digits, zero padded.
+ */
+ public static async computeVerificationCode(publicKeyJwk: string): Promise<string> {
+ const digest = await MobileLoginProtocol.sha256(MobileLoginProtocol.VERIFICATION_CODE_CONTEXT + publicKeyJwk);
+ const value = new DataView(digest.buffer, digest.byteOffset, 4).getUint32(0, false);
+ const modulus = 10 ** MobileLoginProtocol.VERIFICATION_CODE_LENGTH;
+ return (value % modulus).toString().padStart(MobileLoginProtocol.VERIFICATION_CODE_LENGTH, '0');
+ }
+
+ /**
+ * Whether the public key is the one the QR code was made for.
+ */
+ public static async isExpectedPublicKey(publicKeyJwk: string, expectedPublicKeyHash: string): Promise<boolean> {
+ if (!MobileLoginProtocol.PUBLIC_KEY_HASH_PATTERN.test(expectedPublicKeyHash)) {
+ return false;
+ }
+ return await MobileLoginProtocol.computePublicKeyHash(publicKeyJwk) === expectedPublicKeyHash;
+ }
+
+ /**
+ * The text to put in the QR code.
+ */
+ public static buildQrPayload(requestId: string, publicKeyHash: string): string {
+ return `${MobileLoginProtocol.QR_PREFIX}${requestId}?pk=${publicKeyHash}`;
+ }
+
+ /**
+ * Parse scanned QR code text. Returns null unless it is a complete mobile login payload: the public key hash is
+ * mandatory, a QR code without it is never accepted.
+ */
+ public static parseQrPayload(data: string): MobileLoginQrPayload | null {
+ if (!data.startsWith(MobileLoginProtocol.QR_PREFIX)) {
+ return null;
+ }
+
+ const [requestId, query, ...rest] = data.substring(MobileLoginProtocol.QR_PREFIX.length).split('?');
+ if (rest.length > 0 || !query || !MobileLoginProtocol.REQUEST_ID_PATTERN.test(requestId)) {
+ return null;
+ }
+
+ const publicKeyHash = query.split('&').find(part => part.startsWith('pk='))?.substring(3) ?? '';
+ if (!MobileLoginProtocol.PUBLIC_KEY_HASH_PATTERN.test(publicKeyHash)) {
+ return null;
+ }
+
+ return { requestId, publicKeyHash };
+ }
+
+ /**
+ * SHA-256 of a UTF-8 string.
+ */
+ private static async sha256(data: string): Promise<Uint8Array> {
+ return new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(data)));
+ }
+}
diff --git a/core/models/src/webapi/MobileLogin.ts b/core/models/src/webapi/MobileLogin.ts
index a0c0c0b11..a2e309b4d 100644
--- a/core/models/src/webapi/MobileLogin.ts
+++ b/core/models/src/webapi/MobileLogin.ts
@@ -6,28 +6,73 @@ export type MobileLoginInitiateRequest = {
}
/**
- * Mobile login initiate response type.
+ * Mobile login initiate response type. The request id goes into the QR code, the poll secret stays with the initiating client.
*/
export type MobileLoginInitiateResponse = {
requestId: string;
+ pollSecret: string;
}
/**
- * Mobile login submit request type.
+ * Mobile login poll request type.
*/
-export type MobileLoginSubmitRequest = {
+export type MobileLoginPollRequest = {
requestId: string;
- encryptedDecryptionKey: string;
+ pollSecret: string;
}
/**
- * Mobile login poll response type.
+ * State of a mobile login request as seen by the polling client.
+ */
+export type MobileLoginStatus = 'Pending' | 'Approved' | 'Declined';
+
+/**
+ * Mobile login poll response type. The encrypted fields are only set when the status is Approved.
*/
export type MobileLoginPollResponse = {
- fulfilled: boolean;
+ status: MobileLoginStatus;
encryptedSymmetricKey: string | null;
- encryptedToken: string | null;
- encryptedRefreshToken: string | null;
- encryptedDecryptionKey: string | null;
- encryptedUsername: string | null;
+ encryptedPayload: string | null;
+ encryptedUnlockKey: string | null;
+}
+
+/**
+ * Decrypted content of `encryptedPayload` in the poll response.
+ */
+export type MobileLoginPayload = {
+ username: string;
+ token: string;
+ refreshToken: string;
+ salt: string;
+ encryptionType: string;
+ encryptionSettings: string;
+}
+
+/**
+ * Request type of the mobile app calls that only name a request (details and decline).
+ */
+export type MobileLoginRequestReference = {
+ requestId: string;
+}
+
+/**
+ * Mobile login details response type: what the mobile app shows before the user approves.
+ * Everything except the public key is reported by the requesting client and is context, not proof.
+ */
+export type MobileLoginDetailsResponse = {
+ clientPublicKey: string;
+ ipAddress: string | null;
+ location: string | null;
+ clientName: string | null;
+ browser: string | null;
+ operatingSystem: string | null;
+ createdAt: string;
+}
+
+/**
+ * Mobile login submit request type.
+ */
+export type MobileLoginSubmitRequest = {
+ requestId: string;
+ encryptedUnlockKey: string;
}