diff --git a/__e2e__/flows/group-invite/accept-outage.yml b/__e2e__/flows/group-invite/accept-outage.yml new file mode 100644 index 000000000..c936695a5 --- /dev/null +++ b/__e2e__/flows/group-invite/accept-outage.yml @@ -0,0 +1,28 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: accept-outage +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInviteRetryButton + timeout: 30000 +- assertVisible: 'We could not contact the group service. Please try again.' +- tapOn: + id: groupInviteRetryButton +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '2' + EXPECT_ACCEPT_WITH_BEARER: '2' + EXPECT_CLAIM_COUNT: '0' diff --git a/__e2e__/flows/group-invite/authentication-required.yml b/__e2e__/flows/group-invite/authentication-required.yml new file mode 100644 index 000000000..d0f2b13fb --- /dev/null +++ b/__e2e__/flows/group-invite/authentication-required.yml @@ -0,0 +1,28 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: auth-required +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInviteRetryButton + timeout: 30000 +- assertVisible: 'Please sign in again to accept this invite.' +- tapOn: + id: groupInviteRetryButton +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '1' + EXPECT_ACCEPT_WITH_BEARER: '1' + EXPECT_CLAIM_COUNT: '0' diff --git a/__e2e__/flows/group-invite/capability-outage.yml b/__e2e__/flows/group-invite/capability-outage.yml new file mode 100644 index 000000000..abd8d0e6e --- /dev/null +++ b/__e2e__/flows/group-invite/capability-outage.yml @@ -0,0 +1,33 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: capability-outage +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInviteRetryButton + timeout: 30000 +- assertVisible: 'We could not contact the group service. Please try again.' +- tapOn: + id: groupInviteRetryButton +- extendedWaitUntil: + visible: + id: groupInviteAcceptedMembership + timeout: 30000 +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '2' + EXPECT_ACCEPT_WITH_BEARER: '2' + EXPECT_CLAIM_COUNT: '1' + EXPECT_CLAIMANT_COUNT: '1' diff --git a/__e2e__/flows/group-invite/cold-auth-resume.yml b/__e2e__/flows/group-invite/cold-auth-resume.yml new file mode 100644 index 000000000..2b81b5f3a --- /dev/null +++ b/__e2e__/flows/group-invite/cold-auth-resume.yml @@ -0,0 +1,24 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: resumable +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteLanding + timeout: 30000 +- assertVisible: 'Members' +- assertVisible: 'Test Community' +- runFlow: + file: ../../helpers/group-invite-sign-in.yml +- assertVisible: + id: groupInviteAcceptedMembership +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '1' + EXPECT_ACCEPT_WITH_BEARER: '1' + EXPECT_CLAIM_COUNT: '1' + EXPECT_CLAIMANT_COUNT: '1' diff --git a/__e2e__/flows/group-invite/existing-unpinned.yml b/__e2e__/flows/group-invite/existing-unpinned.yml new file mode 100644 index 000000000..93a740e3c --- /dev/null +++ b/__e2e__/flows/group-invite/existing-unpinned.yml @@ -0,0 +1,35 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: existing-unpinned +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInvitePinOpenButton + timeout: 30000 +- tapOn: + id: groupInvitePinOpenButton +- extendedWaitUntil: + visible: + id: homeScreen + timeout: 30000 +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '1' + EXPECT_CLAIM_COUNT: '1' + EXPECT_SAVED_TOTAL: '2' + EXPECT_SAVED_PINNED: '2' + EXPECT_SAVED_VISIBLE: '2' + EXPECT_VISIBLE_PINNED: '2' + EXPECT_INACCESSIBLE_SAVED: '0' diff --git a/__e2e__/flows/group-invite/group-at-capacity.yml b/__e2e__/flows/group-invite/group-at-capacity.yml new file mode 100644 index 000000000..d7e8ab80a --- /dev/null +++ b/__e2e__/flows/group-invite/group-at-capacity.yml @@ -0,0 +1,28 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: capacity +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInviteRetryButton + timeout: 30000 +- assertVisible: 'This group is currently at capacity.' +- tapOn: + id: groupInviteRetryButton +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '1' + EXPECT_ACCEPT_WITH_BEARER: '1' + EXPECT_CLAIM_COUNT: '0' diff --git a/__e2e__/flows/group-invite/https-universal-link.yml b/__e2e__/flows/group-invite/https-universal-link.yml new file mode 100644 index 000000000..ab4541c2a --- /dev/null +++ b/__e2e__/flows/group-invite/https-universal-link.yml @@ -0,0 +1,19 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: mixed +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'https://blacksky.community/join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- assertVisible: + id: groupInviteAcceptButton +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '0' diff --git a/__e2e__/flows/group-invite/invite-unavailable-consumed.yml b/__e2e__/flows/group-invite/invite-unavailable-consumed.yml new file mode 100644 index 000000000..a70f5afb8 --- /dev/null +++ b/__e2e__/flows/group-invite/invite-unavailable-consumed.yml @@ -0,0 +1,20 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: consumed +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteRetryButton + timeout: 30000 +- assertVisible: 'This invite is no longer available.' +- tapOn: + id: groupInviteRetryButton +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '0' diff --git a/__e2e__/flows/group-invite/invite-unavailable-expired.yml b/__e2e__/flows/group-invite/invite-unavailable-expired.yml new file mode 100644 index 000000000..5ea0c7fb7 --- /dev/null +++ b/__e2e__/flows/group-invite/invite-unavailable-expired.yml @@ -0,0 +1,14 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: expired +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteLandingRetry + timeout: 30000 +- assertVisible: 'This invite is no longer available.' +- tapOn: + id: groupInviteLandingRetry diff --git a/__e2e__/flows/group-invite/invite-unavailable-missing.yml b/__e2e__/flows/group-invite/invite-unavailable-missing.yml new file mode 100644 index 000000000..912e7afcd --- /dev/null +++ b/__e2e__/flows/group-invite/invite-unavailable-missing.yml @@ -0,0 +1,20 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: missing +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteLandingRetry + timeout: 30000 +- assertVisible: 'This invite is no longer available.' +- assertNotVisible: + id: groupInviteAcceptButton +- tapOn: + id: groupInviteLandingRetry +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '0' diff --git a/__e2e__/flows/group-invite/malformed-link.yml b/__e2e__/flows/group-invite/malformed-link.yml new file mode 100644 index 000000000..e2282d25c --- /dev/null +++ b/__e2e__/flows/group-invite/malformed-link.yml @@ -0,0 +1,19 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: mixed +- openLink: 'blacksky://join/not-a-valid-group-code' +- extendedWaitUntil: + visible: + id: mobileShellView + timeout: 10000 +- assertNotVisible: + id: groupInviteLanding +- assertNotVisible: + id: groupInviteAcceptButton +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '0' diff --git a/__e2e__/flows/group-invite/malformed-success.yml b/__e2e__/flows/group-invite/malformed-success.yml new file mode 100644 index 000000000..32aff94db --- /dev/null +++ b/__e2e__/flows/group-invite/malformed-success.yml @@ -0,0 +1,33 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: malformed-success +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInviteRetryButton + timeout: 30000 +- assertVisible: 'We could not contact the group service. Please try again.' +- tapOn: + id: groupInviteRetryButton +- extendedWaitUntil: + visible: + id: groupInviteAcceptedMembership + timeout: 30000 +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '2' + EXPECT_ACCEPT_WITH_BEARER: '2' + EXPECT_CLAIM_COUNT: '1' + EXPECT_CLAIMANT_COUNT: '1' diff --git a/__e2e__/flows/group-invite/misconfigured.yml b/__e2e__/flows/group-invite/misconfigured.yml new file mode 100644 index 000000000..2c036c055 --- /dev/null +++ b/__e2e__/flows/group-invite/misconfigured.yml @@ -0,0 +1,14 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: misconfigured +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteLandingRetry + timeout: 30000 +- assertVisible: 'This invite is temporarily unavailable.' +- tapOn: + id: groupInviteLandingRetry diff --git a/__e2e__/flows/group-invite/navigation-failure.yml b/__e2e__/flows/group-invite/navigation-failure.yml new file mode 100644 index 000000000..616eb151d --- /dev/null +++ b/__e2e__/flows/group-invite/navigation-failure.yml @@ -0,0 +1,45 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: navigation +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- tapOn: + id: e2eGroupInviteFailNavigation +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInvitePinOpenButton + timeout: 30000 +- tapOn: + id: groupInvitePinOpenButton +- extendedWaitUntil: + visible: + id: groupInviteNavigationError + timeout: 30000 +- assertVisible: 'Your membership and saved feeds are preserved.' +- assertVisible: + id: groupInviteNavigationRetryButton +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '1' + EXPECT_CLAIM_COUNT: '1' + EXPECT_SAVED_TOTAL: '2' + EXPECT_SAVED_PINNED: '2' + EXPECT_SAVED_VISIBLE: '2' + EXPECT_VISIBLE_PINNED: '2' +- tapOn: + id: groupInviteNavigationRetryButton +- extendedWaitUntil: + visible: + id: homeScreen + timeout: 30000 diff --git a/__e2e__/flows/group-invite/no-post.yml b/__e2e__/flows/group-invite/no-post.yml new file mode 100644 index 000000000..91b8d7093 --- /dev/null +++ b/__e2e__/flows/group-invite/no-post.yml @@ -0,0 +1,24 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: no-post +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInviteNoPostableFeeds + timeout: 30000 +- assertVisible: + id: groupInviteNoPostableFeeds +- assertVisible: + id: groupInvitePinOpenButton +- assertVisible: 'Please let your admins know if you think this is a mistake.' diff --git a/__e2e__/flows/group-invite/pin-add-failure.yml b/__e2e__/flows/group-invite/pin-add-failure.yml new file mode 100644 index 000000000..7dcbe3d19 --- /dev/null +++ b/__e2e__/flows/group-invite/pin-add-failure.yml @@ -0,0 +1,43 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: pin-add +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- tapOn: + id: e2eGroupInviteFailAdd +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInvitePinOpenButton + timeout: 30000 +- tapOn: + id: groupInvitePinOpenButton +- extendedWaitUntil: + visible: + id: groupInvitePinError + timeout: 30000 +- assertVisible: 'We could not save your feeds. Please try again.' +- tapOn: + id: groupInvitePinRetryButton +- extendedWaitUntil: + visible: + id: homeScreen + timeout: 30000 +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '1' + EXPECT_CLAIM_COUNT: '1' + EXPECT_SAVED_TOTAL: '2' + EXPECT_SAVED_PINNED: '2' + EXPECT_SAVED_VISIBLE: '2' + EXPECT_VISIBLE_PINNED: '2' diff --git a/__e2e__/flows/group-invite/pin-update-failure.yml b/__e2e__/flows/group-invite/pin-update-failure.yml new file mode 100644 index 000000000..6cbb18af3 --- /dev/null +++ b/__e2e__/flows/group-invite/pin-update-failure.yml @@ -0,0 +1,43 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: pin-update +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- tapOn: + id: e2eGroupInviteFailUpdate +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInvitePinOpenButton + timeout: 30000 +- tapOn: + id: groupInvitePinOpenButton +- extendedWaitUntil: + visible: + id: groupInvitePinError + timeout: 30000 +- assertVisible: 'We could not save your feeds. Please try again.' +- tapOn: + id: groupInvitePinRetryButton +- extendedWaitUntil: + visible: + id: homeScreen + timeout: 30000 +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '1' + EXPECT_CLAIM_COUNT: '1' + EXPECT_SAVED_TOTAL: '2' + EXPECT_SAVED_PINNED: '2' + EXPECT_SAVED_VISIBLE: '2' + EXPECT_VISIBLE_PINNED: '2' diff --git a/__e2e__/flows/group-invite/preview-identity.yml b/__e2e__/flows/group-invite/preview-identity.yml new file mode 100644 index 000000000..50d87ab12 --- /dev/null +++ b/__e2e__/flows/group-invite/preview-identity.yml @@ -0,0 +1,21 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: mixed +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- assertVisible: 'Members' +- assertVisible: 'Test Community' +- assertNotVisible: + id: groupInviteAcceptedMembership +- assertNotVisible: + id: groupInviteFeedOption-0 +- assertNotVisible: + id: groupInviteFeedOption-1 diff --git a/__e2e__/flows/group-invite/preview-outage.yml b/__e2e__/flows/group-invite/preview-outage.yml new file mode 100644 index 000000000..7c7622f8f --- /dev/null +++ b/__e2e__/flows/group-invite/preview-outage.yml @@ -0,0 +1,14 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: preview-outage +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteLandingRetry + timeout: 30000 +- assertVisible: 'We could not contact the group service. Please try again.' +- tapOn: + id: groupInviteLandingRetry diff --git a/__e2e__/flows/group-invite/rapid-taps.yml b/__e2e__/flows/group-invite/rapid-taps.yml new file mode 100644 index 000000000..8379b2c26 --- /dev/null +++ b/__e2e__/flows/group-invite/rapid-taps.yml @@ -0,0 +1,35 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: rapid +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton + repeat: 2 + delay: 0 +- extendedWaitUntil: + visible: + id: groupInviteAcceptedMembership + timeout: 30000 +- tapOn: + id: groupInvitePinOpenButton +- extendedWaitUntil: + visible: + id: homeScreen + timeout: 30000 +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '1' + EXPECT_ACCEPT_WITH_BEARER: '1' + EXPECT_CLAIM_COUNT: '1' + EXPECT_SAVED_TOTAL: '2' + EXPECT_SAVED_PINNED: '2' diff --git a/__e2e__/flows/group-invite/rate-limit.yml b/__e2e__/flows/group-invite/rate-limit.yml new file mode 100644 index 000000000..129d1d598 --- /dev/null +++ b/__e2e__/flows/group-invite/rate-limit.yml @@ -0,0 +1,28 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: rate-limit +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInviteRetryButton + timeout: 30000 +- assertVisible: 'Too many attempts. Please try again shortly.' +- tapOn: + id: groupInviteRetryButton +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '1' + EXPECT_ACCEPT_WITH_BEARER: '1' + EXPECT_CLAIM_COUNT: '0' diff --git a/__e2e__/flows/group-invite/read-only.yml b/__e2e__/flows/group-invite/read-only.yml new file mode 100644 index 000000000..7d2926806 --- /dev/null +++ b/__e2e__/flows/group-invite/read-only.yml @@ -0,0 +1,36 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: read-only +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInviteNoPostableFeeds + timeout: 30000 +- assertVisible: + id: groupInviteFeedOption-0 +- assertVisible: '.*Read only.*' +- assertVisible: "You joined the group, but you don't currently have access to a feed you can post in." +- tapOn: + id: groupInvitePinOpenButton +- extendedWaitUntil: + visible: + id: homeScreen + timeout: 30000 +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '1' + EXPECT_CLAIM_COUNT: '1' + EXPECT_SAVED_TOTAL: '1' + EXPECT_SAVED_PINNED: '1' diff --git a/__e2e__/flows/group-invite/same-did-other-did.yml b/__e2e__/flows/group-invite/same-did-other-did.yml new file mode 100644 index 000000000..d8524a741 --- /dev/null +++ b/__e2e__/flows/group-invite/same-did-other-did.yml @@ -0,0 +1,65 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: resumable +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInviteAcceptedMembership + timeout: 30000 +- tapOn: + id: groupInviteDialogHandle +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInviteAcceptedMembership + timeout: 30000 +- tapOn: + id: groupInviteDialogHandle +- tapOn: + id: e2eSignOut +- extendedWaitUntil: + visible: + id: e2eSignInAlice + timeout: 10000 +- tapOn: + id: e2eSignInBob +- extendedWaitUntil: + visible: + id: bottomBarHomeBtn + timeout: 30000 +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInviteRetryButton + timeout: 30000 +- assertVisible: 'This invite is no longer available.' +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '3' + EXPECT_ACCEPT_WITH_BEARER: '3' + EXPECT_CLAIM_COUNT: '1' + EXPECT_CLAIMANT_COUNT: '1' diff --git a/__e2e__/flows/group-invite/selection-readable-fallback.yml b/__e2e__/flows/group-invite/selection-readable-fallback.yml new file mode 100644 index 000000000..99f7abcdc --- /dev/null +++ b/__e2e__/flows/group-invite/selection-readable-fallback.yml @@ -0,0 +1,37 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: mixed +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInviteFeedOption-1 + timeout: 30000 +- tapOn: + id: groupInviteFeedOption-1 +- tapOn: + id: groupInvitePinOpenButton +- extendedWaitUntil: + visible: + id: homeScreen + timeout: 30000 +- assertVisible: e2e-group-read +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '1' + EXPECT_CLAIM_COUNT: '1' + EXPECT_SAVED_TOTAL: '1' + EXPECT_SAVED_PINNED: '1' + EXPECT_SAVED_VISIBLE: '1' + EXPECT_VISIBLE_PINNED: '1' diff --git a/__e2e__/flows/group-invite/success-mixed.yml b/__e2e__/flows/group-invite/success-mixed.yml new file mode 100644 index 000000000..686c8db92 --- /dev/null +++ b/__e2e__/flows/group-invite/success-mixed.yml @@ -0,0 +1,47 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: mixed +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInviteAcceptedMembership + timeout: 30000 +- assertVisible: + id: groupInviteFeedOption-0 +- assertVisible: '.*Read only.*' +- assertVisible: + id: groupInviteFeedOption-1 +- assertVisible: '.*Postable feed.*Post.*read.*' +- assertNotVisible: + id: groupInviteFeedOption-2 +- assertNotVisible: '.*Inaccessible feed.*' +- tapOn: + id: groupInvitePinOpenButton +- extendedWaitUntil: + visible: + id: homeScreen + timeout: 30000 +- assertVisible: e2e-group-post +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '1' + EXPECT_ACCEPT_WITH_BEARER: '1' + EXPECT_CLAIM_COUNT: '1' + EXPECT_CLAIMANT_COUNT: '1' + EXPECT_SAVED_TOTAL: '2' + EXPECT_SAVED_PINNED: '2' + EXPECT_SAVED_VISIBLE: '2' + EXPECT_VISIBLE_PINNED: '2' + EXPECT_INACCESSIBLE_SAVED: '0' diff --git a/__e2e__/flows/group-invite/warm-custom-scheme.yml b/__e2e__/flows/group-invite/warm-custom-scheme.yml new file mode 100644 index 000000000..33f9cdcde --- /dev/null +++ b/__e2e__/flows/group-invite/warm-custom-scheme.yml @@ -0,0 +1,23 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: mixed +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- assertVisible: + id: groupInviteAcceptButton +- assertNotVisible: + id: groupInviteLanding +- assertNotVisible: + id: loginForm +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '0' diff --git a/__e2e__/flows/group-invite/zero-readable.yml b/__e2e__/flows/group-invite/zero-readable.yml new file mode 100644 index 000000000..adf34256f --- /dev/null +++ b/__e2e__/flows/group-invite/zero-readable.yml @@ -0,0 +1,30 @@ +appId: community.blacksky.app +--- +- runFlow: + file: ../../helpers/group-invite-setup.yml + env: + SCENARIO: zero-readable +- runFlow: + file: ../../helpers/group-invite-sign-in-alice.yml +- openLink: 'blacksky://join/${output.groupInviteCode}' +- extendedWaitUntil: + visible: + id: groupInviteAcceptButton + timeout: 30000 +- tapOn: + id: groupInviteAcceptButton +- extendedWaitUntil: + visible: + id: groupInviteNoReadableFeeds + timeout: 30000 +- assertVisible: 'No feeds available.' +- assertVisible: + id: groupInviteNoReadableWarning +- assertVisible: 'Please let your admins know if you think this is a mistake.' +- assertNotVisible: + id: groupInvitePinOpenButton +- runScript: + file: ../../helpers/assert-group-invite-state.js + env: + EXPECT_ACCEPT_REQUESTS: '1' + EXPECT_CLAIM_COUNT: '1' diff --git a/__e2e__/helpers/assert-group-invite-state.js b/__e2e__/helpers/assert-group-invite-state.js new file mode 100644 index 000000000..05c7757bb --- /dev/null +++ b/__e2e__/helpers/assert-group-invite-state.js @@ -0,0 +1,80 @@ +var response = http.get('http://localhost:1986/__e2e/group-invite/state') + +if (response.status !== 200 || !response.body) { + throw new Error('Group invite fixture state was unavailable') +} + +var state +try { + state = json(response.body) +} catch (_error) { + throw new Error('Group invite fixture state response was invalid') +} + +function assertNumber(path, actual, expected) { + if (expected === undefined || expected === '') return + var parsed = Number(expected) + if (actual !== parsed) { + throw new Error(path + ' expected ' + parsed + ' but was ' + actual) + } +} + +assertNumber( + 'acceptRequests', + state.acceptRequests, + typeof EXPECT_ACCEPT_REQUESTS === 'undefined' + ? undefined + : EXPECT_ACCEPT_REQUESTS, +) +assertNumber( + 'acceptRequestsWithBearer', + state.acceptRequestsWithBearer, + typeof EXPECT_ACCEPT_WITH_BEARER === 'undefined' + ? undefined + : EXPECT_ACCEPT_WITH_BEARER, +) +assertNumber( + 'claimCount', + state.claimCount, + typeof EXPECT_CLAIM_COUNT === 'undefined' ? undefined : EXPECT_CLAIM_COUNT, +) +assertNumber( + 'claimantCount', + state.claimantCount, + typeof EXPECT_CLAIMANT_COUNT === 'undefined' + ? undefined + : EXPECT_CLAIMANT_COUNT, +) +assertNumber( + 'savedFeeds.total', + state.savedFeeds.total, + typeof EXPECT_SAVED_TOTAL === 'undefined' ? undefined : EXPECT_SAVED_TOTAL, +) +assertNumber( + 'savedFeeds.pinned', + state.savedFeeds.pinned, + typeof EXPECT_SAVED_PINNED === 'undefined' ? undefined : EXPECT_SAVED_PINNED, +) +assertNumber( + 'savedFeeds.visible', + state.savedFeeds.visible, + typeof EXPECT_SAVED_VISIBLE === 'undefined' + ? undefined + : EXPECT_SAVED_VISIBLE, +) +assertNumber( + 'savedFeeds.visiblePinned', + state.savedFeeds.visiblePinned, + typeof EXPECT_VISIBLE_PINNED === 'undefined' + ? undefined + : EXPECT_VISIBLE_PINNED, +) +assertNumber( + 'savedFeeds.inaccessible', + state.savedFeeds.inaccessible, + typeof EXPECT_INACCESSIBLE_SAVED === 'undefined' + ? undefined + : EXPECT_INACCESSIBLE_SAVED, +) + +output.groupInviteStateChecked = true diff --git a/__e2e__/helpers/group-invite-setup.yml b/__e2e__/helpers/group-invite-setup.yml new file mode 100644 index 000000000..b61f74bf1 --- /dev/null +++ b/__e2e__/helpers/group-invite-setup.yml @@ -0,0 +1,8 @@ +appId: community.blacksky.app +--- +- runScript: + file: ../setupServer.js + env: + SERVER_PATH: '?groupInvite=${SCENARIO}' +- runFlow: + file: ../setupApp.yml diff --git a/__e2e__/helpers/group-invite-sign-in-alice.yml b/__e2e__/helpers/group-invite-sign-in-alice.yml new file mode 100644 index 000000000..a0af1e41c --- /dev/null +++ b/__e2e__/helpers/group-invite-sign-in-alice.yml @@ -0,0 +1,12 @@ +appId: community.blacksky.app +--- +- extendedWaitUntil: + visible: + id: e2eSignInAlice + timeout: 10000 +- tapOn: + id: e2eSignInAlice +- extendedWaitUntil: + visible: + id: bottomBarHomeBtn + timeout: 30000 diff --git a/__e2e__/helpers/group-invite-sign-in.yml b/__e2e__/helpers/group-invite-sign-in.yml new file mode 100644 index 000000000..307b121b2 --- /dev/null +++ b/__e2e__/helpers/group-invite-sign-in.yml @@ -0,0 +1,24 @@ +appId: community.blacksky.app +--- +- tapOn: + id: 'groupInviteLandingSignIn' +- tapOn: + id: 'selectServiceButton' +- tapOn: 'Custom' +- tapOn: + id: 'customServerTextInput' +- inputText: 'http://localhost:3000' +- pressKey: Enter +- tapOn: + id: 'doneBtn' +- tapOn: + id: 'loginUsernameInput' +- inputText: 'alice.test' +- tapOn: + id: 'loginPasswordInput' +- inputText: 'hunter2' +- pressKey: Enter +- extendedWaitUntil: + visible: + id: 'groupInviteAcceptButton' + timeout: 30000 diff --git a/__e2e__/setupApp.yml b/__e2e__/setupApp.yml index d26ad9df2..3bee39643 100644 --- a/__e2e__/setupApp.yml +++ b/__e2e__/setupApp.yml @@ -1,15 +1,15 @@ appId: community.blacksky.app --- - launchApp: - appId: "community.blacksky.app" + appId: 'community.blacksky.app' clearState: true arguments: - "-EXDevMenuIsOnboardingFinished": true + '-EXDevMenuIsOnboardingFinished': true - runFlow: when: platform: iOS commands: - - openLink: "exp+blacksky://expo-development-client/?url=http%3A%2F%2Flocalhost%3A8082" + - openLink: 'exp+blacksky://expo-development-client/?url=http%3A%2F%2Flocalhost%3A8082' - runFlow: when: visible: 'Open in "Blacksky"' @@ -19,11 +19,11 @@ appId: community.blacksky.app when: platform: Android commands: - - tapOn: 'http://localhost:8082' + - tapOn: 'http://10.0.2.2:8082' - runFlow: - label: "Dismiss Expo dev menu" + label: 'Dismiss Expo dev menu' when: - visible: "Continue" + visible: 'Continue' commands: - back - tapOn: diff --git a/__e2e__/setupServer.js b/__e2e__/setupServer.js index 5038197b0..08fbf8996 100644 --- a/__e2e__/setupServer.js +++ b/__e2e__/setupServer.js @@ -4,5 +4,29 @@ var res = http.post('http://localhost:1986/' + SERVER_PATH, { body: '', }) +if (res.status !== 200 || !res.body) { + throw new Error( + 'Local E2E manager failed to create the requested fixture (status ' + + res.status + + ')', + ) +} + // eslint-disable-next-line no-undef -output.result = json(res.body).appviewDid +var payload +try { + payload = json(res.body) +} catch (_error) { + throw new Error('Local E2E manager returned an invalid fixture response') +} + +if (!payload || !payload.appviewDid) { + throw new Error('Local E2E manager returned an incomplete fixture response') +} + +output.result = payload.appviewDid +if (payload.groupInvite) { + output.groupInviteCode = payload.groupInvite.code + output.groupInviteScenario = payload.groupInvite.scenario + output.groupInviteServiceUrl = payload.groupInvite.acornUrl +} diff --git a/__tests__/lib/feed-manip-community.test.ts b/__tests__/lib/feed-manip-community.test.ts index 8350acef5..a78ca36a3 100644 --- a/__tests__/lib/feed-manip-community.test.ts +++ b/__tests__/lib/feed-manip-community.test.ts @@ -4,7 +4,7 @@ import { type AppBskyFeedPost, } from '@atproto/api' -import {FeedTuner} from '#/lib/api/feed-manip' +import {FeedTuner, FeedViewPostsSlice} from '#/lib/api/feed-manip' // The repo-wide manual mock stubs CID.parse away, which makes every // cid-format validation fail; these tests exercise real record validation. @@ -20,6 +20,8 @@ const VIEWER_DID = 'did:plc:viewer' const MEMBER_DID = 'did:plc:member' const COLLECTION = 'community.blacksky.feed.post' const CID = 'bafyreihhl5mpvjkrhnnagen2fomozzhnhhdq2jr6cego2nzbvmwewv5rd4' +const SPACE_URI = + 'at://did:plc:community/space/community.blacksky.feed/aabbcc/did:plc:member/app.bsky.feed.post/root' function author( did: string, @@ -77,6 +79,37 @@ function followingTuner() { } describe('FeedTuner with merged community posts', () => { + it('keeps a space quote whose embedded record uses a space URI', () => { + const post = communityPost({rkey: 'quote'}) + post.uri = + 'at://did:plc:community/space/community.blacksky.feed/aabbcc/did:plc:member/app.bsky.feed.post/quote' + post.record = { + $type: 'app.bsky.feed.post', + text: 'quoted', + createdAt: '2026-07-17T12:00:00.000Z', + embed: { + $type: 'app.bsky.embed.record', + record: {uri: SPACE_URI, cid: CID}, + }, + } + post.embed = { + $type: 'app.bsky.embed.record#view', + record: { + $type: 'app.bsky.embed.record#viewRecord', + uri: SPACE_URI, + cid: CID, + author: author(MEMBER_DID), + value: {text: 'root', createdAt: '2026-07-17T12:00:00.000Z'}, + indexedAt: '2026-07-17T12:00:00.000Z', + }, + } + + const slice = new FeedViewPostsSlice({post}) + + expect(slice.items).toHaveLength(1) + expect(slice.isQuotePost).toBe(true) + }) + it('keeps a top-level community post', () => { const feed: AppBskyFeedDefs.FeedViewPost[] = [ {post: communityPost({rkey: 'aaa'})}, diff --git a/__tests__/lib/space-feed-routing.test.ts b/__tests__/lib/space-feed-routing.test.ts new file mode 100644 index 000000000..945977790 --- /dev/null +++ b/__tests__/lib/space-feed-routing.test.ts @@ -0,0 +1,155 @@ +// `jsonToLex` walks the body looking for CID links, and the multiformats CID +// helper it uses does not load under jest's module resolution. Nothing here is +// about CID inflation, so it is stubbed to a passthrough. +jest.mock('@atproto/api', () => ({ + ...jest.requireActual('@atproto/api'), + jsonToLex: (value: unknown) => value, +})) + +import {type AtpAgent} from '@atproto/api' + +import {CustomFeedAPI} from '#/lib/api/feed/custom' +import {toPostView, toSpaceFeedPage} from '#/lib/api/space-views' + +const FEED = 'at://did:plc:community/app.bsky.feed.generator/private' +const SPACE = 'at://did:plc:community/space/community.blacksky.feed/private' +const POST = `${SPACE}/did:plc:alice/app.bsky.feed.post/3kaaa` + +const config = { + $type: 'community.blacksky.feed.config', + contentType: 'communityRecord', + visibility: 'gated', + group: 'at://did:plc:community/app.bsky.graph.list/members', + createdAt: '2026-08-18T00:00:00.000Z', + space: SPACE, +} + +type FakeAgent = { + did?: string + fetchHandler: jest.Mock + app: {bsky: {feed: {getFeed: jest.Mock}}} + com: {atproto: {repo: {getRecord: jest.Mock}}} +} + +function agent({did}: {did?: string}): FakeAgent { + const getFeed = jest.fn() + const fetchHandler = jest.fn((path: string) => { + if (path.includes('community.blacksky.feed.getSpaceFeed')) { + return Promise.resolve( + new Response( + JSON.stringify({ + cursor: '2026-08-18T00:00:00.000Z::bafyone', + feed: [ + { + post: { + $type: 'community.blacksky.feed.defs#spacePostView', + uri: POST, + cid: 'bafyone', + author: {did: 'did:plc:alice', handle: 'alice.test'}, + record: {$type: 'app.bsky.feed.post', text: 'hi'}, + indexedAt: '2026-08-18T00:00:00.000Z', + communitySpace: SPACE, + }, + }, + ], + }), + {status: 200, headers: {'content-type': 'application/json'}}, + ), + ) + } + throw new Error(`unexpected request: ${path}`) + }) + return { + did, + fetchHandler, + app: {bsky: {feed: {getFeed}}}, + com: { + atproto: { + repo: { + getRecord: jest.fn(() => Promise.resolve({data: {value: config}})), + }, + }, + }, + } +} + +// The feed APIs take a real `AtpAgent`; only the four members above are +// reachable on this path, so the fake is narrowed rather than filled in. +const asAgent = (a: FakeAgent) => a as unknown as AtpAgent + +describe('space-backed feed routing', () => { + it('reads a space feed through the private endpoint and never the standard one', async () => { + const a = agent({did: 'did:plc:alice'}) + const api = new CustomFeedAPI({agent: asAgent(a), feedParams: {feed: FEED}}) + + const page = await api.fetch({cursor: undefined, limit: 30}) + + expect(a.app.bsky.feed.getFeed).not.toHaveBeenCalled() + expect(page.feed).toHaveLength(1) + // The real space record URI survives: every later interaction (like, + // delete, permalink, thread) targets it. + expect(page.feed[0].post.uri).toBe(POST) + expect(page.feed[0].post.$type).toBe('app.bsky.feed.defs#postView') + }) + + it('peekLatest uses the same endpoint, so polling agrees with pagination', async () => { + const a = agent({did: 'did:plc:alice'}) + const api = new CustomFeedAPI({agent: asAgent(a), feedParams: {feed: FEED}}) + + await api.peekLatest() + + expect(a.app.bsky.feed.getFeed).not.toHaveBeenCalled() + expect(a.fetchHandler).toHaveBeenCalled() + }) + + it('refuses logged out rather than falling back to the public appview', async () => { + const a = agent({}) + const api = new CustomFeedAPI({agent: asAgent(a), feedParams: {feed: FEED}}) + + await expect(api.fetch({cursor: undefined, limit: 30})).rejects.toThrow( + 'FeedSignedInOnly', + ) + await expect(api.peekLatest()).rejects.toThrow('FeedSignedInOnly') + expect(a.fetchHandler).not.toHaveBeenCalled() + }) +}) + +describe('private view type mapping', () => { + it('renames the whole tree, quote embeds included', () => { + const page = toSpaceFeedPage({ + feed: [ + { + post: { + $type: 'community.blacksky.feed.defs#spacePostView', + uri: POST, + cid: 'bafyone', + author: {did: 'did:plc:alice'}, + record: {}, + indexedAt: '2026-08-18T00:00:00.000Z', + embed: { + $type: 'community.blacksky.feed.defs#spaceRecordView', + record: { + $type: 'community.blacksky.feed.defs#spaceViewRecord', + uri: POST, + }, + }, + }, + }, + ], + }) + const embed = page.feed[0].post.embed as unknown as Record< + string, + Record + > + expect(embed.$type).toBe('app.bsky.embed.record#view') + expect(embed.record.$type).toBe('app.bsky.embed.record#viewRecord') + // A space URI is carried through untouched; nothing parses it. + expect(embed.record.uri).toBe(POST) + }) + + it('drops a structurally invalid row instead of the whole page', () => { + const page = toSpaceFeedPage({feed: [{post: {}}, {nope: true}]}) + expect(page.feed).toEqual([]) + expect(toPostView({uri: 42})).toBeUndefined() + }) +}) diff --git a/dev-env/group-invite-fixture.ts b/dev-env/group-invite-fixture.ts new file mode 100644 index 000000000..570add77f --- /dev/null +++ b/dev-env/group-invite-fixture.ts @@ -0,0 +1,314 @@ +export type GroupInviteFixtureScenario = + | 'mixed' + | 'read-only' + | 'no-post' + | 'zero-readable' + | 'missing' + | 'unavailable' + | 'expired' + | 'consumed' + | 'capacity' + | 'auth-required' + | 'preview-outage' + | 'accept-outage' + | 'malformed-success' + | 'capability-outage' + | 'misconfigured' + | 'rate-limit' + | 'resumable' + | 'existing-unpinned' + | 'pin-update' + | 'pin-add' + | 'navigation' + | 'rapid' + +/** + * These values are deliberately synthetic and only exist in the local E2E + * fixture. They are long enough to exercise the production router's code + * validation without putting invite material in UI selectors or logs. + */ +const fixtureCode = (name: string) => `e2e-${name}`.padEnd(43, 'x') + +export const GROUP_INVITE_FIXTURE_CODES: Record< + GroupInviteFixtureScenario, + string +> = { + mixed: fixtureCode('mixed'), + 'read-only': fixtureCode('read-only'), + 'no-post': fixtureCode('no-post'), + 'zero-readable': fixtureCode('zero-readable'), + missing: fixtureCode('missing'), + unavailable: fixtureCode('unavailable'), + expired: fixtureCode('expired'), + consumed: fixtureCode('consumed'), + capacity: fixtureCode('capacity'), + 'auth-required': fixtureCode('auth-required'), + 'preview-outage': fixtureCode('preview-outage'), + 'accept-outage': fixtureCode('accept-outage'), + 'malformed-success': fixtureCode('malformed-success'), + 'capability-outage': fixtureCode('capability-outage'), + misconfigured: fixtureCode('misconfigured'), + 'rate-limit': fixtureCode('rate-limit'), + resumable: fixtureCode('resumable'), + 'existing-unpinned': fixtureCode('existing-unpinned'), + 'pin-update': fixtureCode('pin-update'), + 'pin-add': fixtureCode('pin-add'), + navigation: fixtureCode('navigation'), + rapid: fixtureCode('rapid'), +} + +export type GroupInviteFixtureFeed = { + uri: string + name: string + canView: boolean + canPost: boolean +} + +type InviteRecord = { + claimedDid?: string + grantCompleted: boolean + malformedResponseReturned: boolean + capabilityOutageReturned: boolean +} + +export type GroupInviteFixtureResponse = { + status: number + body: Record +} + +export type GroupInviteFixtureState = { + scenario: GroupInviteFixtureScenario + previewRequests: number + acceptRequests: number + acceptRequestsWithBearer: number + claimCount: number + grantCompleted: boolean + claimantCount: number + visibleFeedCount: number + inaccessibleFeedCount: number +} + +const ERROR_STATUS = { + InviteUnavailable: {status: 400, code: 'BAD_REQUEST'}, + GroupAtCapacity: {status: 409, code: 'CONFLICT'}, + AuthenticationRequired: {status: 401, code: 'UNAUTHORIZED'}, + AuthorizationUnavailable: {status: 503, code: 'SERVICE_UNAVAILABLE'}, + InviteMisconfigured: {status: 500, code: 'INTERNAL_SERVER_ERROR'}, + RateLimitExceeded: {status: 429, code: 'TOO_MANY_REQUESTS'}, +} as const + +function success(data: unknown): GroupInviteFixtureResponse { + return { + status: 200, + body: {result: {data: {json: data}}}, + } +} + +function failure( + stableCode: keyof typeof ERROR_STATUS, +): GroupInviteFixtureResponse { + const transport = ERROR_STATUS[stableCode] + return { + status: transport.status, + body: { + error: { + json: { + message: stableCode, + data: {code: transport.code}, + }, + }, + }, + } +} + +function isBearerAuthorization(value: string | undefined) { + return /^Bearer\s+\S+$/.test(value ?? '') +} + +export class GroupInviteFixture { + private readonly communityName = 'Test Community' + private readonly groupName = 'members' + private communityDid = 'did:plc:e2e-community' + private feeds: GroupInviteFixtureFeed[] = [] + private record: InviteRecord = this.newRecord() + private previewRequestCount = 0 + private acceptRequestCount = 0 + private acceptRequestsWithBearer = 0 + private claimCount = 0 + private claimants = new Set() + private scenario: GroupInviteFixtureScenario + + constructor(scenario: GroupInviteFixtureScenario = 'mixed') { + this.scenario = scenario + } + + configure({ + scenario, + communityDid, + feeds, + }: { + scenario: GroupInviteFixtureScenario + communityDid: string + feeds: GroupInviteFixtureFeed[] + }) { + this.scenario = scenario + this.communityDid = communityDid + this.feeds = feeds + this.record = this.newRecord() + this.previewRequestCount = 0 + this.acceptRequestCount = 0 + this.acceptRequestsWithBearer = 0 + this.claimCount = 0 + this.claimants = new Set() + + if (scenario === 'consumed') { + this.record.claimedDid = 'did:plc:e2e-consumed-by-other' + this.record.grantCompleted = true + this.claimants.add(this.record.claimedDid) + } + } + + get inviteCode() { + return GROUP_INVITE_FIXTURE_CODES[this.scenario] + } + + get visibleFeedUris() { + return this.responseFeeds().map(feed => feed.uri) + } + + get allFeedUris() { + return this.feeds.map(feed => feed.uri) + } + + preview(code: string): GroupInviteFixtureResponse { + this.previewRequestCount += 1 + + if (code !== this.inviteCode) return failure('InviteUnavailable') + if ( + this.scenario === 'unavailable' || + this.scenario === 'expired' || + this.scenario === 'consumed' || + this.scenario === 'missing' + ) { + return failure('InviteUnavailable') + } + if (this.scenario === 'preview-outage') { + return failure('AuthorizationUnavailable') + } + if (this.scenario === 'misconfigured') { + return failure('InviteMisconfigured') + } + + return success({ + community: {did: this.communityDid, name: this.communityName}, + group: {name: this.groupName, displayName: 'Members'}, + expiresAt: new Date(Date.now() + 86_400_000).toISOString(), + }) + } + + accept({ + code, + authorization, + memberDid, + }: { + code: string + authorization?: string + memberDid?: string + }): GroupInviteFixtureResponse { + this.acceptRequestCount += 1 + if (isBearerAuthorization(authorization)) { + this.acceptRequestsWithBearer += 1 + } + + if (code !== this.inviteCode) return failure('InviteUnavailable') + if (!isBearerAuthorization(authorization) || !memberDid) { + return failure('AuthenticationRequired') + } + if (this.scenario === 'auth-required') { + return failure('AuthenticationRequired') + } + if (this.scenario === 'accept-outage') { + return failure('AuthorizationUnavailable') + } + if (this.scenario === 'misconfigured') { + return failure('InviteMisconfigured') + } + if (this.scenario === 'rate-limit') { + return failure('RateLimitExceeded') + } + if (this.scenario === 'capacity') { + return failure('GroupAtCapacity') + } + if (this.record.claimedDid && this.record.claimedDid !== memberDid) { + return failure('InviteUnavailable') + } + + if (!this.record.claimedDid) { + this.record.claimedDid = memberDid + this.claimCount += 1 + this.claimants.add(memberDid) + this.record.grantCompleted = true + } + + if ( + this.scenario === 'malformed-success' && + !this.record.malformedResponseReturned + ) { + this.record.malformedResponseReturned = true + return success({membership: 'joined', feeds: 'malformed'}) + } + if ( + this.scenario === 'capability-outage' && + !this.record.capabilityOutageReturned + ) { + this.record.capabilityOutageReturned = true + return failure('AuthorizationUnavailable') + } + + return success({ + communityDid: this.communityDid, + groupName: this.groupName, + membership: 'joined', + feeds: this.responseFeeds(), + }) + } + + getState(): GroupInviteFixtureState { + return { + scenario: this.scenario, + previewRequests: this.previewRequestCount, + acceptRequests: this.acceptRequestCount, + acceptRequestsWithBearer: this.acceptRequestsWithBearer, + claimCount: this.claimCount, + grantCompleted: this.record.grantCompleted, + claimantCount: this.claimants.size, + visibleFeedCount: this.responseFeeds().length, + inaccessibleFeedCount: this.feeds.filter(feed => !feed.canView).length, + } + } + + private responseFeeds() { + if (this.scenario === 'zero-readable') return [] + if (this.scenario === 'read-only' || this.scenario === 'no-post') { + return this.feeds.filter(feed => feed.canView && !feed.canPost) + } + return this.feeds.filter(feed => feed.canView) + } + + private newRecord(): InviteRecord { + return { + grantCompleted: false, + malformedResponseReturned: false, + capabilityOutageReturned: false, + } + } +} + +export function isGroupInviteFixtureScenario( + value: string | string[] | undefined, +): value is GroupInviteFixtureScenario { + return ( + typeof value === 'string' && + Object.prototype.hasOwnProperty.call(GROUP_INVITE_FIXTURE_CODES, value) + ) +} diff --git a/dev-env/mock-server.ts b/dev-env/mock-server.ts index 12f5bb7ed..efbe41ad0 100644 --- a/dev-env/mock-server.ts +++ b/dev-env/mock-server.ts @@ -1,13 +1,233 @@ import {createServer as createHTTPServer} from 'node:http' import {parse} from 'node:url' +import { + GroupInviteFixture, + type GroupInviteFixtureFeed, + type GroupInviteFixtureScenario, + isGroupInviteFixtureScenario, +} from './group-invite-fixture.ts' import {createServer, type TestPDS} from './test-pds.ts' let server: TestPDS + +const GROUP_INVITE_COMMUNITY_DID = 'did:plc:e2e-community' + +async function ensureGroupInviteUsers(testPds: TestPDS) { + for (const name of ['alice', 'bob']) { + if (!testPds.mocker.users[name]) { + await testPds.mocker.createUser(name) + } + } +} + +async function seedGroupInviteFixture( + testPds: TestPDS, + scenario: GroupInviteFixtureScenario, +) { + await ensureGroupInviteUsers(testPds) + + const post = await testPds.mocker.createPost( + 'alice', + 'Synthetic group invite feed post', + ) + const postUris = [post.uri] + const readOnly = await testPds.mocker.createFeed( + 'alice', + 'e2e-group-read', + postUris, + ) + const postable = await testPds.mocker.createFeed( + 'alice', + 'e2e-group-post', + postUris, + ) + const inaccessible = await testPds.mocker.createFeed( + 'alice', + 'e2e-group-hidden', + postUris, + ) + + const feeds: GroupInviteFixtureFeed[] = [ + { + uri: readOnly.uri, + name: 'Read only feed', + canView: scenario !== 'zero-readable', + canPost: false, + }, + { + uri: postable.uri, + name: 'Postable feed', + canView: scenario !== 'zero-readable', + canPost: true, + }, + { + uri: inaccessible.uri, + name: 'Inaccessible feed', + canView: false, + canPost: false, + }, + ] + + const fixture = new GroupInviteFixture(scenario) + fixture.configure({ + scenario, + communityDid: GROUP_INVITE_COMMUNITY_DID, + feeds, + }) + testPds.groupInviteFixture = fixture + + if ( + scenario === 'existing-unpinned' || + scenario === 'pin-update' || + scenario === 'pin-add' + ) { + await testPds.mocker.users.alice.agent.overwriteSavedFeeds([ + {id: readOnly.uri, type: 'feed', value: readOnly.uri, pinned: false}, + ]) + } + + // Ensure the local AppView has indexed the feed-generator records before a + // client can navigate to one from the invite dialog. + await testPds.mocker.testNet.processAll() +} + +function decodeServiceAuthIssuer(authorization: string | undefined) { + if (!authorization || !/^Bearer\s+\S+$/.test(authorization)) { + return undefined + } + const token = authorization.split(/\s+/)[1] + const payload = token?.split('.')[1] + if (!payload) return undefined + try { + const parsed = JSON.parse( + Buffer.from(payload, 'base64url').toString('utf8'), + ) as {iss?: unknown; sub?: unknown} + if (typeof parsed.iss === 'string') return parsed.iss + if (typeof parsed.sub === 'string') return parsed.sub + } catch { + // The fixture intentionally treats an undecodable token as unauthenticated. + } + return undefined +} + +async function readRequestBody(req: import('node:http').IncomingMessage) { + const chunks: Buffer[] = [] + for await (const chunk of req) { + chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)) + } + return Buffer.concat(chunks).toString('utf8') +} + +function sendJson( + res: import('node:http').ServerResponse, + status: number, + body: Record, +) { + res.writeHead(status, {'content-type': 'application/json'}) + res.end(JSON.stringify(body)) +} + +function inputCode(value: unknown) { + if (!value || typeof value !== 'object') return undefined + const wrapped = (value as {json?: unknown}).json + const input = wrapped && typeof wrapped === 'object' ? wrapped : value + const code = (input as {code?: unknown}).code + return typeof code === 'string' ? code : undefined +} + +async function handleGroupInviteRequest( + req: import('node:http').IncomingMessage, + res: import('node:http').ServerResponse, + procedure: 'preview' | 'accept', + query: Record, +) { + const fixture = server?.groupInviteFixture + if (!fixture) { + sendJson(res, 503, { + error: { + json: { + message: 'AuthorizationUnavailable', + data: {code: 'SERVICE_UNAVAILABLE'}, + }, + }, + }) + return + } + + let input: unknown + if (req.method === 'GET') { + const rawInput = query.input + if (typeof rawInput === 'string') { + try { + input = JSON.parse(rawInput) + } catch { + input = undefined + } + } + } else { + try { + input = JSON.parse(await readRequestBody(req)) + } catch { + input = undefined + } + } + + const code = inputCode(input) ?? '' + const result = + procedure === 'preview' + ? fixture.preview(code) + : fixture.accept({ + code, + authorization: + typeof req.headers.authorization === 'string' + ? req.headers.authorization + : undefined, + memberDid: decodeServiceAuthIssuer( + typeof req.headers.authorization === 'string' + ? req.headers.authorization + : undefined, + ), + }) + sendJson(res, result.status, result.body) +} + +async function handleGroupInviteState(res: import('node:http').ServerResponse) { + const fixture = server?.groupInviteFixture + if (!fixture) { + sendJson(res, 404, {error: 'No group invite fixture is active'}) + return + } + const fixtureState = fixture.getState() + const savedFeeds = await server.mocker.getSavedFeedSummary( + 'alice', + fixture.visibleFeedUris, + fixture.allFeedUris, + ) + sendJson(res, 200, {...fixtureState, savedFeeds}) +} + // eslint-disable-next-line @typescript-eslint/no-misused-promises createHTTPServer(async (req, res) => { const url = parse(req.url || '/', true) - if (req.method !== 'POST') { + const pathname = url.pathname || '/' + if (pathname === '/__e2e/group-invite/state' && req.method === 'GET') { + try { + await handleGroupInviteState(res) + } catch { + sendJson(res, 503, {error: 'Unable to read fixture state'}) + } + return + } + if (pathname === '/api/trpc/groupInvites.preview') { + await handleGroupInviteRequest(req, res, 'preview', url.query) + return + } + if (pathname === '/api/trpc/groupInvites.accept') { + await handleGroupInviteRequest(req, res, 'accept', url.query) + return + } + if (req.method !== 'POST' || pathname !== '/') { return res.writeHead(200).end() } try { @@ -18,6 +238,14 @@ createHTTPServer(async (req, res) => { server = await createServer({inviteRequired}) console.log('Listening at', server.pdsUrl) if (url?.query) { + const requestedGroupInvite = url.query.groupInvite + if ( + typeof requestedGroupInvite === 'string' && + isGroupInviteFixtureScenario(requestedGroupInvite) + ) { + console.log('Generating group invite fixture') + await seedGroupInviteFixture(server, requestedGroupInvite) + } if ('users' in url.query) { console.log('Generating mock users') await server.mocker.createUser('alice') @@ -97,8 +325,8 @@ createHTTPServer(async (req, res) => { await server.mocker.follow('alice', 'bob') await server.mocker.follow('alice', 'carla') console.log('Generating mock posts') - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let posts: Record = { + + let posts: Record = { alice: [], bob: [], carla: [], @@ -501,6 +729,13 @@ createHTTPServer(async (req, res) => { JSON.stringify({ pdsUrl: server.pdsUrl, appviewDid: server.appviewDid, + groupInvite: server.groupInviteFixture + ? { + scenario: server.groupInviteFixture.getState().scenario, + code: server.groupInviteFixture.inviteCode, + acornUrl: 'http://localhost:1986', + } + : undefined, }), ) } catch (e) { diff --git a/dev-env/test-pds.ts b/dev-env/test-pds.ts index 669686886..f0590194e 100644 --- a/dev-env/test-pds.ts +++ b/dev-env/test-pds.ts @@ -1,4 +1,5 @@ import fs from 'node:fs' +import http from 'node:http' import net from 'node:net' import path from 'node:path' @@ -13,10 +14,19 @@ export interface TestUser { agent: BskyAgent } +export type SavedFeedSummary = { + total: number + pinned: number + visible: number + visiblePinned: number + inaccessible: number +} + export interface TestPDS { appviewDid: string pdsUrl: string mocker: Mocker + groupInviteFixture?: import('./group-invite-fixture.ts').GroupInviteFixture close: () => Promise } @@ -58,30 +68,103 @@ class StringIdGenerator { const ids = new StringIdGenerator() +type PdsProxy = { + close: () => Promise +} + +function sendJson( + res: http.ServerResponse, + status: number, + body: Record, +) { + res.writeHead(status, {'content-type': 'application/json'}) + res.end(JSON.stringify(body)) +} + +async function createPdsProxy( + port: number, + pdsTarget: string, +): Promise { + const server = http.createServer((req, res) => { + const pathname = new URL(req.url || '/', `http://${req.headers.host}`) + .pathname + const upstreamUrl = new URL(req.url || '/', pdsTarget) + const headers: http.OutgoingHttpHeaders = { + ...req.headers, + host: upstreamUrl.host, + } + if ( + pathname === '/xrpc/app.bsky.actor.getPreferences' || + pathname === '/xrpc/app.bsky.actor.putPreferences' + ) { + delete headers['atproto-proxy'] + } + const upstream = http.request( + upstreamUrl, + {method: req.method, headers}, + upstreamRes => { + res.writeHead(upstreamRes.statusCode || 502, upstreamRes.headers) + upstreamRes.pipe(res) + }, + ) + upstream.on('error', () => { + if (!res.headersSent) { + sendJson(res, 502, { + error: 'UpstreamUnavailable', + message: 'PDS unavailable', + }) + } else { + res.destroy() + } + }) + req.pipe(upstream) + }) + await new Promise((resolve, reject) => { + server.once('error', reject) + server.listen(port, 'localhost', resolve) + }) + return { + close: () => + new Promise((resolve, reject) => { + server.close(error => (error ? reject(error) : resolve())) + }), + } +} + export async function createServer( {inviteRequired}: {inviteRequired: boolean} = { inviteRequired: false, }, ): Promise { - const port = 3000 - const port2 = await getPort(port + 1) - const port3 = await getPort(port2 + 1) - const pdsUrl = `http://localhost:${port}` + const publicPdsPort = 3000 + const pdsPort = await getPort(publicPdsPort + 1) + const plcPort = await getPort(pdsPort + 1) + const bskyPort = await getPort(plcPort + 1) + const pdsUrl = `http://localhost:${publicPdsPort}` const id = ids.next() - const testNet = await TestNetwork.create({ pds: { - port, + port: pdsPort, hostname: 'localhost', inviteRequired, }, bsky: { dbPostgresSchema: `bsky_${id}`, - port: port3, + port: bskyPort, publicUrl: 'http://localhost:2584', }, - plc: {port: port2}, + plc: {port: plcPort}, }) + let pdsProxy: PdsProxy + try { + pdsProxy = await createPdsProxy( + publicPdsPort, + `http://localhost:${pdsPort}`, + ) + } catch (error) { + await testNet.close() + throw error + } // DISABLED - looks like dev-env added this and now it conflicts // add the test mod authority @@ -120,6 +203,7 @@ export async function createServer( pdsUrl, mocker: new Mocker(testNet, pdsUrl, pic), async close() { + await pdsProxy.close() await testNet.close() }, } @@ -351,6 +435,34 @@ class Mocker { ) } + async getSavedFeedSummary( + user: string, + visibleUris: readonly string[], + allUris: readonly string[], + ): Promise { + const agent = this.users[user]?.agent + if (!agent) { + throw new Error(`Not a user: ${user}`) + } + const preferences = await agent.getPreferences() + const savedFeeds = preferences.savedFeeds.filter( + feed => feed.type === 'feed', + ) + const visible = new Set(visibleUris) + const all = new Set(allUris) + return { + total: savedFeeds.length, + pinned: savedFeeds.filter(feed => feed.pinned).length, + visible: savedFeeds.filter(feed => visible.has(feed.value)).length, + visiblePinned: savedFeeds.filter( + feed => visible.has(feed.value) && feed.pinned, + ).length, + inaccessible: savedFeeds.filter( + feed => all.has(feed.value) && !visible.has(feed.value), + ).length, + } + } + async labelAccount(label: string, user: string) { const did = this.users[user]?.did if (!did) { diff --git a/docs/testing.md b/docs/testing.md index 763b267eb..2bf329e34 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -21,8 +21,29 @@ You will need to allow your device access to the port that the mock server is ru ``` adb reverse tcp:3000 tcp:3000 +adb reverse tcp:1986 tcp:1986 +adb reverse tcp:8082 tcp:8082 ``` +### Group invite Maestro suite + +The production-shaped group invite flows live in +`__e2e__/flows/group-invite/`. They reset the existing dev-env manager with a +scenario-specific local fixture and use real local feed-generator records. +Point the client at that fixture while starting Metro; the value is read by +the app at runtime and does not change the existing build commands. + +```sh +EXPO_PUBLIC_ACORN_SERVICE_URL=http://localhost:1986 pnpm e2e:start +EXPO_PUBLIC_ACORN_SERVICE_URL=http://localhost:1986 pnpm e2e:run __e2e__/flows/group-invite +``` + +Build the E2E app once with the existing `pnpm e2e:build` command. The local +fixture checks that accept requests carry a Bearer header, but it does not +validate the production service-auth signature. A disposable real Acorn, +OpenFGA, and feed-service journey is still required for that enforcement +boundary. + ### Running Maestro tests - In one tab, run `pnpm e2e:mock-server` @@ -30,6 +51,7 @@ adb reverse tcp:3000 tcp:3000 - In a third tab, run `pnpm e2e:run __e2e__` ## Using Flashlight for Performance Testing + 1. Make sure Maestro is installed (optional: only for automated testing) by following the instructions above 2. Install Flashlight by following [these instructions](https://docs.flashlight.dev/) 3. The simplest way to get started is by running `pnpm perf:measure` which will run a live preview of the performance test results. You can [see a demo here](https://github.com/bamlab/flashlight/assets/4534323/4038a342-f145-4c3b-8cde-17949bf52612) diff --git a/eslint-suppressions.json b/eslint-suppressions.json index 68dfa075a..8b0fb9df9 100644 --- a/eslint-suppressions.json +++ b/eslint-suppressions.json @@ -856,7 +856,7 @@ }, "src/lib/hooks/useIntentHandler.ts": { "@typescript-eslint/no-floating-promises": { - "count": 2 + "count": 1 } }, "src/lib/hooks/useNonReactiveCallback.ts": { diff --git a/jest/jestSetup.js b/jest/jestSetup.js index ca04d5426..402bb09eb 100644 --- a/jest/jestSetup.js +++ b/jest/jestSetup.js @@ -106,3 +106,8 @@ jest.mock('expo-modules-core', () => ({ jest.mock('expo-localization', () => ({ getLocales: () => [], })) + +// Lingui throws on any `t` outside an activated locale, so a message string is +// unreachable in tests until one is set — including the guard messages. +const {i18n} = require('@lingui/core') +i18n.loadAndActivate({locale: 'en', messages: {}}) diff --git a/package.json b/package.json index d13487e37..fb1e99fff 100644 --- a/package.json +++ b/package.json @@ -66,9 +66,9 @@ "lint-native:fix": "swiftlint --fix ./modules && ktlint --format ./modules", "typecheck": "tsgo --project ./tsconfig.check.json", "e2e:mock-server": "cd dev-env && pnpm start", - "e2e:build": "EXPO_PUBLIC_ENV=e2e NODE_ENV=test RN_SRC_EXT=e2e.ts,e2e.tsx expo run:ios", - "e2e:build-android": "EXPO_PUBLIC_ENV=e2e NODE_ENV=test RN_SRC_EXT=e2e.ts,e2e.tsx expo run:android", - "e2e:start": "EXPO_PUBLIC_ENV=e2e NODE_ENV=test RN_SRC_EXT=e2e.ts,e2e.tsx expo start -c --port 8082", + "e2e:build": "EXPO_PUBLIC_ENV=e2e EXPO_PUBLIC_ACORN_SERVICE_URL=http://localhost:1986 NODE_ENV=test RN_SRC_EXT=e2e.ts,e2e.tsx expo run:ios", + "e2e:build-android": "EXPO_PUBLIC_ENV=e2e EXPO_PUBLIC_ACORN_SERVICE_URL=http://localhost:1986 NODE_ENV=test RN_SRC_EXT=e2e.ts,e2e.tsx expo run:android", + "e2e:start": "EXPO_PUBLIC_ENV=e2e EXPO_PUBLIC_ACORN_SERVICE_URL=http://localhost:1986 NODE_ENV=test RN_SRC_EXT=e2e.ts,e2e.tsx expo start -c --port 8082", "e2e:run": "maestro test", "perf:test": "NODE_ENV=test maestro test", "perf:test:run": "NODE_ENV=test maestro test __e2e__/perf-test.yml", diff --git a/src/Navigation.tsx b/src/Navigation.tsx index e1f93e2a6..5bfbc7e8d 100644 --- a/src/Navigation.tsx +++ b/src/Navigation.tsx @@ -44,7 +44,11 @@ import { type State, } from '#/lib/routes/types' import {bskyTitle} from '#/lib/strings/headings' -import {CHAT_INVITE_CODE_REGEX} from '#/lib/strings/url-helpers' +import { + CHAT_INVITE_CODE_REGEX, + getDeepLinkAnalyticsTarget, + GROUP_INVITE_CODE_REGEX, +} from '#/lib/strings/url-helpers' import {useUnreadNotifications} from '#/state/queries/notifications/unread' import {useSession} from '#/state/session' import {useLoggedOutViewControls} from '#/state/shell/logged-out' @@ -849,7 +853,11 @@ const LINKING = { // react-navigation strips the `bluesky://` prefix and passes the path // without a leading slash, so normalize before matching. const normalizedPath = path.startsWith('/') ? path : `/${path}` - if (CHAT_INVITE_CODE_REGEX.test(normalizedPath.split('?')[0])) { + const pathWithoutQuery = normalizedPath.split('?')[0] + if ( + CHAT_INVITE_CODE_REGEX.test(pathWithoutQuery) || + GROUP_INVITE_CODE_REGEX.test(pathWithoutQuery) + ) { if (IS_NATIVE) { return buildStateObject('HomeTab', 'Home', params) } @@ -1033,7 +1041,7 @@ function RoutesContainer({children}: React.PropsWithChildren<{}>) { const referrerInfo = Referrer.getReferrerInfo() if (referrerInfo && referrerInfo.hostname !== 'bsky.app') { ax.metric('deepLink:referrerReceived', { - to: window.location.href, + to: getDeepLinkAnalyticsTarget(window.location.href), referrer: referrerInfo?.referrer, hostname: referrerInfo?.hostname, }) diff --git a/src/analytics/metrics/types.ts b/src/analytics/metrics/types.ts index 794908e50..3390d314b 100644 --- a/src/analytics/metrics/types.ts +++ b/src/analytics/metrics/types.ts @@ -57,6 +57,7 @@ export type Events = { | 'Deactivated' | 'Takendown' | 'AgeAssuranceNoAccessScreen' + | 'GroupInvite' scope: 'current' | 'every' } // OAuth session lifecycle. These are silent client-side events used to @@ -682,6 +683,19 @@ export type Events = { } 'groupchat:inviteLink:redeem': {} + // Group invite deep links + 'groupInvite:opened': { + hasSession: boolean + } + 'groupInvite:signInRequested': {} + 'groupInvite:acceptAttempted': {} + 'groupInvite:joined': { + hasPosting: boolean + } + 'groupInvite:failure': { + errorName: string + } + // Group chat user interactions 'groupchat:message:send': { convoId: string diff --git a/src/components/CommunityOnlyBadge.tsx b/src/components/CommunityOnlyBadge.tsx index 5ecc0a8a2..a3d94c931 100644 --- a/src/components/CommunityOnlyBadge.tsx +++ b/src/components/CommunityOnlyBadge.tsx @@ -7,19 +7,25 @@ import {Trans} from '@lingui/react/macro' import {Logo as BlackskyLogo} from '#/view/icons/Logo' import {atoms as a, useTheme} from '#/alf' import {ChevronBottom_Stroke2_Corner0_Rounded as ChevronDown} from '#/components/icons/Chevron' +import {Group3_Stroke2_Corner0_Rounded as GroupIcon} from '#/components/icons/Group' import * as Tooltip from '#/components/Tooltip' import {Text} from '#/components/Typography' -const COMMUNITY_POST_COLLECTION = 'community.blacksky.feed.post' - -export function isCommunityPostUri(uri: string | undefined): boolean { - return !!uri && uri.includes(COMMUNITY_POST_COLLECTION) -} - -export function CommunityOnlyBadge() { +export function CommunityOnlyBadge({ + communitySpace, +}: { + communitySpace?: string +}) { const t = useTheme() const {_} = useLingui() const [visible, setVisible] = useState(false) + const isTenant = !!communitySpace + const label = isTenant + ? _(msg`Community-only post`) + : _(msg`Blacksky-only post`) + const hint = isTenant + ? _(msg`Only visible to members of this community`) + : _(msg`Only visible to members of the Blacksky community`) useEffect(() => { return () => setVisible(false) @@ -33,10 +39,8 @@ export function CommunityOnlyBadge() { setVisible(v => !v)} style={[ a.flex_row, @@ -47,19 +51,33 @@ export function CommunityOnlyBadge() { a.rounded_full, {backgroundColor: t.palette.primary_500}, ]}> - + {isTenant ? ( + + ) : ( + + )} - + - Blacksky Only + {isTenant ? ( + Community Only + ) : ( + Blacksky Only + )} - - This post is only visible to members of the Blacksky community. - + {isTenant ? ( + + This post is only visible to members of its community. + + ) : ( + + This post is only visible to members of the Blacksky community. + + )} diff --git a/src/components/Dialog/index.tsx b/src/components/Dialog/index.tsx index bd23e566a..bec939b0a 100644 --- a/src/components/Dialog/index.tsx +++ b/src/components/Dialog/index.tsx @@ -396,9 +396,11 @@ export function FlatListFooter({ export function Handle({ difference = false, fill, + testID, }: { difference?: boolean fill?: string + testID?: string }) { const t = useTheme() const {_} = useLingui() @@ -408,6 +410,7 @@ export function Handle({ return ( close()} accessibilityLabel={_(msg`Dismiss`)} diff --git a/src/components/Dialog/index.web.tsx b/src/components/Dialog/index.web.tsx index 37c893be1..879d008f4 100644 --- a/src/components/Dialog/index.web.tsx +++ b/src/components/Dialog/index.web.tsx @@ -321,7 +321,7 @@ export function Close() { ) } -export function Handle() { +export function Handle(_props?: {testID?: string}) { return null } diff --git a/src/components/Post/Embed/index.tsx b/src/components/Post/Embed/index.tsx index 914ffc65c..2fe377379 100644 --- a/src/components/Post/Embed/index.tsx +++ b/src/components/Post/Embed/index.tsx @@ -4,14 +4,13 @@ import { type $Typed, type AppBskyFeedDefs, AppBskyFeedPost, - AtUri, moderatePost, RichText as RichTextAPI, } from '@atproto/api' import {Trans} from '@lingui/react/macro' import {useQueryClient} from '@tanstack/react-query' -import {makeProfileLink} from '#/lib/routes/links' +import {postPermalink} from '#/lib/routes/links' import {getChatInviteCodeFromUrl} from '#/lib/strings/url-helpers' import {useModerationOpts} from '#/state/preferences/moderation-opts' import {useEmbedFallback} from '#/state/queries/embed-fallback' @@ -326,12 +325,7 @@ export function QuoteEmbed({ const t = useTheme() const queryClient = useQueryClient() - const itemUrip = new AtUri(quote.uri) - const isCommunityQuote = - itemUrip.collection === 'community.blacksky.feed.post' - const itemHref = isCommunityQuote - ? `${makeProfileLink(quote.author, 'post', itemUrip.rkey)}?collection=${itemUrip.collection}` - : makeProfileLink(quote.author, 'post', itemUrip.rkey) + const itemHref = postPermalink(quote.author, quote.uri) const itemTitle = `Post by ${quote.author.handle}` const richText = useMemo(() => { diff --git a/src/components/PostControls/PostMenu/PostMenuItems.tsx b/src/components/PostControls/PostMenu/PostMenuItems.tsx index 8b0c4651c..a7f700074 100644 --- a/src/components/PostControls/PostMenu/PostMenuItems.tsx +++ b/src/components/PostControls/PostMenu/PostMenuItems.tsx @@ -17,8 +17,10 @@ import {plural} from '@lingui/core/macro' import {useLingui} from '@lingui/react/macro' import {useNavigation} from '@react-navigation/native' +import {getCommunitySpaceUri} from '#/lib/api/community-post' +import {isSpaceRecordUri} from '#/lib/api/space-uri' import {getCurrentRoute} from '#/lib/routes/helpers' -import {makeProfileLink} from '#/lib/routes/links' +import {makeProfileLink, postPermalink} from '#/lib/routes/links' import { type CommonNavigatorParams, type NavigationProp, @@ -162,7 +164,8 @@ let PostMenuItems = ({ [postUri], ) const {data: peerModPerms} = useMyPeerModPermissions() - const canLabelPost = !!peerModPerms?.isPeerMod && isCommunityPost + const canLabelPost = + !!peerModPerms?.isPeerMod && isCommunityPost && !getCommunitySpaceUri(post) const [isThreadMuted, muteThread, unmuteThread] = useThreadMuteMutationQueue( post, rootUri, @@ -175,6 +178,10 @@ let PostMenuItems = ({ }) const isReplyHiddenByThreadgate = threadgateHiddenReplies.has(postUri) const isPinned = post.viewer?.pinned + // Pinning writes the post's URI into the public profile record, so a space + // post cannot be pinned: the URI alone publishes that the private post + // exists, and who wrote it. + const canPin = !isSpaceRecordUri(postUri) const {mutateAsync: toggleQuoteDetachment, isPending: isDetachPending} = useToggleQuoteDetachmentMutation() @@ -188,10 +195,7 @@ let PostMenuItems = ({ }) const href = useMemo(() => { - const urip = new AtUri(postUri) - const link = makeProfileLink(postAuthor, 'post', urip.rkey) - const isCommunity = urip.collection === 'community.blacksky.feed.post' - return isCommunity ? `${link}?collection=${urip.collection}` : link + return postPermalink(postAuthor, postUri) }, [postUri, postAuthor]) const onDeletePost = () => { @@ -491,7 +495,7 @@ let PostMenuItems = ({ return ( <> - {isAuthor && ( + {isAuthor && canPin && ( <> { - const urip = new AtUri(postUri) - const link = makeProfileLink(postAuthor, 'post', urip.rkey) - const isCommunity = urip.collection === 'community.blacksky.feed.post' - return isCommunity ? `${link}?collection=${urip.collection}` : link + return postPermalink(postAuthor, postUri) }, [postUri, postAuthor]) const hideInPWI = useMemo(() => { diff --git a/src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx b/src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx index 963c5bb04..ad10bcafd 100644 --- a/src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx +++ b/src/components/PostControls/ShareMenu/ShareMenuItems.web.tsx @@ -1,11 +1,10 @@ import {memo, useMemo} from 'react' -import {AtUri} from '@atproto/api' import {msg} from '@lingui/core/macro' import {useLingui} from '@lingui/react' import {Trans} from '@lingui/react/macro' import {useNavigation} from '@react-navigation/native' -import {makeProfileLink} from '#/lib/routes/links' +import {postPermalink} from '#/lib/routes/links' import {type NavigationProp} from '#/lib/routes/types' import {shareText, shareUrl} from '#/lib/sharing' import {toShareUrl} from '#/lib/strings/url-helpers' @@ -45,10 +44,7 @@ let ShareMenuItems = ({ const postAuthor = useProfileShadow(post.author) const href = useMemo(() => { - const urip = new AtUri(postUri) - const link = makeProfileLink(postAuthor, 'post', urip.rkey) - const isCommunity = urip.collection === 'community.blacksky.feed.post' - return isCommunity ? `${link}?collection=${urip.collection}` : link + return postPermalink(postAuthor, postUri) }, [postUri, postAuthor]) const hideInPWI = useMemo(() => { diff --git a/src/components/PostControls/ShareMenu/index.tsx b/src/components/PostControls/ShareMenu/index.tsx index 6464d0dd3..7d9536818 100644 --- a/src/components/PostControls/ShareMenu/index.tsx +++ b/src/components/PostControls/ShareMenu/index.tsx @@ -4,13 +4,12 @@ import { type AppBskyFeedDefs, type AppBskyFeedPost, type AppBskyFeedThreadgate, - AtUri, type RichText as RichTextAPI, } from '@atproto/api' import {msg} from '@lingui/core/macro' import {useLingui} from '@lingui/react' -import {makeProfileLink} from '#/lib/routes/links' +import {postPermalink} from '#/lib/routes/links' import {shareUrl} from '#/lib/sharing' import {toShareUrl} from '#/lib/strings/url-helpers' import {type Shadow} from '#/state/cache/post-shadow' @@ -85,10 +84,7 @@ let ShareMenuButton = ({ const onNativeLongPress = () => { ax.metric('share:press:nativeShare', {}) - const urip = new AtUri(post.uri) - const link = makeProfileLink(post.author, 'post', urip.rkey) - const isCommunity = urip.collection === 'community.blacksky.feed.post' - const href = isCommunity ? `${link}?collection=${urip.collection}` : link + const href = postPermalink(post.author, post.uri) const url = toShareUrl(href) shareUrl(url) onShare() diff --git a/src/components/PostControls/index.tsx b/src/components/PostControls/index.tsx index 240a4256c..47c1a70e8 100644 --- a/src/components/PostControls/index.tsx +++ b/src/components/PostControls/index.tsx @@ -9,6 +9,10 @@ import { import {plural} from '@lingui/core/macro' import {useLingui} from '@lingui/react/macro' +import { + getCommunitySpaceUri, + isCommunityPostUri, +} from '#/lib/api/community-post' import {CountWheel} from '#/lib/custom-animations/CountWheel' import {AnimatedLikeIcon} from '#/lib/custom-animations/LikeIcon' import {useOpenComposer} from '#/lib/hooks/useOpenComposer' @@ -24,10 +28,7 @@ import { useProgressGuideControls, } from '#/state/shell/progress-guide' import {atoms as a, useBreakpoints, useTheme} from '#/alf' -import { - CommunityOnlyBadge, - isCommunityPostUri, -} from '#/components/CommunityOnlyBadge' +import {CommunityOnlyBadge} from '#/components/CommunityOnlyBadge' import {Reply as Bubble} from '#/components/icons/Reply' import {useFormatPostStatCount} from '#/components/PostControls/util' import * as Skele from '#/components/Skeleton' @@ -267,7 +268,7 @@ let PostControls = ({ onQuote={onQuote} big={big} embeddingDisabled={Boolean(post.viewer?.embeddingDisabled)} - repostDisabled={post.uri.includes('community.blacksky.feed.post')} + repostDisabled={isCommunityPostUri(post.uri)} /> @@ -323,7 +324,9 @@ let PostControls = ({ a.align_center, secondaryControlSpacingStyles, ]}> - {isCommunityPostUri(post.uri) && } + {isCommunityPostUri(post.uri) && ( + + )} { - const actual = jest.requireActual('react-native') - - Object.defineProperty(actual.Platform, 'OS', { - value: 'ios', - configurable: true, - }) - Object.defineProperty(actual.Platform, 'Version', { - value: '17.0', - configurable: true, - }) - - return actual -}) - -jest.mock('react-native-uitextview', () => { - const React = require('react') - const {Text: RNText} = require('react-native') - - return { - UITextView: jest.fn(({children, ...props}) => ( - - {children} - - )), - } -}) - -describe('Text', () => { - it('renders non-selectable text without UITextView', () => { - const {getByText, queryByTestId} = render(Normal text) - - expect(getByText('Normal text')).toBeTruthy() - expect(queryByTestId('ui-text-view')).toBeNull() - }) - - it('uses UITextView for selectable iOS text', () => { - const {getByTestId} = render(Selectable text) - - expect(getByTestId('ui-text-view')).toBeTruthy() - }) - - it('does not nest UITextView inside selectable emoji text', () => { - const {getAllByTestId, getByText} = render( - - 😀 popular post - , - ) - - expect(getByText('😀 popular post')).toBeTruthy() - expect(getAllByTestId('ui-text-view')).toHaveLength(1) - }) - - it('still allows native Text children inside non-selectable text', () => { - const {getByText, queryByTestId} = render( - - Nested text - , - ) - - expect(getByText('Nested text')).toBeTruthy() - expect(queryByTestId('ui-text-view')).toBeNull() - }) -}) diff --git a/src/components/forms/Toggle/index.tsx b/src/components/forms/Toggle/index.tsx index a62a82b62..8bca96ead 100644 --- a/src/components/forms/Toggle/index.tsx +++ b/src/components/forms/Toggle/index.tsx @@ -72,6 +72,7 @@ export type GroupProps = React.PropsWithChildren<{ }> export type ItemProps = ViewStyleProp & { + testID?: string type?: 'radio' | 'checkbox' name: string label: string diff --git a/src/components/hooks/useLandingEntry.native.ts b/src/components/hooks/useLandingEntry.native.ts index c5950a646..5a7558be6 100644 --- a/src/components/hooks/useLandingEntry.native.ts +++ b/src/components/hooks/useLandingEntry.native.ts @@ -6,7 +6,10 @@ import { createStarterPackLinkFromAndroidReferrer, httpStarterPackUriToAtUri, } from '#/lib/strings/starter-pack' -import {CHAT_INVITE_CODE_REGEX} from '#/lib/strings/url-helpers' +import { + CHAT_INVITE_CODE_REGEX, + GROUP_INVITE_CODE_REGEX, +} from '#/lib/strings/url-helpers' import {useHasCheckedForStarterPack} from '#/state/preferences/used-starter-packs' import { useSetActiveLanding, @@ -38,6 +41,18 @@ export function useLandingEntry() { setReady(true) return } + const groupInviteMatch = urlp.pathname.match(GROUP_INVITE_CODE_REGEX) + if (groupInviteMatch) { + setActiveLanding({ + type: 'groupinvite', + // The code is sufficient to resume this flow. Do not retain the + // bearer-bearing URL in landing state across auth transitions. + uri: '', + code: groupInviteMatch[1], + }) + setReady(true) + return + } } // On Android, we cannot clear the referral link. It gets stored for 90 days and all we can do is query for it. So, diff --git a/src/components/intents/GroupInviteDialog.tsx b/src/components/intents/GroupInviteDialog.tsx new file mode 100644 index 000000000..80104d896 --- /dev/null +++ b/src/components/intents/GroupInviteDialog.tsx @@ -0,0 +1,502 @@ +import {useCallback, useEffect, useRef, useState} from 'react' +import {View} from 'react-native' +import {Trans, useLingui} from '@lingui/react/macro' +import {useNavigation} from '@react-navigation/native' + +import { + isGroupInviteE2EFailure, + maybeFailGroupInviteE2E, +} from '#/lib/api/group-invite-e2e' +import { + getDefaultGroupInviteFeedUris, + getFirstSelectedGroupInviteFeed, + getGroupInviteFeedMutations, + getGroupInviteMembershipCopy, + getGroupInviteNoPostCopy, + groupInviteErrorCopy, + groupInviteFailureName, + shouldOpenGroupInviteFeedAfterPinning, + shouldResetGroupInvitePinning, + shouldTrackGroupInviteOpened, + summarizeGroupInviteFeeds, +} from '#/lib/api/group-invite-ui' +import { + type GroupInviteAcceptance, + GroupInviteClientError, + GroupInviteError, +} from '#/lib/api/group-invites' +import {type NavigationProp} from '#/lib/routes/types' +import {logger} from '#/logger' +import { + useAcceptGroupInviteMutation, + useGroupInvitePreviewQuery, +} from '#/state/queries/group-invites' +import { + useAddSavedFeedsMutation, + usePreferencesQuery, + useUpdateSavedFeedsMutation, +} from '#/state/queries/preferences' +import {useSessionApi} from '#/state/session' +import {useSetActiveLanding} from '#/state/shell/landing' +import {useLoggedOutViewControls} from '#/state/shell/logged-out' +import {useSetSelectedFeed} from '#/state/shell/selected-feed' +import {atoms as a, useTheme, web} from '#/alf' +import {Button, ButtonText} from '#/components/Button' +import * as Dialog from '#/components/Dialog' +import * as Toggle from '#/components/forms/Toggle' +import {Loader} from '#/components/Loader' +import {Text} from '#/components/Typography' +import {useAnalytics} from '#/analytics' +import {useIntentDialogs} from './IntentDialogs' + +export function GroupInviteDialog() { + const {groupInviteDialogControl, groupInviteState, setGroupInviteState} = + useIntentDialogs() + return ( + setGroupInviteState(undefined)} + nativeOptions={{preventExpansion: true}}> + + + + + ) +} + +export function GroupInviteDialogContent({code}: {code?: string}) { + const {t: l} = useLingui() + const ax = useAnalytics() + const t = useTheme() + const navigation = useNavigation() + const {groupInviteDialogControl} = useIntentDialogs() + const {logoutCurrentAccount} = useSessionApi() + const {requestSwitchToAccount} = useLoggedOutViewControls() + const setActiveLanding = useSetActiveLanding() + const { + data: preview, + error: previewError, + isPending: isPreviewPending, + refetch: refetchPreview, + } = useGroupInvitePreviewQuery(code) + const { + mutateAsync: acceptInvite, + isPending: isAcceptPending, + error: acceptError, + reset: resetAccept, + } = useAcceptGroupInviteMutation() + const {mutateAsync: addSavedFeeds} = useAddSavedFeedsMutation() + const {mutateAsync: updateSavedFeeds} = useUpdateSavedFeedsMutation() + const preferencesQuery = usePreferencesQuery() + const {data: preferences} = preferencesQuery + const savedFeeds = preferences?.savedFeeds + const preferencesReady = preferencesQuery.isSuccess + const setSelectedFeed = useSetSelectedFeed() + const [acceptance, setAcceptance] = useState() + const [selectedFeedUris, setSelectedFeedUris] = useState([]) + const [hasPinned, setHasPinned] = useState(false) + const [pinError, setPinError] = useState<'pinning' | 'navigation'>() + const [isPinning, setIsPinning] = useState(false) + const reportedPreviewError = useRef(undefined) + const acceptingRef = useRef(false) + + useEffect(() => { + if (code && shouldTrackGroupInviteOpened(code)) { + ax.metric('groupInvite:opened', {hasSession: true}) + } + }, [ax, code]) + + useEffect(() => { + if (!previewError || reportedPreviewError.current === previewError) return + reportedPreviewError.current = previewError + ax.metric('groupInvite:failure', { + errorName: groupInviteFailureName(previewError), + }) + }, [ax, previewError]) + + const openSelectedFeed = useCallback(() => { + if (!acceptance) return + const feed = getFirstSelectedGroupInviteFeed( + acceptance.feeds, + new Set(selectedFeedUris), + ) + if (!feed?.uri) return + maybeFailGroupInviteE2E('navigation') + setSelectedFeed(`feedgen|${feed.uri}`) + groupInviteDialogControl.close() + navigation.navigate('HomeTab') + }, [ + acceptance, + groupInviteDialogControl, + navigation, + selectedFeedUris, + setSelectedFeed, + ]) + + const pinAndOpen = useCallback(async () => { + if (!acceptance || isPinning || !preferencesReady) return + const selectedUris = new Set(selectedFeedUris) + const {readable} = summarizeGroupInviteFeeds(acceptance.feeds) + const selectedReadable = readable.filter( + feed => feed.uri && selectedUris.has(feed.uri), + ) + if (selectedReadable.length === 0) return + + setIsPinning(true) + try { + const {toAdd, toUpdate} = getGroupInviteFeedMutations( + acceptance.feeds, + savedFeeds, + selectedUris, + ) + if (toUpdate.length) { + maybeFailGroupInviteE2E('saved-feed-update') + await updateSavedFeeds(toUpdate) + } + if (toAdd.length) { + maybeFailGroupInviteE2E('saved-feed-add') + await addSavedFeeds(toAdd) + } + setHasPinned(true) + setPinError(undefined) + if ( + shouldOpenGroupInviteFeedAfterPinning(acceptance.feeds, selectedUris) + ) { + openSelectedFeed() + } + } catch (error) { + setPinError( + isGroupInviteE2EFailure(error, 'navigation') ? 'navigation' : 'pinning', + ) + ax.metric('groupInvite:failure', { + errorName: isGroupInviteE2EFailure(error, 'navigation') + ? 'NavigationFailed' + : 'PinningFailed', + }) + logger.error('Failed to complete group invite feed setup', { + errorName: isGroupInviteE2EFailure(error, 'navigation') + ? 'NavigationFailed' + : 'PinningFailed', + }) + } finally { + setIsPinning(false) + } + }, [ + acceptance, + addSavedFeeds, + ax, + openSelectedFeed, + isPinning, + selectedFeedUris, + updateSavedFeeds, + savedFeeds, + preferencesReady, + ]) + + const reauthenticate = useCallback(() => { + if (!code) return + setActiveLanding({type: 'groupinvite', uri: '', code}) + groupInviteDialogControl.close() + logoutCurrentAccount('GroupInvite') + requestSwitchToAccount({requestedAccount: 'groupinvite'}) + }, [ + code, + groupInviteDialogControl, + logoutCurrentAccount, + requestSwitchToAccount, + setActiveLanding, + ]) + + const onAccept = async () => { + if (!code || !preview || acceptingRef.current || isAcceptPending) return + acceptingRef.current = true + resetAccept() + setPinError(undefined) + setHasPinned(false) + try { + ax.metric('groupInvite:acceptAttempted', {}) + const result = await acceptInvite({ + code, + communityDid: preview.community.did, + }) + setAcceptance(result) + setSelectedFeedUris(getDefaultGroupInviteFeedUris(result.feeds)) + ax.metric('groupInvite:joined', { + hasPosting: result.feeds.some(feed => feed.canView && feed.canPost), + }) + } catch (error) { + ax.metric('groupInvite:failure', { + errorName: groupInviteFailureName(error), + }) + logger.info('Group invite acceptance failed', { + errorName: groupInviteFailureName(error), + }) + } finally { + acceptingRef.current = false + } + } + + const error = previewError || acceptError + const isPending = isPreviewPending || isAcceptPending + const onSelectedFeedUrisChange = useCallback( + (nextUris: string[]) => { + if ( + hasPinned && + shouldResetGroupInvitePinning(selectedFeedUris, nextUris) + ) { + setHasPinned(false) + setPinError(undefined) + } + setSelectedFeedUris(nextUris) + }, + [hasPinned, selectedFeedUris], + ) + + return ( + + + {isPending && !preview ? ( + + ) : error ? ( + { + if (previewError) void refetchPreview() + else if ( + acceptError instanceof GroupInviteClientError && + acceptError.code === GroupInviteError.AuthenticationRequired + ) + reauthenticate() + else void onAccept() + }} + /> + ) : preview ? ( + <> + + + Group invite + + + {preview.group.displayName} + + + {preview.community.name} + + + {acceptance ? ( + void preferencesQuery.refetch()} + onPinAndOpen={() => void pinAndOpen()} + onOpenFeed={() => { + try { + openSelectedFeed() + } catch { + setPinError('navigation') + ax.metric('groupInvite:failure', { + errorName: 'NavigationFailed', + }) + } + }} + /> + ) : ( + + )} + + ) : null} + + + ) +} + +function AcceptedState({ + acceptance, + pinError, + hasPinned, + isPinning, + selectedFeedUris, + onSelectedFeedUrisChange, + preferencesPending, + preferencesError, + onRetryPreferences, + onPinAndOpen, + onOpenFeed, +}: { + acceptance: GroupInviteAcceptance + pinError: 'pinning' | 'navigation' | undefined + hasPinned: boolean + isPinning: boolean + selectedFeedUris: string[] + onSelectedFeedUrisChange: (uris: string[]) => void + preferencesPending: boolean + preferencesError: boolean + onRetryPreferences: () => void + onPinAndOpen: () => void + onOpenFeed: () => void +}) { + const {t: l} = useLingui() + const readable = acceptance.feeds.filter(feed => feed.canView) + const membershipCopy = getGroupInviteMembershipCopy(acceptance.feeds) + const hasSelectedReadable = readable.some( + feed => feed.uri && selectedFeedUris.includes(feed.uri), + ) + return ( + + + You joined {acceptance.groupName}. + + {readable.length > 0 ? ( + + {readable.map((feed, index) => { + const capability = feed.canPost ? 'Post + read' : 'Read only' + const label = `${feed.name} — ${capability}` + return ( + + + {label} + + ) + })} + + ) : null} + {membershipCopy && ( + + {membershipCopy} + + )} + {preferencesPending && ( + + Loading your saved feeds… + + )} + {preferencesError && ( + + )} + {readable.length === 0 && ( + + {getGroupInviteNoPostCopy()} + + )} + {readable.length > 0 && !hasPinned && ( + + )} + {pinError === 'pinning' && ( + + )} + {pinError === 'navigation' && ( + + )} + {hasPinned && hasSelectedReadable && ( + + )} + + ) +} + +function InviteErrorState({ + message, + onRetry, + retryLabel, + testID, + retryTestID, +}: { + message: string + onRetry: () => void + retryLabel?: string + testID?: string + retryTestID?: string +}) { + const {t: l} = useLingui() + return ( + + {message} + + + ) +} diff --git a/src/components/intents/IntentDialogs.tsx b/src/components/intents/IntentDialogs.tsx index 76809b366..9a712272c 100644 --- a/src/components/intents/IntentDialogs.tsx +++ b/src/components/intents/IntentDialogs.tsx @@ -7,15 +7,18 @@ import { useState, } from 'react' +import {usePrefetchGroupInvitePreview} from '#/state/queries/group-invites' import {usePrefetchJoinLinkPreviews} from '#/state/queries/join-links' import {useSession} from '#/state/session' import { useActiveGroupChatJoinRequest, + useActiveGroupInvite, useSetActiveLanding, } from '#/state/shell/landing' import * as Dialog from '#/components/Dialog' import {type DialogControlProps} from '#/components/Dialog' import {GroupChatJoinDialog} from '#/components/intents/GroupChatJoinDialog' +import {GroupInviteDialog} from '#/components/intents/GroupInviteDialog' import {VerifyEmailIntentDialog} from '#/components/intents/VerifyEmailIntentDialog' interface Context { @@ -25,6 +28,9 @@ interface Context { groupChatJoinDialogControl: DialogControlProps groupChatJoinState: {code: string} | undefined setGroupChatJoinState: (state: {code: string} | undefined) => void + groupInviteDialogControl: DialogControlProps + groupInviteState: {code: string} | undefined + setGroupInviteState: (state: {code: string} | undefined) => void } const Context = createContext({} as Context) @@ -40,12 +46,19 @@ export function Provider({children}: {children: React.ReactNode}) { const [groupChatJoinState, setGroupChatJoinState] = useState< {code: string} | undefined >() + const groupInviteDialogControl = Dialog.useDialogControl() + const [groupInviteState, setGroupInviteState] = useState< + {code: string} | undefined + >() const {hasSession} = useSession() const groupChatLanding = useActiveGroupChatJoinRequest() + const groupInviteLanding = useActiveGroupInvite() const setActiveLanding = useSetActiveLanding() const prefetchJoinLinkPreviews = usePrefetchJoinLinkPreviews() + const prefetchGroupInvitePreview = usePrefetchGroupInvitePreview() const landingHandledRef = useRef(false) + const groupInviteLandingHandledRef = useRef(false) useEffect(() => { if (hasSession && groupChatLanding && !landingHandledRef.current) { @@ -67,6 +80,26 @@ export function Provider({children}: {children: React.ReactNode}) { if (!groupChatLanding) { landingHandledRef.current = false } + if ( + hasSession && + groupInviteLanding && + !groupInviteLandingHandledRef.current + ) { + groupInviteLandingHandledRef.current = true + const code = groupInviteLanding.code + setActiveLanding(undefined) + const prefetch = prefetchGroupInvitePreview(code) + void Promise.race([ + prefetch, + new Promise(res => setTimeout(res, 200)), + ]).finally(() => { + setGroupInviteState({code}) + groupInviteDialogControl.open() + }) + } + if (!groupInviteLanding) { + groupInviteLandingHandledRef.current = false + } }, [ hasSession, groupChatLanding, @@ -74,6 +107,10 @@ export function Provider({children}: {children: React.ReactNode}) { setGroupChatJoinState, prefetchJoinLinkPreviews, groupChatJoinDialogControl, + groupInviteLanding, + prefetchGroupInvitePreview, + groupInviteDialogControl, + setGroupInviteState, ]) const value = useMemo( @@ -84,6 +121,9 @@ export function Provider({children}: {children: React.ReactNode}) { groupChatJoinDialogControl, groupChatJoinState, setGroupChatJoinState, + groupInviteDialogControl, + groupInviteState, + setGroupInviteState, }), [ verifyEmailDialogControl, @@ -92,6 +132,9 @@ export function Provider({children}: {children: React.ReactNode}) { groupChatJoinDialogControl, groupChatJoinState, setGroupChatJoinState, + groupInviteDialogControl, + groupInviteState, + setGroupInviteState, ], ) @@ -100,6 +143,7 @@ export function Provider({children}: {children: React.ReactNode}) { {children} + ) } diff --git a/src/env/common.ts b/src/env/common.ts index 0318842f0..5a79e68eb 100644 --- a/src/env/common.ts +++ b/src/env/common.ts @@ -17,6 +17,7 @@ export const ENV: string = process.env.EXPO_PUBLIC_ENV as | 'production' | 'testflight' | 'development' + | 'staging' | 'e2e' | (string & {}) @@ -153,6 +154,21 @@ export const BRAND_SERVICE_URL: string = process.env.EXPO_PUBLIC_BRAND_SERVICE_URL || 'https://brand.acorn.blacksky.community' +/** Acorn Web endpoint for community invitation previews and acceptance. */ +export const ACORN_SERVICE_URL: string = + process.env.EXPO_PUBLIC_ACORN_SERVICE_URL || + (ENV === 'production' || ENV === 'testflight' + ? 'https://acorn.blacksky.community' + : ENV === 'e2e' + ? 'http://localhost:1986' + : ENV === 'staging' + ? (() => { + throw new Error( + 'EXPO_PUBLIC_ACORN_SERVICE_URL is required for staging builds', + ) + })() + : 'http://localhost:3000') + /** * Stripe publishable key for embedded checkout */ diff --git a/src/lib/api/__tests__/community-feed.test.ts b/src/lib/api/__tests__/community-feed.test.ts new file mode 100644 index 000000000..55380c4bb --- /dev/null +++ b/src/lib/api/__tests__/community-feed.test.ts @@ -0,0 +1,175 @@ +import {type AtpAgent, XRPCError} from '@atproto/api' + +import { + ADMIT_FEED_POST, + admitFeedPost, + CHECK_FEED_PERMISSIONS, + fetchCommunityFeedConfig, + fetchCommunityFeedConfigStrict, + fetchCommunityFeedTarget, + fetchFeedPermissions, + fetchFeedServiceDid, +} from '../community-feed' +import {getServiceAuthToken} from '../service-auth' + +jest.mock('../service-auth', () => ({ + getServiceAuthToken: jest.fn(), +})) + +const feed = 'at://did:plc:community/app.bsky.feed.generator/3m2communityfeed' +const serviceDid = 'did:web:feeds.example.com' +const config = { + $type: 'community.blacksky.feed.config', + contentType: 'publicRecord', + visibility: 'public', + policyMode: 'public', + group: 'at://did:plc:community/community.blacksky.group/community', + createdAt: '2026-08-06T12:00:00.000Z', +} as const + +function mockAgent() { + const getRecord = jest.fn(({collection}: {collection: string}) => { + if (collection === 'community.blacksky.feed.config') { + return Promise.resolve({data: {value: config}}) + } + return Promise.resolve({ + data: {value: {$type: collection, did: serviceDid}}, + }) + }) + const fetchHandler = jest.fn, [string, RequestInit?]>() + return { + agent: { + com: {atproto: {repo: {getRecord}}}, + fetchHandler, + } as unknown as AtpAgent, + fetchHandler, + getRecord, + } +} + +describe('community feed API', () => { + beforeEach(() => { + jest.mocked(getServiceAuthToken).mockReset() + jest.mocked(getServiceAuthToken).mockResolvedValue('service-token') + }) + + it('loads config and generator records from the feed owner at the same rkey', async () => { + const {agent, getRecord} = mockAgent() + + await expect(fetchCommunityFeedConfig(agent, feed)).resolves.toEqual(config) + await expect(fetchFeedServiceDid(agent, feed)).resolves.toBe(serviceDid) + + expect(getRecord).toHaveBeenNthCalledWith(1, { + repo: 'did:plc:community', + collection: 'community.blacksky.feed.config', + rkey: '3m2communityfeed', + }) + expect(getRecord).toHaveBeenNthCalledWith(2, { + repo: 'did:plc:community', + collection: 'app.bsky.feed.generator', + rkey: '3m2communityfeed', + }) + }) + + it('distinguishes an absent config from a failed config read', async () => { + const {agent, getRecord} = mockAgent() + getRecord.mockRejectedValueOnce(new XRPCError(400, 'RecordNotFound')) + + await expect( + fetchCommunityFeedConfigStrict(agent, feed), + ).resolves.toBeNull() + + getRecord.mockRejectedValueOnce(new XRPCError(503, 'UpstreamFailure')) + await expect(fetchCommunityFeedConfigStrict(agent, feed)).rejects.toThrow( + 'UpstreamFailure', + ) + }) + + it('checks self-scoped permissions with exact service auth and filters unknown values', async () => { + const {agent, fetchHandler} = mockAgent() + fetchHandler.mockResolvedValue( + new Response( + JSON.stringify({ + permissions: ['canView', 'futurePermission', 'canPost'], + }), + ), + ) + + await expect(fetchFeedPermissions(agent, feed)).resolves.toEqual([ + 'canView', + 'canPost', + ]) + expect(getServiceAuthToken).toHaveBeenCalledWith( + expect.objectContaining({ + agent, + aud: serviceDid, + lxm: CHECK_FEED_PERMISSIONS, + }), + ) + expect(fetchHandler).toHaveBeenCalledWith( + `/xrpc/${CHECK_FEED_PERMISSIONS}?feed=${encodeURIComponent(feed)}`, + { + headers: { + Authorization: 'Bearer service-token', + 'atproto-proxy': `${serviceDid}#bsky_fg`, + }, + }, + ) + }) + + it('fails closed when the permission service rejects the request', async () => { + const {agent, fetchHandler} = mockAgent() + fetchHandler.mockResolvedValue(new Response('{}', {status: 403})) + + await expect(fetchFeedPermissions(agent, feed)).resolves.toEqual([]) + }) + + it('resolves a post target only when the user can post', async () => { + const {agent, fetchHandler} = mockAgent() + fetchHandler.mockResolvedValue( + new Response(JSON.stringify({permissions: ['canView', 'canPost']})), + ) + + await expect(fetchCommunityFeedTarget(agent, feed)).resolves.toEqual({ + feed, + name: feed, + serviceDid, + config, + }) + }) + + it('fails closed when resolving a post target without canPost', async () => { + const {agent, fetchHandler} = mockAgent() + fetchHandler.mockResolvedValue( + new Response(JSON.stringify({permissions: ['canView']})), + ) + + await expect(fetchCommunityFeedTarget(agent, feed)).resolves.toBeNull() + }) + + it('admits a canonical record through the feed generator service', async () => { + const {agent, fetchHandler} = mockAgent() + fetchHandler.mockResolvedValue(new Response('{}')) + const post = 'at://did:plc:author/app.bsky.feed.post/3m2post' + + await admitFeedPost( + agent, + {feed, name: 'Community', serviceDid, config}, + post, + 'bafyrecordcid', + ) + + expect(getServiceAuthToken).toHaveBeenCalledWith( + expect.objectContaining({agent, aud: serviceDid, lxm: ADMIT_FEED_POST}), + ) + expect(fetchHandler).toHaveBeenCalledWith(`/xrpc/${ADMIT_FEED_POST}`, { + method: 'POST', + headers: { + Authorization: 'Bearer service-token', + 'Content-Type': 'application/json', + 'atproto-proxy': `${serviceDid}#bsky_fg`, + }, + body: JSON.stringify({feed, post, cid: 'bafyrecordcid'}), + }) + }) +}) diff --git a/src/lib/api/__tests__/community-post-uri.test.ts b/src/lib/api/__tests__/community-post-uri.test.ts new file mode 100644 index 000000000..1b1176e78 --- /dev/null +++ b/src/lib/api/__tests__/community-post-uri.test.ts @@ -0,0 +1,20 @@ +import {isCommunityPostUri} from '../community-post' + +const SPACE = 'at://did:plc:community/space/community.blacksky.feed/private' + +describe(isCommunityPostUri, () => { + it.each([ + ['a stub post', 'at://did:plc:alice/community.blacksky.feed.post/3kabc'], + ['a space post', `${SPACE}/did:plc:alice/app.bsky.feed.post/3kabc`], + ['a space like', `${SPACE}/did:plc:alice/app.bsky.feed.like/3klike`], + ])('treats %s as community content', (_name, uri) => { + expect(isCommunityPostUri(uri)).toBe(true) + }) + + it.each([undefined, 'at://did:plc:alice/app.bsky.feed.post/3kabc', SPACE])( + 'leaves public content alone: %p', + uri => { + expect(isCommunityPostUri(uri)).toBe(false) + }, + ) +}) diff --git a/src/lib/api/__tests__/community-post.test.ts b/src/lib/api/__tests__/community-post.test.ts new file mode 100644 index 000000000..775949210 --- /dev/null +++ b/src/lib/api/__tests__/community-post.test.ts @@ -0,0 +1,29 @@ +import {getCommunitySpaceUri} from '../community-post' + +const post = (communitySpace?: unknown) => + ({ + uri: 'at://did:plc:author/community.blacksky.feed.post/3m2post', + communitySpace, + }) as never + +describe(getCommunitySpaceUri, () => { + it('accepts a space URI', () => { + const space = 'at://did:plc:community/space/community.blacksky.feed/private' + + expect(getCommunitySpaceUri(post(space))).toBe(space) + }) + + it.each([ + undefined, + 42, + 'not-an-at-uri', + // A feed generator URI is not a space: the field names where content + // lives, and a feed is only a view over it. + 'at://did:plc:community/app.bsky.feed.generator/3m2communityfeed', + 'at://did:plc:community/community.blacksky.feed.config/3m2communityfeed', + // A record inside a space is not the space itself. + 'at://did:plc:c/space/community.blacksky.feed/main/did:plc:a/app.bsky.feed.post/3k', + ])('rejects absent or invalid space context: %p', communitySpace => { + expect(getCommunitySpaceUri(post(communitySpace))).toBeUndefined() + }) +}) diff --git a/src/lib/api/__tests__/community.test.ts b/src/lib/api/__tests__/community.test.ts index 28b2539f1..3ab2c7e8c 100644 --- a/src/lib/api/__tests__/community.test.ts +++ b/src/lib/api/__tests__/community.test.ts @@ -1,11 +1,23 @@ import {type BskyAgent} from '@atproto/api' +jest.mock('@atproto/api', () => ({ + ...jest.requireActual('@atproto/api'), + jsonToLex: (value: unknown) => value, +})) + import { BLUESKY_FALLBACK_PROXY_HEADER, BLUESKY_PROXY_HEADER, HOME_PROXY_HEADER, } from '#/lib/constants' -import {communityXrpc} from '../community' +import { + communityXrpc, + getSpacePostLikes, + getSpacePostQuotes, +} from '../community' + +const SPACE = 'at://did:plc:space/space/community.blacksky.feed/test' +const SPACE_POST = `${SPACE}/did:plc:alice/app.bsky.feed.post/3kpost` describe('communityXrpc', () => { const originalHeader = BLUESKY_PROXY_HEADER.get() @@ -34,4 +46,89 @@ describe('communityXrpc', () => { BLUESKY_FALLBACK_PROXY_HEADER, ) }) + + it('can target a configured content store', async () => { + const {agent, fetchHandler} = mockAgent() + + await communityXrpc(agent, 'community.blacksky.feed.submitPost', { + body: {text: 'hello'}, + serviceDid: 'did:web:content.example.com', + }) + + const init = fetchHandler.mock.calls[0][1] as { + headers: Record + } + expect(init.headers['atproto-proxy']).toBe( + 'did:web:content.example.com#bsky_appview', + ) + }) + + it('fetches space likes through the permission-aware endpoint', async () => { + const {agent, fetchHandler} = mockAgent() + fetchHandler.mockResolvedValue( + new Response( + JSON.stringify({ + uri: SPACE_POST, + cursor: 'next', + likes: [ + { + indexedAt: '2026-08-27T12:00:00.000Z', + createdAt: '2026-08-27T11:00:00.000Z', + actor: {did: 'did:plc:bob', handle: 'bob.test'}, + }, + ], + }), + ), + ) + + const page = await getSpacePostLikes(agent, { + uri: SPACE_POST, + limit: 30, + cursor: 'before', + }) + + expect(page.cursor).toBe('next') + expect(page.likes[0].actor.did).toBe('did:plc:bob') + expect(fetchHandler).toHaveBeenCalledWith( + expect.stringContaining( + '/xrpc/community.blacksky.feed.getSpacePostLikes?', + ), + expect.objectContaining({method: 'GET'}), + ) + const url = new URL(fetchHandler.mock.calls[0][0], 'https://example.test') + expect(Object.fromEntries(url.searchParams)).toEqual({ + uri: SPACE_POST, + limit: '30', + cursor: 'before', + }) + }) + + it('converts custom space quote views into standard renderer views', async () => { + const {agent, fetchHandler} = mockAgent() + fetchHandler.mockResolvedValue( + new Response( + JSON.stringify({ + cursor: 'next', + posts: [ + { + $type: 'community.blacksky.feed.defs#spacePostView', + uri: `${SPACE}/did:plc:bob/app.bsky.feed.post/3kquote`, + cid: 'bafyquote', + author: {did: 'did:plc:bob', handle: 'bob.test'}, + record: {$type: 'app.bsky.feed.post', text: 'quote'}, + indexedAt: '2026-08-27T12:00:00.000Z', + }, + ], + }), + ), + ) + + const page = await getSpacePostQuotes(agent, { + uri: SPACE_POST, + limit: 30, + }) + + expect(page.uri).toBe(SPACE_POST) + expect(page.posts[0].$type).toBe('app.bsky.feed.defs#postView') + }) }) diff --git a/src/lib/api/__tests__/group-invite-fixture.test.ts b/src/lib/api/__tests__/group-invite-fixture.test.ts new file mode 100644 index 000000000..2e235e43e --- /dev/null +++ b/src/lib/api/__tests__/group-invite-fixture.test.ts @@ -0,0 +1,132 @@ +import {describe, expect, it} from '@jest/globals' + +import { + GROUP_INVITE_FIXTURE_CODES, + GroupInviteFixture, +} from '../../../../dev-env/group-invite-fixture' + +const COMMUNITY = 'did:plc:e2e-community' +const FEEDS = [ + { + uri: 'at://did:plc:feed/app.bsky.feed.generator/read', + name: 'Read only feed', + canView: true, + canPost: false, + }, + { + uri: 'at://did:plc:feed/app.bsky.feed.generator/post', + name: 'Postable feed', + canView: true, + canPost: true, + }, + { + uri: 'at://did:plc:feed/app.bsky.feed.generator/hidden', + name: 'Inaccessible feed', + canView: false, + canPost: false, + }, +] + +function fixture( + scenario: ConstructorParameters[0] = 'mixed', +) { + const value = new GroupInviteFixture(scenario) + value.configure({scenario, communityDid: COMMUNITY, feeds: FEEDS}) + return value +} + +function bearerFor(did: string) { + return `Bearer ${did}` +} + +describe('group invite E2E fixture contract', () => { + it('returns the public preview envelope without invite material', () => { + const value = fixture() + const result = value.preview(value.inviteCode) + + expect(result).toMatchObject({status: 200}) + expect(result.body).toMatchObject({ + result: { + data: { + json: { + community: {did: COMMUNITY, name: 'Test Community'}, + group: {name: 'members', displayName: 'Members'}, + }, + }, + }, + }) + expect(JSON.stringify(result.body)).not.toContain(value.inviteCode) + }) + + it('requires Bearer auth and makes claims resumable for one DID only', () => { + const value = fixture('resumable') + const code = GROUP_INVITE_FIXTURE_CODES.resumable + + expect(value.accept({code}).status).toBe(401) + expect( + value.accept({ + code, + authorization: bearerFor('did:plc:alice'), + memberDid: 'did:plc:alice', + }), + ).toMatchObject({status: 200}) + expect( + value.accept({ + code, + authorization: bearerFor('did:plc:alice'), + memberDid: 'did:plc:alice', + }), + ).toMatchObject({status: 200}) + expect( + value.accept({ + code, + authorization: bearerFor('did:plc:bob'), + memberDid: 'did:plc:bob', + }), + ).toMatchObject({status: 400}) + + expect(value.getState()).toMatchObject({ + acceptRequests: 4, + acceptRequestsWithBearer: 3, + claimCount: 1, + claimantCount: 1, + }) + }) + + it('preserves adversarial feed order while omitting inaccessible feeds', () => { + const value = fixture() + const result = value.accept({ + code: value.inviteCode, + authorization: bearerFor('did:plc:alice'), + memberDid: 'did:plc:alice', + }) + const feeds = (result.body.result as {data: {json: {feeds: unknown[]}}}) + .data.json.feeds as Array<{name: string}> + + expect(feeds.map(feed => feed.name)).toEqual([ + 'Read only feed', + 'Postable feed', + ]) + expect(value.getState()).toMatchObject({ + visibleFeedCount: 2, + inaccessibleFeedCount: 1, + }) + }) + + it('retains membership when capability lookup fails and recovers on same-DID retry', () => { + const value = fixture('capability-outage') + const request = { + code: value.inviteCode, + authorization: bearerFor('did:plc:alice'), + memberDid: 'did:plc:alice', + } + + expect(value.accept(request).status).toBe(503) + expect(value.accept(request).status).toBe(200) + expect(value.getState()).toMatchObject({ + claimCount: 1, + grantCompleted: true, + acceptRequestsWithBearer: 2, + }) + }) +}) diff --git a/src/lib/api/__tests__/group-invite-ui.test.ts b/src/lib/api/__tests__/group-invite-ui.test.ts new file mode 100644 index 000000000..ab0d66426 --- /dev/null +++ b/src/lib/api/__tests__/group-invite-ui.test.ts @@ -0,0 +1,200 @@ +import {describe, expect, it} from '@jest/globals' + +import { + getDefaultGroupInviteFeedUris, + getFirstSelectedGroupInviteFeed, + getGroupInviteFeedMutations, + getGroupInviteMembershipCopy, + getGroupInviteNoPostCopy, + groupInviteErrorCopy, + groupInviteFailureName, + shouldOpenGroupInviteFeedAfterPinning, + shouldResetGroupInvitePinning, + shouldTrackGroupInviteOpened, + summarizeGroupInviteFeeds, +} from '../group-invite-ui' +import {GroupInviteClientError, GroupInviteError} from '../group-invites' + +describe('group invite UI state', () => { + it('uses friendly stable copy for backend failures', () => { + expect( + groupInviteErrorCopy( + new GroupInviteClientError(GroupInviteError.InviteUnavailable), + ), + ).toBe('This invite is no longer available.') + expect(groupInviteErrorCopy(new Error('database password'))).not.toContain( + 'database password', + ) + }) + + it('separates readable postable and read-only feeds', () => { + const result = summarizeGroupInviteFeeds([ + {uri: 'at://feed/post', name: 'Post', canView: true, canPost: true}, + {uri: 'at://feed/read', name: 'Read', canView: true, canPost: false}, + {uri: 'at://feed/hidden', name: 'Hidden', canView: false, canPost: false}, + ]) + expect(result.postable.map(feed => feed.uri)).toEqual(['at://feed/post']) + expect(result.readOnly.map(feed => feed.uri)).toEqual(['at://feed/read']) + expect(result.readable).not.toContainEqual( + expect.objectContaining({uri: 'at://feed/hidden'}), + ) + }) + + it('pins missing and previously saved-but-unpinned feeds without duplicating pinned feeds', () => { + const result = getGroupInviteFeedMutations( + [ + { + uri: 'at://feed/missing', + name: 'Missing', + canView: true, + canPost: true, + }, + {uri: 'at://feed/pinned', name: 'Pinned', canView: true, canPost: true}, + { + uri: 'at://feed/unpinned', + name: 'Unpinned', + canView: true, + canPost: false, + }, + { + uri: 'at://feed/hidden', + name: 'Hidden', + canView: false, + canPost: true, + }, + ], + [ + {id: '1', type: 'feed', value: 'at://feed/pinned', pinned: true}, + {id: '2', type: 'feed', value: 'at://feed/unpinned', pinned: false}, + ], + ) + expect(result.toAdd).toEqual([ + {type: 'feed', value: 'at://feed/missing', pinned: true}, + ]) + expect(result.toUpdate).toEqual([ + {id: '2', type: 'feed', value: 'at://feed/unpinned', pinned: true}, + ]) + }) + + it('defaults selection to accessible feeds and never includes hidden feeds', () => { + expect( + getDefaultGroupInviteFeedUris([ + {uri: 'at://feed/post', name: 'Post', canView: true, canPost: true}, + {uri: 'at://feed/read', name: 'Read', canView: true, canPost: false}, + { + uri: 'at://feed/hidden', + name: 'Hidden', + canView: false, + canPost: true, + }, + ]), + ).toEqual(['at://feed/post', 'at://feed/read']) + }) + + it('selects the first postable feed before an earlier readable fallback', () => { + const feeds = [ + {uri: 'at://feed/read', name: 'Read', canView: true, canPost: false}, + {uri: 'at://feed/post', name: 'Post', canView: true, canPost: true}, + ] + expect( + getFirstSelectedGroupInviteFeed( + feeds, + new Set(['at://feed/read', 'at://feed/post']), + )?.uri, + ).toBe('at://feed/post') + expect( + getFirstSelectedGroupInviteFeed(feeds, new Set(['at://feed/read']))?.uri, + ).toBe('at://feed/read') + }) + + it('opens a selected read-only feed after pinning when no postable feed is selected', () => { + expect( + shouldOpenGroupInviteFeedAfterPinning( + [ + {uri: 'at://feed/read', name: 'Read', canView: true, canPost: false}, + { + uri: 'at://feed/hidden', + name: 'Hidden', + canView: false, + canPost: false, + }, + ], + new Set(['at://feed/read']), + ), + ).toBe(true) + }) + + it('pins only selected accessible feeds', () => { + const result = getGroupInviteFeedMutations( + [ + { + uri: 'at://feed/selected', + name: 'Selected', + canView: true, + canPost: true, + }, + {uri: 'at://feed/other', name: 'Other', canView: true, canPost: false}, + { + uri: 'at://feed/hidden', + name: 'Hidden', + canView: false, + canPost: true, + }, + ], + [], + new Set(['at://feed/selected']), + ) + expect(result.toAdd).toEqual([ + {type: 'feed', value: 'at://feed/selected', pinned: true}, + ]) + }) + + it('uses the required membership copy for no-post and no-readable outcomes', () => { + expect( + getGroupInviteMembershipCopy([ + {uri: 'at://feed/read', name: 'Read', canView: true, canPost: false}, + ]), + ).toBe( + "You joined the group, but you don't currently have access to a feed you can post in. Please let your admins know if you think this is a mistake.", + ) + expect( + getGroupInviteMembershipCopy([ + { + uri: 'at://feed/hidden', + name: 'Hidden', + canView: false, + canPost: false, + }, + ]), + ).toBe('No feeds available.') + expect(getGroupInviteNoPostCopy()).toContain( + 'Please let your admins know if you think this is a mistake.', + ) + }) + + it('invalidates completed pinning when feed selection changes', () => { + expect( + shouldResetGroupInvitePinning(['at://feed/one'], ['at://feed/one']), + ).toBe(false) + expect( + shouldResetGroupInvitePinning(['at://feed/one'], ['at://feed/two']), + ).toBe(true) + }) + + it('returns only stable failure names for analytics', () => { + expect( + groupInviteFailureName( + new GroupInviteClientError(GroupInviteError.InviteMisconfigured), + ), + ).toBe('InviteMisconfigured') + expect(groupInviteFailureName(new Error('invite-code-secret'))).toBe( + 'Unknown', + ) + }) + + it('deduplicates opened analytics for the same invite', () => { + const code = `analytics-${Date.now()}-${Math.random()}` + expect(shouldTrackGroupInviteOpened(code)).toBe(true) + expect(shouldTrackGroupInviteOpened(code)).toBe(false) + }) +}) diff --git a/src/lib/api/__tests__/group-invites.test.ts b/src/lib/api/__tests__/group-invites.test.ts new file mode 100644 index 000000000..6e9ebfcde --- /dev/null +++ b/src/lib/api/__tests__/group-invites.test.ts @@ -0,0 +1,183 @@ +import {afterEach, beforeEach, describe, expect, it, jest} from '@jest/globals' + +import { + acceptGroupInvite, + GroupInviteError, + previewGroupInvite, +} from '../group-invites' +import {getServiceAuthToken} from '../service-auth' + +jest.mock('../service-auth', () => ({ + getServiceAuthToken: jest.fn(), +})) + +const mockGetServiceAuthToken = jest.mocked(getServiceAuthToken) +const fetchMock = jest.fn() +const CODE = 'a'.repeat(43) +const COMMUNITY_DID = 'did:plc:community' + +function response(body: unknown, ok = true, status = 200) { + return {ok, status, json: () => Promise.resolve(body)} as Response +} + +describe('group invite client API', () => { + beforeEach(() => { + global.fetch = fetchMock + fetchMock.mockReset() + mockGetServiceAuthToken.mockReset() + }) + + afterEach(() => { + jest.restoreAllMocks() + }) + + it('previews through the public Acorn tRPC query', async () => { + fetchMock.mockResolvedValue( + response({ + result: { + data: { + json: { + community: {did: COMMUNITY_DID, name: 'Test Community'}, + group: {name: 'members', displayName: 'Members'}, + expiresAt: new Date().toISOString(), + }, + }, + }, + }), + ) + + await expect(previewGroupInvite(CODE)).resolves.toEqual({ + community: {did: COMMUNITY_DID, name: 'Test Community'}, + group: {name: 'members', displayName: 'Members'}, + expiresAt: expect.any(String), + }) + expect(fetchMock).toHaveBeenCalledWith( + expect.not.stringContaining('?input='), + expect.objectContaining({ + method: 'POST', + body: JSON.stringify({code: CODE}), + }), + ) + }) + + it('requests method-bound service auth for the invite community and sends it', async () => { + mockGetServiceAuthToken.mockResolvedValue('service-token') + fetchMock.mockResolvedValue( + response({ + result: { + data: { + json: { + communityDid: COMMUNITY_DID, + groupName: 'members', + membership: 'joined', + feeds: [ + { + uri: 'at://feed/one', + name: 'One', + canView: true, + canPost: false, + }, + ], + }, + }, + }, + }), + ) + const agent = {} as Parameters[0]['agent'] + + await expect( + acceptGroupInvite({code: CODE, communityDid: COMMUNITY_DID, agent}), + ).resolves.toMatchObject({membership: 'joined'}) + expect(mockGetServiceAuthToken).toHaveBeenCalledWith( + expect.objectContaining({ + agent, + aud: COMMUNITY_DID, + lxm: 'community.blacksky.group.acceptInvite', + }), + ) + expect(fetchMock.mock.calls[0][1]).toEqual( + expect.objectContaining({ + method: 'POST', + headers: expect.objectContaining({ + Authorization: 'Bearer service-token', + }), + }), + ) + }) + + it('turns an expired-session service-auth response into reauthentication', async () => { + mockGetServiceAuthToken.mockRejectedValue({status: 401}) + + await expect( + acceptGroupInvite({ + code: CODE, + communityDid: COMMUNITY_DID, + agent: {} as Parameters[0]['agent'], + }), + ).rejects.toMatchObject({code: GroupInviteError.AuthenticationRequired}) + expect(fetchMock).not.toHaveBeenCalled() + }) + + it('normalizes stable Acorn errors without exposing raw server messages', async () => { + fetchMock.mockResolvedValue( + response( + { + error: { + json: { + data: {code: 'INVITE_UNAVAILABLE'}, + message: 'internal row details', + }, + }, + }, + false, + 410, + ), + ) + + await expect(previewGroupInvite(CODE)).rejects.toMatchObject({ + code: GroupInviteError.InviteUnavailable, + }) + }) + + it('prefers Acorn stable messages over generic tRPC transport codes', async () => { + fetchMock.mockResolvedValue( + response( + { + error: { + json: { + message: 'InviteMisconfigured', + data: {code: 'INTERNAL_SERVER_ERROR'}, + }, + }, + }, + false, + 500, + ), + ) + + await expect(previewGroupInvite(CODE)).rejects.toMatchObject({ + code: 'InviteMisconfigured', + }) + }) + + it('rejects a malformed successful acceptance payload as unavailable', async () => { + mockGetServiceAuthToken.mockResolvedValue('service-token') + fetchMock.mockResolvedValue( + response({ + result: { + data: { + json: {membership: 'joined', feeds: 'not-an-array'}, + }, + }, + }), + ) + + await expect( + acceptGroupInvite({ + code: CODE, + communityDid: COMMUNITY_DID, + agent: {} as Parameters[0]['agent'], + }), + ).rejects.toMatchObject({code: GroupInviteError.AuthorizationUnavailable}) + }) +}) diff --git a/src/lib/api/__tests__/post-routing.test.ts b/src/lib/api/__tests__/post-routing.test.ts new file mode 100644 index 000000000..f9af8adac --- /dev/null +++ b/src/lib/api/__tests__/post-routing.test.ts @@ -0,0 +1,258 @@ +import {type AtpAgent} from '@atproto/api' +import {type QueryClient} from '@tanstack/react-query' + +import {post, quotedSpace, resolveReply} from '../index' +import {postToSpace} from '../space-post' + +// `post()`'s module graph reaches the image picker, which pulls in native UI +// modules that cannot load under jest. Only the write routing is under test. +jest.mock('react-native-uuid', () => ({default: {v4: () => 'test-device-id'}})) +jest.mock('#/state/gallery', () => ({compressImage: jest.fn()})) +jest.mock('#/state/queries/resolve-link', () => ({ + fetchResolveGifQuery: jest.fn(), + fetchResolveLinkQuery: jest.fn(), +})) +jest.mock('#/state/queries/threadgate', () => ({ + createThreadgateRecord: jest.fn(), + threadgateAllowUISettingToAllowRecordValue: jest.fn(() => []), +})) + +jest.mock('../space-post', () => ({ + postToSpace: jest.fn(() => Promise.resolve({uris: ['at://space/post']})), +})) + +const SPACE = 'at://did:plc:community/space/community.blacksky.feed/private' + +const feedConfig = (space?: string) => ({ + $type: 'community.blacksky.feed.config', + contentType: 'communityRecord', + visibility: 'gated', + group: 'at://did:plc:community/community.blacksky.group/community', + createdAt: '2026-08-09T12:00:00.000Z', + ...(space ? {space} : {}), +}) + +const threadWith = (space?: string) => + ({ + posts: [], + postgate: {}, + threadgate: [], + blackskyOnly: false, + communityFeed: { + feed: 'at://did:plc:community/app.bsky.feed.generator/3m2feed', + name: 'Private', + serviceDid: 'did:web:feeds.example.com', + config: feedConfig(space), + }, + }) as never + +function mockAgent() { + const fetchHandler = jest.fn() + const applyWrites = jest.fn(() => Promise.resolve({})) + return { + agent: { + assertDid: 'did:plc:alice', + fetchHandler, + com: {atproto: {repo: {applyWrites}}}, + } as unknown as AtpAgent, + fetchHandler, + applyWrites, + } +} + +const queryClient = {invalidateQueries: jest.fn()} as unknown as QueryClient + +describe('post routing', () => { + beforeEach(() => jest.clearAllMocks()) + + it('sends a space-backed feed down the space write path', async () => { + const {agent, fetchHandler, applyWrites} = mockAgent() + + await post(agent, queryClient, {thread: threadWith(SPACE)}) + + expect(postToSpace).toHaveBeenCalledWith(agent, queryClient, SPACE, { + thread: threadWith(SPACE), + }) + // Nothing may reach the appview or the public repo on this path. + expect(fetchHandler).not.toHaveBeenCalled() + expect(applyWrites).not.toHaveBeenCalled() + }) + + it('leaves a feed without a space on the community path', async () => { + const {agent, applyWrites} = mockAgent() + + await post(agent, queryClient, {thread: threadWith(undefined)}) + + expect(postToSpace).not.toHaveBeenCalled() + expect(applyWrites).toHaveBeenCalled() + }) +}) + +describe('quoting a space post from outside the space', () => { + const SPACE_POST = `${SPACE}/did:plc:bob/app.bsky.feed.post/3kabc` + const permalink = `https://blacksky.community/profile/did:plc:bob/post/3kabc?space=${encodeURIComponent( + SPACE, + )}` + + const threadQuoting = (uri: string, space?: string) => + ({ + ...(threadWith(space) as object), + posts: [ + { + richtext: {text: '', facets: []}, + shortenedGraphemeLength: 0, + labels: [], + embed: {quote: {type: 'link', uri}}, + }, + ], + }) as never + + beforeEach(() => jest.clearAllMocks()) + + // The link form is what the composer actually holds: it is only expanded to + // the at:// form at publish, after routing has already decided. + it.each([ + ['a pasted permalink', permalink], + ['an at:// space record uri', SPACE_POST], + ])( + 'refuses %s rather than writing it to the public repo', + async (_n, uri) => { + const {agent, applyWrites, fetchHandler} = mockAgent() + + await expect( + post(agent, queryClient, {thread: threadQuoting(uri)}), + ).rejects.toThrow(/private post/) + + expect(applyWrites).not.toHaveBeenCalled() + expect(fetchHandler).not.toHaveBeenCalled() + expect(postToSpace).not.toHaveBeenCalled() + }, + ) + + it.each([ + ['opened from the space post', {communitySpaceUri: SPACE}], + ['composing into the space-backed feed', {}], + ])( + 'allows the quote when the post goes into that space (%s)', + async (_n, extra) => { + const {agent} = mockAgent() + + await post(agent, queryClient, { + thread: { + ...(threadQuoting(permalink, SPACE) as object), + ...extra, + } as never, + }) + + expect(postToSpace).toHaveBeenCalled() + }, + ) +}) + +describe('quotedSpace', () => { + const OTHER = 'at://did:plc:community/space/community.blacksky.feed/other' + + it('reads the space out of either form', () => { + expect(quotedSpace(`${SPACE}/did:plc:bob/app.bsky.feed.post/3kabc`)).toBe( + SPACE, + ) + expect( + quotedSpace( + `/profile/did:plc:bob/post/3kabc?space=${encodeURIComponent(OTHER)}`, + ), + ).toBe(OTHER) + }) + + it.each([ + ['a public post', 'at://did:plc:bob/app.bsky.feed.post/3kabc'], + ['a community stub', 'at://did:plc:bob/community.blacksky.feed.post/3kabc'], + ['a bare space uri with no record', SPACE], + ['nothing', undefined], + ])('returns null for %s', (_n, uri) => { + expect(quotedSpace(uri)).toBeNull() + }) +}) + +describe('space replies', () => { + it('passes the reply target down to the space write path', async () => { + const {agent} = mockAgent() + const parent = `${SPACE}/did:plc:bob/app.bsky.feed.post/3kparent` + + await post(agent, queryClient, { + thread: threadWith(SPACE), + replyTo: parent, + }) + + // postToSpace resolves the parent itself; what matters here is that the + // reply is routed into the space at all rather than posted publicly. + expect(postToSpace).toHaveBeenCalledWith(agent, queryClient, SPACE, { + thread: threadWith(SPACE), + replyTo: parent, + }) + }) + + it('reconstructs the space target when the reply view omitted it', async () => { + const {agent} = mockAgent() + const parent = `${SPACE}/did:plc:bob/app.bsky.feed.post/3kparent` + const thread = threadWith(undefined) + + await post(agent, queryClient, {thread, replyTo: parent}) + + expect(postToSpace).toHaveBeenCalledWith(agent, queryClient, SPACE, { + thread, + replyTo: parent, + }) + }) +}) + +describe('resolveReply public-path guard', () => { + const publicParent = 'at://did:plc:bob/app.bsky.feed.post/3kparent' + const spaceRecord = `${SPACE}/did:plc:bob/app.bsky.feed.post/3kroot` + + const agentReturningRoot = (rootUri: string) => + ({ + app: { + bsky: { + feed: { + getPosts: jest.fn(() => + Promise.resolve({ + data: { + posts: [ + { + uri: publicParent, + cid: 'bafyreiparent', + record: { + $type: 'app.bsky.feed.post', + text: 'hi', + createdAt: '2026-08-09T12:00:00.000Z', + reply: { + root: {uri: rootUri, cid: 'bafyreiroot'}, + parent: {uri: publicParent, cid: 'bafyreiparent'}, + }, + }, + }, + ], + }, + }), + ), + }, + }, + }, + }) as unknown as AtpAgent + + it('refuses to hand a space thread root to the public write path', async () => { + await expect( + resolveReply(agentReturningRoot(spaceRecord), publicParent), + ).rejects.toThrow(/private post/i) + }) + + it('passes an ordinary thread root through', async () => { + const root = 'at://did:plc:bob/app.bsky.feed.post/3kroot' + await expect( + resolveReply(agentReturningRoot(root), publicParent), + ).resolves.toEqual({ + root: {uri: root, cid: 'bafyreiroot'}, + parent: {uri: publicParent, cid: 'bafyreiparent'}, + }) + }) +}) diff --git a/src/lib/api/__tests__/space-permalink.test.ts b/src/lib/api/__tests__/space-permalink.test.ts new file mode 100644 index 000000000..62cc2b4fa --- /dev/null +++ b/src/lib/api/__tests__/space-permalink.test.ts @@ -0,0 +1,138 @@ +import {postPermalink} from '#/lib/routes/links' +import {postUriToRelativePath} from '#/lib/strings/url-helpers' +import { + isSpacePostUrl, + postUriAuthor, + spacePostUriFromRoute, +} from '../space-permalink' + +const SPACE = 'at://did:plc:community/space/community.blacksky.feed/private' +const AUTHOR = {did: 'did:plc:alice', handle: 'alice.test'} +const SPACE_POST = `${SPACE}/did:plc:alice/app.bsky.feed.post/3kabc` + +describe('space permalinks', () => { + it('keeps the ordinary post url and attaches the space', () => { + expect(postPermalink(AUTHOR, SPACE_POST)).toBe( + `/profile/did:plc:alice/post/3kabc?space=${encodeURIComponent(SPACE)}`, + ) + }) + + it('carries a suffix segment before the query', () => { + expect(postPermalink(AUTHOR, SPACE_POST, 'liked-by')).toBe( + `/profile/did:plc:alice/post/3kabc/liked-by?space=${encodeURIComponent( + SPACE, + )}`, + ) + }) + + it.each([ + ['a public post', 'at://did:plc:alice/app.bsky.feed.post/3kabc', ''], + [ + 'the community stub', + 'at://did:plc:alice/community.blacksky.feed.post/3kabc', + '?collection=community.blacksky.feed.post', + ], + ])('leaves %s alone', (_name, uri, query) => { + expect(postPermalink(AUTHOR, uri)).toBe( + `/profile/did:plc:alice/post/3kabc${query}`, + ) + }) + + it('round-trips back to the record uri', () => { + expect(spacePostUriFromRoute(SPACE, 'did:plc:alice', '3kabc')).toBe( + SPACE_POST, + ) + }) + + it.each([ + ['no space', undefined, 'did:plc:alice'], + [ + 'a malformed space', + 'at://did:plc:community/space/onlythree', + 'did:plc:alice', + ], + // A handle cannot stand in for the author: the URI form admits only DIDs, + // so the caller has to resolve it first. + ['an unresolved handle', SPACE, 'alice.test'], + ])('refuses %s', (_name, space, author) => { + expect(spacePostUriFromRoute(space, author, '3kabc')).toBeNull() + }) +}) + +describe('post uri authors', () => { + it.each([ + [ + 'a public post', + 'at://did:plc:public/app.bsky.feed.post/3kroot', + 'did:plc:public', + ], + [ + 'a legacy community post', + 'at://did:plc:community/community.blacksky.feed.post/3kroot', + 'did:plc:community', + ], + ['a permissioned-space post', SPACE_POST, AUTHOR.did], + ])('finds the author of %s', (_name, uri, expected) => { + expect(postUriAuthor(uri)).toBe(expected) + }) + + it('does not feed malformed input through as an author', () => { + expect(postUriAuthor('not-an-at-uri')).toBeNull() + }) +}) + +describe('recognising a space link before it is expanded', () => { + const encoded = encodeURIComponent(SPACE) + + it.each([ + [ + 'a full url', + `https://blacksky.community/profile/did:plc:alice/post/3kabc?space=${encoded}`, + ], + ['a relative path', `/profile/did:plc:alice/post/3kabc?space=${encoded}`], + [ + 'a suffix route', + `https://bsky.app/profile/did:plc:alice/post/3kabc/liked-by?space=${encoded}`, + ], + [ + 'an unencoded space param', + `/profile/did:plc:alice/post/3kabc?space=${SPACE}`, + ], + ])('spots %s', (_name, url) => { + expect(isSpacePostUrl(url)).toBe(true) + }) + + it.each([ + ['a public post url', 'https://bsky.app/profile/alice.test/post/3kabc'], + [ + 'a community stub url', + '/profile/did:plc:alice/post/3kabc?collection=community.blacksky.feed.post', + ], + [ + 'a space param that is not a space uri', + '/profile/did:plc:alice/post/3kabc?space=nonsense', + ], + ['nothing', undefined], + ])('ignores %s', (_name, url) => { + expect(isSpacePostUrl(url)).toBe(false) + }) +}) + +describe('space post urls survive the composer round trip', () => { + it('encodes and decodes back to the same record uri', () => { + const path = postUriToRelativePath(SPACE_POST) + expect(path).toBe( + `/profile/did:plc:alice/post/3kabc?space=${encodeURIComponent(SPACE)}`, + ) + // What resolveLink does on the way back: read the parts out of the url. + const url = new URL(path!, 'http://_') + const [, user, , rkey] = url.pathname.split('/').filter(Boolean) + expect( + spacePostUriFromRoute( + url.searchParams.get('space') ?? undefined, + user, + rkey, + ), + ).toBe(SPACE_POST) + }) +}) diff --git a/src/lib/api/__tests__/space-post.test.ts b/src/lib/api/__tests__/space-post.test.ts new file mode 100644 index 000000000..a31b20e23 --- /dev/null +++ b/src/lib/api/__tests__/space-post.test.ts @@ -0,0 +1,124 @@ +import {type AtpAgent} from '@atproto/api' +import {type QueryClient} from '@tanstack/react-query' + +import {resolveEmbed} from '../index' +import {postToSpace} from '../space-post' +import {spaceCreateRecord} from '../space-write' + +jest.mock('../index', () => ({ + quotedSpace: jest.fn((uri?: string) => + uri?.includes('/space/') ? uri.split('/did:plc:author/')[0] : null, + ), + resolveEmbed: jest.fn(), + resolveReply: jest.fn(), + resolveRT: jest.fn((_agent, richtext) => Promise.resolve(richtext)), +})) + +jest.mock('../space-write', () => ({ + POST_COLLECTION: 'app.bsky.feed.post', + spaceCreateRecord: jest.fn(() => + Promise.resolve({ + uri: 'at://space/post', + cid: 'bafyspace', + }), + ), +})) + +const SPACE = 'at://did:plc:space/space/community.blacksky.feed/private' +const OTHER = 'at://did:plc:other/space/community.blacksky.feed/private' +const agent = {} as AtpAgent +const queryClient = {} as QueryClient + +const thread = (embed: object = {}, id = 'draft-operation-1') => + ({ + posts: [ + { + id, + richtext: {text: 'hello', facets: []}, + shortenedGraphemeLength: 5, + labels: [], + embed, + }, + ], + postgate: {}, + threadgate: [], + blackskyOnly: false, + communitySpaceUri: SPACE, + }) as never + +describe(postToSpace, () => { + beforeEach(() => jest.clearAllMocks()) + + it.each(['images', 'gallery', 'video', 'gif'])( + 'blocks %s before embed resolution or a write', + async type => { + await expect( + postToSpace(agent, queryClient, SPACE, { + thread: thread({media: {type}}), + }), + ).rejects.toThrow(/not available in private spaces/i) + + expect(resolveEmbed).not.toHaveBeenCalled() + expect(spaceCreateRecord).not.toHaveBeenCalled() + }, + ) + + it('refuses a quote from another space before embed resolution', async () => { + await expect( + postToSpace(agent, queryClient, SPACE, { + thread: thread({ + quote: { + uri: `${OTHER}/did:plc:author/app.bsky.feed.post/3kquote`, + }, + }), + }), + ).rejects.toThrow(/another space/i) + + expect(resolveEmbed).not.toHaveBeenCalled() + expect(spaceCreateRecord).not.toHaveBeenCalled() + }) + + it('uses the stable protocol-valid draft id as the record key', async () => { + await postToSpace(agent, queryClient, SPACE, {thread: thread()}) + + expect(spaceCreateRecord).toHaveBeenCalledWith( + agent, + SPACE, + 'app.bsky.feed.post', + expect.objectContaining({text: 'hello'}), + 'draft-operation-1', + ) + }) + + it('derives a stable record key from a saved draft id and post index', async () => { + const opts = {thread: thread(), draftId: '3mabcde234567'} + + await postToSpace(agent, queryClient, SPACE, opts) + await postToSpace(agent, queryClient, SPACE, opts) + + expect(spaceCreateRecord).toHaveBeenNthCalledWith( + 1, + agent, + SPACE, + 'app.bsky.feed.post', + expect.any(Object), + '3mabcde234567-0', + ) + expect(spaceCreateRecord).toHaveBeenNthCalledWith( + 2, + agent, + SPACE, + 'app.bsky.feed.post', + expect.any(Object), + '3mabcde234567-0', + ) + }) + + it('rejects an invalid draft id before writing', async () => { + await expect( + postToSpace(agent, queryClient, SPACE, {thread: thread({}, 'bad/id')}), + ).rejects.toThrow(/record key/i) + + expect(spaceCreateRecord).not.toHaveBeenCalled() + }) +}) diff --git a/src/lib/api/__tests__/space-write.test.ts b/src/lib/api/__tests__/space-write.test.ts new file mode 100644 index 000000000..2aa5885df --- /dev/null +++ b/src/lib/api/__tests__/space-write.test.ts @@ -0,0 +1,274 @@ +import {type BskyAgent} from '@atproto/api' +import {describe, expect, it} from '@jest/globals' + +import { + LIKE_COLLECTION, + POST_COLLECTION, + spaceCreateRecord, + spaceDeleteIfSpace, + spaceDeleteRecord, + spaceLike, + spaceLikeIfSpace, + spaceUnlike, + spaceUnlikeIfSpace, + SpaceUnsupportedError, +} from '#/lib/api/space-write' + +const SPACE = 'at://did:plc:tenant/space/community.blacksky.feed/private' +const SUBJECT = { + uri: `${SPACE}/did:plc:alice/app.bsky.feed.post/3kabc`, + cid: 'bafyreisubject', +} + +type Call = { + path: string + method?: string + headers: Record + body: string +} +type MockResponse = {status?: number; body?: unknown} + +function agentWith( + response: MockResponse | MockResponse[] = {}, + signedIn = true, +) { + const calls: Call[] = [] + const responses = Array.isArray(response) ? response : [response] + let responseIndex = 0 + const agent = { + ...(signedIn ? {session: {did: 'did:plc:me'}} : {}), + fetchHandler(path: string, init: RequestInit) { + const current = responses[Math.min(responseIndex++, responses.length - 1)] + const status = current.status ?? 200 + calls.push({ + path, + method: init.method, + headers: (init.headers ?? {}) as Record, + body: typeof init.body === 'string' ? init.body : '', + }) + return Promise.resolve({ + ok: status < 400, + status, + json: () => + Promise.resolve( + current.body ?? {uri: 'at://space/record', cid: 'bafyreinew'}, + ), + } as unknown as Response) + }, + } as unknown as BskyAgent + return {agent, calls} +} + +const bodyOf = (call: Call): Record => + JSON.parse(call.body) as Record + +describe('space writes', () => { + it('posts to the account’s own pds without a proxy header', async () => { + const {agent, calls} = agentWith() + await spaceCreateRecord(agent, SPACE, POST_COLLECTION, { + $type: POST_COLLECTION, + text: 'hello', + }) + + expect(calls).toHaveLength(1) + expect(calls[0].path).toBe('/xrpc/com.atproto.space.createRecord') + // The write belongs to the PDS, not the appview. Proxying it would send + // private content to the wrong service entirely. + expect(calls[0].headers['atproto-proxy']).toBeUndefined() + expect(bodyOf(calls[0])).toEqual({ + space: SPACE, + repo: 'did:plc:me', + collection: POST_COLLECTION, + record: {$type: POST_COLLECTION, text: 'hello'}, + rkey: expect.any(String), + }) + }) + + it('uses an explicit stable rkey or generates a protocol key', async () => { + const {agent, calls} = agentWith() + await spaceCreateRecord(agent, SPACE, POST_COLLECTION, {}, '3kxyz') + expect(bodyOf(calls[0]).rkey).toBe('3kxyz') + + await spaceCreateRecord(agent, SPACE, POST_COLLECTION, {}) + expect(bodyOf(calls[1]).rkey).toEqual(expect.any(String)) + }) + + it('recovers a same-rkey retry from RecordExists by authoritative readback', async () => { + const record = { + $type: POST_COLLECTION, + text: 'hello', + createdAt: '2026-08-26T12:00:00.000Z', + } + const original = {uri: 'at://space/original', cid: 'bafyreioriginal'} + const {agent, calls} = agentWith([ + {body: original}, + {status: 400, body: {error: 'RecordExists'}}, + {body: {...original, value: record}}, + ]) + + const first = await spaceCreateRecord( + agent, + SPACE, + POST_COLLECTION, + {...record, createdAt: '2026-08-26T12:00:01.000Z'}, + '3mstablekey', + ) + const retry = await spaceCreateRecord( + agent, + SPACE, + POST_COLLECTION, + record, + '3mstablekey', + ) + + expect(retry).toEqual(first) + expect(bodyOf(calls[0]).rkey).toBe('3mstablekey') + expect(bodyOf(calls[1]).rkey).toBe('3mstablekey') + expect(calls[2].method).toBe('GET') + const readback = new URL(calls[2].path, 'https://pds.example') + expect(readback.pathname).toBe('/xrpc/com.atproto.space.getRecord') + expect(Object.fromEntries(readback.searchParams)).toEqual({ + space: SPACE, + repo: 'did:plc:me', + collection: POST_COLLECTION, + rkey: '3mstablekey', + }) + }) + + it('writes a like into the permissioned repo, never the public one', async () => { + const {agent, calls} = agentWith() + await spaceLike(agent, SPACE, SUBJECT) + + // The one thing that must never happen: com.atproto.repo.createRecord with + // a space-uri subject, which would publish that the private post exists. + expect(calls[0].path).toBe('/xrpc/com.atproto.space.createRecord') + expect(calls[0].path).not.toContain('com.atproto.repo') + expect(bodyOf(calls[0])).toMatchObject({ + space: SPACE, + collection: LIKE_COLLECTION, + record: {$type: LIKE_COLLECTION, subject: SUBJECT}, + }) + }) + + it('unlikes by the rkey of the like record', async () => { + const {agent, calls} = agentWith({body: {}}) + await spaceUnlike( + agent, + SPACE, + `${SPACE}/did:plc:me/${LIKE_COLLECTION}/3klike`, + ) + + expect(calls[0].path).toBe('/xrpc/com.atproto.space.deleteRecord') + expect(bodyOf(calls[0])).toEqual({ + space: SPACE, + repo: 'did:plc:me', + collection: LIKE_COLLECTION, + rkey: '3klike', + }) + }) + + it('deletes one of the caller’s own records', async () => { + const {agent, calls} = agentWith({body: {}}) + await spaceDeleteRecord(agent, SPACE, POST_COLLECTION, '3kpost') + expect(bodyOf(calls[0]).rkey).toBe('3kpost') + expect(bodyOf(calls[0]).repo).toBe('did:plc:me') + }) + + it('fails before issuing a request when the agent is signed out', async () => { + const {agent, calls} = agentWith({}, false) + + await expect( + spaceCreateRecord(agent, SPACE, POST_COLLECTION, {}), + ).rejects.toThrow(/sign in/i) + await expect( + spaceDeleteRecord(agent, SPACE, POST_COLLECTION, '3kpost'), + ).rejects.toThrow(/sign in/i) + expect(calls).toHaveLength(0) + }) + + it('reads a 404 as “this pds has no space support”', async () => { + const {agent} = agentWith({status: 404}) + // A PDS that never heard of the method answers 404 rather than an XRPC + // error; that is how a foreign-PDS account is recognised so the UI can + // offer migration instead of a generic failure. + await expect( + spaceCreateRecord(agent, SPACE, POST_COLLECTION, {}), + ).rejects.toBeInstanceOf(SpaceUnsupportedError) + }) + + it('surfaces the host’s own message on other failures', async () => { + const {agent} = agentWith({ + status: 429, + body: {error: 'RateLimitExceeded', message: 'records quota exceeded'}, + }) + await expect( + spaceCreateRecord(agent, SPACE, POST_COLLECTION, {}), + ).rejects.toThrow('records quota exceeded') + }) + + it('refuses a response that names no record', async () => { + const {agent} = agentWith({body: {cid: 'bafyreinew'}}) + await expect( + spaceCreateRecord(agent, SPACE, POST_COLLECTION, {}), + ).rejects.toThrow(/no record reference/) + }) +}) + +const PUBLIC_POST = 'at://did:plc:alice/app.bsky.feed.post/3kabc' +const PUBLIC_LIKE = 'at://did:plc:alice/app.bsky.feed.like/3klike' + +describe('interaction routing', () => { + it('likes a space post into its own space', async () => { + const {agent, calls} = agentWith() + + await spaceLikeIfSpace(agent, SUBJECT.uri, SUBJECT.cid) + + // The leak this prevents: a like in the public repo whose subject is a + // space URI announces that the private post exists. + expect(calls[0].path).toBe('/xrpc/com.atproto.space.createRecord') + expect(bodyOf(calls[0])).toMatchObject({ + space: SPACE, + collection: LIKE_COLLECTION, + }) + }) + + it('unlikes and deletes within the space the record belongs to', async () => { + const {agent, calls} = agentWith({body: {}}) + + await spaceUnlikeIfSpace( + agent, + `${SPACE}/did:plc:alice/${LIKE_COLLECTION}/3klike`, + ) + await spaceDeleteIfSpace( + agent, + `${SPACE}/did:plc:alice/${POST_COLLECTION}/3kpost`, + ) + + expect(calls.map(bodyOf)).toEqual([ + { + space: SPACE, + repo: 'did:plc:me', + collection: LIKE_COLLECTION, + rkey: '3klike', + }, + { + space: SPACE, + repo: 'did:plc:me', + collection: POST_COLLECTION, + rkey: '3kpost', + }, + ]) + }) + + it.each([ + ['like', (a: BskyAgent) => spaceLikeIfSpace(a, PUBLIC_POST, 'bafy')], + ['unlike', (a: BskyAgent) => spaceUnlikeIfSpace(a, PUBLIC_LIKE)], + ['delete', (a: BskyAgent) => spaceDeleteIfSpace(a, PUBLIC_POST)], + ])('leaves a public %s to the public repo', (_name, run) => { + const {agent, calls} = agentWith() + + // null means "not mine" — the caller falls back to the ordinary agent call. + expect(run(agent)).toBeNull() + expect(calls).toHaveLength(0) + }) +}) diff --git a/src/lib/api/community-feed.ts b/src/lib/api/community-feed.ts new file mode 100644 index 000000000..374a9c55b --- /dev/null +++ b/src/lib/api/community-feed.ts @@ -0,0 +1,264 @@ +import {type AtpAgent, AtUri, XRPCError} from '@atproto/api' + +import {getServiceAuthToken} from '#/lib/api/service-auth' +import {isSpaceUri} from '#/lib/api/space-uri' + +export const COMMUNITY_FEED_CONFIG_COLLECTION = 'community.blacksky.feed.config' +export const CHECK_FEED_PERMISSIONS = 'community.blacksky.feed.checkPermissions' +export const ADMIT_FEED_POST = 'community.blacksky.feed.admitPost' + +export const COMMUNITY_FEED_PERMISSIONS = [ + 'canView', + 'canPost', + 'canRemovePost', + 'canRemoveMember', + 'canConfigure', + 'canModerate', +] as const + +export type CommunityFeedPermission = + (typeof COMMUNITY_FEED_PERMISSIONS)[number] + +export type CommunityFeedConfig = { + $type: 'community.blacksky.feed.config' + contentType: 'publicRecord' | 'communityRecord' + visibility: 'public' | 'gated' + authorization?: { + serviceDid: string + method?: string + } + policyMode?: 'memberList' | 'managingApp' | 'public' + /** + * Present when the feed's content lives in a permissioned space rather than + * in an appview table. A plain string, never `format: at-uri` — a space URI + * is not a valid at-uri. + */ + space?: string + group: string + createdAt: string +} + +/** + * Whether this feed's content lives in a permissioned space. + * + * This is the discriminator, and the only one. `visibility: 'gated'` is an + * invariant the config must satisfy to parse at all, not an input to the + * decision; access itself is always decided by the space authority, never read + * off the record. + */ +export function isSpaceBackedFeed( + config: CommunityFeedConfig | null | undefined, +): config is CommunityFeedConfig & {space: string} { + return !!config?.space && isSpaceUri(config.space) +} + +export type CommunityFeedTarget = { + feed: string + name: string + serviceDid: string + config: CommunityFeedConfig +} + +type CommunityFeedGenerator = { + serviceDid: string + name: string +} + +function parseCommunityFeedConfig(value: unknown): CommunityFeedConfig | null { + if (!value || typeof value !== 'object') return null + const config = value as Record + const authorization = config.authorization as + | Record + | undefined + if ( + config.$type !== COMMUNITY_FEED_CONFIG_COLLECTION || + (config.contentType !== 'publicRecord' && + config.contentType !== 'communityRecord') || + (config.visibility !== 'public' && config.visibility !== 'gated') || + (authorization !== undefined && + typeof authorization.serviceDid !== 'string') || + typeof config.group !== 'string' || + typeof config.createdAt !== 'string' || + (config.space !== undefined && typeof config.space !== 'string') + ) { + return null + } + return config as CommunityFeedConfig +} + +export async function fetchCommunityFeedConfig( + agent: AtpAgent, + feed: string, +): Promise { + try { + return await fetchCommunityFeedConfigStrict(agent, feed) + } catch { + return null + } +} + +/** + * Distinguishes "no config record exists" (null) from a failed read (throws). + * The feed dispatch must not treat a transient config-read failure as "not + * space-backed" and route a private feed down the standard path. + */ +export async function fetchCommunityFeedConfigStrict( + agent: AtpAgent, + feed: string, +): Promise { + let uri: AtUri + try { + uri = new AtUri(feed) + } catch { + return null + } + if (!uri.rkey) return null + try { + const {data} = await agent.com.atproto.repo.getRecord({ + repo: uri.hostname, + collection: COMMUNITY_FEED_CONFIG_COLLECTION, + rkey: uri.rkey, + }) + return parseCommunityFeedConfig(data.value) + } catch (e) { + if (e instanceof XRPCError && e.error === 'RecordNotFound') { + return null + } + throw e + } +} + +async function fetchFeedGenerator( + agent: AtpAgent, + feed: string, +): Promise { + try { + const uri = new AtUri(feed) + if (!uri.rkey) return null + const {data} = await agent.com.atproto.repo.getRecord({ + repo: uri.hostname, + collection: 'app.bsky.feed.generator', + rkey: uri.rkey, + }) + const value = data.value as Record + return typeof value.did === 'string' + ? { + serviceDid: value.did, + name: + typeof value.displayName === 'string' ? value.displayName : feed, + } + : null + } catch { + return null + } +} + +export async function fetchFeedServiceDid( + agent: AtpAgent, + feed: string, +): Promise { + return (await fetchFeedGenerator(agent, feed))?.serviceDid ?? null +} + +function isCommunityFeedPermission( + value: unknown, +): value is CommunityFeedPermission { + return ( + typeof value === 'string' && + COMMUNITY_FEED_PERMISSIONS.includes(value as CommunityFeedPermission) + ) +} + +async function fetchFeedPermissionsFromService( + agent: AtpAgent, + feed: string, + serviceDid: string, +): Promise { + try { + const token = await getServiceAuthToken({ + agent, + aud: serviceDid, + lxm: CHECK_FEED_PERMISSIONS, + exp: Math.floor(Date.now() / 1000) + 60, + }) + const response = await agent.fetchHandler( + `/xrpc/${CHECK_FEED_PERMISSIONS}?${new URLSearchParams({feed})}`, + { + headers: { + Authorization: `Bearer ${token}`, + 'atproto-proxy': `${serviceDid}#bsky_fg`, + }, + }, + ) + if (!response.ok) return [] + const body = (await response.json()) as {permissions?: unknown} + return Array.isArray(body.permissions) + ? body.permissions.filter(isCommunityFeedPermission) + : [] + } catch { + return [] + } +} + +export async function fetchFeedPermissions( + agent: AtpAgent, + feed: string, +): Promise { + const config = await fetchCommunityFeedConfig(agent, feed) + if (!config) return [] + const serviceDid = await fetchFeedServiceDid(agent, feed) + return serviceDid + ? fetchFeedPermissionsFromService(agent, feed, serviceDid) + : [] +} + +export async function fetchCommunityFeedTarget( + agent: AtpAgent, + feed: string, +): Promise { + const [config, generator] = await Promise.all([ + fetchCommunityFeedConfig(agent, feed), + fetchFeedGenerator(agent, feed), + ]) + if (!config || !generator) return null + const permissions = await fetchFeedPermissionsFromService( + agent, + feed, + generator.serviceDid, + ) + return permissions.includes('canPost') + ? { + feed, + name: generator.name, + serviceDid: generator.serviceDid, + config, + } + : null +} + +export async function admitFeedPost( + agent: AtpAgent, + target: CommunityFeedTarget, + post: string, + cid: string, +): Promise { + const token = await getServiceAuthToken({ + agent, + aud: target.serviceDid, + lxm: ADMIT_FEED_POST, + exp: Math.floor(Date.now() / 1000) + 60, + }) + const response = await agent.fetchHandler(`/xrpc/${ADMIT_FEED_POST}`, { + method: 'POST', + headers: { + Authorization: `Bearer ${token}`, + 'Content-Type': 'application/json', + 'atproto-proxy': `${target.serviceDid}#bsky_fg`, + }, + body: JSON.stringify({feed: target.feed, post, cid}), + }) + if (!response.ok) { + const body = (await response.json().catch(() => ({}))) as {message?: string} + throw new Error(body.message || `HTTP ${response.status}`) + } +} diff --git a/src/lib/api/community-post.ts b/src/lib/api/community-post.ts new file mode 100644 index 000000000..4eb41154a --- /dev/null +++ b/src/lib/api/community-post.ts @@ -0,0 +1,92 @@ +import { + type AppBskyFeedDefs, + AppBskyFeedPost, + type BskyAgent, + jsonToLex, +} from '@atproto/api' + +import {communityXrpc} from '#/lib/api/community' +import {isSpaceRecordUri, parseSpaceUri} from '#/lib/api/space-uri' +import {toPostView} from '#/lib/api/space-views' +import * as bsky from '#/types/bsky' + +export const GET_COMMUNITY_POST = 'community.blacksky.feed.getCommunityPost' + +const COMMUNITY_POST_COLLECTION = 'community.blacksky.feed.post' + +/** + * Whether this post is community content — the appview-stored stub, or a + * record living in a permissioned space. Keyed structurally rather than by + * collection, so a new kind of space record is covered the day it appears. + */ +export function isCommunityPostUri(uri: string | undefined): boolean { + return ( + !!uri && (uri.includes(COMMUNITY_POST_COLLECTION) || isSpaceRecordUri(uri)) + ) +} + +/** + * Space records use the same post record shape as public posts, but their + * reply and quote refs are permissioned-space URIs rather than AT-URIs. The + * public lexicon validator therefore cannot validate those otherwise valid + * records. Space responses are already validated by the AppView endpoint; + * retain the fields the renderer requires here while keeping strict lexicon + * validation for public posts. + */ +export function isRenderablePostRecord( + post: AppBskyFeedDefs.PostView, +): post is AppBskyFeedDefs.PostView & {record: AppBskyFeedPost.Record} { + if (!AppBskyFeedPost.isRecord(post.record)) return false + if (!isSpaceRecordUri(post.uri)) { + return bsky.validate(post.record, AppBskyFeedPost.validateRecord) + } + return ( + typeof post.record.text === 'string' && + typeof post.record.createdAt === 'string' + ) +} + +export type CommunityPostView = AppBskyFeedDefs.PostView & { + communitySpace?: string +} + +/** + * The permissioned space a post lives in, which is its authorization + * boundary. A feed is only a view over a space, so the post view carries the + * space; never fed to `AtUri`, which misparses a space URI. + */ +export function getCommunitySpaceUri( + post: AppBskyFeedDefs.PostView | undefined, +): string | undefined { + const space = (post as unknown as {communitySpace?: unknown} | undefined) + ?.communitySpace + // The 4-segment pointer only: a record inside a space is not the space. + return typeof space === 'string' && parseSpaceUri(space) !== null + ? space + : undefined +} + +/** + * Read one community post by URI. + * + * The standard `getPosts` cannot serve these: its `uris` are at-uris, and a + * space record URI is not one. This endpoint takes a plain string, and gates + * on membership before returning anything. + */ +export async function fetchCommunityPostView( + agent: BskyAgent, + uri: string, +): Promise { + const res = await communityXrpc(agent, GET_COMMUNITY_POST, {params: {uri}}) + if (!res.ok) { + const body = (await res.json().catch(() => ({}))) as { + message?: string + error?: string + } + throw new Error(body.message || body.error || `HTTP ${res.status}`) + } + const data = jsonToLex(await res.json()) as {post?: unknown} + const post = toPostView(data.post) + if (!post) throw new Error('Community post not found') + return post +} diff --git a/src/lib/api/community-thread.ts b/src/lib/api/community-thread.ts new file mode 100644 index 000000000..f3c6743a5 --- /dev/null +++ b/src/lib/api/community-thread.ts @@ -0,0 +1,81 @@ +import {type BskyAgent} from '@atproto/api' + +import {communityXrpc} from '#/lib/api/community' +import {toSpaceThreadBody} from '#/lib/api/space-views' + +export const GET_COMMUNITY_THREAD = 'community.blacksky.feed.getCommunityThread' + +export type CommunityThreadResponse = { + thread: unknown[] + hasOtherReplies: boolean + /** Space feeds carry no threadgates (they are deferred), so never set. */ + threadgate?: undefined +} + +/** + * Fetch a thread anchored on a permissioned-space record. + * + * The standard thread endpoint cannot be used: its anchor is declared + * `format: at-uri`, and a space URI is not one, so the request is refused + * before it reaches a handler. This endpoint takes the anchor as a plain + * string and answers with the same item shape. + */ +export async function fetchCommunityThread( + agent: BskyAgent, + params: { + anchor: string + above?: boolean + below?: number + branchingFactor?: number + }, +): Promise { + const query: Record = {anchor: params.anchor} + if (params.above !== undefined) query.above = String(params.above) + if (params.below !== undefined) query.below = String(params.below) + if (params.branchingFactor !== undefined) { + query.branchingFactor = String(params.branchingFactor) + } + const res = await communityXrpc(agent, GET_COMMUNITY_THREAD, {params: query}) + if (!res.ok) { + const body = (await res.json().catch(() => ({}))) as { + message?: string + error?: string + } + throw new Error(body.message || body.error || `HTTP ${res.status}`) + } + // The wire types are community.blacksky.feed.defs; the thread renderer + // consumes the standard threadItem shapes, which are structurally identical. + const data = toSpaceThreadBody( + await res.json(), + ) as Partial + return { + thread: data.thread ?? [], + hasOtherReplies: !!data.hasOtherReplies, + } +} + +export const SET_THREAD_MUTE = 'community.blacksky.feed.setThreadMute' + +/** + * Mute or unmute a thread rooted at a space record. + * + * The standard mute methods take an at-uri, which a space URI is not. Mute + * state itself is keyed by plain URI on both sides, so nothing else differs. + */ +export async function setSpaceThreadMute( + agent: BskyAgent, + root: string, + mute: boolean, +): Promise<{}> { + const res = await communityXrpc(agent, SET_THREAD_MUTE, { + body: {root, mute}, + }) + if (!res.ok) { + const body = (await res.json().catch(() => ({}))) as { + message?: string + error?: string + } + throw new Error(body.message || body.error || `HTTP ${res.status}`) + } + return {} +} diff --git a/src/lib/api/community.ts b/src/lib/api/community.ts index cd0aa72f2..817580059 100644 --- a/src/lib/api/community.ts +++ b/src/lib/api/community.ts @@ -1,22 +1,20 @@ -import {type BskyAgent} from '@atproto/api' +import { + type AppBskyFeedGetLikes, + type AppBskyFeedGetQuotes, + type BskyAgent, + jsonToLex, +} from '@atproto/api' import {HOME_PROXY_HEADER} from '#/lib/constants' +import {toPostView} from './space-views' -/** - * Make an XRPC call to a community.blacksky.feed.* endpoint. - * - * Calls through the PDS using the agent's session auth and atproto-proxy - * header. The PDS validates the user's credentials, creates a service auth - * JWT signed by the user's keypair, and forwards the request to the appview. - * - * Pinned: community.blacksky.* endpoints only exist on the home appview. - */ export async function communityXrpc( agent: BskyAgent, method: string, opts?: { params?: Record body?: unknown + serviceDid?: string }, ): Promise { const qs = opts?.params @@ -25,7 +23,9 @@ export async function communityXrpc( const path = `/xrpc/${method}${qs}` const headers: Record = { - 'atproto-proxy': HOME_PROXY_HEADER, + 'atproto-proxy': opts?.serviceDid + ? `${opts.serviceDid}#bsky_appview` + : HOME_PROXY_HEADER, } const init: RequestInit = { method: opts?.body ? 'POST' : 'GET', @@ -37,3 +37,58 @@ export async function communityXrpc( } return agent.fetchHandler(path, init) } + +export async function getSpacePostLikes( + agent: BskyAgent, + params: {uri: string; limit: number; cursor?: string}, +): Promise { + const response = await communityXrpc( + agent, + 'community.blacksky.feed.getSpacePostLikes', + { + params: { + uri: params.uri, + limit: String(params.limit), + ...(params.cursor ? {cursor: params.cursor} : {}), + }, + }, + ) + if (!response.ok) { + throw new Error(`getSpacePostLikes ${response.status}`) + } + return jsonToLex(await response.json()) as AppBskyFeedGetLikes.OutputSchema +} + +export async function getSpacePostQuotes( + agent: BskyAgent, + params: {uri: string; limit: number; cursor?: string}, +): Promise { + const response = await communityXrpc( + agent, + 'community.blacksky.feed.getSpacePostQuotes', + { + params: { + uri: params.uri, + limit: String(params.limit), + ...(params.cursor ? {cursor: params.cursor} : {}), + }, + }, + ) + if (!response.ok) { + throw new Error(`getSpacePostQuotes ${response.status}`) + } + const data = jsonToLex(await response.json()) as { + cursor?: string + posts?: unknown[] + } + return { + uri: params.uri, + cursor: data.cursor, + posts: (data.posts ?? []) + .map(toPostView) + .filter( + (post): post is AppBskyFeedGetQuotes.OutputSchema['posts'][number] => + Boolean(post), + ), + } +} diff --git a/src/lib/api/feed-manip.ts b/src/lib/api/feed-manip.ts index 335bf28c8..501e12573 100644 --- a/src/lib/api/feed-manip.ts +++ b/src/lib/api/feed-manip.ts @@ -6,7 +6,7 @@ import { AppBskyFeedPost, } from '@atproto/api' -import * as bsky from '#/types/bsky' +import {isRenderablePostRecord} from '#/lib/api/community-post' import {isPostInLanguage} from '../../locale/helpers' import {FALLBACK_MARKER_POST} from './feed/home' import {type ReasonFeedSource} from './feed/types' @@ -68,10 +68,7 @@ export class FeedViewPostsSlice { this.isFallbackMarker = true return } - if ( - !AppBskyFeedPost.isRecord(post.record) || - !bsky.validate(post.record, AppBskyFeedPost.validateRecord) - ) { + if (!isRenderablePostRecord(post)) { return } const parent = reply?.parent @@ -101,8 +98,7 @@ export class FeedViewPostsSlice { } if ( !AppBskyFeedDefs.isPostView(parent) || - !AppBskyFeedPost.isRecord(parent.record) || - !bsky.validate(parent.record, AppBskyFeedPost.validateRecord) + !isRenderablePostRecord(parent) ) { this.isOrphan = true return @@ -141,11 +137,7 @@ export class FeedViewPostsSlice { // Keep going, it might still have a root, and we need this for thread // de-deduping } - if ( - !AppBskyFeedDefs.isPostView(root) || - !AppBskyFeedPost.isRecord(root.record) || - !bsky.validate(root.record, AppBskyFeedPost.validateRecord) - ) { + if (!AppBskyFeedDefs.isPostView(root) || !isRenderablePostRecord(root)) { this.isOrphan = true return } diff --git a/src/lib/api/feed/custom.ts b/src/lib/api/feed/custom.ts index d751629b3..00065bc6f 100644 --- a/src/lib/api/feed/custom.ts +++ b/src/lib/api/feed/custom.ts @@ -5,6 +5,14 @@ import { jsonStringToLex, } from '@atproto/api' +import { + type CommunityFeedConfig, + fetchCommunityFeedConfigStrict, + fetchFeedServiceDid, + isSpaceBackedFeed, +} from '#/lib/api/community-feed' +import {getServiceAuthToken} from '#/lib/api/service-auth' +import {fetchSpaceFeed, signInRequiredError} from '#/lib/api/space-feed' import { getAppLanguageAsContentLanguage, getContentLanguages, @@ -20,6 +28,8 @@ export class CustomFeedAPI implements FeedAPI { agent: AtpAgent params: GetCustomFeed.QueryParams userInterests?: string + communityConfig: Promise + feedServiceDid: Promise constructor({ agent, @@ -33,10 +43,54 @@ export class CustomFeedAPI implements FeedAPI { this.agent = agent this.params = feedParams this.userInterests = userInterests + this.communityConfig = fetchCommunityFeedConfigStrict( + agent, + feedParams.feed, + ) + this.feedServiceDid = this.communityConfig + .then(config => + config ? fetchFeedServiceDid(agent, feedParams.feed) : null, + ) + .catch(() => null) + } + + async communityAuthHeaders(): Promise> { + const [config, serviceDid] = await Promise.all([ + this.communityConfig, + this.feedServiceDid, + ]) + if (!config || !serviceDid) return {} + const token = await getServiceAuthToken({ + agent: this.agent, + aud: serviceDid, + lxm: 'app.bsky.feed.getFeedSkeleton', + exp: Math.floor(Date.now() / 1000) + 60, + }) + return {Authorization: `Bearer ${token}`} + } + + /** + * A space-backed feed never reaches the standard route, in either method. + * `app.bsky.feed.getFeed` now refuses it outright, so a poller that skipped + * this branch would error on every tick, and the logged-out fallback below + * would ask the public appview for private content. + */ + private async spaceFeed(): Promise { + const config = await this.communityConfig + return isSpaceBackedFeed(config) ? this.params.feed : null } async peekLatest(): Promise { + const spaceFeed = await this.spaceFeed() + if (spaceFeed) { + if (!this.agent.did) throw signInRequiredError() + const page = await fetchSpaceFeed(this.agent, spaceFeed, {limit: 1}) + return page.feed[0] + } const contentLangs = getContentLanguages().join(',') + const communityAuthHeaders = this.agent.did + ? await this.communityAuthHeaders() + : {} const res = await this.agent.app.bsky.feed.getFeed( { ...this.params, @@ -45,6 +99,7 @@ export class CustomFeedAPI implements FeedAPI { { headers: { ...getProxyHeadersForFeed(this.params.feed), + ...communityAuthHeaders, 'Accept-Language': contentLangs, }, }, @@ -59,9 +114,22 @@ export class CustomFeedAPI implements FeedAPI { cursor: string | undefined limit: number }): Promise { + const spaceFeed = await this.spaceFeed() + if (spaceFeed) { + if (!this.agent.did) throw signInRequiredError() + const page = await fetchSpaceFeed(this.agent, spaceFeed, {cursor, limit}) + return { + cursor: page.feed.length ? page.cursor : undefined, + feed: page.feed, + } + } + const contentLangs = getContentLanguages().join(',') const agent = this.agent const isBlueskyOwned = isBlueskyOwnedFeed(this.params.feed) + const communityAuthHeaders = agent.did + ? await this.communityAuthHeaders() + : {} const res = agent.did ? await this.agent.app.bsky.feed.getFeed( @@ -73,6 +141,7 @@ export class CustomFeedAPI implements FeedAPI { { headers: { ...getProxyHeadersForFeed(this.params.feed), + ...communityAuthHeaders, ...(isBlueskyOwned ? createBskyTopicsHeader(this.userInterests) : {}), diff --git a/src/lib/api/group-invite-e2e.e2e.ts b/src/lib/api/group-invite-e2e.e2e.ts new file mode 100644 index 000000000..153cf18cd --- /dev/null +++ b/src/lib/api/group-invite-e2e.e2e.ts @@ -0,0 +1,33 @@ +type GroupInviteE2EFailureStage = + | 'saved-feed-update' + | 'saved-feed-add' + | 'navigation' + +let pendingFailure: GroupInviteE2EFailureStage | undefined + +class GroupInviteE2EInjectedFailure extends Error { + readonly stage: GroupInviteE2EFailureStage + + constructor(stage: GroupInviteE2EFailureStage) { + super(`Injected group invite E2E failure: ${stage}`) + this.name = 'GroupInviteE2EInjectedFailure' + this.stage = stage + } +} + +export function setGroupInviteE2EFailure(stage: GroupInviteE2EFailureStage) { + pendingFailure = stage +} + +export function maybeFailGroupInviteE2E(stage: GroupInviteE2EFailureStage) { + if (pendingFailure !== stage) return + pendingFailure = undefined + throw new GroupInviteE2EInjectedFailure(stage) +} + +export function isGroupInviteE2EFailure( + error: unknown, + stage: GroupInviteE2EFailureStage, +) { + return error instanceof GroupInviteE2EInjectedFailure && error.stage === stage +} diff --git a/src/lib/api/group-invite-e2e.ts b/src/lib/api/group-invite-e2e.ts new file mode 100644 index 000000000..5771fdbfd --- /dev/null +++ b/src/lib/api/group-invite-e2e.ts @@ -0,0 +1,20 @@ +export type GroupInviteE2EFailureStage = + | 'saved-feed-update' + | 'saved-feed-add' + | 'navigation' + +/** Production builds never inject client-side failures. */ +export function setGroupInviteE2EFailure( + _stage: GroupInviteE2EFailureStage, +): void {} + +export function maybeFailGroupInviteE2E( + _stage: GroupInviteE2EFailureStage, +): void {} + +export function isGroupInviteE2EFailure( + _error: unknown, + _stage: GroupInviteE2EFailureStage, +): boolean { + return false +} diff --git a/src/lib/api/group-invite-ui.ts b/src/lib/api/group-invite-ui.ts new file mode 100644 index 000000000..87fe3986a --- /dev/null +++ b/src/lib/api/group-invite-ui.ts @@ -0,0 +1,124 @@ +import {type AppBskyActorDefs} from '@atproto/api' + +import { + GroupInviteClientError, + GroupInviteError, + type GroupInviteFeed, +} from './group-invites' + +const openedGroupInviteCodes = new Set() +const MAX_TRACKED_GROUP_INVITES = 1_000 + +export function shouldTrackGroupInviteOpened(code: string) { + if (openedGroupInviteCodes.has(code)) return false + if (openedGroupInviteCodes.size >= MAX_TRACKED_GROUP_INVITES) { + const oldest = openedGroupInviteCodes.values().next().value + if (oldest) openedGroupInviteCodes.delete(oldest) + } + openedGroupInviteCodes.add(code) + return true +} + +export function groupInviteErrorCopy(error: unknown): string { + const code = + error instanceof GroupInviteClientError + ? error.code + : GroupInviteError.AuthorizationUnavailable + switch (code) { + case GroupInviteError.InviteUnavailable: + return 'This invite is no longer available.' + case GroupInviteError.GroupAtCapacity: + return 'This group is currently at capacity.' + case GroupInviteError.RateLimitExceeded: + return 'Too many attempts. Please try again shortly.' + case GroupInviteError.AuthenticationRequired: + return 'Please sign in again to accept this invite.' + case GroupInviteError.InviteMisconfigured: + return 'This invite is temporarily unavailable.' + case GroupInviteError.AuthorizationUnavailable: + default: + return 'We could not contact the group service. Please try again.' + } +} + +export function summarizeGroupInviteFeeds(feeds: GroupInviteFeed[]) { + const readable = feeds.filter(feed => feed.canView) + return { + readable, + postable: readable.filter(feed => feed.canPost), + readOnly: readable.filter(feed => !feed.canPost), + } +} + +export function getDefaultGroupInviteFeedUris(feeds: GroupInviteFeed[]) { + return feeds + .filter(feed => feed.canView && Boolean(feed.uri)) + .map(feed => feed.uri) +} + +export function getFirstSelectedGroupInviteFeed( + feeds: GroupInviteFeed[], + selectedUris: ReadonlySet, +) { + const selected = feeds.filter( + feed => feed.canView && Boolean(feed.uri) && selectedUris.has(feed.uri), + ) + return selected.find(feed => feed.canPost) ?? selected[0] +} + +export function shouldOpenGroupInviteFeedAfterPinning( + feeds: GroupInviteFeed[], + selectedUris: ReadonlySet, +) { + return Boolean(getFirstSelectedGroupInviteFeed(feeds, selectedUris)) +} + +export function getGroupInviteMembershipCopy(feeds: GroupInviteFeed[]) { + const {readable, postable} = summarizeGroupInviteFeeds(feeds) + if (readable.length === 0) return 'No feeds available.' + if (postable.length === 0) return getGroupInviteNoPostCopy() + return undefined +} + +export function getGroupInviteNoPostCopy() { + return "You joined the group, but you don't currently have access to a feed you can post in. Please let your admins know if you think this is a mistake." +} + +export function shouldResetGroupInvitePinning( + previousUris: string[], + nextUris: string[], +) { + return ( + previousUris.length !== nextUris.length || + previousUris.some(uri => !nextUris.includes(uri)) + ) +} + +export function groupInviteFailureName(error: unknown) { + return error instanceof GroupInviteClientError ? error.code : 'Unknown' +} + +export function getGroupInviteFeedMutations( + feeds: GroupInviteFeed[], + savedFeeds: AppBskyActorDefs.SavedFeed[] = [], + selectedUris?: ReadonlySet, +) { + const savedByValue = new Map(savedFeeds.map(feed => [feed.value, feed])) + const readable = feeds.filter( + feed => + feed.canView && + Boolean(feed.uri) && + (selectedUris === undefined || selectedUris.has(feed.uri)), + ) + return { + toAdd: readable + .filter(feed => !savedByValue.has(feed.uri)) + .map(feed => ({type: 'feed' as const, value: feed.uri, pinned: true})), + toUpdate: readable + .map(feed => savedByValue.get(feed.uri)) + .filter((feed): feed is AppBskyActorDefs.SavedFeed => + Boolean(feed && !feed.pinned), + ) + .map(feed => ({...feed, pinned: true})), + } +} diff --git a/src/lib/api/group-invites.ts b/src/lib/api/group-invites.ts new file mode 100644 index 000000000..b1819d76e --- /dev/null +++ b/src/lib/api/group-invites.ts @@ -0,0 +1,280 @@ +import {type AtpAgent} from '@atproto/api' + +import {ACORN_SERVICE_URL} from '#/env' +import {getServiceAuthToken} from './service-auth' + +export const GROUP_INVITE_LXM = 'community.blacksky.group.acceptInvite' + +export const GroupInviteError = { + InviteUnavailable: 'InviteUnavailable', + GroupAtCapacity: 'GroupAtCapacity', + AuthenticationRequired: 'AuthenticationRequired', + AuthorizationUnavailable: 'AuthorizationUnavailable', + InviteMisconfigured: 'InviteMisconfigured', + RateLimitExceeded: 'RateLimitExceeded', +} as const + +export type GroupInviteErrorCode = + (typeof GroupInviteError)[keyof typeof GroupInviteError] + +export class GroupInviteClientError extends Error { + readonly code: GroupInviteErrorCode + + constructor(code: GroupInviteErrorCode) { + super(code) + this.name = 'GroupInviteClientError' + this.code = code + } +} + +export type GroupInvitePreview = { + community: {did: string; name: string} + group: {name: string; displayName: string} + expiresAt: string +} + +export type GroupInviteFeed = { + uri: string + name: string + canView: boolean + canPost: boolean +} + +export type GroupInviteAcceptance = { + communityDid: string + groupName: string + membership: 'joined' + feeds: GroupInviteFeed[] +} + +type TrpcEnvelope = { + result?: {data?: unknown} + error?: { + message?: string + json?: {message?: string; data?: {code?: string}} + } +} + +function isRecord(value: unknown): value is Record { + return Boolean(value && typeof value === 'object' && !Array.isArray(value)) +} + +function isNonEmptyString(value: unknown): value is string { + return typeof value === 'string' && value.length > 0 +} + +function isAuthenticationError(error: unknown): boolean { + if (!error || typeof error !== 'object') return false + const value = error as { + status?: unknown + error?: unknown + name?: unknown + } + return ( + value.status === 401 || + value.error === 'AuthenticationRequired' || + value.name === 'AuthenticationRequired' + ) +} + +function parsePreview(value: unknown): GroupInvitePreview { + if (!isRecord(value)) { + throw new GroupInviteClientError(GroupInviteError.AuthorizationUnavailable) + } + const community = value.community + const group = value.group + if ( + !isRecord(community) || + !isNonEmptyString(community.did) || + !isNonEmptyString(community.name) || + !isRecord(group) || + !isNonEmptyString(group.name) || + !isNonEmptyString(group.displayName) || + !isNonEmptyString(value.expiresAt) + ) { + throw new GroupInviteClientError(GroupInviteError.AuthorizationUnavailable) + } + return { + community: {did: community.did, name: community.name}, + group: {name: group.name, displayName: group.displayName}, + expiresAt: value.expiresAt, + } +} + +function parseAcceptance(value: unknown): GroupInviteAcceptance { + if (!isRecord(value) || value.membership !== 'joined') { + throw new GroupInviteClientError(GroupInviteError.AuthorizationUnavailable) + } + if ( + !isNonEmptyString(value.communityDid) || + !isNonEmptyString(value.groupName) || + !Array.isArray(value.feeds) + ) { + throw new GroupInviteClientError(GroupInviteError.AuthorizationUnavailable) + } + const feeds: GroupInviteFeed[] = [] + for (const feed of value.feeds) { + if ( + !isRecord(feed) || + !isNonEmptyString(feed.uri) || + !isNonEmptyString(feed.name) || + typeof feed.canView !== 'boolean' || + typeof feed.canPost !== 'boolean' || + (!feed.canView && feed.canPost) + ) { + throw new GroupInviteClientError( + GroupInviteError.AuthorizationUnavailable, + ) + } + feeds.push({ + uri: feed.uri, + name: feed.name, + canView: feed.canView, + canPost: feed.canPost, + }) + } + return { + communityDid: value.communityDid, + groupName: value.groupName, + membership: 'joined', + feeds, + } +} + +function unwrapResult(value: unknown): unknown { + if (!value || typeof value !== 'object') return undefined + const data = (value as {result?: {data?: unknown}}).result?.data + if (data && typeof data === 'object' && 'json' in data) { + return data.json + } + return data +} + +function stableCodeFromResponse(body: TrpcEnvelope): GroupInviteErrorCode { + const message = body.error?.json?.message || body.error?.message + const stableMessage = mapStableCode(message) + if (stableMessage) return stableMessage + return ( + mapStableCode(body.error?.json?.data?.code) ?? + GroupInviteError.AuthorizationUnavailable + ) +} + +function mapStableCode( + raw: string | undefined, +): GroupInviteErrorCode | undefined { + switch (raw) { + case 'InviteUnavailable': + case 'INVITE_UNAVAILABLE': + case 'BAD_REQUEST': + case 'NOT_FOUND': + return GroupInviteError.InviteUnavailable + case 'GroupAtCapacity': + case 'GROUP_AT_CAPACITY': + case 'CONFLICT': + return GroupInviteError.GroupAtCapacity + case 'AuthenticationRequired': + case 'AUTHENTICATION_REQUIRED': + case 'UNAUTHORIZED': + return GroupInviteError.AuthenticationRequired + case 'RateLimitExceeded': + case 'RATE_LIMIT_EXCEEDED': + case 'TOO_MANY_REQUESTS': + return GroupInviteError.RateLimitExceeded + case 'InviteMisconfigured': + case 'INVITE_MISCONFIGURED': + return GroupInviteError.InviteMisconfigured + case 'AuthorizationUnavailable': + case 'AUTHORIZATION_UNAVAILABLE': + case 'SERVICE_UNAVAILABLE': + case 'INTERNAL_SERVER_ERROR': + return GroupInviteError.AuthorizationUnavailable + default: + return undefined + } +} + +async function request({ + procedure, + input, + method, + headers, +}: { + procedure: string + input: Record + method: 'GET' | 'POST' + headers?: Record +}): Promise { + const endpoint = `${ACORN_SERVICE_URL.replace(/\/$/, '')}/api/trpc/${procedure}` + // Invite codes are bearer credentials. Keep them in a POST body so they do + // not enter URL/access/referrer logs or browser history. + const url = endpoint + + let response: Response + try { + response = await fetch(url, { + method, + headers: { + Accept: 'application/json', + ...(method === 'POST' ? {'Content-Type': 'application/json'} : {}), + ...headers, + }, + ...(method === 'POST' ? {body: JSON.stringify(input)} : undefined), + }) + } catch { + throw new GroupInviteClientError(GroupInviteError.AuthorizationUnavailable) + } + + const body = (await response.json().catch(() => ({}))) as TrpcEnvelope + if (!response.ok || body.error) { + throw new GroupInviteClientError(stableCodeFromResponse(body)) + } + + const result = unwrapResult(body) + if (result === undefined) { + throw new GroupInviteClientError(GroupInviteError.AuthorizationUnavailable) + } + return result as T +} + +export function previewGroupInvite(code: string) { + return request({ + procedure: 'groupInvites.preview', + input: {code}, + method: 'POST', + }).then(parsePreview) +} + +export async function acceptGroupInvite({ + code, + communityDid, + agent, +}: { + code: string + communityDid: string + agent: AtpAgent +}) { + let token: string + try { + token = await getServiceAuthToken({ + agent, + aud: communityDid, + lxm: GROUP_INVITE_LXM, + exp: Math.floor(Date.now() / 1000) + 60, + }) + } catch (error) { + throw new GroupInviteClientError( + isAuthenticationError(error) + ? GroupInviteError.AuthenticationRequired + : GroupInviteError.AuthorizationUnavailable, + ) + } + + const result = await request({ + procedure: 'groupInvites.accept', + input: {code}, + method: 'POST', + headers: {Authorization: `Bearer ${token}`}, + }) + return parseAcceptance(result) +} diff --git a/src/lib/api/index.ts b/src/lib/api/index.ts index 46a2d8789..8a1f279e2 100644 --- a/src/lib/api/index.ts +++ b/src/lib/api/index.ts @@ -26,6 +26,15 @@ import {CID} from 'multiformats/cid' import * as Hasher from 'multiformats/hashes/hasher' import {communityXrpc} from '#/lib/api/community' +import { + admitFeedPost, + fetchCommunityFeedTarget, + isSpaceBackedFeed, +} from '#/lib/api/community-feed' +import {fetchCommunityPostView} from '#/lib/api/community-post' +import {spaceOfPostUrl} from '#/lib/api/space-permalink' +import {postToSpace} from '#/lib/api/space-post' +import {isSpaceRecordUri, spaceOfRecordUri} from '#/lib/api/space-uri' import {IMAGE_SIZE_CONFIG_POSTS} from '#/lib/constants' import {isNetworkError} from '#/lib/strings/errors' import {shortenLinks, stripInvalidMentions} from '#/lib/strings/rich-text-manip' @@ -52,8 +61,28 @@ export {uploadBlob} const COMMUNITY_POST_COLLECTION = 'community.blacksky.feed.post' -interface PostOpts { +/** + * The space a quote belongs to, whichever form it is in — a pasted permalink + * carries the space in `?space=` and is only expanded to its at:// form at + * publish, long after routing has decided where the post goes. + */ +export function quotedSpace(uri?: string | null): string | null { + return spaceOfRecordUri(uri) ?? spaceOfPostUrl(uri) +} + +function embedNamesSpaceRecord(embed: unknown): boolean { + if (!embed || typeof embed !== 'object') return false + const record = (embed as {record?: unknown}).record + if (!record || typeof record !== 'object') return false + const uri = + (record as {uri?: unknown}).uri ?? + (record as {record?: {uri?: unknown}}).record?.uri + return typeof uri === 'string' && isSpaceRecordUri(uri) +} + +export interface PostOpts { thread: ThreadDraft + draftId?: string replyTo?: string onStateChange?: (state: string) => void langs?: string[] @@ -64,9 +93,60 @@ export async function post( queryClient: QueryClient, opts: PostOpts, ) { - const thread = opts.thread + let thread = opts.thread + const replySpace = spaceOfRecordUri(opts.replyTo) + // Replying to or quoting a space post: the parent's space is the target, and + // no feed needs resolving — a feed is only a view over the space. + if (thread.communitySpaceUri || replySpace) { + const space = thread.communitySpaceUri ?? replySpace! + if ( + thread.communitySpaceUri && + replySpace && + thread.communitySpaceUri !== replySpace + ) { + throw new Error( + t`This reply targets a different private space than its parent.`, + ) + } + return postToSpace(agent, queryClient, space, opts) + } + + if (!thread.communityFeed && thread.communityFeedUri) { + const target = await fetchCommunityFeedTarget( + agent, + thread.communityFeedUri, + ) + if (!target) { + throw new Error( + t`You no longer have permission to post to this community.`, + ) + } + thread = {...thread, communityFeed: target} + opts = {...opts, thread} + } opts.onStateChange?.(t`Processing...`) + // A space-backed feed keeps its content in the author's permissioned repo, + // so it takes an entirely different write path and must be checked before + // the community routing below, which would otherwise claim it. + const config = thread.communityFeed?.config + if (isSpaceBackedFeed(config)) { + return postToSpace(agent, queryClient, config.space, opts) + } + + // Past this point the post is going to a public or community repo, not into + // any space, so nothing it carries may name one. A quote reaches the composer + // as a pasted link and is only expanded to its at:// form at publish, by + // which time the routing decision is made — so both forms are refused here, + // together. Without this a pasted space permalink rides `postCommunity`'s + // stub embed into the author's public repo, publishing the existence of a + // private post. + if (thread.posts.some(p => quotedSpace(p.embed.quote?.uri))) { + throw new Error( + t`This is a private post. You can only quote it in a post to that space.`, + ) + } + // Route to community post endpoint if the user explicitly toggled // Blacksky-Only, is replying to a community post, or is quoting one. const isReplyToCommunityPost = @@ -74,17 +154,28 @@ export async function post( const isQuoteOfCommunityPost = thread.posts.some(p => p.embed.quote?.uri?.includes(COMMUNITY_POST_COLLECTION), ) + const selectedCommunityRecordFeed = + thread.communityFeed?.config.contentType === 'communityRecord' - if (thread.blackskyOnly || isReplyToCommunityPost || isQuoteOfCommunityPost) { + if ( + thread.blackskyOnly || + selectedCommunityRecordFeed || + isReplyToCommunityPost || + isQuoteOfCommunityPost + ) { return postCommunity(agent, queryClient, opts) } // A public post must never carry a community post in its embed; the // routing above sends those to postCommunity, so reaching here with one - // is a bug we refuse rather than leak community content publicly. + // is a bug we refuse rather than leak community content publicly. A space + // record is refused for the same reason, and its URI would leak the space + // even if the appview declined to hydrate it. if ( - thread.posts.some(p => - p.embed.quote?.uri?.includes(COMMUNITY_POST_COLLECTION), + thread.posts.some( + p => + p.embed.quote?.uri?.includes(COMMUNITY_POST_COLLECTION) || + isSpaceRecordUri(p.embed.quote?.uri), ) ) { throw new Error('Public posts cannot embed a community post') @@ -108,6 +199,7 @@ export async function post( const did = agent.assertDid const writes: $Typed[] = [] const uris: string[] = [] + const admissions: Array<{post: string; cid: string}> = [] let now = new Date() let tid: TID | undefined @@ -196,6 +288,9 @@ export async function post( cid: await computeCid(record), uri, } + if (thread.communityFeed?.config.contentType === 'publicRecord') { + admissions.push({post: uri, cid: ref.cid}) + } replyPromise = { root: reply?.root ?? ref, parent: ref, @@ -222,6 +317,14 @@ export async function post( } } + if (thread.communityFeed?.config.contentType === 'publicRecord') { + await Promise.all( + admissions.map(({post, cid}) => + admitFeedPost(agent, thread.communityFeed!, post, cid), + ), + ) + } + return {uris} } @@ -248,6 +351,7 @@ async function postCommunity( const did = agent.assertDid const writes: $Typed[] = [] const uris: string[] = [] + const admissions: Array<{post: string; cid: string}> = [] let now = new Date() let tid: TID | undefined @@ -362,6 +466,10 @@ async function postCommunity( const submitRes = await communityXrpc( agent, 'community.blacksky.feed.submitPost', + // No serviceDid: submitPost serves the Blacksky community feed, whose + // content lives on the home appview. `contentStore` named a per-feed + // appview for the retired multi-tenant path and was always undefined + // here, so the proxy target is unchanged. {body: submitBody}, ) if (!submitRes.ok) { @@ -404,6 +512,14 @@ async function postCommunity( // stub so external-thumb / image / video / gallery blobs stay alive for // the post's lifetime. Text / facets / langs / reply remain appview-only. if (embed) { + // The stub goes to the author's public repo, so it is the last place a + // space URI could leak from. The routing guard in `post` already refuses + // these; this is the invariant restated where the write happens. + if (embedNamesSpaceRecord(embed)) { + throw new Error( + t`This is a private post. You can only quote it in a post to that space.`, + ) + } stubRecord.embed = embed } @@ -419,6 +535,9 @@ async function postCommunity( cid: await computeCid(stubRecord as unknown as AppBskyFeedPost.Record), uri, } + if (thread.communityFeed) { + admissions.push({post: uri, cid: ref.cid}) + } replyPromise = { root: reply?.root ?? ref, parent: ref, @@ -445,13 +564,21 @@ async function postCommunity( } } + if (thread.communityFeed) { + await Promise.all( + admissions.map(({post, cid}) => + admitFeedPost(agent, thread.communityFeed!, post, cid), + ), + ) + } + void queryClient.invalidateQueries({queryKey: ['community-timeline']}) void queryClient.invalidateQueries({queryKey: ['community-feed']}) return {uris} } -async function resolveRT(agent: AtpAgent, richtext: RichText) { +export async function resolveRT(agent: AtpAgent, richtext: RichText) { const trimmedText = richtext.text // Trim leading whitespace-only lines (but don't break ASCII art). .replace(/^(\s*\n)+/, '') @@ -471,7 +598,39 @@ export class ReplyDeletedError extends Error { } } -async function resolveReply(agent: AtpAgent, replyTo: string) { +/** + * The reply refs a caller gets back from the non-space branches go straight + * into a public `app.bsky.feed.post`, so a thread root that turns out to name a + * space has to stop here: the space branch above is the only one allowed to + * return one. + */ +function refusePublicSpaceRefs< + T extends {root: {uri: string}; parent: {uri: string}}, +>(refs: T): T { + if (isSpaceRecordUri(refs.root.uri) || isSpaceRecordUri(refs.parent.uri)) { + throw new Error( + t`This is a private post. You can only reply to it in that space.`, + ) + } + return refs +} + +export async function resolveReply(agent: AtpAgent, replyTo: string) { + // Space records first: they are not at-uris, so AtUri would misparse one. + // The parent is read back through the appview, which is the only read path + // the client has into a space, and carries the root of its own thread. + if (isSpaceRecordUri(replyTo)) { + const post = await fetchCommunityPostView(agent, replyTo) + const parent = {uri: post.uri, cid: post.cid} + const root = ( + post.record as {reply?: {root?: {uri?: string; cid?: string}}} + )?.reply?.root + return { + root: root?.uri && root?.cid ? {uri: root.uri, cid: root.cid} : parent, + parent, + } + } + const replyToUrip = new AtUri(replyTo) // Community posts are fetched from the appview, not the standard feed API. @@ -503,7 +662,7 @@ async function resolveReply(agent: AtpAgent, replyTo: string) { parentRootRef?.uri && parentRootRef?.cid ? {uri: parentRootRef.uri, cid: parentRootRef.cid} : parentRef - return {root: rootRef, parent: parentRef} + return refusePublicSpaceRefs({root: rootRef, parent: parentRef}) } return undefined } @@ -534,13 +693,13 @@ async function resolveReply(agent: AtpAgent, replyTo: string) { } } - return { + return refusePublicSpaceRefs({ root: rootRef, parent: parentRef, - } + }) } -async function resolveEmbed( +export async function resolveEmbed( agent: AtpAgent, queryClient: QueryClient, draft: PostDraft, diff --git a/src/lib/api/resolve.ts b/src/lib/api/resolve.ts index 2c97afbee..5b3bc961d 100644 --- a/src/lib/api/resolve.ts +++ b/src/lib/api/resolve.ts @@ -7,6 +7,9 @@ import { import {AtUri, jsonToLex} from '@atproto/api' import {communityXrpc} from '#/lib/api/community' +import {fetchCommunityPostView} from '#/lib/api/community-post' +import {spacePostUriFromRoute} from '#/lib/api/space-permalink' +import {isSpaceRecordUri} from '#/lib/api/space-uri' import {DM_SERVICE_HEADERS, IMAGE_SIZE_CONFIG_2K_1MB} from '#/lib/constants' import {getLinkMeta, type LinkMeta} from '#/lib/link-meta/link-meta' import {resolveShortLink} from '#/lib/link-meta/resolve-short-link' @@ -100,12 +103,17 @@ const COMMUNITY_POST_COLLECTION = 'community.blacksky.feed.post' // Pull the path portion (without ?query) and the collection from a bsky-style // post URL. Community posts share the /profile//post/ shape with a // ?collection=community.blacksky.feed.post tail. -function splitPostUrl(url: string): {path: string; collection: string} { +function splitPostUrl(url: string): { + path: string + collection: string + space?: string +} { const stripped = convertBskyAppUrlIfNeeded(url) try { const u = new URL(stripped, 'http://_') const collection = u.searchParams.get('collection') || 'app.bsky.feed.post' - return {path: u.pathname, collection} + const space = u.searchParams.get('space') || undefined + return {path: u.pathname, collection, space} } catch { const [path] = stripped.split('?') return {path, collection: 'app.bsky.feed.post'} @@ -116,6 +124,10 @@ async function getCommunityPost( agent: AtpAgent, uri: string, ): Promise { + // A space record URI is already fully qualified — and would misparse here. + if (isSpaceRecordUri(uri)) { + return fetchCommunityPostView(agent, uri) + } const urip = new AtUri(uri) if (!urip.host.startsWith('did:')) { const res = await agent.resolveHandle({handle: urip.host}) @@ -145,11 +157,14 @@ export async function resolveLink( uri = await resolveShortLink(uri) } if (isBskyPostUrl(uri)) { - const {path, collection} = splitPostUrl(uri) + const {path, collection, space} = splitPostUrl(uri) const [_0, user, _1, rkey] = path.split('/').filter(Boolean) - const recordUri = makeRecordUri(user, collection, rkey) + // A `?space=` link addresses a record inside a permissioned space, which + // is read back through the appview like any other community post. + const spaceUri = spacePostUriFromRoute(space, user, rkey, collection) + const recordUri = spaceUri ?? makeRecordUri(user, collection, rkey) const post = - collection === COMMUNITY_POST_COLLECTION + spaceUri || collection === COMMUNITY_POST_COLLECTION ? await getCommunityPost(agent, recordUri) : await getPost({uri: recordUri}) if (post.viewer?.embeddingDisabled) { diff --git a/src/lib/api/service-auth.ts b/src/lib/api/service-auth.ts new file mode 100644 index 000000000..8806de5c3 --- /dev/null +++ b/src/lib/api/service-auth.ts @@ -0,0 +1,26 @@ +import {type AtpAgent} from '@atproto/api' + +import {getServiceAuthAudFromUrl} from '#/lib/strings/url-helpers' + +export async function getServiceAuthToken({ + agent, + aud, + lxm, + exp, +}: { + agent: AtpAgent + aud?: string + lxm: string + exp?: number +}) { + const pdsAud = getServiceAuthAudFromUrl(agent.dispatchUrl) + if (!pdsAud) { + throw new Error('Agent does not have a PDS URL') + } + const {data: serviceAuth} = await agent.com.atproto.server.getServiceAuth({ + aud: aud ?? pdsAud, + lxm, + exp, + }) + return serviceAuth.token +} diff --git a/src/lib/api/space-feed.ts b/src/lib/api/space-feed.ts new file mode 100644 index 000000000..99d27338d --- /dev/null +++ b/src/lib/api/space-feed.ts @@ -0,0 +1,45 @@ +import {type BskyAgent, jsonToLex} from '@atproto/api' + +import {communityXrpc} from '#/lib/api/community' +import {type SpaceFeedPage, toSpaceFeedPage} from '#/lib/api/space-views' + +export const GET_SPACE_FEED = 'community.blacksky.feed.getSpaceFeed' + +/** + * Thrown when a space-backed feed is opened without a session. The message is + * the `KnownError.FeedSignedInOnly` token so `detectKnownError` renders the + * sign-in-required state; the alternative — falling through to the public + * `api.bsky.app` fetch the standard custom-feed path uses when logged out — + * would ask a public appview for private content and leave the feed spinning. + */ +export const signInRequiredError = () => new Error('FeedSignedInOnly') + +/** + * The private read for a space-backed feed. + * + * `feed` is still the ordinary public `app.bsky.feed.generator` at-uri: the + * generator record remains the feed's identity, so no saved-feed preference + * needs migrating. Only the query chosen for that URI changes. The record URIs + * inside the response are space URIs and are never parsed here. + */ +export async function fetchSpaceFeed( + agent: BskyAgent, + feed: string, + {cursor, limit}: {cursor?: string; limit?: number} = {}, +): Promise { + const params: Record = {feed} + if (cursor) params.cursor = cursor + if (limit) params.limit = String(limit) + + const res = await communityXrpc(agent, GET_SPACE_FEED, {params}) + if (!res.ok) { + const body = (await res.json().catch(() => ({}))) as { + error?: string + message?: string + } + // Surfaced verbatim so an access refusal stays an access refusal: an empty + // page here would report "no posts" for "no access". + throw new Error(body.message || body.error || `HTTP ${res.status}`) + } + return toSpaceFeedPage(jsonToLex(await res.json())) +} diff --git a/src/lib/api/space-permalink.ts b/src/lib/api/space-permalink.ts new file mode 100644 index 000000000..af3c9db45 --- /dev/null +++ b/src/lib/api/space-permalink.ts @@ -0,0 +1,61 @@ +import {AtUri} from '@atproto/api' + +import { + parseSpaceUri, + spaceRecordAuthor, + spaceRecordUri, +} from '#/lib/api/space-uri' +import {POST_COLLECTION} from '#/lib/api/space-write' + +/** + * Rebuild a space post's URI from the parts a route carries. + * + * A space record URI has seven segments, of which the path supplies only the + * author and the rkey; the space itself rides in `?space=`. Returns null when + * the pieces do not add up — including when `author` is still a handle, which + * the caller must resolve to a DID first, since the URI form admits only DIDs. + */ +/** + * True when a link addresses a post inside a permissioned space. + * + * A space permalink is an ordinary-looking post URL — the space rides in + * `?space=`, so nothing about the path distinguishes it. Anything that decides + * where a post is written has to test the link form as well as the at:// form, + * because a pasted link is still a link when it reaches the composer. + */ +export function spaceOfPostUrl(url?: string | null): string | null { + if (!url) return null + try { + const space = new URL(url, 'http://_').searchParams.get('space') + return parseSpaceUri(space) ? space : null + } catch { + return null + } +} + +export function isSpacePostUrl(url?: string | null): boolean { + return !!spaceOfPostUrl(url) +} + +export function spacePostUriFromRoute( + space: string | undefined, + author: string, + rkey: string, + collection: string = POST_COLLECTION, +): string | null { + if (!space) return null + const ref = parseSpaceUri(space) + if (!ref || !author.startsWith('did:')) return null + return spaceRecordUri({...ref, authorDid: author, collection, rkey}) +} + +/** Read the author from either an ordinary post URI or a space record URI. */ +export function postUriAuthor(uri: string): string | null { + const spaceAuthor = spaceRecordAuthor(uri) + if (spaceAuthor) return spaceAuthor + try { + return new AtUri(uri).host + } catch { + return null + } +} diff --git a/src/lib/api/space-post.ts b/src/lib/api/space-post.ts new file mode 100644 index 000000000..535d89cc9 --- /dev/null +++ b/src/lib/api/space-post.ts @@ -0,0 +1,130 @@ +import {type AppBskyFeedPost, type AtpAgent} from '@atproto/api' +import {ensureValidRecordKey} from '@atproto/syntax' +import {t} from '@lingui/core/macro' +import {type QueryClient} from '@tanstack/react-query' + +import { + type PostOpts, + quotedSpace, + resolveEmbed, + resolveReply, + resolveRT, +} from '#/lib/api/index' +import {POST_COLLECTION, spaceCreateRecord} from '#/lib/api/space-write' + +/** + * Post a thread into a permissioned space. + * + * Deliberately not a branch inside `postCommunity`: that function implements + * the Blacksky community feed's three-step write (submit to the appview, write + * a public stub, admit to the feed generator), and none of those steps exist + * here. A space post is one ordinary `app.bsky.feed.post` written into the + * author's own permissioned repo; the syncer materialises it into the feed. + * + * Records are built as raw JSON rather than through typed builders, because a + * reply within a space refers to space URIs, which are not valid at-uris and + * would fail SDK-side validation. + */ +export async function postToSpace( + agent: AtpAgent, + queryClient: QueryClient, + space: string, + opts: PostOpts, +): Promise<{uris: string[]}> { + const thread = opts.thread + const langs = opts.langs?.slice(0, 3) + const uris: string[] = [] + + if (thread.posts.some(draft => draft.embed.media)) { + throw new Error( + t`Photos, videos, and GIFs are not available in private spaces yet.`, + ) + } + + // Read access is uniform within a space but not across spaces, so quoting + // another space's post here would name a private post to people who cannot + // see it. Same space is fine — everyone reading this record can already read + // the quoted one. + const foreign = thread.posts + .map(p => quotedSpace(p.embed.quote?.uri)) + .find(quoted => quoted && quoted !== space) + if (foreign) { + throw new Error( + t`This is a private post from another space. You can only quote it in a post to that space.`, + ) + } + + // Threads are written in order: each reply refers to the space URI the host + // returned for the post before it, so they cannot be batched. + let root: {uri: string; cid: string} | undefined + let parent: {uri: string; cid: string} | undefined + + // Replying into the space: the first draft hangs off the post being replied + // to, and everything after it hangs off its predecessor as usual. + if (opts.replyTo) { + const replyRef = await resolveReply(agent, opts.replyTo) + if (replyRef) { + root = replyRef.root + parent = replyRef.parent + } + } + + for (const [index, draft] of thread.posts.entries()) { + const rt = await resolveRT(agent, draft.richtext) + const embed = await resolveEmbed( + agent, + queryClient, + draft, + opts.onStateChange, + ) + + const record: Record = { + $type: POST_COLLECTION, + text: rt.text, + createdAt: new Date().toISOString(), + } + if (rt.facets?.length) record.facets = rt.facets + if (langs?.length) record.langs = langs + if (embed) record.embed = embed + if (draft.labels.length) { + record.labels = { + $type: 'com.atproto.label.defs#selfLabels', + values: draft.labels.map(val => ({val})), + } + } + if (root && parent) { + record.reply = {root, parent} + } + + opts.onStateChange?.(t`Posting to the private feed...`) + const rkey = opts.draftId ? `${opts.draftId}-${index}` : draft.id + ensureValidRecordKey(rkey) + const written = await spaceCreateRecord( + agent, + space, + POST_COLLECTION, + record, + rkey, + ) + + uris.push(written.uri) + root ??= written + parent = written + } + + return {uris} +} + +/** + * Threadgates and postgates are not written into a space. + * + * The public gate records address posts by at-uri and are enforced where + * public content is hydrated, neither of which applies here. The composer + * hides the controls; this exists so a caller that still holds gate state + * knows it is intentionally dropped rather than silently lost. + */ +export function spacePostsIgnoreGates(): true { + return true +} + +export type {AppBskyFeedPost} diff --git a/src/lib/api/space-uri.ts b/src/lib/api/space-uri.ts new file mode 100644 index 000000000..6fe54f8ad --- /dev/null +++ b/src/lib/api/space-uri.ts @@ -0,0 +1,117 @@ +/** + * Permissioned-space URIs (proposal 0016 addressing). + * + * space: at://{spaceDid}/space/{spaceType}/{skey} + * record: at://{spaceDid}/space/{spaceType}/{skey}/{authorDid}/{collection}/{rkey} + * + * These are NOT valid at-uris. `@atproto/syntax` caps an at-uri at + * authority/collection/rkey and requires the collection to be an NSID, and + * `space` has no dots — so both forms fail `format: at-uri` validation and + * misparse in `AtUri`. Never hand a space URI to `AtUri`; use this instead. + * + * Deliberately dependency-free: the appview, the client and both syncers need + * the same parser, and a copy that imports nothing can be vendored verbatim. + * The appview keeps the same parser at + * `packages/bsky/src/api/community/blacksky/space-uri.ts`; the two differ only + * where each repo's formatter differs. Any behavioral change goes in both. + */ + +/** The literal segment that marks a URI as addressing permissioned data. */ +export const SPACE_MARKER = 'space' + +const AT_PREFIX = 'at://' + +export type SpaceRef = { + spaceDid: string + spaceType: string + skey: string +} + +export type SpaceRecordRef = SpaceRef & { + authorDid: string + collection: string + rkey: string +} + +/** + * True when `uri` addresses permissioned data, in either form. + * + * A public at-uri can never collide: its second segment is a collection NSID, + * which always contains at least one dot, and `space` contains none. + */ +export const isSpaceUri = (uri?: string | null): boolean => { + if (!uri || !uri.startsWith(AT_PREFIX)) return false + const parts = uri.slice(AT_PREFIX.length).split('/') + return (parts.length === 4 || parts.length === 7) && parts[1] === SPACE_MARKER +} + +/** True only for the 7-segment record form. */ +export const isSpaceRecordUri = (uri?: string | null): boolean => + parseSpaceRecordUri(uri) !== null + +const looksLikeDid = (value: string): boolean => + /^did:[a-z]+:[A-Za-z0-9._:%-]*[A-Za-z0-9._-]$/.test(value) + +const isNonEmpty = (value: string): boolean => value.length > 0 + +/** Parse the 4-segment space form. Returns null for anything else. */ +export const parseSpaceUri = (uri?: string | null): SpaceRef | null => { + if (!uri || !uri.startsWith(AT_PREFIX)) return null + const parts = uri.slice(AT_PREFIX.length).split('/') + if (parts.length !== 4 || parts[1] !== SPACE_MARKER) return null + const [spaceDid, , spaceType, skey] = parts + if (!looksLikeDid(spaceDid) || !isNonEmpty(spaceType) || !isNonEmpty(skey)) { + return null + } + return {spaceDid, spaceType, skey} +} + +/** + * Parse the 7-segment record form. Returns null for anything else — including + * the 4-segment space form, a public at-uri, and near-misses at 6 or 8 + * segments. + */ +export const parseSpaceRecordUri = ( + uri?: string | null, +): SpaceRecordRef | null => { + if (!uri || !uri.startsWith(AT_PREFIX)) return null + const parts = uri.slice(AT_PREFIX.length).split('/') + if (parts.length !== 7 || parts[1] !== SPACE_MARKER) return null + const [spaceDid, , spaceType, skey, authorDid, collection, rkey] = parts + if ( + !looksLikeDid(spaceDid) || + !looksLikeDid(authorDid) || + !isNonEmpty(spaceType) || + !isNonEmpty(skey) || + !isNonEmpty(collection) || + !isNonEmpty(rkey) + ) { + return null + } + return {spaceDid, spaceType, skey, authorDid, collection, rkey} +} + +/** The space a record belongs to, as a URI. */ +export const spaceUriOf = (ref: SpaceRef): string => + `${AT_PREFIX}${ref.spaceDid}/${SPACE_MARKER}/${ref.spaceType}/${ref.skey}` + +/** Build a record URI inside a space. */ +export const spaceRecordUri = (ref: SpaceRecordRef): string => + `${spaceUriOf(ref)}/${ref.authorDid}/${ref.collection}/${ref.rkey}` + +/** + * The author of a space record. Authorship comes from the URI's own + * `authorDid` segment, never from a repo the URI was fetched from. + */ +export const spaceRecordAuthor = (uri?: string | null): string | null => + parseSpaceRecordUri(uri)?.authorDid ?? null + +/** The collection of a space record. */ +export const spaceRecordCollection = (uri?: string | null): string | null => + parseSpaceRecordUri(uri)?.collection ?? null + +/** The space a record URI belongs to, or null if it is not one. */ +export const spaceOfRecordUri = (uri?: string | null): string | null => { + const parsed = parseSpaceRecordUri(uri) + return parsed ? spaceUriOf(parsed) : null +} diff --git a/src/lib/api/space-views.ts b/src/lib/api/space-views.ts new file mode 100644 index 000000000..0a27dc4ca --- /dev/null +++ b/src/lib/api/space-views.ts @@ -0,0 +1,93 @@ +import {type AppBskyFeedDefs} from '@atproto/api' + +/** + * The private read contract's wire types, mapped back onto the shapes the feed + * UI already renders. + * + * A permissioned-space record URI is not an at-uri, so the appview cannot + * return one inside `app.bsky.feed.defs#postView`, whose `uri` is declared + * `format: at-uri`. Its private endpoints therefore answer in + * `community.blacksky.feed.defs`, which is structurally the same but declares + * every URI-bearing field a plain string. + * + * These are the same objects under different `$type`s, so the mapping is a + * rename: the alternative is a parallel renderer for private posts, which + * would drift from the public one. Nothing here parses a URI — the whole point + * of the custom types is that these URIs must never reach `AtUri`. + */ + +const DEFS = 'community.blacksky.feed.defs' + +const TYPE_MAP: Record = { + [`${DEFS}#spacePostView`]: 'app.bsky.feed.defs#postView', + [`${DEFS}#spaceRecordView`]: 'app.bsky.embed.record#view', + [`${DEFS}#spaceViewRecord`]: 'app.bsky.embed.record#viewRecord', + [`${DEFS}#spaceViewNotFound`]: 'app.bsky.embed.record#viewNotFound', + [`${DEFS}#spaceViewBlocked`]: 'app.bsky.embed.record#viewBlocked', + [`${DEFS}#spaceRecordWithMediaView`]: 'app.bsky.embed.recordWithMedia#view', + [`${DEFS}#spaceThreadItemPost`]: 'app.bsky.unspecced.defs#threadItemPost', + [`${DEFS}#spaceThreadItemNotFound`]: + 'app.bsky.unspecced.defs#threadItemNotFound', + [`${DEFS}#spaceThreadItemBlocked`]: + 'app.bsky.unspecced.defs#threadItemBlocked', +} + +function isPlainObject(value: unknown): value is Record { + return !!value && typeof value === 'object' && !Array.isArray(value) +} + +function rename(value: unknown): unknown { + if (Array.isArray(value)) return value.map(rename) + if (!isPlainObject(value)) return value + const out: Record = {} + for (const [key, entry] of Object.entries(value)) { + out[key] = + key === '$type' && typeof entry === 'string' + ? (TYPE_MAP[entry] ?? entry) + : rename(entry) + } + return out +} + +/** + * A single item of a private feed page. Returns undefined when the item is not + * structurally a feed item, so one malformed row cannot take a page down. + */ +export function toFeedViewPost( + item: unknown, +): AppBskyFeedDefs.FeedViewPost | undefined { + if (!isPlainObject(item)) return undefined + const post = item.post + if (!isPlainObject(post) || typeof post.uri !== 'string') return undefined + return rename(item) as AppBskyFeedDefs.FeedViewPost +} + +/** A private post view, from `getCommunityPost` or a private feed row. */ +export function toPostView( + post: unknown, +): AppBskyFeedDefs.PostView | undefined { + if (!isPlainObject(post) || typeof post.uri !== 'string') return undefined + return rename(post) as AppBskyFeedDefs.PostView +} + +export type SpaceFeedPage = { + cursor?: string + feed: AppBskyFeedDefs.FeedViewPost[] +} + +/** The whole `getSpaceFeed` / community-feed body. */ +export function toSpaceFeedPage(body: unknown): SpaceFeedPage { + const source = isPlainObject(body) ? body : {} + const feed = Array.isArray(source.feed) ? source.feed : [] + return { + cursor: typeof source.cursor === 'string' ? source.cursor : undefined, + feed: feed + .map(toFeedViewPost) + .filter((item): item is AppBskyFeedDefs.FeedViewPost => !!item), + } +} + +/** The `thread`/`hasOtherReplies` body of a private thread read. */ +export function toSpaceThreadBody(body: unknown): unknown { + return rename(body) +} diff --git a/src/lib/api/space-write.ts b/src/lib/api/space-write.ts new file mode 100644 index 000000000..a541356ea --- /dev/null +++ b/src/lib/api/space-write.ts @@ -0,0 +1,233 @@ +import {type BskyAgent} from '@atproto/api' +import {TID} from '@atproto/common-web' + +import {parseSpaceRecordUri, spaceUriOf} from '#/lib/api/space-uri' + +/** + * Writes into a permissioned space. + * + * A space record goes to the account's **own PDS**. The local stack does not + * implement the 0016 PDS methods yet, so development may point these requests + * at its same-origin edge instead. That means **no `atproto-proxy` header**: + * proxying would send the write to the appview, which is not where this + * content lives. The request remains DPoP-signed by the agent, and the space + * host verifies that token itself. + * + * Records are sent as raw JSON rather than through typed builders. A like or a + * reply inside a space refers to other space records, whose URIs are not valid + * at-uris, so SDK-side lexicon validation would reject them; the receiving + * host stores records shape-agnostically and the syncers validate instead. + */ + +export const SPACE_CREATE_RECORD = 'com.atproto.space.createRecord' +export const SPACE_DELETE_RECORD = 'com.atproto.space.deleteRecord' +export const SPACE_GET_RECORD = 'com.atproto.space.getRecord' + +export const POST_COLLECTION = 'app.bsky.feed.post' +export const LIKE_COLLECTION = 'app.bsky.feed.like' + +const LOCAL_SPACE_XRPC_ORIGIN = + __DEV__ && + process.env.NODE_ENV !== 'test' && + process.env.EXPO_PUBLIC_SPACE_XRPC_ORIGIN + +export type SpaceWriteResult = { + uri: string + cid: string +} + +/** Raised when the PDS does not serve the space methods at all. */ +export class SpaceUnsupportedError extends Error { + constructor() { + super('This account’s server does not support private feeds yet') + this.name = 'SpaceUnsupportedError' + } +} + +async function spaceXrpc( + agent: BskyAgent, + method: string, + body: unknown, +): Promise { + const path = `/xrpc/${method}` + const url = LOCAL_SPACE_XRPC_ORIGIN + ? `${LOCAL_SPACE_XRPC_ORIGIN}${path}` + : path + return agent.fetchHandler(url, { + method: 'POST', + // Deliberately no `atproto-proxy`: this write belongs to the account's own + // PDS, not the appview. + headers: {'Content-Type': 'application/json'}, + body: JSON.stringify(body), + }) +} + +async function spaceQuery( + agent: BskyAgent, + method: string, + params: Record, +): Promise { + const path = `/xrpc/${method}?${new URLSearchParams(params)}` + const url = LOCAL_SPACE_XRPC_ORIGIN + ? `${LOCAL_SPACE_XRPC_ORIGIN}${path}` + : path + return agent.fetchHandler(url, {method: 'GET'}) +} + +function authenticatedRepo(agent: BskyAgent): string { + const repo = agent.session?.did + if (!repo) { + throw new Error('Sign in before writing to a private space') + } + return repo +} + +type XrpcErrorBody = {message?: string; error?: string} + +async function errorBody(response: Response): Promise { + return (await response.json().catch(() => ({}))) as XrpcErrorBody +} + +function failure(response: Response, body: XrpcErrorBody): never { + // A PDS that has never heard of the space methods answers 404 rather than an + // XRPC error, which is how a foreign-PDS account is recognised. + if (response.status === 404) { + throw new SpaceUnsupportedError() + } + throw new Error(body.message || body.error || `HTTP ${response.status}`) +} + +async function existingRecord( + agent: BskyAgent, + space: string, + repo: string, + collection: string, + rkey: string, +): Promise { + const response = await spaceQuery(agent, SPACE_GET_RECORD, { + space, + repo, + collection, + rkey, + }) + if (!response.ok) return failure(response, await errorBody(response)) + const data = (await response.json()) as Partial + if (!data.uri || !data.cid) { + throw new Error('Space host returned no record reference') + } + return {uri: data.uri, cid: data.cid} +} + +/** Create a record in the caller's permissioned repo within `space`. */ +export async function spaceCreateRecord( + agent: BskyAgent, + space: string, + collection: string, + record: Record, + rkey?: string, +): Promise { + const repo = authenticatedRepo(agent) + const recordKey = rkey ?? TID.nextStr() + const response = await spaceXrpc(agent, SPACE_CREATE_RECORD, { + space, + repo, + collection, + record, + rkey: recordKey, + }) + if (!response.ok) { + const body = await errorBody(response) + if (body.error === 'RecordExists') { + return existingRecord(agent, space, repo, collection, recordKey) + } + return failure(response, body) + } + const data = (await response.json()) as Partial + if (!data.uri || !data.cid) { + throw new Error('Space host returned no record reference') + } + return {uri: data.uri, cid: data.cid} +} + +/** Delete one of the caller's own records from `space`. */ +export async function spaceDeleteRecord( + agent: BskyAgent, + space: string, + collection: string, + rkey: string, +): Promise { + const repo = authenticatedRepo(agent) + const response = await spaceXrpc(agent, SPACE_DELETE_RECORD, { + space, + repo, + collection, + rkey, + }) + if (!response.ok) return failure(response, await errorBody(response)) +} + +/** + * Like a post inside a space. + * + * The like is written into the **permissioned repo**, never the public one: a + * public like whose subject is a space URI would announce that the private + * post exists, and to whom. + */ +export async function spaceLike( + agent: BskyAgent, + space: string, + subject: {uri: string; cid: string}, +): Promise { + return spaceCreateRecord(agent, space, LIKE_COLLECTION, { + $type: LIKE_COLLECTION, + subject: {uri: subject.uri, cid: subject.cid}, + createdAt: new Date().toISOString(), + }) +} + +/** Remove a like previously written into `space`. */ +export async function spaceUnlike( + agent: BskyAgent, + space: string, + likeUri: string, +): Promise { + const rkey = likeUri.split('/').pop() + if (!rkey) throw new Error(`Unusable like uri: ${likeUri}`) + return spaceDeleteRecord(agent, space, LIKE_COLLECTION, rkey) +} + +/* + * The three interactions below answer `null` for anything that is not a space + * record, so a caller reads as `spaceX(...) ?? publicX(...)`. The routing lives + * here rather than in the mutation hooks so it can be tested without them. + */ + +/** Like `uri` in its own space, or null if it is not a space record. */ +export function spaceLikeIfSpace( + agent: BskyAgent, + uri: string, + cid: string, +): Promise | null { + const ref = parseSpaceRecordUri(uri) + return ref ? spaceLike(agent, spaceUriOf(ref), {uri, cid}) : null +} + +/** Undo a like held in a space, or null if `likeUri` is not a space record. */ +export function spaceUnlikeIfSpace( + agent: BskyAgent, + likeUri: string, +): Promise | null { + const ref = parseSpaceRecordUri(likeUri) + return ref ? spaceUnlike(agent, spaceUriOf(ref), likeUri) : null +} + +/** Delete one's own space record, or null if `uri` is not one. */ +export function spaceDeleteIfSpace( + agent: BskyAgent, + uri: string, +): Promise | null { + const ref = parseSpaceRecordUri(uri) + return ref + ? spaceDeleteRecord(agent, spaceUriOf(ref), ref.collection, ref.rkey) + : null +} diff --git a/src/lib/constants.ts b/src/lib/constants.ts index cfdeae2f2..f9d7e16de 100644 --- a/src/lib/constants.ts +++ b/src/lib/constants.ts @@ -9,7 +9,9 @@ export const LOCAL_DEV_SERVICE = export const STAGING_SERVICE = 'https://staging.bsky.dev' export const BSKY_SERVICE = 'https://blacksky.app' export const BSKY_SERVICE_DID = 'did:web:bsky.social' -export const PUBLIC_BSKY_SERVICE = 'https://api.blacksky.community' +export const PUBLIC_BSKY_SERVICE = + (__DEV__ && process.env.EXPO_PUBLIC_APPVIEW_URL) || + 'https://api.blacksky.community' export const DEFAULT_SERVICE = BSKY_SERVICE // Handle suffixes that identify a Latinsky-community account living on the shared @@ -24,6 +26,7 @@ export const CHAT_SERVICE = 'https://api.bsky.chat' export const EMBED_SERVICE = 'https://embed.bsky.app' export const EMBED_SCRIPT = `${EMBED_SERVICE}/static/embed.js` export const BSKY_DOWNLOAD_URL = 'https://blacksky.community/download' +export const ACCOUNT_MIGRATION_URL = 'https://move.blacksky.community' export const STARTER_PACK_MAX_SIZE = 150 export const CARD_ASPECT_RATIO = 1200 / 630 diff --git a/src/lib/hooks/__tests__/useOpenComposer-context.test.tsx b/src/lib/hooks/__tests__/useOpenComposer-context.test.tsx new file mode 100644 index 000000000..b7cdb3006 --- /dev/null +++ b/src/lib/hooks/__tests__/useOpenComposer-context.test.tsx @@ -0,0 +1,144 @@ +import {Pressable} from 'react-native' +import {fireEvent, render, waitFor} from '@testing-library/react-native' + +import {type FeedDescriptor} from '#/state/queries/post-feed' + +const mockRootOpenComposer = jest.fn() +const mockUseCommunityPostTargets = jest.fn() + +jest.mock('#/lib/hooks/useRequireEmailVerification', () => ({ + useRequireEmailVerification: + () => + (callback: (...args: unknown[]) => unknown) => + (...args: unknown[]) => + callback(...args), +})) +jest.mock('#/state/shell/composer', () => ({ + useOpenComposer: () => ({openComposer: mockRootOpenComposer}), +})) +jest.mock('#/state/queries/community-post-targets', () => ({ + useCommunityPostTargets: (feed?: unknown) => + mockUseCommunityPostTargets(feed), +})) +jest.mock('@lingui/react', () => ({Trans: () => null})) + +import {useOpenComposer} from '../useOpenComposer' + +const FEED_URI = 'at://did:plc:test/app.bsky.feed.generator/private' +const FEED_DESCRIPTOR = `feedgen|${FEED_URI}` as FeedDescriptor +const PRIVATE_TARGET = { + feed: FEED_URI, + name: 'Private Test', + serviceDid: 'did:web:feeds.test', + config: { + $type: 'community.blacksky.feed.config', + contentType: 'communityRecord', + visibility: 'gated', + space: 'at://did:plc:test/space/community.blacksky.feed/private', + group: 'members', + createdAt: '2026-08-29T00:00:00.000Z', + }, +} +function OpenComposerHarness({ + opts = {}, + contextualFeed, +}: { + opts?: Record + contextualFeed?: FeedDescriptor +}) { + const {openComposer} = useOpenComposer(contextualFeed) + return ( + { + void openComposer(opts) + }} + /> + ) +} + +describe('useOpenComposer selected feed context', () => { + beforeEach(() => { + jest.clearAllMocks() + mockUseCommunityPostTargets.mockReturnValue({data: [PRIVATE_TARGET]}) + }) + + it('captures the active private Home feed for shared FAB/sidebar entry points', async () => { + const {getByLabelText} = render( + , + ) + + fireEvent.press(getByLabelText('Open composer')) + + await waitFor(() => { + expect(mockUseCommunityPostTargets).toHaveBeenCalledWith(FEED_DESCRIPTOR) + expect(mockRootOpenComposer).toHaveBeenCalledWith({ + contextualCommunityFeedTarget: PRIVATE_TARGET, + }) + }) + }) + + it('opens from the global keyboard shortcut path outside a navigator', async () => { + const {getByLabelText} = render() + + fireEvent.press(getByLabelText('Open composer')) + + await waitFor(() => { + expect(mockUseCommunityPostTargets).toHaveBeenCalledWith(undefined) + expect(mockRootOpenComposer).toHaveBeenCalledWith({}) + }) + }) + + it('waits for the authoritative target lookup before opening', async () => { + const refetch = jest.fn().mockResolvedValue({data: [PRIVATE_TARGET]}) + mockUseCommunityPostTargets.mockReturnValue({data: undefined, refetch}) + const {getByLabelText} = render( + , + ) + + fireEvent.press(getByLabelText('Open composer')) + + await waitFor(() => { + expect(refetch).toHaveBeenCalled() + expect(mockRootOpenComposer).toHaveBeenCalledWith({ + contextualCommunityFeedTarget: PRIVATE_TARGET, + }) + }) + }) + + it('does not capture a selected feed without a permissioned space', async () => { + mockUseCommunityPostTargets.mockReturnValue({ + data: [ + { + ...PRIVATE_TARGET, + config: {...PRIVATE_TARGET.config, space: undefined}, + }, + ], + }) + const {getByLabelText} = render( + , + ) + + fireEvent.press(getByLabelText('Open composer')) + + await waitFor(() => { + expect(mockRootOpenComposer).toHaveBeenCalledWith({}) + }) + }) + + it.each([ + ['a reply', {replyTo: {uri: 'at://did:plc:test/post/1'}}], + ['a quote', {quote: {uri: 'at://did:plc:test/post/1'}}], + ])('does not leak selected-feed context into %s', async (_, opts) => { + const {getByLabelText} = render( + , + ) + + fireEvent.press(getByLabelText('Open composer')) + + await waitFor(() => { + expect(mockRootOpenComposer).toHaveBeenCalledWith(opts) + }) + }) +}) diff --git a/src/lib/hooks/useIntentHandler.ts b/src/lib/hooks/useIntentHandler.ts index 8fefe3a24..1a62362c1 100644 --- a/src/lib/hooks/useIntentHandler.ts +++ b/src/lib/hooks/useIntentHandler.ts @@ -5,7 +5,12 @@ import * as WebBrowser from 'expo-web-browser' import {useOpenComposer} from '#/lib/hooks/useOpenComposer' import {parseLinkingUrl} from '#/lib/parseLinkingUrl' -import {CHAT_INVITE_CODE_REGEX} from '#/lib/strings/url-helpers' +import { + CHAT_INVITE_CODE_REGEX, + GROUP_INVITE_CODE_REGEX, + shouldHandleIncomingIntentUrl, +} from '#/lib/strings/url-helpers' +import {usePrefetchGroupInvitePreview} from '#/state/queries/group-invites' import {usePrefetchJoinLinkPreviews} from '#/state/queries/join-links' import {useSession} from '#/state/session' import {useSetActiveLanding} from '#/state/shell/landing' @@ -30,6 +35,7 @@ export function useIntentHandler() { const composeIntent = useComposeIntent() const verifyEmailIntent = useVerifyEmailIntent() const groupChatJoinIntent = useGroupChatJoinIntent() + const groupInviteIntent = useGroupInviteIntent() const {currentAccount} = useSession() const {tryApplyUpdate} = useApplyPullRequestOTAUpdate() @@ -40,20 +46,25 @@ export function useIntentHandler() { await WebBrowser.dismissBrowser().catch(() => {}) } - const referrerInfo = Referrer.getReferrerInfo() - if (referrerInfo && referrerInfo.hostname !== 'bsky.app') { - ax.metric('deepLink:referrerReceived', { - to: url, - referrer: referrerInfo?.referrer, - hostname: referrerInfo?.hostname, - }) - } const urlp = parseLinkingUrl(url) const chatInviteMatch = urlp.pathname.match(CHAT_INVITE_CODE_REGEX) if (chatInviteMatch) { groupChatJoinIntent(chatInviteMatch[1], url) return } + const groupInviteMatch = urlp.pathname.match(GROUP_INVITE_CODE_REGEX) + if (groupInviteMatch) { + groupInviteIntent(groupInviteMatch[1]) + return + } + const referrerInfo = Referrer.getReferrerInfo() + if (referrerInfo && referrerInfo.hostname !== 'bsky.app') { + ax.metric('deepLink:referrerReceived', { + to: url, + referrer: referrerInfo.referrer, + hostname: referrerInfo.hostname, + }) + } const [, intent, intentType] = urlp.pathname.split('/') // On native, our links look like blacksky://intent/SomeIntent, so we have to check the hostname for the @@ -97,24 +108,73 @@ export function useIntentHandler() { } } - if (incomingUrl) { - if (previousIntentUrl === incomingUrl) { + const processIncomingURL = (url: string, fromLinkEvent: boolean) => { + if ( + !shouldHandleIncomingIntentUrl(url, previousIntentUrl, fromLinkEvent) + ) { return } - handleIncomingURL(incomingUrl) - previousIntentUrl = incomingUrl + previousIntentUrl = url + void handleIncomingURL(url) } + + const subscription = Linking.addEventListener('url', event => { + processIncomingURL(event.url, true) + }) + if (incomingUrl) processIncomingURL(incomingUrl, false) + + return () => subscription.remove() }, [ incomingUrl, ax, composeIntent, verifyEmailIntent, groupChatJoinIntent, + groupInviteIntent, currentAccount, tryApplyUpdate, ]) } +export function useGroupInviteIntent() { + const closeAllActiveElements = useCloseAllActiveElements() + const {hasSession} = useSession() + const {groupInviteDialogControl: control, setGroupInviteState: setState} = + useIntentDialogs() + const {requestSwitchToAccount} = useLoggedOutViewControls() + const setActiveLanding = useSetActiveLanding() + const prefetchGroupInvitePreview = usePrefetchGroupInvitePreview() + + return useCallback( + (code: string) => { + closeAllActiveElements() + if (hasSession) { + setActiveLanding(undefined) + setState({code}) + const prefetch = prefetchGroupInvitePreview(code) + void Promise.race([ + prefetch, + new Promise(res => setTimeout(res, 200)), + ]).finally(() => control.open()) + } else { + // The original URL contains the bearer code. It is not needed to + // resume the landing flow and must not be retained in redirect state. + setActiveLanding({type: 'groupinvite', uri: '', code}) + requestSwitchToAccount({requestedAccount: 'groupinvite'}) + } + }, + [ + closeAllActiveElements, + hasSession, + setState, + prefetchGroupInvitePreview, + control, + setActiveLanding, + requestSwitchToAccount, + ], + ) +} + export function useComposeIntent() { const closeAllActiveElements = useCloseAllActiveElements() const {openComposer} = useOpenComposer() diff --git a/src/lib/hooks/useOpenComposer.tsx b/src/lib/hooks/useOpenComposer.tsx index f35b8722d..8088067b1 100644 --- a/src/lib/hooks/useOpenComposer.tsx +++ b/src/lib/hooks/useOpenComposer.tsx @@ -1,12 +1,54 @@ -import {useMemo} from 'react' +import {useCallback, useMemo} from 'react' import {Trans} from '@lingui/react/macro' +import {isSpaceBackedFeed} from '#/lib/api/community-feed' import {useRequireEmailVerification} from '#/lib/hooks/useRequireEmailVerification' -import {useOpenComposer as useRootOpenComposer} from '#/state/shell/composer' +import {useCommunityPostTargets} from '#/state/queries/community-post-targets' +import {type FeedDescriptor} from '#/state/queries/post-feed' +import { + type ComposerOpts, + useOpenComposer as useRootOpenComposer, +} from '#/state/shell/composer' -export function useOpenComposer() { - const {openComposer} = useRootOpenComposer() +export function useOpenComposer(contextualFeed?: FeedDescriptor) { + const {openComposer: rootOpenComposer} = useRootOpenComposer() const requireEmailVerification = useRequireEmailVerification() + const {data: postTargets, refetch: refetchPostTargets} = + useCommunityPostTargets(contextualFeed) + const openComposer = useCallback( + (opts: ComposerOpts) => { + if (!contextualFeed || opts.replyTo || opts.quote) { + rootOpenComposer(opts) + return + } + + const openWithTargets = ( + availableTargets: NonNullable, + ) => { + const contextualCommunityFeedTarget = availableTargets.find( + target => + `feedgen|${target.feed}` === contextualFeed && + isSpaceBackedFeed(target.config), + ) + + rootOpenComposer( + contextualCommunityFeedTarget + ? {...opts, contextualCommunityFeedTarget} + : opts, + ) + } + + if (postTargets) { + openWithTargets(postTargets) + } else { + void refetchPostTargets().then(result => { + openWithTargets(result.data ?? []) + }) + } + }, + [contextualFeed, postTargets, refetchPostTargets, rootOpenComposer], + ) + return useMemo(() => { return { openComposer: requireEmailVerification(openComposer, { diff --git a/src/lib/media/video/upload.shared.ts b/src/lib/media/video/upload.shared.ts index f8aaa1249..eb4c917b1 100644 --- a/src/lib/media/video/upload.shared.ts +++ b/src/lib/media/video/upload.shared.ts @@ -2,34 +2,11 @@ import {type AtpAgent} from '@atproto/api' import {type I18n} from '@lingui/core' import {msg} from '@lingui/core/macro' +import {getServiceAuthToken} from '#/lib/api/service-auth' import {VIDEO_SERVICE_DID} from '#/lib/constants' import {UploadLimitError} from '#/lib/media/video/errors' -import {getServiceAuthAudFromUrl} from '#/lib/strings/url-helpers' import {createVideoAgent} from './util' -export async function getServiceAuthToken({ - agent, - aud, - lxm, - exp, -}: { - agent: AtpAgent - aud?: string - lxm: string - exp?: number -}) { - const pdsAud = getServiceAuthAudFromUrl(agent.dispatchUrl) - if (!pdsAud) { - throw new Error('Agent does not have a PDS URL') - } - const {data: serviceAuth} = await agent.com.atproto.server.getServiceAuth({ - aud: aud ?? pdsAud, - lxm, - exp, - }) - return serviceAuth.token -} - export async function getVideoUploadLimits(agent: AtpAgent, i18n: I18n) { const token = await getServiceAuthToken({ agent, diff --git a/src/lib/media/video/upload.ts b/src/lib/media/video/upload.ts index 721ee7f94..c3504d379 100644 --- a/src/lib/media/video/upload.ts +++ b/src/lib/media/video/upload.ts @@ -4,10 +4,11 @@ import {type I18n} from '@lingui/core' import {msg} from '@lingui/core/macro' import {nanoid} from 'nanoid/non-secure' +import {getServiceAuthToken} from '#/lib/api/service-auth' import {AbortError} from '#/lib/async/cancelable' import {ServerError} from '#/lib/media/video/errors' import {type CompressedVideo} from '#/lib/media/video/types' -import {getServiceAuthToken, getVideoUploadLimits} from './upload.shared' +import {getVideoUploadLimits} from './upload.shared' import {createVideoEndpointUrl, mimeToExt} from './util' export async function uploadVideo({ diff --git a/src/lib/media/video/upload.web.ts b/src/lib/media/video/upload.web.ts index 59c6f6597..271827c5e 100644 --- a/src/lib/media/video/upload.web.ts +++ b/src/lib/media/video/upload.web.ts @@ -3,10 +3,11 @@ import {type I18n} from '@lingui/core' import {msg} from '@lingui/core/macro' import {nanoid} from 'nanoid/non-secure' +import {getServiceAuthToken} from '#/lib/api/service-auth' import {AbortError} from '#/lib/async/cancelable' import {ServerError} from '#/lib/media/video/errors' import {type CompressedVideo} from '#/lib/media/video/types' -import {getServiceAuthToken, getVideoUploadLimits} from './upload.shared' +import {getVideoUploadLimits} from './upload.shared' import {createVideoEndpointUrl, mimeToExt} from './util' export async function uploadVideo({ diff --git a/src/lib/routes/links.ts b/src/lib/routes/links.ts index 549e179d4..b1a7e4d94 100644 --- a/src/lib/routes/links.ts +++ b/src/lib/routes/links.ts @@ -1,5 +1,7 @@ import {type AppBskyGraphDefs, AtUri} from '@atproto/api' +import {parseSpaceRecordUri, spaceUriOf} from '#/lib/api/space-uri' + export function makeProfileLink( info: { did: string @@ -10,6 +12,32 @@ export function makeProfileLink( return [`/profile`, info.did, ...segments].join('/') } +/** + * The in-app path for a post, whatever kind it is. + * + * Three shapes share one route: a public post, the community stub (which + * carries its collection as a query param), and a permissioned-space record, + * whose URI has seven segments and cannot be rebuilt from the path alone — + * so the space it belongs to rides along as `?space=`. The author DID and + * rkey come from the path exactly as they always have. + */ +export function postPermalink( + author: {did: string; handle: string}, + postUri: string, + ...segments: string[] +): string { + const spaceRef = parseSpaceRecordUri(postUri) + if (spaceRef) { + const base = makeProfileLink(author, 'post', spaceRef.rkey, ...segments) + return `${base}?space=${encodeURIComponent(spaceUriOf(spaceRef))}` + } + const urip = new AtUri(postUri) + const base = makeProfileLink(author, 'post', urip.rkey, ...segments) + return urip.collection && urip.collection !== 'app.bsky.feed.post' + ? `${base}?collection=${urip.collection}` + : base +} + export function makeCustomFeedLink( did: string, rkey: string, diff --git a/src/lib/routes/types.ts b/src/lib/routes/types.ts index 70c801d2d..a22e33c70 100644 --- a/src/lib/routes/types.ts +++ b/src/lib/routes/types.ts @@ -22,14 +22,20 @@ export type CommonNavigatorParams = { ProfileKnownFollowers: {name: string} ProfileSearch: {name: string; q?: string} ProfileList: {name: string; rkey: string} - PostThread: {name: string; rkey: string; collection?: string} - PostLikedBy: {name: string; rkey: string; collection?: string} - PostRepostedBy: {name: string; rkey: string; collection?: string} - PostQuotes: {name: string; rkey: string; collection?: string} + PostThread: {name: string; rkey: string; collection?: string; space?: string} + PostLikedBy: {name: string; rkey: string; collection?: string; space?: string} + PostRepostedBy: { + name: string + rkey: string + collection?: string + space?: string + } + PostQuotes: {name: string; rkey: string; collection?: string; space?: string} ProfileFeed: { name: string rkey: string feedCacheKey?: 'discover' | 'explore' | undefined + resolvedFeed?: string } ProfileFeedLikedBy: {name: string; rkey: string} ProfileLabelerLikedBy: {name: string} diff --git a/src/lib/strings/__tests__/group-invite-url.test.ts b/src/lib/strings/__tests__/group-invite-url.test.ts new file mode 100644 index 000000000..d5109c539 --- /dev/null +++ b/src/lib/strings/__tests__/group-invite-url.test.ts @@ -0,0 +1,29 @@ +import {describe, expect, it} from '@jest/globals' + +import { + getGroupInviteCodeFromUrl, + GROUP_INVITE_CODE_REGEX, + isBskyGroupInviteUrl, +} from '../url-helpers' + +const CODE = 'a'.repeat(43) + +describe('group invite URLs', () => { + it('accepts the exact client deep-link shape', () => { + expect(GROUP_INVITE_CODE_REGEX.test(`/join/${CODE}`)).toBe(true) + expect( + getGroupInviteCodeFromUrl(`https://blacksky.community/join/${CODE}`), + ).toBe(CODE) + expect(isBskyGroupInviteUrl(`/join/${CODE}?from=message`)).toBe(true) + }) + + it.each([ + `/join/${'a'.repeat(42)}`, + `/join/${'a'.repeat(44)}`, + `/join/${'a'.repeat(42)}!`, + `/join/${'a'.repeat(42)}%2F`, + `/join/${'a'.repeat(43)}/extra`, + ])('rejects malformed group invite URL %s', url => { + expect(getGroupInviteCodeFromUrl(url)).toBeUndefined() + }) +}) diff --git a/src/lib/strings/__tests__/url-helpers.test.ts b/src/lib/strings/__tests__/url-helpers.test.ts new file mode 100644 index 000000000..ffc39a96a --- /dev/null +++ b/src/lib/strings/__tests__/url-helpers.test.ts @@ -0,0 +1,27 @@ +import {describe, expect, it} from '@jest/globals' + +import { + getDeepLinkAnalyticsTarget, + shouldHandleIncomingIntentUrl, +} from '../url-helpers' + +const URL = 'https://bsky.app/join/' + 'a'.repeat(43) + +describe('incoming intent URL handling', () => { + it('reopens the same group invite for a new warm-app link event', () => { + expect(shouldHandleIncomingIntentUrl(URL, URL, true)).toBe(true) + expect(shouldHandleIncomingIntentUrl(URL, URL, false)).toBe(false) + }) + + it('continues deduplicating repeated non-invite URLs', () => { + const url = 'https://bsky.app/profile/alice' + expect(shouldHandleIncomingIntentUrl(url, url, true)).toBe(false) + }) + + it('removes group invite bearer codes from analytics targets', () => { + expect(getDeepLinkAnalyticsTarget(URL)).toBe('group-invite') + expect(getDeepLinkAnalyticsTarget('https://bsky.app/profile/alice')).toBe( + 'https://bsky.app/profile/alice', + ) + }) +}) diff --git a/src/lib/strings/url-helpers.ts b/src/lib/strings/url-helpers.ts index 9b07881b9..48568f703 100644 --- a/src/lib/strings/url-helpers.ts +++ b/src/lib/strings/url-helpers.ts @@ -2,6 +2,7 @@ import {AtUri} from '@atproto/api' import {parse} from 'psl' import TLDs from 'tlds' +import {parseSpaceRecordUri, spaceUriOf} from '#/lib/api/space-uri' import {DEFAULT_BRAND_CONFIG} from '#/lib/community/BrandContext' import {BSKY_SERVICE} from '#/lib/constants' import {isInvalidHandle} from '#/lib/strings/handles' @@ -215,6 +216,53 @@ export function isBskyStarterPackUrl(url: string): boolean { // Invite codes are 7 alphanumeric characters long, supporting up to 10 here to future-proof. export const CHAT_INVITE_CODE_REGEX = /^\/chat\/([a-zA-Z0-9]{7,10})$/ +export const GROUP_INVITE_CODE_REGEX = /^\/join\/([A-Za-z0-9_-]{43})$/ + +/** + * Linking can emit an already-seen URL again after a warm-app tap. The hook + * listener is the authoritative event source for that case; the URL-state + * effect must not process the same event a second time. + */ +export function shouldHandleIncomingIntentUrl( + url: string, + previousUrl: string, + fromLinkEvent: boolean, +): boolean { + if (url !== previousUrl) return true + try { + const isGroupInvite = GROUP_INVITE_CODE_REGEX.test( + new URL(url, BSKY_APP_HOST).pathname, + ) + return isGroupInvite && fromLinkEvent + } catch { + return false + } +} + +export function getGroupInviteCodeFromUrl(url: string): string | undefined { + let pathname: string + if (isBskyAppUrl(url)) { + try { + pathname = new URL(url).pathname + } catch { + return undefined + } + } else if (url.startsWith('/')) { + pathname = url.split('?')[0].split('#')[0] + } else { + return undefined + } + return pathname.match(GROUP_INVITE_CODE_REGEX)?.[1] +} + +export function isBskyGroupInviteUrl(url: string): boolean { + return getGroupInviteCodeFromUrl(url) !== undefined +} + +export function getDeepLinkAnalyticsTarget(url: string): string { + return isBskyGroupInviteUrl(url) ? 'group-invite' : url +} + export function getChatInviteCodeFromUrl(url: string): string | undefined { let pathname: string if (isBskyAppUrl(url)) { @@ -284,6 +332,13 @@ export function postUriToRelativePath( uri: string, options?: {handle?: string}, ): string | undefined { + // A space record URI has seven segments and misparses in AtUri. Its author + // and rkey come out of the URI itself; the space rides in the query, which + // is what rebuilds it on the way back. + const spaceRef = parseSpaceRecordUri(uri) + if (spaceRef) { + return `/profile/${spaceRef.authorDid}/post/${spaceRef.rkey}?space=${encodeURIComponent(spaceUriOf(spaceRef))}` + } try { const {hostname, rkey, collection} = new AtUri(uri) const handleOrDid = diff --git a/src/screens/GroupInviteLanding.tsx b/src/screens/GroupInviteLanding.tsx new file mode 100644 index 000000000..202e7ebd4 --- /dev/null +++ b/src/screens/GroupInviteLanding.tsx @@ -0,0 +1,108 @@ +import {useEffect} from 'react' +import {View} from 'react-native' +import {Trans, useLingui} from '@lingui/react/macro' + +import { + groupInviteErrorCopy, + shouldTrackGroupInviteOpened, +} from '#/lib/api/group-invite-ui' +import {useGroupInvitePreviewQuery} from '#/state/queries/group-invites' +import {useActiveGroupInvite} from '#/state/shell/landing' +import {LoggedOutScreenState} from '#/view/com/auth/LoggedOut' +import {Logo} from '#/view/icons/Logo' +import {atoms as a, useTheme} from '#/alf' +import {Button, ButtonText} from '#/components/Button' +import {Loader} from '#/components/Loader' +import {Text} from '#/components/Typography' +import {useAnalytics} from '#/analytics' + +export function GroupInviteLanding({ + setScreenState, +}: { + setScreenState: (state: LoggedOutScreenState) => void +}) { + const {t: l} = useLingui() + const ax = useAnalytics() + const t = useTheme() + const landing = useActiveGroupInvite() + const {data, error, isPending, refetch} = useGroupInvitePreviewQuery( + landing?.code, + ) + + useEffect(() => { + if (landing?.code && shouldTrackGroupInviteOpened(landing.code)) { + ax.metric('groupInvite:opened', {hasSession: false}) + } + }, [ax, landing?.code]) + + return ( + + + + {isPending ? ( + + ) : error ? ( + + {groupInviteErrorCopy(error)} + + + ) : data ? ( + <> + + Group invite + + + {data.group.displayName} + + + {data.community.name} + + + ) : null} + + + + + + + ) +} diff --git a/src/screens/Login/LoginForm.tsx b/src/screens/Login/LoginForm.tsx index 18a26767e..7e1e51a54 100644 --- a/src/screens/Login/LoginForm.tsx +++ b/src/screens/Login/LoginForm.tsx @@ -26,22 +26,26 @@ import * as TextField from '#/components/forms/TextField' import {At_Stroke2_Corner0_Rounded as At} from '#/components/icons/At' import {Loader} from '#/components/Loader' import {Text} from '#/components/Typography' +import {IS_E2E} from '#/env' import {FormContainer} from './FormContainer' export const LoginForm = ({ error, + serviceUrl, serviceDescription, initialHandle, setError, onPressBack, }: { error: string + serviceUrl: string serviceDescription: ComAtprotoServerDescribeServer.OutputSchema | undefined initialHandle: string setError: (v: string) => void onPressBack: () => void }) => { const [isProcessing, setIsProcessing] = useState(false) + const [password, setPassword] = useState('') const [awaitingRedirect, setAwaitingRedirect] = useState(false) const abortRef = useRef(null) const processingRef = useRef(false) @@ -144,6 +148,31 @@ export const LoginForm = ({ } const signInWithIdentifier = async (identifier: string) => { + if (IS_E2E) { + if (!password) { + setError(_(msg`Please enter your password`)) + return + } + setIsProcessing(true) + try { + await login({service: serviceUrl, identifier, password}, 'LoginForm') + } catch (e) { + const errMsg = String(e) + if (isNetworkError(e)) { + setError( + _( + msg`Unable to contact your service. Please check your Internet connection.`, + ), + ) + } else { + setError(cleanError(errMsg)) + } + } finally { + setIsProcessing(false) + } + return + } + const client = getOAuthClient() const controller = Platform.OS === 'android' ? new AbortController() : null if (controller) { @@ -249,6 +278,27 @@ export const LoginForm = ({ + {IS_E2E && ( + + + Password + + + void onPressNext()} + editable={!isProcessing} + /> + + + )} {handleOptions && ( diff --git a/src/screens/Login/index.tsx b/src/screens/Login/index.tsx index 6456a8704..d1b20ca4e 100644 --- a/src/screens/Login/index.tsx +++ b/src/screens/Login/index.tsx @@ -129,6 +129,7 @@ export const Login = ({ content = ( export const PostLikedByScreen = ({route}: Props) => { - const {name, rkey, collection} = route.params - const uri = makeRecordUri(name, collection || 'app.bsky.feed.post', rkey) + return +} + +function PostLikedByRoute({ + name, + rkey, + collection, + space, +}: CommonNavigatorParams['PostLikedBy']) { + const needsDid = !!space && !name.startsWith('did:') + const {data: resolvedDid, isPending} = useResolveDidQuery( + needsDid ? name : undefined, + ) + const uri = + needsDid && isPending + ? undefined + : (space && + spacePostUriFromRoute( + space, + needsDid ? resolvedDid || '' : name, + rkey, + collection, + )) || + makeRecordUri(name, collection || 'app.bsky.feed.post', rkey) const {data: post} = usePostQuery(uri) + if (!uri) return null let likeCount if (post) { diff --git a/src/screens/Post/PostQuotes.tsx b/src/screens/Post/PostQuotes.tsx index 7328c6ad9..f4d09ca33 100644 --- a/src/screens/Post/PostQuotes.tsx +++ b/src/screens/Post/PostQuotes.tsx @@ -1,19 +1,44 @@ import {Plural, Trans} from '@lingui/react/macro' +import {spacePostUriFromRoute} from '#/lib/api/space-permalink' import { type CommonNavigatorParams, type NativeStackScreenProps, } from '#/lib/routes/types' import {makeRecordUri} from '#/lib/strings/url-helpers' import {usePostQuery} from '#/state/queries/post' +import {useResolveDidQuery} from '#/state/queries/resolve-uri' import {PostQuotes as PostQuotesComponent} from '#/view/com/post-thread/PostQuotes' import * as Layout from '#/components/Layout' type Props = NativeStackScreenProps export const PostQuotesScreen = ({route}: Props) => { - const {name, rkey, collection} = route.params - const uri = makeRecordUri(name, collection || 'app.bsky.feed.post', rkey) + return +} + +function PostQuotesRoute({ + name, + rkey, + collection, + space, +}: CommonNavigatorParams['PostQuotes']) { + const needsDid = !!space && !name.startsWith('did:') + const {data: resolvedDid, isPending} = useResolveDidQuery( + needsDid ? name : undefined, + ) + const uri = + needsDid && isPending + ? undefined + : (space && + spacePostUriFromRoute( + space, + needsDid ? resolvedDid || '' : name, + rkey, + collection, + )) || + makeRecordUri(name, collection || 'app.bsky.feed.post', rkey) const {data: post} = usePostQuery(uri) + if (!uri) return null let quoteCount if (post) { diff --git a/src/screens/Post/PostRepostedBy.tsx b/src/screens/Post/PostRepostedBy.tsx index 40a7beb7e..8d1c2c4bd 100644 --- a/src/screens/Post/PostRepostedBy.tsx +++ b/src/screens/Post/PostRepostedBy.tsx @@ -1,19 +1,44 @@ import {Plural, Trans} from '@lingui/react/macro' +import {spacePostUriFromRoute} from '#/lib/api/space-permalink' import { type CommonNavigatorParams, type NativeStackScreenProps, } from '#/lib/routes/types' import {makeRecordUri} from '#/lib/strings/url-helpers' import {usePostQuery} from '#/state/queries/post' +import {useResolveDidQuery} from '#/state/queries/resolve-uri' import {PostRepostedBy as PostRepostedByComponent} from '#/view/com/post-thread/PostRepostedBy' import * as Layout from '#/components/Layout' type Props = NativeStackScreenProps export const PostRepostedByScreen = ({route}: Props) => { - const {name, rkey, collection} = route.params - const uri = makeRecordUri(name, collection || 'app.bsky.feed.post', rkey) + return +} + +function PostRepostedByRoute({ + name, + rkey, + collection, + space, +}: CommonNavigatorParams['PostRepostedBy']) { + const needsDid = !!space && !name.startsWith('did:') + const {data: resolvedDid, isPending} = useResolveDidQuery( + needsDid ? name : undefined, + ) + const uri = + needsDid && isPending + ? undefined + : (space && + spacePostUriFromRoute( + space, + needsDid ? resolvedDid || '' : name, + rkey, + collection, + )) || + makeRecordUri(name, collection || 'app.bsky.feed.post', rkey) const {data: post} = usePostQuery(uri) + if (!uri) return null let quoteCount if (post) { diff --git a/src/screens/PostThread/components/ThreadItemAnchor.tsx b/src/screens/PostThread/components/ThreadItemAnchor.tsx index 8e772da18..55898d6cb 100644 --- a/src/screens/PostThread/components/ThreadItemAnchor.tsx +++ b/src/screens/PostThread/components/ThreadItemAnchor.tsx @@ -4,14 +4,16 @@ import { AppBskyFeedDefs, AppBskyFeedPost, type AppBskyFeedThreadgate, - AtUri, RichText as RichTextAPI, } from '@atproto/api' import {Plural, Trans, useLingui} from '@lingui/react/macro' +import {getCommunitySpaceUri} from '#/lib/api/community-post' +import {postUriAuthor} from '#/lib/api/space-permalink' +import {isSpaceRecordUri} from '#/lib/api/space-uri' import {useNonReactiveCallback} from '#/lib/hooks/useNonReactiveCallback' import {useOpenComposer} from '#/lib/hooks/useOpenComposer' -import {makeProfileLink} from '#/lib/routes/links' +import {makeProfileLink, postPermalink} from '#/lib/routes/links' import {sanitizeDisplayName} from '#/lib/strings/display-names' import {sanitizeHandle} from '#/lib/strings/handles' import {niceDate} from '#/lib/strings/time' @@ -196,17 +198,17 @@ const ThreadItemAnchorInner = memo(function ThreadItemAnchorInner({ [record], ) - const threadRootUri = record.reply?.root?.uri || post.uri const authorHref = makeProfileLink(post.author) const isThreadAuthor = getThreadAuthor(post, record) === currentAccount?.did const statHref = useCallback( (suffix: string) => { - const urip = new AtUri(post.uri) - const link = makeProfileLink(post.author, 'post', urip.rkey, suffix) - return urip.collection === 'community.blacksky.feed.post' - ? `${link}?collection=${urip.collection}` - : link + // Space likes and quotes have permission-aware endpoints. Reposts remain + // unsupported, so their count deliberately has no destination. + if (isSpaceRecordUri(post.uri) && suffix === 'reposted-by') { + return undefined + } + return postPermalink(post.author, post.uri, suffix) }, [post.uri, post.author], ) @@ -219,8 +221,7 @@ const ThreadItemAnchorInner = memo(function ThreadItemAnchorInner({ }) const additionalPostAlerts: AppModerationCause[] = useMemo(() => { const isPostHiddenByThreadgate = threadgateHiddenReplies.has(post.uri) - const isControlledByViewer = - new AtUri(threadRootUri).host === currentAccount?.did + const isControlledByViewer = isThreadAuthor return isControlledByViewer && isPostHiddenByThreadgate ? [ { @@ -230,7 +231,7 @@ const ThreadItemAnchorInner = memo(function ThreadItemAnchorInner({ }, ] : [] - }, [post, currentAccount?.did, threadgateHiddenReplies, threadRootUri]) + }, [post, currentAccount?.did, isThreadAuthor, threadgateHiddenReplies]) const onlyFollowersCanReply = !!threadgateRecord?.allow?.find( rule => rule.$type === 'app.bsky.feed.threadgate#followerRule', ) @@ -258,6 +259,7 @@ const ThreadItemAnchorInner = memo(function ThreadItemAnchorInner({ embed: post.embed, moderation, langs: record.langs, + communitySpace: getCommunitySpaceUri(post), }, onPostSuccess: onPostSuccess, logContext: 'PostReply', @@ -446,7 +448,7 @@ const ThreadItemAnchorInner = memo(function ThreadItemAnchorInner({ t.atoms.border_contrast_low, ]}> {post.repostCount != null && post.repostCount !== 0 ? ( - + @@ -462,12 +464,12 @@ const ThreadItemAnchorInner = memo(function ThreadItemAnchorInner({ /> - + ) : null} {post.quoteCount != null && post.quoteCount !== 0 && !post.viewer?.embeddingDisabled ? ( - + @@ -483,10 +485,10 @@ const ThreadItemAnchorInner = memo(function ThreadItemAnchorInner({ /> - + ) : null} {post.likeCount != null && post.likeCount !== 0 ? ( - + @@ -502,7 +504,7 @@ const ThreadItemAnchorInner = memo(function ThreadItemAnchorInner({ /> - + ) : null} {post.bookmarkCount != null && post.bookmarkCount !== 0 ? ( ) } + +/** + * A stat that links to its own screen when there is one to link to. + * + * Space posts have no liked-by / reposted-by / quotes screens, so the count + * renders as plain text rather than a link that would 400. + */ +function StatLink({ + to, + label, + children, +}: { + to?: string + label: string + children: React.ReactElement +}) { + if (!to) return children + return ( + + {children} + + ) +} diff --git a/src/screens/PostThread/components/ThreadItemPost.tsx b/src/screens/PostThread/components/ThreadItemPost.tsx index 5ee7d85b2..b15d7c719 100644 --- a/src/screens/PostThread/components/ThreadItemPost.tsx +++ b/src/screens/PostThread/components/ThreadItemPost.tsx @@ -8,9 +8,10 @@ import { } from '@atproto/api' import {Trans} from '@lingui/react/macro' +import {getCommunitySpaceUri} from '#/lib/api/community-post' import {MAX_POST_LINES} from '#/lib/constants' import {useOpenComposer} from '#/lib/hooks/useOpenComposer' -import {makeProfileLink} from '#/lib/routes/links' +import {postPermalink} from '#/lib/routes/links' import {countLines} from '#/lib/strings/helpers' import { POST_TOMBSTONE, @@ -211,10 +212,7 @@ const ThreadItemPostInner = memo(function ThreadItemPostInner({ ) const threadRootUri = record.reply?.root?.uri || post.uri const postHref = useMemo(() => { - const urip = new AtUri(post.uri) - const link = makeProfileLink(post.author, 'post', urip.rkey) - const isCommunity = urip.collection === 'community.blacksky.feed.post' - return isCommunity ? `${link}?collection=${urip.collection}` : link + return postPermalink(post.author, post.uri) }, [post.uri, post.author]) const threadgateHiddenReplies = useMergedThreadgateHiddenReplies({ threadgateRecord, @@ -244,6 +242,7 @@ const ThreadItemPostInner = memo(function ThreadItemPostInner({ embed: post.embed, moderation, langs: post.record.langs, + communitySpace: getCommunitySpaceUri(post), }, onPostSuccess: onPostSuccess, logContext: 'PostReply', diff --git a/src/screens/PostThread/components/ThreadItemTreePost.tsx b/src/screens/PostThread/components/ThreadItemTreePost.tsx index c1125110b..adeda3ec5 100644 --- a/src/screens/PostThread/components/ThreadItemTreePost.tsx +++ b/src/screens/PostThread/components/ThreadItemTreePost.tsx @@ -8,9 +8,10 @@ import { } from '@atproto/api' import {Trans} from '@lingui/react/macro' +import {getCommunitySpaceUri} from '#/lib/api/community-post' import {MAX_POST_LINES} from '#/lib/constants' import {useOpenComposer} from '#/lib/hooks/useOpenComposer' -import {makeProfileLink} from '#/lib/routes/links' +import {postPermalink} from '#/lib/routes/links' import {countLines} from '#/lib/strings/helpers' import { POST_TOMBSTONE, @@ -273,10 +274,7 @@ const ThreadItemTreePostInner = memo(function ThreadItemTreePostInner({ ) const threadRootUri = record.reply?.root?.uri || post.uri const postHref = useMemo(() => { - const urip = new AtUri(post.uri) - const link = makeProfileLink(post.author, 'post', urip.rkey) - const isCommunity = urip.collection === 'community.blacksky.feed.post' - return isCommunity ? `${link}?collection=${urip.collection}` : link + return postPermalink(post.author, post.uri) }, [post.uri, post.author]) const threadgateHiddenReplies = useMergedThreadgateHiddenReplies({ threadgateRecord, @@ -306,6 +304,7 @@ const ThreadItemTreePostInner = memo(function ThreadItemTreePostInner({ embed: post.embed, moderation, langs: post.record.langs, + communitySpace: getCommunitySpaceUri(post), }, onPostSuccess: onPostSuccess, logContext: 'PostReply', diff --git a/src/screens/PostThread/index.tsx b/src/screens/PostThread/index.tsx index 64d652972..02c885525 100644 --- a/src/screens/PostThread/index.tsx +++ b/src/screens/PostThread/index.tsx @@ -10,6 +10,7 @@ import {useWindowDimensions, View} from 'react-native' import Animated, {useAnimatedStyle} from 'react-native-reanimated' import {Trans} from '@lingui/react/macro' +import {getCommunitySpaceUri} from '#/lib/api/community-post' import {useInitialNumToRender} from '#/lib/hooks/useInitialNumToRender' import {useNonReactiveCallback} from '#/lib/hooks/useNonReactiveCallback' import {useOpenComposer} from '#/lib/hooks/useOpenComposer' @@ -131,6 +132,7 @@ export function PostThread({uri}: {uri: string}) { embed: post.embed, moderation: anchor.moderation, langs: post.record.langs, + communitySpace: getCommunitySpaceUri(post), }, onPostSuccess: optimisticOnPostReply, logContext: 'PostReply', diff --git a/src/screens/Profile/ProfileFeed/__tests__/ProfileFeed-composer.test.tsx b/src/screens/Profile/ProfileFeed/__tests__/ProfileFeed-composer.test.tsx new file mode 100644 index 000000000..0070bcff4 --- /dev/null +++ b/src/screens/Profile/ProfileFeed/__tests__/ProfileFeed-composer.test.tsx @@ -0,0 +1,149 @@ +import {QueryClient, QueryClientProvider} from '@tanstack/react-query' +import {fireEvent, render, waitFor} from '@testing-library/react-native' + +import {type FeedSourceFeedInfo} from '#/state/queries/feed' +import {type UsePreferencesQueryResponse} from '#/state/queries/preferences' + +const mockOpenComposer = jest.fn() +const mockUseOpenComposer = jest.fn((_feed?: string) => ({ + openComposer: mockOpenComposer, +})) +const mockSetParams = jest.fn() +const mockUseResolveUriQuery = jest.fn() + +jest.mock('react-native-reanimated', () => ({ + useAnimatedRef: () => ({current: null}), +})) +jest.mock('@react-navigation/native', () => ({ + useIsFocused: () => true, +})) +jest.mock('@lingui/react', () => ({ + useLingui: () => ({ + _: (message: {message?: string} | string) => + typeof message === 'string' ? message : (message.message ?? ''), + }), +})) +jest.mock('#/lib/hooks/useOpenComposer', () => ({ + useOpenComposer: (feed?: string) => mockUseOpenComposer(feed), +})) +jest.mock('#/lib/hooks/useSetTitle', () => ({useSetTitle: jest.fn()})) +jest.mock('#/state/events', () => ({listenSoftReset: jest.fn()})) +jest.mock('#/state/feed-feedback', () => ({ + FeedFeedbackProvider: ({children}: React.PropsWithChildren) => children, + useFeedFeedback: () => ({}), +})) +jest.mock('#/state/queries/feed', () => ({ + useFeedSourceInfoQuery: () => ({data: undefined}), +})) +jest.mock('#/state/queries/preferences', () => ({ + usePreferencesQuery: () => ({data: undefined}), +})) +jest.mock('#/state/queries/post-feed', () => ({ + RQKEY: jest.fn(() => ['post-feed']), +})) +jest.mock('#/state/queries/resolve-uri', () => ({ + useResolveUriQuery: (...args: unknown[]) => mockUseResolveUriQuery(...args), +})) +jest.mock('#/state/session', () => ({ + useSession: () => ({hasSession: true}), +})) +jest.mock('#/view/com/posts/PostFeed', () => ({PostFeed: () => null})) +jest.mock('#/view/com/util/EmptyState', () => ({EmptyState: () => null})) +jest.mock('#/view/com/util/error/ErrorScreen', () => ({ + ErrorScreen: () => null, +})) +jest.mock('#/view/com/util/LoadingPlaceholder', () => ({ + PostFeedLoadingPlaceholder: () => null, +})) +jest.mock('#/view/com/util/load-latest/LoadLatestBtn', () => ({ + LoadLatestBtn: () => null, +})) +jest.mock('#/view/com/util/fab/FAB', () => { + const {Pressable} = require('react-native') + return { + FAB: ({onPress, testID}: {onPress: () => void; testID: string}) => ( + + ), + } +}) +jest.mock('#/screens/Profile/components/ProfileFeedHeader', () => ({ + ProfileFeedHeader: () => null, + ProfileFeedHeaderSkeleton: () => null, +})) +jest.mock('#/components/Layout', () => { + const {View} = require('react-native') + return { + Screen: ({children}: React.PropsWithChildren) => {children}, + Content: ({children}: React.PropsWithChildren) => {children}, + } +}) +jest.mock('#/alf', () => ({ + useTheme: () => ({palette: {white: '#fff'}}), +})) + +import {ProfileFeedScreen, ProfileFeedScreenInner} from '../index' + +const FEED_URI = 'at://did:plc:test/app.bsky.feed.generator/private' +const FEED_DESCRIPTOR = `feedgen|${FEED_URI}` as const +const FEED_INFO = { + type: 'feed', + uri: FEED_URI, + feedDescriptor: FEED_DESCRIPTOR, + displayName: 'Private Test', + contentMode: undefined, +} as unknown as FeedSourceFeedInfo + +function wrapper({children}: React.PropsWithChildren) { + const client = new QueryClient() + return {children} +} + +describe('ProfileFeed composer context', () => { + beforeEach(() => { + jest.clearAllMocks() + mockUseResolveUriQuery.mockReturnValue({ + data: {uri: FEED_URI}, + error: undefined, + refetch: jest.fn(), + isRefetching: false, + }) + }) + + it('passes the resolved active feed to the ProfileFeed FAB composer', () => { + const {getByTestId} = render( + , + {wrapper}, + ) + + expect(mockUseOpenComposer).toHaveBeenCalledWith(FEED_DESCRIPTOR) + fireEvent.press(getByTestId('composeFAB')) + expect(mockOpenComposer).toHaveBeenCalledWith({logContext: 'Fab'}) + }) + + it('publishes the resolved descriptor for the desktop sidebar composer', async () => { + const props = { + route: { + params: {name: 'did:plc:test', rkey: 'private'}, + }, + navigation: {setParams: mockSetParams}, + } as unknown as React.ComponentProps + + render(, {wrapper}) + + await waitFor(() => { + expect(mockSetParams).toHaveBeenCalledWith({ + resolvedFeed: FEED_DESCRIPTOR, + }) + }) + }) +}) diff --git a/src/screens/Profile/ProfileFeed/index.tsx b/src/screens/Profile/ProfileFeed/index.tsx index 6ed5f4b5b..a2f93d622 100644 --- a/src/screens/Profile/ProfileFeed/index.tsx +++ b/src/screens/Profile/ProfileFeed/index.tsx @@ -64,6 +64,13 @@ export function ProfileFeedScreen(props: Props) { refetch, isRefetching, } = useResolveUriQuery(uri) + const resolvedFeed = resolvedUri + ? (`feedgen|${resolvedUri.uri}` as FeedDescriptor) + : undefined + + useEffect(() => { + props.navigation.setParams({resolvedFeed}) + }, [props.navigation, resolvedFeed]) if (error && !isRefetching) { return ( @@ -133,13 +140,13 @@ export function ProfileFeedScreenInner({ }) { const {_} = useLingui() const {hasSession} = useSession() - const {openComposer} = useOpenComposer() const isScreenFocused = useIsFocused() const t = useTheme() useSetTitle(feedInfo?.displayName) const feed = `feedgen|${feedInfo.uri}` as FeedDescriptor + const {openComposer} = useOpenComposer(feed) const [hasNew, setHasNew] = useState(false) const [isScrolledDown, setIsScrolledDown] = useState(false) diff --git a/src/screens/VideoFeed/index.tsx b/src/screens/VideoFeed/index.tsx index 7e760b88d..ba8e02e19 100644 --- a/src/screens/VideoFeed/index.tsx +++ b/src/screens/VideoFeed/index.tsx @@ -43,6 +43,7 @@ import { } from '@react-navigation/native' import {type NativeStackScreenProps} from '@react-navigation/native-stack' +import {getCommunitySpaceUri} from '#/lib/api/community-post' import {HITSLOP_20} from '#/lib/constants' import {useHaptics} from '#/lib/haptics' import {useNonReactiveCallback} from '#/lib/hooks/useNonReactiveCallback' @@ -772,6 +773,7 @@ function Overlay({ author: post.author, embed: post.embed, langs: record?.langs, + communitySpace: getCommunitySpaceUri(post), }, logContext: 'PostReply', }) diff --git a/src/state/cache/__tests__/post-shadow-space.test.ts b/src/state/cache/__tests__/post-shadow-space.test.ts new file mode 100644 index 000000000..17f9f06de --- /dev/null +++ b/src/state/cache/__tests__/post-shadow-space.test.ts @@ -0,0 +1,75 @@ +import {type AppBskyFeedDefs} from '@atproto/api' +import {QueryClient} from '@tanstack/react-query' + +jest.mock('#/state/session', () => ({useAgent: jest.fn()})) +jest.mock('#/state/queries/notifications/feed', () => ({ + findAllPostsInQueryData: function* () {}, +})) +jest.mock('#/view/com/posts/PostFeedErrorMessage', () => ({ + KnownError: {FeedSignedInOnly: 'FeedSignedInOnly'}, +})) +jest.mock('#/state/queries/usePostThread', () => ({ + usePostThreadContext: jest.fn(), +})) + +import { + dangerousGetPostShadow, + updatePostShadow, +} from '#/state/cache/post-shadow' +import {RQKEY_ROOT as POST_FEED_QUERY_KEY_ROOT} from '#/state/queries/post-feed' + +const PUBLIC_POST = 'at://did:plc:alice/app.bsky.feed.post/3kpublic' +const LEGACY_POST = 'at://did:plc:alice/community.blacksky.feed.post/3klegacy' +const SPACE_POST = + 'at://did:plc:space/space/community.blacksky.feed/test/did:plc:alice/app.bsky.feed.post/3kspace' + +function post(uri: string): AppBskyFeedDefs.PostView { + return { + uri, + cid: 'bafyrei post', + author: {did: 'did:plc:alice', handle: 'alice.test'}, + record: {$type: 'app.bsky.feed.post', text: 'hello'}, + indexedAt: '2026-08-27T00:00:00.000Z', + } +} + +function cachePost( + queryClient: QueryClient, + cachedPost: AppBskyFeedDefs.PostView, +) { + queryClient.setQueryData([POST_FEED_QUERY_KEY_ROOT, 'following'], { + pages: [{feed: [{post: cachedPost}]}], + pageParams: [undefined], + }) +} + +describe('post shadow URI matching', () => { + it.each([PUBLIC_POST, LEGACY_POST])( + 'preserves ordinary matching for %s', + uri => { + const queryClient = new QueryClient() + const cachedPost = post(uri) + cachePost(queryClient, cachedPost) + + expect(() => + updatePostShadow(queryClient, uri, {likeUri: `${uri}/like`}), + ).not.toThrow() + expect(dangerousGetPostShadow(cachedPost)?.likeUri).toBe(`${uri}/like`) + }, + ) + + it('updates a cached permissioned-space post without parsing its URI', () => { + const queryClient = new QueryClient() + const cachedPost = post(SPACE_POST) + cachePost(queryClient, cachedPost) + + expect(() => + updatePostShadow(queryClient, SPACE_POST, { + likeUri: 'at://did:plc:alice/app.bsky.feed.like/3klike', + }), + ).not.toThrow() + expect(dangerousGetPostShadow(cachedPost)?.likeUri).toBe( + 'at://did:plc:alice/app.bsky.feed.like/3klike', + ) + }) +}) diff --git a/src/state/queries/__tests__/community-post-targets.test.tsx b/src/state/queries/__tests__/community-post-targets.test.tsx new file mode 100644 index 000000000..3c3d10ee1 --- /dev/null +++ b/src/state/queries/__tests__/community-post-targets.test.tsx @@ -0,0 +1,92 @@ +import {QueryClient, QueryClientProvider} from '@tanstack/react-query' +import {renderHook, waitFor} from '@testing-library/react-native' + +const mockFetchCommunityFeedTarget = jest.fn() +const mockUseSavedFeeds = jest.fn() +const mockAgent = {} + +jest.mock('#/lib/api/community-feed', () => ({ + fetchCommunityFeedTarget: (...args: unknown[]) => + mockFetchCommunityFeedTarget(...args), +})) +jest.mock('#/state/queries/feed', () => ({ + useSavedFeeds: () => mockUseSavedFeeds(), +})) +jest.mock('#/state/session', () => ({ + useAgent: () => mockAgent, + useSession: () => ({currentAccount: {did: 'did:plc:test'}}), +})) + +import {useCommunityPostTargets} from '../community-post-targets' + +const FEED_URI = 'at://did:plc:test/app.bsky.feed.generator/private' +const FEED_DESCRIPTOR = `feedgen|${FEED_URI}` as const +const TARGET = { + feed: FEED_URI, + name: 'Generator fallback', + serviceDid: 'did:web:feeds.test', + config: { + $type: 'community.blacksky.feed.config', + contentType: 'communityRecord', + visibility: 'gated', + space: 'at://did:plc:test/community.blacksky.space/private', + group: 'members', + createdAt: '2026-08-30T00:00:00.000Z', + }, +} + +function wrapper({children}: React.PropsWithChildren) { + const client = new QueryClient({ + defaultOptions: {queries: {retry: false}}, + }) + return {children} +} + +describe('useCommunityPostTargets', () => { + beforeEach(() => { + jest.clearAllMocks() + mockUseSavedFeeds.mockReturnValue({data: {feeds: []}, isLoading: false}) + mockFetchCommunityFeedTarget.mockResolvedValue(TARGET) + }) + + it('authoritatively resolves an unsaved writable contextual feed', async () => { + const {result} = renderHook( + () => useCommunityPostTargets(FEED_DESCRIPTOR), + {wrapper}, + ) + + await waitFor(() => expect(result.current.isSuccess).toBe(true)) + + expect(mockFetchCommunityFeedTarget).toHaveBeenCalledTimes(1) + expect(mockFetchCommunityFeedTarget).toHaveBeenCalledWith( + mockAgent, + FEED_URI, + ) + expect(result.current.data).toEqual([TARGET]) + }) + + it('deduplicates the current feed against saved targets and keeps its saved display name', async () => { + mockUseSavedFeeds.mockReturnValue({ + data: { + feeds: [ + { + type: 'feed', + view: {uri: FEED_URI, displayName: 'Saved display name'}, + }, + ], + }, + isLoading: false, + }) + const {result} = renderHook( + () => useCommunityPostTargets(FEED_DESCRIPTOR), + {wrapper}, + ) + + await waitFor(() => expect(result.current.isSuccess).toBe(true)) + + expect(mockFetchCommunityFeedTarget).toHaveBeenCalledTimes(1) + expect(result.current.data).toEqual([ + {...TARGET, name: 'Saved display name'}, + ]) + }) +}) diff --git a/src/state/queries/__tests__/space-engagement-routing.test.ts b/src/state/queries/__tests__/space-engagement-routing.test.ts new file mode 100644 index 000000000..4055f47d9 --- /dev/null +++ b/src/state/queries/__tests__/space-engagement-routing.test.ts @@ -0,0 +1,106 @@ +import {type BskyAgent} from '@atproto/api' + +const mockGetSpacePostLikes = jest.fn() +const mockGetSpacePostQuotes = jest.fn() + +jest.mock('#/lib/api/community', () => ({ + getSpacePostLikes: (...args: unknown[]) => mockGetSpacePostLikes(...args), + getSpacePostQuotes: (...args: unknown[]) => mockGetSpacePostQuotes(...args), +})) +jest.mock('#/state/session', () => ({useAgent: jest.fn()})) + +import {fetchLikedByPage} from '../post-liked-by' +import {fetchPostQuotesPage} from '../post-quotes' +import {fetchRepostedByPage} from '../post-reposted-by' + +const SPACE = 'at://did:plc:space/space/community.blacksky.feed/test' +const SPACE_POST = `${SPACE}/did:plc:alice/app.bsky.feed.post/3kpost` +const PUBLIC_POST = 'at://did:plc:alice/app.bsky.feed.post/3kpost' +const LEGACY_POST = 'at://did:plc:alice/community.blacksky.feed.post/3kpost' + +function mockAgent() { + const getLikes = jest.fn().mockResolvedValue({ + data: {uri: PUBLIC_POST, likes: []}, + }) + const getQuotes = jest.fn().mockResolvedValue({ + data: {uri: PUBLIC_POST, posts: []}, + }) + const getRepostedBy = jest.fn().mockResolvedValue({ + data: {uri: PUBLIC_POST, repostedBy: []}, + }) + mockGetSpacePostLikes.mockResolvedValue({uri: SPACE_POST, likes: []}) + mockGetSpacePostQuotes.mockResolvedValue({uri: SPACE_POST, posts: []}) + const agent = { + getLikes, + getRepostedBy, + api: {app: {bsky: {feed: {getQuotes}}}}, + } as unknown as BskyAgent + return {agent, getLikes, getQuotes, getRepostedBy} +} + +describe('post engagement routing', () => { + beforeEach(() => { + jest.clearAllMocks() + }) + + it.each([PUBLIC_POST, LEGACY_POST])( + 'keeps likes for %s on the standard endpoint', + async uri => { + const {agent, getLikes} = mockAgent() + + await fetchLikedByPage(agent, uri, 'next') + + expect(getLikes).toHaveBeenCalledWith({ + uri, + limit: 30, + cursor: 'next', + }) + expect(mockGetSpacePostLikes).not.toHaveBeenCalled() + }, + ) + + it.each([PUBLIC_POST, LEGACY_POST])( + 'keeps quotes for %s on the standard endpoint', + async uri => { + const {agent, getQuotes} = mockAgent() + + await fetchPostQuotesPage(agent, uri, 'next') + + expect(getQuotes).toHaveBeenCalledWith({ + uri, + limit: 30, + cursor: 'next', + }) + expect(mockGetSpacePostQuotes).not.toHaveBeenCalled() + }, + ) + + it('uses only the permission-aware endpoints for space engagement', async () => { + const {agent, getLikes, getQuotes} = mockAgent() + + await fetchLikedByPage(agent, SPACE_POST) + await fetchPostQuotesPage(agent, SPACE_POST) + + expect(getLikes).not.toHaveBeenCalled() + expect(getQuotes).not.toHaveBeenCalled() + expect(mockGetSpacePostLikes).toHaveBeenCalledWith(agent, { + uri: SPACE_POST, + limit: 30, + cursor: undefined, + }) + expect(mockGetSpacePostQuotes).toHaveBeenCalledWith(agent, { + uri: SPACE_POST, + limit: 30, + cursor: undefined, + }) + }) + + it('never calls the standard repost endpoint for a space URI', async () => { + const {agent, getRepostedBy} = mockAgent() + + await expect(fetchRepostedByPage(agent, SPACE_POST)).rejects.toThrow( + 'Reposts are not supported for private space posts', + ) + expect(getRepostedBy).not.toHaveBeenCalled() + }) +}) diff --git a/src/state/queries/bookmarks/useBookmarksQuery.ts b/src/state/queries/bookmarks/useBookmarksQuery.ts index 3e8e87a13..706d50e94 100644 --- a/src/state/queries/bookmarks/useBookmarksQuery.ts +++ b/src/state/queries/bookmarks/useBookmarksQuery.ts @@ -2,7 +2,6 @@ import { type $Typed, type AppBskyBookmarkGetBookmarks, AppBskyFeedDefs, - AtUri, } from '@atproto/api' import { type InfiniteData, @@ -12,9 +11,9 @@ import { } from '@tanstack/react-query' import { - didOrHandleUriMatches, embedViewRecordToPostView, getEmbeddedPost, + makeUriMatcher, } from '#/state/queries/util' import {useAgent} from '#/state/session' import * as bsky from '#/types/bsky' @@ -129,7 +128,7 @@ export function* findAllPostsInQueryData( >({ queryKey: [bookmarksQueryKeyRoot], }) - const atUri = new AtUri(uri) + const matches = makeUriMatcher(uri) for (const [_queryKey, queryData] of queryDatas) { if (!queryData?.pages) { @@ -145,12 +144,12 @@ export function* findAllPostsInQueryData( ) continue - if (didOrHandleUriMatches(atUri, bookmark.item)) { + if (matches(bookmark.item)) { yield bookmark.item } const quotedPost = getEmbeddedPost(bookmark.item.embed) - if (quotedPost && didOrHandleUriMatches(atUri, quotedPost)) { + if (quotedPost && matches(quotedPost)) { yield embedViewRecordToPostView(quotedPost) } } diff --git a/src/state/queries/community-feed-permissions.ts b/src/state/queries/community-feed-permissions.ts new file mode 100644 index 000000000..7479767b8 --- /dev/null +++ b/src/state/queries/community-feed-permissions.ts @@ -0,0 +1,23 @@ +import {useQuery} from '@tanstack/react-query' + +import { + type CommunityFeedPermission, + fetchFeedPermissions, +} from '#/lib/api/community-feed' +import {useAgent, useSession} from '#/state/session' + +export const feedPermissionsQueryKey = ( + did: string | undefined, + feed: string, +) => ['community-feed-permissions', did ?? '', feed] + +export function useFeedPermissionsQuery(feed: string) { + const agent = useAgent() + const {currentAccount} = useSession() + return useQuery({ + queryKey: feedPermissionsQueryKey(currentAccount?.did, feed), + enabled: !!currentAccount?.did && !!feed, + staleTime: 60 * 1000, + queryFn: () => fetchFeedPermissions(agent, feed), + }) +} diff --git a/src/state/queries/community-feed.ts b/src/state/queries/community-feed.ts index 1753c6180..e518019e0 100644 --- a/src/state/queries/community-feed.ts +++ b/src/state/queries/community-feed.ts @@ -18,13 +18,15 @@ import { import {communityXrpc} from '#/lib/api/community' import {FeedTuner} from '#/lib/api/feed-manip' +import {spaceRecordAuthor} from '#/lib/api/space-uri' +import {toPostView, toSpaceFeedPage} from '#/lib/api/space-views' import {useModerationOpts} from '#/state/preferences/moderation-opts' import {STALE} from '#/state/queries' import {usePreferencesQuery} from '#/state/queries/preferences' import { - didOrHandleUriMatches, embedViewRecordToPostView, getEmbeddedPost, + makeUriMatcher, } from '#/state/queries/util' import {useAgent} from '#/state/session' @@ -79,7 +81,7 @@ export function useCommunityFeedQuery(actor: string | undefined) { if (!res.ok) { throw new Error(`getCommunityFeed failed: ${res.status}`) } - return jsonToLex(await res.json()) as CommunityFeedPage + return toSpaceFeedPage(jsonToLex(await res.json())) }, initialPageParam: undefined, getNextPageParam: lastPage => lastPage.cursor, @@ -116,7 +118,7 @@ export function useCommunityTimelineQuery(enabled: boolean) { if (!res.ok) { throw new Error(`getCommunityTimeline failed: ${res.status}`) } - return jsonToLex(await res.json()) as CommunityFeedPage + return toSpaceFeedPage(jsonToLex(await res.json())) }, initialPageParam: undefined, getNextPageParam: lastPage => lastPage.cursor, @@ -144,8 +146,8 @@ export async function fetchCommunityTimelineHead( if (!res.ok) { throw new Error(`getCommunityTimeline failed: ${res.status}`) } - const page = jsonToLex(await res.json()) as CommunityFeedPage - return page.feed?.find(surfacesInCommunityFeed) + const page = toSpaceFeedPage(jsonToLex(await res.json())) + return page.feed.find(surfacesInCommunityFeed) } // A reply only resurfaces its thread when the root author is @@ -171,7 +173,11 @@ export function surfacesInCommunityFeed( if (!item.reason && !AppBskyFeedDefs.isPostView(item.reply?.parent)) { return false } - return new AtUri(reply.root.uri).host === item.post.author.did + // A space record URI names its author in its own segment; `AtUri` would + // report the space authority as the host and never match. + const rootAuthor = + spaceRecordAuthor(reply.root.uri) ?? new AtUri(reply.root.uri).host + return rootAuthor === item.post.author.did } const COMMUNITY_POST_RQKEY_ROOT = 'community-post' @@ -193,10 +199,10 @@ export function useCommunityPostQuery(uri: string | undefined) { if (!res.ok) { throw new Error(`getCommunityPost failed: ${res.status}`) } - const data = jsonToLex(await res.json()) as { - post: AppBskyFeedDefs.PostView - } - return data.post + const data = jsonToLex(await res.json()) as {post?: unknown} + const post = toPostView(data.post) + if (!post) throw new Error('Community post not found') + return post }, enabled: !!uri, }) @@ -321,7 +327,7 @@ export function* findAllPostsInQueryData( queryClient: QueryClient, uri: string, ): Generator { - const atUri = new AtUri(uri) + const matches = makeUriMatcher(uri) // Search both actor feeds and timeline const queryDatas = [ @@ -345,25 +351,25 @@ export function* findAllPostsInQueryData( if (!item?.post) { continue } - if (didOrHandleUriMatches(atUri, item.post)) { + if (matches(item.post)) { yield item.post } // Check for quoted posts in embeds const quotedPost = getEmbeddedPost(item.post.embed) - if (quotedPost && didOrHandleUriMatches(atUri, quotedPost)) { + if (quotedPost && matches(quotedPost)) { yield embedViewRecordToPostView(quotedPost) } // Reply-context rows render in slices too; without these, likes on // a parent/root row never reach the shadow cache. if (AppBskyFeedDefs.isPostView(item.reply?.parent)) { - if (didOrHandleUriMatches(atUri, item.reply.parent)) { + if (matches(item.reply.parent)) { yield item.reply.parent } } if (AppBskyFeedDefs.isPostView(item.reply?.root)) { - if (didOrHandleUriMatches(atUri, item.reply.root)) { + if (matches(item.reply.root)) { yield item.reply.root } } diff --git a/src/state/queries/community-post-targets.ts b/src/state/queries/community-post-targets.ts new file mode 100644 index 000000000..cc17df19c --- /dev/null +++ b/src/state/queries/community-post-targets.ts @@ -0,0 +1,48 @@ +import {useQuery} from '@tanstack/react-query' + +import { + type CommunityFeedTarget, + fetchCommunityFeedTarget, +} from '#/lib/api/community-feed' +import {STALE} from '#/state/queries' +import {useSavedFeeds} from '#/state/queries/feed' +import {type FeedDescriptor} from '#/state/queries/post-feed' +import {useAgent, useSession} from '#/state/session' + +export function useCommunityPostTargets(contextualFeed?: FeedDescriptor) { + const agent = useAgent() + const {currentAccount} = useSession() + const {data, isLoading} = useSavedFeeds() + const feeds = (data?.feeds ?? []).filter(item => item.type === 'feed') + const candidates = new Map( + feeds.map(item => [item.view.uri, item.view.displayName] as const), + ) + if (contextualFeed?.startsWith('feedgen|')) { + const currentFeedUri = contextualFeed.slice('feedgen|'.length) + if (!candidates.has(currentFeedUri)) { + candidates.set(currentFeedUri, undefined) + } + } + const candidateFeeds = [...candidates] + + return useQuery({ + queryKey: [ + 'community-post-targets', + currentAccount?.did ?? '', + candidateFeeds, + ], + enabled: !!currentAccount?.did && !isLoading, + staleTime: STALE.MINUTES.FIVE, + queryFn: async () => { + const targets = await Promise.all( + candidateFeeds.map(async ([feed, displayName]) => { + const target = await fetchCommunityFeedTarget(agent, feed) + return target ? {...target, name: displayName ?? target.name} : null + }), + ) + return targets.filter( + (target): target is CommunityFeedTarget => target !== null, + ) + }, + }) +} diff --git a/src/state/queries/explore-feed-previews.tsx b/src/state/queries/explore-feed-previews.tsx index acbc4ee7e..7ba6a6c4d 100644 --- a/src/state/queries/explore-feed-previews.tsx +++ b/src/state/queries/explore-feed-previews.tsx @@ -2,7 +2,6 @@ import {useMemo, useRef} from 'react' import { type AppBskyActorDefs, AppBskyFeedDefs, - AtUri, moderatePost, } from '@atproto/api' import {msg} from '@lingui/core/macro' @@ -24,9 +23,9 @@ import { } from '#/state/queries/post-feed' import {usePreferencesQuery} from '#/state/queries/preferences' import { - didOrHandleUriMatches, embedViewRecordToPostView, getEmbeddedPost, + makeUriMatcher, } from '#/state/queries/util' import {useAgent} from '#/state/session' @@ -350,7 +349,7 @@ export function* findAllPostsInQueryData( queryClient: QueryClient, uri: string, ): Generator { - const atUri = new AtUri(uri) + const matches = makeUriMatcher(uri) const queryDatas = queryClient.getQueriesData< InfiniteData<{ @@ -366,36 +365,33 @@ export function* findAllPostsInQueryData( } for (const page of queryData?.pages) { for (const item of page.posts) { - if (didOrHandleUriMatches(atUri, item.post)) { + if (matches(item.post)) { yield item.post } const quotedPost = getEmbeddedPost(item.post.embed) - if (quotedPost && didOrHandleUriMatches(atUri, quotedPost)) { + if (quotedPost && matches(quotedPost)) { yield embedViewRecordToPostView(quotedPost) } if (AppBskyFeedDefs.isPostView(item.reply?.parent)) { - if (didOrHandleUriMatches(atUri, item.reply.parent)) { + if (matches(item.reply.parent)) { yield item.reply.parent } const parentQuotedPost = getEmbeddedPost(item.reply.parent.embed) - if ( - parentQuotedPost && - didOrHandleUriMatches(atUri, parentQuotedPost) - ) { + if (parentQuotedPost && matches(parentQuotedPost)) { yield embedViewRecordToPostView(parentQuotedPost) } } if (AppBskyFeedDefs.isPostView(item.reply?.root)) { - if (didOrHandleUriMatches(atUri, item.reply.root)) { + if (matches(item.reply.root)) { yield item.reply.root } const rootQuotedPost = getEmbeddedPost(item.reply.root.embed) - if (rootQuotedPost && didOrHandleUriMatches(atUri, rootQuotedPost)) { + if (rootQuotedPost && matches(rootQuotedPost)) { yield embedViewRecordToPostView(rootQuotedPost) } } diff --git a/src/state/queries/feed.ts b/src/state/queries/feed.ts index f016461b3..0f5a38ed1 100644 --- a/src/state/queries/feed.ts +++ b/src/state/queries/feed.ts @@ -21,6 +21,10 @@ import { useQueryClient, } from '@tanstack/react-query' +import { + type CommunityFeedConfig, + fetchCommunityFeedConfig, +} from '#/lib/api/community-feed' import {getProxyHeadersForFeed} from '#/lib/api/feed/utils' import {searchAppviewOpts} from '#/lib/api/search-routing' import {useBrand} from '#/lib/community/BrandContext' @@ -223,6 +227,20 @@ export function useFeedSourceInfoQuery({uri}: {uri: string}) { }) } +export const communityFeedConfigQueryKey = (uri: string) => [ + 'community-feed-config', + uri, +] + +export function useCommunityFeedConfigQuery({uri}: {uri: string}) { + const agent = useAgent() + return useQuery({ + queryKey: communityFeedConfigQueryKey(uri), + staleTime: STALE.INFINITY, + queryFn: () => fetchCommunityFeedConfig(agent, uri), + }) +} + // HACK // the protocol doesn't yet tell us which feeds are personalized // this list is used to filter out feed recommendations from logged out users diff --git a/src/state/queries/group-invites.ts b/src/state/queries/group-invites.ts new file mode 100644 index 000000000..47e5fc3bb --- /dev/null +++ b/src/state/queries/group-invites.ts @@ -0,0 +1,42 @@ +import {useCallback} from 'react' +import {useMutation, useQuery, useQueryClient} from '@tanstack/react-query' + +import {acceptGroupInvite, previewGroupInvite} from '#/lib/api/group-invites' +import {useAgent} from '#/state/session' +import {createQueryKey} from './util' + +export const groupInvitePreviewQueryKey = (code: string) => + createQueryKey('group-invite-preview', {code}, {persistedVersion: 1}) + +export function useGroupInvitePreviewQuery(code?: string) { + return useQuery({ + queryKey: groupInvitePreviewQueryKey(code ?? ''), + queryFn: () => { + if (!code) throw new Error('Missing invite code') + return previewGroupInvite(code) + }, + enabled: Boolean(code), + retry: false, + }) +} + +export function usePrefetchGroupInvitePreview() { + const queryClient = useQueryClient() + return useCallback( + (code: string) => + queryClient.prefetchQuery({ + queryKey: groupInvitePreviewQueryKey(code), + queryFn: () => previewGroupInvite(code), + staleTime: 15_000, + }), + [queryClient], + ) +} + +export function useAcceptGroupInviteMutation() { + const agent = useAgent() + return useMutation({ + mutationFn: ({code, communityDid}: {code: string; communityDid: string}) => + acceptGroupInvite({code, communityDid, agent}), + }) +} diff --git a/src/state/queries/notifications/__tests__/space-subjects.test.ts b/src/state/queries/notifications/__tests__/space-subjects.test.ts new file mode 100644 index 000000000..27dccdc4a --- /dev/null +++ b/src/state/queries/notifications/__tests__/space-subjects.test.ts @@ -0,0 +1,70 @@ +import {type AtpAgent} from '@atproto/api' + +const mockCommunityXrpc = jest.fn() + +jest.mock('@atproto/api', () => ({ + ...jest.requireActual('@atproto/api'), + jsonToLex: (value: unknown) => value, +})) +jest.mock('#/lib/api/community', () => ({ + communityXrpc: (...args: unknown[]) => mockCommunityXrpc(...args), +})) +jest.mock('#/state/queries/profile', () => ({precacheProfile: jest.fn()})) + +import {type FeedNotification} from '../types' +import {fetchSubjects} from '../util' + +const SPACE = 'at://did:plc:space/space/community.blacksky.feed/test' + +const subject = (rkey: string): FeedNotification => { + const uri = `${SPACE}/did:plc:alice/app.bsky.feed.post/${rkey}` + return { + subjectUri: uri, + notification: {}, + } as FeedNotification +} + +describe('space notification subject hydration', () => { + it('routes like, reply, and quote subjects through getCommunityPost', async () => { + const notifications = [subject('like'), subject('reply'), subject('quote')] + mockCommunityXrpc.mockImplementation( + (_agent: AtpAgent, _method: string, opts: {params: {uri: string}}) => + Promise.resolve( + new Response( + JSON.stringify({ + post: { + uri: opts.params.uri, + cid: 'bafypost', + author: {did: 'did:plc:alice', handle: 'alice.test'}, + record: {$type: 'app.bsky.feed.post', text: 'private'}, + indexedAt: '2026-08-27T12:00:00.000Z', + }, + }), + ), + ), + ) + const getPosts = jest.fn() + const getStarterPacks = jest.fn().mockResolvedValue({ + data: {starterPacks: []}, + }) + const agent = { + app: { + bsky: { + feed: {getPosts}, + graph: {getStarterPacks}, + }, + }, + } as unknown as AtpAgent + + const result = await fetchSubjects(agent, notifications) + + expect(mockCommunityXrpc).toHaveBeenCalledTimes(3) + expect(mockCommunityXrpc.mock.calls.map(([, method]) => method)).toEqual([ + 'community.blacksky.feed.getCommunityPost', + 'community.blacksky.feed.getCommunityPost', + 'community.blacksky.feed.getCommunityPost', + ]) + expect(getPosts).not.toHaveBeenCalled() + expect(result.posts.size).toBe(3) + }) +}) diff --git a/src/state/queries/notifications/feed.ts b/src/state/queries/notifications/feed.ts index a81802e56..97091e31e 100644 --- a/src/state/queries/notifications/feed.ts +++ b/src/state/queries/notifications/feed.ts @@ -17,12 +17,7 @@ */ import {useCallback, useEffect, useMemo, useRef} from 'react' -import { - AppBskyFeedDefs, - AppBskyFeedPost, - AtUri, - moderatePost, -} from '@atproto/api' +import {AppBskyFeedDefs, AppBskyFeedPost, moderatePost} from '@atproto/api' import { type InfiniteData, type QueryClient, @@ -38,9 +33,9 @@ import {useAgent} from '#/state/session' import {useThreadgateHiddenReplyUris} from '#/state/threadgate-hidden-replies' import type * as bsky from '#/types/bsky' import { - didOrHandleUriMatches, embedViewRecordToPostView, getEmbeddedPost, + makeUriMatcher, } from '../util' import {type FeedPage} from './types' import {useUnreadNotificationsApi} from './unread' @@ -280,7 +275,7 @@ export function* findAllPostsInQueryData( queryClient: QueryClient, uri: string, ): Generator { - const atUri = new AtUri(uri) + const matches = makeUriMatcher(uri) const queryDatas = queryClient.getQueriesData>({ queryKey: [RQKEY_ROOT], @@ -293,14 +288,14 @@ export function* findAllPostsInQueryData( for (const page of queryData?.pages) { for (const item of page.items) { if (item.type !== 'starterpack-joined') { - if (item.subject && didOrHandleUriMatches(atUri, item.subject)) { + if (item.subject && matches(item.subject)) { yield item.subject } } if (AppBskyFeedDefs.isPostView(item.subject)) { const quotedPost = getEmbeddedPost(item.subject?.embed) - if (quotedPost && didOrHandleUriMatches(atUri, quotedPost)) { + if (quotedPost && matches(quotedPost)) { yield embedViewRecordToPostView(quotedPost) } } diff --git a/src/state/queries/notifications/util.ts b/src/state/queries/notifications/util.ts index e9264d9ff..59e8f5d5f 100644 --- a/src/state/queries/notifications/util.ts +++ b/src/state/queries/notifications/util.ts @@ -16,6 +16,8 @@ import {type QueryClient} from '@tanstack/react-query' import chunk from 'lodash.chunk' import {communityXrpc} from '#/lib/api/community' +import {isCommunityPostUri} from '#/lib/api/community-post' +import {toPostView} from '#/lib/api/space-views' import {HOME_APPVIEW_PINNED_OPTS} from '#/lib/constants' import {labelIsHideableOffense} from '#/lib/moderation' import * as bsky from '#/types/bsky' @@ -215,7 +217,7 @@ export function groupNotifications( return groupedNotifs } -async function fetchSubjects( +export async function fetchSubjects( agent: AtpAgent, groupedNotifs: FeedNotification[], ): Promise<{ @@ -226,10 +228,11 @@ async function fetchSubjects( const communityPostUris = new Set() const packUris = new Set() for (const notif of groupedNotifs) { - if (notif.subjectUri?.includes('community.blacksky.feed.post')) { - communityPostUris.add(notif.subjectUri) - } else if (notif.subjectUri?.includes('app.bsky.feed.post')) { - postUris.add(notif.subjectUri) + const subjectUri = notif.subjectUri + if (subjectUri && isCommunityPostUri(subjectUri)) { + communityPostUris.add(subjectUri) + } else if (subjectUri?.includes('app.bsky.feed.post')) { + postUris.add(subjectUri) } else if ( notif.notification.reasonSubject?.includes('app.bsky.graph.starterpack') ) { @@ -253,10 +256,8 @@ async function fetchSubjects( }) .then(async res => { if (!res.ok) return undefined - const data = jsonToLex(await res.json()) as { - post?: AppBskyFeedDefs.PostView - } - return data.post + const data = jsonToLex(await res.json()) as {post?: unknown} + return toPostView(data.post) }) .catch(() => undefined), ), diff --git a/src/state/queries/pinned-post.ts b/src/state/queries/pinned-post.ts index 09a0b4c9b..8b7a69736 100644 --- a/src/state/queries/pinned-post.ts +++ b/src/state/queries/pinned-post.ts @@ -2,6 +2,7 @@ import {msg} from '@lingui/core/macro' import {useLingui} from '@lingui/react' import {useMutation, useQueryClient} from '@tanstack/react-query' +import {isSpaceRecordUri} from '#/lib/api/space-uri' import {logger} from '#/logger' import {RQKEY as FEED_RQKEY} from '#/state/queries/post-feed' import * as Toast from '#/components/Toast' @@ -27,6 +28,12 @@ export function usePinnedPostMutation() { action: 'pin' | 'unpin' }) => { const pinCurrentPost = action === 'pin' + // The pin lands in the public profile record, so a space URI here would + // publish a private post's existence and author. The menu already hides + // the control; this is the invariant at the write. + if (isSpaceRecordUri(postUri)) { + throw new Error('A post in a private space cannot be pinned') + } let prevPinnedPost: string | undefined try { updatePostShadow(queryClient, postUri, {pinned: pinCurrentPost}) diff --git a/src/state/queries/post-feed.ts b/src/state/queries/post-feed.ts index b0c226b23..f7163ea76 100644 --- a/src/state/queries/post-feed.ts +++ b/src/state/queries/post-feed.ts @@ -5,7 +5,6 @@ import { AppBskyFeedDefs, type AppBskyFeedPost, type AtpAgent, - AtUri, moderatePost, type ModerationDecision, type ModerationPrefs, @@ -40,9 +39,9 @@ import {useFeedTuners} from '../preferences/feed-tuners' import {useModerationOpts} from '../preferences/moderation-opts' import {usePreferencesQuery} from './preferences' import { - didOrHandleUriMatches, embedViewRecordToPostView, getEmbeddedPost, + makeUriMatcher, } from './util' type ActorDid = string @@ -500,7 +499,7 @@ export function* findAllPostsInQueryData( queryClient: QueryClient, uri: string, ): Generator { - const atUri = new AtUri(uri) + const matches = makeUriMatcher(uri) const queryDatas = queryClient.getQueriesData< InfiniteData @@ -513,36 +512,33 @@ export function* findAllPostsInQueryData( } for (const page of queryData?.pages) { for (const item of page.feed) { - if (didOrHandleUriMatches(atUri, item.post)) { + if (matches(item.post)) { yield item.post } const quotedPost = getEmbeddedPost(item.post.embed) - if (quotedPost && didOrHandleUriMatches(atUri, quotedPost)) { + if (quotedPost && matches(quotedPost)) { yield embedViewRecordToPostView(quotedPost) } if (AppBskyFeedDefs.isPostView(item.reply?.parent)) { - if (didOrHandleUriMatches(atUri, item.reply.parent)) { + if (matches(item.reply.parent)) { yield item.reply.parent } const parentQuotedPost = getEmbeddedPost(item.reply.parent.embed) - if ( - parentQuotedPost && - didOrHandleUriMatches(atUri, parentQuotedPost) - ) { + if (parentQuotedPost && matches(parentQuotedPost)) { yield embedViewRecordToPostView(parentQuotedPost) } } if (AppBskyFeedDefs.isPostView(item.reply?.root)) { - if (didOrHandleUriMatches(atUri, item.reply.root)) { + if (matches(item.reply.root)) { yield item.reply.root } const rootQuotedPost = getEmbeddedPost(item.reply.root.embed) - if (rootQuotedPost && didOrHandleUriMatches(atUri, rootQuotedPost)) { + if (rootQuotedPost && matches(rootQuotedPost)) { yield embedViewRecordToPostView(rootQuotedPost) } } diff --git a/src/state/queries/post-liked-by.ts b/src/state/queries/post-liked-by.ts index e02de6153..63c31d28b 100644 --- a/src/state/queries/post-liked-by.ts +++ b/src/state/queries/post-liked-by.ts @@ -1,4 +1,8 @@ -import {type AppBskyActorDefs, type AppBskyFeedGetLikes} from '@atproto/api' +import { + type AppBskyActorDefs, + type AppBskyFeedGetLikes, + type BskyAgent, +} from '@atproto/api' import { type InfiniteData, type QueryClient, @@ -6,6 +10,8 @@ import { useInfiniteQuery, } from '@tanstack/react-query' +import {getSpacePostLikes} from '#/lib/api/community' +import {isSpaceRecordUri} from '#/lib/api/space-uri' import {useAgent} from '#/state/session' const PAGE_SIZE = 30 @@ -15,6 +21,26 @@ type RQPageParam = string | undefined const RQKEY_ROOT = 'liked-by' export const RQKEY = (resolvedUri: string) => [RQKEY_ROOT, resolvedUri] +export async function fetchLikedByPage( + agent: BskyAgent, + resolvedUri: string, + cursor?: string, +): Promise { + if (isSpaceRecordUri(resolvedUri)) { + return getSpacePostLikes(agent, { + uri: resolvedUri, + limit: PAGE_SIZE, + cursor, + }) + } + const res = await agent.getLikes({ + uri: resolvedUri, + limit: PAGE_SIZE, + cursor, + }) + return res.data +} + export function useLikedByQuery(resolvedUri: string | undefined) { const agent = useAgent() return useInfiniteQuery< @@ -26,12 +52,7 @@ export function useLikedByQuery(resolvedUri: string | undefined) { >({ queryKey: RQKEY(resolvedUri || ''), async queryFn({pageParam}: {pageParam: RQPageParam}) { - const res = await agent.getLikes({ - uri: resolvedUri || '', - limit: PAGE_SIZE, - cursor: pageParam, - }) - return res.data + return fetchLikedByPage(agent, resolvedUri || '', pageParam) }, initialPageParam: undefined, getNextPageParam: lastPage => lastPage.cursor, diff --git a/src/state/queries/post-quotes.ts b/src/state/queries/post-quotes.ts index 1d0fa07e8..633b79f50 100644 --- a/src/state/queries/post-quotes.ts +++ b/src/state/queries/post-quotes.ts @@ -3,7 +3,7 @@ import { AppBskyEmbedRecord, type AppBskyFeedDefs, type AppBskyFeedGetQuotes, - AtUri, + type BskyAgent, } from '@atproto/api' import { type InfiniteData, @@ -12,11 +12,13 @@ import { useInfiniteQuery, } from '@tanstack/react-query' +import {getSpacePostQuotes} from '#/lib/api/community' +import {isSpaceRecordUri} from '#/lib/api/space-uri' import {useAgent} from '#/state/session' import { - didOrHandleUriMatches, embedViewRecordToPostView, getEmbeddedPost, + makeUriMatcher, } from './util' const PAGE_SIZE = 30 @@ -25,6 +27,26 @@ type RQPageParam = string | undefined const RQKEY_ROOT = 'post-quotes' export const RQKEY = (resolvedUri: string) => [RQKEY_ROOT, resolvedUri] +export async function fetchPostQuotesPage( + agent: BskyAgent, + resolvedUri: string, + cursor?: string, +): Promise { + if (isSpaceRecordUri(resolvedUri)) { + return getSpacePostQuotes(agent, { + uri: resolvedUri, + limit: PAGE_SIZE, + cursor, + }) + } + const res = await agent.api.app.bsky.feed.getQuotes({ + uri: resolvedUri, + limit: PAGE_SIZE, + cursor, + }) + return res.data +} + export function usePostQuotesQuery(resolvedUri: string | undefined) { const agent = useAgent() return useInfiniteQuery< @@ -36,12 +58,7 @@ export function usePostQuotesQuery(resolvedUri: string | undefined) { >({ queryKey: RQKEY(resolvedUri || ''), async queryFn({pageParam}: {pageParam: RQPageParam}) { - const res = await agent.api.app.bsky.feed.getQuotes({ - uri: resolvedUri || '', - limit: PAGE_SIZE, - cursor: pageParam, - }) - return res.data + return fetchPostQuotesPage(agent, resolvedUri || '', pageParam) }, initialPageParam: undefined, getNextPageParam: lastPage => lastPage.cursor, @@ -103,19 +120,19 @@ export function* findAllPostsInQueryData( >({ queryKey: [RQKEY_ROOT], }) - const atUri = new AtUri(uri) + const matches = makeUriMatcher(uri) for (const [_queryKey, queryData] of queryDatas) { if (!queryData?.pages) { continue } for (const page of queryData?.pages) { for (const post of page.posts) { - if (didOrHandleUriMatches(atUri, post)) { + if (matches(post)) { yield post } const quotedPost = getEmbeddedPost(post.embed) - if (quotedPost && didOrHandleUriMatches(atUri, quotedPost)) { + if (quotedPost && matches(quotedPost)) { yield embedViewRecordToPostView(quotedPost) } } diff --git a/src/state/queries/post-reposted-by.ts b/src/state/queries/post-reposted-by.ts index 814a815aa..1c3a37e34 100644 --- a/src/state/queries/post-reposted-by.ts +++ b/src/state/queries/post-reposted-by.ts @@ -1,6 +1,7 @@ import { type AppBskyActorDefs, type AppBskyFeedGetRepostedBy, + type BskyAgent, } from '@atproto/api' import { type InfiniteData, @@ -9,6 +10,7 @@ import { useInfiniteQuery, } from '@tanstack/react-query' +import {isSpaceRecordUri} from '#/lib/api/space-uri' import {useAgent} from '#/state/session' const PAGE_SIZE = 30 @@ -18,6 +20,22 @@ type RQPageParam = string | undefined const RQKEY_ROOT = 'post-reposted-by' export const RQKEY = (resolvedUri: string) => [RQKEY_ROOT, resolvedUri] +export async function fetchRepostedByPage( + agent: BskyAgent, + resolvedUri: string, + cursor?: string, +): Promise { + if (isSpaceRecordUri(resolvedUri)) { + throw new Error('Reposts are not supported for private space posts') + } + const res = await agent.getRepostedBy({ + uri: resolvedUri, + limit: PAGE_SIZE, + cursor, + }) + return res.data +} + export function usePostRepostedByQuery(resolvedUri: string | undefined) { const agent = useAgent() return useInfiniteQuery< @@ -29,16 +47,11 @@ export function usePostRepostedByQuery(resolvedUri: string | undefined) { >({ queryKey: RQKEY(resolvedUri || ''), async queryFn({pageParam}: {pageParam: RQPageParam}) { - const res = await agent.getRepostedBy({ - uri: resolvedUri || '', - limit: PAGE_SIZE, - cursor: pageParam, - }) - return res.data + return fetchRepostedByPage(agent, resolvedUri || '', pageParam) }, initialPageParam: undefined, getNextPageParam: lastPage => lastPage.cursor, - enabled: !!resolvedUri, + enabled: !!resolvedUri && !isSpaceRecordUri(resolvedUri), }) } diff --git a/src/state/queries/post.ts b/src/state/queries/post.ts index 7b936299a..e7eeaed67 100644 --- a/src/state/queries/post.ts +++ b/src/state/queries/post.ts @@ -8,6 +8,14 @@ import { } from '@tanstack/react-query' import {communityXrpc} from '#/lib/api/community' +import {fetchCommunityPostView} from '#/lib/api/community-post' +import {setSpaceThreadMute} from '#/lib/api/community-thread' +import {isSpaceRecordUri} from '#/lib/api/space-uri' +import { + spaceDeleteIfSpace, + spaceLikeIfSpace, + spaceUnlikeIfSpace, +} from '#/lib/api/space-write' import {useToggleMutationQueue} from '#/lib/hooks/useToggleMutationQueue' import {updatePostShadow} from '#/state/cache/post-shadow' import {type Shadow} from '#/state/cache/types' @@ -28,6 +36,12 @@ export function usePostQuery(uri: string | undefined) { queryFn: async () => { if (!uri) throw new Error('[unreachable] No URI provided') + // Checked before AtUri, which misparses a space URI, and before + // getPosts, whose uris are at-uris. + if (isSpaceRecordUri(uri)) { + return fetchCommunityPostView(agent, uri) + } + const urip = new AtUri(uri) if (!urip.host.startsWith('did:')) { @@ -65,6 +79,9 @@ export function useGetPost() { return queryClient.fetchQuery({ queryKey: RQKEY(uri || ''), async queryFn() { + if (isSpaceRecordUri(uri)) { + return fetchCommunityPostView(agent, uri) + } const urip = new AtUri(uri) if (!urip.host.startsWith('did:')) { @@ -216,7 +233,10 @@ function usePostLikeMutation( : undefined, feedDescriptor: feedDescriptor, }) - return agent.like(uri, cid, via) + // A like on a permissioned post is written into the space, never the + // public repo: a public like naming a space URI would announce that the + // private post exists, and who can see it. + return spaceLikeIfSpace(agent, uri, cid) ?? agent.like(uri, cid, via) }, }) } @@ -236,7 +256,7 @@ function usePostUnlikeMutation( logContext, feedDescriptor, }) - return agent.deleteLike(likeUri) + return spaceUnlikeIfSpace(agent, likeUri) ?? agent.deleteLike(likeUri) }, }) } @@ -356,6 +376,12 @@ export function usePostDeleteMutation() { const agent = useAgent() return useMutation({ mutationFn: async ({uri}) => { + // Checked before AtUri sees the URI: a space URI misparses there. + const spaceDelete = spaceDeleteIfSpace(agent, uri) + if (spaceDelete) { + await spaceDelete + return + } const parsedUri = new AtUri(uri) if (parsedUri.collection === COMMUNITY_POST_COLLECTION) { // Both deletes are idempotent, so ordering is safe and a retry after @@ -440,7 +466,10 @@ function useThreadMuteMutation() { Error, {uri: string} // the root post's uri >({ - mutationFn: ({uri}) => { + mutationFn: async ({uri}) => { + if (isSpaceRecordUri(uri)) { + return setSpaceThreadMute(agent, uri, true) + } return agent.api.app.bsky.graph.muteThread({root: uri}) }, }) @@ -449,7 +478,10 @@ function useThreadMuteMutation() { function useThreadUnmuteMutation() { const agent = useAgent() return useMutation<{}, Error, {uri: string}>({ - mutationFn: ({uri}) => { + mutationFn: async ({uri}) => { + if (isSpaceRecordUri(uri)) { + return setSpaceThreadMute(agent, uri, false) + } return agent.api.app.bsky.graph.unmuteThread({root: uri}) }, }) diff --git a/src/state/queries/resolve-uri.ts b/src/state/queries/resolve-uri.ts index b27e6ef7d..8d8d37999 100644 --- a/src/state/queries/resolve-uri.ts +++ b/src/state/queries/resolve-uri.ts @@ -46,18 +46,21 @@ const resolvedDidQueryOptions = ( }) export function useResolveUriQuery(uri: string | undefined) { - const urip = new AtUri(uri || '') - const host = urip.host + const urip = uri ? new AtUri(uri) : undefined + const host = urip?.host const agent = useAgent() const {getUnstableProfile} = useUnstableProfileViewCache() return useQuery({ ...resolvedDidQueryOptions(agent, getUnstableProfile, host), - select: did => ({ - did, - uri: AtUri.make(did, urip.collection, urip.rkey).toString(), - }), + select: did => { + if (!urip) return undefined + return { + did, + uri: AtUri.make(did, urip.collection, urip.rkey).toString(), + } + }, }) } diff --git a/src/state/queries/search-posts.ts b/src/state/queries/search-posts.ts index 95cc5f24a..97a4d3bab 100644 --- a/src/state/queries/search-posts.ts +++ b/src/state/queries/search-posts.ts @@ -3,7 +3,6 @@ import { type AppBskyActorDefs, type AppBskyFeedDefs, type AppBskyFeedSearchPosts, - AtUri, moderatePost, } from '@atproto/api' import { @@ -17,9 +16,9 @@ import {searchAppviewOpts} from '#/lib/api/search-routing' import {useModerationOpts} from '#/state/preferences/moderation-opts' import {useAgent} from '#/state/session' import { - didOrHandleUriMatches, embedViewRecordToPostView, getEmbeddedPost, + makeUriMatcher, } from './util' const searchPostsQueryKeyRoot = 'search-posts' @@ -154,7 +153,7 @@ export function* findAllPostsInQueryData( >({ queryKey: [searchPostsQueryKeyRoot], }) - const atUri = new AtUri(uri) + const matches = makeUriMatcher(uri) for (const [_queryKey, queryData] of queryDatas) { if (!queryData?.pages) { @@ -162,12 +161,12 @@ export function* findAllPostsInQueryData( } for (const page of queryData?.pages) { for (const post of page.posts) { - if (didOrHandleUriMatches(atUri, post)) { + if (matches(post)) { yield post } const quotedPost = getEmbeddedPost(post.embed) - if (quotedPost && didOrHandleUriMatches(atUri, quotedPost)) { + if (quotedPost && matches(quotedPost)) { yield embedViewRecordToPostView(quotedPost) } } diff --git a/src/state/queries/usePostThread/index.ts b/src/state/queries/usePostThread/index.ts index f27b532f1..62a939869 100644 --- a/src/state/queries/usePostThread/index.ts +++ b/src/state/queries/usePostThread/index.ts @@ -1,6 +1,8 @@ import {useCallback, useMemo, useState} from 'react' import {useQuery, useQueryClient} from '@tanstack/react-query' +import {fetchCommunityThread} from '#/lib/api/community-thread' +import {isSpaceRecordUri} from '#/lib/api/space-uri' import {HOME_APPVIEW_PINNED_OPTS} from '#/lib/constants' import {useModerationOpts} from '#/state/preferences/moderation-opts' import {useThreadPreferences} from '#/state/queries/preferences/useThreadPreferences' @@ -82,15 +84,27 @@ export function usePostThread({anchor}: {anchor?: string}) { enabled: isThreadPreferencesLoaded && !!anchor && !!moderationOpts, queryKey: postThreadQueryKey, async queryFn(ctx) { - const {data} = await agent.app.bsky.unspecced.getPostThreadV2( - { - anchor: anchor!, - branchingFactor: view === 'linear' ? LINEAR_VIEW_BF : TREE_VIEW_BF, - below, - sort: sort, - }, - pinnedOpts, - ) + const branchingFactor = view === 'linear' ? LINEAR_VIEW_BF : TREE_VIEW_BF + // A space record cannot be an anchor on the standard endpoint: that + // parameter is an at-uri and a space URI is not one. The community + // endpoint answers with the same item shape. + const data = isSpaceRecordUri(anchor) + ? await fetchCommunityThread(agent, { + anchor: anchor!, + branchingFactor, + below, + }) + : ( + await agent.app.bsky.unspecced.getPostThreadV2( + { + anchor: anchor!, + branchingFactor, + below, + sort: sort, + }, + pinnedOpts, + ) + ).data /* * Initialize `ctx.meta` to track if we know we have additional replies diff --git a/src/state/queries/usePostThread/queryCache.ts b/src/state/queries/usePostThread/queryCache.ts index 5f5481d65..93401cbcf 100644 --- a/src/state/queries/usePostThread/queryCache.ts +++ b/src/state/queries/usePostThread/queryCache.ts @@ -6,7 +6,6 @@ import { AppBskyUnspeccedDefs, type AppBskyUnspeccedGetPostThreadOtherV2, type AppBskyUnspeccedGetPostThreadV2, - AtUri, } from '@atproto/api' import {type QueryClient, useQueryClient} from '@tanstack/react-query' @@ -32,9 +31,9 @@ import { import {getRootPostAtUri} from '#/state/queries/usePostThread/utils' import {postViewToThreadPlaceholder} from '#/state/queries/usePostThread/views' import { - didOrHandleUriMatches, embedViewRecordToPostView, getEmbeddedPost, + makeUriMatcher, } from '#/state/queries/util' export function createCacheMutator({ @@ -277,7 +276,7 @@ export function* findAllPostsInQueryData( queryClient: QueryClient, uri: string, ): Generator { - const atUri = new AtUri(uri) + const matches = makeUriMatcher(uri) const queryDatas = queryClient.getQueriesData({ queryKey: [postThreadQueryKeyRoot], @@ -290,12 +289,12 @@ export function* findAllPostsInQueryData( for (const item of thread) { if (AppBskyUnspeccedDefs.isThreadItemPost(item.value)) { - if (didOrHandleUriMatches(atUri, item.value.post)) { + if (matches(item.value.post)) { yield item.value.post } const qp = getEmbeddedPost(item.value.post.embed) - if (qp && didOrHandleUriMatches(atUri, qp)) { + if (qp && matches(qp)) { yield embedViewRecordToPostView(qp) } } diff --git a/src/state/queries/util.ts b/src/state/queries/util.ts index 7ea54745c..90c0520d1 100644 --- a/src/state/queries/util.ts +++ b/src/state/queries/util.ts @@ -4,7 +4,7 @@ import { AppBskyEmbedRecordWithMedia, type AppBskyFeedDefs, AppBskyFeedPost, - type AtUri, + AtUri, } from '@atproto/api' import { type InfiniteData, @@ -12,6 +12,7 @@ import { type QueryKey, } from '@tanstack/react-query' +import {isSpaceRecordUri} from '#/lib/api/space-uri' import * as bsky from '#/types/bsky' export type StructuredQueryKey> = readonly [ @@ -102,6 +103,27 @@ export function didOrHandleUriMatches( return atUri.host === record.author.handle && record.uri.endsWith(atUri.rkey) } +/** + * A predicate matching cached posts against a target URI, for shadow-cache + * updates (like, delete, ...). + * + * A permissioned-space record URI is not an at-uri: `AtUri` misparses it, so + * its `host` becomes the space authority and its `rkey` the space type. The + * handle branch of `didOrHandleUriMatches` would then compare the wrong + * segments and could match a different post entirely, which is why the space + * form is matched by exact equality — it is always fully qualified — and never + * constructed as an `AtUri` at all. + */ +export function makeUriMatcher(uri: string) { + if (isSpaceRecordUri(uri)) { + return (record: {uri: string; author: AppBskyActorDefs.ProfileViewBasic}) => + record.uri === uri + } + const atUri = new AtUri(uri) + return (record: {uri: string; author: AppBskyActorDefs.ProfileViewBasic}) => + didOrHandleUriMatches(atUri, record) +} + export function getEmbeddedPost( v: unknown, ): AppBskyEmbedRecord.ViewRecord | undefined { diff --git a/src/state/session/__tests__/strip-appview-proxy-test.ts b/src/state/session/__tests__/strip-appview-proxy-test.ts index 710757332..4a8fb2f3c 100644 --- a/src/state/session/__tests__/strip-appview-proxy-test.ts +++ b/src/state/session/__tests__/strip-appview-proxy-test.ts @@ -19,6 +19,12 @@ function headerValue( const GET_PREFS = 'https://pds.example.com/xrpc/app.bsky.actor.getPreferences' const PUT_PREFS = 'https://pds.example.com/xrpc/app.bsky.actor.putPreferences' const TIMELINE = 'https://pds.example.com/xrpc/app.bsky.feed.getTimeline' +const SPACE_CREATE = + 'https://pds.example.com/xrpc/com.atproto.space.createRecord' +const SPACE_DELETE = + 'https://pds.example.com/xrpc/com.atproto.space.deleteRecord' +const SPACE_GET = 'https://pds.example.com/xrpc/com.atproto.space.getRecord' +const SPACE_OTHER = 'https://pds.example.com/xrpc/com.atproto.space.listRecords' describe('stripAppviewProxyForPdsLocalMethods', () => { it('strips the appview proxy header on getPreferences', () => { @@ -61,4 +67,23 @@ describe('stripAppviewProxyForPdsLocalMethods', () => { ) expect(headerValue(out, PROXY)).toBeNull() }) + + it.each([SPACE_CREATE, SPACE_DELETE, SPACE_GET])( + 'strips the appview proxy header on %s', + url => { + const out = stripAppviewProxyForPdsLocalMethods( + url, + getInit({[PROXY]: PROXY_VALUE, authorization: 'DPoP tok'}), + ) + expect(headerValue(out, PROXY)).toBeNull() + expect(headerValue(out, 'authorization')).toBe('DPoP tok') + }, + ) + + it('does not strip unlisted space methods', () => { + const init = getInit({[PROXY]: PROXY_VALUE}) + const out = stripAppviewProxyForPdsLocalMethods(SPACE_OTHER, init) + expect(out).toBe(init) + expect(headerValue(out, PROXY)).toBe(PROXY_VALUE) + }) }) diff --git a/src/state/session/agent.ts b/src/state/session/agent.ts index f21750f8b..0f483282a 100644 --- a/src/state/session/agent.ts +++ b/src/state/session/agent.ts @@ -457,6 +457,9 @@ export class Agent extends BaseAgent { const PDS_LOCAL_PROXY_EXEMPT_METHODS = [ 'app.bsky.actor.getPreferences', 'app.bsky.actor.putPreferences', + 'com.atproto.space.createRecord', + 'com.atproto.space.deleteRecord', + 'com.atproto.space.getRecord', ] export function stripAppviewProxyForPdsLocalMethods( diff --git a/src/state/session/oauth-client.ts b/src/state/session/oauth-client.ts index e4ee5ed9d..2317be2c1 100644 --- a/src/state/session/oauth-client.ts +++ b/src/state/session/oauth-client.ts @@ -9,6 +9,22 @@ import { } from '#/state/session/oauth-telemetry' import {OAUTH_BASE_URL, OAUTH_CLIENT_NAME, OAUTH_SCOPE} from './oauth-config' +const LOCAL_OAUTH_HANDLE_RESOLVER = + process.env.EXPO_PUBLIC_OAUTH_HANDLE_RESOLVER +const LOCAL_OAUTH_PLC_DIRECTORY_URL = + process.env.EXPO_PUBLIC_OAUTH_PLC_DIRECTORY_URL +const USE_LOCAL_OAUTH_RESOLUTION = + __DEV__ && !!LOCAL_OAUTH_HANDLE_RESOLVER && !!LOCAL_OAUTH_PLC_DIRECTORY_URL + +const oauthResolutionOptions = { + handleResolver: USE_LOCAL_OAUTH_RESOLUTION + ? LOCAL_OAUTH_HANDLE_RESOLVER + : 'https://blacksky.app', + ...(USE_LOCAL_OAUTH_RESOLUTION + ? {plcDirectoryUrl: LOCAL_OAUTH_PLC_DIRECTORY_URL, allowHttp: true} + : {}), +} + export const NATIVE_REDIRECT_URI = 'community.blacksky:/oauth/callback' // The redirect deep-link can arrive with either a single (`:/oauth`) or double @@ -79,7 +95,7 @@ const BSKY_OAUTH_CLIENT = new ExpoOAuthClient({ application_type: 'native', dpop_bound_access_tokens: true, }, - handleResolver: 'https://blacksky.app', + ...oauthResolutionOptions, fetch: debugFetch, ...sessionHooks, }) diff --git a/src/state/session/oauth-client.web.ts b/src/state/session/oauth-client.web.ts index a38b0ebb3..b512bcf2f 100644 --- a/src/state/session/oauth-client.web.ts +++ b/src/state/session/oauth-client.web.ts @@ -9,6 +9,22 @@ import { import {type Metrics} from '#/analytics/metrics' import {OAUTH_SCOPE} from './oauth-config' +const LOCAL_OAUTH_HANDLE_RESOLVER = + process.env.EXPO_PUBLIC_OAUTH_HANDLE_RESOLVER +const LOCAL_OAUTH_PLC_DIRECTORY_URL = + process.env.EXPO_PUBLIC_OAUTH_PLC_DIRECTORY_URL +const USE_LOCAL_OAUTH_RESOLUTION = + __DEV__ && !!LOCAL_OAUTH_HANDLE_RESOLVER && !!LOCAL_OAUTH_PLC_DIRECTORY_URL + +const oauthResolutionOptions = { + handleResolver: USE_LOCAL_OAUTH_RESOLUTION + ? LOCAL_OAUTH_HANDLE_RESOLVER + : 'https://blacksky.app', + ...(USE_LOCAL_OAUTH_RESOLUTION + ? {plcDirectoryUrl: LOCAL_OAUTH_PLC_DIRECTORY_URL, allowHttp: true} + : {}), +} + function getOAuthBaseUrl(): string { if (typeof window !== 'undefined') { return window.location.origin @@ -162,7 +178,7 @@ function createWebOAuthClient() { application_type: 'web', dpop_bound_access_tokens: true, }, - handleResolver: 'https://blacksky.app', + ...oauthResolutionOptions, fetch: oauthInstrumentedFetch, ...sessionHooks, }) @@ -184,7 +200,7 @@ function createWebOAuthClient() { application_type: 'web', dpop_bound_access_tokens: true, }, - handleResolver: 'https://blacksky.app', + ...oauthResolutionOptions, fetch: oauthInstrumentedFetch, ...sessionHooks, }) diff --git a/src/state/shell/composer/index.tsx b/src/state/shell/composer/index.tsx index 9a1e212f4..265e93d5a 100644 --- a/src/state/shell/composer/index.tsx +++ b/src/state/shell/composer/index.tsx @@ -9,6 +9,7 @@ import {msg} from '@lingui/core/macro' import {useLingui} from '@lingui/react' import {useQueryClient} from '@tanstack/react-query' +import {type CommunityFeedTarget} from '#/lib/api/community-feed' import {useNonReactiveCallback} from '#/lib/hooks/useNonReactiveCallback' import {postUriToRelativePath, toBskyAppUrl} from '#/lib/strings/url-helpers' import {purgeTemporaryImageFiles} from '#/state/gallery' @@ -27,6 +28,7 @@ export interface ComposerOptsPostRef { author: AppBskyActorDefs.ProfileViewBasic embed?: AppBskyFeedDefs.PostView['embed'] moderation?: ModerationDecision + communitySpace?: string } export type OnPostSuccessData = @@ -55,6 +57,7 @@ export interface ComposerOpts { videoUri?: {uri: string; width: number; height: number} openGallery?: boolean logContext?: ComposerLogContext + contextualCommunityFeedTarget?: CommunityFeedTarget } type StateContext = ComposerOpts | undefined diff --git a/src/state/shell/landing.tsx b/src/state/shell/landing.tsx index f071c79e3..f69dc5ab0 100644 --- a/src/state/shell/landing.tsx +++ b/src/state/shell/landing.tsx @@ -1,4 +1,4 @@ -import {createContext, useContext, useState} from 'react' +import {createContext, useContext, useEffect, useState} from 'react' import {logger} from '#/logger' @@ -14,17 +14,70 @@ type GroupChatJoinRequestLanding = { code: string } -type LandingType = StarterPackLanding | GroupChatJoinRequestLanding | undefined +type GroupInviteLanding = { + type: 'groupinvite' + uri: string + code: string +} + +type LandingType = + | StarterPackLanding + | GroupChatJoinRequestLanding + | GroupInviteLanding + | undefined type SetContext = (v: LandingType) => void +const PENDING_GROUP_INVITE_KEY = 'blacksky.pendingGroupInvite' + +function readPendingGroupInvite(): GroupInviteLanding | undefined { + if (typeof window === 'undefined') return undefined + try { + const value: unknown = JSON.parse( + window.sessionStorage.getItem(PENDING_GROUP_INVITE_KEY) ?? 'null', + ) + const code = + value && typeof value === 'object' + ? (value as {code?: unknown}).code + : undefined + if ( + value && + typeof value === 'object' && + (value as {type?: unknown}).type === 'groupinvite' && + typeof code === 'string' && + /^[A-Za-z0-9_-]{43}$/.test(code) + ) { + return {type: 'groupinvite', uri: '', code} + } + } catch { + // Session storage is a best-effort OAuth resume aid. + } + return undefined +} + const stateContext = createContext(undefined) stateContext.displayName = 'ActiveLandingStateContext' const setContext = createContext((_: LandingType) => {}) setContext.displayName = 'ActiveLandingSetContext' export function Provider({children}: {children: React.ReactNode}) { - const [state, setState] = useState() + const [state, setState] = useState(readPendingGroupInvite) + + useEffect(() => { + if (typeof window === 'undefined') return + try { + if (state?.type === 'groupinvite') { + window.sessionStorage.setItem( + PENDING_GROUP_INVITE_KEY, + JSON.stringify({type: state.type, code: state.code}), + ) + } else { + window.sessionStorage.removeItem(PENDING_GROUP_INVITE_KEY) + } + } catch { + // Session storage is never required for normal invite handling. + } + }, [state]) return ( @@ -64,3 +117,8 @@ export const useActiveGroupChatJoinRequest = () => { const landing = useActiveLanding() return landing?.type === 'groupchat' ? landing : undefined } + +export const useActiveGroupInvite = () => { + const landing = useActiveLanding() + return landing?.type === 'groupinvite' ? landing : undefined +} diff --git a/src/state/shell/logged-out.tsx b/src/state/shell/logged-out.tsx index fcb76818c..7d5d65ca7 100644 --- a/src/state/shell/logged-out.tsx +++ b/src/state/shell/logged-out.tsx @@ -32,6 +32,7 @@ type Controls = { | 'new' | 'starterpack' | 'groupchat' + | 'groupinvite' }) => void /** * Clears the requested account so that next time the logged out view is @@ -64,6 +65,8 @@ function getRequestedAccountFromLanding( return IS_WEB ? 'starterpack' : 'new' case 'groupchat': return 'groupchat' + case 'groupinvite': + return 'groupinvite' default: return undefined } diff --git a/src/view/com/auth/LoggedOut.tsx b/src/view/com/auth/LoggedOut.tsx index 05340d0d2..063eded10 100644 --- a/src/view/com/auth/LoggedOut.tsx +++ b/src/view/com/auth/LoggedOut.tsx @@ -16,6 +16,7 @@ import { } from '#/state/shell/logged-out' import {useEnableMinimalShellMode} from '#/state/shell/minimal-mode' import {ErrorBoundary} from '#/view/com/util/ErrorBoundary' +import {GroupInviteLanding} from '#/screens/GroupInviteLanding' import {Login} from '#/screens/Login' import {JoinRequest} from '#/screens/Messages/JoinRequest' import {Signup} from '#/screens/Signup' @@ -32,6 +33,7 @@ enum ScreenState { S_CreateAccount, S_StarterPack, S_GroupChatJoinRequest, + S_GroupInvite, } export {ScreenState as LoggedOutScreenState} @@ -43,6 +45,8 @@ function getInitialScreenState(requestedAccountSwitchTo?: string): ScreenState { return ScreenState.S_StarterPack case 'groupchat': return ScreenState.S_GroupChatJoinRequest + case 'groupinvite': + return ScreenState.S_GroupInvite case undefined: return ScreenState.S_LoginOrCreateAccount default: @@ -124,6 +128,8 @@ export function LoggedOut({onDismiss}: {onDismiss?: () => void}) { ) : screenState === ScreenState.S_GroupChatJoinRequest ? ( + ) : screenState === ScreenState.S_GroupInvite ? ( + ) : screenState === ScreenState.S_LoginOrCreateAccount ? ( { diff --git a/src/view/com/composer/Composer.tsx b/src/view/com/composer/Composer.tsx index e83db8211..f2d61e698 100644 --- a/src/view/com/composer/Composer.tsx +++ b/src/view/com/composer/Composer.tsx @@ -60,13 +60,28 @@ import {Trans, useLingui} from '@lingui/react/macro' import {useNavigation} from '@react-navigation/native' import {useQueries, useQueryClient} from '@tanstack/react-query' +import { + type CommunityFeedTarget, + isSpaceBackedFeed, +} from '#/lib/api/community-feed' +import { + getCommunitySpaceUri, + isCommunityPostUri, +} from '#/lib/api/community-post' import * as apilib from '#/lib/api/index' import {EmbeddingDisabledError} from '#/lib/api/resolve' +import { + isSpaceRecordUri, + parseSpaceRecordUri, + spaceUriOf, +} from '#/lib/api/space-uri' +import {SpaceUnsupportedError} from '#/lib/api/space-write' import {useAppState} from '#/lib/appState' import {retry} from '#/lib/async/retry' import {until} from '#/lib/async/until' import {useBrand} from '#/lib/community/BrandContext' import { + ACCOUNT_MIGRATION_URL, MAX_DRAFT_GRAPHEME_LENGTH, MAX_GRAPHEME_LENGTH, SUPPORTED_MIME_TYPES, @@ -119,6 +134,7 @@ import {LabelsBtn} from '#/view/com/composer/labels/LabelsBtn' import {Gallery} from '#/view/com/composer/photos/Gallery' import {OpenCameraBtn} from '#/view/com/composer/photos/OpenCameraBtn' import {SelectGifBtn} from '#/view/com/composer/photos/SelectGifBtn' +import {PostTargetControls} from '#/view/com/composer/PostTargetControls' import {SuggestedLanguage} from '#/view/com/composer/select-language/SuggestedLanguage' // TODO: Prevent naming components that coincide with RN primitives // due to linting false positives @@ -133,11 +149,11 @@ import {Admonition} from '#/components/Admonition' import {Button, ButtonIcon, ButtonText} from '#/components/Button' import {CommunityOnlyBadge} from '#/components/CommunityOnlyBadge' import * as EmojiPicker from '#/components/EmojiPicker' -import * as Toggle from '#/components/forms/Toggle' import {CircleInfo_Stroke2_Corner0_Rounded as CircleInfoIcon} from '#/components/icons/CircleInfo' import {EmojiArc_Stroke2_Corner0_Rounded as EmojiSmileIcon} from '#/components/icons/Emoji' import {PlusLarge_Stroke2_Corner0_Rounded as PlusIcon} from '#/components/icons/Plus' import {TimesLarge_Stroke2_Corner0_Rounded as XIcon} from '#/components/icons/Times' +import {SimpleInlineLinkText} from '#/components/Link' import {LazyQuoteEmbed} from '#/components/Post/Embed/LazyQuoteEmbed' import * as Prompt from '#/components/Prompt' import * as Toast from '#/components/Toast' @@ -268,6 +284,7 @@ export const ComposePost = ({ videoUri: initVideoUri, openGallery, logContext, + contextualCommunityFeedTarget, cancelRef, }: Props & { cancelRef?: React.RefObject @@ -298,6 +315,10 @@ export const ComposePost = ({ const [isPublishing, setIsPublishing] = useState(false) const [publishingStage, setPublishingStage] = useState('') const [error, setError] = useState('') + // A write refused because the account's server has no space support: the + // only fix is moving the account, so the banner offers that rather than a + // failure the user cannot act on. + const [needsMigration, setNeedsMigration] = useState(false) /** * Track when a draft was created so we can measure draft age in metrics. @@ -363,11 +384,18 @@ export const ComposePost = ({ const setBlackskyOnlyDefault = useSetBlackskyOnlyDefault() const {data: isCommunityMember = false} = useCommunityMembership() - // Force Blacksky-Only when the thread targets a community post — replies - // and quotes of a community post can only land in the community. + // Both the appview-stored stub and any record inside a space: a reply or + // quote of either must stay inside the community it came from. + const isCommunityReply = isCommunityPostUri(replyTo?.uri) + const isCommunityQuote = isCommunityPostUri(initQuote?.uri) + const replyCommunitySpace = replyTo?.communitySpace + const quoteCommunitySpace = getCommunitySpaceUri(initQuote) const isForcedBlackskyOnly = - (!!replyTo?.uri && replyTo.uri.includes('community.blacksky.feed.post')) || - (!!initQuote?.uri && initQuote.uri.includes('community.blacksky.feed.post')) + (isCommunityReply && !replyCommunitySpace) || + (isCommunityQuote && !quoteCommunitySpace) + const isForcedCommunityTarget = isCommunityReply || isCommunityQuote + const hasEligibleContextualTarget = + !!contextualCommunityFeedTarget && !replyTo && !isForcedCommunityTarget const [composerState, composerDispatch] = useReducer( composerReducer, @@ -377,17 +405,56 @@ export const ComposePost = ({ initText, initMention, initInteractionSettings: preferences?.postInteractionSettings, + initCommunitySpaceUri: replyCommunitySpace ?? quoteCommunitySpace, // Replies inherit their parent's audience: forced on for community // parents, forced off for public parents. The sticky default only - // applies to top-level posts, and only for community members. + // applies to top-level posts for community members. A selected writable + // private feed starts public and supersedes that default for this + // composer instance without changing the persisted preference. initBlackskyOnly: isForcedBlackskyOnly || - (!replyTo && isCommunityMember && blackskyOnlyDefault), + (!hasEligibleContextualTarget && + !replyTo && + isCommunityMember && + blackskyOnlyDefault), }, createComposerState, ) const thread = composerState.thread + const spaceTarget = + thread.communitySpaceUri ?? + (isSpaceBackedFeed(thread.communityFeed?.config) + ? thread.communityFeed.config.space + : undefined) + + useEffect(() => { + if (!spaceTarget) return + for (const post of thread.posts) { + const media = post.embed.media + if (media?.type === 'images' || media?.type === 'gallery') { + for (const image of media.images) { + composerDispatch({ + type: 'update_post', + postId: post.id, + postAction: {type: 'embed_remove_image', image}, + }) + } + } else if (media?.type === 'video') { + composerDispatch({ + type: 'update_post', + postId: post.id, + postAction: {type: 'embed_remove_video'}, + }) + } else if (media?.type === 'gif') { + composerDispatch({ + type: 'update_post', + postId: post.id, + postAction: {type: 'embed_remove_gif'}, + }) + } + } + }, [spaceTarget, thread.posts]) // Clear error when composer content changes, but only if all posts are // back within the character limit. @@ -998,6 +1065,7 @@ export const ComposePost = ({ postUri = ( await apilib.post(agent, queryClient, { thread: filteredThread, + draftId: composerState.draftId, replyTo: replyTo?.uri, onStateChange: setPublishingStage, langs: currentLanguages, @@ -1064,6 +1132,9 @@ export const ComposePost = ({ err = l`We're sorry! The post you are replying to has been deleted.` } else if (e instanceof EmbeddingDisabledError) { err = l`This post's author has disabled quote posts.` + } else if (e instanceof SpaceUnsupportedError) { + err = l`Your account is hosted elsewhere, so it cannot post to a private community feed. You can read it, but posting needs an account hosted here.` + setNeedsMigration(true) } setError(err) setIsPublishing(false) @@ -1133,7 +1204,7 @@ export const ComposePost = ({ }) } setLangPrefs.savePostLanguageToHistory() - if (initQuote) { + if (initQuote && !isSpaceRecordUri(initQuote.uri)) { // We want to wait for the quote count to update before we call `onPost`, which will refetch data void whenAppViewReady(agent, initQuote.uri, res => { const anchor = res.data.thread.at(0) @@ -1167,17 +1238,33 @@ export const ComposePost = ({ { - const urip = new AtUri(postUri) const params: { name: string rkey: string collection?: string - } = { - name: urip.host, - rkey: urip.rkey, - } - if (urip.collection !== 'app.bsky.feed.post') { - params.collection = urip.collection + space?: string + } = (() => { + // A space record uri is not an at-uri, so its parts come + // from the space parser and the space itself travels as a + // route param rather than in the path. + const inSpace = parseSpaceRecordUri(postUri) + if (inSpace) { + return { + name: inSpace.authorDid, + rkey: inSpace.rkey, + collection: inSpace.collection, + space: spaceUriOf(inSpace), + } + } + const urip = new AtUri(postUri) + return { + name: urip.host, + rkey: urip.rkey, + collection: urip.collection, + } + })() + if (params.collection === 'app.bsky.feed.post') { + delete params.collection } navigation.navigate('PostThread', params) }}> @@ -1326,7 +1413,9 @@ export const ComposePost = ({ dispatch={composerDispatch} bottomBarAnimatedStyle={bottomBarAnimatedStyle} isForcedBlackskyOnly={isForcedBlackskyOnly} + isForcedCommunityTarget={isForcedCommunityTarget} setBlackskyOnlyDefault={setBlackskyOnlyDefault} + contextualCommunityFeedTarget={contextualCommunityFeedTarget} /> ) @@ -1383,8 +1473,12 @@ export const ComposePost = ({ {missingAltError && } setError('')} + clearError={() => { + setError('') + setNeedsMigration(false) + }} clearVideo={ erroredVideoPostId ? () => clearVideo(erroredVideoPostId) @@ -1984,7 +2078,9 @@ function ComposerPills({ dispatch, bottomBarAnimatedStyle, isForcedBlackskyOnly, + isForcedCommunityTarget, setBlackskyOnlyDefault, + contextualCommunityFeedTarget, }: { isReply: boolean thread: ThreadDraft @@ -1992,10 +2088,11 @@ function ComposerPills({ dispatch: (action: ComposerAction) => void bottomBarAnimatedStyle: StyleProp isForcedBlackskyOnly: boolean + isForcedCommunityTarget: boolean setBlackskyOnlyDefault: (v: boolean) => void + contextualCommunityFeedTarget?: CommunityFeedTarget }) { const t = useTheme() - const {t: l} = useLingui() const {data: isCommunityMember = false} = useCommunityMembership() const homeAppviewOutage = useHomeAppviewOutage() const media = post.embed.media @@ -2006,7 +2103,14 @@ function ComposerPills({ media?.type === 'video' const hasLink = !!post.embed.link - if (isReply && !hasMedia && !hasLink && !isForcedBlackskyOnly) { + if ( + isReply && + !hasMedia && + !hasLink && + !isForcedBlackskyOnly && + !thread.communityFeedUri && + !thread.communitySpaceUri + ) { return null } @@ -2020,7 +2124,7 @@ function ComposerPills({ bounces={false} keyboardShouldPersistTaps="always" showsHorizontalScrollIndicator={false}> - {isReply ? null : ( + {isReply || isSpaceBackedFeed(thread.communityFeed?.config) ? null : ( { @@ -2036,28 +2140,17 @@ function ComposerPills({ style={bottomBarAnimatedStyle} /> )} - {!isCommunityMember || (isReply && !isForcedBlackskyOnly) ? null : ( - { - const next = !thread.blackskyOnly - dispatch({type: 'toggle_blacksky_only'}) - setBlackskyOnlyDefault(next) - }} - style={[a.flex_row, a.align_center, a.gap_xs]}> - - {homeAppviewOutage ? ( - Blacksky Only (temporarily unavailable) - ) : ( - Blacksky Only - )} - - - - )} + {hasMedia || hasLink ? ( ) : null} - {thread.blackskyOnly && ( + {(thread.blackskyOnly || + thread.communityFeedUri || + thread.communitySpaceUri) && ( - + )} @@ -2094,6 +2191,7 @@ function ComposerFooter({ languageNudgeAt, openGallery, textInputRef, + spaceMediaDisabled, }: { post: PostDraft dispatch: (action: PostAction) => void @@ -2106,6 +2204,7 @@ function ComposerFooter({ languageNudgeAt: number openGallery?: boolean textInputRef: React.RefObject + spaceMediaDisabled: boolean }) { const t = useTheme() const {t: l} = useLingui() @@ -2142,9 +2241,10 @@ function ComposerFooter({ const onSelectGif = useCallback( (gif: Gif) => { + if (spaceMediaDisabled) return dispatch({type: 'embed_add_gif', gif}) }, - [dispatch], + [dispatch, spaceMediaDisabled], ) /* @@ -2156,6 +2256,7 @@ function ComposerFooter({ const onSelectAssets = useCallback( async ({type, assets, errors}) => { + if (spaceMediaDisabled) return setSelectedAssetsType(type) if (assets.length) { @@ -2192,7 +2293,7 @@ function ComposerFooter({ }) }) }, - [post.id, onSelectVideo, onImageAdd], + [post.id, onSelectVideo, onImageAdd, spaceMediaDisabled], ) return ( @@ -2214,7 +2315,7 @@ function ComposerFooter({ ) : ( - + {IS_WEB && gtPhone ? ( @@ -2250,6 +2356,11 @@ function ComposerFooter({ )} + {spaceMediaDisabled ? ( + + Media isn’t available in private spaces yet. + + ) : null} {showAddButton && ( @@ -2527,11 +2638,13 @@ const styles = StyleSheet.create({ function ErrorBanner({ error: standardError, + needsMigration, videoState, clearError, clearVideo, }: { error: string + needsMigration?: boolean videoState: VideoState | NoVideoState clearError: () => void clearVideo: () => void @@ -2582,6 +2695,15 @@ function ErrorBanner({ + {needsMigration && ( + + + Move your account to Blacksky + + + )} {videoError && videoState.jobId && ( void + isCommunityMember: boolean + homeAppviewOutage: boolean + setBlackskyOnlyDefault: (value: boolean) => void + isReply: boolean + isForcedBlackskyOnly: boolean + isForcedCommunityTarget: boolean + contextualCommunityFeedTarget?: CommunityFeedTarget +}) { + const {t} = useLingui() + const showContextualTarget = + !isReply && !isForcedCommunityTarget && !!contextualCommunityFeedTarget + const showBlackskyOnly = + !showContextualTarget && + isCommunityMember && + !(isReply && !isForcedBlackskyOnly) && + (!isForcedCommunityTarget || isForcedBlackskyOnly) + + return ( + <> + {showBlackskyOnly ? ( + { + const next = !thread.blackskyOnly + dispatch({type: 'toggle_blacksky_only'}) + setBlackskyOnlyDefault(next) + }} + style={[a.flex_row, a.align_center, a.gap_xs]}> + + {homeAppviewOutage ? ( + Blacksky Only (temporarily unavailable) + ) : ( + Blacksky Only + )} + + + + ) : null} + {showContextualTarget ? ( + { + dispatch({ + type: 'set_post_target', + target: + thread.communityFeed?.feed === + contextualCommunityFeedTarget.feed + ? 'public' + : contextualCommunityFeedTarget, + }) + }} + style={[a.flex_row, a.align_center, a.gap_xs]}> + + {contextualCommunityFeedTarget.name} + + + + ) : null} + + ) +} diff --git a/src/view/com/composer/__tests__/PostTargetControls.test.tsx b/src/view/com/composer/__tests__/PostTargetControls.test.tsx new file mode 100644 index 000000000..8ca7c1a1d --- /dev/null +++ b/src/view/com/composer/__tests__/PostTargetControls.test.tsx @@ -0,0 +1,196 @@ +import {fireEvent, render} from '@testing-library/react-native' + +import {type CommunityFeedTarget} from '#/lib/api/community-feed' +import {type ThreadDraft} from '#/view/com/composer/state/composer' + +jest.mock('@lingui/react', () => ({ + useLingui: () => ({ + _: ( + message: {message?: string; values?: Record} | string, + ) => { + if (typeof message === 'string') return message + return message.message?.replace( + /{(\w+)}/g, + (_, key: string) => message.values?.[key] ?? '', + ) + }, + }), + Trans: ({ + id, + message, + values, + }: { + id: string + message?: string + values?: Record + }) => + (message ?? id).replace( + /{(\w+)}/g, + (_, key: string) => values?.[key] ?? '', + ), +})) +jest.mock('#/alf', () => ({ + atoms: {flex_row: {}, align_center: {}, gap_xs: {}}, +})) +jest.mock('#/components/forms/Toggle', () => { + const React = require('react') + const {Pressable, Text} = require('react-native') + return { + Item: ({ + children, + disabled, + label, + name, + onChange, + value, + }: { + children: React.ReactNode + disabled?: boolean + label: string + name: string + onChange: () => void + value: boolean + }) => ( + + {children} + + ), + LabelText: ({children}: {children: React.ReactNode}) => ( + {children} + ), + Switch: () => null, + } +}) + +import {PostTargetControls} from '../PostTargetControls' + +const PRIVATE_TARGET: CommunityFeedTarget = { + feed: 'at://did:plc:test/app.bsky.feed.generator/private', + name: 'Private Test', + serviceDid: 'did:web:feeds.test', + config: { + $type: 'community.blacksky.feed.config', + contentType: 'communityRecord', + visibility: 'gated', + space: 'at://did:plc:test/space/community.blacksky.feed/private', + group: 'members', + createdAt: '2026-08-30T00:00:00.000Z', + }, +} + +function thread(overrides: Partial = {}): ThreadDraft { + return { + posts: [], + postgate: {} as ThreadDraft['postgate'], + threadgate: [], + blackskyOnly: false, + ...overrides, + } +} + +function renderControls({ + draft = thread(), + target, + isForcedCommunityTarget = false, +}: { + draft?: ThreadDraft + target?: CommunityFeedTarget + isForcedCommunityTarget?: boolean +} = {}) { + const dispatch = jest.fn() + const setBlackskyOnlyDefault = jest.fn() + return { + ...render( + , + ), + dispatch, + setBlackskyOnlyDefault, + } +} + +describe('PostTargetControls', () => { + it('keeps ordinary public composition on the legacy Blacksky-only toggle', () => { + const {getByTestId, queryByTestId} = renderControls() + + expect(getByTestId('blacksky_only')).toBeTruthy() + expect(queryByTestId('permissioned_space')).toBeNull() + }) + + it('preserves legacy Blacksky-only state and behavior', () => { + const {dispatch, getByTestId, setBlackskyOnlyDefault} = renderControls({ + draft: thread({blackskyOnly: true}), + }) + + fireEvent.press(getByTestId('blacksky_only')) + expect(dispatch).toHaveBeenCalledWith({type: 'toggle_blacksky_only'}) + expect(setBlackskyOnlyDefault).toHaveBeenCalledWith(false) + }) + + it('offers public versus the selected private feed when Blacksky-only is off', () => { + const {dispatch, getByTestId, getByText, queryByTestId} = renderControls({ + target: PRIVATE_TARGET, + }) + + expect(getByText('Private Test')).toBeTruthy() + expect(queryByTestId('blacksky_only')).toBeNull() + fireEvent.press(getByTestId('permissioned_space')) + expect(dispatch).toHaveBeenCalledWith({ + type: 'set_post_target', + target: PRIVATE_TARGET, + }) + }) + + it('gives the selected private feed precedence over sticky Blacksky-only state', () => { + const {dispatch, getByTestId, queryByTestId} = renderControls({ + draft: thread({blackskyOnly: true}), + target: PRIVATE_TARGET, + }) + + expect(queryByTestId('blacksky_only')).toBeNull() + const contextualToggle = getByTestId('permissioned_space') + expect(contextualToggle).toHaveProp( + 'accessibilityState', + expect.objectContaining({checked: false}), + ) + fireEvent.press(contextualToggle) + expect(dispatch).toHaveBeenCalledWith({ + type: 'set_post_target', + target: PRIVATE_TARGET, + }) + }) + + it('does not expose private-space controls outside selected-feed context', () => { + const {queryByTestId} = renderControls({ + draft: thread({communityFeed: PRIVATE_TARGET}), + }) + + expect(queryByTestId('permissioned_space')).toBeNull() + }) + + it('does not expose destination controls for a forced private quote', () => { + const {queryByTestId} = renderControls({ + target: PRIVATE_TARGET, + isForcedCommunityTarget: true, + }) + + expect(queryByTestId('blacksky_only')).toBeNull() + expect(queryByTestId('permissioned_space')).toBeNull() + }) +}) diff --git a/src/view/com/composer/state/composer.ts b/src/view/com/composer/state/composer.ts index b1a64ae71..3f0684bb1 100644 --- a/src/view/com/composer/state/composer.ts +++ b/src/view/com/composer/state/composer.ts @@ -8,6 +8,7 @@ import { } from '@atproto/api' import {nanoid} from 'nanoid/non-secure' +import {type CommunityFeedTarget} from '#/lib/api/community-feed' import {type SelfLabel} from '#/lib/moderation' import {insertMentionAt} from '#/lib/strings/mention-manip' import {shortenLinks} from '#/lib/strings/rich-text-manip' @@ -103,6 +104,14 @@ export type ThreadDraft = { postgate: AppBskyFeedPostgate.Record threadgate: ThreadgateAllowUISetting[] blackskyOnly: boolean + communityFeed?: CommunityFeedTarget + communityFeedUri?: string + /** + * The space a parent post lives in, inherited when replying to or quoting + * one. Distinct from `communityFeedUri`, which names a feed the author + * chose to post into: a space is where content goes, a feed is a view. + */ + communitySpaceUri?: string } export type ComposerState = { @@ -123,6 +132,10 @@ export type ComposerAction = | {type: 'update_postgate'; postgate: AppBskyFeedPostgate.Record} | {type: 'update_threadgate'; threadgate: ThreadgateAllowUISetting[]} | {type: 'toggle_blacksky_only'} + | { + type: 'set_post_target' + target: 'public' | 'blacksky' | CommunityFeedTarget + } | { type: 'update_post' postId: string @@ -220,6 +233,23 @@ export function composerReducer( thread: { ...state.thread, blackskyOnly: !state.thread.blackskyOnly, + communityFeed: undefined, + communityFeedUri: undefined, + communitySpaceUri: undefined, + }, + } + } + case 'set_post_target': { + return { + ...state, + isDirty: true, + thread: { + ...state.thread, + blackskyOnly: action.target === 'blacksky', + communityFeed: + typeof action.target === 'string' ? undefined : action.target, + communityFeedUri: + typeof action.target === 'string' ? undefined : action.target.feed, }, } } @@ -631,6 +661,7 @@ export function createComposerState({ initQuoteUri, initInteractionSettings, initBlackskyOnly, + initCommunitySpaceUri, }: { initText: string | undefined initMention: string | undefined @@ -640,6 +671,7 @@ export function createComposerState({ | AppBskyActorDefs.PostInteractionSettingsPref | undefined initBlackskyOnly?: boolean + initCommunitySpaceUri?: string }): ComposerState { let media: ImagesMedia | GalleryMedia | undefined if (initImageUris?.length) { @@ -761,6 +793,7 @@ export function createComposerState({ allow: initInteractionSettings?.threadgateAllowRules, }), blackskyOnly: !!initBlackskyOnly, + communitySpaceUri: initCommunitySpaceUri, }, } } diff --git a/src/view/com/feeds/FeedPage.tsx b/src/view/com/feeds/FeedPage.tsx index 331c62e0d..7c40b8ce5 100644 --- a/src/view/com/feeds/FeedPage.tsx +++ b/src/view/com/feeds/FeedPage.tsx @@ -67,7 +67,7 @@ export function FeedPage({ const {_} = useLingui() const navigation = useNavigation>() const queryClient = useQueryClient() - const {openComposer} = useOpenComposer() + const {openComposer} = useOpenComposer(isPageFocused ? feed : undefined) const [isScrolledDown, setIsScrolledDown] = useState(false) const headerOffset = useHeaderOffset() const feedFeedback = useFeedFeedback(feedInfo, hasSession) diff --git a/src/view/com/post-thread/PostLikedBy.tsx b/src/view/com/post-thread/PostLikedBy.tsx index 48669d99c..a82b5644d 100644 --- a/src/view/com/post-thread/PostLikedBy.tsx +++ b/src/view/com/post-thread/PostLikedBy.tsx @@ -3,6 +3,7 @@ import {type AppBskyFeedGetLikes as GetLikes} from '@atproto/api' import {msg} from '@lingui/core/macro' import {useLingui} from '@lingui/react' +import {isSpaceRecordUri} from '#/lib/api/space-uri' import {useInitialNumToRender} from '#/lib/hooks/useInitialNumToRender' import {cleanError} from '#/lib/strings/errors' import {logger} from '#/logger' @@ -32,11 +33,11 @@ export function PostLikedBy({uri}: {uri: string}) { const [isPTRing, setIsPTRing] = useState(false) - const { - data: resolvedUri, - error: resolveError, - isLoading: isLoadingUri, - } = useResolveUriQuery(uri) + const isSpacePost = isSpaceRecordUri(uri) + const resolveQuery = useResolveUriQuery(isSpacePost ? undefined : uri) + const resolvedUri = isSpacePost ? {uri} : resolveQuery.data + const resolveError = isSpacePost ? undefined : resolveQuery.error + const isLoadingUri = isSpacePost ? false : resolveQuery.isLoading const { data, isLoading: isLoadingLikes, diff --git a/src/view/com/post-thread/PostQuotes.tsx b/src/view/com/post-thread/PostQuotes.tsx index 671334ad3..d03e491a8 100644 --- a/src/view/com/post-thread/PostQuotes.tsx +++ b/src/view/com/post-thread/PostQuotes.tsx @@ -8,6 +8,7 @@ import { import {msg} from '@lingui/core/macro' import {useLingui} from '@lingui/react' +import {isSpaceRecordUri} from '#/lib/api/space-uri' import {useInitialNumToRender} from '#/lib/hooks/useInitialNumToRender' import {usePostViewTracking} from '#/lib/hooks/usePostViewTracking' import {cleanError} from '#/lib/strings/errors' @@ -47,11 +48,11 @@ export function PostQuotes({uri}: {uri: string}) { const [isPTRing, setIsPTRing] = useState(false) const trackPostView = usePostViewTracking('PostQuotes') - const { - data: resolvedUri, - error: resolveError, - isLoading: isLoadingUri, - } = useResolveUriQuery(uri) + const isSpacePost = isSpaceRecordUri(uri) + const resolveQuery = useResolveUriQuery(isSpacePost ? undefined : uri) + const resolvedUri = isSpacePost ? {uri} : resolveQuery.data + const resolveError = isSpacePost ? undefined : resolveQuery.error + const isLoadingUri = isSpacePost ? false : resolveQuery.isLoading const { data, isLoading: isLoadingQuotes, diff --git a/src/view/com/post-thread/PostRepostedBy.tsx b/src/view/com/post-thread/PostRepostedBy.tsx index 611eb7c43..60d392264 100644 --- a/src/view/com/post-thread/PostRepostedBy.tsx +++ b/src/view/com/post-thread/PostRepostedBy.tsx @@ -3,6 +3,7 @@ import {type AppBskyActorDefs as ActorDefs} from '@atproto/api' import {msg} from '@lingui/core/macro' import {useLingui} from '@lingui/react' +import {isSpaceRecordUri} from '#/lib/api/space-uri' import {useInitialNumToRender} from '#/lib/hooks/useInitialNumToRender' import {cleanError} from '#/lib/strings/errors' import {logger} from '#/logger' @@ -38,11 +39,11 @@ export function PostRepostedBy({uri}: {uri: string}) { const [isPTRing, setIsPTRing] = useState(false) - const { - data: resolvedUri, - error: resolveError, - isLoading: isLoadingUri, - } = useResolveUriQuery(uri) + const isSpacePost = isSpaceRecordUri(uri) + const resolveQuery = useResolveUriQuery(isSpacePost ? undefined : uri) + const resolvedUri = isSpacePost ? {uri} : resolveQuery.data + const resolveError = isSpacePost ? undefined : resolveQuery.error + const isLoadingUri = isSpacePost ? false : resolveQuery.isLoading const { data, isLoading: isLoadingRepostedBy, diff --git a/src/view/com/post-thread/__tests__/space-engagement.test.tsx b/src/view/com/post-thread/__tests__/space-engagement.test.tsx new file mode 100644 index 000000000..b654fe45f --- /dev/null +++ b/src/view/com/post-thread/__tests__/space-engagement.test.tsx @@ -0,0 +1,95 @@ +import {type ReactNode} from 'react' +import {QueryClient, QueryClientProvider} from '@tanstack/react-query' +import {render, waitFor} from '@testing-library/react-native' + +const mockGetSpacePostLikes = jest.fn() +const mockGetSpacePostQuotes = jest.fn() +const mockAgent = { + getLikes: jest.fn(), + api: {app: {bsky: {feed: {getQuotes: jest.fn()}}}}, +} + +jest.mock('#/lib/api/community', () => ({ + getSpacePostLikes: (...args: unknown[]) => mockGetSpacePostLikes(...args), + getSpacePostQuotes: (...args: unknown[]) => mockGetSpacePostQuotes(...args), +})) +jest.mock('#/state/session', () => ({useAgent: () => mockAgent})) +jest.mock('#/state/queries/profile', () => ({ + useUnstableProfileViewCache: () => ({getUnstableProfile: jest.fn()}), +})) +jest.mock('@lingui/react', () => ({ + useLingui: () => ({_: (value: unknown) => value}), +})) +jest.mock('#/lib/hooks/useInitialNumToRender', () => ({ + useInitialNumToRender: () => 1, +})) +jest.mock('#/lib/hooks/usePostViewTracking', () => ({ + usePostViewTracking: () => jest.fn(), +})) +jest.mock('#/lib/strings/errors', () => ({ + cleanError: (error: unknown) => error, +})) +jest.mock('#/logger', () => ({logger: {error: jest.fn()}})) +jest.mock('#/state/preferences/moderation-opts', () => ({ + useModerationOpts: () => ({}), +})) +jest.mock('#/view/com/profile/ProfileCard', () => ({ + ProfileCardWithFollowBtn: () => null, +})) +jest.mock('#/view/com/post/Post', () => ({Post: () => null})) +jest.mock('#/view/com/util/List', () => ({List: () => null})) +jest.mock('#/components/Lists', () => ({ + ListFooter: () => null, + ListMaybePlaceholder: () => null, +})) + +import {PostLikedBy} from '../PostLikedBy' +import {PostQuotes} from '../PostQuotes' + +const SPACE_POST = + 'at://did:plc:space/space/community.blacksky.feed/test/did:plc:alice/app.bsky.feed.post/3kspace' + +function wrapper({children}: {children: ReactNode}) { + const queryClient = new QueryClient({ + defaultOptions: {queries: {retry: false}}, + }) + return ( + {children} + ) +} + +describe('permissioned-space post engagement components', () => { + beforeEach(() => { + jest.clearAllMocks() + mockGetSpacePostLikes.mockImplementation(() => new Promise(() => {})) + mockGetSpacePostQuotes.mockImplementation(() => new Promise(() => {})) + }) + + it('mounts liked-by and requests the space likes endpoint', async () => { + expect(() => + render(, {wrapper}), + ).not.toThrow() + + await waitFor(() => { + expect(mockGetSpacePostLikes).toHaveBeenCalledWith(mockAgent, { + uri: SPACE_POST, + limit: 30, + cursor: undefined, + }) + }) + }) + + it('mounts quotes and requests the space quotes endpoint', async () => { + expect(() => + render(, {wrapper}), + ).not.toThrow() + + await waitFor(() => { + expect(mockGetSpacePostQuotes).toHaveBeenCalledWith(mockAgent, { + uri: SPACE_POST, + limit: 30, + cursor: undefined, + }) + }) + }) +}) diff --git a/src/view/com/post/Post.tsx b/src/view/com/post/Post.tsx index 0e701312e..3ced56d22 100644 --- a/src/view/com/post/Post.tsx +++ b/src/view/com/post/Post.tsx @@ -10,9 +10,13 @@ import { } from '@atproto/api' import {useQueryClient} from '@tanstack/react-query' +import { + getCommunitySpaceUri, + isRenderablePostRecord, +} from '#/lib/api/community-post' import {MAX_POST_LINES} from '#/lib/constants' import {useOpenComposer} from '#/lib/hooks/useOpenComposer' -import {makeProfileLink} from '#/lib/routes/links' +import {postPermalink} from '#/lib/routes/links' import {countLines} from '#/lib/strings/helpers' import { POST_TOMBSTONE, @@ -39,7 +43,6 @@ import {TranslatedPost} from '#/components/Post/Translated' import {PostControls} from '#/components/PostControls' import {RichText} from '#/components/RichText' import {SubtleHover} from '#/components/SubtleHover' -import * as bsky from '#/types/bsky' export function Post({ post, @@ -56,10 +59,7 @@ export function Post({ }) { const moderationOpts = useModerationOpts() const record = useMemo( - () => - bsky.validate(post.record, AppBskyFeedPost.validateRecord) - ? post.record - : undefined, + () => (isRenderablePostRecord(post) ? post.record : undefined), [post], ) const postShadowed = usePostShadow(post) @@ -122,11 +122,7 @@ function PostInner({ const [limitLines, setLimitLines] = useState( () => countLines(richText?.text) >= MAX_POST_LINES, ) - const itemUrip = new AtUri(post.uri) - const isCommunityPost = itemUrip.collection === 'community.blacksky.feed.post' - const itemHref = isCommunityPost - ? `${makeProfileLink(post.author, 'post', itemUrip.rkey)}?collection=${itemUrip.collection}` - : makeProfileLink(post.author, 'post', itemUrip.rkey) + const itemHref = postPermalink(post.author, post.uri) let replyAuthorDid = '' if (record.reply) { const urip = new AtUri(record.reply.parent?.uri || record.reply.root.uri) @@ -143,6 +139,7 @@ function PostInner({ embed: post.embed, moderation, langs: record.langs, + communitySpace: getCommunitySpaceUri(post), }, logContext: 'PostReply', }) diff --git a/src/view/com/posts/PostFeedItem.tsx b/src/view/com/posts/PostFeedItem.tsx index 6fa693578..7a1a2c90e 100644 --- a/src/view/com/posts/PostFeedItem.tsx +++ b/src/view/com/posts/PostFeedItem.tsx @@ -11,11 +11,15 @@ import { } from '@atproto/api' import {useQueryClient} from '@tanstack/react-query' +import { + getCommunitySpaceUri, + isRenderablePostRecord, +} from '#/lib/api/community-post' import {type ReasonFeedSource} from '#/lib/api/feed/types' import {MAX_POST_LINES} from '#/lib/constants' import {useOpenComposer} from '#/lib/hooks/useOpenComposer' import {usePalette} from '#/lib/hooks/usePalette' -import {makeProfileLink} from '#/lib/routes/links' +import {postPermalink} from '#/lib/routes/links' import {countLines} from '#/lib/strings/helpers' import { POST_TOMBSTONE, @@ -174,12 +178,8 @@ let FeedItemInner = ({ const [href] = useMemo(() => { const urip = new AtUri(post.uri) - const link = makeProfileLink(post.author, 'post', urip.rkey) - const isCommunity = urip.collection === 'community.blacksky.feed.post' - return [ - isCommunity ? `${link}?collection=${urip.collection}` : link, - urip.rkey, - ] + const link = postPermalink(post.author, post.uri) + return [link, urip.rkey] }, [post.uri, post.author]) const {sendInteraction, feedSourceInfo, feedDescriptor} = useFeedFeedbackContext() @@ -200,6 +200,7 @@ let FeedItemInner = ({ embed: post.embed, moderation, langs: record.langs, + communitySpace: getCommunitySpaceUri(post), }, logContext: 'PostReply', }) @@ -482,10 +483,7 @@ let PostContent = ({ ) const record = useMemo( - () => - bsky.validate(post.record, AppBskyFeedPost.validateRecord) - ? post.record - : undefined, + () => (isRenderablePostRecord(post) ? post.record : undefined), [post], ) diff --git a/src/view/com/testing/TestCtrls.e2e.tsx b/src/view/com/testing/TestCtrls.e2e.tsx index f7e7bc1a1..0e395b559 100644 --- a/src/view/com/testing/TestCtrls.e2e.tsx +++ b/src/view/com/testing/TestCtrls.e2e.tsx @@ -2,6 +2,7 @@ import {useState} from 'react' import {LogBox, Pressable, TextInput, View} from 'react-native' import {useQueryClient} from '@tanstack/react-query' +import {setGroupInviteE2EFailure} from '#/lib/api/group-invite-e2e' import {BLUESKY_PROXY_HEADER} from '#/lib/constants' import {useAgent, useSessionApi} from '#/state/session' import {useLoggedOutViewControls} from '#/state/shell/logged-out' @@ -148,6 +149,24 @@ export function TestCtrls() { accessibilityRole="button" style={BTN} /> + setGroupInviteE2EFailure('saved-feed-update')} + accessibilityRole="button" + style={BTN} + /> + setGroupInviteE2EFailure('saved-feed-add')} + accessibilityRole="button" + style={BTN} + /> + setGroupInviteE2EFailure('navigation')} + accessibilityRole="button" + style={BTN} + /> ) } diff --git a/src/view/screens/PostThread.tsx b/src/view/screens/PostThread.tsx index c4ba6b7d3..8cd0e4816 100644 --- a/src/view/screens/PostThread.tsx +++ b/src/view/screens/PostThread.tsx @@ -1,8 +1,10 @@ +import {spacePostUriFromRoute} from '#/lib/api/space-permalink' import { type CommonNavigatorParams, type NativeStackScreenProps, } from '#/lib/routes/types' import {makeRecordUri} from '#/lib/strings/url-helpers' +import {useResolveDidQuery} from '#/state/queries/resolve-uri' import {PostThread} from '#/screens/PostThread' import * as Layout from '#/components/Layout' @@ -18,11 +20,48 @@ export function PostThreadScreen({route}: Props) { collection = collection || qs.get('collection') || undefined rkey = rkey.slice(0, qIndex) } - const uri = makeRecordUri(name, collection || 'app.bsky.feed.post', rkey) + const space = route.params.space return ( - + ) } + +function PostThreadRoute({ + name, + rkey, + collection, + space, +}: { + name: string + rkey: string + collection?: string + space?: string +}) { + // A space URI admits only DIDs in its author segment, so a handle in the + // path has to be resolved before the URI can be assembled. Links the app + // builds already carry DIDs; this covers hand-typed and shared URLs. + const needsDid = !!space && !name.startsWith('did:') + const {data: resolvedDid, isPending} = useResolveDidQuery( + needsDid ? name : undefined, + ) + if (needsDid && isPending) return null + + const author = needsDid ? resolvedDid : name + // Falling back to the ordinary URI when the space parts do not add up gives + // the thread's own not-found state rather than a blank screen. + const uri = + (space && + author && + spacePostUriFromRoute(space, author, rkey, collection)) || + makeRecordUri(name, collection || 'app.bsky.feed.post', rkey) + + return +} diff --git a/src/view/shell/Composer.ios.tsx b/src/view/shell/Composer.ios.tsx index 7a1f59937..bc8e2c649 100644 --- a/src/view/shell/Composer.ios.tsx +++ b/src/view/shell/Composer.ios.tsx @@ -47,6 +47,7 @@ export function Composer() { text={state?.text} imageUris={state?.imageUris} videoUri={state?.videoUri} + contextualCommunityFeedTarget={state?.contextualCommunityFeedTarget} /> diff --git a/src/view/shell/Composer.tsx b/src/view/shell/Composer.tsx index e5705f422..853c2e54c 100644 --- a/src/view/shell/Composer.tsx +++ b/src/view/shell/Composer.tsx @@ -48,6 +48,7 @@ export function Composer() { imageUris={state.imageUris} videoUri={state.videoUri} openGallery={state.openGallery} + contextualCommunityFeedTarget={state.contextualCommunityFeedTarget} /> ) diff --git a/src/view/shell/Composer.web.tsx b/src/view/shell/Composer.web.tsx index d7d0e4ed8..0ab8d6958 100644 --- a/src/view/shell/Composer.web.tsx +++ b/src/view/shell/Composer.web.tsx @@ -72,6 +72,7 @@ function Inner({state}: {state: ComposerOpts}) { text={state.text} imageUris={state.imageUris} openGallery={state.openGallery} + contextualCommunityFeedTarget={state.contextualCommunityFeedTarget} /> diff --git a/src/view/shell/__tests__/Composer-context.test.tsx b/src/view/shell/__tests__/Composer-context.test.tsx new file mode 100644 index 000000000..3d3a2f80f --- /dev/null +++ b/src/view/shell/__tests__/Composer-context.test.tsx @@ -0,0 +1,57 @@ +import {render} from '@testing-library/react-native' + +const mockComposePost = jest.fn((_props: Record) => null) +const mockUseComposerState = jest.fn() + +jest.mock('#/state/shell/composer', () => ({ + useComposerState: () => mockUseComposerState(), +})) +jest.mock('#/view/com/composer/Composer', () => ({ + ComposePost: (props: Record) => mockComposePost(props), + useComposerCancelRef: () => ({current: null}), +})) +jest.mock('#/components/Tooltip', () => ({ + SheetCompatProvider: ({children}: {children: React.ReactNode}) => children, +})) +jest.mock('#/alf', () => ({ + atoms: {absolute: {}, inset_0: {}}, + useTheme: () => ({name: 'light', atoms: {bg: {}}}), +})) +jest.mock('react-native-edge-to-edge', () => ({ + SystemBars: { + pushStackEntry: jest.fn(() => ({})), + popStackEntry: jest.fn(), + }, +})) +jest.mock('react-native-reanimated', () => { + const {View} = require('react-native') + const animation = {duration: () => animation, easing: () => animation} + return { + __esModule: true, + default: {View}, + Easing: {out: jest.fn(), in: jest.fn(), exp: {}, quad: {}}, + SlideInDown: animation, + SlideOutDown: animation, + } +}) + +import {Composer} from '../Composer' + +describe('Composer selected feed context', () => { + it('forwards the contextual private feed into ComposePost', () => { + const target = { + feed: 'at://did:plc:test/app.bsky.feed.generator/private', + name: 'Private Test', + } + mockUseComposerState.mockReturnValue({ + text: 'hello', + contextualCommunityFeedTarget: target, + }) + + render() + + expect(mockComposePost).toHaveBeenCalledWith( + expect.objectContaining({contextualCommunityFeedTarget: target}), + ) + }) +}) diff --git a/src/view/shell/desktop/LeftNav.tsx b/src/view/shell/desktop/LeftNav.tsx index 53181655c..a62ec5edb 100644 --- a/src/view/shell/desktop/LeftNav.tsx +++ b/src/view/shell/desktop/LeftNav.tsx @@ -17,12 +17,15 @@ import { import {sanitizeDisplayName} from '#/lib/strings/display-names' import {isInvalidHandle, sanitizeHandle} from '#/lib/strings/handles' import {emitSoftReset} from '#/state/events' +import {usePinnedFeedsInfos} from '#/state/queries/feed' import {useFetchHandle} from '#/state/queries/handle' import {useUnreadMessageCount} from '#/state/queries/messages/list-conversations' import {useUnreadNotifications} from '#/state/queries/notifications/unread' +import {type FeedDescriptor} from '#/state/queries/post-feed' import {useProfilesQuery} from '#/state/queries/profile' import {type SessionAccount, useSession, useSessionApi} from '#/state/session' import {useLoggedOutViewControls} from '#/state/shell/logged-out' +import {useSelectedFeed} from '#/state/shell/selected-feed' import {useCloseAllActiveElements} from '#/state/util' import {LoadingPlaceholder} from '#/view/com/util/LoadingPlaceholder' import {PressableWithHover} from '#/view/com/util/PressableWithHover' @@ -543,7 +546,22 @@ function NavItem({ function ComposeBtn({minimal}: {minimal: boolean}) { const {currentAccount} = useSession() const {getState} = useNavigation() - const {openComposer} = useOpenComposer() + const currentRoute = useNavigationState(state => + state ? getCurrentRoute(state) : {name: 'Home'}, + ) + const selectedFeed = useSelectedFeed() + const {data: pinnedFeedInfos} = usePinnedFeedsInfos() + const contextualFeed = + currentRoute.name === 'Home' + ? (selectedFeed ?? pinnedFeedInfos?.[0]?.feedDescriptor) + : currentRoute.name === 'ProfileFeed' + ? (( + currentRoute.params as + | CommonNavigatorParams['ProfileFeed'] + | undefined + )?.resolvedFeed as FeedDescriptor | undefined) + : undefined + const {openComposer} = useOpenComposer(contextualFeed) const {t: l} = useLingui() const brand = useBrand() const {leftNavMinimal} = useLayoutBreakpoints()