feat: Migrate from self-hosted to Vercel + Neon + Clerk

- Move database from self-hosted Postgres to Neon (free tier)
- Replace better-auth with Clerk authentication (email/password + OAuth)
- Integrate Ably for real-time sync (replaces custom WebSocket)
- Remove passkey authentication (pending Apple Developer account)
- Add Clerk Organizations for household management
- Implement custom household join-code flow with Clerk
- Add secure Ably key fetching via backend API
- Update iOS app for Clerk auth and Ably real-time sync
- Configure Vercel deployment settings
- Update environment configuration for new infrastructure

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
bananabas 2026-06-27 18:59:00 +01:00
parent 3421d35c0e
commit 4fe4a98b1c
43 changed files with 3191 additions and 3485 deletions

1
.gitignore vendored
View file

@ -44,6 +44,7 @@ yarn-error.log*
.turbo/
.next/
ios/build/
ios/.build/
android/.gradle/
# Secrets & sensitive

View file

@ -1,12 +1,17 @@
# Database
DATABASE_URL=postgresql://user:password@localhost:5432/shop
# Database (Neon pooled connection string)
# Use the pooled connection string from Neon (ends with -pooler.hostname)
# Example: postgresql://user:password@ep-xyz-123456-pooler.us-east-2.aws.neon.tech/neondb?sslmode=verify-full
DATABASE_URL=postgresql://user:password@ep-xyz-123456-pooler.us-east-2.aws.neon.tech/neondb?sslmode=verify-full
# Better Auth
# IMPORTANT: BETTER_AUTH_URL must match the actual server URL or auth will return 404
# For VPS: use the actual domain (e.g., https://api.bagsy.frg.network)
# For local: use http://localhost:3001
BETTER_AUTH_SECRET=your-secret-key-here-at-least-32-characters
BETTER_AUTH_URL=http://localhost:3001
# Clerk Authentication
# Get these from your Clerk Dashboard: https://dashboard.clerk.com
CLERK_SECRET_KEY=sk_test_your-secret-key-here
CLERK_PUBLISHABLE_KEY=pk_test_your-publishable-key-here
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_your-publishable-key-here
# Ably Real-time Sync
# Get this from your Ably Dashboard: https://ably.com/dashboard
ABLY_API_KEY=your-ably-api-key-here
# AI (OpenRouter)
OPENROUTER_API_KEY=your-openrouter-api-key-here

7
apps/api/.gitignore vendored Normal file
View file

@ -0,0 +1,7 @@
.vercel
.env.local
node_modules
.next
*.db
*.db-shm
*.db-wal

View file

@ -1,4 +0,0 @@
import { auth } from '@/lib/auth';
import { toNextJsHandler } from 'better-auth/next-js';
export const { GET, POST, PUT, PATCH, DELETE } = toNextJsHandler(auth);

View file

@ -0,0 +1,19 @@
import { NextResponse } from 'next/server';
/**
* GET /api/config/ably-key
* Returns the Ably API key for iOS clients
* This allows us to keep the key server-side and not embed it in the app
*/
export async function GET() {
const ablyKey = process.env.ABLY_API_KEY;
if (!ablyKey) {
return NextResponse.json(
{ error: 'Ably API key not configured' },
{ status: 500 }
);
}
return NextResponse.json({ ablyKey });
}

View file

@ -23,7 +23,7 @@ function generateInviteCode(): string {
*/
async function POST(req: NextRequest) {
try {
const session = await requireAuth();
const userId = await requireAuth();
const household = await getActiveHousehold();
// Generate a unique code
@ -52,7 +52,7 @@ async function POST(req: NextRequest) {
await db.insert(householdInviteCodes).values({
householdId: household.id,
code: code!,
createdBy: session.user.id,
createdBy: userId,
expiresAt,
});

View file

@ -4,6 +4,7 @@ import { successResponse, errorResponse, handleError } from '@/lib/response';
import { db } from '@/db';
import { householdInviteCodes } from '@/db/schema';
import { eq } from 'drizzle-orm';
import { clerkClient } from '@clerk/nextjs/server';
/**
* POST /api/households/join
@ -12,7 +13,7 @@ import { eq } from 'drizzle-orm';
*/
async function POST(req: NextRequest) {
try {
const session = await requireAuth();
const userId = await requireAuth();
const body = await req.json();
if (!body.code || typeof body.code !== 'string') {
@ -36,8 +37,13 @@ async function POST(req: NextRequest) {
return errorResponse('INVALID_INPUT', 'Invite code has expired');
}
// In production, add user to the household in the database
// or via better-auth organization plugin
// Add user to the Clerk organization
await clerkClient.organizations.createOrganizationMembership({
organizationId: invite.householdId,
userId: userId,
role: 'basic_member',
});
return successResponse({
id: invite.householdId,
message: 'Successfully joined household',

View file

@ -1,6 +1,7 @@
import { NextRequest } from 'next/server';
import { requireAuth, getActiveHousehold } from '@/lib/auth-middleware';
import { successResponse, errorResponse, handleError } from '@/lib/response';
import { clerkClient } from '@clerk/nextjs/server';
/**
* GET /api/households
@ -8,13 +9,23 @@ import { successResponse, errorResponse, handleError } from '@/lib/response';
*/
async function GET() {
try {
const session = await requireAuth();
const userId = await requireAuth();
const household = await getActiveHousehold();
// Fetch organization details from Clerk
const organization = await clerkClient.organizations.getOrganization({
organizationId: household.id,
});
// Fetch organization members
const memberships = await clerkClient.organizations.getOrganizationMembershipList({
organizationId: household.id,
});
return successResponse({
id: household.id,
name: household.name,
memberIds: [], // TODO: fetch member IDs from database
id: organization.id,
name: organization.name,
memberIds: memberships.data.map((m) => m.publicUserData?.userId).filter(Boolean) as string[],
});
} catch (error) {
return handleError(error);
@ -23,26 +34,36 @@ async function GET() {
/**
* POST /api/households
* Create a new household
* Create a new household (Clerk organization)
* Body: { name: string }
* Note: Uses better-auth organization plugin to manage households
*/
async function POST(req: NextRequest) {
try {
const session = await requireAuth();
const userId = await requireAuth();
const body = await req.json();
if (!body.name || typeof body.name !== 'string') {
return errorResponse('INVALID_INPUT', 'Household name is required');
}
// For now, just return a placeholder
// In production, this would create a better-auth organization
// Create Clerk organization
const organization = await clerkClient.organizations.createOrganization({
name: body.name,
createdBy: userId,
});
// Add the creator as an admin member
await clerkClient.organizations.createOrganizationMembership({
organizationId: organization.id,
userId: userId,
role: 'admin',
});
return successResponse(
{
id: `household-${Date.now()}`,
name: body.name,
memberIds: [session.user.id],
id: organization.id,
name: organization.name,
memberIds: [userId],
},
201
);

View file

@ -0,0 +1,116 @@
import { NextRequest } from 'next/server';
import { requireAuth, getActiveHousehold } from '@/lib/auth-middleware';
import { successResponse, errorResponse, handleError } from '@/lib/response';
import { db } from '@/db';
import { shoppingLists, listItems } from '@/db/schema';
import { eq, and } from 'drizzle-orm';
import { publishToHousehold, HouseholdEvents } from '@/lib/ably';
interface RouteParams {
params: Promise<{ id: string; itemId: string }>;
}
/**
* PUT /api/lists/[id]/items/[itemId]
* Update a list item (e.g., check/uncheck)
* Body: { checked?: boolean, quantity?: number }
*/
async function PUT(req: NextRequest, { params }: RouteParams) {
try {
await requireAuth();
const household = await getActiveHousehold();
const { id: listId, itemId } = await params;
const body = await req.json();
// Verify list belongs to household
const [list] = await db
.select()
.from(shoppingLists)
.where(and(eq(shoppingLists.id, listId), eq(shoppingLists.householdId, household.id)));
if (!list) {
return errorResponse('NOT_FOUND', 'List not found');
}
// Get existing list item
const [existing] = await db
.select()
.from(listItems)
.where(and(eq(listItems.id, itemId), eq(listItems.shoppingListId, listId)));
if (!existing) {
return errorResponse('NOT_FOUND', 'List item not found');
}
// Update item
const [updated] = await db
.update(listItems)
.set({
...(typeof body.checked === 'boolean' && { checked: body.checked }),
...(typeof body.quantity === 'number' && { quantity: body.quantity }),
updatedAt: new Date(),
})
.where(eq(listItems.id, itemId))
.returning();
// Publish real-time update if checked status changed
if (typeof body.checked === 'boolean') {
await publishToHousehold(household.id, HouseholdEvents.ITEM_CHECKED, {
listId,
itemId,
checked: body.checked,
});
}
return successResponse(updated);
} catch (error) {
return handleError(error);
}
}
/**
* DELETE /api/lists/[id]/items/[itemId]
* Remove an item from a shopping list
*/
async function DELETE(req: NextRequest, { params }: RouteParams) {
try {
await requireAuth();
const household = await getActiveHousehold();
const { id: listId, itemId } = await params;
// Verify list belongs to household
const [list] = await db
.select()
.from(shoppingLists)
.where(and(eq(shoppingLists.id, listId), eq(shoppingLists.householdId, household.id)));
if (!list) {
return errorResponse('NOT_FOUND', 'List not found');
}
// Get existing list item before deletion
const [existing] = await db
.select()
.from(listItems)
.where(and(eq(listItems.id, itemId), eq(listItems.shoppingListId, listId)));
if (!existing) {
return errorResponse('NOT_FOUND', 'List item not found');
}
// Delete item
await db.delete(listItems).where(eq(listItems.id, itemId));
// Publish real-time update
await publishToHousehold(household.id, HouseholdEvents.ITEM_REMOVED, {
listId,
itemId,
});
return successResponse({ message: 'Item removed' });
} catch (error) {
return handleError(error);
}
}
export { PUT, DELETE };

View file

@ -0,0 +1,73 @@
import { NextRequest } from 'next/server';
import { requireAuth, getActiveHousehold } from '@/lib/auth-middleware';
import { successResponse, errorResponse, handleError } from '@/lib/response';
import { db } from '@/db';
import { shoppingLists, listItems, items } from '@/db/schema';
import { eq, and } from 'drizzle-orm';
import { publishToHousehold, HouseholdEvents } from '@/lib/ably';
interface RouteParams {
params: Promise<{ id: string }>;
}
/**
* POST /api/lists/[id]/items
* Add an item to a shopping list
* Body: { itemId: string, quantity?: number }
*/
async function POST(req: NextRequest, { params }: RouteParams) {
try {
await requireAuth();
const household = await getActiveHousehold();
const { id: listId } = await params;
const body = await req.json();
if (!body.itemId || typeof body.itemId !== 'string') {
return errorResponse('INVALID_INPUT', 'Item ID is required');
}
// Verify list belongs to household
const [list] = await db
.select()
.from(shoppingLists)
.where(and(eq(shoppingLists.id, listId), eq(shoppingLists.householdId, household.id)));
if (!list) {
return errorResponse('NOT_FOUND', 'List not found');
}
// Verify item belongs to household
const [item] = await db
.select()
.from(items)
.where(and(eq(items.id, body.itemId), eq(items.householdId, household.id)));
if (!item) {
return errorResponse('NOT_FOUND', 'Item not found');
}
const [listItem] = await db
.insert(listItems)
.values({
shoppingListId: listId,
itemId: body.itemId,
quantity: body.quantity || 1,
checked: false,
addedBy: household.userId, // Use actual user ID from Clerk
excludedFromPreset: false,
})
.returning();
// Publish real-time update
await publishToHousehold(household.id, HouseholdEvents.ITEM_ADDED, {
listId,
item: listItem,
});
return successResponse(listItem, 201);
} catch (error) {
return handleError(error);
}
}
export { POST };

View file

@ -4,6 +4,7 @@ import { successResponse, errorResponse, handleError } from '@/lib/response';
import { db } from '@/db';
import { shoppingLists, listItems } from '@/db/schema';
import { eq, and } from 'drizzle-orm';
import { publishToHousehold, HouseholdEvents } from '@/lib/ably';
interface RouteParams {
params: Promise<{ id: string }>;
@ -57,6 +58,12 @@ async function POST(req: NextRequest, { params }: RouteParams) {
// Fetch updated items
const updatedItems = await db.select().from(listItems).where(eq(listItems.shoppingListId, id));
// Publish real-time update
await publishToHousehold(household.id, HouseholdEvents.LIST_RESET, {
listId: id,
excludedItemIds,
});
return successResponse({
message: 'List reset',
list: { ...list, items: updatedItems },

View file

@ -4,6 +4,7 @@ import { successResponse, errorResponse, handleError } from '@/lib/response';
import { db } from '@/db';
import { shoppingLists, listItems } from '@/db/schema';
import { eq } from 'drizzle-orm';
import { publishToHousehold, HouseholdEvents } from '@/lib/ably';
/**
* GET /api/lists
@ -65,6 +66,11 @@ async function POST(req: NextRequest) {
})
.returning();
// Publish real-time update
await publishToHousehold(household.id, HouseholdEvents.LIST_CREATED, {
list: { ...list, items: [] },
});
return successResponse({ ...list, items: [] }, 201);
} catch (error) {
return handleError(error);

View file

@ -1,216 +0,0 @@
import { relations } from "drizzle-orm";
import {
pgTable,
text,
timestamp,
boolean,
integer,
index,
uniqueIndex,
} from "drizzle-orm/pg-core";
export const user = pgTable("user", {
id: text("id").primaryKey(),
name: text("name").notNull(),
email: text("email").notNull().unique(),
emailVerified: boolean("email_verified").default(false).notNull(),
image: text("image"),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at")
.defaultNow()
.$onUpdate(() => /* @__PURE__ */ new Date())
.notNull(),
});
export const session = pgTable(
"session",
{
id: text("id").primaryKey(),
expiresAt: timestamp("expires_at").notNull(),
token: text("token").notNull().unique(),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at")
.$onUpdate(() => /* @__PURE__ */ new Date())
.notNull(),
ipAddress: text("ip_address"),
userAgent: text("user_agent"),
userId: text("user_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
activeOrganizationId: text("active_organization_id"),
},
(table) => [index("session_userId_idx").on(table.userId)],
);
export const account = pgTable(
"account",
{
id: text("id").primaryKey(),
accountId: text("account_id").notNull(),
providerId: text("provider_id").notNull(),
userId: text("user_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
accessToken: text("access_token"),
refreshToken: text("refresh_token"),
idToken: text("id_token"),
accessTokenExpiresAt: timestamp("access_token_expires_at"),
refreshTokenExpiresAt: timestamp("refresh_token_expires_at"),
scope: text("scope"),
password: text("password"),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at")
.$onUpdate(() => /* @__PURE__ */ new Date())
.notNull(),
},
(table) => [index("account_userId_idx").on(table.userId)],
);
export const verification = pgTable(
"verification",
{
id: text("id").primaryKey(),
identifier: text("identifier").notNull(),
value: text("value").notNull(),
expiresAt: timestamp("expires_at").notNull(),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at")
.defaultNow()
.$onUpdate(() => /* @__PURE__ */ new Date())
.notNull(),
},
(table) => [index("verification_identifier_idx").on(table.identifier)],
);
export const organization = pgTable(
"organization",
{
id: text("id").primaryKey(),
name: text("name").notNull(),
slug: text("slug").notNull().unique(),
logo: text("logo"),
createdAt: timestamp("created_at").notNull(),
metadata: text("metadata"),
},
(table) => [uniqueIndex("organization_slug_uidx").on(table.slug)],
);
export const member = pgTable(
"member",
{
id: text("id").primaryKey(),
organizationId: text("organization_id")
.notNull()
.references(() => organization.id, { onDelete: "cascade" }),
userId: text("user_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
role: text("role").default("member").notNull(),
createdAt: timestamp("created_at").notNull(),
},
(table) => [
index("member_organizationId_idx").on(table.organizationId),
index("member_userId_idx").on(table.userId),
],
);
export const invitation = pgTable(
"invitation",
{
id: text("id").primaryKey(),
organizationId: text("organization_id")
.notNull()
.references(() => organization.id, { onDelete: "cascade" }),
email: text("email").notNull(),
role: text("role"),
status: text("status").default("pending").notNull(),
expiresAt: timestamp("expires_at").notNull(),
createdAt: timestamp("created_at").defaultNow().notNull(),
inviterId: text("inviter_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
},
(table) => [
index("invitation_organizationId_idx").on(table.organizationId),
index("invitation_email_idx").on(table.email),
],
);
export const passkey = pgTable(
"passkey",
{
id: text("id").primaryKey(),
name: text("name"),
publicKey: text("public_key").notNull(),
userId: text("user_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
credentialID: text("credential_id").notNull(),
counter: integer("counter").notNull(),
deviceType: text("device_type").notNull(),
backedUp: boolean("backed_up").notNull(),
transports: text("transports"),
createdAt: timestamp("created_at"),
aaguid: text("aaguid"),
},
(table) => [
index("passkey_userId_idx").on(table.userId),
index("passkey_credentialID_idx").on(table.credentialID),
],
);
export const userRelations = relations(user, ({ many }) => ({
sessions: many(session),
accounts: many(account),
members: many(member),
invitations: many(invitation),
passkeys: many(passkey),
}));
export const sessionRelations = relations(session, ({ one }) => ({
user: one(user, {
fields: [session.userId],
references: [user.id],
}),
}));
export const accountRelations = relations(account, ({ one }) => ({
user: one(user, {
fields: [account.userId],
references: [user.id],
}),
}));
export const organizationRelations = relations(organization, ({ many }) => ({
members: many(member),
invitations: many(invitation),
}));
export const memberRelations = relations(member, ({ one }) => ({
organization: one(organization, {
fields: [member.organizationId],
references: [organization.id],
}),
user: one(user, {
fields: [member.userId],
references: [user.id],
}),
}));
export const invitationRelations = relations(invitation, ({ one }) => ({
organization: one(organization, {
fields: [invitation.organizationId],
references: [organization.id],
}),
user: one(user, {
fields: [invitation.inviterId],
references: [user.id],
}),
}));
export const passkeyRelations = relations(passkey, ({ one }) => ({
user: one(user, {
fields: [passkey.userId],
references: [user.id],
}),
}));

View file

@ -0,0 +1,187 @@
CREATE TABLE "aisles" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"store_id" uuid NOT NULL,
"name" varchar(255) NOT NULL,
"order" integer NOT NULL,
"colour" varchar(7) NOT NULL,
"created_at" timestamp DEFAULT now()
);
--> statement-breakpoint
CREATE TABLE "household_invite_codes" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"household_id" uuid NOT NULL,
"code" varchar(8) NOT NULL,
"created_by" uuid NOT NULL,
"expires_at" timestamp with time zone NOT NULL,
"created_at" timestamp DEFAULT now(),
CONSTRAINT "household_invite_codes_code_unique" UNIQUE("code")
);
--> statement-breakpoint
CREATE TABLE "items" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"household_id" uuid NOT NULL,
"name" varchar(255) NOT NULL,
"barcode" varchar(255),
"aisle_id" uuid,
"store_id" uuid,
"alternatives" json,
"created_at" timestamp DEFAULT now(),
"updated_at" timestamp DEFAULT now()
);
--> statement-breakpoint
CREATE TABLE "list_items" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"shopping_list_id" uuid NOT NULL,
"item_id" uuid NOT NULL,
"quantity" integer DEFAULT 1 NOT NULL,
"checked" boolean DEFAULT false NOT NULL,
"added_by" uuid NOT NULL,
"excluded_from_preset" boolean DEFAULT false NOT NULL,
"created_at" timestamp DEFAULT now(),
"updated_at" timestamp DEFAULT now()
);
--> statement-breakpoint
CREATE TABLE "scan_history" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"household_id" uuid NOT NULL,
"barcode" varchar(255) NOT NULL,
"item_id" uuid NOT NULL,
"scanned_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "shopping_lists" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"household_id" uuid NOT NULL,
"store_id" uuid NOT NULL,
"name" varchar(255) NOT NULL,
"is_preset" boolean DEFAULT false NOT NULL,
"auto_reset" boolean DEFAULT false NOT NULL,
"created_at" timestamp DEFAULT now(),
"updated_at" timestamp DEFAULT now()
);
--> statement-breakpoint
CREATE TABLE "stores" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"household_id" uuid NOT NULL,
"name" varchar(255) NOT NULL,
"location" text,
"created_at" timestamp DEFAULT now(),
"updated_at" timestamp DEFAULT now()
);
--> statement-breakpoint
CREATE TABLE "account" (
"id" text PRIMARY KEY NOT NULL,
"account_id" text NOT NULL,
"provider_id" text NOT NULL,
"user_id" text NOT NULL,
"access_token" text,
"refresh_token" text,
"id_token" text,
"access_token_expires_at" timestamp,
"refresh_token_expires_at" timestamp,
"scope" text,
"password" text,
"created_at" timestamp DEFAULT now() NOT NULL,
"updated_at" timestamp NOT NULL
);
--> statement-breakpoint
CREATE TABLE "invitation" (
"id" text PRIMARY KEY NOT NULL,
"organization_id" text NOT NULL,
"email" text NOT NULL,
"role" text,
"status" text DEFAULT 'pending' NOT NULL,
"expires_at" timestamp NOT NULL,
"created_at" timestamp DEFAULT now() NOT NULL,
"inviter_id" text NOT NULL
);
--> statement-breakpoint
CREATE TABLE "member" (
"id" text PRIMARY KEY NOT NULL,
"organization_id" text NOT NULL,
"user_id" text NOT NULL,
"role" text DEFAULT 'member' NOT NULL,
"created_at" timestamp NOT NULL
);
--> statement-breakpoint
CREATE TABLE "organization" (
"id" text PRIMARY KEY NOT NULL,
"name" text NOT NULL,
"slug" text NOT NULL,
"logo" text,
"created_at" timestamp NOT NULL,
"metadata" text,
CONSTRAINT "organization_slug_unique" UNIQUE("slug")
);
--> statement-breakpoint
CREATE TABLE "passkey" (
"id" text PRIMARY KEY NOT NULL,
"name" text,
"public_key" text NOT NULL,
"user_id" text NOT NULL,
"credential_id" text NOT NULL,
"counter" integer NOT NULL,
"device_type" text NOT NULL,
"backed_up" boolean NOT NULL,
"transports" text,
"created_at" timestamp,
"aaguid" text
);
--> statement-breakpoint
CREATE TABLE "session" (
"id" text PRIMARY KEY NOT NULL,
"expires_at" timestamp NOT NULL,
"token" text NOT NULL,
"created_at" timestamp DEFAULT now() NOT NULL,
"updated_at" timestamp NOT NULL,
"ip_address" text,
"user_agent" text,
"user_id" text NOT NULL,
"active_organization_id" text,
CONSTRAINT "session_token_unique" UNIQUE("token")
);
--> statement-breakpoint
CREATE TABLE "user" (
"id" text PRIMARY KEY NOT NULL,
"name" text NOT NULL,
"email" text NOT NULL,
"email_verified" boolean DEFAULT false NOT NULL,
"image" text,
"created_at" timestamp DEFAULT now() NOT NULL,
"updated_at" timestamp DEFAULT now() NOT NULL,
CONSTRAINT "user_email_unique" UNIQUE("email")
);
--> statement-breakpoint
CREATE TABLE "verification" (
"id" text PRIMARY KEY NOT NULL,
"identifier" text NOT NULL,
"value" text NOT NULL,
"expires_at" timestamp NOT NULL,
"created_at" timestamp DEFAULT now() NOT NULL,
"updated_at" timestamp DEFAULT now() NOT NULL
);
--> statement-breakpoint
ALTER TABLE "aisles" ADD CONSTRAINT "aisles_store_id_stores_id_fk" FOREIGN KEY ("store_id") REFERENCES "public"."stores"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "items" ADD CONSTRAINT "items_aisle_id_aisles_id_fk" FOREIGN KEY ("aisle_id") REFERENCES "public"."aisles"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "items" ADD CONSTRAINT "items_store_id_stores_id_fk" FOREIGN KEY ("store_id") REFERENCES "public"."stores"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "list_items" ADD CONSTRAINT "list_items_shopping_list_id_shopping_lists_id_fk" FOREIGN KEY ("shopping_list_id") REFERENCES "public"."shopping_lists"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "list_items" ADD CONSTRAINT "list_items_item_id_items_id_fk" FOREIGN KEY ("item_id") REFERENCES "public"."items"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "scan_history" ADD CONSTRAINT "scan_history_item_id_items_id_fk" FOREIGN KEY ("item_id") REFERENCES "public"."items"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "shopping_lists" ADD CONSTRAINT "shopping_lists_store_id_stores_id_fk" FOREIGN KEY ("store_id") REFERENCES "public"."stores"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "account" ADD CONSTRAINT "account_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "invitation" ADD CONSTRAINT "invitation_organization_id_organization_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organization"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "invitation" ADD CONSTRAINT "invitation_inviter_id_user_id_fk" FOREIGN KEY ("inviter_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "member" ADD CONSTRAINT "member_organization_id_organization_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organization"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "member" ADD CONSTRAINT "member_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "passkey" ADD CONSTRAINT "passkey_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "session" ADD CONSTRAINT "session_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
CREATE INDEX "account_userId_idx" ON "account" USING btree ("user_id");--> statement-breakpoint
CREATE INDEX "invitation_organizationId_idx" ON "invitation" USING btree ("organization_id");--> statement-breakpoint
CREATE INDEX "invitation_email_idx" ON "invitation" USING btree ("email");--> statement-breakpoint
CREATE INDEX "member_organizationId_idx" ON "member" USING btree ("organization_id");--> statement-breakpoint
CREATE INDEX "member_userId_idx" ON "member" USING btree ("user_id");--> statement-breakpoint
CREATE UNIQUE INDEX "organization_slug_uidx" ON "organization" USING btree ("slug");--> statement-breakpoint
CREATE INDEX "passkey_userId_idx" ON "passkey" USING btree ("user_id");--> statement-breakpoint
CREATE INDEX "passkey_credentialID_idx" ON "passkey" USING btree ("credential_id");--> statement-breakpoint
CREATE INDEX "session_userId_idx" ON "session" USING btree ("user_id");--> statement-breakpoint
CREATE INDEX "verification_identifier_idx" ON "verification" USING btree ("identifier");

View file

@ -0,0 +1,8 @@
DROP TABLE "account" CASCADE;--> statement-breakpoint
DROP TABLE "invitation" CASCADE;--> statement-breakpoint
DROP TABLE "member" CASCADE;--> statement-breakpoint
DROP TABLE "organization" CASCADE;--> statement-breakpoint
DROP TABLE "passkey" CASCADE;--> statement-breakpoint
DROP TABLE "session" CASCADE;--> statement-breakpoint
DROP TABLE "user" CASCADE;--> statement-breakpoint
DROP TABLE "verification" CASCADE;

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,531 @@
{
"id": "83a779e2-6624-4497-9622-aa949733f6cd",
"prevId": "db7e21fb-ece5-4aee-b587-82deabed69e6",
"version": "7",
"dialect": "postgresql",
"tables": {
"public.aisles": {
"name": "aisles",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true,
"default": "gen_random_uuid()"
},
"store_id": {
"name": "store_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"name": {
"name": "name",
"type": "varchar(255)",
"primaryKey": false,
"notNull": true
},
"order": {
"name": "order",
"type": "integer",
"primaryKey": false,
"notNull": true
},
"colour": {
"name": "colour",
"type": "varchar(7)",
"primaryKey": false,
"notNull": true
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": false,
"default": "now()"
}
},
"indexes": {},
"foreignKeys": {
"aisles_store_id_stores_id_fk": {
"name": "aisles_store_id_stores_id_fk",
"tableFrom": "aisles",
"tableTo": "stores",
"columnsFrom": [
"store_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.household_invite_codes": {
"name": "household_invite_codes",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true,
"default": "gen_random_uuid()"
},
"household_id": {
"name": "household_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"code": {
"name": "code",
"type": "varchar(8)",
"primaryKey": false,
"notNull": true
},
"created_by": {
"name": "created_by",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"expires_at": {
"name": "expires_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": false,
"default": "now()"
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {
"household_invite_codes_code_unique": {
"name": "household_invite_codes_code_unique",
"nullsNotDistinct": false,
"columns": [
"code"
]
}
},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.items": {
"name": "items",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true,
"default": "gen_random_uuid()"
},
"household_id": {
"name": "household_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"name": {
"name": "name",
"type": "varchar(255)",
"primaryKey": false,
"notNull": true
},
"barcode": {
"name": "barcode",
"type": "varchar(255)",
"primaryKey": false,
"notNull": false
},
"aisle_id": {
"name": "aisle_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"store_id": {
"name": "store_id",
"type": "uuid",
"primaryKey": false,
"notNull": false
},
"alternatives": {
"name": "alternatives",
"type": "json",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": false,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": false,
"default": "now()"
}
},
"indexes": {},
"foreignKeys": {
"items_aisle_id_aisles_id_fk": {
"name": "items_aisle_id_aisles_id_fk",
"tableFrom": "items",
"tableTo": "aisles",
"columnsFrom": [
"aisle_id"
],
"columnsTo": [
"id"
],
"onDelete": "set null",
"onUpdate": "no action"
},
"items_store_id_stores_id_fk": {
"name": "items_store_id_stores_id_fk",
"tableFrom": "items",
"tableTo": "stores",
"columnsFrom": [
"store_id"
],
"columnsTo": [
"id"
],
"onDelete": "set null",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.list_items": {
"name": "list_items",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true,
"default": "gen_random_uuid()"
},
"shopping_list_id": {
"name": "shopping_list_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"item_id": {
"name": "item_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"quantity": {
"name": "quantity",
"type": "integer",
"primaryKey": false,
"notNull": true,
"default": 1
},
"checked": {
"name": "checked",
"type": "boolean",
"primaryKey": false,
"notNull": true,
"default": false
},
"added_by": {
"name": "added_by",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"excluded_from_preset": {
"name": "excluded_from_preset",
"type": "boolean",
"primaryKey": false,
"notNull": true,
"default": false
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": false,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": false,
"default": "now()"
}
},
"indexes": {},
"foreignKeys": {
"list_items_shopping_list_id_shopping_lists_id_fk": {
"name": "list_items_shopping_list_id_shopping_lists_id_fk",
"tableFrom": "list_items",
"tableTo": "shopping_lists",
"columnsFrom": [
"shopping_list_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"list_items_item_id_items_id_fk": {
"name": "list_items_item_id_items_id_fk",
"tableFrom": "list_items",
"tableTo": "items",
"columnsFrom": [
"item_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.scan_history": {
"name": "scan_history",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true,
"default": "gen_random_uuid()"
},
"household_id": {
"name": "household_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"barcode": {
"name": "barcode",
"type": "varchar(255)",
"primaryKey": false,
"notNull": true
},
"item_id": {
"name": "item_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"scanned_at": {
"name": "scanned_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {},
"foreignKeys": {
"scan_history_item_id_items_id_fk": {
"name": "scan_history_item_id_items_id_fk",
"tableFrom": "scan_history",
"tableTo": "items",
"columnsFrom": [
"item_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.shopping_lists": {
"name": "shopping_lists",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true,
"default": "gen_random_uuid()"
},
"household_id": {
"name": "household_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"store_id": {
"name": "store_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"name": {
"name": "name",
"type": "varchar(255)",
"primaryKey": false,
"notNull": true
},
"is_preset": {
"name": "is_preset",
"type": "boolean",
"primaryKey": false,
"notNull": true,
"default": false
},
"auto_reset": {
"name": "auto_reset",
"type": "boolean",
"primaryKey": false,
"notNull": true,
"default": false
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": false,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": false,
"default": "now()"
}
},
"indexes": {},
"foreignKeys": {
"shopping_lists_store_id_stores_id_fk": {
"name": "shopping_lists_store_id_stores_id_fk",
"tableFrom": "shopping_lists",
"tableTo": "stores",
"columnsFrom": [
"store_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.stores": {
"name": "stores",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true,
"default": "gen_random_uuid()"
},
"household_id": {
"name": "household_id",
"type": "uuid",
"primaryKey": false,
"notNull": true
},
"name": {
"name": "name",
"type": "varchar(255)",
"primaryKey": false,
"notNull": true
},
"location": {
"name": "location",
"type": "text",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp",
"primaryKey": false,
"notNull": false,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp",
"primaryKey": false,
"notNull": false,
"default": "now()"
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
}
},
"enums": {},
"schemas": {},
"sequences": {},
"roles": {},
"policies": {},
"views": {},
"_meta": {
"columns": {},
"schemas": {},
"tables": {}
}
}

View file

@ -0,0 +1,20 @@
{
"version": "7",
"dialect": "postgresql",
"entries": [
{
"idx": 0,
"version": "7",
"when": 1782581031633,
"tag": "0000_sour_violations",
"breakpoints": true
},
{
"idx": 1,
"version": "7",
"when": 1782581423495,
"tag": "0001_fresh_daredevil",
"breakpoints": true
}
]
}

View file

@ -1,4 +1,3 @@
export * from '../auth-schema';
import {
pgTable,
text,
@ -15,7 +14,7 @@ import {
*/
export const stores = pgTable('stores', {
id: uuid('id').primaryKey().defaultRandom(),
householdId: uuid('household_id').notNull(), // references better-auth organization
householdId: uuid('household_id').notNull(), // references Clerk organization
name: varchar('name', { length: 255 }).notNull(),
location: text('location'),
createdAt: timestamp('created_at').defaultNow(),
@ -80,7 +79,7 @@ export const listItems = pgTable('list_items', {
.references(() => items.id),
quantity: integer('quantity').notNull().default(1),
checked: boolean('checked').notNull().default(false),
addedBy: uuid('added_by').notNull(), // userId from better-auth
addedBy: uuid('added_by').notNull(), // userId from Clerk
excludedFromPreset: boolean('excluded_from_preset').notNull().default(false),
createdAt: timestamp('created_at').defaultNow(),
updatedAt: timestamp('updated_at').defaultNow(),

View file

@ -1,20 +1,12 @@
import { defineConfig } from 'drizzle-kit';
// Support both SQLite (local development) and PostgreSQL (production)
const isLocal = !process.env.DATABASE_URL;
const dialect = isLocal ? 'sqlite' : 'postgresql';
export default defineConfig({
schema: './db/schema.ts',
out: './db/migrations',
dialect,
dbCredentials: isLocal
? {
url: 'file:./dev.db',
}
: {
url: process.env.DATABASE_URL!,
},
dialect: 'postgresql',
dbCredentials: {
url: process.env.DATABASE_URL!,
},
strict: true,
verbose: true,
});

52
apps/api/lib/ably.ts Normal file
View file

@ -0,0 +1,52 @@
/**
* Ably real-time messaging integration
* Replaces custom WebSocket server for shopping list synchronization
*/
import { Realtime } from 'ably';
let ablyInstance: Realtime | null = null;
/**
* Get or create Ably instance
*/
export function getAblyInstance(): Realtime {
if (!ablyInstance) {
const apiKey = process.env.ABLY_API_KEY;
if (!apiKey) {
throw new Error('ABLY_API_KEY environment variable is not set');
}
ablyInstance = new Realtime(apiKey);
}
return ablyInstance;
}
/**
* Publish real-time update to household channel
*/
export async function publishToHousehold(
householdId: string,
eventType: string,
data: any
) {
const ably = getAblyInstance();
const channel = ably.channels.get(`household:${householdId}`);
await channel.publish(eventType, {
...data,
timestamp: new Date().toISOString(),
});
}
/**
* Household event types
*/
export const HouseholdEvents = {
ITEM_CHECKED: 'item_checked',
ITEM_ADDED: 'item_added',
ITEM_REMOVED: 'item_removed',
LIST_RESET: 'list_reset',
LIST_CREATED: 'list_created',
USER_PRESENCE: 'user_presence',
TYPING_INDICATOR: 'typing_indicator',
} as const;

View file

@ -1,16 +1,11 @@
import { headers } from 'next/headers';
import { auth } from './auth';
import { auth } from '@clerk/nextjs/server';
/**
* Get the current session from request headers
* Used in API routes to validate authentication
* Get the current Clerk user from request
*/
export async function getSession() {
const headerList = await headers();
const session = await auth.api.getSession({
headers: headerList,
});
return session;
export async function getCurrentUser() {
const { userId } = await auth();
return userId;
}
/**
@ -18,25 +13,30 @@ export async function getSession() {
* Throws 401 if not authenticated
*/
export async function requireAuth() {
const session = await getSession();
if (!session?.user) {
const { userId } = await auth();
if (!userId) {
throw new Error('Unauthorized');
}
return session;
return userId;
}
/**
* Get the user's active organization (household)
* For now, returns a placeholder household with the user ID
* In production, this would fetch from better-auth organizations
* Get the user's active organization (household) from Clerk
*/
export async function getActiveHousehold() {
const session = await requireAuth();
// TODO: Implement proper household lookup from better-auth organizations
// For now, return a mock household with user ID
const { userId, orgId } = await auth();
if (!userId) {
throw new Error('Unauthorized');
}
if (!orgId) {
throw new Error('No active household');
}
return {
id: session.user.id,
name: 'My Household',
id: orgId,
userId,
name: 'My Household', // TODO: Fetch actual org name from Clerk
};
}
}

View file

@ -1,39 +0,0 @@
import { betterAuth } from 'better-auth';
import { organization, magicLink } from 'better-auth/plugins';
import { passkey } from '@better-auth/passkey';
import { drizzleAdapter } from 'better-auth/adapters/drizzle';
import { db } from '@/db';
import * as schema from '@/db/schema';
const baseURL = process.env.BETTER_AUTH_URL || 'http://localhost:3001';
export const auth = betterAuth({
baseURL,
database: drizzleAdapter(db, {
provider: 'pg',
schema,
}),
emailAndPassword: {
enabled: true,
},
plugins: [
organization(),
passkey({
rpID: new URL(baseURL).hostname,
rpName: 'Bagsy',
origin: baseURL,
}),
magicLink({
sendMagicLink: async ({ email, url }) => {
console.log(`Magic link for ${email}: ${url}`);
},
}),
],
trustedOrigins: [
baseURL,
'bagsy://',
'bagsy://localhost',
'http://localhost:3001',
'http://192.168.*:3001',
],
});

View file

@ -1,282 +0,0 @@
/**
* WebSocket server for real-time shopping list synchronization
* Handles live updates when items are checked, added, or removed
*/
import { WebSocketServer, WebSocket } from 'ws';
import type { IncomingMessage } from 'http';
import type { Server } from 'http';
// Track connected clients by household
interface ClientConnection {
ws: WebSocket;
userId: string;
householdId: string;
listId?: string;
}
const connectedClients = new Map<string, ClientConnection[]>(); // householdId -> clients
/**
* Initialize WebSocket server
* Call this from your Next.js server initialization
*/
export function initializeWebSocketServer(httpServer: Server) {
const wss = new WebSocketServer({ noServer: true });
// Handle upgrade from HTTP to WebSocket
httpServer.on('upgrade', (request: IncomingMessage, socket, head) => {
if (request.url?.startsWith('/api/ws')) {
wss.handleUpgrade(request, socket, head, (ws) => {
handleNewConnection(ws, request);
});
} else {
socket.destroy();
}
});
wss.on('close', () => {
console.log('WebSocket server closed');
});
return wss;
}
/**
* Handle new WebSocket connection
*/
function handleNewConnection(ws: WebSocket, request: IncomingMessage) {
// Extract auth from URL params or headers
const url = new URL(request.url || '', `http://${request.headers.host}`);
const userId = url.searchParams.get('userId');
const householdId = url.searchParams.get('householdId');
const listId = url.searchParams.get('listId') || undefined;
if (!userId || !householdId) {
console.warn('WebSocket connection rejected: missing userId or householdId');
ws.close(4001, 'Missing auth parameters');
return;
}
const connection: ClientConnection = {
ws,
userId,
householdId,
listId,
};
// Add to connected clients
if (!connectedClients.has(householdId)) {
connectedClients.set(householdId, []);
}
connectedClients.get(householdId)!.push(connection);
console.log(
`[WebSocket] User ${userId} connected to household ${householdId}. Total: ${connectedClients.get(householdId)!.length}`
);
// Send confirmation
ws.send(
JSON.stringify({
type: 'connected',
userId,
householdId,
timestamp: new Date().toISOString(),
})
);
// Handle messages
ws.on('message', (data) => {
try {
const message = JSON.parse(data.toString());
handleWebSocketMessage(connection, message);
} catch (err) {
console.error('[WebSocket] Failed to parse message:', err);
ws.send(
JSON.stringify({
type: 'error',
message: 'Invalid message format',
})
);
}
});
// Handle disconnect
ws.on('close', () => {
handleDisconnect(connection);
});
ws.on('error', (err) => {
console.error('[WebSocket] Connection error:', err);
handleDisconnect(connection);
});
}
/**
* Handle incoming WebSocket messages
*/
function handleWebSocketMessage(connection: ClientConnection, message: any) {
const { type, data } = message;
console.log(`[WebSocket] Message from ${connection.userId}: ${type}`);
switch (type) {
case 'item_checked':
broadcastToHousehold(connection.householdId, {
type: 'item_checked',
listId: data.listId,
itemId: data.itemId,
checked: data.checked,
userId: connection.userId,
timestamp: new Date().toISOString(),
});
break;
case 'item_added':
broadcastToHousehold(connection.householdId, {
type: 'item_added',
listId: data.listId,
item: data.item,
userId: connection.userId,
timestamp: new Date().toISOString(),
});
break;
case 'item_removed':
broadcastToHousehold(connection.householdId, {
type: 'item_removed',
listId: data.listId,
itemId: data.itemId,
userId: connection.userId,
timestamp: new Date().toISOString(),
});
break;
case 'list_reset':
broadcastToHousehold(connection.householdId, {
type: 'list_reset',
listId: data.listId,
excludedItemIds: data.excludedItemIds,
userId: connection.userId,
timestamp: new Date().toISOString(),
});
break;
case 'list_created':
broadcastToHousehold(connection.householdId, {
type: 'list_created',
list: data.list,
userId: connection.userId,
timestamp: new Date().toISOString(),
});
break;
case 'ping':
connection.ws.send(
JSON.stringify({
type: 'pong',
timestamp: new Date().toISOString(),
})
);
break;
case 'user_presence':
// Broadcast user's online status to household
broadcastToHousehold(connection.householdId, {
type: 'userPresence',
userId: connection.userId,
userName: data.userName || 'User',
userEmail: data.userEmail || '',
status: data.status, // 'online' | 'offline' | 'away'
householdId: connection.householdId,
lastSeen: new Date().toISOString(),
});
break;
case 'typing_indicator':
// Broadcast typing status to household
broadcastToHousehold(connection.householdId, {
type: 'typingIndicator',
userId: connection.userId,
userName: data.userName || 'User',
listId: data.listId,
householdId: connection.householdId,
isTyping: data.isTyping,
timestamp: new Date().toISOString(),
});
break;
case 'get_online_users':
// Send list of online users to requester
const onlineUsers =
connectedClients
.get(connection.householdId)
?.filter((c) => c.userId !== connection.userId)
.map((c) => ({ userId: c.userId })) || [];
connection.ws.send(
JSON.stringify({
type: 'online_users',
users: onlineUsers,
})
);
break;
default:
console.warn(`[WebSocket] Unknown message type: ${type}`);
}
}
/**
* Broadcast message to all clients in a household
*/
function broadcastToHousehold(householdId: string, message: any) {
const clients = connectedClients.get(householdId);
if (!clients) return;
let sentCount = 0;
for (const client of clients) {
if (client.ws.readyState === WebSocket.OPEN) {
client.ws.send(JSON.stringify(message));
sentCount++;
}
}
console.log(
`[WebSocket] Broadcast to household ${householdId}: sent to ${sentCount}/${clients.length} clients`
);
}
/**
* Handle client disconnect
*/
function handleDisconnect(connection: ClientConnection) {
const clients = connectedClients.get(connection.householdId);
if (!clients) return;
const index = clients.indexOf(connection);
if (index > -1) {
clients.splice(index, 1);
}
if (clients.length === 0) {
connectedClients.delete(connection.householdId);
}
console.log(
`[WebSocket] User ${connection.userId} disconnected from household ${connection.householdId}. Remaining: ${clients?.length || 0}`
);
}
/**
* Graceful shutdown
*/
export function closeWebSocketServer(wss: WebSocketServer) {
connectedClients.forEach((clients) => {
clients.forEach((client) => {
client.ws.close(1000, 'Server shutting down');
});
});
connectedClients.clear();
wss.close();
console.log('[WebSocket] Server closed');
}

21
apps/api/middleware.ts Normal file
View file

@ -0,0 +1,21 @@
import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server';
/**
* Clerk middleware for route protection
* Protects all API routes except public endpoints
*/
const isPublicRoute = createRouteMatcher([
'/api/auth(.*)',
'/api/health',
'/api/config(.*)', // Allow config endpoints for iOS to fetch keys
]);
export default clerkMiddleware((auth, req) => {
if (!isPublicRoute(req)) {
auth().protect();
}
});
export const config = {
matcher: ['/((?!.*\\..*|_next).*)', '/', '/(api|trpc)(.*)'],
};

View file

@ -11,15 +11,14 @@
"lint": "eslint . --max-warnings 0",
"typecheck": "tsc --noEmit --skipLibCheck",
"db:generate": "drizzle-kit generate",
"db:push": "drizzle-kit push"
"db:push": "dotenv -e .env.local -- drizzle-kit push --force"
},
"dependencies": {
"@better-auth/expo": "^1.1.4",
"@better-auth/passkey": "^1.1.4",
"@clerk/backend": "^3.8.4",
"@clerk/nextjs": "^7.5.9",
"@shop/types": "workspace:*",
"@simplewebauthn/server": "^13.3.0",
"better-auth": "^1.1.4",
"better-sqlite3": "^12.8.0",
"ably": "^2.23.0",
"dotenv": "^17.4.2",
"drizzle-orm": "^0.36.3",
"next": "^16.2.1",
"pg": "^8.13.0",
@ -27,13 +26,13 @@
"react-dom": "^19.0.0"
},
"devDependencies": {
"@types/better-sqlite3": "^7.6.13",
"@types/node": "^20.16.0",
"@types/pg": "^8.12.0",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@typescript-eslint/eslint-plugin": "^8.5.0",
"@typescript-eslint/parser": "^8.5.0",
"dotenv-cli": "^11.0.0",
"drizzle-kit": "^0.31.10",
"eslint": "^9.10.0",
"ts-node": "^10.9.2",

4
apps/api/push-db.sh Normal file
View file

@ -0,0 +1,4 @@
#!/bin/bash
cd "$(dirname "$0")"
export $(cat .env.local | grep -v '^#' | xargs)
bun db:push

View file

@ -3,6 +3,7 @@
"compilerOptions": {
"baseUrl": ".",
"declaration": false,
"declarationMap": false,
"jsx": "preserve",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"paths": {

View file

@ -1,7 +1,6 @@
import Foundation
import Combine
import UIKit
import AuthenticationServices
@MainActor
class AppState: ObservableObject {
@ -11,12 +10,24 @@ class AppState: ObservableObject {
@Published var currentHousehold: Household?
@Published var isLoading = false
@Published var errorMessage: String?
@Published var serverURL: URL = URL(string: "http://localhost:3001") ?? URL(fileURLWithPath: "/")
// TODO: Update this URL for production deployment
// For local development: http://localhost:3001
// For Vercel production: https://your-vercel-app.vercel.app
@Published var serverURL: URL = {
#if DEBUG
return URL(string: "http://localhost:3001") ?? URL(fileURLWithPath: "/")
#else
// TODO: Replace with your Vercel production URL
return URL(string: "https://your-vercel-app.vercel.app") ?? URL(fileURLWithPath: "/")
#endif
}()
private let apiClient = APIClient.shared
private let keychainManager: KeychainManager
private let cacheManager: CacheManager
private let webSocketManager = WebSocketManager.shared
private let ablyManager = AblyRealtimeManager.shared
private let clerkAuth = ClerkAuthManager.shared
init() {
self.keychainManager = KeychainManager.shared
@ -38,96 +49,39 @@ class AppState: ObservableObject {
// MARK: - Session Management
private func checkExistingSession() async {
if let token = await keychainManager.retrieveToken(),
let user = await cacheManager.getCachedUser() {
self.currentUser = user
// Check if user is signed in with Clerk
if clerkAuth.isSignedIn {
self.currentUser = clerkAuth.currentUser
self.isAuthenticated = true
await configureAPIClient(token: token)
if let household = await cacheManager.getCachedHousehold() {
// Try to get active household
if let household = try? await clerkAuth.getActiveHousehold() {
self.currentHousehold = household
await webSocketManager.connect(
householdId: household.id,
userId: user.id,
baseURL: serverURL
)
// Connect to Ably with fetched API key
do {
let ablyKey = try await clerkAuth.fetchAblyKey()
ablyManager.connect(householdId: household.id, apiKey: ablyKey)
} catch {
print("[Ably] Failed to connect: \(error.localizedDescription)")
}
}
}
}
// MARK: - Authentication
func signInWithPasskey() async throws {
isLoading = true
errorMessage = nil
defer { isLoading = false }
// TODO: Implement passkey authentication when Apple Developer account is available
// Passkey functionality temporarily removed per migration requirements
// func signInWithPasskey() async throws {
// isLoading = true
// errorMessage = nil
// defer { isLoading = false }
// // Passkey implementation will be added later
// }
let passkeyHelper = PasskeyHelper.shared
guard passkeyHelper.isAvailable else {
throw PasskeyError.notAvailable
}
do {
let passkeyResult: PasskeySignInResult = try await passkeyHelper.signIn()
let response: APIResponse<AuthResponse> = try await apiClient.post(
"api/auth/sign-in/passkey",
body: passkeyResult
)
if let error = response.error {
throw AuthError.serverError(message: error.message)
}
guard let data = response.data else {
throw AuthError.invalidResponse
}
try await keychainManager.saveToken(data.session.token)
self.currentUser = data.user
self.currentHousehold = data.household
try await cacheManager.cacheUser(data.user)
try await cacheManager.cacheHousehold(data.household)
self.isAuthenticated = true
await webSocketManager.connect(
householdId: data.household.id,
userId: data.user.id,
baseURL: serverURL
)
} catch let error as APIError {
throw AuthError.apiError(error)
}
}
func setupPasskey() async throws {
isLoading = true
errorMessage = nil
defer { isLoading = false }
guard let user = currentUser else {
throw AuthError.invalidResponse
}
let passkeyHelper = PasskeyHelper.shared
guard passkeyHelper.isAvailable else {
throw PasskeyError.notAvailable
}
do {
let passkeyResult: PasskeyRegistrationResult = try await passkeyHelper.register(userId: user.id, email: user.email)
let response: APIResponse<SuccessResponse> = try await apiClient.post(
"api/auth/passkey/add-passkey",
body: passkeyResult
)
if let error = response.error {
throw AuthError.serverError(message: error.message)
}
} catch let error as APIError {
throw AuthError.apiError(error)
}
}
// func setupPasskey() async throws {
// // Passkey setup will be added later
// }
func authenticate(email: String, password: String) async throws {
isLoading = true
@ -136,52 +90,20 @@ class AppState: ObservableObject {
do {
// Try sign in first
let signInPayload = SignInPayload(email: email, password: password)
let signInResponse: APIResponse<AuthResponse> = try await apiClient.post("api/auth/sign-in/email", body: signInPayload)
// If sign in succeeds, use that response
if let authData = signInResponse.data, signInResponse.error == nil {
return try await _completeAuthentication(authData)
try await clerkAuth.signIn(email: email, password: password)
self.currentUser = clerkAuth.currentUser
self.isAuthenticated = true
print("[Auth] Sign-in succeeded")
} catch {
print("[Auth] Sign-in failed: \(error), attempting sign-up as fallback")
do {
let displayName = email.split(separator: "@").first.map(String.init) ?? email
try await clerkAuth.signUp(email: email, password: password, name: displayName)
self.currentUser = clerkAuth.currentUser
self.isAuthenticated = true
} catch {
throw AuthError.apiError(APIError.unknown(error.localizedDescription))
}
// If sign in fails with user not found, try sign up
let displayName = email.split(separator: "@").first.map(String.init) ?? email
let signUpPayload = SignUpPayload(email: email, password: password, name: displayName)
let signUpResponse: APIResponse<AuthResponse> = try await apiClient.post("api/auth/sign-up/email", body: signUpPayload)
if let error = signUpResponse.error {
throw AuthError.serverError(message: error.message)
}
guard let authData = signUpResponse.data else {
throw AuthError.invalidResponse
}
try await _completeAuthentication(authData)
} catch let error as APIError {
throw AuthError.apiError(error)
}
}
private func _completeAuthentication(_ authData: AuthResponse) async throws {
try await keychainManager.saveToken(authData.session.token)
self.currentUser = authData.user
self.currentHousehold = authData.household
try await cacheManager.cacheUser(authData.user)
if let household = authData.household {
try await cacheManager.cacheHousehold(household)
await webSocketManager.connect(
householdId: household.id,
userId: authData.user.id,
baseURL: serverURL
)
}
self.isAuthenticated = true
// Set token in PasskeyHelper and setup passkey if household exists
PasskeyHelper.shared.setAuthToken(authData.session.token)
if authData.household != nil {
try await setupPasskey()
}
}
@ -190,31 +112,16 @@ class AppState: ObservableObject {
errorMessage = nil
defer { isLoading = false }
let payload = CreateHouseholdPayload(name: name)
do {
let response: APIResponse<Household> = try await apiClient.post("households", body: payload)
if let error = response.error {
throw AuthError.serverError(message: error.message)
}
guard let household = response.data else {
throw AuthError.invalidResponse
}
let household = try await clerkAuth.createHousehold(name: name)
self.currentHousehold = household
try await cacheManager.cacheHousehold(household)
if let user = currentUser {
await webSocketManager.connect(
householdId: household.id,
userId: user.id,
baseURL: serverURL
)
}
} catch let error as APIError {
throw AuthError.apiError(error)
// Connect to Ably with fetched API key
let ablyKey = try await clerkAuth.fetchAblyKey()
ablyManager.connect(householdId: household.id, apiKey: ablyKey)
} catch {
throw AuthError.serverError(error.localizedDescription)
}
}
@ -223,31 +130,16 @@ class AppState: ObservableObject {
errorMessage = nil
defer { isLoading = false }
let payload = JoinHouseholdPayload(code: code)
do {
let response: APIResponse<Household> = try await apiClient.post("households/join", body: payload)
if let error = response.error {
throw AuthError.serverError(message: error.message)
}
guard let household = response.data else {
throw AuthError.invalidResponse
}
let household = try await clerkAuth.joinHousehold(code: code)
self.currentHousehold = household
try await cacheManager.cacheHousehold(household)
if let user = currentUser {
await webSocketManager.connect(
householdId: household.id,
userId: user.id,
baseURL: serverURL
)
}
} catch let error as APIError {
throw AuthError.apiError(error)
// Connect to Ably with fetched API key
let ablyKey = try await clerkAuth.fetchAblyKey()
ablyManager.connect(householdId: household.id, apiKey: ablyKey)
} catch {
throw AuthError.serverError(error.localizedDescription)
}
}
@ -256,7 +148,8 @@ class AppState: ObservableObject {
errorMessage = nil
defer { isLoading = false }
webSocketManager.disconnect()
ablyManager.disconnect()
await apiClient.setToken(nil)
try await keychainManager.clearAll()
await cacheManager.clearAll()
self.currentUser = nil
@ -270,15 +163,39 @@ class AppState: ObservableObject {
self.serverURL = url
self.serverURLConfigured = true
UserDefaults.standard.set(url.absoluteString, forKey: "serverURL")
PasskeyHelper.shared.relyingPartyID = url.host ?? "localhost"
PasskeyHelper.shared.serverBaseURL = url.absoluteString.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
Task {
await apiClient.setBaseURL(url)
}
}
private func configureAPIClient(token: String) async {
await apiClient.setBaseURL(serverURL)
func signInWithSocial(provider: String) async throws {
isLoading = true
errorMessage = nil
defer { isLoading = false }
let oauthProvider: OAuthProvider
switch provider.lowercased() {
case "google":
oauthProvider = .google
case "discord":
oauthProvider = .discord
default:
throw AuthError.notImplemented
}
try await clerkAuth.signInWithOAuth(provider: oauthProvider)
self.currentUser = clerkAuth.currentUser
self.isAuthenticated = true
}
private func fetchCurrentUser() async {
do {
// Assuming there's an endpoint to get the current user session
let response: AuthResponse = try await apiClient.get("api/auth/get-session")
try await _completeAuthentication(response)
} catch {
print("[Auth] Failed to fetch current user: \(error)")
}
}
}
@ -296,13 +213,10 @@ struct SignInPayload: Codable {
}
struct AuthResponse: Codable {
let token: String
let user: User
let household: Household?
let session: Session
}
struct Session: Codable {
let token: String
let redirect: Bool?
}
struct CreateHouseholdPayload: Codable {
@ -348,189 +262,6 @@ extension Data {
}
}
// MARK: - Passkey Helper
class PasskeyHelper: NSObject, ObservableObject, ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {
static let shared = PasskeyHelper()
var relyingPartyID: String = "localhost"
var serverBaseURL: String = "http://localhost:3001"
private var authToken: String?
var isAvailable: Bool {
if #available(iOS 16.0, *) { return true }
return false
}
private var authContinuation: CheckedContinuation<ASAuthorizationPlatformPublicKeyCredentialAssertion, Error>?
private var regContinuation: CheckedContinuation<ASAuthorizationPlatformPublicKeyCredentialRegistration, Error>?
func setAuthToken(_ token: String) {
self.authToken = token
}
func signIn() async throws -> PasskeySignInResult {
guard #available(iOS 16.0, *) else { throw PasskeyError.notAvailable }
let options = try await fetchOptions(path: "generate-authentication-options")
let challengeData: Data = {
var b64 = options.challenge.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
let rem = b64.count % 4; if rem != 0 { b64 += String(repeating: "=", count: 4 - rem) }
return Data(base64Encoded: b64) ?? Data()
}()
let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: relyingPartyID)
let request = provider.createCredentialAssertionRequest(challenge: challengeData)
let assertion = try await withCheckedThrowingContinuation { continuation in
self.authContinuation = continuation
let controller = ASAuthorizationController(authorizationRequests: [request])
controller.delegate = self
controller.presentationContextProvider = self
controller.performRequests()
}
return PasskeySignInResult(
id: assertion.credentialID.base64URLEncoded(),
rawId: assertion.credentialID.base64URLEncoded(),
response: AssertionResponse(
clientDataJSON: assertion.rawClientDataJSON.base64URLEncoded(),
authenticatorData: assertion.rawAuthenticatorData.base64URLEncoded(),
signature: assertion.signature.base64URLEncoded(),
userHandle: assertion.userID?.base64URLEncoded()
),
type: "public-key"
)
}
func register(userId: String, email: String) async throws -> PasskeyRegistrationResult {
guard #available(iOS 16.0, *) else { throw PasskeyError.notAvailable }
let options = try await fetchRegistrationOptions()
let challengeData: Data = {
var b64 = options.challenge.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
let rem = b64.count % 4; if rem != 0 { b64 += String(repeating: "=", count: 4 - rem) }
return Data(base64Encoded: b64) ?? Data()
}()
let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: relyingPartyID)
let request = provider.createCredentialRegistrationRequest(
challenge: challengeData,
name: email,
userID: Data(userId.utf8)
)
let registration = try await withCheckedThrowingContinuation { continuation in
self.regContinuation = continuation
let controller = ASAuthorizationController(authorizationRequests: [request])
controller.delegate = self
controller.presentationContextProvider = self
controller.performRequests()
}
return PasskeyRegistrationResult(
id: registration.credentialID.base64URLEncoded(),
rawId: registration.credentialID.base64URLEncoded(),
response: AttestationResponse(
clientDataJSON: registration.rawClientDataJSON.base64URLEncoded(),
attestationObject: registration.rawAttestationObject?.base64URLEncoded() ?? ""
),
type: "public-key"
)
}
private func fetchOptions(path: String) async throws -> WebAuthnOptionsResponse {
let url = URL(string: "\(serverBaseURL)/api/auth/passkey/\(path)")!
var req = URLRequest(url: url)
req.httpMethod = "GET"
let (data, _) = try await URLSession.shared.data(for: req)
return try JSONDecoder().decode(WebAuthnOptionsResponse.self, from: data)
}
private func fetchRegistrationOptions() async throws -> WebAuthnOptionsResponse {
guard let token = authToken else {
throw PasskeyError.invalidCredential
}
let url = URL(string: "\(serverBaseURL)/api/auth/passkey/add-passkey")!
var req = URLRequest(url: url)
req.httpMethod = "POST"
req.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
let (data, _) = try await URLSession.shared.data(for: req)
return try JSONDecoder().decode(WebAuthnOptionsResponse.self, from: data)
}
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
if #available(iOS 16.0, *) {
if let assertion = authorization.credential as? ASAuthorizationPlatformPublicKeyCredentialAssertion {
authContinuation?.resume(returning: assertion)
authContinuation = nil
} else if let registration = authorization.credential as? ASAuthorizationPlatformPublicKeyCredentialRegistration {
regContinuation?.resume(returning: registration)
regContinuation = nil
}
}
}
func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
let passkeyError: PasskeyError
if let authError = error as? ASAuthorizationError {
switch authError.code {
case .canceled: passkeyError = .userCancelled
default: passkeyError = .invalidCredential
}
} else {
passkeyError = .invalidCredential
}
authContinuation?.resume(throwing: passkeyError)
authContinuation = nil
regContinuation?.resume(throwing: passkeyError)
regContinuation = nil
}
func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
UIApplication.shared.connectedScenes
.compactMap { $0 as? UIWindowScene }
.flatMap { $0.windows }
.first { $0.isKeyWindow } ?? UIWindow()
}
}
// MARK: - Passkey Types
struct WebAuthnOptionsResponse: Codable {
let challenge: String
}
struct PasskeySignInResult: Codable {
let id: String
let rawId: String
let response: AssertionResponse
let type: String
}
struct AssertionResponse: Codable {
let clientDataJSON: String
let authenticatorData: String
let signature: String
let userHandle: String?
}
struct PasskeyRegistrationResult: Codable {
let id: String
let rawId: String
let response: AttestationResponse
let type: String
}
struct AttestationResponse: Codable {
let clientDataJSON: String
let attestationObject: String
}
enum PasskeyError: LocalizedError {
case invalidCredential, userCancelled, notAvailable
var errorDescription: String? {
switch self {
case .invalidCredential: return "Invalid passkey credential"
case .userCancelled: return "Passkey cancelled"
case .notAvailable: return "Passkeys require iOS 16+"
}
}
}
// MARK: - Presence Helper
class PresenceHelper: ObservableObject {

View file

@ -5,6 +5,7 @@ actor APIClient {
private var baseURL: URL
private let session: URLSession
private var token: String?
nonisolated private static let decoder: JSONDecoder = {
let decoder = JSONDecoder()
@ -34,6 +35,10 @@ actor APIClient {
func setBaseURL(_ url: URL) {
self.baseURL = url
}
func setToken(_ token: String?) {
self.token = token
}
// MARK: - Public Methods
@ -41,7 +46,7 @@ actor APIClient {
let url = baseURL.appendingPathComponent(endpoint)
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.addHeaders()
request.addHeaders(token: token)
return try await perform(request)
}
@ -50,12 +55,16 @@ actor APIClient {
let url = baseURL.appendingPathComponent(endpoint)
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addHeaders()
request.addHeaders(token: token)
if let body = body {
request.httpBody = try Self.encoder.encode(body)
if let bodyString = String(data: request.httpBody!, encoding: .utf8) {
print("[API] POST \(url.absoluteString) body: \(bodyString)")
}
} else {
print("[API] POST \(url.absoluteString)")
}
return try await perform(request)
}
@ -63,7 +72,7 @@ actor APIClient {
let url = baseURL.appendingPathComponent(endpoint)
var request = URLRequest(url: url)
request.httpMethod = "PUT"
request.addHeaders()
request.addHeaders(token: token)
if let body = body {
request.httpBody = try Self.encoder.encode(body)
@ -76,7 +85,7 @@ actor APIClient {
let url = baseURL.appendingPathComponent(endpoint)
var request = URLRequest(url: url)
request.httpMethod = "DELETE"
request.addHeaders()
request.addHeaders(token: token)
return try await perform(request)
}
@ -85,11 +94,13 @@ actor APIClient {
private func perform<T: Decodable>(_ request: URLRequest) async throws -> T {
let (data, response) = try await session.data(for: request)
guard let httpResponse = response as? HTTPURLResponse else {
throw APIError.invalidResponse
}
print("[API] Response: \(httpResponse.statusCode) from \(httpResponse.url?.absoluteString ?? "unknown")")
switch httpResponse.statusCode {
case 200...299:
// Success
@ -124,8 +135,11 @@ actor APIClient {
struct Empty: Codable {}
extension URLRequest {
mutating func addHeaders() {
mutating func addHeaders(token: String?) {
setValue("application/json", forHTTPHeaderField: "Content-Type")
setValue("application/json", forHTTPHeaderField: "Accept")
if let token = token {
setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
}
}
}

View file

@ -0,0 +1,208 @@
import Foundation
import Combine
import Ably
enum AblyStatus {
case disconnected
case connecting
case connected
case failed(Error)
}
@MainActor
class AblyRealtimeManager: ObservableObject {
static let shared = AblyRealtimeManager()
@Published var isConnected = false
@Published var connectionStatus: AblyStatus = .disconnected
private var realtime: ARTRealtime?
private var channel: ARTChannel?
private var householdId: String?
@Published var lastMessage: AblyMessage?
@Published var messagePublisher = PassthroughSubject<AblyMessage, Never>()
private init() {}
// MARK: - Connection Management
func connect(householdId: String, apiKey: String) {
self.householdId = householdId
connectionStatus = .connecting
// Initialize Ably realtime client
realtime = ARTRealtime(key: apiKey)
guard let realtime = realtime else {
connectionStatus = .failed(AblyError.initializationFailed)
return
}
// Set up connection state changes
realtime.connection.on { [weak self] stateChange in
guard let self = self else { return }
switch stateChange.current {
case .connected:
self.isConnected = true
self.connectionStatus = .connected
self.subscribeToChannel()
case .connecting:
self.connectionStatus = .connecting
case .disconnected, .closed, .suspended:
self.isConnected = false
self.connectionStatus = .disconnected
case .failed:
self.isConnected = false
if let error = stateChange.error {
self.connectionStatus = .failed(error)
} else {
self.connectionStatus = .disconnected
}
default:
break
}
}
}
func disconnect() {
channel?.unsubscribe()
channel = nil
realtime?.close()
realtime = nil
isConnected = false
connectionStatus = .disconnected
householdId = nil
}
// MARK: - Channel Subscription
private func subscribeToChannel() {
guard let householdId = householdId,
let realtime = realtime else {
return
}
let channelName = "household:\(householdId)"
channel = realtime.channels.get(channelName)
// Subscribe to all messages on the household channel
channel?.subscribe { [weak self] message in
guard let self = self else { return }
if let data = message.data as? [String: Any],
let eventName = message.name {
self.handleAblyMessage(eventName: eventName, data: data)
}
}
}
// MARK: - Message Handling
private func handleAblyMessage(eventName: String, data: [String: Any]) {
guard let eventData = try? JSONSerialization.data(withJSONObject: data),
let jsonString = String(data: eventData, encoding: .utf8) else {
return
}
// Map Ably event names to our message types
let messageType: AblyMessageType
switch eventName {
case "item_checked":
messageType = .itemChecked
case "item_added":
messageType = .itemAdded
case "item_removed":
messageType = .itemRemoved
case "list_reset":
messageType = .listReset
case "list_created":
messageType = .listCreated
case "user_presence":
messageType = .userPresence
case "typing_indicator":
messageType = .typingIndicator
default:
messageType = .unknown
}
let ablyMessage = AblyMessage(
type: messageType,
data: jsonString,
timestamp: (data["timestamp"] as? String).flatMap { ISO8601DateFormatter().date(from: $0) } ?? Date()
)
self.lastMessage = ablyMessage
self.messagePublisher.send(ablyMessage)
}
// MARK: - Send Messages (if needed for presence/typing)
func publishPresence(status: String, userName: String, userEmail: String) {
guard let channel = channel else { return }
let messageData: [String: Any] = [
"status": status,
"userName": userName,
"userEmail": userEmail,
"householdId": householdId ?? "",
"lastSeen": ISO8601DateFormatter().string(from: Date())
]
channel.publish("user_presence", data: messageData)
}
func publishTypingIndicator(isTyping: Bool, listId: String, userName: String) {
guard let channel = channel else { return }
let messageData: [String: Any] = [
"isTyping": isTyping,
"listId": listId,
"userName": userName,
"householdId": householdId ?? "",
"timestamp": ISO8601DateFormatter().string(from: Date())
]
channel.publish("typing_indicator", data: messageData)
}
}
// MARK: - Ably Message Types
enum AblyMessageType: String {
case itemChecked
case itemAdded
case itemRemoved
case listReset
case listCreated
case userPresence
case typingIndicator
case unknown
}
struct AblyMessage {
let type: AblyMessageType
let data: String
let timestamp: Date
}
// MARK: - Ably Errors
enum AblyError: LocalizedError {
case initializationFailed
case connectionFailed
case channelSubscriptionFailed
var errorDescription: String? {
switch self {
case .initializationFailed:
return "Failed to initialize Ably client"
case .connectionFailed:
return "Failed to connect to Ably"
case .channelSubscriptionFailed:
return "Failed to subscribe to channel"
}
}
}

View file

@ -0,0 +1,220 @@
import Foundation
import ClerkSDK
import Combine
@MainActor
class ClerkAuthManager: ObservableObject {
static let shared = ClerkAuthManager()
@Published var isSignedIn = false
@Published var currentUser: User?
@Published var currentHousehold: Household?
@Published var isLoading = false
@Published var errorMessage: String?
private let clerkClient: Clerk
private var cancellables = Set<AnyCancellable>()
private var ablyApiKey: String?
// TODO: Configure with your Clerk publishable key
private let publishableKey = "pk_test_cG9saXNoZWQtaW1wYWxhLTIzLmNsZXJrLmFjY291bnRzLmRldiQ"
private init() {
// Initialize Clerk with your publishable key
self.clerkClient = Clerk.create(publishableKey: publishableKey)
// Set up auth state listener
clerkClient.auth.addListener { [weak self] event in
guard let self = self else { return }
switch event {
case .signedIn:
self.isSignedIn = true
if let user = self.clerkClient.user {
self.currentUser = User(
id: user.id,
email: user.primaryEmailAddress?.emailAddress ?? "",
name: user.firstName ?? user.username ?? "",
householdId: nil // Will be set after organization selection
)
}
case .signedOut:
self.isSignedIn = false
self.currentUser = nil
self.currentHousehold = nil
case .tokenUpdated:
// Handle token refresh if needed
break
case .clientCreated:
break
@unknown default:
break
}
}
}
// MARK: - Email/Password Authentication
func signIn(email: String, password: String) async throws {
isLoading = true
errorMessage = nil
defer { isLoading = false }
try await clerkClient.signIn.create(
emailAddress: email,
password: password
)
// Check if user needs to complete sign-up
if let firstFactor = clerkClient.signIn.supportedFirstFactors.first {
try await clerkClient.signIn.attemptFirstFactor(
strategy: .emailCode,
emailAddressId: firstFactor.emailAddressId
)
}
// Set active session
try await clerkClient.signIn.setActive()
}
func signUp(email: String, password: String, name: String) async throws {
isLoading = true
errorMessage = nil
defer { isLoading = false }
try await clerkClient.signUp.create(
emailAddress: email,
password: password
)
// Attempt to prepare the first verification strategy
try await clerkClient.signUp.prepareEmailAddressVerification()
// Complete sign-up
try await clerkClient.signUp.attemptEmailAddressVerification(
code: "" // For email code verification
)
// Update user name
if let user = clerkClient.user {
try await user.update(
firstName: name,
lastName: ""
)
}
// Set active session
try await clerkClient.signUp.setActive()
}
// MARK: - OAuth Authentication
func signInWithOAuth(provider: OAuthProvider) async throws {
isLoading = true
errorMessage = nil
defer { isLoading = false }
try await clerkClient.signIn.create(oauthProvider: provider)
try await clerkClient.signIn.setActive()
}
// MARK: - Sign Out
func signOut() async throws {
isLoading = true
errorMessage = nil
defer { isLoading = false }
try await clerkClient.signOut()
}
// MARK: - Household/Organization Management
func createHousehold(name: String) async throws -> Household {
isLoading = true
errorMessage = nil
defer { isLoading = false }
guard let user = clerkClient.user else {
throw AuthError.notAuthenticated
}
// Create organization via Clerk Backend API
// This requires a backend call to your Clerk-enabled API
// For now, we'll call your existing API endpoint
let household = try await APIClient.shared.post("api/households", body: ["name": name])
self.currentHousehold = household
return household
}
func joinHousehold(code: String) async throws -> Household {
isLoading = true
errorMessage = nil
defer { isLoading = false }
// Join household via your API endpoint
let household = try await APIClient.shared.post("api/households/join", body: ["code": code])
self.currentHousehold = household
return household
}
// MARK: - Get Active Organization
func getActiveHousehold() async throws -> Household? {
guard let user = clerkClient.user else {
throw AuthError.notAuthenticated
}
// Get user's active organization from Clerk
// This requires backend API call to fetch organization details
let household: Household? = try? await APIClient.shared.get("api/households")
self.currentHousehold = household
return household
}
// MARK: - Ably Key Management
func fetchAblyKey() async throws -> String {
if let cachedKey = ablyApiKey {
return cachedKey
}
let response: AblyKeyResponse = try await APIClient.shared.get("api/config/ably-key")
self.ablyApiKey = response.ablyKey
return response.ablyKey
}
}
struct AblyKeyResponse: Codable {
let ablyKey: String
}
enum OAuthProvider: String {
case google = "oauth_google"
case discord = "oauth_discord"
// TODO: Add Apple when Apple Developer account is available
// case apple = "oauth_apple"
}
enum AuthError: LocalizedError {
case notAuthenticated
case invalidCredentials
case networkError
case serverError(String)
var errorDescription: String? {
switch self {
case .notAuthenticated:
return "Not authenticated"
case .invalidCredentials:
return "Invalid email or password"
case .networkError:
return "Network error occurred"
case .serverError(let message):
return message
}
}
}

View file

@ -1,280 +0,0 @@
import Foundation
import AuthenticationServices
import CryptoKit
/// Manages WebAuthn/Passkey registration and authentication using native iOS APIs
@MainActor
class PasskeyManager: NSObject, ObservableObject {
static let shared: PasskeyManager = {
let instance = PasskeyManager()
return instance
}()
@Published var isAvailable = false
override init() {
super.init()
checkPasskeyAvailability()
}
private static let initOnce: () = {
_ = PasskeyManager.shared
}()
// MARK: - Availability Check
private func checkPasskeyAvailability() {
isAvailable = ASAuthorizationPlatformPublicKeyCredentialProvider.isUserVerificationPreferred
}
// MARK: - Passkey Sign-In
/// Initiate passkey sign-in flow
func signIn(email: String, presentationAnchor: ASPresentationAnchor) async throws -> PasskeySignInResponse {
let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: "bagsy.local")
// Create a random challenge (in production, this comes from server)
let challenge = generateChallenge()
let request = provider.createSignInRequest(challenge: challenge)
request.allowedCredentials = [] // Allow all registered passkeys
let controller = ASAuthorizationController(authorizationRequests: [request])
controller.presentationContextProvider = self
return try await performAuthorization(controller)
}
// MARK: - Passkey Registration
/// Initiate passkey registration after email/password signup
func register(
userId: String,
email: String,
displayName: String,
presentationAnchor: ASPresentationAnchor
) async throws -> PasskeyRegistrationResponse {
let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: "bagsy.local")
// Create a random challenge (in production, this comes from server)
let challenge = generateChallenge()
let request = provider.createRegistrationRequest(
challenge: challenge,
name: email,
userID: Data(userId.utf8)
)
// Configure for iCloud Keychain
request.residentKeyPreference = .preferred
let controller = ASAuthorizationController(authorizationRequests: [request])
controller.presentationContextProvider = self
return try await performRegistration(controller)
}
// MARK: - Private Helpers
private func generateChallenge() -> Data {
var bytes = [UInt8](repeating: 0, count: 32)
_ = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes)
return Data(bytes)
}
private func performAuthorization(
_ controller: ASAuthorizationController
) async throws -> PasskeySignInResponse {
return try await withCheckedThrowingContinuation { continuation in
let delegate = PasskeyAuthorizationDelegate { result in
switch result {
case .success(let response):
continuation.resume(returning: response)
case .failure(let error):
continuation.resume(throwing: error)
}
}
controller.delegate = delegate
controller.performRequests()
// Keep delegate alive
objc_setAssociatedObject(
controller,
"PasskeyAuthorizationDelegate",
delegate,
.OBJC_ASSOCIATION_RETAIN
)
}
}
private func performRegistration(
_ controller: ASAuthorizationController
) async throws -> PasskeyRegistrationResponse {
return try await withCheckedThrowingContinuation { continuation in
let delegate = PasskeyRegistrationDelegate { result in
switch result {
case .success(let response):
continuation.resume(returning: response)
case .failure(let error):
continuation.resume(throwing: error)
}
}
controller.delegate = delegate
controller.performRequests()
// Keep delegate alive
objc_setAssociatedObject(
controller,
"PasskeyRegistrationDelegate",
delegate,
.OBJC_ASSOCIATION_RETAIN
)
}
}
}
// MARK: - Presentation Context Provider
extension PasskeyManager: ASAuthorizationControllerPresentationContextProviding {
func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
guard let window = UIApplication.shared.connectedScenes
.compactMap({ $0 as? UIWindowScene })
.first?
.windows
.first(where: { $0.isKeyWindow }) else {
return ASPresentationAnchor()
}
return window
}
}
// MARK: - Authorization Delegate
private class PasskeyAuthorizationDelegate: NSObject, ASAuthorizationControllerDelegate {
let completion: (Result<PasskeySignInResponse, Error>) -> Void
init(completion: @escaping (Result<PasskeySignInResponse, Error>) -> Void) {
self.completion = completion
}
func authorizationController(
controller: ASAuthorizationController,
didCompleteWithAuthorization authorization: ASAuthorization
) {
guard let credential = authorization.credential as? ASAuthorizationPlatformPublicKeyCredentialAssertion else {
completion(.failure(PasskeyError.invalidCredential))
return
}
let response = PasskeySignInResponse(
credentialID: credential.credentialID,
authenticatorData: credential.authenticatorData,
clientDataJSON: credential.clientDataJSON,
signature: credential.signature
)
completion(.success(response))
}
func authorizationController(
controller: ASAuthorizationController,
didCompleteWithError error: Error
) {
completion(.failure(error))
}
}
// MARK: - Registration Delegate
private class PasskeyRegistrationDelegate: NSObject, ASAuthorizationControllerDelegate {
let completion: (Result<PasskeyRegistrationResponse, Error>) -> Void
init(completion: @escaping (Result<PasskeyRegistrationResponse, Error>) -> Void) {
self.completion = completion
}
func authorizationController(
controller: ASAuthorizationController,
didCompleteWithAuthorization authorization: ASAuthorization
) {
guard let credential = authorization.credential as? ASAuthorizationPlatformPublicKeyCredentialRegistration else {
completion(.failure(PasskeyError.invalidCredential))
return
}
let response = PasskeyRegistrationResponse(
credentialID: credential.credentialID,
attestationObject: credential.attestationObject,
clientDataJSON: credential.clientDataJSON
)
completion(.success(response))
}
func authorizationController(
controller: ASAuthorizationController,
didCompleteWithError error: Error
) {
completion(.failure(error))
}
}
// MARK: - Types
struct PasskeySignInResponse: Codable {
let credentialID: Data
let authenticatorData: Data
let clientDataJSON: Data
let signature: Data
enum CodingKeys: String, CodingKey {
case credentialID = "id"
case authenticatorData
case clientDataJSON
case signature
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(credentialID.base64EncodedString(), forKey: .credentialID)
try container.encode(authenticatorData.base64EncodedString(), forKey: .authenticatorData)
try container.encode(clientDataJSON.base64EncodedString(), forKey: .clientDataJSON)
try container.encode(signature.base64EncodedString(), forKey: .signature)
}
}
struct PasskeyRegistrationResponse: Codable {
let credentialID: Data
let attestationObject: Data
let clientDataJSON: Data
enum CodingKeys: String, CodingKey {
case credentialID = "id"
case attestationObject
case clientDataJSON
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(credentialID.base64EncodedString(), forKey: .credentialID)
try container.encode(attestationObject.base64EncodedString(), forKey: .attestationObject)
try container.encode(clientDataJSON.base64EncodedString(), forKey: .clientDataJSON)
}
}
// MARK: - Objc helpers
import ObjectiveC
private func objc_setAssociatedObject(
_ object: Any,
_ key: String,
_ value: Any,
_ policy: objc_AssociationPolicy
) {
let keyPointer = UnsafeMutablePointer<Int8>.allocate(capacity: key.count)
keyPointer.initialize(repeating: 0, count: key.count)
objc_setAssociatedObject(object, keyPointer, value, policy)
}

View file

@ -5,7 +5,6 @@ struct SignInView: View {
@State private var email = ""
@State private var password = ""
@State private var showError = false
@State private var usePasskey = false
@FocusState private var focusedField: FocusedField?
enum FocusedField {
@ -42,105 +41,86 @@ struct SignInView: View {
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.bottom, 20)
if usePasskey {
// Passkey Option
VStack(spacing: 16) {
Image(systemName: "faceid")
.font(.system(size: 48))
.foregroundColor(bagsyOrange)
Text("Use Passkey")
.font(.headline)
// Email & Password Form
VStack(spacing: 16) {
VStack(alignment: .leading, spacing: 8) {
Text("Email")
.font(.subheadline)
.fontWeight(.semibold)
.foregroundColor(.black)
Text("Faster and more secure")
.font(.caption)
.foregroundColor(.gray)
Button(action: authenticateWithPasskey) {
if appState.isLoading {
ProgressView().tint(.white)
} else {
Text("Continue with Passkey")
.fontWeight(.semibold)
}
}
.frame(maxWidth: .infinity)
.frame(height: 56)
.background(bagsyOrange)
.foregroundColor(.white)
.cornerRadius(16)
.disabled(appState.isLoading)
Button(action: { usePasskey = false }) {
Text("Use Email & Password")
.foregroundColor(bagsyOrange)
.fontWeight(.semibold)
}
TextField("you@example.com", text: $email)
.keyboardType(.emailAddress)
.textInputAutocapitalization(.never)
.autocorrectionDisabled(true)
.focused($focusedField, equals: .email)
.padding(14)
.background(Color.white)
.cornerRadius(16)
.overlay(
RoundedRectangle(cornerRadius: 16)
.stroke(bagsyOrange, lineWidth: focusedField == .email ? 2 : 0)
)
}
.padding(.bottom, 20)
} else {
// Email & Password Form
VStack(spacing: 16) {
VStack(alignment: .leading, spacing: 8) {
Text("Email")
.font(.subheadline)
.fontWeight(.semibold)
.foregroundColor(.black)
TextField("you@example.com", text: $email)
.keyboardType(.emailAddress)
.textInputAutocapitalization(.never)
.autocorrectionDisabled(true)
.focused($focusedField, equals: .email)
.padding(14)
.background(Color.white)
.cornerRadius(16)
.overlay(
RoundedRectangle(cornerRadius: 16)
.stroke(bagsyOrange, lineWidth: focusedField == .email ? 2 : 0)
)
}
VStack(alignment: .leading, spacing: 8) {
Text("Password")
.font(.subheadline)
.fontWeight(.semibold)
.foregroundColor(.black)
SecureField("At least 8 characters", text: $password)
.focused($focusedField, equals: .password)
.padding(14)
.background(Color.white)
.cornerRadius(16)
.overlay(
RoundedRectangle(cornerRadius: 16)
.stroke(bagsyOrange, lineWidth: focusedField == .password ? 2 : 0)
)
}
VStack(alignment: .leading, spacing: 8) {
Text("Password")
.font(.subheadline)
.fontWeight(.semibold)
.foregroundColor(.black)
SecureField("At least 8 characters", text: $password)
.focused($focusedField, equals: .password)
.padding(14)
.background(Color.white)
.cornerRadius(16)
.overlay(
RoundedRectangle(cornerRadius: 16)
.stroke(bagsyOrange, lineWidth: focusedField == .password ? 2 : 0)
)
}
.padding(.bottom, 20)
}
.padding(.bottom, 20)
// Auth Button
Button(action: authenticate) {
if appState.isLoading {
ProgressView().tint(.white)
} else {
Text("Continue")
.fontWeight(.semibold)
}
}
.frame(maxWidth: .infinity)
.frame(height: 56)
.background(bagsyOrange)
.foregroundColor(.white)
.cornerRadius(16)
.disabled(appState.isLoading || !isFormValid)
Button(action: { usePasskey = true }) {
Text("Use Passkey Instead")
.foregroundColor(bagsyOrange)
// Auth Button
Button(action: authenticate) {
if appState.isLoading {
ProgressView().tint(.white)
} else {
Text("Continue")
.fontWeight(.semibold)
}
}
.frame(maxWidth: .infinity)
.frame(height: 56)
.background(bagsyOrange)
.foregroundColor(.white)
.cornerRadius(16)
.disabled(appState.isLoading || !isFormValid)
// Social Login
HStack {
Rectangle()
.fill(Color.gray.opacity(0.3))
.frame(height: 1)
Text("OR")
.font(.caption)
.foregroundColor(.gray)
Rectangle()
.fill(Color.gray.opacity(0.3))
.frame(height: 1)
}
.padding(.vertical, 10)
HStack(spacing: 16) {
socialButton(title: "Google", icon: "g.circle.fill", color: .red) {
authenticateWithSocial(provider: "google")
}
socialButton(title: "Discord", icon: "bubble.left.and.bubble.right.fill", color: Color(red: 0.35, green: 0.40, blue: 0.94)) {
authenticateWithSocial(provider: "discord")
}
}
// TODO: Add "Sign in with Apple" when Apple Developer account is available
// .disabled(true)
Spacer()
}
@ -159,6 +139,24 @@ struct SignInView: View {
}
}
private func socialButton(title: String, icon: String, color: Color, action: @escaping () -> Void) -> some View {
Button(action: action) {
HStack {
Image(systemName: icon)
Text(title)
}
.frame(maxWidth: .infinity)
.frame(height: 48)
.background(Color.white)
.foregroundColor(.black)
.overlay(
RoundedRectangle(cornerRadius: 12)
.stroke(Color.gray.opacity(0.2), lineWidth: 1)
)
}
.disabled(appState.isLoading)
}
private func authenticate() {
Task {
do {
@ -169,10 +167,10 @@ struct SignInView: View {
}
}
private func authenticateWithPasskey() {
private func authenticateWithSocial(provider: String) {
Task {
do {
try await appState.signInWithPasskey()
try await appState.signInWithSocial(provider: provider)
} catch {
appState.errorMessage = error.localizedDescription
}

View file

@ -31,20 +31,7 @@ class ListDetailViewModel: ObservableObject {
defer { isLoading = false }
do {
let response: APIResponse<ShoppingList> = try await apiClient.get("lists/\(listId)")
if let error = response.error {
throw APIError.serverError(code: error.code, message: error.message)
}
guard let list = response.data else {
// Try cache
if let cached = await cacheManager.getCachedItems(for: listId) {
self.items = cached
organizeBYAisle()
}
throw APIError.invalidResponse
}
let list: ShoppingList = try await apiClient.get("api/lists/\(listId)")
self.list = list
self.items = list.items
@ -85,7 +72,7 @@ class ListDetailViewModel: ObservableObject {
// Send via API
let payload = UpdateListItemPayload(checked: checked)
do {
let _: Empty = try await apiClient.put("lists/\(list?.id ?? "")/items/\(id)", body: payload)
let _: Empty = try await apiClient.put("api/lists/\(list?.id ?? "")/items/\(id)", body: payload)
} catch {
self.error = error as? APIError
}
@ -94,19 +81,10 @@ class ListDetailViewModel: ObservableObject {
func addItem(name: String, aisleId: String?, quantity: Int = 1) async throws {
guard let listId = list?.id else { throw APIError.invalidResponse }
let payload = AddItemPayload(name: name, aisleId: aisleId, quantity: quantity)
let response: APIResponse<ListItem> = try await apiClient.post("lists/\(listId)/items", body: payload)
if let error = response.error {
throw APIError.serverError(code: error.code, message: error.message)
}
guard let item = response.data else {
throw APIError.invalidResponse
}
let item: ListItem = try await apiClient.post("api/lists/\(listId)/items", body: payload)
items.append(item)
organizeBYAisle()
@ -116,8 +94,8 @@ class ListDetailViewModel: ObservableObject {
func removeItem(_ id: String) async throws {
guard let listId = list?.id else { throw APIError.invalidResponse }
let _: Empty = try await apiClient.delete("lists/\(listId)/items/\(id)")
let _: Empty = try await apiClient.delete("api/lists/\(listId)/items/\(id)")
items.removeAll { $0.id == id }
organizeBYAisle()
@ -134,7 +112,7 @@ class ListDetailViewModel: ObservableObject {
}
let payload = UpdateListItemPayload(quantity: quantity)
let _: Empty = try await apiClient.put("lists/\(listId)/items/\(id)", body: payload)
let _: Empty = try await apiClient.put("api/lists/\(listId)/items/\(id)", body: payload)
// Cache
try await cacheManager.cacheItems(items, for: listId)

View file

@ -22,30 +22,18 @@ class ListsViewModel: ObservableObject {
func load(for householdId: String) async {
isLoading = true
defer { isLoading = false }
do {
// Fetch lists from API
let response: APIResponse<[ShoppingList]> = try await apiClient.get("lists")
if let error = response.error {
throw APIError.serverError(code: error.code, message: error.message)
}
guard let lists = response.data else {
// Fallback to cache
if let cached = await cacheManager.getCachedLists(for: householdId) {
self.shoppingLists = cached
}
throw APIError.invalidResponse
}
let lists: [ShoppingList] = try await apiClient.get("api/lists")
// Cache the lists
self.shoppingLists = lists
try await cacheManager.cacheLists(lists, for: householdId)
} catch let apiError as APIError {
self.error = apiError
// Fallback to cache on error
if let cached = await cacheManager.getCachedLists(for: householdId) {
self.shoppingLists = cached
@ -54,45 +42,25 @@ class ListsViewModel: ObservableObject {
self.error = APIError.networkError(error as? URLError ?? URLError(.unknown))
}
}
func createList(name: String, for householdId: String) async throws {
let payload = CreateListPayload(name: name, householdId: householdId)
let response: APIResponse<ShoppingList> = try await apiClient.post("lists", body: payload)
if let error = response.error {
throw APIError.serverError(code: error.code, message: error.message)
}
guard let list = response.data else {
throw APIError.invalidResponse
}
let list: ShoppingList = try await apiClient.post("api/lists", body: payload)
shoppingLists.append(list)
}
func deleteList(_ id: String, for householdId: String) async throws {
let _: Empty = try await apiClient.delete("lists/\(id)")
let _: Empty = try await apiClient.delete("api/lists/\(id)")
shoppingLists.removeAll { $0.id == id }
// Update cache
try await cacheManager.cacheLists(shoppingLists, for: householdId)
}
func loadForgottenItems() async {
do {
let response: APIResponse<[Item]> = try await apiClient.get("items/forgotten")
if let error = response.error {
self.error = APIError.serverError(code: error.code, message: error.message)
return
}
guard let items = response.data else {
self.error = APIError.invalidResponse
return
}
let items: [Item] = try await apiClient.get("api/items/forgotten")
self.forgottenItems = items
} catch let apiError as APIError {
self.error = apiError

View file

@ -22,28 +22,16 @@ class StoresViewModel: ObservableObject {
func load(for householdId: String) async {
isLoading = true
defer { isLoading = false }
do {
let response: APIResponse<[Store]> = try await apiClient.get("stores")
if let error = response.error {
throw APIError.serverError(code: error.code, message: error.message)
}
guard let stores = response.data else {
// Fallback to cache
if let cached = await cacheManager.getCachedStores(for: householdId) {
self.stores = cached
}
throw APIError.invalidResponse
}
let stores: [Store] = try await apiClient.get("api/stores")
self.stores = stores
try await cacheManager.cacheStores(stores, for: householdId)
} catch let apiError as APIError {
self.error = apiError
// Fallback to cache on error
if let cached = await cacheManager.getCachedStores(for: householdId) {
self.stores = cached
@ -52,35 +40,26 @@ class StoresViewModel: ObservableObject {
self.error = APIError.networkError(error as? URLError ?? URLError(.unknown))
}
}
func createStore(name: String, householdId: String) async throws {
let payload = CreateStorePayload(name: name)
let response: APIResponse<Store> = try await apiClient.post("stores", body: payload)
if let error = response.error {
throw APIError.serverError(code: error.code, message: error.message)
}
guard let store = response.data else {
throw APIError.invalidResponse
}
let store: Store = try await apiClient.post("api/stores", body: payload)
stores.append(store)
}
func deleteStore(_ id: String, householdId: String) async throws {
let _: Empty = try await apiClient.delete("stores/\(id)")
let _: Empty = try await apiClient.delete("api/stores/\(id)")
stores.removeAll { $0.id == id }
// Update cache
try await cacheManager.cacheStores(stores, for: householdId)
}
func updateAisle(_ aisleId: String, in storeId: String, name: String, order: Int, hexColor: String) async throws {
let payload = UpdateAislePayload(name: name, order: order, hexColor: hexColor)
let _: Empty = try await apiClient.put("stores/\(storeId)/aisles/\(aisleId)", body: payload)
let _: Empty = try await apiClient.put("api/stores/\(storeId)/aisles/\(aisleId)", body: payload)
if let storeIndex = stores.firstIndex(where: { $0.id == storeId }) {
if let aisleIndex = stores[storeIndex].aisles.firstIndex(where: { $0.id == aisleId }) {

View file

@ -5,7 +5,7 @@ struct User: Codable, Identifiable {
let email: String
let name: String
let image: String?
let householdId: String
let householdId: String?
let createdAt: Date
enum CodingKeys: String, CodingKey {

View file

@ -12,9 +12,14 @@ let package = Package(
targets: ["Bagsy"]
)
],
dependencies: [
.package(url: "https://github.com/ably/ably-swift.git", from: "1.2.0"),
.package(url: "https://github.com/clerk/clerk-sdk-swift.git", from: "1.0.0")
],
targets: [
.target(
name: "Bagsy",
dependencies: ["Ably", "ClerkSDK"],
path: "ShopList",
publicHeadersPath: "."
)

2071
bun.lock

File diff suppressed because it is too large Load diff