Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Add browser tokens for public link device limits

Neeraj Gupta14ba926426bc
diff --git a/server/cmd/museum/main.go b/server/cmd/museum/main.go
index e8c6ac328d..5734d642b8 100644
--- a/server/cmd/museum/main.go
+++ b/server/cmd/museum/main.go
@@ -1298,8 +1298,8 @@ func cors() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", c.GetHeader("Origin"))
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
- c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, X-Auth-Token, X-Auth-Access-Token, X-Cast-Access-Token, X-Auth-Access-Token-JWT, X-Client-Package, X-Client-Version, X-Paste-Consume, Authorization, accept, origin, Cache-Control, X-Requested-With, upgrade-insecure-requests, Range")
- c.Writer.Header().Set("Access-Control-Expose-Headers", "X-Request-Id")
+ c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, X-Auth-Token, X-Auth-Access-Token, X-Cast-Access-Token, X-Auth-Access-Token-JWT, X-Auth-Link-Device-Token, X-Client-Package, X-Client-Version, X-Paste-Consume, Authorization, accept, origin, Cache-Control, X-Requested-With, upgrade-insecure-requests, Range")
+ c.Writer.Header().Set("Access-Control-Expose-Headers", "X-Request-Id, X-Ente-Link-Device-Token")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, PATCH, DELETE")
c.Writer.Header().Set("Access-Control-Max-Age", "1728000")
diff --git a/server/pkg/api/file_link.go b/server/pkg/api/file_link.go
index 44bb3372aa..cce5689751 100644
--- a/server/pkg/api/file_link.go
+++ b/server/pkg/api/file_link.go
@@ -38,6 +38,11 @@ func (h *FileHandler) LinkInfo(c *gin.Context) {
if linkMeta != nil {
response["link"] = linkMeta
}
+ if linkDeviceToken, ok := c.Get(auth.LinkDeviceTokenResponseKey); ok {
+ if token, ok := linkDeviceToken.(string); ok && token != "" {
+ c.Header(auth.LinkDeviceTokenResponseHeader, token)
+ }
+ }
c.JSON(http.StatusOK, response)
}
diff --git a/server/pkg/api/public_collection.go b/server/pkg/api/public_collection.go
index 39edf6165e..1d046424a5 100644
--- a/server/pkg/api/public_collection.go
+++ b/server/pkg/api/public_collection.go
@@ -110,10 +110,16 @@ func (h *PublicCollectionHandler) GetCollection(c *gin.Context) {
return
}
referralCode, _ := h.StorageBonusController.GetOrCreateReferralCode(c, collection.Owner.ID)
- c.JSON(http.StatusOK, gin.H{
+ response := gin.H{
"collection": collection,
"referralCode": referralCode,
- })
+ }
+ if linkDeviceToken, ok := c.Get(auth.LinkDeviceTokenResponseKey); ok {
+ if token, ok := linkDeviceToken.(string); ok && token != "" {
+ c.Header(auth.LinkDeviceTokenResponseHeader, token)
+ }
+ }
+ c.JSON(http.StatusOK, response)
}
// GetUploadUrls returns upload Urls where files can be uploaded
diff --git a/server/pkg/controller/public/link_device_token.go b/server/pkg/controller/public/link_device_token.go
new file mode 100644
index 0000000000..2f4473701d
--- /dev/null
+++ b/server/pkg/controller/public/link_device_token.go
@@ -0,0 +1,100 @@
+package public
+
+import (
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/base64"
+ "errors"
+ "fmt"
+
+ "github.com/ente-io/museum/pkg/utils/time"
+ "github.com/ente-io/stacktrace"
+ "github.com/golang-jwt/jwt/v4"
+)
+
+const (
+ LinkDeviceScopeCollection = "collection"
+ LinkDeviceScopeFile = "file"
+
+ linkDeviceTokenType = "link-device"
+ linkDeviceTokenIssuer = "museum"
+ linkDeviceTokenAudience = "public-link-device"
+ linkDeviceTokenTTL = 365
+ LinkDeviceTokenRefreshBefore = 30 * 24 * time.MicroSecondsInOneHour
+)
+
+// LinkDeviceClaim represents a signed browser admission token for public links.
+type LinkDeviceClaim struct {
+ Typ string `json:"typ"`
+ Scope string `json:"scope"`
+ LinkID string `json:"linkID"`
+ AccessTokenHMAC string `json:"ath"`
+ IssuedAt int64 `json:"iat"`
+ ExpiryTime int64 `json:"exp"`
+ Issuer string `json:"iss"`
+ Audience string `json:"aud"`
+}
+
+func (c LinkDeviceClaim) Valid() error {
+ if c.ExpiryTime < time.Microseconds() {
+ return errors.New("token expired")
+ }
+ return nil
+}
+
+func NewLinkDeviceToken(secret []byte, scope string, linkID string, accessToken string, validTill int64) (string, int64, error) {
+ now := time.Microseconds()
+ expiry := time.NDaysFromNow(linkDeviceTokenTTL)
+ if validTill > 0 && validTill < expiry {
+ expiry = validTill
+ }
+
+ token := jwt.NewWithClaims(jwt.SigningMethodHS256, &LinkDeviceClaim{
+ Typ: linkDeviceTokenType,
+ Scope: scope,
+ LinkID: linkID,
+ AccessTokenHMAC: linkDeviceAccessTokenHMAC(secret, accessToken),
+ IssuedAt: now,
+ ExpiryTime: expiry,
+ Issuer: linkDeviceTokenIssuer,
+ Audience: linkDeviceTokenAudience,
+ })
+ tokenString, err := token.SignedString(secret)
+ return tokenString, expiry, stacktrace.Propagate(err, "failed to sign link device token")
+}
+
+func ValidateLinkDeviceToken(secret []byte, tokenString string, scope string, linkID string, accessToken string) (*LinkDeviceClaim, error) {
+ token, err := jwt.ParseWithClaims(tokenString, &LinkDeviceClaim{}, func(token *jwt.Token) (interface{}, error) {
+ if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
+ return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
+ }
+ return secret, nil
+ })
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "link device token parse failed")
+ }
+ claim, ok := token.Claims.(*LinkDeviceClaim)
+ if !ok || !token.Valid {
+ return nil, stacktrace.NewError("invalid link device token")
+ }
+ if claim.Typ != linkDeviceTokenType ||
+ claim.Scope != scope ||
+ claim.LinkID != linkID ||
+ claim.Issuer != linkDeviceTokenIssuer ||
+ claim.Audience != linkDeviceTokenAudience {
+ return nil, stacktrace.NewError("link device token claim mismatch")
+ }
+ expectedAccessTokenHMAC := linkDeviceAccessTokenHMAC(secret, accessToken)
+ if !hmac.Equal([]byte(claim.AccessTokenHMAC), []byte(expectedAccessTokenHMAC)) {
+ return nil, stacktrace.NewError("link device token access token mismatch")
+ }
+ return claim, nil
+}
+
+func linkDeviceAccessTokenHMAC(secret []byte, accessToken string) string {
+ mac := hmac.New(sha256.New, secret)
+ mac.Write([]byte("ente:public-link-device-token:access-token:v1"))
+ mac.Write([]byte{0})
+ mac.Write([]byte(accessToken))
+ return base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
+}
diff --git a/server/pkg/controller/public/link_device_token_test.go b/server/pkg/controller/public/link_device_token_test.go
new file mode 100644
index 0000000000..1fbe8e0cfb
--- /dev/null
+++ b/server/pkg/controller/public/link_device_token_test.go
@@ -0,0 +1,50 @@
+package public
+
+import (
+ "testing"
+
+ "github.com/ente-io/museum/pkg/utils/time"
+ "github.com/stretchr/testify/require"
+)
+
+func TestLinkDeviceTokenValidation(t *testing.T) {
+ secret := []byte("test-secret")
+ token, _, err := NewLinkDeviceToken(secret, LinkDeviceScopeCollection, "123", "ACCESS", 0)
+ require.NoError(t, err)
+
+ claim, err := ValidateLinkDeviceToken(secret, token, LinkDeviceScopeCollection, "123", "ACCESS")
+ require.NoError(t, err)
+ require.Equal(t, LinkDeviceScopeCollection, claim.Scope)
+ require.Equal(t, "123", claim.LinkID)
+
+ _, err = ValidateLinkDeviceToken(secret, token, LinkDeviceScopeFile, "123", "ACCESS")
+ require.Error(t, err)
+
+ _, err = ValidateLinkDeviceToken(secret, token, LinkDeviceScopeCollection, "456", "ACCESS")
+ require.Error(t, err)
+
+ _, err = ValidateLinkDeviceToken(secret, token, LinkDeviceScopeCollection, "123", "OTHER")
+ require.Error(t, err)
+}
+
+func TestLinkDeviceTokenExpiryIsCappedByLinkExpiry(t *testing.T) {
+ secret := []byte("test-secret")
+ validTill := time.MicrosecondsAfterHours(1)
+
+ token, expiry, err := NewLinkDeviceToken(secret, LinkDeviceScopeCollection, "123", "ACCESS", validTill)
+ require.NoError(t, err)
+ require.Equal(t, validTill, expiry)
+
+ claim, err := ValidateLinkDeviceToken(secret, token, LinkDeviceScopeCollection, "123", "ACCESS")
+ require.NoError(t, err)
+ require.Equal(t, validTill, claim.ExpiryTime)
+}
+
+func TestExpiredLinkDeviceTokenIsRejected(t *testing.T) {
+ secret := []byte("test-secret")
+ token, _, err := NewLinkDeviceToken(secret, LinkDeviceScopeCollection, "123", "ACCESS", time.MicrosecondsBeforeDays(1))
+ require.NoError(t, err)
+
+ _, err = ValidateLinkDeviceToken(secret, token, LinkDeviceScopeCollection, "123", "ACCESS")
+ require.Error(t, err)
+}
diff --git a/server/pkg/middleware/collection_link.go b/server/pkg/middleware/collection_link.go
index 7f9da0dcbb..57bbcc32b8 100644
--- a/server/pkg/middleware/collection_link.go
+++ b/server/pkg/middleware/collection_link.go
@@ -9,6 +9,7 @@ import (
"fmt"
"net/http"
"net/url"
+ "strconv"
"strings"
"golang.org/x/net/idna"
@@ -64,9 +65,16 @@ func (m *CollectionLinkMiddleware) Authenticate(urlSanitizer func(_ *gin.Context
userAgent := c.GetHeader("User-Agent")
var publicCollectionSummary ente.PublicCollectionSummary
var err error
+ reqPath := urlSanitizer(c)
+ shouldCheckDeviceLimit := shouldCheckCollectionLinkDeviceLimit(reqPath)
+ passwordValidated := false
cacheKey := computeHashKeyForList([]string{accessToken, clientIP, userAgent}, ":")
- cachedValue, cacheHit := m.Cache.Get(cacheKey)
+ var cachedValue interface{}
+ cacheHit := false
+ if !shouldCheckDeviceLimit {
+ cachedValue, cacheHit = m.Cache.Get(cacheKey)
+ }
if !cacheHit {
publicCollectionSummary, err = m.CollectionLinkRepo.GetCollectionSummaryByToken(c, accessToken)
if err != nil {
@@ -89,16 +97,35 @@ func (m *CollectionLinkMiddleware) Authenticate(urlSanitizer func(_ *gin.Context
publicCollectionSummary.DeviceLimit = public2.FreeUserDeviceLimit
}
- // validate device limit
- reached, err := m.isDeviceLimitReached(c, publicCollectionSummary, clientIP, userAgent)
- if err != nil {
- logrus.WithError(err).Error("failed to check device limit")
- c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "something went wrong"})
+ if publicCollectionSummary.ValidTill > 0 && // expiry time is defined, 0 indicates no expiry
+ publicCollectionSummary.ValidTill < time.Microseconds() {
+ c.AbortWithStatusJSON(http.StatusGone, gin.H{"error": "expired token"})
return
}
- if reached {
- c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{"error": "reached device limit"})
- return
+
+ if publicCollectionSummary.PassHash != nil && *publicCollectionSummary.PassHash != "" {
+ if err = m.validatePassword(c, reqPath, publicCollectionSummary); err != nil {
+ logrus.WithError(err).Warn("password validation failed")
+ c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": err})
+ return
+ }
+ passwordValidated = true
+ }
+
+ if shouldCheckDeviceLimit {
+ linkDeviceToken, reached, limitErr := m.checkDeviceLimit(c, accessToken, publicCollectionSummary, clientIP, userAgent)
+ if limitErr != nil {
+ logrus.WithError(limitErr).Error("failed to check device limit")
+ c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "something went wrong"})
+ return
+ }
+ if reached {
+ c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{"error": "reached device limit"})
+ return
+ }
+ if linkDeviceToken != "" {
+ c.Set(auth.LinkDeviceTokenResponseKey, linkDeviceToken)
+ }
}
} else {
publicCollectionSummary = cachedValue.(ente.PublicCollectionSummary)
@@ -111,8 +138,7 @@ func (m *CollectionLinkMiddleware) Authenticate(urlSanitizer func(_ *gin.Context
}
// checks password protected public collection
- if publicCollectionSummary.PassHash != nil && *publicCollectionSummary.PassHash != "" {
- reqPath := urlSanitizer(c)
+ if !passwordValidated && publicCollectionSummary.PassHash != nil && *publicCollectionSummary.PassHash != "" {
if err = m.validatePassword(c, reqPath, publicCollectionSummary); err != nil {
logrus.WithError(err).Warn("password validation failed")
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": err})
@@ -120,7 +146,7 @@ func (m *CollectionLinkMiddleware) Authenticate(urlSanitizer func(_ *gin.Context
}
}
- if !cacheHit {
+ if !cacheHit && !shouldCheckDeviceLimit {
m.Cache.Set(cacheKey, publicCollectionSummary, cache.DefaultExpiration)
}
@@ -151,6 +177,33 @@ func (m *CollectionLinkMiddleware) Authenticate(urlSanitizer func(_ *gin.Context
}
}
+func (m *CollectionLinkMiddleware) checkDeviceLimit(c *gin.Context, accessToken string,
+ collectionSummary ente.PublicCollectionSummary, ip string, ua string) (string, bool, error) {
+ linkID := strconv.FormatInt(collectionSummary.ID, 10)
+ linkDeviceToken := auth.GetLinkDeviceToken(c)
+ if linkDeviceToken != "" {
+ claim, err := public2.ValidateLinkDeviceToken(m.PublicCollectionCtrl.JwtSecret, linkDeviceToken, public2.LinkDeviceScopeCollection, linkID, accessToken)
+ if err == nil {
+ if claim.ExpiryTime-time.Microseconds() < public2.LinkDeviceTokenRefreshBefore {
+ token, _, tokenErr := public2.NewLinkDeviceToken(m.PublicCollectionCtrl.JwtSecret, public2.LinkDeviceScopeCollection, linkID, accessToken, collectionSummary.ValidTill)
+ return token, false, stacktrace.Propagate(tokenErr, "")
+ }
+ return "", false, nil
+ }
+ }
+ reached, err := m.isDeviceLimitReached(c, collectionSummary, ip, ua)
+ if err != nil || reached {
+ return "", reached, stacktrace.Propagate(err, "")
+ }
+ token, _, err := public2.NewLinkDeviceToken(m.PublicCollectionCtrl.JwtSecret, public2.LinkDeviceScopeCollection, linkID, accessToken, collectionSummary.ValidTill)
+ return token, false, stacktrace.Propagate(err, "")
+}
+
+func shouldCheckCollectionLinkDeviceLimit(reqPath string) bool {
+ return reqPath == "/public-collection/info" ||
+ reqPath == "/public-collection/diff"
+}
+
// validateOwnersSubscription checks if the owner has an active subscription.
// Returns (isFreeUser, error) where isFreeUser is true if user is on free plan but has active subscription.
func (m *CollectionLinkMiddleware) validateOwnersSubscription(c *gin.Context, cID int64) (bool, error) {
@@ -217,6 +270,9 @@ func (m *CollectionLinkMiddleware) isDeviceLimitReached(ctx context.Context,
// validatePassword will verify if the user is provided correct password for the public album
func (m *CollectionLinkMiddleware) validatePassword(c *gin.Context, reqPath string,
collectionSummary ente.PublicCollectionSummary) error {
+ // /public-collection/info is allowed before password unlock so clients can
+ // fetch the KDF parameters needed to verify the password. Device-limit
+ // admission is intentionally still applied to this public entrypoint.
if array.StringInList(reqPath, passwordWhiteListedURLs) {
return nil
}
diff --git a/server/pkg/middleware/collection_link_test.go b/server/pkg/middleware/collection_link_test.go
new file mode 100644
index 0000000000..0322198891
--- /dev/null
+++ b/server/pkg/middleware/collection_link_test.go
@@ -0,0 +1,16 @@
+package middleware
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestShouldCheckCollectionLinkDeviceLimit(t *testing.T) {
+ require.True(t, shouldCheckCollectionLinkDeviceLimit("/public-collection/info"))
+ require.True(t, shouldCheckCollectionLinkDeviceLimit("/public-collection/diff"))
+
+ require.False(t, shouldCheckCollectionLinkDeviceLimit("/public-collection/files/download/1"))
+ require.False(t, shouldCheckCollectionLinkDeviceLimit("/public-collection/upload-urls"))
+ require.False(t, shouldCheckCollectionLinkDeviceLimit("/public-collection/verify-password"))
+}
diff --git a/server/pkg/middleware/file_link.go b/server/pkg/middleware/file_link.go
index 540bdd4f7d..ee67444d34 100644
--- a/server/pkg/middleware/file_link.go
+++ b/server/pkg/middleware/file_link.go
@@ -44,9 +44,16 @@ func (m *FileLinkMiddleware) Authenticate(urlSanitizer func(_ *gin.Context) stri
}
clientIP := network.GetClientIP(c)
userAgent := c.GetHeader("User-Agent")
+ reqPath := urlSanitizer(c)
+ shouldCheckDeviceLimit := reqPath == "/file-link/info"
+ passwordValidated := false
cacheKey := computeHashKeyForList([]string{accessToken, clientIP, userAgent}, ":")
- cachedValue, cacheHit := m.Cache.Get(cacheKey)
+ var cachedValue interface{}
+ cacheHit := false
+ if !shouldCheckDeviceLimit {
+ cachedValue, cacheHit = m.Cache.Get(cacheKey)
+ }
var fileLinkRow *ente.FileLinkRow
var err error
if !cacheHit {
@@ -60,16 +67,33 @@ func (m *FileLinkMiddleware) Authenticate(urlSanitizer func(_ *gin.Context) stri
c.AbortWithStatusJSON(http.StatusGone, gin.H{"error": "disabled token"})
return
}
- // validate device limit
- reached, limitErr := m.isDeviceLimitReached(c, fileLinkRow, clientIP, userAgent)
- if limitErr != nil {
- logrus.WithError(limitErr).Error("failed to check device limit")
- c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "something went wrong"})
+ if fileLinkRow.ValidTill > 0 && // expiry time is defined, 0 indicates no expiry
+ fileLinkRow.ValidTill < time.Microseconds() {
+ c.AbortWithStatusJSON(http.StatusGone, gin.H{"error": "expired token"})
return
}
- if reached {
- c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{"error": "reached device limit"})
- return
+ if fileLinkRow.PassHash != nil && *fileLinkRow.PassHash != "" {
+ if err = m.validatePassword(c, reqPath, fileLinkRow); err != nil {
+ logrus.WithError(err).Warn("password validation failed")
+ c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": err})
+ return
+ }
+ passwordValidated = true
+ }
+ if shouldCheckDeviceLimit {
+ linkDeviceToken, reached, limitErr := m.checkDeviceLimit(c, accessToken, fileLinkRow, clientIP, userAgent)
+ if limitErr != nil {
+ logrus.WithError(limitErr).Error("failed to check device limit")
+ c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "something went wrong"})
+ return
+ }
+ if reached {
+ c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{"error": "reached device limit"})
+ return
+ }
+ if linkDeviceToken != "" {
+ c.Set(auth.LinkDeviceTokenResponseKey, linkDeviceToken)
+ }
}
} else {
fileLinkRow = cachedValue.(*ente.FileLinkRow)
@@ -82,8 +106,7 @@ func (m *FileLinkMiddleware) Authenticate(urlSanitizer func(_ *gin.Context) stri
}
// checks password protected public collection
- if fileLinkRow.PassHash != nil && *fileLinkRow.PassHash != "" {
- reqPath := urlSanitizer(c)
+ if !passwordValidated && fileLinkRow.PassHash != nil && *fileLinkRow.PassHash != "" {
if err = m.validatePassword(c, reqPath, fileLinkRow); err != nil {
logrus.WithError(err).Warn("password validation failed")
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": err})
@@ -91,7 +114,7 @@ func (m *FileLinkMiddleware) Authenticate(urlSanitizer func(_ *gin.Context) stri
}
}
- if !cacheHit {
+ if !cacheHit && !shouldCheckDeviceLimit {
m.Cache.Set(cacheKey, fileLinkRow, cache.DefaultExpiration)
}
@@ -106,6 +129,27 @@ func (m *FileLinkMiddleware) Authenticate(urlSanitizer func(_ *gin.Context) stri
}
}
+func (m *FileLinkMiddleware) checkDeviceLimit(c *gin.Context, accessToken string,
+ fileLinkRow *ente.FileLinkRow, ip string, ua string) (string, bool, error) {
+ linkDeviceToken := auth.GetLinkDeviceToken(c)
+ if linkDeviceToken != "" {
+ claim, err := publicCtrl.ValidateLinkDeviceToken(m.FileLinkCtrl.JwtSecret, linkDeviceToken, publicCtrl.LinkDeviceScopeFile, fileLinkRow.LinkID, accessToken)
+ if err == nil {
+ if claim.ExpiryTime-time.Microseconds() < publicCtrl.LinkDeviceTokenRefreshBefore {
+ token, _, tokenErr := publicCtrl.NewLinkDeviceToken(m.FileLinkCtrl.JwtSecret, publicCtrl.LinkDeviceScopeFile, fileLinkRow.LinkID, accessToken, fileLinkRow.ValidTill)
+ return token, false, stacktrace.Propagate(tokenErr, "")
+ }
+ return "", false, nil
+ }
+ }
+ reached, err := m.isDeviceLimitReached(c, fileLinkRow, ip, ua)
+ if err != nil || reached {
+ return "", reached, stacktrace.Propagate(err, "")
+ }
+ token, _, err := publicCtrl.NewLinkDeviceToken(m.FileLinkCtrl.JwtSecret, publicCtrl.LinkDeviceScopeFile, fileLinkRow.LinkID, accessToken, fileLinkRow.ValidTill)
+ return token, false, stacktrace.Propagate(err, "")
+}
+
func (m *FileLinkMiddleware) isDeviceLimitReached(ctx context.Context,
collectionSummary *ente.FileLinkRow, ip string, ua string) (bool, error) {
// skip deviceLimit check & record keeping for requests via CF worker
diff --git a/server/pkg/utils/auth/auth.go b/server/pkg/utils/auth/auth.go
index d4987f5fdf..d890233011 100644
--- a/server/pkg/utils/auth/auth.go
+++ b/server/pkg/utils/auth/auth.go
@@ -23,6 +23,10 @@ const (
FileLinkAccessKey = "X-Public-FileLink-Access-ID"
CastContext = "X-Cast-Context"
MemoryShareAccessKey = "X-Memory-Share-Access-ID"
+
+ LinkDeviceTokenHeader = "X-Auth-Link-Device-Token"
+ LinkDeviceTokenResponseHeader = "X-Ente-Link-Device-Token"
+ LinkDeviceTokenResponseKey = "linkDeviceToken"
)
// GenerateRandomBytes returns securely generated random bytes.
@@ -134,6 +138,10 @@ func GetAccessTokenJWT(c *gin.Context) string {
return token
}
+func GetLinkDeviceToken(c *gin.Context) string {
+ return c.GetHeader(LinkDeviceTokenHeader)
+}
+
func MustGetPublicAccessContext(c *gin.Context) ente.PublicAccessContext {
return c.MustGet(PublicAccessKey).(ente.PublicAccessContext)
}
diff --git a/web/apps/albums/src/public-album/data/api/public-collection.ts b/web/apps/albums/src/public-album/data/api/public-collection.ts
index c544d22896..e91e4e6ce0 100644
--- a/web/apps/albums/src/public-album/data/api/public-collection.ts
+++ b/web/apps/albums/src/public-album/data/api/public-collection.ts
@@ -1,7 +1,10 @@
import { deriveKey } from "ente-base/crypto";
import {
+ authenticatedPublicAlbumsDeviceLimitRequestHeaders,
+ authenticatedPublicAlbumsInfoRequestHeaders,
authenticatedPublicAlbumsRequestHeaders,
ensureOk,
+ linkDeviceTokenFromResponse,
type PublicAlbumsCredentials,
} from "ente-base/http";
import { apiURL } from "ente-base/origins";
@@ -97,11 +100,15 @@ export const verifyPublicAlbumPassword = async (
* secrets that are not sent by the browser to the server).
*/
export const pullCollection = async (
- accessToken: string,
+ credentials: PublicAlbumsCredentials,
collectionKey: string,
-): Promise<{ collection: Collection; referralCode: string }> => {
- const { collection: remoteCollection, referralCode } =
- await getPublicCollectionInfo(accessToken);
+): Promise<{
+ collection: Collection;
+ referralCode: string;
+ linkDeviceToken?: string;
+}> => {
+ const { collection: remoteCollection, referralCode, linkDeviceToken } =
+ await getPublicCollectionInfo(credentials);
const collection = await decryptRemoteCollection(
remoteCollection,
@@ -111,7 +118,7 @@ export const pullCollection = async (
await savePublicCollection(collection);
await saveLastPublicCollectionReferralCode(referralCode);
- return { collection, referralCode };
+ return { collection, referralCode, linkDeviceToken };
};
const PublicCollectionInfo = z.object({
@@ -135,12 +142,16 @@ const PublicCollectionInfo = z.object({
*
* @param accessToken A public collection access key.
*/
-const getPublicCollectionInfo = async (accessToken: string) => {
+const getPublicCollectionInfo = async (credentials: PublicAlbumsCredentials) => {
const res = await fetch(await apiURL("/public-collection/info"), {
- headers: authenticatedPublicAlbumsRequestHeaders({ accessToken }),
+ headers: authenticatedPublicAlbumsInfoRequestHeaders(credentials),
});
ensureOk(res);
- return PublicCollectionInfo.parse(await res.json());
+ const info = PublicCollectionInfo.parse(await res.json());
+ return {
+ ...info,
+ linkDeviceToken: linkDeviceTokenFromResponse(res),
+ };
};
/**
@@ -244,7 +255,10 @@ const getPublicCollectionDiff = async (
) => {
const res = await fetch(
await apiURL("/public-collection/diff", { sinceTime }),
- { headers: authenticatedPublicAlbumsRequestHeaders(credentials) },
+ {
+ headers:
+ authenticatedPublicAlbumsDeviceLimitRequestHeaders(credentials),
+ },
);
ensureOk(res);
return FileDiffResponse.parse(await res.json());
diff --git a/web/apps/albums/src/public-album/data/storage/public-albums-fdb.ts b/web/apps/albums/src/public-album/data/storage/public-albums-fdb.ts
index 82b6ff5e13..c7fd2ac2be 100644
--- a/web/apps/albums/src/public-album/data/storage/public-albums-fdb.ts
+++ b/web/apps/albums/src/public-album/data/storage/public-albums-fdb.ts
@@ -264,6 +264,41 @@ export const removePublicCollectionAccessTokenJWT = async (
await localForage.removeItem(`public-${accessToken}-passkey`);
};
+const publicCollectionLinkDeviceTokenKey = (
+ apiOrigin: string,
+ accessToken: string,
+) => `public-collection-link-device-token:${apiOrigin}:${accessToken}`;
+
+export const savedPublicCollectionLinkDeviceToken = async (
+ apiOrigin: string,
+ accessToken: string,
+) =>
+ LocalString.parse(
+ await localForage.getItem(
+ publicCollectionLinkDeviceTokenKey(apiOrigin, accessToken),
+ ),
+ );
+
+export const savePublicCollectionLinkDeviceToken = async (
+ apiOrigin: string,
+ accessToken: string,
+ linkDeviceToken: string,
+) => {
+ await localForage.setItem(
+ publicCollectionLinkDeviceTokenKey(apiOrigin, accessToken),
+ linkDeviceToken,
+ );
+};
+
+export const removePublicCollectionLinkDeviceToken = async (
+ apiOrigin: string,
+ accessToken: string,
+) => {
+ await localForage.removeItem(
+ publicCollectionLinkDeviceTokenKey(apiOrigin, accessToken),
+ );
+};
+
/**
* Return the previously saved uploader name, if any, present in our local
* database corresponding to a public collection.
diff --git a/web/apps/albums/src/public-album/page/PublicAlbumPage.tsx b/web/apps/albums/src/public-album/page/PublicAlbumPage.tsx
index a55ba6e04d..36a73a1cf5 100644
--- a/web/apps/albums/src/public-album/page/PublicAlbumPage.tsx
+++ b/web/apps/albums/src/public-album/page/PublicAlbumPage.tsx
@@ -72,6 +72,7 @@ import {
import log from "ente-base/log";
import {
albumsAppOrigin,
+ apiOrigin,
isCustomAlbumsAppOrigin,
isOfficialAlbumsApp,
photosAppOrigin,
@@ -270,6 +271,7 @@ export default function PublicAlbumPage() {
const [
{ extractCollectionKeyFromShareURL },
{
+ savedPublicCollectionLinkDeviceToken,
savedPublicCollectionAccessTokenJWT,
savedPublicCollectionByKey,
savedPublicCollectionFiles,
@@ -292,7 +294,13 @@ export default function PublicAlbumPage() {
collectionKey.current = ck;
const collection = await savedPublicCollectionByKey(ck);
const accessToken = t;
+ const currentAPIOrigin = await apiOrigin();
let accessTokenJWT: string | undefined;
+ const linkDeviceToken =
+ await savedPublicCollectionLinkDeviceToken(
+ currentAPIOrigin,
+ accessToken,
+ );
if (collection) {
setPublicCollection(collection);
setIsPasswordProtected(
@@ -307,7 +315,11 @@ export default function PublicAlbumPage() {
accessTokenJWT =
await savedPublicCollectionAccessTokenJWT(accessToken);
}
- credentials.current = { accessToken, accessTokenJWT };
+ credentials.current = {
+ accessToken,
+ accessTokenJWT,
+ linkDeviceToken,
+ };
setPublicAlbumsCredentials(credentials.current);
await publicAlbumsRemotePull();
} finally {
@@ -362,15 +374,27 @@ export default function PublicAlbumPage() {
pullPublicCollectionFiles,
removePublicCollectionFileData,
},
- { removePublicCollectionAccessTokenJWT },
+ {
+ removePublicCollectionAccessTokenJWT,
+ savePublicCollectionLinkDeviceToken,
+ },
] = await Promise.all([
loadPublicCollectionService(),
loadPublicAlbumsFDB(),
]);
- const { collection } = await pullCollection(
- accessToken,
+ const { collection, linkDeviceToken } = await pullCollection(
+ credentials.current!,
collectionKey.current!,
);
+ if (linkDeviceToken) {
+ credentials.current!.linkDeviceToken = linkDeviceToken;
+ setPublicAlbumsCredentials(credentials.current);
+ await savePublicCollectionLinkDeviceToken(
+ await apiOrigin(),
+ accessToken,
+ linkDeviceToken,
+ );
+ }
if (checkAndRedirectForTripAlbum(collection)) {
return;
diff --git a/web/apps/embed/src/pages/index.tsx b/web/apps/embed/src/pages/index.tsx
index bfff393425..b01f7a1804 100644
--- a/web/apps/embed/src/pages/index.tsx
+++ b/web/apps/embed/src/pages/index.tsx
@@ -13,7 +13,7 @@ import {
type PublicAlbumsCredentials,
} from "ente-base/http";
import log from "ente-base/log";
-import { isCustomAlbumsAppOrigin } from "ente-base/origins";
+import { apiOrigin, isCustomAlbumsAppOrigin } from "ente-base/origins";
import { downloadManager } from "ente-gallery/services/download";
import { extractCollectionKeyFromShareURL } from "ente-gallery/services/share";
import { sortFiles } from "ente-gallery/utils/file";
@@ -27,9 +27,11 @@ import { EmbedPasswordForm } from "../components/EmbedPasswordForm";
import {
removePublicCollectionByKey,
savedPublicCollectionAccessTokenJWT,
+ savedPublicCollectionLinkDeviceToken,
savedPublicCollectionByKey,
savedPublicCollectionFiles,
savePublicCollectionAccessTokenJWT,
+ savePublicCollectionLinkDeviceToken,
} from "../services/public-albums-storage";
import {
pullCollection,
@@ -64,10 +66,19 @@ export default function EmbedGallery() {
showLoadingBar();
setLoading(true);
try {
- const { collection } = await pullCollection(
- accessToken,
+ const { collection, linkDeviceToken } = await pullCollection(
+ credentials.current!,
collectionKey.current!,
);
+ if (linkDeviceToken) {
+ credentials.current!.linkDeviceToken = linkDeviceToken;
+ downloadManager.setPublicAlbumsCredentials(credentials.current);
+ savePublicCollectionLinkDeviceToken(
+ await apiOrigin(),
+ accessToken,
+ linkDeviceToken,
+ );
+ }
setPublicCollection(collection);
const isPasswordProtected =
@@ -150,7 +161,12 @@ export default function EmbedGallery() {
collectionKey.current = ck;
const collection = savedPublicCollectionByKey(ck);
const accessToken = t;
+ const currentAPIOrigin = await apiOrigin();
let accessTokenJWT: string | undefined;
+ const linkDeviceToken = savedPublicCollectionLinkDeviceToken(
+ currentAPIOrigin,
+ accessToken,
+ );
if (collection) {
setPublicCollection(collection);
@@ -167,7 +183,11 @@ export default function EmbedGallery() {
savedPublicCollectionAccessTokenJWT(accessToken);
}
- credentials.current = { accessToken, accessTokenJWT };
+ credentials.current = {
+ accessToken,
+ accessTokenJWT,
+ linkDeviceToken,
+ };
downloadManager.setPublicAlbumsCredentials(credentials.current);
await publicAlbumsRemotePull();
diff --git a/web/apps/embed/src/services/public-albums-storage.ts b/web/apps/embed/src/services/public-albums-storage.ts
index f14bd25089..4784717c9a 100644
--- a/web/apps/embed/src/services/public-albums-storage.ts
+++ b/web/apps/embed/src/services/public-albums-storage.ts
@@ -250,6 +250,41 @@ export const removePublicCollectionAccessTokenJWT = (accessToken: string) => {
inMemoryStorage.removeItem(`public-${accessToken}-passkey`);
};
+const publicCollectionLinkDeviceTokenKey = (
+ apiOrigin: string,
+ accessToken: string,
+) => `public-collection-link-device-token:${apiOrigin}:${accessToken}`;
+
+export const savedPublicCollectionLinkDeviceToken = (
+ apiOrigin: string,
+ accessToken: string,
+) =>
+ LocalString.parse(
+ inMemoryStorage.getItem(
+ publicCollectionLinkDeviceTokenKey(apiOrigin, accessToken),
+ ),
+ );
+
+export const savePublicCollectionLinkDeviceToken = (
+ apiOrigin: string,
+ accessToken: string,
+ linkDeviceToken: string,
+) => {
+ inMemoryStorage.setItem(
+ publicCollectionLinkDeviceTokenKey(apiOrigin, accessToken),
+ linkDeviceToken,
+ );
+};
+
+export const removePublicCollectionLinkDeviceToken = (
+ apiOrigin: string,
+ accessToken: string,
+) => {
+ inMemoryStorage.removeItem(
+ publicCollectionLinkDeviceTokenKey(apiOrigin, accessToken),
+ );
+};
+
/**
* Return the previously saved uploader name, if any, present in our local
* storage corresponding to a public collection.
diff --git a/web/apps/embed/src/services/public-collection.ts b/web/apps/embed/src/services/public-collection.ts
index b8868cfb4c..01a8f7b7a9 100644
--- a/web/apps/embed/src/services/public-collection.ts
+++ b/web/apps/embed/src/services/public-collection.ts
@@ -7,8 +7,11 @@
import { deriveKey } from "ente-base/crypto";
import {
+ authenticatedPublicAlbumsDeviceLimitRequestHeaders,
+ authenticatedPublicAlbumsInfoRequestHeaders,
authenticatedPublicAlbumsRequestHeaders,
ensureOk,
+ linkDeviceTokenFromResponse,
type PublicAlbumsCredentials,
} from "ente-base/http";
import { apiURL } from "ente-base/origins";
@@ -103,12 +106,12 @@ export const verifyPublicAlbumPassword = async (
* secrets that are not sent by the browser to the server).
*/
export const pullCollection = async (
- accessToken: string,
+ credentials: PublicAlbumsCredentials,
collectionKey: string,
) => {
const res = await fetch(await apiURL("/public-collection/info"), {
method: "GET",
- headers: authenticatedPublicAlbumsRequestHeaders({ accessToken }),
+ headers: authenticatedPublicAlbumsInfoRequestHeaders(credentials),
});
ensureOk(res);
@@ -126,7 +129,11 @@ export const pullCollection = async (
savePublicCollection(collection);
- return { collection, referralCode } as const;
+ return {
+ collection,
+ referralCode,
+ linkDeviceToken: linkDeviceTokenFromResponse(res),
+ } as const;
};
/**
@@ -155,7 +162,12 @@ export const pullPublicCollectionFiles = async (
while (hasMore) {
const res = await fetch(
await apiURL("/public-collection/diff", { sinceTime: time ?? 0 }),
- { headers: authenticatedPublicAlbumsRequestHeaders(credentials) },
+ {
+ headers:
+ authenticatedPublicAlbumsDeviceLimitRequestHeaders(
+ credentials,
+ ),
+ },
);
ensureOk(res);
diff --git a/web/apps/share/src/hooks/useCollectionShare.ts b/web/apps/share/src/hooks/useCollectionShare.ts
index 4a0ace2795..097d51cd06 100644
--- a/web/apps/share/src/hooks/useCollectionShare.ts
+++ b/web/apps/share/src/hooks/useCollectionShare.ts
@@ -4,6 +4,7 @@ import {
isHTTP401Error,
isHTTPErrorWithStatus,
} from "ente-base/http";
+import { apiOrigin } from "ente-base/origins";
import { extractCollectionKeyFromShareURL } from "ente-gallery/services/share";
import type { PublicURL } from "ente-media/collection";
import type { NotificationAttributes } from "ente-new/photos/components/Notification";
@@ -91,6 +92,23 @@ const saveAccessTokenJWT = (accessToken: string, accessTokenJWT: string) => {
const removeAccessTokenJWT = (accessToken: string) =>
removeLocalStorageItem(accessTokenJWTStorageKey(accessToken));
+const linkDeviceTokenStorageKey = (apiOrigin: string, accessToken: string) =>
+ `share-collection-link-device-token:${apiOrigin}:${accessToken}`;
+
+const savedLinkDeviceToken = (apiOrigin: string, accessToken: string) =>
+ readLocalStorageItem(linkDeviceTokenStorageKey(apiOrigin, accessToken));
+
+const saveLinkDeviceToken = (
+ apiOrigin: string,
+ accessToken: string,
+ linkDeviceToken: string,
+) => {
+ writeLocalStorageItem(
+ linkDeviceTokenStorageKey(apiOrigin, accessToken),
+ linkDeviceToken,
+ );
+};
+
const collectionShareLoadError = async (
err: unknown,
): Promise<CollectionShareLoadError> => {
@@ -250,17 +268,35 @@ export const useCollectionShare = (): UseCollectionShareResult => {
}
const storedAccessTokenJWT = savedAccessTokenJWT(token);
+ const currentAPIOrigin = await apiOrigin();
+ const storedLinkDeviceToken = savedLinkDeviceToken(
+ currentAPIOrigin,
+ token,
+ );
const resolvedAccessTokenJWT =
opts?.accessTokenJWT ?? storedAccessTokenJWT ?? undefined;
+ const resolvedLinkDeviceToken =
+ storedLinkDeviceToken ?? undefined;
setAccessToken(token);
setCollectionKey(resolvedCollectionKey);
setAccessTokenJWT(resolvedAccessTokenJWT ?? null);
const metadata = await fetchPublicCollectionShareMetadata(
- token,
+ {
+ accessToken: token,
+ accessTokenJWT: resolvedAccessTokenJWT,
+ linkDeviceToken: resolvedLinkDeviceToken,
+ },
resolvedCollectionKey,
);
+ if (metadata.linkDeviceToken) {
+ saveLinkDeviceToken(
+ currentAPIOrigin,
+ token,
+ metadata.linkDeviceToken,
+ );
+ }
if (!metadata.passwordEnabled && resolvedAccessTokenJWT) {
removeAccessTokenJWT(token);
setAccessTokenJWT(null);
@@ -283,6 +319,9 @@ export const useCollectionShare = (): UseCollectionShareResult => {
{
accessToken: token,
accessTokenJWT: activeAccessTokenJWT,
+ linkDeviceToken:
+ metadata.linkDeviceToken ??
+ resolvedLinkDeviceToken,
},
metadata,
);
@@ -448,7 +487,10 @@ export const useCollectionShare = (): UseCollectionShareResult => {
setDownloadProgress(null);
try {
await downloadPublicCollectionFile(
- { accessToken, accessTokenJWT: accessTokenJWT ?? undefined },
+ {
+ accessToken,
+ accessTokenJWT: accessTokenJWT ?? undefined,
+ },
item.id,
fileKey,
item.fileName,
diff --git a/web/apps/share/src/hooks/useFileShare.ts b/web/apps/share/src/hooks/useFileShare.ts
index cad1ef0f95..37289938c6 100644
--- a/web/apps/share/src/hooks/useFileShare.ts
+++ b/web/apps/share/src/hooks/useFileShare.ts
@@ -1,4 +1,5 @@
import type { NotificationAttributes } from "ente-new/photos/components/Notification";
+import { apiOrigin } from "ente-base/origins";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import {
@@ -9,6 +10,34 @@ import {
} from "../services/file-share";
import type { DecryptedFileInfo } from "../types/file-share";
+const linkDeviceTokenStorageKey = (apiOrigin: string, accessToken: string) =>
+ `share-file-link-device-token:${apiOrigin}:${accessToken}`;
+
+const savedLinkDeviceToken = (apiOrigin: string, accessToken: string) => {
+ try {
+ return window.localStorage.getItem(
+ linkDeviceTokenStorageKey(apiOrigin, accessToken),
+ );
+ } catch {
+ return null;
+ }
+};
+
+const saveLinkDeviceToken = (
+ apiOrigin: string,
+ accessToken: string,
+ linkDeviceToken: string,
+) => {
+ try {
+ window.localStorage.setItem(
+ linkDeviceTokenStorageKey(apiOrigin, accessToken),
+ linkDeviceToken,
+ );
+ } catch {
+ // Ignore storage failures and continue with in-memory state.
+ }
+};
+
interface UseFileShareResult {
loading: boolean;
downloading: boolean;
@@ -56,7 +85,23 @@ export const useFileShare = (): UseFileShareResult => {
setAccessToken(token);
- const encryptedInfo = await fetchFileInfo(token);
+ const currentAPIOrigin = await apiOrigin();
+ const storedLinkDeviceToken = savedLinkDeviceToken(
+ currentAPIOrigin,
+ token,
+ );
+ const { fileLinkInfo: encryptedInfo, linkDeviceToken } =
+ await fetchFileInfo(
+ token,
+ storedLinkDeviceToken ?? undefined,
+ );
+ if (linkDeviceToken) {
+ saveLinkDeviceToken(
+ currentAPIOrigin,
+ token,
+ linkDeviceToken,
+ );
+ }
const decryptedInfo = await decryptFileInfo(
encryptedInfo,
keyMaterial,
diff --git a/web/apps/share/src/services/collection-share.ts b/web/apps/share/src/services/collection-share.ts
index 51c1175629..09b2232e35 100644
--- a/web/apps/share/src/services/collection-share.ts
+++ b/web/apps/share/src/services/collection-share.ts
@@ -5,8 +5,11 @@ import {
deriveKey,
} from "ente-base/crypto";
import {
+ authenticatedPublicAlbumsDeviceLimitRequestHeaders,
+ authenticatedPublicAlbumsInfoRequestHeaders,
authenticatedPublicAlbumsRequestHeaders,
ensureOk,
+ linkDeviceTokenFromResponse,
type PublicAlbumsCredentials,
} from "ente-base/http";
import { apiOrigin, apiURL } from "ente-base/origins";
@@ -48,6 +51,7 @@ export interface PublicCollectionShareMetadata {
passwordEnabled: boolean;
publicURL?: PublicURL;
collectionKey: string;
+ linkDeviceToken?: string;
}
interface DownloadProgress {
@@ -238,7 +242,10 @@ const fetchPublicCollectionDiff = async (
const res = await fetch(
await apiURL("/public-collection/diff", { sinceTime }),
{
- headers: authenticatedPublicAlbumsRequestHeaders(credentials),
+ headers:
+ authenticatedPublicAlbumsDeviceLimitRequestHeaders(
+ credentials,
+ ),
cache: "no-store",
},
);
@@ -287,16 +294,18 @@ export const verifyPublicCollectionPassword = async (
};
export const fetchPublicCollectionShareMetadata = async (
- accessToken: string,
+ credentials: PublicAlbumsCredentials,
collectionKey: string,
): Promise<PublicCollectionShareMetadata> => {
const res = await fetch(await apiURL("/public-collection/info"), {
- headers: authenticatedPublicAlbumsRequestHeaders({ accessToken }),
+ headers: authenticatedPublicAlbumsInfoRequestHeaders(credentials),
cache: "no-store",
});
ensureOk(res);
- const data = (await res.json()) as { collection: unknown };
+ const data = (await res.json()) as {
+ collection: unknown;
+ };
const remoteCollection = RemoteCollection.parse(data.collection);
const collection = await decryptRemoteCollection(
remoteCollection,
@@ -312,6 +321,7 @@ export const fetchPublicCollectionShareMetadata = async (
passwordEnabled: publicURL?.passwordEnabled ?? false,
publicURL,
collectionKey: collection.key,
+ linkDeviceToken: linkDeviceTokenFromResponse(res),
};
};
diff --git a/web/apps/share/src/services/file-share.ts b/web/apps/share/src/services/file-share.ts
index 2292055e6a..fbaeb60d5a 100644
--- a/web/apps/share/src/services/file-share.ts
+++ b/web/apps/share/src/services/file-share.ts
@@ -1,4 +1,8 @@
import bs58 from "bs58";
+import {
+ linkDeviceTokenFromResponse,
+ linkDeviceTokenRequestHeader,
+} from "ente-base/http";
import {
decryptBoxBytes,
decryptMetadataJSON,
@@ -69,11 +73,17 @@ export const extractFileKeyFromURL = async (
*/
export const fetchFileInfo = async (
accessToken: string,
-): Promise<FileLinkInfo> => {
+ linkDeviceToken?: string,
+): Promise<{ fileLinkInfo: FileLinkInfo; linkDeviceToken?: string }> => {
const url = `${await apiOrigin()}/file-link/info`;
const response = await fetch(url, {
- headers: { "X-Auth-Access-Token": accessToken },
+ headers: {
+ "X-Auth-Access-Token": accessToken,
+ ...(linkDeviceToken && {
+ [linkDeviceTokenRequestHeader]: linkDeviceToken,
+ }),
+ },
cache: "no-store",
});
@@ -85,7 +95,10 @@ export const fetchFileInfo = async (
}
const data = (await response.json()) as FileLinkInfo;
- return data;
+ return {
+ fileLinkInfo: data,
+ linkDeviceToken: linkDeviceTokenFromResponse(response),
+ };
};
/**
diff --git a/web/packages/base/http.ts b/web/packages/base/http.ts
index d2942cb9ad..8422ea9375 100644
--- a/web/packages/base/http.ts
+++ b/web/packages/base/http.ts
@@ -65,8 +65,20 @@ export interface PublicAlbumsCredentials {
* public collections related API requests.
*/
accessTokenJWT?: string | undefined;
+ /**
+ * A signed token issued after this browser has been admitted once for this
+ * public link's device limit. It is separate from the password JWT.
+ */
+ linkDeviceToken?: string | undefined;
}
+export const linkDeviceTokenRequestHeader = "X-Auth-Link-Device-Token";
+
+export const linkDeviceTokenResponseHeader = "X-Ente-Link-Device-Token";
+
+export const linkDeviceTokenFromResponse = (res: Response) =>
+ res.headers.get(linkDeviceTokenResponseHeader) ?? undefined;
+
/**
* Return headers that should be passed alongwith public collection related
* authenticated `fetch` calls that we make to our API servers.
@@ -84,6 +96,18 @@ export const authenticatedPublicAlbumsRequestHeaders = ({
"X-Client-Package": clientPackageName,
});
+export const authenticatedPublicAlbumsDeviceLimitRequestHeaders = (
+ credentials: PublicAlbumsCredentials,
+) => ({
+ ...authenticatedPublicAlbumsRequestHeaders(credentials),
+ ...(credentials.linkDeviceToken && {
+ [linkDeviceTokenRequestHeader]: credentials.linkDeviceToken,
+ }),
+});
+
+export const authenticatedPublicAlbumsInfoRequestHeaders =
+ authenticatedPublicAlbumsDeviceLimitRequestHeaders;
+
/**
* A custom Error that is thrown if a fetch fails with a non-2xx HTTP status.
*/