feat(01-04): switch media storage from Cloudflare R2 to Supabase Storage

This commit is contained in:
admin committed 2026-06-06 11:32:17 +02:00
1 parent 1a735b9393
commit e3c279d6a4
11 files changed
+156 -54

No files matched your search

+12 -1
View File
@@ -24,7 +24,18 @@
"Bash(gsd-tools query *)",
"Bash(git commit *)",
"Bash(Test-Path *)",
"Bash(git mv *)"
"Bash(git mv *)",
"Bash(git rm *)",
"Skill(gsd:verify-work)",
"Bash(node -e \"const pkg = require\\('./package.json'\\); console.log\\('react-hook-form:', pkg.dependencies['react-hook-form'] || pkg.devDependencies?.['react-hook-form'] || 'NOT INSTALLED'\\); console.log\\('@hookform/resolvers:', pkg.dependencies['@hookform/resolvers'] || pkg.devDependencies?.['@hookform/resolvers'] || 'NOT INSTALLED'\\);\")",
"Bash(npm install *)",
"Bash(npx prisma *)",
"Bash(node -e \"const pkg = require\\('./node_modules/@base-ui/react/package.json'\\); console.log\\('version:', pkg.version\\);\")",
"Bash(grep -v \"^$\")",
"Skill(gsd:progress)",
"Bash(node \"T:/CC-Projekte/.claude/gsd-core/bin/gsd-tools.cjs\" query state.advance-plan --phase 1 --plan \"01-03\")",
"Bash(git stash *)",
"Bash(echo \"Exit: $?\")"
]
}
}
+5 -10
View File
@@ -16,13 +16,8 @@ DIRECT_URL="postgresql://postgres.xxxxxxxxxxxx:password@aws-0-eu-central-1.poole
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY="pk_test_xxxxxxxxxxxxxxxxxxxx"
CLERK_SECRET_KEY="sk_test_xxxxxxxxxxxxxxxxxxxx"
# ── Cloudflare R2 (Media Storage) ───────────────────────────
# Cloudflare Dashboard -> R2 -> Account ID
CF_ACCOUNT_ID="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
# Cloudflare Dashboard -> R2 -> Manage R2 API Tokens
R2_ACCESS_KEY_ID="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
R2_SECRET_ACCESS_KEY="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
# Cloudflare Dashboard -> R2 -> bucket name you create
R2_BUCKET_NAME="onlypets-media"
# Cloudflare R2 -> bucket -> Settings -> Public Development URL or custom CDN domain
NEXT_PUBLIC_R2_PUBLIC_URL="https://pub-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.r2.dev"
# ── Supabase Storage (Media) ─────────────────────────────────
# Supabase Dashboard -> Project Settings -> API -> Project URL
NEXT_PUBLIC_SUPABASE_URL="https://xxxxxxxxxxxxxxxxxxxx.supabase.co"
# Supabase Dashboard -> Project Settings -> API -> service_role (secret!)
SUPABASE_SERVICE_ROLE_KEY="eyJxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+1 -1
View File
@@ -125,7 +125,7 @@ Phases execute in numeric order. Phase 5 depends only on Phase 2 (not Phase 4) s
| Phase | Plans Complete | Status | Completed |
|-------|----------------|--------|-----------|
| 1. Foundation | 0/4 | Not started | - |
| 1. Foundation | 2/4 | In progress | - |
| 2. Content Core | 0/TBD | Not started | - |
| 3. Engagement and Discovery | 0/TBD | Not started | - |
| 4. Notifications | 0/TBD | Not started | - |
+8 -8
View File
@@ -2,15 +2,15 @@
gsd_state_version: 1.0
milestone: v1.0
milestone_name: milestone
status: executing
status: verifying
stopped_at: Phase 1 plans complete (01-01 through 01-04)
last_updated: "2026-06-06T06:40:22.471Z"
last_activity: 2026-06-05 -- Phase 1 execution started
last_updated: "2026-06-06T08:55:46.710Z"
last_activity: 2026-06-06 -- Plan 01-03 (Pet CRUD) verified by human checkpoint; 5 post-checkpoint UX fixes applied
progress:
total_phases: 7
completed_phases: 0
total_plans: 4
completed_plans: 1
completed_plans: 3
percent: 0
---
@@ -26,11 +26,11 @@ See: .planning/PROJECT.md (updated 2026-06-05)
## Current Position
Phase: 1 (Foundation) — EXECUTING
Plan: 2 of 4
Status: Ready to execute
Last activity: 2026-06-05 -- Phase 1 execution started
Plan: 4 of 4 (next: 01-04 Media Pipeline / R2 Avatar Upload)
Status: Plans 01-01, 01-02, 01-03 complete and UAT verified
Last activity: 2026-06-06 -- Plan 01-03 (Pet CRUD) verified by human checkpoint; 5 post-checkpoint UX fixes applied
Progress: [░░░░░░░░░░] 0%
Progress: [██░░░░░░░░] 7%
## Performance Metrics
@@ -0,0 +1,66 @@
---
status: complete
phase: 01-foundation
source: 01-01-SUMMARY.md, 01-02-SUMMARY.md
started: 2026-06-06T07:05:00Z
updated: 2026-06-06T07:10:00Z
---
## Current Test
[testing complete]
## Tests
### 1. Unauthenticated Redirect
expected: Visiting /pets (or any protected route) without being logged in redirects to /log-in
result: pass
### 2. Sign-In Page Renders with Orange Branding
expected: /log-in renders Clerk SignIn component with orange-500 (#F97316) primary color on CTA button
result: pass
### 3. Sign-Up Page Renders with Orange Branding
expected: /sign-up renders Clerk SignUp component with orange-500 (#F97316) primary color on CTA button
result: pass
### 4. Sign-Up Redirects to Onboarding
expected: Completing sign-up redirects to /onboarding/pet; the app shell (sidebar) is visible
result: pass
### 5. Onboarding Stub Page
expected: /onboarding/pet shows a dashed-border placeholder (Plan 03 stub) with correct copy, without redirect loop
result: pass
### 6. Forgot Password Form
expected: /forgot-password renders "Reset your password" form; submitting email shows confirmation and redirects to /reset-password
result: pass
### 7. Desktop Sidebar
expected: At viewport >= 1024px the 240px sidebar is visible with OnlyPets wordmark, orange PawPrint icon, pet switcher dropdown, nav links, and Clerk UserButton at bottom
result: pass
### 8. Mobile Bottom Tab Bar
expected: At viewport < 768px the fixed bottom tab bar (h-16) is visible with 5 tabs; active pet switcher bar appears above tabs
result: pass
### 9. App Shell Auth Guard
expected: (app)/layout.tsx server-side auth() check gates all app routes; owners with no pets are redirected to /onboarding/pet
result: pass
### 10. Database Schema Live
expected: prisma db push succeeded — Owner, Species, Breed, Pet tables exist in Supabase; schema is queryable
result: pass
## Summary
total: 10
passed: 10
issues: 0
pending: 0
skipped: 0
blocked: 0
## Gaps
[none]
@@ -202,6 +202,20 @@ Commits verified:
- f996459: test(01-03) unit tests
- 8824391: fix(01-03) type fix
## Checkpoint Fixes (Post-Execution Verification)
The following fixes were applied during the human UAT checkpoint for Plan 03 after the summary was first written. They are captured here for completeness.
| Fix | File | Detail |
|-----|------|--------|
| PetForm Select trigger resolves name from loaded list | `src/components/pet/PetForm.tsx` | Bypasses Radix `SelectValue` display bug — trigger reads species/breed name directly from the fetched array instead of relying on `SelectValue` to render it |
| Select value uses `""` instead of `undefined` | `src/components/pet/PetForm.tsx` | Keeps the Radix Select controlled at all times; `undefined` value caused uncontrolled→controlled React warning |
| Pet name auto-capitalizes first letter on input | `src/components/pet/PetForm.tsx` | `onChange` handler capitalizes `value[0]` before storing into react-hook-form state |
| PetGrid card click navigates to `/pets/[petId]` AND sets active pet | `src/app/(app)/pets/PetGrid.tsx` | `useRouter().push()` added alongside `setActivePetId()` so clicking a pet card performs both navigation and context update |
| Species/breed selects deferred render until data loaded | `src/components/pet/PetForm.tsx` | Select options rendered only after `isLoadingSpecies` / `isLoadingBreeds` is false, preventing empty option flash |
All five fixes are contained in a single post-checkpoint commit (see git log for `fix(01-03) checkpoint ux fixes`).
---
*Phase: 01-foundation*
*Completed: 2026-06-06*
+6 -19
View File
@@ -1,31 +1,18 @@
import type { NextConfig } from "next";
/**
* Derive the R2 CDN hostname for Next.js Image remote patterns.
* Falls back to '*.r2.cloudflarestorage.com' when env var is not set (CI/build).
* The NEXT_PUBLIC_R2_PUBLIC_URL is the only R2 env var accessible client-side — it is
* the CDN domain only (not credentials).
*/
function getR2Hostname(): string {
const publicUrl = process.env.NEXT_PUBLIC_R2_PUBLIC_URL;
if (publicUrl) {
try {
return new URL(publicUrl).hostname;
} catch {
// Invalid URL — fall through to default
}
function getSupabaseHostname(): string {
const url = process.env.NEXT_PUBLIC_SUPABASE_URL;
if (url) {
try { return new URL(url).hostname; } catch { /* fall through */ }
}
return "*.r2.cloudflarestorage.com";
return "*.supabase.co";
}
const nextConfig: NextConfig = {
allowedDevOrigins: ["192.168.1.92"],
images: {
remotePatterns: [
{
protocol: "https",
hostname: getR2Hostname(),
},
{ protocol: "https", hostname: getSupabaseHostname() },
],
},
};
+1 -1
View File
@@ -140,7 +140,7 @@ export function AvatarUpload({
await confirmUploadMutation.mutateAsync({ petId, key });
// Step 4: Show CDN avatar URL immediately (no page reload needed)
const cdnUrl = `${process.env.NEXT_PUBLIC_R2_PUBLIC_URL}/${key}`;
const cdnUrl = `${process.env.NEXT_PUBLIC_SUPABASE_URL}/storage/v1/object/public/pet-avatars/${key}`;
setLocalAvatarUrl(cdnUrl);
setUploadState("idle");
setUploadProgress(0);
+1 -1
View File
@@ -166,7 +166,7 @@ export function PetForm({
petId={petId}
currentAvatarUrl={
currentAvatarKey
? `${process.env.NEXT_PUBLIC_R2_PUBLIC_URL}/${currentAvatarKey}`
? `${process.env.NEXT_PUBLIC_SUPABASE_URL}/storage/v1/object/public/pet-avatars/${currentAvatarKey}`
: null
}
onUploadComplete={(key) => {
+35
View File
@@ -0,0 +1,35 @@
import "server-only";
import { createClient } from "@supabase/supabase-js";
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
const serviceRoleKey = process.env.SUPABASE_SERVICE_ROLE_KEY!;
// Server-side Supabase client with service role key — never exposed to client
const supabase = createClient(supabaseUrl, serviceRoleKey, {
auth: { persistSession: false },
});
export const STORAGE_BUCKET = "pet-avatars";
export const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MB
export const ALLOWED_CONTENT_TYPES = ["image/jpeg", "image/png", "image/webp"] as const;
/**
* Creates a signed upload URL for direct client-to-Supabase uploads.
* The client PUTs the file directly to this URL — bytes never pass through the API server.
*/
export async function createSignedUploadUrl(key: string) {
const { data, error } = await supabase.storage
.from(STORAGE_BUCKET)
.createSignedUploadUrl(key);
if (error) throw new Error(`Storage error: ${error.message}`);
return { signedUrl: data.signedUrl, path: data.path };
}
/**
* Returns the public CDN URL for a stored object.
*/
export function getPublicUrl(key: string): string {
const { data } = supabase.storage.from(STORAGE_BUCKET).getPublicUrl(key);
return data.publicUrl;
}
+7 -13
View File
@@ -2,7 +2,7 @@ import "server-only";
import { z } from "zod";
import { TRPCError } from "@trpc/server";
import { protectedProcedure, router } from "@/trpc/init";
import { getPresignedUploadUrl } from "@/lib/r2";
import { createSignedUploadUrl, getPublicUrl, ALLOWED_CONTENT_TYPES, MAX_FILE_SIZE } from "@/lib/supabase-storage";
import { randomUUID } from "crypto";
/**
@@ -32,28 +32,22 @@ export const mediaRouter = router({
.input(
z.object({
petId: z.string(),
contentType: z.enum(["image/jpeg", "image/png", "image/webp"]),
fileSize: z
.number()
.max(10 * 1024 * 1024, "Photo must be under 10 MB"),
contentType: z.enum(ALLOWED_CONTENT_TYPES),
fileSize: z.number().max(MAX_FILE_SIZE, "Photo must be under 10 MB"),
})
)
.mutation(async ({ ctx, input }) => {
// Ownership assertion (T-4-01): verify pet belongs to authenticated owner
const pet = await ctx.prisma.pet.findUnique({
where: { id: input.petId },
});
// Ownership assertion (T-4-01)
const pet = await ctx.prisma.pet.findUnique({ where: { id: input.petId } });
if (!pet || pet.ownerId !== ctx.userId) {
throw new TRPCError({ code: "FORBIDDEN" });
}
// Generate unique R2 key scoped by owner and pet
// Format: avatars/{ownerId}/{petId}/{uuid}.{ext}
const ext = input.contentType.split("/")[1].replace("jpeg", "jpg");
const key = `avatars/${ctx.userId}/${input.petId}/${randomUUID()}.${ext}`;
const presignedUrl = await getPresignedUploadUrl(key, input.contentType);
return { presignedUrl, key };
const { signedUrl } = await createSignedUploadUrl(key);
return { presignedUrl: signedUrl, key };
}),
/**