@clubedge/create-clubedge-app 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +49 -13
  3. package/dist/cli/args.js +20 -0
  4. package/dist/cli/ui.js +6 -0
  5. package/dist/core/customize.js +167 -1
  6. package/dist/core/manifest.js +130 -3
  7. package/dist/core/plan.js +203 -3
  8. package/dist/index.js +91 -7
  9. package/dist/utils/fs.js +3 -0
  10. package/package.json +5 -4
  11. package/template/.dockerignore +3 -0
  12. package/template/.env.example +19 -6
  13. package/template/.github/workflows/ci.yml +34 -4
  14. package/template/.prettierignore +1 -0
  15. package/template/AGENTS.md +11 -3
  16. package/template/CONTRIBUTING.md +2 -2
  17. package/template/README.md +73 -54
  18. package/template/SETUP.md +112 -40
  19. package/template/_gitignore +6 -0
  20. package/template/apps/start/.env.example +40 -0
  21. package/template/apps/start/AGENTS.md +11 -0
  22. package/template/apps/start/Dockerfile +38 -0
  23. package/template/apps/start/components.json +21 -0
  24. package/template/apps/start/package.json +43 -0
  25. package/template/apps/start/public/.well-known/logo.svg +1 -0
  26. package/template/apps/start/public/favicon.ico +0 -0
  27. package/template/apps/start/src/components/auth/auth-form-controls.tsx +108 -0
  28. package/template/apps/start/src/components/branding/clubedge-mark.tsx +24 -0
  29. package/template/apps/start/src/components/dashboard/account-button.tsx +33 -0
  30. package/template/apps/start/src/components/dashboard/app-sidebar.tsx +90 -0
  31. package/template/apps/start/src/components/dashboard/variants/account-button.none.tsx +9 -0
  32. package/template/apps/start/src/components/landing/copy-command.tsx +46 -0
  33. package/template/apps/start/src/components/theme/theme-provider.tsx +41 -0
  34. package/template/apps/start/src/components/theme/theme-toggle.tsx +21 -0
  35. package/template/apps/start/src/config/site.json +11 -0
  36. package/template/apps/start/src/config/site.ts +20 -0
  37. package/template/apps/start/src/env/auth.test.ts +26 -0
  38. package/template/apps/start/src/env/auth.ts +46 -0
  39. package/template/apps/start/src/env/server.test.ts +32 -0
  40. package/template/apps/start/src/env/server.ts +43 -0
  41. package/template/apps/start/src/lib/login-url.test.ts +16 -0
  42. package/template/apps/start/src/lib/login-url.ts +16 -0
  43. package/template/apps/start/src/router.tsx +27 -0
  44. package/template/apps/start/src/routes/__root.tsx +59 -0
  45. package/template/apps/start/src/routes/api/health.ts +15 -0
  46. package/template/apps/start/src/routes/auth/callback.ts +10 -0
  47. package/template/apps/start/src/routes/auth/sign-in.ts +11 -0
  48. package/template/apps/start/src/routes/auth/sign-out.ts +11 -0
  49. package/template/apps/start/src/routes/auth/sign-up.ts +11 -0
  50. package/template/apps/start/src/routes/dashboard.tsx +361 -0
  51. package/template/apps/start/src/routes/index.tsx +237 -0
  52. package/template/apps/start/src/routes/login.tsx +164 -0
  53. package/template/apps/start/src/server/auth-forms.test.ts +169 -0
  54. package/template/apps/start/src/server/auth-forms.ts +118 -0
  55. package/template/apps/start/src/server/auth.functions.ts +27 -0
  56. package/template/apps/start/src/server/auth.ts +51 -0
  57. package/template/apps/start/src/server/cache.test.ts +65 -0
  58. package/template/apps/start/src/server/cache.ts +58 -0
  59. package/template/apps/start/src/server/cookies.test.ts +41 -0
  60. package/template/apps/start/src/server/cookies.ts +31 -0
  61. package/template/apps/start/src/server/db.ts +16 -0
  62. package/template/apps/start/src/server/storage.ts +42 -0
  63. package/template/apps/start/src/server/users.ts +17 -0
  64. package/template/apps/start/src/server/variants/auth.better-auth.ts +57 -0
  65. package/template/apps/start/src/server/variants/auth.functions.none.ts +9 -0
  66. package/template/apps/start/src/server/variants/auth.none.ts +28 -0
  67. package/template/apps/start/src/server/variants/cache.memory.ts +26 -0
  68. package/template/apps/start/src/server/variants/storage.supabase.ts +35 -0
  69. package/template/apps/start/src/start.ts +40 -0
  70. package/template/apps/start/src/styles.css +2 -0
  71. package/template/apps/start/tsconfig.json +19 -0
  72. package/template/apps/start/tsr.config.json +7 -0
  73. package/template/apps/start/vite.config.ts +27 -0
  74. package/template/apps/web/next.config.ts +9 -9
  75. package/template/apps/web/package.json +7 -2
  76. package/template/{scripts → apps/web/scripts}/start-standalone.mjs +1 -2
  77. package/template/apps/web/src/app/dashboard/_components/account-button.tsx +1 -1
  78. package/template/apps/web/src/app/dashboard/_components/app-sidebar.tsx +1 -1
  79. package/template/apps/web/src/app/dashboard/_components/variants/account-button.none.tsx +9 -0
  80. package/template/apps/web/src/app/dashboard/page.tsx +18 -8
  81. package/template/apps/web/src/app/login/page.tsx +5 -4
  82. package/template/apps/web/src/app/page.tsx +7 -3
  83. package/template/apps/web/src/env/auth.ts +48 -0
  84. package/template/apps/web/src/env/client.ts +1 -8
  85. package/template/apps/web/src/env/server.test.ts +27 -4
  86. package/template/apps/web/src/env/server.ts +19 -29
  87. package/template/apps/web/src/proxy.ts +5 -8
  88. package/template/apps/web/src/server/auth.ts +14 -26
  89. package/template/apps/web/src/server/cache.ts +36 -16
  90. package/template/apps/web/src/server/cookies.ts +18 -0
  91. package/template/apps/web/src/server/storage.ts +22 -19
  92. package/template/apps/web/src/server/variants/auth.better-auth.ts +63 -0
  93. package/template/apps/web/src/server/variants/auth.none.ts +26 -0
  94. package/template/apps/web/src/server/variants/cache.memory.ts +26 -0
  95. package/template/apps/web/src/server/variants/storage.supabase.ts +35 -0
  96. package/template/apps/web/src/variants/proxy.better-auth.ts +46 -0
  97. package/template/clubedge.template.json +173 -2
  98. package/template/e2e/app.ts +12 -0
  99. package/template/e2e/auth-flow.spec.ts +29 -0
  100. package/template/{apps/web/e2e → e2e}/auth.spec.ts +2 -12
  101. package/template/e2e/home.spec.ts +24 -0
  102. package/template/eslint.config.mjs +6 -1
  103. package/template/package.json +6 -6
  104. package/template/packages/auth/package.json +3 -6
  105. package/template/packages/auth-better-auth/drizzle/0000_initial.sql +50 -0
  106. package/template/packages/auth-better-auth/drizzle/meta/0000_snapshot.json +320 -0
  107. package/template/packages/auth-better-auth/drizzle/meta/_journal.json +13 -0
  108. package/template/packages/auth-better-auth/drizzle.config.ts +12 -0
  109. package/template/packages/auth-better-auth/package.json +31 -0
  110. package/template/packages/auth-better-auth/scripts/migrate.ts +14 -0
  111. package/template/packages/auth-better-auth/src/index.test.ts +118 -0
  112. package/template/packages/auth-better-auth/src/index.ts +135 -0
  113. package/template/packages/auth-better-auth/src/schema.ts +74 -0
  114. package/template/packages/auth-better-auth/tsconfig.json +4 -0
  115. package/template/packages/auth-supabase/package.json +24 -0
  116. package/template/packages/{auth/src/supabase.test.ts → auth-supabase/src/index.test.ts} +2 -2
  117. package/template/packages/{auth/src/supabase.ts → auth-supabase/src/index.ts} +1 -1
  118. package/template/packages/auth-supabase/tsconfig.json +4 -0
  119. package/template/packages/cache/package.json +1 -4
  120. package/template/packages/cache/src/index.ts +3 -13
  121. package/template/packages/cache/src/memory-cache.test.ts +40 -0
  122. package/template/packages/cache/src/memory-cache.ts +37 -0
  123. package/template/packages/cache-redis/package.json +22 -0
  124. package/template/packages/{cache → cache-redis}/src/index.test.ts +6 -15
  125. package/template/packages/{cache/src/redis.ts → cache-redis/src/index.ts} +2 -6
  126. package/template/packages/cache-redis/tsconfig.json +4 -0
  127. package/template/packages/core/package.json +1 -1
  128. package/template/packages/db/package.json +3 -2
  129. package/template/packages/storage/package.json +2 -9
  130. package/template/packages/storage-s3/package.json +23 -0
  131. package/template/packages/{storage/src/s3.test.ts → storage-s3/src/index.test.ts} +1 -1
  132. package/template/packages/{storage/src/s3.ts → storage-s3/src/index.ts} +1 -1
  133. package/template/packages/storage-s3/tsconfig.json +4 -0
  134. package/template/packages/storage-supabase/package.json +22 -0
  135. package/template/packages/{storage/src/supabase.ts → storage-supabase/src/index.ts} +1 -1
  136. package/template/packages/storage-supabase/tsconfig.json +4 -0
  137. package/template/packages/ui/package.json +1 -1
  138. package/template/playwright.config.ts +6 -2
  139. package/template/pnpm-lock.yaml +1912 -27
  140. package/template/turbo.json +1 -1
  141. package/template/vitest.config.ts +2 -0
  142. package/template.lock.json +96 -12
  143. package/template/apps/web/e2e/home.spec.ts +0 -15
@@ -0,0 +1,27 @@
1
+ import { redirect } from "@tanstack/react-router";
2
+ import { createServerFn } from "@tanstack/react-start";
3
+ import { z } from "zod";
4
+ import { safeRedirectPath } from "@clubedge/core";
5
+ import { loginUrl } from "@/lib/login-url";
6
+ import { getCurrentUser, isAuthConfigured } from "./auth";
7
+
8
+ // Server functions are RPC endpoints that route loaders call. The build replaces their
9
+ // bodies with network stubs in the browser bundle, so this file is safe to import anywhere.
10
+
11
+ /**
12
+ * For pages: redirects signed-out visitors to the login page and back afterwards.
13
+ * Returns null while authentication is not configured so the starter stays explorable.
14
+ */
15
+ export const getPageUser = createServerFn({ method: "GET" })
16
+ .validator(z.object({ pathname: z.string() }))
17
+ .handler(async ({ data }) => {
18
+ if (!isAuthConfigured()) return null;
19
+ const user = await getCurrentUser();
20
+ if (!user) throw redirect({ href: loginUrl({ next: safeRedirectPath(data.pathname) }) });
21
+ return user;
22
+ });
23
+
24
+ /** Lets the login page explain that authentication still needs configuring. */
25
+ export const getAuthStatus = createServerFn({ method: "GET" }).handler(() => ({
26
+ configured: isAuthConfigured(),
27
+ }));
@@ -0,0 +1,51 @@
1
+ import "@tanstack/react-start/server-only";
2
+ import type { AuthProvider, AuthUser } from "@clubedge/auth";
3
+ import { createSupabaseAuth, createSupabaseServerClient } from "@clubedge/auth-supabase";
4
+ import { AppError } from "@clubedge/core";
5
+ import { getSupabaseAuthEnv } from "@/env/auth";
6
+ import { requestCookieStore } from "./cookies";
7
+
8
+ export type { AuthUser } from "@clubedge/auth";
9
+
10
+ export function isAuthConfigured(): boolean {
11
+ return getSupabaseAuthEnv() !== null;
12
+ }
13
+
14
+ function supabaseConfig() {
15
+ const env = getSupabaseAuthEnv();
16
+ if (!env) throw new Error("Supabase Auth is not configured.");
17
+ return { ...env, cookies: requestCookieStore() };
18
+ }
19
+
20
+ /** Request-scoped auth provider. Throws when authentication is not configured. */
21
+ export function getAuth(): AuthProvider {
22
+ return createSupabaseAuth(supabaseConfig());
23
+ }
24
+
25
+ /** Request-scoped Supabase client for provider features such as Storage. */
26
+ export async function getSupabaseClient() {
27
+ return createSupabaseServerClient(supabaseConfig());
28
+ }
29
+
30
+ /** Validates the session and rotates its cookies. Runs once per request from src/start.ts. */
31
+ export async function refreshAuthSession(): Promise<void> {
32
+ if (!isAuthConfigured()) return;
33
+ try {
34
+ await getAuth().refreshSession();
35
+ } catch (error) {
36
+ // Pages still render; protected handlers re-check the user and reject when needed.
37
+ console.error("Session refresh failed", error);
38
+ }
39
+ }
40
+
41
+ export async function getCurrentUser(): Promise<AuthUser | null> {
42
+ if (!isAuthConfigured()) return null;
43
+ return getAuth().getUser();
44
+ }
45
+
46
+ /** For server functions and routes: throws a 401 AppError when signed out. */
47
+ export async function requireUser(): Promise<AuthUser> {
48
+ const user = await getCurrentUser();
49
+ if (!user) throw new AppError("Authentication required.", "UNAUTHENTICATED", 401);
50
+ return user;
51
+ }
@@ -0,0 +1,65 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
+
3
+ const redis = vi.hoisted(() => ({
4
+ limit: vi.fn(async () => ({ success: true, limit: 2, remaining: 1, resetAt: 0 })),
5
+ createRedisRateLimiter: vi.fn(),
6
+ createRedisCache: vi.fn(),
7
+ }));
8
+
9
+ vi.mock("@clubedge/cache-redis", () => ({
10
+ createRedisRateLimiter: redis.createRedisRateLimiter,
11
+ createRedisCache: redis.createRedisCache,
12
+ }));
13
+
14
+ async function loadFreshModule() {
15
+ vi.resetModules();
16
+ return import("./cache");
17
+ }
18
+
19
+ beforeEach(() => {
20
+ vi.clearAllMocks();
21
+ redis.createRedisRateLimiter.mockReturnValue({ limit: redis.limit });
22
+ redis.createRedisCache.mockReturnValue({ get: vi.fn(async () => "cached"), set: vi.fn() });
23
+ });
24
+
25
+ afterEach(() => {
26
+ vi.unstubAllEnvs();
27
+ });
28
+
29
+ describe("cache composition root", () => {
30
+ it("limits and caches in memory while REDIS_URL is empty", async () => {
31
+ vi.stubEnv("REDIS_URL", "");
32
+ const { cacheGet, cacheSet, createRateLimiter } = await loadFreshModule();
33
+ const limiter = createRateLimiter(1, 60);
34
+
35
+ expect((await limiter.limit("client")).success).toBe(true);
36
+ expect((await limiter.limit("client")).success).toBe(false);
37
+ await cacheSet("key", { value: 1 }, 60);
38
+ expect(await cacheGet("key")).toEqual({ value: 1 });
39
+ expect(redis.createRedisRateLimiter).not.toHaveBeenCalled();
40
+ expect(redis.createRedisCache).not.toHaveBeenCalled();
41
+ });
42
+
43
+ it("uses Redis once REDIS_URL is set, choosing the backend on first use", async () => {
44
+ vi.stubEnv("REDIS_URL", "");
45
+ const { cacheGet, createRateLimiter } = await loadFreshModule();
46
+ const limiter = createRateLimiter(2, 60);
47
+ vi.stubEnv("REDIS_URL", "redis://localhost:6379");
48
+
49
+ await limiter.limit("client");
50
+ expect(redis.createRedisRateLimiter).toHaveBeenCalledWith("redis://localhost:6379", {
51
+ requests: 2,
52
+ windowSeconds: 60,
53
+ });
54
+ expect(await cacheGet("key")).toBe("cached");
55
+ });
56
+
57
+ it("rejects a REDIS_URL that is not a Redis URL", async () => {
58
+ vi.stubEnv("REDIS_URL", "https://example.com");
59
+ vi.spyOn(console, "error").mockImplementation(() => {});
60
+ const { createRateLimiter } = await loadFreshModule();
61
+ expect(() => createRateLimiter().limit("client")).toThrow(
62
+ "Cache environment validation failed",
63
+ );
64
+ });
65
+ });
@@ -0,0 +1,58 @@
1
+ import "@tanstack/react-start/server-only";
2
+ import { z } from "zod";
3
+ import {
4
+ createMemoryCache,
5
+ createMemoryRateLimiter,
6
+ type Cache,
7
+ type RateLimiter,
8
+ } from "@clubedge/cache";
9
+ import { createRedisCache, createRedisRateLimiter } from "@clubedge/cache-redis";
10
+ import { optional, parseEnv } from "@/env/server";
11
+
12
+ export type { Cache, RateLimiter, RateLimitResult } from "@clubedge/cache";
13
+
14
+ const cacheEnvSchema = z.object({
15
+ REDIS_URL: optional(z.url({ protocol: /^rediss?$/ })),
16
+ });
17
+
18
+ function getRedisUrl(): string | undefined {
19
+ return parseEnv(cacheEnvSchema, "Cache").REDIS_URL || undefined;
20
+ }
21
+
22
+ /**
23
+ * Uses Redis when REDIS_URL is configured, otherwise a per-process memory limiter. The
24
+ * backend is chosen on first use so module-level limiters do not read env at import time.
25
+ */
26
+ export function createRateLimiter(requests = 10, windowSeconds = 60): RateLimiter {
27
+ let limiter: RateLimiter | undefined;
28
+ return {
29
+ limit(identifier) {
30
+ if (!limiter) {
31
+ const url = getRedisUrl();
32
+ limiter = url
33
+ ? createRedisRateLimiter(url, { requests, windowSeconds })
34
+ : createMemoryRateLimiter({ requests, windowSeconds });
35
+ }
36
+ return limiter.limit(identifier);
37
+ },
38
+ };
39
+ }
40
+
41
+ let cache: Cache | undefined;
42
+
43
+ /** Redis when REDIS_URL is configured, otherwise per-process memory. Resolved on first use. */
44
+ function resolveCache(): Cache {
45
+ if (!cache) {
46
+ const url = getRedisUrl();
47
+ cache = url ? createRedisCache(url) : createMemoryCache();
48
+ }
49
+ return cache;
50
+ }
51
+
52
+ export function cacheGet<T>(key: string): Promise<T | null> {
53
+ return resolveCache().get<T>(key);
54
+ }
55
+
56
+ export function cacheSet(key: string, value: unknown, ttlSeconds: number): Promise<void> {
57
+ return resolveCache().set(key, value, ttlSeconds);
58
+ }
@@ -0,0 +1,41 @@
1
+ import { beforeEach, describe, expect, it, vi } from "vitest";
2
+
3
+ const server = vi.hoisted(() => ({
4
+ request: new Request("https://app.example/"),
5
+ cookies: {} as Record<string, string>,
6
+ setCookie: vi.fn(),
7
+ }));
8
+
9
+ vi.mock("@tanstack/react-start/server", () => ({
10
+ getRequest: () => server.request,
11
+ getCookies: () => server.cookies,
12
+ setCookie: server.setCookie,
13
+ }));
14
+
15
+ const { requestCookieStore } = await import("./cookies");
16
+
17
+ beforeEach(() => {
18
+ server.request = new Request("https://app.example/");
19
+ server.cookies = { session: "old" };
20
+ server.setCookie.mockClear();
21
+ });
22
+
23
+ describe("requestCookieStore", () => {
24
+ it("reads the request cookies", () => {
25
+ expect(requestCookieStore().getAll()).toEqual([{ name: "session", value: "old" }]);
26
+ });
27
+
28
+ it("shares writes with later readers in the same request and sends them to the browser", () => {
29
+ const options = { httpOnly: true, path: "/" };
30
+ requestCookieStore().setAll([{ name: "session", value: "new", options }]);
31
+
32
+ expect(requestCookieStore().getAll()).toEqual([{ name: "session", value: "new" }]);
33
+ expect(server.setCookie).toHaveBeenCalledWith("session", "new", options);
34
+ });
35
+
36
+ it("starts fresh for every request", () => {
37
+ requestCookieStore().setAll([{ name: "session", value: "new" }]);
38
+ server.request = new Request("https://app.example/next");
39
+ expect(requestCookieStore().getAll()).toEqual([{ name: "session", value: "old" }]);
40
+ });
41
+ });
@@ -0,0 +1,31 @@
1
+ import "@tanstack/react-start/server-only";
2
+ import { getCookies, getRequest, setCookie } from "@tanstack/react-start/server";
3
+ import type { CookieStore } from "@clubedge/auth";
4
+
5
+ const jars = new WeakMap<Request, CookieStore>();
6
+
7
+ /**
8
+ * Bridges TanStack Start request cookies to the framework-agnostic CookieStore.
9
+ *
10
+ * There is one jar per request, so a session refreshed by the request middleware is visible
11
+ * to the server functions and routes that run later in the same request, and every write
12
+ * is also sent to the browser.
13
+ */
14
+ export function requestCookieStore(): CookieStore {
15
+ const request = getRequest();
16
+ const existing = jars.get(request);
17
+ if (existing) return existing;
18
+
19
+ const values = new Map(Object.entries(getCookies()));
20
+ const store: CookieStore = {
21
+ getAll: () => Array.from(values, ([name, value]) => ({ name, value })),
22
+ setAll(cookies) {
23
+ for (const { name, value, options } of cookies) {
24
+ values.set(name, value);
25
+ setCookie(name, value, options);
26
+ }
27
+ },
28
+ };
29
+ jars.set(request, store);
30
+ return store;
31
+ }
@@ -0,0 +1,16 @@
1
+ import "@tanstack/react-start/server-only";
2
+ import { createDb, type Database } from "@clubedge/db";
3
+ import { getServerEnv } from "@/env/server";
4
+
5
+ const globalForDb = globalThis as typeof globalThis & { clubedgeDb?: Database };
6
+
7
+ /** Creates the connection pool on first use and reuses it across dev hot reloads. */
8
+ export function getDb(): Database {
9
+ if (globalForDb.clubedgeDb) return globalForDb.clubedgeDb;
10
+ const env = getServerEnv();
11
+ globalForDb.clubedgeDb = createDb({
12
+ url: env.DATABASE_URL,
13
+ maxConnections: env.NODE_ENV === "production" ? 10 : 1,
14
+ });
15
+ return globalForDb.clubedgeDb;
16
+ }
@@ -0,0 +1,42 @@
1
+ import "@tanstack/react-start/server-only";
2
+ import { z } from "zod";
3
+ import type { StorageProvider } from "@clubedge/storage";
4
+ import { createS3Storage } from "@clubedge/storage-s3";
5
+ import { optional, parseEnv } from "@/env/server";
6
+
7
+ export type { SignedUrlOptions, StorageProvider, UploadInput } from "@clubedge/storage";
8
+
9
+ // S3-compatible storage: AWS S3, Cloudflare R2, MinIO, and similar services.
10
+ const storageEnvSchema = z.object({
11
+ STORAGE_BUCKET: optional(z.string()),
12
+ STORAGE_REGION: z.string().default("auto"),
13
+ STORAGE_ENDPOINT: optional(z.url()),
14
+ STORAGE_ACCESS_KEY_ID: optional(z.string()),
15
+ STORAGE_SECRET_ACCESS_KEY: optional(z.string()),
16
+ STORAGE_PUBLIC_URL: optional(z.url()),
17
+ });
18
+
19
+ let provider: StorageProvider | undefined;
20
+
21
+ function resolveProvider(): StorageProvider {
22
+ if (provider) return provider;
23
+ const env = parseEnv(storageEnvSchema, "Storage");
24
+ provider = createS3Storage({
25
+ bucket: env.STORAGE_BUCKET || undefined,
26
+ region: env.STORAGE_REGION,
27
+ endpoint: env.STORAGE_ENDPOINT || undefined,
28
+ accessKeyId: env.STORAGE_ACCESS_KEY_ID || undefined,
29
+ secretAccessKey: env.STORAGE_SECRET_ACCESS_KEY || undefined,
30
+ publicUrl: env.STORAGE_PUBLIC_URL || undefined,
31
+ });
32
+ return provider;
33
+ }
34
+
35
+ /** The configured storage provider, resolved on first use so imports stay side-effect free. */
36
+ export const storage: StorageProvider = {
37
+ upload: (input) => resolveProvider().upload(input),
38
+ download: (key) => resolveProvider().download(key),
39
+ delete: (key) => resolveProvider().delete(key),
40
+ exists: (key) => resolveProvider().exists(key),
41
+ getSignedUrl: (key, options) => resolveProvider().getSignedUrl(key, options),
42
+ };
@@ -0,0 +1,17 @@
1
+ import "@tanstack/react-start/server-only";
2
+ import type { AuthUser } from "@clubedge/auth";
3
+ import { upsertUserProfile } from "@clubedge/db";
4
+ import { getDb } from "./db";
5
+
6
+ /**
7
+ * Keeps the app-owned users row in step with the identity provider. Failures are logged
8
+ * rather than thrown so a database outage does not block an otherwise valid sign-in.
9
+ */
10
+ export async function ensureUserProfile(user: AuthUser | null): Promise<void> {
11
+ if (!user?.email) return;
12
+ try {
13
+ await upsertUserProfile(getDb(), { authUserId: user.id, email: user.email });
14
+ } catch (error) {
15
+ console.error("Could not sync the user profile", error);
16
+ }
17
+ }
@@ -0,0 +1,57 @@
1
+ import "@tanstack/react-start/server-only";
2
+ import type { AuthProvider, AuthUser } from "@clubedge/auth";
3
+ import {
4
+ createBetterAuth,
5
+ createBetterAuthServer,
6
+ drizzleDatabase,
7
+ type BetterAuthServer,
8
+ } from "@clubedge/auth-better-auth";
9
+ import { AppError } from "@clubedge/core";
10
+ import { getBetterAuthEnv } from "@/env/auth";
11
+ import { requestCookieStore } from "@/server/cookies";
12
+ import { getDb } from "@/server/db";
13
+
14
+ export type { AuthUser } from "@clubedge/auth";
15
+
16
+ export function isAuthConfigured(): boolean {
17
+ return getBetterAuthEnv() !== null;
18
+ }
19
+
20
+ let server: BetterAuthServer | undefined;
21
+
22
+ /** One Better Auth server per process, storing users and sessions in the app database. */
23
+ function getServer(): BetterAuthServer {
24
+ if (server) return server;
25
+ const env = getBetterAuthEnv();
26
+ if (!env) throw new Error("Better Auth is not configured.");
27
+ server = createBetterAuthServer({ database: drizzleDatabase(getDb()), ...env });
28
+ return server;
29
+ }
30
+
31
+ /** Request-scoped auth provider. Throws when authentication is not configured. */
32
+ export function getAuth(): AuthProvider {
33
+ return createBetterAuth({ server: getServer(), cookies: requestCookieStore() });
34
+ }
35
+
36
+ /** Validates the session and rotates its cookies. Runs once per request from src/start.ts. */
37
+ export async function refreshAuthSession(): Promise<void> {
38
+ if (!isAuthConfigured()) return;
39
+ try {
40
+ await getAuth().refreshSession();
41
+ } catch (error) {
42
+ // Pages still render; protected handlers re-check the user and reject when needed.
43
+ console.error("Session refresh failed", error);
44
+ }
45
+ }
46
+
47
+ export async function getCurrentUser(): Promise<AuthUser | null> {
48
+ if (!isAuthConfigured()) return null;
49
+ return getAuth().getUser();
50
+ }
51
+
52
+ /** For server functions and routes: throws a 401 AppError when signed out. */
53
+ export async function requireUser(): Promise<AuthUser> {
54
+ const user = await getCurrentUser();
55
+ if (!user) throw new AppError("Authentication required.", "UNAUTHENTICATED", 401);
56
+ return user;
57
+ }
@@ -0,0 +1,9 @@
1
+ import { createServerFn } from "@tanstack/react-start";
2
+ import { z } from "zod";
3
+ import type { AuthUser } from "@/server/auth";
4
+
5
+ // This project was created without authentication, so every page renders for everyone.
6
+
7
+ export const getPageUser = createServerFn({ method: "GET" })
8
+ .validator(z.object({ pathname: z.string() }))
9
+ .handler(async (): Promise<AuthUser | null> => null);
@@ -0,0 +1,28 @@
1
+ import "@tanstack/react-start/server-only";
2
+ import { AppError } from "@clubedge/core";
3
+
4
+ // This project was created without authentication. These helpers keep the contract the pages
5
+ // rely on, so adding a provider later means replacing this file and adding a login flow.
6
+
7
+ export interface AuthUser {
8
+ id: string;
9
+ email: string | null;
10
+ }
11
+
12
+ export function isAuthConfigured(): boolean {
13
+ return false;
14
+ }
15
+
16
+ export async function getCurrentUser(): Promise<AuthUser | null> {
17
+ return null;
18
+ }
19
+
20
+ /** Called by the request middleware in src/start.ts. */
21
+ export async function refreshAuthSession(): Promise<void> {
22
+ // There are no sessions to refresh without authentication.
23
+ }
24
+
25
+ /** Server functions and routes that need a user always refuse: there is no way to sign in. */
26
+ export async function requireUser(): Promise<AuthUser> {
27
+ throw new AppError("This application has no authentication.", "UNAUTHENTICATED", 401);
28
+ }
@@ -0,0 +1,26 @@
1
+ import "@tanstack/react-start/server-only";
2
+ import {
3
+ createMemoryCache,
4
+ createMemoryRateLimiter,
5
+ type Cache,
6
+ type RateLimiter,
7
+ } from "@clubedge/cache";
8
+
9
+ export type { Cache, RateLimiter, RateLimitResult } from "@clubedge/cache";
10
+
11
+ // Rate limits and cached values live in process memory, which suits a single server instance.
12
+ // Projects that run several instances should use the Redis module instead.
13
+
14
+ export function createRateLimiter(requests = 10, windowSeconds = 60): RateLimiter {
15
+ return createMemoryRateLimiter({ requests, windowSeconds });
16
+ }
17
+
18
+ const cache: Cache = createMemoryCache();
19
+
20
+ export function cacheGet<T>(key: string): Promise<T | null> {
21
+ return cache.get<T>(key);
22
+ }
23
+
24
+ export function cacheSet(key: string, value: unknown, ttlSeconds: number): Promise<void> {
25
+ return cache.set(key, value, ttlSeconds);
26
+ }
@@ -0,0 +1,35 @@
1
+ import "@tanstack/react-start/server-only";
2
+ import { z } from "zod";
3
+ import type { StorageProvider } from "@clubedge/storage";
4
+ import { createSupabaseStorage } from "@clubedge/storage-supabase";
5
+ import { optional, parseEnv } from "@/env/server";
6
+ import { getSupabaseClient } from "@/server/auth";
7
+
8
+ export type { SignedUrlOptions, StorageProvider, UploadInput } from "@clubedge/storage";
9
+
10
+ // Supabase Storage, through the request-scoped Supabase client, so bucket policies can use
11
+ // the signed-in user.
12
+ const storageEnvSchema = z.object({
13
+ SUPABASE_STORAGE_BUCKET: optional(z.string()),
14
+ });
15
+
16
+ let provider: StorageProvider | undefined;
17
+
18
+ function resolveProvider(): StorageProvider {
19
+ if (provider) return provider;
20
+ const env = parseEnv(storageEnvSchema, "Storage");
21
+ provider = createSupabaseStorage({
22
+ bucket: env.SUPABASE_STORAGE_BUCKET || undefined,
23
+ getClient: getSupabaseClient,
24
+ });
25
+ return provider;
26
+ }
27
+
28
+ /** The configured storage provider, resolved on first use so imports stay side-effect free. */
29
+ export const storage: StorageProvider = {
30
+ upload: (input) => resolveProvider().upload(input),
31
+ download: (key) => resolveProvider().download(key),
32
+ delete: (key) => resolveProvider().delete(key),
33
+ exists: (key) => resolveProvider().exists(key),
34
+ getSignedUrl: (key, options) => resolveProvider().getSignedUrl(key, options),
35
+ };
@@ -0,0 +1,40 @@
1
+ import { createCsrfMiddleware, createMiddleware, createStart } from "@tanstack/react-start";
2
+ import { refreshAuthSession } from "@/server/auth";
3
+
4
+ const securityHeaders: Record<string, string> = {
5
+ "X-Content-Type-Options": "nosniff",
6
+ "X-Frame-Options": "DENY",
7
+ "Referrer-Policy": "strict-origin-when-cross-origin",
8
+ "Permissions-Policy": "camera=(), microphone=(), geolocation=()",
9
+ "Strict-Transport-Security": "max-age=63072000; includeSubDomains; preload",
10
+ };
11
+
12
+ const safeMethods = new Set(["GET", "HEAD", "OPTIONS"]);
13
+
14
+ // Rejects cross-site form posts and server function calls (Next.js does this for actions).
15
+ const csrfProtection = createCsrfMiddleware({
16
+ filter: ({ request }) => !safeMethods.has(request.method),
17
+ });
18
+
19
+ // Refreshed cookies reach both later handlers in this request and the browser response.
20
+ const sessionRefresh = createMiddleware().server(async ({ next }) => {
21
+ await refreshAuthSession();
22
+ return next();
23
+ });
24
+
25
+ const responseHeaders = createMiddleware().server(async ({ next }) => {
26
+ const result = await next();
27
+ let response = result.response;
28
+ try {
29
+ for (const [name, value] of Object.entries(securityHeaders)) response.headers.set(name, value);
30
+ } catch {
31
+ // Some responses have immutable headers; copy them into a mutable response.
32
+ response = new Response(response.body, response);
33
+ for (const [name, value] of Object.entries(securityHeaders)) response.headers.set(name, value);
34
+ }
35
+ return { ...result, response };
36
+ });
37
+
38
+ export const startInstance = createStart(() => ({
39
+ requestMiddleware: [responseHeaders, csrfProtection, sessionRefresh],
40
+ }));
@@ -0,0 +1,2 @@
1
+ @import "@clubedge/ui/globals.css";
2
+ @source "./";
@@ -0,0 +1,19 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "lib": ["dom", "dom.iterable", "esnext"],
5
+ "jsx": "react-jsx",
6
+ "types": ["node", "vite/client"],
7
+ "baseUrl": ".",
8
+ "paths": {
9
+ "@/*": ["./src/*"]
10
+ }
11
+ },
12
+ "include": [
13
+ "**/*.ts",
14
+ "**/*.tsx",
15
+ "../../packages/ui/src/**/*.ts",
16
+ "../../packages/ui/src/**/*.tsx"
17
+ ],
18
+ "exclude": ["node_modules", ".output", ".nitro", ".tanstack", "dist"]
19
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "routesDirectory": "./src/routes",
3
+ "generatedRouteTree": "./src/routeTree.gen.ts",
4
+ "routeTreeFileFooter": [
5
+ "import type { getRouter } from './router.tsx'\nimport type { startInstance } from './start.ts'\ndeclare module '@tanstack/react-start' {\n interface Register {\n ssr: true\n router: Awaited<ReturnType<typeof getRouter>>\n config: Awaited<ReturnType<typeof startInstance.getOptions>>\n }\n}"
6
+ ]
7
+ }
@@ -0,0 +1,27 @@
1
+ import tailwindcss from "@tailwindcss/vite";
2
+ import { tanstackStart } from "@tanstack/react-start/plugin/vite";
3
+ import viteReact from "@vitejs/plugin-react";
4
+ import { nitro } from "nitro/vite";
5
+ import { defineConfig, loadEnv } from "vite";
6
+
7
+ export default defineConfig(({ mode }) => {
8
+ // Server code reads process.env. Load .env, .env.local and friends from this directory so
9
+ // local development behaves like the Next.js app; real environment variables still win.
10
+ for (const [key, value] of Object.entries(loadEnv(mode, import.meta.dirname, ""))) {
11
+ process.env[key] ??= value;
12
+ }
13
+
14
+ return {
15
+ // Listen on every interface like `next dev`, so http://127.0.0.1:3000 (used by the
16
+ // browser tests) works where localhost resolves to IPv6 only.
17
+ server: { port: 3000, host: true },
18
+ resolve: { tsconfigPaths: true },
19
+ // TanStack Router and Base UI use this CommonJS package, which calls require("react").
20
+ // Inlined into the SSR build, that call survives as a runtime require of a second React
21
+ // copy and breaks hooks. Keeping it external lets Nitro bundle it with the one React.
22
+ // Vite resolves externals from this app, so it is also a direct dependency here.
23
+ environments: { ssr: { resolve: { external: ["use-sync-external-store"] } } },
24
+ // The Start plugin must come before the React plugin.
25
+ plugins: [tailwindcss(), tanstackStart(), nitro(), viteReact()],
26
+ };
27
+ });
@@ -1,8 +1,16 @@
1
1
  import type { NextConfig } from "next";
2
+ import { readFileSync } from "node:fs";
2
3
  import { fileURLToPath } from "node:url";
3
4
 
4
5
  const workspaceRoot = fileURLToPath(new URL("../..", import.meta.url));
5
6
 
7
+ // Workspace packages ship TypeScript source and are compiled by the app. Reading them from
8
+ // package.json keeps this list right when packages are added or removed.
9
+ const { dependencies } = JSON.parse(
10
+ readFileSync(new URL("./package.json", import.meta.url), "utf8"),
11
+ );
12
+ const workspacePackages = Object.keys(dependencies).filter((name) => name.startsWith("@clubedge/"));
13
+
6
14
  const securityHeaders = [
7
15
  { key: "X-Content-Type-Options", value: "nosniff" },
8
16
  { key: "X-Frame-Options", value: "DENY" },
@@ -15,15 +23,7 @@ const nextConfig: NextConfig = {
15
23
  poweredByHeader: false,
16
24
  output: "standalone",
17
25
  outputFileTracingRoot: workspaceRoot,
18
- // Workspace packages ship TypeScript source and are compiled by the app.
19
- transpilePackages: [
20
- "@clubedge/auth",
21
- "@clubedge/cache",
22
- "@clubedge/core",
23
- "@clubedge/db",
24
- "@clubedge/storage",
25
- "@clubedge/ui",
26
- ],
26
+ transpilePackages: workspacePackages,
27
27
  async headers() {
28
28
  return [{ source: "/:path*", headers: securityHeaders }];
29
29
  },