π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Prune server authentication comments
Manav Rathif2be9bfd472c
diff --git a/server/ente/billing.go b/server/ente/billing.goindex 98b09f46dd..0292d53c81 100644--- a/server/ente/billing.go+++ b/server/ente/billing.go@@ -96,7 +96,8 @@ type Subscription struct {UserID int64 `json:"userID"`ProductID string `json:"productID"`Storage int64 `json:"storage"`- // LinkedPurchaseToken on PlayStore , OriginalTransactionID on AppStore and SubscriptionID on Stripe+ // Play Store linked purchase token, App Store original transaction ID, or+ // Stripe subscription ID.OriginalTransactionID string `json:"originalTransactionID"`ExpiryTime int64 `json:"expiryTime"`UpgradedAt int64 `json:"upgradedAt,omitempty"`diff --git a/server/ente/family.go b/server/ente/family.goindex cb8a3e5dd5..e64af5b143 100644--- a/server/ente/family.go+++ b/server/ente/family.go@@ -43,11 +43,11 @@ type FamilyMember struct {Status MemberStatus `json:"status" binding:"required"`StorageLimit *int64 `json:"storageLimit" binding:"omitempty"`UserID *int64 `json:"userID"`- // This information should not be sent back in the response if the membership status is `INVITED`+ // Do not expose usage for invited members.Usage int64 `json:"usage"`IsAdmin bool `json:"isAdmin"`- MemberUserID int64 `json:"-"` // for internal use only, ignore from json response- AdminUserID int64 `json:"-"` // for internal use only, ignore from json response+ MemberUserID int64 `json:"-"`+ AdminUserID int64 `json:"-"`}type ModifyMemberStorage struct {@@ -57,7 +57,7 @@ type ModifyMemberStorage struct {type FamilyMemberResponse struct {Members []FamilyMember `json:"members" binding:"required"`- // Family admin subscription storage capacity. This excludes add-on and any other bonus storage+ // The family admin's plan storage, excluding bonuses and add-ons.Storage int64 `json:"storage" binding:"required"`ExpiryTime int64 `json:"expiryTime" binding:"required"`@@ -66,8 +66,6 @@ type FamilyMemberResponse struct {type UserUsageWithSubData struct {UserID int64- // StorageConsumed by the current member.- // This information should not be sent back in the response if the membership status is `INVITED`StorageConsumed int64ExpiryTime int64Storage int64diff --git a/server/ente/legacy_kit.go b/server/ente/legacy_kit.goindex f26fdad0d5..8429d05cc5 100644--- a/server/ente/legacy_kit.go+++ b/server/ente/legacy_kit.go@@ -59,9 +59,7 @@ type LegacyKitRecoverySession struct {ID uuid.UUID `json:"id"`KitID uuid.UUID `json:"kitID"`Status LegacyKitRecoveryStatus `json:"status"`- // Remaining microseconds until recovery becomes ready. This follows the- // existing emergency legacy recovery API shape, where waitTill is a- // duration in API responses, not an epoch timestamp.+ // Remaining microseconds until recovery is ready, not an epoch timestamp.WaitTill int64 `json:"waitTill"`CreatedAt int64 `json:"createdAt"`}@@ -93,7 +91,6 @@ type LegacyKitRecoveryInitiator struct {// reconstruct the kit secret. This is an audit hint, not an authorization// primitive.UsedPartIndexes []int `json:"usedPartIndexes,omitempty"`- // Server-captured request metadata for the successful recovery open call.IP string `json:"ip"`UserAgent string `json:"userAgent"`}diff --git a/server/ente/passkey.go b/server/ente/passkey.goindex 7a4e69908a..43c40dd5d9 100644--- a/server/ente/passkey.go+++ b/server/ente/passkey.go@@ -14,16 +14,12 @@ var MaxPasskeys = 10type SetPasskeyRecoveryRequest struct {Secret string `json:"secret" binding:"required"`- // The UserSecretCipher has SkipSecret encrypted with the user's recoveryKey- // If the user sends the correct UserSecretCipher, we can be sure that the user has the recoveryKey,- // and we can allow the user to recover their MFA.+ // SkipSecret encrypted with the user's recovery key.UserSecretCipher string `json:"userSecretCipher" binding:"required"`UserSecretNonce string `json:"userSecretNonce" binding:"required"`}type TwoFactorRecoveryStatus struct {- // AllowAdminReset is a boolean that determines if the admin can reset the user's MFA.- // If true, in the event that the user loses their MFA device, the admin can reset the user's MFA.AllowAdminReset bool `json:"allowAdminReset" binding:"required"`IsPasskeyRecoveryEnabled bool `json:"isPasskeyRecoveryEnabled" binding:"required"`}diff --git a/server/ente/user.go b/server/ente/user.goindex da33bd3c30..f371b5de3d 100644--- a/server/ente/user.go+++ b/server/ente/user.go@@ -46,8 +46,6 @@ type EmailVerificationResponse struct {Subscription Subscription `json:"subscription"`}-// EmailAuthorizationResponse represents the response after user has verified his email,-// if two factor enabled just `TwoFactorSessionID` is sent else the keyAttributes and encryptedTokentype EmailAuthorizationResponse struct {ID int64 `json:"id"`KeyAttributes *KeyAttributes `json:"keyAttributes,omitempty"`@@ -60,8 +58,7 @@ type EmailAuthorizationResponse struct {// This is to ensure older clients keep using passkey flow when both are set. We can remove// This field once the clients starts surface both options for performing 2faTwoFactorSessionIDV2 string `json:"twoFactorSessionIDV2"`- // SrpM2 is sent only if the user is logging via SRP- // SrpM2 is the SRP M2 value aka the proof that the server has the verifier+ // SRP server proof, set only for SRP logins.SrpM2 *string `json:"srpM2,omitempty"`}diff --git a/server/pkg/controller/appstore.go b/server/pkg/controller/appstore.goindex 5a647761c0..95ed56f207 100644--- a/server/pkg/controller/appstore.go+++ b/server/pkg/controller/appstore.go@@ -70,8 +70,6 @@ func isEnteSandboxEmail(userEmail string) bool {strings.HasSuffix(normalizedEmail, "@ente.com")}-// validateSandboxRequest checks if the request is from sandbox environment.-// If sandbox, it sends a Discord alert and returns an error for non-whitelisted users.func (c *AppStoreController) validateSandboxRequest(ctx context.Context, environment string, userID int64, sandboxContext string) error {if environment != "Sandbox" {return nildiff --git a/server/pkg/controller/billing.go b/server/pkg/controller/billing.goindex 36e6866793..062d3b07a9 100644--- a/server/pkg/controller/billing.go+++ b/server/pkg/controller/billing.go@@ -79,8 +79,6 @@ func (c *BillingController) GetPlansV2(countryCode string, stripeAccountCountryreturn result}-// GetStripeAccountCountry returns the stripe account country the user's existing plan is from-// if he doesn't have a stripe subscription then ente.DefaultStripeAccountCountry is returnedfunc (c *BillingController) GetStripeAccountCountry(userID int64) (ente.StripeAccountCountry, error) {subscription, err := c.BillingRepo.GetUserSubscription(userID)if err != nil {@@ -216,8 +214,6 @@ func (c *BillingController) VerifySubscription(hasChangedProductID := currentSubscription.ProductID != newSubscription.ProductIDisOutdatedPurchase := !isUpgradingFromFreePlan && !hasChangedProductID && newSubscriptionExpiresSoonerif isOutdatedPurchase {- // User is reporting an outdated purchase that was already verified- // no-oplog.Info("Outdated purchase reported")return currentSubscription, nil}@@ -367,7 +363,6 @@ func (c *BillingController) HandleAccountDeletion(ctx context.Context, userID inif err != nil {return false, stacktrace.Propagate(err, "")}- // on customer deletion, subscription is automatically cancelledisCancelled = true} else if subscription.PaymentProvider == ente.AppStore || subscription.PaymentProvider == ente.PlayStore {logger.Info("Updating originalTransactionID for app/playStore provider")@@ -430,8 +425,7 @@ func (c *BillingController) getPlanForCountry(s ente.Subscription, countryCode sreturn ente.BillingPlan{Period: ente.PeriodYear}, nil}- // If request has a different `countryCode` because the user is traveling, and we're unable to find a plan for that country,- // fallback to the previous logic for finding a plan.+ // The request country may differ from the subscription country while traveling.plan, _, err := c.getPlanWithCountry(s)if err != nil {return ente.BillingPlan{}, stacktrace.Propagate(err, "")diff --git a/server/pkg/controller/playstore.go b/server/pkg/controller/playstore.goindex c0072b4739..285abe311d 100644--- a/server/pkg/controller/playstore.go+++ b/server/pkg/controller/playstore.go@@ -44,9 +44,7 @@ func NewPlayStoreController(if err != nil {log.Fatal(err)}- // We don't do nil checks for playStoreClient in the definitions of these- // methods - if they're getting called, that means we're not in a test- // environment and so playStoreClient really should've been there.+ // Callers assume the client is configured outside local and test environments.return &PlayStoreController{PlayStoreClient: playStoreClient,@@ -65,7 +63,6 @@ func newPlayStoreClient() (*playstore.Client, error) {return nil, stacktrace.Propagate(err, "")}if playStoreCredentialsFile == "" {- // Can happen when running locallyreturn nil, nil}diff --git a/server/pkg/controller/stripe.go b/server/pkg/controller/stripe.goindex de6ddcebce..96556b085b 100644--- a/server/pkg/controller/stripe.go+++ b/server/pkg/controller/stripe.go@@ -66,7 +66,6 @@ func (c *StripeController) GetCheckoutSession(productID string, userID int64, re}subscription, err := c.BillingRepo.GetUserSubscription(userID)if err != nil {- // error sql.ErrNoRows not possible as user must at least have a free subscriptionreturn "", stacktrace.Propagate(err, "")}hasActivePaidSubscription := billing.IsActivePaidPlan(subscription)@@ -163,9 +162,6 @@ func (c *StripeController) HandleINNotification(payload []byte, header string) e}func (c *StripeController) handleWebhookEvent(event stripe.Event, country ente.StripeAccountCountry) error {- // The event body would already have been logged by the upper layers by the- // time we get here, so we can only handle the events that we care about. In- // case we receive an unexpected event, we do log an error though.handler := c.findHandlerForEvent(event)if handler == nil {log.Error("Received an unexpected webhook from stripe:", event.Type)@@ -176,11 +172,8 @@ func (c *StripeController) handleWebhookEvent(event stripe.Event, country ente.Sreturn stacktrace.Propagate(err, "")}if eventLog.UserID == 0 {- // Do not try to log if we do not have an associated user. This can- // happen, e.g. with out of order webhooks.- // Or in case of offer application, where events are logged by the Storage Bonus Repo- //- // See: Ignore webhooks received before user has been created+ // Out-of-order events may have no user. Offer events are logged by+ // StorageBonusRepo instead.return nil}err = c.BillingRepo.LogStripePush(eventLog)@@ -265,18 +258,12 @@ func (c *StripeController) handleCheckoutSessionCompleted(event stripe.Event, coreturn ente.StripeEventLog{}, nil}-// Stripe fires this when a subscription starts or changes. For example,-// renewing a subscription, adding a coupon, applying a discount, adding an-// invoice item, and changing plans all trigger this event. In our case, we use-// this only to track plan changes and renewal failures resulting in-// subscriptions going past due.func (c *StripeController) handleCustomerSubscriptionUpdated(event stripe.Event, country ente.StripeAccountCountry) (ente.StripeEventLog, error) {var stripeSubscription stripe.Subscriptionjson.Unmarshal(event.Data.Raw, &stripeSubscription)currentSubscription, err := c.BillingRepo.GetSubscriptionForTransaction(stripeSubscription.ID, ente.Stripe)if err != nil {if errors.Is(err, sql.ErrNoRows) {- // See: Ignore webhooks received before user has been createdlog.Warn("Webhook is reporting an event for un-verified subscription stripeSubscriptionID:", stripeSubscription.ID)return ente.StripeEventLog{}, nil}@@ -287,9 +274,7 @@ func (c *StripeController) handleCustomerSubscriptionUpdated(event stripe.Event,if err != nil {return ente.StripeEventLog{}, stacktrace.Propagate(err, "")}- // If the customer has changed the plan, we update state in the database. If- // the plan has not changed, we will ignore this webhook and rely on other- // events to update the state+ // Other events update subscription state when the product is unchanged.if currentSubscription.ProductID != newSubscription.ProductID {c.BillingRepo.ReplaceSubscription(currentSubscription.ID, newSubscription)}@@ -321,7 +306,6 @@ func (c *StripeController) handleInvoicePaid(event stripe.Event, country ente.StcurrentSubscription, err := c.BillingRepo.GetSubscriptionForTransaction(stripeSubscriptionID, ente.Stripe)if err != nil {if errors.Is(err, sql.ErrNoRows) {- // See: Ignore webhooks received before user has been createdif invoice.BillingReason != stripe.InvoiceBillingReasonSubscriptionCreate {c.notifyIgnoredPaidStripeWebhook(event.Type, country, stripeSubscriptionID, invoice.Customer.ID)}@@ -341,7 +325,6 @@ func (c *StripeController) handleInvoicePaid(event stripe.Event, country ente.StnewExpiryTime := stripeSubscription.CurrentPeriodEnd * 1000 * 1000if currentSubscription.ExpiryTime == newExpiryTime {- //outdated invoicelog.Warn("Webhook is reporting an outdated purchase that was already verified stripeSubscriptionID:", stripeSubscription.ID)return ente.StripeEventLog{UserID: userID, StripeSubscription: *stripeSubscription, Event: event}, nil}@@ -353,17 +336,13 @@ func (c *StripeController) handleInvoicePaid(event stripe.Event, country ente.Streturn ente.StripeEventLog{UserID: userID, StripeSubscription: *stripeSubscription, Event: event}, nil}-// Event used to handle failures for payment methods whose subscription updates-// use allow_incomplete (currently SEPA and UPI). Other subscription update-// modes are handled synchronously in UpdateSubscription and-// customer.subscription.updated.+// SEPA and UPI failures are handled here because their updates use+// allow_incomplete.func (c *StripeController) handlePaymentIntentFailed(event stripe.Event, country ente.StripeAccountCountry) (ente.StripeEventLog, error) {var paymentIntent stripe.PaymentIntentjson.Unmarshal(event.Data.Raw, &paymentIntent)paymentMethodType := getPaymentIntentErrorPaymentMethodType(paymentIntent)if !usesAllowIncompleteSubscriptionUpdate(paymentMethodType) {- // Ignore events for payment methods that are already handled- // synchronously.log.Info("Ignoring payment intent failed event for payment method handled synchronously")return ente.StripeEventLog{}, nil}@@ -379,7 +358,6 @@ func (c *StripeController) handlePaymentIntentFailed(event stripe.Event, countrycurrentSubscription, err := c.BillingRepo.GetSubscriptionForTransaction(stripeSubscriptionID, ente.Stripe)if err != nil {if errors.Is(err, sql.ErrNoRows) {- // See: Ignore webhooks received before user has been createdlog.Warn("Webhook is reporting an event for un-verified subscription stripeSubscriptionID:", stripeSubscriptionID)}return ente.StripeEventLog{}, stacktrace.Propagate(err, "")@@ -397,15 +375,10 @@ func (c *StripeController) handlePaymentIntentFailed(event stripe.Event, country}productID := stripeSubscription.Items.Data[0].Price.ID- // If the current subscription is not the same as the one in the webhook,- // then ignoreif currentSubscription.ProductID != productID {- // no-oplog.Warn("Webhook is reporting un-verified subscription update", stripeSubscription.ID, "invoiceID:", invoiceID)return ente.StripeEventLog{UserID: userID, StripeSubscription: *stripeSubscription, Event: event}, nil}- // If the current subscription is the same as the one in the webhook, then- // we need to expire the subscription, and send an email to the user.newExpiryTime := time.Now().UnixMicro()err = c.BillingRepo.UpdateSubscriptionExpiryTime(currentSubscription.ID, newExpiryTime)@@ -514,7 +487,6 @@ func (c *StripeController) UpdateSubscription(stripeID string, userID int64) (enfunc (c *StripeController) UpdateSubscriptionCancellationStatus(userID int64, shouldCancel bool) (ente.Subscription, error) {subscription, err := c.BillingRepo.GetUserSubscription(userID)if err != nil {- // error sql.ErrNoRows not possible as user must at least have a free subscriptionreturn ente.Subscription{}, stacktrace.Propagate(err, "")}if subscription.PaymentProvider != ente.Stripe {@@ -522,7 +494,6 @@ func (c *StripeController) UpdateSubscriptionCancellationStatus(userID int64, sh}if subscription.Attributes.IsCancelled == shouldCancel {- // no-opreturn subscription, nil}diff --git a/server/pkg/controller/user/srp.go b/server/pkg/controller/user/srp.goindex 270afa1da2..46cc3563f8 100644--- a/server/pkg/controller/user/srp.go+++ b/server/pkg/controller/user/srp.go@@ -22,10 +22,8 @@ import (const (Srp4096Params = 4096- // MaxUnverifiedSessionInAnHour is the number of unverified sessions in the last hourMaxUnverifiedSessionInAnHour = 10- // FakeVerifier is a realistic-looking base64 verifier used for non-existent users- // to prevent timing attacks and user enumeration+ // Used for nonexistent users to preserve SRP timing and prevent enumeration.FakeVerifier = "RNYLOgdzKsbhRWN8OoD05kNpfbqb9uASHYpaLrYLYVemCV0pf4fBgo+25jeu8SaVMQhlkyIF2BgGXX4uzy8Pmwq1ocqt8DsGk0DrlOE1AV9ogaY3myoTjXTQG5dU/hTywylKJYdpWSEyzMMLbWcuO8ldS6uzYXqK+jbfEDDj8k4PqLx1715BPgigNydCbD7/VtwaMhQ8MEygiW/2PbieeqUzuCqEWfwu0uytPM9LiuHH7DT3k2fELFOoPWs3KQAhk6rmM17JOLm8Qvt+xGU6nJZKzTNPxw9o4H4FvlGmsEYUdTP+WPdWpzcton6BowCXKN9G3hZx10OUzBuePHFNKjDlaSLpJXVclLWmza6aDBpjKahayW2UvdQw1tSonyFUjJOanocrPEoHthHUjUGXkeRqcaU4CV9KLQFaHqnHTYc9uJKuYl/tcYoWXuHrZ0cFYRpc6qf/gBCuuwkhTXXsJxTlepe5x0gqgQb7mD5y+dvINks/gpO/3x4T4RkQcyoonsOZv2uLIBr3D6Ede9/aJstIkMh3dTEpDWdw8tEaO7ZjqEwKXVA+/fquJ7P8B3fcIvPy8UZOpwAYtWSPh3OYzijG7WFXu+ajPBqkVI1OBSCYOlTQlPXyrv7myiD8/FXJep5IDPeuJsmGrLPJXBZjPKWR0ISBWol5KTYWE2EllYQ=")@@ -165,8 +163,6 @@ func (c *UserController) VerifySRPSession(context *gin.Context, req ente.VerifySsrpAuthEntity, err := c.UserAuthRepo.GetSRPAuthEntityBySRPUserID(context, req.SRPUserID)if err != nil {if errors.Is(err, sql.ErrNoRows) {- // For non-existent users, try to verify against the fake session- // This will always fail but maintains consistent timing and error responses_, verifyErr := c.verifySRPSession(context, FakeVerifier, req.SessionID, req.SRPM1)return nil, verifyErr}@@ -261,20 +257,18 @@ func (c *UserController) verifySRPSession(ctx context.Context,}srpSession, err := c.UserAuthRepo.GetSrpSessionEntity(ctx, sessionID)if err != nil {- // Session not found - return invalid password to avoid revealing non-existence+ // Do not reveal whether the session exists.if errors.Is(err, sql.ErrNoRows) {- // Add small delay to simulate processing+ // Match normal verification timing.time.Sleep(time.Duration(10+mathRand.Intn(20)) * time.Millisecond)return nil, stacktrace.Propagate(ente.ErrInvalidPassword, "session not found")}return nil, stacktrace.Propagate(err, "")}- // Handle fake sessions - always fail with invalid passwordif srpSession.IsFake {- // Simulate realistic timing for fake session verification+ // Match real-session timing and attempt bookkeeping.time.Sleep(time.Duration(20+mathRand.Intn(30)) * time.Millisecond)- // Increment attempt count for fake sessions too_ = c.UserAuthRepo.IncrementSrpSessionAttemptCount(ctx, sessionID)return nil, stacktrace.Propagate(ente.ErrInvalidPassword, "fake session verification")}@@ -344,10 +338,8 @@ func fSrpAttributes(email string, hashKey []byte) (*ente.GetSRPAttributesResponskekSaltMaker.Write(hashKey)kekSaltHash := kekSaltMaker.Sum(nil)- // Generate UUIDv4 from first 16 bytes of hashuuidBytes := make([]byte, 16)copy(uuidBytes, emailHash[:16])- // Set version bits (4) and variant bits (RFC 4122)uuidBytes[6] = (uuidBytes[6] & 0x0f) | 0x40 // Version 4uuidBytes[8] = (uuidBytes[8] & 0x3f) | 0x80 // Variant RFC 4122uuidStr := fmt.Sprintf("%08x-%04x-%04x-%04x-%012x",@@ -386,27 +378,24 @@ func (c *UserController) fCreateSession(srpUserID string, srpA string) (*ente.Crreturn nil, ente.NewBadRequestWithMessage("Invalid length for srpA")}- // Simulate realistic timing with variable delay (30-80ms)- // This matches the timing variance of real SRP operations+ // Match the timing variance of a real SRP exchange.baseDelay := 30variableDelay := mathRand.Intn(50)time.Sleep(time.Duration(baseDelay+variableDelay) * time.Millisecond)- // Generate realistic fake SRP data- serverSecret := make([]byte, 64) // Same size as real srp.GenKey()+ // Match real SRP key and response sizes.+ serverSecret := make([]byte, 64)rand.Read(serverSecret)- // Generate fake SRP B value (512 bytes like real)srpBBytes := make([]byte, 512)rand.Read(srpBBytes)- // Parse srpUserID as UUIDuserUUID, err := uuid.Parse(srpUserID)if err != nil {return nil, stacktrace.Propagate(err, "failed to parse srpUserID")}- // Store the fake session in the database (adds natural DB timing variance)+ // Persist fake sessions so verification follows the normal database path.sessionID, err := c.UserAuthRepo.AddFakeSRPSession(userUUID, convertBytesToString(serverSecret), srpA)if err != nil {// If storage fails, still return a response to avoid revealing system errorsdiff --git a/server/pkg/controller/user/twofactor.go b/server/pkg/controller/user/twofactor.goindex 042d53e09c..0b6d49ad01 100644--- a/server/pkg/controller/user/twofactor.go+++ b/server/pkg/controller/user/twofactor.go@@ -133,7 +133,6 @@ func (c *UserController) VerifyTwoFactor(context *gin.Context, sessionID string,return ente.TwoFactorAuthorizationResponse{}, stacktrace.Propagate(ente.ErrIncorrectTOTP, "")}- // Try to record OTP atomically - this will fail if already usedhashData := fmt.Sprintf("%d:%s", userID, otp)hash := sha256.Sum256([]byte(hashData))otpHash := hex.EncodeToString(hash[:])@@ -143,7 +142,6 @@ func (c *UserController) VerifyTwoFactor(context *gin.Context, sessionID string,log.WithError(err).Error("Failed to record used OTP code")// Continue anyway to not break authentication} else if !wasNew {- // Code was already used - replay attackmsg := fmt.Sprintf("Replay attack detected for userID: %d - OTP code reused", userID)log.Warn(msg)go c.DiscordController.NotifyPotentialAbuse(msg)diff --git a/server/pkg/controller/user/user_details.go b/server/pkg/controller/user/user_details.goindex 95cf6fc3d0..5938ea3b6d 100644--- a/server/pkg/controller/user/user_details.go+++ b/server/pkg/controller/user/user_details.go@@ -145,7 +145,6 @@ func (c *UserController) GetDetailsV2(ctx *gin.Context, userID int64, fetchMemorresult.SharedCollectionsCount = &sharedCollectionCount}if lockerUsage != nil {- // reduce the locker usage from user's usage for surfacing on photos app.for _, userLockerUsage := range lockerUsage.Users {if userLockerUsage.UserID == userID {result.Usage -= userLockerUsage.Usage@@ -161,7 +160,6 @@ func (c *UserController) GetDetailsV2(ctx *gin.Context, userID int64, fetchMemor}result.FamilyData = familyData}- // For Locker app, include family usage dataif app == ente.Locker {result.LockerFamilyUsage = &details.LockerFamilyUsage{FamilyFileCount: lockerUsage.TotalFileCount,diff --git a/server/pkg/controller/user/userauth.go b/server/pkg/controller/user/userauth.goindex 1ec1a4d2dd..877abac8c1 100644--- a/server/pkg/controller/user/userauth.go+++ b/server/pkg/controller/user/userauth.go@@ -133,7 +133,6 @@ func (c *UserController) SendEmailOTT(context *gin.Context, email string, purposif err != nil {return stacktrace.Propagate(err, "")}- // for hard-coded ott, adding same OTT in db can throw errorhasHardcodedOTT := falseif purpose != ente.ChangeEmailOTTPurpose {hardCodedOTT := hardcodedOTTForEmail(c.HardCodedOTT, email)@@ -145,8 +144,8 @@ func (c *UserController) SendEmailOTT(context *gin.Context, email string, purpos}err = c.UserAuthRepo.AddOTT(emailHash, app, ott, time.Microseconds()+OTTValidityDurationInMicroSeconds)+ // Reused hard-coded OTTs may violate the database uniqueness check.if !hasHardcodedOTT {- // ignore error for AddOTT for hardcode OTT. This is to avoid error when unique OTT check fails at db layerif err != nil {return stacktrace.Propagate(err, "")}@@ -199,7 +198,6 @@ func (c *UserController) validateSendOTT(ctx *gin.Context, email string, purposedisclosureErr = stacktrace.Propagate(ente.ErrUserSignupIncomplete, "user has not completed sign up process")}}- // If there is no state-disclosing error, allow the OTT request.if disclosureErr == nil {return true, nil}@@ -228,8 +226,7 @@ func (c *UserController) shouldSwallowSendOTTDisclosureError(ctx *gin.Context) breturn true}-// getSignUpState returns the signup state for an email.-// Signup is complete only when both email and key attributes exist.+// Signup requires both an account row and key attributes.func (c *UserController) getSignUpState(email string) (signUpState, error) {userID, err := c.UserRepo.GetUserIDWithEmailUnrestricted(email)if err != nil && errors.Is(err, sql.ErrNoRows) {diff --git a/server/pkg/repo/billing.go b/server/pkg/repo/billing.goindex 801c47b481..4792f6afaf 100644--- a/server/pkg/repo/billing.go+++ b/server/pkg/repo/billing.go@@ -51,9 +51,8 @@ func (repo *BillingRepository) GetSubscriptionForTransaction(transactionID strinreturn s, stacktrace.Propagate(err, "")}-// UpdateTransactionIDOnDeletion just append `userID:` before original transaction id on account deletion.-// This is to ensure that any subscription update isn't accidently applied to the deleted account and-// if user want to use same subscription in different ente account, they should be able to do that.+// Prefix the transaction ID so provider updates cannot reach the deleted+// account. The original ID can then be linked to another account.func (repo *BillingRepository) UpdateTransactionIDOnDeletion(userID int64) error {_, err := repo.DB.Query(`update subscriptions SET original_transaction_id = user_id || ':' || original_transaction_id where original_transaction_id is not NULL and user_id= $1`, userID)return stacktrace.Propagate(err, "")diff --git a/server/pkg/repo/family.go b/server/pkg/repo/family.goindex e4435b03d5..523e784132 100644--- a/server/pkg/repo/family.go+++ b/server/pkg/repo/family.go@@ -81,8 +81,7 @@ func (repo *FamilyRepository) AddMemberInvite(ctx context.Context, adminID int64if adminID == memberID {return "", stacktrace.Propagate(errors.New("memberID and adminID can not be same"), "")}- // on conflict, we should not change the status from 'ACCEPTED' to `INVITED`.- // Also, the token should not be updated if the user is already in `INVITED` state.+ // Reinviting must not replace an invite token or reopen an accepted membership._, err := repo.DB.ExecContext(ctx, `INSERT INTO families(id, admin_id, member_id, status, token, storage_limit)VALUES($1, $2, $3, $4, $5, $6) ON CONFLICT (admin_id,member_id)DO UPDATE SET(status, token) = ($4, $5) WHERE NOT (families.status = ANY($7))`,@@ -90,8 +89,6 @@ func (repo *FamilyRepository) AddMemberInvite(ctx context.Context, adminID int64if err != nil {return "", stacktrace.Propagate(err, "")}- // separate query for fetch current token. Returning the same token in previous query was making query complex for- // the case when there's no DB update.var activeInviteToken stringerr = repo.DB.QueryRowContext(ctx, `SELECT token from families where admin_id = $1 and member_id = $2 and status = $3`,adminID, memberID, ente.INVITED).Scan(&activeInviteToken)diff --git a/server/pkg/repo/passkey/passkey.go b/server/pkg/repo/passkey/passkey.goindex 3d743527f7..4ef43198d2 100644--- a/server/pkg/repo/passkey/passkey.go+++ b/server/pkg/repo/passkey/passkey.go@@ -53,8 +53,7 @@ func (u *PasskeyUser) WebAuthnName() string {}func (u *PasskeyUser) WebAuthnDisplayName() string {- // Safari requires a display name to be set, otherwise it does not recognize- // security keys.+ // Safari ignores security keys unless a display name is set.return u.Email}@@ -68,7 +67,7 @@ func (u *PasskeyUser) WebAuthnCredentials() []webauthn.Credential {}func (u *PasskeyUser) WebAuthnIcon() string {- // this specification is deprecated but the interface requires it+ // The interface still requires the deprecated icon field.return ""}@@ -235,11 +234,8 @@ func (r *Repository) CreateBeginRegistrationData(user *ente.User) (options *protreturn}- // Set residentKey to "required" to ensure passkeys are created as discoverable credentials.- // This is necessary for Android to show third-party password managers (1Password, Bitwarden, etc.)- // in the Credential Manager UI during passkey registration. Without this, Android falls back to- // the legacy FIDO2 API which only offers Google Password Manager.- // This feature is currently enabled only for internal users with Ente email addresses.+ // Discoverable credentials let Android offer third-party password managers.+ // This is currently limited to Ente accounts.normalizedEmail := emailUtil.NormalizeEmail(user.Email)if strings.HasSuffix(normalizedEmail, "@ente.io") ||strings.HasSuffix(normalizedEmail, "@ente.com") {diff --git a/server/pkg/repo/user.go b/server/pkg/repo/user.goindex 955e830af8..1a0656777b 100644--- a/server/pkg/repo/user.go+++ b/server/pkg/repo/user.go@@ -48,9 +48,6 @@ func (repo *UserRepository) Get(userID int64) (ente.User, error) {if err != nil {return ente.User{}, stacktrace.Propagate(err, "")}- // We should not be calling Get user for a deleted account. The one valid- // use case is for internal/Admin APIs, where please we should instead be- // using GetUserByIDInternal.if strings.EqualFold(user.Hash, fmt.Sprintf(DELETED_EMAIL_HASH_FORMAT, userID)) {return user, stacktrace.Propagate(ente.ErrUserDeleted, "user account is deleted %d", userID)}@@ -62,7 +59,7 @@ func (repo *UserRepository) Get(userID int64) (ente.User, error) {return user, nil}-// GetUserByIDInternal returns a user indicated by the id. Strickly use this method for internal APIs only.+// Internal APIs only; unlike Get, this does not reject the deleted-account marker.func (repo *UserRepository) GetUserByIDInternal(id int64) (ente.User, error) {var user ente.Uservar encryptedEmail, nonce []byte@@ -79,7 +76,6 @@ func (repo *UserRepository) GetUserByIDInternal(id int64) (ente.User, error) {return user, nil}-// Return true if userId 1 doesn't exists in the system.func (repo *UserRepository) IsLikelySelfHosted() bool {var userOneExists boolif err := repo.DB.QueryRow(`SELECT EXISTS(SELECT 1 FROM users WHERE user_id = 1)`).Scan(&userOneExists); err != nil {@@ -89,8 +85,6 @@ func (repo *UserRepository) IsLikelySelfHosted() bool {return !userOneExists}-// Delete removes the email_hash and encrypted email information for the user. It replaces email_hash with placeholder value-// based on DELETED_EMAIL_HASH_FORMATfunc (repo *UserRepository) Delete(userID int64) error {return deleteUser(context.Background(), repo.DB, userID)}@@ -167,10 +161,8 @@ func (repo *UserRepository) GetAll(sinceTime int64, tillTime int64) ([]ente.Userreturn users, nil}-// GetActiveUsersByLastActivityBefore returns active users whose effective last-// activity is older than or equal to beforeTime. Effective activity is the-// latest of token activity, users.creation_time, authenticator_entity.updated_at,-// and collections.updation_time. Paging is done by user_id.+// Effective activity is the latest account creation, token, authenticator, or+// collection activity. Results page by user ID.func (repo *UserRepository) GetActiveUsersByLastActivityBefore(beforeTime int64, afterUserID int64, limit int) ([]UserInactivityCandidate, error) {rows, err := repo.DB.Query(`SELECT@@ -233,7 +225,6 @@ func (repo *UserRepository) GetActiveUsersByLastActivityBefore(beforeTime int64,return result, nil}-// GetLatestActivity returns the latest effective activity for a user.// The second return value is false when the user is no longer active.func (repo *UserRepository) GetLatestActivity(userID int64) (int64, bool, error) {var lastActivity int64@@ -343,9 +334,8 @@ func updateEmail(ctx context.Context, executor userMutationExecutor, userID int6return stacktrace.Propagate(err, "")}-// GetUserIDWithEmailUnrestricted returns the user ID associated with an email.-// It bypasses authenticated discovery limits and is only for trusted,-// non-disclosing flows. User-facing discovery must use controller.UserLookup.+// Trusted, non-disclosing flows only. User-facing discovery must use+// controller.UserLookup.func (repo *UserRepository) GetUserIDWithEmailUnrestricted(email string) (int64, error) {sanitizedEmail := emailUtil.NormalizeEmail(email)emailHash, err := crypto.GetHash(sanitizedEmail, repo.HashingKey)@@ -460,7 +450,6 @@ func (repo *UserRepository) GetUsersWithIndividualPlanWhoHaveExceededStorageQuot}if refBonusStorage, ok := refBonus[user.ID]; ok {addOnBonusStorage := addOnBonus[user.ID]- // cap usable ref bonus to the subscription storage + addOnBonusif refBonusStorage > (subStorage + addOnBonusStorage) {refBonusStorage = subStorage + addOnBonusStorage}