Auto-create tenant for any hostname that reaches the app
DNS is the gatekeeper — if a request arrives, it was pointed here intentionally. Every new hostname gets its own tenant automatically, no manual setup or seeding required. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -19,23 +19,71 @@ export async function resolveTenant(hostname: string): Promise<TenantInfo | null
|
||||
return cached.tenant;
|
||||
}
|
||||
|
||||
// Look up existing hostname mapping
|
||||
const record = await prisma.tenantHostname.findUnique({
|
||||
where: { hostname: host },
|
||||
include: { tenant: true }
|
||||
});
|
||||
|
||||
if (!record) return null;
|
||||
if (record) {
|
||||
const tenant: TenantInfo = {
|
||||
id: record.tenant.id,
|
||||
name: record.tenant.name,
|
||||
slug: record.tenant.slug
|
||||
};
|
||||
tenantCache.set(host, { tenant, expiresAt: Date.now() + CACHE_TTL });
|
||||
return tenant;
|
||||
}
|
||||
|
||||
const tenant: TenantInfo = {
|
||||
id: record.tenant.id,
|
||||
name: record.tenant.name,
|
||||
slug: record.tenant.slug
|
||||
};
|
||||
|
||||
tenantCache.set(host, { tenant, expiresAt: Date.now() + CACHE_TTL });
|
||||
// No mapping found — auto-provision
|
||||
// If a default tenant exists, map this hostname to it.
|
||||
// If no tenants exist at all, create the first one.
|
||||
const tenant = await autoProvisionTenant(host);
|
||||
if (tenant) {
|
||||
tenantCache.set(host, { tenant, expiresAt: Date.now() + CACHE_TTL });
|
||||
}
|
||||
return tenant;
|
||||
}
|
||||
|
||||
async function autoProvisionTenant(host: string): Promise<TenantInfo> {
|
||||
// Any hostname that reaches this app was pointed here via DNS,
|
||||
// so it's intentional. Auto-create a tenant for it.
|
||||
const slug = slugify(host);
|
||||
const name = humanizeDomain(host);
|
||||
|
||||
const tenant = await prisma.tenant.create({
|
||||
data: {
|
||||
name,
|
||||
slug,
|
||||
hostnames: {
|
||||
create: { hostname: host, isPrimary: true }
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return { id: tenant.id, name: tenant.name, slug: tenant.slug };
|
||||
}
|
||||
|
||||
function slugify(host: string): string {
|
||||
return host
|
||||
.replace(/[^a-zA-Z0-9]/g, '-')
|
||||
.replace(/-+/g, '-')
|
||||
.replace(/^-|-$/g, '')
|
||||
.toLowerCase()
|
||||
.slice(0, 48);
|
||||
}
|
||||
|
||||
function humanizeDomain(host: string): string {
|
||||
// "pounce.catrenelle.com" -> "Pounce"
|
||||
// "192.168.3.65" -> "Pounce"
|
||||
// "localhost" -> "Pounce"
|
||||
const part = host.split('.')[0];
|
||||
if (/^\d+$/.test(part) || part === 'localhost') {
|
||||
return 'Pounce';
|
||||
}
|
||||
return part.charAt(0).toUpperCase() + part.slice(1);
|
||||
}
|
||||
|
||||
export function clearTenantCache() {
|
||||
tenantCache.clear();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user