Skip to content

Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.

fix(v0.9.1): honest claim counts, legacy bulk-adopt opt-in, auth-state refresh

Ashiq Hussain Mire996670ef3f3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index deaadd7..4a1d99c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -26,8 +26,14 @@ called for exists as executable tests.
`403 NOT_ELIGIBLE`; races between two claimants are resolved atomically
by a conditional `updateMany` (`409` on loss).
- **Dashboard** shows the honest claimable count ("Save my designs to
- this account (N)") and a per-design "Save to my account" action; the
- list API exposes a boolean `claimable` per design (never the hash).
+ this account (N)" counts only browser-attributed designs), a per-design
+ "Save to my account" action, and — for self-hosters — a separate,
+ confirmation-guarded "Adopt legacy (pre-accounts) designs" bulk item
+ (`adopt-all { includeLegacy: true }`; foreign attributions remain
+ excluded even then). The list API exposes boolean `claimable` and
+ `mine` flags per design (never the hash). Dialog-driven sign-in/up now
+ refreshes the dashboard's auth state immediately (the account chip no
+ longer waits for a reload).
### CSRF protection for cookie-authenticated writes
- Every mutating API route (`POST /api/designs`, `PUT`/`DELETE` on a
diff --git a/src/app/api/designs/adopt-all/adopt-all.test.ts b/src/app/api/designs/adopt-all/adopt-all.test.ts
index 4031ac9..6e157e7 100644
--- a/src/app/api/designs/adopt-all/adopt-all.test.ts
+++ b/src/app/api/designs/adopt-all/adopt-all.test.ts
@@ -22,11 +22,15 @@ import { ANON_COOKIE, anonKeyHash } from '@/lib/auth/anon'
const USER = { id: 'user-1', username: 'ashiq', createdAt: new Date() }
-function post(opts: { cookie?: string; origin?: string } = {}) {
+function post(opts: { cookie?: string; origin?: string; body?: unknown } = {}) {
const headers: Record<string, string> = { host: 'canvix.test' }
if (opts.cookie) headers.cookie = opts.cookie
if (opts.origin) headers.origin = opts.origin
- const req = new NextRequest('http://canvix.test/api/designs/adopt-all', { method: 'POST', headers })
+ const req = new NextRequest('http://canvix.test/api/designs/adopt-all', {
+ method: 'POST',
+ headers,
+ ...(opts.body !== undefined ? { body: JSON.stringify(opts.body) } : {}),
+ })
return POST(req)
}
@@ -67,7 +71,37 @@ describe('POST /api/designs/adopt-all', () => {
// Foreign anonymous designs (other hashes) and legacy rows (null)
// are outside this UPDATE by construction.
expect(dbMock.design.updateMany).toHaveBeenCalledWith({
- where: { ownerId: null, anonKey: anonKeyHash(token) },
+ where: { ownerId: null, OR: [{ anonKey: anonKeyHash(token) }] },
+ data: { ownerId: USER.id },
+ })
+ })
+
+ it('includeLegacy opt-in adds ONLY legacy rows — foreign attributions still excluded', async () => {
+ const token = 'browser-a-token'
+ dbMock.design.updateMany.mockResolvedValue({ count: 10 })
+ const res = await post({ cookie: `${ANON_COOKIE}=${token}`, body: { includeLegacy: true } })
+ expect(res.status).toBe(200)
+ expect(dbMock.design.updateMany).toHaveBeenCalledWith({
+ where: { ownerId: null, OR: [{ anonKey: anonKeyHash(token) }, { anonKey: null }] },
+ data: { ownerId: USER.id },
+ })
+ })
+
+ it('includeLegacy with NO attribution cookie claims only legacy rows', async () => {
+ dbMock.design.updateMany.mockResolvedValue({ count: 7 })
+ const res = await post({ body: { includeLegacy: true } })
+ expect(res.status).toBe(200)
+ expect(dbMock.design.updateMany).toHaveBeenCalledWith({
+ where: { ownerId: null, OR: [{ anonKey: null }] },
+ data: { ownerId: USER.id },
+ })
+ })
+
+ it('non-boolean includeLegacy is ignored (strict opt-in)', async () => {
+ const res = await post({ cookie: `${ANON_COOKIE}=t`, body: { includeLegacy: 'yes' } })
+ expect(res.status).toBe(200)
+ expect(dbMock.design.updateMany).toHaveBeenCalledWith({
+ where: { ownerId: null, OR: [{ anonKey: anonKeyHash('t') }] },
data: { ownerId: USER.id },
})
})
diff --git a/src/app/api/designs/adopt-all/route.ts b/src/app/api/designs/adopt-all/route.ts
index 6c29b08..a5fe4d5 100644
--- a/src/app/api/designs/adopt-all/route.ts
+++ b/src/app/api/designs/adopt-all/route.ts
@@ -6,11 +6,15 @@ import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
// POST /api/designs/adopt-all — one-click migration into an account.
//
-// v0.9.1 SAFETY: claims ONLY the ownerless designs attributed to the
-// caller's own browser (Design.anonKey = sha256 of the canvix_anon
-// cookie). Another person's anonymous work and pre-attribution legacy
-// rows are never touched — the first need their author's own browser,
-// the second are claimed one-by-one via POST /api/designs/[id]/adopt.
+// v0.9.1 SAFETY: by default claims ONLY the ownerless designs attributed
+// to the caller's own browser (Design.anonKey = sha256 of the canvix_anon
+// cookie). Another person's anonymous work is never touched.
+//
+// `{ includeLegacy: true }` additionally claims legacy rows (anonKey null,
+// created before attribution existed) — the deliberate, confirmed path for
+// self-hosters migrating a pre-accounts library. Even then, designs
+// attributed to OTHER browsers remain untouchable.
+//
// Idempotent; already-owned designs are excluded by the query itself.
export async function POST(req: NextRequest) {
if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
@@ -22,13 +26,26 @@ export async function POST(req: NextRequest) {
)
}
try {
+ const body = await req.json().catch(() => ({}))
+ const includeLegacy = body?.includeLegacy === true
const anonHash = anonHashFrom(req)
- if (!anonHash) {
- // No attribution cookie → nothing this browser created → claim nothing.
+
+ if (!anonHash && !includeLegacy) {
+ // No attribution cookie and no explicit legacy opt-in → claim nothing.
return NextResponse.json({ ok: true, adopted: 0 })
}
+
+ // mine (browser-attributed) always; legacy only with the explicit opt-in;
+ // foreign attributions NEVER.
+ const where = {
+ ownerId: null,
+ OR: [
+ ...(anonHash ? [{ anonKey: anonHash }] : []),
+ ...(includeLegacy ? [{ anonKey: null }] : []),
+ ],
+ }
const result = await db.design.updateMany({
- where: { ownerId: null, anonKey: anonHash },
+ where,
data: { ownerId: user.id },
})
return NextResponse.json({ ok: true, adopted: result.count })
diff --git a/src/app/api/designs/route.ts b/src/app/api/designs/route.ts
index daf94d4..b539097 100644
--- a/src/app/api/designs/route.ts
+++ b/src/app/api/designs/route.ts
@@ -22,10 +22,12 @@ function toPages(value: unknown): Prisma.InputJsonValue {
// designs; anonymous visitors see ownerless designs only. Owned designs
// are private to their account.
//
-// v0.9.1: each ownerless row carries `claimable` — true when the signed-in
-// (or anonymous) caller's browser is the author of the design, or when the
-// design predates attribution (legacy). The anonKey hash itself is never
-// returned, only the boolean decision.
+// v0.9.1: each ownerless row carries two flags (the anonKey hash itself is
+// never returned):
+// claimable — eligible for the per-design "Save to my account" action
+// (this browser's attribution OR a legacy pre-accounts row)
+// mine — attributed to THIS browser; the only rows the bulk
+// "Save my designs" action will claim
export async function GET(req: NextRequest) {
try {
const trash = req.nextUrl.searchParams.get('trash') === '1'
@@ -57,6 +59,7 @@ export async function GET(req: NextRequest) {
const out = designs.map(({ anonKey, ...d }) => ({
...d,
claimable: d.ownerId === null && (anonKey === null || anonKey === myHash),
+ mine: d.ownerId === null && anonKey !== null && anonKey === myHash,
}))
return NextResponse.json(out)
} catch (error) {
diff --git a/src/components/dashboard/Dashboard.tsx b/src/components/dashboard/Dashboard.tsx
index 096f2c0..ad982a0 100644
--- a/src/components/dashboard/Dashboard.tsx
+++ b/src/components/dashboard/Dashboard.tsx
@@ -116,13 +116,15 @@ export function Dashboard() {
const [helpOpen, setHelpOpen] = useState(false)
// v0.9: accounts — free forever, username + password
- const { user, login, register, logout } = useAuth()
+ const { user, login, register, logout, refresh: refreshAuth } = useAuth()
const [authOpen, setAuthOpen] = useState(false)
const [authMode, setAuthMode] = useState<'login' | 'register'>('login')
const [adopting, setAdopting] = useState(false)
- // v0.9.1: only designs attributed to THIS browser (or legacy rows) are
- // bulk-claimable — the server enforces the same rule, this is just the count.
- const claimableCount = (designs ?? []).filter((d) => d.claimable === true).length
+ // v0.9.1: the BULK action only claims designs attributed to THIS browser
+ // (server enforces the same). Legacy (pre-accounts) designs are claimable
+ // one-by-one, or deliberately in bulk via the explicit legacy item below.
+ const mineCount = (designs ?? []).filter((d) => d.mine === true).length
+ const legacyCount = (designs ?? []).filter((d) => d.ownerId === null && d.claimable === true && d.mine !== true).length
const [query, setQuery] = useState('')
const [category, setCategory] = useState<string>('all')
@@ -389,7 +391,7 @@ export function Dashboard() {
</div>
{user ? (
<>
- {claimableCount > 0 && (
+ {mineCount > 0 && (
<DropdownMenuItem
className="gap-2"
disabled={adopting}
@@ -406,10 +408,36 @@ export function Dashboard() {
}
}}
>
- <FolderInput size={14} /> {adopting ? 'Adopting…' : `Save my designs to this account (${claimableCount})`}
+ <FolderInput size={14} /> {adopting ? 'Adopting…' : `Save my designs to this account (${mineCount})`}
</DropdownMenuItem>
)}
- <DropdownMenuItem className="gap-2" onClick={() => void logout().then(() => refresh())}>
+ {legacyCount > 0 && (
+ <DropdownMenuItem
+ className="gap-2"
+ disabled={adopting}
+ onClick={async () => {
+ const ok = window.confirm(
+ `Adopt ${legacyCount} legacy design${legacyCount === 1 ? '' : 's'} created before accounts existed?\n\n` +
+ 'Only do this if this Canvix instance (or its shared designs) is yours — ' +
+ 'on a shared deployment, legacy designs may include other people\u2019s work.',
+ )
+ if (!ok) return
+ setAdopting(true)
+ try {
+ const adopted = await adoptAllDesigns(true)
+ await Promise.all([refreshAuth(), refresh()])
+ toast({ title: `${adopted} design${adopted === 1 ? '' : 's'} moved into your account` })
+ } catch {
+ toast({ title: 'Could not adopt designs', variant: 'destructive' })
+ } finally {
+ setAdopting(false)
+ }
+ }}
+ >
+ <FolderInput size={14} /> Adopt legacy (pre-accounts) designs ({legacyCount})
+ </DropdownMenuItem>
+ )}
+ <DropdownMenuItem className="gap-2" onClick={() => void logout().then(() => { void refreshAuth(); void refresh() })}>
<LogOut size={14} /> Sign out
</DropdownMenuItem>
</>
@@ -943,7 +971,8 @@ export function Dashboard() {
onOpenChange={setAuthOpen}
initialMode={authMode}
onAuthed={() => {
- // the dashboard scope changes with the session — reload it
+ // the session changed — re-read auth state AND the dashboard scope
+ void refreshAuth()
void refresh()
}}
/>
diff --git a/src/components/dashboard/hooks.ts b/src/components/dashboard/hooks.ts
index 78d848c..98b9bc6 100644
--- a/src/components/dashboard/hooks.ts
+++ b/src/components/dashboard/hooks.ts
@@ -15,6 +15,9 @@ export interface DesignMeta {
* signed-in account may claim this design. Foreign anonymous designs
* are view/share-only and can never be claimed from here. */
claimable?: boolean
+ /** v0.9.1: ownerless AND attributed to this exact browser — the only rows
+ * the bulk "Save my designs" action will claim. */
+ mine?: boolean
deletedAt: string | null
createdAt: string
updatedAt: string
diff --git a/src/lib/auth/client.ts b/src/lib/auth/client.ts
index 749237e..ebd58da 100644
--- a/src/lib/auth/client.ts
+++ b/src/lib/auth/client.ts
@@ -88,9 +88,17 @@ export function useAuth(): AuthState & {
* Claim the ownerless designs attributed to THIS browser for the signed-in
* account (v0.9.1: server-side scoped to the caller's canvix_anon cookie —
* another person's anonymous work is never touched).
+ *
+ * `includeLegacy` additionally claims pre-accounts (legacy) rows — the
+ * deliberate, confirmed path for self-hosters; the UI guards it behind a
+ * confirmation dialog.
*/
-export async function adoptAllDesigns(): Promise<number> {
- const res = await fetch('/api/designs/adopt-all', { method: 'POST' })
+export async function adoptAllDesigns(includeLegacy = false): Promise<number> {
+ const res = await fetch('/api/designs/adopt-all', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ includeLegacy }),
+ })
if (!res.ok) throw new Error('adopt failed')
const data = (await res.json()) as { adopted?: number }
return data.adopted ?? 0