π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Update social wall flow
Anand Baburajan0125ff1011fd
diff --git a/rust/core/src/http.rs b/rust/core/src/http.rsindex 5e978369f9..0fcc05ba8b 100644--- a/rust/core/src/http.rs+++ b/rust/core/src/http.rs@@ -3,7 +3,6 @@use std::error::Error as StdError;use std::fmt::Write as _;use std::sync::RwLock;-#[cfg(not(target_arch = "wasm32"))]use std::time::Duration;use reqwest::header::{HeaderMap, HeaderName, HeaderValue, LOCATION};@@ -269,12 +268,14 @@ pub struct HttpClient {user_agent: Option<String>,client_package: Option<String>,client_version: Option<String>,+ timeout: Option<Duration>,}/// Bare HTTP client for presigned object-store transfers.#[derive(Clone)]pub struct ObjectStoreHttpClient {client: reqwest::Client,+ timeout: Option<Duration>,}impl HttpClient {@@ -296,14 +297,15 @@ impl HttpClient {None}});+ let timeout = config.timeout_secs.map(Duration::from_secs);#[cfg(not(target_arch = "wasm32"))]let mut builder = reqwest::Client::builder();#[cfg(target_arch = "wasm32")]let builder = reqwest::Client::builder();#[cfg(not(target_arch = "wasm32"))]- if let Some(timeout) = config.timeout_secs {- builder = builder.timeout(Duration::from_secs(timeout));+ if let Some(timeout) = timeout {+ builder = builder.timeout(timeout);}let client = builder.build().map_err(Error::from)?;@@ -312,8 +314,8 @@ impl HttpClient {#[cfg(target_arch = "wasm32")]let no_redirect_builder = reqwest::Client::builder();#[cfg(not(target_arch = "wasm32"))]- if let Some(timeout) = config.timeout_secs {- no_redirect_builder = no_redirect_builder.timeout(Duration::from_secs(timeout));+ if let Some(timeout) = timeout {+ no_redirect_builder = no_redirect_builder.timeout(timeout);}let no_redirect_client = no_redirect_builder.build().map_err(Error::from)?;@@ -327,6 +329,7 @@ impl HttpClient {user_agent: config.user_agent,client_package: config.client_package,client_version: config.client_version,+ timeout,})}@@ -340,6 +343,7 @@ impl HttpClient {pub fn object_store(&self) -> ObjectStoreHttpClient {ObjectStoreHttpClient {client: self.no_redirect_client.clone(),+ timeout: self.timeout,}}@@ -557,12 +561,14 @@ impl HttpClient {let mut current_url = self.parse_url(url)?;for _ in 0..5 {let headers = headers_for_url(¤t_url)?;- let response = self+ let mut request = self.no_redirect_client.get(current_url.clone())- .headers(headers)- .send()- .await?;+ .headers(headers);+ if let Some(timeout) = self.timeout {+ request = request.timeout(timeout);+ }+ let response = request.send().await?;if response.status().is_redirection()&& let Some(location) = response.headers().get(LOCATION){@@ -707,7 +713,7 @@ impl HttpClient {impl ObjectStoreHttpClient {/// Download bytes from a presigned URL without Ente headers.pub async fn get_bytes(&self, url: &str) -> Result<Vec<u8>, Error> {- get_bytes_with_client(&self.client, url, |_| Ok(HeaderMap::new())).await+ get_bytes_with_client(&self.client, url, self.timeout, |_| Ok(HeaderMap::new())).await}/// Upload raw bytes to a presigned URL without Ente headers.@@ -717,13 +723,14 @@ impl ObjectStoreHttpClient {body: &[u8],headers: &[(&str, String)],) -> Result<(), Error> {- put_bytes_with_client(&self.client, url, body, headers).await+ put_bytes_with_client(&self.client, url, self.timeout, body, headers).await}}async fn get_bytes_with_client<F>(client: &reqwest::Client,url: &str,+ timeout: Option<Duration>,headers_for_url: F,) -> Result<Vec<u8>, Error>where@@ -732,11 +739,11 @@ wherelet mut current_url = parse_url(url)?;for _ in 0..5 {let headers = headers_for_url(¤t_url)?;- let response = client- .get(current_url.clone())- .headers(headers)- .send()- .await?;+ let mut request = client.get(current_url.clone()).headers(headers);+ if let Some(timeout) = timeout {+ request = request.timeout(timeout);+ }+ let response = request.send().await?;if response.status().is_redirection()&& let Some(location) = response.headers().get(LOCATION){@@ -752,18 +759,21 @@ whereasync fn put_bytes_with_client(client: &reqwest::Client,url: &str,+ timeout: Option<Duration>,body: &[u8],headers: &[(&str, String)],) -> Result<(), Error> {let header_map = build_header_map(headers)?;let mut current_url = parse_url(url)?;for _ in 0..5 {- let response = client+ let mut request = client.put(current_url.clone()).headers(header_map.clone())- .body(body.to_vec())- .send()- .await?;+ .body(body.to_vec());+ if let Some(timeout) = timeout {+ request = request.timeout(timeout);+ }+ let response = request.send().await?;if response.status().is_redirection()&& let Some(location) = response.headers().get(LOCATION){diff --git a/rust/wall/src/client.rs b/rust/wall/src/client.rsindex d971162f77..2d718b1113 100644--- a/rust/wall/src/client.rs+++ b/rust/wall/src/client.rs@@ -123,6 +123,26 @@ impl AccountWallCtx {}}+ pub async fn ensure_entity_key(+ &self,+ key_type: &str,+ payload: &EntityKeyPayload,+ ) -> Result<EntityKeyPayload> {+ let request = CreateEntityKeyRequest {+ key_type: key_type.to_owned(),+ encrypted_key: payload.encrypted_key.clone(),+ header: payload.header.clone(),+ };+ let response = self+ .client+ .post_json::<EntityKeyResponse, _>("/user-entity/key/ensure", &request)+ .await?;+ Ok(EntityKeyPayload {+ encrypted_key: response.encrypted_key,+ header: response.header,+ })+ }+pub async fn get_root_wall_key(&self) -> Result<Option<Vec<u8>>> {let payload = match self.get_entity_key(ROOT_WALL_KEY_TYPE).await? {Some(value) => value,@@ -132,18 +152,10 @@ impl AccountWallCtx {}pub async fn get_or_create_root_wall_key(&self) -> Result<Vec<u8>> {- if let Some(root_wall_key) = self.get_root_wall_key().await? {- return Ok(root_wall_key);- }let root_wall_key = generate_key();let payload = encrypt_entity_key(&self.master_key, &root_wall_key)?;- match self.create_entity_key(ROOT_WALL_KEY_TYPE, &payload).await {- Ok(()) => Ok(root_wall_key),- Err(WallError::EntityKeyConflict) => self.get_root_wall_key().await?.ok_or_else(|| {- WallError::InvalidInput("root wall key was created but not retrievable".into())- }),- Err(err) => Err(err),- }+ let ensured = self.ensure_entity_key(ROOT_WALL_KEY_TYPE, &payload).await?;+ decrypt_entity_key(&self.master_key, &ensured)}pub async fn list_owned_walls(&self) -> Result<Vec<WallKeyResponse>> {@@ -177,7 +189,10 @@ impl AccountWallCtx {}async fn default_owned_wall_access(&self) -> Result<(WallKeyResponse, Vec<u8>)> {- let root_wall_key = self.get_or_create_root_wall_key().await?;+ let root_wall_key = self+ .get_root_wall_key()+ .await?+ .ok_or_else(|| WallError::InvalidInput("root wall key is missing".into()))?;let wall = self.list_owned_walls().await?@@ -1384,20 +1399,12 @@ mod tests {async fn get_or_create_root_wall_key_creates_when_missing() {let mut server = Server::new_async().await;let ctx = test_account_ctx(&server.url());- let first_get = server- .mock("GET", "/user-entity/key")- .match_query(Matcher::UrlEncoded(- "type".into(),- ROOT_WALL_KEY_TYPE.into(),- ))- .with_status(404)- .create_async()- .await;- let create = server- .mock("POST", "/user-entity/key")+ let expected_root = generate_key();+ let ensure = server+ .mock("POST", "/user-entity/key/ensure").match_header("x-auth-token", "token").with_status(200)- .with_body(r#"{"status":"ok"}"#)+ .with_body(root_entity_response(&ctx.master_key, &expected_root)).create_async().await;@@ -1406,49 +1413,20 @@ mod tests {.await.expect("root wall key should be created");- assert_eq!(root.len(), 32);- first_get.assert_async().await;- create.assert_async().await;+ assert_eq!(root, expected_root);+ ensure.assert_async().await;}#[tokio::test]- async fn get_or_create_root_wall_key_refetches_on_conflict() {+ async fn get_or_create_root_wall_key_uses_existing_key_from_ensure() {let mut server = Server::new_async().await;let ctx = test_account_ctx(&server.url());let expected_root = generate_key();- let payload = encrypt_entity_key(&ctx.master_key, &expected_root).expect("entity key");- let missing = server- .mock("GET", "/user-entity/key")- .match_query(Matcher::UrlEncoded(- "type".into(),- ROOT_WALL_KEY_TYPE.into(),- ))- .with_status(404)- .expect(1)- .create_async()- .await;- let conflict = server- .mock("POST", "/user-entity/key")- .with_status(409)- .with_body("conflict")- .create_async()- .await;- let refetch = server- .mock("GET", "/user-entity/key")- .match_query(Matcher::UrlEncoded(- "type".into(),- ROOT_WALL_KEY_TYPE.into(),- ))+ let ensure = server+ .mock("POST", "/user-entity/key/ensure").with_status(200)- .with_body(- json!({- "type": ROOT_WALL_KEY_TYPE,- "encryptedKey": payload.encrypted_key,- "header": payload.header,- })- .to_string(),- )+ .with_body(root_entity_response(&ctx.master_key, &expected_root)).expect(1).create_async().await;@@ -1456,11 +1434,9 @@ mod tests {let root = ctx.get_or_create_root_wall_key().await- .expect("root wall key should refetch on conflict");+ .expect("root wall key should come from ensure response");assert_eq!(root, expected_root);- missing.assert_async().await;- conflict.assert_async().await;- refetch.assert_async().await;+ ensure.assert_async().await;}#[tokio::test]@@ -1821,19 +1797,9 @@ mod tests {let mut server = Server::new_async().await;let ctx = test_account_ctx(&server.url());let wall_key = generate_key();- let missing_root = server- .mock("GET", "/user-entity/key")- .match_header("x-auth-token", "token")- .match_query(Matcher::UrlEncoded(- "type".into(),- ROOT_WALL_KEY_TYPE.into(),- ))- .with_status(404)- .expect(1)- .create_async()- .await;- let create_root = server- .mock("POST", "/user-entity/key")+ let root_wall_key = generate_key();+ let ensure_root = server+ .mock("POST", "/user-entity/key/ensure").match_header("x-auth-token", "token").match_body(Matcher::AllOf(vec![Matcher::Regex("\"type\":\"wall\"".into()),@@ -1841,7 +1807,7 @@ mod tests {Matcher::Regex("\"header\":\"[^\"]+\"".into()),])).with_status(200)- .with_body(r#"{"status":"ok"}"#)+ .with_body(root_entity_response(&ctx.master_key, &root_wall_key)).create_async().await;let create_wall = server@@ -1878,8 +1844,7 @@ mod tests {decrypt_secretbox_packed(&wall_key, &decode_b64(&created.encrypted_profile).unwrap()).expect("created profile should decrypt");assert_eq!(profile_plaintext, b"profile-json");- missing_root.assert_async().await;- create_root.assert_async().await;+ ensure_root.assert_async().await;create_wall.assert_async().await;}@@ -1889,9 +1854,6 @@ mod tests {let ctx = test_account_ctx(&server.url());let root_wall_key = generate_key();let wall_key = generate_key();- let entity_payload =- encrypt_entity_key(&ctx.master_key, &root_wall_key).expect("root wall entity");-let entity = server.mock("GET", "/user-entity/key").match_header("x-auth-token", "token")@@ -1900,14 +1862,7 @@ mod tests {ROOT_WALL_KEY_TYPE.into(),)).with_status(200)- .with_body(- json!({- "type": ROOT_WALL_KEY_TYPE,- "encryptedKey": entity_payload.encrypted_key,- "header": entity_payload.header,- })- .to_string(),- )+ .with_body(root_entity_response(&ctx.master_key, &root_wall_key)).create_async().await;let walls = serverdiff --git a/server/cmd/museum/main.go b/server/cmd/museum/main.goindex 72c5e58009..9a8deb7d4d 100644--- a/server/cmd/museum/main.go+++ b/server/cmd/museum/main.go@@ -944,6 +944,7 @@ func main() {wallHandlers := wallapi.NewHandlers(wallModule)privateAPI.POST("/user-entity/key", userEntityHandler.CreateKey)+ privateAPI.POST("/user-entity/key/ensure", userEntityHandler.EnsureKey)privateAPI.GET("/user-entity/key", userEntityHandler.GetKey)privateAPI.POST("/user-entity/entity", userEntityHandler.CreateEntity)privateAPI.PUT("/user-entity/entity", userEntityHandler.UpdateEntity)diff --git a/server/pkg/api/userentity.go b/server/pkg/api/userentity.goindex e8aa043b5b..efcf65f013 100644--- a/server/pkg/api/userentity.go+++ b/server/pkg/api/userentity.go@@ -37,6 +37,25 @@ func (h *UserEntityHandler) CreateKey(c *gin.Context) {c.Status(http.StatusOK)}+func (h *UserEntityHandler) EnsureKey(c *gin.Context) {+ var request model.EntityKeyRequest+ if err := c.ShouldBindJSON(&request); err != nil {+ handler.Error(c,+ stacktrace.Propagate(ente.ErrBadRequest, fmt.Sprintf("Request binding failed %s", err)))+ return+ }+ if err := request.Type.IsValid(); err != nil {+ handler.Error(c, stacktrace.Propagate(err, "Invalid EntityType"))+ return+ }+ resp, err := h.Controller.EnsureKey(c, request)+ if err != nil {+ handler.Error(c, stacktrace.Propagate(err, "Failed to ensure EntityKey"))+ return+ }+ c.JSON(http.StatusOK, resp)+}+// GetKey...func (h *UserEntityHandler) GetKey(c *gin.Context) {var request model.GetEntityKeyRequestdiff --git a/server/pkg/api/userentity_test.go b/server/pkg/api/userentity_test.goindex 81f70a4fdc..d96c02c4a8 100644--- a/server/pkg/api/userentity_test.go+++ b/server/pkg/api/userentity_test.go@@ -71,6 +71,43 @@ func TestCreateUserEntityKeyReturnsAlreadyExistsForConflictingCreate(t *testing.assertAPIErrorResponse(t, second, http.StatusConflict, ente.AlreadyExists, "Key already exists")}+func TestEnsureUserEntityKeyReturnsExistingKeyForConflict(t *testing.T) {+ handler, db := setupUserEntityHandlerTest(t)++ userID := testutil.InsertUser(t, db, testutil.UserFixture{+ UserID: 203,+ Email: "[email protected]",+ CreationTime: 1,+ })++ firstBody := map[string]any{+ "type": "wall",+ "encryptedKey": "encrypted-key",+ "header": "header",+ }+ secondBody := map[string]any{+ "type": "wall",+ "encryptedKey": "different-encrypted-key",+ "header": "different-header",+ }++ first := performEnsureUserEntityKeyRequest(t, handler, userID, firstBody)+ if first.Code != http.StatusOK {+ t.Fatalf("unexpected status code on first ensure: got %d want %d; body=%s", first.Code, http.StatusOK, first.Body.String())+ }+ second := performEnsureUserEntityKeyRequest(t, handler, userID, secondBody)+ if second.Code != http.StatusOK {+ t.Fatalf("unexpected status code on duplicate ensure: got %d want %d; body=%s", second.Code, http.StatusOK, second.Body.String())+ }+ var response map[string]any+ if err := json.Unmarshal(second.Body.Bytes(), &response); err != nil {+ t.Fatalf("failed to decode ensure response: %v", err)+ }+ if response["encryptedKey"] != firstBody["encryptedKey"] || response["header"] != firstBody["header"] {+ t.Fatalf("ensure returned wrong key: got %v", response)+ }+}+func setupUserEntityHandlerTest(t *testing.T) (*UserEntityHandler, *sql.DB) {t.Helper()@@ -115,3 +152,30 @@ func performCreateUserEntityKeyRequest(return recorder}++func performEnsureUserEntityKeyRequest(+ t *testing.T,+ handler *UserEntityHandler,+ userID int64,+ body map[string]any,+) *httptest.ResponseRecorder {+ t.Helper()++ gin.SetMode(gin.TestMode)++ payload, err := json.Marshal(body)+ if err != nil {+ t.Fatalf("failed to marshal request body: %v", err)+ }++ recorder := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodPost, "/user-entity/key/ensure", bytes.NewReader(payload))+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("X-Auth-User-ID", strconv.FormatInt(userID, 10))++ router := gin.New()+ router.POST("/user-entity/key/ensure", handler.EnsureKey)+ router.ServeHTTP(recorder, req)++ return recorder+}diff --git a/server/pkg/controller/userentity/controller.go b/server/pkg/controller/userentity/controller.goindex bc30911e36..c3c24c7fb1 100644--- a/server/pkg/controller/userentity/controller.go+++ b/server/pkg/controller/userentity/controller.go@@ -20,6 +20,15 @@ func (c *Controller) CreateKey(ctx *gin.Context, req model.EntityKeyRequest) errreturn c.Repo.CreateKey(ctx, userID, req)}+func (c *Controller) EnsureKey(ctx *gin.Context, req model.EntityKeyRequest) (*model.EntityKey, error) {+ userID := auth.GetUserID(ctx.Request.Header)+ res, err := c.Repo.EnsureKey(ctx, userID, req)+ if err != nil {+ return nil, stacktrace.Propagate(err, "")+ }+ return &res, nil+}+// GetKeyfunc (c *Controller) GetKey(ctx *gin.Context, req model.GetEntityKeyRequest) (*model.EntityKey, error) {userID := auth.GetUserID(ctx.Request.Header)diff --git a/server/pkg/repo/userentity/key.go b/server/pkg/repo/userentity/key.goindex a202a3a8dc..fc21ff76b6 100644--- a/server/pkg/repo/userentity/key.go+++ b/server/pkg/repo/userentity/key.go@@ -35,6 +35,20 @@ func (r *Repository) CreateKey(ctx context.Context, userID int64, entry model.Enreturn ente.NewAlreadyExistsError("Key already exists")}+func (r *Repository) EnsureKey(ctx context.Context, userID int64, entry model.EntityKeyRequest) (model.EntityKey, error) {+ if _, err := r.DB.ExecContext(ctx, `INSERT into entity_key(+ user_id, type, encrypted_key, header) VALUES ($1,$2,$3, $4)+ ON CONFLICT (user_id, type) DO NOTHING`,+ userID, entry.Type, entry.EncryptedKey, entry.Header); err != nil {+ return model.EntityKey{}, stacktrace.Propagate(err, "Failed to ensure entity key")+ }+ key, err := r.GetKey(ctx, userID, entry.Type)+ if err != nil {+ return model.EntityKey{}, stacktrace.Propagate(err, "failed to fetch ensured key")+ }+ return key, nil+}+func (r *Repository) GetKey(ctx context.Context, userID int64, eType model.EntityType) (model.EntityKey, error) {row := r.DB.QueryRowContext(ctx, `SELECT user_id, type, encrypted_key, header,created_at from entity_key where user_id = $1 and type = $2`, userID, eType)diff --git a/server/wall/api/register.go b/server/wall/api/register.goindex c614d3740c..dc1dc419e0 100644--- a/server/wall/api/register.go+++ b/server/wall/api/register.go@@ -34,5 +34,6 @@ func Register(privateAPI, publicAPI gin.IRoutes, handlers *Handlers) {publicAPI.GET("/wall/posts/:postID/likes", handlers.ListPostLikers)publicAPI.GET("/wall/versions", handlers.ListWallKeyVersions)publicAPI.GET("/wall/public/by-slug/:wallSlug", handlers.LookupWallBySlug)+ publicAPI.GET("/wall/public/slug-availability/:wallSlug", handlers.WallSlugAvailability)publicAPI.POST("/wall/links/session", handlers.WallLinkLogin)}diff --git a/server/wall/api/walls.go b/server/wall/api/walls.goindex 5a82ed76a2..ab6f4a5074 100644--- a/server/wall/api/walls.go+++ b/server/wall/api/walls.go@@ -1,8 +1,12 @@package apiimport (+ "database/sql"+ "net/http"+"github.com/ente-io/museum/ente""github.com/ente-io/museum/wall/models"+ "github.com/ente-io/stacktrace""github.com/gin-gonic/gin")@@ -58,6 +62,15 @@ func (h *Handlers) UpdateWallSlug(c *gin.Context) {func (h *Handlers) LookupWallBySlug(c *gin.Context) {resp, err := h.Module.Walls.LookupBySlug(c, c.Param("wallSlug"))+ if err != nil && stacktrace.RootCause(err) == sql.ErrNoRows {+ c.Status(http.StatusNotFound)+ return+ }+ respondJSON(c, resp, err)+}++func (h *Handlers) WallSlugAvailability(c *gin.Context) {+ resp, err := h.Module.Walls.SlugAvailability(c, c.Param("wallSlug"))respondJSON(c, resp, err)}diff --git a/server/wall/api/walls_test.go b/server/wall/api/walls_test.gonew file mode 100644index 0000000000..e7fb113cdc--- /dev/null+++ b/server/wall/api/walls_test.go@@ -0,0 +1,48 @@+package api++import (+ "context"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/ente-io/museum/internal/testutil"+ baserepo "github.com/ente-io/museum/pkg/repo"+ timeutil "github.com/ente-io/museum/pkg/utils/time"+ "github.com/ente-io/museum/wall/controller"+ wallrepo "github.com/ente-io/museum/wall/repo"+ "github.com/gin-gonic/gin"+ "github.com/stretchr/testify/require"+)++func TestWallSlugAvailabilityRouteReturnsOK(t *testing.T) {+ testutil.WithServerRoot(t)+ db := testutil.RequireTestDB(t)+ testutil.ResetTables(t, db)+ t.Cleanup(func() {+ testutil.ResetTables(t, db)+ })+ gin.SetMode(gin.TestMode)+ repos := wallrepo.NewModule(db, nil)+ userID := testutil.InsertUser(t, db, testutil.UserFixture{+ Email: "[email protected]",+ CreationTime: timeutil.Microseconds(),+ })+ _, err := repos.Walls.CreateWall(context.Background(), userID, "alice", "alice-wall-key", "alice-profile")+ require.NoError(t, err)+ router := gin.New()+ Register(router.Group(""), router.Group(""), NewHandlers(controller.NewModule(+ repos,+ &baserepo.UserAuthRepository{DB: db},+ )))++ existing := httptest.NewRecorder()+ router.ServeHTTP(existing, httptest.NewRequest(http.MethodGet, "/wall/public/slug-availability/alice", nil))+ require.Equal(t, http.StatusOK, existing.Code)+ require.JSONEq(t, `{"available": false}`, existing.Body.String())++ free := httptest.NewRecorder()+ router.ServeHTTP(free, httptest.NewRequest(http.MethodGet, "/wall/public/slug-availability/new-person", nil))+ require.Equal(t, http.StatusOK, free.Code)+ require.JSONEq(t, `{"available": true}`, free.Body.String())+}diff --git a/server/wall/controller/walls.go b/server/wall/controller/walls.goindex 16de1e8876..2cc7ccfa8b 100644--- a/server/wall/controller/walls.go+++ b/server/wall/controller/walls.go@@ -1,11 +1,13 @@package controllerimport (+ "database/sql""strings""github.com/ente-io/museum/ente""github.com/ente-io/museum/wall/models""github.com/ente-io/museum/wall/repo"+ "github.com/ente-io/stacktrace""github.com/gin-gonic/gin")@@ -167,6 +169,20 @@ func (c *WallsController) LookupBySlug(ctx *gin.Context, wallSlug string) (*mode}, nil}+func (c *WallsController) SlugAvailability(ctx *gin.Context, wallSlug string) (*models.WallSlugAvailabilityResponse, error) {+ normalizedSlug, err := repo.ValidateWallSlug(wallSlug)+ if err != nil {+ return &models.WallSlugAvailabilityResponse{Available: false}, nil+ }+ if _, err := c.WallsRepo.GetWallBySlug(ctx.Request.Context(), normalizedSlug); err != nil {+ if stacktrace.RootCause(err) == sql.ErrNoRows {+ return &models.WallSlugAvailabilityResponse{Available: true}, nil+ }+ return nil, err+ }+ return &models.WallSlugAvailabilityResponse{Available: false}, nil+}+func (c *WallsController) RotateKey(ctx *gin.Context, req models.RotateWallKeyRequest) (*models.WallKeyResponse, error) {userID, err := c.auth.requireUser(ctx)if err != nil {diff --git a/server/wall/controller/walls_test.go b/server/wall/controller/walls_test.goindex e76dbf8e40..aa39560b72 100644--- a/server/wall/controller/walls_test.go+++ b/server/wall/controller/walls_test.go@@ -55,3 +55,23 @@ func TestGetProfileRejectsInvalidVersion(t *testing.T) {require.Nil(t, resp)require.Error(t, err)}++func TestSlugAvailabilityReturnsFalseForExistingAndReservedSlugs(t *testing.T) {+ module, repos, _, ctx := setupWallAuthControllerTest(t)+ aliceID := insertWallControllerUser(t, repos, "[email protected]", "alice-public")+ _, err := repos.Walls.CreateWall(ctx, aliceID, "alice", "alice-wall-key", "alice-profile")+ require.NoError(t, err)+ ginCtx := newPublicWallContext()++ existing, err := module.Walls.SlugAvailability(ginCtx, "Alice")+ require.NoError(t, err)+ require.False(t, existing.Available)++ reserved, err := module.Walls.SlugAvailability(ginCtx, "support")+ require.NoError(t, err)+ require.False(t, reserved.Available)++ free, err := module.Walls.SlugAvailability(ginCtx, "new-person")+ require.NoError(t, err)+ require.True(t, free.Available)+}diff --git a/server/wall/models/models.go b/server/wall/models/models.goindex ce68fbd97c..e7ba58ae1e 100644--- a/server/wall/models/models.go+++ b/server/wall/models/models.go@@ -189,6 +189,10 @@ type WallLookupResponse struct {PublicKey string `json:"publicKey,omitempty"`}+type WallSlugAvailabilityResponse struct {+ Available bool `json:"available"`+}+type RotateWallKeyRequest struct {WallID string `json:"wallId"`EncryptedWallKey string `json:"encryptedWallKey"`diff --git a/server/wall/repo/common.go b/server/wall/repo/common.goindex c91dee0135..1bd2c2bd8a 100644--- a/server/wall/repo/common.go+++ b/server/wall/repo/common.go@@ -153,6 +153,10 @@ func validateWallSlug(input string) (string, error) {return slug, nil}+func ValidateWallSlug(input string) (string, error) {+ return validateWallSlug(input)+}+func isReservedWallSlug(slug string) bool {if _, ok := reservedWallSlugs[slug]; ok {return truediff --git a/web/apps/social/src/components/SocialRouteFallback.tsx b/web/apps/social/src/components/SocialRouteFallback.tsxindex fb129deb17..ecb17a47e4 100644--- a/web/apps/social/src/components/SocialRouteFallback.tsx+++ b/web/apps/social/src/components/SocialRouteFallback.tsx@@ -11,6 +11,30 @@ export const SocialRouteFallback: React.FC<SocialRouteFallbackProps> = ({}) => (<><SocialPageMeta themeColor={background} />- <Box sx={{ bgcolor: background, minHeight: "100svh" }} />+ <Box+ sx={{+ bgcolor: background,+ display: "grid",+ minHeight: "100svh",+ placeItems: "center",+ }}+ >+ <Box+ component="span"+ role="status"+ aria-label="Loading"+ sx={{+ animation: "socialRouteFallbackSpin 800ms linear infinite",+ border: "3px solid rgba(8, 194, 37, 0.18)",+ borderRadius: "50%",+ borderTopColor: "#08C225",+ height: 32,+ width: 32,+ "@keyframes socialRouteFallbackSpin": {+ to: { transform: "rotate(360deg)" },+ },+ }}+ />+ </Box></>);diff --git a/web/apps/social/src/pages/app/friend.tsx b/web/apps/social/src/pages/app/friend.tsxindex 3de953c050..c618b0b6b8 100644--- a/web/apps/social/src/pages/app/friend.tsx+++ b/web/apps/social/src/pages/app/friend.tsx@@ -25,7 +25,7 @@ const backRouteForSource = (const Page: React.FC = () => {const router = useRouter();- const { friends, profile } = useSocialAppState();+ const { friends, profile, profileLoadStatus } = useSocialAppState();const friendID = friendIDFromQuery(router.query.friendID);const backSource = friendProfileSourceFromQuery(router.query.from);const selectedFriend =@@ -34,14 +34,19 @@ const Page: React.FC = () => {useEffect(() => {if (!router.isReady) return;- if (!profile) {+ if (profileLoadStatus == "ready" && !profile) {void router.replace(socialRoutes.onboarding);return;}if (!selectedFriend) void router.replace(socialRoutes.friends);- }, [profile, router, selectedFriend]);+ }, [profile, profileLoadStatus, router, selectedFriend]);- if (!router.isReady || !profile || !selectedFriend) {+ if (+ !router.isReady ||+ profileLoadStatus == "loading" ||+ !profile ||+ !selectedFriend+ ) {return <SocialRouteFallback background={friendsBackground} />;}diff --git a/web/apps/social/src/pages/app/friends.tsx b/web/apps/social/src/pages/app/friends.tsxindex 3894034ac4..920df9de9e 100644--- a/web/apps/social/src/pages/app/friends.tsx+++ b/web/apps/social/src/pages/app/friends.tsx@@ -8,13 +8,16 @@ import { socialRoutes } from "utils/socialRoutes";const Page: React.FC = () => {const router = useRouter();- const { friends, profile, setFriends } = useSocialAppState();+ const { friends, profile, profileLoadStatus, setFriends } =+ useSocialAppState();useEffect(() => {- if (!profile) void router.replace(socialRoutes.onboarding);- }, [profile, router]);+ if (profileLoadStatus == "ready" && !profile) {+ void router.replace(socialRoutes.onboarding);+ }+ }, [profile, profileLoadStatus, router]);- if (!profile) {+ if (profileLoadStatus == "loading" || !profile) {return <SocialRouteFallback background={friendsBackground} />;}diff --git a/web/apps/social/src/pages/app/index.tsx b/web/apps/social/src/pages/app/index.tsxindex e456f6b3d7..4e0d082f39 100644--- a/web/apps/social/src/pages/app/index.tsx+++ b/web/apps/social/src/pages/app/index.tsx@@ -8,13 +8,15 @@ import { socialRoutes } from "utils/socialRoutes";const Page: React.FC = () => {const router = useRouter();- const { friends, profile } = useSocialAppState();+ const { friends, profile, profileLoadStatus } = useSocialAppState();useEffect(() => {- if (!profile) void router.replace(socialRoutes.onboarding);- }, [profile, router]);+ if (profileLoadStatus == "ready" && !profile) {+ void router.replace(socialRoutes.onboarding);+ }+ }, [profile, profileLoadStatus, router]);- if (!profile) {+ if (profileLoadStatus == "loading" || !profile) {return <SocialRouteFallback background={homeBackground} />;}diff --git a/web/apps/social/src/pages/app/notifications.tsx b/web/apps/social/src/pages/app/notifications.tsxindex 2b44ddd227..6def4ea9f9 100644--- a/web/apps/social/src/pages/app/notifications.tsx+++ b/web/apps/social/src/pages/app/notifications.tsx@@ -11,13 +11,15 @@ import { socialRoutes } from "utils/socialRoutes";const Page: React.FC = () => {const router = useRouter();- const { profile } = useSocialAppState();+ const { profile, profileLoadStatus } = useSocialAppState();useEffect(() => {- if (!profile) void router.replace(socialRoutes.onboarding);- }, [profile, router]);+ if (profileLoadStatus == "ready" && !profile) {+ void router.replace(socialRoutes.onboarding);+ }+ }, [profile, profileLoadStatus, router]);- if (!profile) {+ if (profileLoadStatus == "loading" || !profile) {return <SocialRouteFallback background={notificationsBackground} />;}diff --git a/web/apps/social/src/pages/app/profile.tsx b/web/apps/social/src/pages/app/profile.tsxindex 65efb74d5a..53dc6e83c3 100644--- a/web/apps/social/src/pages/app/profile.tsx+++ b/web/apps/social/src/pages/app/profile.tsx@@ -8,13 +8,15 @@ import { socialRoutes } from "utils/socialRoutes";const Page: React.FC = () => {const router = useRouter();- const { friends, profile } = useSocialAppState();+ const { friends, profile, profileLoadStatus } = useSocialAppState();useEffect(() => {- if (!profile) void router.replace(socialRoutes.onboarding);- }, [profile, router]);+ if (profileLoadStatus == "ready" && !profile) {+ void router.replace(socialRoutes.onboarding);+ }+ }, [profile, profileLoadStatus, router]);- if (!profile) {+ if (profileLoadStatus == "loading" || !profile) {return <SocialRouteFallback background={profileBackground} />;}diff --git a/web/apps/social/src/pages/app/settings.tsx b/web/apps/social/src/pages/app/settings.tsxindex dd92c27960..808da3e1c8 100644--- a/web/apps/social/src/pages/app/settings.tsx+++ b/web/apps/social/src/pages/app/settings.tsx@@ -1,5 +1,6 @@import { SocialPageMeta } from "components/SocialPageMeta";import { SocialRouteFallback } from "components/SocialRouteFallback";+import { accountLogout } from "ente-accounts-rs/services/logout";import { useRouter } from "next/router";import React, { useEffect } from "react";import { SettingsScreen, settingsBackground } from "screens/SettingsScreen";@@ -8,13 +9,16 @@ import { socialRoutes } from "utils/socialRoutes";const Page: React.FC = () => {const router = useRouter();- const { profile, resetAfterLogout } = useSocialAppState();+ const { profile, profileLoadStatus, resetAfterLogout } =+ useSocialAppState();useEffect(() => {- if (!profile) void router.replace(socialRoutes.onboarding);- }, [profile, router]);+ if (profileLoadStatus == "ready" && !profile) {+ void router.replace(socialRoutes.onboarding);+ }+ }, [profile, profileLoadStatus, router]);- if (!profile) {+ if (profileLoadStatus == "loading" || !profile) {return <SocialRouteFallback background={settingsBackground} />;}@@ -24,8 +28,10 @@ const Page: React.FC = () => {<SettingsScreenonBack={() => void router.push(socialRoutes.profile)}onLogout={() => {- resetAfterLogout();- void router.push(socialRoutes.onboarding);+ void accountLogout().then(() => {+ resetAfterLogout();+ void router.push(socialRoutes.onboarding);+ });}}/></>diff --git a/web/apps/social/src/pages/index.tsx b/web/apps/social/src/pages/index.tsxindex 7c9f034088..052110ecd1 100644--- a/web/apps/social/src/pages/index.tsx+++ b/web/apps/social/src/pages/index.tsx@@ -78,8 +78,12 @@ const publicProfileFromLink = (): SetupProfile => ({const Page: React.FC = () => {const router = useRouter();- const { onboardingEntrySource, setOnboardingEntrySource } =- useSocialAppState();+ const {+ onboardingEntrySource,+ profile,+ profileLoadStatus,+ setOnboardingEntrySource,+ } = useSocialAppState();const [routeMode, setRouteMode] = useState<RouteMode>({ kind: "checking" });useEffect(() => {@@ -95,7 +99,21 @@ const Page: React.FC = () => {);}, [setOnboardingEntrySource]);- if (routeMode.kind == "checking") {+ useEffect(() => {+ if (+ routeMode.kind == "app" &&+ profileLoadStatus == "ready" &&+ profile+ ) {+ void router.replace(socialRoutes.home);+ }+ }, [profile, profileLoadStatus, routeMode.kind, router]);++ if (+ routeMode.kind == "checking" ||+ (routeMode.kind == "app" &&+ (profileLoadStatus == "loading" || Boolean(profile)))+ ) {return <SocialRouteFallback background={profileBackground} />;}diff --git a/web/apps/social/src/pages/invite.tsx b/web/apps/social/src/pages/invite.tsxindex b179e125e3..b8fe338bca 100644--- a/web/apps/social/src/pages/invite.tsx+++ b/web/apps/social/src/pages/invite.tsx@@ -11,13 +11,15 @@ import { socialRoutes } from "utils/socialRoutes";const Page: React.FC = () => {const router = useRouter();- const { profile } = useSocialAppState();+ const { profile, profileLoadStatus } = useSocialAppState();useEffect(() => {- if (!profile) void router.replace(socialRoutes.setupProfile("verify"));- }, [profile, router]);+ if (profileLoadStatus == "ready" && !profile) {+ void router.replace(socialRoutes.setupProfile("verify"));+ }+ }, [profile, profileLoadStatus, router]);- if (!profile) {+ if (profileLoadStatus == "loading" || !profile) {return <SocialRouteFallback background={shareProfileLinkBackground} />;}diff --git a/web/apps/social/src/pages/setup-profile.tsx b/web/apps/social/src/pages/setup-profile.tsxindex 7aca0849c7..743ca07c7a 100644--- a/web/apps/social/src/pages/setup-profile.tsx+++ b/web/apps/social/src/pages/setup-profile.tsx@@ -1,25 +1,107 @@import { SocialPageMeta } from "components/SocialPageMeta";+import { SocialRouteFallback } from "components/SocialRouteFallback";import { useRouter } from "next/router";-import React from "react";+import React, { useEffect, useMemo, useState } from "react";import {SetupProfileScreen,setupProfileBackground,} from "screens/SetupProfileScreen";+import {+ saveSocialProfile,+ socialProfileErrorMessage,+ socialUsernameAvailability,+ socialUsernameValidationError,+} from "services/socialProfile";import { useSocialAppState } from "state/socialAppState";import { setupProfileSourceFromQuery, socialRoutes } from "utils/socialRoutes";const Page: React.FC = () => {const router = useRouter();- const { onboardingEntrySource, setProfile } = useSocialAppState();+ const {+ onboardingEntrySource,+ profile,+ profileLoadStatus,+ refreshProfile,+ setProfile,+ } = useSocialAppState();const backSource = setupProfileSourceFromQuery(router.query.from);const isAddFriendLinkOnboarding =onboardingEntrySource == "add-friend-link";+ const [setupError, setSetupError] = useState<string>();+ const [isSubmitting, setIsSubmitting] = useState(false);+ const [draftUsername, setDraftUsername] = useState("");+ const [usernameStatus, setUsernameStatus] = useState<+ "available" | "unavailable"+ >();+ const existingProfileRoute = useMemo(+ () =>+ isAddFriendLinkOnboarding || backSource == "login"+ ? socialRoutes.home+ : socialRoutes.invite,+ [backSource, isAddFriendLinkOnboarding],+ );++ useEffect(() => {+ if (router.isReady) void refreshProfile();+ }, [refreshProfile, router.isReady]);++ useEffect(() => {+ if (profileLoadStatus == "ready" && profile) {+ void router.replace(existingProfileRoute);+ }+ }, [existingProfileRoute, profile, profileLoadStatus, router]);++ useEffect(() => {+ if (profileLoadStatus != "ready" || profile) return;++ const username = draftUsername.trim();+ if (!username) {+ setUsernameStatus(undefined);+ return;+ }++ const validationError = socialUsernameValidationError(username);+ if (validationError) {+ setUsernameStatus("unavailable");+ return;+ }++ setUsernameStatus(undefined);++ let cancelled = false;+ const timeout = window.setTimeout(() => {+ void socialUsernameAvailability(username)+ .then((availability) => {+ if (cancelled) return;+ setUsernameStatus(+ availability == "taken" ? "unavailable" : "available",+ );+ })+ .catch((error: unknown) => {+ console.error("Username availability check failed", error);+ if (!cancelled) {+ setUsernameStatus(undefined);+ }+ });+ }, 350);++ return () => {+ cancelled = true;+ window.clearTimeout(timeout);+ };+ }, [draftUsername, profile, profileLoadStatus]);++ if (profileLoadStatus == "loading" || profile) {+ return <SocialRouteFallback background={setupProfileBackground} />;+ }return (<><SocialPageMeta themeColor={setupProfileBackground} /><SetupProfileScreenctaLabel={isAddFriendLinkOnboarding ? "Done" : "Next"}+ errorMessage={setupError}+ isSubmitting={isSubmitting}onBack={() =>void router.push(backSource == "login"@@ -27,14 +109,26 @@ const Page: React.FC = () => {: socialRoutes.verify,)}- onContinue={(nextProfile) => {- setProfile(nextProfile);- void router.push(- isAddFriendLinkOnboarding- ? socialRoutes.home- : socialRoutes.invite,- );+ onContinue={async (nextProfile) => {+ setIsSubmitting(true);+ setSetupError(undefined);+ try {+ const savedProfile =+ await saveSocialProfile(nextProfile);+ setProfile(savedProfile);+ void router.push(+ isAddFriendLinkOnboarding+ ? socialRoutes.home+ : socialRoutes.invite,+ );+ } catch (error) {+ console.error("Social profile setup failed", error);+ setSetupError(socialProfileErrorMessage(error));+ setIsSubmitting(false);+ }}}+ onUsernameChange={setDraftUsername}+ usernameStatus={usernameStatus}/></>);diff --git a/web/apps/social/src/pages/signup.tsx b/web/apps/social/src/pages/signup.tsxindex d7279fc149..948fac384f 100644--- a/web/apps/social/src/pages/signup.tsx+++ b/web/apps/social/src/pages/signup.tsx@@ -6,7 +6,10 @@ import {createAccountBackground,type CreateAccountInput,} from "screens/CreateAccountScreen";-import { beginSocialSignup } from "services/socialSignup";+import {+ beginSocialSignup,+ socialSignupErrorMessage,+} from "services/socialSignup";import { useSocialAppState } from "state/socialAppState";import { socialRoutes } from "utils/socialRoutes";@@ -25,12 +28,7 @@ const Page: React.FC = () => {setIsLiveSignupVerification(true);void router.push(socialRoutes.verify);} catch (error) {- console.error("Social signup failed", error);- setSignupError(- error instanceof Error- ? error.message- : "Couldn't create account. Please try again.",- );+ setSignupError(await socialSignupErrorMessage(error));setIsSubmitting(false);}};diff --git a/web/apps/social/src/screens/FriendsScreen.tsx b/web/apps/social/src/screens/FriendsScreen.tsxindex 1ed30f233f..ecd16c7481 100644--- a/web/apps/social/src/screens/FriendsScreen.tsx+++ b/web/apps/social/src/screens/FriendsScreen.tsx@@ -13,6 +13,7 @@ import {} from "components/SocialActionFeedback";import type { FriendProfile } from "data/friends";import React, { useState } from "react";+import { initialsFor } from "utils/socialDisplay";export const friendsBackground = "#FFFFFF";@@ -36,14 +37,6 @@ interface FriendRowProps {onUnfriend?: (friendID: string) => void;}-const initialsFor = (name: string) =>- name- .trim()- .split(/\s+/)- .slice(0, 2)- .map((part) => part[0]?.toUpperCase())- .join("");-const FriendRow: React.FC<FriendRowProps> = ({friend,onOpenFriend,diff --git a/web/apps/social/src/screens/HomeScreen.tsx b/web/apps/social/src/screens/HomeScreen.tsxindex 780cbdacb7..946f2a1f9d 100644--- a/web/apps/social/src/screens/HomeScreen.tsx+++ b/web/apps/social/src/screens/HomeScreen.tsx@@ -20,7 +20,11 @@ import {type LocalPostPhotoDimensions,} from "utils/localPostPhoto";import { profileLinkForUsername } from "utils/profileLink";-import { firstNameFrom, formatSocialDate } from "utils/socialDisplay";+import {+ firstNameFrom,+ formatSocialDate,+ initialsFor,+} from "utils/socialDisplay";export const homeBackground = "#FFFFFF";@@ -508,11 +512,7 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({: "When your friends share posts, they'll appear here.";const profileLink = profileLinkForUsername(profile.username.trim());const initialsSource = profile.fullName.trim() || profile.username.trim();- const initials = initialsSource- .split(/\s+/)- .slice(0, 2)- .map((part) => part[0]?.toUpperCase())- .join("");+ const initials = initialsFor(initialsSource);const revokeLocalPostObjectUrl = React.useCallback((objectUrl?: string) => {if (!objectUrl || !localPostObjectUrlsRef.current.has(objectUrl))return;diff --git a/web/apps/social/src/screens/SetupProfileScreen.tsx b/web/apps/social/src/screens/SetupProfileScreen.tsxindex 43ad9b16d2..9ff9751571 100644--- a/web/apps/social/src/screens/SetupProfileScreen.tsx+++ b/web/apps/social/src/screens/SetupProfileScreen.tsx@@ -9,26 +9,34 @@ const textLight = "#969696";const warning = "#F63A3A";const paleGreen = "#E7F6E9";const setupProfileFormID = "social-setup-profile-form";--const mockSetupProfileData = {- avatarUrl: "/images/sample-avatar.jpg",- username: "anandbaburajan",- fullName: "Anand Baburajan",-};+const maxAvatarBytes = 19 * 1024 * 1024;export interface SetupProfile {avatarUrl: string | null;+ avatarObjectKey?: string;+ avatarUpdatedAt?: string;fullName: string;username: string;+ wallId?: string;+ wallSlug?: string;+}++export interface SetupProfileInput extends SetupProfile {+ avatarFile?: File | null;}interface SetupProfileScreenProps {ctaLabel?: string;+ errorMessage?: string;+ isSubmitting?: boolean;onBack: () => void;- onContinue?: (profile: SetupProfile) => void;+ onContinue?: (profile: SetupProfileInput) => Promise<void> | void;+ onUsernameChange?: (username: string) => void;+ usernameStatus?: "available" | "unavailable";}interface TextInputProps {+ endAdornment?: React.ReactNode;label: string;onChange?: (value: string) => void;placeholder?: string;@@ -59,7 +67,7 @@ const UploadIcon: React.FC = () => (component="svg"viewBox="0 0 24 24"aria-hidden- sx={{ display: "block", height: 20, width: 20 }}+ sx={{ display: "block", height: 40, width: 40 }}><pathd="M8.5 7.5L9.75 5.75H14.25L15.5 7.5H18C19.1 7.5 20 8.4 20 9.5V17C20 18.1 19.1 19 18 19H6C4.9 19 4 18.1 4 17V9.5C4 8.4 4.9 7.5 6 7.5H8.5Z"@@ -97,7 +105,72 @@ const PencilIcon: React.FC = () => (</Box>);+const CheckIcon: React.FC = () => (+ <Box+ component="svg"+ viewBox="0 0 20 20"+ aria-hidden+ sx={{ display: "block", height: 18, width: 18 }}+ >+ <path+ d="M4.5 10.25L8.25 14L15.75 6"+ fill="none"+ stroke="currentColor"+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth="2.2"+ />+ </Box>+);++const XIcon: React.FC = () => (+ <Box+ component="svg"+ viewBox="0 0 20 20"+ aria-hidden+ sx={{ display: "block", height: 18, width: 18 }}+ >+ <path+ d="M5.75 5.75L14.25 14.25M14.25 5.75L5.75 14.25"+ fill="none"+ stroke="currentColor"+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth="2.2"+ />+ </Box>+);++const UsernameStatusIcon: React.FC<{+ status?: "available" | "unavailable";+}> = ({ status }) => {+ if (!status) return null;++ return (+ <Box+ component="span"+ role="img"+ aria-label={+ status == "available"+ ? "Username available"+ : "Username unavailable"+ }+ sx={{+ alignItems: "center",+ color: status == "available" ? green : warning,+ display: "flex",+ flexShrink: 0,+ justifyContent: "center",+ ml: 1,+ }}+ >+ {status == "available" ? <CheckIcon /> : <XIcon />}+ </Box>+ );+};+const TextInput: React.FC<TextInputProps> = ({+ endAdornment,label,onChange,placeholder,@@ -157,33 +230,33 @@ const TextInput: React.FC<TextInputProps> = ({"&::placeholder": { color: textLight, opacity: 1 },}}/>+ {endAdornment}</Box></Box>);export const SetupProfileScreen: React.FC<SetupProfileScreenProps> = ({ctaLabel = "Next",+ errorMessage,+ isSubmitting = false,onBack,onContinue,+ onUsernameChange,+ usernameStatus,}) => {- const [avatarUrl, setAvatarUrl] = useState<string | null>(- mockSetupProfileData.avatarUrl,- );- const [username, setUsername] = useState(mockSetupProfileData.username);- const [fullName, setFullName] = useState(mockSetupProfileData.fullName);+ const [avatarFile, setAvatarFile] = useState<File | null>(null);+ const [avatarUrl, setAvatarUrl] = useState<string | null>(null);+ const [avatarError, setAvatarError] = useState<string>();+ const [username, setUsername] = useState("");+ const [fullName, setFullName] = useState("");const avatarUrlRef = useRef<string | null>(null);const fileInputRef = useRef<HTMLInputElement | null>(null);const canContinue =- Boolean(avatarUrl) &&+ !isSubmitting &&+ usernameStatus != "unavailable" &&username.trim().length > 0 &&fullName.trim().length > 0;- const initialsSource = fullName.trim() || username.trim();- const initials = initialsSource- .split(/\s+/)- .slice(0, 2)- .map((part) => part[0]?.toUpperCase())- .join("");useEffect(() => () => {@@ -198,16 +271,35 @@ export const SetupProfileScreen: React.FC<SetupProfileScreenProps> = ({const file = event.target.files?.[0];if (!file) return;+ if (!file.type.startsWith("image/")) {+ setAvatarError("Choose an image file.");+ event.target.value = "";+ return;+ }+ if (file.size > maxAvatarBytes) {+ setAvatarError("Choose an image under 19 MB.");+ event.target.value = "";+ return;+ }+if (avatarUrlRef.current) URL.revokeObjectURL(avatarUrlRef.current);const nextUrl = URL.createObjectURL(file);avatarUrlRef.current = nextUrl;+ setAvatarError(undefined);+ setAvatarFile(file);setAvatarUrl(nextUrl);event.target.value = "";};+ const handleUsernameChange = (value: string) => {+ setUsername(value);+ onUsernameChange?.(value);+ };+const submitProfile = () => {if (canContinue) {- onContinue?.({+ void onContinue?.({+ avatarFile,avatarUrl,fullName: fullName.trim(),username: username.trim(),@@ -361,19 +453,6 @@ export const SetupProfileScreen: React.FC<SetupProfileScreenProps> = ({width: "100%",}}/>- ) : initials ? (- <Box- sx={{- color: green,- fontFamily:- '"Inter Variable", Inter, sans-serif',- fontSize: 32,- fontWeight: 700,- lineHeight: 1,- }}- >- {initials}- </Box>) : (<UploadIcon />)}@@ -418,8 +497,11 @@ export const SetupProfileScreen: React.FC<SetupProfileScreenProps> = ({}}><TextInput+ endAdornment={+ <UsernameStatusIcon status={usernameStatus} />+ }label="Username"- onChange={setUsername}+ onChange={handleUsernameChange}placeholder="Choose a username"requiredvalue={username}@@ -431,6 +513,22 @@ export const SetupProfileScreen: React.FC<SetupProfileScreenProps> = ({requiredvalue={fullName}/>+ {(avatarError || errorMessage) && (+ <Box+ role="alert"+ sx={{+ color: warning,+ fontFamily:+ '"Inter Variable", Inter, sans-serif',+ fontSize: 13,+ fontWeight: 500,+ lineHeight: "18px",+ mt: "-8px",+ }}+ >+ {errorMessage ?? avatarError}+ </Box>+ )}</Box></Box>@@ -478,7 +576,7 @@ export const SetupProfileScreen: React.FC<SetupProfileScreenProps> = ({: undefined,}}>- {ctaLabel}+ {isSubmitting ? "Saving..." : ctaLabel}</Box></Box></Box>diff --git a/web/apps/social/src/screens/ShareProfileLinkScreen.tsx b/web/apps/social/src/screens/ShareProfileLinkScreen.tsxindex aefc27c014..eca72e2835 100644--- a/web/apps/social/src/screens/ShareProfileLinkScreen.tsx+++ b/web/apps/social/src/screens/ShareProfileLinkScreen.tsx@@ -4,6 +4,7 @@ import { Box } from "@mui/material";import React, { useState } from "react";import type { SetupProfile } from "screens/SetupProfileScreen";import { profileLinkForUsername } from "utils/profileLink";+import { initialsFor } from "utils/socialDisplay";export const shareProfileLinkBackground = "#FAFAFA";@@ -172,11 +173,7 @@ export const ShareProfileLinkScreen: React.FC<ShareProfileLinkScreenProps> = ({const profileLink = profileLinkForUsername(profile.username.trim());const displayName = profile.fullName.trim() || profile.username.trim();const initialsSource = displayName || profile.username.trim();- const initials = initialsSource- .split(/\s+/)- .slice(0, 2)- .map((part) => part[0]?.toUpperCase())- .join("");+ const initials = initialsFor(initialsSource);const copyProfileLink = async () => {await navigator.clipboard.writeText(profileLink);diff --git a/web/apps/social/src/services/socialProfile.ts b/web/apps/social/src/services/socialProfile.tsnew file mode 100644index 0000000000..053bd50730--- /dev/null+++ b/web/apps/social/src/services/socialProfile.ts@@ -0,0 +1,322 @@+import {+ savedKeyAttributes,+ savedLocalUser,+} from "ente-accounts-rs/services/accounts-db";+import { masterKeyFromSession } from "ente-accounts-rs/services/session-storage";+import { clientPackageName, desktopAppVersion, isDesktop } from "ente-base/app";+import { apiOrigin, apiURL } from "ente-base/origins";+import { savedAuthToken } from "ente-base/token";+import type { WallAccountCtxHandle } from "ente-wasm";+import { loadEnteWasm } from "ente-wasm/load";+import type {+ SetupProfile,+ SetupProfileInput,+} from "screens/SetupProfileScreen";++const usernamePattern = /^[a-z0-9][a-z0-9._-]*$/;+const minUsernameLength = 3;+const maxUsernameLength = 30;++interface WallAvatar {+ objectKey: string;+ size?: number;+ updatedAt?: string;+}++interface OwnedWall {+ wallId: string;+ wallSlug: string;+}++interface CreatedWall {+ wallId: string;+ wallSlug: string;+}++interface WallLookup {+ wallId: string;+ wallSlug: string;+}++interface DecryptedWallProfile {+ wallId: string;+ wallSlug: string;+ profile: string;+ avatar?: WallAvatar;+ updatedAt?: string;+}++interface UpdateWallProfileResponse {+ avatar?: WallAvatar;+}++interface WallProfilePayload {+ displayName?: unknown;+ fullName?: unknown;+ username?: unknown;+}++export type UsernameAvailability = "available" | "taken";++export const normalizeSocialUsername = (username: string) =>+ username.trim().toLowerCase();++export const socialUsernameValidationError = (username: string) => {+ const normalized = normalizeSocialUsername(username);+ if (normalized.length < minUsernameLength) {+ return "Username must be at least 3 characters.";+ }+ if (normalized.length > maxUsernameLength) {+ return "Username must be 30 characters or less.";+ }+ if (!usernamePattern.test(normalized)) {+ return "Use lowercase letters, numbers, dots, dashes, or underscores.";+ }+ if (normalized.startsWith("ente")) {+ return "This username is reserved.";+ }+ return undefined;+};++const wallProfilePayloadFor = (profile: SetupProfileInput) =>+ JSON.stringify({+ displayName: profile.fullName.trim(),+ fullName: profile.fullName.trim(),+ username: normalizeSocialUsername(profile.username),+ });++const parseWallProfilePayload = (profile: string): WallProfilePayload => {+ if (!profile.trim()) return {};+ try {+ const parsed: unknown = JSON.parse(profile);+ return parsed && typeof parsed == "object"+ ? (parsed as WallProfilePayload)+ : {};+ } catch {+ return {};+ }+};++const textField = (value: unknown) =>+ typeof value == "string" ? value.trim() : "";++const wallHTTPStatus = (error: unknown) => {+ if (!error || typeof error != "object" || !("status" in error)) {+ return undefined;+ }+ const { status } = error as { status?: unknown };+ return typeof status == "number" ? status : undefined;+};++const openCurrentWallContext = async () => {+ const [authToken, baseUrl, masterKeyB64] = await Promise.all([+ savedAuthToken(),+ apiOrigin(),+ masterKeyFromSession(),+ ]);+ const user = savedLocalUser();+ const keyAttributes = savedKeyAttributes();++ if (!authToken || !masterKeyB64 || !user || !keyAttributes) {+ return undefined;+ }++ const { wall_open_account_ctx } = await loadEnteWasm();+ return await wall_open_account_ctx({+ authToken,+ baseUrl,+ clientPackage: clientPackageName,+ clientVersion: isDesktop ? desktopAppVersion : undefined,+ keyAttributes,+ masterKeyB64,+ publicKeyB64: keyAttributes.publicKey,+ userId: user.id,+ });+};++const ensureCurrentWallContext = async () => {+ const ctx = await openCurrentWallContext();+ if (!ctx) throw new Error("Please sign in again.");+ return ctx;+};++const avatarURLForRemoteAvatar = async (+ ctx: WallAccountCtxHandle,+ wallId: string,+ avatar: WallAvatar | undefined,+) => {+ if (!avatar?.objectKey) return null;+ const bytes = await ctx.download_wall_avatar(wallId, avatar.objectKey);+ return URL.createObjectURL(new Blob([bytes]));+};++const profileFromDecryptedWallProfile = (+ wallProfile: DecryptedWallProfile,+): SetupProfile => {+ const payload = parseWallProfilePayload(wallProfile.profile);+ const fullName =+ textField(payload.fullName) ||+ textField(payload.displayName) ||+ wallProfile.wallSlug;++ return {+ avatarObjectKey: wallProfile.avatar?.objectKey,+ avatarUpdatedAt: wallProfile.avatar?.updatedAt,+ avatarUrl: null,+ fullName,+ username: wallProfile.wallSlug,+ wallId: wallProfile.wallId,+ wallSlug: wallProfile.wallSlug,+ };+};++export const loadExistingSocialProfile = async () => {+ const ctx = await openCurrentWallContext();+ if (!ctx) return null;++ try {+ const walls = (await ctx.list_owned_walls()) as OwnedWall[];+ const wall = walls[0];+ if (!wall) return null;++ const wallProfile = (await ctx.get_wall_profile(+ wall.wallId,+ )) as DecryptedWallProfile;+ return profileFromDecryptedWallProfile(wallProfile);+ } finally {+ ctx.free();+ }+};++export const loadExistingSocialAvatar = async (+ wallId: string | undefined,+ avatarObjectKey: string | undefined,+) => {+ if (!wallId || !avatarObjectKey) return null;++ const ctx = await openCurrentWallContext();+ if (!ctx) return null;++ try {+ return await avatarURLForRemoteAvatar(ctx, wallId, {+ objectKey: avatarObjectKey,+ });+ } finally {+ ctx.free();+ }+};++export const socialUsernameAvailability = async (+ username: string,+): Promise<UsernameAvailability> => {+ const validationError = socialUsernameValidationError(username);+ if (validationError) return "taken";++ const slug = normalizeSocialUsername(username);+ const response = await fetch(+ await apiURL(+ `/wall/public/slug-availability/${encodeURIComponent(slug)}`,+ ),+ );+ if (!response.ok) {+ throw new Error("Username availability check failed.");+ }+ const { available } = (await response.json()) as { available?: unknown };+ return available === true ? "available" : "taken";+};++export const saveSocialProfile = async (+ profile: SetupProfileInput,+): Promise<SetupProfile> => {+ const username = normalizeSocialUsername(profile.username);+ const usernameError = socialUsernameValidationError(username);+ if (usernameError) throw new Error(usernameError);++ const ctx = await ensureCurrentWallContext();+ try {+ const walls = (await ctx.list_owned_walls()) as OwnedWall[];+ const existingWall =+ (profile.wallId &&+ walls.find((wall) => wall.wallId == profile.wallId)) ||+ walls[0];+ const profilePayload = wallProfilePayloadFor({ ...profile, username });++ let wallId: string;+ let wallSlug = username;+ let updateResponse: UpdateWallProfileResponse | undefined;++ if (existingWall) {+ wallId = existingWall.wallId;+ wallSlug = existingWall.wallSlug;+ if (normalizeSocialUsername(wallSlug) != username) {+ const updatedSlug = (await ctx.update_wall_slug(+ wallId,+ username,+ )) as WallLookup;+ wallSlug = updatedSlug.wallSlug;+ }+ } else {+ const created = (await ctx.create_wall(+ username,+ profilePayload,+ )) as CreatedWall;+ wallId = created.wallId;+ wallSlug = created.wallSlug;+ }++ let avatarUrl: string | null = null;+ if (profile.avatarFile) {+ const avatarBytes = new Uint8Array(+ await profile.avatarFile.arrayBuffer(),+ );+ updateResponse = (await ctx.update_wall_profile_with_avatar(+ wallId,+ profilePayload,+ avatarBytes,+ )) as UpdateWallProfileResponse;+ avatarUrl = URL.createObjectURL(profile.avatarFile);+ } else if (existingWall) {+ updateResponse = (await ctx.update_wall_profile(+ wallId,+ profilePayload,+ )) as UpdateWallProfileResponse;+ avatarUrl = profile.avatarUrl;+ }++ return {+ avatarObjectKey:+ updateResponse?.avatar?.objectKey ?? profile.avatarObjectKey,+ avatarUpdatedAt:+ updateResponse?.avatar?.updatedAt ?? profile.avatarUpdatedAt,+ avatarUrl,+ fullName: profile.fullName.trim(),+ username: wallSlug,+ wallId,+ wallSlug,+ };+ } catch (error) {+ if (wallHTTPStatus(error) == 409) {+ throw new Error("This username is already taken.");+ }+ throw error;+ } finally {+ ctx.free();+ }+};++export const socialProfileErrorMessage = (error: unknown) => {+ const status = wallHTTPStatus(error);+ if (status == 409) return "This username is already taken.";+ if (status == 400) {+ const message = error instanceof Error ? error.message : "";+ if (message.toLowerCase().includes("reserved")) {+ return "This username is reserved.";+ }+ return "That username is not available. Please choose another.";+ }+ if (status == 401) return "Your session expired. Please sign in again.";+ if (status == 403) return "You do not have access to update this profile.";+ return error instanceof Error+ ? error.message+ : "Couldn't save your profile. Please try again.";+};diff --git a/web/apps/social/src/services/socialSignup.ts b/web/apps/social/src/services/socialSignup.tsindex 212baf0890..fdfe7c6d79 100644--- a/web/apps/social/src/services/socialSignup.ts+++ b/web/apps/social/src/services/socialSignup.ts@@ -27,6 +27,7 @@ import {sendOTT,verifyEmail,} from "ente-accounts-rs/services/user";+import { isMuseumHTTPError } from "ente-base/http";import { saveAuthToken } from "ente-base/token";export interface SocialSignupInput {@@ -112,3 +113,12 @@ export const completeSocialSignup = async (email: string, code: string) => {export const resendSocialSignupCode = (email: string) =>sendOTT(email.trim(), "signup");++export const socialSignupErrorMessage = async (error: unknown) => {+ if (await isMuseumHTTPError(error, 409, "USER_ALREADY_REGISTERED")) {+ return "This email already has an account. Please sign in.";+ }+ return error instanceof Error+ ? error.message+ : "Couldn't create account. Please try again.";+};diff --git a/web/apps/social/src/state/SocialAppStateProvider.tsx b/web/apps/social/src/state/SocialAppStateProvider.tsxindex 2f5bf7af5d..75c3178b52 100644--- a/web/apps/social/src/state/SocialAppStateProvider.tsx+++ b/web/apps/social/src/state/SocialAppStateProvider.tsx@@ -1,11 +1,22 @@-import React, { useCallback, useMemo, useState } from "react";+import React, {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";import type { SocialLoginCredentials } from "screens/LoginScreen";import type { SetupProfile } from "screens/SetupProfileScreen";import type { PendingSocialPasskeyVerification } from "services/socialPasskeyVerification";+import {+ loadExistingSocialAvatar,+ loadExistingSocialProfile,+} from "services/socialProfile";import {type OnboardingEntrySource,type SocialAppState,SocialAppStateContext,+ type SocialProfileLoadStatus,initialFriends,} from "state/socialAppState";@@ -22,15 +33,98 @@ export const SocialAppStateProvider: React.FC<React.PropsWithChildren> = ({const [pendingPasskeyVerification, setPendingPasskeyVerification] =useState<PendingSocialPasskeyVerification | null>(null);const [profile, setProfile] = useState<SetupProfile | null>(null);+ const [profileLoadStatus, setProfileLoadStatus] =+ useState<SocialProfileLoadStatus>("loading");const [signupEmail, setSignupEmail] = useState("");+ const avatarURLRef = useRef<string | null>(null);+ const profileRef = useRef<SetupProfile | null>(null);+ const profileLoadGenerationRef = useRef(0);++ const applyProfile = useCallback((nextProfile: SetupProfile | null) => {+ const previousAvatarURL = avatarURLRef.current;+ if (previousAvatarURL && previousAvatarURL != nextProfile?.avatarUrl) {+ URL.revokeObjectURL(previousAvatarURL);+ }+ avatarURLRef.current = nextProfile?.avatarUrl?.startsWith("blob:")+ ? nextProfile.avatarUrl+ : null;+ profileRef.current = nextProfile;+ setProfile(nextProfile);+ }, []);++ const loadProfileAvatar = useCallback(+ async (profileToHydrate: SetupProfile | null, generation: number) => {+ if (+ !profileToHydrate?.avatarObjectKey ||+ profileToHydrate.avatarUrl+ ) {+ return;+ }++ try {+ const avatarUrl = await loadExistingSocialAvatar(+ profileToHydrate.wallId,+ profileToHydrate.avatarObjectKey,+ );+ if (!avatarUrl) return;++ const currentProfile = profileRef.current;+ if (+ profileLoadGenerationRef.current != generation ||+ !currentProfile ||+ currentProfile.wallId != profileToHydrate.wallId ||+ currentProfile.avatarObjectKey !=+ profileToHydrate.avatarObjectKey+ ) {+ URL.revokeObjectURL(avatarUrl);+ return;+ }++ applyProfile({ ...currentProfile, avatarUrl });+ } catch (error) {+ console.warn("Failed to load social avatar", error);+ }+ },+ [applyProfile],+ );++ const refreshProfile = useCallback(async () => {+ const generation = ++profileLoadGenerationRef.current;+ setProfileLoadStatus("loading");++ try {+ const nextProfile = await loadExistingSocialProfile();+ if (profileLoadGenerationRef.current == generation) {+ applyProfile(nextProfile);+ void loadProfileAvatar(nextProfile, generation);+ }+ return nextProfile;+ } catch (error) {+ console.error("Failed to load social profile", error);+ if (profileLoadGenerationRef.current == generation) {+ applyProfile(null);+ }+ return null;+ } finally {+ if (profileLoadGenerationRef.current == generation) {+ setProfileLoadStatus("ready");+ }+ }+ }, [applyProfile, loadProfileAvatar]);const resetAfterLogout = useCallback(() => {- setProfile(null);+ profileLoadGenerationRef.current += 1;+ applyProfile(null);+ setProfileLoadStatus("ready");setPendingLoginCredentials(null);setPendingPasskeyVerification(null);setOnboardingEntrySource("direct");setFriends(initialFriends());- }, []);+ }, [applyProfile]);++ useEffect(() => {+ void refreshProfile();+ }, [refreshProfile]);const value = useMemo<SocialAppState>(() => ({@@ -40,13 +134,15 @@ export const SocialAppStateProvider: React.FC<React.PropsWithChildren> = ({pendingLoginCredentials,pendingPasskeyVerification,profile,+ profileLoadStatus,+ refreshProfile,resetAfterLogout,setFriends,setIsLiveSignupVerification,setOnboardingEntrySource,setPendingLoginCredentials,setPendingPasskeyVerification,- setProfile,+ setProfile: applyProfile,setSignupEmail,signupEmail,}),@@ -57,8 +153,11 @@ export const SocialAppStateProvider: React.FC<React.PropsWithChildren> = ({pendingLoginCredentials,pendingPasskeyVerification,profile,+ profileLoadStatus,+ refreshProfile,resetAfterLogout,signupEmail,+ applyProfile,],);diff --git a/web/apps/social/src/state/socialAppState.tsx b/web/apps/social/src/state/socialAppState.tsxindex 601edd9ab7..c9b31d3726 100644--- a/web/apps/social/src/state/socialAppState.tsx+++ b/web/apps/social/src/state/socialAppState.tsx@@ -5,6 +5,7 @@ import type { SetupProfile } from "screens/SetupProfileScreen";import type { PendingSocialPasskeyVerification } from "services/socialPasskeyVerification";export type OnboardingEntrySource = "direct" | "add-friend-link";+export type SocialProfileLoadStatus = "loading" | "ready";export interface SocialAppState {friends: FriendProfile[];@@ -13,7 +14,9 @@ export interface SocialAppState {pendingLoginCredentials: SocialLoginCredentials | null;pendingPasskeyVerification: PendingSocialPasskeyVerification | null;profile: SetupProfile | null;+ profileLoadStatus: SocialProfileLoadStatus;signupEmail: string;+ refreshProfile: () => Promise<SetupProfile | null>;resetAfterLogout: () => void;setFriends: React.Dispatch<React.SetStateAction<FriendProfile[]>>;setIsLiveSignupVerification: React.Dispatch<React.SetStateAction<boolean>>;@@ -26,7 +29,7 @@ export interface SocialAppState {setPendingPasskeyVerification: React.Dispatch<React.SetStateAction<PendingSocialPasskeyVerification | null>>;- setProfile: React.Dispatch<React.SetStateAction<SetupProfile | null>>;+ setProfile: (profile: SetupProfile | null) => void;setSignupEmail: React.Dispatch<React.SetStateAction<string>>;}diff --git a/web/apps/social/src/utils/socialDisplay.ts b/web/apps/social/src/utils/socialDisplay.tsindex b561c53463..810a994fbb 100644--- a/web/apps/social/src/utils/socialDisplay.ts+++ b/web/apps/social/src/utils/socialDisplay.ts@@ -5,7 +5,7 @@ export const initialsFor = (name: string) =>name.trim().split(/\s+/)- .slice(0, 2)+ .slice(0, 1).map((part) => part[0]?.toUpperCase()).join("");diff --git a/web/packages/accounts-rs/services/redirect.ts b/web/packages/accounts-rs/services/redirect.tsindex 5b601c08a5..ef87bef8bb 100644--- a/web/packages/accounts-rs/services/redirect.ts+++ b/web/packages/accounts-rs/services/redirect.ts@@ -15,6 +15,7 @@ export const appHomeRoute: string = {photos: "/gallery",ensu: "/",locker: "/locker",+ social: "/app",}[appName];let _stashedRedirect: string | undefined;diff --git a/web/packages/accounts/services/redirect.ts b/web/packages/accounts/services/redirect.tsindex 5b601c08a5..ef87bef8bb 100644--- a/web/packages/accounts/services/redirect.ts+++ b/web/packages/accounts/services/redirect.ts@@ -15,6 +15,7 @@ export const appHomeRoute: string = {photos: "/gallery",ensu: "/",locker: "/locker",+ social: "/app",}[appName];let _stashedRedirect: string | undefined;diff --git a/web/packages/base/app.ts b/web/packages/base/app.tsindex 0556caaca9..5a6ddcf7dd 100644--- a/web/packages/base/app.ts+++ b/web/packages/base/app.ts@@ -8,6 +8,7 @@ export const appNames = ["photos","ensu","locker",+ "social",] as const;/**@@ -73,6 +74,7 @@ export const staticAppTitle = {// Ensu (chat) web app.ensu: "Ensu",locker: "Ente Locker",+ social: "Ente Social",}[appName];/**@@ -100,6 +102,7 @@ export const clientPackageName = (() => {// Ensu (chat) web app.ensu: "io.ente.ensu",locker: "io.ente.locker.web",+ social: "io.ente.social.web",}[appName];})();