From b446adaee4890113e71a177814c7f631489b0255 Mon Sep 17 00:00:00 2001 From: Bas van den Aakster Date: Mon, 8 Dec 2025 21:31:36 +0100 Subject: [PATCH] fix: better error handling for public key constraint - Add try/catch in claimUsername to handle UNIQUE constraint - Return meaningful error: 'This public key has already claimed a different username' - Enable observability logs for better debugging --- src/storage/d1.ts | 64 ++++++++++++++++++++++++++--------------------- wrangler.toml | 2 +- 2 files changed, 37 insertions(+), 29 deletions(-) diff --git a/src/storage/d1.ts b/src/storage/d1.ts index 2dd74f9..d1a99a0 100644 --- a/src/storage/d1.ts +++ b/src/storage/d1.ts @@ -320,36 +320,44 @@ export class D1Storage implements Storage { const now = Date.now(); const expiresAt = now + YEAR_IN_MS; - // Try to insert or update - const result = await this.db.prepare(` - INSERT INTO usernames (username, public_key, claimed_at, expires_at, last_used, metadata) - VALUES (?, ?, ?, ?, ?, NULL) - ON CONFLICT(username) DO UPDATE SET - expires_at = ?, - last_used = ? - WHERE public_key = ? - `).bind( - request.username, - request.publicKey, - now, - expiresAt, - now, - expiresAt, - now, - request.publicKey - ).run(); + try { + // Try to insert or update + const result = await this.db.prepare(` + INSERT INTO usernames (username, public_key, claimed_at, expires_at, last_used, metadata) + VALUES (?, ?, ?, ?, ?, NULL) + ON CONFLICT(username) DO UPDATE SET + expires_at = ?, + last_used = ? + WHERE public_key = ? + `).bind( + request.username, + request.publicKey, + now, + expiresAt, + now, + expiresAt, + now, + request.publicKey + ).run(); - if ((result.meta.changes || 0) === 0) { - throw new Error('Username already claimed by different public key'); + if ((result.meta.changes || 0) === 0) { + throw new Error('Username already claimed by different public key'); + } + + return { + username: request.username, + publicKey: request.publicKey, + claimedAt: now, + expiresAt, + lastUsed: now, + }; + } catch (err: any) { + // Handle UNIQUE constraint on public_key + if (err.message?.includes('UNIQUE constraint failed: usernames.public_key')) { + throw new Error('This public key has already claimed a different username'); + } + throw err; } - - return { - username: request.username, - publicKey: request.publicKey, - claimedAt: now, - expiresAt, - lastUsed: now, - }; } async getUsername(username: string): Promise { diff --git a/wrangler.toml b/wrangler.toml index 7fd56c1..20bd84b 100644 --- a/wrangler.toml +++ b/wrangler.toml @@ -39,7 +39,7 @@ command = "" [observability] [observability.logs] -enabled = false +enabled = true head_sampling_rate = 1 invocation_logs = true persist = true