π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Add Space web push notifications and PWA prompts
Anand Baburajan7a290f2f7ae6
diff --git a/rust/bindings/wasm/space/src/space.rs b/rust/bindings/wasm/space/src/space.rsindex bb90dc1459..17499043f4 100644--- a/rust/bindings/wasm/space/src/space.rs+++ b/rust/bindings/wasm/space/src/space.rs@@ -600,6 +600,29 @@ impl SpaceLinkCtxHandle {.map_err(Into::into)}+ /// Subscribe this browser to new posts from the linked Space.+ #[wasm_bindgen(js_name = subscribeWebPush)]+ pub async fn subscribe_web_push(+ &self,+ endpoint: String,+ p256dh: String,+ auth: String,+ ) -> Result<String, WasmSpaceError> {+ self.inner+ .subscribe_web_push(&endpoint, &p256dh, &auth)+ .await+ .map_err(Into::into)+ }++ /// Remove this linked Space from the browser's push targets.+ #[wasm_bindgen(js_name = unsubscribeWebPush)]+ pub async fn unsubscribe_web_push(&self, endpoint: String) -> Result<(), WasmSpaceError> {+ self.inner+ .unsubscribe_web_push(&endpoint)+ .await+ .map_err(Into::into)+ }+/// Download and decrypt one post photo.#[wasm_bindgen(js_name = downloadPostAsset)]pub async fn download_post_asset(diff --git a/rust/space/src/client/links.rs b/rust/space/src/client/links.rsindex 48085e76ea..0024184590 100644--- a/rust/space/src/client/links.rs+++ b/rust/space/src/client/links.rs@@ -16,7 +16,8 @@ use crate::{transport::{AssetDownloadResponse, PostPage, PostResponse, SpaceKeyVersionResponse,SpaceLinkBootstrapResponse, SpaceLinkProfileResponse, SpaceLinkStatusResponse,- SpaceLinkWriteRequest,+ SpaceLinkWriteRequest, WebPushSubscriptionKeys, WebPushSubscriptionRequest,+ WebPushTargetResponse, WebPushUnsubscriptionRequest,},};@@ -259,6 +260,44 @@ impl SpaceLinkCtx {Ok(page)}+ pub async fn subscribe_web_push(+ &self,+ endpoint: &str,+ p256dh: &str,+ auth: &str,+ ) -> Result<String> {+ let response: WebPushTargetResponse = self+ .api+ .put(&format!("{}/push/subscription", self.prefix()))+ .header(AUTH_HEADER, &self.auth_key)+ .json(&WebPushSubscriptionRequest {+ endpoint: endpoint.to_owned(),+ keys: WebPushSubscriptionKeys {+ p256dh: p256dh.to_owned(),+ auth: auth.to_owned(),+ },+ })+ .send()+ .await?+ .error_for_status()?+ .json()+ .await?;+ Ok(response.target_id)+ }++ pub async fn unsubscribe_web_push(&self, endpoint: &str) -> Result<()> {+ self.api+ .delete(&format!("{}/push/subscription", self.prefix()))+ .header(AUTH_HEADER, &self.auth_key)+ .json(&WebPushUnsubscriptionRequest {+ endpoint: endpoint.to_owned(),+ })+ .send()+ .await?+ .error_for_status()?;+ Ok(())+ }+pub fn decrypt_post(&self, post: &PostResponse) -> Result<DecryptedPost> {let space_key = self.space_key(post.key_version, "post")?;let post_key =@@ -473,7 +512,7 @@ fn derive_link_keys_with_salt(#[cfg(test)]mod tests {use super::*;- use mockito::Server;+ use mockito::{Matcher, Server};use serde_json::json;#[test]@@ -559,6 +598,29 @@ mod tests {).create_async().await;+ let subscribe = server+ .mock("PUT", format!("{prefix}/push/subscription").as_str())+ .match_header("x-ente-space-link-auth", auth.as_str())+ .match_body(Matcher::Json(json!({+ "endpoint": "https://push.example/subscription",+ "keys": {+ "p256dh": "p256dh",+ "auth": "auth"+ }+ })))+ .with_status(200)+ .with_body(json!({"targetId": "wpt_target"}).to_string())+ .create_async()+ .await;+ let unsubscribe = server+ .mock("DELETE", format!("{prefix}/push/subscription").as_str())+ .match_header("x-ente-space-link-auth", auth.as_str())+ .match_body(Matcher::Json(json!({+ "endpoint": "https://push.example/subscription"+ })))+ .with_status(204)+ .create_async()+ .await;let ctx = SpaceLinkCtx::open(OpenSpaceLinkCtxInput {base_url: server.url(),@@ -574,8 +636,19 @@ mod tests {assert_eq!(ctx.profile().profile, profile);assert_eq!(ctx.profile().friends, 2);assert_eq!(ctx.posts(), 3);+ assert_eq!(+ ctx.subscribe_web_push("https://push.example/subscription", "p256dh", "auth")+ .await+ .unwrap(),+ "wpt_target"+ );+ ctx.unsubscribe_web_push("https://push.example/subscription")+ .await+ .unwrap();bootstrap.assert_async().await;profile_request.assert_async().await;versions.assert_async().await;+ subscribe.assert_async().await;+ unsubscribe.assert_async().await;}}diff --git a/rust/space/src/transport.rs b/rust/space/src/transport.rsindex a85fb54fc6..9d3c333c31 100644--- a/rust/space/src/transport.rs+++ b/rust/space/src/transport.rs@@ -406,6 +406,32 @@ pub struct SpaceLinkProfileResponse {pub profile: SpaceProfileResponse,}+#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct WebPushSubscriptionKeys {+ pub p256dh: String,+ pub auth: String,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct WebPushSubscriptionRequest {+ pub endpoint: String,+ pub keys: WebPushSubscriptionKeys,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct WebPushUnsubscriptionRequest {+ pub endpoint: String,+}++#[derive(Debug, Clone, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct WebPushTargetResponse {+ pub target_id: String,+}+#[cfg(test)]mod tests {use super::{diff --git a/server/cmd/museum/main.go b/server/cmd/museum/main.goindex 4f836c4afa..e9cc77e9ad 100644--- a/server/cmd/museum/main.go+++ b/server/cmd/museum/main.go@@ -989,7 +989,7 @@ func main() {userEntityHandler := &api.UserEntityHandler{Controller: userEntityController}spaceRepos := spacerepo.NewModule(db, s3Config)userController.SpaceAccessResetter = spaceRepos- spaceModule := spacecontroller.NewModule(spaceRepos, userAuthRepo, spacecontroller.NewSpaceEmailSender(userRepo))+ spaceModule := spacecontroller.NewModule(spaceRepos, userAuthRepo, spacecontroller.NewSpaceWebPushSender(spaceRepos.WebPush))spaceModule.Posts.AbuseNotifier = discordControllerspaceDripController := spacecontroller.NewSpaceDripController(spaceRepos, userRepo, notificationHistoryRepo, lockController)spaceModule.UserTokens = userControllerdiff --git a/server/config/example.yaml b/server/config/example.yamlindex a2353273c9..a5a162521e 100644--- a/server/config/example.yaml+++ b/server/config/example.yaml@@ -66,6 +66,12 @@ space:# Bucket ID used for Space post, avatar, and cover uploads.# If omitted, Space asset uploads return SPACE_ASSETS_UNAVAILABLE.primaryBucket: b2-eu-cen+ webPush:+ # Generate once with `go run tools/gen-vapid-keys/main.go` and keep the pair stable.+ publicKey:+ privateKey:+ # Bare email address. webpush-go adds the mailto: prefix.+ subscriber:# Key used for encrypting customer emails before storing them in DB#diff --git a/server/go.mod b/server/go.modindex 0e95023661..30721c19d9 100644--- a/server/go.mod+++ b/server/go.mod@@ -5,6 +5,7 @@ go 1.26.0toolchain go1.26.5require (+ github.com/SherClockHolmes/webpush-go v1.4.0github.com/TwiN/go-away v1.6.13github.com/avct/uasurfer v0.0.0-20191028135549-26b5daa857f1github.com/awa/go-iap v1.3.16diff --git a/server/go.sum b/server/go.sumindex a5cd4d80c9..9cb95f0a5a 100644--- a/server/go.sum+++ b/server/go.sum@@ -52,6 +52,8 @@ github.com/ClickHouse/clickhouse-go v1.3.12/go.mod h1:EaI/sW7Azgz9UATzd5ZdZHRUhHgithub.com/Microsoft/go-winio v0.4.11/go.mod h1:VhR8bwka0BXejwEJY73c50VrPtXAaKcyvVC4A4RozmA=github.com/Microsoft/go-winio v0.4.14 h1:+hMXMk01us9KgxGb7ftKQt2Xpf5hH/yky+TDA+qxleU=github.com/Microsoft/go-winio v0.4.14/go.mod h1:qXqCSQ3Xa7+6tgxaGTIe4Kpcdsi+P8jBhyzoq1bpyYA=+github.com/SherClockHolmes/webpush-go v1.4.0 h1:ocnzNKWN23T9nvHi6IfyrQjkIc0oJWv1B1pULsf9i3s=+github.com/SherClockHolmes/webpush-go v1.4.0/go.mod h1:XSq8pKX11vNV8MJEMwjrlTkxhAj1zKfxmyhdV7Pd6UA=github.com/TwiN/go-away v1.6.13 h1:aB6l/FPXmA5ds+V7I9zdhxzpsLLUvVtEuS++iU/ZmgE=github.com/TwiN/go-away v1.6.13/go.mod h1:MpvIC9Li3minq+CGgbgUDvQ9tDaeW35k5IXZrF9MVas=github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=@@ -223,6 +225,7 @@ github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=github.com/golang-jwt/jwt/v4 v4.5.2 h1:YtQM7lnr8iZ+j5q71MGKkNw9Mn7AjHM68uc9g5fXeUI=github.com/golang-jwt/jwt/v4 v4.5.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=+github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8=github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=github.com/golang-migrate/migrate/v4 v4.12.2 h1:QI43Tlouiwpp2dK5Y767OouX0snJNRP/NubsVaArzDU=@@ -279,6 +282,7 @@ github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=+github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=github.com/google/go-github v17.0.0+incompatible/go.mod h1:zLgOLi98H3fifZn+44m+umXrS52loVEgC2AApnigrVQ=@@ -669,6 +673,10 @@ golang.org/x/crypto v0.0.0-20200709230013-948cd5f35899/go.mod h1:LzIPMQfyMNhhGPhgolang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=golang.org/x/crypto v0.0.0-20220314234659-1baeb1ce4c0b/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=+golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=+golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=+golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=+golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto=golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio=golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=@@ -707,6 +715,10 @@ golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=+golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=+golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=+golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=+golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=@@ -755,6 +767,11 @@ golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420/go.mod h1:9nx3DQGgdP8bBQD5qxgolang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=+golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=+golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=+golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=+golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=+golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o=golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec=golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=@@ -785,6 +802,11 @@ golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJgolang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=+golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=+golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=+golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=+golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=+golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=@@ -855,11 +877,24 @@ golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBcgolang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=+golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=+golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=+golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=+golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=+golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=+golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=+golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=+golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=+golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=@@ -870,6 +905,12 @@ golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=+golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=+golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=+golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=+golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=+golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=+golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=golang.org/x/text v0.39.0 h1:UbZz4pLOvn600D6Oh6GGEI6VAmndrEBLv8/6BEXzyus=golang.org/x/text v0.39.0/go.mod h1:3UwRclnC2g0TU9x8PZiyfOajCd1zaUNHF9cvqcQZ+ZM=golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=@@ -938,6 +979,9 @@ golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0=golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=+golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=+golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=+golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=golang.org/x/xerrors v0.0.0-20190410155217-1f06c39b4373/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=diff --git a/server/mail-templates/space_notification.html b/server/mail-templates/space_notification.htmldeleted file mode 100644index 200f811a95..0000000000--- a/server/mail-templates/space_notification.html+++ /dev/null@@ -1,103 +0,0 @@-<!DOCTYPE html>-<html>-<head>-<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />-<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />-<title>Ente Space notification</title>-<style>- @media screen and (max-width: 480px) {- .space-shell {- padding-left: 12px !important;- padding-right: 12px !important;- }-- .space-card {- padding-left: 18px !important;- padding-right: 18px !important;- }- }-- .footer-icons {- padding: 4px !important;- width: 24px !important;- }-</style>-</head>-<body style="background-color: #f0f1f3; color: #232323; font-family: 'Helvetica Neue', Arial, Helvetica, sans-serif; margin: 0; padding: 0; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;">-<table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#f0f1f3" style="background-color: #f0f1f3; border-collapse: collapse; margin: 0; width: 100%;">- <tr>- <td align="center" class="space-shell" style="padding: 48px 20px 0;">- <table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="border-collapse: separate; border-spacing: 0; max-width: 364px; width: 100%;">- <tr>- <td align="center" class="space-card" bgcolor="#ffffff" style="background-color: #ffffff; border-radius: 32px; color: #232323; font-family: 'Helvetica Neue', Arial, Helvetica, sans-serif; padding: 34px 22px 22px; text-align: center;">- <table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="border-collapse: collapse; width: 100%;">- {{if .IllustrationURL}}- <tr>- <td align="center" style="padding: 0 0 24px;">- <img src="{{ .IllustrationURL }}" width="{{ .IllustrationWidth }}" alt="" style="border: 0; display: block; height: auto; margin: 0 auto; max-width: 100%; outline: none; text-decoration: none; width: {{ .IllustrationWidth }}px;" />- </td>- </tr>- {{end}}- <tr>- <td align="center" style="color: #232323; font-family: 'Helvetica Neue', Arial, Helvetica, sans-serif; font-size: 26px; font-weight: 800; line-height: 30px; padding: 0 0 4px; text-align: center;">- {{ .ActorLabel }}- </td>- </tr>- <tr>- <td align="center" style="color: #6b6b6b; font-family: 'Helvetica Neue', Arial, Helvetica, sans-serif; font-size: 15px; line-height: 21px; padding: 0 0 28px; text-align: center;">- {{ .Notification }}- </td>- </tr>- <tr>- <td align="center">- <table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="border-collapse: separate; border-spacing: 0; width: 100%;">- <tr>- <td align="center" bgcolor="#08C225" style="background-color: #08C225; border-radius: 16px;">- <a href="{{ .AppURL }}" target="_blank" style="background-color: #08C225; border-radius: 16px; color: #ffffff !important; display: block; font-family: 'Helvetica Neue', Arial, Helvetica, sans-serif; font-size: 14px; font-weight: 700; line-height: 20px; padding: 16px 28px; text-align: center; text-decoration: none !important;">Open Ente Space</a>- </td>- </tr>- </table>- </td>- </tr>- </table>- </td>- </tr>- </table>- </td>- </tr>-</table>-<br />-<div class="footer" style="text-align: center; font-size: 12px; color:- rgb(136, 136, 136)" >- <div>- <a href="https://ente.com" target="_blank" ><img- src="https://email-assets.ente.com/ente-2026-green.png" style="width: 100px;- padding: 24px" title="Ente" alt="Ente" /></a>- </div>- <div>- <a href="https://fosstodon.org/@ente" target="_blank" ><img- src="https://email-assets.ente.com/mastodon-icon.png"- class="footer-icons" style="width: 24px; padding: 4px" title="Mastodon"- alt="Mastodon" /></a>- <a href="https://twitter.com/enteio" target="_blank" ><img- src="https://email-assets.ente.com/twitter-icon.png" class="footer-icons"- style="width: 24px; padding: 4px" title="Twitter" alt="Twitter" /></a>- <a href="https://ente.com/discord" target="_blank" ><img- src="https://email-assets.ente.com/discord-icon.png" class="footer-icons"- style="width: 24px; padding: 4px" title="Discord" alt="Discord" /></a>- <a href="https://github.com/ente-io" target="_blank" ><img- src="https://email-assets.ente.com/github-icon.png" class="footer-icons"- style="width: 24px; padding: 4px" title="GitHub" alt="GitHub" /></a>-- <a href="https://www.youtube.com/@entestudio" target="_blank" ><img- src="https://email-assets.ente.com/youtube-icon.png" class="footer-icons"- style="width: 24px; padding: 4px" title="YouTube" alt="YouTube" /></a>- </div>- <p>- Ente Technologies, Inc.- <br /> 1111B S Governors Ave 6032 Dover, DE 19904- </p>- <br />-</div>-</body>-</html>diff --git a/server/migrations/130_space_web_push.down.sql b/server/migrations/130_space_web_push.down.sqlnew file mode 100644index 0000000000..e61a287590--- /dev/null+++ b/server/migrations/130_space_web_push.down.sql@@ -0,0 +1,2 @@+DROP TRIGGER IF EXISTS update_space_web_push_subscriptions_updated_at ON space_web_push_subscriptions;+DROP TABLE IF EXISTS space_web_push_subscriptions;diff --git a/server/migrations/130_space_web_push.up.sql b/server/migrations/130_space_web_push.up.sqlnew file mode 100644index 0000000000..dbabbd3bea--- /dev/null+++ b/server/migrations/130_space_web_push.up.sql@@ -0,0 +1,31 @@+CREATE TABLE IF NOT EXISTS space_web_push_subscriptions (+ target_id TEXT PRIMARY KEY,+ endpoint TEXT NOT NULL,+ session_token_hash BYTEA UNIQUE+ REFERENCES space_browser_sessions (token_hash) ON DELETE CASCADE,+ link_id BIGINT+ REFERENCES space_links (link_id) ON DELETE CASCADE,+ p256dh TEXT NOT NULL,+ auth TEXT NOT NULL,+ created_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),+ updated_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),+ CONSTRAINT chk_space_web_push_subscription_target CHECK (+ (session_token_hash IS NOT NULL AND link_id IS NULL)+ OR+ (session_token_hash IS NULL AND link_id IS NOT NULL)+ ),+ CONSTRAINT uq_space_web_push_link UNIQUE (endpoint, link_id)+);++CREATE UNIQUE INDEX uq_space_web_push_account_endpoint+ ON space_web_push_subscriptions (endpoint)+ WHERE session_token_hash IS NOT NULL;++CREATE INDEX idx_space_web_push_link+ ON space_web_push_subscriptions (link_id)+ WHERE link_id IS NOT NULL;++CREATE TRIGGER update_space_web_push_subscriptions_updated_at+ BEFORE UPDATE ON space_web_push_subscriptions+ FOR EACH ROW+EXECUTE PROCEDURE trigger_updated_at_microseconds_column();diff --git a/server/pkg/middleware/event_test.go b/server/pkg/middleware/event_test.goindex 0c754e7f54..1f67c0092c 100644--- a/server/pkg/middleware/event_test.go+++ b/server/pkg/middleware/event_test.go@@ -63,6 +63,7 @@ func TestSpaceRoutesUseRouteSpecificRateLimits(t *testing.T) {require.Same(t, limit200ReqPerMin, rateLimiter.getLimiter("/space/public/by-slug/:spaceSlug/link/posts", http.MethodGet))require.Same(t, limit200ReqPerMin, rateLimiter.getLimiter("/space/public/by-slug/:spaceSlug/link/versions", http.MethodGet))require.Same(t, limit500ReqPerMin, rateLimiter.getLimiter("/space/public/by-slug/:spaceSlug/link/assets/redirect", http.MethodGet))+ require.Same(t, limit10ReqPerMin, rateLimiter.getLimiter("/space/public/by-slug/:spaceSlug/link/push/subscription", http.MethodPut))require.Same(t, limit10ReqPerMin, rateLimiter.getLimiter("/spaces/:spaceID/uploads/presign", http.MethodPost))require.Same(t, limit200ReqPerMin, rateLimiter.getLimiter("/spaces/:spaceID/profile", http.MethodGet))require.Same(t, limit500ReqPerMin, rateLimiter.getLimiter("/spaces/:spaceID/assets/redirect", http.MethodGet))diff --git a/server/pkg/middleware/rate_limit.go b/server/pkg/middleware/rate_limit.goindex 4ea370811a..fe02badd23 100644--- a/server/pkg/middleware/rate_limit.go+++ b/server/pkg/middleware/rate_limit.go@@ -227,6 +227,10 @@ func (r *RateLimitMiddleware) getLimiter(reqPath string, reqMethod string) *limiif reqPath == "/space/public/by-slug/:spaceSlug/link/assets/redirect" {return r.limit500ReqPerMin}+ if reqPath == "/space/public/by-slug/:spaceSlug/link/push/subscription" &&+ reqMethod == http.MethodPut {+ return r.limit10ReqPerMin+ }if reqPath == "/spaces/:spaceID/uploads/presign" && reqMethod == http.MethodPost {return r.limit10ReqPerMin}diff --git a/server/pkg/utils/email/space_notification_template_test.go b/server/pkg/utils/email/space_notification_template_test.godeleted file mode 100644index 8542c6c62c..0000000000--- a/server/pkg/utils/email/space_notification_template_test.go+++ /dev/null@@ -1,73 +0,0 @@-package email--import (- "testing"-- "github.com/ente/museum/internal/testutil"- "github.com/stretchr/testify/require"-)--func TestSpaceNotificationTemplateUsesEmailSafeLayout(t *testing.T) {- testutil.WithServerRoot(t)-- body, err := getMailBody("space_notification.html", map[string]interface{}{- "ActorLabel": "@alice",- "AppURL": "https://ente.space/app",- "IllustrationURL": "https://email-assets.ente.com/space-new-post.png",- "IllustrationWidth": 112,- "Notification": "just posted a new photo",- })- require.NoError(t, err)- require.Contains(t, body, `<head>`)- require.Contains(t, body, `role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#f0f1f3"`)- require.Contains(t, body, `bgcolor="#08C225"`)- require.Contains(t, body, `style="background-color: #08C225; border-radius: 16px; color: #ffffff !important; display: block;`)- require.Contains(t, body, "@alice")- require.Contains(t, body, "just posted a new photo")- require.Contains(t, body, `https://email-assets.ente.com/space-new-post.png`)- require.Contains(t, body, `https://email-assets.ente.com/ente-2026-green.png`)- require.Contains(t, body, `padding: 24px" title="Ente"`)- require.Contains(t, body, `class="footer-icons" style="width: 24px; padding: 4px"`)-}--func TestSpaceDripTemplateRendersCTAAndBody(t *testing.T) {- testutil.WithServerRoot(t)-- body, err := getMailBody("space_drip.html", map[string]interface{}{- "BodyLines": []string{- "Hey,",- "Your Ente Space profile is still unfinished.",- },- "CTAURL": "https://ente.space/app",- "CTALabel": "Finish setup",- })- require.NoError(t, err)- require.Contains(t, body, `role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#f0f1f3"`)- require.Contains(t, body, `max-width: 420px; width: 100%;`)- require.Contains(t, body, `align="left" style="color: #5f5f5f;`)- require.Contains(t, body, "Your Ente Space profile is still unfinished.")- require.Contains(t, body, `style="border-collapse: separate; border-spacing: 0; width: 100%;"`)- require.Contains(t, body, `href="https://ente.space/app"`)- require.Contains(t, body, "Finish setup")- require.Contains(t, body, `https://email-assets.ente.com/ente-2026-green.png`)- require.Contains(t, body, `class="footer-icons" style="width: 24px; padding: 4px"`)- require.Contains(t, body, "Ente Technologies, Inc.")-}--func TestSpaceDripTemplateOmitsCTAWithoutLabel(t *testing.T) {- testutil.WithServerRoot(t)-- body, err := getMailBody("space_drip.html", map[string]interface{}{- "BodyLines": []string{- "Hey,",- "Reply to this email or drop a message on our Discord!",- },- "CTAURL": "https://ente.space/app",- })- require.NoError(t, err)- require.Contains(t, body, "Reply to this email or drop a message on our Discord!")- require.Contains(t, body, `padding: 0 0 0; text-align: left;`)- require.NotContains(t, body, `href="https://ente.space/app"`)- require.NotContains(t, body, `Open Ente Space`)- require.Contains(t, body, `https://email-assets.ente.com/ente-2026-green.png`)-}diff --git a/server/space/api/register.go b/server/space/api/register.goindex a88cc5e0b0..3d4d131e3c 100644--- a/server/space/api/register.go+++ b/server/space/api/register.go@@ -5,6 +5,9 @@ import "github.com/gin-gonic/gin"func Register(privateAPI, publicAPI gin.IRouter, handlers *Handlers) {privateAPI.GET("/account/space", handlers.ListSpaces)privateAPI.POST("/account/space", handlers.CreateSpace)+ privateAPI.GET("/account/space/push/vapid-key", handlers.GetWebPushVAPIDKey)+ privateAPI.PUT("/account/space/push/subscription", handlers.UpsertWebPushSubscription)+ privateAPI.DELETE("/account/space/push/subscription", handlers.DeleteWebPushSubscription)spaceAPI := privateAPI.Group("/spaces/:spaceID", handlers.RequireSelectedSpace())selected := handlers.withSelectedSpace@@ -54,6 +57,9 @@ func Register(privateAPI, publicAPI gin.IRouter, handlers *Handlers) {publicAPI.GET("/space/public/by-slug/:spaceSlug/link/posts", handlers.SpaceLinkPosts)publicAPI.GET("/space/public/by-slug/:spaceSlug/link/versions", handlers.SpaceLinkVersions)publicAPI.GET("/space/public/by-slug/:spaceSlug/link/assets/redirect", handlers.SpaceLinkAssetRedirect)+ publicAPI.GET("/space/push/vapid-key", handlers.GetWebPushVAPIDKey)+ publicAPI.PUT("/space/public/by-slug/:spaceSlug/link/push/subscription", handlers.UpsertSpaceLinkWebPushSubscription)+ publicAPI.DELETE("/space/public/by-slug/:spaceSlug/link/push/subscription", handlers.DeleteSpaceLinkWebPushSubscription)publicAPI.POST("/account/space/sessions/bootstrap", handlers.BootstrapBrowserSession)publicAPI.DELETE("/account/space/sessions/current", handlers.DeleteBrowserSession)}diff --git a/server/space/api/web_push.go b/server/space/api/web_push.gonew file mode 100644index 0000000000..75466a3315--- /dev/null+++ b/server/space/api/web_push.go@@ -0,0 +1,52 @@+package api++import (+ "strings"++ "github.com/ente/museum/space/controller"+ "github.com/ente/museum/space/models"+ "github.com/gin-gonic/gin"+)++func (h *Handlers) GetWebPushVAPIDKey(c *gin.Context) {+ resp, err := h.Module.WebPush.VAPIDPublicKey()+ respondJSON(c, resp, err)+}++func (h *Handlers) UpsertWebPushSubscription(c *gin.Context) {+ var req models.SpaceWebPushSubscriptionRequest+ if !bindJSON(c, &req) {+ return+ }+ sessionToken := strings.TrimSpace(c.GetHeader(controller.SpaceBrowserSessionTokenHeader))+ resp, err := h.Module.WebPush.UpsertAccountSubscription(c, sessionToken, req)+ respondJSON(c, resp, err)+}++func (h *Handlers) DeleteWebPushSubscription(c *gin.Context) {+ var req models.SpaceWebPushUnsubscriptionRequest+ if !bindJSON(c, &req) {+ return+ }+ sessionToken := strings.TrimSpace(c.GetHeader(controller.SpaceBrowserSessionTokenHeader))+ err := h.Module.WebPush.DeleteAccountSubscription(c, sessionToken, req)+ respondStatus(c, err)+}++func (h *Handlers) UpsertSpaceLinkWebPushSubscription(c *gin.Context) {+ var req models.SpaceWebPushSubscriptionRequest+ if !bindJSON(c, &req) {+ return+ }+ resp, err := h.Module.WebPush.UpsertLinkSubscription(c, c.Param("spaceSlug"), req)+ respondJSON(c, resp, err)+}++func (h *Handlers) DeleteSpaceLinkWebPushSubscription(c *gin.Context) {+ var req models.SpaceWebPushUnsubscriptionRequest+ if !bindJSON(c, &req) {+ return+ }+ err := h.Module.WebPush.DeleteLinkSubscription(c, c.Param("spaceSlug"), req)+ respondStatus(c, err)+}diff --git a/server/space/api/web_push_test.go b/server/space/api/web_push_test.gonew file mode 100644index 0000000000..599faaaeed--- /dev/null+++ b/server/space/api/web_push_test.go@@ -0,0 +1,113 @@+package api++import (+ "bytes"+ "context"+ "crypto/ecdh"+ "crypto/rand"+ "crypto/sha256"+ "encoding/base64"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"++ webpush "github.com/SherClockHolmes/webpush-go"+ timeutil "github.com/ente/museum/pkg/utils/time"+ "github.com/ente/museum/space/controller"+ "github.com/gin-gonic/gin"+ "github.com/spf13/viper"+ "github.com/stretchr/testify/require"+)++func TestSpaceWebPushAccountSubscriptionAPI(t *testing.T) {+ handlers, repos, userID := setupSpaceSessionAPITest(t)+ sessionToken := "space-web-push-session"+ sessionHash := sha256.Sum256([]byte(sessionToken))+ require.NoError(t, repos.Sessions.CreateBrowserSession(context.Background(), sessionHash[:], userID, "wrap-key", timeutil.NDaysFromNow(1)))+ vapidPublicKey := setSpaceWebPushTestConfig(t)++ publicRouter := gin.New()+ publicRouter.GET("/space/push/vapid-key", handlers.GetWebPushVAPIDKey)+ keyRequest := httptest.NewRequest(http.MethodGet, "/space/push/vapid-key", nil)+ keyRecorder := httptest.NewRecorder()+ publicRouter.ServeHTTP(keyRecorder, keyRequest)+ require.Equal(t, http.StatusOK, keyRecorder.Code)+ require.JSONEq(t, `{"publicKey":"`+vapidPublicKey+`"}`, keyRecorder.Body.String())++ privateKey, err := ecdh.P256().GenerateKey(rand.Reader)+ require.NoError(t, err)+ payload, err := json.Marshal(map[string]any{+ "endpoint": "https://push.example/subscription",+ "keys": map[string]string{+ "p256dh": base64.RawURLEncoding.EncodeToString(privateKey.PublicKey().Bytes()),+ "auth": base64.RawURLEncoding.EncodeToString(make([]byte, 16)),+ },+ })+ require.NoError(t, err)++ privateRouter := gin.New()+ privateRouter.Use(handlers.RequireSpaceBrowserSession())+ privateRouter.PUT("/account/space/push/subscription", handlers.UpsertWebPushSubscription)+ privateRouter.DELETE("/account/space/push/subscription", handlers.DeleteWebPushSubscription)+ subscriptionRequest := httptest.NewRequest(http.MethodPut, "/account/space/push/subscription", bytes.NewReader(payload))+ subscriptionRequest.Header.Set(controller.SpaceBrowserSessionTokenHeader, sessionToken)+ subscriptionRequest.Header.Set("Content-Type", "application/json")+ subscriptionRecorder := httptest.NewRecorder()+ privateRouter.ServeHTTP(subscriptionRecorder, subscriptionRequest)+ require.Equal(t, http.StatusOK, subscriptionRecorder.Code)+ require.Contains(t, subscriptionRecorder.Body.String(), `"targetId":"wpt_`)++ var count int+ require.NoError(t, repos.WebPush.DB.QueryRow(`+ SELECT COUNT(*)+ FROM space_web_push_subscriptions+ WHERE session_token_hash = $1+ `, sessionHash[:]).Scan(&count))+ require.Equal(t, 1, count)++ unsubscriptionPayload, err := json.Marshal(map[string]string{+ "endpoint": "https://push.example/subscription",+ })+ require.NoError(t, err)+ unsubscriptionRequest := httptest.NewRequest(http.MethodDelete, "/account/space/push/subscription", bytes.NewReader(unsubscriptionPayload))+ unsubscriptionRequest.Header.Set(controller.SpaceBrowserSessionTokenHeader, sessionToken)+ unsubscriptionRequest.Header.Set("Content-Type", "application/json")+ unsubscriptionRecorder := httptest.NewRecorder()+ privateRouter.ServeHTTP(unsubscriptionRecorder, unsubscriptionRequest)+ require.Equal(t, http.StatusOK, unsubscriptionRecorder.Code)+ require.NoError(t, repos.WebPush.DB.QueryRow(`+ SELECT COUNT(*)+ FROM space_web_push_subscriptions+ WHERE session_token_hash = $1+ `, sessionHash[:]).Scan(&count))+ require.Zero(t, count)+}++func TestSpaceWebPushVAPIDKeyRequiresCompleteConfig(t *testing.T) {+ handlers, _, _ := setupSpaceSessionAPITest(t)+ setSpaceWebPushTestConfig(t)+ viper.Set("space.webPush.privateKey", "")++ router := gin.New()+ router.GET("/space/push/vapid-key", handlers.GetWebPushVAPIDKey)+ request := httptest.NewRequest(http.MethodGet, "/space/push/vapid-key", nil)+ recorder := httptest.NewRecorder()+ router.ServeHTTP(recorder, request)+ require.Equal(t, http.StatusServiceUnavailable, recorder.Code)+}++func setSpaceWebPushTestConfig(t *testing.T) string {+ t.Helper()+ privateKey, publicKey, err := webpush.GenerateVAPIDKeys()+ require.NoError(t, err)+ viper.Set("space.webPush.publicKey", publicKey)+ viper.Set("space.webPush.privateKey", privateKey)+ viper.Set("space.webPush.subscriber", "[email protected]")+ t.Cleanup(func() {+ viper.Set("space.webPush.publicKey", "")+ viper.Set("space.webPush.privateKey", "")+ viper.Set("space.webPush.subscriber", "")+ })+ return publicKey+}diff --git a/server/space/controller/friends.go b/server/space/controller/friends.goindex 375ec6df74..cef948b9a6 100644--- a/server/space/controller/friends.go+++ b/server/space/controller/friends.go@@ -13,9 +13,9 @@ import ()type FriendsController struct {- FriendsRepo *repo.FriendsRepository- SpacesRepo *repo.SpacesRepository- EmailNotifier SpaceEmailNotifier+ FriendsRepo *repo.FriendsRepository+ SpacesRepo *repo.SpacesRepository+ ActivityNotifier SpaceActivityNotifier}func (c *FriendsController) Add(ctx context.Context, requesterSpace *repo.SpaceRecord, req models.AddFriendPayload) (*models.FriendStatusResponse, error) {@@ -62,13 +62,22 @@ func (c *FriendsController) Add(ctx context.Context, requesterSpace *repo.SpaceRreturn nil, err}if becameFriends {- if c.EmailNotifier != nil {- go c.EmailNotifier.OnSpaceFriendAdded(requesterSpace.OwnerID, requesterSpace.SpaceSlug, request.RequesterID)+ if c.ActivityNotifier != nil {+ go c.ActivityNotifier.OnSpaceFriendAdded(+ requesterSpace.OwnerID,+ requesterSpace.SpaceID,+ requesterSpace.SpaceSlug,+ request.RequesterID,+ )}return &models.FriendStatusResponse{Status: "friend"}, nil}- if created && c.EmailNotifier != nil {- go c.EmailNotifier.OnSpaceFriendRequested(requesterSpace.OwnerID, requesterSpace.SpaceSlug, request.TargetID)+ if created && c.ActivityNotifier != nil {+ go c.ActivityNotifier.OnSpaceFriendRequested(+ requesterSpace.OwnerID,+ requesterSpace.SpaceSlug,+ request.TargetID,+ )}return &models.FriendStatusResponse{Status: "requested"}, nil}@@ -126,8 +135,13 @@ func (c *FriendsController) ConfirmRequest(ctx context.Context, targetSpace *rep}return nil, err}- if created && c.EmailNotifier != nil {- go c.EmailNotifier.OnSpaceFriendAdded(targetSpace.OwnerID, targetSpace.SpaceSlug, requesterID)+ if created && c.ActivityNotifier != nil {+ go c.ActivityNotifier.OnSpaceFriendAdded(+ targetSpace.OwnerID,+ targetSpace.SpaceID,+ targetSpace.SpaceSlug,+ requesterID,+ )}return &models.FriendStatusResponse{Status: "friend"}, nil}diff --git a/server/space/controller/links.go b/server/space/controller/links.goindex ad855962a5..6e02ea4b15 100644--- a/server/space/controller/links.go+++ b/server/space/controller/links.go@@ -195,6 +195,11 @@ func (c *LinksController) authorize(ctx *gin.Context, slug string) (*repo.SpaceLreturn link, space, nil}+func (c *LinksController) Authorize(ctx *gin.Context, slug string) (*repo.SpaceLinkRecord, error) {+ link, _, err := c.authorize(ctx, slug)+ return link, err+}+func (c *LinksController) Profile(ctx *gin.Context, slug string) (*models.SpaceLinkProfileResponse, error) {link, space, err := c.authorize(ctx, slug)if err != nil {diff --git a/server/space/controller/messages.go b/server/space/controller/messages.goindex 80f0a836c3..c659acd24f 100644--- a/server/space/controller/messages.go+++ b/server/space/controller/messages.go@@ -27,13 +27,13 @@ const ()type MessagesController struct {- MessagesRepo *repo.MessagesRepository- PostsRepo *repo.PostsRepository- SpacesRepo *repo.SpacesRepository- FriendsRepo *repo.FriendsRepository- ReadMarkersRepo *repo.ReadMarkersRepository- EmailNotifier SpaceEmailNotifier- auth authDeps+ MessagesRepo *repo.MessagesRepository+ PostsRepo *repo.PostsRepository+ SpacesRepo *repo.SpacesRepository+ FriendsRepo *repo.FriendsRepository+ ReadMarkersRepo *repo.ReadMarkersRepository+ ActivityNotifier SpaceActivityNotifier+ auth authDeps}func (c *MessagesController) Create(ctx context.Context, senderSpace *repo.SpaceRecord, targetSpaceID string, req models.CreateMessageRequest) (*models.MessageResponse, error) {@@ -69,6 +69,14 @@ func (c *MessagesController) Create(ctx context.Context, senderSpace *repo.Space}return nil, err}+ if c.ActivityNotifier != nil {+ go c.ActivityNotifier.OnSpaceMessageSent(+ senderSpace.OwnerID,+ senderSpace.SpaceID,+ senderSpace.SpaceSlug,+ recipientSpace.OwnerID,+ )+ }return toMessageResponse(*message), nil}@@ -118,8 +126,13 @@ func (c *MessagesController) ReplyToPost(ctx context.Context, senderSpace *repo.}return nil, err}- if c.EmailNotifier != nil {- go c.EmailNotifier.OnSpacePostReplied(senderSpace.OwnerID, senderSpace.SpaceSlug, recipientSpace.OwnerID)+ if c.ActivityNotifier != nil {+ go c.ActivityNotifier.OnSpacePostReplied(+ senderSpace.OwnerID,+ senderSpace.SpaceID,+ senderSpace.SpaceSlug,+ recipientSpace.OwnerID,+ )}return toMessageResponse(*message), nil}@@ -220,9 +233,26 @@ func (c *MessagesController) SetLike(ctx context.Context, actorSpace *repo.Space}return nil, err}- if err := c.MessagesRepo.SetLike(ctx, messageID, actorSpace.SpaceID, like); err != nil {+ var recipientUserID int64+ if like && c.ActivityNotifier != nil {+ otherSpace, err := c.SpacesRepo.GetSpaceByID(ctx, otherSpaceID)+ if err != nil {+ return nil, err+ }+ recipientUserID = otherSpace.OwnerID+ }+ changed, err := c.MessagesRepo.SetLikeWithChanged(ctx, messageID, actorSpace.SpaceID, like)+ if err != nil {return nil, err}+ if like && changed && c.ActivityNotifier != nil {+ go c.ActivityNotifier.OnSpaceMessageLiked(+ actorSpace.OwnerID,+ actorSpace.SpaceID,+ actorSpace.SpaceSlug,+ recipientUserID,+ )+ }return &models.LikeMessageResponse{Liked: like}, nil}diff --git a/server/space/controller/module.go b/server/space/controller/module.goindex 3c09e29ee2..cc7faf2144 100644--- a/server/space/controller/module.go+++ b/server/space/controller/module.go@@ -14,6 +14,7 @@ type Module struct {Assets *AssetsControllerRead *ReadMarkersControllerSessions *SessionsController+ WebPush *WebPushControllerCleanup *CleanupControllerLinks *LinksControllerUserTokens UserTokenTerminator@@ -24,10 +25,10 @@ type UserTokenTerminator interface {TerminateSession(userID int64, token string) error}-func NewModule(repos *repo.Module, userAuthRepo *baserepo.UserAuthRepository, emailNotifiers ...SpaceEmailNotifier) *Module {- var emailNotifier SpaceEmailNotifier- if len(emailNotifiers) > 0 {- emailNotifier = emailNotifiers[0]+func NewModule(repos *repo.Module, userAuthRepo *baserepo.UserAuthRepository, activityNotifiers ...SpaceActivityNotifier) *Module {+ var activityNotifier SpaceActivityNotifier+ if len(activityNotifiers) > 0 {+ activityNotifier = activityNotifiers[0]}authDeps := authDeps{UserAuthRepo: userAuthRepo,@@ -36,18 +37,20 @@ func NewModule(repos *repo.Module, userAuthRepo *baserepo.UserAuthRepository, emSessionsRepo: repos.Sessions,}spaces := &SpacesController{SpacesRepo: repos.Spaces, AssetsRepo: repos.Assets, auth: authDeps}- posts := &PostsController{PostsRepo: repos.Posts, SpacesRepo: repos.Spaces, FriendsRepo: repos.Friends, AssetsRepo: repos.Assets, EmailNotifier: emailNotifier, auth: authDeps}+ posts := &PostsController{PostsRepo: repos.Posts, SpacesRepo: repos.Spaces, FriendsRepo: repos.Friends, AssetsRepo: repos.Assets, ActivityNotifier: activityNotifier, auth: authDeps}assets := &AssetsController{AssetsRepo: repos.Assets, SpacesRepo: repos.Spaces, auth: authDeps}+ links := &LinksController{LinksRepo: repos.Links, SpacesRepo: repos.Spaces, FriendsRepo: repos.Friends, Posts: posts, Assets: assets}return &Module{Spaces: spaces,Posts: posts,- Friends: &FriendsController{FriendsRepo: repos.Friends, SpacesRepo: repos.Spaces, EmailNotifier: emailNotifier},- Messages: &MessagesController{MessagesRepo: repos.Messages, PostsRepo: repos.Posts, SpacesRepo: repos.Spaces, FriendsRepo: repos.Friends, ReadMarkersRepo: repos.Read, EmailNotifier: emailNotifier, auth: authDeps},+ Friends: &FriendsController{FriendsRepo: repos.Friends, SpacesRepo: repos.Spaces, ActivityNotifier: activityNotifier},+ Messages: &MessagesController{MessagesRepo: repos.Messages, PostsRepo: repos.Posts, SpacesRepo: repos.Spaces, FriendsRepo: repos.Friends, ReadMarkersRepo: repos.Read, ActivityNotifier: activityNotifier, auth: authDeps},Assets: assets,Read: &ReadMarkersController{ReadMarkersRepo: repos.Read},Sessions: &SessionsController{SessionsRepo: repos.Sessions},+ WebPush: &WebPushController{WebPushRepo: repos.WebPush, Links: links},Cleanup: &CleanupController{AssetsRepo: repos.Assets},- Links: &LinksController{LinksRepo: repos.Links, SpacesRepo: repos.Spaces, FriendsRepo: repos.Friends, Posts: posts, Assets: assets},+ Links: links,auth: authDeps,}}diff --git a/server/space/controller/notifications.go b/server/space/controller/notifications.goindex daaa05d514..0fd0480d56 100644--- a/server/space/controller/notifications.go+++ b/server/space/controller/notifications.go@@ -2,202 +2,326 @@ package controllerimport ("context"+ "encoding/json"+ "errors""fmt"+ "net"+ "net/http"+ "net/url""strconv""strings"+ "sync"+ "time"- baserepo "github.com/ente/museum/pkg/repo"+ webpush "github.com/SherClockHolmes/webpush-go"util "github.com/ente/museum/pkg/utils"- emailutil "github.com/ente/museum/pkg/utils/email"+ "github.com/ente/museum/space/repo"log "github.com/sirupsen/logrus""github.com/spf13/viper""github.com/ulule/limiter/v3")const (- spaceNotificationTemplate = "space_notification.html"- spaceNewPostIllustrationURL = "https://email-assets.ente.com/space-new-post.png"- spaceNewPostLikeIllustrationURL = "https://email-assets.ente.com/space-new-post-like.png"- spaceNewPostReplyIllustrationURL = "https://email-assets.ente.com/space-new-post-reply.png"- spaceNewFriendIllustrationURL = "https://email-assets.ente.com/space-new-friend.png"- spaceNotificationPostCreated = "post_created"- spaceNotificationPostLiked = "post_liked"- spaceNotificationPostReplied = "post_replied"- spaceNotificationFriendAdded = "friend_added"- spaceNotificationFriendRequested = "friend_requested"- spaceNewPostIllustrationWidth = 112- spaceNewPostLikeIllustrationWidth = 132- spaceNewPostReplyIllustrationWidth = 132- spaceNewFriendIllustrationWidth = 220- spaceEmailSendRate = "50-H"+ spaceActivityPostCreated = "post_created"+ spaceActivityPostLiked = "post_liked"+ spaceActivityPostReplied = "post_replied"+ spaceActivityMessageSent = "message_sent"+ spaceActivityMessageLiked = "message_liked"+ spaceActivityFriendAdded = "friend_added"+ spaceActivityFriendRequested = "friend_requested"+ spaceWebPushSendRate = "50-H"+ spaceWebPushTTLSeconds = 24 * 60 * 60+ spaceWebPushSendTimeout = 30 * time.Second+ spaceWebPushConcurrency = 10)-var sendSpaceNotificationEmail = emailutil.SendTemplatedEmail+var sendSpaceWebPush = webpush.SendNotificationWithContext-type SpaceEmailNotifier interface {- OnSpacePostCreated(actorUserID int64, actorSlug string, recipientUserIDs []int64)- OnSpacePostLiked(actorUserID int64, actorSlug string, recipientUserID int64)- OnSpacePostReplied(actorUserID int64, actorSlug string, recipientUserID int64)- OnSpaceFriendAdded(actorUserID int64, actorSlug string, recipientUserID int64)+type SpaceActivityNotifier interface {+ OnSpacePostCreated(actorUserID int64, actorSpaceID, actorSlug string, recipientUserIDs []int64)+ OnSpacePostLiked(actorUserID int64, actorSpaceID, actorSlug string, recipientUserID int64)+ OnSpacePostReplied(actorUserID int64, actorSpaceID, actorSlug string, recipientUserID int64)+ OnSpaceMessageSent(actorUserID int64, actorSpaceID, actorSlug string, recipientUserID int64)+ OnSpaceMessageLiked(actorUserID int64, actorSpaceID, actorSlug string, recipientUserID int64)+ OnSpaceFriendAdded(actorUserID int64, actorSpaceID, actorSlug string, recipientUserID int64)OnSpaceFriendRequested(actorUserID int64, actorSlug string, recipientUserID int64)}-type SpaceEmailSender struct {- UserRepo *baserepo.UserRepository+type SpaceWebPushSender struct {+ WebPushRepo *repo.WebPushRepository+ HTTPClient webpush.HTTPClientsendLimiter *limiter.Limiter+ sendSlots chan struct{}}-func NewSpaceEmailSender(userRepo *baserepo.UserRepository) *SpaceEmailSender {- return &SpaceEmailSender{- UserRepo: userRepo,- sendLimiter: util.NewRateLimiter(spaceEmailSendRate),+type spaceWebPushPayload struct {+ Title string `json:"title"`+ Body string `json:"body"`+ Action string `json:"action,omitempty"`+ URL string `json:"url,omitempty"`+ TargetID string `json:"targetId,omitempty"`+}++func NewSpaceWebPushSender(webPushRepo *repo.WebPushRepository) *SpaceWebPushSender {+ return &SpaceWebPushSender{+ WebPushRepo: webPushRepo,+ HTTPClient: newSpaceWebPushHTTPClient(),+ sendLimiter: util.NewRateLimiter(spaceWebPushSendRate),+ sendSlots: make(chan struct{}, spaceWebPushConcurrency),+ }+}++func (n *SpaceWebPushSender) OnSpacePostCreated(+ actorUserID int64,+ actorSpaceID, actorSlug string,+ recipientUserIDs []int64,+) {+ if !n.available() {+ return}+ subscriptions, err := n.WebPushRepo.ListPostSubscriptions(+ context.Background(),+ actorSpaceID,+ uniqueUserIDs(recipientUserIDs),+ )+ if err != nil {+ log.WithField("event", spaceActivityPostCreated).WithError(err).+ Error("Failed to list Space web push subscriptions")+ return+ }+ n.send(+ actorUserID,+ actorSlug,+ "posted a new photo",+ "Check it out",+ spaceActivityPostCreated,+ "/app",+ subscriptions,+ )}-func (n *SpaceEmailSender) OnSpacePostCreated(actorUserID int64, actorSlug string, recipientUserIDs []int64) {- n.send(actorUserID, actorSlug, "posted a new photo", spaceNotificationPostCreated, recipientUserIDs)+func (n *SpaceWebPushSender) OnSpacePostLiked(+ actorUserID int64,+ actorSpaceID, actorSlug string,+ recipientUserID int64,+) {+ n.sendAccountActivity(actorUserID, actorSlug, "liked your post", "", spaceActivityPostLiked, conversationURL(actorSpaceID), recipientUserID)}-func (n *SpaceEmailSender) OnSpacePostLiked(actorUserID int64, actorSlug string, recipientUserID int64) {- n.send(actorUserID, actorSlug, "liked your post", spaceNotificationPostLiked, []int64{recipientUserID})+func (n *SpaceWebPushSender) OnSpacePostReplied(+ actorUserID int64,+ actorSpaceID, actorSlug string,+ recipientUserID int64,+) {+ n.sendAccountActivity(actorUserID, actorSlug, "replied to your post", "Check it out", spaceActivityPostReplied, conversationURL(actorSpaceID), recipientUserID)}-func (n *SpaceEmailSender) OnSpacePostReplied(actorUserID int64, actorSlug string, recipientUserID int64) {- n.send(actorUserID, actorSlug, "replied to your post", spaceNotificationPostReplied, []int64{recipientUserID})+func (n *SpaceWebPushSender) OnSpaceMessageSent(+ actorUserID int64,+ actorSpaceID, actorSlug string,+ recipientUserID int64,+) {+ n.sendAccountActivity(actorUserID, actorSlug, "sent you a message", "Check it out", spaceActivityMessageSent, conversationURL(actorSpaceID), recipientUserID)}-func (n *SpaceEmailSender) OnSpaceFriendAdded(actorUserID int64, actorSlug string, recipientUserID int64) {- n.send(actorUserID, actorSlug, "is now your friend", spaceNotificationFriendAdded, []int64{recipientUserID})+func (n *SpaceWebPushSender) OnSpaceMessageLiked(+ actorUserID int64,+ actorSpaceID, actorSlug string,+ recipientUserID int64,+) {+ n.sendAccountActivity(actorUserID, actorSlug, "liked a message", "View conversation", spaceActivityMessageLiked, conversationURL(actorSpaceID), recipientUserID)+}++func (n *SpaceWebPushSender) OnSpaceFriendAdded(+ actorUserID int64,+ actorSpaceID, actorSlug string,+ recipientUserID int64,+) {+ n.sendAccountActivity(+ actorUserID,+ actorSlug,+ "is now your friend",+ "Say hi to "+spaceActivityActorLabel(actorSlug),+ spaceActivityFriendAdded,+ conversationURL(actorSpaceID),+ recipientUserID,+ )+}++func (n *SpaceWebPushSender) OnSpaceFriendRequested(+ actorUserID int64,+ actorSlug string,+ recipientUserID int64,+) {+ n.sendAccountActivity(actorUserID, actorSlug, "sent you a friend request", "Review request", spaceActivityFriendRequested, "/app/messages", recipientUserID)+}++func (n *SpaceWebPushSender) sendAccountActivity(+ actorUserID int64,+ actorSlug, activity, action, event, destination string,+ recipientUserID int64,+) {+ if !n.available() || recipientUserID <= 0 {+ return+ }+ subscriptions, err := n.WebPushRepo.ListActiveAccountSubscriptions(+ context.Background(),+ []int64{recipientUserID},+ )+ if err != nil {+ log.WithField("event", event).WithError(err).+ Error("Failed to list Space web push subscriptions")+ return+ }+ n.send(actorUserID, actorSlug, activity, action, event, destination, subscriptions)}-func (n *SpaceEmailSender) OnSpaceFriendRequested(actorUserID int64, actorSlug string, recipientUserID int64) {- n.send(actorUserID, actorSlug, "sent you a friend request", spaceNotificationFriendRequested, []int64{recipientUserID})+func (n *SpaceWebPushSender) available() bool {+ return n != nil &&+ n.WebPushRepo != nil &&+ n.HTTPClient != nil &&+ n.sendLimiter != nil &&+ n.sendSlots != nil &&+ !viper.GetBool("internal.silent")}-func (n *SpaceEmailSender) send(actorUserID int64, actorSlug, action, event string, recipientUserIDs []int64) {- if n == nil || n.UserRepo == nil || len(recipientUserIDs) == 0 {+func (n *SpaceWebPushSender) send(+ actorUserID int64,+ actorSlug, activity, action, event, destination string,+ subscriptions []repo.SpaceWebPushSubscriptionRecord,+) {+ options, ok := spaceWebPushOptions(n.HTTPClient)+ if !ok {return}- recipientUserIDs = uniqueUserIDs(recipientUserIDs)- if len(recipientUserIDs) == 0 {+ subscriptions = deduplicateSpaceWebPushSubscriptions(subscriptions)+ if len(subscriptions) == 0 {return}- users, err := n.UserRepo.GetActiveUsersForIds(recipientUserIDs)+ limitContext, err := n.sendLimiter.Get(+ context.Background(),+ strconv.FormatInt(actorUserID, 10),+ )if err != nil {- log.WithField("event", event).WithError(err).Error("Error fetching users for space email")+ log.WithField("actor_user_id", actorUserID).WithError(err).+ Error("Failed to check Space web push rate limit")return}-- subject := spaceEmailSubject(actorSlug, action)- templateData := map[string]interface{}{- "ActorLabel": spaceEmailActorLabel(actorSlug),- "AppURL": spaceAppURL(),- "IllustrationURL": spaceEmailIllustrationURL(event),- "IllustrationWidth": spaceEmailIllustrationWidth(event),- "Notification": spaceEmailNotificationText(event, action),+ if limitContext.Reached {+ return}- for _, userID := range recipientUserIDs {- user := users[userID]- if user == nil || strings.TrimSpace(user.Email) == "" {- continue+ if limitContext.Remaining == 0 {+ log.WithFields(log.Fields{+ "actor_user_id": actorUserID,+ "reset_at": limitContext.Reset,+ }).Warn("Space web push rate limit reached")+ }++ var waitGroup sync.WaitGroup+ for _, subscription := range subscriptions {+ payload := spaceWebPushPayload{+ Title: "Ente Space",+ Body: fmt.Sprintf("%s %s", spaceActivityActorLabel(actorSlug), activity),+ Action: action,}- limitContext, err := n.sendLimiter.Get(context.Background(), strconv.FormatInt(actorUserID, 10))- if err != nil {- log.WithField("actor_user_id", actorUserID).WithError(err).Error("Error checking space email rate limit")- continue+ if subscription.Public {+ payload.TargetID = subscription.TargetID+ } else {+ payload.URL = destination}- if limitContext.Reached {+ encoded, err := json.Marshal(payload)+ if err != nil {+ log.WithField("event", event).WithError(err).+ Error("Failed to encode Space web push payload")continue}- if limitContext.Remaining == 0 {- log.WithFields(log.Fields{- "actor_user_id": actorUserID,- "reset_at": limitContext.Reset,- }).Warn("Space email rate limit reached")- }- if err := sendSpaceNotificationEmail(- []string{user.Email},- "Ente Space",- "[email protected]",- subject,- spaceNotificationTemplate,- templateData,- nil,- ); err != nil {- log.WithFields(log.Fields{- "user_id": userID,- "email": user.Email,- "event": event,- }).WithError(err).Error("Error sending space email")++ waitGroup.Add(1)+ go func(subscription repo.SpaceWebPushSubscriptionRecord, payload []byte) {+ defer waitGroup.Done()+ n.sendSlots <- struct{}{}+ defer func() { <-n.sendSlots }()+ n.sendSubscription(event, payload, subscription, options)+ }(subscription, encoded)+ }+ waitGroup.Wait()+}++func (n *SpaceWebPushSender) sendSubscription(+ event string,+ payload []byte,+ subscription repo.SpaceWebPushSubscriptionRecord,+ options *webpush.Options,+) {+ ctx, cancel := context.WithTimeout(context.Background(), spaceWebPushSendTimeout)+ defer cancel()+ response, err := sendSpaceWebPush(ctx, payload, &webpush.Subscription{+ Endpoint: subscription.Endpoint,+ Keys: webpush.Keys{+ P256dh: subscription.P256dh,+ Auth: subscription.Auth,+ },+ }, options)+ if err != nil {+ log.WithFields(log.Fields{+ "event": event,+ "user_id": subscription.UserID,+ }).WithError(err).Error("Failed to send Space web push")+ return+ }+ defer response.Body.Close()+ if response.StatusCode == http.StatusNotFound || response.StatusCode == http.StatusGone {+ if err := n.WebPushRepo.DeleteEndpoint(context.Background(), subscription.Endpoint); err != nil {+ log.WithField("event", event).WithError(err).+ Error("Failed to delete expired Space web push subscription")}+ return+ }+ if response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusMultipleChoices {+ log.WithFields(log.Fields{+ "event": event,+ "status": response.StatusCode,+ "user_id": subscription.UserID,+ }).Warn("Space web push provider rejected notification")}}-func spaceEmailSubject(actorSlug, action string) string {- actorSlug = strings.TrimSpace(actorSlug)- if actorSlug == "" {- return fmt.Sprintf("A friend %s", action)+func spaceWebPushOptions(client webpush.HTTPClient) (*webpush.Options, bool) {+ config, ok := configuredSpaceWebPush()+ if !ok {+ return nil, false}- return fmt.Sprintf("@%s %s", actorSlug, action)+ return &webpush.Options{+ HTTPClient: client,+ Subscriber: config.Subscriber,+ TTL: spaceWebPushTTLSeconds,+ Urgency: webpush.UrgencyNormal,+ VAPIDPublicKey: config.PublicKey,+ VAPIDPrivateKey: config.PrivateKey,+ }, true}-func spaceEmailActorLabel(actorSlug string) string {- actorSlug = strings.TrimSpace(actorSlug)- if actorSlug == "" {- return "A friend"+func deduplicateSpaceWebPushSubscriptions(+ subscriptions []repo.SpaceWebPushSubscriptionRecord,+) []repo.SpaceWebPushSubscriptionRecord {+ byEndpoint := make(map[string]repo.SpaceWebPushSubscriptionRecord, len(subscriptions))+ order := make([]string, 0, len(subscriptions))+ for _, subscription := range subscriptions {+ existing, found := byEndpoint[subscription.Endpoint]+ if !found {+ order = append(order, subscription.Endpoint)+ byEndpoint[subscription.Endpoint] = subscription+ continue+ }+ if existing.Public && !subscription.Public {+ byEndpoint[subscription.Endpoint] = subscription+ }}- return fmt.Sprintf("@%s", actorSlug)-}--func spaceEmailNotificationText(event, action string) string {- switch event {- case spaceNotificationPostCreated:- return "just posted a new photo"- case spaceNotificationPostLiked:- return "just liked your post"- case spaceNotificationPostReplied:- return "just replied to your post"- case spaceNotificationFriendAdded:- return "is now your friend"- case spaceNotificationFriendRequested:- return "sent you a friend request"- default:- return action- }-}--func spaceEmailIllustrationURL(event string) string {- switch event {- case spaceNotificationPostCreated:- return spaceNewPostIllustrationURL- case spaceNotificationPostLiked:- return spaceNewPostLikeIllustrationURL- case spaceNotificationPostReplied:- return spaceNewPostReplyIllustrationURL- case spaceNotificationFriendAdded:- return spaceNewFriendIllustrationURL- case spaceNotificationFriendRequested:- return spaceNewFriendIllustrationURL- default:- return ""- }-}--func spaceEmailIllustrationWidth(event string) int {- switch event {- case spaceNotificationPostCreated:- return spaceNewPostIllustrationWidth- case spaceNotificationPostLiked:- return spaceNewPostLikeIllustrationWidth- case spaceNotificationPostReplied:- return spaceNewPostReplyIllustrationWidth- case spaceNotificationFriendAdded:- return spaceNewFriendIllustrationWidth- case spaceNotificationFriendRequested:- return spaceNewFriendIllustrationWidth- default:- return 0+ result := make([]repo.SpaceWebPushSubscriptionRecord, 0, len(order))+ for _, endpoint := range order {+ result = append(result, byEndpoint[endpoint])}+ return result}func uniqueUserIDs(userIDs []int64) []int64 {@@ -216,6 +340,18 @@ func uniqueUserIDs(userIDs []int64) []int64 {return out}+func spaceActivityActorLabel(actorSlug string) string {+ actorSlug = strings.TrimSpace(actorSlug)+ if actorSlug == "" {+ return "A friend"+ }+ return "@" + actorSlug+}++func conversationURL(spaceID string) string {+ return "/app/messages/" + url.PathEscape(spaceID)+}+func spaceAppURL() string {origin := strings.TrimRight(strings.TrimSpace(viper.GetString("apps.space")), "/")if origin == "" {@@ -223,3 +359,90 @@ func spaceAppURL() string {}return origin + "/app"}++func newSpaceWebPushHTTPClient() *http.Client {+ dialer := &net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second}+ transport := http.DefaultTransport.(*http.Transport).Clone()+ transport.Proxy = nil+ transport.DialContext = func(+ ctx context.Context,+ network, address string,+ ) (net.Conn, error) {+ host, port, err := net.SplitHostPort(address)+ if err != nil {+ return nil, err+ }+ addresses, err := net.DefaultResolver.LookupIP(ctx, "ip", host)+ if err != nil {+ return nil, err+ }+ for _, address := range addresses {+ if !isPublicWebPushAddress(address) {+ return nil, errors.New("web push endpoint resolved to a non-public address")+ }+ }+ for _, address := range addresses {+ connection, err := dialer.DialContext(+ ctx,+ network,+ net.JoinHostPort(address.String(), port),+ )+ if err == nil {+ return connection, nil+ }+ }+ return nil, errors.New("failed to connect to web push endpoint")+ }+ return &http.Client{+ Transport: transport,+ Timeout: spaceWebPushSendTimeout,+ CheckRedirect: func(_ *http.Request, _ []*http.Request) error {+ return errors.New("web push endpoint redirects are not allowed")+ },+ }+}++var reservedWebPushNetworks = mustParseNetworks(+ "0.0.0.0/8",+ "100.64.0.0/10",+ "192.0.0.0/24",+ "192.0.2.0/24",+ "192.88.99.0/24",+ "198.18.0.0/15",+ "198.51.100.0/24",+ "203.0.113.0/24",+ "240.0.0.0/4",+ "64:ff9b::/96",+ "64:ff9b:1::/48",+ "100::/64",+ "2001::/23",+ "2001:db8::/32",+ "2002::/16",+)++func mustParseNetworks(values ...string) []*net.IPNet {+ networks := make([]*net.IPNet, 0, len(values))+ for _, value := range values {+ _, network, err := net.ParseCIDR(value)+ if err != nil {+ panic(err)+ }+ networks = append(networks, network)+ }+ return networks+}++func isPublicWebPushAddress(address net.IP) bool {+ if !address.IsGlobalUnicast() ||+ address.IsPrivate() ||+ address.IsLoopback() ||+ address.IsLinkLocalUnicast() {+ return false+ }+ for _, network := range reservedWebPushNetworks {+ if network.Contains(address) {+ return false+ }+ }+ return true+}diff --git a/server/space/controller/notifications_test.go b/server/space/controller/notifications_test.goindex 1178c0e657..eb16959862 100644--- a/server/space/controller/notifications_test.go+++ b/server/space/controller/notifications_test.go@@ -1,229 +1,442 @@package controllerimport (+ "context"+ "crypto/ecdh"+ "crypto/rand""encoding/base64"+ "encoding/json"+ "fmt""io"+ "net"+ "net/http"+ "strings""testing""time"- "github.com/ente/museum/internal/testutil"- baserepo "github.com/ente/museum/pkg/repo"+ webpush "github.com/SherClockHolmes/webpush-go"+ timeutil "github.com/ente/museum/pkg/utils/time""github.com/ente/museum/space/models"- log "github.com/sirupsen/logrus"- logtest "github.com/sirupsen/logrus/hooks/test"+ "github.com/ente/museum/space/repo"+ "github.com/spf13/viper""github.com/stretchr/testify/require")-type recordedSpaceEmail struct {- event string- actorUserID int64- actorSlug string- recipients []int64+type recordedSpaceActivity struct {+ event string+ actorUserID int64+ actorSpaceID string+ actorSlug string+ recipientIDs []int64}-type recordingSpaceEmailNotifier struct {- events chan recordedSpaceEmail+type recordingSpaceActivityNotifier struct {+ events chan recordedSpaceActivity}-func newRecordingSpaceEmailNotifier() *recordingSpaceEmailNotifier {- return &recordingSpaceEmailNotifier{events: make(chan recordedSpaceEmail, 8)}+func newRecordingSpaceActivityNotifier() *recordingSpaceActivityNotifier {+ return &recordingSpaceActivityNotifier{events: make(chan recordedSpaceActivity, 8)}}-func (n *recordingSpaceEmailNotifier) OnSpacePostCreated(actorUserID int64, actorSlug string, recipientUserIDs []int64) {- n.events <- recordedSpaceEmail{event: "post_created", actorUserID: actorUserID, actorSlug: actorSlug, recipients: append([]int64(nil), recipientUserIDs...)}+func (n *recordingSpaceActivityNotifier) OnSpacePostCreated(actorUserID int64, actorSpaceID, actorSlug string, recipientUserIDs []int64) {+ n.record(spaceActivityPostCreated, actorUserID, actorSpaceID, actorSlug, recipientUserIDs...)}-func (n *recordingSpaceEmailNotifier) OnSpacePostLiked(actorUserID int64, actorSlug string, recipientUserID int64) {- n.events <- recordedSpaceEmail{event: "post_liked", actorUserID: actorUserID, actorSlug: actorSlug, recipients: []int64{recipientUserID}}+func (n *recordingSpaceActivityNotifier) OnSpacePostLiked(actorUserID int64, actorSpaceID, actorSlug string, recipientUserID int64) {+ n.record(spaceActivityPostLiked, actorUserID, actorSpaceID, actorSlug, recipientUserID)}-func (n *recordingSpaceEmailNotifier) OnSpacePostReplied(actorUserID int64, actorSlug string, recipientUserID int64) {- n.events <- recordedSpaceEmail{event: "post_replied", actorUserID: actorUserID, actorSlug: actorSlug, recipients: []int64{recipientUserID}}+func (n *recordingSpaceActivityNotifier) OnSpacePostReplied(actorUserID int64, actorSpaceID, actorSlug string, recipientUserID int64) {+ n.record(spaceActivityPostReplied, actorUserID, actorSpaceID, actorSlug, recipientUserID)}-func (n *recordingSpaceEmailNotifier) OnSpaceFriendAdded(actorUserID int64, actorSlug string, recipientUserID int64) {- n.events <- recordedSpaceEmail{event: "friend_added", actorUserID: actorUserID, actorSlug: actorSlug, recipients: []int64{recipientUserID}}+func (n *recordingSpaceActivityNotifier) OnSpaceMessageSent(actorUserID int64, actorSpaceID, actorSlug string, recipientUserID int64) {+ n.record(spaceActivityMessageSent, actorUserID, actorSpaceID, actorSlug, recipientUserID)}-func (n *recordingSpaceEmailNotifier) OnSpaceFriendRequested(actorUserID int64, actorSlug string, recipientUserID int64) {- n.events <- recordedSpaceEmail{event: "friend_requested", actorUserID: actorUserID, actorSlug: actorSlug, recipients: []int64{recipientUserID}}+func (n *recordingSpaceActivityNotifier) OnSpaceMessageLiked(actorUserID int64, actorSpaceID, actorSlug string, recipientUserID int64) {+ n.record(spaceActivityMessageLiked, actorUserID, actorSpaceID, actorSlug, recipientUserID)}-func requireSpaceEmail(t *testing.T, notifier *recordingSpaceEmailNotifier) recordedSpaceEmail {+func (n *recordingSpaceActivityNotifier) OnSpaceFriendAdded(actorUserID int64, actorSpaceID, actorSlug string, recipientUserID int64) {+ n.record(spaceActivityFriendAdded, actorUserID, actorSpaceID, actorSlug, recipientUserID)+}++func (n *recordingSpaceActivityNotifier) OnSpaceFriendRequested(actorUserID int64, actorSlug string, recipientUserID int64) {+ n.record(spaceActivityFriendRequested, actorUserID, "", actorSlug, recipientUserID)+}++func (n *recordingSpaceActivityNotifier) record(event string, actorUserID int64, actorSpaceID, actorSlug string, recipientIDs ...int64) {+ n.events <- recordedSpaceActivity{+ event: event,+ actorUserID: actorUserID,+ actorSpaceID: actorSpaceID,+ actorSlug: actorSlug,+ recipientIDs: append([]int64(nil), recipientIDs...),+ }+}++func requireSpaceActivity(t *testing.T, notifier *recordingSpaceActivityNotifier) recordedSpaceActivity {t.Helper()select {case event := <-notifier.events:return eventcase <-time.After(time.Second):- t.Fatal("timed out waiting for space email")- return recordedSpaceEmail{}+ t.Fatal("timed out waiting for Space activity notification")+ return recordedSpaceActivity{}}}-func requireNoSpaceEmail(t *testing.T, notifier *recordingSpaceEmailNotifier) {+func requireNoSpaceActivity(t *testing.T, notifier *recordingSpaceActivityNotifier) {t.Helper()select {case event := <-notifier.events:- t.Fatalf("unexpected space email: %+v", event)+ t.Fatalf("unexpected Space activity notification: %+v", event)case <-time.After(100 * time.Millisecond):}}-func TestSpaceEmailSubjectPrefixesUsernameWithAt(t *testing.T) {- require.Equal(t, "@alice liked your post", spaceEmailSubject("alice", "liked your post"))- require.Equal(t, "@alice posted a new photo", spaceEmailSubject(" alice ", "posted a new photo"))- require.Equal(t, "A friend liked your post", spaceEmailSubject(" ", "liked your post"))-}--func TestSpaceEmailTemplateData(t *testing.T) {- require.Equal(t, "@alice", spaceEmailActorLabel(" alice "))- require.Equal(t, "A friend", spaceEmailActorLabel(" "))- require.Equal(t, "just posted a new photo", spaceEmailNotificationText(spaceNotificationPostCreated, "posted a new photo"))- require.Equal(t, "just liked your post", spaceEmailNotificationText(spaceNotificationPostLiked, "liked your post"))- require.Equal(t, "just replied to your post", spaceEmailNotificationText(spaceNotificationPostReplied, "replied to your post"))- require.Equal(t, "is now your friend", spaceEmailNotificationText(spaceNotificationFriendAdded, "is now your friend"))- require.Equal(t, "sent you a friend request", spaceEmailNotificationText(spaceNotificationFriendRequested, "sent you a friend request"))- require.Equal(t, spaceNewPostIllustrationURL, spaceEmailIllustrationURL(spaceNotificationPostCreated))- require.Equal(t, spaceNewPostLikeIllustrationURL, spaceEmailIllustrationURL(spaceNotificationPostLiked))- require.Equal(t, spaceNewPostReplyIllustrationURL, spaceEmailIllustrationURL(spaceNotificationPostReplied))- require.Equal(t, spaceNewFriendIllustrationURL, spaceEmailIllustrationURL(spaceNotificationFriendAdded))- require.Equal(t, spaceNewFriendIllustrationURL, spaceEmailIllustrationURL(spaceNotificationFriendRequested))- require.Equal(t, spaceNewPostIllustrationWidth, spaceEmailIllustrationWidth(spaceNotificationPostCreated))- require.Equal(t, spaceNewPostLikeIllustrationWidth, spaceEmailIllustrationWidth(spaceNotificationPostLiked))- require.Equal(t, spaceNewPostReplyIllustrationWidth, spaceEmailIllustrationWidth(spaceNotificationPostReplied))- require.Equal(t, spaceNewFriendIllustrationWidth, spaceEmailIllustrationWidth(spaceNotificationFriendAdded))- require.Equal(t, spaceNewFriendIllustrationWidth, spaceEmailIllustrationWidth(spaceNotificationFriendRequested))-}--func TestSpaceEmailSenderLimitsEachSenderToFiftyEmailsPerHour(t *testing.T) {- _, repos, _ := setupPostsControllerTest(t)- recipientID := insertSpaceControllerUser(t, repos, "[email protected]", "recipient-public")- otherRecipientID := insertSpaceControllerUser(t, repos, "[email protected]", "other-recipient-public")- sender := NewSpaceEmailSender(&baserepo.UserRepository{- DB: repos.Spaces.DB,- SecretEncryptionKey: testutil.SecretEncryptionKey(),- })- logger := log.StandardLogger()- originalHooks := logger.ReplaceHooks(make(log.LevelHooks))- originalOutput := logger.Out- logger.SetOutput(io.Discard)- hook := logtest.NewGlobal()+func TestSpaceWebPushCopyAndValidation(t *testing.T) {+ require.Equal(t, "@alice", spaceActivityActorLabel(" alice "))+ require.Equal(t, "A friend", spaceActivityActorLabel(" "))+ require.Equal(t, "/app/messages/space_id", conversationURL("space_id"))++ privateKey, err := ecdh.P256().GenerateKey(rand.Reader)+ require.NoError(t, err)+ p256dh := base64.RawURLEncoding.EncodeToString(privateKey.PublicKey().Bytes())+ auth := base64.RawURLEncoding.EncodeToString(make([]byte, 16))+ require.NoError(t, validateWebPushSubscription("https://push.example/subscription", p256dh, auth))+ require.Error(t, validateWebPushSubscription("http://push.example/subscription", p256dh, auth))+ require.Error(t, validateWebPushSubscription("https://[email protected]/subscription", p256dh, auth))+ require.Error(t, validateWebPushSubscription("https://push.example/subscription#fragment", p256dh, auth))+ require.Error(t, validateWebPushSubscription("https://push.example/subscription", "invalid", auth))+ require.Error(t, validateWebPushSubscription("https://push.example/subscription", p256dh, "invalid"))+}++func TestSpaceWebPushAddressMustBePublic(t *testing.T) {+ require.True(t, isPublicWebPushAddress(net.ParseIP("8.8.8.8")))+ require.True(t, isPublicWebPushAddress(net.ParseIP("2606:4700:4700::1111")))+ require.False(t, isPublicWebPushAddress(net.ParseIP("127.0.0.1")))+ require.False(t, isPublicWebPushAddress(net.ParseIP("10.0.0.1")))+ require.False(t, isPublicWebPushAddress(net.ParseIP("100.64.0.1")))+ require.False(t, isPublicWebPushAddress(net.ParseIP("192.0.2.1")))+ require.False(t, isPublicWebPushAddress(net.ParseIP("::1")))+ require.False(t, isPublicWebPushAddress(net.ParseIP("2001:db8::1")))+}++func TestSpaceWebPushConfigRequiresMatchingKeysAndBareSubscriber(t *testing.T) {+ privateKey, publicKey, err := webpush.GenerateVAPIDKeys()+ require.NoError(t, err)+ viper.Set("space.webPush.publicKey", publicKey)+ viper.Set("space.webPush.privateKey", privateKey)+ viper.Set("space.webPush.subscriber", "[email protected]")t.Cleanup(func() {- logger.ReplaceHooks(originalHooks)- logger.SetOutput(originalOutput)- hook.Reset()+ viper.Set("space.webPush.publicKey", "")+ viper.Set("space.webPush.privateKey", "")+ viper.Set("space.webPush.subscriber", "")})- originalSend := sendSpaceNotificationEmail- t.Cleanup(func() {- sendSpaceNotificationEmail = originalSend+ config, ok := configuredSpaceWebPush()+ require.True(t, ok)+ require.Equal(t, publicKey, config.PublicKey)++ otherPrivateKey, _, err := webpush.GenerateVAPIDKeys()+ require.NoError(t, err)+ viper.Set("space.webPush.privateKey", otherPrivateKey)+ _, ok = configuredSpaceWebPush()+ require.False(t, ok)++ viper.Set("space.webPush.privateKey", privateKey)+ viper.Set("space.webPush.subscriber", "mailto:[email protected]")+ _, ok = configuredSpaceWebPush()+ require.False(t, ok)+}++func TestSpaceWebPushDeduplicatesSharedEndpointForAccount(t *testing.T) {+ subscriptions := deduplicateSpaceWebPushSubscriptions([]repo.SpaceWebPushSubscriptionRecord{+ {Endpoint: "https://push.example/shared", TargetID: "public", Public: true},+ {Endpoint: "https://push.example/shared", TargetID: "account"},+ {Endpoint: "https://push.example/other", TargetID: "other", Public: true},})- sent := 0- sendSpaceNotificationEmail = func(_ []string, fromName string, fromEmail string, _ string, _ string, _ map[string]interface{}, _ []map[string]interface{}) error {- require.Equal(t, "Ente Space", fromName)- require.Equal(t, "[email protected]", fromEmail)- sent++- return nil- }+ require.Equal(t, []repo.SpaceWebPushSubscriptionRecord{+ {Endpoint: "https://push.example/shared", TargetID: "account"},+ {Endpoint: "https://push.example/other", TargetID: "other", Public: true},+ }, subscriptions)+}- for range 50 {- sender.OnSpacePostReplied(1, "alice", recipientID)- }- require.Equal(t, 50, sent)+func TestNewPostNotifiesWithNoAccountFriends(t *testing.T) {+ _, repos, _ := setupPostsControllerTest(t)+ notifier := newRecordingSpaceActivityNotifier()+ posts := NewModule(repos, nil, notifier).Posts- sender.OnSpacePostLiked(1, "alice", otherRecipientID)- require.Equal(t, 50, sent)- require.Len(t, hook.AllEntries(), 1)- require.Equal(t, log.WarnLevel, hook.LastEntry().Level)- require.Equal(t, "Space email rate limit reached", hook.LastEntry().Message)- require.Equal(t, int64(1), hook.LastEntry().Data["actor_user_id"])+ posts.notifyFriendsOfNewPost(1, "space_id", "alice")- sender.OnSpaceFriendRequested(2, "bob", recipientID)- require.Equal(t, 51, sent)+ require.Equal(t, recordedSpaceActivity{+ event: spaceActivityPostCreated,+ actorUserID: 1,+ actorSpaceID: "space_id",+ actorSlug: "alice",+ }, requireSpaceActivity(t, notifier))}-func TestPostLikeSendsEmailOnce(t *testing.T) {+func TestPostLikeSendsActivityOnlyOnLikeTransition(t *testing.T) {_, repos, ctx := setupPostsControllerTest(t)- notifier := newRecordingSpaceEmailNotifier()+ notifier := newRecordingSpaceActivityNotifier()posts := NewModule(repos, nil, notifier).Posts- aliceID := insertSpaceControllerUser(t, repos, "[email protected]", "alice-public")- bobID := insertSpaceControllerUser(t, repos, "[email protected]", "bob-public")- aliceSpace, err := testCreateSpace(ctx, repos, aliceID, "alice_post_like_email", "alice-space-key", "alice-post-like-email-public", "alice-post-like-email-secret", "alice-post-like-email-secret-nonce", "alice-profile")+ aliceID := insertSpaceControllerUser(t, repos, "[email protected]", "alice-public")+ bobID := insertSpaceControllerUser(t, repos, "[email protected]", "bob-public")+ aliceSpace, err := testCreateSpace(ctx, repos, aliceID, "alice_post_like_push", "alice-space-key", "alice-post-public", "alice-post-secret", "nonce", "alice-profile")require.NoError(t, err)- bobSpace, err := testCreateSpace(ctx, repos, bobID, "bob_post_like_email", "bob-space-key", "bob-post-like-email-public", "bob-post-like-email-secret", "bob-post-like-email-secret-nonce", "bob-profile")+ bobSpace, err := testCreateSpace(ctx, repos, bobID, "bob_post_like_push", "bob-space-key", "bob-post-public", "bob-post-secret", "nonce", "bob-profile")require.NoError(t, err)require.NoError(t, testAddFriend(ctx, repos, bobID, bobSpace.SpaceID, aliceSpace.SpaceID, "alice-share-key", aliceSpace.CurrentVersion, "bob-share-key", bobSpace.CurrentVersion))postID, err := testCreatePost(ctx, repos, aliceID, aliceSpace.SpaceID, "post-key", nil, aliceSpace.CurrentVersion, nil)require.NoError(t, err)- resp, err := posts.SetLike(ctx, bobSpace, postID, true)+ _, err = posts.SetLike(ctx, bobSpace, postID, true)require.NoError(t, err)- require.True(t, resp.Liked)- email := requireSpaceEmail(t, notifier)- require.Equal(t, recordedSpaceEmail{event: "post_liked", actorUserID: bobID, actorSlug: bobSpace.SpaceSlug, recipients: []int64{aliceID}}, email)+ expected := recordedSpaceActivity{+ event: spaceActivityPostLiked,+ actorUserID: bobID,+ actorSpaceID: bobSpace.SpaceID,+ actorSlug: bobSpace.SpaceSlug,+ recipientIDs: []int64{aliceID},+ }+ require.Equal(t, expected, requireSpaceActivity(t, notifier))_, err = posts.SetLike(ctx, bobSpace, postID, true)require.NoError(t, err)- requireNoSpaceEmail(t, notifier)+ requireNoSpaceActivity(t, notifier)+ _, err = posts.SetLike(ctx, bobSpace, postID, false)+ require.NoError(t, err)+ requireNoSpaceActivity(t, notifier)+ _, err = posts.SetLike(ctx, bobSpace, postID, true)+ require.NoError(t, err)+ require.Equal(t, expected, requireSpaceActivity(t, notifier))}-func TestPostReplySendsEmail(t *testing.T) {+func TestMessageActivitiesAndLikeTransition(t *testing.T) {_, repos, ctx := setupMessagesControllerTest(t)- notifier := newRecordingSpaceEmailNotifier()+ notifier := newRecordingSpaceActivityNotifier()messages := NewModule(repos, nil, notifier).Messages- aliceID, aliceSpace := createMessageControllerUserAndSpace(t, repos, "alice-post-reply-email", "alice-public")- bobID, bobSpace := createMessageControllerUserAndSpace(t, repos, "bob-post-reply-email", "bob-public")+ aliceID, aliceSpace := createMessageControllerUserAndSpace(t, repos, "alice-message-push", "alice-public")+ bobID, bobSpace := createMessageControllerUserAndSpace(t, repos, "bob-message-push", "bob-public")require.NoError(t, testAddFriend(ctx, repos, bobID, bobSpace.SpaceID, aliceSpace.SpaceID, "alice-share-key", aliceSpace.CurrentVersion, "bob-share-key", bobSpace.CurrentVersion))- postID, err := testCreatePost(ctx, repos, aliceID, aliceSpace.SpaceID, "post-key", nil, aliceSpace.CurrentVersion, nil)+ request := models.CreateMessageRequest{+ MessageCipher: spaceTestB64("cipher"),+ SenderEncryptedMessageKey: spaceTestB64("sender-key"),+ RecipientEncryptedMessageKey: spaceTestB64("recipient-key"),+ }++ message, err := messages.Create(ctx, aliceSpace, bobSpace.SpaceID, request)require.NoError(t, err)+ require.Equal(t, recordedSpaceActivity{+ event: spaceActivityMessageSent,+ actorUserID: aliceID,+ actorSpaceID: aliceSpace.SpaceID,+ actorSlug: aliceSpace.SpaceSlug,+ recipientIDs: []int64{bobID},+ }, requireSpaceActivity(t, notifier))- _, err = messages.ReplyToPost(ctx, bobSpace, postID, models.CreateMessageRequest{- MessageCipher: spaceTestB64("reply-cipher"),- SenderEncryptedMessageKey: spaceTestB64("reply-sender-key"),- RecipientEncryptedMessageKey: spaceTestB64("reply-recipient-key"),- })+ _, err = messages.SetLike(ctx, bobSpace, message.MessageID, true)require.NoError(t, err)- email := requireSpaceEmail(t, notifier)- require.Equal(t, recordedSpaceEmail{event: "post_replied", actorUserID: bobID, actorSlug: bobSpace.SpaceSlug, recipients: []int64{aliceID}}, email)+ expectedLike := recordedSpaceActivity{+ event: spaceActivityMessageLiked,+ actorUserID: bobID,+ actorSpaceID: bobSpace.SpaceID,+ actorSlug: bobSpace.SpaceSlug,+ recipientIDs: []int64{aliceID},+ }+ require.Equal(t, expectedLike, requireSpaceActivity(t, notifier))+ _, err = messages.SetLike(ctx, bobSpace, message.MessageID, true)+ require.NoError(t, err)+ requireNoSpaceActivity(t, notifier)+ _, err = messages.SetLike(ctx, bobSpace, message.MessageID, false)+ require.NoError(t, err)+ requireNoSpaceActivity(t, notifier)++ postID, err := testCreatePost(ctx, repos, aliceID, aliceSpace.SpaceID, "post-key", nil, aliceSpace.CurrentVersion, nil)+ require.NoError(t, err)+ _, err = messages.ReplyToPost(ctx, bobSpace, postID, request)+ require.NoError(t, err)+ require.Equal(t, recordedSpaceActivity{+ event: spaceActivityPostReplied,+ actorUserID: bobID,+ actorSpaceID: bobSpace.SpaceID,+ actorSlug: bobSpace.SpaceSlug,+ recipientIDs: []int64{aliceID},+ }, requireSpaceActivity(t, notifier))}-func TestAddFriendSendsEmailOnce(t *testing.T) {+func TestFriendActivitiesOnlyOnRelationshipTransitions(t *testing.T) {_, repos, ctx := setupFriendsControllerTest(t)- notifier := newRecordingSpaceEmailNotifier()+ notifier := newRecordingSpaceActivityNotifier()friends := NewModule(repos, nil, notifier).Friends- aliceID := insertSpaceControllerUser(t, repos, "[email protected]", "alice-public")- bobID := insertSpaceControllerUser(t, repos, "[email protected]", "bob-public")- aliceSpace, err := testCreateSpace(ctx, repos, aliceID, "alice_friend_email", "alice-space-key", "alice-friend-email-public", "alice-friend-email-secret", "alice-friend-email-secret-nonce", "alice-profile")+ aliceID := insertSpaceControllerUser(t, repos, "[email protected]", "alice-public")+ bobID := insertSpaceControllerUser(t, repos, "[email protected]", "bob-public")+ aliceSpace, err := testCreateSpace(ctx, repos, aliceID, "alice_friend_push", "alice-space-key", "alice-public", "alice-secret", "nonce", "alice-profile")require.NoError(t, err)- bobSpace, err := testCreateSpace(ctx, repos, bobID, "bob_friend_email", "bob-space-key", "bob-friend-email-public", "bob-friend-email-secret", "bob-friend-email-secret-nonce", "bob-profile")+ bobSpace, err := testCreateSpace(ctx, repos, bobID, "bob_friend_push", "bob-space-key", "bob-public", "bob-secret", "nonce", "bob-profile")require.NoError(t, err)- req := models.AddFriendPayload{+ request := models.AddFriendPayload{TargetSpaceID: aliceSpace.SpaceID,RequesterFriendSealedSpaceKey: base64.StdEncoding.EncodeToString([]byte("bob-requester-key")),RequesterKeyVersion: bobSpace.CurrentVersion,}- resp, err := friends.Add(ctx, bobSpace, req)+ _, err = friends.Add(ctx, bobSpace, request)require.NoError(t, err)- require.Equal(t, "requested", resp.Status)- email := requireSpaceEmail(t, notifier)- require.Equal(t, recordedSpaceEmail{event: "friend_requested", actorUserID: bobID, actorSlug: bobSpace.SpaceSlug, recipients: []int64{aliceID}}, email)-- _, err = friends.Add(ctx, bobSpace, req)+ require.Equal(t, recordedSpaceActivity{+ event: spaceActivityFriendRequested,+ actorUserID: bobID,+ actorSlug: bobSpace.SpaceSlug,+ recipientIDs: []int64{aliceID},+ }, requireSpaceActivity(t, notifier))+ _, err = friends.Add(ctx, bobSpace, request)require.NoError(t, err)- requireNoSpaceEmail(t, notifier)+ requireNoSpaceActivity(t, notifier)requests, err := friends.ListRequests(ctx, aliceSpace)require.NoError(t, err)require.Len(t, requests, 1)- require.Equal(t, bobSpace.SpaceSlug, requests[0].Requester.SpaceSlug)-- resp, err = friends.ConfirmRequest(ctx, aliceSpace, requests[0].RequestID, models.ConfirmFriendRequestPayload{+ _, err = friends.ConfirmRequest(ctx, aliceSpace, requests[0].RequestID, models.ConfirmFriendRequestPayload{TargetFriendSealedSpaceKey: base64.StdEncoding.EncodeToString([]byte("alice-target-key")),TargetKeyVersion: aliceSpace.CurrentVersion,})require.NoError(t, err)- require.Equal(t, "friend", resp.Status)- email = requireSpaceEmail(t, notifier)- require.Equal(t, recordedSpaceEmail{event: "friend_added", actorUserID: aliceID, actorSlug: aliceSpace.SpaceSlug, recipients: []int64{bobID}}, email)+ require.Equal(t, recordedSpaceActivity{+ event: spaceActivityFriendAdded,+ actorUserID: aliceID,+ actorSpaceID: aliceSpace.SpaceID,+ actorSlug: aliceSpace.SpaceSlug,+ recipientIDs: []int64{bobID},+ }, requireSpaceActivity(t, notifier))+}++func TestSpaceWebPushSenderUsesGenericPayloadAndPrunesDeadEndpoint(t *testing.T) {+ _, repos, ctx := setupPostsControllerTest(t)+ recipientID := insertSpaceControllerUser(t, repos, "[email protected]", "recipient-public")+ sessionHash := []byte("space-push-session-hash")+ require.NoError(t, repos.Sessions.CreateBrowserSession(ctx, sessionHash, recipientID, "wrap-key", timeutil.NDaysFromNow(1)))+ _, err := repos.WebPush.UpsertAccountSubscription(ctx, sessionHash, "https://push.example/subscription", "p256dh", "auth")+ require.NoError(t, err)++ vapidPrivateKey, vapidPublicKey, err := webpush.GenerateVAPIDKeys()+ require.NoError(t, err)+ viper.Set("space.webPush.publicKey", vapidPublicKey)+ viper.Set("space.webPush.privateKey", vapidPrivateKey)+ viper.Set("space.webPush.subscriber", "[email protected]")+ t.Cleanup(func() {+ viper.Set("space.webPush.publicKey", "")+ viper.Set("space.webPush.privateKey", "")+ viper.Set("space.webPush.subscriber", "")+ })++ originalSend := sendSpaceWebPush+ t.Cleanup(func() { sendSpaceWebPush = originalSend })+ var payload spaceWebPushPayload+ sendSpaceWebPush = func(_ context.Context, message []byte, subscription *webpush.Subscription, options *webpush.Options) (*http.Response, error) {+ require.Equal(t, "https://push.example/subscription", subscription.Endpoint)+ require.Equal(t, spaceWebPushTTLSeconds, options.TTL)+ require.Equal(t, webpush.UrgencyNormal, options.Urgency)+ require.Equal(t, "[email protected]", options.Subscriber)+ require.NoError(t, json.Unmarshal(message, &payload))+ return &http.Response{StatusCode: http.StatusGone, Body: io.NopCloser(strings.NewReader(""))}, nil+ }++ sender := NewSpaceWebPushSender(repos.WebPush)+ sender.OnSpacePostReplied(1, "alice_space", "alice", recipientID)+ require.Equal(t, spaceWebPushPayload{+ Title: "Ente Space",+ Body: "@alice replied to your post",+ Action: "Check it out",+ URL: "/app/messages/alice_space",+ }, payload)+ var count int+ require.NoError(t, repos.WebPush.DB.QueryRow(`SELECT COUNT(*) FROM space_web_push_subscriptions`).Scan(&count))+ require.Zero(t, count)+}++func TestPublicPostPushCarriesOnlyOpaqueLocalRouteTarget(t *testing.T) {+ vapidPrivateKey, vapidPublicKey, err := webpush.GenerateVAPIDKeys()+ require.NoError(t, err)+ viper.Set("space.webPush.publicKey", vapidPublicKey)+ viper.Set("space.webPush.privateKey", vapidPrivateKey)+ viper.Set("space.webPush.subscriber", "[email protected]")+ t.Cleanup(func() {+ viper.Set("space.webPush.publicKey", "")+ viper.Set("space.webPush.privateKey", "")+ viper.Set("space.webPush.subscriber", "")+ })++ originalSend := sendSpaceWebPush+ t.Cleanup(func() { sendSpaceWebPush = originalSend })+ var payload spaceWebPushPayload+ sendSpaceWebPush = func(_ context.Context, message []byte, _ *webpush.Subscription, _ *webpush.Options) (*http.Response, error) {+ require.NoError(t, json.Unmarshal(message, &payload))+ return &http.Response{StatusCode: http.StatusCreated, Body: io.NopCloser(strings.NewReader(""))}, nil+ }++ sender := NewSpaceWebPushSender(nil)+ sender.send(+ 2,+ "alice",+ "posted a new photo",+ "Check it out",+ spaceActivityPostCreated,+ "/app",+ []repo.SpaceWebPushSubscriptionRecord{{+ Endpoint: "https://push.example/public",+ P256dh: "p256dh",+ Auth: "auth",+ TargetID: "wpt_public_target",+ Public: true,+ }},+ )+ require.Equal(t, spaceWebPushPayload{+ Title: "Ente Space",+ Body: "@alice posted a new photo",+ Action: "Check it out",+ TargetID: "wpt_public_target",+ }, payload)+}++func TestSpaceWebPushSendRateAppliesOncePerActivity(t *testing.T) {+ vapidPrivateKey, vapidPublicKey, err := webpush.GenerateVAPIDKeys()+ require.NoError(t, err)+ viper.Set("space.webPush.publicKey", vapidPublicKey)+ viper.Set("space.webPush.privateKey", vapidPrivateKey)+ viper.Set("space.webPush.subscriber", "[email protected]")+ t.Cleanup(func() {+ viper.Set("space.webPush.publicKey", "")+ viper.Set("space.webPush.privateKey", "")+ viper.Set("space.webPush.subscriber", "")+ })++ originalSend := sendSpaceWebPush+ t.Cleanup(func() { sendSpaceWebPush = originalSend })+ sent := make(chan struct{}, 51)+ sendSpaceWebPush = func(_ context.Context, _ []byte, _ *webpush.Subscription, _ *webpush.Options) (*http.Response, error) {+ sent <- struct{}{}+ return &http.Response{StatusCode: http.StatusCreated, Body: io.NopCloser(strings.NewReader(""))}, nil+ }++ subscriptions := make([]repo.SpaceWebPushSubscriptionRecord, 51)+ for index := range subscriptions {+ subscriptions[index] = repo.SpaceWebPushSubscriptionRecord{+ Endpoint: fmt.Sprintf("https://push.example/%d", index),+ P256dh: "p256dh",+ Auth: "auth",+ }+ }+ NewSpaceWebPushSender(nil).send(+ 3,+ "alice",+ "posted a new photo",+ "Check it out",+ spaceActivityPostCreated,+ "/app",+ subscriptions,+ )+ require.Equal(t, len(subscriptions), len(sent))}diff --git a/server/space/controller/posts.go b/server/space/controller/posts.goindex 69a02032f9..35207ce73c 100644--- a/server/space/controller/posts.go+++ b/server/space/controller/posts.go@@ -22,13 +22,13 @@ type SpaceAbuseNotifier interface {}type PostsController struct {- PostsRepo *repo.PostsRepository- SpacesRepo *repo.SpacesRepository- FriendsRepo *repo.FriendsRepository- AssetsRepo *repo.AssetsRepository- EmailNotifier SpaceEmailNotifier- AbuseNotifier SpaceAbuseNotifier- auth authDeps+ PostsRepo *repo.PostsRepository+ SpacesRepo *repo.SpacesRepository+ FriendsRepo *repo.FriendsRepository+ AssetsRepo *repo.AssetsRepository+ ActivityNotifier SpaceActivityNotifier+ AbuseNotifier SpaceAbuseNotifier+ auth authDeps}func (c *PostsController) Create(ctx context.Context, space *repo.SpaceRecord, req models.CreatePostRequest) (*models.CreatePostResponse, error) {@@ -97,19 +97,16 @@ func (c *PostsController) Create(ctx context.Context, space *repo.SpaceRecord, r}func (c *PostsController) notifyFriendsOfNewPost(ownerID int64, spaceID, spaceSlug string) {- if c.EmailNotifier == nil || c.FriendsRepo == nil {+ if c.ActivityNotifier == nil || c.FriendsRepo == nil {return}go func() {recipientUserIDs, err := c.FriendsRepo.ListFriendOwnerIDsForSpace(context.Background(), spaceID)if err != nil {- log.WithField("space_id", spaceID).WithError(err).Error("Failed to list friends for space post email")+ log.WithField("space_id", spaceID).WithError(err).Error("Failed to list friends for Space post notification")return}- if len(recipientUserIDs) == 0 {- return- }- c.EmailNotifier.OnSpacePostCreated(ownerID, spaceSlug, recipientUserIDs)+ c.ActivityNotifier.OnSpacePostCreated(ownerID, spaceID, spaceSlug, recipientUserIDs)}()}@@ -242,8 +239,13 @@ func (c *PostsController) SetLike(ctx context.Context, actorSpace *repo.SpaceRecif err != nil {return nil, err}- if like && created && c.EmailNotifier != nil {- go c.EmailNotifier.OnSpacePostLiked(actorSpace.OwnerID, actorSpace.SpaceSlug, post.OwnerID)+ if like && created && c.ActivityNotifier != nil {+ go c.ActivityNotifier.OnSpacePostLiked(+ actorSpace.OwnerID,+ actorSpace.SpaceID,+ actorSpace.SpaceSlug,+ post.OwnerID,+ )}return &models.LikePostResponse{Liked: like}, nil}diff --git a/server/space/controller/web_push.go b/server/space/controller/web_push.gonew file mode 100644index 0000000000..c8bbb57d36--- /dev/null+++ b/server/space/controller/web_push.go@@ -0,0 +1,230 @@+package controller++import (+ "bytes"+ "crypto/ecdh"+ "crypto/sha256"+ "database/sql"+ "encoding/base64"+ "errors"+ "net/http"+ "net/mail"+ "net/url"+ "strings"++ "github.com/ente/museum/ente"+ "github.com/ente/museum/space/models"+ "github.com/ente/museum/space/repo"+ "github.com/ente/stacktrace"+ "github.com/gin-gonic/gin"+ "github.com/spf13/viper"+)++const (+ spaceWebPushEndpointMaxBytes = 2048+ spaceWebPushP256dhMaxBytes = 256+ spaceWebPushAuthMaxBytes = 128+)++type WebPushController struct {+ WebPushRepo *repo.WebPushRepository+ Links *LinksController+}++type spaceWebPushConfig struct {+ PublicKey string+ PrivateKey string+ Subscriber string+}++func (c *WebPushController) VAPIDPublicKey() (*models.SpaceWebPushVAPIDKeyResponse, error) {+ config, ok := configuredSpaceWebPush()+ if !ok {+ return nil, &ente.ApiError{+ Code: ente.ErrorCode("SPACE_WEB_PUSH_UNAVAILABLE"),+ Message: "space web push is unavailable",+ HttpStatusCode: http.StatusServiceUnavailable,+ }+ }+ return &models.SpaceWebPushVAPIDKeyResponse{PublicKey: config.PublicKey}, nil+}++func (c *WebPushController) UpsertAccountSubscription(+ ctx *gin.Context,+ sessionToken string,+ req models.SpaceWebPushSubscriptionRequest,+) (*models.SpaceWebPushTargetResponse, error) {+ if c == nil || c.WebPushRepo == nil {+ return nil, ente.ErrNotFound+ }+ endpoint, p256dh, auth, err := validatedWebPushSubscription(req)+ if err != nil {+ return nil, err+ }+ sessionHash := sha256.Sum256([]byte(sessionToken))+ targetID, err := c.WebPushRepo.UpsertAccountSubscription(+ ctx,+ sessionHash[:],+ endpoint,+ p256dh,+ auth,+ )+ if err != nil {+ return nil, err+ }+ return &models.SpaceWebPushTargetResponse{TargetID: targetID}, nil+}++func (c *WebPushController) DeleteAccountSubscription(+ ctx *gin.Context,+ sessionToken string,+ req models.SpaceWebPushUnsubscriptionRequest,+) error {+ if c == nil || c.WebPushRepo == nil {+ return ente.ErrNotFound+ }+ endpoint := strings.TrimSpace(req.Endpoint)+ if err := validateWebPushEndpoint(endpoint); err != nil {+ return err+ }+ sessionHash := sha256.Sum256([]byte(sessionToken))+ return c.WebPushRepo.DeleteAccountSubscription(ctx, sessionHash[:], endpoint)+}++func (c *WebPushController) UpsertLinkSubscription(+ ctx *gin.Context,+ slug string,+ req models.SpaceWebPushSubscriptionRequest,+) (*models.SpaceWebPushTargetResponse, error) {+ if c == nil || c.WebPushRepo == nil || c.Links == nil {+ return nil, ente.ErrNotFound+ }+ endpoint, p256dh, auth, err := validatedWebPushSubscription(req)+ if err != nil {+ return nil, err+ }+ link, err := c.Links.Authorize(ctx, slug)+ if err != nil {+ return nil, err+ }+ targetID, err := c.WebPushRepo.UpsertLinkSubscription(+ ctx,+ link.LinkID,+ endpoint,+ p256dh,+ auth,+ )+ if err != nil {+ if errors.Is(err, repo.ErrSpaceWebPushLinkSubscriptionLimit) {+ return nil, &ente.ApiError{+ Code: ente.ErrorCode("SPACE_WEB_PUSH_SUBSCRIPTION_LIMIT"),+ Message: "too many web push subscriptions for this Space link",+ HttpStatusCode: http.StatusTooManyRequests,+ }+ }+ if errors.Is(stacktrace.RootCause(err), sql.ErrNoRows) {+ return nil, ente.ErrNotFound+ }+ return nil, err+ }+ return &models.SpaceWebPushTargetResponse{TargetID: targetID}, nil+}++func (c *WebPushController) DeleteLinkSubscription(+ ctx *gin.Context,+ slug string,+ req models.SpaceWebPushUnsubscriptionRequest,+) error {+ if c == nil || c.WebPushRepo == nil || c.Links == nil {+ return ente.ErrNotFound+ }+ endpoint := strings.TrimSpace(req.Endpoint)+ if err := validateWebPushEndpoint(endpoint); err != nil {+ return err+ }+ link, err := c.Links.Authorize(ctx, slug)+ if err != nil {+ return err+ }+ return c.WebPushRepo.DeleteLinkSubscription(ctx, link.LinkID, endpoint)+}++func validatedWebPushSubscription(+ req models.SpaceWebPushSubscriptionRequest,+) (string, string, string, error) {+ endpoint := strings.TrimSpace(req.Endpoint)+ p256dh := strings.TrimSpace(req.Keys.P256dh)+ auth := strings.TrimSpace(req.Keys.Auth)+ if err := validateWebPushSubscription(endpoint, p256dh, auth); err != nil {+ return "", "", "", err+ }+ return endpoint, p256dh, auth, nil+}++func validateWebPushSubscription(endpoint, p256dh, auth string) error {+ if err := validateWebPushEndpoint(endpoint); err != nil {+ return err+ }+ if p256dh == "" || len(p256dh) > spaceWebPushP256dhMaxBytes {+ return ente.NewBadRequestWithMessage("invalid web push p256dh key")+ }+ decodedP256dh, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(p256dh, "="))+ _, publicKeyErr := ecdh.P256().NewPublicKey(decodedP256dh)+ if err != nil || len(decodedP256dh) != 65 || publicKeyErr != nil {+ return ente.NewBadRequestWithMessage("invalid web push p256dh key")+ }+ if auth == "" || len(auth) > spaceWebPushAuthMaxBytes {+ return ente.NewBadRequestWithMessage("invalid web push auth key")+ }+ decodedAuth, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(auth, "="))+ if err != nil || len(decodedAuth) != 16 {+ return ente.NewBadRequestWithMessage("invalid web push auth key")+ }+ return nil+}++func configuredSpaceWebPush() (spaceWebPushConfig, bool) {+ config := spaceWebPushConfig{+ PublicKey: strings.TrimSpace(viper.GetString("space.webPush.publicKey")),+ PrivateKey: strings.TrimSpace(viper.GetString("space.webPush.privateKey")),+ Subscriber: strings.TrimSpace(viper.GetString("space.webPush.subscriber")),+ }+ decodedPublicKey, publicKeyErr := decodeBase64URL(config.PublicKey)+ _, publicCurveErr := ecdh.P256().NewPublicKey(decodedPublicKey)+ decodedPrivateKey, privateKeyErr := decodeBase64URL(config.PrivateKey)+ privateKey, privateCurveErr := ecdh.P256().NewPrivateKey(decodedPrivateKey)+ subscriber, subscriberErr := mail.ParseAddress(config.Subscriber)+ if publicKeyErr != nil ||+ len(decodedPublicKey) != 65 ||+ publicCurveErr != nil ||+ privateKeyErr != nil ||+ len(decodedPrivateKey) != 32 ||+ privateCurveErr != nil ||+ !bytes.Equal(privateKey.PublicKey().Bytes(), decodedPublicKey) ||+ subscriberErr != nil ||+ subscriber.Address != config.Subscriber {+ return spaceWebPushConfig{}, false+ }+ return config, true+}++func decodeBase64URL(value string) ([]byte, error) {+ return base64.RawURLEncoding.DecodeString(strings.TrimRight(value, "="))+}++func validateWebPushEndpoint(endpoint string) error {+ if endpoint == "" ||+ len(endpoint) > spaceWebPushEndpointMaxBytes ||+ strings.Contains(endpoint, "#") {+ return ente.NewBadRequestWithMessage("invalid web push endpoint")+ }+ parsed, err := url.ParseRequestURI(endpoint)+ if err != nil ||+ parsed.Scheme != "https" ||+ parsed.Hostname() == "" ||+ parsed.User != nil ||+ parsed.Fragment != "" {+ return ente.NewBadRequestWithMessage("invalid web push endpoint")+ }+ return nil+}diff --git a/server/space/models/models.go b/server/space/models/models.goindex c671ba8878..79ca7322c2 100644--- a/server/space/models/models.go+++ b/server/space/models/models.go@@ -20,6 +20,28 @@ type SpaceBrowserSessionBootstrapResponse struct {SessionWrapKey string `json:"sessionWrapKey"`}+type SpaceWebPushVAPIDKeyResponse struct {+ PublicKey string `json:"publicKey"`+}++type SpaceWebPushSubscriptionKeys struct {+ P256dh string `json:"p256dh" binding:"required"`+ Auth string `json:"auth" binding:"required"`+}++type SpaceWebPushSubscriptionRequest struct {+ Endpoint string `json:"endpoint" binding:"required"`+ Keys SpaceWebPushSubscriptionKeys `json:"keys" binding:"required"`+}++type SpaceWebPushUnsubscriptionRequest struct {+ Endpoint string `json:"endpoint" binding:"required"`+}++type SpaceWebPushTargetResponse struct {+ TargetID string `json:"targetId"`+}+type GetSpaceProfileRequest struct {SpaceID string `form:"spaceId"`ViewerSpaceID string `form:"viewerSpaceId"`diff --git a/server/space/repo/links.go b/server/space/repo/links.goindex c19847304b..0986ab07bf 100644--- a/server/space/repo/links.go+++ b/server/space/repo/links.go@@ -213,6 +213,16 @@ func (r *LinksRepository) Rotate(`, spaceID); err != nil {return nil, stacktrace.Propagate(err, "")}+ if _, err := tx.ExecContext(ctx, `+ DELETE FROM space_web_push_subscriptions+ WHERE link_id IN (+ SELECT link_id+ FROM space_links+ WHERE space_id = $1 AND active = FALSE+ )+ `, spaceID); err != nil {+ return nil, stacktrace.Propagate(err, "")+ }var linkID int64err = tx.QueryRowContext(ctx, `INSERT INTO space_links (diff --git a/server/space/repo/messages.go b/server/space/repo/messages.goindex 4ee5e4472d..c78a21765f 100644--- a/server/space/repo/messages.go+++ b/server/space/repo/messages.go@@ -294,25 +294,40 @@ func (r *MessagesRepository) ListThread(ctx context.Context, viewerSpaceID strin}func (r *MessagesRepository) SetLike(ctx context.Context, messageID string, actorSpaceID string, like bool) error {+ _, err := r.SetLikeWithChanged(ctx, messageID, actorSpaceID, like)+ return err+}++func (r *MessagesRepository) SetLikeWithChanged(ctx context.Context, messageID string, actorSpaceID string, like bool) (bool, error) {if like {- _, err := r.DB.ExecContext(ctx, `+ result, err := r.DB.ExecContext(ctx, `UPDATE space_messages- SET recipient_liked_at = COALESCE(recipient_liked_at, now_utc_micro_seconds())+ SET recipient_liked_at = now_utc_micro_seconds()WHERE message_id = $1AND recipient_space_id = $2AND kind IN ('regular', 'post_reply')AND is_deleted = FALSE+ AND recipient_liked_at IS NULL`, messageID, actorSpaceID)- return stacktrace.Propagate(err, "")+ if err != nil {+ return false, stacktrace.Propagate(err, "")+ }+ affected, err := result.RowsAffected()+ return affected > 0, stacktrace.Propagate(err, "")}- _, err := r.DB.ExecContext(ctx, `+ result, err := r.DB.ExecContext(ctx, `UPDATE space_messagesSET recipient_liked_at = NULLWHERE message_id = $1AND recipient_space_id = $2AND kind IN ('regular', 'post_reply')+ AND recipient_liked_at IS NOT NULL`, messageID, actorSpaceID)- return stacktrace.Propagate(err, "")+ if err != nil {+ return false, stacktrace.Propagate(err, "")+ }+ affected, err := result.RowsAffected()+ return affected > 0, stacktrace.Propagate(err, "")}func (r *MessagesRepository) DeleteMessage(ctx context.Context, messageID string, senderSpaceID string) error {diff --git a/server/space/repo/module.go b/server/space/repo/module.goindex 8d23c627a8..4332d61ca0 100644--- a/server/space/repo/module.go+++ b/server/space/repo/module.go@@ -16,6 +16,7 @@ type Module struct {Sessions *SessionsRepositoryDrips *DripsRepositoryLinks *LinksRepository+ WebPush *WebPushRepository}type SpacesRepository struct {@@ -55,6 +56,10 @@ type LinksRepository struct {DB *sql.DB}+type WebPushRepository struct {+ DB *sql.DB+}+type SpaceRecord struct {SpaceID stringOwnerID int64@@ -246,6 +251,15 @@ type SpaceLinkRecord struct {UpdatedAt int64}+type SpaceWebPushSubscriptionRecord struct {+ TargetID string+ Endpoint string+ P256dh string+ Auth string+ UserID int64+ Public bool+}+func NewModule(db *sql.DB, s3Config *s3config.S3Config) *Module {return &Module{Spaces: &SpacesRepository{DB: db},@@ -257,5 +271,6 @@ func NewModule(db *sql.DB, s3Config *s3config.S3Config) *Module {Sessions: &SessionsRepository{DB: db},Drips: &DripsRepository{DB: db},Links: &LinksRepository{DB: db},+ WebPush: &WebPushRepository{DB: db},}}diff --git a/server/space/repo/module_test.go b/server/space/repo/module_test.goindex 3b7e7dc276..abee5c0600 100644--- a/server/space/repo/module_test.go+++ b/server/space/repo/module_test.go@@ -1,6 +1,7 @@package repoimport (+ "bytes""context""crypto/sha256""database/sql"@@ -526,7 +527,10 @@ func TestSpaceAccountDeletionResetAccountDeletionAccess(t *testing.T) {pendingRequest, created, err := testCreateFriendRequest(ctx, module, aliceID, aliceSpace.SpaceID, charlieSpace.SpaceID, "alice-charlie-share-key", aliceSpace.CurrentVersion)require.NoError(t, err)require.True(t, created)- require.NoError(t, module.Sessions.CreateBrowserSession(ctx, []byte("alice-browser-token"), aliceID, "session-wrap-key", timeutil.NDaysFromNow(1)))+ aliceSession := []byte("alice-browser-token")+ require.NoError(t, module.Sessions.CreateBrowserSession(ctx, aliceSession, aliceID, "session-wrap-key", timeutil.NDaysFromNow(1)))+ _, err = module.WebPush.UpsertAccountSubscription(ctx, aliceSession, "https://push.example/alice-reset", "p256dh", "auth")+ require.NoError(t, err)postID, err := testCreatePost(ctx, module, aliceID, aliceSpace.SpaceID, "alice-post-key", nil, aliceSpace.CurrentVersion, nil)require.NoError(t, err)@@ -549,6 +553,7 @@ func TestSpaceAccountDeletionResetAccountDeletionAccess(t *testing.T) {require.Equal(t, int64(1), countSpaceRows(t, module, `SELECT COUNT(*) FROM spaces WHERE owner_id = $1`, aliceID))require.Equal(t, int64(1), countSpaceRows(t, module, `SELECT COUNT(*) FROM space_posts WHERE space_id = $1`, aliceSpace.SpaceID))require.Equal(t, int64(0), countSpaceRows(t, module, `SELECT COUNT(*) FROM space_browser_sessions WHERE user_id = $1`, aliceID))+ require.Equal(t, int64(0), countSpaceRows(t, module, `SELECT COUNT(*) FROM space_web_push_subscriptions WHERE endpoint = $1`, "https://push.example/alice-reset"))require.Equal(t, int64(2), countSpaceRows(t, module, `SELECT COUNT(*) FROM space_friend_shares WHERE space_id = $1 OR friend_space_id = $1`, aliceSpace.SpaceID))require.Equal(t, int64(1), countSpaceRows(t, module, `SELECT COUNT(*) FROM space_friend_requests WHERE requester_space_id = $1 OR target_space_id = $1`, aliceSpace.SpaceID))require.Equal(t, int64(2), countSpaceRows(t, module, `SELECT COUNT(*) FROM space_notification_read_markers WHERE viewer_space_id = $1 OR friend_space_id = $1`, aliceSpace.SpaceID))@@ -591,7 +596,24 @@ func TestSpaceAccountDeletionDeleteUserData(t *testing.T) {ExpectedSize: 44,ExpiresAt: timeutil.NDaysFromNow(1),}))- require.NoError(t, module.Sessions.CreateBrowserSession(ctx, []byte("alice-delete-browser-token"), aliceID, "session-wrap-key", timeutil.NDaysFromNow(1)))+ aliceSession := []byte("alice-delete-browser-token")+ require.NoError(t, module.Sessions.CreateBrowserSession(ctx, aliceSession, aliceID, "session-wrap-key", timeutil.NDaysFromNow(1)))+ _, err = module.WebPush.UpsertAccountSubscription(ctx, aliceSession, "https://push.example/alice-delete", "p256dh", "auth")+ require.NoError(t, err)+ link, err := module.Links.Create(+ ctx,+ aliceSpace.SpaceID,+ bytes.Repeat([]byte{7}, 32),+ bytes.Repeat([]byte{8}, 16),+ 67108864,+ 2,+ aliceSpace.CurrentVersion,+ []byte("encrypted-space-key"),+ []byte("encrypted-access-key"),+ )+ require.NoError(t, err)+ _, err = module.WebPush.UpsertLinkSubscription(ctx, link.LinkID, "https://push.example/alice-public-delete", "p256dh", "auth")+ require.NoError(t, err)require.NoError(t, testAddFriend(ctx, module, bobID, bobSpace.SpaceID, aliceSpace.SpaceID, "alice-share-key", aliceSpace.CurrentVersion, "bob-share-key", bobSpace.CurrentVersion))message, err := module.Messages.CreateMessage(ctx, CreateSpaceMessageRecord{Kind: "regular",@@ -613,6 +635,7 @@ func TestSpaceAccountDeletionDeleteUserData(t *testing.T) {require.Equal(t, int64(0), countSpaceRows(t, module, `SELECT COUNT(*) FROM space_post_assets WHERE object_key = $1`, "space/alice/post-asset"))require.Equal(t, int64(0), countSpaceRows(t, module, `SELECT COUNT(*) FROM space_messages WHERE sender_space_id = $1 OR recipient_space_id = $1`, aliceSpace.SpaceID))require.Equal(t, int64(0), countSpaceRows(t, module, `SELECT COUNT(*) FROM space_browser_sessions WHERE user_id = $1`, aliceID))+ require.Equal(t, int64(0), countSpaceRows(t, module, `SELECT COUNT(*) FROM space_web_push_subscriptions WHERE endpoint IN ($1, $2)`, "https://push.example/alice-delete", "https://push.example/alice-public-delete"))require.Equal(t, int64(0), countSpaceRows(t, module, `SELECT COUNT(*) FROM space_friend_shares WHERE space_id = $1 OR friend_space_id = $1`, aliceSpace.SpaceID))require.Equal(t, int64(0), countSpaceRows(t, module, `SELECT COUNT(*) FROM space_notification_read_markers WHERE viewer_space_id = $1 OR friend_space_id = $1`, aliceSpace.SpaceID))diff --git a/server/space/repo/web_push.go b/server/space/repo/web_push.gonew file mode 100644index 0000000000..9aba69347a--- /dev/null+++ b/server/space/repo/web_push.go@@ -0,0 +1,258 @@+package repo++import (+ "context"+ "errors"++ "github.com/ente/museum/ente/base"+ timeutil "github.com/ente/museum/pkg/utils/time"+ "github.com/ente/stacktrace"+ "github.com/lib/pq"+)++const spaceWebPushLinkSubscriptionLimit = 10000++// ErrSpaceWebPushLinkSubscriptionLimit prevents an individual public link from growing without bound.+var ErrSpaceWebPushLinkSubscriptionLimit = errors.New("space web push link subscription limit reached")++func (r *WebPushRepository) UpsertAccountSubscription(+ ctx context.Context,+ sessionTokenHash []byte,+ endpoint, p256dh, auth string,+) (string, error) {+ tx, err := r.DB.BeginTx(ctx, nil)+ if err != nil {+ return "", stacktrace.Propagate(err, "")+ }+ defer tx.Rollback()++ var sessionExists int+ if err := tx.QueryRowContext(ctx, `+ SELECT 1+ FROM space_browser_sessions+ WHERE token_hash = $1+ FOR UPDATE+ `, sessionTokenHash).Scan(&sessionExists); err != nil {+ return "", stacktrace.Propagate(err, "")+ }+ if _, err := tx.ExecContext(ctx, `+ DELETE FROM space_web_push_subscriptions+ WHERE session_token_hash = $1 AND endpoint <> $2+ `, sessionTokenHash, endpoint); err != nil {+ return "", stacktrace.Propagate(err, "")+ }+ if _, err := tx.ExecContext(ctx, `+ UPDATE space_web_push_subscriptions+ SET p256dh = $2, auth = $3+ WHERE endpoint = $1+ `, endpoint, p256dh, auth); err != nil {+ return "", stacktrace.Propagate(err, "")+ }++ targetID := base.MustNewID("wpt")+ if err := tx.QueryRowContext(ctx, `+ INSERT INTO space_web_push_subscriptions (+ target_id, endpoint, session_token_hash, p256dh, auth+ )+ VALUES ($1, $2, $3, $4, $5)+ ON CONFLICT (endpoint) WHERE session_token_hash IS NOT NULL+ DO UPDATE SET+ session_token_hash = EXCLUDED.session_token_hash,+ p256dh = EXCLUDED.p256dh,+ auth = EXCLUDED.auth+ RETURNING target_id+ `, targetID, endpoint, sessionTokenHash, p256dh, auth).Scan(&targetID); err != nil {+ return "", stacktrace.Propagate(err, "")+ }+ if err := tx.Commit(); err != nil {+ return "", stacktrace.Propagate(err, "")+ }+ return targetID, nil+}++func (r *WebPushRepository) UpsertLinkSubscription(+ ctx context.Context,+ linkID int64,+ endpoint, p256dh, auth string,+) (string, error) {+ tx, err := r.DB.BeginTx(ctx, nil)+ if err != nil {+ return "", stacktrace.Propagate(err, "")+ }+ defer tx.Rollback()++ var activeLinkID int64+ if err := tx.QueryRowContext(ctx, `+ SELECT link_id+ FROM space_links+ WHERE link_id = $1 AND active = TRUE+ FOR UPDATE+ `, linkID).Scan(&activeLinkID); err != nil {+ return "", stacktrace.Propagate(err, "")+ }+ var subscriptionCount int+ var endpointExists bool+ if err := tx.QueryRowContext(ctx, `+ SELECT COUNT(*), COUNT(*) FILTER (WHERE endpoint = $2) > 0+ FROM space_web_push_subscriptions+ WHERE link_id = $1+ `, activeLinkID, endpoint).Scan(&subscriptionCount, &endpointExists); err != nil {+ return "", stacktrace.Propagate(err, "")+ }+ if !endpointExists && subscriptionCount >= spaceWebPushLinkSubscriptionLimit {+ return "", ErrSpaceWebPushLinkSubscriptionLimit+ }+ if _, err := tx.ExecContext(ctx, `+ UPDATE space_web_push_subscriptions+ SET p256dh = $2, auth = $3+ WHERE endpoint = $1+ `, endpoint, p256dh, auth); err != nil {+ return "", stacktrace.Propagate(err, "")+ }++ targetID := base.MustNewID("wpt")+ if err := tx.QueryRowContext(ctx, `+ INSERT INTO space_web_push_subscriptions (+ target_id, endpoint, link_id, p256dh, auth+ )+ VALUES ($1, $2, $3, $4, $5)+ ON CONFLICT (endpoint, link_id)+ DO UPDATE SET+ p256dh = EXCLUDED.p256dh,+ auth = EXCLUDED.auth+ RETURNING target_id+ `, targetID, endpoint, activeLinkID, p256dh, auth).Scan(&targetID); err != nil {+ return "", stacktrace.Propagate(err, "")+ }+ if err := tx.Commit(); err != nil {+ return "", stacktrace.Propagate(err, "")+ }+ return targetID, nil+}++func (r *WebPushRepository) DeleteAccountSubscription(+ ctx context.Context,+ sessionTokenHash []byte,+ endpoint string,+) error {+ _, err := r.DB.ExecContext(ctx, `+ DELETE FROM space_web_push_subscriptions+ WHERE session_token_hash = $1 AND endpoint = $2+ `, sessionTokenHash, endpoint)+ return stacktrace.Propagate(err, "")+}++func (r *WebPushRepository) DeleteLinkSubscription(+ ctx context.Context,+ linkID int64,+ endpoint string,+) error {+ _, err := r.DB.ExecContext(ctx, `+ DELETE FROM space_web_push_subscriptions+ WHERE link_id = $1 AND endpoint = $2+ `, linkID, endpoint)+ return stacktrace.Propagate(err, "")+}++func (r *WebPushRepository) DeleteEndpoint(ctx context.Context, endpoint string) error {+ _, err := r.DB.ExecContext(ctx, `+ DELETE FROM space_web_push_subscriptions+ WHERE endpoint = $1+ `, endpoint)+ return stacktrace.Propagate(err, "")+}++func (r *WebPushRepository) ListActiveAccountSubscriptions(+ ctx context.Context,+ userIDs []int64,+) ([]SpaceWebPushSubscriptionRecord, error) {+ if len(userIDs) == 0 {+ return nil, nil+ }+ rows, err := r.DB.QueryContext(ctx, `+ SELECT push.target_id, push.endpoint, push.p256dh, push.auth, session.user_id+ FROM space_web_push_subscriptions push+ JOIN space_browser_sessions session+ ON session.token_hash = push.session_token_hash+ AND session.expires_at > $2+ JOIN users active_user+ ON active_user.user_id = session.user_id+ AND active_user.encrypted_email IS NOT NULL+ WHERE session.user_id = ANY($1)+ `, pq.Array(userIDs), timeutil.Microseconds())+ if err != nil {+ return nil, stacktrace.Propagate(err, "")+ }+ defer rows.Close()++ var subscriptions []SpaceWebPushSubscriptionRecord+ for rows.Next() {+ var subscription SpaceWebPushSubscriptionRecord+ if err := rows.Scan(+ &subscription.TargetID,+ &subscription.Endpoint,+ &subscription.P256dh,+ &subscription.Auth,+ &subscription.UserID,+ ); err != nil {+ return nil, stacktrace.Propagate(err, "")+ }+ subscriptions = append(subscriptions, subscription)+ }+ return subscriptions, stacktrace.Propagate(rows.Err(), "")+}++func (r *WebPushRepository) ListPostSubscriptions(+ ctx context.Context,+ spaceID string,+ friendUserIDs []int64,+) ([]SpaceWebPushSubscriptionRecord, error) {+ rows, err := r.DB.QueryContext(ctx, `+ SELECT push.target_id, push.endpoint, push.p256dh, push.auth,+ session.user_id, FALSE+ FROM space_web_push_subscriptions push+ JOIN space_browser_sessions session+ ON session.token_hash = push.session_token_hash+ AND session.expires_at > $3+ JOIN users active_user+ ON active_user.user_id = session.user_id+ AND active_user.encrypted_email IS NOT NULL+ WHERE session.user_id = ANY($1)++ UNION ALL++ SELECT push.target_id, push.endpoint, push.p256dh, push.auth,+ 0, TRUE+ FROM space_web_push_subscriptions push+ JOIN space_links link+ ON link.link_id = push.link_id+ AND link.active = TRUE+ JOIN spaces space+ ON space.space_id = link.space_id+ JOIN users active_user+ ON active_user.user_id = space.owner_id+ AND active_user.encrypted_email IS NOT NULL+ WHERE link.space_id = $2+ `, pq.Array(friendUserIDs), spaceID, timeutil.Microseconds())+ if err != nil {+ return nil, stacktrace.Propagate(err, "")+ }+ defer rows.Close()++ var subscriptions []SpaceWebPushSubscriptionRecord+ for rows.Next() {+ var subscription SpaceWebPushSubscriptionRecord+ if err := rows.Scan(+ &subscription.TargetID,+ &subscription.Endpoint,+ &subscription.P256dh,+ &subscription.Auth,+ &subscription.UserID,+ &subscription.Public,+ ); err != nil {+ return nil, stacktrace.Propagate(err, "")+ }+ subscriptions = append(subscriptions, subscription)+ }+ return subscriptions, stacktrace.Propagate(rows.Err(), "")+}diff --git a/server/space/repo/web_push_test.go b/server/space/repo/web_push_test.gonew file mode 100644index 0000000000..ca55717e5c--- /dev/null+++ b/server/space/repo/web_push_test.go@@ -0,0 +1,224 @@+package repo++import (+ "bytes"+ "context"+ "testing"++ timeutil "github.com/ente/museum/pkg/utils/time"+ "github.com/stretchr/testify/require"+)++func TestWebPushSubscriptionsFollowTargetsAndActiveSessions(t *testing.T) {+ module := newSpaceTestModule(t)+ ctx := context.Background()+ ownerID := insertSpaceUser(t, module, "[email protected]", "owner-public")+ friendID := insertSpaceUser(t, module, "[email protected]", "friend-public")+ space, err := testCreateSpace(ctx, module, ownerID, "space_push_owner", "root", "public", "secret", "nonce", "profile")+ require.NoError(t, err)+ link, err := module.Links.Create(+ ctx,+ space.SpaceID,+ bytes.Repeat([]byte{1}, 32),+ bytes.Repeat([]byte{2}, 16),+ 67108864,+ 2,+ space.CurrentVersion,+ []byte("encrypted-space-key"),+ []byte("encrypted-access-key"),+ )+ require.NoError(t, err)++ activeSession := []byte("active-space-web-push-session")+ expiredSession := []byte("expired-space-web-push-session")+ require.NoError(t, module.Sessions.CreateBrowserSession(ctx, activeSession, friendID, "active-wrap", timeutil.NDaysFromNow(1)))+ require.NoError(t, module.Sessions.CreateBrowserSession(ctx, expiredSession, friendID, "expired-wrap", timeutil.Microseconds()-1))++ activeTargetID, err := module.WebPush.UpsertAccountSubscription(+ ctx,+ activeSession,+ "https://push.example/active",+ "active-p256dh",+ "active-auth",+ )+ require.NoError(t, err)+ _, err = module.WebPush.UpsertAccountSubscription(+ ctx,+ activeSession,+ "https://push.example/replaced",+ "replaced-p256dh",+ "replaced-auth",+ )+ require.NoError(t, err)+ _, err = module.WebPush.UpsertAccountSubscription(+ ctx,+ expiredSession,+ "https://push.example/expired",+ "expired-p256dh",+ "expired-auth",+ )+ require.NoError(t, err)+ publicTargetID, err := module.WebPush.UpsertLinkSubscription(+ ctx,+ link.LinkID,+ "https://push.example/public",+ "public-p256dh",+ "public-auth",+ )+ require.NoError(t, err)+ require.NotEqual(t, activeTargetID, publicTargetID)++ accountSubscriptions, err := module.WebPush.ListActiveAccountSubscriptions(ctx, []int64{friendID})+ require.NoError(t, err)+ require.Len(t, accountSubscriptions, 1)+ require.Equal(t, "https://push.example/replaced", accountSubscriptions[0].Endpoint)+ require.Equal(t, friendID, accountSubscriptions[0].UserID)++ postSubscriptions, err := module.WebPush.ListPostSubscriptions(ctx, space.SpaceID, nil)+ require.NoError(t, err)+ require.Equal(t, []SpaceWebPushSubscriptionRecord{{+ TargetID: publicTargetID,+ Endpoint: "https://push.example/public",+ P256dh: "public-p256dh",+ Auth: "public-auth",+ Public: true,+ }}, postSubscriptions)++ require.NoError(t, module.Sessions.DeleteBrowserSession(ctx, activeSession))+ var count int+ require.NoError(t, module.WebPush.DB.QueryRow(`+ SELECT COUNT(*)+ FROM space_web_push_subscriptions+ WHERE endpoint = 'https://push.example/replaced'+ `).Scan(&count))+ require.Zero(t, count)+ require.NoError(t, module.WebPush.DB.QueryRow(`+ SELECT COUNT(*)+ FROM space_web_push_subscriptions+ WHERE endpoint = 'https://push.example/public'+ `).Scan(&count))+ require.Equal(t, 1, count)++ _, err = module.Links.Rotate(+ ctx,+ space.SpaceID,+ bytes.Repeat([]byte{3}, 32),+ bytes.Repeat([]byte{4}, 16),+ 67108864,+ 2,+ space.CurrentVersion,+ []byte("rotated-encrypted-space-key"),+ []byte("rotated-encrypted-access-key"),+ )+ require.NoError(t, err)+ require.NoError(t, module.WebPush.DB.QueryRow(`+ SELECT COUNT(*)+ FROM space_web_push_subscriptions+ WHERE endpoint = 'https://push.example/public'+ `).Scan(&count))+ require.Zero(t, count)+}++func TestWebPushSharedEndpointKeepsIndependentTargets(t *testing.T) {+ module := newSpaceTestModule(t)+ ctx := context.Background()+ ownerID := insertSpaceUser(t, module, "[email protected]", "owner-public")+ space, err := testCreateSpace(ctx, module, ownerID, "space_push_shared", "root", "public", "secret", "nonce", "profile")+ require.NoError(t, err)+ link, err := module.Links.Create(+ ctx,+ space.SpaceID,+ bytes.Repeat([]byte{5}, 32),+ bytes.Repeat([]byte{6}, 16),+ 67108864,+ 2,+ space.CurrentVersion,+ []byte("encrypted-space-key"),+ []byte("encrypted-access-key"),+ )+ require.NoError(t, err)+ session := []byte("shared-space-web-push-session")+ require.NoError(t, module.Sessions.CreateBrowserSession(ctx, session, ownerID, "wrap", timeutil.NDaysFromNow(1)))+ endpoint := "https://push.example/shared"++ _, err = module.WebPush.UpsertAccountSubscription(ctx, session, endpoint, "first-p256dh", "first-auth")+ require.NoError(t, err)+ _, err = module.WebPush.UpsertLinkSubscription(ctx, link.LinkID, endpoint, "second-p256dh", "second-auth")+ require.NoError(t, err)++ var count int+ require.NoError(t, module.WebPush.DB.QueryRow(`+ SELECT COUNT(*)+ FROM space_web_push_subscriptions+ WHERE endpoint = $1+ `, endpoint).Scan(&count))+ require.Equal(t, 2, count)++ require.NoError(t, module.WebPush.DeleteAccountSubscription(ctx, session, endpoint))+ require.NoError(t, module.WebPush.DB.QueryRow(`+ SELECT COUNT(*)+ FROM space_web_push_subscriptions+ WHERE endpoint = $1 AND link_id = $2+ `, endpoint, link.LinkID).Scan(&count))+ require.Equal(t, 1, count)++ require.NoError(t, module.WebPush.DeleteLinkSubscription(ctx, link.LinkID, endpoint))+ require.NoError(t, module.WebPush.DB.QueryRow(`+ SELECT COUNT(*)+ FROM space_web_push_subscriptions+ WHERE endpoint = $1+ `, endpoint).Scan(&count))+ require.Zero(t, count)+}++func TestWebPushLinkSubscriptionLimit(t *testing.T) {+ module := newSpaceTestModule(t)+ ctx := context.Background()+ ownerID := insertSpaceUser(t, module, "[email protected]", "limit-owner")+ space, err := testCreateSpace(ctx, module, ownerID, "space_push_limit", "root", "public", "secret", "nonce", "profile")+ require.NoError(t, err)+ link, err := module.Links.Create(+ ctx,+ space.SpaceID,+ bytes.Repeat([]byte{7}, 32),+ bytes.Repeat([]byte{8}, 16),+ 67108864,+ 2,+ space.CurrentVersion,+ []byte("encrypted-space-key"),+ []byte("encrypted-access-key"),+ )+ require.NoError(t, err)++ _, err = module.WebPush.DB.Exec(`+ INSERT INTO space_web_push_subscriptions (+ target_id, endpoint, link_id, p256dh, auth+ )+ SELECT+ 'wpt_limit_' || value,+ 'https://push.example/limit/' || value,+ $1,+ 'p256dh',+ 'auth'+ FROM generate_series(1, $2) value+ `, link.LinkID, spaceWebPushLinkSubscriptionLimit)+ require.NoError(t, err)++ _, err = module.WebPush.UpsertLinkSubscription(+ ctx,+ link.LinkID,+ "https://push.example/limit/new",+ "p256dh",+ "auth",+ )+ require.ErrorIs(t, err, ErrSpaceWebPushLinkSubscriptionLimit)++ _, err = module.WebPush.UpsertLinkSubscription(+ ctx,+ link.LinkID,+ "https://push.example/limit/1",+ "updated-p256dh",+ "updated-auth",+ )+ require.NoError(t, err)+}diff --git a/server/tools/gen-vapid-keys/main.go b/server/tools/gen-vapid-keys/main.gonew file mode 100644index 0000000000..39fc6fe22b--- /dev/null+++ b/server/tools/gen-vapid-keys/main.go@@ -0,0 +1,18 @@+package main++import (+ "fmt"+ "os"++ webpush "github.com/SherClockHolmes/webpush-go"+)++func main() {+ privateKey, publicKey, err := webpush.GenerateVAPIDKeys()+ if err != nil {+ fmt.Fprintln(os.Stderr, err)+ os.Exit(1)+ }+ fmt.Printf("space.webPush.publicKey: %s\n", publicKey)+ fmt.Printf("space.webPush.privateKey: %s\n", privateKey)+}diff --git a/web/apps/space/public/_redirects b/web/apps/space/public/_redirectsindex 47a4c2b731..05067fd7c0 100644--- a/web/apps/space/public/_redirects+++ b/web/apps/space/public/_redirects@@ -9,10 +9,10 @@/app/profile/photo /app/profile/photo 200/app/profile/photo-edit /app/profile/photo-edit 200/app/settings /app/settings 200-/app/settings/profile /app/settings/profile 200/app/settings/profile/name /app/settings/profile/name 200/login /login 200/manifest.webmanifest /manifest.webmanifest 200+/manifest-public.webmanifest /manifest-public.webmanifest 200/passkeys/finish /passkeys/finish 200/passkeys/verify /passkeys/verify 200/create-profile /create-profile 200diff --git a/web/apps/space/public/manifest-public.webmanifest b/web/apps/space/public/manifest-public.webmanifestnew file mode 100644index 0000000000..b05fd33938--- /dev/null+++ b/web/apps/space/public/manifest-public.webmanifest@@ -0,0 +1,24 @@+{+ "name": "Ente Space",+ "short_name": "Ente Space",+ "description": "Share everyday moments with friends and family, privately.",+ "id": "/app",+ "scope": "/",+ "display": "standalone",+ "background_color": "#08C225",+ "theme_color": "#FFFFFF",+ "icons": [+ {+ "src": "/images/pwa-icon-192.png",+ "sizes": "192x192",+ "type": "image/png",+ "purpose": "any maskable"+ },+ {+ "src": "/images/pwa-icon-512.png",+ "sizes": "512x512",+ "type": "image/png",+ "purpose": "any maskable"+ }+ ]+}diff --git a/web/apps/space/public/manifest.webmanifest b/web/apps/space/public/manifest.webmanifestindex 61ed5a265b..8d42361611 100644--- a/web/apps/space/public/manifest.webmanifest+++ b/web/apps/space/public/manifest.webmanifest@@ -2,6 +2,7 @@"name": "Ente Space","short_name": "Ente Space","description": "Share everyday moments with friends and family, privately.",+ "id": "/app","start_url": "/app","scope": "/","display": "standalone",diff --git a/web/apps/space/public/sw.js b/web/apps/space/public/sw.jsnew file mode 100644index 0000000000..7619ac6b4e--- /dev/null+++ b/web/apps/space/public/sw.js@@ -0,0 +1,113 @@+const pushDatabaseName = "ente-space-web-push";+const pushDatabaseVersion = 1;+const pushTargetStoreName = "targets";++self.addEventListener("push", (event) => {+ let payload = {};+ try {+ payload = event.data ? event.data.json() : {};+ } catch {+ payload = {};+ }++ event.waitUntil(+ notificationURL(payload).then((url) =>+ self.registration.showNotification(notificationTitle(payload), {+ actions: notificationActions(payload),+ body: notificationBody(payload),+ data: { url },+ icon: "/images/pwa-icon-192.png",+ }),+ ),+ );+});++self.addEventListener("notificationclick", (event) => {+ event.notification.close();+ event.waitUntil(+ notificationURL(event.notification.data).then(async (url) => {+ const destination = new URL(url, self.location.origin).href;+ const windows = await self.clients.matchAll({+ includeUncontrolled: true,+ type: "window",+ });+ const client = windows.find(+ (candidate) =>+ new URL(candidate.url).origin == self.location.origin,+ );+ if (client) {+ await client.navigate(destination);+ return client.focus();+ }+ return self.clients.openWindow(destination);+ }),+ );+});++const notificationTitle = (payload) =>+ typeof payload?.title == "string" && payload.title.trim()+ ? payload.title.trim()+ : "Ente Space";++const notificationBody = (payload) =>+ typeof payload?.body == "string" ? payload.body.trim() : "";++const notificationActions = (payload) =>+ typeof payload?.action == "string" && payload.action.trim()+ ? [{ action: "open", title: payload.action.trim() }]+ : [];++const notificationURL = async (payload) => {+ if (typeof payload?.targetId == "string" && payload.targetId) {+ const route = await routeForTarget(payload.targetId);+ if (route) return safeRoute(route);+ }+ return safeRoute(payload?.url);+};++const safeRoute = (value) => {+ if (typeof value != "string") return "/app";+ try {+ const url = new URL(value, self.location.origin);+ if (url.origin != self.location.origin) return "/app";+ return `${url.pathname}${url.search}${url.hash}`;+ } catch {+ return "/app";+ }+};++const routeForTarget = async (targetId) => {+ try {+ const database = await openPushDatabase();+ return await new Promise((resolve, reject) => {+ const transaction = database.transaction(+ pushTargetStoreName,+ "readonly",+ );+ const request = transaction+ .objectStore(pushTargetStoreName)+ .index("targetId")+ .get(targetId);+ request.onerror = () => reject(request.error);+ request.onsuccess = () => resolve(request.result?.route);+ });+ } catch {+ return undefined;+ }+};++const openPushDatabase = () =>+ new Promise((resolve, reject) => {+ const request = indexedDB.open(pushDatabaseName, pushDatabaseVersion);+ request.onupgradeneeded = () => {+ const database = request.result;+ if (!database.objectStoreNames.contains(pushTargetStoreName)) {+ const store = database.createObjectStore(pushTargetStoreName, {+ keyPath: "key",+ });+ store.createIndex("targetId", "targetId");+ }+ };+ request.onerror = () => reject(request.error);+ request.onsuccess = () => resolve(request.result);+ });diff --git a/web/apps/space/src/components/SpaceNotificationPermissionInstructions.tsx b/web/apps/space/src/components/SpaceNotificationPermissionInstructions.tsxnew file mode 100644index 0000000000..d743d52e42--- /dev/null+++ b/web/apps/space/src/components/SpaceNotificationPermissionInstructions.tsx@@ -0,0 +1,116 @@+import { Box, Dialog, useMediaQuery } from "@mui/material";+import { SpaceBottomSheetTransition } from "components/SpaceBottomSheetTransition";+import { isSpaceIOS } from "hooks/useSpacePWAInstallPrompt";+import React from "react";++const green = "#08C225";++interface SpaceNotificationPermissionInstructionsProps {+ onClose: () => void;+ open: boolean;+}++export const SpaceNotificationPermissionInstructions: React.FC<+ SpaceNotificationPermissionInstructionsProps+> = ({ onClose, open }) => {+ const titleID = React.useId();+ const isBottomSheet = useMediaQuery("(max-width: 599px)");+ const steps = isSpaceIOS()+ ? [+ "Open Settings",+ 'Tap "Notifications"',+ 'Tap "Ente Space" and turn on "Allow Notifications"',+ ]+ : [+ "Open your browser's site settings for Space",+ 'Find "Notifications"',+ 'Choose "Allow"',+ ];++ return (+ <Dialog+ open={open}+ onClose={onClose}+ aria-labelledby={titleID}+ maxWidth={false}+ sx={{ "--space-dialog-backdrop": "rgba(0 0 0 / 0.56)" }}+ slots={+ isBottomSheet+ ? { transition: SpaceBottomSheetTransition }+ : undefined+ }+ slotProps={{+ paper: {+ sx: {+ borderRadius: "28px 28px 0 0",+ bottom: 0,+ m: 0,+ p: "26px 20px calc(24px + env(safe-area-inset-bottom))",+ position: "fixed",+ width: "100vw",+ "@media (min-width: 600px)": {+ borderRadius: "20px",+ bottom: "auto",+ left: "50%",+ maxWidth: 342,+ p: "24px 20px 20px",+ top: "50%",+ transform: "translate(-50%, -50%)",+ },+ },+ },+ }}+ >+ <Box+ component="h2"+ id={titleID}+ sx={{+ fontFamily: '"Inter Variable", Inter, sans-serif',+ fontSize: 16,+ fontWeight: 650,+ m: 0,+ textAlign: "center",+ }}+ >+ Turn on notifications+ </Box>+ <Box+ component="ol"+ sx={{+ color: "#555",+ display: "grid",+ fontFamily: '"Inter Variable", Inter, sans-serif',+ fontSize: 14,+ gap: "12px",+ lineHeight: "20px",+ my: "22px",+ pl: "28px",+ }}+ >+ {steps.map((step) => (+ <li key={step}>{step}</li>+ ))}+ </Box>+ <Box+ className="green-bg"+ component="button"+ type="button"+ onClick={onClose}+ sx={{+ bgcolor: green,+ border: 0,+ borderRadius: "20px",+ color: "#FFFFFF",+ cursor: "pointer",+ fontFamily: '"Inter Variable", Inter, sans-serif',+ fontSize: 14,+ fontWeight: 650,+ height: 48,+ width: "100%",+ }}+ >+ Got it+ </Box>+ </Dialog>+ );+};diff --git a/web/apps/space/src/components/SpacePWAInstallPrompt.tsx b/web/apps/space/src/components/SpacePWAInstallPrompt.tsxindex 7ed5dbbfa6..a7428185b5 100644--- a/web/apps/space/src/components/SpacePWAInstallPrompt.tsx+++ b/web/apps/space/src/components/SpacePWAInstallPrompt.tsx@@ -3,19 +3,24 @@ import {ArrowDown01Icon,MoreHorizontalIcon,MoreVerticalIcon,+ MultiplicationSignIcon,+ Notification02Icon,ScreenAddToHomeIcon,Upload01Icon,} from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";import { Box, Dialog, useMediaQuery } from "@mui/material";-import { SpaceActionToast } from "components/SpaceActionToast";import { SpaceBottomSheetTransition } from "components/SpaceBottomSheetTransition";import { useSpacePWAInstallPrompt } from "hooks/useSpacePWAInstallPrompt";+import { useSpaceWebPushPrompt } from "hooks/useSpaceWebPushPrompt";import React from "react";+import { spaceTouchTargetSize } from "styles/touchTargets";const green = "#08C225";const textBase = "#000";const textSoft = "#777777";+const authenticatedSessionSeenKey = "space.prompts.authenticatedSessionSeen";+const automaticPromptClaimedKey = "space.prompts.automaticClaimed";interface SpacePWAInstallPromptProps {enabled: boolean;@@ -29,75 +34,113 @@ interface InstallStep {export const SpacePWAInstallPrompt: React.FC<SpacePWAInstallPromptProps> = ({enabled,}) => {- const { dismiss, mode, shouldShow } = useSpacePWAInstallPrompt();+ const installPrompt = useSpacePWAInstallPrompt();+ const webPushPrompt = useSpaceWebPushPrompt();const [instructionsOpen, setInstructionsOpen] = React.useState(false);- const showPrompt = enabled && shouldShow;+ const [automaticAllowed] = React.useState(() => {+ try {+ if (sessionStorage.getItem(automaticPromptClaimedKey)) return false;+ const seen = localStorage.getItem(authenticatedSessionSeenKey);+ localStorage.setItem(authenticatedSessionSeenKey, "1");+ if (seen != "1") {+ sessionStorage.setItem(automaticPromptClaimedKey, "1");+ }+ return seen == "1";+ } catch {+ return false;+ }+ });+ const [claimedPrompt, setClaimedPrompt] = React.useState<+ "install" | "webPush" | null+ >(null);+ const hasCandidate = webPushPrompt.shouldShow || installPrompt.shouldShow;React.useEffect(() => {- if (!showPrompt) setInstructionsOpen(false);- }, [showPrompt]);+ if (+ !enabled ||+ !automaticAllowed ||+ claimedPrompt ||+ !webPushPrompt.isResolved ||+ !hasCandidate+ ) {+ return;+ }+ try {+ sessionStorage.setItem(automaticPromptClaimedKey, "1");+ } catch {+ return;+ }+ setClaimedPrompt(+ webPushPrompt.shouldShow+ ? "webPush"+ : installPrompt.shouldShow+ ? "install"+ : null,+ );+ }, [+ automaticAllowed,+ claimedPrompt,+ enabled,+ hasCandidate,+ installPrompt.shouldShow,+ webPushPrompt.isResolved,+ webPushPrompt.shouldShow,+ ]);++ const showWebPushPrompt =+ enabled && claimedPrompt == "webPush" && webPushPrompt.shouldShow;+ const showInstallPrompt =+ enabled && claimedPrompt == "install" && installPrompt.shouldShow;- if (!showPrompt) return null;+ React.useEffect(() => {+ if (!showInstallPrompt) setInstructionsOpen(false);+ }, [showInstallPrompt]);- const openInstructions = () => setInstructionsOpen(true);+ if (!showWebPushPrompt && !showInstallPrompt) return null;++ const addToHomeScreen = () => {+ if (installPrompt.mode == "native") {+ void installPrompt.install();+ } else {+ setInstructionsOpen(true);+ }+ };const closeInstructions = () => setInstructionsOpen(false);const dismissInstructions = () => {setInstructionsOpen(false);- dismiss();+ installPrompt.dismiss();};return (<>- <SpaceActionToast- action={- <Box- className="green-bg"- component="button"- type="button"- onClick={openInstructions}- sx={{- alignItems: "center",- bgcolor: green,- border: 0,- borderRadius: "14px",- color: "#FFFFFF",- cursor: "pointer",- display: "flex",- flexShrink: 0,- fontFamily: '"Inter Variable", Inter, sans-serif',- fontSize: 13,- fontWeight: 700,- height: 34,- justifyContent: "center",- lineHeight: "18px",- minWidth: 48,- px: "17px",- transition: "filter 120ms ease",- "&:active": { filter: "brightness(0.96)" },- "&:focus-visible": {- outline: "2px solid rgba(0 0 0 / 0.72)",- outlineOffset: 2,- },- "&:hover": { filter: "brightness(0.98)" },- }}- >- Add- </Box>- }- closeLabel="Close install prompt"- icon={- <HugeiconsIcon- icon={ScreenAddToHomeIcon}- size={24}- strokeWidth={1.9}- />- }- message="Add to home screen"- onClose={dismiss}- zIndex={19}- />+ {showWebPushPrompt ? (+ <SpacePWAPromptBanner+ actionDisabled={webPushPrompt.isEnabling}+ actionLabel={+ webPushPrompt.isEnabling ? "Turning onβ¦" : "Turn on"+ }+ dismissLabel="Close notification prompt"+ icon={Notification02Icon}+ label={+ webPushPrompt.needsRecovery+ ? "Turn notifications back on"+ : "Turn on notifications"+ }+ onAction={() => void webPushPrompt.enable()}+ onDismiss={webPushPrompt.dismiss}+ />+ ) : (+ <SpacePWAPromptBanner+ actionLabel="Add"+ dismissLabel="Close install prompt"+ icon={ScreenAddToHomeIcon}+ label="Add to home screen"+ onAction={addToHomeScreen}+ onDismiss={installPrompt.dismiss}+ />+ )}<SpacePWAInstallInstructions- mode={mode}+ mode={installPrompt.mode}open={instructionsOpen}onClose={closeInstructions}onDismiss={dismissInstructions}@@ -106,6 +149,143 @@ export const SpacePWAInstallPrompt: React.FC<SpacePWAInstallPromptProps> = ({);};+interface SpacePWAPromptBannerProps {+ actionDisabled?: boolean;+ actionLabel: string;+ dismissLabel: string;+ icon: Parameters<typeof HugeiconsIcon>[0]["icon"];+ label: string;+ onAction: () => void;+ onDismiss: () => void;+}++const SpacePWAPromptBanner: React.FC<SpacePWAPromptBannerProps> = ({+ actionDisabled,+ actionLabel,+ dismissLabel,+ icon,+ label,+ onAction,+ onDismiss,+}) => (+ <Box+ sx={{+ boxSizing: "border-box",+ left: "50%",+ px: "16px",+ pointerEvents: "none",+ position: "fixed",+ top: "calc(env(safe-area-inset-top) + 10px)",+ transform: "translateX(-50%)",+ width: "100%",+ zIndex: 19,+ "@media (min-width: 600px)": { maxWidth: 390 },+ }}+ >+ <Box+ role="status"+ aria-live="polite"+ sx={{+ alignItems: "center",+ bgcolor: "#FFFFFF",+ borderRadius: "18px",+ boxShadow: "0 12px 32px rgba(0, 0, 0, 0.18)",+ color: textBase,+ display: "flex",+ fontFamily: '"Inter Variable", Inter, sans-serif',+ fontSize: 14,+ fontWeight: 650,+ gap: "10px",+ lineHeight: "20px",+ minHeight: 50,+ pointerEvents: "auto",+ pl: "10px",+ pr: "6px",+ py: "3px",+ width: "100%",+ }}+ >+ <Box+ component="span"+ sx={{+ alignItems: "center",+ color: green,+ display: "flex",+ flexShrink: 0,+ height: 24,+ justifyContent: "center",+ width: 24,+ }}+ >+ <HugeiconsIcon icon={icon} size={24} strokeWidth={1.9} />+ </Box>+ <Box+ sx={{+ flex: "1 1 auto",+ minWidth: 0,+ overflow: "hidden",+ textOverflow: "ellipsis",+ whiteSpace: "nowrap",+ }}+ >+ {label}+ </Box>+ <Box sx={{ alignItems: "center", display: "flex", flexShrink: 0 }}>+ <Box+ className="green-bg"+ component="button"+ type="button"+ disabled={actionDisabled}+ onClick={onAction}+ sx={{+ alignItems: "center",+ bgcolor: green,+ border: 0,+ borderRadius: "14px",+ color: "#FFFFFF",+ cursor: actionDisabled ? "default" : "pointer",+ display: "flex",+ fontFamily: '"Inter Variable", Inter, sans-serif',+ fontSize: 13,+ fontWeight: 700,+ height: 34,+ justifyContent: "center",+ minWidth: 48,+ opacity: actionDisabled ? 0.7 : 1,+ px: "17px",+ }}+ >+ {actionLabel}+ </Box>+ <Box+ component="button"+ type="button"+ aria-label={dismissLabel}+ onClick={onDismiss}+ sx={{+ alignItems: "center",+ bgcolor: "transparent",+ border: 0,+ color: textBase,+ cursor: "pointer",+ display: "flex",+ height: spaceTouchTargetSize,+ justifyContent: "center",+ p: 0,+ width: 36,+ }}+ >+ <HugeiconsIcon+ icon={MultiplicationSignIcon}+ size={16}+ strokeWidth={2}+ />+ </Box>+ </Box>+ </Box>+ </Box>+);+interface SpacePWAInstallInstructionsProps {mode: ReturnType<typeof useSpacePWAInstallPrompt>["mode"];open: boolean;@@ -113,7 +293,7 @@ interface SpacePWAInstallInstructionsProps {onDismiss: () => void;}-const SpacePWAInstallInstructions: React.FC<+export const SpacePWAInstallInstructions: React.FC<SpacePWAInstallInstructionsProps> = ({ mode, open, onClose, onDismiss }) => {const titleID = React.useId();diff --git a/web/apps/space/src/components/SpaceProfileImagePages.tsx b/web/apps/space/src/components/SpaceProfileImagePages.tsxindex dfee8eb2e2..04933b8d7e 100644--- a/web/apps/space/src/components/SpaceProfileImagePages.tsx+++ b/web/apps/space/src/components/SpaceProfileImagePages.tsx@@ -39,7 +39,7 @@ const editProfileRouteFor = (: spaceRoutes.editProfilePhotoFrom(source);const savedRouteFor = (source: ProfileImageFlowSource) =>- source == "settings" ? spaceRoutes.settingsProfile : spaceRoutes.profile;+ source == "settings" ? spaceRoutes.settings : spaceRoutes.profile;export const SpaceProfileImageViewerPage: React.FC<{variant: ProfileImageVariant;diff --git a/web/apps/space/src/components/SpacePublicProfileNotificationControl.tsx b/web/apps/space/src/components/SpacePublicProfileNotificationControl.tsxnew file mode 100644index 0000000000..d22e03bddd--- /dev/null+++ b/web/apps/space/src/components/SpacePublicProfileNotificationControl.tsx@@ -0,0 +1,234 @@+import {+ Notification02Icon,+ ScreenAddToHomeIcon,+} from "@hugeicons/core-free-icons";+import { HugeiconsIcon, type IconSvgElement } from "@hugeicons/react";+import { Box } from "@mui/material";+import { SpaceNotificationPermissionInstructions } from "components/SpaceNotificationPermissionInstructions";+import { SpacePWAInstallInstructions } from "components/SpacePWAInstallPrompt";+import {+ isSpaceIOS,+ isSpaceStandalone,+ useSpacePWAInstallPrompt,+} from "hooks/useSpacePWAInstallPrompt";+import React from "react";+import type { PublicSpaceLinkSession } from "services/space";+import {+ isSpaceWebPushSupported,+ reconcilePublicSpaceWebPush,+ subscribeToPublicSpaceWebPush,+ type SpaceWebPushState,+} from "services/spaceWebPush";++interface SpacePublicProfileNotificationControlProps {+ session: PublicSpaceLinkSession;+}++export const SpacePublicProfileNotificationControl: React.FC<+ SpacePublicProfileNotificationControlProps+> = ({ session }) => {+ const installPrompt = useSpacePWAInstallPrompt();+ const updating = React.useRef(false);+ const [state, setState] = React.useState<SpaceWebPushState>("unavailable");+ const [busy, setBusy] = React.useState(true);+ const [installInstructionsOpen, setInstallInstructionsOpen] =+ React.useState(false);+ const [permissionInstructionsOpen, setPermissionInstructionsOpen] =+ React.useState(false);+ const route =+ typeof window == "undefined"+ ? ""+ : `${window.location.pathname}${window.location.search}${window.location.hash}`;+ const requiresIOSInstall = isSpaceIOS() && !isSpaceStandalone();++ const reconcile = React.useCallback(async () => {+ if (!route || !isSpaceWebPushSupported() || requiresIOSInstall) {+ setState("unavailable");+ setBusy(false);+ return;+ }+ try {+ setState(await reconcilePublicSpaceWebPush(session, route));+ } catch (error) {+ console.warn(+ "Failed to reconcile public Space notifications",+ error,+ );+ setState("recovery");+ } finally {+ setBusy(false);+ }+ }, [requiresIOSInstall, route, session]);++ React.useEffect(() => {+ let running = false;+ const check = () => {+ if (running || updating.current) return;+ running = true;+ void reconcile().finally(() => {+ running = false;+ });+ };+ const checkWhenVisible = () => {+ if (document.visibilityState == "visible") check();+ };++ check();+ window.addEventListener("focus", check);+ document.addEventListener("visibilitychange", checkWhenVisible);+ return () => {+ window.removeEventListener("focus", check);+ document.removeEventListener("visibilitychange", checkWhenVisible);+ };+ }, [reconcile]);++ const canShowNotifications =+ !requiresIOSInstall && isSpaceWebPushSupported();+ const showNotificationButton =+ canShowNotifications &&+ (updating.current ||+ (!busy && state != "subscribed" && state != "unavailable"));+ const showNotificationStatus =+ canShowNotifications && !busy && state == "subscribed";+ const showInstall = requiresIOSInstall && installPrompt.canInstall;+ const reserveControlSpace =+ busy && (canShowNotifications || requiresIOSInstall);+ if (+ !showNotificationButton &&+ !showNotificationStatus &&+ !showInstall &&+ !reserveControlSpace+ ) {+ return null;+ }++ const enable = async () => {+ if (Notification.permission == "denied") {+ setPermissionInstructionsOpen(true);+ return;+ }+ updating.current = true;+ setBusy(true);+ try {+ const permission = await subscribeToPublicSpaceWebPush(+ session,+ route,+ );+ if (permission == "granted") {+ setState("subscribed");+ } else if (permission == "denied") {+ setState("denied");+ setPermissionInstructionsOpen(true);+ }+ } catch (error) {+ console.warn("Failed to update public Space notifications", error);+ setState("recovery");+ } finally {+ updating.current = false;+ setBusy(false);+ }+ };++ const label = busy ? "Enablingβ¦" : "Get notified of new posts";++ return (+ <>+ <Box+ sx={{+ alignItems: "center",+ display: "flex",+ flexWrap: "wrap",+ gap: "8px",+ justifyContent: "center",+ minHeight: 40,+ mt: "14px",+ }}+ >+ {showNotificationButton && (+ <PublicProfileControlButton+ busy={busy}+ icon={Notification02Icon}+ label={label}+ onClick={() => void enable()}+ />+ )}+ {showNotificationStatus && <PublicProfileNotificationStatus />}+ {showInstall && (+ <PublicProfileControlButton+ icon={ScreenAddToHomeIcon}+ label="Add to home screen"+ onClick={() => setInstallInstructionsOpen(true)}+ />+ )}+ </Box>+ <SpacePWAInstallInstructions+ mode={installPrompt.mode}+ open={installInstructionsOpen}+ onClose={() => setInstallInstructionsOpen(false)}+ onDismiss={() => setInstallInstructionsOpen(false)}+ />+ <SpaceNotificationPermissionInstructions+ open={permissionInstructionsOpen}+ onClose={() => setPermissionInstructionsOpen(false)}+ />+ </>+ );+};++const PublicProfileNotificationStatus: React.FC = () => (+ <Box+ role="status"+ sx={{+ alignItems: "center",+ color: "#777777",+ display: "inline-flex",+ fontFamily: '"Inter Variable", Inter, sans-serif',+ fontSize: 14,+ fontWeight: 500,+ gap: "8px",+ minHeight: 40,+ }}+ >+ <HugeiconsIcon icon={Notification02Icon} size={18} strokeWidth={1.9} />+ Youβll be notified of new posts+ </Box>+);++const PublicProfileControlButton: React.FC<{+ busy?: boolean;+ icon: IconSvgElement;+ label: string;+ onClick: () => void;+}> = ({ busy, icon, label, onClick }) => (+ <Box+ component="button"+ type="button"+ disabled={busy}+ onClick={onClick}+ sx={{+ alignItems: "center",+ appearance: "none",+ bgcolor: "#F2F2F2",+ border: 0,+ borderRadius: "14px",+ color: "#1B1B1B",+ cursor: busy ? "default" : "pointer",+ display: "inline-flex",+ fontFamily: '"Inter Variable", Inter, sans-serif',+ fontSize: 14,+ fontWeight: 600,+ gap: "8px",+ minHeight: 40,+ opacity: busy ? 0.7 : 1,+ px: "16px",+ "&:hover": { bgcolor: busy ? "#F2F2F2" : "#E7E7E7" },+ "&:focus-visible": {+ outline: "2px solid #1B1B1B",+ outlineOffset: 2,+ },+ }}+ >+ <HugeiconsIcon icon={icon} size={18} strokeWidth={1.9} />+ {label}+ </Box>+);diff --git a/web/apps/space/src/hooks/useSpacePWAInstallPrompt.ts b/web/apps/space/src/hooks/useSpacePWAInstallPrompt.tsindex 5727483f06..8ad7177e27 100644--- a/web/apps/space/src/hooks/useSpacePWAInstallPrompt.ts+++ b/web/apps/space/src/hooks/useSpacePWAInstallPrompt.ts@@ -1,25 +1,53 @@import React from "react";-type SpacePWAInstallMode =+export type SpacePWAInstallMode =| "android-fallback"| "ios-chrome"| "ios-fallback"- | "ios-safari";+ | "ios-safari"+ | "native";++interface BeforeInstallPromptEvent extends Event {+ prompt: () => Promise<void>;+ userChoice: Promise<{ outcome: "accepted" | "dismissed" }>;+}interface SpacePWAInstallPromptState {+ canInstall: boolean;dismiss: () => void;+ install: () => Promise<void>;mode: SpacePWAInstallMode | null;shouldShow: boolean;}const dismissedUntilKey = "space.pwaInstall.dismissedUntil";const dismissalDurationMs = 14 * 24 * 60 * 60 * 1000;+const promptListeners = new Set<() => void>();+let deferredInstallPrompt: BeforeInstallPromptEvent | undefined;const hasWindow = () => typeof window != "undefined";-const isIOS = () => {- if (!hasWindow()) return false;+export const captureSpacePWAInstallPrompt = () => {+ if (!hasWindow()) return;+ const beforeInstallPrompt = (event: Event) => {+ event.preventDefault();+ deferredInstallPrompt = event as BeforeInstallPromptEvent;+ promptListeners.forEach((listener) => listener());+ };+ const appInstalled = () => {+ deferredInstallPrompt = undefined;+ promptListeners.forEach((listener) => listener());+ };+ window.addEventListener("beforeinstallprompt", beforeInstallPrompt);+ window.addEventListener("appinstalled", appInstalled);+ return () => {+ window.removeEventListener("beforeinstallprompt", beforeInstallPrompt);+ window.removeEventListener("appinstalled", appInstalled);+ };+};+export const isSpaceIOS = () => {+ if (!hasWindow()) return false;const { maxTouchPoints, userAgent } = navigator;return (/iPad|iPhone|iPod/.test(userAgent) ||@@ -30,8 +58,7 @@ const isIOS = () => {const isAndroid = () => hasWindow() && /Android/i.test(navigator.userAgent);const isIOSSafari = () => {- if (!isIOS()) return false;-+ if (!isSpaceIOS()) return false;const { userAgent } = navigator;return (/Safari/i.test(userAgent) &&@@ -39,20 +66,9 @@ const isIOSSafari = () => {);};-const isIOSChrome = () => isIOS() && /CriOS/i.test(navigator.userAgent);--const isAndroidNativePromptBrowser = () => {- if (!isAndroid()) return false;-- const { userAgent } = navigator;- if (/Firefox|OPR\/|Opera/i.test(userAgent)) return false;- return /Chrome|Chromium|EdgA|SamsungBrowser/i.test(userAgent);-};--const shouldShowAndroidInstructions = () =>- isAndroid() && !isAndroidNativePromptBrowser();+const isIOSChrome = () => isSpaceIOS() && /CriOS/i.test(navigator.userAgent);-const isStandalone = () =>+export const isSpaceStandalone = () =>hasWindow() &&(window.matchMedia("(display-mode: standalone)").matches ||("standalone" in navigator &&@@ -84,15 +100,22 @@ const storageRemove = (key: string) => {const isDismissed = () => {if (!hasWindow()) return true;-const dismissedUntil = Number(storageGet(dismissedUntilKey));if (!Number.isFinite(dismissedUntil) || dismissedUntil <= 0) return false;if (dismissedUntil > Date.now()) return true;-storageRemove(dismissedUntilKey);return false;};+const currentMode = (): SpacePWAInstallMode | null => {+ if (isIOSChrome()) return "ios-chrome";+ if (isIOSSafari()) return "ios-safari";+ if (isSpaceIOS()) return "ios-fallback";+ if (!isAndroid()) return null;+ if (deferredInstallPrompt) return "native";+ return "android-fallback";+};+export const useSpacePWAInstallPrompt = (): SpacePWAInstallPromptState => {const [mode, setMode] = React.useState<SpacePWAInstallMode | null>(null);const [dismissed, setDismissed] = React.useState(true);@@ -100,29 +123,21 @@ export const useSpacePWAInstallPrompt = (): SpacePWAInstallPromptState => {React.useEffect(() => {if (!hasWindow()) return;-setDismissed(isDismissed());- setInstalled(isStandalone());-- if (isIOSChrome()) {- setMode("ios-chrome");- } else if (isIOSSafari()) {- setMode("ios-safari");- } else if (isIOS()) {- setMode("ios-fallback");- } else if (shouldShowAndroidInstructions()) {- setMode("android-fallback");- }+ setInstalled(isSpaceStandalone());+ setMode(currentMode());+ const promptChanged = () => setMode(currentMode());const appInstalled = () => {setInstalled(true);setMode(null);};- const standaloneChange = () => setInstalled(isStandalone());+ const standaloneChange = () => setInstalled(isSpaceStandalone());const standaloneQuery = window.matchMedia("(display-mode: standalone)");const supportsEventListener =typeof standaloneQuery.addEventListener == "function";+ promptListeners.add(promptChanged);window.addEventListener("appinstalled", appInstalled);if (supportsEventListener) {standaloneQuery.addEventListener("change", standaloneChange);@@ -132,6 +147,7 @@ export const useSpacePWAInstallPrompt = (): SpacePWAInstallPromptState => {}return () => {+ promptListeners.delete(promptChanged);window.removeEventListener("appinstalled", appInstalled);if (supportsEventListener) {standaloneQuery.removeEventListener("change", standaloneChange);@@ -147,9 +163,26 @@ export const useSpacePWAInstallPrompt = (): SpacePWAInstallPromptState => {setDismissed(true);}, []);+ const install = React.useCallback(async () => {+ const prompt = deferredInstallPrompt;+ if (!prompt) return;+ await prompt.prompt();+ const choice = await prompt.userChoice;+ deferredInstallPrompt = undefined;+ promptListeners.forEach((listener) => listener());+ if (choice.outcome == "accepted") {+ setInstalled(true);+ } else {+ dismiss();+ }+ }, [dismiss]);++ const canInstall = Boolean(mode) && !installed;return {+ canInstall,dismiss,+ install,mode,- shouldShow: Boolean(mode) && !dismissed && !installed,+ shouldShow: canInstall && !dismissed,};};diff --git a/web/apps/space/src/hooks/useSpaceWebPushPrompt.ts b/web/apps/space/src/hooks/useSpaceWebPushPrompt.tsnew file mode 100644index 0000000000..193f7958ab--- /dev/null+++ b/web/apps/space/src/hooks/useSpaceWebPushPrompt.ts@@ -0,0 +1,172 @@+import { isSpaceIOS, isSpaceStandalone } from "hooks/useSpacePWAInstallPrompt";+import React from "react";+import {+ isSpaceWebPushSupported,+ reconcileSpaceWebPush,+ subscribeToSpaceWebPush,+ unsubscribeFromSpaceWebPush,+ type SpaceWebPushState,+} from "services/spaceWebPush";++type PromptStatus = "enabling" | "error" | "hidden" | "loading" | "ready";++const dismissedUntilKey = "space.webPush.dismissedUntil";+const dismissalDurationMs = 14 * 24 * 60 * 60 * 1000;++const storageGet = (key: string) => {+ try {+ return window.localStorage.getItem(key);+ } catch {+ return null;+ }+};++const storageSet = (key: string, value: string) => {+ try {+ window.localStorage.setItem(key, value);+ } catch {+ return;+ }+};++const storageRemove = (key: string) => {+ try {+ window.localStorage.removeItem(key);+ } catch {+ return;+ }+};++const isDismissed = () => {+ const dismissedUntil = Number(storageGet(dismissedUntilKey));+ if (!Number.isFinite(dismissedUntil) || dismissedUntil <= 0) return false;+ if (dismissedUntil > Date.now()) return true;+ storageRemove(dismissedUntilKey);+ return false;+};++export const useSpaceWebPushPrompt = () => {+ const updating = React.useRef(false);+ const [isAvailable, setIsAvailable] = React.useState(false);+ const [isSubscribed, setIsSubscribed] = React.useState<boolean | null>(+ null,+ );+ const [needsRecovery, setNeedsRecovery] = React.useState(false);+ const [permissionDenied, setPermissionDenied] = React.useState(false);+ const [status, setStatus] = React.useState<PromptStatus>("loading");++ React.useEffect(() => {+ const available =+ isSpaceWebPushSupported() && (!isSpaceIOS() || isSpaceStandalone());+ setIsAvailable(available);+ if (!available) {+ setStatus("hidden");+ return;+ }++ let cancelled = false;+ let running = false;+ const applyState = (state: SpaceWebPushState) => {+ if (cancelled) return;+ const subscribed = state == "subscribed";+ const recovery = state == "recovery";+ const denied =+ state == "denied" || Notification.permission == "denied";+ const available = state != "unavailable";+ setIsAvailable(available);+ setIsSubscribed(available ? subscribed : null);+ setNeedsRecovery(recovery);+ setPermissionDenied(denied);+ setStatus(+ available &&+ (state == "unsubscribed" || recovery) &&+ !isDismissed()+ ? "ready"+ : "hidden",+ );+ };+ const reconcile = async () => {+ if (running || updating.current) return;+ running = true;+ try {+ applyState(await reconcileSpaceWebPush());+ } catch (error) {+ console.warn("Failed to prepare Space notifications", error);+ if (!cancelled) setStatus(isDismissed() ? "hidden" : "error");+ } finally {+ running = false;+ }+ };+ const visible = () => {+ if (document.visibilityState == "visible") void reconcile();+ };++ void reconcile();+ window.addEventListener("focus", reconcile);+ document.addEventListener("visibilitychange", visible);+ return () => {+ cancelled = true;+ window.removeEventListener("focus", reconcile);+ document.removeEventListener("visibilitychange", visible);+ };+ }, []);++ const dismiss = React.useCallback(() => {+ storageSet(dismissedUntilKey, String(Date.now() + dismissalDurationMs));+ setStatus("hidden");+ }, []);++ const enable = React.useCallback(async () => {+ updating.current = true;+ setStatus("enabling");+ try {+ const permission = await subscribeToSpaceWebPush();+ if (permission == "granted") {+ setIsSubscribed(true);+ setNeedsRecovery(false);+ setPermissionDenied(false);+ setStatus("hidden");+ } else if (permission == "default") {+ dismiss();+ } else {+ setIsSubscribed(false);+ setPermissionDenied(true);+ setStatus("hidden");+ }+ } catch (error) {+ console.warn("Failed to enable Space notifications", error);+ setStatus("error");+ } finally {+ updating.current = false;+ }+ }, [dismiss]);++ const disable = React.useCallback(async () => {+ updating.current = true;+ setStatus("enabling");+ try {+ await unsubscribeFromSpaceWebPush();+ setIsSubscribed(false);+ setNeedsRecovery(false);+ dismiss();+ } catch (error) {+ console.warn("Failed to disable Space notifications", error);+ setStatus("error");+ } finally {+ updating.current = false;+ }+ }, [dismiss]);++ return {+ dismiss,+ enable,+ isAvailable,+ isEnabling: status == "enabling",+ isResolved: status != "loading",+ isSubscribed,+ needsRecovery,+ permissionDenied,+ shouldShow: status == "ready" || status == "error",+ toggle: isSubscribed === true ? disable : enable,+ };+};diff --git a/web/apps/space/src/pages/_app.tsx b/web/apps/space/src/pages/_app.tsxindex 98f617f4c8..c31cacb86e 100644--- a/web/apps/space/src/pages/_app.tsx+++ b/web/apps/space/src/pages/_app.tsx@@ -8,10 +8,13 @@ import "configureZod";import { CustomHead } from "ente-base/components/Head";import { useSetupLogs } from "ente-base/components/utils/hooks-app";import { shareTheme } from "ente-base/components/utils/theme";+import { captureSpacePWAInstallPrompt } from "hooks/useSpacePWAInstallPrompt";import type { AppProps } from "next/app";+import { useRouter } from "next/router";import "photoswipe/dist/photoswipe.css";import React from "react";import "react-easy-crop/react-easy-crop.css";+import { registerSpaceServiceWorker } from "services/spaceWebPush";import { SpaceAppStateProvider } from "state/SpaceAppStateProvider";import "styles/globals.css";@@ -32,6 +35,15 @@ const spaceTheme = createTheme(shareTheme, {const App: React.FC<AppProps> = ({ Component, pageProps }) => {useSetupLogs({ disableDiskLogs: true });+ const router = useRouter();+ const publicProfileManifest = /^\/[^/?#]+#/.test(router.asPath);++ React.useEffect(captureSpacePWAInstallPrompt, []);+ React.useEffect(() => {+ void registerSpaceServiceWorker().catch((error: unknown) =>+ console.warn("Failed to register the Space service worker", error),+ );+ }, []);return (<ThemeProvider@@ -52,7 +64,14 @@ const App: React.FC<AppProps> = ({ Component, pageProps }) => {name="apple-mobile-web-app-status-bar-style"content="default"/>- <link rel="manifest" href="/manifest.webmanifest" />+ <link+ rel="manifest"+ href={+ publicProfileManifest+ ? "/manifest-public.webmanifest"+ : "/manifest.webmanifest"+ }+ /><linkrel="apple-touch-icon"href="/images/apple-touch-icon.png"diff --git a/web/apps/space/src/pages/app/settings.tsx b/web/apps/space/src/pages/app/settings.tsxindex 39c3ba720a..a6df294f1a 100644--- a/web/apps/space/src/pages/app/settings.tsx+++ b/web/apps/space/src/pages/app/settings.tsx@@ -32,8 +32,14 @@ const Page: React.FC = () => {<SpacePageMeta themeColor={settingsBackground} /><SettingsScreenonBack={() => void router.push(spaceRoutes.profile)}- onOpenProfile={() =>- void router.push(spaceRoutes.settingsProfile)+ onChangeCoverImage={() =>+ void router.push(spaceRoutes.profileCoverFrom("settings"))+ }+ onChangeName={() =>+ void router.push(spaceRoutes.settingsProfileName)+ }+ onChangeProfilePicture={() =>+ void router.push(spaceRoutes.profilePhotoFrom("settings"))}onLogout={async () => {await spaceLogout();diff --git a/web/apps/space/src/pages/app/settings/profile.tsx b/web/apps/space/src/pages/app/settings/profile.tsxdeleted file mode 100644index acf5503423..0000000000--- a/web/apps/space/src/pages/app/settings/profile.tsx+++ /dev/null@@ -1,50 +0,0 @@-import { SpacePageMeta } from "components/SpacePageMeta";-import { SpaceRouteFallback } from "components/SpaceRouteFallback";-import React, { useEffect } from "react";-import {- ProfileSettingsScreen,- settingsBackground,-} from "screens/SettingsScreen";-import { useSpaceAppState } from "state/spaceAppState";-import { spaceRoutes } from "utils/spaceRoutes";-import { useSpaceRouter } from "utils/spaceRouteTransitions";--const Page: React.FC = () => {- const router = useSpaceRouter();- const { profile, profileLoadError, profileLoadStatus } = useSpaceAppState();-- useEffect(() => {- if (profileLoadStatus == "ready" && !profile) {- void router.replace(spaceRoutes.onboarding);- }- }, [profile, profileLoadStatus, router]);-- if (profileLoadStatus != "ready" || !profile) {- return (- <SpaceRouteFallback- background={settingsBackground}- message={profileLoadError}- />- );- }-- return (- <>- <SpacePageMeta themeColor={settingsBackground} />- <ProfileSettingsScreen- onBack={() => void router.push(spaceRoutes.settings)}- onChangeCoverImage={() =>- void router.push(spaceRoutes.profileCoverFrom("settings"))- }- onChangeName={() =>- void router.push(spaceRoutes.settingsProfileName)- }- onChangeProfilePicture={() =>- void router.push(spaceRoutes.profilePhotoFrom("settings"))- }- />- </>- );-};--export default Page;diff --git a/web/apps/space/src/pages/app/settings/profile/name.tsx b/web/apps/space/src/pages/app/settings/profile/name.tsxindex 15062e7781..1c1c5176e7 100644--- a/web/apps/space/src/pages/app/settings/profile/name.tsx+++ b/web/apps/space/src/pages/app/settings/profile/name.tsx@@ -43,14 +43,14 @@ const Page: React.FC = () => {errorMessage={errorMessage}initialName={profile.fullName}isSaving={isSaving}- onBack={() => void router.push(spaceRoutes.settingsProfile)}+ onBack={() => void router.push(spaceRoutes.settings)}onSave={(fullName) => {setErrorMessage(undefined);setIsSaving(true);void saveSpaceProfile({ ...profile, fullName }).then((savedProfile) => {setProfile(savedProfile);- void router.push(spaceRoutes.settingsProfile);+ void router.push(spaceRoutes.settings);}).catch((error: unknown) => {log.error("Space name update failed", error);diff --git a/web/apps/space/src/pages/index.tsx b/web/apps/space/src/pages/index.tsxindex 5fc3471663..519322fd91 100644--- a/web/apps/space/src/pages/index.tsx+++ b/web/apps/space/src/pages/index.tsx@@ -3,6 +3,7 @@ import { AuthenticatedFriendProfile } from "components/AuthenticatedFriendProfilimport { SpaceButtonSpinner } from "components/SpaceButtonSpinner";import { SpaceMobileBestToast } from "components/SpaceMobileBestToast";import { SpacePageMeta } from "components/SpacePageMeta";+import { SpacePublicProfileNotificationControl } from "components/SpacePublicProfileNotificationControl";import { SpaceRouteFallback } from "components/SpaceRouteFallback";import log from "ente-base/log";import React, { useEffect, useMemo, useState } from "react";@@ -643,6 +644,11 @@ export const Page: React.FC<PageProps> = ({ invitePreview }) => {postGroups={publicPostGroups}postsCount={publicLink.postsCount}profile={publicLink.profile}+ publicNotificationControl={+ <SpacePublicProfileNotificationControl+ session={publicLink}+ />+ }showAddingFriendSpinner={isAddingFriend && Boolean(profile)}diff --git a/web/apps/space/src/screens/HomeScreen.tsx b/web/apps/space/src/screens/HomeScreen.tsxindex c1fdeca0fc..748717ab84 100644--- a/web/apps/space/src/screens/HomeScreen.tsx+++ b/web/apps/space/src/screens/HomeScreen.tsx@@ -532,14 +532,22 @@ const pageScrollY = () =>);const scrollPageToTop = () => {- const scrollOptions: ScrollToOptions = { behavior: "auto", top: 0 };- document.scrollingElement?.scrollTo(scrollOptions);- window.scrollTo(scrollOptions);+ const behavior = window.matchMedia("(prefers-reduced-motion: reduce)")+ .matches+ ? "auto"+ : "smooth";+ window.scrollTo({ behavior, top: 0 });};const scheduleScrollPageToTop = () => {- const timeoutID = window.setTimeout(scrollPageToTop, 0);- return () => window.clearTimeout(timeoutID);+ let scrollFrame = 0;+ const closeFrame = window.requestAnimationFrame(() => {+ scrollFrame = window.requestAnimationFrame(scrollPageToTop);+ });+ return () => {+ window.cancelAnimationFrame(closeFrame);+ window.cancelAnimationFrame(scrollFrame);+ };};const useHideHeaderOnScrollDirection = () => {@@ -2469,6 +2477,8 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({}onDraftPostExitStart={() => {setIsDraftPostExiting(true);+ }}+ onDraftPostPublished={() => {setFeedScrollRequest((request) => request + 1);}}onSetPostLiked={onSetPostLiked}diff --git a/web/apps/space/src/screens/ProfileScreen.tsx b/web/apps/space/src/screens/ProfileScreen.tsxindex 03b201858a..3588021cb1 100644--- a/web/apps/space/src/screens/ProfileScreen.tsx+++ b/web/apps/space/src/screens/ProfileScreen.tsx@@ -478,6 +478,7 @@ interface ProfileScreenProps {postsCount?: number;profile: SetupProfile;profileLink?: string;+ publicNotificationControl?: React.ReactNode;}export const ProfileScreen: React.FC<ProfileScreenProps> = ({@@ -509,6 +510,7 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({postsCount,profile,profileLink,+ publicNotificationControl,showAddingFriendSpinner = isAddingFriend,showPostLoadingIndicator,}) => {@@ -1674,6 +1676,7 @@ export const ProfileScreen: React.FC<ProfileScreenProps> = ({</Box></Box>)}+ {isPublicProfile && publicNotificationControl}</Box></Box><Boxdiff --git a/web/apps/space/src/screens/SettingsScreen.tsx b/web/apps/space/src/screens/SettingsScreen.tsxindex c3ab7cafd6..2b52d86a02 100644--- a/web/apps/space/src/screens/SettingsScreen.tsx+++ b/web/apps/space/src/screens/SettingsScreen.tsx@@ -5,15 +5,24 @@ import {CustomerSupportIcon,Image01Icon,Logout05Icon,+ Notification02Icon,+ ScreenAddToHomeIcon,UserEdit01Icon,- UserIcon,} from "@hugeicons/core-free-icons";import { HugeiconsIcon, type IconSvgElement } from "@hugeicons/react";import { Box } from "@mui/material";import { ConfirmationActionSheet } from "components/ConfirmationActionSheet";import type { SpaceActionPhase } from "components/SpaceActionFeedback";import { SpaceButtonSpinner } from "components/SpaceButtonSpinner";+import { SpaceNotificationPermissionInstructions } from "components/SpaceNotificationPermissionInstructions";+import { SpacePWAInstallInstructions } from "components/SpacePWAInstallPrompt";import log from "ente-base/log";+import {+ isSpaceIOS,+ isSpaceStandalone,+ useSpacePWAInstallPrompt,+} from "hooks/useSpacePWAInstallPrompt";+import { useSpaceWebPushPrompt } from "hooks/useSpaceWebPushPrompt";import React from "react";import { spaceTouchTargetSize } from "styles/touchTargets";@@ -62,7 +71,9 @@ const spaceLinks = [interface SettingsScreenProps {onLogout: () => Promise<void>;onBack?: () => void;- onOpenProfile: () => void;+ onChangeCoverImage: () => void;+ onChangeName: () => void;+ onChangeProfilePicture: () => void;}interface SettingsRowProps {@@ -71,6 +82,8 @@ interface SettingsRowProps {icon: IconSvgElement;label: string;onClick?: () => void;+ trailingOnClick?: () => void;+ toggleState?: boolean | null;}interface SpaceIconProps {@@ -79,13 +92,6 @@ interface SpaceIconProps {url: string;}-interface ProfileSettingsScreenProps {- onBack: () => void;- onChangeCoverImage: () => void;- onChangeName: () => void;- onChangeProfilePicture: () => void;-}-interface ChangeNameSettingsScreenProps {errorMessage?: string;initialName: string;@@ -100,84 +106,177 @@ const SettingsRow: React.FC<SettingsRowProps> = ({icon,label,onClick,-}) => (- <Box- component={href ? "a" : "button"}- href={href}- rel={href?.startsWith("http") ? "noopener noreferrer" : undefined}- target={href?.startsWith("http") ? "_blank" : undefined}- type={href ? undefined : "button"}- onClick={onClick}- sx={{- alignItems: "center",- bgcolor: rowBackground,- border: 0,- borderRadius: "20px",- boxSizing: "border-box",- cursor: "pointer",- display: "flex",- justifyContent: "space-between",- minHeight: 56,- p: "8px",- textDecoration: "none",- textAlign: "left",- transition: "background-color 120ms ease",- width: "100%",- "&:active": { bgcolor: "rgba(0, 0, 0, 0.025)" },- "&:focus-visible": {- outline: `2px solid ${green}`,- outlineOffset: 2,- },- "&:hover": { bgcolor: "rgba(0, 0, 0, 0.025)" },- }}- >+ trailingOnClick,+ toggleState,+}) => {+ const rowInteractive = Boolean(href || onClick);+ const chevron = (+ <HugeiconsIcon+ aria-hidden+ icon={ChevronRightIcon}+ size={20}+ strokeWidth={1.8}+ style={{ color: textBase, flexShrink: 0 }}+ />+ );++ return (<Box+ component={href ? "a" : onClick ? "button" : "div"}+ href={href}+ rel={href?.startsWith("http") ? "noopener noreferrer" : undefined}+ target={href?.startsWith("http") ? "_blank" : undefined}+ type={onClick ? "button" : undefined}+ onClick={onClick}sx={{alignItems: "center",+ bgcolor: rowBackground,+ border: 0,+ borderRadius: "20px",+ boxSizing: "border-box",+ cursor: rowInteractive ? "pointer" : "default",display: "flex",- gap: "4px",- minWidth: 0,+ justifyContent: "space-between",+ minHeight: 56,+ p: "8px",+ textDecoration: "none",+ textAlign: "left",+ transition: "background-color 120ms ease",+ width: "100%",+ ...(rowInteractive && {+ "&:active": { bgcolor: "rgba(0, 0, 0, 0.025)" },+ "&:focus-visible": {+ outline: `2px solid ${green}`,+ outlineOffset: 2,+ },+ "&:hover": { bgcolor: "rgba(0, 0, 0, 0.025)" },+ }),}}><Boxsx={{alignItems: "center",- borderRadius: "12px",- color: danger ? dangerColor : iconMuted,display: "flex",- flexShrink: 0,- height: 40,- justifyContent: "center",- width: 40,- }}- >- <HugeiconsIcon icon={icon} size={20} strokeWidth={1.6} />- </Box>- <Box- sx={{- color: danger ? dangerColor : textBase,- fontFamily: '"Inter Variable", Inter, sans-serif',- fontSize: 14,- fontWeight: 600,- lineHeight: "17px",+ gap: "4px",minWidth: 0,- overflow: "hidden",- textOverflow: "ellipsis",- whiteSpace: "nowrap",}}>- {label}+ <Box+ sx={{+ alignItems: "center",+ borderRadius: "12px",+ color: danger ? dangerColor : iconMuted,+ display: "flex",+ flexShrink: 0,+ height: 40,+ justifyContent: "center",+ width: 40,+ }}+ >+ <HugeiconsIcon icon={icon} size={20} strokeWidth={1.6} />+ </Box>+ <Box+ sx={{+ color: danger ? dangerColor : textBase,+ fontFamily: '"Inter Variable", Inter, sans-serif',+ fontSize: 14,+ fontWeight: 600,+ lineHeight: "17px",+ minWidth: 0,+ overflow: "hidden",+ textOverflow: "ellipsis",+ whiteSpace: "nowrap",+ }}+ >+ {label}+ </Box></Box>+ {toggleState === undefined ? (+ trailingOnClick ? (+ <Box+ component="button"+ type="button"+ aria-label={label}+ onClick={trailingOnClick}+ sx={{+ alignItems: "center",+ bgcolor: "transparent",+ border: 0,+ borderRadius: "50%",+ cursor: "pointer",+ display: "flex",+ height: 40,+ justifyContent: "center",+ width: 40,+ "&:focus-visible": {+ outline: `2px solid ${green}`,+ outlineOffset: 1,+ },+ }}+ >+ {chevron}+ </Box>+ ) : (+ chevron+ )+ ) : toggleState === null ? null : (+ <Box+ component="button"+ type="button"+ aria-checked={toggleState}+ aria-label={label}+ disabled={!trailingOnClick}+ onClick={trailingOnClick}+ role="switch"+ sx={{+ alignItems: "center",+ bgcolor: "transparent",+ border: 0,+ borderRadius: "12px",+ cursor: trailingOnClick ? "pointer" : "default",+ display: "flex",+ flexShrink: 0,+ height: 40,+ justifyContent: "center",+ mr: "2px",+ p: 0,+ width: 52,+ "&:focus-visible": {+ outline: `2px solid ${green}`,+ outlineOffset: 1,+ },+ }}+ >+ <Box+ aria-hidden+ sx={{+ bgcolor: toggleState ? green : "#D6D6D6",+ borderRadius: "999px",+ height: 24,+ p: "2px",+ transition: "background-color 160ms ease",+ width: 42,+ }}+ >+ <Box+ sx={{+ bgcolor: "#FFFFFF",+ borderRadius: "50%",+ boxShadow: "0 1px 3px rgba(0, 0, 0, 0.24)",+ height: 20,+ transform: toggleState+ ? "translateX(18px)"+ : "translateX(0)",+ transition: "transform 160ms ease",+ width: 20,+ }}+ />+ </Box>+ </Box>+ )}</Box>- <HugeiconsIcon- aria-hidden- icon={ChevronRightIcon}- size={20}- strokeWidth={1.8}- style={{ color: textBase, flexShrink: 0 }}- />- </Box>-);+ );+};const SpaceIcon: React.FC<SpaceIconProps> = ({ label, src, url }) => (<Box@@ -217,11 +316,40 @@ const SpaceIcon: React.FC<SpaceIconProps> = ({ label, src, url }) => (</Box>);+const SettingsEyebrow: React.FC<{ children: React.ReactNode }> = ({+ children,+}) => (+ <Box+ component="h2"+ sx={{+ color: textLight,+ fontFamily: '"Inter Variable", Inter, sans-serif',+ fontSize: 11,+ fontWeight: 700,+ letterSpacing: "0.8px",+ lineHeight: "16px",+ m: 0,+ px: "8px",+ "&:not(:first-child)": { mt: "16px" },+ }}+ >+ {children}+ </Box>+);+export const SettingsScreen: React.FC<SettingsScreenProps> = ({onLogout,onBack,- onOpenProfile,+ onChangeCoverImage,+ onChangeName,+ onChangeProfilePicture,}) => {+ const installPrompt = useSpacePWAInstallPrompt();+ const webPushPrompt = useSpaceWebPushPrompt();+ const [installInstructionsOpen, setInstallInstructionsOpen] =+ React.useState(false);+ const [notificationInstructionsOpen, setNotificationInstructionsOpen] =+ React.useState(false);const [logoutSheetOpen, setLogoutSheetOpen] = React.useState(false);const [logoutActionPhase, setLogoutActionPhase] =React.useState<SpaceActionPhase | null>(null);@@ -229,6 +357,7 @@ export const SettingsScreen: React.FC<SettingsScreenProps> = ({string | null>(null);const isLogoutRunning = logoutActionPhase != null;+ const requiresIOSInstall = isSpaceIOS() && !isSpaceStandalone();const handleConfirmLogout = () => {setLogoutErrorMessage(null);@@ -245,6 +374,24 @@ export const SettingsScreen: React.FC<SettingsScreenProps> = ({setLogoutErrorMessage(null);};+ const addToHomeScreen = () => {+ if (installPrompt.mode == "native") {+ void installPrompt.install();+ } else {+ setInstallInstructionsOpen(true);+ }+ };++ const toggleNotifications = () => {+ if (requiresIOSInstall) {+ setInstallInstructionsOpen(true);+ } else if (webPushPrompt.permissionDenied) {+ setNotificationInstructionsOpen(true);+ } else {+ void webPushPrompt.toggle();+ }+ };+return (<Boxcomponent="main"@@ -337,11 +484,50 @@ export const SettingsScreen: React.FC<SettingsScreenProps> = ({width: "100%",}}>+ <SettingsEyebrow>PROFILE</SettingsEyebrow>+ <SettingsRow+ icon={UserEdit01Icon}+ label="Change name"+ onClick={onChangeName}+ />+ <SettingsRow+ icon={Camera01Icon}+ label="Change profile picture"+ onClick={onChangeProfilePicture}+ /><SettingsRow- icon={UserIcon}- label="Profile"- onClick={onOpenProfile}+ icon={Image01Icon}+ label="Change cover image"+ onClick={onChangeCoverImage}/>+ <SettingsEyebrow>PREFERENCES</SettingsEyebrow>+ <SettingsRow+ icon={Notification02Icon}+ label="Notifications"+ trailingOnClick={+ webPushPrompt.isResolved &&+ !webPushPrompt.isEnabling &&+ (requiresIOSInstall || webPushPrompt.isAvailable)+ ? toggleNotifications+ : undefined+ }+ toggleState={+ requiresIOSInstall+ ? undefined+ : webPushPrompt.isResolved &&+ webPushPrompt.isAvailable+ ? Boolean(webPushPrompt.isSubscribed)+ : null+ }+ />+ {installPrompt.canInstall && (+ <SettingsRow+ icon={ScreenAddToHomeIcon}+ label="Add to home screen"+ onClick={addToHomeScreen}+ />+ )}+ <SettingsEyebrow>GENERAL</SettingsEyebrow><SettingsRowhref={supportMailURL}icon={CustomerSupportIcon}@@ -394,127 +580,20 @@ export const SettingsScreen: React.FC<SettingsScreenProps> = ({onCancel={cancelLogout}onConfirm={handleConfirmLogout}/>+ <SpacePWAInstallInstructions+ mode={installPrompt.mode}+ open={installInstructionsOpen}+ onClose={() => setInstallInstructionsOpen(false)}+ onDismiss={() => setInstallInstructionsOpen(false)}+ />+ <SpaceNotificationPermissionInstructions+ open={notificationInstructionsOpen}+ onClose={() => setNotificationInstructionsOpen(false)}+ /></Box>);};-export const ProfileSettingsScreen: React.FC<ProfileSettingsScreenProps> = ({- onBack,- onChangeCoverImage,- onChangeName,- onChangeProfilePicture,-}) => (- <Box- component="main"- sx={{- bgcolor: settingsBackground,- color: textBase,- display: "grid",- minHeight: "100svh",- overflowX: "hidden",- placeItems: { xs: "stretch", sm: "start center" },- }}- >- <Box- sx={{- bgcolor: settingsBackground,- boxSizing: "border-box",- display: "flex",- flexDirection: "column",- minHeight: "100svh",- mx: "auto",- width: "100%",- "@media (min-width: 600px)": { maxWidth: 390 },- }}- >- <Box- component="header"- sx={{- alignItems: "center",- display: "grid",- gridTemplateColumns: `${spaceTouchTargetSize}px 1fr ${spaceTouchTargetSize}px`,- height: 56,- px: 2,- width: "100%",- }}- >- <Box- component="button"- type="button"- aria-label="Back to settings"- onClick={onBack}- sx={{- alignItems: "center",- bgcolor: "transparent",- border: 0,- color: textBase,- cursor: "pointer",- display: "flex",- height: spaceTouchTargetSize,- justifyContent: "flex-start",- ml: "-2px",- p: 0,- width: spaceTouchTargetSize,- "&:focus-visible": {- borderRadius: "50%",- outline: `2px solid ${green}`,- outlineOffset: 2,- },- }}- >- <HugeiconsIcon- icon={ArrowLeft02Icon}- size={24}- strokeWidth={1.8}- />- </Box>- <Box- component="h1"- sx={{- color: textBase,- fontFamily: '"Inter Variable", Inter, sans-serif',- fontSize: 18,- fontWeight: 700,- justifySelf: "center",- lineHeight: "24px",- m: 0,- }}- >- Profile- </Box>- </Box>-- <Box- component="section"- sx={{- display: "flex",- flexDirection: "column",- gap: "8px",- mt: "24px",- px: "14px",- width: "100%",- }}- >- <SettingsRow- icon={UserEdit01Icon}- label="Change name"- onClick={onChangeName}- />- <SettingsRow- icon={Camera01Icon}- label="Change profile picture"- onClick={onChangeProfilePicture}- />- <SettingsRow- icon={Image01Icon}- label="Change cover image"- onClick={onChangeCoverImage}- />- </Box>- </Box>- </Box>-);-export const ChangeNameSettingsScreen: React.FC<ChangeNameSettingsScreenProps> = ({ errorMessage, initialName, isSaving = false, onBack, onSave }) => {diff --git a/web/apps/space/src/services/space.ts b/web/apps/space/src/services/space.tsindex 8890add7cc..825db8c40c 100644--- a/web/apps/space/src/services/space.ts+++ b/web/apps/space/src/services/space.ts@@ -225,6 +225,12 @@ export interface PublicSpaceLinkSession {loadPosts: () => Promise<SpaceProfilePost[]>;profile: FriendProfile & { avatarUrl: string | null };postsCount: number;+ subscribeWebPush: (+ endpoint: string,+ p256dh: string,+ auth: string,+ ) => Promise<string>;+ unsubscribeWebPush: (endpoint: string) => Promise<void>;}export interface CurrentSpaceLink {@@ -759,6 +765,9 @@ export const openPublicSpaceLink = async ().items,profile: { ...profile, avatarUrl: profile.avatarUrl ?? null },postsCount: response.posts ?? 0,+ subscribeWebPush: (endpoint, p256dh, auth) =>+ ctx.subscribeWebPush(endpoint, p256dh, auth),+ unsubscribeWebPush: (endpoint) => ctx.unsubscribeWebPush(endpoint),};} catch (error) {ctx.free();diff --git a/web/apps/space/src/services/spaceLogout.ts b/web/apps/space/src/services/spaceLogout.tsindex e2ecf3e391..0e1407db54 100644--- a/web/apps/space/src/services/spaceLogout.ts+++ b/web/apps/space/src/services/spaceLogout.ts@@ -4,9 +4,15 @@ import {clearSpaceBrowserSession,revokeSpaceBrowserSessions,} from "services/spacePersistentSession";+import { forgetSpaceWebPushAccountTarget } from "services/spaceWebPush";export const spaceLogout = async () => {await revokeSpaceBrowserSessions();+ try {+ await forgetSpaceWebPushAccountTarget();+ } catch (error) {+ log.warn("Failed to clear Space notification state on logout", error);+ }try {clearSpaceBrowserSession();} catch (error) {diff --git a/web/apps/space/src/services/spacePersistentSession.ts b/web/apps/space/src/services/spacePersistentSession.tsindex dd9b3a6566..6be428cb0e 100644--- a/web/apps/space/src/services/spacePersistentSession.ts+++ b/web/apps/space/src/services/spacePersistentSession.ts@@ -27,7 +27,7 @@ import {import { z } from "zod";const spaceBrowserSessionStorageKey = "spaceBrowserSession";-const spaceSessionTokenHeader = "X-Space-Session-Token";+export const spaceSessionTokenHeader = "X-Space-Session-Token";const OwnedSpace = z.object({spaceId: z.string(),diff --git a/web/apps/space/src/services/spaceWebPush.ts b/web/apps/space/src/services/spaceWebPush.tsnew file mode 100644index 0000000000..db1f4ae763--- /dev/null+++ b/web/apps/space/src/services/spaceWebPush.ts@@ -0,0 +1,516 @@+import { ensureOk, publicRequestHeaders } from "ente-base/http";+import { apiURL } from "ente-base/origins";+import type { PublicSpaceLinkSession } from "services/space";+import {+ savedSpaceSessionToken,+ spaceSessionTokenHeader,+} from "services/spacePersistentSession";+import { z } from "zod";++const SpaceWebPushVAPIDKeyResponse = z.object({ publicKey: z.string() });+const SpaceWebPushTargetResponse = z.object({ targetId: z.string() });++const pushDatabaseName = "ente-space-web-push";+const pushDatabaseVersion = 1;+const pushTargetStoreName = "targets";+const accountTargetKey = "account";+const vapidPublicKeyStorageKey = "ente-space-web-push-vapid-key";+const publicTargetSyncInterval = 24 * 60 * 60 * 1000;++interface StoredPushTarget {+ endpoint: string;+ key: string;+ kind: "account" | "public";+ lastSyncedAt?: number;+ route: string;+ targetId: string;+}++interface PreparedSpaceWebPush {+ publicKey: string;+ registration: ServiceWorkerRegistration;+}++interface SubscriptionDetails {+ auth: string;+ endpoint: string;+ p256dh: string;+}++export type SpaceWebPushState =+ | "denied"+ | "recovery"+ | "subscribed"+ | "unavailable"+ | "unsubscribed";++let pendingPreparation: Promise<PreparedSpaceWebPush | undefined> | undefined;+let pendingDatabase: Promise<IDBDatabase> | undefined;++export const isSpaceWebPushSupported = () =>+ typeof window != "undefined" &&+ "Notification" in window &&+ "serviceWorker" in navigator &&+ "PushManager" in window &&+ "indexedDB" in window;++export const registerSpaceServiceWorker = async () => {+ if (typeof navigator == "undefined" || !("serviceWorker" in navigator)) {+ return undefined;+ }+ await navigator.serviceWorker.register("/sw.js", { scope: "/" });+ return navigator.serviceWorker.ready;+};++const openPushDatabase = () =>+ (pendingDatabase ??= new Promise<IDBDatabase>((resolve, reject) => {+ const request = indexedDB.open(pushDatabaseName, pushDatabaseVersion);+ request.onupgradeneeded = () => {+ const database = request.result;+ if (!database.objectStoreNames.contains(pushTargetStoreName)) {+ const store = database.createObjectStore(pushTargetStoreName, {+ keyPath: "key",+ });+ store.createIndex("targetId", "targetId");+ }+ };+ request.onerror = () =>+ reject(request.error ?? new Error("Failed to open push storage."));+ request.onsuccess = () => {+ request.result.onversionchange = () => request.result.close();+ resolve(request.result);+ };+ }).catch((error: unknown) => {+ pendingDatabase = undefined;+ throw error;+ }));++const targetRequest = async <T>(+ mode: IDBTransactionMode,+ action: (store: IDBObjectStore) => IDBRequest<T>,+) => {+ const database = await openPushDatabase();+ return new Promise<T>((resolve, reject) => {+ const transaction = database.transaction(pushTargetStoreName, mode);+ const request = action(transaction.objectStore(pushTargetStoreName));+ request.onerror = () =>+ reject(request.error ?? new Error("Push storage request failed."));+ request.onsuccess = () => resolve(request.result);+ transaction.onerror = () =>+ reject(+ transaction.error ??+ new Error("Push storage transaction failed."),+ );+ });+};++const getTarget = (key: string) =>+ targetRequest<StoredPushTarget | undefined>(+ "readonly",+ (store) => store.get(key) as IDBRequest<StoredPushTarget | undefined>,+ );++const putTarget = (target: StoredPushTarget) =>+ targetRequest<IDBValidKey>("readwrite", (store) => store.put(target));++const deleteTarget = (key: string) =>+ targetRequest<undefined>("readwrite", (store) => store.delete(key));++const listTargets = () =>+ targetRequest<StoredPushTarget[]>(+ "readonly",+ (store) => store.getAll() as IDBRequest<StoredPushTarget[]>,+ );++const invalidateTargetDeliveries = async () => {+ const targets = await listTargets();+ await Promise.all(+ targets.map((target) =>+ putTarget({ ...target, endpoint: "", targetId: "" }),+ ),+ );+};++const publicTargetKey = (route: string) => `public:${route}`;++const cachedVAPIDPublicKey = () => {+ try {+ return localStorage.getItem(vapidPublicKeyStorageKey)?.trim();+ } catch {+ return undefined;+ }+};++const cacheVAPIDPublicKey = (publicKey: string) => {+ try {+ localStorage.setItem(vapidPublicKeyStorageKey, publicKey);+ } catch {+ // Push still works when persistent browser storage is unavailable.+ }+};++const spaceSessionHeaders = () => {+ const sessionToken = savedSpaceSessionToken();+ if (!sessionToken) throw new Error("Space session is missing.");+ return {+ ...publicRequestHeaders(),+ [spaceSessionTokenHeader]: sessionToken,+ };+};++const prepareSpaceWebPush = async () => {+ if (!isSpaceWebPushSupported()) return undefined;+ try {+ await openPushDatabase();+ } catch {+ return undefined;+ }+ const registration = await registerSpaceServiceWorker();+ if (!registration) return undefined;+ const cachedPublicKey = cachedVAPIDPublicKey();+ if (cachedPublicKey) {+ return { publicKey: cachedPublicKey, registration };+ }+ const response = await fetch(await apiURL("/space/push/vapid-key"), {+ headers: publicRequestHeaders(),+ });+ if (response.status == 503) return undefined;+ ensureOk(response);+ const { publicKey } = SpaceWebPushVAPIDKeyResponse.parse(+ await response.json(),+ );+ if (!publicKey.trim()) return undefined;+ cacheVAPIDPublicKey(publicKey);+ return { publicKey, registration };+};++const preparedSpaceWebPush = async () => {+ const preparation = (pendingPreparation ??= prepareSpaceWebPush());+ try {+ return await preparation;+ } finally {+ if (pendingPreparation == preparation) pendingPreparation = undefined;+ }+};++const subscriptionDetails = (+ subscription: PushSubscription,+): SubscriptionDetails => {+ const serialized = subscription.toJSON();+ const p256dh = serialized.keys?.p256dh;+ const auth = serialized.keys?.auth;+ if (!serialized.endpoint || !p256dh || !auth) {+ throw new Error("Web push subscription is incomplete.");+ }+ return { endpoint: serialized.endpoint, p256dh, auth };+};++const sameBytes = (left: ArrayBuffer | null, right: ArrayBuffer) => {+ if (left?.byteLength != right.byteLength) return false;+ const leftBytes = new Uint8Array(left);+ const rightBytes = new Uint8Array(right);+ return leftBytes.every((value, index) => value == rightBytes[index]);+};++const currentSubscription = async (prepared: PreparedSpaceWebPush) => {+ const subscription =+ await prepared.registration.pushManager.getSubscription();+ if (+ !subscription ||+ sameBytes(+ subscription.options.applicationServerKey,+ base64URLKey(prepared.publicKey),+ )+ ) {+ return subscription;+ }+ if (!(await subscription.unsubscribe())) {+ throw new Error("Failed to replace the old web push subscription.");+ }+ await invalidateTargetDeliveries();+ return null;+};++const ensureSubscription = async (prepared: PreparedSpaceWebPush) => {+ const existing = await currentSubscription(prepared);+ if (existing) return existing;+ return prepared.registration.pushManager.subscribe({+ applicationServerKey: base64URLKey(prepared.publicKey),+ userVisibleOnly: true,+ });+};++const uploadAccountTarget = async (subscription: PushSubscription) => {+ const details = subscriptionDetails(subscription);+ const response = await fetch(+ await apiURL("/account/space/push/subscription"),+ {+ method: "PUT",+ headers: {+ ...spaceSessionHeaders(),+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ endpoint: details.endpoint,+ keys: { auth: details.auth, p256dh: details.p256dh },+ }),+ },+ );+ ensureOk(response);+ const { targetId } = SpaceWebPushTargetResponse.parse(+ await response.json(),+ );+ await putTarget({+ endpoint: details.endpoint,+ key: accountTargetKey,+ kind: "account",+ route: "/app",+ targetId,+ });+};++export const reconcileSpaceWebPush = async (): Promise<SpaceWebPushState> => {+ if (!isSpaceWebPushSupported()) return "unavailable";+ let target: StoredPushTarget | undefined;+ try {+ target = await getTarget(accountTargetKey);+ } catch {+ return "unavailable";+ }+ if (Notification.permission == "denied") return "denied";+ const prepared = await preparedSpaceWebPush();+ if (!prepared) return "unavailable";+ const subscription = await currentSubscription(prepared);+ if (!target) {+ if (subscription) {+ if ((await listTargets()).length == 0) {+ if (!(await subscription.unsubscribe())) {+ throw new Error(+ "Failed to clear an untracked web push subscription.",+ );+ }+ }+ await deleteAccountTarget(subscription.endpoint);+ }+ return "unsubscribed";+ }+ if (!subscription) return "recovery";+ await uploadAccountTarget(subscription);+ return "subscribed";+};++export const subscribeToSpaceWebPush = async () => {+ if (!isSpaceWebPushSupported()) {+ throw new Error("Web push is unavailable.");+ }+ const permission =+ Notification.permission == "granted"+ ? "granted"+ : await Notification.requestPermission();+ if (permission != "granted") return permission;+ const prepared = await preparedSpaceWebPush();+ if (!prepared) throw new Error("Web push is unavailable.");+ const subscription = await ensureSubscription(prepared);+ const details = subscriptionDetails(subscription);+ await putTarget({+ endpoint: details.endpoint,+ key: accountTargetKey,+ kind: "account",+ route: "/app",+ targetId: "",+ });+ await uploadAccountTarget(subscription);+ return permission;+};++const deleteAccountTarget = async (endpoint: string) => {+ const response = await fetch(+ await apiURL("/account/space/push/subscription"),+ {+ method: "DELETE",+ headers: {+ ...spaceSessionHeaders(),+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ endpoint }),+ },+ );+ ensureOk(response);+};++const removingLastTarget = async (targetKey: string) => {+ const targets = await listTargets();+ return targets.every((target) => target.key == targetKey);+};++export const unsubscribeFromSpaceWebPush = async () => {+ const prepared = await preparedSpaceWebPush();+ if (!prepared) throw new Error("Web push is unavailable.");+ const target = await getTarget(accountTargetKey);+ if (!target) return;+ const subscription =+ await prepared.registration.pushManager.getSubscription();+ const endpoint = subscription?.endpoint || target.endpoint;+ if (!endpoint) {+ await deleteTarget(accountTargetKey);+ return;+ }+ if (subscription && (await removingLastTarget(accountTargetKey))) {+ if (!(await subscription.unsubscribe())) {+ throw new Error("Failed to unsubscribe from web push.");+ }+ await deleteTarget(accountTargetKey);+ await deleteAccountTarget(endpoint);+ return;+ }+ await deleteAccountTarget(endpoint);+ await deleteTarget(accountTargetKey);+};++export const forgetSpaceWebPushAccountTarget = async () => {+ const target = await getTarget(accountTargetKey);+ if (!target) return;+ await deleteTarget(accountTargetKey);+ if (!isSpaceWebPushSupported() || (await listTargets()).length > 0) return;+ const registration = await navigator.serviceWorker.ready;+ const subscription = await registration.pushManager.getSubscription();+ if (subscription) await subscription.unsubscribe();+};++export const reconcilePublicSpaceWebPush = async (+ session: PublicSpaceLinkSession,+ route: string,+): Promise<SpaceWebPushState> => {+ if (!isSpaceWebPushSupported()) return "unavailable";+ const key = publicTargetKey(route);+ let target: StoredPushTarget | undefined;+ try {+ target = await getTarget(key);+ } catch {+ return "unavailable";+ }+ if (Notification.permission == "denied") return "denied";+ const prepared = await preparedSpaceWebPush();+ if (!prepared) return "unavailable";+ const subscription = await currentSubscription(prepared);+ if (!target) {+ if (subscription) {+ if ((await listTargets()).length == 0) {+ if (!(await subscription.unsubscribe())) {+ throw new Error(+ "Failed to clear an untracked web push subscription.",+ );+ }+ }+ await session.unsubscribeWebPush(subscription.endpoint);+ }+ return "unsubscribed";+ }+ if (!subscription) return "recovery";+ const details = subscriptionDetails(subscription);+ if (+ target.endpoint == details.endpoint &&+ target.targetId &&+ (target.lastSyncedAt ?? 0) > Date.now() - publicTargetSyncInterval+ ) {+ return "subscribed";+ }+ const targetId = await session.subscribeWebPush(+ details.endpoint,+ details.p256dh,+ details.auth,+ );+ await putTarget({+ endpoint: details.endpoint,+ key,+ kind: "public",+ lastSyncedAt: Date.now(),+ route,+ targetId,+ });+ return "subscribed";+};++export const subscribeToPublicSpaceWebPush = async (+ session: PublicSpaceLinkSession,+ route: string,+) => {+ if (!isSpaceWebPushSupported()) {+ throw new Error("Web push is unavailable.");+ }+ const permission =+ Notification.permission == "granted"+ ? "granted"+ : await Notification.requestPermission();+ if (permission != "granted") return permission;+ const prepared = await preparedSpaceWebPush();+ if (!prepared) throw new Error("Web push is unavailable.");+ const key = publicTargetKey(route);+ const previousTarget = await getTarget(key);+ const subscription = await ensureSubscription(prepared);+ const details = subscriptionDetails(subscription);+ if (+ previousTarget?.endpoint &&+ previousTarget.endpoint != details.endpoint+ ) {+ await session.unsubscribeWebPush(previousTarget.endpoint);+ }+ await putTarget({+ endpoint: details.endpoint,+ key,+ kind: "public",+ route,+ targetId: "",+ });+ const targetId = await session.subscribeWebPush(+ details.endpoint,+ details.p256dh,+ details.auth,+ );+ await putTarget({+ endpoint: details.endpoint,+ key,+ kind: "public",+ lastSyncedAt: Date.now(),+ route,+ targetId,+ });+ return permission;+};++export const unsubscribeFromPublicSpaceWebPush = async (+ session: PublicSpaceLinkSession,+ route: string,+) => {+ const prepared = await preparedSpaceWebPush();+ if (!prepared) throw new Error("Web push is unavailable.");+ const key = publicTargetKey(route);+ const target = await getTarget(key);+ if (!target) return;+ const subscription =+ await prepared.registration.pushManager.getSubscription();+ const endpoint = subscription?.endpoint || target.endpoint;+ if (!endpoint) {+ await deleteTarget(key);+ return;+ }+ if (subscription && (await removingLastTarget(key))) {+ if (!(await subscription.unsubscribe())) {+ throw new Error("Failed to unsubscribe from web push.");+ }+ await deleteTarget(key);+ await session.unsubscribeWebPush(endpoint);+ return;+ }+ await session.unsubscribeWebPush(endpoint);+ await deleteTarget(key);+};++const base64URLKey = (value: string): ArrayBuffer => {+ const padding = "=".repeat((4 - (value.length % 4)) % 4);+ const bytes = Uint8Array.from(+ atob((value + padding).replaceAll("-", "+").replaceAll("_", "/")),+ (character) => character.charCodeAt(0),+ );+ return bytes.buffer;+};diff --git a/web/apps/space/src/utils/spaceRouteTransitions.tsx b/web/apps/space/src/utils/spaceRouteTransitions.tsxindex 494fd27976..8d388ab373 100644--- a/web/apps/space/src/utils/spaceRouteTransitions.tsx+++ b/web/apps/space/src/utils/spaceRouteTransitions.tsx@@ -43,8 +43,7 @@ const parentRoutePaths = (path: string) => {"/app/profile/photo": ["/app/profile"],"/app/profile/photo-edit": ["/app/profile/photo"],"/app/settings": ["/app/profile"],- "/app/settings/profile": ["/app/settings"],- "/app/settings/profile/name": ["/app/settings/profile"],+ "/app/settings/profile/name": ["/app/settings"],"/login": ["/"],"/passkeys/finish": ["/passkeys/verify"],"/passkeys/verify": ["/login", "/verify"],diff --git a/web/apps/space/src/utils/spaceRoutes.ts b/web/apps/space/src/utils/spaceRoutes.tsindex a42afcab13..0fbe90c90b 100644--- a/web/apps/space/src/utils/spaceRoutes.ts+++ b/web/apps/space/src/utils/spaceRoutes.ts@@ -38,7 +38,6 @@ export const spaceRoutes = {profilePhotoFrom: (source?: ProfileImageFlowSource) =>routeWithProfileImageFlowSource("/app/profile/photo", source),settings: "/app/settings",- settingsProfile: "/app/settings/profile",settingsProfileName: "/app/settings/profile/name",createProfile: (from?: CreateProfileSource) =>from == "login" ? "/create-profile?from=login" : "/create-profile",