stack/apps/backend/prisma/seed.ts
BilalG1 57ff5d3ce9
Some checks failed
all-good: Did all the other checks pass? / all-good (push) Has been cancelled
Ensure Prisma migrations are in sync with the schema / check_prisma_migrations (22.x) (push) Has been cancelled
DB migration compat / Check if migrations changed (push) Has been cancelled
Docker Server Build and Push / Docker Build and Push Server (push) Has been cancelled
Docker Server Build and Run / docker (push) Has been cancelled
Runs E2E API Tests (Local Emulator) / E2E Tests (Local Emulator, Node ${{ matrix.node-version }}) (22.x) (push) Has been cancelled
Runs E2E API Tests / E2E Tests (Node ${{ matrix.node-version }}, Freestyle ${{ matrix.freestyle-mode }}) (mock, 22.x) (push) Has been cancelled
Runs E2E API Tests / E2E Tests (Node ${{ matrix.node-version }}, Freestyle ${{ matrix.freestyle-mode }}) (prod, 22.x) (push) Has been cancelled
Runs E2E API Tests with custom port prefix / build (22.x) (push) Has been cancelled
Runs E2E Fallback Tests / E2E Fallback Tests (Node ${{ matrix.node-version }}) (22.x) (push) Has been cancelled
Lint & build / lint_and_build (24) (push) Has been cancelled
TOC Generator / TOC Generator (push) Has been cancelled
DB migration compat / Back-compat — Current branch migrations with ${{ needs.check-migrations-changed.outputs.base_branch }} branch code (push) Has been cancelled
DB migration compat / Forward-compat — Current branch code with ${{ needs.check-migrations-changed.outputs.base_branch }} branch migrations (push) Has been cancelled
DB migration compat / No migration changes (skipped) (push) Has been cancelled
feat(hexclave): PR 2 — visible rebrand (Hexclave brand goes public) (#1481)
## Summary

**Stacked on [#1475](https://github.com/hexclave/stack-auth/pull/1475)**
(`cl/hexclave-pr1`, the invisible compatibility layer). Diff vs that
base = the actual PR 2 code.

This is **PR 2 of the Stack Auth → Hexclave rebrand: the visible flip**.
Old wire identifiers (cookies, request/response headers, Bearer prefix,
JWT issuers, MCP tool name) keep working indefinitely via PR 1's
dual-accept. This PR flips every user-visible surface — package names
taught in docs, SDK class names in code examples, dashboard setup
snippets, page titles, error messages, email content, CLI binary,
default base URLs, GitHub repo slug, contributor guidance — to the
Hexclave brand.

See [`RENAME-TO-HEXCLAVE.md`](./RENAME-TO-HEXCLAVE.md) → *"PR 2: Rebrand
to Hexclave (visible)"* for the full per-work-area spec.

## What's implemented (per the plan's PR 2 scope)

- **SDK base URLs** flipped: `defaultBaseUrl` and
`defaultAnalyticsBaseUrl` in
[common.ts](packages/template/src/lib/stack-app/apps/implementations/common.ts:127)
→ `https://api.hexclave.com` / `https://r.hexclave.com`. PR 1's
[`getHardcodedFallbackUrls`](packages/stack-shared/src/utils/urls.tsx:199)
table now keys on the Hexclave domain.

- **Domain inventory sweep** (16 subdomains from the plan): every
`api/app/docs/discord/demo/mcp/skill/feedback/test/preview/r/api2/api.staging/idp-jwk-audience/built-with.stack-auth.com`
reference in production code, docs-mintlify, examples, READMEs, and
contributor guidance flipped to `*.hexclave.com`. Carve-outs: PR 1's
intentional JWT issuer dual-accept table in
[tokens.tsx](apps/backend/src/lib/tokens.tsx), the legacy `./docs/`
folder, the `unified-docs-widget` allowlist (deliberately accepts both
during DNS transition), and `url-targets.ts` hosted-component default
(baked into existing customer deploys).

- **`@deprecated` JSDoc** on every `Stack*` public export
([packages/template/src/lib/stack-app/index.ts](packages/template/src/lib/stack-app/index.ts)
+ [packages/template/src/index.ts](packages/template/src/index.ts)) —
`StackClientApp`, `StackServerApp`, `StackAdminApp` + every
constructor/options/JSON type, `StackHandler`, `StackProvider`,
`StackTheme`, `useStackApp`, `defineStackConfig`, `StackConfig`.
Hexclave\* aliases are now canonical.

- **Runtime `console.warn`**
([packages/template/src/internal/deprecation-warning.ts](packages/template/src/internal/deprecation-warning.ts))
— once-per-process when the SDK is loaded from a `@stackframe/*`
artifact. Detection uses the existing
`STACK_COMPILE_TIME_CLIENT_PACKAGE_VERSION_SENTINEL` (rewritten at build
time to e.g. `js @stackframe/stack@2.8.92` or `js
@hexclave/next@1.0.0`); `@hexclave/*` mirror artifacts short-circuit the
warning.

- **Tier 3 data migration**: new idempotent SQL migration
[`20260523000000_rename_internal_project_to_hexclave`](apps/backend/prisma/migrations/20260523000000_rename_internal_project_to_hexclave/migration.sql)
— updates the internal Project `displayName` 'Stack Dashboard' →
'Hexclave Dashboard' and `description` only if both still hold the
pre-rebrand defaults. Operator-renamed projects untouched, missing row
no-ops, re-runs are no-ops. [`seed.ts`](apps/backend/prisma/seed.ts:87)
default flipped. `getSharedEmailConfig("Stack Auth")` → `("Hexclave")`.

- **Tier 4 brand strings** (mechanical sweep, ~340 files):
- Page + OpenAPI titles (Hexclave API / Dashboard / REST API / Webhooks
API / Documentation). OpenAPI `info.description` documents
`X-Hexclave-*` headers as canonical with compat note on `X-Stack-*`.
- `HexclaveAssertionError` message text
([errors.tsx:71](packages/stack-shared/src/utils/errors.tsx:71)) — "an
error in Stack." → "an error in Hexclave."
- Known-error message templates
([known-errors.tsx](packages/stack-shared/src/known-errors.tsx)) flipped
to lead with `x-hexclave-*` + the new `docs.hexclave.com` URL; legacy
`x-stack-*` mentioned as compat aliases. **25 e2e test files updated in
lockstep**.
- Email content: failed-emails-digest body, sendTestEmail recipient (now
`sent-with-hexclave.com`), test-email-recipient default.
  - `CHANGELOG.md` title → "Hexclave Changelog".
- `AGENTS.md` env var convention: new vars prefix `HEXCLAVE_` /
`NEXT_PUBLIC_HEXCLAVE_` for Category A/B; legacy `STACK_*` explicitly
noted as accepted via PR 1's dual-read.

- **CLI / init wizard**:
- Every dashboard setup snippet, init-stack template, and docs-mintlify
page teaches `npx @hexclave/cli@latest init` (was
`@stackframe/stack-cli`).
[setup-page.tsx](apps/dashboard/src/app/(main)/(protected)/projects/[projectId]/(overview)/setup-page.tsx)
+
[link-existing-onboarding](apps/dashboard/src/app/(main)/(protected)/(outside-dashboard)/new-project/page-client-parts/link-existing-onboarding.tsx).
- [init-stack](packages/init-stack/src/index.ts:634)
`STACK_*_INSTALL_PACKAGE_NAME_OVERRIDE` defaults flipped to
`@hexclave/*`.
- Generated `stack/client.ts` / `stack/server.ts` import from
`@hexclave/next` and reference `HexclaveClientApp` /
`HexclaveServerApp`.
- Internal `StackAuthKeys` dashboard component renamed to
`HexclaveKeys`.

- **docs-mintlify rewrite** (legacy `./docs/` intentionally untouched
per scoping decision):
- **78 MDX files swept**.
`@stackframe/{react,stack,js,tanstack-start,...}` →
`@hexclave/{react,stack,js,...}` in install snippets and code blocks;
`Stack*` SDK class names → `Hexclave*` in all code examples; 'Stack
Auth' brand phrase → 'Hexclave'.
- `openapi/{server,admin,client,webhooks}.json` titles → 'Hexclave REST
API' / 'Hexclave Webhooks API'.

- **Generators flipped before regeneration**:
-
[`packages/stack-shared/src/helpers/init-prompt.ts`](packages/stack-shared/src/helpers/init-prompt.ts),
[`/ai/prompts.ts`](packages/stack-shared/src/ai/prompts.ts),
[`apps/backend/src/lib/ai/prompts.ts`](apps/backend/src/lib/ai/prompts.ts),
[`apps/backend/src/lib/ai/tools/create-email-{template,draft}.ts`](apps/backend/src/lib/ai/tools/create-email-template.ts),
[`apps/skills/src/app/route.ts`](apps/skills/src/app/route.ts) (taught
MCP tool → `ask_hexclave` with compat note; CLI binary teach →
`hexclave`),
[`docs-mintlify/snippets/home-prompt-island.jsx`](docs-mintlify/snippets/home-prompt-island.jsx),
[`packages/template/README.md`](packages/template/README.md) +
integrations/convex/component/README.md.
  - `generate-sdks` propagated changes to `packages/{react,stack,js}`.

- **OpenAPI dual-documentation**:
[`apps/backend/src/app/api/latest/route.ts`](apps/backend/src/app/api/latest/route.ts)
now lists `X-Hexclave-*` headers as primary documented schemas with
`X-Stack-*` duplicates marked `.optional()` (both accepted at runtime by
PR 1's normalize-at-proxy shim).

- **`@stackframe/emails` virtual module**: dual-aliased to
`@hexclave/emails` at the bundler boundary
([email-rendering.tsx:89](apps/backend/src/lib/email-rendering.tsx:89)).
Stored email templates continue to import from either name; new
AI-generated templates and the system prompt teach `@hexclave/emails`.

- **Tier 2 mirror-publish wiring** (new this PR, lays the groundwork for
`@hexclave/*` first publish):
-
[`scripts/rewrite-packages-to-hexclave.ts`](scripts/rewrite-packages-to-hexclave.ts)
— rewrites 9 publishable `@stackframe/*` → `@hexclave/*` `package.json`
files (reads `HEXCLAVE_VERSION` env or `--version=` flag), pins
cross-deps to the shared `@hexclave` version, registers `hexclave` bin
alongside `stack` for `@hexclave/cli`.
-
[`.github/workflows/npm-publish.yaml`](.github/workflows/npm-publish.yaml)
appended with rewrite-then-republish step. `pnpm publish` skips
already-on-npm versions so reruns are safe.

- **Sender email domain**: `noreply@stackframe.co` →
`noreply@sent-with-hexclave.com` (the dedicated transactional-sender
domain split per the plan, to isolate bulk deliverability from
`hexclave.com` reputation); `security@` / `team@stack-auth.com` inbound
mailboxes → `@hexclave.com`.

- **Self-host docs**: docker network / container names in the bash
examples flipped from `stack-auth` to `hexclave` (`hexclave-postgres`,
`hexclave-clickhouse`, `hexclave.env`). The docker image tag
`stackauth/server:latest` stays per the plan's locked decision.

- **GitHub repo slug**: `hexclave/stack-auth` → `hexclave/hexclave` in
every `package.json` `repository` field, README link, CHANGELOG
raw-asset URL.

## Carve-outs (deliberately untouched)

-
**[`apps/backend/src/lib/tokens.tsx`](apps/backend/src/lib/tokens.tsx)**
JWT issuer dual-accept table — PR 1 intentional infrastructure, kept
indefinitely.
- **Legacy `./docs/` folder** — per scoping decision (only
`docs-mintlify/` rewritten).
- **`unified-docs-widget` hostname allowlist** — accepts both
`.hexclave.com` (canonical) and `.stack-auth.com` (transition window)
for DNS rollout.
- **`url-targets.ts`** hosted-domain default
`.built-with-stack-auth.com` — wire identifier baked into existing
customer deploys; indefinite read-fallback.
- **Binary visual assets** (logos, favicons, OG images, README
screenshots) — out of scope for this PR. Need design work; tracked
separately.

## Verification

- **`pnpm typecheck`** on
`packages/{template,stack-shared,react,stack,js}` + `apps/dashboard`:
**all green**. The remaining backend / e-commerce-demo typecheck errors
are pre-existing (Prisma codegen output +
`./generated/api-versions.json` not present in fresh worktrees without
`pnpm run codegen-prisma` + a live DB) and unrelated to this diff.
- **`pnpm lint`** on the same 6 packages: all green.
- **Final grep** for residual `Stack Auth` / `stack-auth.com` /
`@stackframe/stack-cli@latest` references: zero outside the intentional
carve-outs above.
- **25 e2e test files updated in lockstep** with the known-error message
changes (asserted strings flipped to match the new x-hexclave-* +
compat-note messages).

## Deploy blockers (ops sequencing before this rebrand goes live)

This PR is code-complete, but the rebrand's visible surfaces (SDK
default URLs, dashboard links, npm READMEs, REST error messages, runtime
deprecation warning) all point at `*.hexclave.com` / `@hexclave/*`
resources that don't exist yet. None of these are fixable from a PR —
they're ops/registrar/npm work that has to be sequenced before merging
this to a release tag.

Suggested ordering, hardest blockers first:

### Tier 1 — required before customer-facing deploy (everything below
this line *will visibly break customers on day 1* if skipped)

1. **DNS + TLS for `api.hexclave.com` + `api1./api2.hexclave.com`** →
must point at the same backend that serves `api.stack-auth.com` (or a
backend that mirrors PR 1's dual-accept). The SDK's new `defaultBaseUrl`
is `https://api.hexclave.com`; every customer that relied on the old
default and upgrades to a post-PR2 SDK build sends API requests here.
Until this resolves, every default-config customer's API call NXDOMAINs.
2. **DNS for `app.hexclave.com`** → the dashboard. Referenced in the
SDK's default-error messages ("Please create a project on the Hexclave
dashboard at https://app.hexclave.com"), the init-stack flow's
`wizard-congrats` redirect, and the OAuth dashboard handoff.
3. **DNS for `docs.hexclave.com`** + Mintlify deploy → the SDK runtime
deprecation warning (`https://docs.hexclave.com/migration`), every
README, every "Learn more" link in the dashboard, and every REST API
error body (`/api/overview#authentication`) points here. The MDX is in
this PR; the docs build target needs DNS.
4. **DNS for `mcp.hexclave.com`** → the MCP server endpoint that every
taught agent integration (`claude mcp add ...`, `cursor`, `codex`,
`vscode`) registers. Until this resolves, every `npx
@hexclave/cli@latest init` MCP-registration step fails.
5. **Reserve the `@hexclave` npm scope + set repo variable
`HEXCLAVE_VERSION`** → the mirror-publish step in
`.github/workflows/npm-publish.yaml` is gated on this variable. Without
it, the entire taught onboarding command `npx @hexclave/cli@latest init`
404s from the npm registry, *and* every README that says "install
`@hexclave/next`" leads to install failure. Pick the initial version
intentionally (`1.0.0` or aligned to `@stackframe/stack`); don't accept
a silent default.

### Tier 2 — required before announcing the rebrand publicly (lookalike
or low-traffic surfaces, but visibly broken)

6. **DNS for `r.hexclave.com`** → the analytics beacon
`defaultAnalyticsBaseUrl`. Silent failure if missing (analytics drops),
but should land alongside Tier 1.
7. **Register `sent-with-hexclave.com` + full email auth (SPF / DKIM /
DMARC)** → the new default sender domain for shared-sender transactional
emails. Without it the dashboard "send test email" path emits bounces,
and shared-sender flows (`getSharedEmailConfig("Hexclave")`) deliver to
spam at best.
8. **MX + SPF / DMARC for `hexclave.com`** → `team@hexclave.com` and
`security@hexclave.com` mailboxes. The security disclosure mailbox is
referenced in [`.github/SECURITY.md`](.github/SECURITY.md);
`team@hexclave.com` is the actual recipient of internal feedback emails
sent at runtime by
[`apps/backend/src/lib/internal-feedback-emails.tsx`](apps/backend/src/lib/internal-feedback-emails.tsx).
Today, every runtime feedback email bounces.
9. **DNS for `skill.hexclave.com`** → the canonical AI-agent skill fetch
URL (the agent bootstrap pivot). Without it, the entire "agent downloads
`SKILL.md` from a known URL" flow taught in
[`packages/stack-shared/src/helpers/init-prompt.ts`](packages/stack-shared/src/helpers/init-prompt.ts)
fails.
10. **Create `github.com/hexclave/hexclave` as a public repo** (even as
a redirect to `hexclave/stack-auth`) **OR** rewrite every `package.json`
`"repository"` field + dashboard footer "view on GitHub" link to point
at `hexclave/stack-auth` (which already exists). Currently every npm
package page's "Repository" link is dead, and the dashboard's GitHub
button + dev-tool repo link are dead.

### Tier 3 — broken but low-visibility / low-traffic

11. **DNS for `discord.hexclave.com`** → Discord invite redirect, used
in every README's chip and the dashboard footer.
12. **DNS for `demo.hexclave.com`** → " Demo" badge in every npm
package README. Broken-image badge on the package page.
13. **DNS + TLS for `built-with-hexclave.com`** → optional
hosted-handler domain (the default reverted to
`.built-with-stack-auth.com` in this PR's carve-outs, so this only
matters for projects that manually flip).

## Other follow-ups (not deploy-blocking)

- **E2E snapshot regen across the full suite** for the dual-emitted
`x-hexclave-*` response headers (PR 1 follow-up; `vitest -u` in CI
absorbs).
- **Binary visual assets** — logos, favicons, OG images, README
screenshots; need design pass.
- **Backend OpenAPI fumadocs regen** in CI flow — the JSON files in
`docs-mintlify/openapi/` are committed but regen runs in CI. Verify the
workflow that does this still works against the post-PR2 source.
- **Backend typecheck infra debt** — needs `codegen-prisma` +
`codegen-route-info` to clear; pre-existing, unaffected by this PR.

## Test plan

- [ ] CI runs full e2e suite (with `vitest -u` to absorb residual
snapshot deltas, then committed back).
- [ ] Spot-check: new `@hexclave/cli init` (once published) generates
`hexclave.config.ts` and works against a fresh project.
- [ ] Spot-check: existing customer with `@stackframe/stack` import sees
the once-per-process `console.warn` recommending `@hexclave/next` on SDK
init.
- [ ] Manual: dashboard setup page renders the `npx @hexclave/cli@latest
init` snippet and the `x-hexclave-publishable-client-key` API header in
the curl example.
- [ ] Manual: a fresh `pnpm run prisma migrate` against a clean DB sets
the internal project displayName to 'Hexclave Dashboard'.

---------

Co-authored-by: Konstantin Wohlwend <n2d4xc@gmail.com>
2026-05-26 19:18:20 -07:00

673 lines
26 KiB
TypeScript

/* eslint-disable no-restricted-syntax */
import { usersCrudHandlers } from '@/app/api/latest/users/crud';
import { CustomerType, Prisma, PurchaseCreationSource, SubscriptionStatus } from '@/generated/prisma/client';
import { overrideBranchConfigOverride } from '@/lib/config';
import {
LOCAL_EMULATOR_ADMIN_EMAIL,
LOCAL_EMULATOR_ADMIN_PASSWORD,
LOCAL_EMULATOR_ADMIN_USER_ID,
LOCAL_EMULATOR_OWNER_TEAM_ID,
isLocalEmulatorEnabled,
} from '@/lib/local-emulator';
import { ensurePermissionDefinition, grantTeamPermission } from '@/lib/permissions';
import { createOrUpdateProjectWithLegacyConfig, getProject } from '@/lib/projects';
import { seedDummyProject } from '@/lib/seed-dummy-data';
import { DEFAULT_BRANCH_ID, getSoleTenancyFromProjectBranch } from '@/lib/tenancies';
import { getPrismaClientForTenancy, globalPrismaClient } from '@/prisma-client';
import { ALL_APPS } from '@stackframe/stack-shared/dist/apps/apps-config';
import { DEFAULT_EMAIL_THEME_ID } from '@stackframe/stack-shared/dist/helpers/emails';
import { AdminUserProjectsCrud } from '@stackframe/stack-shared/dist/interface/crud/projects';
import { ITEM_IDS, PLAN_LIMITS } from '@stackframe/stack-shared/dist/plans';
import { DayInterval } from '@stackframe/stack-shared/dist/utils/dates';
import { throwErr } from '@stackframe/stack-shared/dist/utils/errors';
import { typedEntries, typedFromEntries } from '@stackframe/stack-shared/dist/utils/objects';
const MONTHLY_REPEAT: DayInterval = [1, "month"];
const DUMMY_PROJECT_ID = '6fbbf22e-f4b2-4c6e-95a1-beab6fa41063';
const DEVELOPMENT_ENVIRONMENT_PROJECT_ID = '5f2a45c8-9096-4f0b-b987-7640a47f7a79';
let didEnableSeedLogTimestamps = false;
function enableSeedLogTimestamps() {
if (didEnableSeedLogTimestamps) return;
didEnableSeedLogTimestamps = true;
const originalLog = console.log.bind(console);
const originalInfo = console.info.bind(console);
const originalWarn = console.warn.bind(console);
const originalError = console.error.bind(console);
const withTimestamp = (...data: unknown[]) => [`[${new Date().toISOString()}]`, ...data];
console.log = (...data: Parameters<typeof console.log>) => {
originalLog(...withTimestamp(...data));
};
console.info = (...data: Parameters<typeof console.info>) => {
originalInfo(...withTimestamp(...data));
};
console.warn = (...data: Parameters<typeof console.warn>) => {
originalWarn(...withTimestamp(...data));
};
console.error = (...data: Parameters<typeof console.error>) => {
originalError(...withTimestamp(...data));
};
}
export async function seed() {
enableSeedLogTimestamps();
process.env.STACK_SEED_MODE = 'true';
console.log('Seeding database...');
// Optional default admin user
const adminEmail = process.env.STACK_SEED_INTERNAL_PROJECT_USER_EMAIL;
const adminPassword = process.env.STACK_SEED_INTERNAL_PROJECT_USER_PASSWORD;
const adminInternalAccess = process.env.STACK_SEED_INTERNAL_PROJECT_USER_INTERNAL_ACCESS === 'true';
const adminGithubId = process.env.STACK_SEED_INTERNAL_PROJECT_USER_GITHUB_ID;
// dashboard settings
const dashboardDomain = process.env.NEXT_PUBLIC_STACK_DASHBOARD_URL;
const oauthProviderIds = process.env.STACK_SEED_INTERNAL_PROJECT_OAUTH_PROVIDERS?.split(',') ?? [];
const otpEnabled = process.env.STACK_SEED_INTERNAL_PROJECT_OTP_ENABLED === 'true';
const signUpEnabled = process.env.STACK_SEED_INTERNAL_PROJECT_SIGN_UP_ENABLED === 'true';
const allowLocalhost = process.env.STACK_SEED_INTERNAL_PROJECT_ALLOW_LOCALHOST === 'true';
const localEmulatorEnabled = isLocalEmulatorEnabled();
const apiKeyId = '3142e763-b230-44b5-8636-aa62f7489c26';
const defaultUserId = '33e7c043-d2d1-4187-acd3-f91b5ed64b46';
const internalTeamId = 'a23e1b7f-ab18-41fc-9ee6-7a9ca9fa543c';
let internalProject = await getProject('internal');
if (!internalProject) {
internalProject = await createOrUpdateProjectWithLegacyConfig({
type: 'create',
projectId: 'internal',
data: {
display_name: 'Hexclave Dashboard',
owner_team_id: internalTeamId,
description: 'Hexclave\'s admin dashboard',
is_production_mode: false,
config: {
allow_localhost: true,
oauth_providers: oauthProviderIds.map((id) => ({
id: id as any,
type: 'shared',
})),
sign_up_enabled: signUpEnabled,
credential_enabled: true,
magic_link_enabled: otpEnabled,
},
},
});
console.log('Internal project created');
}
const internalTenancy = await getSoleTenancyFromProjectBranch("internal", DEFAULT_BRANCH_ID);
const internalPrisma = await getPrismaClientForTenancy(internalTenancy);
internalProject = await createOrUpdateProjectWithLegacyConfig({
projectId: 'internal',
branchId: DEFAULT_BRANCH_ID,
type: 'update',
data: {
config: {
create_team_on_sign_up: true,
sign_up_enabled: signUpEnabled,
magic_link_enabled: otpEnabled,
allow_localhost: allowLocalhost,
client_team_creation_enabled: true,
domains: [
...(dashboardDomain && new URL(dashboardDomain).hostname !== 'localhost' ? [{ domain: dashboardDomain, handler_path: '/handler' }] : []),
...Object.values(internalTenancy.config.domains.trustedDomains)
.filter((d) => d.baseUrl !== dashboardDomain && d.baseUrl)
.map((d) => ({ domain: d.baseUrl || throwErr('Domain base URL is required'), handler_path: d.handlerPath })),
],
},
},
});
await overrideBranchConfigOverride({
projectId: 'internal',
branchId: DEFAULT_BRANCH_ID,
branchConfigOverrideOverride: {
// Disable email verification for internal project - dashboard admins shouldn't need to verify their email
onboarding: {
requireEmailVerification: false,
},
dataVault: {
stores: {
'neon-connection-strings': {
displayName: 'Neon Connection Strings',
}
}
},
payments: {
productLines: {
plans: {
displayName: "Plans",
customerType: "team",
},
},
products: {
free: {
productLineId: "plans",
displayName: "Free",
customerType: "team",
serverOnly: false,
stackable: false,
prices: {
"free-monthly": {
USD: "0",
interval: [1, "month"] as any,
},
},
includedItems: {
[ITEM_IDS.seats]: { quantity: PLAN_LIMITS.free.seats, repeat: "never" as const, expires: "when-purchase-expires" as const },
[ITEM_IDS.authUsers]: { quantity: PLAN_LIMITS.free.authUsers, repeat: "never" as const, expires: "when-purchase-expires" as const },
[ITEM_IDS.emailsPerMonth]: { quantity: PLAN_LIMITS.free.emailsPerMonth, repeat: MONTHLY_REPEAT, expires: "when-repeated" as const },
[ITEM_IDS.analyticsTimeoutSeconds]: { quantity: PLAN_LIMITS.free.analyticsTimeoutSeconds, repeat: "never" as const, expires: "when-purchase-expires" as const },
[ITEM_IDS.analyticsEvents]: { quantity: PLAN_LIMITS.free.analyticsEvents, repeat: MONTHLY_REPEAT, expires: "when-repeated" as const },
[ITEM_IDS.sessionReplays]: { quantity: PLAN_LIMITS.free.sessionReplays, repeat: MONTHLY_REPEAT, expires: "when-repeated" as const },
},
},
team: {
productLineId: "plans",
displayName: "Team",
customerType: "team",
serverOnly: false,
stackable: false,
prices: {
monthly: {
USD: "49",
interval: MONTHLY_REPEAT,
serverOnly: false,
},
},
includedItems: {
[ITEM_IDS.seats]: { quantity: PLAN_LIMITS.team.seats, repeat: "never" as const, expires: "when-purchase-expires" as const },
[ITEM_IDS.authUsers]: { quantity: PLAN_LIMITS.team.authUsers, repeat: "never" as const, expires: "when-purchase-expires" as const },
[ITEM_IDS.emailsPerMonth]: { quantity: PLAN_LIMITS.team.emailsPerMonth, repeat: MONTHLY_REPEAT, expires: "when-repeated" as const },
[ITEM_IDS.analyticsTimeoutSeconds]: { quantity: PLAN_LIMITS.team.analyticsTimeoutSeconds, repeat: "never" as const, expires: "when-purchase-expires" as const },
[ITEM_IDS.analyticsEvents]: { quantity: PLAN_LIMITS.team.analyticsEvents, repeat: MONTHLY_REPEAT, expires: "when-repeated" as const },
[ITEM_IDS.sessionReplays]: { quantity: PLAN_LIMITS.team.sessionReplays, repeat: MONTHLY_REPEAT, expires: "when-repeated" as const },
[ITEM_IDS.onboardingCall]: { quantity: 1, repeat: "never" as const, expires: "when-purchase-expires" as const },
},
},
growth: {
productLineId: "plans",
displayName: "Growth",
customerType: "team",
serverOnly: false,
stackable: false,
prices: {
monthly: {
USD: "299",
interval: MONTHLY_REPEAT,
serverOnly: false,
},
},
includedItems: {
[ITEM_IDS.seats]: { quantity: PLAN_LIMITS.growth.seats, repeat: "never" as const, expires: "when-purchase-expires" as const },
[ITEM_IDS.authUsers]: { quantity: PLAN_LIMITS.growth.authUsers, repeat: "never" as const, expires: "when-purchase-expires" as const },
[ITEM_IDS.emailsPerMonth]: { quantity: PLAN_LIMITS.growth.emailsPerMonth, repeat: MONTHLY_REPEAT, expires: "when-repeated" as const },
[ITEM_IDS.analyticsTimeoutSeconds]: { quantity: PLAN_LIMITS.growth.analyticsTimeoutSeconds, repeat: "never" as const, expires: "when-purchase-expires" as const },
[ITEM_IDS.analyticsEvents]: { quantity: PLAN_LIMITS.growth.analyticsEvents, repeat: MONTHLY_REPEAT, expires: "when-repeated" as const },
[ITEM_IDS.sessionReplays]: { quantity: PLAN_LIMITS.growth.sessionReplays, repeat: MONTHLY_REPEAT, expires: "when-repeated" as const },
[ITEM_IDS.onboardingCall]: { quantity: 1, repeat: "never" as const, expires: "when-purchase-expires" as const },
},
},
"extra-seats": {
productLineId: "plans",
displayName: "Extra Seats",
customerType: "team",
serverOnly: false,
stackable: true,
prices: {
monthly: {
USD: "29",
interval: MONTHLY_REPEAT,
serverOnly: false,
},
},
includedItems: {
[ITEM_IDS.seats]: { quantity: 1, repeat: "never" as const, expires: "when-purchase-expires" as const },
},
isAddOnTo: {
team: true,
growth: true,
},
},
},
items: {
[ITEM_IDS.seats]: { displayName: "Dashboard Admins", customerType: "team" as const },
[ITEM_IDS.authUsers]: { displayName: "Auth Users", customerType: "team" as const },
[ITEM_IDS.emailsPerMonth]: { displayName: "Emails per Month", customerType: "team" as const },
[ITEM_IDS.analyticsTimeoutSeconds]: { displayName: "Analytics Timeout (seconds)", customerType: "team" as const },
[ITEM_IDS.analyticsEvents]: { displayName: "Analytics Events", customerType: "team" as const },
[ITEM_IDS.sessionReplays]: { displayName: "Session Replays", customerType: "team" as const },
[ITEM_IDS.onboardingCall]: { displayName: "Onboarding Call", customerType: "team" as const },
},
},
apps: {
installed: typedFromEntries(typedEntries(ALL_APPS).map(([key, value]) => [key, { enabled: true }])),
},
}
});
await ensurePermissionDefinition(
globalPrismaClient,
internalPrisma,
{
id: "team_member",
scope: "team",
tenancy: internalTenancy,
data: {
description: "1",
contained_permission_ids: ["$read_members"],
}
}
);
const updatedInternalTenancy = await getSoleTenancyFromProjectBranch("internal", DEFAULT_BRANCH_ID);
await ensurePermissionDefinition(
globalPrismaClient,
internalPrisma,
{
id: "team_admin",
scope: "team",
tenancy: updatedInternalTenancy,
data: {
description: "2",
contained_permission_ids: ["$read_members", "$remove_members", "$update_team"],
}
}
);
const internalTeam = await internalPrisma.team.findUnique({
where: {
tenancyId_teamId: {
tenancyId: internalTenancy.id,
teamId: internalTeamId,
},
},
});
if (!internalTeam) {
await internalPrisma.team.create({
data: {
tenancyId: internalTenancy.id,
teamId: internalTeamId,
displayName: 'Internal Team',
mirroredProjectId: 'internal',
mirroredBranchId: DEFAULT_BRANCH_ID,
},
});
console.log('Internal team created');
}
// The team-create CRUD path auto-grants the free plan to every team in the
// internal project, but the internal team itself is written directly above
// (bypassing that code path), so it would otherwise end up with zero
// entitlements and trip the plan-limit enforcement. Grant it the Growth plan
// so Hexclave employees using the dashboard get full quotas. Idempotent —
// skipped if an active Growth subscription already exists.
//
// We create the subscription with raw Prisma (matching seed-dummy-data.ts)
// rather than grantProductToCustomer because bulldozer storage tables
// aren't initialized at this point in the seed yet. The Bulldozer init
// call right below this block ingresses the row into the ledger.
const growthProduct = updatedInternalTenancy.config.payments.products.growth;
if (growthProduct.customerType === 'team') {
const existingGrowthSub = await internalPrisma.subscription.findFirst({
where: {
tenancyId: internalTenancy.id,
customerId: internalTeamId,
customerType: CustomerType.TEAM,
productId: 'growth',
status: SubscriptionStatus.active,
},
});
if (!existingGrowthSub) {
const firstPriceId = Object.keys(growthProduct.prices)[0];
if (!firstPriceId) {
throw new Error("Internal seed invariant violated: the Growth product must have at least one price configured before seeding the internal team subscription.");
}
const now = new Date();
// Clone to ensure the stored JSON snapshot is independent of the config object
// (mirrors the pattern used in seed-dummy-data.ts).
const storedProduct = JSON.parse(JSON.stringify(growthProduct)) as Prisma.InputJsonValue;
// Mirror what a real Stripe checkout would produce, based on whether
// the internal project is running in test mode.
const creationSource = updatedInternalTenancy.config.payments.testMode
? PurchaseCreationSource.TEST_MODE
: PurchaseCreationSource.PURCHASE_PAGE;
await internalPrisma.subscription.create({
data: {
tenancyId: internalTenancy.id,
customerId: internalTeamId,
customerType: CustomerType.TEAM,
status: SubscriptionStatus.active,
productId: 'growth',
priceId: firstPriceId,
product: storedProduct,
quantity: 1,
currentPeriodStart: now,
currentPeriodEnd: new Date('2099-12-31T23:59:59Z'),
cancelAtPeriodEnd: false,
creationSource,
},
});
console.log('Granted Growth plan to internal team');
}
}
// Upsert the internal API key set before any flake-prone work (dummy-project
// seed, email/svix, clickhouse). The emulator CLI authenticates against the
// internal project using the pck stored here, so it must land before the rest
// of the seed even if something later fails.
const isLocalEmulator = process.env.NEXT_PUBLIC_STACK_IS_LOCAL_EMULATOR === 'true';
const rawPck = process.env.STACK_INTERNAL_PROJECT_PUBLISHABLE_CLIENT_KEY;
if (isLocalEmulator && !rawPck) {
// Emulator images build before a per-VM pck is available. Runtime boots set
// STACK_INTERNAL_PROJECT_PUBLISHABLE_CLIENT_KEY from the VM-generated
// random value and re-run the seed, which upserts the internal key set then.
console.log('Skipping internal API key set (no pck provided; emulator mode).');
} else {
const keySet = {
publishableClientKey: rawPck || throwErr('STACK_INTERNAL_PROJECT_PUBLISHABLE_CLIENT_KEY is not set'),
secretServerKey: isLocalEmulator
? (process.env.STACK_INTERNAL_PROJECT_SECRET_SERVER_KEY ?? null)
: (process.env.STACK_INTERNAL_PROJECT_SECRET_SERVER_KEY || throwErr('STACK_INTERNAL_PROJECT_SECRET_SERVER_KEY is not set')),
superSecretAdminKey: isLocalEmulator
? (process.env.STACK_SEED_INTERNAL_PROJECT_SUPER_SECRET_ADMIN_KEY ?? null)
: (process.env.STACK_SEED_INTERNAL_PROJECT_SUPER_SECRET_ADMIN_KEY || throwErr('STACK_SEED_INTERNAL_PROJECT_SUPER_SECRET_ADMIN_KEY is not set')),
};
await globalPrismaClient.apiKeySet.upsert({
where: { projectId_id: { projectId: 'internal', id: apiKeyId } },
update: {
...keySet,
},
create: {
id: apiKeyId,
projectId: 'internal',
description: "Internal API key set",
expiresAt: new Date('2099-12-31T23:59:59Z'),
...keySet,
}
});
console.log('Updated internal API key set');
}
const shouldSeedDummyProject = process.env.STACK_SEED_ENABLE_DUMMY_PROJECT === 'true';
if (shouldSeedDummyProject) {
await seedDummyProject({
projectId: DUMMY_PROJECT_ID,
ownerTeamId: internalTeamId,
oauthProviderIds,
});
}
const developmentEnvironmentProjectData = {
display_name: 'Development Environment Project',
description: 'Seeded project for debugging development-environment dashboard behavior.',
is_production_mode: false,
is_development_environment: true,
owner_team_id: internalTeamId,
config: {
allow_localhost: true,
sign_up_enabled: true,
credential_enabled: true,
magic_link_enabled: true,
passkey_enabled: true,
client_team_creation_enabled: true,
client_user_deletion_enabled: true,
allow_user_api_keys: true,
allow_team_api_keys: true,
create_team_on_sign_up: false,
email_theme: DEFAULT_EMAIL_THEME_ID,
email_config: {
type: 'shared',
},
oauth_providers: oauthProviderIds.map((id) => ({
id: id as any,
type: 'shared',
})),
domains: [],
},
} satisfies AdminUserProjectsCrud["Admin"]["Create"];
if (await getProject(DEVELOPMENT_ENVIRONMENT_PROJECT_ID)) {
await createOrUpdateProjectWithLegacyConfig({
type: 'update',
projectId: DEVELOPMENT_ENVIRONMENT_PROJECT_ID,
branchId: DEFAULT_BRANCH_ID,
data: developmentEnvironmentProjectData,
});
} else {
await createOrUpdateProjectWithLegacyConfig({
type: 'create',
projectId: DEVELOPMENT_ENVIRONMENT_PROJECT_ID,
data: developmentEnvironmentProjectData,
});
}
// Create optional default admin user if credentials are provided.
// This user will be able to login to the dashboard with both email/password and magic link.
if ((adminEmail && adminPassword) || adminGithubId) {
const oldAdminUser = await internalPrisma.projectUser.findFirst({
where: {
mirroredProjectId: 'internal',
mirroredBranchId: DEFAULT_BRANCH_ID,
projectUserId: defaultUserId
}
});
if (oldAdminUser) {
console.log(`Admin user already exists, skipping creation`);
} else {
const newUser = await internalPrisma.projectUser.create({
data: {
displayName: 'Administrator (created by seed script)',
projectUserId: defaultUserId,
tenancyId: internalTenancy.id,
mirroredProjectId: 'internal',
mirroredBranchId: DEFAULT_BRANCH_ID,
signedUpAt: new Date(),
signUpRiskScoreBot: 0,
signUpRiskScoreFreeTrialAbuse: 0,
}
});
// Note: TeamMember creation is handled by the upsert below (after this if/else block)
// to ensure idempotency when adminInternalAccess changes between runs
if (adminEmail && adminPassword) {
await usersCrudHandlers.adminUpdate({
tenancy: internalTenancy,
user_id: defaultUserId,
data: {
password: adminPassword,
primary_email: adminEmail,
primary_email_auth_enabled: true,
},
});
console.log(`Added admin user with email ${adminEmail}`);
}
if (adminGithubId) {
const githubAccount = await internalPrisma.projectUserOAuthAccount.findFirst({
where: {
tenancyId: internalTenancy.id,
configOAuthProviderId: 'github',
providerAccountId: adminGithubId,
}
});
if (githubAccount) {
console.log(`GitHub account already exists, skipping creation`);
} else {
await internalPrisma.projectUserOAuthAccount.create({
data: {
tenancyId: internalTenancy.id,
projectUserId: newUser.projectUserId,
configOAuthProviderId: 'github',
providerAccountId: adminGithubId
}
});
await internalPrisma.authMethod.create({
data: {
tenancyId: internalTenancy.id,
projectUserId: newUser.projectUserId,
oauthAuthMethod: {
create: {
projectUserId: newUser.projectUserId,
configOAuthProviderId: 'github',
providerAccountId: adminGithubId,
}
}
}
});
console.log(`Added admin user with GitHub ID ${adminGithubId}`);
}
}
}
// Create or ensure TeamMember exists before granting permissions.
// Using upsert here (instead of create inside the else block above) ensures
// idempotency when adminInternalAccess changes between seed runs.
if (adminInternalAccess) {
await internalPrisma.teamMember.upsert({
where: {
tenancyId_projectUserId_teamId: {
tenancyId: internalTenancy.id,
projectUserId: defaultUserId,
teamId: internalTeamId,
},
},
create: {
tenancyId: internalTenancy.id,
teamId: internalTeamId,
projectUserId: defaultUserId,
},
update: {},
});
await grantTeamPermission(internalPrisma, {
tenancy: internalTenancy,
teamId: internalTeamId,
userId: defaultUserId,
permissionId: "team_admin",
});
}
}
if (localEmulatorEnabled) {
const emulatorTeam = await internalPrisma.team.findUnique({
where: {
tenancyId_teamId: {
tenancyId: internalTenancy.id,
teamId: LOCAL_EMULATOR_OWNER_TEAM_ID,
},
},
});
if (!emulatorTeam) {
await internalPrisma.team.create({
data: {
tenancyId: internalTenancy.id,
teamId: LOCAL_EMULATOR_OWNER_TEAM_ID,
displayName: 'Emulator Team',
mirroredProjectId: "internal",
mirroredBranchId: DEFAULT_BRANCH_ID,
},
});
console.log('Created emulator team');
}
const existingUser = await internalPrisma.projectUser.findFirst({
where: {
mirroredProjectId: 'internal',
mirroredBranchId: DEFAULT_BRANCH_ID,
projectUserId: LOCAL_EMULATOR_ADMIN_USER_ID,
}
});
if (existingUser) {
console.log('Emulator user already exists, skipping creation');
} else {
await internalPrisma.projectUser.create({
data: {
displayName: 'Local Emulator User',
projectUserId: LOCAL_EMULATOR_ADMIN_USER_ID,
tenancyId: internalTenancy.id,
mirroredProjectId: 'internal',
mirroredBranchId: DEFAULT_BRANCH_ID,
signedUpAt: new Date(),
signUpRiskScoreBot: 0,
signUpRiskScoreFreeTrialAbuse: 0,
}
});
console.log('Created emulator user');
}
await internalPrisma.teamMember.upsert({
where: {
tenancyId_projectUserId_teamId: {
tenancyId: internalTenancy.id,
projectUserId: LOCAL_EMULATOR_ADMIN_USER_ID,
teamId: LOCAL_EMULATOR_OWNER_TEAM_ID,
},
},
create: {
tenancyId: internalTenancy.id,
teamId: LOCAL_EMULATOR_OWNER_TEAM_ID,
projectUserId: LOCAL_EMULATOR_ADMIN_USER_ID,
},
update: {},
});
await usersCrudHandlers.adminUpdate({
tenancy: internalTenancy,
user_id: LOCAL_EMULATOR_ADMIN_USER_ID,
data: {
password: LOCAL_EMULATOR_ADMIN_PASSWORD,
primary_email: LOCAL_EMULATOR_ADMIN_EMAIL,
primary_email_auth_enabled: true,
},
});
const userTeamMembership = await internalPrisma.teamMember.findUnique({
where: {
tenancyId_projectUserId_teamId: {
tenancyId: internalTenancy.id,
projectUserId: LOCAL_EMULATOR_ADMIN_USER_ID,
teamId: LOCAL_EMULATOR_OWNER_TEAM_ID,
},
},
select: {
projectUserId: true,
},
});
if (!userTeamMembership) {
throw new Error('Local emulator user must be a member of the local emulator owner team');
} else {
console.log('Ensured emulator user is a member of emulator team');
}
await grantTeamPermission(internalPrisma, {
tenancy: internalTenancy,
teamId: LOCAL_EMULATOR_OWNER_TEAM_ID,
userId: LOCAL_EMULATOR_ADMIN_USER_ID,
permissionId: "team_admin",
});
}
console.log('Seeding complete!');
}