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.

Add extra passkeys and a one-time device-link

Alexander Kiselev98645547d525
diff --git a/api/device-link.js b/api/device-link.js
new file mode 100644
index 000000000..a2fe73bcc
--- /dev/null
+++ b/api/device-link.js
@@ -0,0 +1,34 @@
+import crypto from 'node:crypto';
+
+export const DEVICE_LINK_TTL_MS = 15 * 60 * 1000;
+
+function prune(db, now, keepUserId) {
+ db.deviceLinks = (db.deviceLinks || []).filter(l => l.exp > now && l.userId !== keepUserId);
+}
+
+export function createDeviceLink(db, userId, now = Date.now(), ttlMs = DEVICE_LINK_TTL_MS) {
+ prune(db, now, userId);
+ const link = {
+ token: crypto.randomBytes(18).toString('base64url'),
+ userId,
+ exp: now + ttlMs,
+ created: now
+ };
+ db.deviceLinks.push(link);
+ return link;
+}
+
+export function claimDeviceLink(db, token, now = Date.now()) {
+ db.deviceLinks = db.deviceLinks || [];
+ const i = db.deviceLinks.findIndex(l => l.token === token);
+ if (i < 0) return { error: 'unknown or already used' };
+ const link = db.deviceLinks[i];
+ db.deviceLinks.splice(i, 1);
+ if (link.exp < now) return { error: 'link expired' };
+ return { userId: link.userId };
+}
+
+export function deviceLinkUrl(origin, token) {
+ const base = String(origin || '').replace(/\/+$/, '');
+ return base + '/?link=' + encodeURIComponent(token);
+}
diff --git a/api/passkeys-store.js b/api/passkeys-store.js
new file mode 100644
index 000000000..a2f346347
--- /dev/null
+++ b/api/passkeys-store.js
@@ -0,0 +1,33 @@
+export function listPasskeys(db, userId) {
+ return (db.creds || [])
+ .filter(c => c.userId === userId)
+ .map(c => ({
+ id: c.id,
+ created: c.created || null,
+ transports: c.transports || []
+ }));
+}
+
+export function addPasskeyRecord(db, userId, cred) {
+ db.creds = db.creds || [];
+ if (db.creds.some(c => c.id === cred.id)) return { error: 'credential already registered' };
+ db.creds.push({
+ id: cred.id,
+ userId,
+ publicKey: cred.publicKey,
+ counter: cred.counter || 0,
+ transports: cred.transports || [],
+ created: cred.created || new Date().toISOString()
+ });
+ return { ok: true };
+}
+
+export function removePasskeyRecord(db, userId, credId) {
+ db.creds = db.creds || [];
+ const i = db.creds.findIndex(c => c.id === credId && c.userId === userId);
+ if (i < 0) return { error: 'passkey not found' };
+ const mine = db.creds.filter(c => c.userId === userId);
+ if (mine.length <= 1) return { error: 'keep at least one passkey' };
+ db.creds.splice(i, 1);
+ return { ok: true };
+}
diff --git a/api/test/device-link.test.js b/api/test/device-link.test.js
new file mode 100644
index 000000000..68697f663
--- /dev/null
+++ b/api/test/device-link.test.js
@@ -0,0 +1,75 @@
+import { describe, it } from 'node:test';
+import assert from 'node:assert/strict';
+import { createDeviceLink, claimDeviceLink, deviceLinkUrl } from '../device-link.js';
+
+describe('createDeviceLink', () => {
+ it('issues a one-time token bound to the user, with an expiry', () => {
+ const db = { deviceLinks: [] };
+ const now = 1_700_000_000_000;
+ const link = createDeviceLink(db, 'user-a', now, 15 * 60 * 1000);
+ assert.equal(link.userId, 'user-a');
+ assert.equal(link.exp, now + 15 * 60 * 1000);
+ assert.equal(typeof link.token, 'string');
+ assert.ok(link.token.length >= 20);
+ assert.equal(db.deviceLinks.length, 1);
+ assert.equal(db.deviceLinks[0].token, link.token);
+ });
+
+ it('replaces any unused link for the same user', () => {
+ const db = { deviceLinks: [] };
+ const first = createDeviceLink(db, 'user-a', 1000, 60_000);
+ const second = createDeviceLink(db, 'user-a', 2000, 60_000);
+ assert.equal(db.deviceLinks.length, 1);
+ assert.equal(db.deviceLinks[0].token, second.token);
+ assert.notEqual(first.token, second.token);
+ });
+
+ it('leaves another user’s unused link alone', () => {
+ const db = { deviceLinks: [] };
+ createDeviceLink(db, 'user-a', 1000, 60_000);
+ createDeviceLink(db, 'user-b', 1000, 60_000);
+ assert.equal(db.deviceLinks.length, 2);
+ });
+});
+
+describe('claimDeviceLink', () => {
+ it('returns the user and burns the token', () => {
+ const db = { deviceLinks: [] };
+ const link = createDeviceLink(db, 'user-a', 1000, 60_000);
+ const claimed = claimDeviceLink(db, link.token, 2000);
+ assert.deepEqual(claimed, { userId: 'user-a' });
+ assert.equal(db.deviceLinks.length, 0);
+ assert.deepEqual(claimDeviceLink(db, link.token, 3000), { error: 'unknown or already used' });
+ });
+
+ it('refuses an expired link and removes it', () => {
+ const db = { deviceLinks: [] };
+ const link = createDeviceLink(db, 'user-a', 1000, 60_000);
+ const claimed = claimDeviceLink(db, link.token, 1000 + 60_000 + 1);
+ assert.deepEqual(claimed, { error: 'link expired' });
+ assert.equal(db.deviceLinks.length, 0);
+ });
+
+ it('refuses a missing token without touching other links', () => {
+ const db = { deviceLinks: [] };
+ createDeviceLink(db, 'user-a', 1000, 60_000);
+ assert.deepEqual(claimDeviceLink(db, 'nope', 1000), { error: 'unknown or already used' });
+ assert.equal(db.deviceLinks.length, 1);
+ });
+});
+
+describe('deviceLinkUrl', () => {
+ it('puts the token on the origin as ?link=', () => {
+ assert.equal(
+ deviceLinkUrl('https://gym.avott.duckdns.org', 'abc+1'),
+ 'https://gym.avott.duckdns.org/?link=abc%2B1'
+ );
+ });
+
+ it('does not double the slash when the origin already has one', () => {
+ assert.equal(
+ deviceLinkUrl('https://gym.example.com/', 'tok'),
+ 'https://gym.example.com/?link=tok'
+ );
+ });
+});
diff --git a/api/test/passkeys-store.test.js b/api/test/passkeys-store.test.js
new file mode 100644
index 000000000..c07190428
--- /dev/null
+++ b/api/test/passkeys-store.test.js
@@ -0,0 +1,58 @@
+import { describe, it } from 'node:test';
+import assert from 'node:assert/strict';
+import { addPasskeyRecord, listPasskeys, removePasskeyRecord } from '../passkeys-store.js';
+
+const cred = (id, userId = 'u1') => ({
+ id, userId, publicKey: 'pk-' + id, counter: 0, transports: ['internal']
+});
+
+describe('addPasskeyRecord', () => {
+ it('attaches a credential to the existing user', () => {
+ const db = { creds: [cred('hello', 'u1')] };
+ const r = addPasskeyRecord(db, 'u1', cred('phone', 'u1'));
+ assert.deepEqual(r, { ok: true });
+ assert.equal(db.creds.length, 2);
+ assert.equal(db.creds[1].id, 'phone');
+ assert.equal(db.creds[1].userId, 'u1');
+ assert.ok(db.creds[1].created);
+ });
+
+ it('refuses a credential id that already exists', () => {
+ const db = { creds: [cred('hello', 'u1')] };
+ const r = addPasskeyRecord(db, 'u2', cred('hello', 'u2'));
+ assert.deepEqual(r, { error: 'credential already registered' });
+ assert.equal(db.creds.length, 1);
+ });
+});
+
+describe('listPasskeys', () => {
+ it('returns only this user’s credentials, without the public key', () => {
+ const db = { creds: [cred('a', 'u1'), cred('b', 'u2'), cred('c', 'u1')] };
+ const list = listPasskeys(db, 'u1');
+ assert.deepEqual(list.map(c => c.id), ['a', 'c']);
+ for (const c of list) assert.equal(c.publicKey, undefined);
+ });
+});
+
+describe('removePasskeyRecord', () => {
+ it('removes one of several passkeys', () => {
+ const db = { creds: [cred('hello', 'u1'), cred('phone', 'u1')] };
+ const r = removePasskeyRecord(db, 'u1', 'hello');
+ assert.deepEqual(r, { ok: true });
+ assert.deepEqual(db.creds.map(c => c.id), ['phone']);
+ });
+
+ it('refuses to remove the last passkey', () => {
+ const db = { creds: [cred('hello', 'u1')] };
+ const r = removePasskeyRecord(db, 'u1', 'hello');
+ assert.deepEqual(r, { error: 'keep at least one passkey' });
+ assert.equal(db.creds.length, 1);
+ });
+
+ it('does not let one user delete another’s passkey', () => {
+ const db = { creds: [cred('hello', 'u1'), cred('other', 'u2')] };
+ const r = removePasskeyRecord(db, 'u2', 'hello');
+ assert.deepEqual(r, { error: 'passkey not found' });
+ assert.equal(db.creds.length, 2);
+ });
+});
diff --git a/frontend/src/lib/device-link.js b/frontend/src/lib/device-link.js
new file mode 100644
index 000000000..eaff8528d
--- /dev/null
+++ b/frontend/src/lib/device-link.js
@@ -0,0 +1,15 @@
+// Device-link URL is origin + ?link=TOKEN. HashRouter never sees that query, so we read
+// window.location.search directly rather than the router.
+
+export function linkTokenFromSearch(search) {
+ return new URLSearchParams(search.startsWith('?') ? search.slice(1) : search).get('link') || ''
+}
+
+export function stripLinkFromUrl() {
+ if (typeof window === 'undefined') return
+ const u = new URL(window.location.href)
+ if (!u.searchParams.has('link')) return
+ u.searchParams.delete('link')
+ const q = u.searchParams.toString()
+ history.replaceState({}, '', u.pathname + (q ? '?' + q : '') + u.hash)
+}
diff --git a/frontend/src/lib/device-link.test.js b/frontend/src/lib/device-link.test.js
new file mode 100644
index 000000000..7b706e6da
--- /dev/null
+++ b/frontend/src/lib/device-link.test.js
@@ -0,0 +1,17 @@
+import { describe, expect, it } from 'vitest'
+import { linkTokenFromSearch } from './device-link.js'
+
+describe('linkTokenFromSearch', () => {
+ it('reads ?link= from the query string', () => {
+ expect(linkTokenFromSearch('?link=abc123')).toBe('abc123')
+ })
+
+ it('returns empty when there is no link', () => {
+ expect(linkTokenFromSearch('')).toBe('')
+ expect(linkTokenFromSearch('?foo=1')).toBe('')
+ })
+
+ it('decodes a percent-encoded token', () => {
+ expect(linkTokenFromSearch('?link=abc%2B1')).toBe('abc+1')
+ })
+})