Merge pull request 'feat: setup Next.js web project with Drizzle + PostgreSQL schema (#35)' (#42) from issue-35-web-setup into master

This commit is contained in:
maximus 2026-04-06 16:58:04 +00:00
commit f4df9bbfd0
51 changed files with 10266 additions and 0 deletions

8
web/.env.example Normal file
View file

@ -0,0 +1,8 @@
DATABASE_URL=postgresql://user:password@localhost:5432/simpliste
# Logto
LOGTO_ENDPOINT=https://auth.lacompagniemaximus.com
LOGTO_APP_ID=
LOGTO_APP_SECRET=
LOGTO_COOKIE_SECRET=
LOGTO_BASE_URL=https://liste.lacompagniemaximus.com

41
web/.gitignore vendored Normal file
View file

@ -0,0 +1,41 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts

5
web/AGENTS.md Normal file
View file

@ -0,0 +1,5 @@
<!-- BEGIN:nextjs-agent-rules -->
# This is NOT the Next.js you know
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` before writing any code. Heed deprecation notices.
<!-- END:nextjs-agent-rules -->

1
web/CLAUDE.md Normal file
View file

@ -0,0 +1 @@
@AGENTS.md

36
web/Dockerfile Normal file
View file

@ -0,0 +1,36 @@
FROM node:22-alpine AS base
# Dependencies
FROM base AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --only=production
# Build
FROM base AS builder
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build
# Production
FROM base AS runner
WORKDIR /app
ENV NODE_ENV=production
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
COPY --from=builder /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
COPY --from=builder --chown=nextjs:nodejs /app/server.ts ./server.ts
USER nextjs
EXPOSE 3000
ENV PORT=3000
ENV HOSTNAME="0.0.0.0"
# Use custom server instead of default next start
CMD ["node", "server.ts"]

36
web/README.md Normal file
View file

@ -0,0 +1,36 @@
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.

11
web/drizzle.config.ts Normal file
View file

@ -0,0 +1,11 @@
import 'dotenv/config';
import { defineConfig } from 'drizzle-kit';
export default defineConfig({
schema: './src/db/schema.ts',
out: './src/db/migrations',
dialect: 'postgresql',
dbCredentials: {
url: process.env.DATABASE_URL!,
},
});

18
web/eslint.config.mjs Normal file
View file

@ -0,0 +1,18 @@
import { defineConfig, globalIgnores } from "eslint/config";
import nextVitals from "eslint-config-next/core-web-vitals";
import nextTs from "eslint-config-next/typescript";
const eslintConfig = defineConfig([
...nextVitals,
...nextTs,
// Override default ignores of eslint-config-next.
globalIgnores([
// Default ignores of eslint-config-next:
".next/**",
"out/**",
"build/**",
"next-env.d.ts",
]),
]);
export default eslintConfig;

7
web/next.config.ts Normal file
View file

@ -0,0 +1,7 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
output: "standalone",
};
export default nextConfig;

8553
web/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

35
web/package.json Normal file
View file

@ -0,0 +1,35 @@
{
"name": "web",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "eslint"
},
"dependencies": {
"@logto/next": "^4.2.9",
"@types/pg": "^8.20.0",
"dotenv": "^17.4.1",
"drizzle-orm": "^0.45.2",
"next": "16.2.2",
"pg": "^8.20.0",
"react": "19.2.4",
"react-dom": "19.2.4",
"ws": "^8.20.0",
"zod": "^4.3.6"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"@types/ws": "^8.18.1",
"drizzle-kit": "^0.31.10",
"eslint": "^9",
"eslint-config-next": "16.2.2",
"tailwindcss": "^4",
"typescript": "^5"
}
}

7
web/postcss.config.mjs Normal file
View file

@ -0,0 +1,7 @@
const config = {
plugins: {
"@tailwindcss/postcss": {},
},
};
export default config;

1
web/public/file.svg Normal file
View file

@ -0,0 +1 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 391 B

1
web/public/globe.svg Normal file
View file

@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1 KiB

1
web/public/next.svg Normal file
View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

1
web/public/vercel.svg Normal file
View file

@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

After

Width:  |  Height:  |  Size: 128 B

1
web/public/window.svg Normal file
View file

@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

After

Width:  |  Height:  |  Size: 385 B

24
web/server.ts Normal file
View file

@ -0,0 +1,24 @@
import { createServer } from 'http';
import next from 'next';
import { setupWebSocket } from './src/lib/ws';
const dev = process.env.NODE_ENV !== 'production';
const hostname = process.env.HOSTNAME || '0.0.0.0';
const port = parseInt(process.env.PORT || '3000', 10);
const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = createServer((req, res) => {
// Don't log query params on /ws route (ticket security)
handle(req, res);
});
setupWebSocket(server);
server.listen(port, hostname, () => {
console.log(`> Ready on http://${hostname}:${port}`);
console.log(`> WebSocket server on ws://${hostname}:${port}/ws`);
});
});

View file

@ -0,0 +1,37 @@
import { NextResponse } from 'next/server';
import { db } from '@/db/client';
import { sql } from 'drizzle-orm';
import { getActiveConnections } from '@/lib/ws';
export async function GET() {
const start = Date.now();
try {
await db.execute(sql`SELECT 1`);
const dbLatency = Date.now() - start;
return NextResponse.json({
status: 'ok',
timestamp: new Date().toISOString(),
db: {
status: 'connected',
latencyMs: dbLatency,
},
ws: {
activeConnections: getActiveConnections(),
},
});
} catch (error) {
return NextResponse.json({
status: 'degraded',
timestamp: new Date().toISOString(),
db: {
status: 'disconnected',
error: error instanceof Error ? error.message : 'Unknown error',
},
ws: {
activeConnections: getActiveConnections(),
},
}, { status: 503 });
}
}

View file

@ -0,0 +1,52 @@
import { NextResponse } from 'next/server';
import { db } from '@/db/client';
import { slLists } from '@/db/schema';
import { eq, and } from 'drizzle-orm';
import { requireAuth, parseBody } from '@/lib/api';
import { updateListSchema } from '@/lib/validators';
export async function PUT(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = await requireAuth();
if (auth.error) return auth.error;
const { id } = await params;
const body = await parseBody(request, (d) => updateListSchema.parse(d));
if (body.error) return body.error;
const [updated] = await db
.update(slLists)
.set({ ...body.data, updatedAt: new Date() })
.where(and(eq(slLists.id, id), eq(slLists.userId, auth.userId)))
.returning();
if (!updated) {
return NextResponse.json({ error: 'Not found' }, { status: 404 });
}
return NextResponse.json(updated);
}
export async function DELETE(
_request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = await requireAuth();
if (auth.error) return auth.error;
const { id } = await params;
const [deleted] = await db
.update(slLists)
.set({ deletedAt: new Date(), updatedAt: new Date() })
.where(and(eq(slLists.id, id), eq(slLists.userId, auth.userId)))
.returning();
if (!deleted) {
return NextResponse.json({ error: 'Not found' }, { status: 404 });
}
return NextResponse.json({ ok: true });
}

View file

@ -0,0 +1,85 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/db/client';
import { slTasks, slLists, slTaskTags } from '@/db/schema';
import { eq, and, isNull, asc, desc, inArray, SQL } from 'drizzle-orm';
import { requireAuth } from '@/lib/api';
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = await requireAuth();
if (auth.error) return auth.error;
const { id: listId } = await params;
// Verify list belongs to user
const [list] = await db
.select({ id: slLists.id })
.from(slLists)
.where(and(eq(slLists.id, listId), eq(slLists.userId, auth.userId)));
if (!list) {
return NextResponse.json({ error: 'List not found' }, { status: 404 });
}
const url = request.nextUrl;
const completed = url.searchParams.get('completed');
const priority = url.searchParams.get('priority');
const dueDate = url.searchParams.get('dueDate');
const tags = url.searchParams.get('tags');
const sortBy = url.searchParams.get('sortBy') || 'position';
const sortOrder = url.searchParams.get('sortOrder') || 'asc';
const conditions: SQL[] = [
eq(slTasks.listId, listId),
eq(slTasks.userId, auth.userId),
isNull(slTasks.deletedAt),
isNull(slTasks.parentId),
];
if (completed !== null) {
conditions.push(eq(slTasks.completed, completed === 'true'));
}
if (priority !== null) {
conditions.push(eq(slTasks.priority, parseInt(priority, 10)));
}
// Build query
let query = db
.select()
.from(slTasks)
.where(and(...conditions));
// Sort
const sortColumn = sortBy === 'priority' ? slTasks.priority
: sortBy === 'dueDate' ? slTasks.dueDate
: sortBy === 'createdAt' ? slTasks.createdAt
: sortBy === 'title' ? slTasks.title
: slTasks.position;
const orderFn = sortOrder === 'desc' ? desc : asc;
const tasks = await query.orderBy(orderFn(sortColumn));
// Filter by tags if specified (post-query since it's a join table)
if (tags) {
const tagIds = tags.split(',');
const taskTagRows = await db
.select({ taskId: slTaskTags.taskId })
.from(slTaskTags)
.where(inArray(slTaskTags.tagId, tagIds));
const taskIdsWithTags = new Set(taskTagRows.map((r) => r.taskId));
return NextResponse.json(tasks.filter((t) => taskIdsWithTags.has(t.id)));
}
// Filter by dueDate if specified (before/on that date)
if (dueDate) {
const cutoff = new Date(dueDate);
return NextResponse.json(
tasks.filter((t) => t.dueDate && t.dueDate <= cutoff)
);
}
return NextResponse.json(tasks);
}

View file

@ -0,0 +1,36 @@
import { NextResponse } from 'next/server';
import { db } from '@/db/client';
import { slLists } from '@/db/schema';
import { eq, and, inArray } from 'drizzle-orm';
import { requireAuth, parseBody } from '@/lib/api';
import { reorderSchema } from '@/lib/validators';
export async function PUT(request: Request) {
const auth = await requireAuth();
if (auth.error) return auth.error;
const body = await parseBody(request, (d) => reorderSchema.parse(d));
if (body.error) return body.error;
// Verify all lists belong to user
const existing = await db
.select({ id: slLists.id })
.from(slLists)
.where(and(eq(slLists.userId, auth.userId), inArray(slLists.id, body.data.ids)));
if (existing.length !== body.data.ids.length) {
return NextResponse.json({ error: 'Some lists not found' }, { status: 404 });
}
// Update positions in order
await Promise.all(
body.data.ids.map((id, index) =>
db
.update(slLists)
.set({ position: index, updatedAt: new Date() })
.where(and(eq(slLists.id, id), eq(slLists.userId, auth.userId)))
)
);
return NextResponse.json({ ok: true });
}

View file

@ -0,0 +1,34 @@
import { NextResponse } from 'next/server';
import { db } from '@/db/client';
import { slLists } from '@/db/schema';
import { eq, isNull, and, asc } from 'drizzle-orm';
import { requireAuth, parseBody } from '@/lib/api';
import { createListSchema } from '@/lib/validators';
export async function GET() {
const auth = await requireAuth();
if (auth.error) return auth.error;
const lists = await db
.select()
.from(slLists)
.where(and(eq(slLists.userId, auth.userId), isNull(slLists.deletedAt)))
.orderBy(asc(slLists.position));
return NextResponse.json(lists);
}
export async function POST(request: Request) {
const auth = await requireAuth();
if (auth.error) return auth.error;
const body = await parseBody(request, (d) => createListSchema.parse(d));
if (body.error) return body.error;
const [list] = await db
.insert(slLists)
.values({ ...body.data, userId: auth.userId })
.returning();
return NextResponse.json(list, { status: 201 });
}

View file

@ -0,0 +1,17 @@
import { handleSignIn } from '@logto/next/server-actions';
import { logtoConfig } from '@/lib/logto';
import { NextRequest } from 'next/server';
import { redirect } from 'next/navigation';
export const dynamic = 'force-dynamic';
export async function GET(request: NextRequest) {
const searchParams = request.nextUrl.searchParams;
try {
await handleSignIn(logtoConfig, searchParams);
redirect('/');
} catch {
redirect('/?error=auth');
}
}

View file

@ -0,0 +1,9 @@
import { signIn } from '@logto/next/server-actions';
import { logtoConfig } from '@/lib/logto';
import { NextRequest } from 'next/server';
export const dynamic = 'force-dynamic';
export async function GET(request: NextRequest) {
await signIn(logtoConfig, `${logtoConfig.baseUrl}/api/logto/callback`);
}

View file

@ -0,0 +1,8 @@
import { signOut } from '@logto/next/server-actions';
import { logtoConfig } from '@/lib/logto';
export const dynamic = 'force-dynamic';
export async function GET() {
await signOut(logtoConfig, `${logtoConfig.baseUrl}`);
}

View file

@ -0,0 +1,228 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/db/client';
import { slLists, slTasks, slTags, slTaskTags } from '@/db/schema';
import { eq, and, gte } from 'drizzle-orm';
import { requireAuth, parseBody } from '@/lib/api';
import { syncPushSchema, type SyncOperation } from '@/lib/validators';
// Idempotency key store (TTL 24h)
const idempotencyStore = new Map<string, { result: unknown; expiresAt: number }>();
// Cleanup expired keys periodically
function cleanupIdempotencyKeys() {
const now = Date.now();
for (const [key, entry] of idempotencyStore) {
if (entry.expiresAt < now) {
idempotencyStore.delete(key);
}
}
}
const TTL_24H = 24 * 60 * 60 * 1000;
export async function GET(request: NextRequest) {
const auth = await requireAuth();
if (auth.error) return auth.error;
const since = request.nextUrl.searchParams.get('since');
if (!since) {
return NextResponse.json({ error: 'Missing "since" parameter' }, { status: 400 });
}
const sinceDate = new Date(since);
if (isNaN(sinceDate.getTime())) {
return NextResponse.json({ error: 'Invalid "since" timestamp' }, { status: 400 });
}
// Fetch all entities updated since timestamp (including soft-deleted)
const [lists, tasks, tags] = await Promise.all([
db
.select()
.from(slLists)
.where(and(eq(slLists.userId, auth.userId), gte(slLists.updatedAt, sinceDate))),
db
.select()
.from(slTasks)
.where(and(eq(slTasks.userId, auth.userId), gte(slTasks.updatedAt, sinceDate))),
db
.select()
.from(slTags)
.where(and(eq(slTags.userId, auth.userId), gte(slTags.createdAt, sinceDate))),
]);
// Get task-tag relations for the affected tasks
const taskIds = tasks.map((t) => t.id);
let taskTags: { taskId: string; tagId: string }[] = [];
if (taskIds.length > 0) {
const { inArray } = await import('drizzle-orm');
taskTags = await db
.select()
.from(slTaskTags)
.where(inArray(slTaskTags.taskId, taskIds));
}
return NextResponse.json({
lists,
tasks,
tags,
taskTags,
syncedAt: new Date().toISOString(),
});
}
export async function POST(request: Request) {
const auth = await requireAuth();
if (auth.error) return auth.error;
const body = await parseBody(request, (d) => syncPushSchema.parse(d));
if (body.error) return body.error;
cleanupIdempotencyKeys();
const results: { idempotencyKey: string; status: 'applied' | 'skipped'; error?: string }[] = [];
for (const op of body.data.operations) {
const storeKey = `${auth.userId}:${op.idempotencyKey}`;
// Check idempotency
const existing = idempotencyStore.get(storeKey);
if (existing && existing.expiresAt > Date.now()) {
results.push({ idempotencyKey: op.idempotencyKey, status: 'skipped' });
continue;
}
try {
await processOperation(op, auth.userId);
idempotencyStore.set(storeKey, {
result: true,
expiresAt: Date.now() + TTL_24H,
});
results.push({ idempotencyKey: op.idempotencyKey, status: 'applied' });
} catch (e) {
results.push({
idempotencyKey: op.idempotencyKey,
status: 'skipped',
error: e instanceof Error ? e.message : 'Unknown error',
});
}
}
return NextResponse.json({ results, syncedAt: new Date().toISOString() });
}
async function processOperation(op: SyncOperation, userId: string) {
const { entityType, entityId, action, data } = op;
const now = new Date();
switch (entityType) {
case 'list': {
if (action === 'create') {
await db.insert(slLists).values({
id: entityId,
userId,
name: (data as Record<string, unknown>)?.name as string || 'Untitled',
color: (data as Record<string, unknown>)?.color as string | undefined,
icon: (data as Record<string, unknown>)?.icon as string | undefined,
position: (data as Record<string, unknown>)?.position as number | undefined,
isInbox: (data as Record<string, unknown>)?.isInbox as boolean | undefined,
}).onConflictDoNothing();
} else if (action === 'update') {
await verifyOwnership(slLists, entityId, userId);
await db.update(slLists)
.set({ ...(data as Record<string, unknown>), updatedAt: now })
.where(and(eq(slLists.id, entityId), eq(slLists.userId, userId)));
} else if (action === 'delete') {
await verifyOwnership(slLists, entityId, userId);
await db.update(slLists)
.set({ deletedAt: now, updatedAt: now })
.where(and(eq(slLists.id, entityId), eq(slLists.userId, userId)));
}
break;
}
case 'task': {
if (action === 'create') {
const d = (data as Record<string, unknown>) || {};
await db.insert(slTasks).values({
id: entityId,
userId,
title: d.title as string || 'Untitled',
listId: d.listId as string,
notes: d.notes as string | undefined,
priority: d.priority as number | undefined,
dueDate: d.dueDate ? new Date(d.dueDate as string) : undefined,
parentId: d.parentId as string | undefined,
recurrence: d.recurrence as string | undefined,
position: d.position as number | undefined,
}).onConflictDoNothing();
} else if (action === 'update') {
await verifyOwnership(slTasks, entityId, userId);
const raw = { ...(data as Record<string, unknown>), updatedAt: now } as Record<string, unknown>;
if (raw.dueDate !== undefined) {
raw.dueDate = raw.dueDate ? new Date(raw.dueDate as string) : null;
}
await db.update(slTasks)
.set(raw)
.where(and(eq(slTasks.id, entityId), eq(slTasks.userId, userId)));
} else if (action === 'delete') {
await verifyOwnership(slTasks, entityId, userId);
await db.update(slTasks)
.set({ deletedAt: now, updatedAt: now })
.where(and(eq(slTasks.id, entityId), eq(slTasks.userId, userId)));
}
break;
}
case 'tag': {
if (action === 'create') {
const d = (data as Record<string, unknown>) || {};
await db.insert(slTags).values({
id: entityId,
userId,
name: d.name as string || 'Untitled',
color: d.color as string | undefined,
}).onConflictDoNothing();
} else if (action === 'update') {
await verifyTagOwnership(entityId, userId);
await db.update(slTags)
.set(data as Record<string, unknown>)
.where(and(eq(slTags.id, entityId), eq(slTags.userId, userId)));
} else if (action === 'delete') {
await verifyTagOwnership(entityId, userId);
await db.update(slTags)
.set({ deletedAt: now })
.where(and(eq(slTags.id, entityId), eq(slTags.userId, userId)));
}
break;
}
case 'taskTag': {
// entityId is used as taskId, tagId comes from data
const d = (data as Record<string, unknown>) || {};
const tagId = d.tagId as string;
if (action === 'create') {
await db.insert(slTaskTags)
.values({ taskId: entityId, tagId })
.onConflictDoNothing();
} else if (action === 'delete') {
await db.delete(slTaskTags)
.where(and(eq(slTaskTags.taskId, entityId), eq(slTaskTags.tagId, tagId)));
}
break;
}
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async function verifyOwnership(table: any, entityId: string, userId: string) {
const [row] = await db
.select({ id: table.id })
.from(table)
.where(and(eq(table.id, entityId), eq(table.userId, userId)));
if (!row) throw new Error('Entity not found or access denied');
}
async function verifyTagOwnership(entityId: string, userId: string) {
const [row] = await db
.select({ id: slTags.id })
.from(slTags)
.where(and(eq(slTags.id, entityId), eq(slTags.userId, userId)));
if (!row) throw new Error('Tag not found or access denied');
}

View file

@ -0,0 +1,52 @@
import { NextResponse } from 'next/server';
import { db } from '@/db/client';
import { slTags } from '@/db/schema';
import { eq, and } from 'drizzle-orm';
import { requireAuth, parseBody } from '@/lib/api';
import { updateTagSchema } from '@/lib/validators';
export async function PUT(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = await requireAuth();
if (auth.error) return auth.error;
const { id } = await params;
const body = await parseBody(request, (d) => updateTagSchema.parse(d));
if (body.error) return body.error;
const [updated] = await db
.update(slTags)
.set(body.data)
.where(and(eq(slTags.id, id), eq(slTags.userId, auth.userId)))
.returning();
if (!updated) {
return NextResponse.json({ error: 'Not found' }, { status: 404 });
}
return NextResponse.json(updated);
}
export async function DELETE(
_request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = await requireAuth();
if (auth.error) return auth.error;
const { id } = await params;
const [deleted] = await db
.update(slTags)
.set({ deletedAt: new Date() })
.where(and(eq(slTags.id, id), eq(slTags.userId, auth.userId)))
.returning();
if (!deleted) {
return NextResponse.json({ error: 'Not found' }, { status: 404 });
}
return NextResponse.json({ ok: true });
}

View file

@ -0,0 +1,34 @@
import { NextResponse } from 'next/server';
import { db } from '@/db/client';
import { slTags } from '@/db/schema';
import { eq, isNull, and, asc } from 'drizzle-orm';
import { requireAuth, parseBody } from '@/lib/api';
import { createTagSchema } from '@/lib/validators';
export async function GET() {
const auth = await requireAuth();
if (auth.error) return auth.error;
const tags = await db
.select()
.from(slTags)
.where(and(eq(slTags.userId, auth.userId), isNull(slTags.deletedAt)))
.orderBy(asc(slTags.name));
return NextResponse.json(tags);
}
export async function POST(request: Request) {
const auth = await requireAuth();
if (auth.error) return auth.error;
const body = await parseBody(request, (d) => createTagSchema.parse(d));
if (body.error) return body.error;
const [tag] = await db
.insert(slTags)
.values({ ...body.data, userId: auth.userId })
.returning();
return NextResponse.json(tag, { status: 201 });
}

View file

@ -0,0 +1,67 @@
import { NextResponse } from 'next/server';
import { db } from '@/db/client';
import { slTasks } from '@/db/schema';
import { eq, and } from 'drizzle-orm';
import { requireAuth, parseBody } from '@/lib/api';
import { updateTaskSchema } from '@/lib/validators';
export async function PUT(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = await requireAuth();
if (auth.error) return auth.error;
const { id } = await params;
const body = await parseBody(request, (d) => updateTaskSchema.parse(d));
if (body.error) return body.error;
const updateData: Record<string, unknown> = {
...body.data,
updatedAt: new Date(),
};
// Convert dueDate string to Date
if (body.data.dueDate !== undefined) {
updateData.dueDate = body.data.dueDate ? new Date(body.data.dueDate) : null;
}
// Set completedAt when toggling completed
if (body.data.completed !== undefined) {
updateData.completedAt = body.data.completed ? new Date() : null;
}
const [updated] = await db
.update(slTasks)
.set(updateData)
.where(and(eq(slTasks.id, id), eq(slTasks.userId, auth.userId)))
.returning();
if (!updated) {
return NextResponse.json({ error: 'Not found' }, { status: 404 });
}
return NextResponse.json(updated);
}
export async function DELETE(
_request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = await requireAuth();
if (auth.error) return auth.error;
const { id } = await params;
const [deleted] = await db
.update(slTasks)
.set({ deletedAt: new Date(), updatedAt: new Date() })
.where(and(eq(slTasks.id, id), eq(slTasks.userId, auth.userId)))
.returning();
if (!deleted) {
return NextResponse.json({ error: 'Not found' }, { status: 404 });
}
return NextResponse.json({ ok: true });
}

View file

@ -0,0 +1,39 @@
import { NextResponse } from 'next/server';
import { db } from '@/db/client';
import { slTasks } from '@/db/schema';
import { eq, and, isNull, asc } from 'drizzle-orm';
import { requireAuth } from '@/lib/api';
export async function GET(
_request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = await requireAuth();
if (auth.error) return auth.error;
const { id } = await params;
// Verify parent task belongs to user
const [parent] = await db
.select({ id: slTasks.id })
.from(slTasks)
.where(and(eq(slTasks.id, id), eq(slTasks.userId, auth.userId)));
if (!parent) {
return NextResponse.json({ error: 'Task not found' }, { status: 404 });
}
const subtasks = await db
.select()
.from(slTasks)
.where(
and(
eq(slTasks.parentId, id),
eq(slTasks.userId, auth.userId),
isNull(slTasks.deletedAt)
)
)
.orderBy(asc(slTasks.position));
return NextResponse.json(subtasks);
}

View file

@ -0,0 +1,31 @@
import { NextResponse } from 'next/server';
import { db } from '@/db/client';
import { slTasks, slTaskTags } from '@/db/schema';
import { eq, and } from 'drizzle-orm';
import { requireAuth } from '@/lib/api';
export async function DELETE(
_request: Request,
{ params }: { params: Promise<{ id: string; tagId: string }> }
) {
const auth = await requireAuth();
if (auth.error) return auth.error;
const { id: taskId, tagId } = await params;
// Verify task belongs to user
const [task] = await db
.select({ id: slTasks.id })
.from(slTasks)
.where(and(eq(slTasks.id, taskId), eq(slTasks.userId, auth.userId)));
if (!task) {
return NextResponse.json({ error: 'Task not found' }, { status: 404 });
}
await db
.delete(slTaskTags)
.where(and(eq(slTaskTags.taskId, taskId), eq(slTaskTags.tagId, tagId)));
return NextResponse.json({ ok: true });
}

View file

@ -0,0 +1,47 @@
import { NextResponse } from 'next/server';
import { db } from '@/db/client';
import { slTasks, slTags, slTaskTags } from '@/db/schema';
import { eq, and, inArray } from 'drizzle-orm';
import { requireAuth, parseBody } from '@/lib/api';
import { assignTagsSchema } from '@/lib/validators';
export async function POST(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const auth = await requireAuth();
if (auth.error) return auth.error;
const { id: taskId } = await params;
const body = await parseBody(request, (d) => assignTagsSchema.parse(d));
if (body.error) return body.error;
// Verify task belongs to user
const [task] = await db
.select({ id: slTasks.id })
.from(slTasks)
.where(and(eq(slTasks.id, taskId), eq(slTasks.userId, auth.userId)));
if (!task) {
return NextResponse.json({ error: 'Task not found' }, { status: 404 });
}
// Verify all tags belong to user
const existingTags = await db
.select({ id: slTags.id })
.from(slTags)
.where(and(eq(slTags.userId, auth.userId), inArray(slTags.id, body.data.tagIds)));
if (existingTags.length !== body.data.tagIds.length) {
return NextResponse.json({ error: 'Some tags not found' }, { status: 404 });
}
// Insert (ignore conflicts)
await db
.insert(slTaskTags)
.values(body.data.tagIds.map((tagId) => ({ taskId, tagId })))
.onConflictDoNothing();
return NextResponse.json({ ok: true }, { status: 201 });
}

View file

@ -0,0 +1,35 @@
import { NextResponse } from 'next/server';
import { db } from '@/db/client';
import { slTasks } from '@/db/schema';
import { eq, and, inArray } from 'drizzle-orm';
import { requireAuth, parseBody } from '@/lib/api';
import { reorderSchema } from '@/lib/validators';
export async function PUT(request: Request) {
const auth = await requireAuth();
if (auth.error) return auth.error;
const body = await parseBody(request, (d) => reorderSchema.parse(d));
if (body.error) return body.error;
// Verify all tasks belong to user
const existing = await db
.select({ id: slTasks.id })
.from(slTasks)
.where(and(eq(slTasks.userId, auth.userId), inArray(slTasks.id, body.data.ids)));
if (existing.length !== body.data.ids.length) {
return NextResponse.json({ error: 'Some tasks not found' }, { status: 404 });
}
await Promise.all(
body.data.ids.map((id, index) =>
db
.update(slTasks)
.set({ position: index, updatedAt: new Date() })
.where(and(eq(slTasks.id, id), eq(slTasks.userId, auth.userId)))
)
);
return NextResponse.json({ ok: true });
}

View file

@ -0,0 +1,47 @@
import { NextResponse } from 'next/server';
import { db } from '@/db/client';
import { slTasks, slLists } from '@/db/schema';
import { eq, and } from 'drizzle-orm';
import { requireAuth, parseBody } from '@/lib/api';
import { createTaskSchema } from '@/lib/validators';
export async function POST(request: Request) {
const auth = await requireAuth();
if (auth.error) return auth.error;
const body = await parseBody(request, (d) => createTaskSchema.parse(d));
if (body.error) return body.error;
// Verify list belongs to user
const [list] = await db
.select({ id: slLists.id })
.from(slLists)
.where(and(eq(slLists.id, body.data.listId), eq(slLists.userId, auth.userId)));
if (!list) {
return NextResponse.json({ error: 'List not found' }, { status: 404 });
}
// If parentId, verify parent task belongs to user
if (body.data.parentId) {
const [parent] = await db
.select({ id: slTasks.id })
.from(slTasks)
.where(and(eq(slTasks.id, body.data.parentId), eq(slTasks.userId, auth.userId)));
if (!parent) {
return NextResponse.json({ error: 'Parent task not found' }, { status: 404 });
}
}
const [task] = await db
.insert(slTasks)
.values({
...body.data,
dueDate: body.data.dueDate ? new Date(body.data.dueDate) : undefined,
userId: auth.userId,
})
.returning();
return NextResponse.json(task, { status: 201 });
}

View file

@ -0,0 +1,31 @@
import { NextResponse } from 'next/server';
import { randomUUID } from 'crypto';
import { requireAuth } from '@/lib/api';
import { getTicketStore } from '@/lib/ws';
const TTL_30S = 30 * 1000;
function cleanupTickets() {
const store = getTicketStore();
const now = Date.now();
for (const [key, entry] of store) {
if (entry.expiresAt < now) {
store.delete(key);
}
}
}
export async function POST() {
const auth = await requireAuth();
if (auth.error) return auth.error;
cleanupTickets();
const ticket = randomUUID();
getTicketStore().set(ticket, {
userId: auth.userId,
expiresAt: Date.now() + TTL_30S,
});
return NextResponse.json({ ticket }, { status: 201 });
}

20
web/src/app/auth/page.tsx Normal file
View file

@ -0,0 +1,20 @@
import Link from 'next/link';
export default function AuthPage() {
return (
<div className="min-h-screen flex items-center justify-center bg-[#FFF8F0]">
<div className="text-center space-y-6 p-8">
<h1 className="text-3xl font-bold text-[#1A1A1A]">Simpl-Liste</h1>
<p className="text-[#6B6B6B]">
Connectez-vous avec votre Compte Maximus
</p>
<Link
href="/api/logto/sign-in"
className="inline-block px-6 py-3 bg-[#4A90A4] text-white rounded-lg font-medium hover:bg-[#3A7389] transition-colors"
>
Se connecter
</Link>
</div>
</div>
);
}

BIN
web/src/app/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

26
web/src/app/globals.css Normal file
View file

@ -0,0 +1,26 @@
@import "tailwindcss";
:root {
--background: #ffffff;
--foreground: #171717;
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
body {
background: var(--background);
color: var(--foreground);
font-family: Arial, Helvetica, sans-serif;
}

33
web/src/app/layout.tsx Normal file
View file

@ -0,0 +1,33 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html
lang="en"
className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}
>
<body className="min-h-full flex flex-col">{children}</body>
</html>
);
}

65
web/src/app/page.tsx Normal file
View file

@ -0,0 +1,65 @@
import Image from "next/image";
export default function Home() {
return (
<div className="flex flex-col flex-1 items-center justify-center bg-zinc-50 font-sans dark:bg-black">
<main className="flex flex-1 w-full max-w-3xl flex-col items-center justify-between py-32 px-16 bg-white dark:bg-black sm:items-start">
<Image
className="dark:invert"
src="/next.svg"
alt="Next.js logo"
width={100}
height={20}
priority
/>
<div className="flex flex-col items-center gap-6 text-center sm:items-start sm:text-left">
<h1 className="max-w-xs text-3xl font-semibold leading-10 tracking-tight text-black dark:text-zinc-50">
To get started, edit the page.tsx file.
</h1>
<p className="max-w-md text-lg leading-8 text-zinc-600 dark:text-zinc-400">
Looking for a starting point or more instructions? Head over to{" "}
<a
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="font-medium text-zinc-950 dark:text-zinc-50"
>
Templates
</a>{" "}
or the{" "}
<a
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="font-medium text-zinc-950 dark:text-zinc-50"
>
Learning
</a>{" "}
center.
</p>
</div>
<div className="flex flex-col gap-4 text-base font-medium sm:flex-row">
<a
className="flex h-12 w-full items-center justify-center gap-2 rounded-full bg-foreground px-5 text-background transition-colors hover:bg-[#383838] dark:hover:bg-[#ccc] md:w-[158px]"
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
className="dark:invert"
src="/vercel.svg"
alt="Vercel logomark"
width={16}
height={16}
/>
Deploy Now
</a>
<a
className="flex h-12 w-full items-center justify-center rounded-full border border-solid border-black/[.08] px-5 transition-colors hover:border-transparent hover:bg-black/[.04] dark:border-white/[.145] dark:hover:bg-[#1a1a1a] md:w-[158px]"
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Documentation
</a>
</div>
</main>
</div>
);
}

9
web/src/db/client.ts Normal file
View file

@ -0,0 +1,9 @@
import { drizzle } from 'drizzle-orm/node-postgres';
import { Pool } from 'pg';
import * as schema from './schema';
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
});
export const db = drizzle(pool, { schema });

56
web/src/db/schema.ts Normal file
View file

@ -0,0 +1,56 @@
import { pgTable, uuid, text, integer, boolean, timestamp, primaryKey, index } from 'drizzle-orm/pg-core';
export const slLists = pgTable('sl_lists', {
id: uuid('id').primaryKey().defaultRandom(),
userId: uuid('user_id').notNull(),
name: text('name').notNull(),
color: text('color'),
icon: text('icon'),
position: integer('position').notNull().default(0),
isInbox: boolean('is_inbox').notNull().default(false),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
deletedAt: timestamp('deleted_at', { withTimezone: true }),
}, (table) => [
index('idx_sl_lists_user').on(table.userId),
]);
export const slTasks = pgTable('sl_tasks', {
id: uuid('id').primaryKey().defaultRandom(),
userId: uuid('user_id').notNull(),
title: text('title').notNull(),
notes: text('notes'),
completed: boolean('completed').notNull().default(false),
completedAt: timestamp('completed_at', { withTimezone: true }),
priority: integer('priority').notNull().default(0),
dueDate: timestamp('due_date', { withTimezone: true }),
listId: uuid('list_id').notNull().references(() => slLists.id, { onDelete: 'cascade' }),
parentId: uuid('parent_id'),
position: integer('position').notNull().default(0),
recurrence: text('recurrence'),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
deletedAt: timestamp('deleted_at', { withTimezone: true }),
}, (table) => [
index('idx_sl_tasks_user').on(table.userId),
index('idx_sl_tasks_list').on(table.listId),
index('idx_sl_tasks_parent').on(table.parentId),
]);
export const slTags = pgTable('sl_tags', {
id: uuid('id').primaryKey().defaultRandom(),
userId: uuid('user_id').notNull(),
name: text('name').notNull(),
color: text('color').notNull().default('#4A90A4'),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
deletedAt: timestamp('deleted_at', { withTimezone: true }),
}, (table) => [
index('idx_sl_tags_user').on(table.userId),
]);
export const slTaskTags = pgTable('sl_task_tags', {
taskId: uuid('task_id').notNull().references(() => slTasks.id, { onDelete: 'cascade' }),
tagId: uuid('tag_id').notNull().references(() => slTags.id, { onDelete: 'cascade' }),
}, (table) => [
primaryKey({ columns: [table.taskId, table.tagId] }),
]);

36
web/src/db/seed.ts Normal file
View file

@ -0,0 +1,36 @@
import 'dotenv/config';
import { Pool } from 'pg';
import { drizzle } from 'drizzle-orm/node-postgres';
import { slLists } from './schema';
import { eq, and } from 'drizzle-orm';
async function seed() {
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const db = drizzle(pool);
const userId = process.argv[2];
if (!userId) {
console.error('Usage: npx tsx src/db/seed.ts <user-id>');
process.exit(1);
}
const existing = await db.select()
.from(slLists)
.where(and(eq(slLists.userId, userId), eq(slLists.isInbox, true)));
if (existing.length === 0) {
await db.insert(slLists).values({
userId,
name: 'Inbox',
isInbox: true,
position: 0,
});
console.log(`Inbox created for user ${userId}`);
} else {
console.log(`Inbox already exists for user ${userId}`);
}
await pool.end();
}
seed().catch(console.error);

33
web/src/lib/api.ts Normal file
View file

@ -0,0 +1,33 @@
import { getAuthenticatedUser } from '@/lib/auth';
import { NextResponse } from 'next/server';
/**
* Authenticate the request and return userId or a 401 response.
*/
export async function requireAuth(): Promise<
| { userId: string; error?: never }
| { userId?: never; error: NextResponse }
> {
const user = await getAuthenticatedUser();
if (!user) {
return { error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) };
}
return { userId: user.userId };
}
/**
* Wrap a handler with JSON parse error handling.
*/
export async function parseBody<T>(request: Request, parse: (data: unknown) => T): Promise<
| { data: T; error?: never }
| { data?: never; error: NextResponse }
> {
try {
const raw = await request.json();
const data = parse(raw);
return { data };
} catch (e) {
const message = e instanceof Error ? e.message : 'Invalid request body';
return { error: NextResponse.json({ error: message }, { status: 400 }) };
}
}

16
web/src/lib/auth.ts Normal file
View file

@ -0,0 +1,16 @@
import { getLogtoContext } from '@logto/next/server-actions';
import { logtoConfig } from './logto';
export async function getAuthenticatedUser() {
const context = await getLogtoContext(logtoConfig);
if (!context.isAuthenticated || !context.claims?.sub) {
return null;
}
return {
userId: context.claims.sub,
email: context.claims.email,
name: context.claims.name,
};
}

11
web/src/lib/logto.ts Normal file
View file

@ -0,0 +1,11 @@
import type { LogtoNextConfig } from '@logto/next';
export const logtoConfig: LogtoNextConfig = {
endpoint: process.env.LOGTO_ENDPOINT!,
appId: process.env.LOGTO_APP_ID!,
appSecret: process.env.LOGTO_APP_SECRET!,
baseUrl: process.env.LOGTO_BASE_URL || 'http://localhost:3000',
cookieSecret: process.env.LOGTO_COOKIE_SECRET!,
cookieSecure: process.env.NODE_ENV === 'production',
scopes: ['openid', 'profile', 'email'],
};

71
web/src/lib/validators.ts Normal file
View file

@ -0,0 +1,71 @@
import { z } from 'zod';
// Lists
export const createListSchema = z.object({
name: z.string().min(1).max(200),
color: z.string().max(20).optional(),
icon: z.string().max(50).optional(),
}).strict();
export const updateListSchema = z.object({
name: z.string().min(1).max(200).optional(),
color: z.string().max(20).nullable().optional(),
icon: z.string().max(50).nullable().optional(),
position: z.number().int().min(0).optional(),
isInbox: z.boolean().optional(),
}).strict();
export const reorderSchema = z.object({
ids: z.array(z.string().uuid()).min(1),
}).strict();
// Tasks
export const createTaskSchema = z.object({
title: z.string().min(1).max(500),
listId: z.string().uuid(),
notes: z.string().max(5000).optional(),
priority: z.number().int().min(0).max(3).optional(),
dueDate: z.string().datetime().optional(),
parentId: z.string().uuid().optional(),
recurrence: z.string().max(100).optional(),
}).strict();
export const updateTaskSchema = z.object({
title: z.string().min(1).max(500).optional(),
notes: z.string().max(5000).nullable().optional(),
completed: z.boolean().optional(),
priority: z.number().int().min(0).max(3).optional(),
dueDate: z.string().datetime().nullable().optional(),
listId: z.string().uuid().optional(),
parentId: z.string().uuid().nullable().optional(),
position: z.number().int().min(0).optional(),
recurrence: z.string().max(100).nullable().optional(),
}).strict();
// Tags
export const createTagSchema = z.object({
name: z.string().min(1).max(100),
color: z.string().max(20).optional(),
}).strict();
export const updateTagSchema = z.object({
name: z.string().min(1).max(100).optional(),
color: z.string().max(20).optional(),
}).strict();
export const assignTagsSchema = z.object({
tagIds: z.array(z.string().uuid()).min(1),
}).strict();
// Sync
export const syncPushSchema = z.object({
operations: z.array(z.object({
idempotencyKey: z.string().min(1).max(200),
entityType: z.enum(['list', 'task', 'tag', 'taskTag']),
entityId: z.string().uuid(),
action: z.enum(['create', 'update', 'delete']),
data: z.record(z.string(), z.unknown()).optional(),
}).strict()),
}).strict();
export type SyncOperation = z.infer<typeof syncPushSchema>['operations'][number];

147
web/src/lib/ws.ts Normal file
View file

@ -0,0 +1,147 @@
import { WebSocketServer, WebSocket } from 'ws';
import type { IncomingMessage } from 'http';
import type { Server } from 'http';
export type WsMessage =
| { type: 'sync'; entity: 'list' | 'task' | 'tag'; action: 'create' | 'update' | 'delete'; id: string }
| { type: 'auth_expired' };
interface AuthenticatedSocket extends WebSocket {
userId: string;
lastValidated: number;
isAlive: boolean;
}
// Ticket store (shared with /api/ws-ticket route)
// In production this would be imported from a shared module
const ticketStore = globalThis as unknown as {
__wsTickets?: Map<string, { userId: string; expiresAt: number }>;
};
export function getTicketStore() {
if (!ticketStore.__wsTickets) {
ticketStore.__wsTickets = new Map();
}
return ticketStore.__wsTickets;
}
const ALLOWED_ORIGINS = [
'https://liste.lacompagniemaximus.com',
'http://localhost:3000',
];
const REVALIDATION_INTERVAL = 15 * 60 * 1000; // 15 minutes
const HEARTBEAT_INTERVAL = 30 * 1000; // 30 seconds
const clients = new Set<AuthenticatedSocket>();
export function setupWebSocket(server: Server) {
const wss = new WebSocketServer({ noServer: true });
server.on('upgrade', (request: IncomingMessage, socket, head) => {
const url = new URL(request.url || '', `http://${request.headers.host}`);
if (url.pathname !== '/ws') {
socket.destroy();
return;
}
// Validate Origin
const origin = request.headers.origin;
if (origin && !ALLOWED_ORIGINS.includes(origin)) {
socket.destroy();
return;
}
// Validate ticket
const ticket = url.searchParams.get('ticket');
if (!ticket) {
socket.destroy();
return;
}
const store = getTicketStore();
const entry = store.get(ticket);
if (!entry || entry.expiresAt < Date.now()) {
store.delete(ticket);
socket.destroy();
return;
}
// Invalidate ticket (single use)
const userId = entry.userId;
store.delete(ticket);
wss.handleUpgrade(request, socket, head, (ws) => {
const authWs = ws as AuthenticatedSocket;
authWs.userId = userId;
authWs.lastValidated = Date.now();
authWs.isAlive = true;
wss.emit('connection', authWs);
});
});
wss.on('connection', (ws: AuthenticatedSocket) => {
clients.add(ws);
ws.on('pong', () => {
ws.isAlive = true;
});
ws.on('close', () => {
clients.delete(ws);
});
ws.on('error', () => {
clients.delete(ws);
});
});
// Heartbeat + session revalidation
const interval = setInterval(() => {
const now = Date.now();
for (const ws of clients) {
// Check session expiry
if (now - ws.lastValidated > REVALIDATION_INTERVAL) {
const msg: WsMessage = { type: 'auth_expired' };
ws.send(JSON.stringify(msg));
ws.terminate();
clients.delete(ws);
continue;
}
// Heartbeat
if (!ws.isAlive) {
ws.terminate();
clients.delete(ws);
continue;
}
ws.isAlive = false;
ws.ping();
}
}, HEARTBEAT_INTERVAL);
wss.on('close', () => {
clearInterval(interval);
});
return wss;
}
/**
* Broadcast a sync notification to all connected clients of a specific user.
*/
export function broadcastToUser(userId: string, message: WsMessage) {
const payload = JSON.stringify(message);
for (const ws of clients) {
if (ws.userId === userId && ws.readyState === WebSocket.OPEN) {
ws.send(payload);
}
}
}
export function getActiveConnections(): number {
return clients.size;
}

33
web/src/middleware.ts Normal file
View file

@ -0,0 +1,33 @@
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Let Logto API routes and health endpoint pass through
if (pathname.startsWith('/api/logto') || pathname.startsWith('/api/health')) {
return NextResponse.next();
}
// Protected routes: check for Logto session cookie
// The Logto SDK stores session data in a cookie named `logto:<appId>`
const hasSession = request.cookies.getAll().some(
(cookie) => cookie.name.startsWith('logto:')
);
if (!hasSession && !pathname.startsWith('/auth')) {
return NextResponse.redirect(new URL('/auth', request.url));
}
if (hasSession && pathname === '/auth') {
return NextResponse.redirect(new URL('/', request.url));
}
return NextResponse.next();
}
export const config = {
matcher: [
'/((?!_next/static|_next/image|favicon.ico|api/logto|api/health).*)',
],
};

34
web/tsconfig.json Normal file
View file

@ -0,0 +1,34 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules"]
}