Skip to content

Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.

TypeScript

fix(auth): a taken workspace slug must not abort the signup transaction

Xialie Zhuangd2ea7b7e5be0
diff --git a/server/src/__integration__/signup-slug-collision.test.ts b/server/src/__integration__/signup-slug-collision.test.ts
new file mode 100644
index 0000000..905cac8
--- /dev/null
+++ b/server/src/__integration__/signup-slug-collision.test.ts
@@ -0,0 +1,198 @@
+/**
+ * Personal-workspace slug collisions at signup (#102).
+ *
+ * This can only be proven against a real Postgres, because the bug IS a
+ * Postgres behaviour: a unique violation aborts the entire transaction until
+ * something rolls it back, so the retry that was supposed to pick a new slug
+ * instead came back with "current transaction is aborted, commands ignored
+ * until end of transaction block" — a message that is not a duplicate-key
+ * error, so it escaped the retry and was thrown all the way to the browser.
+ *
+ * The collision is not between one user's two accounts. The slug is derived
+ * from the email's local part and is unique across the whole deployment, so
+ * every signup whose local part was already taken by ANY earlier user hit it.
+ * Short, common local parts ("info", "me", "admin", a first name) make that
+ * ordinary rather than unlucky.
+ */
+import { after, before, beforeEach, test } from 'node:test'
+import assert from 'node:assert/strict'
+import { randomUUID } from 'node:crypto'
+import { pool } from '../db/pool.js'
+import { insertPersonalWorkspace, workspaceSlugSeed } from '../personal-workspace.js'
+import { ensureSchemaOnce, resetAllTables, teardownAll } from './_helpers.js'
+
+before(async () => { await ensureSchemaOnce() })
+beforeEach(async () => { await resetAllTables() })
+after(async () => { await teardownAll() })
+
+/** A user row to own the workspace — `companies.owner_user_id` references it. */
+async function seedUser(email: string): Promise<string> {
+ const id = `u-${randomUUID().slice(0, 8)}`
+ await pool.query(
+ `INSERT INTO users (id, email, display_name) VALUES ($1, $2, $3)`,
+ [id, email, email.split('@')[0]],
+ )
+ return id
+}
+
+/** Take a slug, exactly as an earlier signup would have. */
+async function occupySlug(slug: string): Promise<void> {
+ const owner = await seedUser(`${slug}[email protected]`)
+ await pool.query(
+ `INSERT INTO companies (id, name, slug, owner_user_id) VALUES ($1, $2, $3, $4)`,
+ [`co-${randomUUID().slice(0, 10)}`, 'earlier workspace', slug, owner],
+ )
+}
+
+test('a taken slug no longer aborts the signup transaction', async () => {
+ // The reported failure, reduced to its mechanism. Before the fix this threw
+ // `current transaction is aborted, commands ignored until end of transaction
+ // block` — the exact text the reporter saw in their address bar.
+ await occupySlug('info')
+
+ const userId = await seedUser('[email protected]')
+ const companyId = `co-${randomUUID().slice(0, 10)}`
+ const client = await pool.connect()
+ try {
+ await client.query('BEGIN')
+ const slug = await insertPersonalWorkspace(client, {
+ companyId, name: "Info's workspace", ownerUserId: userId, email: '[email protected]',
+ })
+ // The transaction must still be USABLE afterwards — that is the whole
+ // point. Signup does several more inserts (company_members, participants)
+ // before it commits, and an aborted transaction would fail every one.
+ await client.query(
+ `INSERT INTO company_members (company_id, user_id, role) VALUES ($1, $2, 'owner')`,
+ [companyId, userId],
+ )
+ await client.query('COMMIT')
+
+ assert.notEqual(slug, 'info', 'the taken slug must not be reused')
+ assert.match(slug, /^info-[0-9a-f]{4}$/)
+ } finally {
+ client.release()
+ }
+
+ const r = await pool.query(`SELECT slug FROM companies WHERE id = $1`, [companyId])
+ assert.equal(r.rowCount, 1, 'the workspace row must have been committed')
+
+ const m = await pool.query(`SELECT 1 FROM company_members WHERE company_id = $1`, [companyId])
+ assert.equal(m.rowCount, 1, 'the statements after the collision must have run')
+})
+
+test('an uncontested slug is still the plain local part', async () => {
+ // The retry must not change the common case: the first user named "erika"
+ // keeps `erika`, not `erika-1f2c`.
+ const userId = await seedUser('[email protected]')
+ const companyId = `co-${randomUUID().slice(0, 10)}`
+ const client = await pool.connect()
+ try {
+ await client.query('BEGIN')
+ const slug = await insertPersonalWorkspace(client, {
+ companyId, name: "Erika's workspace", ownerUserId: userId, email: '[email protected]',
+ })
+ await client.query('COMMIT')
+ assert.equal(slug, 'erika')
+ } finally {
+ client.release()
+ }
+})
+
+test('several signups on the same local part all succeed', async () => {
+ // Sequential rather than concurrent on purpose: each one must see the
+ // previous winner's slug and route around it. A single savepoint that was
+ // released but not re-taken would pass the first collision and fail the
+ // second.
+ const seen = new Set<string>()
+ for (let i = 0; i < 4; i++) {
+ const email = `me@example${i}.com`
+ const userId = await seedUser(email)
+ const companyId = `co-${randomUUID().slice(0, 10)}`
+ const client = await pool.connect()
+ try {
+ await client.query('BEGIN')
+ const slug = await insertPersonalWorkspace(client, {
+ companyId, name: `me ${i}`, ownerUserId: userId, email,
+ })
+ await client.query('COMMIT')
+ assert.ok(!seen.has(slug), `slug ${slug} handed out twice`)
+ seen.add(slug)
+ } finally {
+ client.release()
+ }
+ }
+ assert.equal(seen.size, 4)
+ assert.ok(seen.has('me'), 'the first one should still get the bare slug')
+})
+
+test('a failure that is not a unique violation is raised as itself', async () => {
+ // The retry exists for conflicts. Anything else — here a NOT NULL violation
+ // on companies.name — must come straight back out, not be retried four more
+ // times and then reported as a slug problem.
+ const userId = await seedUser('[email protected]')
+ const client = await pool.connect()
+ try {
+ await client.query('BEGIN')
+ await assert.rejects(
+ () => insertPersonalWorkspace(client, {
+ companyId: `co-${randomUUID().slice(0, 10)}`,
+ name: null as unknown as string,
+ ownerUserId: userId,
+ email: '[email protected]',
+ }),
+ (e: Error & { code?: string }) => e.code === '23502' && !/could not allocate/.test(e.message),
+ )
+ } finally {
+ await client.query('ROLLBACK').catch(() => {})
+ client.release()
+ }
+})
+
+test('an exhausted retry names the constraint that actually kept losing', async () => {
+ // Every retry changes only the SLUG, so a conflict on a different unique
+ // index can never be retried away. When that happens the error has to say
+ // so — "could not allocate a slug" alone would send the reader after the
+ // wrong problem for a second time.
+ const userId = await seedUser('[email protected]')
+ const companyId = `co-${randomUUID().slice(0, 10)}`
+ await pool.query(
+ `INSERT INTO companies (id, name, slug, owner_user_id) VALUES ($1, 'taken', $2, $3)`,
+ [companyId, `already-${randomUUID().slice(0, 6)}`, userId],
+ )
+
+ const client = await pool.connect()
+ try {
+ await client.query('BEGIN')
+ await assert.rejects(
+ // Same id as the row above: the conflict is on companies_pkey, and no
+ // amount of new slugs will move it.
+ () => insertPersonalWorkspace(client, {
+ companyId, name: 'dup', ownerUserId: userId, email: '[email protected]',
+ }),
+ (e: Error) => /could not allocate a workspace slug/.test(e.message)
+ && /companies_pkey/.test(e.message),
+ )
+ // And the transaction is still alive: each attempt rolled back to its own
+ // savepoint, so the caller can still report the failure cleanly.
+ const ping = await client.query('SELECT 1 AS ok')
+ assert.equal(ping.rows[0].ok, 1)
+ } finally {
+ await client.query('ROLLBACK').catch(() => {})
+ client.release()
+ }
+})
+
+test('the slug seed is unchanged for the shapes that already exist', () => {
+ // Existing workspaces keep the slugs they were given, so this derivation is
+ // frozen — including its quirks (it does not lowercase, so an uppercase
+ // local part becomes dashes).
+ assert.equal(workspaceSlugSeed('[email protected]'), 'info')
+ assert.equal(workspaceSlugSeed('[email protected]'), 'first-last')
+ assert.equal(workspaceSlugSeed('[email protected]'), 'a-b')
+ assert.equal(workspaceSlugSeed('@example.com'), 'workspace')
+ // An all-punctuation local part collapses to a bare '-' rather than the
+ // 'workspace' fallback, because '-' is truthy. Odd, but it is what existing
+ // workspaces were slugged with, so it stays.
+ assert.equal(workspaceSlugSeed('[email protected]'), '-')
+ assert.equal(workspaceSlugSeed(`${'x'.repeat(50)}@example.com`), 'x'.repeat(30))
+})
diff --git a/server/src/admin.ts b/server/src/admin.ts
index e31fef7..905bb8b 100644
--- a/server/src/admin.ts
+++ b/server/src/admin.ts
@@ -27,6 +27,7 @@ import { onboardStarterAgents, joinAllHands } from './onboardCompany.js'
import { companyTier } from './tier.js'
import { ensureCloudComputer, cloudComputerId } from './agents/computer/registry.js'
import { mirrorAvatar } from './oauth.js'
+import { insertPersonalWorkspace } from './personal-workspace.js'
import { provisionUser as provisionSub2apiUser, sub2apiConfigured, setUserTier } from './sub2api.js'
import { formatAddress, mintMessageId, sendViaProvider } from './email.js'
@@ -541,29 +542,12 @@ export async function approveWaitlist(waitlistId: string, decidedBy: string): Pr
let companyId: string | null = null
if (!skipPersonalWorkspace) {
companyId = `co-${randomUUID().slice(0, 10)}`
- const slugSeed = (row.email.split('@')[0] || 'workspace').replace(/[^a-z0-9]+/g, '-').slice(0, 30) || 'workspace'
- let finalSlug = slugSeed
- for (let attempt = 0; attempt < 5; attempt++) {
- // SAVEPOINT per attempt: a duplicate-key error aborts the whole
- // transaction until rolled back, so without this the *retry* INSERT
- // fails with "current transaction is aborted". Slug collisions are
- // common in bulk approval (short local-parts like "info"/"me" recur),
- // so this path is hot, not theoretical.
- await client.query('SAVEPOINT company_ins')
- try {
- await client.query(
- `INSERT INTO companies (id, name, slug, owner_user_id) VALUES ($1, $2, $3, $4)`,
- [companyId, `${row.display_name}'s workspace`, finalSlug, userId],
- )
- await client.query('RELEASE SAVEPOINT company_ins')
- break
- } catch (e) {
- const msg = e instanceof Error ? e.message : String(e)
- if (!/duplicate key/.test(msg)) throw e
- await client.query('ROLLBACK TO SAVEPOINT company_ins')
- finalSlug = `${slugSeed}-${randomUUID().slice(0, 4)}`
- }
- }
+ await insertPersonalWorkspace(client, {
+ companyId,
+ name: `${row.display_name}'s workspace`,
+ ownerUserId: userId,
+ email: row.email,
+ })
await client.query(
`INSERT INTO company_members (company_id, user_id, role) VALUES ($1, $2, 'owner')`,
[companyId, userId],
diff --git a/server/src/oauth.ts b/server/src/oauth.ts
index d5443f6..6b10633 100644
--- a/server/src/oauth.ts
+++ b/server/src/oauth.ts
@@ -34,12 +34,18 @@ import { pool } from './db/pool.js'
import { redis } from './redis.js'
import { env } from './env.js'
import { audit, createSession, gravatarUrlForEmail } from './auth.js'
+// Re-exported so callers keep importing sign-in errors from the auth module
+// they already use; the definitions live apart so unit tests can load them
+// without the DB/redis graph.
+export { SignInError, publicSignInError } from './auth-errors.js'
+import { SignInError } from './auth-errors.js'
import { onboardStarterAgents, joinAllHands } from './onboardCompany.js'
import { companyTier } from './tier.js'
import { ensureCloudComputer, cloudComputerId } from './agents/computer/registry.js'
import { storage } from './storage.js'
import { provisionUser as provisionSub2apiUser, sub2apiConfigured } from './sub2api.js'
import { isWaitlistEnabled, enqueueWaitlist, isAllowlistedAdmin } from './admin.js'
+import { insertPersonalWorkspace } from './personal-workspace.js'
export type Provider = 'google' | 'github' | 'gitlab' | 'apple'
@@ -233,7 +239,7 @@ export async function fetchProfile(p: Provider, accessToken: string): Promise<No
const r = await fetch(cfg.userInfoUrl, { headers: { authorization: `Bearer ${accessToken}` } })
if (!r.ok) throw new Error(`google userinfo ${r.status}`)
const g = await r.json() as GoogleProfile
- if (!g.email || !g.email_verified) throw new Error('google account has no verified email')
+ if (!g.email || !g.email_verified) throw new SignInError('google account has no verified email')
return {
providerId: g.sub,
email: g.email.toLowerCase(),
@@ -258,9 +264,9 @@ export async function fetchProfile(p: Provider, accessToken: string): Promise<No
// user confirmation disabled, in which case confirmed_at stays null even
// for an active account — refuse rather than trust it. `state` catches
// accounts that are blocked/deactivated but still hold a live token.
- if (g.state !== 'active') throw new Error('gitlab account is not active')
- if (!g.confirmed_at) throw new Error('gitlab account has no confirmed email')
- if (!g.email) throw new Error('gitlab account exposes no email to read_user')
+ if (g.state !== 'active') throw new SignInError('gitlab account is not active')
+ if (!g.confirmed_at) throw new SignInError('gitlab account has no confirmed email')
+ if (!g.email) throw new SignInError('gitlab account exposes no email to read_user')
return {
providerId: String(g.id),
email: g.email.toLowerCase(),
@@ -283,7 +289,7 @@ export async function fetchProfile(p: Provider, accessToken: string): Promise<No
const u = await userR.json() as GitHubProfile
const emails = await emailsR.json() as GitHubEmail[]
const verified = emails.find((e) => e.primary && e.verified) ?? emails.find((e) => e.verified)
- if (!verified) throw new Error('github account has no verified email')
+ if (!verified) throw new SignInError('github account has no verified email')
return {
providerId: String(u.id),
email: verified.email.toLowerCase(),
@@ -502,21 +508,12 @@ export async function findOrCreateUserByProfile(
let companyId: string | null = null
if (!inviteToken) {
companyId = `co-${randomUUID().slice(0, 10)}`
- const slugSeed = (profile.email.split('@')[0] || 'workspace').replace(/[^a-z0-9]+/g, '-').slice(0, 30) || 'workspace'
- let finalSlug = slugSeed
- for (let attempt = 0; attempt < 3; attempt++) {
- try {
- await client.query(
- `INSERT INTO companies (id, name, slug, owner_user_id) VALUES ($1, $2, $3, $4)`,
- [companyId, `${profile.displayName}'s workspace`, finalSlug, userId],
- )
- break
- } catch (e) {
- const msg = e instanceof Error ? e.message : String(e)
- if (!/duplicate key/.test(msg)) throw e
- finalSlug = `${slugSeed}-${randomUUID().slice(0, 4)}`
- }
- }
+ await insertPersonalWorkspace(client, {
+ companyId,
+ name: `${profile.displayName}'s workspace`,
+ ownerUserId: userId,
+ email: profile.email,
+ })
await client.query(
`INSERT INTO company_members (company_id, user_id, role) VALUES ($1, $2, 'owner')`,
[companyId, userId],
diff --git a/server/src/personal-workspace.ts b/server/src/personal-workspace.ts
new file mode 100644
index 0000000..edfe32a
--- /dev/null
+++ b/server/src/personal-workspace.ts
@@ -0,0 +1,95 @@
+/**
+ * Creating a user's personal workspace — the `companies` row plus a slug that
+ * is unique across the deployment.
+ *
+ * This lives in one module because the two paths that do it had drifted apart,
+ * and the drift WAS the bug (#102). Admin waitlist approval hit slug collisions
+ * first (bulk approval retries short local-parts like "info" and "me" back to
+ * back), was given a SAVEPOINT, and got a comment explaining why. OAuth signup
+ * — the path every single user takes — kept the version without one. One
+ * shared implementation is what stops the next fix landing on only one of them.
+ */
+import { randomUUID } from 'node:crypto'
+
+/** Attempts before we give up on finding a free slug. Each retry appends 4 hex
+ * characters, so reaching the end means something other than bad luck. */
+const MAX_SLUG_ATTEMPTS = 5
+
+/** Postgres `unique_violation`.
+ *
+ * Checked by SQLSTATE rather than by matching "duplicate key" in the message:
+ * that text comes from the server and is translated when `lc_messages` is not
+ * English, which would turn a recoverable collision into a hard signup
+ * failure on exactly the deployments least able to diagnose it. The message
+ * test stays as a fallback for drivers that surface an error without a code. */
+function isUniqueViolation(e: unknown): boolean {
+ const code = (e as { code?: unknown } | null)?.code
+ if (code === '23505') return true
+ return /duplicate key/i.test(e instanceof Error ? e.message : String(e))
+}
+
+/** The constraint a unique violation actually named, when the driver reports
+ * one. Only used to explain an exhausted retry — deliberately NOT used to
+ * decide whether to retry, because narrowing the retry to `companies_slug_key`
+ * would reintroduce #102 on any deployment that renamed the constraint. */
+function violatedConstraint(e: unknown): string | null {
+ const c = (e as { constraint?: unknown } | null)?.constraint
+ return typeof c === 'string' && c ? c : null
+}
+
+/** The slug a personal workspace starts from: the email's local part, reduced
+ * to the characters a slug may contain. Unchanged from what both call sites
+ * did inline — existing workspaces must keep the slugs they already have. */
+export function workspaceSlugSeed(email: string): string {
+ return (email.split('@')[0] || 'workspace').replace(/[^a-z0-9]+/g, '-').slice(0, 30) || 'workspace'
+}
+
+/**
+ * INSERT the personal workspace, retrying on slug collision. Returns the slug
+ * that was actually taken. Must be called inside an open transaction.
+ */
+export async function insertPersonalWorkspace(
+ client: import('pg').PoolClient,
+ args: { companyId: string; name: string; ownerUserId: string; email: string },
+): Promise<string> {
+ const seed = workspaceSlugSeed(args.email)
+ let slug = seed
+ let lastConflict: unknown = null
+ for (let attempt = 0; attempt < MAX_SLUG_ATTEMPTS; attempt++) {
+ // SAVEPOINT per attempt, and it is load-bearing. A unique violation aborts
+ // the ENTIRE transaction until something rolls it back, so a bare retry
+ // does not get a second shot at the slug: it fails with "current
+ // transaction is aborted, commands ignored until end of transaction
+ // block". That is not a duplicate-key error, so it escapes the retry and
+ // is thrown — which is how ONE taken slug turned every later signup with
+ // the same local part into a hard "Sign-in failed" (#102).
+ await client.query('SAVEPOINT personal_workspace')
+ try {
+ await client.query(
+ `INSERT INTO companies (id, name, slug, owner_user_id) VALUES ($1, $2, $3, $4)`,
+ [args.companyId, args.name, slug, args.ownerUserId],
+ )
+ await client.query('RELEASE SAVEPOINT personal_workspace')
+ return slug
+ } catch (e) {
+ if (!isUniqueViolation(e)) throw e
+ lastConflict = e
+ await client.query('ROLLBACK TO SAVEPOINT personal_workspace')
+ slug = `${seed}-${randomUUID().slice(0, 4)}`
+ }
+ }
+ // Running out used to fall through silently, leaving companyId pointing at no
+ // row — so a later statement failed on something unrelated and the operator
+ // was handed the wrong problem to solve.
+ //
+ // Name the constraint that actually kept losing. Every retry only changes the
+ // SLUG, so if the conflict was on some other unique index (a `companies_pkey`
+ // id collision, say) then five more attempts were never going to help, and
+ // saying "could not allocate a slug" would send the reader down the wrong
+ // path a second time.
+ const on = violatedConstraint(lastConflict)
+ throw new Error(
+ `could not allocate a workspace slug from "${seed}" after ${MAX_SLUG_ATTEMPTS} attempts` +
+ (on ? ` (last conflict was on ${on})` : ''),
+ )
+}