mirror of
https://github.com/stack-auth/stack.git
synced 2026-06-30 21:01:54 +08:00
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
## Summary
Completes the env-var side of the Hexclave rebrand: every
`STACK_*`-prefixed variable (including `NEXT_PUBLIC_STACK_*` and
`VITE_STACK_*`) is renamed to `HEXCLAVE_*` across all checked-in `.env`,
`.env.development`, and `.env.example` files (30 files, ~135 keys).
Legacy `STACK_*` names keep working everywhere via dual-read, so
**existing deployments, `.env.local` files, and self-hosted setups need
no immediate migration**.
## How legacy names keep working
- **Server code** already resolves `HEXCLAVE_*` first with `STACK_*`
fallback via `getEnvVariable`. Direct `process.env.STACK_X` readers fed
by the renamed files (prisma seed, e2e tests/helpers, internal-tool
scripts, examples, `prisma.config.ts`) now read `HEXCLAVE_X || STACK_X`.
- **Client code** (Next.js build-time inlining) uses literal dual-read
expressions; the dashboard's `_inlineEnvVars` already had them.
- **Docker/self-hosting**: `docker/server/entrypoint.sh` (shared by the
server and local-emulator images) gets a generic two-way
`HEXCLAVE_`↔`STACK_` env mirror — runs at startup and again before
sentinel replacement — replacing the previous URL-trio-only mirror.
Operators can use either prefix.
## The empty-placeholder trap (`||` vs `??`)
The checked-in templates define empty placeholders (`HEXCLAVE_X=#
comment` parses to `""` via dotenv). With `?? `-based fallbacks, that
empty string would silently shadow a real value under the legacy name —
including legacy vars set in Vercel/CI env at build time, since the
tracked `.env` is present during builds. All fallback chains therefore
treat empty-as-unset (`||`):
- `getEnvVariable` and `getProcessEnv` in `packages/shared`
- the dashboard/docs/example literal dual-reads
- the generated SDK env getters (via
`packages/template/scripts/generate-env.ts`; the generated
`src/generated/env.ts` files are gitignored and regenerate at build)
## Other notable changes
- Tests that override env now set the canonical `HEXCLAVE_*` name (it
wins over `STACK_*`): e2e `cross-domain-auth`, backend
`internal-feedback-emails` in-source test.
- e2e `helpers.ts` port-prefix expansion loop also matches the
`HEXCLAVE_` prefixes.
- `docker/local-emulator/generate-env-development.mjs` reads source keys
canonically (legacy fallback) and emits canonical keys; regenerated
output matches.
- `rotate-secrets.sh` falls back to
`HEXCLAVE_DATABASE_CONNECTION_STRING`.
- Docs code snippets (`docs/code-examples`) renamed outright to
canonical names, consistent with #1571.
- OAuth callback `console.warn` in `packages/template/src/lib/auth.ts`
now says Hexclave.
## Migration note for the team
Local `.env.local` files with legacy `STACK_*` overrides keep working
**unless** the override targets a var that `.env.development` now sets
to a real (non-empty) `HEXCLAVE_*` value — the canonical name wins over
file precedence. Rename those keys in your `.env.local` once.
## Verification
- `typecheck` + `lint` pass on every touched package (shared, backend,
dashboard, e2e, internal-tool, cli, docs, template). Pre-existing
failures on dev (`admin-app-impl.ts` typecheck, dashboard metrics-page
errors) are unchanged (identical error counts with/without this change).
- `getEnvVariable`/`getProcessEnv` fallback semantics smoke-tested
directly (empty-HEXCLAVE → legacy fallback, HEXCLAVE wins when set,
defaults intact).
- `internal-feedback-emails` in-source vitest passes; emulator env
generator `--check` passes; `bash -n` on touched shell scripts.
- Two independent review agents audited the diff for correctness bugs
and coverage gaps; all confirmed findings are fixed in the third commit.
<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Renamed all `STACK_*` env vars (including
`NEXT_PUBLIC_STACK_*`/`VITE_STACK_*`) to `HEXCLAVE_*` across env
templates and code, with dual‑read that treats empty as unset, detects
conflicts, ignores post‑build sentinels, and falls back to legacy names.
All GitHub Actions now use `HEXCLAVE_*`; local‑emulator e2e is fixed by
setting `NEXT_PUBLIC_HEXCLAVE_IS_LOCAL_EMULATOR` in CI.
- **Refactors**
- Added conflict‑aware dual‑read helpers (prefer `HEXCLAVE_*`,
empty‑as‑unset, ignore post‑build sentinels, preserve empty passthrough)
and used them across `packages/shared` (resolver + tests),
`apps/dashboard` inline/public envs (with tests), `apps/backend` Prisma
config/seed and vitest (accept both prefixes), `packages/cli`
(API/Dashboard URLs, project ID, `HEXCLAVE_EMULATOR_HOME`; tests),
Docker (`entrypoint.sh` mirroring + `rotate-secrets.sh` DB URL),
docs/components (`docs/src/lib/env.ts`), and examples; hosted/Vite apps
now error if both spellings differ.
- Port‑prefix expansion includes `HEXCLAVE_*`; backend tests use a new
helper to resolve DB connection strings; Prisma prefers
`HEXCLAVE_DATABASE_CONNECTION_STRING` with legacy fallback.
- Generated SDK env getters use plain `HEXCLAVE_*` || `STACK_*` (no
conflict throw); dashboard inline resolver preserves empty/sentinel
passthrough to avoid build failures; docs/examples include dual‑read
utilities.
- Tests now stub canonical `HEXCLAVE_*` flags (e.g., plan limits, bot
challenge, OAuth tokens, hosted handler) to avoid shadowing/conflict
with committed defaults.
- **Migration**
- No immediate action; legacy `STACK_*` names still work.
- If both names are set with different values, builds/scripts error. Set
only `HEXCLAVE_*` or make both equal.
- SDK consumers won’t see conflict throws; update env names to
`HEXCLAVE_*` over time.
<sup>Written for commit 7539fb9fbf.
Summary will update on new commits.</sup>
<a
href="https://cubic.dev/pr/hexclave/hexclave/pull/1588?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
* **Chores**
* Migrated environment variable names from the legacy `STACK_*` prefix
to the new `HEXCLAVE_*` prefix across backend, dashboard, tooling,
Docker, and examples.
* Updated environment/config resolution to prefer `HEXCLAVE_*`, treat
empty strings as unset, and detect conflicts when both `STACK_*` and
`HEXCLAVE_*` are set to different values.
* Updated local emulator, server startup, and env-generation workflows
to use the new names (with legacy fallback where applicable).
* **Documentation**
* Updated docs and code examples to reference `HEXCLAVE_*` variables.
* **Tests**
* Refreshed unit and e2e coverage to validate dual-read behavior,
conflict detection, and empty-value handling.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
290 lines
12 KiB
TypeScript
290 lines
12 KiB
TypeScript
import { globalVar } from "./globals";
|
|
import { Json } from "./json";
|
|
import { pick } from "./objects";
|
|
import { nicify } from "./strings";
|
|
|
|
|
|
export function throwErr(errorMessage: string, extraData?: any): never;
|
|
export function throwErr(error: Error): never;
|
|
export function throwErr(...args: StatusErrorConstructorParameters): never;
|
|
export function throwErr(...args: any[]): never {
|
|
if (typeof args[0] === "string") {
|
|
throw new HexclaveAssertionError(args[0], args[1]);
|
|
} else if (args[0] instanceof Error) {
|
|
throw args[0];
|
|
} else {
|
|
// @ts-expect-error
|
|
throw new StatusError(...args);
|
|
}
|
|
}
|
|
|
|
function removeStacktraceNameLine(stack: string): string {
|
|
// some browsers (eg. Chrome) prepend the stack with an extra line with the error name
|
|
const addsNameLine = new Error().stack?.startsWith("Error\n");
|
|
return stack.split("\n").slice(addsNameLine ? 1 : 0).join("\n");
|
|
}
|
|
|
|
|
|
/**
|
|
* Concatenates the (original) stacktraces of the given errors onto the first.
|
|
*
|
|
* Note: Very often, the concatStacktracesIfRejected function in promises.tsx is an easier way to use this function.
|
|
*
|
|
* Useful when you invoke an async function to receive a promise without awaiting it immediately. Browsers are smart
|
|
* enough to keep track of the call stack in async function calls when you invoke `.then` within the same async tick,
|
|
* but if you don't, the stacktrace will be lost.
|
|
*
|
|
* Here's an example of the unwanted behavior:
|
|
*
|
|
* ```tsx
|
|
* async function log() {
|
|
* await wait(0); // put the task on the event loop
|
|
* console.log(new Error().stack);
|
|
* }
|
|
*
|
|
* async function main() {
|
|
* await log(); // good; prints both "log" and "main" on the stacktrace
|
|
* log(); // bad; prints only "log" on the stacktrace
|
|
* }
|
|
* ```
|
|
*/
|
|
export function concatStacktraces(first: Error, ...errors: Error[]): void {
|
|
// some browsers (eg. Firefox) add an extra empty line at the end
|
|
const addsEmptyLineAtEnd = first.stack?.endsWith("\n");
|
|
|
|
|
|
// Add a reference to this function itself so that we know that stacktraces were concatenated
|
|
// If you are coming here from a stacktrace, please know that the two parts before and after this line are different
|
|
// stacktraces that were concatenated with concatStacktraces
|
|
const separator = removeStacktraceNameLine(new Error().stack ?? "").split("\n")[0];
|
|
|
|
|
|
for (const error of errors) {
|
|
const toAppend = removeStacktraceNameLine(error.stack ?? "");
|
|
first.stack += (addsEmptyLineAtEnd ? "" : "\n") + separator + "\n" + toAppend;
|
|
}
|
|
}
|
|
|
|
|
|
export class HexclaveAssertionError extends Error {
|
|
constructor(message: string, public readonly extraData?: Record<string, any> & ErrorOptions) {
|
|
const disclaimer = `\n\nThis is likely an error in Hexclave. Please make sure you are running the newest version and report it.`;
|
|
super(`${message}${message.endsWith(disclaimer) ? "" : disclaimer}`, pick(extraData ?? {}, ["cause"]));
|
|
|
|
Object.defineProperty(this, "customCaptureExtraArgs", {
|
|
get() {
|
|
return [this.extraData];
|
|
},
|
|
enumerable: false,
|
|
});
|
|
|
|
// Use literal dot-form (guarded with `typeof process`) so Next.js / webpack
|
|
// DefinePlugin can inline the value at build time. See getProcessEnv in ./env.
|
|
const hexclaveDebuggerValue = typeof process !== "undefined" ? process.env.NEXT_PUBLIC_HEXCLAVE_DEBUGGER_ON_ASSERTION_ERROR : undefined;
|
|
const stackDebuggerValue = typeof process !== "undefined" ? process.env.NEXT_PUBLIC_STACK_DEBUGGER_ON_ASSERTION_ERROR : undefined;
|
|
if (hexclaveDebuggerValue && stackDebuggerValue && hexclaveDebuggerValue !== stackDebuggerValue) {
|
|
throw new Error("Environment variables NEXT_PUBLIC_HEXCLAVE_DEBUGGER_ON_ASSERTION_ERROR and NEXT_PUBLIC_STACK_DEBUGGER_ON_ASSERTION_ERROR are both set to different values. Remove one of them or set them to the same value.");
|
|
}
|
|
if ((hexclaveDebuggerValue || stackDebuggerValue) === "true") {
|
|
debugger;
|
|
}
|
|
}
|
|
}
|
|
HexclaveAssertionError.prototype.name = "HexclaveAssertionError";
|
|
|
|
|
|
export function errorToNiceString(error: unknown): string {
|
|
if (!(error instanceof Error)) return `${typeof error}<${nicify(error)}>`;
|
|
return nicify(error, { maxDepth: 8 });
|
|
}
|
|
|
|
|
|
export type CaptureLevel = "error" | "warning";
|
|
|
|
type ErrorSink = (location: string, error: unknown, level: CaptureLevel, ...extraArgs: unknown[]) => void;
|
|
|
|
const errorSinks = new Set<ErrorSink>();
|
|
export function registerErrorSink(sink: ErrorSink): void {
|
|
if (errorSinks.has(sink)) {
|
|
return;
|
|
}
|
|
errorSinks.add(sink);
|
|
}
|
|
registerErrorSink((location, error, level, ...extraArgs) => {
|
|
const logger = level === "warning" ? console.warn : console.error;
|
|
const colorCode = level === "warning" ? "\x1b[43m" : "\x1b[41m";
|
|
const label = level === "warning" ? "warning" : "error";
|
|
logger(
|
|
`${colorCode}Captured ${label} in ${location}:`,
|
|
// HACK: Log a nicified version of the error to get around buggy Next.js pretty-printing
|
|
// https://www.reddit.com/r/nextjs/comments/1gkxdqe/comment/m19kxgn/?utm_source=share&utm_medium=web3x&utm_name=web3xcss&utm_term=1&utm_content=share_button
|
|
errorToNiceString(error),
|
|
...extraArgs,
|
|
"\x1b[0m",
|
|
);
|
|
});
|
|
registerErrorSink((location, error, level, ...extraArgs) => {
|
|
globalVar.hexclaveCapturedErrors = globalVar.hexclaveCapturedErrors ?? [];
|
|
globalVar.hexclaveCapturedErrors.push({ location, error, level, extraArgs });
|
|
});
|
|
|
|
function dispatchToSinks(location: string, error: unknown, level: CaptureLevel): void {
|
|
for (const sink of errorSinks) {
|
|
sink(
|
|
location,
|
|
error,
|
|
level,
|
|
...error && (typeof error === 'object' || typeof error === 'function') && "customCaptureExtraArgs" in error && Array.isArray(error.customCaptureExtraArgs) ? (error.customCaptureExtraArgs as any[]) : [],
|
|
);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Captures an error and sends it to the error sinks (most notably, Sentry). Errors caught with captureError are
|
|
* supposed to be seen by an engineer, so they should be actionable and important.
|
|
*
|
|
* The location string is a machine-readable ID, and should hence not contain spaces or anything like that. Good
|
|
* examples are: "api-route-handler", "renderPart()", etc.
|
|
*
|
|
* Errors that bubble up to the top of runAsynchronously or a route handler are already captured with captureError.
|
|
*/
|
|
export function captureError(location: string, error: unknown): void {
|
|
dispatchToSinks(location, error, "error");
|
|
}
|
|
|
|
/**
|
|
* Like captureError, but logs at warning level. Use for issues that an engineer should know about but that aren't
|
|
* severe enough to be treated as an error (e.g. recoverable failures in background tasks).
|
|
*/
|
|
export function captureWarning(location: string, error: unknown): void {
|
|
dispatchToSinks(location, error, "warning");
|
|
}
|
|
|
|
|
|
type Status = {
|
|
statusCode: number,
|
|
message: string,
|
|
};
|
|
|
|
type StatusErrorConstructorParameters =
|
|
| [
|
|
status: Status,
|
|
message?: string
|
|
]
|
|
| [
|
|
statusCode: number | Status,
|
|
message: string,
|
|
];
|
|
|
|
export class StatusError extends Error {
|
|
private readonly __stackStatusErrorBrand = "stack-status-error-brand-sentinel" as const;
|
|
public name = "StatusError";
|
|
public readonly statusCode: number;
|
|
|
|
public static BadRequest = { statusCode: 400, message: "Bad Request" };
|
|
public static Unauthorized = { statusCode: 401, message: "Unauthorized" };
|
|
public static PaymentRequired = { statusCode: 402, message: "Payment Required" };
|
|
public static Forbidden = { statusCode: 403, message: "Forbidden" };
|
|
public static NotFound = { statusCode: 404, message: "Not Found" };
|
|
public static MethodNotAllowed = { statusCode: 405, message: "Method Not Allowed" };
|
|
public static NotAcceptable = { statusCode: 406, message: "Not Acceptable" };
|
|
public static ProxyAuthenticationRequired = { statusCode: 407, message: "Proxy Authentication Required" };
|
|
public static RequestTimeout = { statusCode: 408, message: "Request Timeout" };
|
|
public static Conflict = { statusCode: 409, message: "Conflict" };
|
|
public static Gone = { statusCode: 410, message: "Gone" };
|
|
public static LengthRequired = { statusCode: 411, message: "Length Required" };
|
|
public static PreconditionFailed = { statusCode: 412, message: "Precondition Failed" };
|
|
public static PayloadTooLarge = { statusCode: 413, message: "Payload Too Large" };
|
|
public static URITooLong = { statusCode: 414, message: "URI Too Long" };
|
|
public static UnsupportedMediaType = { statusCode: 415, message: "Unsupported Media Type" };
|
|
public static RangeNotSatisfiable = { statusCode: 416, message: "Range Not Satisfiable" };
|
|
public static ExpectationFailed = { statusCode: 417, message: "Expectation Failed" };
|
|
public static ImATeapot = { statusCode: 418, message: "I'm a teapot" };
|
|
public static MisdirectedRequest = { statusCode: 421, message: "Misdirected Request" };
|
|
public static UnprocessableEntity = { statusCode: 422, message: "Unprocessable Entity" };
|
|
public static Locked = { statusCode: 423, message: "Locked" };
|
|
public static FailedDependency = { statusCode: 424, message: "Failed Dependency" };
|
|
public static TooEarly = { statusCode: 425, message: "Too Early" };
|
|
public static UpgradeRequired = { statusCode: 426, message: "Upgrade Required" };
|
|
public static PreconditionRequired = { statusCode: 428, message: "Precondition Required" };
|
|
public static TooManyRequests = { statusCode: 429, message: "Too Many Requests" };
|
|
public static RequestHeaderFieldsTooLarge = { statusCode: 431, message: "Request Header Fields Too Large" };
|
|
public static UnavailableForLegalReasons = { statusCode: 451, message: "Unavailable For Legal Reasons" };
|
|
|
|
public static InternalServerError = { statusCode: 500, message: "Internal Server Error" };
|
|
public static NotImplemented = { statusCode: 501, message: "Not Implemented" };
|
|
public static BadGateway = { statusCode: 502, message: "Bad Gateway" };
|
|
public static ServiceUnavailable = { statusCode: 503, message: "Service Unavailable" };
|
|
public static GatewayTimeout = { statusCode: 504, message: "Gateway Timeout" };
|
|
public static HTTPVersionNotSupported = { statusCode: 505, message: "HTTP Version Not Supported" };
|
|
public static VariantAlsoNegotiates = { statusCode: 506, message: "Variant Also Negotiates" };
|
|
public static InsufficientStorage = { statusCode: 507, message: "Insufficient Storage" };
|
|
public static LoopDetected = { statusCode: 508, message: "Loop Detected" };
|
|
public static NotExtended = { statusCode: 510, message: "Not Extended" };
|
|
public static NetworkAuthenticationRequired = { statusCode: 511, message: "Network Authentication Required" };
|
|
|
|
|
|
constructor(...args: StatusErrorConstructorParameters);
|
|
constructor(
|
|
status: number | Status,
|
|
message?: string,
|
|
) {
|
|
if (typeof status === "object") {
|
|
message ??= status.message;
|
|
status = status.statusCode;
|
|
}
|
|
super(message);
|
|
this.statusCode = status;
|
|
if (!message) {
|
|
throw new HexclaveAssertionError("StatusError always requires a message unless a Status object is passed", { cause: this });
|
|
}
|
|
}
|
|
|
|
public static isStatusError(error: unknown): error is StatusError {
|
|
// like instanceof, but also works for errors thrown in other realms or by different versions of the same package
|
|
return typeof error === "object" && error !== null && "__stackStatusErrorBrand" in error && error.__stackStatusErrorBrand === "stack-status-error-brand-sentinel";
|
|
}
|
|
|
|
public isClientError() {
|
|
return this.statusCode >= 400 && this.statusCode < 500;
|
|
}
|
|
|
|
public isServerError() {
|
|
return !this.isClientError();
|
|
}
|
|
|
|
public getStatusCode(): number {
|
|
return this.statusCode;
|
|
}
|
|
|
|
public getBody(): Uint8Array {
|
|
return new TextEncoder().encode(this.message);
|
|
}
|
|
|
|
public getHeaders(): Record<string, string[]> {
|
|
return {
|
|
"Content-Type": ["text/plain; charset=utf-8"],
|
|
};
|
|
}
|
|
|
|
public toDescriptiveJson(): Json {
|
|
return {
|
|
status_code: this.getStatusCode(),
|
|
message: this.message,
|
|
headers: this.getHeaders(),
|
|
};
|
|
}
|
|
|
|
/**
|
|
* @deprecated this is not a good way to make status errors human-readable, use toDescriptiveJson instead
|
|
*/
|
|
public toHttpJson(): Json {
|
|
return {
|
|
status_code: this.statusCode,
|
|
body: this.message,
|
|
headers: this.getHeaders(),
|
|
};
|
|
}
|
|
}
|
|
StatusError.prototype.name = "StatusError";
|