feat(tenant): single-tenant mode core (config SSOT + server/UI guards + branding)
Add lib/tenant.ts as the single source of truth for multi- vs single-tenant deployment. Gate space creation (server + signup UI), add open-join to the one space, hide the marketing shell, and route brand name + base URL through config. Also commit the _migrations_applied table into the canonical schema so a fresh instance is reproducible from schema.sql alone. - lib/tenant.ts: resolveTenantConfig (pure) + tenantConfig() + appBaseUrl() - lib/auth-actions.ts: createSpace refused when !allowSpaceCreation; joinSpace open-join resolves the configured/sole space with no invite code - proxy.ts: marketing paths redirect to /login when showMarketing is off - app/signup/page.tsx: single-tenant hides create/join chooser, brand=siteName - app/layout.tsx + 4 link builders: brand/base-URL via config (no hackerspace.sh literal) - scripts/schema.sql: public._migrations_applied tracking table - .env.example: documented single-tenant + first-admin bootstrap vars - package.json: pnpm setup
This commit is contained in:
@@ -17,6 +17,7 @@ import {
|
||||
deriveSubmitterEmail,
|
||||
} from '@/lib/forms-logic'
|
||||
import { renderFormEmail, formDedupeKey } from '@/lib/notifications-logic'
|
||||
import { appBaseUrl } from '@/lib/tenant'
|
||||
import {
|
||||
enqueueNotification,
|
||||
resolveMemberContact,
|
||||
@@ -193,7 +194,7 @@ export async function submitForm(input: unknown) {
|
||||
new Set(((admins ?? []) as Array<{ member_id: string }>).map(a => a.member_id)),
|
||||
)
|
||||
if (adminMemberIds.length > 0) {
|
||||
const resultsUrl = `${process.env.NEXT_PUBLIC_APP_URL || 'https://hackerspace.sh'}/forms/${form.id}/results`
|
||||
const resultsUrl = `${appBaseUrl()}/forms/${form.id}/results`
|
||||
const submitterLabel = await deriveSubmitterLabel(admin, form.space_id, {
|
||||
linkedMemberId,
|
||||
submitterEmail,
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
parseInput,
|
||||
} from '@/lib/auth-helpers'
|
||||
import { ADMIN_ROLES } from '@/lib/permissions'
|
||||
import { appBaseUrl } from '@/lib/tenant'
|
||||
import {
|
||||
addMemberSchema,
|
||||
updateMemberSchema,
|
||||
@@ -242,7 +243,7 @@ export async function requestEmailChange(input: { email: string }) {
|
||||
// Origin from trusted server config ONLY — never request headers. A forged
|
||||
// Host/X-Forwarded-Host could otherwise point the confirmation link at an
|
||||
// attacker origin and capture the victim's token_hash.
|
||||
const origin = process.env.NEXT_PUBLIC_APP_URL || 'https://hackerspace.sh'
|
||||
const origin = appBaseUrl()
|
||||
|
||||
const { error } = await supabase.auth.updateUser(
|
||||
{ email: v.data.email },
|
||||
|
||||
@@ -10,12 +10,13 @@ import { stripeSettingsSchema } from '@/lib/validations'
|
||||
import { isStripeConfigured, priceIdForTier } from '@/lib/stripe-logic'
|
||||
import { getStripeConfig, storeStripeSecret, readStripeSecret, type StripeConfig } from '@/lib/stripe/config'
|
||||
import { getStripe } from '@/lib/stripe/client'
|
||||
import { appBaseUrl } from '@/lib/tenant'
|
||||
|
||||
async function appOrigin(): Promise<string> {
|
||||
const h = await headers()
|
||||
const host = h.get('x-forwarded-host') ?? h.get('host')
|
||||
const proto = h.get('x-forwarded-proto') ?? 'https'
|
||||
return host ? `${proto}://${host}` : 'https://hackerspace.sh'
|
||||
return host ? `${proto}://${host}` : appBaseUrl()
|
||||
}
|
||||
|
||||
// Admin-facing settings view. NEVER returns secret values, only whether they
|
||||
|
||||
+51
-19
@@ -6,6 +6,7 @@ import { redirect } from 'next/navigation'
|
||||
import { checkRateLimit, sanitizeString, sanitizeSlug } from '@/lib/security'
|
||||
import { ACTIVE_STATUSES } from '@/lib/permissions'
|
||||
import { claimInviteUse } from '@/lib/invite-claim'
|
||||
import { tenantConfig } from '@/lib/tenant'
|
||||
|
||||
function generateInviteCode() {
|
||||
// Cryptographically random, and wider (8 chars) so the code space is not
|
||||
@@ -26,6 +27,13 @@ export async function createSpace(formData: {
|
||||
spaceCity?: string
|
||||
displayName: string
|
||||
}) {
|
||||
// Single-tenant instances host exactly one space; the app must not be able to
|
||||
// grow a second tenant. This is the authoritative server-side guard — the
|
||||
// signup UI also hides the "create a space" path, but that is UX only.
|
||||
if (!tenantConfig().allowSpaceCreation) {
|
||||
return { error: 'Space creation is disabled on this instance.' }
|
||||
}
|
||||
|
||||
// Verify user is authenticated using regular client
|
||||
const supabase = await createClient()
|
||||
const { data: { user }, error: userErr } = await supabase.auth.getUser()
|
||||
@@ -120,32 +128,56 @@ export async function joinSpace(formData: {
|
||||
|
||||
// Use admin client for operations
|
||||
const admin = createAdminClient()
|
||||
const tenant = tenantConfig()
|
||||
|
||||
const code = formData.inviteCode.trim().toUpperCase()
|
||||
|
||||
// Try the new multi-code invites table first. Falls back to the legacy
|
||||
// spaces.invite_code (a permanent default) if the code isn't found there.
|
||||
const { data: inviteRow } = await admin
|
||||
.from('space_invites')
|
||||
.select('id, space_id, max_uses, uses_count, expires_at, is_enabled, role')
|
||||
.eq('code', code)
|
||||
.maybeSingle()
|
||||
const invite = inviteRow
|
||||
// Single-tenant open-join: when this instance permits joining its one space
|
||||
// without an invite code, resolve that space directly (by configured slug, or
|
||||
// the sole space if no slug is set). require_approval is still honored below,
|
||||
// so new members land 'unverified' when the space demands approval.
|
||||
const openJoin = tenant.singleTenant && tenant.openJoin && code === ''
|
||||
|
||||
type InviteRow = {
|
||||
id: string; space_id: string; max_uses: number | null
|
||||
uses_count: number; expires_at: string | null; is_enabled: boolean
|
||||
role: 'admin' | 'board' | 'treasurer' | 'member' | 'associate'
|
||||
}
|
||||
let invite: InviteRow | null = null
|
||||
let spaceId: string | null = null
|
||||
if (invite) {
|
||||
if (!invite.is_enabled) return { error: 'This invite is disabled.' }
|
||||
if (invite.expires_at && new Date(invite.expires_at) < new Date()) return { error: 'This invite has expired.' }
|
||||
if (invite.max_uses !== null && invite.uses_count >= invite.max_uses) return { error: 'This invite has reached its use cap.' }
|
||||
spaceId = invite.space_id
|
||||
|
||||
if (openJoin) {
|
||||
const { data: target } = tenant.spaceSlug
|
||||
? await admin.from('spaces').select('id').eq('slug', tenant.spaceSlug).maybeSingle()
|
||||
: await admin.from('spaces').select('id').order('created_at', { ascending: true }).limit(1).maybeSingle()
|
||||
if (!target) {
|
||||
return { error: 'This instance is not set up yet. Ask an administrator to finish setup.' }
|
||||
}
|
||||
spaceId = target.id
|
||||
} else {
|
||||
const { data: legacy } = await admin
|
||||
.from('spaces')
|
||||
.select('id')
|
||||
.eq('invite_code', code)
|
||||
// Try the new multi-code invites table first. Falls back to the legacy
|
||||
// spaces.invite_code (a permanent default) if the code isn't found there.
|
||||
const { data: inviteRow } = await admin
|
||||
.from('space_invites')
|
||||
.select('id, space_id, max_uses, uses_count, expires_at, is_enabled, role')
|
||||
.eq('code', code)
|
||||
.maybeSingle()
|
||||
if (!legacy) return { error: 'Invalid invite code' }
|
||||
spaceId = legacy.id
|
||||
invite = inviteRow
|
||||
|
||||
if (invite) {
|
||||
if (!invite.is_enabled) return { error: 'This invite is disabled.' }
|
||||
if (invite.expires_at && new Date(invite.expires_at) < new Date()) return { error: 'This invite has expired.' }
|
||||
if (invite.max_uses !== null && invite.uses_count >= invite.max_uses) return { error: 'This invite has reached its use cap.' }
|
||||
spaceId = invite.space_id
|
||||
} else {
|
||||
const { data: legacy } = await admin
|
||||
.from('spaces')
|
||||
.select('id')
|
||||
.eq('invite_code', code)
|
||||
.maybeSingle()
|
||||
if (!legacy) return { error: 'Invalid invite code' }
|
||||
spaceId = legacy.id
|
||||
}
|
||||
}
|
||||
|
||||
const { data: space, error: lookupErr } = await admin
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
|
||||
import type { createAdminClient } from '@/lib/supabase/admin'
|
||||
import { captureException } from '@/lib/observability/capture'
|
||||
import { appBaseUrl } from '@/lib/tenant'
|
||||
|
||||
type AdminClient = ReturnType<typeof createAdminClient>
|
||||
|
||||
@@ -122,9 +123,9 @@ export async function getSpaceName(admin: AdminClient, spaceId: string): Promise
|
||||
|
||||
// Build the member portal URL the way every enqueue site does. Header host
|
||||
// takes precedence (lets a request to a non-canonical host link back to
|
||||
// itself); otherwise falls back to NEXT_PUBLIC_APP_URL and finally the prod
|
||||
// default. Same shape as the existing dues path.
|
||||
// itself); otherwise falls back to the configured base URL (appBaseUrl, which
|
||||
// resolves NEXT_PUBLIC_APP_URL). Same shape as the existing dues path.
|
||||
export function buildManageUrl(host?: string | null, proto?: string | null): string {
|
||||
if (host) return `${proto || 'https'}://${host}/me`
|
||||
return `${process.env.NEXT_PUBLIC_APP_URL || 'https://hackerspace.sh'}/me`
|
||||
return `${appBaseUrl()}/me`
|
||||
}
|
||||
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
// -----------------------------------------------------------------------------
|
||||
// Tenant / deployment configuration — the single source of truth for whether
|
||||
// this installation runs as a multi-tenant platform (the hackerspace.sh model,
|
||||
// one deployment hosting many spaces) or a single-tenant instance (one org runs
|
||||
// its own private deployment with exactly one space).
|
||||
//
|
||||
// The whole app is space-scoped either way; single-tenant mode does not change
|
||||
// the data model. It only (a) forbids creating a second space, (b) turns the
|
||||
// signup flow into "join THE space" instead of "create or join", (c) optionally
|
||||
// opens join without an invite code, (d) hides the hackerspace.sh marketing
|
||||
// shell, and (e) lets a deployer white-label the brand name and base URL.
|
||||
//
|
||||
// Pattern mirrors lib/auth-config.ts: a PURE resolver (unit-tested, no env) plus
|
||||
// a thin env-reading wrapper. Flags that the browser needs (the signup page is a
|
||||
// client component) are NEXT_PUBLIC_ so Next.js inlines them into the client
|
||||
// bundle — hence the literal `process.env.NEXT_PUBLIC_*` member expressions.
|
||||
//
|
||||
// SECURITY: every NEXT_PUBLIC_ flag is visible to and forgeable by the browser.
|
||||
// The server MUST re-enforce the same rules (see lib/auth-actions.ts). Treat the
|
||||
// client-side use of this config as UX only, never as an authorization boundary.
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
export type TenantConfig = {
|
||||
/** True when this deployment hosts exactly one space and behaves as a
|
||||
* dedicated instance rather than the multi-tenant platform. */
|
||||
singleTenant: boolean
|
||||
/** Brand name shown throughout the UI (logo wordmark, page titles). */
|
||||
siteName: string
|
||||
/** Canonical public base URL of this deployment, no trailing slash. Used for
|
||||
* absolute links in emails, form-result links, and OAuth redirects. */
|
||||
appUrl: string
|
||||
/** In single-tenant mode, the slug of the one space new signups join. Null
|
||||
* falls back to "the only space in the database" at join time. */
|
||||
spaceSlug: string | null
|
||||
/** Single-tenant only: allow signups to join without an invite code (still
|
||||
* subject to the space's require_approval gate). Ignored in multi-tenant. */
|
||||
openJoin: boolean
|
||||
/** Whether the "create a space" flow (signup UI + createSpace action) is
|
||||
* available. False in single-tenant mode so the instance cannot grow a
|
||||
* second tenant through the app. */
|
||||
allowSpaceCreation: boolean
|
||||
/** Whether the public marketing/landing shell (`/`, the /resources subsite)
|
||||
* is served. Defaults off in single-tenant mode. */
|
||||
showMarketing: boolean
|
||||
}
|
||||
|
||||
export type TenantEnv = {
|
||||
singleTenant?: string
|
||||
siteName?: string
|
||||
appUrl?: string
|
||||
spaceSlug?: string
|
||||
openJoin?: string
|
||||
showMarketing?: string
|
||||
}
|
||||
|
||||
const DEFAULT_SITE_NAME = 'hackerspace.sh'
|
||||
const DEFAULT_APP_URL = 'http://localhost:3000'
|
||||
|
||||
function isTrue(v: string | undefined): boolean {
|
||||
return v === 'true'
|
||||
}
|
||||
|
||||
/** Strip a trailing slash so callers can safely template `${appUrl}/path`. */
|
||||
function normalizeUrl(v: string | undefined, fallback: string): string {
|
||||
const raw = v?.trim()
|
||||
if (!raw) return fallback
|
||||
return raw.replace(/\/+$/, '')
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure core: resolve the tenant configuration from raw flag strings. No
|
||||
* process.env access, so it is trivially unit-testable. All defaulting and
|
||||
* precedence lives here.
|
||||
*/
|
||||
export function resolveTenantConfig(env: TenantEnv): TenantConfig {
|
||||
const singleTenant = isTrue(env.singleTenant)
|
||||
const slug = env.spaceSlug?.trim().toLowerCase()
|
||||
|
||||
return {
|
||||
singleTenant,
|
||||
siteName: env.siteName?.trim() || DEFAULT_SITE_NAME,
|
||||
appUrl: normalizeUrl(env.appUrl, DEFAULT_APP_URL),
|
||||
spaceSlug: singleTenant ? (slug || null) : null,
|
||||
// Open join only means anything in single-tenant mode. In multi-tenant the
|
||||
// invite code is the whole join model and is always required.
|
||||
openJoin: singleTenant && isTrue(env.openJoin),
|
||||
// Second-space creation is disabled in single-tenant mode. There is no
|
||||
// opt-out flag: the instance is single-tenant by definition.
|
||||
allowSpaceCreation: !singleTenant,
|
||||
// Marketing shell defaults to on for the platform, off for an instance,
|
||||
// but a single-tenant deployer can re-enable it explicitly.
|
||||
showMarketing: env.showMarketing !== undefined
|
||||
? isTrue(env.showMarketing)
|
||||
: !singleTenant,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Env-reading wrapper. The `process.env.NEXT_PUBLIC_*` reads are written as
|
||||
* literals so Next.js statically inlines them into the client bundle. Safe to
|
||||
* call from both server and client components.
|
||||
*/
|
||||
export function tenantConfig(): TenantConfig {
|
||||
return resolveTenantConfig({
|
||||
singleTenant: process.env.NEXT_PUBLIC_SINGLE_TENANT,
|
||||
siteName: process.env.NEXT_PUBLIC_SITE_NAME,
|
||||
appUrl: process.env.NEXT_PUBLIC_APP_URL,
|
||||
spaceSlug: process.env.NEXT_PUBLIC_SINGLE_TENANT_SPACE_SLUG,
|
||||
openJoin: process.env.NEXT_PUBLIC_SINGLE_TENANT_OPEN_JOIN,
|
||||
showMarketing: process.env.NEXT_PUBLIC_SHOW_MARKETING,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Canonical base URL for absolute links (emails, form results, self-serve
|
||||
* portal links). Replaces the scattered `NEXT_PUBLIC_APP_URL || 'https://hackerspace.sh'`
|
||||
* fallbacks so a single-tenant deploy never leaks the platform domain.
|
||||
*/
|
||||
export function appBaseUrl(): string {
|
||||
return tenantConfig().appUrl
|
||||
}
|
||||
|
||||
/** The set of public marketing paths gated by `showMarketing`. Kept in sync
|
||||
* with the /resources subsite routes and the landing page. */
|
||||
export const MARKETING_PATHS = [
|
||||
'/',
|
||||
'/resources',
|
||||
'/zine',
|
||||
'/governance',
|
||||
'/space-after-dark',
|
||||
'/proposal-duel',
|
||||
'/atlas',
|
||||
'/atlas.html',
|
||||
] as const
|
||||
|
||||
/** True when `pathname` is part of the marketing shell (exact or subpath). */
|
||||
export function isMarketingPath(pathname: string): boolean {
|
||||
return MARKETING_PATHS.some(
|
||||
p => pathname === p || (p !== '/' && pathname.startsWith(p + '/')),
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user