Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

A code from a link no longer signs this browser in to someone else's profile unnoticed, nor moves a guest's workouts into it unasked (#95)

Duarte Santos37d4937211b4
diff --git a/api/openapi.yaml b/api/openapi.yaml
index c20bb4bd9..aa2918f4f 100644
--- a/api/openapi.yaml
+++ b/api/openapi.yaml
@@ -1099,7 +1099,7 @@ paths:
description: |
Called on the other device, which has no session: the code is the credential.
Returns creation options for the profile the code belongs to, and that profile's
- name. Does not use the code up, so a dismissed passkey prompt can be tried again.
+ id and name. Does not use the code up, so a dismissed passkey prompt can be tried again.
Wrong codes count toward a per-address pause of link redemption (see
*Throttling*). **Not** CSRF-exempt.
security: []
@@ -1123,6 +1123,7 @@ paths:
properties:
cid: { type: string }
options: { $ref: '#/components/schemas/WebAuthnRegistrationOptions' }
+ id: { type: string, description: "The profile's id (also the options' user handle). Names are not unique; this is what tells two profiles apart." }
name: { type: string, description: The profile this device is being added to. }
'400': { $ref: '#/components/responses/LinkInvalid' }
'409': { $ref: '#/components/responses/PasskeyLimit' }
diff --git a/api/server.js b/api/server.js
index 5d9cd3c2c..b703aef35 100644
--- a/api/server.js
+++ b/api/server.js
@@ -1336,7 +1336,10 @@ const passkeyRoutes = {
// Redeeming, from the other device, which has no session: the code is the credential. Step one
// checks it and hands back creation options for the profile it belongs to, and that profile's
- // name, so the screen can say where this device is being added. It does not use the code up —
+ // name and id, so the screen can say where this device is being added — and tell it apart from
+ // the profile this browser is signed in as by the id, since names are not unique and whoever
+ // sends a code chooses the name of theirs. The id is the options' user handle anyway, so it
+ // tells the holder of the code nothing new. It does not use the code up —
// a passkey prompt dismissed by mistake can be tried again — and wrong codes pause the address.
// Not CSRF-exempt: only the app's own origin can create a passkey for it anyway, and a code
// redeemed from anywhere else is not one the owner meant to hand over.
@@ -1357,7 +1360,7 @@ const passkeyRoutes = {
if (passkeyCount(user) >= MAX_PASSKEYS) return json(res, 409, LIMIT);
const options = await moreOptions(user);
const cid = putChallenge({ challenge: options.challenge, uid: user.id, kind: 'link', lh: link.h });
- json(res, 200, { cid, options, name: user.name });
+ json(res, 200, { cid, options, id: user.id, name: user.name });
},
// Step two: the new passkey is stored, the code is burned, and this device is signed in by the
diff --git a/api/test/server-passkeys.test.js b/api/test/server-passkeys.test.js
index 198fa0fa1..d2247f4c5 100644
--- a/api/test/server-passkeys.test.js
+++ b/api/test/server-passkeys.test.js
@@ -346,6 +346,7 @@ test('a device link: made with proof, kept only as a hash, redeemed once by a ne
const opt = await h.req('POST', '/api/device-link/options', { body: { code: code.toLowerCase() }, ip: '198.51.100.41' });
assert.equal(opt.status, 200);
assert.equal(opt.body.name, 'Ana');
+ assert.equal(opt.body.id, 'u1'); // what the other device tells profiles apart by, not the name
assert.deepEqual(opt.body.options.excludeCredentials.map(c => c.id), [key.id]);
const done = await h.req('POST', '/api/device-link/verify', {
body: { code, cid: opt.body.cid, credential: phone.attestation(opt.body.options.challenge), name: 'Phone' }, ip: '198.51.100.41'
diff --git a/frontend/src/components/Passkeys.jsx b/frontend/src/components/Passkeys.jsx
index 3b6f3130c..512fbd831 100644
--- a/frontend/src/components/Passkeys.jsx
+++ b/frontend/src/components/Passkeys.jsx
@@ -266,14 +266,22 @@ export function DeviceLinkSheet({ close }) {
in. The code comes from the link's ?link= (the store holds it, see boot()) or is typed. A code
from a link is checked as the sheet opens, so it can say whose profile this device is joining
and the passkey prompt then opens straight from the tap. The passkey is named after this
- browser (deviceLabel), which the list in Settings can change. Signed in afterwards exactly as a
- passkey sign-in on the sign-in screen is: the same account coming back merges what this device
- kept for it (adoptProfile), and another account's copy is kept aside for that one (setUser). */
+ browser (deviceLabel), which the list in Settings can change. Signed in afterwards like a
+ passkey sign-in on the sign-in screen: the same account coming back merges what this device
+ kept for it (adoptProfile), and another account's copy is kept aside for that one (setUser).
+
+ A link opens this sheet by itself, and anyone can send one: a code for their own profile would
+ sign this browser in to it with a single tap and the passkey prompt, and whatever is logged
+ here afterwards would be theirs to read (login CSRF). So unless the code is for the profile
+ this browser is already signed in as — told apart by id, since names are not unique and the
+ sender chooses theirs — the sheet says which profile this device ends up in and to go on only
+ with a code from a device of one's own, and a guest's workouts go into that profile only when
+ the guest says so, even into one that has nothing yet (adoptProfile's alwaysAsk). */
export function DeviceLinkRedeemSheet({ close }) {
const user = useStore(s => s.user)
const pending = useStore(s => s.linkCode)
const [code, setCode] = useState(pending || '')
- const [info, setInfo] = useState(null) // { code, cid, options, name, at } from checking the code
+ const [info, setInfo] = useState(null) // { code, cid, options, id, name, at } from checking the code
const [busy, setBusy] = useState(false)
const [err, setErr] = useState(null)
const ref = useRef(null)
@@ -308,8 +316,9 @@ export function DeviceLinkRedeemSheet({ close }) {
if (same) { toast(t('Passkey added')); return }
// Signed in by now whatever happens next: a pull that fails is the sync banner's to say
// (adoptProfile records it), not a reason to hide that this device got in.
- await st.adoptProfile(askAddDeviceData).catch(() => {})
- toast(t('Welcome back, {0}', r.user.name))
+ await st.adoptProfile(askAddDeviceData, { alwaysAsk: true }).catch(() => {})
+ // Not "Welcome back": this may be the first time this person has seen that profile.
+ toast(t('Signed in as {0}', r.user.name))
} catch (e) {
if (!dismissed(e)) setErr(passkeyError(e))
// Answered by the server, the challenge is gone; the next try asks for a new one.
@@ -322,14 +331,19 @@ export function DeviceLinkRedeemSheet({ close }) {
<div style={{ height: 12 }} />
<Button onClick={close}>{t('Done')}</Button>
</>
- const joining = info && info.code === code.trim() ? info.name : null
+ const joining = info && info.code === code.trim() ? info : null
+ const elsewhere = joining && joining.id !== user?.id
return <>
<h3>{t('Add this device')}</h3>
<div className="muted small" style={{ marginBottom: 14 }}>{joining
- ? t('Create a passkey on this device for the profile “{0}”. It signs you in here from now on.', joining)
+ ? t('Create a passkey on this device for the profile “{0}”. It signs you in here from now on.', joining.name)
: t('Enter the code your other device shows under Settings → Add another device. This device then gets a passkey of its own.')}</div>
- {user && joining && user.name !== joining && <div className="card small muted" style={{ textAlign: 'start', marginBottom: 14 }}>
- {t('This browser is signed in as “{0}”. Adding it to “{1}” signs “{0}” out here.', user.name, joining)}</div>}
+ {elsewhere && <div className="card small" style={{ textAlign: 'start', marginBottom: 14 }}>
+ {user && <div style={{ marginBottom: 8 }}>{user.name === joining.name
+ ? t('This code is for a different profile that is also called “{0}”, not the one this browser is signed in as. Adding it there signs yours out here.', joining.name)
+ : t('This browser is signed in as “{0}”. Adding it to “{1}” signs “{0}” out here.', user.name, joining.name)}</div>}
+ <div>{t('Only continue if this code comes from a device of your own. This browser is then signed in to “{0}”, and what you log here goes to that profile.', joining.name)}</div>
+ </div>}
<form onSubmit={submit} noValidate>
<input ref={ref} className="input" name="device-code" autoComplete="one-time-code" placeholder={t('Code from your other device')} maxLength={20}
value={code} onChange={e => setCode(e.target.value.toUpperCase())} autoCapitalize="characters" autoCorrect="off" spellCheck={false}
diff --git a/frontend/src/components/Passkeys.test.jsx b/frontend/src/components/Passkeys.test.jsx
index cc8859799..5307c1e95 100644
--- a/frontend/src/components/Passkeys.test.jsx
+++ b/frontend/src/components/Passkeys.test.jsx
@@ -19,6 +19,7 @@ const mocks = vi.hoisted(() => {
state.createPasskey = vi.fn(async () => ({ id: 'new-key', response: {} }))
state.copyText = vi.fn(async () => true)
state.confirmSheet = vi.fn()
+ state.askAddDeviceData = vi.fn()
state.api = vi.fn(async (path, init) => {
const method = init?.method || 'GET'
state.calls.push({ path, method, body: init?.body ? JSON.parse(init.body) : null })
@@ -50,7 +51,7 @@ vi.mock('../lib/api.js', () => ({
passwordLogin: vi.fn(), passwordRegister: vi.fn(), passwordResetRedeem: vi.fn(),
}))
vi.mock('../lib/clipboard.js', () => ({ copyText: (...a) => mocks.copyText(...a) }))
-vi.mock('../sheets.jsx', () => ({ askAddDeviceData: vi.fn(), confirmSheet: (...a) => mocks.confirmSheet(...a) }))
+vi.mock('../sheets.jsx', () => ({ askAddDeviceData: mocks.askAddDeviceData, confirmSheet: (...a) => mocks.confirmSheet(...a) }))
// lean-qr loads on demand; what matters here is what the QR code carries.
vi.mock('./QrCanvas.jsx', () => ({ default: ({ value }) => <canvas data-qr={value} /> }))
@@ -95,7 +96,7 @@ beforeEach(() => {
mocks.answers = {}
mocks.calls.length = 0
mocks.store = { user: { id: 'u1', name: 'Ana' }, linkCode: null }
- for (const f of [mocks.toast, mocks.setUser, mocks.adoptProfile, mocks.passkeyAssertion, mocks.createPasskey, mocks.copyText, mocks.confirmSheet]) f.mockClear()
+ for (const f of [mocks.toast, mocks.setUser, mocks.adoptProfile, mocks.passkeyAssertion, mocks.createPasskey, mocks.copyText, mocks.confirmSheet, mocks.askAddDeviceData]) f.mockClear()
})
afterEach(() => { vi.useRealTimers(); act(() => { mounted.splice(0).forEach(({ root, host }) => { root.unmount(); host.remove() }) }) })
@@ -266,7 +267,8 @@ describe('Settings: a code for another device', () => {
})
describe('the other device: redeeming a code', () => {
- const OPTIONS = { cid: 'link-cid', options: { challenge: 'xyz' }, name: 'Ana' }
+ const OPTIONS = { cid: 'link-cid', options: { challenge: 'xyz' }, id: 'u1', name: 'Ana' }
+ const CAUTION = 'Only continue if this code comes from a device of your own. This browser is then signed in to “Ana”, and what you log here goes to that profile.'
it('checks a code from the link at once, then creates the passkey and signs in like a passkey sign-in', async () => {
mocks.store = { user: null, linkCode: 'K7WQ-2MZP-4HXA' }
@@ -277,6 +279,9 @@ describe('the other device: redeeming a code', () => {
await settle()
expect(mocks.calls[0]).toEqual({ path: '/api/device-link/options', method: 'POST', body: { code: 'K7WQ-2MZP-4HXA' } })
expect(host.textContent).toContain('for the profile “Ana”')
+ // A guest is told where this device ends up, and that the code has to be their own.
+ expect(host.textContent).toContain(CAUTION)
+ expect(host.textContent).not.toMatch(/signed in as/)
expect(byPlaceholder(host, 'Code from your other device').value).toBe('K7WQ-2MZP-4HXA')
await submit(host)
// The options already here are used as they are: the prompt opens straight from the tap.
@@ -285,10 +290,11 @@ describe('the other device: redeeming a code', () => {
expect(mocks.calls.at(-1).path).toBe('/api/device-link/verify')
expect(mocks.calls.at(-1).body).toMatchObject({ code: 'K7WQ-2MZP-4HXA', cid: 'link-cid', credential: { id: 'new-key' } })
expect(mocks.setUser).toHaveBeenCalledWith({ id: 'u1', name: 'Ana', admin: false })
- expect(mocks.adoptProfile).toHaveBeenCalled()
+ // What this device logged goes into that profile only when asked, even into an empty one.
+ expect(mocks.adoptProfile).toHaveBeenCalledWith(mocks.askAddDeviceData, { alwaysAsk: true })
expect(mocks.store.linkCode).toBeNull()
expect(close).toHaveBeenCalled()
- expect(mocks.toast).toHaveBeenCalledWith('Welcome back, Ana')
+ expect(mocks.toast).toHaveBeenCalledWith('Signed in as Ana')
})
it('a typed code is checked on the tap; a wrong one stays on the sheet and says so', async () => {
@@ -320,12 +326,14 @@ describe('the other device: redeeming a code', () => {
})
it('the same account adding this browser keeps its copy as it is', async () => {
- mocks.store = { user: { id: 'u1', name: 'Ana' }, linkCode: 'K7WQ-2MZP-4HXA' }
+ // Renamed since this browser signed in: the id is what makes it the same profile.
+ mocks.store = { user: { id: 'u1', name: 'Ana (old name)' }, linkCode: 'K7WQ-2MZP-4HXA' }
mocks.answers['POST /api/device-link/options'] = OPTIONS
mocks.answers['POST /api/device-link/verify'] = { user: { id: 'u1', name: 'Ana', admin: false } }
const host = mount(<DeviceLinkRedeemSheet close={() => {}} />)
await settle()
expect(host.textContent).not.toMatch(/signed in as/)
+ expect(host.textContent).not.toContain(CAUTION)
await submit(host)
expect(mocks.adoptProfile).not.toHaveBeenCalled()
expect(mocks.toast).toHaveBeenCalledWith('Passkey added')
@@ -337,6 +345,23 @@ describe('the other device: redeeming a code', () => {
const host = mount(<DeviceLinkRedeemSheet close={() => {}} />)
await settle()
expect(host.textContent).toContain('This browser is signed in as “Bea”. Adding it to “Ana” signs “Bea” out here.')
+ expect(host.textContent).toContain(CAUTION)
+ })
+
+ it('tells a different profile with the same name apart by its id', async () => {
+ // Someone else's profile, named like the one signed in here on purpose.
+ mocks.store = { user: { id: 'u2', name: 'Ana' }, linkCode: 'K7WQ-2MZP-4HXA' }
+ mocks.answers['POST /api/device-link/options'] = OPTIONS
+ mocks.answers['POST /api/device-link/verify'] = { user: { id: 'u1', name: 'Ana', admin: false } }
+ const host = mount(<DeviceLinkRedeemSheet close={() => {}} />)
+ await settle()
+ expect(host.textContent).toContain('This code is for a different profile that is also called “Ana”, not the one this browser is signed in as. Adding it there signs yours out here.')
+ expect(host.textContent).toContain(CAUTION)
+ await submit(host)
+ // Went on anyway: signed in to that profile, never greeted as if it were the one before.
+ expect(mocks.adoptProfile).toHaveBeenCalledWith(mocks.askAddDeviceData, { alwaysAsk: true })
+ expect(mocks.toast).toHaveBeenCalledWith('Signed in as Ana')
+ expect(mocks.toast).not.toHaveBeenCalledWith('Passkey added')
})
it('a browser without passkeys is told plainly, and nothing is asked of the server', async () => {
diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.js
index 27b4b0235..a90900fc5 100644
--- a/frontend/src/locales/ar.js
+++ b/frontend/src/locales/ar.js
@@ -1566,6 +1566,8 @@ export default {
'This browser cannot confirm with your passkey. Do this on a device that holds one.': 'لا يستطيع هذا المتصفح التأكيد بمفتاح المرور الخاص بك. افعل ذلك على جهاز يحفظ مفتاحًا.',
'This browser cannot create passkeys, so it cannot be added with a code. Open the link in a browser that can.': 'لا يستطيع هذا المتصفح إنشاء مفاتيح مرور، لذا لا يمكن إضافته برمز. افتح الرابط في متصفح يستطيع ذلك.',
'This browser is signed in as “{0}”. Adding it to “{1}” signs “{0}” out here.': 'هذا المتصفح مسجّل الدخول باسم «{0}». إضافته إلى «{1}» تُخرج «{0}» من هنا.',
+ 'This code is for a different profile that is also called “{0}”, not the one this browser is signed in as. Adding it there signs yours out here.': 'هذا الرمز لملف شخصي آخر اسمه أيضًا «{0}»، وليس للملف الذي سجّل هذا المتصفح الدخول به. إضافة المتصفح إلى هناك تُخرج ملفك الشخصي من هنا.',
+ 'Only continue if this code comes from a device of your own. This browser is then signed in to “{0}”, and what you log here goes to that profile.': 'تابع فقط إذا كان هذا الرمز من جهاز يخصّك. عندها يُسجَّل دخول هذا المتصفح إلى «{0}»، وكل ما تسجّله هنا يذهب إلى ذلك الملف الشخصي.',
'This code has expired.': 'انتهت صلاحية هذا الرمز.',
'This device already has a passkey for this profile.': 'لدى هذا الجهاز مفتاح مرور لهذا الملف الشخصي بالفعل.',
'This passkey already belongs to a profile.': 'مفتاح المرور هذا مرتبط بملف شخصي بالفعل.',
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index 77d7a3a19..d8400e894 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -386,6 +386,8 @@ export default {
'This browser cannot confirm with your passkey. Do this on a device that holds one.': 'Dieser Browser kann nicht mit deinem Passkey bestätigen. Mach das auf einem Gerät, auf dem einer gespeichert ist.',
'This browser cannot create passkeys, so it cannot be added with a code. Open the link in a browser that can.': 'Dieser Browser kann keine Passkeys erstellen und lässt sich deshalb nicht per Code hinzufügen. Öffne den Link in einem Browser, der das kann.',
'This browser is signed in as “{0}”. Adding it to “{1}” signs “{0}” out here.': 'Dieser Browser ist als „{0}“ angemeldet. Wenn du ihn zu „{1}“ hinzufügst, wird „{0}“ hier abgemeldet.',
+ 'This code is for a different profile that is also called “{0}”, not the one this browser is signed in as. Adding it there signs yours out here.': 'Dieser Code gehört zu einem anderen Profil, das ebenfalls „{0}“ heißt, nicht zu dem, mit dem dieser Browser angemeldet ist. Fügst du den Browser dort hinzu, wird dein Profil hier abgemeldet.',
+ 'Only continue if this code comes from a device of your own. This browser is then signed in to “{0}”, and what you log here goes to that profile.': 'Mach nur weiter, wenn dieser Code von einem deiner eigenen Geräte stammt. Dieser Browser wird dann bei „{0}“ angemeldet, und was du hier einträgst, landet in diesem Profil.',
'This code has expired.': 'Dieser Code ist abgelaufen.',
'This device already has a passkey for this profile.': 'Dieses Gerät hat schon einen Passkey für dieses Profil.',
'This passkey already belongs to a profile.': 'Dieser Passkey gehört schon zu einem Profil.',
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index 2d439f38c..9a19f1635 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -372,6 +372,8 @@ export default {
'This browser cannot confirm with your passkey. Do this on a device that holds one.': 'Este navegador no puede confirmar con tu passkey. Hazlo en un dispositivo que tenga una.',
'This browser cannot create passkeys, so it cannot be added with a code. Open the link in a browser that can.': 'Este navegador no puede crear passkeys, así que no se puede añadir con un código. Abre el enlace en un navegador que pueda.',
'This browser is signed in as “{0}”. Adding it to “{1}” signs “{0}” out here.': 'Este navegador tiene la sesión iniciada como «{0}». Añadirlo a «{1}» cierra aquí la sesión de «{0}».',
+ 'This code is for a different profile that is also called “{0}”, not the one this browser is signed in as. Adding it there signs yours out here.': 'Este código es de otro perfil que también se llama «{0}», no del perfil con el que este navegador tiene la sesión iniciada. Añadir allí el navegador cierra aquí la sesión de tu perfil.',
+ 'Only continue if this code comes from a device of your own. This browser is then signed in to “{0}”, and what you log here goes to that profile.': 'Continúa solo si este código viene de un dispositivo tuyo. Este navegador iniciará entonces sesión en «{0}», y lo que registres aquí irá a ese perfil.',
'This code has expired.': 'Este código ha caducado.',
'This device already has a passkey for this profile.': 'Este dispositivo ya tiene una passkey para este perfil.',
'This passkey already belongs to a profile.': 'Esta passkey ya pertenece a un perfil.',
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index 9ac14efee..db033a350 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -372,6 +372,8 @@ export default {
'This browser cannot confirm with your passkey. Do this on a device that holds one.': 'Ce navigateur ne peut pas confirmer avec ta passkey. Fais-le sur un appareil qui en garde une.',
'This browser cannot create passkeys, so it cannot be added with a code. Open the link in a browser that can.': 'Ce navigateur ne peut pas créer de passkeys, il ne peut donc pas être ajouté avec un code. Ouvre le lien dans un navigateur qui le peut.',
'This browser is signed in as “{0}”. Adding it to “{1}” signs “{0}” out here.': 'Ce navigateur est connecté en tant que « {0} ». L’ajouter à « {1} » déconnecte « {0} » ici.',
+ 'This code is for a different profile that is also called “{0}”, not the one this browser is signed in as. Adding it there signs yours out here.': 'Ce code appartient à un autre profil qui s’appelle aussi « {0} », pas à celui avec lequel ce navigateur est connecté. Y ajouter ce navigateur déconnecte ici ton profil.',
+ 'Only continue if this code comes from a device of your own. This browser is then signed in to “{0}”, and what you log here goes to that profile.': 'Ne continue que si ce code vient d’un de tes propres appareils. Ce navigateur sera alors connecté à « {0} », et ce que tu enregistres ici ira dans ce profil.',
'This code has expired.': 'Ce code a expiré.',
'This device already has a passkey for this profile.': 'Cet appareil a déjà une passkey pour ce profil.',
'This passkey already belongs to a profile.': 'Cette passkey appartient déjà à un profil.',
diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js
index 0127e1695..eef229078 100644
--- a/frontend/src/locales/hi.js
+++ b/frontend/src/locales/hi.js
@@ -372,6 +372,8 @@ export default {
'This browser cannot confirm with your passkey. Do this on a device that holds one.': 'यह ब्राउज़र आपकी पासकी से पुष्टि नहीं कर सकता। यह काम उस डिवाइस पर करें जिसमें पासकी रखी है।',
'This browser cannot create passkeys, so it cannot be added with a code. Open the link in a browser that can.': 'यह ब्राउज़र पासकी नहीं बना सकता, इसलिए इसे कोड से नहीं जोड़ा जा सकता। लिंक ऐसे ब्राउज़र में खोलें जो पासकी बना सके।',
'This browser is signed in as “{0}”. Adding it to “{1}” signs “{0}” out here.': 'यह ब्राउज़र "{0}" के रूप में साइन इन है। इसे "{1}" में जोड़ने से यहाँ "{0}" साइन आउट हो जाएगा।',
+ 'This code is for a different profile that is also called “{0}”, not the one this browser is signed in as. Adding it there signs yours out here.': 'यह कोड किसी दूसरी प्रोफ़ाइल का है जिसका नाम भी "{0}" है, उसका नहीं जिससे यह ब्राउज़र साइन इन है। ब्राउज़र को वहाँ जोड़ने से आपकी प्रोफ़ाइल यहाँ से साइन आउट हो जाएगी।',
+ 'Only continue if this code comes from a device of your own. This browser is then signed in to “{0}”, and what you log here goes to that profile.': 'आगे तभी बढ़ें जब यह कोड आपके अपने किसी डिवाइस से आया हो। फिर यह ब्राउज़र "{0}" में साइन इन हो जाएगा, और आप यहाँ जो भी दर्ज करेंगे वह उसी प्रोफ़ाइल में जाएगा।',
'This code has expired.': 'यह कोड समाप्त हो चुका है।',
'This device already has a passkey for this profile.': 'इस डिवाइस में इस प्रोफ़ाइल की पासकी पहले से है।',
'This passkey already belongs to a profile.': 'यह पासकी पहले से किसी प्रोफ़ाइल की है।',
diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js
index f3cf85e22..00c76e233 100644
--- a/frontend/src/locales/hu.js
+++ b/frontend/src/locales/hu.js
@@ -378,6 +378,8 @@ export default {
'This browser cannot confirm with your passkey. Do this on a device that holds one.': 'Ez a böngésző nem tud megerősíteni a jelszókulcsoddal. Tedd ezt egy olyan eszközön, amelyik tárol egyet.',
'This browser cannot create passkeys, so it cannot be added with a code. Open the link in a browser that can.': 'Ez a böngésző nem tud jelszókulcsot létrehozni, ezért kóddal sem adható hozzá. Nyisd meg a linket egy olyan böngészőben, amelyik képes rá.',
'This browser is signed in as “{0}”. Adding it to “{1}” signs “{0}” out here.': 'Ez a böngésző „{0}” néven van bejelentkezve. Ha hozzáadod a(z) „{1}” profilhoz, „{0}” itt kijelentkezik.',
+ 'This code is for a different profile that is also called “{0}”, not the one this browser is signed in as. Adding it there signs yours out here.': 'Ez a kód egy másik profilé, amelynek szintén „{0}” a neve, nem azé, amellyel ez a böngésző be van jelentkezve. Ha ott adod hozzá a böngészőt, a te profilod itt kijelentkezik.',
+ 'Only continue if this code comes from a device of your own. This browser is then signed in to “{0}”, and what you log here goes to that profile.': 'Csak akkor folytasd, ha ez a kód a saját eszközödről származik. Ez a böngésző ezután a(z) „{0}” profilba lesz bejelentkezve, és amit itt rögzítesz, az abba a profilba kerül.',
'This code has expired.': 'Ez a kód lejárt.',
'This device already has a passkey for this profile.': 'Ezen az eszközön már van jelszókulcs ehhez a profilhoz.',
'This passkey already belongs to a profile.': 'Ez a jelszókulcs már egy profilhoz tartozik.',
diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js
index b9ba37fcf..e278e6ffc 100644
--- a/frontend/src/locales/it.js
+++ b/frontend/src/locales/it.js
@@ -372,6 +372,8 @@ export default {
'This browser cannot confirm with your passkey. Do this on a device that holds one.': 'Questo browser non può confermare con la tua passkey. Fallo su un dispositivo che ne conserva una.',
'This browser cannot create passkeys, so it cannot be added with a code. Open the link in a browser that can.': 'Questo browser non può creare passkey, quindi non può essere aggiunto con un codice. Apri il link in un browser che ci riesce.',
'This browser is signed in as “{0}”. Adding it to “{1}” signs “{0}” out here.': 'Questo browser ha effettuato l’accesso come «{0}». Aggiungerlo a «{1}» fa uscire «{0}» da qui.',
+ 'This code is for a different profile that is also called “{0}”, not the one this browser is signed in as. Adding it there signs yours out here.': 'Questo codice è di un altro profilo che si chiama anch’esso «{0}», non di quello con cui questo browser ha effettuato l’accesso. Aggiungere lì il browser fa uscire da qui il tuo profilo.',
+ 'Only continue if this code comes from a device of your own. This browser is then signed in to “{0}”, and what you log here goes to that profile.': 'Continua solo se questo codice viene da un tuo dispositivo. Questo browser accederà poi a «{0}», e ciò che registri qui finirà in quel profilo.',
'This code has expired.': 'Questo codice è scaduto.',
'This device already has a passkey for this profile.': 'Questo dispositivo ha già una passkey per questo profilo.',
'This passkey already belongs to a profile.': 'Questa passkey appartiene già a un profilo.',
diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js
index 5fc726cd0..3be64f9f9 100644
--- a/frontend/src/locales/ko.js
+++ b/frontend/src/locales/ko.js
@@ -372,6 +372,8 @@ export default {
'This browser cannot confirm with your passkey. Do this on a device that holds one.': '이 브라우저에서는 패스키로 확인할 수 없습니다. 패스키가 있는 기기에서 진행하세요.',
'This browser cannot create passkeys, so it cannot be added with a code. Open the link in a browser that can.': '이 브라우저는 패스키를 만들 수 없어 코드로 추가할 수 없습니다. 패스키를 만들 수 있는 브라우저에서 링크를 여세요.',
'This browser is signed in as “{0}”. Adding it to “{1}” signs “{0}” out here.': '이 브라우저는 "{0}"(으)로 로그인되어 있습니다. "{1}"에 추가하면 여기서 "{0}"은(는) 로그아웃됩니다.',
+ 'This code is for a different profile that is also called “{0}”, not the one this browser is signed in as. Adding it there signs yours out here.': '이 코드는 이름이 똑같이 "{0}"인 다른 프로필의 것이며, 이 브라우저가 로그인한 프로필이 아닙니다. 브라우저를 그곳에 추가하면 지금 로그인된 프로필은 여기서 로그아웃됩니다.',
+ 'Only continue if this code comes from a device of your own. This browser is then signed in to “{0}”, and what you log here goes to that profile.': '이 코드가 본인 기기에서 받은 것일 때만 계속하세요. 그러면 이 브라우저는 "{0}"(으)로 로그인되고, 여기서 기록하는 내용은 그 프로필로 들어갑니다.',
'This code has expired.': '코드가 만료되었습니다.',
'This device already has a passkey for this profile.': '이 기기에는 이미 이 프로필의 패스키가 있습니다.',
'This passkey already belongs to a profile.': '이 패스키는 이미 프로필에 등록되어 있습니다.',
diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js
index 54e251e01..13425306f 100644
--- a/frontend/src/locales/pl.js
+++ b/frontend/src/locales/pl.js
@@ -372,6 +372,8 @@ export default {
'This browser cannot confirm with your passkey. Do this on a device that holds one.': 'Ta przeglądarka nie może potwierdzić twoim passkey. Zrób to na urządzeniu, na którym go masz.',
'This browser cannot create passkeys, so it cannot be added with a code. Open the link in a browser that can.': 'Ta przeglądarka nie potrafi tworzyć passkey, więc nie można jej dodać kodem. Otwórz link w przeglądarce, która to potrafi.',
'This browser is signed in as “{0}”. Adding it to “{1}” signs “{0}” out here.': 'Ta przeglądarka jest zalogowana jako „{0}”. Dodanie jej do „{1}” wyloguje tu „{0}”.',
+ 'This code is for a different profile that is also called “{0}”, not the one this browser is signed in as. Adding it there signs yours out here.': 'Ten kod należy do innego profilu, który też nazywa się „{0}”, a nie do tego, na który zalogowana jest ta przeglądarka. Dodanie jej tam wyloguje tu Twój profil.',
+ 'Only continue if this code comes from a device of your own. This browser is then signed in to “{0}”, and what you log here goes to that profile.': 'Kontynuuj tylko wtedy, gdy ten kod pochodzi z Twojego własnego urządzenia. Ta przeglądarka zostanie wtedy zalogowana do „{0}”, a to, co tu zapiszesz, trafi do tego profilu.',
'This code has expired.': 'Ten kod wygasł.',
'This device already has a passkey for this profile.': 'To urządzenie ma już passkey dla tego profilu.',
'This passkey already belongs to a profile.': 'Ten passkey należy już do jakiegoś profilu.',
diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js
index 0bbaf3fd6..71cbe45d5 100644
--- a/frontend/src/locales/pt-BR.js
+++ b/frontend/src/locales/pt-BR.js
@@ -378,6 +378,8 @@ export const PT_BR_OVERRIDES = {
'This browser cannot confirm with your passkey. Do this on a device that holds one.': 'Este navegador não consegue confirmar com sua chave de acesso. Faça isso em um dispositivo que tenha uma.',
'This browser cannot create passkeys, so it cannot be added with a code. Open the link in a browser that can.': 'Este navegador não consegue criar chaves de acesso, por isso não pode ser adicionado com um código. Abra o link em um navegador que consiga.',
'This browser is signed in as “{0}”. Adding it to “{1}” signs “{0}” out here.': 'Este navegador está conectado como “{0}”. Adicioná-lo a “{1}” desconecta “{0}” aqui.',
+ 'This code is for a different profile that is also called “{0}”, not the one this browser is signed in as. Adding it there signs yours out here.': 'Este código é de outro perfil que também se chama “{0}”, não daquele com que este navegador está conectado. Adicionar o navegador lá desconecta o seu perfil aqui.',
+ 'Only continue if this code comes from a device of your own. This browser is then signed in to “{0}”, and what you log here goes to that profile.': 'Continue só se este código vier de um dispositivo seu. Este navegador fica então conectado a “{0}”, e o que você registrar aqui vai para esse perfil.',
'This code has expired.': 'Este código expirou.',
'This device already has a passkey for this profile.': 'Este dispositivo já tem uma chave de acesso para este perfil.',
'This passkey already belongs to a profile.': 'Esta chave de acesso já pertence a um perfil.',
diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js
index 423892b60..6e3432c2a 100644
--- a/frontend/src/locales/pt.js
+++ b/frontend/src/locales/pt.js
@@ -372,6 +372,8 @@ export default {
'This browser cannot confirm with your passkey. Do this on a device that holds one.': 'Este navegador não consegue confirmar com a tua passkey. Faz isto num dispositivo que tenha uma.',
'This browser cannot create passkeys, so it cannot be added with a code. Open the link in a browser that can.': 'Este navegador não consegue criar passkeys, por isso não pode ser adicionado com um código. Abre a ligação num navegador que consiga.',
'This browser is signed in as “{0}”. Adding it to “{1}” signs “{0}” out here.': 'Este navegador tem sessão iniciada como «{0}». Adicioná-lo a «{1}» termina aqui a sessão de «{0}».',
+ 'This code is for a different profile that is also called “{0}”, not the one this browser is signed in as. Adding it there signs yours out here.': 'Este código é de outro perfil que também se chama «{0}», não daquele com que este navegador tem sessão iniciada. Adicionar aí o navegador termina aqui a sessão do teu perfil.',
+ 'Only continue if this code comes from a device of your own. This browser is then signed in to “{0}”, and what you log here goes to that profile.': 'Continua só se este código vier de um dispositivo teu. Este navegador fica então com sessão iniciada em «{0}», e o que registares aqui vai para esse perfil.',
'This code has expired.': 'Este código expirou.',
'This device already has a passkey for this profile.': 'Este dispositivo já tem uma passkey para este perfil.',
'This passkey already belongs to a profile.': 'Esta passkey já pertence a um perfil.',
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index d7761112b..223aa0811 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -372,6 +372,8 @@ export default {
'This browser cannot confirm with your passkey. Do this on a device that holds one.': 'Этот браузер не может подтвердить твоим ключом доступа. Сделай это на устройстве, где он хранится.',
'This browser cannot create passkeys, so it cannot be added with a code. Open the link in a browser that can.': 'Этот браузер не умеет создавать ключи доступа, поэтому его нельзя добавить по коду. Открой ссылку в браузере, который это умеет.',
'This browser is signed in as “{0}”. Adding it to “{1}” signs “{0}” out here.': 'В этом браузере выполнен вход как «{0}». Если добавить его к «{1}», «{0}» здесь выйдет из аккаунта.',
+ 'This code is for a different profile that is also called “{0}”, not the one this browser is signed in as. Adding it there signs yours out here.': 'Этот код от другого профиля, который тоже называется «{0}», а не от того, под которым выполнен вход в этом браузере. Если добавить браузер туда, твой профиль здесь выйдет из системы.',
+ 'Only continue if this code comes from a device of your own. This browser is then signed in to “{0}”, and what you log here goes to that profile.': 'Продолжай, только если этот код пришёл с твоего собственного устройства. Тогда в этом браузере будет выполнен вход в «{0}», и всё, что ты здесь запишешь, попадёт в этот профиль.',
'This code has expired.': 'Срок действия кода истёк.',
'This device already has a passkey for this profile.': 'На этом устройстве уже есть ключ доступа для этого профиля.',
'This passkey already belongs to a profile.': 'Этот ключ доступа уже принадлежит профилю.',
diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js
index 3551980d5..679a77b3b 100644
--- a/frontend/src/locales/th.js
+++ b/frontend/src/locales/th.js
@@ -378,6 +378,8 @@ export default {
'This browser cannot confirm with your passkey. Do this on a device that holds one.': 'เบราว์เซอร์นี้ยืนยันด้วยพาสคีย์ของคุณไม่ได้ ทำขั้นตอนนี้บนอุปกรณ์ที่เก็บพาสคีย์ไว้',
'This browser cannot create passkeys, so it cannot be added with a code. Open the link in a browser that can.': 'เบราว์เซอร์นี้สร้างพาสคีย์ไม่ได้ จึงเพิ่มด้วยรหัสไม่ได้ เปิดลิงก์ในเบราว์เซอร์ที่สร้างพาสคีย์ได้',
'This browser is signed in as “{0}”. Adding it to “{1}” signs “{0}” out here.': 'เบราว์เซอร์นี้เข้าสู่ระบบในชื่อ “{0}” อยู่ การเพิ่มเบราว์เซอร์นี้ให้ “{1}” จะทำให้ “{0}” ออกจากระบบที่นี่',
+ 'This code is for a different profile that is also called “{0}”, not the one this browser is signed in as. Adding it there signs yours out here.': 'รหัสนี้เป็นของโปรไฟล์อื่นที่ชื่อ “{0}” เหมือนกัน ไม่ใช่โปรไฟล์ที่เบราว์เซอร์นี้เข้าสู่ระบบอยู่ การเพิ่มเบราว์เซอร์ไปที่นั่นจะทำให้โปรไฟล์ของคุณออกจากระบบที่นี่',
+ 'Only continue if this code comes from a device of your own. This browser is then signed in to “{0}”, and what you log here goes to that profile.': 'ดำเนินการต่อเฉพาะเมื่อรหัสนี้มาจากอุปกรณ์ของคุณเองเท่านั้น จากนั้นเบราว์เซอร์นี้จะเข้าสู่ระบบในชื่อ “{0}” และสิ่งที่คุณบันทึกที่นี่จะเข้าไปอยู่ในโปรไฟล์นั้น',
'This code has expired.': 'รหัสนี้หมดอายุแล้ว',
'This device already has a passkey for this profile.': 'อุปกรณ์นี้มีพาสคีย์สำหรับโปรไฟล์นี้อยู่แล้ว',
'This passkey already belongs to a profile.': 'พาสคีย์นี้เป็นของโปรไฟล์หนึ่งอยู่แล้ว',
diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js
index 1a9584d5c..fb50830a8 100644
--- a/frontend/src/locales/tr.js
+++ b/frontend/src/locales/tr.js
@@ -372,6 +372,8 @@ export default {
'This browser cannot confirm with your passkey. Do this on a device that holds one.': 'Bu tarayıcı geçiş anahtarınla onaylayamaz. Bunu, anahtarın kayıtlı olduğu bir cihazda yap.',
'This browser cannot create passkeys, so it cannot be added with a code. Open the link in a browser that can.': 'Bu tarayıcı geçiş anahtarı oluşturamadığı için kodla eklenemez. Bağlantıyı bunu yapabilen bir tarayıcıda aç.',
'This browser is signed in as “{0}”. Adding it to “{1}” signs “{0}” out here.': 'Bu tarayıcıda “{0}” olarak oturum açık. Onu “{1}” profiline eklemek burada “{0}” oturumunu kapatır.',
+ 'This code is for a different profile that is also called “{0}”, not the one this browser is signed in as. Adding it there signs yours out here.': 'Bu kod, yine “{0}” adını taşıyan başka bir profile ait; bu tarayıcıda oturumu açık olan profile değil. Tarayıcıyı oraya eklemek buradaki kendi profilinin oturumunu kapatır.',
+ 'Only continue if this code comes from a device of your own. This browser is then signed in to “{0}”, and what you log here goes to that profile.': 'Yalnızca bu kod kendi cihazlarından birinden geliyorsa devam et. O zaman bu tarayıcıda “{0}” olarak oturum açılır ve burada kaydettiklerin o profile gider.',
'This code has expired.': 'Bu kodun süresi doldu.',
'This device already has a passkey for this profile.': 'Bu cihazda bu profil için zaten bir geçiş anahtarı var.',
'This passkey already belongs to a profile.': 'Bu geçiş anahtarı zaten bir profile ait.',
diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.js
index 0cdce0137..66e788513 100644
--- a/frontend/src/locales/uk.js
+++ b/frontend/src/locales/uk.js
@@ -1510,6 +1510,8 @@ export default {
'This browser cannot confirm with your passkey. Do this on a device that holds one.': 'Цей браузер не може підтвердити твоїм ключем доступу. Зроби це на пристрої, де він зберігається.',
'This browser cannot create passkeys, so it cannot be added with a code. Open the link in a browser that can.': 'Цей браузер не вміє створювати ключі доступу, тож його не можна додати за кодом. Відкрий посилання в браузері, який це вміє.',
'This browser is signed in as “{0}”. Adding it to “{1}” signs “{0}” out here.': 'У цьому браузері виконано вхід як «{0}». Якщо додати його до «{1}», «{0}» тут вийде з акаунта.',
+ 'This code is for a different profile that is also called “{0}”, not the one this browser is signed in as. Adding it there signs yours out here.': 'Цей код належить іншому профілю, який теж називається «{0}», а не тому, під яким виконано вхід у цьому браузері. Якщо додати браузер туди, твій профіль тут вийде з системи.',
+ 'Only continue if this code comes from a device of your own. This browser is then signed in to “{0}”, and what you log here goes to that profile.': 'Продовжуй, лише якщо цей код надійшов з твого власного пристрою. Тоді в цьому браузері буде виконано вхід у «{0}», і все, що ти тут запишеш, потрапить до цього профілю.',
'This code has expired.': 'Термін дії коду минув.',
'This device already has a passkey for this profile.': 'На цьому пристрої вже є ключ доступу для цього профілю.',
'This passkey already belongs to a profile.': 'Цей ключ доступу вже належить профілю.',
diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js
index 088b7ed6b..b6701b94b 100644
--- a/frontend/src/locales/zh.js
+++ b/frontend/src/locales/zh.js
@@ -372,6 +372,8 @@ export default {
'This browser cannot confirm with your passkey. Do this on a device that holds one.': '此浏览器无法用你的通行密钥确认。请在保存了通行密钥的设备上操作。',
'This browser cannot create passkeys, so it cannot be added with a code. Open the link in a browser that can.': '此浏览器无法创建通行密钥,因此不能通过代码添加。请在能创建通行密钥的浏览器中打开此链接。',
'This browser is signed in as “{0}”. Adding it to “{1}” signs “{0}” out here.': '此浏览器已以“{0}”登录。将它添加到“{1}”会让“{0}”在这里退出登录。',
+ 'This code is for a different profile that is also called “{0}”, not the one this browser is signed in as. Adding it there signs yours out here.': '这个代码属于另一个同样名为“{0}”的档案,而不是此浏览器当前登录的那个。将浏览器添加到那里,会让你的档案在这里退出登录。',
+ 'Only continue if this code comes from a device of your own. This browser is then signed in to “{0}”, and what you log here goes to that profile.': '只有当这个代码来自你自己的设备时才继续。之后此浏览器将登录到“{0}”,你在这里记录的内容都会进入该档案。',
'This code has expired.': '此代码已过期。',
'This device already has a passkey for this profile.': '此设备已有该档案的通行密钥。',
'This passkey already belongs to a profile.': '此通行密钥已属于某个档案。',
diff --git a/frontend/src/store/useStore.adopt.test.jsx b/frontend/src/store/useStore.adopt.test.jsx
index 4fd9730b0..7efa015c3 100644
--- a/frontend/src/store/useStore.adopt.test.jsx
+++ b/frontend/src/store/useStore.adopt.test.jsx
@@ -82,6 +82,47 @@ describe('adoptProfile — sign-in takes the server profile', () => {
expect(puts()[0].state.workouts.map(w => w.id)).toEqual(['w9'])
expect(useStore.getState().S.unit).toBe('kg')
})
+
+ // A profile joined with a code from somewhere else (#95): whoever sent the code chose it, so a
+ // guest's workouts are not moved into it unasked, even when it has nothing yet.
+ it('alwaysAsk: asks before moving the device data into an empty profile, and moves nothing when declined', async () => {
+ signedIn(clone(guest))
+ api.mockResolvedValueOnce({ state: null, rev: 0 })
+ const ask = vi.fn(async () => false)
+ const r = await useStore.getState().adoptProfile(ask, { alwaysAsk: true })
+ expect(ask).toHaveBeenCalledWith({ workouts: 1, bodyweight: 0, customEx: 0 })
+ expect(puts()).toHaveLength(0)
+ const S = useStore.getState().S
+ expect(S.workouts).toEqual([])
+ expect(S.routines).toEqual([])
+ expect(S.active).toEqual({ id: 'running' }) // the in-progress session stays with the device
+ expect(sync().rev).toBe(0)
+ expect(r).toEqual({ adopted: true, added: false })
+ })
+
+ it('alwaysAsk: moves the device data into an empty profile once the user says so', async () => {
+ signedIn(clone(guest))
+ api.mockResolvedValueOnce({ state: null, rev: 0 })
+ api.mockResolvedValueOnce({ ok: true, rev: 1 })
+ const ask = vi.fn(async () => true)
+ await useStore.getState().adoptProfile(ask, { alwaysAsk: true })
+ expect(ask).toHaveBeenCalledTimes(1)
+ expect(puts()).toHaveLength(1)
+ expect(puts()[0].state.workouts.map(w => w.id)).toEqual(['w9'])
+ })
+
+ it('alwaysAsk: the account this copy already belongs to is not asked about its own data', async () => {
+ useStore.setState({ S: clone(guest), ready: true, sync: { offline: false, pending: false, lastSynced: 0 } })
+ localStorage.setItem('gym_owner', 'user-1')
+ useStore.getState().setUser({ id: 'user-1', name: 'Ana' })
+ api.mockResolvedValueOnce({ state: null, rev: 0 })
+ api.mockResolvedValueOnce({ ok: true, rev: 1 })
+ const ask = vi.fn(async () => false)
+ await useStore.getState().adoptProfile(ask, { alwaysAsk: true })
+ expect(ask).not.toHaveBeenCalled()
+ expect(puts()).toHaveLength(1)
+ expect(puts()[0].state.workouts.map(w => w.id)).toEqual(['w9'])
+ })
})
describe('offline and unsynced flags', () => {
diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js
index 292e67dbc..53934993e 100644
--- a/frontend/src/store/useStore.js
+++ b/frontend/src/store/useStore.js
@@ -893,7 +893,13 @@ export const useStore = create((set, get) => {
// are added to the profile or dropped. A profile with no state yet simply takes the
// device's data, as creating a profile always did. The same account signing in again is
// different: see below.
- async adoptProfile(ask) {
+ //
+ // `alwaysAsk` is for a profile this device joins with a code from another device (#95,
+ // DeviceLinkRedeemSheet). Nothing proves that profile is this person's own — whoever sends
+ // the code chooses it — so what a guest logged here is not moved into it unasked, not even
+ // into one with no state yet, where it would otherwise go without a word. Declined, this
+ // device takes that empty profile as it is, the way it takes a profile that has state.
+ async adoptProfile(ask, { alwaysAsk = false } = {}) {
if (pulling) await pulling
const sameAccount = rejoined
let res
@@ -902,14 +908,24 @@ export const useStore = create((set, get) => {
const { state, rev } = res
const S = get().S
reached()
+ const askAbout = async extras =>
+ (extras.workouts || extras.bodyweight || extras.customEx) && typeof ask === 'function' ? await ask(extras) : false
+ const serverCopy = Object.assign(clone(DEF), state, { active: S.active || null })
if (!state) {
+ const push = hasData(S) && (!alwaysAsk || sameAccount || await askAbout(localExtras(S, null)))
+ if (hasData(S) && !push) {
+ if (rev != null) adopt(serverCopy, rev)
+ else { dropSync(); persist(serverCopy, false, false); markOwed(false) }
+ confirmed(get().S)
+ await applyStash()
+ return { adopted: true, added: false }
+ }
markOwed(false)
- if (hasData(S)) { if (rev != null) writeSync(rev, 0); forceNext = true; await get().pushState() }
+ if (push) { if (rev != null) writeSync(rev, 0); forceNext = true; await get().pushState() }
else { if (rev != null) writeSync(rev, 0); confirmed(get().S) }
await applyStash()
return { adopted: false, added: false }
}
- const serverCopy = Object.assign(clone(DEF), state, { active: S.active || null })
if (sameAccount) {
// This copy already belongs to the account: a phone paired again after its token was
// refused, a browser signed in again after its session ended. It may hold days the server
@@ -931,8 +947,7 @@ export const useStore = create((set, get) => {
await applyStash()
return { adopted: true, added: false, merged: true }
}
- const extras = localExtras(S, state)
- const keep = (extras.workouts || extras.bodyweight || extras.customEx) && typeof ask === 'function' ? await ask(extras) : false
+ const keep = await askAbout(localExtras(S, state))
if (keep) {
const merged = Object.assign(clone(DEF), mergeStates(state, S, { prefer: 'a' }))
merged.active = S.active || null