mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 16:33:16 +00:00
feat(journey): read and unlock protected share links in the client hooks
The data side of the protected journey link (#2553), without markup yet: - journeyApi.unlockPublicJourney posts a reader's password; the answer sets the link's unlock cookie. - useJourneyPublic tells a locked link (access 'locked') and an expired one ('expired') apart from a broken one, and unlock() reports 'ok', 'wrong', 'rate_limited', 'expired' or 'failed', reloading the journey on success. - useJourneyShareLink carries has_password, expires_at, view_count and last_viewed_at, and setProtection() sets or clears the password and the expiry, shown only once the server took it.
This commit is contained in:
@@ -1047,6 +1047,12 @@ export const journeyApi = {
|
||||
createShareLink: (id: number, perms: JourneyShareLinkRequest) => apiClient.post(`/journeys/${id}/share-link`, perms).then(r => r.data),
|
||||
deleteShareLink: (id: number) => apiClient.delete(`/journeys/${id}/share-link`).then(r => r.data),
|
||||
getPublicJourney: (token: string) => apiClient.get(`/public/journey/${token}`).then(r => r.data),
|
||||
/**
|
||||
* A reader's password for a protected link (#2553). The answer sets the link's
|
||||
* unlock cookie, which every later read and photo of that link sends along.
|
||||
*/
|
||||
unlockPublicJourney: (token: string, password: string): Promise<{ success: true }> =>
|
||||
apiClient.post(`/public/journey/${token}/unlock`, { password }).then(r => r.data),
|
||||
}
|
||||
|
||||
// Photo providers (Immich, Synology Photos, …) behind /api/integrations/memories.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-JRN-SHAREHOOK-001 to FE-JRN-SHAREHOOK-009: the public share link logic behind
|
||||
// FE-JRN-SHAREHOOK-001 to FE-JRN-SHAREHOOK-011: the public share link logic behind
|
||||
// both the desktop share section and the phone settings sheet.
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
@@ -134,4 +134,37 @@ describe('useJourneyShareLink', () => {
|
||||
await act(() => result.current.togglePerm('share_recordings'));
|
||||
expect(posted[1]).toEqual({ share_timeline: true, share_gallery: false, share_map: true, share_recordings: true });
|
||||
});
|
||||
|
||||
it('FE-JRN-SHAREHOOK-010: a password and an expiry are saved on their own and only shown once taken (#2553)', async () => {
|
||||
const { result } = await loaded();
|
||||
let saved: boolean | undefined;
|
||||
await act(async () => {
|
||||
saved = await result.current.setProtection({ password: 'secret', expires_at: '2027-01-01T00:00:00.000Z' });
|
||||
});
|
||||
expect(saved).toBe(true);
|
||||
expect(posted).toEqual([{ password: 'secret', expires_at: '2027-01-01T00:00:00.000Z' }]);
|
||||
expect(result.current.link?.has_password).toBe(true);
|
||||
expect(result.current.link?.expires_at).toBe('2027-01-01T00:00:00.000Z');
|
||||
// The password itself is never kept on the client.
|
||||
expect(JSON.stringify(result.current.link)).not.toContain('secret');
|
||||
|
||||
await act(async () => {
|
||||
await result.current.setProtection({ password: null });
|
||||
});
|
||||
expect(posted[1]).toEqual({ password: null });
|
||||
expect(result.current.link?.has_password).toBe(false);
|
||||
expect(result.current.link?.expires_at).toBe('2027-01-01T00:00:00.000Z');
|
||||
});
|
||||
|
||||
it('FE-JRN-SHAREHOOK-011: a refused protection change toasts and leaves the link as it was', async () => {
|
||||
const { result } = await loaded();
|
||||
server.use(http.post('/api/journeys/7/share-link', () => HttpResponse.json({ error: 'x' }, { status: 400 })));
|
||||
let saved: boolean | undefined;
|
||||
await act(async () => {
|
||||
saved = await result.current.setProtection({ expires_at: null });
|
||||
});
|
||||
expect(saved).toBe(false);
|
||||
expect(result.current.link).toEqual(LINK);
|
||||
expect(addToast).toHaveBeenCalledWith('journey.share.updateFailed', 'error', undefined);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -13,6 +13,22 @@ export interface JourneyShareLink {
|
||||
/** JRN-04: the trips' plan and the recorded days on the shared map; off unless switched on. */
|
||||
share_plan?: boolean;
|
||||
share_recordings?: boolean;
|
||||
/** #2553: whether readers have to enter a password first; the password itself never comes back. */
|
||||
has_password?: boolean;
|
||||
/** When the link stops working (ISO, UTC), null for never. */
|
||||
expires_at?: string | null;
|
||||
/** Readers who opened the link, each counted once a day, and when the last one did (ISO, UTC). */
|
||||
view_count?: number;
|
||||
last_viewed_at?: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A change to a link's protection (#2553): a new password or null to take it
|
||||
* off, an ISO expiry or null for never. What is left out stays as it is.
|
||||
*/
|
||||
interface JourneyShareProtectionChange {
|
||||
password?: string | null;
|
||||
expires_at?: string | null;
|
||||
}
|
||||
|
||||
/** What the shared map can show besides the entries, each only while the map itself is shared. */
|
||||
@@ -25,6 +41,15 @@ export const SHARE_MAP_EXTRAS: { key: JourneyShareMapExtra; labelKey: string; hi
|
||||
{ key: 'share_recordings', labelKey: 'journey.share.recordings', hintKey: 'journey.share.recordingsHint' },
|
||||
];
|
||||
|
||||
/** The link as it reads after `change` was saved: the password is only ever known as there or not. */
|
||||
function applyProtection(link: JourneyShareLink, change: JourneyShareProtectionChange): JourneyShareLink {
|
||||
return {
|
||||
...link,
|
||||
...(change.password !== undefined ? { has_password: change.password !== null } : {}),
|
||||
...(change.expires_at !== undefined ? { expires_at: change.expires_at } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** The public address of a journey share token. */
|
||||
export function journeyShareUrl(link: JourneyShareLink | null, origin: string): string {
|
||||
return link ? `${origin}/public/journey/${link.token}` : '';
|
||||
@@ -101,9 +126,27 @@ export function useJourneyShareLink(journeyId: number) {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Set or take off the password, or change the expiry. Not optimistic: the
|
||||
* link only shows the new state once the server took it, and a refusal toasts
|
||||
* and leaves it as it was. Resolves whether it was saved, so a dialog knows
|
||||
* whether to close.
|
||||
*/
|
||||
const setProtection = async (change: JourneyShareProtectionChange): Promise<boolean> => {
|
||||
if (!link) return false;
|
||||
try {
|
||||
await journeyApi.createShareLink(journeyId, change);
|
||||
setLink((current) => (current ? applyProtection(current, change) : current));
|
||||
return true;
|
||||
} catch {
|
||||
toast.error(t('journey.share.updateFailed'));
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const shareUrl = journeyShareUrl(link, window.location.origin);
|
||||
|
||||
const copyLink = () => copy(shareUrl);
|
||||
|
||||
return { link, loading, manageable, copied, shareUrl, createLink, togglePerm, deleteLink, copyLink };
|
||||
return { link, loading, manageable, copied, shareUrl, createLink, togglePerm, deleteLink, copyLink, setProtection };
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
* No React, no side effects — safe to import from both the data hook and the
|
||||
* presentational page.
|
||||
*/
|
||||
import { JOURNEY_PUBLIC_ERROR_CODES } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* An entry as the share link sends it (`journeyPublicEntrySchema` in
|
||||
@@ -53,6 +54,41 @@ export interface PublicGalleryPhoto extends PublicPhoto {
|
||||
lng?: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the link lets this browser in (#2553): open, waiting for its
|
||||
* password, or past the date its owner set.
|
||||
*/
|
||||
export type PublicLinkAccess = 'open' | 'locked' | 'expired';
|
||||
|
||||
/** What typing a password came to. */
|
||||
export type PublicUnlockOutcome = 'ok' | 'wrong' | 'rate_limited' | 'expired' | 'failed';
|
||||
|
||||
interface ApiErrorLike {
|
||||
response?: { status?: number; data?: { code?: unknown } };
|
||||
}
|
||||
|
||||
function failureOf(err: unknown): { status?: number; code?: unknown } {
|
||||
const response = (err as ApiErrorLike | null)?.response;
|
||||
return { status: response?.status, code: response?.data?.code };
|
||||
}
|
||||
|
||||
/** The access a failed read of the link means, or null for any other failure. */
|
||||
export function publicLinkAccessOf(err: unknown): Exclude<PublicLinkAccess, 'open'> | null {
|
||||
const { status, code } = failureOf(err);
|
||||
if (status === 401 && code === JOURNEY_PUBLIC_ERROR_CODES.locked) return 'locked';
|
||||
if (status === 410 && code === JOURNEY_PUBLIC_ERROR_CODES.expired) return 'expired';
|
||||
return null;
|
||||
}
|
||||
|
||||
/** What a failed unlock means to the reader. */
|
||||
export function unlockOutcomeOf(err: unknown): Exclude<PublicUnlockOutcome, 'ok'> {
|
||||
const { status, code } = failureOf(err);
|
||||
if (status === 401 && code === JOURNEY_PUBLIC_ERROR_CODES.denied) return 'wrong';
|
||||
if (status === 429) return 'rate_limited';
|
||||
if (status === 410) return 'expired';
|
||||
return 'failed';
|
||||
}
|
||||
|
||||
export function groupByDate(entries: PublicEntry[]): Map<string, PublicEntry[]> {
|
||||
const groups = new Map<string, PublicEntry[]>();
|
||||
for (const e of entries) {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// FE-JRN-PUBHOOK-001 to FE-JRN-PUBHOOK-003
|
||||
// FE-JRN-PUBHOOK-001 to FE-JRN-PUBHOOK-007
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { renderHook, waitFor } from '../../../tests/helpers/render';
|
||||
import { act, renderHook, waitFor } from '../../../tests/helpers/render';
|
||||
import type { PublicEntry } from './journeyPublicModel';
|
||||
import { useJourneyPublic } from './useJourneyPublic';
|
||||
|
||||
@@ -108,4 +108,88 @@ describe('useJourneyPublic', () => {
|
||||
// A journey that ended long ago, read oldest-first, starts at the beginning.
|
||||
await waitFor(() => expect(result.current.openAtEntryId).toBeNull());
|
||||
});
|
||||
|
||||
it('FE-JRN-PUBHOOK-004: a link with a password reads as locked, not as broken (#2553)', async () => {
|
||||
server.use(
|
||||
http.get('/api/public/journey/tok-1', () =>
|
||||
HttpResponse.json({ error: 'Password required', code: 'JOURNEY_PASSWORD_REQUIRED' }, { status: 401 })
|
||||
)
|
||||
);
|
||||
const { result } = renderHook(() => useJourneyPublic());
|
||||
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
expect(result.current.access).toBe('locked');
|
||||
expect(result.current.error).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-JRN-PUBHOOK-005: a link past its date reads as expired', async () => {
|
||||
server.use(
|
||||
http.get('/api/public/journey/tok-1', () =>
|
||||
HttpResponse.json({ error: 'This link has expired', code: 'JOURNEY_LINK_EXPIRED' }, { status: 410 })
|
||||
)
|
||||
);
|
||||
const { result } = renderHook(() => useJourneyPublic());
|
||||
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
expect(result.current.access).toBe('expired');
|
||||
expect(result.current.error).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-JRN-PUBHOOK-006: the right password loads the journey', async () => {
|
||||
let unlocked = false;
|
||||
const sent: unknown[] = [];
|
||||
server.use(
|
||||
http.get('/api/public/journey/tok-1', () =>
|
||||
unlocked
|
||||
? HttpResponse.json({
|
||||
journey: { title: 'Japan' },
|
||||
entries: [buildEntry({ id: 1 })],
|
||||
gallery: [],
|
||||
permissions: { share_timeline: true, share_gallery: true, share_map: false },
|
||||
stats: {},
|
||||
})
|
||||
: HttpResponse.json({ error: 'Password required', code: 'JOURNEY_PASSWORD_REQUIRED' }, { status: 401 })
|
||||
),
|
||||
http.post('/api/public/journey/tok-1/unlock', async ({ request }) => {
|
||||
sent.push(await request.json());
|
||||
unlocked = true;
|
||||
return HttpResponse.json({ success: true });
|
||||
})
|
||||
);
|
||||
const { result } = renderHook(() => useJourneyPublic());
|
||||
await waitFor(() => expect(result.current.access).toBe('locked'));
|
||||
|
||||
let outcome: string | undefined;
|
||||
await act(async () => {
|
||||
outcome = await result.current.unlock('secret');
|
||||
});
|
||||
|
||||
expect(outcome).toBe('ok');
|
||||
expect(sent).toEqual([{ password: 'secret' }]);
|
||||
await waitFor(() => expect(result.current.access).toBe('open'));
|
||||
expect(result.current.timelineEntries).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('FE-JRN-PUBHOOK-007: a wrong password, too many tries and a dead link each say so', async () => {
|
||||
let answer = HttpResponse.json({ error: 'Wrong password', code: 'JOURNEY_PASSWORD_INVALID' }, { status: 401 });
|
||||
server.use(
|
||||
http.get('/api/public/journey/tok-1', () =>
|
||||
HttpResponse.json({ error: 'Password required', code: 'JOURNEY_PASSWORD_REQUIRED' }, { status: 401 })
|
||||
),
|
||||
http.post('/api/public/journey/tok-1/unlock', () => answer)
|
||||
);
|
||||
const { result } = renderHook(() => useJourneyPublic());
|
||||
await waitFor(() => expect(result.current.access).toBe('locked'));
|
||||
|
||||
expect(await result.current.unlock('nope')).toBe('wrong');
|
||||
answer = HttpResponse.json({ error: 'Too many attempts. Please try again later.' }, { status: 429 });
|
||||
expect(await result.current.unlock('nope')).toBe('rate_limited');
|
||||
answer = HttpResponse.json({ error: 'boom' }, { status: 500 });
|
||||
expect(await result.current.unlock('nope')).toBe('failed');
|
||||
answer = HttpResponse.json({ error: 'This link has expired', code: 'JOURNEY_LINK_EXPIRED' }, { status: 410 });
|
||||
await act(async () => {
|
||||
expect(await result.current.unlock('nope')).toBe('expired');
|
||||
});
|
||||
expect(result.current.access).toBe('expired');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,7 +7,10 @@ import { useIsMobile } from '../../hooks/useIsMobile'
|
||||
import { DAY_COLORS } from '../../components/Journey/dayColors'
|
||||
import { journeyMapStops } from '../../components/Journey/journeyMapStops'
|
||||
import { posterlessVideo } from '../journeyDetail/JourneyDetailPage.helpers'
|
||||
import { groupByDate, type PublicEntry, type PublicGalleryPhoto } from './journeyPublicModel'
|
||||
import {
|
||||
groupByDate, publicLinkAccessOf, unlockOutcomeOf,
|
||||
type PublicEntry, type PublicGalleryPhoto, type PublicLinkAccess, type PublicUnlockOutcome,
|
||||
} from './journeyPublicModel'
|
||||
import { useJourneyMapLayers } from '../../components/Journey/useJourneyMapLayers'
|
||||
import { journeyOpenAtEntryId } from '../../components/Journey/journeyOpenAt'
|
||||
import { localIsoDate } from '../../utils/localDate'
|
||||
@@ -26,6 +29,11 @@ export function useJourneyPublic() {
|
||||
const [data, setData] = useState<any>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState(false)
|
||||
// #2553: a link with a password answers 401 until this browser unlocked it,
|
||||
// one past its date 410; the page shows a password card or a "gone" note.
|
||||
const [access, setAccess] = useState<PublicLinkAccess>('open')
|
||||
// Bumped by a successful unlock, so the read runs again with the new cookie.
|
||||
const [reloadKey, setReloadKey] = useState(0)
|
||||
const isMobile = useIsMobile()
|
||||
const [view, setView] = useState<'timeline' | 'gallery' | 'map'>('timeline')
|
||||
const [lightbox, setLightbox] = useState<{ photos: { id: string; src: string; thumbSrc?: string; caption?: string | null; mediaType?: string | null }[]; index: number } | null>(null)
|
||||
@@ -46,10 +54,44 @@ export function useJourneyPublic() {
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) return
|
||||
let cancelled = false
|
||||
journeyApi.getPublicJourney(token)
|
||||
.then(d => setData(d))
|
||||
.catch(() => setError(true))
|
||||
.finally(() => setLoading(false))
|
||||
.then(d => {
|
||||
if (cancelled) return
|
||||
setData(d)
|
||||
setAccess('open')
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (cancelled) return
|
||||
const refused = publicLinkAccessOf(err)
|
||||
if (refused) setAccess(refused)
|
||||
else setError(true)
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false)
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [token, reloadKey])
|
||||
|
||||
/**
|
||||
* Send the password a reader typed. On 'ok' the server has set the link's
|
||||
* cookie and the journey loads; every other outcome is for the password card
|
||||
* to word ('wrong', 'rate_limited', 'expired', 'failed').
|
||||
*/
|
||||
const unlock = useCallback(async (password: string): Promise<PublicUnlockOutcome> => {
|
||||
if (!token) return 'failed'
|
||||
try {
|
||||
await journeyApi.unlockPublicJourney(token, password)
|
||||
} catch (err) {
|
||||
const outcome = unlockOutcomeOf(err)
|
||||
if (outcome === 'expired') setAccess('expired')
|
||||
return outcome
|
||||
}
|
||||
setLoading(true)
|
||||
setReloadKey(n => n + 1)
|
||||
return 'ok'
|
||||
}, [token])
|
||||
|
||||
const entries = (data?.entries || []) as PublicEntry[]
|
||||
@@ -170,7 +212,7 @@ export function useJourneyPublic() {
|
||||
}, [desktopTwoColumn, view])
|
||||
|
||||
return {
|
||||
token, data, loading, error, isMobile, locale,
|
||||
token, data, loading, error, access, unlock, isMobile, locale,
|
||||
view, setView, lightbox, setLightbox, showLangPicker, setShowLangPicker,
|
||||
mapRef, feedRef, activeEntryId, setActiveEntryId, viewingEntry, setViewingEntry, handleMarkerClick,
|
||||
perms, journey, stats,
|
||||
|
||||
Reference in New Issue
Block a user