From be4999e1e0cd7bb2948a8c895de4a97aca2a0d20 Mon Sep 17 00:00:00 2001 From: Rishi Balakrishnan Date: Sat, 29 Aug 2026 11:05:14 -0400 Subject: [PATCH] feat(invites): add group deep-link join flow --- __e2e__/flows/group-invite/accept-outage.yml | 28 + .../group-invite/authentication-required.yml | 28 + .../flows/group-invite/capability-outage.yml | 33 ++ .../flows/group-invite/cold-auth-resume.yml | 24 + .../flows/group-invite/existing-unpinned.yml | 35 ++ .../flows/group-invite/group-at-capacity.yml | 28 + .../group-invite/https-universal-link.yml | 19 + .../invite-unavailable-consumed.yml | 20 + .../invite-unavailable-expired.yml | 14 + .../invite-unavailable-missing.yml | 20 + __e2e__/flows/group-invite/malformed-link.yml | 19 + .../flows/group-invite/malformed-success.yml | 33 ++ __e2e__/flows/group-invite/misconfigured.yml | 14 + .../flows/group-invite/navigation-failure.yml | 45 ++ __e2e__/flows/group-invite/no-post.yml | 24 + .../flows/group-invite/pin-add-failure.yml | 43 ++ .../flows/group-invite/pin-update-failure.yml | 43 ++ .../flows/group-invite/preview-identity.yml | 21 + __e2e__/flows/group-invite/preview-outage.yml | 14 + __e2e__/flows/group-invite/rapid-taps.yml | 35 ++ __e2e__/flows/group-invite/rate-limit.yml | 28 + __e2e__/flows/group-invite/read-only.yml | 36 ++ .../flows/group-invite/same-did-other-did.yml | 65 +++ .../selection-readable-fallback.yml | 37 ++ __e2e__/flows/group-invite/success-mixed.yml | 47 ++ .../flows/group-invite/warm-custom-scheme.yml | 23 + __e2e__/flows/group-invite/zero-readable.yml | 30 ++ __e2e__/helpers/assert-group-invite-state.js | 80 +++ __e2e__/helpers/group-invite-setup.yml | 8 + .../helpers/group-invite-sign-in-alice.yml | 12 + __e2e__/helpers/group-invite-sign-in.yml | 24 + __e2e__/setupApp.yml | 12 +- __e2e__/setupServer.js | 26 +- dev-env/group-invite-fixture.ts | 314 +++++++++++ dev-env/mock-server.ts | 241 ++++++++- dev-env/test-pds.ts | 128 ++++- docs/testing.md | 22 + package.json | 8 +- src/Navigation.tsx | 14 +- src/analytics/metrics/types.ts | 14 + src/components/Dialog/index.tsx | 3 + src/components/Dialog/index.web.tsx | 2 +- src/components/forms/Toggle/index.tsx | 1 + .../hooks/useLandingEntry.native.ts | 17 +- src/components/intents/GroupInviteDialog.tsx | 502 ++++++++++++++++++ src/components/intents/IntentDialogs.tsx | 44 ++ src/env/common.ts | 16 + .../__tests__/group-invite-fixture.test.ts | 132 +++++ src/lib/api/__tests__/group-invite-ui.test.ts | 200 +++++++ src/lib/api/__tests__/group-invites.test.ts | 183 +++++++ src/lib/api/group-invite-e2e.e2e.ts | 33 ++ src/lib/api/group-invite-e2e.ts | 20 + src/lib/api/group-invite-ui.ts | 124 +++++ src/lib/api/group-invites.ts | 280 ++++++++++ src/lib/hooks/useIntentHandler.ts | 86 ++- .../__tests__/group-invite-url.test.ts | 29 + src/lib/strings/__tests__/url-helpers.test.ts | 27 + src/lib/strings/url-helpers.ts | 47 ++ src/screens/GroupInviteLanding.tsx | 108 ++++ src/screens/Login/LoginForm.tsx | 50 ++ src/screens/Login/index.tsx | 1 + src/state/queries/group-invites.ts | 42 ++ src/state/shell/landing.tsx | 64 ++- src/state/shell/logged-out.tsx | 3 + src/view/com/auth/LoggedOut.tsx | 6 + src/view/com/testing/TestCtrls.e2e.tsx | 19 + 66 files changed, 3705 insertions(+), 43 deletions(-) create mode 100644 __e2e__/flows/group-invite/accept-outage.yml create mode 100644 __e2e__/flows/group-invite/authentication-required.yml create mode 100644 __e2e__/flows/group-invite/capability-outage.yml create mode 100644 __e2e__/flows/group-invite/cold-auth-resume.yml create mode 100644 __e2e__/flows/group-invite/existing-unpinned.yml create mode 100644 __e2e__/flows/group-invite/group-at-capacity.yml create mode 100644 __e2e__/flows/group-invite/https-universal-link.yml create mode 100644 __e2e__/flows/group-invite/invite-unavailable-consumed.yml create mode 100644 __e2e__/flows/group-invite/invite-unavailable-expired.yml create mode 100644 __e2e__/flows/group-invite/invite-unavailable-missing.yml create mode 100644 __e2e__/flows/group-invite/malformed-link.yml create mode 100644 __e2e__/flows/group-invite/malformed-success.yml create mode 100644 __e2e__/flows/group-invite/misconfigured.yml create mode 100644 __e2e__/flows/group-invite/navigation-failure.yml create mode 100644 __e2e__/flows/group-invite/no-post.yml create mode 100644 __e2e__/flows/group-invite/pin-add-failure.yml create mode 100644 __e2e__/flows/group-invite/pin-update-failure.yml create mode 100644 __e2e__/flows/group-invite/preview-identity.yml create mode 100644 __e2e__/flows/group-invite/preview-outage.yml create mode 100644 __e2e__/flows/group-invite/rapid-taps.yml create mode 100644 __e2e__/flows/group-invite/rate-limit.yml create mode 100644 __e2e__/flows/group-invite/read-only.yml create mode 100644 __e2e__/flows/group-invite/same-did-other-did.yml create mode 100644 __e2e__/flows/group-invite/selection-readable-fallback.yml create mode 100644 __e2e__/flows/group-invite/success-mixed.yml create mode 100644 __e2e__/flows/group-invite/warm-custom-scheme.yml create mode 100644 __e2e__/flows/group-invite/zero-readable.yml create mode 100644 __e2e__/helpers/assert-group-invite-state.js create mode 100644 __e2e__/helpers/group-invite-setup.yml create mode 100644 __e2e__/helpers/group-invite-sign-in-alice.yml create mode 100644 __e2e__/helpers/group-invite-sign-in.yml create mode 100644 dev-env/group-invite-fixture.ts create mode 100644 src/components/intents/GroupInviteDialog.tsx create mode 100644 src/lib/api/__tests__/group-invite-fixture.test.ts create mode 100644 src/lib/api/__tests__/group-invite-ui.test.ts create mode 100644 src/lib/api/__tests__/group-invites.test.ts create mode 100644 src/lib/api/group-invite-e2e.e2e.ts create mode 100644 src/lib/api/group-invite-e2e.ts create mode 100644 src/lib/api/group-invite-ui.ts create mode 100644 src/lib/api/group-invites.ts create mode 100644 src/lib/strings/__tests__/group-invite-url.test.ts create mode 100644 src/lib/strings/__tests__/url-helpers.test.ts create mode 100644 src/screens/GroupInviteLanding.tsx create mode 100644 src/state/queries/group-invites.ts 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/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/package.json b/package.json index bc9ae2a89..d834627b4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "blacksky.community", - "version": "1.131.4", + "version": "1.132.0", "private": true, "packageManager": "pnpm@11.7.0", "engines": { @@ -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/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/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__/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/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/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/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 af5e7bf16..48568f703 100644 --- a/src/lib/strings/url-helpers.ts +++ b/src/lib/strings/url-helpers.ts @@ -216,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)) { 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 = ( + 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/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/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} + /> ) } -- knotmirror 0.0.1